Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
373,200 | def _to_sqlite3_by_table(self, conn, table_name):
def _insert_item(item):
if isinstance(item, dict):
cols = .join(item.keys())
placeholders = .join( * len(item))
sql = .format(table_name, cols, placeholders)
conn.execute(sql, t... | Saves the sequence to the specified table of sqlite3 database.
Each element can be a dictionary, namedtuple, tuple or list.
Target table must be created in advance.
:param conn: path or sqlite connection, cursor
:param table_name: table name string |
373,201 | def add_to_recent(self, notebook):
if notebook not in self.recent_notebooks:
self.recent_notebooks.insert(0, notebook)
self.recent_notebooks = self.recent_notebooks[:20] | Add an entry to recent notebooks.
We only maintain the list of the 20 most recent notebooks. |
373,202 | def create(self, width, height):
return Image.new(self.mode, (width, height)) | Create an image of type.
Parameters
----------
width: `int`
Image width.
height: `int`
Image height.
Returns
-------
`PIL.Image.Image` |
373,203 | def call_from_executor(self, callback, _max_postpone_until=None):
assert _max_postpone_until is None or isinstance(_max_postpone_until, float)
self._calls_from_executor.append((callback, _max_postpone_until))
if self._schedule_pipe:
try:
os.write(self._sched... | Call this function in the main event loop.
Similar to Twisted's ``callFromThread``.
:param _max_postpone_until: `None` or `time.time` value. For interal
use. If the eventloop is saturated, consider this task to be low
priority and postpone maximum until this timestamp. (For inst... |
373,204 | def GetTransPosition(df,field,dic,refCol="transcript_id"):
try:
gen=str(int(df[field]))
transid=df[refCol]
bases=dic.get(transid).split(",")
bases=bases.index(str(gen))+1
except:
bases=np.nan
return bases | Maps a genome position to transcript positon"
:param df: a Pandas dataframe
:param field: the head of the column containing the genomic position
:param dic: a dictionary containing for each transcript the respective bases eg. {ENST23923910:'234,235,236,1021,..'}
:param refCol: header of the reference c... |
373,205 | def onCancelButton(self, event):
if self.grid.changes:
dlg1 = wx.MessageDialog(self, caption="Message:",
message="Are you sure you want to exit this grid?\nYour changes will not be saved.\n ",
style=wx.OK|wx.CANCEL)
... | Quit grid with warning if unsaved changes present |
373,206 | def examples_section(doc, header_level):
lines = []
if "Examples" in doc and len(doc["Examples"]) > 0:
lines.append(f"{*(header_level+1)} Examples \n")
egs = "\n".join(doc["Examples"])
lines += mangle_examples(doc["Examples"])
return lines | Generate markdown for Examples section.
Parameters
----------
doc : dict
Dict from numpydoc
header_level : int
Number of `#`s to use for header
Returns
-------
list of str
Markdown for examples section |
373,207 | def get_inflators_cn_to_cn(target_year):
inflateur de vieillissement à partir des masses de comptabilité nationale.
consoCN_COICOP_{}consoCN_COICOP_{}'.format(target_year)].to_dict()
return dict(
(key, target_year_cn_aggregates[key] / data_year_cn_aggregates[key])
for key in data_year_cn_ag... | Calcule l'inflateur de vieillissement à partir des masses de comptabilité nationale. |
373,208 | def _get_body_instance(self):
simple_body = {
MultipartType.OFPMP_FLOW: FlowStatsRequest,
MultipartType.OFPMP_AGGREGATE: AggregateStatsRequest,
MultipartType.OFPMP_PORT_STATS: PortStatsRequest,
MultipartType.OFPMP_QUEUE: QueueStatsRequest,
Mul... | Return the body instance. |
373,209 | def _sumLists(a, b):
val = 0
for i in map(lambda a, b: a * b, a, b):
val += i
return val | Algorithm to check validity of NBI and NIF.
Receives string with a umber to validate. |
373,210 | def add_handler_spec(f, handler_spec, *, kwargs=None):
handler_dict = automake_magic_attr(f)
if kwargs is None:
kwargs = {}
if kwargs != handler_dict.setdefault(handler_spec, kwargs):
raise ValueError(
"The additional keyword arguments to the handler are incompatible") | Attach a handler specification (see :class:`HandlerSpec`) to a function.
:param f: Function to attach the handler specification to.
:param handler_spec: Handler specification to attach to the function.
:type handler_spec: :class:`HandlerSpec`
:param kwargs: additional keyword arguments passed to the fu... |
373,211 | def pick_four_unique_nodes_quickly(n, seed=None):
rng = get_rng(seed)
k = rng.randint(n**4)
a = k % n
b = k // n % n
c = k // n ** 2 % n
d = k // n ** 3 % n
if (a != b and a != c and a != d and b != c and b != d and c != d):
return (a, b, c, d)
else:
... | This is equivalent to np.random.choice(n, 4, replace=False)
Another fellow suggested np.random.random_sample(n).argpartition(4) which is
clever but still substantially slower. |
373,212 | def get_listeners(self, event_type: str) -> List[Callable]:
if event_type not in self.events:
raise ValueError(f)
return self.events.get_listeners(event_type) | Get all listeners of a particular type of event. |
373,213 | def plotEzJz(self,*args,**kwargs):
labeldict= {:r,:r,:r,:r,
:r,:r,:r,
:r,:r,:r,:r}
if not in kwargs:
try:
pot= self._pot
except AttributeError:
raise AttributeError("Integrate orbit first or specify... | NAME:
plotEzJz
PURPOSE:
plot E_z(.)/sqrt(dens(R)) along the orbit
INPUT:
pot= Potential instance or list of instances in which the orbit was
integrated
d1= - plot Ez vs d1: e.g., 't', 'z', 'R', 'vR', 'vT', 'vz'
+bovy_plot.bovy... |
373,214 | def get_adapter_for_persistent_model(self, persistent_model, rest_model=None):
persistent_signature = self.generate_signature(persistent_model)
if persistent_signature in self._persistent_map:
sub_map = self._persistent_map[persistent_signature]
if... | :param persistent_model: instance of persistent model
:param rest_model: specific REST model
:return: the matching model adapter
:rtype: ModelAdapter |
373,215 | async def expand_now(self, building: UnitTypeId=None, max_distance: Union[int, float]=10, location: Optional[Point2]=None):
if not building:
start_townhall_type = {Race.Protoss: UnitTypeId.NEXUS, Race.Terran: UnitTypeId.COMMANDCENTER, Race.Zerg: UnitTypeId.HATCHERY}
... | Takes new expansion. |
373,216 | def uri_tree_encode(uri_tree, type_host = HOST_REG_NAME):
scheme, authority, path, query, fragment = uri_tree
if authority:
user, passwd, host, port = authority
if user:
user = pct_encode(user, USER_ENCDCT)
if passwd:
passwd = pct_encode(passwd, PASSWD_ENCDCT... | Percent/Query encode a raw URI tree. |
373,217 | def get_ip(request):
if getsetting():
return getsetting()
forwarded_for = request.META.get()
if not forwarded_for:
return UNKNOWN_IP
for ip in forwarded_for.split():
ip = ip.strip()
if not ip.startswith() and not ip == :
return ip
return UNKNOWN_I... | Return the IP address inside the HTTP_X_FORWARDED_FOR var inside
the `request` object.
The return of this function can be overrided by the
`LOCAL_GEOLOCATION_IP` variable in the `conf` module.
This function will skip local IPs (starting with 10. and equals to
127.0.0.1). |
373,218 | def search_in_dirs(fname, search_dpaths=[], shortcircuit=True,
return_tried=False, strict=False):
fpath_list = []
tried_list = []
for dpath in search_dpaths:
fpath = join(dpath, fname)
if return_tried:
tried_list.append(fpath)
if exists(fpath):
... | search_in_dirs
Args:
fname (str): file name
search_dpaths (list):
shortcircuit (bool):
return_tried (bool): return tried paths
strict (bool): (default = False)
Returns:
fpath: None
Example:
>>> # DISABLE_DOCTEST
>>> import utool as ut
... |
373,219 | def psql_csv_run(sql_command, error_handler=None):
csv_query = (
.format(query=sql_command))
new_env = os.environ.copy()
new_env.setdefault(, )
new_env["PGOPTIONS"] +=
psql_proc = popen_nonblock([PSQL_BIN, , , ,
, , csv_query],
... | Runs psql and returns a CSVReader object from the query
This CSVReader includes header names as the first record in all
situations. The output is fully buffered into Python. |
373,220 | def release(self, tid, fh):
try:
try:
self.fds[fh].unregisterHandler(fh)
except AttributeError:
pass
del self.fds[fh]
except KeyError:
raise FuseOSError(errno.EBADF)
return 0 | Close file. Descriptor is removed from ``self.fds``.
Parameters
----------
tid : str
Path to file. Ignored.
fh : int
File descriptor to release. |
373,221 | def containsUid(self, uid):
s uid, or is the uid of any children at any level down
'
if self.uid == uid:
return True
for child in self.children:
if child.containsUid(uid):
return True
return False | containsUid - Check if the uid (unique internal ID) appears anywhere as a direct child to this node, or the node itself.
@param uid <uuid.UUID> - uuid to check
@return <bool> - True if #uid is this node's uid, or is the uid of any children at any level down |
373,222 | def _post_md5_skip_on_check(self, key, filename, size, md5_match):
with self._md5_meta_lock:
rfile = self._md5_map.pop(key)
lpath = pathlib.Path(filename)
if md5_match:
if size is None:
size = lpath.stat().st_size
with self._t... | Perform post MD5 skip on check
:param Downloader self: this
:param str key: md5 map key
:param str filename: local filename
:param int size: size of checked data
:param bool md5_match: if MD5 matches |
373,223 | def updateEvolution(self):
self.pEvolution = np.zeros((self.pCount,self.pNextCount))
for j in range(self.pCount):
pNow = self.pGrid[j]
pNextMean = self.pNextIntercept + self.pNextSlope*pNow
dist = approxUniform(N=self.pNextCount,bot=pNextMean-self.pNextWidth,... | Updates the "population punk proportion" evolution array. Fasion victims
believe that the proportion of punks in the subsequent period is a linear
function of the proportion of punks this period, subject to a uniform
shock. Given attributes of self pNextIntercept, pNextSlope, pNextCount,
... |
373,224 | def login(context, request):
__ac_name = request.get("__ac_name", None)
__ac_password = request.get("__ac_password", None)
logger.info("*** LOGIN %s ***" % __ac_name)
if __ac_name is None:
api.fail(400, "__ac_name is missing")
if __ac_password is None:
api.fail(400, "__ac... | Login Route
Login route to authenticate a user against Plone. |
373,225 | def pp_file_to_dataframe(pp_filename):
df = pd.read_csv(pp_filename, delim_whitespace=True,
header=None, names=PP_NAMES,usecols=[0,1,2,3,4])
df.loc[:,"name"] = df.name.apply(str).apply(str.lower)
return df | read a pilot point file to a pandas Dataframe
Parameters
----------
pp_filename : str
pilot point file
Returns
-------
df : pandas.DataFrame
a dataframe with pp_utils.PP_NAMES for columns |
373,226 | def _get_dvs(service_instance, dvs_name):
switches = list_dvs(service_instance)
if dvs_name in switches:
inventory = get_inventory(service_instance)
container = inventory.viewManager.CreateContainerView(inventory.rootFolder, [vim.DistributedVirtualSwitch], True)
for item in containe... | Return a reference to a Distributed Virtual Switch object.
:param service_instance: PyVmomi service instance
:param dvs_name: Name of DVS to return
:return: A PyVmomi DVS object |
373,227 | def example(self) -> str:
if self.rgb_mode:
colorcode = .format(*self.rgb)
else:
colorcode = .format(self.code)
return .format(code=colorcode, s=self) | Same as str(self), except the color codes are actually used. |
373,228 | def ajax_count_plus(self, slug):
output = {
: 1 if MWiki.view_count_plus(slug) else 0,
}
return json.dump(output, self) | post count plus one via ajax. |
373,229 | def simBirth(self,which_agents):
N = np.sum(which_agents)
self.aLvlNow[which_agents] = drawLognormal(N,mu=self.aLvlInitMean,sigma=self.aLvlInitStd,seed=self.RNG.randint(0,2**31-1))
self.eStateNow[which_agents] = 1.0
self.t_age[which_agents] = 0
self.t_cycle... | Makes new consumers for the given indices. Initialized variables include aNrm, as
well as time variables t_age and t_cycle. Normalized assets are drawn from a lognormal
distributions given by aLvlInitMean and aLvlInitStd.
Parameters
----------
which_agents : np.array(Bool)
... |
373,230 | def get_selinux_context(path):
*
out = __salt__[]([, , path], python_shell=False)
try:
ret = re.search(r, out).group(0)
except AttributeError:
ret = (
.format(path)
)
return ret | Get an SELinux context from a given path
CLI Example:
.. code-block:: bash
salt '*' file.get_selinux_context /etc/hosts |
373,231 | def destroy_balancer(balancer_id, profile, **libcloud_kwargs):
s destroy_balancer method
:type libcloud_kwargs: ``dict``
:return: ``True`` if the destroy was successful, otherwise ``False``.
:rtype: ``bool``
CLI Example:
.. code-block:: bash
salt myminion libcloud_storage.destroy_ba... | Destroy a load balancer
:param balancer_id: LoadBalancer ID which should be used
:type balancer_id: ``str``
:param profile: The profile key
:type profile: ``str``
:param libcloud_kwargs: Extra arguments for the driver's destroy_balancer method
:type libcloud_kwargs: ``dict``
:return: ... |
373,232 | def _aggregate_one_result(
self, sock_info, slave_ok, cmd, collation=None, session=None):
result = self._command(
sock_info,
cmd,
slave_ok,
codec_options=self.__write_response_codec_options,
read_concern=self.read_concern,
... | Internal helper to run an aggregate that returns a single result. |
373,233 | def _dataframe_from_csv(reader, delimiter, with_header, skipspace):
sep = delimiter
header = 0
if not with_header:
header = None
return pd.read_csv(
reader,
header=header,
sep=sep,
skipinitialspace=skipspace,
encoding=
) | Returns csv data as a pandas Dataframe object |
373,234 | def template(self, key):
try:
return self._templates[key]
except KeyError:
return Template.Plugins[key] | Returns the template associated with this scaffold.
:param key | <str>
:return <projex.scaffold.Template> || None |
373,235 | def load_parameter_definitions(self, sheet_name: str = None):
definitions = self.excel_handler.load_definitions(sheet_name, filename=self.filename)
self.definition_version = self.excel_handler.version
return definitions | Load variable text from rows in excel file.
If no spreadsheet arg is given, all spreadsheets are loaded.
The first cell in the first row in a spreadsheet must contain the keyword 'variable' or the sheet is ignored.
Any cells used as titles (with no associated value) are also added to the return... |
373,236 | def _network_event_lifecycle_cb(conn, net, event, detail, opaque):
_salt_send_event(opaque, conn, {
: {
: net.name(),
: net.UUIDString()
},
: _get_libvirt_enum_string(, event),
:
}) | Network lifecycle events handler |
373,237 | def record_make_all_subfields_volatile(rec):
for tag in rec.keys():
for field_position, field in enumerate(rec[tag]):
for subfield_position, subfield in enumerate(field[0]):
if subfield[1][:9] != "VOLATILE:":
record_modify_subfield(rec, tag, subfield[0], ... | Turns all subfields to volatile |
373,238 | def _CreateReadAccessHelper(self):
h = CheckAccessHelper("read")
h.Allow("aff4:/")
h.Allow("aff4:/users")
h.Allow("aff4:/users/*", self._IsHomeDir)
h.Allow("aff4:/foreman", self._UserHasAdminLabel)
h.Allow("aff4:/blobs")
h.Allow("aff4:/blobs/*")
... | Creates a CheckAccessHelper for controlling read access.
This function and _CreateQueryAccessHelper essentially define GRR's ACL
policy. Please refer to these 2 functions to either review or modify
GRR's ACLs.
Read access gives you the ability to open and read aff4 objects for which
you already ha... |
373,239 | def fetch(self):
params = values.of({})
payload = self._version.fetch(
,
self._uri,
params=params,
)
return TaskQueueInstance(
self._version,
payload,
workspace_sid=self._solution[],
sid=self._... | Fetch a TaskQueueInstance
:returns: Fetched TaskQueueInstance
:rtype: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueInstance |
373,240 | def get_top(modality_type, value=None):
if modality_type in (ModalityType.AUDIO,
ModalityType.AUDIO_SPECTRAL,
ModalityType.GENERIC_L2_LOSS,
ModalityType.IDENTITY,
ModalityType.IDENTITY_SYMBOL,
Modalit... | Gets default top transformation; if none available, return value. |
373,241 | def register_whoosheer(self, wh):
self.whoosheers.append(wh)
for model in wh.models:
event.listen(model, .format(INSERT_KWD), self.after_insert)
event.listen(model, .format(UPDATE_KWD), self.after_update)
event.listen(model, .format(DELETE_KWD), self.after_de... | This will register the given whoosher on `whoosheers`, create the
neccessary SQLAlchemy event listeners, replace the `query_class` with
our own query class which will provide the search functionality
and store the app on the whoosheer, so that we can always work
with that.
:param... |
373,242 | def tag(self, path, name):
if not path[len(path) - 1] == :
path +=
config = self.get_config()
folder = self.find_folder({
: path
}, config)
if not folder:
raise custom_errors.FileNotInConfig(path)
old_name = folder[]
folder[] = name
dir_config = self.ada... | Change name associated with path |
373,243 | def get_analysis_data_for(self, ar):
analyses = ar.objectValues("Analysis")
out = []
for an in analyses:
info = self.get_base_info(an)
info.update({
"service_uid": an.getServiceUID(),
})
out.append(info)
re... | Return the Analysis data for this AR |
373,244 | def raw(self, query, settings=None, stream=False):
query = self._substitute(query, None)
return self._send(query, settings=settings, stream=stream).text | Performs a query and returns its output as text.
- `query`: the SQL query to execute.
- `settings`: query settings to send as HTTP GET parameters
- `stream`: if true, the HTTP response from ClickHouse will be streamed. |
373,245 | def calculate_perf_counter_100ns_queuelen_type(previous, current, property_name):
n0 = previous[property_name]
n1 = current[property_name]
d0 = previous["Timestamp_Sys100NS"]
d1 = current["Timestamp_Sys100NS"]
if n0 is None or n1 is None:
return
return (n1 - n0) / (d1 - d0) | PERF_COUNTER_100NS_QUEUELEN_TYPE
Average length of a queue to a resource over time in 100 nanosecond units.
https://msdn.microsoft.com/en-us/library/aa392905(v=vs.85).aspx
Formula (n1 - n0) / (d1 - d0) |
373,246 | def log_analyzer2(path):
with handle(MalformedLogEntryError,
lambda (c):
invoke_restart(,
+ c.text)):
for filename in find_all_logs(path):
analyze_log(filename) | This procedure considers every line which can't be parsed
as a line with ERROR level. |
373,247 | def connect(self, *args, **kwargs):
self._bootstrap_cm_list_from_file()
CMClient.connect(self, *args, **kwargs) | Attempt to establish connection, see :meth:`.CMClient.connect` |
373,248 | def get_vm(self, resource_group_name, vm_name):
s where the decorator comes in
this will return all the data about the virtual machine
instanceView') | you need to retry this just in case the credentials token expires,
that's where the decorator comes in
this will return all the data about the virtual machine |
373,249 | def from_string(cls, string, format_=None, fps=None, **kwargs):
fp = io.StringIO(string)
return cls.from_file(fp, format_, fps=fps, **kwargs) | Load subtitle file from string.
See :meth:`SSAFile.load()` for full description.
Arguments:
string (str): Subtitle file in a string. Note that the string
must be Unicode (in Python 2).
Returns:
SSAFile
Example:
>>> text = '''
... |
373,250 | def unpack_rows(self, column_types, connection):
for _ in iter_range(self.num_rows):
yield tuple(typ.from_resultset(self.payload, connection) for typ in column_types) | Unpack rows for data (from a select statement) from payload and yield a single row at a time.
:param column_types: a tuple of column descriptors
e.g. (<class 'pyhdb.protocol.types.String'>, <class 'pyhdb.protocol.types.ClobType'>)
:param connection: a db connection object
:returns... |
373,251 | def delete_rrset(self, zone_name, rtype, owner_name):
return self.rest_api_connection.delete("/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name) | Deletes an RRSet.
Arguments:
zone_name -- The zone containing the RRSet to be deleted. The trailing dot is optional.
rtype -- The type of the RRSet. This can be numeric (1) or
if a well-known name is defined for the type (A), you can use it instead.
owner_name -- The ... |
373,252 | def duplicate_files(self):
result=list()
files = SubmissionFile.valid_ones.order_by()
for key, dup_group in groupby(files, lambda f: f.md5):
file_list=[entry for entry in dup_group]
if len(file_list)>1:
for entry in file_list:
... | Search for duplicates of submission file uploads for this assignment.
This includes the search in other course, whether inactive or not.
Returns a list of lists, where each latter is a set of duplicate submissions
with at least on of them for this assignment |
373,253 | def insert_pattern(pattern, model, index=0):
if not pattern:
return False
pattern = pattern.replace(QChar(QChar.ParagraphSeparator), QString("\n"))
pattern = foundations.common.get_first_item(foundations.strings.to_string(pattern).split("\n"))
model.insert_pattern... | Inserts given pattern into given Model.
:param pattern: Pattern.
:type pattern: unicode
:param model: Model.
:type model: PatternsModel
:param index: Insertion indes.
:type index: int
:return: Method success.
:rtype: bool |
373,254 | def url(context, view, subdomain=UNSET, *args, **kwargs):
if subdomain is UNSET:
request = context.get()
if request is not None:
subdomain = getattr(request, , None)
else:
subdomain = None
elif subdomain is :
subdomain = None
return reverse(view,... | Resolves a URL in a template, using subdomain-based URL resolution.
If no subdomain is provided and a ``request`` is in the template context
when rendering, the URL will be resolved relative to the current request's
subdomain. If no ``request`` is provided, the URL will be resolved relative
to current ... |
373,255 | def track_progress(
measure: MeasureProgress,
target: MetricProgress,
interval_check: float,
capture_maybe: Optional[CaptureProgress] = None
) -> None:
def measure_to_target() -> MeasureComparison:
return list(zip(measure(), target))
def is_finished(progress: MeasureComparison) ->... | Tracks progress against a certain end condition of the simulation (for instance, a certain duration on the simulated
clock), reporting this progress as the simulation chugs along. Stops the simulation once the target has been
reached. By default, the progress is reported as printout on standard output, in a man... |
373,256 | def intersects_segment(self, seg):
return any(value.intersects_segment(seg) for value in self.itervalues()) | Returns True if any segmentlist in self intersects the
segment, otherwise returns False. |
373,257 | def load_jupyter_server_extension(nb_server_app):
app = nb_server_app.web_app
host_pattern =
app.add_handlers(host_pattern, [
(utils.url_path_join(app.settings[], ),
handlers.HttpOverWebSocketHandler),
(utils.url_path_join(app.settings[],
),
handlers.HttpO... | Called by Jupyter when this module is loaded as a server extension. |
373,258 | def makeAnimation(self):
aclip=mpy.AudioFileClip("sound.wav")
self.iS=self.iS.set_audio(aclip)
self.iS.write_videofile("mixedVideo.webm",15,audio=True)
print("wrote "+"mixedVideo.webm") | Use pymovie to render (visual+audio)+text overlays. |
373,259 | def fetch(self, category, filter_classified=False, **kwargs):
if category not in self.categories:
cause = "%s category not valid for %s" % (category, self.__class__.__name__)
raise BackendError(cause=cause)
if filter_classified and self.archive:
cause = "cla... | Fetch items from the repository.
The method retrieves items from a repository.
To removed classified fields from the resulting items, set
the parameter `filter_classified`. Take into account this
parameter is incompatible with archiving items. Raw client
data are archived befor... |
373,260 | def swap(self, core, other):
params = {
: ,
: core,
: other,
}
return self._get_url(self.url, params=params) | http://wiki.apache.org/solr/CoreAdmin#head-928b872300f1b66748c85cebb12a59bb574e501b |
373,261 | def get_dataset(self, name, multi_instance=0):
return [elem for elem in self._data_list
if elem.name == name and elem.multi_id == multi_instance][0] | get a specific dataset.
example:
try:
gyro_data = ulog.get_dataset('sensor_gyro')
except (KeyError, IndexError, ValueError) as error:
print(type(error), "(sensor_gyro):", error)
:param name: name of the dataset
:param multi_instance: the multi_id, defaul... |
373,262 | def render(self, template, **kwargs):
kwargs["cache_key"] = "%s" % kwargs["url"].values()
kwargs["lang"] = self.get_locale()
kwargs["assets"] = self.assets
kwargs["main_collections"] = self.main_collections(kwargs["lang"])
kwargs["cache_active"] = self.cache is not None... | Render a route template and adds information to this route.
:param template: Template name.
:type template: str
:param kwargs: dictionary of named arguments used to be passed to the template
:type kwargs: dict
:return: Http Response with rendered template
:rtype: flask.R... |
373,263 | def scale_up(self, n, pods=None, **kwargs):
maximum = dask.config.get()
if maximum is not None and maximum < n:
logger.info("Tried to scale beyond maximum number of workers %d > %d",
n, maximum)
n = maximum
pods = pods or self._cleanup_ter... | Make sure we have n dask-workers available for this cluster
Examples
--------
>>> cluster.scale_up(20) # ask for twenty workers |
373,264 | def validate_proof(proof: List[Keccak256], root: Keccak256, leaf_element: Keccak256) -> bool:
hash_ = leaf_element
for pair in proof:
hash_ = hash_pair(hash_, pair)
return hash_ == root | Checks that `leaf_element` was contained in the tree represented by
`merkleroot`. |
373,265 | def get_database_columns(self, tables=None, database=None):
source = database if database else self.database
tables = tables if tables else self.tables
return {tbl: self.get_columns(tbl) for tbl in tqdm(tables, total=len(tables),
... | Retrieve a dictionary of columns. |
373,266 | def meta(self):
if not self._pv.meta_data_property or not self._meta_target:
return {}
return getattr(self._meta_target, self._pv.meta_data_property) | Value of the bound meta-property on the target. |
373,267 | def vocab_account_type(instance):
for key, obj in instance[].items():
if in obj and obj[] == :
try:
acct_type = obj[]
except KeyError:
continue
if acct_type not in enums.ACCOUNT_TYPE_OV:
yield JSONError("Object is a U... | Ensure a user-account objects' 'account-type' property is from the
account-type-ov vocabulary. |
373,268 | def get_code_language(self):
js_source = self.get_js_source()
if self.options.get("include_html", False):
resources = get_sphinx_resources(include_bokehjs_api=True)
html_source = BJS_HTML.render(
css_files=resources.css_files,
js_files=res... | This is largely copied from bokeh.sphinxext.bokeh_plot.run |
373,269 | def _to_json(self, include_references=True):
if include_references:
return json.dumps(self._resource._properties, cls=PotionJSONEncoder)
else:
return json.dumps(
{
k: v
for k, v in self._resource._properties.items()... | Convert the model to JSON using the PotionJSONEncode and automatically
resolving the resource as needed (`_properties` call handles this). |
373,270 | def stream_events(self, filter: Callable[[Event], bool] = None, *, max_queue_size: int = 0):
return stream_events([self], filter, max_queue_size=max_queue_size) | Shortcut for calling :func:`stream_events` with this signal in the first argument. |
373,271 | def types(**args):
def l(func):
if hasattr(func, ):
func.__annotations__.update(args)
else:
func.__annotations__ = args
return func
return l | Specifies the types used for the arguments of a published service.
@types(a=int, b = str)
def f(a, b):
pass |
373,272 | def list_commands(self, ctx):
self.connect(ctx)
if not hasattr(ctx, "widget"):
return super(Engineer, self).list_commands(ctx)
return ctx.widget.engineer_list_commands() + super(Engineer, self).list_commands(ctx) | list all commands exposed to engineer |
373,273 | async def set_property_value(self, turn_context: TurnContext, property_name: str, value: object) -> None:
if turn_context == None:
raise TypeError()
if not property_name:
raise TypeError()
cached_state = turn_context.turn_state.get(self._context_service_key)
... | Deletes a property from the state cache in the turn context.
:param turn_context: The context object for this turn.
:param property_name: The value to set on the property.
:return: None |
373,274 | def files(self):
if self._rundir[] is UNDETERMINED:
out_stem = pathlib.Path(self.par[][] + )
out_dir = self.path / out_stem.parent
if out_dir.is_dir():
self._rundir[] = set(out_dir.iterdir())
else:
self._rundir[] = set()
... | Set of found binary files output by StagYY. |
373,275 | def _rspiral(width, height):
x0 = 0
y0 = 0
x1 = width - 1
y1 = height - 1
while x0 < x1 and y0 < y1:
for x in range(x0, x1):
yield x, y0
for y in range(y0, y1):
yield x1, y
for x in range(x1, x0, -1):
... | Reversed spiral generator.
Parameters
----------
width : `int`
Spiral width.
height : `int`
Spiral height.
Returns
-------
`generator` of (`int`, `int`)
Points. |
373,276 | def main():
configure_obj = None
parser = argparse.ArgumentParser(description=)
parser.add_argument(
, ,
help=,
)
parser.add_argument(
, ,
help=,
)
parser.add_argument(
, ,
help=,
)
parser.add_argument(
, ,
dest... | Check args |
373,277 | def get_item(self, table_name, key_dict,
consistent_read=False,
expression_attribute_names=None,
projection_expression=None,
return_consumed_capacity=None):
payload = {: table_name,
: utils.marshall(key_dict),
... | Invoke the `GetItem`_ function.
:param str table_name: table to retrieve the item from
:param dict key_dict: key to use for retrieval. This will
be marshalled for you so a native :class:`dict` works.
:param bool consistent_read: Determines the read consistency model: If
... |
373,278 | def to_networkx(self, labels=None, edge_labels=False):
import networkx as nx
graph = nx.DiGraph()
for node in self._traverse_nodes():
u = node.key
graph.add_node(u)
graph.nodes[u][] = node.value
if labels is not None:
... | Get a networkx representation of the binary search tree. |
373,279 | def decode(self, bytes, raw=False):
sec = super(Time32Type, self).decode(bytes)
return sec if raw else dmc.toLocalTime(sec) | decode(bytearray, raw=False) -> value
Decodes the given bytearray containing the elapsed time in
seconds since the GPS epoch and returns the corresponding
Python :class:`datetime`.
If the optional parameter ``raw`` is ``True``, the integral
number of seconds will be returned in... |
373,280 | def _unpack_case(self, case):
base_mva = case.base_mva
b = case.connected_buses
l = case.online_branches
g = case.online_generators
nb = len(b)
nl = len(l)
ng = len(g)
return b, l, g, nb, nl, ng, base_mva | Returns the contents of the case to be used in the OPF. |
373,281 | def _include_file(context, uri, calling_uri, **kwargs):
template = _lookup_template(context, uri, calling_uri)
(callable_, ctx) = _populate_self_namespace(
context._clean_inheritance_tokens(),
template)
callable_(ctx, **_kwargs_for_includ... | locate the template from the given uri and include it in
the current output. |
373,282 | def write(self, outfile=None, section=None):
with io.open(outfile or self.user_config_file(), ) as f:
self.data.write(outfile=f, section=section) | Write the current config to a file (defaults to user config).
:param str outfile: The path to the file to write to.
:param None/str section: The config section to write, or :data:`None`
to write the entire config. |
373,283 | def get_suitable_slot_for_duplicate(self, src_slot):
slot_from = to_int(src_slot, 0)
if slot_from < 1:
return -1
container = self.get_container_at(slot_from)
if not container or not IAnalysisRequest.providedBy(container):
... | Returns the suitable position for a duplicate analysis, taking into
account if there is a WorksheetTemplate assigned to this worksheet.
By default, returns a new slot at the end of the worksheet unless there
is a slot defined for a duplicate of the src_slot in the worksheet
template lay... |
373,284 | def calibration_stimulus(self, mode):
if mode == :
return self.tone_calibrator.stimulus
elif mode ==:
return self.bs_calibrator.stimulus | Gets the stimulus model for calibration
:param mode: Type of stimulus to get: tone or noise
:type mode: str
:returns: :class:`StimulusModel<sparkle.stim.stimulus_model.StimulusModel>` |
373,285 | def _merge_align_bams(data):
for key in (["work_bam"], ["work_bam_plus", "disc"], ["work_bam_plus", "sr"], ["umi_bam"]):
in_files = tz.get_in(key, data, [])
if not isinstance(in_files, (list, tuple)):
in_files = [in_files]
in_files = [x for x in in_files if x and x != "None"... | Merge multiple alignment BAMs, including split and discordant reads. |
373,286 | def _build_header(self):
logger.debug("===============")
logger.debug("Building header")
logger.debug("===============")
self.template += hs.header | Adds the header template to the master template string |
373,287 | def segmentlistdict_fromsearchsummary_in(xmldoc, program = None):
stbl = lsctables.SearchSummaryTable.get_table(xmldoc)
ptbl = lsctables.ProcessTable.get_table(xmldoc)
return stbl.get_in_segmentlistdict(program and ptbl.get_ids_by_program(program)) | Convenience wrapper for a common case usage of the segmentlistdict
class: searches the process table in xmldoc for occurances of a
program named program, then scans the search summary table for
matching process IDs and constructs a segmentlistdict object from
the in segments in those rows.
Note: the segmentlist... |
373,288 | def draw(self):
if not self.visible:
return
self.window.blit(self.image, self.loc) | Draws the image at the given location. |
373,289 | def start_health_check(self, recipient):
if recipient not in self.addresses_events:
self.whitelist(recipient)
ping_nonce = self.nodeaddresses_to_nonces.setdefault(
recipient,
{: 0},
)
events = healthcheck.HealthEvents(... | Starts a task for healthchecking `recipient` if there is not
one yet.
It also whitelists the address |
373,290 | def validate(self):
for validator in self.validators:
try:
validator(self.obj)
except ValidationError as e:
self.errors.append(e.error)
if not self.errors and self._has_unvalidated_prefix():
self._move_to_validated()
... | Validates the given Amazon S3 file with :attr:`validators`. If errors
occur they are appended to :attr:`errors`. If the file is valid and a
`AWS_UNVALIDATED_PREFIX` config is present, its value will be removed
from the file key.
:return: a boolean indicating if the file vas valid. |
373,291 | def dump(self):
return json.dumps(
self.primitive,
sort_keys=True,
ensure_ascii=False,
separators=(, )) | Item as a JSON representation. |
373,292 | def request(self, url, post=None, method="GET"):
dsid = self.get_dsid()
baseurl = "https://auth.api.swedbank.se/TDE_DAP_Portal_REST_WEB/api/v1/%s?dsid=%s" % (
url, dsid)
if self.pch is None:
self.pch = build_opener(HTTPCookieProcessor(self.cj))
if post:... | Make the request |
373,293 | def sign(self, issuer_cert, issuer_key, digest):
digest_obj = _lib.EVP_get_digestbyname(digest)
_openssl_assert(digest_obj != _ffi.NULL)
_lib.X509_CRL_set_issuer_name(
self._crl, _lib.X509_get_subject_name(issuer_cert._x509))
_lib.X509_CRL_sort(self._crl)
res... | Sign the CRL.
Signing a CRL enables clients to associate the CRL itself with an
issuer. Before a CRL is meaningful to other OpenSSL functions, it must
be signed by an issuer.
This method implicitly sets the issuer's name based on the issuer
certificate and private key used to s... |
373,294 | def save_controls(self, parameterstep: = None,
simulationstep: = None,
auxfiler: = None):
if auxfiler:
auxfiler.save(parameterstep, simulationstep)
for element in printtools.progressbar(self):
element.model.parameters.save_c... | Save the control parameters of the |Model| object handled by
each |Element| object and eventually the ones handled by the
given |Auxfiler| object. |
373,295 | def Shah(m, x, D, rhol, mul, kl, Cpl, P, Pc):
r
VL = m/(rhol*pi/4*D**2)
ReL = Reynolds(V=VL, D=D, rho=rhol, mu=mul)
Prl = Prandtl(Cp=Cpl, k=kl, mu=mul)
hL = turbulent_Dittus_Boelter(ReL, Prl)*kl/D
Pr = P/Pc
return hL*((1-x)**0.8 + 3.8*x**0.76*(1-x)**0.04/Pr**0.38) | r'''Calculates heat transfer coefficient for condensation
of a fluid inside a tube, as presented in [1]_ and again by the same
author in [2]_; also given in [3]_. Requires no properties of the gas.
Uses the Dittus-Boelter correlation for single phase heat transfer
coefficient, with a Reynolds number a... |
373,296 | def push_log(self, info, level, *args, **kwargs):
log.log(level, info, *args, **kwargs) | Writes logs. To be fully implemented by subclasses.
:param info: Log message content.
:type info: unicode | str
:param level: Logging level.
:type level: int
:param args: Positional arguments to pass to logger.
:param kwargs: Keyword arguments to pass to logger. |
373,297 | def set_trunk_groups(self, intf, value=None, default=False, disable=False):
if default:
cmd =
return self.configure_interface(intf, cmd)
if disable:
cmd =
return self.configure_interface(intf, cmd)
current_value = self.get(intf)[]
... | Configures the switchport trunk group value
Args:
intf (str): The interface identifier to configure.
value (str): The set of values to configure the trunk group
default (bool): Configures the trunk group default value
disable (bool): Negates all trunk group setti... |
373,298 | def add_videos_to_playlist(self, access_token, playlist_id, video_ids):
url =
data = {
: self.client_id,
: access_token,
: playlist_id,
: video_ids
}
r = requests.post(url, data=data)
check_error(r)
return r.json()... | doc: http://open.youku.com/docs/doc?id=75 |
373,299 | def get(self, url=None, params=None, retry=True):
headers = self._gen_headers(self.access_token, url)
attempts = 1
while attempts <= HTTP_ATTEMPTS_MAX:
try:
res = requests.get(url,
headers=headers,
... | Execute HTTP GET |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.