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
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/django-auth-ldap-1.3.0/django_auth_ldap/backend.py
python
_LDAPUser._populate_user
(self)
Populates our User object with information from the LDAP directory.
Populates our User object with information from the LDAP directory.
[ "Populates", "our", "User", "object", "with", "information", "from", "the", "LDAP", "directory", "." ]
def _populate_user(self): """ Populates our User object with information from the LDAP directory. """ self._populate_user_from_attributes() self._populate_user_from_group_memberships()
[ "def", "_populate_user", "(", "self", ")", ":", "self", ".", "_populate_user_from_attributes", "(", ")", "self", ".", "_populate_user_from_group_memberships", "(", ")" ]
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/django-auth-ldap-1.3.0/django_auth_ldap/backend.py#L644-L649
django/django
0a17666045de6739ae1c2ac695041823d5f827f7
django/db/models/base.py
python
full_clean
(self, exclude=None, validate_unique=True)
Call clean_fields(), clean(), and validate_unique() on the model. Raise a ValidationError for any errors that occur.
Call clean_fields(), clean(), and validate_unique() on the model. Raise a ValidationError for any errors that occur.
[ "Call", "clean_fields", "()", "clean", "()", "and", "validate_unique", "()", "on", "the", "model", ".", "Raise", "a", "ValidationError", "for", "any", "errors", "that", "occur", "." ]
def full_clean(self, exclude=None, validate_unique=True): """ Call clean_fields(), clean(), and validate_unique() on the model. Raise a ValidationError for any errors that occur. """ errors = {} if exclude is None: exclude = [] else: exclude = list(exclude) try: self.clean_fields(exclude=exclude) except ValidationError as e: errors = e.update_error_dict(errors) # Form.clean() is run even if other validation fails, so do the # same with Model.clean() for consistency. try: self.clean() except ValidationError as e: errors = e.update_error_dict(errors) # Run unique checks, but only for fields that passed validation. if validate_unique: for name in errors: if name != NON_FIELD_ERRORS and name not in exclude: exclude.append(name) try: self.validate_unique(exclude=exclude) except ValidationError as e: errors = e.update_error_dict(errors) if errors: raise ValidationError(errors)
[ "def", "full_clean", "(", "self", ",", "exclude", "=", "None", ",", "validate_unique", "=", "True", ")", ":", "errors", "=", "{", "}", "if", "exclude", "is", "None", ":", "exclude", "=", "[", "]", "else", ":", "exclude", "=", "list", "(", "exclude", ...
https://github.com/django/django/blob/0a17666045de6739ae1c2ac695041823d5f827f7/django/db/models/base.py#L1251-L1285
boto/boto
b2a6f08122b2f1b89888d2848e730893595cd001
boto/ec2/connection.py
python
EC2Connection.trim_snapshots
(self, hourly_backups=8, daily_backups=7, weekly_backups=4, monthly_backups=True)
Trim excess snapshots, based on when they were taken. More current snapshots are retained, with the number retained decreasing as you move back in time. If ebs volumes have a 'Name' tag with a value, their snapshots will be assigned the same tag when they are created. The values of the 'Name' tags for snapshots are used by this function to group snapshots taken from the same volume (or from a series of like-named volumes over time) for trimming. For every group of like-named snapshots, this function retains the newest and oldest snapshots, as well as, by default, the first snapshots taken in each of the last eight hours, the first snapshots taken in each of the last seven days, the first snapshots taken in the last 4 weeks (counting Midnight Sunday morning as the start of the week), and the first snapshot from the first day of each month forever. :type hourly_backups: int :param hourly_backups: How many recent hourly backups should be saved. :type daily_backups: int :param daily_backups: How many recent daily backups should be saved. :type weekly_backups: int :param weekly_backups: How many recent weekly backups should be saved. :type monthly_backups: int :param monthly_backups: How many monthly backups should be saved. Use True for no limit.
Trim excess snapshots, based on when they were taken. More current snapshots are retained, with the number retained decreasing as you move back in time.
[ "Trim", "excess", "snapshots", "based", "on", "when", "they", "were", "taken", ".", "More", "current", "snapshots", "are", "retained", "with", "the", "number", "retained", "decreasing", "as", "you", "move", "back", "in", "time", "." ]
def trim_snapshots(self, hourly_backups=8, daily_backups=7, weekly_backups=4, monthly_backups=True): """ Trim excess snapshots, based on when they were taken. More current snapshots are retained, with the number retained decreasing as you move back in time. If ebs volumes have a 'Name' tag with a value, their snapshots will be assigned the same tag when they are created. The values of the 'Name' tags for snapshots are used by this function to group snapshots taken from the same volume (or from a series of like-named volumes over time) for trimming. For every group of like-named snapshots, this function retains the newest and oldest snapshots, as well as, by default, the first snapshots taken in each of the last eight hours, the first snapshots taken in each of the last seven days, the first snapshots taken in the last 4 weeks (counting Midnight Sunday morning as the start of the week), and the first snapshot from the first day of each month forever. :type hourly_backups: int :param hourly_backups: How many recent hourly backups should be saved. :type daily_backups: int :param daily_backups: How many recent daily backups should be saved. :type weekly_backups: int :param weekly_backups: How many recent weekly backups should be saved. :type monthly_backups: int :param monthly_backups: How many monthly backups should be saved. Use True for no limit. """ # This function first builds up an ordered list of target times # that snapshots should be saved for (last 8 hours, last 7 days, etc.). # Then a map of snapshots is constructed, with the keys being # the snapshot / volume names and the values being arrays of # chronologically sorted snapshots. # Finally, for each array in the map, we go through the snapshot # array and the target time array in an interleaved fashion, # deleting snapshots whose start_times don't immediately follow a # target time (we delete a snapshot if there's another snapshot # that was made closer to the preceding target time). now = datetime.utcnow() last_hour = datetime(now.year, now.month, now.day, now.hour) last_midnight = datetime(now.year, now.month, now.day) last_sunday = datetime(now.year, now.month, now.day) - timedelta(days=(now.weekday() + 1) % 7) start_of_month = datetime(now.year, now.month, 1) target_backup_times = [] # there are no snapshots older than 1/1/2007 oldest_snapshot_date = datetime(2007, 1, 1) for hour in range(0, hourly_backups): target_backup_times.append(last_hour - timedelta(hours=hour)) for day in range(0, daily_backups): target_backup_times.append(last_midnight - timedelta(days=day)) for week in range(0, weekly_backups): target_backup_times.append(last_sunday - timedelta(weeks=week)) one_day = timedelta(days=1) monthly_snapshots_added = 0 while (start_of_month > oldest_snapshot_date and (monthly_backups is True or monthly_snapshots_added < monthly_backups)): # append the start of the month to the list of # snapshot dates to save: target_backup_times.append(start_of_month) monthly_snapshots_added += 1 # there's no timedelta setting for one month, so instead: # decrement the day by one, so we go to the final day of # the previous month... start_of_month -= one_day # ... and then go to the first day of that previous month: start_of_month = datetime(start_of_month.year, start_of_month.month, 1) temp = [] for t in target_backup_times: if temp.__contains__(t) == False: temp.append(t) # sort to make the oldest dates first, and make sure the month start # and last four week's start are in the proper order target_backup_times = sorted(temp) # get all the snapshots, sort them by date and time, and # organize them into one array for each volume: all_snapshots = self.get_all_snapshots(owner = 'self') all_snapshots.sort(key=lambda x: x.start_time) snaps_for_each_volume = {} for snap in all_snapshots: # the snapshot name and the volume name are the same. # The snapshot name is set from the volume # name at the time the snapshot is taken volume_name = snap.tags.get('Name') if volume_name: # only examine snapshots that have a volume name snaps_for_volume = snaps_for_each_volume.get(volume_name) if not snaps_for_volume: snaps_for_volume = [] snaps_for_each_volume[volume_name] = snaps_for_volume snaps_for_volume.append(snap) # Do a running comparison of snapshot dates to desired time #periods, keeping the oldest snapshot in each # time period and deleting the rest: for volume_name in snaps_for_each_volume: snaps = snaps_for_each_volume[volume_name] snaps = snaps[:-1] # never delete the newest snapshot time_period_number = 0 snap_found_for_this_time_period = False for snap in snaps: check_this_snap = True while check_this_snap and time_period_number < target_backup_times.__len__(): snap_date = datetime.strptime(snap.start_time, '%Y-%m-%dT%H:%M:%S.000Z') if snap_date < target_backup_times[time_period_number]: # the snap date is before the cutoff date. # Figure out if it's the first snap in this # date range and act accordingly (since both #date the date ranges and the snapshots # are sorted chronologically, we know this #snapshot isn't in an earlier date range): if snap_found_for_this_time_period == True: if not snap.tags.get('preserve_snapshot'): # as long as the snapshot wasn't marked # with the 'preserve_snapshot' tag, delete it: try: self.delete_snapshot(snap.id) boto.log.info('Trimmed snapshot %s (%s)' % (snap.tags['Name'], snap.start_time)) except EC2ResponseError: boto.log.error('Attempt to trim snapshot %s (%s) failed. Possible result of a race condition with trimming on another server?' % (snap.tags['Name'], snap.start_time)) # go on and look at the next snapshot, #leaving the time period alone else: # this was the first snapshot found for this #time period. Leave it alone and look at the # next snapshot: snap_found_for_this_time_period = True check_this_snap = False else: # the snap is after the cutoff date. Check it # against the next cutoff date time_period_number += 1 snap_found_for_this_time_period = False
[ "def", "trim_snapshots", "(", "self", ",", "hourly_backups", "=", "8", ",", "daily_backups", "=", "7", ",", "weekly_backups", "=", "4", ",", "monthly_backups", "=", "True", ")", ":", "# This function first builds up an ordered list of target times", "# that snapshots sh...
https://github.com/boto/boto/blob/b2a6f08122b2f1b89888d2848e730893595cd001/boto/ec2/connection.py#L2558-L2709
Jenyay/outwiker
50530cf7b3f71480bb075b2829bc0669773b835b
plugins/webpage/webpage/libs/soupsieve/css_match.py
python
_DocumentNav.is_iframe
(self, el)
return ((el.name if self.is_xml_tree(el) else util.lower(el.name)) == 'iframe') and self.is_html_tag(el)
Check if element is an `iframe`.
Check if element is an `iframe`.
[ "Check", "if", "element", "is", "an", "iframe", "." ]
def is_iframe(self, el): """Check if element is an `iframe`.""" return ((el.name if self.is_xml_tree(el) else util.lower(el.name)) == 'iframe') and self.is_html_tag(el)
[ "def", "is_iframe", "(", "self", ",", "el", ")", ":", "return", "(", "(", "el", ".", "name", "if", "self", ".", "is_xml_tree", "(", "el", ")", "else", "util", ".", "lower", "(", "el", ".", "name", ")", ")", "==", "'iframe'", ")", "and", "self", ...
https://github.com/Jenyay/outwiker/blob/50530cf7b3f71480bb075b2829bc0669773b835b/plugins/webpage/webpage/libs/soupsieve/css_match.py#L162-L165
onetwo1/pinduoduo
021ed7772373ef382ef7f96f006cc92b4201035a
pin_duoduo/pin_duoduo/randomproxy.py
python
RandomProxy.process_response
(self, request, response, spider)
[]
def process_response(self, request, response, spider): if response.status == 200: return response # 出错会引发异常而进入 process_exception 逻辑, 更换代理重抓 raise ResponseCodeError
[ "def", "process_response", "(", "self", ",", "request", ",", "response", ",", "spider", ")", ":", "if", "response", ".", "status", "==", "200", ":", "return", "response", "# 出错会引发异常而进入 process_exception 逻辑, 更换代理重抓", "raise", "ResponseCodeError" ]
https://github.com/onetwo1/pinduoduo/blob/021ed7772373ef382ef7f96f006cc92b4201035a/pin_duoduo/pin_duoduo/randomproxy.py#L57-L61
simoncadman/CUPS-Cloud-Print
5d96eaa5ba1d3ffe40845498917879b0e907f6bd
oauth2client/client.py
python
_update_query_params
(uri, params)
return urllib.parse.urlunparse(new_parts)
Updates a URI with new query parameters. Args: uri: string, A valid URI, with potential existing query parameters. params: dict, A dictionary of query parameters. Returns: The same URI but with the new query parameters added.
Updates a URI with new query parameters.
[ "Updates", "a", "URI", "with", "new", "query", "parameters", "." ]
def _update_query_params(uri, params): """Updates a URI with new query parameters. Args: uri: string, A valid URI, with potential existing query parameters. params: dict, A dictionary of query parameters. Returns: The same URI but with the new query parameters added. """ parts = urllib.parse.urlparse(uri) query_params = dict(urllib.parse.parse_qsl(parts.query)) query_params.update(params) new_parts = parts._replace(query=urllib.parse.urlencode(query_params)) return urllib.parse.urlunparse(new_parts)
[ "def", "_update_query_params", "(", "uri", ",", "params", ")", ":", "parts", "=", "urllib", ".", "parse", ".", "urlparse", "(", "uri", ")", "query_params", "=", "dict", "(", "urllib", ".", "parse", ".", "parse_qsl", "(", "parts", ".", "query", ")", ")"...
https://github.com/simoncadman/CUPS-Cloud-Print/blob/5d96eaa5ba1d3ffe40845498917879b0e907f6bd/oauth2client/client.py#L413-L427
tableau/rest-api-samples
0be12fa52c6e66104633ab26e67fdf73ae411b33
python/users_by_group.py
python
sign_out
(server, auth_token)
return
Destroys the active session and invalidates authentication token. 'server' specified server address 'auth_token' authentication token that grants user access to API calls
Destroys the active session and invalidates authentication token.
[ "Destroys", "the", "active", "session", "and", "invalidates", "authentication", "token", "." ]
def sign_out(server, auth_token): """ Destroys the active session and invalidates authentication token. 'server' specified server address 'auth_token' authentication token that grants user access to API calls """ url = server + "/api/{0}/auth/signout".format(VERSION) server_response = requests.post(url, headers={'x-tableau-auth': auth_token}) _check_status(server_response, 204) return
[ "def", "sign_out", "(", "server", ",", "auth_token", ")", ":", "url", "=", "server", "+", "\"/api/{0}/auth/signout\"", ".", "format", "(", "VERSION", ")", "server_response", "=", "requests", ".", "post", "(", "url", ",", "headers", "=", "{", "'x-tableau-auth...
https://github.com/tableau/rest-api-samples/blob/0be12fa52c6e66104633ab26e67fdf73ae411b33/python/users_by_group.py#L111-L121
GRAAL-Research/poutyne
f46e5fe610d175b96a490db24ef2d22b49cc594b
poutyne/framework/callbacks/mlflow_logger.py
python
MLFlowLogger._on_epoch_end_write
(self, epoch_number: int, logs: Dict)
Log the batch and epoch metric.
Log the batch and epoch metric.
[ "Log", "the", "batch", "and", "epoch", "metric", "." ]
def _on_epoch_end_write(self, epoch_number: int, logs: Dict) -> None: """ Log the batch and epoch metric. """ logs.pop("epoch") for key, value in logs.items(): self.log_metric(key, value, step=epoch_number)
[ "def", "_on_epoch_end_write", "(", "self", ",", "epoch_number", ":", "int", ",", "logs", ":", "Dict", ")", "->", "None", ":", "logs", ".", "pop", "(", "\"epoch\"", ")", "for", "key", ",", "value", "in", "logs", ".", "items", "(", ")", ":", "self", ...
https://github.com/GRAAL-Research/poutyne/blob/f46e5fe610d175b96a490db24ef2d22b49cc594b/poutyne/framework/callbacks/mlflow_logger.py#L140-L146
spack/spack
675210bd8bd1c5d32ad1cc83d898fb43b569ed74
var/spack/repos/builtin/packages/flex/package.py
python
Flex.symlink_lex
(self)
Install symlinks for lex compatibility.
Install symlinks for lex compatibility.
[ "Install", "symlinks", "for", "lex", "compatibility", "." ]
def symlink_lex(self): """Install symlinks for lex compatibility.""" if self.spec.satisfies('+lex'): dso = dso_suffix for dir, flex, lex in \ ((self.prefix.bin, 'flex', 'lex'), (self.prefix.lib, 'libfl.a', 'libl.a'), (self.prefix.lib, 'libfl.' + dso, 'libl.' + dso), (self.prefix.lib64, 'libfl.a', 'libl.a'), (self.prefix.lib64, 'libfl.' + dso, 'libl.' + dso)): if os.path.isdir(dir): with working_dir(dir): if (os.path.isfile(flex) and not os.path.lexists(lex)): symlink(flex, lex)
[ "def", "symlink_lex", "(", "self", ")", ":", "if", "self", ".", "spec", ".", "satisfies", "(", "'+lex'", ")", ":", "dso", "=", "dso_suffix", "for", "dir", ",", "flex", ",", "lex", "in", "(", "(", "self", ".", "prefix", ".", "bin", ",", "'flex'", ...
https://github.com/spack/spack/blob/675210bd8bd1c5d32ad1cc83d898fb43b569ed74/var/spack/repos/builtin/packages/flex/package.py#L102-L116
yzhao062/pyod
13b0cd5f50d5ea5c5321da88c46232ae6f24dff7
pyod/models/sos.py
python
SOS._x2d
(self, X)
return D
Computes the dissimilarity matrix of a given dataset. Parameters ---------- X : array-like, shape (n_samples, n_features) The query sample or samples to compute the dissimilarity matrix w.r.t. to the training samples. Returns ------- D : array, shape (n_samples, ) Returns the dissimilarity matrix.
Computes the dissimilarity matrix of a given dataset. Parameters ---------- X : array-like, shape (n_samples, n_features) The query sample or samples to compute the dissimilarity matrix w.r.t. to the training samples. Returns ------- D : array, shape (n_samples, ) Returns the dissimilarity matrix.
[ "Computes", "the", "dissimilarity", "matrix", "of", "a", "given", "dataset", ".", "Parameters", "----------", "X", ":", "array", "-", "like", "shape", "(", "n_samples", "n_features", ")", "The", "query", "sample", "or", "samples", "to", "compute", "the", "di...
def _x2d(self, X): """Computes the dissimilarity matrix of a given dataset. Parameters ---------- X : array-like, shape (n_samples, n_features) The query sample or samples to compute the dissimilarity matrix w.r.t. to the training samples. Returns ------- D : array, shape (n_samples, ) Returns the dissimilarity matrix. """ (n, d) = X.shape if self.metric == 'none': if n != d: raise ValueError( "If you specify 'none' as the metric, the data set " "should be a square dissimilarity matrix") else: D = X elif self.metric == 'euclidean': sumX = np.sum(np.square(X), 1) # np.abs protects against extremely small negative values # that may arise due to floating point arithmetic errors D = np.sqrt( np.abs(np.add(np.add(-2 * np.dot(X, X.T), sumX).T, sumX))) else: try: from scipy.spatial import distance except ImportError as e: raise ImportError( "Please install scipy if you wish to use a metric " "other than 'euclidean' or 'none'") else: D = distance.squareform(distance.pdist(X, self.metric)) return D
[ "def", "_x2d", "(", "self", ",", "X", ")", ":", "(", "n", ",", "d", ")", "=", "X", ".", "shape", "if", "self", ".", "metric", "==", "'none'", ":", "if", "n", "!=", "d", ":", "raise", "ValueError", "(", "\"If you specify 'none' as the metric, the data s...
https://github.com/yzhao062/pyod/blob/13b0cd5f50d5ea5c5321da88c46232ae6f24dff7/pyod/models/sos.py#L122-L161
PUNCH-Cyber/stoq
8bfc78b226ee6500eb78e1bdf361fc83bc5005b7
stoq/data_classes.py
python
WorkerResponse.__str__
(self)
return helpers.dumps(self)
[]
def __str__(self) -> str: return helpers.dumps(self)
[ "def", "__str__", "(", "self", ")", "->", "str", ":", "return", "helpers", ".", "dumps", "(", "self", ")" ]
https://github.com/PUNCH-Cyber/stoq/blob/8bfc78b226ee6500eb78e1bdf361fc83bc5005b7/stoq/data_classes.py#L343-L344
rwth-i6/returnn
f2d718a197a280b0d5f0fd91a7fcb8658560dddb
returnn/extern/graph_editor/subgraph.py
python
SubGraphView._remove_unused_ops
(self, control_inputs=True)
Remove unused ops in place. Args: control_inputs: if True, control inputs are used to detect used ops. Returns: A new subgraph view which only contains used operations.
Remove unused ops in place.
[ "Remove", "unused", "ops", "in", "place", "." ]
def _remove_unused_ops(self, control_inputs=True): """Remove unused ops in place. Args: control_inputs: if True, control inputs are used to detect used ops. Returns: A new subgraph view which only contains used operations. """ ops = select.get_walks_union_ops( self.connected_inputs, self.connected_outputs, within_ops=self._ops, control_inputs=control_inputs) self._ops = [op for op in self._ops if op in ops]
[ "def", "_remove_unused_ops", "(", "self", ",", "control_inputs", "=", "True", ")", ":", "ops", "=", "select", ".", "get_walks_union_ops", "(", "self", ".", "connected_inputs", ",", "self", ".", "connected_outputs", ",", "within_ops", "=", "self", ".", "_ops", ...
https://github.com/rwth-i6/returnn/blob/f2d718a197a280b0d5f0fd91a7fcb8658560dddb/returnn/extern/graph_editor/subgraph.py#L336-L349
cloudera/impyla
0c736af4cad2bade9b8e313badc08ec50e81c948
impala/_thrift_gen/hive_metastore/ThriftHiveMetastore.py
python
show_compact_args.__eq__
(self, other)
return isinstance(other, self.__class__) and self.__dict__ == other.__dict__
[]
def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__
[ "def", "__eq__", "(", "self", ",", "other", ")", ":", "return", "isinstance", "(", "other", ",", "self", ".", "__class__", ")", "and", "self", ".", "__dict__", "==", "other", ".", "__dict__" ]
https://github.com/cloudera/impyla/blob/0c736af4cad2bade9b8e313badc08ec50e81c948/impala/_thrift_gen/hive_metastore/ThriftHiveMetastore.py#L33604-L33605
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/google/appengine/_internal/django/utils/safestring.py
python
mark_for_escaping
(s)
return EscapeString(str(s))
Explicitly mark a string as requiring HTML escaping upon output. Has no effect on SafeData subclasses. Can be called multiple times on a single string (the resulting escaping is only applied once).
Explicitly mark a string as requiring HTML escaping upon output. Has no effect on SafeData subclasses.
[ "Explicitly", "mark", "a", "string", "as", "requiring", "HTML", "escaping", "upon", "output", ".", "Has", "no", "effect", "on", "SafeData", "subclasses", "." ]
def mark_for_escaping(s): """ Explicitly mark a string as requiring HTML escaping upon output. Has no effect on SafeData subclasses. Can be called multiple times on a single string (the resulting escaping is only applied once). """ if isinstance(s, (SafeData, EscapeData)): return s if isinstance(s, str) or (isinstance(s, Promise) and s._delegate_str): return EscapeString(s) if isinstance(s, (unicode, Promise)): return EscapeUnicode(s) return EscapeString(str(s))
[ "def", "mark_for_escaping", "(", "s", ")", ":", "if", "isinstance", "(", "s", ",", "(", "SafeData", ",", "EscapeData", ")", ")", ":", "return", "s", "if", "isinstance", "(", "s", ",", "str", ")", "or", "(", "isinstance", "(", "s", ",", "Promise", "...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/google/appengine/_internal/django/utils/safestring.py#L104-L118
ethereum/trinity
6383280c5044feb06695ac2f7bc1100b7bcf4fe0
trinity/protocol/eth/validators.py
python
GetBlockBodiesValidator.__init__
(self, headers: Sequence[BlockHeaderAPI])
[]
def __init__(self, headers: Sequence[BlockHeaderAPI]) -> None: self.headers = headers
[ "def", "__init__", "(", "self", ",", "headers", ":", "Sequence", "[", "BlockHeaderAPI", "]", ")", "->", "None", ":", "self", ".", "headers", "=", "headers" ]
https://github.com/ethereum/trinity/blob/6383280c5044feb06695ac2f7bc1100b7bcf4fe0/trinity/protocol/eth/validators.py#L88-L89
1040003585/WebScrapingWithPython
a770fa5b03894076c8c9539b1ffff34424ffc016
portia_examle/lib/python2.7/site-packages/pip/exceptions.py
python
HashError._requirement_name
(self)
return str(self.req) if self.req else 'unknown package'
Return a description of the requirement that triggered me. This default implementation returns long description of the req, with line numbers
Return a description of the requirement that triggered me.
[ "Return", "a", "description", "of", "the", "requirement", "that", "triggered", "me", "." ]
def _requirement_name(self): """Return a description of the requirement that triggered me. This default implementation returns long description of the req, with line numbers """ return str(self.req) if self.req else 'unknown package'
[ "def", "_requirement_name", "(", "self", ")", ":", "return", "str", "(", "self", ".", "req", ")", "if", "self", ".", "req", "else", "'unknown package'" ]
https://github.com/1040003585/WebScrapingWithPython/blob/a770fa5b03894076c8c9539b1ffff34424ffc016/portia_examle/lib/python2.7/site-packages/pip/exceptions.py#L113-L120
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/apps/reports/views.py
python
get_scheduled_report_response
(couch_user, domain, scheduled_report_id, email=True, attach_excel=False, send_only_active=False, request=None)
return _render_report_configs( request, scheduled_report.configs, scheduled_report.domain, scheduled_report.owner_id, couch_user, email, attach_excel=attach_excel, lang=scheduled_report.language, send_only_active=send_only_active, )
This function somewhat confusingly returns a tuple of: (response, excel_files) If attach_excel is false, excel_files will always be an empty list. If send_only_active is True, then only ReportConfigs that have a start_date in the past will be sent. If none of the ReportConfigs are valid, no email will be sent.
This function somewhat confusingly returns a tuple of: (response, excel_files) If attach_excel is false, excel_files will always be an empty list. If send_only_active is True, then only ReportConfigs that have a start_date in the past will be sent. If none of the ReportConfigs are valid, no email will be sent.
[ "This", "function", "somewhat", "confusingly", "returns", "a", "tuple", "of", ":", "(", "response", "excel_files", ")", "If", "attach_excel", "is", "false", "excel_files", "will", "always", "be", "an", "empty", "list", ".", "If", "send_only_active", "is", "Tru...
def get_scheduled_report_response(couch_user, domain, scheduled_report_id, email=True, attach_excel=False, send_only_active=False, request=None): """ This function somewhat confusingly returns a tuple of: (response, excel_files) If attach_excel is false, excel_files will always be an empty list. If send_only_active is True, then only ReportConfigs that have a start_date in the past will be sent. If none of the ReportConfigs are valid, no email will be sent. """ # todo: clean up this API? domain_obj = Domain.get_by_name(domain) if not user_can_view_reports(domain_obj, couch_user): raise Http404 scheduled_report = ReportNotification.get_report(scheduled_report_id) if not scheduled_report: raise Http404 if not (scheduled_report.domain == domain and scheduled_report.can_be_viewed_by(couch_user)): raise Http404 from django.http import HttpRequest if not request: request = HttpRequest() request.couch_user = couch_user request.user = couch_user.get_django_user() request.domain = domain request.couch_user.current_domain = domain return _render_report_configs( request, scheduled_report.configs, scheduled_report.domain, scheduled_report.owner_id, couch_user, email, attach_excel=attach_excel, lang=scheduled_report.language, send_only_active=send_only_active, )
[ "def", "get_scheduled_report_response", "(", "couch_user", ",", "domain", ",", "scheduled_report_id", ",", "email", "=", "True", ",", "attach_excel", "=", "False", ",", "send_only_active", "=", "False", ",", "request", "=", "None", ")", ":", "# todo: clean up this...
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/reports/views.py#L948-L988
google/diff-match-patch
62f2e689f498f9c92dbc588c58750addec9b1654
python2/diff_match_patch.py
python
diff_match_patch.diff_cleanupEfficiency
(self, diffs)
Reduce the number of edits by eliminating operationally trivial equalities. Args: diffs: Array of diff tuples.
Reduce the number of edits by eliminating operationally trivial equalities.
[ "Reduce", "the", "number", "of", "edits", "by", "eliminating", "operationally", "trivial", "equalities", "." ]
def diff_cleanupEfficiency(self, diffs): """Reduce the number of edits by eliminating operationally trivial equalities. Args: diffs: Array of diff tuples. """ changes = False equalities = [] # Stack of indices where equalities are found. lastEquality = None # Always equal to diffs[equalities[-1]][1] pointer = 0 # Index of current position. pre_ins = False # Is there an insertion operation before the last equality. pre_del = False # Is there a deletion operation before the last equality. post_ins = False # Is there an insertion operation after the last equality. post_del = False # Is there a deletion operation after the last equality. while pointer < len(diffs): if diffs[pointer][0] == self.DIFF_EQUAL: # Equality found. if (len(diffs[pointer][1]) < self.Diff_EditCost and (post_ins or post_del)): # Candidate found. equalities.append(pointer) pre_ins = post_ins pre_del = post_del lastEquality = diffs[pointer][1] else: # Not a candidate, and can never become one. equalities = [] lastEquality = None post_ins = post_del = False else: # An insertion or deletion. if diffs[pointer][0] == self.DIFF_DELETE: post_del = True else: post_ins = True # Five types to be split: # <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del> # <ins>A</ins>X<ins>C</ins><del>D</del> # <ins>A</ins><del>B</del>X<ins>C</ins> # <ins>A</del>X<ins>C</ins><del>D</del> # <ins>A</ins><del>B</del>X<del>C</del> if lastEquality and ((pre_ins and pre_del and post_ins and post_del) or ((len(lastEquality) < self.Diff_EditCost / 2) and (pre_ins + pre_del + post_ins + post_del) == 3)): # Duplicate record. diffs.insert(equalities[-1], (self.DIFF_DELETE, lastEquality)) # Change second copy to insert. diffs[equalities[-1] + 1] = (self.DIFF_INSERT, diffs[equalities[-1] + 1][1]) equalities.pop() # Throw away the equality we just deleted. lastEquality = None if pre_ins and pre_del: # No changes made which could affect previous entry, keep going. post_ins = post_del = True equalities = [] else: if len(equalities): equalities.pop() # Throw away the previous equality. if len(equalities): pointer = equalities[-1] else: pointer = -1 post_ins = post_del = False changes = True pointer += 1 if changes: self.diff_cleanupMerge(diffs)
[ "def", "diff_cleanupEfficiency", "(", "self", ",", "diffs", ")", ":", "changes", "=", "False", "equalities", "=", "[", "]", "# Stack of indices where equalities are found.", "lastEquality", "=", "None", "# Always equal to diffs[equalities[-1]][1]", "pointer", "=", "0", ...
https://github.com/google/diff-match-patch/blob/62f2e689f498f9c92dbc588c58750addec9b1654/python2/diff_match_patch.py#L853-L922
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/zwave_js/light.py
python
ZwaveLight.rgbw_color
(self)
return self._rgbw_color
Return the hs color.
Return the hs color.
[ "Return", "the", "hs", "color", "." ]
def rgbw_color(self) -> tuple[int, int, int, int] | None: """Return the hs color.""" return self._rgbw_color
[ "def", "rgbw_color", "(", "self", ")", "->", "tuple", "[", "int", ",", "int", ",", "int", ",", "int", "]", "|", "None", ":", "return", "self", ".", "_rgbw_color" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/zwave_js/light.py#L195-L197
robotlearn/pyrobolearn
9cd7c060723fda7d2779fa255ac998c2c82b8436
pyrobolearn/dynamics/dynamic.py
python
DynamicModel.__init__
(self, state, action, next_state=None, preprocessors=None, postprocessors=None)
Initialize the dynamic transition probability :math:`p(s_{t+1} | s_t, a_t)`, or dynamic transition function :math:`s_{t+1} = f(s_t, a_t)`. Args: state (State): state inputs. action (Action): action inputs. next_state (State, None): state outputs. If None, it will take the state inputs as the outputs. preprocessors (Processor, list of Processor, None): pre-processors to be applied to the given input postprocessors (Processor, list of Processor, None): post-processors to be applied to the output
Initialize the dynamic transition probability :math:`p(s_{t+1} | s_t, a_t)`, or dynamic transition function :math:`s_{t+1} = f(s_t, a_t)`.
[ "Initialize", "the", "dynamic", "transition", "probability", ":", "math", ":", "p", "(", "s_", "{", "t", "+", "1", "}", "|", "s_t", "a_t", ")", "or", "dynamic", "transition", "function", ":", "math", ":", "s_", "{", "t", "+", "1", "}", "=", "f", ...
def __init__(self, state, action, next_state=None, preprocessors=None, postprocessors=None): """ Initialize the dynamic transition probability :math:`p(s_{t+1} | s_t, a_t)`, or dynamic transition function :math:`s_{t+1} = f(s_t, a_t)`. Args: state (State): state inputs. action (Action): action inputs. next_state (State, None): state outputs. If None, it will take the state inputs as the outputs. preprocessors (Processor, list of Processor, None): pre-processors to be applied to the given input postprocessors (Processor, list of Processor, None): post-processors to be applied to the output """ # set inputs self.state = state self.action = action # set outputs self.next_state = next_state self.state_data = None # preprocessors and postprocessors if preprocessors is None: preprocessors = [] if not isinstance(preprocessors, collections.Iterable): preprocessors = [preprocessors] self.preprocessors = preprocessors if postprocessors is None: postprocessors = [] if not isinstance(postprocessors, collections.Iterable): postprocessors = [postprocessors] self.postprocessors = postprocessors
[ "def", "__init__", "(", "self", ",", "state", ",", "action", ",", "next_state", "=", "None", ",", "preprocessors", "=", "None", ",", "postprocessors", "=", "None", ")", ":", "# set inputs", "self", ".", "state", "=", "state", "self", ".", "action", "=", ...
https://github.com/robotlearn/pyrobolearn/blob/9cd7c060723fda7d2779fa255ac998c2c82b8436/pyrobolearn/dynamics/dynamic.py#L79-L110
SebKuzminsky/pycam
55e3129f518e470040e79bb00515b4bfcf36c172
pycam/Utils/iterators.py
python
Iterator.insert
(self, item)
[]
def insert(self, item): self.seq.insert(self.ind, item) self.ind += 1
[ "def", "insert", "(", "self", ",", "item", ")", ":", "self", ".", "seq", ".", "insert", "(", "self", ".", "ind", ",", "item", ")", "self", ".", "ind", "+=", "1" ]
https://github.com/SebKuzminsky/pycam/blob/55e3129f518e470040e79bb00515b4bfcf36c172/pycam/Utils/iterators.py#L38-L40
Chaffelson/nipyapi
d3b186fd701ce308c2812746d98af9120955e810
nipyapi/registry/models/extension_metadata.py
python
ExtensionMetadata.link_docs
(self)
return self._link_docs
Gets the link_docs of this ExtensionMetadata. A WebLink to the documentation for this extension. :return: The link_docs of this ExtensionMetadata. :rtype: JaxbLink
Gets the link_docs of this ExtensionMetadata. A WebLink to the documentation for this extension.
[ "Gets", "the", "link_docs", "of", "this", "ExtensionMetadata", ".", "A", "WebLink", "to", "the", "documentation", "for", "this", "extension", "." ]
def link_docs(self): """ Gets the link_docs of this ExtensionMetadata. A WebLink to the documentation for this extension. :return: The link_docs of this ExtensionMetadata. :rtype: JaxbLink """ return self._link_docs
[ "def", "link_docs", "(", "self", ")", ":", "return", "self", ".", "_link_docs" ]
https://github.com/Chaffelson/nipyapi/blob/d3b186fd701ce308c2812746d98af9120955e810/nipyapi/registry/models/extension_metadata.py#L366-L374
rm-hull/luma.examples
3a5110ab27a2d4f10cd62dc0156f439f4decd1e7
examples/scrolling_pixelart.py
python
scroll_left
(virtual, pos)
return (x, y)
[]
def scroll_left(virtual, pos): x, y = pos while x >= 0: virtual.set_position((x, y)) x -= 1 x = 0 return (x, y)
[ "def", "scroll_left", "(", "virtual", ",", "pos", ")", ":", "x", ",", "y", "=", "pos", "while", "x", ">=", "0", ":", "virtual", ".", "set_position", "(", "(", "x", ",", "y", ")", ")", "x", "-=", "1", "x", "=", "0", "return", "(", "x", ",", ...
https://github.com/rm-hull/luma.examples/blob/3a5110ab27a2d4f10cd62dc0156f439f4decd1e7/examples/scrolling_pixelart.py#L49-L55
OmkarPathak/pygorithm
be35813729a0151da1ac9ba013453a61ffa249b8
pygorithm/fibonacci/goldenratio.py
python
sequence
(n)
return [fib(value) for value in range(n + 1)]
Return sequence of Fibonacci values as list.
Return sequence of Fibonacci values as list.
[ "Return", "sequence", "of", "Fibonacci", "values", "as", "list", "." ]
def sequence(n): """ Return sequence of Fibonacci values as list. """ return [fib(value) for value in range(n + 1)]
[ "def", "sequence", "(", "n", ")", ":", "return", "[", "fib", "(", "value", ")", "for", "value", "in", "range", "(", "n", "+", "1", ")", "]" ]
https://github.com/OmkarPathak/pygorithm/blob/be35813729a0151da1ac9ba013453a61ffa249b8/pygorithm/fibonacci/goldenratio.py#L32-L36
JaniceWuo/MovieRecommend
4c86db64ca45598917d304f535413df3bc9fea65
movierecommend/venv1/Lib/site-packages/django/middleware/csrf.py
python
CsrfViewMiddleware.process_response
(self, request, response)
return response
[]
def process_response(self, request, response): if not getattr(request, 'csrf_cookie_needs_reset', False): if getattr(response, 'csrf_cookie_set', False): return response if not request.META.get("CSRF_COOKIE_USED", False): return response # Set the CSRF cookie even if it's already set, so we renew # the expiry timer. self._set_token(request, response) response.csrf_cookie_set = True return response
[ "def", "process_response", "(", "self", ",", "request", ",", "response", ")", ":", "if", "not", "getattr", "(", "request", ",", "'csrf_cookie_needs_reset'", ",", "False", ")", ":", "if", "getattr", "(", "response", ",", "'csrf_cookie_set'", ",", "False", ")"...
https://github.com/JaniceWuo/MovieRecommend/blob/4c86db64ca45598917d304f535413df3bc9fea65/movierecommend/venv1/Lib/site-packages/django/middleware/csrf.py#L320-L332
aiidateam/aiida-core
c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2
aiida/cmdline/commands/cmd_verdi.py
python
VerdiCommandGroup.add_verbosity_option
(cmd)
return cmd
Apply the ``verbosity`` option to the command, which is common to all ``verdi`` commands.
Apply the ``verbosity`` option to the command, which is common to all ``verdi`` commands.
[ "Apply", "the", "verbosity", "option", "to", "the", "command", "which", "is", "common", "to", "all", "verdi", "commands", "." ]
def add_verbosity_option(cmd): """Apply the ``verbosity`` option to the command, which is common to all ``verdi`` commands.""" # Only apply the option if it hasn't been already added in a previous call. if cmd is not None and 'verbosity' not in [param.name for param in cmd.params]: cmd = options.VERBOSITY()(cmd) return cmd
[ "def", "add_verbosity_option", "(", "cmd", ")", ":", "# Only apply the option if it hasn't been already added in a previous call.", "if", "cmd", "is", "not", "None", "and", "'verbosity'", "not", "in", "[", "param", ".", "name", "for", "param", "in", "cmd", ".", "par...
https://github.com/aiidateam/aiida-core/blob/c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2/aiida/cmdline/commands/cmd_verdi.py#L40-L46
lazylibrarian/LazyLibrarian
ae3c14e9db9328ce81765e094ab2a14ed7155624
cherrypy/_cptools.py
python
Tool.__call__
(self, *args, **kwargs)
return tool_decorator
Compile-time decorator (turn on the tool in config). For example:: @tools.proxy() def whats_my_base(self): return cherrypy.request.base whats_my_base.exposed = True
Compile-time decorator (turn on the tool in config).
[ "Compile", "-", "time", "decorator", "(", "turn", "on", "the", "tool", "in", "config", ")", "." ]
def __call__(self, *args, **kwargs): """Compile-time decorator (turn on the tool in config). For example:: @tools.proxy() def whats_my_base(self): return cherrypy.request.base whats_my_base.exposed = True """ if args: raise TypeError("The %r Tool does not accept positional " "arguments; you must use keyword arguments." % self._name) def tool_decorator(f): if not hasattr(f, "_cp_config"): f._cp_config = {} subspace = self.namespace + "." + self._name + "." f._cp_config[subspace + "on"] = True for k, v in kwargs.items(): f._cp_config[subspace + k] = v return f return tool_decorator
[ "def", "__call__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "args", ":", "raise", "TypeError", "(", "\"The %r Tool does not accept positional \"", "\"arguments; you must use keyword arguments.\"", "%", "self", ".", "_name", ")", "def...
https://github.com/lazylibrarian/LazyLibrarian/blob/ae3c14e9db9328ce81765e094ab2a14ed7155624/cherrypy/_cptools.py#L111-L134
Tautulli/Tautulli
2410eb33805aaac4bd1c5dad0f71e4f15afaf742
lib/plexapi/mixins.py
python
StyleMixin.removeStyle
(self, styles, locked=True)
Remove a style tag(s). Parameters: styles (list): List of strings. locked (bool): True (default) to lock the field, False to unlock the field.
Remove a style tag(s).
[ "Remove", "a", "style", "tag", "(", "s", ")", "." ]
def removeStyle(self, styles, locked=True): """ Remove a style tag(s). Parameters: styles (list): List of strings. locked (bool): True (default) to lock the field, False to unlock the field. """ self._edit_tags('style', styles, locked=locked, remove=True)
[ "def", "removeStyle", "(", "self", ",", "styles", ",", "locked", "=", "True", ")", ":", "self", ".", "_edit_tags", "(", "'style'", ",", "styles", ",", "locked", "=", "locked", ",", "remove", "=", "True", ")" ]
https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/plexapi/mixins.py#L534-L541
edisonlz/fastor
342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3
base/site-packages/south/creator/actions.py
python
ChangeField.console_line
(self)
return " ~ Changed field %s on %s.%s" % ( self.new_field.name, self.model._meta.app_label, self.model._meta.object_name, )
Returns the string to print on the console, e.g. ' + Added field foo
Returns the string to print on the console, e.g. ' + Added field foo
[ "Returns", "the", "string", "to", "print", "on", "the", "console", "e", ".", "g", ".", "+", "Added", "field", "foo" ]
def console_line(self): "Returns the string to print on the console, e.g. ' + Added field foo'" return " ~ Changed field %s on %s.%s" % ( self.new_field.name, self.model._meta.app_label, self.model._meta.object_name, )
[ "def", "console_line", "(", "self", ")", ":", "return", "\" ~ Changed field %s on %s.%s\"", "%", "(", "self", ".", "new_field", ".", "name", ",", "self", ".", "model", ".", "_meta", ".", "app_label", ",", "self", ".", "model", ".", "_meta", ".", "object_na...
https://github.com/edisonlz/fastor/blob/342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3/base/site-packages/south/creator/actions.py#L318-L324
wxWidgets/Phoenix
b2199e299a6ca6d866aa6f3d0888499136ead9d6
wx/lib/agw/foldpanelbar.py
python
FoldPanelItem.Reposition
(self, pos)
return self.GetPanelLength()
Repositions this :class:`FoldPanelItem` and reports the length occupied for the next :class:`FoldPanelItem` in the list. :param `pos`: the new item position.
Repositions this :class:`FoldPanelItem` and reports the length occupied for the next :class:`FoldPanelItem` in the list.
[ "Repositions", "this", ":", "class", ":", "FoldPanelItem", "and", "reports", "the", "length", "occupied", "for", "the", "next", ":", "class", ":", "FoldPanelItem", "in", "the", "list", "." ]
def Reposition(self, pos): """ Repositions this :class:`FoldPanelItem` and reports the length occupied for the next :class:`FoldPanelItem` in the list. :param `pos`: the new item position. """ # NOTE: Call Resize before Reposition when an item is added, because the new # size needed will be calculated by Resize. Of course the relative position # of the controls have to be correct in respect to the caption bar self.Freeze() vertical = self.IsVertical() xpos = (vertical and [-1] or [pos])[0] ypos = (vertical and [pos] or [-1])[0] self.SetSize(xpos, ypos, -1, -1, wx.SIZE_USE_EXISTING) self._itemPos = pos self.Thaw() return self.GetPanelLength()
[ "def", "Reposition", "(", "self", ",", "pos", ")", ":", "# NOTE: Call Resize before Reposition when an item is added, because the new", "# size needed will be calculated by Resize. Of course the relative position", "# of the controls have to be correct in respect to the caption bar", "self", ...
https://github.com/wxWidgets/Phoenix/blob/b2199e299a6ca6d866aa6f3d0888499136ead9d6/wx/lib/agw/foldpanelbar.py#L1851-L1874
007gzs/dingtalk-sdk
7979da2e259fdbc571728cae2425a04dbc65850a
dingtalk/client/api/taobao.py
python
TbMiaoJie.alibaba_mos_store_getitemsrecommended
( self, item_id, screen_no )
return self._top_request( "alibaba.mos.store.getitemsrecommended", { "item_id": item_id, "screen_no": screen_no } )
根据商品id获取推荐商品列表 文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=35537 :param item_id: 商品id :param screen_no: 屏编号
根据商品id获取推荐商品列表 文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=35537
[ "根据商品id获取推荐商品列表", "文档地址:https", ":", "//", "open", "-", "doc", ".", "dingtalk", ".", "com", "/", "docs", "/", "api", ".", "htm?apiId", "=", "35537" ]
def alibaba_mos_store_getitemsrecommended( self, item_id, screen_no ): """ 根据商品id获取推荐商品列表 文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=35537 :param item_id: 商品id :param screen_no: 屏编号 """ return self._top_request( "alibaba.mos.store.getitemsrecommended", { "item_id": item_id, "screen_no": screen_no } )
[ "def", "alibaba_mos_store_getitemsrecommended", "(", "self", ",", "item_id", ",", "screen_no", ")", ":", "return", "self", ".", "_top_request", "(", "\"alibaba.mos.store.getitemsrecommended\"", ",", "{", "\"item_id\"", ":", "item_id", ",", "\"screen_no\"", ":", "scree...
https://github.com/007gzs/dingtalk-sdk/blob/7979da2e259fdbc571728cae2425a04dbc65850a/dingtalk/client/api/taobao.py#L59878-L59896
007gzs/dingtalk-sdk
7979da2e259fdbc571728cae2425a04dbc65850a
dingtalk/client/api/taobao.py
python
TbDuJiaShangPinGuanLi.taobao_alitrip_travel_item_sku_override
( self, skus, item_id='', out_product_id='' )
return self._top_request( "taobao.alitrip.travel.item.sku.override", { "skus": skus, "item_id": item_id, "out_product_id": out_product_id }, result_processor=lambda x: x["travel_item"] )
【API3.0】商品级别日历价格库存修改,全量覆盖 旅行度假新商品日历价格库存信息修改接口 第三版。提供商家通过TOP API方式修改商品sku信息。 文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=25759 :param skus: 商品日历价格库存套餐 :param item_id: 商品id。itemId和outProductId至少填写一个 :param out_product_id: 商品 外部商家编码。itemId和outProductId至少填写一个
【API3.0】商品级别日历价格库存修改,全量覆盖 旅行度假新商品日历价格库存信息修改接口 第三版。提供商家通过TOP API方式修改商品sku信息。 文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=25759
[ "【API3", ".", "0】商品级别日历价格库存修改,全量覆盖", "旅行度假新商品日历价格库存信息修改接口", "第三版。提供商家通过TOP", "API方式修改商品sku信息。", "文档地址:https", ":", "//", "open", "-", "doc", ".", "dingtalk", ".", "com", "/", "docs", "/", "api", ".", "htm?apiId", "=", "25759" ]
def taobao_alitrip_travel_item_sku_override( self, skus, item_id='', out_product_id='' ): """ 【API3.0】商品级别日历价格库存修改,全量覆盖 旅行度假新商品日历价格库存信息修改接口 第三版。提供商家通过TOP API方式修改商品sku信息。 文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=25759 :param skus: 商品日历价格库存套餐 :param item_id: 商品id。itemId和outProductId至少填写一个 :param out_product_id: 商品 外部商家编码。itemId和outProductId至少填写一个 """ return self._top_request( "taobao.alitrip.travel.item.sku.override", { "skus": skus, "item_id": item_id, "out_product_id": out_product_id }, result_processor=lambda x: x["travel_item"] )
[ "def", "taobao_alitrip_travel_item_sku_override", "(", "self", ",", "skus", ",", "item_id", "=", "''", ",", "out_product_id", "=", "''", ")", ":", "return", "self", ".", "_top_request", "(", "\"taobao.alitrip.travel.item.sku.override\"", ",", "{", "\"skus\"", ":", ...
https://github.com/007gzs/dingtalk-sdk/blob/7979da2e259fdbc571728cae2425a04dbc65850a/dingtalk/client/api/taobao.py#L69903-L69926
whyliam/whyliam.workflows.youdao
2dfa7f1de56419dab1c2e70c1a27e5e13ba25a5c
workflow/notify.py
python
convert_image
(inpath, outpath, size)
Convert an image file using ``sips``. Args: inpath (str): Path of source file. outpath (str): Path to destination file. size (int): Width and height of destination image in pixels. Raises: RuntimeError: Raised if ``sips`` exits with non-zero status.
Convert an image file using ``sips``.
[ "Convert", "an", "image", "file", "using", "sips", "." ]
def convert_image(inpath, outpath, size): """Convert an image file using ``sips``. Args: inpath (str): Path of source file. outpath (str): Path to destination file. size (int): Width and height of destination image in pixels. Raises: RuntimeError: Raised if ``sips`` exits with non-zero status. """ cmd = [ b'sips', b'-z', str(size), str(size), inpath, b'--out', outpath] # log().debug(cmd) with open(os.devnull, 'w') as pipe: retcode = subprocess.call(cmd, stdout=pipe, stderr=subprocess.STDOUT) if retcode != 0: raise RuntimeError('sips exited with %d' % retcode)
[ "def", "convert_image", "(", "inpath", ",", "outpath", ",", "size", ")", ":", "cmd", "=", "[", "b'sips'", ",", "b'-z'", ",", "str", "(", "size", ")", ",", "str", "(", "size", ")", ",", "inpath", ",", "b'--out'", ",", "outpath", "]", "# log().debug(cm...
https://github.com/whyliam/whyliam.workflows.youdao/blob/2dfa7f1de56419dab1c2e70c1a27e5e13ba25a5c/workflow/notify.py#L213-L234
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/form_processor/reprocess.py
python
_perfom_post_save_actions
(form, save=True)
[]
def _perfom_post_save_actions(form, save=True): interface = FormProcessorInterface(form.domain) cache = interface.casedb_cache( domain=form.domain, lock=False, deleted_ok=True, xforms=[form], load_src="reprocess_form_post_save", ) with cache as casedb: case_stock_result = SubmissionPost.process_xforms_for_cases([form], casedb) case_models = case_stock_result.case_models forms = ProcessedForms(form, None) stock_result = case_stock_result.stock_result try: FormProcessorSQL.publish_changes_to_kafka(forms, case_models, stock_result) except Exception: error_message = "Error publishing to kafka" return ReprocessingResult(form, None, None, error_message) try: save and SubmissionPost.do_post_save_actions(casedb, [form], case_stock_result) except PostSaveError: error_message = "Error performing post save operations" return ReprocessingResult(form, None, None, error_message) return ReprocessingResult(form, case_models, None, None)
[ "def", "_perfom_post_save_actions", "(", "form", ",", "save", "=", "True", ")", ":", "interface", "=", "FormProcessorInterface", "(", "form", ".", "domain", ")", "cache", "=", "interface", ".", "casedb_cache", "(", "domain", "=", "form", ".", "domain", ",", ...
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/form_processor/reprocess.py#L64-L87
twilio/twilio-python
6e1e811ea57a1edfadd5161ace87397c563f6915
twilio/rest/taskrouter/v1/workspace/workflow/workflow_cumulative_statistics.py
python
WorkflowCumulativeStatisticsInstance._proxy
(self)
return self._context
Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: WorkflowCumulativeStatisticsContext for this WorkflowCumulativeStatisticsInstance :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsContext
Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context
[ "Generate", "an", "instance", "context", "for", "the", "instance", "the", "context", "is", "capable", "of", "performing", "various", "actions", ".", "All", "instance", "actions", "are", "proxied", "to", "the", "context" ]
def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: WorkflowCumulativeStatisticsContext for this WorkflowCumulativeStatisticsInstance :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsContext """ if self._context is None: self._context = WorkflowCumulativeStatisticsContext( self._version, workspace_sid=self._solution['workspace_sid'], workflow_sid=self._solution['workflow_sid'], ) return self._context
[ "def", "_proxy", "(", "self", ")", ":", "if", "self", ".", "_context", "is", "None", ":", "self", ".", "_context", "=", "WorkflowCumulativeStatisticsContext", "(", "self", ".", "_version", ",", "workspace_sid", "=", "self", ".", "_solution", "[", "'workspace...
https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/taskrouter/v1/workspace/workflow/workflow_cumulative_statistics.py#L221-L235
HHammond/PrettyPandas
639c5c48b657c02570a7f423e8a3c4a1572f969b
prettypandas/summarizer.py
python
PrettyPandas.summary
(self, func=methodcaller('sum'), title='Total', axis=0, subset=None, *args, **kwargs)
Add multiple summary rows or columns to the dataframe. Parameters ---------- :param func: function to be used for a summary. :param titles: Title for this summary column. :param axis: Same as numpy and pandas axis argument. A value of None will cause the summary to be applied to both rows and columns. :param args: Positional arguments passed to all the functions. :param kwargs: Keyword arguments passed to all the functions. The results of summary can be chained together.
Add multiple summary rows or columns to the dataframe.
[ "Add", "multiple", "summary", "rows", "or", "columns", "to", "the", "dataframe", "." ]
def summary(self, func=methodcaller('sum'), title='Total', axis=0, subset=None, *args, **kwargs): """Add multiple summary rows or columns to the dataframe. Parameters ---------- :param func: function to be used for a summary. :param titles: Title for this summary column. :param axis: Same as numpy and pandas axis argument. A value of None will cause the summary to be applied to both rows and columns. :param args: Positional arguments passed to all the functions. :param kwargs: Keyword arguments passed to all the functions. The results of summary can be chained together. """ if axis is None: return ( self .summary( func=func, title=title, axis=0, subset=subset, *args, **kwargs ) .summary( func=func, title=title, axis=1, subset=subset, *args, **kwargs ) ) else: agg = Aggregate(title, func, subset=subset, axis=axis, *args, **kwargs) return self._add_summary(agg)
[ "def", "summary", "(", "self", ",", "func", "=", "methodcaller", "(", "'sum'", ")", ",", "title", "=", "'Total'", ",", "axis", "=", "0", ",", "subset", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "axis", "is", "None", ...
https://github.com/HHammond/PrettyPandas/blob/639c5c48b657c02570a7f423e8a3c4a1572f969b/prettypandas/summarizer.py#L240-L285
Vespa314/bilibili-api
42b6b90aa7c141f5cfb0fdc754435518106f6966
bilibili-video/GetAssDanmaku.py
python
ProcessComments
(comments, f, width, height, bottomReserved, fontface, fontsize, alpha, lifetime, reduced, progress_callback)
[]
def ProcessComments(comments, f, width, height, bottomReserved, fontface, fontsize, alpha, lifetime, reduced, progress_callback): styleid = 'Danmaku2ASS_%04x' % random.randint(0, 0xffff) WriteASSHead(f, width, height, fontface, fontsize, alpha, styleid) rows = [[None]*(height-bottomReserved+1) for i in range(4)] for idx, i in enumerate(comments): if progress_callback and idx % 1000 == 0: progress_callback(idx, len(comments)) if isinstance(i[4], int): row = 0 rowmax = height-bottomReserved-i[7] while row <= rowmax: freerows = TestFreeRows(rows, i, row, width, height, bottomReserved, lifetime) if freerows >= i[7]: MarkCommentRow(rows, i, row) WriteComment(f, i, row, width, height, bottomReserved, fontsize, lifetime, styleid) break else: row += freerows or 1 else: if not reduced: row = FindAlternativeRow(rows, i, height, bottomReserved) MarkCommentRow(rows, i, row) WriteComment(f, i, row, width, height, bottomReserved, fontsize, lifetime, styleid) elif i[4] == 'bilipos': WriteCommentBilibiliPositioned(f, i, width, height, styleid) elif i[4] == 'acfunpos': WriteCommentAcfunPositioned(f, i, width, height, styleid) elif i[4] == 'sH5Vpos': WriteCommentSH5VPositioned(f, i, width, height, styleid) else: logging.warning(_('Invalid comment: %r') % i[3]) if progress_callback: progress_callback(len(comments), len(comments))
[ "def", "ProcessComments", "(", "comments", ",", "f", ",", "width", ",", "height", ",", "bottomReserved", ",", "fontface", ",", "fontsize", ",", "alpha", ",", "lifetime", ",", "reduced", ",", "progress_callback", ")", ":", "styleid", "=", "'Danmaku2ASS_%04x'", ...
https://github.com/Vespa314/bilibili-api/blob/42b6b90aa7c141f5cfb0fdc754435518106f6966/bilibili-video/GetAssDanmaku.py#L407-L439
HLTCHKUST/Mem2Seq
4224ccf9e14956115cfdc98814d340d9bd7b953e
utils/utils_babi.py
python
Dataset.preprocess_inde
(self, sequence,src_seq)
return sequence
Converts words to ids.
Converts words to ids.
[ "Converts", "words", "to", "ids", "." ]
def preprocess_inde(self, sequence,src_seq): """Converts words to ids.""" sequence = sequence + [len(src_seq)-1] sequence = torch.Tensor(sequence) return sequence
[ "def", "preprocess_inde", "(", "self", ",", "sequence", ",", "src_seq", ")", ":", "sequence", "=", "sequence", "+", "[", "len", "(", "src_seq", ")", "-", "1", "]", "sequence", "=", "torch", ".", "Tensor", "(", "sequence", ")", "return", "sequence" ]
https://github.com/HLTCHKUST/Mem2Seq/blob/4224ccf9e14956115cfdc98814d340d9bd7b953e/utils/utils_babi.py#L79-L83
firebase/firebase-admin-python
7cfb798ca78f706d08a46c3c48028895787d0ea4
firebase_admin/_messaging_encoder.py
python
MessageEncoder.encode_apns
(cls, apns)
return cls.remove_null_values(result)
Encodes an ``APNSConfig`` instance into JSON.
Encodes an ``APNSConfig`` instance into JSON.
[ "Encodes", "an", "APNSConfig", "instance", "into", "JSON", "." ]
def encode_apns(cls, apns): """Encodes an ``APNSConfig`` instance into JSON.""" if apns is None: return None if not isinstance(apns, _messaging_utils.APNSConfig): raise ValueError('Message.apns must be an instance of APNSConfig class.') result = { 'headers': _Validators.check_string_dict( 'APNSConfig.headers', apns.headers), 'payload': cls.encode_apns_payload(apns.payload), 'fcm_options': cls.encode_apns_fcm_options(apns.fcm_options), } return cls.remove_null_values(result)
[ "def", "encode_apns", "(", "cls", ",", "apns", ")", ":", "if", "apns", "is", "None", ":", "return", "None", "if", "not", "isinstance", "(", "apns", ",", "_messaging_utils", ".", "APNSConfig", ")", ":", "raise", "ValueError", "(", "'Message.apns must be an in...
https://github.com/firebase/firebase-admin-python/blob/7cfb798ca78f706d08a46c3c48028895787d0ea4/firebase_admin/_messaging_encoder.py#L501-L513
tensorflow/data-validation
6c68c219c5d78d3736fd011d8a7c53fbcb94379c
tensorflow_data_validation/utils/mutual_information_util.py
python
adjusted_mutual_information
( feature_list0: List[np.ndarray], feature_list1: List[np.ndarray], is_categorical_list0: List[bool], is_categorical_list1: List[bool], k: int = 3, estimate_method: str = 'larger_data', weight_feature: Optional[np.ndarray] = None, filter_feature: Optional[np.ndarray] = None, seed: Optional[int] = None, )
return _adjusted_mi_for_arrays(cf_list0, cf_list1, df_list0, df_list1, weights, k, estimate_method, seed)
Computes adjusted MI between two lists of features. Args: feature_list0: (list(np.ndarray)) a list of features represented as numpy arrays. feature_list1: (list(np.ndarray)) a list of features represented as numpy arrays. is_categorical_list0: (list(bool)) Whether the first list of features are categorical or not. is_categorical_list1: (list(bool)) Whether the second list of features are categorical or not. k: (int) The number of nearest neighbors. It has to be an integer no less than 3. estimate_method: (str) 'smaller_data' or 'larger_data' estimator in the above paper. weight_feature: (np.ndarray) numpy array that are weights for each example. filter_feature: (np.ndarray) numpy array that is used as the filter to drop all data where this has missing values. By default, it is None and no filtering is done. seed: (int) the numpy random seed. Returns: The adjusted mutual information between the features in feature_list0 and feature_list1.
Computes adjusted MI between two lists of features.
[ "Computes", "adjusted", "MI", "between", "two", "lists", "of", "features", "." ]
def adjusted_mutual_information( feature_list0: List[np.ndarray], feature_list1: List[np.ndarray], is_categorical_list0: List[bool], is_categorical_list1: List[bool], k: int = 3, estimate_method: str = 'larger_data', weight_feature: Optional[np.ndarray] = None, filter_feature: Optional[np.ndarray] = None, seed: Optional[int] = None, ) -> float: """Computes adjusted MI between two lists of features. Args: feature_list0: (list(np.ndarray)) a list of features represented as numpy arrays. feature_list1: (list(np.ndarray)) a list of features represented as numpy arrays. is_categorical_list0: (list(bool)) Whether the first list of features are categorical or not. is_categorical_list1: (list(bool)) Whether the second list of features are categorical or not. k: (int) The number of nearest neighbors. It has to be an integer no less than 3. estimate_method: (str) 'smaller_data' or 'larger_data' estimator in the above paper. weight_feature: (np.ndarray) numpy array that are weights for each example. filter_feature: (np.ndarray) numpy array that is used as the filter to drop all data where this has missing values. By default, it is None and no filtering is done. seed: (int) the numpy random seed. Returns: The adjusted mutual information between the features in feature_list0 and feature_list1. """ _validate_args(feature_list0, feature_list1, is_categorical_list0, is_categorical_list1, k, estimate_method, weight_feature, filter_feature, False, seed) cf_list0, cf_list1, df_list0, df_list1, weights = _feature_list_to_numpy_arrays( feature_list0, feature_list1, is_categorical_list0, is_categorical_list1, weight_feature, filter_feature) return _adjusted_mi_for_arrays(cf_list0, cf_list1, df_list0, df_list1, weights, k, estimate_method, seed)
[ "def", "adjusted_mutual_information", "(", "feature_list0", ":", "List", "[", "np", ".", "ndarray", "]", ",", "feature_list1", ":", "List", "[", "np", ".", "ndarray", "]", ",", "is_categorical_list0", ":", "List", "[", "bool", "]", ",", "is_categorical_list1",...
https://github.com/tensorflow/data-validation/blob/6c68c219c5d78d3736fd011d8a7c53fbcb94379c/tensorflow_data_validation/utils/mutual_information_util.py#L169-L214
PytLab/simpleflow
72b06c7bca7088352074d6cbdf29578c9c06b657
simpleflow/operations.py
python
Add.__init__
(self, x, y, name=None)
Addition constructor. :param x: The first input node. :type x: Object of `Operation`, `Variable` or `Placeholder`. :param y: The second input node. :type y: Object of `Operation`, `Variable` or `Placeholder`. :param name: The operation name. :type name: str.
Addition constructor.
[ "Addition", "constructor", "." ]
def __init__(self, x, y, name=None): ''' Addition constructor. :param x: The first input node. :type x: Object of `Operation`, `Variable` or `Placeholder`. :param y: The second input node. :type y: Object of `Operation`, `Variable` or `Placeholder`. :param name: The operation name. :type name: str. ''' super(self.__class__, self).__init__(x, y, name=name)
[ "def", "__init__", "(", "self", ",", "x", ",", "y", ",", "name", "=", "None", ")", ":", "super", "(", "self", ".", "__class__", ",", "self", ")", ".", "__init__", "(", "x", ",", "y", ",", "name", "=", "name", ")" ]
https://github.com/PytLab/simpleflow/blob/72b06c7bca7088352074d6cbdf29578c9c06b657/simpleflow/operations.py#L76-L88
kubernetes-client/python
47b9da9de2d02b2b7a34fbe05afb44afd130d73a
kubernetes/client/models/v1_horizontal_pod_autoscaler_status.py
python
V1HorizontalPodAutoscalerStatus.observed_generation
(self)
return self._observed_generation
Gets the observed_generation of this V1HorizontalPodAutoscalerStatus. # noqa: E501 most recent generation observed by this autoscaler. # noqa: E501 :return: The observed_generation of this V1HorizontalPodAutoscalerStatus. # noqa: E501 :rtype: int
Gets the observed_generation of this V1HorizontalPodAutoscalerStatus. # noqa: E501
[ "Gets", "the", "observed_generation", "of", "this", "V1HorizontalPodAutoscalerStatus", ".", "#", "noqa", ":", "E501" ]
def observed_generation(self): """Gets the observed_generation of this V1HorizontalPodAutoscalerStatus. # noqa: E501 most recent generation observed by this autoscaler. # noqa: E501 :return: The observed_generation of this V1HorizontalPodAutoscalerStatus. # noqa: E501 :rtype: int """ return self._observed_generation
[ "def", "observed_generation", "(", "self", ")", ":", "return", "self", ".", "_observed_generation" ]
https://github.com/kubernetes-client/python/blob/47b9da9de2d02b2b7a34fbe05afb44afd130d73a/kubernetes/client/models/v1_horizontal_pod_autoscaler_status.py#L170-L178
seemoo-lab/internalblue
ba6ba0b99f835964395d6dd1b1eb7dd850398fd6
internalblue/core.py
python
InternalBlue.connectToRemoteDevice
(self, bt_addr)
Send a HCI Connect Command to the firmware. This will setup a connection (inserted into the connection structure) if the remote device (specified by bt_addr) accepts. To be exact: This will most likely send - LMP_features_req - LMP_version_req - LMP_features_req_ext - LMP_host_connection_req - LMP_setup_complete and also other channel-related packets to the remote device. The devices do not have to be paired and the remote device does not need to be visible. This will not initiate the pairing sequence, therefore the remote host will not show any notification to the user yet, the host is however notified via HCI that there is an incomming connection. bt_addr: address of remote device (byte string) e.g. for 'f8:95:c7:83:f8:11' you would pass b'\xf8\x95\xc7\x83\xf8\x11'.
Send a HCI Connect Command to the firmware. This will setup a connection (inserted into the connection structure) if the remote device (specified by bt_addr) accepts. To be exact: This will most likely send - LMP_features_req - LMP_version_req - LMP_features_req_ext - LMP_host_connection_req - LMP_setup_complete and also other channel-related packets to the remote device. The devices do not have to be paired and the remote device does not need to be visible. This will not initiate the pairing sequence, therefore the remote host will not show any notification to the user yet, the host is however notified via HCI that there is an incomming connection. bt_addr: address of remote device (byte string) e.g. for 'f8:95:c7:83:f8:11' you would pass b'\xf8\x95\xc7\x83\xf8\x11'.
[ "Send", "a", "HCI", "Connect", "Command", "to", "the", "firmware", ".", "This", "will", "setup", "a", "connection", "(", "inserted", "into", "the", "connection", "structure", ")", "if", "the", "remote", "device", "(", "specified", "by", "bt_addr", ")", "ac...
def connectToRemoteDevice(self, bt_addr): # type: (BluetoothAddress) -> None """ Send a HCI Connect Command to the firmware. This will setup a connection (inserted into the connection structure) if the remote device (specified by bt_addr) accepts. To be exact: This will most likely send - LMP_features_req - LMP_version_req - LMP_features_req_ext - LMP_host_connection_req - LMP_setup_complete and also other channel-related packets to the remote device. The devices do not have to be paired and the remote device does not need to be visible. This will not initiate the pairing sequence, therefore the remote host will not show any notification to the user yet, the host is however notified via HCI that there is an incomming connection. bt_addr: address of remote device (byte string) e.g. for 'f8:95:c7:83:f8:11' you would pass b'\xf8\x95\xc7\x83\xf8\x11'. """ # TODO: expose more of the connection create parameters (instead of # passing 0's. self.sendHciCommand( HCI_COMND.Create_Connection, bt_addr[::-1] + b"\x00\x00\x00\x00\x00\x00\x01" )
[ "def", "connectToRemoteDevice", "(", "self", ",", "bt_addr", ")", ":", "# type: (BluetoothAddress) -> None", "# TODO: expose more of the connection create parameters (instead of", "# passing 0's.", "self", ".", "sendHciCommand", "(", "HCI_COMND", ".", "Create_Connection", "...
https://github.com/seemoo-lab/internalblue/blob/ba6ba0b99f835964395d6dd1b1eb7dd850398fd6/internalblue/core.py#L1785-L1813
ahkab/ahkab
1e8939194b689909b8184ce7eba478b485ff9e3a
ahkab/ekv.py
python
ekv_mos_model.setup_scaling
(self, nq, device)
return
Calculates and stores in self.scaling the following factors: Ut, the thermal voltage, Is, the specific current, Gs, the specific transconductance, Qs, the specific charge.
Calculates and stores in self.scaling the following factors: Ut, the thermal voltage, Is, the specific current, Gs, the specific transconductance, Qs, the specific charge.
[ "Calculates", "and", "stores", "in", "self", ".", "scaling", "the", "following", "factors", ":", "Ut", "the", "thermal", "voltage", "Is", "the", "specific", "current", "Gs", "the", "specific", "transconductance", "Qs", "the", "specific", "charge", "." ]
def setup_scaling(self, nq, device): """Calculates and stores in self.scaling the following factors: Ut, the thermal voltage, Is, the specific current, Gs, the specific transconductance, Qs, the specific charge. """ self.scaling.Ut = constants.Vth() self.scaling.Is = 2 * nq * \ self.scaling.Ut ** 2 * self.KP * device.W / device.L self.scaling.Gs = 2 * nq * \ self.scaling.Ut * self.KP * device.W / device.L self.scaling.Qs = 2 * nq * self.scaling.Ut * self.COX return
[ "def", "setup_scaling", "(", "self", ",", "nq", ",", "device", ")", ":", "self", ".", "scaling", ".", "Ut", "=", "constants", ".", "Vth", "(", ")", "self", ".", "scaling", ".", "Is", "=", "2", "*", "nq", "*", "self", ".", "scaling", ".", "Ut", ...
https://github.com/ahkab/ahkab/blob/1e8939194b689909b8184ce7eba478b485ff9e3a/ahkab/ekv.py#L509-L522
007gzs/dingtalk-sdk
7979da2e259fdbc571728cae2425a04dbc65850a
dingtalk/client/api/taobao.py
python
TbJiuDianShangPin.taobao_xhotel_rooms_update
( self, room_quota_map )
return self._top_request( "taobao.xhotel.rooms.update", { "room_quota_map": room_quota_map }, result_processor=lambda x: x["gids"] )
房型共享库存推送接口(批量全量) 此接口用于更新多个集市酒店商品房态信息,根据传入的gids更新商品信息,该商品必须为对应的发布者才能执行更新操作。如果对应的商品在淘宝集市酒店系统中不存在,则会返回错误提示。是全量更新,非增量,会把之前的房态进行覆盖。 文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=22670 :param room_quota_map: 批量全量推送房型共享库存,一次最多修改30个房型。json encode。示例:[{'out_rid':'hotel1_roomtype22','vendor':'','allotment_start_Time':'','allotment_end_time':'','superbook_start_time':'','superbook_end_time':'','roomQuota':[{'date':2010-01-28,'quota':10,'al_quota':2,'sp_quota':3}]}] 其中al_quota为保留房库存,sp_quota为超预定库存,quota为物理库存。al_quota和sp_quota需要向运营申请权限才可维护。allotment_start_Time和allotment_end_time为保留房库存开始和截止时间;superbook_start_time和superbook_end_time为超预定库存开始和截止时间。
房型共享库存推送接口(批量全量) 此接口用于更新多个集市酒店商品房态信息,根据传入的gids更新商品信息,该商品必须为对应的发布者才能执行更新操作。如果对应的商品在淘宝集市酒店系统中不存在,则会返回错误提示。是全量更新,非增量,会把之前的房态进行覆盖。 文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=22670
[ "房型共享库存推送接口(批量全量)", "此接口用于更新多个集市酒店商品房态信息,根据传入的gids更新商品信息,该商品必须为对应的发布者才能执行更新操作。如果对应的商品在淘宝集市酒店系统中不存在,则会返回错误提示。是全量更新,非增量,会把之前的房态进行覆盖。", "文档地址:https", ":", "//", "open", "-", "doc", ".", "dingtalk", ".", "com", "/", "docs", "/", "api", ".", "htm?apiId", "=", "22670" ]
def taobao_xhotel_rooms_update( self, room_quota_map ): """ 房型共享库存推送接口(批量全量) 此接口用于更新多个集市酒店商品房态信息,根据传入的gids更新商品信息,该商品必须为对应的发布者才能执行更新操作。如果对应的商品在淘宝集市酒店系统中不存在,则会返回错误提示。是全量更新,非增量,会把之前的房态进行覆盖。 文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=22670 :param room_quota_map: 批量全量推送房型共享库存,一次最多修改30个房型。json encode。示例:[{'out_rid':'hotel1_roomtype22','vendor':'','allotment_start_Time':'','allotment_end_time':'','superbook_start_time':'','superbook_end_time':'','roomQuota':[{'date':2010-01-28,'quota':10,'al_quota':2,'sp_quota':3}]}] 其中al_quota为保留房库存,sp_quota为超预定库存,quota为物理库存。al_quota和sp_quota需要向运营申请权限才可维护。allotment_start_Time和allotment_end_time为保留房库存开始和截止时间;superbook_start_time和superbook_end_time为超预定库存开始和截止时间。 """ return self._top_request( "taobao.xhotel.rooms.update", { "room_quota_map": room_quota_map }, result_processor=lambda x: x["gids"] )
[ "def", "taobao_xhotel_rooms_update", "(", "self", ",", "room_quota_map", ")", ":", "return", "self", ".", "_top_request", "(", "\"taobao.xhotel.rooms.update\"", ",", "{", "\"room_quota_map\"", ":", "room_quota_map", "}", ",", "result_processor", "=", "lambda", "x", ...
https://github.com/007gzs/dingtalk-sdk/blob/7979da2e259fdbc571728cae2425a04dbc65850a/dingtalk/client/api/taobao.py#L71590-L71607
scrapinghub/frontera
84f9e1034d2868447db88e865596c0fbb32e70f6
frontera/worker/components/__init__.py
python
DBWorkerBaseComponent.schedule
(self, delay=0)
Schedule component start with optional delay. The function must return None or Deferred.
Schedule component start with optional delay. The function must return None or Deferred.
[ "Schedule", "component", "start", "with", "optional", "delay", ".", "The", "function", "must", "return", "None", "or", "Deferred", "." ]
def schedule(self, delay=0): """Schedule component start with optional delay. The function must return None or Deferred. """ raise NotImplementedError
[ "def", "schedule", "(", "self", ",", "delay", "=", "0", ")", ":", "raise", "NotImplementedError" ]
https://github.com/scrapinghub/frontera/blob/84f9e1034d2868447db88e865596c0fbb32e70f6/frontera/worker/components/__init__.py#L21-L25
kuri65536/python-for-android
26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891
python3-alpha/python-libs/gdata/apps/organization/client.py
python
OrganizationUnitProvisioningClient.retrieve_all_org_units
(self, customer_id, **kwargs)
return self.RetrieveAllOrgUnitsFromUri(uri)
Retrieve all OrgUnits in the customer's domain. Args: customer_id: string The ID of the Google Apps customer. Returns: gdata.apps.organisation.data.OrgUnitFeed object
Retrieve all OrgUnits in the customer's domain.
[ "Retrieve", "all", "OrgUnits", "in", "the", "customer", "s", "domain", "." ]
def retrieve_all_org_units(self, customer_id, **kwargs): """Retrieve all OrgUnits in the customer's domain. Args: customer_id: string The ID of the Google Apps customer. Returns: gdata.apps.organisation.data.OrgUnitFeed object """ uri = self.MakeOrganizationUnitOrgunitProvisioningUri( customer_id, params={'get': 'all'}, **kwargs) return self.RetrieveAllOrgUnitsFromUri(uri)
[ "def", "retrieve_all_org_units", "(", "self", ",", "customer_id", ",", "*", "*", "kwargs", ")", ":", "uri", "=", "self", ".", "MakeOrganizationUnitOrgunitProvisioningUri", "(", "customer_id", ",", "params", "=", "{", "'get'", ":", "'all'", "}", ",", "*", "*"...
https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python3-alpha/python-libs/gdata/apps/organization/client.py#L324-L335
openedx/edx-platform
68dd185a0ab45862a2a61e0f803d7e03d2be71b5
lms/djangoapps/grades/services.py
python
GradesService.undo_override_subsection_grade
(self, user_id, course_key_or_id, usage_key_or_id, feature=api.constants.GradeOverrideFeatureEnum.proctoring)
return api.undo_override_subsection_grade(user_id, course_key_or_id, usage_key_or_id, feature=feature)
Delete the override subsection grade row (the PersistentSubsectionGrade model must already exist) Fires off a recalculate_subsection_grade async task to update the PersistentSubsectionGrade table. If the override does not exist, no error is raised, it just triggers the recalculation.
Delete the override subsection grade row (the PersistentSubsectionGrade model must already exist)
[ "Delete", "the", "override", "subsection", "grade", "row", "(", "the", "PersistentSubsectionGrade", "model", "must", "already", "exist", ")" ]
def undo_override_subsection_grade(self, user_id, course_key_or_id, usage_key_or_id, feature=api.constants.GradeOverrideFeatureEnum.proctoring): """ Delete the override subsection grade row (the PersistentSubsectionGrade model must already exist) Fires off a recalculate_subsection_grade async task to update the PersistentSubsectionGrade table. If the override does not exist, no error is raised, it just triggers the recalculation. """ return api.undo_override_subsection_grade(user_id, course_key_or_id, usage_key_or_id, feature=feature)
[ "def", "undo_override_subsection_grade", "(", "self", ",", "user_id", ",", "course_key_or_id", ",", "usage_key_or_id", ",", "feature", "=", "api", ".", "constants", ".", "GradeOverrideFeatureEnum", ".", "proctoring", ")", ":", "return", "api", ".", "undo_override_su...
https://github.com/openedx/edx-platform/blob/68dd185a0ab45862a2a61e0f803d7e03d2be71b5/lms/djangoapps/grades/services.py#L53-L61
aianaconda/TensorFlow_Engineering_Implementation
cb787e359da9ac5a08d00cd2458fecb4cb5a3a31
code/7-9 mnistkmeans.py
python
inference
(inp, num_clusters, hidden1_units, hidden2_units)
return logits, clustering_loss, kmeans_init, kmeans_training_op
Build the MNIST model up to where it may be used for inference. Args: inp: input data num_clusters: number of clusters of input features to train. hidden1_units: Size of the first hidden layer. hidden2_units: Size of the second hidden layer. Returns: logits: Output tensor with the computed logits. clustering_loss: Clustering loss. kmeans_training_op: An op to train the clustering.
Build the MNIST model up to where it may be used for inference. Args: inp: input data num_clusters: number of clusters of input features to train. hidden1_units: Size of the first hidden layer. hidden2_units: Size of the second hidden layer. Returns: logits: Output tensor with the computed logits. clustering_loss: Clustering loss. kmeans_training_op: An op to train the clustering.
[ "Build", "the", "MNIST", "model", "up", "to", "where", "it", "may", "be", "used", "for", "inference", ".", "Args", ":", "inp", ":", "input", "data", "num_clusters", ":", "number", "of", "clusters", "of", "input", "features", "to", "train", ".", "hidden1_...
def inference(inp, num_clusters, hidden1_units, hidden2_units): """Build the MNIST model up to where it may be used for inference. Args: inp: input data num_clusters: number of clusters of input features to train. hidden1_units: Size of the first hidden layer. hidden2_units: Size of the second hidden layer. Returns: logits: Output tensor with the computed logits. clustering_loss: Clustering loss. kmeans_training_op: An op to train the clustering. """ # Clustering kmeans = tf.contrib.factorization.KMeans( inp, num_clusters, distance_metric=tf.contrib.factorization.COSINE_DISTANCE, # TODO(agarwal): kmeans++ is currently causing crash in dbg mode. # Enable this after fixing. # initial_clusters=tf.contrib.factorization.KMEANS_PLUS_PLUS_INIT, use_mini_batch=True) (all_scores, _, clustering_scores, _, kmeans_init, kmeans_training_op) = kmeans.training_graph() # Some heuristics to approximately whiten this output. all_scores = (all_scores[0] - 0.5) * 5 # Here we avoid passing the gradients from the supervised objective back to # the clusters by creating a stop_gradient node. all_scores = tf.stop_gradient(all_scores) clustering_loss = tf.reduce_sum(clustering_scores[0]) # Hidden 1 with tf.name_scope('hidden1'): weights = tf.Variable( tf.truncated_normal([num_clusters, hidden1_units], stddev=1.0 / math.sqrt(float(IMAGE_PIXELS))), name='weights') biases = tf.Variable(tf.zeros([hidden1_units]), name='biases') hidden1 = tf.nn.relu(tf.matmul(all_scores, weights) + biases) # Hidden 2 with tf.name_scope('hidden2'): weights = tf.Variable( tf.truncated_normal([hidden1_units, hidden2_units], stddev=1.0 / math.sqrt(float(hidden1_units))), name='weights') biases = tf.Variable(tf.zeros([hidden2_units]), name='biases') hidden2 = tf.nn.relu(tf.matmul(hidden1, weights) + biases) # Linear with tf.name_scope('softmax_linear'): weights = tf.Variable( tf.truncated_normal([hidden2_units, NUM_CLASSES], stddev=1.0 / math.sqrt(float(hidden2_units))), name='weights') biases = tf.Variable(tf.zeros([NUM_CLASSES]), name='biases') logits = tf.matmul(hidden2, weights) + biases return logits, clustering_loss, kmeans_init, kmeans_training_op
[ "def", "inference", "(", "inp", ",", "num_clusters", ",", "hidden1_units", ",", "hidden2_units", ")", ":", "# Clustering", "kmeans", "=", "tf", ".", "contrib", ".", "factorization", ".", "KMeans", "(", "inp", ",", "num_clusters", ",", "distance_metric", "=", ...
https://github.com/aianaconda/TensorFlow_Engineering_Implementation/blob/cb787e359da9ac5a08d00cd2458fecb4cb5a3a31/code/7-9 mnistkmeans.py#L96-L153
tensorflow/lattice
784eca50cbdfedf39f183cc7d298c9fe376b69c0
tensorflow_lattice/python/premade_lib.py
python
_verify_feature_config
(feature_config)
Verifies that feature_config is properly specified. Args: feature_config: Feature configuration object describing an input feature to a model. Should be an instance of `tfl.configs.FeatureConfig`. Raises: ValueError: If `feature_config.pwl_calibration_input_keypoints` is not iterable or contains non-{int/float} values for a numerical feature. ValueError: If `feature_config.monotonicity` is not an iterable for a categorical feature. ValueError: If any element in `feature_config.monotonicity` is not an iterable for a categorical feature. ValueError: If any value in any element in `feature_config.monotonicity` is not an int for a categorical feature. ValueError: If any value in any element in `feature_config.monotonicity` is not in the range `[0, feature_config.num_buckets]` for a categorical feature.
Verifies that feature_config is properly specified.
[ "Verifies", "that", "feature_config", "is", "properly", "specified", "." ]
def _verify_feature_config(feature_config): """Verifies that feature_config is properly specified. Args: feature_config: Feature configuration object describing an input feature to a model. Should be an instance of `tfl.configs.FeatureConfig`. Raises: ValueError: If `feature_config.pwl_calibration_input_keypoints` is not iterable or contains non-{int/float} values for a numerical feature. ValueError: If `feature_config.monotonicity` is not an iterable for a categorical feature. ValueError: If any element in `feature_config.monotonicity` is not an iterable for a categorical feature. ValueError: If any value in any element in `feature_config.monotonicity` is not an int for a categorical feature. ValueError: If any value in any element in `feature_config.monotonicity` is not in the range `[0, feature_config.num_buckets]` for a categorical feature. """ if not feature_config.num_buckets: # Validate PWL Calibration configuration. if (not np.iterable(feature_config.pwl_calibration_input_keypoints) or any(not isinstance(x, (int, float)) for x in feature_config.pwl_calibration_input_keypoints)): raise ValueError('Input keypoints are invalid for feature {}: {}'.format( feature_config.name, feature_config.pwl_calibration_input_keypoints)) elif feature_config.monotonicity and feature_config.monotonicity != 'none': # Validate Categorical Calibration configuration. if not np.iterable(feature_config.monotonicity): raise ValueError('Monotonicity is not a list for feature {}: {}'.format( feature_config.name, feature_config.monotonicity)) for i, t in enumerate(feature_config.monotonicity): if not np.iterable(t): raise ValueError( 'Element {} is not a list/tuple for feature {} monotonicty: {}' .format(i, feature_config.name, t)) for j, val in enumerate(t): if not isinstance(val, int): raise ValueError( 'Element {} for list/tuple {} for feature {} monotonicity is ' 'not an index: {}'.format(j, i, feature_config.name, val)) if val < 0 or val >= feature_config.num_buckets: raise ValueError( 'Element {} for list/tuple {} for feature {} monotonicity is ' 'an invalid index not in range [0, num_buckets - 1]: {}'.format( j, i, feature_config.name, val))
[ "def", "_verify_feature_config", "(", "feature_config", ")", ":", "if", "not", "feature_config", ".", "num_buckets", ":", "# Validate PWL Calibration configuration.", "if", "(", "not", "np", ".", "iterable", "(", "feature_config", ".", "pwl_calibration_input_keypoints", ...
https://github.com/tensorflow/lattice/blob/784eca50cbdfedf39f183cc7d298c9fe376b69c0/tensorflow_lattice/python/premade_lib.py#L1509-L1555
thu-coai/ConvLab-2
ad32b76022fa29cbc2f24cbefbb855b60492985e
convlab2/evaluator/multiwoz_eval.py
python
MultiWozEvaluator.domain_success
(self, domain, ref2goal=True)
judge if the domain (subtask) is successfully completed
judge if the domain (subtask) is successfully completed
[ "judge", "if", "the", "domain", "(", "subtask", ")", "is", "successfully", "completed" ]
def domain_success(self, domain, ref2goal=True): """ judge if the domain (subtask) is successfully completed """ if domain not in self.goal: return None if ref2goal: goal = {} goal[domain] = self._expand(self.goal)[domain] else: goal = {} goal[domain] = {'info': {}, 'book': {}, 'reqt': []} if 'book' in self.goal[domain]: goal[domain]['book'] = self.goal[domain]['book'] for da in self.usr_da_array: d, i, s, v = da.split('-', 3) if d != domain: continue if i in ['inform', 'recommend', 'offerbook', 'offerbooked'] and s in mapping[d]: goal[d]['info'][mapping[d][s]] = v elif i == 'request': goal[d]['reqt'].append(s) book_rate = self._book_rate_goal(goal, self.booked, [domain]) book_rate = np.mean(book_rate) if book_rate else None inform = self._inform_F1_goal(goal, self.sys_da_array, [domain]) try: inform_rec = inform[0] / (inform[0] + inform[2]) except ZeroDivisionError: inform_rec = None if (book_rate == 1 and inform_rec == 1) \ or (book_rate == 1 and inform_rec is None) \ or (book_rate is None and inform_rec == 1): return 1 else: return 0
[ "def", "domain_success", "(", "self", ",", "domain", ",", "ref2goal", "=", "True", ")", ":", "if", "domain", "not", "in", "self", ".", "goal", ":", "return", "None", "if", "ref2goal", ":", "goal", "=", "{", "}", "goal", "[", "domain", "]", "=", "se...
https://github.com/thu-coai/ConvLab-2/blob/ad32b76022fa29cbc2f24cbefbb855b60492985e/convlab2/evaluator/multiwoz_eval.py#L335-L373
algorithmiaio/algorithmia-python
7fd688d75baafe071beb964e250450fd738ca17c
Algorithmia/data.py
python
DataObject.get_type
(self)
return self.data_object_type
Returns type of this DataObject
Returns type of this DataObject
[ "Returns", "type", "of", "this", "DataObject" ]
def get_type(self): '''Returns type of this DataObject''' return self.data_object_type
[ "def", "get_type", "(", "self", ")", ":", "return", "self", ".", "data_object_type" ]
https://github.com/algorithmiaio/algorithmia-python/blob/7fd688d75baafe071beb964e250450fd738ca17c/Algorithmia/data.py#L17-L19
openedx/edx-platform
68dd185a0ab45862a2a61e0f803d7e03d2be71b5
common/lib/xmodule/xmodule/modulestore/mongo/base.py
python
CachingDescriptorSystem.get_subtree_edited_on
(self, xblock)
return xblock._edit_info.get('subtree_edited_on')
See :class: cms.lib.xblock.runtime.EditInfoRuntimeMixin
See :class: cms.lib.xblock.runtime.EditInfoRuntimeMixin
[ "See", ":", "class", ":", "cms", ".", "lib", ".", "xblock", ".", "runtime", ".", "EditInfoRuntimeMixin" ]
def get_subtree_edited_on(self, xblock): """ See :class: cms.lib.xblock.runtime.EditInfoRuntimeMixin """ return xblock._edit_info.get('subtree_edited_on')
[ "def", "get_subtree_edited_on", "(", "self", ",", "xblock", ")", ":", "return", "xblock", ".", "_edit_info", ".", "get", "(", "'subtree_edited_on'", ")" ]
https://github.com/openedx/edx-platform/blob/68dd185a0ab45862a2a61e0f803d7e03d2be71b5/common/lib/xmodule/xmodule/modulestore/mongo/base.py#L395-L399
gramps-project/gramps
04d4651a43eb210192f40a9f8c2bad8ee8fa3753
gramps/plugins/lib/libtreebase.py
python
Page.is_blank
(self)
return self.boxes == [] and self.lines == []
Am I a blank page? Notes and Titles are boxes too
Am I a blank page? Notes and Titles are boxes too
[ "Am", "I", "a", "blank", "page?", "Notes", "and", "Titles", "are", "boxes", "too" ]
def is_blank(self): """ Am I a blank page? Notes and Titles are boxes too """ return self.boxes == [] and self.lines == []
[ "def", "is_blank", "(", "self", ")", ":", "return", "self", ".", "boxes", "==", "[", "]", "and", "self", ".", "lines", "==", "[", "]" ]
https://github.com/gramps-project/gramps/blob/04d4651a43eb210192f40a9f8c2bad8ee8fa3753/gramps/plugins/lib/libtreebase.py#L106-L108
henkelis/sonospy
841f52010fd6e1e932d8f1a8896ad4e5a0667b8a
web2py/gluon/sneaky3.py
python
Sneaky.set_listen_queue_size
(self)
tries a listen argument that works
tries a listen argument that works
[ "tries", "a", "listen", "argument", "that", "works" ]
def set_listen_queue_size(self): """tries a listen argument that works""" if self.request_queue_size: self.socket.listen(self.request_queue_size) else: for request_queue_size in [1024,128,5,1]: try: self.socket.listen(request_queue_size) break except: pass
[ "def", "set_listen_queue_size", "(", "self", ")", ":", "if", "self", ".", "request_queue_size", ":", "self", ".", "socket", ".", "listen", "(", "self", ".", "request_queue_size", ")", "else", ":", "for", "request_queue_size", "in", "[", "1024", ",", "128", ...
https://github.com/henkelis/sonospy/blob/841f52010fd6e1e932d8f1a8896ad4e5a0667b8a/web2py/gluon/sneaky3.py#L376-L386
pynag/pynag
e72cf7ce2395263e2b3080cae0ece2b03dbbfa27
pynag/Utils/metrics.py
python
PerfDataMetric.__repr__
(self)
return "'%s'=%s%s;%s;%s;%s;%s" % ( self.label, self.value, self.uom, self.warn, self.crit, self.min, self.max, )
[]
def __repr__(self): return "'%s'=%s%s;%s;%s;%s;%s" % ( self.label, self.value, self.uom, self.warn, self.crit, self.min, self.max, )
[ "def", "__repr__", "(", "self", ")", ":", "return", "\"'%s'=%s%s;%s;%s;%s;%s\"", "%", "(", "self", ".", "label", ",", "self", ".", "value", ",", "self", ".", "uom", ",", "self", ".", "warn", ",", "self", ".", "crit", ",", "self", ".", "min", ",", "...
https://github.com/pynag/pynag/blob/e72cf7ce2395263e2b3080cae0ece2b03dbbfa27/pynag/Utils/metrics.py#L77-L86
burke-software/schooldriver
a07262ba864aee0182548ecceb661e49c925725f
appy/fields/pod.py
python
Pod.getTemplateName
(self, obj, fileName)
return res
Gets the name of a template given its p_fileName.
Gets the name of a template given its p_fileName.
[ "Gets", "the", "name", "of", "a", "template", "given", "its", "p_fileName", "." ]
def getTemplateName(self, obj, fileName): '''Gets the name of a template given its p_fileName.''' res = None if self.templateName: # Use the method specified in self.templateName. res = self.templateName(obj, fileName) # Else, deduce a nice name from p_fileName. if not res: name = os.path.splitext(os.path.basename(fileName))[0] res = gutils.produceNiceMessage(name) return res
[ "def", "getTemplateName", "(", "self", ",", "obj", ",", "fileName", ")", ":", "res", "=", "None", "if", "self", ".", "templateName", ":", "# Use the method specified in self.templateName.", "res", "=", "self", ".", "templateName", "(", "obj", ",", "fileName", ...
https://github.com/burke-software/schooldriver/blob/a07262ba864aee0182548ecceb661e49c925725f/appy/fields/pod.py#L208-L218
Source-Python-Dev-Team/Source.Python
d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb
addons/source-python/Python3/mailcap.py
python
listmailcapfiles
()
return mailcaps
Return a list of all mailcap files found on the system.
Return a list of all mailcap files found on the system.
[ "Return", "a", "list", "of", "all", "mailcap", "files", "found", "on", "the", "system", "." ]
def listmailcapfiles(): """Return a list of all mailcap files found on the system.""" # This is mostly a Unix thing, but we use the OS path separator anyway if 'MAILCAPS' in os.environ: pathstr = os.environ['MAILCAPS'] mailcaps = pathstr.split(os.pathsep) else: if 'HOME' in os.environ: home = os.environ['HOME'] else: # Don't bother with getpwuid() home = '.' # Last resort mailcaps = [home + '/.mailcap', '/etc/mailcap', '/usr/etc/mailcap', '/usr/local/etc/mailcap'] return mailcaps
[ "def", "listmailcapfiles", "(", ")", ":", "# This is mostly a Unix thing, but we use the OS path separator anyway", "if", "'MAILCAPS'", "in", "os", ".", "environ", ":", "pathstr", "=", "os", ".", "environ", "[", "'MAILCAPS'", "]", "mailcaps", "=", "pathstr", ".", "s...
https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/Python3/mailcap.py#L45-L59
abunsen/Paython
22f7467e1307b8c005609526af6ec4c252a1bae3
paython/lib/utils.py
python
is_valid_email
(email)
return re.search(pat, email, re.IGNORECASE)
Based on "The Perfect E-Mail Regex" : http://fightingforalostcause.net/misc/2006/compare-email-regex.php
Based on "The Perfect E-Mail Regex" : http://fightingforalostcause.net/misc/2006/compare-email-regex.php
[ "Based", "on", "The", "Perfect", "E", "-", "Mail", "Regex", ":", "http", ":", "//", "fightingforalostcause", ".", "net", "/", "misc", "/", "2006", "/", "compare", "-", "email", "-", "regex", ".", "php" ]
def is_valid_email(email): """ Based on "The Perfect E-Mail Regex" : http://fightingforalostcause.net/misc/2006/compare-email-regex.php """ pat = '^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$' return re.search(pat, email, re.IGNORECASE)
[ "def", "is_valid_email", "(", "email", ")", ":", "pat", "=", "'^([\\w\\!\\#$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\`{\\|\\}\\~]+\\.)*[\\w\\!\\#$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\`{\\|\\}\\~]+@((((([a-z0-9]{1}[a-z0-9\\-]{0,62}[a-z0-9]{1})|[a-z])\\.)+[a-z]{2,6})|(\\d{1,3}\\.){3}\\d{1,3}(\\:\\d{1,5})?)$'", "r...
https://github.com/abunsen/Paython/blob/22f7467e1307b8c005609526af6ec4c252a1bae3/paython/lib/utils.py#L116-L121
nltk/nltk
3f74ac55681667d7ef78b664557487145f51eb02
nltk/corpus/reader/framenet.py
python
FramenetCorpusReader.semtype
(self, key)
return st
>>> from nltk.corpus import framenet as fn >>> fn.semtype(233).name 'Temperature' >>> fn.semtype(233).abbrev 'Temp' >>> fn.semtype('Temperature').ID 233 :param key: The name, abbreviation, or id number of the semantic type :type key: string or int :return: Information about a semantic type :rtype: dict
>>> from nltk.corpus import framenet as fn >>> fn.semtype(233).name 'Temperature' >>> fn.semtype(233).abbrev 'Temp' >>> fn.semtype('Temperature').ID 233
[ ">>>", "from", "nltk", ".", "corpus", "import", "framenet", "as", "fn", ">>>", "fn", ".", "semtype", "(", "233", ")", ".", "name", "Temperature", ">>>", "fn", ".", "semtype", "(", "233", ")", ".", "abbrev", "Temp", ">>>", "fn", ".", "semtype", "(", ...
def semtype(self, key): """ >>> from nltk.corpus import framenet as fn >>> fn.semtype(233).name 'Temperature' >>> fn.semtype(233).abbrev 'Temp' >>> fn.semtype('Temperature').ID 233 :param key: The name, abbreviation, or id number of the semantic type :type key: string or int :return: Information about a semantic type :rtype: dict """ if isinstance(key, int): stid = key else: try: stid = self._semtypes[key] except TypeError: self._loadsemtypes() stid = self._semtypes[key] try: st = self._semtypes[stid] except TypeError: self._loadsemtypes() st = self._semtypes[stid] return st
[ "def", "semtype", "(", "self", ",", "key", ")", ":", "if", "isinstance", "(", "key", ",", "int", ")", ":", "stid", "=", "key", "else", ":", "try", ":", "stid", "=", "self", ".", "_semtypes", "[", "key", "]", "except", "TypeError", ":", "self", "....
https://github.com/nltk/nltk/blob/3f74ac55681667d7ef78b664557487145f51eb02/nltk/corpus/reader/framenet.py#L1931-L1961
ni/nidaqmx-python
62fc6b48cbbb330fe1bcc9aedadc86610a1269b6
nidaqmx/_task_modules/channels/ci_channel.py
python
CIChannel.ci_two_edge_sep_second_dig_fltr_min_pulse_width
(self)
return val.value
float: Specifies in seconds the minimum pulse width the filter recognizes.
float: Specifies in seconds the minimum pulse width the filter recognizes.
[ "float", ":", "Specifies", "in", "seconds", "the", "minimum", "pulse", "width", "the", "filter", "recognizes", "." ]
def ci_two_edge_sep_second_dig_fltr_min_pulse_width(self): """ float: Specifies in seconds the minimum pulse width the filter recognizes. """ val = ctypes.c_double() cfunc = (lib_importer.windll. DAQmxGetCITwoEdgeSepSecondDigFltrMinPulseWidth) if cfunc.argtypes is None: with cfunc.arglock: if cfunc.argtypes is None: cfunc.argtypes = [ lib_importer.task_handle, ctypes_byte_str, ctypes.POINTER(ctypes.c_double)] error_code = cfunc( self._handle, self._name, ctypes.byref(val)) check_for_error(error_code) return val.value
[ "def", "ci_two_edge_sep_second_dig_fltr_min_pulse_width", "(", "self", ")", ":", "val", "=", "ctypes", ".", "c_double", "(", ")", "cfunc", "=", "(", "lib_importer", ".", "windll", ".", "DAQmxGetCITwoEdgeSepSecondDigFltrMinPulseWidth", ")", "if", "cfunc", ".", "argty...
https://github.com/ni/nidaqmx-python/blob/62fc6b48cbbb330fe1bcc9aedadc86610a1269b6/nidaqmx/_task_modules/channels/ci_channel.py#L10230-L10250
reahl/reahl
86aac47c3a9b5b98e9f77dad4939034a02d54d46
reahl-webdev/reahl/webdev/webserver.py
python
ReahlWebServer.in_background
(self, wait_till_done_serving=True)
Returns a context manager. Within the context of this context manager, the webserver is temporarily run in a separate thread. After the context managed by this context manager is exited, the server reverts to handling requests in the current (test) thread. :keyword wait_till_done_serving: If True, wait for the server to finish its background job before exiting the context block.
Returns a context manager. Within the context of this context manager, the webserver is temporarily run in a separate thread. After the context managed by this context manager is exited, the server reverts to handling requests in the current (test) thread.
[ "Returns", "a", "context", "manager", ".", "Within", "the", "context", "of", "this", "context", "manager", "the", "webserver", "is", "temporarily", "run", "in", "a", "separate", "thread", ".", "After", "the", "context", "managed", "by", "this", "context", "m...
def in_background(self, wait_till_done_serving=True): """Returns a context manager. Within the context of this context manager, the webserver is temporarily run in a separate thread. After the context managed by this context manager is exited, the server reverts to handling requests in the current (test) thread. :keyword wait_till_done_serving: If True, wait for the server to finish its background job before exiting the context block. """ self.restore_handlers() self.start_thread() try: yield finally: try: self.stop_thread(join=wait_till_done_serving) finally: self.reinstall_handlers()
[ "def", "in_background", "(", "self", ",", "wait_till_done_serving", "=", "True", ")", ":", "self", ".", "restore_handlers", "(", ")", "self", ".", "start_thread", "(", ")", "try", ":", "yield", "finally", ":", "try", ":", "self", ".", "stop_thread", "(", ...
https://github.com/reahl/reahl/blob/86aac47c3a9b5b98e9f77dad4939034a02d54d46/reahl-webdev/reahl/webdev/webserver.py#L552-L567
JaniceWuo/MovieRecommend
4c86db64ca45598917d304f535413df3bc9fea65
movierecommend/venv1/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/html5lib/_tokenizer.py
python
HTMLTokenizer.beforeAttributeValueState
(self)
return True
[]
def beforeAttributeValueState(self): data = self.stream.char() if data in spaceCharacters: self.stream.charsUntil(spaceCharacters, True) elif data == "\"": self.state = self.attributeValueDoubleQuotedState elif data == "&": self.state = self.attributeValueUnQuotedState self.stream.unget(data) elif data == "'": self.state = self.attributeValueSingleQuotedState elif data == ">": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-attribute-value-but-got-right-bracket"}) self.emitCurrentToken() elif data == "\u0000": self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) self.currentToken["data"][-1][1] += "\uFFFD" self.state = self.attributeValueUnQuotedState elif data in ("=", "<", "`"): self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "equals-in-unquoted-attribute-value"}) self.currentToken["data"][-1][1] += data self.state = self.attributeValueUnQuotedState elif data is EOF: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "expected-attribute-value-but-got-eof"}) self.state = self.dataState else: self.currentToken["data"][-1][1] += data self.state = self.attributeValueUnQuotedState return True
[ "def", "beforeAttributeValueState", "(", "self", ")", ":", "data", "=", "self", ".", "stream", ".", "char", "(", ")", "if", "data", "in", "spaceCharacters", ":", "self", ".", "stream", ".", "charsUntil", "(", "spaceCharacters", ",", "True", ")", "elif", ...
https://github.com/JaniceWuo/MovieRecommend/blob/4c86db64ca45598917d304f535413df3bc9fea65/movierecommend/venv1/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/html5lib/_tokenizer.py#L959-L991
google/transitfeed
d727e97cb66ac2ca2d699a382ea1d449ee26c2a1
transitfeed/schedule.py
python
Schedule.GetServicePeriod
(self, service_id)
return self.service_periods[service_id]
Returns the ServicePeriod object with the given ID.
Returns the ServicePeriod object with the given ID.
[ "Returns", "the", "ServicePeriod", "object", "with", "the", "given", "ID", "." ]
def GetServicePeriod(self, service_id): """Returns the ServicePeriod object with the given ID.""" return self.service_periods[service_id]
[ "def", "GetServicePeriod", "(", "self", ",", "service_id", ")", ":", "return", "self", ".", "service_periods", "[", "service_id", "]" ]
https://github.com/google/transitfeed/blob/d727e97cb66ac2ca2d699a382ea1d449ee26c2a1/transitfeed/schedule.py#L217-L219
DingGuodong/LinuxBashShellScriptForOps
d5727b985f920292a10698a3c9751d5dff5fc1a3
projects/LinuxSystemOps/AutoDevOps/Ansible/pyAnsibleGatheringFacts.py
python
get_bin_path
(arg, required=False, opt_dirs=None)
return bin_path
find system executable in PATH. Optional arguments: - required: if executable is not found and required is true - opt_dirs: optional list of directories to search in addition to PATH if found return full path; otherwise return None
find system executable in PATH. Optional arguments: - required: if executable is not found and required is true - opt_dirs: optional list of directories to search in addition to PATH if found return full path; otherwise return None
[ "find", "system", "executable", "in", "PATH", ".", "Optional", "arguments", ":", "-", "required", ":", "if", "executable", "is", "not", "found", "and", "required", "is", "true", "-", "opt_dirs", ":", "optional", "list", "of", "directories", "to", "search", ...
def get_bin_path(arg, required=False, opt_dirs=None): """ find system executable in PATH. Optional arguments: - required: if executable is not found and required is true - opt_dirs: optional list of directories to search in addition to PATH if found return full path; otherwise return None """ sbin_paths = ['/sbin', '/usr/sbin', '/usr/local/sbin'] paths = [] # https://stackoverflow.com/questions/9039191/mutable-default-method-arguments-in-python # https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument if not opt_dirs: opt_dirs = [] for d in opt_dirs: if d is not None and os.path.exists(d): paths.append(d) paths += os.environ.get('PATH', '').split(os.pathsep) bin_path = None # mangle PATH to include /sbin dirs for p in sbin_paths: if p not in paths and os.path.exists(p): paths.append(p) for d in paths: if not d: continue path = os.path.join(d, arg) if os.path.exists(path) and not os.path.isdir(path) and is_executable(path): bin_path = path break if required and bin_path is None: print 'Failed to find required executable %s in paths: %s' % (arg, os.pathsep.join(paths)) return bin_path
[ "def", "get_bin_path", "(", "arg", ",", "required", "=", "False", ",", "opt_dirs", "=", "None", ")", ":", "sbin_paths", "=", "[", "'/sbin'", ",", "'/usr/sbin'", ",", "'/usr/local/sbin'", "]", "paths", "=", "[", "]", "# https://stackoverflow.com/questions/9039191...
https://github.com/DingGuodong/LinuxBashShellScriptForOps/blob/d5727b985f920292a10698a3c9751d5dff5fc1a3/projects/LinuxSystemOps/AutoDevOps/Ansible/pyAnsibleGatheringFacts.py#L199-L233
HaloOrangeWang/NoiseMaker
c4adb1e4e5055b0c26f80060a9fe9920fa93e03b
MakerSrc/validations/melody.py
python
ShiftConfidenceCheck.train_1song
(self, **kwargs)
获取主旋律连续两小节(不跨越乐段)的音高变化得分 分数为(音高变化/时间差)的平方和 kwargs['section_data']: 这首歌的乐段数据 kwargs['raw_melody_data']: 一首歌的主旋律数据
获取主旋律连续两小节(不跨越乐段)的音高变化得分 分数为(音高变化/时间差)的平方和 kwargs['section_data']: 这首歌的乐段数据 kwargs['raw_melody_data']: 一首歌的主旋律数据
[ "获取主旋律连续两小节(不跨越乐段)的音高变化得分", "分数为(音高变化", "/", "时间差)的平方和", "kwargs", "[", "section_data", "]", ":", "这首歌的乐段数据", "kwargs", "[", "raw_melody_data", "]", ":", "一首歌的主旋律数据" ]
def train_1song(self, **kwargs): """ 获取主旋律连续两小节(不跨越乐段)的音高变化得分 分数为(音高变化/时间差)的平方和 kwargs['section_data']: 这首歌的乐段数据 kwargs['raw_melody_data']: 一首歌的主旋律数据 """ raw_melody_data = kwargs['raw_melody_data'] sec_data = kwargs['section_data'] section_data = copy.deepcopy(sec_data) score_ary = [] if section_data: # 训练集中的部分歌没有乐段 section_data.sort() # 按照小节先后顺序排序 for bar_it in range(0, len(raw_melody_data) // 32 - 1): shift_score = 0 sec_dx = -1 # 记录这一拍属于这首歌的第几个乐段 if section_data: # 有乐段的情况下 当这个小节和下一小节均不为空且不跨越乐段时进行收录 for sec_it in range(len(section_data)): if section_data[sec_it][0] * 4 + section_data[sec_it][1] > bar_it * 4: # 将区段的起始拍和当前拍进行比较 如果起始拍在当前拍之前则说明是属于这个区段 sec_dx = sec_it - 1 break if sec_dx == -1: sec_dx = len(section_data) - 1 # 属于这首歌的最后一个区段 if section_data[sec_dx][2] == DEF_SEC_EMPTY: # 这个乐段是间奏 不进行分数选择 continue if sec_dx != len(section_data) - 1: if section_data[sec_dx + 1][0] * 4 + section_data[sec_dx + 1][1] < (bar_it + 2) * 4: continue # 出现跨越乐段的情况,不收录 else: if raw_melody_data[bar_it * 32: (bar_it + 1) * 32] == [0] * 32 or raw_melody_data[(bar_it + 1) * 32: (bar_it + 2) * 32] == [0] * 32: continue # 没有乐段的情况下 这一小节和下一小节均不能为空 last_note = -1 # 上一个音符的音高 last_note_step = -1 # 上一个音符所在的位置 note_count = 0 # 两小节一共多少音符 # for cal_bar_it in range(bar_it, bar_it + 2): for step_it in range(64): if raw_melody_data[bar_it * 32 + step_it] != 0: # 计算变化分 if last_note > 0: step_diff = step_it - last_note_step shift_score += (raw_melody_data[bar_it * 32 + step_it] - last_note) * (raw_melody_data[bar_it * 32 + step_it] - last_note) / (step_diff * step_diff) last_note = raw_melody_data[bar_it * 32 + step_it] last_note_step = step_it note_count += 1 if note_count == 1: # 只有一个音符的情况下,音高差异分为0分 score_ary.append(0) elif note_count > 1: score_ary.append(shift_score / (note_count - 1)) self.evaluating_score_list.extend(score_ary)
[ "def", "train_1song", "(", "self", ",", "*", "*", "kwargs", ")", ":", "raw_melody_data", "=", "kwargs", "[", "'raw_melody_data'", "]", "sec_data", "=", "kwargs", "[", "'section_data'", "]", "section_data", "=", "copy", ".", "deepcopy", "(", "sec_data", ")", ...
https://github.com/HaloOrangeWang/NoiseMaker/blob/c4adb1e4e5055b0c26f80060a9fe9920fa93e03b/MakerSrc/validations/melody.py#L110-L157
ronf/asyncssh
ee1714c598d8c2ea6f5484e465443f38b68714aa
asyncssh/stream.py
python
SSHStreamSession.readuntil
(self, separator: object, datatype: DataType)
Read data from the channel until a separator is seen
Read data from the channel until a separator is seen
[ "Read", "data", "from", "the", "channel", "until", "a", "separator", "is", "seen" ]
async def readuntil(self, separator: object, datatype: DataType) -> AnyStr: """Read data from the channel until a separator is seen""" if not separator: raise ValueError('Separator cannot be empty') buf = cast(AnyStr, '' if self._encoding else b'') recv_buf = self._recv_buf[datatype] if separator is _NEWLINE: seplen = 1 separators = cast(AnyStr, '\n' if self._encoding else b'\n') elif isinstance(separator, (bytes, str)): seplen = len(separator) separators = cast(AnyStr, separator) else: bar = cast(AnyStr, '|' if self._encoding else b'|') seplist = list(cast(Iterable[AnyStr], separator)) seplen = max(len(sep) for sep in seplist) separators = bar.join(re.escape(sep) for sep in seplist) pat = re.compile(separators) curbuf = 0 buflen = 0 async with self._read_locks[datatype]: while True: while curbuf < len(recv_buf): if isinstance(recv_buf[curbuf], Exception): if buf: recv_buf[:curbuf] = [] self._recv_buf_len -= buflen raise asyncio.IncompleteReadError( cast(bytes, buf), None) else: exc = recv_buf.pop(0) if isinstance(exc, SoftEOFReceived): return buf else: raise cast(Exception, exc) newbuf = cast(AnyStr, recv_buf[curbuf]) buf += newbuf start = max(buflen + 1 - seplen, 0) match = pat.search(buf, start) if match: idx = match.end() recv_buf[:curbuf] = [] recv_buf[0] = buf[idx:] buf = buf[:idx] self._recv_buf_len -= idx if not recv_buf[0]: recv_buf.pop(0) self._maybe_resume_reading() return buf buflen += len(newbuf) curbuf += 1 if self._read_paused or self._eof_received: recv_buf[:curbuf] = [] self._recv_buf_len -= buflen self._maybe_resume_reading() raise asyncio.IncompleteReadError(cast(bytes, buf), None) await self._block_read(datatype)
[ "async", "def", "readuntil", "(", "self", ",", "separator", ":", "object", ",", "datatype", ":", "DataType", ")", "->", "AnyStr", ":", "if", "not", "separator", ":", "raise", "ValueError", "(", "'Separator cannot be empty'", ")", "buf", "=", "cast", "(", "...
https://github.com/ronf/asyncssh/blob/ee1714c598d8c2ea6f5484e465443f38b68714aa/asyncssh/stream.py#L558-L627
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/utils/decorators/__init__.py
python
Depends.__init__
(self, *dependencies, **kwargs)
The decorator is instantiated with a list of dependencies (string of global name) An example use of this would be: .. code-block:: python @depends('modulename') def test(): return 'foo' OR @depends('modulename', fallback_function=function) def test(): return 'foo' .. code-block:: python This can also be done with the retcode of a command, using the ``retcode`` argument: @depends('/opt/bin/check_cmd', retcode=0) def test(): return 'foo' It is also possible to check for any nonzero retcode using the ``nonzero_retcode`` argument: @depends('/opt/bin/check_cmd', nonzero_retcode=True) def test(): return 'foo' .. note:: The command must be formatted as a string, not a list of args. Additionally, I/O redirection and other shell-specific syntax are not supported since this uses shell=False when calling subprocess.Popen().
The decorator is instantiated with a list of dependencies (string of global name)
[ "The", "decorator", "is", "instantiated", "with", "a", "list", "of", "dependencies", "(", "string", "of", "global", "name", ")" ]
def __init__(self, *dependencies, **kwargs): """ The decorator is instantiated with a list of dependencies (string of global name) An example use of this would be: .. code-block:: python @depends('modulename') def test(): return 'foo' OR @depends('modulename', fallback_function=function) def test(): return 'foo' .. code-block:: python This can also be done with the retcode of a command, using the ``retcode`` argument: @depends('/opt/bin/check_cmd', retcode=0) def test(): return 'foo' It is also possible to check for any nonzero retcode using the ``nonzero_retcode`` argument: @depends('/opt/bin/check_cmd', nonzero_retcode=True) def test(): return 'foo' .. note:: The command must be formatted as a string, not a list of args. Additionally, I/O redirection and other shell-specific syntax are not supported since this uses shell=False when calling subprocess.Popen(). """ log.trace( "Depends decorator instantiated with dep list of %s and kwargs %s", dependencies, kwargs, ) self.dependencies = dependencies self.params = kwargs
[ "def", "__init__", "(", "self", ",", "*", "dependencies", ",", "*", "*", "kwargs", ")", ":", "log", ".", "trace", "(", "\"Depends decorator instantiated with dep list of %s and kwargs %s\"", ",", "dependencies", ",", "kwargs", ",", ")", "self", ".", "dependencies"...
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/utils/decorators/__init__.py#L42-L90
simoncadman/CUPS-Cloud-Print
5d96eaa5ba1d3ffe40845498917879b0e907f6bd
oauth2client/locked_file.py
python
LockedFile.filename
(self)
return self._opener._filename
Return the filename we were constructed with.
Return the filename we were constructed with.
[ "Return", "the", "filename", "we", "were", "constructed", "with", "." ]
def filename(self): """Return the filename we were constructed with.""" return self._opener._filename
[ "def", "filename", "(", "self", ")", ":", "return", "self", ".", "_opener", ".", "_filename" ]
https://github.com/simoncadman/CUPS-Cloud-Print/blob/5d96eaa5ba1d3ffe40845498917879b0e907f6bd/oauth2client/locked_file.py#L349-L351
kivy/kivy-designer
20343184a28c2851faf0c1ab451d0286d147a441
designer/core/project_manager.py
python
ProjectWatcher.stop_watching
(self)
To stop watching currently watched directory. This will also call join() on the thread created by Observer.
To stop watching currently watched directory. This will also call join() on the thread created by Observer.
[ "To", "stop", "watching", "currently", "watched", "directory", ".", "This", "will", "also", "call", "join", "()", "on", "the", "thread", "created", "by", "Observer", "." ]
def stop_watching(self): '''To stop watching currently watched directory. This will also call join() on the thread created by Observer. ''' if self._observer: self._observer.unschedule_all() self._observer.stop() self._observer.join() self._observer = None
[ "def", "stop_watching", "(", "self", ")", ":", "if", "self", ".", "_observer", ":", "self", ".", "_observer", ".", "unschedule_all", "(", ")", "self", ".", "_observer", ".", "stop", "(", ")", "self", ".", "_observer", ".", "join", "(", ")", "self", "...
https://github.com/kivy/kivy-designer/blob/20343184a28c2851faf0c1ab451d0286d147a441/designer/core/project_manager.py#L89-L99
phonopy/phonopy
816586d0ba8177482ecf40e52f20cbdee2260d51
phonopy/harmonic/dynamical_matrix.py
python
DynamicalMatrixNAC.nac_method
(self)
return self._method
Return NAC method name.
Return NAC method name.
[ "Return", "NAC", "method", "name", "." ]
def nac_method(self): """Return NAC method name.""" return self._method
[ "def", "nac_method", "(", "self", ")", ":", "return", "self", ".", "_method" ]
https://github.com/phonopy/phonopy/blob/816586d0ba8177482ecf40e52f20cbdee2260d51/phonopy/harmonic/dynamical_matrix.py#L457-L459
spotify/luigi
c3b66f4a5fa7eaa52f9a72eb6704b1049035c789
luigi/execution_summary.py
python
_get_number_of_tasks_for
(status, group_tasks)
return _get_number_of_tasks(group_tasks[status])
[]
def _get_number_of_tasks_for(status, group_tasks): if status == "still_pending": return (_get_number_of_tasks(group_tasks["still_pending_ext"]) + _get_number_of_tasks(group_tasks["still_pending_not_ext"])) return _get_number_of_tasks(group_tasks[status])
[ "def", "_get_number_of_tasks_for", "(", "status", ",", "group_tasks", ")", ":", "if", "status", "==", "\"still_pending\"", ":", "return", "(", "_get_number_of_tasks", "(", "group_tasks", "[", "\"still_pending_ext\"", "]", ")", "+", "_get_number_of_tasks", "(", "grou...
https://github.com/spotify/luigi/blob/c3b66f4a5fa7eaa52f9a72eb6704b1049035c789/luigi/execution_summary.py#L290-L294
jgagneastro/coffeegrindsize
22661ebd21831dba4cf32bfc6ba59fe3d49f879c
App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/pandas/core/series.py
python
Series.ftype
(self)
return self._data.ftype
Return if the data is sparse|dense.
Return if the data is sparse|dense.
[ "Return", "if", "the", "data", "is", "sparse|dense", "." ]
def ftype(self): """ Return if the data is sparse|dense. """ return self._data.ftype
[ "def", "ftype", "(", "self", ")", ":", "return", "self", ".", "_data", ".", "ftype" ]
https://github.com/jgagneastro/coffeegrindsize/blob/22661ebd21831dba4cf32bfc6ba59fe3d49f879c/App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/pandas/core/series.py#L421-L425
realpython/book2-exercises
cde325eac8e6d8cff2316601c2e5b36bb46af7d0
web2py-rest/gluon/contrib/pymysql/connections.py
python
Connection.literal
(self, obj)
return escape_item(obj, self.charset)
Alias for escape()
Alias for escape()
[ "Alias", "for", "escape", "()" ]
def literal(self, obj): ''' Alias for escape() ''' return escape_item(obj, self.charset)
[ "def", "literal", "(", "self", ",", "obj", ")", ":", "return", "escape_item", "(", "obj", ",", "self", ".", "charset", ")" ]
https://github.com/realpython/book2-exercises/blob/cde325eac8e6d8cff2316601c2e5b36bb46af7d0/web2py-rest/gluon/contrib/pymysql/connections.py#L646-L648
joe42/CloudFusion
c4b94124e74a81e0634578c7754d62160081f7a1
cloudfusion/third_party/requests_1_2_3/requests/api.py
python
put
(url, data=None, **kwargs)
return request('put', url, data=data, **kwargs)
Sends a PUT request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes.
Sends a PUT request. Returns :class:`Response` object.
[ "Sends", "a", "PUT", "request", ".", "Returns", ":", "class", ":", "Response", "object", "." ]
def put(url, data=None, **kwargs): """Sends a PUT request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. """ return request('put', url, data=data, **kwargs)
[ "def", "put", "(", "url", ",", "data", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "request", "(", "'put'", ",", "url", ",", "data", "=", "data", ",", "*", "*", "kwargs", ")" ]
https://github.com/joe42/CloudFusion/blob/c4b94124e74a81e0634578c7754d62160081f7a1/cloudfusion/third_party/requests_1_2_3/requests/api.py#L91-L99
PySimpleGUI/PySimpleGUI
6c0d1fb54f493d45e90180b322fbbe70f7a5af3c
PySimpleGUI.py
python
_fixed_map
(style, style_name, option, highlight_colors=(None, None))
return new_map
[]
def _fixed_map(style, style_name, option, highlight_colors=(None, None)): # Fix for setting text colour for Tkinter 8.6.9 # From: https://core.tcl.tk/tk/info/509cafafae # default_map = [elm for elm in style.map("Treeview", query_opt=option) if '!' not in elm[0]] # custom_map = [elm for elm in style.map(style_name, query_opt=option) if '!' not in elm[0]] default_map = [elm for elm in style.map("Treeview", query_opt=option) if '!' not in elm[0] and 'selected' not in elm[0]] custom_map = [elm for elm in style.map(style_name, query_opt=option) if '!' not in elm[0] and 'selected' not in elm[0]] if option == 'background': custom_map.append(('selected', highlight_colors[1] if highlight_colors[1] is not None else ALTERNATE_TABLE_AND_TREE_SELECTED_ROW_COLORS[1])) elif option == 'foreground': custom_map.append(('selected', highlight_colors[0] if highlight_colors[0] is not None else ALTERNATE_TABLE_AND_TREE_SELECTED_ROW_COLORS[0])) new_map = custom_map + default_map return new_map
[ "def", "_fixed_map", "(", "style", ",", "style_name", ",", "option", ",", "highlight_colors", "=", "(", "None", ",", "None", ")", ")", ":", "# Fix for setting text colour for Tkinter 8.6.9", "# From: https://core.tcl.tk/tk/info/509cafafae", "# default_map = [elm for elm in st...
https://github.com/PySimpleGUI/PySimpleGUI/blob/6c0d1fb54f493d45e90180b322fbbe70f7a5af3c/PySimpleGUI.py#L13540-L13554
openedx/edx-platform
68dd185a0ab45862a2a61e0f803d7e03d2be71b5
openedx/core/djangoapps/user_authn/views/password_reset.py
python
PasswordResetTokenValidation.post
(self, request)
return Response({'is_valid': is_valid})
HTTP end-point to validate password reset token.
HTTP end-point to validate password reset token.
[ "HTTP", "end", "-", "point", "to", "validate", "password", "reset", "token", "." ]
def post(self, request): """ HTTP end-point to validate password reset token. """ is_valid = False token = request.data.get('token') try: token = token.split('-', 1) uid_int = base36_to_int(token[0]) if request.user.is_authenticated and request.user.id != uid_int: return Response({'is_valid': is_valid}) user = User.objects.get(id=uid_int) if UserRetirementRequest.has_user_requested_retirement(user): return Response({'is_valid': is_valid}) is_valid = default_token_generator.check_token(user, token[1]) if is_valid and not user.is_active: user.is_active = True user.save() except Exception: # pylint: disable=broad-except AUDIT_LOG.exception("Invalid password reset confirm token") return Response({'is_valid': is_valid})
[ "def", "post", "(", "self", ",", "request", ")", ":", "is_valid", "=", "False", "token", "=", "request", ".", "data", ".", "get", "(", "'token'", ")", "try", ":", "token", "=", "token", ".", "split", "(", "'-'", ",", "1", ")", "uid_int", "=", "ba...
https://github.com/openedx/edx-platform/blob/68dd185a0ab45862a2a61e0f803d7e03d2be71b5/openedx/core/djangoapps/user_authn/views/password_reset.py#L685-L706
pculture/miro
d8e4594441939514dd2ac29812bf37087bb3aea5
tv/lib/frontends/widgets/widgetutil.py
python
circular_rect_negative
(context, x, y, width, height)
The same path as ``circular_rect()``, but going counter clockwise.
The same path as ``circular_rect()``, but going counter clockwise.
[ "The", "same", "path", "as", "circular_rect", "()", "but", "going", "counter", "clockwise", "." ]
def circular_rect_negative(context, x, y, width, height): """The same path as ``circular_rect()``, but going counter clockwise. """ radius = height / 2.0 inner_width = width - height inner_y = y + radius inner_x1 = x + radius inner_x2 = inner_x1 + inner_width context.move_to(inner_x1, y) context.arc_negative(inner_x1, inner_y, radius, -PI/2, PI/2) context.rel_line_to(inner_width, 0) context.arc_negative(inner_x2, inner_y, radius, PI/2, -PI/2) context.rel_line_to(-inner_width, 0)
[ "def", "circular_rect_negative", "(", "context", ",", "x", ",", "y", ",", "width", ",", "height", ")", ":", "radius", "=", "height", "/", "2.0", "inner_width", "=", "width", "-", "height", "inner_y", "=", "y", "+", "radius", "inner_x1", "=", "x", "+", ...
https://github.com/pculture/miro/blob/d8e4594441939514dd2ac29812bf37087bb3aea5/tv/lib/frontends/widgets/widgetutil.py#L105-L118
F8LEFT/DecLLVM
d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c
python/idaapi.py
python
vdui_t.set_num_enum
(self, *args)
return _idaapi.vdui_t_set_num_enum(self, *args)
set_num_enum(self) -> bool
set_num_enum(self) -> bool
[ "set_num_enum", "(", "self", ")", "-", ">", "bool" ]
def set_num_enum(self, *args): """ set_num_enum(self) -> bool """ return _idaapi.vdui_t_set_num_enum(self, *args)
[ "def", "set_num_enum", "(", "self", ",", "*", "args", ")", ":", "return", "_idaapi", ".", "vdui_t_set_num_enum", "(", "self", ",", "*", "args", ")" ]
https://github.com/F8LEFT/DecLLVM/blob/d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c/python/idaapi.py#L39648-L39652
IJDykeman/wangTiles
7c1ee2095ebdf7f72bce07d94c6484915d5cae8b
experimental_code/tiles_3d/venv_mac/lib/python2.7/site-packages/pkg_resources/__init__.py
python
get_build_platform
()
return plat
Return this platform's string for platform-specific distributions XXX Currently this is the same as ``distutils.util.get_platform()``, but it needs some hacks for Linux and Mac OS X.
Return this platform's string for platform-specific distributions
[ "Return", "this", "platform", "s", "string", "for", "platform", "-", "specific", "distributions" ]
def get_build_platform(): """Return this platform's string for platform-specific distributions XXX Currently this is the same as ``distutils.util.get_platform()``, but it needs some hacks for Linux and Mac OS X. """ try: # Python 2.7 or >=3.2 from sysconfig import get_platform except ImportError: from distutils.util import get_platform plat = get_platform() if sys.platform == "darwin" and not plat.startswith('macosx-'): try: version = _macosx_vers() machine = os.uname()[4].replace(" ", "_") return "macosx-%d.%d-%s" % ( int(version[0]), int(version[1]), _macosx_arch(machine), ) except ValueError: # if someone is running a non-Mac darwin system, this will fall # through to the default implementation pass return plat
[ "def", "get_build_platform", "(", ")", ":", "try", ":", "# Python 2.7 or >=3.2", "from", "sysconfig", "import", "get_platform", "except", "ImportError", ":", "from", "distutils", ".", "util", "import", "get_platform", "plat", "=", "get_platform", "(", ")", "if", ...
https://github.com/IJDykeman/wangTiles/blob/7c1ee2095ebdf7f72bce07d94c6484915d5cae8b/experimental_code/tiles_3d/venv_mac/lib/python2.7/site-packages/pkg_resources/__init__.py#L466-L491
CyberZHG/keras-bert
f8bb7ab399f62832badf4c618520264bc91bdff1
keras_bert/bert.py
python
get_custom_objects
()
return custom_objects
Get all custom objects for loading saved models.
Get all custom objects for loading saved models.
[ "Get", "all", "custom", "objects", "for", "loading", "saved", "models", "." ]
def get_custom_objects(): """Get all custom objects for loading saved models.""" custom_objects = get_encoder_custom_objects() custom_objects['PositionEmbedding'] = PositionEmbedding custom_objects['TokenEmbedding'] = TokenEmbedding custom_objects['EmbeddingSimilarity'] = EmbeddingSimilarity custom_objects['TaskEmbedding'] = TaskEmbedding custom_objects['Masked'] = Masked custom_objects['Extract'] = Extract custom_objects['AdamWarmup'] = AdamWarmup return custom_objects
[ "def", "get_custom_objects", "(", ")", ":", "custom_objects", "=", "get_encoder_custom_objects", "(", ")", "custom_objects", "[", "'PositionEmbedding'", "]", "=", "PositionEmbedding", "custom_objects", "[", "'TokenEmbedding'", "]", "=", "TokenEmbedding", "custom_objects",...
https://github.com/CyberZHG/keras-bert/blob/f8bb7ab399f62832badf4c618520264bc91bdff1/keras_bert/bert.py#L193-L203
adobe/NLP-Cube
8c8590f9c4c44569b95778c131d4bf1f19761555
_cube/io_utils/model_store.py
python
ModelStore.delete_model
(self, lang_code, version)
Deletes a local model. Also checks for associated embeddings file and cleans it up as well only if not referenced by any other local model
Deletes a local model. Also checks for associated embeddings file and cleans it up as well only if not referenced by any other local model
[ "Deletes", "a", "local", "model", ".", "Also", "checks", "for", "associated", "embeddings", "file", "and", "cleans", "it", "up", "as", "well", "only", "if", "not", "referenced", "by", "any", "other", "local", "model" ]
def delete_model(self, lang_code, version): """ Deletes a local model. Also checks for associated embeddings file and cleans it up as well only if not referenced by any other local model """ model = lang_code+"-"+str(version) model_folder = os.path.join(self.disk_path,model) # check if model exists if not os.path.isdir(model_folder): print("Model "+model+" not found! Nothing to delete.") return # determine which embedding file we need to delete model_metadata = ModelMetadata() model_metadata.read(os.path.join(model_folder,"metadata.json")) embeddings_file_to_delete = model_metadata.embeddings_file_name # delete the model import shutil try: shutil.rmtree(model_folder) except OSError as e: print ("Error removing folder from local disk: %s - %s." % (e.filename, e.strerror)) # search in other models for referenced embeddings file found_in_other_models = False lang_models = self._list_folders() for lang_model in lang_models: metadata_file_path = os.path.join(self.disk_path, lang_model, "metadata.json") if not os.path.exists(metadata_file_path): continue # this is not a model folder, so skip it model_metadata.read(os.path.join(self.disk_path, lang_model, "metadata.json")) other_embeddings_file = model_metadata.embeddings_file_name if other_embeddings_file == embeddings_file_to_delete: found_in_other_models = True print("Embeddings file "+embeddings_file_to_delete+" is still being used by model "+ lang_model+" so it will not be deleted.") break if not found_in_other_models: try: embeddings_file_to_delete_abs_path = os.path.join(self.disk_path,"embeddings",embeddings_file_to_delete) os.remove(embeddings_file_to_delete_abs_path) print("Removed embeddings file "+embeddings_file_to_delete) except OSError as e: ## if failed, report it back to the user ## print ("Error removing embeddings file: %s - %s." % (e.filename, e.strerror)) print("Model cleanup successful.")
[ "def", "delete_model", "(", "self", ",", "lang_code", ",", "version", ")", ":", "model", "=", "lang_code", "+", "\"-\"", "+", "str", "(", "version", ")", "model_folder", "=", "os", ".", "path", ".", "join", "(", "self", ".", "disk_path", ",", "model", ...
https://github.com/adobe/NLP-Cube/blob/8c8590f9c4c44569b95778c131d4bf1f19761555/_cube/io_utils/model_store.py#L461-L505
line/line-bot-sdk-python
d97d488876d504ab3cb6ecfc1574ea42bd669565
linebot/models/imagemap.py
python
URIImagemapAction.__init__
(self, link_uri=None, area=None, **kwargs)
__init__ method. :param str link_uri: Webpage URL :param area: Defined tappable area :type area: :py:class:`linebot.models.imagemap.ImagemapArea` :param kwargs:
__init__ method.
[ "__init__", "method", "." ]
def __init__(self, link_uri=None, area=None, **kwargs): """__init__ method. :param str link_uri: Webpage URL :param area: Defined tappable area :type area: :py:class:`linebot.models.imagemap.ImagemapArea` :param kwargs: """ super(URIImagemapAction, self).__init__(**kwargs) self.type = 'uri' self.link_uri = link_uri self.area = self.get_or_new_from_json_dict(area, ImagemapArea)
[ "def", "__init__", "(", "self", ",", "link_uri", "=", "None", ",", "area", "=", "None", ",", "*", "*", "kwargs", ")", ":", "super", "(", "URIImagemapAction", ",", "self", ")", ".", "__init__", "(", "*", "*", "kwargs", ")", "self", ".", "type", "=",...
https://github.com/line/line-bot-sdk-python/blob/d97d488876d504ab3cb6ecfc1574ea42bd669565/linebot/models/imagemap.py#L118-L130
pypa/pipenv
b21baade71a86ab3ee1429f71fbc14d4f95fb75d
pipenv/vendor/urllib3/response.py
python
GzipDecoder.__init__
(self)
[]
def __init__(self): self._obj = zlib.decompressobj(16 + zlib.MAX_WBITS) self._state = GzipDecoderState.FIRST_MEMBER
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "_obj", "=", "zlib", ".", "decompressobj", "(", "16", "+", "zlib", ".", "MAX_WBITS", ")", "self", ".", "_state", "=", "GzipDecoderState", ".", "FIRST_MEMBER" ]
https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/vendor/urllib3/response.py#L75-L77
shichao-an/leetcode-python
6c523ef4759a57433e10271b584eece16f9f05f3
minimum_window_substring/solution.py
python
Solution.minWindow
(self, S, T)
return s[res_left:res_right + 1]
[]
def minWindow(self, S, T): s = S t = T d = {} td = {} for c in t: td[c] = td.get(c, 0) + 1 left = 0 right = 0 lefts = [] rights = [] for i, c in enumerate(s): if c in td: d[c] = d.get(c, 0) + 1 if self.contains(d, td): # Contains all characters right = i # Move left pointers cc = s[left] while left <= right and (cc not in d or d[cc] > td[cc]): if cc in d: d[cc] -= 1 left += 1 cc = s[left] lefts.append(left) rights.append(right) if not lefts: return '' res_left = lefts[0] res_right = rights[0] n = len(lefts) for i in range(1, n): if rights[i] - lefts[i] < res_right - res_left: res_left = lefts[i] res_right = rights[i] return s[res_left:res_right + 1]
[ "def", "minWindow", "(", "self", ",", "S", ",", "T", ")", ":", "s", "=", "S", "t", "=", "T", "d", "=", "{", "}", "td", "=", "{", "}", "for", "c", "in", "t", ":", "td", "[", "c", "]", "=", "td", ".", "get", "(", "c", ",", "0", ")", "...
https://github.com/shichao-an/leetcode-python/blob/6c523ef4759a57433e10271b584eece16f9f05f3/minimum_window_substring/solution.py#L3-L37
teemu-l/execution-trace-viewer
d2d99e92decb3526efc1f5bd4bae350aa4c7c0d2
core/trace_files.py
python
save_as_tv_trace
(trace_data, filename)
Saves trace data in a default Trace Viewer format Args: trace_data: TraceData object filename: name of trace file
Saves trace data in a default Trace Viewer format
[ "Saves", "trace", "data", "in", "a", "default", "Trace", "Viewer", "format" ]
def save_as_tv_trace(trace_data, filename): """Saves trace data in a default Trace Viewer format Args: trace_data: TraceData object filename: name of trace file """ try: f = open(filename, "wb") except IOError: print("Error, could not write to file.") else: with f: trace = trace_data.trace f.write(b"TVTR") file_info = {"arch": trace_data.arch, "version": "1.0"} if trace_data.pointer_size: pointer_size = trace_data.pointer_size elif trace_data.arch == "x64": pointer_size = 8 else: pointer_size = 4 file_info["pointer_size"] = pointer_size file_info["regs"] = list(trace_data.regs.keys()) file_info["ip_reg"] = trace_data.ip_reg json_blob = json.dumps(file_info) json_blob_length = len(json_blob) f.write((json_blob_length).to_bytes(4, byteorder="little")) f.write(json_blob.encode()) for i, t in enumerate(trace): f.write(b"\x00") disasm = t["disasm"][:255] # limit length to 0xff f.write((len(disasm)).to_bytes(1, byteorder="little")) f.write(disasm.encode()) comment = t["comment"][:255] f.write((len(comment)).to_bytes(1, byteorder="little")) f.write(comment.encode()) reg_change_newdata = [] reg_change_positions = [] pos = 0 for reg_index, reg_value in enumerate(t["regs"]): if i == 0 or reg_value != trace[i - 1]["regs"][reg_index]: reg_change_newdata.append(reg_value) # value changed reg_change_positions.append(pos) pos = -1 pos += 1 reg_changes = len(reg_change_positions) & 0xFF f.write((reg_changes).to_bytes(1, byteorder="little")) memory_accesses = len(t["mem"]) & 0xFF f.write((memory_accesses).to_bytes(1, byteorder="little")) flag = 0 opcodes = bytes.fromhex(t["opcodes"]) opcode_size = len(opcodes) if "thread" in t: flag = flag | (1 << 7) flags_and_opcode_size = flag | opcode_size f.write((flags_and_opcode_size).to_bytes(1, byteorder="little")) if "thread" in t: f.write((t["thread"]).to_bytes(4, byteorder="little")) f.write(opcodes) for pos in reg_change_positions: f.write((pos).to_bytes(1, byteorder="little")) for newdata in reg_change_newdata: f.write((newdata).to_bytes(pointer_size, byteorder="little")) mem_access_flags = [] mem_access_addresses = [] mem_access_data = [] for mem_access in t["mem"]: flag = 0 if mem_access["access"].lower() == "write": flag = 1 mem_access_flags.append(flag) mem_access_data.append(mem_access["value"]) mem_access_addresses.append(mem_access["addr"]) for flag in mem_access_flags: f.write((flag).to_bytes(1, byteorder="little")) for addr in mem_access_addresses: f.write((addr).to_bytes(pointer_size, byteorder="little")) for data in mem_access_data: f.write((data).to_bytes(pointer_size, byteorder="little")) for bookmark in trace_data.bookmarks: f.write(b"\x01") f.write((bookmark.startrow).to_bytes(4, byteorder="little")) f.write((bookmark.endrow).to_bytes(4, byteorder="little")) disasm = bookmark.disasm[:255] disasm_length = len(disasm) f.write((disasm_length).to_bytes(1, byteorder="little")) f.write(disasm.encode()) comment = bookmark.comment[:255] comment_length = len(comment) f.write((comment_length).to_bytes(1, byteorder="little")) f.write(comment.encode()) addr = bookmark.addr[:255] addr_length = len(addr) f.write((addr_length).to_bytes(1, byteorder="little")) f.write(addr.encode())
[ "def", "save_as_tv_trace", "(", "trace_data", ",", "filename", ")", ":", "try", ":", "f", "=", "open", "(", "filename", ",", "\"wb\"", ")", "except", "IOError", ":", "print", "(", "\"Error, could not write to file.\"", ")", "else", ":", "with", "f", ":", "...
https://github.com/teemu-l/execution-trace-viewer/blob/d2d99e92decb3526efc1f5bd4bae350aa4c7c0d2/core/trace_files.py#L255-L365
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-1.5/django/contrib/gis/gdal/geometries.py
python
OGRGeometry.geom_count
(self)
return capi.get_geom_count(self.ptr)
The number of elements in this Geometry.
The number of elements in this Geometry.
[ "The", "number", "of", "elements", "in", "this", "Geometry", "." ]
def geom_count(self): "The number of elements in this Geometry." return capi.get_geom_count(self.ptr)
[ "def", "geom_count", "(", "self", ")", ":", "return", "capi", ".", "get_geom_count", "(", "self", ".", "ptr", ")" ]
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.5/django/contrib/gis/gdal/geometries.py#L220-L222
oracle/graalpython
577e02da9755d916056184ec441c26e00b70145c
graalpython/lib-python/3/calendar.py
python
_localized_day.__init__
(self, format)
[]
def __init__(self, format): self.format = format
[ "def", "__init__", "(", "self", ",", "format", ")", ":", "self", ".", "format", "=", "format" ]
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/calendar.py#L74-L75
CGATOxford/cgat
326aad4694bdfae8ddc194171bb5d73911243947
CGAT/Expression.py
python
ExperimentalDesign._update
(self)
parse design file and fill class attributes. Call this function whenever self.table changes.
parse design file and fill class attributes.
[ "parse", "design", "file", "and", "fill", "class", "attributes", "." ]
def _update(self): """parse design file and fill class attributes. Call this function whenever self.table changes. """ # remove all entries that should not be included self.table = self.table[self.table["include"] != 0] # define attributes self.conditions = self.table['group'].tolist() self.pairs = self.table['pair'].tolist() # TS - use OrderedDict to retain order in unique self.groups = (list(collections.OrderedDict.fromkeys( self.conditions))) self.samples = self.table.index.tolist() # Test if replicates exist, i.e at least one group has multiple samples # TS - does this need to be extended to check whether replicates exist # for each group? max_per_group = max([self.conditions.count(x) for x in self.groups]) self.has_replicates = max_per_group >= 2 # Test if pairs exist: npairs = len(set(self.pairs)) has_pairs = npairs == 2 # ..if so, at least two samples are required per pair if has_pairs: min_per_pair = min([self.pairs.count(x) for x in set(self.pairs)]) self.has_pairs = min_per_pair >= 2 else: self.has_pairs = False # all columns except "include" may be considered as factors self.factors = self.table.drop(["include"], axis=1) # remove "pair" from factor if design does not include pairs if not self.has_pairs: self.factors.drop("pair", inplace=True, axis=1)
[ "def", "_update", "(", "self", ")", ":", "# remove all entries that should not be included", "self", ".", "table", "=", "self", ".", "table", "[", "self", ".", "table", "[", "\"include\"", "]", "!=", "0", "]", "# define attributes", "self", ".", "conditions", ...
https://github.com/CGATOxford/cgat/blob/326aad4694bdfae8ddc194171bb5d73911243947/CGAT/Expression.py#L205-L243
ScottfreeLLC/AlphaPy
e6419cc811c2a3abc1ad522a85a888c8ef386056
alphapy/plots.py
python
plot_scatter
(df, features, target, tag='eda', directory=None)
r"""Plot a scatterplot matrix, also known as a pair plot. Parameters ---------- df : pandas.DataFrame The dataframe containing the features. features: list of str The features to compare in the scatterplot. target : str The target variable for contrast. tag : str Unique identifier for the plot. directory : str, optional The full specification of the plot location. Returns ------- None : None. References ---------- https://seaborn.pydata.org/examples/scatterplot_matrix.html
r"""Plot a scatterplot matrix, also known as a pair plot.
[ "r", "Plot", "a", "scatterplot", "matrix", "also", "known", "as", "a", "pair", "plot", "." ]
def plot_scatter(df, features, target, tag='eda', directory=None): r"""Plot a scatterplot matrix, also known as a pair plot. Parameters ---------- df : pandas.DataFrame The dataframe containing the features. features: list of str The features to compare in the scatterplot. target : str The target variable for contrast. tag : str Unique identifier for the plot. directory : str, optional The full specification of the plot location. Returns ------- None : None. References ---------- https://seaborn.pydata.org/examples/scatterplot_matrix.html """ logger.info("Generating Scatter Plot") # Get the feature subset features.append(target) df = df[features] # Generate the pair plot sns.set() sns_plot = sns.pairplot(df, hue=target) # Save the plot write_plot('seaborn', sns_plot, 'scatter_plot', tag, directory)
[ "def", "plot_scatter", "(", "df", ",", "features", ",", "target", ",", "tag", "=", "'eda'", ",", "directory", "=", "None", ")", ":", "logger", ".", "info", "(", "\"Generating Scatter Plot\"", ")", "# Get the feature subset", "features", ".", "append", "(", "...
https://github.com/ScottfreeLLC/AlphaPy/blob/e6419cc811c2a3abc1ad522a85a888c8ef386056/alphapy/plots.py#L935-L975
smart-mobile-software/gitstack
d9fee8f414f202143eb6e620529e8e5539a2af56
python/Lib/lib-tk/ttk.py
python
Notebook.select
(self, tab_id=None)
return self.tk.call(self._w, "select", tab_id)
Selects the specified tab. The associated child window will be displayed, and the previously-selected window (if different) is unmapped. If tab_id is omitted, returns the widget name of the currently selected pane.
Selects the specified tab.
[ "Selects", "the", "specified", "tab", "." ]
def select(self, tab_id=None): """Selects the specified tab. The associated child window will be displayed, and the previously-selected window (if different) is unmapped. If tab_id is omitted, returns the widget name of the currently selected pane.""" return self.tk.call(self._w, "select", tab_id)
[ "def", "select", "(", "self", ",", "tab_id", "=", "None", ")", ":", "return", "self", ".", "tk", ".", "call", "(", "self", ".", "_w", ",", "\"select\"", ",", "tab_id", ")" ]
https://github.com/smart-mobile-software/gitstack/blob/d9fee8f414f202143eb6e620529e8e5539a2af56/python/Lib/lib-tk/ttk.py#L904-L911
freedomofpress/securedrop
f768a1a5aa37e790077dfd38d6e7a0299a4b3a0f
securedrop/journalist_app/utils.py
python
validate_hotp_secret
(user: Journalist, otp_secret: str)
return True
Validates and sets the HOTP provided by a user :param user: the change is for this instance of the User object :param otp_secret: the new HOTP secret :return: True if it validates, False if it does not
Validates and sets the HOTP provided by a user :param user: the change is for this instance of the User object :param otp_secret: the new HOTP secret :return: True if it validates, False if it does not
[ "Validates", "and", "sets", "the", "HOTP", "provided", "by", "a", "user", ":", "param", "user", ":", "the", "change", "is", "for", "this", "instance", "of", "the", "User", "object", ":", "param", "otp_secret", ":", "the", "new", "HOTP", "secret", ":", ...
def validate_hotp_secret(user: Journalist, otp_secret: str) -> bool: """ Validates and sets the HOTP provided by a user :param user: the change is for this instance of the User object :param otp_secret: the new HOTP secret :return: True if it validates, False if it does not """ strip_whitespace = otp_secret.replace(' ', '') secret_length = len(strip_whitespace) if secret_length != HOTP_SECRET_LENGTH: flash(ngettext( 'HOTP secrets are 40 characters long - you have entered {num}.', 'HOTP secrets are 40 characters long - you have entered {num}.', secret_length ).format(num=secret_length), "error") return False try: user.set_hotp_secret(otp_secret) except (binascii.Error, TypeError) as e: if "Non-hexadecimal digit found" in str(e): flash(gettext( "Invalid HOTP secret format: " "please only submit letters A-F and numbers 0-9."), "error") return False else: flash(gettext( "An unexpected error occurred! " "Please inform your admin."), "error") current_app.logger.error( "set_hotp_secret '{}' (id {}) failed: {}".format( otp_secret, user.id, e)) return False return True
[ "def", "validate_hotp_secret", "(", "user", ":", "Journalist", ",", "otp_secret", ":", "str", ")", "->", "bool", ":", "strip_whitespace", "=", "otp_secret", ".", "replace", "(", "' '", ",", "''", ")", "secret_length", "=", "len", "(", "strip_whitespace", ")"...
https://github.com/freedomofpress/securedrop/blob/f768a1a5aa37e790077dfd38d6e7a0299a4b3a0f/securedrop/journalist_app/utils.py#L139-L174
home-assistant/supervisor
69c2517d5211b483fdfe968b0a2b36b672ee7ab2
supervisor/resolution/evaluations/container.py
python
EvaluateContainer.known_images
(self)
return { self.sys_homeassistant.image, self.sys_supervisor.image, *(plugin.image for plugin in self.sys_plugins.all_plugins), *(addon.image for addon in self.sys_addons.installed), }
Return a set of all known images.
Return a set of all known images.
[ "Return", "a", "set", "of", "all", "known", "images", "." ]
def known_images(self) -> set[str]: """Return a set of all known images.""" return { self.sys_homeassistant.image, self.sys_supervisor.image, *(plugin.image for plugin in self.sys_plugins.all_plugins), *(addon.image for addon in self.sys_addons.installed), }
[ "def", "known_images", "(", "self", ")", "->", "set", "[", "str", "]", ":", "return", "{", "self", ".", "sys_homeassistant", ".", "image", ",", "self", ".", "sys_supervisor", ".", "image", ",", "*", "(", "plugin", ".", "image", "for", "plugin", "in", ...
https://github.com/home-assistant/supervisor/blob/69c2517d5211b483fdfe968b0a2b36b672ee7ab2/supervisor/resolution/evaluations/container.py#L57-L64
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/full/multiprocessing/connection.py
python
_ConnectionBase.closed
(self)
return self._handle is None
True if the connection is closed
True if the connection is closed
[ "True", "if", "the", "connection", "is", "closed" ]
def closed(self): """True if the connection is closed""" return self._handle is None
[ "def", "closed", "(", "self", ")", ":", "return", "self", ".", "_handle", "is", "None" ]
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/full/multiprocessing/connection.py#L159-L161
openedx/edx-platform
68dd185a0ab45862a2a61e0f803d7e03d2be71b5
cms/djangoapps/contentstore/management/commands/export_olx.py
python
export_course_to_directory
(course_key, root_dir)
return export_dir
Export course into a directory
Export course into a directory
[ "Export", "course", "into", "a", "directory" ]
def export_course_to_directory(course_key, root_dir): """Export course into a directory""" store = modulestore() course = store.get_course(course_key) if course is None: raise CommandError("Invalid course_id") # The safest characters are A-Z, a-z, 0-9, <underscore>, <period> and <hyphen>. # We represent the first four with \w. # TODO: Once we support courses with unicode characters, we will need to revisit this. replacement_char = '-' course_dir = replacement_char.join([course.id.org, course.id.course, course.id.run]) course_dir = re.sub(r'[^\w\.\-]', replacement_char, course_dir) export_course_to_xml(store, None, course.id, root_dir, course_dir) export_dir = path(root_dir) / course_dir return export_dir
[ "def", "export_course_to_directory", "(", "course_key", ",", "root_dir", ")", ":", "store", "=", "modulestore", "(", ")", "course", "=", "store", ".", "get_course", "(", "course_key", ")", "if", "course", "is", "None", ":", "raise", "CommandError", "(", "\"I...
https://github.com/openedx/edx-platform/blob/68dd185a0ab45862a2a61e0f803d7e03d2be71b5/cms/djangoapps/contentstore/management/commands/export_olx.py#L91-L108
venth/aws-adfs
73810a6f60b1a0b1f00921889f163654954fd06f
aws_adfs/reset.py
python
_clear_credentials
(config, profile)
[]
def _clear_credentials(config, profile): def store_config(config_location, storer): config_file = configparser.RawConfigParser() config_file.read(config_location) if not config_file.has_section(profile): config_file.add_section(profile) storer(config_file) with open(config_location, 'w+') as f: try: config_file.write(f) finally: f.close() def profile_remover(config_file): config_file.remove_section(profile) config_file.remove_section('profile {}'.format(profile)) store_config(config.aws_credentials_location, profile_remover) store_config(config.aws_config_location, profile_remover)
[ "def", "_clear_credentials", "(", "config", ",", "profile", ")", ":", "def", "store_config", "(", "config_location", ",", "storer", ")", ":", "config_file", "=", "configparser", ".", "RawConfigParser", "(", ")", "config_file", ".", "read", "(", "config_location"...
https://github.com/venth/aws-adfs/blob/73810a6f60b1a0b1f00921889f163654954fd06f/aws_adfs/reset.py#L24-L45
ingolemo/python-lenses
82f9d2755425ba0fdae1c23f0fd912b31d61cd2d
lenses/ui/__init__.py
python
BoundLens.get
(self)
return self._optic.to_list_of(self._state)[0]
Get the first value focused by the lens. >>> from lenses import bind >>> bind([1, 2, 3]).get() [1, 2, 3] >>> bind([1, 2, 3])[0].get() 1
Get the first value focused by the lens.
[ "Get", "the", "first", "value", "focused", "by", "the", "lens", "." ]
def get(self) -> B: """Get the first value focused by the lens. >>> from lenses import bind >>> bind([1, 2, 3]).get() [1, 2, 3] >>> bind([1, 2, 3])[0].get() 1 """ return self._optic.to_list_of(self._state)[0]
[ "def", "get", "(", "self", ")", "->", "B", ":", "return", "self", ".", "_optic", ".", "to_list_of", "(", "self", ".", "_state", ")", "[", "0", "]" ]
https://github.com/ingolemo/python-lenses/blob/82f9d2755425ba0fdae1c23f0fd912b31d61cd2d/lenses/ui/__init__.py#L194-L203
fake-name/ReadableWebProxy
ed5c7abe38706acc2684a1e6cd80242a03c5f010
WebMirror/management/rss_parser_funcs/feed_parse_extractEggdroptlWordpressCom.py
python
extractEggdroptlWordpressCom
(item)
return False
Parser for 'eggdroptl.wordpress.com'
Parser for 'eggdroptl.wordpress.com'
[ "Parser", "for", "eggdroptl", ".", "wordpress", ".", "com" ]
def extractEggdroptlWordpressCom(item): ''' Parser for 'eggdroptl.wordpress.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('tvhss', 'The Villain Has Something to Say', 'translated'), ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel'), ] for tagname, name, tl_type in tagmap: if tagname in item['tags']: return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False
[ "def", "extractEggdroptlWordpressCom", "(", "item", ")", ":", "vol", ",", "chp", ",", "frag", ",", "postfix", "=", "extractVolChapterFragmentPostfix", "(", "item", "[", "'title'", "]", ")", "if", "not", "(", "chp", "or", "vol", ")", "or", "\"preview\"", "i...
https://github.com/fake-name/ReadableWebProxy/blob/ed5c7abe38706acc2684a1e6cd80242a03c5f010/WebMirror/management/rss_parser_funcs/feed_parse_extractEggdroptlWordpressCom.py#L1-L21
MrH0wl/Cloudmare
65e5bc9888f9d362ab2abfb103ea6c1e869d67aa
thirdparty/beautifulsoup/BeautifulSoup.py
python
Tag.get
(self, key, default=None)
return self._getAttrMap().get(key, default)
Returns the value of the 'key' attribute for the tag, or the value given for 'default' if it doesn't have that attribute.
Returns the value of the 'key' attribute for the tag, or the value given for 'default' if it doesn't have that attribute.
[ "Returns", "the", "value", "of", "the", "key", "attribute", "for", "the", "tag", "or", "the", "value", "given", "for", "default", "if", "it", "doesn", "t", "have", "that", "attribute", "." ]
def get(self, key, default=None): """Returns the value of the 'key' attribute for the tag, or the value given for 'default' if it doesn't have that attribute.""" return self._getAttrMap().get(key, default)
[ "def", "get", "(", "self", ",", "key", ",", "default", "=", "None", ")", ":", "return", "self", ".", "_getAttrMap", "(", ")", ".", "get", "(", "key", ",", "default", ")" ]
https://github.com/MrH0wl/Cloudmare/blob/65e5bc9888f9d362ab2abfb103ea6c1e869d67aa/thirdparty/beautifulsoup/BeautifulSoup.py#L590-L594
open-cogsci/OpenSesame
c4a3641b097a80a76937edbd8c365f036bcc9705
libqtopensesame/items/qtitem.py
python
qtitem.rename
(self, from_name, to_name)
desc: Handles renaming of an item (not necesarrily the current item). arguments: from_name: desc: The old item name. type: unicode to_name: desc: The new item name type: unicode
desc: Handles renaming of an item (not necesarrily the current item).
[ "desc", ":", "Handles", "renaming", "of", "an", "item", "(", "not", "necesarrily", "the", "current", "item", ")", "." ]
def rename(self, from_name, to_name): """ desc: Handles renaming of an item (not necesarrily the current item). arguments: from_name: desc: The old item name. type: unicode to_name: desc: The new item name type: unicode """ if self.name != from_name: return self.name = to_name if self.container_widget is None: return self.container_widget.__item__ = self.name self.header.set_name(to_name) index = self.tabwidget.indexOf(self.widget()) if index is not None: self.tabwidget.setTabText(index, to_name)
[ "def", "rename", "(", "self", ",", "from_name", ",", "to_name", ")", ":", "if", "self", ".", "name", "!=", "from_name", ":", "return", "self", ".", "name", "=", "to_name", "if", "self", ".", "container_widget", "is", "None", ":", "return", "self", ".",...
https://github.com/open-cogsci/OpenSesame/blob/c4a3641b097a80a76937edbd8c365f036bcc9705/libqtopensesame/items/qtitem.py#L610-L634