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
deepfakes/faceswap
09c7d8aca3c608d1afad941ea78e9fd9b64d9219
tools/alignments/media.py
python
Frames.process_video
(self)
Dummy in frames for video
Dummy in frames for video
[ "Dummy", "in", "frames", "for", "video" ]
def process_video(self): """Dummy in frames for video """ logger.info("Loading video frames from %s", self.folder) vidname = os.path.splitext(os.path.basename(self.folder))[0] for i in range(self.count): idx = i + 1 # Keep filename format for outputted face filename = "{}_{:06d}".format(vidname, idx) retval = {"frame_fullname": "{}.png".format(filename), "frame_name": filename, "frame_extension": ".png"} logger.trace(retval) yield retval
[ "def", "process_video", "(", "self", ")", ":", "logger", ".", "info", "(", "\"Loading video frames from %s\"", ",", "self", ".", "folder", ")", "vidname", "=", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "self", ".",...
https://github.com/deepfakes/faceswap/blob/09c7d8aca3c608d1afad941ea78e9fd9b64d9219/tools/alignments/media.py#L328-L340
CGCookie/retopoflow
3d8b3a47d1d661f99ab0aeb21d31370bf15de35e
retopoflow/rfmesh/rfmesh.py
python
RFMesh.get_unselected_edges
(self)
return {self._wrap_bmedge(bme) for bme in self.bme.edges if bme.is_valid and not bme.select and not bme.hide}
[]
def get_unselected_edges(self): return {self._wrap_bmedge(bme) for bme in self.bme.edges if bme.is_valid and not bme.select and not bme.hide}
[ "def", "get_unselected_edges", "(", "self", ")", ":", "return", "{", "self", ".", "_wrap_bmedge", "(", "bme", ")", "for", "bme", "in", "self", ".", "bme", ".", "edges", "if", "bme", ".", "is_valid", "and", "not", "bme", ".", "select", "and", "not", "...
https://github.com/CGCookie/retopoflow/blob/3d8b3a47d1d661f99ab0aeb21d31370bf15de35e/retopoflow/rfmesh/rfmesh.py#L975-L976
jliljebl/flowblade
995313a509b80e99eb1ad550d945bdda5995093b
flowblade-trunk/Flowblade/rendergui.py
python
show_reverse_dialog
(media_file, default_range_render, _response_callback)
[]
def show_reverse_dialog(media_file, default_range_render, _response_callback): folder, file_name = os.path.split(media_file.path) if media_file.is_proxy_file: folder, file_name = os.path.split(media_file.second_file_path) name, ext = os.path.splitext(file_name) dialog = Gtk.Dialog(_("Render Reverse Motion Video File"), gui.editor_window.window, Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT, (Gtk.STOCK_CANCEL, Gtk.ResponseType.REJECT, _("Render"), Gtk.ResponseType.ACCEPT)) media_file_label = Gtk.Label(label=_("Source Media File: ")) media_name = Gtk.Label(label="<b>" + media_file.name + "</b>") media_name.set_use_markup(True) SOURCE_PAD = 8 SOURCE_HEIGHT = 20 mf_row = guiutils.get_left_justified_box([media_file_label, guiutils.pad_label(SOURCE_PAD, SOURCE_HEIGHT), media_name]) mark_in = Gtk.Label(label=_("<b>not set</b>")) mark_out = Gtk.Label(label=_("<b>not set</b>")) if media_file.mark_in != -1: mark_in = Gtk.Label(label="<b>" + utils.get_tc_string(media_file.mark_in) + "</b>") if media_file.mark_out != -1: mark_out = Gtk.Label(label="<b>" + utils.get_tc_string(media_file.mark_out) + "</b>") mark_in.set_use_markup(True) mark_out.set_use_markup(True) fb_widgets = utils.EmptyClass() fb_widgets.file_name = Gtk.Entry() fb_widgets.file_name.set_text(name + "_REVERSE") fb_widgets.extension_label = Gtk.Label() fb_widgets.extension_label.set_size_request(45, 20) name_row = Gtk.HBox(False, 4) name_row.pack_start(fb_widgets.file_name, True, True, 0) name_row.pack_start(fb_widgets.extension_label, False, False, 4) fb_widgets.out_folder = Gtk.FileChooserButton(_("Select Target Folder")) fb_widgets.out_folder.set_action(Gtk.FileChooserAction.SELECT_FOLDER) fb_widgets.out_folder.set_current_folder(folder) label = Gtk.Label(label=_("Speed %:")) adjustment = Gtk.Adjustment(value=float(-100), lower=float(-600), upper=float(-1), step_incr=float(1)) fb_widgets.hslider = Gtk.HScale() fb_widgets.hslider.set_adjustment(adjustment) fb_widgets.hslider.set_draw_value(False) spin = Gtk.SpinButton() spin.set_numeric(True) spin.set_adjustment(adjustment) fb_widgets.hslider.set_digits(0) spin.set_digits(0) slider_hbox = Gtk.HBox(False, 4) slider_hbox.pack_start(fb_widgets.hslider, True, True, 0) slider_hbox.pack_start(spin, False, False, 4) slider_hbox.set_size_request(450,35) hbox = Gtk.HBox(False, 2) hbox.pack_start(guiutils.pad_label(8, 8), False, False, 0) hbox.pack_start(slider_hbox, False, False, 0) profile_selector = ProfileSelector() profile_selector.set_initial_selection() profile_selector.widget.set_sensitive(True) fb_widgets.categories_combo = profile_selector.categories_combo quality_selector = RenderQualitySelector() fb_widgets.quality_cb = quality_selector.widget # Encoding encoding_selector = RenderEncodingSelector(quality_selector, fb_widgets.extension_label, None) encoding_selector.encoding_selection_changed() fb_widgets.encodings_cb = encoding_selector.widget objects_list = Gtk.TreeStore(str, bool) objects_list.append(None, [_("Full Source Length"), True]) if media_file.mark_in != -1 and media_file.mark_out != -1: range_available = True else: range_available = False objects_list.append(None, [_("Source Mark In to Mark Out"), range_available]) fb_widgets.render_range = Gtk.ComboBox.new_with_model(objects_list) renderer_text = Gtk.CellRendererText() fb_widgets.render_range.pack_start(renderer_text, True) fb_widgets.render_range.add_attribute(renderer_text, "text", 0) fb_widgets.render_range.add_attribute(renderer_text, 'sensitive', 1) if default_range_render == False: fb_widgets.render_range.set_active(0) else: fb_widgets.render_range.set_active(1) fb_widgets.render_range.show() # To update rendered length display clip_length = _get_rendered_slomo_clip_length(media_file, fb_widgets.render_range, 100) clip_length_label = Gtk.Label(label=utils.get_tc_string(clip_length)) fb_widgets.hslider.connect("value-changed", _reverse_speed_changed, media_file, fb_widgets.render_range, clip_length_label) fb_widgets.render_range.connect("changed", _reverse_range_changed, media_file, fb_widgets.hslider, clip_length_label) # Build gui vbox = Gtk.VBox(False, 2) vbox.pack_start(mf_row, False, False, 0) vbox.pack_start(guiutils.get_left_justified_box([Gtk.Label(label=_("Source Mark In: ")), guiutils.pad_label(SOURCE_PAD, SOURCE_HEIGHT), mark_in]), False, False, 0) vbox.pack_start(guiutils.get_left_justified_box([Gtk.Label(label=_("Source Mark Out: ")), guiutils.pad_label(SOURCE_PAD, SOURCE_HEIGHT), mark_out]), False, False, 0) vbox.pack_start(guiutils.pad_label(18, 12), False, False, 0) vbox.pack_start(label, False, False, 0) vbox.pack_start(hbox, False, False, 0) vbox.pack_start(guiutils.pad_label(18, 12), False, False, 0) vbox.pack_start(guiutils.get_two_column_box(Gtk.Label(label=_("Target File:")), name_row, 120), False, False, 0) vbox.pack_start(guiutils.get_two_column_box(Gtk.Label(label=_("Target Folder:")), fb_widgets.out_folder, 120), False, False, 0) vbox.pack_start(guiutils.get_two_column_box(Gtk.Label(label=_("Target Profile:")), fb_widgets.categories_combo.widget, 200), False, False, 0) vbox.pack_start(guiutils.get_two_column_box(Gtk.Label(label=_("Target Encoding:")), fb_widgets.encodings_cb, 200), False, False, 0) vbox.pack_start(guiutils.get_two_column_box(Gtk.Label(label=_("Target Quality:")), fb_widgets.quality_cb, 200), False, False, 0) vbox.pack_start(guiutils.pad_label(18, 12), False, False, 0) vbox.pack_start(guiutils.get_two_column_box(Gtk.Label(label=_("Render Range:")), fb_widgets.render_range, 180), False, False, 0) vbox.pack_start(guiutils.get_two_column_box(Gtk.Label(label=_("Rendered Clip Length:")), clip_length_label, 180), False, False, 0) alignment = guiutils.set_margins(vbox, 6, 24, 24, 24) dialog.vbox.pack_start(alignment, True, True, 0) dialogutils.set_outer_margins(dialog.vbox) dialogutils.default_behaviour(dialog) dialog.connect('response', _response_callback, fb_widgets, media_file) dialog.show_all()
[ "def", "show_reverse_dialog", "(", "media_file", ",", "default_range_render", ",", "_response_callback", ")", ":", "folder", ",", "file_name", "=", "os", ".", "path", ".", "split", "(", "media_file", ".", "path", ")", "if", "media_file", ".", "is_proxy_file", ...
https://github.com/jliljebl/flowblade/blob/995313a509b80e99eb1ad550d945bdda5995093b/flowblade-trunk/Flowblade/rendergui.py#L318-L448
gem/oq-engine
1bdb88f3914e390abcbd285600bfd39477aae47c
openquake/hazardlib/scalerel/gsc_offshore_thrusts.py
python
GSCOffshoreThrustsHGT.get_median_area
(self, mag, rake)
return (10.0 ** (-2.943 + 0.677 * mag)) * self.SEIS_WIDTH
The values are a function of magnitude.
The values are a function of magnitude.
[ "The", "values", "are", "a", "function", "of", "magnitude", "." ]
def get_median_area(self, mag, rake): """ The values are a function of magnitude. """ # thrust/reverse for HGT return (10.0 ** (-2.943 + 0.677 * mag)) * self.SEIS_WIDTH
[ "def", "get_median_area", "(", "self", ",", "mag", ",", "rake", ")", ":", "# thrust/reverse for HGT", "return", "(", "10.0", "**", "(", "-", "2.943", "+", "0.677", "*", "mag", ")", ")", "*", "self", ".", "SEIS_WIDTH" ]
https://github.com/gem/oq-engine/blob/1bdb88f3914e390abcbd285600bfd39477aae47c/openquake/hazardlib/scalerel/gsc_offshore_thrusts.py#L180-L185
bjmayor/hacker
e3ce2ad74839c2733b27dac6c0f495e0743e1866
venv/lib/python3.5/site-packages/mechanize/_clientcookie.py
python
user_domain_match
(A, B)
return False
For blocking/accepting domains. A and B may be host domain names or IP addresses.
For blocking/accepting domains.
[ "For", "blocking", "/", "accepting", "domains", "." ]
def user_domain_match(A, B): """For blocking/accepting domains. A and B may be host domain names or IP addresses. """ A = A.lower() B = B.lower() if not (liberal_is_HDN(A) and liberal_is_HDN(B)): if A == B: # equal IP addresses return True return False initial_dot = B.startswith(".") if initial_dot and A.endswith(B): return True if not initial_dot and A == B: return True return False
[ "def", "user_domain_match", "(", "A", ",", "B", ")", ":", "A", "=", "A", ".", "lower", "(", ")", "B", "=", "B", ".", "lower", "(", ")", "if", "not", "(", "liberal_is_HDN", "(", "A", ")", "and", "liberal_is_HDN", "(", "B", ")", ")", ":", "if", ...
https://github.com/bjmayor/hacker/blob/e3ce2ad74839c2733b27dac6c0f495e0743e1866/venv/lib/python3.5/site-packages/mechanize/_clientcookie.py#L130-L148
SteveDoyle2/pyNastran
eda651ac2d4883d95a34951f8a002ff94f642a1a
pyNastran/dev/bdf_vectorized/bdf.py
python
BDF._prepare_dmij
(self, card, card_obj, comment='')
adds a DMIJ
adds a DMIJ
[ "adds", "a", "DMIJ" ]
def _prepare_dmij(self, card, card_obj, comment=''): """adds a DMIJ""" self._prepare_dmix(DMIJ, self._add_dmij_object, card_obj, comment=comment)
[ "def", "_prepare_dmij", "(", "self", ",", "card", ",", "card_obj", ",", "comment", "=", "''", ")", ":", "self", ".", "_prepare_dmix", "(", "DMIJ", ",", "self", ".", "_add_dmij_object", ",", "card_obj", ",", "comment", "=", "comment", ")" ]
https://github.com/SteveDoyle2/pyNastran/blob/eda651ac2d4883d95a34951f8a002ff94f642a1a/pyNastran/dev/bdf_vectorized/bdf.py#L2106-L2108
securityclippy/elasticintel
aa08d3e9f5ab1c000128e95161139ce97ff0e334
intelbot/intelbot.py
python
LambdaBot.is_bot_msg
(self)
return False
return true if processed msg was sent by a bot :return:
return true if processed msg was sent by a bot :return:
[ "return", "true", "if", "processed", "msg", "was", "sent", "by", "a", "bot", ":", "return", ":" ]
def is_bot_msg(self): ''' return true if processed msg was sent by a bot :return: ''' if self.event.event.bot_id: return True return False
[ "def", "is_bot_msg", "(", "self", ")", ":", "if", "self", ".", "event", ".", "event", ".", "bot_id", ":", "return", "True", "return", "False" ]
https://github.com/securityclippy/elasticintel/blob/aa08d3e9f5ab1c000128e95161139ce97ff0e334/intelbot/intelbot.py#L141-L148
dickreuter/Poker
b7642f0277e267e1a44eab957c4c7d1d8f50f4ee
poker/vboxapi/__init__.py
python
ComifyName
(name)
return name[0].capitalize() + name[1:]
[]
def ComifyName(name): return name[0].capitalize() + name[1:]
[ "def", "ComifyName", "(", "name", ")", ":", "return", "name", "[", "0", "]", ".", "capitalize", "(", ")", "+", "name", "[", "1", ":", "]" ]
https://github.com/dickreuter/Poker/blob/b7642f0277e267e1a44eab957c4c7d1d8f50f4ee/poker/vboxapi/__init__.py#L216-L217
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
script/translations/migrate.py
python
apply_data_references
(to_migrate)
Apply references.
Apply references.
[ "Apply", "references", "." ]
def apply_data_references(to_migrate): """Apply references.""" for strings_file in INTEGRATIONS_DIR.glob("*/strings.json"): strings = json.loads(strings_file.read_text()) steps = strings.get("config", {}).get("step") if not steps: continue changed = False for step_data in steps.values(): step_data = step_data.get("data", {}) for key, value in step_data.items(): if key in to_migrate and value != to_migrate[key]: if key.split("_")[0].lower() in value.lower(): step_data[key] = to_migrate[key] changed = True elif value.startswith("[%key"): pass else: print( f"{strings_file}: Skipped swapping '{key}': '{value}' does not contain '{key}'" ) if not changed: continue strings_file.write_text(json.dumps(strings, indent=2))
[ "def", "apply_data_references", "(", "to_migrate", ")", ":", "for", "strings_file", "in", "INTEGRATIONS_DIR", ".", "glob", "(", "\"*/strings.json\"", ")", ":", "strings", "=", "json", ".", "loads", "(", "strings_file", ".", "read_text", "(", ")", ")", "steps",...
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/script/translations/migrate.py#L327-L356
PrefectHQ/prefect
67bdc94e2211726d99561f6f52614bec8970e981
src/prefect/tasks/kubernetes/secrets.py
python
KubernetesSecret.run
( self, secret_name: Optional[str] = None, secret_key: Optional[str] = None, namespace: str = "default", kube_kwargs: dict = None, kubernetes_api_key_secret: str = "KUBERNETES_API_KEY", )
return decoded_secret if self.cast is None else self.cast(decoded_secret)
Returns the value of an kubenetes secret after applying an optional `cast` function. Args: - secret_name (string, optional): The name of the kubernetes secret object - secret_key (string, optional): The key to look for in the kubernetes data - namespace (str, optional): The Kubernetes namespace to read the secret from, defaults to the `default` namespace. - kube_kwargs (dict, optional): Optional extra keyword arguments to pass to the Kubernetes API (e.g. `{"pretty": "...", "dry_run": "..."}`) - kubernetes_api_key_secret (str, optional): the name of the Prefect Secret which stored your Kubernetes API Key; this Secret must be a string and in BearerToken format Raises: - ValueError: if `raise_is_missing` is `True` and the kubernetes secret was not found. The value of secret_name and secret_key are mandatory as well
Returns the value of an kubenetes secret after applying an optional `cast` function.
[ "Returns", "the", "value", "of", "an", "kubenetes", "secret", "after", "applying", "an", "optional", "cast", "function", "." ]
def run( self, secret_name: Optional[str] = None, secret_key: Optional[str] = None, namespace: str = "default", kube_kwargs: dict = None, kubernetes_api_key_secret: str = "KUBERNETES_API_KEY", ): """ Returns the value of an kubenetes secret after applying an optional `cast` function. Args: - secret_name (string, optional): The name of the kubernetes secret object - secret_key (string, optional): The key to look for in the kubernetes data - namespace (str, optional): The Kubernetes namespace to read the secret from, defaults to the `default` namespace. - kube_kwargs (dict, optional): Optional extra keyword arguments to pass to the Kubernetes API (e.g. `{"pretty": "...", "dry_run": "..."}`) - kubernetes_api_key_secret (str, optional): the name of the Prefect Secret which stored your Kubernetes API Key; this Secret must be a string and in BearerToken format Raises: - ValueError: if `raise_is_missing` is `True` and the kubernetes secret was not found. The value of secret_name and secret_key are mandatory as well """ if not secret_name: raise ValueError("The name of a Kubernetes secret must be provided.") if not secret_key: raise ValueError("The key of the secret must be provided.") api_client = typing_cast( client.CoreV1Api, get_kubernetes_client("secret", kubernetes_api_key_secret), ) secret_data = api_client.read_namespaced_secret( name=secret_name, namespace=namespace ).data if secret_key not in secret_data: if self.raise_if_missing: raise ValueError(f"Cannot find the key {secret_key} in {secret_name} ") else: return None decoded_secret = base64.b64decode(secret_data[secret_key]).decode("utf8") return decoded_secret if self.cast is None else self.cast(decoded_secret)
[ "def", "run", "(", "self", ",", "secret_name", ":", "Optional", "[", "str", "]", "=", "None", ",", "secret_key", ":", "Optional", "[", "str", "]", "=", "None", ",", "namespace", ":", "str", "=", "\"default\"", ",", "kube_kwargs", ":", "dict", "=", "N...
https://github.com/PrefectHQ/prefect/blob/67bdc94e2211726d99561f6f52614bec8970e981/src/prefect/tasks/kubernetes/secrets.py#L76-L125
huggingface/transformers
623b4f7c63f60cce917677ee704d6c93ee960b4b
src/transformers/models/detr/modeling_detr.py
python
_expand
(tensor, length: int)
return tensor.unsqueeze(1).repeat(1, int(length), 1, 1, 1).flatten(0, 1)
[]
def _expand(tensor, length: int): return tensor.unsqueeze(1).repeat(1, int(length), 1, 1, 1).flatten(0, 1)
[ "def", "_expand", "(", "tensor", ",", "length", ":", "int", ")", ":", "return", "tensor", ".", "unsqueeze", "(", "1", ")", ".", "repeat", "(", "1", ",", "int", "(", "length", ")", ",", "1", ",", "1", ",", "1", ")", ".", "flatten", "(", "0", "...
https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/src/transformers/models/detr/modeling_detr.py#L1698-L1699
tjweir/liftbook
e977a7face13ade1a4558e1909a6951d2f8928dd
elyxer.py
python
MultiRowFormula.addempty
(self)
Add an empty row.
Add an empty row.
[ "Add", "an", "empty", "row", "." ]
def addempty(self): "Add an empty row." row = FormulaRow().setalignments(self.alignments) for alignment in self.alignments: cell = self.factory.create(FormulaCell).setalignment(alignment) cell.add(FormulaConstant(u' ')) row.add(cell) self.addrow(row)
[ "def", "addempty", "(", "self", ")", ":", "row", "=", "FormulaRow", "(", ")", ".", "setalignments", "(", "self", ".", "alignments", ")", "for", "alignment", "in", "self", ".", "alignments", ":", "cell", "=", "self", ".", "factory", ".", "create", "(", ...
https://github.com/tjweir/liftbook/blob/e977a7face13ade1a4558e1909a6951d2f8928dd/elyxer.py#L7300-L7307
JPStrydom/Crypto-Trading-Bot
94b5aab261a35d99bc044267baf4735f0ee3f89a
src/trader.py
python
Trader.buy_strategy
(self, coin_pair)
Applies the buy checks on the coin pair and handles the results appropriately :param coin_pair: Coin pair market to check (ex: BTC-ETH, BTC-FCT) :type coin_pair: str
Applies the buy checks on the coin pair and handles the results appropriately
[ "Applies", "the", "buy", "checks", "on", "the", "coin", "pair", "and", "handles", "the", "results", "appropriately" ]
def buy_strategy(self, coin_pair): """ Applies the buy checks on the coin pair and handles the results appropriately :param coin_pair: Coin pair market to check (ex: BTC-ETH, BTC-FCT) :type coin_pair: str """ if (len(self.Database.trades["trackedCoinPairs"]) >= self.trade_params["buy"]["maxOpenTrades"] or coin_pair in self.Database.trades["trackedCoinPairs"]): return rsi = self.calculate_rsi(coin_pair=coin_pair, period=14, unit=self.trade_params["tickerInterval"]) day_volume = self.get_current_24hr_volume(coin_pair) current_buy_price = self.get_current_price(coin_pair, "ask") if rsi is None: return if self.check_buy_parameters(rsi, day_volume, current_buy_price): buy_stats = { "rsi": rsi, "24HrVolume": day_volume } self.buy(coin_pair, self.trade_params["buy"]["btcAmount"], current_buy_price, buy_stats) elif "buy" in self.pause_params and rsi >= self.pause_params["buy"]["rsiThreshold"] > 0: self.Messenger.print_pause(coin_pair, [rsi, day_volume], self.pause_params["buy"]["pauseTime"], "buy") self.Database.pause_buy(coin_pair) else: self.Messenger.print_no_buy(coin_pair, rsi, day_volume, current_buy_price)
[ "def", "buy_strategy", "(", "self", ",", "coin_pair", ")", ":", "if", "(", "len", "(", "self", ".", "Database", ".", "trades", "[", "\"trackedCoinPairs\"", "]", ")", ">=", "self", ".", "trade_params", "[", "\"buy\"", "]", "[", "\"maxOpenTrades\"", "]", "...
https://github.com/JPStrydom/Crypto-Trading-Bot/blob/94b5aab261a35d99bc044267baf4735f0ee3f89a/src/trader.py#L70-L97
coderSkyChen/Action_Recognition_Zoo
92ec5ec3efeee852aec5c057798298cd3a8e58ae
model_zoo/models/slim/deployment/model_deploy.py
python
DeploymentConfig.clone_device
(self, clone_index)
return device
Device used to create the clone and all the ops inside the clone. Args: clone_index: Int, representing the clone_index. Returns: A value suitable for `tf.device()`. Raises: ValueError: if `clone_index` is greater or equal to the number of clones".
Device used to create the clone and all the ops inside the clone.
[ "Device", "used", "to", "create", "the", "clone", "and", "all", "the", "ops", "inside", "the", "clone", "." ]
def clone_device(self, clone_index): """Device used to create the clone and all the ops inside the clone. Args: clone_index: Int, representing the clone_index. Returns: A value suitable for `tf.device()`. Raises: ValueError: if `clone_index` is greater or equal to the number of clones". """ if clone_index >= self._num_clones: raise ValueError('clone_index must be less than num_clones') device = '' if self._num_ps_tasks > 0: device += self._worker_device if self._clone_on_cpu: device += '/device:CPU:0' else: if self._num_clones > 1: device += '/device:GPU:%d' % clone_index return device
[ "def", "clone_device", "(", "self", ",", "clone_index", ")", ":", "if", "clone_index", ">=", "self", ".", "_num_clones", ":", "raise", "ValueError", "(", "'clone_index must be less than num_clones'", ")", "device", "=", "''", "if", "self", ".", "_num_ps_tasks", ...
https://github.com/coderSkyChen/Action_Recognition_Zoo/blob/92ec5ec3efeee852aec5c057798298cd3a8e58ae/model_zoo/models/slim/deployment/model_deploy.py#L580-L602
seperman/deepdiff
7e5e9954d635423d691f37194f3d1d93d363a128
deepdiff/diff.py
python
DeepDiff._get_most_in_common_pairs_in_iterables
( self, hashes_added, hashes_removed, t1_hashtable, t2_hashtable, parents_ids, _original_type)
return pairs.copy()
Get the closest pairs between items that are removed and items that are added. returns a dictionary of hashes that are closest to each other. The dictionary is going to be symmetrical so any key will be a value too and otherwise. Note that due to the current reporting structure in DeepDiff, we don't compare an item that was added to an item that is in both t1 and t2. For example [{1, 2}, {4, 5, 6}] [{1, 2}, {1, 2, 3}] is only compared between {4, 5, 6} and {1, 2, 3} even though technically {1, 2, 3} is just one item different than {1, 2} Perhaps in future we can have a report key that is item duplicated and modified instead of just added.
Get the closest pairs between items that are removed and items that are added.
[ "Get", "the", "closest", "pairs", "between", "items", "that", "are", "removed", "and", "items", "that", "are", "added", "." ]
def _get_most_in_common_pairs_in_iterables( self, hashes_added, hashes_removed, t1_hashtable, t2_hashtable, parents_ids, _original_type): """ Get the closest pairs between items that are removed and items that are added. returns a dictionary of hashes that are closest to each other. The dictionary is going to be symmetrical so any key will be a value too and otherwise. Note that due to the current reporting structure in DeepDiff, we don't compare an item that was added to an item that is in both t1 and t2. For example [{1, 2}, {4, 5, 6}] [{1, 2}, {1, 2, 3}] is only compared between {4, 5, 6} and {1, 2, 3} even though technically {1, 2, 3} is just one item different than {1, 2} Perhaps in future we can have a report key that is item duplicated and modified instead of just added. """ cache_key = None if self._stats[DISTANCE_CACHE_ENABLED]: cache_key = combine_hashes_lists(items=[hashes_added, hashes_removed], prefix='pairs_cache') if cache_key in self._distance_cache: return self._distance_cache.get(cache_key).copy() # A dictionary of hashes to distances and each distance to an ordered set of hashes. # It tells us about the distance of each object from other objects. # And the objects with the same distances are grouped together in an ordered set. # It also includes a "max" key that is just the value of the biggest current distance in the # most_in_common_pairs dictionary. most_in_common_pairs = defaultdict(lambda: defaultdict(OrderedSetPlus)) pairs = dict_() pre_calced_distances = None if hashes_added and hashes_removed and np and len(hashes_added) > 1 and len(hashes_removed) > 1: # pre-calculates distances ONLY for 1D arrays whether an _original_type # was explicitly passed or a homogeneous array is detected. # Numpy is needed for this optimization. pre_calced_distances = self._precalculate_numpy_arrays_distance( hashes_added, hashes_removed, t1_hashtable, t2_hashtable, _original_type) if hashes_added and hashes_removed and self.iterable_compare_func and len(hashes_added) > 1 and len(hashes_removed) > 1: pre_calced_distances = self._precalculate_distance_by_custom_compare_func( hashes_added, hashes_removed, t1_hashtable, t2_hashtable, _original_type) for added_hash in hashes_added: for removed_hash in hashes_removed: added_hash_obj = t2_hashtable[added_hash] removed_hash_obj = t1_hashtable[removed_hash] # Loop is detected if id(removed_hash_obj.item) in parents_ids: continue _distance = None if pre_calced_distances: _distance = pre_calced_distances.get("{}--{}".format(added_hash, removed_hash)) if _distance is None: _distance = self._get_rough_distance_of_hashed_objs( added_hash, removed_hash, added_hash_obj, removed_hash_obj, _original_type) # Left for future debugging # print(f'{Fore.RED}distance of {added_hash_obj.item} and {removed_hash_obj.item}: {_distance}{Style.RESET_ALL}') # Discard potential pairs that are too far. if _distance >= self.cutoff_distance_for_pairs: continue pairs_of_item = most_in_common_pairs[added_hash] pairs_of_item[_distance].add(removed_hash) used_to_hashes = set() distances_to_from_hashes = defaultdict(OrderedSetPlus) for from_hash, distances_to_to_hashes in most_in_common_pairs.items(): # del distances_to_to_hashes['max'] for dist in distances_to_to_hashes: distances_to_from_hashes[dist].add(from_hash) for dist in sorted(distances_to_from_hashes.keys()): from_hashes = distances_to_from_hashes[dist] while from_hashes: from_hash = from_hashes.lpop() if from_hash not in used_to_hashes: to_hashes = most_in_common_pairs[from_hash][dist] while to_hashes: to_hash = to_hashes.lpop() if to_hash not in used_to_hashes: used_to_hashes.add(from_hash) used_to_hashes.add(to_hash) # Left for future debugging: # print(f'{bcolors.FAIL}Adding {t2_hashtable[from_hash].item} as a pairs of {t1_hashtable[to_hash].item} with distance of {dist}{bcolors.ENDC}') pairs[from_hash] = to_hash inverse_pairs = {v: k for k, v in pairs.items()} pairs.update(inverse_pairs) if cache_key and self._stats[DISTANCE_CACHE_ENABLED]: self._distance_cache.set(cache_key, value=pairs) return pairs.copy()
[ "def", "_get_most_in_common_pairs_in_iterables", "(", "self", ",", "hashes_added", ",", "hashes_removed", ",", "t1_hashtable", ",", "t2_hashtable", ",", "parents_ids", ",", "_original_type", ")", ":", "cache_key", "=", "None", "if", "self", ".", "_stats", "[", "DI...
https://github.com/seperman/deepdiff/blob/7e5e9954d635423d691f37194f3d1d93d363a128/deepdiff/diff.py#L849-L946
OWASP/Nettacker
0b79a5b4fc8762199e85dd086554d585e62c314a
database/models.py
python
Report.__repr__
(self)
return "<Report(id={0}, scan_unique_id={1}, date={2}, report_path_filename={3})>".format( self.id, self.scan_unique_id, self.date, self.report_path_filename )
returns a printable representation of the object of the class Report
returns a printable representation of the object of the class Report
[ "returns", "a", "printable", "representation", "of", "the", "object", "of", "the", "class", "Report" ]
def __repr__(self): """ returns a printable representation of the object of the class Report """ return "<Report(id={0}, scan_unique_id={1}, date={2}, report_path_filename={3})>".format( self.id, self.scan_unique_id, self.date, self.report_path_filename )
[ "def", "__repr__", "(", "self", ")", ":", "return", "\"<Report(id={0}, scan_unique_id={1}, date={2}, report_path_filename={3})>\"", ".", "format", "(", "self", ".", "id", ",", "self", ".", "scan_unique_id", ",", "self", ".", "date", ",", "self", ".", "report_path_fi...
https://github.com/OWASP/Nettacker/blob/0b79a5b4fc8762199e85dd086554d585e62c314a/database/models.py#L25-L34
PyCon/pycon
666c1444f1b550d539cf6e087c83e749eb2ebf0a
pycon/sponsorship/views.py
python
sponsor_zip_logo_files
(request)
return response
Return a zip file of sponsor web and print logos
Return a zip file of sponsor web and print logos
[ "Return", "a", "zip", "file", "of", "sponsor", "web", "and", "print", "logos" ]
def sponsor_zip_logo_files(request): """Return a zip file of sponsor web and print logos""" zip_stringio = StringIO() with ZipFile(zip_stringio, "w") as zipfile: for benefit_name, dir_name in (("Web logo", "web_logos"), ("Print logo", "print_logos"), ("Advertisement", "advertisement")): for level in SponsorLevel.objects.all(): level_name = level.name.lower().replace(" ", "_") for sponsor in Sponsor.objects.filter(level=level, active=True): sponsor_name = sponsor.name.lower().replace(" ", "_") full_dir = "/".join([dir_name, level_name, sponsor_name]) paths = _get_benefit_filenames(sponsor, benefit_name) for path in paths: modtime = time.gmtime(time.time()) fname = os.path.basename(path.name) zipinfo = ZipInfo(filename=full_dir + "/" + fname, date_time=modtime) zipfile.writestr(zipinfo, path.read()) response = HttpResponse(zip_stringio.getvalue(), content_type="application/zip") prefix = settings.CONFERENCE_URL_PREFIXES[settings.CONFERENCE_ID] response['Content-Disposition'] = \ 'attachment; filename="pycon_%s_sponsorlogos.zip"' % prefix return response
[ "def", "sponsor_zip_logo_files", "(", "request", ")", ":", "zip_stringio", "=", "StringIO", "(", ")", "with", "ZipFile", "(", "zip_stringio", ",", "\"w\"", ")", "as", "zipfile", ":", "for", "benefit_name", ",", "dir_name", "in", "(", "(", "\"Web logo\"", ","...
https://github.com/PyCon/pycon/blob/666c1444f1b550d539cf6e087c83e749eb2ebf0a/pycon/sponsorship/views.py#L159-L185
mozman/ezdxf
59d0fc2ea63f5cf82293428f5931da7e9f9718e9
src/ezdxf/lldxf/extendedtags.py
python
ExtendedTags.new_xdata
(self, appid: str, tags: "IterableTags" = None)
return xtags
Append a new XDATA block. Assumes that no XDATA block with the same `appid` already exist:: try: xdata = tags.get_xdata('EZDXF') except ValueError: xdata = tags.new_xdata('EZDXF')
Append a new XDATA block.
[ "Append", "a", "new", "XDATA", "block", "." ]
def new_xdata(self, appid: str, tags: "IterableTags" = None) -> Tags: """Append a new XDATA block. Assumes that no XDATA block with the same `appid` already exist:: try: xdata = tags.get_xdata('EZDXF') except ValueError: xdata = tags.new_xdata('EZDXF') """ xtags = Tags([DXFTag(XDATA_MARKER, appid)]) if tags is not None: xtags.extend(tuples_to_tags(tags)) self.xdata.append(xtags) return xtags
[ "def", "new_xdata", "(", "self", ",", "appid", ":", "str", ",", "tags", ":", "\"IterableTags\"", "=", "None", ")", "->", "Tags", ":", "xtags", "=", "Tags", "(", "[", "DXFTag", "(", "XDATA_MARKER", ",", "appid", ")", "]", ")", "if", "tags", "is", "n...
https://github.com/mozman/ezdxf/blob/59d0fc2ea63f5cf82293428f5931da7e9f9718e9/src/ezdxf/lldxf/extendedtags.py#L378-L392
SirFroweey/PyDark
617c2bfda360afa7750c4707ecacd4ec82fa29af
PyDark/net.py
python
ServerUDPProtocol.remove_iterable
(self, func)
Remove a registered function(class-method) that is running indefinetly on the server.
Remove a registered function(class-method) that is running indefinetly on the server.
[ "Remove", "a", "registered", "function", "(", "class", "-", "method", ")", "that", "is", "running", "indefinetly", "on", "the", "server", "." ]
def remove_iterable(self, func): """ Remove a registered function(class-method) that is running indefinetly on the server. """ try: self.iterables.remove(func) except ValueError: pass
[ "def", "remove_iterable", "(", "self", ",", "func", ")", ":", "try", ":", "self", ".", "iterables", ".", "remove", "(", "func", ")", "except", "ValueError", ":", "pass" ]
https://github.com/SirFroweey/PyDark/blob/617c2bfda360afa7750c4707ecacd4ec82fa29af/PyDark/net.py#L349-L356
Chaffelson/nipyapi
d3b186fd701ce308c2812746d98af9120955e810
nipyapi/nifi/models/remote_process_group_dto.py
python
RemoteProcessGroupDTO.position
(self)
return self._position
Gets the position of this RemoteProcessGroupDTO. The position of this component in the UI if applicable. :return: The position of this RemoteProcessGroupDTO. :rtype: PositionDTO
Gets the position of this RemoteProcessGroupDTO. The position of this component in the UI if applicable.
[ "Gets", "the", "position", "of", "this", "RemoteProcessGroupDTO", ".", "The", "position", "of", "this", "component", "in", "the", "UI", "if", "applicable", "." ]
def position(self): """ Gets the position of this RemoteProcessGroupDTO. The position of this component in the UI if applicable. :return: The position of this RemoteProcessGroupDTO. :rtype: PositionDTO """ return self._position
[ "def", "position", "(", "self", ")", ":", "return", "self", ".", "_position" ]
https://github.com/Chaffelson/nipyapi/blob/d3b186fd701ce308c2812746d98af9120955e810/nipyapi/nifi/models/remote_process_group_dto.py#L256-L264
clinton-hall/nzbToMedia
27669389216902d1085660167e7bda0bd8527ecf
libs/common/configobj/validate.py
python
is_tuple
(value, min=None, max=None)
return tuple(is_list(value, min, max))
Check that the value is a tuple of values. You can optionally specify the minimum and maximum number of members. It does no check on members. >>> vtor.check('tuple', ()) () >>> vtor.check('tuple', []) () >>> vtor.check('tuple', (1, 2)) (1, 2) >>> vtor.check('tuple', [1, 2]) (1, 2) >>> vtor.check('tuple(3)', (1, 2)) Traceback (most recent call last): VdtValueTooShortError: the value "(1, 2)" is too short. >>> vtor.check('tuple(max=5)', (1, 2, 3, 4, 5, 6)) Traceback (most recent call last): VdtValueTooLongError: the value "(1, 2, 3, 4, 5, 6)" is too long. >>> vtor.check('tuple(min=3, max=5)', (1, 2, 3, 4)) (1, 2, 3, 4) >>> vtor.check('tuple', 0) Traceback (most recent call last): VdtTypeError: the value "0" is of the wrong type. >>> vtor.check('tuple', '12') Traceback (most recent call last): VdtTypeError: the value "12" is of the wrong type.
Check that the value is a tuple of values.
[ "Check", "that", "the", "value", "is", "a", "tuple", "of", "values", "." ]
def is_tuple(value, min=None, max=None): """ Check that the value is a tuple of values. You can optionally specify the minimum and maximum number of members. It does no check on members. >>> vtor.check('tuple', ()) () >>> vtor.check('tuple', []) () >>> vtor.check('tuple', (1, 2)) (1, 2) >>> vtor.check('tuple', [1, 2]) (1, 2) >>> vtor.check('tuple(3)', (1, 2)) Traceback (most recent call last): VdtValueTooShortError: the value "(1, 2)" is too short. >>> vtor.check('tuple(max=5)', (1, 2, 3, 4, 5, 6)) Traceback (most recent call last): VdtValueTooLongError: the value "(1, 2, 3, 4, 5, 6)" is too long. >>> vtor.check('tuple(min=3, max=5)', (1, 2, 3, 4)) (1, 2, 3, 4) >>> vtor.check('tuple', 0) Traceback (most recent call last): VdtTypeError: the value "0" is of the wrong type. >>> vtor.check('tuple', '12') Traceback (most recent call last): VdtTypeError: the value "12" is of the wrong type. """ return tuple(is_list(value, min, max))
[ "def", "is_tuple", "(", "value", ",", "min", "=", "None", ",", "max", "=", "None", ")", ":", "return", "tuple", "(", "is_list", "(", "value", ",", "min", ",", "max", ")", ")" ]
https://github.com/clinton-hall/nzbToMedia/blob/27669389216902d1085660167e7bda0bd8527ecf/libs/common/configobj/validate.py#L1031-L1062
BLCM/BLCMods
a32ba4ce1d627acfd7bfa4c5d37c2cc30875df02
Borderlands 2 mods/Apocalyptech/Stalkers Use Shields/generate-mod.py
python
set_bi_item_pool
(hotfix_name, classname, index, item, level=None, prob=None, invbalance=None, scale=1)
Sets an entire BalancedItem structure
Sets an entire BalancedItem structure
[ "Sets", "an", "entire", "BalancedItem", "structure" ]
def set_bi_item_pool(hotfix_name, classname, index, item, level=None, prob=None, invbalance=None, scale=1): """ Sets an entire BalancedItem structure """ global mp if level is None: level = 'None' if prob is None: prob = 1 if invbalance: itmpool = 'None' invbal = "{}'{}'".format(invbalance, item) else: itmpool = "ItemPoolDefinition'{}'".format(item) invbal = 'None' mp.register_str(hotfix_name, """level {} set {} BalancedItems[{}] ( ItmPoolDefinition={}, InvBalanceDefinition={}, Probability=( BaseValueConstant={}, BaseValueAttribute=None, InitializationDefinition=None, BaseValueScaleConstant={} ), bDropOnDeath=True )""".format(level, classname, index, itmpool, invbal, prob, scale))
[ "def", "set_bi_item_pool", "(", "hotfix_name", ",", "classname", ",", "index", ",", "item", ",", "level", "=", "None", ",", "prob", "=", "None", ",", "invbalance", "=", "None", ",", "scale", "=", "1", ")", ":", "global", "mp", "if", "level", "is", "N...
https://github.com/BLCM/BLCMods/blob/a32ba4ce1d627acfd7bfa4c5d37c2cc30875df02/Borderlands 2 mods/Apocalyptech/Stalkers Use Shields/generate-mod.py#L299-L328
mravanelli/pytorch-kaldi
9773257d4c4edb8bd9a2dcd8c81afa2a4ab9da07
data_io.py
python
read_vec_flt_ark
(file_or_fd, output_folder)
generator(key,vec) = read_vec_flt_ark(file_or_fd) Create generator of (key,vector<float>) tuples, reading from an ark file/stream. file_or_fd : ark, gzipped ark, pipe or opened file descriptor. Read ark to a 'dictionary': d = { u:d for u,d in kaldi_io.read_vec_flt_ark(file) }
generator(key,vec) = read_vec_flt_ark(file_or_fd) Create generator of (key,vector<float>) tuples, reading from an ark file/stream. file_or_fd : ark, gzipped ark, pipe or opened file descriptor.
[ "generator", "(", "key", "vec", ")", "=", "read_vec_flt_ark", "(", "file_or_fd", ")", "Create", "generator", "of", "(", "key", "vector<float", ">", ")", "tuples", "reading", "from", "an", "ark", "file", "/", "stream", ".", "file_or_fd", ":", "ark", "gzippe...
def read_vec_flt_ark(file_or_fd, output_folder): """ generator(key,vec) = read_vec_flt_ark(file_or_fd) Create generator of (key,vector<float>) tuples, reading from an ark file/stream. file_or_fd : ark, gzipped ark, pipe or opened file descriptor. Read ark to a 'dictionary': d = { u:d for u,d in kaldi_io.read_vec_flt_ark(file) } """ fd = open_or_fd(file_or_fd, output_folder) try: key = read_key(fd) while key: ali = read_vec_flt(fd, output_folder) yield key, ali key = read_key(fd) finally: if fd is not file_or_fd: fd.close()
[ "def", "read_vec_flt_ark", "(", "file_or_fd", ",", "output_folder", ")", ":", "fd", "=", "open_or_fd", "(", "file_or_fd", ",", "output_folder", ")", "try", ":", "key", "=", "read_key", "(", "fd", ")", "while", "key", ":", "ali", "=", "read_vec_flt", "(", ...
https://github.com/mravanelli/pytorch-kaldi/blob/9773257d4c4edb8bd9a2dcd8c81afa2a4ab9da07/data_io.py#L902-L919
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-windows/x86/tornado/web.py
python
RequestHandler.write
(self, chunk: Union[str, bytes, dict])
Writes the given chunk to the output buffer. To write the output to the network, use the `flush()` method below. If the given chunk is a dictionary, we write it as JSON and set the Content-Type of the response to be ``application/json``. (if you want to send JSON as a different ``Content-Type``, call ``set_header`` *after* calling ``write()``). Note that lists are not converted to JSON because of a potential cross-site security vulnerability. All JSON output should be wrapped in a dictionary. More details at http://haacked.com/archive/2009/06/25/json-hijacking.aspx/ and https://github.com/facebook/tornado/issues/1009
Writes the given chunk to the output buffer.
[ "Writes", "the", "given", "chunk", "to", "the", "output", "buffer", "." ]
def write(self, chunk: Union[str, bytes, dict]) -> None: """Writes the given chunk to the output buffer. To write the output to the network, use the `flush()` method below. If the given chunk is a dictionary, we write it as JSON and set the Content-Type of the response to be ``application/json``. (if you want to send JSON as a different ``Content-Type``, call ``set_header`` *after* calling ``write()``). Note that lists are not converted to JSON because of a potential cross-site security vulnerability. All JSON output should be wrapped in a dictionary. More details at http://haacked.com/archive/2009/06/25/json-hijacking.aspx/ and https://github.com/facebook/tornado/issues/1009 """ if self._finished: raise RuntimeError("Cannot write() after finish()") if not isinstance(chunk, (bytes, unicode_type, dict)): message = "write() only accepts bytes, unicode, and dict objects" if isinstance(chunk, list): message += ( ". Lists not accepted for security reasons; see " + "http://www.tornadoweb.org/en/stable/web.html#tornado.web.RequestHandler.write" # noqa: E501 ) raise TypeError(message) if isinstance(chunk, dict): chunk = escape.json_encode(chunk) self.set_header("Content-Type", "application/json; charset=UTF-8") chunk = utf8(chunk) self._write_buffer.append(chunk)
[ "def", "write", "(", "self", ",", "chunk", ":", "Union", "[", "str", ",", "bytes", ",", "dict", "]", ")", "->", "None", ":", "if", "self", ".", "_finished", ":", "raise", "RuntimeError", "(", "\"Cannot write() after finish()\"", ")", "if", "not", "isinst...
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-windows/x86/tornado/web.py#L809-L839
jython/frozen-mirror
b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99
lib-python/2.7/lib-tk/Tkinter.py
python
Text.tag_nextrange
(self, tagName, index1, index2=None)
return self.tk.splitlist(self.tk.call( self._w, 'tag', 'nextrange', tagName, index1, index2))
Return a list of start and end index for the first sequence of characters between INDEX1 and INDEX2 which all have tag TAGNAME. The text is searched forward from INDEX1.
Return a list of start and end index for the first sequence of characters between INDEX1 and INDEX2 which all have tag TAGNAME. The text is searched forward from INDEX1.
[ "Return", "a", "list", "of", "start", "and", "end", "index", "for", "the", "first", "sequence", "of", "characters", "between", "INDEX1", "and", "INDEX2", "which", "all", "have", "tag", "TAGNAME", ".", "The", "text", "is", "searched", "forward", "from", "IN...
def tag_nextrange(self, tagName, index1, index2=None): """Return a list of start and end index for the first sequence of characters between INDEX1 and INDEX2 which all have tag TAGNAME. The text is searched forward from INDEX1.""" return self.tk.splitlist(self.tk.call( self._w, 'tag', 'nextrange', tagName, index1, index2))
[ "def", "tag_nextrange", "(", "self", ",", "tagName", ",", "index1", ",", "index2", "=", "None", ")", ":", "return", "self", ".", "tk", ".", "splitlist", "(", "self", ".", "tk", ".", "call", "(", "self", ".", "_w", ",", "'tag'", ",", "'nextrange'", ...
https://github.com/jython/frozen-mirror/blob/b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99/lib-python/2.7/lib-tk/Tkinter.py#L3141-L3146
cyberark/KubiScan
cb2afebde8080ad6de458f9e013003d9da10278e
api/api_client_temp.py
python
ApiClientTemp.__deserialize_date
(self, string)
Deserializes string to date. :param string: str. :return: date.
Deserializes string to date.
[ "Deserializes", "string", "to", "date", "." ]
def __deserialize_date(self, string): """ Deserializes string to date. :param string: str. :return: date. """ try: from dateutil.parser import parse return parse(string).date() except ImportError: return string except ValueError: raise ApiException( status=0, reason="Failed to parse `{0}` into a date object".format(string) )
[ "def", "__deserialize_date", "(", "self", ",", "string", ")", ":", "try", ":", "from", "dateutil", ".", "parser", "import", "parse", "return", "parse", "(", "string", ")", ".", "date", "(", ")", "except", "ImportError", ":", "return", "string", "except", ...
https://github.com/cyberark/KubiScan/blob/cb2afebde8080ad6de458f9e013003d9da10278e/api/api_client_temp.py#L565-L581
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/quopri.py
python
encode
(input, output, quotetabs, header = 0)
Read 'input', apply quoted-printable encoding, and write to 'output'. 'input' and 'output' are files with readline() and write() methods. The 'quotetabs' flag indicates whether embedded tabs and spaces should be quoted. Note that line-ending tabs and spaces are always encoded, as per RFC 1521. The 'header' flag indicates whether we are encoding spaces as _ as per RFC 1522.
Read 'input', apply quoted-printable encoding, and write to 'output'.
[ "Read", "input", "apply", "quoted", "-", "printable", "encoding", "and", "write", "to", "output", "." ]
def encode(input, output, quotetabs, header = 0): """Read 'input', apply quoted-printable encoding, and write to 'output'. 'input' and 'output' are files with readline() and write() methods. The 'quotetabs' flag indicates whether embedded tabs and spaces should be quoted. Note that line-ending tabs and spaces are always encoded, as per RFC 1521. The 'header' flag indicates whether we are encoding spaces as _ as per RFC 1522. """ if b2a_qp is not None: data = input.read() odata = b2a_qp(data, quotetabs = quotetabs, header = header) output.write(odata) return def write(s, output=output, lineEnd='\n'): # RFC 1521 requires that the line ending in a space or tab must have # that trailing character encoded. if s and s[-1:] in ' \t': output.write(s[:-1] + quote(s[-1]) + lineEnd) elif s == '.': output.write(quote(s) + lineEnd) else: output.write(s + lineEnd) prevline = None while 1: line = input.readline() if not line: break outline = [] # Strip off any readline induced trailing newline stripped = '' if line[-1:] == '\n': line = line[:-1] stripped = '\n' # Calculate the un-length-limited encoded line for c in line: if needsquoting(c, quotetabs, header): c = quote(c) if header and c == ' ': outline.append('_') else: outline.append(c) # First, write out the previous line if prevline is not None: write(prevline) # Now see if we need any soft line breaks because of RFC-imposed # length limitations. Then do the thisline->prevline dance. thisline = EMPTYSTRING.join(outline) while len(thisline) > MAXLINESIZE: # Don't forget to include the soft line break `=' sign in the # length calculation! write(thisline[:MAXLINESIZE-1], lineEnd='=\n') thisline = thisline[MAXLINESIZE-1:] # Write out the current line prevline = thisline # Write out the last line, without a trailing newline if prevline is not None: write(prevline, lineEnd=stripped)
[ "def", "encode", "(", "input", ",", "output", ",", "quotetabs", ",", "header", "=", "0", ")", ":", "if", "b2a_qp", "is", "not", "None", ":", "data", "=", "input", ".", "read", "(", ")", "odata", "=", "b2a_qp", "(", "data", ",", "quotetabs", "=", ...
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/quopri.py#L42-L103
spotify/chartify
5ac3a88e54cf620389741f396cc19d60fe032822
chartify/examples.py
python
plot_text
()
Text example
Text example
[ "Text", "example" ]
def plot_text(): """ Text example """ import chartify data = chartify.examples.example_data() # Manipulate the data price_and_quantity_by_country = ( data.groupby('country')[['total_price', 'quantity']].sum() .reset_index()) print(price_and_quantity_by_country.head()) """Print break""" _text_example_1(price_and_quantity_by_country)
[ "def", "plot_text", "(", ")", ":", "import", "chartify", "data", "=", "chartify", ".", "examples", ".", "example_data", "(", ")", "# Manipulate the data", "price_and_quantity_by_country", "=", "(", "data", ".", "groupby", "(", "'country'", ")", "[", "[", "'tot...
https://github.com/spotify/chartify/blob/5ac3a88e54cf620389741f396cc19d60fe032822/chartify/examples.py#L232-L246
gnuradio/pybombs
17044241bf835b93571026b112f179f2db7448a4
pybombs/packagers/yum.py
python
ExternalYumDnf.get_available_version
(self, pkgname)
return False
Return a version that we can install through this package manager.
Return a version that we can install through this package manager.
[ "Return", "a", "version", "that", "we", "can", "install", "through", "this", "package", "manager", "." ]
def get_available_version(self, pkgname): """ Return a version that we can install through this package manager. """ try: ver = subproc.match_output( [self.command, "info", pkgname], r'^Version\s+:\s+(?P<ver>.*$)', 'ver', env=utils.dict_merge(os.environ, {'LC_ALL': 'C'}), ) if ver is None: return False self.log.debug("Package {0} has version {1} in {2}".format(pkgname, ver, self.command)) return ver except subprocess.CalledProcessError as ex: # This usually means the package was not found, so don't worry self.log.trace("`{0} info' returned non-zero exit status.".format(self.command)) self.log.trace(str(ex)) return False except Exception as ex: self.log.error("Error parsing {0} info".format(self.command)) self.log.error(str(ex)) return False
[ "def", "get_available_version", "(", "self", ",", "pkgname", ")", ":", "try", ":", "ver", "=", "subproc", ".", "match_output", "(", "[", "self", ".", "command", ",", "\"info\"", ",", "pkgname", "]", ",", "r'^Version\\s+:\\s+(?P<ver>.*$)'", ",", "'ver'", ",",...
https://github.com/gnuradio/pybombs/blob/17044241bf835b93571026b112f179f2db7448a4/pybombs/packagers/yum.py#L45-L68
MobSF/Mobile-Security-Framework-MobSF
33abc69b54689fb535c72c720b593dc7ed21a4cf
mobsf/DynamicAnalyzer/views/android/frida_core.py
python
Frida.frida_response
(self, message, data)
Function to handle frida responses.
Function to handle frida responses.
[ "Function", "to", "handle", "frida", "responses", "." ]
def frida_response(self, message, data): """Function to handle frida responses.""" if 'payload' in message: msg = message['payload'] api_mon = 'MobSF-API-Monitor: ' aux = '[AUXILIARY] ' deps = '[RUNTIME-DEPS] ' if not isinstance(msg, str): msg = str(msg) if msg.startswith(api_mon): self.write_log(self.api_mon, msg.replace(api_mon, '')) elif msg.startswith(deps): info = msg.replace(deps, '') + '\n' self.write_log(self.deps, info) self.write_log(self.frida_log, info) elif msg.startswith(aux): self.write_log(self.frida_log, msg.replace(aux, '[*] ') + '\n') else: logger.debug('[Frida] %s', msg) self.write_log(self.frida_log, msg + '\n') else: logger.error('[Frida] %s', message)
[ "def", "frida_response", "(", "self", ",", "message", ",", "data", ")", ":", "if", "'payload'", "in", "message", ":", "msg", "=", "message", "[", "'payload'", "]", "api_mon", "=", "'MobSF-API-Monitor: '", "aux", "=", "'[AUXILIARY] '", "deps", "=", "'[RUNTIME...
https://github.com/MobSF/Mobile-Security-Framework-MobSF/blob/33abc69b54689fb535c72c720b593dc7ed21a4cf/mobsf/DynamicAnalyzer/views/android/frida_core.py#L97-L119
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/helpers/template.py
python
average
(*args: Any)
return statistics.fmean(args)
Filter and function to calculate the arithmetic mean of an iterable or of two or more arguments. The parameters may be passed as an iterable or as separate arguments.
Filter and function to calculate the arithmetic mean of an iterable or of two or more arguments.
[ "Filter", "and", "function", "to", "calculate", "the", "arithmetic", "mean", "of", "an", "iterable", "or", "of", "two", "or", "more", "arguments", "." ]
def average(*args: Any) -> float: """ Filter and function to calculate the arithmetic mean of an iterable or of two or more arguments. The parameters may be passed as an iterable or as separate arguments. """ if len(args) == 0: raise TypeError("average expected at least 1 argument, got 0") if len(args) == 1: if isinstance(args[0], Iterable): return statistics.fmean(args[0]) raise TypeError(f"'{type(args[0]).__name__}' object is not iterable") return statistics.fmean(args)
[ "def", "average", "(", "*", "args", ":", "Any", ")", "->", "float", ":", "if", "len", "(", "args", ")", "==", "0", ":", "raise", "TypeError", "(", "\"average expected at least 1 argument, got 0\"", ")", "if", "len", "(", "args", ")", "==", "1", ":", "i...
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/helpers/template.py#L1552-L1567
ConvLab/ConvLab
a04582a77537c1a706fbf64715baa9ad0be1301a
convlab/modules/policy/user/multiwoz/policy_agenda_multiwoz.py
python
Goal.__init__
(self, goal_generator: GoalGenerator, seed=None)
create new Goal by random Args: goal_generator (GoalGenerator): Goal Gernerator.
create new Goal by random Args: goal_generator (GoalGenerator): Goal Gernerator.
[ "create", "new", "Goal", "by", "random", "Args", ":", "goal_generator", "(", "GoalGenerator", ")", ":", "Goal", "Gernerator", "." ]
def __init__(self, goal_generator: GoalGenerator, seed=None): """ create new Goal by random Args: goal_generator (GoalGenerator): Goal Gernerator. """ self.domain_goals = goal_generator.get_user_goal(seed) self.domains = list(self.domain_goals['domain_ordering']) del self.domain_goals['domain_ordering'] for domain in self.domains: if 'reqt' in self.domain_goals[domain].keys(): self.domain_goals[domain]['reqt'] = {slot: DEF_VAL_UNK for slot in self.domain_goals[domain]['reqt']} if 'book' in self.domain_goals[domain].keys(): self.domain_goals[domain]['booked'] = DEF_VAL_UNK
[ "def", "__init__", "(", "self", ",", "goal_generator", ":", "GoalGenerator", ",", "seed", "=", "None", ")", ":", "self", ".", "domain_goals", "=", "goal_generator", ".", "get_user_goal", "(", "seed", ")", "self", ".", "domains", "=", "list", "(", "self", ...
https://github.com/ConvLab/ConvLab/blob/a04582a77537c1a706fbf64715baa9ad0be1301a/convlab/modules/policy/user/multiwoz/policy_agenda_multiwoz.py#L276-L292
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/sqlalchemy/orm/base.py
python
manager_of_class
(cls)
return cls.__dict__.get(DEFAULT_MANAGER_ATTR, None)
[]
def manager_of_class(cls): return cls.__dict__.get(DEFAULT_MANAGER_ATTR, None)
[ "def", "manager_of_class", "(", "cls", ")", ":", "return", "cls", ".", "__dict__", ".", "get", "(", "DEFAULT_MANAGER_ATTR", ",", "None", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/sqlalchemy/orm/base.py#L208-L209
bitcraze/crazyflie-lib-python
876f0dc003b91ba5e4de05daae9d0b79cf600f81
examples/positioning/initial_position.py
python
reset_estimator
(scf)
[]
def reset_estimator(scf): cf = scf.cf cf.param.set_value('kalman.resetEstimation', '1') time.sleep(0.1) cf.param.set_value('kalman.resetEstimation', '0') wait_for_position_estimator(cf)
[ "def", "reset_estimator", "(", "scf", ")", ":", "cf", "=", "scf", ".", "cf", "cf", ".", "param", ".", "set_value", "(", "'kalman.resetEstimation'", ",", "'1'", ")", "time", ".", "sleep", "(", "0.1", ")", "cf", ".", "param", ".", "set_value", "(", "'k...
https://github.com/bitcraze/crazyflie-lib-python/blob/876f0dc003b91ba5e4de05daae9d0b79cf600f81/examples/positioning/initial_position.py#L110-L116
JaniceWuo/MovieRecommend
4c86db64ca45598917d304f535413df3bc9fea65
movierecommend/venv1/Lib/site-packages/django/template/utils.py
python
EngineHandler.all
(self)
return [self[alias] for alias in self]
[]
def all(self): return [self[alias] for alias in self]
[ "def", "all", "(", "self", ")", ":", "return", "[", "self", "[", "alias", "]", "for", "alias", "in", "self", "]" ]
https://github.com/JaniceWuo/MovieRecommend/blob/4c86db64ca45598917d304f535413df3bc9fea65/movierecommend/venv1/Lib/site-packages/django/template/utils.py#L88-L89
SheffieldML/GPy
bb1bc5088671f9316bc92a46d356734e34c2d5c0
GPy/core/gp_grid.py
python
GpGrid.kron_mmprod
(self, A, B)
return result
[]
def kron_mmprod(self, A, B): count = 0 D = len(A) for b in (B.T): x = b N = 1 G = np.zeros(D, dtype=np.int_) for d in range(D): G[d] = len(A[d]) N = np.prod(G) for d in range(D-1, -1, -1): X = np.reshape(x, (G[d], int(np.round(N/G[d]))), order='F') Z = np.dot(A[d], X) Z = Z.T x = np.reshape(Z, (-1, 1), order='F') if (count == 0): result = x else: result = np.column_stack((result, x)) count+=1 return result
[ "def", "kron_mmprod", "(", "self", ",", "A", ",", "B", ")", ":", "count", "=", "0", "D", "=", "len", "(", "A", ")", "for", "b", "in", "(", "B", ".", "T", ")", ":", "x", "=", "b", "N", "=", "1", "G", "=", "np", ".", "zeros", "(", "D", ...
https://github.com/SheffieldML/GPy/blob/bb1bc5088671f9316bc92a46d356734e34c2d5c0/GPy/core/gp_grid.py#L65-L85
bitcoin-abe/bitcoin-abe
33513dc8025cb08df85fc6bf41fa35eb9daa1a33
Abe/DataStore.py
python
DataStore.export_block
(store, chain=None, block_hash=None, block_number=None)
return b
Return a dict with the following: * chain_candidates[] * chain * in_longest * chain_satoshis * chain_satoshi_seconds * chain_work * fees * generated * hash * hashMerkleRoot * hashPrev * height * nBits * next_block_hashes * nNonce * nTime * satoshis_destroyed * satoshi_seconds * transactions[] * fees * hash * in[] * address_version * binaddr * value * out[] * address_version * binaddr * value * size * value_out * version Additionally, for multisig inputs and outputs: * subbinaddr[] * required_signatures Additionally, for proof-of-stake chains: * is_proof_of_stake * proof_of_stake_generated
Return a dict with the following:
[ "Return", "a", "dict", "with", "the", "following", ":" ]
def export_block(store, chain=None, block_hash=None, block_number=None): """ Return a dict with the following: * chain_candidates[] * chain * in_longest * chain_satoshis * chain_satoshi_seconds * chain_work * fees * generated * hash * hashMerkleRoot * hashPrev * height * nBits * next_block_hashes * nNonce * nTime * satoshis_destroyed * satoshi_seconds * transactions[] * fees * hash * in[] * address_version * binaddr * value * out[] * address_version * binaddr * value * size * value_out * version Additionally, for multisig inputs and outputs: * subbinaddr[] * required_signatures Additionally, for proof-of-stake chains: * is_proof_of_stake * proof_of_stake_generated """ if block_number is None and block_hash is None: raise ValueError("export_block requires either block_hash or block_number") where = [] bind = [] if chain is not None: where.append('chain_id = ?') bind.append(chain.id) if block_hash is not None: where.append('block_hash = ?') bind.append(store.hashin_hex(block_hash)) if block_number is not None: where.append('block_height = ? AND in_longest = 1') bind.append(block_number) sql = """ SELECT chain_id, in_longest, block_id, block_hash, block_version, block_hashMerkleRoot, block_nTime, block_nBits, block_nNonce, block_height, prev_block_hash, block_chain_work, block_value_in, block_value_out, block_total_satoshis, block_total_seconds, block_satoshi_seconds, block_total_ss, block_ss_destroyed, block_num_tx FROM chain_summary WHERE """ + ' AND '.join(where) + """ ORDER BY in_longest DESC, chain_id DESC""" rows = store.selectall(sql, bind) if len(rows) == 0: return None row = rows[0][2:] def parse_cc(row): chain_id, in_longest = row[:2] return { "chain": store.get_chain_by_id(chain_id), "in_longest": in_longest } # Absent the chain argument, default to highest chain_id, preferring to avoid side chains. cc = map(parse_cc, rows) # "chain" may be None, but "found_chain" will not. found_chain = chain if found_chain is None: if len(cc) > 0: found_chain = cc[0]['chain'] else: # Should not normally get here. found_chain = store.get_default_chain() (block_id, block_hash, block_version, hashMerkleRoot, nTime, nBits, nNonce, height, prev_block_hash, block_chain_work, value_in, value_out, satoshis, seconds, ss, total_ss, destroyed, num_tx) = ( row[0], store.hashout_hex(row[1]), row[2], store.hashout_hex(row[3]), row[4], int(row[5]), row[6], row[7], store.hashout_hex(row[8]), store.binout_int(row[9]), int(row[10]), int(row[11]), None if row[12] is None else int(row[12]), None if row[13] is None else int(row[13]), None if row[14] is None else int(row[14]), None if row[15] is None else int(row[15]), None if row[16] is None else int(row[16]), int(row[17]), ) next_hashes = [ store.hashout_hex(hash) for hash, il in store.selectall(""" SELECT DISTINCT n.block_hash, cc.in_longest FROM block_next bn JOIN block n ON (bn.next_block_id = n.block_id) JOIN chain_candidate cc ON (n.block_id = cc.block_id) WHERE bn.block_id = ? ORDER BY cc.in_longest DESC""", (block_id,)) ] tx_ids = [] txs = {} block_out = 0 block_in = 0 for row in store.selectall(""" SELECT tx_id, tx_hash, tx_size, txout_value, txout_scriptPubKey FROM txout_detail WHERE block_id = ? ORDER BY tx_pos, txout_pos """, (block_id,)): tx_id, tx_hash, tx_size, txout_value, scriptPubKey = ( row[0], row[1], row[2], int(row[3]), store.binout(row[4])) tx = txs.get(tx_id) if tx is None: tx_ids.append(tx_id) txs[tx_id] = { "hash": store.hashout_hex(tx_hash), "total_out": 0, "total_in": 0, "out": [], "in": [], "size": int(tx_size), } tx = txs[tx_id] tx['total_out'] += txout_value block_out += txout_value txout = { 'value': txout_value } store._export_scriptPubKey(txout, found_chain, scriptPubKey) tx['out'].append(txout) for row in store.selectall(""" SELECT tx_id, txin_value, txin_scriptPubKey FROM txin_detail WHERE block_id = ? ORDER BY tx_pos, txin_pos """, (block_id,)): tx_id, txin_value, scriptPubKey = ( row[0], 0 if row[1] is None else int(row[1]), store.binout(row[2])) tx = txs.get(tx_id) if tx is None: # Strange, inputs but no outputs? tx_ids.append(tx_id) tx_hash, tx_size = store.selectrow(""" SELECT tx_hash, tx_size FROM tx WHERE tx_id = ?""", (tx_id,)) txs[tx_id] = { "hash": store.hashout_hex(tx_hash), "total_out": 0, "total_in": 0, "out": [], "in": [], "size": int(tx_size), } tx = txs[tx_id] tx['total_in'] += txin_value block_in += txin_value txin = { 'value': txin_value } store._export_scriptPubKey(txin, found_chain, scriptPubKey) tx['in'].append(txin) generated = block_out - block_in coinbase_tx = txs[tx_ids[0]] coinbase_tx['fees'] = 0 block_fees = coinbase_tx['total_out'] - generated b = { 'chain_candidates': cc, 'chain_satoshis': satoshis, 'chain_satoshi_seconds': total_ss, 'chain_work': block_chain_work, 'fees': block_fees, 'generated': generated, 'hash': block_hash, 'hashMerkleRoot': hashMerkleRoot, 'hashPrev': prev_block_hash, 'height': height, 'nBits': nBits, 'next_block_hashes': next_hashes, 'nNonce': nNonce, 'nTime': nTime, 'satoshis_destroyed': destroyed, 'satoshi_seconds': ss, 'transactions': [txs[tx_id] for tx_id in tx_ids], 'value_out': block_out, 'version': block_version, } is_stake_chain = chain is not None and chain.has_feature('nvc_proof_of_stake') if is_stake_chain: # Proof-of-stake display based loosely on CryptoManiac/novacoin and # http://nvc.cryptocoinexplorer.com. b['is_proof_of_stake'] = len(tx_ids) > 1 and coinbase_tx['total_out'] == 0 for tx_id in tx_ids[1:]: tx = txs[tx_id] tx['fees'] = tx['total_in'] - tx['total_out'] if is_stake_chain and b['is_proof_of_stake']: b['proof_of_stake_generated'] = -txs[tx_ids[1]]['fees'] txs[tx_ids[1]]['fees'] = 0 b['fees'] += b['proof_of_stake_generated'] return b
[ "def", "export_block", "(", "store", ",", "chain", "=", "None", ",", "block_hash", "=", "None", ",", "block_number", "=", "None", ")", ":", "if", "block_number", "is", "None", "and", "block_hash", "is", "None", ":", "raise", "ValueError", "(", "\"export_bl...
https://github.com/bitcoin-abe/bitcoin-abe/blob/33513dc8025cb08df85fc6bf41fa35eb9daa1a33/Abe/DataStore.py#L1528-L1776
grow/grow
97fc21730b6a674d5d33948d94968e79447ce433
grow/performance/docs_loader.py
python
DocsLoader.fix_default_locale
(pod, docs, ignore_errors=False)
Fixes docs loaded without with the wronge default locale.
Fixes docs loaded without with the wronge default locale.
[ "Fixes", "docs", "loaded", "without", "with", "the", "wronge", "default", "locale", "." ]
def fix_default_locale(pod, docs, ignore_errors=False): """Fixes docs loaded without with the wronge default locale.""" with pod.profile.timer('DocsLoader.fix_default_locale'): root_to_locale = {} for doc in docs: try: # Ignore the docs that are the same as the default locale. kw_locale = doc._locale_kwarg if kw_locale is not None: continue root_path = doc.root_pod_path current_locale = str(doc.locale) safe_locale = str(doc.locale_safe) if (root_path in root_to_locale and current_locale in root_to_locale[root_path]): continue if safe_locale != current_locale: # The None and safe locale is now invalid in the cache # since the front-matter differs. pod.podcache.collection_cache.remove_document_locale( doc, None) pod.podcache.collection_cache.remove_document_locale( doc, doc.locale_safe) # Get the doc for the correct default locale. clean_doc = doc.localize(current_locale) # Cache default locale (based off front-matter). pod.podcache.collection_cache.add_document_locale( clean_doc, None) # If we have already fixed it, ignore any other locales. if root_path not in root_to_locale: root_to_locale[root_path] = [] if current_locale not in root_to_locale[root_path]: root_to_locale[root_path].append(current_locale) except document_front_matter.BadFormatError: if not ignore_errors: raise
[ "def", "fix_default_locale", "(", "pod", ",", "docs", ",", "ignore_errors", "=", "False", ")", ":", "with", "pod", ".", "profile", ".", "timer", "(", "'DocsLoader.fix_default_locale'", ")", ":", "root_to_locale", "=", "{", "}", "for", "doc", "in", "docs", ...
https://github.com/grow/grow/blob/97fc21730b6a674d5d33948d94968e79447ce433/grow/performance/docs_loader.py#L56-L94
sabri-zaki/EasY_HaCk
2a39ac384dd0d6fc51c0dd22e8d38cece683fdb9
.modules/.metagoofil/lib/markup.py
python
page.addcontent
( self, text )
Add some text to the main part of the document
Add some text to the main part of the document
[ "Add", "some", "text", "to", "the", "main", "part", "of", "the", "document" ]
def addcontent( self, text ): """Add some text to the main part of the document""" self.content.append( text )
[ "def", "addcontent", "(", "self", ",", "text", ")", ":", "self", ".", "content", ".", "append", "(", "text", ")" ]
https://github.com/sabri-zaki/EasY_HaCk/blob/2a39ac384dd0d6fc51c0dd22e8d38cece683fdb9/.modules/.metagoofil/lib/markup.py#L222-L224
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/whoosh/src/whoosh/filedb/filetables.py
python
OrderedBase.items_from
(self, key)
Yields an ordered series of ``(key, value)`` tuples for keys equal to or greater than the given key.
Yields an ordered series of ``(key, value)`` tuples for keys equal to or greater than the given key.
[ "Yields", "an", "ordered", "series", "of", "(", "key", "value", ")", "tuples", "for", "keys", "equal", "to", "or", "greater", "than", "the", "given", "key", "." ]
def items_from(self, key): """Yields an ordered series of ``(key, value)`` tuples for keys equal to or greater than the given key. """ dbfile = self.dbfile for keypos, keylen, datapos, datalen in self.ranges_from(key): yield (dbfile.get(keypos, keylen), dbfile.get(datapos, datalen))
[ "def", "items_from", "(", "self", ",", "key", ")", ":", "dbfile", "=", "self", ".", "dbfile", "for", "keypos", ",", "keylen", ",", "datapos", ",", "datalen", "in", "self", ".", "ranges_from", "(", "key", ")", ":", "yield", "(", "dbfile", ".", "get", ...
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/whoosh/src/whoosh/filedb/filetables.py#L494-L501
novoid/Memacs
cc5b89a1da011a1ef08550e4da06c01881995b77
memacs/photos.py
python
PhotosMemacs._parser_add_arguments
(self)
overwritten method of class Memacs add additional arguments
overwritten method of class Memacs
[ "overwritten", "method", "of", "class", "Memacs" ]
def _parser_add_arguments(self): """ overwritten method of class Memacs add additional arguments """ Memacs._parser_add_arguments(self) self._parser.add_argument( "-f", "--folder", dest="photo_folder", action="store", required=True, help="path to search for photos") self._parser.add_argument("-l", "--follow-links", dest="follow_links", action="store_true", help="follow symbolics links," + \ " default False")
[ "def", "_parser_add_arguments", "(", "self", ")", ":", "Memacs", ".", "_parser_add_arguments", "(", "self", ")", "self", ".", "_parser", ".", "add_argument", "(", "\"-f\"", ",", "\"--folder\"", ",", "dest", "=", "\"photo_folder\"", ",", "action", "=", "\"store...
https://github.com/novoid/Memacs/blob/cc5b89a1da011a1ef08550e4da06c01881995b77/memacs/photos.py#L45-L61
aleju/ner-crf
195a67f995120f4d9140538d45364110c75e66b0
train.py
python
train
(args)
Main training method. Does the following: 1. Create a new pycrfsuite trainer object. We will have to add feature chains and label chains to that object and then train on them. 2. Creates the feature (generators). A feature generator might e.g. take in a window of N tokens and then return ["upper=1"] for each token that starts with an uppercase letter and ["upper=0"] for each token that starts with a lowercase letter. (Lists, because a token can be converted into multiple features by a single feature generator, e.g. the case for LDA as a token may be part of multiple topics.) 3. Loads windows from the corpus. Each window has a fixed (maximum) size in tokens. We only load windows that contain at least one label (named entity), so that we don't waste too much time on windows without any label. 4. Generate features for each chain of tokens (window). That's basically described in (2.). Each chain of tokens from a window will be converted to a list of lists. One list at the top level representing each token, then another list for the feature values. E.g. [["w2v=123", "bc=742", "upper=0"], ["w2v=4", "bc=12", "upper=1", "lda4=1"]] for two tokens. 5. Add feature chains and label chains to the trainer. 6. Train. This may take several hours for 20k windows. Args: args: Command line arguments as parsed by argparse.ArgumentParser.
Main training method.
[ "Main", "training", "method", "." ]
def train(args): """Main training method. Does the following: 1. Create a new pycrfsuite trainer object. We will have to add feature chains and label chains to that object and then train on them. 2. Creates the feature (generators). A feature generator might e.g. take in a window of N tokens and then return ["upper=1"] for each token that starts with an uppercase letter and ["upper=0"] for each token that starts with a lowercase letter. (Lists, because a token can be converted into multiple features by a single feature generator, e.g. the case for LDA as a token may be part of multiple topics.) 3. Loads windows from the corpus. Each window has a fixed (maximum) size in tokens. We only load windows that contain at least one label (named entity), so that we don't waste too much time on windows without any label. 4. Generate features for each chain of tokens (window). That's basically described in (2.). Each chain of tokens from a window will be converted to a list of lists. One list at the top level representing each token, then another list for the feature values. E.g. [["w2v=123", "bc=742", "upper=0"], ["w2v=4", "bc=12", "upper=1", "lda4=1"]] for two tokens. 5. Add feature chains and label chains to the trainer. 6. Train. This may take several hours for 20k windows. Args: args: Command line arguments as parsed by argparse.ArgumentParser. """ trainer = pycrfsuite.Trainer(verbose=True) # Create/Initialize the feature generators # this may take a few minutes print("Creating features...") feature_generators = features.create_features() # Initialize the window generator # each window has a fixed maximum size of tokens print("Loading windows...") windows = load_windows(load_articles(cfg.ARTICLES_FILEPATH), cfg.WINDOW_SIZE, feature_generators, only_labeled_windows=True) # Add chains of features (each list of lists of strings) # and chains of labels (each list of strings) # to the trainer. # This may take a long while, especially because of the lengthy POS tagging. # POS tags and LDA results are cached, so the second run through this part will be significantly # faster. print("Adding example windows (up to max %d)..." % (cfg.COUNT_WINDOWS_TRAIN)) examples = generate_examples(windows, nb_append=cfg.COUNT_WINDOWS_TRAIN, nb_skip=cfg.COUNT_WINDOWS_TEST, verbose=True) for feature_values_lists, labels in examples: trainer.append(feature_values_lists, labels) # Train the model # this may take several hours print("Training...") if cfg.MAX_ITERATIONS is not None and cfg.MAX_ITERATIONS > 0: # set the maximum number of iterations of defined in the config file # the optimizer stops automatically after some iterations if this is not set trainer.set_params({'max_iterations': cfg.MAX_ITERATIONS}) trainer.train(args.identifier)
[ "def", "train", "(", "args", ")", ":", "trainer", "=", "pycrfsuite", ".", "Trainer", "(", "verbose", "=", "True", ")", "# Create/Initialize the feature generators", "# this may take a few minutes", "print", "(", "\"Creating features...\"", ")", "feature_generators", "="...
https://github.com/aleju/ner-crf/blob/195a67f995120f4d9140538d45364110c75e66b0/train.py#L32-L90
tomplus/kubernetes_asyncio
f028cc793e3a2c519be6a52a49fb77ff0b014c9b
kubernetes_asyncio/client/models/v1_topology_spread_constraint.py
python
V1TopologySpreadConstraint.when_unsatisfiable
(self)
return self._when_unsatisfiable
Gets the when_unsatisfiable of this V1TopologySpreadConstraint. # noqa: E501 WhenUnsatisfiable indicates how to deal with a pod if it doesn't satisfy the spread constraint. - DoNotSchedule (default) tells the scheduler not to schedule it. - ScheduleAnyway tells the scheduler to schedule the pod in any location, but giving higher precedence to topologies that would help reduce the skew. A constraint is considered \"Unsatisfiable\" for an incoming pod if and only if every possible node assigment for that pod would violate \"MaxSkew\" on some topology. For example, in a 3-zone cluster, MaxSkew is set to 1, and pods with the same labelSelector spread as 3/1/1: | zone1 | zone2 | zone3 | | P P P | P | P | If WhenUnsatisfiable is set to DoNotSchedule, incoming pod can only be scheduled to zone2(zone3) to become 3/2/1(3/1/2) as ActualSkew(2-1) on zone2(zone3) satisfies MaxSkew(1). In other words, the cluster can still be imbalanced, but scheduler won't make it *more* imbalanced. It's a required field. # noqa: E501 :return: The when_unsatisfiable of this V1TopologySpreadConstraint. # noqa: E501 :rtype: str
Gets the when_unsatisfiable of this V1TopologySpreadConstraint. # noqa: E501
[ "Gets", "the", "when_unsatisfiable", "of", "this", "V1TopologySpreadConstraint", ".", "#", "noqa", ":", "E501" ]
def when_unsatisfiable(self): """Gets the when_unsatisfiable of this V1TopologySpreadConstraint. # noqa: E501 WhenUnsatisfiable indicates how to deal with a pod if it doesn't satisfy the spread constraint. - DoNotSchedule (default) tells the scheduler not to schedule it. - ScheduleAnyway tells the scheduler to schedule the pod in any location, but giving higher precedence to topologies that would help reduce the skew. A constraint is considered \"Unsatisfiable\" for an incoming pod if and only if every possible node assigment for that pod would violate \"MaxSkew\" on some topology. For example, in a 3-zone cluster, MaxSkew is set to 1, and pods with the same labelSelector spread as 3/1/1: | zone1 | zone2 | zone3 | | P P P | P | P | If WhenUnsatisfiable is set to DoNotSchedule, incoming pod can only be scheduled to zone2(zone3) to become 3/2/1(3/1/2) as ActualSkew(2-1) on zone2(zone3) satisfies MaxSkew(1). In other words, the cluster can still be imbalanced, but scheduler won't make it *more* imbalanced. It's a required field. # noqa: E501 :return: The when_unsatisfiable of this V1TopologySpreadConstraint. # noqa: E501 :rtype: str """ return self._when_unsatisfiable
[ "def", "when_unsatisfiable", "(", "self", ")", ":", "return", "self", ".", "_when_unsatisfiable" ]
https://github.com/tomplus/kubernetes_asyncio/blob/f028cc793e3a2c519be6a52a49fb77ff0b014c9b/kubernetes_asyncio/client/models/v1_topology_spread_constraint.py#L139-L147
spack/spack
675210bd8bd1c5d32ad1cc83d898fb43b569ed74
lib/spack/spack/store.py
python
_store
()
return Store(root=root, unpadded_root=unpadded_root, projections=projections, hash_length=hash_length)
Get the singleton store instance.
Get the singleton store instance.
[ "Get", "the", "singleton", "store", "instance", "." ]
def _store(): """Get the singleton store instance.""" import spack.bootstrap config_dict = spack.config.get('config') root, unpadded_root, projections = parse_install_tree(config_dict) hash_length = spack.config.get('config:install_hash_length') # Check that the user is not trying to install software into the store # reserved by Spack to bootstrap its own dependencies, since this would # lead to bizarre behaviors (e.g. cleaning the bootstrap area would wipe # user installed software) enable_bootstrap = spack.config.get('bootstrap:enable', True) if enable_bootstrap and spack.bootstrap.store_path() == root: msg = ('please change the install tree root "{0}" in your ' 'configuration [path reserved for Spack internal use]') raise ValueError(msg.format(root)) return Store(root=root, unpadded_root=unpadded_root, projections=projections, hash_length=hash_length)
[ "def", "_store", "(", ")", ":", "import", "spack", ".", "bootstrap", "config_dict", "=", "spack", ".", "config", ".", "get", "(", "'config'", ")", "root", ",", "unpadded_root", ",", "projections", "=", "parse_install_tree", "(", "config_dict", ")", "hash_len...
https://github.com/spack/spack/blob/675210bd8bd1c5d32ad1cc83d898fb43b569ed74/lib/spack/spack/store.py#L189-L209
fluentpython/example-code-2e
80f7f84274a47579e59c29a4657691525152c9d5
10-dp-1class-func/strategy_param.py
python
Order.__init__
( self, customer: Customer, cart: Sequence[LineItem], promotion: Optional['Promotion'] = None, )
[]
def __init__( self, customer: Customer, cart: Sequence[LineItem], promotion: Optional['Promotion'] = None, ): self.customer = customer self.cart = list(cart) self.promotion = promotion
[ "def", "__init__", "(", "self", ",", "customer", ":", "Customer", ",", "cart", ":", "Sequence", "[", "LineItem", "]", ",", "promotion", ":", "Optional", "[", "'Promotion'", "]", "=", "None", ",", ")", ":", "self", ".", "customer", "=", "customer", "sel...
https://github.com/fluentpython/example-code-2e/blob/80f7f84274a47579e59c29a4657691525152c9d5/10-dp-1class-func/strategy_param.py#L53-L61
joxeankoret/diaphora
dcb5a25ac9fe23a285b657e5389cf770de7ac928
jkutils/factor.py
python
factorization
(n)
return factors
[]
def factorization(n): factors = {} for p1 in primefactors(n): try: factors[p1] += 1 except KeyError: factors[p1] = 1 return factors
[ "def", "factorization", "(", "n", ")", ":", "factors", "=", "{", "}", "for", "p1", "in", "primefactors", "(", "n", ")", ":", "try", ":", "factors", "[", "p1", "]", "+=", "1", "except", "KeyError", ":", "factors", "[", "p1", "]", "=", "1", "return...
https://github.com/joxeankoret/diaphora/blob/dcb5a25ac9fe23a285b657e5389cf770de7ac928/jkutils/factor.py#L123-L130
krintoxi/NoobSec-Toolkit
38738541cbc03cedb9a3b3ed13b629f781ad64f6
NoobSecToolkit /tools/inject/lib/core/common.py
python
filterControlChars
(value)
return filterStringValue(value, PRINTABLE_CHAR_REGEX, ' ')
Returns string value with control chars being supstituted with ' ' >>> filterControlChars(u'AND 1>(2+3)\\n--') u'AND 1>(2+3) --'
Returns string value with control chars being supstituted with ' '
[ "Returns", "string", "value", "with", "control", "chars", "being", "supstituted", "with" ]
def filterControlChars(value): """ Returns string value with control chars being supstituted with ' ' >>> filterControlChars(u'AND 1>(2+3)\\n--') u'AND 1>(2+3) --' """ return filterStringValue(value, PRINTABLE_CHAR_REGEX, ' ')
[ "def", "filterControlChars", "(", "value", ")", ":", "return", "filterStringValue", "(", "value", ",", "PRINTABLE_CHAR_REGEX", ",", "' '", ")" ]
https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit /tools/inject/lib/core/common.py#L2647-L2655
peeringdb/peeringdb
47c6a699267b35663898f8d261159bdae9720f04
peeringdb_server/ixf.py
python
PostMortem.reset
(self, asn, **kwargs)
Reset for a fresh run. Argument(s): - asn <int>: asn of the network to run postormem report for Keyword Argument(s): - limit <int=100>: limit amount of import logs to process max limit is defined by server config `IXF_POSTMORTEM_LIMIT`
Reset for a fresh run.
[ "Reset", "for", "a", "fresh", "run", "." ]
def reset(self, asn, **kwargs): """ Reset for a fresh run. Argument(s): - asn <int>: asn of the network to run postormem report for Keyword Argument(s): - limit <int=100>: limit amount of import logs to process max limit is defined by server config `IXF_POSTMORTEM_LIMIT` """ self.asn = asn self.limit = kwargs.get("limit", 100) self.post_mortem = []
[ "def", "reset", "(", "self", ",", "asn", ",", "*", "*", "kwargs", ")", ":", "self", ".", "asn", "=", "asn", "self", ".", "limit", "=", "kwargs", ".", "get", "(", "\"limit\"", ",", "100", ")", "self", ".", "post_mortem", "=", "[", "]" ]
https://github.com/peeringdb/peeringdb/blob/47c6a699267b35663898f8d261159bdae9720f04/peeringdb_server/ixf.py#L2075-L2094
horazont/aioxmpp
c701e6399c90a6bb9bec0349018a03bd7b644cde
aioxmpp/muc/service.py
python
Room.muc_active
(self)
return self._active
A boolean attribute indicating whether the connection to the MUC is currently live. This becomes true when :attr:`joined` first becomes true. It becomes false whenever the connection to the MUC is interrupted in a way which requires re-joining the MUC (this implies that if stream management is being used, active does not become false on temporary connection interruptions).
A boolean attribute indicating whether the connection to the MUC is currently live.
[ "A", "boolean", "attribute", "indicating", "whether", "the", "connection", "to", "the", "MUC", "is", "currently", "live", "." ]
def muc_active(self): """ A boolean attribute indicating whether the connection to the MUC is currently live. This becomes true when :attr:`joined` first becomes true. It becomes false whenever the connection to the MUC is interrupted in a way which requires re-joining the MUC (this implies that if stream management is being used, active does not become false on temporary connection interruptions). """ return self._active
[ "def", "muc_active", "(", "self", ")", ":", "return", "self", ".", "_active" ]
https://github.com/horazont/aioxmpp/blob/c701e6399c90a6bb9bec0349018a03bd7b644cde/aioxmpp/muc/service.py#L929-L940
nodejs/node-gyp
a2f298870692022302fa27a1d42363c4a72df407
gyp/pylib/gyp/generator/cmake.py
python
SetFileProperty
(output, source_name, property_name, values, sep)
Given a set of source file, sets the given property on them.
Given a set of source file, sets the given property on them.
[ "Given", "a", "set", "of", "source", "file", "sets", "the", "given", "property", "on", "them", "." ]
def SetFileProperty(output, source_name, property_name, values, sep): """Given a set of source file, sets the given property on them.""" output.write("set_source_files_properties(") output.write(source_name) output.write(" PROPERTIES ") output.write(property_name) output.write(' "') for value in values: output.write(CMakeStringEscape(value)) output.write(sep) output.write('")\n')
[ "def", "SetFileProperty", "(", "output", ",", "source_name", ",", "property_name", ",", "values", ",", "sep", ")", ":", "output", ".", "write", "(", "\"set_source_files_properties(\"", ")", "output", ".", "write", "(", "source_name", ")", "output", ".", "write...
https://github.com/nodejs/node-gyp/blob/a2f298870692022302fa27a1d42363c4a72df407/gyp/pylib/gyp/generator/cmake.py#L144-L154
pyqt/examples
843bb982917cecb2350b5f6d7f42c9b7fb142ec1
src/pyqt-official/widgets/styles.py
python
WidgetGallery.changePalette
(self)
[]
def changePalette(self): if (self.useStylePaletteCheckBox.isChecked()): QApplication.setPalette(QApplication.style().standardPalette()) else: QApplication.setPalette(self.originalPalette)
[ "def", "changePalette", "(", "self", ")", ":", "if", "(", "self", ".", "useStylePaletteCheckBox", ".", "isChecked", "(", ")", ")", ":", "QApplication", ".", "setPalette", "(", "QApplication", ".", "style", "(", ")", ".", "standardPalette", "(", ")", ")", ...
https://github.com/pyqt/examples/blob/843bb982917cecb2350b5f6d7f42c9b7fb142ec1/src/pyqt-official/widgets/styles.py#L110-L114
schollii/pypubsub
dd5c1e848ff501b192a26a0a0187e618fda13f97
src/contrib/wx_monitor.py
python
LogPanel.write
(self, text)
[]
def write(self, text): ## print "writing" self.Text.AppendText(text)
[ "def", "write", "(", "self", ",", "text", ")", ":", "## print \"writing\"", "self", ".", "Text", ".", "AppendText", "(", "text", ")" ]
https://github.com/schollii/pypubsub/blob/dd5c1e848ff501b192a26a0a0187e618fda13f97/src/contrib/wx_monitor.py#L671-L673
saymedia/remoteobjects
d250e9a0e53c53744cb16c5fb2dc136df3785c1f
remoteobjects/promise.py
python
PromiseObject.get
(cls, url, http=None, **kwargs)
return self
Creates a new undelivered `PromiseObject` instance that, when delivered, will contain the data at the given URL.
Creates a new undelivered `PromiseObject` instance that, when delivered, will contain the data at the given URL.
[ "Creates", "a", "new", "undelivered", "PromiseObject", "instance", "that", "when", "delivered", "will", "contain", "the", "data", "at", "the", "given", "URL", "." ]
def get(cls, url, http=None, **kwargs): """Creates a new undelivered `PromiseObject` instance that, when delivered, will contain the data at the given URL.""" # Make a fake empty instance of this class. self = cls() self._location = url self._http = http self._delivered = False self._get_kwargs = kwargs return self
[ "def", "get", "(", "cls", ",", "url", ",", "http", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Make a fake empty instance of this class.", "self", "=", "cls", "(", ")", "self", ".", "_location", "=", "url", "self", ".", "_http", "=", "http", "se...
https://github.com/saymedia/remoteobjects/blob/d250e9a0e53c53744cb16c5fb2dc136df3785c1f/remoteobjects/promise.py#L152-L162
yeephycho/nasnet-tensorflow
189e22f2de9d6ee1b4abd0a65275d5e6a6c04c45
nets/resnet_v1.py
python
resnet_v1_block
(scope, base_depth, num_units, stride)
return resnet_utils.Block(scope, bottleneck, [{ 'depth': base_depth * 4, 'depth_bottleneck': base_depth, 'stride': 1 }] * (num_units - 1) + [{ 'depth': base_depth * 4, 'depth_bottleneck': base_depth, 'stride': stride }])
Helper function for creating a resnet_v1 bottleneck block. Args: scope: The scope of the block. base_depth: The depth of the bottleneck layer for each unit. num_units: The number of units in the block. stride: The stride of the block, implemented as a stride in the last unit. All other units have stride=1. Returns: A resnet_v1 bottleneck block.
Helper function for creating a resnet_v1 bottleneck block.
[ "Helper", "function", "for", "creating", "a", "resnet_v1", "bottleneck", "block", "." ]
def resnet_v1_block(scope, base_depth, num_units, stride): """Helper function for creating a resnet_v1 bottleneck block. Args: scope: The scope of the block. base_depth: The depth of the bottleneck layer for each unit. num_units: The number of units in the block. stride: The stride of the block, implemented as a stride in the last unit. All other units have stride=1. Returns: A resnet_v1 bottleneck block. """ return resnet_utils.Block(scope, bottleneck, [{ 'depth': base_depth * 4, 'depth_bottleneck': base_depth, 'stride': 1 }] * (num_units - 1) + [{ 'depth': base_depth * 4, 'depth_bottleneck': base_depth, 'stride': stride }])
[ "def", "resnet_v1_block", "(", "scope", ",", "base_depth", ",", "num_units", ",", "stride", ")", ":", "return", "resnet_utils", ".", "Block", "(", "scope", ",", "bottleneck", ",", "[", "{", "'depth'", ":", "base_depth", "*", "4", ",", "'depth_bottleneck'", ...
https://github.com/yeephycho/nasnet-tensorflow/blob/189e22f2de9d6ee1b4abd0a65275d5e6a6c04c45/nets/resnet_v1.py#L237-L258
khalim19/gimp-plugin-export-layers
b37255f2957ad322f4d332689052351cdea6e563
export_layers/pygimplib/progress.py
python
ProgressUpdater._fill_progress_bar
(self)
Fill in `num_finished_tasks`/`num_total_tasks` fraction of the progress bar. This is a method to be overridden by a subclass that implements a GUI-specific progress updater.
Fill in `num_finished_tasks`/`num_total_tasks` fraction of the progress bar. This is a method to be overridden by a subclass that implements a GUI-specific progress updater.
[ "Fill", "in", "num_finished_tasks", "/", "num_total_tasks", "fraction", "of", "the", "progress", "bar", ".", "This", "is", "a", "method", "to", "be", "overridden", "by", "a", "subclass", "that", "implements", "a", "GUI", "-", "specific", "progress", "updater",...
def _fill_progress_bar(self): """ Fill in `num_finished_tasks`/`num_total_tasks` fraction of the progress bar. This is a method to be overridden by a subclass that implements a GUI-specific progress updater. """ pass
[ "def", "_fill_progress_bar", "(", "self", ")", ":", "pass" ]
https://github.com/khalim19/gimp-plugin-export-layers/blob/b37255f2957ad322f4d332689052351cdea6e563/export_layers/pygimplib/progress.py#L87-L94
falconry/falcon
ee97769eab6a951864876202474133446aa50297
falcon/request.py
python
Request.log_error
(self, message)
Write an error message to the server's log. Prepends timestamp and request info to message, and writes the result out to the WSGI server's error stream (`wsgi.error`). Args: message (str): Description of the problem.
Write an error message to the server's log.
[ "Write", "an", "error", "message", "to", "the", "server", "s", "log", "." ]
def log_error(self, message): """Write an error message to the server's log. Prepends timestamp and request info to message, and writes the result out to the WSGI server's error stream (`wsgi.error`). Args: message (str): Description of the problem. """ if self.query_string: query_string_formatted = '?' + self.query_string else: query_string_formatted = '' log_line = DEFAULT_ERROR_LOG_FORMAT.format( now(), self.method, self.path, query_string_formatted ) self._wsgierrors.write(log_line + message + '\n')
[ "def", "log_error", "(", "self", ",", "message", ")", ":", "if", "self", ".", "query_string", ":", "query_string_formatted", "=", "'?'", "+", "self", ".", "query_string", "else", ":", "query_string_formatted", "=", "''", "log_line", "=", "DEFAULT_ERROR_LOG_FORMA...
https://github.com/falconry/falcon/blob/ee97769eab6a951864876202474133446aa50297/falcon/request.py#L1867-L1887
etetoolkit/ete
2b207357dc2a40ccad7bfd8f54964472c72e4726
ete3/nexml/_nexml.py
python
ContinuousObs.exportChildren
(self, outfile, level, namespace_='', name_='ContinuousObs', fromsubclass_=False)
[]
def exportChildren(self, outfile, level, namespace_='', name_='ContinuousObs', fromsubclass_=False): for meta_ in self.get_meta(): meta_.export(outfile, level, namespace_, name_='meta')
[ "def", "exportChildren", "(", "self", ",", "outfile", ",", "level", ",", "namespace_", "=", "''", ",", "name_", "=", "'ContinuousObs'", ",", "fromsubclass_", "=", "False", ")", ":", "for", "meta_", "in", "self", ".", "get_meta", "(", ")", ":", "meta_", ...
https://github.com/etetoolkit/ete/blob/2b207357dc2a40ccad7bfd8f54964472c72e4726/ete3/nexml/_nexml.py#L4193-L4195
coherence-project/Coherence
88016204c7778bf0d3ad1ae331b4d8fd725dd2af
coherence/base.py
python
Coherence.check_devices
(self)
iterate over devices and their embedded ones and renew subscriptions
iterate over devices and their embedded ones and renew subscriptions
[ "iterate", "over", "devices", "and", "their", "embedded", "ones", "and", "renew", "subscriptions" ]
def check_devices(self): """ iterate over devices and their embedded ones and renew subscriptions """ for root_device in self.get_devices(): root_device.renew_service_subscriptions() for device in root_device.get_devices(): device.renew_service_subscriptions()
[ "def", "check_devices", "(", "self", ")", ":", "for", "root_device", "in", "self", ".", "get_devices", "(", ")", ":", "root_device", ".", "renew_service_subscriptions", "(", ")", "for", "device", "in", "root_device", ".", "get_devices", "(", ")", ":", "devic...
https://github.com/coherence-project/Coherence/blob/88016204c7778bf0d3ad1ae331b4d8fd725dd2af/coherence/base.py#L586-L591
openbmc/openbmc
5f4109adae05f4d6925bfe960007d52f98c61086
poky/meta/lib/oeqa/runtime/cases/multilib.py
python
MultilibTest.test_check_multilib_libc
(self)
Check that a multilib image has both 32-bit and 64-bit libc in.
Check that a multilib image has both 32-bit and 64-bit libc in.
[ "Check", "that", "a", "multilib", "image", "has", "both", "32", "-", "bit", "and", "64", "-", "bit", "libc", "in", "." ]
def test_check_multilib_libc(self): """ Check that a multilib image has both 32-bit and 64-bit libc in. """ self.archtest("/lib/libc.so.6", "ELF32") self.archtest("/lib64/libc.so.6", "ELF64")
[ "def", "test_check_multilib_libc", "(", "self", ")", ":", "self", ".", "archtest", "(", "\"/lib/libc.so.6\"", ",", "\"ELF32\"", ")", "self", ".", "archtest", "(", "\"/lib64/libc.so.6\"", ",", "\"ELF64\"", ")" ]
https://github.com/openbmc/openbmc/blob/5f4109adae05f4d6925bfe960007d52f98c61086/poky/meta/lib/oeqa/runtime/cases/multilib.py#L37-L42
brian-team/brian2
c212a57cb992b766786b5769ebb830ff12d8a8ad
brian2/importexport/importexport.py
python
ImportExport.export_data
(group, variables)
Asbtract static export data method with two obligatory parameters. It should return a copy of the current state variable values. The returned arrays are copies of the actual arrays that store the state variable values, therefore changing the values in the returned dictionary will not affect the state variables. Parameters ---------- group : `Group` Group object. variables : list of str The names of the variables to extract.
Asbtract static export data method with two obligatory parameters. It should return a copy of the current state variable values. The returned arrays are copies of the actual arrays that store the state variable values, therefore changing the values in the returned dictionary will not affect the state variables.
[ "Asbtract", "static", "export", "data", "method", "with", "two", "obligatory", "parameters", ".", "It", "should", "return", "a", "copy", "of", "the", "current", "state", "variable", "values", ".", "The", "returned", "arrays", "are", "copies", "of", "the", "a...
def export_data(group, variables): """ Asbtract static export data method with two obligatory parameters. It should return a copy of the current state variable values. The returned arrays are copies of the actual arrays that store the state variable values, therefore changing the values in the returned dictionary will not affect the state variables. Parameters ---------- group : `Group` Group object. variables : list of str The names of the variables to extract. """ raise NotImplementedError()
[ "def", "export_data", "(", "group", ",", "variables", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/brian-team/brian2/blob/c212a57cb992b766786b5769ebb830ff12d8a8ad/brian2/importexport/importexport.py#L51-L66
demisto/content
5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07
Packs/QRadar/Integrations/QRadar_v3/QRadar_v3.py
python
qradar_ips_local_destination_get_command
(client: Client, args: Dict[str, Any])
return CommandResults( readable_output=tableToMarkdown('Local Destination IPs', outputs), outputs_prefix='QRadar.LocalDestinationIP', outputs_key_field='ID', outputs=outputs, raw_response=response )
Get local destination IPS from QRadar service. Args: client (Client): Client to perform API calls to QRadar service. args (Dict[str, Any): XSOAR arguments. Returns: (CommandResults).
Get local destination IPS from QRadar service. Args: client (Client): Client to perform API calls to QRadar service. args (Dict[str, Any): XSOAR arguments.
[ "Get", "local", "destination", "IPS", "from", "QRadar", "service", ".", "Args", ":", "client", "(", "Client", ")", ":", "Client", "to", "perform", "API", "calls", "to", "QRadar", "service", ".", "args", "(", "Dict", "[", "str", "Any", ")", ":", "XSOAR"...
def qradar_ips_local_destination_get_command(client: Client, args: Dict[str, Any]) -> CommandResults: """ Get local destination IPS from QRadar service. Args: client (Client): Client to perform API calls to QRadar service. args (Dict[str, Any): XSOAR arguments. Returns: (CommandResults). """ response = perform_ips_command_request(client, args, is_destination_addresses=True) outputs = sanitize_outputs(response, LOCAL_DESTINATION_IPS_OLD_NEW_MAP) return CommandResults( readable_output=tableToMarkdown('Local Destination IPs', outputs), outputs_prefix='QRadar.LocalDestinationIP', outputs_key_field='ID', outputs=outputs, raw_response=response )
[ "def", "qradar_ips_local_destination_get_command", "(", "client", ":", "Client", ",", "args", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "CommandResults", ":", "response", "=", "perform_ips_command_request", "(", "client", ",", "args", ",", "is_destina...
https://github.com/demisto/content/blob/5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07/Packs/QRadar/Integrations/QRadar_v3/QRadar_v3.py#L2935-L2954
JetBrains/python-skeletons
95ad24b666e475998e5d1cc02ed53a2188036167
__builtin__.py
python
set.discard
(self, x)
Remove an element x from the set, do nothing if it's not present. :type x: T :rtype: None
Remove an element x from the set, do nothing if it's not present.
[ "Remove", "an", "element", "x", "from", "the", "set", "do", "nothing", "if", "it", "s", "not", "present", "." ]
def discard(self, x): """Remove an element x from the set, do nothing if it's not present. :type x: T :rtype: None """ pass
[ "def", "discard", "(", "self", ",", "x", ")", ":", "pass" ]
https://github.com/JetBrains/python-skeletons/blob/95ad24b666e475998e5d1cc02ed53a2188036167/__builtin__.py#L2202-L2208
googlearchive/pywebsocket
c459a5f9a04714e596726e876fcb46951c61a5f7
mod_pywebsocket/util.py
python
RepeatedXorMasker._mask_using_array
(self, s)
return result.tostring()
Perform the mask via python.
Perform the mask via python.
[ "Perform", "the", "mask", "via", "python", "." ]
def _mask_using_array(self, s): """Perform the mask via python.""" result = array.array('B') result.fromstring(s) # Use temporary local variables to eliminate the cost to access # attributes masking_key = map(ord, self._masking_key) masking_key_size = len(masking_key) masking_key_index = self._masking_key_index for i in xrange(len(result)): result[i] ^= masking_key[masking_key_index] masking_key_index = (masking_key_index + 1) % masking_key_size self._masking_key_index = masking_key_index return result.tostring()
[ "def", "_mask_using_array", "(", "self", ",", "s", ")", ":", "result", "=", "array", ".", "array", "(", "'B'", ")", "result", ".", "fromstring", "(", "s", ")", "# Use temporary local variables to eliminate the cost to access", "# attributes", "masking_key", "=", "...
https://github.com/googlearchive/pywebsocket/blob/c459a5f9a04714e596726e876fcb46951c61a5f7/mod_pywebsocket/util.py#L193-L210
ninja-ide/ninja-ide
87d91131bd19fdc3dcfd91eb97ad1e41c49c60c0
ninja_ide/dependencies/pycodestyle.py
python
comparison_to_singleton
(logical_line, noqa)
r"""Comparison to singletons should use "is" or "is not". Comparisons to singletons like None should always be done with "is" or "is not", never the equality operators. Okay: if arg is not None: E711: if arg != None: E711: if None == arg: E712: if arg == True: E712: if False == arg: Also, beware of writing if x when you really mean if x is not None -- e.g. when testing whether a variable or argument that defaults to None was set to some other value. The other value might have a type (such as a container) that could be false in a boolean context!
r"""Comparison to singletons should use "is" or "is not".
[ "r", "Comparison", "to", "singletons", "should", "use", "is", "or", "is", "not", "." ]
def comparison_to_singleton(logical_line, noqa): r"""Comparison to singletons should use "is" or "is not". Comparisons to singletons like None should always be done with "is" or "is not", never the equality operators. Okay: if arg is not None: E711: if arg != None: E711: if None == arg: E712: if arg == True: E712: if False == arg: Also, beware of writing if x when you really mean if x is not None -- e.g. when testing whether a variable or argument that defaults to None was set to some other value. The other value might have a type (such as a container) that could be false in a boolean context! """ match = not noqa and COMPARE_SINGLETON_REGEX.search(logical_line) if match: singleton = match.group(1) or match.group(3) same = (match.group(2) == '==') msg = "'if cond is %s:'" % (('' if same else 'not ') + singleton) if singleton in ('None',): code = 'E711' else: code = 'E712' nonzero = ((singleton == 'True' and same) or (singleton == 'False' and not same)) msg += " or 'if %scond:'" % ('' if nonzero else 'not ') yield match.start(2), ("%s comparison to %s should be %s" % (code, singleton, msg))
[ "def", "comparison_to_singleton", "(", "logical_line", ",", "noqa", ")", ":", "match", "=", "not", "noqa", "and", "COMPARE_SINGLETON_REGEX", ".", "search", "(", "logical_line", ")", "if", "match", ":", "singleton", "=", "match", ".", "group", "(", "1", ")", ...
https://github.com/ninja-ide/ninja-ide/blob/87d91131bd19fdc3dcfd91eb97ad1e41c49c60c0/ninja_ide/dependencies/pycodestyle.py#L1122-L1153
huanghoujing/person-reid-triplet-loss-baseline
a1c2bd20180cfaf225782717aeaaab461798abec
tri_loss/utils/utils.py
python
adjust_lr_staircase
(optimizer, base_lr, ep, decay_at_epochs, factor)
Multiplied by a factor at the BEGINNING of specified epochs. All parameters in the optimizer share the same learning rate. Args: optimizer: a pytorch `Optimizer` object base_lr: starting learning rate ep: current epoch, ep >= 1 decay_at_epochs: a list or tuple; learning rate is multiplied by a factor at the BEGINNING of these epochs factor: a number in range (0, 1) Example: base_lr = 1e-3 decay_at_epochs = [51, 101] factor = 0.1 It means the learning rate starts at 1e-3 and is multiplied by 0.1 at the BEGINNING of the 51'st epoch, and then further multiplied by 0.1 at the BEGINNING of the 101'st epoch, then stays unchanged till the end of training. NOTE: It is meant to be called at the BEGINNING of an epoch.
Multiplied by a factor at the BEGINNING of specified epochs. All parameters in the optimizer share the same learning rate. Args: optimizer: a pytorch `Optimizer` object base_lr: starting learning rate ep: current epoch, ep >= 1 decay_at_epochs: a list or tuple; learning rate is multiplied by a factor at the BEGINNING of these epochs factor: a number in range (0, 1) Example: base_lr = 1e-3 decay_at_epochs = [51, 101] factor = 0.1 It means the learning rate starts at 1e-3 and is multiplied by 0.1 at the BEGINNING of the 51'st epoch, and then further multiplied by 0.1 at the BEGINNING of the 101'st epoch, then stays unchanged till the end of training. NOTE: It is meant to be called at the BEGINNING of an epoch.
[ "Multiplied", "by", "a", "factor", "at", "the", "BEGINNING", "of", "specified", "epochs", ".", "All", "parameters", "in", "the", "optimizer", "share", "the", "same", "learning", "rate", ".", "Args", ":", "optimizer", ":", "a", "pytorch", "Optimizer", "object...
def adjust_lr_staircase(optimizer, base_lr, ep, decay_at_epochs, factor): """Multiplied by a factor at the BEGINNING of specified epochs. All parameters in the optimizer share the same learning rate. Args: optimizer: a pytorch `Optimizer` object base_lr: starting learning rate ep: current epoch, ep >= 1 decay_at_epochs: a list or tuple; learning rate is multiplied by a factor at the BEGINNING of these epochs factor: a number in range (0, 1) Example: base_lr = 1e-3 decay_at_epochs = [51, 101] factor = 0.1 It means the learning rate starts at 1e-3 and is multiplied by 0.1 at the BEGINNING of the 51'st epoch, and then further multiplied by 0.1 at the BEGINNING of the 101'st epoch, then stays unchanged till the end of training. NOTE: It is meant to be called at the BEGINNING of an epoch. """ assert ep >= 1, "Current epoch number should be >= 1" if ep not in decay_at_epochs: return ind = find_index(decay_at_epochs, ep) for g in optimizer.param_groups: g['lr'] = base_lr * factor ** (ind + 1) print('=====> lr adjusted to {:.10f}'.format(g['lr']).rstrip('0'))
[ "def", "adjust_lr_staircase", "(", "optimizer", ",", "base_lr", ",", "ep", ",", "decay_at_epochs", ",", "factor", ")", ":", "assert", "ep", ">=", "1", ",", "\"Current epoch number should be >= 1\"", "if", "ep", "not", "in", "decay_at_epochs", ":", "return", "ind...
https://github.com/huanghoujing/person-reid-triplet-loss-baseline/blob/a1c2bd20180cfaf225782717aeaaab461798abec/tri_loss/utils/utils.py#L566-L598
kanzure/nanoengineer
874e4c9f8a9190f093625b267f9767e19f82e6c4
cad/src/graphics/drawing/GLPrimitiveBuffer.py
python
HunkBuffer.addHunk
(self)
return
Allocate a new hunk VBO when needed.
Allocate a new hunk VBO when needed.
[ "Allocate", "a", "new", "hunk", "VBO", "when", "needed", "." ]
def addHunk(self): """ Allocate a new hunk VBO when needed. """ hunkNumber = len(self.hunks) self.hunks += [Hunk(hunkNumber, self.nVertices, self.nCoords)] return
[ "def", "addHunk", "(", "self", ")", ":", "hunkNumber", "=", "len", "(", "self", ".", "hunks", ")", "self", ".", "hunks", "+=", "[", "Hunk", "(", "hunkNumber", ",", "self", ".", "nVertices", ",", "self", ".", "nCoords", ")", "]", "return" ]
https://github.com/kanzure/nanoengineer/blob/874e4c9f8a9190f093625b267f9767e19f82e6c4/cad/src/graphics/drawing/GLPrimitiveBuffer.py#L518-L524
spyder-ide/spyder
55da47c032dfcf519600f67f8b30eab467f965e7
spyder/plugins/maininterpreter/confpage.py
python
MainInterpreterConfigPage.validate_custom_interpreters_list
(self)
Check that the used custom interpreters are still valid.
Check that the used custom interpreters are still valid.
[ "Check", "that", "the", "used", "custom", "interpreters", "are", "still", "valid", "." ]
def validate_custom_interpreters_list(self): """Check that the used custom interpreters are still valid.""" custom_list = self.get_option('custom_interpreters_list') valid_custom_list = [] for value in custom_list: if osp.isfile(value): valid_custom_list.append(value) self.set_option('custom_interpreters_list', valid_custom_list)
[ "def", "validate_custom_interpreters_list", "(", "self", ")", ":", "custom_list", "=", "self", ".", "get_option", "(", "'custom_interpreters_list'", ")", "valid_custom_list", "=", "[", "]", "for", "value", "in", "custom_list", ":", "if", "osp", ".", "isfile", "(...
https://github.com/spyder-ide/spyder/blob/55da47c032dfcf519600f67f8b30eab467f965e7/spyder/plugins/maininterpreter/confpage.py#L261-L269
adafruit/Adafruit_Blinka
f6a653e6cc34e71c9ef7912b858de1018f08ecf8
src/adafruit_blinka/microcontroller/ftdi_mpsse/mpsse/spi.py
python
SPI.readinto
(self, buf, start=0, end=None, write_value=0)
Read data from SPI and into the buffer
Read data from SPI and into the buffer
[ "Read", "data", "from", "SPI", "and", "into", "the", "buffer" ]
def readinto(self, buf, start=0, end=None, write_value=0): """Read data from SPI and into the buffer""" end = end if end else len(buf) buffer_out = [write_value] * (end - start) result = self._port.exchange(buffer_out, end - start, duplex=True) for i, b in enumerate(result): buf[start + i] = b
[ "def", "readinto", "(", "self", ",", "buf", ",", "start", "=", "0", ",", "end", "=", "None", ",", "write_value", "=", "0", ")", ":", "end", "=", "end", "if", "end", "else", "len", "(", "buf", ")", "buffer_out", "=", "[", "write_value", "]", "*", ...
https://github.com/adafruit/Adafruit_Blinka/blob/f6a653e6cc34e71c9ef7912b858de1018f08ecf8/src/adafruit_blinka/microcontroller/ftdi_mpsse/mpsse/spi.py#L74-L80
GNS3/gns3-gui
da8adbaa18ab60e053af2a619efd468f4c8950f3
gns3/template_manager.py
python
TemplateManager.createTemplate
(self, template, callback=None)
Creates a template on the controller. :param template: template object. :param callback: callback to receive response from the controller.
Creates a template on the controller.
[ "Creates", "a", "template", "on", "the", "controller", "." ]
def createTemplate(self, template, callback=None): """ Creates a template on the controller. :param template: template object. :param callback: callback to receive response from the controller. """ log.debug("Create template '{}' (ID={})".format(template.name(), template.id())) self._controller.post("/templates", callback, body=template.__json__())
[ "def", "createTemplate", "(", "self", ",", "template", ",", "callback", "=", "None", ")", ":", "log", ".", "debug", "(", "\"Create template '{}' (ID={})\"", ".", "format", "(", "template", ".", "name", "(", ")", ",", "template", ".", "id", "(", ")", ")",...
https://github.com/GNS3/gns3-gui/blob/da8adbaa18ab60e053af2a619efd468f4c8950f3/gns3/template_manager.py#L63-L72
tdamdouni/Pythonista
3e082d53b6b9b501a3c8cf3251a8ad4c8be9c2ad
games/mazecraze.py
python
cell.openwall
(self, other, wall)
Open wall then clear the opposite wall in the given neighbor cell.
Open wall then clear the opposite wall in the given neighbor cell.
[ "Open", "wall", "then", "clear", "the", "opposite", "wall", "in", "the", "given", "neighbor", "cell", "." ]
def openwall(self, other, wall): '''Open wall then clear the opposite wall in the given neighbor cell.''' self.clearwall(wall) other.clearwall(otherside(wall)) #Recalculate the images. self.makewallimage() other.makewallimage()
[ "def", "openwall", "(", "self", ",", "other", ",", "wall", ")", ":", "self", ".", "clearwall", "(", "wall", ")", "other", ".", "clearwall", "(", "otherside", "(", "wall", ")", ")", "#Recalculate the images.", "self", ".", "makewallimage", "(", ")", "othe...
https://github.com/tdamdouni/Pythonista/blob/3e082d53b6b9b501a3c8cf3251a8ad4c8be9c2ad/games/mazecraze.py#L401-L407
mpplab/mnssp3
fa82abdcc8cc5486927047811286b3328237cc33
DNA/Motif Finding/Python/logo/pyseqlogo/format_utils.py
python
read_alignment
(infile, data_type='fasta', seq_type='dna', pseudo_count=1)
return counts, total
Read alignment file as motif Parameters ---------- infile: str Path to input alignment file data_type: str 'fasta', 'stockholm', etc/. as supported by Bio.AlignIO seq_type: str 'dna', 'rna' or 'aa' pseudo_count: int psuedo counts to add before calculating information cotent Returns ------- (motif, information_content) : tuple A motif instance followd by total informatio content of the motif
Read alignment file as motif
[ "Read", "alignment", "file", "as", "motif" ]
def read_alignment(infile, data_type='fasta', seq_type='dna', pseudo_count=1): """Read alignment file as motif Parameters ---------- infile: str Path to input alignment file data_type: str 'fasta', 'stockholm', etc/. as supported by Bio.AlignIO seq_type: str 'dna', 'rna' or 'aa' pseudo_count: int psuedo counts to add before calculating information cotent Returns ------- (motif, information_content) : tuple A motif instance followd by total informatio content of the motif """ alignment = AlignIO.read(infile, data_type) data = [] for aln in alignment: data.append([x for x in str(aln.seq)]) df = pd.DataFrame(data) df_counts = df.apply(pd.value_counts, 0) total = df_counts[[0]].sum() df_counts = df_counts[df_counts.index != '-'] # Remove - from counts counts_dict = df_counts.to_dict(orient='index') counts = {} for key, val in counts_dict.items(): counts[key] = list(val.values()) return counts, total """ summary_align = AlignInfo.SummaryInfo(alignment) if seq_type == 'dna': info_content = summary_align.information_content(e_freq_table = naive_freq_tables['dna'], chars_to_ignore = ['N'], pseudo_count = pseudo_count) elif seq_type == 'rna': info_content = summary_align.information_content(e_freq_table = naive_freq_tables['rna'], chars_to_ignore = ['N'], pseudo_count = pseudo_count) else: info_content = summary_align.information_content(e_freq_table = naive_freq_tables['aa'], pseudo_count = pseudo_count) motif = create_motif_from_alignment(alignment) return (motif, summary_align.ic_vector) """
[ "def", "read_alignment", "(", "infile", ",", "data_type", "=", "'fasta'", ",", "seq_type", "=", "'dna'", ",", "pseudo_count", "=", "1", ")", ":", "alignment", "=", "AlignIO", ".", "read", "(", "infile", ",", "data_type", ")", "data", "=", "[", "]", "fo...
https://github.com/mpplab/mnssp3/blob/fa82abdcc8cc5486927047811286b3328237cc33/DNA/Motif Finding/Python/logo/pyseqlogo/format_utils.py#L162-L216
nose-devs/nose
7c26ad1e6b7d308cafa328ad34736d34028c122a
nose/util.py
python
ln
(label)
return out
Draw a 70-char-wide divider, with label in the middle. >>> ln('hello there') '---------------------------- hello there -----------------------------'
Draw a 70-char-wide divider, with label in the middle.
[ "Draw", "a", "70", "-", "char", "-", "wide", "divider", "with", "label", "in", "the", "middle", "." ]
def ln(label): """Draw a 70-char-wide divider, with label in the middle. >>> ln('hello there') '---------------------------- hello there -----------------------------' """ label_len = len(label) + 2 chunk = (70 - label_len) // 2 out = '%s %s %s' % ('-' * chunk, label, '-' * chunk) pad = 70 - len(out) if pad > 0: out = out + ('-' * pad) return out
[ "def", "ln", "(", "label", ")", ":", "label_len", "=", "len", "(", "label", ")", "+", "2", "chunk", "=", "(", "70", "-", "label_len", ")", "//", "2", "out", "=", "'%s %s %s'", "%", "(", "'-'", "*", "chunk", ",", "label", ",", "'-'", "*", "chunk...
https://github.com/nose-devs/nose/blob/7c26ad1e6b7d308cafa328ad34736d34028c122a/nose/util.py#L282-L294
JaniceWuo/MovieRecommend
4c86db64ca45598917d304f535413df3bc9fea65
movierecommend/venv1/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/distlib/database.py
python
EggInfoDistribution.check_installed_files
(self)
return mismatches
Checks that the hashes and sizes of the files in ``RECORD`` are matched by the files themselves. Returns a (possibly empty) list of mismatches. Each entry in the mismatch list will be a tuple consisting of the path, 'exists', 'size' or 'hash' according to what didn't match (existence is checked first, then size, then hash), the expected value and the actual value.
Checks that the hashes and sizes of the files in ``RECORD`` are matched by the files themselves. Returns a (possibly empty) list of mismatches. Each entry in the mismatch list will be a tuple consisting of the path, 'exists', 'size' or 'hash' according to what didn't match (existence is checked first, then size, then hash), the expected value and the actual value.
[ "Checks", "that", "the", "hashes", "and", "sizes", "of", "the", "files", "in", "RECORD", "are", "matched", "by", "the", "files", "themselves", ".", "Returns", "a", "(", "possibly", "empty", ")", "list", "of", "mismatches", ".", "Each", "entry", "in", "th...
def check_installed_files(self): """ Checks that the hashes and sizes of the files in ``RECORD`` are matched by the files themselves. Returns a (possibly empty) list of mismatches. Each entry in the mismatch list will be a tuple consisting of the path, 'exists', 'size' or 'hash' according to what didn't match (existence is checked first, then size, then hash), the expected value and the actual value. """ mismatches = [] record_path = os.path.join(self.path, 'installed-files.txt') if os.path.exists(record_path): for path, _, _ in self.list_installed_files(): if path == record_path: continue if not os.path.exists(path): mismatches.append((path, 'exists', True, False)) return mismatches
[ "def", "check_installed_files", "(", "self", ")", ":", "mismatches", "=", "[", "]", "record_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "path", ",", "'installed-files.txt'", ")", "if", "os", ".", "path", ".", "exists", "(", "record_path...
https://github.com/JaniceWuo/MovieRecommend/blob/4c86db64ca45598917d304f535413df3bc9fea65/movierecommend/venv1/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/distlib/database.py#L958-L975
plotly/plotly.py
cfad7862594b35965c0e000813bd7805e8494a5b
packages/python/plotly/plotly/graph_objs/_heatmapgl.py
python
Heatmapgl.hoverinfosrc
(self)
return self["hoverinfosrc"]
Sets the source reference on Chart Studio Cloud for `hoverinfo`. The 'hoverinfosrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str
Sets the source reference on Chart Studio Cloud for `hoverinfo`. The 'hoverinfosrc' property must be specified as a string or as a plotly.grid_objs.Column object
[ "Sets", "the", "source", "reference", "on", "Chart", "Studio", "Cloud", "for", "hoverinfo", ".", "The", "hoverinfosrc", "property", "must", "be", "specified", "as", "a", "string", "or", "as", "a", "plotly", ".", "grid_objs", ".", "Column", "object" ]
def hoverinfosrc(self): """ Sets the source reference on Chart Studio Cloud for `hoverinfo`. The 'hoverinfosrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["hoverinfosrc"]
[ "def", "hoverinfosrc", "(", "self", ")", ":", "return", "self", "[", "\"hoverinfosrc\"", "]" ]
https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/_heatmapgl.py#L537-L549
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/runners/net.py
python
lldp
( device=None, interface=None, title=None, pattern=None, chassis=None, display=_DEFAULT_DISPLAY, )
return _display_runner(rows, labels, title, display=display)
Search in the LLDP neighbors, using the following mine functions: - net.lldp Optional arguments: device Return interface data from a certain device only. interface Return data selecting by interface name. pattern Return LLDP neighbors that have contain this pattern in one of the following fields: - Remote Port ID - Remote Port Description - Remote System Name - Remote System Description chassis Search using a specific Chassis ID. display: ``True`` Display on the screen or return structured object? Default: ``True`` (return on the CLI). display: ``True`` Display on the screen or return structured object? Default: ``True`` (return on the CLI). title Display a custom title for the table. CLI Example: .. code-block:: bash $ sudo salt-run net.lldp pattern=Ethernet1/48 Output Example: .. code-block:: text Pattern "Ethernet1/48" found in one of the following LLDP details _________________________________________________________________________________________________________________________________________________________________________________________ | Device | Interface | Parent Interface | Remote Chassis ID | Remote Port ID | Remote Port Description | Remote System Name | Remote System Description | _________________________________________________________________________________________________________________________________________________________________________________________ | edge01.bjm01 | xe-2/3/4 | ae0 | 8C:60:4F:3B:52:19 | | Ethernet1/48 | edge05.bjm01.dummy.net | Cisco NX-OS(tm) n6000, Software (n6000-uk9), | | | | | | | | | Version 7.3(0)N7(5), RELEASE SOFTWARE Copyright | | | | | | | | | (c) 2002-2012 by Cisco Systems, Inc. Compiled | | | | | | | | | 2/17/2016 22:00:00 | _________________________________________________________________________________________________________________________________________________________________________________________ | edge01.flw01 | xe-1/2/3 | ae0 | 8C:60:4F:1A:B4:22 | | Ethernet1/48 | edge05.flw01.dummy.net | Cisco NX-OS(tm) n6000, Software (n6000-uk9), | | | | | | | | | Version 7.3(0)N7(5), RELEASE SOFTWARE Copyright | | | | | | | | | (c) 2002-2012 by Cisco Systems, Inc. Compiled | | | | | | | | | 2/17/2016 22:00:00 | _________________________________________________________________________________________________________________________________________________________________________________________ | edge01.oua01 | xe-0/1/2 | ae1 | 8C:60:4F:51:A4:22 | | Ethernet1/48 | edge05.oua01.dummy.net | Cisco NX-OS(tm) n6000, Software (n6000-uk9), | | | | | | | | | Version 7.3(0)N7(5), RELEASE SOFTWARE Copyright | | | | | | | | | (c) 2002-2012 by Cisco Systems, Inc. Compiled | | | | | | | | | 2/17/2016 22:00:00 | _________________________________________________________________________________________________________________________________________________________________________________________
Search in the LLDP neighbors, using the following mine functions:
[ "Search", "in", "the", "LLDP", "neighbors", "using", "the", "following", "mine", "functions", ":" ]
def lldp( device=None, interface=None, title=None, pattern=None, chassis=None, display=_DEFAULT_DISPLAY, ): """ Search in the LLDP neighbors, using the following mine functions: - net.lldp Optional arguments: device Return interface data from a certain device only. interface Return data selecting by interface name. pattern Return LLDP neighbors that have contain this pattern in one of the following fields: - Remote Port ID - Remote Port Description - Remote System Name - Remote System Description chassis Search using a specific Chassis ID. display: ``True`` Display on the screen or return structured object? Default: ``True`` (return on the CLI). display: ``True`` Display on the screen or return structured object? Default: ``True`` (return on the CLI). title Display a custom title for the table. CLI Example: .. code-block:: bash $ sudo salt-run net.lldp pattern=Ethernet1/48 Output Example: .. code-block:: text Pattern "Ethernet1/48" found in one of the following LLDP details _________________________________________________________________________________________________________________________________________________________________________________________ | Device | Interface | Parent Interface | Remote Chassis ID | Remote Port ID | Remote Port Description | Remote System Name | Remote System Description | _________________________________________________________________________________________________________________________________________________________________________________________ | edge01.bjm01 | xe-2/3/4 | ae0 | 8C:60:4F:3B:52:19 | | Ethernet1/48 | edge05.bjm01.dummy.net | Cisco NX-OS(tm) n6000, Software (n6000-uk9), | | | | | | | | | Version 7.3(0)N7(5), RELEASE SOFTWARE Copyright | | | | | | | | | (c) 2002-2012 by Cisco Systems, Inc. Compiled | | | | | | | | | 2/17/2016 22:00:00 | _________________________________________________________________________________________________________________________________________________________________________________________ | edge01.flw01 | xe-1/2/3 | ae0 | 8C:60:4F:1A:B4:22 | | Ethernet1/48 | edge05.flw01.dummy.net | Cisco NX-OS(tm) n6000, Software (n6000-uk9), | | | | | | | | | Version 7.3(0)N7(5), RELEASE SOFTWARE Copyright | | | | | | | | | (c) 2002-2012 by Cisco Systems, Inc. Compiled | | | | | | | | | 2/17/2016 22:00:00 | _________________________________________________________________________________________________________________________________________________________________________________________ | edge01.oua01 | xe-0/1/2 | ae1 | 8C:60:4F:51:A4:22 | | Ethernet1/48 | edge05.oua01.dummy.net | Cisco NX-OS(tm) n6000, Software (n6000-uk9), | | | | | | | | | Version 7.3(0)N7(5), RELEASE SOFTWARE Copyright | | | | | | | | | (c) 2002-2012 by Cisco Systems, Inc. Compiled | | | | | | | | | 2/17/2016 22:00:00 | _________________________________________________________________________________________________________________________________________________________________________________________ """ all_lldp = _get_mine("net.lldp") labels = { "device": "Device", "interface": "Interface", "parent_interface": "Parent Interface", "remote_chassis_id": "Remote Chassis ID", "remote_port_id": "Remote Port ID", "remote_port_desc": "Remote Port Description", "remote_system_name": "Remote System Name", "remote_system_desc": "Remote System Description", } rows = [] if pattern: title = 'Pattern "{}" found in one of the following LLDP details'.format( pattern ) if not title: title = "LLDP Neighbors" if interface: title += " for interface {}".format(interface) else: title += " for all interfaces" if device: title += " on device {}".format(device) if chassis: title += " having Chassis ID {}".format(chassis) if device: all_lldp = {device: all_lldp.get(device)} for device, device_lldp in all_lldp.items(): if not device_lldp: continue if not device_lldp.get("result", False): continue lldp_interfaces = device_lldp.get("out", {}) if interface: lldp_interfaces = {interface: lldp_interfaces.get(interface, [])} for intrf, interface_lldp in lldp_interfaces.items(): if not interface_lldp: continue for lldp_row in interface_lldp: rsn = lldp_row.get("remote_system_name", "") or "" rpi = lldp_row.get("remote_port_id", "") or "" rsd = lldp_row.get("remote_system_description", "") or "" rpd = lldp_row.get("remote_port_description", "") or "" rci = lldp_row.get("remote_chassis_id", "") or "" if pattern: ptl = pattern.lower() if not ( (ptl in rsn.lower()) or (ptl in rsd.lower()) or (ptl in rpd.lower()) or (ptl in rci.lower()) ): # nothing matched, let's move on continue if chassis: if napalm_helpers.convert( napalm_helpers.mac, rci ) != napalm_helpers.convert(napalm_helpers.mac, chassis): continue rows.append( { "device": device, "interface": intrf, "parent_interface": ( lldp_row.get("parent_interface", "") or "" ), "remote_chassis_id": napalm_helpers.convert( napalm_helpers.mac, rci ), "remote_port_id": rpi, "remote_port_descr": rpd, "remote_system_name": rsn, "remote_system_descr": rsd, } ) return _display_runner(rows, labels, title, display=display)
[ "def", "lldp", "(", "device", "=", "None", ",", "interface", "=", "None", ",", "title", "=", "None", ",", "pattern", "=", "None", ",", "chassis", "=", "None", ",", "display", "=", "_DEFAULT_DISPLAY", ",", ")", ":", "all_lldp", "=", "_get_mine", "(", ...
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/runners/net.py#L660-L812
tryton/trytond
9fc68232536d0707b73614eab978bd6f813e3677
trytond/backend/database.py
python
DatabaseInterface.lock_id
(self, id, timeout=None)
Return SQL function to lock resource
Return SQL function to lock resource
[ "Return", "SQL", "function", "to", "lock", "resource" ]
def lock_id(self, id, timeout=None): """Return SQL function to lock resource""" raise NotImplementedError
[ "def", "lock_id", "(", "self", ",", "id", ",", "timeout", "=", "None", ")", ":", "raise", "NotImplementedError" ]
https://github.com/tryton/trytond/blob/9fc68232536d0707b73614eab978bd6f813e3677/trytond/backend/database.py#L140-L142
cherrypy/cherrypy
a7983fe61f7237f2354915437b04295694100372
cherrypy/lib/static.py
python
staticfile
(filename, root=None, match='', content_types=None, debug=False)
return _attempt(filename, content_types, debug=debug)
Serve a static resource from the given (root +) filename. match If given, request.path_info will be searched for the given regular expression before attempting to serve static content. content_types If given, it should be a Python dictionary of {file-extension: content-type} pairs, where 'file-extension' is a string (e.g. "gif") and 'content-type' is the value to write out in the Content-Type response header (e.g. "image/gif").
Serve a static resource from the given (root +) filename.
[ "Serve", "a", "static", "resource", "from", "the", "given", "(", "root", "+", ")", "filename", "." ]
def staticfile(filename, root=None, match='', content_types=None, debug=False): """Serve a static resource from the given (root +) filename. match If given, request.path_info will be searched for the given regular expression before attempting to serve static content. content_types If given, it should be a Python dictionary of {file-extension: content-type} pairs, where 'file-extension' is a string (e.g. "gif") and 'content-type' is the value to write out in the Content-Type response header (e.g. "image/gif"). """ request = cherrypy.serving.request if request.method not in ('GET', 'HEAD'): if debug: cherrypy.log('request.method not GET or HEAD', 'TOOLS.STATICFILE') return False if match and not re.search(match, request.path_info): if debug: cherrypy.log('request.path_info %r does not match pattern %r' % (request.path_info, match), 'TOOLS.STATICFILE') return False # If filename is relative, make absolute using "root". if not os.path.isabs(filename): if not root: msg = "Static tool requires an absolute filename (got '%s')." % ( filename,) if debug: cherrypy.log(msg, 'TOOLS.STATICFILE') raise ValueError(msg) filename = os.path.join(root, filename) return _attempt(filename, content_types, debug=debug)
[ "def", "staticfile", "(", "filename", ",", "root", "=", "None", ",", "match", "=", "''", ",", "content_types", "=", "None", ",", "debug", "=", "False", ")", ":", "request", "=", "cherrypy", ".", "serving", ".", "request", "if", "request", ".", "method"...
https://github.com/cherrypy/cherrypy/blob/a7983fe61f7237f2354915437b04295694100372/cherrypy/lib/static.py#L380-L416
psychopy/psychopy
01b674094f38d0e0bd51c45a6f66f671d7041696
psychopy/scripts/psyexpCompile.py
python
compileScript
(infile=None, version=None, outfile=None)
Compile either Python or JS PsychoPy script from .psyexp file. Parameters ---------- infile: string, experiment.Experiment object The input (psyexp) file to be compiled version: str The PsychoPy version to use for compiling the script. e.g. 1.84.1. Warning: Cannot set version if module imported. Set version from command line interface only. outfile: string The output file to be generated (defaults to Python script).
Compile either Python or JS PsychoPy script from .psyexp file.
[ "Compile", "either", "Python", "or", "JS", "PsychoPy", "script", "from", ".", "psyexp", "file", "." ]
def compileScript(infile=None, version=None, outfile=None): """ Compile either Python or JS PsychoPy script from .psyexp file. Parameters ---------- infile: string, experiment.Experiment object The input (psyexp) file to be compiled version: str The PsychoPy version to use for compiling the script. e.g. 1.84.1. Warning: Cannot set version if module imported. Set version from command line interface only. outfile: string The output file to be generated (defaults to Python script). """ def _setVersion(version): """ Sets the version to be used for compiling using the useVersion function Parameters ---------- version: string The version requested """ # Set version if version: from psychopy import useVersion useVersion(version) global logging from psychopy import logging if __name__ != '__main__' and version not in [None, 'None', 'none', '']: version = None msg = "You cannot set version by calling compileScript() manually. Setting 'version' to None." logging.warning(msg) return version def _getExperiment(infile, version): """ Get experiment if infile is not type experiment.Experiment. Parameters ---------- infile: string, experiment.Experiment object The input (psyexp) file to be compiled version: string The version requested Returns ------- experiment.Experiment The experiment object used for generating the experiment script """ # import PsychoPy experiment and write script with useVersion active from psychopy.app.builder import experiment # Check infile type if isinstance(infile, experiment.Experiment): thisExp = infile else: thisExp = experiment.Experiment() thisExp.loadFromXML(infile) thisExp.psychopyVersion = version return thisExp def _removeDisabledComponents(exp): """ Drop disabled components, if any. Parameters --------- exp : psychopy.experiment.Experiment The experiment from which to remove all components that have been marked `disabled`. Returns ------- exp : psychopy.experiment.Experiment The experiment with the disabled components removed. Notes ----- This function leaves the original experiment unchanged as it always only works on (and returns) a copy. """ # Leave original experiment unchanged. exp = deepcopy(exp) for key, routine in list(exp.routines.items()): # PY2/3 compat if routine.type == 'StandaloneRoutine': if routine.params['disabled']: for node in exp.flow: if node == routine: exp.flow.removeComponent(node) else: for component in routine: try: if component.params['disabled']: routine.removeComponent(component) except KeyError: pass return exp def _setTarget(outfile): """ Set target for compiling i.e., Python or JavaScript. Parameters ---------- outfile : string The output file to be generated (defaults to Python script). Returns ------- string The Python or JavaScript target type """ # Set output type, either JS or Python if outfile.endswith(".js"): targetOutput = "PsychoJS" else: targetOutput = "PsychoPy" return targetOutput def _makeTarget(thisExp, outfile, targetOutput): """ Generate the actual scripts for Python and/or JS. Parameters ---------- thisExp : experiment.Experiment object The current experiment created under requested version outfile : string The output file to be generated (defaults to Python script). targetOutput : string The Python or JavaScript target type """ # Write script if targetOutput == "PsychoJS": # Write module JS code script = thisExp.writeScript(outfile, target=targetOutput, modular=True) # Write no module JS code outfileNoModule = outfile.replace('.js', '-legacy-browsers.js') # For no JS module script scriptNoModule = thisExp.writeScript(outfileNoModule, target=targetOutput, modular=False) # Store scripts in list scriptDict = {'outfile': script, 'outfileNoModule': scriptNoModule} else: script = thisExp.writeScript(outfile, target=targetOutput) scriptDict = {'outfile': script} # Output script to file for scripts in scriptDict: if not type(scriptDict[scripts]) in (str, type(u'')): # We have a stringBuffer not plain string/text scriptText = scriptDict[scripts].getvalue() else: # We already have the text scriptText = scriptDict[scripts] with io.open(eval(scripts), 'w', encoding='utf-8-sig') as f: f.write(scriptText) return 1 ###### Write script ##### version = _setVersion(version) thisExp = _getExperiment(infile, version) thisExp = _removeDisabledComponents(thisExp) targetOutput = _setTarget(outfile) _makeTarget(thisExp, outfile, targetOutput)
[ "def", "compileScript", "(", "infile", "=", "None", ",", "version", "=", "None", ",", "outfile", "=", "None", ")", ":", "def", "_setVersion", "(", "version", ")", ":", "\"\"\"\n Sets the version to be used for compiling using the useVersion function\n\n Para...
https://github.com/psychopy/psychopy/blob/01b674094f38d0e0bd51c45a6f66f671d7041696/psychopy/scripts/psyexpCompile.py#L76-L247
praw-dev/praw
d1280b132f509ad115f3941fb55f13f979068377
praw/models/reddit/draft.py
python
Draft.delete
(self)
Delete the :class:`.Draft`. Example usage: .. code-block:: python draft = reddit.drafts(draft_id="124862bc-e1e9-11eb-aa4f-e68667a77cbb") draft.delete()
Delete the :class:`.Draft`.
[ "Delete", "the", ":", "class", ":", ".", "Draft", "." ]
def delete(self): """Delete the :class:`.Draft`. Example usage: .. code-block:: python draft = reddit.drafts(draft_id="124862bc-e1e9-11eb-aa4f-e68667a77cbb") draft.delete() """ self._reddit.delete(API_PATH["draft"], params={"draft_id": self.id})
[ "def", "delete", "(", "self", ")", ":", "self", ".", "_reddit", ".", "delete", "(", "API_PATH", "[", "\"draft\"", "]", ",", "params", "=", "{", "\"draft_id\"", ":", "self", ".", "id", "}", ")" ]
https://github.com/praw-dev/praw/blob/d1280b132f509ad115f3941fb55f13f979068377/praw/models/reddit/draft.py#L129-L140
karanchahal/distiller
a17ec06cbeafcdd2aea19d7c7663033c951392f5
models/cifar10sm/resnext.py
python
Bottleneck.__init__
(self, inplanes, planes, cardinality, baseWidth, stride=1, downsample=None)
[]
def __init__(self, inplanes, planes, cardinality, baseWidth, stride=1, downsample=None): super(Bottleneck, self).__init__() D = int(planes * (baseWidth / 64.)) C = cardinality self.conv1 = nn.Conv2d(inplanes, D*C, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(D*C) self.conv2 = nn.Conv2d(D*C, D*C, kernel_size=3, stride=stride, padding=1, groups=C, bias=False) self.bn2 = nn.BatchNorm2d(D*C) self.conv3 = nn.Conv2d(D*C, planes*4, kernel_size=1, bias=False) self.bn3 = nn.BatchNorm2d(planes*4) self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride
[ "def", "__init__", "(", "self", ",", "inplanes", ",", "planes", ",", "cardinality", ",", "baseWidth", ",", "stride", "=", "1", ",", "downsample", "=", "None", ")", ":", "super", "(", "Bottleneck", ",", "self", ")", ".", "__init__", "(", ")", "D", "="...
https://github.com/karanchahal/distiller/blob/a17ec06cbeafcdd2aea19d7c7663033c951392f5/models/cifar10sm/resnext.py#L16-L28
meraki/dashboard-api-python
aef5e6fe5d23a40d435d5c64ff30580a28af07f1
meraki/api/wireless.py
python
Wireless.getNetworkWirelessSsids
(self, networkId: str)
return self._session.get(metadata, resource)
**List the MR SSIDs in a network** https://developer.cisco.com/meraki/api-v1/#!get-network-wireless-ssids - networkId (string): (required)
**List the MR SSIDs in a network** https://developer.cisco.com/meraki/api-v1/#!get-network-wireless-ssids
[ "**", "List", "the", "MR", "SSIDs", "in", "a", "network", "**", "https", ":", "//", "developer", ".", "cisco", ".", "com", "/", "meraki", "/", "api", "-", "v1", "/", "#!get", "-", "network", "-", "wireless", "-", "ssids" ]
def getNetworkWirelessSsids(self, networkId: str): """ **List the MR SSIDs in a network** https://developer.cisco.com/meraki/api-v1/#!get-network-wireless-ssids - networkId (string): (required) """ metadata = { 'tags': ['wireless', 'configure', 'ssids'], 'operation': 'getNetworkWirelessSsids' } resource = f'/networks/{networkId}/wireless/ssids' return self._session.get(metadata, resource)
[ "def", "getNetworkWirelessSsids", "(", "self", ",", "networkId", ":", "str", ")", ":", "metadata", "=", "{", "'tags'", ":", "[", "'wireless'", ",", "'configure'", ",", "'ssids'", "]", ",", "'operation'", ":", "'getNetworkWirelessSsids'", "}", "resource", "=", ...
https://github.com/meraki/dashboard-api-python/blob/aef5e6fe5d23a40d435d5c64ff30580a28af07f1/meraki/api/wireless.py#L1142-L1156
KalleHallden/AutoTimer
2d954216700c4930baa154e28dbddc34609af7ce
env/lib/python2.7/site-packages/pip/_internal/index.py
python
PackageFinder._sort_links
(self, links)
return no_eggs + eggs
Returns elements of links in order, non-egg links first, egg links second, while eliminating duplicates
Returns elements of links in order, non-egg links first, egg links second, while eliminating duplicates
[ "Returns", "elements", "of", "links", "in", "order", "non", "-", "egg", "links", "first", "egg", "links", "second", "while", "eliminating", "duplicates" ]
def _sort_links(self, links): # type: (Iterable[Link]) -> List[Link] """ Returns elements of links in order, non-egg links first, egg links second, while eliminating duplicates """ eggs, no_eggs = [], [] seen = set() # type: Set[Link] for link in links: if link not in seen: seen.add(link) if link.egg_fragment: eggs.append(link) else: no_eggs.append(link) return no_eggs + eggs
[ "def", "_sort_links", "(", "self", ",", "links", ")", ":", "# type: (Iterable[Link]) -> List[Link]", "eggs", ",", "no_eggs", "=", "[", "]", ",", "[", "]", "seen", "=", "set", "(", ")", "# type: Set[Link]", "for", "link", "in", "links", ":", "if", "link", ...
https://github.com/KalleHallden/AutoTimer/blob/2d954216700c4930baa154e28dbddc34609af7ce/env/lib/python2.7/site-packages/pip/_internal/index.py#L1288-L1303
OpenSimulationInterface/open-simulation-interface
412521e7fc3fd3d66ec80df2688fb9794fdcc28b
format/OSITrace.py
python
OSITrace.retrieve_message_offsets
(self, max_index)
return len(self.message_offsets)
Retrieve the offsets of all the messages of the scenario and store them in the `message_offsets` attribute of the object It returns the number of discovered timesteps
Retrieve the offsets of all the messages of the scenario and store them in the `message_offsets` attribute of the object
[ "Retrieve", "the", "offsets", "of", "all", "the", "messages", "of", "the", "scenario", "and", "store", "them", "in", "the", "message_offsets", "attribute", "of", "the", "object" ]
def retrieve_message_offsets(self, max_index): """ Retrieve the offsets of all the messages of the scenario and store them in the `message_offsets` attribute of the object It returns the number of discovered timesteps """ scenario_size = get_size_from_file_stream(self.scenario_file) if max_index == -1: max_index = float('inf') buffer_deque = deque(maxlen=2) self.message_offsets = [0] eof = False self.scenario_file.seek(0) while not eof and len(self.message_offsets) <= max_index: found = -1 # SEP offset in buffer buffer_deque.clear() while found == -1 and not eof: new_read = self.scenario_file.read(BUFFER_SIZE) buffer_deque.append(new_read) buffer = b"".join(buffer_deque) found = buffer.find(SEPARATOR) eof = len(new_read) != BUFFER_SIZE buffer_offset = self.scenario_file.tell() - len(buffer) message_offset = found + buffer_offset + SEPARATOR_LENGTH self.message_offsets.append(message_offset) self.scenario_file.seek(message_offset) while eof and found != -1: buffer = buffer[found + SEPARATOR_LENGTH:] found = buffer.find(SEPARATOR) buffer_offset = scenario_size - len(buffer) message_offset = found + buffer_offset + SEPARATOR_LENGTH if message_offset >= scenario_size: break self.message_offsets.append(message_offset) if eof: self.retrieved_scenario_size = scenario_size else: self.retrieved_scenario_size = self.message_offsets[-1] self.message_offsets.pop() return len(self.message_offsets)
[ "def", "retrieve_message_offsets", "(", "self", ",", "max_index", ")", ":", "scenario_size", "=", "get_size_from_file_stream", "(", "self", ".", "scenario_file", ")", "if", "max_index", "==", "-", "1", ":", "max_index", "=", "float", "(", "'inf'", ")", "buffer...
https://github.com/OpenSimulationInterface/open-simulation-interface/blob/412521e7fc3fd3d66ec80df2688fb9794fdcc28b/format/OSITrace.py#L66-L120
bravoserver/bravo
7be5d792871a8447499911fa1502c6a7c1437dc3
bravo/inventory/__init__.py
python
Inventory.consume
(self, item, index)
return False
Attempt to remove a used holdable from the inventory. A return value of ``False`` indicates that there were no holdables of the given type and slot to consume. :param tuple item: a key representing the type of the item :param int slot: which slot was selected :returns: whether the item was successfully removed
Attempt to remove a used holdable from the inventory.
[ "Attempt", "to", "remove", "a", "used", "holdable", "from", "the", "inventory", "." ]
def consume(self, item, index): """ Attempt to remove a used holdable from the inventory. A return value of ``False`` indicates that there were no holdables of the given type and slot to consume. :param tuple item: a key representing the type of the item :param int slot: which slot was selected :returns: whether the item was successfully removed """ slot = self.holdables[index] # Can't really remove things from an empty slot... if slot is None: return False if slot.holds(item): self.holdables[index] = slot.decrement() return True return False
[ "def", "consume", "(", "self", ",", "item", ",", "index", ")", ":", "slot", "=", "self", ".", "holdables", "[", "index", "]", "# Can't really remove things from an empty slot...", "if", "slot", "is", "None", ":", "return", "False", "if", "slot", ".", "holds"...
https://github.com/bravoserver/bravo/blob/7be5d792871a8447499911fa1502c6a7c1437dc3/bravo/inventory/__init__.py#L74-L96
CouchPotato/CouchPotatoV1
135b3331d1b88ef645e29b76f2d4cc4a732c9232
library/sqlalchemy/schema.py
python
ColumnDefault._maybe_wrap_callable
(self, fn)
return fn
Backward compat: Wrap callables that don't accept a context.
Backward compat: Wrap callables that don't accept a context.
[ "Backward", "compat", ":", "Wrap", "callables", "that", "don", "t", "accept", "a", "context", "." ]
def _maybe_wrap_callable(self, fn): """Backward compat: Wrap callables that don't accept a context.""" if inspect.isfunction(fn): inspectable = fn elif inspect.isclass(fn): inspectable = fn.__init__ elif hasattr(fn, '__call__'): inspectable = fn.__call__ else: # probably not inspectable, try anyways. inspectable = fn try: argspec = inspect.getargspec(inspectable) except TypeError: return lambda ctx: fn() positionals = len(argspec[0]) # Py3K compat - no unbound methods if inspect.ismethod(inspectable) or inspect.isclass(fn): positionals -= 1 if positionals == 0: return lambda ctx: fn() defaulted = argspec[3] is not None and len(argspec[3]) or 0 if positionals - defaulted > 1: raise exc.ArgumentError( "ColumnDefault Python function takes zero or one " "positional arguments") return fn
[ "def", "_maybe_wrap_callable", "(", "self", ",", "fn", ")", ":", "if", "inspect", ".", "isfunction", "(", "fn", ")", ":", "inspectable", "=", "fn", "elif", "inspect", ".", "isclass", "(", "fn", ")", ":", "inspectable", "=", "fn", ".", "__init__", "elif...
https://github.com/CouchPotato/CouchPotatoV1/blob/135b3331d1b88ef645e29b76f2d4cc4a732c9232/library/sqlalchemy/schema.py#L1322-L1353
JJBOY/BMN-Boundary-Matching-Network
a92c1d79c19d88b1d57b5abfae5a0be33f3002eb
data/activitynet_feature_cuhk/data_process.py
python
poolData
(data,videoAnno,num_prop=100,num_bin=1,num_sample_bin=3,pool_type="mean")
return video_feature
[]
def poolData(data,videoAnno,num_prop=100,num_bin=1,num_sample_bin=3,pool_type="mean"): feature_frame=len(data)*16 video_frame=videoAnno['duration_frame'] video_second=videoAnno['duration_second'] corrected_second=float(feature_frame)/video_frame*video_second fps=float(video_frame)/video_second st=16/fps if len(data)==1: video_feature=np.stack([data]*num_prop) video_feature=np.reshape(video_feature,[num_prop,400]) return video_feature x=[st/2+ii*st for ii in range(len(data))] f=scipy.interpolate.interp1d(x,data,axis=0) video_feature=[] zero_sample=np.zeros(num_bin*400) tmp_anchor_xmin=[1.0/num_prop*i for i in range(num_prop)] tmp_anchor_xmax=[1.0/num_prop*i for i in range(1,num_prop+1)] num_sample=num_bin*num_sample_bin for idx in range(num_prop): xmin=max(x[0]+0.0001,tmp_anchor_xmin[idx]*corrected_second) xmax=min(x[-1]-0.0001,tmp_anchor_xmax[idx]*corrected_second) if xmax<x[0]: #print "fuck" video_feature.append(zero_sample) continue if xmin>x[-1]: video_feature.append(zero_sample) continue plen=(xmax-xmin)/(num_sample-1) x_new=[xmin+plen*ii for ii in range(num_sample)] y_new=f(x_new) y_new_pool=[] for b in range(num_bin): tmp_y_new=y_new[num_sample_bin*b:num_sample_bin*(b+1)] if pool_type=="mean": tmp_y_new=np.mean(y_new,axis=0) elif pool_type=="max": tmp_y_new=np.max(y_new,axis=0) y_new_pool.append(tmp_y_new) y_new_pool=np.stack(y_new_pool) y_new_pool=np.reshape(y_new_pool,[-1]) video_feature.append(y_new_pool) video_feature=np.stack(video_feature) return video_feature
[ "def", "poolData", "(", "data", ",", "videoAnno", ",", "num_prop", "=", "100", ",", "num_bin", "=", "1", ",", "num_sample_bin", "=", "3", ",", "pool_type", "=", "\"mean\"", ")", ":", "feature_frame", "=", "len", "(", "data", ")", "*", "16", "video_fram...
https://github.com/JJBOY/BMN-Boundary-Matching-Network/blob/a92c1d79c19d88b1d57b5abfae5a0be33f3002eb/data/activitynet_feature_cuhk/data_process.py#L62-L110
compas-dev/compas
0b33f8786481f710115fb1ae5fe79abc2a9a5175
src/compas_rhino/conversions/cone.py
python
RhinoCone.geometry
(self, geometry)
Set the geometry of the wrapper. Parameters ---------- geometry : :rhino:`Rhino_Geometry_Cone` or :class:`compas.geometry.Cone` The geometry object defining a cone. Raises ------ :class:`ConversionError` If the geometry cannot be converted to a cone.
Set the geometry of the wrapper.
[ "Set", "the", "geometry", "of", "the", "wrapper", "." ]
def geometry(self, geometry): """Set the geometry of the wrapper. Parameters ---------- geometry : :rhino:`Rhino_Geometry_Cone` or :class:`compas.geometry.Cone` The geometry object defining a cone. Raises ------ :class:`ConversionError` If the geometry cannot be converted to a cone. """ if not isinstance(geometry, Rhino.Geometry.Cone): if isinstance(geometry, Rhino.Geometry.Brep): if geometry.Faces.Count > 2: raise ConversionError('Object brep cannot be converted to a cone.') faces = geometry.Faces geometry = None for face in faces: if face.IsCone(): result, geometry = face.TryGetCone() if result: break if not geometry: raise ConversionError('Object brep cannot be converted to a cone.') elif isinstance(geometry, Cone): geometry = cone_to_rhino(geometry) else: raise ConversionError('Geometry object cannot be converted to a cone: {}'.format(geometry)) self._geometry = geometry
[ "def", "geometry", "(", "self", ",", "geometry", ")", ":", "if", "not", "isinstance", "(", "geometry", ",", "Rhino", ".", "Geometry", ".", "Cone", ")", ":", "if", "isinstance", "(", "geometry", ",", "Rhino", ".", "Geometry", ".", "Brep", ")", ":", "i...
https://github.com/compas-dev/compas/blob/0b33f8786481f710115fb1ae5fe79abc2a9a5175/src/compas_rhino/conversions/cone.py#L25-L55
meduza-corp/interstellar
40a801ccd7856491726f5a126621d9318cabe2e1
gsutil/third_party/boto/boto/dynamodb/layer1.py
python
Layer1.batch_write_item
(self, request_items, object_hook=None)
return self.make_request('BatchWriteItem', json_input, object_hook=object_hook)
This operation enables you to put or delete several items across multiple tables in a single API call. :type request_items: dict :param request_items: A Python version of the RequestItems data structure defined by DynamoDB.
This operation enables you to put or delete several items across multiple tables in a single API call.
[ "This", "operation", "enables", "you", "to", "put", "or", "delete", "several", "items", "across", "multiple", "tables", "in", "a", "single", "API", "call", "." ]
def batch_write_item(self, request_items, object_hook=None): """ This operation enables you to put or delete several items across multiple tables in a single API call. :type request_items: dict :param request_items: A Python version of the RequestItems data structure defined by DynamoDB. """ data = {'RequestItems': request_items} json_input = json.dumps(data) return self.make_request('BatchWriteItem', json_input, object_hook=object_hook)
[ "def", "batch_write_item", "(", "self", ",", "request_items", ",", "object_hook", "=", "None", ")", ":", "data", "=", "{", "'RequestItems'", ":", "request_items", "}", "json_input", "=", "json", ".", "dumps", "(", "data", ")", "return", "self", ".", "make_...
https://github.com/meduza-corp/interstellar/blob/40a801ccd7856491726f5a126621d9318cabe2e1/gsutil/third_party/boto/boto/dynamodb/layer1.py#L333-L345
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/tiw/v20190919/tiw_client.py
python
TiwClient.DescribeOnlineRecord
(self, request)
查询录制任务状态与结果 :param request: Request instance for DescribeOnlineRecord. :type request: :class:`tencentcloud.tiw.v20190919.models.DescribeOnlineRecordRequest` :rtype: :class:`tencentcloud.tiw.v20190919.models.DescribeOnlineRecordResponse`
查询录制任务状态与结果
[ "查询录制任务状态与结果" ]
def DescribeOnlineRecord(self, request): """查询录制任务状态与结果 :param request: Request instance for DescribeOnlineRecord. :type request: :class:`tencentcloud.tiw.v20190919.models.DescribeOnlineRecordRequest` :rtype: :class:`tencentcloud.tiw.v20190919.models.DescribeOnlineRecordResponse` """ try: params = request._serialize() body = self.call("DescribeOnlineRecord", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeOnlineRecordResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message)
[ "def", "DescribeOnlineRecord", "(", "self", ",", "request", ")", ":", "try", ":", "params", "=", "request", ".", "_serialize", "(", ")", "body", "=", "self", ".", "call", "(", "\"DescribeOnlineRecord\"", ",", "params", ")", "response", "=", "json", ".", ...
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/tiw/v20190919/tiw_client.py#L113-L138
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
source/addons/account/account.py
python
account_journal.name_get
(self, cr, user, ids, context=None)
return res
Returns a list of tupples containing id, name. result format: {[(id, name), (id, name), ...]} @param cr: A database cursor @param user: ID of the user currently logged in @param ids: list of ids for which name should be read @param context: context arguments, like lang, time zone @return: Returns a list of tupples containing id, name
Returns a list of tupples containing id, name. result format: {[(id, name), (id, name), ...]}
[ "Returns", "a", "list", "of", "tupples", "containing", "id", "name", ".", "result", "format", ":", "{", "[", "(", "id", "name", ")", "(", "id", "name", ")", "...", "]", "}" ]
def name_get(self, cr, user, ids, context=None): """ Returns a list of tupples containing id, name. result format: {[(id, name), (id, name), ...]} @param cr: A database cursor @param user: ID of the user currently logged in @param ids: list of ids for which name should be read @param context: context arguments, like lang, time zone @return: Returns a list of tupples containing id, name """ if not ids: return [] if isinstance(ids, (int, long)): ids = [ids] result = self.browse(cr, user, ids, context=context) res = [] for rs in result: if rs.currency: currency = rs.currency else: currency = rs.company_id.currency_id name = "%s (%s)" % (rs.name, currency.name) res += [(rs.id, name)] return res
[ "def", "name_get", "(", "self", ",", "cr", ",", "user", ",", "ids", ",", "context", "=", "None", ")", ":", "if", "not", "ids", ":", "return", "[", "]", "if", "isinstance", "(", "ids", ",", "(", "int", ",", "long", ")", ")", ":", "ids", "=", "...
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/source/addons/account/account.py#L837-L862
phonopy/phonopy
816586d0ba8177482ecf40e52f20cbdee2260d51
phonopy/interface/calculator.py
python
get_force_sets
( interface_mode, num_atoms, force_filenames, verbose=True, )
return force_sets
Read calculator output files and parse force sets. Note ---- Wien2k output is treated by ``get_force_sets_wien2k``.
Read calculator output files and parse force sets.
[ "Read", "calculator", "output", "files", "and", "parse", "force", "sets", "." ]
def get_force_sets( interface_mode, num_atoms, force_filenames, verbose=True, ): """Read calculator output files and parse force sets. Note ---- Wien2k output is treated by ``get_force_sets_wien2k``. """ if interface_mode is None or interface_mode == "vasp": from phonopy.interface.vasp import parse_set_of_forces elif interface_mode == "abinit": from phonopy.interface.abinit import parse_set_of_forces elif interface_mode == "qe": from phonopy.interface.qe import parse_set_of_forces elif interface_mode == "elk": from phonopy.interface.elk import parse_set_of_forces elif interface_mode == "siesta": from phonopy.interface.siesta import parse_set_of_forces elif interface_mode == "cp2k": from phonopy.interface.cp2k import parse_set_of_forces elif interface_mode == "crystal": from phonopy.interface.crystal import parse_set_of_forces elif interface_mode == "dftbp": from phonopy.interface.dftbp import parse_set_of_forces elif interface_mode == "turbomole": from phonopy.interface.turbomole import parse_set_of_forces elif interface_mode == "aims": from phonopy.interface.aims import parse_set_of_forces elif interface_mode == "castep": from phonopy.interface.castep import parse_set_of_forces elif interface_mode == "fleur": from phonopy.interface.fleur import parse_set_of_forces else: return [] force_sets = parse_set_of_forces(num_atoms, force_filenames, verbose=verbose) return force_sets
[ "def", "get_force_sets", "(", "interface_mode", ",", "num_atoms", ",", "force_filenames", ",", "verbose", "=", "True", ",", ")", ":", "if", "interface_mode", "is", "None", "or", "interface_mode", "==", "\"vasp\"", ":", "from", "phonopy", ".", "interface", ".",...
https://github.com/phonopy/phonopy/blob/816586d0ba8177482ecf40e52f20cbdee2260d51/phonopy/interface/calculator.py#L644-L687
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/python/lib/python2.7/site-packages/docutils/utils/math/math2html.py
python
Globable.checkfor
(self, string)
return False
Check for the given string in the current position.
Check for the given string in the current position.
[ "Check", "for", "the", "given", "string", "in", "the", "current", "position", "." ]
def checkfor(self, string): "Check for the given string in the current position." Trace.error('Unimplemented checkfor()') return False
[ "def", "checkfor", "(", "self", ",", "string", ")", ":", "Trace", ".", "error", "(", "'Unimplemented checkfor()'", ")", "return", "False" ]
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/site-packages/docutils/utils/math/math2html.py#L1748-L1751
numba/numba
bf480b9e0da858a65508c2b17759a72ee6a44c51
numba/parfors/array_analysis.py
python
ArrayAnalysis._analyze_op_cast
(self, scope, equiv_set, expr, lhs)
return ArrayAnalysis.AnalyzeResult(shape=expr.value)
[]
def _analyze_op_cast(self, scope, equiv_set, expr, lhs): return ArrayAnalysis.AnalyzeResult(shape=expr.value)
[ "def", "_analyze_op_cast", "(", "self", ",", "scope", ",", "equiv_set", ",", "expr", ",", "lhs", ")", ":", "return", "ArrayAnalysis", ".", "AnalyzeResult", "(", "shape", "=", "expr", ".", "value", ")" ]
https://github.com/numba/numba/blob/bf480b9e0da858a65508c2b17759a72ee6a44c51/numba/parfors/array_analysis.py#L1595-L1596
rotki/rotki
aafa446815cdd5e9477436d1b02bee7d01b398c8
rotkehlchen/exchanges/kraken.py
python
Kraken.process_kraken_trades
( self, raw_data: List[HistoryBaseEntry], )
return trades, Timestamp(max_ts)
Given a list of history events we process them to create Trade objects. The valid History events type are - Trade - Receive - Spend - Adjustment A pair of receive and spend events can be a trade and kraken uses this kind of event for instant trades and trades made from the phone app. What we do in order to verify that it is a trade is to check if we can find a pair with the same event id. Also in some rare occasions Kraken may forcibly adjust something for you. Example would be delisting of DAO token and forcible exchange to ETH. Returns: - The list of trades processed - The biggest timestamp of all the trades processed May raise: - RemoteError if the pairs couldn't be correctly queried
Given a list of history events we process them to create Trade objects. The valid History events type are - Trade - Receive - Spend - Adjustment
[ "Given", "a", "list", "of", "history", "events", "we", "process", "them", "to", "create", "Trade", "objects", ".", "The", "valid", "History", "events", "type", "are", "-", "Trade", "-", "Receive", "-", "Spend", "-", "Adjustment" ]
def process_kraken_trades( self, raw_data: List[HistoryBaseEntry], ) -> Tuple[List[Trade], Timestamp]: """ Given a list of history events we process them to create Trade objects. The valid History events type are - Trade - Receive - Spend - Adjustment A pair of receive and spend events can be a trade and kraken uses this kind of event for instant trades and trades made from the phone app. What we do in order to verify that it is a trade is to check if we can find a pair with the same event id. Also in some rare occasions Kraken may forcibly adjust something for you. Example would be delisting of DAO token and forcible exchange to ETH. Returns: - The list of trades processed - The biggest timestamp of all the trades processed May raise: - RemoteError if the pairs couldn't be correctly queried """ trades = [] max_ts = 0 get_attr = operator.attrgetter('event_identifier') adjustments: List[HistoryBaseEntry] = [] # Create a list of lists where each sublist has the events for the same event identifier grouped_events = [list(g) for k, g in itertools.groupby(sorted(raw_data, key=get_attr), get_attr)] # noqa: E501 for trade_parts in grouped_events: trade = self.process_kraken_events_for_trade(trade_parts, adjustments) if trade is None: continue trades.append(trade) max_ts = max(max_ts, trade.timestamp) adjustments.sort(key=lambda x: x.timestamp) if len(adjustments) % 2 == 0: for a1, a2 in pairwise(adjustments): if a1.event_subtype is None or a2.event_subtype is None: log.warning( f'Found two kraken adjustment entries without a subtype: {a1} {a2}', ) continue if a1.event_subtype == HistoryEventSubType.SPEND and a2.event_subtype == HistoryEventSubType.RECEIVE: # noqa: E501 spend_event = a1 receive_event = a2 elif a2.event_subtype == HistoryEventSubType.SPEND and a2.event_subtype == HistoryEventSubType.RECEIVE: # noqa: E501 spend_event = a2 receive_event = a1 else: log.warning( f'Found two kraken adjustment with unmatching subtype {a1} {a2}', ) continue rate = Price(abs(receive_event.asset_balance.balance.amount / spend_event.asset_balance.balance.amount)) # noqa: E501 trade = Trade( timestamp=Timestamp(int(a1.timestamp / KRAKEN_TS_MULTIPLIER)), location=Location.KRAKEN, base_asset=receive_event.asset_balance.asset, quote_asset=spend_event.asset_balance.asset, trade_type=TradeType.BUY, amount=AssetAmount(receive_event.asset_balance.balance.amount), rate=rate, fee=None, fee_currency=None, link='adjustment' + a1.event_identifier + a2.event_identifier, ) trades.append(trade) else: log.warning( f'Got even number of kraken adjustment historic entries. ' f'Skipping reading them. {adjustments}', ) return trades, Timestamp(max_ts)
[ "def", "process_kraken_trades", "(", "self", ",", "raw_data", ":", "List", "[", "HistoryBaseEntry", "]", ",", ")", "->", "Tuple", "[", "List", "[", "Trade", "]", ",", "Timestamp", "]", ":", "trades", "=", "[", "]", "max_ts", "=", "0", "get_attr", "=", ...
https://github.com/rotki/rotki/blob/aafa446815cdd5e9477436d1b02bee7d01b398c8/rotkehlchen/exchanges/kraken.py#L973-L1055
pulp/pulp
a0a28d804f997b6f81c391378aff2e4c90183df9
streamer/pulp/streamer/cache.py
python
Cache.add
(self, key, object_)
Add an object to the cache. Args: key (hashable): The caching key. object_ (object): An object to be cached.
Add an object to the cache.
[ "Add", "an", "object", "to", "the", "cache", "." ]
def add(self, key, object_): """ Add an object to the cache. Args: key (hashable): The caching key. object_ (object): An object to be cached. """ with self._lock: self._inventory[key] = Item(object_)
[ "def", "add", "(", "self", ",", "key", ",", "object_", ")", ":", "with", "self", ".", "_lock", ":", "self", ".", "_inventory", "[", "key", "]", "=", "Item", "(", "object_", ")" ]
https://github.com/pulp/pulp/blob/a0a28d804f997b6f81c391378aff2e4c90183df9/streamer/pulp/streamer/cache.py#L39-L48
pyparallel/pyparallel
11e8c6072d48c8f13641925d17b147bf36ee0ba3
Lib/tkinter/tix.py
python
CheckList.open
(self, entrypath)
Open the entry given by entryPath if its mode is open.
Open the entry given by entryPath if its mode is open.
[ "Open", "the", "entry", "given", "by", "entryPath", "if", "its", "mode", "is", "open", "." ]
def open(self, entrypath): '''Open the entry given by entryPath if its mode is open.''' self.tk.call(self._w, 'open', entrypath)
[ "def", "open", "(", "self", ",", "entrypath", ")", ":", "self", ".", "tk", ".", "call", "(", "self", ".", "_w", ",", "'open'", ",", "entrypath", ")" ]
https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/tkinter/tix.py#L1574-L1576
nonebot/aiocqhttp
eaa850e8d7432e04394194b3d82bb88570390732
aiocqhttp/message.py
python
MessageSegment.type
(self, type_: str)
[]
def type(self, type_: str): self['type'] = type_
[ "def", "type", "(", "self", ",", "type_", ":", "str", ")", ":", "self", "[", "'type'", "]", "=", "type_" ]
https://github.com/nonebot/aiocqhttp/blob/eaa850e8d7432e04394194b3d82bb88570390732/aiocqhttp/message.py#L115-L116
trailofbits/manticore
b050fdf0939f6c63f503cdf87ec0ab159dd41159
manticore/platforms/evm.py
python
EVM.SELFDESTRUCT
(self, recipient)
Halt execution and register account for later deletion
Halt execution and register account for later deletion
[ "Halt", "execution", "and", "register", "account", "for", "later", "deletion" ]
def SELFDESTRUCT(self, recipient): """Halt execution and register account for later deletion""" # This may create a user account recipient = Operators.EXTRACT(recipient, 0, 160) address = self.address if recipient not in self.world: self.world.create_account(address=recipient) self.world.send_funds(address, recipient, self.world.get_balance(address)) self.world.delete_account(address) raise EndTx("SELFDESTRUCT")
[ "def", "SELFDESTRUCT", "(", "self", ",", "recipient", ")", ":", "# This may create a user account", "recipient", "=", "Operators", ".", "EXTRACT", "(", "recipient", ",", "0", ",", "160", ")", "address", "=", "self", ".", "address", "if", "recipient", "not", ...
https://github.com/trailofbits/manticore/blob/b050fdf0939f6c63f503cdf87ec0ab159dd41159/manticore/platforms/evm.py#L2318-L2330
CalebBell/thermo
572a47d1b03d49fe609b8d5f826fa6a7cde00828
thermo/eos_mix.py
python
GCEOSMIX.d2G_dep_dninjs
(self, Z)
return self._d2_G_dep_lnphi_d2_helper(V=V, d2Vs=d2Vs, d_Vs=dV_dns, dbs=db_dns, d2bs=d2bs, d_epsilons=depsilon_dns, d2_epsilons=d2epsilon_dninjs, d_deltas=ddelta_dns, d2_deltas=d2delta_dninjs, da_alphas=da_alpha_dns, d2a_alphas=d2a_alpha_dninjs, G=True)
r'''Calculates the molar departure Gibbs energy mole number derivatives (where the mole fractions sum to 1). No specific formula is implemented for this property - it is calculated from the mole fraction derivative. .. math:: \left(\frac{\partial^2 G_{dep}}{\partial n_j \partial n_i}\right)_{T, P, n_{i,j\ne k}} = f\left( \left(\frac{\partial^2 G_{dep}}{\partial x_j \partial x_i}\right)_{T, P, x_{i,j\ne k}} \right) Parameters ---------- Z : float Compressibility of the mixture for a desired phase, [-] Returns ------- d2G_dep_dninjs : float Departure Gibbs energy second mole number derivatives, [J/mol^3]
r'''Calculates the molar departure Gibbs energy mole number derivatives (where the mole fractions sum to 1). No specific formula is implemented for this property - it is calculated from the mole fraction derivative.
[ "r", "Calculates", "the", "molar", "departure", "Gibbs", "energy", "mole", "number", "derivatives", "(", "where", "the", "mole", "fractions", "sum", "to", "1", ")", ".", "No", "specific", "formula", "is", "implemented", "for", "this", "property", "-", "it", ...
def d2G_dep_dninjs(self, Z): r'''Calculates the molar departure Gibbs energy mole number derivatives (where the mole fractions sum to 1). No specific formula is implemented for this property - it is calculated from the mole fraction derivative. .. math:: \left(\frac{\partial^2 G_{dep}}{\partial n_j \partial n_i}\right)_{T, P, n_{i,j\ne k}} = f\left( \left(\frac{\partial^2 G_{dep}}{\partial x_j \partial x_i}\right)_{T, P, x_{i,j\ne k}} \right) Parameters ---------- Z : float Compressibility of the mixture for a desired phase, [-] Returns ------- d2G_dep_dninjs : float Departure Gibbs energy second mole number derivatives, [J/mol^3] ''' V = Z*self.T*R/self.P dV_dns = self.dV_dns(Z) d2Vs = self.d2V_dninjs(Z) depsilon_dns = self.depsilon_dns d2epsilon_dninjs = self.d2epsilon_dninjs ddelta_dns = self.ddelta_dns d2delta_dninjs = self.d2delta_dninjs db_dns = self.db_dns d2bs = self.d2b_dninjs da_alpha_dns = self.da_alpha_dns d2a_alpha_dninjs = self.d2a_alpha_dninjs return self._d2_G_dep_lnphi_d2_helper(V=V, d2Vs=d2Vs, d_Vs=dV_dns, dbs=db_dns, d2bs=d2bs, d_epsilons=depsilon_dns, d2_epsilons=d2epsilon_dninjs, d_deltas=ddelta_dns, d2_deltas=d2delta_dninjs, da_alphas=da_alpha_dns, d2a_alphas=d2a_alpha_dninjs, G=True)
[ "def", "d2G_dep_dninjs", "(", "self", ",", "Z", ")", ":", "V", "=", "Z", "*", "self", ".", "T", "*", "R", "/", "self", ".", "P", "dV_dns", "=", "self", ".", "dV_dns", "(", "Z", ")", "d2Vs", "=", "self", ".", "d2V_dninjs", "(", "Z", ")", "deps...
https://github.com/CalebBell/thermo/blob/572a47d1b03d49fe609b8d5f826fa6a7cde00828/thermo/eos_mix.py#L4700-L4739
IronLanguages/main
a949455434b1fda8c783289e897e78a9a0caabb5
External.LCA_RESTRICTED/Languages/IronPython/27/Doc/docutils/readers/__init__.py
python
Reader.set_parser
(self, parser_name)
Set `self.parser` by name.
Set `self.parser` by name.
[ "Set", "self", ".", "parser", "by", "name", "." ]
def set_parser(self, parser_name): """Set `self.parser` by name.""" parser_class = parsers.get_parser_class(parser_name) self.parser = parser_class()
[ "def", "set_parser", "(", "self", ",", "parser_name", ")", ":", "parser_class", "=", "parsers", ".", "get_parser_class", "(", "parser_name", ")", "self", ".", "parser", "=", "parser_class", "(", ")" ]
https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/IronPython/27/Doc/docutils/readers/__init__.py#L58-L61