Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
366,000 | def npz_generator(npz_path):
npz_data = np.load(npz_path)
X = npz_data[]
y = npz_data[]
n = X.shape[0]
while True:
i = np.random.randint(0, n)
yield {: X[i], : y[i]} | Generate data from an npz file. |
366,001 | def version():
short = .join([str(bit) for bit in __version__[:3]])
return .join([short] + [str(bit) for bit in __version__[3:]]) | Returns a human-readable version string.
For official releases, it will follow a semver style (e.g. ``1.2.7``).
For dev versions, it will have the semver style first, followed by
hyphenated qualifiers (e.g. ``1.2.7-dev``).
Returns a string. |
366,002 | def add_variables_from(self, linear, vartype=None):
if isinstance(linear, abc.Mapping):
for v, bias in iteritems(linear):
self.add_variable(v, bias, vartype=vartype)
else:
try:
for v, bias in linear:
self.add_variable(v... | Add variables and/or linear biases to a binary quadratic model.
Args:
linear (dict[variable, bias]/iterable[(variable, bias)]):
A collection of variables and their linear biases to add to the model.
If a dict, keys are variables in the binary quadratic model and
... |
366,003 | def remove_external_references_from_roles(self):
for node_role in self.node.findall():
role = Crole(node_role)
role.remove_external_references() | Removes any external references on any of the roles from the predicate |
366,004 | def nearest_overlap(self, overlap, bins):
bins_overlap = overlap * bins
if bins_overlap % 2 != 0:
bins_overlap = math.ceil(bins_overlap / 2) * 2
overlap = bins_overlap / bins
logger.warning(
.format(overlap))
return overlap | Return nearest overlap/crop factor based on number of bins |
366,005 | def find_bled112_devices(cls):
found_devs = []
ports = serial.tools.list_ports.comports()
for port in ports:
if not hasattr(port, ) or not hasattr(port, ):
continue
if port.pid == 1 and port.vid == 9304:
found_devs.a... | Look for BLED112 dongles on this computer and start an instance on each one |
366,006 | def vmdk_to_ami(args):
aws_importer = AWSUtilities.AWSUtils(args.directory, args.aws_profile, args.s3_bucket,
args.aws_regions, args.ami_name, args.vmdk_upload_file)
aws_importer.import_vmdk() | Calls methods to perform vmdk import
:param args:
:return: |
366,007 | def validate_api_call(schema, raw_request, raw_response):
request = normalize_request(raw_request)
with ErrorDict() as errors:
try:
validate_request(
request=request,
schema=schema,
)
except ValidationError as err:
errors[... | Validate the request/response cycle of an api call against a swagger
schema. Request/Response objects from the `requests` and `urllib` library
are supported. |
366,008 | def write_from_file(library, session, filename, count):
return_count = ViUInt32()
ret = library.viWriteFromFile(session, filename, count, return_count)
return return_count, ret | Take data from a file and write it out synchronously.
Corresponds to viWriteFromFile function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param filename: Name of file from which data will be read.
:param count: N... |
366,009 | def _verify(
self,
request,
return_payload=False,
verify=True,
raise_missing=False,
request_args=None,
request_kwargs=None,
*args,
**kwargs
):
if "permakey" in request.headers:
permakey = request.heade... | If there is a "permakey", then we will verify the token by checking the
database. Otherwise, just do the normal verification.
Typically, any method that begins with an underscore in sanic-jwt should
not be touched. In this case, we are trying to break the rules a bit to handle
a unique ... |
366,010 | def get_next_work_day(self, division=None, date=None):
date = date or datetime.date.today()
one_day = datetime.timedelta(days=1)
holidays = set(holiday[] for holiday in self.get_holidays(division=division))
while True:
date += one_day
if date.weekday() no... | Returns the next work day, skipping weekends and bank holidays
:param division: see division constants; defaults to common holidays
:param date: search starting from this date; defaults to today
:return: datetime.date; NB: get_next_holiday returns a dict |
366,011 | def _lincomb(self, a, x, b, y, out):
for space, xp, yp, outp in zip(self.spaces, x.parts, y.parts,
out.parts):
space._lincomb(a, xp, b, yp, outp) | Linear combination ``out = a*x + b*y``. |
366,012 | def _read_para_r1_counter(self, code, cbit, clen, *, desc, length, version):
if clen != 12:
raise ProtocolError(f)
if code == 128 and version != 1:
raise ProtocolError(f)
_resv = self._read_fileng(4)
_genc = self._read_unpack(8)
r1_counter = dic... | Read HIP R1_COUNTER parameter.
Structure of HIP R1_COUNTER parameter [RFC 5201][RFC 7401]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-... |
366,013 | def partial_normalize(self, axis: AxisIdentifier = 0, inplace: bool = False):
axis = self._get_axis(axis)
if not inplace:
copy = self.copy()
copy.partial_normalize(axis, inplace=True)
return copy
else:
self._coerce_dtype(float)
... | Normalize in rows or columns.
Parameters
----------
axis: int or str
Along which axis to sum (numpy-sense)
inplace: bool
Update the object itself
Returns
-------
hist : Histogram2D |
366,014 | def get_rgb_hex(self):
rgb_r, rgb_g, rgb_b = self.get_upscaled_value_tuple()
return % (rgb_r, rgb_g, rgb_b) | Converts the RGB value to a hex value in the form of: #RRGGBB
:rtype: str |
366,015 | def regen_keys():
*
for fn_ in os.listdir(__opts__[]):
path = os.path.join(__opts__[], fn_)
try:
os.remove(path)
except os.error:
pass
channel = salt.transport.client.ReqChannel.factory(__opts__)
channel.close() | Used to regenerate the minion keys.
CLI Example:
.. code-block:: bash
salt '*' saltutil.regen_keys |
366,016 | def save_list(lst, path):
with open(path, ) as out:
lines = []
for item in lst:
if isinstance(item, (six.text_type, six.binary_type)):
lines.append(make_str(item))
else:
lines.append(make_str(json.dumps(item)))
out.write(b.join(li... | Save items from list to the file. |
366,017 | def convert_descriptor(self, bucket, descriptor, index_fields=[], autoincrement=None):
columns = []
indexes = []
fallbacks = []
constraints = []
column_mapping = {}
table_name = self.convert_bucket(bucket)
table_comment = _get_comment(descriptor... | Convert descriptor to SQL |
366,018 | def get_results(self, *, block=False, timeout=None):
deadline = None
if timeout:
deadline = time.monotonic() + timeout / 1000
for child in self.children:
if deadline:
timeout = max(0, int((deadline - time.monotonic()) * 1000))
if isi... | Get the results of each job in the group.
Parameters:
block(bool): Whether or not to block until the results are stored.
timeout(int): The maximum amount of time, in milliseconds,
to wait for results when block is True. Defaults to 10
seconds.
Raises:
... |
366,019 | def is_stationary(self):
r
return np.allclose(np.dot(self._Pi, self._Tij), self._Pi) | r""" Whether the MSM is stationary, i.e. whether the initial distribution is the stationary distribution
of the hidden transition matrix. |
366,020 | def get_default_config():
config = {}
for name, cls in iteritems(get_tools()):
config[name] = cls.get_default_config()
try:
workers = multiprocessing.cpu_count() - 1
except NotImplementedError:
workers = 1
workers = max(1, min(4, workers))
config.update({
... | Produces a stock/out-of-the-box TidyPy configuration.
:rtype: dict |
366,021 | def _Rzderiv(self,R,z,phi=0.,t=0.):
Raz2= (R+self.a)**2+z**2
m= 4.*R*self.a/Raz2
return (3.*(R+self.a)/Raz2
-2.*((1.+m)/(1.-m)-special.ellipk(m)/special.ellipe(m))\
*self.a*(self.a2+z**2-R**2)/Raz2**2/m)*self._zforce(R,z) | NAME:
_Rzderiv
PURPOSE:
evaluate the mixed R,z derivative for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
d2phi/dR/dz
HISTORY:
2018-0... |
366,022 | def get_encodings_from_content(content):
if isinstance(content, bytes):
find_charset = re.compile(
br]*([a-z0-9\-_]+?) *?["\, flags=re.I
).findall
find_xml = re.compile(
br]*([a-z0-9\-_]+?) *?["\
).findall
return [encoding.decode() for encoding i... | Code from:
https://github.com/sigmavirus24/requests-toolbelt/blob/master/requests_toolbelt/utils/deprecated.py
Return encodings from given content string.
:param content: string to extract encodings from. |
366,023 | def __recognize_user_class(self, node: yaml.Node,
expected_type: Type) -> RecResult:
logger.debug()
loc_str = .format(node.start_mark, os.linesep)
if hasattr(expected_type, ):
try:
unode = UnknownNode(self, node)
... | Recognize a user-defined class in the node.
This tries to recognize only exactly the specified class. It \
recurses down into the class's attributes, but not to its \
subclasses. See also __recognize_user_classes().
Args:
node: The node to recognize.
expected_ty... |
366,024 | def attempt_sync_with_master(pr: PullRequestDetails
) -> Union[bool, CannotAutomergeError]:
master_sha = get_master_sha(pr.repo)
remote = pr.remote_repo
url = ("https://api.github.com/repos/{}/{}/merges"
"?access_token={}".format(remote.organization,
... | References:
https://developer.github.com/v3/repos/merging/#perform-a-merge |
366,025 | def rating(self, **kwargs):
path = self._get_id_path()
payload = {
: kwargs.pop(, None),
}
response = self._POST(path, kwargs, payload)
self._set_attrs_to_values(response)
return response | This method lets users rate a movie. A valid session id or guest
session id is required.
Args:
session_id: see Authentication.
guest_session_id: see Authentication.
value: Rating value.
Returns:
A dict representation of the JSON returned from the... |
366,026 | def twisted_absolute_path(path, request):
parsed = urlparse.urlparse(request.uri)
if parsed.scheme != :
path_parts = parsed.path.lstrip().split()
request.prepath = path_parts[0:1]
request.postpath = path_parts[1:]
path = request.prepath[0]
return path, request | Hack to fix twisted not accepting absolute URIs |
366,027 | def download_file(url):
response = requests.get(url)
if response.status_code is not 200:
return None
return response.text | Downloads a file from the specified URL.
:param str url: The URL to the file to be downloaded
:returns: the downloaded file's content
:rtype: str |
366,028 | def pdf(cls, mass, log_mode=True):
alpha = 2.35
a = 0.060285569480482866
dn_dm = a * mass**(-alpha)
if log_mode:
return dn_dm * (mass * np.log(10))
else:
return dn_dm | PDF for the Salpeter IMF.
Value of 'a' is set to normalize the IMF to 1 between 0.1 and 100 Msun |
366,029 | def ecg_wave_detector(ecg, rpeaks):
q_waves = []
p_waves = []
q_waves_starts = []
s_waves = []
t_waves = []
t_waves_starts = []
t_waves_ends = []
for index, rpeak in enumerate(rpeaks[:-3]):
try:
epoch_before = np.array(ecg)[int(rpeaks[index-1]):int(rpeak)]
... | Returns the localization of the P, Q, T waves. This function needs massive help!
Parameters
----------
ecg : list or ndarray
ECG signal (preferably filtered).
rpeaks : list or ndarray
R peaks localization.
Returns
----------
ecg_waves : dict
Contains wave peaks loca... |
366,030 | def _get_gc2_coordinates_for_rupture(self, edge_sets):
rup_gc2t, rup_gc2u = self.get_generalised_coordinates(
edge_sets[:, 0], edge_sets[:, 1])
self.gc_length = numpy.max(rup_gc2u) | Calculates the GC2 coordinates for the nodes of the upper edge of the
fault |
366,031 | def _maybe_append_chunk(chunk_info, line_index, column, contents, chunks):
if chunk_info:
chunks.append(_chunk_from_ranges(contents,
chunk_info[0],
chunk_info[1],
line_index,
... | Append chunk_info to chunks if it is set. |
366,032 | def parse_s2bins(s2bins):
s2b = {}
b2s = {}
for line in s2bins:
line = line.strip().split()
s, b = line[0], line[1]
if in b:
continue
if len(line) > 2:
g = .join(line[2:])
else:
g =
b = % (b, g)
s2b[s] = b
... | parse ggKbase scaffold-to-bin mapping
- scaffolds-to-bins and bins-to-scaffolds |
366,033 | def _sysv_services():
_services = []
output = __salt__[]([, ], python_shell=False)
for line in output.splitlines():
comps = line.split()
try:
if comps[1].startswith():
_services.append(comps[0])
except IndexError:
continue
return ... | Return list of sysv services. |
366,034 | def owners(self):
result = set()
for role in self._OWNER_ROLES:
for member in self._bindings.get(role, ()):
result.add(member)
return frozenset(result) | Legacy access to owner role.
DEPRECATED: use ``policy["roles/owners"]`` instead. |
366,035 | def read_mrz(file, save_roi=False, extra_cmdline_params=):
p = MRZPipeline(file, extra_cmdline_params)
mrz = p.result
if mrz is not None:
mrz.aux[] = p[]
if save_roi:
mrz.aux[] = p[]
return mrz | The main interface function to this module, encapsulating the recognition pipeline.
Given an image filename, runs MRZPipeline on it, returning the parsed MRZ object.
:param file: A filename or a stream to read the file data from.
:param save_roi: when this is True, the .aux['roi'] field will contain the... |
366,036 | def eci2geodetic (x, y, z, gmst=None, ellipsoid=None):
if gmst is None:
gmst = dmc.toGMST()
if ellipsoid is None:
ellipsoid = WGS84
a = WGS84.a
b = WGS84.b
f = WGS84.f
r = math.sqrt((x * x) + (y * y))
e2 = (2 * f) - (f * f)
lon = math.atan2(y, x) - gmst
k = 0
kmax = 20... | Converts the given ECI coordinates to Geodetic coordinates at the
given Greenwich Mean Sidereal Time (GMST) (defaults to now) and with
the given ellipsoid (defaults to WGS84).
This code was adapted from
`shashwatak/satellite-js <https://github.com/shashwatak/satellite-js/blob/master/src/coordinate-transforms.j... |
366,037 | def handle(self, **options):
print("Starting clean up of django-defender table")
now = timezone.now()
cleanup_delta = timedelta(hours=config.ACCESS_ATTEMPT_EXPIRATION)
min_attempt_time = now - cleanup_delta
attempts_to_clean = AccessAttempt.objects.filter(
a... | Removes any entries in the AccessAttempt that are older
than your DEFENDER_ACCESS_ATTEMPT_EXPIRATION config, default 24 HOURS. |
366,038 | def set_cookie(cookies, key, value=, max_age=None, expires=None, path=,
domain=None, secure=False, httponly=False):
cookies[key] = value
if expires is not None:
if isinstance(expires, datetime):
now = (expires.now(expires.tzinfo) if expires.tzinfo else
... | Set a cookie key into the cookies dictionary *cookies*. |
366,039 | def _add_current_quay_tag(repo, container_tags):
if in repo:
return repo, container_tags
try:
latest_tag = container_tags[repo]
except KeyError:
repo_id = repo[repo.find() + 1:]
tags = requests.request("GET", "https://quay.io/api/v1/repository/" + repo_id).json()["tags"... | Lookup the current quay tag for the repository, adding to repo string.
Enables generation of CWL explicitly tied to revisions. |
366,040 | def pprint(string, token=[WORD, POS, CHUNK, PNP], column=4):
if isinstance(string, basestring):
print("\n\n".join([table(sentence, fill=column) for sentence in Text(string, token)]))
if isinstance(string, Text):
print("\n\n".join([table(sentence, fill=column) for sentence in string]))
i... | Pretty-prints the output of Parser.parse() as a table with outlined columns.
Alternatively, you can supply a tree.Text or tree.Sentence object. |
366,041 | def prune_train_dirs(dir_: str, epochs: int, subdirs: bool) -> None:
if dir_ == CXF_DEFAULT_LOG_DIR and not path.exists(CXF_DEFAULT_LOG_DIR):
print(
.format(CXF_DEFAULT_LOG_DIR))
quit(1)
if not path.exists(dir_):
print(.format(dir_))
quit(1)
_prune(dir_,... | Prune training log dirs contained in the given dir. The function is accessible through cxflow CLI `cxflow prune`.
:param dir_: dir to be pruned
:param epochs: minimum number of finished epochs to keep the training logs
:param subdirs: delete subdirs in training log dirs |
366,042 | def load_gene(ensembl, gene_id, de_novos=[]):
transcripts = minimise_transcripts(ensembl, gene_id, de_novos)
genes = []
for transcript_id in transcripts:
gene = construct_gene_object(ensembl, transcript_id)
genes.append(gene)
if len(genes) == 0:
raise IndexErr... | sort out all the necessary sequences and positions for a gene
Args:
ensembl: EnsemblRequest object to request data from ensembl
gene_id: HGNC symbol for gene
de_novos: list of de novo positions, so we can check they all fit in
the gene transcript
Returns:
... |
366,043 | def FromReadings(cls, uuid, readings, sent_timestamp=0):
header = struct.pack("<BBHLLL", cls.ReportType, 0, len(readings)*16, uuid, sent_timestamp, 0)
packed_readings = bytearray()
for reading in readings:
packed_reading = struct.pack("<HHLLL", reading.stream, 0, reading.... | Generate a broadcast report from a list of readings and a uuid. |
366,044 | def update_or_create(self, location, contact_addresses, with_status=False,
overwrite_existing=False, **kw):
updated, created = False, False
location_ref = location_helper(location)
if location_ref in self:
for loc in self:
if loc.location_ref == l... | Update or create a contact address and location pair. If the
location does not exist it will be automatically created. If the
server already has a location assigned with the same name, the
contact address specified will be added if it doesn't already
exist (Management and Log Server can ... |
366,045 | def child_count(self, only_direct=True):
if not only_direct:
count = 0
for _node in self.dfs_iter():
count += 1
return count
return len(self._children) | Returns how many children this node has, either only the direct
children of this node or inclusive of all children nodes of this node. |
366,046 | def get_filestore_instance(img_dir=None, data_dir=None):
global _filestore_instances
key = "%s:%s" % (img_dir, data_dir)
try:
instance = _filestore_instances[key]
except KeyError:
instance = FileStore(
img_dir=img_dir, data_dir=data_dir
)
_filestore_ins... | Return an instance of FileStore. |
366,047 | def _parse_ethtool_pppoe_opts(opts, iface):
config = {}
for opt in _DEB_CONFIG_PPPOE_OPTS:
if opt in opts:
config[opt] = opts[opt]
if in opts and not opts[]:
_raise_error_iface(iface, , _CONFIG_TRUE + _CONFIG_FALSE)
valid = _CONFIG_TRUE + _CONFIG_FALSE
for option... | Filters given options and outputs valid settings for ETHTOOLS_PPPOE_OPTS
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting. |
366,048 | def _save_to_database(url, property_name, data):
data = json.dumps([
d.to_dict() if hasattr(d, "to_dict") else d
for d in data
])
logger.debug("_save_to_database() data: %s" % repr(data))
requests.post(
_WEB_URL + _REQUEST_DB_SAVE,
timeout=REQUEST_TIMEOUT,
... | Store `data` under `property_name` in the `url` key in REST API DB.
Args:
url (obj): URL of the resource to which `property_name` will be stored.
property_name (str): Name of the property under which the `data` will
be stored.
data (obj): Any object. |
366,049 | def _access_through_cftimeindex(values, name):
from ..coding.cftimeindex import CFTimeIndex
values_as_cftimeindex = CFTimeIndex(values.ravel())
if name == :
months = values_as_cftimeindex.month
field_values = _season_from_months(months)
else:
field_values = getattr(values_as... | Coerce an array of datetime-like values to a CFTimeIndex
and access requested datetime component |
366,050 | def Column(self, column_name):
column_idx = None
for idx, column in enumerate(self.header.columns):
if column.name == column_name:
column_idx = idx
break
if column_idx is None:
raise KeyError("Column not found".format(column_name))
for row in self.rows:
yield ro... | Iterates over values of a given column.
Args:
column_name: A nome of the column to retrieve the values for.
Yields:
Values of the specified column.
Raises:
KeyError: If given column is not present in the table. |
366,051 | def unmatched_quotes_in_line(text):
text = text.replace(, )
if text.count() % 2:
return
elif text.count(""
else:
return | Return whether a string has open quotes.
This simply counts whether the number of quote characters of either
type in the string is odd.
Take from the IPython project (in IPython/core/completer.py in v0.13)
Spyder team: Add some changes to deal with escaped quotes
- Copyright (C) 2008-2011 IPython... |
366,052 | def _get_metrics_to_collect(self, instance_key, additional_metrics):
if instance_key not in self.metrics_to_collect_by_instance:
self.metrics_to_collect_by_instance[instance_key] = self._build_metric_list_to_collect(additional_metrics)
return self.metrics_to_collect_by_instance[inst... | Return and cache the list of metrics to collect. |
366,053 | def add_template_events_to_network(self, columns, vectors):
self.template_events = self.template_event_dict[]
self.add_template_network_events(columns, vectors)
self.template_event_dict[] = self.template_events
self.template_events = None | Add a vector indexed |
366,054 | def press_keys(self,characters=[]):
for character in characters:
self.press_key(character)
for character in characters:
self.release_key(character) | Press a given character key. |
366,055 | def y(self, y):
if y is None:
return None
if self._force_vertical:
return super(HorizontalView, self).y(y)
return super(HorizontalView, self).x(y) | Project y as x |
366,056 | def insertUnorderedList(self):
cursor = self.editor().textCursor()
currlist = cursor.currentList()
new_style = QTextListFormat.ListDisc
indent = 1
if currlist:
format = currlist.format()
indent = format.indent() + 1
... | Inserts an ordered list into the editor. |
366,057 | def parse_link_header(link):
rel_dict = {}
for rels in link.split():
rel_break = quoted_split(rels, )
try:
rel_url = re.search(, rel_break[0]).group(1)
rel_names = quoted_split(rel_break[1], )[-1]
if rel_names.startswith() and rel_names.endswith():
... | takes the link header as a string and returns a dictionary with rel values as keys and urls as values
:param link: link header as a string
:rtype: dictionary {rel_name: rel_value} |
366,058 | def is_trusted_subject(request):
logging.debug(.format(.join(request.all_subjects_set)))
logging.debug(.format(.join(get_trusted_subjects())))
return not request.all_subjects_set.isdisjoint(get_trusted_subjects()) | Determine if calling subject is fully trusted. |
366,059 | def _init_transformer_cache(cache, hparams, batch_size, attention_init_length,
encoder_output, encoder_decoder_attention_bias,
scope_prefix):
key_channels = hparams.attention_key_channels or hparams.hidden_size
value_channels = hparams.attention_value_chann... | Create the initial cache for Transformer fast decoding. |
366,060 | def features_tags_parse_str_to_dict(obj):
features = obj[]
for i in tqdm(range(len(features))):
tags = features[i][].get()
if tags is not None:
try:
tags = json.loads("{" + tags.replace("=>", ":") + "}")
except:
try:
... | Parse tag strings of all features in the collection into a Python
dictionary, if possible. |
366,061 | def infer_id(self, ident, diagnostic=None):
defined = self.infer_node.scope_node.get_by_symbol_name(ident)
if len(defined) > 0:
self.infer_node.scope_node.update(defined)
else:
diagnostic.notify(
Severit... | Infer type from an ID!
- check if ID is declarated in the scope
- if no ID is polymorphic type |
366,062 | def patch(self, pid, record, **kwargs):
data = self.loaders[request.mimetype]()
if data is None:
raise InvalidDataRESTError()
self.check_etag(str(record.revision_id))
try:
record = record.patch(data)
except (JsonPatchException, JsonPointerExcepti... | Modify a record.
Permissions: ``update_permission_factory``
The data should be a JSON-patch, which will be applied to the record.
Requires header ``Content-Type: application/json-patch+json``.
Procedure description:
#. The record is deserialized using the proper loader.
... |
366,063 | def get_form_instance(self, request, data=None, instance=None):
defaults = {}
if self.form:
defaults[] = self.form
if self.fields:
defaults[] = self.fields
return modelform_factory(self.model, **defaults)(data=data, instance=instance) | Returns an instantiated form to be used for adding or editing an object.
The `instance` argument is the model instance (passed only if this form
is going to be used for editing an existing object). |
366,064 | def _check_branch(self, revision, branch):
t find it
json-log' / revision
try:
Log.note("Searching through changelog {{url}}", url=clog_url)
clog_obj = http.get_json(clog_url, retry=RETRY)
if isinstance(clog_obj, (text_type, str)):
Log.note(
... | Used to find out if the revision is in the given branch.
:param revision: Revision to check.
:param branch: Branch to check revision on.
:return: True/False - Found it/Didn't find it |
366,065 | def get_help(self):
current_state = self.get_current_state()
if current_state is None:
return statement(INTERNAL_ERROR_MSG)
else:
try:
return choice(self._scenario_steps[current_state][])
except KeyError:
return choice(... | Get context help, depending on the current step. If no help for current step
was specified in scenario description file, default one will be returned. |
366,066 | def _to_map_job_config(cls,
mr_spec,
queue_name):
mapper_spec = mr_spec.mapper
api_version = mr_spec.params.get("api_version", 0)
old_api = api_version == 0
input_reader_cls = mapper_spe... | Converts model.MapreduceSpec back to JobConfig.
This method allows our internal methods to use JobConfig directly.
This method also allows us to expose JobConfig as an API during execution,
despite that it is not saved into datastore.
Args:
mr_spec: model.MapreduceSpec.
queue_name: queue n... |
366,067 | def get_generator(self, path, *args, **kw_args):
q = self.get_queue(path=path, *args, **kw_args)
try:
for guard in q.iter():
with guard as batch:
batch_copy = batch.copy()
for row in batch_copy:
y... | Get a generator that allows convenient access to the streamed data.
Elements from the dataset are returned from the generator one row at a time.
Unlike the direct access queue, this generator also returns the remainder elements.
Additional arguments are forwarded to get_queue.
See the ge... |
366,068 | def default_should_trace_hook(frame, filename):
ignored_lines = _filename_to_ignored_lines.get(filename)
if ignored_lines is None:
ignored_lines = {}
lines = linecache.getlines(filename)
for i_line... | Return True if this frame should be traced, False if tracing should be blocked. |
366,069 | def _string_from_ip_int(self, ip_int):
octets = []
for _ in xrange(4):
octets.insert(0, str(ip_int & 0xFF))
ip_int >>= 8
return .join(octets) | Turns a 32-bit integer into dotted decimal notation.
Args:
ip_int: An integer, the IP address.
Returns:
The IP address as a string in dotted decimal notation. |
366,070 | def create(self, dataset_name, query, index_by, display_name):
url = "{0}/{1}".format(self._cached_datasets_url, dataset_name)
payload = {
"query": query,
"index_by": index_by,
"display_name": display_name
}
return self._get_json(HTTPMethods.P... | Create a Cached Dataset for a Project. Master key must be set. |
366,071 | def github_gfonts_ttFont(ttFont, license):
if not license:
return
from fontbakery.utils import download_file
from fontTools.ttLib import TTFont
from urllib.request import HTTPError
LICENSE_DIRECTORY = {
"OFL.txt": "ofl",
"UFL.txt": "ufl",
"LICENSE.txt": "apache"
}
filename = os.path.ba... | Get a TTFont object of a font downloaded
from Google Fonts git repository. |
366,072 | def authenticated_request(self, endpoint, method=, params=None, data=None):
X-Access-TokenX-Client-ID
headers = {
: self.access_token,
: self.client_id
}
return self.api.request(endpoint, method=method, headers=headers, params=params, data=data) | Send a request to the given Wunderlist API with 'X-Access-Token' and 'X-Client-ID' headers and ensure the response code is as expected given the request type
Params:
endpoint -- API endpoint to send request to
Keyword Args:
method -- GET, PUT, PATCH, DELETE, etc.
params -- para... |
366,073 | def yaml_load(source, defaultdata=NO_DEFAULT):
logger = logging.getLogger(__name__)
logger.debug("initialized with source=%s, defaultdata=%s", source, defaultdata)
if defaultdata is NO_DEFAULT:
data = None
else:
data = defaultdata
files = []
if type(source) is not str and le... | merge YAML data from files found in source
Always returns a dict. The YAML files are expected to contain some kind of
key:value structures, possibly deeply nested. When merging, lists are
appended and dict keys are replaced. The YAML files are read with the
yaml.safe_load function.
source can be a... |
366,074 | def get_path_url(path, relative=False):
if relative:
return os.path.relpath(path)
else:
return % os.path.abspath(path) | Returns an absolute or relative path url given a path |
366,075 | def distance(p1, p2):
def xyz(some_pose):
if isinstance(some_pose, PoseStamped):
return some_pose.pose.position.x, some_pose.pose.position.y, some_pose.pose.position.z
elif isinstance(some_pose, Pose):
return some_pose.position.x, some_pose.position.y, some_pose.positio... | Cartesian distance between two PoseStamped or PoseLists
:param p1: point 1 (list, Pose or PoseStamped)
:param p2: point 2 (list, Pose or PoseStamped)
:return: cartesian distance (float) |
366,076 | def visit_break(self, node, parent):
return nodes.Break(
getattr(node, "lineno", None), getattr(node, "col_offset", None), parent
) | visit a Break node by returning a fresh instance of it |
366,077 | def lm_tfinal(damping_times, modes):
t_max = {}
for lmn in modes:
l, m, nmodes = int(lmn[0]), int(lmn[1]), int(lmn[2])
for n in range(nmodes):
t_max[ %(l,m,n)] = \
qnm_time_decay(damping_times[ %(l,m,n)], 1./1000)
return max(t_max.values()) | Return the maximum t_final of the modes given, with t_final the time
at which the amplitude falls to 1/1000 of the peak amplitude |
366,078 | def nvrtcGetLoweredName(self, prog, name_expression):
lowered_name = c_char_p()
code = self._lib.nvrtcGetLoweredName(prog,
c_char_p(encode_str(name_expression)),
byref(lowered_name))
self._throw_on... | Notes the given name expression denoting a __global__ function or
function template instantiation. |
366,079 | def host2id(self, hostname):
for key, value in self.server_map.items():
if value == hostname:
return key | return member id by hostname |
366,080 | def cat_acc(y_true, y_pred):
return np.mean(y_true.argmax(axis=1) == y_pred.argmax(axis=1)) | Categorical accuracy |
366,081 | def parse_latitude(latitude, hemisphere):
latitude = int(latitude[:2]) + float(latitude[2:]) / 60
if hemisphere == :
latitude = -latitude
elif not hemisphere == :
raise ValueError( % hemisphere)
return latitude | Parse a NMEA-formatted latitude pair.
Args:
latitude (str): Latitude in DDMM.MMMM
hemisphere (str): North or South
Returns:
float: Decimal representation of latitude |
366,082 | def _arguments_repr(self):
document_class_repr = (
if self.document_class is dict
else repr(self.document_class))
uuid_rep_repr = UUID_REPRESENTATION_NAMES.get(self.uuid_representation,
self.uuid_representation)
... | Representation of the arguments used to create this object. |
366,083 | def format_decimal(decimal):
normalized = decimal.normalize()
sign, digits, exponent = normalized.as_tuple()
if exponent >= 1:
normalized = normalized.quantize(1)
return str(normalized) | Formats a decimal number
:param decimal: the decimal value
:return: the formatted string value |
366,084 | def _del_cached_value(self, xblock):
if hasattr(xblock, ) and self.name in xblock._field_data_cache:
del xblock._field_data_cache[self.name] | Remove a value from the xblock's cache, if the cache exists. |
366,085 | def multi_conv_res(x, padding, name, layers, hparams, mask=None, source=None):
with tf.variable_scope(name):
padding_bias = None
if mask is not None:
padding_bias = (1.0 - mask) * -1e9
if padding == "LEFT":
mask = None
if (hparams.kernel_scheme in _KERNEL_SCHEMES and
hpa... | A stack of separable convolution blocks with residual connections. |
366,086 | def is_Type(tp):
if isinstance(tp, type):
return True
try:
typing._type_check(tp, )
return True
except TypeError:
return False | Python version independent check if an object is a type.
For Python 3.7 onwards(?) this is not equivalent to
``isinstance(tp, type)`` any more, as that call would return
``False`` for PEP 484 types.
Tested with CPython 2.7, 3.5, 3.6, 3.7 and Jython 2.7.1. |
366,087 | def get_ip_address_info(ip_address, cache=None, nameservers=None,
timeout=2.0, parallel=False):
ip_address = ip_address.lower()
if cache:
info = cache.get(ip_address, None)
if info:
return info
info = OrderedDict()
info["ip_address"] = ip_address
... | Returns reverse DNS and country information for the given IP address
Args:
ip_address (str): The IP address to check
cache (ExpiringDict): Cache storage
nameservers (list): A list of one or more nameservers to use
(Cloudflare's public DNS resolvers by default)
timeout (float... |
366,088 | def __general(self):
while 1:
try:
tok = self.__peek()
except DXParserNoTokens:
if self.currentobject and self.currentobject not in self.objects:
... | Level-0 parser and main loop.
Look for a token that matches a level-1 parser and hand over control. |
366,089 | def _compare_strings(cls, source, target):
start = 0
end = len(source)
begins = 0
ends = 0
if source.startswith(CPEComponent2_3_WFN.WILDCARD_MULTI):
start = 1
begins = -1
else:
while ((start < len(source... | Compares a source string to a target string,
and addresses the condition in which the source string
includes unquoted special characters.
It performs a simple regular expression match,
with the assumption that (as required) unquoted special characters
appear only at the beginnin... |
366,090 | def resolve(self, cfg, addr, func_addr, block, jumpkind):
project = self.project
b = Blade(cfg.graph, addr, -1, cfg=cfg, project=project, ignore_sp=True, ignore_bp=True,
ignored_regs=(,)
)
sources = [n for n in b.slice.nodes() if b.slice.in_degree(... | Resolves the indirect jump in MIPS ELF binaries where all external function calls are indexed using gp.
:param cfg: A CFG instance.
:param int addr: IRSB address.
:param int func_addr: The function address.
:param pyvex.IRSB block: The IRSB.
:param str jumpkind: The jumpkind.
... |
366,091 | def register_resources(klass, registry, resource_class):
config_type = getattr(resource_class.resource_type, , None)
if config_type is None:
return
resource_class.filter_registry.register(, klass) | meta model subscriber on resource registration.
We watch for new resource types being registered and if they
support aws config, automatically register the jsondiff filter. |
366,092 | def create_service(self, name, **kwargs):
data = self._wrap_dict("service", kwargs)
data["customer"]["name"] = name
return self.post("/services.json", data=data) | Creates a service with a name. All other parameters are optional. They
are: `note`, `hourly_rate`, `billable`, and `archived`. |
366,093 | def sync_user_email_addresses(user):
from .models import EmailAddress
email = user_email(user)
if email and not EmailAddress.objects.filter(user=user,
email__iexact=email).exists():
if app_settings.UNIQUE_EMAIL \
and EmailAddress.... | Keep user.email in sync with user.emailaddress_set.
Under some circumstances the user.email may not have ended up as
an EmailAddress record, e.g. in the case of manually created admin
users. |
366,094 | def get_item_at(self, *args, **kwargs):
return self.proxy.get_item_at(coerce_point(*args, **kwargs)) | Return the items at the given position |
366,095 | def flag(name=None):
if name is None:
name =
field = pp.Regex()
field.setName(name)
field.leaveWhitespace()
return field | Creates the grammar for a Flag (F) field, accepting only 'Y', 'N' or 'U'.
:param name: name for the field
:return: grammar for the flag field |
366,096 | def help(file=None):
helpstr = getHelpAsString(docstring=True, show_ver=True)
if file is None:
print(helpstr)
else:
with open(file, mode=) as f:
f.write(helpstr) | Print out syntax help for running ``astrodrizzle``
Parameters
----------
file : str (Default = None)
If given, write out help to the filename specified by this parameter
Any previously existing file with this name will be deleted before
writing out the help. |
366,097 | def artist_top_tracks(self, spotify_id, country):
route = Route(, , spotify_id=spotify_id)
payload = {: country}
return self.request(route, params=payload) | Get an artists top tracks per country with their ID.
Parameters
----------
spotify_id : str
The spotify_id to search by.
country : COUNTRY_TP
COUNTRY |
366,098 | def _make_cookie(self):
return struct.pack(self.COOKIE_FMT, self.COOKIE_MAGIC,
os.getpid(), id(self), thread.get_ident()) | Return a string encoding the ID of the process, instance and thread.
This disambiguates legitimate wake-ups, accidental writes to the FD,
and buggy internal FD sharing. |
366,099 | def MaxLikeInterval(self, percentage=90):
interval = []
total = 0
t = [(prob, val) for val, prob in self.Items()]
t.sort(reverse=True)
for prob, val in t:
interval.append(val)
total += prob
if total >= percentage / 100.0:
... | Returns the maximum-likelihood credible interval.
If percentage=90, computes a 90% CI containing the values
with the highest likelihoods.
percentage: float between 0 and 100
Returns: list of values from the suite |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.