body_hash stringlengths 64 64 | body stringlengths 23 109k | docstring stringlengths 1 57k | path stringlengths 4 198 | name stringlengths 1 115 | repository_name stringlengths 7 111 | repository_stars float64 0 191k | lang stringclasses 1 value | body_without_docstring stringlengths 14 108k | unified stringlengths 45 133k |
|---|---|---|---|---|---|---|---|---|---|
cab9d72f4d785b19a68b57a4869d36f7f93086fc4ad8f1488df3d91066ee5fdb | @staticmethod
def update_schema(check_update, from_version):
' Hook for migrating schemata, e.g. table names '
return 0 | Hook for migrating schemata, e.g. table names | dc_common/model.py | update_schema | plaidfluff/dreamcatcher | 0 | python | @staticmethod
def update_schema(check_update, from_version):
' '
return 0 | @staticmethod
def update_schema(check_update, from_version):
' '
return 0<|docstring|>Hook for migrating schemata, e.g. table names<|endoftext|> |
f7b96b85982bf6ea438e3fd2b3ff3d290df4f45b2748ebcb9035cc86602d7527 | @staticmethod
@abstractmethod
def _reduce_values(values):
'\n If a user accesses multidict["foo"], this method\n reduces all values for "foo" to a single value that is returned.\n For example, HTTP headers are folded, whereas we will just take\n the first cookie we found with that name.\n ' | If a user accesses multidict["foo"], this method
reduces all values for "foo" to a single value that is returned.
For example, HTTP headers are folded, whereas we will just take
the first cookie we found with that name. | netlib/multidict.py | _reduce_values | e7appew/pkg-mitmproxy | 1 | python | @staticmethod
@abstractmethod
def _reduce_values(values):
'\n If a user accesses multidict["foo"], this method\n reduces all values for "foo" to a single value that is returned.\n For example, HTTP headers are folded, whereas we will just take\n the first cookie we found with that name.\n ' | @staticmethod
@abstractmethod
def _reduce_values(values):
'\n If a user accesses multidict["foo"], this method\n reduces all values for "foo" to a single value that is returned.\n For example, HTTP headers are folded, whereas we will just take\n the first cookie we found with that name.\n '<|docstring|>If a user accesses multidict["foo"], this method
reduces all values for "foo" to a single value that is returned.
For example, HTTP headers are folded, whereas we will just take
the first cookie we found with that name.<|endoftext|> |
b82473f82264d5d756508f7745cee06ab68ce6e281514f9e805e9056844ff504 | @staticmethod
@abstractmethod
def _kconv(key):
'\n This method converts a key to its canonical representation.\n For example, HTTP headers are case-insensitive, so this method returns key.lower().\n ' | This method converts a key to its canonical representation.
For example, HTTP headers are case-insensitive, so this method returns key.lower(). | netlib/multidict.py | _kconv | e7appew/pkg-mitmproxy | 1 | python | @staticmethod
@abstractmethod
def _kconv(key):
'\n This method converts a key to its canonical representation.\n For example, HTTP headers are case-insensitive, so this method returns key.lower().\n ' | @staticmethod
@abstractmethod
def _kconv(key):
'\n This method converts a key to its canonical representation.\n For example, HTTP headers are case-insensitive, so this method returns key.lower().\n '<|docstring|>This method converts a key to its canonical representation.
For example, HTTP headers are case-insensitive, so this method returns key.lower().<|endoftext|> |
a03a6ef16d586ac431ed495a3ac2d88f5ec8cd8bbd1da8218dece2c0a40c528a | def get_all(self, key):
'\n Return the list of all values for a given key.\n If that key is not in the MultiDict, the return value will be an empty list.\n '
key = self._kconv(key)
return [value for (k, value) in self.fields if (self._kconv(k) == key)] | Return the list of all values for a given key.
If that key is not in the MultiDict, the return value will be an empty list. | netlib/multidict.py | get_all | e7appew/pkg-mitmproxy | 1 | python | def get_all(self, key):
'\n Return the list of all values for a given key.\n If that key is not in the MultiDict, the return value will be an empty list.\n '
key = self._kconv(key)
return [value for (k, value) in self.fields if (self._kconv(k) == key)] | def get_all(self, key):
'\n Return the list of all values for a given key.\n If that key is not in the MultiDict, the return value will be an empty list.\n '
key = self._kconv(key)
return [value for (k, value) in self.fields if (self._kconv(k) == key)]<|docstring|>Return the list of all values for a given key.
If that key is not in the MultiDict, the return value will be an empty list.<|endoftext|> |
864f8e84d522258900327a8fab91f5fc096df18ff77118352490355db473c6b4 | def set_all(self, key, values):
'\n Remove the old values for a key and add new ones.\n '
key_kconv = self._kconv(key)
new_fields = []
for field in self.fields:
if (self._kconv(field[0]) == key_kconv):
if values:
new_fields.append((field[0], values.pop(0)))
else:
new_fields.append(field)
while values:
new_fields.append((key, values.pop(0)))
self.fields = tuple(new_fields) | Remove the old values for a key and add new ones. | netlib/multidict.py | set_all | e7appew/pkg-mitmproxy | 1 | python | def set_all(self, key, values):
'\n \n '
key_kconv = self._kconv(key)
new_fields = []
for field in self.fields:
if (self._kconv(field[0]) == key_kconv):
if values:
new_fields.append((field[0], values.pop(0)))
else:
new_fields.append(field)
while values:
new_fields.append((key, values.pop(0)))
self.fields = tuple(new_fields) | def set_all(self, key, values):
'\n \n '
key_kconv = self._kconv(key)
new_fields = []
for field in self.fields:
if (self._kconv(field[0]) == key_kconv):
if values:
new_fields.append((field[0], values.pop(0)))
else:
new_fields.append(field)
while values:
new_fields.append((key, values.pop(0)))
self.fields = tuple(new_fields)<|docstring|>Remove the old values for a key and add new ones.<|endoftext|> |
8ff1e0f18468c778069b27dd88c645d3f299abc9c73d993e0616c79c2cae459f | def add(self, key, value):
'\n Add an additional value for the given key at the bottom.\n '
self.insert(len(self.fields), key, value) | Add an additional value for the given key at the bottom. | netlib/multidict.py | add | e7appew/pkg-mitmproxy | 1 | python | def add(self, key, value):
'\n \n '
self.insert(len(self.fields), key, value) | def add(self, key, value):
'\n \n '
self.insert(len(self.fields), key, value)<|docstring|>Add an additional value for the given key at the bottom.<|endoftext|> |
1c46db7ce1a9aee71bb1b07311e9b66e7989172a4d2403fbebe77cb9fbc33e81 | def insert(self, index, key, value):
'\n Insert an additional value for the given key at the specified position.\n '
item = (key, value)
self.fields = ((self.fields[:index] + (item,)) + self.fields[index:]) | Insert an additional value for the given key at the specified position. | netlib/multidict.py | insert | e7appew/pkg-mitmproxy | 1 | python | def insert(self, index, key, value):
'\n \n '
item = (key, value)
self.fields = ((self.fields[:index] + (item,)) + self.fields[index:]) | def insert(self, index, key, value):
'\n \n '
item = (key, value)
self.fields = ((self.fields[:index] + (item,)) + self.fields[index:])<|docstring|>Insert an additional value for the given key at the specified position.<|endoftext|> |
60661974383f03fc5c30a596f39d3a169cdf3efc949ef1ecce4832ca82b8663b | def keys(self, multi=False):
'\n Get all keys.\n\n Args:\n multi(bool):\n If True, one key per value will be returned.\n If False, duplicate keys will only be returned once.\n '
return (k for (k, _) in self.items(multi)) | Get all keys.
Args:
multi(bool):
If True, one key per value will be returned.
If False, duplicate keys will only be returned once. | netlib/multidict.py | keys | e7appew/pkg-mitmproxy | 1 | python | def keys(self, multi=False):
'\n Get all keys.\n\n Args:\n multi(bool):\n If True, one key per value will be returned.\n If False, duplicate keys will only be returned once.\n '
return (k for (k, _) in self.items(multi)) | def keys(self, multi=False):
'\n Get all keys.\n\n Args:\n multi(bool):\n If True, one key per value will be returned.\n If False, duplicate keys will only be returned once.\n '
return (k for (k, _) in self.items(multi))<|docstring|>Get all keys.
Args:
multi(bool):
If True, one key per value will be returned.
If False, duplicate keys will only be returned once.<|endoftext|> |
d14cc16f07d66976167713fe3e3248b80431014a5f487fe244935f19fb673e3d | def values(self, multi=False):
'\n Get all values.\n\n Args:\n multi(bool):\n If True, all values will be returned.\n If False, only the first value per key will be returned.\n '
return (v for (_, v) in self.items(multi)) | Get all values.
Args:
multi(bool):
If True, all values will be returned.
If False, only the first value per key will be returned. | netlib/multidict.py | values | e7appew/pkg-mitmproxy | 1 | python | def values(self, multi=False):
'\n Get all values.\n\n Args:\n multi(bool):\n If True, all values will be returned.\n If False, only the first value per key will be returned.\n '
return (v for (_, v) in self.items(multi)) | def values(self, multi=False):
'\n Get all values.\n\n Args:\n multi(bool):\n If True, all values will be returned.\n If False, only the first value per key will be returned.\n '
return (v for (_, v) in self.items(multi))<|docstring|>Get all values.
Args:
multi(bool):
If True, all values will be returned.
If False, only the first value per key will be returned.<|endoftext|> |
1d34d1002f2a25757525e96f07048ba7be5f5d9aaa6ecbae609e97b1b5e54889 | def items(self, multi=False):
'\n Get all (key, value) tuples.\n\n Args:\n multi(bool):\n If True, all (key, value) pairs will be returned\n If False, only the first (key, value) pair per unique key will be returned.\n '
if multi:
return self.fields
else:
return super(_MultiDict, self).items() | Get all (key, value) tuples.
Args:
multi(bool):
If True, all (key, value) pairs will be returned
If False, only the first (key, value) pair per unique key will be returned. | netlib/multidict.py | items | e7appew/pkg-mitmproxy | 1 | python | def items(self, multi=False):
'\n Get all (key, value) tuples.\n\n Args:\n multi(bool):\n If True, all (key, value) pairs will be returned\n If False, only the first (key, value) pair per unique key will be returned.\n '
if multi:
return self.fields
else:
return super(_MultiDict, self).items() | def items(self, multi=False):
'\n Get all (key, value) tuples.\n\n Args:\n multi(bool):\n If True, all (key, value) pairs will be returned\n If False, only the first (key, value) pair per unique key will be returned.\n '
if multi:
return self.fields
else:
return super(_MultiDict, self).items()<|docstring|>Get all (key, value) tuples.
Args:
multi(bool):
If True, all (key, value) pairs will be returned
If False, only the first (key, value) pair per unique key will be returned.<|endoftext|> |
a770c044a2f6e6da2955a0dd638db2fb4e0e4efc75d16b9584986f97be602aaa | def collect(self):
'\n Returns a list of (key, value) tuples, where values are either\n singular if there is only one matching item for a key, or a list\n if there are more than one. The order of the keys matches the order\n in the underlying fields list.\n '
coll = []
for key in self:
values = self.get_all(key)
if (len(values) == 1):
coll.append([key, values[0]])
else:
coll.append([key, values])
return coll | Returns a list of (key, value) tuples, where values are either
singular if there is only one matching item for a key, or a list
if there are more than one. The order of the keys matches the order
in the underlying fields list. | netlib/multidict.py | collect | e7appew/pkg-mitmproxy | 1 | python | def collect(self):
'\n Returns a list of (key, value) tuples, where values are either\n singular if there is only one matching item for a key, or a list\n if there are more than one. The order of the keys matches the order\n in the underlying fields list.\n '
coll = []
for key in self:
values = self.get_all(key)
if (len(values) == 1):
coll.append([key, values[0]])
else:
coll.append([key, values])
return coll | def collect(self):
'\n Returns a list of (key, value) tuples, where values are either\n singular if there is only one matching item for a key, or a list\n if there are more than one. The order of the keys matches the order\n in the underlying fields list.\n '
coll = []
for key in self:
values = self.get_all(key)
if (len(values) == 1):
coll.append([key, values[0]])
else:
coll.append([key, values])
return coll<|docstring|>Returns a list of (key, value) tuples, where values are either
singular if there is only one matching item for a key, or a list
if there are more than one. The order of the keys matches the order
in the underlying fields list.<|endoftext|> |
bf3fca0d9f167451ab9bd86ee14601a9f5c955b753a9d3e05b303b963edc329b | def to_dict(self):
'\n Get the MultiDict as a plain Python dict.\n Keys with multiple values are returned as lists.\n\n Example:\n\n .. code-block:: python\n\n # Simple dict with duplicate values.\n >>> d = MultiDict([("name", "value"), ("a", False), ("a", 42)])\n >>> d.to_dict()\n {\n "name": "value",\n "a": [False, 42]\n }\n '
return {k: v for (k, v) in self.collect()} | Get the MultiDict as a plain Python dict.
Keys with multiple values are returned as lists.
Example:
.. code-block:: python
# Simple dict with duplicate values.
>>> d = MultiDict([("name", "value"), ("a", False), ("a", 42)])
>>> d.to_dict()
{
"name": "value",
"a": [False, 42]
} | netlib/multidict.py | to_dict | e7appew/pkg-mitmproxy | 1 | python | def to_dict(self):
'\n Get the MultiDict as a plain Python dict.\n Keys with multiple values are returned as lists.\n\n Example:\n\n .. code-block:: python\n\n # Simple dict with duplicate values.\n >>> d = MultiDict([("name", "value"), ("a", False), ("a", 42)])\n >>> d.to_dict()\n {\n "name": "value",\n "a": [False, 42]\n }\n '
return {k: v for (k, v) in self.collect()} | def to_dict(self):
'\n Get the MultiDict as a plain Python dict.\n Keys with multiple values are returned as lists.\n\n Example:\n\n .. code-block:: python\n\n # Simple dict with duplicate values.\n >>> d = MultiDict([("name", "value"), ("a", False), ("a", 42)])\n >>> d.to_dict()\n {\n "name": "value",\n "a": [False, 42]\n }\n '
return {k: v for (k, v) in self.collect()}<|docstring|>Get the MultiDict as a plain Python dict.
Keys with multiple values are returned as lists.
Example:
.. code-block:: python
# Simple dict with duplicate values.
>>> d = MultiDict([("name", "value"), ("a", False), ("a", 42)])
>>> d.to_dict()
{
"name": "value",
"a": [False, 42]
}<|endoftext|> |
bdc96ffe0c48b1c3e1aa773b2202f4ba800d23820f905d940c391ee296e965f8 | def with_delitem(self, key):
'\n Returns:\n An updated ImmutableMultiDict. The original object will not be modified.\n '
ret = self.copy()
super(ImmutableMultiDict, ret).__delitem__(key)
return ret | Returns:
An updated ImmutableMultiDict. The original object will not be modified. | netlib/multidict.py | with_delitem | e7appew/pkg-mitmproxy | 1 | python | def with_delitem(self, key):
'\n Returns:\n An updated ImmutableMultiDict. The original object will not be modified.\n '
ret = self.copy()
super(ImmutableMultiDict, ret).__delitem__(key)
return ret | def with_delitem(self, key):
'\n Returns:\n An updated ImmutableMultiDict. The original object will not be modified.\n '
ret = self.copy()
super(ImmutableMultiDict, ret).__delitem__(key)
return ret<|docstring|>Returns:
An updated ImmutableMultiDict. The original object will not be modified.<|endoftext|> |
898efcdfa58b7b003bdb326f2b8771d896bf2f8a8874414618a4b51ace2b9866 | def with_set_all(self, key, values):
'\n Returns:\n An updated ImmutableMultiDict. The original object will not be modified.\n '
ret = self.copy()
super(ImmutableMultiDict, ret).set_all(key, values)
return ret | Returns:
An updated ImmutableMultiDict. The original object will not be modified. | netlib/multidict.py | with_set_all | e7appew/pkg-mitmproxy | 1 | python | def with_set_all(self, key, values):
'\n Returns:\n An updated ImmutableMultiDict. The original object will not be modified.\n '
ret = self.copy()
super(ImmutableMultiDict, ret).set_all(key, values)
return ret | def with_set_all(self, key, values):
'\n Returns:\n An updated ImmutableMultiDict. The original object will not be modified.\n '
ret = self.copy()
super(ImmutableMultiDict, ret).set_all(key, values)
return ret<|docstring|>Returns:
An updated ImmutableMultiDict. The original object will not be modified.<|endoftext|> |
6de8a9472b97a93a54767602f663f683ef5dce04e7ffefe57c5a2e7d616e916f | def with_insert(self, index, key, value):
'\n Returns:\n An updated ImmutableMultiDict. The original object will not be modified.\n '
ret = self.copy()
super(ImmutableMultiDict, ret).insert(index, key, value)
return ret | Returns:
An updated ImmutableMultiDict. The original object will not be modified. | netlib/multidict.py | with_insert | e7appew/pkg-mitmproxy | 1 | python | def with_insert(self, index, key, value):
'\n Returns:\n An updated ImmutableMultiDict. The original object will not be modified.\n '
ret = self.copy()
super(ImmutableMultiDict, ret).insert(index, key, value)
return ret | def with_insert(self, index, key, value):
'\n Returns:\n An updated ImmutableMultiDict. The original object will not be modified.\n '
ret = self.copy()
super(ImmutableMultiDict, ret).insert(index, key, value)
return ret<|docstring|>Returns:
An updated ImmutableMultiDict. The original object will not be modified.<|endoftext|> |
8f637f966aff7077d99058394f4d5594f59b996cc9719726795b47333fe7f6d0 | def dict_to_name(**kwargs) -> str:
'Returns name from a dict.'
kv = []
for key in sorted(kwargs):
if isinstance(key, str):
value = kwargs[key]
if (value is not None):
kv += [f'{key}{to_string(value)}']
return '_'.join(kv) | Returns name from a dict. | optio/get_simulation_fiber.py | dict_to_name | simbilod/grating_coupler_meep | 1 | python | def dict_to_name(**kwargs) -> str:
kv = []
for key in sorted(kwargs):
if isinstance(key, str):
value = kwargs[key]
if (value is not None):
kv += [f'{key}{to_string(value)}']
return '_'.join(kv) | def dict_to_name(**kwargs) -> str:
kv = []
for key in sorted(kwargs):
if isinstance(key, str):
value = kwargs[key]
if (value is not None):
kv += [f'{key}{to_string(value)}']
return '_'.join(kv)<|docstring|>Returns name from a dict.<|endoftext|> |
6225dbf1eb7e594a77331129766389cf4e1e71ac17ff86f5fce8614442b7d834 | def get_simulation_fiber(period: float=0.66, fill_factor: float=0.5, widths: Optional[Floats]=None, gaps: Optional[Floats]=None, n_periods: int=30, etch_depth: float=(70 * nm), fiber_angle_deg: float=20.0, fiber_xposition: float=1.0, fiber_core_diameter: float=10.4, fiber_numerical_aperture: float=0.14, fiber_nclad: float=nSiO2, ncore: float=nSi, ncladtop: float=nSiO2, ncladbottom: float=nSiO2, nsubstrate: float=nSi, pml_thickness: float=1.0, substrate_thickness: float=1.0, bottom_clad_thickness: float=2.0, core_thickness: float=(220 * nm), top_clad_thickness: float=2.0, air_gap_thickness: float=1.0, fiber_thickness: float=2.0, res: int=64, wavelength_min: float=1.4, wavelength_max: float=1.7, wavelength_points: int=150, eps_averaging: bool=False, fiber_port_y_offset_from_air: float=1, waveguide_port_x_offset_from_grating_start: float=10, fiber_port_x_size: Optional[float]=None) -> Dict[(str, Any)]:
'Returns simulation results from grating coupler with fiber.\n na**2 = ncore**2 - nclad**2\n ncore = sqrt(na**2 + ncore**2)\n\n Args:\n TODO\n '
wavelengths = np.linspace(wavelength_min, wavelength_max, wavelength_points)
wavelength = np.mean(wavelengths)
freqs = (1 / wavelengths)
widths = (widths or (n_periods * [(period * fill_factor)]))
gaps = (gaps or (n_periods * [(period * (1 - fill_factor))]))
settings = dict(widths=widths, gaps=gaps, n_periods=n_periods, etch_depth=etch_depth, fiber_angle_deg=fiber_angle_deg, fiber_xposition=fiber_xposition, fiber_core_diameter=fiber_core_diameter, fiber_numerical_aperture=fiber_numerical_aperture, fiber_nclad=fiber_nclad, ncore=ncore, ncladtop=ncladtop, ncladbottom=ncladbottom, nsubstrate=nsubstrate, pml_thickness=pml_thickness, substrate_thickness=substrate_thickness, bottom_clad_thickness=bottom_clad_thickness, core_thickness=core_thickness, top_clad_thickness=top_clad_thickness, air_gap_thickness=air_gap_thickness, fiber_thickness=fiber_thickness, res=res, wavelength_min=wavelength_min, wavelength_max=wavelength_max, wavelength_points=wavelength_points, eps_averaging=eps_averaging, fiber_port_y_offset_from_air=fiber_port_y_offset_from_air, waveguide_port_x_offset_from_grating_start=waveguide_port_x_offset_from_grating_start, fiber_port_x_size=fiber_port_x_size)
settings_string = to_string(settings)
settings_hash = hashlib.md5(settings_string.encode()).hexdigest()[:8]
fiber_angle = np.radians(fiber_angle_deg)
sz = ((((((((+ pml_thickness) + substrate_thickness) + bottom_clad_thickness) + core_thickness) + top_clad_thickness) + air_gap_thickness) + fiber_thickness) + pml_thickness)
fiber_port_y = ((((((- sz) / 2) + core_thickness) + top_clad_thickness) + air_gap_thickness) + fiber_port_y_offset_from_air)
fiber_port_x_offset_from_angle = np.abs((fiber_port_y * np.tan(fiber_angle)))
sxy = (((3.5 * fiber_core_diameter) + (2 * pml_thickness)) + (2 * fiber_port_x_offset_from_angle))
core_material = mp.Medium(index=ncore)
top_clad_material = mp.Medium(index=ncladtop)
bottom_clad_material = mp.Medium(index=ncladbottom)
fiber_ncore = (((fiber_numerical_aperture ** 2) + (fiber_nclad ** 2)) ** 0.5)
fiber_clad_material = mp.Medium(index=fiber_nclad)
fiber_core_material = mp.Medium(index=fiber_ncore)
grating_start = (- fiber_xposition)
cell_size = mp.Vector3(sxy, sz)
fiber_port_y = (((- sz) / 2) + (((((((+ pml_thickness) + substrate_thickness) + bottom_clad_thickness) + core_thickness) + top_clad_thickness) + air_gap_thickness) + fiber_port_y_offset_from_air))
fiber_port_center = mp.Vector3(fiber_port_x_offset_from_angle, fiber_port_y)
fiber_port_x_size = (fiber_port_x_size or (3.5 * fiber_core_diameter))
fiber_port_size = mp.Vector3(fiber_port_x_size, 0, 0)
fiber_port_direction = mp.Vector3(y=(- 1)).rotate(mp.Vector3(z=1), ((- 1) * fiber_angle))
waveguide_port_y = (((- sz) / 2) + (((((+ pml_thickness) + substrate_thickness) + (bottom_clad_thickness / 2)) + (core_thickness / 2)) + (top_clad_thickness / 2)))
waveguide_port_x = (grating_start - waveguide_port_x_offset_from_grating_start)
waveguide_port_center = mp.Vector3(waveguide_port_x, waveguide_port_y)
waveguide_port_size = mp.Vector3(0, ((bottom_clad_thickness + (core_thickness / 2)) + top_clad_thickness))
waveguide_port_direction = mp.X
fiber_clad = 120
hfiber_geom = 200
geometry = []
geometry.append(mp.Block(material=fiber_clad_material, center=mp.Vector3(0, (waveguide_port_y - (core_thickness / 2))), size=mp.Vector3(fiber_clad, hfiber_geom), e1=mp.Vector3(x=1).rotate(mp.Vector3(z=1), ((- 1) * fiber_angle)), e2=mp.Vector3(y=1).rotate(mp.Vector3(z=1), ((- 1) * fiber_angle))))
geometry.append(mp.Block(material=fiber_core_material, center=mp.Vector3(x=0), size=mp.Vector3(fiber_core_diameter, hfiber_geom), e1=mp.Vector3(x=1).rotate(mp.Vector3(z=1), ((- 1) * fiber_angle)), e2=mp.Vector3(y=1).rotate(mp.Vector3(z=1), ((- 1) * fiber_angle))))
geometry.append(mp.Block(material=mp.air, center=mp.Vector3(0, (((- sz) / 2) + ((((((+ pml_thickness) + substrate_thickness) + bottom_clad_thickness) + core_thickness) + top_clad_thickness) + (air_gap_thickness / 2)))), size=mp.Vector3(mp.inf, air_gap_thickness)))
geometry.append(mp.Block(material=top_clad_material, center=mp.Vector3(0, (((- sz) / 2) + (((((+ pml_thickness) + substrate_thickness) + bottom_clad_thickness) + (core_thickness / 2)) + (top_clad_thickness / 2)))), size=mp.Vector3(mp.inf, (core_thickness + top_clad_thickness))))
geometry.append(mp.Block(material=bottom_clad_material, center=mp.Vector3(0, (((- sz) / 2) + (((+ pml_thickness) + substrate_thickness) + (bottom_clad_thickness / 2)))), size=mp.Vector3(mp.inf, bottom_clad_thickness)))
geometry.append(mp.Block(material=core_material, center=mp.Vector3(0, (((- sz) / 2) + ((((+ pml_thickness) + substrate_thickness) + bottom_clad_thickness) + (core_thickness / 2)))), size=mp.Vector3(mp.inf, core_thickness)))
x = grating_start
for (width, gap) in zip(widths, gaps):
geometry.append(mp.Block(material=top_clad_material, center=mp.Vector3((x + (gap / 2)), (((- sz) / 2) + (((((+ pml_thickness) + substrate_thickness) + bottom_clad_thickness) + core_thickness) - (etch_depth / 2)))), size=mp.Vector3(gap, etch_depth)))
x += (width + gap)
geometry.append(mp.Block(material=mp.Medium(index=nsubstrate), center=mp.Vector3(0, ((((- sz) / 2) + (pml_thickness / 2)) + (substrate_thickness / 2))), size=mp.Vector3(mp.inf, (pml_thickness + substrate_thickness))))
boundary_layers = [mp.PML(pml_thickness)]
fcen = (1 / wavelength)
fwidth = (0.2 * fcen)
sources_directions = [mp.X]
sources = [mp.EigenModeSource(src=mp.GaussianSource(frequency=fcen, fwidth=fwidth), size=waveguide_port_size, center=waveguide_port_center, eig_band=1, direction=sources_directions[0], eig_match_freq=True, eig_parity=mp.ODD_Z)]
waveguide_monitor_port = mp.ModeRegion(center=(waveguide_port_center + mp.Vector3(x=0.2)), size=waveguide_port_size)
fiber_monitor_port = mp.ModeRegion(center=(fiber_port_center - mp.Vector3(y=0.2)), size=fiber_port_size)
sim = mp.Simulation(resolution=res, cell_size=cell_size, boundary_layers=boundary_layers, geometry=geometry, sources=sources, dimensions=2, eps_averaging=eps_averaging)
waveguide_monitor = sim.add_mode_monitor(freqs, waveguide_monitor_port, yee_grid=True)
fiber_monitor = sim.add_mode_monitor(freqs, fiber_monitor_port)
field_monitor_point = (0, 0, 0)
return dict(sim=sim, cell_size=cell_size, freqs=freqs, fcen=fcen, waveguide_monitor=waveguide_monitor, waveguide_port_direction=waveguide_port_direction, fiber_monitor=fiber_monitor, fiber_angle_deg=fiber_angle_deg, sources=sources, field_monitor_point=field_monitor_point, initialized=False, settings=settings) | Returns simulation results from grating coupler with fiber.
na**2 = ncore**2 - nclad**2
ncore = sqrt(na**2 + ncore**2)
Args:
TODO | optio/get_simulation_fiber.py | get_simulation_fiber | simbilod/grating_coupler_meep | 1 | python | def get_simulation_fiber(period: float=0.66, fill_factor: float=0.5, widths: Optional[Floats]=None, gaps: Optional[Floats]=None, n_periods: int=30, etch_depth: float=(70 * nm), fiber_angle_deg: float=20.0, fiber_xposition: float=1.0, fiber_core_diameter: float=10.4, fiber_numerical_aperture: float=0.14, fiber_nclad: float=nSiO2, ncore: float=nSi, ncladtop: float=nSiO2, ncladbottom: float=nSiO2, nsubstrate: float=nSi, pml_thickness: float=1.0, substrate_thickness: float=1.0, bottom_clad_thickness: float=2.0, core_thickness: float=(220 * nm), top_clad_thickness: float=2.0, air_gap_thickness: float=1.0, fiber_thickness: float=2.0, res: int=64, wavelength_min: float=1.4, wavelength_max: float=1.7, wavelength_points: int=150, eps_averaging: bool=False, fiber_port_y_offset_from_air: float=1, waveguide_port_x_offset_from_grating_start: float=10, fiber_port_x_size: Optional[float]=None) -> Dict[(str, Any)]:
'Returns simulation results from grating coupler with fiber.\n na**2 = ncore**2 - nclad**2\n ncore = sqrt(na**2 + ncore**2)\n\n Args:\n TODO\n '
wavelengths = np.linspace(wavelength_min, wavelength_max, wavelength_points)
wavelength = np.mean(wavelengths)
freqs = (1 / wavelengths)
widths = (widths or (n_periods * [(period * fill_factor)]))
gaps = (gaps or (n_periods * [(period * (1 - fill_factor))]))
settings = dict(widths=widths, gaps=gaps, n_periods=n_periods, etch_depth=etch_depth, fiber_angle_deg=fiber_angle_deg, fiber_xposition=fiber_xposition, fiber_core_diameter=fiber_core_diameter, fiber_numerical_aperture=fiber_numerical_aperture, fiber_nclad=fiber_nclad, ncore=ncore, ncladtop=ncladtop, ncladbottom=ncladbottom, nsubstrate=nsubstrate, pml_thickness=pml_thickness, substrate_thickness=substrate_thickness, bottom_clad_thickness=bottom_clad_thickness, core_thickness=core_thickness, top_clad_thickness=top_clad_thickness, air_gap_thickness=air_gap_thickness, fiber_thickness=fiber_thickness, res=res, wavelength_min=wavelength_min, wavelength_max=wavelength_max, wavelength_points=wavelength_points, eps_averaging=eps_averaging, fiber_port_y_offset_from_air=fiber_port_y_offset_from_air, waveguide_port_x_offset_from_grating_start=waveguide_port_x_offset_from_grating_start, fiber_port_x_size=fiber_port_x_size)
settings_string = to_string(settings)
settings_hash = hashlib.md5(settings_string.encode()).hexdigest()[:8]
fiber_angle = np.radians(fiber_angle_deg)
sz = ((((((((+ pml_thickness) + substrate_thickness) + bottom_clad_thickness) + core_thickness) + top_clad_thickness) + air_gap_thickness) + fiber_thickness) + pml_thickness)
fiber_port_y = ((((((- sz) / 2) + core_thickness) + top_clad_thickness) + air_gap_thickness) + fiber_port_y_offset_from_air)
fiber_port_x_offset_from_angle = np.abs((fiber_port_y * np.tan(fiber_angle)))
sxy = (((3.5 * fiber_core_diameter) + (2 * pml_thickness)) + (2 * fiber_port_x_offset_from_angle))
core_material = mp.Medium(index=ncore)
top_clad_material = mp.Medium(index=ncladtop)
bottom_clad_material = mp.Medium(index=ncladbottom)
fiber_ncore = (((fiber_numerical_aperture ** 2) + (fiber_nclad ** 2)) ** 0.5)
fiber_clad_material = mp.Medium(index=fiber_nclad)
fiber_core_material = mp.Medium(index=fiber_ncore)
grating_start = (- fiber_xposition)
cell_size = mp.Vector3(sxy, sz)
fiber_port_y = (((- sz) / 2) + (((((((+ pml_thickness) + substrate_thickness) + bottom_clad_thickness) + core_thickness) + top_clad_thickness) + air_gap_thickness) + fiber_port_y_offset_from_air))
fiber_port_center = mp.Vector3(fiber_port_x_offset_from_angle, fiber_port_y)
fiber_port_x_size = (fiber_port_x_size or (3.5 * fiber_core_diameter))
fiber_port_size = mp.Vector3(fiber_port_x_size, 0, 0)
fiber_port_direction = mp.Vector3(y=(- 1)).rotate(mp.Vector3(z=1), ((- 1) * fiber_angle))
waveguide_port_y = (((- sz) / 2) + (((((+ pml_thickness) + substrate_thickness) + (bottom_clad_thickness / 2)) + (core_thickness / 2)) + (top_clad_thickness / 2)))
waveguide_port_x = (grating_start - waveguide_port_x_offset_from_grating_start)
waveguide_port_center = mp.Vector3(waveguide_port_x, waveguide_port_y)
waveguide_port_size = mp.Vector3(0, ((bottom_clad_thickness + (core_thickness / 2)) + top_clad_thickness))
waveguide_port_direction = mp.X
fiber_clad = 120
hfiber_geom = 200
geometry = []
geometry.append(mp.Block(material=fiber_clad_material, center=mp.Vector3(0, (waveguide_port_y - (core_thickness / 2))), size=mp.Vector3(fiber_clad, hfiber_geom), e1=mp.Vector3(x=1).rotate(mp.Vector3(z=1), ((- 1) * fiber_angle)), e2=mp.Vector3(y=1).rotate(mp.Vector3(z=1), ((- 1) * fiber_angle))))
geometry.append(mp.Block(material=fiber_core_material, center=mp.Vector3(x=0), size=mp.Vector3(fiber_core_diameter, hfiber_geom), e1=mp.Vector3(x=1).rotate(mp.Vector3(z=1), ((- 1) * fiber_angle)), e2=mp.Vector3(y=1).rotate(mp.Vector3(z=1), ((- 1) * fiber_angle))))
geometry.append(mp.Block(material=mp.air, center=mp.Vector3(0, (((- sz) / 2) + ((((((+ pml_thickness) + substrate_thickness) + bottom_clad_thickness) + core_thickness) + top_clad_thickness) + (air_gap_thickness / 2)))), size=mp.Vector3(mp.inf, air_gap_thickness)))
geometry.append(mp.Block(material=top_clad_material, center=mp.Vector3(0, (((- sz) / 2) + (((((+ pml_thickness) + substrate_thickness) + bottom_clad_thickness) + (core_thickness / 2)) + (top_clad_thickness / 2)))), size=mp.Vector3(mp.inf, (core_thickness + top_clad_thickness))))
geometry.append(mp.Block(material=bottom_clad_material, center=mp.Vector3(0, (((- sz) / 2) + (((+ pml_thickness) + substrate_thickness) + (bottom_clad_thickness / 2)))), size=mp.Vector3(mp.inf, bottom_clad_thickness)))
geometry.append(mp.Block(material=core_material, center=mp.Vector3(0, (((- sz) / 2) + ((((+ pml_thickness) + substrate_thickness) + bottom_clad_thickness) + (core_thickness / 2)))), size=mp.Vector3(mp.inf, core_thickness)))
x = grating_start
for (width, gap) in zip(widths, gaps):
geometry.append(mp.Block(material=top_clad_material, center=mp.Vector3((x + (gap / 2)), (((- sz) / 2) + (((((+ pml_thickness) + substrate_thickness) + bottom_clad_thickness) + core_thickness) - (etch_depth / 2)))), size=mp.Vector3(gap, etch_depth)))
x += (width + gap)
geometry.append(mp.Block(material=mp.Medium(index=nsubstrate), center=mp.Vector3(0, ((((- sz) / 2) + (pml_thickness / 2)) + (substrate_thickness / 2))), size=mp.Vector3(mp.inf, (pml_thickness + substrate_thickness))))
boundary_layers = [mp.PML(pml_thickness)]
fcen = (1 / wavelength)
fwidth = (0.2 * fcen)
sources_directions = [mp.X]
sources = [mp.EigenModeSource(src=mp.GaussianSource(frequency=fcen, fwidth=fwidth), size=waveguide_port_size, center=waveguide_port_center, eig_band=1, direction=sources_directions[0], eig_match_freq=True, eig_parity=mp.ODD_Z)]
waveguide_monitor_port = mp.ModeRegion(center=(waveguide_port_center + mp.Vector3(x=0.2)), size=waveguide_port_size)
fiber_monitor_port = mp.ModeRegion(center=(fiber_port_center - mp.Vector3(y=0.2)), size=fiber_port_size)
sim = mp.Simulation(resolution=res, cell_size=cell_size, boundary_layers=boundary_layers, geometry=geometry, sources=sources, dimensions=2, eps_averaging=eps_averaging)
waveguide_monitor = sim.add_mode_monitor(freqs, waveguide_monitor_port, yee_grid=True)
fiber_monitor = sim.add_mode_monitor(freqs, fiber_monitor_port)
field_monitor_point = (0, 0, 0)
return dict(sim=sim, cell_size=cell_size, freqs=freqs, fcen=fcen, waveguide_monitor=waveguide_monitor, waveguide_port_direction=waveguide_port_direction, fiber_monitor=fiber_monitor, fiber_angle_deg=fiber_angle_deg, sources=sources, field_monitor_point=field_monitor_point, initialized=False, settings=settings) | def get_simulation_fiber(period: float=0.66, fill_factor: float=0.5, widths: Optional[Floats]=None, gaps: Optional[Floats]=None, n_periods: int=30, etch_depth: float=(70 * nm), fiber_angle_deg: float=20.0, fiber_xposition: float=1.0, fiber_core_diameter: float=10.4, fiber_numerical_aperture: float=0.14, fiber_nclad: float=nSiO2, ncore: float=nSi, ncladtop: float=nSiO2, ncladbottom: float=nSiO2, nsubstrate: float=nSi, pml_thickness: float=1.0, substrate_thickness: float=1.0, bottom_clad_thickness: float=2.0, core_thickness: float=(220 * nm), top_clad_thickness: float=2.0, air_gap_thickness: float=1.0, fiber_thickness: float=2.0, res: int=64, wavelength_min: float=1.4, wavelength_max: float=1.7, wavelength_points: int=150, eps_averaging: bool=False, fiber_port_y_offset_from_air: float=1, waveguide_port_x_offset_from_grating_start: float=10, fiber_port_x_size: Optional[float]=None) -> Dict[(str, Any)]:
'Returns simulation results from grating coupler with fiber.\n na**2 = ncore**2 - nclad**2\n ncore = sqrt(na**2 + ncore**2)\n\n Args:\n TODO\n '
wavelengths = np.linspace(wavelength_min, wavelength_max, wavelength_points)
wavelength = np.mean(wavelengths)
freqs = (1 / wavelengths)
widths = (widths or (n_periods * [(period * fill_factor)]))
gaps = (gaps or (n_periods * [(period * (1 - fill_factor))]))
settings = dict(widths=widths, gaps=gaps, n_periods=n_periods, etch_depth=etch_depth, fiber_angle_deg=fiber_angle_deg, fiber_xposition=fiber_xposition, fiber_core_diameter=fiber_core_diameter, fiber_numerical_aperture=fiber_numerical_aperture, fiber_nclad=fiber_nclad, ncore=ncore, ncladtop=ncladtop, ncladbottom=ncladbottom, nsubstrate=nsubstrate, pml_thickness=pml_thickness, substrate_thickness=substrate_thickness, bottom_clad_thickness=bottom_clad_thickness, core_thickness=core_thickness, top_clad_thickness=top_clad_thickness, air_gap_thickness=air_gap_thickness, fiber_thickness=fiber_thickness, res=res, wavelength_min=wavelength_min, wavelength_max=wavelength_max, wavelength_points=wavelength_points, eps_averaging=eps_averaging, fiber_port_y_offset_from_air=fiber_port_y_offset_from_air, waveguide_port_x_offset_from_grating_start=waveguide_port_x_offset_from_grating_start, fiber_port_x_size=fiber_port_x_size)
settings_string = to_string(settings)
settings_hash = hashlib.md5(settings_string.encode()).hexdigest()[:8]
fiber_angle = np.radians(fiber_angle_deg)
sz = ((((((((+ pml_thickness) + substrate_thickness) + bottom_clad_thickness) + core_thickness) + top_clad_thickness) + air_gap_thickness) + fiber_thickness) + pml_thickness)
fiber_port_y = ((((((- sz) / 2) + core_thickness) + top_clad_thickness) + air_gap_thickness) + fiber_port_y_offset_from_air)
fiber_port_x_offset_from_angle = np.abs((fiber_port_y * np.tan(fiber_angle)))
sxy = (((3.5 * fiber_core_diameter) + (2 * pml_thickness)) + (2 * fiber_port_x_offset_from_angle))
core_material = mp.Medium(index=ncore)
top_clad_material = mp.Medium(index=ncladtop)
bottom_clad_material = mp.Medium(index=ncladbottom)
fiber_ncore = (((fiber_numerical_aperture ** 2) + (fiber_nclad ** 2)) ** 0.5)
fiber_clad_material = mp.Medium(index=fiber_nclad)
fiber_core_material = mp.Medium(index=fiber_ncore)
grating_start = (- fiber_xposition)
cell_size = mp.Vector3(sxy, sz)
fiber_port_y = (((- sz) / 2) + (((((((+ pml_thickness) + substrate_thickness) + bottom_clad_thickness) + core_thickness) + top_clad_thickness) + air_gap_thickness) + fiber_port_y_offset_from_air))
fiber_port_center = mp.Vector3(fiber_port_x_offset_from_angle, fiber_port_y)
fiber_port_x_size = (fiber_port_x_size or (3.5 * fiber_core_diameter))
fiber_port_size = mp.Vector3(fiber_port_x_size, 0, 0)
fiber_port_direction = mp.Vector3(y=(- 1)).rotate(mp.Vector3(z=1), ((- 1) * fiber_angle))
waveguide_port_y = (((- sz) / 2) + (((((+ pml_thickness) + substrate_thickness) + (bottom_clad_thickness / 2)) + (core_thickness / 2)) + (top_clad_thickness / 2)))
waveguide_port_x = (grating_start - waveguide_port_x_offset_from_grating_start)
waveguide_port_center = mp.Vector3(waveguide_port_x, waveguide_port_y)
waveguide_port_size = mp.Vector3(0, ((bottom_clad_thickness + (core_thickness / 2)) + top_clad_thickness))
waveguide_port_direction = mp.X
fiber_clad = 120
hfiber_geom = 200
geometry = []
geometry.append(mp.Block(material=fiber_clad_material, center=mp.Vector3(0, (waveguide_port_y - (core_thickness / 2))), size=mp.Vector3(fiber_clad, hfiber_geom), e1=mp.Vector3(x=1).rotate(mp.Vector3(z=1), ((- 1) * fiber_angle)), e2=mp.Vector3(y=1).rotate(mp.Vector3(z=1), ((- 1) * fiber_angle))))
geometry.append(mp.Block(material=fiber_core_material, center=mp.Vector3(x=0), size=mp.Vector3(fiber_core_diameter, hfiber_geom), e1=mp.Vector3(x=1).rotate(mp.Vector3(z=1), ((- 1) * fiber_angle)), e2=mp.Vector3(y=1).rotate(mp.Vector3(z=1), ((- 1) * fiber_angle))))
geometry.append(mp.Block(material=mp.air, center=mp.Vector3(0, (((- sz) / 2) + ((((((+ pml_thickness) + substrate_thickness) + bottom_clad_thickness) + core_thickness) + top_clad_thickness) + (air_gap_thickness / 2)))), size=mp.Vector3(mp.inf, air_gap_thickness)))
geometry.append(mp.Block(material=top_clad_material, center=mp.Vector3(0, (((- sz) / 2) + (((((+ pml_thickness) + substrate_thickness) + bottom_clad_thickness) + (core_thickness / 2)) + (top_clad_thickness / 2)))), size=mp.Vector3(mp.inf, (core_thickness + top_clad_thickness))))
geometry.append(mp.Block(material=bottom_clad_material, center=mp.Vector3(0, (((- sz) / 2) + (((+ pml_thickness) + substrate_thickness) + (bottom_clad_thickness / 2)))), size=mp.Vector3(mp.inf, bottom_clad_thickness)))
geometry.append(mp.Block(material=core_material, center=mp.Vector3(0, (((- sz) / 2) + ((((+ pml_thickness) + substrate_thickness) + bottom_clad_thickness) + (core_thickness / 2)))), size=mp.Vector3(mp.inf, core_thickness)))
x = grating_start
for (width, gap) in zip(widths, gaps):
geometry.append(mp.Block(material=top_clad_material, center=mp.Vector3((x + (gap / 2)), (((- sz) / 2) + (((((+ pml_thickness) + substrate_thickness) + bottom_clad_thickness) + core_thickness) - (etch_depth / 2)))), size=mp.Vector3(gap, etch_depth)))
x += (width + gap)
geometry.append(mp.Block(material=mp.Medium(index=nsubstrate), center=mp.Vector3(0, ((((- sz) / 2) + (pml_thickness / 2)) + (substrate_thickness / 2))), size=mp.Vector3(mp.inf, (pml_thickness + substrate_thickness))))
boundary_layers = [mp.PML(pml_thickness)]
fcen = (1 / wavelength)
fwidth = (0.2 * fcen)
sources_directions = [mp.X]
sources = [mp.EigenModeSource(src=mp.GaussianSource(frequency=fcen, fwidth=fwidth), size=waveguide_port_size, center=waveguide_port_center, eig_band=1, direction=sources_directions[0], eig_match_freq=True, eig_parity=mp.ODD_Z)]
waveguide_monitor_port = mp.ModeRegion(center=(waveguide_port_center + mp.Vector3(x=0.2)), size=waveguide_port_size)
fiber_monitor_port = mp.ModeRegion(center=(fiber_port_center - mp.Vector3(y=0.2)), size=fiber_port_size)
sim = mp.Simulation(resolution=res, cell_size=cell_size, boundary_layers=boundary_layers, geometry=geometry, sources=sources, dimensions=2, eps_averaging=eps_averaging)
waveguide_monitor = sim.add_mode_monitor(freqs, waveguide_monitor_port, yee_grid=True)
fiber_monitor = sim.add_mode_monitor(freqs, fiber_monitor_port)
field_monitor_point = (0, 0, 0)
return dict(sim=sim, cell_size=cell_size, freqs=freqs, fcen=fcen, waveguide_monitor=waveguide_monitor, waveguide_port_direction=waveguide_port_direction, fiber_monitor=fiber_monitor, fiber_angle_deg=fiber_angle_deg, sources=sources, field_monitor_point=field_monitor_point, initialized=False, settings=settings)<|docstring|>Returns simulation results from grating coupler with fiber.
na**2 = ncore**2 - nclad**2
ncore = sqrt(na**2 + ncore**2)
Args:
TODO<|endoftext|> |
353f77ea5709c8dd20dbb3eaa805e1b045e1717ea1802ee3cf1563ecb569eded | def get_port_1D_eigenmode(sim_dict, band_num=1, fiber_angle_deg=15):
'\n\n Args:\n sim_dict: simulation dict\n band_num: band number to solve for\n\n Returns:\n Mode object compatible with /modes plugin\n '
sim = sim_dict['sim']
source = sim_dict['sources'][0]
waveguide_monitor = sim_dict['waveguide_monitor']
fiber_monitor = sim_dict['fiber_monitor']
fsrc = source.src.frequency
center_fiber = fiber_monitor.regions[0].center
size_fiber = fiber_monitor.regions[0].size
center_waveguide = waveguide_monitor.regions[0].center
size_waveguide = waveguide_monitor.regions[0].size
if (sim_dict['initialized'] is False):
sim.init_sim()
sim_dict['initialized'] = True
eigenmode_waveguide = sim.get_eigenmode(direction=mp.X, where=mp.Volume(center=center_waveguide, size=size_waveguide), band_num=band_num, kpoint=mp.Vector3((fsrc * 3.48), 0, 0), frequency=fsrc)
ys_waveguide = np.linspace((center_waveguide.y - (size_waveguide.y / 2)), (center_waveguide.y + (size_waveguide.y / 2)), int((sim.resolution * size_waveguide.y)))
x_waveguide = center_waveguide.x
eigenmode_fiber = sim.get_eigenmode(direction=mp.NO_DIRECTION, where=mp.Volume(center=center_fiber, size=size_fiber), band_num=band_num, kpoint=mp.Vector3(0, (fsrc * 1.45), 0).rotate(mp.Vector3(z=1), ((- 1) * np.radians(fiber_angle_deg))), frequency=fsrc)
xs_fiber = np.linspace((center_fiber.x - (size_fiber.x / 2)), (center_fiber.x + (size_fiber.x / 2)), int((sim.resolution * size_fiber.x)))
y_fiber = center_fiber.y
return (x_waveguide, ys_waveguide, eigenmode_waveguide, xs_fiber, y_fiber, eigenmode_fiber) | Args:
sim_dict: simulation dict
band_num: band number to solve for
Returns:
Mode object compatible with /modes plugin | optio/get_simulation_fiber.py | get_port_1D_eigenmode | simbilod/grating_coupler_meep | 1 | python | def get_port_1D_eigenmode(sim_dict, band_num=1, fiber_angle_deg=15):
'\n\n Args:\n sim_dict: simulation dict\n band_num: band number to solve for\n\n Returns:\n Mode object compatible with /modes plugin\n '
sim = sim_dict['sim']
source = sim_dict['sources'][0]
waveguide_monitor = sim_dict['waveguide_monitor']
fiber_monitor = sim_dict['fiber_monitor']
fsrc = source.src.frequency
center_fiber = fiber_monitor.regions[0].center
size_fiber = fiber_monitor.regions[0].size
center_waveguide = waveguide_monitor.regions[0].center
size_waveguide = waveguide_monitor.regions[0].size
if (sim_dict['initialized'] is False):
sim.init_sim()
sim_dict['initialized'] = True
eigenmode_waveguide = sim.get_eigenmode(direction=mp.X, where=mp.Volume(center=center_waveguide, size=size_waveguide), band_num=band_num, kpoint=mp.Vector3((fsrc * 3.48), 0, 0), frequency=fsrc)
ys_waveguide = np.linspace((center_waveguide.y - (size_waveguide.y / 2)), (center_waveguide.y + (size_waveguide.y / 2)), int((sim.resolution * size_waveguide.y)))
x_waveguide = center_waveguide.x
eigenmode_fiber = sim.get_eigenmode(direction=mp.NO_DIRECTION, where=mp.Volume(center=center_fiber, size=size_fiber), band_num=band_num, kpoint=mp.Vector3(0, (fsrc * 1.45), 0).rotate(mp.Vector3(z=1), ((- 1) * np.radians(fiber_angle_deg))), frequency=fsrc)
xs_fiber = np.linspace((center_fiber.x - (size_fiber.x / 2)), (center_fiber.x + (size_fiber.x / 2)), int((sim.resolution * size_fiber.x)))
y_fiber = center_fiber.y
return (x_waveguide, ys_waveguide, eigenmode_waveguide, xs_fiber, y_fiber, eigenmode_fiber) | def get_port_1D_eigenmode(sim_dict, band_num=1, fiber_angle_deg=15):
'\n\n Args:\n sim_dict: simulation dict\n band_num: band number to solve for\n\n Returns:\n Mode object compatible with /modes plugin\n '
sim = sim_dict['sim']
source = sim_dict['sources'][0]
waveguide_monitor = sim_dict['waveguide_monitor']
fiber_monitor = sim_dict['fiber_monitor']
fsrc = source.src.frequency
center_fiber = fiber_monitor.regions[0].center
size_fiber = fiber_monitor.regions[0].size
center_waveguide = waveguide_monitor.regions[0].center
size_waveguide = waveguide_monitor.regions[0].size
if (sim_dict['initialized'] is False):
sim.init_sim()
sim_dict['initialized'] = True
eigenmode_waveguide = sim.get_eigenmode(direction=mp.X, where=mp.Volume(center=center_waveguide, size=size_waveguide), band_num=band_num, kpoint=mp.Vector3((fsrc * 3.48), 0, 0), frequency=fsrc)
ys_waveguide = np.linspace((center_waveguide.y - (size_waveguide.y / 2)), (center_waveguide.y + (size_waveguide.y / 2)), int((sim.resolution * size_waveguide.y)))
x_waveguide = center_waveguide.x
eigenmode_fiber = sim.get_eigenmode(direction=mp.NO_DIRECTION, where=mp.Volume(center=center_fiber, size=size_fiber), band_num=band_num, kpoint=mp.Vector3(0, (fsrc * 1.45), 0).rotate(mp.Vector3(z=1), ((- 1) * np.radians(fiber_angle_deg))), frequency=fsrc)
xs_fiber = np.linspace((center_fiber.x - (size_fiber.x / 2)), (center_fiber.x + (size_fiber.x / 2)), int((sim.resolution * size_fiber.x)))
y_fiber = center_fiber.y
return (x_waveguide, ys_waveguide, eigenmode_waveguide, xs_fiber, y_fiber, eigenmode_fiber)<|docstring|>Args:
sim_dict: simulation dict
band_num: band number to solve for
Returns:
Mode object compatible with /modes plugin<|endoftext|> |
25bde179d2afb9a36ff826f6355453dfbb045798db98f5c1423bc425729836ce | def plot(sim, eps_parameters=None):
'\n sim: simulation object\n '
sim.plot2D(eps_parameters=eps_parameters) | sim: simulation object | optio/get_simulation_fiber.py | plot | simbilod/grating_coupler_meep | 1 | python | def plot(sim, eps_parameters=None):
'\n \n '
sim.plot2D(eps_parameters=eps_parameters) | def plot(sim, eps_parameters=None):
'\n \n '
sim.plot2D(eps_parameters=eps_parameters)<|docstring|>sim: simulation object<|endoftext|> |
a6cf938b6406cd8e2fa1f8a72ac1f639325e306065724044d52cfcbbdc325325 | @staticmethod
def add_args(parser):
'Add model-specific arguments to the parser.'
parser.add_argument('--num-features', type=int)
parser.add_argument('--hidden-size', type=int, default=256)
parser.add_argument('--embedding-size', type=int, default=16)
parser.add_argument('--num-heads', type=int, default=1)
parser.add_argument('--dropout', type=float, default=0)
parser.add_argument('--max-epoch', type=int, default=100)
parser.add_argument('--lr', type=float, default=0.001)
parser.add_argument('--gamma', type=float, default=10) | Add model-specific arguments to the parser. | cogdl/models/nn/daegc.py | add_args | THUDM/cogdl | 1,072 | python | @staticmethod
def add_args(parser):
parser.add_argument('--num-features', type=int)
parser.add_argument('--hidden-size', type=int, default=256)
parser.add_argument('--embedding-size', type=int, default=16)
parser.add_argument('--num-heads', type=int, default=1)
parser.add_argument('--dropout', type=float, default=0)
parser.add_argument('--max-epoch', type=int, default=100)
parser.add_argument('--lr', type=float, default=0.001)
parser.add_argument('--gamma', type=float, default=10) | @staticmethod
def add_args(parser):
parser.add_argument('--num-features', type=int)
parser.add_argument('--hidden-size', type=int, default=256)
parser.add_argument('--embedding-size', type=int, default=16)
parser.add_argument('--num-heads', type=int, default=1)
parser.add_argument('--dropout', type=float, default=0)
parser.add_argument('--max-epoch', type=int, default=100)
parser.add_argument('--lr', type=float, default=0.001)
parser.add_argument('--gamma', type=float, default=10)<|docstring|>Add model-specific arguments to the parser.<|endoftext|> |
1814340ed5c0db12889dddbb9a868310cbe643706c2b1ce33cccdf0d995ff72b | def get_2hop(self, edge_index):
'add 2-hop neighbors as new edges'
G = nx.Graph()
edge_index = torch.stack(edge_index)
G.add_edges_from(edge_index.t().tolist())
H = nx.Graph()
for i in range(G.number_of_nodes()):
layers = dict(nx.bfs_successors(G, source=i, depth_limit=2))
for succ in layers:
for idx in layers[succ]:
H.add_edge(i, idx)
return torch.tensor(list(H.edges())).t() | add 2-hop neighbors as new edges | cogdl/models/nn/daegc.py | get_2hop | THUDM/cogdl | 1,072 | python | def get_2hop(self, edge_index):
G = nx.Graph()
edge_index = torch.stack(edge_index)
G.add_edges_from(edge_index.t().tolist())
H = nx.Graph()
for i in range(G.number_of_nodes()):
layers = dict(nx.bfs_successors(G, source=i, depth_limit=2))
for succ in layers:
for idx in layers[succ]:
H.add_edge(i, idx)
return torch.tensor(list(H.edges())).t() | def get_2hop(self, edge_index):
G = nx.Graph()
edge_index = torch.stack(edge_index)
G.add_edges_from(edge_index.t().tolist())
H = nx.Graph()
for i in range(G.number_of_nodes()):
layers = dict(nx.bfs_successors(G, source=i, depth_limit=2))
for succ in layers:
for idx in layers[succ]:
H.add_edge(i, idx)
return torch.tensor(list(H.edges())).t()<|docstring|>add 2-hop neighbors as new edges<|endoftext|> |
666b3e1833b8e39d7c4a290271df5e7cd75a6d94ba719bbd8c9437b94e733d0a | def set_peek(self, dataset):
'Set the peek and blurb text'
if (not dataset.dataset.purged):
dataset.peek = get_file_peek(dataset.file_name)
dataset.blurb = 'NCBI Blast XML data'
else:
dataset.peek = 'file does not exist'
dataset.blurb = 'file purged from disk' | Set the peek and blurb text | lib/galaxy/datatypes/blast.py | set_peek | quacksawbones/galaxy-1 | 1,085 | python | def set_peek(self, dataset):
if (not dataset.dataset.purged):
dataset.peek = get_file_peek(dataset.file_name)
dataset.blurb = 'NCBI Blast XML data'
else:
dataset.peek = 'file does not exist'
dataset.blurb = 'file purged from disk' | def set_peek(self, dataset):
if (not dataset.dataset.purged):
dataset.peek = get_file_peek(dataset.file_name)
dataset.blurb = 'NCBI Blast XML data'
else:
dataset.peek = 'file does not exist'
dataset.blurb = 'file purged from disk'<|docstring|>Set the peek and blurb text<|endoftext|> |
9b1046896d9552e2070023915ed497e977088616b85e714cd8d5945faac5f14c | def sniff_prefix(self, file_prefix: FilePrefix):
"Determines whether the file is blastxml\n\n >>> from galaxy.datatypes.sniff import get_test_fname\n >>> fname = get_test_fname('megablast_xml_parser_test1.blastxml')\n >>> BlastXml().sniff(fname)\n True\n >>> fname = get_test_fname('tblastn_four_human_vs_rhodopsin.blastxml')\n >>> BlastXml().sniff(fname)\n True\n >>> fname = get_test_fname('interval.interval')\n >>> BlastXml().sniff(fname)\n False\n "
handle = file_prefix.string_io()
line = handle.readline()
if (line.strip() != '<?xml version="1.0"?>'):
return False
line = handle.readline()
if (line.strip() not in ['<!DOCTYPE BlastOutput PUBLIC "-//NCBI//NCBI BlastOutput/EN" "http://www.ncbi.nlm.nih.gov/dtd/NCBI_BlastOutput.dtd">', '<!DOCTYPE BlastOutput PUBLIC "-//NCBI//NCBI BlastOutput/EN" "NCBI_BlastOutput.dtd">']):
return False
line = handle.readline()
if (line.strip() != '<BlastOutput>'):
return False
return True | Determines whether the file is blastxml
>>> from galaxy.datatypes.sniff import get_test_fname
>>> fname = get_test_fname('megablast_xml_parser_test1.blastxml')
>>> BlastXml().sniff(fname)
True
>>> fname = get_test_fname('tblastn_four_human_vs_rhodopsin.blastxml')
>>> BlastXml().sniff(fname)
True
>>> fname = get_test_fname('interval.interval')
>>> BlastXml().sniff(fname)
False | lib/galaxy/datatypes/blast.py | sniff_prefix | quacksawbones/galaxy-1 | 1,085 | python | def sniff_prefix(self, file_prefix: FilePrefix):
"Determines whether the file is blastxml\n\n >>> from galaxy.datatypes.sniff import get_test_fname\n >>> fname = get_test_fname('megablast_xml_parser_test1.blastxml')\n >>> BlastXml().sniff(fname)\n True\n >>> fname = get_test_fname('tblastn_four_human_vs_rhodopsin.blastxml')\n >>> BlastXml().sniff(fname)\n True\n >>> fname = get_test_fname('interval.interval')\n >>> BlastXml().sniff(fname)\n False\n "
handle = file_prefix.string_io()
line = handle.readline()
if (line.strip() != '<?xml version="1.0"?>'):
return False
line = handle.readline()
if (line.strip() not in ['<!DOCTYPE BlastOutput PUBLIC "-//NCBI//NCBI BlastOutput/EN" "http://www.ncbi.nlm.nih.gov/dtd/NCBI_BlastOutput.dtd">', '<!DOCTYPE BlastOutput PUBLIC "-//NCBI//NCBI BlastOutput/EN" "NCBI_BlastOutput.dtd">']):
return False
line = handle.readline()
if (line.strip() != '<BlastOutput>'):
return False
return True | def sniff_prefix(self, file_prefix: FilePrefix):
"Determines whether the file is blastxml\n\n >>> from galaxy.datatypes.sniff import get_test_fname\n >>> fname = get_test_fname('megablast_xml_parser_test1.blastxml')\n >>> BlastXml().sniff(fname)\n True\n >>> fname = get_test_fname('tblastn_four_human_vs_rhodopsin.blastxml')\n >>> BlastXml().sniff(fname)\n True\n >>> fname = get_test_fname('interval.interval')\n >>> BlastXml().sniff(fname)\n False\n "
handle = file_prefix.string_io()
line = handle.readline()
if (line.strip() != '<?xml version="1.0"?>'):
return False
line = handle.readline()
if (line.strip() not in ['<!DOCTYPE BlastOutput PUBLIC "-//NCBI//NCBI BlastOutput/EN" "http://www.ncbi.nlm.nih.gov/dtd/NCBI_BlastOutput.dtd">', '<!DOCTYPE BlastOutput PUBLIC "-//NCBI//NCBI BlastOutput/EN" "NCBI_BlastOutput.dtd">']):
return False
line = handle.readline()
if (line.strip() != '<BlastOutput>'):
return False
return True<|docstring|>Determines whether the file is blastxml
>>> from galaxy.datatypes.sniff import get_test_fname
>>> fname = get_test_fname('megablast_xml_parser_test1.blastxml')
>>> BlastXml().sniff(fname)
True
>>> fname = get_test_fname('tblastn_four_human_vs_rhodopsin.blastxml')
>>> BlastXml().sniff(fname)
True
>>> fname = get_test_fname('interval.interval')
>>> BlastXml().sniff(fname)
False<|endoftext|> |
abd1272261a6a008ae8704d5188a5663bc82b287d4790f3b2d514f0aef4afb24 | @staticmethod
def merge(split_files, output_file):
'Merging multiple XML files is non-trivial and must be done in subclasses.'
if (len(split_files) == 1):
return Text.merge(split_files, output_file)
if (not split_files):
raise ValueError(('Given no BLAST XML files, %r, to merge into %s' % (split_files, output_file)))
with open(output_file, 'w') as out:
h = None
old_header = None
for f in split_files:
if (not os.path.isfile(f)):
log.warning(f'BLAST XML file {f} missing, retry in 1s...')
sleep(1)
if (not os.path.isfile(f)):
log.error(f'BLAST XML file {f} missing')
raise ValueError(f'BLAST XML file {f} missing')
h = open(f)
header = h.readline()
if (not header):
h.close()
log.warning(f'BLAST XML file {f} empty, retry in 1s...')
sleep(1)
h = open(f)
header = h.readline()
if (not header):
log.error(f'BLAST XML file {f} was empty')
raise ValueError(f'BLAST XML file {f} was empty')
if (header.strip() != '<?xml version="1.0"?>'):
out.write(header)
h.close()
raise ValueError(f'{f} is not an XML file!')
line = h.readline()
header += line
if (line.strip() not in ['<!DOCTYPE BlastOutput PUBLIC "-//NCBI//NCBI BlastOutput/EN" "http://www.ncbi.nlm.nih.gov/dtd/NCBI_BlastOutput.dtd">', '<!DOCTYPE BlastOutput PUBLIC "-//NCBI//NCBI BlastOutput/EN" "NCBI_BlastOutput.dtd">']):
out.write(header)
h.close()
raise ValueError(f'{f} is not a BLAST XML file!')
while True:
line = h.readline()
if (not line):
out.write(header)
h.close()
raise ValueError(f'BLAST XML file {f} ended prematurely')
header += line
if ('<Iteration>' in line):
break
if (len(header) > 10000):
out.write(header)
h.close()
raise ValueError(f'The header in BLAST XML file {f} is too long')
if ('<BlastOutput>' not in header):
h.close()
raise ValueError(f'''{f} is not a BLAST XML file:
{header}
...''')
if (f == split_files[0]):
out.write(header)
old_header = header
elif ((old_header is not None) and (old_header[:300] != header[:300])):
h.close()
raise ValueError(("BLAST XML headers don't match for %s and %s - have:\n%s\n...\n\nAnd:\n%s\n...\n" % (split_files[0], f, old_header[:300], header[:300])))
else:
out.write(' <Iteration>\n')
for line in h:
if ('</BlastOutput_iterations>' in line):
break
out.write(line)
h.close()
out.write(' </BlastOutput_iterations>\n')
out.write('</BlastOutput>\n') | Merging multiple XML files is non-trivial and must be done in subclasses. | lib/galaxy/datatypes/blast.py | merge | quacksawbones/galaxy-1 | 1,085 | python | @staticmethod
def merge(split_files, output_file):
if (len(split_files) == 1):
return Text.merge(split_files, output_file)
if (not split_files):
raise ValueError(('Given no BLAST XML files, %r, to merge into %s' % (split_files, output_file)))
with open(output_file, 'w') as out:
h = None
old_header = None
for f in split_files:
if (not os.path.isfile(f)):
log.warning(f'BLAST XML file {f} missing, retry in 1s...')
sleep(1)
if (not os.path.isfile(f)):
log.error(f'BLAST XML file {f} missing')
raise ValueError(f'BLAST XML file {f} missing')
h = open(f)
header = h.readline()
if (not header):
h.close()
log.warning(f'BLAST XML file {f} empty, retry in 1s...')
sleep(1)
h = open(f)
header = h.readline()
if (not header):
log.error(f'BLAST XML file {f} was empty')
raise ValueError(f'BLAST XML file {f} was empty')
if (header.strip() != '<?xml version="1.0"?>'):
out.write(header)
h.close()
raise ValueError(f'{f} is not an XML file!')
line = h.readline()
header += line
if (line.strip() not in ['<!DOCTYPE BlastOutput PUBLIC "-//NCBI//NCBI BlastOutput/EN" "http://www.ncbi.nlm.nih.gov/dtd/NCBI_BlastOutput.dtd">', '<!DOCTYPE BlastOutput PUBLIC "-//NCBI//NCBI BlastOutput/EN" "NCBI_BlastOutput.dtd">']):
out.write(header)
h.close()
raise ValueError(f'{f} is not a BLAST XML file!')
while True:
line = h.readline()
if (not line):
out.write(header)
h.close()
raise ValueError(f'BLAST XML file {f} ended prematurely')
header += line
if ('<Iteration>' in line):
break
if (len(header) > 10000):
out.write(header)
h.close()
raise ValueError(f'The header in BLAST XML file {f} is too long')
if ('<BlastOutput>' not in header):
h.close()
raise ValueError(f'{f} is not a BLAST XML file:
{header}
...')
if (f == split_files[0]):
out.write(header)
old_header = header
elif ((old_header is not None) and (old_header[:300] != header[:300])):
h.close()
raise ValueError(("BLAST XML headers don't match for %s and %s - have:\n%s\n...\n\nAnd:\n%s\n...\n" % (split_files[0], f, old_header[:300], header[:300])))
else:
out.write(' <Iteration>\n')
for line in h:
if ('</BlastOutput_iterations>' in line):
break
out.write(line)
h.close()
out.write(' </BlastOutput_iterations>\n')
out.write('</BlastOutput>\n') | @staticmethod
def merge(split_files, output_file):
if (len(split_files) == 1):
return Text.merge(split_files, output_file)
if (not split_files):
raise ValueError(('Given no BLAST XML files, %r, to merge into %s' % (split_files, output_file)))
with open(output_file, 'w') as out:
h = None
old_header = None
for f in split_files:
if (not os.path.isfile(f)):
log.warning(f'BLAST XML file {f} missing, retry in 1s...')
sleep(1)
if (not os.path.isfile(f)):
log.error(f'BLAST XML file {f} missing')
raise ValueError(f'BLAST XML file {f} missing')
h = open(f)
header = h.readline()
if (not header):
h.close()
log.warning(f'BLAST XML file {f} empty, retry in 1s...')
sleep(1)
h = open(f)
header = h.readline()
if (not header):
log.error(f'BLAST XML file {f} was empty')
raise ValueError(f'BLAST XML file {f} was empty')
if (header.strip() != '<?xml version="1.0"?>'):
out.write(header)
h.close()
raise ValueError(f'{f} is not an XML file!')
line = h.readline()
header += line
if (line.strip() not in ['<!DOCTYPE BlastOutput PUBLIC "-//NCBI//NCBI BlastOutput/EN" "http://www.ncbi.nlm.nih.gov/dtd/NCBI_BlastOutput.dtd">', '<!DOCTYPE BlastOutput PUBLIC "-//NCBI//NCBI BlastOutput/EN" "NCBI_BlastOutput.dtd">']):
out.write(header)
h.close()
raise ValueError(f'{f} is not a BLAST XML file!')
while True:
line = h.readline()
if (not line):
out.write(header)
h.close()
raise ValueError(f'BLAST XML file {f} ended prematurely')
header += line
if ('<Iteration>' in line):
break
if (len(header) > 10000):
out.write(header)
h.close()
raise ValueError(f'The header in BLAST XML file {f} is too long')
if ('<BlastOutput>' not in header):
h.close()
raise ValueError(f'{f} is not a BLAST XML file:
{header}
...')
if (f == split_files[0]):
out.write(header)
old_header = header
elif ((old_header is not None) and (old_header[:300] != header[:300])):
h.close()
raise ValueError(("BLAST XML headers don't match for %s and %s - have:\n%s\n...\n\nAnd:\n%s\n...\n" % (split_files[0], f, old_header[:300], header[:300])))
else:
out.write(' <Iteration>\n')
for line in h:
if ('</BlastOutput_iterations>' in line):
break
out.write(line)
h.close()
out.write(' </BlastOutput_iterations>\n')
out.write('</BlastOutput>\n')<|docstring|>Merging multiple XML files is non-trivial and must be done in subclasses.<|endoftext|> |
ba790fb602d230865d7cb299c9f828d048c2997c66746544b7794a20413e199c | def set_peek(self, dataset):
'Set the peek and blurb text.'
if (not dataset.dataset.purged):
dataset.peek = 'BLAST database (multiple files)'
dataset.blurb = 'BLAST database (multiple files)'
else:
dataset.peek = 'file does not exist'
dataset.blurb = 'file purged from disk' | Set the peek and blurb text. | lib/galaxy/datatypes/blast.py | set_peek | quacksawbones/galaxy-1 | 1,085 | python | def set_peek(self, dataset):
if (not dataset.dataset.purged):
dataset.peek = 'BLAST database (multiple files)'
dataset.blurb = 'BLAST database (multiple files)'
else:
dataset.peek = 'file does not exist'
dataset.blurb = 'file purged from disk' | def set_peek(self, dataset):
if (not dataset.dataset.purged):
dataset.peek = 'BLAST database (multiple files)'
dataset.blurb = 'BLAST database (multiple files)'
else:
dataset.peek = 'file does not exist'
dataset.blurb = 'file purged from disk'<|docstring|>Set the peek and blurb text.<|endoftext|> |
1a32aa38f632aaf722bbe17d5af6126e9e5aefd6e61c89a3cbf24afcf02b9d3a | def display_peek(self, dataset):
'Create HTML content, used for displaying peek.'
try:
return dataset.peek
except Exception:
return 'BLAST database (multiple files)' | Create HTML content, used for displaying peek. | lib/galaxy/datatypes/blast.py | display_peek | quacksawbones/galaxy-1 | 1,085 | python | def display_peek(self, dataset):
try:
return dataset.peek
except Exception:
return 'BLAST database (multiple files)' | def display_peek(self, dataset):
try:
return dataset.peek
except Exception:
return 'BLAST database (multiple files)'<|docstring|>Create HTML content, used for displaying peek.<|endoftext|> |
2956cd3c0db6d76f3423629bf665c315895f205335947be4d2907b17d69f0e69 | def display_data(self, trans, data, preview=False, filename=None, to_ext=None, size=None, offset=None, **kwd):
'\n If preview is `True` allows us to format the data shown in the central pane via the "eye" icon.\n If preview is `False` triggers download.\n '
headers = kwd.get('headers', {})
if (not preview):
return super().display_data(trans, data=data, preview=preview, filename=filename, to_ext=to_ext, size=size, offset=offset, **kwd)
if (self.file_ext == 'blastdbn'):
title = 'This is a nucleotide BLAST database'
elif (self.file_ext == 'blastdbp'):
title = 'This is a protein BLAST database'
elif (self.file_ext == 'blastdbd'):
title = 'This is a domain BLAST database'
else:
title = 'This is a BLAST database.'
msg = ''
try:
with open(data.file_name, encoding='utf-8') as handle:
msg = handle.read().strip()
except Exception:
pass
if (not msg):
msg = title
return (smart_str(f'<html><head><title>{title}</title></head><body><pre>{msg}</pre></body></html>'), headers) | If preview is `True` allows us to format the data shown in the central pane via the "eye" icon.
If preview is `False` triggers download. | lib/galaxy/datatypes/blast.py | display_data | quacksawbones/galaxy-1 | 1,085 | python | def display_data(self, trans, data, preview=False, filename=None, to_ext=None, size=None, offset=None, **kwd):
'\n If preview is `True` allows us to format the data shown in the central pane via the "eye" icon.\n If preview is `False` triggers download.\n '
headers = kwd.get('headers', {})
if (not preview):
return super().display_data(trans, data=data, preview=preview, filename=filename, to_ext=to_ext, size=size, offset=offset, **kwd)
if (self.file_ext == 'blastdbn'):
title = 'This is a nucleotide BLAST database'
elif (self.file_ext == 'blastdbp'):
title = 'This is a protein BLAST database'
elif (self.file_ext == 'blastdbd'):
title = 'This is a domain BLAST database'
else:
title = 'This is a BLAST database.'
msg =
try:
with open(data.file_name, encoding='utf-8') as handle:
msg = handle.read().strip()
except Exception:
pass
if (not msg):
msg = title
return (smart_str(f'<html><head><title>{title}</title></head><body><pre>{msg}</pre></body></html>'), headers) | def display_data(self, trans, data, preview=False, filename=None, to_ext=None, size=None, offset=None, **kwd):
'\n If preview is `True` allows us to format the data shown in the central pane via the "eye" icon.\n If preview is `False` triggers download.\n '
headers = kwd.get('headers', {})
if (not preview):
return super().display_data(trans, data=data, preview=preview, filename=filename, to_ext=to_ext, size=size, offset=offset, **kwd)
if (self.file_ext == 'blastdbn'):
title = 'This is a nucleotide BLAST database'
elif (self.file_ext == 'blastdbp'):
title = 'This is a protein BLAST database'
elif (self.file_ext == 'blastdbd'):
title = 'This is a domain BLAST database'
else:
title = 'This is a BLAST database.'
msg =
try:
with open(data.file_name, encoding='utf-8') as handle:
msg = handle.read().strip()
except Exception:
pass
if (not msg):
msg = title
return (smart_str(f'<html><head><title>{title}</title></head><body><pre>{msg}</pre></body></html>'), headers)<|docstring|>If preview is `True` allows us to format the data shown in the central pane via the "eye" icon.
If preview is `False` triggers download.<|endoftext|> |
13baf7392c638eec8745aebd677cddca15fdef22b4391bfc675ac8f024047f12 | def merge(split_files, output_file):
'Merge BLAST databases (not implemented for now).'
raise NotImplementedError('Merging BLAST databases is non-trivial (do this via makeblastdb?)') | Merge BLAST databases (not implemented for now). | lib/galaxy/datatypes/blast.py | merge | quacksawbones/galaxy-1 | 1,085 | python | def merge(split_files, output_file):
raise NotImplementedError('Merging BLAST databases is non-trivial (do this via makeblastdb?)') | def merge(split_files, output_file):
raise NotImplementedError('Merging BLAST databases is non-trivial (do this via makeblastdb?)')<|docstring|>Merge BLAST databases (not implemented for now).<|endoftext|> |
a96073b63de8be661c6f6758ad4ace5a8d32bf92ca7a06247e34673151ac6a3b | def split(cls, input_datasets, subdir_generator_function, split_params):
'Split a BLAST database (not implemented for now).'
if (split_params is None):
return None
raise NotImplementedError("Can't split BLAST databases") | Split a BLAST database (not implemented for now). | lib/galaxy/datatypes/blast.py | split | quacksawbones/galaxy-1 | 1,085 | python | def split(cls, input_datasets, subdir_generator_function, split_params):
if (split_params is None):
return None
raise NotImplementedError("Can't split BLAST databases") | def split(cls, input_datasets, subdir_generator_function, split_params):
if (split_params is None):
return None
raise NotImplementedError("Can't split BLAST databases")<|docstring|>Split a BLAST database (not implemented for now).<|endoftext|> |
0e4e31726b1ef3375c3ff1b20344912d1eee71b5aa1981da50c97bd89ee8ee01 | def set_peek(self, dataset):
'Set the peek and blurb text.'
if (not dataset.dataset.purged):
dataset.peek = 'LAST database (multiple files)'
dataset.blurb = 'LAST database (multiple files)'
else:
dataset.peek = 'file does not exist'
dataset.blurb = 'file purged from disk' | Set the peek and blurb text. | lib/galaxy/datatypes/blast.py | set_peek | quacksawbones/galaxy-1 | 1,085 | python | def set_peek(self, dataset):
if (not dataset.dataset.purged):
dataset.peek = 'LAST database (multiple files)'
dataset.blurb = 'LAST database (multiple files)'
else:
dataset.peek = 'file does not exist'
dataset.blurb = 'file purged from disk' | def set_peek(self, dataset):
if (not dataset.dataset.purged):
dataset.peek = 'LAST database (multiple files)'
dataset.blurb = 'LAST database (multiple files)'
else:
dataset.peek = 'file does not exist'
dataset.blurb = 'file purged from disk'<|docstring|>Set the peek and blurb text.<|endoftext|> |
1966267eca730d6a3ccfdd487cc7e9272d4784b9a4178ad4909c8ceeb07b771b | def display_peek(self, dataset):
'Create HTML content, used for displaying peek.'
try:
return dataset.peek
except Exception:
return 'LAST database (multiple files)' | Create HTML content, used for displaying peek. | lib/galaxy/datatypes/blast.py | display_peek | quacksawbones/galaxy-1 | 1,085 | python | def display_peek(self, dataset):
try:
return dataset.peek
except Exception:
return 'LAST database (multiple files)' | def display_peek(self, dataset):
try:
return dataset.peek
except Exception:
return 'LAST database (multiple files)'<|docstring|>Create HTML content, used for displaying peek.<|endoftext|> |
b4558b7d76dfffc6a7c67026edfd7eff4a3033a20fe01a3bd85c9ffa15b56967 | def main():
'\n FUNCTION DESCRIPTION\n OTHER COMMENTS\n INPUTS\n OUTPUTS\n EXAMPLES\n >>> main();\n hello world\n '
if (len(sys.argv) != 2):
raise ValueError('Expected one file as comandline argument')
try:
astart = str(input('enter analysis start date YYYYMMDD: '))
if (len(astart) != 8):
raise ValueError('Date format expected is YYYYMMDD')
astart_yr = int(astart[:4])
astart_mo = int(astart[4:6])
astart_da = int(astart[6:8])
aend = str(input('enter analysis end date YYYYMMDD: '))
if (len(aend) != 8):
raise ValueError('Date format expected is YYYYMMDD')
aend_yr = int(aend[:4])
aend_mo = int(aend[4:6])
aend_da = int(aend[6:8])
earliest_yr = 1910
cur_yr = datetime.date.today().year
if ((astart_yr < earliest_yr) or (astart_yr > cur_yr) or (aend_yr < earliest_yr) or (aend_yr > cur_yr)):
raise ValueError(('Date expected year YYYY between 1940 and %d' % yr))
elif ((astart_mo < 1) or (astart_mo > 12) or (aend_mo < 1) or (aend_mo > 12)):
raise ValueError('Date expected month MM between 1 and 12')
if ((astart_mo == 9) or (astart_mo == 4) or (astart_mo == 6) or (astart_mo == 11) or (aend_mo == 9) or (aend_mo == 4) or (aend_mo == 6) or (aend_mo == 11)):
if ((astart_da < 1) or (astart_da > 30) or (aend_da < 1) or (aend_da > 30)):
raise ValueError('Invalid day of month entered')
elif ((astart_da < 1) or (astart_da > 31) or (aend_da < 1) or (aend_da > 31)):
raise ValueError('Invalid day of month entered')
folio = pd.read_csv(sys.argv[1])
print('\n{0} tickers loaded from {1}\n'.format(len(folio['ticker']), sys.argv[1]))
for bd in folio['buy_date']:
buy_mo = int(str(bd)[4:6])
buy_da = int(str(bd)[6:8])
if ((buy_mo > 12) or (buy_mo < 1)):
raise ValueError('Invalid month in CSV')
if ((buy_mo == 9) or (buy_mo == 4) or (buy_mo == 6) or (buy_mo == 11)):
if ((buy_da < 1) or (buy_da > 30)):
raise ValueError('Invalid day of month in CSV')
elif ((buy_mo < 1) or (buy_da > 31)):
raise ValueError('Invalid day of month in CSV')
for (i, sd) in enumerate(folio['sell_date']):
if pd.isnull(sd):
folio.loc[(i, 'sell_date')] = aend
else:
sell_mo = int(str(sd)[4:6])
sell_da = int(str(sd)[6:8])
if ((sell_mo > 12) or (sell_mo < 1)):
raise ValueError('Invalid month in CSV')
if ((sell_mo == 9) or (sell_mo == 4) or (sell_mo == 6) or (sell_mo == 11)):
if ((sell_da < 1) or (sell_da > 30)):
raise ValueError('Invalid day of month in CSV')
elif ((sell_da < 1) or (sell_da > 31)):
raise ValueError('Invalid day of month in CSV')
index = input('1) FTSE 100; 2) S&P 500; 3) NASDAQ Composit\nselect a comparison index: ')
if (index == '1'):
index = '^FTSE'
elif (index == '2'):
index = '^GSPC'
elif (index == '3'):
index = '^IXIC'
else:
raise ValueError('Comparison index must be a number 1 - 3')
i = (- 1)
iflag = []
for row in folio.itertuples():
i = (i + 1)
buy_yr = int(str(folio.loc[(i, 'buy_date')])[:4])
buy_mo = int(str(folio.loc[(i, 'buy_date')])[4:6])
buy_da = int(str(folio.loc[(i, 'buy_date')])[6:8])
sell_yr = int(str(folio.loc[(i, 'sell_date')])[:4])
sell_mo = int(str(folio.loc[(i, 'sell_date')])[4:6])
sell_da = int(str(folio.loc[(i, 'sell_date')])[6:8])
if ((buy_yr > aend_yr) or ((buy_yr == aend_yr) and (buy_mo > aend_mo)) or ((buy_yr == aend_yr) and (buy_mo == aend_mo) and (buy_da > aend_da))):
iflag.append(i)
elif ((sell_yr < astart_yr) or ((sell_yr == astart_yr) and (sell_mo < astart_mo)) or ((sell_yr == astart_yr) and (sell_mo == astart_mo) and (buy_da < astart_da))):
iflag.append(i)
elif ((sell_yr > aend_yr) or ((sell_yr == aend_yr) and (sell_mo > aend_yr)) or ((sell_yr == aend_yr) and (sell_mo == aend_mo) and (sell_yr > aend_yr))):
folio.loc[(i, 'sell_date')] = ((str(aend_yr) + str(aend_mo)) + str(aend_da))
folio.loc[(i, 'sell_date')] = int(folio.loc[(i, 'sell_date')])
for i in iflag:
folio.drop(i, axis='index', inplace=True)
if (len(folio) < 1):
raise ValueError('CSV file has no valid lines')
folio.insert(len(folio.columns), '+-%', 'NA')
folio.insert(len(folio.columns), '+-GBP', 'NA')
i = (- 1)
for row in folio.itertuples():
i = (i + 1)
sell_yr = str(folio.loc[(i, 'sell_date')])[:4]
sell_mo = str(folio.loc[(i, 'sell_date')])[4:6]
sell_da = str(folio.loc[(i, 'sell_date')])[6:8]
sell_str = ((((sell_yr + '-') + sell_mo) + '-') + sell_da)
if (int(sell_da) >= 3):
start_da = (int(sell_da) - 3)
start_mo = int(sell_mo)
start_yr = int(sell_yr)
elif (int(sell_mo) > 1):
start_da = 25
start_mo = (int(sell_mo) - 1)
start_yr = int(sell_yr)
else:
start_da = 25
start_mo = 12
start_yr = (int(sell_yr) - 1)
start_str = ((((str(start_yr) + '-') + str(start_mo)) + '-') + str(start_da))
dat = yf.Ticker(row[1])
hist = dat.history(start=start_str, end=sell_str, interval='1d', actions='false')
if (folio.loc[(i, 'purchase_price_GBP')] < hist.iloc[(0, 3)]):
folio.loc[(i, '+-GBP')] = (hist.iloc[(0, 3)] - folio.loc[(i, 'purchase_price_GBP')])
else:
folio.loc[(i, '+-GBP')] = ((folio.loc[(i, 'purchase_price_GBP')] - hist.iloc[(0, 3)]) * (- 1))
folio.loc[(i, '+-%')] = (hist.iloc[(0, 3)] / folio.loc[(i, 'purchase_price_GBP')])
sumGBP = 0
sumPER = 0
for i in range(len(folio)):
sumGBP += folio.loc[(i, '+-GBP')]
sumPER += folio.loc[(i, '+-%')]
folio = folio.append({'ticker': 'TOTAL', '+-%': sumPER, '+-GBP': sumGBP}, ignore_index=True)
astart_str = ((((str(astart_yr) + '-') + str(astart_mo)) + '-') + str(astart_da))
aend_str = ((((str(aend_yr) + '-') + str(aend_mo)) + '-') + str(aend_da))
dat = yf.Ticker(index)
hist = dat.history(start=astart_str, end=aend_str, interval='1d', actions='false')
if (hist.iloc[(0, 3)] < hist.iloc[((len(hist) - 1), 3)]):
indexGBP = (hist.iloc[((len(hist) - 1), 3)] - hist.iloc[(0, 3)])
else:
indexGBP = (hist.iloc[(0, 3)] - hist.iloc[((len(hist) - 1), 3)])
indexPER = (hist.iloc[((len(hist) - 1), 3)] / hist.iloc[(0, 3)])
print('\n********************************************\n')
if (sumGBP > indexGBP):
print('Portfolio beat the market by £{:.0f} GBP, making a total of £{:.0f} GBP over the analysis periord'.format((sumGBP - indexGBP), indexGBP))
print('Percentage growth was {:.0f}% verses {:.0f}% for the index over the same periord'.format(sumPER, indexPER))
else:
print('Portfolio did not beat the market, making a total of £{:.0f} GBP over the analysis periord, £{:.0f} GBP less than the market'.format(sumGBP, (indexGBP - sumGBP)))
print('In percentage terms the portoflio changed by {:.0f}% verses {:.0f}% for the index over the same periord'.format(sumPER, indexPER))
except ValueError as err:
print(('Something went wrong: %s' % err), file=sys.stderr)
sys.exit(1)
return | FUNCTION DESCRIPTION
OTHER COMMENTS
INPUTS
OUTPUTS
EXAMPLES
>>> main();
hello world | portfolio_analysis.py | main | pushbuttondesign/finance | 0 | python | def main():
'\n FUNCTION DESCRIPTION\n OTHER COMMENTS\n INPUTS\n OUTPUTS\n EXAMPLES\n >>> main();\n hello world\n '
if (len(sys.argv) != 2):
raise ValueError('Expected one file as comandline argument')
try:
astart = str(input('enter analysis start date YYYYMMDD: '))
if (len(astart) != 8):
raise ValueError('Date format expected is YYYYMMDD')
astart_yr = int(astart[:4])
astart_mo = int(astart[4:6])
astart_da = int(astart[6:8])
aend = str(input('enter analysis end date YYYYMMDD: '))
if (len(aend) != 8):
raise ValueError('Date format expected is YYYYMMDD')
aend_yr = int(aend[:4])
aend_mo = int(aend[4:6])
aend_da = int(aend[6:8])
earliest_yr = 1910
cur_yr = datetime.date.today().year
if ((astart_yr < earliest_yr) or (astart_yr > cur_yr) or (aend_yr < earliest_yr) or (aend_yr > cur_yr)):
raise ValueError(('Date expected year YYYY between 1940 and %d' % yr))
elif ((astart_mo < 1) or (astart_mo > 12) or (aend_mo < 1) or (aend_mo > 12)):
raise ValueError('Date expected month MM between 1 and 12')
if ((astart_mo == 9) or (astart_mo == 4) or (astart_mo == 6) or (astart_mo == 11) or (aend_mo == 9) or (aend_mo == 4) or (aend_mo == 6) or (aend_mo == 11)):
if ((astart_da < 1) or (astart_da > 30) or (aend_da < 1) or (aend_da > 30)):
raise ValueError('Invalid day of month entered')
elif ((astart_da < 1) or (astart_da > 31) or (aend_da < 1) or (aend_da > 31)):
raise ValueError('Invalid day of month entered')
folio = pd.read_csv(sys.argv[1])
print('\n{0} tickers loaded from {1}\n'.format(len(folio['ticker']), sys.argv[1]))
for bd in folio['buy_date']:
buy_mo = int(str(bd)[4:6])
buy_da = int(str(bd)[6:8])
if ((buy_mo > 12) or (buy_mo < 1)):
raise ValueError('Invalid month in CSV')
if ((buy_mo == 9) or (buy_mo == 4) or (buy_mo == 6) or (buy_mo == 11)):
if ((buy_da < 1) or (buy_da > 30)):
raise ValueError('Invalid day of month in CSV')
elif ((buy_mo < 1) or (buy_da > 31)):
raise ValueError('Invalid day of month in CSV')
for (i, sd) in enumerate(folio['sell_date']):
if pd.isnull(sd):
folio.loc[(i, 'sell_date')] = aend
else:
sell_mo = int(str(sd)[4:6])
sell_da = int(str(sd)[6:8])
if ((sell_mo > 12) or (sell_mo < 1)):
raise ValueError('Invalid month in CSV')
if ((sell_mo == 9) or (sell_mo == 4) or (sell_mo == 6) or (sell_mo == 11)):
if ((sell_da < 1) or (sell_da > 30)):
raise ValueError('Invalid day of month in CSV')
elif ((sell_da < 1) or (sell_da > 31)):
raise ValueError('Invalid day of month in CSV')
index = input('1) FTSE 100; 2) S&P 500; 3) NASDAQ Composit\nselect a comparison index: ')
if (index == '1'):
index = '^FTSE'
elif (index == '2'):
index = '^GSPC'
elif (index == '3'):
index = '^IXIC'
else:
raise ValueError('Comparison index must be a number 1 - 3')
i = (- 1)
iflag = []
for row in folio.itertuples():
i = (i + 1)
buy_yr = int(str(folio.loc[(i, 'buy_date')])[:4])
buy_mo = int(str(folio.loc[(i, 'buy_date')])[4:6])
buy_da = int(str(folio.loc[(i, 'buy_date')])[6:8])
sell_yr = int(str(folio.loc[(i, 'sell_date')])[:4])
sell_mo = int(str(folio.loc[(i, 'sell_date')])[4:6])
sell_da = int(str(folio.loc[(i, 'sell_date')])[6:8])
if ((buy_yr > aend_yr) or ((buy_yr == aend_yr) and (buy_mo > aend_mo)) or ((buy_yr == aend_yr) and (buy_mo == aend_mo) and (buy_da > aend_da))):
iflag.append(i)
elif ((sell_yr < astart_yr) or ((sell_yr == astart_yr) and (sell_mo < astart_mo)) or ((sell_yr == astart_yr) and (sell_mo == astart_mo) and (buy_da < astart_da))):
iflag.append(i)
elif ((sell_yr > aend_yr) or ((sell_yr == aend_yr) and (sell_mo > aend_yr)) or ((sell_yr == aend_yr) and (sell_mo == aend_mo) and (sell_yr > aend_yr))):
folio.loc[(i, 'sell_date')] = ((str(aend_yr) + str(aend_mo)) + str(aend_da))
folio.loc[(i, 'sell_date')] = int(folio.loc[(i, 'sell_date')])
for i in iflag:
folio.drop(i, axis='index', inplace=True)
if (len(folio) < 1):
raise ValueError('CSV file has no valid lines')
folio.insert(len(folio.columns), '+-%', 'NA')
folio.insert(len(folio.columns), '+-GBP', 'NA')
i = (- 1)
for row in folio.itertuples():
i = (i + 1)
sell_yr = str(folio.loc[(i, 'sell_date')])[:4]
sell_mo = str(folio.loc[(i, 'sell_date')])[4:6]
sell_da = str(folio.loc[(i, 'sell_date')])[6:8]
sell_str = ((((sell_yr + '-') + sell_mo) + '-') + sell_da)
if (int(sell_da) >= 3):
start_da = (int(sell_da) - 3)
start_mo = int(sell_mo)
start_yr = int(sell_yr)
elif (int(sell_mo) > 1):
start_da = 25
start_mo = (int(sell_mo) - 1)
start_yr = int(sell_yr)
else:
start_da = 25
start_mo = 12
start_yr = (int(sell_yr) - 1)
start_str = ((((str(start_yr) + '-') + str(start_mo)) + '-') + str(start_da))
dat = yf.Ticker(row[1])
hist = dat.history(start=start_str, end=sell_str, interval='1d', actions='false')
if (folio.loc[(i, 'purchase_price_GBP')] < hist.iloc[(0, 3)]):
folio.loc[(i, '+-GBP')] = (hist.iloc[(0, 3)] - folio.loc[(i, 'purchase_price_GBP')])
else:
folio.loc[(i, '+-GBP')] = ((folio.loc[(i, 'purchase_price_GBP')] - hist.iloc[(0, 3)]) * (- 1))
folio.loc[(i, '+-%')] = (hist.iloc[(0, 3)] / folio.loc[(i, 'purchase_price_GBP')])
sumGBP = 0
sumPER = 0
for i in range(len(folio)):
sumGBP += folio.loc[(i, '+-GBP')]
sumPER += folio.loc[(i, '+-%')]
folio = folio.append({'ticker': 'TOTAL', '+-%': sumPER, '+-GBP': sumGBP}, ignore_index=True)
astart_str = ((((str(astart_yr) + '-') + str(astart_mo)) + '-') + str(astart_da))
aend_str = ((((str(aend_yr) + '-') + str(aend_mo)) + '-') + str(aend_da))
dat = yf.Ticker(index)
hist = dat.history(start=astart_str, end=aend_str, interval='1d', actions='false')
if (hist.iloc[(0, 3)] < hist.iloc[((len(hist) - 1), 3)]):
indexGBP = (hist.iloc[((len(hist) - 1), 3)] - hist.iloc[(0, 3)])
else:
indexGBP = (hist.iloc[(0, 3)] - hist.iloc[((len(hist) - 1), 3)])
indexPER = (hist.iloc[((len(hist) - 1), 3)] / hist.iloc[(0, 3)])
print('\n********************************************\n')
if (sumGBP > indexGBP):
print('Portfolio beat the market by £{:.0f} GBP, making a total of £{:.0f} GBP over the analysis periord'.format((sumGBP - indexGBP), indexGBP))
print('Percentage growth was {:.0f}% verses {:.0f}% for the index over the same periord'.format(sumPER, indexPER))
else:
print('Portfolio did not beat the market, making a total of £{:.0f} GBP over the analysis periord, £{:.0f} GBP less than the market'.format(sumGBP, (indexGBP - sumGBP)))
print('In percentage terms the portoflio changed by {:.0f}% verses {:.0f}% for the index over the same periord'.format(sumPER, indexPER))
except ValueError as err:
print(('Something went wrong: %s' % err), file=sys.stderr)
sys.exit(1)
return | def main():
'\n FUNCTION DESCRIPTION\n OTHER COMMENTS\n INPUTS\n OUTPUTS\n EXAMPLES\n >>> main();\n hello world\n '
if (len(sys.argv) != 2):
raise ValueError('Expected one file as comandline argument')
try:
astart = str(input('enter analysis start date YYYYMMDD: '))
if (len(astart) != 8):
raise ValueError('Date format expected is YYYYMMDD')
astart_yr = int(astart[:4])
astart_mo = int(astart[4:6])
astart_da = int(astart[6:8])
aend = str(input('enter analysis end date YYYYMMDD: '))
if (len(aend) != 8):
raise ValueError('Date format expected is YYYYMMDD')
aend_yr = int(aend[:4])
aend_mo = int(aend[4:6])
aend_da = int(aend[6:8])
earliest_yr = 1910
cur_yr = datetime.date.today().year
if ((astart_yr < earliest_yr) or (astart_yr > cur_yr) or (aend_yr < earliest_yr) or (aend_yr > cur_yr)):
raise ValueError(('Date expected year YYYY between 1940 and %d' % yr))
elif ((astart_mo < 1) or (astart_mo > 12) or (aend_mo < 1) or (aend_mo > 12)):
raise ValueError('Date expected month MM between 1 and 12')
if ((astart_mo == 9) or (astart_mo == 4) or (astart_mo == 6) or (astart_mo == 11) or (aend_mo == 9) or (aend_mo == 4) or (aend_mo == 6) or (aend_mo == 11)):
if ((astart_da < 1) or (astart_da > 30) or (aend_da < 1) or (aend_da > 30)):
raise ValueError('Invalid day of month entered')
elif ((astart_da < 1) or (astart_da > 31) or (aend_da < 1) or (aend_da > 31)):
raise ValueError('Invalid day of month entered')
folio = pd.read_csv(sys.argv[1])
print('\n{0} tickers loaded from {1}\n'.format(len(folio['ticker']), sys.argv[1]))
for bd in folio['buy_date']:
buy_mo = int(str(bd)[4:6])
buy_da = int(str(bd)[6:8])
if ((buy_mo > 12) or (buy_mo < 1)):
raise ValueError('Invalid month in CSV')
if ((buy_mo == 9) or (buy_mo == 4) or (buy_mo == 6) or (buy_mo == 11)):
if ((buy_da < 1) or (buy_da > 30)):
raise ValueError('Invalid day of month in CSV')
elif ((buy_mo < 1) or (buy_da > 31)):
raise ValueError('Invalid day of month in CSV')
for (i, sd) in enumerate(folio['sell_date']):
if pd.isnull(sd):
folio.loc[(i, 'sell_date')] = aend
else:
sell_mo = int(str(sd)[4:6])
sell_da = int(str(sd)[6:8])
if ((sell_mo > 12) or (sell_mo < 1)):
raise ValueError('Invalid month in CSV')
if ((sell_mo == 9) or (sell_mo == 4) or (sell_mo == 6) or (sell_mo == 11)):
if ((sell_da < 1) or (sell_da > 30)):
raise ValueError('Invalid day of month in CSV')
elif ((sell_da < 1) or (sell_da > 31)):
raise ValueError('Invalid day of month in CSV')
index = input('1) FTSE 100; 2) S&P 500; 3) NASDAQ Composit\nselect a comparison index: ')
if (index == '1'):
index = '^FTSE'
elif (index == '2'):
index = '^GSPC'
elif (index == '3'):
index = '^IXIC'
else:
raise ValueError('Comparison index must be a number 1 - 3')
i = (- 1)
iflag = []
for row in folio.itertuples():
i = (i + 1)
buy_yr = int(str(folio.loc[(i, 'buy_date')])[:4])
buy_mo = int(str(folio.loc[(i, 'buy_date')])[4:6])
buy_da = int(str(folio.loc[(i, 'buy_date')])[6:8])
sell_yr = int(str(folio.loc[(i, 'sell_date')])[:4])
sell_mo = int(str(folio.loc[(i, 'sell_date')])[4:6])
sell_da = int(str(folio.loc[(i, 'sell_date')])[6:8])
if ((buy_yr > aend_yr) or ((buy_yr == aend_yr) and (buy_mo > aend_mo)) or ((buy_yr == aend_yr) and (buy_mo == aend_mo) and (buy_da > aend_da))):
iflag.append(i)
elif ((sell_yr < astart_yr) or ((sell_yr == astart_yr) and (sell_mo < astart_mo)) or ((sell_yr == astart_yr) and (sell_mo == astart_mo) and (buy_da < astart_da))):
iflag.append(i)
elif ((sell_yr > aend_yr) or ((sell_yr == aend_yr) and (sell_mo > aend_yr)) or ((sell_yr == aend_yr) and (sell_mo == aend_mo) and (sell_yr > aend_yr))):
folio.loc[(i, 'sell_date')] = ((str(aend_yr) + str(aend_mo)) + str(aend_da))
folio.loc[(i, 'sell_date')] = int(folio.loc[(i, 'sell_date')])
for i in iflag:
folio.drop(i, axis='index', inplace=True)
if (len(folio) < 1):
raise ValueError('CSV file has no valid lines')
folio.insert(len(folio.columns), '+-%', 'NA')
folio.insert(len(folio.columns), '+-GBP', 'NA')
i = (- 1)
for row in folio.itertuples():
i = (i + 1)
sell_yr = str(folio.loc[(i, 'sell_date')])[:4]
sell_mo = str(folio.loc[(i, 'sell_date')])[4:6]
sell_da = str(folio.loc[(i, 'sell_date')])[6:8]
sell_str = ((((sell_yr + '-') + sell_mo) + '-') + sell_da)
if (int(sell_da) >= 3):
start_da = (int(sell_da) - 3)
start_mo = int(sell_mo)
start_yr = int(sell_yr)
elif (int(sell_mo) > 1):
start_da = 25
start_mo = (int(sell_mo) - 1)
start_yr = int(sell_yr)
else:
start_da = 25
start_mo = 12
start_yr = (int(sell_yr) - 1)
start_str = ((((str(start_yr) + '-') + str(start_mo)) + '-') + str(start_da))
dat = yf.Ticker(row[1])
hist = dat.history(start=start_str, end=sell_str, interval='1d', actions='false')
if (folio.loc[(i, 'purchase_price_GBP')] < hist.iloc[(0, 3)]):
folio.loc[(i, '+-GBP')] = (hist.iloc[(0, 3)] - folio.loc[(i, 'purchase_price_GBP')])
else:
folio.loc[(i, '+-GBP')] = ((folio.loc[(i, 'purchase_price_GBP')] - hist.iloc[(0, 3)]) * (- 1))
folio.loc[(i, '+-%')] = (hist.iloc[(0, 3)] / folio.loc[(i, 'purchase_price_GBP')])
sumGBP = 0
sumPER = 0
for i in range(len(folio)):
sumGBP += folio.loc[(i, '+-GBP')]
sumPER += folio.loc[(i, '+-%')]
folio = folio.append({'ticker': 'TOTAL', '+-%': sumPER, '+-GBP': sumGBP}, ignore_index=True)
astart_str = ((((str(astart_yr) + '-') + str(astart_mo)) + '-') + str(astart_da))
aend_str = ((((str(aend_yr) + '-') + str(aend_mo)) + '-') + str(aend_da))
dat = yf.Ticker(index)
hist = dat.history(start=astart_str, end=aend_str, interval='1d', actions='false')
if (hist.iloc[(0, 3)] < hist.iloc[((len(hist) - 1), 3)]):
indexGBP = (hist.iloc[((len(hist) - 1), 3)] - hist.iloc[(0, 3)])
else:
indexGBP = (hist.iloc[(0, 3)] - hist.iloc[((len(hist) - 1), 3)])
indexPER = (hist.iloc[((len(hist) - 1), 3)] / hist.iloc[(0, 3)])
print('\n********************************************\n')
if (sumGBP > indexGBP):
print('Portfolio beat the market by £{:.0f} GBP, making a total of £{:.0f} GBP over the analysis periord'.format((sumGBP - indexGBP), indexGBP))
print('Percentage growth was {:.0f}% verses {:.0f}% for the index over the same periord'.format(sumPER, indexPER))
else:
print('Portfolio did not beat the market, making a total of £{:.0f} GBP over the analysis periord, £{:.0f} GBP less than the market'.format(sumGBP, (indexGBP - sumGBP)))
print('In percentage terms the portoflio changed by {:.0f}% verses {:.0f}% for the index over the same periord'.format(sumPER, indexPER))
except ValueError as err:
print(('Something went wrong: %s' % err), file=sys.stderr)
sys.exit(1)
return<|docstring|>FUNCTION DESCRIPTION
OTHER COMMENTS
INPUTS
OUTPUTS
EXAMPLES
>>> main();
hello world<|endoftext|> |
52fcdcf50447b8485d99f35e94055bb3faa7396c95c491daa60f28cce3a3ab04 | def get_top_k(self, x, ratio):
'it will sample the top 1-ratio of the samples.'
x_data = x.view((- 1))
x_len = x_data.nelement()
top_k = max(1, int((x_len * (1 - ratio))))
if (top_k == 1):
(_, selected_indices) = torch.max(x_data.abs(), dim=0, keepdim=True)
else:
(_, selected_indices) = torch.topk(x_data.abs(), top_k, largest=True, sorted=False)
return (x_data[selected_indices], selected_indices) | it will sample the top 1-ratio of the samples. | gossip_ds/compressor.py | get_top_k | aparna-aketi/Low_Precision_DL | 0 | python | def get_top_k(self, x, ratio):
x_data = x.view((- 1))
x_len = x_data.nelement()
top_k = max(1, int((x_len * (1 - ratio))))
if (top_k == 1):
(_, selected_indices) = torch.max(x_data.abs(), dim=0, keepdim=True)
else:
(_, selected_indices) = torch.topk(x_data.abs(), top_k, largest=True, sorted=False)
return (x_data[selected_indices], selected_indices) | def get_top_k(self, x, ratio):
x_data = x.view((- 1))
x_len = x_data.nelement()
top_k = max(1, int((x_len * (1 - ratio))))
if (top_k == 1):
(_, selected_indices) = torch.max(x_data.abs(), dim=0, keepdim=True)
else:
(_, selected_indices) = torch.topk(x_data.abs(), top_k, largest=True, sorted=False)
return (x_data[selected_indices], selected_indices)<|docstring|>it will sample the top 1-ratio of the samples.<|endoftext|> |
2e0cdb5ec3fd974a1a2bf78fd0d2e3a596e6c02c50f1ae74b374b0cf96ad1a4e | def get_random_k(self, x, ratio, is_biased=True):
'it will randomly sample the 1-ratio of the samples.'
x_data = x.view((- 1))
x_len = x_data.nelement()
top_k = max(1, int((x_len * (1 - ratio))))
selected_indices = np.random.choice(x_len, top_k, replace=False)
selected_indices = torch.LongTensor(selected_indices).to(x.device)
if is_biased:
return (x_data[selected_indices], selected_indices)
else:
return (((x_len / top_k) * x_data[selected_indices]), selected_indices) | it will randomly sample the 1-ratio of the samples. | gossip_ds/compressor.py | get_random_k | aparna-aketi/Low_Precision_DL | 0 | python | def get_random_k(self, x, ratio, is_biased=True):
x_data = x.view((- 1))
x_len = x_data.nelement()
top_k = max(1, int((x_len * (1 - ratio))))
selected_indices = np.random.choice(x_len, top_k, replace=False)
selected_indices = torch.LongTensor(selected_indices).to(x.device)
if is_biased:
return (x_data[selected_indices], selected_indices)
else:
return (((x_len / top_k) * x_data[selected_indices]), selected_indices) | def get_random_k(self, x, ratio, is_biased=True):
x_data = x.view((- 1))
x_len = x_data.nelement()
top_k = max(1, int((x_len * (1 - ratio))))
selected_indices = np.random.choice(x_len, top_k, replace=False)
selected_indices = torch.LongTensor(selected_indices).to(x.device)
if is_biased:
return (x_data[selected_indices], selected_indices)
else:
return (((x_len / top_k) * x_data[selected_indices]), selected_indices)<|docstring|>it will randomly sample the 1-ratio of the samples.<|endoftext|> |
063286be31b79e07728ed5bfb2e105fd8fc0a04d55274f6a303460fbb2e9dc61 | def version(arguments):
"\n Main dispatcher for diags commands. Calls the corresponding helper function.\n\n :param arguments: A dictionary of arguments already processed through\n this file's docstring with docopt\n :return: None\n "
print(__version__)
sys.exit(0) | Main dispatcher for diags commands. Calls the corresponding helper function.
:param arguments: A dictionary of arguments already processed through
this file's docstring with docopt
:return: None | calicoctl/calico_ctl/version.py | version | EdSchouten/calico-containers | 0 | python | def version(arguments):
"\n Main dispatcher for diags commands. Calls the corresponding helper function.\n\n :param arguments: A dictionary of arguments already processed through\n this file's docstring with docopt\n :return: None\n "
print(__version__)
sys.exit(0) | def version(arguments):
"\n Main dispatcher for diags commands. Calls the corresponding helper function.\n\n :param arguments: A dictionary of arguments already processed through\n this file's docstring with docopt\n :return: None\n "
print(__version__)
sys.exit(0)<|docstring|>Main dispatcher for diags commands. Calls the corresponding helper function.
:param arguments: A dictionary of arguments already processed through
this file's docstring with docopt
:return: None<|endoftext|> |
0f182e87410e547cfae06d4987647064c328d8c4de97ff64d1e5332ecd59a751 | def ceaser(msg, shift, action):
' Turn a msg into a cipher text'
end_msg = ''
if (action == 'decode'):
shift *= (- 1)
for letter in msg:
if (letter in alphabet):
i = alphabet.index(letter)
new_i = (i + shift)
end_msg += alphabet[new_i]
else:
end_msg += letter
print(f'The {action}d message is: {end_msg}') | Turn a msg into a cipher text | Cipher/encoder.py | ceaser | Rekid46/Python-Games | 1 | python | def ceaser(msg, shift, action):
' '
end_msg =
if (action == 'decode'):
shift *= (- 1)
for letter in msg:
if (letter in alphabet):
i = alphabet.index(letter)
new_i = (i + shift)
end_msg += alphabet[new_i]
else:
end_msg += letter
print(f'The {action}d message is: {end_msg}') | def ceaser(msg, shift, action):
' '
end_msg =
if (action == 'decode'):
shift *= (- 1)
for letter in msg:
if (letter in alphabet):
i = alphabet.index(letter)
new_i = (i + shift)
end_msg += alphabet[new_i]
else:
end_msg += letter
print(f'The {action}d message is: {end_msg}')<|docstring|>Turn a msg into a cipher text<|endoftext|> |
58de41bd909387267510a0d555019b71fa5edc4ba7cff6a03ab1139437355851 | def getNSView(self):
'\n Return the *NSView* that this object wraps.\n '
return self._nsObject | Return the *NSView* that this object wraps. | Lib/vanilla/vanillaGroup.py | getNSView | miguelsousa/vanilla | 21 | python | def getNSView(self):
'\n \n '
return self._nsObject | def getNSView(self):
'\n \n '
return self._nsObject<|docstring|>Return the *NSView* that this object wraps.<|endoftext|> |
ca92fae19904e66436563d0c57b3f25a7fdca99cadb496a267ff85f855b665fb | def get(isdsAppliance, check_mode=False, force=False):
'\n Get Event Log\n '
return isdsAppliance.invoke_get('Retrieving Authentication Token', '/authenticate') | Get Event Log | ibmsecurity/isds/token.py | get | Franclaf7/ibmsecurity | 46 | python | def get(isdsAppliance, check_mode=False, force=False):
'\n \n '
return isdsAppliance.invoke_get('Retrieving Authentication Token', '/authenticate') | def get(isdsAppliance, check_mode=False, force=False):
'\n \n '
return isdsAppliance.invoke_get('Retrieving Authentication Token', '/authenticate')<|docstring|>Get Event Log<|endoftext|> |
72d72b30056dab5cc6196c12dd73ba98081fcd36eda46005a1ce3328f2a7a32c | def test_init(self):
"\n Use the v1 configuration to initialize the working\n directory and install the required provider plugins,\n but don't apply the configuration yet.\n\n "
self.tf.init('v1') | Use the v1 configuration to initialize the working
directory and install the required provider plugins,
but don't apply the configuration yet. | examples/simple-test/test_simple_test.py | test_init | mdawar/pretf | 85 | python | def test_init(self):
"\n Use the v1 configuration to initialize the working\n directory and install the required provider plugins,\n but don't apply the configuration yet.\n\n "
self.tf.init('v1') | def test_init(self):
"\n Use the v1 configuration to initialize the working\n directory and install the required provider plugins,\n but don't apply the configuration yet.\n\n "
self.tf.init('v1')<|docstring|>Use the v1 configuration to initialize the working
directory and install the required provider plugins,
but don't apply the configuration yet.<|endoftext|> |
19211f1cf95c9549da9d21b1bbdb66061aa624be9ff2d2ce814e526e95a41867 | def test_v1(self):
'\n Apply the v1 configuration and check its outputs.\n\n '
outputs = self.tf.apply('v1')
assert ('original' in outputs)
assert outputs['original'].startswith('original-')
self.state['original'] = outputs['original']
assert ('additional' not in outputs) | Apply the v1 configuration and check its outputs. | examples/simple-test/test_simple_test.py | test_v1 | mdawar/pretf | 85 | python | def test_v1(self):
'\n \n\n '
outputs = self.tf.apply('v1')
assert ('original' in outputs)
assert outputs['original'].startswith('original-')
self.state['original'] = outputs['original']
assert ('additional' not in outputs) | def test_v1(self):
'\n \n\n '
outputs = self.tf.apply('v1')
assert ('original' in outputs)
assert outputs['original'].startswith('original-')
self.state['original'] = outputs['original']
assert ('additional' not in outputs)<|docstring|>Apply the v1 configuration and check its outputs.<|endoftext|> |
8fc150a0d58b0ffaa4c5bfea669acdede0d4340a76878fd622c39c5233b54ac0 | def test_v2(self):
'\n Apply the v2 configuration and check that the original\n resource from v1 is still there, and that an additional\n resource was created.\n\n '
outputs = self.pretf.apply('v2')
assert ('original' in outputs)
assert (outputs['original'] == self.state['original'])
assert ('additional' in outputs)
assert outputs['additional'].startswith('additional-') | Apply the v2 configuration and check that the original
resource from v1 is still there, and that an additional
resource was created. | examples/simple-test/test_simple_test.py | test_v2 | mdawar/pretf | 85 | python | def test_v2(self):
'\n Apply the v2 configuration and check that the original\n resource from v1 is still there, and that an additional\n resource was created.\n\n '
outputs = self.pretf.apply('v2')
assert ('original' in outputs)
assert (outputs['original'] == self.state['original'])
assert ('additional' in outputs)
assert outputs['additional'].startswith('additional-') | def test_v2(self):
'\n Apply the v2 configuration and check that the original\n resource from v1 is still there, and that an additional\n resource was created.\n\n '
outputs = self.pretf.apply('v2')
assert ('original' in outputs)
assert (outputs['original'] == self.state['original'])
assert ('additional' in outputs)
assert outputs['additional'].startswith('additional-')<|docstring|>Apply the v2 configuration and check that the original
resource from v1 is still there, and that an additional
resource was created.<|endoftext|> |
db3f197a5031d72296fbfbf4033559f224048810d121ebb5d46422867eb2d5fb | def test_v1_again(self):
'\n Apply the v1 configuration again and check that the original\n resource is still there, and that the additional resource\n from v2 was deleted.\n\n '
outputs = self.tf.apply('v1')
assert ('original' in outputs)
assert (outputs['original'] == self.state['original'])
assert ('additional' not in outputs) | Apply the v1 configuration again and check that the original
resource is still there, and that the additional resource
from v2 was deleted. | examples/simple-test/test_simple_test.py | test_v1_again | mdawar/pretf | 85 | python | def test_v1_again(self):
'\n Apply the v1 configuration again and check that the original\n resource is still there, and that the additional resource\n from v2 was deleted.\n\n '
outputs = self.tf.apply('v1')
assert ('original' in outputs)
assert (outputs['original'] == self.state['original'])
assert ('additional' not in outputs) | def test_v1_again(self):
'\n Apply the v1 configuration again and check that the original\n resource is still there, and that the additional resource\n from v2 was deleted.\n\n '
outputs = self.tf.apply('v1')
assert ('original' in outputs)
assert (outputs['original'] == self.state['original'])
assert ('additional' not in outputs)<|docstring|>Apply the v1 configuration again and check that the original
resource is still there, and that the additional resource
from v2 was deleted.<|endoftext|> |
5dcb7219417ff2f8847a98be1f6738a14d5e888b99ff2d36dcb2dac8eba6f84a | @test.always
def test_destroy(self):
'\n Clean up the resources.\n\n '
self.tf.destroy() | Clean up the resources. | examples/simple-test/test_simple_test.py | test_destroy | mdawar/pretf | 85 | python | @test.always
def test_destroy(self):
'\n \n\n '
self.tf.destroy() | @test.always
def test_destroy(self):
'\n \n\n '
self.tf.destroy()<|docstring|>Clean up the resources.<|endoftext|> |
7e0ff7415cc21f269e908128a9c02013f39d1dd0bb89a5dfcb73a68036570273 | def find_connector(device_spec: DeviceSpec, connection_method: ConnectionMethod) -> Callable[([DeviceSpec, Dict], Connector)]:
'Find the first matching connector for the given device and\n connection method.\n\n Parameters\n ----------\n device_spec - details about the hardware device\n connection_method - method used to connect to the device\n Returns\n -------\n Connector constructor\n '
connector = next((conn for conn in Connector.subclasses if conn.supports(device_spec, connection_method)))
if (not connector):
raise ValueError(f'{connection_method} client for device {device_spec.name} is not supported')
return connector | Find the first matching connector for the given device and
connection method.
Parameters
----------
device_spec - details about the hardware device
connection_method - method used to connect to the device
Returns
-------
Connector constructor | bcipy/acquisition/protocols/registry.py | find_connector | mberkanbicer/BciPy | 32 | python | def find_connector(device_spec: DeviceSpec, connection_method: ConnectionMethod) -> Callable[([DeviceSpec, Dict], Connector)]:
'Find the first matching connector for the given device and\n connection method.\n\n Parameters\n ----------\n device_spec - details about the hardware device\n connection_method - method used to connect to the device\n Returns\n -------\n Connector constructor\n '
connector = next((conn for conn in Connector.subclasses if conn.supports(device_spec, connection_method)))
if (not connector):
raise ValueError(f'{connection_method} client for device {device_spec.name} is not supported')
return connector | def find_connector(device_spec: DeviceSpec, connection_method: ConnectionMethod) -> Callable[([DeviceSpec, Dict], Connector)]:
'Find the first matching connector for the given device and\n connection method.\n\n Parameters\n ----------\n device_spec - details about the hardware device\n connection_method - method used to connect to the device\n Returns\n -------\n Connector constructor\n '
connector = next((conn for conn in Connector.subclasses if conn.supports(device_spec, connection_method)))
if (not connector):
raise ValueError(f'{connection_method} client for device {device_spec.name} is not supported')
return connector<|docstring|>Find the first matching connector for the given device and
connection method.
Parameters
----------
device_spec - details about the hardware device
connection_method - method used to connect to the device
Returns
-------
Connector constructor<|endoftext|> |
91f0aab349bf4ac872f105c6282667478eebd72f9a2cef86f94e7dadfbad838d | def make_connector(device_spec: DeviceSpec, connection_method: ConnectionMethod, connection_params: dict) -> Connector:
'Find and construct a Connector for the given device and connection method.\n\n Parameters\n ----------\n device_spec - details about the hardware device.\n connection_method - method used to connect to the device.\n connection_params - parameters specific to the relevant Connector, such\n as host and port information (for a TCP connector).\n Returns\n -------\n Connector instanct\n '
connector = find_connector(device_spec, connection_method)
return connector(connection_params=connection_params, device_spec=device_spec) | Find and construct a Connector for the given device and connection method.
Parameters
----------
device_spec - details about the hardware device.
connection_method - method used to connect to the device.
connection_params - parameters specific to the relevant Connector, such
as host and port information (for a TCP connector).
Returns
-------
Connector instanct | bcipy/acquisition/protocols/registry.py | make_connector | mberkanbicer/BciPy | 32 | python | def make_connector(device_spec: DeviceSpec, connection_method: ConnectionMethod, connection_params: dict) -> Connector:
'Find and construct a Connector for the given device and connection method.\n\n Parameters\n ----------\n device_spec - details about the hardware device.\n connection_method - method used to connect to the device.\n connection_params - parameters specific to the relevant Connector, such\n as host and port information (for a TCP connector).\n Returns\n -------\n Connector instanct\n '
connector = find_connector(device_spec, connection_method)
return connector(connection_params=connection_params, device_spec=device_spec) | def make_connector(device_spec: DeviceSpec, connection_method: ConnectionMethod, connection_params: dict) -> Connector:
'Find and construct a Connector for the given device and connection method.\n\n Parameters\n ----------\n device_spec - details about the hardware device.\n connection_method - method used to connect to the device.\n connection_params - parameters specific to the relevant Connector, such\n as host and port information (for a TCP connector).\n Returns\n -------\n Connector instanct\n '
connector = find_connector(device_spec, connection_method)
return connector(connection_params=connection_params, device_spec=device_spec)<|docstring|>Find and construct a Connector for the given device and connection method.
Parameters
----------
device_spec - details about the hardware device.
connection_method - method used to connect to the device.
connection_params - parameters specific to the relevant Connector, such
as host and port information (for a TCP connector).
Returns
-------
Connector instanct<|endoftext|> |
ed8126b2cb9b9e3943c2afd9a429c6e591bc8b1a9d559858d430bd8569e72477 | def find_protocol(device_spec: DeviceSpec, connection_method: ConnectionMethod=ConnectionMethod.TCP) -> DeviceProtocol:
'Find the DeviceProtocol instance for the given DeviceSpec.'
device_protocol = next((protocol for protocol in DeviceProtocol.subclasses if protocol.supports(device_spec, connection_method)))
if (not device_protocol):
raise ValueError(f'{device_spec.name} over {connection_method.name} is not supported.')
return device_protocol(device_spec) | Find the DeviceProtocol instance for the given DeviceSpec. | bcipy/acquisition/protocols/registry.py | find_protocol | mberkanbicer/BciPy | 32 | python | def find_protocol(device_spec: DeviceSpec, connection_method: ConnectionMethod=ConnectionMethod.TCP) -> DeviceProtocol:
device_protocol = next((protocol for protocol in DeviceProtocol.subclasses if protocol.supports(device_spec, connection_method)))
if (not device_protocol):
raise ValueError(f'{device_spec.name} over {connection_method.name} is not supported.')
return device_protocol(device_spec) | def find_protocol(device_spec: DeviceSpec, connection_method: ConnectionMethod=ConnectionMethod.TCP) -> DeviceProtocol:
device_protocol = next((protocol for protocol in DeviceProtocol.subclasses if protocol.supports(device_spec, connection_method)))
if (not device_protocol):
raise ValueError(f'{device_spec.name} over {connection_method.name} is not supported.')
return device_protocol(device_spec)<|docstring|>Find the DeviceProtocol instance for the given DeviceSpec.<|endoftext|> |
cc96ca209c68cd3169c3a6cdcf5ac82ca2e21c94da70e2add11ef8fde974b33c | def __call__(self, *dp):
'\n Call the predictor on some inputs.\n\n Example:\n When you have a predictor defined with two inputs, call it with:\n\n .. code-block:: python\n\n predictor(e1, e2)\n '
output = self._do_call(dp)
if self.return_input:
return (dp, output)
else:
return output | Call the predictor on some inputs.
Example:
When you have a predictor defined with two inputs, call it with:
.. code-block:: python
predictor(e1, e2) | tensorpack/predict/base.py | __call__ | wilsonjvp/mask-rcnn-tensorflow | 32 | python | def __call__(self, *dp):
'\n Call the predictor on some inputs.\n\n Example:\n When you have a predictor defined with two inputs, call it with:\n\n .. code-block:: python\n\n predictor(e1, e2)\n '
output = self._do_call(dp)
if self.return_input:
return (dp, output)
else:
return output | def __call__(self, *dp):
'\n Call the predictor on some inputs.\n\n Example:\n When you have a predictor defined with two inputs, call it with:\n\n .. code-block:: python\n\n predictor(e1, e2)\n '
output = self._do_call(dp)
if self.return_input:
return (dp, output)
else:
return output<|docstring|>Call the predictor on some inputs.
Example:
When you have a predictor defined with two inputs, call it with:
.. code-block:: python
predictor(e1, e2)<|endoftext|> |
3f54a29f8308711092683412485b9dc714bb6747d5514b6fd592efa18621ed80 | @abstractmethod
def _do_call(self, dp):
'\n Args:\n dp: input datapoint. must have the same length as input_names\n Returns:\n output as defined by the config\n ' | Args:
dp: input datapoint. must have the same length as input_names
Returns:
output as defined by the config | tensorpack/predict/base.py | _do_call | wilsonjvp/mask-rcnn-tensorflow | 32 | python | @abstractmethod
def _do_call(self, dp):
'\n Args:\n dp: input datapoint. must have the same length as input_names\n Returns:\n output as defined by the config\n ' | @abstractmethod
def _do_call(self, dp):
'\n Args:\n dp: input datapoint. must have the same length as input_names\n Returns:\n output as defined by the config\n '<|docstring|>Args:
dp: input datapoint. must have the same length as input_names
Returns:
output as defined by the config<|endoftext|> |
88e9efb53346074a50ecf3755a21d228f2ec278721e8ce627586218b264efa33 | @abstractmethod
def put_task(self, dp, callback=None):
'\n Args:\n dp (list): A datapoint as inputs. It could be either batched or not\n batched depending on the predictor implementation).\n callback: a thread-safe callback to get called with\n either outputs or (inputs, outputs).\n Returns:\n concurrent.futures.Future: a Future of results\n ' | Args:
dp (list): A datapoint as inputs. It could be either batched or not
batched depending on the predictor implementation).
callback: a thread-safe callback to get called with
either outputs or (inputs, outputs).
Returns:
concurrent.futures.Future: a Future of results | tensorpack/predict/base.py | put_task | wilsonjvp/mask-rcnn-tensorflow | 32 | python | @abstractmethod
def put_task(self, dp, callback=None):
'\n Args:\n dp (list): A datapoint as inputs. It could be either batched or not\n batched depending on the predictor implementation).\n callback: a thread-safe callback to get called with\n either outputs or (inputs, outputs).\n Returns:\n concurrent.futures.Future: a Future of results\n ' | @abstractmethod
def put_task(self, dp, callback=None):
'\n Args:\n dp (list): A datapoint as inputs. It could be either batched or not\n batched depending on the predictor implementation).\n callback: a thread-safe callback to get called with\n either outputs or (inputs, outputs).\n Returns:\n concurrent.futures.Future: a Future of results\n '<|docstring|>Args:
dp (list): A datapoint as inputs. It could be either batched or not
batched depending on the predictor implementation).
callback: a thread-safe callback to get called with
either outputs or (inputs, outputs).
Returns:
concurrent.futures.Future: a Future of results<|endoftext|> |
28c06f830924a0d3da4df5d8147002074a58f272afbfefab75ee32caa1e9366d | @abstractmethod
def start(self):
' Start workers ' | Start workers | tensorpack/predict/base.py | start | wilsonjvp/mask-rcnn-tensorflow | 32 | python | @abstractmethod
def start(self):
' ' | @abstractmethod
def start(self):
' '<|docstring|>Start workers<|endoftext|> |
54c270a9eee63471a42d41538224530d4bf9a7723fd7f294edab6d6eece3bc5d | def __init__(self, input_tensors, output_tensors, return_input=False, sess=None):
'\n Args:\n input_tensors (list): list of names.\n output_tensors (list): list of names.\n return_input (bool): same as :attr:`PredictorBase.return_input`.\n sess (tf.Session): the session this predictor runs in. If None,\n will use the default session at the first call.\n Note that in TensorFlow, default session is thread-local.\n '
self.return_input = return_input
self.input_tensors = input_tensors
self.output_tensors = output_tensors
self.sess = sess
if (sess is not None):
self._callable = sess.make_callable(fetches=output_tensors, feed_list=input_tensors, accept_options=self.ACCEPT_OPTIONS)
else:
self._callable = None | Args:
input_tensors (list): list of names.
output_tensors (list): list of names.
return_input (bool): same as :attr:`PredictorBase.return_input`.
sess (tf.Session): the session this predictor runs in. If None,
will use the default session at the first call.
Note that in TensorFlow, default session is thread-local. | tensorpack/predict/base.py | __init__ | wilsonjvp/mask-rcnn-tensorflow | 32 | python | def __init__(self, input_tensors, output_tensors, return_input=False, sess=None):
'\n Args:\n input_tensors (list): list of names.\n output_tensors (list): list of names.\n return_input (bool): same as :attr:`PredictorBase.return_input`.\n sess (tf.Session): the session this predictor runs in. If None,\n will use the default session at the first call.\n Note that in TensorFlow, default session is thread-local.\n '
self.return_input = return_input
self.input_tensors = input_tensors
self.output_tensors = output_tensors
self.sess = sess
if (sess is not None):
self._callable = sess.make_callable(fetches=output_tensors, feed_list=input_tensors, accept_options=self.ACCEPT_OPTIONS)
else:
self._callable = None | def __init__(self, input_tensors, output_tensors, return_input=False, sess=None):
'\n Args:\n input_tensors (list): list of names.\n output_tensors (list): list of names.\n return_input (bool): same as :attr:`PredictorBase.return_input`.\n sess (tf.Session): the session this predictor runs in. If None,\n will use the default session at the first call.\n Note that in TensorFlow, default session is thread-local.\n '
self.return_input = return_input
self.input_tensors = input_tensors
self.output_tensors = output_tensors
self.sess = sess
if (sess is not None):
self._callable = sess.make_callable(fetches=output_tensors, feed_list=input_tensors, accept_options=self.ACCEPT_OPTIONS)
else:
self._callable = None<|docstring|>Args:
input_tensors (list): list of names.
output_tensors (list): list of names.
return_input (bool): same as :attr:`PredictorBase.return_input`.
sess (tf.Session): the session this predictor runs in. If None,
will use the default session at the first call.
Note that in TensorFlow, default session is thread-local.<|endoftext|> |
abdd52b525d38162c2eb5ac87d38f9c2eb46cacf9448b395837bb7d24ce5a58b | def __init__(self, config):
'\n Args:\n config (PredictConfig): the config to use.\n '
self.graph = config._maybe_create_graph()
with self.graph.as_default():
input = PlaceholderInput()
input.setup(config.inputs_desc)
with PredictTowerContext(''):
config.tower_func(*input.get_input_tensors())
input_tensors = get_tensors_by_names(config.input_names)
output_tensors = get_tensors_by_names(config.output_names)
config.session_init._setup_graph()
sess = config.session_creator.create_session()
config.session_init._run_init(sess)
super(OfflinePredictor, self).__init__(input_tensors, output_tensors, config.return_input, sess) | Args:
config (PredictConfig): the config to use. | tensorpack/predict/base.py | __init__ | wilsonjvp/mask-rcnn-tensorflow | 32 | python | def __init__(self, config):
'\n Args:\n config (PredictConfig): the config to use.\n '
self.graph = config._maybe_create_graph()
with self.graph.as_default():
input = PlaceholderInput()
input.setup(config.inputs_desc)
with PredictTowerContext():
config.tower_func(*input.get_input_tensors())
input_tensors = get_tensors_by_names(config.input_names)
output_tensors = get_tensors_by_names(config.output_names)
config.session_init._setup_graph()
sess = config.session_creator.create_session()
config.session_init._run_init(sess)
super(OfflinePredictor, self).__init__(input_tensors, output_tensors, config.return_input, sess) | def __init__(self, config):
'\n Args:\n config (PredictConfig): the config to use.\n '
self.graph = config._maybe_create_graph()
with self.graph.as_default():
input = PlaceholderInput()
input.setup(config.inputs_desc)
with PredictTowerContext():
config.tower_func(*input.get_input_tensors())
input_tensors = get_tensors_by_names(config.input_names)
output_tensors = get_tensors_by_names(config.output_names)
config.session_init._setup_graph()
sess = config.session_creator.create_session()
config.session_init._run_init(sess)
super(OfflinePredictor, self).__init__(input_tensors, output_tensors, config.return_input, sess)<|docstring|>Args:
config (PredictConfig): the config to use.<|endoftext|> |
9cdfea54fce9d4fc5517b9df2c7df5118be07496d33cd874de6ea304704313bc | def convert_examples_to_features(examples, label2id, max_seq_length, tokenizer, special_tokens, unused_tokens=True):
'\n Loads a data file into a list of `InputBatch`s.\n unused_tokens: whether use [unused1] [unused2] as special tokens\n '
def get_special_token(w):
if (w not in special_tokens):
if unused_tokens:
special_tokens[w] = ('[unused%d]' % (len(special_tokens) + 1))
else:
special_tokens[w] = (('<' + w) + '>').lower()
return special_tokens[w]
num_tokens = 0
max_tokens = 0
num_fit_examples = 0
num_shown_examples = 0
features = []
for (ex_index, example) in enumerate(examples):
if ((ex_index % 10000) == 0):
logger.info(('Writing example %d of %d' % (ex_index, len(examples))))
tokens = [CLS]
SUBJECT_START = get_special_token('SUBJ_START')
SUBJECT_END = get_special_token('SUBJ_END')
OBJECT_START = get_special_token('OBJ_START')
OBJECT_END = get_special_token('OBJ_END')
SUBJECT_NER = get_special_token(('SUBJ=%s' % example['subj_type']))
OBJECT_NER = get_special_token(('OBJ=%s' % example['obj_type']))
SUBJECT_START_NER = get_special_token(('SUBJ_START=%s' % example['subj_type']))
SUBJECT_END_NER = get_special_token(('SUBJ_END=%s' % example['subj_type']))
OBJECT_START_NER = get_special_token(('OBJ_START=%s' % example['obj_type']))
OBJECT_END_NER = get_special_token(('OBJ_END=%s' % example['obj_type']))
for (i, token) in enumerate(example['token']):
if (i == example['subj_start']):
sub_idx = len(tokens)
tokens.append(SUBJECT_START_NER)
if (i == example['obj_start']):
obj_idx = len(tokens)
tokens.append(OBJECT_START_NER)
for sub_token in tokenizer.tokenize(token):
tokens.append(sub_token)
if (i == example['subj_end']):
tokens.append(SUBJECT_END_NER)
if (i == example['obj_end']):
tokens.append(OBJECT_END_NER)
tokens.append(SEP)
num_tokens += len(tokens)
max_tokens = max(max_tokens, len(tokens))
if (len(tokens) > max_seq_length):
tokens = tokens[:max_seq_length]
if (sub_idx >= max_seq_length):
sub_idx = 0
if (obj_idx >= max_seq_length):
obj_idx = 0
else:
num_fit_examples += 1
segment_ids = ([0] * len(tokens))
input_ids = tokenizer.convert_tokens_to_ids(tokens)
input_mask = ([1] * len(input_ids))
padding = ([0] * (max_seq_length - len(input_ids)))
input_ids += padding
input_mask += padding
segment_ids += padding
label_id = label2id[example['relation']]
assert (len(input_ids) == max_seq_length)
assert (len(input_mask) == max_seq_length)
assert (len(segment_ids) == max_seq_length)
if (num_shown_examples < 20):
if ((ex_index < 5) or (label_id > 0)):
num_shown_examples += 1
logger.info('*** Example ***')
logger.info(('guid: %s' % example['id']))
logger.info(('tokens: %s' % ' '.join([str(x) for x in tokens])))
logger.info(('input_ids: %s' % ' '.join([str(x) for x in input_ids])))
logger.info(('input_mask: %s' % ' '.join([str(x) for x in input_mask])))
logger.info(('segment_ids: %s' % ' '.join([str(x) for x in segment_ids])))
logger.info(('label: %s (id = %d)' % (example['relation'], label_id)))
logger.info(('sub_idx, obj_idx: %d, %d' % (sub_idx, obj_idx)))
features.append(InputFeatures(input_ids=input_ids, input_mask=input_mask, segment_ids=segment_ids, label_id=label_id, sub_idx=sub_idx, obj_idx=obj_idx))
logger.info(('Average #tokens: %.2f' % ((num_tokens * 1.0) / len(examples))))
logger.info(('Max #tokens: %d' % max_tokens))
logger.info(('%d (%.2f %%) examples can fit max_seq_length = %d' % (num_fit_examples, ((num_fit_examples * 100.0) / len(examples)), max_seq_length)))
return features | Loads a data file into a list of `InputBatch`s.
unused_tokens: whether use [unused1] [unused2] as special tokens | run_relation.py | convert_examples_to_features | johnson7788/PURE | 476 | python | def convert_examples_to_features(examples, label2id, max_seq_length, tokenizer, special_tokens, unused_tokens=True):
'\n Loads a data file into a list of `InputBatch`s.\n unused_tokens: whether use [unused1] [unused2] as special tokens\n '
def get_special_token(w):
if (w not in special_tokens):
if unused_tokens:
special_tokens[w] = ('[unused%d]' % (len(special_tokens) + 1))
else:
special_tokens[w] = (('<' + w) + '>').lower()
return special_tokens[w]
num_tokens = 0
max_tokens = 0
num_fit_examples = 0
num_shown_examples = 0
features = []
for (ex_index, example) in enumerate(examples):
if ((ex_index % 10000) == 0):
logger.info(('Writing example %d of %d' % (ex_index, len(examples))))
tokens = [CLS]
SUBJECT_START = get_special_token('SUBJ_START')
SUBJECT_END = get_special_token('SUBJ_END')
OBJECT_START = get_special_token('OBJ_START')
OBJECT_END = get_special_token('OBJ_END')
SUBJECT_NER = get_special_token(('SUBJ=%s' % example['subj_type']))
OBJECT_NER = get_special_token(('OBJ=%s' % example['obj_type']))
SUBJECT_START_NER = get_special_token(('SUBJ_START=%s' % example['subj_type']))
SUBJECT_END_NER = get_special_token(('SUBJ_END=%s' % example['subj_type']))
OBJECT_START_NER = get_special_token(('OBJ_START=%s' % example['obj_type']))
OBJECT_END_NER = get_special_token(('OBJ_END=%s' % example['obj_type']))
for (i, token) in enumerate(example['token']):
if (i == example['subj_start']):
sub_idx = len(tokens)
tokens.append(SUBJECT_START_NER)
if (i == example['obj_start']):
obj_idx = len(tokens)
tokens.append(OBJECT_START_NER)
for sub_token in tokenizer.tokenize(token):
tokens.append(sub_token)
if (i == example['subj_end']):
tokens.append(SUBJECT_END_NER)
if (i == example['obj_end']):
tokens.append(OBJECT_END_NER)
tokens.append(SEP)
num_tokens += len(tokens)
max_tokens = max(max_tokens, len(tokens))
if (len(tokens) > max_seq_length):
tokens = tokens[:max_seq_length]
if (sub_idx >= max_seq_length):
sub_idx = 0
if (obj_idx >= max_seq_length):
obj_idx = 0
else:
num_fit_examples += 1
segment_ids = ([0] * len(tokens))
input_ids = tokenizer.convert_tokens_to_ids(tokens)
input_mask = ([1] * len(input_ids))
padding = ([0] * (max_seq_length - len(input_ids)))
input_ids += padding
input_mask += padding
segment_ids += padding
label_id = label2id[example['relation']]
assert (len(input_ids) == max_seq_length)
assert (len(input_mask) == max_seq_length)
assert (len(segment_ids) == max_seq_length)
if (num_shown_examples < 20):
if ((ex_index < 5) or (label_id > 0)):
num_shown_examples += 1
logger.info('*** Example ***')
logger.info(('guid: %s' % example['id']))
logger.info(('tokens: %s' % ' '.join([str(x) for x in tokens])))
logger.info(('input_ids: %s' % ' '.join([str(x) for x in input_ids])))
logger.info(('input_mask: %s' % ' '.join([str(x) for x in input_mask])))
logger.info(('segment_ids: %s' % ' '.join([str(x) for x in segment_ids])))
logger.info(('label: %s (id = %d)' % (example['relation'], label_id)))
logger.info(('sub_idx, obj_idx: %d, %d' % (sub_idx, obj_idx)))
features.append(InputFeatures(input_ids=input_ids, input_mask=input_mask, segment_ids=segment_ids, label_id=label_id, sub_idx=sub_idx, obj_idx=obj_idx))
logger.info(('Average #tokens: %.2f' % ((num_tokens * 1.0) / len(examples))))
logger.info(('Max #tokens: %d' % max_tokens))
logger.info(('%d (%.2f %%) examples can fit max_seq_length = %d' % (num_fit_examples, ((num_fit_examples * 100.0) / len(examples)), max_seq_length)))
return features | def convert_examples_to_features(examples, label2id, max_seq_length, tokenizer, special_tokens, unused_tokens=True):
'\n Loads a data file into a list of `InputBatch`s.\n unused_tokens: whether use [unused1] [unused2] as special tokens\n '
def get_special_token(w):
if (w not in special_tokens):
if unused_tokens:
special_tokens[w] = ('[unused%d]' % (len(special_tokens) + 1))
else:
special_tokens[w] = (('<' + w) + '>').lower()
return special_tokens[w]
num_tokens = 0
max_tokens = 0
num_fit_examples = 0
num_shown_examples = 0
features = []
for (ex_index, example) in enumerate(examples):
if ((ex_index % 10000) == 0):
logger.info(('Writing example %d of %d' % (ex_index, len(examples))))
tokens = [CLS]
SUBJECT_START = get_special_token('SUBJ_START')
SUBJECT_END = get_special_token('SUBJ_END')
OBJECT_START = get_special_token('OBJ_START')
OBJECT_END = get_special_token('OBJ_END')
SUBJECT_NER = get_special_token(('SUBJ=%s' % example['subj_type']))
OBJECT_NER = get_special_token(('OBJ=%s' % example['obj_type']))
SUBJECT_START_NER = get_special_token(('SUBJ_START=%s' % example['subj_type']))
SUBJECT_END_NER = get_special_token(('SUBJ_END=%s' % example['subj_type']))
OBJECT_START_NER = get_special_token(('OBJ_START=%s' % example['obj_type']))
OBJECT_END_NER = get_special_token(('OBJ_END=%s' % example['obj_type']))
for (i, token) in enumerate(example['token']):
if (i == example['subj_start']):
sub_idx = len(tokens)
tokens.append(SUBJECT_START_NER)
if (i == example['obj_start']):
obj_idx = len(tokens)
tokens.append(OBJECT_START_NER)
for sub_token in tokenizer.tokenize(token):
tokens.append(sub_token)
if (i == example['subj_end']):
tokens.append(SUBJECT_END_NER)
if (i == example['obj_end']):
tokens.append(OBJECT_END_NER)
tokens.append(SEP)
num_tokens += len(tokens)
max_tokens = max(max_tokens, len(tokens))
if (len(tokens) > max_seq_length):
tokens = tokens[:max_seq_length]
if (sub_idx >= max_seq_length):
sub_idx = 0
if (obj_idx >= max_seq_length):
obj_idx = 0
else:
num_fit_examples += 1
segment_ids = ([0] * len(tokens))
input_ids = tokenizer.convert_tokens_to_ids(tokens)
input_mask = ([1] * len(input_ids))
padding = ([0] * (max_seq_length - len(input_ids)))
input_ids += padding
input_mask += padding
segment_ids += padding
label_id = label2id[example['relation']]
assert (len(input_ids) == max_seq_length)
assert (len(input_mask) == max_seq_length)
assert (len(segment_ids) == max_seq_length)
if (num_shown_examples < 20):
if ((ex_index < 5) or (label_id > 0)):
num_shown_examples += 1
logger.info('*** Example ***')
logger.info(('guid: %s' % example['id']))
logger.info(('tokens: %s' % ' '.join([str(x) for x in tokens])))
logger.info(('input_ids: %s' % ' '.join([str(x) for x in input_ids])))
logger.info(('input_mask: %s' % ' '.join([str(x) for x in input_mask])))
logger.info(('segment_ids: %s' % ' '.join([str(x) for x in segment_ids])))
logger.info(('label: %s (id = %d)' % (example['relation'], label_id)))
logger.info(('sub_idx, obj_idx: %d, %d' % (sub_idx, obj_idx)))
features.append(InputFeatures(input_ids=input_ids, input_mask=input_mask, segment_ids=segment_ids, label_id=label_id, sub_idx=sub_idx, obj_idx=obj_idx))
logger.info(('Average #tokens: %.2f' % ((num_tokens * 1.0) / len(examples))))
logger.info(('Max #tokens: %d' % max_tokens))
logger.info(('%d (%.2f %%) examples can fit max_seq_length = %d' % (num_fit_examples, ((num_fit_examples * 100.0) / len(examples)), max_seq_length)))
return features<|docstring|>Loads a data file into a list of `InputBatch`s.
unused_tokens: whether use [unused1] [unused2] as special tokens<|endoftext|> |
1189b72261a7b59eeaab7af36a1d6e5c8ac76671e24c08e7acd7b736659c9e80 | def __init__(self, data):
'Note how the data argument is handled differently for DataComposite\n objects and DataNode objects. The data passed to a composite object is\n set as meta data about the composite set. The user need not know this\n while passing the data.'
self._meta_data = data
self.sub_objects = [] | Note how the data argument is handled differently for DataComposite
objects and DataNode objects. The data passed to a composite object is
set as meta data about the composite set. The user need not know this
while passing the data. | structural/composite.py | __init__ | prateeksan/python-design-patterns | 61 | python | def __init__(self, data):
'Note how the data argument is handled differently for DataComposite\n objects and DataNode objects. The data passed to a composite object is\n set as meta data about the composite set. The user need not know this\n while passing the data.'
self._meta_data = data
self.sub_objects = [] | def __init__(self, data):
'Note how the data argument is handled differently for DataComposite\n objects and DataNode objects. The data passed to a composite object is\n set as meta data about the composite set. The user need not know this\n while passing the data.'
self._meta_data = data
self.sub_objects = []<|docstring|>Note how the data argument is handled differently for DataComposite
objects and DataNode objects. The data passed to a composite object is
set as meta data about the composite set. The user need not know this
while passing the data.<|endoftext|> |
53607ea2523c23aca408941650a1ca8465257118af3b95433c2bc7580657d204 | def read(self):
"Note how the user can call the read method on all children of\n DataObject and get a desired response even though the method's behaviour \n differs in the child classes."
print('Data Composite For: {}'.format(self._meta_data))
for data_object in self.sub_objects:
data_object.read() | Note how the user can call the read method on all children of
DataObject and get a desired response even though the method's behaviour
differs in the child classes. | structural/composite.py | read | prateeksan/python-design-patterns | 61 | python | def read(self):
"Note how the user can call the read method on all children of\n DataObject and get a desired response even though the method's behaviour \n differs in the child classes."
print('Data Composite For: {}'.format(self._meta_data))
for data_object in self.sub_objects:
data_object.read() | def read(self):
"Note how the user can call the read method on all children of\n DataObject and get a desired response even though the method's behaviour \n differs in the child classes."
print('Data Composite For: {}'.format(self._meta_data))
for data_object in self.sub_objects:
data_object.read()<|docstring|>Note how the user can call the read method on all children of
DataObject and get a desired response even though the method's behaviour
differs in the child classes.<|endoftext|> |
ec6318ccbcebd7aa53005be9487b17344e7e44edc0d1ea4efcb2894cc75e21c5 | def mark_point(im, x, y):
'\n Mark position to show which point clicked\n\n Args:\n im: pillow.Image\n '
draw = ImageDraw.Draw(im)
(w, h) = im.size
draw.line((x, 0, x, h), fill='red', width=5)
draw.line((0, y, w, y), fill='red', width=5)
r = (min(im.size) // 40)
draw.ellipse(((x - r), (y - r), (x + r), (y + r)), fill='red')
r = (min(im.size) // 50)
draw.ellipse(((x - r), (y - r), (x + r), (y + r)), fill='white')
del draw
return im | Mark position to show which point clicked
Args:
im: pillow.Image | uiautomator2/ext/htmlreport/__init__.py | mark_point | hiyongz/uiautomator2 | 4,493 | python | def mark_point(im, x, y):
'\n Mark position to show which point clicked\n\n Args:\n im: pillow.Image\n '
draw = ImageDraw.Draw(im)
(w, h) = im.size
draw.line((x, 0, x, h), fill='red', width=5)
draw.line((0, y, w, y), fill='red', width=5)
r = (min(im.size) // 40)
draw.ellipse(((x - r), (y - r), (x + r), (y + r)), fill='red')
r = (min(im.size) // 50)
draw.ellipse(((x - r), (y - r), (x + r), (y + r)), fill='white')
del draw
return im | def mark_point(im, x, y):
'\n Mark position to show which point clicked\n\n Args:\n im: pillow.Image\n '
draw = ImageDraw.Draw(im)
(w, h) = im.size
draw.line((x, 0, x, h), fill='red', width=5)
draw.line((0, y, w, y), fill='red', width=5)
r = (min(im.size) // 40)
draw.ellipse(((x - r), (y - r), (x + r), (y + r)), fill='red')
r = (min(im.size) // 50)
draw.ellipse(((x - r), (y - r), (x + r), (y + r)), fill='white')
del draw
return im<|docstring|>Mark position to show which point clicked
Args:
im: pillow.Image<|endoftext|> |
ca4ac7e71ad94de1076d9d5fa41a6191428dd9c81d5b688da83dc92184fa2c68 | def _record_screenshot(self, pos=None):
'\n Save screenshot and add record into record.json\n \n Example record data:\n {\n "time": "2017/1/2 10:20:30",\n "code": "d.click(100, 800)",\n "screenshot": "imgs/demo.jpg"\n }\n '
im = self._driver.screenshot()
if pos:
(x, y) = pos
im = mark_point(im, x, y)
im.thumbnail((800, 800))
relpath = os.path.join('imgs', ('img-%d.jpg' % (time.time() * 1000)))
abspath = os.path.join(self._target_dir, relpath)
dstdir = os.path.dirname(abspath)
if (not os.path.exists(dstdir)):
os.makedirs(dstdir)
im.save(abspath)
self._addtosteps(dict(screenshot=relpath)) | Save screenshot and add record into record.json
Example record data:
{
"time": "2017/1/2 10:20:30",
"code": "d.click(100, 800)",
"screenshot": "imgs/demo.jpg"
} | uiautomator2/ext/htmlreport/__init__.py | _record_screenshot | hiyongz/uiautomator2 | 4,493 | python | def _record_screenshot(self, pos=None):
'\n Save screenshot and add record into record.json\n \n Example record data:\n {\n "time": "2017/1/2 10:20:30",\n "code": "d.click(100, 800)",\n "screenshot": "imgs/demo.jpg"\n }\n '
im = self._driver.screenshot()
if pos:
(x, y) = pos
im = mark_point(im, x, y)
im.thumbnail((800, 800))
relpath = os.path.join('imgs', ('img-%d.jpg' % (time.time() * 1000)))
abspath = os.path.join(self._target_dir, relpath)
dstdir = os.path.dirname(abspath)
if (not os.path.exists(dstdir)):
os.makedirs(dstdir)
im.save(abspath)
self._addtosteps(dict(screenshot=relpath)) | def _record_screenshot(self, pos=None):
'\n Save screenshot and add record into record.json\n \n Example record data:\n {\n "time": "2017/1/2 10:20:30",\n "code": "d.click(100, 800)",\n "screenshot": "imgs/demo.jpg"\n }\n '
im = self._driver.screenshot()
if pos:
(x, y) = pos
im = mark_point(im, x, y)
im.thumbnail((800, 800))
relpath = os.path.join('imgs', ('img-%d.jpg' % (time.time() * 1000)))
abspath = os.path.join(self._target_dir, relpath)
dstdir = os.path.dirname(abspath)
if (not os.path.exists(dstdir)):
os.makedirs(dstdir)
im.save(abspath)
self._addtosteps(dict(screenshot=relpath))<|docstring|>Save screenshot and add record into record.json
Example record data:
{
"time": "2017/1/2 10:20:30",
"code": "d.click(100, 800)",
"screenshot": "imgs/demo.jpg"
}<|endoftext|> |
f17f0f9efe2c5fdcde68cbd93db6717a5660558d0fcfb070df5c70d3f5315003 | def _addtosteps(self, data):
'\n Args:\n data: dict used to save into record.json\n '
codelines = []
for stk in inspect.stack()[1:]:
filename = stk[1]
try:
filename = os.path.relpath(filename)
except ValueError:
continue
if (filename.find('/site-packages/') != (- 1)):
continue
if filename.startswith('..'):
continue
codeline = ('%s:%d\n %s' % (filename, stk[2], ''.join((stk[4] or [])).strip()))
codelines.append(codeline)
code = '\n'.join(codelines)
steps = self._steps
base_data = {'time': time.strftime('%H:%M:%S'), 'code': code}
base_data.update(data)
steps.append(base_data)
self._flush() | Args:
data: dict used to save into record.json | uiautomator2/ext/htmlreport/__init__.py | _addtosteps | hiyongz/uiautomator2 | 4,493 | python | def _addtosteps(self, data):
'\n Args:\n data: dict used to save into record.json\n '
codelines = []
for stk in inspect.stack()[1:]:
filename = stk[1]
try:
filename = os.path.relpath(filename)
except ValueError:
continue
if (filename.find('/site-packages/') != (- 1)):
continue
if filename.startswith('..'):
continue
codeline = ('%s:%d\n %s' % (filename, stk[2], .join((stk[4] or [])).strip()))
codelines.append(codeline)
code = '\n'.join(codelines)
steps = self._steps
base_data = {'time': time.strftime('%H:%M:%S'), 'code': code}
base_data.update(data)
steps.append(base_data)
self._flush() | def _addtosteps(self, data):
'\n Args:\n data: dict used to save into record.json\n '
codelines = []
for stk in inspect.stack()[1:]:
filename = stk[1]
try:
filename = os.path.relpath(filename)
except ValueError:
continue
if (filename.find('/site-packages/') != (- 1)):
continue
if filename.startswith('..'):
continue
codeline = ('%s:%d\n %s' % (filename, stk[2], .join((stk[4] or [])).strip()))
codelines.append(codeline)
code = '\n'.join(codelines)
steps = self._steps
base_data = {'time': time.strftime('%H:%M:%S'), 'code': code}
base_data.update(data)
steps.append(base_data)
self._flush()<|docstring|>Args:
data: dict used to save into record.json<|endoftext|> |
b2368c5b67a0188b73ec06473d6de4495e413fa639a440bb3d0aa002b5dd81d9 | def _patch_instance_func(self, obj, name, newfunc):
' patch a.funcname to new func '
oldfunc = getattr(obj, name)
print('mock', oldfunc)
newfunc = functools.wraps(oldfunc)(newfunc)
newfunc.oldfunc = oldfunc
setattr(obj, name, types.MethodType(newfunc, obj)) | patch a.funcname to new func | uiautomator2/ext/htmlreport/__init__.py | _patch_instance_func | hiyongz/uiautomator2 | 4,493 | python | def _patch_instance_func(self, obj, name, newfunc):
' '
oldfunc = getattr(obj, name)
print('mock', oldfunc)
newfunc = functools.wraps(oldfunc)(newfunc)
newfunc.oldfunc = oldfunc
setattr(obj, name, types.MethodType(newfunc, obj)) | def _patch_instance_func(self, obj, name, newfunc):
' '
oldfunc = getattr(obj, name)
print('mock', oldfunc)
newfunc = functools.wraps(oldfunc)(newfunc)
newfunc.oldfunc = oldfunc
setattr(obj, name, types.MethodType(newfunc, obj))<|docstring|>patch a.funcname to new func<|endoftext|> |
d7169423e555581ff87870d7821435d748430c698bcf12e1a5dedeff3b755082 | def _patch_class_func(self, obj, funcname, newfunc):
' patch A.funcname to new func '
oldfunc = getattr(obj, funcname)
if hasattr(oldfunc, 'oldfunc'):
raise RuntimeError(('function: %s.%s already patched before' % (obj, funcname)))
newfunc = functools.wraps(oldfunc)(newfunc)
newfunc.oldfunc = oldfunc
setattr(obj, funcname, newfunc) | patch A.funcname to new func | uiautomator2/ext/htmlreport/__init__.py | _patch_class_func | hiyongz/uiautomator2 | 4,493 | python | def _patch_class_func(self, obj, funcname, newfunc):
' '
oldfunc = getattr(obj, funcname)
if hasattr(oldfunc, 'oldfunc'):
raise RuntimeError(('function: %s.%s already patched before' % (obj, funcname)))
newfunc = functools.wraps(oldfunc)(newfunc)
newfunc.oldfunc = oldfunc
setattr(obj, funcname, newfunc) | def _patch_class_func(self, obj, funcname, newfunc):
' '
oldfunc = getattr(obj, funcname)
if hasattr(oldfunc, 'oldfunc'):
raise RuntimeError(('function: %s.%s already patched before' % (obj, funcname)))
newfunc = functools.wraps(oldfunc)(newfunc)
newfunc.oldfunc = oldfunc
setattr(obj, funcname, newfunc)<|docstring|>patch A.funcname to new func<|endoftext|> |
db21c703262fedab3f1003cfc57c4cd07f08c268cfc1967e8b43a227842d440b | def patch_click(self):
'\n Record every click operation into report.\n '
def _mock_click(obj, x, y):
(x, y) = obj.pos_rel2abs(x, y)
self._record_screenshot((x, y))
return obj.click.oldfunc(obj, x, y)
def _mock_long_click(obj, x, y, duration=None):
(x, y) = obj.pos_rel2abs(x, y)
self._record_screenshot((x, y))
return obj.long_click.oldfunc(obj, x, y, duration)
self._patch_class_func(uiautomator2.Session, 'click', _mock_click)
self._patch_class_func(uiautomator2.Session, 'long_click', _mock_long_click) | Record every click operation into report. | uiautomator2/ext/htmlreport/__init__.py | patch_click | hiyongz/uiautomator2 | 4,493 | python | def patch_click(self):
'\n \n '
def _mock_click(obj, x, y):
(x, y) = obj.pos_rel2abs(x, y)
self._record_screenshot((x, y))
return obj.click.oldfunc(obj, x, y)
def _mock_long_click(obj, x, y, duration=None):
(x, y) = obj.pos_rel2abs(x, y)
self._record_screenshot((x, y))
return obj.long_click.oldfunc(obj, x, y, duration)
self._patch_class_func(uiautomator2.Session, 'click', _mock_click)
self._patch_class_func(uiautomator2.Session, 'long_click', _mock_long_click) | def patch_click(self):
'\n \n '
def _mock_click(obj, x, y):
(x, y) = obj.pos_rel2abs(x, y)
self._record_screenshot((x, y))
return obj.click.oldfunc(obj, x, y)
def _mock_long_click(obj, x, y, duration=None):
(x, y) = obj.pos_rel2abs(x, y)
self._record_screenshot((x, y))
return obj.long_click.oldfunc(obj, x, y, duration)
self._patch_class_func(uiautomator2.Session, 'click', _mock_click)
self._patch_class_func(uiautomator2.Session, 'long_click', _mock_long_click)<|docstring|>Record every click operation into report.<|endoftext|> |
5738fd3d1a42b1da4d122bbe391454ef09400d9477a234bf375418b9d31ead70 | def unpatch_click(self):
'\n Remove record for click operation\n '
self._unpatch_func(uiautomator2.Session, 'click')
self._unpatch_func(uiautomator2.Session, 'long_click') | Remove record for click operation | uiautomator2/ext/htmlreport/__init__.py | unpatch_click | hiyongz/uiautomator2 | 4,493 | python | def unpatch_click(self):
'\n \n '
self._unpatch_func(uiautomator2.Session, 'click')
self._unpatch_func(uiautomator2.Session, 'long_click') | def unpatch_click(self):
'\n \n '
self._unpatch_func(uiautomator2.Session, 'click')
self._unpatch_func(uiautomator2.Session, 'long_click')<|docstring|>Remove record for click operation<|endoftext|> |
925b0bf034b712740ec3d1aa60ff170167ad912c46d6155b615aaaa8366951c6 | def __init__(self, session):
'\n\n :param session: a db session\n '
self.session = session | :param session: a db session | kubb_match/data/data_managers.py | __init__ | BartSaelen/kubb_match | 2 | python | def __init__(self, session):
'\n\n \n '
self.session = session | def __init__(self, session):
'\n\n \n '
self.session = session<|docstring|>:param session: a db session<|endoftext|> |
3d58d1fba42d2655723a05e50f063799ee44a909e2389fc4e8a229079c208368 | def save(self, object):
'\n bewaar een bepaald advies\n\n :param advies: het te bewaren advies\n :return: het bewaarde advies\n '
self.session.add(object)
self.session.flush()
return object | bewaar een bepaald advies
:param advies: het te bewaren advies
:return: het bewaarde advies | kubb_match/data/data_managers.py | save | BartSaelen/kubb_match | 2 | python | def save(self, object):
'\n bewaar een bepaald advies\n\n :param advies: het te bewaren advies\n :return: het bewaarde advies\n '
self.session.add(object)
self.session.flush()
return object | def save(self, object):
'\n bewaar een bepaald advies\n\n :param advies: het te bewaren advies\n :return: het bewaarde advies\n '
self.session.add(object)
self.session.flush()
return object<|docstring|>bewaar een bepaald advies
:param advies: het te bewaren advies
:return: het bewaarde advies<|endoftext|> |
c9f6f69bb8209a7afd395ab7c1500d6723189aa30a84b695a1145b38b695788b | def test_backend(self):
'\n Test to see if tests are running without any X11 or any other display\n variable set. Therefore, the AGG backend is chosen in\n obspy.imaging.tests.__init__, and nothing must be imported before,\n e.g. by obspy.imaging.__init__. The AGG backend does not require and\n display setting. It is therefore the optimal for programs on servers\n etc.\n '
self.assertEqual('AGG', matplotlib.get_backend().upper()) | Test to see if tests are running without any X11 or any other display
variable set. Therefore, the AGG backend is chosen in
obspy.imaging.tests.__init__, and nothing must be imported before,
e.g. by obspy.imaging.__init__. The AGG backend does not require and
display setting. It is therefore the optimal for programs on servers
etc. | IRIS_data_download/IRIS_download_support/obspy/imaging/tests/test_backend.py | test_backend | earthinversion/Fnet_IRIS_data_automated_download | 2 | python | def test_backend(self):
'\n Test to see if tests are running without any X11 or any other display\n variable set. Therefore, the AGG backend is chosen in\n obspy.imaging.tests.__init__, and nothing must be imported before,\n e.g. by obspy.imaging.__init__. The AGG backend does not require and\n display setting. It is therefore the optimal for programs on servers\n etc.\n '
self.assertEqual('AGG', matplotlib.get_backend().upper()) | def test_backend(self):
'\n Test to see if tests are running without any X11 or any other display\n variable set. Therefore, the AGG backend is chosen in\n obspy.imaging.tests.__init__, and nothing must be imported before,\n e.g. by obspy.imaging.__init__. The AGG backend does not require and\n display setting. It is therefore the optimal for programs on servers\n etc.\n '
self.assertEqual('AGG', matplotlib.get_backend().upper())<|docstring|>Test to see if tests are running without any X11 or any other display
variable set. Therefore, the AGG backend is chosen in
obspy.imaging.tests.__init__, and nothing must be imported before,
e.g. by obspy.imaging.__init__. The AGG backend does not require and
display setting. It is therefore the optimal for programs on servers
etc.<|endoftext|> |
d683e21e47cb6bec8b007759e44fc926e0ae7014c490f0b3863bcbfb803097bd | def create_user(self, email, password, **extra_fields):
'\n Creates and saves a User with the given email and password.\n '
if (not email):
raise ValueError('The Email must be set')
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save()
return user | Creates and saves a User with the given email and password. | users/models.py | create_user | adamgogogo/glitchtip-backend | 0 | python | def create_user(self, email, password, **extra_fields):
'\n \n '
if (not email):
raise ValueError('The Email must be set')
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save()
return user | def create_user(self, email, password, **extra_fields):
'\n \n '
if (not email):
raise ValueError('The Email must be set')
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save()
return user<|docstring|>Creates and saves a User with the given email and password.<|endoftext|> |
1e5945b5e4e8f33e8bf42643f0288f5f3dc7a2a3853c5286aa0fae85627e7622 | def auto_name(ext: str) -> str:
"Generates a string name using the local date/time and given ext.\n\n Return format is 'Y-m-d_H:M:S.ext'\n "
time_str = strftime('%Y-%m-%d_%H:%M:%S', localtime())
return f'{time_str}.{ext}' | Generates a string name using the local date/time and given ext.
Return format is 'Y-m-d_H:M:S.ext' | collatzpy/plot/helpers/auto_name.py | auto_name | stkterry/collatzpy | 0 | python | def auto_name(ext: str) -> str:
"Generates a string name using the local date/time and given ext.\n\n Return format is 'Y-m-d_H:M:S.ext'\n "
time_str = strftime('%Y-%m-%d_%H:%M:%S', localtime())
return f'{time_str}.{ext}' | def auto_name(ext: str) -> str:
"Generates a string name using the local date/time and given ext.\n\n Return format is 'Y-m-d_H:M:S.ext'\n "
time_str = strftime('%Y-%m-%d_%H:%M:%S', localtime())
return f'{time_str}.{ext}'<|docstring|>Generates a string name using the local date/time and given ext.
Return format is 'Y-m-d_H:M:S.ext'<|endoftext|> |
790b9785ffff9d89a3618680737397f41ffcbc64f77ed6b24a2d6c27da167454 | def auto_name_with_dir(directory, ext):
"Generates a string name using the local date/time and given dir/ext.\n\n Return format is 'directory/Y-m-d_H:M:S.ext'\n "
time_str = strftime('%Y-%m-%d_%H:%M:%S%', localtime())
return f'{directory}/{time_str}.{ext}' | Generates a string name using the local date/time and given dir/ext.
Return format is 'directory/Y-m-d_H:M:S.ext' | collatzpy/plot/helpers/auto_name.py | auto_name_with_dir | stkterry/collatzpy | 0 | python | def auto_name_with_dir(directory, ext):
"Generates a string name using the local date/time and given dir/ext.\n\n Return format is 'directory/Y-m-d_H:M:S.ext'\n "
time_str = strftime('%Y-%m-%d_%H:%M:%S%', localtime())
return f'{directory}/{time_str}.{ext}' | def auto_name_with_dir(directory, ext):
"Generates a string name using the local date/time and given dir/ext.\n\n Return format is 'directory/Y-m-d_H:M:S.ext'\n "
time_str = strftime('%Y-%m-%d_%H:%M:%S%', localtime())
return f'{directory}/{time_str}.{ext}'<|docstring|>Generates a string name using the local date/time and given dir/ext.
Return format is 'directory/Y-m-d_H:M:S.ext'<|endoftext|> |
952828c555de8328fd77d19a61f9c7d7e311ca2f58f5fe65940a72dc9629fa5e | def problem345():
'\n\n\n We define the Matrix Sum of a matrix as the maximum sum of matrix elements\n with each element being the only one in his row and column. For example,\n the Matrix Sum of the matrix below equals 3315 ( = 863 + 383 + 343 + 959 +\n 767):\n\n 7 53 183 439 863\n 497 383 563 79 973\n 287 63 343 169 583\n 627 343 773 959 943\n 767 473 103 699 303\n\n Find the Matrix Sum of:\n\n 7 53 183 439 863 497 383 563 79 973 287 63 343 169 583\n 627 343 773 959 943 767 473 103 699 303 957 703 583 639 913\n 447 283 463 29 23 487 463 993 119 883 327 493 423 159 743\n 217 623 3 399 853 407 103 983 89 463 290 516 212 462 350\n 960 376 682 962 300 780 486 502 912 800 250 346 172 812 350\n 870 456 192 162 593 473 915 45 989 873 823 965 425 329 803\n 973 965 905 919 133 673 665 235 509 613 673 815 165 992 326\n 322 148 972 962 286 255 941 541 265 323 925 281 601 95 973\n 445 721 11 525 473 65 511 164 138 672 18 428 154 448 848\n 414 456 310 312 798 104 566 520 302 248 694 976 430 392 198\n 184 829 373 181 631 101 969 613 840 740 778 458 284 760 390\n 821 461 843 513 17 901 711 993 293 157 274 94 192 156 574\n 34 124 4 878 450 476 712 914 838 669 875 299 823 329 699\n 815 559 813 459 522 788 168 586 966 232 308 833 251 631 107\n 813 883 451 509 615 77 281 613 459 205 380 274 302 35 805\n '
maxsum = [([None] * (2 ** COLUMNS)) for _ in range(ROWS)]
def find_maximum_sum(startrow, setofcols):
if (startrow == ROWS):
assert (eulerlib.popcount(setofcols) == (COLUMNS - ROWS))
return 0
if (maxsum[startrow][setofcols] is None):
result = 0
col = 0
bit = 1
while True:
if (bit > setofcols):
break
if ((setofcols & bit) != 0):
result = max((MATRIX[startrow][col] + find_maximum_sum((startrow + 1), (setofcols ^ bit))), result)
col += 1
bit <<= 1
maxsum[startrow][setofcols] = result
return maxsum[startrow][setofcols]
ans = find_maximum_sum(0, ((2 ** COLUMNS) - 1))
return ans | We define the Matrix Sum of a matrix as the maximum sum of matrix elements
with each element being the only one in his row and column. For example,
the Matrix Sum of the matrix below equals 3315 ( = 863 + 383 + 343 + 959 +
767):
7 53 183 439 863
497 383 563 79 973
287 63 343 169 583
627 343 773 959 943
767 473 103 699 303
Find the Matrix Sum of:
7 53 183 439 863 497 383 563 79 973 287 63 343 169 583
627 343 773 959 943 767 473 103 699 303 957 703 583 639 913
447 283 463 29 23 487 463 993 119 883 327 493 423 159 743
217 623 3 399 853 407 103 983 89 463 290 516 212 462 350
960 376 682 962 300 780 486 502 912 800 250 346 172 812 350
870 456 192 162 593 473 915 45 989 873 823 965 425 329 803
973 965 905 919 133 673 665 235 509 613 673 815 165 992 326
322 148 972 962 286 255 941 541 265 323 925 281 601 95 973
445 721 11 525 473 65 511 164 138 672 18 428 154 448 848
414 456 310 312 798 104 566 520 302 248 694 976 430 392 198
184 829 373 181 631 101 969 613 840 740 778 458 284 760 390
821 461 843 513 17 901 711 993 293 157 274 94 192 156 574
34 124 4 878 450 476 712 914 838 669 875 299 823 329 699
815 559 813 459 522 788 168 586 966 232 308 833 251 631 107
813 883 451 509 615 77 281 613 459 205 380 274 302 35 805 | src/euler_python_package/euler_python/easy/p345.py | problem345 | wilsonify/euler | 0 | python | def problem345():
'\n\n\n We define the Matrix Sum of a matrix as the maximum sum of matrix elements\n with each element being the only one in his row and column. For example,\n the Matrix Sum of the matrix below equals 3315 ( = 863 + 383 + 343 + 959 +\n 767):\n\n 7 53 183 439 863\n 497 383 563 79 973\n 287 63 343 169 583\n 627 343 773 959 943\n 767 473 103 699 303\n\n Find the Matrix Sum of:\n\n 7 53 183 439 863 497 383 563 79 973 287 63 343 169 583\n 627 343 773 959 943 767 473 103 699 303 957 703 583 639 913\n 447 283 463 29 23 487 463 993 119 883 327 493 423 159 743\n 217 623 3 399 853 407 103 983 89 463 290 516 212 462 350\n 960 376 682 962 300 780 486 502 912 800 250 346 172 812 350\n 870 456 192 162 593 473 915 45 989 873 823 965 425 329 803\n 973 965 905 919 133 673 665 235 509 613 673 815 165 992 326\n 322 148 972 962 286 255 941 541 265 323 925 281 601 95 973\n 445 721 11 525 473 65 511 164 138 672 18 428 154 448 848\n 414 456 310 312 798 104 566 520 302 248 694 976 430 392 198\n 184 829 373 181 631 101 969 613 840 740 778 458 284 760 390\n 821 461 843 513 17 901 711 993 293 157 274 94 192 156 574\n 34 124 4 878 450 476 712 914 838 669 875 299 823 329 699\n 815 559 813 459 522 788 168 586 966 232 308 833 251 631 107\n 813 883 451 509 615 77 281 613 459 205 380 274 302 35 805\n '
maxsum = [([None] * (2 ** COLUMNS)) for _ in range(ROWS)]
def find_maximum_sum(startrow, setofcols):
if (startrow == ROWS):
assert (eulerlib.popcount(setofcols) == (COLUMNS - ROWS))
return 0
if (maxsum[startrow][setofcols] is None):
result = 0
col = 0
bit = 1
while True:
if (bit > setofcols):
break
if ((setofcols & bit) != 0):
result = max((MATRIX[startrow][col] + find_maximum_sum((startrow + 1), (setofcols ^ bit))), result)
col += 1
bit <<= 1
maxsum[startrow][setofcols] = result
return maxsum[startrow][setofcols]
ans = find_maximum_sum(0, ((2 ** COLUMNS) - 1))
return ans | def problem345():
'\n\n\n We define the Matrix Sum of a matrix as the maximum sum of matrix elements\n with each element being the only one in his row and column. For example,\n the Matrix Sum of the matrix below equals 3315 ( = 863 + 383 + 343 + 959 +\n 767):\n\n 7 53 183 439 863\n 497 383 563 79 973\n 287 63 343 169 583\n 627 343 773 959 943\n 767 473 103 699 303\n\n Find the Matrix Sum of:\n\n 7 53 183 439 863 497 383 563 79 973 287 63 343 169 583\n 627 343 773 959 943 767 473 103 699 303 957 703 583 639 913\n 447 283 463 29 23 487 463 993 119 883 327 493 423 159 743\n 217 623 3 399 853 407 103 983 89 463 290 516 212 462 350\n 960 376 682 962 300 780 486 502 912 800 250 346 172 812 350\n 870 456 192 162 593 473 915 45 989 873 823 965 425 329 803\n 973 965 905 919 133 673 665 235 509 613 673 815 165 992 326\n 322 148 972 962 286 255 941 541 265 323 925 281 601 95 973\n 445 721 11 525 473 65 511 164 138 672 18 428 154 448 848\n 414 456 310 312 798 104 566 520 302 248 694 976 430 392 198\n 184 829 373 181 631 101 969 613 840 740 778 458 284 760 390\n 821 461 843 513 17 901 711 993 293 157 274 94 192 156 574\n 34 124 4 878 450 476 712 914 838 669 875 299 823 329 699\n 815 559 813 459 522 788 168 586 966 232 308 833 251 631 107\n 813 883 451 509 615 77 281 613 459 205 380 274 302 35 805\n '
maxsum = [([None] * (2 ** COLUMNS)) for _ in range(ROWS)]
def find_maximum_sum(startrow, setofcols):
if (startrow == ROWS):
assert (eulerlib.popcount(setofcols) == (COLUMNS - ROWS))
return 0
if (maxsum[startrow][setofcols] is None):
result = 0
col = 0
bit = 1
while True:
if (bit > setofcols):
break
if ((setofcols & bit) != 0):
result = max((MATRIX[startrow][col] + find_maximum_sum((startrow + 1), (setofcols ^ bit))), result)
col += 1
bit <<= 1
maxsum[startrow][setofcols] = result
return maxsum[startrow][setofcols]
ans = find_maximum_sum(0, ((2 ** COLUMNS) - 1))
return ans<|docstring|>We define the Matrix Sum of a matrix as the maximum sum of matrix elements
with each element being the only one in his row and column. For example,
the Matrix Sum of the matrix below equals 3315 ( = 863 + 383 + 343 + 959 +
767):
7 53 183 439 863
497 383 563 79 973
287 63 343 169 583
627 343 773 959 943
767 473 103 699 303
Find the Matrix Sum of:
7 53 183 439 863 497 383 563 79 973 287 63 343 169 583
627 343 773 959 943 767 473 103 699 303 957 703 583 639 913
447 283 463 29 23 487 463 993 119 883 327 493 423 159 743
217 623 3 399 853 407 103 983 89 463 290 516 212 462 350
960 376 682 962 300 780 486 502 912 800 250 346 172 812 350
870 456 192 162 593 473 915 45 989 873 823 965 425 329 803
973 965 905 919 133 673 665 235 509 613 673 815 165 992 326
322 148 972 962 286 255 941 541 265 323 925 281 601 95 973
445 721 11 525 473 65 511 164 138 672 18 428 154 448 848
414 456 310 312 798 104 566 520 302 248 694 976 430 392 198
184 829 373 181 631 101 969 613 840 740 778 458 284 760 390
821 461 843 513 17 901 711 993 293 157 274 94 192 156 574
34 124 4 878 450 476 712 914 838 669 875 299 823 329 699
815 559 813 459 522 788 168 586 966 232 308 833 251 631 107
813 883 451 509 615 77 281 613 459 205 380 274 302 35 805<|endoftext|> |
5568b8c50b9f6726b7f363a9645e33fc0aa1c1e59a86d0f45392fd0bb9ff6ea2 | def issubclass_(arg1, arg2):
'\n Like issubclass but without exception.\n '
try:
return issubclass(arg1, arg2)
except TypeError:
return False | Like issubclass but without exception. | simpleflow/utils/__init__.py | issubclass_ | David-Wobrock/simpleflow | 69 | python | def issubclass_(arg1, arg2):
'\n \n '
try:
return issubclass(arg1, arg2)
except TypeError:
return False | def issubclass_(arg1, arg2):
'\n \n '
try:
return issubclass(arg1, arg2)
except TypeError:
return False<|docstring|>Like issubclass but without exception.<|endoftext|> |
99d5e39b9ffb3bd2aea56d8b43658118405526b76a2d245eee3829f1ab6a70cf | def hex_hash(s):
'\n Hex hash of a string. Not too much constrained\n :param s:\n :return:\n '
if (not s):
return '0'
s = s.encode('utf-8')
return '{:x}'.format((adler32(s) & 4294967295)) | Hex hash of a string. Not too much constrained
:param s:
:return: | simpleflow/utils/__init__.py | hex_hash | David-Wobrock/simpleflow | 69 | python | def hex_hash(s):
'\n Hex hash of a string. Not too much constrained\n :param s:\n :return:\n '
if (not s):
return '0'
s = s.encode('utf-8')
return '{:x}'.format((adler32(s) & 4294967295)) | def hex_hash(s):
'\n Hex hash of a string. Not too much constrained\n :param s:\n :return:\n '
if (not s):
return '0'
s = s.encode('utf-8')
return '{:x}'.format((adler32(s) & 4294967295))<|docstring|>Hex hash of a string. Not too much constrained
:param s:
:return:<|endoftext|> |
0bc14b8c066ccf8b077422c2b4953868eecea52dfc1046b7b4586312564c87be | def format_exc(exc):
'\n Copy-pasted from traceback._format_final_exc_line.\n :param exc: Exception value\n '
etype = exc.__class__.__name__
valuestr = _some_str(exc)
if ((exc is None) or (not valuestr)):
line = ('%s' % etype)
else:
line = ('%s: %s' % (etype, valuestr))
return line | Copy-pasted from traceback._format_final_exc_line.
:param exc: Exception value | simpleflow/utils/__init__.py | format_exc | David-Wobrock/simpleflow | 69 | python | def format_exc(exc):
'\n Copy-pasted from traceback._format_final_exc_line.\n :param exc: Exception value\n '
etype = exc.__class__.__name__
valuestr = _some_str(exc)
if ((exc is None) or (not valuestr)):
line = ('%s' % etype)
else:
line = ('%s: %s' % (etype, valuestr))
return line | def format_exc(exc):
'\n Copy-pasted from traceback._format_final_exc_line.\n :param exc: Exception value\n '
etype = exc.__class__.__name__
valuestr = _some_str(exc)
if ((exc is None) or (not valuestr)):
line = ('%s' % etype)
else:
line = ('%s: %s' % (etype, valuestr))
return line<|docstring|>Copy-pasted from traceback._format_final_exc_line.
:param exc: Exception value<|endoftext|> |
8a89e3e35fefc2bb1fa7b31a35a52690cfc0e4f1e22fdff3874fd347ac714e0a | def _some_str(value):
'\n Copy-pasted from traceback.\n '
try:
return str(value)
except Exception:
return ('<unprintable %s object>' % type(value).__name__) | Copy-pasted from traceback. | simpleflow/utils/__init__.py | _some_str | David-Wobrock/simpleflow | 69 | python | def _some_str(value):
'\n \n '
try:
return str(value)
except Exception:
return ('<unprintable %s object>' % type(value).__name__) | def _some_str(value):
'\n \n '
try:
return str(value)
except Exception:
return ('<unprintable %s object>' % type(value).__name__)<|docstring|>Copy-pasted from traceback.<|endoftext|> |
b212387d24e130ca8d1fc2a3fa32d7e25a0ae7362ebe046e91dbbb70d9fdf347 | def import_from_module(path):
'\n Import a class or other object: either module.Foo or (builtin) Foo.\n :param path: object name\n :return: object\n :raise ImportError: module not found\n '
(module_path, _, obj_name) = path.rpartition('.')
return import_object_from_module(module_path, obj_name) | Import a class or other object: either module.Foo or (builtin) Foo.
:param path: object name
:return: object
:raise ImportError: module not found | simpleflow/utils/__init__.py | import_from_module | David-Wobrock/simpleflow | 69 | python | def import_from_module(path):
'\n Import a class or other object: either module.Foo or (builtin) Foo.\n :param path: object name\n :return: object\n :raise ImportError: module not found\n '
(module_path, _, obj_name) = path.rpartition('.')
return import_object_from_module(module_path, obj_name) | def import_from_module(path):
'\n Import a class or other object: either module.Foo or (builtin) Foo.\n :param path: object name\n :return: object\n :raise ImportError: module not found\n '
(module_path, _, obj_name) = path.rpartition('.')
return import_object_from_module(module_path, obj_name)<|docstring|>Import a class or other object: either module.Foo or (builtin) Foo.
:param path: object name
:return: object
:raise ImportError: module not found<|endoftext|> |
e5fe071a0ce219486dfd9d50d223e8b3ea6eb8ca93d7ee992538aa204f178f75 | @commands.command(pass_context=True, description=poll_description)
@has_permissions(administrator=True, manage_guild=True)
async def poll(self, ctx):
'\n The poll command.\n This is used to create polls in an interactive manner\n Another command (makepoll) can be used to make polls in one command\n '
(await ctx.send(topic_msg))
try:
title = (await self.bot.wait_for('message', timeout=30, check=(lambda message: (message.author.id == ctx.author.id))))
except asyncio.TimeoutError:
return (await ctx.send(timeout_message))
else:
(await ctx.send(duration_message))
try:
time = (await self.bot.wait_for('message', timeout=30, check=(lambda message: (message.author.id == ctx.author.id))))
except asyncio.TimeoutError:
return (await ctx.send(timeout_message))
else:
re_check = re.match('\\d', str(time.content))
if re_check:
(await ctx.send(channel_message))
try:
gw_channel = (await self.bot.wait_for('message', timeout=30, check=(lambda message: (message.author.id == ctx.author.id))))
except asyncio.TimeoutError:
return (await ctx.send(timeout_message))
else:
for channel in ctx.guild.channels:
if (str(channel.mention) == str(gw_channel.content)):
gw_channel_name = gw_channel.content[2:(- 2)]
gw_channel_obj = channel
break
else:
gw_channel_name = None
continue
if (gw_channel_name != None):
(await ctx.send(react_message))
try:
reactions = (await self.bot.wait_for('message', timeout=30, check=(lambda msg: (msg.author.id == ctx.author.id))))
except asyncio.TimeoutError:
return (await ctx.send(timeout_message))
else:
reaction_list = reactions.content.split()
(await ctx.send('Enter the content'))
try:
message = (await self.bot.wait_for('message', timeout=30, check=(lambda message: (message.author.id == ctx.author.id))))
except asyncio.TimeoutError:
return (await ctx.send(timeout_message))
else:
content = message.content
(await ctx.send('Creating poll'))
(await self.create_poll(title=title.content, content=content, channel=gw_channel_obj, reactions=reaction_list, time=int(time.content), time_created=datetime.now(tz=IST)))
else:
return (await ctx.send('Channel not found'))
else:
return (await ctx.send("That doesn't seem to be a valid duration")) | The poll command.
This is used to create polls in an interactive manner
Another command (makepoll) can be used to make polls in one command | cogs/poll.py | poll | IamEinstein/Boom | 1 | python | @commands.command(pass_context=True, description=poll_description)
@has_permissions(administrator=True, manage_guild=True)
async def poll(self, ctx):
'\n The poll command.\n This is used to create polls in an interactive manner\n Another command (makepoll) can be used to make polls in one command\n '
(await ctx.send(topic_msg))
try:
title = (await self.bot.wait_for('message', timeout=30, check=(lambda message: (message.author.id == ctx.author.id))))
except asyncio.TimeoutError:
return (await ctx.send(timeout_message))
else:
(await ctx.send(duration_message))
try:
time = (await self.bot.wait_for('message', timeout=30, check=(lambda message: (message.author.id == ctx.author.id))))
except asyncio.TimeoutError:
return (await ctx.send(timeout_message))
else:
re_check = re.match('\\d', str(time.content))
if re_check:
(await ctx.send(channel_message))
try:
gw_channel = (await self.bot.wait_for('message', timeout=30, check=(lambda message: (message.author.id == ctx.author.id))))
except asyncio.TimeoutError:
return (await ctx.send(timeout_message))
else:
for channel in ctx.guild.channels:
if (str(channel.mention) == str(gw_channel.content)):
gw_channel_name = gw_channel.content[2:(- 2)]
gw_channel_obj = channel
break
else:
gw_channel_name = None
continue
if (gw_channel_name != None):
(await ctx.send(react_message))
try:
reactions = (await self.bot.wait_for('message', timeout=30, check=(lambda msg: (msg.author.id == ctx.author.id))))
except asyncio.TimeoutError:
return (await ctx.send(timeout_message))
else:
reaction_list = reactions.content.split()
(await ctx.send('Enter the content'))
try:
message = (await self.bot.wait_for('message', timeout=30, check=(lambda message: (message.author.id == ctx.author.id))))
except asyncio.TimeoutError:
return (await ctx.send(timeout_message))
else:
content = message.content
(await ctx.send('Creating poll'))
(await self.create_poll(title=title.content, content=content, channel=gw_channel_obj, reactions=reaction_list, time=int(time.content), time_created=datetime.now(tz=IST)))
else:
return (await ctx.send('Channel not found'))
else:
return (await ctx.send("That doesn't seem to be a valid duration")) | @commands.command(pass_context=True, description=poll_description)
@has_permissions(administrator=True, manage_guild=True)
async def poll(self, ctx):
'\n The poll command.\n This is used to create polls in an interactive manner\n Another command (makepoll) can be used to make polls in one command\n '
(await ctx.send(topic_msg))
try:
title = (await self.bot.wait_for('message', timeout=30, check=(lambda message: (message.author.id == ctx.author.id))))
except asyncio.TimeoutError:
return (await ctx.send(timeout_message))
else:
(await ctx.send(duration_message))
try:
time = (await self.bot.wait_for('message', timeout=30, check=(lambda message: (message.author.id == ctx.author.id))))
except asyncio.TimeoutError:
return (await ctx.send(timeout_message))
else:
re_check = re.match('\\d', str(time.content))
if re_check:
(await ctx.send(channel_message))
try:
gw_channel = (await self.bot.wait_for('message', timeout=30, check=(lambda message: (message.author.id == ctx.author.id))))
except asyncio.TimeoutError:
return (await ctx.send(timeout_message))
else:
for channel in ctx.guild.channels:
if (str(channel.mention) == str(gw_channel.content)):
gw_channel_name = gw_channel.content[2:(- 2)]
gw_channel_obj = channel
break
else:
gw_channel_name = None
continue
if (gw_channel_name != None):
(await ctx.send(react_message))
try:
reactions = (await self.bot.wait_for('message', timeout=30, check=(lambda msg: (msg.author.id == ctx.author.id))))
except asyncio.TimeoutError:
return (await ctx.send(timeout_message))
else:
reaction_list = reactions.content.split()
(await ctx.send('Enter the content'))
try:
message = (await self.bot.wait_for('message', timeout=30, check=(lambda message: (message.author.id == ctx.author.id))))
except asyncio.TimeoutError:
return (await ctx.send(timeout_message))
else:
content = message.content
(await ctx.send('Creating poll'))
(await self.create_poll(title=title.content, content=content, channel=gw_channel_obj, reactions=reaction_list, time=int(time.content), time_created=datetime.now(tz=IST)))
else:
return (await ctx.send('Channel not found'))
else:
return (await ctx.send("That doesn't seem to be a valid duration"))<|docstring|>The poll command.
This is used to create polls in an interactive manner
Another command (makepoll) can be used to make polls in one command<|endoftext|> |
41d97b92d9d31a21d6f9286cb634d9679d909e6189d383b6bfc8d34c94af7460 | async def create_poll(self, title: str, content: str, channel, reactions: list, time: int, time_created: datetime):
'\n Method for creating a poll and registering it in the database\n '
time_to_end = (timedelta(minutes=time) + time_created)
embed = discord.Embed(title=title, description=content, color=discord.Color.blurple())
embed.set_footer(text=f'Ends at {format_time(time_to_end)}')
msg = (await channel.send(embed=embed))
for (i, reaction) in enumerate(reactions):
globals()[f'reaction_list{i}'] = []
(await msg.add_reaction(reaction))
poll = PollModel(title=title, content=content, reactions=reactions, start_time=time_created, end_time=time_to_end, poll_id=msg.id, channel_id=channel.id)
try:
poll.commit()
except Exception as e:
(await channel.send(e))
else:
return True | Method for creating a poll and registering it in the database | cogs/poll.py | create_poll | IamEinstein/Boom | 1 | python | async def create_poll(self, title: str, content: str, channel, reactions: list, time: int, time_created: datetime):
'\n \n '
time_to_end = (timedelta(minutes=time) + time_created)
embed = discord.Embed(title=title, description=content, color=discord.Color.blurple())
embed.set_footer(text=f'Ends at {format_time(time_to_end)}')
msg = (await channel.send(embed=embed))
for (i, reaction) in enumerate(reactions):
globals()[f'reaction_list{i}'] = []
(await msg.add_reaction(reaction))
poll = PollModel(title=title, content=content, reactions=reactions, start_time=time_created, end_time=time_to_end, poll_id=msg.id, channel_id=channel.id)
try:
poll.commit()
except Exception as e:
(await channel.send(e))
else:
return True | async def create_poll(self, title: str, content: str, channel, reactions: list, time: int, time_created: datetime):
'\n \n '
time_to_end = (timedelta(minutes=time) + time_created)
embed = discord.Embed(title=title, description=content, color=discord.Color.blurple())
embed.set_footer(text=f'Ends at {format_time(time_to_end)}')
msg = (await channel.send(embed=embed))
for (i, reaction) in enumerate(reactions):
globals()[f'reaction_list{i}'] = []
(await msg.add_reaction(reaction))
poll = PollModel(title=title, content=content, reactions=reactions, start_time=time_created, end_time=time_to_end, poll_id=msg.id, channel_id=channel.id)
try:
poll.commit()
except Exception as e:
(await channel.send(e))
else:
return True<|docstring|>Method for creating a poll and registering it in the database<|endoftext|> |
9baef849979778a111e154146655e7ea24bde9b5d0e7d4d1580187589c005830 | @commands.command(description=testpoll_description)
async def testpoll(self, ctx):
'\n A (temporary) testing command,\n used to test polls\n '
if (ctx.author.id == 764415588873273345):
(await self.create_poll(title='Test', content='oof', channel=ctx.channel, reactions=['🤣', '😔', '😈'], time=0.5, time_created=datetime.now(tz=IST))) | A (temporary) testing command,
used to test polls | cogs/poll.py | testpoll | IamEinstein/Boom | 1 | python | @commands.command(description=testpoll_description)
async def testpoll(self, ctx):
'\n A (temporary) testing command,\n used to test polls\n '
if (ctx.author.id == 764415588873273345):
(await self.create_poll(title='Test', content='oof', channel=ctx.channel, reactions=['🤣', '😔', '😈'], time=0.5, time_created=datetime.now(tz=IST))) | @commands.command(description=testpoll_description)
async def testpoll(self, ctx):
'\n A (temporary) testing command,\n used to test polls\n '
if (ctx.author.id == 764415588873273345):
(await self.create_poll(title='Test', content='oof', channel=ctx.channel, reactions=['🤣', '😔', '😈'], time=0.5, time_created=datetime.now(tz=IST)))<|docstring|>A (temporary) testing command,
used to test polls<|endoftext|> |
5399df52c25866df1afebe5e789a93fab00ff8d3d15cdc4ddeaa7a93a5de0789 | async def end_poll(self, poll: PollModel):
'\n To end the poll which is past the end time\n '
channel = self.bot.get_channel(poll['channel_id'])
msg = (await channel.fetch_message(poll['poll_id']))
reactions = msg.reactions
reaction_count = 0
reaction_emoji = None
for reaction in reactions:
if (reaction.count > reaction_count):
reaction_count = reaction.count
reaction_emoji = reaction.emoji
if reaction_emoji:
(await msg.reply(f'{reaction_emoji} has won'))
poll['ended'] = True
poll['winner'] = reaction_emoji
poll['winner_reaction_count'] = reaction_count
print(poll)
polls.find_and_modify(query={'poll_id': poll['poll_id'], 'channel_id': poll['channel_id']}, update={'$set': poll}) | To end the poll which is past the end time | cogs/poll.py | end_poll | IamEinstein/Boom | 1 | python | async def end_poll(self, poll: PollModel):
'\n \n '
channel = self.bot.get_channel(poll['channel_id'])
msg = (await channel.fetch_message(poll['poll_id']))
reactions = msg.reactions
reaction_count = 0
reaction_emoji = None
for reaction in reactions:
if (reaction.count > reaction_count):
reaction_count = reaction.count
reaction_emoji = reaction.emoji
if reaction_emoji:
(await msg.reply(f'{reaction_emoji} has won'))
poll['ended'] = True
poll['winner'] = reaction_emoji
poll['winner_reaction_count'] = reaction_count
print(poll)
polls.find_and_modify(query={'poll_id': poll['poll_id'], 'channel_id': poll['channel_id']}, update={'$set': poll}) | async def end_poll(self, poll: PollModel):
'\n \n '
channel = self.bot.get_channel(poll['channel_id'])
msg = (await channel.fetch_message(poll['poll_id']))
reactions = msg.reactions
reaction_count = 0
reaction_emoji = None
for reaction in reactions:
if (reaction.count > reaction_count):
reaction_count = reaction.count
reaction_emoji = reaction.emoji
if reaction_emoji:
(await msg.reply(f'{reaction_emoji} has won'))
poll['ended'] = True
poll['winner'] = reaction_emoji
poll['winner_reaction_count'] = reaction_count
print(poll)
polls.find_and_modify(query={'poll_id': poll['poll_id'], 'channel_id': poll['channel_id']}, update={'$set': poll})<|docstring|>To end the poll which is past the end time<|endoftext|> |
9925bbad6982004904c09397083d5ee4d633adf514bfd60865962c31e0f16a60 | @tasks.loop(seconds=45)
async def check_ended(self):
'\n Checks for ended polls\n '
print('Checking for ended polls')
ended_polls = (await PollModel.check_ended_polls())
if ended_polls:
for ended_poll in ended_polls:
(await self.end_poll(poll=ended_poll)) | Checks for ended polls | cogs/poll.py | check_ended | IamEinstein/Boom | 1 | python | @tasks.loop(seconds=45)
async def check_ended(self):
'\n \n '
print('Checking for ended polls')
ended_polls = (await PollModel.check_ended_polls())
if ended_polls:
for ended_poll in ended_polls:
(await self.end_poll(poll=ended_poll)) | @tasks.loop(seconds=45)
async def check_ended(self):
'\n \n '
print('Checking for ended polls')
ended_polls = (await PollModel.check_ended_polls())
if ended_polls:
for ended_poll in ended_polls:
(await self.end_poll(poll=ended_poll))<|docstring|>Checks for ended polls<|endoftext|> |
85802d7b5e794747f128a6d269e4283598e18094ee5f590dd7bb357a47b0166c | @check_ended.before_loop
async def before_check_ended(self):
'Makes sure that the bot is ready before it checks for ended polls'
(await self.bot.wait_until_ready()) | Makes sure that the bot is ready before it checks for ended polls | cogs/poll.py | before_check_ended | IamEinstein/Boom | 1 | python | @check_ended.before_loop
async def before_check_ended(self):
(await self.bot.wait_until_ready()) | @check_ended.before_loop
async def before_check_ended(self):
(await self.bot.wait_until_ready())<|docstring|>Makes sure that the bot is ready before it checks for ended polls<|endoftext|> |
1b053f51fbe72928eec42f8df3a8fd4a2471c672f5a80466555df234a958d755 | def test_frequencies(self):
'Check the frequencies sums up to 1 and that the original data can be obtained by\n multiplying the frequencies by `N`.'
self.assertTrue(np.isclose(self.ca.P.sum().sum(), 1))
self.assertTrue(np.allclose((self.ca.P * self.ca.N), self.initial_dataframe)) | Check the frequencies sums up to 1 and that the original data can be obtained by
multiplying the frequencies by `N`. | tests/test_ca.py | test_frequencies | kormilitzin/Prince | 10 | python | def test_frequencies(self):
'Check the frequencies sums up to 1 and that the original data can be obtained by\n multiplying the frequencies by `N`.'
self.assertTrue(np.isclose(self.ca.P.sum().sum(), 1))
self.assertTrue(np.allclose((self.ca.P * self.ca.N), self.initial_dataframe)) | def test_frequencies(self):
'Check the frequencies sums up to 1 and that the original data can be obtained by\n multiplying the frequencies by `N`.'
self.assertTrue(np.isclose(self.ca.P.sum().sum(), 1))
self.assertTrue(np.allclose((self.ca.P * self.ca.N), self.initial_dataframe))<|docstring|>Check the frequencies sums up to 1 and that the original data can be obtained by
multiplying the frequencies by `N`.<|endoftext|> |
62aaf8de530999acc3624f862b469be2053099399611b05c3d3995815ebe2bae | def train_logistic_regression(data, labels, n_way, device):
' Return a trained logistic regression'
classifier = logistic_regression(data.shape[1], n_way)
classifier.to(device)
criterion = nn.CrossEntropyLoss()
n_steps = 100
batch_size = 5
loss_history = []
steps_per_epoch = int(ceil((data.shape[0] / batch_size)))
n_epoch = (n_steps // steps_per_epoch)
for epoch in tqdm(range(n_epoch), leave=False):
optimizer = get_optimizer_xuqing(classifier)
permut = np.random.permutation(data.shape[0])
data = data[permut]
labels = labels[permut]
sum_loss = 0
for step in range(steps_per_epoch):
(start_batch, end_batch) = ((batch_size * step), (batch_size * (step + 1)))
inputs = data[start_batch:end_batch].to(device)
label = labels[start_batch:end_batch].to(device)
optimizer.zero_grad()
outputs = classifier(inputs)
loss = criterion(outputs, label)
loss.backward()
optimizer.step()
sum_loss += loss
loss_history.append(sum_loss.detach().cpu().item())
return classifier | Return a trained logistic regression | case_study_toolbox/classifiers.py | train_logistic_regression | mbonto/fewshot_generalization | 0 | python | def train_logistic_regression(data, labels, n_way, device):
' '
classifier = logistic_regression(data.shape[1], n_way)
classifier.to(device)
criterion = nn.CrossEntropyLoss()
n_steps = 100
batch_size = 5
loss_history = []
steps_per_epoch = int(ceil((data.shape[0] / batch_size)))
n_epoch = (n_steps // steps_per_epoch)
for epoch in tqdm(range(n_epoch), leave=False):
optimizer = get_optimizer_xuqing(classifier)
permut = np.random.permutation(data.shape[0])
data = data[permut]
labels = labels[permut]
sum_loss = 0
for step in range(steps_per_epoch):
(start_batch, end_batch) = ((batch_size * step), (batch_size * (step + 1)))
inputs = data[start_batch:end_batch].to(device)
label = labels[start_batch:end_batch].to(device)
optimizer.zero_grad()
outputs = classifier(inputs)
loss = criterion(outputs, label)
loss.backward()
optimizer.step()
sum_loss += loss
loss_history.append(sum_loss.detach().cpu().item())
return classifier | def train_logistic_regression(data, labels, n_way, device):
' '
classifier = logistic_regression(data.shape[1], n_way)
classifier.to(device)
criterion = nn.CrossEntropyLoss()
n_steps = 100
batch_size = 5
loss_history = []
steps_per_epoch = int(ceil((data.shape[0] / batch_size)))
n_epoch = (n_steps // steps_per_epoch)
for epoch in tqdm(range(n_epoch), leave=False):
optimizer = get_optimizer_xuqing(classifier)
permut = np.random.permutation(data.shape[0])
data = data[permut]
labels = labels[permut]
sum_loss = 0
for step in range(steps_per_epoch):
(start_batch, end_batch) = ((batch_size * step), (batch_size * (step + 1)))
inputs = data[start_batch:end_batch].to(device)
label = labels[start_batch:end_batch].to(device)
optimizer.zero_grad()
outputs = classifier(inputs)
loss = criterion(outputs, label)
loss.backward()
optimizer.step()
sum_loss += loss
loss_history.append(sum_loss.detach().cpu().item())
return classifier<|docstring|>Return a trained logistic regression<|endoftext|> |
32e96e6f9bcbf3c6266168fd1ff14e4cae09912289d8265c2aa5e87df3fb1e2d | @ops.RegisterGradient('ResizeNearestNeighbor')
def _ResizeNearestNeighborGrad(op, grad):
'The derivatives for nearest neighbor resizing.\n\n Args:\n op: The ResizeNearestNeighbor op.\n grad: The tensor representing the gradient w.r.t. the output.\n\n Returns:\n The gradients w.r.t. the input and the output.\n '
image = op.inputs[0]
if image.get_shape()[1:3].is_fully_defined():
image_shape = image.get_shape()[1:3]
else:
image_shape = array_ops.shape(image)[1:3]
grads = gen_image_ops.resize_nearest_neighbor_grad(grad, image_shape, align_corners=op.get_attr('align_corners'), half_pixel_centers=op.get_attr('half_pixel_centers'))
return [grads, None] | The derivatives for nearest neighbor resizing.
Args:
op: The ResizeNearestNeighbor op.
grad: The tensor representing the gradient w.r.t. the output.
Returns:
The gradients w.r.t. the input and the output. | tensorflow/python/ops/image_grad.py | _ResizeNearestNeighborGrad | jnorwood/tensorflow | 36 | python | @ops.RegisterGradient('ResizeNearestNeighbor')
def _ResizeNearestNeighborGrad(op, grad):
'The derivatives for nearest neighbor resizing.\n\n Args:\n op: The ResizeNearestNeighbor op.\n grad: The tensor representing the gradient w.r.t. the output.\n\n Returns:\n The gradients w.r.t. the input and the output.\n '
image = op.inputs[0]
if image.get_shape()[1:3].is_fully_defined():
image_shape = image.get_shape()[1:3]
else:
image_shape = array_ops.shape(image)[1:3]
grads = gen_image_ops.resize_nearest_neighbor_grad(grad, image_shape, align_corners=op.get_attr('align_corners'), half_pixel_centers=op.get_attr('half_pixel_centers'))
return [grads, None] | @ops.RegisterGradient('ResizeNearestNeighbor')
def _ResizeNearestNeighborGrad(op, grad):
'The derivatives for nearest neighbor resizing.\n\n Args:\n op: The ResizeNearestNeighbor op.\n grad: The tensor representing the gradient w.r.t. the output.\n\n Returns:\n The gradients w.r.t. the input and the output.\n '
image = op.inputs[0]
if image.get_shape()[1:3].is_fully_defined():
image_shape = image.get_shape()[1:3]
else:
image_shape = array_ops.shape(image)[1:3]
grads = gen_image_ops.resize_nearest_neighbor_grad(grad, image_shape, align_corners=op.get_attr('align_corners'), half_pixel_centers=op.get_attr('half_pixel_centers'))
return [grads, None]<|docstring|>The derivatives for nearest neighbor resizing.
Args:
op: The ResizeNearestNeighbor op.
grad: The tensor representing the gradient w.r.t. the output.
Returns:
The gradients w.r.t. the input and the output.<|endoftext|> |
e02b358413ffa804669fa7e49a34421e03ed342b756804a179e3a9d52d0b21b4 | @ops.RegisterGradient('ResizeBilinear')
def _ResizeBilinearGrad(op, grad):
'The derivatives for bilinear resizing.\n\n Args:\n op: The ResizeBilinear op.\n grad: The tensor representing the gradient w.r.t. the output.\n\n Returns:\n The gradients w.r.t. the input.\n '
grad0 = gen_image_ops.resize_bilinear_grad(grad, op.inputs[0], align_corners=op.get_attr('align_corners'), half_pixel_centers=op.get_attr('half_pixel_centers'))
return [grad0, None] | The derivatives for bilinear resizing.
Args:
op: The ResizeBilinear op.
grad: The tensor representing the gradient w.r.t. the output.
Returns:
The gradients w.r.t. the input. | tensorflow/python/ops/image_grad.py | _ResizeBilinearGrad | jnorwood/tensorflow | 36 | python | @ops.RegisterGradient('ResizeBilinear')
def _ResizeBilinearGrad(op, grad):
'The derivatives for bilinear resizing.\n\n Args:\n op: The ResizeBilinear op.\n grad: The tensor representing the gradient w.r.t. the output.\n\n Returns:\n The gradients w.r.t. the input.\n '
grad0 = gen_image_ops.resize_bilinear_grad(grad, op.inputs[0], align_corners=op.get_attr('align_corners'), half_pixel_centers=op.get_attr('half_pixel_centers'))
return [grad0, None] | @ops.RegisterGradient('ResizeBilinear')
def _ResizeBilinearGrad(op, grad):
'The derivatives for bilinear resizing.\n\n Args:\n op: The ResizeBilinear op.\n grad: The tensor representing the gradient w.r.t. the output.\n\n Returns:\n The gradients w.r.t. the input.\n '
grad0 = gen_image_ops.resize_bilinear_grad(grad, op.inputs[0], align_corners=op.get_attr('align_corners'), half_pixel_centers=op.get_attr('half_pixel_centers'))
return [grad0, None]<|docstring|>The derivatives for bilinear resizing.
Args:
op: The ResizeBilinear op.
grad: The tensor representing the gradient w.r.t. the output.
Returns:
The gradients w.r.t. the input.<|endoftext|> |
972a079339bbcc5d5cd5cb9c9a56792fe5528995c6a74042ca4399e403dfc707 | @ops.RegisterGradient('ScaleAndTranslate')
def _ScaleAndTranslateGrad(op, grad):
'The derivatives for ScaleAndTranslate transformation op.\n\n Args:\n op: The ScaleAndTranslate op.\n grad: The tensor representing the gradient w.r.t. the output.\n\n Returns:\n The gradients w.r.t. the input.\n '
grad0 = gen_image_ops.scale_and_translate_grad(grad, op.inputs[0], op.inputs[2], op.inputs[3], kernel_type=op.get_attr('kernel_type'), antialias=op.get_attr('antialias'))
return [grad0, None, None, None] | The derivatives for ScaleAndTranslate transformation op.
Args:
op: The ScaleAndTranslate op.
grad: The tensor representing the gradient w.r.t. the output.
Returns:
The gradients w.r.t. the input. | tensorflow/python/ops/image_grad.py | _ScaleAndTranslateGrad | jnorwood/tensorflow | 36 | python | @ops.RegisterGradient('ScaleAndTranslate')
def _ScaleAndTranslateGrad(op, grad):
'The derivatives for ScaleAndTranslate transformation op.\n\n Args:\n op: The ScaleAndTranslate op.\n grad: The tensor representing the gradient w.r.t. the output.\n\n Returns:\n The gradients w.r.t. the input.\n '
grad0 = gen_image_ops.scale_and_translate_grad(grad, op.inputs[0], op.inputs[2], op.inputs[3], kernel_type=op.get_attr('kernel_type'), antialias=op.get_attr('antialias'))
return [grad0, None, None, None] | @ops.RegisterGradient('ScaleAndTranslate')
def _ScaleAndTranslateGrad(op, grad):
'The derivatives for ScaleAndTranslate transformation op.\n\n Args:\n op: The ScaleAndTranslate op.\n grad: The tensor representing the gradient w.r.t. the output.\n\n Returns:\n The gradients w.r.t. the input.\n '
grad0 = gen_image_ops.scale_and_translate_grad(grad, op.inputs[0], op.inputs[2], op.inputs[3], kernel_type=op.get_attr('kernel_type'), antialias=op.get_attr('antialias'))
return [grad0, None, None, None]<|docstring|>The derivatives for ScaleAndTranslate transformation op.
Args:
op: The ScaleAndTranslate op.
grad: The tensor representing the gradient w.r.t. the output.
Returns:
The gradients w.r.t. the input.<|endoftext|> |
c990c2fcb19c5e22b7958d670e336da45367ea708f332026c32711cb4addea5e | @ops.RegisterGradient('ResizeBicubic')
def _ResizeBicubicGrad(op, grad):
'The derivatives for bicubic resizing.\n\n Args:\n op: The ResizeBicubic op.\n grad: The tensor representing the gradient w.r.t. the output.\n\n Returns:\n The gradients w.r.t. the input.\n '
allowed_types = [dtypes.float32, dtypes.float64]
grad0 = None
if (op.inputs[0].dtype in allowed_types):
grad0 = gen_image_ops.resize_bicubic_grad(grad, op.inputs[0], align_corners=op.get_attr('align_corners'), half_pixel_centers=op.get_attr('half_pixel_centers'))
return [grad0, None] | The derivatives for bicubic resizing.
Args:
op: The ResizeBicubic op.
grad: The tensor representing the gradient w.r.t. the output.
Returns:
The gradients w.r.t. the input. | tensorflow/python/ops/image_grad.py | _ResizeBicubicGrad | jnorwood/tensorflow | 36 | python | @ops.RegisterGradient('ResizeBicubic')
def _ResizeBicubicGrad(op, grad):
'The derivatives for bicubic resizing.\n\n Args:\n op: The ResizeBicubic op.\n grad: The tensor representing the gradient w.r.t. the output.\n\n Returns:\n The gradients w.r.t. the input.\n '
allowed_types = [dtypes.float32, dtypes.float64]
grad0 = None
if (op.inputs[0].dtype in allowed_types):
grad0 = gen_image_ops.resize_bicubic_grad(grad, op.inputs[0], align_corners=op.get_attr('align_corners'), half_pixel_centers=op.get_attr('half_pixel_centers'))
return [grad0, None] | @ops.RegisterGradient('ResizeBicubic')
def _ResizeBicubicGrad(op, grad):
'The derivatives for bicubic resizing.\n\n Args:\n op: The ResizeBicubic op.\n grad: The tensor representing the gradient w.r.t. the output.\n\n Returns:\n The gradients w.r.t. the input.\n '
allowed_types = [dtypes.float32, dtypes.float64]
grad0 = None
if (op.inputs[0].dtype in allowed_types):
grad0 = gen_image_ops.resize_bicubic_grad(grad, op.inputs[0], align_corners=op.get_attr('align_corners'), half_pixel_centers=op.get_attr('half_pixel_centers'))
return [grad0, None]<|docstring|>The derivatives for bicubic resizing.
Args:
op: The ResizeBicubic op.
grad: The tensor representing the gradient w.r.t. the output.
Returns:
The gradients w.r.t. the input.<|endoftext|> |
6cd56659027cb1ec7add8659e3d1e7079886b55642a53f7d2b9a19fa7fca9a17 | @ops.RegisterGradient('CropAndResize')
def _CropAndResizeGrad(op, grad):
'The derivatives for crop_and_resize.\n\n We back-propagate to the image only when the input image tensor has floating\n point dtype but we always back-propagate to the input boxes tensor.\n\n Args:\n op: The CropAndResize op.\n grad: The tensor representing the gradient w.r.t. the output.\n\n Returns:\n The gradients w.r.t. the input image, boxes, as well as the always-None\n gradients w.r.t. box_ind and crop_size.\n '
image = op.inputs[0]
if image.get_shape().is_fully_defined():
image_shape = image.get_shape().as_list()
else:
image_shape = array_ops.shape(image)
allowed_types = [dtypes.float16, dtypes.float32, dtypes.float64]
if (op.inputs[0].dtype in allowed_types):
grad0 = gen_image_ops.crop_and_resize_grad_image(grad, op.inputs[1], op.inputs[2], image_shape, T=op.get_attr('T'), method=op.get_attr('method'))
else:
grad0 = None
grad1 = gen_image_ops.crop_and_resize_grad_boxes(grad, op.inputs[0], op.inputs[1], op.inputs[2])
return [grad0, grad1, None, None] | The derivatives for crop_and_resize.
We back-propagate to the image only when the input image tensor has floating
point dtype but we always back-propagate to the input boxes tensor.
Args:
op: The CropAndResize op.
grad: The tensor representing the gradient w.r.t. the output.
Returns:
The gradients w.r.t. the input image, boxes, as well as the always-None
gradients w.r.t. box_ind and crop_size. | tensorflow/python/ops/image_grad.py | _CropAndResizeGrad | jnorwood/tensorflow | 36 | python | @ops.RegisterGradient('CropAndResize')
def _CropAndResizeGrad(op, grad):
'The derivatives for crop_and_resize.\n\n We back-propagate to the image only when the input image tensor has floating\n point dtype but we always back-propagate to the input boxes tensor.\n\n Args:\n op: The CropAndResize op.\n grad: The tensor representing the gradient w.r.t. the output.\n\n Returns:\n The gradients w.r.t. the input image, boxes, as well as the always-None\n gradients w.r.t. box_ind and crop_size.\n '
image = op.inputs[0]
if image.get_shape().is_fully_defined():
image_shape = image.get_shape().as_list()
else:
image_shape = array_ops.shape(image)
allowed_types = [dtypes.float16, dtypes.float32, dtypes.float64]
if (op.inputs[0].dtype in allowed_types):
grad0 = gen_image_ops.crop_and_resize_grad_image(grad, op.inputs[1], op.inputs[2], image_shape, T=op.get_attr('T'), method=op.get_attr('method'))
else:
grad0 = None
grad1 = gen_image_ops.crop_and_resize_grad_boxes(grad, op.inputs[0], op.inputs[1], op.inputs[2])
return [grad0, grad1, None, None] | @ops.RegisterGradient('CropAndResize')
def _CropAndResizeGrad(op, grad):
'The derivatives for crop_and_resize.\n\n We back-propagate to the image only when the input image tensor has floating\n point dtype but we always back-propagate to the input boxes tensor.\n\n Args:\n op: The CropAndResize op.\n grad: The tensor representing the gradient w.r.t. the output.\n\n Returns:\n The gradients w.r.t. the input image, boxes, as well as the always-None\n gradients w.r.t. box_ind and crop_size.\n '
image = op.inputs[0]
if image.get_shape().is_fully_defined():
image_shape = image.get_shape().as_list()
else:
image_shape = array_ops.shape(image)
allowed_types = [dtypes.float16, dtypes.float32, dtypes.float64]
if (op.inputs[0].dtype in allowed_types):
grad0 = gen_image_ops.crop_and_resize_grad_image(grad, op.inputs[1], op.inputs[2], image_shape, T=op.get_attr('T'), method=op.get_attr('method'))
else:
grad0 = None
grad1 = gen_image_ops.crop_and_resize_grad_boxes(grad, op.inputs[0], op.inputs[1], op.inputs[2])
return [grad0, grad1, None, None]<|docstring|>The derivatives for crop_and_resize.
We back-propagate to the image only when the input image tensor has floating
point dtype but we always back-propagate to the input boxes tensor.
Args:
op: The CropAndResize op.
grad: The tensor representing the gradient w.r.t. the output.
Returns:
The gradients w.r.t. the input image, boxes, as well as the always-None
gradients w.r.t. box_ind and crop_size.<|endoftext|> |
5e13f2fdc132244f7c5bf7731d9521adf1b292d47175d4ddee67bbc9b0b4147a | def parse_ltl(formula: str):
'\n Parses LTL formula\n Args:\n formula: string, in infix or prefix notation\n Returns:\n abstract syntax tree or None if formula can not be parsed\n '
ast = parse_infix_ltl(formula)
if ast:
return ast
return parse_prefix_ltl(formula) | Parses LTL formula
Args:
formula: string, in infix or prefix notation
Returns:
abstract syntax tree or None if formula can not be parsed | ml2/ltl/ltl_parser.py | parse_ltl | reactive-systems/ml2 | 2 | python | def parse_ltl(formula: str):
'\n Parses LTL formula\n Args:\n formula: string, in infix or prefix notation\n Returns:\n abstract syntax tree or None if formula can not be parsed\n '
ast = parse_infix_ltl(formula)
if ast:
return ast
return parse_prefix_ltl(formula) | def parse_ltl(formula: str):
'\n Parses LTL formula\n Args:\n formula: string, in infix or prefix notation\n Returns:\n abstract syntax tree or None if formula can not be parsed\n '
ast = parse_infix_ltl(formula)
if ast:
return ast
return parse_prefix_ltl(formula)<|docstring|>Parses LTL formula
Args:
formula: string, in infix or prefix notation
Returns:
abstract syntax tree or None if formula can not be parsed<|endoftext|> |
1e77969c6d8e811a219c65b4f240758df0174d78501e8dcd6097401333cb6719 | def clean(self, *args, **kwargs):
" Check that the secret starts with the URL slug plus a dot, as that's the format that\n Let's Encrypt creates them in.\n "
return_value = super(Secret, self).clean(*args, **kwargs)
if (not self.secret.startswith((self.url_slug + '.'))):
raise ValidationError('The URL slug and the beginning of the secret should be the same.') | Check that the secret starts with the URL slug plus a dot, as that's the format that
Let's Encrypt creates them in. | letsencryptae/models.py | clean | adamalton/letsencrypt-appengine | 5 | python | def clean(self, *args, **kwargs):
" Check that the secret starts with the URL slug plus a dot, as that's the format that\n Let's Encrypt creates them in.\n "
return_value = super(Secret, self).clean(*args, **kwargs)
if (not self.secret.startswith((self.url_slug + '.'))):
raise ValidationError('The URL slug and the beginning of the secret should be the same.') | def clean(self, *args, **kwargs):
" Check that the secret starts with the URL slug plus a dot, as that's the format that\n Let's Encrypt creates them in.\n "
return_value = super(Secret, self).clean(*args, **kwargs)
if (not self.secret.startswith((self.url_slug + '.'))):
raise ValidationError('The URL slug and the beginning of the secret should be the same.')<|docstring|>Check that the secret starts with the URL slug plus a dot, as that's the format that
Let's Encrypt creates them in.<|endoftext|> |
a173e85a23caf31b6f1a8622ebb242322655b0fdbf8f5303551967137730a8be | def compose_tx_locking_script(dest_address):
'\n Create a Locking script (ScriptPubKey) that will be assigned to a transaction output.\n :param dest_address: destination address in Base58Check format\n :return: sequence of opcodes and its arguments, defining logic of the locking script\n '
pubkey_hash = bytearray.fromhex(b58check_to_hex(dest_address))
if (len(pubkey_hash) != 20):
raise Exception(('Invalid length of the public key hash: ' + str(len(pubkey_hash))))
if (dest_address[0] in P2PKH_PREFIXES):
scr = (((((OP_DUP + OP_HASH160) + int.to_bytes(len(pubkey_hash), 1, byteorder='little')) + pubkey_hash) + OP_QEUALVERIFY) + OP_CHECKSIG)
elif (dest_address[0] in P2SH_PREFIXES):
scr = (((OP_HASH160 + int.to_bytes(len(pubkey_hash), 1, byteorder='little')) + pubkey_hash) + OP_EQUAL)
else:
raise Exception(('Invalid dest address prefix: ' + dest_address[0]))
return scr | Create a Locking script (ScriptPubKey) that will be assigned to a transaction output.
:param dest_address: destination address in Base58Check format
:return: sequence of opcodes and its arguments, defining logic of the locking script | src/utils.py | compose_tx_locking_script | p0lt/QMT | 1 | python | def compose_tx_locking_script(dest_address):
'\n Create a Locking script (ScriptPubKey) that will be assigned to a transaction output.\n :param dest_address: destination address in Base58Check format\n :return: sequence of opcodes and its arguments, defining logic of the locking script\n '
pubkey_hash = bytearray.fromhex(b58check_to_hex(dest_address))
if (len(pubkey_hash) != 20):
raise Exception(('Invalid length of the public key hash: ' + str(len(pubkey_hash))))
if (dest_address[0] in P2PKH_PREFIXES):
scr = (((((OP_DUP + OP_HASH160) + int.to_bytes(len(pubkey_hash), 1, byteorder='little')) + pubkey_hash) + OP_QEUALVERIFY) + OP_CHECKSIG)
elif (dest_address[0] in P2SH_PREFIXES):
scr = (((OP_HASH160 + int.to_bytes(len(pubkey_hash), 1, byteorder='little')) + pubkey_hash) + OP_EQUAL)
else:
raise Exception(('Invalid dest address prefix: ' + dest_address[0]))
return scr | def compose_tx_locking_script(dest_address):
'\n Create a Locking script (ScriptPubKey) that will be assigned to a transaction output.\n :param dest_address: destination address in Base58Check format\n :return: sequence of opcodes and its arguments, defining logic of the locking script\n '
pubkey_hash = bytearray.fromhex(b58check_to_hex(dest_address))
if (len(pubkey_hash) != 20):
raise Exception(('Invalid length of the public key hash: ' + str(len(pubkey_hash))))
if (dest_address[0] in P2PKH_PREFIXES):
scr = (((((OP_DUP + OP_HASH160) + int.to_bytes(len(pubkey_hash), 1, byteorder='little')) + pubkey_hash) + OP_QEUALVERIFY) + OP_CHECKSIG)
elif (dest_address[0] in P2SH_PREFIXES):
scr = (((OP_HASH160 + int.to_bytes(len(pubkey_hash), 1, byteorder='little')) + pubkey_hash) + OP_EQUAL)
else:
raise Exception(('Invalid dest address prefix: ' + dest_address[0]))
return scr<|docstring|>Create a Locking script (ScriptPubKey) that will be assigned to a transaction output.
:param dest_address: destination address in Base58Check format
:return: sequence of opcodes and its arguments, defining logic of the locking script<|endoftext|> |
c7819ed3229fc02c08e6206da7a00f298415670bb5bdfa34a9ab024f51d00a71 | def compose_tx_locking_script_OR(message):
'\n Create a Locking script (ScriptPubKey) that will be assigned to a transaction output.\n :param message: data for the OP_RETURN\n :return: sequence of opcodes and its arguments, defining logic of the locking script\n '
scr = ((OP_RETURN + int.to_bytes(len(data), 1, byteorder='little')) + message.encode())
return scr | Create a Locking script (ScriptPubKey) that will be assigned to a transaction output.
:param message: data for the OP_RETURN
:return: sequence of opcodes and its arguments, defining logic of the locking script | src/utils.py | compose_tx_locking_script_OR | p0lt/QMT | 1 | python | def compose_tx_locking_script_OR(message):
'\n Create a Locking script (ScriptPubKey) that will be assigned to a transaction output.\n :param message: data for the OP_RETURN\n :return: sequence of opcodes and its arguments, defining logic of the locking script\n '
scr = ((OP_RETURN + int.to_bytes(len(data), 1, byteorder='little')) + message.encode())
return scr | def compose_tx_locking_script_OR(message):
'\n Create a Locking script (ScriptPubKey) that will be assigned to a transaction output.\n :param message: data for the OP_RETURN\n :return: sequence of opcodes and its arguments, defining logic of the locking script\n '
scr = ((OP_RETURN + int.to_bytes(len(data), 1, byteorder='little')) + message.encode())
return scr<|docstring|>Create a Locking script (ScriptPubKey) that will be assigned to a transaction output.
:param message: data for the OP_RETURN
:return: sequence of opcodes and its arguments, defining logic of the locking script<|endoftext|> |
a29659263d60a6182d96e2c939851efa97ce42814cdc5c222d05ad616da0d13f | def ecdsa_sign(msg, priv):
'\n Based on project: https://github.com/chaeplin/dashmnb.\n '
(v, r, s) = ecdsa_raw_sign(electrum_sig_hash(msg), priv)
sig = encode_sig(v, r, s)
pubkey = privkey_to_pubkey(wif_to_privkey(priv))
ok = ecdsa_raw_verify(electrum_sig_hash(msg), decode_sig(sig), pubkey)
if (not ok):
raise Exception('Bad signature!')
return sig | Based on project: https://github.com/chaeplin/dashmnb. | src/utils.py | ecdsa_sign | p0lt/QMT | 1 | python | def ecdsa_sign(msg, priv):
'\n \n '
(v, r, s) = ecdsa_raw_sign(electrum_sig_hash(msg), priv)
sig = encode_sig(v, r, s)
pubkey = privkey_to_pubkey(wif_to_privkey(priv))
ok = ecdsa_raw_verify(electrum_sig_hash(msg), decode_sig(sig), pubkey)
if (not ok):
raise Exception('Bad signature!')
return sig | def ecdsa_sign(msg, priv):
'\n \n '
(v, r, s) = ecdsa_raw_sign(electrum_sig_hash(msg), priv)
sig = encode_sig(v, r, s)
pubkey = privkey_to_pubkey(wif_to_privkey(priv))
ok = ecdsa_raw_verify(electrum_sig_hash(msg), decode_sig(sig), pubkey)
if (not ok):
raise Exception('Bad signature!')
return sig<|docstring|>Based on project: https://github.com/chaeplin/dashmnb.<|endoftext|> |
0865945e84ec7dd2cb3952425bf77b33713a803216368346945e0ae7cc5a2682 | def electrum_sig_hash(message):
'\n Based on project: https://github.com/chaeplin/dashmnb.\n '
padded = ((b'\x18DarkNet Signed Message:\n' + num_to_varint(len(message))) + from_string_to_bytes(message))
return dbl_sha256(padded) | Based on project: https://github.com/chaeplin/dashmnb. | src/utils.py | electrum_sig_hash | p0lt/QMT | 1 | python | def electrum_sig_hash(message):
'\n \n '
padded = ((b'\x18DarkNet Signed Message:\n' + num_to_varint(len(message))) + from_string_to_bytes(message))
return dbl_sha256(padded) | def electrum_sig_hash(message):
'\n \n '
padded = ((b'\x18DarkNet Signed Message:\n' + num_to_varint(len(message))) + from_string_to_bytes(message))
return dbl_sha256(padded)<|docstring|>Based on project: https://github.com/chaeplin/dashmnb.<|endoftext|> |
b75082916e5a472ff32ac7bd807795fbfa2ccef19520fe74afa8865bba5b6a4c | def num_to_varint(a):
'\n Based on project: https://github.com/chaeplin/dashmnb\n '
x = int(a)
if (x < 253):
return x.to_bytes(1, byteorder='big')
elif (x < 65536):
return (int(253).to_bytes(1, byteorder='big') + x.to_bytes(2, byteorder='little'))
elif (x < 4294967296):
return (int(254).to_bytes(1, byteorder='big') + x.to_bytes(4, byteorder='little'))
else:
return (int(255).to_bytes(1, byteorder='big') + x.to_bytes(8, byteorder='little')) | Based on project: https://github.com/chaeplin/dashmnb | src/utils.py | num_to_varint | p0lt/QMT | 1 | python | def num_to_varint(a):
'\n \n '
x = int(a)
if (x < 253):
return x.to_bytes(1, byteorder='big')
elif (x < 65536):
return (int(253).to_bytes(1, byteorder='big') + x.to_bytes(2, byteorder='little'))
elif (x < 4294967296):
return (int(254).to_bytes(1, byteorder='big') + x.to_bytes(4, byteorder='little'))
else:
return (int(255).to_bytes(1, byteorder='big') + x.to_bytes(8, byteorder='little')) | def num_to_varint(a):
'\n \n '
x = int(a)
if (x < 253):
return x.to_bytes(1, byteorder='big')
elif (x < 65536):
return (int(253).to_bytes(1, byteorder='big') + x.to_bytes(2, byteorder='little'))
elif (x < 4294967296):
return (int(254).to_bytes(1, byteorder='big') + x.to_bytes(4, byteorder='little'))
else:
return (int(255).to_bytes(1, byteorder='big') + x.to_bytes(8, byteorder='little'))<|docstring|>Based on project: https://github.com/chaeplin/dashmnb<|endoftext|> |
9c2d5f352ffa7912bc2766077b62b66396906e143f1b12d11784ed91854d849e | def serialize_input_str(tx, prevout_n, sequence, script_sig):
'\n Based on project: https://github.com/chaeplin/dashmnb.\n '
s = ['CTxIn(']
s.append(('COutPoint(%s, %s)' % (tx, prevout_n)))
s.append(', ')
if ((tx == ('00' * 32)) and (prevout_n == 4294967295)):
s.append(('coinbase %s' % script_sig))
else:
script_sig2 = script_sig
if (len(script_sig2) > 24):
script_sig2 = script_sig2[0:24]
s.append(('scriptSig=%s' % script_sig2))
if (sequence != 4294967295):
s.append((', nSequence=%d' % sequence))
s.append(')')
return ''.join(s) | Based on project: https://github.com/chaeplin/dashmnb. | src/utils.py | serialize_input_str | p0lt/QMT | 1 | python | def serialize_input_str(tx, prevout_n, sequence, script_sig):
'\n \n '
s = ['CTxIn(']
s.append(('COutPoint(%s, %s)' % (tx, prevout_n)))
s.append(', ')
if ((tx == ('00' * 32)) and (prevout_n == 4294967295)):
s.append(('coinbase %s' % script_sig))
else:
script_sig2 = script_sig
if (len(script_sig2) > 24):
script_sig2 = script_sig2[0:24]
s.append(('scriptSig=%s' % script_sig2))
if (sequence != 4294967295):
s.append((', nSequence=%d' % sequence))
s.append(')')
return .join(s) | def serialize_input_str(tx, prevout_n, sequence, script_sig):
'\n \n '
s = ['CTxIn(']
s.append(('COutPoint(%s, %s)' % (tx, prevout_n)))
s.append(', ')
if ((tx == ('00' * 32)) and (prevout_n == 4294967295)):
s.append(('coinbase %s' % script_sig))
else:
script_sig2 = script_sig
if (len(script_sig2) > 24):
script_sig2 = script_sig2[0:24]
s.append(('scriptSig=%s' % script_sig2))
if (sequence != 4294967295):
s.append((', nSequence=%d' % sequence))
s.append(')')
return .join(s)<|docstring|>Based on project: https://github.com/chaeplin/dashmnb.<|endoftext|> |
0ae3a686eaa8b5890af251c52c525f743572aa171c0961d86ae246c6ace7b815 | def setUp(self) -> None:
'\n Sets up for the test cases\n '
state1: Dict[(str, Any)] = {'timestamp': 1, 'pose': [1, 2, 3]}
state2: Dict[(str, Any)] = {'timestamp': 2, 'pose': [3, 4, 5]}
prediction_states: List[Dict[(str, Any)]] = [state1, state2]
self.width = 3
self.length = 6
self.height = 2
self.scene_simple_trajectory = SceneSimpleTrajectory(prediction_states, width=self.width, length=self.length, height=self.height) | Sets up for the test cases | nuplan/planning/utils/serialization/test/test_scene_simple_trajectory.py | setUp | motional/nuplan-devkit | 128 | python | def setUp(self) -> None:
'\n \n '
state1: Dict[(str, Any)] = {'timestamp': 1, 'pose': [1, 2, 3]}
state2: Dict[(str, Any)] = {'timestamp': 2, 'pose': [3, 4, 5]}
prediction_states: List[Dict[(str, Any)]] = [state1, state2]
self.width = 3
self.length = 6
self.height = 2
self.scene_simple_trajectory = SceneSimpleTrajectory(prediction_states, width=self.width, length=self.length, height=self.height) | def setUp(self) -> None:
'\n \n '
state1: Dict[(str, Any)] = {'timestamp': 1, 'pose': [1, 2, 3]}
state2: Dict[(str, Any)] = {'timestamp': 2, 'pose': [3, 4, 5]}
prediction_states: List[Dict[(str, Any)]] = [state1, state2]
self.width = 3
self.length = 6
self.height = 2
self.scene_simple_trajectory = SceneSimpleTrajectory(prediction_states, width=self.width, length=self.length, height=self.height)<|docstring|>Sets up for the test cases<|endoftext|> |
39f7a4e0be77a3325bc049c14f34a0a84093492d0218040ce749cba386bfc732 | def test_init(self) -> None:
'\n Tests the init of SceneSiimpleTrajectory\n '
state1: Dict[(str, Any)] = {'timestamp': 1, 'pose': [1, 2, 3]}
state2: Dict[(str, Any)] = {'timestamp': 2, 'pose': [3, 4, 5]}
prediction_states: List[Dict[(str, Any)]] = [state1, state2]
result = SceneSimpleTrajectory(prediction_states, width=self.width, length=self.length, height=self.height)
self.assertEqual(result._start_time, 1)
self.assertEqual(result._end_time, 2) | Tests the init of SceneSiimpleTrajectory | nuplan/planning/utils/serialization/test/test_scene_simple_trajectory.py | test_init | motional/nuplan-devkit | 128 | python | def test_init(self) -> None:
'\n \n '
state1: Dict[(str, Any)] = {'timestamp': 1, 'pose': [1, 2, 3]}
state2: Dict[(str, Any)] = {'timestamp': 2, 'pose': [3, 4, 5]}
prediction_states: List[Dict[(str, Any)]] = [state1, state2]
result = SceneSimpleTrajectory(prediction_states, width=self.width, length=self.length, height=self.height)
self.assertEqual(result._start_time, 1)
self.assertEqual(result._end_time, 2) | def test_init(self) -> None:
'\n \n '
state1: Dict[(str, Any)] = {'timestamp': 1, 'pose': [1, 2, 3]}
state2: Dict[(str, Any)] = {'timestamp': 2, 'pose': [3, 4, 5]}
prediction_states: List[Dict[(str, Any)]] = [state1, state2]
result = SceneSimpleTrajectory(prediction_states, width=self.width, length=self.length, height=self.height)
self.assertEqual(result._start_time, 1)
self.assertEqual(result._end_time, 2)<|docstring|>Tests the init of SceneSiimpleTrajectory<|endoftext|> |
bac2fffd21f57a6c9a2b525d500b11f879de48a07012e3756349a21b32113084 | def test_start_time(self) -> None:
'\n Tests the start time property\n '
scene_simple_trajectory = self.scene_simple_trajectory
result = scene_simple_trajectory.start_time
self.assertEqual(result, 1) | Tests the start time property | nuplan/planning/utils/serialization/test/test_scene_simple_trajectory.py | test_start_time | motional/nuplan-devkit | 128 | python | def test_start_time(self) -> None:
'\n \n '
scene_simple_trajectory = self.scene_simple_trajectory
result = scene_simple_trajectory.start_time
self.assertEqual(result, 1) | def test_start_time(self) -> None:
'\n \n '
scene_simple_trajectory = self.scene_simple_trajectory
result = scene_simple_trajectory.start_time
self.assertEqual(result, 1)<|docstring|>Tests the start time property<|endoftext|> |
32e530db784a8430091152f9870fbdc579ed72d8bfe279af21673c94d4cf9b8e | def test_end_time(self) -> None:
'\n Tests the start time property\n '
scene_simple_trajectory = self.scene_simple_trajectory
result = scene_simple_trajectory.end_time
self.assertEqual(result, 2) | Tests the start time property | nuplan/planning/utils/serialization/test/test_scene_simple_trajectory.py | test_end_time | motional/nuplan-devkit | 128 | python | def test_end_time(self) -> None:
'\n \n '
scene_simple_trajectory = self.scene_simple_trajectory
result = scene_simple_trajectory.end_time
self.assertEqual(result, 2) | def test_end_time(self) -> None:
'\n \n '
scene_simple_trajectory = self.scene_simple_trajectory
result = scene_simple_trajectory.end_time
self.assertEqual(result, 2)<|docstring|>Tests the start time property<|endoftext|> |
1850c27320d463accc25300b13a2fdf6242e2a1e4eb5c785455f171e8455ee37 | def test_get_state_at_time(self) -> None:
'\n Tests the get state at time method\n '
scene_simple_trajectory = self.scene_simple_trajectory
result = scene_simple_trajectory.get_state_at_time(TimePoint(int(1000000.0)))
self.assertEqual(result.x, 1)
self.assertEqual(result.y, 2) | Tests the get state at time method | nuplan/planning/utils/serialization/test/test_scene_simple_trajectory.py | test_get_state_at_time | motional/nuplan-devkit | 128 | python | def test_get_state_at_time(self) -> None:
'\n \n '
scene_simple_trajectory = self.scene_simple_trajectory
result = scene_simple_trajectory.get_state_at_time(TimePoint(int(1000000.0)))
self.assertEqual(result.x, 1)
self.assertEqual(result.y, 2) | def test_get_state_at_time(self) -> None:
'\n \n '
scene_simple_trajectory = self.scene_simple_trajectory
result = scene_simple_trajectory.get_state_at_time(TimePoint(int(1000000.0)))
self.assertEqual(result.x, 1)
self.assertEqual(result.y, 2)<|docstring|>Tests the get state at time method<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.