nwo stringlengths 5 106 | sha stringlengths 40 40 | path stringlengths 4 174 | language stringclasses 1
value | identifier stringlengths 1 140 | parameters stringlengths 0 87.7k | argument_list stringclasses 1
value | return_statement stringlengths 0 426k | docstring stringlengths 0 64.3k | docstring_summary stringlengths 0 26.3k | docstring_tokens list | function stringlengths 18 4.83M | function_tokens list | url stringlengths 83 304 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/lib/python2.7/site-packages/sqlalchemy/orm/collections.py | python | _locate_roles_and_methods | (cls) | return roles, methods | search for _sa_instrument_role-decorated methods in
method resolution order, assign to roles. | search for _sa_instrument_role-decorated methods in
method resolution order, assign to roles. | [
"search",
"for",
"_sa_instrument_role",
"-",
"decorated",
"methods",
"in",
"method",
"resolution",
"order",
"assign",
"to",
"roles",
"."
] | def _locate_roles_and_methods(cls):
"""search for _sa_instrument_role-decorated methods in
method resolution order, assign to roles.
"""
roles = {}
methods = {}
for supercls in cls.__mro__:
for name, method in vars(supercls).items():
if not util.callable(method):
continue
# note role declarations
if hasattr(method, '_sa_instrument_role'):
role = method._sa_instrument_role
assert role in ('appender', 'remover', 'iterator',
'linker', 'converter')
roles.setdefault(role, name)
# transfer instrumentation requests from decorated function
# to the combined queue
before, after = None, None
if hasattr(method, '_sa_instrument_before'):
op, argument = method._sa_instrument_before
assert op in ('fire_append_event', 'fire_remove_event')
before = op, argument
if hasattr(method, '_sa_instrument_after'):
op = method._sa_instrument_after
assert op in ('fire_append_event', 'fire_remove_event')
after = op
if before:
methods[name] = before + (after, )
elif after:
methods[name] = None, None, after
return roles, methods | [
"def",
"_locate_roles_and_methods",
"(",
"cls",
")",
":",
"roles",
"=",
"{",
"}",
"methods",
"=",
"{",
"}",
"for",
"supercls",
"in",
"cls",
".",
"__mro__",
":",
"for",
"name",
",",
"method",
"in",
"vars",
"(",
"supercls",
")",
".",
"items",
"(",
")",... | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/sqlalchemy/orm/collections.py#L845-L881 | |
plotly/plotly.py | cfad7862594b35965c0e000813bd7805e8494a5b | packages/python/plotly/plotly/graph_objs/histogram/marker/_colorbar.py | python | ColorBar.x | (self) | return self["x"] | Sets the x position of the color bar (in plot fraction).
Defaults to 1.02 when `orientation` is "v" and 0.5 when
`orientation` is "h".
The 'x' property is a number and may be specified as:
- An int or float in the interval [-2, 3]
Returns
-------
int|float | Sets the x position of the color bar (in plot fraction).
Defaults to 1.02 when `orientation` is "v" and 0.5 when
`orientation` is "h".
The 'x' property is a number and may be specified as:
- An int or float in the interval [-2, 3] | [
"Sets",
"the",
"x",
"position",
"of",
"the",
"color",
"bar",
"(",
"in",
"plot",
"fraction",
")",
".",
"Defaults",
"to",
"1",
".",
"02",
"when",
"orientation",
"is",
"v",
"and",
"0",
".",
"5",
"when",
"orientation",
"is",
"h",
".",
"The",
"x",
"prop... | def x(self):
"""
Sets the x position of the color bar (in plot fraction).
Defaults to 1.02 when `orientation` is "v" and 0.5 when
`orientation` is "h".
The 'x' property is a number and may be specified as:
- An int or float in the interval [-2, 3]
Returns
-------
int|float
"""
return self["x"] | [
"def",
"x",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"x\"",
"]"
] | https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/histogram/marker/_colorbar.py#L1259-L1272 | |
openshift/openshift-tools | 1188778e728a6e4781acf728123e5b356380fe6f | openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_vendored_deps/library/oc_clusterrole.py | python | OpenShiftCLI._run | (self, cmds, input_data) | return proc.returncode, stdout.decode('utf-8'), stderr.decode('utf-8') | Actually executes the command. This makes mocking easier. | Actually executes the command. This makes mocking easier. | [
"Actually",
"executes",
"the",
"command",
".",
"This",
"makes",
"mocking",
"easier",
"."
] | def _run(self, cmds, input_data):
''' Actually executes the command. This makes mocking easier. '''
curr_env = os.environ.copy()
curr_env.update({'KUBECONFIG': self.kubeconfig})
proc = subprocess.Popen(cmds,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=curr_env)
stdout, stderr = proc.communicate(input_data)
return proc.returncode, stdout.decode('utf-8'), stderr.decode('utf-8') | [
"def",
"_run",
"(",
"self",
",",
"cmds",
",",
"input_data",
")",
":",
"curr_env",
"=",
"os",
".",
"environ",
".",
"copy",
"(",
")",
"curr_env",
".",
"update",
"(",
"{",
"'KUBECONFIG'",
":",
"self",
".",
"kubeconfig",
"}",
")",
"proc",
"=",
"subproces... | https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_vendored_deps/library/oc_clusterrole.py#L1088-L1100 | |
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/Python-2.7.9/Mac/Demo/mlte/mlted.py | python | MlteWindow.can_undo | (self) | return "Undo "+which | [] | def can_undo(self):
can, which = self.ted.TXNCanUndo()
if not can:
return None
if which >= len(UNDOLABELS):
# Unspecified undo
return "Undo"
which = UNDOLABELS[which]
return "Undo "+which | [
"def",
"can_undo",
"(",
"self",
")",
":",
"can",
",",
"which",
"=",
"self",
".",
"ted",
".",
"TXNCanUndo",
"(",
")",
"if",
"not",
"can",
":",
"return",
"None",
"if",
"which",
">=",
"len",
"(",
"UNDOLABELS",
")",
":",
"# Unspecified undo",
"return",
"... | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Mac/Demo/mlte/mlted.py#L149-L158 | |||
JasperSnoek/spearmint | b37a541be1ea035f82c7c82bbd93f5b4320e7d91 | spearmint/spearmint/chooser/cma.py | python | FitnessFunctions.cornerellirot | (self, x) | return self.ellirot(x) | [] | def cornerellirot(self, x):
""" """
if any(x < 1):
return np.NaN
return self.ellirot(x) | [
"def",
"cornerellirot",
"(",
"self",
",",
"x",
")",
":",
"if",
"any",
"(",
"x",
"<",
"1",
")",
":",
"return",
"np",
".",
"NaN",
"return",
"self",
".",
"ellirot",
"(",
"x",
")"
] | https://github.com/JasperSnoek/spearmint/blob/b37a541be1ea035f82c7c82bbd93f5b4320e7d91/spearmint/spearmint/chooser/cma.py#L6527-L6531 | |||
django-nonrel/django-nonrel | 4fbfe7344481a5eab8698f79207f09124310131b | django/views/generic/dates.py | python | DayMixin.get_day_format | (self) | return self.day_format | Get a day format string in strptime syntax to be used to parse the day
from url variables. | Get a day format string in strptime syntax to be used to parse the day
from url variables. | [
"Get",
"a",
"day",
"format",
"string",
"in",
"strptime",
"syntax",
"to",
"be",
"used",
"to",
"parse",
"the",
"day",
"from",
"url",
"variables",
"."
] | def get_day_format(self):
"""
Get a day format string in strptime syntax to be used to parse the day
from url variables.
"""
return self.day_format | [
"def",
"get_day_format",
"(",
"self",
")",
":",
"return",
"self",
".",
"day_format"
] | https://github.com/django-nonrel/django-nonrel/blob/4fbfe7344481a5eab8698f79207f09124310131b/django/views/generic/dates.py#L82-L87 | |
tp4a/teleport | 1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad | server/www/packages/packages-linux/x64/ldap3/utils/ciDict.py | python | CaseInsensitiveWithAliasDict.set_alias | (self, key, alias, ignore_duplicates=False) | [] | def set_alias(self, key, alias, ignore_duplicates=False):
if not isinstance(alias, SEQUENCE_TYPES):
alias = [alias]
for alias_to_add in alias:
ci_key = self._ci_key(key)
if ci_key in self._case_insensitive_keymap:
ci_alias = self._ci_key(alias_to_add)
if ci_alias not in self._case_insensitive_keymap: # checks if alias is used a key
if ci_alias not in self._aliases: # checks if alias is used as another alias
self._aliases[ci_alias] = ci_key
if ci_key in self._alias_keymap: # extends alias keymap
self._alias_keymap[ci_key].append(self._ci_key(ci_alias))
else:
self._alias_keymap[ci_key] = list()
self._alias_keymap[ci_key].append(self._ci_key(ci_alias))
else:
if ci_key in self._alias_keymap and ci_alias in self._alias_keymap[ci_key]: # passes if alias is already defined to the same key
pass
elif not ignore_duplicates:
raise KeyError('\'' + str(alias_to_add) + '\' already used as alias')
else:
if ci_key == self._ci_key(self._case_insensitive_keymap[ci_alias]): # passes if alias is already defined to the same key
pass
elif not ignore_duplicates:
raise KeyError('\'' + str(alias_to_add) + '\' already used as key')
else:
for keymap in self._alias_keymap:
if ci_key in self._alias_keymap[keymap]: # kye is already aliased
self.set_alias(keymap, alias + [ci_key], ignore_duplicates=ignore_duplicates)
break
else:
raise KeyError('\'' + str(ci_key) + '\' is not an existing alias or key') | [
"def",
"set_alias",
"(",
"self",
",",
"key",
",",
"alias",
",",
"ignore_duplicates",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"alias",
",",
"SEQUENCE_TYPES",
")",
":",
"alias",
"=",
"[",
"alias",
"]",
"for",
"alias_to_add",
"in",
"alias",
... | https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-linux/x64/ldap3/utils/ciDict.py#L146-L177 | ||||
triaquae/triaquae | bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9 | TriAquae/models/Ubuntu_13/pyasn1/codec/ber/decoder.py | python | AbstractConstructedDecoder._createComponent | (self, asn1Spec, tagSet, value=None) | [] | def _createComponent(self, asn1Spec, tagSet, value=None):
if tagSet[0][1] not in self.tagFormats:
raise error.PyAsn1Error('Invalid tag format %r for %r' % (tagSet[0], self.protoComponent,))
if asn1Spec is None:
return self.protoComponent.clone(tagSet)
else:
return asn1Spec.clone() | [
"def",
"_createComponent",
"(",
"self",
",",
"asn1Spec",
",",
"tagSet",
",",
"value",
"=",
"None",
")",
":",
"if",
"tagSet",
"[",
"0",
"]",
"[",
"1",
"]",
"not",
"in",
"self",
".",
"tagFormats",
":",
"raise",
"error",
".",
"PyAsn1Error",
"(",
"'Inval... | https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/Ubuntu_13/pyasn1/codec/ber/decoder.py#L31-L37 | ||||
jerryli27/TwinGAN | 4e5593445778dfb77af9f815b3f4fcafc35758dc | preprocessing/inception_preprocessing.py | python | preprocess_for_train | (image, height, width, bbox,
fast_mode=True,
scope=None,
add_image_summaries=True) | Distort one image for training a network.
Distorting images provides a useful technique for augmenting the data
set during training in order to make the network invariant to aspects
of the image that do not effect the label.
Additionally it would create image_summaries to display the different
transformations applied to the image.
Args:
image: 3-D Tensor of image. If dtype is tf.float32 then the range should be
[0, 1], otherwise it would converted to tf.float32 assuming that the range
is [0, MAX], where MAX is largest positive representable number for
int(8/16/32) data type (see `tf.image.convert_image_dtype` for details).
height: integer
width: integer
bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords]
where each coordinate is [0, 1) and the coordinates are arranged
as [ymin, xmin, ymax, xmax].
fast_mode: Optional boolean, if True avoids slower transformations (i.e.
bi-cubic resizing, random_hue or random_contrast).
scope: Optional scope for name_scope.
add_image_summaries: Enable image summaries.
Returns:
3-D float Tensor of distorted image used for training with range [-1, 1]. | Distort one image for training a network. | [
"Distort",
"one",
"image",
"for",
"training",
"a",
"network",
"."
] | def preprocess_for_train(image, height, width, bbox,
fast_mode=True,
scope=None,
add_image_summaries=True):
"""Distort one image for training a network.
Distorting images provides a useful technique for augmenting the data
set during training in order to make the network invariant to aspects
of the image that do not effect the label.
Additionally it would create image_summaries to display the different
transformations applied to the image.
Args:
image: 3-D Tensor of image. If dtype is tf.float32 then the range should be
[0, 1], otherwise it would converted to tf.float32 assuming that the range
is [0, MAX], where MAX is largest positive representable number for
int(8/16/32) data type (see `tf.image.convert_image_dtype` for details).
height: integer
width: integer
bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords]
where each coordinate is [0, 1) and the coordinates are arranged
as [ymin, xmin, ymax, xmax].
fast_mode: Optional boolean, if True avoids slower transformations (i.e.
bi-cubic resizing, random_hue or random_contrast).
scope: Optional scope for name_scope.
add_image_summaries: Enable image summaries.
Returns:
3-D float Tensor of distorted image used for training with range [-1, 1].
"""
with tf.name_scope(scope, 'distort_image', [image, height, width, bbox]):
if bbox is None:
bbox = tf.constant([0.0, 0.0, 1.0, 1.0],
dtype=tf.float32,
shape=[1, 1, 4])
if image.dtype != tf.float32:
image = tf.image.convert_image_dtype(image, dtype=tf.float32)
# Each bounding box has shape [1, num_boxes, box coords] and
# the coordinates are ordered [ymin, xmin, ymax, xmax].
image_with_box = tf.image.draw_bounding_boxes(tf.expand_dims(image, 0),
bbox)
if add_image_summaries:
tf.summary.image('image_with_bounding_boxes', image_with_box)
distorted_image, distorted_bbox = distorted_bounding_box_crop(image, bbox)
# Restore the shape since the dynamic slice based upon the bbox_size loses
# the third dimension.
distorted_image.set_shape([None, None, 3])
image_with_distorted_box = tf.image.draw_bounding_boxes(
tf.expand_dims(image, 0), distorted_bbox)
if add_image_summaries:
tf.summary.image('images_with_distorted_bounding_box',
image_with_distorted_box)
# This resizing operation may distort the images because the aspect
# ratio is not respected. We select a resize method in a round robin
# fashion based on the thread number.
# Note that ResizeMethod contains 4 enumerated resizing methods.
# We select only 1 case for fast_mode bilinear.
num_resize_cases = 1 if fast_mode else 4
distorted_image = apply_with_random_selector(
distorted_image,
lambda x, method: tf.image.resize_images(x, [height, width], method),
num_cases=num_resize_cases)
if add_image_summaries:
tf.summary.image('cropped_resized_image',
tf.expand_dims(distorted_image, 0))
# Randomly flip the image horizontally.
distorted_image = tf.image.random_flip_left_right(distorted_image)
# Randomly distort the colors. There are 4 ways to do it.
distorted_image = apply_with_random_selector(
distorted_image,
lambda x, ordering: distort_color(x, ordering, fast_mode),
num_cases=4)
if add_image_summaries:
tf.summary.image('final_distorted_image',
tf.expand_dims(distorted_image, 0))
distorted_image = tf.subtract(distorted_image, 0.5)
distorted_image = tf.multiply(distorted_image, 2.0)
return distorted_image | [
"def",
"preprocess_for_train",
"(",
"image",
",",
"height",
",",
"width",
",",
"bbox",
",",
"fast_mode",
"=",
"True",
",",
"scope",
"=",
"None",
",",
"add_image_summaries",
"=",
"True",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"scope",
",",
"'dist... | https://github.com/jerryli27/TwinGAN/blob/4e5593445778dfb77af9f815b3f4fcafc35758dc/preprocessing/inception_preprocessing.py#L156-L240 | ||
modin-project/modin | 0d9d14e6669be3dd6bb3b72222dbe6a6dffe1bee | modin/core/dataframe/algebra/default2pandas/str.py | python | StrDefault.frame_wrapper | (cls, df) | return df.squeeze(axis=1).str | Get `str` accessor of the passed frame.
Parameters
----------
df : pandas.DataFrame
Returns
-------
pandas.core.strings.accessor.StringMethods | Get `str` accessor of the passed frame. | [
"Get",
"str",
"accessor",
"of",
"the",
"passed",
"frame",
"."
] | def frame_wrapper(cls, df):
"""
Get `str` accessor of the passed frame.
Parameters
----------
df : pandas.DataFrame
Returns
-------
pandas.core.strings.accessor.StringMethods
"""
return df.squeeze(axis=1).str | [
"def",
"frame_wrapper",
"(",
"cls",
",",
"df",
")",
":",
"return",
"df",
".",
"squeeze",
"(",
"axis",
"=",
"1",
")",
".",
"str"
] | https://github.com/modin-project/modin/blob/0d9d14e6669be3dd6bb3b72222dbe6a6dffe1bee/modin/core/dataframe/algebra/default2pandas/str.py#L23-L35 | |
JacquesLucke/animation_nodes | b1e3ace8dcb0a771fd882fc3ac4e490b009fa0d1 | animation_nodes/nodes/mesh/mesh_points_scatter.py | python | MeshPointsScatterNode.create | (self) | [] | def create(self):
self.newInput("Mesh", "Mesh", "mesh")
self.newInput("Integer", "Seed", "seed", minValue = 0)
self.newInput("Integer", "Amount", "amount", value = 10, minValue = 0)
self.newInput("Float List", "Weights", "weights", hide = True)
self.newOutput("Matrix List", "Matrices", "matrices")
self.newOutput("Vector List", "Vectors", "vectors")
self.newOutput("Vector List", "Normals", "normals", hide = True) | [
"def",
"create",
"(",
"self",
")",
":",
"self",
".",
"newInput",
"(",
"\"Mesh\"",
",",
"\"Mesh\"",
",",
"\"mesh\"",
")",
"self",
".",
"newInput",
"(",
"\"Integer\"",
",",
"\"Seed\"",
",",
"\"seed\"",
",",
"minValue",
"=",
"0",
")",
"self",
".",
"newInp... | https://github.com/JacquesLucke/animation_nodes/blob/b1e3ace8dcb0a771fd882fc3ac4e490b009fa0d1/animation_nodes/nodes/mesh/mesh_points_scatter.py#L35-L43 | ||||
nodesign/weio | 1d67d705a5c36a2e825ad13feab910b0aca9a2e8 | handlers/dashboardHandler.py | python | WeioDashBoardHandler.sendUserData | (self,rq) | [] | def sendUserData(self,rq):
data = {}
# get configuration from file
config = weioConfig.getConfiguration()
data['requested'] = rq['request']
data['name'] = config["user"]
self.broadcast(clients, json.dumps(data)) | [
"def",
"sendUserData",
"(",
"self",
",",
"rq",
")",
":",
"data",
"=",
"{",
"}",
"# get configuration from file",
"config",
"=",
"weioConfig",
".",
"getConfiguration",
"(",
")",
"data",
"[",
"'requested'",
"]",
"=",
"rq",
"[",
"'request'",
"]",
"data",
"[",... | https://github.com/nodesign/weio/blob/1d67d705a5c36a2e825ad13feab910b0aca9a2e8/handlers/dashboardHandler.py#L244-L251 | ||||
vmware/vcd-cli | 648dced8c2f6b14493b69b7c3f67344a1b5dbcc5 | vcd_cli/vcd.py | python | vcd | (ctx, debug, json_output, no_wait, is_colorized) | VMware vCloud Director Command Line Interface.
\b
Environment Variables
VCD_USE_COLORED_OUTPUT
If this environment variable is set, and it's value is not '0',
the command vcd info will print the output in color. The effect
of the environment variable will be overridden by the param
--colorized/--no-colorized. | VMware vCloud Director Command Line Interface. | [
"VMware",
"vCloud",
"Director",
"Command",
"Line",
"Interface",
"."
] | def vcd(ctx, debug, json_output, no_wait, is_colorized):
"""VMware vCloud Director Command Line Interface.
\b
Environment Variables
VCD_USE_COLORED_OUTPUT
If this environment variable is set, and it's value is not '0',
the command vcd info will print the output in color. The effect
of the environment variable will be overridden by the param
--colorized/--no-colorized.
"""
if ctx.invoked_subcommand is None:
click.secho(ctx.get_help())
return | [
"def",
"vcd",
"(",
"ctx",
",",
"debug",
",",
"json_output",
",",
"no_wait",
",",
"is_colorized",
")",
":",
"if",
"ctx",
".",
"invoked_subcommand",
"is",
"None",
":",
"click",
".",
"secho",
"(",
"ctx",
".",
"get_help",
"(",
")",
")",
"return"
] | https://github.com/vmware/vcd-cli/blob/648dced8c2f6b14493b69b7c3f67344a1b5dbcc5/vcd_cli/vcd.py#L55-L68 | ||
eventable/vobject | 498555a553155ea9b26aace93332ae79365ecb31 | vobject/icalendar.py | python | VCalendar2_0.generateImplicitParameters | (cls, obj) | Create PRODID, VERSION and VTIMEZONEs if needed.
VTIMEZONEs will need to exist whenever TZID parameters exist or when
datetimes with tzinfo exist. | Create PRODID, VERSION and VTIMEZONEs if needed. | [
"Create",
"PRODID",
"VERSION",
"and",
"VTIMEZONEs",
"if",
"needed",
"."
] | def generateImplicitParameters(cls, obj):
"""
Create PRODID, VERSION and VTIMEZONEs if needed.
VTIMEZONEs will need to exist whenever TZID parameters exist or when
datetimes with tzinfo exist.
"""
for comp in obj.components():
if comp.behavior is not None:
comp.behavior.generateImplicitParameters(comp)
if not hasattr(obj, 'prodid'):
obj.add(ContentLine('PRODID', [], PRODID))
if not hasattr(obj, 'version'):
obj.add(ContentLine('VERSION', [], cls.versionString))
tzidsUsed = {}
def findTzids(obj, table):
if isinstance(obj, ContentLine) and (obj.behavior is None or
not obj.behavior.forceUTC):
if getattr(obj, 'tzid_param', None):
table[obj.tzid_param] = 1
else:
if type(obj.value) == list:
for item in obj.value:
tzinfo = getattr(obj.value, 'tzinfo', None)
tzid = TimezoneComponent.registerTzinfo(tzinfo)
if tzid:
table[tzid] = 1
else:
tzinfo = getattr(obj.value, 'tzinfo', None)
tzid = TimezoneComponent.registerTzinfo(tzinfo)
if tzid:
table[tzid] = 1
for child in obj.getChildren():
if obj.name != 'VTIMEZONE':
findTzids(child, table)
findTzids(obj, tzidsUsed)
oldtzids = [toUnicode(x.tzid.value) for x in getattr(obj, 'vtimezone_list', [])]
for tzid in tzidsUsed.keys():
tzid = toUnicode(tzid)
if tzid != u'UTC' and tzid not in oldtzids:
obj.add(TimezoneComponent(tzinfo=getTzid(tzid))) | [
"def",
"generateImplicitParameters",
"(",
"cls",
",",
"obj",
")",
":",
"for",
"comp",
"in",
"obj",
".",
"components",
"(",
")",
":",
"if",
"comp",
".",
"behavior",
"is",
"not",
"None",
":",
"comp",
".",
"behavior",
".",
"generateImplicitParameters",
"(",
... | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/icalendar.py#L943-L985 | ||
biolab/orange3 | 41685e1c7b1d1babe680113685a2d44bcc9fec0b | Orange/preprocess/normalize.py | python | Normalizer.__call__ | (self, data) | return data.transform(domain) | [] | def __call__(self, data):
dists = distribution.get_distributions(data)
new_attrs = [self.normalize(dists[i], var) for
(i, var) in enumerate(data.domain.attributes)]
new_class_vars = data.domain.class_vars
if self.transform_class:
attr_len = len(data.domain.attributes)
new_class_vars = [self.normalize(dists[i + attr_len], var) for
(i, var) in enumerate(data.domain.class_vars)]
domain = Domain(new_attrs, new_class_vars, data.domain.metas)
return data.transform(domain) | [
"def",
"__call__",
"(",
"self",
",",
"data",
")",
":",
"dists",
"=",
"distribution",
".",
"get_distributions",
"(",
"data",
")",
"new_attrs",
"=",
"[",
"self",
".",
"normalize",
"(",
"dists",
"[",
"i",
"]",
",",
"var",
")",
"for",
"(",
"i",
",",
"v... | https://github.com/biolab/orange3/blob/41685e1c7b1d1babe680113685a2d44bcc9fec0b/Orange/preprocess/normalize.py#L24-L36 | |||
wwqgtxx/wwqLyParse | 33136508e52821babd9294fdecffbdf02d73a6fc | wwqLyParse/lib/python-3.7.2-embed-win32/gevent/_sslgte279.py | python | _create_unverified_context | (protocol=PROTOCOL_SSLv23, cert_reqs=None,
check_hostname=False, purpose=Purpose.SERVER_AUTH,
certfile=None, keyfile=None,
cafile=None, capath=None, cadata=None) | return context | Create a SSLContext object for Python stdlib modules
All Python stdlib modules shall use this function to create SSLContext
objects in order to keep common settings in one place. The configuration
is less restrict than create_default_context()'s to increase backward
compatibility. | Create a SSLContext object for Python stdlib modules | [
"Create",
"a",
"SSLContext",
"object",
"for",
"Python",
"stdlib",
"modules"
] | def _create_unverified_context(protocol=PROTOCOL_SSLv23, cert_reqs=None,
check_hostname=False, purpose=Purpose.SERVER_AUTH,
certfile=None, keyfile=None,
cafile=None, capath=None, cadata=None):
"""Create a SSLContext object for Python stdlib modules
All Python stdlib modules shall use this function to create SSLContext
objects in order to keep common settings in one place. The configuration
is less restrict than create_default_context()'s to increase backward
compatibility.
"""
if not isinstance(purpose, _ASN1Object):
raise TypeError(purpose)
context = SSLContext(protocol)
# SSLv2 considered harmful.
context.options |= OP_NO_SSLv2
# SSLv3 has problematic security and is only required for really old
# clients such as IE6 on Windows XP
context.options |= OP_NO_SSLv3
if cert_reqs is not None:
context.verify_mode = cert_reqs
context.check_hostname = check_hostname # pylint: disable=attribute-defined-outside-init
if keyfile and not certfile:
raise ValueError("certfile must be specified")
if certfile or keyfile:
context.load_cert_chain(certfile, keyfile)
# load CA root certs
if cafile or capath or cadata:
context.load_verify_locations(cafile, capath, cadata)
elif context.verify_mode != CERT_NONE:
# no explicit cafile, capath or cadata but the verify mode is
# CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
# root CA certificates for the given purpose. This may fail silently.
context.load_default_certs(purpose)
return context | [
"def",
"_create_unverified_context",
"(",
"protocol",
"=",
"PROTOCOL_SSLv23",
",",
"cert_reqs",
"=",
"None",
",",
"check_hostname",
"=",
"False",
",",
"purpose",
"=",
"Purpose",
".",
"SERVER_AUTH",
",",
"certfile",
"=",
"None",
",",
"keyfile",
"=",
"None",
","... | https://github.com/wwqgtxx/wwqLyParse/blob/33136508e52821babd9294fdecffbdf02d73a6fc/wwqLyParse/lib/python-3.7.2-embed-win32/gevent/_sslgte279.py#L119-L158 | |
khanhnamle1994/natural-language-processing | 01d450d5ac002b0156ef4cf93a07cb508c1bcdc5 | assignment1/.env/lib/python2.7/site-packages/scipy/stats/_multivariate.py | python | _process_quantiles | (x, dim) | return x | Adjust quantiles array so that last axis labels the components of
each data point. | Adjust quantiles array so that last axis labels the components of
each data point. | [
"Adjust",
"quantiles",
"array",
"so",
"that",
"last",
"axis",
"labels",
"the",
"components",
"of",
"each",
"data",
"point",
"."
] | def _process_quantiles(x, dim):
"""
Adjust quantiles array so that last axis labels the components of
each data point.
"""
x = np.asarray(x, dtype=float)
if x.ndim == 0:
x = x[np.newaxis]
elif x.ndim == 1:
if dim == 1:
x = x[:, np.newaxis]
else:
x = x[np.newaxis, :]
return x | [
"def",
"_process_quantiles",
"(",
"x",
",",
"dim",
")",
":",
"x",
"=",
"np",
".",
"asarray",
"(",
"x",
",",
"dtype",
"=",
"float",
")",
"if",
"x",
".",
"ndim",
"==",
"0",
":",
"x",
"=",
"x",
"[",
"np",
".",
"newaxis",
"]",
"elif",
"x",
".",
... | https://github.com/khanhnamle1994/natural-language-processing/blob/01d450d5ac002b0156ef4cf93a07cb508c1bcdc5/assignment1/.env/lib/python2.7/site-packages/scipy/stats/_multivariate.py#L69-L85 | |
google/flax | 89e1126cc43588c6946bc85506987dc812909575 | flax/core/scope.py | python | Scope.child | (self,
fn: Callable[..., Any],
name: Optional[str] = None,
prefix: Optional[str] = None,
named_call: bool = True,
**partial_kwargs) | return wrapper | Partially applies a child scope to fn.
When calling the returned function multiple times variables will be reused.
Args:
fn: the function to partially apply the child Scope to.
name: optional name of the child.
prefix: prefix used for generating name if it is `None`.
named_call: if true, `fn` will be wrapped with `lift.named_call`. The XLA
profiler will use this to name tag the computation.
**partial_kwargs: additional kwargs partially applied to `fn`.
Returns:
The function with a partially applied scope. | Partially applies a child scope to fn. | [
"Partially",
"applies",
"a",
"child",
"scope",
"to",
"fn",
"."
] | def child(self,
fn: Callable[..., Any],
name: Optional[str] = None,
prefix: Optional[str] = None,
named_call: bool = True,
**partial_kwargs) -> Callable[..., Any]:
"""Partially applies a child scope to fn.
When calling the returned function multiple times variables will be reused.
Args:
fn: the function to partially apply the child Scope to.
name: optional name of the child.
prefix: prefix used for generating name if it is `None`.
named_call: if true, `fn` will be wrapped with `lift.named_call`. The XLA
profiler will use this to name tag the computation.
**partial_kwargs: additional kwargs partially applied to `fn`.
Returns:
The function with a partially applied scope.
"""
if name is None:
if prefix is None:
prefix = fn.__name__ + '_' if hasattr(fn, '__name__') else ''
name = self.default_name(prefix)
scope = self.push(name)
if named_call:
# We import named_call at runtime to avoid a circular import issue.
from . import lift # type: ignore
fn = lift.named_call(fn, name)
@functools.wraps(fn)
def wrapper(*args, **kwargs):
kwargs = dict(partial_kwargs, **kwargs)
return fn(scope.rewound(), *args, **kwargs)
return wrapper | [
"def",
"child",
"(",
"self",
",",
"fn",
":",
"Callable",
"[",
"...",
",",
"Any",
"]",
",",
"name",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"prefix",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"named_call",
":",
"bool",
"=",
... | https://github.com/google/flax/blob/89e1126cc43588c6946bc85506987dc812909575/flax/core/scope.py#L490-L526 | |
mchristopher/PokemonGo-DesktopMap | ec37575f2776ee7d64456e2a1f6b6b78830b4fe0 | app/pywin/Lib/ftplib.py | python | FTP.quit | (self) | return resp | Quit, and close the connection. | Quit, and close the connection. | [
"Quit",
"and",
"close",
"the",
"connection",
"."
] | def quit(self):
'''Quit, and close the connection.'''
resp = self.voidcmd('QUIT')
self.close()
return resp | [
"def",
"quit",
"(",
"self",
")",
":",
"resp",
"=",
"self",
".",
"voidcmd",
"(",
"'QUIT'",
")",
"self",
".",
"close",
"(",
")",
"return",
"resp"
] | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/ec37575f2776ee7d64456e2a1f6b6b78830b4fe0/app/pywin/Lib/ftplib.py#L589-L593 | |
openseg-group/OCNet.pytorch | 812cc57b560fe7fb3b3d9c80da5db80d1e83fbaa | utils/files.py | python | check_sha1 | (filename, sha1_hash) | return sha1.hexdigest() == sha1_hash | Check whether the sha1 hash of the file content matches the expected hash.
Parameters
----------
filename : str
Path to the file.
sha1_hash : str
Expected sha1 hash in hexadecimal digits.
Returns
-------
bool
Whether the file content matches the expected hash. | Check whether the sha1 hash of the file content matches the expected hash.
Parameters
----------
filename : str
Path to the file.
sha1_hash : str
Expected sha1 hash in hexadecimal digits.
Returns
-------
bool
Whether the file content matches the expected hash. | [
"Check",
"whether",
"the",
"sha1",
"hash",
"of",
"the",
"file",
"content",
"matches",
"the",
"expected",
"hash",
".",
"Parameters",
"----------",
"filename",
":",
"str",
"Path",
"to",
"the",
"file",
".",
"sha1_hash",
":",
"str",
"Expected",
"sha1",
"hash",
... | def check_sha1(filename, sha1_hash):
"""Check whether the sha1 hash of the file content matches the expected hash.
Parameters
----------
filename : str
Path to the file.
sha1_hash : str
Expected sha1 hash in hexadecimal digits.
Returns
-------
bool
Whether the file content matches the expected hash.
"""
sha1 = hashlib.sha1()
with open(filename, 'rb') as f:
while True:
data = f.read(1048576)
if not data:
break
sha1.update(data)
return sha1.hexdigest() == sha1_hash | [
"def",
"check_sha1",
"(",
"filename",
",",
"sha1_hash",
")",
":",
"sha1",
"=",
"hashlib",
".",
"sha1",
"(",
")",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"f",
":",
"while",
"True",
":",
"data",
"=",
"f",
".",
"read",
"(",
"1048576",... | https://github.com/openseg-group/OCNet.pytorch/blob/812cc57b560fe7fb3b3d9c80da5db80d1e83fbaa/utils/files.py#L81-L102 | |
EmilyAlsentzer/clinicalBERT | a9d91698929b7189311bba364ccdd0360e847276 | downstream_tasks/ner_eval/format_for_i2b2_eval.py | python | tok_concepts_to_labels | (tokenized_sents, tok_concepts) | return labels | for i in range(len(tokenized_sents)):
assert len(tokenized_sents[i]) == len(labels[i])
for tok,lab in zip(tokenized_sents[i],labels[i]):
if lab != 'O': print '\t',
print lab, tok
print
exit() | for i in range(len(tokenized_sents)):
assert len(tokenized_sents[i]) == len(labels[i])
for tok,lab in zip(tokenized_sents[i],labels[i]):
if lab != 'O': print '\t',
print lab, tok
print
exit() | [
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"tokenized_sents",
"))",
":",
"assert",
"len",
"(",
"tokenized_sents",
"[",
"i",
"]",
")",
"==",
"len",
"(",
"labels",
"[",
"i",
"]",
")",
"for",
"tok",
"lab",
"in",
"zip",
"(",
"tokenized_sents",
"[",
"i... | def tok_concepts_to_labels(tokenized_sents, tok_concepts):
# parallel to tokens
labels = [ ['O' for tok in sent] for sent in tokenized_sents ]
# fill each concept's tokens appropriately
for concept in tok_concepts:
label,lineno,start_tok,end_tok = concept
labels[lineno-1][start_tok] = 'B-%s' % label
for i in range(start_tok+1,end_tok+1):
labels[lineno-1][i] = 'I-%s' % label
# test it out
'''
for i in range(len(tokenized_sents)):
assert len(tokenized_sents[i]) == len(labels[i])
for tok,lab in zip(tokenized_sents[i],labels[i]):
if lab != 'O': print '\t',
print lab, tok
print
exit()
'''
return labels | [
"def",
"tok_concepts_to_labels",
"(",
"tokenized_sents",
",",
"tok_concepts",
")",
":",
"# parallel to tokens",
"labels",
"=",
"[",
"[",
"'O'",
"for",
"tok",
"in",
"sent",
"]",
"for",
"sent",
"in",
"tokenized_sents",
"]",
"# fill each concept's tokens appropriately",
... | https://github.com/EmilyAlsentzer/clinicalBERT/blob/a9d91698929b7189311bba364ccdd0360e847276/downstream_tasks/ner_eval/format_for_i2b2_eval.py#L183-L205 | |
statsmodels/statsmodels | debbe7ea6ba28fe5bdb78f09f8cac694bef98722 | statsmodels/multivariate/factor.py | python | FactorResults.plot_loadings | (self, loading_pairs=None, plot_prerotated=False) | return plot_loadings(loadings, loading_pairs=loading_pairs,
title=title, row_names=self.endog_names,
percent_variance=var_explained) | Plot factor loadings in 2-d plots
Parameters
----------
loading_pairs : None or a list of tuples
Specify plots. Each tuple (i, j) represent one figure, i and j is
the loading number for x-axis and y-axis, respectively. If `None`,
all combinations of the loadings will be plotted.
plot_prerotated : True or False
If True, the loadings before rotation applied will be plotted. If
False, rotated loadings will be plotted.
Returns
-------
figs : a list of figure handles | Plot factor loadings in 2-d plots | [
"Plot",
"factor",
"loadings",
"in",
"2",
"-",
"d",
"plots"
] | def plot_loadings(self, loading_pairs=None, plot_prerotated=False):
"""
Plot factor loadings in 2-d plots
Parameters
----------
loading_pairs : None or a list of tuples
Specify plots. Each tuple (i, j) represent one figure, i and j is
the loading number for x-axis and y-axis, respectively. If `None`,
all combinations of the loadings will be plotted.
plot_prerotated : True or False
If True, the loadings before rotation applied will be plotted. If
False, rotated loadings will be plotted.
Returns
-------
figs : a list of figure handles
"""
_import_mpl()
from .plots import plot_loadings
if self.rotation_method is None:
plot_prerotated = True
loadings = self.loadings_no_rot if plot_prerotated else self.loadings
if plot_prerotated:
title = 'Prerotated Factor Pattern'
else:
title = '%s Rotated Factor Pattern' % (self.rotation_method)
var_explained = self.eigenvals / self.n_comp * 100
return plot_loadings(loadings, loading_pairs=loading_pairs,
title=title, row_names=self.endog_names,
percent_variance=var_explained) | [
"def",
"plot_loadings",
"(",
"self",
",",
"loading_pairs",
"=",
"None",
",",
"plot_prerotated",
"=",
"False",
")",
":",
"_import_mpl",
"(",
")",
"from",
".",
"plots",
"import",
"plot_loadings",
"if",
"self",
".",
"rotation_method",
"is",
"None",
":",
"plot_p... | https://github.com/statsmodels/statsmodels/blob/debbe7ea6ba28fe5bdb78f09f8cac694bef98722/statsmodels/multivariate/factor.py#L932-L964 | |
oracle/graalpython | 577e02da9755d916056184ec441c26e00b70145c | graalpython/lib-python/3/idlelib/macosx.py | python | hideTkConsole | (root) | [] | def hideTkConsole(root):
try:
root.tk.call('console', 'hide')
except tkinter.TclError:
# Some versions of the Tk framework don't have a console object
pass | [
"def",
"hideTkConsole",
"(",
"root",
")",
":",
"try",
":",
"root",
".",
"tk",
".",
"call",
"(",
"'console'",
",",
"'hide'",
")",
"except",
"tkinter",
".",
"TclError",
":",
"# Some versions of the Tk framework don't have a console object",
"pass"
] | https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/idlelib/macosx.py#L141-L146 | ||||
pypa/pip | 7f8a6844037fb7255cfd0d34ff8e8cf44f2598d4 | src/pip/_vendor/rich/console.py | python | Console.print | (
self,
*objects: Any,
sep: str = " ",
end: str = "\n",
style: Optional[Union[str, Style]] = None,
justify: Optional[JustifyMethod] = None,
overflow: Optional[OverflowMethod] = None,
no_wrap: Optional[bool] = None,
emoji: Optional[bool] = None,
markup: Optional[bool] = None,
highlight: Optional[bool] = None,
width: Optional[int] = None,
height: Optional[int] = None,
crop: bool = True,
soft_wrap: Optional[bool] = None,
new_line_start: bool = False,
) | Print to the console.
Args:
objects (positional args): Objects to log to the terminal.
sep (str, optional): String to write between print data. Defaults to " ".
end (str, optional): String to write at end of print data. Defaults to "\\\\n".
style (Union[str, Style], optional): A style to apply to output. Defaults to None.
justify (str, optional): Justify method: "default", "left", "right", "center", or "full". Defaults to ``None``.
overflow (str, optional): Overflow method: "ignore", "crop", "fold", or "ellipsis". Defaults to None.
no_wrap (Optional[bool], optional): Disable word wrapping. Defaults to None.
emoji (Optional[bool], optional): Enable emoji code, or ``None`` to use console default. Defaults to ``None``.
markup (Optional[bool], optional): Enable markup, or ``None`` to use console default. Defaults to ``None``.
highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use console default. Defaults to ``None``.
width (Optional[int], optional): Width of output, or ``None`` to auto-detect. Defaults to ``None``.
crop (Optional[bool], optional): Crop output to width of terminal. Defaults to True.
soft_wrap (bool, optional): Enable soft wrap mode which disables word wrapping and cropping of text or ``None`` for
Console default. Defaults to ``None``.
new_line_start (bool, False): Insert a new line at the start if the output contains more than one line. Defaults to ``False``. | Print to the console. | [
"Print",
"to",
"the",
"console",
"."
] | def print(
self,
*objects: Any,
sep: str = " ",
end: str = "\n",
style: Optional[Union[str, Style]] = None,
justify: Optional[JustifyMethod] = None,
overflow: Optional[OverflowMethod] = None,
no_wrap: Optional[bool] = None,
emoji: Optional[bool] = None,
markup: Optional[bool] = None,
highlight: Optional[bool] = None,
width: Optional[int] = None,
height: Optional[int] = None,
crop: bool = True,
soft_wrap: Optional[bool] = None,
new_line_start: bool = False,
) -> None:
"""Print to the console.
Args:
objects (positional args): Objects to log to the terminal.
sep (str, optional): String to write between print data. Defaults to " ".
end (str, optional): String to write at end of print data. Defaults to "\\\\n".
style (Union[str, Style], optional): A style to apply to output. Defaults to None.
justify (str, optional): Justify method: "default", "left", "right", "center", or "full". Defaults to ``None``.
overflow (str, optional): Overflow method: "ignore", "crop", "fold", or "ellipsis". Defaults to None.
no_wrap (Optional[bool], optional): Disable word wrapping. Defaults to None.
emoji (Optional[bool], optional): Enable emoji code, or ``None`` to use console default. Defaults to ``None``.
markup (Optional[bool], optional): Enable markup, or ``None`` to use console default. Defaults to ``None``.
highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use console default. Defaults to ``None``.
width (Optional[int], optional): Width of output, or ``None`` to auto-detect. Defaults to ``None``.
crop (Optional[bool], optional): Crop output to width of terminal. Defaults to True.
soft_wrap (bool, optional): Enable soft wrap mode which disables word wrapping and cropping of text or ``None`` for
Console default. Defaults to ``None``.
new_line_start (bool, False): Insert a new line at the start if the output contains more than one line. Defaults to ``False``.
"""
if not objects:
objects = (NewLine(),)
if soft_wrap is None:
soft_wrap = self.soft_wrap
if soft_wrap:
if no_wrap is None:
no_wrap = True
if overflow is None:
overflow = "ignore"
crop = False
with self:
renderables = self._collect_renderables(
objects,
sep,
end,
justify=justify,
emoji=emoji,
markup=markup,
highlight=highlight,
)
for hook in self._render_hooks:
renderables = hook.process_renderables(renderables)
render_options = self.options.update(
justify=justify,
overflow=overflow,
width=min(width, self.width) if width is not None else NO_CHANGE,
height=height,
no_wrap=no_wrap,
markup=markup,
highlight=highlight,
)
new_segments: List[Segment] = []
extend = new_segments.extend
render = self.render
if style is None:
for renderable in renderables:
extend(render(renderable, render_options))
else:
for renderable in renderables:
extend(
Segment.apply_style(
render(renderable, render_options), self.get_style(style)
)
)
if new_line_start:
if (
len("".join(segment.text for segment in new_segments).splitlines())
> 1
):
new_segments.insert(0, Segment.line())
if crop:
buffer_extend = self._buffer.extend
for line in Segment.split_and_crop_lines(
new_segments, self.width, pad=False
):
buffer_extend(line)
else:
self._buffer.extend(new_segments) | [
"def",
"print",
"(",
"self",
",",
"*",
"objects",
":",
"Any",
",",
"sep",
":",
"str",
"=",
"\" \"",
",",
"end",
":",
"str",
"=",
"\"\\n\"",
",",
"style",
":",
"Optional",
"[",
"Union",
"[",
"str",
",",
"Style",
"]",
"]",
"=",
"None",
",",
"just... | https://github.com/pypa/pip/blob/7f8a6844037fb7255cfd0d34ff8e8cf44f2598d4/src/pip/_vendor/rich/console.py#L1534-L1631 | ||
Tuxemon/Tuxemon | ee80708090525391c1dfc43849a6348aca636b22 | tuxemon/graphics.py | python | capture_screenshot | (game: LocalPygameClient) | return screenshot | Capture a screenshot of the current map.
Parameters:
game: The game object.
Returns:
The captured screenshot. | Capture a screenshot of the current map. | [
"Capture",
"a",
"screenshot",
"of",
"the",
"current",
"map",
"."
] | def capture_screenshot(game: LocalPygameClient) -> pygame.surface.Surface:
"""
Capture a screenshot of the current map.
Parameters:
game: The game object.
Returns:
The captured screenshot.
"""
from tuxemon.states.world.worldstate import WorldState
screenshot = pygame.Surface(game.screen.get_size())
world = game.get_state_by_name(WorldState)
world.draw(screenshot)
return screenshot | [
"def",
"capture_screenshot",
"(",
"game",
":",
"LocalPygameClient",
")",
"->",
"pygame",
".",
"surface",
".",
"Surface",
":",
"from",
"tuxemon",
".",
"states",
".",
"world",
".",
"worldstate",
"import",
"WorldState",
"screenshot",
"=",
"pygame",
".",
"Surface"... | https://github.com/Tuxemon/Tuxemon/blob/ee80708090525391c1dfc43849a6348aca636b22/tuxemon/graphics.py#L444-L460 | |
smart-mobile-software/gitstack | d9fee8f414f202143eb6e620529e8e5539a2af56 | python/Lib/sched.py | python | scheduler.enterabs | (self, time, priority, action, argument) | return event | Enter a new event in the queue at an absolute time.
Returns an ID for the event which can be used to remove it,
if necessary. | Enter a new event in the queue at an absolute time. | [
"Enter",
"a",
"new",
"event",
"in",
"the",
"queue",
"at",
"an",
"absolute",
"time",
"."
] | def enterabs(self, time, priority, action, argument):
"""Enter a new event in the queue at an absolute time.
Returns an ID for the event which can be used to remove it,
if necessary.
"""
event = Event(time, priority, action, argument)
heapq.heappush(self._queue, event)
return event | [
"def",
"enterabs",
"(",
"self",
",",
"time",
",",
"priority",
",",
"action",
",",
"argument",
")",
":",
"event",
"=",
"Event",
"(",
"time",
",",
"priority",
",",
"action",
",",
"argument",
")",
"heapq",
".",
"heappush",
"(",
"self",
".",
"_queue",
",... | https://github.com/smart-mobile-software/gitstack/blob/d9fee8f414f202143eb6e620529e8e5539a2af56/python/Lib/sched.py#L46-L55 | |
holzschu/Carnets | 44effb10ddfc6aa5c8b0687582a724ba82c6b547 | Library/lib/python3.7/site-packages/pip/_vendor/distlib/wheel.py | python | compatible_tags | () | return set(result) | Return (pyver, abi, arch) tuples compatible with this Python. | Return (pyver, abi, arch) tuples compatible with this Python. | [
"Return",
"(",
"pyver",
"abi",
"arch",
")",
"tuples",
"compatible",
"with",
"this",
"Python",
"."
] | def compatible_tags():
"""
Return (pyver, abi, arch) tuples compatible with this Python.
"""
versions = [VER_SUFFIX]
major = VER_SUFFIX[0]
for minor in range(sys.version_info[1] - 1, - 1, -1):
versions.append(''.join([major, str(minor)]))
abis = []
for suffix, _, _ in imp.get_suffixes():
if suffix.startswith('.abi'):
abis.append(suffix.split('.', 2)[1])
abis.sort()
if ABI != 'none':
abis.insert(0, ABI)
abis.append('none')
result = []
arches = [ARCH]
if sys.platform == 'darwin':
m = re.match(r'(\w+)_(\d+)_(\d+)_(\w+)$', ARCH)
if m:
name, major, minor, arch = m.groups()
minor = int(minor)
matches = [arch]
if arch in ('i386', 'ppc'):
matches.append('fat')
if arch in ('i386', 'ppc', 'x86_64'):
matches.append('fat3')
if arch in ('ppc64', 'x86_64'):
matches.append('fat64')
if arch in ('i386', 'x86_64'):
matches.append('intel')
if arch in ('i386', 'x86_64', 'intel', 'ppc', 'ppc64'):
matches.append('universal')
while minor >= 0:
for match in matches:
s = '%s_%s_%s_%s' % (name, major, minor, match)
if s != ARCH: # already there
arches.append(s)
minor -= 1
# Most specific - our Python version, ABI and arch
for abi in abis:
for arch in arches:
result.append((''.join((IMP_PREFIX, versions[0])), abi, arch))
# where no ABI / arch dependency, but IMP_PREFIX dependency
for i, version in enumerate(versions):
result.append((''.join((IMP_PREFIX, version)), 'none', 'any'))
if i == 0:
result.append((''.join((IMP_PREFIX, version[0])), 'none', 'any'))
# no IMP_PREFIX, ABI or arch dependency
for i, version in enumerate(versions):
result.append((''.join(('py', version)), 'none', 'any'))
if i == 0:
result.append((''.join(('py', version[0])), 'none', 'any'))
return set(result) | [
"def",
"compatible_tags",
"(",
")",
":",
"versions",
"=",
"[",
"VER_SUFFIX",
"]",
"major",
"=",
"VER_SUFFIX",
"[",
"0",
"]",
"for",
"minor",
"in",
"range",
"(",
"sys",
".",
"version_info",
"[",
"1",
"]",
"-",
"1",
",",
"-",
"1",
",",
"-",
"1",
")... | https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/pip/_vendor/distlib/wheel.py#L911-L970 | |
poppy-project/pypot | c5d384fe23eef9f6ec98467f6f76626cdf20afb9 | pypot/robot/robot.py | python | Robot.__repr__ | (self) | return '<Robot motors={}>'.format(self.motors) | [] | def __repr__(self):
return '<Robot motors={}>'.format(self.motors) | [
"def",
"__repr__",
"(",
"self",
")",
":",
"return",
"'<Robot motors={}>'",
".",
"format",
"(",
"self",
".",
"motors",
")"
] | https://github.com/poppy-project/pypot/blob/c5d384fe23eef9f6ec98467f6f76626cdf20afb9/pypot/robot/robot.py#L56-L57 | |||
uber-research/DeepPruner | 40b188cf954577e21d5068db2be2bedc6b0e8781 | DifferentiablePatchMatch/models/feature_extractor.py | python | feature_extractor.forward | (self, left_input, right_input) | return left_features, right_features, one_hot_filter | Feature Extractor
Description: Aggregates the RGB values from the neighbouring pixels in the window (filter_size * filter_size).
No weights are learnt for this feature extractor.
Args:
:param left_input: Left Image
:param right_input: Right Image
Returns:
:left_features: Left Image features
:right_features: Right Image features
:one_hot_filter: Convolution filter used to aggregate neighbour RGB features to the center pixel.
one_hot_filter.shape = (filter_size * filter_size) | Feature Extractor | [
"Feature",
"Extractor"
] | def forward(self, left_input, right_input):
"""
Feature Extractor
Description: Aggregates the RGB values from the neighbouring pixels in the window (filter_size * filter_size).
No weights are learnt for this feature extractor.
Args:
:param left_input: Left Image
:param right_input: Right Image
Returns:
:left_features: Left Image features
:right_features: Right Image features
:one_hot_filter: Convolution filter used to aggregate neighbour RGB features to the center pixel.
one_hot_filter.shape = (filter_size * filter_size)
"""
device = left_input.get_device()
label = torch.arange(0, self.filter_size * self.filter_size, device=device).repeat(
self.filter_size * self.filter_size).view(
self.filter_size * self.filter_size, 1, 1, self.filter_size, self.filter_size)
one_hot_filter = torch.zeros_like(label).scatter_(0, label, 1).float()
left_features = F.conv3d(left_input.unsqueeze(1), one_hot_filter,
padding=(0, self.filter_size // 2, self.filter_size // 2))
right_features = F.conv3d(right_input.unsqueeze(1), one_hot_filter,
padding=(0, self.filter_size // 2, self.filter_size // 2))
left_features = left_features.view(left_features.size()[0],
left_features.size()[1] * left_features.size()[2],
left_features.size()[3],
left_features.size()[4])
right_features = right_features.view(right_features.size()[0],
right_features.size()[1] * right_features.size()[2],
right_features.size()[3],
right_features.size()[4])
return left_features, right_features, one_hot_filter | [
"def",
"forward",
"(",
"self",
",",
"left_input",
",",
"right_input",
")",
":",
"device",
"=",
"left_input",
".",
"get_device",
"(",
")",
"label",
"=",
"torch",
".",
"arange",
"(",
"0",
",",
"self",
".",
"filter_size",
"*",
"self",
".",
"filter_size",
... | https://github.com/uber-research/DeepPruner/blob/40b188cf954577e21d5068db2be2bedc6b0e8781/DifferentiablePatchMatch/models/feature_extractor.py#L28-L69 | |
pfalcon/pycopy-lib | 56ebf2110f3caa63a3785d439ce49b11e13c75c0 | datetime/datetime.py | python | date.timetuple | (self) | return _build_struct_time(self._year, self._month, self._day,
0, 0, 0, -1) | Return local time tuple compatible with time.localtime(). | Return local time tuple compatible with time.localtime(). | [
"Return",
"local",
"time",
"tuple",
"compatible",
"with",
"time",
".",
"localtime",
"()",
"."
] | def timetuple(self):
"Return local time tuple compatible with time.localtime()."
return _build_struct_time(self._year, self._month, self._day,
0, 0, 0, -1) | [
"def",
"timetuple",
"(",
"self",
")",
":",
"return",
"_build_struct_time",
"(",
"self",
".",
"_year",
",",
"self",
".",
"_month",
",",
"self",
".",
"_day",
",",
"0",
",",
"0",
",",
"0",
",",
"-",
"1",
")"
] | https://github.com/pfalcon/pycopy-lib/blob/56ebf2110f3caa63a3785d439ce49b11e13c75c0/datetime/datetime.py#L763-L766 | |
fancompute/ceviche | 5da9df12cb2b15cc25ca1a3d4b5eb827eb89e195 | ceviche/jacobians.py | python | jacobian_numerical | (fn, x, step_size=1e-7) | return jacobian | numerically differentiate `fn` w.r.t. its argument `x` | numerically differentiate `fn` w.r.t. its argument `x` | [
"numerically",
"differentiate",
"fn",
"w",
".",
"r",
".",
"t",
".",
"its",
"argument",
"x"
] | def jacobian_numerical(fn, x, step_size=1e-7):
""" numerically differentiate `fn` w.r.t. its argument `x` """
in_array = float_2_array(x).flatten()
out_array = float_2_array(fn(x)).flatten()
m = in_array.size
n = out_array.size
shape = (n, m)
jacobian = npa.zeros(shape)
for i in range(m):
input_i = in_array.copy()
input_i[i] += step_size
arg_i = input_i.reshape(in_array.shape)
output_i = fn(arg_i).flatten()
grad_i = (output_i - out_array) / step_size
jacobian[:, i] = get_value_arr(get_value(grad_i)) # need to convert both the grad_i array and its contents to actual data.
return jacobian | [
"def",
"jacobian_numerical",
"(",
"fn",
",",
"x",
",",
"step_size",
"=",
"1e-7",
")",
":",
"in_array",
"=",
"float_2_array",
"(",
"x",
")",
".",
"flatten",
"(",
")",
"out_array",
"=",
"float_2_array",
"(",
"fn",
"(",
"x",
")",
")",
".",
"flatten",
"(... | https://github.com/fancompute/ceviche/blob/5da9df12cb2b15cc25ca1a3d4b5eb827eb89e195/ceviche/jacobians.py#L55-L73 | |
cdhigh/KindleEar | 7c4ecf9625239f12a829210d1760b863ef5a23aa | lib/web/template.py | python | Parser.read_statement | (self, text) | return text[:tok.index], text[tok.index:] | r"""Reads a python statement.
>>> read_statement = Parser().read_statement
>>> read_statement('for i in range(10): hello $name')
('for i in range(10):', ' hello $name') | r"""Reads a python statement.
>>> read_statement = Parser().read_statement
>>> read_statement('for i in range(10): hello $name')
('for i in range(10):', ' hello $name') | [
"r",
"Reads",
"a",
"python",
"statement",
".",
">>>",
"read_statement",
"=",
"Parser",
"()",
".",
"read_statement",
">>>",
"read_statement",
"(",
"for",
"i",
"in",
"range",
"(",
"10",
")",
":",
"hello",
"$name",
")",
"(",
"for",
"i",
"in",
"range",
"("... | def read_statement(self, text):
r"""Reads a python statement.
>>> read_statement = Parser().read_statement
>>> read_statement('for i in range(10): hello $name')
('for i in range(10):', ' hello $name')
"""
tok = PythonTokenizer(text)
tok.consume_till(':')
return text[:tok.index], text[tok.index:] | [
"def",
"read_statement",
"(",
"self",
",",
"text",
")",
":",
"tok",
"=",
"PythonTokenizer",
"(",
"text",
")",
"tok",
".",
"consume_till",
"(",
"':'",
")",
"return",
"text",
"[",
":",
"tok",
".",
"index",
"]",
",",
"text",
"[",
"tok",
".",
"index",
... | https://github.com/cdhigh/KindleEar/blob/7c4ecf9625239f12a829210d1760b863ef5a23aa/lib/web/template.py#L417-L426 | |
cloudera/hue | 23f02102d4547c17c32bd5ea0eb24e9eadd657a4 | desktop/core/ext-py/Django-1.11.29/django/utils/formats.py | python | time_format | (value, format=None, use_l10n=None) | return dateformat.time_format(value, get_format(format or 'TIME_FORMAT', use_l10n=use_l10n)) | Formats a datetime.time object using a localizable format
If use_l10n is provided and is not None, that will force the value to
be localized (or not), overriding the value of settings.USE_L10N. | Formats a datetime.time object using a localizable format | [
"Formats",
"a",
"datetime",
".",
"time",
"object",
"using",
"a",
"localizable",
"format"
] | def time_format(value, format=None, use_l10n=None):
"""
Formats a datetime.time object using a localizable format
If use_l10n is provided and is not None, that will force the value to
be localized (or not), overriding the value of settings.USE_L10N.
"""
return dateformat.time_format(value, get_format(format or 'TIME_FORMAT', use_l10n=use_l10n)) | [
"def",
"time_format",
"(",
"value",
",",
"format",
"=",
"None",
",",
"use_l10n",
"=",
"None",
")",
":",
"return",
"dateformat",
".",
"time_format",
"(",
"value",
",",
"get_format",
"(",
"format",
"or",
"'TIME_FORMAT'",
",",
"use_l10n",
"=",
"use_l10n",
")"... | https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/Django-1.11.29/django/utils/formats.py#L165-L172 | |
tobegit3hub/deep_image_model | 8a53edecd9e00678b278bb10f6fb4bdb1e4ee25e | java_predict_client/src/main/proto/tensorflow/contrib/factorization/python/ops/factorization_ops.py | python | WALSModel._shard_sizes | (cls, dims, num_shards) | return [shard_size + 1] * residual + [shard_size] * (num_shards - residual) | Helper function to split dims values into num_shards. | Helper function to split dims values into num_shards. | [
"Helper",
"function",
"to",
"split",
"dims",
"values",
"into",
"num_shards",
"."
] | def _shard_sizes(cls, dims, num_shards):
"""Helper function to split dims values into num_shards."""
shard_size, residual = divmod(dims, num_shards)
return [shard_size + 1] * residual + [shard_size] * (num_shards - residual) | [
"def",
"_shard_sizes",
"(",
"cls",
",",
"dims",
",",
"num_shards",
")",
":",
"shard_size",
",",
"residual",
"=",
"divmod",
"(",
"dims",
",",
"num_shards",
")",
"return",
"[",
"shard_size",
"+",
"1",
"]",
"*",
"residual",
"+",
"[",
"shard_size",
"]",
"*... | https://github.com/tobegit3hub/deep_image_model/blob/8a53edecd9e00678b278bb10f6fb4bdb1e4ee25e/java_predict_client/src/main/proto/tensorflow/contrib/factorization/python/ops/factorization_ops.py#L274-L277 | |
home-assistant/core | 265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1 | homeassistant/components/solarlog/sensor.py | python | SolarlogSensor.native_value | (self) | return raw_attr | Return the native sensor value. | Return the native sensor value. | [
"Return",
"the",
"native",
"sensor",
"value",
"."
] | def native_value(self):
"""Return the native sensor value."""
raw_attr = getattr(self.coordinator.data, self.entity_description.key)
if self.entity_description.value:
return self.entity_description.value(raw_attr)
return raw_attr | [
"def",
"native_value",
"(",
"self",
")",
":",
"raw_attr",
"=",
"getattr",
"(",
"self",
".",
"coordinator",
".",
"data",
",",
"self",
".",
"entity_description",
".",
"key",
")",
"if",
"self",
".",
"entity_description",
".",
"value",
":",
"return",
"self",
... | https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/solarlog/sensor.py#L46-L51 | |
Ghirensics/ghiro | c9ff33b6ed16eb1cd960822b8031baf9b84a8636 | analyses/models.py | python | Analysis.to_json | (self) | Converts object to JSON. | Converts object to JSON. | [
"Converts",
"object",
"to",
"JSON",
"."
] | def to_json(self):
"""Converts object to JSON."""
def date_handler(obj):
"""Converts datetime to str."""
return obj.isoformat() if hasattr(obj, "isoformat") else obj
# Fetch report from mongo.
data = self.report
# Cleanup.
del(data["_id"])
# If result available converts it.
if data:
return json.dumps(data, sort_keys=False, indent=4,
default=date_handler)
else:
return json.dumps({}) | [
"def",
"to_json",
"(",
"self",
")",
":",
"def",
"date_handler",
"(",
"obj",
")",
":",
"\"\"\"Converts datetime to str.\"\"\"",
"return",
"obj",
".",
"isoformat",
"(",
")",
"if",
"hasattr",
"(",
"obj",
",",
"\"isoformat\"",
")",
"else",
"obj",
"# Fetch report f... | https://github.com/Ghirensics/ghiro/blob/c9ff33b6ed16eb1cd960822b8031baf9b84a8636/analyses/models.py#L183-L198 | ||
gem/oq-engine | 1bdb88f3914e390abcbd285600bfd39477aae47c | openquake/calculators/extract.py | python | parse | (query_string, info={}) | return qdic | :returns: a normalized query_dict as in the following examples:
>>> parse('kind=stats', {'stats': {'mean': 0, 'max': 1}})
{'kind': ['mean', 'max'], 'k': [0, 1], 'rlzs': False}
>>> parse('kind=rlzs', {'stats': {}, 'num_rlzs': 3})
{'kind': ['rlz-000', 'rlz-001', 'rlz-002'], 'k': [0, 1, 2], 'rlzs': True}
>>> parse('kind=mean', {'stats': {'mean': 0, 'max': 1}})
{'kind': ['mean'], 'k': [0], 'rlzs': False}
>>> parse('kind=rlz-3&imt=PGA&site_id=0', {'stats': {}})
{'kind': ['rlz-3'], 'imt': ['PGA'], 'site_id': [0], 'k': [3], 'rlzs': True} | :returns: a normalized query_dict as in the following examples: | [
":",
"returns",
":",
"a",
"normalized",
"query_dict",
"as",
"in",
"the",
"following",
"examples",
":"
] | def parse(query_string, info={}):
"""
:returns: a normalized query_dict as in the following examples:
>>> parse('kind=stats', {'stats': {'mean': 0, 'max': 1}})
{'kind': ['mean', 'max'], 'k': [0, 1], 'rlzs': False}
>>> parse('kind=rlzs', {'stats': {}, 'num_rlzs': 3})
{'kind': ['rlz-000', 'rlz-001', 'rlz-002'], 'k': [0, 1, 2], 'rlzs': True}
>>> parse('kind=mean', {'stats': {'mean': 0, 'max': 1}})
{'kind': ['mean'], 'k': [0], 'rlzs': False}
>>> parse('kind=rlz-3&imt=PGA&site_id=0', {'stats': {}})
{'kind': ['rlz-3'], 'imt': ['PGA'], 'site_id': [0], 'k': [3], 'rlzs': True}
"""
qdic = parse_qs(query_string)
loss_types = info.get('loss_types', [])
for key, val in sorted(qdic.items()):
# convert site_id to an int, loss_type to an int, etc
if key == 'loss_type':
qdic[key] = [loss_types[k] for k in val]
qdic['lt'] = val
else:
qdic[key] = [lit_eval(v) for v in val]
if info:
qdic['k'], qdic['kind'], qdic['rlzs'] = _normalize(qdic['kind'], info)
return qdic | [
"def",
"parse",
"(",
"query_string",
",",
"info",
"=",
"{",
"}",
")",
":",
"qdic",
"=",
"parse_qs",
"(",
"query_string",
")",
"loss_types",
"=",
"info",
".",
"get",
"(",
"'loss_types'",
",",
"[",
"]",
")",
"for",
"key",
",",
"val",
"in",
"sorted",
... | https://github.com/gem/oq-engine/blob/1bdb88f3914e390abcbd285600bfd39477aae47c/openquake/calculators/extract.py#L105-L129 | |
canonical/cloud-init | dc1aabfca851e520693c05322f724bd102c76364 | cloudinit/cmd/status.py | python | _get_status_details | (paths) | return status, status_detail, time | Return a 3-tuple of status, status_details and time of last event.
@param paths: An initialized cloudinit.helpers.paths object.
Values are obtained from parsing paths.run_dir/status.json. | Return a 3-tuple of status, status_details and time of last event. | [
"Return",
"a",
"3",
"-",
"tuple",
"of",
"status",
"status_details",
"and",
"time",
"of",
"last",
"event",
"."
] | def _get_status_details(paths):
"""Return a 3-tuple of status, status_details and time of last event.
@param paths: An initialized cloudinit.helpers.paths object.
Values are obtained from parsing paths.run_dir/status.json.
"""
status = STATUS_ENABLED_NOT_RUN
status_detail = ""
status_v1 = {}
status_file = os.path.join(paths.run_dir, "status.json")
result_file = os.path.join(paths.run_dir, "result.json")
(is_disabled, reason) = _is_cloudinit_disabled(
CLOUDINIT_DISABLED_FILE, paths
)
if is_disabled:
status = STATUS_DISABLED
status_detail = reason
if os.path.exists(status_file):
if not os.path.exists(result_file):
status = STATUS_RUNNING
status_v1 = load_json(load_file(status_file)).get("v1", {})
errors = []
latest_event = 0
for key, value in sorted(status_v1.items()):
if key == "stage":
if value:
status = STATUS_RUNNING
status_detail = "Running in stage: {0}".format(value)
elif key == "datasource":
status_detail = value
elif isinstance(value, dict):
errors.extend(value.get("errors", []))
start = value.get("start") or 0
finished = value.get("finished") or 0
if finished == 0 and start != 0:
status = STATUS_RUNNING
event_time = max(start, finished)
if event_time > latest_event:
latest_event = event_time
if errors:
status = STATUS_ERROR
status_detail = "\n".join(errors)
elif status == STATUS_ENABLED_NOT_RUN and latest_event > 0:
status = STATUS_DONE
if latest_event:
time = strftime("%a, %d %b %Y %H:%M:%S %z", gmtime(latest_event))
else:
time = ""
return status, status_detail, time | [
"def",
"_get_status_details",
"(",
"paths",
")",
":",
"status",
"=",
"STATUS_ENABLED_NOT_RUN",
"status_detail",
"=",
"\"\"",
"status_v1",
"=",
"{",
"}",
"status_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"paths",
".",
"run_dir",
",",
"\"status.json\"",
... | https://github.com/canonical/cloud-init/blob/dc1aabfca851e520693c05322f724bd102c76364/cloudinit/cmd/status.py#L111-L162 | |
tp4a/teleport | 1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad | server/www/packages/packages-darwin/x64/PIL/ImageStat.py | python | Stat._getmedian | (self) | return v | Get median pixel level for each layer | Get median pixel level for each layer | [
"Get",
"median",
"pixel",
"level",
"for",
"each",
"layer"
] | def _getmedian(self):
"Get median pixel level for each layer"
v = []
for i in self.bands:
s = 0
l = self.count[i]//2
b = i * 256
for j in range(256):
s = s + self.h[b+j]
if s > l:
break
v.append(j)
return v | [
"def",
"_getmedian",
"(",
"self",
")",
":",
"v",
"=",
"[",
"]",
"for",
"i",
"in",
"self",
".",
"bands",
":",
"s",
"=",
"0",
"l",
"=",
"self",
".",
"count",
"[",
"i",
"]",
"//",
"2",
"b",
"=",
"i",
"*",
"256",
"for",
"j",
"in",
"range",
"(... | https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-darwin/x64/PIL/ImageStat.py#L107-L120 | |
linuxscout/mishkal | 4f4ae0ebc2d6acbeb3de3f0303151ec7b54d2f76 | interfaces/web/lib/paste/fixture.py | python | TestApp.encode_multipart | (self, params, files) | return content_type, body | Encodes a set of parameters (typically a name/value list) and
a set of files (a list of (name, filename, file_body)) into a
typical POST body, returning the (content_type, body). | Encodes a set of parameters (typically a name/value list) and
a set of files (a list of (name, filename, file_body)) into a
typical POST body, returning the (content_type, body). | [
"Encodes",
"a",
"set",
"of",
"parameters",
"(",
"typically",
"a",
"name",
"/",
"value",
"list",
")",
"and",
"a",
"set",
"of",
"files",
"(",
"a",
"list",
"of",
"(",
"name",
"filename",
"file_body",
"))",
"into",
"a",
"typical",
"POST",
"body",
"returnin... | def encode_multipart(self, params, files):
"""
Encodes a set of parameters (typically a name/value list) and
a set of files (a list of (name, filename, file_body)) into a
typical POST body, returning the (content_type, body).
"""
boundary = '----------a_BoUnDaRy%s$' % random.random()
lines = []
for key, value in params:
lines.append('--'+boundary)
lines.append('Content-Disposition: form-data; name="%s"' % key)
lines.append('')
lines.append(value)
for file_info in files:
key, filename, value = self._get_file_info(file_info)
lines.append('--'+boundary)
lines.append('Content-Disposition: form-data; name="%s"; filename="%s"'
% (key, filename))
fcontent = mimetypes.guess_type(filename)[0]
lines.append('Content-Type: %s' %
fcontent or 'application/octet-stream')
lines.append('')
lines.append(value)
lines.append('--' + boundary + '--')
lines.append('')
body = '\r\n'.join(lines)
content_type = 'multipart/form-data; boundary=%s' % boundary
return content_type, body | [
"def",
"encode_multipart",
"(",
"self",
",",
"params",
",",
"files",
")",
":",
"boundary",
"=",
"'----------a_BoUnDaRy%s$'",
"%",
"random",
".",
"random",
"(",
")",
"lines",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"params",
":",
"lines",
".",
... | https://github.com/linuxscout/mishkal/blob/4f4ae0ebc2d6acbeb3de3f0303151ec7b54d2f76/interfaces/web/lib/paste/fixture.py#L314-L341 | |
NeuromorphicProcessorProject/snn_toolbox | a85ada7b5d060500703285ef8a68f06ea1ffda65 | snntoolbox/simulation/backends/inisim/temporal_pattern.py | python | SpikeFlatten.class_name | (self) | return self.__class__.__name__ | Get class name. | Get class name. | [
"Get",
"class",
"name",
"."
] | def class_name(self):
"""Get class name."""
return self.__class__.__name__ | [
"def",
"class_name",
"(",
"self",
")",
":",
"return",
"self",
".",
"__class__",
".",
"__name__"
] | https://github.com/NeuromorphicProcessorProject/snn_toolbox/blob/a85ada7b5d060500703285ef8a68f06ea1ffda65/snntoolbox/simulation/backends/inisim/temporal_pattern.py#L196-L199 | |
bikalims/bika.lims | 35e4bbdb5a3912cae0b5eb13e51097c8b0486349 | bika/lims/exportimport/instruments/abaxis/vetscan/__init__.py | python | AbaxisVetScanCSVParser.parse_data_line | (self, sline) | return 0 | Parses the data line and builds the dictionary.
:param sline: a split data line to parse
:return: the number of rows to jump and parse the next data line or return the code error -1 | Parses the data line and builds the dictionary.
:param sline: a split data line to parse
:return: the number of rows to jump and parse the next data line or return the code error -1 | [
"Parses",
"the",
"data",
"line",
"and",
"builds",
"the",
"dictionary",
".",
":",
"param",
"sline",
":",
"a",
"split",
"data",
"line",
"to",
"parse",
":",
"return",
":",
"the",
"number",
"of",
"rows",
"to",
"jump",
"and",
"parse",
"the",
"next",
"data",... | def parse_data_line(self, sline):
"""
Parses the data line and builds the dictionary.
:param sline: a split data line to parse
:return: the number of rows to jump and parse the next data line or return the code error -1
"""
# if there are less values founded than headers, it's an error
if len(sline) != len(self._columns):
self.err("One data line has the wrong number of items")
return -1
values = {}
remark = ''
date = ''
resid = ''
for idx, result in enumerate(sline):
if self._columns[idx] == 'Date':
date = self.csvDate2BikaDate(result)
elif self._columns[idx] == 'Patient no.':
resid = result
elif self._columns[idx] == 'Customer no.':
remark = result
elif self._columns[idx] != '':
values[self._columns[idx]] = {
'result': result,
'DefaultResult': 'result',
'Remarks': remark,
'DateTime': date,
}
self._addRawResult(resid, values, False)
return 0 | [
"def",
"parse_data_line",
"(",
"self",
",",
"sline",
")",
":",
"# if there are less values founded than headers, it's an error",
"if",
"len",
"(",
"sline",
")",
"!=",
"len",
"(",
"self",
".",
"_columns",
")",
":",
"self",
".",
"err",
"(",
"\"One data line has the ... | https://github.com/bikalims/bika.lims/blob/35e4bbdb5a3912cae0b5eb13e51097c8b0486349/bika/lims/exportimport/instruments/abaxis/vetscan/__init__.py#L35-L64 | |
bruderstein/PythonScript | df9f7071ddf3a079e3a301b9b53a6dc78cf1208f | PythonLib/min/encodings/mbcs.py | python | IncrementalEncoder.encode | (self, input, final=False) | return mbcs_encode(input, self.errors)[0] | [] | def encode(self, input, final=False):
return mbcs_encode(input, self.errors)[0] | [
"def",
"encode",
"(",
"self",
",",
"input",
",",
"final",
"=",
"False",
")",
":",
"return",
"mbcs_encode",
"(",
"input",
",",
"self",
".",
"errors",
")",
"[",
"0",
"]"
] | https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/min/encodings/mbcs.py#L24-L25 | |||
merenlab/anvio | 9b792e2cedc49ecb7c0bed768261595a0d87c012 | anvio/dbops.py | python | ProfileSuperclass.get_blank_indels_dict | (self) | return d | Returns an empty indels dictionary to be filled elsewhere | Returns an empty indels dictionary to be filled elsewhere | [
"Returns",
"an",
"empty",
"indels",
"dictionary",
"to",
"be",
"filled",
"elsewhere"
] | def get_blank_indels_dict(self):
"""Returns an empty indels dictionary to be filled elsewhere"""
d = {}
for sample_name in self.p_meta['samples']:
d[sample_name] = {'indels': {}}
return d | [
"def",
"get_blank_indels_dict",
"(",
"self",
")",
":",
"d",
"=",
"{",
"}",
"for",
"sample_name",
"in",
"self",
".",
"p_meta",
"[",
"'samples'",
"]",
":",
"d",
"[",
"sample_name",
"]",
"=",
"{",
"'indels'",
":",
"{",
"}",
"}",
"return",
"d"
] | https://github.com/merenlab/anvio/blob/9b792e2cedc49ecb7c0bed768261595a0d87c012/anvio/dbops.py#L3383-L3390 | |
IronLanguages/ironpython3 | 7a7bb2a872eeab0d1009fc8a6e24dca43f65b693 | Src/StdLib/Lib/idlelib/configDialog.py | python | ConfigDialog.SetKeysType | (self) | [] | def SetKeysType(self):
if self.keysAreBuiltin.get():
self.optMenuKeysBuiltin.config(state=NORMAL)
self.optMenuKeysCustom.config(state=DISABLED)
self.buttonDeleteCustomKeys.config(state=DISABLED)
else:
self.optMenuKeysBuiltin.config(state=DISABLED)
self.radioKeysCustom.config(state=NORMAL)
self.optMenuKeysCustom.config(state=NORMAL)
self.buttonDeleteCustomKeys.config(state=NORMAL) | [
"def",
"SetKeysType",
"(",
"self",
")",
":",
"if",
"self",
".",
"keysAreBuiltin",
".",
"get",
"(",
")",
":",
"self",
".",
"optMenuKeysBuiltin",
".",
"config",
"(",
"state",
"=",
"NORMAL",
")",
"self",
".",
"optMenuKeysCustom",
".",
"config",
"(",
"state"... | https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/idlelib/configDialog.py#L625-L634 | ||||
travisgoodspeed/goodfet | 1750cc1e8588af5470385e52fa098ca7364c2863 | contrib/reCAN/mainDisplay.py | python | DisplayApp.buildControls | (self) | return | This method builds out the top frame bar which allows the user to switch tabs between the
experiments, sniff/write, MYSQL and Arbitration id tabs | This method builds out the top frame bar which allows the user to switch tabs between the
experiments, sniff/write, MYSQL and Arbitration id tabs | [
"This",
"method",
"builds",
"out",
"the",
"top",
"frame",
"bar",
"which",
"allows",
"the",
"user",
"to",
"switch",
"tabs",
"between",
"the",
"experiments",
"sniff",
"/",
"write",
"MYSQL",
"and",
"Arbitration",
"id",
"tabs"
] | def buildControls(self):
"""
This method builds out the top frame bar which allows the user to switch tabs between the
experiments, sniff/write, MYSQL and Arbitration id tabs
"""
# make a control frame
self.cntlframe = tk.Frame(self.root)
self.cntlframe.pack(side=tk.TOP, padx=2, pady=2, fill=X)
# make a separator line
sep = tk.Frame( self.root, height=2, width=self.initDx, bd=1, relief=tk.SUNKEN )
sep.pack( side=tk.TOP, padx = 2, pady = 2, fill=tk.Y)
# make a cmd 1 button in the frame
self.buttons = []
#width should be in characters. stored in a touple with the first one being a tag
self.buttons.append( ( 'sniff', tk.Button(self.cntlframe, \
text="Sniff", command=self.sniffFrameLift,width=10)))
self.buttons[-1][1].pack(side=tk.LEFT)
self.buttons.append( ( 'experiments', tk.Button( self.cntlframe, text="Experiments", \
command=self.experimentFrameLift, width=10 ) ) )
self.buttons[-1][1].pack(side=tk.LEFT)
self.buttons.append( ('Info', tk.Button(self.cntlframe, text="ID Information",\
command=self.infoFrameLift, width=15)))
self.buttons[-1][1].pack(side=tk.LEFT)
self.buttons.append( ( 'SQL', tk.Button( self.cntlframe, text="MySQL", \
command=self.sqlFrameLift, width=10)))
self.buttons[-1][1].pack(side=tk.LEFT)
self.buttons.append( ('Car Module', tk.Button(self.cntlframe, text="Car Module", \
command=self.ourCarFrameLift, width=10)))
self.buttons[-1][1].pack(side=tk.LEFT)
return | [
"def",
"buildControls",
"(",
"self",
")",
":",
"# make a control frame",
"self",
".",
"cntlframe",
"=",
"tk",
".",
"Frame",
"(",
"self",
".",
"root",
")",
"self",
".",
"cntlframe",
".",
"pack",
"(",
"side",
"=",
"tk",
".",
"TOP",
",",
"padx",
"=",
"2... | https://github.com/travisgoodspeed/goodfet/blob/1750cc1e8588af5470385e52fa098ca7364c2863/contrib/reCAN/mainDisplay.py#L1929-L1962 | |
bonsaiviking/NfSpy | a588acbe471229c9dce0472d32055d30fe671f2f | nfspy/rpc.py | python | RawBroadcastUDPClient.connsocket | (self) | [] | def connsocket(self):
# Don't connect -- use sendto
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) | [
"def",
"connsocket",
"(",
"self",
")",
":",
"# Don't connect -- use sendto",
"self",
".",
"sock",
".",
"setsockopt",
"(",
"socket",
".",
"SOL_SOCKET",
",",
"socket",
".",
"SO_BROADCAST",
",",
"1",
")"
] | https://github.com/bonsaiviking/NfSpy/blob/a588acbe471229c9dce0472d32055d30fe671f2f/nfspy/rpc.py#L411-L413 | ||||
albertz/music-player | d23586f5bf657cbaea8147223be7814d117ae73d | mac/pyobjc-framework-Cocoa/Examples/AppKit/DatePicker/MyWindowController.py | python | MyWindowController.setBackgroundColor_ | (self, sender) | [] | def setBackgroundColor_(self, sender):
newColor = sender.color()
self.datePickerControl.setBackgroundColor_(newColor) | [
"def",
"setBackgroundColor_",
"(",
"self",
",",
"sender",
")",
":",
"newColor",
"=",
"sender",
".",
"color",
"(",
")",
"self",
".",
"datePickerControl",
".",
"setBackgroundColor_",
"(",
"newColor",
")"
] | https://github.com/albertz/music-player/blob/d23586f5bf657cbaea8147223be7814d117ae73d/mac/pyobjc-framework-Cocoa/Examples/AppKit/DatePicker/MyWindowController.py#L282-L284 | ||||
yuxiaokui/Intranet-Penetration | f57678a204840c83cbf3308e3470ae56c5ff514b | proxy/XX-Net/code/default/python27/1.0/lib/xml/etree/ElementTree.py | python | XMLParser.doctype | (self, name, pubid, system) | This method of XMLParser is deprecated. | This method of XMLParser is deprecated. | [
"This",
"method",
"of",
"XMLParser",
"is",
"deprecated",
"."
] | def doctype(self, name, pubid, system):
"""This method of XMLParser is deprecated."""
warnings.warn(
"This method of XMLParser is deprecated. Define doctype() "
"method on the TreeBuilder target.",
DeprecationWarning,
) | [
"def",
"doctype",
"(",
"self",
",",
"name",
",",
"pubid",
",",
"system",
")",
":",
"warnings",
".",
"warn",
"(",
"\"This method of XMLParser is deprecated. Define doctype() \"",
"\"method on the TreeBuilder target.\"",
",",
"DeprecationWarning",
",",
")"
] | https://github.com/yuxiaokui/Intranet-Penetration/blob/f57678a204840c83cbf3308e3470ae56c5ff514b/proxy/XX-Net/code/default/python27/1.0/lib/xml/etree/ElementTree.py#L1622-L1628 | ||
sony/nnabla-examples | 068be490aacf73740502a1c3b10f8b2d15a52d32 | GANs/pggan/networks.py | python | Generator.__call__ | (self, x, test=False) | return h | Generate images. | Generate images. | [
"Generate",
"images",
"."
] | def __call__(self, x, test=False):
"""Generate images.
"""
with nn.parameter_scope("generator"):
h = self.first_cnn(
x, self.resolution_list[0], self.channel_list[0], test)
for i in range(1, len(self.resolution_list)):
h = self.cnn(
h, self.resolution_list[i], self.channel_list[i], test)
h = self.to_RGB(h, self.resolution_list[-1])
h = self.last_act(h)
return h | [
"def",
"__call__",
"(",
"self",
",",
"x",
",",
"test",
"=",
"False",
")",
":",
"with",
"nn",
".",
"parameter_scope",
"(",
"\"generator\"",
")",
":",
"h",
"=",
"self",
".",
"first_cnn",
"(",
"x",
",",
"self",
".",
"resolution_list",
"[",
"0",
"]",
"... | https://github.com/sony/nnabla-examples/blob/068be490aacf73740502a1c3b10f8b2d15a52d32/GANs/pggan/networks.py#L53-L64 | |
sagemath/sage | f9b2db94f675ff16963ccdefba4f1a3393b3fe0d | src/sage/algebras/lie_algebras/symplectic_derivation.py | python | SymplecticDerivationLieAlgebra._unicode_art_term | (self, m) | return unicode_art("·".join(label(i) for i in reversed(m))) | r"""
Return a unicode art representation of the term indexed by ``m``.
EXAMPLES::
sage: L = lie_algebras.SymplecticDerivation(QQ, 5)
sage: L._unicode_art_term([7, 5, 2, 1])
a₁·a₂·a₅·b₂ | r"""
Return a unicode art representation of the term indexed by ``m``. | [
"r",
"Return",
"a",
"unicode",
"art",
"representation",
"of",
"the",
"term",
"indexed",
"by",
"m",
"."
] | def _unicode_art_term(self, m):
r"""
Return a unicode art representation of the term indexed by ``m``.
EXAMPLES::
sage: L = lie_algebras.SymplecticDerivation(QQ, 5)
sage: L._unicode_art_term([7, 5, 2, 1])
a₁·a₂·a₅·b₂
"""
from sage.typeset.unicode_art import unicode_art, unicode_subscript
g = self._g
def label(i):
return "a{}".format(unicode_subscript(i)) if i <= g else "b{}".format(unicode_subscript(i-g))
return unicode_art("·".join(label(i) for i in reversed(m))) | [
"def",
"_unicode_art_term",
"(",
"self",
",",
"m",
")",
":",
"from",
"sage",
".",
"typeset",
".",
"unicode_art",
"import",
"unicode_art",
",",
"unicode_subscript",
"g",
"=",
"self",
".",
"_g",
"def",
"label",
"(",
"i",
")",
":",
"return",
"\"a{}\"",
".",... | https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/algebras/lie_algebras/symplectic_derivation.py#L159-L173 | |
ClusterHQ/dvol | adf6c49bbf74d26fbc802a3cdd02ee47e18ad934 | dvol_python/prototype.py | python | FlockerBranch.fromDatasetName | (cls, datasetName) | return cls(volume, branchName) | Convert ZFS dataset name to FlockerBranch instance. | Convert ZFS dataset name to FlockerBranch instance. | [
"Convert",
"ZFS",
"dataset",
"name",
"to",
"FlockerBranch",
"instance",
"."
] | def fromDatasetName(cls, datasetName):
"""
Convert ZFS dataset name to FlockerBranch instance.
"""
flockerName, volumeName, branchName = datasetName.split(b".")
volume = FlockerVolume(flockerName, volumeName)
return cls(volume, branchName) | [
"def",
"fromDatasetName",
"(",
"cls",
",",
"datasetName",
")",
":",
"flockerName",
",",
"volumeName",
",",
"branchName",
"=",
"datasetName",
".",
"split",
"(",
"b\".\"",
")",
"volume",
"=",
"FlockerVolume",
"(",
"flockerName",
",",
"volumeName",
")",
"return",... | https://github.com/ClusterHQ/dvol/blob/adf6c49bbf74d26fbc802a3cdd02ee47e18ad934/dvol_python/prototype.py#L112-L118 | |
googleads/google-ads-python | 2a1d6062221f6aad1992a6bcca0e7e4a93d2db86 | google/ads/googleads/v7/services/services/change_status_service/transports/grpc.py | python | ChangeStatusServiceGrpcTransport.grpc_channel | (self) | return self._grpc_channel | Return the channel designed to connect to this service. | Return the channel designed to connect to this service. | [
"Return",
"the",
"channel",
"designed",
"to",
"connect",
"to",
"this",
"service",
"."
] | def grpc_channel(self) -> grpc.Channel:
"""Return the channel designed to connect to this service.
"""
return self._grpc_channel | [
"def",
"grpc_channel",
"(",
"self",
")",
"->",
"grpc",
".",
"Channel",
":",
"return",
"self",
".",
"_grpc_channel"
] | https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v7/services/services/change_status_service/transports/grpc.py#L207-L210 | |
kiibohd/kll | b6d997b810006326d31fc570c89d396fd0b70569 | kll/common/parse.py | python | Make.indCode_range | (rangeVals) | return Make.hidCode_range('IndCode', rangeVals) | Indicator HID Code range expansion | Indicator HID Code range expansion | [
"Indicator",
"HID",
"Code",
"range",
"expansion"
] | def indCode_range(rangeVals):
'''
Indicator HID Code range expansion
'''
return Make.hidCode_range('IndCode', rangeVals) | [
"def",
"indCode_range",
"(",
"rangeVals",
")",
":",
"return",
"Make",
".",
"hidCode_range",
"(",
"'IndCode'",
",",
"rangeVals",
")"
] | https://github.com/kiibohd/kll/blob/b6d997b810006326d31fc570c89d396fd0b70569/kll/common/parse.py#L669-L673 | |
carljm/django-form-utils | 08a95987546b2f0969a70b393fc9c3373fbd0e30 | form_utils/forms.py | python | Fieldset.__repr__ | (self) | return "%s('%s', %s, legend='%s', classes='%s', description='%s')" % (
self.__class__.__name__, self.name,
[f.name for f in self.boundfields], self.legend, self.classes,
self.description) | [] | def __repr__(self):
return "%s('%s', %s, legend='%s', classes='%s', description='%s')" % (
self.__class__.__name__, self.name,
[f.name for f in self.boundfields], self.legend, self.classes,
self.description) | [
"def",
"__repr__",
"(",
"self",
")",
":",
"return",
"\"%s('%s', %s, legend='%s', classes='%s', description='%s')\"",
"%",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"self",
".",
"name",
",",
"[",
"f",
".",
"name",
"for",
"f",
"in",
"self",
".",
"bo... | https://github.com/carljm/django-form-utils/blob/08a95987546b2f0969a70b393fc9c3373fbd0e30/form_utils/forms.py#L54-L58 | |||
pantsbuild/pex | 473c6ac732ed4bc338b4b20a9ec930d1d722c9b4 | pex/vendor/_vendored/pip/pip/_vendor/distlib/_backport/tarfile.py | python | ExFileObject.tell | (self) | return self.position | Return the current file position. | Return the current file position. | [
"Return",
"the",
"current",
"file",
"position",
"."
] | def tell(self):
"""Return the current file position.
"""
if self.closed:
raise ValueError("I/O operation on closed file")
return self.position | [
"def",
"tell",
"(",
"self",
")",
":",
"if",
"self",
".",
"closed",
":",
"raise",
"ValueError",
"(",
"\"I/O operation on closed file\"",
")",
"return",
"self",
".",
"position"
] | https://github.com/pantsbuild/pex/blob/473c6ac732ed4bc338b4b20a9ec930d1d722c9b4/pex/vendor/_vendored/pip/pip/_vendor/distlib/_backport/tarfile.py#L876-L882 | |
sympy/sympy | d822fcba181155b85ff2b29fe525adbafb22b448 | sympy/logic/boolalg.py | python | bool_map | (bool1, bool2) | return m | Return the simplified version of *bool1*, and the mapping of variables
that makes the two expressions *bool1* and *bool2* represent the same
logical behaviour for some correspondence between the variables
of each.
If more than one mappings of this sort exist, one of them
is returned.
For example, ``And(x, y)`` is logically equivalent to ``And(a, b)`` for
the mapping ``{x: a, y: b}`` or ``{x: b, y: a}``.
If no such mapping exists, return ``False``.
Examples
========
>>> from sympy import SOPform, bool_map, Or, And, Not, Xor
>>> from sympy.abc import w, x, y, z, a, b, c, d
>>> function1 = SOPform([x, z, y],[[1, 0, 1], [0, 0, 1]])
>>> function2 = SOPform([a, b, c],[[1, 0, 1], [1, 0, 0]])
>>> bool_map(function1, function2)
(y & ~z, {y: a, z: b})
The results are not necessarily unique, but they are canonical. Here,
``(w, z)`` could be ``(a, d)`` or ``(d, a)``:
>>> eq = Or(And(Not(y), w), And(Not(y), z), And(x, y))
>>> eq2 = Or(And(Not(c), a), And(Not(c), d), And(b, c))
>>> bool_map(eq, eq2)
((x & y) | (w & ~y) | (z & ~y), {w: a, x: b, y: c, z: d})
>>> eq = And(Xor(a, b), c, And(c,d))
>>> bool_map(eq, eq.subs(c, x))
(c & d & (a | b) & (~a | ~b), {a: a, b: b, c: d, d: x}) | Return the simplified version of *bool1*, and the mapping of variables
that makes the two expressions *bool1* and *bool2* represent the same
logical behaviour for some correspondence between the variables
of each.
If more than one mappings of this sort exist, one of them
is returned. | [
"Return",
"the",
"simplified",
"version",
"of",
"*",
"bool1",
"*",
"and",
"the",
"mapping",
"of",
"variables",
"that",
"makes",
"the",
"two",
"expressions",
"*",
"bool1",
"*",
"and",
"*",
"bool2",
"*",
"represent",
"the",
"same",
"logical",
"behaviour",
"f... | def bool_map(bool1, bool2):
"""
Return the simplified version of *bool1*, and the mapping of variables
that makes the two expressions *bool1* and *bool2* represent the same
logical behaviour for some correspondence between the variables
of each.
If more than one mappings of this sort exist, one of them
is returned.
For example, ``And(x, y)`` is logically equivalent to ``And(a, b)`` for
the mapping ``{x: a, y: b}`` or ``{x: b, y: a}``.
If no such mapping exists, return ``False``.
Examples
========
>>> from sympy import SOPform, bool_map, Or, And, Not, Xor
>>> from sympy.abc import w, x, y, z, a, b, c, d
>>> function1 = SOPform([x, z, y],[[1, 0, 1], [0, 0, 1]])
>>> function2 = SOPform([a, b, c],[[1, 0, 1], [1, 0, 0]])
>>> bool_map(function1, function2)
(y & ~z, {y: a, z: b})
The results are not necessarily unique, but they are canonical. Here,
``(w, z)`` could be ``(a, d)`` or ``(d, a)``:
>>> eq = Or(And(Not(y), w), And(Not(y), z), And(x, y))
>>> eq2 = Or(And(Not(c), a), And(Not(c), d), And(b, c))
>>> bool_map(eq, eq2)
((x & y) | (w & ~y) | (z & ~y), {w: a, x: b, y: c, z: d})
>>> eq = And(Xor(a, b), c, And(c,d))
>>> bool_map(eq, eq.subs(c, x))
(c & d & (a | b) & (~a | ~b), {a: a, b: b, c: d, d: x})
"""
def match(function1, function2):
"""Return the mapping that equates variables between two
simplified boolean expressions if possible.
By "simplified" we mean that a function has been denested
and is either an And (or an Or) whose arguments are either
symbols (x), negated symbols (Not(x)), or Or (or an And) whose
arguments are only symbols or negated symbols. For example,
``And(x, Not(y), Or(w, Not(z)))``.
Basic.match is not robust enough (see issue 4835) so this is
a workaround that is valid for simplified boolean expressions
"""
# do some quick checks
if function1.__class__ != function2.__class__:
return None # maybe simplification makes them the same?
if len(function1.args) != len(function2.args):
return None # maybe simplification makes them the same?
if function1.is_Symbol:
return {function1: function2}
# get the fingerprint dictionaries
f1 = _finger(function1)
f2 = _finger(function2)
# more quick checks
if len(f1) != len(f2):
return False
# assemble the match dictionary if possible
matchdict = {}
for k in f1.keys():
if k not in f2:
return False
if len(f1[k]) != len(f2[k]):
return False
for i, x in enumerate(f1[k]):
matchdict[x] = f2[k][i]
return matchdict
a = simplify_logic(bool1)
b = simplify_logic(bool2)
m = match(a, b)
if m:
return a, m
return m | [
"def",
"bool_map",
"(",
"bool1",
",",
"bool2",
")",
":",
"def",
"match",
"(",
"function1",
",",
"function2",
")",
":",
"\"\"\"Return the mapping that equates variables between two\n simplified boolean expressions if possible.\n\n By \"simplified\" we mean that a functio... | https://github.com/sympy/sympy/blob/d822fcba181155b85ff2b29fe525adbafb22b448/sympy/logic/boolalg.py#L2910-L2992 | |
inspurer/WorkAttendanceSystem | 1221e2d67bdf5bb15fe99517cc3ded58ccb066df | V2.0/venv/Lib/site-packages/pip-9.0.1-py3.5.egg/pip/_vendor/packaging/specifiers.py | python | BaseSpecifier.__eq__ | (self, other) | Returns a boolean representing whether or not the two Specifier like
objects are equal. | Returns a boolean representing whether or not the two Specifier like
objects are equal. | [
"Returns",
"a",
"boolean",
"representing",
"whether",
"or",
"not",
"the",
"two",
"Specifier",
"like",
"objects",
"are",
"equal",
"."
] | def __eq__(self, other):
"""
Returns a boolean representing whether or not the two Specifier like
objects are equal.
""" | [
"def",
"__eq__",
"(",
"self",
",",
"other",
")",
":"
] | https://github.com/inspurer/WorkAttendanceSystem/blob/1221e2d67bdf5bb15fe99517cc3ded58ccb066df/V2.0/venv/Lib/site-packages/pip-9.0.1-py3.5.egg/pip/_vendor/packaging/specifiers.py#L37-L41 | ||
astropy/photutils | 3caa48e4e4d139976ed7457dc41583fb2c56ba20 | photutils/segmentation/catalog.py | python | SourceCatalog._process_quantities | (self, data, error, background) | return data, error, background | Check units of input arrays.
If any of the input arrays have units then they all must have
units and the units must be the same.
Return unitless ndarrays with the array unit set in
self._data_unit. | Check units of input arrays. | [
"Check",
"units",
"of",
"input",
"arrays",
"."
] | def _process_quantities(self, data, error, background):
"""
Check units of input arrays.
If any of the input arrays have units then they all must have
units and the units must be the same.
Return unitless ndarrays with the array unit set in
self._data_unit.
"""
inputs = (data, error, background)
has_unit = [hasattr(x, 'unit') for x in inputs if x is not None]
use_units = all(has_unit)
if any(has_unit) and not use_units:
raise ValueError('If any of data, error, or background has '
'units, then they all must all have units.')
if use_units:
self._data_unit = data.unit
data = data.value
if error is not None:
if error.unit != self._data_unit:
raise ValueError('error must have the same units as data')
error = error.value
if background is not None:
if background.unit != self._data_unit:
raise ValueError('background must have the same units as '
'data')
background = background.value
return data, error, background | [
"def",
"_process_quantities",
"(",
"self",
",",
"data",
",",
"error",
",",
"background",
")",
":",
"inputs",
"=",
"(",
"data",
",",
"error",
",",
"background",
")",
"has_unit",
"=",
"[",
"hasattr",
"(",
"x",
",",
"'unit'",
")",
"for",
"x",
"in",
"inp... | https://github.com/astropy/photutils/blob/3caa48e4e4d139976ed7457dc41583fb2c56ba20/photutils/segmentation/catalog.py#L258-L286 | |
git-cola/git-cola | b48b8028e0c3baf47faf7b074b9773737358163d | cola/app.py | python | ColaApplication.exit | (self, status) | return self._app.exit(status) | QApplication::exit(status) pass-through | QApplication::exit(status) pass-through | [
"QApplication",
"::",
"exit",
"(",
"status",
")",
"pass",
"-",
"through"
] | def exit(self, status):
"""QApplication::exit(status) pass-through"""
return self._app.exit(status) | [
"def",
"exit",
"(",
"self",
",",
"status",
")",
":",
"return",
"self",
".",
"_app",
".",
"exit",
"(",
"status",
")"
] | https://github.com/git-cola/git-cola/blob/b48b8028e0c3baf47faf7b074b9773737358163d/cola/app.py#L247-L249 | |
mitogen-hq/mitogen | 5b505f524a7ae170fe68613841ab92b299613d3f | mitogen/core.py | python | Router.route | (self, msg) | Arrange for the :class:`Message` `msg` to be delivered to its
destination using any relevant downstream context, or if none is found,
by forwarding the message upstream towards the master context. If `msg`
is destined for the local context, it is dispatched using the handles
registered with :meth:`add_handler`.
This may be called from any thread. | Arrange for the :class:`Message` `msg` to be delivered to its
destination using any relevant downstream context, or if none is found,
by forwarding the message upstream towards the master context. If `msg`
is destined for the local context, it is dispatched using the handles
registered with :meth:`add_handler`. | [
"Arrange",
"for",
"the",
":",
"class",
":",
"Message",
"msg",
"to",
"be",
"delivered",
"to",
"its",
"destination",
"using",
"any",
"relevant",
"downstream",
"context",
"or",
"if",
"none",
"is",
"found",
"by",
"forwarding",
"the",
"message",
"upstream",
"towa... | def route(self, msg):
"""
Arrange for the :class:`Message` `msg` to be delivered to its
destination using any relevant downstream context, or if none is found,
by forwarding the message upstream towards the master context. If `msg`
is destined for the local context, it is dispatched using the handles
registered with :meth:`add_handler`.
This may be called from any thread.
"""
self.broker.defer(self._async_route, msg) | [
"def",
"route",
"(",
"self",
",",
"msg",
")",
":",
"self",
".",
"broker",
".",
"defer",
"(",
"self",
".",
"_async_route",
",",
"msg",
")"
] | https://github.com/mitogen-hq/mitogen/blob/5b505f524a7ae170fe68613841ab92b299613d3f/mitogen/core.py#L3343-L3353 | ||
deepfakes/faceswap | 09c7d8aca3c608d1afad941ea78e9fd9b64d9219 | lib/gui/utils.py | python | Config.user_config | (self) | return self._user_config | dict: The GUI config in dict form. | dict: The GUI config in dict form. | [
"dict",
":",
"The",
"GUI",
"config",
"in",
"dict",
"form",
"."
] | def user_config(self):
""" dict: The GUI config in dict form. """
return self._user_config | [
"def",
"user_config",
"(",
"self",
")",
":",
"return",
"self",
".",
"_user_config"
] | https://github.com/deepfakes/faceswap/blob/09c7d8aca3c608d1afad941ea78e9fd9b64d9219/lib/gui/utils.py#L940-L942 | |
tensorflow/tensor2tensor | 2a33b152d7835af66a6d20afe7961751047e28dd | tensor2tensor/rl/player.py | python | PlayerEnv.get_keys_to_action | (self) | return keys_to_action | Get mapping from keyboard keys to actions.
Required by gym.utils.play in environment or top level wrapper.
Returns:
{
Unicode code point for keyboard key: action (formatted for step()),
...
} | Get mapping from keyboard keys to actions. | [
"Get",
"mapping",
"from",
"keyboard",
"keys",
"to",
"actions",
"."
] | def get_keys_to_action(self):
"""Get mapping from keyboard keys to actions.
Required by gym.utils.play in environment or top level wrapper.
Returns:
{
Unicode code point for keyboard key: action (formatted for step()),
...
}
"""
# Based on gym AtariEnv.get_keys_to_action()
keyword_to_key = {
"UP": ord("w"),
"DOWN": ord("s"),
"LEFT": ord("a"),
"RIGHT": ord("d"),
"FIRE": ord(" "),
}
keys_to_action = {}
for action_id, action_meaning in enumerate(self.action_meanings):
keys_tuple = tuple(sorted([
key for keyword, key in keyword_to_key.items()
if keyword in action_meaning]))
assert keys_tuple not in keys_to_action
keys_to_action[keys_tuple] = action_id
# Special actions:
keys_to_action[(ord("r"),)] = self.RETURN_DONE_ACTION
keys_to_action[(ord("c"),)] = self.TOGGLE_WAIT_ACTION
keys_to_action[(ord("n"),)] = self.WAIT_MODE_NOOP_ACTION
return keys_to_action | [
"def",
"get_keys_to_action",
"(",
"self",
")",
":",
"# Based on gym AtariEnv.get_keys_to_action()",
"keyword_to_key",
"=",
"{",
"\"UP\"",
":",
"ord",
"(",
"\"w\"",
")",
",",
"\"DOWN\"",
":",
"ord",
"(",
"\"s\"",
")",
",",
"\"LEFT\"",
":",
"ord",
"(",
"\"a\"",
... | https://github.com/tensorflow/tensor2tensor/blob/2a33b152d7835af66a6d20afe7961751047e28dd/tensor2tensor/rl/player.py#L157-L191 | |
python-provy/provy | ca3d5e96a2210daf3c1fd4b96e047efff152db14 | provy/more/debian/security/selinux.py | python | SELinuxRole.enforce | (self) | Puts the system into enforce mode.
This is executed during provisioning, so you can ignore this method.
Example:
::
from provy.core import Role
from provy.more.debian import SELinuxRole
class MySampleRole(Role):
def provision(self):
with self.using(SELinuxRole) as selinux:
selinux.enforce() # no need to call this directly. | Puts the system into enforce mode. | [
"Puts",
"the",
"system",
"into",
"enforce",
"mode",
"."
] | def enforce(self):
'''
Puts the system into enforce mode.
This is executed during provisioning, so you can ignore this method.
Example:
::
from provy.core import Role
from provy.more.debian import SELinuxRole
class MySampleRole(Role):
def provision(self):
with self.using(SELinuxRole) as selinux:
selinux.enforce() # no need to call this directly.
'''
with fabric.api.settings(warn_only=True):
self.execute('setenforce 1', stdout=False, sudo=True)
self.ensure_line('SELINUX=enforcing', '/etc/selinux/config', sudo=True) | [
"def",
"enforce",
"(",
"self",
")",
":",
"with",
"fabric",
".",
"api",
".",
"settings",
"(",
"warn_only",
"=",
"True",
")",
":",
"self",
".",
"execute",
"(",
"'setenforce 1'",
",",
"stdout",
"=",
"False",
",",
"sudo",
"=",
"True",
")",
"self",
".",
... | https://github.com/python-provy/provy/blob/ca3d5e96a2210daf3c1fd4b96e047efff152db14/provy/more/debian/security/selinux.py#L116-L135 | ||
wanggrun/Adaptively-Connected-Neural-Networks | e27066ef52301bdafa5932f43af8feeb23647edb | tensorpack-installed/build/lib/tensorpack/dataflow/parallel.py | python | MultiProcessPrefetchData.__init__ | (self, ds, nr_prefetch, nr_proc) | Args:
ds (DataFlow): input DataFlow.
nr_prefetch (int): size of the queue to hold prefetched datapoints.
nr_proc (int): number of processes to use. | Args:
ds (DataFlow): input DataFlow.
nr_prefetch (int): size of the queue to hold prefetched datapoints.
nr_proc (int): number of processes to use. | [
"Args",
":",
"ds",
"(",
"DataFlow",
")",
":",
"input",
"DataFlow",
".",
"nr_prefetch",
"(",
"int",
")",
":",
"size",
"of",
"the",
"queue",
"to",
"hold",
"prefetched",
"datapoints",
".",
"nr_proc",
"(",
"int",
")",
":",
"number",
"of",
"processes",
"to"... | def __init__(self, ds, nr_prefetch, nr_proc):
"""
Args:
ds (DataFlow): input DataFlow.
nr_prefetch (int): size of the queue to hold prefetched datapoints.
nr_proc (int): number of processes to use.
"""
if os.name == 'nt':
logger.warn("MultiProcessPrefetchData may not support windows!")
super(MultiProcessPrefetchData, self).__init__(ds)
try:
self._size = ds.size()
except NotImplementedError:
self._size = -1
self.nr_proc = nr_proc
self.nr_prefetch = nr_prefetch
if nr_proc > 1:
logger.info("[MultiProcessPrefetchData] Will fork a dataflow more than one times. "
"This assumes the datapoints are i.i.d.")
self.queue = mp.Queue(self.nr_prefetch)
self.procs = [MultiProcessPrefetchData._Worker(self.ds, self.queue)
for _ in range(self.nr_proc)]
ensure_proc_terminate(self.procs)
start_proc_mask_signal(self.procs) | [
"def",
"__init__",
"(",
"self",
",",
"ds",
",",
"nr_prefetch",
",",
"nr_proc",
")",
":",
"if",
"os",
".",
"name",
"==",
"'nt'",
":",
"logger",
".",
"warn",
"(",
"\"MultiProcessPrefetchData may not support windows!\"",
")",
"super",
"(",
"MultiProcessPrefetchData... | https://github.com/wanggrun/Adaptively-Connected-Neural-Networks/blob/e27066ef52301bdafa5932f43af8feeb23647edb/tensorpack-installed/build/lib/tensorpack/dataflow/parallel.py#L162-L187 | ||
eugenevinitsky/sequential_social_dilemma_games | ef3dd2c3d838880e71daf7d13246f2e0342cd1ab | social_dilemmas/envs/cleanup.py | python | CleanupEnv.compute_permitted_area | (self) | return free_area | How many cells can we spawn waste on? | How many cells can we spawn waste on? | [
"How",
"many",
"cells",
"can",
"we",
"spawn",
"waste",
"on?"
] | def compute_permitted_area(self):
"""How many cells can we spawn waste on?"""
unique, counts = np.unique(self.world_map, return_counts=True)
counts_dict = dict(zip(unique, counts))
current_area = counts_dict.get(b"H", 0)
free_area = self.potential_waste_area - current_area
return free_area | [
"def",
"compute_permitted_area",
"(",
"self",
")",
":",
"unique",
",",
"counts",
"=",
"np",
".",
"unique",
"(",
"self",
".",
"world_map",
",",
"return_counts",
"=",
"True",
")",
"counts_dict",
"=",
"dict",
"(",
"zip",
"(",
"unique",
",",
"counts",
")",
... | https://github.com/eugenevinitsky/sequential_social_dilemma_games/blob/ef3dd2c3d838880e71daf7d13246f2e0342cd1ab/social_dilemmas/envs/cleanup.py#L189-L195 | |
pwnieexpress/pwn_plug_sources | 1a23324f5dc2c3de20f9c810269b6a29b2758cad | src/metagoofil/hachoir_parser/audio/itunesdb.py | python | ITunesDBFile.createContentSize | (self) | return self["entry_length"].value * 8 | [] | def createContentSize(self):
return self["entry_length"].value * 8 | [
"def",
"createContentSize",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"entry_length\"",
"]",
".",
"value",
"*",
"8"
] | https://github.com/pwnieexpress/pwn_plug_sources/blob/1a23324f5dc2c3de20f9c810269b6a29b2758cad/src/metagoofil/hachoir_parser/audio/itunesdb.py#L431-L432 | |||
llSourcell/AI_Artist | 3038c06c2e389b9c919c881c9a169efe2fd7810e | lib/python2.7/site-packages/pip/_vendor/re-vendor.py | python | usage | () | [] | def usage():
print("Usage: re-vendor.py [clean|vendor]")
sys.exit(1) | [
"def",
"usage",
"(",
")",
":",
"print",
"(",
"\"Usage: re-vendor.py [clean|vendor]\"",
")",
"sys",
".",
"exit",
"(",
"1",
")"
] | https://github.com/llSourcell/AI_Artist/blob/3038c06c2e389b9c919c881c9a169efe2fd7810e/lib/python2.7/site-packages/pip/_vendor/re-vendor.py#L9-L11 | ||||
noamraph/dreampie | b09ee546ec099ee6549c649692ceb129e05fb229 | dulwich/object_store.py | python | PackBasedObjectStore.contains_loose | (self, sha) | return self._get_loose_object(sha) is not None | Check if a particular object is present by SHA1 and is loose. | Check if a particular object is present by SHA1 and is loose. | [
"Check",
"if",
"a",
"particular",
"object",
"is",
"present",
"by",
"SHA1",
"and",
"is",
"loose",
"."
] | def contains_loose(self, sha):
"""Check if a particular object is present by SHA1 and is loose."""
return self._get_loose_object(sha) is not None | [
"def",
"contains_loose",
"(",
"self",
",",
"sha",
")",
":",
"return",
"self",
".",
"_get_loose_object",
"(",
"sha",
")",
"is",
"not",
"None"
] | https://github.com/noamraph/dreampie/blob/b09ee546ec099ee6549c649692ceb129e05fb229/dulwich/object_store.py#L290-L292 | |
AI4Finance-Foundation/ElegantRL | 74103d9cc4ce9c573f83bc42d9129ff15b9ff018 | elegantrl_helloworld/MARL/eRL_demo_MADDPG.py | python | save_learning_curve | (recorder=None, cwd='.', save_title='learning curve', fig_name='plot_learning_curve.jpg') | plot subplots | plot subplots | [
"plot",
"subplots"
] | def save_learning_curve(recorder=None, cwd='.', save_title='learning curve', fig_name='plot_learning_curve.jpg'):
if recorder is None:
recorder = np.load(f"{cwd}/recorder.npy")
recorder = np.array(recorder)
steps = recorder[:, 0] # x-axis is training steps
r_avg = recorder[:, 1]
r_std = recorder[:, 2]
r_exp = recorder[:, 3]
#obj_c = recorder[:, 4]
#obj_a = recorder[:, 5]
'''plot subplots'''
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
fig, axs = plt.subplots(2)
'''axs[0]'''
ax00 = axs[0]
ax00.cla()
ax01 = axs[0].twinx()
color01 = 'darkcyan'
ax01.set_ylabel('Explore AvgReward', color=color01)
ax01.plot(steps, r_exp, color=color01, alpha=0.5, )
ax01.tick_params(axis='y', labelcolor=color01)
color0 = 'lightcoral'
ax00.set_ylabel('Episode Return')
ax00.plot(steps, r_avg, label='Episode Return', color=color0)
ax00.fill_between(steps, r_avg - r_std, r_avg + r_std, facecolor=color0, alpha=0.3)
ax00.grid()
'''axs[1]'''
ax10 = axs[1]
ax10.cla()
'''plot save'''
plt.title(save_title, y=2.3)
plt.savefig(f"{cwd}/{fig_name}")
plt.close('all') # avoiding warning about too many open figures, rcParam `figure.max_open_warning` | [
"def",
"save_learning_curve",
"(",
"recorder",
"=",
"None",
",",
"cwd",
"=",
"'.'",
",",
"save_title",
"=",
"'learning curve'",
",",
"fig_name",
"=",
"'plot_learning_curve.jpg'",
")",
":",
"if",
"recorder",
"is",
"None",
":",
"recorder",
"=",
"np",
".",
"loa... | https://github.com/AI4Finance-Foundation/ElegantRL/blob/74103d9cc4ce9c573f83bc42d9129ff15b9ff018/elegantrl_helloworld/MARL/eRL_demo_MADDPG.py#L17-L58 | ||
jython/frozen-mirror | b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99 | lib-python/2.7/lib-tk/ttk.py | python | OptionMenu.destroy | (self) | Destroy this widget and its associated variable. | Destroy this widget and its associated variable. | [
"Destroy",
"this",
"widget",
"and",
"its",
"associated",
"variable",
"."
] | def destroy(self):
"""Destroy this widget and its associated variable."""
del self._variable
Menubutton.destroy(self) | [
"def",
"destroy",
"(",
"self",
")",
":",
"del",
"self",
".",
"_variable",
"Menubutton",
".",
"destroy",
"(",
"self",
")"
] | https://github.com/jython/frozen-mirror/blob/b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99/lib-python/2.7/lib-tk/ttk.py#L1606-L1609 | ||
pdm-project/pdm | 34ba2ea48bf079044b0ca8c0017f3c0e7d9e198b | pdm/cli/utils.py | python | _format_forward_dependency_graph | (project: Project, graph: DirectedGraph) | return "".join(content).strip() | Format dependency graph for output. | Format dependency graph for output. | [
"Format",
"dependency",
"graph",
"for",
"output",
"."
] | def _format_forward_dependency_graph(project: Project, graph: DirectedGraph) -> str:
"""Format dependency graph for output."""
content = []
all_dependencies = ChainMap(*project.all_dependencies.values())
top_level_dependencies = sorted(graph.iter_children(None), key=lambda p: p.name)
for package in top_level_dependencies:
if package.name in all_dependencies:
required = specifier_from_requirement(all_dependencies[package.name])
elif package_is_project(package, project):
required = "This project"
else:
required = ""
content.append(format_package(graph, package, required, ""))
return "".join(content).strip() | [
"def",
"_format_forward_dependency_graph",
"(",
"project",
":",
"Project",
",",
"graph",
":",
"DirectedGraph",
")",
"->",
"str",
":",
"content",
"=",
"[",
"]",
"all_dependencies",
"=",
"ChainMap",
"(",
"*",
"project",
".",
"all_dependencies",
".",
"values",
"(... | https://github.com/pdm-project/pdm/blob/34ba2ea48bf079044b0ca8c0017f3c0e7d9e198b/pdm/cli/utils.py#L297-L310 | |
TencentCloud/tencentcloud-sdk-python | 3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2 | tencentcloud/cdb/v20170320/models.py | python | DescribeSlowLogDataResponse.__init__ | (self) | r"""
:param TotalCount: 符合条件的记录总数。
:type TotalCount: int
:param Items: 查询到的记录。
注意:此字段可能返回 null,表示取不到有效值。
:type Items: list of SlowLogItem
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str | r"""
:param TotalCount: 符合条件的记录总数。
:type TotalCount: int
:param Items: 查询到的记录。
注意:此字段可能返回 null,表示取不到有效值。
:type Items: list of SlowLogItem
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str | [
"r",
":",
"param",
"TotalCount",
":",
"符合条件的记录总数。",
":",
"type",
"TotalCount",
":",
"int",
":",
"param",
"Items",
":",
"查询到的记录。",
"注意:此字段可能返回",
"null,表示取不到有效值。",
":",
"type",
"Items",
":",
"list",
"of",
"SlowLogItem",
":",
"param",
"RequestId",
":",
"唯一请求",
... | def __init__(self):
r"""
:param TotalCount: 符合条件的记录总数。
:type TotalCount: int
:param Items: 查询到的记录。
注意:此字段可能返回 null,表示取不到有效值。
:type Items: list of SlowLogItem
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.TotalCount = None
self.Items = None
self.RequestId = None | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"TotalCount",
"=",
"None",
"self",
".",
"Items",
"=",
"None",
"self",
".",
"RequestId",
"=",
"None"
] | https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/cdb/v20170320/models.py#L5424-L5436 | ||
deepmind/sonnet | 5cbfdc356962d9b6198d5b63f0826a80acfdf35b | sonnet/src/recurrent.py | python | _ConvNDLSTM.__init__ | (self,
num_spatial_dims: int,
input_shape: types.ShapeLike,
output_channels: int,
kernel_shape: Union[int, Sequence[int]],
data_format: Optional[str] = None,
w_i_init: Optional[initializers.Initializer] = None,
w_h_init: Optional[initializers.Initializer] = None,
b_init: Optional[initializers.Initializer] = None,
forget_bias: types.FloatLike = 1.0,
dtype: tf.DType = tf.float32,
name: Optional[str] = None) | Constructs a convolutional LSTM.
Args:
num_spatial_dims: Number of spatial dimensions of the input.
input_shape: Shape of the inputs excluding batch size.
output_channels: Number of output channels.
kernel_shape: Sequence of kernel sizes (of length ``num_spatial_dims``),
or an int. ``kernel_shape`` will be expanded to define a kernel size in
all dimensions.
data_format: The data format of the input.
w_i_init: Optional initializer for the input-to-hidden convolution
weights. Defaults to :class:`~initializers.TruncatedNormal` with a
standard deviation of ``1 / sqrt(kernel_shape**num_spatial_dims *
input_channels)``.
w_h_init: Optional initializer for the hidden-to-hidden convolution
weights. Defaults to :class:`~initializers.TruncatedNormal` with a
standard deviation of ``1 / sqrt(kernel_shape**num_spatial_dims *
input_channels)``.
b_init: Optional initializer for the biases. Defaults to
:class:`~initializers.Zeros`.
forget_bias: Optional float to add to the bias of the forget gate after
initialization.
dtype: Optional :tf:`DType` of the core's variables. Defaults to
``tf.float32``.
name: Name of the module. | Constructs a convolutional LSTM. | [
"Constructs",
"a",
"convolutional",
"LSTM",
"."
] | def __init__(self,
num_spatial_dims: int,
input_shape: types.ShapeLike,
output_channels: int,
kernel_shape: Union[int, Sequence[int]],
data_format: Optional[str] = None,
w_i_init: Optional[initializers.Initializer] = None,
w_h_init: Optional[initializers.Initializer] = None,
b_init: Optional[initializers.Initializer] = None,
forget_bias: types.FloatLike = 1.0,
dtype: tf.DType = tf.float32,
name: Optional[str] = None):
"""Constructs a convolutional LSTM.
Args:
num_spatial_dims: Number of spatial dimensions of the input.
input_shape: Shape of the inputs excluding batch size.
output_channels: Number of output channels.
kernel_shape: Sequence of kernel sizes (of length ``num_spatial_dims``),
or an int. ``kernel_shape`` will be expanded to define a kernel size in
all dimensions.
data_format: The data format of the input.
w_i_init: Optional initializer for the input-to-hidden convolution
weights. Defaults to :class:`~initializers.TruncatedNormal` with a
standard deviation of ``1 / sqrt(kernel_shape**num_spatial_dims *
input_channels)``.
w_h_init: Optional initializer for the hidden-to-hidden convolution
weights. Defaults to :class:`~initializers.TruncatedNormal` with a
standard deviation of ``1 / sqrt(kernel_shape**num_spatial_dims *
input_channels)``.
b_init: Optional initializer for the biases. Defaults to
:class:`~initializers.Zeros`.
forget_bias: Optional float to add to the bias of the forget gate after
initialization.
dtype: Optional :tf:`DType` of the core's variables. Defaults to
``tf.float32``.
name: Name of the module.
"""
super().__init__(name)
self._num_spatial_dims = num_spatial_dims
self._input_shape = list(input_shape)
self._channel_index = 1 if (data_format is not None and
data_format.startswith("NC")) else -1
self._output_channels = output_channels
self._b_init = b_init or initializers.Zeros()
self._forget_bias = forget_bias
self._dtype = dtype
self._input_to_hidden = conv.ConvND(
self._num_spatial_dims,
output_channels=4 * output_channels,
kernel_shape=kernel_shape,
padding="SAME",
with_bias=False,
w_init=w_i_init,
data_format=data_format,
name="input_to_hidden")
self._hidden_to_hidden = conv.ConvND(
self._num_spatial_dims,
output_channels=4 * output_channels,
kernel_shape=kernel_shape,
padding="SAME",
with_bias=False,
w_init=w_h_init,
data_format=data_format,
name="hidden_to_hidden") | [
"def",
"__init__",
"(",
"self",
",",
"num_spatial_dims",
":",
"int",
",",
"input_shape",
":",
"types",
".",
"ShapeLike",
",",
"output_channels",
":",
"int",
",",
"kernel_shape",
":",
"Union",
"[",
"int",
",",
"Sequence",
"[",
"int",
"]",
"]",
",",
"data_... | https://github.com/deepmind/sonnet/blob/5cbfdc356962d9b6198d5b63f0826a80acfdf35b/sonnet/src/recurrent.py#L1238-L1303 | ||
bjmayor/hacker | e3ce2ad74839c2733b27dac6c0f495e0743e1866 | venv/lib/python3.5/site-packages/pip/_vendor/requests/packages/urllib3/connectionpool.py | python | HTTPConnectionPool._validate_conn | (self, conn) | Called right before a request is made, after the socket is created. | Called right before a request is made, after the socket is created. | [
"Called",
"right",
"before",
"a",
"request",
"is",
"made",
"after",
"the",
"socket",
"is",
"created",
"."
] | def _validate_conn(self, conn):
"""
Called right before a request is made, after the socket is created.
"""
pass | [
"def",
"_validate_conn",
"(",
"self",
",",
"conn",
")",
":",
"pass"
] | https://github.com/bjmayor/hacker/blob/e3ce2ad74839c2733b27dac6c0f495e0743e1866/venv/lib/python3.5/site-packages/pip/_vendor/requests/packages/urllib3/connectionpool.py#L289-L293 | ||
tdamdouni/Pythonista | 3e082d53b6b9b501a3c8cf3251a8ad4c8be9c2ad | omz/Map View Demo.py | python | MapView.point_to_coordinate | (self, point) | return coordinate.latitude, coordinate.longitude | Convert from a point in the view (e.g. touch location) to a latitude/longitude | Convert from a point in the view (e.g. touch location) to a latitude/longitude | [
"Convert",
"from",
"a",
"point",
"in",
"the",
"view",
"(",
"e",
".",
"g",
".",
"touch",
"location",
")",
"to",
"a",
"latitude",
"/",
"longitude"
] | def point_to_coordinate(self, point):
'''Convert from a point in the view (e.g. touch location) to a latitude/longitude'''
coordinate = self.mk_map_view.convertPoint_toCoordinateFromView_(CGPoint(*point), self._objc_ptr, restype=CLLocationCoordinate2D, argtypes=[CGPoint, c_void_p])
return coordinate.latitude, coordinate.longitude | [
"def",
"point_to_coordinate",
"(",
"self",
",",
"point",
")",
":",
"coordinate",
"=",
"self",
".",
"mk_map_view",
".",
"convertPoint_toCoordinateFromView_",
"(",
"CGPoint",
"(",
"*",
"point",
")",
",",
"self",
".",
"_objc_ptr",
",",
"restype",
"=",
"CLLocation... | https://github.com/tdamdouni/Pythonista/blob/3e082d53b6b9b501a3c8cf3251a8ad4c8be9c2ad/omz/Map View Demo.py#L145-L148 | |
mapbox/mason | 0296d767a588bab4ca043474c48c0f269ccb8b81 | scripts/clang-tidy/6.0.0/yaml/__init__.py | python | compose_all | (stream, Loader=Loader) | Parse all YAML documents in a stream
and produce corresponding representation trees. | Parse all YAML documents in a stream
and produce corresponding representation trees. | [
"Parse",
"all",
"YAML",
"documents",
"in",
"a",
"stream",
"and",
"produce",
"corresponding",
"representation",
"trees",
"."
] | def compose_all(stream, Loader=Loader):
"""
Parse all YAML documents in a stream
and produce corresponding representation trees.
"""
loader = Loader(stream)
try:
while loader.check_node():
yield loader.get_node()
finally:
loader.dispose() | [
"def",
"compose_all",
"(",
"stream",
",",
"Loader",
"=",
"Loader",
")",
":",
"loader",
"=",
"Loader",
"(",
"stream",
")",
"try",
":",
"while",
"loader",
".",
"check_node",
"(",
")",
":",
"yield",
"loader",
".",
"get_node",
"(",
")",
"finally",
":",
"... | https://github.com/mapbox/mason/blob/0296d767a588bab4ca043474c48c0f269ccb8b81/scripts/clang-tidy/6.0.0/yaml/__init__.py#L52-L62 | ||
mcfletch/pyopengl | 02d11dad9ff18e50db10e975c4756e17bf198464 | OpenGL/GL/ARB/copy_image.py | python | glInitCopyImageARB | () | return extensions.hasGLExtension( _EXTENSION_NAME ) | Return boolean indicating whether this extension is available | Return boolean indicating whether this extension is available | [
"Return",
"boolean",
"indicating",
"whether",
"this",
"extension",
"is",
"available"
] | def glInitCopyImageARB():
'''Return boolean indicating whether this extension is available'''
from OpenGL import extensions
return extensions.hasGLExtension( _EXTENSION_NAME ) | [
"def",
"glInitCopyImageARB",
"(",
")",
":",
"from",
"OpenGL",
"import",
"extensions",
"return",
"extensions",
".",
"hasGLExtension",
"(",
"_EXTENSION_NAME",
")"
] | https://github.com/mcfletch/pyopengl/blob/02d11dad9ff18e50db10e975c4756e17bf198464/OpenGL/GL/ARB/copy_image.py#L38-L41 | |
dimagi/commcare-hq | d67ff1d3b4c51fa050c19e60c3253a79d3452a39 | corehq/motech/value_source.py | python | get_case_trigger_info_for_case | (case, value_source_configs) | return CaseTriggerInfo(
domain=case.domain,
case_id=case.case_id,
type=case.type,
name=case.name,
owner_id=case.owner_id,
modified_by=case.modified_by,
extra_fields=extra_fields,
) | [] | def get_case_trigger_info_for_case(case, value_source_configs):
case_properties = [c['case_property'] for c in value_source_configs
if 'case_property' in c]
extra_fields = {p: case.get_case_property(p) for p in case_properties}
return CaseTriggerInfo(
domain=case.domain,
case_id=case.case_id,
type=case.type,
name=case.name,
owner_id=case.owner_id,
modified_by=case.modified_by,
extra_fields=extra_fields,
) | [
"def",
"get_case_trigger_info_for_case",
"(",
"case",
",",
"value_source_configs",
")",
":",
"case_properties",
"=",
"[",
"c",
"[",
"'case_property'",
"]",
"for",
"c",
"in",
"value_source_configs",
"if",
"'case_property'",
"in",
"c",
"]",
"extra_fields",
"=",
"{",... | https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/motech/value_source.py#L693-L705 | |||
openedx/edx-platform | 68dd185a0ab45862a2a61e0f803d7e03d2be71b5 | common/lib/xmodule/xmodule/course_module.py | python | CourseBlock.clean_id | (self, padding_char='=') | return course_metadata_utils.clean_course_key(self.location.course_key, padding_char) | Returns a unique deterministic base32-encoded ID for the course.
The optional padding_char parameter allows you to override the "=" character used for padding. | Returns a unique deterministic base32-encoded ID for the course.
The optional padding_char parameter allows you to override the "=" character used for padding. | [
"Returns",
"a",
"unique",
"deterministic",
"base32",
"-",
"encoded",
"ID",
"for",
"the",
"course",
".",
"The",
"optional",
"padding_char",
"parameter",
"allows",
"you",
"to",
"override",
"the",
"=",
"character",
"used",
"for",
"padding",
"."
] | def clean_id(self, padding_char='='):
"""
Returns a unique deterministic base32-encoded ID for the course.
The optional padding_char parameter allows you to override the "=" character used for padding.
"""
return course_metadata_utils.clean_course_key(self.location.course_key, padding_char) | [
"def",
"clean_id",
"(",
"self",
",",
"padding_char",
"=",
"'='",
")",
":",
"return",
"course_metadata_utils",
".",
"clean_course_key",
"(",
"self",
".",
"location",
".",
"course_key",
",",
"padding_char",
")"
] | https://github.com/openedx/edx-platform/blob/68dd185a0ab45862a2a61e0f803d7e03d2be71b5/common/lib/xmodule/xmodule/course_module.py#L1489-L1494 | |
CiscoDevNet/netprog_basics | 3fa67855ef461ccaee283dcbbdd9bf00e7a52378 | network_controllers/dnac/troubleshoot_step2.py | python | print_host_details | (host) | Print to screen interesting details about a given host.
Input Paramters are:
host_desc: string to describe this host. Example "Source"
host: dictionary object of a host returned from dnac
Standard Output Details:
Host Name (hostName) - If available
Host IP (hostIp)
Host MAC (hostMac)
Network Type (hostType) - wired/wireless
Host Sub Type (subType)
VLAN (vlanId)
Connected Network Device (connectedNetworkDeviceIpAddress)
Wired Host Details:
Connected Interface Name (connectedInterfaceName)
Wireless Host Details:
Connected AP Name (connectedAPName) | Print to screen interesting details about a given host.
Input Paramters are:
host_desc: string to describe this host. Example "Source"
host: dictionary object of a host returned from dnac
Standard Output Details:
Host Name (hostName) - If available
Host IP (hostIp)
Host MAC (hostMac)
Network Type (hostType) - wired/wireless
Host Sub Type (subType)
VLAN (vlanId)
Connected Network Device (connectedNetworkDeviceIpAddress) | [
"Print",
"to",
"screen",
"interesting",
"details",
"about",
"a",
"given",
"host",
".",
"Input",
"Paramters",
"are",
":",
"host_desc",
":",
"string",
"to",
"describe",
"this",
"host",
".",
"Example",
"Source",
"host",
":",
"dictionary",
"object",
"of",
"a",
... | def print_host_details(host):
"""
Print to screen interesting details about a given host.
Input Paramters are:
host_desc: string to describe this host. Example "Source"
host: dictionary object of a host returned from dnac
Standard Output Details:
Host Name (hostName) - If available
Host IP (hostIp)
Host MAC (hostMac)
Network Type (hostType) - wired/wireless
Host Sub Type (subType)
VLAN (vlanId)
Connected Network Device (connectedNetworkDeviceIpAddress)
Wired Host Details:
Connected Interface Name (connectedInterfaceName)
Wireless Host Details:
Connected AP Name (connectedAPName)
"""
# If optional host details missing, add as "Unavailable"
if "hostName" not in host.keys():
host["hostName"] = "Unavailable"
# Print Standard Details
print("Host Name: {}".format(host["hostName"]))
print("Network Type: {}".format(host["hostType"]))
print("Connected Network Device: {}".format(host["connectedNetworkDeviceIpAddress"])) # noqa: E501
# Print Wired/Wireless Details
if host["hostType"] == "wired":
print("Connected Interface Name: {}".format(host["connectedInterfaceName"])) # noqa: E501
if host["hostType"] == "wireless":
print("Connected AP Name: {}".format(host["connectedAPName"]))
# Print More Standard Details
print("VLAN: {}".format(host["vlanId"]))
print("Host IP: {}".format(host["hostIp"]))
print("Host MAC: {}".format(host["hostMac"]))
print("Host Sub Type: {}".format(host["subType"]))
# Blank line at the end
print("") | [
"def",
"print_host_details",
"(",
"host",
")",
":",
"# If optional host details missing, add as \"Unavailable\"",
"if",
"\"hostName\"",
"not",
"in",
"host",
".",
"keys",
"(",
")",
":",
"host",
"[",
"\"hostName\"",
"]",
"=",
"\"Unavailable\"",
"# Print Standard Details",... | https://github.com/CiscoDevNet/netprog_basics/blob/3fa67855ef461ccaee283dcbbdd9bf00e7a52378/network_controllers/dnac/troubleshoot_step2.py#L92-L135 | ||
biopython/biopython | 2dd97e71762af7b046d7f7f8a4f1e38db6b06c86 | Bio/motifs/jaspar/__init__.py | python | read | (handle, format) | Read motif(s) from a file in one of several different JASPAR formats.
Return the record of PFM(s).
Call the appropriate routine based on the format passed. | Read motif(s) from a file in one of several different JASPAR formats. | [
"Read",
"motif",
"(",
"s",
")",
"from",
"a",
"file",
"in",
"one",
"of",
"several",
"different",
"JASPAR",
"formats",
"."
] | def read(handle, format):
"""Read motif(s) from a file in one of several different JASPAR formats.
Return the record of PFM(s).
Call the appropriate routine based on the format passed.
"""
format = format.lower()
if format == "pfm":
record = _read_pfm(handle)
return record
elif format == "sites":
record = _read_sites(handle)
return record
elif format == "jaspar":
record = _read_jaspar(handle)
return record
else:
raise ValueError("Unknown JASPAR format %s" % format) | [
"def",
"read",
"(",
"handle",
",",
"format",
")",
":",
"format",
"=",
"format",
".",
"lower",
"(",
")",
"if",
"format",
"==",
"\"pfm\"",
":",
"record",
"=",
"_read_pfm",
"(",
"handle",
")",
"return",
"record",
"elif",
"format",
"==",
"\"sites\"",
":",
... | https://github.com/biopython/biopython/blob/2dd97e71762af7b046d7f7f8a4f1e38db6b06c86/Bio/motifs/jaspar/__init__.py#L150-L167 | ||
NVIDIA/DeepLearningExamples | 589604d49e016cd9ef4525f7abcc9c7b826cfc5e | TensorFlow/Detection/SSD/models/research/object_detection/core/balanced_positive_negative_sampler.py | python | BalancedPositiveNegativeSampler._get_values_from_start_and_end | (self, input_tensor, num_start_samples,
num_end_samples, total_num_samples) | return tf.cast(tf.tensordot(tf.cast(input_tensor, tf.float32),
one_hot_selector, axes=[0, 0]), tf.int32) | slices num_start_samples and last num_end_samples from input_tensor.
Args:
input_tensor: An int32 tensor of shape [N] to be sliced.
num_start_samples: Number of examples to be sliced from the beginning
of the input tensor.
num_end_samples: Number of examples to be sliced from the end of the
input tensor.
total_num_samples: Sum of is num_start_samples and num_end_samples. This
should be a scalar.
Returns:
A tensor containing the first num_start_samples and last num_end_samples
from input_tensor. | slices num_start_samples and last num_end_samples from input_tensor. | [
"slices",
"num_start_samples",
"and",
"last",
"num_end_samples",
"from",
"input_tensor",
"."
] | def _get_values_from_start_and_end(self, input_tensor, num_start_samples,
num_end_samples, total_num_samples):
"""slices num_start_samples and last num_end_samples from input_tensor.
Args:
input_tensor: An int32 tensor of shape [N] to be sliced.
num_start_samples: Number of examples to be sliced from the beginning
of the input tensor.
num_end_samples: Number of examples to be sliced from the end of the
input tensor.
total_num_samples: Sum of is num_start_samples and num_end_samples. This
should be a scalar.
Returns:
A tensor containing the first num_start_samples and last num_end_samples
from input_tensor.
"""
input_length = tf.shape(input_tensor)[0]
start_positions = tf.less(tf.range(input_length), num_start_samples)
end_positions = tf.greater_equal(
tf.range(input_length), input_length - num_end_samples)
selected_positions = tf.logical_or(start_positions, end_positions)
selected_positions = tf.cast(selected_positions, tf.float32)
indexed_positions = tf.multiply(tf.cumsum(selected_positions),
selected_positions)
one_hot_selector = tf.one_hot(tf.cast(indexed_positions, tf.int32) - 1,
total_num_samples,
dtype=tf.float32)
return tf.cast(tf.tensordot(tf.cast(input_tensor, tf.float32),
one_hot_selector, axes=[0, 0]), tf.int32) | [
"def",
"_get_values_from_start_and_end",
"(",
"self",
",",
"input_tensor",
",",
"num_start_samples",
",",
"num_end_samples",
",",
"total_num_samples",
")",
":",
"input_length",
"=",
"tf",
".",
"shape",
"(",
"input_tensor",
")",
"[",
"0",
"]",
"start_positions",
"=... | https://github.com/NVIDIA/DeepLearningExamples/blob/589604d49e016cd9ef4525f7abcc9c7b826cfc5e/TensorFlow/Detection/SSD/models/research/object_detection/core/balanced_positive_negative_sampler.py#L86-L116 | |
openshift/openshift-tools | 1188778e728a6e4781acf728123e5b356380fe6f | openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_vendored_deps/library/oc_label.py | python | Utils.openshift_installed | () | return rpmquery.count() > 0 | check if openshift is installed | check if openshift is installed | [
"check",
"if",
"openshift",
"is",
"installed"
] | def openshift_installed():
''' check if openshift is installed '''
import rpm
transaction_set = rpm.TransactionSet()
rpmquery = transaction_set.dbMatch("name", "atomic-openshift")
return rpmquery.count() > 0 | [
"def",
"openshift_installed",
"(",
")",
":",
"import",
"rpm",
"transaction_set",
"=",
"rpm",
".",
"TransactionSet",
"(",
")",
"rpmquery",
"=",
"transaction_set",
".",
"dbMatch",
"(",
"\"name\"",
",",
"\"atomic-openshift\"",
")",
"return",
"rpmquery",
".",
"count... | https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_vendored_deps/library/oc_label.py#L1336-L1343 | |
thunlp/ERNIE | 9a4ab4af54bccb70b4eb53cbfe71a2bc16b9e93f | code/indexed_dataset.py | python | IndexedDataset.__del__ | (self) | [] | def __del__(self):
if self.data_file:
self.data_file.close() | [
"def",
"__del__",
"(",
"self",
")",
":",
"if",
"self",
".",
"data_file",
":",
"self",
".",
"data_file",
".",
"close",
"(",
")"
] | https://github.com/thunlp/ERNIE/blob/9a4ab4af54bccb70b4eb53cbfe71a2bc16b9e93f/code/indexed_dataset.py#L82-L84 | ||||
sagemath/sage | f9b2db94f675ff16963ccdefba4f1a3393b3fe0d | src/sage/rings/universal_cyclotomic_field.py | python | UniversalCyclotomicFieldElement.is_integral | (self) | return self._obj.IsIntegralCyclotomic().sage() | Return whether ``self`` is an algebraic integer.
This just wraps ``IsIntegralCyclotomic`` from GAP.
.. SEEALSO:: :meth:`denominator`
EXAMPLES::
sage: E(6).is_integral()
True
sage: (E(4)/2).is_integral()
False | Return whether ``self`` is an algebraic integer. | [
"Return",
"whether",
"self",
"is",
"an",
"algebraic",
"integer",
"."
] | def is_integral(self):
"""
Return whether ``self`` is an algebraic integer.
This just wraps ``IsIntegralCyclotomic`` from GAP.
.. SEEALSO:: :meth:`denominator`
EXAMPLES::
sage: E(6).is_integral()
True
sage: (E(4)/2).is_integral()
False
"""
return self._obj.IsIntegralCyclotomic().sage() | [
"def",
"is_integral",
"(",
"self",
")",
":",
"return",
"self",
".",
"_obj",
".",
"IsIntegralCyclotomic",
"(",
")",
".",
"sage",
"(",
")"
] | https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/rings/universal_cyclotomic_field.py#L490-L505 | |
replit-archive/empythoned | 977ec10ced29a3541a4973dc2b59910805695752 | cpython/Lib/mhlib.py | python | Folder.removemessages | (self, list) | Remove one or more messages -- may raise os.error. | Remove one or more messages -- may raise os.error. | [
"Remove",
"one",
"or",
"more",
"messages",
"--",
"may",
"raise",
"os",
".",
"error",
"."
] | def removemessages(self, list):
"""Remove one or more messages -- may raise os.error."""
errors = []
deleted = []
for n in list:
path = self.getmessagefilename(n)
commapath = self.getmessagefilename(',' + str(n))
try:
os.unlink(commapath)
except os.error:
pass
try:
os.rename(path, commapath)
except os.error, msg:
errors.append(msg)
else:
deleted.append(n)
if deleted:
self.removefromallsequences(deleted)
if errors:
if len(errors) == 1:
raise os.error, errors[0]
else:
raise os.error, ('multiple errors:', errors) | [
"def",
"removemessages",
"(",
"self",
",",
"list",
")",
":",
"errors",
"=",
"[",
"]",
"deleted",
"=",
"[",
"]",
"for",
"n",
"in",
"list",
":",
"path",
"=",
"self",
".",
"getmessagefilename",
"(",
"n",
")",
"commapath",
"=",
"self",
".",
"getmessagefi... | https://github.com/replit-archive/empythoned/blob/977ec10ced29a3541a4973dc2b59910805695752/cpython/Lib/mhlib.py#L465-L488 | ||
Nuitka/Nuitka | 39262276993757fa4e299f497654065600453fc9 | nuitka/build/inline_copy/lib/scons-4.3.0/SCons/SConf.py | python | SConfBase.Finish | (self) | return self.env | Call this method after finished with your tests:
env = sconf.Finish() | Call this method after finished with your tests:
env = sconf.Finish() | [
"Call",
"this",
"method",
"after",
"finished",
"with",
"your",
"tests",
":",
"env",
"=",
"sconf",
".",
"Finish",
"()"
] | def Finish(self):
"""Call this method after finished with your tests:
env = sconf.Finish()
"""
self._shutdown()
return self.env | [
"def",
"Finish",
"(",
"self",
")",
":",
"self",
".",
"_shutdown",
"(",
")",
"return",
"self",
".",
"env"
] | https://github.com/Nuitka/Nuitka/blob/39262276993757fa4e299f497654065600453fc9/nuitka/build/inline_copy/lib/scons-4.3.0/SCons/SConf.py#L469-L475 | |
zhixinwang/frustum-convnet | 5b1508d3f2140c3c0dd6dd17b5606b532b7a5ec8 | kitti/prepare_data_refine.py | python | extract_frustum_data | (idx_filename, split, output_filename,
perturb_box2d=False, augmentX=1, type_whitelist=['Car'], remove_diff=False) | Extract point clouds and corresponding annotations in frustums
defined generated from 2D bounding boxes
Lidar points and 3d boxes are in *rect camera* coord system
(as that in 3d box label files)
Input:
idx_filename: string, each line of the file is a sample ID
split: string, either trianing or testing
output_filename: string, the name for output .pickle file
viz: bool, whether to visualize extracted data
perturb_box2d: bool, whether to perturb the box2d
(used for data augmentation in train set)
augmentX: scalar, how many augmentations to have for each 2D box.
type_whitelist: a list of strings, object types we are interested in.
Output:
None (will write a .pickle file to the disk) | Extract point clouds and corresponding annotations in frustums
defined generated from 2D bounding boxes
Lidar points and 3d boxes are in *rect camera* coord system
(as that in 3d box label files) | [
"Extract",
"point",
"clouds",
"and",
"corresponding",
"annotations",
"in",
"frustums",
"defined",
"generated",
"from",
"2D",
"bounding",
"boxes",
"Lidar",
"points",
"and",
"3d",
"boxes",
"are",
"in",
"*",
"rect",
"camera",
"*",
"coord",
"system",
"(",
"as",
... | def extract_frustum_data(idx_filename, split, output_filename,
perturb_box2d=False, augmentX=1, type_whitelist=['Car'], remove_diff=False):
''' Extract point clouds and corresponding annotations in frustums
defined generated from 2D bounding boxes
Lidar points and 3d boxes are in *rect camera* coord system
(as that in 3d box label files)
Input:
idx_filename: string, each line of the file is a sample ID
split: string, either trianing or testing
output_filename: string, the name for output .pickle file
viz: bool, whether to visualize extracted data
perturb_box2d: bool, whether to perturb the box2d
(used for data augmentation in train set)
augmentX: scalar, how many augmentations to have for each 2D box.
type_whitelist: a list of strings, object types we are interested in.
Output:
None (will write a .pickle file to the disk)
'''
dataset = kitti_object(os.path.join(ROOT_DIR, 'data/kitti'), split)
data_idx_list = [int(line.rstrip()) for line in open(idx_filename)]
id_list = [] # int number
box3d_list = [] # (8,3) array in rect camera coord
input_list = [] # channel number = 4, xyz,intensity in rect camera coord
label_list = [] # 1 for roi object, 0 for clutter
type_list = [] # string e.g. Car
heading_list = [] # ry (along y-axis in rect camera coord) radius of
# (cont.) clockwise angle from positive x axis in velo coord.
box3d_size_list = [] # array of l,w,h
frustum_angle_list = [] # angle of 2d box center from pos x-axis
gt_box2d_list = []
calib_list = []
enlarge_box3d_list = []
enlarge_box3d_size_list = []
enlarge_box3d_angle_list = []
pos_cnt = 0
all_cnt = 0
for data_idx in data_idx_list:
print('------------- ', data_idx)
calib = dataset.get_calibration(data_idx) # 3 by 4 matrix
objects = dataset.get_label_objects(data_idx)
pc_velo = dataset.get_lidar(data_idx)
pc_rect = np.zeros_like(pc_velo)
pc_rect[:, 0:3] = calib.project_velo_to_rect(pc_velo[:, 0:3])
pc_rect[:, 3] = pc_velo[:, 3]
img = dataset.get_image(data_idx)
img_height, img_width, img_channel = img.shape
_, pc_image_coord, img_fov_inds = get_lidar_in_image_fov(pc_velo[:, 0:3],
calib, 0, 0, img_width, img_height, True)
pc_rect = pc_rect[img_fov_inds, :]
pc_image_coord = pc_image_coord[img_fov_inds]
for obj_idx in range(len(objects)):
if objects[obj_idx].type not in type_whitelist:
continue
if remove_diff:
box2d = objects[obj_idx].box2d
xmin, ymin, xmax, ymax = box2d
if objects[obj_idx].occlusion > 2 or objects[obj_idx].truncation > 0.5 or ymax - ymin < 25:
continue
# 2D BOX: Get pts rect backprojected
box2d = objects[obj_idx].box2d
obj = objects[obj_idx]
l, w, h = obj.l, obj.w, obj.h
cx, cy, cz = obj.t
ry = obj.ry
cy = cy - h / 2
obj_array = np.array([cx, cy, cz, l, w, h, ry])
box3d_pts_3d = compute_box_3d_obj_array(obj_array)
ratio = 1.2
enlarge_obj_array = obj_array.copy()
enlarge_obj_array[3:6] = enlarge_obj_array[3:6] * ratio
for _ in range(augmentX):
if perturb_box2d:
# print(box3d_align)
enlarge_obj_array = random_shift_rotate_box3d(
enlarge_obj_array, 0.05)
box3d_corners_enlarge = compute_box_3d_obj_array(
enlarge_obj_array)
else:
box3d_corners_enlarge = compute_box_3d_obj_array(
enlarge_obj_array)
_, inds = extract_pc_in_box3d(pc_rect, box3d_corners_enlarge)
pc_in_cuboid = pc_rect[inds]
pc_box_image_coord = pc_image_coord[inds]
_, inds = extract_pc_in_box3d(pc_in_cuboid, box3d_pts_3d)
label = np.zeros((pc_in_cuboid.shape[0]))
label[inds] = 1
_, inds = extract_pc_in_box3d(pc_rect, box3d_pts_3d)
# print(np.sum(label), np.sum(inds))
# Get 3D BOX heading
heading_angle = obj.ry
# Get 3D BOX size
box3d_size = np.array([obj.l, obj.w, obj.h])
# Reject too far away object or object without points
if np.sum(label) == 0:
continue
box3d_center = enlarge_obj_array[:3]
frustum_angle = -1 * np.arctan2(box3d_center[2],
box3d_center[0])
id_list.append(data_idx)
box3d_list.append(box3d_pts_3d)
input_list.append(pc_in_cuboid)
label_list.append(label)
type_list.append(objects[obj_idx].type)
heading_list.append(heading_angle)
box3d_size_list.append(box3d_size)
frustum_angle_list.append(frustum_angle)
gt_box2d_list.append(box2d)
calib_list.append(calib.calib_dict)
enlarge_box3d_list.append(box3d_corners_enlarge)
enlarge_box3d_size_list.append(enlarge_obj_array[3:6])
enlarge_box3d_angle_list.append(enlarge_obj_array[-1])
# collect statistics
pos_cnt += np.sum(label)
all_cnt += pc_in_cuboid.shape[0]
print('total_objects %d' % len(id_list))
print('Average pos ratio: %f' % (pos_cnt / float(all_cnt)))
print('Average npoints: %f' % (float(all_cnt) / len(id_list)))
with open(output_filename, 'wb') as fp:
pickle.dump(id_list, fp, -1)
pickle.dump(box3d_list, fp, -1)
pickle.dump(input_list, fp, -1)
pickle.dump(label_list, fp, -1)
pickle.dump(type_list, fp, -1)
pickle.dump(heading_list, fp, -1)
pickle.dump(box3d_size_list, fp, -1)
pickle.dump(frustum_angle_list, fp, -1)
pickle.dump(gt_box2d_list, fp, -1)
pickle.dump(calib_list, fp, -1)
pickle.dump(enlarge_box3d_list, fp, -1)
pickle.dump(enlarge_box3d_size_list, fp, -1)
pickle.dump(enlarge_box3d_angle_list, fp, -1)
print('save in {}'.format(output_filename)) | [
"def",
"extract_frustum_data",
"(",
"idx_filename",
",",
"split",
",",
"output_filename",
",",
"perturb_box2d",
"=",
"False",
",",
"augmentX",
"=",
"1",
",",
"type_whitelist",
"=",
"[",
"'Car'",
"]",
",",
"remove_diff",
"=",
"False",
")",
":",
"dataset",
"="... | https://github.com/zhixinwang/frustum-convnet/blob/5b1508d3f2140c3c0dd6dd17b5606b532b7a5ec8/kitti/prepare_data_refine.py#L239-L403 | ||
prompt-toolkit/python-prompt-toolkit | e9eac2eb59ec385e81742fa2ac623d4b8de00925 | prompt_toolkit/application/application.py | python | Application.exit | (
self, *, exception: Union[BaseException, Type[BaseException]], style: str = ""
) | Exit with exception. | Exit with exception. | [
"Exit",
"with",
"exception",
"."
] | def exit(
self, *, exception: Union[BaseException, Type[BaseException]], style: str = ""
) -> None:
"Exit with exception." | [
"def",
"exit",
"(",
"self",
",",
"*",
",",
"exception",
":",
"Union",
"[",
"BaseException",
",",
"Type",
"[",
"BaseException",
"]",
"]",
",",
"style",
":",
"str",
"=",
"\"\"",
")",
"->",
"None",
":"
] | https://github.com/prompt-toolkit/python-prompt-toolkit/blob/e9eac2eb59ec385e81742fa2ac623d4b8de00925/prompt_toolkit/application/application.py#L1050-L1053 | ||
minio/minio-py | b3ba3bf99fe6b9ff2b28855550d6ab5345c134e3 | minio/lifecycleconfig.py | python | Rule.noncurrent_version_transition | (self) | return self._noncurrent_version_transition | Get noncurrent version transition. | Get noncurrent version transition. | [
"Get",
"noncurrent",
"version",
"transition",
"."
] | def noncurrent_version_transition(self):
"""Get noncurrent version transition."""
return self._noncurrent_version_transition | [
"def",
"noncurrent_version_transition",
"(",
"self",
")",
":",
"return",
"self",
".",
"_noncurrent_version_transition"
] | https://github.com/minio/minio-py/blob/b3ba3bf99fe6b9ff2b28855550d6ab5345c134e3/minio/lifecycleconfig.py#L284-L286 | |
XX-net/XX-Net | a9898cfcf0084195fb7e69b6bc834e59aecdf14f | code/default/lib/noarch/hyper/packages/hpack/hpack.py | python | Decoder._assert_valid_table_size | (self) | Check that the table size set by the encoder is lower than the maximum
we expect to have. | Check that the table size set by the encoder is lower than the maximum
we expect to have. | [
"Check",
"that",
"the",
"table",
"size",
"set",
"by",
"the",
"encoder",
"is",
"lower",
"than",
"the",
"maximum",
"we",
"expect",
"to",
"have",
"."
] | def _assert_valid_table_size(self):
"""
Check that the table size set by the encoder is lower than the maximum
we expect to have.
"""
if self.header_table_size > self.max_allowed_table_size:
raise InvalidTableSizeError(
"Encoder did not shrink table size to within the max"
) | [
"def",
"_assert_valid_table_size",
"(",
"self",
")",
":",
"if",
"self",
".",
"header_table_size",
">",
"self",
".",
"max_allowed_table_size",
":",
"raise",
"InvalidTableSizeError",
"(",
"\"Encoder did not shrink table size to within the max\"",
")"
] | https://github.com/XX-net/XX-Net/blob/a9898cfcf0084195fb7e69b6bc834e59aecdf14f/code/default/lib/noarch/hyper/packages/hpack/hpack.py#L524-L532 | ||
etetoolkit/ete | 2b207357dc2a40ccad7bfd8f54964472c72e4726 | ete3/nexml/_nexml.py | python | AbstractUncertainStateSet.exportAttributes | (self, outfile, level, already_processed, namespace_='', name_='AbstractUncertainStateSet') | [] | def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='AbstractUncertainStateSet'):
super(AbstractUncertainStateSet, self).exportAttributes(outfile, level, already_processed, namespace_, name_='AbstractUncertainStateSet') | [
"def",
"exportAttributes",
"(",
"self",
",",
"outfile",
",",
"level",
",",
"already_processed",
",",
"namespace_",
"=",
"''",
",",
"name_",
"=",
"'AbstractUncertainStateSet'",
")",
":",
"super",
"(",
"AbstractUncertainStateSet",
",",
"self",
")",
".",
"exportAtt... | https://github.com/etetoolkit/ete/blob/2b207357dc2a40ccad7bfd8f54964472c72e4726/ete3/nexml/_nexml.py#L10941-L10942 | ||||
tav/pylibs | 3c16b843681f54130ee6a022275289cadb2f2a69 | markdown/__init__.py | python | Markdown.convertFile | (self, input=None, output=None, encoding=None) | Converts a markdown file and returns the HTML as a unicode string.
Decodes the file using the provided encoding (defaults to utf-8),
passes the file content to markdown, and outputs the html to either
the provided stream or the file with provided name, using the same
encoding as the source file.
**Note:** This is the only place that decoding and encoding of unicode
takes place in Python-Markdown. (All other code is unicode-in /
unicode-out.)
Keyword arguments:
* input: Name of source text file.
* output: Name of output file. Writes to stdout if `None`.
* encoding: Encoding of input and output files. Defaults to utf-8. | Converts a markdown file and returns the HTML as a unicode string. | [
"Converts",
"a",
"markdown",
"file",
"and",
"returns",
"the",
"HTML",
"as",
"a",
"unicode",
"string",
"."
] | def convertFile(self, input=None, output=None, encoding=None):
"""Converts a markdown file and returns the HTML as a unicode string.
Decodes the file using the provided encoding (defaults to utf-8),
passes the file content to markdown, and outputs the html to either
the provided stream or the file with provided name, using the same
encoding as the source file.
**Note:** This is the only place that decoding and encoding of unicode
takes place in Python-Markdown. (All other code is unicode-in /
unicode-out.)
Keyword arguments:
* input: Name of source text file.
* output: Name of output file. Writes to stdout if `None`.
* encoding: Encoding of input and output files. Defaults to utf-8.
"""
encoding = encoding or "utf-8"
# Read the source
input_file = codecs.open(input, mode="r", encoding=encoding)
text = input_file.read()
input_file.close()
text = text.lstrip(u'\ufeff') # remove the byte-order mark
# Convert
html = self.convert(text)
# Write to file or stdout
if isinstance(output, (str, unicode)):
output_file = codecs.open(output, "w", encoding=encoding)
output_file.write(html)
output_file.close()
else:
output.write(html.encode(encoding)) | [
"def",
"convertFile",
"(",
"self",
",",
"input",
"=",
"None",
",",
"output",
"=",
"None",
",",
"encoding",
"=",
"None",
")",
":",
"encoding",
"=",
"encoding",
"or",
"\"utf-8\"",
"# Read the source",
"input_file",
"=",
"codecs",
".",
"open",
"(",
"input",
... | https://github.com/tav/pylibs/blob/3c16b843681f54130ee6a022275289cadb2f2a69/markdown/__init__.py#L420-L457 | ||
mathics/Mathics | 318e06dea8f1c70758a50cb2f95c9900150e3a68 | mathics/builtin/pympler/asizeof.py | python | Asizer.cutoff | (self) | return self._cutoff_ | Stats cutoff (int). | Stats cutoff (int). | [
"Stats",
"cutoff",
"(",
"int",
")",
"."
] | def cutoff(self):
"""Stats cutoff (int)."""
return self._cutoff_ | [
"def",
"cutoff",
"(",
"self",
")",
":",
"return",
"self",
".",
"_cutoff_"
] | https://github.com/mathics/Mathics/blob/318e06dea8f1c70758a50cb2f95c9900150e3a68/mathics/builtin/pympler/asizeof.py#L2293-L2295 | |
secynic/ipwhois | a5d5b65ce3b1d4b2c20bba2e981968f54e1b5e9e | ipwhois/ipwhois.py | python | IPWhois.lookup_rdap | (self, inc_raw=False, retry_count=3, depth=0,
excluded_entities=None, bootstrap=False,
rate_limit_timeout=120, extra_org_map=None,
inc_nir=True, nir_field_list=None, asn_methods=None,
get_asn_description=True, root_ent_check=True) | return results | The function for retrieving and parsing whois information for an IP
address via HTTP (RDAP).
**This is now the recommended method, as RDAP contains much better
information to parse.**
Args:
inc_raw (:obj:`bool`): Whether to include the raw whois results in
the returned dictionary. Defaults to False.
retry_count (:obj:`int`): The number of times to retry in case
socket errors, timeouts, connection resets, etc. are
encountered. Defaults to 3.
depth (:obj:`int`): How many levels deep to run queries when
additional referenced objects are found. Defaults to 0.
excluded_entities (:obj:`list`): Entity handles to not perform
lookups. Defaults to None.
bootstrap (:obj:`bool`): If True, performs lookups via ARIN
bootstrap rather than lookups based on ASN data. ASN lookups
are not performed and no output for any of the asn* fields is
provided. Defaults to False.
rate_limit_timeout (:obj:`int`): The number of seconds to wait
before retrying when a rate limit notice is returned via
rdap+json. Defaults to 120.
extra_org_map (:obj:`dict`): Dictionary mapping org handles to
RIRs. This is for limited cases where ARIN REST (ASN fallback
HTTP lookup) does not show an RIR as the org handle e.g., DNIC
(which is now the built in ORG_MAP) e.g., {'DNIC': 'arin'}.
Valid RIR values are (note the case-sensitive - this is meant
to match the REST result):
'ARIN', 'RIPE', 'apnic', 'lacnic', 'afrinic'
Defaults to None.
inc_nir (:obj:`bool`): Whether to retrieve NIR (National Internet
Registry) information, if registry is JPNIC (Japan) or KRNIC
(Korea). If True, extra network requests will be required.
If False, the information returned for JP or KR IPs is
severely restricted. Defaults to True.
nir_field_list (:obj:`list`): If provided and inc_nir, a list of
fields to parse:
['name', 'handle', 'country', 'address', 'postal_code',
'nameservers', 'created', 'updated', 'contacts']
If None, defaults to all.
asn_methods (:obj:`list`): ASN lookup types to attempt, in order.
If None, defaults to all ['dns', 'whois', 'http'].
get_asn_description (:obj:`bool`): Whether to run an additional
query when pulling ASN information via dns, in order to get
the ASN description. Defaults to True.
root_ent_check (:obj:`bool`): If True, will perform
additional RDAP HTTP queries for missing entity data at the
root level. Defaults to True.
Returns:
dict: The IP RDAP lookup results
::
{
'query' (str) - The IP address
'asn' (str) - The Autonomous System Number
'asn_date' (str) - The ASN Allocation date
'asn_registry' (str) - The assigned ASN registry
'asn_cidr' (str) - The assigned ASN CIDR
'asn_country_code' (str) - The assigned ASN country code
'asn_description' (str) - The ASN description
'entities' (list) - Entity handles referred by the top
level query.
'network' (dict) - Network information which consists of
the fields listed in the ipwhois.rdap._RDAPNetwork
dict.
'objects' (dict) - Mapping of entity handle->entity dict
which consists of the fields listed in the
ipwhois.rdap._RDAPEntity dict. The raw result is
included for each object if the inc_raw parameter
is True.
'raw' (dict) - Whois results in json format if the inc_raw
parameter is True.
'nir' (dict) - ipwhois.nir.NIRWhois results if inc_nir is
True.
} | The function for retrieving and parsing whois information for an IP
address via HTTP (RDAP). | [
"The",
"function",
"for",
"retrieving",
"and",
"parsing",
"whois",
"information",
"for",
"an",
"IP",
"address",
"via",
"HTTP",
"(",
"RDAP",
")",
"."
] | def lookup_rdap(self, inc_raw=False, retry_count=3, depth=0,
excluded_entities=None, bootstrap=False,
rate_limit_timeout=120, extra_org_map=None,
inc_nir=True, nir_field_list=None, asn_methods=None,
get_asn_description=True, root_ent_check=True):
"""
The function for retrieving and parsing whois information for an IP
address via HTTP (RDAP).
**This is now the recommended method, as RDAP contains much better
information to parse.**
Args:
inc_raw (:obj:`bool`): Whether to include the raw whois results in
the returned dictionary. Defaults to False.
retry_count (:obj:`int`): The number of times to retry in case
socket errors, timeouts, connection resets, etc. are
encountered. Defaults to 3.
depth (:obj:`int`): How many levels deep to run queries when
additional referenced objects are found. Defaults to 0.
excluded_entities (:obj:`list`): Entity handles to not perform
lookups. Defaults to None.
bootstrap (:obj:`bool`): If True, performs lookups via ARIN
bootstrap rather than lookups based on ASN data. ASN lookups
are not performed and no output for any of the asn* fields is
provided. Defaults to False.
rate_limit_timeout (:obj:`int`): The number of seconds to wait
before retrying when a rate limit notice is returned via
rdap+json. Defaults to 120.
extra_org_map (:obj:`dict`): Dictionary mapping org handles to
RIRs. This is for limited cases where ARIN REST (ASN fallback
HTTP lookup) does not show an RIR as the org handle e.g., DNIC
(which is now the built in ORG_MAP) e.g., {'DNIC': 'arin'}.
Valid RIR values are (note the case-sensitive - this is meant
to match the REST result):
'ARIN', 'RIPE', 'apnic', 'lacnic', 'afrinic'
Defaults to None.
inc_nir (:obj:`bool`): Whether to retrieve NIR (National Internet
Registry) information, if registry is JPNIC (Japan) or KRNIC
(Korea). If True, extra network requests will be required.
If False, the information returned for JP or KR IPs is
severely restricted. Defaults to True.
nir_field_list (:obj:`list`): If provided and inc_nir, a list of
fields to parse:
['name', 'handle', 'country', 'address', 'postal_code',
'nameservers', 'created', 'updated', 'contacts']
If None, defaults to all.
asn_methods (:obj:`list`): ASN lookup types to attempt, in order.
If None, defaults to all ['dns', 'whois', 'http'].
get_asn_description (:obj:`bool`): Whether to run an additional
query when pulling ASN information via dns, in order to get
the ASN description. Defaults to True.
root_ent_check (:obj:`bool`): If True, will perform
additional RDAP HTTP queries for missing entity data at the
root level. Defaults to True.
Returns:
dict: The IP RDAP lookup results
::
{
'query' (str) - The IP address
'asn' (str) - The Autonomous System Number
'asn_date' (str) - The ASN Allocation date
'asn_registry' (str) - The assigned ASN registry
'asn_cidr' (str) - The assigned ASN CIDR
'asn_country_code' (str) - The assigned ASN country code
'asn_description' (str) - The ASN description
'entities' (list) - Entity handles referred by the top
level query.
'network' (dict) - Network information which consists of
the fields listed in the ipwhois.rdap._RDAPNetwork
dict.
'objects' (dict) - Mapping of entity handle->entity dict
which consists of the fields listed in the
ipwhois.rdap._RDAPEntity dict. The raw result is
included for each object if the inc_raw parameter
is True.
'raw' (dict) - Whois results in json format if the inc_raw
parameter is True.
'nir' (dict) - ipwhois.nir.NIRWhois results if inc_nir is
True.
}
"""
from .rdap import RDAP
# Create the return dictionary.
results = {'nir': None}
asn_data = None
response = None
if not bootstrap:
# Retrieve the ASN information.
log.debug('ASN lookup for {0}'.format(self.address_str))
asn_data = self.ipasn.lookup(
inc_raw=inc_raw, retry_count=retry_count,
extra_org_map=extra_org_map, asn_methods=asn_methods,
get_asn_description=get_asn_description
)
# Add the ASN information to the return dictionary.
results.update(asn_data)
# Retrieve the RDAP data and parse.
rdap = RDAP(self.net)
log.debug('RDAP lookup for {0}'.format(self.address_str))
rdap_data = rdap.lookup(
inc_raw=inc_raw, retry_count=retry_count, asn_data=asn_data,
depth=depth, excluded_entities=excluded_entities,
response=response, bootstrap=bootstrap,
rate_limit_timeout=rate_limit_timeout,
root_ent_check=root_ent_check
)
# Add the RDAP information to the return dictionary.
results.update(rdap_data)
if inc_nir:
nir = None
if 'JP' == asn_data['asn_country_code']:
nir = 'jpnic'
elif 'KR' == asn_data['asn_country_code']:
nir = 'krnic'
if nir:
nir_whois = NIRWhois(self.net)
nir_data = nir_whois.lookup(
nir=nir, inc_raw=inc_raw, retry_count=retry_count,
response=None,
field_list=nir_field_list, is_offline=False
)
# Add the NIR information to the return dictionary.
results['nir'] = nir_data
return results | [
"def",
"lookup_rdap",
"(",
"self",
",",
"inc_raw",
"=",
"False",
",",
"retry_count",
"=",
"3",
",",
"depth",
"=",
"0",
",",
"excluded_entities",
"=",
"None",
",",
"bootstrap",
"=",
"False",
",",
"rate_limit_timeout",
"=",
"120",
",",
"extra_org_map",
"=",
... | https://github.com/secynic/ipwhois/blob/a5d5b65ce3b1d4b2c20bba2e981968f54e1b5e9e/ipwhois/ipwhois.py#L198-L337 | |
mylar3/mylar3 | fce4771c5b627f8de6868dd4ab6bc53f7b22d303 | lib/comictaggerlib/comicapi/filenameparser.py | python | FileNameParser.getIssueNumber | (self, filename) | return issue, start, end | Returns a tuple of issue number string, and start and end indexes in the filename
(The indexes will be used to split the string up for further parsing) | Returns a tuple of issue number string, and start and end indexes in the filename
(The indexes will be used to split the string up for further parsing) | [
"Returns",
"a",
"tuple",
"of",
"issue",
"number",
"string",
"and",
"start",
"and",
"end",
"indexes",
"in",
"the",
"filename",
"(",
"The",
"indexes",
"will",
"be",
"used",
"to",
"split",
"the",
"string",
"up",
"for",
"further",
"parsing",
")"
] | def getIssueNumber(self, filename):
"""Returns a tuple of issue number string, and start and end indexes in the filename
(The indexes will be used to split the string up for further parsing)
"""
found = False
issue = ''
start = 0
end = 0
# first, look for multiple "--", this means it's formatted differently
# from most:
if "--" in filename:
# the pattern seems to be that anything to left of the first "--"
# is the series name followed by issue
filename = re.sub("--.*", self.repl, filename)
elif "__" in filename:
# the pattern seems to be that anything to left of the first "__"
# is the series name followed by issue
filename = re.sub("__.*", self.repl, filename)
filename = filename.replace("+", " ")
# replace parenthetical phrases with spaces
filename = re.sub("\(.*?\)", self.repl, filename)
filename = re.sub("\[.*?\]", self.repl, filename)
# replace any name separators with spaces
filename = self.fixSpaces(filename)
# remove any "of NN" phrase with spaces (problem: this could break on
# some titles)
filename = re.sub("of [\d]+", self.repl, filename)
# print u"[{0}]".format(filename)
# we should now have a cleaned up filename version with all the words in
# the same positions as original filename
# make a list of each word and its position
word_list = list()
for m in re.finditer("\S+", filename):
word_list.append((m.group(0), m.start(), m.end()))
# remove the first word, since it can't be the issue number
if len(word_list) > 1:
word_list = word_list[1:]
else:
# only one word?? just bail.
return issue, start, end
# Now try to search for the likely issue number word in the list
# first look for a word with "#" followed by digits with optional suffix
# this is almost certainly the issue number
for w in reversed(word_list):
if re.match("#[-]?(([0-9]*\.[0-9]+|[0-9]+)(\w*))", w[0]):
found = True
break
# same as above but w/o a '#', and only look at the last word in the
# list
if not found:
w = word_list[-1]
if re.match("[-]?(([0-9]*\.[0-9]+|[0-9]+)(\w*))", w[0]):
found = True
# now try to look for a # followed by any characters
if not found:
for w in reversed(word_list):
if re.match("#\S+", w[0]):
found = True
break
if found:
issue = w[0]
start = w[1]
end = w[2]
if issue[0] == '#':
issue = issue[1:]
return issue, start, end | [
"def",
"getIssueNumber",
"(",
"self",
",",
"filename",
")",
":",
"found",
"=",
"False",
"issue",
"=",
"''",
"start",
"=",
"0",
"end",
"=",
"0",
"# first, look for multiple \"--\", this means it's formatted differently",
"# from most:",
"if",
"\"--\"",
"in",
"filenam... | https://github.com/mylar3/mylar3/blob/fce4771c5b627f8de6868dd4ab6bc53f7b22d303/lib/comictaggerlib/comicapi/filenameparser.py#L66-L148 | |
pyqt/examples | 843bb982917cecb2350b5f6d7f42c9b7fb142ec1 | src/pyqt-official/designer/plugins/widgets/polygonwidget.py | python | PolygonWidget.setOuterColor | (self, color) | [] | def setOuterColor(self, color):
self._outerColor = color
self.createGradient()
self.update() | [
"def",
"setOuterColor",
"(",
"self",
",",
"color",
")",
":",
"self",
".",
"_outerColor",
"=",
"color",
"self",
".",
"createGradient",
"(",
")",
"self",
".",
"update",
"(",
")"
] | https://github.com/pyqt/examples/blob/843bb982917cecb2350b5f6d7f42c9b7fb142ec1/src/pyqt-official/designer/plugins/widgets/polygonwidget.py#L177-L180 | ||||
entropy1337/infernal-twin | 10995cd03312e39a48ade0f114ebb0ae3a711bb8 | Modules/build/pillow/Scripts/pildriver.py | python | PILDriver.do_crop | (self) | usage: crop <int:left> <int:upper> <int:right> <int:lower> <image:pic1>
Crop and push a rectangular region from the current image. | usage: crop <int:left> <int:upper> <int:right> <int:lower> <image:pic1> | [
"usage",
":",
"crop",
"<int",
":",
"left",
">",
"<int",
":",
"upper",
">",
"<int",
":",
"right",
">",
"<int",
":",
"lower",
">",
"<image",
":",
"pic1",
">"
] | def do_crop(self):
"""usage: crop <int:left> <int:upper> <int:right> <int:lower> <image:pic1>
Crop and push a rectangular region from the current image.
"""
left = int(self.do_pop())
upper = int(self.do_pop())
right = int(self.do_pop())
lower = int(self.do_pop())
image = self.do_pop()
self.push(image.crop((left, upper, right, lower))) | [
"def",
"do_crop",
"(",
"self",
")",
":",
"left",
"=",
"int",
"(",
"self",
".",
"do_pop",
"(",
")",
")",
"upper",
"=",
"int",
"(",
"self",
".",
"do_pop",
"(",
")",
")",
"right",
"=",
"int",
"(",
"self",
".",
"do_pop",
"(",
")",
")",
"lower",
"... | https://github.com/entropy1337/infernal-twin/blob/10995cd03312e39a48ade0f114ebb0ae3a711bb8/Modules/build/pillow/Scripts/pildriver.py#L183-L193 | ||
theotherp/nzbhydra | 4b03d7f769384b97dfc60dade4806c0fc987514e | libs/passlib/utils/__init__.py | python | Base64Engine.encode_int64 | (self, value) | return self._encode_int(value, 64) | encode 64-bit integer -> 11 char hash64 string
this format is used primarily by des-crypt & variants to encode
the DES output value used as a checksum. | encode 64-bit integer -> 11 char hash64 string | [
"encode",
"64",
"-",
"bit",
"integer",
"-",
">",
"11",
"char",
"hash64",
"string"
] | def encode_int64(self, value):
"""encode 64-bit integer -> 11 char hash64 string
this format is used primarily by des-crypt & variants to encode
the DES output value used as a checksum.
"""
if value < 0 or value > 0xffffffffffffffff:
raise ValueError("value out of range")
return self._encode_int(value, 64) | [
"def",
"encode_int64",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"<",
"0",
"or",
"value",
">",
"0xffffffffffffffff",
":",
"raise",
"ValueError",
"(",
"\"value out of range\"",
")",
"return",
"self",
".",
"_encode_int",
"(",
"value",
",",
"64",
")... | https://github.com/theotherp/nzbhydra/blob/4b03d7f769384b97dfc60dade4806c0fc987514e/libs/passlib/utils/__init__.py#L1246-L1254 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.