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
XX-net/XX-Net
a9898cfcf0084195fb7e69b6bc834e59aecdf14f
python3.8.2/Lib/site-packages/cerealizer/__init__.py
python
Handler.undump_data
(self, obj, dumper, s)
Handler.undump_data(obj, dumper, s) Reads the data for OBJ, from DUMPER and file S. If you override undump_data, you should use DUMPER.undump_ref(S) to read a reference or a basic type (=a string, an int,...).
Handler.undump_data(obj, dumper, s)
[ "Handler", ".", "undump_data", "(", "obj", "dumper", "s", ")" ]
def undump_data(self, obj, dumper, s): """Handler.undump_data(obj, dumper, s) Reads the data for OBJ, from DUMPER and file S. If you override undump_data, you should use DUMPER.undump_ref(S) to read a reference or a basic type (=a string, an int,...)."""
[ "def", "undump_data", "(", "self", ",", "obj", ",", "dumper", ",", "s", ")", ":" ]
https://github.com/XX-net/XX-Net/blob/a9898cfcf0084195fb7e69b6bc834e59aecdf14f/python3.8.2/Lib/site-packages/cerealizer/__init__.py#L268-L273
tuckerbalch/QSTK
4981506c37227a72404229d5e1e0887f797a5d57
epydoc-3.0.1/epydoc/gui.py
python
_version
()
Display the version information, and exit. @rtype: C{None}
Display the version information, and exit.
[ "Display", "the", "version", "information", "and", "exit", "." ]
def _version(): """ Display the version information, and exit. @rtype: C{None} """ import epydoc print "Epydoc version %s" % epydoc.__version__ sys.exit(0)
[ "def", "_version", "(", ")", ":", "import", "epydoc", "print", "\"Epydoc version %s\"", "%", "epydoc", ".", "__version__", "sys", ".", "exit", "(", "0", ")" ]
https://github.com/tuckerbalch/QSTK/blob/4981506c37227a72404229d5e1e0887f797a5d57/epydoc-3.0.1/epydoc/gui.py#L1084-L1091
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/django-extensions-1.8.0/django_extensions/management/commands/sqldiff.py
python
PostgresqlSQLDiff.get_constraints
(self, cursor, table_name, introspection)
return constraints
backport of django's introspection.get_constraints(...)
backport of django's introspection.get_constraints(...)
[ "backport", "of", "django", "s", "introspection", ".", "get_constraints", "(", "...", ")" ]
def get_constraints(self, cursor, table_name, introspection): """ backport of django's introspection.get_constraints(...) """ constraints = {} # Loop over the key table, collecting things as constraints # This will get PKs, FKs, and uniques, but not CHECK cursor.execute(""" SELECT kc.constraint_name, kc.column_name, c.constraint_type, array(SELECT table_name::text || '.' || column_name::text FROM information_schema.constraint_column_usage WHERE constraint_name = kc.constraint_name) FROM information_schema.key_column_usage AS kc JOIN information_schema.table_constraints AS c ON kc.table_schema = c.table_schema AND kc.table_name = c.table_name AND kc.constraint_name = c.constraint_name WHERE kc.table_schema = %s AND kc.table_name = %s """, ["public", table_name]) for constraint, column, kind, used_cols in cursor.fetchall(): # If we're the first column, make the record if constraint not in constraints: constraints[constraint] = { "columns": [], "primary_key": kind.lower() == "primary key", "unique": kind.lower() in ["primary key", "unique"], "foreign_key": tuple(used_cols[0].split(".", 1)) if kind.lower() == "foreign key" else None, "check": False, "index": False, } # Record the details constraints[constraint]['columns'].append(column) # Now get CHECK constraint columns cursor.execute(""" SELECT kc.constraint_name, kc.column_name FROM information_schema.constraint_column_usage AS kc JOIN information_schema.table_constraints AS c ON kc.table_schema = c.table_schema AND kc.table_name = c.table_name AND kc.constraint_name = c.constraint_name WHERE c.constraint_type = 'CHECK' AND kc.table_schema = %s AND kc.table_name = %s """, ["public", table_name]) for constraint, column in cursor.fetchall(): # If we're the first column, make the record if constraint not in constraints: constraints[constraint] = { "columns": [], "primary_key": False, "unique": False, "foreign_key": None, "check": True, "index": False, } # Record the details constraints[constraint]['columns'].append(column) # Now get indexes cursor.execute(""" SELECT c2.relname, ARRAY( SELECT (SELECT attname FROM pg_catalog.pg_attribute WHERE attnum = i AND attrelid = c.oid) FROM unnest(idx.indkey) i ), idx.indisunique, idx.indisprimary FROM pg_catalog.pg_class c, pg_catalog.pg_class c2, pg_catalog.pg_index idx WHERE c.oid = idx.indrelid AND idx.indexrelid = c2.oid AND c.relname = %s """, [table_name]) for index, columns, unique, primary in cursor.fetchall(): if index not in constraints: constraints[index] = { "columns": list(columns), "primary_key": primary, "unique": unique, "foreign_key": None, "check": False, "index": True, } return constraints
[ "def", "get_constraints", "(", "self", ",", "cursor", ",", "table_name", ",", "introspection", ")", ":", "constraints", "=", "{", "}", "# Loop over the key table, collecting things as constraints", "# This will get PKs, FKs, and uniques, but not CHECK", "cursor", ".", "execut...
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/django-extensions-1.8.0/django_extensions/management/commands/sqldiff.py#L753-L838
log2timeline/plaso
fe2e316b8c76a0141760c0f2f181d84acb83abc2
plaso/multi_process/analysis_engine.py
python
AnalysisMultiProcessEngine.AnalyzeEvents
( self, session, knowledge_base_object, storage_writer, data_location, analysis_plugins, processing_configuration, event_filter=None, event_filter_expression=None, status_update_callback=None, storage_file_path=None)
return self._processing_status
Analyzes events in a Plaso storage. Args: session (Session): session in which the events are analyzed. knowledge_base_object (KnowledgeBase): contains information from the source data needed for processing. storage_writer (StorageWriter): storage writer. data_location (str): path to the location that data files should be loaded from. analysis_plugins (dict[str, AnalysisPlugin]): analysis plugins that should be run and their names. processing_configuration (ProcessingConfiguration): processing configuration. event_filter (Optional[EventObjectFilter]): event filter. event_filter_expression (Optional[str]): event filter expression. status_update_callback (Optional[function]): callback function for status updates. storage_file_path (Optional[str]): path to the session storage file. Returns: ProcessingStatus: processing status. Raises: KeyboardInterrupt: if a keyboard interrupt was raised. ValueError: if analysis plugins are missing.
Analyzes events in a Plaso storage.
[ "Analyzes", "events", "in", "a", "Plaso", "storage", "." ]
def AnalyzeEvents( self, session, knowledge_base_object, storage_writer, data_location, analysis_plugins, processing_configuration, event_filter=None, event_filter_expression=None, status_update_callback=None, storage_file_path=None): """Analyzes events in a Plaso storage. Args: session (Session): session in which the events are analyzed. knowledge_base_object (KnowledgeBase): contains information from the source data needed for processing. storage_writer (StorageWriter): storage writer. data_location (str): path to the location that data files should be loaded from. analysis_plugins (dict[str, AnalysisPlugin]): analysis plugins that should be run and their names. processing_configuration (ProcessingConfiguration): processing configuration. event_filter (Optional[EventObjectFilter]): event filter. event_filter_expression (Optional[str]): event filter expression. status_update_callback (Optional[function]): callback function for status updates. storage_file_path (Optional[str]): path to the session storage file. Returns: ProcessingStatus: processing status. Raises: KeyboardInterrupt: if a keyboard interrupt was raised. ValueError: if analysis plugins are missing. """ if not analysis_plugins: raise ValueError('Missing analysis plugins') abort_kill = False keyboard_interrupt = False queue_full = False self._analysis_plugins = {} self._data_location = data_location self._event_filter_expression = event_filter_expression self._events_status = processing_status.EventsStatus() self._knowledge_base = knowledge_base_object self._processing_configuration = processing_configuration self._session = session self._status_update_callback = status_update_callback self._storage_file_path = storage_file_path stored_event_labels_counter = {} if storage_writer.HasAttributeContainers('event_label_count'): stored_event_labels_counter = { event_label_count.label: event_label_count for event_label_count in storage_writer.GetAttributeContainers( 'event_label_count')} self._event_labels_counter = collections.Counter() if storage_writer.HasAttributeContainers('parser_count'): parsers_counter = { parser_count.name: parser_count.number_of_events for parser_count in storage_writer.GetAttributeContainers( 'parser_count')} total_number_of_events = parsers_counter['total'] else: total_number_of_events = 0 for stored_session in storage_writer.GetSessions(): total_number_of_events += stored_session.parsers_counter['total'] self._events_status.total_number_of_events = total_number_of_events # Set up the storage writer before the analysis processes. self._StartTaskStorage(definitions.STORAGE_FORMAT_SQLITE) self._StartAnalysisProcesses(analysis_plugins) self._StartProfiling(self._processing_configuration.profiling) # Start the status update thread after open of the storage writer # so we don't have to clean up the thread if the open fails. self._StartStatusUpdateThread() try: self._AnalyzeEvents( storage_writer, analysis_plugins, event_filter=event_filter) for key, value in self._event_labels_counter.items(): event_label_count = stored_event_labels_counter.get(key, None) if event_label_count: event_label_count.number_of_events += value storage_writer.UpdateAttributeContainer(event_label_count) else: event_label_count = counts.EventLabelCount( label=key, number_of_events=value) storage_writer.AddAttributeContainer(event_label_count) self._status = definitions.STATUS_INDICATOR_FINALIZING except errors.QueueFull: queue_full = True self._abort = True except KeyboardInterrupt: keyboard_interrupt = True self._abort = True finally: self._processing_status.aborted = self._abort session.aborted = self._abort # Stop the status update thread after close of the storage writer # so we include the storage sync to disk in the status updates. self._StopStatusUpdateThread() self._StopProfiling() # Update the status view one last time before the analysis processses are # stopped. self._UpdateStatus() if queue_full: # TODO: handle abort on queue full more elegant. abort_kill = True else: try: self._StopAnalysisProcesses(abort=self._abort) except KeyboardInterrupt: keyboard_interrupt = True abort_kill = True if abort_kill: self._AbortKill() # The abort can leave the main process unresponsive # due to incorrectly finalized IPC. self._KillProcess(os.getpid()) try: self._StopTaskStorage( definitions.STORAGE_FORMAT_SQLITE, session.identifier, abort=self._abort) except (IOError, OSError) as exception: logger.error('Unable to stop task storage with error: {0!s}'.format( exception)) if self._abort: logger.debug('Analysis aborted.') else: logger.debug('Analysis completed.') # Update the status view one last time. self._UpdateStatus() # Reset values. self._analysis_plugins = {} self._data_location = None self._event_filter_expression = None self._knowledge_base = None self._processing_configuration = None self._session = None self._status_update_callback = None self._storage_file_path = None if keyboard_interrupt: raise KeyboardInterrupt return self._processing_status
[ "def", "AnalyzeEvents", "(", "self", ",", "session", ",", "knowledge_base_object", ",", "storage_writer", ",", "data_location", ",", "analysis_plugins", ",", "processing_configuration", ",", "event_filter", "=", "None", ",", "event_filter_expression", "=", "None", ","...
https://github.com/log2timeline/plaso/blob/fe2e316b8c76a0141760c0f2f181d84acb83abc2/plaso/multi_process/analysis_engine.py#L531-L699
plotly/plotly.py
cfad7862594b35965c0e000813bd7805e8494a5b
packages/python/plotly/plotly/graph_objs/layout/geo/_center.py
python
Center.lat
(self)
return self["lat"]
Sets the latitude of the map's center. For all projection types, the map's latitude center lies at the middle of the latitude range by default. The 'lat' property is a number and may be specified as: - An int or float Returns ------- int|float
Sets the latitude of the map's center. For all projection types, the map's latitude center lies at the middle of the latitude range by default. The 'lat' property is a number and may be specified as: - An int or float
[ "Sets", "the", "latitude", "of", "the", "map", "s", "center", ".", "For", "all", "projection", "types", "the", "map", "s", "latitude", "center", "lies", "at", "the", "middle", "of", "the", "latitude", "range", "by", "default", ".", "The", "lat", "propert...
def lat(self): """ Sets the latitude of the map's center. For all projection types, the map's latitude center lies at the middle of the latitude range by default. The 'lat' property is a number and may be specified as: - An int or float Returns ------- int|float """ return self["lat"]
[ "def", "lat", "(", "self", ")", ":", "return", "self", "[", "\"lat\"", "]" ]
https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/layout/geo/_center.py#L16-L29
Calysto/calysto_scheme
15bf81987870bcae1264e5a0a06feb9a8ee12b8b
calysto_scheme/src/Scheme.py
python
caaddr
(lyst)
return lyst.cdr.cdr.car.car
[]
def caaddr(lyst): return lyst.cdr.cdr.car.car
[ "def", "caaddr", "(", "lyst", ")", ":", "return", "lyst", ".", "cdr", ".", "cdr", ".", "car", ".", "car" ]
https://github.com/Calysto/calysto_scheme/blob/15bf81987870bcae1264e5a0a06feb9a8ee12b8b/calysto_scheme/src/Scheme.py#L412-L413
Tautulli/Tautulli
2410eb33805aaac4bd1c5dad0f71e4f15afaf742
lib/musicbrainzngs/musicbrainz.py
python
browse_works
(artist=None, includes=[], limit=None, offset=None)
return _browse_impl("work", includes, limit, offset, params)
Get all works linked to an artist *Available includes*: {includes}
Get all works linked to an artist
[ "Get", "all", "works", "linked", "to", "an", "artist" ]
def browse_works(artist=None, includes=[], limit=None, offset=None): """Get all works linked to an artist *Available includes*: {includes}""" params = {"artist": artist} return _browse_impl("work", includes, limit, offset, params)
[ "def", "browse_works", "(", "artist", "=", "None", ",", "includes", "=", "[", "]", ",", "limit", "=", "None", ",", "offset", "=", "None", ")", ":", "params", "=", "{", "\"artist\"", ":", "artist", "}", "return", "_browse_impl", "(", "\"work\"", ",", ...
https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/musicbrainzngs/musicbrainz.py#L1180-L1185
nopernik/mpDNS
b17dc39e7068406df82cb3431b3042e74e520cf9
circuits/core/pollers.py
python
Poll._process
(self, fileno, event)
[]
def _process(self, fileno, event): if fileno not in self._map: return fd = self._map[fileno] if fd == self._ctrl_recv: self._read_ctrl() return if event & self._disconnected_flag and not (event & select.POLLIN): self.fire(_disconnect(fd), self.getTarget(fd)) self._poller.unregister(fileno) super(Poll, self).discard(fd) del self._map[fileno] else: try: if event & select.POLLIN: self.fire(_read(fd), self.getTarget(fd)) if event & select.POLLOUT: self.fire(_write(fd), self.getTarget(fd)) except Exception as e: self.fire(_error(fd, e), self.getTarget(fd)) self.fire(_disconnect(fd), self.getTarget(fd)) self._poller.unregister(fileno) super(Poll, self).discard(fd) del self._map[fileno]
[ "def", "_process", "(", "self", ",", "fileno", ",", "event", ")", ":", "if", "fileno", "not", "in", "self", ".", "_map", ":", "return", "fd", "=", "self", ".", "_map", "[", "fileno", "]", "if", "fd", "==", "self", ".", "_ctrl_recv", ":", "self", ...
https://github.com/nopernik/mpDNS/blob/b17dc39e7068406df82cb3431b3042e74e520cf9/circuits/core/pollers.py#L298-L323
taoyds/spider
7036cf422b1da08a907acbdc062e598bb0761bf7
baselines/seq2seq_attention_copy/seq2seq/data/sequence_example_decoder.py
python
TFSEquenceExampleDecoder.decode
(self, serialized_example, items=None)
return outputs
Decodes the given serialized TF-example. Args: serialized_example: a serialized TF-example tensor. items: the list of items to decode. These must be a subset of the item keys in self._items_to_handlers. If `items` is left as None, then all of the items in self._items_to_handlers are decoded. Returns: the decoded items, a list of tensor.
Decodes the given serialized TF-example. Args: serialized_example: a serialized TF-example tensor. items: the list of items to decode. These must be a subset of the item keys in self._items_to_handlers. If `items` is left as None, then all of the items in self._items_to_handlers are decoded. Returns: the decoded items, a list of tensor.
[ "Decodes", "the", "given", "serialized", "TF", "-", "example", ".", "Args", ":", "serialized_example", ":", "a", "serialized", "TF", "-", "example", "tensor", ".", "items", ":", "the", "list", "of", "items", "to", "decode", ".", "These", "must", "be", "a...
def decode(self, serialized_example, items=None): """Decodes the given serialized TF-example. Args: serialized_example: a serialized TF-example tensor. items: the list of items to decode. These must be a subset of the item keys in self._items_to_handlers. If `items` is left as None, then all of the items in self._items_to_handlers are decoded. Returns: the decoded items, a list of tensor. """ context, sequence = tf.parse_single_sequence_example( serialized_example, self._context_keys_to_features, self._sequence_keys_to_features) # Merge context and sequence features example = {} example.update(context) example.update(sequence) all_features = {} all_features.update(self._context_keys_to_features) all_features.update(self._sequence_keys_to_features) # Reshape non-sparse elements just once: for k, value in all_features.items(): if isinstance(value, tf.FixedLenFeature): example[k] = tf.reshape(example[k], value.shape) if not items: items = self._items_to_handlers.keys() outputs = [] for item in items: handler = self._items_to_handlers[item] keys_to_tensors = {key: example[key] for key in handler.keys} outputs.append(handler.tensors_to_item(keys_to_tensors)) return outputs
[ "def", "decode", "(", "self", ",", "serialized_example", ",", "items", "=", "None", ")", ":", "context", ",", "sequence", "=", "tf", ".", "parse_single_sequence_example", "(", "serialized_example", ",", "self", ".", "_context_keys_to_features", ",", "self", ".",...
https://github.com/taoyds/spider/blob/7036cf422b1da08a907acbdc062e598bb0761bf7/baselines/seq2seq_attention_copy/seq2seq/data/sequence_example_decoder.py#L53-L89
google/ml-fairness-gym
5b1cd336b844059aa4e4426b54d1f0e6b8c4c7e9
agents/recommenders/utils.py
python
accumulate_rewards
(rewards, gamma)
return np.array(acc[::-1])
Computes the discounted reward for the entire episode.
Computes the discounted reward for the entire episode.
[ "Computes", "the", "discounted", "reward", "for", "the", "entire", "episode", "." ]
def accumulate_rewards(rewards, gamma): """Computes the discounted reward for the entire episode.""" reversed_rewards = rewards[::-1] # list reversal acc = list(itertools.accumulate(reversed_rewards, lambda x, y: x*gamma + y)) return np.array(acc[::-1])
[ "def", "accumulate_rewards", "(", "rewards", ",", "gamma", ")", ":", "reversed_rewards", "=", "rewards", "[", ":", ":", "-", "1", "]", "# list reversal", "acc", "=", "list", "(", "itertools", ".", "accumulate", "(", "reversed_rewards", ",", "lambda", "x", ...
https://github.com/google/ml-fairness-gym/blob/5b1cd336b844059aa4e4426b54d1f0e6b8c4c7e9/agents/recommenders/utils.py#L35-L39
adewes/blitzdb
36191579be14fbc2d7a47ede099bcdf31297a9fa
blitzdb/backends/mongo/queryset.py
python
QuerySet.limit
(self, *args, **kwargs)
return self
[]
def limit(self, *args, **kwargs): self._cursor.limit(*args, **kwargs) return self
[ "def", "limit", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_cursor", ".", "limit", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "self" ]
https://github.com/adewes/blitzdb/blob/36191579be14fbc2d7a47ede099bcdf31297a9fa/blitzdb/backends/mongo/queryset.py#L81-L83
log2timeline/plaso
fe2e316b8c76a0141760c0f2f181d84acb83abc2
plaso/parsers/fseventsd.py
python
FseventsdParser._GetParentModificationTime
(self, gzip_file_entry)
return parent_file_entry.modification_time
Retrieves the modification time of the file entry's parent file. Note that this retrieves the time from the file entry of the parent of the gzip file entry's path spec, which is different from trying to retrieve it from the gzip file entry's parent file entry. It would be preferable to retrieve the modification time from the metadata in the gzip file itself, but it appears to not be set when the file is written by fseventsd. Args: gzip_file_entry (dfvfs.FileEntry): file entry of the gzip file containing the fseventsd data. Returns: dfdatetime.DateTimeValues: parent modification time, or None if not available.
Retrieves the modification time of the file entry's parent file.
[ "Retrieves", "the", "modification", "time", "of", "the", "file", "entry", "s", "parent", "file", "." ]
def _GetParentModificationTime(self, gzip_file_entry): """Retrieves the modification time of the file entry's parent file. Note that this retrieves the time from the file entry of the parent of the gzip file entry's path spec, which is different from trying to retrieve it from the gzip file entry's parent file entry. It would be preferable to retrieve the modification time from the metadata in the gzip file itself, but it appears to not be set when the file is written by fseventsd. Args: gzip_file_entry (dfvfs.FileEntry): file entry of the gzip file containing the fseventsd data. Returns: dfdatetime.DateTimeValues: parent modification time, or None if not available. """ parent_file_entry = path_spec_resolver.Resolver.OpenFileEntry( gzip_file_entry.path_spec.parent) if not parent_file_entry: return None return parent_file_entry.modification_time
[ "def", "_GetParentModificationTime", "(", "self", ",", "gzip_file_entry", ")", ":", "parent_file_entry", "=", "path_spec_resolver", ".", "Resolver", ".", "OpenFileEntry", "(", "gzip_file_entry", ".", "path_spec", ".", "parent", ")", "if", "not", "parent_file_entry", ...
https://github.com/log2timeline/plaso/blob/fe2e316b8c76a0141760c0f2f181d84acb83abc2/plaso/parsers/fseventsd.py#L122-L146
kuri65536/python-for-android
26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891
python3-alpha/python-libs/gdata/analytics/data.py
python
AnalyticsLink.parent
(cls)
return '%s#parent' % GA_NS[1:-3]
Parent target_kind
Parent target_kind
[ "Parent", "target_kind" ]
def parent(cls): """Parent target_kind""" return '%s#parent' % GA_NS[1:-3]
[ "def", "parent", "(", "cls", ")", ":", "return", "'%s#parent'", "%", "GA_NS", "[", "1", ":", "-", "3", "]" ]
https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python3-alpha/python-libs/gdata/analytics/data.py#L278-L280
mbusb/multibootusb
fa89b28f27891a9ce8d6e2a5737baa2e6ee83dfd
scripts/imager.py
python
Imager.__init__
(self)
[]
def __init__(self): QtWidgets.QMainWindow.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self)
[ "def", "__init__", "(", "self", ")", ":", "QtWidgets", ".", "QMainWindow", ".", "__init__", "(", "self", ")", "self", ".", "ui", "=", "Ui_MainWindow", "(", ")", "self", ".", "ui", ".", "setupUi", "(", "self", ")" ]
https://github.com/mbusb/multibootusb/blob/fa89b28f27891a9ce8d6e2a5737baa2e6ee83dfd/scripts/imager.py#L90-L93
OpenRCE/paimei
d78f574129f9aade35af03ced08765ea2a15288c
console/modules/_PAIMEIpstalker/PIDAModulesListCtrl.py
python
PIDAModulesListCtrl.on_right_down
(self, event)
Grab the x/y coordinates when the right mouse button is clicked.
Grab the x/y coordinates when the right mouse button is clicked.
[ "Grab", "the", "x", "/", "y", "coordinates", "when", "the", "right", "mouse", "button", "is", "clicked", "." ]
def on_right_down (self, event): ''' Grab the x/y coordinates when the right mouse button is clicked. ''' self.x = event.GetX() self.y = event.GetY() item, flags = self.HitTest((self.x, self.y)) if flags & wx.LIST_HITTEST_ONITEM: self.Select(item) else: self.x = None self.y = None
[ "def", "on_right_down", "(", "self", ",", "event", ")", ":", "self", ".", "x", "=", "event", ".", "GetX", "(", ")", "self", ".", "y", "=", "event", ".", "GetY", "(", ")", "item", ",", "flags", "=", "self", ".", "HitTest", "(", "(", "self", ".",...
https://github.com/OpenRCE/paimei/blob/d78f574129f9aade35af03ced08765ea2a15288c/console/modules/_PAIMEIpstalker/PIDAModulesListCtrl.py#L166-L180
sqlmapproject/sqlmap
3b07b70864624dff4c29dcaa8a61c78e7f9189f7
lib/core/session.py
python
setOs
()
Example of kb.bannerFp dictionary: { 'sp': set(['Service Pack 4']), 'dbmsVersion': '8.00.194', 'dbmsServicePack': '0', 'distrib': set(['2000']), 'dbmsRelease': '2000', 'type': set(['Windows']) }
Example of kb.bannerFp dictionary:
[ "Example", "of", "kb", ".", "bannerFp", "dictionary", ":" ]
def setOs(): """ Example of kb.bannerFp dictionary: { 'sp': set(['Service Pack 4']), 'dbmsVersion': '8.00.194', 'dbmsServicePack': '0', 'distrib': set(['2000']), 'dbmsRelease': '2000', 'type': set(['Windows']) } """ infoMsg = "" if not kb.bannerFp: return if "type" in kb.bannerFp: Backend.setOs(Format.humanize(kb.bannerFp["type"])) infoMsg = "the back-end DBMS operating system is %s" % Backend.getOs() if "distrib" in kb.bannerFp: kb.osVersion = Format.humanize(kb.bannerFp["distrib"]) infoMsg += " %s" % kb.osVersion if "sp" in kb.bannerFp: kb.osSP = int(Format.humanize(kb.bannerFp["sp"]).replace("Service Pack ", "")) elif "sp" not in kb.bannerFp and Backend.isOs(OS.WINDOWS): kb.osSP = 0 if Backend.getOs() and kb.osVersion and kb.osSP: infoMsg += " Service Pack %d" % kb.osSP if infoMsg: logger.info(infoMsg) hashDBWrite(HASHDB_KEYS.OS, Backend.getOs())
[ "def", "setOs", "(", ")", ":", "infoMsg", "=", "\"\"", "if", "not", "kb", ".", "bannerFp", ":", "return", "if", "\"type\"", "in", "kb", ".", "bannerFp", ":", "Backend", ".", "setOs", "(", "Format", ".", "humanize", "(", "kb", ".", "bannerFp", "[", ...
https://github.com/sqlmapproject/sqlmap/blob/3b07b70864624dff4c29dcaa8a61c78e7f9189f7/lib/core/session.py#L40-L79
oracle/graalpython
577e02da9755d916056184ec441c26e00b70145c
graalpython/com.oracle.graal.python.cext/setup.py
python
Bzip2Depedency.build
(self, extracted_dir=None)
return lib_src_folder
[]
def build(self, extracted_dir=None): if not extracted_dir: extracted_dir = self.download() lib_src_folder = os.path.join(extracted_dir, self.package_name + "-" + self.version) logger.info("Building dependency %s in %s using Makefile %s" % (self.package_name, lib_src_folder, self.makefile)) # On Darwin, we need to use -install_name for the native linker if darwin_native: makefile_path = os.path.join(lib_src_folder, self.makefile) with open(makefile_path, "r") as f: content = f.read() content = content.replace("-Wl,-soname -Wl,%s" % self.install_name, "-Wl,-install_name -Wl,@rpath/%s" % self.install_name) with open(makefile_path, "w") as f: f.write(content) parallel_arg = "-j" + str(min(4, os.cpu_count())) if threaded else "" system("make -C '%s' %s -f '%s' CC='%s'" % (lib_src_folder, parallel_arg, self.makefile, get_config_var("CC")), msg="Could not build libbz2") return lib_src_folder
[ "def", "build", "(", "self", ",", "extracted_dir", "=", "None", ")", ":", "if", "not", "extracted_dir", ":", "extracted_dir", "=", "self", ".", "download", "(", ")", "lib_src_folder", "=", "os", ".", "path", ".", "join", "(", "extracted_dir", ",", "self"...
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/com.oracle.graal.python.cext/setup.py#L258-L275
tflearn/tflearn
db5176773299b67a2a75c5889fb2aba7fd0fea8a
tflearn/initializations.py
python
truncated_normal
(shape=None, mean=0.0, stddev=0.02, dtype=tf.float32, seed=None)
Truncated Normal. Initialization with random values from a normal truncated distribution. The generated values follow a normal distribution with specified mean and standard deviation, except that values whose magnitude is more than 2 standard deviations from the mean are dropped and re-picked. Arguments: shape: List of `int`. A shape to initialize a Tensor (optional). mean: Same as `dtype`. The mean of the truncated normal distribution. stddev: Same as `dtype`. The standard deviation of the truncated normal distribution. dtype: The tensor data type. seed: `int`. Used to create a random seed for the distribution. Returns: The Initializer, or an initialized `Tensor` if shape is specified.
Truncated Normal.
[ "Truncated", "Normal", "." ]
def truncated_normal(shape=None, mean=0.0, stddev=0.02, dtype=tf.float32, seed=None): """ Truncated Normal. Initialization with random values from a normal truncated distribution. The generated values follow a normal distribution with specified mean and standard deviation, except that values whose magnitude is more than 2 standard deviations from the mean are dropped and re-picked. Arguments: shape: List of `int`. A shape to initialize a Tensor (optional). mean: Same as `dtype`. The mean of the truncated normal distribution. stddev: Same as `dtype`. The standard deviation of the truncated normal distribution. dtype: The tensor data type. seed: `int`. Used to create a random seed for the distribution. Returns: The Initializer, or an initialized `Tensor` if shape is specified. """ if shape: return tf.truncated_normal(shape=shape, mean=mean, stddev=stddev, seed=seed, dtype=dtype) else: return tf.truncated_normal_initializer(mean=mean, stddev=stddev, seed=seed, dtype=dtype)
[ "def", "truncated_normal", "(", "shape", "=", "None", ",", "mean", "=", "0.0", ",", "stddev", "=", "0.02", ",", "dtype", "=", "tf", ".", "float32", ",", "seed", "=", "None", ")", ":", "if", "shape", ":", "return", "tf", ".", "truncated_normal", "(", ...
https://github.com/tflearn/tflearn/blob/db5176773299b67a2a75c5889fb2aba7fd0fea8a/tflearn/initializations.py#L138-L165
AstroPrint/AstroBox
e7e3b8a7d33ea85fcb6b2696869c0d719ceb8b75
src/ext/makerbot_driver/FileReader/FileReader.py
python
FileReader.GetNextCommand
(self)
return cmd
Assuming the file pointer is at a command, gets the next command number If ReadBytes raises an InsufficientDataError (indicating no more information if available in the file), we throw an EndOfFileError @return int The command number
Assuming the file pointer is at a command, gets the next command number If ReadBytes raises an InsufficientDataError (indicating no more information if available in the file), we throw an EndOfFileError
[ "Assuming", "the", "file", "pointer", "is", "at", "a", "command", "gets", "the", "next", "command", "number", "If", "ReadBytes", "raises", "an", "InsufficientDataError", "(", "indicating", "no", "more", "information", "if", "available", "in", "the", "file", ")...
def GetNextCommand(self): """Assuming the file pointer is at a command, gets the next command number If ReadBytes raises an InsufficientDataError (indicating no more information if available in the file), we throw an EndOfFileError @return int The command number """ try: cmd = ord(self.ReadBytes(1)) except makerbot_driver.FileReader.InsufficientDataError: raise makerbot_driver.FileReader.EndOfFileError # TODO: Break the tool action commands out of here if (not cmd in makerbot_driver.slave_action_command_dict.values()) and \ (not cmd in makerbot_driver.host_action_command_dict.values()): self._log.debug('{"event":"bad_read_command", "command":%s}', cmd) raise makerbot_driver.FileReader.BadCommandError(cmd) return cmd
[ "def", "GetNextCommand", "(", "self", ")", ":", "try", ":", "cmd", "=", "ord", "(", "self", ".", "ReadBytes", "(", "1", ")", ")", "except", "makerbot_driver", ".", "FileReader", ".", "InsufficientDataError", ":", "raise", "makerbot_driver", ".", "FileReader"...
https://github.com/AstroPrint/AstroBox/blob/e7e3b8a7d33ea85fcb6b2696869c0d719ceb8b75/src/ext/makerbot_driver/FileReader/FileReader.py#L55-L73
ninja-ide/ninja-ide
87d91131bd19fdc3dcfd91eb97ad1e41c49c60c0
ninja_ide/dependencies/notimportchecker.py
python
Checker.get_not_imports_on_file
(self, stmt, path=None)
Get imports that dont exist on the file Parameters ---------- stmt: dict -> dict of not imports in the file {'sys':{'lineno': 1, 'mod_name': 'sys'}} if stmt == -1 (see parse_file) return None path: string -> default None. path is the basename of the file.
Get imports that dont exist on the file
[ "Get", "imports", "that", "dont", "exist", "on", "the", "file" ]
def get_not_imports_on_file(self, stmt, path=None): """Get imports that dont exist on the file Parameters ---------- stmt: dict -> dict of not imports in the file {'sys':{'lineno': 1, 'mod_name': 'sys'}} if stmt == -1 (see parse_file) return None path: string -> default None. path is the basename of the file. """ if (stmt == -1): self._import_error_list = {} return None if path is None: path = self._path workspace = os.getcwd() dn = os.path.dirname(path) if dn == '': # if path file is in the current folder os.chdir(workspace) else: os.chdir(dn) # if path is complete for key, value in stmt.items(): for mod_name in value['mod_name']: try: if key == mod_name: exec('import {}'.format(key)) else: exec('from {} import {}'.format(key, mod_name)) except RuntimeError as e: pass except ImportError as e: self._import_error_list.setdefault(key, {'mod_name': mod_name, 'lineno': value['lineno']}) os.chdir(workspace) if len(self._import_error_list) == 0: return None else: return self._import_error_list
[ "def", "get_not_imports_on_file", "(", "self", ",", "stmt", ",", "path", "=", "None", ")", ":", "if", "(", "stmt", "==", "-", "1", ")", ":", "self", ".", "_import_error_list", "=", "{", "}", "return", "None", "if", "path", "is", "None", ":", "path", ...
https://github.com/ninja-ide/ninja-ide/blob/87d91131bd19fdc3dcfd91eb97ad1e41c49c60c0/ninja_ide/dependencies/notimportchecker.py#L130-L173
wakatime/komodo-wakatime
8923c04ded9fa64d7374fadd8cde3a6fadfe053d
components/wakatime/packages/urllib3/packages/ordered_dict.py
python
OrderedDict.update
(*args, **kwds)
od.update(E, **F) -> None. Update od from dict/iterable E and F. If E is a dict instance, does: for k in E: od[k] = E[k] If E has a .keys() method, does: for k in E.keys(): od[k] = E[k] Or if E is an iterable of items, does: for k, v in E: od[k] = v In either case, this is followed by: for k, v in F.items(): od[k] = v
od.update(E, **F) -> None. Update od from dict/iterable E and F.
[ "od", ".", "update", "(", "E", "**", "F", ")", "-", ">", "None", ".", "Update", "od", "from", "dict", "/", "iterable", "E", "and", "F", "." ]
def update(*args, **kwds): '''od.update(E, **F) -> None. Update od from dict/iterable E and F. If E is a dict instance, does: for k in E: od[k] = E[k] If E has a .keys() method, does: for k in E.keys(): od[k] = E[k] Or if E is an iterable of items, does: for k, v in E: od[k] = v In either case, this is followed by: for k, v in F.items(): od[k] = v ''' if len(args) > 2: raise TypeError('update() takes at most 2 positional ' 'arguments (%d given)' % (len(args),)) elif not args: raise TypeError('update() takes at least 1 argument (0 given)') self = args[0] # Make progressively weaker assumptions about "other" other = () if len(args) == 2: other = args[1] if isinstance(other, dict): for key in other: self[key] = other[key] elif hasattr(other, 'keys'): for key in other.keys(): self[key] = other[key] else: for key, value in other: self[key] = value for key, value in kwds.items(): self[key] = value
[ "def", "update", "(", "*", "args", ",", "*", "*", "kwds", ")", ":", "if", "len", "(", "args", ")", ">", "2", ":", "raise", "TypeError", "(", "'update() takes at most 2 positional '", "'arguments (%d given)'", "%", "(", "len", "(", "args", ")", ",", ")", ...
https://github.com/wakatime/komodo-wakatime/blob/8923c04ded9fa64d7374fadd8cde3a6fadfe053d/components/wakatime/packages/urllib3/packages/ordered_dict.py#L142-L171
VirtueSecurity/aws-extender
d123b7e1a845847709ba3a481f11996bddc68a1c
BappModules/docutils/parsers/rst/states.py
python
Body.directive
(self, match, **option_presets)
Returns a 2-tuple: list of nodes, and a "blank finish" boolean.
Returns a 2-tuple: list of nodes, and a "blank finish" boolean.
[ "Returns", "a", "2", "-", "tuple", ":", "list", "of", "nodes", "and", "a", "blank", "finish", "boolean", "." ]
def directive(self, match, **option_presets): """Returns a 2-tuple: list of nodes, and a "blank finish" boolean.""" type_name = match.group(1) directive_class, messages = directives.directive( type_name, self.memo.language, self.document) self.parent += messages if directive_class: return self.run_directive( directive_class, match, type_name, option_presets) else: return self.unknown_directive(type_name)
[ "def", "directive", "(", "self", ",", "match", ",", "*", "*", "option_presets", ")", ":", "type_name", "=", "match", ".", "group", "(", "1", ")", "directive_class", ",", "messages", "=", "directives", ".", "directive", "(", "type_name", ",", "self", ".",...
https://github.com/VirtueSecurity/aws-extender/blob/d123b7e1a845847709ba3a481f11996bddc68a1c/BappModules/docutils/parsers/rst/states.py#L2073-L2083
Dvlv/Tkinter-By-Example
30721f15f7bea41489a7c46819beb5282781e563
Code/Chapter6-1.py
python
Editor.destroy_autocomplete_menu
(self, event=None)
[]
def destroy_autocomplete_menu(self, event=None): try: self.complete_menu.destroy() self.main_text.unbind("<Down>") self.main_text.focus_force() except AttributeError: pass
[ "def", "destroy_autocomplete_menu", "(", "self", ",", "event", "=", "None", ")", ":", "try", ":", "self", ".", "complete_menu", ".", "destroy", "(", ")", "self", ".", "main_text", ".", "unbind", "(", "\"<Down>\"", ")", "self", ".", "main_text", ".", "foc...
https://github.com/Dvlv/Tkinter-By-Example/blob/30721f15f7bea41489a7c46819beb5282781e563/Code/Chapter6-1.py#L117-L123
gramps-project/gramps
04d4651a43eb210192f40a9f8c2bad8ee8fa3753
gramps/gen/proxy/proxybase.py
python
ProxyDbBase.get_note_from_handle
(self, handle)
return self.gfilter(self.include_note, self.db.get_note_from_handle(handle))
Finds a Note in the database from the passed gramps handle. If no such Note exists, None is returned.
Finds a Note in the database from the passed gramps handle. If no such Note exists, None is returned.
[ "Finds", "a", "Note", "in", "the", "database", "from", "the", "passed", "gramps", "handle", ".", "If", "no", "such", "Note", "exists", "None", "is", "returned", "." ]
def get_note_from_handle(self, handle): """ Finds a Note in the database from the passed gramps handle. If no such Note exists, None is returned. """ return self.gfilter(self.include_note, self.db.get_note_from_handle(handle))
[ "def", "get_note_from_handle", "(", "self", ",", "handle", ")", ":", "return", "self", ".", "gfilter", "(", "self", ".", "include_note", ",", "self", ".", "db", ".", "get_note_from_handle", "(", "handle", ")", ")" ]
https://github.com/gramps-project/gramps/blob/04d4651a43eb210192f40a9f8c2bad8ee8fa3753/gramps/gen/proxy/proxybase.py#L562-L568
ThaWeatherman/scrapers
d82e2b707bbb2b450176dbf85842aeccb6e812f9
craigslist/free_stuff_requests.py
python
get_args
()
return parser.parse_args()
[]
def get_args(): parser = argparse.ArgumentParser() parser.add_argument('-w', type=str, default='http://baltimore.craigslist.org', help='your local craigslist website, including HTTP schema') return parser.parse_args()
[ "def", "get_args", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "'-w'", ",", "type", "=", "str", ",", "default", "=", "'http://baltimore.craigslist.org'", ",", "help", "=", "'your local craigsli...
https://github.com/ThaWeatherman/scrapers/blob/d82e2b707bbb2b450176dbf85842aeccb6e812f9/craigslist/free_stuff_requests.py#L15-L18
GoogleChrome/chromium-dashboard
7ef9184080fc4cdf11efbe29dba27f95f07a20d9
internals/search.py
python
_get_referenced_features
(approvals, reverse=False)
return features
Retrieve the features being approved, withuot duplicates.
Retrieve the features being approved, withuot duplicates.
[ "Retrieve", "the", "features", "being", "approved", "withuot", "duplicates", "." ]
def _get_referenced_features(approvals, reverse=False): """Retrieve the features being approved, withuot duplicates.""" logging.info('approvals is %r', [(a.feature_id, a.state) for a in approvals]) feature_ids = [] seen = set() for appr in approvals: if appr.feature_id not in seen: seen.add(appr.feature_id) feature_ids.append(appr.feature_id) features = models.Feature.get_by_ids(feature_ids) return features
[ "def", "_get_referenced_features", "(", "approvals", ",", "reverse", "=", "False", ")", ":", "logging", ".", "info", "(", "'approvals is %r'", ",", "[", "(", "a", ".", "feature_id", ",", "a", ".", "state", ")", "for", "a", "in", "approvals", "]", ")", ...
https://github.com/GoogleChrome/chromium-dashboard/blob/7ef9184080fc4cdf11efbe29dba27f95f07a20d9/internals/search.py#L31-L42
polakowo/vectorbt
6638735c131655760474d72b9f045d1dbdbd8fe9
vectorbt/generic/nb.py
python
pct_change_nb
(a: tp.Array2d, n: int = 1)
return out
2-dim version of `pct_change_1d_nb`.
2-dim version of `pct_change_1d_nb`.
[ "2", "-", "dim", "version", "of", "pct_change_1d_nb", "." ]
def pct_change_nb(a: tp.Array2d, n: int = 1) -> tp.Array2d: """2-dim version of `pct_change_1d_nb`.""" out = np.empty_like(a, dtype=np.float_) for col in range(a.shape[1]): out[:, col] = pct_change_1d_nb(a[:, col], n=n) return out
[ "def", "pct_change_nb", "(", "a", ":", "tp", ".", "Array2d", ",", "n", ":", "int", "=", "1", ")", "->", "tp", ".", "Array2d", ":", "out", "=", "np", ".", "empty_like", "(", "a", ",", "dtype", "=", "np", ".", "float_", ")", "for", "col", "in", ...
https://github.com/polakowo/vectorbt/blob/6638735c131655760474d72b9f045d1dbdbd8fe9/vectorbt/generic/nb.py#L319-L324
titu1994/keras-non-local-nets
334b0331d230383bf36328a1cd8cd409246bcafd
non_local.py
python
non_local_block
(ip, intermediate_dim=None, compression=2, mode='embedded', add_residual=True)
return y
Adds a Non-Local block for self attention to the input tensor. Input tensor can be or rank 3 (temporal), 4 (spatial) or 5 (spatio-temporal). Arguments: ip: input tensor intermediate_dim: The dimension of the intermediate representation. Can be `None` or a positive integer greater than 0. If `None`, computes the intermediate dimension as half of the input channel dimension. compression: None or positive integer. Compresses the intermediate representation during the dot products to reduce memory consumption. Default is set to 2, which states halve the time/space/spatio-time dimension for the intermediate step. Set to 1 to prevent computation compression. None or 1 causes no reduction. mode: Mode of operation. Can be one of `embedded`, `gaussian`, `dot` or `concatenate`. add_residual: Boolean value to decide if the residual connection should be added or not. Default is True for ResNets, and False for Self Attention. Returns: a tensor of same shape as input
Adds a Non-Local block for self attention to the input tensor. Input tensor can be or rank 3 (temporal), 4 (spatial) or 5 (spatio-temporal).
[ "Adds", "a", "Non", "-", "Local", "block", "for", "self", "attention", "to", "the", "input", "tensor", ".", "Input", "tensor", "can", "be", "or", "rank", "3", "(", "temporal", ")", "4", "(", "spatial", ")", "or", "5", "(", "spatio", "-", "temporal", ...
def non_local_block(ip, intermediate_dim=None, compression=2, mode='embedded', add_residual=True): """ Adds a Non-Local block for self attention to the input tensor. Input tensor can be or rank 3 (temporal), 4 (spatial) or 5 (spatio-temporal). Arguments: ip: input tensor intermediate_dim: The dimension of the intermediate representation. Can be `None` or a positive integer greater than 0. If `None`, computes the intermediate dimension as half of the input channel dimension. compression: None or positive integer. Compresses the intermediate representation during the dot products to reduce memory consumption. Default is set to 2, which states halve the time/space/spatio-time dimension for the intermediate step. Set to 1 to prevent computation compression. None or 1 causes no reduction. mode: Mode of operation. Can be one of `embedded`, `gaussian`, `dot` or `concatenate`. add_residual: Boolean value to decide if the residual connection should be added or not. Default is True for ResNets, and False for Self Attention. Returns: a tensor of same shape as input """ channel_dim = 1 if K.image_data_format() == 'channels_first' else -1 ip_shape = K.int_shape(ip) if mode not in ['gaussian', 'embedded', 'dot', 'concatenate']: raise ValueError('`mode` must be one of `gaussian`, `embedded`, `dot` or `concatenate`') if compression is None: compression = 1 dim1, dim2, dim3 = None, None, None # check rank and calculate the input shape if len(ip_shape) == 3: # temporal / time series data rank = 3 batchsize, dim1, channels = ip_shape elif len(ip_shape) == 4: # spatial / image data rank = 4 if channel_dim == 1: batchsize, channels, dim1, dim2 = ip_shape else: batchsize, dim1, dim2, channels = ip_shape elif len(ip_shape) == 5: # spatio-temporal / Video or Voxel data rank = 5 if channel_dim == 1: batchsize, channels, dim1, dim2, dim3 = ip_shape else: batchsize, dim1, dim2, dim3, channels = ip_shape else: raise ValueError('Input dimension has to be either 3 (temporal), 4 (spatial) or 5 (spatio-temporal)') # verify correct intermediate dimension specified if intermediate_dim is None: intermediate_dim = channels // 2 if intermediate_dim < 1: intermediate_dim = 1 else: intermediate_dim = int(intermediate_dim) if intermediate_dim < 1: raise ValueError('`intermediate_dim` must be either `None` or positive integer greater than 1.') if mode == 'gaussian': # Gaussian instantiation x1 = Reshape((-1, channels))(ip) # xi x2 = Reshape((-1, channels))(ip) # xj f = dot([x1, x2], axes=2) f = Activation('softmax')(f) elif mode == 'dot': # Dot instantiation # theta path theta = _convND(ip, rank, intermediate_dim) theta = Reshape((-1, intermediate_dim))(theta) # phi path phi = _convND(ip, rank, intermediate_dim) phi = Reshape((-1, intermediate_dim))(phi) f = dot([theta, phi], axes=2) size = K.int_shape(f) # scale the values to make it size invariant f = Lambda(lambda z: (1. / float(size[-1])) * z)(f) elif mode == 'concatenate': # Concatenation instantiation raise NotImplementedError('Concatenate model has not been implemented yet') else: # Embedded Gaussian instantiation # theta path theta = _convND(ip, rank, intermediate_dim) theta = Reshape((-1, intermediate_dim))(theta) # phi path phi = _convND(ip, rank, intermediate_dim) phi = Reshape((-1, intermediate_dim))(phi) if compression > 1: # shielded computation phi = MaxPool1D(compression)(phi) f = dot([theta, phi], axes=2) f = Activation('softmax')(f) # g path g = _convND(ip, rank, intermediate_dim) g = Reshape((-1, intermediate_dim))(g) if compression > 1 and mode == 'embedded': # shielded computation g = MaxPool1D(compression)(g) # compute output path y = dot([f, g], axes=[2, 1]) # reshape to input tensor format if rank == 3: y = Reshape((dim1, intermediate_dim))(y) elif rank == 4: if channel_dim == -1: y = Reshape((dim1, dim2, intermediate_dim))(y) else: y = Reshape((intermediate_dim, dim1, dim2))(y) else: if channel_dim == -1: y = Reshape((dim1, dim2, dim3, intermediate_dim))(y) else: y = Reshape((intermediate_dim, dim1, dim2, dim3))(y) # project filters y = _convND(y, rank, channels) # residual connection if add_residual: y = add([ip, y]) return y
[ "def", "non_local_block", "(", "ip", ",", "intermediate_dim", "=", "None", ",", "compression", "=", "2", ",", "mode", "=", "'embedded'", ",", "add_residual", "=", "True", ")", ":", "channel_dim", "=", "1", "if", "K", ".", "image_data_format", "(", ")", "...
https://github.com/titu1994/keras-non-local-nets/blob/334b0331d230383bf36328a1cd8cd409246bcafd/non_local.py#L7-L152
Scalsol/mega.pytorch
a6aa6e0537b82d70da94228100a51e6a53d98f82
mega_core/modeling/roi_heads/mask_head/inference.py
python
expand_boxes
(boxes, scale)
return boxes_exp
[]
def expand_boxes(boxes, scale): w_half = (boxes[:, 2] - boxes[:, 0]) * .5 h_half = (boxes[:, 3] - boxes[:, 1]) * .5 x_c = (boxes[:, 2] + boxes[:, 0]) * .5 y_c = (boxes[:, 3] + boxes[:, 1]) * .5 w_half *= scale h_half *= scale boxes_exp = torch.zeros_like(boxes) boxes_exp[:, 0] = x_c - w_half boxes_exp[:, 2] = x_c + w_half boxes_exp[:, 1] = y_c - h_half boxes_exp[:, 3] = y_c + h_half return boxes_exp
[ "def", "expand_boxes", "(", "boxes", ",", "scale", ")", ":", "w_half", "=", "(", "boxes", "[", ":", ",", "2", "]", "-", "boxes", "[", ":", ",", "0", "]", ")", "*", ".5", "h_half", "=", "(", "boxes", "[", ":", ",", "3", "]", "-", "boxes", "[...
https://github.com/Scalsol/mega.pytorch/blob/a6aa6e0537b82d70da94228100a51e6a53d98f82/mega_core/modeling/roi_heads/mask_head/inference.py#L91-L105
jython/jython3
def4f8ec47cb7a9c799ea4c745f12badf92c5769
lib-python/3.5.1/imp.py
python
get_magic
()
return util.MAGIC_NUMBER
**DEPRECATED** Return the magic number for .pyc files.
**DEPRECATED**
[ "**", "DEPRECATED", "**" ]
def get_magic(): """**DEPRECATED** Return the magic number for .pyc files. """ return util.MAGIC_NUMBER
[ "def", "get_magic", "(", ")", ":", "return", "util", ".", "MAGIC_NUMBER" ]
https://github.com/jython/jython3/blob/def4f8ec47cb7a9c799ea4c745f12badf92c5769/lib-python/3.5.1/imp.py#L59-L64
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/requests/cookies.py
python
MockRequest.get_new_headers
(self)
return self._new_headers
[]
def get_new_headers(self): return self._new_headers
[ "def", "get_new_headers", "(", "self", ")", ":", "return", "self", ".", "_new_headers" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/requests/cookies.py#L82-L83
Yubico/yubikey-manager
32914673d1d0004aba820e614ac9a9a640b4d196
ykman/pcsc/__init__.py
python
ScardYubiKeyDevice.__init__
(self, reader)
[]
def __init__(self, reader): # Base transport on reader name: NFC readers will have a different name if YK_READER_NAME in reader.name.lower(): transport = TRANSPORT.USB else: transport = TRANSPORT.NFC super(ScardYubiKeyDevice, self).__init__( transport, reader.name, _pid_from_name(reader.name) ) self.reader = reader
[ "def", "__init__", "(", "self", ",", "reader", ")", ":", "# Base transport on reader name: NFC readers will have a different name", "if", "YK_READER_NAME", "in", "reader", ".", "name", ".", "lower", "(", ")", ":", "transport", "=", "TRANSPORT", ".", "USB", "else", ...
https://github.com/Yubico/yubikey-manager/blob/32914673d1d0004aba820e614ac9a9a640b4d196/ykman/pcsc/__init__.py#L69-L78
tuckerbalch/QSTK
4981506c37227a72404229d5e1e0887f797a5d57
epydoc-3.0.1/epydoc/docwriter/dotgraph.py
python
DotGraphEdge.to_dotfile
(self)
return 'node%d -> node%d%s' % (self.start.id, self.end.id, attribs)
Return the dot commands that should be used to render this edge.
Return the dot commands that should be used to render this edge.
[ "Return", "the", "dot", "commands", "that", "should", "be", "used", "to", "render", "this", "edge", "." ]
def to_dotfile(self): """ Return the dot commands that should be used to render this edge. """ # Set head & tail ports, if the nodes have preferred ports. attribs = self._attribs.copy() if (self.start.port is not None and 'headport' not in attribs): attribs['headport'] = self.start.port if (self.end.port is not None and 'tailport' not in attribs): attribs['tailport'] = self.end.port # Convert attribs to a string attribs = ','.join(['%s="%s"' % (k,v) for (k,v) in attribs.items() if v is not None]) if attribs: attribs = ' [%s]' % attribs # Return the dotfile edge. return 'node%d -> node%d%s' % (self.start.id, self.end.id, attribs)
[ "def", "to_dotfile", "(", "self", ")", ":", "# Set head & tail ports, if the nodes have preferred ports.", "attribs", "=", "self", ".", "_attribs", ".", "copy", "(", ")", "if", "(", "self", ".", "start", ".", "port", "is", "not", "None", "and", "'headport'", "...
https://github.com/tuckerbalch/QSTK/blob/4981506c37227a72404229d5e1e0887f797a5d57/epydoc-3.0.1/epydoc/docwriter/dotgraph.py#L333-L348
conda/conda-build
2a19925f2b2ca188f80ffa625cd783e7d403793f
conda_build/environ.py
python
Environment.package_specs
(self)
return specs
List all package specs in the environment.
List all package specs in the environment.
[ "List", "all", "package", "specs", "in", "the", "environment", "." ]
def package_specs(self): """ List all package specs in the environment. """ self._read_package_json() json_objs = self._packages.values() specs = [] for i in json_objs: p, v, b = i['name'], i['version'], i['build'] specs.append(f'{p} {v} {b}') return specs
[ "def", "package_specs", "(", "self", ")", ":", "self", ".", "_read_package_json", "(", ")", "json_objs", "=", "self", ".", "_packages", ".", "values", "(", ")", "specs", "=", "[", "]", "for", "i", "in", "json_objs", ":", "p", ",", "v", ",", "b", "=...
https://github.com/conda/conda-build/blob/2a19925f2b2ca188f80ffa625cd783e7d403793f/conda_build/environ.py#L741-L751
JetBrains/python-skeletons
95ad24b666e475998e5d1cc02ed53a2188036167
os/path.py
python
expanduser
(path)
return path
On Unix and Windows, return the argument with an initial component of ~ or ~user replaced by that user's home directory. :type path: bytes | unicode | os.PathLike :rtype: bytes | unicode
On Unix and Windows, return the argument with an initial component of ~ or ~user replaced by that user's home directory.
[ "On", "Unix", "and", "Windows", "return", "the", "argument", "with", "an", "initial", "component", "of", "~", "or", "~user", "replaced", "by", "that", "user", "s", "home", "directory", "." ]
def expanduser(path): """On Unix and Windows, return the argument with an initial component of ~ or ~user replaced by that user's home directory. :type path: bytes | unicode | os.PathLike :rtype: bytes | unicode """ return path
[ "def", "expanduser", "(", "path", ")", ":", "return", "path" ]
https://github.com/JetBrains/python-skeletons/blob/95ad24b666e475998e5d1cc02ed53a2188036167/os/path.py#L65-L72
mnot/thor
8a6f14e15bd4e59e2348e6308e935a401e39d4a6
thor/http/common.py
python
header_dict
( hdr_tuples: RawHeaderListType, omit: List[bytes] = None )
return out
Given a list of header tuples, return a dictionary keyed upon the lower-cased header names. If omit is defined, each header listed (by lower-cased name) will not be returned in the dictionary.
Given a list of header tuples, return a dictionary keyed upon the lower-cased header names.
[ "Given", "a", "list", "of", "header", "tuples", "return", "a", "dictionary", "keyed", "upon", "the", "lower", "-", "cased", "header", "names", "." ]
def header_dict( hdr_tuples: RawHeaderListType, omit: List[bytes] = None ) -> Dict[bytes, List[bytes]]: """ Given a list of header tuples, return a dictionary keyed upon the lower-cased header names. If omit is defined, each header listed (by lower-cased name) will not be returned in the dictionary. """ out = defaultdict(list) # type: Dict[bytes, List[bytes]] for (n, v) in hdr_tuples: n = n.lower() if n in (omit or []): continue out[n].extend([i.strip() for i in v.split(b",")]) return out
[ "def", "header_dict", "(", "hdr_tuples", ":", "RawHeaderListType", ",", "omit", ":", "List", "[", "bytes", "]", "=", "None", ")", "->", "Dict", "[", "bytes", ",", "List", "[", "bytes", "]", "]", ":", "out", "=", "defaultdict", "(", "list", ")", "# ty...
https://github.com/mnot/thor/blob/8a6f14e15bd4e59e2348e6308e935a401e39d4a6/thor/http/common.py#L68-L84
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/modules/pkg_resource.py
python
pack_sources
(sources, normalize=True)
return ret
Accepts list of dicts (or a string representing a list of dicts) and packs the key/value pairs into a single dict. ``'[{"foo": "salt://foo.rpm"}, {"bar": "salt://bar.rpm"}]'`` would become ``{"foo": "salt://foo.rpm", "bar": "salt://bar.rpm"}`` normalize : True Normalize the package name by removing the architecture, if the architecture of the package is different from the architecture of the operating system. The ability to disable this behavior is useful for poorly-created packages which include the architecture as an actual part of the name, such as kernel modules which match a specific kernel version. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' pkg_resource.pack_sources '[{"foo": "salt://foo.rpm"}, {"bar": "salt://bar.rpm"}]'
Accepts list of dicts (or a string representing a list of dicts) and packs the key/value pairs into a single dict.
[ "Accepts", "list", "of", "dicts", "(", "or", "a", "string", "representing", "a", "list", "of", "dicts", ")", "and", "packs", "the", "key", "/", "value", "pairs", "into", "a", "single", "dict", "." ]
def pack_sources(sources, normalize=True): """ Accepts list of dicts (or a string representing a list of dicts) and packs the key/value pairs into a single dict. ``'[{"foo": "salt://foo.rpm"}, {"bar": "salt://bar.rpm"}]'`` would become ``{"foo": "salt://foo.rpm", "bar": "salt://bar.rpm"}`` normalize : True Normalize the package name by removing the architecture, if the architecture of the package is different from the architecture of the operating system. The ability to disable this behavior is useful for poorly-created packages which include the architecture as an actual part of the name, such as kernel modules which match a specific kernel version. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' pkg_resource.pack_sources '[{"foo": "salt://foo.rpm"}, {"bar": "salt://bar.rpm"}]' """ if normalize and "pkg.normalize_name" in __salt__: _normalize_name = __salt__["pkg.normalize_name"] else: _normalize_name = lambda pkgname: pkgname if isinstance(sources, str): try: sources = salt.utils.yaml.safe_load(sources) except salt.utils.yaml.parser.ParserError as err: log.error(err) return {} ret = {} for source in sources: if (not isinstance(source, dict)) or len(source) != 1: log.error("Invalid input: %s", pprint.pformat(sources)) log.error("Input must be a list of 1-element dicts") return {} else: key = next(iter(source)) ret[_normalize_name(key)] = source[key] return ret
[ "def", "pack_sources", "(", "sources", ",", "normalize", "=", "True", ")", ":", "if", "normalize", "and", "\"pkg.normalize_name\"", "in", "__salt__", ":", "_normalize_name", "=", "__salt__", "[", "\"pkg.normalize_name\"", "]", "else", ":", "_normalize_name", "=", ...
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/modules/pkg_resource.py#L36-L80
TengXiaoDai/DistributedCrawling
f5c2439e6ce68dd9b49bde084d76473ff9ed4963
Lib/site-packages/pip/wheel.py
python
check_compatibility
(version, name)
Raises errors or warns if called with an incompatible Wheel-Version. Pip should refuse to install a Wheel-Version that's a major series ahead of what it's compatible with (e.g 2.0 > 1.1); and warn when installing a version only minor version ahead (e.g 1.2 > 1.1). version: a 2-tuple representing a Wheel-Version (Major, Minor) name: name of wheel or package to raise exception about :raises UnsupportedWheel: when an incompatible Wheel-Version is given
Raises errors or warns if called with an incompatible Wheel-Version.
[ "Raises", "errors", "or", "warns", "if", "called", "with", "an", "incompatible", "Wheel", "-", "Version", "." ]
def check_compatibility(version, name): """ Raises errors or warns if called with an incompatible Wheel-Version. Pip should refuse to install a Wheel-Version that's a major series ahead of what it's compatible with (e.g 2.0 > 1.1); and warn when installing a version only minor version ahead (e.g 1.2 > 1.1). version: a 2-tuple representing a Wheel-Version (Major, Minor) name: name of wheel or package to raise exception about :raises UnsupportedWheel: when an incompatible Wheel-Version is given """ if not version: raise UnsupportedWheel( "%s is in an unsupported or invalid wheel" % name ) if version[0] > VERSION_COMPATIBLE[0]: raise UnsupportedWheel( "%s's Wheel-Version (%s) is not compatible with this version " "of pip" % (name, '.'.join(map(str, version))) ) elif version > VERSION_COMPATIBLE: logger.warning( 'Installing from a newer Wheel-Version (%s)', '.'.join(map(str, version)), )
[ "def", "check_compatibility", "(", "version", ",", "name", ")", ":", "if", "not", "version", ":", "raise", "UnsupportedWheel", "(", "\"%s is in an unsupported or invalid wheel\"", "%", "name", ")", "if", "version", "[", "0", "]", ">", "VERSION_COMPATIBLE", "[", ...
https://github.com/TengXiaoDai/DistributedCrawling/blob/f5c2439e6ce68dd9b49bde084d76473ff9ed4963/Lib/site-packages/pip/wheel.py#L583-L609
pdfminer/pdfminer.six
10f6fb40c258c86fd04d86bade20f69fb07faabd
pdfminer/_saslprep.py
python
saslprep
(data: str, prohibit_unassigned_code_points: bool = True)
return data
An implementation of RFC4013 SASLprep. :param data: The string to SASLprep. :param prohibit_unassigned_code_points: RFC 3454 and RFCs for various SASL mechanisms distinguish between `queries` (unassigned code points allowed) and `stored strings` (unassigned code points prohibited). Defaults to ``True`` (unassigned code points are prohibited). :return: The SASLprep'ed version of `data`.
An implementation of RFC4013 SASLprep. :param data: The string to SASLprep. :param prohibit_unassigned_code_points: RFC 3454 and RFCs for various SASL mechanisms distinguish between `queries` (unassigned code points allowed) and `stored strings` (unassigned code points prohibited). Defaults to ``True`` (unassigned code points are prohibited). :return: The SASLprep'ed version of `data`.
[ "An", "implementation", "of", "RFC4013", "SASLprep", ".", ":", "param", "data", ":", "The", "string", "to", "SASLprep", ".", ":", "param", "prohibit_unassigned_code_points", ":", "RFC", "3454", "and", "RFCs", "for", "various", "SASL", "mechanisms", "distinguish"...
def saslprep(data: str, prohibit_unassigned_code_points: bool = True) -> str: """An implementation of RFC4013 SASLprep. :param data: The string to SASLprep. :param prohibit_unassigned_code_points: RFC 3454 and RFCs for various SASL mechanisms distinguish between `queries` (unassigned code points allowed) and `stored strings` (unassigned code points prohibited). Defaults to ``True`` (unassigned code points are prohibited). :return: The SASLprep'ed version of `data`. """ if prohibit_unassigned_code_points: prohibited = _PROHIBITED + (stringprep.in_table_a1,) else: prohibited = _PROHIBITED # RFC3454 section 2, step 1 - Map # RFC4013 section 2.1 mappings # Map Non-ASCII space characters to SPACE (U+0020). Map # commonly mapped to nothing characters to, well, nothing. in_table_c12 = stringprep.in_table_c12 in_table_b1 = stringprep.in_table_b1 data = "".join( ["\u0020" if in_table_c12(elt) else elt for elt in data if not in_table_b1(elt)]) # RFC3454 section 2, step 2 - Normalize # RFC4013 section 2.2 normalization data = unicodedata.ucd_3_2_0.normalize('NFKC', data) in_table_d1 = stringprep.in_table_d1 if in_table_d1(data[0]): if not in_table_d1(data[-1]): # RFC3454, Section 6, #3. If a string contains any # RandALCat character, the first and last characters # MUST be RandALCat characters. raise ValueError("SASLprep: failed bidirectional check") # RFC3454, Section 6, #2. If a string contains any RandALCat # character, it MUST NOT contain any LCat character. prohibited = prohibited + (stringprep.in_table_d2,) else: # RFC3454, Section 6, #3. Following the logic of #3, if # the first character is not a RandALCat, no other character # can be either. prohibited = prohibited + (in_table_d1,) # RFC3454 section 2, step 3 and 4 - Prohibit and check bidi for char in data: if any(in_table(char) for in_table in prohibited): raise ValueError( "SASLprep: failed prohibited character check") return data
[ "def", "saslprep", "(", "data", ":", "str", ",", "prohibit_unassigned_code_points", ":", "bool", "=", "True", ")", "->", "str", ":", "if", "prohibit_unassigned_code_points", ":", "prohibited", "=", "_PROHIBITED", "+", "(", "stringprep", ".", "in_table_a1", ",", ...
https://github.com/pdfminer/pdfminer.six/blob/10f6fb40c258c86fd04d86bade20f69fb07faabd/pdfminer/_saslprep.py#L43-L95
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/dateutil/tz/_common.py
python
_tzinfo.fromutc
(self, dt)
return enfold(dt_wall, fold=_fold)
Given a timezone-aware datetime in a given timezone, calculates a timezone-aware datetime in a new timezone. Since this is the one time that we *know* we have an unambiguous datetime object, we take this opportunity to determine whether the datetime is ambiguous and in a "fold" state (e.g. if it's the first occurance, chronologically, of the ambiguous datetime). :param dt: A timezone-aware :class:`datetime.datetime` object.
Given a timezone-aware datetime in a given timezone, calculates a timezone-aware datetime in a new timezone.
[ "Given", "a", "timezone", "-", "aware", "datetime", "in", "a", "given", "timezone", "calculates", "a", "timezone", "-", "aware", "datetime", "in", "a", "new", "timezone", "." ]
def fromutc(self, dt): """ Given a timezone-aware datetime in a given timezone, calculates a timezone-aware datetime in a new timezone. Since this is the one time that we *know* we have an unambiguous datetime object, we take this opportunity to determine whether the datetime is ambiguous and in a "fold" state (e.g. if it's the first occurance, chronologically, of the ambiguous datetime). :param dt: A timezone-aware :class:`datetime.datetime` object. """ dt_wall = self._fromutc(dt) # Calculate the fold status given the two datetimes. _fold = self._fold_status(dt, dt_wall) # Set the default fold value for ambiguous dates return enfold(dt_wall, fold=_fold)
[ "def", "fromutc", "(", "self", ",", "dt", ")", ":", "dt_wall", "=", "self", ".", "_fromutc", "(", "dt", ")", "# Calculate the fold status given the two datetimes.", "_fold", "=", "self", ".", "_fold_status", "(", "dt", ",", "dt_wall", ")", "# Set the default fol...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/dateutil/tz/_common.py#L241-L260
LiuRoy/zhihu_spider
8eb925d294689ad9ab13c1532fb7ba8c556b5ea7
zhihu/zhihu/pipelines.py
python
ZhihuPipeline._process_relation
(self, item)
存储人际拓扑关系
存储人际拓扑关系
[ "存储人际拓扑关系" ]
def _process_relation(self, item): """ 存储人际拓扑关系 """ collection = self.db['relation'] data = collection.find_one({ 'zhihu_id': item['zhihu_id'], 'user_type': item['user_type']}) if not data: self.db['relation'].insert(dict(item)) else: origin_list = data['user_list'] new_list = item['user_list'] data['user_list'] = list(set(origin_list) | set(new_list)) collection.update({'zhihu_id': item['zhihu_id'], 'user_type': item['user_type']}, data)
[ "def", "_process_relation", "(", "self", ",", "item", ")", ":", "collection", "=", "self", ".", "db", "[", "'relation'", "]", "data", "=", "collection", ".", "find_one", "(", "{", "'zhihu_id'", ":", "item", "[", "'zhihu_id'", "]", ",", "'user_type'", ":"...
https://github.com/LiuRoy/zhihu_spider/blob/8eb925d294689ad9ab13c1532fb7ba8c556b5ea7/zhihu/zhihu/pipelines.py#L57-L73
Tencent/bk-bcs-saas
2b437bf2f5fd5ce2078f7787c3a12df609f7679d
bcs-app/backend/utils/local.py
python
Local.get_http_request_id
(self)
return new_request_id()
从接入层获取request_id,或者生成一个新的request_id
从接入层获取request_id,或者生成一个新的request_id
[ "从接入层获取request_id,或者生成一个新的request_id" ]
def get_http_request_id(self): """从接入层获取request_id,或者生成一个新的request_id""" # 在从header中获取 request_id = self.request.META.get(settings.REQUEST_ID_HEADER, '') if request_id: return request_id # 最后主动生成一个 return new_request_id()
[ "def", "get_http_request_id", "(", "self", ")", ":", "# 在从header中获取", "request_id", "=", "self", ".", "request", ".", "META", ".", "get", "(", "settings", ".", "REQUEST_ID_HEADER", ",", "''", ")", "if", "request_id", ":", "return", "request_id", "# 最后主动生成一个", ...
https://github.com/Tencent/bk-bcs-saas/blob/2b437bf2f5fd5ce2078f7787c3a12df609f7679d/bcs-app/backend/utils/local.py#L65-L73
log2timeline/plaso
fe2e316b8c76a0141760c0f2f181d84acb83abc2
plaso/analysis/chrome_extension.py
python
ChromeExtensionPlugin._GetPathSegmentSeparator
(self, path)
return '/'
Given a path give back the path separator as a best guess. Args: path (str): path. Returns: str: path segment separator.
Given a path give back the path separator as a best guess.
[ "Given", "a", "path", "give", "back", "the", "path", "separator", "as", "a", "best", "guess", "." ]
def _GetPathSegmentSeparator(self, path): """Given a path give back the path separator as a best guess. Args: path (str): path. Returns: str: path segment separator. """ if path[0] in ('\\', '/'): return path[0] if path[1:].startswith(':\\'): return '\\' backward_slash_count = path.count('\\') forward_slash_count = path.count('/') if backward_slash_count > forward_slash_count: return '\\' return '/'
[ "def", "_GetPathSegmentSeparator", "(", "self", ",", "path", ")", ":", "if", "path", "[", "0", "]", "in", "(", "'\\\\'", ",", "'/'", ")", ":", "return", "path", "[", "0", "]", "if", "path", "[", "1", ":", "]", ".", "startswith", "(", "':\\\\'", "...
https://github.com/log2timeline/plaso/blob/fe2e316b8c76a0141760c0f2f181d84acb83abc2/plaso/analysis/chrome_extension.py#L54-L74
h5py/h5py
aa31f03bef99e5807d1d6381e36233325d944279
h5py/_hl/files.py
python
register_driver
(name, set_fapl)
Register a custom driver. Parameters ---------- name : str The name of the driver. set_fapl : callable[PropFAID, **kwargs] -> NoneType The function to set the fapl to use your custom driver.
Register a custom driver.
[ "Register", "a", "custom", "driver", "." ]
def register_driver(name, set_fapl): """Register a custom driver. Parameters ---------- name : str The name of the driver. set_fapl : callable[PropFAID, **kwargs] -> NoneType The function to set the fapl to use your custom driver. """ _drivers[name] = set_fapl
[ "def", "register_driver", "(", "name", ",", "set_fapl", ")", ":", "_drivers", "[", "name", "]", "=", "set_fapl" ]
https://github.com/h5py/h5py/blob/aa31f03bef99e5807d1d6381e36233325d944279/h5py/_hl/files.py#L81-L91
IronLanguages/ironpython3
7a7bb2a872eeab0d1009fc8a6e24dca43f65b693
Src/StdLib/Lib/encodings/cp720.py
python
IncrementalEncoder.encode
(self, input, final=False)
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
[]
def encode(self, input, final=False): return codecs.charmap_encode(input,self.errors,encoding_table)[0]
[ "def", "encode", "(", "self", ",", "input", ",", "final", "=", "False", ")", ":", "return", "codecs", ".", "charmap_encode", "(", "input", ",", "self", ".", "errors", ",", "encoding_table", ")", "[", "0", "]" ]
https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/encodings/cp720.py#L20-L21
mjwestcott/Goodrich
dc2516591bd28488516c0337a62e64248debe47c
ch08/linked_binary_tree.py
python
LinkedBinaryTree._delete
(self, p)
return node._element
Delete the node at Position p, and replace it with its child, if any. Return the element that had been stored at Position p. Raise ValueError if Position p is invalid or p has two children.
Delete the node at Position p, and replace it with its child, if any.
[ "Delete", "the", "node", "at", "Position", "p", "and", "replace", "it", "with", "its", "child", "if", "any", "." ]
def _delete(self, p): """Delete the node at Position p, and replace it with its child, if any. Return the element that had been stored at Position p. Raise ValueError if Position p is invalid or p has two children. """ node = self._validate(p) if self.num_children(p) == 2: raise ValueError('Position has two children') child = node._left if node._left else node._right # might be None if child is not None: child._parent = node._parent # child's grandparent becomes parent if node is self._root: self._root = child # child becomes root else: parent = node._parent if node is parent._left: parent._left = child else: parent._right = child self._size -= 1 node._parent = node # convention for deprecated node return node._element
[ "def", "_delete", "(", "self", ",", "p", ")", ":", "node", "=", "self", ".", "_validate", "(", "p", ")", "if", "self", ".", "num_children", "(", "p", ")", "==", "2", ":", "raise", "ValueError", "(", "'Position has two children'", ")", "child", "=", "...
https://github.com/mjwestcott/Goodrich/blob/dc2516591bd28488516c0337a62e64248debe47c/ch08/linked_binary_tree.py#L155-L177
researchmm/tasn
5dba8ccc096cedc63913730eeea14a9647911129
tasn-mxnet/3rdparty/tvm/python/tvm/autotvm/database.py
python
Database.load
(self, inp, get_all=False)
Load a result based on an input's string key Parameters ---------- inp: MeasureInput to be translated into key for RedisDB get_all: bool, optional Whether the latest result (or all matching results) should be returned Returns ------- rec: MeasureResult if previously saved, otherwise None
Load a result based on an input's string key
[ "Load", "a", "result", "based", "on", "an", "input", "s", "string", "key" ]
def load(self, inp, get_all=False): """ Load a result based on an input's string key Parameters ---------- inp: MeasureInput to be translated into key for RedisDB get_all: bool, optional Whether the latest result (or all matching results) should be returned Returns ------- rec: MeasureResult if previously saved, otherwise None """ raise NotImplementedError()
[ "def", "load", "(", "self", ",", "inp", ",", "get_all", "=", "False", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/researchmm/tasn/blob/5dba8ccc096cedc63913730eeea14a9647911129/tasn-mxnet/3rdparty/tvm/python/tvm/autotvm/database.py#L15-L30
IronLanguages/ironpython3
7a7bb2a872eeab0d1009fc8a6e24dca43f65b693
Src/StdLib/Lib/shutil.py
python
_unpack_zipfile
(filename, extract_dir)
Unpack zip `filename` to `extract_dir`
Unpack zip `filename` to `extract_dir`
[ "Unpack", "zip", "filename", "to", "extract_dir" ]
def _unpack_zipfile(filename, extract_dir): """Unpack zip `filename` to `extract_dir` """ try: import zipfile except ImportError: raise ReadError('zlib not supported, cannot unpack this archive.') if not zipfile.is_zipfile(filename): raise ReadError("%s is not a zip file" % filename) zip = zipfile.ZipFile(filename) try: for info in zip.infolist(): name = info.filename # don't extract absolute paths or ones with .. in them if name.startswith('/') or '..' in name: continue target = os.path.join(extract_dir, *name.split('/')) if not target: continue _ensure_directory(target) if not name.endswith('/'): # file data = zip.read(info.filename) f = open(target, 'wb') try: f.write(data) finally: f.close() del data finally: zip.close()
[ "def", "_unpack_zipfile", "(", "filename", ",", "extract_dir", ")", ":", "try", ":", "import", "zipfile", "except", "ImportError", ":", "raise", "ReadError", "(", "'zlib not supported, cannot unpack this archive.'", ")", "if", "not", "zipfile", ".", "is_zipfile", "(...
https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/shutil.py#L869-L904
simonw/sqlite-utils
e0c476bc380744680c8b7675c24fb0e9f5ec6dcd
sqlite_utils/db.py
python
Database.vacuum
(self)
Run a SQLite ``VACUUM`` against the database.
Run a SQLite ``VACUUM`` against the database.
[ "Run", "a", "SQLite", "VACUUM", "against", "the", "database", "." ]
def vacuum(self): "Run a SQLite ``VACUUM`` against the database." self.execute("VACUUM;")
[ "def", "vacuum", "(", "self", ")", ":", "self", ".", "execute", "(", "\"VACUUM;\"", ")" ]
https://github.com/simonw/sqlite-utils/blob/e0c476bc380744680c8b7675c24fb0e9f5ec6dcd/sqlite_utils/db.py#L922-L924
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
vendor/packages/twisted/twisted/spread/pb.py
python
RemoteReference.callRemote
(self, _name, *args, **kw)
return self.broker._sendMessage('',self.perspective, self.luid, _name, args, kw)
Asynchronously invoke a remote method. @type _name: C{string} @param _name: the name of the remote method to invoke @param args: arguments to serialize for the remote function @param kw: keyword arguments to serialize for the remote function. @rtype: L{twisted.internet.defer.Deferred} @returns: a Deferred which will be fired when the result of this remote call is received.
Asynchronously invoke a remote method.
[ "Asynchronously", "invoke", "a", "remote", "method", "." ]
def callRemote(self, _name, *args, **kw): """Asynchronously invoke a remote method. @type _name: C{string} @param _name: the name of the remote method to invoke @param args: arguments to serialize for the remote function @param kw: keyword arguments to serialize for the remote function. @rtype: L{twisted.internet.defer.Deferred} @returns: a Deferred which will be fired when the result of this remote call is received. """ # note that we use '_name' instead of 'name' so the user can call # remote methods with 'name' as a keyword parameter, like this: # ref.callRemote("getPeopleNamed", count=12, name="Bob") return self.broker._sendMessage('',self.perspective, self.luid, _name, args, kw)
[ "def", "callRemote", "(", "self", ",", "_name", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "# note that we use '_name' instead of 'name' so the user can call", "# remote methods with 'name' as a keyword parameter, like this:", "# ref.callRemote(\"getPeopleNamed\", count=12, ...
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/twisted/twisted/spread/pb.py#L312-L328
pypa/pip
7f8a6844037fb7255cfd0d34ff8e8cf44f2598d4
src/pip/_internal/metadata/pkg_resources.py
python
Distribution.metadata
(self)
return feed_parser.close()
:raises NoneMetadataError: if the distribution reports `has_metadata()` True but `get_metadata()` returns None.
:raises NoneMetadataError: if the distribution reports `has_metadata()` True but `get_metadata()` returns None.
[ ":", "raises", "NoneMetadataError", ":", "if", "the", "distribution", "reports", "has_metadata", "()", "True", "but", "get_metadata", "()", "returns", "None", "." ]
def metadata(self) -> email.message.Message: """ :raises NoneMetadataError: if the distribution reports `has_metadata()` True but `get_metadata()` returns None. """ if isinstance(self._dist, pkg_resources.DistInfoDistribution): metadata_name = "METADATA" else: metadata_name = "PKG-INFO" try: metadata = self.read_text(metadata_name) except FileNotFoundError: if self.location: displaying_path = display_path(self.location) else: displaying_path = repr(self.location) logger.warning("No metadata found in %s", displaying_path) metadata = "" feed_parser = email.parser.FeedParser() feed_parser.feed(metadata) return feed_parser.close()
[ "def", "metadata", "(", "self", ")", "->", "email", ".", "message", ".", "Message", ":", "if", "isinstance", "(", "self", ".", "_dist", ",", "pkg_resources", ".", "DistInfoDistribution", ")", ":", "metadata_name", "=", "\"METADATA\"", "else", ":", "metadata_...
https://github.com/pypa/pip/blob/7f8a6844037fb7255cfd0d34ff8e8cf44f2598d4/src/pip/_internal/metadata/pkg_resources.py#L177-L197
andresriancho/w3af
cd22e5252243a87aaa6d0ddea47cf58dacfe00a9
w3af/plugins/attack/db/sqlmap/thirdparty/odict/odict.py
python
Keys.__call__
(self)
return self._main._keys()
Pretend to be the keys method.
Pretend to be the keys method.
[ "Pretend", "to", "be", "the", "keys", "method", "." ]
def __call__(self): """Pretend to be the keys method.""" return self._main._keys()
[ "def", "__call__", "(", "self", ")", ":", "return", "self", ".", "_main", ".", "_keys", "(", ")" ]
https://github.com/andresriancho/w3af/blob/cd22e5252243a87aaa6d0ddea47cf58dacfe00a9/w3af/plugins/attack/db/sqlmap/thirdparty/odict/odict.py#L889-L891
kennethreitz-archive/requests3
69eb662703b40db58fdc6c095d0fe130c56649bb
requests3/__init__.py
python
_check_cryptography
(cryptography_version: str)
[]
def _check_cryptography(cryptography_version: str) -> None: # cryptography < 1.3.4 try: cryptography_version = list( map(int, cryptography_version.split(".")) ) # type: ignore except ValueError: return if cryptography_version < [1, 3, 4]: warning = "Old version of cryptography ({}) may cause slowdown.".format( cryptography_version ) warnings.warn(warning, RequestsDependencyWarning)
[ "def", "_check_cryptography", "(", "cryptography_version", ":", "str", ")", "->", "None", ":", "# cryptography < 1.3.4", "try", ":", "cryptography_version", "=", "list", "(", "map", "(", "int", ",", "cryptography_version", ".", "split", "(", "\".\"", ")", ")", ...
https://github.com/kennethreitz-archive/requests3/blob/69eb662703b40db58fdc6c095d0fe130c56649bb/requests3/__init__.py#L70-L83
yahoo/lopq
0f17655b901e6dfabe5c2aa62b4c8e492f34b05a
scripts/query_runtime.py
python
subquantizer_flops
(D, M, clusters=256)
return (M / 2) * (D / M) * clusters * 2
Given the dimension of the data, the number of subquantizers and the subquantizer vocabulary size, compute the number of flops to compute a projected query's LOPQ distance for a single half of the query.
Given the dimension of the data, the number of subquantizers and the subquantizer vocabulary size, compute the number of flops to compute a projected query's LOPQ distance for a single half of the query.
[ "Given", "the", "dimension", "of", "the", "data", "the", "number", "of", "subquantizers", "and", "the", "subquantizer", "vocabulary", "size", "compute", "the", "number", "of", "flops", "to", "compute", "a", "projected", "query", "s", "LOPQ", "distance", "for",...
def subquantizer_flops(D, M, clusters=256): """ Given the dimension of the data, the number of subquantizers and the subquantizer vocabulary size, compute the number of flops to compute a projected query's LOPQ distance for a single half of the query. """ # (subquants per half) * (dims per subquant) * (cluster per subquant) * (flops per squared distance) return (M / 2) * (D / M) * clusters * 2
[ "def", "subquantizer_flops", "(", "D", ",", "M", ",", "clusters", "=", "256", ")", ":", "# (subquants per half) * (dims per subquant) * (cluster per subquant) * (flops per squared distance)", "return", "(", "M", "/", "2", ")", "*", "(", "D", "/", "M", ")", "*", "c...
https://github.com/yahoo/lopq/blob/0f17655b901e6dfabe5c2aa62b4c8e492f34b05a/scripts/query_runtime.py#L25-L32
HCIILAB/DeRPN
21e6738ee1f7d3f159ee48d435c543e773f8ce99
tools/train_svms.py
python
SVMTrainer.train
(self)
[]
def train(self): # Initialize SVMs using # a. w_i = fc8_w_i - fc8_w_0 # b. b_i = fc8_b_i - fc8_b_0 # c. Install SVMs into net self.initialize_net() # Pass over roidb to count num positives for each class # a. Pre-allocate arrays for positive feature vectors # Pass over roidb, computing features for positives only self.get_pos_examples() # Pass over roidb # a. Compute cls_score with forward pass # b. For each class # i. Select hard negatives # ii. Add them to cache # c. For each class # i. If SVM retrain criteria met, update SVM # ii. Install new SVM into net self.train_with_hard_negatives() # One final SVM retraining for each class # Install SVMs into net for j in xrange(1, self.imdb.num_classes): new_w_b = self.trainers[j].append_neg_and_retrain(force=True) self.update_net(j, new_w_b[0], new_w_b[1])
[ "def", "train", "(", "self", ")", ":", "# Initialize SVMs using", "# a. w_i = fc8_w_i - fc8_w_0", "# b. b_i = fc8_b_i - fc8_b_0", "# c. Install SVMs into net", "self", ".", "initialize_net", "(", ")", "# Pass over roidb to count num positives for each class", "# a. Pre-alloca...
https://github.com/HCIILAB/DeRPN/blob/21e6738ee1f7d3f159ee48d435c543e773f8ce99/tools/train_svms.py#L164-L190
qiucheng025/zao-
3a5edf3607b3a523f95746bc69b688090c76d89a
lib/face_filter.py
python
FaceFilter.get_filter_encodings
(self)
Return filter face encodings from Keras VGG Face
Return filter face encodings from Keras VGG Face
[ "Return", "filter", "face", "encodings", "from", "Keras", "VGG", "Face" ]
def get_filter_encodings(self): """ Return filter face encodings from Keras VGG Face """ for filename, face in self.filters.items(): logger.debug("Getting encodings for: '%s'", filename) encodings = self.vgg_face.predict(face["face"]) logger.debug("Filter Filename: %s, encoding shape: %s", filename, encodings.shape) face["encoding"] = encodings del face["face"]
[ "def", "get_filter_encodings", "(", "self", ")", ":", "for", "filename", ",", "face", "in", "self", ".", "filters", ".", "items", "(", ")", ":", "logger", ".", "debug", "(", "\"Getting encodings for: '%s'\"", ",", "filename", ")", "encodings", "=", "self", ...
https://github.com/qiucheng025/zao-/blob/3a5edf3607b3a523f95746bc69b688090c76d89a/lib/face_filter.py#L116-L123
flennerhag/mlens
6cbc11354b5f9500a33d9cefb700a1bba9d3199a
mlens/index/subsemble.py
python
SubsetIndex._gen_indices
(self)
Create generator for subsample. Generate indices of training set and test set for - each partition - each fold in the partition Note that the test index return is *global*, i.e. it contains the test indices of that fold across partitions. See Examples for further details.
Create generator for subsample.
[ "Create", "generator", "for", "subsample", "." ]
def _gen_indices(self): """Create generator for subsample. Generate indices of training set and test set for - each partition - each fold in the partition Note that the test index return is *global*, i.e. it contains the test indices of that fold across partitions. See Examples for further details. """ partitions = self.partitions n_samples = self.n_samples folds = self.folds T = self._build_test_sets() # For each partition, for each fold, get the global test fold # from T and index the partition samples not in T as train set p_len = partition(n_samples, partitions) p_last = 0 for p_size in p_len: p_start, p_stop = p_last, p_last + p_size t_len = partition(p_stop - p_start, folds) t_last = p_start for i, t_size in enumerate(t_len): t_start, t_stop = t_last, t_last + t_size # Get global test set indices tei = T[i] # Construct train set tri_start_below, tri_stop_below = p_start, t_start tri_start_above, tri_stop_above = t_stop, p_stop tri = prune_train(tri_start_below, tri_stop_below, tri_start_above, tri_stop_above) yield tri, tei t_last += t_size p_last += p_size
[ "def", "_gen_indices", "(", "self", ")", ":", "partitions", "=", "self", ".", "partitions", "n_samples", "=", "self", ".", "n_samples", "folds", "=", "self", ".", "folds", "T", "=", "self", ".", "_build_test_sets", "(", ")", "# For each partition, for each fol...
https://github.com/flennerhag/mlens/blob/6cbc11354b5f9500a33d9cefb700a1bba9d3199a/mlens/index/subsemble.py#L231-L274
dipy/dipy
be956a529465b28085f8fc435a756947ddee1c89
dipy/io/stateful_tractogram.py
python
StatefulTractogram._vox_to_rasmm
(self)
Unsafe function to transform streamlines
Unsafe function to transform streamlines
[ "Unsafe", "function", "to", "transform", "streamlines" ]
def _vox_to_rasmm(self): """ Unsafe function to transform streamlines """ if self._space == Space.VOX: if self._tractogram.streamlines._data.size > 0: self._tractogram.apply_affine(self._affine) self._space = Space.RASMM logger.debug('Moved streamlines from vox to rasmm.') else: logger.warning('Wrong initial space for this function.') return
[ "def", "_vox_to_rasmm", "(", "self", ")", ":", "if", "self", ".", "_space", "==", "Space", ".", "VOX", ":", "if", "self", ".", "_tractogram", ".", "streamlines", ".", "_data", ".", "size", ">", "0", ":", "self", ".", "_tractogram", ".", "apply_affine",...
https://github.com/dipy/dipy/blob/be956a529465b28085f8fc435a756947ddee1c89/dipy/io/stateful_tractogram.py#L603-L612
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/uptimerobot/__init__.py
python
UptimeRobotDataUpdateCoordinator.__init__
( self, hass: HomeAssistant, config_entry_id: str, dev_reg: DeviceRegistry, api: UptimeRobot, )
Initialize coordinator.
Initialize coordinator.
[ "Initialize", "coordinator", "." ]
def __init__( self, hass: HomeAssistant, config_entry_id: str, dev_reg: DeviceRegistry, api: UptimeRobot, ) -> None: """Initialize coordinator.""" super().__init__( hass, LOGGER, name=DOMAIN, update_method=self._async_update_data, update_interval=COORDINATOR_UPDATE_INTERVAL, ) self._config_entry_id = config_entry_id self._device_registry = dev_reg self._api = api
[ "def", "__init__", "(", "self", ",", "hass", ":", "HomeAssistant", ",", "config_entry_id", ":", "str", ",", "dev_reg", ":", "DeviceRegistry", ",", "api", ":", "UptimeRobot", ",", ")", "->", "None", ":", "super", "(", ")", ".", "__init__", "(", "hass", ...
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/uptimerobot/__init__.py#L60-L77
graphcore/examples
46d2b7687b829778369fc6328170a7b14761e5c6
applications/tensorflow/cnns/inference/models/tf_layers.py
python
crop
(input_tensor: tf.Tensor, cropping: Tuple[Tuple[int, int], Tuple[int, int]])
return input_tensor[:, cropping[0][0]:rows - cropping[0][1], cropping[1][0]:cols - cropping[1][1], :]
Crop input along width and height dimensions, assumes channels_last. Args: input_tensor: Input to be cropped. cropping: Start and stop index along height and width. Returns: Cropped tensor.
Crop input along width and height dimensions, assumes channels_last.
[ "Crop", "input", "along", "width", "and", "height", "dimensions", "assumes", "channels_last", "." ]
def crop(input_tensor: tf.Tensor, cropping: Tuple[Tuple[int, int], Tuple[int, int]]): """Crop input along width and height dimensions, assumes channels_last. Args: input_tensor: Input to be cropped. cropping: Start and stop index along height and width. Returns: Cropped tensor. """ _, rows, cols, _ = input_tensor.get_shape().as_list() return input_tensor[:, cropping[0][0]:rows - cropping[0][1], cropping[1][0]:cols - cropping[1][1], :]
[ "def", "crop", "(", "input_tensor", ":", "tf", ".", "Tensor", ",", "cropping", ":", "Tuple", "[", "Tuple", "[", "int", ",", "int", "]", ",", "Tuple", "[", "int", ",", "int", "]", "]", ")", ":", "_", ",", "rows", ",", "cols", ",", "_", "=", "i...
https://github.com/graphcore/examples/blob/46d2b7687b829778369fc6328170a7b14761e5c6/applications/tensorflow/cnns/inference/models/tf_layers.py#L478-L488
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/python/lib/python2.7/distutils/command/sdist.py
python
sdist.add_defaults
(self)
Add all the default files to self.filelist: - README or README.txt - setup.py - test/test*.py - all pure Python modules mentioned in setup script - all files pointed by package_data (build_py) - all files defined in data_files. - all files defined as scripts. - all C sources listed as part of extensions or C libraries in the setup script (doesn't catch C headers!) Warns if (README or README.txt) or setup.py are missing; everything else is optional.
Add all the default files to self.filelist: - README or README.txt - setup.py - test/test*.py - all pure Python modules mentioned in setup script - all files pointed by package_data (build_py) - all files defined in data_files. - all files defined as scripts. - all C sources listed as part of extensions or C libraries in the setup script (doesn't catch C headers!) Warns if (README or README.txt) or setup.py are missing; everything else is optional.
[ "Add", "all", "the", "default", "files", "to", "self", ".", "filelist", ":", "-", "README", "or", "README", ".", "txt", "-", "setup", ".", "py", "-", "test", "/", "test", "*", ".", "py", "-", "all", "pure", "Python", "modules", "mentioned", "in", "...
def add_defaults(self): """Add all the default files to self.filelist: - README or README.txt - setup.py - test/test*.py - all pure Python modules mentioned in setup script - all files pointed by package_data (build_py) - all files defined in data_files. - all files defined as scripts. - all C sources listed as part of extensions or C libraries in the setup script (doesn't catch C headers!) Warns if (README or README.txt) or setup.py are missing; everything else is optional. """ standards = [('README', 'README.txt'), self.distribution.script_name] for fn in standards: if isinstance(fn, tuple): alts = fn got_it = 0 for fn in alts: if os.path.exists(fn): got_it = 1 self.filelist.append(fn) break if not got_it: self.warn("standard file not found: should have one of " + string.join(alts, ', ')) else: if os.path.exists(fn): self.filelist.append(fn) else: self.warn("standard file '%s' not found" % fn) optional = ['test/test*.py', 'setup.cfg'] for pattern in optional: files = filter(os.path.isfile, glob(pattern)) if files: self.filelist.extend(files) # build_py is used to get: # - python modules # - files defined in package_data build_py = self.get_finalized_command('build_py') # getting python files if self.distribution.has_pure_modules(): self.filelist.extend(build_py.get_source_files()) # getting package_data files # (computed in build_py.data_files by build_py.finalize_options) for pkg, src_dir, build_dir, filenames in build_py.data_files: for filename in filenames: self.filelist.append(os.path.join(src_dir, filename)) # getting distribution.data_files if self.distribution.has_data_files(): for item in self.distribution.data_files: if isinstance(item, str): # plain file item = convert_path(item) if os.path.isfile(item): self.filelist.append(item) else: # a (dirname, filenames) tuple dirname, filenames = item for f in filenames: f = convert_path(f) if os.path.isfile(f): self.filelist.append(f) if self.distribution.has_ext_modules(): build_ext = self.get_finalized_command('build_ext') self.filelist.extend(build_ext.get_source_files()) if self.distribution.has_c_libraries(): build_clib = self.get_finalized_command('build_clib') self.filelist.extend(build_clib.get_source_files()) if self.distribution.has_scripts(): build_scripts = self.get_finalized_command('build_scripts') self.filelist.extend(build_scripts.get_source_files())
[ "def", "add_defaults", "(", "self", ")", ":", "standards", "=", "[", "(", "'README'", ",", "'README.txt'", ")", ",", "self", ".", "distribution", ".", "script_name", "]", "for", "fn", "in", "standards", ":", "if", "isinstance", "(", "fn", ",", "tuple", ...
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/distutils/command/sdist.py#L218-L298
IlyaSkriblovsky/txredisapi
c89a49829d1c48baa10d03c41d39c261c02ad6e1
txredisapi.py
python
BaseRedisProtocol.lindex
(self, key, index)
return self.execute_command("LINDEX", key, index)
Return the element at index position from the List at key
Return the element at index position from the List at key
[ "Return", "the", "element", "at", "index", "position", "from", "the", "List", "at", "key" ]
def lindex(self, key, index): """ Return the element at index position from the List at key """ return self.execute_command("LINDEX", key, index)
[ "def", "lindex", "(", "self", ",", "key", ",", "index", ")", ":", "return", "self", ".", "execute_command", "(", "\"LINDEX\"", ",", "key", ",", "index", ")" ]
https://github.com/IlyaSkriblovsky/txredisapi/blob/c89a49829d1c48baa10d03c41d39c261c02ad6e1/txredisapi.py#L988-L992
Abjad/abjad
d0646dfbe83db3dc5ab268f76a0950712b87b7fd
abjad/indicators/StartPianoPedal.py
python
StartPianoPedal.tweaks
(self)
return self._tweaks
r""" Gets tweaks .. container:: example REGRESSION. Tweaks survive copy: >>> import copy >>> start_piano_pedal = abjad.StartPianoPedal() >>> abjad.tweak(start_piano_pedal).color = "#blue" >>> string = abjad.storage(start_piano_pedal) >>> print(string) abjad.StartPianoPedal( tweaks=TweakInterface(('_literal', None), ('color', '#blue')), ) >>> start_piano_pedal_2 = copy.copy(start_piano_pedal) >>> string = abjad.storage(start_piano_pedal_2) >>> print(string) abjad.StartPianoPedal( tweaks=TweakInterface(('_literal', None), ('color', '#blue')), )
r""" Gets tweaks
[ "r", "Gets", "tweaks" ]
def tweaks(self) -> typing.Optional[_overrides.TweakInterface]: r""" Gets tweaks .. container:: example REGRESSION. Tweaks survive copy: >>> import copy >>> start_piano_pedal = abjad.StartPianoPedal() >>> abjad.tweak(start_piano_pedal).color = "#blue" >>> string = abjad.storage(start_piano_pedal) >>> print(string) abjad.StartPianoPedal( tweaks=TweakInterface(('_literal', None), ('color', '#blue')), ) >>> start_piano_pedal_2 = copy.copy(start_piano_pedal) >>> string = abjad.storage(start_piano_pedal_2) >>> print(string) abjad.StartPianoPedal( tweaks=TweakInterface(('_literal', None), ('color', '#blue')), ) """ return self._tweaks
[ "def", "tweaks", "(", "self", ")", "->", "typing", ".", "Optional", "[", "_overrides", ".", "TweakInterface", "]", ":", "return", "self", ".", "_tweaks" ]
https://github.com/Abjad/abjad/blob/d0646dfbe83db3dc5ab268f76a0950712b87b7fd/abjad/indicators/StartPianoPedal.py#L135-L160
barseghyanartur/django-fobi
a998feae007d7fe3637429a80e42952ec7cda79f
src/fobi/contrib/plugins/form_elements/content/content_text/base.py
python
ContentTextPlugin.get_rendered_text
(self)
return rendered_text
Get rendered text.
Get rendered text.
[ "Get", "rendered", "text", "." ]
def get_rendered_text(self): """Get rendered text.""" rendered_text = "<p>{0}</p>".format(smart_str(self.data.text)) return rendered_text
[ "def", "get_rendered_text", "(", "self", ")", ":", "rendered_text", "=", "\"<p>{0}</p>\"", ".", "format", "(", "smart_str", "(", "self", ".", "data", ".", "text", ")", ")", "return", "rendered_text" ]
https://github.com/barseghyanartur/django-fobi/blob/a998feae007d7fe3637429a80e42952ec7cda79f/src/fobi/contrib/plugins/form_elements/content/content_text/base.py#L49-L52
luispedro/jug
e967c6388ca69c78698e1522b9535d647a2c5b22
jug/hooks/exit_checks.py
python
exit_after_n_tasks
(n)
Exit after a specific number of tasks have been executed Parameters ---------- n : int Number of tasks to execute
Exit after a specific number of tasks have been executed
[ "Exit", "after", "a", "specific", "number", "of", "tasks", "have", "been", "executed" ]
def exit_after_n_tasks(n): '''Exit after a specific number of tasks have been executed Parameters ---------- n : int Number of tasks to execute ''' from jug import hooks # In newer Python, we could use nonlocal, but this is a work around # (http://stackoverflow.com/questions/9603278/is-there-something-like-nonlocal-in-python-3/9603491#9603491) executed = [0] def exit_after(_t): executed[0] += 1 if executed[0] >= n: exit(0) hooks.register_hook('execute.task-executed1', exit_after)
[ "def", "exit_after_n_tasks", "(", "n", ")", ":", "from", "jug", "import", "hooks", "# In newer Python, we could use nonlocal, but this is a work around", "# (http://stackoverflow.com/questions/9603278/is-there-something-like-nonlocal-in-python-3/9603491#9603491)", "executed", "=", "[", ...
https://github.com/luispedro/jug/blob/e967c6388ca69c78698e1522b9535d647a2c5b22/jug/hooks/exit_checks.py#L42-L59
lsbardel/python-stdnet
78db5320bdedc3f28c5e4f38cda13a4469e35db7
stdnet/odm/fields.py
python
JSONField.set_get_value
(self, instance, value)
[]
def set_get_value(self, instance, value): # Optimisation, avoid to call serialise since it is the same # as to_python value = self.to_python(value) setattr(instance, self.attname, value) if self.as_string: # dump as a string return self.serialise(value) else: # unwind as a dictionary value = dict(dict_flat_generator(value, attname=self.attname, dumps=self.serialise, error=FieldValueError)) # If the dictionary is empty we modify so that # an update is possible. if not value: value = {self.attname: self.serialise(None)} elif value.get(self.attname, None) is None: # TODO Better implementation of this is a ack! # set the root value to an empty string to distinguish # from None. value[self.attname] = self.serialise('') return value
[ "def", "set_get_value", "(", "self", ",", "instance", ",", "value", ")", ":", "# Optimisation, avoid to call serialise since it is the same", "# as to_python", "value", "=", "self", ".", "to_python", "(", "value", ")", "setattr", "(", "instance", ",", "self", ".", ...
https://github.com/lsbardel/python-stdnet/blob/78db5320bdedc3f28c5e4f38cda13a4469e35db7/stdnet/odm/fields.py#L770-L793
nerdvegas/rez
d392c65bf63b4bca8106f938cec49144ba54e770
src/rez/rex.py
python
RexExecutor.compile_code
(cls, code, filename=None, exec_namespace=None)
return pyc
Compile and possibly execute rex code. Args: code (str or SourceCode): The python code to compile. filename (str): File to associate with the code, will default to '<string>'. exec_namespace (dict): Namespace to execute the code in. If None, the code is not executed. Returns: Compiled code object.
Compile and possibly execute rex code.
[ "Compile", "and", "possibly", "execute", "rex", "code", "." ]
def compile_code(cls, code, filename=None, exec_namespace=None): """Compile and possibly execute rex code. Args: code (str or SourceCode): The python code to compile. filename (str): File to associate with the code, will default to '<string>'. exec_namespace (dict): Namespace to execute the code in. If None, the code is not executed. Returns: Compiled code object. """ if filename is None: if isinstance(code, SourceCode): filename = code.sourcename else: filename = "<string>" # compile try: if isinstance(code, SourceCode): pyc = code.compiled else: pyc = compile(code, filename, 'exec') except SourceCodeError as e: reraise(e, RexError) except: stack = traceback.format_exc() raise RexError("Failed to compile %s:\n\n%s" % (filename, stack)) exc_type = Exception if config.catch_rex_errors else _NeverError # execute if exec_namespace is not None: try: if isinstance(code, SourceCode): code.exec_(globals_=exec_namespace) else: exec(pyc, exec_namespace) except RexError: raise except SourceCodeError as e: reraise(e, RexError) except exc_type: stack = traceback.format_exc() raise RexError("Failed to exec %s:\n\n%s" % (filename, stack)) return pyc
[ "def", "compile_code", "(", "cls", ",", "code", ",", "filename", "=", "None", ",", "exec_namespace", "=", "None", ")", ":", "if", "filename", "is", "None", ":", "if", "isinstance", "(", "code", ",", "SourceCode", ")", ":", "filename", "=", "code", ".",...
https://github.com/nerdvegas/rez/blob/d392c65bf63b4bca8106f938cec49144ba54e770/src/rez/rex.py#L1316-L1364
seopbo/nlp_classification
21ea6e3f5737e7074bdd8dd190e5f5172f86f6bf
Efficient_Character-level_Document_Classification_by_Combining_Convolution_and_Recurrent_Layers/model/data.py
python
batchify
(data: List[Tuple[torch.Tensor, torch.Tensor]])
return indices, labels
custom collate_fn for DataLoader Args: data (list): list of torch.Tensors Returns: data (tuple): tuple of torch.Tensors
custom collate_fn for DataLoader
[ "custom", "collate_fn", "for", "DataLoader" ]
def batchify(data: List[Tuple[torch.Tensor, torch.Tensor]]) -> Tuple[torch.Tensor, torch.Tensor]: """custom collate_fn for DataLoader Args: data (list): list of torch.Tensors Returns: data (tuple): tuple of torch.Tensors """ indices, labels = zip(*data) indices = pad_sequence(indices, batch_first=True, padding_value=1) labels = torch.stack(labels, 0) return indices, labels
[ "def", "batchify", "(", "data", ":", "List", "[", "Tuple", "[", "torch", ".", "Tensor", ",", "torch", ".", "Tensor", "]", "]", ")", "->", "Tuple", "[", "torch", ".", "Tensor", ",", "torch", ".", "Tensor", "]", ":", "indices", ",", "labels", "=", ...
https://github.com/seopbo/nlp_classification/blob/21ea6e3f5737e7074bdd8dd190e5f5172f86f6bf/Efficient_Character-level_Document_Classification_by_Combining_Convolution_and_Recurrent_Layers/model/data.py#L38-L50
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-1.4/django/views/csrf.py
python
csrf_failure
(request, reason="")
return HttpResponseForbidden(t.render(c), mimetype='text/html')
Default view used when request fails CSRF protection
Default view used when request fails CSRF protection
[ "Default", "view", "used", "when", "request", "fails", "CSRF", "protection" ]
def csrf_failure(request, reason=""): """ Default view used when request fails CSRF protection """ from django.middleware.csrf import REASON_NO_REFERER t = Template(CSRF_FAILURE_TEMPLATE) c = Context({'DEBUG': settings.DEBUG, 'reason': reason, 'no_referer': reason == REASON_NO_REFERER }) return HttpResponseForbidden(t.render(c), mimetype='text/html')
[ "def", "csrf_failure", "(", "request", ",", "reason", "=", "\"\"", ")", ":", "from", "django", ".", "middleware", ".", "csrf", "import", "REASON_NO_REFERER", "t", "=", "Template", "(", "CSRF_FAILURE_TEMPLATE", ")", "c", "=", "Context", "(", "{", "'DEBUG'", ...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.4/django/views/csrf.py#L94-L104
cjdrake/pyeda
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
pyeda/parsing/dimacs.py
python
parse_cnf
(s, varname='x')
return ast
Parse an input string in DIMACS CNF format, and return an expression abstract syntax tree. Parameters ---------- s : str String containing a DIMACS CNF. varname : str, optional The variable name used for creating literals. Defaults to 'x'. Returns ------- An ast tuple, defined recursively: ast := ('var', names, indices) | ('not', ast) | ('or', ast, ...) | ('and', ast, ...) names := (name, ...) indices := (index, ...)
Parse an input string in DIMACS CNF format, and return an expression abstract syntax tree.
[ "Parse", "an", "input", "string", "in", "DIMACS", "CNF", "format", "and", "return", "an", "expression", "abstract", "syntax", "tree", "." ]
def parse_cnf(s, varname='x'): """ Parse an input string in DIMACS CNF format, and return an expression abstract syntax tree. Parameters ---------- s : str String containing a DIMACS CNF. varname : str, optional The variable name used for creating literals. Defaults to 'x'. Returns ------- An ast tuple, defined recursively: ast := ('var', names, indices) | ('not', ast) | ('or', ast, ...) | ('and', ast, ...) names := (name, ...) indices := (index, ...) """ lexer = iter(CNFLexer(s)) try: ast = _cnf(lexer, varname) except lex.RunError as exc: fstr = ("{0.args[0]}: " "(line: {0.lineno}, offset: {0.offset}, text: {0.text})") raise Error(fstr.format(exc)) # Check for end of buffer _expect_token(lexer, {EndToken}) return ast
[ "def", "parse_cnf", "(", "s", ",", "varname", "=", "'x'", ")", ":", "lexer", "=", "iter", "(", "CNFLexer", "(", "s", ")", ")", "try", ":", "ast", "=", "_cnf", "(", "lexer", ",", "varname", ")", "except", "lex", ".", "RunError", "as", "exc", ":", ...
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/dimacs.py#L143-L181
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/urllib/request.py
python
HTTPPasswordMgr.reduce_uri
(self, uri, default_port=True)
return authority, path
Accept authority or URI and extract only the authority and path.
Accept authority or URI and extract only the authority and path.
[ "Accept", "authority", "or", "URI", "and", "extract", "only", "the", "authority", "and", "path", "." ]
def reduce_uri(self, uri, default_port=True): """Accept authority or URI and extract only the authority and path.""" # note HTTP URLs do not have a userinfo component parts = urlsplit(uri) if parts[1]: # URI scheme = parts[0] authority = parts[1] path = parts[2] or '/' else: # host or host:port scheme = None authority = uri path = '/' host, port = splitport(authority) if default_port and port is None and scheme is not None: dport = {"http": 80, "https": 443, }.get(scheme) if dport is not None: authority = "%s:%d" % (host, dport) return authority, path
[ "def", "reduce_uri", "(", "self", ",", "uri", ",", "default_port", "=", "True", ")", ":", "# note HTTP URLs do not have a userinfo component", "parts", "=", "urlsplit", "(", "uri", ")", "if", "parts", "[", "1", "]", ":", "# URI", "scheme", "=", "parts", "[",...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/urllib/request.py#L861-L882
NVlabs/noise2noise
7355519e7bfc49e0606cca8867748e736431244b
dnnlib/tflib/autosummary.py
python
autosummary
(name: str, value: TfExpressionEx)
Create a new autosummary.
Create a new autosummary.
[ "Create", "a", "new", "autosummary", "." ]
def autosummary(name: str, value: TfExpressionEx) -> TfExpressionEx: """Create a new autosummary.""" tfutil.assert_tf_initialized() name_id = name.replace("/", "_") if tfutil.is_tf_expression(value): with tf.name_scope("summary_" + name_id), tf.device(value.device): update_op = _create_var(name, value) with tf.control_dependencies([update_op]): return tf.identity(value) else: # python scalar or numpy array if name not in _immediate: with tfutil.absolute_name_scope("Autosummary/" + name_id), tf.device(None), tf.control_dependencies(None): update_value = tf.placeholder(_dtype) update_op = _create_var(name, update_value) _immediate[name] = update_op, update_value update_op, update_value = _immediate[name] tfutil.run(update_op, {update_value: value}) return value
[ "def", "autosummary", "(", "name", ":", "str", ",", "value", ":", "TfExpressionEx", ")", "->", "TfExpressionEx", ":", "tfutil", ".", "assert_tf_initialized", "(", ")", "name_id", "=", "name", ".", "replace", "(", "\"/\"", ",", "\"_\"", ")", "if", "tfutil",...
https://github.com/NVlabs/noise2noise/blob/7355519e7bfc49e0606cca8867748e736431244b/dnnlib/tflib/autosummary.py#L74-L94
awesto/django-shop
13d9a77aff7eede74a5f363c1d540e005d88dbcd
shop/templatetags/shop_tags.py
python
from_iso8601
(value)
[]
def from_iso8601(value): try: return datetime.strptime(value, "%Y-%m-%dT%H:%M:%S.%fZ") except ValueError: return datetime.strptime(value, "%Y-%m-%dT%H:%M:%SZ")
[ "def", "from_iso8601", "(", "value", ")", ":", "try", ":", "return", "datetime", ".", "strptime", "(", "value", ",", "\"%Y-%m-%dT%H:%M:%S.%fZ\"", ")", "except", "ValueError", ":", "return", "datetime", ".", "strptime", "(", "value", ",", "\"%Y-%m-%dT%H:%M:%SZ\""...
https://github.com/awesto/django-shop/blob/13d9a77aff7eede74a5f363c1d540e005d88dbcd/shop/templatetags/shop_tags.py#L65-L69
uqfoundation/mystic
154e6302d1f2f94e8f13e88ecc5f24241cc28ac7
mystic/math/legacydata.py
python
lipschitzcone.contains
(self, point)
return abs(y - G) <= self.distance(point)
return True if a given point is within the cone
return True if a given point is within the cone
[ "return", "True", "if", "a", "given", "point", "is", "within", "the", "cone" ]
def contains(self, point): """ return True if a given point is within the cone """ L = self.slopes if any([i == NULLSLOPE for i in L]): return True x = point.position Z = self.vertex.position if all([x[i] == Z[i] for i in range(len(x))]): return True y = point.value G = self.vertex.value return abs(y - G) <= self.distance(point)
[ "def", "contains", "(", "self", ",", "point", ")", ":", "L", "=", "self", ".", "slopes", "if", "any", "(", "[", "i", "==", "NULLSLOPE", "for", "i", "in", "L", "]", ")", ":", "return", "True", "x", "=", "point", ".", "position", "Z", "=", "self"...
https://github.com/uqfoundation/mystic/blob/154e6302d1f2f94e8f13e88ecc5f24241cc28ac7/mystic/math/legacydata.py#L60-L69
wistbean/learn_python3_spider
73c873f4845f4385f097e5057407d03dd37a117b
stackoverflow/venv/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/distlib/database.py
python
_Cache.add
(self, dist)
Add a distribution to the cache. :param dist: The distribution to add.
Add a distribution to the cache. :param dist: The distribution to add.
[ "Add", "a", "distribution", "to", "the", "cache", ".", ":", "param", "dist", ":", "The", "distribution", "to", "add", "." ]
def add(self, dist): """ Add a distribution to the cache. :param dist: The distribution to add. """ if dist.path not in self.path: self.path[dist.path] = dist self.name.setdefault(dist.key, []).append(dist)
[ "def", "add", "(", "self", ",", "dist", ")", ":", "if", "dist", ".", "path", "not", "in", "self", ".", "path", ":", "self", ".", "path", "[", "dist", ".", "path", "]", "=", "dist", "self", ".", "name", ".", "setdefault", "(", "dist", ".", "key"...
https://github.com/wistbean/learn_python3_spider/blob/73c873f4845f4385f097e5057407d03dd37a117b/stackoverflow/venv/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/distlib/database.py#L65-L72
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/tbm/v20180129/tbm_client.py
python
TbmClient.DescribeBrandMediaReport
(self, request)
监测品牌关键词出现在媒体网站(新闻媒体、网络门户、政府网站、微信公众号、天天快报等)发布资讯标题和正文中的报道数。按天输出结果。 :param request: Request instance for DescribeBrandMediaReport. :type request: :class:`tencentcloud.tbm.v20180129.models.DescribeBrandMediaReportRequest` :rtype: :class:`tencentcloud.tbm.v20180129.models.DescribeBrandMediaReportResponse`
监测品牌关键词出现在媒体网站(新闻媒体、网络门户、政府网站、微信公众号、天天快报等)发布资讯标题和正文中的报道数。按天输出结果。
[ "监测品牌关键词出现在媒体网站(新闻媒体、网络门户、政府网站、微信公众号、天天快报等)发布资讯标题和正文中的报道数。按天输出结果。" ]
def DescribeBrandMediaReport(self, request): """监测品牌关键词出现在媒体网站(新闻媒体、网络门户、政府网站、微信公众号、天天快报等)发布资讯标题和正文中的报道数。按天输出结果。 :param request: Request instance for DescribeBrandMediaReport. :type request: :class:`tencentcloud.tbm.v20180129.models.DescribeBrandMediaReportRequest` :rtype: :class:`tencentcloud.tbm.v20180129.models.DescribeBrandMediaReportResponse` """ try: params = request._serialize() body = self.call("DescribeBrandMediaReport", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeBrandMediaReportResponse() 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", "DescribeBrandMediaReport", "(", "self", ",", "request", ")", ":", "try", ":", "params", "=", "request", ".", "_serialize", "(", ")", "body", "=", "self", ".", "call", "(", "\"DescribeBrandMediaReport\"", ",", "params", ")", "response", "=", "json", ...
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/tbm/v20180129/tbm_client.py#L85-L110
stevearc/flywheel
ac6eea314f6d88b593cf809336d8723df0b78f6f
flywheel/models.py
python
Model.cached_
(self, name, default=None)
return field.get_cached_value(self)
Get the cached (server) value of a field
Get the cached (server) value of a field
[ "Get", "the", "cached", "(", "server", ")", "value", "of", "a", "field" ]
def cached_(self, name, default=None): """ Get the cached (server) value of a field """ if not self.persisted_: return default if name in self.__cache__: return self.__cache__[name] field = self.meta_.fields.get(name) # Need this redirection for Composite fields return field.get_cached_value(self)
[ "def", "cached_", "(", "self", ",", "name", ",", "default", "=", "None", ")", ":", "if", "not", "self", ".", "persisted_", ":", "return", "default", "if", "name", "in", "self", ".", "__cache__", ":", "return", "self", ".", "__cache__", "[", "name", "...
https://github.com/stevearc/flywheel/blob/ac6eea314f6d88b593cf809336d8723df0b78f6f/flywheel/models.py#L304-L312
pyparallel/pyparallel
11e8c6072d48c8f13641925d17b147bf36ee0ba3
Lib/site-packages/pip-7.1.2-py3.3.egg/pip/download.py
python
get_file_content
(url, comes_from=None, session=None)
return url, content
Gets the content of a file; it may be a filename, file: URL, or http: URL. Returns (location, content). Content is unicode.
Gets the content of a file; it may be a filename, file: URL, or http: URL. Returns (location, content). Content is unicode.
[ "Gets", "the", "content", "of", "a", "file", ";", "it", "may", "be", "a", "filename", "file", ":", "URL", "or", "http", ":", "URL", ".", "Returns", "(", "location", "content", ")", ".", "Content", "is", "unicode", "." ]
def get_file_content(url, comes_from=None, session=None): """Gets the content of a file; it may be a filename, file: URL, or http: URL. Returns (location, content). Content is unicode.""" if session is None: raise TypeError( "get_file_content() missing 1 required keyword argument: 'session'" ) match = _scheme_re.search(url) if match: scheme = match.group(1).lower() if (scheme == 'file' and comes_from and comes_from.startswith('http')): raise InstallationError( 'Requirements file %s references URL %s, which is local' % (comes_from, url)) if scheme == 'file': path = url.split(':', 1)[1] path = path.replace('\\', '/') match = _url_slash_drive_re.match(path) if match: path = match.group(1) + ':' + path.split('|', 1)[1] path = urllib_parse.unquote(path) if path.startswith('/'): path = '/' + path.lstrip('/') url = path else: # FIXME: catch some errors resp = session.get(url) resp.raise_for_status() if six.PY3: return resp.url, resp.text else: return resp.url, resp.content try: with open(url) as f: content = f.read() except IOError as exc: raise InstallationError( 'Could not open requirements file: %s' % str(exc) ) return url, content
[ "def", "get_file_content", "(", "url", ",", "comes_from", "=", "None", ",", "session", "=", "None", ")", ":", "if", "session", "is", "None", ":", "raise", "TypeError", "(", "\"get_file_content() missing 1 required keyword argument: 'session'\"", ")", "match", "=", ...
https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/site-packages/pip-7.1.2-py3.3.egg/pip/download.py#L376-L418
exaile/exaile
a7b58996c5c15b3aa7b9975ac13ee8f784ef4689
xlgui/widgets/dialogs.py
python
error
(parent, message=None, markup=None)
Shows an error dialog
Shows an error dialog
[ "Shows", "an", "error", "dialog" ]
def error(parent, message=None, markup=None): """ Shows an error dialog """ if message is markup is None: raise ValueError("message or markup must be specified") dialog = Gtk.MessageDialog( buttons=Gtk.ButtonsType.CLOSE, message_type=Gtk.MessageType.ERROR, modal=True, transient_for=parent, ) if markup is None: dialog.props.text = message else: dialog.set_markup(markup) dialog.run() dialog.destroy()
[ "def", "error", "(", "parent", ",", "message", "=", "None", ",", "markup", "=", "None", ")", ":", "if", "message", "is", "markup", "is", "None", ":", "raise", "ValueError", "(", "\"message or markup must be specified\"", ")", "dialog", "=", "Gtk", ".", "Me...
https://github.com/exaile/exaile/blob/a7b58996c5c15b3aa7b9975ac13ee8f784ef4689/xlgui/widgets/dialogs.py#L54-L71
twilio/twilio-python
6e1e811ea57a1edfadd5161ace87397c563f6915
twilio/rest/video/v1/composition_hook.py
python
CompositionHookInstance.trim
(self)
return self._properties['trim']
:returns: Whether intervals with no media are clipped :rtype: bool
:returns: Whether intervals with no media are clipped :rtype: bool
[ ":", "returns", ":", "Whether", "intervals", "with", "no", "media", "are", "clipped", ":", "rtype", ":", "bool" ]
def trim(self): """ :returns: Whether intervals with no media are clipped :rtype: bool """ return self._properties['trim']
[ "def", "trim", "(", "self", ")", ":", "return", "self", ".", "_properties", "[", "'trim'", "]" ]
https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/video/v1/composition_hook.py#L479-L484
plasma-umass/scalene
e5d1c4d8cac49d0caa43e1a2c3898a3720071913
scalene/leak_analysis.py
python
zlog
(x: float)
Redefine log so that if x is <= 0, log x is 0.
Redefine log so that if x is <= 0, log x is 0.
[ "Redefine", "log", "so", "that", "if", "x", "is", "<", "=", "0", "log", "x", "is", "0", "." ]
def zlog(x: float) -> float: """Redefine log so that if x is <= 0, log x is 0.""" if x <= 0: return 0 else: return math.log(x)
[ "def", "zlog", "(", "x", ":", "float", ")", "->", "float", ":", "if", "x", "<=", "0", ":", "return", "0", "else", ":", "return", "math", ".", "log", "(", "x", ")" ]
https://github.com/plasma-umass/scalene/blob/e5d1c4d8cac49d0caa43e1a2c3898a3720071913/scalene/leak_analysis.py#L10-L15
vispy/vispy
26256fdc2574259dd227022fbce0767cae4e244b
vispy/gloo/glir.py
python
GlirProgram._get_active_attributes_and_uniforms
(self)
return set([v[0] for v in attributes] + [v[0] for v in uniforms])
Retrieve active attributes and uniforms to be able to check that all uniforms/attributes are set by the user. Other GLIR implementations may omit this.
Retrieve active attributes and uniforms to be able to check that all uniforms/attributes are set by the user. Other GLIR implementations may omit this.
[ "Retrieve", "active", "attributes", "and", "uniforms", "to", "be", "able", "to", "check", "that", "all", "uniforms", "/", "attributes", "are", "set", "by", "the", "user", ".", "Other", "GLIR", "implementations", "may", "omit", "this", "." ]
def _get_active_attributes_and_uniforms(self): """Retrieve active attributes and uniforms to be able to check that all uniforms/attributes are set by the user. Other GLIR implementations may omit this. """ # This match a name of the form "name[size]" (= array) regex = re.compile(r"""(?P<name>\w+)\s*(\[(?P<size>\d+)\])\s*""") # Get how many active attributes and uniforms there are cu = gl.glGetProgramParameter(self._handle, gl.GL_ACTIVE_UNIFORMS) ca = gl.glGetProgramParameter(self.handle, gl.GL_ACTIVE_ATTRIBUTES) # Get info on each one attributes = [] uniforms = [] for container, count, func in [(attributes, ca, gl.glGetActiveAttrib), (uniforms, cu, gl.glGetActiveUniform)]: for i in range(count): name, size, gtype = func(self._handle, i) m = regex.match(name) # Check if xxx[0] instead of xx if m: name = m.group('name') for i in range(size): container.append(('%s[%d]' % (name, i), gtype)) else: container.append((name, gtype)) # return attributes, uniforms return set([v[0] for v in attributes] + [v[0] for v in uniforms])
[ "def", "_get_active_attributes_and_uniforms", "(", "self", ")", ":", "# This match a name of the form \"name[size]\" (= array)", "regex", "=", "re", ".", "compile", "(", "r\"\"\"(?P<name>\\w+)\\s*(\\[(?P<size>\\d+)\\])\\s*\"\"\"", ")", "# Get how many active attributes and uniforms the...
https://github.com/vispy/vispy/blob/26256fdc2574259dd227022fbce0767cae4e244b/vispy/gloo/glir.py#L1124-L1149
fonttools/fonttools
892322aaff6a89bea5927379ec06bc0da3dfb7df
Lib/fontTools/varLib/instancer/names.py
python
_updateNameTableStyleRecords
( varfont, familyNameSuffix, subFamilyName, typoSubFamilyName, platformID=3, platEncID=1, langID=0x409, )
[]
def _updateNameTableStyleRecords( varfont, familyNameSuffix, subFamilyName, typoSubFamilyName, platformID=3, platEncID=1, langID=0x409, ): # TODO (Marc F) It may be nice to make this part a standalone # font renamer in the future. nametable = varfont["name"] platform = (platformID, platEncID, langID) currentFamilyName = nametable.getName( NameID.TYPOGRAPHIC_FAMILY_NAME, *platform ) or nametable.getName(NameID.FAMILY_NAME, *platform) currentStyleName = nametable.getName( NameID.TYPOGRAPHIC_SUBFAMILY_NAME, *platform ) or nametable.getName(NameID.SUBFAMILY_NAME, *platform) if not all([currentFamilyName, currentStyleName]): raise ValueError(f"Missing required NameIDs 1 and 2 for platform {platform}") currentFamilyName = currentFamilyName.toUnicode() currentStyleName = currentStyleName.toUnicode() nameIDs = { NameID.FAMILY_NAME: currentFamilyName, NameID.SUBFAMILY_NAME: subFamilyName or "Regular", } if typoSubFamilyName: nameIDs[NameID.FAMILY_NAME] = f"{currentFamilyName} {familyNameSuffix}".strip() nameIDs[NameID.TYPOGRAPHIC_FAMILY_NAME] = currentFamilyName nameIDs[NameID.TYPOGRAPHIC_SUBFAMILY_NAME] = typoSubFamilyName else: # Remove previous Typographic Family and SubFamily names since they're # no longer required for nameID in ( NameID.TYPOGRAPHIC_FAMILY_NAME, NameID.TYPOGRAPHIC_SUBFAMILY_NAME, ): nametable.removeNames(nameID=nameID) newFamilyName = ( nameIDs.get(NameID.TYPOGRAPHIC_FAMILY_NAME) or nameIDs[NameID.FAMILY_NAME] ) newStyleName = ( nameIDs.get(NameID.TYPOGRAPHIC_SUBFAMILY_NAME) or nameIDs[NameID.SUBFAMILY_NAME] ) nameIDs[NameID.FULL_FONT_NAME] = f"{newFamilyName} {newStyleName}" nameIDs[NameID.POSTSCRIPT_NAME] = _updatePSNameRecord( varfont, newFamilyName, newStyleName, platform ) uniqueID = _updateUniqueIdNameRecord(varfont, nameIDs, platform) if uniqueID: nameIDs[NameID.UNIQUE_FONT_IDENTIFIER] = uniqueID for nameID, string in nameIDs.items(): assert string, nameID nametable.setName(string, nameID, *platform) if "fvar" not in varfont: nametable.removeNames(NameID.VARIATIONS_POSTSCRIPT_NAME_PREFIX)
[ "def", "_updateNameTableStyleRecords", "(", "varfont", ",", "familyNameSuffix", ",", "subFamilyName", ",", "typoSubFamilyName", ",", "platformID", "=", "3", ",", "platEncID", "=", "1", ",", "langID", "=", "0x409", ",", ")", ":", "# TODO (Marc F) It may be nice to ma...
https://github.com/fonttools/fonttools/blob/892322aaff6a89bea5927379ec06bc0da3dfb7df/Lib/fontTools/varLib/instancer/names.py#L252-L318
FederatedAI/FATE
32540492623568ecd1afcb367360133616e02fa3
python/fate_arch/storage/_table.py
python
StorageTableMeta.get_engine
(self)
return self.engine
[]
def get_engine(self): return self.engine
[ "def", "get_engine", "(", "self", ")", ":", "return", "self", ".", "engine" ]
https://github.com/FederatedAI/FATE/blob/32540492623568ecd1afcb367360133616e02fa3/python/fate_arch/storage/_table.py#L352-L353
DataDog/integrations-core
934674b29d94b70ccc008f76ea172d0cdae05e1e
mesos_master/datadog_checks/mesos_master/config_models/defaults.py
python
instance_kerberos_hostname
(field, value)
return get_default_field_value(field, value)
[]
def instance_kerberos_hostname(field, value): return get_default_field_value(field, value)
[ "def", "instance_kerberos_hostname", "(", "field", ",", "value", ")", ":", "return", "get_default_field_value", "(", "field", ",", "value", ")" ]
https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/mesos_master/datadog_checks/mesos_master/config_models/defaults.py#L89-L90
ldx/python-iptables
542efdb739b4e3ef6f28274d23b506bf0027eec2
iptc/xtables.py
python
xtables._fcheck_match_old
(self, match)
[]
def _fcheck_match_old(self, match): # old API if not match.final_check: return rv = _wrap_uintfn(match.final_check, match.mflags) if rv: raise XTablesError("%s.final_check() has failed" % (match.name))
[ "def", "_fcheck_match_old", "(", "self", ",", "match", ")", ":", "# old API", "if", "not", "match", ".", "final_check", ":", "return", "rv", "=", "_wrap_uintfn", "(", "match", ".", "final_check", ",", "match", ".", "mflags", ")", "if", "rv", ":", "raise"...
https://github.com/ldx/python-iptables/blob/542efdb739b4e3ef6f28274d23b506bf0027eec2/iptc/xtables.py#L1222-L1229
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/requests/utils.py
python
urldefragauth
(url)
return urlunparse((scheme, netloc, path, params, query, ''))
Given a url remove the fragment and the authentication part. :rtype: str
Given a url remove the fragment and the authentication part.
[ "Given", "a", "url", "remove", "the", "fragment", "and", "the", "authentication", "part", "." ]
def urldefragauth(url): """ Given a url remove the fragment and the authentication part. :rtype: str """ scheme, netloc, path, params, query, fragment = urlparse(url) # see func:`prepend_scheme_if_needed` if not netloc: netloc, path = path, netloc netloc = netloc.rsplit('@', 1)[-1] return urlunparse((scheme, netloc, path, params, query, ''))
[ "def", "urldefragauth", "(", "url", ")", ":", "scheme", ",", "netloc", ",", "path", ",", "params", ",", "query", ",", "fragment", "=", "urlparse", "(", "url", ")", "# see func:`prepend_scheme_if_needed`", "if", "not", "netloc", ":", "netloc", ",", "path", ...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/requests/utils.py#L948-L962
dingjiansw101/AerialDetection
fbb7726bc0c6898fc00e50a418a3f5e0838b30d4
DOTA_devkit/ImgSplit_multi_process.py
python
splitbase.__init__
(self, basepath, outpath, code = 'utf-8', gap=512, subsize=1024, thresh=0.7, choosebestpoint=True, ext = '.png', padding=True, num_process=8 )
:param basepath: base path for dota data :param outpath: output base path for dota data, the basepath and outputpath have the similar subdirectory, 'images' and 'labelTxt' :param code: encodeing format of txt file :param gap: overlap between two patches :param subsize: subsize of patch :param thresh: the thresh determine whether to keep the instance if the instance is cut down in the process of split :param choosebestpoint: used to choose the first point for the :param ext: ext for the image format :param padding: if to padding the images so that all the images have the same size
:param basepath: base path for dota data :param outpath: output base path for dota data, the basepath and outputpath have the similar subdirectory, 'images' and 'labelTxt' :param code: encodeing format of txt file :param gap: overlap between two patches :param subsize: subsize of patch :param thresh: the thresh determine whether to keep the instance if the instance is cut down in the process of split :param choosebestpoint: used to choose the first point for the :param ext: ext for the image format :param padding: if to padding the images so that all the images have the same size
[ ":", "param", "basepath", ":", "base", "path", "for", "dota", "data", ":", "param", "outpath", ":", "output", "base", "path", "for", "dota", "data", "the", "basepath", "and", "outputpath", "have", "the", "similar", "subdirectory", "images", "and", "labelTxt"...
def __init__(self, basepath, outpath, code = 'utf-8', gap=512, subsize=1024, thresh=0.7, choosebestpoint=True, ext = '.png', padding=True, num_process=8 ): """ :param basepath: base path for dota data :param outpath: output base path for dota data, the basepath and outputpath have the similar subdirectory, 'images' and 'labelTxt' :param code: encodeing format of txt file :param gap: overlap between two patches :param subsize: subsize of patch :param thresh: the thresh determine whether to keep the instance if the instance is cut down in the process of split :param choosebestpoint: used to choose the first point for the :param ext: ext for the image format :param padding: if to padding the images so that all the images have the same size """ self.basepath = basepath self.outpath = outpath self.code = code self.gap = gap self.subsize = subsize self.slide = self.subsize - self.gap self.thresh = thresh self.imagepath = os.path.join(self.basepath, 'images') self.labelpath = os.path.join(self.basepath, 'labelTxt') self.outimagepath = os.path.join(self.outpath, 'images') self.outlabelpath = os.path.join(self.outpath, 'labelTxt') self.choosebestpoint = choosebestpoint self.ext = ext self.padding = padding self.pool = Pool(num_process) print('padding:', padding) # pdb.set_trace() if not os.path.isdir(self.outpath): os.mkdir(self.outpath) if not os.path.isdir(self.outimagepath): # pdb.set_trace() os.mkdir(self.outimagepath) if not os.path.isdir(self.outlabelpath): os.mkdir(self.outlabelpath)
[ "def", "__init__", "(", "self", ",", "basepath", ",", "outpath", ",", "code", "=", "'utf-8'", ",", "gap", "=", "512", ",", "subsize", "=", "1024", ",", "thresh", "=", "0.7", ",", "choosebestpoint", "=", "True", ",", "ext", "=", "'.png'", ",", "paddin...
https://github.com/dingjiansw101/AerialDetection/blob/fbb7726bc0c6898fc00e50a418a3f5e0838b30d4/DOTA_devkit/ImgSplit_multi_process.py#L43-L91
asyml/texar
a23f021dae289a3d768dc099b220952111da04fd
texar/tf/core/layers.py
python
gelu
(input_tensor)
return input_tensor * cdf
Gaussian Error Linear Unit. This is a smoother version of the RELU. Original paper: https://arxiv.org/abs/1606.08415 Args: input_tensor: float Tensor to perform activation. Returns: `input_tensor` with the GELU activation applied.
Gaussian Error Linear Unit.
[ "Gaussian", "Error", "Linear", "Unit", "." ]
def gelu(input_tensor): """Gaussian Error Linear Unit. This is a smoother version of the RELU. Original paper: https://arxiv.org/abs/1606.08415 Args: input_tensor: float Tensor to perform activation. Returns: `input_tensor` with the GELU activation applied. """ cdf = 0.5 * (1.0 + tf.erf(input_tensor / tf.sqrt(2.0))) return input_tensor * cdf
[ "def", "gelu", "(", "input_tensor", ")", ":", "cdf", "=", "0.5", "*", "(", "1.0", "+", "tf", ".", "erf", "(", "input_tensor", "/", "tf", ".", "sqrt", "(", "2.0", ")", ")", ")", "return", "input_tensor", "*", "cdf" ]
https://github.com/asyml/texar/blob/a23f021dae289a3d768dc099b220952111da04fd/texar/tf/core/layers.py#L1250-L1263
mozilla-services/socorro
8bff4a90e9e3320eabe7e067adbe0e89f6a39ba7
bin/permadelete_crash_data.py
python
cmd_permadelete
(ctx, crashidsfile)
Permanently deletes crash report data from crash storage. The crashidsfile should be a complete path to the file with crashids in it--one per line. This will skip lines prefixed with a # treating them like comments.
Permanently deletes crash report data from crash storage.
[ "Permanently", "deletes", "crash", "report", "data", "from", "crash", "storage", "." ]
def cmd_permadelete(ctx, crashidsfile): """ Permanently deletes crash report data from crash storage. The crashidsfile should be a complete path to the file with crashids in it--one per line. This will skip lines prefixed with a # treating them like comments. """ if not os.path.exists(crashidsfile): click.echo("File %s does not exist." % crashidsfile) return 1 crashids = crashid_generator(crashidsfile) for crashid in crashids: click.echo("Working on %s" % crashid) s3_delete(crashid) es_delete(crashid) click.echo("Done!")
[ "def", "cmd_permadelete", "(", "ctx", ",", "crashidsfile", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "crashidsfile", ")", ":", "click", ".", "echo", "(", "\"File %s does not exist.\"", "%", "crashidsfile", ")", "return", "1", "crashids", ...
https://github.com/mozilla-services/socorro/blob/8bff4a90e9e3320eabe7e067adbe0e89f6a39ba7/bin/permadelete_crash_data.py#L216-L236
hbrobotics/ros_arduino_bridge
a960c8a88a6255d0104c92838045c06257c509d0
ros_arduino_python/src/ros_arduino_python/arduino_driver.py
python
Arduino.reset_encoders
(self)
return self.execute_ack('r')
Reset the encoder counts to 0
Reset the encoder counts to 0
[ "Reset", "the", "encoder", "counts", "to", "0" ]
def reset_encoders(self): ''' Reset the encoder counts to 0 ''' return self.execute_ack('r')
[ "def", "reset_encoders", "(", "self", ")", ":", "return", "self", ".", "execute_ack", "(", "'r'", ")" ]
https://github.com/hbrobotics/ros_arduino_bridge/blob/a960c8a88a6255d0104c92838045c06257c509d0/ros_arduino_python/src/ros_arduino_python/arduino_driver.py#L277-L280
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/iotexplorer/v20190423/models.py
python
GetFamilyDeviceUserListResponse.__init__
(self)
r""" :param UserList: 设备的用户列表 注意:此字段可能返回 null,表示取不到有效值。 :type UserList: list of DeviceUser :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str
r""" :param UserList: 设备的用户列表 注意:此字段可能返回 null,表示取不到有效值。 :type UserList: list of DeviceUser :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str
[ "r", ":", "param", "UserList", ":", "设备的用户列表", "注意:此字段可能返回", "null,表示取不到有效值。", ":", "type", "UserList", ":", "list", "of", "DeviceUser", ":", "param", "RequestId", ":", "唯一请求", "ID,每次请求都会返回。定位问题时需要提供该次请求的", "RequestId。", ":", "type", "RequestId", ":", "str" ]
def __init__(self): r""" :param UserList: 设备的用户列表 注意:此字段可能返回 null,表示取不到有效值。 :type UserList: list of DeviceUser :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.UserList = None self.RequestId = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "UserList", "=", "None", "self", ".", "RequestId", "=", "None" ]
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/iotexplorer/v20190423/models.py#L3571-L3580
DamnWidget/anaconda
a9998fb362320f907d5ccbc6fcf5b62baca677c0
anaconda_lib/linting/pycodestyle.py
python
normalize_paths
(value, parent=os.curdir)
return paths
Parse a comma-separated list of paths. Return a list of absolute paths.
Parse a comma-separated list of paths.
[ "Parse", "a", "comma", "-", "separated", "list", "of", "paths", "." ]
def normalize_paths(value, parent=os.curdir): """Parse a comma-separated list of paths. Return a list of absolute paths. """ if not value: return [] if isinstance(value, list): return value paths = [] for path in value.split(','): path = path.strip() if '/' in path: path = os.path.abspath(os.path.join(parent, path)) paths.append(path.rstrip('/')) return paths
[ "def", "normalize_paths", "(", "value", ",", "parent", "=", "os", ".", "curdir", ")", ":", "if", "not", "value", ":", "return", "[", "]", "if", "isinstance", "(", "value", ",", "list", ")", ":", "return", "value", "paths", "=", "[", "]", "for", "pa...
https://github.com/DamnWidget/anaconda/blob/a9998fb362320f907d5ccbc6fcf5b62baca677c0/anaconda_lib/linting/pycodestyle.py#L1872-L1887
HunterMcGushion/hyperparameter_hunter
28b1d48e01a993818510811b82a677e0a7a232b2
hyperparameter_hunter/experiments.py
python
BaseExperiment._empty_output_like
(self, like: pd.DataFrame, index=None, target_column=None)
return pd.DataFrame(0, index=index, columns=target_column)
Make an empty DataFrame of the same shape and with the same index as `like`, intended for use with output :mod:`~hyperparameter_hunter.data.data_chunks`, like descendants of :class:`~hyperparameter_hunter.data.data_chunks.prediction_chunks.BasePredictionChunk` and :class:`~hyperparameter_hunter.data.data_chunks.target_chunks.BaseTargetChunk` Parameters ---------- like: pd.DataFrame DataFrame to use as the basis for the shape and index of the returned DataFrame. `like` has no bearing on the column names of the returned DataFrame index: Array-like, or None, default=None If None, defaults to `like.index`. Else, defines the index of the returned DataFrame target_column: List[str], or None, default=None If None, defaults to the experiment's :attr:`target_column`. Else, defines the column names of the returned DataFrame Returns ------- pd.DataFrame Zero-filled DataFrame with index of `index` or `like.index` and column names of `target_column` or :attr:`target_column`
Make an empty DataFrame of the same shape and with the same index as `like`, intended for use with output :mod:`~hyperparameter_hunter.data.data_chunks`, like descendants of :class:`~hyperparameter_hunter.data.data_chunks.prediction_chunks.BasePredictionChunk` and :class:`~hyperparameter_hunter.data.data_chunks.target_chunks.BaseTargetChunk`
[ "Make", "an", "empty", "DataFrame", "of", "the", "same", "shape", "and", "with", "the", "same", "index", "as", "like", "intended", "for", "use", "with", "output", ":", "mod", ":", "~hyperparameter_hunter", ".", "data", ".", "data_chunks", "like", "descendant...
def _empty_output_like(self, like: pd.DataFrame, index=None, target_column=None): """Make an empty DataFrame of the same shape and with the same index as `like`, intended for use with output :mod:`~hyperparameter_hunter.data.data_chunks`, like descendants of :class:`~hyperparameter_hunter.data.data_chunks.prediction_chunks.BasePredictionChunk` and :class:`~hyperparameter_hunter.data.data_chunks.target_chunks.BaseTargetChunk` Parameters ---------- like: pd.DataFrame DataFrame to use as the basis for the shape and index of the returned DataFrame. `like` has no bearing on the column names of the returned DataFrame index: Array-like, or None, default=None If None, defaults to `like.index`. Else, defines the index of the returned DataFrame target_column: List[str], or None, default=None If None, defaults to the experiment's :attr:`target_column`. Else, defines the column names of the returned DataFrame Returns ------- pd.DataFrame Zero-filled DataFrame with index of `index` or `like.index` and column names of `target_column` or :attr:`target_column`""" index = like.index.copy() if index is None else index target_column = self.target_column if target_column is None else target_column return pd.DataFrame(0, index=index, columns=target_column)
[ "def", "_empty_output_like", "(", "self", ",", "like", ":", "pd", ".", "DataFrame", ",", "index", "=", "None", ",", "target_column", "=", "None", ")", ":", "index", "=", "like", ".", "index", ".", "copy", "(", ")", "if", "index", "is", "None", "else"...
https://github.com/HunterMcGushion/hyperparameter_hunter/blob/28b1d48e01a993818510811b82a677e0a7a232b2/hyperparameter_hunter/experiments.py#L532-L556
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/sympy/sympy/geometry/line.py
python
Ray.contains
(self, o)
return False
Is other GeometryEntity contained in this Ray?
Is other GeometryEntity contained in this Ray?
[ "Is", "other", "GeometryEntity", "contained", "in", "this", "Ray?" ]
def contains(self, o): """Is other GeometryEntity contained in this Ray?""" if isinstance(o, Ray): return (Point.is_collinear(self.p1, self.p2, o.p1, o.p2) and self.xdirection == o.xdirection and self.ydirection == o.ydirection) elif isinstance(o, Segment): return o.p1 in self and o.p2 in self elif isinstance(o, Point): if Point.is_collinear(self.p1, self.p2, o): if self.xdirection is S.Infinity: rv = o.x >= self.source.x elif self.xdirection is S.NegativeInfinity: rv = o.x <= self.source.x elif self.ydirection is S.Infinity: rv = o.y >= self.source.y else: rv = o.y <= self.source.y if rv == True or rv == False: return bool(rv) raise Undecidable( 'Cannot determine if %s is in %s' % (o, self)) else: # Points are not collinear, so the rays are not parallel # and hence it is impossible for self to contain o return False # No other known entity can be contained in a Ray return False
[ "def", "contains", "(", "self", ",", "o", ")", ":", "if", "isinstance", "(", "o", ",", "Ray", ")", ":", "return", "(", "Point", ".", "is_collinear", "(", "self", ".", "p1", ",", "self", ".", "p2", ",", "o", ".", "p1", ",", "o", ".", "p2", ")"...
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/geometry/line.py#L1419-L1447
MartinThoma/algorithms
6199cfa3446e1056c7b4d75ca6e306e9e56fd95b
ML/nlp/reuters_mlp.py
python
main
(data_module)
Load data, train model and evaluate it.
Load data, train model and evaluate it.
[ "Load", "data", "train", "model", "and", "evaluate", "it", "." ]
def main(data_module): """Load data, train model and evaluate it.""" data = data_module.load_data() model = create_model(data_module.n_classes, (data['x_train'].shape[1], )) print(model.summary()) optimizer = get_optimizer({'optimizer': {'initial_lr': 0.001}}) model.compile(loss='binary_crossentropy', optimizer=optimizer, metrics=[precision, recall, f1, accuracy]) t0 = time.time() model.fit(data['x_train'], data['y_train'], batch_size=32, epochs=30, validation_data=(data['x_test'], data['y_test']), shuffle=True, # callbacks=callbacks ) t1 = time.time() # res = get_tptnfpfn(model, data) preds = model.predict(data['x_test']) preds[preds >= 0.5] = 1 preds[preds < 0.5] = 0 t2 = time.time() print(("{clf_name:<30}: {acc:0.2f}% {f1:0.2f}% in {train_time:0.2f}s " "train / {test_time:0.2f}s test") .format(clf_name="MLP", acc=(accuracy_score(y_true=data['y_test'], y_pred=preds) * 100), f1=(fbeta_score(y_true=data['y_test'], y_pred=preds, beta=1, average="weighted") * 100), train_time=(t1 - t0), test_time=(t2 - t1)))
[ "def", "main", "(", "data_module", ")", ":", "data", "=", "data_module", ".", "load_data", "(", ")", "model", "=", "create_model", "(", "data_module", ".", "n_classes", ",", "(", "data", "[", "'x_train'", "]", ".", "shape", "[", "1", "]", ",", ")", "...
https://github.com/MartinThoma/algorithms/blob/6199cfa3446e1056c7b4d75ca6e306e9e56fd95b/ML/nlp/reuters_mlp.py#L82-L111
theislab/scvelo
1805ab4a72d3f34496f0ef246500a159f619d3a2
scvelo/tools/rank_velocity_genes.py
python
velocity_clusters
( data, vkey="velocity", match_with="clusters", sort_by="velocity_pseudotime", resolution=None, min_likelihood=None, copy=False, )
return adata if copy else None
Computes velocity clusters via louvain on velocities. .. code:: python scv.tl.velocity_clusters(adata) scv.pl.scatter(adata, color='velocity_clusters') .. image:: https://user-images.githubusercontent.com/31883718/69625627-484dc480-1047-11ea-847f-6607a3430427.png :width: 600px Arguments ---------- data : :class:`~anndata.AnnData` Annotated data matrix. vkey: `str` (default: `'velocity'`) Key of velocities computed in `tl.velocity` match_with : `int`, optional (default: 100) The number of genes that appear in the returned tables. match_with: `str` (default: `'clusters'`) Match the names of the velocity clusters with the names of this key (.obs). sort_by: `str` or `None` (default: `'dpt_pseudotime'`) Sort velocity clusters by this key (.obs). resolution: `float` (default: 0.7) Resolution for louvain modularity. min_likelihood: `float` between `0` and `1` or `None` (default: `None`) Only rank velocity of genes with a likelihood higher than min_likelihood. copy: `bool` (default: `False`) Return a copy instead of writing to data. Returns ------- velocity_clusters : `.obs` Clusters obtained from applying louvain modularity on velocity expression.
Computes velocity clusters via louvain on velocities.
[ "Computes", "velocity", "clusters", "via", "louvain", "on", "velocities", "." ]
def velocity_clusters( data, vkey="velocity", match_with="clusters", sort_by="velocity_pseudotime", resolution=None, min_likelihood=None, copy=False, ): """Computes velocity clusters via louvain on velocities. .. code:: python scv.tl.velocity_clusters(adata) scv.pl.scatter(adata, color='velocity_clusters') .. image:: https://user-images.githubusercontent.com/31883718/69625627-484dc480-1047-11ea-847f-6607a3430427.png :width: 600px Arguments ---------- data : :class:`~anndata.AnnData` Annotated data matrix. vkey: `str` (default: `'velocity'`) Key of velocities computed in `tl.velocity` match_with : `int`, optional (default: 100) The number of genes that appear in the returned tables. match_with: `str` (default: `'clusters'`) Match the names of the velocity clusters with the names of this key (.obs). sort_by: `str` or `None` (default: `'dpt_pseudotime'`) Sort velocity clusters by this key (.obs). resolution: `float` (default: 0.7) Resolution for louvain modularity. min_likelihood: `float` between `0` and `1` or `None` (default: `None`) Only rank velocity of genes with a likelihood higher than min_likelihood. copy: `bool` (default: `False`) Return a copy instead of writing to data. Returns ------- velocity_clusters : `.obs` Clusters obtained from applying louvain modularity on velocity expression. """ # noqa E501 adata = data.copy() if copy else data logg.info("computing velocity clusters", r=True) tmp_filter = ~np.isnan(adata.layers[vkey].sum(0)) if f"{vkey}_genes" in adata.var.keys(): tmp_filter &= np.array(adata.var[f"{vkey}_genes"].values, dtype=bool) if "unspliced" in adata.layers.keys(): n_counts = (adata.layers["unspliced"] > 0).sum(0) n_counts = n_counts.A1 if issparse(adata.layers["unspliced"]) else n_counts min_counts = min(50, np.percentile(n_counts, 50)) tmp_filter &= np.ravel(n_counts > min_counts) if "r2" in adata.var.keys(): r2 = adata.var.velocity_r2 min_r2 = np.percentile(r2[r2 > 0], 50) tmp_filter &= r2 > min_r2 if "dispersions_norm" in adata.var.keys(): dispersions = adata.var.dispersions_norm min_dispersion = np.percentile(dispersions, 20) tmp_filter &= dispersions > min_dispersion if "fit_likelihood" in adata.var.keys() and min_likelihood is not None: tmp_filter &= adata.var["fit_likelihood"] > min_likelihood from anndata import AnnData vdata = AnnData(adata.layers[vkey][:, tmp_filter]) vdata.obs = adata.obs.copy() vdata.var = adata.var[tmp_filter].copy() if "highly_variable" in vdata.var.keys(): vdata.var["highly_variable"] = np.array( vdata.var["highly_variable"], dtype=bool ) import scanpy as sc logg.switch_verbosity("off", module="scanpy") sc.pp.pca(vdata, n_comps=20, svd_solver="arpack") sc.pp.neighbors(vdata, n_pcs=20) sc.tl.louvain(vdata, resolution=0.7 if resolution is None else resolution) logg.switch_verbosity("on", module="scanpy") if sort_by == "velocity_pseudotime" and sort_by not in adata.obs.keys(): velocity_pseudotime(adata, vkey=vkey) if sort_by in vdata.obs.keys(): vc = vdata.obs["louvain"] vc_cats = vc.cat.categories mean_times = [np.mean(vdata.obs[sort_by][vc == cat]) for cat in vc_cats] vdata.obs["louvain"].cat.reorder_categories( vc_cats[np.argsort(mean_times)], inplace=True ) if isinstance(match_with, str) and match_with in adata.obs.keys(): from .utils import most_common_in_list vc = vdata.obs["louvain"] cats_nums = {cat: 0 for cat in adata.obs[match_with].cat.categories} for cat in vc.cat.categories: cells_in_cat = np.where(vc == cat)[0] new_cat = most_common_in_list(adata.obs[match_with][cells_in_cat]) cats_nums[new_cat] += 1 vc = vc.cat.rename_categories({cat: f"{new_cat} ({cats_nums[new_cat]})"}) vdata.obs["louvain"] = vc else: vdata.obs["louvain"].cat.categories = np.arange( len(vdata.obs["louvain"].cat.categories) ) adata.obs[f"{vkey}_clusters"] = vdata.obs["louvain"].copy() del vdata logg.info(" finished", time=True, end=" " if settings.verbosity > 2 else "\n") logg.hint( "added \n" f" '{vkey}_clusters', " f"clusters based on louvain modularity on velocity vector field (adata.obs)" ) return adata if copy else None
[ "def", "velocity_clusters", "(", "data", ",", "vkey", "=", "\"velocity\"", ",", "match_with", "=", "\"clusters\"", ",", "sort_by", "=", "\"velocity_pseudotime\"", ",", "resolution", "=", "None", ",", "min_likelihood", "=", "None", ",", "copy", "=", "False", ",...
https://github.com/theislab/scvelo/blob/1805ab4a72d3f34496f0ef246500a159f619d3a2/scvelo/tools/rank_velocity_genes.py#L64-L191
intel/virtual-storage-manager
00706ab9701acbd0d5e04b19cc80c6b66a2973b8
source/vsm/vsm/image/glance.py
python
GlanceImageService._is_image_available
(context, image)
return str(user_id) == str(context.user_id)
Check image availability. This check is needed in case Nova and Glance are deployed without authentication turned on.
Check image availability.
[ "Check", "image", "availability", "." ]
def _is_image_available(context, image): """Check image availability. This check is needed in case Nova and Glance are deployed without authentication turned on. """ # The presence of an auth token implies this is an authenticated # request and we need not handle the noauth use-case. if hasattr(context, 'auth_token') and context.auth_token: return True if image.is_public or context.is_admin: return True properties = image.properties if context.project_id and ('owner_id' in properties): return str(properties['owner_id']) == str(context.project_id) if context.project_id and ('project_id' in properties): return str(properties['project_id']) == str(context.project_id) try: user_id = properties['user_id'] except KeyError: return False return str(user_id) == str(context.user_id)
[ "def", "_is_image_available", "(", "context", ",", "image", ")", ":", "# The presence of an auth token implies this is an authenticated", "# request and we need not handle the noauth use-case.", "if", "hasattr", "(", "context", ",", "'auth_token'", ")", "and", "context", ".", ...
https://github.com/intel/virtual-storage-manager/blob/00706ab9701acbd0d5e04b19cc80c6b66a2973b8/source/vsm/vsm/image/glance.py#L288-L315
google/pytype
fa43edc95dd42ade6e3147d6580d63e778c9d506
pytype/tools/analyze_project/parse_args.py
python
parse_jobs
(s)
Parse the --jobs option.
Parse the --jobs option.
[ "Parse", "the", "--", "jobs", "option", "." ]
def parse_jobs(s): """Parse the --jobs option.""" if s == 'auto': n = _auto_detect_cpus() return n if n else 1 elif s is not None: return int(s) else: return None
[ "def", "parse_jobs", "(", "s", ")", ":", "if", "s", "==", "'auto'", ":", "n", "=", "_auto_detect_cpus", "(", ")", "return", "n", "if", "n", "else", "1", "elif", "s", "is", "not", "None", ":", "return", "int", "(", "s", ")", "else", ":", "return",...
https://github.com/google/pytype/blob/fa43edc95dd42ade6e3147d6580d63e778c9d506/pytype/tools/analyze_project/parse_args.py#L22-L30
huggingface/transformers
623b4f7c63f60cce917677ee704d6c93ee960b4b
src/transformers/utils/dummy_pt_objects.py
python
GPTJForCausalLM.__init__
(self, *args, **kwargs)
[]
def __init__(self, *args, **kwargs): requires_backends(self, ["torch"])
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "requires_backends", "(", "self", ",", "[", "\"torch\"", "]", ")" ]
https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/src/transformers/utils/dummy_pt_objects.py#L2522-L2523