Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
360,700 | def add(self, num, price, aType, stuff_status, title, desc, location_state, location_city, cid, session, **kwargs):
request = TOPRequest()
request[] = num
request[] = price
request[] = aType
request[] = stuff_status
request[] = title
request[] = desc
... | taobao.item.add 添加一个商品
此接口用于新增一个商品 商品所属的卖家是当前会话的用户 商品的属性和sku的属性有包含的关系,商品的价格要位于sku的价格区间之中(例如,sku价格有5元、10元两种,那么商品的价格就需要大于等于5元,小于等于10元,否则新增商品会失败) 商品的类目和商品的价格、sku的价格都有一定的相关性(具体的关系要通过类目属性查询接口获得) 商品的运费承担方式和邮费设置有相关性,卖家承担运费不用设置邮费,买家承担运费需要设置邮费 当关键属性值选择了“其他”的时候,需要输入input_pids和input_str商品才能添加成功。 |
360,701 | def ReplaceAttachment(self, attachment_link, attachment, options=None):
if options is None:
options = {}
CosmosClient.__ValidateResource(attachment)
path = base.GetPathFromLink(attachment_link)
attachment_id = base.GetResourceIdOrFullNameFromLink(attachment_link)
... | Replaces an attachment and returns it.
:param str attachment_link:
The link to the attachment.
:param dict attachment:
:param dict options:
The request options for the request.
:return:
The replaced Attachment
:rtype:
dict |
360,702 | def acknowledge_problem(self, notification_period, hosts, services, sticky, notify, author,
comment, end_time=0):
comm = None
logger.debug("Acknowledge requested for %s %s.", self.my_type, self.get_name())
if self.state != self.ok_up:
... | Add an acknowledge
:param sticky: acknowledge will be always present is host return in UP state
:type sticky: integer
:param notify: if to 1, send a notification
:type notify: integer
:param author: name of the author or the acknowledge
:type author: str
:param c... |
360,703 | def set_wallpaper(image):
desktop_env = system.get_name()
if desktop_env in [, , , , ]:
uri = % image
SCHEMA =
KEY =
if desktop_env == :
uri = image
SCHEMA =
KEY =
try:
from gi.repository import Gio
gsettings = Gio.Settings.new(SCHEMA)
gsettings.set_string(KEY, uri)
except ... | Set the desktop wallpaper.
Sets the desktop wallpaper to an image.
Args:
image (str): The path to the image to be set as wallpaper. |
360,704 | def on_deleted(self, event):
for delegate in self.delegates:
if hasattr(delegate, "on_deleted"):
delegate.on_deleted(event) | On deleted method |
360,705 | def find_file(config_file=None, default_directories=None, default_bases=None):
if config_file:
if path.exists(path.expanduser(config_file)):
return config_file
else:
raise FileNotFoundError(.format(config_file))
dirs = default_directories or CONFIG_DIRS
dirs = ... | Search for a config file in a list of files. |
360,706 | def _getSectionForDataDirectoryEntry(self, data_directory_entry, sections):
for section in sections:
if data_directory_entry.VirtualAddress >= section.header.VirtualAddress and \
data_directory_entry.VirtualAddress < section.header.VirtualAddress + section.header.SizeOfRawData :... | Returns the section which contains the data of DataDirectory |
360,707 | def read_geo(fid, key):
dsid = GEO_NAMES[key.name]
add_epoch = False
if "time" in key.name:
days = fid["/L1C/" + dsid["day"]].value
msecs = fid["/L1C/" + dsid["msec"]].value
data = _form_datetimes(days, msecs)
add_epoch = True
dtype = np.float64
else:
... | Read geolocation and related datasets. |
360,708 | def build_permuted_index(self):
for child_hash in self.child_hashes:
config = child_hash[]
num_permutation = config[]
beam_size = config[]
num_neighbour = config[]
bucket_keys = child_hash[].keys()
... | Build PermutedIndex for all your binary hashings.
PermutedIndex would be used to find the neighbour bucket key
in terms of Hamming distance. Permute_configs is nested dict
in the following format:
permuted_config = {"<hash_name>":
{ "num_permutation":50,
... |
360,709 | def method(self) -> str:
if self._method is None:
self._method = decode_bytes(self._parser.get_method())
return self._method | 获取请求方法 |
360,710 | def register_dde_task(self, *args, **kwargs):
kwargs["task_class"] = DdeTask
return self.register_task(*args, **kwargs) | Register a Dde task. |
360,711 | def pad_to_multiple(obj, factor):
_check_supported(obj)
copied = deepcopy(obj)
copied.pad_to_multiple(factor)
return copied | Return a copy of the object with its piano-roll padded with zeros at the
end along the time axis with the minimal length that make the length of
the resulting piano-roll a multiple of `factor`.
Parameters
----------
factor : int
The value which the length of the resulting piano-roll will be... |
360,712 | def _get_xml(self, metric):
self._opener = urllib2.build_opener()
self._opener.addheaders = [(, self.user_agent)]
if metric:
url = self.base_url + .format(self.woeid)
else:
url = self.base_url + .format(self.woeid)
return etree.parse(
... | Returns the channel element of the RSS feed |
360,713 | def ahrs3_send(self, roll, pitch, yaw, altitude, lat, lng, v1, v2, v3, v4, force_mavlink1=False):
return self.send(self.ahrs3_encode(roll, pitch, yaw, altitude, lat, lng, v1, v2, v3, v4), force_mavlink1=force_mavlink1) | Status of third AHRS filter if available. This is for ANU research
group (Ali and Sean)
roll : Roll angle (rad) (float)
pitch : Pitch angle (rad) (float)
yaw : Yaw angle (rad) (float)
... |
360,714 | def get_health_color(score):
color = TERMINAL.green
if score <= 80:
color = TERMINAL.yellow
elif score <= 60:
color = TERMINAL.orange
elif score <= 40:
color = TERMINAL.red
return color | Returns a color based on the health score
:param score: integer from 0 - 100 representing health
:return: string of color to apply in terminal |
360,715 | def press_by_tooltip(step, tooltip):
with AssertContextManager(step):
for button in world.browser.find_elements_by_xpath(str(
%
dict(tooltip=tooltip))):
try:
button.click()
break
except Exception:
pass
... | Press a button having a given tooltip. |
360,716 | def has_no_error(
state,
incorrect_msg="Have a look at the console: your code contains an error. Fix it and try again!",
):
state.assert_root("has_no_error")
if state.reporter.errors:
_msg = state.build_message(
incorrect_msg, {"error": str(state.reporter.errors[0])}
)
... | Check whether the submission did not generate a runtime error.
If all SCTs for an exercise pass, before marking the submission as correct pythonwhat will automatically check whether
the student submission generated an error. This means it is not needed to use ``has_no_error()`` explicitly.
However, in som... |
360,717 | def heatmap(data, scale, vmin=None, vmax=None, cmap=None, ax=None,
scientific=False, style=, colorbar=True,
permutation=None, use_rgba=False, cbarlabel=None, cb_kwargs=None):
if not ax:
fig, ax = pyplot.subplots()
if use_rgba:
for k, v in data.items():
... | Plots heatmap of given color values.
Parameters
----------
data: dictionary
A dictionary mapping the i, j polygon to the heatmap color, where
i + j + k = scale.
scale: Integer
The scale used to partition the simplex.
vmin: float, None
The minimum color value, used to... |
360,718 | def print_stmt(self, print_loc, stmt):
stmt.keyword_loc = print_loc
if stmt.loc is None:
stmt.loc = print_loc
else:
stmt.loc = print_loc.join(stmt.loc)
return stmt | (2.6-2.7)
print_stmt: 'print' ( [ test (',' test)* [','] ] |
'>>' test [ (',' test)+ [','] ] ) |
360,719 | def load_window_settings(self, prefix, default=False, section=):
get_func = CONF.get_default if default else CONF.get
window_size = get_func(section, prefix+)
prefs_dialog_size = get_func(section, prefix+)
if default:
hexstate = None
else:
... | Load window layout settings from userconfig-based configuration
with *prefix*, under *section*
default: if True, do not restore inner layout |
360,720 | def launch_app(app_path, params=[], time_before_kill_app=15):
import subprocess
try:
res = subprocess.call([app_path, params], timeout=time_before_kill_app, shell=True)
print(, res)
if res == 0:
return True
else:
return False
except Exception as e... | start an app |
360,721 | async def jsk_retain(self, ctx: commands.Context, *, toggle: bool = None):
if toggle is None:
if self.retain:
return await ctx.send("Variable retention is set to ON.")
return await ctx.send("Variable retention is set to OFF.")
if toggle:
if... | Turn variable retention for REPL on or off.
Provide no argument for current status. |
360,722 | def groupByWordIndex(self, transaction: , offset: int):
actualW = None
partsInWord = []
wordWidth = self.wordWidth
for item in self.splitOnWords(transaction, offset):
_actualW = item.startOfPart // wordWidth
if actualW is None:
actualW = _... | Group transaction parts splited on words to words
:param transaction: TransTmpl instance which parts
should be grupped into words
:return: generator of tuples (wordIndex, list of transaction parts
in this word) |
360,723 | def cross(triangles):
vectors = np.diff(triangles, axis=1)
crosses = np.cross(vectors[:, 0], vectors[:, 1])
return crosses | Returns the cross product of two edges from input triangles
Parameters
--------------
triangles: (n, 3, 3) float
Vertices of triangles
Returns
--------------
crosses : (n, 3) float
Cross product of two edge vectors |
360,724 | def previous(self):
return self.model.state.get_entity(
self.entity_type, self.entity_id, self._history_index - 1,
connected=False) | Return a copy of this object as was at its previous state in
history.
Returns None if this object is new (and therefore has no history).
The returned object is always "disconnected", i.e. does not receive
live updates. |
360,725 | def model_data(self):
if self.latest_training_job is not None:
model_uri = self.sagemaker_session.sagemaker_client.describe_training_job(
TrainingJobName=self.latest_training_job.name)[][]
else:
logging.warning(
)
m... | str: The model location in S3. Only set if Estimator has been ``fit()``. |
360,726 | def inner(tensor0: BKTensor, tensor1: BKTensor) -> BKTensor:
N = rank(tensor0)
axes = list(range(N))
return tf.tensordot(tf.math.conj(tensor0), tensor1, axes=(axes, axes)) | Return the inner product between two states |
360,727 | def get_path_effect(graph, path, relationship_dict):
causal_effect = []
for predecessor, successor in pairwise(path):
if pair_has_contradiction(graph, predecessor, successor):
return Effect.ambiguous
edges = graph.get_edge_data(predecessor, successor)
edge_key, edge_... | Calculate the final effect of the root node to the sink node in the path.
:param pybel.BELGraph graph: A BEL graph
:param list path: Path from root to sink node
:param dict relationship_dict: dictionary with relationship effects
:rtype: Effect |
360,728 | def execute(self, request, target_route):
presenter = self.create_presenter(request, target_route)
presenter_name = target_route.presenter_name()
action_name = target_route.presenter_action()
presenter_args = target_route.presenter_args()
if hasattr(presenter, action_name) is False:
raise RuntimeError(... | :meth:`.WWebServiceProto.execute` method implementation |
360,729 | def construct_json_event_logger(json_path):
check.str_param(json_path, )
return construct_single_handler_logger(
"json-event-record-logger",
DEBUG,
JsonEventLoggerHandler(
json_path,
lambda record: construct_event_record(
StructuredLoggerMessa... | Record a stream of event records to json |
360,730 | def get_func_argspec(func):
if hasattr(func, ):
argspec = func._utinfo[]
return argspec
if isinstance(func, property):
func = func.fget
try:
argspec = inspect.getargspec(func)
except Exception:
argspec = inspect.getfullargspec(func)
return argspec | wrapper around inspect.getargspec but takes into account utool decorators |
360,731 | def _get_string_match(self, key):
expression = r.join([
,
,
r,
{}\.format(key),
,
r(.*)\,
r,
])
pattern = re.compile(expression, re.MULTILINE)
return pattern.search(self._content) | Gets a MatchObject for the given key, assuming a string value.
Args:
key (str): Key of the property to look-up.
Return:
MatchObject: The discovered match. |
360,732 | def count_cycle(iterable, n=None):
iterable = tuple(iterable)
if not iterable:
return iter(())
counter = count() if n is None else range(n)
return ((i, item) for i in counter for item in iterable) | Cycle through the items from *iterable* up to *n* times, yielding
the number of completed cycles along with each item. If *n* is omitted the
process repeats indefinitely.
>>> list(count_cycle('AB', 3))
[(0, 'A'), (0, 'B'), (1, 'A'), (1, 'B'), (2, 'A'), (2, 'B')] |
360,733 | def get_releases(self, url=, headers={}, repo_name=):
url_releases = (url + )
r = requests.get(url_releases, headers=headers)
self.releases_json[repo_name] = r.json() | Retrieves the releases for the given repo in JSON. |
360,734 | def DeregisterBlockchain():
Blockchain.SECONDS_PER_BLOCK = 15
Blockchain.DECREMENT_INTERVAL = 2000000
Blockchain.GENERATION_AMOUNT = [8, 7, 6, 5, 4, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
Blockchain._blockchain = None
Blockchain._validators = []
Block... | Remove the default blockchain instance. |
360,735 | def dict_merge(a, b):
if not isinstance(b, dict):
return b
result = deepcopy(a)
for k, v in b.iteritems():
if k in result and isinstance(result[k], dict):
result[k] = dict_merge(result[k], v)
else:
result[k] = deepcopy(v)
return result | Recursively merge dicts.
recursively merges dict's. not just simple a['key'] = b['key'], if
both a and bhave a key who's value is a dict then dict_merge is called
on both values and the result stored in the returned dictionary.
@see http://www.xormedia.com/recursively-merge-dictionaries-in-pyt... |
360,736 | def updated_current_fields(
self,
update_fields):
self.fields_to_add = {}
for k in self.org_fields:
self.fields_to_add[k] = self.org_fields[k]
self.fields_to_add.update(update_fields) | updated_current_fields
:param update_fields: dict with values for
updating fields_to_add |
360,737 | def hilbertscan(size, distance):
size = 2*(1<<(size-1).bit_length());
if (distance > size**2 - 1): raise StopIteration("Invalid distance!")
for d in range(distance):
t = d
x = 0
y = 0
s = 1
while (s < size):
rx = 1 & (t / 2)
ry = 1 & (t ... | Scan pixels in a Hilbert curve pattern in the first quadrant. Modified
algorithm from https://en.wikipedia.org/wiki/Hilbert_curve.
:param size: Size of enclosing square
:type size: int
:param distance: Distance along curve (Must be smaller than size**2 - 1)
:type distance: int
:returns: Coordi... |
360,738 | def user_view_task(self, ):
if not self.cur_user:
return
i = self.user_task_treev.currentIndex()
item = i.internalPointer()
if item:
task = item.internal_data()
if isinstance(task, djadapter.models.Task):
self.view_task(task) | View the task that is selected
:returns: None
:rtype: None
:raises: None |
360,739 | def _perform_power_op(self, oper):
power_settings = {"Action": "Reset",
"ResetType": oper}
systems_uri = "/rest/v1/Systems/1"
status, headers, response = self._rest_post(systems_uri, None,
power_settings)
... | Perform requested power operation.
:param oper: Type of power button press to simulate.
Supported values: 'ON', 'ForceOff', 'ForceRestart' and
'Nmi'
:raises: IloError, on an error from iLO. |
360,740 | def quota(self):
response = self._call(
mm_calls.ClientState,
self.uploader_id
)
client_state = response.body.clientstate_response
return (client_state.total_track_count, client_state.locker_track_limit) | Get the uploaded track count and allowance.
Returns:
tuple: Number of uploaded tracks, number of tracks allowed. |
360,741 | def gatk_snp_cutoff(in_file, data):
filters = ["MQRankSum < -12.5", "ReadPosRankSum < -8.0"]
variantcaller = utils.get_in(data, ("config", "algorithm", "variantcaller"))
if variantcaller not in ["gatk-haplotype", "haplotyper"]:
filters.append("HaplotypeScore > 13.0")
if not (... | Perform cutoff-based soft filtering on GATK SNPs using best-practice recommendations.
We have a more lenient mapping quality (MQ) filter compared to GATK defaults.
The recommended filter (MQ < 40) is too stringent, so we adjust to 30:
http://imgur.com/a/oHRVB
QD and FS are not calculated when generati... |
360,742 | def dump_declarations(declarations, file_path):
with open(file_path, "w+") as f:
print_declarations(declarations, writer=f.write) | Dump declarations tree rooted at each of the included nodes to the file
:param declarations: either a single :class:declaration_t object or a list
of :class:declaration_t objects
:param file_path: path to a file |
360,743 | def get_name_cost(name, proxy=None, hostport=None):
assert proxy or hostport,
if proxy is None:
proxy = connect_hostport(hostport)
cost_schema_v1 = {
: ,
: {
: {
: ,
: 0,
},
},
: [
]
... | name_cost
Returns the name cost info on success
Returns {'amount': ..., 'units': ...} on success
Returns {'error': ...} on error |
360,744 | def organization_memberships(self, state=None, number=-1, etag=None):
params = None
url = self._build_url(, , )
if state is not None and state.lower() in (, ):
params = {: state.lower()}
return self._iter(int(number), url, Membership,
params... | List organizations of which the user is a current or pending member.
:param str state: (option), state of the membership, i.e., active,
pending
:returns: iterator of :class:`Membership <github3.orgs.Membership>` |
360,745 | def select_with_index(self, selector):
return self._create(self._pool.imap_unordered(star,
zip(itertools.repeat(selector),
enumerate(iter(self))), self._chunksize)) | Transforms each element of a sequence into a new form, incorporating
the index of the element.
Each element is transformed through a selector function which accepts
the element value and its zero-based index in the source sequence. The
generated sequence is lazily evaluated.
... |
360,746 | def _make_expr_empty_dict(toplevel, stack_builders):
if toplevel.arg:
raise DecompilationError(
"make_expr() called with nonzero BUILD_MAP arg %d" % toplevel.arg
)
if stack_builders:
raise DecompilationError(
"Unexpected stack_builders for BUILD_MAP(0): %s" ... | This should only be hit for empty dicts. Anything else should hit the
STORE_MAP handler instead. |
360,747 | def import_data(self, data_items):
record = {
: 0, : 0, : 0,
: utcnow(),
: {
: [],
: [],
: [],
}
}
for json_id, data in self._prepare_imports(data_items):
obj_id, what =... | import a bunch of dicts together |
360,748 | def stackplot(marray, seconds=None, start_time=None, ylabels=None):
tarray = np.transpose(marray)
stackplot_t(tarray, seconds=seconds, start_time=start_time, ylabels=ylabels)
plt.show() | will plot a stack of traces one above the other assuming
marray.shape = numRows, numSamples |
360,749 | def _get_site_amplification_term(self, C, vs30):
return C["gamma"] * np.log10(vs30 / self.CONSTS["Vref"]) | Returns the site amplification term for the case in which Vs30
is used directly |
360,750 | def send_work(self):
if self.__set_running():
msg = {TYPE: FUTURE, METHOD: self.__method, PARAMS: self.__params,
CHANNEL: self.__channel, TO: self.__target,
RPC_ID: self.__id}
self.__actor_channel.send(msg)
... | Sends the query to the actor for it to start executing the
work.
It is possible to execute once again a future that has finished
if necessary (overwriting the results), but only one execution
at a time. |
360,751 | def p_taskvardecls(self, p):
p[0] = p[1] + (p[2],)
p.set_lineno(0, p.lineno(1)) | taskvardecls : taskvardecls taskvardecl |
360,752 | def mmPrettyPrintConnections(self):
text = ""
text += ("Segments: (format => "
"(
text += "------------------------------------\n"
columns = range(self.numberOfColumns())
for column in columns:
cells = self.cellsForColumn(column)
for cell in cells:
segmentDi... | Pretty print the connections in the temporal memory.
TODO: Use PrettyTable.
@return (string) Pretty-printed text |
360,753 | def delete_vhost(self, name):
self._api_delete(.format(
urllib.parse.quote_plus(name)
)) | Delete a vhost.
:param name: The vhost name
:type name: str |
360,754 | def tabSeparatedSummary(self, sortOn=None):
result = []
for titleSummary in self.summary(sortOn):
result.append(.join([
,
,
,
... | Summarize all the alignments for this title as multi-line string with
TAB-separated values on each line.
@param sortOn: A C{str} attribute to sort titles on. One of 'length',
'maxScore', 'medianScore', 'readCount', or 'title'.
@raise ValueError: If an unknown C{sortOn} value is give... |
360,755 | def _set_timestamps_on_attach(self, record, exists=False):
fresh = self._parent.fresh_timestamp()
if not exists and self._has_pivot_column(self.created_at()):
record[self.created_at()] = fresh
if self._has_pivot_column(self.updated_at()):
record[self.updated_at... | Set the creation an update timestamps on an attach record. |
360,756 | def pause(self):
log.info("Pausing cluster `%s` ...", self.name)
failed = self._pause_all_nodes()
if os.path.exists(self.known_hosts_file):
os.remove(self.known_hosts_file)
self.repository.save_or_update(self)
if failed:
log.warning(
... | Pause all VMs in this cluster and store data so that they
can be restarted later. |
360,757 | def load(cls, filename, **kwargs):
if not os.path.exists(filename):
raise IOError("filename {0} does not exist" .format(filename))
if filename.lower().endswith(".fits") \
or filename.lower().endswith(".fits.gz"):
image = fits.open(filename, **kw... | Load a Spectrum1D from a given filename.
:param filename:
The path of the filename to load. Can be either simple 1D FITS files
or an ASCII filename.
:type filename:
str |
360,758 | def _map_intent_to_view_func(self, intent):
if intent.name in self._intent_view_funcs:
view_func = self._intent_view_funcs[intent.name]
elif self._default_intent_view_func is not None:
view_func = self._default_intent_view_func
else:
raise NotImplemen... | Provides appropiate parameters to the intent functions. |
360,759 | def pin_type(self, pin):
if type(pin) is list:
return [self.pin_type(p) for p in pin]
pin_id = self._pin_mapping.get(pin, None)
if pin_id:
return self._pin_type(pin_id)
else:
raise KeyError( % pin) | Gets the `ahio.PortType` this pin was set to.
If you're developing a driver, implement _pin_type(self, pin)
@arg pin the pin you want to see the mode
@returns the `ahio.PortType` the pin is set to
@throw KeyError if pin isn't mapped. |
360,760 | def gen_query(self):
return (
SQL.forwards_relation(self.src, self.rel) if self.dst is None else
SQL.inverse_relation(self.dst, self.rel)
) | Generate an SQL query for the edge object. |
360,761 | def merge(self, carts=None, new_cart_name=None):
if new_cart_name is not None:
cart_name = new_cart_name
else:
cart_name = carts[0]
result_cart = juicer.common.Cart.Cart(cart_name)
items_hash = {}
for cart in carts:
tmpca... | `carts` - A list of cart names
`new_cart_name` - Resultant cart name
Merge the contents of N carts into a new cart
TODO: Sanity check that each cart in `carts` exists. Try
'juicer pull'ing carts that can't be located locally. Then cry
like a baby and error out. |
360,762 | def fresh(req_headers: HEADER_TYPE, res_headers: HEADER_TYPE) -> bool:
modified_since = cast(
Optional[str],
req_headers.get(),
)
none_match = cast(
Optional[str],
req_headers.get(),
)
if not modified_since and not none_match:
return False
cache_contr... | 根据 req_headers, res_headers 判断改消息是否为 304 |
360,763 | def update_project(self, ID, data):
log.info( % (ID, data))
self.put( % ID, data) | Update a project. |
360,764 | def group_retrieve(self, device_group_id, **kwargs):
kwargs[] = True
if kwargs.get():
return self.group_retrieve_with_http_info(device_group_id, **kwargs)
else:
(data) = self.group_retrieve_with_http_info(device_group_id, **kwargs)
return data | Get a group. # noqa: E501
Get a group. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = api.group_retrieve(device_group_id, asynchronous=True)
>>> result = thread.get()
... |
360,765 | def _get_info(self, fullmodname):
parts = fullmodname.split()
submodname = parts[-1]
for f in self._files:
for prefix in self._prefixes[id(f)]:
for suffix, is_package in _SEARCH_ORDER:
l = [prefix] + parts[:-1] + [submodname + suffix.repla... | Internal helper for find_module() and load_module().
Args:
fullmodname: The dot-separated full module name, e.g. 'django.core.mail'.
Returns:
A tuple (submodname, is_package, relpath, fileobj) where:
submodname: The final component of the module name, e.g. 'mail'.
... |
360,766 | def _tokens_to_subtoken(self, tokens):
ret = []
for token in tokens:
ret.extend(
self._escaped_token_to_subtoken_strings(_escape_token(token, self._alphabet)))
return ret | Converts a list of tokens to a list of subtoken.
Args:
tokens: a list of strings.
Returns:
a list of integers in the range [0, vocab_size) |
360,767 | def get_typecast_value(self, value, type):
if type == entities.Variable.Type.BOOLEAN:
return value ==
elif type == entities.Variable.Type.INTEGER:
return int(value)
elif type == entities.Variable.Type.DOUBLE:
return float(value)
else:
return value | Helper method to determine actual value based on type of feature variable.
Args:
value: Value in string form as it was parsed from datafile.
type: Type denoting the feature flag type.
Return:
Value type-casted based on type of feature variable. |
360,768 | def check_post_role(self):
priv_dic = {: False, : False, : False, : False}
if self.userinfo:
if self.userinfo.role[1] > :
priv_dic[] = True
if self.userinfo.role[1] >= :
priv_dic[] = True
if self.userinfo.role[1] >= :
... | check the user role for docs. |
360,769 | def _init_spmatrix(self, data, index, columns, dtype=None,
fill_value=None):
index, columns = self._prep_index(data, index, columns)
data = data.tocoo()
N = len(index)
sdict = {}
values = Series(data.data, index=data.row, copy=False)
... | Init self from scipy.sparse matrix. |
360,770 | def add_signature(self, key, alg=None, protected=None, header=None):
if not self.objects.get(, None):
raise InvalidJWSObject()
b64 = True
p = dict()
if protected:
if isinstance(protected, dict):
p = protected
protected =... | Adds a new signature to the object.
:param key: A (:class:`jwcrypto.jwk.JWK`) key of appropriate for
the "alg" provided.
:param alg: An optional algorithm name. If already provided as an
element of the protected or unprotected header it can be safely
omitted.
:param p... |
360,771 | def list_records(self, bucket_name, prefix=, delimiter=, max_results=1000, starting_key=):
title = % self.__class__.__name__
from datetime import datetime
from dateutil.tz import tzutc
input_fields = {
: bucket_name,
: pr... | a method for retrieving a list of the versions of records in a bucket
:param bucket_name: string with name of bucket
:param prefix: [optional] string with value limiting results to key prefix
:param delimiter: string with value which results must not contain (after prefix)
:param max_re... |
360,772 | def object_id(self):
pk = self.identity_attributes()
if len(pk) == 1:
pk_value = getattr(self, pk[0])
if isinstance(pk_value, numbers.Integral):
return pk_value
elif isinstance(pk_value, uuid.UUID):
return pk_value.int
... | (:class:`numbers.Integral`) The identifier number of the image.
It uses the primary key if it's integer, but can be overridden,
and must be implemented when the primary key is not integer or
composite key.
.. versionchanged:: 1.1.0
Since 1.1.0, it provides a more default impl... |
360,773 | def _labeled_uniform_sample(self, sample_size):
labeled_entries = self.dataset.get_labeled_entries()
samples = [labeled_entries[
self.random_state_.randint(0, len(labeled_entries))
]for _ in range(sample_size)]
return Dataset(*zip(*samples)) | sample labeled entries uniformly |
360,774 | def from_dict(d):
if isinstance(d, str):
return from_json(d)
if not isinstance(d, dict):
raise TypeError("argument must be of type dict")
if not in d.keys():
raise ValueError("input dictionary missing entry")
classname = d.pop().title()
return getattr(_wrappers, clas... | load an nparray object from a dictionary
@parameter str d: dictionary representing the nparray object |
360,775 | def clean(cls, cpf):
u
if isinstance(cpf, six.string_types):
cpf = int(re.sub(, , cpf))
return .format(cpf) | u"""
Retorna apenas os dígitos do CPF.
>>> CPF.clean('581.194.436-59')
'58119443659' |
360,776 | def call_heat(tstat):
current_hsp, current_csp = tstat.heating_setpoint, tstat.cooling_setpoint
current_temp = tstat.temperature
tstat.write({
: current_temp+10,
: current_temp+20,
: HEAT,
})
def restore():
tstat.write({
: current_hsp,
: ... | Adjusts the temperature setpoints in order to call for heating. Returns
a handler to call when you want to reset the thermostat |
360,777 | def hit(self, event):
aProcess = event.get_process()
aThread = event.get_thread()
state = self.get_state()
event.breakpoint = self
if state == self.ENABLED:
self.running(aProcess, aThread)
elif state == self.RUNNING:
self.enable(aPr... | Notify a breakpoint that it's been hit.
This triggers the corresponding state transition and sets the
C{breakpoint} property of the given L{Event} object.
@see: L{disable}, L{enable}, L{one_shot}, L{running}
@type event: L{Event}
@param event: Debug event to handle (depends o... |
360,778 | def ParseOptions(cls, options, configuration_object):
if not isinstance(configuration_object, tools.CLITool):
raise errors.BadConfigObject(
)
parsers = cls._ParseStringOption(options, , default_value=)
parsers = parsers.replace(, )
setattr(configuration_object, , parsers) | Parses and validates options.
Args:
options (argparse.Namespace): parser options.
configuration_object (CLITool): object to be configured by the argument
helper.
Raises:
BadConfigObject: when the configuration object is of the wrong type. |
360,779 | def download_quad(self, quad, callback=None):
download_url = quad[][]
return self._get(download_url, models.Body, callback=callback) | Download the specified mosaic quad. If provided, the callback will
be invoked asynchronously. Otherwise it is up to the caller to handle
the response Body.
:param asset dict: A mosaic quad representation from the API
:param callback: An optional function to aysnchronsously handle the
... |
360,780 | def format_day(
self, date: datetime.datetime, gmt_offset: int = 0, dow: bool = True
) -> bool:
local_date = date - datetime.timedelta(minutes=gmt_offset)
_ = self.translate
if dow:
return _("%(weekday)s, %(month_name)s %(day)s") % {
"month_name":... | Formats the given date as a day of week.
Example: "Monday, January 22". You can remove the day of week with
``dow=False``. |
360,781 | def feature_selection(feat_select, X, y):
if re.match(, feat_select) is not None:
n = int(feat_select.split()[0])
selector = SelectKBest(k=n)
import warnings
with warnings.catch_warnings():
warnings.simplefilter(, category=UserWarning)
features_sel... | Implements various kinds of feature selection |
360,782 | def prior_to_xarray(self):
return dict_to_dataset(
{k: np.expand_dims(v, 0) for k, v in self.prior.items()},
library=self.pymc3,
coords=self.coords,
dims=self.dims,
) | Convert prior samples to xarray. |
360,783 | def _get_hash(f1, f2, dt):
return ((long(f1) & 0xffff) << 48 |
(long(f2) & 0xffff) << 32 |
(long(dt) & 0x3fff)) | Calculate a 64-bit integral hash from <f1:f2:dt>, where f1 and f2 are
FFT frequency bins (based on frame width), and dt is propotional to the
time difference between f1 and f2 as the the difference in frame number
between the points. |
360,784 | def delete_collaborator(self, email):
args = {
: self.id,
: email,
}
_perform_command(self.owner, , args) | Remove a collaborating user from the shared project.
:param email: The collaborator's email address.
:type email: str
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user.get_project('PyTodoist')
>>> project.del... |
360,785 | def index(self, value):
try:
diff = value - self._start
except TypeError:
raise ValueError( % value)
quotient, remainder = divmod(diff, self._step)
if remainder == 0 and 0 <= quotient < self._len:
return abs(quotient)
raise ValueError(... | Return the 0-based position of integer `value` in
the sequence this range represents. |
360,786 | def get_import_lines(self):
if self.imports:
return ["from %s import %s" % (value, key) for key, value in self.imports.items()]
else:
return [] | Take the stored imports and converts them to lines |
360,787 | def validate_regex(regex, sub_service):
if regex.pattern.startswith() is False:
logger.debug()
raise InvalidRouteRegexError()
if regex.pattern.endswith() is False and sub_service is False:
logger.debug()
raise InvalidR... | Is the regex valid for StackInABox routing?
:param regex: Python regex object to match the URI
:param sub_service: boolean for whether or not the regex is for
a sub-service
:raises: InvalidRouteRegexError if the regex does not meet the
requirements. |
360,788 | def admin_emails(doc):
if doc.get() == and doc.get() != :
if doc.get() == :
yield None, doc[]
for org_id, state in doc.get(, {}).items():
if state.get() == and state.get() != :
yield org_id, doc[] | View for admin email addresses (organisation and global) |
360,789 | def list_keys(key_name,
max_suggestions,
cutoff,
jsonify,
locked,
key_type,
stash,
passphrase,
backend):
stash = _get_stash(backend, stash, passphrase, quiet=jsonify)
try:
keys = stash.l... | List all keys in the stash
If `KEY_NAME` is provided, will look for keys containing `KEY_NAME`.
If `KEY_NAME` starts with `~`, close matches will be provided according
to `max_suggestions` and `cutoff`. |
360,790 | def _setup_transport(self):
self._write = self.sock.sendall
self._read_buffer = EMPTY_BUFFER
self._quick_recv = self.sock.recv | Setup to _write() directly to the socket, and
do our own buffered reads. |
360,791 | def save(self):
with open(self.series_file, "wb") as f:
for patchline in self.patchlines:
f.write(_encode_str(str(patchline)))
f.write(b"\n") | Saves current patches list in the series file |
360,792 | def download(self, dest_pattern="{originalFilename}", override=True, parent=False):
if self.id is None:
raise ValueError("Cannot download image with no ID.")
pattern = re.compile("{(.*?)}")
dest_pattern = re.sub(pattern, lambda m: str(getattr(self, str(m.group(0))[1:-1], "_... | Download the original image.
Parameters
----------
dest_pattern : str, optional
Destination path for the downloaded image. "{X}" patterns are replaced by the value of X attribute
if it exists.
override : bool, optional
True if a file with same name ca... |
360,793 | def create_draft(self, layer_id):
target_url = self.client.get_url(, , , {: layer_id})
r = self.client.request(, target_url, json={})
return self.create_from_result(r.json()) | Creates a new draft version.
If anything in the data object has changed then an import will begin immediately.
Otherwise to force a re-import from the previous sources call :py:meth:`koordinates.layers.LayerManager.start_import`.
:rtype: Layer
:return: the new version
:raises C... |
360,794 | def read_tile_header(codec, stream):
ARGTYPES = [CODEC_TYPE,
STREAM_TYPE_P,
ctypes.POINTER(ctypes.c_uint32),
ctypes.POINTER(ctypes.c_uint32),
ctypes.POINTER(ctypes.c_int32),
ctypes.POINTER(ctypes.c_int32),
ctypes.PO... | Reads a tile header.
Wraps the openjp2 library function opj_read_tile_header.
Parameters
----------
codec : codec_t
The JPEG2000 codec to read.
stream : STREAM_TYPE_P
The JPEG2000 stream.
Returns
-------
tile_index : int
index of the tile being decoded
data... |
360,795 | def _remap(object, name, value, safe=True):
if os.getenv("QT_TESTING") is not None and safe:
if hasattr(object, name):
raise AttributeError("Cannot override existing name: "
"%s.%s" % (object.__name__, name))
if type(object).__nam... | Prevent accidental assignment of existing members
Arguments:
object (object): Parent of new attribute
name (str): Name of new attribute
value (object): Value of new attribute
safe (bool): Whether or not to guarantee that
the new attribute was not overwritten.
... |
360,796 | def _cmp_date(self):
dates = sorted(val for val in self.kw.values()
if isinstance(val, CalendarDate))
if dates:
return dates[0]
return CalendarDate() | Returns Calendar date used for comparison.
Use the earliest date out of all CalendarDates in this instance,
or some date in the future if there are no CalendarDates (e.g.
when Date is a phrase). |
360,797 | def case_highlight(seq, subseq):
return re.subs(subseq.lower(), subseq.upper(), seq.lower()) | Highlights all instances of subseq in seq by making them uppercase and
everything else lowercase. |
360,798 | def get_fastq_files(data):
assert "files" in data, "Did not find `files` in input; nothing to process"
ready_files = []
should_gzip = True
if in data[].keys():
should_gzip = False
for fname in data["files"]:
if fname.endswith(".bam"):
if _pipeline_needs_fastq(... | Retrieve fastq files for the given lane, ready to process. |
360,799 | def _get_value_from_config(self, section, name):
conf = configuration.get_config()
try:
value = conf.get(section, name)
except (NoSectionError, NoOptionError, KeyError):
return _no_value
return self.parse(value) | Loads the default from the config. Returns _no_value if it doesn't exist |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.