uid
stringlengths
24
24
split
stringclasses
1 value
category
stringclasses
2 values
content
stringlengths
5
482k
signature
stringlengths
1
14k
suffix
stringlengths
1
482k
prefix
stringlengths
9
14k
prefix_token_count
int64
3
5.01k
prefix_token_budget
int64
64
256
element_token_count
int64
1
292k
signature_token_count
int64
1
5.01k
prefix_context_token_count
int64
0
255
repo
stringlengths
7
112
path
stringlengths
4
208
language
stringclasses
1 value
name
stringlengths
1
218
qualname
stringlengths
1
218
start_line
int64
1
26.7k
end_line
int64
1
26.7k
signature_start_line
int64
1
26.7k
signature_end_line
int64
1
26.7k
source_hash
stringlengths
40
40
source_dataset
stringclasses
1 value
source_split
stringclasses
1 value
e942f74ea1cf0590950b2a5c
train
function
def _create_interface_spheres(geo_data, r=0.33): "Creates InterfaceSphere (vtkSphereSource) for all interface positions in dataframe." spheres = [] for index, row in geo_data.interfaces.iterrows(): spheres.append(InterfaceSphere(index, fmt=geo_data.interfaces.ix[index]["formation"])) spheres...
def _create_interface_spheres(geo_data, r=0.33):
"Creates InterfaceSphere (vtkSphereSource) for all interface positions in dataframe." spheres = [] for index, row in geo_data.interfaces.iterrows(): spheres.append(InterfaceSphere(index, fmt=geo_data.interfaces.ix[index]["formation"])) spheres[-1].SetCenter(geo_data.interfaces.ix[index]["X"]...
.GetFocalPoint()) print("BLUE XZ:", xz_cam.GetPosition()) print("BLUE FP:", xz_cam.GetFocalPoint()) return [model_cam, xy_cam, yz_cam, xz_cam] def _create_interface_spheres(geo_data, r=0.33):
64
64
118
16
48
nre-aachen/gempy
gempy/visualization_vtk.py
Python
_create_interface_spheres
_create_interface_spheres
296
305
296
296
d610b418f3ef1fa98070192509da8fdf74d4df2e
bigcode/the-stack
train
c545214c4c0e68cc6ee53e94
train
class
class CustomTransformPolyDataFilter(vtk.vtkTransformPolyDataFilter): def __init__(self, index, color=(0.5, 0.5, 0.5)): self.index = index self.color = color
class CustomTransformPolyDataFilter(vtk.vtkTransformPolyDataFilter):
def __init__(self, index, color=(0.5, 0.5, 0.5)): self.index = index self.color = color
[fmt] class ColoredActor(vtk.vtkActor): def __init__(self, index, color=(0.5, 0.5, 0.5)): self.index = index self.color = color class CustomTransformPolyDataFilter(vtk.vtkTransformPolyDataFilter):
64
64
52
15
48
nre-aachen/gempy
gempy/visualization_vtk.py
Python
CustomTransformPolyDataFilter
CustomTransformPolyDataFilter
42
45
42
42
3dc7dd9ddd1fbc5badf39fecb89c2c12d75f59c0
bigcode/the-stack
train
554593a00b34f673f9bd4544
train
function
def _extract_surface(pot_field, val, res, spacing): from skimage import measure vertices, simplices, normals, values = measure.marching_cubes(pot_field.reshape(res[0], res[1], res[2]), val # , #0.2424792, # -0.559606 ...
def _extract_surface(pot_field, val, res, spacing):
from skimage import measure vertices, simplices, normals, values = measure.marching_cubes(pot_field.reshape(res[0], res[1], res[2]), val # , #0.2424792, # -0.559606 # spacing=sp...
Actor(a) # reset cameras for all renderers r.ResetCamera() # initialize and start the app interactor.Initialize() interactor.Start() # close_window(interactor) del renwin, interactor def _extract_surface(pot_field, val, res, spacing):
64
64
107
14
49
nre-aachen/gempy
gempy/visualization_vtk.py
Python
_extract_surface
_extract_surface
224
231
224
224
fb7271ad6114fde89b64940b5e733e2d8d272797
bigcode/the-stack
train
6152a1ee5824abcb2b2afccb
train
class
class CustomInteractorCamera(vtk.vtkInteractorStyleTrackballCamera): """ Custom camera interactor class. """ def __init__(self, ren_list, geo_data, parent, pot_field): self.parent = parent self.AddObserver("LeftButtonPressEvent", self.left_button_press_event) self.AddObserver("L...
class CustomInteractorCamera(vtk.vtkInteractorStyleTrackballCamera):
""" Custom camera interactor class. """ def __init__(self, ren_list, geo_data, parent, pot_field): self.parent = parent self.AddObserver("LeftButtonPressEvent", self.left_button_press_event) self.AddObserver("LeftButtonReleaseEvent", self.left_button_release_event) self....
None self.OnMiddleButtonUp() return def na(self): print("MiddleMouseButton released") if self.PickedProducer is not None: # print("Moving actor: ",type(self.PickedActor)) # print("Producer: ",type(self.PickedProducer)) if type(self.PickedProdu...
203
203
679
14
188
nre-aachen/gempy
gempy/visualization_vtk.py
Python
CustomInteractorCamera
CustomInteractorCamera
703
778
703
703
709f1f09957ef9ae7c57586102e5d7d0c1f0c1da
bigcode/the-stack
train
d45c257a2b4dd15e87d92175
train
class
class CustomInteractorActor(vtk.vtkInteractorStyleTrackballActor): """ Modified vtkInteractorStyleTrackballActor class to accomodate for interface df modifications. """ def __init__(self, ren_list, geo_data, parent): self.On() self.DebugOn() self.parent = parent self.re...
class CustomInteractorActor(vtk.vtkInteractorStyleTrackballActor):
""" Modified vtkInteractorStyleTrackballActor class to accomodate for interface df modifications. """ def __init__(self, ren_list, geo_data, parent): self.On() self.DebugOn() self.parent = parent self.ren_list = ren_list self.geo_data = geo_data self.Add...
_data.resolution lx = geo_data.extent[0] - geo_data.extent[1] ly = geo_data.extent[2] - geo_data.extent[3] lz = geo_data.extent[4] - geo_data.extent[5] dx, dy, dz = lx / nx, ly / ny, lz / nz ncells = nx * ny * nz npoints = (nx + 1) * (ny + 1) * (nz + 1) # Coordinates x = np.arange(0...
256
256
1,846
14
242
nre-aachen/gempy
gempy/visualization_vtk.py
Python
CustomInteractorActor
CustomInteractorActor
503
700
503
503
e4bd4fc3d59b278d73c9460cd9aba92cca450dda
bigcode/the-stack
train
03ed629214d5d9bb7243bb6c
train
function
def visualize(geo_data, pot_field=None, surface_vals=None, interf_bool=True, fol_bool=True, verbose=0, win_size=(1000, 800), sphere_r=None, surface_alpha=1, surface_spacing_modifier=1 ): """...
def visualize(geo_data, pot_field=None, surface_vals=None, interf_bool=True, fol_bool=True, verbose=0, win_size=(1000, 800), sphere_r=None, surface_alpha=1, surface_spacing_modifier=1 ):
""" Args: geo_data: geo_data object pot_field: np.array surface_vals: list of potential field values interf_bool: bool fol_bool: bool surf_bool: bool verbose: int Returns: """ # TODO: Fix move lock if window gets resized global C_LOT # T...
fmt is None: self.color = color else: self.color = C_LOT[fmt] class FoliationArrow(vtk.vtkArrowSource): def __init__(self, index, color=(0.5, 0.5, 0.5), fmt=None): self.index = index # df index if fmt is None: self.color = color else: ...
256
256
1,608
60
195
nre-aachen/gempy
gempy/visualization_vtk.py
Python
visualize
visualize
48
221
48
57
6ebacdac446b753610775bebca7c70d9513e9654
bigcode/the-stack
train
87add1c53c8256ecfe3cb8e6
train
class
class FoliationArrow(vtk.vtkArrowSource): def __init__(self, index, color=(0.5, 0.5, 0.5), fmt=None): self.index = index # df index if fmt is None: self.color = color else: self.color = C_LOT[fmt]
class FoliationArrow(vtk.vtkArrowSource):
def __init__(self, index, color=(0.5, 0.5, 0.5), fmt=None): self.index = index # df index if fmt is None: self.color = color else: self.color = C_LOT[fmt]
0.5, 0.5, 0.5), fmt=None): self.index = index # df index if fmt is None: self.color = color else: self.color = C_LOT[fmt] class FoliationArrow(vtk.vtkArrowSource):
64
64
75
12
52
nre-aachen/gempy
gempy/visualization_vtk.py
Python
FoliationArrow
FoliationArrow
27
33
27
27
130501d39db9d28c44763128ab73aad1f5d25f28
bigcode/the-stack
train
91cb3cf9b95ec028e8f3fd11
train
function
def export_vtk_rectilinear(geo_data, block_lith, path=None): """ export vtk :return: """ from evtk.hl import gridToVTK import numpy as np import random as rnd # Dimensions nx, ny, nz = geo_data.resolution lx = geo_data.extent[0] - geo_data.extent[1] ly = geo...
def export_vtk_rectilinear(geo_data, block_lith, path=None):
""" export vtk :return: """ from evtk.hl import gridToVTK import numpy as np import random as rnd # Dimensions nx, ny, nz = geo_data.resolution lx = geo_data.extent[0] - geo_data.extent[1] ly = geo_data.extent[2] - geo_data.extent[3] lz = geo_data.extent...
if sys.platform == "win32": cube_axes_actor.SetGridLineLocation(cube_axes_actor.VTK_GRID_LINES_FURTHEST) else: # rather use elif == "linux" ? but what about other platforms cube_axes_actor.SetGridLineLocation(vtk.VTK_GRID_LINES_FURTHEST) return cube_axes_actor def export_vtk_rectilinear(ge...
92
92
307
18
73
nre-aachen/gempy
gempy/visualization_vtk.py
Python
export_vtk_rectilinear
export_vtk_rectilinear
461
500
461
461
ddffd2efd194776201e4a8f9bbd40ed7ffe33835
bigcode/the-stack
train
dd15364f25989c974f877586
train
class
class CustomPolyData(vtk.vtkPolyData): def __init__(self, color=(0.5, 0.5, 0.5), surface_alpha=1): self.color = color self.surface_alpha = surface_alpha
class CustomPolyData(vtk.vtkPolyData):
def __init__(self, color=(0.5, 0.5, 0.5), surface_alpha=1): self.color = color self.surface_alpha = surface_alpha
actors[-1].GetProperty().SetColor(actors[-1].color[0], actors[-1].color[1], actors[-1].color[2]) actors[-1].SetMapper(mappers[-1]) return mappers, actors class CustomPolyData(vtk.vtkPolyData):
64
64
53
11
52
nre-aachen/gempy
gempy/visualization_vtk.py
Python
CustomPolyData
CustomPolyData
337
340
337
337
813be19c27bc1000c1d5d5362942ba56092e0ad1
bigcode/the-stack
train
2114533a797d86c40223c830
train
function
def _create_axes(geo_data, camera_list, verbose=0): "Create and returnr cubeAxesActor, settings." cube_axes_actor = vtk.vtkCubeAxesActor() cube_axes_actor.SetBounds(geo_data.extent) cube_axes_actor.SetCamera(camera_list[1]) if verbose == 1: print(cube_axes_actor.GetAxisOrigin()) # set a...
def _create_axes(geo_data, camera_list, verbose=0):
"Create and returnr cubeAxesActor, settings." cube_axes_actor = vtk.vtkCubeAxesActor() cube_axes_actor.SetBounds(geo_data.extent) cube_axes_actor.SetCamera(camera_list[1]) if verbose == 1: print(cube_axes_actor.GetAxisOrigin()) # set axes and label colors cube_axes_actor.GetTitleTex...
_data.foliations.ix[arrow.index]["Z"] + geo_data.foliations.ix[arrow.index]["G_z"] / f) arrows_sp.append(_sp) arrows_ep.append(_ep) # /////////////////////////////////////////////////////////////// # create transformers for ArrowSource and transform arrows_transformers = [] for i, arro...
153
153
512
15
137
nre-aachen/gempy
gempy/visualization_vtk.py
Python
_create_axes
_create_axes
417
458
417
417
93c89087ae58d90b76680a8f4b928d86a2347910
bigcode/the-stack
train
aa7930a0e4034c9618b3c883
train
class
class PriceNode(core.node.Node): def __init__(self, nm, capacity = 15): core.node.Node.__init__(self, nm, "Price", capacity) nm.register_output_wire("", self) def data_income(self, from_name, value): if from_name != "": return self.values.append(value) while len(self.values) > self.capacity: de...
class PriceNode(core.node.Node):
def __init__(self, nm, capacity = 15): core.node.Node.__init__(self, nm, "Price", capacity) nm.register_output_wire("", self) def data_income(self, from_name, value): if from_name != "": return self.values.append(value) while len(self.values) > self.capacity: del self.values[0] self.data_out...
import core.node class PriceNode(core.node.Node):
11
64
144
7
3
stonewell/learn-curve
modules/core/nodes/price_node.py
Python
PriceNode
PriceNode
3
22
3
3
bd979f043cec0959a528d26df16d7a2de467a75a
bigcode/the-stack
train
7b70beb91da3b3cfbe747231
train
function
def create_price_node(nm, capacity = 15): if not "Price" in nm.nodes: price = PriceNode(nm, capacity) nm.nodes["Price"] = price return price else: return nm.nodes["Price"]
def create_price_node(nm, capacity = 15):
if not "Price" in nm.nodes: price = PriceNode(nm, capacity) nm.nodes["Price"] = price return price else: return nm.nodes["Price"]
("Close", value.close_price) self.data_output("Amount", value.amount) self.data_output("Lowest", value.lowest_price) self.data_output("Highest", value.highest_price) self.data_output("Open", value.open_price) def create_price_node(nm, capacity = 15):
64
64
55
12
52
stonewell/learn-curve
modules/core/nodes/price_node.py
Python
create_price_node
create_price_node
24
32
24
24
60a828905b97a3243e3546df7b858f92c353ebbb
bigcode/the-stack
train
c4f9e002febb3cf7cb4a5848
train
function
def _new_interval_id(): global _interval_ctr _interval_ctr += 1 return _interval_ctr
def _new_interval_id():
global _interval_ctr _interval_ctr += 1 return _interval_ctr
#coding:utf-8 import threading import sys import time import threading import atexit intervals = {} _interval_ctr = 0 def _new_interval_id():
39
64
26
6
32
404neko/Marisa
spin.py
Python
_new_interval_id
_new_interval_id
11
14
11
11
b7e0b711ae2ca83a9a0ca306fb5ce4ad0548e75a
bigcode/the-stack
train
86a23e77b42c13cdd063d2a8
train
function
def set_interval(f,delay, *args, **kwargs): i_id = _new_interval_id() def f_major(): f(*args, **kwargs) t = threading.Timer(delay,f_major) intervals[i_id] = t t.daemon = True t.start() t = threading.Timer(delay,f_major) intervals[i_id] = t t.daemon = True ...
def set_interval(f,delay, *args, **kwargs):
i_id = _new_interval_id() def f_major(): f(*args, **kwargs) t = threading.Timer(delay,f_major) intervals[i_id] = t t.daemon = True t.start() t = threading.Timer(delay,f_major) intervals[i_id] = t t.daemon = True t.start() return i_id
import sys import time import threading import atexit intervals = {} _interval_ctr = 0 def _new_interval_id(): global _interval_ctr _interval_ctr += 1 return _interval_ctr def set_interval(f,delay, *args, **kwargs):
64
64
96
13
50
404neko/Marisa
spin.py
Python
set_interval
set_interval
16
28
16
16
1bcef8f4e5ce26486cf79770a3a0d93ee876119e
bigcode/the-stack
train
895b9ed4d5fe4f51b9214d93
train
class
class Spin: pos = 0 words = '' type_ = 'Spin1' flag_exit = False def __init__(self,type_='Spin1',words=''): if words!='': self.words = words+' ' else: pass self.type_=type_ def loop_main(self): sys.stdout.write('\r' + self.words + sel...
class Spin:
pos = 0 words = '' type_ = 'Spin1' flag_exit = False def __init__(self,type_='Spin1',words=''): if words!='': self.words = words+' ' else: pass self.type_=type_ def loop_main(self): sys.stdout.write('\r' + self.words + self.spinner[se...
▏▎▍▌▋▊▉', 'Spin6': '▌▄▐▀', 'Spin7': '╫╪', 'Spin8': '■□▪▫', 'Spin9': '←↑→↓' } class Spin:
64
64
158
3
61
404neko/Marisa
spin.py
Python
Spin
Spin
57
82
57
57
214e144901040111dcbc27436540f2e2480e7eb4
bigcode/the-stack
train
91b3fc309a70ff66a767c065
train
function
def clear_interval(i_id): try: intervals[i_id].cancel() del intervals[i_id] return 0 except KeyError: return 1
def clear_interval(i_id):
try: intervals[i_id].cancel() del intervals[i_id] return 0 except KeyError: return 1
threading.Timer(delay,f_major) intervals[i_id] = t t.daemon = True t.start() t = threading.Timer(delay,f_major) intervals[i_id] = t t.daemon = True t.start() return i_id def clear_interval(i_id):
64
64
37
6
57
404neko/Marisa
spin.py
Python
clear_interval
clear_interval
30
36
30
30
89f5082222d877353ef3bd1c9d5ce973ba4083cf
bigcode/the-stack
train
6b574cc986e072f6ebace478
train
class
class SupervisorTest(test.TestCase): def _test_dir(self, test_name): test_dir = os.path.join(self.get_temp_dir(), test_name) if os.path.exists(test_dir): shutil.rmtree(test_dir) return test_dir def _wait_for_glob(self, pattern, timeout_secs, for_checkpoint=True): """Wait for a checkpoint fil...
class SupervisorTest(test.TestCase):
def _test_dir(self, test_name): test_dir = os.path.join(self.get_temp_dir(), test_name) if os.path.exists(test_dir): shutil.rmtree(test_dir) return test_dir def _wait_for_glob(self, pattern, timeout_secs, for_checkpoint=True): """Wait for a checkpoint file to appear. Args: pattern:...
from tensorflow.core.util import event_pb2 from tensorflow.python.checkpoint import checkpoint_management from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import errors_impl from tensorflow.python.framework import meta_graph from tensorf...
256
256
8,314
7
249
mcx/tensorflow
tensorflow/python/training/supervisor_test.py
Python
SupervisorTest
SupervisorTest
64
915
64
65
b2ac0b19de1f38314618def79cf86025463724c6
bigcode/the-stack
train
dd0925cbda0284b0a5928fe2
train
function
def _summary_iterator(test_dir): """Reads events from test_dir/events. Args: test_dir: Name of the test directory. Returns: A summary_iterator """ event_paths = sorted(glob.glob(os.path.join(test_dir, "event*"))) return summary_iterator.summary_iterator(event_paths[-1])
def _summary_iterator(test_dir):
"""Reads events from test_dir/events. Args: test_dir: Name of the test directory. Returns: A summary_iterator """ event_paths = sorted(glob.glob(os.path.join(test_dir, "event*"))) return summary_iterator.summary_iterator(event_paths[-1])
_iterator from tensorflow.python.summary.writer import writer from tensorflow.python.training import input as input_lib from tensorflow.python.training import saver as saver_lib from tensorflow.python.training import server_lib from tensorflow.python.training import session_manager as session_manager_lib from tensorflo...
64
64
68
7
56
mcx/tensorflow
tensorflow/python/training/supervisor_test.py
Python
_summary_iterator
_summary_iterator
51
61
51
51
27a45a2fbf46aad3d4d1f907693bddddf654c3a7
bigcode/the-stack
train
c7c51bffd1206af877196ac1
train
class
class TreeNodeWithNext(TreeNode): def __init__(self, val, left=None, right=None, next=None): super().__init__(val, left, right) self.next = next def toList(self): leftMostNodes = [] currLvl = -1 queue = deque([(self, 0)]) while queue: node, lvl = qu...
class TreeNodeWithNext(TreeNode):
def __init__(self, val, left=None, right=None, next=None): super().__init__(val, left, right) self.next = next def toList(self): leftMostNodes = [] currLvl = -1 queue = deque([(self, 0)]) while queue: node, lvl = queue.popleft() if lvl > ...
from collections import deque from ..utils import TreeNode class TreeNodeWithNext(TreeNode):
20
64
199
8
11
ansonmiu0214/dsa-worked-solutions
solutions/populating_next_right_pointers_ii/solution.py
Python
TreeNodeWithNext
TreeNodeWithNext
5
35
5
6
0732bec04b39e3c8edd1a768e93d0c3ec05b0a10
bigcode/the-stack
train
6e148bb080d1ae8b464f4250
train
function
def connect(root: TreeNodeWithNext) -> TreeNodeWithNext: """Populate the 'next' pointer of each node in the tree specified by 'root'.""" if root is None: return root currParent = root while currParent is not None: # Connect the nodes in the level below 'currParent', i.e. #...
def connect(root: TreeNodeWithNext) -> TreeNodeWithNext:
"""Populate the 'next' pointer of each node in the tree specified by 'root'.""" if root is None: return root currParent = root while currParent is not None: # Connect the nodes in the level below 'currParent', i.e. # the level where the children of 'currParent' resides. ...
+ 1)) NULL_PLACEHOLDER = '#' nodes = [] for leftMostNode in leftMostNodes: curr = leftMostNode while curr is not None: nodes.append(curr.val) curr = curr.next nodes.append(NULL_PLACEHOLDER) return nodes def connect(roo...
79
79
265
15
63
ansonmiu0214/dsa-worked-solutions
solutions/populating_next_right_pointers_ii/solution.py
Python
connect
connect
37
75
37
37
f136c7cf952b26bc45870c83038a49f11727ffe1
bigcode/the-stack
train
9f7d03a00d8279f7d9109c41
train
function
def train(env_id, num_timesteps, seed=0): U.make_session(num_cpu=1).__enter__() def policy_fn(name, ob_space, ac_space): return cartpole_policy.CartPolePolicy(name=name, ob_space=ob_space, ac_space=ac_space, hid_size=6, num_hid_layers=2) env = make_muj...
def train(env_id, num_timesteps, seed=0):
U.make_session(num_cpu=1).__enter__() def policy_fn(name, ob_space, ac_space): return cartpole_policy.CartPolePolicy(name=name, ob_space=ob_space, ac_space=ac_space, hid_size=6, num_hid_layers=2) env = make_mujoco_env(env_id, seed) pi = pposgd_simp...
baselines.common.cmd_util import make_mujoco_env from baselines.common import tf_util as U from baselines import logger from baselines.ppo1 import pposgd_simple from cartpole.cartpole_sim import cartpole_policy def train(env_id, num_timesteps, seed=0):
64
64
179
13
50
mmolnar0/sgillen_research
old/cartpole_lib/cartpole_ppo.py
Python
train
train
9
26
9
9
c5f0a089d9ddbd9c354f98b637acc879ce102e98
bigcode/the-stack
train
05a625e60fa9c00f0a5923a7
train
function
@njit('i8(i8,i8,i8,i8)') def LMpM_index(ell, mp, m, ell_min): """Array index for given (ell,mp,m) mode Assuming an array (e.g., Wigner D matrices) in the order [[ell,mp,m] for ell in range(ell_min, ell_max+1) for mp in range(-ell,ell+1) for m in range(-ell,ell+1)] this...
@njit('i8(i8,i8,i8,i8)') def LMpM_index(ell, mp, m, ell_min):
"""Array index for given (ell,mp,m) mode Assuming an array (e.g., Wigner D matrices) in the order [[ell,mp,m] for ell in range(ell_min, ell_max+1) for mp in range(-ell,ell+1) for m in range(-ell,ell+1)] this function returns the index of the (ell,mp,m) element. (Note ...
2): for twom in range(-twoell, twoell + 1, 2): LMpM[i, 0] = twoell / 2 LMpM[i, 1] = twomp / 2 LMpM[i, 2] = twom / 2 i += 1 @njit('i8(i8,i8,i8,i8)') def LMpM_index(ell, mp, m, ell_min):
106
106
354
30
75
duetosymmetry/spherical_functions
spherical_functions/__init__.py
Python
LMpM_index
LMpM_index
239
262
239
240
2ff1ae25042af85d19b43e2e989da1988a3fa0e8
bigcode/the-stack
train
7b7a7e3c54b9e3d71e5dcd50
train
function
@njit('f8(i8,i8)') def binomial_coefficient(n, k): return _binomial_coefficients[(n * (n + 1)) // 2 + k]
@njit('f8(i8,i8)') def binomial_coefficient(n, k):
return _binomial_coefficients[(n * (n + 1)) // 2 + k]
('f8(i8)') def factorial(i): return factorials[i] # Binomial coefficients _binomial_coefficients = np.load(os.path.join(os.path.dirname(__file__), 'binomial_coefficients.npy')) @njit('f8(i8,i8)') def binomial_coefficient(n, k):
64
64
42
20
44
duetosymmetry/spherical_functions
spherical_functions/__init__.py
Python
binomial_coefficient
binomial_coefficient
51
53
51
52
e0135d4f4c4b4edf265e2227fc2dcc987c9550dd
bigcode/the-stack
train
191da616cb0a5b89ed348bd6
train
function
def LMpM_range_half_integer(ell_min, ell_max): """Array of (ell,mp,m) indices in standard order, including half-integer values This function returns an array of essentially [[twoell/2, twomp/2, twom/2] for twoell in range(2*ell_min, 2(ell_max+1) for twomp in range(-twoell, twoell+1, 2) for ...
def LMpM_range_half_integer(ell_min, ell_max):
"""Array of (ell,mp,m) indices in standard order, including half-integer values This function returns an array of essentially [[twoell/2, twomp/2, twom/2] for twoell in range(2*ell_min, 2(ell_max+1) for twomp in range(-twoell, twoell+1, 2) for twom in range(-twoell, twoell+1, 2)] See a...
, ell_max + 1): for mp in range(-ell, ell + 1): for m in range(-ell, ell + 1): LMpM[i, 0] = ell LMpM[i, 1] = mp LMpM[i, 2] = m i += 1 def LMpM_range_half_integer(ell_min, ell_max):
89
89
297
14
74
duetosymmetry/spherical_functions
spherical_functions/__init__.py
Python
LMpM_range_half_integer
LMpM_range_half_integer
205
225
205
205
37346fea6699f3901c627db9432ee4f9a8e53319
bigcode/the-stack
train
e4ada08819a7cffee6a2f5fa
train
function
@njit('void(i8,i8,i8[:,:])') def _LM_range(ell_min, ell_max, LM): i = 0 for ell in range(ell_min, ell_max + 1): for m in range(-ell, ell + 1): LM[i, 0] = ell LM[i, 1] = m i += 1
@njit('void(i8,i8,i8[:,:])') def _LM_range(ell_min, ell_max, LM):
i = 0 for ell in range(ell_min, ell_max + 1): for m in range(-ell, ell + 1): LM[i, 0] = ell LM[i, 1] = m i += 1
2) - ell_min ** 2 + 1, 2), dtype=int) _LM_range(ell_min, ell_max, LM) return LM @njit('void(i8,i8,i8[:,:])') def _LM_range(ell_min, ell_max, LM):
64
64
88
28
35
duetosymmetry/spherical_functions
spherical_functions/__init__.py
Python
_LM_range
_LM_range
105
112
105
106
a860d1512d67c572bc1beebbccaddbfc3518387a
bigcode/the-stack
train
790a5db5eccf41d75b82fcfb
train
function
def LM_range(ell_min, ell_max): """Array of (ell,m) indices in standard order This function returns an array of essentially [[ell,m] for ell in range(ell_min, ell_max+1) for m in range(-ell,ell+1)] This is, for example, the order assumed for mode data in the `waveforms` module. ...
def LM_range(ell_min, ell_max):
"""Array of (ell,m) indices in standard order This function returns an array of essentially [[ell,m] for ell in range(ell_min, ell_max+1) for m in range(-ell,ell+1)] This is, for example, the order assumed for mode data in the `waveforms` module. """ # # Sympy commands to ca...
omp, twom)] @njit('f8(f8,f8,f8)') def Wigner_coefficient(ell, mp, m): return _Wigner_coefficient(round(2*ell), round(2*mp), round(2*m)) def LM_range(ell_min, ell_max):
64
64
202
10
54
duetosymmetry/spherical_functions
spherical_functions/__init__.py
Python
LM_range
LM_range
84
102
84
84
6b6ab89ecea57f10e77d1969978372f72c158a3a
bigcode/the-stack
train
293067d60744f408bfc69bdf
train
function
@njit('i8(i8, i8)') def LMpM_total_size(ell_min, ell_max): """Total array size of Wigner D matrix Assuming an array (e.g., Wigner D matrices) in the order [[ell,mp,m] for ell in range(ell_min, ell_max+1) for mp in range(-ell,ell+1) for m in range(-ell,ell+1)] this func...
@njit('i8(i8, i8)') def LMpM_total_size(ell_min, ell_max):
"""Total array size of Wigner D matrix Assuming an array (e.g., Wigner D matrices) in the order [[ell,mp,m] for ell in range(ell_min, ell_max+1) for mp in range(-ell,ell+1) for m in range(-ell,ell+1)] this function returns the total size of that array. This can be...
ange that to act more nicely return (((4 * ell + 6) * ell + 6 * mp + 5) * ell + ell_min * (1 - 4 * ell_min ** 2) + 3 * (m + mp)) // 3 @njit('i8(i8, i8)') def LMpM_total_size(ell_min, ell_max):
84
84
280
25
58
duetosymmetry/spherical_functions
spherical_functions/__init__.py
Python
LMpM_total_size
LMpM_total_size
265
286
265
266
3a2909dbcd2918b23043a70266cf62cbb7e864dd
bigcode/the-stack
train
9f65140e1180a2a043972641
train
function
def theta_phi(n_theta, n_phi): """Construct (theta, phi) grid This grid is in the order expected by spinsfast Parameters ========== n_theta: int Number of points in the theta direction n_phi: int Number of points in the phi direction Returns ======= theta_phi_grid:...
def theta_phi(n_theta, n_phi):
"""Construct (theta, phi) grid This grid is in the order expected by spinsfast Parameters ========== n_theta: int Number of points in the theta direction n_phi: int Number of points in the phi direction Returns ======= theta_phi_grid: ndarray Array of pairs...
# We rearrange that to act more nicely return (((4 * ell_max + 12) * ell_max + 11) * ell_max + (-4 * ell_min ** 2 + 1) * ell_min + 3) // 3 def theta_phi(n_theta, n_phi):
64
64
171
9
54
duetosymmetry/spherical_functions
spherical_functions/__init__.py
Python
theta_phi
theta_phi
289
310
289
289
236c78b664d2534f0309a14f0394cd27982995f7
bigcode/the-stack
train
9902152e1c15daf34b27dfc6
train
function
def LMpM_range(ell_min, ell_max): """Array of (ell,mp,m) indices in standard order This function returns an array of essentially [[ell,mp,m] for ell in range(ell_min, ell_max+1) for mp in range(-ell,ell+1) for m in range(-ell,ell+1)] This is, for instance, the array of...
def LMpM_range(ell_min, ell_max):
"""Array of (ell,mp,m) indices in standard order This function returns an array of essentially [[ell,mp,m] for ell in range(ell_min, ell_max+1) for mp in range(-ell,ell+1) for m in range(-ell,ell+1)] This is, for instance, the array of indices of the Wigner D matrices ...
2 + 1 def LM_deduce_ell_max(size, ell_min=0): ell_max = int(np.sqrt(size + ell_min**2) - 1) if ell_max * (ell_max + 2) - ell_min ** 2 + 1 != size: raise ValueError(f"The input size {size} does not correspond to a possible array of modes with ell_min {ell_min}.") return ell_max def LMpM_range(ell_m...
107
107
358
12
94
duetosymmetry/spherical_functions
spherical_functions/__init__.py
Python
LMpM_range
LMpM_range
166
191
166
166
f6e2b4936b9a285dba29f183e4ad4194feb1e66f
bigcode/the-stack
train
8576e10b321148b555742d05
train
function
@njit('i8(i8,i8)') def LM_total_size(ell_min, ell_max): """Total array size of (ell,m) components Assuming an array of [[ell,m] for ell in range(ell_min, ell_max+1) for m in range(-ell,ell+1)] this function returns the total size of that array. This can be calculated in sympy as ...
@njit('i8(i8,i8)') def LM_total_size(ell_min, ell_max):
"""Total array size of (ell,m) components Assuming an array of [[ell,m] for ell in range(ell_min, ell_max+1) for m in range(-ell,ell+1)] this function returns the total size of that array. This can be calculated in sympy as from sympy import symbols, summation ell,ell_m...
*ell + 1, (ell, ell_min, ell-1)) + (ell+m) """ return ell * (ell + 1) - ell_min ** 2 + m @njit('i8(i8,i8)') def LM_total_size(ell_min, ell_max):
64
64
167
22
41
duetosymmetry/spherical_functions
spherical_functions/__init__.py
Python
LM_total_size
LM_total_size
138
156
138
139
c827bfb1dd2c9a757ba1307172adc9d59d9dec3d
bigcode/the-stack
train
05b7aa0694c9e4e853ae4d4d
train
function
@njit('f8(i8)') def factorial(i): return factorials[i]
@njit('f8(i8)') def factorial(i):
return factorials[i]
_coefficients.npy # Wigner_coefficients.npy # were originally produced with the code in `_generate_coefficients.py`. # Factorial factorials = np.array([float(factorial(i)) for i in range(171)]) @njit('f8(i8)') def factorial(i):
63
64
19
13
50
duetosymmetry/spherical_functions
spherical_functions/__init__.py
Python
factorial
factorial
43
45
43
44
86b21075471400622184566b688b9605756317b3
bigcode/the-stack
train
614073436a41c640296e46b4
train
function
@njit('f8(i8,i8,i8)') def _Wigner_coefficient(twoell, twomp, twom): return _Wigner_coefficients[_Wigner_index(twoell, twomp, twom)]
@njit('f8(i8,i8,i8)') def _Wigner_coefficient(twoell, twomp, twom):
return _Wigner_coefficients[_Wigner_index(twoell, twomp, twom)]
twoell + 1) // 6 + (twoell + twomp)//2 * (twoell + 1) + (twoell + twom)//2 @njit('f8(i8,i8,i8)') def _Wigner_coefficient(twoell, twomp, twom):
64
64
48
28
35
duetosymmetry/spherical_functions
spherical_functions/__init__.py
Python
_Wigner_coefficient
_Wigner_coefficient
75
77
75
76
5b72b8fba2bbeb3c56473ac12d732bcc2e986b35
bigcode/the-stack
train
e89c1cad1756488ca2468167
train
function
def LM_deduce_ell_max(size, ell_min=0): ell_max = int(np.sqrt(size + ell_min**2) - 1) if ell_max * (ell_max + 2) - ell_min ** 2 + 1 != size: raise ValueError(f"The input size {size} does not correspond to a possible array of modes with ell_min {ell_min}.") return ell_max
def LM_deduce_ell_max(size, ell_min=0):
ell_max = int(np.sqrt(size + ell_min**2) - 1) if ell_max * (ell_max + 2) - ell_min ** 2 + 1 != size: raise ValueError(f"The input size {size} does not correspond to a possible array of modes with ell_min {ell_min}.") return ell_max
_max', integer=True) summation(2*ell + 1, (ell, ell_min, ell_max)) """ return ell_max * (ell_max + 2) - ell_min ** 2 + 1 def LM_deduce_ell_max(size, ell_min=0):
64
64
90
15
48
duetosymmetry/spherical_functions
spherical_functions/__init__.py
Python
LM_deduce_ell_max
LM_deduce_ell_max
159
163
159
159
12f4a153b19c3569301866dddc3887336715bb7a
bigcode/the-stack
train
dc8c8c6333839401da54dd78
train
function
@njit('void(i8,i8,f8[:,:])') def _LMpM_range_half_integer(twoell_min, twoell_max, LMpM): i = 0 for twoell in range(twoell_min, twoell_max + 1): for twomp in range(-twoell, twoell + 1, 2): for twom in range(-twoell, twoell + 1, 2): LMpM[i, 0] = twoell / 2 LMpM[...
@njit('void(i8,i8,f8[:,:])') def _LMpM_range_half_integer(twoell_min, twoell_max, LMpM):
i = 0 for twoell in range(twoell_min, twoell_max + 1): for twomp in range(-twoell, twoell + 1, 2): for twom in range(-twoell, twoell + 1, 2): LMpM[i, 0] = twoell / 2 LMpM[i, 1] = twomp / 2 LMpM[i, 2] = twom / 2 i += 1
pM_range_half_integer(round(2*ell_min), round(2*ell_max), LMpM) return LMpM @njit('void(i8,i8,f8[:,:])') def _LMpM_range_half_integer(twoell_min, twoell_max, LMpM):
64
64
150
35
28
duetosymmetry/spherical_functions
spherical_functions/__init__.py
Python
_LMpM_range_half_integer
_LMpM_range_half_integer
227
236
227
228
4934844809feb1e3d6f0113a075995bf9981efcd
bigcode/the-stack
train
e9f01f25ed77ee795dc58c49
train
function
@njit('void(i8,i8,i8[:,:])') def _LMpM_range(ell_min, ell_max, LMpM): i = 0 for ell in range(ell_min, ell_max + 1): for mp in range(-ell, ell + 1): for m in range(-ell, ell + 1): LMpM[i, 0] = ell LMpM[i, 1] = mp LMpM[i, 2] = m i...
@njit('void(i8,i8,i8[:,:])') def _LMpM_range(ell_min, ell_max, LMpM):
i = 0 for ell in range(ell_min, ell_max + 1): for mp in range(-ell, ell + 1): for m in range(-ell, ell + 1): LMpM[i, 0] = ell LMpM[i, 1] = mp LMpM[i, 2] = m i += 1
3, 3), dtype=int) _LMpM_range(ell_min, ell_max, LMpM) return LMpM @njit('void(i8,i8,i8[:,:])') def _LMpM_range(ell_min, ell_max, LMpM):
64
64
121
32
31
duetosymmetry/spherical_functions
spherical_functions/__init__.py
Python
_LMpM_range
_LMpM_range
193
202
193
194
0a02a74c604b5546de310ce2faf44e84666b466a
bigcode/the-stack
train
11e223d5078780633d3e5ba2
train
function
@njit('f8(f8,f8)') def ladder_operator_coefficient(ell, m): return _ladder_operator_coefficient(round(2*ell), round(2*m))
@njit('f8(f8,f8)') def ladder_operator_coefficient(ell, m):
return _ladder_operator_coefficient(round(2*ell), round(2*m))
8,i8)') def _ladder_operator_coefficient(twoell, twom): return _ladder_operator_coefficients[((twoell + 2) * twoell + twom) // 2] @njit('f8(f8,f8)') def ladder_operator_coefficient(ell, m):
64
64
40
21
43
duetosymmetry/spherical_functions
spherical_functions/__init__.py
Python
ladder_operator_coefficient
ladder_operator_coefficient
63
65
63
64
5e7c5da20f43c0c1640b8fde8e53af7f91bac4b2
bigcode/the-stack
train
4d6aade9d66173ab18a1e5d0
train
function
@njit('i8(i8,i8,i8)') def LM_index(ell, m, ell_min): """Array index for given (ell,m) mode Assuming an array of [[ell,m] for ell in range(ell_min, ell_max+1) for m in range(-ell,ell+1)] this function returns the index of the (ell,m) element. (Note that ell_max doesn't actually come ...
@njit('i8(i8,i8,i8)') def LM_index(ell, m, ell_min):
"""Array index for given (ell,m) mode Assuming an array of [[ell,m] for ell in range(ell_min, ell_max+1) for m in range(-ell,ell+1)] this function returns the index of the (ell,m) element. (Note that ell_max doesn't actually come into this calculation, so it is not taken as an a...
): for m in range(-ell, ell + 1): LM[i, 0] = ell LM[i, 1] = m i += 1 @njit('i8(i8,i8,i8)') def LM_index(ell, m, ell_min):
64
64
202
24
39
duetosymmetry/spherical_functions
spherical_functions/__init__.py
Python
LM_index
LM_index
115
135
115
116
9c4edcd202bcf34218969a468dc9d27cdea2f822
bigcode/the-stack
train
8a0279495e24c9dc84eba2c4
train
function
@njit('f8(i8,i8)') def _ladder_operator_coefficient(twoell, twom): return _ladder_operator_coefficients[((twoell + 2) * twoell + twom) // 2]
@njit('f8(i8,i8)') def _ladder_operator_coefficient(twoell, twom):
return _ladder_operator_coefficients[((twoell + 2) * twoell + twom) // 2]
1)) // 2 + k] # Ladder-operator coefficients _ladder_operator_coefficients = np.load(os.path.join(os.path.dirname(__file__), 'ladder_operator_coefficients.npy')) @njit('f8(i8,i8)') def _ladder_operator_coefficient(twoell, twom):
64
64
50
24
40
duetosymmetry/spherical_functions
spherical_functions/__init__.py
Python
_ladder_operator_coefficient
_ladder_operator_coefficient
59
61
59
60
e33b857139ea0170c29273d441b0b6c72f634644
bigcode/the-stack
train
f7b32985570f838147376615
train
function
@njit('i8(i8,i8,i8)') def _Wigner_index(twoell, twomp, twom): return twoell*((2*twoell + 3)*twoell + 1) // 6 + (twoell + twomp)//2 * (twoell + 1) + (twoell + twom)//2
@njit('i8(i8,i8,i8)') def _Wigner_index(twoell, twomp, twom):
return twoell*((2*twoell + 3)*twoell + 1) // 6 + (twoell + twomp)//2 * (twoell + 1) + (twoell + twom)//2
)) # Coefficients used in constructing the Wigner D matrices _Wigner_coefficients = np.load(os.path.join(os.path.dirname(__file__), 'Wigner_coefficients.npy')) @njit('i8(i8,i8,i8)') def _Wigner_index(twoell, twomp, twom):
64
64
76
27
37
duetosymmetry/spherical_functions
spherical_functions/__init__.py
Python
_Wigner_index
_Wigner_index
71
73
71
72
60e9baaf7538675d105e8b099cc2dd02856c0f8f
bigcode/the-stack
train
4f5bb105ef773728c1eb8ddc
train
function
@njit('f8(f8,f8,f8)') def Wigner_coefficient(ell, mp, m): return _Wigner_coefficient(round(2*ell), round(2*mp), round(2*m))
@njit('f8(f8,f8,f8)') def Wigner_coefficient(ell, mp, m):
return _Wigner_coefficient(round(2*ell), round(2*mp), round(2*m))
8,i8)') def _Wigner_coefficient(twoell, twomp, twom): return _Wigner_coefficients[_Wigner_index(twoell, twomp, twom)] @njit('f8(f8,f8,f8)') def Wigner_coefficient(ell, mp, m):
64
64
49
25
39
duetosymmetry/spherical_functions
spherical_functions/__init__.py
Python
Wigner_coefficient
Wigner_coefficient
79
81
79
80
42d58ac1ce99611744331cd1dfa4be0b72b21a9d
bigcode/the-stack
train
c74be6dcd76c84cee0fc421d
train
class
class CacheControlMiddleware(BaseHTTPMiddleware): """Set Cache-Control header for any GET and HEAD requests. If header is set already by route handler or other middleware, not set by it. """ def __init__(self, app: ASGIApp, cache_control: CacheControl): """ :param cache_control: Setting...
class CacheControlMiddleware(BaseHTTPMiddleware):
"""Set Cache-Control header for any GET and HEAD requests. If header is set already by route handler or other middleware, not set by it. """ def __init__(self, app: ASGIApp, cache_control: CacheControl): """ :param cache_control: Setting Cache-Control object. """ super()...
Middleware for Cache-Control. """ from fastapi import Request, Response from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint from starlette.types import ASGIApp from .types import CacheControl CACHEABLE_METHODS = ["GET", "HEAD"] class CacheControlMiddleware(BaseHTTPMiddleware):
63
64
162
8
55
andrijaJ01/portfolio-fastapi
fastapi_cache/middleware.py
Python
CacheControlMiddleware
CacheControlMiddleware
13
34
13
13
aba62a2622bc4c612dcf35c373fdf4326b3ed835
bigcode/the-stack
train
24d415e62f7f14462f7e39cc
train
function
def compute_gain_profile(gain_zero, gain_tilting, freq): """ compute_gain_profile evaluates the gain at the frequencies freq. :param gain_zero: the gain at f=0 in dB. Scalar :param gain_tilting: the gain tilt in dB/THz. Scalar :param freq: the baseband frequencies at which the gain profile ...
def compute_gain_profile(gain_zero, gain_tilting, freq):
""" compute_gain_profile evaluates the gain at the frequencies freq. :param gain_zero: the gain at f=0 in dB. Scalar :param gain_tilting: the gain tilt in dB/THz. Scalar :param freq: the baseband frequencies at which the gain profile is computed in THz. Array :return: gain: the gain...
= 10 ** (-np.abs(attenuation_db_interp) / 10) g_nli_interp *= attenuation_lin_interp return g_nli_comp, f_nli_comp, g_nli_interp, f_nli_interp def compute_gain_profile(gain_zero, gain_tilting, freq):
64
64
120
15
48
zzfhao/gnpy-geant
gnpy/gnpy.py
Python
compute_gain_profile
compute_gain_profile
435
444
435
435
10787477a587c9e43627cc92ce491f89eaa4f1d6
bigcode/the-stack
train
69e4134e57ac28f3977da33b
train
function
def GN_integral(b2, Lspan, a_db, gam, f_ch, b_ch, roll_off, power, Nch, model_param): """ GN_integral computes the GN reference formula via smart brute force integration. The Gaussian Noise model is applied in its incoherent form (phased-array factor =1). The function computes the integral by columns: for each ...
def GN_integral(b2, Lspan, a_db, gam, f_ch, b_ch, roll_off, power, Nch, model_param):
""" GN_integral computes the GN reference formula via smart brute force integration. The Gaussian Noise model is applied in its incoherent form (phased-array factor =1). The function computes the integral by columns: for each f1, a non-uniformly spaced f2 array is generated, and the integrand function is co...
Nlog_short = np.ceil(np.log(fmax / np.abs(f_dense_up)) / np.log(k) + 1.0) f1_short = f_dense_up * np.power(k, np.arange(1, Nlog_short + 1.0) - 1.0) k = (Bopt / 2.0 + (abs(f_dense_low) + f_dense_low)) / (Bopt / 2.0 - max_step + (abs(f_dense_low) + f_dense_low)) Nlog_long = np.ceil(np.log((fmax +...
256
256
1,588
32
223
zzfhao/gnpy-geant
gnpy/gnpy.py
Python
GN_integral
GN_integral
104
197
104
104
aa5ea9f084c7ec3b2ab1d6fd22178ef0fc2ca692
bigcode/the-stack
train
2b9dadb90ae04cee8c6528dd
train
function
def change_component_ref(f_ref, link, fibers): """ it updates the reference frequency of OA gain, PC attenuation and fiber attenuation coefficient :param f_ref: the new reference frequency [THz]. Scalar :param link: the link structure. A list in which each element indicates one link component (PC, OA or fi...
def change_component_ref(f_ref, link, fibers):
""" it updates the reference frequency of OA gain, PC attenuation and fiber attenuation coefficient :param f_ref: the new reference frequency [THz]. Scalar :param link: the link structure. A list in which each element indicates one link component (PC, OA or fiber). List :param fibers: a dictionary cont...
count(1) roll_off = np.zeros(n_ch) b_eq = np.zeros(n_ch) power = np.zeros(n_ch) p_ase = np.zeros(n_ch) p_nli = np.zeros(n_ch) for index, signal in enumerate(spectrum['signals']): b_eq[index] = signal['b_ch'] roll_off[index] = signal['roll_off'] power[index] = signal['p_ch...
152
152
509
11
140
zzfhao/gnpy-geant
gnpy/gnpy.py
Python
change_component_ref
change_component_ref
684
736
684
684
cc6592dc8cd48ece22ad5a8fb565659dd46746e9
bigcode/the-stack
train
e1cfaa128fb99770bd362292
train
function
def compute_and_save_osnr(spectrum, flag_save=False, file_name='00', output_path='./output/'): """ Given the spectrum structure, the function returns the linear and non linear OSNR. If the boolean variable flag_save is true, the function also saves the osnr values for the central channel, the osnr for each chan...
def compute_and_save_osnr(spectrum, flag_save=False, file_name='00', output_path='./output/'):
""" Given the spectrum structure, the function returns the linear and non linear OSNR. If the boolean variable flag_save is true, the function also saves the osnr values for the central channel, the osnr for each channel and spectrum in a file with the name file_name, in the folder indicated by output_path ...
link[index]['gain'] = new_gain elif not component['comp_cat'] is 'fiber': error_string = 'Error in link structure: the ' + str(index+1) + '-th component have unknown category \n'\ + 'allowed values are (case sensitive): PC, OA and fiber' print(error_string)...
256
256
872
24
231
zzfhao/gnpy-geant
gnpy/gnpy.py
Python
compute_and_save_osnr
compute_and_save_osnr
739
809
739
739
bfafd4caed2b260bb261c1187169348e6549dd9a
bigcode/the-stack
train
2b37e127f3465b837f578a43
train
function
def compute_ase_noise(noise_fig, gain, central_freq, freq): """ compute_ase_noise evaluates the ASE spectral density at the frequencies freq. :param noise_fig: the amplifier noise figure in dB. Scalar :param gain: the gain profile in dB at the frequencies contained in freq array. Array :par...
def compute_ase_noise(noise_fig, gain, central_freq, freq):
""" compute_ase_noise evaluates the ASE spectral density at the frequencies freq. :param noise_fig: the amplifier noise figure in dB. Scalar :param gain: the gain profile in dB at the frequencies contained in freq array. Array :param central_freq: the central frequency of the WDM comb. Scal...
:param freq: the baseband frequencies at which the gain profile is computed in THz. Array :return: gain: the gain profile in dB """ gain = gain_zero + gain_tilting * freq return gain def compute_ase_noise(noise_fig, gain, central_freq, freq):
70
70
235
16
53
zzfhao/gnpy-geant
gnpy/gnpy.py
Python
compute_ase_noise
compute_ase_noise
447
464
447
447
decfcd8cda7d799c0431545fe38c4c392514b8e1
bigcode/the-stack
train
d87ad32f088e4e92dcf4a67f
train
function
def get_frequencies_wdm(spectrum, sys_param): """ the function computes the central frequency of the WDM comb and the frequency of each channel. :param spectrum: the WDM spectrum to be attenuated. List of dictionaries :param sys_param: a dictionary containing the system parameters: 'f0': th...
def get_frequencies_wdm(spectrum, sys_param):
""" the function computes the central frequency of the WDM comb and the frequency of each channel. :param spectrum: the WDM spectrum to be attenuated. List of dictionaries :param sys_param: a dictionary containing the system parameters: 'f0': the starting frequency, i.e the frequency of the...
st'] * fiber_length # Apply attenuation passive_component(spectrum, a_zero, a_tilting, f_ch) # Apply NLI if not control_param['is_linear']: for index, s in enumerate(spectrum['signals']): spectrum['signals'][index]['p_nli'] += p_nli[index] return None def get_frequencies_wdm(s...
88
88
294
12
75
zzfhao/gnpy-geant
gnpy/gnpy.py
Python
get_frequencies_wdm
get_frequencies_wdm
625
652
625
625
a63d74410cc5e86281cc59f03d4b885e58e348d0
bigcode/the-stack
train
15a54aecbf2b1448109ebcff
train
function
def fiber(spectrum, fiber_param, fiber_length, f_ch, b_ch, roll_off, control_param): """ fiber updates spectrum with the effects of the fiber :param spectrum: the WDM spectrum to be attenuated. List of dictionaries :param fiber_param: Dictionary with the parameters of the fiber fiber_param[...
def fiber(spectrum, fiber_param, fiber_length, f_ch, b_ch, roll_off, control_param):
""" fiber updates spectrum with the effects of the fiber :param spectrum: the WDM spectrum to be attenuated. List of dictionaries :param fiber_param: Dictionary with the parameters of the fiber fiber_param['alpha']: Fiber loss coeffiecient in dB/km. Scalar fiber_param['beta_...
z]. Scalar :param noise_fig: the noise figure of the amplifier [dB]. Scalar :param central_freq: the central frequency of the optical band [THz]. Scalar :param freq: the central frequency of each WDM channel [THz]. Array :param b_eq: the equivalent -3 dB bandwidth of each WDM channel [TH...
256
256
857
23
232
zzfhao/gnpy-geant
gnpy/gnpy.py
Python
fiber
fiber
552
622
552
552
5b4629f0e23fb98f63644cc86c7ca3f7761641c5
bigcode/the-stack
train
b917b6182d4eed6ecdfaa84d
train
function
def compute_edfa_profile(gain_zero, gain_tilting, noise_fig, central_freq, freq): """ compute_edfa_profile evaluates the gain profile and the ASE spectral density at the frequencies freq. :param gain_zero: the gain at f=0 in dB. Scalar :param gain_tilting: the gain tilt in dB/THz. Scalar :p...
def compute_edfa_profile(gain_zero, gain_tilting, noise_fig, central_freq, freq):
""" compute_edfa_profile evaluates the gain profile and the ASE spectral density at the frequencies freq. :param gain_zero: the gain at f=0 in dB. Scalar :param gain_tilting: the gain tilt in dB/THz. Scalar :param noise_fig: the amplifier noise figure in dB. Scalar :param central_fr...
10, noise_fig / 10.0) g_ase = (gain_lin - 1) * noise_fig_lin * planck * (central_freq + freq) return g_ase def compute_edfa_profile(gain_zero, gain_tilting, noise_fig, central_freq, freq):
64
64
213
22
41
zzfhao/gnpy-geant
gnpy/gnpy.py
Python
compute_edfa_profile
compute_edfa_profile
467
481
467
467
2d108a49fc7d38217a8d403046a3b1934cd71a31
bigcode/the-stack
train
979606361e682afa48799998
train
function
def get_f_computed_interp(f_ch, n_not_interp): """ get_f_computed_array returns the arrays containing the frequencies at which g_nli is computed and interpolated. :param f_ch: the overall frequency array. Array of size 1xnum_ch :param n_not_interp: the number of points at which g_nli has to be computed ...
def get_f_computed_interp(f_ch, n_not_interp):
""" get_f_computed_array returns the arrays containing the frequencies at which g_nli is computed and interpolated. :param f_ch: the overall frequency array. Array of size 1xnum_ch :param n_not_interp: the number of points at which g_nli has to be computed :return: f_nli_comp: the array containing the ...
# Conversion in linear units 1/km l_eff = (1.0 - np.exp(-2.0 * alpha_lin * l_span)) / (2.0 * alpha_lin) # Effective length l_eff_a = 1.0 / (2.0 * alpha_lin) # Asymptotic effective length g_nli = np.zeros(f_ch.size) for ind in np.arange(0, f_ch.size): g_nli[ind] = analytic_formula(ind, b2, l_e...
150
150
503
13
136
zzfhao/gnpy-geant
gnpy/gnpy.py
Python
get_f_computed_interp
get_f_computed_interp
279
320
279
279
6ba408a3c6c71e9d28bb116e98b71604f5063646
bigcode/the-stack
train
99824d6912df9a8a69e56ec6
train
function
def gn_analytic(b2, l_span, a_db, gam, f_ch, b_ch, power, n_ch): """ gn_analytic computes the GN reference formula via analytical solution. :param b2: Fiber dispersion coefficient in ps/THz/km. Scalar :param l_span: Fiber Span length in km. Scalar :param a_db: Fiber loss coefficient in dB/km. Scalar ...
def gn_analytic(b2, l_span, a_db, gam, f_ch, b_ch, power, n_ch):
""" gn_analytic computes the GN reference formula via analytical solution. :param b2: Fiber dispersion coefficient in ps/THz/km. Scalar :param l_span: Fiber Span length in km. Scalar :param a_db: Fiber loss coefficient in dB/km. Scalar :param gam: Fiber nonlinear coefficient in 1/W/km. Scalar :...
psi(b2, l_eff_a, f_ch, ind, n, b_ch) g_nli += g_ch[n] * ch_psd ** 2.0 * psi g_nli *= (16.0 / 27.0) * (gam * l_eff) ** 2.0 / (2.0 * np.pi * b2 * l_eff_a) return g_nli def gn_analytic(b2, l_span, a_db, gam, f_ch, b_ch, power, n_ch):
114
114
382
26
87
zzfhao/gnpy-geant
gnpy/gnpy.py
Python
gn_analytic
gn_analytic
255
276
255
255
619159f19e80a9c8767ecf68ec1f791fd2984ab0
bigcode/the-stack
train
bd71e6bf669c93c048afd576
train
function
def analytic_formula(ind, b2, l_eff, l_eff_a, gam, f_ch, g_ch, b_ch, n_ch): """ analytic_formula computes the analytical formula. :param ind: index of the channel at which g_nli is computed. Scalar :param b2: Fiber dispersion coefficient in ps/THz/km. Scalar :param l_eff: Effective length in km. Scalar...
def analytic_formula(ind, b2, l_eff, l_eff_a, gam, f_ch, g_ch, b_ch, n_ch):
""" analytic_formula computes the analytical formula. :param ind: index of the channel at which g_nli is computed. Scalar :param b2: Fiber dispersion coefficient in ps/THz/km. Scalar :param l_eff: Effective length in km. Scalar :param l_eff_a: Asymptotic effective length in km. Scalar :param ga...
np.arcsinh(np.pi ** 2.0 * l_eff_a * b2 * b_ch_sig * (del_f + 0.5 * b_ch_int)) psi -= np.arcsinh(np.pi ** 2.0 * l_eff_a * b2 * b_ch_sig * (del_f - 0.5 * b_ch_int)) return psi def analytic_formula(ind, b2, l_eff, l_eff_a, gam, f_ch, g_ch, b_ch, n_ch):
108
108
362
29
78
zzfhao/gnpy-geant
gnpy/gnpy.py
Python
analytic_formula
analytic_formula
228
252
228
228
81c28b040277f0001197905b6e78140155ea836a
bigcode/the-stack
train
040c3f5919af8240d42a7c12
train
function
def compute_psi(b2, l_eff_a, f_ch, channel_index, interfering_index, b_ch): """ compute_psi computes the psi coefficient of the analytical formula. :param b2: Fiber dispersion coefficient in ps/THz/km. Scalar :param l_eff_a: Asymptotic effective length in km. Scalar :param f_ch: Baseband channels cente...
def compute_psi(b2, l_eff_a, f_ch, channel_index, interfering_index, b_ch):
""" compute_psi computes the psi coefficient of the analytical formula. :param b2: Fiber dispersion coefficient in ps/THz/km. Scalar :param l_eff_a: Asymptotic effective length in km. Scalar :param f_ch: Baseband channels center frequencies in THz. Array of size 1xNch :param channel_index: Index of...
f_ind += 1 # Compute outer integral. Nominal span loss already compensated GNLI[f_ind_eval] = 16.0 / 27.0 * gam * gam * np.trapz(Gpart, f1_array) f_ind_eval += 1 # Next frequency return GNLI # Return GNLI array in W/THz and the array of the corresponding frequencies def com...
111
111
372
23
87
zzfhao/gnpy-geant
gnpy/gnpy.py
Python
compute_psi
compute_psi
200
225
200
200
94b4e4390f167ccc83cd2f89f91d0d08686c1258
bigcode/the-stack
train
7998c551d5603f20d8b72289
train
function
def interpolate_in_range(x, y, x_new, kind_interp): """ Given some samples y of the function y(x), interpolate_in_range returns the interpolation of values y(x_new) :param x: The points at which y(x) is evaluated. Array :param y: The values of y(x). Array :param x_new: The values at which y(x) has to b...
def interpolate_in_range(x, y, x_new, kind_interp):
""" Given some samples y of the function y(x), interpolate_in_range returns the interpolation of values y(x_new) :param x: The points at which y(x) is evaluated. Array :param y: The values of y(x). Array :param x_new: The values at which y(x) has to be interpolated. Array :param kind_interp: The in...
_ch) index = np.searchsorted(f_ch_sorted, f_nli_comp) f_nli_interp = np.array(f_ch, copy=True) f_nli_interp = np.delete(f_nli_interp, index) return f_nli_comp, f_nli_interp def interpolate_in_range(x, y, x_new, kind_interp):
72
72
242
14
57
zzfhao/gnpy-geant
gnpy/gnpy.py
Python
interpolate_in_range
interpolate_in_range
323
343
323
323
584cfd03e4bd0f061eacf66f68e3cd4ad2ecde51
bigcode/the-stack
train
e9067906f520c559fa307f45
train
function
def raised_cosine_comb(f, rs, roll_off, center_freq, power): """ Returns an array storing the PSD of a WDM comb of raised cosine shaped channels at the input frequencies defined in array f :param f: Array of frequencies in THz :param rs: Array of Symbol Rates in TBaud. One Symbol rate for each channel ...
def raised_cosine_comb(f, rs, roll_off, center_freq, power):
""" Returns an array storing the PSD of a WDM comb of raised cosine shaped channels at the input frequencies defined in array f :param f: Array of frequencies in THz :param rs: Array of Symbol Rates in TBaud. One Symbol rate for each channel :param roll_off: Array of roll-off factors [0,1). One per...
TBD>@<TBD>.com' __version__ = '0.1.0' import numpy as np import multiprocessing as mp import scipy.interpolate as interp """ GNPy: a Python 3 implementation of the Gaussian Noise (GN) Model of nonlinear propagation, developed by the OptCom group, Department of Electronics and Telecommunications, Politecnico di Torino...
124
125
418
17
107
zzfhao/gnpy-geant
gnpy/gnpy.py
Python
raised_cosine_comb
raised_cosine_comb
22
53
22
22
f465c58fe208fec2430fce3d962aeb7ba1de2520
bigcode/the-stack
train
e49c5c09d55296f65879c7a7
train
function
def passive_component(spectrum, a_zero, a_tilting, freq): """passive_component updates the input spectrum with the attenuation described by a_zero and a_tilting :param spectrum: the WDM spectrum to be attenuated. List of dictionaries :param a_zero: attenuation at the central frequency [dB]. Scalar :par...
def passive_component(spectrum, a_zero, a_tilting, freq):
"""passive_component updates the input spectrum with the attenuation described by a_zero and a_tilting :param spectrum: the WDM spectrum to be attenuated. List of dictionaries :param a_zero: attenuation at the central frequency [dB]. Scalar :param a_tilting: attenuation tilting [dB/THz]. Scalar :pa...
if len(freq): attenuation = a_zero + a_tilting * freq # abs in order to avoid ambiguity due to the sign convention attenuation = abs(attenuation) else: attenuation = [] return attenuation def passive_component(spectrum, a_zero, a_tilting, freq):
67
67
224
16
50
zzfhao/gnpy-geant
gnpy/gnpy.py
Python
passive_component
passive_component
504
521
504
504
7b5d44e0dacc38fe5e8c93b31d88f79dc843eef0
bigcode/the-stack
train
566b0978e374ca692fab4824
train
function
def gn_model(spectrum_param, fiber_param, accuracy_param, n_cores): """ gn_model can compute the gn model both analytically or through the smart brute force integral. :param spectrum_param: Dictionary with spectrum parameters spectrum_param['num_ch']: Number of channels. Scalar ...
def gn_model(spectrum_param, fiber_param, accuracy_param, n_cores):
""" gn_model can compute the gn model both analytically or through the smart brute force integral. :param spectrum_param: Dictionary with spectrum parameters spectrum_param['num_ch']: Number of channels. Scalar spectrum_param['f_ch']: Baseband channels ...
_range(x, y, x_new, kind_interp): """ Given some samples y of the function y(x), interpolate_in_range returns the interpolation of values y(x_new) :param x: The points at which y(x) is evaluated. Array :param y: The values of y(x). Array :param x_new: The values at which y(x) has to be interpolated. Ar...
256
256
1,089
17
238
zzfhao/gnpy-geant
gnpy/gnpy.py
Python
gn_model
gn_model
346
432
346
346
a662dce1ef572912380dd40e25d4406fffd5022c
bigcode/the-stack
train
6cb15dce26efc943fac29309
train
function
def optical_amplifier(spectrum, gain_zero, gain_tilting, noise_fig, central_freq, freq, b_eq): """optical_amplifier updates the input spectrum with the gain described by gain_zero and gain_tilting plus ASE noise :param spectrum: the WDM spectrum to be attenuated. List of dictionaries :param gain_ze...
def optical_amplifier(spectrum, gain_zero, gain_tilting, noise_fig, central_freq, freq, b_eq):
"""optical_amplifier updates the input spectrum with the gain described by gain_zero and gain_tilting plus ASE noise :param spectrum: the WDM spectrum to be attenuated. List of dictionaries :param gain_zero: gain at the central frequency [dB]. Scalar :param gain_tilting: gain tilting [dB/TH...
abs(attenuation_db), 10.0) for index, s in enumerate(spectrum['signals']): spectrum['signals'][index]['p_ch'] *= attenuation_lin[index] spectrum['signals'][index]['p_nli'] *= attenuation_lin[index] spectrum['signals'][index]['p_ase'] *= attenuation_lin[index] return None def optical_am...
101
101
338
27
73
zzfhao/gnpy-geant
gnpy/gnpy.py
Python
optical_amplifier
optical_amplifier
524
549
524
524
cd7d66353f11e8a09e7e06985390b040ecd42e49
bigcode/the-stack
train
4202a753ba4ec0d94266a5aa
train
function
def get_freqarray(f, Bopt, fmax, max_step, f_dense_low, f_dense_up, df_dense): """ Returns a non-uniformly spaced frequency array useful for fast GN-model. integration. The frequency array is made of a denser area, sided by two log-spaced arrays :param f: Central frequency at which NLI is evaluated in T...
def get_freqarray(f, Bopt, fmax, max_step, f_dense_low, f_dense_up, df_dense):
""" Returns a non-uniformly spaced frequency array useful for fast GN-model. integration. The frequency array is made of a denser area, sided by two log-spaced arrays :param f: Central frequency at which NLI is evaluated in THz :param Bopt: Total optical bandwidth of the system in THz :param fma...
return psd def fwm_eff(a, Lspan, b2, ff): """ Computes the four-wave mixing efficiency given the fiber characteristics over a given frequency set ff :param a: Fiber loss coefficient in 1/km :param Lspan: Fiber length in km :param b2: Fiber Dispersion coefficient in ps/THz/km :param ff: A...
216
216
721
26
189
zzfhao/gnpy-geant
gnpy/gnpy.py
Python
get_freqarray
get_freqarray
70
101
70
70
e54b3da005b15001c2aaaf6e5788a1d0727e977a
bigcode/the-stack
train
3d80ad1dbd3a3996f556da77
train
function
def ole(spectrum, link, fibers, sys_param, control_param, output_path='./output/'): """ The function takes the input spectrum, the link description, the fiber description, the system parameters, the control parameters and a string describing the destination folder of the output files. After the function is ...
def ole(spectrum, link, fibers, sys_param, control_param, output_path='./output/'):
""" The function takes the input spectrum, the link description, the fiber description, the system parameters, the control parameters and a string describing the destination folder of the output files. After the function is executed the spectrum is updated with all the impairments of the link. The function ...
_nli_db = 10 * np.log10(osnr_nli) # Save spectrum, the non linear OSNR and the linear OSNR out_fle_name = output_path + file_name if flag_save: f = open(out_fle_name, 'w') f.write(''.join(('# Output parameters. The values of OSNR are evaluated in the -3 dB channel band', '\n\n'))) ...
256
256
1,219
21
234
zzfhao/gnpy-geant
gnpy/gnpy.py
Python
ole
ole
812
904
812
812
288927b7416ae64bc1264f14b49d231cdb067c32
bigcode/the-stack
train
a85406bbaae55987aaa22382
train
function
def get_spectrum_param(spectrum): """ the function returns the number of WDM channels and 3 arrays containing the power, the equivalent bandwidth and the roll off of each WDM channel. :param spectrum: the WDM spectrum to be attenuated. List of dictionaries :return: power: the power of each WDM channel...
def get_spectrum_param(spectrum):
""" the function returns the number of WDM channels and 3 arrays containing the power, the equivalent bandwidth and the roll off of each WDM channel. :param spectrum: the WDM spectrum to be attenuated. List of dictionaries :return: power: the power of each WDM channel [W] :return: b_eq: the equiva...
band frequencies n_ch = spectrum['laser_position'].count(1) f_ch = np.zeros(n_ch) count = 0 for index, bool_laser in enumerate(spectrum['laser_position']): if bool_laser: f_ch[count] = (f0 - f_cent) + delta_f * index count += 1 return f_cent, f_ch def get_spectrum_pa...
93
93
310
8
84
zzfhao/gnpy-geant
gnpy/gnpy.py
Python
get_spectrum_param
get_spectrum_param
655
681
655
655
9222af2dae1759f8786112ef83fa1d9d40d32489
bigcode/the-stack
train
89e0d1273d4cb908661ab34e
train
function
def fwm_eff(a, Lspan, b2, ff): """ Computes the four-wave mixing efficiency given the fiber characteristics over a given frequency set ff :param a: Fiber loss coefficient in 1/km :param Lspan: Fiber length in km :param b2: Fiber Dispersion coefficient in ps/THz/km :param ff: Array of Frequency p...
def fwm_eff(a, Lspan, b2, ff):
""" Computes the four-wave mixing efficiency given the fiber characteristics over a given frequency set ff :param a: Fiber loss coefficient in 1/km :param Lspan: Fiber length in km :param b2: Fiber Dispersion coefficient in ps/THz/km :param ff: Array of Frequency points in THz :return: FWM e...
roll_off[ind] * tf)) * np.where(tf > 0, 1., 0.) * np.where(np.abs(ff) <= stopband, 1., 0.)) + psd return psd def fwm_eff(a, Lspan, b2, ff):
64
64
184
14
49
zzfhao/gnpy-geant
gnpy/gnpy.py
Python
fwm_eff
fwm_eff
56
67
56
56
0e3bc60491174c9a3e00f8fe1cc335bb91b5a5ea
bigcode/the-stack
train
ea09a0ba89f35b3a1413e9e8
train
function
def compute_attenuation_profile(a_zero, a_tilting, freq): """compute_attenuation_profile returns the attenuation profile at the frequencies freq :param a_zero: the attenuation [dB] @ the baseband central frequency. Scalar :param a_tilting: the attenuation tilt in dB/THz. Scalar :param freq: the baseban...
def compute_attenuation_profile(a_zero, a_tilting, freq):
"""compute_attenuation_profile returns the attenuation profile at the frequencies freq :param a_zero: the attenuation [dB] @ the baseband central frequency. Scalar :param a_tilting: the attenuation tilt in dB/THz. Scalar :param freq: the baseband frequencies at which attenuation is computed [THz]. Arra...
""" gain = compute_gain_profile(gain_zero, gain_tilting, freq) g_ase = compute_ase_noise(noise_fig, gain, central_freq, freq) return gain, g_ase def compute_attenuation_profile(a_zero, a_tilting, freq):
64
64
159
16
47
zzfhao/gnpy-geant
gnpy/gnpy.py
Python
compute_attenuation_profile
compute_attenuation_profile
484
501
484
484
a925b8b38d03efbecbe6862ff62c5c679f081236
bigcode/the-stack
train
6d5db8fb78833c594deee343
train
function
@app.route('/login', methods=['GET', 'POST']) def login(): return 'HTTP POST REQUEST' if request.method == 'POST' else 'HTTP GET REQUEST'
@app.route('/login', methods=['GET', 'POST']) def login():
return 'HTTP POST REQUEST' if request.method == 'POST' else 'HTTP GET REQUEST'
(the protocol web applications are speaking) knows different methods for accessing URLs. By default, a route only answers to GET requests, but that can be changed by providing the methods argument to the route() decorator. Here are some examples: """ @app.route('/login', methods=['GET', 'POST']) def login():
64
64
35
15
49
all3g/pieces
flask/flask-HTTP_Method.py
Python
login
login
17
19
17
18
8ef0c2b2f0e34457c61f7e14c7800cdbdaddcfc1
bigcode/the-stack
train
9ed97c54eee519e519d3c0e8
train
function
def flip_predictions(predictions, shapes): flipped_preds = [] for pred, shape in zip(predictions, shapes): pred = menpo.shape.PointCloud(pred) if pred.points.shape[0] == 68: pred = utils.mirror_landmarks_68(pred, shape) elif pred.points.shape[0] == 73: pred =...
def flip_predictions(predictions, shapes):
flipped_preds = [] for pred, shape in zip(predictions, shapes): pred = menpo.shape.PointCloud(pred) if pred.points.shape[0] == 68: pred = utils.mirror_landmarks_68(pred, shape) elif pred.points.shape[0] == 73: pred = utils.mirror_landmarks_73(pred, shape) ...
, box.height]) fig.canvas.draw() data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='') data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,)) plt.clf() return data def flip_predictions(predictions, shapes):
63
64
107
8
54
pw1316/ShuffleV2-Face-Alignment
archive/mdm-32-32-wobn-rnn/mdm_eval.py
Python
flip_predictions
flip_predictions
51
62
51
51
0dba5d3a30ebf5dacbfc86c3acc9ce7bbc7fcdee
bigcode/the-stack
train
6047b4bd66020a1f50406396
train
function
def evaluate(): with tf.Graph().as_default(), tf.device('/cpu:0'): path_base = Path(g_config['eval_dataset']).parent.parent _mean_shape = mio.import_pickle(path_base / 'reference_shape.pkl') def decode_feature(serialized): feature = { 'test/image': tf.FixedLenFea...
def evaluate():
with tf.Graph().as_default(), tf.device('/cpu:0'): path_base = Path(g_config['eval_dataset']).parent.parent _mean_shape = mio.import_pickle(path_base / 'reference_shape.pkl') def decode_feature(serialized): feature = { 'test/image': tf.FixedLenFeature([], tf.stri...
fig = plt.figure() fig.add_subplot(111) plot_cumulative_error_distribution(errors, legend_entries=method_names, error_range=(0, 0.09, 0.005)) # shift the main graph to make room for the legend ax = plt.gca() box = ax.get_position() ax.set_position([box....
256
256
1,691
3
253
pw1316/ShuffleV2-Face-Alignment
archive/mdm-32-32-wobn-rnn/mdm_eval.py
Python
evaluate
evaluate
65
223
65
65
227417a645ecef1fcc04b648214f72b7f58f2435
bigcode/the-stack
train
645c95f062805a5dbfb1360a
train
function
def plot_ced(errors, method_names=['MDM']): from menpofit.visualize import plot_cumulative_error_distribution # plot the ced and store it at the root. fig = plt.figure() fig.add_subplot(111) plot_cumulative_error_distribution(errors, legend_entries=method_names, ...
def plot_ced(errors, method_names=['MDM']):
from menpofit.visualize import plot_cumulative_error_distribution # plot the ced and store it at the root. fig = plt.figure() fig.add_subplot(111) plot_cumulative_error_distribution(errors, legend_entries=method_names, error_range=(0, 0.09, 0.005)) # shift ...
with open(tf.flags.FLAGS.c, 'r') as g_config: g_config = json.load(g_config) for k in g_config: print(k, type(g_config[k]), g_config[k]) input('OK?(Y/N): ') def plot_ced(errors, method_names=['MDM']):
63
64
184
12
51
pw1316/ShuffleV2-Face-Alignment
archive/mdm-32-32-wobn-rnn/mdm_eval.py
Python
plot_ced
plot_ced
33
48
33
33
732a87c5df3a9325f778c1ef90183884ac45e8ea
bigcode/the-stack
train
c023baea5bf53ecf14097f2d
train
function
def test_create_product(): output = str(subprocess.check_output("python create_product.py", shell=True)) assert re.match(".*create product request.*", output) assert re.match(".*created product.*", output) assert re.match( '.*name: "projects/.+/locations/global/catalogs/default_catalog/branches...
def test_create_product():
output = str(subprocess.check_output("python create_product.py", shell=True)) assert re.match(".*create product request.*", output) assert re.match(".*created product.*", output) assert re.match( '.*name: "projects/.+/locations/global/catalogs/default_catalog/branches/0/products/.*', ou...
to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re import subprocess def test_create_prod...
64
64
110
5
58
tetiana-karasova/python-retail
samples/interactive-tutorials/product/create_product_test.py
Python
test_create_product
test_create_product
19
29
19
19
7ecaeceb9778b7149baa7933e2548efbeafe1bbd
bigcode/the-stack
train
edb4dcd3ad284dc854aaa6c9
train
function
def is_RandomVariable(X): return isinstance(X, RandomVariable_generic)
def is_RandomVariable(X):
return isinstance(X, RandomVariable_generic)
.rings.rational_field import is_RationalField from sage.sets.set import Set ################################################################################ ################################################################################ def is_ProbabilitySpace(S): return isinstance(S, ProbabilitySpace_generic) ...
64
64
16
7
57
vbraun/sage
src/sage/probability/random_variable.py
Python
is_RandomVariable
is_RandomVariable
34
35
34
34
f11990d3ebecaa538c3e6ee9bc914f3da95f60cf
bigcode/the-stack
train
1ac5ed9dd5b19ea208125f04
train
class
class DiscreteRandomVariable(RandomVariable_generic): """ A random variable on a discrete probability space. """ def __init__(self, X, f, codomain = None, check = False): r""" Create free binary string monoid on `n` generators. INPUT: x: A probability space f: A dictionary such ...
class DiscreteRandomVariable(RandomVariable_generic):
""" A random variable on a discrete probability space. """ def __init__(self, X, f, codomain = None, check = False): r""" Create free binary string monoid on `n` generators. INPUT: x: A probability space f: A dictionary such that X[x] = value for x in X is the discrete f...
_mpfr import (RealField, is_RealField) from sage.rings.rational_field import is_RationalField from sage.sets.set import Set ################################################################################ ################################################################################ def is_ProbabilitySpace(S): ...
256
256
1,801
9
246
vbraun/sage
src/sage/probability/random_variable.py
Python
DiscreteRandomVariable
DiscreteRandomVariable
67
273
67
67
e521b8e8596eaea59cb319974a1ed2159cbdd7d0
bigcode/the-stack
train
4d923f2ee9285c4943bb7c7f
train
class
class ProbabilitySpace_generic(RandomVariable_generic): r""" A probability space. """ def __init__(self, domain, RR): """ A generic probability space on given domain space and codomain ring. """ if isinstance(domain, list): domain = tuple(domain) ...
class ProbabilitySpace_generic(RandomVariable_generic):
r""" A probability space. """ def __init__(self, domain, RR): """ A generic probability space on given domain space and codomain ring. """ if isinstance(domain, list): domain = tuple(domain) if not isinstance(domain, tuple): raise T...
sigY = other.translation_standard_deviation(map) if sigX == 0 or sigY == 0: raise ValueError("Correlation not defined if standard deviations are not both nonzero.") return cov/(sigX*sigY) ################################################################################ ##############...
64
64
126
8
55
vbraun/sage
src/sage/probability/random_variable.py
Python
ProbabilitySpace_generic
ProbabilitySpace_generic
278
295
278
278
cc9a1147c579f45b3dd9ca9e952990aa7d371846
bigcode/the-stack
train
2f50cb1d044b706f325688d4
train
function
def is_ProbabilitySpace(S): return isinstance(S, ProbabilitySpace_generic)
def is_ProbabilitySpace(S):
return isinstance(S, ProbabilitySpace_generic)
from sage.functions.log import log from sage.functions.all import sqrt from sage.rings.real_mpfr import (RealField, is_RealField) from sage.rings.rational_field import is_RationalField from sage.sets.set import Set ################################################################################ ######################...
64
64
16
7
56
vbraun/sage
src/sage/probability/random_variable.py
Python
is_ProbabilitySpace
is_ProbabilitySpace
28
29
28
28
7810c84b3e657a3218d63a16649f8b37871aa5ff
bigcode/the-stack
train
1d4cb3d6fa3b7b28deaff13c
train
function
def is_DiscreteProbabilitySpace(S): return isinstance(S, DiscreteProbabilitySpace)
def is_DiscreteProbabilitySpace(S):
return isinstance(S, DiscreteProbabilitySpace)
.rings.real_mpfr import (RealField, is_RealField) from sage.rings.rational_field import is_RationalField from sage.sets.set import Set ################################################################################ ################################################################################ def is_ProbabilitySpa...
64
64
18
8
56
vbraun/sage
src/sage/probability/random_variable.py
Python
is_DiscreteProbabilitySpace
is_DiscreteProbabilitySpace
31
32
31
31
f414e63bc77fed8d6141d40b959a33ddae702e9f
bigcode/the-stack
train
160dd33733f5912efadd47ba
train
class
class DiscreteProbabilitySpace(ProbabilitySpace_generic,DiscreteRandomVariable): r""" The discrete probability space """ def __init__(self, X, P, codomain = None, check = False): r""" Create the discrete probability space with probabilities on the space X given by the dictionary ...
class DiscreteProbabilitySpace(ProbabilitySpace_generic,DiscreteRandomVariable):
r""" The discrete probability space """ def __init__(self, X, P, codomain = None, check = False): r""" Create the discrete probability space with probabilities on the space X given by the dictionary P with values in the field real_field. EXAMPLES:: s...
other under map. """ cov = self.translation_covariance(other, map) sigX = self.standard_deviation() sigY = other.translation_standard_deviation(map) if sigX == 0 or sigY == 0: raise ValueError("Correlation not defined if standard deviations are not both nonzero.") ...
222
222
740
14
207
vbraun/sage
src/sage/probability/random_variable.py
Python
DiscreteProbabilitySpace
DiscreteProbabilitySpace
297
367
297
297
d50fb3775dd8423aa5cb7cfb417c35554756c99a
bigcode/the-stack
train
24e4d20670966657521cafa7
train
function
def is_DiscreteRandomVariable(X): return isinstance(X, DiscreteRandomVariable)
def is_DiscreteRandomVariable(X):
return isinstance(X, DiscreteRandomVariable)
Set ################################################################################ ################################################################################ def is_ProbabilitySpace(S): return isinstance(S, ProbabilitySpace_generic) def is_DiscreteProbabilitySpace(S): return isinstance(S, DiscretePr...
64
64
18
8
56
vbraun/sage
src/sage/probability/random_variable.py
Python
is_DiscreteRandomVariable
is_DiscreteRandomVariable
37
38
37
37
98510dd1ea452bf5ba5db7c5d9a3da5387998f0e
bigcode/the-stack
train
e19bd1045b5e40e8a90f7f0a
train
class
class RandomVariable_generic(ParentWithBase): """ A random variable. """ def __init__(self, X, RR): if not is_ProbabilitySpace(X): raise TypeError("Argument X (= %s) must be a probability space" % X) ParentWithBase.__init__(self, X) self._codomain = RR def probab...
class RandomVariable_generic(ParentWithBase):
""" A random variable. """ def __init__(self, X, RR): if not is_ProbabilitySpace(X): raise TypeError("Argument X (= %s) must be a probability space" % X) ParentWithBase.__init__(self, X) self._codomain = RR def probability_space(self): return self.base() ...
Space) def is_RandomVariable(X): return isinstance(X, RandomVariable_generic) def is_DiscreteRandomVariable(X): return isinstance(X, DiscreteRandomVariable) ################################################################################ #######################################################################...
64
64
123
9
54
vbraun/sage
src/sage/probability/random_variable.py
Python
RandomVariable_generic
RandomVariable_generic
45
65
45
45
cea142780c288572b20c3845e9d3fca9f9f2f391
bigcode/the-stack
train
e4e8005001d4011ce51854c5
train
function
def predict_next_day(model, scaler, dataset_raw, testPredict): futurePredict = model.predict(np.asarray([[testPredict[-1]]])) futurePredict = scaler.inverse_transform(futurePredict) testPredict = scaler.inverse_transform(testPredict) # Predict value for the next day print ('Bitcoin value for tomorrow : ', futureP...
def predict_next_day(model, scaler, dataset_raw, testPredict):
futurePredict = model.predict(np.asarray([[testPredict[-1]]])) futurePredict = scaler.inverse_transform(futurePredict) testPredict = scaler.inverse_transform(testPredict) # Predict value for the next day print ('Bitcoin value for tomorrow : ', futurePredict)
Sequential() model.add(LSTM(4, input_shape=(1,1))) model.add(Dense(1)) model.compile(loss='mean_squared_error', optimizer='adam') return model def save_model(model, model_path): model.save(model_path) def predict_next_day(model, scaler, dataset_raw, testPredict):
64
64
70
14
50
Neemys/BigCoin
machine_learning/machine_learning_neural_network.py
Python
predict_next_day
predict_next_day
54
60
54
54
86d05306684ba13b3f957039cb3c5e0a34d5d128
bigcode/the-stack
train
6240ae77a134894b5f6721dc
train
function
def create_dataset(dataset): dataX, dataY = [], [] for i in range(len(dataset)-1): dataX.append(dataset[i]) dataY.append(dataset[i + 1]) return np.asarray(dataX), np.asarray(dataY)
def create_dataset(dataset):
dataX, dataY = [], [] for i in range(len(dataset)-1): dataX.append(dataset[i]) dataY.append(dataset[i + 1]) return np.asarray(dataX), np.asarray(dataY)
_bitcoin = 'https://api.coindesk.com/v1/bpi/historical/close.json?currency='+currency+'&start='+start_date+'&end='+end_date res = requests.get(url_cours_bitcoin) if res.ok: return res else: return None def create_dataset(dataset):
64
64
53
5
58
Neemys/BigCoin
machine_learning/machine_learning_neural_network.py
Python
create_dataset
create_dataset
37
42
37
37
5cc7c252a64a4af7c9e63a267e26f5e9cac12d94
bigcode/the-stack
train
d5b556afc59ea49df99d6dda
train
function
def get_historique_data(currency, start_date, end_date): url_cours_bitcoin = 'https://api.coindesk.com/v1/bpi/historical/close.json?currency='+currency+'&start='+start_date+'&end='+end_date res = requests.get(url_cours_bitcoin) if res.ok: return res else: return None
def get_historique_data(currency, start_date, end_date):
url_cours_bitcoin = 'https://api.coindesk.com/v1/bpi/historical/close.json?currency='+currency+'&start='+start_date+'&end='+end_date res = requests.get(url_cours_bitcoin) if res.ok: return res else: return None
.datetime.strptime(date_str, "%Y-%m-%d") next_day = date + timedelta(days=1) next_date_str = next_day.strftime("%Y-%m-%d") return next_date_str # Retrieve data from CoinDesk API def get_historique_data(currency, start_date, end_date):
64
64
77
15
48
Neemys/BigCoin
machine_learning/machine_learning_neural_network.py
Python
get_historique_data
get_historique_data
29
35
29
29
501dfd72b9a655125e1131d0c372501e58d228e6
bigcode/the-stack
train
30b61cc273bca1a9d4fa685f
train
function
def save_model(model, model_path): model.save(model_path)
def save_model(model, model_path):
model.save(model_path)
return np.asarray(dataX), np.asarray(dataY) def create_LSTM_network(): model = Sequential() model.add(LSTM(4, input_shape=(1,1))) model.add(Dense(1)) model.compile(loss='mean_squared_error', optimizer='adam') return model def save_model(model, model_path):
64
64
13
8
55
Neemys/BigCoin
machine_learning/machine_learning_neural_network.py
Python
save_model
save_model
51
52
51
51
19359cb8b2a8f70a2fe642b16cd24c3550ce1ebd
bigcode/the-stack
train
32dce2e5bb741014d4cb3905
train
function
def add_elastic(list, date): for i in range(len(list)): date_event = get_next_day(date[i]) value_event = list[i][0] # print (date_event, value_event) yield { '_index' : 'cours_btc_idx_ml', '_type': 'cours_btc_ml', '_source': { 'date': date_event, 'rate_predicted': value_event, 'devise': cu...
def add_elastic(list, date):
for i in range(len(list)): date_event = get_next_day(date[i]) value_event = list[i][0] # print (date_event, value_event) yield { '_index' : 'cours_btc_idx_ml', '_type': 'cours_btc_ml', '_source': { 'date': date_event, 'rate_predicted': value_event, 'devise': currency, 'data_type': 'his...
PredictPlot[:, :] = np.nan testPredictPlot[len(trainPredict):len(dataset)-1, :] = testPredict # plot baseline and predictions plt.plot(scaler.inverse_transform(dataset)) plt.plot(trainPredictPlot) plt.plot(testPredictPlot) plt.show() def add_elastic(list, date):
63
64
122
8
55
Neemys/BigCoin
machine_learning/machine_learning_neural_network.py
Python
add_elastic
add_elastic
85
99
85
85
62c5182aaf3639f0a0c313a41ed7cd6d9378d068
bigcode/the-stack
train
d897444e7ec0daf344c13447
train
function
def create_LSTM_network(): model = Sequential() model.add(LSTM(4, input_shape=(1,1))) model.add(Dense(1)) model.compile(loss='mean_squared_error', optimizer='adam') return model
def create_LSTM_network():
model = Sequential() model.add(LSTM(4, input_shape=(1,1))) model.add(Dense(1)) model.compile(loss='mean_squared_error', optimizer='adam') return model
: return None def create_dataset(dataset): dataX, dataY = [], [] for i in range(len(dataset)-1): dataX.append(dataset[i]) dataY.append(dataset[i + 1]) return np.asarray(dataX), np.asarray(dataY) def create_LSTM_network():
64
64
45
6
58
Neemys/BigCoin
machine_learning/machine_learning_neural_network.py
Python
create_LSTM_network
create_LSTM_network
44
49
44
44
7e0c7e1d1497d186b5e4795e4728b2b9db906f08
bigcode/the-stack
train
7f3c1dcec51372ec190997a5
train
function
def plot_comparison_curves(dataset, trainPredict, testPredict, scaler): # shift train predictions for plotting trainPredictPlot = np.empty_like(dataset) trainPredictPlot[:, :] = np.nan trainPredictPlot[1:len(trainPredict)+1, :] = trainPredict # shift test predictions for plotting testPredictPlot = np.empty_like(d...
def plot_comparison_curves(dataset, trainPredict, testPredict, scaler): # shift train predictions for plotting
trainPredictPlot = np.empty_like(dataset) trainPredictPlot[:, :] = np.nan trainPredictPlot[1:len(trainPredict)+1, :] = trainPredict # shift test predictions for plotting testPredictPlot = np.empty_like(dataset) testPredictPlot[:, :] = np.nan testPredictPlot[len(trainPredict):len(dataset)-1, :] = testPredict #...
(trainScore)) testScore = math.sqrt(mean_squared_error(testY[:,0], testPredict[:,0])) print('Test Score: %.2f RMSE' % (testScore)) def plot_comparison_curves(dataset, trainPredict, testPredict, scaler): # shift train predictions for plotting
62
64
135
24
38
Neemys/BigCoin
machine_learning/machine_learning_neural_network.py
Python
plot_comparison_curves
plot_comparison_curves
69
83
69
70
e47b336677b5a44c323b36f3a0a3639427f067bc
bigcode/the-stack
train
58326d23c2f0b35ef914611e
train
function
def main(): # Get historical data from CoinDesk API data_historique = get_historique_data('EUR', date_start, date_end) data = data_historique.json() # Filter data to keep date and btc value dataset_raw = [] date = [] rate = [] for i in data["bpi"]: # date_event = datetime.datetime.strptime(i, "%Y-%m-%d").da...
def main(): # Get historical data from CoinDesk API
data_historique = get_historique_data('EUR', date_start, date_end) data = data_historique.json() # Filter data to keep date and btc value dataset_raw = [] date = [] rate = [] for i in data["bpi"]: # date_event = datetime.datetime.strptime(i, "%Y-%m-%d").date() date_event = i value_event = data["bpi"][i] ...
and predictions plt.plot(scaler.inverse_transform(dataset)) plt.plot(trainPredictPlot) plt.plot(testPredictPlot) plt.show() def add_elastic(list, date): for i in range(len(list)): date_event = get_next_day(date[i]) value_event = list[i][0] # print (date_event, value_event) yield { '_index' : 'cours_b...
162
163
546
13
149
Neemys/BigCoin
machine_learning/machine_learning_neural_network.py
Python
main
main
101
162
101
102
bcfd18cdd15e6a2b4307cd75d0b5a6a5160b1083
bigcode/the-stack
train
6e5bd93044e4476bdab89e50
train
function
def get_next_day(date_str): date = datetime.datetime.strptime(date_str, "%Y-%m-%d") next_day = date + timedelta(days=1) next_date_str = next_day.strftime("%Y-%m-%d") return next_date_str
def get_next_day(date_str):
date = datetime.datetime.strptime(date_str, "%Y-%m-%d") next_day = date + timedelta(days=1) next_date_str = next_day.strftime("%Y-%m-%d") return next_date_str
from elasticsearch import Elasticsearch from elasticsearch import helpers model_path = './model_test' currency = 'EUR' date_start = '2010-07-17' date_end = str(datetime.date.today()) host_es = "localhost" port_es = 9200 def get_next_day(date_str):
64
64
51
7
56
Neemys/BigCoin
machine_learning/machine_learning_neural_network.py
Python
get_next_day
get_next_day
22
26
22
22
20766be656c3bcb7196bd002433b2f27375687eb
bigcode/the-stack
train
3317f32642e557333ad85fa7
train
function
def calculate_rmse(trainY, testY, trainPredict, testPredict): # Calculate root mean squared error (RMSE) trainScore = math.sqrt(mean_squared_error(trainY[:,0], trainPredict[:,0])) print('Train Score: %.2f RMSE' % (trainScore)) testScore = math.sqrt(mean_squared_error(testY[:,0], testPredict[:,0])) print('Test Scor...
def calculate_rmse(trainY, testY, trainPredict, testPredict): # Calculate root mean squared error (RMSE)
trainScore = math.sqrt(mean_squared_error(trainY[:,0], trainPredict[:,0])) print('Train Score: %.2f RMSE' % (trainScore)) testScore = math.sqrt(mean_squared_error(testY[:,0], testPredict[:,0])) print('Test Score: %.2f RMSE' % (testScore))
.inverse_transform(futurePredict) testPredict = scaler.inverse_transform(testPredict) # Predict value for the next day print ('Bitcoin value for tomorrow : ', futurePredict) def calculate_rmse(trainY, testY, trainPredict, testPredict): # Calculate root mean squared error (RMSE)
62
64
97
27
35
Neemys/BigCoin
machine_learning/machine_learning_neural_network.py
Python
calculate_rmse
calculate_rmse
62
67
62
63
f78ff06166c9f55b60b3a00120fc2642888bfef5
bigcode/the-stack
train
aba4e8641e057e7945e09ecb
train
class
class Traverse: __slots__ = ("graph", "_active_nodes", "_active_nodes_cache") def __init__(self, graph, active_nodes: set = None): """ Graph Traversal Parameters: graph: Graph active_nodes: Iterable """ self.graph = graph self._active_no...
class Traverse:
__slots__ = ("graph", "_active_nodes", "_active_nodes_cache") def __init__(self, graph, active_nodes: set = None): """ Graph Traversal Parameters: graph: Graph active_nodes: Iterable """ self.graph = graph self._active_nodes_cache = None ...
""" Diablo: Python Graph Library (C) 2021 Justin Joyce. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to i...
132
187
625
3
128
mabel-dev/mabel
mabel/data/formats/graphs/traverse.py
Python
Traverse
Traverse
21
121
21
22
97c2480b37cdec0a121ba5adc69a51ada6aded4f
bigcode/the-stack
train
356c3593e27d770209e0e0fa
train
class
class GlobalAvgPool2d(nn.Module): def __init__(self): """Global average pooling over the input's spatial dimensions""" super(GlobalAvgPool2d, self).__init__() def forward(self, inputs): return nn.functional.adaptive_avg_pool2d(inputs, 1).view(inputs.size(0), -1)
class GlobalAvgPool2d(nn.Module):
def __init__(self): """Global average pooling over the input's spatial dimensions""" super(GlobalAvgPool2d, self).__init__() def forward(self, inputs): return nn.functional.adaptive_avg_pool2d(inputs, 1).view(inputs.size(0), -1)
torch.nn as nn from .splat import SplAtConv2d __all__ = ['ResNet', 'Bottleneck'] class DropBlock2D(object): def __init__(self, *args, **kwargs): raise NotImplementedError class GlobalAvgPool2d(nn.Module):
64
64
71
9
54
wangzheallen/ResNeSt
resnest/torch/resnet.py
Python
GlobalAvgPool2d
GlobalAvgPool2d
21
27
21
21
1ebe26efa91ae1a9cd82cfc1994c78d571ee0bb0
bigcode/the-stack
train
23de7046c770f095245cb7d7
train
class
class Bottleneck(nn.Module): """ResNet Bottleneck """ # pylint: disable=unused-argument expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None, radix=1, cardinality=1, bottleneck_width=64, avd=False, avd_first=False, dilation=1, is_first=False,...
class Bottleneck(nn.Module):
"""ResNet Bottleneck """ # pylint: disable=unused-argument expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None, radix=1, cardinality=1, bottleneck_width=64, avd=False, avd_first=False, dilation=1, is_first=False, rectified_c...
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ## Created by: Hang Zhang ## Email: zhanghang0704@gmail.com ## Copyright (c) 2020 ## ## LICENSE file in the root directory of this source tree ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ """ResNet variants""" im...
194
256
858
6
188
wangzheallen/ResNeSt
resnest/torch/resnet.py
Python
Bottleneck
Bottleneck
29
127
29
29
28348652e4642ae258fe4d91f0af6c494d7d0164
bigcode/the-stack
train
9936a9c42f6e6a89e390cf60
train
class
class DropBlock2D(object): def __init__(self, *args, **kwargs): raise NotImplementedError
class DropBlock2D(object):
def __init__(self, *args, **kwargs): raise NotImplementedError
LICENSE file in the root directory of this source tree ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ """ResNet variants""" import math import torch import torch.nn as nn from .splat import SplAtConv2d __all__ = ['ResNet', 'Bottleneck'] class DropBlock2D(object):
64
64
26
7
57
wangzheallen/ResNeSt
resnest/torch/resnet.py
Python
DropBlock2D
DropBlock2D
17
19
17
17
82b5c5ba10113d9129445a4c12900e734d5a5221
bigcode/the-stack
train
c4ef0a60554a58edc3a4f580
train
class
class ResNet(nn.Module): """ResNet Variants Parameters ---------- block : Block Class for the residual block. Options are BasicBlockV1, BottleneckV1. layers : list of int Numbers of layers in each block classes : int, default 1000 Number of classification classes. di...
class ResNet(nn.Module):
"""ResNet Variants Parameters ---------- block : Block Class for the residual block. Options are BasicBlockV1, BottleneckV1. layers : list of int Numbers of layers in each block classes : int, default 1000 Number of classification classes. dilated : bool, default Fal...
.relu = nn.ReLU(inplace=True) self.downsample = downsample self.dilation = dilation self.stride = stride def forward(self, x): residual = x out = self.conv1(x) out = self.bn1(out) if self.dropblock_prob > 0.0: out = self.dropblock1(out) o...
256
256
1,870
6
249
wangzheallen/ResNeSt
resnest/torch/resnet.py
Python
ResNet
ResNet
129
305
129
129
f2ded0eb046d9d6000b7092ba3e710117e5470d0
bigcode/the-stack
train
1e78f317338764bdd3b3fc72
train
function
@pytest.fixture def data(): return make_classification(n_samples=150, n_features=4, n_informative=4, n_redundant=0, n_repeated=0, n_classes=3, n_clusters_per_class=2, weights=[0.05, 0.05, 0.9], ...
@pytest.fixture def data():
return make_classification(n_samples=150, n_features=4, n_informative=4, n_redundant=0, n_repeated=0, n_classes=3, n_clusters_per_class=2, weights=[0.05, 0.05, 0.9], class_sep=0.8, random_stat...
import numpy as np import pytest from sklearn.base import BaseEstimator from sklearn.datasets import make_classification from sklearn.mixture import BayesianGaussianMixture from sklearn.neighbors import NearestNeighbors from pyloras import GAMUS @pytest.fixture def data():
55
64
86
6
48
zoj613/LoRAS
tests/test_gamus.py
Python
data
data
11
17
11
12
3c984825550c7bb9faa219f0c01897b76ede8f17
bigcode/the-stack
train
905925b5aa44ff225d06f39e
train
function
def test_gamus(data): X, y = data rng = np.random.RandomState(0) gamus = GAMUS(random_state=rng) X_res, y_res = gamus.fit_resample(X, y) _, y_counts = np.unique(y_res, return_counts=True) np.testing.assert_allclose(y_counts[0], y_counts[1]) assert gamus.nn_.n_neighbors == (5 + 1) assert...
def test_gamus(data):
X, y = data rng = np.random.RandomState(0) gamus = GAMUS(random_state=rng) X_res, y_res = gamus.fit_resample(X, y) _, y_counts = np.unique(y_res, return_counts=True) np.testing.assert_allclose(y_counts[0], y_counts[1]) assert gamus.nn_.n_neighbors == (5 + 1) assert len(gamus.alpha_) ==1...
import numpy as np import pytest from sklearn.base import BaseEstimator from sklearn.datasets import make_classification from sklearn.mixture import BayesianGaussianMixture from sklearn.neighbors import NearestNeighbors from pyloras import GAMUS @pytest.fixture def data(): return make_classification(n_samples=15...
141
175
585
6
135
zoj613/LoRAS
tests/test_gamus.py
Python
test_gamus
test_gamus
20
72
20
20
407e4ffee96a82cda7564d41999350e773f69080
bigcode/the-stack
train
71dfe00df39bc7cf37dc6adf
train
class
class SAGetAccountInformationResponse(NDRCALL): structure = ( ('wszBuffer',WORD_ARRAY), ('ErrorCode',ULONG), )
class SAGetAccountInformationResponse(NDRCALL):
structure = ( ('wszBuffer',WORD_ARRAY), ('ErrorCode',ULONG), )
AccountInformation(NDRCALL): opnum = 3 structure = ( ('Handle', PSASEC_HANDLE), ('pwszJobName', WSTR), ('ccBufferSize', DWORD), ('wszBuffer', WORD_ARRAY), ) class SAGetAccountInformationResponse(NDRCALL):
64
64
31
10
54
addenial/impacket
impacket/dcerpc/v5/sasec.py
Python
SAGetAccountInformationResponse
SAGetAccountInformationResponse
117
121
117
117
517a81ccaf4c40bdf24b35f5780f41d1a7e739e4
bigcode/the-stack
train
da7ba49313c724792b51315e
train
function
def checkNullString(string): if string == NULL: return string if string[-1:] != '\x00': return string + '\x00' else: return string
def checkNullString(string):
if string == NULL: return string if string[-1:] != '\x00': return string + '\x00' else: return string
1 : (SASetNSAccountInformation, SASetNSAccountInformationResponse), 2 : (SAGetNSAccountInformation, SAGetNSAccountInformationResponse), 3 : (SAGetAccountInformation, SAGetAccountInformationResponse), } ################################################################################ # HELPER FUNCTIONS ###############...
64
64
42
6
57
addenial/impacket
impacket/dcerpc/v5/sasec.py
Python
checkNullString
checkNullString
135
142
135
135
8933c4f9d9d7170845b9b15f543b52fc2e2e103e
bigcode/the-stack
train
c897ba0b12655ebca2d8e3f7
train
class
class SAGetNSAccountInformation(NDRCALL): opnum = 2 structure = ( ('Handle', PSASEC_HANDLE), ('ccBufferSize', DWORD), ('wszBuffer', WORD_ARRAY), )
class SAGetNSAccountInformation(NDRCALL):
opnum = 2 structure = ( ('Handle', PSASEC_HANDLE), ('ccBufferSize', DWORD), ('wszBuffer', WORD_ARRAY), )
wszPassword', LPWSTR), ) class SASetNSAccountInformationResponse(NDRCALL): structure = ( ('ErrorCode',ULONG), ) # 3.2.5.3.6 SAGetNSAccountInformation (Opnum 2) class SAGetNSAccountInformation(NDRCALL):
64
64
48
10
54
addenial/impacket
impacket/dcerpc/v5/sasec.py
Python
SAGetNSAccountInformation
SAGetNSAccountInformation
93
99
93
93
03447394d2a88e6892584bf1cde404f0a01882c8
bigcode/the-stack
train
6a9dddd097b594b3113410e0
train
class
class DCERPCSessionError(DCERPCException): def __init__(self, error_string=None, error_code=None, packet=None): DCERPCException.__init__(self, error_string, error_code, packet) def __str__( self ): key = self.error_code if key in hresult_errors.ERROR_MESSAGES: error_msg_shor...
class DCERPCSessionError(DCERPCException):
def __init__(self, error_string=None, error_code=None, packet=None): DCERPCException.__init__(self, error_string, error_code, packet) def __str__( self ): key = self.error_code if key in hresult_errors.ERROR_MESSAGES: error_msg_short = hresult_errors.ERROR_MESSAGES[key][0] ...
5.rpcrt import DCERPCException MSRPC_UUID_SASEC = uuidtup_to_bin(('378E52B0-C0A9-11CF-822D-00AA0051E40F','1.0')) class DCERPCSessionError(DCERPCException):
64
64
160
12
52
addenial/impacket
impacket/dcerpc/v5/sasec.py
Python
DCERPCSessionError
DCERPCSessionError
29
40
29
29
af7da2e648d975cb72206b034429eb6807d48e25
bigcode/the-stack
train
d4295f66b5ce42657d3b3da1
train
class
class SAGetAccountInformation(NDRCALL): opnum = 3 structure = ( ('Handle', PSASEC_HANDLE), ('pwszJobName', WSTR), ('ccBufferSize', DWORD), ('wszBuffer', WORD_ARRAY), )
class SAGetAccountInformation(NDRCALL):
opnum = 3 structure = ( ('Handle', PSASEC_HANDLE), ('pwszJobName', WSTR), ('ccBufferSize', DWORD), ('wszBuffer', WORD_ARRAY), )
) class SAGetNSAccountInformationResponse(NDRCALL): structure = ( ('wszBuffer',WORD_ARRAY), ('ErrorCode',ULONG), ) # 3.2.5.3.7 SAGetAccountInformation (Opnum 3) class SAGetAccountInformation(NDRCALL):
64
64
57
9
55
addenial/impacket
impacket/dcerpc/v5/sasec.py
Python
SAGetAccountInformation
SAGetAccountInformation
108
115
108
108
760e09dbb23d210b9cc50e588000895fe93f9e75
bigcode/the-stack
train
32cd56a9cda5e1cf92a610f6
train
function
def hSASetNSAccountInformation(dce, handle, pwszAccount, pwszPassword): request = SASetNSAccountInformation() request['Handle'] = handle request['pwszAccount'] = checkNullString(pwszAccount) request['pwszPassword'] = checkNullString(pwszPassword) return dce.request(request)
def hSASetNSAccountInformation(dce, handle, pwszAccount, pwszPassword):
request = SASetNSAccountInformation() request['Handle'] = handle request['pwszAccount'] = checkNullString(pwszAccount) request['pwszPassword'] = checkNullString(pwszPassword) return dce.request(request)
Account'] = checkNullString(pwszAccount) request['pwszPassword'] = checkNullString(pwszPassword) request['dwJobFlags'] = dwJobFlags return dce.request(request) def hSASetNSAccountInformation(dce, handle, pwszAccount, pwszPassword):
64
64
74
20
44
addenial/impacket
impacket/dcerpc/v5/sasec.py
Python
hSASetNSAccountInformation
hSASetNSAccountInformation
153
158
153
153
a997bd7d4cae980046194a4666d3868bff852fea
bigcode/the-stack
train
29aa655908d4accb968ca2c3
train
class
class WORD_ARRAY(NDRUniConformantArray): item = '<H'
class WORD_ARRAY(NDRUniConformantArray):
item = '<H'
WSTR MAX_BUFFER_SIZE = 273 # 3.2.5.3.4 SASetAccountInformation (Opnum 0) TASK_FLAG_RUN_ONLY_IF_LOGGED_ON = 0x40000 ################################################################################ # STRUCTURES ################################################################################ class WORD_ARRAY(NDRUniConf...
64
64
17
11
52
addenial/impacket
impacket/dcerpc/v5/sasec.py
Python
WORD_ARRAY
WORD_ARRAY
56
57
56
56
656c3614e83a9ac996d91e538eca870d556a1de2
bigcode/the-stack
train