Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
342,100 | def worker(data, json_file):
with open(json_file) as fp:
d = json.load(fp)
json_directory = os.path.dirname(json_file)
def p(*parts):
return os.path.join(json_directory, *parts)
log_file = data[]
savecmd_file = data[]
template_file = data[]
if... | Handle parameter substitution and execute command as child process. |
342,101 | def _logger(self):
log_level = {
: logging.DEBUG,
: logging.INFO,
: logging.WARNING,
: logging.ERROR,
: logging.CRITICAL,
}
level = log_level.get(self.args.logging_level.lower())
tx_format =
tx_format... | Create logger instance.
Returns:
logger: An instance of logging |
342,102 | def rangify(number_list):
if not number_list:
return number_list
ranges = []
range_start = prev_num = number_list[0]
for num in number_list[1:]:
if num != (prev_num + 1):
ranges.append((range_start, prev_num))
range_start = num
prev_num = num
r... | Assumes the list is sorted. |
342,103 | def _stop_remote_console(self):
if self._telnet_server:
self._telnet_server.close()
yield from self._telnet_server.wait_closed()
self._remote_pipe.close()
self._telnet_server = None | Stops remote console support for this VM. |
342,104 | def blow_out(self,
location: Union[types.Location, Well] = None
) -> :
if location is None:
if not self._ctx.location_cache:
raise RuntimeError()
else:
location = self._ctx.location_cache.labware
... | Blow liquid out of the tip.
If :py:attr:`dispense` is used to completely empty a pipette,
usually a small amount of liquid will remain in the tip. This
method moves the plunger past its usual stops to fully remove
any remaining liquid from the tip. Regardless of how much liquid
... |
342,105 | def populate(self, priority, address, rtr, data):
assert isinstance(data, bytes)
self.needs_no_rtr(rtr)
self.needs_data(data, 7)
self.set_attributes(priority, address, rtr)
self.channel = (data[0] & 0x03) +1
self.pulses = (data[0] >> 2) * 100
self.counte... | -DB1 last 2 bits = channel
-DB1 first 6 bist = pulses
-DB2-5 = pulse counter
-DB6-7 = ms/pulse
:return: None |
342,106 | def fill_output_table(filelist, hdu, collist, nbins):
nfiles = len(filelist)
shape = (nbins, nfiles)
outdict = {}
for c in collist:
outdict[c[]] = np.ndarray(shape)
sys.stdout.write( % nfiles)
sys.stdout.flush()
for i, f in enumerate(filelist):
sys.stdout.write()
... | Fill the arrays from the files in filelist
Parameters
----------
filelist : list
List of the files to get data from.
hdu : str
Name of the HDU containing the table with the input data.
colllist : list
List of the column names
nbins : int
Number of bins in the... |
342,107 | def _external_pillar_data(self, pillar, val, key):
ext = None
args = salt.utils.args.get_function_argspec(self.ext_pillars[key]).args
if isinstance(val, dict):
if ( in args) and self.extra_minion_data:
ext = self.ext_pillars[key](
self.mi... | Builds actual pillar data structure and updates the ``pillar`` variable |
342,108 | def set_linkage_method(self, method):
if method == :
self.linkage = single
elif method == :
self.linkage = complete
elif method == :
self.linkage = average
elif method == :
self.linkage = uclus
elif hasattr(method, ):
... | Sets the method to determine the distance between two clusters.
:param method: The method to use. It can be one of ``'single'``,
``'complete'``, ``'average'`` or ``'uclus'``, or a callable. The
callable should take two collections as parameters and return a
distance value be... |
342,109 | def ObjectEnum(ctx):
return Enum(
ctx,
villager_male=83,
villager_female=293,
scout_cavalry=448,
eagle_warrior=751,
king=434,
flare=332,
relic=285,
turkey=833,
sheep=594,
deer=65,
boar=48,
iron_boar=810,
... | Object Enumeration.
Should export the whole list from the game for the best accuracy. |
342,110 | def get_beamarea_deg2(self, ra, dec):
barea = abs(self.beam.a * self.beam.b * np.pi)
if self.lat is not None:
barea /= np.cos(np.radians(dec - self.lat))
return barea | Calculate the area of the synthesized beam in square degrees.
Parameters
----------
ra, dec : float
The sky coordinates at which the calculation is made.
Returns
-------
area : float
The beam area in square degrees. |
342,111 | def replace(self, messages, domain=):
assert isinstance(messages, (dict, CaseInsensitiveDict))
assert isinstance(domain, (str, unicode))
self.messages[domain] = CaseInsensitiveDict({})
self.add(messages, domain) | Sets translations for a given domain. |
342,112 | def remove(cls, name):
api = Client.instance().api
api.collection(name).delete() | Destroys collection.
:param name Collection name |
342,113 | def atomic_download(handle,
download_fn,
module_dir,
lock_file_timeout_sec=10 * 60):
lock_file = _lock_filename(module_dir)
task_uid = uuid.uuid4().hex
lock_contents = _lock_file_contents(task_uid)
tmp_dir = _temp_download_dir(module_dir, task_uid)
... | Returns the path to a Module directory for a given TF-Hub Module handle.
Args:
handle: (string) Location of a TF-Hub Module.
download_fn: Callback function that actually performs download. The callback
receives two arguments, handle and the location of a temporary
directory ... |
342,114 | def case(self, case_id=None):
cases = self.cases()
if case_id:
for case in cases:
if case.case_id == case_id:
return case
else:
if cases:
return cases[0]
return None | Return a Case object
If no case_id is given return one case
Args:
case_id (str): A case id
Returns:
case(Case): A Case object |
342,115 | def main():
prog = sys.argv[0]
arg_parser = create_parser(prog)
opts = parse_cmdline(arg_parser)
print(
%
(opts.server, opts.user, opts.namespace, opts.classname,
opts.max_object_count, opts.usepull))
conn = WBEMConnection(opts.server, (opts.user, opts.p... | Get arguments and call the execution function |
342,116 | def content(self):
if not self._content:
self._content = self._read()
return self._content | Get the file contents.
This property is cached. The file is only read once. |
342,117 | def refine(video, embedded_subtitles=True, **kwargs):
if not video.exists:
return
extension = os.path.splitext(video.name)[1]
if extension == :
with open(video.name, ) as f:
mkv = MKV(f)
if mkv.video_tracks:
video_track = mkv.video_tr... | Refine a video by searching its metadata.
Several :class:`~subliminal.video.Video` attributes can be found:
* :attr:`~subliminal.video.Video.resolution`
* :attr:`~subliminal.video.Video.video_codec`
* :attr:`~subliminal.video.Video.audio_codec`
* :attr:`~subliminal.video.Video.subtitle_lan... |
342,118 | def update(self, E=None, **F):
if hasattr(E, ):
self.extend(E)
else:
for key, value in E:
self._set_key(key, value)
self.extend(F) | D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
If E present and has a .keys() method, does: for k in E: D[k] = E[k]
If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v
In either case, this is followed by: for k in F: D[k] = F[k] |
342,119 | def reportTime(t, options, field=None):
if options.pretty:
return prettyTime(t, field=field)
else:
if field is not None:
return "%*.2f" % (field, t)
else:
return "%.2f" % t | Given t seconds, report back the correct format as string. |
342,120 | def p_cardinality_1(self, p):
if p[1] != :
raise ParsingException("illegal cardinality (%s) at %s:%d" % (p[1],
p.lexer.filename, p.lineno(1)))
p[0] = p[1] | cardinality : NUMBER |
342,121 | def _to_dict(self):
_dict = {}
if hasattr(self, ) and self.document_id is not None:
_dict[] = self.document_id
if hasattr(self,
) and self.configuration_id is not None:
_dict[] = self.configuration_id
if hasattr(self, ) and self.status ... | Return a json dictionary representing this model. |
342,122 | def clark(self, databasepath):
if self.clarkpath:
logging.info()
databasepath = self.create_database_folder(databasepath, )
| Download and set-up the CLARK database using the set_targets.sh script. Use defaults of bacteria for database
type, and species for taxonomic level
:param databasepath: path to use to save the database |
342,123 | def _getgroup(string, depth):
out, comma = [], False
while string:
items, string = _getitem(string, depth)
if not string:
break
out += items
if string[0] == :
if comma:
return out, string[1:]
return [ + a + for a in out]... | Get a group from the string, where group is a list of all the comma
separated substrings up to the next '}' char or the brace enclosed substring
if there is no comma |
342,124 | def translate(line, ascent, offs=0):
ascent *= -2
offs *= -2
l0 = length(line)
t0 = offs
t1 = l0 * ascent + offs
return translate2P(line, t0, t1) | offs -> shifts parallel to line
ascent -> rotate line |
342,125 | def worker_recover(worker, lbn, profile=):
**
cmd = {
: ,
: ,
: lbn,
: worker,
}
return _do_http(cmd, profile) | Set the worker to recover
this module will fail if it is in OK state
CLI Examples:
.. code-block:: bash
salt '*' modjk.worker_recover node1 loadbalancer1
salt '*' modjk.worker_recover node1 loadbalancer1 other-profile |
342,126 | def _get_platform(self):
try:
return PLATFORMS[self.projection_name]
except KeyError:
logger.error(
.format(self.projection_name))
return UNKNOWN_PLATFORM | Get the platform name
The platform is not specified explicitly in JMA HRIT files. For
segmented data it is not even specified in the filename. But it
can be derived indirectly from the projection name:
GEOS(140.00): MTSAT-1R
GEOS(140.25): MTSAT-1R # TODO: Check if th... |
342,127 | def _bcrypt_interpret_ec_key_blob(key_type, blob_struct, blob):
magic = native(int, blob_struct.dwMagic)
key_byte_length = native(int, blob_struct.cbKey)
curve = {
BcryptConst.BCRYPT_ECDSA_PRIVATE_P256_MAGIC: ,
BcryptConst.BCRYPT_ECDSA_PRIVATE_P384_MAGIC: ,
BcryptConst.BCRYPT_... | Take a CNG BCRYPT_ECCKEY_BLOB and converts it into an ASN.1 structure
:param key_type:
A unicode string of "private" or "public"
:param blob_struct:
An instance of BCRYPT_ECCKEY_BLOB
:param blob:
A byte string of the binary data contained after the struct
:return:
An ... |
342,128 | def update(self, request, *args, **kwargs):
with transaction.atomic():
return self._update(request, *args, **kwargs) | Update a resource. |
342,129 | def train(dataset):
with tf.Graph().as_default(), tf.device():
global_step = tf.get_variable(
, [],
initializer=tf.constant_initializer(0), trainable=False)
num_batches_per_epoch = (dataset.num_examples_per_epoch() /
FLAGS.batch_size)
decay_s... | Train on dataset for a number of steps. |
342,130 | def coordinates_to_array(
log,
ra,
dec):
log.info()
if isinstance(ra, np.ndarray) and isinstance(dec, np.ndarray):
return ra, dec
converter = unit_conversion(
log=log
)
if isinstance(ra, float):
pass
elif isinstance(ra, str):
... | *Convert a single value RA, DEC or list of RA and DEC to numpy arrays*
**Key Arguments:**
- ``ra`` -- list, numpy array or single ra value
- ``dec`` --list, numpy array or single dec value
- ``log`` -- logger
**Return:**
- ``raArray`` -- input RAs as a numpy array of decimal de... |
342,131 | def __get_size_and_entry_point(self):
"Get the size and entry point of the module using the Win32 API."
process = self.get_process()
if process:
try:
handle = process.get_handle( win32.PROCESS_VM_READ |
win32.PROCESS_QUERY_... | Get the size and entry point of the module using the Win32 API. |
342,132 | def isAuthorized(self, pid, action, vendorSpecific=None):
response = self.isAuthorizedResponse(pid, action, vendorSpecific)
return self._read_boolean_401_response(response) | Return True if user is allowed to perform ``action`` on ``pid``, else
False. |
342,133 | def parse_config_path(args=sys.argv):
config = CONFIG_PATH
if in args:
idx = args.index()
if len(args) > idx + 1:
config = args.pop(idx + 1)
args.pop(idx)
return config | Preprocess sys.argv and extract --config argument. |
342,134 | def graded_submissions(self):
qs = self._valid_submissions().filter(state__in=[Submission.GRADED])
return qs | Queryset for the graded submissions, which are worth closing. |
342,135 | def get(cls, name_or_numeric):
if isinstance(name_or_numeric, six.string_types):
name_or_numeric = getattr(cls, name_or_numeric.upper())
return cls.values.get(name_or_numeric) | Get Enum.Value object matching the value argument.
:param name_or_numeric: Integer value or attribute name
:type name_or_numeric: int or str
:rtype: Enum.Value |
342,136 | def set_enabled_scanners(self, scanners):
self.logger.debug()
self.zap.ascan.disable_all_scanners()
self.enable_scanners(scanners) | Set only the provided scanners by group and/or IDs and disable all others. |
342,137 | def get_records(self, url):
page = urllib2.urlopen(url)
pages = [BeautifulSoup(page)]
numpag = pages[0].body.findAll(, attrs={: })
if len(numpag) > 0:
if re.search(, numpag[0].string):
for i in range(int(numpag[0].string)-1):
... | Returns the records listed in the webpage given as
parameter as a xml String.
@param url: the url of the Journal, Book, Protocol or Reference work |
342,138 | def replace_wires(wire_map, block=None):
block = working_block(block)
src_nets, dst_nets = block.net_connections(include_virtual_nodes=False)
for old_w, new_w in wire_map.items():
replace_wire_fast(old_w, new_w, new_w, src_nets, dst_nets, block) | Quickly replace all wires in a block
:param {old_wire: new_wire} wire_map: mapping of old wires to
new wires |
342,139 | def is_iterable(value, include_maps=False, include_sets=True):
if hasattr(value, ):
if not include_maps and hasattr(value, ):
return False
if not include_sets and hasattr(value, ):
return False
return True
else:
return False | Returns whether value is iterable.
``include_maps``
Maps are technically iterable, defaulting to their keys, but you
commonly want to find if it is a list-like type and leave maps alone,
so this is False by default.
``include_sets``
Sets are also technically iterab... |
342,140 | def start(self) -> None:
self._shutdown = False
if isinstance(self._protocol, Server):
self.create_task(self._async_listen)
elif isinstance(self._protocol, Client):
self.create_task(self._async_open)
else:
raise NotImplementedError | Start monitoring the base unit. |
342,141 | def _mask_invalid(self, data, header):
invalid = da.logical_or(data == header[]["count_value_outside_scan_pixels"][0],
data == header[]["count_value_error_pixels"][0])
return da.where(invalid, np.float32(np.nan), data) | Mask invalid data |
342,142 | def authorize_url(self):
if self.oauth2_params and self.oauth2_params.get("display") == "mobile":
auth_url = self.mobile_url + "authorize"
else:
auth_url = self.site_url + "authorize"
params = {
: self.client_id,
: self.redirect_url,
... | authorization url
request weibo authorization url
:return:
code string 用于第二步调用oauth2/access_token接口,获取授权后的access token。
state string 如果传递参数,会回传该参数 |
342,143 | def ensure_build(self):
if self.config.build_url:
path = get_buildfile_path(self.config)
mkdir(BUILDS_ROOT)
build_md5 = getattr(self.config, , None)
ensure_file(self.config.build_url, path, build_md5)
self.untar() | If self.config.build_url is set, ensure it's been downloaded to the
builds folder. |
342,144 | def pad(self, start_duration=0.0, end_duration=0.0):
if not is_number(start_duration) or start_duration < 0:
raise ValueError("Start duration must be a positive number.")
if not is_number(end_duration) or end_duration < 0:
raise ValueError("End duration must be positive... | Add silence to the beginning or end of a file.
Calling this with the default arguments has no effect.
Parameters
----------
start_duration : float
Number of seconds of silence to add to beginning.
end_duration : float
Number of seconds of silence to add t... |
342,145 | def module_to_package_data(
name: str,
entry,
path_prefixes: list = None
) -> typing.Union[dict, None]:
if name.find() > -1:
return None
version = getattr(entry, , None)
version = version if not hasattr(version, ) else version.version
location = getattr(en... | Converts a module entry into a package data dictionary with information
about the module. including version and location on disk
:param name:
:param entry:
:param path_prefixes:
:return: |
342,146 | def _construct_params(params, required_keys, opt_keys=None):
try:
params_list = [params.pop(key) for key in required_keys]
except KeyError as e:
raise MissingParameter(
% e)
if opt_keys:
params_list.extend([params.pop(key)
... | Construct params list in order of given keys. |
342,147 | def get_in_ip_addr(cls, tenant_id):
if tenant_id not in cls.serv_obj_dict:
LOG.error("Fabric not prepared for tenant %s", tenant_id)
return
tenant_obj = cls.serv_obj_dict.get(tenant_id)
return tenant_obj.get_in_ip_addr() | Retrieves the 'in' service subnet attributes. |
342,148 | def update(self, body=values.unset, attributes=values.unset):
return self._proxy.update(body=body, attributes=attributes, ) | Update the MessageInstance
:param unicode body: The new message body string.
:param unicode attributes: The new attributes metadata field you can use to store any data you wish.
:returns: Updated MessageInstance
:rtype: twilio.rest.chat.v1.service.channel.message.MessageInstance |
342,149 | def separator(self):
cells = dict([(column, "-" * self.column_widths[column]) for column in self.columns])
return ColorRow(self, **cells) | Generate a separator row using current column widths. |
342,150 | def fetch_top_tracks_of_artist(self, artist_id, terr=KKBOXTerritory.TAIWAN):
https://docs-en.kkbox.codes/v1.1/reference
url = % artist_id
url += + url_parse.urlencode({: terr})
return self.http._post_data(url, None, self.http._headers_with_access_token()) | Fetcher top tracks belong to an artist by given ID.
:param artist_id: the artist ID.
:type artist_id: str
:param terr: the current territory.
:return: API response.
:rtype: dict
See 'https://docs-en.kkbox.codes/v1.1/reference#artists-artist_id-toptracks' |
342,151 | def creators_grouped_by_role(self):
role = -1
creators = []
for wc in self:
if wc.role != role:
if creators:
yield (role, creators)
role = wc.role
creators = []
creators.append(wc.creator)
... | :return: A generator yielding 2-tuples of (role, [creators]) where
adjacent creators who share the same role are grouped together. |
342,152 | def random_line_data(chars_per_line=80):
return .join(__random.choice(__string.ascii_letters) for x in range(chars_per_line)) | Function to create a line of a random string
Args:
chars_per_line: An integer that says how many characters to return
Returns:
A String |
342,153 | def set_printed_time(self, sample):
if api.get_workflow_status_of(sample) != "published":
return False
reports = sample.objectValues("ARReport")
reports = sorted(reports, key=lambda report: report.getDatePublished())
last_report = reports[-1]
if not last_repo... | Updates the printed time of the last results report from the sample |
342,154 | def _integrate_storage(self, timeseries, position, params, voltage_level,
reactive_power_timeseries, **kwargs):
params = self._check_nominal_power(params, timeseries)
if isinstance(position, Station) or isinstance(position, BranchTee) \
or isi... | Integrate storage units in the grid.
Parameters
----------
timeseries : :obj:`str` or :pandas:`pandas.Series<series>`
Parameter used to obtain time series of active power the storage
storage is charged (negative) or discharged (positive) with. Can
either be a... |
342,155 | def update(self, vrfs):
data = {: vrfs}
vrfs_ids = [str(vrf.get()) for vrf in vrfs]
return super(ApiVrf, self).put( %
.join(vrfs_ids), data) | Method to update vrf's
:param vrfs: List containing vrf's desired to updated
:return: None |
342,156 | def _build_tag_param_list(params, tags):
keys = sorted(tags.keys())
i = 1
for key in keys:
value = tags[key]
params[.format(i)] = key
if value is not None:
params[.format(i)] = value
i += 1 | helper function to build a tag parameter list to send |
342,157 | def expireat(self, name, when):
if isinstance(when, datetime.datetime):
when = int(mod_time.mktime(when.timetuple()))
return self.execute_command(, name, when) | Set an expire flag on key ``name``. ``when`` can be represented
as an integer indicating unix time or a Python datetime object. |
342,158 | def statistics(cls, function, group=None):
benchmark = cls.results(function, group)
results = {}
for name, stat in {: numpy.average, : numpy.amax, : numpy.median, : numpy.amin, : numpy.sum}.items():
results[name] = stat(benchmark, axis=0)
return results | Compute statistics (average, max, median, minimun and sum) from _results
into a dictionary of numpy array. |
342,159 | def getAttributeValueType(self, index):
offset = self._get_attribute_offset(index)
return self.m_attributes[offset + const.ATTRIBUTE_IX_VALUE_TYPE] | Return the type of the attribute at the given index
:param index: index of the attribute |
342,160 | def cart2dir(self,cart):
cart=numpy.array(cart)
rad=old_div(numpy.pi,180.)
if len(cart.shape)>1:
Xs,Ys,Zs=cart[:,0],cart[:,1],cart[:,2]
else:
Xs,Ys,Zs=cart[0],cart[1],cart[2]
Rs=numpy.sqrt(Xs**2+Ys**2+Zs**2)
Decs=(old_div(numpy.arctan2... | converts a direction to cartesian coordinates |
342,161 | def refreshQueryRecords(self):
if self._recordSet is not None:
records = RecordSet(self._recordSet)
elif self.tableType():
records = self.tableType().select()
else:
return
records.setDatabase(self.database())
... | Refreshes the query results based on the tree's query. |
342,162 | def _get_key_value_config(self):
for rp in self._remote_providers:
val = self._get_remote_config(rp)
self._kvstore = val
return None
raise errors.RemoteConfigError("No Files Found") | Retrieves the first found remote configuration. |
342,163 | def check_uniqueness(self, *args, **kwargs):
if not self.field.unique:
return
key = kwargs.get(, None)
if key is None:
key = self.get_storage_key(*args)
pk = self.instance.pk.get()
pks = list(self.connection.smembers(key))
sel... | Check if the given "value" (via `args`) is unique or not.
Parameters
----------
kwargs: dict
key: str
When given, it will be used instead of calling ``get_storage_key``
for the given args
MUST be passed as a keyword argument
F... |
342,164 | def data_to_sys_base(self):
if (not self.n) or self._flags[]:
return
Sb = self.system.mva
Vb = matrix([])
if in self._ac.keys():
Vb = self.read_data_ext(, , idx=self.bus)
elif in self._ac.keys():
Vb = self.read_data_ext(, , idx=self.... | Converts parameters to system base. Stores a copy in ``self._store``.
Sets the flag ``self.flag['sysbase']`` to True.
:return: None |
342,165 | def user_grant_roles(name, roles, database, user=None, password=None, host=None,
port=None, authdb=None):
*["readWrite"]*[{"role": "readWrite", "db": "dbname" }, {"role": "read", "db": "otherdb"}]
conn = _connect(user, password, host, port, authdb=authdb)
if not conn:
return
... | Grant one or many roles to a MongoDB user
CLI Examples:
.. code-block:: bash
salt '*' mongodb.user_grant_roles johndoe '["readWrite"]' dbname admin adminpwd localhost 27017
.. code-block:: bash
salt '*' mongodb.user_grant_roles janedoe '[{"role": "readWrite", "db": "dbname" }, {"role": ... |
342,166 | def combine_first(self, other):
import pandas.core.computation.expressions as expressions
def extract_values(arr):
if isinstance(arr, (ABCIndexClass, ABCSeries)):
arr = arr._values
if needs_i8_conversion(arr):
... | Update null elements with value in the same location in `other`.
Combine two DataFrame objects by filling null values in one DataFrame
with non-null values from other DataFrame. The row and column indexes
of the resulting DataFrame will be the union of the two.
Parameters
-----... |
342,167 | def _validate_sleep(minutes):
if isinstance(minutes, six.string_types):
if minutes.lower() in [, ]:
return
else:
msg = \
\
.format(minutes)
raise SaltInvocationError(msg)
elif isinstance(minutes, bool):
... | Helper function that validates the minutes parameter. Can be any number
between 1 and 180. Can also be the string values "Never" and "Off".
Because "On" and "Off" get converted to boolean values on the command line
it will error if "On" is passed
Returns: The value to be passed to the command |
342,168 | def list_comment(self, msg_data_id, index=1, begin=0, count=50, type=0):
return self._post(
,
data={
: msg_data_id,
: index,
: begin,
: count,
: type
}) | 查看指定文章的评论数据 |
342,169 | def with_config(f):
@click.pass_context
def new_func(ctx, *args, **kwargs):
if in kwargs:
return ctx.invoke(f, *args, **kwargs)
if ctx.obj is None:
ctx.obj = {}
config = ctx.obj[]
project_enabled = not ctx.obj.get(, False)
p... | Add config to function. |
342,170 | def _switch_language(self, lang):
data = {"learning_language": lang}
url = "https://www.duolingo.com/switch_language"
request = self._make_req(url, data)
try:
parse = request.json()[]
if parse[] == lang:
self.user_data = Struct(**self._ge... | Change the learned language with
``https://www.duolingo.com/switch_language``.
:param lang: Wanted language abbreviation (example: ``'fr'``)
:type lang: str |
342,171 | def image(alt_text, link_url, title=""):
image_string = ""
if title:
image_string += + esc_format(title) +
return image_string | Return an inline image.
Keyword arguments:
title -- Specify the title of the image, as seen when hovering over it.
>>> image("This is an image", "https://tinyurl.com/bright-green-tree")
''
>>> image("This is an image", "https://tinyurl.com/... |
342,172 | def __add_symbols(self, cmd):
if self.__config.define_symbols:
symbols = self.__config.define_symbols
cmd.append(.join(
[ % def_symbol for def_symbol in symbols]))
if self.__config.undefine_symbols:
un_symbols = self.__config.undefine_symbol... | Add all additional defined and undefined symbols. |
342,173 | def build_list(self):
ret = []
for p in self.args.stdout.split():
if in p:
p, a = p.split()
else:
a = None
ret.append((p, a))
return ret | Return a list of tuples taken from self.args.stdout
[(plugin, attribute), ... ] |
342,174 | def avg(self, vars_list: List[str]) -> :
operand = self
if operand.dtype == tf.bool:
operand = operand.cast(tf.float32)
return self._aggregation_op(tf.reduce_mean, operand, vars_list) | Returns the TensorFluent for the avg aggregation function.
Args:
vars_list: The list of variables to be aggregated over.
Returns:
A TensorFluent wrapping the avg aggregation function. |
342,175 | def process_openxml_file(filename: str,
print_good: bool,
delete_if_bad: bool) -> None:
print_bad = not print_good
try:
file_good = is_openxml_good(filename)
file_bad = not file_good
if (print_good and file_good) or (print_bad and fi... | Prints the filename of, or deletes, an OpenXML file depending on whether
it is corrupt or not.
Args:
filename: filename to check
print_good: if ``True``, then prints the filename if the file
appears good.
delete_if_bad: if ``True``, then deletes the file if the file
... |
342,176 | def get_program_by_title(self, program_title):
all_programs = self._load_data(self.PROGRAMS_ENDPOINT, default=[])
matching_programs = [program for program in all_programs if program.get() == program_title]
if len(matching_programs) > 1:
raise MultipleProgramMatchError(len(ma... | Return single program by name, or None if not found.
Arguments:
program_title(string): Program title as seen by students and in Course Catalog Admin
Returns:
dict: Program data provided by Course Catalog API |
342,177 | def handle_request(self, filter_name, path):
if filter_name in self._filter_sets:
if self._filter_sets[filter_name][]:
cached_item_path = self._adapter.check_cached_item( % (filter_name, path))
if cached_item_path:
return redirect(cached_i... | Handle image request
:param filter_name: filter_name
:param path: image_path
:return: |
342,178 | def do_POST(self):
try:
ct = self.headers[]
if ct.startswith():
cid = resolvers.MIMEResolver(ct, self.rfile)
xml = cid.GetSOAPPart()
ps = ParsedSoap(xml, resolver=cid.Resolve)
else:
length = int(self.hea... | The POST command. |
342,179 | def _clean_dic(self, dic):
aux_dic = dic.copy()
for key, value in iter(dic.items()):
if value is None or value == :
del aux_dic[key]
elif type(value) is dict:
cleaned_dict = self._clean_dic(value)
if not cleaned_dict:
... | Clean recursively all empty or None values inside a dict. |
342,180 | def award_project_bid(session, bid_id):
headers = {
:
}
bid_data = {
:
}
endpoint = .format(bid_id)
response = make_put_request(session, endpoint, headers=headers,
params_data=bid_data)
json_data = response.json()
if response.st... | Award a bid on a project |
342,181 | def _patch_for_tf1_12(tf):
tf.io.gfile = tf.gfile
tf.io.gfile.copy = tf.gfile.Copy
tf.io.gfile.exists = tf.gfile.Exists
tf.io.gfile.glob = tf.gfile.Glob
tf.io.gfile.isdir = tf.gfile.IsDirectory
tf.io.gfile.listdir = tf.gfile.ListDirectory
tf.io.gfile.makedirs = tf.gfile.MakeDirs
tf.io.gfile.mkdir = t... | Monkey patch tf 1.12 so tfds can use it. |
342,182 | def get_file(self,
path,
dest=,
makedirs=False,
saltenv=,
gzip=None,
cachedir=None):
path, senv = salt.utils.url.split_env(path)
if senv:
saltenv = senv
if not salt.utils.p... | Get a single file from the salt-master
path must be a salt server location, aka, salt://path/to/file, if
dest is omitted, then the downloaded file will be placed in the minion
cache |
342,183 | def from_array(array):
if array is None or not array:
return None
assert_type_or_raise(array, dict, parameter_name="array")
from .stickers import MaskPosition
data = {}
data[] = u(array.get())
data[] = int(array.get())
data[] = int(a... | Deserialize a new Sticker from a given dictionary.
:return: new Sticker instance.
:rtype: Sticker |
342,184 | def _get_anchor(module_to_name, fullname):
if not _anchor_re.match(fullname):
raise ValueError(" is not a valid anchor" % fullname)
anchor = fullname
for module_name in module_to_name.values():
if fullname.startswith(module_name + "."):
rest = fullname[len(module_name)+1:]
if len(anc... | Turn a full member name into an anchor.
Args:
module_to_name: Dictionary mapping modules to short names.
fullname: Fully qualified name of symbol.
Returns:
HTML anchor string. The longest module name prefix of fullname is
removed to make the anchor.
Raises:
ValueError: If fullname uses cha... |
342,185 | def _proxy(self):
if self._context is None:
self._context = WorkspaceContext(self._version, sid=self._solution[], )
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: WorkspaceContext for this WorkspaceInstance
:rtype: twilio.rest.taskrouter.v1.workspace.WorkspaceContext |
342,186 | def is_valid_py_file(path):
import os
is_valid = False
if os.path.isfile(path) and not os.path.splitext(path)[1] == :
try:
with open(path, ) as f:
compile(f.read(), path, )
is_valid = True
except:
pass
return is_valid | Checks whether the file can be read by the coverage module. This is especially
needed for .pyx files and .py files with syntax errors. |
342,187 | def from_httplib(cls, message):
obs_fold_continued_leaders = (, )
headers = []
for line in message.headers:
if line.startswith(obs_fold_continued_leaders):
if not headers:
... | Read headers from a Python 2 httplib message object. |
342,188 | def log_error(cls, msg):
cls.error_logger.error(msg)
cls.debug_logger.debug(msg) | Logs the provided error message to both the error logger and the debug logger logging
instances.
Args:
msg: `str`. The error message to log. |
342,189 | def _preprocess_nodes_for_pydot(nodes_with_data):
for (node_id, attrs) in nodes_with_data:
if in attrs:
yield (quote_for_pydot(node_id),
{: quote_for_pydot(attrs[])})
else:
yield (quote_for_pydot(node_id), {}) | throw away all node attributes, except for 'label |
342,190 | def _handle_assignment_message(self, pplan):
Log.debug("In handle_assignment_message() of STStmgrClient, Physical Plan: \n%s", str(pplan))
self.heron_instance_cls.handle_assignment_msg(pplan) | Called when new NewInstanceAssignmentMessage arrives |
342,191 | def find_windows(elements,
coordinates,
processes=None,
mol_size=None,
adjust=1,
pore_opt=True,
increment=1.0,
**kwargs):
coordinates = deepcopy(coordinates)
origin = np.array([0... | Return windows diameters and center of masses for a molecule. |
342,192 | def get_cached_response(cls, key):
request_cached_response = DEFAULT_REQUEST_CACHE.get_cached_response(key)
if not request_cached_response.is_found:
django_cached_response = cls._get_cached_response_from_django_cache(key)
cls._set_request_cache_if_django_cache_hit(key, d... | Retrieves a CachedResponse for the provided key.
Args:
key (string)
Returns:
A CachedResponse with is_found status and value. |
342,193 | def make_exploded_column(df, colname_new, colname_old):
s = df[colname_old].apply(pd.Series).stack()
s.name = colname_new
return s | Internal helper function used by `explode_columns()`. |
342,194 | def fda(X, y, p=2, reg=1e-16):
mx = np.mean(X)
X -= mx.reshape((1, -1))
d = X.shape[1]
xc = split_classes(X, y)
nc = len(xc)
p = min(nc - 1, p)
Cw = 0
for x in xc:
Cw += np.cov(x, rowvar=False)
Cw /= nc
mxc = np.zeros((d, nc))
for i in range(nc):
... | Fisher Discriminant Analysis
Parameters
----------
X : numpy.ndarray (n,d)
Training samples
y : np.ndarray (n,)
labels for training samples
p : int, optional
size of dimensionnality reduction
reg : float, optional
Regularization term >0 (ridge regularization)
... |
342,195 | def _kill(self, live_defs, variable, code_loc):
live_defs[variable] = { code_loc }
l.debug("XX CodeLoc %s kills variable %s", code_loc, variable) | Kill previous defs. `addr_list` is a list of normalized addresses. |
342,196 | def read_config():
if not os.path.isfile(CONFIG):
with open(CONFIG, "w"):
pass
parser = ConfigParser()
parser.read(CONFIG)
return parser | Read the configuration file and parse the different environments.
Returns: ConfigParser object |
342,197 | def _is_version_greater(self):
checked = Version(True).check_versions(
self.current_version[0], self.version_yaml
)
if checked is not None and not checked:
return True
return False | Check if the current version is greater as the older older one. |
342,198 | def score_evaluate(tour, tour_sizes=None, tour_M=None):
sizes_oo = np.array([tour_sizes[x] for x in tour])
sizes_cum = np.cumsum(sizes_oo) - sizes_oo / 2
s = 0
size = len(tour)
for ia in xrange(size):
a = tour[ia]
for ib in xrange(ia + 1, size):
b = tour[ib]
... | SLOW python version of the evaluation function. For benchmarking
purposes only. Do not use in production. |
342,199 | def available(self, context):
if not self._enabled:
return False
try:
return self.pre_condition(context) and self._check_condition(context)
except Exception:
return False | Determine if this actions is available in this `context`.
:param context: a dict whose content is left to application needs; if
:attr:`.condition` is a callable it receives `context`
in parameter. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.