blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
281
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
6
116
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
313 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
18.2k
668M
star_events_count
int64
0
102k
fork_events_count
int64
0
38.2k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
107 values
src_encoding
stringclasses
20 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
4
6.02M
extension
stringclasses
78 values
content
stringlengths
2
6.02M
authors
listlengths
1
1
author
stringlengths
0
175
e84175fc03997448fd0f17f1499d2e5e1f508cd3
1a0e66fd7a238f29b33455e5931d77dc1ebd1244
/2logisticregr.py
8730eaca7de9dea53679cf2191f7b08dbbc80df8
[]
no_license
ahester57/LogisticRegression
07242b7c6a7bd0ab3aeae5b8e4abf418f767e246
18fc1ea2b95b46c9551fc20865827bd50d64df26
refs/heads/master
2021-07-25T17:36:14.690742
2017-11-06T06:16:08
2017-11-06T06:16:08
109,642,260
1
0
null
null
null
null
UTF-8
Python
false
false
1,856
py
# Austin Hester # Logistic Regression # CS 4340 - Intro to Machine Learning # 11.05.17 import numpy as np # define x_0 x0 = 1 # ln L = sum_1_n{ x_i^j * ( y^j - ( e^{w0x0+w1x1+w2x2} / (1 + e^{w0x0+w1x1+w2x2})))} # compute d/dwi ln L with given x, y, weights, and step size def ddw(i, x, y, w_, c): s = 0 # for d/dw1 ln L for j in range(1,9): eexp = np.exp( ( w_[0] * x0 ) + ( w_[1] * x[j-1][0] ) + ( w_[2] * x[j-1][1]) ) if (i == 0): pointmult = 1 else: pointmult = x[j-1][i-1] point = pointmult * (y[j-1] - ( eexp / ( 1 + eexp ) ) ) s = s + point w = w_[i] + (c * s) return w # compute the passing chance given x weeks of inactivity def passingchance(w_, x): chance = 1 / ( 1 + np.exp( x0 * w_[0] + (x[0] * w_[1]) + (x[1]*w_[2]))) return chance # input data [1-8], "weeks of inactivity" , " avg AP score; 0=N/A" #x = np.arange(1, 9) x = np.array( [[1,1,2,3,3,4,4,5,5,6,7,8], [0,4,2,0,0,2,4,5,3,3,4,5]]) x = x.T # output, 0 = "pass", 1 = "fail" y = np.array( [0,0,1,0,1,1,0,0,1,1,1,1] ) # step size c = 0.1 # initial weight vector w_ = np.array( [1., 1., 1.] ) # iterate T times T = 2000 for t in range(T): print("===========================") new_w0 = ddw(0,x,y,w_,c) print(new_w0) print("---------------------------") new_w1 = ddw(1,x,y,w_,c) print(new_w1) print("---------------------------") new_w2 = ddw(2,x,y,w_,c) print(new_w2) w_[0] = new_w0 w_[1] = new_w1 w_[2] = new_w2 print("===========================") # print weight vector print(x) print("\nWeight vector: ", w_) print("\nWeeks of Inactivity") print("x avg AP exam\t\tChances of passing") for i in range(0,12): print("\t",x[i], "\t\t", round(passingchance(w_, x[i]),4)*100, "%")
[ "ahester57@gmail.com" ]
ahester57@gmail.com
f0c53dcf7421bf0aeef4f1f3025ac3e549da2962
f72838a3c6b3f3e89a83db9e057a7bfddefeb099
/crowd_nav/policy/multi_human_rl.py
bb52077ae25241702759670c9ff0b4a2b3780b05
[]
no_license
tessavdheiden/SCR
66a6219c431f72fb243be9731b6c568112da260a
74721e1bb5145d0b4778a99311a716e1279abe76
refs/heads/master
2023-08-17T04:04:26.109612
2020-09-02T13:05:20
2020-09-02T13:05:20
224,380,383
12
6
null
2023-09-06T17:28:42
2019-11-27T08:23:25
Python
UTF-8
Python
false
false
7,014
py
import torch import numpy as np from crowd_sim.envs.utils.action import ActionRot, ActionXY from crowd_nav.policy.cadrl import CADRL from crowd_nav.utils.transformations import build_occupancy_map, propagate class MultiHumanRL(CADRL): def __init__(self): super().__init__() def predict(self, state): """ A base class for all methods that takes pairwise joint state as input to value network. The input to the value network is always of shape (batch_size, # humans, rotated joint state length) """ if self.phase is None or self.device is None: raise AttributeError('Phase, device attributes have to be set!') if self.phase == 'train' and self.epsilon is None: raise AttributeError('Epsilon attribute has to be set in training phase') if self.reach_destination(state): return ActionXY(0, 0) if self.kinematics == 'holonomic' else ActionRot(0, 0) if self.action_space is None: self.build_action_space(state.self_state.v_pref) occupancy_maps = None probability = np.random.random() if self.phase == 'train' and probability < self.epsilon: max_action = self.action_space[np.random.choice(len(self.action_space))] else: self.action_values = list() max_value = float('-inf') max_action = None for action in self.action_space: next_self_state = propagate(state=state.self_state, action=action, time_step=self.time_step, kinematics=self.kinematics) if self.query_env: next_human_states, reward, done, info = self.env.onestep_lookahead(action) else: next_human_states = [self.propagate(human_state, ActionXY(human_state.vx, human_state.vy)) for human_state in state.human_states] reward = self.compute_reward(next_self_state, next_human_states) batch_next_states = torch.cat([torch.Tensor([next_self_state + next_human_state]).to(self.device) for next_human_state in next_human_states], dim=0) rotated_batch_input = self.rotate(batch_next_states).unsqueeze(0) if self.with_om: if occupancy_maps is None: occupancy_maps = self.build_occupancy_maps(next_human_states, next_self_state).unsqueeze(0) rotated_batch_input = torch.cat([rotated_batch_input, occupancy_maps.to(self.device)], dim=2) # VALUE UPDATE next_state_value = self.model(rotated_batch_input).data.item() value = reward + pow(self.gamma, self.time_step * state.self_state.v_pref) * next_state_value self.action_values.append(value) if value > max_value: max_value = value max_action = action if max_action is None: raise ValueError('Value network is not well trained. ') if self.phase == 'train': self.last_state = self.transform(state) return max_action def compute_reward(self, nav, humans): # collision detection dmin = float('inf') collision = False for i, human in enumerate(humans): dist = np.linalg.norm((nav.px - human.px, nav.py - human.py)) - nav.radius - human.radius if dist < 0: collision = True break if dist < dmin: dmin = dist # check if reaching the goal reaching_goal = np.linalg.norm((nav.px - nav.gx, nav.py - nav.gy)) < nav.radius if collision: reward = -0.25 elif reaching_goal: reward = 1 elif dmin < 0.2: reward = (dmin - 0.2) * 0.5 * self.time_step else: reward = 0 return reward def transform(self, state): """ Take the state passed from agent and transform it to the input of value network :param state: :return: tensor of shape (# of humans, len(state)) """ state_tensor = torch.cat([torch.Tensor([state.self_state + human_state]).to(self.device) for human_state in state.human_states], dim=0) if self.with_om: occupancy_maps = self.build_occupancy_maps(state.human_states, state.self_state) state_tensor = torch.cat([self.rotate(state_tensor), occupancy_maps.to(self.device)], dim=1) else: state_tensor = self.rotate(state_tensor) return state_tensor def input_dim(self): return self.joint_state_dim + (self.cell_num ** 2 * self.om_channel_size if self.with_om else 0) def build_occupancy_maps(self, human_states, robot_state): """ :param human_states: :param robot_state :return: tensor of shape (# human - 1, self.cell_num ** 2) """ occupancy_maps = np.zeros((len(human_states), self.cell_num ** 2 * self.om_channel_size)) for i, human in enumerate(human_states): other_humans = np.concatenate([np.array([(other_human.px, other_human.py, other_human.vx, other_human.vy)]) for other_human in human_states + [robot_state] if other_human != human], axis=0) dm = build_occupancy_map(human, other_humans, self.cell_num, self.cell_size, self.om_channel_size) occupancy_maps[i] = dm return torch.from_numpy(occupancy_maps).float() def make_patches(self, h, ax): import matplotlib.patches as patches self.locations = [(i % self.cell_num - self.cell_num // 2, i // self.cell_num - self.cell_num // 2) for i in range(self.cell_num ** 2)] for i in range(self.cell_num ** 2): self.patches[h][i] = patches.Rectangle(self.locations[i], self.cell_size, self.cell_size, alpha=0.1) ax.add_artist(self.patches[h][i]) def draw_observation(self, ax, ob, init=False): import matplotlib as mpl human_num = len(ob[1]) if init: self.patches = [[None for _ in range(self.cell_num ** 2)] for _ in range(human_num)] for h in range(human_num): self.make_patches(h, ax) else: oms = self.build_occupancy_maps(ob[1], ob[0]) for h in range(human_num): (px, py) = ob[1][h].position theta = np.arctan2(ob[1][h].vy, ob[1][h].vx) r = mpl.transforms.Affine2D().rotate(theta) t = mpl.transforms.Affine2D().translate(px, py) tra = r + t + ax.transData for c in range(self.cell_num ** 2): self.patches[h][c].set_transform(tra) self.patches[h][c].set_alpha(np.minimum(np.maximum(oms[h][c].item(), .2), .5))
[ "tessavdheiden@gmail.com" ]
tessavdheiden@gmail.com
6cd250d47fd413455ec250dec981a63376b7a537
1a1979a026c9a3c95bdf98597acf41b5c9f281a2
/Orbit.py
910e5959981ab006a0ac8d64896d95b9b000ab64
[ "BSD-3-Clause" ]
permissive
mtlam/Lab_Orbit
d9edc2d177d221e804ae1e7046a4b8a5ce164366
c43e681f5f2f00d4435b08695a7f2ab33acc6f2b
refs/heads/master
2020-03-28T21:14:18.821546
2018-09-17T14:50:23
2018-09-17T14:50:23
149,140,563
0
0
null
null
null
null
UTF-8
Python
false
false
16,556
py
# -*- coding: utf-8 -*- """ Created on Wed Aug 21 17:49:21 2013 @author: Amit Vishwas Minor edits by Michael Lam """ import numpy as np from matplotlib import pyplot as plt #from mpl_toolkits.mplot3d import Axes3D #import mpl_toolkits.mplot3d.art3d as art3d from matplotlib.patches import Ellipse from matplotlib import animation import matplotlib.gridspec as gridspec # Font to be used for labels on the plot font = {'size' : 9} plt.rc('font', **font) # Setup figure and subplots # Size, dpi and Title for Plot window #fig = plt.figure(num = 'Orbit Simulator', figsize = (12,8.5),dpi = 100) fig = plt.figure(num = 'Orbit Simulator', figsize = (9.5,6.75),dpi = 100) # Divide in 3x3 grid, set area to be used on the plot gs = gridspec.GridSpec(3, 3) gs.update(left=0.07, right=0.95, wspace=0.15) #ax = fig.add_subplot(gs[0,:-1], aspect ='equal', projection = '3d') # Maybe use to implement 3D view # Define the main subplot where orbits are shown ax = fig.add_subplot(gs[0:,:-1], aspect = 'equal') ax.set_ylabel('Distance (in AU)') plt.setp(ax.get_xticklabels(), visible=False) # Set xaxis tick labels to be invisible ax.text(0.01, 0.01, 'As seen by Observer', verticalalignment='bottom', horizontalalignment='left', transform=ax.transAxes, color='Black', fontsize=12) # Define the subplot where the velocity profile is shown ax2 = fig.add_subplot(gs[:-1,-1], aspect = 'auto') ax2.set_xlabel('Time (in Years)') ax2.yaxis.tick_right() ax2.set_ylabel('Velocity (in km/s)') ax2.locator_params(nbins=6) # limit number of x-ticks # Define subplot where the Top view of the orbit is shown ax3 = fig.add_subplot(gs[0,0], aspect = 'equal') ax3.xaxis.set_visible(False) ax3.yaxis.set_visible(False) ax3.text(0.1, 0.99, 'Orbit Top view', verticalalignment='top', horizontalalignment='left', transform=ax.transAxes, color='Black', fontsize=12) pause = True # Click to pause functionality change = False # Initialize global variables - orbital elements phase = 0.0 # Angle in the orbit, measured with respect to periastron timer = 0.0 # Time Counter comx = 0. # Center of Mass co-ordinates comy = 0. m1 = 3.0; # Mass of Obj 1, in Solar mass units m2 = 1.0; # Mass of Obj 2, in Solar mass units semi_a = 1.0 # Semi major axis for the orbit, in AU ecc = 0.3 # Eccentricity alpha = semi_a*(1-ecc**2) nodeangle = 0. # Node angle for the orbit inclination = np.pi/2 # Inclination of the orbit mu = m1*m2/(m1+m2); # Reduced Mass semi_b = semi_a*(1-ecc**2)**0.5 # Semi-minor Axis L = np.sqrt(mu*semi_a*(1-ecc**2)) # Orbital angula rmomentum : constant for a given orbit P = ((1/(m1+m2))*semi_a**3)**0.5 # Period of the orbit, in years tarray = np.zeros(721) # Placeholder to store conversion between time step "i" to phase in orbit xt = np.zeros(721) # Placeholder to store conversion between time step "i" to actual time units in years xt[:]= [(2*P/720)*x for x in range(721)] for i in range(721): tht = np.radians(phase) tarray[i] = tht phase += np.absolute((1 + ecc*np.cos(tht))**2 / (1 - ecc**2)**1.5) phase %= 360 phase = 0. ##################### Show Orbiting Bodies & corresponding orbits M1 = plt.Circle((0, 0), 0.03, fc='r', clip_on=True, lw = 0); # Draw a circle to represent Body 1 M2 = plt.Circle((0, 0), 0.03, fc='b', clip_on=True, lw = 0); # Draw a circle to represent Body 2 # Try to draw the orbit that the objects will follow orb1, = ax.plot(0,0,'r-', alpha = 0.33, visible = False) # empty place holder graphs for orbits orb2, = ax.plot(0,0,'b-', alpha = 0.33, visible = False) ############ Previous attempts for orbits #### #Ellipse(xy=(-semi_a*(ecc)*(mu/m1), 0), width=2*semi_a*(mu/m1), height=2*semi_b*(mu/m1)*np.cos(inclination), # edgecolor='r', fc='None', alpha = 0.33, lw=1) #Ellipse(xy=(semi_a*(ecc)*(mu/m2), 0), width=2*semi_a*(mu/m2), height=2*semi_b*(mu/m2)*np.cos(inclination), # edgecolor='b', fc='None', alpha = 0.33, lw=1) ############################################## ax.set_xlim(-2, 2) ax.set_ylim(-2, 2) ax.grid(True) ############ Show Velocity of corrresponding bodies with respect to time # Draw circles for showing the instantaneous velocity of the body on the velocity - time graph #Mv1 = plt.Circle((0, 0), 0.05*P, fc = 'r', ec='r', clip_on=True, lw = 1); #Mv2 = plt.Circle((0, 0), 0.05*P, fc = 'k', ec='k', clip_on=True, lw = 1); Mv1 = Ellipse((0, 0), 0.1*P, 0.1*P, fc = 'r', ec='r', clip_on=True, lw = 1); Mv2 = Ellipse((0, 0), 0.1*P, 0.1*P, fc = 'b', ec='b', clip_on=True, lw = 1); # 29.87 is velocity of Earth around the Sun, scaled using a^3/(M_sol) = P^2 d3 = 29.87*np.sqrt((m1+m2/alpha))*(1+ecc) d4 = 29.87*np.sqrt((m1+m2/alpha))* ecc d6 = np.sin(inclination)*np.sqrt((d4**2 + d3**2)) # used to define the axis limit on velocity plot, some number larger than either v1, = ax2.plot(0,0,'r-', visible = False) # empty place holder graphs for velocity curves v2, = ax2.plot(0,0,'b-', visible = False) ax2.set_xlim(0, 2*P) # Plot velocity for two prbits ax2.set_ylim(-d6-0.1, d6+0.1) ax2.grid(True) #ax.get_xaxis().set_animated(True) # enabling it takes away the labels ############### Preffered view of the orbits - from the top, no effect of inclination #### Mi1 = plt.Circle((0, 0), 0.05, fc='r', clip_on=True, lw = 0); Mi2 = plt.Circle((0, 0), 0.05, fc='b', clip_on=True, lw = 0); # Draw orbits as elipses orbi1 = Ellipse(xy=(-semi_a*(ecc)*(mu/m1), 0), width=2*semi_a*(mu/m1), height=2*semi_b*(mu/m1), edgecolor='r', fc='None', lw=0.5) orbi2 = Ellipse(xy=(semi_a*(ecc)*(mu/m2), 0), width=2*semi_a*(mu/m2), height=2*semi_b*(mu/m2), edgecolor='b', fc='None', lw=0.5) ax3.set_xlim(-2, 2) ax3.set_ylim(-2, 2) ax3.grid(True) ############################################################################### # pause animation on click def onClick(event): global pause pause ^= True ############################################################################### def init(): global M1, M2, orb1, orb2, Mv1, Mv2, Mi1, Mi2, orbi1, orbi2, phase, v1, v2 M1.center = (-100, -100) # initialize the patches at a far location M2.center = (-100, -100) ax.add_patch(M1) # art3d.pathpatch_2d_to_3d(M1, z=0, zdir="x") ax.add_patch(M2) # art3d.pathpatch_2d_to_3d(M2, z=0, zdir="x") # orb1.center = (-100, -100) # ax.add_patch(orb1) # orb2.center = (-100, -100) # ax.add_patch(orb2) ##################################################### Mv1.center = (-100, -100) Mv2.center = (-100, -100) ax2.add_patch(Mv1) ax2.add_patch(Mv2) ##################################################### Mi1.center = (-100, -100) Mi2.center = (-100, -100) ax3.add_patch(Mi1) ax3.add_patch(Mi2) orbi1.center = (-100, -100) ax3.add_patch(orbi1) orbi2.center = (-100, -100) ax3.add_patch(orbi2) ###################################################### ## return everything that you want to remain visible as the animation runs return M1,M2, orb1, orb2, Mv1, Mv2, Mi1, Mi2, orbi1, orbi2, v1, v2 ############################################################################### def update(val): global comx, comy, m1, m2, d6 global semi_a, semi_b, ecc, alpha, nodeangle, inclination global mu, L, P, r , r1, r2 global M1, M2, orb1, orb2, Mi1, Mi2, orbi1, orbi2, v1, v2, pause global phase, timer, xt, tarray, change phase = 0. timer = 0. v1.set_visible(False) v2.set_visible(False) orb2.set_visible(False) orb2.set_visible(False) m1 = round(s_m1.val,1) m2 = round(s_m2.val,1) semi_a = round(s_a.val,1) if round(s_ecc.val,1) != ecc : ecc = round(s_ecc.val,1) change = True alpha = semi_a*(1-ecc**2) nodeangle = np.radians(int(s_node.val)) inclination = np.radians(int(s_inc.val)) mu = ((m1*m2)/(m1+m2)); semi_b = semi_a*(1-ecc**2)**0.5 L = np.sqrt(mu*alpha) P = ((1/(m1+m2))*semi_a**3)**0.5 if change == True: for i in range(721): tht = np.radians(phase) tarray[i] = tht phase += np.absolute((1 + ecc*np.cos(tht))**2 / (1 - ecc**2)**1.5) phase %= 360 phase = 0. change = False xt[:]= [(2*P/720)*x for x in range(721)] r = alpha/(1+ecc); r1 = r*(mu/m1); r2 = -r*(mu/m2); M1.set_radius(0.03*(semi_a)) M2.set_radius(0.03*(semi_a)) orb1.set_xdata(comx + (mu/m1)*(alpha/(1+(ecc*np.cos(tarray[0:361])))) * np.cos(tarray[0:361] + nodeangle)); orb1.set_ydata(comy + (mu/m1)*(alpha/(1+(ecc*np.cos(tarray[0:361])))) * np.cos(inclination) * np.sin(tarray[0:361] + nodeangle)); orb1.set_visible(True) ax.draw_artist(orb1) orb2.set_xdata(comx - (mu/m2)*(alpha/(1+(ecc*np.cos(tarray[0:361])))) * np.cos(tarray[0:361] + nodeangle)); orb2.set_ydata(comy - (mu/m2)*(alpha/(1+(ecc*np.cos(tarray[0:361])))) * np.cos(inclination) * np.sin(tarray[0:361] + nodeangle)); orb2.set_visible(True) ax.draw_artist(orb2) ########### Old orbit plot attempt #### # orb1.center = (comx + semi_a*(ecc)*(mu/m1)*np.cos(nodeangle+np.pi), comy + np.cos(inclination)*semi_a*(ecc)*(mu/m1)*np.sin(nodeangle+np.pi)) # # orb1.width = 2*semi_a*(mu/m1)*(np.cos(nodeangle))**2 + 2*semi_b*(mu/m1)*(np.sin(nodeangle))**2 # orb1.height = np.cos(inclination)*(2*semi_a*(mu/m1)*(np.sin(nodeangle))**2 + 2*semi_b*(mu/m1)*(np.cos(nodeangle))**2) # #orb1.angle = np.rad2deg(nodeangle) # # orb2.center = (comx + semi_a*(ecc)*(mu/m2)*np.cos(nodeangle), comy + np.cos(inclination)*semi_a*(ecc)*(mu/m2)*np.sin(nodeangle)) # # orb2.width = 2*semi_a*(mu/m2)*(np.cos(nodeangle))**2 + 2*semi_b*(mu/m2)*(np.sin(nodeangle))**2 # orb2.height = np.cos(inclination)*(2*semi_a*(mu/m2)*(np.sin(nodeangle))**2 + 2*semi_b*(mu/m2)*(np.cos(nodeangle))**2) #orb2.angle = np.rad2deg(nodeangle) ax.set_xlim(-2*semi_a, 2*semi_a) ax.set_ylim(-2*semi_a, 2*semi_a) ############################################################### d3 = 29.87*np.sqrt((m1+m2/alpha))*(1+ecc) d4 = 29.87*np.sqrt((m1+m2/alpha))* ecc d6 = np.sin(inclination)*np.sqrt((d4**2 + d3**2)) v1.set_ydata((mu/m1)*np.sin(inclination)*(d4*np.sin(tarray+nodeangle)*np.sin(tarray) + (1/(1+ecc))*d3*np.cos(tarray+nodeangle)*(1+ecc*np.cos(tarray)))) v1.set_xdata(xt) v1.set_visible(True) ax2.draw_artist(v1) v2.set_ydata((-mu/m2)*np.sin(inclination)*(d4*np.sin(tarray+nodeangle)*np.sin(tarray) + (1/(1+ecc))*d3*np.cos(tarray+nodeangle)*(1+ecc*np.cos(tarray)))) v2.set_xdata(xt) v2.set_visible(True) ax2.draw_artist(v2) ax2.set_xlim(0, 2*P) ax2.set_ylim(-d6-0.1, d6+0.1) ratio = (d6+0.1)/P #ylim/xlim ratio #Mv1.set_radius(0.05*(P)) #Mv2.set_radius(0.05*(P)) Mv1.width = 0.1*P Mv1.height = 0.1*P*ratio Mv2.width = 0.1*P Mv2.height = 0.1*P*ratio# / np.sin(inclination) ############################################################### Mi1.set_radius(0.05*(semi_a)) Mi2.set_radius(0.05*(semi_a)) orbi1.width = 2*semi_a*(mu/m1) orbi1.height = 2*semi_b*(mu/m1) orbi1.angle = np.rad2deg(nodeangle) orbi1.center = (comx + semi_a*(ecc)*(mu/m1)*np.cos(nodeangle+np.pi), comy + semi_a*(ecc)*(mu/m1)*np.sin(nodeangle+np.pi)) orbi2.width = 2*semi_a*(mu/m2) orbi2.height = 2*semi_b*(mu/m2) orbi2.angle = np.rad2deg(nodeangle) orbi2.center = (comx + semi_a*(ecc)*(mu/m2)*np.cos(nodeangle), comy + semi_a*(ecc)*(mu/m2)*np.sin(nodeangle)) ax3.set_xlim(-2*semi_a, 2*semi_a) ax3.set_ylim(-2*semi_a, 2*semi_a) ################################################################## pause = False ############################################################################### def animate(i): global semi_a, alpha, ecc, inclination, nodeangle global r, r1, r2, mu, m1, m2, P global M1, M2, orb1, orb2, Mi1, Mi2, orbi1, orbi2, comx, comy global phase, tarray, timer, xt if not pause: tht = phase r = alpha/(1+(ecc*np.cos(tht))); r1 = r*(mu/m1); r2 = -r*(mu/m2); ############################################################# #x1, y1 = M1.center x1 = comx + r1 * np.cos(tht + nodeangle); y1 = (comy + r1 * np.cos(inclination) * np.sin(tht + nodeangle)); #x2, y2 = M2.center x2 = comx + r2 * np.cos(tht + nodeangle); y2 = (comy + r2 * np.cos(inclination) * np.sin(tht + nodeangle)); M1.center = (x1, y1) M2.center = (x2, y2) # orb1.center = (comx + semi_a*(ecc)*(mu/m1)*np.cos(nodeangle+np.pi), comy + np.cos(inclination)*semi_a*(ecc)*(mu/m1)*np.sin(nodeangle+np.pi)) # orb2.center = (comx + semi_a*(ecc)*(mu/m2)*np.cos(nodeangle), comy + np.cos(inclination)*semi_a*(ecc)*(mu/m2)*np.sin(nodeangle)) ############################################################ d3 = 29.87*np.sqrt((m1+m2/alpha))*(1+ecc*np.cos(tht)) d4 = 29.87*np.sqrt((m1+m2/alpha))* ecc*np.sin(tht) d6 = np.sin(inclination)*(d4*np.sin(tht+nodeangle) + d3*np.cos(tht+nodeangle)) vm1 = (mu/m1)*d6 vm2 = -(mu/m2)*d6 xv1, yv1 = Mv1.center xv1 = 2*P*(timer/720) yv1 = vm1 xv2, yv2 = Mv2.center xv2 = 2*P*(timer/720) yv2 = vm2 Mv1.center = (xv1, yv1) Mv2.center = (xv2, yv2) ############################################################# xi1 = comx + r1 * np.cos(tht + nodeangle); yi1 = comy + r1 * np.sin(tht + nodeangle); xi2 = comx + r2 * np.cos(tht + nodeangle); yi2 = comy + r2 * np.sin(tht + nodeangle); Mi1.center = (xi1, yi1) Mi2.center = (xi2, yi2) orbi1.center = (comx + semi_a*(ecc)*(mu/m1)*np.cos(nodeangle+np.pi), comy + semi_a*(ecc)*(mu/m1)*np.sin(nodeangle+np.pi)) orbi2.center = (comx + semi_a*(ecc)*(mu/m2)*np.cos(nodeangle), comy + semi_a*(ecc)*(mu/m2)*np.sin(nodeangle)) ############################################################ phase = tarray[timer] timer += 1 timer %= 720 return M1,M2, orb1, orb2, Mv1, Mv2, v1, v2, Mi1, Mi2, orbi1, orbi2 ############################################################################### fig.canvas.mpl_connect('button_press_event', onClick) anim = animation.FuncAnimation(fig, animate, init_func=init, frames=360, interval=20, blit=True, repeat = True) ############################################################################### ############################## Put sliders axslider_inc = plt.axes([0.1, 0.92, 0.25, 0.03]) s_inc = plt.Slider(axslider_inc, 'Inc ', 0, 90, valfmt='%0d', valinit=90) s_inc.on_changed(update) axslider_node = plt.axes([0.65, 0.92, 0.25, 0.03]) s_node = plt.Slider(axslider_node, 'Node Angle', -90, 90, valfmt='%0d', valinit=0) s_node.on_changed(update) axslider_a = plt.axes([0.1, 0.06, 0.5, 0.03]) s_a = plt.Slider(axslider_a, 'a ', 0.1, 10.0, valfmt='%0.1f', valinit=1.0) s_a.on_changed(update) axslider_ecc = plt.axes([0.1, 0.01, 0.5, 0.03]) s_ecc = plt.Slider(axslider_ecc, 'Ecc ', 0, 0.9, valfmt='%0.1f', valinit=0.3) s_ecc.on_changed(update) axslider_m1 = plt.axes([0.67, 0.06, 0.25, 0.03]) s_m1 = plt.Slider(axslider_m1, 'm1 ', 0.1, 10.0, valfmt='%0.1f', valinit=3.0) s_m1.on_changed(update) axslider_m2 = plt.axes([0.67, 0.01, 0.25, 0.03]) s_m2 = plt.Slider(axslider_m2, 'm2 ', 0.1, 10.0, valfmt='%0.1f', valinit=1.0) s_m2.on_changed(update) ############################################################################### plt.show()
[ "noreply@github.com" ]
noreply@github.com
f3e53acf210e785c0ac6fbb7224f602360a8f839
f2a3f57379cb375c33442afb03baef005b92f819
/김용재/211122 모음사전.py
e52b1fbbb79f6e4468b639b8adfc15ff0b46f549
[]
no_license
rubetyy/Algo-study
9e2d80b2edcd37c67c4c824f5e61b65be272cf06
d7165da60c98227d6f4abf18aa19cd79e006ea59
refs/heads/master
2023-09-02T05:52:41.517447
2021-11-23T04:12:04
2021-11-23T04:12:04
418,523,907
0
0
null
null
null
null
UTF-8
Python
false
false
645
py
def solution(word): answer = 0 check = ['A', 'E', 'I', 'O', 'U'] sum_word = '' dfs(word, check, sum_word) return cnt cnt = 0 flag = False def dfs(word, check, sum_word): global flag global cnt if sum_word == word: answer = cnt flag = True print(sum_word, cnt) return answer if flag == True: return if len(sum_word) == 5: print(sum_word, cnt) return sum_word else: for c in check: if flag == True: return cnt += 1 dfs(word, check, sum_word + c) word = 'I' print(solution(word))
[ "nightyong25@naver.com" ]
nightyong25@naver.com
3f5768ace9e8c5f7894b254ede1264cb65d82a50
813191ee7db33163e4a8ef352412c3e359c243ec
/belote.py
dae80f602ded6dc6015407fc0b164258b2d7f6c8
[]
no_license
TsvetomirTsvetkov/BeloteDeclarations-Crocodile
bf87d13e21ac8014f46cb33f505fbf958bc162bd
1440699ce84d81a6995cb6b84c49eb0cd05fd1b0
refs/heads/master
2021-04-24T00:28:36.145625
2020-03-31T10:36:34
2020-03-31T10:36:34
250,044,212
0
0
null
2020-03-31T10:36:35
2020-03-25T17:21:33
Python
UTF-8
Python
false
false
1,462
py
# belote.py from game import Game from player import Player from team import Team from utils import team_players, validate_teams, validate_player_names def main(): team1_name = input('Team 1 name: ') team2_name = input('Team 2 name: ') validate_teams(team1_name, team2_name) # Checks if teams have the same name input_players_team1 = input(f'"{team1_name}" players: ') input_players_team2 = input(f'"{team2_name}" players: ') list_players_team1 = team_players(input_players_team1) # Converts input to list of strings with names list_players_team2 = team_players(input_players_team2) # Converts input to list of strings with names validate_player_names(list_players_team1, list_players_team2) # Checks if names from the first list appear in the second # and checks if len(lists) == 2 team1_player1 = Player(list_players_team1[0]) # Creating players with the names team1_player2 = Player(list_players_team1[1]) team2_player1 = Player(list_players_team2[0]) team2_player2 = Player(list_players_team2[1]) team1 = Team(team1_name, [team1_player1, team1_player2]) # Creating the teams team2 = Team(team2_name, [team2_player1, team2_player2]) game = Game(team1, team2) winners = {team1: 0, team2: 0} while winners[team1] != 2 and winners[team2] != 2: winners[game.play()] += 1 print('Winner:', team1) if winners[team1] == 2 else print('Winner:', team2) if __name__ == '__main__': main()
[ "cvetomircvetkov24@gmail.com" ]
cvetomircvetkov24@gmail.com
b55a7936ad7a0e3c1058476070f0f4b3bc5173fd
73dc310b46379e92a73fe50533f38ede330b4000
/movieapp_backend/movie_app/migrations/0010_auto_20170209_0956.py
200f752ec048d1726e751fb2f451474868cfe472
[ "MIT" ]
permissive
thepassenger-hub/MyCinema
49c5361064258b47ea5e7e4a907437fd64b817dd
7796a282eff8d169f17374ef11dc9378f506c7a3
refs/heads/master
2021-01-23T00:25:35.503653
2017-05-29T12:02:59
2017-05-29T12:02:59
92,810,841
0
0
null
null
null
null
UTF-8
Python
false
false
476
py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-09 09:56 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('movie_app', '0009_auto_20170206_1011'), ] operations = [ migrations.AlterField( model_name='profile', name='avatar', field=models.ImageField(default='avatar.svg', upload_to=''), ), ]
[ "giulio@debian.debian" ]
giulio@debian.debian
83aff3882cf3a34014c7e624d9349aa5a156af80
12bcebcf76c792f0442ec12de39f4678af9e84a4
/Series Temporales/Prediciendo valores/Tuneando parametros ARIMA/code.py
d4598564e49b38f9652710d14ef7368c688e8550
[]
no_license
fvilchez/Python_for_DataScience
882bac5dac7f6b41f9db946e4a676d8c5bf32b67
fd4e35225a93f6ebf95fa2a75e4684b3937687d6
refs/heads/master
2020-03-22T04:13:31.076017
2020-03-06T09:13:55
2020-03-06T09:13:55
136,737,804
0
0
null
null
null
null
UTF-8
Python
false
false
1,973
py
####################### Grid Search ARIMA ################################# import pandas as pd import warnings import numpy as np from math import sqrt from pandas import datetime from statsmodels.tsa.arima_model import ARIMA from sklearn.metrics import mean_squared_error warnings.filterwarnings('ignore') def evaluate_arima_model(X, arima_order): #Preparamos nuestro dataset train_size = int(len(X) * 0.66) train, test = X[0:train_size], X[train_size:] history = [x for x in train] #Hacemos predicciones predictions = list() for t in range(len(test)): model = ARIMA(history, order = arima_order) model_fit = model.fit(disp = 0) yhat = model_fit.forecast()[0] predictions.append(yhat) history.append(test[t]) #Calculamos el error rmse = sqrt(mean_squared_error(test, predictions)) return rmse def evaluate_models(dataset, p_values, d_values, q_values): dataset = dataset.astype('float32') best_score, best_cfg = float('inf'), None for p in p_values: for d in d_values: for q in q_values: order = (p,d,q) try: rmse = evaluate_arima_model(dataset, order) if rmse < best_score: best_score, best_cfg = rmse, order print('ARIMA%s RMSE=%.3f' % (order, rmse)) except: continue print('Best ARIMA%s RMSE=%.3f' % (best_cfg, best_score)) ########################## Aplicamos esto sobre shampoo ######################## def parser(x): return datetime.strptime('190'+x, '%Y-%m') series = pd.read_csv('shampoo-sales.csv', header = 0, parse_dates = [0], index_col = 0, squeeze = True, date_parser = parser) #Elegimos los parámetros a evaluar p_values = [0,1,2,4,6,8,10] d_values = range(0,3) q_values = range(0,3) evaluate_models(series.values, p_values, d_values, q_values)
[ "franciscojaviervilcheztorralba@gmail.com" ]
franciscojaviervilcheztorralba@gmail.com
e3df84eca6e0476a36dfbe5a48b608d3d1ae056b
76ca57fd77d0bc0007a07ab48b5b809fdc811236
/kbur.py
988ef20169bf58b226307dbada24720504e58dab
[]
no_license
lechub/kburPy
90940f5be19f70b52e6bd18f4af0b4d9d4aad1d8
11263f4b0514cb6ff1a0c4378e490efcf8d63afb
refs/heads/master
2020-04-18T06:23:06.904576
2019-01-24T12:38:58
2019-01-24T12:38:58
167,318,169
0
0
null
null
null
null
UTF-8
Python
false
false
728
py
#!/usr/bin/python ''' Created on 23.01.2019 @author: lechu ''' import serial import time ser = serial.Serial('/dev/ttyUSB0', 38400, timeout=1) # x = ser.read() # read one byte # s = ser.read(10) # read up to ten bytes (timeout) # line = ser.readline() # read a '\n' terminated line def command(cmd): print(cmd + ' -> ', end='') #ser.reset_input_buffer() ser.write((cmd + '\n').encode('utf-8')) #print(ser.readline().decode('utf-8')) print(ser.readline()) if __name__ == '__main__': command('hello') time.sleep(1) for i in range(3): command('set all 1100 on 3') time.sleep(1) command('set all 0011 on 3') time.sleep(1) pass
[ "lechub@tlen.pl" ]
lechub@tlen.pl
ff91db7450857ae17f6711d2d26442035a700058
8625cfec4076b691495a3fa2783125f49dc29863
/src/events/__init__.py
f1eb674b737af674874c824b34eacb25420e509b
[]
no_license
grantHaataja/AILEE
acb2a718433156f88a59510121cdc652051d5dfc
01236c3da46cb049e4b4b821190399cde5491522
refs/heads/master
2020-05-15T07:09:14.691249
2019-09-13T18:54:20
2019-09-13T18:54:20
182,133,852
1
0
null
2019-04-25T21:21:25
2019-04-18T17:56:07
Python
UTF-8
Python
false
false
227
py
__all__ = [] import os files = [f for f in os.listdir('events') if f.endswith('.py')] __all__ = [f[:-3] for f in files if not f.startswith('__')] __events__ = [f for f in __all__ if f.startswith('event')] from events import *
[ "grant.haataja@gmail.com" ]
grant.haataja@gmail.com
3805406d7d67e5a498dfff6b970543445e2a268e
1fb55ab2c082348eb51263357563d20e1fd50b7d
/commons/c2cgeoportal_commons/alembic/main/29f2a32859ec_merge_1_6_and_master_branches.py
e92c014cbf7e91b379db31f2314f86152fee5f02
[ "BSD-2-Clause-Views" ]
permissive
nstoykov/c2cgeoportal
40876bf577cc2ed1877affa9f307acef94d86daa
42c3aab09e0c44a20d0162a85c51c6a9ca0ff95e
refs/heads/master
2020-12-06T03:27:00.330795
2020-01-07T09:25:07
2020-01-07T09:25:07
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,944
py
# -*- coding: utf-8 -*- # Copyright (c) 2015-2019, Camptocamp SA # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # The views and conclusions contained in the software and documentation are those # of the authors and should not be interpreted as representing official policies, # either expressed or implied, of the FreeBSD Project. """Merge 1.6 and master branches Revision ID: 29f2a32859ec Revises: ('22e6dfb556de', '116b9b79fc4d') Create Date: 2015-12-16 14:10:56.704614 """ # revision identifiers, used by Alembic. revision = "29f2a32859ec" down_revision = ("22e6dfb556de", "116b9b79fc4d") branch_labels = None depends_on = None def upgrade(): pass def downgrade(): pass
[ "stephane.brunner@camptocamp.com" ]
stephane.brunner@camptocamp.com
77d13a603375942a0aa68db833cb5b494614626e
5d361a29e7eb009a454318f3621b9c2d22e74c20
/manage.py
8bd6f491853d614cf5d6b8a670a08e947a32e88c
[]
no_license
warmthemall/warmthemall
39758b9c766721d88acedcc9f53c50e9abfcc095
1a21cf3a03ac94b101a1a74f3d6aa59492393d0f
refs/heads/master
2021-01-21T13:03:09.707914
2016-04-21T00:29:50
2016-04-21T00:29:50
54,979,951
0
0
null
null
null
null
UTF-8
Python
false
false
254
py
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "warmthemall.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
[ "warmthemallqu@gmail.com" ]
warmthemallqu@gmail.com
13a4b39436715aef79dafb5bd994d2e385067fa4
21499f0e7695177514e57c64ec775b6c8ba210e4
/Python Scripts/Load_Bays.py
13f2f3154c6a75f7f6cef7274a4d47c5faaf6bfe
[]
no_license
shirl90/nhd_Project
1b869c0154b29d4c3bf6314f8234ef319aef2bce
36ebf81e29ce593a66333bc03728a144d6da5585
refs/heads/master
2016-08-04T11:39:02.393664
2014-10-24T04:44:33
2014-10-24T04:44:33
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,011
py
''' ---------------------------------------------------------------------------------- Source Name: Load_Bays.py Version: ArcGIS 10.1 Author: Shirly Stephen FeatureCode : -------------------------------------------------------------------------------- ''' # Import system modules import arcpy ### Set the workspace outFile = open("Z:\Documents\Shirly\Ontology Research\Output\List_Bays.txt", "w") print "Workspace Space Set" bayTable = "Z:\Documents\Shirly\Ontology Research\Data-To Work\NHDPlusNE.gdb\ExtraData_GNIS\Bay" # Create a search cursor where_clause = "STATE_ALPH = 'ME'" #where_clause = "[" + fieldname + "] = " + value # for Personal Geodatabase bay_Table = arcpy.SearchCursor (bayTable, where_clause, "", "", "") for rows in bay_Table: GNISName = rows.getValue("FEATURE_NA") GNISID = rows.getValue("FEATURE_ID") outFile.write(str(str(GNISID) + ' ; ' +str(GNISName))+'\n') #print GNISName #rows = Stream_Table.next() outFile.close()
[ "shirly.rock@gmail.com" ]
shirly.rock@gmail.com
63df08aefaa3c1c7cab07d65e38a0de2816880ca
a0801d0e7325b31f0383fc68517e208680bb36d6
/Kattis/commercials.py
fe78e87a705a79461a41b0c9e1c0aa6f1c6b0f44
[]
no_license
conormccauley1999/CompetitiveProgramming
bd649bf04438817c7fa4755df2c2c7727273b073
a7e188767364be40f625612af3d16182f2d8d4de
refs/heads/master
2023-05-14T13:19:32.678134
2023-05-11T16:07:33
2023-05-11T16:07:33
179,089,010
0
0
null
null
null
null
UTF-8
Python
false
false
218
py
n, p = map(int, input().split()) vs = list(map(int, input().split())) for i in range(n): vs[i] -= p mx = -10e8 mxh = 0 for i in range(n): mxh = mxh + vs[i] mx = max(mx, mxh) mxh = max(mxh, 0) print(mx)
[ "conormccauley1999@gmail.com" ]
conormccauley1999@gmail.com
721a3e23ac9eafa3b91b240abb7c11c9e475bc15
61a50a8bb13ae69ef1c1ebb517fc20fb4f7b9fdd
/cython_setup.py
186a19133b2abc14af8c3d7d8d5a5f763e70604b
[]
no_license
justimchung/ProductUpgrade
44508583d9a7e6ed00d2be2ed091ae234928c77a
340ef1a49739d73b2fd5cc30145a008f3e845b78
refs/heads/master
2021-01-16T23:51:40.750250
2016-10-07T06:22:03
2016-10-07T06:22:03
58,130,732
0
0
null
null
null
null
UTF-8
Python
false
false
437
py
# -*- coding:utf-8 -*- """ 它是用來將 python 的程式碼轉成 cython 所需要的設定檔 """ # Cython compile instructions from distutils.core import setup from Cython.Build import cythonize import os import numpy # Use python cython_setup.py build_ext --inplace # to compile setup( name = "k_dom_util", ext_modules = cythonize('*.pyx'), include_dirs=[numpy.get_include(), os.path.join(numpy.get_include(), 'numpy')] )
[ "justim@gmail.com" ]
justim@gmail.com
197d249f49a3bf0f4bbe8e5c1e093ff2fd5d13c1
6f23adb3da803dda89e21cfa21a024a015ec1710
/2020/16-2.py
8883ed2bc121687d8e600f19d5385f5a9769ba9f
[]
no_license
Remboooo/adventofcode
1478252bcb19c0dd19e4fa2effd355ee71a5d349
5647b8eddd0a3c7781a9c21019f6f06f6edc09bd
refs/heads/master
2022-12-15T10:21:29.219459
2022-12-13T23:02:03
2022-12-13T23:02:03
226,883,142
0
0
null
null
null
null
UTF-8
Python
false
false
3,264
py
from argparse import ArgumentParser from collections import defaultdict from functools import reduce from itertools import islice, count from pprint import pprint from util import timed def parse_rules(f): rules = {} for line in f: line = line.strip() if line == "": break name, values = line.split(": ", 1) rules[name] = [tuple(int(v) for v in r.split("-", 1)) for r in values.split(" or ")] return rules def parse_my_ticket(f): if f.readline().strip() != "your ticket:": raise ValueError("First line was not 'your ticket:'") result = tuple(int(field) for field in f.readline().split(',')) f.readline() return result def parse_tickets(f): if f.readline().strip() != "nearby tickets:": raise ValueError("First line was not 'nearby tickets:'") for line in f: line = line.strip() yield tuple(int(field) for field in line.split(',')) @timed def get_valid_tickets(nearby_tickets, rules): # A ticket is valid if *all* fields match *any* of the rules return [ ticket for ticket in nearby_tickets if all(any(rlow <= field <= rhigh for rule in rules.values() for rlow, rhigh in rule) for field in ticket) ] @timed def find_field_ids(nearby_tickets, rules): field_ids = {} # For every field name in the rulebook, check which field IDs match its rules on all of the valid tickets for field_name, rule in rules.items(): # Start by considering every possible field ID for this name possible_ids = set(range(len(nearby_tickets[0]))) for ticket in nearby_tickets: # Prune the possible IDs for this field name by checking which field IDs match its rules on this ticket possible_ids &= {n for n, field in enumerate(ticket) if any(rlow <= field <= rhigh for rlow, rhigh in rule)} field_ids[field_name] = possible_ids # Some fields still have multiple possibilities after checking all of the tickets, but then others only have one, # so there's some overlap and we can eliminate the ambiguities. # I'm 99% sure this will not work in all possible cases, but it works for the test input and my puzzle input 🤷🏻‍ field_ids = { name: next( fid for fid in pid if not any( # if there's another field with a shorter list of ID options that also contains this ID, skip it name != oname and len(opid) < len(pid) and fid in opid for oname, opid in field_ids.items() ) ) for name, pid in field_ids.items() } return field_ids def main(): argparse = ArgumentParser() argparse.add_argument("file", nargs='?', type=str, default="16-input.txt") args = argparse.parse_args() with open(args.file, 'r') as f: rules = parse_rules(f) my_ticket = parse_my_ticket(f) nearby_tickets = list(parse_tickets(f)) nearby_tickets = get_valid_tickets(nearby_tickets, rules) field_ids = find_field_ids(nearby_tickets, rules) print( reduce(lambda a, b: a * b, (my_ticket[fid] for name, fid in field_ids.items() if name.startswith('departure'))) ) if __name__ == '__main__': main()
[ "rembrand.vanlakwijk@nedap.com" ]
rembrand.vanlakwijk@nedap.com
3f42ac3e745b95a6f434a1d8d947ef0c3d66e83a
57d9c43774ddbf8e6e9460b7b0343c10471a2f63
/mysite/polls/models.py
e2018cf4980c11e1eda837addc68551317c1eaab
[]
no_license
zulalgdk/django-project
8fb01de3ed69c638396faf30a7b3ba0209e4e1a0
79b692f3633589f03ec685d5e7d78ff240496a7c
refs/heads/master
2021-01-22T19:54:02.280121
2017-08-18T12:51:47
2017-08-18T12:51:47
100,711,253
0
0
null
null
null
null
UTF-8
Python
false
false
834
py
import datetime from django.db import models from django.utils import timezone from django.utils.encoding import python_2_unicode_compatible class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.pub_date <= now class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
[ "zulal__guduk@hotmail.com" ]
zulal__guduk@hotmail.com
b80fd84ef155c45a534c775faf4fe4571af8a2f4
534af65ceead2d1ad04e2b5e0bfc87c35f065729
/com/obs/utils/request_format.py
41bf2ae251505947c3d20afd449ccd9312e5f7be
[]
no_license
FunctionStage/ImageWatermark
df0e536644280ff2a1af049e262561e375f3da4b
6143d730c7178042a1f61373bfb92d460bee6eaf
refs/heads/master
2021-09-12T21:22:01.179775
2018-04-21T02:33:59
2018-04-21T02:33:59
109,988,029
3
0
null
null
null
null
UTF-8
Python
false
false
5,906
py
#!/usr/bin/python # -*- coding:utf-8 -*- from com.obs.models.base_model import IS_PYTHON2 if IS_PYTHON2: import urllib else: import urllib.parse as urllib #=============================================================================== # 请求格式,发送HTTP请求时,URL是路径模式或者子域名格式 #=============================================================================== class RequestFormat(object): @staticmethod def get_pathformat(): return PathFormat() @staticmethod def get_subdomainformat(): return SubdomainFormat() @staticmethod def get_vanityformat(): return VanityFormat() # =========================================================================== # 将路径参数从map类型转换为字符串 # @path_args 参数hash表 # @return 转换后的路径参数字符串 # =========================================================================== @classmethod def convert_path_string(cls, path_args, allowdNames=None, safe=' ,:?/=+&%'): e = '' if isinstance(path_args, dict): e1 = '?' e2 = '&' for path_key, path_value in path_args.items(): flag = True if allowdNames is not None and path_key not in allowdNames: flag = False if flag: path_key = urllib.quote(str(path_key), safe) if path_value is None: e1 += path_key + '&' continue e2 += path_key + '=' + urllib.quote(str(path_value), safe) + '&' e = (e1 + e2).replace('&&', '&').replace('?&', '?')[:-1] return e @classmethod def toString(cls,item): try: return str(item) if item is not None else '' except: return '' @classmethod def encode_object_key(cls, key): return urllib.quote(cls.toString(key), ',:?/=+&%') def supports_locatedbuckets(self): ''' ''' return def get_endpoint(self, server, port, bucket): ''' ''' return def get_pathbase(self, bucket, key): ''' ''' return def get_url(self, bucket, key, path_args): ''' ''' return #========================================================================== # 请求方式类,路径请求方式。 # 带对象和存储空间的请求为:s3.xxxx.com/bucketname/key # 不带对象,带存储空间的请求为:s3.xxxx.com/bucketname/ # 不带存储空间和对象的的请求为:s3.xxxx.com/ #========================================================================== class PathFormat(RequestFormat): def supports_locatedbuckets(self): return True def get_server(self, server, bucket): return server def get_pathbase(self, bucket, key): if not bucket: return '/' if key is None: return '/' + bucket return '/' + bucket + '/' + self.encode_object_key(key) def get_endpoint(self, server, port, bucket): return server + ':' + str(port) #=========================================================================== # 获得相对url #=========================================================================== def get_url(self, bucket, key, path_args): path_base = self.get_pathbase(bucket, key) path_arguments = self.convert_path_string(path_args) return path_base + path_arguments #=========================================================================== # 获得绝对url 完整路径 #=========================================================================== def get_full_url(self, is_secure, server, port, bucket, key, path_args): url = 'https://' if is_secure else 'http://' url += self.get_endpoint(server, port, bucket) url += self.get_url(bucket, key, path_args) return url #=============================================================================== # 请求方式类,子域请求方式。 # 带对象和存储空间的请求为:bucketname.s3.xxxx.com/key # 不带对象,带存储空间的请求为:bucketname.s3.xxxx.com/ # 不带存储空间和对象的的请求为:s3.xxxx.com/ #=============================================================================== class SubdomainFormat(RequestFormat): def supports_locatedbuckets(self): return True def get_server(self, server, bucket): return bucket + '.' + server if bucket else server def get_pathbase(self, bucket, key): if key is None: return '/' return '/' + self.encode_object_key(key) def get_endpoint(self, server, port, bucket): return self.get_server(server, bucket) + ':' + str(port) #=========================================================================== # 获得相对url #=========================================================================== def get_url(self, bucket, key, path_args): url = self.convert_path_string(path_args) return self.get_pathbase(bucket, key) + url if bucket else url #=========================================================================== # 获得绝对url 完整路径 #=========================================================================== def get_full_url(self, is_secure, server, port, bucket, key, path_args): url = 'https://' if is_secure else 'http://' url += self.get_endpoint(server, port, bucket) url += self.get_url(bucket, key, path_args) return url class VanityFormat(SubdomainFormat): def get_server(self, server, bucket): return bucket
[ "shibaotong@gmail.com" ]
shibaotong@gmail.com
d9488e55773f53b084a0d709450f00dfefd69089
299fe2ca879e509798e95c00b7ba33914031f4a7
/eruditio/shared_apps/django_wizard/wizard.py
dbfab0dcfbd21b9bc03b532bad0f2afd2d52e2e6
[ "MIT" ]
permissive
genghisu/eruditio
dcf2390c98d5d1a7c1044a9221bf319cb7d1f0f6
5f8f3b682ac28fd3f464e7a993c3988c1a49eb02
refs/heads/master
2021-01-10T11:15:28.230527
2010-04-23T21:13:01
2010-04-23T21:13:01
50,865,100
0
0
null
null
null
null
UTF-8
Python
false
false
2,097
py
from django_wizard.models import ConfigOption, ConfigFixture, DefinedConfigOption from django.core.exceptions import ObjectDoesNotExist class ConfigIndex(object): def __init__(self): self._registry = {} def register(self, configuration): if configuration.__class__ == ConfigOption and not (configuration.app, configuration.name) in self._registry: try: existing_config = ConfigOption.objects.get(app = configuration.app, name = configuration.name) except ObjectDoesNotExist: configuration.save() existing_config = configuration try: defined_config = DefinedConfigOption.objects.get(option__name = configuration.name, option__app = configuration.app) except ObjectDoesNotExist: defined_config = DefinedConfigOption(option = existing_config, value = configuration.default) defined_config.save() self._registry[(configuration.app, configuration.name)] = existing_config def unregister(self, configuration): try: existing_config = ConfigOption.objects.get(app = configuration.app, name = configuration.name) existing_config.delete() del self._registry[(configuration.app, configuration.name)] except ObjectDoesNotExist: pass def clear_registry(self): self._registry = {} config_index = ConfigIndex() class FixtureIndex(object): def __init__(self): self._registry = {} def register(self, fixture): if not (fixture.app_label, fixture.module_name) in self._registry: try: existing_fixture = ConfigFixture.objects.get(app_label = fixture.app_label, module_name = fixture.module_name) except ObjectDoesNotExist: fixture.save() existing_fixture = fixture self._registry[(fixture.app_label, fixture.module_name)] = fixture fixtures_index = FixtureIndex()
[ "genghisu@6a795458-236b-11df-a5e4-cb4ff25536bb" ]
genghisu@6a795458-236b-11df-a5e4-cb4ff25536bb
e0fd65e046d41a3d74cc70a6f6e48a82aff64f1e
dd3ae3fecd71db22ea0c14da081b9f6d937a1edc
/Year 3/LP4/Subatomär/K6/k6-emulator/physics.py
37630c75c8f4957ce85b3662665f1f4695f925b5
[]
no_license
dtonderski/School
d59154c5b8eefc64cda6c15826c151c827509391
b362d1229ed21f2bd03fac5f096241aa9c8046cc
refs/heads/master
2023-02-13T00:47:26.190869
2021-01-14T10:22:38
2021-01-14T10:22:38
300,598,386
0
0
null
null
null
null
UTF-8
Python
false
false
1,358
py
import numpy as np # Decay constants of Ag108 and Ag110 (per second) lambda_108 = 0.693 / (2.4 * 60) lambda_110 = 0.693 / 25.0 # Calculate the expected number of decays in # the interval [t0, t1] for a single isotope. def calculate_decays_in_interval_single(n, lmbda, t0, t1): return n * (np.exp(-lmbda*t0) - np.exp(-lmbda*t1)) # Calculate the expected number of decays in # the interval [t0, t1] for each of the two isotopes. def calculate_decays_in_interval(nnuclei, t0, t1): ndecays_108 = calculate_decays_in_interval_single(nnuclei[0], lambda_108, t0, t1) ndecays_110 = calculate_decays_in_interval_single(nnuclei[1], lambda_110, t0, t1) return np.array([ndecays_108, ndecays_110]) # Calculate the total number of expected decays in the time interval. def total_decays_in_interval(nnuclei, t0, t1): return np.sum(calculate_decays_in_interval(nnuclei, t0, t1)) # Draws a random number of decays in time period dt, # given the previous number of nuclei, nnuclei. # A random number generator is passed along too def decay(nnuclei, dt, rng): expected_decays = calculate_decays_in_interval(nnuclei, 0, dt) ndecays = np.zeros(2, dtype=int) if expected_decays[0] > 0: ndecays[0] = rng.poisson(expected_decays[0]) if expected_decays[1] > 0: ndecays[1] = rng.poisson(expected_decays[1]) return ndecays
[ "dtonderski@gmail.com" ]
dtonderski@gmail.com
d2f817ce547020deb24980787d61a4775fe21557
0f6f95af209ff9192702c2176c4513cb28929ba5
/syd/commands/base.py
ff759bd373fea19e05e2ad6b670aa903bdbfd1e8
[]
no_license
SD2E/aliases-cli
87a03f83cbbed5f5860e77457718f7eb6121a311
c634012a2623b975b8eeb6e210fabe51fe53a6ab
refs/heads/master
2020-03-10T19:33:47.852609
2018-04-18T22:27:40
2018-04-18T22:27:40
129,550,330
1
0
null
2018-04-17T19:55:08
2018-04-14T20:01:52
Python
UTF-8
Python
false
false
425
py
"""The base command.""" from agavepy.agave import Agave from .reactors import alias class Base(object): """A base command.""" def __init__(self, options, *args, **kwargs): self.options = options self.args = args self.kwargs = kwargs self.store = alias.AliasStore(Agave.restore()) def run(self): raise NotImplementedError('You must implement the run() method yourself!')
[ "vaughn@tacc.utexas.edu" ]
vaughn@tacc.utexas.edu
e5755a3d897e49d3a0ef501d254813c4afb0c40e
f4b60f5e49baf60976987946c20a8ebca4880602
/lib64/python2.7/site-packages/acimodel-1.3_2j-py2.7.egg/cobra/modelimpl/bgp/ctxafdef.py
d649b8e14aa620c77367e3c7b8b845e9914a019b
[]
no_license
cqbomb/qytang_aci
12e508d54d9f774b537c33563762e694783d6ba8
a7fab9d6cda7fadcc995672e55c0ef7e7187696e
refs/heads/master
2022-12-21T13:30:05.240231
2018-12-04T01:46:53
2018-12-04T01:46:53
159,911,666
0
0
null
2022-12-07T23:53:02
2018-12-01T05:17:50
Python
UTF-8
Python
false
false
6,835
py
# coding=UTF-8 # ********************************************************************** # Copyright (c) 2013-2016 Cisco Systems, Inc. All rights reserved # written by zen warriors, do not modify! # ********************************************************************** from cobra.mit.meta import ClassMeta from cobra.mit.meta import StatsClassMeta from cobra.mit.meta import CounterMeta from cobra.mit.meta import PropMeta from cobra.mit.meta import Category from cobra.mit.meta import SourceRelationMeta from cobra.mit.meta import NamedSourceRelationMeta from cobra.mit.meta import TargetRelationMeta from cobra.mit.meta import DeploymentPathMeta, DeploymentCategory from cobra.model.category import MoCategory, PropCategory, CounterCategory from cobra.mit.mo import Mo # ################################################## class CtxAfDef(Mo): """ The BGP address family context definition. """ meta = ClassMeta("cobra.model.bgp.CtxAfDef") meta.moClassName = "bgpCtxAfDef" meta.rnFormat = "bgpCtxAfP-%(af)s" meta.category = MoCategory.REGULAR meta.label = "Address Family Context Definition" meta.writeAccessMask = 0x20000001 meta.readAccessMask = 0x20000001 meta.isDomainable = False meta.isReadOnly = True meta.isConfigurable = False meta.isDeletable = False meta.isContextRoot = False meta.childClasses.add("cobra.model.fault.Delegate") meta.childNamesAndRnPrefix.append(("cobra.model.fault.Delegate", "fd-")) meta.parentClasses.add("cobra.model.fv.RtdEpP") meta.parentClasses.add("cobra.model.fv.BrEpP") meta.superClasses.add("cobra.model.bgp.ACtxAfPol") meta.superClasses.add("cobra.model.fabric.L3CtxPol") meta.superClasses.add("cobra.model.fabric.ProtoPol") meta.superClasses.add("cobra.model.fabric.ProtoDomPol") meta.superClasses.add("cobra.model.naming.NamedObject") meta.superClasses.add("cobra.model.pol.Obj") meta.superClasses.add("cobra.model.pol.Def") meta.superClasses.add("cobra.model.fabric.L3DomPol") meta.rnPrefixes = [ ('bgpCtxAfP-', True), ] prop = PropMeta("str", "af", "af", 17566, PropCategory.REGULAR) prop.label = "Address Family" prop.isConfig = True prop.isAdmin = True prop.isCreateOnly = True prop.isNaming = True prop.defaultValue = 1 prop.defaultValueStr = "ipv4-ucast" prop._addConstant("ipv4-ucast", "ipv4-unicast-address-family", 1) prop._addConstant("ipv6-ucast", "ipv6-unicast-address-family", 3) prop._addConstant("vpnv4-ucast", "vpnv4-unicast-address-family", 2) prop._addConstant("vpnv6-ucast", "vpnv6-unicast-address-family", 4) meta.props.add("af", prop) prop = PropMeta("str", "childAction", "childAction", 4, PropCategory.CHILD_ACTION) prop.label = "None" prop.isImplicit = True prop.isAdmin = True prop._addConstant("deleteAll", "deleteall", 16384) prop._addConstant("deleteNonPresent", "deletenonpresent", 8192) prop._addConstant("ignore", "ignore", 4096) meta.props.add("childAction", prop) prop = PropMeta("str", "descr", "descr", 5579, PropCategory.REGULAR) prop.label = "Description" prop.isConfig = True prop.isAdmin = True prop.range = [(0, 128)] prop.regex = ['[a-zA-Z0-9\\!#$%()*,-./:;@ _{|}~?&+]+'] meta.props.add("descr", prop) prop = PropMeta("str", "dn", "dn", 1, PropCategory.DN) prop.label = "None" prop.isDn = True prop.isImplicit = True prop.isAdmin = True prop.isCreateOnly = True meta.props.add("dn", prop) prop = PropMeta("str", "eDist", "eDist", 17563, PropCategory.REGULAR) prop.label = "eBGP Distance" prop.isConfig = True prop.isAdmin = True prop.range = [(1, 255)] prop.defaultValue = 20 prop.defaultValueStr = "20" meta.props.add("eDist", prop) prop = PropMeta("str", "iDist", "iDist", 17564, PropCategory.REGULAR) prop.label = "iBGP Distance" prop.isConfig = True prop.isAdmin = True prop.range = [(1, 255)] prop.defaultValue = 200 prop.defaultValueStr = "200" meta.props.add("iDist", prop) prop = PropMeta("str", "lcOwn", "lcOwn", 9, PropCategory.REGULAR) prop.label = "None" prop.isImplicit = True prop.isAdmin = True prop.defaultValue = 0 prop.defaultValueStr = "local" prop._addConstant("implicit", "implicit", 4) prop._addConstant("local", "local", 0) prop._addConstant("policy", "policy", 1) prop._addConstant("replica", "replica", 2) prop._addConstant("resolveOnBehalf", "resolvedonbehalf", 3) meta.props.add("lcOwn", prop) prop = PropMeta("str", "localDist", "localDist", 17565, PropCategory.REGULAR) prop.label = "Local Distance" prop.isConfig = True prop.isAdmin = True prop.range = [(1, 255)] prop.defaultValue = 220 prop.defaultValueStr = "220" meta.props.add("localDist", prop) prop = PropMeta("str", "modTs", "modTs", 7, PropCategory.REGULAR) prop.label = "None" prop.isImplicit = True prop.isAdmin = True prop.defaultValue = 0 prop.defaultValueStr = "never" prop._addConstant("never", "never", 0) meta.props.add("modTs", prop) prop = PropMeta("str", "name", "name", 4991, PropCategory.REGULAR) prop.label = "Name" prop.isConfig = True prop.isAdmin = True prop.range = [(0, 64)] prop.regex = ['[a-zA-Z0-9_.:-]+'] meta.props.add("name", prop) prop = PropMeta("str", "ownerKey", "ownerKey", 15230, PropCategory.REGULAR) prop.label = "None" prop.isConfig = True prop.isAdmin = True prop.range = [(0, 128)] prop.regex = ['[a-zA-Z0-9\\!#$%()*,-./:;@ _{|}~?&+]+'] meta.props.add("ownerKey", prop) prop = PropMeta("str", "ownerTag", "ownerTag", 15231, PropCategory.REGULAR) prop.label = "None" prop.isConfig = True prop.isAdmin = True prop.range = [(0, 64)] prop.regex = ['[a-zA-Z0-9\\!#$%()*,-./:;@ _{|}~?&+]+'] meta.props.add("ownerTag", prop) prop = PropMeta("str", "rn", "rn", 2, PropCategory.RN) prop.label = "None" prop.isRn = True prop.isImplicit = True prop.isAdmin = True prop.isCreateOnly = True meta.props.add("rn", prop) prop = PropMeta("str", "status", "status", 3, PropCategory.STATUS) prop.label = "None" prop.isImplicit = True prop.isAdmin = True prop._addConstant("created", "created", 2) prop._addConstant("deleted", "deleted", 8) prop._addConstant("modified", "modified", 4) meta.props.add("status", prop) meta.namingProps.append(getattr(meta.props, "af")) def __init__(self, parentMoOrDn, af, markDirty=True, **creationProps): namingVals = [af] Mo.__init__(self, parentMoOrDn, markDirty, *namingVals, **creationProps) # End of package file # ##################################################
[ "collinsctk@qytang.com" ]
collinsctk@qytang.com
2b635c686116d35e68b27c54c8e51ce63188ca13
019bb87ff1b6958fbc8e4f9debfc2e6d3c2475d0
/demoapp/views.py
c5245c0c0483d38154f57da8a568dbdb989b392f
[]
no_license
daxuliu/software
0ba5604fec4534ecbf8ea02e99e7a02e48a889b1
c8deecbf3ec13e2587bacef02ea54d5007eef73f
refs/heads/master
2022-12-13T06:13:04.504998
2020-09-10T03:03:40
2020-09-10T03:03:40
294,123,978
0
0
null
null
null
null
UTF-8
Python
false
false
369
py
from django.shortcuts import render # Create your views here. from django.conf.urls import url from . import view urlpatterns = [ url(r'^$', view.hello), url(r'^$', view.exa), url(r'^$', view.img), url(r'^$',view.addgood), url(r'^$',view.change), url(r'^$',view.select), url(r'^$',view.judge),url(r'^$',view.Passages), ]
[ "1697935859@qq.com" ]
1697935859@qq.com
7f0647971b6942014c2858a68d7ffcb1164791cf
ad2cecf4187cf5066e95cceb6adacb41908c2472
/python/gigasecond/gigasecond_test.py
01d62a5b11e2469e6ec1fe3c721976e1ce87a9aa
[]
no_license
mstange22/Exercism
ac0d15dd3555d24b5c9f44345e63bfd8ebf68da5
23903125853c870a972e29d4b6b6bb260ee4ab3b
refs/heads/master
2023-01-12T19:33:30.632673
2020-10-18T15:30:47
2020-10-18T15:30:47
164,342,472
0
0
null
2023-01-06T04:33:04
2019-01-06T20:22:42
C++
UTF-8
Python
false
false
1,440
py
import unittest from datetime import datetime from gigasecond import add_gigasecond # Tests adapted from `problem-specifications//canonical-data.json` @ v2.0.0 class GigasecondTest(unittest.TestCase): def test_date_only_specification_of_time(self): self.assertEqual( add_gigasecond(datetime(2011, 4, 25)), datetime(2043, 1, 1, 1, 46, 40)) def test_another_date_only_specification_of_time(self): self.assertEqual( add_gigasecond(datetime(1977, 6, 13)), datetime(2009, 2, 19, 1, 46, 40)) def test_one_more_date_only_specification_of_time(self): self.assertEqual( add_gigasecond(datetime(1959, 7, 19)), datetime(1991, 3, 27, 1, 46, 40)) def test_full_time_specified(self): self.assertEqual( add_gigasecond(datetime(2015, 1, 24, 22, 0, 0)), datetime(2046, 10, 2, 23, 46, 40)) def test_full_time_with_day_roll_over(self): self.assertEqual( add_gigasecond(datetime(2015, 1, 24, 23, 59, 59)), datetime(2046, 10, 3, 1, 46, 39)) def test_yourself(self): # customize this to test your birthday and find your gigasecond date: your_birthday = datetime(1970, 1, 1) your_gigasecond = datetime(2001, 9, 9, 1, 46, 40) self.assertEqual(add_gigasecond(your_birthday), your_gigasecond) if __name__ == '__main__': unittest.main()
[ "mstange@dthera.com" ]
mstange@dthera.com
897ad7e176ebf755416c4ef9da8439614ab668bc
eca943a64310efd88e304ea4c0cecb2886ceefd5
/pythonr/lista04/zad02.py
651156c3cd9a26c06c814cc8e985f18cd8249030
[]
no_license
0sk4r/Uwr
b20696a4c3df9c86994869e34681cd66e699362d
f2587845e351ba53a44ba27912aa0dfb693c8765
refs/heads/master
2021-07-25T23:42:38.099511
2021-04-09T18:36:29
2021-04-09T18:36:29
52,679,999
0
0
null
null
null
null
UTF-8
Python
false
false
1,770
py
from io import StringIO def upper_first(str): return str[0].upper() + str[1:] def korekta(str): str = upper_first(str) if str[-2:] == '. ': return str elif str[-1] == '.': return str + ' ' else: return str + '. ' def zdania(stream): sentences = stream.read().split(sep='.') sentences = filter( None, map(lambda s: s.replace("\n", " ").strip(), sentences)) for s in sentences: yield "%s." % s if __name__ == "__main__": str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Pellentesque elit ullamcorper dignissim cras tincidunt lobortis. Faucibus ornare suspendisse sed nisi lacus sed viverra tellus. Quam id leo in vitae turpis massa. Tristique senectus et netus et malesuada fames. Convallis tellus id interdum velit laoreet id donec. At augue eget arcu dictum varius. Scelerisque varius morbi enim nunc faucibus a pellentesque sit. At imperdiet dui accumsan sit amet nulla. In tellus integer feugiat scelerisque. Nec ultrices dui sapien eget mi. At auctor urna nunc id cursus metus aliquam. Elit scelerisque mauris pellentesque pulvinar pellentesque habitant morbi tristique. Ullamcorper velit sed ullamcorper morbi. Tempor nec feugiat nisl pretium. Leo in vitae turpis massa. Quis imperdiet massa tincidunt nunc pulvinar sapien et ligula. Purus faucibus ornare suspendisse sed. Purus non enim praesent elementum facilisis leo vel fringilla. Commodo nulla facilisi nullam vehicula." in1 = StringIO(str) in2 = StringIO(str) before = list(zdania(in1)) after = list(map(lambda s: korekta(s), zdania(in2))) print("Przed: ", before) print("Po: ", after) in1.close() in2.close()
[ "sobczykoskar@gmail.com" ]
sobczykoskar@gmail.com
a4a181d9be86dc62432fbdc0cbad1778b1a8fae0
9c5d4e55f4f83afdcf42f06d1289086753751f45
/python/Tema 3/Ejercicio4tema3.py
db6cc75333625833c5fd060e2b709eaaf2969e3b
[]
no_license
alexjorlo/iw-Ejercicios-html
bc8c6ac9eb9831002e372b3c75d33aab398c020f
3ddd704ea5521a250fb6408fe5dbc82deff553bc
refs/heads/master
2021-01-02T22:02:38.506830
2020-04-25T13:24:23
2020-04-25T13:24:23
239,818,708
0
0
null
null
null
null
UTF-8
Python
false
false
409
py
usuario=str("root") contraseña=str("root") intento=3 while(intento>0): X=str(input("Escriba el usuario: ")) Y=str(input("Escriba la contraseña: ")) if X.__eq__(usuario) and Y.__eq__(contraseña): print("Bienvenido") else: print("error") intento=intento-1 print(f"Te quedan {intento} intentos") if (intento==0): print("Te has quedado sin oportunidades")
[ "alejandro.jorge@opendeusto.es" ]
alejandro.jorge@opendeusto.es
c13daefa47e7bfd9bb6125fc5e926a3bfb322f89
accd88f6b7036d5a102f60186ede195240ff5688
/venv/bin/wheel
f7eb75ef035ed7a447f46dd356dea5efd589b308
[]
no_license
abhiyan52/codesharing
1270d1c8e71c4949cf69e541e028e542f175afb7
ee5942c2c131540a7748cb6d224ba9fb4f3ec921
refs/heads/master
2020-04-20T10:47:15.388642
2019-02-02T17:06:55
2019-02-02T17:06:55
168,798,593
0
0
null
null
null
null
UTF-8
Python
false
false
254
#!/home/abhiyantimilsina/Desktop/codemirror/venv/bin/python3 # -*- coding: utf-8 -*- import re import sys from wheel.cli import main if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit(main())
[ "abhiyantimilsina@gmail.com" ]
abhiyantimilsina@gmail.com
52bac37037d550c2a2aae038c7e551a45f41832d
91da8a59561d6f2c7852c0548298434e0ede2ac7
/Linked list/sort_a_linkedList.py
a0ff4d4ccaf23fb3e9297409fbd6d52413ca3256
[]
no_license
prashant97sikarwar/leetcode
6d3828772cc426ccf53dad07edb1efbc2f1e1ded
e76054e27a5d4493bd1bcef2ebdeb21d257afb63
refs/heads/master
2023-08-23T05:06:23.181869
2021-10-28T18:19:10
2021-10-28T18:19:10
286,057,727
0
0
null
null
null
null
UTF-8
Python
false
false
1,346
py
"""Sort a linked list in O(n log n) time using constant space complexity.""" # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def sortList(self, head: ListNode) -> ListNode: if head is None or head.next is None: return head middle = self.findMiddle(head) nextToMiddle = middle.next middle.next = None left = self.sortList(head) right = self.sortList(nextToMiddle) sortedList = self.finalMergeSort(left, right) return sortedList def findMiddle(self, node): if node is None or node.next is None: return node slow = node fast = node while (fast.next != None and fast.next.next != None): slow = slow.next fast = fast.next.next return slow def finalMergeSort(self, a, b): result = None if a == None: return b if b == None: return a if a.val <= b.val: result = a result.next = self.finalMergeSort(a.next, b) else: result = b result.next = self.finalMergeSort(a, b.next) return result
[ "prashant97sikarwar@gmail.com" ]
prashant97sikarwar@gmail.com
7ec797ebd713bd8fe2e4fcf0632b4193c4995b27
42d25cfa8b9e1b0e5f1e5708d016a46c8636ced9
/escape.py
4f5e358d4a7a2d1f8473dfedaed51d52b4750064
[]
no_license
horlas/OC_Project3
e78ee40cf0c5cef685d296a5d99f6f34b7023380
cdc61cac45e31e49215cf7f6b892bb30c16edb46
refs/heads/master
2020-03-07T21:39:30.809881
2018-04-16T13:26:20
2018-04-16T13:26:20
127,732,766
0
2
null
null
null
null
UTF-8
Python
false
false
4,523
py
#!/usr/bin/python3.5 # -*-coding:utf-8 - """Program "Help MacGyver to escape!""" from constant import* from classes import* #Open game window pygame.display.set_icon(ICONE) pygame.display.set_caption(TITLE_WINDOW) ######MAIN_LOOP############ MAIN_LOOP = True while MAIN_LOOP: #Load home screen window.blit(BLACK_GROUND, (0, 0)) window.blit(HOME, (30, 30)) #Reload display pygame.display.flip() ######HOME LOOP############### HOME_LOOP = True while HOME_LOOP: #play soundtrack #SOUNDTRACK.play() #loop delay pygame.time.Clock().tick(30) for event in pygame.event.get(): #Quit the program if event.type == QUIT: print("Bye bye!") MAIN_LOOP = False HOME_LOOP = False GAME_LOOP = False #Quit home loop to enter in game loop if event.type == KEYDOWN and event.key == K_RETURN: #######WELCOME TO THE GAME########## SOUNDTRACK.stop() window.blit(BACKGROUND, (30, 30)) window.blit(WELCOME, (120, 150)) pygame.display.flip() time.sleep(1) #################################### HOME_LOOP = False GAME_LOOP = True #Load the game's map FILE = "map/N1.txt" if FILE != "": #We make sure that the file really exists and is not empty #load the background window.blit(BACKGROUND, (30, 30)) #generate the labyrinth labyrinth = Map(FILE) labyrinth.generate() labyrinth.display(window) #Get the items in the labyrinthe syringe = Elements("syringe", SYRINGE, labyrinth) syringe.locate_elements() syringe.pin_elements() ether = Elements("ether", ETHER, labyrinth) ether.locate_elements() ether.pin_elements() tube = Elements("tube", TUBE, labyrinth) tube.locate_elements() tube.pin_elements() #And God create an Heroe MacGyver = Heroe(labyrinth) #########GAME_LOOP############## #Initialyse at every game_loop an empty list to put the elements inside TOOLS = [] while GAME_LOOP: pygame.time.Clock().tick(30) for event in pygame.event.get(): #Quit the program if event.type == QUIT: print("Bye bye!") MAIN_LOOP = False GAME_LOOP = False if event.type == KEYDOWN: #Quit the game and go back Home if event.key == K_ESCAPE: GAME_LOOP = False #Move our heroe! if event.key == K_RIGHT: MacGyver.move("right") if event.key == K_LEFT: MacGyver.move("left") if event.key == K_DOWN: MacGyver.move("bottom") if event.key == K_UP: MacGyver.move("up") #Display the game board window.blit(BACKGROUND, (0+30, 0+30)) labyrinth.display(window) #Add MacGyver in the Labyrinth with his position window.blit(MG, (MacGyver.x + 30, MacGyver.y + 30)) # + 30 for the offset of the black outline #Add conditionnal display of Element tube.display_elements(window, MacGyver, TOOLS) syringe.display_elements(window, MacGyver, TOOLS) ether.display_elements(window, MacGyver, TOOLS) pygame.display.flip() if labyrinth.grid[MacGyver.sprite_x][MacGyver.sprite_y] == "a": #The gamer wins if he has the tree elements if len(TOOLS) < 3: #####DISPLAY GAME OVER##### window.blit(GAMEOVER, (150+30, 150+30)) pygame.display.flip() time.sleep(2) ########################### print("You loose") GAME_LOOP = False if len(TOOLS) == 3: ######DISPLAY YOU WIN##### window.blit(WIN, (100+30, 150+30)) pygame.display.flip() time.sleep(2) ########################## print("You win!") GAME_LOOP = False
[ "aurelia.gourbere@gmail.com" ]
aurelia.gourbere@gmail.com
57e38fba70b247f8785ef9324ea9937447df7193
27dccff23ce75151f967c701e685dad21e790d0c
/Server/Eve/post.py
b146f5b9a867868e798f74df6a23c35323a90677
[ "MIT" ]
permissive
Hearen/OnceServer
cf0c863626176d0e2097525ed1722a30af55a5f0
8df8b811fd92afcdda1bef6b5a03657ada1fbe7d
refs/heads/master
2021-01-17T06:08:30.494134
2016-08-10T03:06:15
2016-08-10T03:06:15
47,436,350
0
2
null
2015-12-31T08:06:57
2015-12-05T00:53:58
Python
UTF-8
Python
false
false
12,002
py
# -*- coding: utf-8 -*- """ eve.methods.post ~~~~~~~~~~~~~~~~ This module imlements the POST method, supported by the resources endopints. :copyright: (c) 2015 by Nicola Iarocci. :license: BSD, see LICENSE for more details. """ from datetime import datetime from flask import current_app as app, abort from eve.utils import config, parse_request, debug_error_message from eve.auth import requires_auth from eve.defaults import resolve_default_values from eve.validation import ValidationError from eve.methods.common import parse, payload, ratelimit, \ pre_event, store_media_files, resolve_user_restricted_access, \ resolve_embedded_fields, build_response_document, marshal_write_response, \ resolve_sub_resource_path, resolve_document_etag, oplog_push from eve.versioning import resolve_document_version, \ insert_versioning_documents @ratelimit() @requires_auth('resource') @pre_event def post(resource, payl=None): """ Default function for handling POST requests, it has decorators for rate limiting, authentication and for raising pre-request events. After the decorators are applied forwards to call to :func:`post_internal` .. versionchanged:: 0.5 Split original post() into post/post_internal combo. """ return post_internal(resource, payl, skip_validation=False) def post_internal(resource, payl=None, skip_validation=False): """ Intended for internal post calls, this method is not rate limited, authentication is not checked and pre-request events are not raised. Adds one or more documents to a resource. Each document is validated against the domain schema. If validation passes the document is inserted and ID_FIELD, LAST_UPDATED and DATE_CREATED along with a link to the document are returned. If validation fails, a list of validation issues is returned. :param resource: name of the resource involved. :param payl: alternative payload. When calling post() from your own code you can provide an alternative payload. This can be useful, for example, when you have a callback function hooked to a certain endpoint, and want to perform additional post() calls from there. Please be advised that in order to successfully use this option, a request context must be available. See https://github.com/nicolaiarocci/eve/issues/74 for a discussion, and a typical use case. :param skip_validation: skip payload validation before write (bool) .. versionchanged:: 0.6 Fix: since v0.6, skip_validation = True causes a 422 response (#726). .. versionchanged:: 0.6 Initialize DELETED field when soft_delete is enabled. .. versionchanged:: 0.5 Back to resolving default values after validaton as now the validator can properly validate dependency even when some have default values. See #353. Push updates to the OpLog. Original post() has been split into post() and post_internal(). ETAGS are now stored with documents (#369). .. versionchanged:: 0.4 Resolve default values before validation is performed. See #353. Support for document versioning. .. versionchanged:: 0.3 Return 201 if at least one document has been successfully inserted. Fix #231 auth field not set if resource level authentication is set. Support for media fields. When IF_MATCH is disabled, no etag is included in the payload. Support for new validation format introduced with Cerberus v0.5. .. versionchanged:: 0.2 Use the new STATUS setting. Use the new ISSUES setting. Raise 'on_pre_<method>' event. Explictly resolve default values instead of letting them be resolved by common.parse. This avoids a validation error when a read-only field also has a default value. Added ``on_inserted*`` events after the database insert .. versionchanged:: 0.1.1 auth.request_auth_value is now used to store the auth_field value. .. versionchanged:: 0.1.0 More robust handling of auth_field. Support for optional HATEOAS. .. versionchanged: 0.0.9 Event hooks renamed to be more robuts and consistent: 'on_posting' renamed to 'on_insert'. You can now pass a pre-defined custom payload to the funcion. .. versionchanged:: 0.0.9 Storing self.app.auth.userid in auth_field when 'user-restricted resource access' is enabled. .. versionchanged: 0.0.7 Support for Rate-Limiting. Support for 'extra_response_fields'. 'on_posting' and 'on_posting_<resource>' events are raised before the documents are inserted into the database. This allows callback functions to arbitrarily edit/update the documents being stored. .. versionchanged:: 0.0.6 Support for bulk inserts. Please note: validation constraints are checked against the database, and not between the payload documents themselves. This causes an interesting corner case: in the event of a multiple documents payload where two or more documents carry the same value for a field where the 'unique' constraint is set, the payload will validate successfully, as there are no duplicates in the database (yet). If this is an issue, the client can always send the documents once at a time for insertion, or validate locally before submitting the payload to the API. .. versionchanged:: 0.0.5 Support for 'application/json' Content-Type . Support for 'user-restricted resource access'. .. versionchanged:: 0.0.4 Added the ``requires_auth`` decorator. .. versionchanged:: 0.0.3 JSON links. Superflous ``response`` container removed. """ date_utc = datetime.utcnow().replace(microsecond=0) resource_def = app.config['DOMAIN'][resource] schema = resource_def['schema'] validator = None if skip_validation else app.validator(schema, resource) documents = [] results = [] failures = 0 if config.BANDWIDTH_SAVER is True: embedded_fields = [] else: req = parse_request(resource) embedded_fields = resolve_embedded_fields(resource, req) # validation, and additional fields if payl is None: payl = payload() # print "\n\ninside eve post\n\n***************************************" # print embedded_fields # print "payl " # print payl ''' Added by : LHearen E-mail : LHearen@126.com Description: Used to construct our own RESTful interfaces - but the extra items should not be stored in DB; ''' if "_id" in payl: payl["_id"] = '27167fe7-fc9d-47d5-9cd0-717106ef67be' if "Module" in payl: del payl["Module"] if "Method" in payl: del payl["Method"] # print "payl " # print payl # print "resource " # print resource # print "\n\nend here" if isinstance(payl, dict): payl = [payl] if not payl: # empty bulkd insert abort(400, description=debug_error_message( 'Empty bulk insert' )) if len(payl) > 1 and not config.DOMAIN[resource]['bulk_enabled']: abort(400, description=debug_error_message( 'Bulk insert not allowed' )) for value in payl: document = [] doc_issues = {} try: document = parse(value, resource) resolve_sub_resource_path(document, resource) if skip_validation: validation = True else: validation = validator.validate(document) if validation: # validation is successful # validator might be not available if skip_validation. #726. if validator: # Apply coerced values document = validator.document # Populate meta and default fields document[config.LAST_UPDATED] = \ document[config.DATE_CREATED] = date_utc if config.DOMAIN[resource]['soft_delete'] is True: document[config.DELETED] = False resolve_user_restricted_access(document, resource) resolve_default_values(document, resource_def['defaults']) store_media_files(document, resource) resolve_document_version(document, resource, 'POST') else: # validation errors added to list of document issues doc_issues = validator.errors except ValidationError as e: doc_issues['validation exception'] = str(e) except Exception as e: # most likely a problem with the incoming payload, report back to # the client as if it was a validation issue app.logger.exception(e) doc_issues['exception'] = str(e) if len(doc_issues): document = { config.STATUS: config.STATUS_ERR, config.ISSUES: doc_issues, } failures += 1 documents.append(document) if failures: # If at least one document got issues, the whole request fails and a # ``422 Bad Request`` status is return. for document in documents: if config.STATUS in document \ and document[config.STATUS] == config.STATUS_ERR: results.append(document) else: results.append({config.STATUS: config.STATUS_OK}) return_code = config.VALIDATION_ERROR_STATUS else: # notify callbacks getattr(app, "on_insert")(resource, documents) getattr(app, "on_insert_%s" % resource)(documents) # compute etags here as documents might have been updated by callbacks. resolve_document_etag(documents, resource) # bulk insert ids = app.data.insert(resource, documents) # update oplog if needed oplog_push(resource, documents, 'POST') # assign document ids for document in documents: # either return the custom ID_FIELD or the id returned by # data.insert(). document[resource_def['id_field']] = \ document.get(resource_def['id_field'], ids.pop(0)) # build the full response document result = document build_response_document( result, resource, embedded_fields, document) # add extra write meta data result[config.STATUS] = config.STATUS_OK # limit what actually gets sent to minimize bandwidth usage result = marshal_write_response(result, resource) results.append(result) # insert versioning docs insert_versioning_documents(resource, documents) # notify callbacks getattr(app, "on_inserted")(resource, documents) getattr(app, "on_inserted_%s" % resource)(documents) # request was received and accepted; at least one document passed # validation and was accepted for insertion. return_code = 201 if len(results) == 1: response = results.pop(0) else: response = { config.STATUS: config.STATUS_ERR if failures else config.STATUS_OK, config.ITEMS: results, } if failures: response[config.ERROR] = { "code": return_code, "message": "Insertion failure: %d document(s) contain(s) error(s)" % failures, } print "now we're inside post.py, before customizing response" print response for key in response.keys(): if key != "_id": del response[key] print 'final response' print response return response, None, None, return_code
[ "lhearen@126.com" ]
lhearen@126.com
91f266dc667325bdcaaec433e89ba6d8563f80ea
1360a84fba508b22f50c163b12127c64405130b8
/tenis.py
9a9a3e4f91cab356687a5b9b80d96173581b1361
[]
no_license
ComunidadeDosCodigos/Desafios-Dojos
f2c9dd7c8b26452e333ad52fe850a699e7ad334f
c1cad549794261d79ba4ac62d15834eafc9dcc2e
refs/heads/master
2021-01-25T13:00:16.007633
2018-03-02T02:58:35
2018-03-02T02:58:35
123,522,191
1
1
null
null
null
null
UTF-8
Python
false
false
966
py
#Criado por: #Caio Carnelos #Kaio #Diego import os def clear(): os.system("cls") estagio = [0, 15, 30, 40, 'deuce', 'vantagem', 'vitoria'] P1 = 0 P2 = 0 while True: print("Player 1: {}".format(estagio[P1])) print("Player 2: {}".format(estagio[P2])) try: n = int(input('\n\t player: ')) except ValueError: print("O Valor precisa ser inteiro!") n = int(input('\n\t player: ')) clear() if n == 1: P1 += 1 elif n == 2: P2 += 1 if P1 == 3 and P2 == 3: P1 = 4 P2 = 4 #Aqui vai a regra da vantagem. if P1 == 5 and P2 == 5: P1 = 4 P2 = 4 if P1 >= 4 and P2 <= 2: print("\n\t Player 1 Venceu") break if P2 >= 4 and P1 <= 2: print("\n\t Player 2 Venceu") break if P1 == 6: print("\n\t Player 1 Venceu") break if P2 == 6: print("\n\t Player 2 Venceu") break
[ "noreply@github.com" ]
noreply@github.com
e72a8f840fe19cba7a78f1c106c11412b4ce1858
8df7ef807ddeeb0213243214ac4a56409b22f6c8
/lista2/salario.py
249088f46c090794aad05f6c40c502bcb5ba77ee
[]
no_license
centralnett/ALGO_REDES__2016_1_LISTA2
ef53e6e40b7567725d28e2893851d36484a92db1
aeb8553d56fd5bd485f6b51ec3871ac18a175f83
refs/heads/master
2021-01-10T13:25:42.514112
2016-02-29T19:08:09
2016-02-29T19:08:09
52,815,848
0
0
null
null
null
null
UTF-8
Python
false
false
301
py
Funcionario = input() Salario = float(input ()) NS = float(Salario) + float(Salario*0.25) print ("Prezado %s, a partir hoje você receverá R$%.2f" % (Funcionario, NS)) #Aparentemente, o mix de tipos de entradas de dados é uma das possibilidades para funcionar, porem nao acho que seja o correto.
[ "luadossantospereira@gmail.com" ]
luadossantospereira@gmail.com
ecd01d10a1558751757d179781b4e920b374d1a7
acf712c69818bcfee7a7c51631283671e6f9ad07
/blog/migrations/0001_initial.py
819f594b4c57e5e3707370d407b9dcbe66e75022
[]
no_license
hellofjoy/my_first_blog
7025187b9c33aa5d1577aac355de3ead25918661
390252e9fa5854b6ea1290054f4c4ace758a583f
refs/heads/master
2021-05-01T04:09:18.567532
2018-02-13T06:39:07
2018-02-13T06:39:07
121,200,165
0
0
null
null
null
null
UTF-8
Python
false
false
986
py
# Generated by Django 2.0.1 on 2018-02-09 11:09 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Post', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=200)), ('text', models.TextField()), ('created_date', models.DateTimeField(default=django.utils.timezone.now)), ('published_date', models.DateTimeField(blank=True, null=True)), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ]
[ "yhoh@anapass.com" ]
yhoh@anapass.com
ee426a16bbba6e8d3758021939034929ac68c187
a6f019dcba354e531eebb7ebef2688980f103577
/assignment/assignment/urls.py
e6a37bf88c6209bc8e0127583615d32c6f96ab6a
[]
no_license
Sanayshah2/salesforce_integration_assignment
09dd270513d18363633e955d7fe0bcc6b0ad4088
52f870f7700e6a363bbcb7265c7077f9139379aa
refs/heads/master
2023-08-15T18:14:28.736042
2021-09-15T22:48:41
2021-09-15T22:48:41
406,944,706
0
0
null
null
null
null
UTF-8
Python
false
false
802
py
"""assignment URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('salesforce.urls')) ]
[ "sanayshah2@gmail.com" ]
sanayshah2@gmail.com
45a5e9c32a2a75392ea4d754b08929dd43bb3c1f
fb9922c7f3f86d13d8e630c5bc84fd77d79b2df1
/geotransform.py
dfd842ecf7972dfcd415ce7f1964fb86299f4d50
[]
no_license
coin-org/geotransform
9696d18978d6c3e7064724b7e0f3154602440544
7743b32a1ffa7ac4a119898478b9192357740972
refs/heads/master
2022-11-03T04:33:32.626293
2020-06-17T14:51:30
2020-06-17T15:04:58
273,001,304
0
1
null
null
null
null
UTF-8
Python
false
false
2,243
py
from pyproj import Transformer from multiprocessing import Pool import psycopg2 def update(si_nm): transformer = Transformer.from_crs('epsg:5179', 'epsg:4326', always_xy=True) # UTM-K(Bassel) 도로명주소 지도 사용 중 connection = psycopg2.connect(dbname='juso', user='postgres', password='password', host='happyjoy1234.asuscomm.com') connection2 = psycopg2.connect(dbname='juso', user='postgres', password='password', host='happyjoy1234.asuscomm.com') count = 0 with connection2.cursor() as cursor2: with connection.cursor() as cursor: cursor.execute( "DECLARE super_cursor BINARY CURSOR FOR select * from address where si_nm = '" + si_nm + "'") while True: cursor.execute("FETCH 1000 FROM super_cursor") rows = cursor.fetchall() if not rows: break for row in rows: if row[16] != '' and row[17] != '': long, lat = transformer.transform(row[16], row[17]) cursor2.execute("UPDATE address " "SET longitude = %s, latitude = %s " "WHERE dong_cd = %s and rn_mg_sn = %s and udrt_yn = %s and buld_mnnm = %s and buld_slno = %s" , (round(long, 6), round(lat, 6), row[2], row[6], row[8], row[9], row[10])) count += 1 print(si_nm + "-" + str(count)) connection2.commit() return count if __name__ == '__main__': with Pool(17) as p: print(p.map(update, [ "대전광역시" , "인천광역시" , "울산광역시" , "광주광역시" , "강원도" , "부산광역시" , "대구광역시" , "서울특별시" , "전라남도" , "경기도" , "경상북도" , "제주특별자치도" , "전라북도" , "충청남도" , "경상남도" , "세종특별자치시" , "충청북도" ]))
[ "leehyunguu@gmail.com" ]
leehyunguu@gmail.com
6b2cfe16eeae107dde4f90e1146826db9c70bba8
ae6dd63751e6d3b07e274c25acf0f36de9284824
/elevator/asgi.py
f392ad8ffb2b3cb88a65c408a00efbc778bd89bd
[]
no_license
AleksejKorobac1/elevator
e64e3e0dd837f4aa810de5951b8f8316e742dd40
bb1b14eabaaca2db2dde5844d56a36d266c72439
refs/heads/main
2023-01-22T02:58:29.331215
2020-12-03T12:03:08
2020-12-03T12:03:08
318,159,001
0
0
null
null
null
null
UTF-8
Python
false
false
409
py
""" ASGI config for elevator project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'elevator.settings') application = get_asgi_application()
[ "noreply@github.com" ]
noreply@github.com
724698132f626f1a3a989c97a64e08f6e58ca378
e380df2813156a643f8f00754da2f24be4f1d015
/hw1/10.12-1.py
5ff52cdb188fe93fbe31427c9e8d01469fe8e460
[]
no_license
IrynaKucherenko/hw_repository
7da94a70bc41f8445ccd9e2dc673e4362816e2ff
3ef4f4cb33c5e9704382dd345afdbac72c48ec02
refs/heads/main
2023-02-22T13:44:37.551956
2021-01-30T19:48:31
2021-01-30T19:48:31
325,782,179
0
0
null
null
null
null
UTF-8
Python
false
false
90
py
#1# a=int(input("a= ")) b=int(input("b= ")) c=int(input("c= ")) print(a,b,c) print(c,b,a)
[ "irruna_kiev@ukr.net" ]
irruna_kiev@ukr.net
81bd2b2a328a6e4dd44b19fdd29ef301958ada2c
48e124e97cc776feb0ad6d17b9ef1dfa24e2e474
/sdk/python/pulumi_azure_native/timeseriesinsights/v20210630preview/reference_data_set.py
5b350da438874cbf3ea8e7b7b52d7935a1a141be
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
bpkgoud/pulumi-azure-native
0817502630062efbc35134410c4a784b61a4736d
a3215fe1b87fba69294f248017b1591767c2b96c
refs/heads/master
2023-08-29T22:39:49.984212
2021-11-15T12:43:41
2021-11-15T12:43:41
null
0
0
null
null
null
null
UTF-8
Python
false
false
16,422
py
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities from . import outputs from ._enums import * from ._inputs import * __all__ = ['ReferenceDataSetArgs', 'ReferenceDataSet'] @pulumi.input_type class ReferenceDataSetArgs: def __init__(__self__, *, environment_name: pulumi.Input[str], key_properties: pulumi.Input[Sequence[pulumi.Input['ReferenceDataSetKeyPropertyArgs']]], resource_group_name: pulumi.Input[str], data_string_comparison_behavior: Optional[pulumi.Input[Union[str, 'DataStringComparisonBehavior']]] = None, location: Optional[pulumi.Input[str]] = None, reference_data_set_name: Optional[pulumi.Input[str]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None): """ The set of arguments for constructing a ReferenceDataSet resource. :param pulumi.Input[str] environment_name: The name of the Time Series Insights environment associated with the specified resource group. :param pulumi.Input[Sequence[pulumi.Input['ReferenceDataSetKeyPropertyArgs']]] key_properties: The list of key properties for the reference data set. :param pulumi.Input[str] resource_group_name: Name of an Azure Resource group. :param pulumi.Input[Union[str, 'DataStringComparisonBehavior']] data_string_comparison_behavior: The reference data set key comparison behavior can be set using this property. By default, the value is 'Ordinal' - which means case sensitive key comparison will be performed while joining reference data with events or while adding new reference data. When 'OrdinalIgnoreCase' is set, case insensitive comparison will be used. :param pulumi.Input[str] location: The location of the resource. :param pulumi.Input[str] reference_data_set_name: Name of the reference data set. :param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: Key-value pairs of additional properties for the resource. """ pulumi.set(__self__, "environment_name", environment_name) pulumi.set(__self__, "key_properties", key_properties) pulumi.set(__self__, "resource_group_name", resource_group_name) if data_string_comparison_behavior is not None: pulumi.set(__self__, "data_string_comparison_behavior", data_string_comparison_behavior) if location is not None: pulumi.set(__self__, "location", location) if reference_data_set_name is not None: pulumi.set(__self__, "reference_data_set_name", reference_data_set_name) if tags is not None: pulumi.set(__self__, "tags", tags) @property @pulumi.getter(name="environmentName") def environment_name(self) -> pulumi.Input[str]: """ The name of the Time Series Insights environment associated with the specified resource group. """ return pulumi.get(self, "environment_name") @environment_name.setter def environment_name(self, value: pulumi.Input[str]): pulumi.set(self, "environment_name", value) @property @pulumi.getter(name="keyProperties") def key_properties(self) -> pulumi.Input[Sequence[pulumi.Input['ReferenceDataSetKeyPropertyArgs']]]: """ The list of key properties for the reference data set. """ return pulumi.get(self, "key_properties") @key_properties.setter def key_properties(self, value: pulumi.Input[Sequence[pulumi.Input['ReferenceDataSetKeyPropertyArgs']]]): pulumi.set(self, "key_properties", value) @property @pulumi.getter(name="resourceGroupName") def resource_group_name(self) -> pulumi.Input[str]: """ Name of an Azure Resource group. """ return pulumi.get(self, "resource_group_name") @resource_group_name.setter def resource_group_name(self, value: pulumi.Input[str]): pulumi.set(self, "resource_group_name", value) @property @pulumi.getter(name="dataStringComparisonBehavior") def data_string_comparison_behavior(self) -> Optional[pulumi.Input[Union[str, 'DataStringComparisonBehavior']]]: """ The reference data set key comparison behavior can be set using this property. By default, the value is 'Ordinal' - which means case sensitive key comparison will be performed while joining reference data with events or while adding new reference data. When 'OrdinalIgnoreCase' is set, case insensitive comparison will be used. """ return pulumi.get(self, "data_string_comparison_behavior") @data_string_comparison_behavior.setter def data_string_comparison_behavior(self, value: Optional[pulumi.Input[Union[str, 'DataStringComparisonBehavior']]]): pulumi.set(self, "data_string_comparison_behavior", value) @property @pulumi.getter def location(self) -> Optional[pulumi.Input[str]]: """ The location of the resource. """ return pulumi.get(self, "location") @location.setter def location(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "location", value) @property @pulumi.getter(name="referenceDataSetName") def reference_data_set_name(self) -> Optional[pulumi.Input[str]]: """ Name of the reference data set. """ return pulumi.get(self, "reference_data_set_name") @reference_data_set_name.setter def reference_data_set_name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "reference_data_set_name", value) @property @pulumi.getter def tags(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]: """ Key-value pairs of additional properties for the resource. """ return pulumi.get(self, "tags") @tags.setter def tags(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]): pulumi.set(self, "tags", value) class ReferenceDataSet(pulumi.CustomResource): @overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, data_string_comparison_behavior: Optional[pulumi.Input[Union[str, 'DataStringComparisonBehavior']]] = None, environment_name: Optional[pulumi.Input[str]] = None, key_properties: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ReferenceDataSetKeyPropertyArgs']]]]] = None, location: Optional[pulumi.Input[str]] = None, reference_data_set_name: Optional[pulumi.Input[str]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, __props__=None): """ A reference data set provides metadata about the events in an environment. Metadata in the reference data set will be joined with events as they are read from event sources. The metadata that makes up the reference data set is uploaded or modified through the Time Series Insights data plane APIs. :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[Union[str, 'DataStringComparisonBehavior']] data_string_comparison_behavior: The reference data set key comparison behavior can be set using this property. By default, the value is 'Ordinal' - which means case sensitive key comparison will be performed while joining reference data with events or while adding new reference data. When 'OrdinalIgnoreCase' is set, case insensitive comparison will be used. :param pulumi.Input[str] environment_name: The name of the Time Series Insights environment associated with the specified resource group. :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ReferenceDataSetKeyPropertyArgs']]]] key_properties: The list of key properties for the reference data set. :param pulumi.Input[str] location: The location of the resource. :param pulumi.Input[str] reference_data_set_name: Name of the reference data set. :param pulumi.Input[str] resource_group_name: Name of an Azure Resource group. :param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: Key-value pairs of additional properties for the resource. """ ... @overload def __init__(__self__, resource_name: str, args: ReferenceDataSetArgs, opts: Optional[pulumi.ResourceOptions] = None): """ A reference data set provides metadata about the events in an environment. Metadata in the reference data set will be joined with events as they are read from event sources. The metadata that makes up the reference data set is uploaded or modified through the Time Series Insights data plane APIs. :param str resource_name: The name of the resource. :param ReferenceDataSetArgs args: The arguments to use to populate this resource's properties. :param pulumi.ResourceOptions opts: Options for the resource. """ ... def __init__(__self__, resource_name: str, *args, **kwargs): resource_args, opts = _utilities.get_resource_args_opts(ReferenceDataSetArgs, pulumi.ResourceOptions, *args, **kwargs) if resource_args is not None: __self__._internal_init(resource_name, opts, **resource_args.__dict__) else: __self__._internal_init(resource_name, *args, **kwargs) def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, data_string_comparison_behavior: Optional[pulumi.Input[Union[str, 'DataStringComparisonBehavior']]] = None, environment_name: Optional[pulumi.Input[str]] = None, key_properties: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ReferenceDataSetKeyPropertyArgs']]]]] = None, location: Optional[pulumi.Input[str]] = None, reference_data_set_name: Optional[pulumi.Input[str]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, __props__=None): if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version() if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = ReferenceDataSetArgs.__new__(ReferenceDataSetArgs) __props__.__dict__["data_string_comparison_behavior"] = data_string_comparison_behavior if environment_name is None and not opts.urn: raise TypeError("Missing required property 'environment_name'") __props__.__dict__["environment_name"] = environment_name if key_properties is None and not opts.urn: raise TypeError("Missing required property 'key_properties'") __props__.__dict__["key_properties"] = key_properties __props__.__dict__["location"] = location __props__.__dict__["reference_data_set_name"] = reference_data_set_name if resource_group_name is None and not opts.urn: raise TypeError("Missing required property 'resource_group_name'") __props__.__dict__["resource_group_name"] = resource_group_name __props__.__dict__["tags"] = tags __props__.__dict__["creation_time"] = None __props__.__dict__["name"] = None __props__.__dict__["provisioning_state"] = None __props__.__dict__["type"] = None alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-native:timeseriesinsights:ReferenceDataSet"), pulumi.Alias(type_="azure-native:timeseriesinsights/v20170228preview:ReferenceDataSet"), pulumi.Alias(type_="azure-native:timeseriesinsights/v20171115:ReferenceDataSet"), pulumi.Alias(type_="azure-native:timeseriesinsights/v20180815preview:ReferenceDataSet"), pulumi.Alias(type_="azure-native:timeseriesinsights/v20200515:ReferenceDataSet"), pulumi.Alias(type_="azure-native:timeseriesinsights/v20210331preview:ReferenceDataSet")]) opts = pulumi.ResourceOptions.merge(opts, alias_opts) super(ReferenceDataSet, __self__).__init__( 'azure-native:timeseriesinsights/v20210630preview:ReferenceDataSet', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None) -> 'ReferenceDataSet': """ Get an existing ReferenceDataSet resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options for the resource. """ opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = ReferenceDataSetArgs.__new__(ReferenceDataSetArgs) __props__.__dict__["creation_time"] = None __props__.__dict__["data_string_comparison_behavior"] = None __props__.__dict__["key_properties"] = None __props__.__dict__["location"] = None __props__.__dict__["name"] = None __props__.__dict__["provisioning_state"] = None __props__.__dict__["tags"] = None __props__.__dict__["type"] = None return ReferenceDataSet(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name="creationTime") def creation_time(self) -> pulumi.Output[str]: """ The time the resource was created. """ return pulumi.get(self, "creation_time") @property @pulumi.getter(name="dataStringComparisonBehavior") def data_string_comparison_behavior(self) -> pulumi.Output[Optional[str]]: """ The reference data set key comparison behavior can be set using this property. By default, the value is 'Ordinal' - which means case sensitive key comparison will be performed while joining reference data with events or while adding new reference data. When 'OrdinalIgnoreCase' is set, case insensitive comparison will be used. """ return pulumi.get(self, "data_string_comparison_behavior") @property @pulumi.getter(name="keyProperties") def key_properties(self) -> pulumi.Output[Sequence['outputs.ReferenceDataSetKeyPropertyResponse']]: """ The list of key properties for the reference data set. """ return pulumi.get(self, "key_properties") @property @pulumi.getter def location(self) -> pulumi.Output[str]: """ Resource location """ return pulumi.get(self, "location") @property @pulumi.getter def name(self) -> pulumi.Output[str]: """ Resource name """ return pulumi.get(self, "name") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> pulumi.Output[str]: """ Provisioning state of the resource. """ return pulumi.get(self, "provisioning_state") @property @pulumi.getter def tags(self) -> pulumi.Output[Optional[Mapping[str, str]]]: """ Resource tags """ return pulumi.get(self, "tags") @property @pulumi.getter def type(self) -> pulumi.Output[str]: """ Resource type """ return pulumi.get(self, "type")
[ "noreply@github.com" ]
noreply@github.com
314be4571818499b9133b733908fa91faf720aad
896b79a235796da67cdabd52e88d8b218882c3fe
/src/aioquic/quic/recovery.py
dae3712bc63d32f253ebceca8c49e3dc11109ba0
[ "BSD-3-Clause" ]
permissive
LautaroJayat/aioquic
b9b84b59c849a3dc4cfc3a986b679dd0723ddbf7
b1ecd8a1dd9089fa536b7d62ab06d7127d768e8d
refs/heads/main
2022-10-27T01:30:04.846852
2020-06-16T01:04:25
2020-06-16T01:04:25
272,577,005
0
0
BSD-3-Clause
2020-06-16T01:04:27
2020-06-16T01:01:58
null
UTF-8
Python
false
false
17,096
py
import math from typing import Callable, Dict, Iterable, List, Optional from .logger import QuicLoggerTrace from .packet_builder import QuicDeliveryState, QuicSentPacket from .rangeset import RangeSet # loss detection K_PACKET_THRESHOLD = 3 K_GRANULARITY = 0.001 # seconds K_TIME_THRESHOLD = 9 / 8 K_MICRO_SECOND = 0.000001 K_SECOND = 1.0 # congestion control K_MAX_DATAGRAM_SIZE = 1280 K_INITIAL_WINDOW = 10 * K_MAX_DATAGRAM_SIZE K_MINIMUM_WINDOW = 2 * K_MAX_DATAGRAM_SIZE K_LOSS_REDUCTION_FACTOR = 0.5 class QuicPacketSpace: def __init__(self) -> None: self.ack_at: Optional[float] = None self.ack_queue = RangeSet() self.discarded = False self.expected_packet_number = 0 self.largest_received_packet = -1 self.largest_received_time: Optional[float] = None # sent packets and loss self.ack_eliciting_in_flight = 0 self.largest_acked_packet = 0 self.loss_time: Optional[float] = None self.sent_packets: Dict[int, QuicSentPacket] = {} class QuicPacketPacer: def __init__(self) -> None: self.bucket_max: float = 0.0 self.bucket_time: float = 0.0 self.evaluation_time: float = 0.0 self.packet_time: Optional[float] = None def next_send_time(self, now: float) -> float: if self.packet_time is not None: self.update_bucket(now=now) if self.bucket_time <= 0: return now + self.packet_time return None def update_after_send(self, now: float) -> None: if self.packet_time is not None: self.update_bucket(now=now) if self.bucket_time < self.packet_time: self.bucket_time = 0.0 else: self.bucket_time -= self.packet_time def update_bucket(self, now: float) -> None: if now > self.evaluation_time: self.bucket_time = min( self.bucket_time + (now - self.evaluation_time), self.bucket_max ) self.evaluation_time = now def update_rate(self, congestion_window: int, smoothed_rtt: float) -> None: pacing_rate = congestion_window / max(smoothed_rtt, K_MICRO_SECOND) self.packet_time = max( K_MICRO_SECOND, min(K_MAX_DATAGRAM_SIZE / pacing_rate, K_SECOND) ) self.bucket_max = ( max( 2 * K_MAX_DATAGRAM_SIZE, min(congestion_window // 4, 16 * K_MAX_DATAGRAM_SIZE), ) / pacing_rate ) if self.bucket_time > self.bucket_max: self.bucket_time = self.bucket_max class QuicCongestionControl: """ New Reno congestion control. """ def __init__(self) -> None: self.bytes_in_flight = 0 self.congestion_window = K_INITIAL_WINDOW self._congestion_recovery_start_time = 0.0 self._congestion_stash = 0 self._rtt_monitor = QuicRttMonitor() self.ssthresh: Optional[int] = None def on_packet_acked(self, packet: QuicSentPacket) -> None: self.bytes_in_flight -= packet.sent_bytes # don't increase window in congestion recovery if packet.sent_time <= self._congestion_recovery_start_time: return if self.ssthresh is None or self.congestion_window < self.ssthresh: # slow start self.congestion_window += packet.sent_bytes else: # congestion avoidance self._congestion_stash += packet.sent_bytes count = self._congestion_stash // self.congestion_window if count: self._congestion_stash -= count * self.congestion_window self.congestion_window += count * K_MAX_DATAGRAM_SIZE def on_packet_sent(self, packet: QuicSentPacket) -> None: self.bytes_in_flight += packet.sent_bytes def on_packets_expired(self, packets: Iterable[QuicSentPacket]) -> None: for packet in packets: self.bytes_in_flight -= packet.sent_bytes def on_packets_lost(self, packets: Iterable[QuicSentPacket], now: float) -> None: lost_largest_time = 0.0 for packet in packets: self.bytes_in_flight -= packet.sent_bytes lost_largest_time = packet.sent_time # start a new congestion event if packet was sent after the # start of the previous congestion recovery period. if lost_largest_time > self._congestion_recovery_start_time: self._congestion_recovery_start_time = now self.congestion_window = max( int(self.congestion_window * K_LOSS_REDUCTION_FACTOR), K_MINIMUM_WINDOW ) self.ssthresh = self.congestion_window # TODO : collapse congestion window if persistent congestion def on_rtt_measurement(self, latest_rtt: float, now: float) -> None: # check whether we should exit slow start if self.ssthresh is None and self._rtt_monitor.is_rtt_increasing( latest_rtt, now ): self.ssthresh = self.congestion_window class QuicPacketRecovery: """ Packet loss and congestion controller. """ def __init__( self, initial_rtt: float, peer_completed_address_validation: bool, send_probe: Callable[[], None], quic_logger: Optional[QuicLoggerTrace] = None, ) -> None: self.max_ack_delay = 0.025 self.peer_completed_address_validation = peer_completed_address_validation self.spaces: List[QuicPacketSpace] = [] # callbacks self._quic_logger = quic_logger self._send_probe = send_probe # loss detection self._pto_count = 0 self._rtt_initial = initial_rtt self._rtt_initialized = False self._rtt_latest = 0.0 self._rtt_min = math.inf self._rtt_smoothed = 0.0 self._rtt_variance = 0.0 self._time_of_last_sent_ack_eliciting_packet = 0.0 # congestion control self._cc = QuicCongestionControl() self._pacer = QuicPacketPacer() @property def bytes_in_flight(self) -> int: return self._cc.bytes_in_flight @property def congestion_window(self) -> int: return self._cc.congestion_window def discard_space(self, space: QuicPacketSpace) -> None: assert space in self.spaces self._cc.on_packets_expired( filter(lambda x: x.in_flight, space.sent_packets.values()) ) space.sent_packets.clear() space.ack_at = None space.ack_eliciting_in_flight = 0 space.loss_time = None if self._quic_logger is not None: self._log_metrics_updated() def get_loss_detection_time(self) -> float: # loss timer loss_space = self._get_loss_space() if loss_space is not None: return loss_space.loss_time # packet timer if ( not self.peer_completed_address_validation or sum(space.ack_eliciting_in_flight for space in self.spaces) > 0 ): timeout = self.get_probe_timeout() * (2 ** self._pto_count) return self._time_of_last_sent_ack_eliciting_packet + timeout return None def get_probe_timeout(self) -> float: if not self._rtt_initialized: return 2 * self._rtt_initial return ( self._rtt_smoothed + max(4 * self._rtt_variance, K_GRANULARITY) + self.max_ack_delay ) def on_ack_received( self, space: QuicPacketSpace, ack_rangeset: RangeSet, ack_delay: float, now: float, ) -> None: """ Update metrics as the result of an ACK being received. """ is_ack_eliciting = False largest_acked = ack_rangeset.bounds().stop - 1 largest_newly_acked = None largest_sent_time = None if largest_acked > space.largest_acked_packet: space.largest_acked_packet = largest_acked for packet_number in sorted(space.sent_packets.keys()): if packet_number > largest_acked: break if packet_number in ack_rangeset: # remove packet and update counters packet = space.sent_packets.pop(packet_number) if packet.is_ack_eliciting: is_ack_eliciting = True space.ack_eliciting_in_flight -= 1 if packet.in_flight: self._cc.on_packet_acked(packet) largest_newly_acked = packet_number largest_sent_time = packet.sent_time # trigger callbacks for handler, args in packet.delivery_handlers: handler(QuicDeliveryState.ACKED, *args) # nothing to do if there are no newly acked packets if largest_newly_acked is None: return if largest_acked == largest_newly_acked and is_ack_eliciting: latest_rtt = now - largest_sent_time log_rtt = True # limit ACK delay to max_ack_delay ack_delay = min(ack_delay, self.max_ack_delay) # update RTT estimate, which cannot be < 1 ms self._rtt_latest = max(latest_rtt, 0.001) if self._rtt_latest < self._rtt_min: self._rtt_min = self._rtt_latest if self._rtt_latest > self._rtt_min + ack_delay: self._rtt_latest -= ack_delay if not self._rtt_initialized: self._rtt_initialized = True self._rtt_variance = latest_rtt / 2 self._rtt_smoothed = latest_rtt else: self._rtt_variance = 3 / 4 * self._rtt_variance + 1 / 4 * abs( self._rtt_min - self._rtt_latest ) self._rtt_smoothed = ( 7 / 8 * self._rtt_smoothed + 1 / 8 * self._rtt_latest ) # inform congestion controller self._cc.on_rtt_measurement(latest_rtt, now=now) self._pacer.update_rate( congestion_window=self._cc.congestion_window, smoothed_rtt=self._rtt_smoothed, ) else: log_rtt = False self._detect_loss(space, now=now) if self._quic_logger is not None: self._log_metrics_updated(log_rtt=log_rtt) self._pto_count = 0 def on_loss_detection_timeout(self, now: float) -> None: loss_space = self._get_loss_space() if loss_space is not None: self._detect_loss(loss_space, now=now) else: self._pto_count += 1 # reschedule some data for space in self.spaces: self._on_packets_lost( tuple( filter( lambda i: i.is_crypto_packet, space.sent_packets.values() ) ), space=space, now=now, ) self._send_probe() def on_packet_sent(self, packet: QuicSentPacket, space: QuicPacketSpace) -> None: space.sent_packets[packet.packet_number] = packet if packet.is_ack_eliciting: space.ack_eliciting_in_flight += 1 if packet.in_flight: if packet.is_ack_eliciting: self._time_of_last_sent_ack_eliciting_packet = packet.sent_time # add packet to bytes in flight self._cc.on_packet_sent(packet) if self._quic_logger is not None: self._log_metrics_updated() def _detect_loss(self, space: QuicPacketSpace, now: float) -> None: """ Check whether any packets should be declared lost. """ loss_delay = K_TIME_THRESHOLD * ( max(self._rtt_latest, self._rtt_smoothed) if self._rtt_initialized else self._rtt_initial ) packet_threshold = space.largest_acked_packet - K_PACKET_THRESHOLD time_threshold = now - loss_delay lost_packets = [] space.loss_time = None for packet_number, packet in space.sent_packets.items(): if packet_number > space.largest_acked_packet: break if packet_number <= packet_threshold or packet.sent_time <= time_threshold: lost_packets.append(packet) else: packet_loss_time = packet.sent_time + loss_delay if space.loss_time is None or space.loss_time > packet_loss_time: space.loss_time = packet_loss_time self._on_packets_lost(lost_packets, space=space, now=now) def _get_loss_space(self) -> Optional[QuicPacketSpace]: loss_space = None for space in self.spaces: if space.loss_time is not None and ( loss_space is None or space.loss_time < loss_space.loss_time ): loss_space = space return loss_space def _log_metrics_updated(self, log_rtt=False) -> None: data = { "bytes_in_flight": self._cc.bytes_in_flight, "cwnd": self._cc.congestion_window, } if self._cc.ssthresh is not None: data["ssthresh"] = self._cc.ssthresh if log_rtt: data.update( { "latest_rtt": self._quic_logger.encode_time(self._rtt_latest), "min_rtt": self._quic_logger.encode_time(self._rtt_min), "smoothed_rtt": self._quic_logger.encode_time(self._rtt_smoothed), "rtt_variance": self._quic_logger.encode_time(self._rtt_variance), } ) self._quic_logger.log_event( category="recovery", event="metrics_updated", data=data ) def _on_packets_lost( self, packets: Iterable[QuicSentPacket], space: QuicPacketSpace, now: float ) -> None: lost_packets_cc = [] for packet in packets: del space.sent_packets[packet.packet_number] if packet.in_flight: lost_packets_cc.append(packet) if packet.is_ack_eliciting: space.ack_eliciting_in_flight -= 1 if self._quic_logger is not None: self._quic_logger.log_event( category="recovery", event="packet_lost", data={ "type": self._quic_logger.packet_type(packet.packet_type), "packet_number": str(packet.packet_number), }, ) self._log_metrics_updated() # trigger callbacks for handler, args in packet.delivery_handlers: handler(QuicDeliveryState.LOST, *args) # inform congestion controller if lost_packets_cc: self._cc.on_packets_lost(lost_packets_cc, now=now) self._pacer.update_rate( congestion_window=self._cc.congestion_window, smoothed_rtt=self._rtt_smoothed, ) if self._quic_logger is not None: self._log_metrics_updated() class QuicRttMonitor: """ Roundtrip time monitor for HyStart. """ def __init__(self) -> None: self._increases = 0 self._last_time = None self._ready = False self._size = 5 self._filtered_min: Optional[float] = None self._sample_idx = 0 self._sample_max: Optional[float] = None self._sample_min: Optional[float] = None self._sample_time = 0.0 self._samples = [0.0 for i in range(self._size)] def add_rtt(self, rtt: float) -> None: self._samples[self._sample_idx] = rtt self._sample_idx += 1 if self._sample_idx >= self._size: self._sample_idx = 0 self._ready = True if self._ready: self._sample_max = self._samples[0] self._sample_min = self._samples[0] for sample in self._samples[1:]: if sample < self._sample_min: self._sample_min = sample elif sample > self._sample_max: self._sample_max = sample def is_rtt_increasing(self, rtt: float, now: float) -> bool: if now > self._sample_time + K_GRANULARITY: self.add_rtt(rtt) self._sample_time = now if self._ready: if self._filtered_min is None or self._filtered_min > self._sample_max: self._filtered_min = self._sample_max delta = self._sample_min - self._filtered_min if delta * 4 >= self._filtered_min: self._increases += 1 if self._increases >= self._size: return True elif delta > 0: self._increases = 0 return False
[ "jeremy.laine@m4x.org" ]
jeremy.laine@m4x.org
01893f13d23f63efc4f427a9eb781cbc09388785
dee345b10c7dc29dd6b0cac04677beef14f2d64f
/tests/test_manual_quality_merging.py
35dc41c621fefe22e33d69b77f397f562e697051
[ "MIT" ]
permissive
richard-shepherd/calculation_graph
fcd0df6b0d4fc598586ee67c129ccc90b9cac383
647b1f13544e3525068c8b3b83a7eed3f7e473bd
refs/heads/master
2016-09-05T19:46:14.567122
2015-05-21T10:58:14
2015-05-21T10:58:14
31,436,445
0
1
null
null
null
null
UTF-8
Python
false
false
5,491
py
from graph import * class SourceNode(GraphNode): """ A data source. Just a value with data-quality. """ def __init__(self, source_name, *args, **kwargs): super().__init__(*args, **kwargs) self.source_name = source_name # The value provided by this source... self.value = 0.0 # True if the source is working correctly... self.source_is_good = False def set_value(self, value, source_is_good): """ Sets the value of this source and whether the source is good. This causes the node to need recalculation. """ self.value = value self.source_is_good = source_is_good self.needs_calculation() def calculate(self): """ We set the data-quality from the source_is_good information. """ self.quality.clear_to_good() if self.source_is_good is False: self.quality.merge(Quality.BAD, "Source " + self.source_name + " is bad") return GraphNode.CalculateChildrenType.CALCULATE_CHILDREN class SourceChooserNode(GraphNode): """ Chooses between two of the SourceNodes above, depending on their data-quality. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Parent nodes... self.source_A_node = None self.source_B_node = None # The value for this node will be chosen from one of the # parent sources... self.value = 0.0 def set_dependencies(self): """ We hook up to two sources. """ self.source_A_node = self.add_parent_node(SourceNode, "A") self.source_B_node = self.add_parent_node(SourceNode, "B") def calculate_quality(self): """ We override automatic quality merging. In this case, we will set this node's data-quality in the calculate() function. """ pass def calculate(self): """ We choose the value from whichever parent node has Good data-quality. """ if self.source_A_node.quality.is_good(): # Source A has good data... self.value = self.source_A_node.value self.quality.set_from(self.source_A_node.quality) elif self.source_B_node.quality.is_good(): # Source B has good data... self.value = self.source_B_node.value self.quality.set_from(self.source_B_node.quality) else: # Neither source has good data... self.value = 0.0 self.quality.set_to_bad("No source has Good data") return GraphNode.CalculateChildrenType.CALCULATE_CHILDREN def test_manual_quality_merging(): """ Tests manual merging of quality from parent nodes. The graph for this test has a "redundant" data source. The test node has two parents A and B. It chooses which ever one of them has good quality. So in this case, we do not want to automatically merge quality, as otherwise if one of the parents goes Bad, the "choosing" node would go bad as well. In this case, as long as one of the parents is Good, then the choosing node will be Good as well. """ graph_manager = GraphManager() # We create the sources before the chooser, so we can set their values... source_A_node = NodeFactory.get_node(graph_manager, GraphNode.GCType.NON_COLLECTABLE, SourceNode, "A") source_B_node = NodeFactory.get_node(graph_manager, GraphNode.GCType.NON_COLLECTABLE, SourceNode, "B") # We create a node to choose between the two sources above... chooser_node = NodeFactory.get_node(graph_manager, GraphNode.GCType.NON_COLLECTABLE, SourceChooserNode) # We set both sources to have Good data-quality. The value from source A # is chosen when both are good... source_A_node.set_value(123.0, source_is_good=True) source_B_node.set_value(456.0, source_is_good=True) graph_manager.calculate() assert chooser_node.value == 123.0 assert chooser_node.quality.is_good() assert chooser_node.quality.get_description() == "" # We set source B bad. The value from A should still be used... source_B_node.set_value(457.0, source_is_good=False) graph_manager.calculate() assert chooser_node.value == 123.0 assert chooser_node.quality.is_good() assert chooser_node.quality.get_description() == "" # We set source A bad as well... source_A_node.set_value(124.0, source_is_good=False) graph_manager.calculate() assert chooser_node.value == 0.0 assert chooser_node.quality.is_good() is False assert "No source has Good data" in chooser_node.quality.get_description() # We set source B Good... source_B_node.set_value(567.0, source_is_good=True) graph_manager.calculate() assert chooser_node.value == 567.0 assert chooser_node.quality.is_good() is True assert chooser_node.quality.get_description() == "" # We set source A Good... source_A_node.set_value(321.0, source_is_good=True) graph_manager.calculate() assert chooser_node.value == 321.0 assert chooser_node.quality.is_good() is True assert chooser_node.quality.get_description() == "" # We update A... source_A_node.set_value(432.0, source_is_good=True) graph_manager.calculate() assert chooser_node.value == 432.0 assert chooser_node.quality.is_good() is True assert chooser_node.quality.get_description() == ""
[ "richard.s.shepherd@gmail.com" ]
richard.s.shepherd@gmail.com
acde0420d5ab3939d172fe9bb041ec0a578d0335
95e44da0affe35a1f928543f9ea2fd2fbd4a6bd1
/src/order_detections_by_outlierness.py
584294a45668a4335bc1950e2940294265a948a0
[ "MIT" ]
permissive
mbanibenson/FaunD-Fast
caf1882d92a1da1308c7384db7984708d61217ad
146260ac3cb06a660db7122425fe08e958b5d1e8
refs/heads/main
2023-04-13T20:02:16.324831
2023-03-22T21:44:14
2023-03-22T21:44:14
617,589,813
0
0
null
null
null
null
UTF-8
Python
false
false
336
py
from pathlib import Path from visualization.sort_patches_by_outlier_scores import save_copies_of_detected_patches_ordered_by_anomaly_score if __name__ == '__main__': data_directory = Path.cwd().parents[0] / 'data/unsupervised_outlier_detection' save_copies_of_detected_patches_ordered_by_anomaly_score(data_directory)
[ "onyangombani@gmail.com" ]
onyangombani@gmail.com
0065833c1f25a7bfaaa59e6c837052035b4b3d4f
56eb8e3765244022cf380be85075a6291fc5bbc8
/Populating Next Right Pointers in Each Node II.py
b308ee7cb4479b633d467b20a298d942610b94c1
[]
no_license
zhouyuhangnju/freshLeetcode
bb564818909322699434912c4b75253b37b58a97
f52dfa5451475932b81081e8f23259672153dd7a
refs/heads/master
2020-12-02T10:00:50.410692
2017-08-01T07:39:10
2017-08-01T07:39:10
96,677,353
0
0
null
null
null
null
UTF-8
Python
false
false
1,186
py
# Definition for binary tree with next pointer. class TreeLinkNode: def __init__(self, x): self.val = x self.left = None self.right = None self.next = None # @param root, a tree link node # @return nothing def connect(root): if not root: return rightdict = {} def subConnect(currroot, layer): if currroot.left: subConnect(currroot.left, layer + 1) if currroot.right: subConnect(currroot.right, layer + 1) if layer in rightdict: preright = rightdict[layer] preright.next = currroot rightdict[layer] = currroot subConnect(root, 0) if __name__ == '__main__': root = TreeLinkNode(1) root.left = TreeLinkNode(2) root.right = TreeLinkNode(3) root.left.left = TreeLinkNode(4) root.left.right = TreeLinkNode(5) # root.right.left = TreeLinkNode(6) root.right.right = TreeLinkNode(7) connect(root) print root.next print root.left.next.val print root.right.next print root.left.left.next.val print root.left.right.next.val # print root.right.left.next.val print root.right.right.next
[ "zhouyhnju@qq.com" ]
zhouyhnju@qq.com
a9bca25f432b41dcf088d3342acd241c9975acb8
cbaac065a9e708569e516ec3932b75fa48ee7f87
/kattis-unbearzoo.py
1a0070f2c4780003df3478ffffd0f74f7ec174b1
[]
no_license
rezabayu/sedati
59c5ea0845bdbadbafe638bd4db3ab33eaeee11e
eccfbfffb39c0a1fb11dac7c38445eab50fe9d98
refs/heads/master
2021-09-26T04:25:45.375171
2021-09-19T15:38:22
2021-09-19T15:38:22
253,642,841
0
0
null
null
null
null
UTF-8
Python
false
false
456
py
from collections import Counter final = [] while True: n = int(input()) if n == 0: break ani = [] for i in range(n): kindo = input().split(" ")[-1] ani.append(kindo.lower()) ani.sort() kount = Counter(ani) anak = [] for a, b in kount.items(): anak.append(a+" | "+str(b)) final.append(anak) for i in range(len(final)): print("List %s:" % (i+1)) for j in final[i]: print(j)
[ "noreply@github.com" ]
noreply@github.com
d08201f6feccffe37f082e1b0346ae3e153f21c0
f4a5ceedda530491c539f0f658ea532c49bb10aa
/prog5.py
0c578da9bb3ced936491bbbf2f1cf6a02a8c49c6
[]
no_license
KirillBaboshko/Klasswork
43f03c15a08c8d17dd0005d311d77063cc7f1806
39f2aa4690be2ac60e4c59f2ca1e8032fcdc8c8a
refs/heads/master
2023-07-23T12:49:36.970846
2021-09-06T17:28:17
2021-09-06T17:28:17
null
0
0
null
null
null
null
UTF-8
Python
false
false
197
py
number = int(input("Введите целое число ")) revers_number = 0 while number > 0: revers_number = revers_number * 10 + number % 10 number = number // 10 print(revers_number)
[ "levanikogamer@yandex.ru" ]
levanikogamer@yandex.ru
1e219e53153cc2ba64677c4a7cdcbd6dadc77b4f
ca8200f8fa078aa4936544fdd7b31a91a7480351
/Kaggle/Plant_Pathology/self_attempt_01.py
9a3ad8b3590463a36029ad0e7d982532084c7ff6
[]
no_license
Lem0nRavioli/tutorial_backup
a7e1e627bff7ad527273069408d5f26bb588d880
e7c83908867a8a636757703e082766e7494d7dfc
refs/heads/master
2023-07-13T19:55:18.530141
2021-08-18T15:47:56
2021-08-18T15:47:56
321,391,393
0
0
null
null
null
null
UTF-8
Python
false
false
3,014
py
import silence_tensorflow.auto import tensorflow as tf from tensorflow.keras.preprocessing.image import ImageDataGenerator import pandas as pd import numpy as np import os class CFG: root = 'D:\Progs - D\DataSets\Plant_Pathology' root_train = os.path.join(root, 'train_images') root_train_shrinked = os.path.join(root, 'train_shrinked') root_test = os.path.join(root, 'test_images') root_csv = os.path.join(root, 'train.csv') root_duplicate = os.path.join(root, 'duplicates.csv') classes = [ 'complex', 'frog_eye_leaf_spot', 'powdery_mildew', 'rust', 'scab', 'healthy' ] strategy = tf.distribute.get_strategy() batch_size = 128 img_size = 128 folds = 5 seed = 42 subfolds = 16 transform = True # Data augmentation epochs = 10 df = pd.read_csv('train_multilabel.csv', index_col='image') train_images_names = df.index.values.copy() train_images = [] labels = [] test_loc = '800113bb65efe69e.jpg' for filename in train_images_names: image = tf.io.read_file(os.path.join(CFG.root_train_shrinked, filename)) image = tf.image.decode_jpeg(image, channels=3) image = tf.image.resize(image, [CFG.img_size, CFG.img_size]) image = np.array(image).astype('float32') train_images.append(image) labels.append(df.loc[filename].values) images = np.array(train_images) image_train = images[:12000] image_valid = images[12000:15555] image_test = images[15555:] labels = np.array(labels) labels_train = labels[:12000] labels_valid = labels[12000:15555] labels_test = labels[12000] print(images.shape) print(labels.shape) train_datagen = ImageDataGenerator( rescale=1. / 255, rotation_range=40, width_shift_range=.2, height_shift_range=.2, shear_range=.2, zoom_range=.2, horizontal_flip=True, fill_mode='nearest' ) validation_datagen = ImageDataGenerator(rescale=1. / 255) model = tf.keras.models.Sequential([ tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(128, 128, 3)), tf.keras.layers.MaxPooling2D(2, 2), tf.keras.layers.Conv2D(64, (3, 3), activation='relu'), tf.keras.layers.MaxPooling2D(2, 2), tf.keras.layers.Conv2D(128, (3, 3), activation='relu'), tf.keras.layers.MaxPooling2D(2, 2), tf.keras.layers.Dropout(.5), tf.keras.layers.Flatten(), tf.keras.layers.Dense(512, activation='relu'), tf.keras.layers.Dense(6, activation='sigmoid') ]) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['acc']) history = model.fit_generator(train_datagen.flow(images, labels, batch_size=CFG.batch_size), epochs=CFG.epochs, steps_per_epoch=int(len(images) / CFG.batch_size), validation_data=validation_datagen.flow(image_valid, labels_valid, batch_size=CFG.batch_size), validation_steps=int(len(image_valid) / CFG.batch_size)) # model.save("../Models/plant_128x128")
[ "hirona_mj@hotmail.fr" ]
hirona_mj@hotmail.fr
e8dbb49eaf032f605ddb2cf83de4810e472111da
934927eff3e755a82a8232aedc4e3f8bc2d1d9c8
/website/user.py
582980b36c88e9b279ff4b43c00a9915ae435f2d
[]
no_license
jpinheiro228/myCW
d855bc09f6f19bb5a2ef81cdc75eb379916516fc
9fe23b44c611809e9790c45dc83538fb30f3abf6
refs/heads/master
2022-04-13T17:43:07.942403
2020-03-25T19:08:01
2020-03-25T19:08:01
180,448,782
0
0
null
null
null
null
UTF-8
Python
false
false
2,066
py
from flask import (Blueprint, flash, redirect, render_template, request, url_for, abort, session) from website import db_utils from website.auth import login_required import os import docker_control as dc dir_path = os.path.dirname(os.path.realpath(__file__)) bp = Blueprint('user', __name__, url_prefix='/my_home') @bp.route("/") @login_required def main_page(): return render_template("user/main.html", current_exercise=db_utils.get_current_exercise_id( user_id=session["user_id"])) @bp.route("/list", methods=["GET", "POST"]) @login_required def list_exercises(): if request.method == "GET": return render_template("user/list.html") else: return abort(501) @bp.route("/exercise", methods=["GET", "POST"]) @login_required def exercise(): exercise_id = request.args.get('exercise_id') output = request.args.get('output') if not exercise_id: exercise_id = db_utils.get_current_exercise_id(user_id=session["user_id"]) ex = db_utils.get_exercise(int(exercise_id)) ex_sol = db_utils.get_exercise_solution(exercise_id=int(exercise_id), user=session["user_id"]) my_solution = "" if ex_sol: my_solution = ex_sol.code if request.method == "POST": sub_type = request.form["sub_type"] my_solution = request.form["my_solution"] if sub_type == "test": exec_code = ex.test_code else: exec_code = ex.check_code output = dc.run_code(code=my_solution, test_code=exec_code, user=session["username"]) db_utils.update_exercise_solution(exercise_id, session["user_id"], my_solution) return render_template("user/exercise.html", description=ex.description, test_code=ex.test_code, my_solution=my_solution, output=output, exercise_id=exercise_id)
[ "joao@gtel.ufc.br" ]
joao@gtel.ufc.br
17c32a613daa0e013bfcaad2caa72d86e7343183
53b47cbfea75afd22f37a2a9c8af4573165a0515
/Week5/Assessment 1/algorithm/algo.py
aa58e2a50fecb31c7a089d08f9c8950556523934
[]
no_license
bmolina-nyc/ByteAcademyWork
d757ed04033e23a4ec7aa8d09283f65b4cebcb17
b7a6790c2905afc9532b348149b730b7ea71de44
refs/heads/master
2022-12-06T19:17:02.164451
2019-03-11T15:31:10
2019-03-11T15:31:10
169,432,884
0
1
null
2022-11-18T15:08:12
2019-02-06T16:00:41
Python
UTF-8
Python
false
false
679
py
def sorting(MyList): zero_count = MyList.count(0) list_check = MyList.count(0) check = [] while zero_count > 0: check.append(0) zero_count -= 1 while True: for el in MyList: if el == 0: idx = MyList.index(el) pop = MyList.pop(idx) MyList.append(pop) elif el != 0: continue if MyList[-list_check:] == check: return MyList else: continue # print(sorting([1, 0, 7, 2, 0, 3, 9, 0, 4])) # [1, 7, 2, 3, 9, 4, 0, 0, 0] if __name__ == "__main__": print(sorting([1, 0, 7, 2, 0, 3, 9, 0, 4]))
[ "bruce.molina.81@gmail.com" ]
bruce.molina.81@gmail.com
a71c8b1625234bc4464d232588c2bc939ed2e953
4c3fbb4988850204f5ea0e667d54f29cdacdcc50
/plugins/Nuke/v13.0/nim_tools.py
ce8b59ca0d49adc91828564c1078c390c3b8efe1
[]
no_license
nsankar90/connectors
aa605d5ab7c0671ee8bd10931849b20645b30c87
5b5efa9f4c111ed76148185ede56e68830785611
refs/heads/master
2023-08-14T14:21:35.691251
2021-09-22T20:04:22
2021-09-22T20:04:22
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,415
py
#!/usr/bin/env python #****************************************************************************** # # Filename: Nuke/nim_tools.py # Version: v4.0.67.200319 # # Copyright (c) 2014-2021 NIM Labs LLC # All rights reserved. # # Use of this software is subject to the terms of the NIM Labs license # agreement provided at the time of installation or download, or which # otherwise accompanies this software in either electronic or hard copy form. # ***************************************************************************** print ("Loading: nim_tools") import os #This part of the scripts checks the output path and if it doesn't exist it creates it for you def CheckOutputPath(): import nuke file = nuke.filename(nuke.thisNode()) dir = os.path.dirname(file) osdir = nuke.callbacks.filenameFilter(dir) try: os.makedirs (osdir) except OSError: pass def updateNimWriteNodes(): import nuke writeNodes = nuke.allNodes('WriteNIM_JPG') writeNodes.extend(nuke.allNodes('WriteNIM_PNG')) writeNodes.extend(nuke.allNodes('WriteNIM_EXR')) writeNodes.extend(nuke.allNodes('WriteNIM_DPX')) writeNodes.extend(nuke.allNodes('WriteNIM_TIF')) writeNodes.extend(nuke.allNodes('WriteNIM_MOV')) # find autoFillWrite nodes for n in writeNodes: for k in n.knobs(): print(k) if k == "nim_outputFileText": try: n[k].setValue(n.knobs()['nimFilename'].value()) except: print("No NIM Write Nodes Found.") def logNimRender(writeNode=None): # Use this function by adding the following command to a writeNIM node's afterRender Python hook # # import nim_tools; nim_tools.logNimRender(nuke.thisNode()) # # You will need to set the frame range on the writeNIM node to match that of your output range # Currently this function is hardcoded to a single elementTypeID until a dropdown picker is added to the writeNIM node if writeNode is not None : print("Logging Render to NIM") import nuke import nim_core.nim_api as nimAPI shotID = nuke.root().knob('nim_shotID').getValue() #taskTypeID = nuke.root().knob('nim_taskID').getValue() #taskID = 15221 #tmp - hard coded till elementTypeID can be read from node elementTypeID = 1 #tmp - hard coded till elementTypeID can be read from node nimFolder = writeNode.knob('nimFolder').getValue() nimFileName = writeNode.knob('nimFilename').getValue() nimPath = writeNode.knob('nimPath').getValue() startFrame = writeNode.knob('first').getValue() endFrame = writeNode.knob('last').getValue() handles = 0 isPublished = False folderPath = nimPath+"/"+nimFolder nimFileName = nimFileName.replace('%04d','####') # Below commented out till taskID and elementTypeID can be read from node ''' result = nimAPI.add_render(taskID=taskID, renderName=nimFolder) if result['success'] == 'true': #nimAPI.upload_renderIcon(renderID=result['ID'],img='/path/to/icon.jpeg') nimAPI.add_element( parent='render', parentID=result['ID'], \ path=nimPath, name=nimFileName, \ typeID=elementTypeID, \ startFrame=startFrame, endFrame=endFrame, \ handles=handles, isPublished=isPublished ) else : print "Failed to add Render" ''' nimAPI.add_element( parent='shot', parentID=shotID, \ path=folderPath, name=nimFileName, \ typeID=elementTypeID, \ startFrame=startFrame, endFrame=endFrame, \ handles=handles, isPublished=isPublished ) return
[ "andrew@nim-labs.com" ]
andrew@nim-labs.com
29ec147b5a92e8a4e1dbf345acd3c425408dcbb0
471db8632f1b67ee532c057dc778979b956fcf50
/squidpy/instruments/ppms.py
acfd1c64be2d83b261e1ca3808158ad0c008cd6e
[ "MIT" ]
permissive
guenp/squidpy
b0509d3a75a7226bfa027787e1895f8c2ce9288a
17af231cef7142325a483aaa95041671e4daaea4
refs/heads/master
2021-01-22T17:17:56.027947
2016-03-04T21:53:19
2016-03-04T21:53:19
45,823,821
0
0
null
null
null
null
UTF-8
Python
false
false
1,950
py
from squidpy.instrument import Instrument from squidpy.utils import ask_socket, connect_socket class PPMS(Instrument): ''' For remote operation of the Quantum Design PPMS. Make sure to run PyQDInstrument.run_server() in an IronPython console on a machine that can connect to the PPMS control PC's QDInstrument_Server.exe program. Attributes represent the system control parameters: 'temperature', 'temperature_rate', 'temperature_approach', 'field', 'field_rate', 'field_approach', 'field_mode', 'temperature_status', 'field_status', 'chamber' ''' def __init__(self, host, port, s=None, name='ppms'): self._name = name if s == None: self._s = connect_socket(host, port) else: self._s = s self._units = {'temperature': 'K', 'temperature_rate': 'K/min','field': 'Oe', 'field_rate': 'Oe/min'} for param in ['temperature', 'temperature_rate', 'field', 'field_rate', 'temperature_approach', 'field_approach', 'field_mode']: setattr(PPMS,param,property(fget=eval("lambda self: self._get_param('%s')" %param), fset=eval("lambda self, value: self._set_param('%s',value)" %param))) for param in ['temperature_status', 'field_status', 'chamber']: setattr(PPMS,param,property(fget=eval("lambda self: self._get_param('%s')" %param))) self._params = ['temperature', 'temperature_rate', 'temperature_approach', 'field', 'field_rate', 'field_approach', 'field_mode', 'temperature_status', 'field_status', 'chamber'] self._functions = [] def _get_param(self, param): return ask_socket(self._s, param) def _set_param(self, param, value): if type(value) == str: cmd = "%s = '%s'" %(param, value) else: cmd = '%s = %s' %(param, value) return ask_socket(self._s, cmd) def __del__(self): self._s.close()
[ "guen@nbi.dk" ]
guen@nbi.dk
0066db67f7740aee920daacc38dcce5f944b7ec6
9432848a2dbd56c16e307923769831f68c8db35b
/main.py
7ec27e2fe8b2f04cb25a47d6c81f3b9ff1f87d52
[]
no_license
Nadunnissanka/Day-68-flask-auth
e5a64326bc79d8d94b7866ad6f1baa2b0639af64
d0d4b39291daf786ee7b4d4a6e4fc60fcecabf60
refs/heads/master
2023-07-18T10:29:34.543899
2021-08-18T17:03:18
2021-08-18T17:03:18
397,647,972
0
0
null
null
null
null
UTF-8
Python
false
false
3,432
py
from flask import Flask, render_template, request, url_for, redirect, flash, send_from_directory from werkzeug.security import generate_password_hash, check_password_hash from flask_sqlalchemy import SQLAlchemy from flask_login import UserMixin, login_user, LoginManager, login_required, current_user, logout_user app = Flask(__name__) app.config['SECRET_KEY'] = 'any-secret-key-you-choose' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) # Flask Login Configure login_manager = LoginManager() login_manager.init_app(app) # Provide user loader callback @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) # CREATE TABLE IN DB class User(UserMixin, db.Model): id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(100), unique=True) password = db.Column(db.String(100)) name = db.Column(db.String(1000)) # Line below only required once, when creating DB. # db.create_all() @app.route('/') def home(): return render_template("index.html", logged_in=current_user.is_authenticated) @app.route('/register', methods=['POST', 'GET']) def register(): if request.method == "POST": form_data = request.form user_name = form_data['name'] user_email = form_data['email'] if User.query.filter_by(email=user_email).first(): # user already exist msg flash("you are already logged in using this email") return redirect(url_for('register')) user_password = generate_password_hash(form_data['password'], method='pbkdf2:sha256', salt_length=8) new_user = User(name=user_name, email=user_email, password=user_password) db.session.add(new_user) db.session.commit() # Log in and authenticate user after adding details to database. login_user(new_user) return redirect(url_for('secrets', name=new_user.name)) return render_template("register.html", logged_in=current_user.is_authenticated) @app.route('/login', methods=['POST', 'GET']) def login(): if request.method == "POST": form_data = request.form user_email = form_data['email'] user_password = form_data['password'] # Email doesn't exist user = User.query.filter_by(email=user_email).first() if not user: flash("That email does not exist, please try again.") return redirect(url_for('login')) # Password incorrect elif not check_password_hash(user.password, user_password): flash('Password incorrect, please try again.') return redirect(url_for('login')) # Email exists and password correct else: login_user(user) return redirect(url_for('secrets', name=user.name)) return render_template("login.html", logged_in=current_user.is_authenticated) @app.route('/secrets/<name>') @login_required def secrets(name): return render_template("secrets.html", name=name) @app.route('/logout') def logout(): logout_user() return redirect(url_for('home')) @app.route('/download') @login_required def download(): try: return send_from_directory('static', filename="files/cheat_sheet.pdf") except FileNotFoundError: return "404! File not found..." if __name__ == "__main__": app.run(debug=True)
[ "61065783+Nadunnissanka@users.noreply.github.com" ]
61065783+Nadunnissanka@users.noreply.github.com
bdb29b4f051ad6074cdbe4071a341a81d25d3545
0cd4014040a7374f0b82fe7077246f2cab470c3d
/linkedin_profile_search.py
f7cc8bd21ce073efe556506c2adf5b5f0dc0c463
[]
no_license
LinkedIn-Crawler/Crawler
6e5970caad586d3e817398ab0c965d3aee79ac18
6f33a232941564adadfd2f453974c456263acefd
refs/heads/master
2023-05-27T00:16:59.834194
2021-06-15T17:20:42
2021-06-15T17:20:42
284,042,525
0
0
null
null
null
null
UTF-8
Python
false
false
3,321
py
import csv import sys import fileinput from selenium import webdriver from time import sleep from selenium.webdriver.common.keys import Keys import parameters from parsel import Selector writer = csv.writer(open(parameters.result_file,'w')) writer.writerow(['Sl. No.','Name of the Candidate','Job Title','Schooling/Education','Current Location','Profile LinkedIn URL']) driver = webdriver.Chrome('C:/Users/saisa/Desktop/chromedriver') driver.maximize_window() sleep(0.5) driver.get('https://www.linkedin.com/') sleep(2) driver.find_element_by_xpath('//a[text()="Sign in"]').click() sleep(3) username = driver.find_element_by_name('session_key') username.send_keys(parameters.user) sleep(0.5) password = driver.find_element_by_name('session_password') password.send_keys(parameters.passw) sleep(0.5) driver.find_element_by_xpath('//button[text()="Sign in"]').click() sleep(5) driver.get('https://www.google.com/') sleep(2) search_input = driver.find_element_by_name('q') beg = 'site:linkedin.com/in -intitle:profiles -inurl:"/dir' print('Instructions:') print('Enter the Keywords you require one by one and then Press Enter') print('Enter -1 if you are done with your keywords') for line in sys.stdin: if('-1' == line.rstrip()): break r1 = line.rstrip() beg = beg + ' AND ' beg = beg + '"{}"'.format(r1) print('Enter the next keyword') print('Enter -1 if you are done with your keywords') k = int(input('Enter the number of Profiles Required (between 1 to 200)')) print('FINDING SUITABLE PROFILES.......') search_input.send_keys(beg) sleep(0.5) search_input.send_keys(Keys.RETURN) sleep(3) i = 0 prev = driver.current_url while i<k: profiles = driver.find_elements_by_xpath('//*[@class="r"]/a[1]') profiles = [profile.get_attribute('href') for profile in profiles] for profile in profiles: i = i+1 driver.get(profile) sleep(3) linkedin_url = driver.current_url if linkedin_url.find('unavailable') != -1: i = i-1 continue if linkedin_url.find('linkedin') == -1: i = i-1 continue sel = Selector(text=driver.page_source) name = sel.xpath('//title/text()').extract_first().split(' | ')[0].strip() if name[0]=='(': name = name.split(')')[1].strip() print(i) print('Scraping Profile of ' + name) temp = sel.xpath('//h2/text()').extract() sz = len(temp) job_title = ''; if sz>=2: job_title = temp[1].strip() else: job_title = temp[0].strip() schools = sel.xpath('//*[contains(@class,"pv-entity__school-name")]/text()').extract() location = sel.xpath('//*[@class="t-16 t-black t-normal inline-block"]/text()').extract_first().strip() try: writer.writerow([i,name,job_title,schools,location,linkedin_url]) except: continue if i==k: break if i==k: break driver.get(prev) sleep(2) clicker = driver.find_elements_by_xpath('//span[text()="Next"]') if len(clicker)>0: clicker[0].click() sleep(2) else: print('Number of profiles Does Not meet User Requirements') break; prev = driver.current_url driver.quit()
[ "samay@iitg.ac.in" ]
samay@iitg.ac.in
446964d9b5e4afad27b0dc77eb6cd248496d477b
b000af82a539dd065d01ceeb7362e5beaee1659e
/basics/urls.py
c3a0b7bde77ade4bba43c8bea73d600c1288b7f1
[]
no_license
buwaketaki/Stock-Market-Analysis
1de008f4439ae5855945700b4d42404fcb08c030
75a45c264d1c366cae9ed8d1e063c1e2d3b64e6d
refs/heads/master
2022-12-15T10:35:22.579397
2020-09-01T05:24:55
2020-09-01T05:24:55
291,901,651
0
0
null
null
null
null
UTF-8
Python
false
false
856
py
from django.urls import path from rest_framework import routers from .api import HistoryDataViewSet, UpdatedDataViewSet, DataViewSet from . import views from django.views.decorators.csrf import csrf_exempt router = routers.DefaultRouter() router.register('api/data', DataViewSet, 'HistoryData') router.register('api/recentdata',DataViewSet, 'RecentData') router.register('api/historydata', HistoryDataViewSet, 'HistoryData') # router.register(('', views.index, name='index') urlpatterns= [path('updatedData/', views.check_if_update_present), path('data/<stock_name>/',csrf_exempt( views.check_recent_record.as_view())), path('historicalData/<stock_name>/',csrf_exempt( views.check_historical_record.as_view())), path('', views.index, name='index'), # path('getRecentInfo', views.check_recent_record) ] urlpatterns += router.urls
[ "ketaki.buwa.kb@gmail.com" ]
ketaki.buwa.kb@gmail.com
ba390262491d2b85c1a086e78fde731a173b1ef6
4cf3f8845d64ed31737bd7795581753c6e682922
/.history/main_20200118152650.py
71f2c0cb3e667e65dce164fea2e7b4e149d01c27
[]
no_license
rtshkmr/hack-roll
9bc75175eb9746b79ff0dfa9307b32cfd1417029
3ea480a8bf6d0067155b279740b4edc1673f406d
refs/heads/master
2021-12-23T12:26:56.642705
2020-01-19T04:26:39
2020-01-19T04:26:39
234,702,684
1
0
null
2021-12-13T20:30:54
2020-01-18T08:12:52
Python
UTF-8
Python
false
false
82,147
py
from telegram.ext import Updater, CommandHandler import requests import re # API call to source, get json (url is obtained): contents = requests.get('https://random.dog/woof.json').json() image_url = contents['url'] def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main()
[ "ritesh@emerald.pink" ]
ritesh@emerald.pink
b1d7d6b13505195a68322431517578106a571d2e
0e14bf4cfebd1e78bce92c4cc36d301b3185aa08
/BookingPlatform/migrations/0001_initial.py
4924ed1cbe26b96d34349aea56f03a705837217d
[]
no_license
karantatiwala/Booking-Platform-API
e2bf38373a6735e17bfa36a86ea0e1bd5fb64e20
f8544173d5e8cdf1c4a77995d4461bf61afc8135
refs/heads/master
2020-04-06T13:28:17.442317
2018-11-14T06:25:54
2018-11-14T06:25:54
157,496,017
0
0
null
null
null
null
UTF-8
Python
false
false
733
py
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-10-12 20:38 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='TheatreDetails', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('screenName', models.CharField(max_length=25)), ('rowNumber', models.CharField(max_length=2)), ('maxCapacity', models.IntegerField()), ('aisleSeats', models.TextField()), ], ), ]
[ "noreply@github.com" ]
noreply@github.com
a047cd7c702fb834ba38166a6d918c83e9a7cfcb
af31378dbb1ca367d5917ea5af37aac7c3193ae6
/authors/models.py
d509ae67655ac9631762aded12aae48693542dac
[]
no_license
aish1499/library_projects
8104ec5919079e1dcb1c5b9b21f65167b1a6a136
fcbe8f680bdf6313cc10a6b11f5f1edb6de028e3
refs/heads/master
2022-12-09T20:37:14.549414
2020-01-28T12:17:44
2020-01-28T12:17:44
236,725,279
0
0
null
2022-11-22T04:57:49
2020-01-28T12:01:21
Python
UTF-8
Python
false
false
748
py
from django.db import models from django.utils.translation import ugettext_lazy as _ # Create your models here. def upload_photo(instance, filename): return f'{instance.name}/{filename}' class Author(models.Model): name = models.CharField(max_length=100) about = models.TextField(_("About"),blank=True,null=True) dob = models.DateField(blank=True, null=True) language = models.CharField(max_length=50) country = models.CharField(max_length=50, blank=True, null=True) books_in_collection = models.IntegerField(_("Books in collection"),default=0,blank=True,null=True) image = models.ImageField(_("photo"), upload_to=upload_photo,blank=True, null=True ) def __str__(self): return self.name
[ "aishwaryabpotadar@gmail.com" ]
aishwaryabpotadar@gmail.com
8f6a8483eb5361ba18a975aad682f9d16df8ea1d
474c1742341ed2ab3baeecc9eb17fb42ae359936
/main.py
9bba9e8dcb56aa31f207ccf9a63e765c4a956e09
[]
no_license
extremecodetv/walrus
fe0e1d0e8ddc5fb15c42463f04bf1c7f56c729c3
0fd3a834f4720b35d5571e1e877ac4fd58148e6d
refs/heads/master
2021-07-12T11:34:07.518483
2021-03-26T09:33:50
2021-03-26T09:33:50
245,806,428
51
26
null
2021-06-02T01:09:15
2020-03-08T12:01:14
Python
UTF-8
Python
false
false
269
py
import argparse import gender def main(): parser = argparse.ArgumentParser() parser.add_argument("--image") args = parser.parse_args() genders = gender.resolve(args.image) for g in genders: print(g) if __name__ == "__main__": main()
[ "extremecodetv@gmail.com" ]
extremecodetv@gmail.com
a52d484c64105b891b86fb82a6743f01e41391c9
b01a3044764386602029fe0ad1ff50a035d78f59
/homework_11_30_18/Product.py
a473eabd7c474c5bd319b0cef00d01402529f96e
[]
no_license
0kba/python
5dcdf51c7dedae66f3a5dfc71704c32693014f7d
9264dee507e296bbef31b689578bb49b347ec9b9
refs/heads/master
2020-03-29T14:34:06.148277
2018-11-30T01:02:14
2018-11-30T01:02:14
150,023,623
0
1
null
null
null
null
UTF-8
Python
false
false
323
py
class Product: def __init__(self, ProductId, ProductName, Category, Price): self.ProductId = ProductId self.ProductName = ProductName self.Category = Category self.Price = Price def __repr__(self): return (f"{self.ProductId} {self.ProductName} {self.Category} {self.Price}")
[ "m.okba@outlook.com" ]
m.okba@outlook.com
b037a44c8142b552def5b0a27460e18016cdcb7b
0445301b7214bb58808c6f1c768d1580dc26f247
/seinfeld/quote_of_the_day.py
666e369b2a3a83ec516e05424933e708a75bfd31
[]
no_license
hello-newman/minimal-pants
1a29346d32b39d56b963061ddad54f317a0e0707
05cf60c1c2e10d45d5a138c624833e2aba5276bd
refs/heads/main
2023-08-25T15:04:14.950593
2021-09-24T19:51:11
2021-09-24T19:51:11
371,522,935
0
0
null
2021-09-25T05:54:33
2021-05-27T22:53:46
Shell
UTF-8
Python
false
false
927
py
from __future__ import annotations import random _QUOTES = [ "What do you need it for after you read it", "How come people don’t have dip for dinner", "You have the chicken, the hen, and the rooster", "Jerry, just remember, it’s not a lie if you believe it.", "Moles — freckles’ ugly cousin", "Just remember, when you control the mail, you control… information", "Human, it’s human to be moved by a fragrance.", "Women don’t respect salad eaters.", "Maybe the dingo ate your baby!", "People on dates shouldn’t even be allowed out in public.", "Three squares? You can’t spare three squares?", "He stopped short? ", ] class Quotes: @classmethod def create(cls): return cls(quotes=_QUOTES) def __init__(self, quotes: list[str]) -> None: self._quotes = quotes def quote(self) -> str: return random.choice(self._quotes)
[ "1268088+asherf@users.noreply.github.com" ]
1268088+asherf@users.noreply.github.com
e0e89fc50efc89bf53d5cfdcb633d9707c8981e9
ac176f429c420a8d6290c57df14346d207cff3de
/leetcodepython/app/algorithm/MaxHeap.py
f370b41197fa1071203817620dfdece566d53ac2
[]
no_license
xu20160924/leetcode
72c6fc02428e568148af4503c63c6f2553982a1c
43e12a3db5b4087913ec338e652ae7fd59859c23
refs/heads/master
2023-08-04T14:41:06.964273
2022-11-20T13:39:28
2022-11-20T13:39:28
252,931,114
0
0
null
2023-07-23T10:52:04
2020-04-04T06:57:49
Java
UTF-8
Python
false
false
3,210
py
class MaxHeap: def __init__(self, capacity): # 我们这个版本的实现中,0号索引是不存数据的, 这一点一定要注意 # 因为数组从索引1开始存放数值 # 所以开辟 capacity + 1 这么多打下的空间 self.data = [None for _ in range(capacity + 1)] # 当前堆中存储的元素的个数 self.count = 0 # 堆中能够存储的元素的最大数量(为简化问题, 不考虑动态扩展) self.capacity = capacity def size(self): """ 返回最大堆中的元素个数 :return: """ return self.count def is_empty(self): return self.count == 0 def insert(self, item): if self.count + 1 > self.capacity: raise Exception('堆的容量不够了') self.count += 1 self.data[self.count] = item # 上移 self.__siwn(self.count) def __shift_up(self, k): # 有索引就要考虑索引越界的情况,已经在索引1的位置,就没有必要上移了 while k > 1 and self.data[k // 2] < self.data[k]: self.data[k // 2], self.data[k] = self.data[k], self.data[k // 2] k //= 2 def __shift_down(self, k): # 只要有左右孩子,左右孩子只要比自己大,就交换 while 2 * k <= self.count: # 如果这个元素有左边的孩子 j = 2 * k # 如果右边的孩子,大于左边的孩子,就好像左边的孩子不存在一样 if j + 1 <= self.count and self.data[j + 1] > self.data[j]: j = j + 1 if self.data[k] >= self.data[j]: break self.data[k], self.data[j] = self.data[j], self.data[k] k = j def extract_max(self): if self.count == 0: raise Exception('堆里没有可以取出的元素') ret = self.data[1] self.data[1], self.data[self.count] = self.data[self.count], self.data[1] self.count -= 1 self.__sink(1) return ret def __siwn(self, k): # 上浮, 与父节点进行比较 temp = self.data[k] # 有索引就要考虑索引越界的情况,已经在索引1的位置,就没必要上移了 while k > 1 and self.data[k // 2] < temp: self.data[k] = self.data[k // 2] k //= 2 self.data[k] = temp def __sink(self, k): # 下沉 temp = self.data[k] # 只要它有孩子, 这里的等于号是十分关键的 while 2 * k <= self.count: j = 2 * k # 如果它有右边的孩子,并且右边的孩子大于左边的孩子 if j + 1 <= self.count and self.data[j + 1] > self.data[j]: # 右边的孩子胜出,此时可以认为没有左孩子 j += 1 # 如果当前的元素的值,比右边的孩子节点要大,则逐渐下落的过程到此结束 if temp >= self.data[j]: break # 否则, 交换位置, 继续循环 self.data[k] = self.data[j] k = j self.data[k] = temp
[ "xu20151211@gmail.com" ]
xu20151211@gmail.com
01e84a5b890b5329173fd3e9147e0c68891ed5b6
0a503a34cb2183163b7e5dc1f5f3db285c1543a6
/downloader.py
723f27c37d1c1aafcec502beba3449eb62a90733
[ "MIT" ]
permissive
LinkWoong/CIS668_Final_Project
98c722faab38eff15a38e36b1634e4fb088598c4
f6b4646e0c07848968d1ea90e5ca4f59f5d5c35a
refs/heads/main
2023-01-13T22:05:15.762819
2020-11-21T16:28:48
2020-11-21T16:28:48
300,903,853
0
1
MIT
2020-11-22T01:23:42
2020-10-03T14:49:02
Jupyter Notebook
UTF-8
Python
false
false
11,295
py
from __future__ import print_function import io import json import os import sys import time import argparse import lxml.html import requests import queue import google_auth_oauthlib.flow from lxml.cssselect import CSSSelector from googleapiclient.discovery import build from googleapiclient.discovery import build_from_document from googleapiclient.errors import HttpError from google_auth_oauthlib.flow import InstalledAppFlow from id_getter import youtube_search YOUTUBE_VIDEO_URL = 'https://www.youtube.com/watch?v={youtube_id}' YOUTUBE_COMMENTS_AJAX_URL_OLD = 'https://www.youtube.com/comment_ajax' YOUTUBE_COMMENTS_AJAX_URL_NEW = 'https://www.youtube.com/comment_service_ajax' # AIzaSyBE5tvxahwBu3Z3y2R2lVrY11pNfQLOcIA, this is my API key. Please replace it with yours # download it from your google developer console: https://cloud.google.com/console under tab of API Keys DEVELOPER_KEY = "AIzaSyBE5tvxahwBu3Z3y2R2lVrY11pNfQLOcIA" YOUTUBE_API_SERVICE_NAME = 'youtube' YOUTUBE_API_VERSION = "v3" # Http header USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36' # find a specific value in HTML entities def find_value(html, key, num_chars=2, separator='"'): pos_begin = html.find(key) + len(key) + num_chars pos_end = html.find(separator, pos_begin) return html[pos_begin: pos_end] # simple HTTP GET request with retries, each retry has 20 seconds separation def ajax_request(session, url, params=None, data=None, headers=None, retries=5, sleep=20): for _ in range(retries): response = session.post(url, params=params, data=data, headers=headers) if response.status_code == 200: return response.json() if response.status_code in [403, 413]: return {} else: time.sleep(sleep) # use new api to download live stream # else use old api def download_comments(youtube_id, sleep=.1): if r'\"isLiveContent\":true' in requests.get(YOUTUBE_VIDEO_URL.format(youtube_id=youtube_id)).text: print('Live stream detected! Not all comments may be downloaded.') return download_comments_new_api(youtube_id, sleep) return download_comments_old_api(youtube_id, sleep) def download_comments_new_api(youtube_id, sleep=1): # Use the new youtube API to download some comments session = requests.Session() session.headers['User-Agent'] = USER_AGENT response = session.get(YOUTUBE_VIDEO_URL.format(youtube_id=youtube_id)) html = response.text session_token = find_value(html, 'XSRF_TOKEN', 3) data = json.loads(find_value(html, 'window["ytInitialData"] = ', 0, '\n').rstrip(';')) for renderer in search_dict(data, 'itemSectionRenderer'): ncd = next(search_dict(renderer, 'nextContinuationData'), None) if ncd: break continuations = [(ncd['continuation'], ncd['clickTrackingParams'])] while continuations: continuation, itct = continuations.pop() response = ajax_request(session, YOUTUBE_COMMENTS_AJAX_URL_NEW, params={'action_get_comments': 1, 'pbj': 1, 'ctoken': continuation, 'continuation': continuation, 'itct': itct}, data={'session_token': session_token}, headers={'X-YouTube-Client-Name': '1', 'X-YouTube-Client-Version': '2.20200207.03.01'}) if not response: break if list(search_dict(response, 'externalErrorMessage')): raise RuntimeError('Error returned from server: ' + next(search_dict(response, 'externalErrorMessage'))) # Ordering matters. The newest continuations should go first. continuations = [(ncd['continuation'], ncd['clickTrackingParams']) for ncd in search_dict(response, 'nextContinuationData')] + continuations for comment in search_dict(response, 'commentRenderer'): yield {'cid': comment['commentId'], 'text': ''.join([c['text'] for c in comment['contentText']['runs']])} time.sleep(sleep) # sleep for a given time period so we don't get blocked by Google :) def search_dict(partial, key): if isinstance(partial, dict): for k, v in partial.items(): if k == key: yield v else: for o in search_dict(v, key): yield o elif isinstance(partial, list): for i in partial: for o in search_dict(i, key): yield o def download_comments_old_api(youtube_id, sleep=1): # Use the old youtube API to download all comments (does not work for live streams) session = requests.Session() session.headers['User-Agent'] = USER_AGENT # Get Youtube page with initial comments response = session.get(YOUTUBE_VIDEO_URL.format(youtube_id=youtube_id)) html = response.text reply_cids = extract_reply_cids(html) ret_cids = [] for comment in extract_comments(html): ret_cids.append(comment['cid']) yield comment page_token = find_value(html, 'data-token') session_token = find_value(html, 'XSRF_TOKEN', 3) first_iteration = True # Get remaining comments (the same as pressing the 'Show more' button) while page_token: data = {'video_id': youtube_id, 'session_token': session_token} params = {'action_load_comments': 1, 'order_by_time': True, 'filter': youtube_id} if first_iteration: params['order_menu'] = True else: data['page_token'] = page_token response = ajax_request(session, YOUTUBE_COMMENTS_AJAX_URL_OLD, params, data) if not response: break page_token, html = response.get('page_token', None), response['html_content'] reply_cids += extract_reply_cids(html) for comment in extract_comments(html): if comment['cid'] not in ret_cids: ret_cids.append(comment['cid']) yield comment first_iteration = False time.sleep(sleep) # Get replies (the same as pressing the 'View all X replies' link) for cid in reply_cids: data = {'comment_id': cid, 'video_id': youtube_id, 'can_reply': 1, 'session_token': session_token} params = {'action_load_replies': 1, 'order_by_time': True, 'filter': youtube_id, 'tab': 'inbox'} response = ajax_request(session, YOUTUBE_COMMENTS_AJAX_URL_OLD, params, data) if not response: break html = response['html_content'] for comment in extract_comments(html): if comment['cid'] not in ret_cids: ret_cids.append(comment['cid']) yield comment time.sleep(sleep) # use lxml parser to extract comments from html tree def extract_comments(html): tree = lxml.html.fromstring(html) item_sel = CSSSelector('.comment-item') text_sel = CSSSelector('.comment-text-content') for item in item_sel(tree): yield {'cid': item.get('data-cid'), 'text': text_sel(item)[0].text_content()} def extract_reply_cids(html): tree = lxml.html.fromstring(html) sel = CSSSelector('.comment-replies-header > .load-comments') return [i.get('data-cid') for i in sel(tree)] def main(argv): parser = argparse.ArgumentParser(add_help=False, description=('Download Youtube comments without using the Youtube API')) # parser.add_argument('--youtubeid', '-y', help='ID of Youtube video for which to download the comments') parser.add_argument('--output', '-o', help='Output filename (output format is line delimited JSON)') # parser.add_argument('--limit', '-l', type=int, help='Limit the number of comments') parser.add_argument('--q', '-q', help='Keyword to search, now only accept one word.') parser.add_argument('--maxresults', '-m', help='Maximum query result for a keyword', default=25) # TODO: read a list containing all words needed instead of read one by one # example output: <K, V> pair -> cid : comment # { # "UgyNfVDpgesamWyWT794AaABAg": "the irony is that this video is stored in google cloud platform", # "UghZPYxpAU6oT3gCoAEC": "Ouch, high frequency tones used for digital bit flow sound effect. Use lower tones...", # "UghZPYxpAU6oT3gCoAEC.8OrRc3r3vFl8W71TLv2WSz": "nerd", # "UgjO0PNK_Y2nMngCoAEC": "That's awesome. People with money who want to help people are the best" # } try: args = parser.parse_args(argv) output = args.output video_ids = youtube_search(args, YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, DEVELOPER_KEY) inc = 0 while not video_ids.empty(): youtube_id = video_ids.get() if not youtube_id or not output: parser.print_usage() raise ValueError('you need to specify a Youtube ID and an output filename') if os.sep in output: outdir = os.path.dirname(output) if not os.path.exists(outdir): os.makedirs(outdir) print('Downloading Youtube comments for video:', youtube_id) count = 0 sys.stdout.write('Downloaded %d comment(s)\r' % count) sys.stdout.flush() start_time = time.time() for comment in download_comments(youtube_id): comment_json = json.dumps(comment, ensure_ascii=False) if isinstance(comment_json, bytes): comment_json = comment_json.decode('utf-8') # print(comment_json) # {"cid": "UgyNfVDpgesamWyWT794AaABAg", "text": "the irony is that this video is stored in google cloud platform"} comment_json = json.loads(comment_json) if inc != 0: with open(output) as fp: data = json.load(fp) data.update({comment_json["cid"]: comment_json["text"]}) with open(output, "w", encoding='utf-8') as fp: json.dump(data, fp, ensure_ascii=False, indent=4) else: with open(output, "w", encoding='utf-8') as fp: # print(comment_json.decode('utf-8') if isinstance(comment_json, bytes) else comment_json, file=fp) json.dump({comment_json["cid"]: comment_json["text"]}, fp, ensure_ascii=False, indent=4) inc += 1 count += 1 sys.stdout.write('Downloaded %d comment(s)\r' % count) sys.stdout.flush() print('\n[{:.2f} seconds] Done!'.format(time.time() - start_time)) except Exception as e: print('Error:', str(e)) sys.exit(1) if __name__ == "__main__": main(sys.argv[1:])
[ "zuiaineo@foxmail.com" ]
zuiaineo@foxmail.com
2e2aa42191565859e305c671773a20d93e459e04
615ce4f7790057c92d93f43a5f0cab9ba018fbd6
/pathological/atomics/strings/evaluatable.py
29efa6a5e4aceb5c95b7ef7a0bd4d68ee5b533fd
[ "MIT" ]
permissive
OaklandPeters/pathological
20e88fac7216eebfe735a018449813f956c69484
c561eb30df8cdcc0f277a17cd08a03cf173e312f
refs/heads/master
2021-01-10T16:00:54.798667
2016-03-07T14:47:54
2016-03-07T14:55:20
53,332,021
0
0
null
null
null
null
UTF-8
Python
false
false
64
py
""" SQL Python code Python eval Javscript Javascript eval C """
[ "oakland.peters@gmail.com" ]
oakland.peters@gmail.com
dbbafc2c33719d692df83c2c0a3a15b9124eba86
14e30f6324200569a75ed5210f7aee842fc901d0
/venv/Lib/site-packages/cx_Freeze/samples/cryptography/setup.py
b54d61ce4f8702cee905d5223d9fa5aedec88ab7
[]
no_license
FardinOyon/MP3-Player
bc56ae7c2153e7651bc21744f3e0606c0300c250
8b832c09a6190589e1256637b874b6fc2e986adb
refs/heads/main
2023-04-01T20:13:07.487350
2021-04-10T17:40:10
2021-04-10T17:40:10
356,653,188
1
0
null
null
null
null
UTF-8
Python
false
false
672
py
"""A setup script to demonstrate build using cffi (used by cryptography)""" # # Run the build process by running the command 'python setup.py build' # # If everything works well you should find a subdirectory in the build # subdirectory that contains the files needed to run the script without Python from cx_Freeze import setup, Executable setup( name="test_crypt", version="0.2", description="cx_Freeze script to test cryptography", executables=[Executable("test_crypt.py")], options={ "build_exe": { "excludes": ["tkinter"], "zip_include_packages": ["*"], "zip_exclude_packages": [], } }, )
[ "oyonfardin8@gmail.com" ]
oyonfardin8@gmail.com
bd62b0d666650471f065aa55e2f898a6ad1fc359
bdd7e4fcc017ec724caa05eb2a624f60208b8813
/script.py
99d6d7313477507312001f2a720b33551b1e22be
[]
no_license
etjkai/Tkinter
5a944990ec6ebef0e65350dec897993beff6ee8b
62012d9a4b6202eec664c61b3b1e46993ca93a26
refs/heads/master
2022-12-08T20:19:15.688285
2020-09-10T18:32:54
2020-09-10T18:32:54
294,491,627
0
0
null
null
null
null
UTF-8
Python
false
false
1,791
py
import tkinter as tk window = tk.Tk() frame_a = tk.Frame(master=window) frame_b = tk.Frame(master=window, # Creates a border around frame relief=tk.RAISED, # Border must be > 1 for frame to take effect borderwidth=3) ''' List of Widgets 1) Label (lbl) 2) Button (btn) 3) Entry (ent) - .get() - retrieve text - .delete() - delete text - .insert() - insert text 4) Text (txt) - .get() / delete() parameters <line number>.<position of a character on that line> - e.g. "1.5" - .insert() -- Insert text at position if already present -- Append text to line if character number > index of last character - tk.END for all text in box 5) Frame (frm) ''' # Creating Label widget label_a = tk.Label( # Which frame to assign this widget master=frame_a, text='I am in Frame A!', foreground='black', # Height & width are respective to the character: 0 width=40, height=10, background='orange' ) label_b = tk.Label(master=frame_b, text="I am in Frame B!", height=15) # Adding widgets into frame label_a.pack() label_b.pack() ''' Geometry Managers [1] .pack() - creates rectangular area (parcel) just tall/wide enough for widget - fills rest with blank space - centers widget by default [2] .place() - may be difficult to manage - not responsive to resizing [3] .grid() ''' # Add frame into window frame_a.pack() frame_b.pack( # fill - which direction frames should fill: tk.X - horizontal, tk.Y - vertical, tk.BOTH fill=tk.X, side=tk.LEFT ) # Run Tkinter event loop - listening for events, until window it is called on is closed. window.mainloop() # Close the window # window.destroy()
[ "etjkai@gmail.com" ]
etjkai@gmail.com
b8124490b623a6c5b281a10cce0cc972f2334d95
9017f217abe077aff77f64938a988fcc4a292e40
/plate/common/syntax_highlighting.py
aa0484c12f2fad1de5134b9f34f2332e331f0d6d
[ "Apache-2.0" ]
permissive
gogit/plate
c8c47d47de2b11d5c7b4840106181bb177b50c88
2e5fdb1ddfad560986b429cf2ff92aed4d35e56c
refs/heads/master
2021-01-18T07:18:52.770779
2016-04-08T11:45:00
2016-04-08T11:45:00
null
0
0
null
null
null
null
UTF-8
Python
false
false
804
py
# -*- coding:utf-8 -*- def syntax_highlight(lang, code): """ code highlighting HTML Format :param lang: programming language :param code: code :return: highlighted code """ from pygments import lexers from pygments import highlight from pygments.formatters import HtmlFormatter try: lexer = lexers.get_lexer_by_name(lang.lower()) highlighted = highlight(code, lexer, HtmlFormatter()) splitted = highlighted.split('"highlight') highlighted = splitted[0] + '"highlight '+lang + splitted[1] highlighted = highlighted.replace("<pre>", "") highlighted = highlighted.replace("</pre>", "") highlighted = highlighted.replace("div", "pre") return highlighted except Exception as e: raise e
[ "sh84.ahn@gmail.com" ]
sh84.ahn@gmail.com
7dd1ce764affe3b286ebc77ccb89d3c8250e2bcb
e14e3c3690326ff208d5d32fe934b5004f8df629
/venv/Example/计算三角形的面积.py
428d7f5016ed09f4f8080c4f94e11e3dd17ca96e
[]
no_license
succ1984/PythonLearning
dfd2b7897ab71bcb7af55768a0f0cf859e8ad4ec
595eb63178bdf12886a4cdc0a1d3462b4a0baf79
refs/heads/master
2022-04-15T02:48:20.367390
2020-04-13T16:02:44
2020-04-13T16:02:44
255,371,180
0
0
null
null
null
null
UTF-8
Python
false
false
392
py
#!/usr/bin/env python # -*- coding:utf-8 -*- # Filename : test.py # author by : www.runoob.com a = float(input('输入三角形第一边长: ')) b = float(input('输入三角形第二边长: ')) c = float(input('输入三角形第三边长: ')) # 计算半周长 s = (a + b + c) / 2 # 计算面积 area = (s * (s - a) * (s - b) * (s - c)) ** 0.5 print('三角形面积为 %0.2f' % area)
[ "succhn@vip.qq.com" ]
succhn@vip.qq.com
93cfea989ae00a620d50b77cd1466bb4fb9b27b8
b99dbe2c1a4666f02e5c66a06fa8e4a06c132bbc
/Visualisation/MahaCovidVisualisation.py
076d10964127176badf6b8b97efbed4714e20a53
[]
no_license
trivedimilan97/Covid-Maharashtra-Web-Scraping-Data-Analysis-and-Visualisation
b0aa5411d1deee80fa48da6890ae2e2628ba371e
4a63658ac129f2ac281e0b79a183f0243c85de15
refs/heads/main
2023-02-21T15:23:56.141635
2021-01-23T15:06:55
2021-01-23T15:06:55
331,654,578
1
0
null
null
null
null
UTF-8
Python
false
false
4,145
py
#importing libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt #Plot 1 data = pd.read_csv('MahaCovid.csv') #Converts the csv data scraped from Covid India into a DataFrame ac=data.iloc[:35,4].values #ac active cases re=data.iloc[:35,2].values #re recovered de=data.iloc[:35,3].values #de deceased x=list(data.iloc[:35,0]) #District names plt.figure(figsize=(30,10)) ax=plt.axes() ax.set_facecolor('black') ax.grid(linewidth=0.4, color='#8f8f8f') plt.xticks(rotation='vertical', size='20',color='black') plt.yticks(size='20',color='black') ax.set_xlabel('\nDistrict', size=30, color='#4bb4f2') ax.set_ylabel('Total no. of cases\n', size=30, color='#4bb4f2') ax.set_title('Maharashtra district wise breakdown\n',size=50,color='#28a9ff') b_re=list(np.add(de,ac)) #plotting a stacked bar plt.bar(x,re,bottom=b_re,color='green',label="Recovered") plt.bar(x,ac, bottom =de,color='blue',label="Active") plt.bar(x,de,color='red',label="Deceased") plt.legend(fontsize=20) plt.show() #stacked bar plot showing district wise case distribution #Plot 2 plt.figure(figsize=(30,10))#more granular visualisation of the active cases ax=plt.axes() ax.set_facecolor('black') ax.grid(linewidth=0.4, color='#8f8f8f') plt.xticks(rotation='vertical', size='20',color='black') plt.yticks(size='20',color='black') ax.set_xlabel('\nDistrict', size=30, color='#4bb4f2') ax.set_ylabel('No. of active cases\n', size=30, color='#4bb4f2') ax.set_title('Maharashtra District Wise Active Cases\n', size=50,color='#28a9ff') plt.bar(x=data['District'],height=data['Active']) plt.show() #second plot showing district wise active cases #Plot 3 time_series=pd.read_csv("MahaTimeSeries.csv") #pulled the day wise data from "https://covidindia.org/open-data/" #Doc link - "https://docs.google.com/spreadsheets/d/1lgaEhEPfXiLr-88QgtBrEoE-m-lPIpKuIZS7E80EBlY/edit#gid=877650231" time_series['Date'] = pd.to_datetime(time_series['Date']) plt.figure(figsize=(30,10)) Y = time_series.iloc[0:,1].values X = list(time_series.iloc[0:,0]) ax = plt.axes() ax.grid(linewidth=0.5, color='#b8b8b8') ax.set_facecolor("black") ax.set_xlabel('\nMonth',size=30,color='#4bb4f2') ax.set_ylabel('No. of Active Cases\n',size=30,color='#4bb4f2') plt.xticks(rotation='vertical',size='20',color='black') plt.yticks(size=20,color='black') plt.title("COVID-19 Cases: Maharashtra\n",size=50,color='#28a9ff') ax.plot(X,Y,linewidth=3) plt.show() #third plot showing the rise/drop of active cases month wise for the whole state #Plot 4 time_series=pd.read_csv("MahaTimeSeries.csv") time_series['Date'] = pd.to_datetime(time_series['Date']) plt.figure(figsize=(30,10)) Y = time_series.iloc[0:,4].values X = list(time_series.iloc[0:,0]) ax = plt.axes() ax.grid(linewidth=0.5, color='#b8b8b8') ax.set_facecolor("black") ax.set_xlabel('\nMonth',size=30,color='#4bb4f2') ax.set_ylabel('Percentage\n',size=30,color='#4bb4f2') plt.xticks(rotation='vertical',size='20',color='black') plt.yticks(size=20,color='black') plt.title("COVID-19 Recovery Rate: Maharashtra\n",size=50,color='#28a9ff') ax.plot(X,Y,linewidth=3) plt.show() #fourth plot showing the increasing recovery rate by month #Plot 5 series=pd.read_csv("MahaTimeSeries.csv") series['Date'] = pd.to_datetime(series['Date']) X = list(series.iloc[0:,0]) Y = series.iloc[0:,1].values Z = series.iloc[0:,4].values fig, (ax1,ax2) = plt.subplots(2,sharex=True,figsize=(10,8),gridspec_kw={'hspace': 0 }) fig.suptitle('COVID 19 Monthly : Maharashtra',color='b',size=20) ax1.grid(linewidth=0.5, color='#b8b8b8') ax2.grid(linewidth=0.5, color='#b8b8b8') # ax1.set_facecolor("black") # ax2.set_facecolor("black") ax1.set_ylabel('No. of Active Cases\n',size=12,color='b') ax2.set_ylabel('%Recovery Rate\n',size=12,color='b') plt.xticks(rotation='vertical',size='10',color='black') ax1.plot(X, Y) ax2.plot(X, Z) plt.show()#subplot showing the inverse ratio of no. of active cases to the recovery rate
[ "noreply@github.com" ]
noreply@github.com
07455c7971c5cbf33c0d714beb2789ced4f3ae31
8b2bd04cde76a0acfbd82af78bec44d1ac6f81b2
/sift2.py
1547f02e1eaa8fcd8e89066415f44d008e35bec6
[]
no_license
zhangysh1995/ObjectDetectionKinect
e3c09984c0a416369290c49f5709624520511919
a916a009ecf41acdc9c0a7e0dae1951be4c2001b
refs/heads/master
2021-10-21T20:52:56.084820
2019-03-06T10:34:47
2019-03-06T10:34:47
116,142,929
3
0
null
null
null
null
UTF-8
Python
false
false
3,580
py
import cv2 # from find_obj import filter_matches,explore_match import numpy as np class sift_match(object): def __init__(self): pass def filter_matches(self, kp1, kp2, matches, ratio=0.75): mkp1, mkp2 = [], [] for m in matches: if len(m) == 2 and m[0].distance < m[1].distance * ratio: m = m[0] mkp1.append(kp1[m.queryIdx]) mkp2.append(kp2[m.trainIdx]) p1 = np.float32([kp.pt for kp in mkp1]) p2 = np.float32([kp.pt for kp in mkp2]) kp_pairs = zip(mkp1, mkp2) return p1, p2, kp_pairs def explore_match(self, win, img1, img2, kp_pairs, status=None, H=None): h1, w1 = img1.shape[:2] h2, w2 = img2.shape[:2] vis = np.zeros((max(h1, h2), w1 + w2), np.uint8) vis[:h1, :w1] = img1 vis[:h2, w1:w1 + w2] = img2 vis = cv2.cvtColor(vis, cv2.COLOR_GRAY2BGR) if H is not None: corners = np.float32([[0, 0], [w1, 0], [w1, h1], [0, h1]]) corners = np.int32(cv2.perspectiveTransform(corners.reshape(1, -1, 2), H).reshape(-1, 2) + (w1, 0)) cv2.polylines(vis, [corners], True, (255, 255, 255)) if status is None: status = np.ones(len(kp_pairs), np.bool) p1 = np.int32([kpp[0].pt for kpp in kp_pairs]) p2 = np.int32([kpp[1].pt for kpp in kp_pairs]) + (w1, 0) green = (0, 255, 0) red = (0, 0, 255) white = (255, 255, 255) kp_color = (51, 103, 236) match_num = 0 fail_num = 0 for (x1, y1), (x2, y2), inlier in zip(p1, p2, status): if inlier: col = green cv2.circle(vis, (x1, y1), 2, col, -1) cv2.circle(vis, (x2, y2), 2, col, -1) match_num = match_num + 1 else: col = red r = 2 thickness = 3 cv2.line(vis, (x1 - r, y1 - r), (x1 + r, y1 + r), col, thickness) cv2.line(vis, (x1 - r, y1 + r), (x1 + r, y1 - r), col, thickness) cv2.line(vis, (x2 - r, y2 - r), (x2 + r, y2 + r), col, thickness) cv2.line(vis, (x2 - r, y2 + r), (x2 + r, y2 - r), col, thickness) fail_num = fail_num + 1 vis0 = vis.copy() for (x1, y1), (x2, y2), inlier in zip(p1, p2, status): if inlier: cv2.line(vis, (x1, y1), (x2, y2), green) rate = match_num / (match_num + fail_num) # cv2.imshow(win, vis) return vis, rate def match(self, img2, img1): # img1 = cv2.imread("test.jpg") # img2 = cv2.imread("train.jpg") # # cv2.imshow("img1", img1) # cv2.imshow("img2", img2) # cv2.waitKey(0) img1_gray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY) img2_gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY) sift = cv2.SIFT() kp1, des1 = sift.detectAndCompute(img1_gray, None) kp2, des2 = sift.detectAndCompute(img2_gray, None) # BFmatcher with default parms bf = cv2.BFMatcher(cv2.NORM_L2) matches = bf.knnMatch(des1, des2, k=2) p1, p2, kp_pairs = self.filter_matches(kp1, kp2, matches, ratio=0.5) # print(len(kp_pairs)) if len(kp_pairs) == 0: return None, None else: vis, rate = self.explore_match('matches', img1_gray, img2_gray, kp_pairs) return vis, rate
[ "zhangysh1995@gmail.com" ]
zhangysh1995@gmail.com
01fc201f65a3262bb2c03edbb137f2567ead95d9
93ba95e18e51eec689114d4bed53cd3089754209
/maps/admin.py
2dbf39c88987d1adc744bf076efbb342de9e6f93
[]
no_license
ernestone/maps_django
42f5e1934830572b111f803e73191d866b59ae91
051ba90782b805139024daf3f0bbbd6a2e1fd00c
refs/heads/master
2020-05-14T18:50:51.915093
2019-09-24T23:12:57
2019-09-24T23:12:57
181,916,930
0
0
null
null
null
null
UTF-8
Python
false
false
470
py
from django.contrib.gis import admin from .models import events_centre from leaflet.admin import LeafletGeoAdmin # Register your models here. #admin.site.register(events_centre, admin.GeoModelAdmin) #admin.site.register(events_centre, admin.OSMGeoAdmin) @admin.register(events_centre) class event_centreAdmin(LeafletGeoAdmin): list_display = ['seqevent', 'seqentitat', 'idtipus', 'seqorigen', 'fecha_validez', 'seqorigen_fi'] date_hierarchy = 'fecha_validez'
[ "ernestone@gmail.com" ]
ernestone@gmail.com
8b27dfabec0874e5bd28b3055920ddb5fcdc15c9
10630887f1ec6347a7c42ecc4a8338c132bac267
/mydiary/entries/urls.py
3e0cd009ccc48bf0b51b74a68a998c7b98a12a2a
[]
no_license
Anni1123/DiaryApp
8a44fbbe4ce900c5ed9e32adabd697d2fc315aeb
88dbf7fb49e131555c9d489378c81057ee6e6551
refs/heads/master
2023-03-29T04:46:22.571571
2021-03-23T11:01:02
2021-03-23T11:01:02
285,774,093
0
0
null
null
null
null
UTF-8
Python
false
false
144
py
from django.urls import path from . import views urlpatterns = [ path('', views.index,name="home"), path('add/',views.add,name="add"), ]
[ "kumarianni1213@gmail.com" ]
kumarianni1213@gmail.com
cf778af0af1dddef7a128d1e74c241f6d5102ed0
f07a42f652f46106dee4749277d41c302e2b7406
/Data Set/bug-fixing-3/e5f4987a8fe1b2a1907436c11e0c5ae9ae6b12b3-<mandatory>-fix.py
a5a74f66992fb6dfef2b09ed691874a499fea364
[]
no_license
wsgan001/PyFPattern
e0fe06341cc5d51b3ad0fe29b84098d140ed54d1
cc347e32745f99c0cd95e79a18ddacc4574d7faa
refs/heads/main
2023-08-25T23:48:26.112133
2021-10-23T14:11:22
2021-10-23T14:11:22
null
0
0
null
null
null
null
UTF-8
Python
false
false
355
py
def mandatory(a): from jinja2.runtime import Undefined ' Make a variable mandatory ' if isinstance(a, Undefined): if (a._undefined_name is not None): name = ("'%s' " % to_text(a._undefined_name)) else: name = '' raise AnsibleFilterError(('Mandatory variable %snot defined.' % name)) return a
[ "dg1732004@smail.nju.edu.cn" ]
dg1732004@smail.nju.edu.cn
a255456d0a019eb574c9d471d675d371ed409336
c971cefa15391eb5bfc661b61791aa641089ff71
/Term 2/9/problem.py
a23dfbc6292d27e54b1f0f46a5e555232a0c0e39
[]
no_license
theseana/ajil
d8816be35b7ee56d9bc6899587b71c664a455f5f
3fcda909dae50394120c7c05d530ad905b05da0c
refs/heads/master
2023-02-23T23:28:23.529531
2021-01-26T10:07:11
2021-01-26T10:07:11
305,970,739
0
0
null
null
null
null
UTF-8
Python
false
false
43
py
# ssssssss # iiiiiiii # nnnnnnnn # aaaaaaaa
[ "info@poulstar.com" ]
info@poulstar.com
b32201fe4bcba5b5044dd43bd63144b156758276
8f5c7f28703b274163c2832f6511025e37b4295f
/helloworld.com/reviews/migrations/0001_initial.py
98cc1576bfc65b810dcb3c4f295628f97c64f0c6
[]
no_license
reinaaa05/portfolio
159dc4d48b3e215bfb6c7115cd39b7f63ee2418a
e93189e3aa027e57bac490d8874519dd7f717620
refs/heads/main
2023-05-15T09:56:30.741402
2021-06-12T13:46:44
2021-06-12T13:46:44
307,375,148
0
0
null
null
null
null
UTF-8
Python
false
false
1,024
py
# Generated by Django 3.1.7 on 2021-03-19 05:50 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='ReviewsConfig', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('store_name', models.CharField(max_length=255, verbose_name='店名')), ('title', models.CharField(max_length=255, verbose_name='タイトル')), ('text', models.TextField(blank=True, verbose_name='口コミテキスト')), ('stars', models.IntegerField(choices=[(1, '☆'), (2, '☆☆'), (3, '☆☆☆'), (4, '☆☆☆☆'), (5, '☆☆☆☆☆')], verbose_name='星の数')), ('created_at', models.DateTimeField(default=django.utils.timezone.now, verbose_name='作成日')), ], ), ]
[ "Reinaaa0555@gmail.com" ]
Reinaaa0555@gmail.com
d672d92fcd9d2770b069e63d30f25774575f0e1b
0f6a0a53fbab0092272f59e5d2f49c9b492c3b25
/Week 08/id_668/leetcode_387_668.py
6f119e75257f4774a4efadc4fe33fb99019553bc
[]
no_license
HaoWangCold/algorithm004-03
662f5d3512c94b81305eab43277c1d0cfdbd1bed
b03f841ed18190c9b42997998de839731a98cc88
refs/heads/master
2020-08-07T19:55:51.769325
2019-12-11T05:09:10
2019-12-11T05:09:10
213,571,366
1
0
null
2019-12-11T05:00:46
2019-10-08T07:04:21
Java
UTF-8
Python
false
false
809
py
#!/usr/bin/env python # -*- coding:utf-8 -*- """ @file: 387_first_unique_character_in_a_string.py @time: 2019/12/5 11:04 """ class Solution(object): """ 给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。 案例: s = "leetcode" 返回 0. s = "loveleetcode", 返回 2. 注意事项:您可以假定该字符串只包含小写字母。 """ def first_uniq_char(self, s): """ :type s: str :rtype: int """ counter = [0] * 26 for e in s: counter[ord(e) - ord('a')] += 1 for i in range(len(s)): if counter[ord(s[i]) - ord('a')] == 1: return i return -1
[ "noreply@github.com" ]
noreply@github.com
aec91a9ce7f35dfa47aaf32a2ca1c5960d6a0f98
fbf82e9a3d6e7b4dbaa2771eed0d96efabc87b3b
/platform/storage/storage/ceph/ceph/manager/cephmon_manager.py
1a1d68c8581d61a22a5d18d91845d4a99f3ac9e9
[]
no_license
woshidashayuchi/boxlinker-all
71603066fee41988108d8e6c803264bd5f1552bc
318f85e6ff5542cd70b7a127c0b1d77a01fdf5e3
refs/heads/master
2021-05-09T03:29:30.652065
2018-01-28T09:17:18
2018-01-28T09:17:18
119,243,814
1
0
null
null
null
null
UTF-8
Python
false
false
12,801
py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Author: YanHua <it-yanh@all-reach.com> import uuid from common.logs import logging as log from common.code import request_result from ceph.driver import ceph_driver class CephMonManager(object): def __init__(self): self.ceph_driver = ceph_driver.CephDriver() def cephmon_init(self, cluster_info, mon01_hostip, mon01_rootpwd, mon01_snic, mon02_hostip, mon02_rootpwd, mon02_snic): host_ssh_conf = self.ceph_driver.host_ssh_conf( mon01_hostip, mon01_rootpwd) if host_ssh_conf != 0: if host_ssh_conf == 1: log.warning('mon节点(%s)密码错误' % (mon01_hostip)) return request_result(523) elif host_ssh_conf == 2: log.warning('mon节点(%s)连接超时' % (mon01_hostip)) return request_result(522) else: log.warning('mon节点(%s)连接错误' % (mon01_hostip)) return request_result(601) host_ssh_conf = self.ceph_driver.host_ssh_conf( mon02_hostip, mon02_rootpwd) if host_ssh_conf != 0: if host_ssh_conf == 1: log.warning('mon节点(%s)密码错误' % (mon01_hostip)) return request_result(523) elif host_ssh_conf == 2: log.warning('mon节点(%s)连接超时' % (mon01_hostip)) return request_result(522) else: log.warning('mon节点(%s)连接错误' % (mon01_hostip)) return request_result(601) mon01_hostname = self.ceph_driver.remote_host_name(mon01_hostip) if not mon01_hostname: log.error('无法获取节点(%s)主机名' % (mon01_hostip)) return request_result(524) mon02_hostname = self.ceph_driver.remote_host_name(mon02_hostip) if not mon02_hostname: log.error('无法获取节点(%s)主机名' % (mon02_hostip)) return request_result(524) mon01_storage_ip = self.ceph_driver.storage_ip( mon01_hostip, mon01_snic) if not mon01_storage_ip: log.error('无法获取节点(%s)存储IP' % (mon01_hostip)) return request_result(524) mon02_storage_ip = self.ceph_driver.storage_ip( mon02_hostip, mon02_snic) if not mon02_storage_ip: log.error('无法获取节点(%s)存储IP' % (mon02_hostip)) return request_result(524) if cluster_info: cluster_uuid = cluster_info.get('cluster_uuid') cluster_name = cluster_info.get('cluster_name') cluster_auth = cluster_info.get('cluster_auth') service_auth = cluster_info.get('service_auth') client_auth = cluster_info.get('client_auth') ceph_pgnum = cluster_info.get('ceph_pgnum') ceph_pgpnum = cluster_info.get('ceph_pgpnum') public_network = cluster_info.get('public_network') cluster_network = cluster_info.get('cluster_network') osd_full_ratio = cluster_info.get('osd_full_ratio') osd_nearfull_ratio = cluster_info.get('osd_nearfull_ratio') journal_size = cluster_info.get('journal_size') ntp_server = cluster_info.get('ntp_server') else: cluster_uuid = str(uuid.uuid4()) cluster_auth = 'none' service_auth = 'none' client_auth = 'none' ceph_pgnum = 300 ceph_pgpnum = 300 public_network = '192.168.1.0/24' cluster_network = '10.10.1.0/24' osd_full_ratio = '.85' osd_nearfull_ratio = '.70' journal_size = 5000 ntp_server = 'time.nist.gov' self.ceph_driver.ceph_conf_init( cluster_uuid, cluster_auth, service_auth, client_auth, ceph_pgnum, ceph_pgpnum, public_network, cluster_network, osd_full_ratio, osd_nearfull_ratio, journal_size) self.ceph_driver.mon_conf_update( cluster_uuid, '1', mon01_hostname, mon01_storage_ip) self.ceph_driver.mon_conf_update( cluster_uuid, '2', mon02_hostname, mon02_storage_ip) mon01_conf_dist = self.ceph_driver.conf_dist( cluster_uuid, mon01_hostip) if int(mon01_conf_dist) != 0: log.error('mon节点(主机名:%s, IP:%s)ceph配置文件分发失败' % (mon01_hostname, mon01_hostip)) return request_result(525) mon02_conf_dist = self.ceph_driver.conf_dist( cluster_uuid, mon02_hostip) if int(mon02_conf_dist) != 0: log.error('mon节点(主机名:%s, IP:%s)ceph配置文件分发失败' % (mon02_hostname, mon02_hostip)) return request_result(525) ntp01_conf = self.ceph_driver.host_ntp_conf( mon01_hostip, ntp_server) if int(ntp01_conf) != 0: log.error('Host ntp server conf failure, ' 'host_ip=%s, ntp_server=%s' % (mon01_hostip, ntp_server)) return request_result(526) ntp02_conf = self.ceph_driver.host_ntp_conf( mon02_hostip, ntp_server) if int(ntp02_conf) != 0: log.error('Host ntp server conf failure, ' 'host_ip=%s, ntp_server=%s' % (mon02_hostip, ntp_server)) return request_result(526) mon01_ceph_install = self.ceph_driver.ceph_service_install( mon01_hostip, cluster_uuid) if int(mon01_ceph_install) != 0: log.error('Ceph service install failure, mon_host_ip=%s' % (mon01_hostip)) return request_result(526) mon02_ceph_install = self.ceph_driver.ceph_service_install( mon02_hostip, cluster_uuid) if int(mon02_ceph_install) != 0: log.error('Ceph service install failure, mon_host_ip=%s' % (mon02_hostip)) return request_result(526) monmap_init = self.ceph_driver.monmap_init( mon01_hostname, mon01_storage_ip, mon02_hostname, mon02_storage_ip, mon01_hostip, cluster_uuid) if int(monmap_init) != 0: log.error('Ceph monmap init failure') return request_result(526) monmap_sync = self.ceph_driver.monmap_sync( mon01_hostip, mon02_hostip) if int(monmap_sync) != 0: log.error('Ceph monmap sync failure') return request_result(526) mon01_init = self.ceph_driver.mon_host_init( mon01_hostname, mon01_hostip) if int(mon01_init) != 0: log.error('mon节点(主机名:%s,IP:%s)初始化失败' % (mon01_hostname, mon01_hostip)) return request_result(526) mon02_init = self.ceph_driver.mon_host_init( mon02_hostname, mon02_hostip) if int(mon02_init) != 0: log.error('mon节点(主机名:%s,IP:%s)初始化失败' % (mon02_hostname, mon02_hostip)) return request_result(526) crush_ssd_add = self.ceph_driver.crush_ssd_add(mon01_hostip) if int(crush_ssd_add) != 0: log.error('创建ssd bucket失败') return request_result(526) control_host_name = self.ceph_driver.local_host_name() self.ceph_driver.host_ssh_del(mon01_hostip, control_host_name) self.ceph_driver.host_ssh_del(mon02_hostip, control_host_name) result = { "mon01_hostip": mon01_hostip, "mon02_hostip": mon02_hostip, "mon01_hostname": mon01_hostname, "mon02_hostname": mon02_hostname, "cluster_uuid": cluster_uuid, "mon01_storage_ip": mon01_storage_ip, "mon02_storage_ip": mon02_storage_ip } return request_result(0, result) def cephmon_add(self, cluster_info, mon_id, host_ip, rootpwd, storage_nic, mon_list): host_ssh_conf = self.ceph_driver.host_ssh_conf( host_ip, rootpwd) if host_ssh_conf != 0: if host_ssh_conf == 1: log.warning('mon节点(%s)密码错误' % (mon01_hostip)) return request_result(523) elif host_ssh_conf == 2: log.warning('mon节点(%s)连接超时' % (mon01_hostip)) return request_result(522) else: log.warning('mon节点(%s)连接错误' % (mon01_hostip)) return request_result(601) host_name = self.ceph_driver.remote_host_name(host_ip) if not host_name: log.error('无法获取节点(%s)主机名' % (host_ip)) return request_result(524) storage_ip = self.ceph_driver.storage_ip( host_ip, storage_nic) if not storage_ip: log.error('无法获取节点(%s)存储IP' % (host_ip)) return request_result(524) if cluster_info: cluster_uuid = cluster_info.get('cluster_uuid') cluster_name = cluster_info.get('cluster_name') cluster_auth = cluster_info.get('cluster_auth') service_auth = cluster_info.get('service_auth') client_auth = cluster_info.get('client_auth') ceph_pgnum = cluster_info.get('ceph_pgnum') ceph_pgpnum = cluster_info.get('ceph_pgpnum') public_network = cluster_info.get('public_network') cluster_network = cluster_info.get('cluster_network') osd_full_ratio = cluster_info.get('osd_full_ratio') osd_nearfull_ratio = cluster_info.get('osd_nearfull_ratio') journal_size = cluster_info.get('journal_size') ntp_server = cluster_info.get('ntp_server') else: log.warning('Ceph cluster info not exists') return request_result(528) if not self.ceph_driver.ceph_conf_check(cluster_uuid): self.ceph_driver.ceph_conf_init( cluster_uuid, cluster_auth, service_auth, client_auth, ceph_pgnum, ceph_pgpnum, public_network, cluster_network, osd_full_ratio, osd_nearfull_ratio, journal_size) for mon_info in mon_list: ceph_mon_id = mon_info[0] mon_host_name = mon_info[1] mon_storage_ip = mon_info[2] self.ceph_driver.mon_conf_update( cluster_uuid, ceph_mon_id[-1], mon_host_name, mon_storage_ip) self.ceph_driver.mon_conf_update( cluster_uuid, mon_id[-1], host_name, storage_ip) mon_conf_dist = self.ceph_driver.conf_dist(cluster_uuid, host_ip) if int(mon_conf_dist) != 0: log.error('mon节点(主机名:%s, IP:%s)ceph配置文件分发失败' % (host_name, host_ip)) return request_result(525) ntp_conf = self.ceph_driver.host_ntp_conf( host_ip, ntp_server) if int(ntp_conf) != 0: log.error('Host ntp server conf failure, ' 'host_ip=%s, ntp_server=%s' % (host_ip, ntp_server)) return request_result(526) mon_ceph_install = self.ceph_driver.ceph_service_install( host_ip, cluster_uuid) if int(mon_ceph_install) != 0: log.error('Ceph service install failure, mon_host_ip=%s' % (host_ip)) return request_result(526) mon_add = self.ceph_driver.mon_host_add( host_name, host_ip, storage_ip) if int(mon_add) != 0: log.error('mon节点(主机名:%s,IP:%s)添加失败' % (host_name, host_ip)) return request_result(526) control_host_name = self.ceph_driver.local_host_name() self.ceph_driver.host_ssh_del(host_ip, control_host_name) result = { "host_ip": host_ip, "host_name": host_name, "cluster_uuid": cluster_uuid, "storage_ip": storage_ip } return request_result(0, result)
[ "359876749@qq.com" ]
359876749@qq.com
f845123ddf4a90c5080f4bd640f47010d786bac5
61ada335c336101f5550280cb5a0ff0eca29f90a
/chapter4/bst_sequence.py
33dcb9826e7a835b52e67b6b64f46a0b7d0af50d
[]
no_license
WesleyT4N/CTCI
0a083e34c4d7102eb5f39b484a8b4f9b3cc3b259
3b4751e43626120cb3e6891c0a864677f8237b59
refs/heads/master
2020-03-25T07:17:43.127459
2019-01-11T04:51:10
2019-01-11T04:51:10
143,552,731
0
0
null
null
null
null
UTF-8
Python
false
false
820
py
def weave(first, second, results, prefix): if len(first) == 0 or len(second) == 0: result = prefix results += result + first + second head_first = first.pop(0) prefix.append(head_first) weave(first, second, results, prefix) prefix.pop() first.insert(0, head_first) head_second = second.pop(0) prefix.append(head_second) weave(first, second, results, prefix) prefix.pop() second.insert(0, head_second) def bst_sequence(root): result = [] if root is None: return result prefix = [root.data] left = bst_sequence(root.left) right = bst_sequence(root.right) for l_seq in left: for r_seq in right: weaved = [] weave_lists(left, right, weaved, prefix) result += weaved return result
[ "wesleyt1998@gmail.com" ]
wesleyt1998@gmail.com
afc502fd894e0319fb56f6217f21a3b934829d0c
e4045e99ae5395ce5369a1374a20eae38fd5179b
/db/add_emp.py
07ba831ed9d733fb43393f8841ade51ce422921f
[]
no_license
srikanthpragada/09_MAR_2018_PYTHON_DEMO
74fdb54004ab82b62f68c9190fe868f3c2961ec0
8684137c77d04701f226e1e2741a7faf9eeef086
refs/heads/master
2021-09-11T15:52:17.715078
2018-04-09T15:29:16
2018-04-09T15:29:16
124,910,054
0
1
null
null
null
null
UTF-8
Python
false
false
539
py
import sqlite3 try: con = sqlite3.connect(r"e:\classroom\python\hr.db") cur = con.cursor() # take input from user ename = input("Enter name :") salary = input("Enter salary : ") dept = input("Enter dept id :") # get next emp id cur.execute("select max(empid) + 1 from emp") empid = cur.fetchone()[0] cur.execute("insert into emp values(?,?,?,?)", (empid, ename, salary, dept)) con.commit() print("Added Employee") except Exception as ex: print("Error : ", ex) finally: con.close()
[ "srikanthpragada@gmail.com" ]
srikanthpragada@gmail.com
35f8d03aeb920c25f794dccf14d28d00a16dc8a5
6d6fb9b30dc5856bbfec6b7a8877494709ed0d5d
/cap6/ex_143.py
130520a5b258fdc5c1b4d66c0070001fcc105d4f
[]
no_license
ignaziocapuano/workbook_ex
2b5b644d5d4d1940c871f9083764413671482213
ff6d2625e46a2f17af804105f4e88cf8772a39a3
refs/heads/main
2023-01-04T20:28:08.956999
2020-11-02T07:48:18
2020-11-02T07:48:18
304,552,342
0
0
null
null
null
null
UTF-8
Python
false
false
698
py
#Anagrams string1=input("Inserisci prima parola: ") string2=input("Inserisci seconda parola: ") if len(string1)!=len(string2): print("Parole di lunghezza diversa") quit() elif string1==string2: print("Parole uguali") count1={} count2={} for i in range(len(string1)): if string1[i] in count1: count1[string1[i]]+=1 else: count1[string1[i]]=1 for i in range(len(string2)): if string2[i] in count2: count2[string2[i]]+=1 else: count2[string2[i]]=1 isAnagram=True for key in count1: if key in count2.keys() or count1[key]==count2[key]: pass else: isAnagram=False if isAnagram: print("Le parole sono anagrammi")
[ "72966219+ignaziocapuano@users.noreply.github.com" ]
72966219+ignaziocapuano@users.noreply.github.com
4ba863c2665be91eec065ed4c30766c4093d1eee
ce61d882ab402283c60580cd6b99ac74eb6e3644
/sixdegrees/random_geometric_api.py
21de8f64714697adfd352a786159f4126ce9aec3
[ "MIT" ]
permissive
benmaier/sixdegrees
f4a6c54cce8021cc4f55a832fbe629e8e22b0cb2
6fee5a4f81d91ec2ce92c8767add67b701651a85
refs/heads/master
2022-12-11T00:10:42.210563
2020-09-15T21:58:18
2020-09-15T21:58:18
216,598,531
0
1
null
null
null
null
UTF-8
Python
false
false
22,459
py
# -*- coding: utf-8 -*- """ This module provides convenient wrapper functions for the C++-functions sampling from all random geometric small-world network models. """ import numpy as np from _sixdegrees import ( _random_geometric_small_world_network_coord_lists, _random_geometric_small_world_network, _random_geometric_kleinberg_network_coord_lists, _random_geometric_kleinberg_network, _twoD_random_geometric_kleinberg_network_coord_lists, _twoD_random_geometric_kleinberg_network, ) from sixdegrees.kleinberg_helper_functions import ( get_distance_connection_probability_parameters, get_continuous_distance_connection_probability_parameters, ) def random_geometric_kleinberg_network(N, k, mu, use_largest_component=False, delete_non_largest_component_nodes=True, seed=0, return_positions=False, ): r""" Generate a Kleinberg small-world network from nodes that are uniformly i.i.d. on a ring. Parameters ========== N : int Number of nodes. k : float Mean degree. mu : float Structural control parameter. use_largest_component : bool, default = False Whether or not to only return the largest connected component of size :math:`N_g\leq N`. delete_non_largest_component_nodes : bool, default = True If only the largest connected component is returned, relabel the nodes to be indexed from zero to :math:`N_g`. seed : int, default = 0 The seed with which to generate this network. Choose ``0`` for random initialization. return_positions : bool, default = False Whether or not to return the node positions on the ring. Returns ======= N : int Number of nodes in the generated network (can be smaller than the demanded number of nodes if only the largest connected component is returned) edges : list of tuple of int A list of node index pairs that constitute the edges of the generated network. X : numpy.ndarray Node positions on the ring. Is only returned if ``return_positions = True`` was set. Example ======= >>> N, edges = random_geometric_kleinberg_network(N=512,k=7,mu=-0.5) >>> print(N) 512 """ X = np.random.rand(N) * N # positions do not need to be sorted necessarily # but it helps knowing that 0, 1, 2,... are # the first, second, third ... nodes in # the interval [0,N] X.sort() _N, _edges = _random_geometric_kleinberg_network( N, k, mu, X.tolist(), use_largest_component=use_largest_component, delete_non_largest_component_nodes=delete_non_largest_component_nodes, seed=seed ) if return_positions: return _N, _edges, X else: return _N, _edges def twoD_random_geometric_kleinberg_network( N, k, mu, periodic_boundary_conditions=True, use_largest_component=False, delete_non_largest_component_nodes=True, seed=0, epsilon=1e-9, return_positions=False, use_continuous_connection_probability=False, X=None, Y=None, ): r""" Generate a Kleinberg small-world network from nodes that are uniformly i.i.d. on a square. Parameters ========== N : int Number of nodes. k : float Mean degree. mu : float Structural control parameter. periodic_boundary_conditions : bool, default = True Whether or not to apply periodic boundary conditions (2-torus). use_largest_component : bool, default = False Whether or not to only return the largest connected component of size :math:`N_g\leq N`. delete_non_largest_component_nodes : bool, default = True If only the largest connected component is returned, relabel the nodes to be indexed from zero to :math:`N_g`. seed : int, default = 0 The seed with which to generate this network. Choose ``0`` for random initialization. epsilon : float, default = 1e-9 Minimal distance below which node pairs are always connected. return_positions : bool, default = False Whether or not to return the node positions on the ring. use_continuous_connection_probability : bool, default = False Excess connection probability can be redistributed to the whole ensemble or to nearest neighbors. If this flag is true, the excess probability will be redistributed to the whole ensemble. X : numpy.ndarray, default = None Node positions in x-direction (:math:`x \in [0,1)`). Y : numpy.ndarray, default = None Node positions in y-direction (:math:`x \in [0,1)`). Returns ======= N : int Number of nodes in the generated network (can be smaller than the demanded number of nodes if only the largest connected component is returned) edges : list of tuple of int A list of node index pairs that constitute the edges of the generated network. X : numpy.ndarray Node positions on the ring. Is only returned if ``return_positions = True`` was set. Y : numpy.ndarray Node positions on the ring. Is only returned if ``return_positions = True`` was set. """ if X is None: X = np.random.rand(N) if Y is None: Y = np.random.rand(N) kappa = mu-2 if not use_continuous_connection_probability: C, rmin = get_distance_connection_probability_parameters( N, k, kappa, epsilon=epsilon, use_periodic_boundary_conditions=periodic_boundary_conditions, ) else: C, rmin = get_continuous_distance_connection_probability_parameters( N, k, kappa, epsilon=epsilon, use_periodic_boundary_conditions=periodic_boundary_conditions, ) _N, _edges = _twoD_random_geometric_kleinberg_network( N, C, rmin, kappa, X.tolist(), Y.tolist(), periodic_boundary_conditions=periodic_boundary_conditions, use_largest_component=use_largest_component, delete_non_largest_component_nodes=delete_non_largest_component_nodes, seed=seed ) if return_positions: return _N, _edges, X, Y else: return _N, _edges def random_geometric_small_world_network(N, k, mu, use_largest_component=False, delete_non_largest_component_nodes=True, seed=0, return_positions=False, ): r""" Generate a small-world network from nodes that are uniformly i.i.d. on a ring. Parameters ========== N : int Number of nodes. k : float Mean degree. mu : float Structural control parameter. use_largest_component : bool, default = False Whether or not to only return the largest connected component of size :math:`N_g\leq N`. delete_non_largest_component_nodes : bool, default = True If only the largest connected component is returned, relabel the nodes to be indexed from zero to :math:`N_g`. seed : int, default = 0 The seed with which to generate this network. Choose ``0`` for random initialization. return_positions : bool, default = False Whether or not to return the node positions on the ring. Returns ======= N : int Number of nodes in the generated network (can be smaller than the demanded number of nodes if only the largest connected component is returned) edges : list of tuple of int A list of node index pairs that constitute the edges of the generated network. X : numpy.ndarray Node positions on the ring. Is only returned if ``return_positions = True`` was set. """ beta = k /(N-1-k) * ((N-1-k)/k)**mu beta = k /(N-1-k) * ((N-1-k)/k)**mu X = np.random.rand(N) * N # positions do not need to be sorted necessarily # but it helps knowing that 0, 1, 2,... are # the first, second, third ... nodes in # the interval [0,N] X.sort() _N, _edges = _random_geometric_small_world_network( N, k, beta, X.tolist(), use_largest_component=use_largest_component, delete_non_largest_component_nodes=delete_non_largest_component_nodes, seed=seed ) if return_positions: return _N, _edges, X else: return _N, _edges def random_geometric_kleinberg_network_coord_lists( N, k, mu, use_largest_component=False, delete_non_largest_component_nodes=True, seed=0, return_positions=False, ): r""" Generate a Kleinberg small-world network from nodes that are uniformly i.i.d. on a ring. Parameters ========== N : int Number of nodes. k : float Mean degree. mu : float Structural control parameter. use_largest_component : bool, default = False Whether or not to only return the largest connected component of size :math:`N_g\leq N`. delete_non_largest_component_nodes : bool, default = True If only the largest connected component is returned, relabel the nodes to be indexed from zero to :math:`N_g`. seed : int, default = 0 The seed with which to generate this network. Choose ``0`` for random initialization. return_positions : bool, default = False Whether or not to return the node positions on the ring. Returns ======= N : int Number of nodes in the generated network (can be smaller than the demanded number of nodes if only the largest connected component is returned) row : list of int Row coordinates of non-zero entries in the generated adjacency matrix col : list of int Column coordinates of non-zero entries in the generated adjacency matrix X : numpy.ndarray Node positions on the ring. Is only returned if ``return_positions = True`` was set. """ X = np.random.rand(N) * N # positions do not need to be sorted necessarily # but it helps knowing that 0, 1, 2,... are # the first, second, third ... nodes in # the interval [0,N] X.sort() _N, row, col = _random_geometric_kleinberg_network_coord_lists( N, k, mu, X.tolist(), use_largest_component=use_largest_component, delete_non_largest_component_nodes=delete_non_largest_component_nodes, seed=seed ) if return_positions: return _N, row, col, X else: return _N, row, col def random_geometric_small_world_network_coord_lists( N, k, mu, use_largest_component=False, delete_non_largest_component_nodes=True, seed=0, return_positions=False, ): r""" Generate a small-world network from nodes that are uniformly i.i.d. on a ring. Parameters ========== N : int Number of nodes. k : float Mean degree. mu : float Structural control parameter. use_largest_component : bool, default = False Whether or not to only return the largest connected component of size :math:`N_g\leq N`. delete_non_largest_component_nodes : bool, default = True If only the largest connected component is returned, relabel the nodes to be indexed from zero to :math:`N_g`. seed : int, default = 0 The seed with which to generate this network. Choose ``0`` for random initialization. return_positions : bool, default = False Whether or not to return the node positions on the ring. Returns ======= N : int Number of nodes in the generated network (can be smaller than the demanded number of nodes if only the largest connected component is returned) row : list of int Row coordinates of non-zero entries in the generated adjacency matrix col : list of int Column coordinates of non-zero entries in the generated adjacency matrix X : numpy.ndarray Node positions on the ring. Is only returned if ``return_positions = True`` was set. """ beta = k /(N-1-k) * ((N-1-k)/k)**mu X = np.random.rand(N) * N # positions do not need to be sorted necessarily # but it helps knowing that 0, 1, 2,... are # the first, second, third ... nodes in # the interval [0,N] X.sort() _N, row, col = _random_geometric_small_world_network_coord_lists( N, k, beta, X.tolist(), use_largest_component=use_largest_component, delete_non_largest_component_nodes=delete_non_largest_component_nodes, seed=seed ) if return_positions: return _N, row, col, X else: return _N, row, col def twoD_random_geometric_kleinberg_network_coord_lists( N, k, mu, periodic_boundary_conditions=True, use_largest_component=False, delete_non_largest_component_nodes=True, seed=0, epsilon=1e-9, return_positions=False, use_continuous_connection_probability=False, X = None, Y = None, ): r""" Generate a Kleinberg (power-law) small-world network from nodes that are uniformly i.i.d. on a square. Parameters ========== N : int Number of nodes. k : float Mean degree. mu : float Structural control parameter. periodic_boundary_conditions : bool, default = True Whether or not to apply periodic boundary conditions (2-torus). use_largest_component : bool, default = False Whether or not to only return the largest connected component of size :math:`N_g\leq N`. delete_non_largest_component_nodes : bool, default = True If only the largest connected component is returned, relabel the nodes to be indexed from zero to :math:`N_g`. seed : int, default = 0 The seed with which to generate this network. Choose ``0`` for random initialization. epsilon : float, default = 1e-9 Minimal distance below which node pairs are always connected. return_positions : bool, default = False Whether or not to return the node positions on the ring. use_continuous_connection_probability : bool, default = False Excess connection probability can be redistributed to the whole ensemble or to nearest neighbors. If this flag is true, the excess probability will be redistributed to the whole ensemble. X : numpy.ndarray, default = None Node positions in x-direction (:math:`x \in [0,1)`). Y : numpy.ndarray, default = None Node positions in y-direction (:math:`x \in [0,1)`). Returns ======= N : int Number of nodes in the generated network (can be smaller than the demanded number of nodes if only the largest connected component is returned) row : list of int Row coordinates of non-zero entries in the generated adjacency matrix col : list of int Column coordinates of non-zero entries in the generated adjacency matrix X : numpy.ndarray Node positions on the ring. Is only returned if ``return_positions = True`` was set. Y : numpy.ndarray Node positions on the ring. Is only returned if ``return_positions = True`` was set. """ if X is None: X = np.random.rand(N) if Y is None: Y = np.random.rand(N) kappa = mu-2 if not use_continuous_connection_probability: C, rmin = get_distance_connection_probability_parameters( N, k, kappa, epsilon=epsilon, use_periodic_boundary_conditions=periodic_boundary_conditions, ) else: C, rmin = get_continuous_distance_connection_probability_parameters( N, k, kappa, epsilon=epsilon, use_periodic_boundary_conditions=periodic_boundary_conditions, ) _N, row, col = _twoD_random_geometric_kleinberg_network_coord_lists( N, C, rmin, kappa, X.tolist(), Y.tolist(), periodic_boundary_conditions=periodic_boundary_conditions, use_largest_component=use_largest_component, delete_non_largest_component_nodes=delete_non_largest_component_nodes, seed=seed ) if return_positions: return _N, row, col, X, Y else: return _N, row, col if __name__=="__main__": import matplotlib.pyplot as pl N = 401 k = 30 mu = -1 kappa = 2*(mu-1) _, edges = twoD_random_geometric_kleinberg_network(N,k,mu,periodic_boundary_conditions=False,use_continuous_connection_probability=True) print(2*len(edges)/N, k) C, rmin = get_continuous_distance_connection_probability_parameters( N, k, 2*(mu-1), epsilon=1e-9, use_periodic_boundary_conditions=False ) def P(r, C, rmin, kappa): if r < rmin: return 1 else: return C * r**kappa r = np.linspace(0,1,10000) Ps = [P(_r,C,rmin, kappa) for _r in r] pl.plot(r, Ps) #pl.xscale('log') #pl.yscale('log') pl.show() #print(edges)
[ "benjaminfrankmaier@gmail.com" ]
benjaminfrankmaier@gmail.com
21122806780db4ca9eaa3c3dce798f3d25d1200d
724ed0cf0bc207c9f106ce74ca03984247a8dab3
/test/test_app1.py
2c739334f3684e06566a8e3cbf5929be385cd326
[]
no_license
mengjiao718/ww_api
38166762d58ecc5e880a8c22a42727e5aa1af1c8
c61a2956dd2bfe225e9c85ba608f40ce87128748
refs/heads/master
2021-05-24T04:21:24.701332
2016-08-26T19:16:01
2016-08-26T19:16:01
65,039,534
0
1
null
2020-07-23T12:45:14
2016-08-05T18:13:07
Python
UTF-8
Python
false
false
3,387
py
#!flask/bin/python from flask import Flask, jsonify, abort, request, make_response, url_for from flask.ext.httpauth import HTTPBasicAuth app = Flask(__name__, static_url_path = "") auth = HTTPBasicAuth() @auth.get_password def get_password(username): if username == 'miguel': return 'python' return None @auth.error_handler def unauthorized(): return make_response(jsonify( { 'error': 'Unauthorized access' } ), 403) # return 403 instead of 401 to prevent browsers from displaying the default auth dialog @app.errorhandler(400) def not_found(error): return make_response(jsonify( { 'error': 'Bad request' } ), 400) @app.errorhandler(404) def not_found(error): return make_response(jsonify( { 'error': 'Not found' } ), 404) tasks = [ { 'id': 1, 'title': u'Buy groceries', 'description': u'Milk, Cheese, Pizza, Fruit, Tylenol', 'done': False }, { 'id': 2, 'title': u'Learn Python', 'description': u'Need to find a good Python tutorial on the web', 'done': False } ] def make_public_task(task): new_task = {} for field in task: if field == 'id': new_task['uri'] = url_for('get_task', task_id = task['id'], _external = True) else: new_task[field] = task[field] return new_task @app.route('/todo/api/v1.0/tasks', methods = ['GET']) @auth.login_required def get_tasks(): return jsonify( { 'tasks': map(make_public_task, tasks) } ) @app.route('/todo/api/v1.0/tasks/<int:task_id>', methods = ['GET']) @auth.login_required def get_task(task_id): task = filter(lambda t: t['id'] == task_id, tasks) if len(task) == 0: abort(404) return jsonify( { 'task': make_public_task(task[0]) } ) @app.route('/todo/api/v1.0/tasks', methods = ['POST']) @auth.login_required def create_task(): if not request.json or not 'title' in request.json: abort(400) task = { 'id': tasks[-1]['id'] + 1, 'title': request.json['title'], 'description': request.json.get('description', ""), 'done': False } tasks.append(task) return jsonify( { 'task': make_public_task(task) } ), 201 @app.route('/todo/api/v1.0/tasks/<int:task_id>', methods = ['PUT']) @auth.login_required def update_task(task_id): task = filter(lambda t: t['id'] == task_id, tasks) if len(task) == 0: abort(404) if not request.json: abort(400) if 'title' in request.json and type(request.json['title']) != unicode: abort(400) if 'description' in request.json and type(request.json['description']) is not unicode: abort(400) if 'done' in request.json and type(request.json['done']) is not bool: abort(400) task[0]['title'] = request.json.get('title', task[0]['title']) task[0]['description'] = request.json.get('description', task[0]['description']) task[0]['done'] = request.json.get('done', task[0]['done']) return jsonify( { 'task': make_public_task(task[0]) } ) @app.route('/todo/api/v1.0/tasks/<int:task_id>', methods = ['DELETE']) @auth.login_required def delete_task(task_id): task = filter(lambda t: t['id'] == task_id, tasks) if len(task) == 0: abort(404) tasks.remove(task[0]) return jsonify( { 'result': True } ) if __name__ == '__main__': app.run(debug = True)
[ "mengjiao.zhang@issuerdirect.com" ]
mengjiao.zhang@issuerdirect.com
0f0fa09b4da7bdac7b101b28a117b9782fe16b70
6fae09c2b851c47c21157e371a0a38dbbcd3ca74
/venv/bin/chardetect
ea64b7535a3ef539901282b44e1fdc581324a37f
[]
no_license
bopopescu/sistemaMonitoreo
50a4c05bace2be8a691130d2026d2e51d332a008
c2328afd613864dc4ba1f296946fecf8c7e22843
refs/heads/master
2022-11-19T16:18:22.247779
2019-01-27T20:49:40
2019-01-27T20:49:40
282,366,646
0
0
null
2020-07-25T03:59:20
2020-07-25T03:59:19
null
UTF-8
Python
false
false
290
#!/Users/gnunez/eclipse-workspace/sistemaMonitoreo/sistemaMonitoreo/venv/bin/python # -*- coding: utf-8 -*- import re import sys from chardet.cli.chardetect import main if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit(main())
[ "guillermo.nunez@gnp.com.mx" ]
guillermo.nunez@gnp.com.mx
da61b563cf512ba2c1ce1858d3cfd0c17efe86de
0ebdbcdd072a67c8115082c97d7b838f640b885b
/bot_teleg_control.py
4ff20bdcdd18100f5a4f9243e3d9ecdedc8d71f0
[]
no_license
Dini4ka/insta_post_bot
75e68fc924b723fd3336c1bf4e29a91422f962d9
365f8e0177cc647d069780666595d8880a7634a3
refs/heads/main
2023-02-18T01:49:23.164824
2021-01-14T17:34:34
2021-01-14T17:34:34
329,082,816
0
0
null
null
null
null
UTF-8
Python
false
false
4,406
py
import time import sys, traceback import datetime from aiogram import Bot, Dispatcher, types from aiogram.contrib.fsm_storage.memory import MemoryStorage from insta_post_bot import instabot, BOT from mouse_coordinates import getting_coordinates from connect_to_google_disk import check_new_files from aiogram.utils import executor bot = Bot(token='1584254213:AAGr7iEilj9n_afn0Bplu_ASVJKbanS2mVc') storage = MemoryStorage() dp = Dispatcher(bot, storage=storage) # Начинаем наш диалог @dp.message_handler(commands=['start']) async def cmd_start(message: types.Message): await message.reply("Hello! First of all we should make some settings.\nType /get_coordinates for start settings") @dp.message_handler(commands=['get_coordinates']) async def cmd_start(message: types.Message): await message.answer('wait a little bit, untill u see opend folder') BOT.set_up() BOT.go_home() await message.answer('please put ur cursor on the field for writing \n and write me /get_cursor_coordinates_field') @dp.message_handler(commands=['get_cursor_coordinates_field']) async def cmd_start(message: types.Message): getting_coordinates() await message.answer('Thank u much! please put ur cursor on the button "send" \n and write me /get_cursor_coordinates_button') @dp.message_handler(commands=['get_cursor_coordinates_button']) async def cmd_start(message: types.Message): getting_coordinates() await message.answer('Thank u much! Bot is starting work') time_to_post = 60 * 180 await message.answer('checking images') check_new_files() await message.answer('checking is done') count_of_posts = len(open('downloaded_files.txt').readlines()) print(count_of_posts) for i in range(count_of_posts): try: # check new files on google_disk await message.answer('checking images') new_images = check_new_files() if new_images == 0: await message.answer('checking is done') else: count_of_posts += new_images await message.answer('find ' + new_images + ' new images') text = 'Quiz #' + '['+str(i+1)+']' + ', test your self with this random question. Write your answer in the comments section. Share with friends to make this exciting.\n\ #upsc #ias #xpertifyu #history #pcs #ssc #ips\nCheck www.xpertso.com to see other questions like this.' way_to_image = open('downloaded_files.txt').readlines()[i] a = datetime.datetime.now().hour time_to_rest = [23, 24, 0, 1, 2, 3, 4, 5, 6] while (a in time_to_rest): a = datetime.datetime.now().hour BOT.make_posts(way_to_image, text) await message.answer(str(i+1) + ' image was publicated') time.sleep(time_to_post) except: await message.answer('there is problem, trying to fix it...') # check new files on google_disk count_of_posts += check_new_files() text = 'Quiz #' + '[' + str(i + 1) + ']' + ', test your self with this random question. Write your answer in the comments section. Share with friends to make this exciting.\n\ #upsc #ias #xpertifyu #history #pcs #ssc #ips\nCheck www.xpertso.com to see other questions like this.' way_to_image = open('downloaded_files.txt').readlines()[i] a = datetime.datetime.now().hour time_to_rest = [23, 24, 0, 1, 2, 3, 4, 5, 6] while (a in time_to_rest): a = datetime.datetime.now().hour BOT.make_posts(way_to_image, text) await message.answer('problem is solvec') await message.answer(str(i+1) + ' image was publicated') time.sleep(time_to_post) def telegram_polling(): try: executor.start_polling(dp,skip_updates=True) #constantly get messages from Telegram except: traceback_error_string=traceback.format_exc() with open("Error.Log", "a") as myfile: myfile.write("\r\n\r\n" + time.strftime("%c")+"\r\n<<ERROR polling>>\r\n"+ traceback_error_string + "\r\n<<ERROR polling>>") time.sleep(10) telegram_polling() if __name__ == '__main__': telegram_polling()
[ "noreply@github.com" ]
noreply@github.com
b2e6140c9bee43937e6705d6ea974a889996e645
f21a9bca554a6242527f502dca0ef8af095b6a37
/views/viewComment.py
daa23cb62db32fa935f0dc3ce875c4eccb0212bc
[]
no_license
guredora403/TCV
1fc5aae473bece1437d15413d34b5d091425e4ad
5221f61a0df44f840e02075f35ec0818f5163076
refs/heads/master
2022-12-06T20:47:55.653790
2020-05-30T08:38:09
2020-05-30T08:38:09
268,027,039
0
0
null
2020-05-30T07:00:52
2020-05-30T07:00:51
null
UTF-8
Python
false
false
1,221
py
# -*- coding: utf-8 -*- # コメントの詳細 import wx import globalVars import views.ViewCreator from logging import getLogger from views.baseDialog import * class Dialog(BaseDialog): def __init__(self, comment): super().__init__() self.comment = { _("コメント本文"): comment["message"], _("名前"): comment["from_user"]["name"], _("ユーザ名"): comment["from_user"]["screen_id"], _("レベル"): str(comment["from_user"]["level"]), _("自己紹介"): comment["from_user"]["profile"] } def Initialize(self): self.identifier="viewCommentDialog"#このビューを表す文字列 self.log=getLogger(self.identifier) self.log.debug("created") super().Initialize(self.app.hMainView.hFrame,_("コメントの詳細")) self.InstallControls() return True def InstallControls(self): """いろんなwidgetを設置する。""" self.creator=views.ViewCreator.ViewCreator(0,self.panel,self.sizer,wx.VERTICAL,20) for key, value in self.comment.items(): self.creator.inputbox(key, 500, value, wx.TE_MULTILINE|wx.TE_READONLY|wx.TE_DONTWRAP) self.closeButton=self.creator.cancelbutton(_("閉じる(&C)"), None) def GetData(self): return self.iText.GetLineText(0)
[ "kashiwamochi@mbr.nifty.com" ]
kashiwamochi@mbr.nifty.com
19586668a678070771164a878b7d68f616fc2bd4
fd37c0ec422317234a8fbf544154c1224b4199d5
/pop_model.py
a2a61b6fb382798ab32a9797e4aa78611ca3b453
[]
no_license
benjirewis/tweetvec
7080ab2a38ae4cb921ec2af92d9a1a9ebc8d0d13
335fb990c5f44c4028924ef1b98d3c7b3ac64573
refs/heads/master
2022-04-28T21:29:41.850339
2020-04-30T04:14:55
2020-04-30T04:14:55
260,111,574
1
0
null
null
null
null
UTF-8
Python
false
false
4,451
py
# import twitter API and JSON processor import twitter import json # gensim imports. from gensim.test.utils import common_texts from gensim.models.doc2vec import Doc2Vec, TaggedDocument from sklearn import utils import csv import multiprocessing import nltk from nltk.corpus import stopwords from __future__ import print_function # define our accessible API object api = twitter.Api(consumer_key='iTYLP38Z7pGv31kIg6x994IIJ', consumer_secret='wxw4zrKmxhvmOlkwFI4UhVoVKWRCpZsaQH3gF8BIFoyViFHuCV', access_token_key='1071489398317989889-wRuGv0r65uK8RX9wHFTrFbSRNMNgMr', access_token_secret='zGa4BDFxIb3RIa7hoiVtQZLuRc9ehKd3vqMbUkkbqs2pF', tweet_mode="extended") # Most popular users retreived from https://friendorfollow.com/twitter/most-followers/ top_accounts = [ "BarackObama", "justinbieber", "katyperry" ,"rihanna", "taylorswift13", "Cristiano", "ladygaga", "TheEllenShow", "realDonaldTrump", "ArianaGrande", "YouTube", "jtimberlake", "KimKardashian", "selenagomez", "Twitter", "cnnbrk", "britneyspears", "narendramodi", "shakira", "jimmyfallon", "BillGates", "CNN", "neymarjr", "nytimes", "KingJames", "JLo", "MileyCyrus", "BrunoMars", "Oprah", "BBCBreaking", "SrBachchan", "iamsrk", "BeingSalmanKhan", "NiallOfficial", "Drake", "SportsCenter", "KevinHart4real", "wizkhalifa", "NASA", "instagram", "akshaykumar", "espn", "LilTunechi", "imVkohli", "Harry_Styles", "realmadrid", "PMOIndia", "LouisTomlinson", "elonmusk", "LiamPayne" "BarackObama", "justinbieber", "katyperry" ,"rihanna", "taylorswift13", "Cristiano", "ladygaga", "TheEllenShow", "realDonaldTrump", "ArianaGrande", "YouTube", "jtimberlake", "KimKardashian", "selenagomez", "Twitter", "cnnbrk", "britneyspears", "narendramodi", "shakira", "jimmyfallon", "BillGates", "CNN", "neymarjr", "nytimes", "KingJames", "JLo", "MileyCyrus", "BrunoMars", "Oprah", "BBCBreaking", "SrBachchan", "iamsrk", "BeingSalmanKhan", "NiallOfficial", "Drake", "SportsCenter", "KevinHart4real", "wizkhalifa", "NASA", "instagram", "akshaykumar", "espn", "LilTunechi", "imVkohli", "Harry_Styles", "realmadrid", "PMOIndia", "LouisTomlinson", "elonmusk", "LiamPayne" "BarackObama", "justinbieber", "katyperry" ,"rihanna", "taylorswift13", "Cristiano", "ladygaga", "TheEllenShow", "realDonaldTrump", "ArianaGrande", "YouTube", "jtimberlake", "KimKardashian", "selenagomez", "Twitter", "cnnbrk", "britneyspears", "narendramodi", "shakira", "jimmyfallon", "BillGates", "CNN", "neymarjr", "nytimes", "KingJames", "JLo", "MileyCyrus", "BrunoMars", "Oprah", "BBCBreaking", "SrBachchan", "iamsrk", "BeingSalmanKhan", "NiallOfficial", "Drake", "SportsCenter", "KevinHart4real", "wizkhalifa", "NASA", "instagram", "akshaykumar", "espn", "LilTunechi", "imVkohli", "Harry_Styles", "realmadrid", "PMOIndia", "LouisTomlinson", "elonmusk", "LiamPayne" ] # add tweets from all senators to correct list tweets = [] for handle in top_accounts: for tweet in api.GetUserTimeline(screen_name=handle, count=200): t = tweet.full_text separate = "https" t_new = t.split(separate, 1)[0] tweets.append(t_new) # revised tokenizer. def tokenize_text(text): tokens = [] for sent in nltk.sent_tokenize(text): for word in nltk.word_tokenize(sent): if len(word) < 2: continue tokens.append(word.lower()) return tokens # find number of cores for parallelization. cores = multiprocessing.cpu_count() # read + tokenize the tweets. documents = [] for i,tweet in enumerate(tweets): documents.append(TaggedDocument(words=tokenize_text(tweet), tags=[tweet_label,i+1]) # create Doc2Vec model. model_dbow = Doc2Vec(dm=1, vector_size=45, negative=5, hs=0, min_count=2, sample=0, workers=cores) model_dbow.build_vocab([x for x in documents]) documents = utils.shuffle(documents) # shuffle model_dbow.train(documents,total_examples=len(documents), epochs=30) model_dbow.save('./out/pop_model.d2v')
[ "ben.rewis98@gmail.com" ]
ben.rewis98@gmail.com
cb3298d58096d95d57b1a990d94dab654f8eb045
bbe8a3f6b02aaa0bf8944e97930344eee6406195
/strings/ans5.py
06ec5ffbaeeccd38c9fb2b92f81f790e816e75ac
[]
no_license
Harshit090/Python-Problems
f0ec363fb98b40b755ac9afd278e98d7c7594c7d
c49087db259c3b7f52bf32f664cc3397796afcf5
refs/heads/master
2020-05-31T10:13:16.146073
2019-07-07T15:11:32
2019-07-07T15:11:32
190,234,919
0
1
null
2019-10-28T07:20:56
2019-06-04T15:54:28
Python
UTF-8
Python
false
false
367
py
l = [] ; n = [] x = int(input("Enter no of words to be added to list")) for i in range(x): a = input("Enter a string\n") l.append(a) for i in range(x): n.append(len(l[i])) b = len(l[0]) for i in range(x): if b < len(l[i]): b = len(l[i]) else: continue print(b,"is the length of the longest string in the list")
[ "noreply@github.com" ]
noreply@github.com
1f98db6d5dd9b2e6e10f8e0eb56e911ea4716dde
2f87108c884d8d1fb4636694e243846fbf1f813b
/natjecanje.py
5ade0308d44dcb20bf433dffb2d2a9b171f79d5f
[]
no_license
IngridFeng/competitive-programming
8f1fa5e270b00967da86868fca7e28661c477205
7aec03dec4bb5c9ddb377d5e4de86fe6b57ec017
refs/heads/master
2020-04-19T19:10:53.851125
2019-04-21T21:40:00
2019-04-21T21:40:00
168,381,769
0
0
null
null
null
null
UTF-8
Python
false
false
548
py
#! /usr/bin/python3 import sys lines = sys.stdin.readlines() dam = [int(i) for i in lines[1].split()] #store the number of damaged kayak into list res = [int(i) for i in lines[2].split()] #store the team number with reserved kayak into list count = 0 for d in dam: if res: for r in res: if abs(d-r) <= 1: #either the kayak itself, or on the left, or on the right res.remove(r) count += 1 #number of kayak borrowed break print(len(dam) - count) #number of kayak can't compete
[ "yigefeng@YigedeMacBook-Pro.local" ]
yigefeng@YigedeMacBook-Pro.local
19bf93fb7f263d11e77e96002fe5f58d107ffb35
382e308f433dd3b2c2601568f480be30a704e7d7
/Django 실습/sample_community/board/views.py
94525375f9d3f0d7adf021b9bb0a2d913286ea95
[]
no_license
5d5ng/LACUC-capstone1
29240f4109d397ceab3ad7bb771cbcdf69cb944c
01b0a1136dab592b778ac99c346c318d3c6ed30f
refs/heads/master
2022-12-03T15:57:55.804687
2019-11-18T09:44:04
2019-11-18T09:44:04
211,851,523
0
1
null
2022-11-17T07:05:21
2019-09-30T12:11:32
Python
UTF-8
Python
false
false
453
py
from django.shortcuts import render from .models import Board from .forms import BoardForm # Create your views here. def board_write(request): form = BoardForm() return render(request, 'board_write.html', {'form': form}) def board_list(request): boards = Board.objects.all().order_by('-id') # 시간 역순으로 모든 게시글을 가져옴 return render(request, 'board_list.html', {'boards': boards}) # 템플릿으로 전달
[ "deo1915@gmail.com" ]
deo1915@gmail.com
e09e54f9c04b097283001ad2a80995c20b218b1f
239ff863fade39e426112da979149214bb0d5630
/reid/reid-matching/tools/cluster.py
9f42be18278d0270a46b678a0a16c065366bfd15
[ "MIT" ]
permissive
regob/AIC21-MTMC
b99f6cbd11152241f5082ff61bca80715d0bbb0f
19c2cd6bfb6549c58ec1b7b54f6b7138efde6823
refs/heads/main
2023-08-22T21:34:04.592660
2021-10-06T14:08:56
2021-10-06T14:08:56
411,345,668
0
0
MIT
2021-09-28T15:49:24
2021-09-28T15:49:24
null
UTF-8
Python
false
false
3,477
py
from utils.filter import * from utils.visual_rr import visual_rerank from sklearn.cluster import AgglomerativeClustering,DBSCAN import sys sys.path.append('../../../') from config import cfg def get_sim_matrix(_cfg, cid_tid_dict,cid_tids, save_name='sim_matrix.pkl'): count = len(cid_tids) print('count: ', count) q_arr = np.array([cid_tid_dict[cid_tids[i]]['mean_feat'] for i in range(count)]) g_arr = np.array([cid_tid_dict[cid_tids[i]]['mean_feat'] for i in range(count)]) q_arr = normalize(q_arr, axis=1) g_arr = normalize(g_arr, axis=1) # sim_matrix = np.matmul(q_arr, g_arr.T) # st mask st_mask = np.ones((count, count), dtype=np.float32) st_mask = intracam_ignore(st_mask, cid_tids) # st_mask = st_filter(st_mask, cid_tids, cid_tid_dict) # visual rerank visual_sim_matrix = visual_rerank(q_arr, g_arr, cid_tids, _cfg) + 5 visual_sim_matrix = visual_sim_matrix.astype('float32') print(visual_sim_matrix) # merge result np.set_printoptions(precision=3) sim_matrix = visual_sim_matrix * st_mask # sim_matrix[sim_matrix < 0] = 0 np.fill_diagonal(sim_matrix, 0) sim_matrix = 6-sim_matrix pickle.dump(sim_matrix, open(save_name, 'wb')) return sim_matrix def normalize(nparray, axis=0): nparray = preprocessing.normalize(nparray, norm='l2', axis=axis) return nparray def get_match(cluster_labels): cluster_dict = dict() cluster = list() for i, l in enumerate(cluster_labels): if l in list(cluster_dict.keys()): cluster_dict[l].append(i) else: cluster_dict[l] = [i] for idx in cluster_dict: cluster.append(cluster_dict[idx]) return cluster def get_labels(_cfg,cid_tid_dict, cid_tids, score_thr): sim_matrix = get_sim_matrix(_cfg,cid_tid_dict,cid_tids) cluster_labels = AgglomerativeClustering(n_clusters=None, distance_threshold=1-score_thr, affinity='precomputed', linkage='average').fit_predict(sim_matrix) # linkage='complete').fit_predict(sim_matrix) labels = get_match(cluster_labels) return labels if __name__ == '__main__': cfg.merge_from_file(f'../../../config/{sys.argv[1]}') cfg.freeze() scene_name = ['S06'] scene_cluster = [[41, 42, 43, 44, 45, 46]] fea_dir = './exp/viz/test/S06/trajectory/' cid_tid_dict = dict() for pkl_path in os.listdir(fea_dir): cid = int(pkl_path.split('.')[0][-3:]) with open(opj(fea_dir, pkl_path),'rb') as f: lines = pickle.load(f) for line in lines: tracklet = lines[line] tid = tracklet['tid'] if (cid, tid) not in cid_tid_dict: cid_tid_dict[(cid, tid)] = tracklet cid_tids = sorted([key for key in cid_tid_dict.keys() if key[0] in scene_cluster[0]]) clu = get_labels(cfg,cid_tid_dict,cid_tids,score_thr=cfg.SCORE_THR) print('all_clu:', len(clu)) new_clu = list() for c_list in clu: if len(c_list) <= 1: continue cam_list = [cid_tids[c][0] for c in c_list] if len(cam_list)!=len(set(cam_list)): continue new_clu.append([cid_tids[c] for c in c_list]) print('new_clu: ', len(new_clu)) all_clu = new_clu cid_tid_label = dict() for i, c_list in enumerate(all_clu): for c in c_list: cid_tid_label[c] = i + 1 pickle.dump({'cluster': cid_tid_label}, open('test_cluster.pkl', 'wb'))
[ "liuchong@ios.ac.cn" ]
liuchong@ios.ac.cn
32f5577f3a00944015b637101dc7c1f2a32ddea1
b6316ed86238d8bd04d5fdbde82fdee01c2797cd
/com/hjs/basic/07_exception/MyInputError_2.py
dfd49b89f896cdeda4d3901362a68e7ff83056f3
[]
no_license
haojunsheng/PythonLearning
ba90476edbf7ddbd4731f1be7a8e4d6d8f879afb
784a8ce99392b8fd154f769d4a75e66827af7103
refs/heads/main
2023-01-07T19:24:23.496508
2020-10-26T11:07:57
2020-10-26T11:07:57
306,554,866
1
0
null
null
null
null
UTF-8
Python
false
false
493
py
class MyInputError(Exception): """Exception raised when there're errors in input""" def __init__(self, value): # 自定义异常类型的初始化 self.value = value def __str__(self): # 自定义异常类型的 string 表达形式 return ("{} is invalid input".format(repr(self.value))) if __name__ == '__main__': try: raise MyInputError(1) # 抛出 MyInputError 这个异常 except MyInputError as err: print('error: {}'.format(err))
[ "1324722673@qq.com" ]
1324722673@qq.com
5628e61cf22b3e0fdfbf7bf21d611443c3c12d42
27caa29053c9b6c7734c46f27ee3bc86d40bd9bd
/quspin/basis/basis_1d/_basis_1d_core/spf_ops.pyx
1103e5c8d84687b3ade78f6bbb169e17d402cf59
[]
no_license
wenya-r/ED
c121006418db6cff8c43aade957c3915865ecdb6
50f2c37465fdd6b4a0be5ce909a65edb94b9902b
refs/heads/master
2020-04-08T13:21:30.034824
2019-03-14T21:20:24
2019-03-14T21:20:24
159,097,043
0
0
null
null
null
null
UTF-8
Python
false
false
418
pyx
#!python #cython: boundscheck=False #cython: wraparound=False #cython: cdivision=True # distutils: language=c++ cimport numpy as _np from libc.math cimport sin,cos,sqrt from types cimport * import numpy as _np from scipy.misc import comb cdef extern from "glibc_fix.h": pass include "sources/spf_bitops.pyx" include "sources/refstate.pyx" include "sources/op_templates.pyx" include "sources/spf_ops.pyx"
[ "wwrowe@gmail.com" ]
wwrowe@gmail.com
b4f1719e30ccc17f774bee4996315d146f9cb3f6
740ad4d8be97373e30aafc09ec53446d681f6c5e
/sillynames/sillyname.py
ad62e56fcd64fc80ef1f4cad15889ae58ba45456
[]
no_license
kevinleethompson/original-code
d14ac2c1fdb71ff811cc680d6ac1f7c68bdb1c8c
7e7965590f5a82f48722efe3a26954223311e325
refs/heads/master
2020-03-27T04:01:56.358991
2018-12-13T19:05:44
2018-12-13T19:05:44
145,906,853
0
0
null
null
null
null
UTF-8
Python
false
false
8,202
py
import sys import json import random import copy import re ''' This program mutates a normal personal name into a silly sounding version. (Ex: "Kevin Thompson" may become "Kifin Tompsan" or "Quevil Thankson") The program takes an input personal name given as space-delimited strings. It first runs checks to ensure the provided strings are likely to be actual names (and not random letter combos or non-alpha chars), then uses the wordparts JSON to break out the names into its significant letter combos (Ex: "Chundrick" -> ["ch", "u", "nd", "r", "i", "ck"]). The parts are then mutated individually and joined back together to form the sillified name (Ex: ["ch", "u", "nd", "r", "i", "ck"] -> ["ch", "u", "mp", "l", "e", "rk"] -> "Chumplerk"). The mutation is performed in a very dumb way but is sufficient to produce the desired result. The wordparts dictionary contains 'vowel' and 'consonant' dictionaries which contain the corresponding letter combos mapped to dicts with three keys: 'mutations' -> a list of suitable letter combos to mutate to, 'adj_l' and 'adj_r' -> the numeric codes denoting which class of letter can be adjacent this one on the left and right sides, respectively (See 'Wordparts Dictionary Excerpt' and 'Adjacency Rules Codes' below). These hard-coded data ensure that the names are mutated in a sensible way by replacing the original parts with those having similar sounds and by avoiding unusual or invalid letter combinations. Including many common 2-3 letter combinations in the wordparts dict helps significantly to produce natural sound combinations. For example, if we treat the "nd" in "Chundrick" as the separate letters "n" and "d", we may get back the mutations "m" and "t." These mutations are fine on their own, but after joining back together they would form the unnatural combination "mt", producing the awkward name "Chumtlerk" instead of "Chumplerk." Randomized shuffling of possible mutation targets and occassional "two-hop" mutations (mutating an already mutated part) are done to give results a higher rate of variation. However, the algorithm also ensures that not every word part gets mutated so that the result is still recognizable as a variation of the original name and not something entirely different. Wordparts Dictionary Excerpt: { "vowel": { "a": {"mutations": ["a", "o", "u"], "adj_l": 3, "adj_r": 3}, "ai": {"mutations": ["a", "ai", "e", "ei", "y"], "adj_l": 1, "adj_r": 1}, ... }, "consonant": { "b": {"mutations": ["d", "p"], "adj_l": 3, "adj_r": 3}, "bb": {"mutations": ["b", "d", "dd", "p", "pp"], "adj_l": 30, "adj_r": 3}, ... } } Adjacency Rules Codes: 0 - start/end only 1 - consonant only 2 - vowel only 3 - any 10 - consonant only, cannot be at start/end 20 - vowel only, cannot be at start/end 30 - any, cannot be at start/end ''' # This wordParts dictionary is both how the program will identify discrete consonant and vowel strings and how it will choose a suitable mutation. with open('wordparts.json') as data_file: wordParts = json.load(data_file) def isValidName(nameStr): return re.match(r"^[a-zA-Z/' ]+$", nameStr) def capitalizeName(name): capName = '' for n in name.split(): if n.startswith('mc') or n.startswith('mac'): n = (n.split('c', 1)[0]).capitalize()+'c'+(n.split('c', 1)[1]).capitalize() else: n = n.capitalize() capName += n + ' ' return capName.rstrip(' ') def enforceAdjRules(reqLeftAdj, reqRightAdj, item): leftAdj = item['adj_l'] rightAdj = item['adj_r'] leftAllowsAny = leftAdj == 3 or leftAdj == 30 rightAllowsAny = rightAdj == 3 or rightAdj == 30 if (reqLeftAdj and reqRightAdj): return (leftAdj == reqLeftAdj or leftAdj == reqLeftAdj*10 or leftAllowsAny) and (rightAdj == reqRightAdj or rightAdj == reqRightAdj*10 or rightAllowsAny) elif (reqLeftAdj and not reqRightAdj): return (leftAdj == reqLeftAdj or leftAdj == reqLeftAdj*10 or leftAdj == 3 or leftAdj == 30) and rightAdj <= 3 elif (not reqLeftAdj and reqRightAdj): return (rightAdj == reqRightAdj or rightAdj == reqRightAdj*10 or rightAllowsAny) and leftAdj <= 3 else: return True def filterPartsDict(p, leftPartType, rightPartType, partType): passedPart = wordParts[partType][p] partNum = 1 if partType == 'consonant' else 2 leftPartNum = 0 rightPartNum = 0 if leftPartType: leftPartNum = 1 if leftPartType == 'consonant' else 2 if rightPartType: rightPartNum = 1 if rightPartType == 'consonant' else 2 return {k:v for (k,v) in copy.deepcopy(wordParts[partType]).items() if enforceAdjRules(leftPartNum, rightPartNum, v)} def mutateWordPart(p, leftPartType, rightPartType, partType): if p == 'mc' or p == 'mac': return p if p == 'e' and rightPartType == 0: return p filteredParts = filterPartsDict(p, leftPartType, rightPartType, partType); partsList = list(filteredParts) random.shuffle(filteredParts[p]['mutations']) random.shuffle(partsList) randomPassedPartChange = filteredParts[p]['mutations'].pop() while randomPassedPartChange not in partsList: randomPassedPartChange = filteredParts[p]['mutations'].pop() randomOtherPart = partsList[0] random.shuffle(filteredParts[randomOtherPart]['mutations']) print(randomOtherPart) randomOtherPartChange = filteredParts[randomOtherPart]['mutations'].pop() while randomOtherPartChange not in partsList: randomOtherPartChange = filteredParts[randomOtherPart]['mutations'].pop() randNum = random.randint(0,10) return randomPassedPartChange if randNum > 3 else randomOtherPartChange def mutateWords(wordsDict): wordStr = '' for word in wordsDict: chosenIndexes = random.sample(range(len(wordsDict[word])), round(len(wordsDict[word])*0.4)) for i in range(len(wordsDict[word])): part = wordsDict[word][i] leftPartType = 0 if i == 0 else wordsDict[word][i - 1]['type'] rightPartType = 0 if i == len(wordsDict[word]) - 1 else wordsDict[word][i + 1]['type'] if i in chosenIndexes: mutated = mutateWordPart(part['part'], leftPartType, rightPartType, part['type']) wordStr += mutated else: wordStr += part['part'] wordStr += ' ' return wordStr.rstrip(' ') def identifyWordParts(words): wordBreakdowns = {} wordsList = words.split(' ') for word in wordsList: wordBreakdowns[word] = [] wordLen = len(word) start = 0 while wordLen >= 0: wordChunk = word[start:wordLen].lower() middle = start != 0 and wordLen < len(word) vowelList = [part for part in list(wordParts['vowel']) if (wordParts['vowel'][part]['adj_l'] <= 3 and start == 0) or (wordParts['vowel'][part]['adj_l'] > 0 and wordParts['vowel'][part]['adj_r'] > 0 and middle) or (wordParts['vowel'][part]['adj_r'] <= 3 and wordLen == len(word))] consList = [part for part in list(wordParts['consonant']) if (wordParts['consonant'][part]['adj_l'] <= 3 and start == 0) or (wordParts['consonant'][part]['adj_l'] > 0 and wordParts['consonant'][part]['adj_r'] > 0 and middle) or (wordParts['consonant'][part]['adj_r'] <= 3 and wordLen == len(word))] if wordChunk in vowelList: identifiedPart = {'type': 'vowel', 'start': start == 0, 'end': wordLen == len(word), 'part': wordChunk} wordBreakdowns[word].append(identifiedPart) start = wordLen wordLen = len(word) continue elif wordChunk in consList: identifiedPart = {'type': 'consonant', 'start': start == 0, 'end': wordLen == len(word), 'part': wordChunk} wordBreakdowns[word].append(identifiedPart) start = wordLen wordLen = len(word) continue wordLen -= 1 # print(list(map(lambda o: [x['part'] for x in o], wordBreakdowns.values()))) return wordBreakdowns if __name__ == '__main__': name = '' if len(sys.argv) == 0: name = input("Please provide a space-delimited name: ") else: for i in range(1, len(sys.argv)): name += sys.argv[i] + ' ' while not isValidName(name): print("Names may only contain letters and apostrophes.") name = input("Please provide a space-delimited name: ") identified = identifyWordParts(name) mutated = capitalizeName(mutateWords(identified)) print(mutated)
[ "kevleethompson@gmail.com" ]
kevleethompson@gmail.com
25f57e9fd9eb49bfaeaf1224e60379ea378f2e30
577646264fc5e58e9f18c9ee5959d91e3dbcf371
/mvhgd/core/draw.py
95f29330cceb2695d1c2e72030a722e9957cd11e
[]
no_license
sulyi/multivariate-hypergeometric
9346ae04921bf757301c63696172240c4be3501d
b4783944deb5be86a516d559eeeb248e76a6822d
refs/heads/master
2020-05-18T13:32:54.736144
2015-12-01T01:30:57
2015-12-01T01:30:57
25,878,112
0
0
null
null
null
null
UTF-8
Python
false
false
1,989
py
class Draw(list): """ An event happened by drawing elements from an urn containing elements falling under different categories. The number of elements still remaining in each category is given by an iterable. """ __slots__ = [ 'gamma', 'P' ] def __init__( self, iterable=None, gamma=0, P=1.0 ): if iterable is not None: try: super(Draw, self).__init__(int(i) for i in iterable) except TypeError: raise TypeError("argument must support iteration") else: super(Draw, self).__init__() self.gamma = int(gamma) # fractional data type for P would be be swell as far as numeric stability goes, # but again that would make values grow factorially in size self.P = float(P) def __gt__( self, other ): if len(self) != len(other): return False return all(o < d for o, d in zip(other, self)) def __lt__( self, other ): if len(self) != len(other): return False return all(o > d for o, d in zip(other, self)) def __ge__( self, other ): if len(self) != len(other): return False return all(o <= d for o, d in zip(other, self)) def __le__( self, other ): if len(self) != len(other): return False return all(o >= d for o, d in zip(other, self)) def __eq__( self, other ): if not isinstance(other, Draw): return False return super(Draw, self).__eq__(other) and self.gamma == other.gamma def __str__( self ): return '%s ~ (%d) - %f' % ( list(self), self.gamma, self.P ) def __repr__( self ): return 'Draw(%s, %r, %r)' % ( list(self), self.gamma, self.P )
[ "sulyi.gbox@gmail.com" ]
sulyi.gbox@gmail.com
fb1dbea69368764bd3081e83799ba2e26db00e89
b5e06a1d0e1aae6909262bfaa810dc99c7c26c93
/Stack.py
3c4a8a795340379d9688357d7d6508c81d93cc31
[]
no_license
bhavin250495/Python-DataStructures
4586b7d9a85a0260c083840ca8b7522506faa86c
106b9a693f136b711db9f3e3dd36fa9adab52a30
refs/heads/master
2020-04-19T08:49:48.003197
2019-02-24T14:56:43
2019-02-24T14:56:43
168,090,590
1
0
null
null
null
null
UTF-8
Python
false
false
401
py
class Stack : stackDS = [] head = 0 def __init__(self,startStack): self.stackDS.append(startStack) def printTop(self): print(self.stackDS[self.head]) def push(self,data): self.stackDS.append(data) def pop(self): self.head +=1 return self.stackDS[self.head] s = Stack(12) s.push(10) s.push(90) s.printTop() s.pop() s.printTop()
[ "bhavinathunt@gmail.com" ]
bhavinathunt@gmail.com
1e9643e29a62f65549643552a3099a030cff8794
3caa8df238cd36c4c0732bf6a8ddbdab9c91e166
/Room org 1/Camera calibrate/self Cam Calib.py
87032b3f6e00f4e46c870e29ceab1c31d64c6638
[]
no_license
chirag-j/Eklavya-2017
b0090d18dad5f00f89af73a162d222043823721b
12129d4e1e4cb2c35258c70f3fd7dcf52ff9c83b
refs/heads/main
2023-05-08T04:23:36.625216
2021-05-31T17:58:39
2021-05-31T17:58:39
372,587,192
0
0
null
null
null
null
UTF-8
Python
false
false
2,183
py
import numpy as np import cv2 import glob import time def draw(img, corners, imgpts): corner = tuple(corners[0].ravel()) print corner img = cv2.line(img, corner, tuple(imgpts[0].ravel()), (255,0,0), 5) img = cv2.line(img, corner, tuple(imgpts[1].ravel()), (0,255,0), 5) img = cv2.line(img, corner, tuple(imgpts[2].ravel()), (0,0,255), 5) return img # termination criteria criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001) # prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0) objp = np.zeros((6*7,3), np.float32) objp[:,:2] = np.mgrid[0:7,0:6].T.reshape(-1,2) # Arrays to store object points and image points from all the images. objpoints = [] # 3d point in real world space imgpoints = [] # 2d points in image plane. cap = cv2.VideoCapture(1) i = 0 while i<14: ret, img = cap.read() if ret == True: gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) cv2.imshow('img',img) # Find the chess board corners found, corners = cv2.findChessboardCorners(gray, (7,6),None) # If found, add object points, image points (after refining them) if found == True: print 'Found!!!!!!!!!!!!!!' i+=1 print 'i: ', i objpoints.append(objp) cv2.cornerSubPix(gray,corners,(11,11),(-1,-1),criteria) imgpoints.append(corners) cv2.imwrite("C:\Users\Chirag\Documents\Bluetooth Folder\Calibration"+chr(i+96)+"1.jpg", gray) # Draw and display the corners cv2.drawChessboardCorners(img, (7,6), corners, ret) ## cv2.imwrite(chr(i+96)+".jpg", img) cv2.imshow('img',img) time.sleep(3) ## cv2.waitKey(5000) else: print "not found" if cv2.waitKey(1) == 27: break ## else: print 'ret: ', ret break cv2.destroyAllWindows() ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1],None,None) print mtx np.save('mtx.npy', mtx) np.save('dist.npy', dist)
[ "noreply@github.com" ]
noreply@github.com
b3d544d541aef8199863a213dfa2f0677802d67e
3708b87a48fe4bfff8d64c7485a54643b9539248
/PyTest.py
964521646ef4be558a0af5ee3c05bed732c07cd5
[]
no_license
jassanw/LaserBallPythonGame
f3048b7473891b47f4cb8e9b7e396c2440659f16
0ccfeafe064788670dc3ef5323a46e5c3b405a9b
refs/heads/main
2023-07-19T22:59:40.378377
2021-08-24T20:15:04
2021-08-24T20:15:04
398,953,349
0
0
null
null
null
null
UTF-8
Python
false
false
1,148
py
import random import os import time import pygame black = [0,0,0] pygame.init() WIDTH, HEIGHT = 750,750 WIN = pygame.display.set_mode((WIDTH,HEIGHT)) def main(): run = True FPS = 60 yspeed = 0 #random.choice([-1,1]) * 4 xspeed = 0 #random.choice([-1,1]) * 4 xposition = random.randrange(0,WIDTH) yposition = random.randrange(0,HEIGHT) clock = pygame.time.Clock() def redraw_window(): WIN.fill(black) pygame.draw.rect(WIN,(0,0,0),(0,0,20,20)) pygame.draw.circle(WIN,(255,0,0),(0,0),20) pygame.display.update() while run: clock.tick(FPS) redraw_window() for event in pygame.event.get(): if event.type == pygame.QUIT: run = False if(xposition + xspeed >= WIDTH): xposition = WIDTH xspeed*=-1 if (xposition + xspeed <= 0): xposition = 0 xspeed*=-1 if(xposition + xspeed < WIDTH and xposition + xspeed > 0): xposition += xspeed if(yposition + yspeed>= HEIGHT): yposition = HEIGHT yspeed *= -1 if(yposition + yspeed <= 0 ): yposition = 0 yspeed *= -1 if(yposition + yspeed < HEIGHT and yposition + yspeed > 0): yposition += yspeed pygame.quit() main()
[ "jassan@rfgsoftware.com" ]
jassan@rfgsoftware.com
ae8e11dbf700e8b547f3301a18102059e7cdabf8
54bb9ba6d507cd25b2c2ac553665bc5fc95280d1
/src/onegov/file/__init__.py
7cc5a6d0232f51b69f22604b6201246450e833ec
[ "MIT" ]
permissive
href/onegov-cloud
9ff736d968979380edba266b6eba0e9096438397
bb292e8e0fb60fd1cd4e11b0196fbeff1a66e079
refs/heads/master
2020-12-22T07:59:13.691431
2020-01-28T08:51:54
2020-01-28T08:51:54
null
0
0
null
null
null
null
UTF-8
Python
false
false
362
py
from onegov.file.collection import FileCollection, FileSetCollection from onegov.file.integration import DepotApp from onegov.file.models import ( File, FileSet, AssociatedFiles, SearchableFile ) __all__ = ( 'AssociatedFiles', 'DepotApp', 'File', 'FileCollection', 'FileSet', 'FileSetCollection', 'SearchableFile', )
[ "denis.krienbuehl@seantis.ch" ]
denis.krienbuehl@seantis.ch
24b577a58bcf921ba934bb85a3e142b93eba8b2f
00dfeccd2f1b934b945ff125b7a523e05107cc3c
/sorting algorithms/bubblesort.py
583ae965763e2b352043b2c59f6d175e88df2491
[]
no_license
anamikasen/ctci_solutions
2de379257b4800a700c1032421d38fd2028c53f0
7375f94b7c00baf9e084b70c7326878753902ddd
refs/heads/master
2020-03-29T04:26:11.165885
2018-10-09T15:41:14
2018-10-09T15:41:14
149,531,502
0
0
null
null
null
null
UTF-8
Python
false
false
305
py
array = [3, 2, 1, 6, 4, 19, 32, 0] def bubbleSort(array): for i in range(0, len(array)-1): for j in range(0, len(array)-i-1): if array[j] > array[j+1]: array[j], array[j+1] = array[j+1], array[j] print(array) if __name__=="__main__": bubbleSort(array)
[ "anamika13sen@gmail.com" ]
anamika13sen@gmail.com
9a56acf7d78a0d4e44de05e9ee623aa1ac9fdc6d
113148549e08f9bf71de933dff64e9c320c26a57
/counterapp/migrations/0001_initial.py
1c0f8f4f7f6b651d831f4e30a81d8caf6888231e
[]
no_license
omeshkumarfso/Django-PizzaApp
d949e76e7644668ea8d7f31f13c5cf244869d967
f176f9780a306b989bb88499ab2fe470fa871e3a
refs/heads/master
2023-01-20T15:51:44.591920
2020-12-03T08:26:25
2020-12-03T08:26:25
318,124,556
0
0
null
null
null
null
UTF-8
Python
false
false
493
py
# Generated by Django 3.0.8 on 2020-09-04 06:01 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='CounterModel', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('number', models.CharField(max_length=10)), ], ), ]
[ "omeshkumarfso@gmail.com" ]
omeshkumarfso@gmail.com
73fb3d9250f02d8fe9facad696350a28915550dd
d7a34338f51310f7803f5829ba073fff28a07d91
/All Chat Load Testing - WebSockets_Polling_MTQQ/load-master/Sharing/mergeCsvResults.py
8a938cc9ab1bab640760c2319481721f52eb1dcf
[]
no_license
Sreejithkurup4/Performance-Testing
47939f6d0a54e75086537068f5804eba807777dd
1664a87c45d73bb0e966b64b779c971d93069af5
refs/heads/main
2023-05-15T21:44:18.244090
2021-06-14T08:53:50
2021-06-14T08:53:50
376,721,892
0
0
null
null
null
null
UTF-8
Python
false
false
399
py
from glob import glob with open("finalFile", "a") as singleFile: has_header = False for csvFile in glob("*.jtl"): i = 1 for line in open(csvFile, "r"): if i > 1: singleFile.write(line) elif not has_header: singleFile.write(line) has_header = True i=i+1 print(csvFile) exit()
[ "Sreejithkurup5@gmail.com" ]
Sreejithkurup5@gmail.com
1c315168a10b7435053d60aa5a58f84ecd7097c3
7bb0f97632e6ef24b6b2fc9bb3166480abb51aaa
/boutique_ado/settings.py
e9cb110b4baa4c50fde9e3272f5d18c49afa9ffc
[]
no_license
adowlin/boutique-ado-v1
648c754ad1fcbdae29724efe5560ba847f574f9d
0ec5d3917fde176cdc6d25f67a0e935fbf000144
refs/heads/master
2023-06-26T22:19:19.917797
2021-07-26T20:43:45
2021-07-26T20:43:45
380,599,381
0
0
null
null
null
null
UTF-8
Python
false
false
6,592
py
""" Django settings for boutique_ado project. Generated by 'django-admin startproject' using Django 3.2.4. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path import os import dj_database_url # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY', ''), # SECURITY WARNING: don't run with debug turned on in production! DEBUG = 'DEVELOPMENT' in os.environ ALLOWED_HOSTS = ['django-boutique-ado-ad.herokuapp.com', 'localhost'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'home', 'products', 'bag', 'checkout', 'profiles', # Other 'crispy_forms', 'storages', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'boutique_ado.urls' CRISPY_TEMPLATE_PACK = 'bootstrap4' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), os.path.join(BASE_DIR, 'templates', 'allauth'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', # required by allauth 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media', 'bag.contexts.bag_contents', ], 'builtins': [ 'crispy_forms.templatetags.crispy_forms_tags', 'crispy_forms.templatetags.crispy_forms_field', ] }, }, ] MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage' AUTHENTICATION_BACKENDS = ( # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by e-mail 'allauth.account.auth_backends.AuthenticationBackend', ) SITE_ID = 1 ACCOUNT_AUTHENTICATION_METHOD = 'username_email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_SIGNUP_EMAIL_ENTER_TWICE = True ACCOUNT_USERNAME_MIN_LENGTH = 4 LOGIN_URL = '/accounts/login/' LOGIN_REDIRECT_URL = '/' WSGI_APPLICATION = 'boutique_ado.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases if 'DATABASE_URL' in os.environ: DATABASES = { 'default': dj_database_url.parse(os.environ.get('DATABASE_URL')) } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') if 'USE_AWS' in os.environ: # Cache control AWS_S3_OBJECT_PARAMETERS = { 'Expires': 'Thu, 31 Dec 2099 20:00:00 GMT', 'CacheControl': 'max-age=94608000' } # Bucket Config AWS_STORAGE_BUCKET_NAME = 'django-boutique-ado-ad' AWS_S3_REGION_NAME = 'eu-west-1' AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' # Static & media files STATICFILES_STORAGE = 'custom_storages.StaticStorage' STATICFILES_LOCATION = 'static' DEFAULT_FILE_STORAGE = 'custom_storages.MediaStorage' MEDIAFILES_LOCATION = 'media' # Override static and media URLs in production STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{STATICFILES_LOCATION}' MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{MEDIAFILES_LOCATION}' # Stripe FREE_DELIVERY_THRESHOLD = 50 STANDARD_DELIVERY_PERCENTAGE = 10 STRIPE_CURRENCY = 'usd' STRIPE_PUBLIC_KEY = os.getenv('STRIPE_PUBLIC_KEY', '') STRIPE_SECRET_KEY = os.getenv('STRIPE_SECRET_KEY', '') STRIPE_WH_SECRET = os.getenv('STRIPE_WH_SECRET', '') if 'DEVELOPMENT' in os.environ: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' DEFAULT_FROM_EMAIL = 'boutiqueado@example.com' else: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASS') DEFAULT_FROM_EMAIL = os.environ.get('EMAIL_HOST_USER') # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
[ "dowlingalison@gmail.com" ]
dowlingalison@gmail.com
95bc689f2debc6907b2ceb600e9071226766bbab
59b8ad854b6ee3be7fed72c16e413a44028d9814
/lambda/postReview.py
8655640a07a25f0a6ca862b02a7c4335dd0aa2b5
[]
no_license
Tejas-Ghanekar/restaurant-review
6107cba77358d5312c1df979d46de5e4920e1a03
3bd5da8d444cc79fcd076ba126c3b9570c5a2c11
refs/heads/master
2022-12-12T00:16:49.976030
2020-02-03T20:25:04
2020-02-03T20:25:04
228,703,789
0
0
null
2022-12-11T19:14:42
2019-12-17T21:22:14
TypeScript
UTF-8
Python
false
false
961
py
import pymysql import sys import os import logging import json logger = logging.getLogger() logger.setLevel(logging.INFO) REGION = 'us-east-1' host = os.environ['HOST'] user_name = os.environ['USER'] password = os.environ['PASSWORD'] db_name = os.environ['DB_NAME'] def lambda_handler(event, context): # TODO implement request = json.dumps(event) data = json.loads(request) try: conn = pymysql.connect(host,user=user_name,passwd=password,db=db_name,connect_timeout=5) sql="INSERT INTO review (restaurant_id,customer_id,review_text,rating,timestamp) VALUES (%s, %s, %s, %s, %s)" val = (data['body']['restaurant_id'],data['body']['customer_id'],data['body']['resReviewText'],data['body']['rating'],data['body']['timestamp']) with conn.cursor() as cur: cur.execute(sql,val) conn.commit() print("success") finally: cur.close() conn.close() return event
[ "tejas.ghanekar@slalom.com" ]
tejas.ghanekar@slalom.com
5494da1fde51e2b036cfae84db3b9f33a86c2556
931926968461bbe8fc6295d4f5b702c5de99c231
/paper/plot_cifar10_confusion_diff.py
f9a3028e134b9ca9deca51fdf7202d96223084c2
[]
no_license
annaproxy/modules
93315ce684bdda4fb7a34a518ac2154e506a6579
771e1fa49edd2f237883842f741ea1d8ce1fccdc
refs/heads/master
2022-12-27T22:27:39.408250
2020-10-06T10:30:22
2020-10-06T10:30:22
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,606
py
#!/usr/bin/env python3 import os import lib from lib import StatTracker import torch import shutil import matplotlib.pyplot as plt import numpy as np import itertools from mpl_toolkits.axes_grid1 import make_axes_locatable from lib.common import group BASE_DIR = "out/cifar10_confusion/" shutil.rmtree(BASE_DIR, ignore_errors=True) def draw(runs, name): VER_DIR = f"{BASE_DIR}/{name}/download/" os.makedirs(VER_DIR, exist_ok=True) def draw_confusion(means: np.ndarray, std: np.ndarray): print("MEAN", means) figure = plt.figure(figsize=[7,3])#means.shape) ax = plt.gca() #, vmin = -65, vmax = 65 im = plt.imshow(means, interpolation='nearest', cmap=plt.cm.viridis, aspect='auto') x_marks = ["airplane", "automobile", "bird", "cat", "deer", "dog", "frog", "horse", "ship", "truck"] assert len(x_marks) == means.shape[1] y_marks = x_marks assert len(y_marks) == means.shape[0] plt.xticks(np.arange(means.shape[1]), x_marks, rotation=45) # plt.xticks(np.arange(means.shape[1]), x_marks) plt.yticks(np.arange(means.shape[0]), y_marks) # for tick in figure.axes[0].xaxis.get_major_ticks()[1::2]: # tick.set_pad(15) # Use white text if squares are dark; otherwise black. threshold = (means.max() + means.min()) / 2. print("THRESHOLD", threshold) # rmap = np.around(means, decimals=0) rmap = np.round(means).astype(np.int) std = np.round(std).astype(np.int) for i, j in itertools.product(range(means.shape[0]), range(means.shape[1])): color = "white" if means[i, j] < threshold else "black" plt.text(j, i, f"${rmap[i, j]}\\pm{std[i,j]}$", ha="center", va="center", color=color) plt.ylabel("True label", labelpad=-10) plt.xlabel("Predicted label", labelpad=-10) # plt.xlabel("Predicted label", labelpad=10) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="2%", pad=0.1) plt.colorbar(im, cax) # plt.tight_layout() return figure def create_trackers(runs): trackers = {} for i_run, run in enumerate(runs): for f in run.files(per_page=10000): if not f.name.startswith("export") or "/confusion" not in f.name: continue if f.name not in trackers: trackers[f.name] = StatTracker() full_name = os.path.join(VER_DIR, f.name) print(f"Downloading {full_name}") f.download(root=VER_DIR, replace=True) data = torch.load(full_name) data = data.astype(np.float32) if "confusion_difference" not in f.name: data = data / np.sum(data, axis=1, keepdims=True) data = data * 100 trackers[f.name].add(data) # break # # if i_run >= 2: # break return trackers trackers = create_trackers(runs) for k, v in trackers.items(): s = v.get() figure = draw_confusion(s.mean, s.std) prefix = f"out/cifar10_confusion/{name}/" dir = os.path.join(prefix, os.path.dirname(k)) os.makedirs(dir, exist_ok=True) figure.savefig(f"{prefix}/{k}.pdf", bbox_inches='tight', pad_inches = 0.01) plt.close() draw(lib.get_runs(["cifar10_no_dropout"]), "no_dropout") draw(lib.get_runs(["cifar10"]), "with_dropout") draw(lib.get_runs(["cifar10_resnet"]), "resnet")
[ "xdever@gmail.com" ]
xdever@gmail.com