Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
381,900 | def offsets_for_max_size( max_size ):
for i, max in enumerate( reversed( BIN_OFFSETS_MAX ) ):
if max_size < max:
break
else:
raise Exception( "%d is larger than the maximum possible size (%d)" % ( max_size, BIN_OFFSETS_MAX[0] ) )
return BIN_OFFSETS[ ( len(BIN_OFFSETS) - i - ... | Return the subset of offsets needed to contain intervals over (0,max_size) |
381,901 | def apply_filters(target, lines):
filters = get_filters(target)
if filters:
for l in lines:
if any(f in l for f in filters):
yield l
else:
for l in lines:
yield l | Applys filters to the lines of a datasource. This function is used only in
integration tests. Filters are applied in an equivalent but more performant
way at run time. |
381,902 | def _set_error_disable_timeout(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=error_disable_timeout.error_disable_timeout, is_container=, presence=False, yang_name="error-disable-timeout", rest_name="error-disable-timeout", parent=self, path_helper=s... | Setter method for error_disable_timeout, mapped from YANG variable /protocol/spanning_tree/rpvst/error_disable_timeout (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_error_disable_timeout is considered as a private
method. Backends looking to populate this varia... |
381,903 | def start_listener_thread(self, timeout_ms=30000, exception_handler=None):
try:
thread = Thread(target=self.listen_forever,
args=(timeout_ms, exception_handler))
thread.daemon = True
self.sync_thread = thread
self.should_listen... | Start a listener thread to listen for events in the background.
Args:
timeout (int): How long to poll the Home Server for before
retrying.
exception_handler (func(exception)): Optional exception handler
function which can be used to handle exceptions in the... |
381,904 | def _headers(self, name, is_file=False):
value = self._files[name] if is_file else self._data[name]
_boundary = self.boundary.encode("utf-8") if isinstance(self.boundary, unicode) else urllib.quote_plus(self.boundary)
headers = ["--%s" % _boundary]
if is_file:
d... | Returns the header of the encoding of this parameter.
Args:
name (str): Field name
Kwargs:
is_file (bool): If true, this is a file field
Returns:
array. Headers |
381,905 | async def executor(func, *args, **kwargs):
def syncfunc():
return func(*args, **kwargs)
loop = asyncio.get_running_loop()
return await loop.run_in_executor(None, syncfunc) | Execute a function in an executor thread.
Args:
todo ((func,args,kwargs)): A todo tuple. |
381,906 | def listlike(obj):
return hasattr(obj, "__iter__") \
and not issubclass(type(obj), str)\
and not issubclass(type(obj), unicode) | Is an object iterable like a list (and not a string)? |
381,907 | def check_lazy_load_straat(f):
def wrapper(*args):
straat = args[0]
if (
straat._namen is None or straat._metadata is None
):
log.debug(, straat.id)
straat.check_gateway()
s = straat.gateway.get_straat_by_id(straat.id)
straat._... | Decorator function to lazy load a :class:`Straat`. |
381,908 | def alert_statuses(self, alert_statuses):
if alert_statuses is None:
raise ValueError("Invalid value for `alert_statuses`, must not be `None`")
allowed_values = ["VISIBLE", "HIDDEN", "NOT_LOADED"]
if not set(alert_statuses.keys()).issubset(set(allowed_values)):
... | Sets the alert_statuses of this IntegrationStatus.
A Map from the ids of the alerts contained in this integration to their install status. The install status can take on one of three values, `VISIBLE`, `HIDDEN`, and `NOT_LOADED` # noqa: E501
:param alert_statuses: The alert_statuses of this Integrat... |
381,909 | def get_cursor_position(self):
in_stream = self.in_stream
query_cursor_position = u"\x1b[6n"
self.write(query_cursor_position)
def retrying_read():
while True:
try:
c = in_stream.read(1)
if c == :
... | Returns the terminal (row, column) of the cursor
0-indexed, like blessings cursor positions |
381,910 | def pos_tag(self):
self._require_tokens()
self._require_no_ngrams_as_tokens()
self._invalidate_workers_tokens()
logger.info()
self._send_task_to_workers()
self.pos_tagged = True
return self | Apply Part-of-Speech (POS) tagging on each token.
Uses the default NLTK tagger if no language-specific tagger could be loaded (English is assumed then as
language). The default NLTK tagger uses Penn Treebank tagset
(https://ling.upenn.edu/courses/Fall_2003/ling001/penn_treebank_pos.html).
... |
381,911 | def format_installed_dap_list(simple=False):
lines = []
if simple:
for pkg in sorted(get_installed_daps()):
lines.append(pkg)
else:
for pkg, instances in sorted(get_installed_daps_detailed().items()):
versions = []
for instance in instances:
... | Formats all installed DAPs in a human readable form to list of lines |
381,912 | def get_series_episode(series_id, season, episode):
result = tvdb_client.query_series_episodes(series_id, aired_season=season, aired_episode=episode)
if result:
return tvdb_client.get_episode(result[][0][]) | Get an episode of a series.
:param int series_id: id of the series.
:param int season: season number of the episode.
:param int episode: episode number of the episode.
:return: the episode data.
:rtype: dict |
381,913 | def close(self):
if not self._process:
return
if self._process.returncode is not None:
return
_logger.debug()
try:
self._process.terminate()
except OSError as error:
if error.errno != errno.ESRCH:
raise
... | Terminate or kill the subprocess.
This function is blocking. |
381,914 | def _decimal_to_xsd_format(value):
value = XDecimal._decimal_canonical(value)
negative, digits, exponent = value.as_tuple()
assert digits
assert digits[0] != 0 or len(digits) == 1
result = []
if neg... | Converts a decimal.Decimal value to its XSD decimal type value.
Result is a string containing the XSD decimal type's lexical value
representation. The conversion is done without any precision loss.
Note that Python's native decimal.Decimal string representation will
not do here as the ... |
381,915 | def get_policies(self):
prefix = _IDENTITY_NS + _POLICY_NS
policylist_list = [
_create_from_bytes(d, identity_pb2.PolicyList)
for _, d in self._state_view.leaves(prefix=prefix)
]
policies = []
for policy_list in policylist_list:
for p... | Returns all the Policies under the Identity namespace.
Returns:
(list): A list containing all the Policies under the Identity
namespace. |
381,916 | def parse(self,fileName,offset):
p = Parser()
p.file = open(fileName, )
a = p.parse_synset(offset=offset)
p.file.close()
self.__dict__.update(a.__dict__) | Parses synset from file <fileName>
from offset <offset> |
381,917 | def isorbit_record(self):
import re
test = re.match(, self.targetname.strip()) is not None
return test | `True` if `targetname` appears to be a comet orbit record number.
NAIF record numbers are 6 digits, begin with a '9' and can
change at any time. |
381,918 | def match_and(self, tokens, item):
for match in tokens:
self.match(match, item) | Matches and. |
381,919 | def replace_uri(rdf, fromuri, touri):
replace_subject(rdf, fromuri, touri)
replace_predicate(rdf, fromuri, touri)
replace_object(rdf, fromuri, touri) | Replace all occurrences of fromuri with touri in the given model.
If touri is a list or tuple of URIRef, all values will be inserted.
If touri=None, will delete all occurrences of fromuri instead. |
381,920 | def read_validate_params(self, request):
self.client = self.client_authenticator.by_identifier_secret(request)
self.password = request.post_param("password")
self.username = request.post_param("username")
self.scope_handler.parse(request=request, source="body")
return... | Checks if all incoming parameters meet the expected values. |
381,921 | def connect_ssl(cls, user, password, endpoints,
ca_certs=None, validate=None):
if isinstance(endpoints, basestring):
endpoints = [endpoints]
transport = SingleEndpointTransport(
SocketTransport.connect_ssl, endpoints, ca_certs=ca_certs,
va... | Creates an SSL transport to the first endpoint (aserver) to which
we successfully connect |
381,922 | def addcols(X, cols, names=None):
if isinstance(names,str):
names = [n.strip() for n in names.split()]
if isinstance(cols, list):
if any([isinstance(x,np.ndarray) or isinstance(x,list) or \
isinstance(x,tuple) for x in cols]):
assert all([l... | Add one or more columns to a numpy ndarray.
Technical dependency of :func:`tabular.spreadsheet.aggregate_in`.
Implemented by the tabarray method
:func:`tabular.tab.tabarray.addcols`.
**Parameters**
**X** : numpy ndarray with structured dtype or recarray
The recarra... |
381,923 | def power(self):
power = self._state[]
return PowerUsage(power.get(),
power.get(),
power.get(),
power.get(),
power.get(),
power.get(),
powe... | :return: A power object modeled as a named tuple |
381,924 | def build_backend(self, conn_string):
backend_name, _ = conn_string.split(, 1)
backend_path = .format(backend_name)
client_class = import_attr(backend_path, )
return client_class(conn_string) | Given a DSN, returns an instantiated backend class.
Ex::
backend = gator.build_backend('locmem://')
# ...or...
backend = gator.build_backend('redis://127.0.0.1:6379/0')
:param conn_string: A DSN for connecting to the queue. Passed along
to the backend.
... |
381,925 | def update_enterprise_courses(self, enterprise_customer, course_container_key=, **kwargs):
enterprise_context = {
: enterprise_customer and enterprise_customer.identity_provider,
: enterprise_customer and str(enterprise_customer.uuid),
}
enterprise_context.update... | This method adds enterprise-specific metadata for each course.
We are adding following field in all the courses.
tpa_hint: a string for identifying Identity Provider.
enterprise_id: the UUID of the enterprise
**kwargs: any additional data one would like to add on a per-use b... |
381,926 | def add_tab(self, widget):
self.clients.append(widget)
index = self.tabwidget.addTab(widget, widget.get_short_name())
self.tabwidget.setCurrentIndex(index)
self.tabwidget.setTabToolTip(index, widget.get_filename())
if self.dockwidget and not self.ismaximized:
... | Add tab. |
381,927 | async def finalize_websocket(
self,
result: ResponseReturnValue,
websocket_context: Optional[WebsocketContext]=None,
from_error_handler: bool=False,
) -> Optional[Response]:
if result is not None:
response = await self.make_response(result)
else:
... | Turns the view response return value into a response.
Arguments:
result: The result of the websocket to finalize into a response.
websocket_context: The websocket context, optional as Flask
omits this argument. |
381,928 | def do_query(self, line):
table, line = self.get_table_params(line)
args = self.getargs(line)
condition = None
count = False
as_array = False
max_size = None
batch_size = None
start = None
if in args:
asc = False
... | query [:tablename] [-r] [--count|-c] [--array|-a] [-{max}] [{rkey-condition}] hkey [attributes,...]
where rkey-condition:
--eq={key} (equal key)
--ne={key} (not equal key)
--le={key} (less or equal than key)
--lt={key} (less than key)
--ge={key} (grea... |
381,929 | def profile(script, argv, profiler_factory,
pickle_protocol, dump_filename, mono):
filename, code, globals_ = script
sys.argv[:] = [filename] + list(argv)
__profile__(filename, code, globals_, profiler_factory,
pickle_protocol=pickle_protocol, dump_filename=dump_filename,
... | Profile a Python script. |
381,930 | def minimize(f, start=None, smooth=False, log=None, array=False, **vargs):
if start is None:
assert not array, "Please pass starting values explicitly when array=True"
arg_count = f.__code__.co_argcount
assert arg_count > 0, "Please pass starting values explicitly for variadic functions... | Minimize a function f of one or more arguments.
Args:
f: A function that takes numbers and returns a number
start: A starting value or list of starting values
smooth: Whether to assume that f is smooth and use first-order info
log: Logging function called on the result of optimiz... |
381,931 | def _to_dict(self, node, fast_access=True, short_names=False, nested=False,
copy=True, with_links=True):
if (fast_access or short_names or nested) and not copy:
raise ValueError(
)
if nested and short_names:
raise ValueErro... | Returns a dictionary with pairings of (full) names as keys and instances as values.
:param fast_access:
If true parameter or result values are returned instead of the
instances.
:param short_names:
If true keys are not full names but only the names.
Ra... |
381,932 | def home():
return dict(links=dict(api=.format(request.url, PREFIX[1:]))), \
HTTPStatus.OK | Temporary helper function to link to the API routes |
381,933 | def build_routename(cls, name, routename_prefix=None):
if routename_prefix is None:
routename_prefix = .format(
cls.__name__.replace(, ).lower()
)
routename_prefix = routename_prefix.rstrip()
return .join([routename_prefix, name]) | Given a ``name`` & an optional ``routename_prefix``, this generates a
name for a URL.
:param name: The name for the URL (ex. 'detail')
:type name: string
:param routename_prefix: (Optional) A prefix for the URL's name (for
resolving). The default is ``None``, which will aut... |
381,934 | def custom_indicator_class_factory(indicator_type, base_class, class_dict, value_fields):
value_count = len(value_fields)
def init_1(self, tcex, value1, xid, **kwargs):
summary = self.build_summary(value1)
base_class.__init__(self, tcex, indicator_type, summary, xid, **kwargs)... | Internal method for dynamically building Custom Indicator Class. |
381,935 | def metar(wxdata: MetarData, units: Units) -> MetarTrans:
translations = shared(wxdata, units)
translations[] = wind(wxdata.wind_direction, wxdata.wind_speed,
wxdata.wind_gust, wxdata.wind_variable_direction,
units.wind_speed)
translations... | Translate the results of metar.parse
Keys: Wind, Visibility, Clouds, Temperature, Dewpoint, Altimeter, Other |
381,936 | def fdr(pvals, alpha=0.05, method=):
assert method.lower() in [, ]
pvals = np.asarray(pvals)
shape_init = pvals.shape
pvals = pvals.ravel()
num_nan = np.isnan(pvals).sum()
pvals_sortind = np.argsort(pvals)
pvals_sorted = pvals[pvals_sortind]
sortrevind = pvals_sortind.arg... | P-values FDR correction with Benjamini/Hochberg and
Benjamini/Yekutieli procedure.
This covers Benjamini/Hochberg for independent or positively correlated and
Benjamini/Yekutieli for general or negatively correlated tests.
Parameters
----------
pvals : array_like
Array of p-values of t... |
381,937 | def preprocess_legislation(legislation_json):
import os
import pkg_resources
import pandas as pd
default_config_files_directory = os.path.join(
pkg_resources.get_distribution().location)
prix_annuel_carburants = pd.read_csv(
os.path.join(
default_config_files_... | Preprocess the legislation parameters to add prices and amounts from national accounts |
381,938 | def get_parameter_p_value_too_high_warning(
model_type, model_params, parameter, p_value, maximum_p_value
):
warnings = []
if p_value > maximum_p_value:
data = {
"{}_p_value".format(parameter): p_value,
"{}_maximum_p_value".format(parameter): maximum_p_value,
}
... | Return an empty list or a single warning wrapped in a list indicating
whether model parameter p-value is too high.
Parameters
----------
model_type : :any:`str`
Model type (e.g., ``'cdd_hdd'``).
model_params : :any:`dict`
Parameters as stored in :any:`eemeter.CalTRACKUsagePerDayCand... |
381,939 | def statuses(self):
r_json = self._get_json()
statuses = [Status(self._options, self._session, raw_stat_json)
for raw_stat_json in r_json]
return statuses | Get a list of status Resources from the server.
:rtype: List[Status] |
381,940 | def append_seeding_annotation(self, annotation: str, values: Set[str]) -> Seeding:
return self.seeding.append_annotation(annotation, values) | Add a seed induction method for single annotation's values.
:param annotation: The annotation to filter by
:param values: The values of the annotation to keep |
381,941 | def p_file_type_1(self, p):
try:
self.builder.set_file_type(self.document, p[2])
except OrderError:
self.order_error(, , p.lineno(1))
except CardinalityError:
self.more_than_one_error(, p.lineno(1)) | file_type : FILE_TYPE file_type_value |
381,942 | def process_m2m_through_save(self, obj, created=False, **kwargs):
if not created:
return
self._process_m2m_through(obj, ) | Process M2M post save for custom through model. |
381,943 | def setAndUpdateValues(self,solution_next,IncomeDstn,LivPrb,DiscFac):
s marginal value function
(etc), the probability of getting the worst income shock next period,
the patience factor, human wealth, and the bounding MPCs.
Parameters
----------
solution_next : ConsumerS... | Unpacks some of the inputs (and calculates simple objects based on them),
storing the results in self for use by other methods. These include:
income shocks and probabilities, next period's marginal value function
(etc), the probability of getting the worst income shock next period,
the... |
381,944 | def trc(postfix: Optional[str] = None, *, depth=1) -> logging.Logger:
x = inspect.stack()[depth]
code = x[0].f_code
func = [obj for obj in gc.get_referrers(code) if inspect.isfunction(obj)][0]
mod = inspect.getmodule(x.frame)
parts = (mod.__name__, func.__qualname__)
if postfix:
... | Automatically generate a logger from the calling function
:param postfix: append another logger name on top this
:param depth: depth of the call stack at which to capture the caller name
:return: instance of a logger with a correct path to a current caller |
381,945 | def remove_independent_variable(self, variable_name):
self._remove_child(variable_name)
self._independent_variables.pop(variable_name) | Remove an independent variable which was added with add_independent_variable
:param variable_name: name of variable to remove
:return: |
381,946 | def run(self):
if not self._queue:
raise Exception("No queue available to send messages")
factory = LiveStreamFactory(self)
self._reactor.connectSSL("streaming.campfirenow.com", 443, factory, ssl.ClientContextFactory())
self._reactor.run() | Called by the process, it runs it.
NEVER call this method directly. Instead call start() to start the separate process.
If you don't want to use a second process, then call fetch() directly on this istance.
To stop, call terminate() |
381,947 | def on_message(self, msg):
msg = json.loads(msg)
psession = self.funcserver.pysessions.get(self.pysession_id, None)
if psession is None:
interpreter = PyInterpreter(self.funcserver.define_python_namespace())
psession = dict(interpreter=interpreter, socks=set([s... | Called when client sends a message.
Supports a python debugging console. This forms
the "eval" part of a standard read-eval-print loop.
Currently the only implementation of the python
console is in the WebUI but the implementation
of a terminal based console is planned. |
381,948 | def isasteroid(self):
if self.asteroid is not None:
return self.asteroid
elif self.comet is not None:
return not self.comet
else:
return any(self.parse_asteroid()) is not None | `True` if `targetname` appears to be an asteroid. |
381,949 | def get_compound_ids(self):
cursor = self.conn.cursor()
cursor.execute()
self.conn.commit()
for row in cursor:
if not row[0] in self.compound_ids:
self.compound_ids.append(row[0]) | Extract the current compound ids in the database. Updates the self.compound_ids list |
381,950 | def add_message(self, id, body, tags=False):
if not tags:
tags = {}
try:
self._tx_queue_lock.acquire()
self._tx_queue.append(
EventHub_pb2.Message(id=id, body=body, tags=tags, zone_id=self.eventhub_client.zone_id))
finally:
... | add messages to the rx_queue
:param id: str message Id
:param body: str the message body
:param tags: dict[string->string] tags to be associated with the message
:return: self |
381,951 | def _delete(self, url, data, scope):
self._create_session(scope)
response = self.session.delete(url, data=data)
return response.status_code, response.text | Make a DELETE request using the session object to a Degreed endpoint.
Args:
url (str): The url to send a DELETE request to.
data (str): The json encoded payload to DELETE.
scope (str): Must be one of the scopes Degreed expects:
- `CONTENT_PROVIDER_SCO... |
381,952 | def encoded_dict(in_dict):
out_dict = {}
for k, v in in_dict.items():
if isinstance(v, unicode):
if sys.version_info < (3, 0):
v = v.encode()
elif isinstance(v, str):
if sys.version_info < (3, 0):
v.decode()
out_di... | Encode every value of a dict to UTF-8.
Useful for POSTing requests on the 'data' parameter of urlencode. |
381,953 | def _verify_configs(configs):
if configs:
scenario_names = [c.scenario.name for c in configs]
for scenario_name, n in collections.Counter(scenario_names).items():
if n > 1:
msg = ("Duplicate scenario name found. "
).format(scenario_name)
... | Verify a Molecule config was found and returns None.
:param configs: A list containing absolute paths to Molecule config files.
:return: None |
381,954 | def update(name, connection_uri="", id_file="", o=[], config=None):
storm_ = get_storm_instance(config)
settings = {}
if id_file != "":
settings[] = id_file
for option in o:
k, v = option.split("=")
settings[k] = v
try:
storm_.update_entry(name, **settings)
... | Enhanced version of the edit command featuring multiple
edits using regular expressions to match entries |
381,955 | def setUp(self, port, soc, input):
name = soc.getOperationName()
bop = port.getBinding().operations.get(name)
op = port.getBinding().getPortType().operations.get(name)
assert op is not None, %name
assert bop is not None, %name
self.input = input
self.... | Instance Data:
op -- WSDLTools Operation instance
bop -- WSDLTools BindingOperation instance
input -- boolean input/output |
381,956 | def delta_e_cie2000(lab_color_vector, lab_color_matrix, Kl=1, Kc=1, Kh=1):
L, a, b = lab_color_vector
avg_Lp = (L + lab_color_matrix[:, 0]) / 2.0
C1 = numpy.sqrt(numpy.sum(numpy.power(lab_color_vector[1:], 2)))
C2 = numpy.sqrt(numpy.sum(numpy.power(lab_color_matrix[:, 1:], 2), axis=1))
avg_C... | Calculates the Delta E (CIE2000) of two colors. |
381,957 | def whichEncoding(self):
if self.request.mode in BROWSER_REQUEST_MODES:
if self.fields.getOpenIDNamespace() == OPENID2_NS and \
len(self.encodeToURL()) > OPENID1_URL_LIMIT:
return ENCODE_HTML_FORM
else:
return ENCODE_URL
els... | How should I be encoded?
@returns: one of ENCODE_URL, ENCODE_HTML_FORM, or ENCODE_KVFORM.
@change: 2.1.0 added the ENCODE_HTML_FORM response. |
381,958 | def process_request(self, request):
request.token = get_token(request)
request.user = SimpleLazyObject(lambda: get_user(request))
request._dont_enforce_csrf_checks = dont_enforce_csrf_checks(request) | Lazy set user and token |
381,959 | def _render_item(self, depth, key, value = None, **settings):
strptrn = self.INDENT * depth
lchar = self.lchar(settings[self.SETTING_LIST_STYLE])
s = self._es_text(settings, settings[self.SETTING_LIST_FORMATING])
lchar = self.fmt_text(lchar, **s)
strptrn = "{}"
... | Format single list item. |
381,960 | def compute_diff(dir_base, dir_cmp):
data = {}
data[] = list(set(dir_cmp[]) - set(dir_base[]))
data[] = list(set(dir_base[]) - set(dir_cmp[]))
data[] = []
data[] = list(set(dir_cmp[]) - set(dir_base[]))
for f in set(dir_cmp[]).intersection(set(dir_base[])):
if dir_base[][f] != dir_... | Compare `dir_base' and `dir_cmp' and returns a list with
the following keys:
- deleted files `deleted'
- created files `created'
- updated files `updated'
- deleted directories `deleted_dirs' |
381,961 | def deal_with_changeset_stack_policy(self, fqn, stack_policy):
if stack_policy:
kwargs = generate_stack_policy_args(stack_policy)
kwargs["StackName"] = fqn
logger.debug("Setting stack policy on %s.", fqn)
self.cloudformation.set_stack_policy(**kwargs) | Set a stack policy when using changesets.
ChangeSets don't allow you to set stack policies in the same call to
update them. This sets it before executing the changeset if the
stack policy is passed in.
Args:
stack_policy (:class:`stacker.providers.base.Template`): A templat... |
381,962 | def find_root(filename, target=):
lg.debug(f)
if target == and (filename / ).exists():
return filename
elif filename.is_dir():
pattern = target[:3] +
if filename.stem.startswith(pattern):
return filename
return find_root(filename.parent, target) | Find base directory (root) for a filename.
Parameters
----------
filename : instance of Path
search the root for this file
target: str
'bids' (the directory containing 'participants.tsv'), 'subject' (the
directory starting with 'sub-'), 'session' (the directory starting with
... |
381,963 | def service_execution(self, name=None, pk=None, scope=None, service=None, **kwargs):
_service_executions = self.service_executions(name=name, pk=pk, scope=scope, service=service, **kwargs)
if len(_service_executions) == 0:
raise NotFoundError("No service execution fits criteria")
... | Retrieve single KE-chain ServiceExecution.
Uses the same interface as the :func:`service_executions` method but returns only a single
pykechain :class:`models.ServiceExecution` instance.
If additional `keyword=value` arguments are provided, these are added to the request parameters. Please
... |
381,964 | def lookupGeoInfo(positions):
list_data=[]
oldlat=0
oldlon=0
d={}
for pos in positions:
diff_lat=abs(float(pos[])-oldlat)
diff_lon=abs(float(pos[])-oldlon)
if (diff_lat>POS_THRESHOLD_DEG) or\
(diff_lon>POS_THRESHOLD_DEG):
d=lookup_by_latlo... | Looks up lat/lon info with goole given a list
of positions as parsed by parsePositionFile.
Returns google results in form of dicionary |
381,965 | def do_check_freshness(self, hosts, services, timeperiods, macromodulations, checkmodulations,
checks, when):
now = when
cls = self.__class__
if not self.in_checking and self.freshness_threshold and not self.freshness_expired:
... | Check freshness and schedule a check now if necessary.
This function is called by the scheduler if Alignak is configured to check the freshness.
It is called for hosts that have the freshness check enabled if they are only
passively checked.
It is called for services that have the fre... |
381,966 | def add_path_part(url, regex=PATH_PART):
formatter = string.Formatter()
url_var_template = "(?P<{var_name}>{regex})"
for part in formatter.parse(url):
string_part, var_name, _, _ = part
if string_part:
yield string_part
if var_name:
yield url_var_templat... | replace the variables in a url template with regex named groups
:param url: string of a url template
:param regex: regex of the named group
:returns: regex |
381,967 | def p_generate_block(self, p):
p[0] = Block(p[2], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | generate_block : BEGIN generate_items END |
381,968 | def add_axes_and_nodes(self):
for i, (group, nodelist) in enumerate(self.nodes.items()):
theta = self.group_theta(group)
if self.has_edge_within_group(group):
theta = theta - self.minor_angle
self.plot_nodes(nodelist, theta, group)
... | Adds the axes (i.e. 2 or 3 axes, not to be confused with matplotlib
axes) and the nodes that belong to each axis. |
381,969 | def setOrientation( self, orientation ):
super(XToolBar, self).setOrientation(orientation)
self.refreshButton() | Sets the orientation for this toolbar to the inputed value, and \
updates the contents margins and collapse button based on the vaule.
:param orientation | <Qt.Orientation> |
381,970 | def change_state_id(self, state_id=None):
if state_id is None:
state_id = state_id_generator(used_state_ids=[self.state_id])
if not self.is_root_state and not self.is_root_state_of_library:
used_ids = list(self.parent.states.keys()) + [self.parent.state_id, self.state_id... | Changes the id of the state to a new id
If no state_id is passed as parameter, a new state id is generated.
:param str state_id: The new state id of the state
:return: |
381,971 | def create_bracket_parameter_id(brackets_id, brackets_curr_decay, increased_id=-1):
if increased_id == -1:
increased_id = str(create_parameter_id())
params_id = .join([str(brackets_id),
str(brackets_curr_decay),
increased_id])
return params_id | Create a full id for a specific bracket's hyperparameter configuration
Parameters
----------
brackets_id: int
brackets id
brackets_curr_decay:
brackets curr decay
increased_id: int
increased id
Returns
-------
int
params id |
381,972 | def remove_group(self, process_id, wit_ref_name, page_id, section_id, group_id):
route_values = {}
if process_id is not None:
route_values[] = self._serialize.url(, process_id, )
if wit_ref_name is not None:
route_values[] = self._serialize.url(, wit_ref_name, )
... | RemoveGroup.
[Preview API] Removes a group from the work item form.
:param str process_id: The ID of the process
:param str wit_ref_name: The reference name of the work item type
:param str page_id: The ID of the page the group is in
:param str section_id: The ID of the section t... |
381,973 | def from_ordinal(cls, ordinal):
if ordinal == 0:
return ZeroDate
if ordinal >= 736695:
year = 2018
month = 1
day = int(ordinal - 736694)
elif ordinal >= 719163:
year = 1970
month = 1
day = int(... | Return the :class:`.Date` that corresponds to the proleptic
Gregorian ordinal, where ``0001-01-01`` has ordinal 1 and
``9999-12-31`` has ordinal 3,652,059. Values outside of this
range trigger a :exc:`ValueError`. The corresponding instance
method for the reverse date-to-ordinal transfor... |
381,974 | def get_default_property_values(self, classname):
schema_element = self.get_element_by_class_name(classname)
result = {
property_name: property_descriptor.default
for property_name, property_descriptor in six.iteritems(schema_element.properties)
}
if sc... | Return a dict with default values for all properties declared on this class. |
381,975 | def at_css(self, css, timeout = DEFAULT_AT_TIMEOUT, **kw):
return self.wait_for_safe(lambda: super(WaitMixin, self).at_css(css),
timeout = timeout,
**kw) | Returns the first node matching the given CSSv3 expression or ``None``
if a timeout occurs. |
381,976 | def plot(graph, show_x_axis=True,
head=None, tail=None, label_length=4, padding=0,
height=2, show_min_max=True, show_data_range=True,
show_title=True):
def __plot(graph):
def get_padding_str(label, value):
padding_str =
... | show_x_axis: Display X axis
head: Show first [head:] elements
tail: Show last [-tail:] elements
padding: Padding size between columns (default 0)
height: Override graph height
label_length: Force X axis label string size, may truncate label
show_min_max: Display Min and M... |
381,977 | def multi_future(
children: Union[List[_Yieldable], Dict[Any, _Yieldable]],
quiet_exceptions: "Union[Type[Exception], Tuple[Type[Exception], ...]]" = (),
) -> "Union[Future[List], Future[Dict]]":
if isinstance(children, dict):
keys = list(children.keys())
children_seq = children.value... | Wait for multiple asynchronous futures in parallel.
Since Tornado 6.0, this function is exactly the same as `multi`.
.. versionadded:: 4.0
.. versionchanged:: 4.2
If multiple ``Futures`` fail, any exceptions after the first (which is
raised) will be logged. Added the ``quiet_exceptions``
... |
381,978 | def _ComputeHash( key, seed = 0x0 ):
def fmix( h ):
h ^= h >> 16
h = ( h * 0x85ebca6b ) & 0xFFFFFFFF
h ^= h >> 13
h = ( h * 0xc2b2ae35 ) & 0xFFFFFFFF
h ^= h >> 16
return h
length = len( key )
nblocks = int( lengt... | Computes the hash of the value passed using MurmurHash3 algorithm with the seed value. |
381,979 | def interfaces():
results = []
if not sys.platform.startswith("win"):
net_if_addrs = psutil.net_if_addrs()
for interface in sorted(net_if_addrs.keys()):
ip_address = ""
mac_address = ""
netmask = ""
interface_type = "ethernet"
for... | Gets the network interfaces on this server.
:returns: list of network interfaces |
381,980 | def get(self, default=None):
if not self.__cancelled and self.__state == Job.SUCCESS:
return self.__result
else:
return default | Get the result of the Job, or return *default* if the job is not finished
or errored. This function will never explicitly raise an exception. Note
that the *default* value is also returned if the job was cancelled.
# Arguments
default (any): The value to return when the result can not be obtained. |
381,981 | def SecurityCheck(self, func, request, *args, **kwargs):
try:
auth_header = request.headers.get("Authorization", "")
if not auth_header.startswith(self.BEARER_PREFIX):
raise ValueError("JWT token is missing.")
token = auth_header[len(self.BEARER_PREFIX):]
auth_domain = config... | Check if access should be allowed for the request. |
381,982 | def unpack(data):
length = struct.unpack(, data[0:HEADER_SIZE])
return length[0], data[HEADER_SIZE:] | return length, content |
381,983 | def _get_address_override(endpoint_type=PUBLIC):
override_key = ADDRESS_MAP[endpoint_type][]
addr_override = config(override_key)
if not addr_override:
return None
else:
return addr_override.format(service_name=service_name()) | Returns any address overrides that the user has defined based on the
endpoint type.
Note: this function allows for the service name to be inserted into the
address if the user specifies {service_name}.somehost.org.
:param endpoint_type: the type of endpoint to retrieve the override
... |
381,984 | def get_siblings_treepos(self, treepos):
parent_pos = self.get_parent_treepos(treepos)
siblings_treepos = []
if parent_pos is not None:
for child_treepos in self.get_children_treepos(parent_pos):
if child_treepos != treepos:
siblings_tree... | Given a treeposition, return the treepositions of its siblings. |
381,985 | def sents(self, fileids=None) -> Generator[str, str, None]:
for para in self.paras(fileids):
sentences = self._sent_tokenizer.tokenize(para)
for sentence in sentences:
yield sentence | :param fileids:
:return: A generator of sentences |
381,986 | def any_hook(*hook_patterns):
current_hook = hookenv.hook_name()
i_pat = re.compile(r)
hook_patterns = _expand_replacements(i_pat, hookenv.role_and_interface_to_relations, hook_patterns)
c_pat = re.compile(r)
hook_patterns = _expand_replacements(c_pat, lambda v: v.split(), hook_patt... | Assert that the currently executing hook matches one of the given patterns.
Each pattern will match one or more hooks, and can use the following
special syntax:
* ``db-relation-{joined,changed}`` can be used to match multiple hooks
(in this case, ``db-relation-joined`` and ``db-relation-changed`... |
381,987 | def enqueue(trg_queue, item_f, *args, **kwargs):
/my/file
return venqueue(trg_queue, item_f, args, **kwargs) | Enqueue the contents of a file, or file-like object, file-descriptor or
the contents of a file at an address (e.g. '/my/file') queue with
arbitrary arguments, enqueue is to venqueue what printf is to vprintf |
381,988 | def load_data(self, path):
path = pathlib.Path(path).resolve()
meta = {}
with path.open() as fd:
while True:
line = fd.readline().strip()
if line.startswith("
line = line.strip("
var, val = line... | Load isoelastics from a text file
The text file is loaded with `numpy.loadtxt` and must have
three columns, representing the two data columns and the
elastic modulus with units defined in `definitions.py`.
The file header must have a section defining meta data of the
content lik... |
381,989 | def filter_seq(seq):
if seq.res:
return None
n = nt.Factors(seq.factors)
guide, s, t = aq.canonical_form(n)
seq.guide = guide
cls = aq.get_class(guide=guide)
num_larges = seq.factors.count()
upper_bound_tau = cls - num_larges - len(t)
if cls < 2 or upper_bo... | Examines unreserved sequences to see if they are prone to mutation. This
currently ignores solely-power-of-2 guides with b > 3 |
381,990 | def dbg_repr(self, max_display=10):
s = repr(self) + "\n"
if len(self.chosen_statements) > max_display:
s += "%d SimRuns in program slice, displaying %d.\n" % (len(self.chosen_statements), max_display)
else:
s += "%d SimRuns in program slice.\n" % len(self.chos... | Debugging output of this slice.
:param max_display: The maximum number of SimRun slices to show.
:return: A string representation. |
381,991 | def search_shell(self):
with self._lock:
if self._shell is not None:
return
reference = self._context.get_service_reference(SERVICE_SHELL)
if reference is not None:
self.set_shell(reference) | Looks for a shell service |
381,992 | def origin(self):
if not self.is_absolute():
raise ValueError("URL should be absolute")
if not self._val.scheme:
raise ValueError("URL should have scheme")
v = self._val
netloc = self._make_netloc(None, None, v.hostname, v.port, encode=False)
... | Return an URL with scheme, host and port parts only.
user, password, path, query and fragment are removed. |
381,993 | def mpraw_as_np(shape, dtype):
sz = int(np.product(shape))
csz = sz * np.dtype(dtype).itemsize
raw = mp.RawArray(, csz)
return np.frombuffer(raw, dtype=dtype, count=sz).reshape(shape) | Construct a numpy array of the specified shape and dtype for which the
underlying storage is a multiprocessing RawArray in shared memory.
Parameters
----------
shape : tuple
Shape of numpy array
dtype : data-type
Data type of array
Returns
-------
arr : ndarray
Numpy ... |
381,994 | def tablib_export_action(modeladmin, request, queryset, file_type="xls"):
dataset = SimpleDataset(queryset, headers=None)
filename = .format(
smart_str(modeladmin.model._meta.verbose_name_plural), file_type)
response_kwargs = {
: get_content_type(file_type)
}
response = HttpR... | Allow the user to download the current filtered list of items
:param file_type:
One of the formats supported by tablib (e.g. "xls", "csv", "html",
etc.) |
381,995 | def execute_prepared(self, prepared_statement, multi_row_parameters):
self._check_closed()
parameters = prepared_statement.prepare_parameters(multi_row_parameters)
while parameters:
request = RequestMessage.new(
self.connection,
Req... | :param prepared_statement: A PreparedStatement instance
:param multi_row_parameters: A list/tuple containing list/tuples of parameters (for multiple rows) |
381,996 | def reset_network(message):
for command in settings.RESTART_NETWORK:
try:
subprocess.check_call(command)
except:
pass
print(message) | Resets the users network to make changes take effect |
381,997 | def conn_has_method(conn, method_name):
if method_name in dir(conn):
return True
log.error(%s\, method_name)
return False | Find if the provided connection object has a specific method |
381,998 | def with_trailing_args(self, *arguments):
new_command = copy.deepcopy(self)
new_command._trailing_args = [str(arg) for arg in arguments]
return new_command | Return new Command object that will be run with specified
trailing arguments. |
381,999 | def _link_package_versions(self, link, search):
platform = get_platform()
version = None
if link.egg_fragment:
egg_info = link.egg_fragment
ext = link.ext
else:
egg_info, ext = link.splitext()
if not ext:
self._log... | Return an InstallationCandidate or None |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.