language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
---|---|---|---|---|---|---|---|
Python
|
UTF-8
| 29,983 | 2.71875 | 3 |
[
"Unlicense"
] |
permissive
|
import numpy as np
WEIGHT = 1e-4 # critical weight for roulette
CHANCE = 0.1 # Chance of roulette survival
PARTIALREFLECTION = 0 # 1=split photon, 0=statistical reflection.
COSZERO = 1.0 - 1.0e-12 # cosine of about 1e-6 rad
COS90D = 1.0e-6 # cosine of about 1.57 - 1e-6 rad
class Medium:
"""Medium class - optical medium class defining the optical properties
Class instance variables:
n - refractive index
mua - absorption coefficient. [1/cm]
mus - scattering coefficient. [1/cm]
g - anisotropy
Methods:
"""
def __init__(self, mediumName = 'DERMIS'):
# initialize medium optical properties
if mediumName.lower() == 'AIR'.lower():
self.n = 1.0
self.mua = 0.0
self.mus = 0.0
self.g = 1.0
elif mediumName.lower() == 'DERMIS'.lower(): # 800-nm wavelngth
self.n = 1.4
self.mua = 0.26
self.mus = 137.0
self.g = 0.90
elif mediumName.lower() == 'TYPE_II_EPIDERMIS'.lower(): # 800-nm
self.n = 1.3
self.mua = 5.0
self.mus = 200.0
self.g = 0.70
elif mediumName.lower() == 'CORNEA'.lower(): # 1060-nm
self.n = 1.376
self.mua = 0.157 # from Bovine NIR paper 2011
self.mus = 1.064
self.g = 0.90
elif mediumName.lower() == 'AQUEOUS_HUMOR'.lower(): # 1060-nm
self.n = 1.336
self.mua = 0.78 # from Optical properties of ocular tissues
self.mus = 0.60
self.g = 0.99
elif mediumName.lower() == 'LENS'.lower(): # 1060-nm
self.n = 1.406
self.mua = 0.206 # from Bovine NIR paper 2011
self.mus = 1.131
self.g = 0.90
elif mediumName.lower() == 'VITREOUS_HUMOR'.lower(): # 1060-nm
self.n = 1.337
self.mua = 0.48 # from Optical properties of ocular tissues
self.mus = 0.25
self.g = 0.99
elif mediumName.lower() == 'RETINA'.lower(): # 1060-nm
self.n = 1.358
self.mua = 2.745 # from Bovine NIR paper 2011
self.mus = 71.50
self.g = 0.70
else:
self.n = 1.4
self.mua = 0.26
self.mus = 137.0
self.g = 0.90
class LayerStruct:
"""LayerStruct class - multi-layered structure
Class instance variables:
nIn - refractive index of the incidence medium
nOut - refractive index of the exit medium
numLayers - number of layers
layer - list of layer objects
layerThickness - layer thickness in [cm]
layerZ - layer depth z coordinates, top and bottom [cm]
cosCrit - ciritical angle cosines of each layer, top and bottom
Methods:
"""
def __init__(self, layerName = 'BARE_DERMIS'):
if layerName.lower() == 'BARE_DERMIS'.lower():
self.numLayers = 1
self.layer = [Medium('AIR'), Medium('DERMIS'), Medium('DERMIS')]
self.layerThickness = [0.3]
elif layerName.lower() == 'TYPE_II_SKIN'.lower():
self.numLayers = 2 # number of layers
self.layer = [Medium('AIR'), Medium('TYPE_II_EPIDERMIS'), \
Medium('DERMIS'), Medium('DERMIS')]
self.layerThickness = [0.006, 0.3] # in [cm]
elif layerName.lower() == 'CORNEA'.lower():
self.numLayers = 1 # number of layers
self.layer = [Medium('AIR'), Medium('CORNEA'), \
Medium('AQUEOUS_HUMOR')]
self.layerThickness = [0.0449] # in [cm]
elif layerName.lower() == 'EYE_ANTERIOR'.lower():
self.numLayers = 3 # number of layers
self.layer = [Medium('AIR'), Medium('CORNEA'), \
Medium('AQUEOUS_HUMOR'), Medium('LENS'), \
Medium('VITREOUS_HUMOR')]
self.layerThickness = [0.0449, 0.2794, 0.4979] # in [cm]
else:
self.numLayers = 1
self.layer = [Medium('AIR'), Medium('DERMIS'), Medium('DERMIS')]
self.layerThickness = [0.3]
self.layerZ = []
self.cosCrit = []
z = 0 # incidence first medium z coordinate [cm]
self.layerZ.append([0, 0]) # first incidence medium, not used
self.cosCrit.append([0, 0]) # first incidence medium, not used
# find the z depth coordinates and cosine critical angles for each
# layer
for i in range(1, self.numLayers+1):
self.layerZ.append([z, z+self.layerThickness[i-1]])
z = self.layerZ[-1][1]
# calculate the critical angle cosines for each layer
# crticial angle at top interface of the current layer
n1 = self.layer[i].n
n2 = self.layer[i-1].n
if n1 > n2:
cosCrit0 = (1.0 - n2*n2/(n1*n1))**0.5
else:
cosCrit0 = 0.0
# crticial angle at bottom interface of the current layer
n2 = self.layer[i+1].n
if n1 > n2:
cosCrit1 = (1.0 - n2*n2/(n1*n1))**0.5
else:
cosCrit1 = 0.0
self.cosCrit.append([cosCrit0, cosCrit1])
def calc_r_specular(self):
# direct reflections from the 1st and 2nd layers.
temp = (self.layer[0].n - self.layer[1].n)/(self.layer[0].n + \
self.layer[1].n)
r1 = temp*temp
if ((self.layer[1].mua == 0.0) and (self.layer[1].mus == 0.0)):
# glass layer.
temp = (self.layer[1].n - self.layer[2].n)/(self.layer[1].n + \
self.layer[2].n)
r2 = temp*temp
r1 = r1 + (1 - r1)*(1 - r1)*r2/(1 - r1*r2)
return r1
class ModelInput:
"""ModelInput class - multi-layered photon scattering model input
Class instance variables:
Wth - play roulette if photon weight < Wth
dz - z grid separation [cm]
dr - r grid separation [cm]
da - alpha grid separation [radian]
nz - array range 0..nz-1
nr - array range 0..nr-1
na - array range 0..na-1
layerObj - medium layer structure class instance
Methods:
"""
def __init__(self, modelName = 'BARE_DERMIS'):
if modelName.lower() == 'BARE_DERMIS'.lower():
self.layerObj = LayerStruct('BARE_DERMIS')
self.dz = 100e-4
self.dr = 100e-4
self.nz = 30
self.nr = 50
self.na = 10
elif modelName.lower() == 'TYPE_II_SKIN'.lower():
self.layerObj = LayerStruct('TYPE_II_SKIN')
self.dz = 20e-4
self.dr = 20e-4
self.nz = 10
self.nr = 50
self.na = 10
elif modelName.lower() == 'CORNEA'.lower():
self.layerObj = LayerStruct('CORNEA')
self.dz = 10e-4
self.dr = 10e-4
self.nz = 100
self.nr = 50
self.na = 10
elif modelName.lower() == 'EYE_ANTERIOR'.lower():
self.layerObj = LayerStruct('EYE_ANTERIOR')
self.dz = 20e-4
self.dr = 20e-4
self.nz = 500
self.nr = 250
self.na = 10
else:
self.layerObj = LayerStruct('BARE_DERMIS')
self.dz = 100e-4
self.dr = 100e-4
self.nz = 30
self.nr = 50
self.na = 10
self.Wth = WEIGHT
self.da = 0.5*np.pi/self.na
class MCMLModel(ModelInput):
"""MCMLModel class - multi-layered photon scattering model, inherits from
ModelInput layer structure setup
Class instance variables:
Rsp - specular reflectance [-]
Rd - total diffuse reflectance [-]
A - total absorption probability [-]
Tt - total transmittance [-]
Rd_ra - 2D distribution of diffuse reflectance [1/(cm2 sr)]
Rd_r - 1D radial distribution of diffuse reflectance [1/cm2]
Rd_a - 1D angular distribution of diffuse reflectance [1/sr]
A_rz - 2D probability density in turbid media over r & z [1/cm3]
A_z - 1D probability density over z [1/cm]
A_l - each layer's absorption probability [-]
Tt_ra - 2D distribution of total transmittance [1/(cm2 sr)]
Tt_r - 1D radial distribution of transmittance [1/cm2]
Tt_a - 1D angular distribution of transmittance [1/sr]
Methods:
"""
def __init__(self, modelName = 'BARE_DERMIS'):
# extend the ModelInput base class instance variables
ModelInput.__init__(self, modelName)
self.numPhotons = 0
# initialize the model grid arrays
self.Rsp = self.layerObj.calc_r_specular()
self.Rd = 0.0
self.A = 0.0
self.Tt = 0.0
self.Rd_ra = np.matrix(np.zeros((self.nr, self.na)))
self.Rd_r = np.zeros(self.nr)
self.Rd_a = np.zeros(self.na)
self.A_rz = np.matrix(np.zeros((self.nr, self.nz)))
self.A_z = np.zeros(self.nz)
self.A_l = np.zeros(2 + self.layerObj.numLayers)
self.Tt_ra = np.matrix(np.zeros((self.nr, self.na)))
self.Tt_r = np.zeros(self.nr)
self.Tt_a = np.zeros(self.na)
def do_one_run(self, numPhotons):
for i in range(numPhotons):
photon = Photon(self.layerObj, self.Rsp)
photon.run_one_photon(self)
def sum_scale_result(self):
# Get 1D & 0D results.
self.sum_2D_Rd()
self.sum_2D_A()
self.sum_2D_Tt()
self.scale_Rd_Tt()
self.scale_A()
def sum_2D_Rd(self):
# Get 1D array elements by summing the 2D array elements.
for ir in range(self.nr):
sum = 0.0
for ia in range(self.na):
sum += self.Rd_ra[ir, ia]
self.Rd_r[ir] = sum
for ia in range(self.na):
sum = 0.0
for ir in range(self.nr):
sum += self.Rd_ra[ir, ia]
self.Rd_a[ia] = sum
sum = 0.0
for ir in range(self.nr):
sum += self.Rd_r[ir]
self.Rd = sum
def iz_to_layer(self, iz):
# Return the index to the layer according to the index
# to the grid line system in z direction (Iz).
# Use the center of box.
i = 1 # index to layer.
while ((iz+0.5)*self.dz >= self.layerObj.layerZ[i][1] and \
i < self.layerObj.numLayers):
i += 1
return i
def sum_2D_A(self):
# Get 1D array elements by summing the 2D array elements.
for iz in range(self.nz):
sum = 0.0
for ir in range(self.nr):
sum += self.A_rz[ir, iz]
self.A_z[iz] = sum
sum = 0.0
for iz in range(self.nz):
sum += self.A_z[iz]
self.A_l[self.iz_to_layer(iz)] += self.A_z[iz]
self.A = sum
def sum_2D_Tt(self):
# Get 1D array elements by summing the 2D array elements.
for ir in range(self.nr):
sum = 0.0
for ia in range(self.na):
sum += self.Tt_ra[ir, ia]
self.Tt_r[ir] = sum
for ia in range(self.na):
sum = 0.0
for ir in range(self.nr):
sum += self.Tt_ra[ir, ia]
self.Tt_a[ia] = sum
sum = 0.0
for ir in range(self.nr):
sum += self.Tt_r[ir]
self.Tt = sum
def scale_Rd_Tt(self):
# Scale Rd and Tt properly.
# "a" stands for angle alpha.
# Scale Rd(r,a) and Tt(r,a) by
# (area perpendicular to photon direction)
# x(solid angle)x(No. of photons).
# or
# [2*PI*r*dr*cos(a)]x[2*PI*sin(a)*da]x[No. of photons]
# or
# [2*PI*PI*dr*da*r*sin(2a)]x[No. of photons]
# Scale Rd(r) and Tt(r) by
# (area on the surface)x(No. of photons).
# Scale Rd(a) and Tt(a) by
# (solid angle)x(No. of photons).
scale1 = 4.0*np.pi*np.pi*self.dr*np.sin(self.da/2)\
*self.dr*self.numPhotons
# The factor (ir+0.5)*sin(2a) to be added.
for ir in range(self.nr):
for ia in range(self.na):
scale2 = 1.0/((ir+0.5)*np.sin(2.0*(ia+0.5)*self.da)*scale1)
self.Rd_ra[ir, ia] *= scale2
self.Tt_ra[ir, ia] *= scale2
scale1 = 2.0*np.pi*self.dr*self.dr*self.numPhotons
# area is 2*PI*[(ir+0.5)*dr]*dr.
# ir+0.5 to be added. */
for ir in range(self.nr):
scale2 = 1.0/((ir+0.5)*scale1)
self.Rd_r[ir] *= scale2
self.Tt_r[ir] *= scale2
scale1 = 2.0*np.pi*self.da*self.numPhotons
# solid angle is 2*PI*sin(a)*da. sin(a) to be added.
for ia in range(self.na):
scale2 = 1.0/(np.sin((ia+0.5)*self.da)*scale1)
self.Rd_a[ia] *= scale2
self.Tt_a[ia] *= scale2
scale2 = 1.0/self.numPhotons
self.Rd *= scale2
self.Tt *= scale2
def scale_A(self):
# Scale absorption arrays properly.
# Scale A_rz.
scale1 = 2.0*np.pi*self.dr*self.dr*self.dz*self.numPhotons
# volume is 2*pi*(ir+0.5)*dr*dr*dz.*/
# ir+0.5 to be added.
for iz in range(self.nz):
for ir in range(self.nr):
self.A_rz[ir, iz] /= (ir+0.5)*scale1
# Scale A_z.
scale1 = 1.0/(self.dz*self.numPhotons)
for iz in range(self.nz):
self.A_z[iz] *= scale1
# Scale A_l. Avoid int/int.
scale1 = 1.0/self.numPhotons
for il in range(self.layerObj.numLayers+2):
self.A_l[il] *= scale1
self.A *=scale1
def get_mua_at_iz(self, iz):
i = 1 # index to layer
numLayers = self.layerObj.numLayers
dz = self.dz
while ((iz + 0.5)*dz >= self.layerObj.layerZ[i][1] and i < numLayers):
i += 1
mua = self.layerObj.layer[i].mua
return mua
class Photon:
"""Photon class - MCML photon class for Monte Carlo scattering model in
multilayered turbid media.
Class instance variables:
x = Cartesian coordinate x [cm]
y = Cartesian coordinate y [cm]
z = Cartesian coordinate z [cm]
ux = directional cosine x of a photon
uy = directional cosine y of a photon
uz = directional cosine z of a photon
w - weight
dead - true if photon is terminated
layer - index to layer where the photon packet resides
s - current step size [cm]
sleft - step size left, dimensionless [-]
Methods:
"""
def __init__(self, layerObj = LayerStruct('BARE_DERMIS'), \
rSpecular = 0.017):
# initialize a photon
self.x = 0.0
self.y = 0.0
self.z = 0.0
self.ux = 0.0
self.uy = 0.0
self.uz = 1.0
self.w = 1.0 - rSpecular
self.dead = False
self.layer = 1
self.s = 0
self.sleft = 0
# take care of the case when the first layer is glass
if (layerObj.layer[1].mua == 0.0) and (layerObj.layer[1].mus == 0.0):
self.layer = 2 # skip to next layer
self.z = layerObj.layerZ[2][0] # use z0 from the next layer
def run_one_photon(self, model):
while self.dead == False:
self.hop_drop_spin(model)
model.numPhotons += 1
def hop_drop_spin(self, model):
layer = self.layer
if (model.layerObj.layer[layer].mua == 0.0) and \
(model.layerObj.layer[layer].mus == 0.0):
# glass layer
self.hop_in_glass(model)
else:
self.hop_drop_spin_in_tissue(model)
if (self.w < model.Wth) and (self.dead == False):
self.roulette
def hop_in_glass(self, model):
# Move the photon packet in glass layer.
# Horizontal photons are killed because they will
# never interact with tissue again.
if self.uz == 0.0:
# horizontal photon in glass is killed
self.dead = True
else:
self.step_size_in_glass(model)
self.hop()
self.cross_or_not(model)
def hop_drop_spin_in_tissue(self, model):
# Set a step size, move the photon, drop some weight,
# choose a new photon direction for propagation.
# When a step size is long enough for the photon to
# hit an interface, this step is divided into two steps.
# First, move the photon to the boundary free of
# absorption or scattering, then decide whether the
# photon is reflected or transmitted.
# Then move the photon in the current or transmission
# medium with the unfinished stepsize to interaction
# site. If the unfinished stepsize is still too long,
# repeat the above process.
self.step_size_in_tissue(model)
if self.hit_boundary(model) == True:
self.hop() # move to boundary plane
self.cross_or_not(model)
else:
self.hop()
self.drop(model);
self.spin(model.layerObj.layer[self.layer].g)
def step_size_in_glass(self, model):
# If uz != 0, return the photon step size in glass,
# Otherwise, return 0.
# The step size is the distance between the current
# position and the boundary in the photon direction.
# Make sure uz !=0 before calling this function.
# Stepsize to the boundary.
layer = self.layer
uz = self.uz
if uz > 0.0:
dl_b = (model.layerObj.layerZ[layer][1] - self.z)/uz
elif uz < 0.0:
dl_b = (model.layerObj.layerZ[layer][0] - self.z)/uz
else:
dl_b = 0.0
self.s = dl_b;
def step_size_in_tissue(self, model):
# Pick a step size for a photon packet when it is in
# tissue.
# If the member sleft is zero, make a new step size
# with: -log(rnd)/(mua+mus).
# Otherwise, pick up the leftover in sleft.
# Layer is the index to layer.
# In_Ptr is the input parameters.
layer = self.layer
mua = model.layerObj.layer[layer].mua
mus = model.layerObj.layer[layer].mus
if self.sleft == 0.0: # make a new step
rnd = np.random.random_sample()
self.s = -np.log(rnd)/(mua + mus)
else: # take the leftover
self.s = self.sleft/(mua + mus)
self.sleft = 0.0
def hop(self):
# Move the photon s away in the current layer of medium.
s = self.s
self.x += s*self.ux
self.y += s*self.uy
self.z += s*self.uz
def cross_or_not(self, model):
if self.uz < 0.0:
self.cross_up_or_not(model)
else:
self.cross_dn_or_not(model)
def cross_up_or_not(self, model):
# Decide whether the photon will be transmitted or
# reflected on the upper boundary (uz<0) of the current
# layer.
# If "layer" is the first layer, the photon packet will
# be partially transmitted and partially reflected if
# PARTIALREFLECTION is set to 1,
# or the photon packet will be either transmitted or
# reflected determined statistically if PARTIALREFLECTION
# is set to 0.
# Record the transmitted photon weight as reflection.
# If the "layer" is not the first layer and the photon
# packet is transmitted, move the photon to "layer-1".
# Update the photon parmameters.
uz = self.uz
r = 0.0 # reflectance
layer = self.layer
ni = model.layerObj.layer[layer].n
nt = model.layerObj.layer[layer-1].n
# Get r.
if -uz <= model.layerObj.cosCrit[layer][0]:
r = 1.0 # total internal reflection
else:
r, uz1 = RFresnel(ni, nt, -uz)
if PARTIALREFLECTION == 1:
if (layer == 1) and (r < 1.0): # partially transmitted
self.uz = -uz1 # transmitted photon
self.record_R(r, model)
self.uz = -uz # reflected photon
elif np.random.random_sample() > r: # transmitted to layer-1
self.layer -= 1
self.ux *= ni/nt
self.uy *= ni/nt
self.uz = -uz1
else : # reflected
self.uz = -uz
else:
if np.random.random_sample() > r: # transmitted to layer-1
if layer == 1:
self.uz = -uz1
self.record_R(model, 0.0)
self.dead = True
else:
self.layer -= 1
self.ux *= ni/nt
self.uy *= ni/nt
self.uz = -uz1
else: # reflected
self.uz = -uz
def cross_dn_or_not(self, model):
# Decide whether the photon will be transmitted or be
# reflected on the bottom boundary (uz>0) of the current
# layer.
# If the photon is transmitted, move the photon to
# "layer+1". If "layer" is the last layer, record the
# transmitted weight as transmittance. See comments for
# CrossUpOrNot.
# Update the photon parmameters.
uz = self.uz # z directional cosine
r = 0.0 # reflectance
layer = self.layer
ni = model.layerObj.layer[layer].n
nt = model.layerObj.layer[layer+1].n
# Get r
if uz <= model.layerObj.cosCrit[layer][1]:
r=1.0 # total internal reflection
else:
r, uz1 = RFresnel(ni, nt, uz)
if PARTIALREFLECTION == 1:
if (layer == model.layerObj.numLayers) and (r < 1.0):
self.uz = uz1
self.record_T(r, model)
self.uz = -uz
elif np.random.random_sample() > r: # transmitted to layer+1
self.layer += 1
self.ux *= ni/nt
self.uy *= ni/nt
self.uz = uz1
else: # reflected
self.uz = -uz
else:
if np.random.random_sample() > r: # transmitted to layer+1
if layer == model.layerObj.numLayers:
self.uz = uz1
self.record_T(model, 0.0)
self.dead = True
else:
self.layer += 1
self.ux *= ni/nt
self.uy *= ni/nt
self.uz = uz1
else: # reflected
self.uz = -uz
def hit_boundary(self, model):
# Check if the step will hit the boundary.
# Return 1 if hit boundary.
# Return 0 otherwise.
# If the projected step hits the boundary, the members
# s and sleft of Photon_Ptr are updated.
layer = self.layer
uz = self.uz
# Distance to the boundary.
if uz > 0.0:
dl_b = (model.layerObj.layerZ[layer][1] - self.z)/uz # dl_b>0
elif uz < 0.0:
dl_b = (model.layerObj.layerZ[layer][0] - self.z)/uz # dl_b>0
if (uz != 0.0) and (self.s > dl_b):
# not horizontal & crossing
mut = model.layerObj.layer[layer].mua + \
model.layerObj.layer[layer].mus
self.sleft = (self.s - dl_b)*mut
self.s = dl_b
hit = True
else:
hit = False
return hit
def drop(self, model):
# Drop photon weight inside the tissue (not glass).
# The photon is assumed not dead.
# The weight drop is dw = w*mua/(mua+mus).
# The dropped weight is assigned to the absorption array
# elements.
x = self.x
y = self.y
layer = self.layer
# compute array indices
iz = int(self.z/model.dz)
if iz > (model.nz - 1):
iz = model.nz - 1
ir = int((x*x + y*y)**0.5/model.dr)
if ir > (model.nr - 1):
ir = model.nr - 1
# update photon weight.
mua = model.layerObj.layer[layer].mua
mus = model.layerObj.layer[layer].mus
dwa = self.w * mua/(mua+mus)
self.w -= dwa
# assign dwa to the absorption array element.
model.A_rz[ir, iz] += dwa
def spin(self, g):
# Choose a new direction for photon propagation by
# sampling the polar deflection angle theta and the
# azimuthal angle psi.
# Note:
# theta: 0 - pi so sin(theta) is always positive
# feel free to use sqrt() for cos(theta).
# psi: 0 - 2pi
# for 0-pi sin(psi) is +
# for pi-2pi sin(psi) is -
ux = self.ux
uy = self.uy
uz = self.uz
cost = SpinTheta(g)
sint = (1.0 - cost*cost)**0.5
# sqrt() is faster than sin().
psi = 2.0*np.pi*np.random.random_sample() # spin psi 0-2pi
cosp = np.cos(psi)
if psi < np.pi:
sinp = (1.0 - cosp*cosp)**0.5
# sqrt() is faster than sin().
else:
sinp = -(1.0 - cosp*cosp)**0.5
if np.fabs(uz) > COSZERO: # normal incident.
self.ux = sint*cosp
self.uy = sint*sinp
self.uz = cost*np.sign(uz)
# SIGN() is faster than division.
else: # regular incident.
temp = (1.0 - uz*uz)**0.5
self.ux = sint*(ux*uz*cosp - uy*sinp)/temp + ux*cost
self.uy = sint*(uy*uz*cosp + ux*sinp)/temp + uy*cost
self.uz = -sint*cosp*temp + uz*cost
def record_R(self, model, refl):
# Record the photon weight exiting the first layer(uz<0),
# no matter whether the layer is glass or not, to the
# reflection array.
# Update the photon weight as well.
x = self.x
y = self.y
ir = int((x*x + y*y)**0.5/model.dr)
if ir > (model.nr - 1):
ir = (model.nr - 1)
ia = int(np.arccos(-self.uz)/model.da)
if ia > (model.na - 1):
ia = model.na - 1
# assign photon to the reflection array element.
model.Rd_ra[ir, ia] += self.w*(1.0 - refl)
self.w *= refl
def record_T(self, model, refl):
# Record the photon weight exiting the last layer(uz>0),
# no matter whether the layer is glass or not, to the
# transmittance array.
# Update the photon weight as well.
x = self.x
y = self.y
ir = int((x*x + y*y)**0.5/model.dr)
if ir > (model.nr - 1):
ir = model.nr - 1
ia = int(np.arccos(self.uz)/model.da)
if ia > (model.na - 1):
ia = model.na - 1
# assign photon to the transmittance array element.
model.Tt_ra[ir, ia] += self.w*(1.0 - refl)
self.w *= refl
def roulette(self):
# The photon weight is small, and the photon packet tries
# to survive a roulette.
if self.w == 0.0:
self.dead = True
elif np.random.random_sample() < CHANCE: # survived the roulette.
self.w /= CHANCE
else:
self.dead = True
def RFresnel(n1, n2, ca1):
# Compute the Fresnel reflectance.
# Make sure that the cosine of the incident angle a1
# is positive, and the case when the angle is greater
# than the critical angle is ruled out.
# Avoid trigonometric function operations as much as
# possible, because they are computation-intensive.
if n1 == n2: # matched boundary
ca2 = ca1
r = 0.0
elif ca1 > COSZERO: # normal incident
ca2 = ca1
r = (n2-n1)/(n2+n1)
r *= r
elif ca1 < COS90D: # very slant
ca2 = 0.0
r = 1.0
else: # general
# sine of the incident and transmission angles
sa1 = (1.0 - ca1*ca1)**0.5
sa2 = n1*sa1/n2
if sa2 >= 1.0:
# double check for total internal reflection
ca2 = 0.0
r = 1.0
else:
# cosines of the sum ap or
# difference am of the two
# angles. ap = a1+a2
# am = a1 - a2
ca2 = (1.0 - sa2*sa2)**0.5;
cap = ca1*ca2 - sa1*sa2 # c+ = cc - ss
cam = ca1*ca2 + sa1*sa2 # c- = cc + ss
sap = sa1*ca2 + ca1*sa2 # s+ = sc + cs
sam = sa1*ca2 - ca1*sa2 # s- = sc - cs
r = 0.5*sam*sam*(cam*cam+cap*cap)/(sap*sap*cam*cam)
return r, ca2
def SpinTheta(g):
# Choose (sample) a new theta angle for photon propagation
# according to the anisotropy.
# If anisotropy g is 0, then
# cos(theta) = 2*rand-1.
# otherwise
# sample according to the Henyey-Greenstein function.
# Returns the cosine of the polar deflection angle theta.
if g == 0.0:
cost = 2*np.random.random_sample() - 1
else:
temp = (1 - g*g)/(1 - g + 2*g*np.random.random_sample())
cost = (1 + g*g - temp*temp)/(2*g)
if cost < -1:
cost = -1.0
elif cost > 1:
cost = 1.0
return cost
|
C++
|
UTF-8
| 659 | 4 | 4 |
[] |
no_license
|
/*
* Determine whether an integer is a palindrome.
* An integer is a palindrome when it reads the same backward as forward.
* Without converting the interger to string
*/
#include <iostream>
class Solution {
public:
bool isPalindrome(int x) {
if (x < 0) return false;
int _x = x;
int rev = 0;
while (_x != 0) {
rev = rev * 10 + _x % 10;
_x /= 10;
}
if (rev == x) return true;
return false;
}
};
int main() {
Solution s;
int x;
x = 121;
std::cout << s.isPalindrome(x) << std::endl;
x = -121;
std::cout << s.isPalindrome(x) << std::endl;
x = 10;
std::cout << s.isPalindrome(x) << std::endl;
}
|
Markdown
|
UTF-8
| 6,584 | 2.515625 | 3 |
[] |
no_license
|
---
author: allen
comments: true
date: 2014-06-30 23:00:00
layout: post
slug: "a-company-made-of-people"
summary: "Apple proves it's human."
title: "A Company Made of People"
categories:
- Article
oldtags:
- Apple
---
<img src='/images/2014/apple-cube.jpg' style='width:250px'>
The worst misconception I see about Apple, or around any large company for that matter, is that the company is monolithic. One homogeneous entity that acts in unison. This idea breeds misunderstanding.
The news teaches us that companies are ethicless profit-seeking automata. They are granted corporate personhood, with [the right to deny healthcare to their workers](http://jezebel.com/why-women-arent-people-but-corporations-are-1598061808) but no obligation to make the world a better place. Most people think of corporations as a single soulless blob.
No corporation has worked harder to seem monolithic than Apple. With a famously tight focus and legendary secrecy, the internal workings of the company are a mystery. "Apple" rejects your app, not some front-line app reviewer. "Apple" opaquely dupes your Radars, not a specific team's junior Engineering Project Manager. For years, Apple's showmanship and PR have bred the sense that they are more magical chocolate factory than cube farm.
## Producing the world's finest sausage
Back when I worked there, I was surprised by many things. More than anything else, though, I was surprised that it is simply a company made of people.
A company made of very bright people, of course. Very bright people working very hard. But still, people. Messy, wonderful, fallible people just trying to do their jobs. People who disagree with one another. People with families, and hobbies, and political opinions. People who say things that are not finely crafted PR messages.
This may seem obvious when put into words, but all these details are so well hidden from view in Apple's external persona that I was taken aback by it. Most of the executive staff didn't speak publically. Even Steve Jobs himself reserved his spotlight for the product - politics and personal flair, not so much.
Although [some employees](http://randsinrepose.com/) got away with writing under a pseudonym, most Apple folks reasonably considered media attention [a bad thing](http://abcnews.go.com/Technology/apple-engineer-gray-powell-lost-iphone/story?id=10430224) and did their best to stay under the radar.
<img src='/images/2014/scott-erase.jpg' style='width:250px'>
Today, the people, their personalities, and their values are starting to shine through. Beginning with the leadership “[changes to increase collaboration](https://www.apple.com/pr/library/2012/10/29Apple-Announces-Changes-to-Increase-Collaboration-Across-Hardware-Software-Services.html),” through the departure of Katie Cotton as the head of PR, to the most open WWDC in memory, it's become clear that this is intentional.
WWDC this year was filled with things that developers have wanted for years, but most assumed Apple would never allow. We got open analytics data in iTunes Connect, more generous allowances for beta testing, and a slew of extensibility APIs throughout the OS. At the same time, the [lifting of the ridiculous WWDC NDA](http://oleb.net/blog/2014/06/apple-lifted-beta-nda/) dramatically improved discussion and collaboration within the community.
Developers went wild. Brent Simmons marked it [the beginning of a new era](http://inessential.com/2014/06/06/early_thoughts_on_wwdc_2014), Chock [chalked it up to confidence](http://furbo.org/2014/06/03/confidence/), and Casey Liss [relished the sense of cooperation](http://www.caseyliss.com/2014/6/6/together). All true.
Still, there's more to it.
### The people shining through
Earlier this year, at Apple's annual shareholder meeting, a representative of an anti-environment activist group asked Tim Cook to halt Apple's environmental initiatives unless they could be proven profitable. [Cook's response](http://www.macobserver.com/tmo/article/tim-cook-soundly-rejects-politics-of-the-ncppr-suggests-group-sell-apples-s):
> When we work on making our devices accessible by the blind, I don't consider the bloody ROI.
He suggested the group sell their Apple stock. I'm not sure what Katie Cotton thought of that, but it was great to see Tim's personality and values laid out.
More recently, Eddy Cue and Jimmy Iovine [did an interview for re/code](http://recode.net/2014/05/30/apples-jimmy-iovine-and-eddy-cue-explain-the-beats-deal-and-hint-at-the-future-video/), Jony Ive has been giving more frequent and in depth [interviews](http://bits.blogs.nytimes.com/2014/06/16/jonathan-ive-on-apples-design-process-and-product-philosophy/), Angela Arhents [wrote a piece on LinkedIn](https://www.linkedin.com/today/post/article/20140623211315-269697626-starting-anew) about her first month at Apple, and Phil Schiller has [started tweeting regularly](https://twitter.com/pschiller), cartoon avatar and all.
Of course, no discussion of Apple execs letting their hair down is complete without Craig Federighi. Craig's WWDC performance was full of personality, but I paid special attention to a gesture he made off stage. He took the time, on what was surely one of the most exhausting days of his life, to let hordes of developers take selfies with their silver-haired hero.
<img src='/images/2014/craig-triptych-wide.jpg' style='width:100%'>
With the WWDC NDA lifted, other Apple employees, from [the creator of Swift](https://twitter.com/clattner_llvm) to various API maintainers, took to Twitter to gather feedback on all the goodies they'd dumped on developers. In the web community this would be expected behaviour. In the Apple community, it's a delight.
Of course, this is a shift, not a revolution. Apple will never get to the point where their culture tolerates, say, [employees publicly tweeting that their CEO should step down](http://thenextweb.com/insider/2014/03/27/staff-mozilla-call-new-ceo-brendan-eich-step/). Indeed, as a public company with fierce competitors, they're obligated to maintain decorum and secrecy around things that are materially sensitive.
Still, around the things that aren't core secrets - developer relations, employee personality, and standing up for their values - Apple is feeling more like a chorus of real people and less like a monolith.
On Sunday, Tim Cook [led thousands of Apple employees in the San Francisco Pride Parade](http://9to5mac.com/2014/06/29/tim-cook-and-apple-celebrate-applepride-in-san-francisco-today/). This is Tim's Apple, and I like it a lot.
<img src='/images/2014/apple-pride.jpg' style='width:100%'>
|
JavaScript
|
UTF-8
| 1,682 | 2.6875 | 3 |
[] |
no_license
|
import Mecab from 'mecab-async'
import { SourceModel, WordModel } from '../models'
export default class ParseService {
constructor() {
this.mecab = new Mecab()
}
parse(callback, limit = 1000) {
(async () => {
let sources = await SourceModel.findAll({where: {parsed: 0}, limit: limit})
let i, j, source, words, word_instance
for (i = 0; i < sources.length; i++) {
source = sources[i]
words = await this.wakachi(source.message)
words = this.formatWordList(words)
for (j = 0; j < words.length - 1; j++) {
word_instance = await WordModel.findOne({
where: {
first_word : words[j],
second_word: words[j + 1]
}
})
if (word_instance) {
word_instance.point++
} else {
word_instance = WordModel.build({
first_word : words[j],
second_word: words[j + 1],
point : 1
})
}
await word_instance.save()
}
source.parsed = 1
await source.save()
}
callback()
})().catch(err => {
console.error(err)
process.exit(1)
})
}
wakachi(message) {
return new Promise((resolve, reject) => {
this.mecab.parse(message, (err, result) => {
return (err) ? reject(err) : resolve(result)
})
})
}
formatWordList(words) {
words = words.map((words) => {
return words[0] === 'EOS' ? '__END__' : words[0]
})
if (words.length === 0) {
return []
}
words.unshift('__BEGIN__')
words.push('__END__')
return words
}
}
|
Python
|
UTF-8
| 8,975 | 2.53125 | 3 |
[
"Apache-2.0"
] |
permissive
|
#!/usr/bin/python
# install via pip: web3, jsonschema
#
# ethInterface.py
# python script that listens for json requests, parses them and interacts with the ethereum blockchain
# to store the delivered via smart contract. Needs contract address, abi and an ethereum (light) node including account with some eth
# works asynchronousm all incoming requests are dumped into a queue beforehand and processed afterwards
import sys
import web3
from web3 import Web3, HTTPProvider
from web3.gas_strategies.time_based import medium_gas_price_strategy
from web3.contract import ConciseContract
import queue
import fnmatch
import json
from jsonschema import validate
import time
import datetime
import http.server
from http.server import BaseHTTPRequestHandler, HTTPServer
import socketserver
from socketserver import ThreadingMixIn
import threading
debug = False #for extensive logging
mainnet = True # if not True: use ropsten test net
# if a trade should be logged onto the block chain
# has the timestamp of order and direction as in "Up" or "down"
class tradeobject:
def __init__(self, year,month,day,hour,minute,second,direction):
self.year=year
self.month=month
self.day=day
self.hour=hour
self.minute=minute
self.second=second
self.direction=direction
self.purpose="addtrade"
# if a trade is closed this will be stored onto the block chain
# has the exact closing time and the result as in pips
class resultobject:
def __init__(self, year,month,day,hour,minute,second,netpips):
self.year=year
self.month=month
self.day=day
self.hour=hour
self.minute=minute
self.second=second
self.netpips=netpips
self.purpose="addresult"
class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):
pass
# requesthandler parses the http request and creates an object that is dropped into the main loop
# as of now, all http requests with proper data fields here will go into the blockchain function
class RequestHandler(BaseHTTPRequestHandler):
def log_message(self, format, *args):
return
def do_POST(self):
request_path = self.path
if debug:
print("\n----- Request Start ----->\n")
print("Request path:", request_path)
request_headers = self.headers
content_length = request_headers.get('Content-Length')
length = int(content_length) if content_length else 0
if debug:
print("Content Length:", length)
print("Request headers:", request_headers)
print("Request payload:", self.rfile.read(length))
print("<----- Request End -----\n")
obj = json.loads(self.rfile.read(length))
if debug:
print("Request payload:", obj)
print(datetime.datetime.now())
doQuery="false"
doFunction=""
for x in obj:
print("RECEIVED: ",x, " ", obj[x])
if(x=="do"):
if(obj[x]=="query"):
doQuery="true"
if(x=="function"):
if(obj[x]=="getTrade"):
doFunction="getTrade"
if(doQuery=="true"):
if(doFunction!=""):
print("put/exec function: ", doFunction ," use main net: ", mainnet)
q.put(doFunction)
if("hour" in obj and "minute" in obj and "second" in obj and "direction" in obj and "year" in obj and "month" in obj and "day" in obj):
if("TEST" not in obj["direction"]):
print("found addTrade - ", obj["direction"])
q.put(tradeobject(obj["year"],obj["month"],obj["day"],obj["hour"],obj["minute"],obj["second"],obj["direction"]))
if("hour" in obj and "minute" in obj and "second" in obj and "netpips" in obj and "year" in obj and "month" in obj and "day" in obj):
if("TEST" not in obj["netpips"]):
print("found addResult - ", obj["netpips"])
q.put(resultobject(obj["year"],obj["month"],obj["day"],obj["hour"],obj["minute"],obj["second"],obj["netpips"]))
self.send_response(200)
self.end_headers()
#possible to give a return message to the post request
responsetext="this is a sample return message."
self.wfile.write(responsetext.encode("utf-8"))
# interface to Ethereum blockchain. Has the ABI of the contract, and interacts with the blockchain through the functions addTradeNow()
# and addResultNow()
# Needs a ethereum node reachable via http and an account with some eth to pay for gas in it
# Light Node is enough, no need to sync the whole chain
class EthInterface:
def __init__(self):
if(mainnet):
self.web3Interface = Web3(HTTPProvider('http://localhost:8545')) #real net
else:
self.web3Interface = Web3(HTTPProvider('http://localhost:8546')) #test net
self.web3Interface.eth.setGasPriceStrategy(medium_gas_price_strategy)
for account in self.web3Interface.eth.accounts:
print("account: ", account, " - balance: ", self.web3Interface.eth.getBalance(account))
#implicit: first account used
if(self.web3Interface.eth.accounts):
self.useAccount = self.web3Interface.eth.accounts[0]
print("using account ", self.useAccount)
jforexabiJSON = open('/path/to/Contract.json', 'r').read() #read the ABI for the contract
self.jforexabi = json.loads(jforexabiJSON)
if(mainnet):
self.adr = self.web3Interface.toChecksumAddress("0xffffffffffffffffffffffffffffffffffffffff") #address of main net contract
else:
self.adr = self.web3Interface.toChecksumAddress("0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee") #address of test net contract
self.myContract = self.web3Interface.eth.contract(address=self.adr, abi=self.jforexabi)
if debug:
print("self my contract set to ", self.myContract)
def callback_newblock(self,block_hash): #may be useful later for monitoring of blockchain related events
pass
def addTradeNow(self,tradeObjectdata):
print("called addTradeNow")
dateData=int(tradeObjectdata.year+tradeObjectdata.month+tradeObjectdata.day)
timeData=int(tradeObjectdata.hour+tradeObjectdata.minute+tradeObjectdata.second)
fulltime=int(tradeObjectdata.year+tradeObjectdata.month+tradeObjectdata.day+tradeObjectdata.hour+tradeObjectdata.minute+tradeObjectdata.second)
buyBool=False
if tradeObjectdata.direction is "up":
buyBool=True
print("tradeObjectdata: ", fulltime, " buy ",buyBool, " use account: ", self.useAccount)
tx_hash = self.myContract.functions.addTrade(fulltime,buyBool).transact({'from': self.useAccount,'gas': 160000})
try:
txn_receipt = self.web3Interface.eth.waitForTransactionReceipt(tx_hash, timeout=360)
except:
print("exception at waitForTransactionReceipt addTradeNow")
print("txn_receipt addTradeNow: ", txn_receipt)
def addResultNow(self,resultData):
print("called addResultNow")
resultpips=int(float(resultData.netpips))
print("will add result of ",resultpips, " to blockchain . main net?: ", mainnet)
uid = int(self.myContract.functions.getId().call())
print("received UID from blockchain: ", uid)
if(uid > -1):
tx_hash = self.myContract.functions.addProfit(uid,resultpips).transact({'from': self.useAccount,'gas': 160000})
try:
txn_receipt = self.web3Interface.eth.waitForTransactionReceipt(tx_hash, timeout=360)
except:
print("exception at waitfortransactionreceipt addProfit")
print("txn_receipt addResultNow: ", txn_receipt)
else:
print("invalid uid: ",uid)
# main loop iterates over its queue and assigns each item to
# the proper function...if applicable
def mainLoop(ethInterfaceObject):
while True:
qitem = q.get()
if(qitem.purpose is "addtrade"):
print("addtrade found in queue for ",qitem)
ethInterfaceObject.addTradeNow(qitem)
if(qitem.purpose is "addresult"):
print("addresult found in queue for ",qitem)
ethInterfaceObject.addResultNow(qitem)
time.sleep(10)
# main functions opens the webserver and starts the main loop with the Ethereum interface class
def main():
HOST, PORT = "localhost", 8080
server = ThreadingHTTPServer((HOST, PORT), RequestHandler)
ip, port = server.server_address
server_thread = threading.Thread(target=server.serve_forever)
server_thread.daemon = True
server_thread.start()
print("Server loop running in thread:", server_thread.name, ip, port)
ethClient = EthInterface()
mainLoop(ethClient)
# start here
if __name__ == "__main__":
q = queue.Queue()
main()
|
C#
|
UTF-8
| 3,754 | 3.09375 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Advent_of_Code_2020.Day7
{
public class Day7 : IDay
{
private static readonly Regex BagRegex = new Regex("^(?<color>.+?)\\sbags\\scontain\\s(?:\\s*(?<amount>\\d+)\\s(?<child>.+?)\\sbags?[,|\\.])*$");
public static IEnumerable<ColoredBag> ParseBagInput(string file)
{
var bags = new Dictionary<string, ColoredBag>();
new ResourceReader<ColoredBag>(file)
.LineReader(line =>
{
var match = BagRegex.Match(line);
var color = match.Groups["color"].Value;
if (!bags.ContainsKey(color))
bags.Add(color, new ColoredBag() {Color = color});
for (var i = 0; i < match.Groups["child"].Captures.Count; i++)
{
var childColor = match.Groups["child"].Captures[i].Value;
var childAmount = match.Groups["amount"].Captures[i].Value;
if (!bags.ContainsKey(childColor))
bags.Add(childColor, new ColoredBag() {Color = childColor});
var relation = new BagRelation()
{
Amount = int.Parse(childAmount),
Bag = bags[color],
ChildBag = bags[childColor]
};
bags[color].ChildBags.Add(relation);
bags[childColor].ParentBags.Add(relation);
}
return null;
});
return bags.Values;
}
private static int CountParentBags(ColoredBag coloredBag, ISet<ColoredBag> knownBags)
{
foreach (var bag in coloredBag.ParentBags.Select(relation => relation.Bag))
{
knownBags.Add(bag);
CountParentBags(bag, knownBags);
}
return knownBags.Count;
}
public static int CountParentBags(IEnumerable<ColoredBag> bags, string color)
{
return CountParentBags(bags.First(bag => bag.Color == color), new HashSet<ColoredBag>());
}
private static int CountAmountOfChildBags(ColoredBag bag)
{
var count = 0;
foreach (var relation in bag.ChildBags)
{
count += relation.Amount;
count += CountAmountOfChildBags(relation.ChildBag) * relation.Amount;
}
return count;
}
public static int CountAmountOfChildBags(IEnumerable<ColoredBag> bags, string color)
{
return CountAmountOfChildBags(bags.First(bag => bag.Color == color));
}
public void SolveProblem1()
{
var bags = ParseBagInput("Advent_of_Code_2020.Day7.input.txt").ToList();
Console.WriteLine(CountParentBags(bags, "shiny gold"));
}
public void SolveProblem2()
{
var bags = ParseBagInput("Advent_of_Code_2020.Day7.input.txt").ToList();
Console.WriteLine(CountAmountOfChildBags(bags, "shiny gold"));
}
}
public class ColoredBag
{
public string Color { get; set; }
public List<BagRelation> ChildBags { get; } = new List<BagRelation>();
public List<BagRelation> ParentBags { get; } = new List<BagRelation>();
}
public class BagRelation
{
public ColoredBag Bag { get; set; }
public ColoredBag ChildBag { get; set; }
public int Amount { get; set; }
}
}
|
Python
|
UTF-8
| 22,128 | 2.59375 | 3 |
[] |
no_license
|
import os
import numpy as np
import pandas
import HRV_METHODS
import globals
import openpyxl
def flag_match_exec(par, parSIM, lst, col_name): # flag_match(parECG, parSIM, list_of_bpm_flag, 'BPM')
"""
Match the scenario flag
from:simulation data
to:ecg data
--> by time
:param par: DataFrame of par data
:param parSIM: DataFrame of SIMULATION data
:param lst: List of List - values for specific flag
:param col_name: column name
:type par: DataFrame
:type parSIM: DataFrame
:type col_name: str
"""
i = 0
j = 1
initial_rows_at_par = len(par)
rows_sim = len(parSIM)
# print("initial_rows_at_par: " + str(initial_rows_at_par))
# print("initial_rows_at_sim: " + str(rows_sim))
if col_name == 'BPM':
l_limit = globals.BPM_lower
u_limit = globals.BPM_upper
if col_name == 'RRIntervals':
l_limit = globals.RR_lower
u_limit = globals.RR_upper
# print(l_limit)
# print(u_limit)
# print("start while loop")
exceptions_ok = check_filter_type(col_name)
while i < initial_rows_at_par:
curr_value = par.at[i, col_name]
if exceptions_ok:
if not (l_limit <= curr_value <= u_limit): # value not in range
i += 1
continue # move to the next value
if j < len(parSIM): # while there are still rows to match in ECG/RR-1
if parSIM.at[j - 1, 'Time'] <= par.at[i, 'Time'] < parSIM.at[j, 'Time']:
# if time in ECG/RR between time range in SIM
if int(parSIM.at[j - 1, 'Scenario']) != 0: # אם אנחנו לא בתרחיש 0 כלומר תרחיש אמיתי
if int(parSIM.at[j, 'Scenario']) == 0 and par.at[i, 'Time'] == parSIM.at[j - 1, 'Time']:
scenario = int(parSIM.at[j - 1, 'Scenario'])
else:
scenario = int(parSIM.at[j, 'Scenario'])
par.at[i, 'Scenario'] = scenario # match the flag
lst[scenario].append(par.at[i, col_name]) # מכניס לרשימה של הרשימות- bpm לכל flag
if col_name == "BPM":
dq_bpm_start_end_min_max_null(i, j, par, parSIM)
if col_name == "RRIntervals":
dq_rr_min_max_null(i, j, par, parSIM)
i += 1 # move to the next ECG/RR row to match
else:
j += 1
else:
break
def check_filter_type(col_name):
"""function that indicates which filter is selected in exceptions window"""
if globals.filter_type == globals.Filter.NONE:
return False
if globals.filter_type == globals.Filter.BPM and col_name != "BPM":
return False
if globals.filter_type == globals.Filter.RR and col_name != "RRIntervals":
return False
return True
def dq_bpm_start_end_min_max_null(i, j, par, parSIM):
"""
The function calculates the data quality indicators for calculate BPM (IN ECG FILE):
- start time
- end time
- min value
- max value
- null lines
"""
if int(parSIM.at[j, 'Scenario']) != 0:
globals.list_end_time[int(parSIM.at[j, 'Scenario']) - 1] = parSIM.at[j, 'Time'] # insert end time - all the time till the end
if globals.list_start_time[int(parSIM.at[j - 1, 'Scenario']) - 1] == 0:
globals.list_start_time[int(parSIM.at[j - 1, 'Scenario']) - 1] = parSIM.at[j - 1, 'Time'] # insert start time for the specific scenario
if par.at[i, 'BPM'] < globals.list_min_bpm[int(parSIM.at[j - 1, 'Scenario']) - 1]:
globals.list_min_bpm[int(parSIM.at[j - 1, 'Scenario']) - 1] = par.at[i, 'BPM'] # insert min value
if par.at[i, 'BPM'] > globals.list_max_bpm[int(parSIM.at[j - 1, 'Scenario']) - 1]:
globals.list_max_bpm[int(parSIM.at[j - 1, 'Scenario']) - 1] = par.at[i, 'BPM'] # insert max value
if par.at[i, 'BPM'] is None:
globals.list_null_bpm[int(parSIM.at[j - 1, 'Scenario']) - 1] += 1 # count null lines
def dq_rr_min_max_null(i, j, par, parSIM):
"""
The function calculates the data quality indicators for calculate HRV METHODS (IN RR FILE):
- min value
- max value
- null lines
"""
if par.at[i, 'RRIntervals'] < globals.list_min_rr[int(parSIM.at[j - 1, 'Scenario']) - 1]:
globals.list_min_rr[int(parSIM.at[j - 1, 'Scenario']) - 1] = par.at[i, 'RRIntervals'] # insert min value
if par.at[i, 'RRIntervals'] > globals.list_max_rr[int(parSIM.at[j - 1, 'Scenario']) - 1]:
globals.list_max_rr[int(parSIM.at[j - 1, 'Scenario']) - 1] = par.at[i, 'RRIntervals'] # insert max value
if par.at[i, 'RRIntervals'] is None:
globals.list_null_rr[int(parSIM.at[j - 1, 'Scenario']) - 1] += 1 # count null lines
def fix_min_bpm():
"""
The initial minimum value is initialized by a large number (1000)
and if it remains so, it is updated to be 0, because there is really no minimum value.
"""
for x in range(globals.scenario_num):
if globals.list_min_bpm[x] == 1000:
globals.list_min_bpm[x] = 0
def fix_min_rr():
"""
The initial minimum value is initialized by a large number (100)
and if it remains so, it is updated to be 0, because there is really no minimum value.
"""
for x in range(globals.scenario_num):
if globals.list_min_rr[x] == 100:
globals.list_min_rr[x] = 0
def rr_time_match(parRR):
"""
filling Time coloumn in RR file
:param parRR: DataFrame of RR data
"""
i = 1
while i < len(parRR):
parRR.at[i, 'Time'] = round(parRR.at[i - 1, 'Time'] + parRR.at[i - 1, 'RRIntervals'], 4)
i += 1
def initial_list_of_existing_par():
"""function that create a list of existing participants"""
globals.list_of_existing_par = [*range(1, globals.par_num + 1)]
copy_of_list_of_existing_par = [*range(1, globals.par_num + 1)]
# print("begining: list of existing par")
# print(globals.list_of_existing_par) # 1,2,3
for num in copy_of_list_of_existing_par:
# print("the num in list of copy of existing is " + str(num))
if num in globals.par_not_existing:
globals.list_of_existing_par.remove(num)
# print(globals.list_of_existing_par)
# print("list of existing par end:\n")
# print(*globals.list_of_existing_par)
def list_hrv_methods(avg_base, baseRR, list_of_rr_flag):
"""
Using functions from file "HRV_METHODS" to create lists of HRV methods per scenario
"""
listRMSSD = HRV_METHODS.RMSSD(list_of_rr_flag)
listSDSD = HRV_METHODS.SDSD(list_of_rr_flag)
listSDNN = HRV_METHODS.SDNN(list_of_rr_flag)
listPNN50 = HRV_METHODS.PNN50(list_of_rr_flag)
listBaseBPM = [avg_base] * globals.scenario_num
listBaseRMSSD = [HRV_METHODS.Baseline_RMSSD(baseRR)] * globals.scenario_num
listBaseSDNN = [HRV_METHODS.Baseline_SDNN(baseRR)] * globals.scenario_num
listBaseSDSD = [HRV_METHODS.Baseline_SDSD(baseRR)] * globals.scenario_num
listBasePNN50 = [HRV_METHODS.Baseline_PNN50(baseRR)] * globals.scenario_num
return listBaseBPM, listBasePNN50, listBaseRMSSD, listBaseSDNN, listBaseSDSD, listPNN50, listRMSSD, listSDNN, listSDSD
def filling_summary_table(avg_base, baseRR, listBPM, par, list_of_rr_flag, ride, group_list):
"""
Using function "list_hrv_methods"
and filling the summary table with the lists
using "append" to add all the lines for each participant
"""
listBaseBPM, listBasePNN50, listBaseRMSSD, listBaseSDNN, listBaseSDSD, listPNN50, listRMSSD, listSDNN, listSDSD = list_hrv_methods(
avg_base, baseRR, list_of_rr_flag)
globals.summary_table = globals.summary_table.append(
pandas.DataFrame({'Participant': [par] * globals.scenario_num,
'Ride Number': [ride] * globals.scenario_num,
'Scenario': list(range(1, globals.scenario_num + 1)),
'Group': group_list,
'Average BPM': listBPM, 'RMSSD': listRMSSD, 'SDSD': listSDSD,
'SDNN': listSDNN, 'PNN50': listPNN50, 'Baseline BPM': listBaseBPM,
'Baseline RMSSD': listBaseRMSSD, 'Baseline SDNN': listBaseSDNN,
'Baseline SDSD': listBaseSDSD, 'Baseline PNN50': listBasePNN50,
'Subtraction BPM': [round(abs(x - y), 4) for x, y in
zip(listBaseBPM, listBPM)],
'Subtraction RMSSD': [round(abs(x - y), 4) for x, y in
zip(listBaseRMSSD, listRMSSD)],
'Subtraction SDNN': [round(abs(x - y), 4) for x, y in
zip(listBaseSDNN, listSDNN)],
'Subtraction SDSD': [round(abs(x - y), 4) for x, y in
zip(listBaseSDSD, listSDSD)],
'Subtraction PNN50': [round(abs(x - y), 4) for x, y in
zip(listBasePNN50, listPNN50)]
}))
globals.summary_table.reset_index(drop=True, inplace=True) # reset the index after the append
def make_par_group_list(par):
"""
Create the "Group" column in the Summary_Table
"""
group_list = []
if globals.group_num == 0: # if there is no groups
group_list = [0] * globals.scenario_num # the "group" column in the summary table is filled by 0
else:
for group in range(globals.group_num):
if par in globals.lists_of_groups[group]: # if the participant is in the group
group_list = [group + 1] * globals.scenario_num # the group is "+1" becauseine the list : index 0=1, index 1=2...
break
return group_list
def calc_rr_num_of_rows_per_flag():
"""
Calculation the number of rows used to calculate HRV methods, per flag (scenario)
"""
list_count_rr_flag = [] # rr values count per flag - number of rows in RR file per flag
for i in range(1, len(globals.list_count_rr_intervals_flag)):
# add 1 to the interval to get the count of rr values - not rr intervals
if globals.list_count_rr_intervals_flag[i] != 0:
list_count_rr_flag.append(globals.list_count_rr_intervals_flag[i] + 1)
else:
list_count_rr_flag.append(0)
return list_count_rr_flag
def filling_dq_table(listBPM_per_scenario, par, ride, group_list):
"""
Using function "calc_rr_num_of_rows_per_flag"
and filling the data_quality_table with the lists
using "append" to add all the lines for each participant
"""
list_count_rr_flag = calc_rr_num_of_rows_per_flag()
globals.data_quality_table = \
globals.data_quality_table.append(pandas.DataFrame({'Participant': [par] * globals.scenario_num,
'Ride Number': [
ride] * globals.scenario_num,
'Scenario': list(
range(1, globals.scenario_num + 1)),
'Group': group_list,
"Start time (sec)": globals.list_start_time,
"End time (sec)": globals.list_end_time,
"Duration (sec)": [round(x - y, 4) for x, y in
zip(globals.list_end_time,
globals.list_start_time)],
"BPM(ecg) : Total number of rows": listBPM_per_scenario,
"BPM(ecg) : Number of empty rows": globals.list_null_bpm,
"BPM(ecg) : % Completeness": globals.list_completeness_bpm,
"BPM(ecg) : Minimum value": globals.list_min_bpm,
"BPM(ecg) : Maximum value": globals.list_max_bpm,
"BPM(ecg) : Median": globals.list_median_bpm,
"HRV methods(rr) : Total number of rows": list_count_rr_flag,
"HRV methods(rr) : Number of empty rows": globals.list_null_rr,
"HRV methods(rr) : % Completeness": globals.list_completeness_rr,
"HRV methods(rr) : Minimum value": globals.list_min_rr,
"HRV methods(rr) : Maximum value": globals.list_max_rr,
"HRV methods(rr) : Median": globals.list_median_rr
}))
globals.data_quality_table.reset_index(drop=True, inplace=True) # reset the index after the append
def early_process_rr(index_in_folder, ride):
"""
Loading the RR files, arranging the columns: TIME, RRIntervals and Scenario
"""
parRR = pandas.read_excel(os.path.join(globals.main_path + "\\" + "ride " + str(ride) + "\\" + "rr",
os.listdir(
globals.main_path + "\\" + "ride " + str(
ride) + "\\" + "rr")[
index_in_folder]),
names=['RRIntervals'], skiprows=4, skipfooter=8, header=None,
engine='openpyxl')
parRR['RRIntervals'] = [round(x, 3) for x in parRR['RRIntervals']]
parRR.insert(1, 'Time', [0.00 for x in range(0, (len(parRR)))],
True) # insert Time column with zero
parRR.insert(2, 'Scenario', [0 for x in range(0, (len(parRR)))],
True) # insert Scenario column with zero
# Creates a list of lists as the number of scenarios
list_of_rr_flag = [[] for i in range(globals.scenario_num + 1)]
return parRR, list_of_rr_flag
def sync_RR(parRR):
"""
Synchronize RR files. Lower the amount of seconds entered as input from these files
to reset them in front of the simulator.
"""
pandas.options.mode.chained_assignment = None # So as not to give a warning that I am overwriting the original file
parRR = parRR[parRR['Time'] >= globals.biopac_sync_time] # leave only the lines that bigger then sync time
parRR.reset_index(drop=True, inplace=True)
parRR['Time'] = [round(x - globals.biopac_sync_time, 3) for x in parRR['Time']] # Subtract the seconds from the remaining rows
return parRR
def dq_completeness_bpm(listBPM_per_scenario):
"""
Calculation of the percentage of data integrity in ECG file:
the total number of rows less the number of empty rows divided by the total number of rows - multiplied by 100.
"""
for i in range(globals.scenario_num):
if listBPM_per_scenario[i] == 0:
globals.list_completeness_bpm[i] = 0
else:
globals.list_completeness_bpm[i] = \
round(((listBPM_per_scenario[i] - globals.list_null_bpm[i]) / listBPM_per_scenario[i]) * 100, 2)
def dq_completeness_rr():
"""
Calculation of the percentage of data integrity in RR file:
the total number of rows less the number of empty rows divided by the total number of rows - multiplied by 100.
"""
for i in range(globals.scenario_num):
if globals.list_count_rr_intervals_flag[i + 1] == 0:
globals.list_completeness_rr[i] = 0
else:
globals.list_completeness_rr[i] = \
round(
((globals.list_count_rr_intervals_flag[i + 1] - globals.list_null_bpm[i]) / globals.list_count_rr_intervals_flag[
i + 1]) * 100,
2)
def avg_med_bpm(list_of_bpm_flag):
"""
Calculate the mean and median from the ECG files.
"""
listBPM = [] # list of Average BPM by scenario
listBPM_per_scenario = []
for i in range(1, globals.scenario_num + 1):
if len(list_of_bpm_flag[i]) != 0:
listBPM.append(sum(list_of_bpm_flag[i]) / len(list_of_bpm_flag[i]))
globals.list_median_bpm[i - 1] = round(np.median(list_of_bpm_flag[i]), 4)
else:
listBPM.append(0)
globals.list_median_bpm[i - 1] = 0
listBPM_per_scenario.append(len(list_of_bpm_flag[i]))
return listBPM, listBPM_per_scenario
def med_rr(list_of_rr_flag):
"""
Calculate the median from the RR files.
"""
for i in range(1, globals.scenario_num + 1):
if len(list_of_rr_flag[i]) != 0:
globals.list_median_rr[i - 1] = round(np.median(list_of_rr_flag[i]), 4)
else:
globals.list_median_rr[i - 1] = 0
def early_process_ecg_sim(index_in_folder, ride):
"""
File upload: ECG and SIM.
Arrange the columns in these files.
If synchronization has taken place -
ignore the relevant lines (1000 per sec or 60 per sec):
ECG: skiprows = 11 + int(globals.biopac_sync_time * 1000)
sim: skiprows = 1 + int(globals.sim_sync_time * 60)
and subtract the seconds from each remaining line.
"""
globals.list_count_rr_intervals_flag = [0] * (
globals.scenario_num + 1) # Initialize the list to zero for each scenario
list_of_bpm_flag = [[] for i in
range(
globals.scenario_num + 1)] # Creates a list of lists as the number of scenarios
parECG = pandas.read_csv(os.path.join(globals.main_path + "\\" + "ride " + str(ride) + "\\" + "ecg",
os.listdir(
globals.main_path + "\\" + "ride " + str(
ride) + "\\" + "ecg")[
index_in_folder]),
sep="\t", usecols=[2], names=['BPM'],
skiprows=11 + int(globals.biopac_sync_time * 1000), header=None)
parECG.insert(1, 'Time', [x / 1000 for x in range(0, (len(parECG)))], True) # filling a time column - 0, 0.001, 0.002...
parSIM = pandas.read_csv(os.path.join(globals.main_path + "\\" + "ride " + str(ride) + "\\" + "sim",
os.listdir(
globals.main_path + "\\" + "ride " + str(
ride) + "\\" + "sim")[
index_in_folder]),
sep=",", skiprows=1 + int(globals.sim_sync_time * 60),
usecols=[0, globals.scenario_col_num - 1],
names=['Time', 'Scenario'])
if globals.sim_sync_time > 0: # Sync sim time
parSIM['Time'] = [round(x - globals.sim_sync_time, 4) for x in parSIM['Time']] # Subtract the seconds from each line to synchronize
else:
parSIM['Time'] = [round(x, 4) for x in parSIM['Time']]
parECG.insert(2, 'Scenario', [0 for x in range(0, (len(parECG)))],
True) # adding scenario column and filling with 0
return list_of_bpm_flag, parECG, parSIM
def early_process_base(index_in_folder):
"""
Loading the BASE files with column 'RRIntervals'
and calculate AVG BPM column.
"""
baseECG = pandas.read_csv(os.path.join(globals.main_path + "\\" + "base" + "\\" + "base ecg",
os.listdir(
globals.main_path + "\\" + "base" + "\\" + "base ecg")[
index_in_folder]),
sep="\t",
names=['BPM'], usecols=[2],
skiprows=11, header=None)
avg_base = np.average(baseECG) # avg for column BPM at baseECG
baseRR = pandas.read_excel(os.path.join(globals.main_path + "\\" + "base" + "\\" + "base rr",
os.listdir(
globals.main_path + "\\" + "base" + "\\" + "base rr")[
index_in_folder]),
names=['RRIntervals'], skiprows=4, skipfooter=8, header=None,
engine='openpyxl')
return avg_base, baseRR, baseECG
def initial_data_quality():
"""
Initialize values for the lists that calculate the data quality table's columns.
"""
globals.list_start_time = [0] * globals.scenario_num
globals.list_end_time = [0] * globals.scenario_num
globals.list_min_bpm = [1000] * globals.scenario_num
globals.list_max_bpm = [0] * globals.scenario_num
globals.list_null_bpm = [0] * globals.scenario_num
globals.list_completeness_bpm = [0] * globals.scenario_num
globals.list_median_bpm = [0] * globals.scenario_num
globals.list_min_rr = [100] * globals.scenario_num
globals.list_max_rr = [0] * globals.scenario_num
globals.list_null_rr = [0] * globals.scenario_num
globals.list_completeness_rr = [0] * globals.scenario_num
globals.list_median_rr = [0] * globals.scenario_num
|
Java
|
UTF-8
| 1,727 | 2 | 2 |
[] |
no_license
|
package com.qingboat.as.dao;
import com.qingboat.as.entity.ReadonEntity;
import com.qingboat.as.vo.ReadOnVo;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface ReadOnDao {
@Insert("insert into apps_readon (user_id,content_type,content_id,creator_id,height,create_at,updated_at,pathway_id) " +
"values(#{readEntity.userId},#{readEntity.contentType},#{readEntity.contentId},#{readEntity.creatorId},#{readEntity.height},NOW(),NOW(),#{readEntity.pathwayId})")
public Integer insertRecord(@Param("readEntity")ReadonEntity readonEntity);
@Select("select * from apps_readon where user_id = #{userId} and content_type = #{contentType} and content_id = #{contentId} and pathway_id = #{pathwayId}")
public ReadonEntity findRecordWithPathwayId(@Param("userId")Integer userId,@Param("contentType")Integer contentType,@Param("contentId")String contentId,@Param("pathwayId")Integer pathwayId);
@Select("select * from apps_readon where user_id = #{userId} and content_type = #{contentType} and content_id = #{contentId}")
public ReadonEntity findRecord(@Param("userId")Integer userId,@Param("contentType")Integer contentType,@Param("contentId")String contentId);
@Update("update apps_readon set height = #{readEntity.height} , updated_at = NOW() where user_id = #{readEntity.userId} and content_type = #{readEntity.contentType} and content_id = #{readEntity.contentId}")
public Integer updateRecord(@Param("readEntity")ReadonEntity readonEntity);
@Select("select * from apps_readon where user_id = #{userId} and height != 100 order by updated_at desc")
public List<ReadonEntity> selectAllReadOnListByUserId(@Param("userId")Integer userId);
}
|
PHP
|
UTF-8
| 421 | 2.6875 | 3 |
[] |
no_license
|
<?php
/**
* User: filway
* Email: filway@126.com
* Date: 2022/5/21
* Time: 00:20
*/
namespace Filway\Component;
trait Singleton
{
private static $instance;
/**
* @param mixed ...$args
* @return static
*/
static function getInstance(...$args)
{
if(!isset(static::$instance)){
static::$instance = new static(...$args);
}
return static::$instance;
}
}
|
Java
|
UTF-8
| 4,080 | 2.65625 | 3 |
[] |
no_license
|
package com.eyecall.server;
import java.io.IOException;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.eyecall.connection.Connection;
import com.eyecall.connection.Message;
import com.eyecall.database.Volunteer;
public class RequestPool {
private static final Logger logger = LoggerFactory.getLogger(RequestPool.class);
private static RequestPool instance;
private Map<String, Request> connections;
private RequestPool(){
this.connections = new ConcurrentHashMap<String, Request>();
}
public static RequestPool getInstance(){
if(instance == null){
instance = new RequestPool();
}
return instance;
}
public void tunnel(String id, Entity e, Message m){
logger.debug("tunneling message to {}: {}", e, m);
if(connections.containsKey(id)){
Request r = connections.get(id);
Connection c = null;
switch(e){
case VIP:
c = r.getVipConnection();
break;
case VOLUNTEER:
c = r.getVolunteerConnection();
break;
}
c.send(m);
}
}
@SuppressWarnings("unused")
public void tunnelUdp(String id, Entity e, Message m) throws IOException{
if(true) throw new UnsupportedOperationException("not yet implemented");
if(connections.containsKey(id)){
Request r = connections.get(id);
Connection c = null;
switch(e){
case VIP:
c = r.getVipConnection();
case VOLUNTEER:
c = r.getVolunteerConnection();
}
//c.sendUDP(m);
}
}
/**
* setup a request
* @param c Connection to VIP
* @return
*/
public Request setup(Connection c, String longitude, String latitude) {
try{
return setup(c, Double.valueOf(longitude), Double.valueOf(latitude));
}catch(NumberFormatException e){
return null;
}
}
/**
* setup a request
* @param c Connection to VIP
* @return
*/
public Request setup(Connection c, double longitude, double latitude) {
String id = new BigInteger(128, new SecureRandom()).toString(16);
logger.debug("setting up new request with id: {}", id);
Request r = new Request(id, c, longitude, latitude);
connections.put(id, r);
return r;
}
/**
* attach a volunteer to a request
* @param id
* @param c
*/
public Request attach(String id, Connection c){
logger.debug("attaching request with id {}...", id);
Request r = null;
if(connections.containsKey(id)){
logger.debug("request exists: {}", id);
r = connections.get(id);
if(!r.connected()){
logger.debug("successfully attached volunteer!");
r.setVolunteerConnection(c);
} else{
logger.debug("failed to attach volunteer");
}
} else{
logger.warn("no request exists with id {}", id);
}
return r;
}
public boolean isConnected(String id){
boolean isConnected = false;
if(!connections.containsKey(id)){
isConnected = connections.get(id).connected();
}
logger.debug("{} is connected: {}", id, isConnected);
return isConnected;
}
public boolean exists(String id){
logger.debug("{} exists: {}", id, connections.containsKey(id));
return connections.containsKey(id);
}
/**
* remove a request
* @param id
*/
public void remove(String id){
connections.remove(id);
}
/**
* Checks if the given volunteer is currently helping a VIP or is in the
* pendingVolunteers list of a request.
* @param volunteer
* @return false if volunteer is currently helping or is in the pendingVolunteers list, true otherwise.
*/
public boolean isFree(Volunteer volunteer) {
for(Request request : connections.values()){
if(request.getPendingVolunteers().contains(volunteer) || (request.getVolunteerId()!=null && request.getVolunteerId().equals(volunteer.getId()))){
return false;
}
}
return true;
}
public Request getPendingRequest(String volunteerId) {
Volunteer volunteer = new Volunteer(volunteerId);
for(Request request : connections.values()){
if(request.getPendingVolunteers().contains(volunteer)) return request;
}
return null;
}
}
|
TypeScript
|
UTF-8
| 13,187 | 2.515625 | 3 |
[] |
no_license
|
import Core from "../../core/Core";
import {CoreConfig} from "../../core/CoreConfig";
import {HookSkill} from "../skill/tickSkill/HookSkill";
import {SpeedUpSkill} from "../skill/tickSkill/SpeedUpSkill";
import {Unit} from "../common/Unit";
import {MoveToSkill} from "../skill/tickSkill/MoveToSkill";
import {BaseTicker} from "../../common/BaseTicker";
import {FloatNumHandler} from "../../common/FloatNumHandler";
import {FireAroundSkill} from "../skill/tickSkill/FireAroundSkill";
import {IceDartScatterSkill} from "../skill/commonSkill/IceDartScatterSkill";
import {IceWind} from "../skill/commonSkill/IceWindSkill";
import {FlashAwaySkill} from "../skill/tickSkill/FlashAwaySkill";
import {ThunderStrikeSkill} from "../skill/tickSkill/ThunderStrikeSkill";
import {AvatarSkill} from "../skill/tickSkill/AvatarSkill";
import {GalaxyVortexSkill} from "../skill/tickSkill/GalaxyVortexSkill";
import {UnitSkillMsg, UnitMoveMsg, UnitHPChangeMsg} from "../../common/message/EventMsg";
import {EventID} from "../../core/EventID";
/**准备被废弃的移动方案 */
export enum eMoveType
{
UP = 0,
DOWN = 1,
LEFT = 2,
Right = 3
}
export class ActionMgr
{
/**舞台,也是所有物体的父节点 */
private m_stCanvas: cc.Node;
/**MoveMgr */
private m_stMoveMgr: MoveMgr;
constructor()
{
this.Init();
}
private Init(): void
{
// 找到舞台
this.m_stCanvas = cc.find("Canvas");
this.m_stMoveMgr = new MoveMgr();
Core.TickMgr.AddTicker(this.m_stMoveMgr);
// 注册事件
this.BindEvent();
}
private BindEvent(): void
{
Core.EventMgr.BindEvent(EventID.UNIT_SKILL, this.OnUnitSkillHandler, this);
Core.EventMgr.BindEvent(EventID.UNIT_MOVE, this.OnUnitMoveHandler, this);
Core.EventMgr.BindEvent(EventID.UNIT_HP_CHANGE, this.OnUnitHPChangeHandler, this);
}
// /**
// * 英雄移动
// * @param heroID 英雄id
// * @param endPos 移动到的位置
// */
// public HeroMove(heroID: number, endPos: cc.Vec2)
// {
// this.m_stMoveMgr.UnitMove(heroID, endPos);
// }
// /**
// * 英雄移动
// * @param heroID 英雄id
// * @param moveType 方向类型
// */
// public HeroMove(heroID: number, moveType: eMoveType): void
// {
// let speed = this.GetUnitByID(heroID).Speed;
// let node = this.GetNodeByID(heroID);
// if(moveType == eMoveType.UP)
// {
// // node.position = node.position.add(new cc.Vec2(0, speed));
// let rot = node.rotation / 180 * Math.PI;
// let vec = new cc.Vec2(Math.sin(rot), Math.cos(rot));
// node.position = node.position.add(vec.mul(speed));
// }
// else if(moveType == eMoveType.DOWN)
// {
// // node.position = node.position.add(new cc.Vec2(0, -speed));
// let rot = node.rotation / 180 * Math.PI;
// let vec = new cc.Vec2(Math.sin(rot), Math.cos(rot));
// node.position = node.position.sub(vec.mul(speed));
// }
// else if(moveType == eMoveType.LEFT)
// {
// // node.position = node.position.add(new cc.Vec2(-speed, 0));
// node.rotation -= 5;
// }
// else if(moveType == eMoveType.Right)
// {
// // node.position = node.position.add(new cc.Vec2(speed, 0));
// node.rotation += 5;
// }
// }
// /**
// * 英雄释放技能
// * @param btnID 按钮的id
// * @param heroID 释放技能的英雄的id
// * @param skillID 技能的id
// * @param pos 技能释放的坐标点
// */
// public HeroSkill(btnID: number, heroID: number, skillID: number, pos?: cc.Vec2, clickUnitID?: number): void
// {
// if(heroID == CoreConfig.MY_HERO_ID)
// {
// // 使播放cd动画
// Core.GameLogic.SkillMgr.GoInCD(btnID);
// // 使恢复正常状态
// Core.GameLogic.SkillMgr.GoNormalState(btnID);
// }
// // 释放技能,停止之前的移动行为
// this.m_stMoveMgr.UnitUnMove(heroID);
// // 各个技能逻辑处理
// if(skillID == CoreConfig.SKILL_HOOK)
// {
// this.SkillHook(heroID, pos);
// }
// else if(skillID == CoreConfig.SKILL_SPEED_UP)
// {
// this.SkillSpeedUp(heroID);
// }
// else if(skillID == CoreConfig.SKILL_FIRE_AROUND)
// {
// this.SkillFireAround(heroID);
// }
// else if(skillID == CoreConfig.SKILL_ICE_DART_SCATTER)
// {
// this.SkillIceDartScatter(heroID, pos);
// }
// else if(skillID == CoreConfig.SKILL_ICE_WIND)
// {
// this.SkillIceWind(heroID);
// }
// else if(skillID == CoreConfig.SKILL_FLASH_AWAY)
// {
// this.SkillFlashAway(heroID, pos);
// }
// else if(skillID == CoreConfig.SKILL_THUNDER_STRIKE)
// {
// this.SkillThunderStrike(heroID, pos);
// }
// else if(skillID == CoreConfig.SKILL_AVATAR)
// {
// this.SkillAvatar(heroID);
// }
// else if(skillID == CoreConfig.SKILL_GALAXY_VORTEX)
// {
// this.SkillGalaxyVortex(heroID, clickUnitID);
// }
// else
// {
// console.log(heroID, "释放的技能为", skillID);
// }
// }
// /**
// * 让指定id的单位生命值发生变化
// * @param unitID 单位id
// * @param hpChange 生命值的变化,可正可负
// */
// public UnitHPChange(unitID: number, hpChange: number): void
// {
// let unit = Core.GameLogic.UnitMgr.GetUnitByID(unitID);
// unit.NowHP += hpChange;
// }
/**
* 处理单位释放技能的回调函数
*/
private OnUnitSkillHandler(data: UnitSkillMsg): void
{
let unitID = data.UnitID;
let btnID = data.BtnID;
let skillID = data.SkillID;
let pos = data.Pos;
let clickUnitID = data.ClickUnitID;
if(unitID == CoreConfig.MY_HERO_ID)
{
// 使播放cd动画
Core.GameLogic.SkillMgr.GoInCD(btnID);
// 使恢复正常状态
Core.GameLogic.SkillMgr.GoNormalState(btnID);
}
// 释放技能,停止之前的移动行为
this.m_stMoveMgr.UnitUnMove(unitID);
// 各个技能逻辑处理
if(skillID == CoreConfig.SKILL_HOOK)
{
this.SkillHook(unitID, pos);
}
else if(skillID == CoreConfig.SKILL_SPEED_UP)
{
this.SkillSpeedUp(unitID);
}
else if(skillID == CoreConfig.SKILL_FIRE_AROUND)
{
this.SkillFireAround(unitID);
}
else if(skillID == CoreConfig.SKILL_ICE_DART_SCATTER)
{
this.SkillIceDartScatter(unitID, pos);
}
else if(skillID == CoreConfig.SKILL_ICE_WIND)
{
this.SkillIceWind(unitID);
}
else if(skillID == CoreConfig.SKILL_FLASH_AWAY)
{
this.SkillFlashAway(unitID, pos);
}
else if(skillID == CoreConfig.SKILL_THUNDER_STRIKE)
{
this.SkillThunderStrike(unitID, pos);
}
else if(skillID == CoreConfig.SKILL_AVATAR)
{
this.SkillAvatar(unitID);
}
else if(skillID == CoreConfig.SKILL_GALAXY_VORTEX)
{
this.SkillGalaxyVortex(unitID, clickUnitID);
}
else
{
console.log(unitID, "释放的技能为", skillID);
}
}
/**
* 处理单位移动的回调函数
*/
private OnUnitMoveHandler(data: UnitMoveMsg): void
{
let unitID = data.UnitID;
let pos = data.Pos;
this.m_stMoveMgr.UnitMove(unitID, pos);
}
/**
* 处理单位生命值变化的回调函数
*/
private OnUnitHPChangeHandler(data: UnitHPChangeMsg): void
{
let unitID = data.UnitID;
let hpChange = data.HPChange;
let unit = Core.GameLogic.UnitMgr.GetUnitByID(unitID);
unit.NowHP += hpChange;
}
/**
* 钩子技能
*/
private SkillHook(heroID: number, pos: cc.Vec2): void
{
let hero = this.GetNodeByID(heroID);
let skillPos = hero.position; // 释放技能者的位置
let vec = pos.sub(skillPos).normalize();
let ticker = new HookSkill(this.GetUnitByID(heroID), skillPos, vec);
Core.TickMgr.AddTicker(ticker);
}
/**
* 冰箭散射技能
*/
private SkillIceDartScatter(unitID: number, pos: cc.Vec2): void
{
let unit = this.GetUnitByID(unitID);
let skillPos = unit.GetNode().position; // 释放技能者的位置
let vec = pos.sub(skillPos).normalize();
new IceDartScatterSkill(unit, vec);
}
/**
* 灼烧技能
*/
private SkillFireAround(unitID: number): void
{
let ticker = new FireAroundSkill(this.GetUnitByID(unitID));
Core.TickMgr.AddTicker(ticker);
}
/**加速技能 */
private SkillSpeedUp(heroID: number): void
{
let unit = this.GetUnitByID(heroID);
let ticker = new SpeedUpSkill(unit);
Core.TickMgr.AddTicker(ticker);
}
/**闪现技能 */
private SkillFlashAway(heroID: number, pos: cc.Vec2): void
{
let ticker = new FlashAwaySkill(this.GetUnitByID(heroID), pos);
Core.TickMgr.AddTicker(ticker);
}
/**雷霆一击技能 */
private SkillThunderStrike(heroID: number, pos: cc.Vec2): void
{
let ticker = new ThunderStrikeSkill(this.GetUnitByID(heroID), pos);
Core.TickMgr.AddTicker(ticker);
}
/**罡风护体技能 */
private SkillIceWind(heroID: number): void
{
let iceWind = new IceWind(this.GetUnitByID(heroID));
}
/**天神下凡技能 */
private SkillAvatar(heroID: number): void
{
let ticker = new AvatarSkill(this.GetUnitByID(heroID));
Core.TickMgr.AddTicker(ticker);
}
/**星河涡流技能 */
private SkillGalaxyVortex(heroID: number, clickUnitID: number): void
{
let ticker = new GalaxyVortexSkill(this.GetUnitByID(heroID), this.GetUnitByID(clickUnitID));
Core.TickMgr.AddTicker(ticker);
}
private GetNodeByID(unitID: number): cc.Node
{
let unit = Core.GameLogic.UnitMgr.GetUnitByID(unitID);
return unit.GetNode();
}
private GetUnitByID(unitID: number): Unit
{
return Core.GameLogic.UnitMgr.GetUnitByID(unitID);
}
}
// 隶属于ActionMgr的管理类
class MoveMgr implements BaseTicker
{
private m_mapMoveUnits: Map<number, cc.Vec2>;
constructor()
{
this.Init();
}
private Init(): void
{
this.m_mapMoveUnits = new Map<number, cc.Vec2>();
}
/**
* 单位向某个位置移动的指令
* @param unitID 单位id
* @param moveTo 移动到的位置
*/
public UnitMove(unitID: number, moveTo: cc.Vec2): void
{
this.m_mapMoveUnits.set(unitID, moveTo);
}
/**
* 撤销某个单位的移动指令
* @param unitID 单位id
*/
public UnitUnMove(unitID: number): void
{
if(this.m_mapMoveUnits.has(unitID))
{
this.m_mapMoveUnits.delete(unitID);
}
}
Update(): void
{
let removeArray = new Array<number>();
this.m_mapMoveUnits.forEach((moveTo: cc.Vec2, unitID: number) =>
{
let unit = Core.GameLogic.UnitMgr.GetUnitByID(unitID);
let node = unit.GetNode();
let dis = node.position.sub(moveTo).mag();
dis = FloatNumHandler.PreservedTo(dis);
// 改变朝向
if(dis > 0.0)
{
node.rotation = this.CalcAngle(moveTo.sub(node.position));
}
else
{
removeArray.push(unitID);
return;
}
// 做出位移
if(dis <= unit.Speed)
{
node.position = moveTo;
}
else
{
node.position = node.position.add(moveTo.sub(node.position).normalize().mul(unit.Speed));
}
});
for(let unitID of removeArray)
{
this.UnitUnMove(unitID);
}
}
IsFinished(): boolean
{
return false;
}
Clear(): void
{
}
/**
* 计算从vec(0,1.0)顺时针旋转到vec之间的角度
* @param vec 向量vec2
*/
private CalcAngle(vec: cc.Vec2): number
{
let angle: number;
let temp = new cc.Vec2(0, 1.0);
angle = vec.dot(temp) / (vec.mag() * temp.mag());
angle = Math.acos(angle) * 180 / Math.PI;
if(vec.x < 0)
{
angle = 360 - angle;
}
return angle;
}
}
|
Go
|
UTF-8
| 1,549 | 3.265625 | 3 |
[
"MIT"
] |
permissive
|
type sum struct {
i, j, val int
}
type MinValHeap []sum
func (a MinValHeap) Len() int { return len(a) }
func (a MinValHeap) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a MinValHeap) Less(i, j int) bool { return a[i].val < a[j].val }
func (a *MinValHeap) Push(v interface{}) {
*a = append(*a, v.(sum))
}
func (a *MinValHeap) Pop() interface{} {
old := *a
n := len(old)
v := old[n-1]
*a = old[0:n-1]
return v
}
func min(a, b int) int {
if a < b {
return a
} else {
return b
}
}
func kSmallestPairs(nums1 []int, nums2 []int, k int) [][]int {
isSwap := false
if len(nums1) > len(nums2) {
nums1, nums2 = nums2, nums1
isSwap = true
}
n1, n2 := len(nums1), len(nums2)
if n1 == 0 || n2 == 0 {
return [][]int{}
}
heapSize := min(n1, k)
sumHeap := make(MinValHeap, 0, heapSize)
// fmt.Println("n1", n1, "n2", n2, "k", k)
for i := 0; i < heapSize; i++ {
heap.Push(&sumHeap, sum{i, 0, nums1[i]+nums2[0]})
}
var result [][]int
for k > 0 && sumHeap.Len() > 0 {
current := heap.Pop(&sumHeap).(sum)
if isSwap {
result = append(result, []int{nums2[current.j], nums1[current.i]})
} else {
result = append(result, []int{nums1[current.i], nums2[current.j]})
}
if current.j++; current.j < n2 {
heap.Push(&sumHeap, sum{current.i, current.j, nums1[current.i]+nums2[current.j]})
}
k--
}
return result
}
|
Markdown
|
UTF-8
| 7,031 | 3.140625 | 3 |
[] |
no_license
|
## Filter
- 테스트 조건을 만족하는 항목들만 배출
> Observavle 변형할때 사용
- Map : 전달받은 이벤트를 다른 값으로 변경
```java
public void doMap() {
observable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.filter( item -> item.equals("May")?false:true)
.map( item -> ">> "+item+"")
.subscribe(
item -> {
data.add(item);
adapter.notifyItemInserted(data.size()-1);
},
error -> Log.e("Error",error.getMessage()),
() -> Log.i("Complete","Successfully completed!")
);
}
```
- FlatMap : 하나의 Observavle이 발행하는 항목들을 여러개의 Observavle로 변환, 항목들의 배출을 차례차례 줄 세워 하나의 Observavle로 전달
```java
public void doFmap() {
observable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.flatMap(item -> Observable.fromArray(new String[]{"name:"+months[item], "code:"+item}))
.subscribe(
item -> {
data.add(item);
adapter.notifyItemInserted(data.size()-1);
},
error -> Log.e("Error",error.getMessage()),
() -> Log.i("Complete","Successfully completed!")
);
}
```
- Zip : 네트워크 작업으로 사용자의 프로필과 프로필 이미지를 동시에 요청, 그 결과를 합성해서 화면에 표현해준다거나하는 형태의 작업이 필요한 경우 사용
```java
observableZip = Observable.zip(
Observable.just("daJung","iJune"),
Observable.just("girl","boy"),
(item1, item2) -> "name:"+item1+", gender:"+item2
);
public void doZip() {
observableZip
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
item -> {
data.add(item+"");
adapter.notifyItemInserted(data.size()-1);
},
error -> Log.e("Error",error.getMessage()),
() -> Log.i("Complete","Successfully completed!")
);
}
```
## Subject
- 하나 이상의 Observable을 구독할 수 있으며 동시에 Observable이기도 하기 때문에 항목들을 하나 하나 거치면서 재배출하고 관찰하며 새로운 항목들을 배출
- publish
```java
/*
구독 시점부터 발행한 데이터 읽을 수 있음
*/
PublishSubject<String> publishSubject = PublishSubject.create(); // 발행 준비
public void doPublish(View view){
new Thread(){
public void run(){
for(int i = 0; i<10; i++) {
publishSubject.onNext("a" + i); // 발행
Log.i("publish", "a" + i);
try {
Thread.sleep(1000); // 1초씩 텀을두고 발행
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
public void getPublish (View view){
//구독
publishSubject.subscribe(
item -> Log.i("publish","item="+item)
);
}
```
- behavior
```java
/*
가장 마지막에 발행한 데이터부터 읽을 수 있음 (바로 이전에 읽은거까지)
*/
BehaviorSubject<String> behaviorSubject = BehaviorSubject.create(); // 발행 준비
public void doBehavior(View view){
new Thread(){
public void run(){
for(int i = 0; i<10; i++) {
behaviorSubject.onNext("b" + i); // 발행
Log.i("behavior", "b" + i);
try {
Thread.sleep(1000); // 1초씩 텀을두고 발행
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
public void getBehavior(View view){
//구독
behaviorSubject.subscribe(
item -> Log.i("behavior","item="+item)
);
}
```
- replay
```java
/*
처음 발행한 데이터부터 읽을 수 있음
*/
ReplaySubject<String> replaySubject = ReplaySubject.create(); // 발행 준비
public void doReplay(View view){
new Thread(){
public void run(){
for(int i = 0; i<10; i++) {
replaySubject.onNext("c" + i); // 발행
Log.i("replay", "c" + i);
try {
Thread.sleep(1000); // 1초씩 텀을두고 발행
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
public void getReplay(View view){
//구독
replaySubject.subscribe(
item -> Log.i("replay","item="+item)
);
}
```
- async
```java
/*
완료된 시점에서 마지막 데이터만 읽을 수 있음
*/
AsyncSubject<String> asyncSubject = AsyncSubject.create(); // 발행 준비
public void doAsync(View view){
new Thread(){
public void run() {
for (int i = 0; i < 10; i++) {
asyncSubject.onNext("d" + i); // 발행
Log.i("async", "d" + i);
try {
Thread.sleep(1000); // 1초씩 텀을두고 발행
} catch (InterruptedException e) {
e.printStackTrace();
}
}
asyncSubject.onComplete();
}
}.start();
}
public void getAsync(View view){
//구독
asyncSubject.subscribe(
item -> Log.i("async","item="+item)
);
}
```
## RxBinding
> 사용 시 추가
```java
implementation 'com.jakewharton.rxbinding2:rxbinding-appcompat-v7:2.+'
```
- textChangeEvents
```java
// 텍스트의 변경사항을 체크
RxTextView.textChangeEvents((TextView) findViewById(R.id.editText))
.subscribe(
item -> Log.i("word", "item" + item.text().toString()) // 텍스트로 변환
);
```
- clicks
: setOnClickListener를 통해 OnClickListener에 전달될 이벤트를 옵저버블 형태로 래핑 -> 간단한 click event 구현 가능
```java
RxView.clicks(findViewById(R.id.btnRandom))
.map(event -> new Random().nextInt()) // 랜덤 값으로 구현
.subscribe(
number -> textView.setText("number" + number)
);
```
|
Java
|
UTF-8
| 208 | 1.625 | 2 |
[] |
no_license
|
package in.bananaa.pass.helper.exception;
public class BusinessNoRollbackException extends BusinessException {
private static final long serialVersionUID = 1L;
public BusinessNoRollbackException() {
}
}
|
C++
|
UTF-8
| 595 | 3.125 | 3 |
[] |
no_license
|
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
cout << "writing to the file" ;
ofstream fout;
ifstream fin;
fout.open("Task 2", ios::out);
int age; char name[15];
cout << "Enter your name: ";
cin >> name;
cout << endl;
cout << "Enter your age: ";
cin >> age; cout << endl;
if (fout) {
fout << name << endl;
fout << age << endl;
}
else
cout << "error";
fout.close();
fin.open("Task 2", ios::in);
int Rage; char Rname[15];
if (fin) {
fin >> Rname;
fin >> Rage;
}
cout << "The name is : " << Rname << endl;
cout << "The age is : " << Rage;
}
|
C++
|
UTF-8
| 1,616 | 2.984375 | 3 |
[] |
no_license
|
#include <stdio.h>
int main (){
int n;
bool cs = true;
while (cs){
do {
printf("Vui long chon chuc nang:\n");
printf("1.Goi mon an\n");
printf("2.Goi do uong\n");
printf("3.Tinh tien\n");
printf("4.Thoat chuong trinh\n");
scanf("%d",&n);
}while (n>4||n<1);
switch (n){
case 1:
{
int choose;
bool cs1 = true;
while (cs1){
do {
printf ("Chon mon\n");
printf (" 1 . Bo\n");
printf (" 2 . Ga\n");
printf (" 3 . Vit\n");
printf (" 4 . Quay lai\n");
scanf ("%d", &choose);
}while (choose > 4 || choose < 1);
switch (choose){
case 1: printf ("Khach hang vua chon mon Bo\n"); break;
case 2: printf ("Khach hang vua chon mon Ga\n"); break;
case 3: printf ("Khach hang vua chon mon Vit\n");break;
case 4: cs1 = false; break;
}
}
break;
}
case 2:
{
int choose2;
bool cs2 = true;
while (cs2){
do {
printf ("Chon do uong\n");
printf (" 1 . Bia\n");
printf (" 2 . Ruou\n");
printf (" 3 . Nuoc ngot\n");
printf (" 4 . Quay lai\n");
scanf ("%d", &choose2);
}while (choose2 > 4 || choose2 < 1);
switch (choose2){
case 1: printf ("Khach hang vua goi Bia\n"); break;
case 2: printf ("Khach hang vua goi Ruou\n"); break;
case 3: printf ("Khach hang vua goi Nuoc ngot\n");break;
case 4: cs2 = false; break;
}
}
break;
}
case 3:
{
printf ("Tinh tien\n");
break;
}
case 4:
{
cs = false;
break;
}
}
}
return 0;
}
|
Java
|
UTF-8
| 1,180 | 1.875 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2017-2021 original authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.micronaut.http.server.exceptions.response;
import java.util.Optional;
/**
* Contains information about an error that occurred.
*
* @author James Kleeh
* @since 2.4.0
*/
public interface Error {
/**
* @return The optional error path
*/
default Optional<String> getPath() {
return Optional.empty();
}
/**
* @return The error message
*/
String getMessage();
/**
* @return An optional short description for the error
*/
default Optional<String> getTitle() {
return Optional.empty();
}
}
|
JavaScript
|
UTF-8
| 5,969 | 2.640625 | 3 |
[] |
no_license
|
/**
* loadJSON Ejecuta una llamada asíncrona dependiendo del entorno para obtener el cursoJSON
* @param function callback Función de callback del ajax.
* @return boolean False en caso de que no haya callback.
*/
function loadJSON(callback) {
if (!callback && typeof callback === 'undefined') {
return false;
}
var isBlink = (window.location.href.indexOf("blinklearning.com") > -1);
if (isBlink) { //online
blink.getCourse(window.idcurso).done(callback);
} else { //local
var url = window.location.href.replace("curso2", "curso_json");
if (offline) {
if (url.indexOf("curso_json") > -1) {
url = removeParams(['idtema', 'idalumno'], url);
}
}
$.ajax({
url: url,
dataType: 'json',
beforeSend: function (xhr) {
if (xhr.overrideMimeType) xhr.overrideMimeType("application/json");
},
success: callback
});
}
}
// ████░██▄░▄██░████░████░████▄░██▄░██░░▄███▄░░██░░
// ██▄░░░▀███▀░░░██░░██▄░░██░██░███▄██░██▀░▀██░██░░
// ██▀░░░▄███▄░░░██░░██▀░░████▀░██▀███░███████░██░░
// ████░██▀░▀██░░██░░████░██░██░██░░██░██░░░██░████
var sekApp = window.sekApp || {};
sekApp.courseData = '';
sekApp.tags = {
home : 'home',
unithead : 'unit_head'
}
sekApp.getCourseData = function() {
loadJSON(function(json) {
sekApp.courseData = json;
sekApp.init();
});
}
sekApp.getTocInfo = function() {
var data = sekApp.courseData;
$.each(data.units, function(i, unit) {
var unitTitle = unit.title,
unitDescription = unit.description,
unitId = unit.id,
unitTags = unit.tags,
unitTagsArray = (typeof unitTags !== 'undefined') ? unitTags.split(" ") : [];
var $currentListUnit = $('#list-units li[data-id="'+unitId+'"], .col-main [data-id="'+unitId+'"]');
var $currentListUnitTOC = $('#list-units li[data-id="'+unitId+'"]');
if (unitTagsArray.length) {
if (unitTagsArray.indexOf(sekApp.tags.home) >= 0 ) {
$currentUnit.addClass('sek-toc-home sek-toc-home-content');
$currentListUnit.addClass('sek-toc-home');
}
if (unitTagsArray.indexOf(sekApp.tags.unithead) >= 0 ) {
$currentListUnit.addClass('sek-toc-unithead');
if ($currentListUnit.prevAll('li').first().hasClass('sek-toc-unithead')) {
$currentListUnit.prevAll('li').first().addClass('sek-toc-unithead_empty');
}
if (!$currentListUnit.nextAll('li').length) {
$currentListUnit.addClass('sek-toc-unithead_empty');
}
//Add button
$currentListUnitTOC.append('<button class="sek-toc-unithead-button"></button>');
}
}
});
var $current = $('#list-units .litema.active');
$current.addClass('sek-toc-active').nextUntil('.sek-toc-unithead', 'li').addClass('sek-toc-subunit-active');
if (!$current.hasClass('sek-toc-unithead')){
$current
.addClass('sek-toc-subunit-active')
.prevUntil('.sek-toc-unithead', 'li')
.addClass('sek-toc-subunit-active')
.end()
.prevAll('.sek-toc-unithead')
.first()
.addClass('sek-toc-unithead-ancestor');
} else {
$current.addClass('sek-toc-unithead-ancestor');
}
if (!$('#list-units li.sek-toc-unithead').length) {
$('#list-units li').addClass('sek-toc-subunit-active sek-toc-subunit-woparent');
}
if ($('#list-units li.sek-toc-unithead').first().prevAll('li:not(.sek-toc-home)').length) {
$('#list-units li.sek-toc-unithead').first().prevAll('li:not(.sek-toc-home)').addClass('sek-toc-subunit-active sek-toc-subunit-woparent');
}
}
// INIT
sekApp.init = function() {
if ($('body').hasClass('edit')) return;
sekApp.getTocInfo();
}
$(document).ready(function() {
sekApp.getCourseData();
$('body').on('click', '#list-units .sek-toc-unithead-button', function(e) {
var $parent = $(this).parent('.js-indice-tema');
var $sublevels = $parent.nextUntil('.sek-toc-unithead', 'li');
if ($parent.hasClass('sek-toc-active') || $parent.hasClass('sek-toc-unithead-ancestor')) {
$parent.removeClass('sek-toc-active sek-toc-unithead-ancestor');
$sublevels.removeClass('sek-toc-subunit-active');
} else {
$parent.addClass('sek-toc-unithead-ancestor').siblings('li').removeClass('sek-toc-active sek-toc-unithead-ancestor sek-toc-subunit-active sek-toc-unithead-ancestor-active');
$sublevels.addClass('sek-toc-subunit-active');
}
$parent
.parent()
.children('li.active:not(.sek-toc-unithead):not(.sek-toc-unithead-ancestor)')
.prevAll('.sek-toc-unithead', 'li')
.first()
.addClass('sek-toc-unithead-ancestor-active');
e.stopPropagation();
});
$('body').on('click', '#list-units .js-indice-tema', function() {
if ($(this).hasClass('sek-toc-unithead') && !$(this).hasClass('sek-toc-unithead-ancestor')) {
$(this)
.siblings('li')
.removeClass('sek-toc-subunit-active')
.siblings('li.sek-toc-unithead')
.removeClass('sek-toc-open sek-toc-unithead-ancestor sek-toc-unithead-ancestor-active');
} else if ($(this).hasClass('sek-toc-unithead') && $(this).hasClass('sek-toc-unithead-ancestor')) {
$(this)
.siblings('li.sek-toc-unithead')
.removeClass('sek-toc-unithead-ancestor-active');
} else if (!$(this).hasClass('sek-toc-unithead')) {
$(this)
.prevAll('.sek-toc-unithead', 'li')
.first()
.addClass('sek-toc-unithead-ancestor-active')
.end()
.siblings('li')
.removeClass('sek-toc-unithead-ancestor-active');
}
});
});
|
C++
|
UTF-8
| 525 | 2.59375 | 3 |
[] |
no_license
|
//
// main.cpp
// boj_n2133
//https://www.acmicpc.net/problem/2133
// Created by Sujin Han on 2018. 6. 15..
// Copyright © 2018년 ddudini. All rights reserved.
//
#include <iostream>
using namespace std;
int main(int argc, const char * argv[]) {
int n;
cin >> n;
int dp[30];
dp[0] = 1;
dp[1] = 0;
dp[2] = 3;
for(int i = 3; i <= n ; i++){
dp[i] = dp[i-2]*3;
for(int j = i-4; j >=0 ; j-=2){
dp[i] += 2*dp[j];
}
}
cout << dp[n];
return 0;
}
|
Python
|
UTF-8
| 934 | 3.03125 | 3 |
[] |
no_license
|
#!/usr/bin/python
import sys
import json
import requests
def parse_json(json_object):
parsed_json = json.loads(json_object)
periods = parsed_json['properties']['periods']
count = len(periods)
count -= 1
while count > -1:
#print count
print str(periods[count])
count -= 1
return count
def main():
####################
# Define variables #
####################
url = "https://api.weather.gov/gridpoints/FFC/51,87/forecast/hourly"
#################
# Make API call #
#################
r = requests.get(url)
###############
# Get results #
###############
json_object = r.content
api_status = r.status_code
api_url = r.url
#################
# Print results #
#################
print api_url
print api_status
result = parse_json(json_object)
#print result
if __name__=="__main__":
sys.exit(main())
|
Ruby
|
UTF-8
| 1,552 | 2.59375 | 3 |
[] |
no_license
|
require "thor"
require "yaml"
require "bulk_publisher/version"
class BulkPublisher::Runner < Thor
$0 = "BulkPublisher - #{::BulkPublisher::Version::STRING}"
desc "start", "Run the bulk_publisher"
option :daemonize, type: :boolean, aliases: '-d', desc: "Running as a daemon"
option :message_count, type: :numeric, aliases: '-m', desc: "message count that number of per thread"
option :connection_count, default: 5, type: :numeric, aliases: '-c', desc: "connection count"
option :pid_file, type: :string, aliases: '-P', desc: "pid file name."
def start
puts "Starting bulk_publisher process."
params = get_params( options )
BulkPublisher::Pid.file = options["pid_file"]
BulkPublisher::Daemon.new(params).start
rescue Interrupt #Ctrl+c の処理
BulkPublisher::Daemon.new(params).stop
end
private
def get_params( options )
@params ||= {}
BulkPublisher::OPTIOM_KEYS.each { |key|
set_param!( hash: @params, key: key )
}
#環境変数から取得する際にtrue/falseが文字列になるので変換
case @params["ssl"]
when "true"; @params["ssl"] = true
when "false"; @params["ssl"] = false
end
if options
@params["connection_count"] = options["connection_count"]
@params["message_count"] = options["message_count"]
end
@params
end
def set_param!( hash:, key: )
env_key = BulkPublisher::ENVIRONMENT[key]
hash[key] = ENV[env_key] if env_key
hash
end
end
|
Python
|
UTF-8
| 1,298 | 2.890625 | 3 |
[] |
no_license
|
import pygame
import sys
import src.controllers.views.viewinfo as vi
import src.controllers.entity_handlers as eh
import src.controllers.tile_handlers as th
import src.controllers.gui_handlers as gh
# main game surface
surface = pygame.display.set_mode(
(vi.window_size_in_units[0]*vi.unit_size[0],
vi.window_size_in_units[1]*vi.unit_size[0]),
pygame.RESIZABLE)
# set app name
pygame.display.set_caption('Cool Game')
# manages tme between screen updates
clock = pygame.time.Clock()
# main game loop
while True:
clock.tick(17)
# list of events (keyboard / mouse presses)
for event in pygame.event.get():
# if QUIT (X pressed) -> close the app
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.VIDEORESIZE:
vi.adjust(event.w, event.h)
surface = pygame.display.set_mode((event.w, event.h), pygame.RESIZABLE)
# "clears" the screen by filling it with background color
surface.fill((0, 0, 0))
# handles all active tiles
th.handle_all()
# handles all active entities
eh.handle_all()
# handles all gui components
gh.handle_all()
# draws usable window space
vi.draw_usable(surface)
# draws current game state on display
pygame.display.update()
|
C++
|
GB18030
| 666 | 3.109375 | 3 |
[] |
no_license
|
#include<iostream>
#include<list>
using namespace std;
void TestListIterator1()
{
int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
list<int> l(array, array + sizeof(array) / sizeof(array[0]));
auto it = l.begin();
while (it != l.end())
{
// erase()ִкitָĽڵѱɾitЧһʹitʱȸ丳
l.erase(it);
++it;
}
}
//
void TestListIterator()
{
int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
list<int> l(array, array + sizeof(array) / sizeof(array[0]));
auto it = l.begin();
while (it != l.end())
{
it = l.erase(it);
}
}
int main()
{
TestListIterator();
return 0;
}
|
Java
|
UTF-8
| 1,590 | 2.859375 | 3 |
[] |
no_license
|
package language;
import lombok.Getter;
import process.parser.KeywordMatchStrategy;
import process.parser.StringTree;
import util.Token;
import util.Word;
import java.util.*;
public abstract class Language {
@Getter protected Map<Token, List<String>> tokenMap;
@Getter protected Map<Word, String> wordMap;
@Getter protected Map<String, List<Token>> keywordMap = new LinkedHashMap<>();
@Getter protected StringTree keywordTree;
protected abstract Map<Token, List<String>> createToken();
protected abstract Map<Word, String> createWords();
public abstract String getArticle(String label, Article article_type);
public Language() {
this.createWords();
this.createToken();
this.createKeyword();
this.keywordTree = new StringTree(keywordMap.keySet());
this.keywordTree.setNodeMatchStrategy(new KeywordMatchStrategy(this));
}
private void createKeyword() {
for (Map.Entry<Token, List<String>> t : this.tokenMap.entrySet()) {
for (String string : t.getValue()) {
if (this.keywordMap.containsKey(string)) {
this.keywordMap.get(string).add(t.getKey());
} else {
this.keywordMap.put(string, Arrays.asList(t.getKey()));
}
}
}
}
public boolean addToken (Token t, String... strings) {
if (this.tokenMap.containsKey(t)) {
this.tokenMap.get(t).addAll(Arrays.asList(strings));
return true;
} else {
return false;
}
}
}
|
C++
|
UTF-8
| 514 | 3.34375 | 3 |
[] |
no_license
|
#ifndef ANIMAL_H // Include guards that prevent redefinition error
#define ANIMAL_H // #ifndef checks if it has been defined and #define begins defining
#include <string>
using namespace std;
// Prototype for animal class
class animal
{
public:
static int count; // Static variable count that counts the number of animals created
animal(); // Default constructor
virtual string speak() = 0; // Pure virtual function that returns a string
};
#endif // Specifies end of the #ifndef
|
JavaScript
|
UTF-8
| 1,772 | 3.359375 | 3 |
[] |
no_license
|
const pegaInput = document.querySelector("input");
const btnCadastrar = document.querySelector('button');
const ul = document.querySelector('ul');
//O que será executado ao clicar no botão cadastrar
function cadastrar(){
if(pegaInput.value){
const textElemento = document.createElement('span');
textElemento.innerHTML = pegaInput.value
const btnRemover = document.createElement('button');
btnRemover.innerHTML = "remover";
const li = document.createElement('li');
li.appendChild(textElemento) ;
li.appendChild(btnRemover)
//Removendo item da lista
btnRemover.onclick = ()=>{
ul.removeChild(li);
}
ul.appendChild(li);
pegaInput.value = "";
// Adicionando com a tecla enter
pegaInput.addEventListener("keypress", (e)=>{
if(e.key === "Enter"){
if(pegaInput.value){
const textElemento = document.createElement('span');
textElemento.innerHTML = pegaInput.value
const btnRemover = document.createElement('button');
btnRemover.innerHTML = "remover";
const li = document.createElement('li');
li.appendChild(textElemento) ;
li.appendChild(btnRemover)
//Removendo item da lista
btnRemover.onclick = ()=>{
ul.removeChild(li);
}
ul.appendChild(li);
pegaInput.value = "";
}
}
})
}
}
btnCadastrar.onclick = cadastrar;
|
PHP
|
UTF-8
| 3,139 | 2.671875 | 3 |
[] |
no_license
|
<div class="settingsDiv1">
<div class="settingsDiv2">
<form method="post" enctype="multipart/form-data">
<?php
$settings = new Settings();
$settings = $settings->getSettings($_SESSION['showtime_userid']);
if(is_array($settings)) {
echo "<input type='text' id='textbox' name='firstName' value='". htmlspecialchars($settings['first_name'])."' placeholder='First name' >";
echo "<input type='text' id='textbox' name='lastName' value='". htmlspecialchars($settings['last_name'])."' placeholder='Last name' >";
echo "<input type='text' id='textbox' name='email' value='". htmlspecialchars($settings['email'])."' placeholder='Email' >";
echo "<br>About me:<br>
<textarea id='textbox' style='height: 200px;' name='about'>".htmlspecialchars($settings['about'])."</textarea>";
echo '<input id="postButton" type="submit" value="Save">';
}
?>
</form>
<br><br><br>Change password:
<form method="post" enctype="multipart/form-data">
<?php
$settings = new Settings();
$settings = $settings->getSettings($_SESSION['showtime_userid']);
if(is_array($settings)) {
echo "<input type='password' id='textbox' name='password' placeholder='Old password'>";
if(isset($passError)){
$errors = explode("<br>", $passError);
foreach ($errors as $error){
if((strpos($error, 'Wrong') !== false)){
echo "<div class='errorDiv'>* $error</div>";
break;
}
}
}
echo "<input type='password' id='textbox' name='password1' placeholder='New password'>";
if(isset($passError)){
$errors = explode("<br>", $passError);
foreach ($errors as $error){
if((strpos($error, 'contain') !== false)){
echo "<div class='errorDiv'>* $error</div>";
break;
}
}
}
echo "<input type='password' id='textbox' name='password2' placeholder='Confirm new password'>";
if(isset($passError)){
$errors = explode("<br>", $passError);
foreach ($errors as $error){
if((strpos($error, 'confirm') !== false)){
echo "<div class='errorDiv'>* $error</div>";
break;
}
}
}
echo"<input style='margin-left: 10px' type='submit' id='changePassword' value='Save password'>";
}
?>
</form>
</div>
</div>
|
PHP
|
UTF-8
| 993 | 2.71875 | 3 |
[
"MIT"
] |
permissive
|
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class Subprograma extends Migration {
/**
* Run the migrations.
* Migracion para crear la tabla subprograma en la base de datos con todos sus atributos con el metodo up
* @return void
*/
public function up()
{
Schema::create('sub_programa', function (Blueprint $table) {
$table->increments('id');
$table->integer('codigo_sub_programa');
$table->string('nombre_sub_programa',200);
$table->integer('id_programa')->unsigned();
$table->foreign('id_programa')
->references('id')->on('programa')
->onDelete('restrict')
->onUpdate('cascade');
});
}
/**
* Reverse the migrations.
* metodo down para realizar el rollback de la migracion de la tabla subprograma.
* @return void
*/
public function down()
{
Schema::drop('sub_programa');
}
}
|
Java
|
UTF-8
| 167 | 1.507813 | 2 |
[
"Apache-2.0"
] |
permissive
|
package ga.thesis.hibernate.service;
import ga.thesis.hibernate.entities.StudentList;
public interface StudentListService extends CRUDService<StudentList, Long> {
}
|
Java
|
UTF-8
| 518 | 1.898438 | 2 |
[] |
no_license
|
/*
*
* BaseModel.java
* gogame-android
*
* Created by Alan Keh on 19-1-13 下午8:36
* Copyright (c) 2019 melote. All rights reserved.
* /
*/
package com.phubber.loopback;
import com.strongloop.android.loopback.Model;
import java.io.Serializable;
public class BaseModel extends Model implements Serializable, Cloneable {
@Override
public Object clone() {
try {
return super.clone();
} catch (Throwable e) {
throw new AssertionError();
}
}
}
|
C
|
UTF-8
| 354 | 3.359375 | 3 |
[] |
no_license
|
#include <stdio.h>
int main(){
int a=10,b=20,c,d;
printf("give me value of c:");
scanf("%d",&c);
d= a+b/c;
printf("d=%d\n",d);
d = a%c + b/d; // if there are operators with euqal precedence
// they are executed fromleft to right
printf("d = %d\n", d);
d = (a+40>c) + (b<=a);
printf("d = %d\n",d);
d = ++d++a;
getchar();
return 0;
}
|
Java
|
UTF-8
| 9,240 | 2.75 | 3 |
[] |
no_license
|
//// Project 3, Teng Lin 2015/11/4.
Ball c, r, g, b, y;
Buttons reset, rwall, bird, rat;
Bird o, p, q;
////global
float ratx= 40, raty=random(250,350), ratdx=random(2,6);
float cloudx=40, cloudy=30, clouddx=random(1,2) ; // cloud variables
int tableRed=70, tableGreen=240, tableBlue=230; // pool table color
float left=50, right=450, top=100, bottom=250; // Table boundaries
float middle=250;
boolean wall = true;
boolean rat2 = false;
boolean birds = false;
int score;
void setup() {
size( 700, 500 ); //window size
left= 50;
right= width-50;
top= 100;
bottom= height-80;
middle= left + (right-left) / 2;
//creating balls.
c= new Ball( width/8, height/2, color (255),0,0); // cue ball
r= new Ball( color (255,0,0), random( middle+25, right), random (top, bottom) ); // red ball
r.name= "1";
g= new Ball( color (0,255,0), random( middle+25, right), random (top, bottom) ); // green ball
g.name= "2";
b= new Ball( color (0,0,255), random( middle+25, right), random (top, bottom) ); // blue ball
b.name= "3";
y= new Ball( color (255,255,0), random( middle+25, right), random (top, bottom) ); // yellow ball
y.name= "4";
//creating birds
o = new Bird( 255,0,0, random(50,100), random(20,30),random(1,3));
p = new Bird( 0,255,0, random(50,100), random(35,50),random(1,3));
q = new Bird( 0,0,255, random(50,100), random(40,65),random(1,3));
//creating buttons, and name.
reset = new Buttons( 70,105,60,30);
reset.name= "RESET";
rwall = new Buttons( 140,105,60,30);
rwall.name= "WALL";
bird = new Buttons( 70,145,60,30);
bird.name= "BIRDS";
rat = new Buttons( 140,145,60,30);
rat.name= "RAT";
reset();
}
void reset() {
r.reset();
g.reset();
b.reset();
y.reset();
c.bx=width/8;
c.by=height/2;
c.bdx=0;
c.bdy=0;
r.bx=middle+30;
r.by=height/3;
g.bx=middle+random(60,65);
g.by=height/3.2;
//rat reset.
rat2=false;
ratx= 40;
raty=random(250,350);
ratdx=random(2,6);
score=0;
//birds reset.
birds= false;
o.birdx=random(50,100); o.birdy=random(20,30);
p.birdx=random(50,100); p.birdy=random(35,50);
q.birdx=random(50,100); q.birdy=random(40,65);
}
void draw() {
background( 250,250,200 ); //background color
table( left, top, right, bottom );
grass();
cloud();
bird();
ball();
rat2();
buttons();
score();
}
void table( float east, float north, float west, float south ) {
rectMode( CORNERS );
fill( tableRed, tableGreen, tableBlue ); // pool table
strokeWeight(20);
stroke( 240, 150, 50 );
rect( east-20, north-20, west+20, south+20 );
// Start with a WALL down the middle of the table!
if (wall) {
float middle= (east+west)/2;
stroke(0,0,0,30);
line( middle,north+10, middle,south-10 );
}
stroke(0);
strokeWeight(1);
}
void grass() {
stroke(0,255,0); //grass color green.
strokeWeight(3);
int gx = 10;
while( gx < width-20) {
line( gx, height-30 , gx+15, height);
line( gx+20, height, gx+30, height-30);
gx=gx+45; //spacing between grass
}
}
void cloud() {
noStroke();
float x;
//construct 7 clouds.
for ( x = cloudx ; x < width; x++) {
fill(255);
ellipse(x, cloudy, 60,40);
x= x+100; //spacing
}
cloudx = cloudx + clouddx; //cloud moving
cloudx %= width+(width/50); //cloud move back to screen
}
void ball() {
noStroke();
c.show();
r.show();
g.show();
b.show();
y.show();
c.move();
r.move();
g.move();
b.move();
y.move();
//// Elastic collisions.
collision( c,r);
collision( c,g);
collision( c,b);
collision( c,y);
collision( r,g);
collision( r,b);
collision( r,y);
collision( g,b);
collision( g,y);
collision( b,y);
}
void collision( Ball p, Ball q ) {
if ( p.hit( q.bx,q.by ) ) {
float tmp;
tmp=p.bdx; p.bdx=q.bdx; q.bdx=tmp; // Swap the velocities.
tmp=p.bdy; p.bdy=q.bdy; q.bdy=tmp;
p.move(); p.move(); p.move();
q.move(); q.move(); q.move();
score = score+1;
}
}
void bird() {
if (birds) {
o.show();
p.show();
q.show();
o.move();
p.move();
q.move();
}
o.mousePressed();
p.mousePressed();
q.mousePressed();
}
//rat
void rat2() {
if (rat2) {
fill(0);
ellipse(ratx, raty, 30,30);
fill(255,0,0);
ellipse(ratx+10, raty, 5,5);
//moving rat
ratx = ratx + ratdx;
//goes back to screen
ratx %= width+(width/10);
if(ratx>width+50) {
raty=random(150,350);
}
//moving legs.
int k= frameCount/30%2;
if (k==0) {
stroke(5);
fill(0);
line( ratx, raty, ratx-20, raty+25);
line( ratx, raty, ratx+20, raty+25);
raty = raty+0.5;
}
else {
stroke(5);
fill(0);
line( ratx, raty, ratx-25, raty+25);
line( ratx, raty, ratx+25, raty+25);
raty = raty-0.8;
}
noStroke();
}
//if rat collide with ball, ball will stop.
if ( dist( ratx,raty, r.bx,r.by ) < 30 ){
r.bdx=0;
r.bdy=0;
score = score-10;
}
if ( dist( ratx,raty, g.bx,g.by ) < 30 ){
g.bdx=0;
g.bdy=0;
score = score-10;
}
if ( dist( ratx,raty, b.bx,b.by ) < 30 ){
b.bdx=0;
b.bdy=0;
score = score-10;
}
if ( dist( ratx,raty, y.bx,y.by ) < 30 ){
y.bdx=0;
y.bdy=0;
score = score-10;
}
}
//// HANDLERS: keys, click
void keyPressed() {
if( key == 'r') {
reset();
}
}
//click on ball to reset the ball.
void mousePressed() {
r.mousePressed();
g.mousePressed();
b.mousePressed();
y.mousePressed();
//reset button
if ( mouseX<100 && mouseX>40 && mouseY<120 && mouseY>90) {
reset();
}
//wall button
if ( mouseX<170 && mouseX>110 && mouseY<120 && mouseY>90) {
wall=false;
r.move2();
g.move2();
b.move2();
y.move2();
}
//bird button
if ( mouseX<100 && mouseX>40 && mouseY<160 && mouseY>130) {
birds=true;
}
//rat button
if ( mouseX<170 && mouseX>110 && mouseY<160 && mouseY>130) {
rat2=true;
}
//catch the rat.
if ( dist( ratx,raty, mouseX,mouseY ) < 30 ) {
rat2= false;
ratx=40;
score = score+50;
}
}
void buttons() {
reset.show();
rwall.show();
bird.show();
rat.show();
}
class Buttons {
int mx, my, l, w; //buttons centerx , centery , length , width.
String name="";
Buttons( int templ, int tempr, int tempt, int tempb) {
mx=templ;
my=tempr;
l=tempt;
w=tempb;
}
void show() {
fill(0,0,0,30);
rectMode(CENTER);
rect( mx, my, l, w);
textSize(14);
text( name, mx-20, my+5);
}
}
void score() {
fill(0);
textSize(10);
text("SCORE", 600, 80);
text(score, 600, 90);
text("Teng Lin", 330, 80);
text("Project 3", 330, 90);
}
class Ball {
int c;
float bx, by;
float bdx=random(1,2), bdy=random(1,2);
String name="";
Ball( float tempx, float tempy, color tempc, float tempdx, float tempdy) {
c=tempc;
bx=tempx;
by=tempy;
bdy=tempdy;
bdx=tempdx;
}
Ball( color tempc, float tempx, float tempy) {
c=tempc;
bx=tempx;
by=tempy;
}
void show() {
fill(c);
ellipse( bx, by, 30,30);
fill(0);
textSize(15);
text( name, bx-5, by+5);
}
void move() {
bx = bx + bdx;
by = by + bdy;
// bounce off wall
if ( bx < middle || bx > right ) bdx *= -1;
if ( by < top || by > bottom ) bdy *= -1;
}
void move2() {
if (wall=!wall) {
middle=left;
}
}
void reset() {
bx= random(middle+25, right );
by= random( top, bottom );
bdx= random( 1,2 );
bdy= random( 1,2 );
wall= true;
middle= (width/2)+30;
}
boolean hit( float x, float y ) {
if ( dist( x,y, this.bx,this.by ) < 30 ) return true;
else return false;
}
void mousePressed() {
if (dist ( bx, by, mouseX, mouseY) <30) {
bx= random( 390,right );
by= random( top, bottom );
bdx= random( 1,2 );
bdy= random( 1,2 );
}
}
}
class Bird {
float r,g,b, birdx,birdy, bomby=birdy+1, birddx=random(1,3);
Bird( int tempr, int tempg, int tempb, float tempx, float tempy, float tempdx) {
r=tempr;
g=tempg;
b=tempb;
birdx = tempx;
birdy = tempy;
birddx = tempdx;
}
void show() {
fill(r,g,b);
ellipse(birdx, birdy, 60, 30);
fill(0);
ellipse(birdx+20, birdy-5, 5,5);
fill(r,g,b);
int k= frameCount/30%2;
if (k==0) {
triangle( birdx-10,birdy, birdx+20, birdy, birdx, birdy-30);
}
else {
triangle( birdx-10,birdy, birdx+20, birdy, birdx, birdy+30);
}
}
void move() {
birdx += birddx;
birdx %= width+(width/10);
}
void mousePressed() {
if ( dist( birdx, birdy, mouseX, mouseY) <30) {
fill(0);
ellipse( birdx,bomby, 30, 50);
bomby = bomby + 1 ;
}
}
}
|
Java
|
UTF-8
| 3,861 | 2.296875 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Trident - A Multithreaded Server Alternative
* Copyright 2014 The TridentSDK Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.tridentsdk.server.netty.packet;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import net.tridentsdk.Trident;
import net.tridentsdk.server.TridentServer;
import net.tridentsdk.server.netty.ClientConnection;
import net.tridentsdk.server.netty.protocol.Protocol;
import net.tridentsdk.server.packets.login.PacketLoginOutDisconnect;
import net.tridentsdk.server.packets.play.out.PacketPlayOutDisconnect;
import net.tridentsdk.server.player.PlayerConnection;
import net.tridentsdk.util.TridentLogger;
import javax.annotation.concurrent.ThreadSafe;
/**
* The channel handler that is placed into the netty connection bootstrap to process inbound messages from clients (not
* just players)
*
* @author The TridentSDK Team
*/
@ThreadSafe
public class PacketHandler extends SimpleChannelInboundHandler<PacketData> {
private final Protocol protocol;
private ClientConnection connection;
public PacketHandler() {
this.protocol = ((TridentServer) Trident.getServer()).getProtocol();
}
@Override
public void handlerAdded(ChannelHandlerContext context) {
this.connection = ClientConnection.getConnection(context);
}
/**
* Converts the PacketData to a Packet depending on the ConnectionStage of the Client <p/> {@inheritDoc}
*/
@Override
protected void messageReceived(ChannelHandlerContext context, PacketData data)
throws Exception {
if (this.connection.isEncryptionEnabled()) {
data.decrypt(this.connection);
}
Packet packet = this.protocol.getPacket(data.getId(), this.connection.getStage(), PacketType.IN);
//If packet is unknown disconnect the client, as said client seems to be modified
if (packet.getId() == -1) {
this.connection.logout();
// TODO Print client info. stating that has sent an invalid packet and has been disconnected
return;
}
// decode and handle the packet
packet.decode(data.getData());
try {
packet.handleReceived(this.connection);
} catch (Exception ex) {
TridentLogger.error(ex);
switch (this.connection.getStage()) {
case LOGIN:
PacketLoginOutDisconnect disconnect = new PacketLoginOutDisconnect();
disconnect.setJsonMessage(ex.getMessage());
this.connection.sendPacket(disconnect);
this.connection.logout();
// fall through
case PLAY:
PacketPlayOutDisconnect quit = new PacketPlayOutDisconnect();
quit.set("reason", "\"Internal Error: " + ex.getClass().getName() +
((ex.getMessage() != null) ? ": " + ex.getMessage() : "") + "\"");
this.connection.sendPacket(quit);
this.connection.logout();
// fall through
default:
break;
}
}
}
public void updateConnection(PlayerConnection connection) {
this.connection = connection;
}
}
|
Java
|
UTF-8
| 1,052 | 2.578125 | 3 |
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright (C) 2015 Jack Jiang(cngeeker.com) The DroidUIBuilder Project.
* All rights reserved.
* Project URL:https://github.com/JackJiang2011/DroidUIBuilder
* Version 1.0
*
* Jack Jiang PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
* FloatProperty.java at 2015-2-6 16:12:03, original version by Jack Jiang.
* You can contact author with jb2011@163.com.
*/
package org.droiddraw.property;
public class FloatProperty extends Property
{
float def;
float value;
public FloatProperty(String englishName, String attName, float def)
{
super(englishName, attName, true, true);
this.def = def;
this.value = def;
}
@Override
public Object getValue()
{
return new Float(value);
}
@Override
protected boolean isDefaultInternal()
{
return value == def;
}
@Override
public void setValue(String value)
{
try
{
this.value = Float.parseFloat(value);
}
catch (NumberFormatException ex)
{
ex.printStackTrace();
this.value = -1f;
}
}
public void setFloatValue(float value)
{
this.value = value;
}
}
|
Java
|
UTF-8
| 1,748 | 2.71875 | 3 |
[] |
no_license
|
package ch11.FromTextBookDemo;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
public class ShowFlowPane extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
Pane flowpane=new FlowPane();
Image image=new Image("http://pic1.nipic.com/2009-01-07/20091713417344_2.jpg",
200,200,false,true);
ImageView imageView1=new ImageView(image);
ImageView imageView2=new ImageView(image);
ImageView imageView3=new ImageView(image);
ImageView imageView4=new ImageView(image);
ImageView imageView5=new ImageView(image);
Label label=new Label("请输入长度");
TextField textField=new TextField();
Label label1=new Label("米");
// imageView5.setRotate(90);
flowpane.getChildren().add(imageView1);
flowpane.getChildren().add(imageView2);
flowpane.getChildren().add(imageView3);
flowpane.getChildren().add(imageView4);
flowpane.getChildren().add(imageView5);
flowpane.getChildren().addAll(label,textField,label1);
// flowpane.setPadding(new Insets(10,11,12,13));
((FlowPane) flowpane).setHgap(10);
((FlowPane) flowpane).setVgap(10);
Scene scene=new Scene(flowpane,1400,1100);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args){
Application.launch(args);
}
}
|
JavaScript
|
UTF-8
| 5,207 | 2.546875 | 3 |
[] |
no_license
|
import multiparty from 'multiparty';
import path from 'path';
import fse from 'fs-extra';
const extractExt = fileName => fileName.slice(fileName.lastIndexOf('.'), fileName.length); // 提取后缀名
const UPLOAD_DIR = path.resolve(__dirname, '..', 'target'); // 大文件存储目录
// 返回已经上传切片名
const createUploadedList = async fileHash =>
fse.existsSync(path.resolve(UPLOAD_DIR, fileHash)) // 查看切片目录是否存在
? await fse.readdir(path.resolve(UPLOAD_DIR, fileHash)) // 返回已上传的切片地址
: [];
const pipeStream = (path, writeStream) =>
new Promise(resolve => {
const readStream = fse.createReadStream(path);
readStream.on('end', () => {
fse.unlinkSync(path);
resolve();
});
readStream.pipe(writeStream);
});
// 循环读取切换切入目标文件地址
const mergeFileChunk = async (filePath, fileHash, size) => {
const chunkDir = path.resolve(UPLOAD_DIR, fileHash);
const chunkPaths = await fse.readdir(chunkDir);
// 根据切片下标进行排序
// 否则直接读取目录的获得的顺序可能会错乱
chunkPaths.sort((a, b) => a.split('-')[1] - b.split('-')[1]);
await Promise.all(
chunkPaths.map((chunkPath, index) =>
pipeStream(
path.resolve(chunkDir, chunkPath),
// 指定位置创建可写流
fse.createWriteStream(filePath, {
start: index * size,
end: (index + 1) * size,
})
)
)
);
fse.rmdirSync(chunkDir); // 合并后删除保存切片的目录
};
// 检查是否已存在上传文件,未存在也要返回是否存在文件切片了
export const handleVerifyUpload = async ctx => {
const req = ctx.request;
const data = req.body;
const { fileHash, fileName } = data;
const ext = extractExt(fileName);
const filePath = path.resolve(UPLOAD_DIR, `${fileHash}${ext}`); // 判断文件是否已经有一份上传成功并在服务器了
if (fse.existsSync(filePath)) {
return {
code: 200,
data: {
shouldUpload: false,
},
message: '',
success: true,
};
} else {
return {
code: 200,
data: {
shouldUpload: true,
// 文件未上传,但有可能已上传了部分切片,所以返回的是已上传的所有切片地址
uploadedList: await createUploadedList(fileHash),
},
message: '',
success: true,
};
}
};
// 处理切片
export const handleFormData = async ctx => {
const req = ctx.req;
const multipart = new multiparty.Form();
multipart.on('error', function(err) {
console.log('Emultipart 解析失败: ' + err.stack);
});
return new Promise(resolve => {
// multipart Api https://www.npmjs.com/package/multiparty
multipart.parse(req, async (err, fields, files) => {
// 模拟报错
if (Math.random() < 0.2) {
console.log(fields.hash, '500');
return resolve({
code: 500,
data: null,
message: `上传失败`,
success: false,
});
}
if (err) {
return resolve({
code: 500,
data: null,
message: `上传失败【${err}】`,
success: false,
});
}
const [chunk] = files.chunk; // 切面文件
const [hash] = fields.hash; // 切片文件 hash 值
const [fileHash] = fields.fileHash; // 文件 hash 值
const [fileName] = fields.fileName; // 文件名
const filePath = path.resolve(UPLOAD_DIR, `${fileHash}${extractExt(fileName)}`);
const chunkDir = path.resolve(UPLOAD_DIR, fileHash);
// 文件存在直接返回
if (fse.existsSync(filePath)) {
return resolve({
code: 200,
data: null,
message: `上传成功`,
success: true,
});
}
// 切片目录不存在,创建切片目录
if (!fse.existsSync(chunkDir)) {
await fse.mkdirs(chunkDir);
}
// fs-extra 专用方法,类似 fs.rename 并且跨平台
// fs-extra 的 rename 方法 windows 平台会有权限问题
// https://github.com/meteor/meteor/issues/7852#issuecomment-255767835
/**
* 这里的 chunk.path 是 koa-bodyparser 库对上传的文件的系统临时存放的地址
* 存放目录为 '/var/folders/g5/x7gcn7492qb3d6gbw1z6qjw00000gn/T'
* 这个目录是 koa-bodyparser 通过使用 node 的 Api os.tmpdir() 进行获取的
* 对于这个系统临时存放地址也可以进行更改,通过 koa-bodyparser 配置时的参数
* */
await fse.move(chunk.path, path.resolve(chunkDir, hash));
return resolve({
code: 200,
data: null,
message: `切片上传成功【${hash}】`,
success: true,
});
});
});
};
// 合并切片
export const handleMerge = async ctx => {
const req = ctx.request;
const data = req.body;
const { fileHash, fileName, size } = data;
const ext = extractExt(fileName);
const filePath = path.resolve(UPLOAD_DIR, `${fileHash}${ext}`); // 获取组装文件输出地址
await mergeFileChunk(filePath, fileHash, size);
return {
code: 200,
data: null,
message: '上传成功',
success: true,
};
};
|
PHP
|
UTF-8
| 919 | 2.703125 | 3 |
[] |
no_license
|
<?php
include_once("addAnimal.php");
$location ="pictures/";
$target_file=$location.basename($_FILES["fileToUpload"]["name"]);
$success=1;
$fileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
if(isset($_POST["submit"])) {
if (hash_equals($_SESSION['token'], $_POST['token'])) {
if($fileType !="jpg"){
$success=0;
}
if ($success == 0) {
echo "Sorry, your file was not uploaded. Make sure it is in type .jpg";
} else {
$temp = explode(".", $_FILES["fileToUpload"]["name"]);
$newfilename = filter_var($_POST['name'], FILTER_SANITIZE_STRING).filter_var($_POST['ID'], FILTER_SANITIZE_STRING).'.'.end($temp);
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], "pictures/".$newfilename)) {
echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
}
?>
|
Ruby
|
UTF-8
| 2,038 | 2.65625 | 3 |
[
"LicenseRef-scancode-warranty-disclaimer",
"BSD-3-Clause"
] |
permissive
|
#
# DNA Shipistrano
#
# = Htaccess
#
# Provides ways of adjusting the .htaccess file
#
# == Variables
#
# - *auth_user* username for basic auth
# - *auth_pass* password for basic auth
# - *auth_folder* folder to protect auth
#
# == Tasks
#
# - *htaccess:auth:protect* add a htpasswd protection to the server.
# - *htaccess:auth:unprotect* remove htpasswd protection
# - *htaccess:rewrite_base* add a rewrite base /
#
namespace :htaccess do
namespace :auth do
desc <<-DESC
Protect a given folder. Use set :auth_folder to protect.
DESC
task :protect do
run "#{try_sudo} htpasswd -nb #{auth_user} '#{auth_pass}' > #{auth_folder}/.htpasswd"
backup_file("#{auth_folder}/.htaccess")
prepend_to_file(
"#{auth_folder}/.htaccess",
"AuthType Basic\\nAuthName #{app}\\nAuthUserFile #{auth_folder}/.htpasswd\\nRequire valid-user\\n"
)
end
desc <<-DESC
Unprotect latest version.
DESC
task :unprotect_release do
run "if [ -f #{auth_folder}/.htaccess.backup ]; then #{try_sudo} rm -rf #{auth_folder}/.htaccess && cp #{auth_folder}/.htaccess.backup #{auth_folder}/.htaccess; fi"
end
desc <<-DESC
Unprotect latest version.
DESC
task :unprotect_production do
run "if [ -f #{production_folder}/.htaccess.backup ]; then #{try_sudo} rm -rf #{production_folder}/.htaccess && cp #{production_folder}/.htaccess.backup #{production_folder}/.htaccess; fi"
end
end
desc <<-DESC
Rewrite base in htaccess file to /.
DESC
task :rewrite_base do
append_to_file("#{latest_release}/.htaccess", "\\nRewriteBase /")
end
def prepend_to_file(filename, str)
run "if [ -f #{filename} ]; then echo -e \"#{str}\"|cat - #{filename} > /tmp/out && mv /tmp/out #{filename}; fi"
end
def append_to_file(filename, str)
run "if [ -f #{filename} ]; then echo -e \"#{str}\" >> #{filename}; fi"
end
def backup_file(filename)
run "if [ -f #{filename} ]; then #{try_sudo} cp #{filename} #{filename}.backup; fi"
end
end
|
Java
|
UTF-8
| 789 | 3.015625 | 3 |
[] |
no_license
|
package com.example.demo.chap05_책임할당하기_영화예매;
import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.time.LocalTime;
public class PeriodCondition implements DiscountCondition {
private DayOfWeek dayOfWeek;
private LocalTime startTime;
private LocalTime endTime;
public PeriodCondition(DayOfWeek dayOfWeek, LocalTime startTime, LocalTime endTime) {
this.dayOfWeek = dayOfWeek;
this.startTime = startTime;
this.endTime = endTime;
}
@Override
public boolean isSatisfiedBy(Screening screening) {
LocalDateTime whenScreened = screening.getWhenScreened();
return dayOfWeek.equals(whenScreened.getDayOfWeek()) &&
startTime.compareTo(whenScreened.toLocalTime()) <= 0 &&
endTime.compareTo(whenScreened.toLocalTime()) >= 0;
}
}
|
Shell
|
UTF-8
| 1,683 | 2.8125 | 3 |
[
"MIT"
] |
permissive
|
echo "Using Docker"
# If a value is not set here a default will be assigned.
# MariaDB Connection Information
unset MARIADB_USER
unset MARIADB_PWD
export MARIADB_HOST=MARIA10-01
unset MARIADB_PORT
unset MARIADB_DBNAME
# Generic SQL Server Connection Information
unset MSSQL_USER
unset MSSQL_PWD
export MSSQL_HOST=MSSQL19-01
unset MSSQL_PORT
unset MSSQL_DBNAME
# SQL Server 2017 Connection Information
unset MSSQL17_USER
unset MSSQL17_PWD
export MSSQL17_HOST=MSSQL17-01
unset MSSQL17_PORT
unset MSSQL17_DBNAME
# SQL Server 2019 Connection Information
unset MSSQL19_USER
unset MSSQL19_PWD
export MSSQL19_HOST=MSSQL19-01
unset MSSQL19_PORT
unset MSSQL19_DBNAME
# SQL Server 2022 Connection Information
unset MSSQL22_USER
unset MSSQL22_PWD
export MSSQL22_HOST=MSSQL22-01
unset MSSQL22_PORT
unset MSSQL22_DBNAME
# MySQL Connection Information
unset MYSQL_USER
unset MYSQL_PWD
export MYSQL_HOST=MYSQL80-01
unset MYSQL_PORT
unset MYSQL_DBNAME
# Oracle 19c Connection Information
export ORACLE19C=ORA1903
unset ORACLE19C_USER
unset ORACLE19C_PWD
# Oracle 18c Connection Information
export ORACLE18C=ORA1803
unset ORACLE18C_USER
unset ORACLE18C_PWD
# Oracle 12c Connection Information
export ORACLE12C=ORA1220
unset ORACLE12C_USER
unset ORACLE12C_PWD
# Oracle 11g Connection Information
export ORACLE11G=ORA1120
unset ORACLE11G_USER
unset ORACLE11G_PWD
# Postgres Connection Information
unset POSTGRES_USER
unset POSTGRES_PWD
export POSTGRES_HOST=PGSQL14-01
unset POSTGRES_PORT
unset POSTGRES_DBNAME
# Relative location of export files to be used for testing
export YADAMU_ORACLE_PATH=oracle19c
export YADAMU_MSSQL_PATH=mssql19
export YADAMU_MYSQL_PATH=mysql
export YADAMU_TEST_FOLDER=cmdLine
|
C
|
UTF-8
| 430 | 3.21875 | 3 |
[] |
no_license
|
//
// Created by saud1 on 12-09-2020.
//
#include <stdio.h>
#include "Stack.h"
int main(){
Stack * s;
int max,i;
printf("Stack size?:");
scanf("%d",&max);
s=createStack(max);
if(!s)return 1;
if(isempty(s))return 2;
for(i=0;i<max;i++)
push(s,i);
if(!isempty(s))return 3;
while (isempty(s)){
printf("%d\n",top(s));
pop(s);
}
destroyStack(s);
return 0;
}
|
PHP
|
UTF-8
| 1,416 | 2.765625 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Phone extends Model
{
const TYPE_HOME = 'home';
const TYPE_WORK = 'work';
const TYPE_MOBILE = 'mobile';
/**
* The model's default values for attributes.
*
* @var array
*/
protected $attributes = [
'type' => self::TYPE_HOME
];
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'type', 'phone_country_code', 'phone_number', 'phone',
];
/**
* Bootstrap the model and its traits.
*
* @return void
*/
public static function boot()
{
parent::boot();
static::creating(function ($model) {
if( empty( $model->phone ) ) {
$model->phone = $model->phone_country_code . $model->phone_number;
}
});
static::updating(function ($model) {
if( empty( $model->phone ) ) {
$model->phone = $model->phone_country_code . $model->phone_number;
}
});
}
/**
* Get the user that owns the phone.
*/
public function user()
{
return $this->belongsTo(User::class);
}
/**
* Get the order that owns the phone.
*/
public function order()
{
return $this->belongsTo(Order::class);
}
}
|
C#
|
UTF-8
| 4,367 | 2.515625 | 3 |
[] |
no_license
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TriangleNet.Geometry;
public class GeneratePaths : MonoBehaviour
{
public float PathMultiplier = 1f; //How many paths should be removed after spanning path is found?
public bool superLink;
MapGenerator2 MapGen;
List<Feature> allFeatures;
List<Path> paths;
List<Path> shortPath;
TriangleNet.Mesh mesh;
public void GenerateMesh()
{
MapGen = GetComponent<MapGenerator2>();
allFeatures = MapManager.allFeatures;
paths = new List<Path>();
shortPath = new List<Path>();
Polygon polygon = new Polygon();
for (int i = 0; i < allFeatures.Count; i++)
{
polygon.Add(new Vertex(allFeatures[i].centerPoint.x, allFeatures[i].centerPoint.y));
}
mesh = (TriangleNet.Mesh)polygon.Triangulate();
paths = ConvertToPath(mesh);
//foreach (Path item in paths)
//{
// Debug.Log(item);
//}
shortPath = GenerateShortPath(paths);
}
List<Path> GenerateShortPath(List<Path> paths)
{
if (!superLink)
{
List<Path> oldpath = paths;
paths.Sort((p1, p2) => p1.length.CompareTo(p2.length));
List<Path> tree = new List<Path>();
List<int> verticesRepresented = new List<int>();
int i = 0;
while (verticesRepresented.Count != allFeatures.Count)
{
if (paths.Count == 0)
{
Debug.Log("Too many points!");
break;
}
i = Random.Range(0, paths.Count - 1);
tree.Add(paths[i]);
if (!verticesRepresented.Contains(paths[i].sourceID))
{
verticesRepresented.Add(paths[i].sourceID);
}
if (!verticesRepresented.Contains(paths[i].endID))
{
verticesRepresented.Add(paths[i].endID);
}
verticesRepresented.Sort();
paths.RemoveAt(i);
}
while (tree.Count > allFeatures.Count * PathMultiplier)
{
tree.RemoveAt(Random.Range(0, tree.Count - 1));
}
return tree;
}
else
{
return paths;
}
}
int FindID(Vector2 point)
{
for (int i = 0; i < allFeatures.Count; i++)
{
if (point == allFeatures[i].centerPoint)
return allFeatures[i].ID;
}
Debug.LogWarning("Point at " + point + " has no ID associated with it");
return -1;
}
List<Path> ConvertToPath(TriangleNet.Mesh mesh)
{
List<Path> path = new List<Path>();
int pathID = 0;
foreach (Edge edge in mesh.Edges)
{
Vertex v0 = mesh.vertices[edge.P0];
Vertex v1 = mesh.vertices[edge.P1];
Vector2 start = new Vector2((float)v0.x, (float)v0.y);
Vector2 end = new Vector2((float)v1.x, (float)v1.y);
float length = Vector2.Distance(start, end);
int startID = FindID(start);
int endID = FindID(end);
if (startID > endID)
{
int tmp = startID;
startID = endID;
endID = tmp;
}
path.Add(new Path(start, end, length, startID, endID, pathID));
pathID++;
}
return path;
}
public List<Path> GetShortPath()
{
return shortPath;
}
public void OnDrawGizmos()
{
if (mesh == null)
{
return;
}
//Gizmos.color = Color.red;
//foreach (Edge edge in mesh.Edges)
//{
// Vertex v0 = mesh.vertices[edge.P0];
// Vertex v1 = mesh.vertices[edge.P1];
// Vector3 p0 = new Vector3((float)v0.x, (float)v0.y, 0.0f);
// Vector3 p1 = new Vector3((float)v1.x, (float)v1.y, 0.0f );
// Gizmos.DrawLine(p0, p1);
//}
Gizmos.color = Color.blue;
foreach (Path path in shortPath)
{
Vector3 p0 = path.sourcePoint;
Vector3 p1 = path.endPoint;
Gizmos.DrawLine(p0, p1);
}
}
}
|
JavaScript
|
UTF-8
| 4,777 | 2.796875 | 3 |
[
"MIT"
] |
permissive
|
$(function() {
var img_urls = ["img/deer.png", "img/dolphin.png", "img/kangaroo.png", "img/leopard.png", "img/panther.png", "img/penguin.png", "img/rabbit.png", "img/sheep.png", "img/swan.png", "img/wolf.png", "img/zebra.png", "img/duck.png", "img/deer.png", "img/dolphin.png", "img/kangaroo.png", "img/leopard.png", "img/panther.png", "img/penguin.png", "img/rabbit.png", "img/sheep.png", "img/swan.png", "img/wolf.png", "img/zebra.png", "img/duck.png"];
//Shuffle js array > http://stackoverflow.com/a/2450976/4991434
function shuffle(array) {
var currentIndex = array.length,
temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
var arr = img_urls;
arr = shuffle(arr);
for (i = 0; i < img_urls.length; i++) {
$(".items").append(
"<div class='container'><div class='front'>" + img_urls[i] + "</div><div class='back'><img class='image' src=' " + img_urls[i] + "'/></div></div>"
);
}
var first;
var second;
var total_clicks = 0;
var count = 0;
function check_level() {
if (total_clicks === 10) {
$(".first-svg").removeClass("level");
} else if (total_clicks === 15) {
$(".second-svg").removeClass("level");
} else if (total_clicks === 20) {
$(".third-svg").removeClass("level");
}
}
function game_over() {
if ($(".matched").length === 48) {
setTimeout(function() {
alert("Congrats. You have finished the game!");
}, 1200);
setTimeout(function() {
location.reload();
}, 1800);
}
}
// for mozilla issue, make opacity 0 as default
$('.image').addClass('noOpacity');
$(".front").click(function(e) {
// for mozilla issue, play opacity of .image
var self = this;
setTimeout(function() {
$(self).next('.back').find('.image').addClass('yesOpacity');
}, 300);
count++;
// prevent fast click
if ($(e.target).data('oneclicked') != 'yes') {
$(e.target).css("pointer-events", "none")
setTimeout(function() {
$(e.target).css("pointer-events", "auto")
}, 400);
}
if (count === 1) {
$(this, ".front").addClass("showBack-front").addClass("clicked");
$(this).next('.back').addClass("showBack-back").addClass("clicked");
first = $(this, ".front").text();
} else {
$(this, ".front").addClass("showBack-front").addClass("clicked");;
$(this).next('.back').addClass("showBack-back").addClass("clicked");;
second = $(this, ".front").text();
count = 0;
$(".front").css("pointer-events", "none");
setTimeout(function() {
if (first === second) {
total_clicks = total_clicks - 1;
$('.clicked').addClass('animated tada matched no-pointer-events');
//Check if game is over
game_over();
} else {
$(".front").removeClass("showBack-front");
$(".back").removeClass("showBack-back");
$('.clicked').addClass('animated shake');
setTimeout(function() {
$(".clicked").removeClass("clicked shake");
// for mozilla issue, play opacity of .image
$('.image').not('section .matched').removeClass('yesOpacity');
$('.image').not('section .matched').addClass('noOpacity');
}, 500);
}
$(".front").css("pointer-events", "auto");
total_clicks++;
$(".total_clicks span").text(total_clicks);
check_level();
}, 525);
}
return false;
});
// hide particles in mozilla
if (navigator.userAgent.indexOf("Firefox") > 0) {
document.getElementById('particles-js').style.display = "none";
}
});
|
TypeScript
|
UTF-8
| 743 | 2.546875 | 3 |
[] |
no_license
|
import {Transformer} from './compile';
declare var require;
let closure:((string)=>{compiledCode:string})|null|undefined = undefined;
export class OptimizeUtil {
static closure(flags:any = {}):Transformer|null {
if (closure === undefined) {
try {
closure = require('google-closure-compiler-js').compile;
} catch (e) {
closure = null;
}
}
if (closure !== null && closure !== undefined) {
let fn = closure;
return src => {
let finalFlags = {jsCode:[{src}]};
for (let k of Object.keys(flags)) {
finalFlags[k] = flags[k];
}
let res = fn(finalFlags);
return res.compiledCode;
}
} else {
return null;
}
}
}
|
Java
|
UTF-8
| 20,690 | 2.09375 | 2 |
[
"Apache-2.0",
"AGPL-3.0-or-later",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
/* ******************************************************************************
* Copyright (c) 2022 Konduit K.K.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
package ai.konduit.serving.pipeline.impl.data;
import ai.konduit.serving.pipeline.api.data.*;
import ai.konduit.serving.pipeline.impl.data.box.BBoxCHW;
import ai.konduit.serving.pipeline.impl.data.box.BBoxXY;
import ai.konduit.serving.pipeline.impl.data.image.Png;
import ai.konduit.serving.pipeline.impl.data.ndarray.SerializedNDArray;
import org.apache.commons.compress.utils.Lists;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.nd4j.common.resources.Resources;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static ai.konduit.serving.pipeline.impl.data.JData.empty;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
public class DataTest {
private final String KEY = "stringData";
private final String VALUE = "Some string data";
@Rule
public TemporaryFolder testDir = new TemporaryFolder();
@Test
public void testStringData() {
Data container = JData.singleton(KEY, VALUE);
String value = container.getString(KEY);
assertEquals(VALUE, value);
}
@Test(expected = IllegalStateException.class)
public void testNoData() {
BigDecimal notSupportedValue = BigDecimal.ONE;
Data container = JData.singleton(KEY, notSupportedValue);
}
@Test(expected = ValueNotFoundException.class)
public void testAbsentData() {
Data container = JData.singleton(KEY, VALUE);
String value = container.getString("no_data_for_this_key");
assertEquals(VALUE, value);
}
@Test
public void testBooleanData() {
boolean value = true;
Data container = JData.singleton(KEY, value);
assertEquals(true, container.getBoolean(KEY));
}
@Test
public void testBytesData() {
byte[] input = new byte[]{1,2,3,4,5};
Data container = JData.singleton(KEY, input);
assertArrayEquals(input, container.getBytes(KEY));
}
@Test
public void testDoubleData() {
Double input = 1.0;
Data container = JData.singleton(KEY, input);
assertEquals(input, container.getDouble(KEY), 1e-4);
}
@Test
public void testIntData() {
long data = 100;
Data container = JData.singleton(KEY, data);
assertEquals(data, container.getLong(KEY));
}
@Test
public void testEmbeddedData() {
Data stringContainer = JData.singleton("stringData", "test");
Data booleanContainer = JData.singleton("boolData", false);
booleanContainer.put("level1", stringContainer);
Data ndContainer = JData.singleton("bytesData", new byte[10]);
ndContainer.put("level2", booleanContainer);
Data layeredContainer = JData.singleton("upperLevel", ndContainer);
}
@Test
public void testSerde() throws IOException {
Data someData = JData.singleton(KEY, Long.valueOf(200));
ProtoData protoData = someData.toProtoData();
File testFile = testDir.newFile();
protoData.save(testFile);
Data restoredData = Data.fromFile(testFile);
assertEquals(protoData.get(KEY), restoredData.get(KEY));
}
@Test
public void testConvertToBytes() {
Data longData = Data.singleton(KEY, Long.valueOf(200));
byte[] output = longData.asBytes();
assert(output != null);
/*Data intData = Data.singleton(KEY, Integer.valueOf(20));
output = intData.asBytes();
assert(output != null);*/
}
@Test
public void testInt32Conversion() {
Data intData = Data.singleton(KEY, Integer.valueOf(200));
Data longData = Data.singleton(KEY, Long.valueOf(200L));
assertEquals(intData.get(KEY), longData.get(KEY));
}
@Test
public void testFloatConversion() {
Data floatData = Data.singleton(KEY, Float.valueOf(200));
Data doubleData = Data.singleton(KEY, Double.valueOf(200.0));
assertEquals(floatData.get(KEY), doubleData.get(KEY));
}
@Test
public void testLists() {
Data someData = (JData) JData.singletonList(KEY, Collections.singletonList(Long.valueOf(200)), ValueType.INT64);
List<?> someList = someData.getList(KEY, ValueType.INT64);
assertEquals(1, someList.size());
assertEquals(200L, someList.get(0));
assertEquals(ValueType.INT64, someData.listType(KEY));
List<String> strings = new ArrayList<>();
strings.add("one");
strings.add("two");
strings.add("three");
Data listOfStrings = JData.singletonList(KEY, strings, ValueType.STRING);
assertEquals(ValueType.LIST, listOfStrings.type(KEY));
assertEquals(ValueType.STRING, listOfStrings.listType(KEY));
List<?> actual = listOfStrings.getList(KEY, ValueType.STRING);
assertEquals(strings, actual);
}
@Test
public void testListOfLists() {
List<Long> innerData = new ArrayList<>();
for (long i = 0; i < 6; ++i) {
innerData.add(i);
}
List<List<Long>> data = new ArrayList<>();
data.add(innerData);
Data listOfLists = Data.singletonList(KEY, data, ValueType.INT64);
List<?> actual = listOfLists.getList(KEY, ValueType.LIST);
assertEquals(1, actual.size());
assertEquals(6, ((List<Long>)actual.get(0)).size());
for (long i = 0; i < 6; ++i) {
assertEquals(i, (long)((List<Long>)actual.get(0)).get((int)i));
}
assertEquals(ValueType.INT64, listOfLists.listType(KEY));
List<Long> innerBigData = new ArrayList<>();
for (long i = 0; i < 100; ++i) {
innerBigData.add(i);
}
data.add(innerBigData);
Data listOfTwoLists = Data.singletonList(KEY, data, ValueType.INT64);
assertEquals(ValueType.LIST, listOfTwoLists.type(KEY));
assertEquals(ValueType.INT64, listOfTwoLists.listType(KEY));
List<?> bigData = listOfTwoLists.getList(KEY, ValueType.INT64);
assertEquals(2,bigData.size());
assertEquals(6, ((List<?>)bigData.get(0)).size());
assertEquals(100, ((List<?>)bigData.get(1)).size() );
}
@Test
public void testWrongValueTypeForList() {
List<String> strings = new ArrayList<>();
strings.add("one");
strings.add("two");
strings.add("three");
// TODO: Value type check for lists is missing.
Data brokenList = Data.singletonList(KEY, strings, ValueType.BOOLEAN);
assertEquals(ValueType.BOOLEAN, brokenList.listType(KEY));
}
@Test
public void testsNumericLists() {
final long LIST_SIZE = 6;
List<Long> numbers = Lists.newArrayList();
for (long i = 0; i < LIST_SIZE; ++i) {
numbers.add(i);
}
Data listOfNumbers = new JData.DataBuilder().
addListInt64(KEY, numbers).
build();
assertEquals(ValueType.INT64, listOfNumbers.listType(KEY));
List<?> actual = listOfNumbers.getList(KEY, ValueType.INT64);
assertEquals(numbers, actual);
for (int i = 0 ; i < LIST_SIZE; ++i) {
assertEquals(numbers.get(i), actual.get(i));
}
}
@Test
public void testBooleanList() {
final long LIST_SIZE = 6;
List<Boolean> data = Lists.newArrayList();
for (int i = 0; i < LIST_SIZE; ++i) {
data.add(i % 2 == 0);
}
Data listOfBoolean = Data.singletonList(KEY, data, ValueType.BOOLEAN);
assertEquals(ValueType.BOOLEAN, listOfBoolean.listType(KEY));
List<?> actual = listOfBoolean.getList(KEY, ValueType.BOOLEAN);
for (int i = 0 ; i < LIST_SIZE; ++i) {
assertEquals(data.get(i), actual.get(i));
}
}
@Test
public void testDoubleLists() {
final long LIST_SIZE = 6;
List<Double> data = Lists.newArrayList();
for (int i = 0; i < LIST_SIZE; ++i) {
data.add(Double.valueOf(i));
}
Data listOfDouble = new JData.DataBuilder().addListDouble(KEY, data).build();
assertEquals(ValueType.DOUBLE, listOfDouble.listType(KEY));
List<?> actual = listOfDouble.getList(KEY, ValueType.DOUBLE);
for (int i = 0 ; i < LIST_SIZE; ++i) {
assertEquals(data.get(i), actual.get(i));
}
}
@Test
public void testBuilderVSFactory() {
JData built = new JData.DataBuilder().
add("key1", true).
add("key2","null").
build();
// Normally don't need this cast. Just for asserts below and is subject to change.
JData made = (JData)JData.singleton("key1", true);
made.put("key2", "null");
JData madeFromEmpty = (JData) JData.empty();
madeFromEmpty.put("key1", true);
madeFromEmpty.put("key2", "null");
assertEquals(built.getDataMap().get("key1").get(), made.getDataMap().get("key1").get());
assertEquals(built.getDataMap().get("key2").get(), made.getDataMap().get("key2").get());
assertEquals(built.getDataMap().get("key1").get(), madeFromEmpty.getDataMap().get("key1").get());
assertEquals(built.getDataMap().get("key2").get(), madeFromEmpty.getDataMap().get("key2").get());
}
@Test
public void testJsonConversion() {
Data someData = Data.singleton(KEY, "test");
String jsonString = someData.toJson();
Data someDataFromJson = Data.fromJson(jsonString);
String actualJsonStr = someDataFromJson.toJson();
assertEquals(jsonString, actualJsonStr);
assertEquals(someData.get(KEY), someDataFromJson.get(KEY));
}
@Test
public void testBytesSerde() {
JData someData = (JData)Data.singleton(KEY, "testString");
byte[] someBytes = someData.asBytes();
JData restoredData = (JData) Data.fromBytes(someBytes);
assertEquals(someData.get(KEY), restoredData.get(KEY));
}
@Test
public void testStreamsSerde() throws IOException {
JData someData = (JData)Data.singleton(KEY, "testString");
Data restored = empty();
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
someData.write(baos);
try (ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray())) {
restored = Data.fromStream(bais);
}
}
assertEquals(someData.get(KEY), restored.get(KEY));
}
@Test
public void testImageData() {
File f = Resources.asFile("data/5_32x32.png");
Image i = Image.create(f);
Data imageData = Data.singleton(KEY, i);
Png p = i.getAs(Png.class);
byte[] origBytes = p.getBytes();
Png p2 = ((Image)imageData.get(KEY)).getAs(Png.class);
byte[] actualBytes = p2.getBytes();
assertEquals(origBytes, actualBytes);
}
@Test
public void testImageSerde() throws IOException {
File f = Resources.asFile("data/5_32x32.png");
Image i = Image.create(f);
Data imageData = Data.singleton(KEY, i);
File serFile = testDir.newFile();
imageData.save(serFile);
Data restoredData = Data.fromFile(serFile);
assertEquals(imageData.get(KEY), restoredData.get(KEY));
assertEquals(imageData, restoredData);
}
@Test
public void testNDArraySerde() throws IOException {
float[] rawData = {1, 3, 6, 7, 8, 10, 4, 3, 2, 4};
long[] shape = {1, 10};
NDArray ndArray = NDArray.create(rawData);
//SerializedNDArray serializedNDArray = ndArray.getAs(SerializedNDArray.class);
Data ndData = Data.singleton(KEY, ndArray);
File serFile = testDir.newFile();
ndData.save(serFile);
Data restoredData = Data.fromFile(serFile);
assertEquals(ndData.get(KEY), restoredData.get(KEY));
assertEquals(ndData, restoredData);
}
@Test
public void testImageListSerde() throws IOException {
List<Image> imageList = new ArrayList<>();
for (int i = 0; i < 5; ++i) {
File f = Resources.asFile("data/5_32x32.png");
imageList.add(Image.create(f));
}
Data imageData = Data.singletonList(KEY, imageList, ValueType.IMAGE);
File serFile = testDir.newFile();
imageData.save(serFile);
Data restoredData = Data.fromFile(serFile);
assertEquals(imageData.getList(KEY, ValueType.IMAGE),
restoredData.getList(KEY, ValueType.IMAGE));
assertEquals(imageData, restoredData);
}
@Test
public void testNDArraysListSerde() throws IOException {
List<NDArray> arrays = new ArrayList<>();
for (int i = 0; i < 5; ++i) {
float[] rawData = {1, 3, 6, 7, 8, 10, 4, 3, 2, 4};
arrays.add(NDArray.create(rawData));
}
Data ndData = Data.singletonList(KEY, arrays, ValueType.NDARRAY);
File serFile = testDir.newFile();
ndData.save(serFile);
Data restoredData = Data.fromFile(serFile);
assertEquals(ndData.getList(KEY, ValueType.NDARRAY),
restoredData.getList(KEY, ValueType.NDARRAY));
assertEquals(ndData, restoredData);
}
@Test
public void testStringsListSerde() throws IOException {
List<String> strData = new ArrayList<>();
strData.add("one");
strData.add("two");
strData.add("three");
Data stringsData = Data.singletonList(KEY, strData, ValueType.STRING);
File serFile = testDir.newFile();
stringsData.save(serFile);
Data restoredData = Data.fromFile(serFile);
assertEquals(stringsData.getList(KEY, ValueType.STRING),
restoredData.getList(KEY, ValueType.STRING));
assertEquals(stringsData, restoredData);
}
@Test
public void testDoubleListsSerde() throws IOException {
List<Double> rawData = new ArrayList<>();
rawData.add(1.);
rawData.add(20.);
rawData.add(50.);
rawData.add(0.78767);
Data doubleData = Data.singletonList(KEY, rawData, ValueType.DOUBLE);
File serFile = testDir.newFile();
doubleData.save(serFile);
Data restoredData = Data.fromFile(serFile);
assertEquals(doubleData.getList(KEY, ValueType.DOUBLE),
restoredData.getList(KEY, ValueType.DOUBLE));
assertEquals(doubleData, restoredData);
}
@Test
public void testBooleanListsSerde() throws IOException {
List<Boolean> rawData = new ArrayList<>();
rawData.add(true);
rawData.add(false);
rawData.add(true);
rawData.add(true);
Data boolData = Data.singletonList(KEY, rawData, ValueType.BOOLEAN);
File serFile = testDir.newFile();
boolData.save(serFile);
Data restoredData = Data.fromFile(serFile);
assertEquals(boolData.getList(KEY, ValueType.DOUBLE),
restoredData.getList(KEY, ValueType.DOUBLE));
assertEquals(boolData, restoredData);
}
@Test
public void testInt64ListsSerde() throws IOException {
List<Long> rawData = new ArrayList<>();
for (long l = 0; l < 10000; ++l) {
rawData.add(l);
}
Data intData = Data.singletonList(KEY, rawData, ValueType.INT64);
File serFile = testDir.newFile();
intData.save(serFile);
Data restoredData = Data.fromFile(serFile);
assertEquals(intData.getList(KEY, ValueType.DOUBLE),
restoredData.getList(KEY, ValueType.DOUBLE));
assertEquals(intData, restoredData);
}
@Test
public void testDataSerde() throws IOException {
List<String> strings = new ArrayList<>();
strings.add("one");
strings.add("two");
strings.add("three");
strings.add("four");
final String dataAsValue = "dataAsValue";
Data strData = Data.singletonList(KEY, strings, ValueType.STRING);
Data wrapppedData = Data.singleton(dataAsValue, strData);
File serFile = testDir.newFile();
wrapppedData.save(serFile);
Data restoredData = Data.fromFile(serFile);
Data expectedData = (Data)wrapppedData.get(dataAsValue);
Data actualData = (Data)restoredData.get(dataAsValue);
assertEquals(expectedData, actualData);
assertEquals(expectedData.get(KEY), actualData.get(KEY));
}
@Test
public void testMetaDataSerde() throws IOException {
List<String> strings = new ArrayList<>();
strings.add("one");
strings.add("two");
strings.add("three");
strings.add("four");
Data strData = Data.singletonList(KEY, strings, ValueType.STRING);
List<Long> numbers = new ArrayList<>();
for (long l = 0; l < 100; ++l) {
numbers.add(l);
}
Data numData = Data.singletonList("numData", numbers, ValueType.INT64);
strData.setMetaData(numData);
assertEquals(numData, strData.getMetaData());
File serFile = testDir.newFile();
strData.save(serFile);
Data restoredData = Data.fromFile(serFile);
assertEquals(numData, restoredData.getMetaData());
}
@Test
public void testBoundingBoxesCHWSerde() throws IOException {
BoundingBox boundingBox = new BBoxCHW(1.0, 2.0, 1.0, 2.0, "head", 7.0);
Data boxData = Data.singleton(KEY, boundingBox);
assertEquals(boundingBox, boxData.get(KEY));
File newFile = testDir.newFile();
boxData.save(newFile);
Data restoredData = Data.fromFile(newFile);
assertEquals(boxData.get(KEY), restoredData.get(KEY));
assertEquals(boxData, restoredData);
}
@Test
public void testBoundingBoxesXYSerde() throws IOException {
BoundingBox boundingBox = new BBoxXY(1.0, 2.0, 1.0, 2.0, "tail", 3.0);
Data boxData = Data.singleton(KEY, boundingBox);
assertEquals(boundingBox, boxData.get(KEY));
File newFile = testDir.newFile();
boxData.save(newFile);
Data restoredData = Data.fromFile(newFile);
assertEquals(boxData.get(KEY), restoredData.get(KEY));
assertEquals(boxData, restoredData);
}
@Test
public void testBoundingBoxesListSerde() throws IOException {
List<BoundingBox> boxes = new ArrayList<>();
for (double d = 0; d < 10; ++d) {
boxes.add(new BBoxXY(d, d, d+5, d+6, "testArea", 0.7));
}
Data boxesData = Data.singletonList(KEY, boxes, ValueType.BOUNDING_BOX);
boxesData.put("box", BoundingBox.create(0.5, 0.5, 1, 1, null, 1.0));
boxesData.put("box2", BoundingBox.create(0.5, 0.5, 1, 1, "label", null));
boxesData.put("box3", BoundingBox.createXY(0.5, 0.5, 1, 1, null, 1.0));
boxesData.put("box4", BoundingBox.createXY(0.5, 0.5, 1, 1, "label", null));
File newFile = testDir.newFile();
boxesData.save(newFile);
Data restoredData = Data.fromFile(newFile);
assertEquals(boxesData, restoredData);
}
@Test
public void testPointSerde() throws IOException {
Data d = Data.singleton("point", Point.create(0.1, 0.2, "foo", 1.0));
d.put("point2", Point.create(0.1, 0.2, 0.3));
d.putListPoint("pointList", Arrays.asList(
Point.create(0.9, 0.8, 0.7, 0.6, 0.4, 0.5),
Point.create(0.9, 0.8, "label", 0.0),
Point.create(0.9, 0.8, 0.7),
Point.create(0.1, 0.2, 0.3, "", 1.0)));
File newFile = testDir.newFile();
d.save(newFile);
Data restored = Data.fromFile(newFile);
assertEquals(d, restored);
}
}
|
Python
|
UTF-8
| 2,664 | 2.8125 | 3 |
[] |
no_license
|
import random
class Display(object):
def __init__(self, settings, screen):
self.settings = settings
self.screen = screen
self.place = self.map = self.origin_map = None
self.reset_data()
self.map_flag = False
def reset_data(self):
self.place = list()
self.map = list()
self.origin_map = list()
width = self.settings.block_width + self.settings.block_space
height = self.settings.block_height + self.settings.block_space
for i in range(self.settings.map_size):
self.place.append(list())
self.map.append(list())
self.origin_map.append(list())
for j in range(self.settings.map_size):
self.place[i].append((j * width + self.settings.block_space, i * height + self.settings.block_space))
self.map[i].append((j * width, i * height, self.settings.block_width, self.settings.block_height))
self.origin_map[i].append(self.map[i][j])
self.map[-1][-1] = tuple()
def draw(self):
for i in range(self.settings.map_size):
for j in range(self.settings.map_size):
if self.map[i][j] == () and not self.map_flag:
continue
self.screen.blit(self.settings.image, self.place[i][j],
self.origin_map[i][j] if self.map_flag else self.map[i][j])
def move(self, i, j):
for m in range(len(self.map)):
for n in range(len(self.map[i])):
if self.map[m][n] == ():
if m == i:
move = 1 if j > n else -1
for l in range(n, j, move):
self.map[i][l], self.map[i][l + move] = self.map[i][l + move], self.map[i][l]
elif n == j:
move = 1 if i > m else -1
for l in range(m, i, move):
self.map[l][j], self.map[l + move][j] = self.map[l + move][j], self.map[l][j]
return
def disrupt(self):
i = j = space = None
for m in range(len(self.map)):
for n in range(len(self.map[m])):
if self.map[m][n] == ():
space = [m, n]
for _ in range(1000):
flag = True
while flag:
i = random.randint(0, self.settings.map_size - 1)
j = random.randint(0, self.settings.map_size - 1)
if i == space[0] or j == space[1]:
space = [i, j]
flag = False
self.move(i, j)
|
Java
|
UTF-8
| 3,545 | 3.25 | 3 |
[] |
no_license
|
import java.util.ArrayList;
import java.util.Iterator;
public class FuzzySet extends ListSet {
ArrayList<Float> degreeValue;
public FuzzySet ()
{
super();
degreeValue = new ArrayList<Float>();
}
public FuzzySet (int values[] , ArrayList<Float> degree)
{
super(values);
degreeValue = new ArrayList<Float>();
Iterator<Float> iterate = degree.iterator();
while(iterate.hasNext())
{
degreeValue.add(iterate.next());
}
}
public FuzzySet (ArrayList<Integer> values , ArrayList<Float> degree)
{
super(values);
degreeValue = new ArrayList<Float>();
Iterator<Float> iterate = degree.iterator();
while(iterate.hasNext())
{
degreeValue.add(iterate.next());
}
}
public boolean containsAll(FuzzySet otherSet)
{
boolean container = false;
if (super.containsAll(otherSet.getSetClass()) && this.degreeValue.containsAll(otherSet.getDegreeValue()))
{
container = true;
}
return container;
}
public boolean addAll(FuzzySet values)
{
Iterator<Integer> iteratorInteger = values.iterator();
Iterator<Float> iteratorFloats = values.degreeValue.iterator();
FuzzySet newFuzzyset = new FuzzySet();
int integerValue;
float floatValue;
boolean someInterception = false;
while(iteratorInteger.hasNext())
{
integerValue = iteratorInteger.next();
floatValue = iteratorFloats.next();
if(this.contains(integerValue))
{
int index = this.getSetClass().indexOf(integerValue);
float valueOriginal = this.degreeValue.get(index);
if(valueOriginal <= floatValue && valueOriginal > 0.0)
{
/*Here we can check visualy if our results are good,because we'll see the values that are identical
* and which degree we got, should be always the min*/
System.out.println("Value:" + integerValue + " degree:" + valueOriginal + " " +"Value 2:" +
integerValue + " degree 2:" + floatValue);
newFuzzyset.add(integerValue);
newFuzzyset.degreeValue.add(valueOriginal);
someInterception = true;
}
else if (floatValue > 0.0 && floatValue < valueOriginal)
{
System.out.println("Value: " + integerValue + " degree: " + valueOriginal + " " +"Value 2: " +
integerValue + " degree 2: " + floatValue);
newFuzzyset.add(integerValue);
newFuzzyset.degreeValue.add(floatValue);
someInterception = true;
}
}
}
this.setSetClass(newFuzzyset.getSetClass());
this.degreeValue = newFuzzyset.degreeValue;
return someInterception;
}
public ArrayList<Float> getDegreeValue() {
return degreeValue;
}
public String toString ()
{
String string = "";
Iterator<Integer> iteratorInteger = this.iterator();
Iterator<Float> iteratorFloats = this.degreeValue.iterator();
while(iteratorInteger.hasNext())
{
string = string + "{" + iteratorInteger.next() + ":" + iteratorFloats.next() + "}" + " ";
}
return string;
}
}
|
PHP
|
UTF-8
| 5,367 | 2.859375 | 3 |
[
"MIT"
] |
permissive
|
<?php
declare(strict_types=1);
/**
* This file is part of the server-status package.
*
* (c) Roberto Martin <rmh.dev@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace ServerStatus\Tests\Domain\Model\Common\DateRange;
use ServerStatus\Domain\Model\Common\DateRange\DateRange;
use ServerStatus\Domain\Model\Common\DateRange\DateRangeCustom;
class DateRangeCustomTest extends DateRangeTestCase implements DateRangeInterfaceTest
{
/**
* @test
*/
public function isShouldReturnCorrectFromDate()
{
$from = new \DateTimeImmutable("2018-02-18T12:00:00+0200");
$to = new \DateTimeImmutable("2018-02-18T18:30:15+0200");
$dateRange = new DateRangeCustom($from, $to);
$this->assertEquals($from, $dateRange->from());
}
protected function createDateRange(\DateTimeInterface $date): DateRange
{
return new DateRangeCustom(
$date,
\DateTimeImmutable::createFromFormat(
DATE_ISO8601,
$date->format(DATE_ISO8601)
)->modify("+3000 seconds")
);
}
/**
* @test
*/
public function isShouldReturnCorrectToDate()
{
$from = new \DateTimeImmutable("2018-02-18T12:00:00+0200");
$to = new \DateTimeImmutable("2018-02-18T18:30:15+0200");
$dateRange = new DateRangeCustom($from, $to);
$this->assertEquals($to, $dateRange->to());
}
/**
* @test
*/
public function itShouldReturnName()
{
$dateRange = $this->createDateRange(new \DateTime("2018-02-19T12:00:00+0200"));
$this->assertEquals('custom', $dateRange->name());
}
/**
* @test
*/
public function itShouldReturnTheDateFormatted()
{
$from = new \DateTimeImmutable("2018-02-18T12:00:00+0200");
$to = new \DateTimeImmutable("2018-02-18T18:30:15+0200");
$dateRange = new DateRangeCustom($from, $to);
$this->assertEquals('2018-02-18 12:00:00, 2018-02-18 18:30:15', $dateRange->formatted());
}
/**
* @test
*/
public function itShouldBeAbleToCastToStringWithTheFormattedDate()
{
$from = new \DateTimeImmutable("2018-02-18T12:00:00+0200");
$to = new \DateTimeImmutable("2018-02-18T18:30:15+0200");
$dateRange = new DateRangeCustom($from, $to);
$this->assertEquals('2018-02-18 12:00:00, 2018-02-18 18:30:15', (string) $dateRange);
}
/**
* @test
*/
public function itShouldReturnTheNextDateRange()
{
$diff = new \DateInterval('PT3000S');
$from = new \DateTimeImmutable("2018-02-18T12:00:00+0200");
$to = $from->add($diff);
$dateRange = new DateRangeCustom($from, $to);
$expectedNext = new DateRangeCustom($to, $to->add($diff));
$this->assertEquals(
$expectedNext->from(),
$dateRange->next()->from(),
$dateRange->name() . ", " . $dateRange
);
$this->assertEquals(
$expectedNext->to(),
$dateRange->next()->to(),
$dateRange->name() . ", " . $dateRange
);
}
/**
* @test
*/
public function itShouldReturnThePreviousDateRange()
{
$diff = new \DateInterval('PT3000S');
$from = new \DateTimeImmutable("2018-02-18T12:00:00+0200");
$to = $from->add($diff);
$dateRange = new DateRangeCustom($from, $to);
$expectedPrevious = new DateRangeCustom($from->sub($diff), $from);
$this->assertEquals(
$expectedPrevious->from(),
$dateRange->previous()->from(),
$dateRange->name() . ", " . $dateRange
);
$this->assertEquals(
$expectedPrevious->to(),
$dateRange->previous()->to(),
$dateRange->name() . ", " . $dateRange
);
}
/**
* @test
* @expectedException \UnexpectedValueException
*/
public function itShouldThrowExceptionIfFromIsLowerThanTo()
{
$from = new \DateTimeImmutable("2018-02-18T12:00:00+0200");
new DateRangeCustom($from, $from->modify("-1 second"));
}
/**
* @test
* @expectedException \UnexpectedValueException
*/
public function itShouldThrowExceptionIfDatesAreEqual()
{
$from = new \DateTimeImmutable("2018-02-18T12:00:00+0200");
new DateRangeCustom($from, $from);
}
/**
* @test
* @expectedException \UnexpectedValueException
*/
public function itShouldThrowExceptionIfDatesHaveDifferentTimezones()
{
new DateRangeCustom(
new \DateTimeImmutable("2018-02-18T12:00:00+0200"),
new \DateTimeImmutable("2018-02-20T16:00:00+0100")
);
}
/**
* interval: 10 minutes
* @inheritdoc
*/
protected function expectedDateInterval(): \DateInterval
{
return new \DateInterval("PT600S");
}
/**
* @test
*/
public function itShouldReturnADateRageCollection()
{
$collection = new DateRangeCustom(
new \DateTimeImmutable("2018-02-18T12:00:00+0200"),
new \DateTimeImmutable("2018-02-18T16:00:00+0200")
);
$this->assertEquals(4 * (60 / 10), $collection->dateRanges()->count());
}
}
|
TypeScript
|
UTF-8
| 3,532 | 2.796875 | 3 |
[] |
no_license
|
import logger from 'logger'
import WebSocket from 'ws'
import Connection from './connection'
const BASE_URL = 'wss://ws.cobinhood.com/v2/ws'
const PING_INTERVAL = 1000 * 20
const HEARTBEAT_INTERVAL = 1000 * 30
export namespace CobinhoodConnectionTypes {
type OrderBookEntry = [string, string, string]
export type OrderBookData = {
asks: Array<OrderBookEntry>,
bids: Array<OrderBookEntry>
}
export type UpdateType = 'initial' | 'delta'
export type Message = {
h: [string, string, 'subscribed' | 's' | 'u' | 'pong' | 'error'],
d: OrderBookData
}
}
export default class CobinhoodConnection extends Connection {
private client!: WebSocket
private subscriptions: Set<string> = new Set()
private pingTimer: NodeJS.Timer | null = null
constructor () { super('cobinhood', HEARTBEAT_INTERVAL) }
protected connect (): void {
logger.debug(`[COBINHOOD]: Connecting to socket`)
this.client = new WebSocket(BASE_URL)
this.client.on('error', this.refreshConnection.bind(this, 'connectionerror'))
this.client.on('open', () => {
logger.debug(`[COBINHOOD]: Connection open`)
// TODO: Error handling
this.subscriptions.forEach(pair => {
logger.debug(`[COBINHOOD]: Resubscribing to ${pair}`)
this.subscribe(pair)
})
this.alive()
this.setPingInterval(PING_INTERVAL)
this.connectionOpened()
})
this.client.on('message', (m: string) => this.onMessage(JSON.parse(m)))
}
protected disconnect (): Promise<void> {
if (this.client && this.client.readyState !== WebSocket.CLOSED) {
logger.debug('[COBINHOOD]: Closing previous connection')
return new Promise((resolve) => {
try {
this.client.removeEventListener('message')
this.client.removeEventListener('off')
this.client.on('close', resolve)
this.client.close()
} catch (err) {
logger.debug(err.message, err)
this.client.off('close', resolve)
resolve()
}
})
}
return Promise.resolve()
}
private onMessage (message: CobinhoodConnectionTypes.Message): void {
this.alive()
const type = message.h[2]
if (type === 'error') {
logger.warn(`Message was errored ${JSON.stringify(message)}`)
this.refreshConnection('message error')
return
}
const market = message.h[0].split('.')[1].replace('-', '/')
switch (type) {
case 's':
this.emit('updateExchangeState', 'initial', market, message.d)
break
case 'u':
this.emit('updateExchangeState', 'delta', market, message.d)
break
case 'pong':
logger.debug('[COBINHOOD] Ponged')
break
}
}
subscribe (pair: string): Promise<void> {
logger.debug(`[COBINHOOD]: Subscribing to pair ${pair}`)
this.subscriptions.add(pair)
this.client.send(JSON.stringify({
action: 'subscribe',
type: 'order-book',
trading_pair_id: pair
}))
return Promise.resolve()
}
private setPingInterval (ms: number): void {
if (this.pingTimer) {
clearInterval(this.pingTimer)
}
this.pingTimer = setInterval(this.ping.bind(this), ms)
}
private ping (): void {
if (this.client.readyState !== WebSocket.OPEN) {
logger.warn('Connection seems to be closed during ping')
return
}
this.client.send(JSON.stringify({
action: 'ping'
}))
}
call (): Promise<void> {
throw new Error('[COBINHOOD]: call() implemented')
}
}
|
C++
|
UTF-8
| 337 | 2.65625 | 3 |
[] |
no_license
|
#ifndef OUTPUT_H
#define OUTPUT_H
#include <string>
class Model;
#include "model.h"
#include <thread>
class Output
{
public:
Output();
virtual ~Output(){}
virtual void print()=0;
auto getModel(){
return model;
}
std::thread mThread;
protected:
Model*model;
size_t count;
};
#endif // OUTPUT_H
|
Python
|
UTF-8
| 1,611 | 2.796875 | 3 |
[
"MIT"
] |
permissive
|
import util as util
import torch
import unittest
class TestUtil(unittest.TestCase):
def test_masked_max(self):
hiddens = torch.tensor([[[3, 3, 3, 3], [2, 2, 2, 7], [8, 8, 8, 8]],
[[1, 1, 17, 1], [9, 9, 9, 9], [11, 1, 11, 11]]])
lengths = torch.LongTensor([2, 3])
output = util.masked_max_from_lengths(hiddens, lengths)[0]
self.assertListEqual(output.tolist(), [[3, 3, 3, 7],
[11, 9, 17, 11]])
def test_masked_mean(self):
hiddens = torch.tensor([[[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]],
[[100, 100, 100, 100], [9, 9, 9, 9],
[11, 11, 11, 11]]])
lengths = torch.LongTensor([2, 3])
output = util.masked_mean_from_lengths(hiddens, lengths)
self.assertListEqual(output.tolist(), [[1.5, 1.5, 1.5, 1.5],
[40, 40, 40, 40]])
def test_get_length_mask(self):
mask = util.get_length_mask(torch.LongTensor([3, 1, 4]), 6)
self.assertListEqual(mask.tolist(), [[1, 1, 1, 0, 0, 0],
[1, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 0, 0]])
mask = util.get_length_mask(torch.LongTensor([3, 1, 4]), 6, flip=True)
self.assertListEqual(mask.tolist(), [[0, 0, 0, 1, 1, 1],
[0, 1, 1, 1, 1, 1],
[0, 0, 0, 0, 1, 1]])
if __name__ == '__main__':
unittest.main()
|
Python
|
UTF-8
| 335 | 2.8125 | 3 |
[] |
no_license
|
from shapes import Paper , Rectangle
paper = Paper()
rect = Rectangle()
rect.set_color('yellow')
rect.set_height(50)
rect.set_width(150)
rect.draw()
rect.set_x(0)
rect.set_y(0)
rect2 = Rectangle()
rect2.set_color('blue')
rect2.set_height(10)
rect2.set_width(10)
rect2.draw()
rect2.set_x(150)
rect2.set_y(200)
paper.display()
|
Java
|
UTF-8
| 3,052 | 1.679688 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2014-2015 by Cloudsoft Corporation Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package clocker.docker.entity.container.application;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import clocker.docker.entity.DockerHost;
import clocker.docker.entity.container.DockerContainer;
import clocker.docker.entity.util.DockerAttributes;
import clocker.docker.entity.util.DockerUtils;
import clocker.docker.location.DockerContainerLocation;
import com.google.common.base.Objects;
import com.google.common.base.Predicates;
import com.google.common.collect.Iterables;
import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
public class VanillaDockerApplicationImpl extends SoftwareProcessImpl implements VanillaDockerApplication {
private static final Logger LOG = LoggerFactory.getLogger(VanillaDockerApplicationImpl.class);
@Override
public String getIconUrl() { return "classpath://container.png"; }
public String getDisplayName() {
return String.format("Container (%s)",
Objects.firstNonNull(sensors().get(DockerContainer.DOCKER_CONTAINER_NAME), config().get(IMAGE_NAME)));
}
@Override
protected void connectSensors() {
connectServiceUpIsRunning();
super.connectSensors();
}
@Override
protected void postStart() {
super.postStart();
// Refresh (or set) the container port sensors
DockerUtils.getContainerPorts(this);
}
@Override
protected void disconnectSensors() {
super.disconnectSensors();
disconnectServiceUpIsRunning();
}
@Override
public void rebind() {
super.rebind();
disconnectSensors();
connectSensors();
}
@Override
public Class<? extends VanillaDockerApplicationDriver> getDriverInterface() {
return VanillaDockerApplicationDriver.class;
}
@Override
public DockerContainer getDockerContainer() {
DockerContainerLocation location = (DockerContainerLocation) Iterables.find(getLocations(), Predicates.instanceOf(DockerContainerLocation.class));
return location.getOwner();
}
@Override
public DockerHost getDockerHost() {
return getDockerContainer().getDockerHost();
}
@Override
public String getDockerfile() {
return config().get(DOCKERFILE_URL);
}
@Override
public List<Integer> getContainerPorts() {
return config().get(DockerAttributes.DOCKER_OPEN_PORTS);
}
}
|
Java
|
UTF-8
| 2,524 | 2.09375 | 2 |
[] |
no_license
|
package com.example.javapwpb;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText txtNamaDepan,txtNamaBelakang;
TextView txtOutput;
Button btnTampil;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtNamaDepan = (EditText) findViewById(R.id.txtNamaDepan);
txtNamaBelakang= (EditText) findViewById(R.id.txtNamaBelakang);
txtOutput= (TextView) findViewById(R.id.txtOutput);
btnTampil= (Button) findViewById(R.id.btnTampil);
btnTampil.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String namaDepan = txtNamaDepan.getText().toString();
String namaBelakagan = txtNamaBelakang.getText().toString();
String output = namaDepan + " " + namaBelakagan;
txtOutput.setText(output);
}
});
findViewById(R.id.btn_hitung_luas).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent luas = new Intent(MainActivity.this, HitungLuasActivity.class);
startActivity(luas);
}
});
findViewById(R.id.btn_kalkulator).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent kalkulator = new Intent(MainActivity.this, KalkulatorActivity.class);
startActivity(kalkulator);
}
});
findViewById(R.id.konversi_suhu).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent suhu = new Intent(MainActivity.this, KonversiSuhuActivity.class);
startActivity(suhu);
}
});
findViewById(R.id.kalkulator_button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent btn_kalkulator = new Intent(MainActivity.this, SecondCalculatorActivity.class);
startActivity(btn_kalkulator);
}
});
}
}
|
Java
|
UTF-8
| 5,499 | 2.109375 | 2 |
[] |
no_license
|
package com.finki.mobilniproekt;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseNetworkException;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class SignInWithMailActivity extends AppCompatActivity {
private EditText email;
private EditText password;
private Button signInButton;
private TextInputLayout emailLayout;
private TextInputLayout passwordLayout;
private FirebaseAuth mAuth;
ProgressDialog progressDialog;
private AdView mAdView;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sign_in_with_mail_layout);
email = findViewById(R.id.emailSignInInfo);
password = findViewById(R.id.passwordSignInInfo);
signInButton = findViewById(R.id.signInProceedBtn);
emailLayout = findViewById(R.id.emailSignInInfoErrorLayout);
passwordLayout = findViewById(R.id.passwordSignInInfoErrorLayout);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading....");
mAuth = FirebaseAuth.getInstance();
mAdView = findViewById(R.id.adViewMail);
//test : ca-app-pub-3940256099942544/6300978111
//my : ca-app-pub-2112536401499963/1376229189
//mAdView.setAdUnitId("ca-app-pub-3940256099942544/6300978111");
//AdRequest adRequest = new AdRequest.Builder().build();
//mAdView.loadAd(adRequest);
signInButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(validateInput())
{
mAuth.signInWithEmailAndPassword(email.getText().toString(), password.getText().toString())
.addOnCompleteListener(SignInWithMailActivity.this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
FirebaseUser user = mAuth.getCurrentUser();
progressDialog.hide();
Intent intentToMainMenu = new Intent(SignInWithMailActivity.this,MainMenuActivity.class);
startActivity(intentToMainMenu);
Toast.makeText(SignInWithMailActivity.this, "Welcome "+user.getEmail().split("@")[0],
Toast.LENGTH_LONG).show();
} else {
// If sign in fails, display a message to the user.
Log.e("exception", task.getException().toString());
progressDialog.hide();
if(task.getException() instanceof FirebaseNetworkException){
Toast.makeText(SignInWithMailActivity.this, "Internet connection problem.",
Toast.LENGTH_SHORT).show();
}
else {
emailLayout.setError("Invalid username or password");
passwordLayout.setError("Invalid username or password");
Toast.makeText(SignInWithMailActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
}
// ...
}
});
}
}
});
}
public boolean validateInput(){
if(email.getText().toString().isEmpty() || password.getText().toString().isEmpty() )
{
if(email.getText().toString().isEmpty())
emailLayout.setError("Required field.");
else
emailLayout.setError(null);
if(password.getText().toString().isEmpty())
passwordLayout.setError("Required field.");
else
passwordLayout.setError(null);
Toast.makeText(SignInWithMailActivity.this,"Please fill all required fields.",Toast.LENGTH_LONG).show();
return false;
}
emailLayout.setError(null);
passwordLayout.setError(null);
progressDialog.show();
return true;
}
}
|
TypeScript
|
UTF-8
| 1,260 | 3.265625 | 3 |
[
"MIT"
] |
permissive
|
module lazyness {
function lazyFind<T>(arr: T[], filter: (i: T) => boolean): T {
let hero: T | null = null;
const proxy = new Proxy(
{},
{
get: (obj, prop) => {
console.log("Filtering...");
if (!hero) {
hero = arr.find(filter) || null;
}
return hero ? (hero as any)[prop] : null;
}
}
);
return proxy as any;
}
const heroes = [
{
name: "Spiderman",
powers: [
"wall-crawling",
"enhanced strength",
"enhanced speed",
"spider-Sense"
]
},
{
name: "Superman",
powers: [
"flight",
"superhuman strength",
"x-ray vision",
"super-speed"
]
}
];
console.log("A");
const spiderman = lazyFind(heroes, (h) => h.name === "Spiderman");
console.log("B");
console.log(spiderman.name);
console.log("C");
/*
A
B
Filtering...
Spiderman
C
*/
}
|
JavaScript
|
UTF-8
| 1,666 | 2.5625 | 3 |
[] |
no_license
|
const mysql = require('mysql2/promise');
const pool = mysql.createPool({
host: 'localhost',
port: 3306,
user: 'admin',
password: 'hello',
database: 'es_starter'
}); //maybe should be const options
const connection = pool;
class User {
constructor(username, hash, salt) {
//this.user_id = user_id;
this.username = username;
this.hash = hash;
this.salt = salt;
}
static findOne(username) {
//console.log(username + " from line 25 database.js")
return connection.execute(
"SELECT * FROM users WHERE username = ?", [username]
)
};
static findById(id) {
return connection.execute(
"SELECT user_id, username, hash, salt, admin FROM users WHERE user_id = ?", [id]
)
};
save() {
/* return connection.execute(
"INSERT INTO users (username, hash, salt) VALUES (?, ?, ?)", [this.username, this.hash, this.salt] //do i need to use 'this'?
) */
try {
return connection.execute(
"INSERT INTO users (username, hash, salt, admin) VALUES (?, ?, ?)", [this.username, this.hash, this.salt, this.admin] //do i need to use 'this'?,
).catch(e => {
console.log('error', e);
});
} catch (e) {
console.log('error', e);
}
}
}
/* module.exports = {
connection: connection,
User: User,
pool: pool
}; */
module.exports.connection = connection;
module.exports.pool = pool;
/*pool and connection are kinda sorta redundant but why not?*/
module.exports.User = User;
|
C#
|
UTF-8
| 1,209 | 2.828125 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace CodeNameTwang.Views
{
public class MenuItem:INotifyPropertyChanged
{
public MenuItem()
{
TargetType = typeof(MenuItem);
}
public int Id { get; set; }
public string Title { get; set; }
public Type TargetType { get; set; }
private string myVar;
public string notification
{
get { return myVar; }
set { myVar = value; OnPropertyChanged(); }
}
public Page OnLoad() {
return (Page)Activator.CreateInstance(TargetType);
}
#region INotifyPropertyChanged Implementation
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
if (PropertyChanged == null)
return;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
}
|
Java
|
UTF-8
| 381 | 1.976563 | 2 |
[] |
no_license
|
package mx.ssmxli.food.repository;
import mx.ssmxli.food.entity.Recibo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.io.Serializable;
@Repository("reciboRepository")
public interface ReciboRepository extends JpaRepository<Recibo, Serializable> {
public abstract Recibo findReciboById(int id);
}
|
Python
|
UTF-8
| 11,666 | 3.40625 | 3 |
[
"MIT"
] |
permissive
|
from enum import Enum
class LaserPathType(Enum):
hit = "hit"
bounce = "bounce"
through = "pass"
# destroy = "destroy"
class MoveType(Enum):
rotate = "ROTATE"
move = "MOVE"
swap = "SWAP"
class TeamColor(Enum):
red = "red"
silver = "silver"
blank = "blank"
@staticmethod
def opposite_color(color):
if color is TeamColor.blank:
return TeamColor.blank
elif color is TeamColor.silver:
return TeamColor.red
else:
return TeamColor.silver
class Orientation(Enum):
"""Class for orientations"""
up = 0
left = 270
right = 90
down = 180
none = -1
@staticmethod
def from_position(position1, position2):
return Orientation.up
@staticmethod
def next_position(position, direction):
if direction is Orientation.up:
return Position(position.x, position.y - 1)
if direction is Orientation.down:
return Position(position.x, position.y + 1)
if direction is Orientation.left:
return Position(position.x - 1, position.y)
if direction is Orientation.right:
return Position(position.x + 1, position.y)
@staticmethod
def delta(orientation, delta):
delta %= 360
if orientation is Orientation.none:
return Orientation.none
else:
if orientation.value + delta < 0:
return Orientation((orientation.value + 360 + delta) % 360)
else:
return Orientation((orientation.value + delta) % 360)
class Position(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return "(" + str(self.x) + "," + str(self.y) + ")"
def to_dictionary(self):
return {"x": self.x, "y": self.y}
@staticmethod
def from_dictionary(value):
return Position(value["x"], value["y"])
class PieceType(Enum):
"""Class for piece types and valid orientations"""
pharaoh = "pharaoh"
anubis = "anubis"
pyramid = "pyramid"
scarab = "scarab"
sphinx = "sphinx"
@staticmethod
def can_move(from_piece, to_piece):
"""
Determine if a move is valid
:param from_piece: Square
:param to_piece: Square
:return: Boolean
"""
# Check Place Color (square we are entering is blank or same color)
if to_piece.color is not TeamColor.blank and from_piece.piece.color is not to_piece.color:
return False
# Make sure it's a movable piece
if from_piece.piece.type is PieceType.sphinx:
return False
# Make sure pieces are swappable
if to_piece.piece is not None:
# scarab can swap with pyramid and anubis
if from_piece.piece.type is PieceType.scarab:
if to_piece.piece.type is PieceType.pyramid or to_piece.piece.type is PieceType.anubis:
return True
else:
return False
else:
return False
else:
return True
@staticmethod
def can_rotate(piece, target_orientation):
"""
Returns true if a piece can rotate
:param piece: Piece
:param target_orientation: Orientation
:return: Boolean
"""
if target_orientation is Orientation.none:
return False
if abs(piece.orientation.value - target_orientation.value) == 180: # 270 or 90 are the allowed values
return False
if piece.type is PieceType.sphinx:
if piece.color is TeamColor.silver:
return target_orientation is Orientation.down or target_orientation is Orientation.right
else:
return target_orientation is Orientation.up or target_orientation is Orientation.left
return True
@staticmethod
def bounce_direction(piece, light_direction):
if piece.type is PieceType.pyramid:
if light_direction is Orientation.up:
if piece.orientation is Orientation.down:
return Orientation.left
elif piece.orientation is Orientation.right:
return Orientation.right
else:
return None
elif light_direction is Orientation.down:
if piece.orientation is Orientation.left:
return Orientation.left
elif piece.orientation is Orientation.up:
return Orientation.right
else:
return None
elif light_direction is Orientation.left:
if piece.orientation is Orientation.right:
return Orientation.down
elif piece.orientation is Orientation.up:
return Orientation.up
else:
return None
elif light_direction is Orientation.right:
if piece.orientation is Orientation.down:
return Orientation.down
elif piece.orientation is Orientation.left:
return Orientation.up
else:
return None
if piece.type is PieceType.scarab:
if piece.orientation is Orientation.down or piece.orientation is Orientation.up:
if light_direction is Orientation.up:
return Orientation.left
elif light_direction is Orientation.down:
return Orientation.right
elif light_direction is Orientation.left:
return Orientation.up
elif light_direction is Orientation.right:
return Orientation.down
elif piece.orientation is Orientation.left or piece.orientation is Orientation.right:
if light_direction is Orientation.up:
return Orientation.right
elif light_direction is Orientation.down:
return Orientation.left
elif light_direction is Orientation.left:
return Orientation.down
elif light_direction is Orientation.right:
return Orientation.up
return None
@staticmethod
def valid_rotations(piece):
current_orientation = piece.orientation
if piece.type is PieceType.pharaoh:
return []
elif piece.type is PieceType.sphinx:
if current_orientation is Orientation.down:
return [Orientation.right]
elif current_orientation is Orientation.right:
return [Orientation.down]
elif current_orientation is Orientation.up:
return [Orientation.left]
else:
return [Orientation.up]
else:
return [Orientation.delta(current_orientation, -90), Orientation.delta(current_orientation, 90)]
@staticmethod
def can_swap(piece_from, piece_to):
if piece_from.type is PieceType.sphinx:
return False
if piece_to is None:
return True
return piece_from.type is PieceType.scarab and \
(piece_to.type is PieceType.pyramid or piece_to.type is PieceType.anubis)
class LaserPathNode(object):
def __init__(self, path_type, position, direction):
self.type = path_type
self.position = position
self.direction = direction
def to_dictionary(self):
return {
"type": self.type.value,
"position": self.position.to_dictionary(),
"direction": self.direction.value
}
@staticmethod
def from_dictionary(value):
path_type = LaserPathType(value["type"])
position = Position.from_dictionary(value["position"])
direction = Orientation(value["direction"])
return LaserPathNode(path_type, position, direction)
def __str__(self):
return "( " + str(self.type.value) + ", " + str(self.position) + ", " + str(self.direction.value) + ")"
class Move(object):
def __init__(self, move_type, move_position, move_value):
self.type = move_type
self.position = move_position
self.value = move_value
def to_dictionary(self):
value = self.value
if isinstance(value, Position):
value = value.to_dictionary()
if isinstance(value, Orientation):
value = value.value
return {"type": self.type.value, "position": self.position.to_dictionary(), "value": value}
@staticmethod
def from_dictionary(value):
move_type = MoveType(value["type"])
position = Position(value["position"]["x"], value["position"]["y"])
value = value["value"] # Notice the aliasing...
if move_type is not MoveType.rotate:
value = Position(value["x"], value["y"])
else:
value = Orientation(value)
return Move(move_type, position, value)
def __str__(self):
return "{ T: " + str(self.type.value) + ", P: " + str(self.position) + ", V: " + str(self.value) + "}"
class Piece(object):
"""Generic Piece Class"""
def __init__(self, piece_type, color, orientation=Orientation.none):
self.color = color
self.type = piece_type
self.orientation = orientation
def to_dictionary(self):
return {"type": self.type.value, "color": self.color.value, "orientation": self.orientation.value}
@staticmethod
def from_dictionary(value):
return Piece(PieceType(value["type"]), TeamColor(value["color"]), Orientation(value["orientation"]))
def __str__(self):
return "(" + str(self.color.value) + "," + str(self.type.value) + "," + str(self.orientation.value) + ")"
class Square(object):
def __init__(self, square_type, position):
self.color = square_type
self.piece = None
self.position = position
def get_moves(self, board):
if self.piece is None:
return []
# Get Squares
squares = [board.get(self.position.x + 1, self.position.y),
board.get(self.position.x - 1, self.position.y),
board.get(self.position.x, self.position.y + 1),
board.get(self.position.x, self.position.y - 1),
board.get(self.position.x + 1, self.position.y - 1),
board.get(self.position.x + 1, self.position.y + 1),
board.get(self.position.x - 1, self.position.y + 1),
board.get(self.position.x - 1, self.position.y - 1)]
squares = [x for x in squares if x is not None and (x.color is TeamColor.blank or x.color is self.piece.color)]
moves = []
# Get Valid Moves
for square in squares:
if PieceType.can_swap(self.piece, square.piece):
if square.piece is None:
moves.append(Move(MoveType.move, self.position, square.position))
else:
moves.append(Move(MoveType.swap, self.position, square.position))
# Get Valid Rotations
rotations = PieceType.valid_rotations(self.piece)
for rotation in rotations:
moves.append(Move(MoveType.rotate, self.position, rotation))
return moves
def to_dictionary(self):
value = {"position": self.position.to_dictionary(), "color": self.color.value}
if self.piece is not None:
value["piece"] = self.piece.to_dictionary()
return value
|
Python
|
UTF-8
| 191 | 3.296875 | 3 |
[] |
no_license
|
a = [0,1]
a.append(3)
a.append(4)
for loopStart in a :
print(loopStart)
myMap = {7 :"Hola" 8:"Adios"}
for element in myMap
print("key" + str(element)+ "value"+ str(myMap))
|
Markdown
|
UTF-8
| 2,898 | 3.171875 | 3 |
[
"MIT"
] |
permissive
|
# Live code coverage
[](https://travis-ci.org/matthiasnoback/live-code-coverage)
This library should help you generate code coverage reports on a live server (it doesn't have to be a production server of course).
Install this library using:
```bash
composer require matthiasnoback/live-code-coverage
```
## Collecting code coverage data
In your front controller (e.g. `index.php`), add the following:
```php
<?php
use LiveCodeCoverage\LiveCodeCoverage;
$shutDownCodeCoverage = LiveCodeCoverage::bootstrap(
(bool)getenv('CODE_COVERAGE_ENABLED'),
__DIR__ . '/../var/coverage',
__DIR__ . '/../phpunit.xml.dist'
);
// Run your web application now...
// This will save and store collected coverage data:
$shutDownCodeCoverage();
```
- The first argument passed to `LiveCodeCoverage::bootstrap()` is a boolean that will be used to determine if code coverage is enabled at all. The example shows how you can use an environment variable for that.
- The second argument is the directory where all the collected coverage data will be stored (`*.cov` files). If this directory doesn't exist yet, it will be created.
- The third argument is the path to a PHPUnit configuration file. Its `<filter>` section will be used to configure the code coverage whitelist. For example, this `phpunit.xml.dist` file might look something like this:
```xml
<?xml version="1.0" encoding="utf-8"?>
<phpunit>
<filter>
<whitelist>
<directory suffix=".php">src</directory>
</whitelist>
</filter>
</phpunit>
```
Most configuration directives that are [available in PHPUnit](https://phpunit.de/manual/current/en/appendixes.configuration.html#appendixes.configuration.whitelisting-files) work for this library too.
If you notice that something doesn't work, please submit an issue.
If you don't provide a PHPUnit configuration file, no filters will be applied, so you will get a coverage report for all the code in your project, including vendor and test code if applicable.
If your application is a legacy application which `exit()`s or `die()`s before execution reaches the end of your front controller, the bootstrap should be slightly different:
```php
$shutDownCodeCoverage = LiveCodeCoverage::bootstrap(
// ...
);
register_shutdown_function($shutDownCodeCoverage);
// Run your web application now...
```
## Generating code coverage reports (HTML, Clover, etc.)
To merge all the coverage data and generate a report for it, install Sebastian Bergmann's [`phpcov` tool](https://github.com/sebastianbergmann/phpcov). Run it like this (or in any other way you like):
```bash
phpcov merge --html=./coverage/html ./var/coverage
```
## Downsides
Please note that collecting code coverage data will make your application run much slower. Just see for yourself if that's acceptable.
|
Markdown
|
UTF-8
| 1,212 | 2.65625 | 3 |
[] |
no_license
|
---
title: Glacier Connector FAQ
---
Here are the answers to some frequently asked questions.
## Why can't I create an **Archive** or **Restore** rule in a Records Management site?
The **Archive** or **Restore** rule isn't available on a folder when creating a rule on a Records Management site. To move declared records from S3 to Amazon S3 Glacier, they must first be declared as Easy Access records from a collaboration site. You can then configure the **Archive** or **Restore** rule on the folder in the collaboration site.
> **Note:** The **Archive** and **Restore** action is available using the v1 REST API and is displayed as an action in the rules engine for Alfresco Content Services.
## Why can't I view the content of the Record version of a file?
When a file is 'Declared version as record' the record created has the same internal content url as the file. If the original file has been archived, the declared as version node has not been marked as archived in Alfresco Content Services. For the Record version file you won't receive the message stating the content has been archived.
> **Note:** See additional information in the [S3 Connector FAQs]({% link aws-s3/latest/using/faq.md %}).
|
SQL
|
UTF-8
| 402 | 4.03125 | 4 |
[] |
no_license
|
SELECT de.emp_no, dm.emp_no manager_no, s1.salary emp_salary, s2.salary manager_salary
FROM dept_emp de
INNER JOIN dept_manager dm
ON de.dept_no = dm.dept_no
INNER JOIN salaries s1
ON de.emp_no = s1.emp_no
INNER JOIN salaries s2
ON dm.emp_no = s2.emp_no
WHERE s1.salary > s2.salary
AND de.to_date = '9999-01-01'
AND dm.to_date = '9999-01-01'
AND s1.to_date = '9999-01-01'
AND s2.to_date = '9999-01-01';
|
Python
|
UTF-8
| 1,302 | 2.640625 | 3 |
[] |
no_license
|
import pandas as pd
import streamlit as st
import numpy as np
from pandas import DataFrame
from pmdarima import auto_arima
def AutoARIMA(df, type, split):
data = df.sort_index(ascending=True, axis=0)
train = data[:split]
valid = data[split:]
training = train[type]
validation = valid[type]
model = auto_arima(training, start_p=1, start_q=1, max_p=3, max_q=3, m=12, start_P=0, seasonal=True, d=1, D=1,
trace=True, error_action='ignore', suppress_warnings=True)
model.fit(training)
forecast = model.predict(len(df)-split)
forecast = pd.DataFrame(forecast, index=valid.index, columns=['Prediction'])
rmse = np.sqrt(np.mean(np.power((np.array(valid[type]) - np.array(forecast['Prediction'])), 2)))
st.write('RMSE value on validation set:')
st.write(rmse)
append_data = DataFrame(data={type: [], 'Predictions': []})
append_data[type] = training
append_data['Predictions'] = training
append_data_2 = DataFrame(data={type: [], 'Predictions': []})
append_data_2[type] = validation
append_data_2['Predictions'] = forecast['Prediction']
pic = pd.concat([append_data[[type, 'Predictions']], append_data_2[[type, 'Predictions']]], axis=0)
st.line_chart(pic)
|
Ruby
|
UTF-8
| 1,322 | 2.890625 | 3 |
[] |
no_license
|
require_relative 'base_scrapper'
require 'nokogiri'
require 'open-uri'
require_relative 'table'
require_relative 'github_worker'
require_relative 'does_not_include'
class GithubRepoScrapper < BaseScrapper
attr_accessor :user_list, :table
def initialize(user_list, workers_count = 3)
super workers_count
self.user_list = user_list
self.headers['User-Agent'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.94 Safari/537.36'
@table = Table.new({})
self.data = @table
end
def execute_scrapper
puts self.user_list
self.user_list.each do |user|
self.get_user_repos user
end
self.run_workers
end
def get_user_repos(user)
self.headers['Referer'] = "https://github.com/#{user}"
self.headers['Host'] = 'github.com'
uri = "https://github.com/#{user}?tab=repositories"
repo_page = Nokogiri::HTML(open(uri, self.headers))
selected_repos = repo_page.css('a').map{|anchor| anchor['href']}.select { |link| link.start_with? "/#{user}/" and link.does_not_include? 'stargazers' and link.does_not_include? 'network'}
self.add_links selected_repos
end
end
#Demo
user_list = ['tacaswell', 'bossiernesto', 'flbulgarelli']
scrapper = GithubRepoScrapper.new(user_list, 3)
scrapper.execute_scrapper
|
C#
|
UTF-8
| 1,984 | 2.734375 | 3 |
[] |
no_license
|
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Threading.Tasks;
using Zapchastulkin.Models;
namespace Zapchastulkin.Controllers
{
[ApiController]
[Route("api/units")]
public class UnitController : Controller
{
ApplicationContext db;
public UnitController(ApplicationContext context)
{
db = context;
}
[HttpGet]
public async Task<ActionResult<IEnumerable<Unit>>> Get()
{
return Ok(await db.Units.ToListAsync());
}
[HttpGet("{unitId}")]
public async Task<ActionResult<IEnumerable<Product>>> Get(int unitId)
{
Unit unit = await db.Units
.Include(unit => unit.Products)
.FirstOrDefaultAsync(unit => unit.Id == unitId);
if (unit == null)
NotFound();
return Ok(unit);
}
[HttpPost]
public async Task<IActionResult> Post(Unit unit)
{
if (ModelState.IsValid)
{
Category category = await db.Categories.FirstOrDefaultAsync(category => category.Id == unit.CategoryId);
if (category != null)
{
db.Units.Add(unit);
await db.SaveChangesAsync();
return Ok(unit);
}
}
return BadRequest(ModelState);
}
[HttpPut]
public async Task<ActionResult> Put(Unit unit)
{
if (ModelState.IsValid)
{
db.Update(unit);
await db.SaveChangesAsync();
return Ok(unit);
}
return BadRequest(ModelState);
}
[HttpDelete("{id}")]
public async Task<ActionResult> Delete(int id)
{
await db.DeleteUnitAsync(id);
return Ok();
}
}
}
|
Shell
|
UTF-8
| 361 | 3.640625 | 4 |
[] |
no_license
|
#!/bin/bash
set -e
CURRENT_DIR=$(cd $(dirname $0) ; pwd)
SRC_FILE="$1"
TARGET_FILE="$2"
if [ -e "$TARGET_FILE" ] || [ -L "$TARGET_FILE" ] ; then
echo "Backing up $TARGET_FILE"
mv "$TARGET_FILE" "$TARGET_FILE.$(date '+%Y-%m-%d-%H:%M:%S').backup"
fi
echo "$SRC_FILE -> $TARGET_FILE"
mkdir -p "$(dirname $TARGET_FILE)"
ln -s "$SRC_FILE" "$TARGET_FILE"
|
Java
|
UTF-8
| 14,185 | 2.6875 | 3 |
[] |
no_license
|
package courtreferences.model;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import courtreferences.southafrica.SouthAfricanCourtDocument;
public class CaseDetailsModel {
/*
* This model file contains methods which facilitate db interaction for CaseDetails Table
*/
public static void insertCaseDetails(CourtDocument saf){
/*
* Inserts new case into the CaseDetails Table
*/
ConnectionHandler connHandler = new ConnectionHandler();
String insertCaseDetailsQuery = "insert into CaseDetails(CountryId, CourtId, CaseId, ParticipantsName, DecisionDate, HeardDate, ProcessedDate, ProcessedUser, Status, SourceFileName, DuplicateofCase) values(?,?,?,?,?,?,?,?,?,?,?)";
String dummy = "insert into CaseDetails(CountryId, CourtId, CaseId, ParticipantsName, DecisionDate, HeardDate, ProcessedDate, ProcessedUser, Status, SourceFileName, DuplicateofCase) values(";
String selectCaseIdQuery = "select max(CaseRefId) from CaseDetails";
try {
PreparedStatement prep = connHandler.getConnection().prepareStatement(insertCaseDetailsQuery);
prep.setInt(1, saf.getCountryId());
dummy+=saf.getCountryId()+",";
prep.setInt(2, saf.getCourtId());
dummy+=saf.getCourtId()+",";
prep.setString(3, saf.getCaseId());
//System.out.println("Caseid="+saf.getCaseId());
dummy+=saf.getCaseId()+",";
if(saf.getParticipantsName()!=null)
{
prep.setString(4, saf.getParticipantsName().replaceAll("\r\n", " ").trim());
dummy+=saf.getParticipantsName().replaceAll("\r\n", " ").trim()+",";
}
else{
prep.setString(4, saf.getParticipantsName());
dummy+=saf.getParticipantsName()+",";
}
prep.setString(5, saf.getDecisionDate());
dummy+=saf.getDecisionDate()+",";
prep.setString(6, saf.getHeardDate());
dummy+=saf.getHeardDate()+",";
prep.setDate(7, saf.getProcessedDate());
dummy+=saf.getProcessedDate()+",";
prep.setString(8, saf.getProcessedUser());
dummy+=saf.getProcessedUser()+",";
prep.setString(9, saf.getStatus());
dummy+=saf.getStatus()+",";
prep.setString(10, saf.getSourceFileName());
dummy+=saf.getSourceFileName()+",";
prep.setInt(11, saf.getDuplicateCaseof());
dummy+=saf.getDuplicateCaseof()+",";
//System.out.println(dummy);
prep.executeUpdate();
Statement st = connHandler.getConnection().createStatement();
ResultSet rs = st.executeQuery(selectCaseIdQuery);
if(rs.next())
saf.setCaseRefId(rs.getInt(1));
}
catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("Exception while writing Doc to DB : "+e.getMessage());
e.printStackTrace();
}catch(Exception e){
System.out.println("Exception while writing Doc to DB : "+e.getMessage());
e.printStackTrace();
}
}
public static String retrieveParticipantsName(List<String> participantsName){
/*
* Converts multi-line participants name into a single line String
*/
StringBuffer participantsNameBuffer = new StringBuffer();
for(String participant : participantsName){
participantsNameBuffer.append(participant);
participantsNameBuffer.append("\t");
}
return participantsNameBuffer.toString();
}
public static int retrieveCountryID(String countryName){
/*
* Gets CountryName as input and finds corresponding CountryId
*/
ConnectionHandler connHandler = new ConnectionHandler();
Connection conn = connHandler.getConn();
String countryIdQuery = "select CountryId from CountryDetails where CountryName = '" + countryName + "'";
try{
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(countryIdQuery);
if(rs.next()){
return rs.getInt(1);
}
}
catch(SQLException sc){
System.out.println("SQL Exception : " + sc.getMessage());
}
catch(Exception ex){
System.out.println("Exception : " + ex.getMessage());
}
return -1;
}
public static int retrieveCourtID(int countryId, String courtName){
/*
* Gets the CountryId and CourtName as input and finds the corresponding court id
*/
ConnectionHandler connHandler = new ConnectionHandler();
Connection conn = connHandler.getConn();
String courtIdQuery = "select CourtId from CourtDetails where CourtName = '" + courtName + "' and CountryId = " + countryId;
try{
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(courtIdQuery);
if(rs.next()){
return rs.getInt(1);
}
}
catch(SQLException sc){
System.out.println("SQL Exception : " + sc.getMessage());
}
catch(Exception ex){
System.out.println("Exception : " + ex.getMessage());
}
return -1;
}
private static List<CourtDocument> selectCases(String inputQuery){
/*
* Extracts cases matching constraints specified in inputQuery
* Output is the list of CaseDetails which is of type CourtDocument
* NOTE : CourtDocument should always be the super class of any specific Country Document
*/
List<CourtDocument> unprocessedRecords = new ArrayList<CourtDocument>();
ConnectionHandler connHandler = new ConnectionHandler();
Connection conn = connHandler.getConn();
try{
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(inputQuery);
while(rs.next()){
CourtDocument hc = new CourtDocument();
hc.setCaseRefId(rs.getInt(1));
hc.setCountryName(rs.getString(2));
hc.setCourtId(rs.getInt(3));
hc.setCourtName(rs.getString(4));
hc.setCaseId(rs.getString(5));
hc.setParticipantsName(rs.getString(6));
hc.setDecisionDate(rs.getString(7));
hc.setHeardDate(rs.getString(8));
hc.setProcessedDate(rs.getDate(9));
hc.setProcessedUser(rs.getString(10));
hc.setSourceFileName(rs.getString(11));
unprocessedRecords.add(hc);
}
}
catch(SQLException sc){
System.out.println("SQL Exception : " + sc.getMessage());
}
catch(Exception ex){
System.out.println("Exception : " + ex.getMessage());
}
return unprocessedRecords;
}
public static List<CourtDocument> selectUnprocessedRecords(){
/*
* This method fetches the records which were not processed and confirmed by the user
* Records in the CaseDetails table with 'Status' field set to 'N'
* 'N' - specifies unprocessed records
* 'Y' - specifies processed records
*/
/*Ashmit-update
* include courtid in the output result
* */
String unprocessedRecordsQuery = "select CaseDetails.CaseRefId, CountryDetails.CountryName, CourtDetails.CourtId,CourtDetails.CourtName, CaseDetails.CaseId, CaseDetails.ParticipantsName, CaseDetails.DecisionDate, CaseDetails.HeardDate, CaseDetails.ProcessedDate, CaseDetails.ProcessedUser, CaseDetails.SourceFileName from CaseDetails inner join CountryDetails on CaseDetails.CountryId = CountryDetails.CountryId inner join CourtDetails on CourtDetails.CourtId = CaseDetails.CourtId where CaseDetails.Status = 'N'";
return selectCases(unprocessedRecordsQuery);
}
public static void updateCaseDetails(int caseRefId,String caseId,String participantsName, String decisionDate, String heardDate){
/*
* This method gets the user input for the existing case in the database and updates in the table
*/
ConnectionHandler connHndlr = new ConnectionHandler();
Connection conn = connHndlr.getConnection();
try{
String updtQuery = "update CaseDetails set CaseId = ?, ParticipantsName = ?, DecisionDate = ?,HeardDate = ? where CaseRefId = ?";
PreparedStatement preparedStatement = conn.prepareStatement(updtQuery);
preparedStatement.setString(1,caseId);
preparedStatement.setString(2,participantsName);
preparedStatement.setString(3, decisionDate);
preparedStatement.setString(4, heardDate);
preparedStatement.setInt(5, caseRefId);
preparedStatement.executeUpdate();
//System.out.println("Values updated to " + participantsName);
}
catch(SQLException se){
System.out.println("SQL Exception " + se.getMessage());
}
catch(Exception e){
System.out.println("Exception " + e.getMessage());
}
}
public static void updateProcessedStatus(int CaseRefId){
/*
* This method updates the 'Status' field of a record to 'N'
* The records with 'Status' field set to 'Y' are not displayed by default
*/
ConnectionHandler connHndlr = new ConnectionHandler();
Connection conn = connHndlr.getConnection();
try{
String processedStatus = "Y";
String updtQuery = "update CaseDetails set Status = '" + processedStatus + "' where CaseRefId = " + CaseRefId;
Statement stmt = conn.createStatement();
stmt.executeUpdate(updtQuery);
}
catch(SQLException se){
System.out.println("SQL Exception " + se.getMessage());
}
catch(Exception e){
System.out.println("Exception " + e.getMessage());
}
}
public static int deleteCaseDetails(int caseRefId){
/*
* Deletes the particular case from the CaseDetails table
*/
ConnectionHandler connHndlr = new ConnectionHandler();
Connection conn = connHndlr.getConnection();
try{
String delQuery = "delete from CaseDetails where CaseRefId = " + caseRefId;
PreparedStatement preparedStatement = conn.prepareStatement(delQuery);
preparedStatement = conn.prepareStatement(delQuery);
preparedStatement.executeUpdate();
}
catch(SQLException se){
System.out.println("SQL Exception " + se.getMessage());
return 0;
}
catch(Exception e){
System.out.println("Exception " + e.getMessage());
return -1;
}
return 1;
}
public static List<CourtDocument> selectCaseDetails(int searchOption, String searchTerm){
/*
* Returns list of cases depending on the Search Criteria
*/
String searchQuery = "";
if(searchOption == 0){
searchQuery = "select CaseDetails.CaseRefId, CountryDetails.CountryName, CourtDetails.CourtName, CaseDetails.CaseId, CaseDetails.ParticipantsName, CaseDetails.DecisionDate, CaseDetails.HeardDate, CaseDetails.ProcessedDate, CaseDetails.ProcessedUser, CaseDetails.SourceFileName from CaseDetails inner join CountryDetails on CaseDetails.CountryId = CountryDetails.CountryId inner join CourtDetails on CourtDetails.CourtId = CaseDetails.CourtId where CAST(CaseDetails.CaseId as BINARY) like '%" + searchTerm.toLowerCase() + "%'";
}
else if(searchOption == 1){
String searchTerms[] = searchTerm.split("\t");
searchQuery = "select CaseDetails.CaseRefId, CountryDetails.CountryName, CourtDetails.CourtName, CaseDetails.CaseId, CaseDetails.ParticipantsName, CaseDetails.DecisionDate, CaseDetails.HeardDate, CaseDetails.ProcessedDate, CaseDetails.ProcessedUser, CaseDetails.SourceFileName from CaseDetails inner join CountryDetails on CaseDetails.CountryId = CountryDetails.CountryId inner join CourtDetails on CourtDetails.CourtId = CaseDetails.CourtId where CountryDetails.CountryName = '" + searchTerms[0] + "' and CourtDetails.CourtName = '" + searchTerms[1] + "'";
}
else if(searchOption == 2){
searchQuery = "select CaseDetails.CaseRefId, CountryDetails.CountryName, CourtDetails.CourtName, CaseDetails.CaseId, CaseDetails.ParticipantsName, CaseDetails.DecisionDate, CaseDetails.HeardDate, CaseDetails.ProcessedDate, CaseDetails.ProcessedUser, CaseDetails.SourceFileName from CaseDetails inner join CountryDetails on CaseDetails.CountryId = CountryDetails.CountryId inner join CourtDetails on CourtDetails.CourtId = CaseDetails.CourtId where CAST(CaseDetails.ParticipantsName as BINARY) like '%" + searchTerm.toLowerCase() + "%'";
}
else if(searchOption == 3)
searchQuery = "select CaseDetails.CaseRefId, CountryDetails.CountryName, CourtDetails.CourtName, CaseDetails.CaseId, CaseDetails.ParticipantsName, CaseDetails.DecisionDate, CaseDetails.HeardDate, CaseDetails.ProcessedDate, CaseDetails.ProcessedUser, CaseDetails.SourceFileName from CaseDetails inner join CountryDetails on CaseDetails.CountryId = CountryDetails.CountryId inner join CourtDetails on CourtDetails.CourtId = CaseDetails.CourtId where CaseDetails.ProcessedDate like '" + searchTerm.toLowerCase() + "'";
else if(searchOption == 4){
searchQuery = "select CaseDetails.CaseRefId, CountryDetails.CountryName, CourtDetails.CourtName, CaseDetails.CaseId, CaseDetails.ParticipantsName, CaseDetails.DecisionDate, CaseDetails.HeardDate, CaseDetails.ProcessedDate, CaseDetails.ProcessedUser, CaseDetails.SourceFileName from CaseDetails inner join CountryDetails on CaseDetails.CountryId = CountryDetails.CountryId inner join CourtDetails on CourtDetails.CourtId = CaseDetails.CourtId where CaseDetails.CaseRefId = " + Integer.parseInt(searchTerm);
}
else if(searchOption == 5)
searchQuery = "select CaseDetails.CaseRefId, CountryDetails.CountryName, CourtDetails.CourtName, CaseDetails.CaseId, CaseDetails.ParticipantsName, CaseDetails.DecisionDate, CaseDetails.HeardDate, CaseDetails.ProcessedDate, CaseDetails.ProcessedUser, CaseDetails.SourceFileName from CaseDetails inner join CountryDetails on CaseDetails.CountryId = CountryDetails.CountryId inner join CourtDetails on CourtDetails.CourtId = CaseDetails.CourtId where CAST(CaseDetails.ProcessedUser as BINARY) = '" + searchTerm.toLowerCase() + "'";
return selectCases(searchQuery);
}
public static int checkForDuplicates(int countryId, int courtId, String caseId){
/*
* Checks whether there is already a case with same countryid, courtid and caseid
*/
String searchQuery = "select CaseRefId,DuplicateofCase from CaseDetails where CaseDetails.CourtId = " + courtId + " and CaseDetails.CountryId = " + countryId + " and CaseDetails.CaseId = '" + caseId + "'";
ConnectionHandler connHandler = new ConnectionHandler();
Connection conn = connHandler.getConn();
int dcaseId = 0;
int ddupRefId = 0;
try{
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(searchQuery);
if(rs.next()){
dcaseId = rs.getInt(1);
ddupRefId = rs.getInt(2);
}
}
catch(SQLException sc){
System.out.println("SQL Exception : " + sc.getMessage());
}
catch(Exception ex){
System.out.println("Exception : " + ex.getMessage());
}
if(ddupRefId != -1)
return ddupRefId;
else if(dcaseId != 0)
return dcaseId;
return -1;
}
}
|
Python
|
UTF-8
| 2,013 | 2.796875 | 3 |
[
"MIT"
] |
permissive
|
#!/usr/bin/python3
# Echo server program
import socket
import logging
import json
logging.basicConfig(level=logging.INFO)
class SpringConnector(object):
def __init__(self, host, port):
self.host = host
self.port = port
self.callbacks = {}
def register(self, name, callback):
if name not in self.callbacks:
self.callbacks[name] = []
self.callbacks[name].append(callback)
def send(self, command):
self.conn.sendall(bytearray(json.dumps(command) + "\n", 'utf-8'))
def fire(self, name, command):
if name not in self.callbacks:
logging.warning("No callback defined for command: {}".format(name))
return
for fn in self.callbacks[name]:
try:
fn(command)
except Exception as ex:
logging.error("Error while executing command: {}".format(name))
import traceback
tb = traceback.format_exc()
logging.error(tb)
def listen(self):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((self.host, self.port))
s.listen(1)
while True:
logging.info("Waiting on connection at {}:{} ...".format(self.host, self.port))
self.conn, addr = s.accept()
self.clientAddress = addr
logging.info('Connected by: {}'.format(self.clientAddress))
while True:
data = self.conn.recv(20971520)
if not data:
break
jsonData = json.loads(data.decode('utf-8'))
print(jsonData)
if "name" in jsonData:
command = jsonData.get("command")
if not command:
command = {}
self.fire(jsonData["name"], command)
self.conn.close()
logging.info('Connection closed')
|
Python
|
UTF-8
| 1,563 | 3.03125 | 3 |
[
"BSD-3-Clause",
"MIT"
] |
permissive
|
# -*- coding: utf-8 -*-
"""A simple processor that does simple image transforms, e.g. color transform or transferring an image to a GPU
"""
import cv2
from .base import *
class ImageTransform(ProcessorBase):
"""Class implementing simple image transforms
"""
def __init__(self, vision, ocl=False, color=None, operator=None, *args, **kwargs):
"""ImageTransform instance initialization
:param vision: source capturing object
:param ocl: will transform an image to UMat effectively transferring it to GPU and back
:param color: specify ``cv2.COLOR_*`` which will be used for ``cvtColor``
:param operator: specify a callable that will be called in ``process`` method
"""
self._color = color
self._ocl = ocl
self._operator = operator
self._cache_img = None
super(ImageTransform, self).__init__(vision, *args, **kwargs)
@property
def description(self):
return "Image Transform processor"
def process(self, image):
if not self._ocl and not self._color and not self._operator:
return image
img = image.image
if self._ocl:
img = cv2.UMat(img)
elif isinstance(img, cv2.UMat):
img = img.get()
if self._color:
img = cv2.cvtColor(img, self._color)
if self._operator:
img = self._operator(img)
if self.display_results:
cv2.imshow(self.name, img)
self._cache_img = img
return image._replace(image=img)
|
Java
|
UTF-8
| 1,221 | 3.0625 | 3 |
[] |
no_license
|
package com.amao.Ademo_kp;
public class Summary {
/*
- 能够知道private关键字的特点
可以修饰成员变量和成员方法,被private修饰的成员变量或者成员方法只能在本类中访问
- 能够知道this关键字的作用
this关键字可以用来区别同名的成员变量和成员方法
格式: this.成员变量名
- 能够知道构造方法的格式和注意事项
public 类名(){}
public 类名(形参列表){}
注意:
1.构造方法没有返回值类型,连void都不能写
2.构造方法的方法名一定是类名
3.构造方法可以重载的
4.如果一个类没有定义构造方法,系统会自动生成一个空参构造方法
如果定义了构造方法,系统就不会自动生成空参构造方法
- 能够完成一个标准类代码的编写及测试
成员变量 private
空参构造
满参构造
set方法
get方法
成员方法
- 能够知道帮助文档的使用步骤
1.打开api
2.点击显示
3.点击索引
4.在搜索框中输入要查找的内容,回车
5.查看包
6.查看类的解释说明
7.查看构造方法
8.查看成员方法
*/
}
|
JavaScript
|
UTF-8
| 1,041 | 2.703125 | 3 |
[] |
no_license
|
const request = require('request');
const {apiKeys} = require('./../apikeys');
let geocodeAddress = (address, callback) => {
if (address) {
const apiKey = apiKeys.geocode;
let encodedAddress = encodeURIComponent(address);
request({
url: `https://maps.googleapis.com/maps/api/geocode/json?address=${encodedAddress}&key=${apiKey}`,
json: true
}, (error, {body} = {}) => {
if (error) {
callback('Unable to connect to google srevers. Check internet access!');
} else if (body.status === 'ZERO_RESULTS') {
callback('Unable to find address. Provide another address!');
} else if (body.status === 'OK') {
callback(undefined, {
address: body.results[0].formatted_address,
latitude: body.results[0].geometry.location.lat,
longitude: body.results[0].geometry.location.lng
})
} else {callback('Mogbe! An unknown error has occured.')}
})} else {callback('No address provided!')}
}
module.exports = {geocodeAddress};
|
Python
|
UTF-8
| 5,130 | 3.5 | 4 |
[] |
no_license
|
#---------------------------------------------------------------
# HASH TABLE
#---------------------------------------------------------------
# V0
class Node:
def __init__(self, key, value):
self.key = key
self.value = value
class HashTable:
def __init__(self, init_size, hash=hash):
self.__slot = [[] for _ in range(init_size)]
self.__size = init_size
self.hash = hash
def put(self, key, value):
"""
* variable
: key : put/remove key-value's key
: value : put/remove key-value's value
: address : the hashed "key" in hashmap
* transfromation
: hash transfromation : hash(value)/self.size
"""
node = Node(key, value)
# get hashmap index (address) via hash func
address = self.hash(node.key) % self.__size
self.__slot[address].append(node)
def get(self, key):
# get the address in hashmap from "hashed" key
address = self.hash(key) % self.__size
# go through every node in the self.__slot[address]
for node in self.__slot[address]:
if node.key == key:
return node.value
return None
def remove(self, key):
# get hashmap index (address) via hash func
address = self.hash(key) % self.__size
# go through every node in the self.__slot[address]
for idx, node in enumerate(self.__slot[address].copy()):
if node.key == key:
self.__slot[address].pop(idx)
# map = HashTable(5)
# print (map)
# print ('*** put into hashmap')
# for i in range(5):
# map.put(i, i)
# print ('*** get from hashmap')
# for i in range(5):
# print (map.get(i))
# print ('*** remove from hashmap')
# for i in range(5):
# (map.remove(i))
# print ('*** get from hashmap')
# for i in range(5):
# print (map.get(i))
# V1
# http://zhaochj.github.io/2016/05/16/2016-05-16-%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84-hash/
class Node:
def __init__(self, key, value):
self.key = key
self.value = value
class HashTable:
def __init__(self, init_size, hash=hash):
self.__slot = [[] for _ in range(init_size)]
#self.__slot = []
#for _ in range(init_size):
# self.__slot.append([])
self.__size = init_size
self.hash = hash
def put(self, key, value):
node = Node(key, value)
address = self.hash(node.key) % self.__size
self.__slot[address].append(node)
def get(self, key, default=None):
_key = self.hash(key)
address = _key % self.__size
for node in self.__slot[address]:
if node.key == key:
return node.value
return default
def remove(self, key):
address = self.hash(key) % self.__size
for idx, node in enumerate(self.__slot[address].copy()):
if node.key == key:
self.__slot[address].pop(idx)
# map = HashTable(16)
# for i in range(5):
# map.put(i, i)
# map.remove(3)
# for i in range(5):
# print(map.get(i, 'not set'))
# # V2
# # https://github.com/joeyajames/Python/blob/master/HashMap.py
# class HashMap:
# def __init__(self):
# self.size = 6
# self.map = [None] * self.size
# def _get_hash(self, key):
# hash = 0
# for char in str(key):
# hash += ord(char)
# return hash % self.size
# def add(self, key, value):
# key_hash = self._get_hash(key)
# key_value = [key, value]
# if self.map[key_hash] is None:
# self.map[key_hash] = list([key_value])
# return True
# else:
# for pair in self.map[key_hash]:
# if pair[0] == key:
# pair[1] = value
# return True
# self.map[key_hash].append(key_value)
# return True
# def get(self, key):
# key_hash = self._get_hash(key)
# if self.map[key_hash] is not None:
# for pair in self.map[key_hash]:
# if pair[0] == key:
# return pair[1]
# return None
# def delete(self, key):
# key_hash = self._get_hash(key)
# if self.map[key_hash] is None:
# return False
# for i in range (0, len(self.map[key_hash])):
# if self.map[key_hash][i][0] == key:
# self.map[key_hash].pop(i)
# return True
# return False
# def print(self):
# print ('---PHONEBOOK----')
# for item in self.map:
# if item is not None:
# print (str(item))
# # h = HashMap()
# # h.add('Bob', '567-8888')
# # h.add('Ming', '293-6753')
# # h.add('Ming', '333-8233')
# # h.add('Ankit', '293-8625')
# # h.add('Aditya', '852-6551')
# # h.add('Alicia', '632-4123')
# # h.add('Mike', '567-2188')
# # h.add('Aditya', '777-8888')
# # h.print()
# # h.delete('Bob')
# # h.print()
# # print('Ming: ' + h.get('Ming'))
|
C
|
UTF-8
| 2,930 | 2.515625 | 3 |
[] |
no_license
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* loop.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: smight <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/08/01 02:10:30 by smight #+# #+# */
/* Updated: 2019/08/01 02:10:31 by smight ### ########.fr */
/* */
/* ************************************************************************** */
#include "../inc/fdf.h"
void get_shift(int key, t_fdf *fdf)
{
if (key == 123)//left
fdf->width_shift -= SHIFT;
else if (key == 124)//right
fdf->width_shift += SHIFT;
else if (key == 125)//down
fdf->hight_shift += SHIFT;
else//up
fdf->hight_shift -= SHIFT;
}
void to_start(t_fdf *fdf)
{
fdf->width_shift = 0;
fdf->hight_shift = 0;
fdf->x_rotation = 0;
fdf->y_rotation = 0;
fdf->z_rotation = 0;
fdf->height_coeff = 1;
}
void write_rotation(t_fdf *fdf, int key)
{
if (key == 92)
fdf->x_rotation = (fdf->x_rotation + 1);
else if (key == 88)
fdf->x_rotation = (fdf->x_rotation - 1);
else if (key == 91)
fdf->y_rotation = (fdf->y_rotation + 1);
else if (key == 87)
fdf->y_rotation = (fdf->y_rotation - 1);
else if (key == 89)
fdf->z_rotation = (fdf->z_rotation + 1);
else if (key == 86)
fdf->z_rotation = (fdf->z_rotation - 1);
}
int deal_key(int key, void *param)
{
if (key == ESC)
end_mlx(param);
else if (key == PUT)
mlx_put_image_to_window(((t_fdf*)param)->mlx_ptr, ((t_fdf*)param)->win_ptr, ((t_fdf*)param)->img_ptr, 0, 0);
else if (key >= 123 && key <= 126)
get_shift(key, param);
else if (key == 83)
((t_fdf*)param)->projection = ISO;
else if (key == 84)
((t_fdf*)param)->projection = PARALLEL;
else if (key == 49)
to_start(param);
else if (key == 92 || key == 88 || key == 91 || key == 87 || key == 89 || key == 86)
write_rotation(param, key);
else if (key == 69)
((t_fdf*)param)->height_coeff *= 2;
else if (key == 78)
((t_fdf*)param)->height_coeff /= 2;
draw_map((t_fdf*)param);//каждый раз после кнопок рисую мапу
mlx_put_image_to_window(((t_fdf*)param)->mlx_ptr, ((t_fdf*)param)->win_ptr,\
((t_fdf*)param)->img_ptr, 0, 0);
draw_menu(param);
return (0);
}
void loop(t_fdf *fdf)
{
fdf->projection = PARALLEL;
to_start(fdf);
draw_map(fdf);
mlx_hook(fdf->win_ptr, 2, 0, deal_key, fdf);//ловлю с клавы esc
mlx_put_image_to_window(fdf->mlx_ptr, fdf->win_ptr, fdf->img_ptr, 0, 0);
draw_menu(fdf);
mlx_loop(fdf->mlx_ptr);
}
|
Python
|
UTF-8
| 1,346 | 2.6875 | 3 |
[] |
no_license
|
import pygame
class Utils:
#Class attributes (static)
init_pos_x = 100
init_pos_y = 570# 410
enemy_init_pos_x = init_pos_x+100
enemy_init_pos_y = init_pos_y
screen_width = 990 #500
screen_height = 675 #480
charact_width = 40
charact_height = 60
enemy_width = 64
enemy_height = 64
init_count = 10
vel = 5
enemyVel = 3
numMaxBullet = 5
enemy_health = 10
img_list = [x for x in range(15) if x > 0]
img_list_enemy = [x for x in range(11) if x > 0]
walkRight = [pygame.image.load('../media/R' + str(x) + '.png') for x in img_list]
walkRight = [pygame.transform.scale(x, (60, 70)) for x in walkRight] #rescale
walkLeft = [pygame.image.load('../media/L' + str(x) + '.png') for x in img_list]
walkLeft = [pygame.transform.scale(x, (60, 70)) for x in walkLeft] #rescale
walkRightE = [pygame.image.load('../media/R' + str(x) + 'E.png') for x in img_list_enemy]
walkLeftE = [pygame.image.load('../media/L' + str(x) + 'E.png') for x in img_list_enemy]
clockTick = int(len(img_list)) * 3 # higher is factor, higher is speed animation
clockTickEnemy = int(len(img_list_enemy)) * 3 # higher is factor, higher is speed animation
bg_image = pygame.image.load('../media/bg1.jpg')
char = pygame.image.load('../media/standing.png')
font_size = 30
|
Java
|
UTF-8
| 1,546 | 2.171875 | 2 |
[] |
no_license
|
package com.cg.flight.web;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import com.cg.flight.entity.Booking;
import com.cg.flight.entity.Passenger;
import com.cg.flight.exception.InvalidBookingIdException;
import com.cg.flight.exception.InvalidContactException;
import com.cg.flight.exception.LoginException;
import com.cg.flight.service.FlightListBookingService;
@RestController
public class FlightListBookingRestController {
@Autowired
private FlightListBookingService service;
@CrossOrigin(origins = {"http://localhost:4200"})
@GetMapping("/viewbooking/{contact}")
public List<Booking> viewBooking(@PathVariable("contact")String contactNo,HttpServletRequest req) throws InvalidContactException, LoginException{
if((boolean)req.getAttribute("authFlag"))
return service.viewBooking(contactNo);
throw new LoginException();
}
@CrossOrigin(origins = {"http://localhost:4200"})
@GetMapping("/viewpassenger/{bookId}")
public List<Passenger> viewPassengers(@PathVariable("bookId")String bookId,HttpServletRequest req) throws InvalidBookingIdException,
LoginException{
if((boolean)req.getAttribute("authFlag"))
return service.viewPassengers(bookId);
throw new LoginException();
}
}
|
C++
|
UTF-8
| 5,196 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
#include "GLDepthTesting.h"
GLDepthTesting::GLDepthTesting(QWidget *parent)
: QOpenGLWidget(parent)
{
}
GLDepthTesting::~GLDepthTesting()
{
//initializeGL在显示时才调用,释放未初始化的会异常
if(!isValid())
return;
//QOpenGLWidget
//三个虚函数不需要makeCurrent,对应的操作已由框架完成
//但是释放时需要设置当前上下文
makeCurrent();
vao.destroy();
vbo.destroy();
doneCurrent();
}
void GLDepthTesting::initializeGL()
{
//QOpenGLFunctions
//为当前上下文初始化opengl函数解析
initializeOpenGLFunctions();
//着色器代码
//in输入,out输出,uniform从cpu向gpu发送
const char *vertex_str=R"(#version 450
layout (location = 0) in vec3 vPos;
layout (location = 1) in vec3 vColor;
uniform mat4 mvp;
out vec3 theColor;
void main() {
gl_Position = mvp * vec4(vPos, 1.0f);
theColor = vColor;
})";
const char *fragment_str=R"(#version 450
in vec3 theColor;
out vec4 fragColor;
void main() {
fragColor = vec4(theColor * (1.0f - gl_FragCoord.z), 1.0f);
})";
//顶点着色器
//可以直接add着色器代码,也可以借助QOpenGLShader类
bool success=shaderProgram.addCacheableShaderFromSourceCode(QOpenGLShader::Vertex,vertex_str);
if(!success){
qDebug()<<"compiler vertex failed!"<<shaderProgram.log();
}
//片段着色器
success=shaderProgram.addCacheableShaderFromSourceCode(QOpenGLShader::Fragment,fragment_str);
if(!success){
qDebug()<<"compiler fragment failed!"<<shaderProgram.log();
}
success = shaderProgram.link();
if(!success){
qDebug()<<"link shader failed!"<<shaderProgram.log();
}
//两个交叠的三角形顶点
//这里的z值和投影的z范围对应
GLfloat vertices[] = {
-0.55f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f,
-0.55f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f,
1.0f, 0.0f, -50.0f, 1.0f, 0.0f, 0.0f,
0.55f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
0.55f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
-1.0f, 0.0f, -50.0f, 0.0f, 0.0f, 1.0f
};
vao.create();
vao.bind();
vbo=QOpenGLBuffer(QOpenGLBuffer::VertexBuffer);
vbo.create();
vbo.bind();
vbo.allocate(vertices,sizeof(vertices));
//setAttributeBuffer(int location, GLenum type, int offset, int tupleSize, int stride = 0)
shaderProgram.setAttributeBuffer(0, GL_FLOAT, 0, 3, sizeof(GLfloat) * 6);
shaderProgram.enableAttributeArray(0);
shaderProgram.setAttributeBuffer(1, GL_FLOAT, sizeof(GLfloat) * 3, 3, sizeof(GLfloat) * 6);
shaderProgram.enableAttributeArray(1);
vbo.release();
vao.release();
//清屏设置
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
//深度测试默认是关闭的,需要用GL_DEPTH_TEST选项启用深度测试
glEnable(GL_DEPTH_TEST);
//在某些情况下我们需要进行深度测试并相应地丢弃片段,但我们不希望更新深度缓冲区,
//基本上,可以使用一个只读的深度缓冲区;
//OpenGL允许我们通过将其深度掩码设置为GL_FALSE禁用深度缓冲区写入:
//glDepthMask(GL_FALSE);
//可以修改深度测试使用的比较规则,默认GL_LESS丢弃深度大于等于的
//glDepthFunc(GL_LESS);
//使近平面外的可见
//glEnable(GL_DEPTH_CLAMP);
}
void GLDepthTesting::paintGL()
{
//渲染之前使用GL_DEPTH_BUFFER_BIT清除深度缓冲区
//否则深度缓冲区将保留上一次进行深度测试时所写的深度值
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
shaderProgram.bind();
//观察矩阵
QMatrix4x4 view;
//OpenGL本身没有摄像机(Camera)的概念,但我们可以通过把场景中的所有物体往相反方向移动的方式来模拟出摄像机,
//产生一种我们在移动的感觉,而不是场景在移动。
view.translate(QVector3D(0.0f, 0.0f, -3.0f));
shaderProgram.setUniformValue("mvp", projection * view);
{
QOpenGLVertexArrayObject::Binder vao_bind(&vao); Q_UNUSED(vao_bind);
//使用当前激活的着色器和顶点属性配置和VBO(通过VAO间接绑定)来绘制图元
//void glDrawArrays(GLenum mode, GLint first, GLsizei count);
//参数1为图元类型
//参数2指定顶点数组的起始索引
//参数3指定顶点个数
//(这里分别画两个三角)
glDrawArrays(GL_TRIANGLES, 0, 3); //red
glDrawArrays(GL_TRIANGLES, 3, 3); //blue
//glDrawArrays(GL_TRIANGLES, 0, 3); //red
}
shaderProgram.release();
}
void GLDepthTesting::resizeGL(int width, int height)
{
if (width < 1 || height < 1) {
return;
}
//宽高比例
qreal aspect = qreal(width) / qreal(height);
//单位矩阵
projection.setToIdentity();
//坐标到达观察空间之后,我们需要将其投影到裁剪坐标。
//裁剪坐标会被处理至-1.0到1.0的范围内,并判断哪些顶点将会出现在屏幕上
//float left, float right, float bottom, float top, float nearPlane, float farPlane
projection.ortho(-1.0f * aspect, 1.0f * aspect, -1.0f, 1.0f, 0.0f, 100.0f);
}
|
C++
|
UTF-8
| 1,729 | 3.28125 | 3 |
[] |
no_license
|
#ifndef lesson3LogicConstnessAndBitwise_h
#define lesson3LogicConstnessAndBitwise_h
/*
Logic Constness: do not change variable that you think is import
如果const function改变了一些次要的varible,
两个方法解决:
1. mutable int a; 在次要的variable 加mutable
2. const_cast<BigArray*>(this)->accessCounter++; 不提倡,cast constness
const int * const fun(const int * const & p) const;
A cosnt function that doesn't mdify its data members and only calls other const member functions.
1. return value of fun is a const pointer pointing t o a constant integer value
2. the parameter of fun is aference of a const pointer pointer to a const integer
the reference cannot refer to a different pointer (naturre of reference)
the referred pointer cannot point to a different value
*/
#include<iostream>
#include <vector>
using namespace std;
class BigArray {
vector<int>v;//huge vector
//mutable int accessCounter; // keep track of how many times v has been accessed, logic constness
int accessCounter;
// add mutable variable, the variable can be changed in the const function
int *v2;
public:
int getItem(int index) const {
//accessCounter++; // as long as variable is inside function cannot be const function
// it conflict with bitwise constness
// or
const_cast<BigArray*>(this)->accessCounter++; // const cast this object
return v[index];
}
void setV2Item(int index, int x) const {
*(v2 + index) = x; //set item in v2 at position index as x
// it did not change memeber directly, maintain member directly
}
//quiz
//const int * const fun(const int * const & p) const;
};
void lesson_3() {
BigArray b;
}
#endif
#pragma once
|
JavaScript
|
UTF-8
| 1,804 | 2.828125 | 3 |
[] |
no_license
|
'use strict'
async function getTasks() {
const URL = 'https://7wc.zhehaizhang.com/task/get/275707420595191808'
const Params = {
headers: {
'x-access-token': '7wc-zhehai',
'Content-Type': 'application/json'
},
method: 'GET'
}
return await fetch(URL, Params)
.then(res => res.json())
.catch(err => console.log(err))
}
async function load_list() {
let html = '<ul>';
const response = await getTasks();
// console.log(response)
for (var i = 0; i < response.length; i++) {
html+= '<li> <h2> ID:' + response[i].taskid + '</h2> <p>' + response[i].contents + ` </p>
<form>
<button class="taskButton btn" type='submit' onclick="clearTask(${response[i].taskid}); return false"> Clear Task </button>
</form>
</li>`
}
html+= '</ul>'
document.getElementById('contents').innerHTML = html
}
async function submitTask() {
const URL = 'https://7wc.zhehaizhang.com/task/post/275707420595191808'
const Data = {
'contents': document.getElementById('task_contents').value
}
const Params = {
headers: {
'x-access-token': '7wc-zhehai',
'Content-Type': 'application/json'
},
body: JSON.stringify(Data),
method: 'POST'
}
console.log(Params)
await fetch(URL, Params)
document.getElementById('task_contents').value = ""
load_list()
}
async function clearTask(id) {
const URL = 'https://7wc.zhehaizhang.com/task/delete/275707420595191808'
const Data = {
'id': id
}
const Params = {
headers: {
'x-access-token': '7wc-zhehai',
'Content-Type': 'application/json'
},
body: JSON.stringify(Data),
method: 'DELETE'
}
await fetch(URL, Params)
load_list()
}
|
PHP
|
UTF-8
| 9,789 | 2.515625 | 3 |
[] |
no_license
|
<?php
//Se incluye el modelo donde conectará el controlador.
require_once '../Modelo/alumno.php';
require_once '../Modelo/seguimiento.php';
require_once '../Modelo/profesor.php';
require_once '../Modelo/tutoria.php';
require_once '../Modelo/usuario.php';
require_once '../Modelo/database.php';
require_once '../Modelo/comentar.php';
if(isset($_POST['id_usuario'])) {
$usuario = $_POST['id_usuario'];
$modelo = new tutoria();
$pvd = $modelo->Obtener($usuario);
header('Content-Type: application/json');
echo json_encode($pvd);
}
class TutoriaController{
private $model;
//Creación del modelo
public function __CONSTRUCT(){
$this->model = new tutoria();
$this->modell = new alumno();
$this->modeloCurso = new alumnoCurso();
}
//Llamado plantilla principal
public function Index(){
require_once '../Vista/Tutoria/lista-tutorias.php';
}
//Llamado plantilla principal
public function ListarAlumnosDerivadoPsicologia(){
require_once '../Vista/Tutoria/lista-AlumnosDerivadoPsicologia.php';
}
public function ListaCitas(){
require_once '../Vista/Tutoria/ListaCitas-tutoria.php';
}
public function error(){
require_once '../Vista/error.php';
}
//Llamado a la vista tutoria-editar
public function Crud(){
$pvd = new tutoria();
//Se obtienen los datos del tutoria a editar.
if(isset($_REQUEST['persona_id'])){
$pvd = $this->model->Obtener($_REQUEST['persona_id']);
}
//Llamado de las vistas.
require_once '../Vista/Tutoria/editar-tutorias.php';
}
//Llamado a la vista tutoria-perfil
public function Perfil(){
$pvd = new tutoria();
//Se obtienen los datos del tutoria.
if(isset($_REQUEST['persona_id'])){
$pvd = $this->model->Obtener($_REQUEST['persona_id']);
}
//Llamado de las vistas.
require_once '../Vista/Tutoria/perfil-tutoria.php';
}
public function Nuevo(){
$tut = new tutoria();
$alm = new usuario();
$dct = new usuario();
//Se obtienen los datos del tutoria.
if(isset($_REQUEST['persona_id'])){
$tut = $this->model->Obtener($_REQUEST['persona_id']);
}
if(isset($_REQUEST['id_alumno'])){
$alm = $this->modell->Obtener($_REQUEST['id_alumno']);
}
if(isset($_REQUEST['id_docente'])){
$dct = $this->modell->Obtener($_REQUEST['id_docente']);
}
//Llamado de las vistas.
require_once '../Vista/Tutoria/agregar-tutoria.php';
}
public function Ver(){
$tut = new tutoria();
$alm = new usuario();
$dct = new usuario();
//Se obtienen los datos del tutoria.
if(isset($_REQUEST['id_alumno'])){
$tut = $this->model->Obtenert($_REQUEST['id_alumno']);
}
if(isset($_REQUEST['id_alumno'])){
$alm = $this->modell->Obtener($_REQUEST['id_alumno']);
}
if(isset($_REQUEST['id_docente'])){
$dct = $this->modell->Obtener($_REQUEST['id_docente']);
}
//Llamado de las vistas.
require_once '../Vista/Tutoria/ver-tutoria.php';
}
public function EstadoCurso(){
$tut = new tutoria();
$alm = new usuario();
$dct = new usuario();
$pvd = new alumnoCurso();
$pvd->alumno_curso_id = $_REQUEST['aa'];
//Se obtienen los datos del tutoria.
if($_REQUEST['id_tipo']==0){
$this->modeloCurso->Bueno($pvd);
}
if($_REQUEST['id_tipo']==1){
$this->modeloCurso->Regular($pvd);
}
if($_REQUEST['id_tipo']==2){
$this->modeloCurso->Malo($pvd);
}
if(isset($_REQUEST['id_alumno'])){
$tut = $this->model->Obtenert($_REQUEST['id_alumno']);
}
if(isset($_REQUEST['id_alumno'])){
$alm = $this->modell->Obtener($_REQUEST['id_alumno']);
}
if(isset($_REQUEST['id_docente'])){
$dct = $this->modell->Obtener($_REQUEST['id_docente']);
}
//Llamado de las vistas.
require_once '../Vista/Tutoria/ver-tutoria.php';
}
public function cancelar(){
$tut = new tutoria();
$alm = new usuario();
$dct = new usuario();
//Se obtienen los datos del tutoria.
if(isset($_REQUEST['id_alumno'])){
$tut = $this->model->Obtenert($_REQUEST['id_alumno']);
}
if(isset($_REQUEST['id_alumno'])){
$alm = $this->modell->Obtener($_REQUEST['id_alumno']);
}
if(isset($_REQUEST['id_docente'])){
$dct = $this->modell->Obtener($_REQUEST['id_docente']);
}
//Llamado de las vistas.
require_once '../Vista/Tutoria/cancelar-tutoria.php';
}
public function Citar(){
$tut = new tutoria();
$alm = new usuario();
$dct = new usuario();
//Se obtienen los datos del tutoria.
if(isset($_REQUEST['persona_id'])){
$tut = $this->model->Obtener($_REQUEST['persona_id']);
}
if(isset($_REQUEST['id_alumno'])){
$alm = $this->modell->Obtener($_REQUEST['id_alumno']);
}
if(isset($_REQUEST['id_docente'])){
$dct = $this->modell->Obtener($_REQUEST['id_docente']);
}
//Llamado de las vistas.
require_once '../Vista/Tutoria/citar-tutoria.php';
}
//Método que registrar al modelo un nuevo proveedor.
public function Guardar(){
$pvd = new tutoria();
$pvd->seguimiento_alumno = $_REQUEST['seguimiento_alumno'];
$pvd->seguimiento_docente = $_REQUEST['seguimiento_docente'];
$pvd->seguimiento_asistencia = $_REQUEST['seguimiento_asistencia'];
$pvd->seguimiento_asignatura = $_REQUEST['seguimiento_asignatura'];
$pvd->seguimiento_fecha = $_REQUEST['seguimiento_fecha'];
$pvd->seguimiento_tema = $_REQUEST['seguimiento_tema'];
//Registro al modelo tutoria.
$this->model->Registrar($pvd);
header('Location: ../Vista/Accion.php?c=alumno&a=Perfil&persona_id='.$_REQUEST['tutoria_alumno']);
//header() es usado para enviar encabezados HTTP sin formato.
//"Location:" No solamente envía el encabezado al navegador, sino que
//también devuelve el código de status (302) REDIRECT al
//navegador
}
public function Asistido(){
$pvd = new tutoria();
$pvd->tutoria_medico_aceptado = $_REQUEST['tutoria_medico_aceptado'];
$pvd->tutoria_social_aceptado = $_REQUEST['tutoria_social_aceptado'];
$pvd->tutoria_piscologia_aceptado = $_REQUEST['tutoria_piscologia_aceptado'];
$pvd->tutoria_id = $_REQUEST['tutoria_id'];
$pvd->tutoria_alumno = $_REQUEST['tutoria_alumno'];
//Registro al modelo tutoria.
$this->model->Asistido($pvd);
header('Location: ../Vista/Accion.php?c=tutoria&a=ListarAlumnosDerivadoPsicologia');
//header() es usado para enviar encabezados HTTP sin formato.
//"Location:" No solamente envía el encabezado al navegador, sino que
//también devuelve el código de status (302) REDIRECT al
//navegador
}
//Método que registrar al modelo un nuevo proveedor.
//Método que modifica el modelo de un proveedor.
public function Editar(){
$pvd = new tutoria();
$pvd->persona_id = $_REQUEST['persona_id'];
$pvd->persona_nombres = strtoupper($_REQUEST['persona_nombres']);
$pvd->persona_apellido1 = "";
$pvd->persona_apellido2 = "";
$pvd->persona_tipo_id = $_REQUEST['persona_tipo_id'];
$pvd->persona_cui = $_REQUEST['persona_cui'];
$pvd->persona_dni = $_REQUEST['persona_cui'];
$pvd->persona_direccion = $_REQUEST['persona_direccion'];
$pvd->persona_email = $_REQUEST['persona_email'];
$pvd->persona_telefono = $_REQUEST['persona_telefono'];
$pvd->persona_prestamo = $_REQUEST['persona_prestamo'];
$this->model->Actualizar($pvd);
header('Location: ../Vista/Accion.php?c=tutoria&a=Perfil&persona_id='.$_REQUEST['persona_id']);
}
//Método que elimina la tupla proveedor con el nit dado.
public function Eliminar(){
$this->model->Eliminar($_REQUEST['persona_id']);
header('Location: ../Vista/Accion.php?c=tutoria');
}
public function GuardarArchivo(){
$pvd = new tutoria();
$pc2 = new usuario();
$tipo = $_FILES['archivo']['type'];
$tamanio = $_FILES['archivo']['size'];
$archivotmp = $_FILES['archivo']['tmp_name'];
$lineas = file($archivotmp);
$i = 0;
foreach ($lineas as $linea_num => $linea) {
if($i != 0) {
$datos = explode(";",$linea);
$hash = password_hash($datos[1], PASSWORD_BCRYPT);
$pvd->persona_id = $datos[1];
$pvd->persona_nombres = utf8_encode($datos[2]);
$pvd->persona_apellido1 = "";
$pvd->persona_apellido2 = "";
$pvd->persona_prestamo=0;
$pvd->persona_tipo_id = 2;
$pvd->persona_cui = $datos[1];
$pvd->persona_dni = $datos[3];
//$pvd->persona_direccion = utf8_encode($datos[5]);
$pvd->persona_email = utf8_encode($datos[5]);
//$pvd->persona_telefono = $datos[7];
$pvd->persona_estado = 0;
$pc2->usuario_cuenta = $datos[1];
$pc2->usuario_password = $hash;
$pc2->usuario_rol_id = 2;
$pc2->usuario_persona_id = $datos[1];
$pc2->usuario_estado = 0;
$this->model->Registrar($pvd);
$this->model->RegistrarU($pc2);
}
$i++;
}
}
}
|
Python
|
UTF-8
| 1,645 | 2.609375 | 3 |
[] |
no_license
|
from terio.async import AsyncIO
import logging
import ds18b20
from config import config
import subprocess
class TempSensorsManager():
QUEUE_CHECK_PERIOD = 0.2 # seconds
def __init__(self):
self.log = logging.getLogger('TEMP_T')
self.bus = ds18b20.DS18B20()
self.asyncIO = AsyncIO(self.QUEUE_CHECK_PERIOD, self.__onRead, None, self.__onStart)
# create translator between raw device name and human readable name
self.names = {'t' + str(i + 1): rawName for i, rawName in enumerate(self.bus.devices)}
def translate(self, name):
for friendlyName, rawName in self.names.items():
if name == friendlyName:
return rawName
elif name == rawName:
return friendlyName
def __onRead(self, data):
return self.bus.readTemps()
def __onStart(self):
self.log.info('Temp sensor thread started')
def readEnv(self):
return self.asyncIO.read(None)
def readCpu(self):
if config.getPlatform() == 'rpi':
try:
result = subprocess.run('vcgencmd measure_temp', stdout=subprocess.PIPE, shell=True, check=True, universal_newlines=True)
return float(result.stdout.strip()[5:-2])
except Exception as e:
self.log.error('Cannot read CPU temp: {}'.format(e))
return 0
else:
return 42.5
def close(self):
self.asyncIO.close()
def main():
from time import sleep
tman = TempSensorsManager()
print(tman.readEnv())
sleep(1)
tman.close()
if __name__ == '__main__':
main()
|
JavaScript
|
UTF-8
| 223 | 2.84375 | 3 |
[] |
no_license
|
const url = location.pathname;
const nav = document.querySelectorAll('a');
nav.forEach((link) => {
const href = link.href.match(/(\/\w*.html?)+/g)[0];
if (url.indexOf(href) >= 0) {
link.className = 'active';
}
});
|
SQL
|
UTF-8
| 1,068 | 2.859375 | 3 |
[] |
no_license
|
.mode columns
.header on
.nullvalue NULL
PRAGMA foreign_keys = ON;
.print ''
.print '<<<Estado atual de Viagem>>>'
.print ''
SELECT id , lugares_ocupados
FROM viagem
WHERE id = 1;
.print ''
.print '<<<Apos criacao de LocalParagem -> dispara gatilho que incrementa o número de lugares ocupados de Viagem>>>'
.print ''
INSERT INTO LocalParagem (utilizador, viagem, morada, coordenadas_GPS, zona) VALUES (201620671, 1, 'Porto', '13.220554', 2);
SELECT id , lugares_ocupados
FROM viagem
WHERE id = 1;
.print ''
.print '<<<Apos criacao de LocalParagem -> nao pode adicionar mais por o carro estar cheio>>>'
.print ''
INSERT INTO LocalParagem (utilizador, viagem, morada, coordenadas_GPS, zona) VALUES (201763907, 1, 'Porto', '13.220554', 2);
SELECT id , lugares_ocupados
FROM viagem
WHERE id = 1;
.print ''
.print '<<<Apos remocao de LocalParagem -> dispara gatilho que decrementa o número de lugares ocupados de Viagem>>>'
.print ''
DELETE FROM LocalParagem WHERE viagem = 1 AND utilizador = 201620671;
SELECT id , lugares_ocupados
FROM viagem
WHERE id = 1;
|
Java
|
UTF-8
| 7,377 | 2.0625 | 2 |
[] |
no_license
|
package com.taugame.tau.server;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.logging.Logger;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.sun.grizzly.comet.CometContext;
import com.sun.grizzly.comet.CometEngine;
import com.sun.grizzly.comet.CometEvent;
import com.sun.grizzly.comet.CometHandler;
import com.taugame.tau.client.TauService;
import com.taugame.tau.shared.Card;
/**
* The server side implementation of the RPC service.
*/
@SuppressWarnings("serial")
public class TauServiceImpl extends RemoteServiceServlet implements TauService, GameListener {
private static final Logger logger = Logger.getLogger("grizzly");
private static final String BEGIN_SCRIPT = "<script type='text/javascript'>\nwindow.parent.";
private static final String END_SCRIPT = "</script>\n";
private String contextPath;
private GameMaster gm;
private HashMap<String, String> names;
private HashMap<String, TauCometHandler> handlers;
private HashMap<TauCometHandler, Boolean> inGame;
private Integer c = 0;
private static final String JUNK =
"<!-- Comet is a programming technique that enables web " +
"servers to send data to the client without having any need " +
"for the client to request it. -->\n";
public class TauCometHandler implements CometHandler<HttpServletResponse> {
HttpServletResponse response;
@Override
public void attach(HttpServletResponse attachment) {
this.response = attachment;
}
@Override
public void onEvent(CometEvent event) throws IOException {
if (inGame.get(this)) {
String output = (String) event.attachment();
logger.info("CometEvent.NOTIFY => {}" + output);
PrintWriter writer = response.getWriter();
writer.println(output);
writer.flush();
}
}
@Override
public void onInitialize(CometEvent event) throws IOException {}
@Override
public void onInterrupt(CometEvent event) throws IOException {
String script = BEGIN_SCRIPT + "l();\n" + END_SCRIPT;
logger.info("CometEvent.INTERRUPT => {}" + script);
PrintWriter writer = response.getWriter();
writer.println(script);
writer.flush();
removeThisFromContext();
}
@Override
public void onTerminate(CometEvent event) throws IOException {
removeThisFromContext();
}
private void removeThisFromContext() throws IOException {
response.getWriter().close();
CometContext context = CometEngine.getEngine().getCometContext(contextPath);
context.removeCometHandler(this);
}
}
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
gm = new GameMaster(this);
names = new HashMap<String, String>();
handlers = new HashMap<String, TauCometHandler>();
inGame = new HashMap<TauCometHandler, Boolean>();
contextPath = config.getServletContext().getContextPath() + "game";
CometContext context = CometEngine.getEngine().register(contextPath);
context.setExpirationDelay(60 * 60 * 1000);
}
@Override
synchronized protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("text/html");
resp.setHeader("Cache-Control", "private");
resp.setHeader("Pragma", "no-cache");
// For IE, Safari and Chrome, we must output some junk to enable streaming
PrintWriter writer = resp.getWriter();
for (int i = 0; i < 10; i++) {
resp.getWriter().write(JUNK);
}
writer.flush();
TauCometHandler handler = new TauCometHandler();
handler.attach(resp);
CometContext context = CometEngine.getEngine().getCometContext(contextPath);
context.addCometHandler(handler);
handlers.put(req.getSession().getId(), handler);
inGame.put(handler, false);
}
synchronized public String join() {
String name = getName();
if (name != null) {
joinAs(name);
}
return name;
}
@Override
synchronized public Boolean joinAs(String name) {
if (name != null && !name.equals("") && !names.containsValue(name)) {
names.put(getID(), name);
inGame.put(handlers.get(getID()), true);
gm.joinAs(name);
return true;
} else {
return false;
}
}
@Override
synchronized public void setReady(boolean ready) {
String name = getName();
if (name != null) {
gm.setReady(name, ready);
}
}
@Override
synchronized public void submit(Card card1, Card card2, Card card3) {
String name = getName();
if (name != null) {
gm.submit(name, card1, card2, card3);
}
}
private String getName() {
return names.get(getID());
}
private String getID() {
return this.getThreadLocalRequest().getSession().getId();
}
@Override
public void statusChanged() {
notifyUpdate(toJson("t", "l"));
}
@Override
public void boardChanged(Board board) {
notifyUpdate(
toJson("t", "b") +
toJson("b", board));
}
@Override
public void gameEnded(List<Entry<String, Integer>> rankings) {
StringBuilder sb = new StringBuilder("[");
for (Entry<String, Integer> entry : rankings) {
sb.append("[" + entry.getKey() + "," + entry.getValue() + "],");
}
sb.append("]");
notifyUpdate(
toJson("t", "e") +
toJson("s", sb));
}
private void notifyUpdate(String json) {
try {
CometContext context = CometEngine.getEngine().getCometContext(contextPath);
// Set<CometHandler> handlers = context.getCometHandlers();
// for (CometHandler handler : handlers) {
context.notify(BEGIN_SCRIPT + "u({"
+ toJson("c", c++)
+ json
+ "});\n" + END_SCRIPT);
// }
} catch (IOException e) {
logger.info(e.toString());
}
}
private String toJson(String key, String value) {
return toJson(key, (Object)("\"" + value + "\""));
}
private String toJson(String key, Object value) {
return "\"" + key + "\":" + value + ",";
}
}
|
PHP
|
UTF-8
| 671 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
<?php
use Illuminate\Database\Seeder;
use Carbon\Carbon;
class RoomsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$rooms = [
'Carlo corinto' => 'Sala de juntas para 10 personas.',
'Moschino' => 'Sala de juntas para 5 personas',
'Paris Hilton' => 'Sala de juntas para 6 personas',
];
foreach ($rooms as $name => $description) {
DB::table('rooms')->insert([
'name' => $name,
'description' => $description,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
]);
}
}
}
|
PHP
|
UTF-8
| 3,233 | 2.796875 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace App\Services;
/**
* Class NTLMRequestService
* @package App\Services
*/
class NTLMRequestService
{
/**
* @var string
*/
private const USER_AGENT = 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Mobile Safari/537.36';
/**
* @var array
*/
private const JSON_HEADERS = [
'Accept:application/json',
'Content-Type:application/json'
];
/**
* @var string
*/
private string $credentials;
/**
* NTLMRequestService constructor.
*/
public function __construct()
{
$this->credentials = config('ntlm-auth.username') . ':' . config('ntlm-auth.password');
}
/**
* @return NTLMRequestService
*/
public static function instantiate(): NTLMRequestService
{
return new static();
}
/**
* @param string $url
* @param array $params
* @return array
*/
public function sendGetRequest(string $url, array $params = []): array
{
$options = [
CURLOPT_HTTPHEADER => self::JSON_HEADERS,
CURLOPT_USERAGENT => self::USER_AGENT,
CURLOPT_HTTPAUTH => CURLAUTH_NTLM,
CURLOPT_USERPWD => $this->credentials,
CURLOPT_VERBOSE => true,
CURLOPT_HEADER => false,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLINFO_HEADER_OUT => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 60,
CURLOPT_CUSTOMREQUEST => 'GET'
];
if (! empty($params)) {
$url = $url . '?' . http_build_query($params);
}
return $this->executeRequest($url, $options);
}
/**
* @param string $url
* @param array $data
* @return array
*/
public function sendPostRequest(string $url, array $data): array
{
$options = [
CURLOPT_HTTPHEADER => self::JSON_HEADERS,
CURLOPT_USERAGENT => self::USER_AGENT,
CURLOPT_HTTPAUTH => CURLAUTH_NTLM,
CURLOPT_USERPWD => $this->credentials,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($data),
CURLOPT_VERBOSE => true,
CURLOPT_HEADER => false,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLINFO_HEADER_OUT => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 60,
];
return $this->executeRequest($url, $options);
}
/**
* @param string $url
* @param array $options
* @return array
*/
private function executeRequest(string $url, array $options): array
{
$curl = curl_init($url);
if (is_resource($curl)) {
curl_setopt_array($curl, $options);
$response = (string) curl_exec($curl);
curl_close($curl);
}
$response = json_decode($response ?? '', true);
return $response;
}
}
|
Markdown
|
UTF-8
| 8,442 | 2.71875 | 3 |
[
"MIT"
] |
permissive
|
---
layout: post
title: freertos学习
subtitle:
date: 2017-03-04
author: 高庆东
header-img: img/ceshi.jpg
catalog: true
tags:
- c语言
- 操作系统
- 进程
- 任务
- 中断
---
# Freertos操作系统学习
## 任务关系
有点类似ucos 但是涉及到api函数 需要理解创建任务的api都有神马功能
创建任务函数完成任务的创建 任务函数完成具体的任务
任务函数必须返回void 而且带有一个void指针参数,任务函数不能被执行完不能有返回值
Viod指针参数用于配合创建任务函数中的参数指针变量
创建任务函数是个api函数函数具体实现如下

pvTaskCode 是指向任务函数的指针
pcName 为任务起的名字(名字的长度可以通过修改某个变量改变)
usStacKDepth 分配任务运行时栈空间的大小
pvParameters 传递到任务中的参数的指针(与任务与外界沟通时需要)
uxPriority 任务的优先级设定
pxCreatedTask 用于传出任务的句柄(可以不用)
### 创建任务函数有两个返回值
有两个可能的返回值: 1. pdTRUE
表明任务创建成功。 2. errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY
由于内存空间不足,
FreeRTOS 无法分配足够的空间来保存任务结构数据和任务栈,因此无法创
建任务。
任务的优先级号越低 任务的优先级越低(与ucos相反)与ucos不同的是任务
可以共享一个优先级
### 任务运行状态
阻塞态:任务在运行时等待 1定时时间到达 2等待接收数据
挂起态:对于调度器而言不可见让任务进入挂起态的函数
vTaskSuspend()API 退出挂起态
vTaskResume() 或 vTaskResumeFromISR() API
(大多数应用程序都不会用到挂起态)
就绪态:准备运行状态
vTaskDelay() API 函数来代替空循环 目的是让任务进入阻塞状态,阻塞状态
时调度器寻找高优先级的就绪任务执行 阻塞时间到达后进入高优先级的
任务执行
vTaskDelayUntil(portTickType*pxPreviousWakeTime,
portTickType xTimeIncrem
类似于 vTaskDelay() 用于精确的延时(解除阻塞的时刻是绝对的)
pxPreviousWakeTime xLastWakeTime = xTaskGetTickCount() (保存上一个离开阻塞的时刻)
一般只需要初始化一次,不需要修改
xTimeIncrem 延时时间的设置
合并阻塞与非阻塞任务(阻塞任务优先级为2 非阻塞任务优先级为1)
阻塞任务运行完调用延时进入阻塞态调度器开始寻找就绪态任务
非阻塞任务一直执行当阻塞任务到达延时调度器进入阻塞任务
执行。空闲任务永远没有机会运行(同一个优先级的任务在调度器看来
是一样的所以运行时一会运行它一会运行另一个,)
### 空闲任务
用空闲任务钩子函数来在添加应用程序 1用于执行低优先级程序或需要
执行不停处理的功能代码 2让处理器进入低功耗模式
空闲任务的运行规则1不能阻塞或者挂起(只有在其他任务不运行时才运行)
2如果应用程序用到了 vTaskDelete() AP 函数,则空闲钩子函数必须能够 尽快返回。 因为在任务被删除后,空闲任务负责回收内核资源。如果空闲任务一直运行在钩 子函数中,则无法进行回收工作。
钩子函数原型 void vApplicationIdleHook( void );钩子函数必须定义为此名无参数也无返回值
FreeRTOSConfig.h 中的配置常量 configUSE_IDLE_HOOK 必须定义为 1,这样空 闲任务钩子函数才会被调用。
改变任务优先级函数
vTaskPrioritySet() API 函数
用于调度器启动后改变任务优先级
void vTaskPrioritySet( xTaskHandle pxTask, unsigned portBASE_TYPE uxNewPriority )
pxTask:需要修改的任务的句柄
uxNewPriority 需要改变的优先级
查询任务的优先级
unsigned portBASE_TYPE uxTaskPriorityGet( xTaskHandle pxTask );
pxTask:任务的句柄 返回值为任务的优先级
通过任务间相互改变优先级可以实现循环
删除任务
void vTaskDelete( xTaskHandle pxTaskToDelete )
通过目标任务的句柄删除任务 空闲任务负责释放内核
## 队列简介
队列是先进先出FIFO的从尾部写入从首部读出队列不属于任何任务
是独立与任务之外的 可以由多个任务写入但很少由多任务读出
在队列创建时需要对其深度和每个单元大小进行设定
当任务读取队列时可以进入阻塞态,当其他任务往队列写入信息后
退出阻塞态 当多个任务读取队列进入阻塞态时退出阻塞态的顺序按
优先级来 当优先级相同时谁等的时间长谁退出阻塞态
## 队列创建
xQueueHandle xQueueCreate( unsigned portBASE_TYPE uxQueueLength,unsigned portBASE_TYPE uxItemSize )
(队列空间是在堆中的)
### 队列的发送函数
xQueueHandle 创建队列的返回值 如果不成功返回NULL 成功的话返回值为队列的句柄
用于队列其他操作
uxQueueLength 队列存储的最大单元数目 队列深度
uxItemSize 队列中数据单元的长度 以字节为单位
portBASE_TYPE xQueueSendToFront( xQueueHandle xQueue,
const void * pvItemToQueue,
portTickType xTicksToWait ); 用于将数据发送到队列首
portBASE_TYPE xQueueSendToBack( xQueueHandle xQueue,
const void * pvItemToQueue,
portTickType xTicksToWait );用于将数据发送到队列尾等同于与portBASE_TYPE xQueueSend()
xQueue 创建的队列的句柄(队列的返回值)
pvItemToQueue 待发送的数据的首地址指针
xTicksToWait 阻塞超时时间。如果在发送时队列已满,这个时间即是任务处于阻塞态等待队列空间有效
的最长等待时间 可以设为0 (任务直接返回不进入阻塞态)
函数的返回值有两个 1paPASS数据被成功发送 2errQUEUE_FULL表示队列已经满了
队列的接收函数
portBASE_TYPE xQueueReceive( xQueueHandle xQueue,const void * pvBuffer,
portTickType xTicksToWait );接收到数据后会删除队列中的数据
portBASE_TYPE xQueuePeek( xQueueHandle xQueue,const void * pvBuffer,
portTickType xTicksToWait );接收到数据后不删除原数据也不改变队列中数据顺序
xQueue 队列的句柄
pvBuffer 接收数据的缓存指针
xTicksToWait 队列在接收时为空则等待,任务进入阻塞态
返回值有两种 1pdPASS 成功接收到数据 2errQUEUE_FULL 队列空没有接受到数据
unsigned portBASE_TYPE uxQueueMessagesWaiting( xQueueHandle xQueue );
用于查询队列中有效数据的个数
taskYIELD()用于任务切换当任务进行完后可以调用此函数
可以直接跳过需要等待的时间片 让调度器进行
切换
接收任务的优先级高于发送任务两个发送任务同优先级。当队列中有数据时就会执行接收任务所以队列中最对只存一个数据,程序执行时先执行接收任务此时队列中无数据接收任务进入阻塞态 调度器执行发送任务1,当发送数据后(此时发送任务1还没执行完)打破接收任务阻塞态 执行接收任务 ,任务执行完后队列中无数据此时又进入阻塞态 接收任务1继续执行当执行到taskYIELD()后调到接收任务2 如同接收任务1如此反复。(接收任务1,2是同优先级的类似任务)
## 注意事项
1指针指向的内存空间的所有权必须明确 当任务通过指针共享内存时
应从根本上保证不会有任意两个任务同时修改内存数据
原则上内存在其指针发送到队列之前起内容只允许发送任务访问
2 指针指向的内存必须有效不能访问已经删除的内存
不能访问栈的内存
## 中断管理
系统需要处理来自各个源头产生的事件对于处理时间和响应时间
有不同的要求
1时间通过中断被检测到
2中断服务程序(isr)
延时中断处理
|
Java
|
UTF-8
| 952 | 1.851563 | 2 |
[] |
no_license
|
package com.cartmatic.estore.common.model.content;
import com.cartmatic.estore.core.model.BaseObject;
public class IndexMsg extends BaseObject
{
private Integer id;
private String msg;
private Integer status;
private String url;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
@Override
public boolean equals(Object o) {
// TODO Auto-generated method stub
return false;
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
return 0;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return null;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
|
Markdown
|
UTF-8
| 4,779 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
# SeisNoise.jl :sound: :earth_americas:
SeisNoise.jl is designed for fast and easy ambient noise cross-correlation on the CPU and GPU in Julia.
| **Documentation** | **Build Status** | **Coverage** | **Chat** |
|:---------------------------------------:|:-----------------------------------------:|:---------------------:|:---------------------:|
| [](https://tclements.github.io/SeisNoise.jl/latest) | [](https://travis-ci.org/tclements/SeisNoise.jl) | [](https://coveralls.io/github/tclements/SeisNoise.jl?branch=master) | [](https://slackinvite.julialang.org/) |

## Installation
You can install the latest version of SeisNoise using the Julia package manager (Press `]` to enter `pkg`).
From the Julia command prompt:
```julia
julia>]
(@v1.4) pkg> add SeisNoise
```
Or, equivalently, via the `Pkg` API:
```julia
julia> import Pkg; Pkg.add("SeisNoise")
```
We recommend using the latest version of SeisNoise by updating with the Julia package manager:
```julia
(@v1.4) pkg> update SeisNoise
```
## Package Features
- Built upon [SeisIO](https://seisio.readthedocs.io/en/latest/) for easy and fast I/O.
- Custom structures for storing Raw Data, Fourier Transforms of data, and cross-correlations
- CPU/GPU compatible functions for cross-correlation.
- Methods for [*dv/v* measurements](https://github.com/tclements/SeisDvv.jl).
- Coming soon: Dispersion analysis.
## SeisNoise Cross-Correlation Example
Once you have installed the package you can type `using SeisNoise` to start
cross-correlating. SeisNoise uses a functional syntax to implement cross-correlation. For example
```Julia
using SeisNoise, SeisIO
fs = 40. # sampling frequency in Hz
freqmin,freqmax = 0.1,0.2 # min and max frequencies
cc_step, cc_len = 450, 1800 # corrleation step and length in S
maxlag = 60. # maximum lag time in correlation
s = "2019-02-03"
t = "2019-02-04"
S1 = get_data("FDSN","CI.SDD..BHZ",src="SCEDC",s=s,t=t)
S2 = get_data("FDSN","CI.PER..BHZ",src="SCEDC",s=s,t=t)
process_raw!(S1,fs)
process_raw!(S2,fs)
R = RawData.([S1,S2],cc_len,cc_step)
detrend!.(R)
taper!.(R)
bandpass!.(R,freqmin,freqmax,zerophase=true)
FFT = rfft.(R)
whiten!.(FFT,freqmin,freqmax)
C = correlate(FFT[1],FFT[2],maxlag)
clean_up!(C,freqmin,freqmax)
abs_max!(C)
corrplot(C)
```
will produce this figure:

## Cross-correlation on the GPU
SeisNoise can process data and compute cross-correlations on the GPU with CUDA. The [JuliaGPU](https://github.com/JuliaGPU) suite provides a high-level interface for CUDA programming through the CUDA.jl package. CUDA.jl provides an the `CuArray` type for storing data on the GPU. Data in SeisNoise structures (`R.x`, `F.fft`, and `C.corr` fields, for `RawData`, `FFTData`, and `CorrData`, respectively) can move between an `Array` on the CPU to a `CuArray` on the GPU using the `gpu` and `cpu` functions, as shown below.
> :warning: Only **Nvidia** GPUs are suported at the moment. Hold in there for AMD/OpenCL support...
```julia
# create raw data and send to GPU
R = RawData(S1, cc_len, cc_step) |> gpu
R.x
72000×188 CUDA.CuArray{Float32,2,Nothing}
# send data back to the CPU
R = R |> cpu
R.x
72000×188 Array{Float32,2}
```
All basic processing remains the same on the GPU. Here is a complete cross-correlation routine on the GPU:
```julia
# send data to GPU
R1 = RawData(S1, cc_len, cc_step) |> gpu
R2 = RawData(S2, cc_len, cc_step) |> gpu
R = [R1,R2]
# preprocess on the GPU
detrend!.(R)
taper!.(R)
bandpass!.(R,freqmin,freqmax,zerophase=true)
# Real FFT on GPU
FFT = rfft.(R)
whiten!.(FFT,freqmin,freqmax)
# compute correlation and send to cpu
C = correlate(FFT[1],FFT[2],maxlag) |> cpu
```
### Routines Implemented on the GPU
- Preprocessing:
- `detrend`,`demean`, `taper`, `onebit`, `smooth`
- Filtering:
- `bandpass`, `bandstop`, `lowpass`, `highpass`
- Fourier Domain:
- `whiten`, `rfft`, `irfft`
- Cross-correlation:
- `correlate`, `cross-coherence`, `deconvolution`
- Post-processing:
- `stack`, `filter`s, etc..
## Contributing
We welcome folks interested in contributing to SeisNoise. Please [open an issue](https://github.com/tclements/SeisNoise.jl/issues/new) to let us know about bug reports, new methods/code, and or feature requests/usage cases. If you would like to submit a pull request (PR), please include accompanying [tests](https://github.com/tclements/SeisNoise.jl/tree/master/test).
|
Java
|
UTF-8
| 988 | 2.46875 | 2 |
[] |
no_license
|
package com.mewin.stc.state;
import com.mewin.stc.game.Unit;
import com.mewin.util.CameraUtil;
import com.mewin.util.GameUtil;
import java.util.List;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
/**
*
* @author mewin<mewin001@hotmail.de>
*/
public abstract class State
{
public static final State EMPTY = new EmptyState();
public static final State UNIT = new UnitSelectedState();
public void onLeftClick(Player player, Location loc)
{
List<Unit> units = CameraUtil.getFocusedUnits(player);
if (units.size() > 0)
{
GameUtil.setSelectedUnits(player, units);
}
else
{
GameUtil.getPlugin().getListener().setPlayerState(player, EMPTY);
}
}
public abstract void onRightClick(Player player, Location loc);
public abstract ItemStack[] getItems(Player player);
public abstract void update(Player player);
}
|
C++
|
BIG5
| 511 | 3.28125 | 3 |
[] |
no_license
|
#include <iostream>
using namespace std;
int main(){
int A,B,C;
cout << "пJAȡH";
cin >> A;
cout << "пJBȡH";
cin >> B;
cout << "пJCȡH";
cin >> C;
if (A > B) {
if (A > C) {
cout << "A=" << A <<"̤j" << endl;
} else {
cout << "C=" << C <<"̤j" << endl;
}
}else {
if (B > C) {
cout << "B=" << B <<"̤j" << endl;
}else {
cout << "C=" << C <<"̤j" << endl;
}
}
}
|
Python
|
UTF-8
| 570 | 2.65625 | 3 |
[] |
no_license
|
from flask import Flask
from flask import redirect
from flask import url_for
app=Flask(__name__)
@app.route("/")
def index():
return "hello"
@app.route("/index02/<user>")
def index2(user):
return "hello222%s"%user
@app.route("/redirect01",methods=["get","put"])
def redirect1():
return redirect("https://www.baidu.com")
@app.route("/redirect02",methods=['get'])
def redirect2():
return redirect(url_for("index"))
@app.route("/redirect03")
def redirect3():
return redirect(url_for("index2",user="3333")),666
if __name__ == '__main__':
app.run()
|
Shell
|
UTF-8
| 364 | 2.734375 | 3 |
[] |
no_license
|
# tasks/init.sh
function btask.init.run() {
local file="$(dirname $(readlink -f $(which xp)))/etc/xp.completion.bash"
if [ -n "$file" ]; then
if [ -e "$file" ]; then
cat $file
else
b.raise FileNotFoundException
fi
else
b.raise StringIsNullException
fi
}
# vim: set ts=4 sw=4 tw=78 ft=sh:
|
Shell
|
UTF-8
| 867 | 2.890625 | 3 |
[] |
no_license
|
#!/usr/bin/env bash
scriptDir=$(dirname `realpath -P "$0"`)
# Generate hotkey file
export WM_NAME="${1}"
"${scriptDir}"/hotkeys
# Change desktop theme
"${scriptDir}"/theme 'y'
[[ ! $(pgrep 'sxhkd') ]] && ("${scriptDir}"/xwait sxhkd -c ~/.config/sxhkd/sxhkdrc) &
[[ ! $(pgrep 'dunst') ]] && ("${scriptDir}"/xwait dunst -c ~/.config/dunst/dunstrc) &
[[ ! $(pgrep 'compton') ]] && ("${scriptDir}"/xcheck compton -b --config ~/.config/compton/compton.conf) &
[[ ! $(pgrep 'mpd') ]] && ("${scriptDir}"/xcheck mpd) &
#[[ ! $(pgrep 'gpg-agent') ]] && gpg-connect-agent reloadagent /bye
[[ ! $(pgrep -f 'wm/displays') ]] && ("${scriptDir}"/xwait "${scriptDir}"/displays) &
#[[ ! $(pgrep -f 'wm/walpaper') ]] && ("${scriptDir}"/wallpaper) &
[[ ! $(pgrep -f 'wm/panel') ]] && ("${scriptDir}"/xwait 1 "${scriptDir}"/panel) &
notify-send -u 'low' 'User is logged in.'
|
JavaScript
|
UTF-8
| 2,946 | 2.71875 | 3 |
[] |
no_license
|
const chai = require('chai');
const supertest = require('supertest');
const expect = require('chai').expect;
const api = supertest('http://107.170.223.162:1337/api');
const nonexistantID = 1234567890123456;
const dummyID = null;
const dummyProductionID = null;
describe('Users:', () => {
it('a GET/ should return a 200 response', function(done) {
api.get('/users')
.set('Accept', 'application/json')
.expect(200, done);
});
it('a GET/ response body should be an array', function(done) {
api.get('users')
.set('Accept', 'application/json')
.expect(200)
.end(function(err, res) {
expect(res.body).to.be.an('array');
done();
});
});
it('a GET/ to a nonexistant user should return a 404', function(done) {
api.get('/user/' + nonexistantID)
.set('Accept', 'application/json')
.expect(404, done);
});
it('a GET/ to a specific user should return a 200', function(done) {
api.get('/user/' + dummyID)
.set('Accept', 'application/json')
.expect(200, done);
});
it('a GET/ to a specific user should respond with the correct user object', function(done) {
api.get('/user/' + dummyID)
.set('Accept', 'application/json')
.expect(function(err, res) {
expect(res.body).to.be.an('array');
expect(res.body[0].firstName).to.equal('Timothy');
expect(res.body[0].lastName).to.equal('Chin');
expect(res.body[0].email).to.equal('timm.chin@gmail.com');
expect(res.body[0].phone).to.equal('9092636664');
expect(res.body[0].role).to.equal('gaffer');
expect(res.body[0].production).to.be.an('array');
expect(res.body[0].production[0]).to.equal(dummyProductionID);
});
xit('a POST/ to users should create a user object', function(done) {
api.post('/users')
.send({
firstName: 'Testerino',
lastName: 'Testerson'
})
.expect(201)
.end(function(err, res) {
expect(res.body).to.be.an('object');
expect(res.body.params.userId).to.exist();
});
});
it('a GET/ to a specific user\'s productions should return an array', function(done) {
api.get('/users/' + dummyID + '/productions')
.set('Accept', 'application/json')
.expect(function(err, res) {
expect(res.body).to.be.an('array');
});
});
});
describe('Productions:', () => {
it('a GET/ should return a 200 response', function(done) {
api.get('/productions')
.set('Accept', 'application/json')
.expect(200, done);
});
it('a GET/ to a specific production should return that production', function(done) {
api.get('/production/' + dummyProductionID)
.set('Accept', 'application/json')
.expect(function(err, res) {
expect(res.body[0].name).to.equal('the_hitchhiker');
expect(res.body[0].location).to.equal('middleofnowhere');
expect(res.body[0].crew).to.be.an('array');
});
});
});
});
|
Java
|
UTF-8
| 14,094 | 2.265625 | 2 |
[] |
no_license
|
package com.oldhigh.customchildlayout.ui;
import android.content.ClipData;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.AttributeSet;
import android.view.DragEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import com.oldhigh.customchildlayout.R;
import com.oldhigh.customchildlayout.bean.CollectionViewState;
import com.oldhigh.customchildlayout.bean.ViewBean;
import com.oldhigh.customchildlayout.utils.L;
import java.util.ArrayList;
import java.util.List;
import static com.oldhigh.customchildlayout.LocalContant.*;
/**
* Created by Administrator on 2017/9/5 0005.
*/
public class CustomChildLayout extends RelativeLayout implements View.OnDragListener {
//布局参数
private LayoutParams mParams;
//数据类
private ViewBean mBean;
//初始化的宽高
private int mWidthInit = 300 ;
private int mHeightInit = 200 ;
//view的集合
private List<ViewBean> mListPool;
//创建的view 以及当前操作的view
private View mView;
//当前拖拽的view的位置
private int mRealViewPosition = 0 ;
//侧滑菜单
private DrawerLayout mDrawerLayout;
//默认最小值的宽高
private final int minDp = 5;
//x y 是准备划线的坐标
private int mX = -1 ;
private int mY = -1;
private Paint mPaint;
public CustomChildLayout(Context context) {
this(context , null);
}
public CustomChildLayout(Context context, AttributeSet attrs) {
this(context, attrs , 0 );
}
public CustomChildLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
if (!isInEditMode()) {
init(context, attrs);
}
}
/**
*初始化一些数据
*/
private void init(Context context, AttributeSet attrs) {
//这里是主要的监听, 因为创建的子view,在拖拽的时候都是在自己原有的宽高内, 所以拖拽总是不成功,
//监听父布局的拖拽,可以确保子view是一直在父布局的view中的。
this.setOnDragListener(this);
mParams = new LayoutParams(mWidthInit, mHeightInit);
mListPool = new ArrayList<>();
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setColor(Color.RED);
mPaint.setStrokeWidth(3);
if (getBackground() == null){
this.setBackground(new ColorDrawable(Color.WHITE));
}else {
this.setBackground(getBackground());
}
}
public void setDrawerLayout(DrawerLayout drawerLayout){
mDrawerLayout = drawerLayout;
}
/**
* 根据类型创建不同的view
* @param type {@link #}
*/
public void createView(int type){
checkDrawerLayout();
mView = new View(getContext());
if (type == IMAGE_VIEW){
mView.setBackground(ContextCompat.getDrawable(getContext() , R.drawable.vr_image));
}
if (type == VIDEO_VIEW){
mView.setBackground(ContextCompat.getDrawable(getContext() , R.drawable.video_image));
}
mParams = new LayoutParams(mWidthInit, mHeightInit);
mParams.leftMargin = getWindowWidth() / 2;
mParams.topMargin = 0 ;
addView(mView, mParams);
mBean = new ViewBean(mView, getWindowWidth() , getWindowHeight() ,type );
mListPool.add(mBean);
onOnLong(mView);
}
/**
* 检测DrawerLayout 是否为空, 否则就关闭侧滑布局
*/
private void checkDrawerLayout() {
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawers();
}
}
/**
* 创建长按事件 , 并添加拖拽操作
*/
private void onOnLong(final View imageView) {
imageView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
ClipData data = ClipData.newPlainText("", "");
DragShadowBuilder shadowBuilder = new DragShadowBuilder(imageView);
v.startDrag(data, shadowBuilder, imageView, 0);
v.setVisibility(View.INVISIBLE);
//这里将进行操作的对象取出来放到对尾,到删除的时候就是删除最近操作的view
for (int i = mListPool.size() -1 ; i >= 0; i--) {
if (v == mListPool.get(i).getView()){
L.e("image onTouch == " + i );
mListPool.add( mListPool.remove(i) );
mRealViewPosition = mListPool.size() - 1 ;
break;
}
}
return true;
}
else{
return false;
}
}
});
}
/**
* 监听拖拽后的view的位置
*/
@Override
public boolean onDrag(View v, DragEvent event) {
if (checkList() ) {
return false;
}
mView = mListPool.get(mRealViewPosition).getView();
int width = mView.getWidth();
int height = mView.getHeight();
//说明已经不再父布局内了
if (event.getAction() == DragEvent.ACTION_DRAG_EXITED){
mView.setVisibility(View.VISIBLE);
}
//这里就是手指抬起来的操作了, 可以布局view
if (event.getAction() == DragEvent.ACTION_DROP){
L.e("drop parent x = " + event.getX() + " y = " + event.getY());
L.e("view x = "+ width + " y = "+height);
int x_cord = (int) event.getX() - width/2;
int y_cord = (int) event.getY() - height/2;
L.e("cord x = "+ x_cord + " y = "+y_cord);
L.e("screen x = "+ getWindowWidth() + " y = "+getWindowHeight());
if (x_cord <= 0 ) {
x_cord = 0;
}
if (y_cord <= 0 ) {
y_cord = 0;
}
if (x_cord >= (getWindowWidth() - width ) ) {
x_cord = (getWindowWidth() - width);
}
if (y_cord >= (getWindowHeight() - height )) {
y_cord = (getWindowHeight() - height);
}
L.e("over x= " +x_cord + " y = " +y_cord);
LayoutParams params = (LayoutParams) mView.getLayoutParams();
params.leftMargin = x_cord ;
params.topMargin = y_cord;
mView.setLayoutParams(params);
bringChildToFront(mView);
mView.setVisibility(View.VISIBLE);
mX = -1 ;
mY = -1 ;
widthCanvas = -1 ;
postInvalidate();
}
//这是一直在移动的过程, 准备划线
if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION){
mX = (int) (event.getX() - width /2);
mY = (int) (event.getY() - height / 2);
widthCanvas = width ;
L.e( " mx = "+mX + " my = "+ mY + " " + event.getX() + " " + event.getY());
postInvalidate();
}
return true;
}
private int widthCanvas = -1 ;
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//画左上角的竖线
canvas.drawLine(mX, 0 , mX , getWindowHeight() , mPaint);
//画左上角的横线
canvas.drawLine(0 , mY , getWindowWidth() , mY , mPaint);
//画右上角的竖线
canvas.drawLine(mX + widthCanvas , 0 , mX + widthCanvas , getWindowHeight() , mPaint );
mPaint.setTextSize(spTopx(15));
//画左上角的坐标
canvas.drawText("( " + mX + " , " + mY +" )" , mX , mY - dpToPx() , mPaint);
//画右上角的坐标
canvas.drawText("( " +( mX + widthCanvas) + " , " + mY +" )" , mX + widthCanvas , mY - dpToPx() , mPaint);
}
/**
* 获取当前的view总是
*/
public int getViewCount(){
return mListPool.size();
}
/**
* 增加view的宽高
* @param width MATCH_PARENT} , HALF_PARENT} , other
*/
public void addWidth(int width) {
if (checkList() ) {
return;
}
View imageView = mListPool.get(mRealViewPosition).getView();
LayoutParams params = (LayoutParams) imageView.getLayoutParams();
if (width == MATCH_PARENT){
params.width = LayoutParams.MATCH_PARENT;
params.topMargin = 0 ;
params.leftMargin = 0 ;
}else if (width == HALF_PARENT){
params.width = getWindowWidth() / 2 ;
params.topMargin = 0 ;
params.leftMargin = 0 ;
}else {
params.width = imageView.getWidth() + dpToPx(width);
}
imageView.setLayoutParams(params);
}
/**
* 检测list的集合
*/
private boolean checkList() {
if (mListPool.size() == 0) {
return true;
}
return false;
}
public void addHeight( int heightInit ) {
if (checkList() ) {
return;
}
View imageView = mListPool.get(mRealViewPosition).getView();
LayoutParams params = (LayoutParams) imageView.getLayoutParams();
if (heightInit == MATCH_PARENT){
params.height = LayoutParams.MATCH_PARENT;
params.topMargin = 0 ;
params.leftMargin = 0 ;
}else if (heightInit == HALF_PARENT){
params.height = getWindowHeight() / 2 ;
params.topMargin = 0 ;
params.leftMargin = 0 ;
}else {
params.height = imageView.getHeight() + dpToPx(heightInit);
}
imageView.setLayoutParams(params);
}
/**
* 减去MINUS view的宽高
* @param width MATCH_PARENT = 1 dp } , HALF_PARENT <= 0 : 1 dp} , other
*/
public void deleteWidth(int width) {
if (checkList() ) {
return;
}
View imageView = mListPool.get(mRealViewPosition).getView();
LayoutParams params = (LayoutParams) imageView.getLayoutParams();
if (width == MATCH_PARENT){
params.width = dpToPx();
}else if (width == HALF_PARENT){
int result = imageView.getWidth() - getWindowWidth() / 2;
params.width = result <= 0 ? dpToPx() : result;
}else {
params.width = (imageView.getWidth() - width) <= 0 ? dpToPx() : (imageView.getWidth() - width);
}
imageView.setLayoutParams(params);
}
public void deleteHeight(int height) {
if (checkList() ) {
return;
}
View imageView = mListPool.get(mRealViewPosition).getView();
LayoutParams params = (LayoutParams) imageView.getLayoutParams();
if (height == MATCH_PARENT){
params.width = dpToPx();
}else if (height == HALF_PARENT){
int result = imageView.getWidth() - getWindowHeight() / 2;
params.height = result <= 0 ? dpToPx() : result;
}else {
params.height = (imageView.getHeight() - height) <= 0 ? dpToPx() : (imageView.getHeight() - height);
}
imageView.setLayoutParams(params);
}
/**
* 获取屏幕的宽
*/
private int getWindowWidth() {
final WindowManager windowManager = ((WindowManager) getContext().getApplicationContext()
.getSystemService(Context.WINDOW_SERVICE));
Point point = new Point();
windowManager.getDefaultDisplay().getSize(point);
return point.x;
}
/**
* 获取屏幕的高 包括状态栏
*/
private int getWindowHeight() {
final WindowManager windowManager = ((WindowManager) getContext().getApplicationContext()
.getSystemService(Context.WINDOW_SERVICE));
Point point = new Point();
windowManager.getDefaultDisplay().getSize(point);
return point.y;
}
/**
* 删除单个View
*/
public void deleteRecentView(){
checkDrawerLayout();
if (mListPool.size() <= 0 ) {
return;
}
View remove = mListPool.remove(mRealViewPosition).getView();
removeView(remove);
mRealViewPosition = mListPool.size() -1;
}
/**
* 删除整个view
*/
public void deleteAllView(){
checkDrawerLayout();
mListPool.clear();
removeAllViews();
}
//转换dp为px
private int dpToPx(int dip) {
float scale = getResources().getDisplayMetrics().density;
return (int) (dip * scale + 0.5f * (dip >= 0 ? 1 : -1));
}
//转换dp为px 默认最小宽高
private int dpToPx() {
float scale = getResources().getDisplayMetrics().density;
return (int) (minDp * scale + 0.5f * (minDp >= 0 ? 1 : -1));
}
//转换sp为px
private int spTopx( float spValue) {
float fontScale = getResources().getDisplayMetrics().scaledDensity;
return (int) (spValue * fontScale + 0.5f);
}
/**
* 初始化 新建view的 宽高
*/
public void setWidthHeightInit(int widthInit , int heightInit){
mWidthInit = widthInit;
mHeightInit = heightInit;
}
/**
* 保存所有的 view 已经状态
*/
public List<CollectionViewState> getListView(){
CollectionViewState state ;
List<CollectionViewState> stateList = new ArrayList<>();
for (int i = 0; i < mListPool.size(); i++) {
state = new CollectionViewState();
mListPool.get(i).update(state);
stateList.add(state);
}
return stateList;
}
}
|
Java
|
UTF-8
| 460 | 2.375 | 2 |
[] |
no_license
|
package com.razil.noteit.util;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class ValidatorTest {
@Test
public void isNullOrEmpty_returnsTrue() {
String str = "";
assertThat(Validator.isNullOrEmpty(str), is(true));
}
@Test
public void isNullOrEmpty_returnFalse() {
String str = "Non empty string";
assertThat(Validator.isNullOrEmpty(str), is(false));
}
}
|
Java
|
UTF-8
| 1,229 | 2.046875 | 2 |
[] |
no_license
|
package com.ai.opt.sol.business.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ai.opt.sol.api.apisol.param.APISolServiceDesignInput;
import com.ai.opt.sol.business.interfaces.ISolServiceDesignInputBuessiness;
import com.ai.opt.sol.dao.mapper.bo.SolServiceDesignInput;
import com.ai.opt.sol.dao.mapper.interfaces.SolServiceDesignInputMapper;
@Service
@Transactional()
public class ISolServiceDesignInputBussinessImpl implements ISolServiceDesignInputBuessiness{
@Autowired
SolServiceDesignInputMapper solServiceDesignInputMapper;
@Override
public void insertServiceInput(APISolServiceDesignInput solServiceInput) {
SolServiceDesignInput serviceInput=new SolServiceDesignInput();
serviceInput.setInputId(solServiceInput.getInputId());
serviceInput.setInputName(solServiceInput.getInputName());
serviceInput.setIsrequired(solServiceInput.getIsRequired());
serviceInput.setParentInputName(solServiceInput.getParentInputName());
serviceInput.setSrvApiId(solServiceInput.getSrvApiId());
solServiceDesignInputMapper.insert(serviceInput);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.