Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
337,200 | def logdir(self):
run_name = ncluster_globals.get_run_for_task(self)
logdir = ncluster_globals.get_logdir(run_name)
if logdir:
return logdir
if ncluster_globals.is_chief(self, run_name):
chief = self
else:
chief = ncluster_globals.get_chief(run_name)
chief.setup_lo... | Returns logging directory, creating one if necessary. See "Logdir" section of design doc on naming convention. |
337,201 | def frame(self):
frames = self._spinner[]
frame = frames[self._frame_index]
if self._color:
frame = colored_frame(frame, self._color)
self._frame_index += 1
self._frame_index = self._frame_index % len(frames)
text_frame = self.text_frame()
... | Builds and returns the frame to be rendered
Returns
-------
self |
337,202 | def newton_update(x, a, c, step=1.0):
return x - step*np.linalg.inv(hessian(x, a)).dot(gradient(x, a, c)) | Given a value of x, return a better x
using newton-gauss |
337,203 | def convert_sbcs_model(old_model, alphabet):
char_to_order = {i: order
for i, order in enumerate(old_model[])}
pos_ratio = old_model[]
keep_ascii_letters = old_model[]
curr_model = SingleByteCharSetModel(charset_name=old_model[],
la... | Create a SingleByteCharSetModel object representing the charset. |
337,204 | def compilearg(self):
if isinstance(self.value,list):
value = self.delimiter.join(self.value)
else:
value = self.value
if value.find(" ") >= 0:
value = + value +
else:
return str(value)
return self.paramflag + ... | This method compiles the parameter into syntax that can be used on the shell, such as -paramflag=value |
337,205 | def alterar(self, id_net_type, name):
if not is_valid_int_param(id_net_type):
raise InvalidParameterError(
u)
url = + str(id_net_type) +
net_type_map = dict()
net_type_map[] = name
code, xml = self.submit({: net_type_map}, , url)
... | Edit network type by its identifier.
:param id_net_type: Network type identifier.
:param name: Network type name.
:return: None
:raise InvalidParameterError: Network type identifier and/or name is(are) none or invalid.
:raise TipoRedeNaoExisteError: Network type does not exist... |
337,206 | def section(msg):
logger.info(bar(msg, position=))
try:
yield
except SectionError as e:
logger.error(e)
logger.info(bar(, position=))
except SectionWarning as e:
logger.warning(e)
logger.info(bar(, position=))
else:
logger.info(bar(, position=)) | Context manager that prints a top bar to stderr upon entering and a bottom
bar upon exiting. The caption of the top bar is specified by `msg`. The
caption of the bottom bar is '...done!' if the context manager exits
successfully. If a SectionError or SectionWarning is raised inside of the
context man... |
337,207 | def _match_dialog(self, query, dialogues=None):
if dialogues is None:
dialogues = self._dialogues
if query in dialogues:
response = dialogues[query]
logger.debug( % repr(response))
return response | Tries to match in dialogues
:param query: message tuple
:type query: Tuple[bytes]
:return: response if found or None
:rtype: Tuple[bytes] | None |
337,208 | def gmb(a, b):
return np.exp(np.log(a).mean() - np.log(b).mean()) | Geometric mean bias |
337,209 | def FromString(cls, string_rep):
rep = str(string_rep)
parts = rep.split()
if len(parts) > 3:
raise ArgumentError("Too many whitespace separated parts of stream designator", input_string=string_rep)
elif len(parts) == 3 and parts[0] != u:
raise Argument... | Create a DataStream from a string representation.
The format for stream designators when encoded as strings is:
[system] (buffered|unbuffered|constant|input|count|output) <integer>
Args:
string_rep (str): The string representation to turn into a
DataStream |
337,210 | def from_object(self, instance: Union[object, str]) -> None:
if isinstance(instance, str):
try:
path, config = instance.rsplit(, 1)
except ValueError:
path = instance
instance = importlib.import_module(path)
else:
... | Load the configuration from a Python object.
This can be used to reference modules or objects within
modules for example,
.. code-block:: python
app.config.from_object('module')
app.config.from_object('module.instance')
from module import instance
... |
337,211 | def apply(self, axes="gca"):
if axes == "gca": axes = _pylab.gca()
self.reset()
lines = axes.get_lines()
for l in lines:
l.set_color(self.get_line_color(1))
l.set_mfc(self.get_face_color(1))
l.set_marker(self.get_marker(1))
l.set... | Applies the style cycle to the lines in the axes specified |
337,212 | def is_outdated(self, infile, outfile):
if super(BrowserifyCompiler, self).is_outdated(infile, outfile):
return True
if super(BrowserifyCompiler, self).is_outdated(dep_file, outfile):
if self.verbose:
print(... | Check if the input file is outdated.
The difficulty with the default implementation is that any file that is
`require`d from the entry-point file will not trigger a recompile if it
is modified. This overloaded version of the method corrects this by generating
a list of all requi... |
337,213 | def neg_loglik(self, beta):
lmda, Y, ___, theta = self._model(beta)
return -np.sum(logpdf(Y, self.latent_variables.z_list[-3].prior.transform(beta[-3]),
loc=theta, scale=np.exp(lmda/2.0),
skewness = self.latent_variables.z_list[-4].prior.transform(beta[-4]))) | Creates the negative log-likelihood of the model
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
Returns
----------
The negative logliklihood of the model |
337,214 | def publish_message(self,
exchange,
routing_key,
properties,
body,
connection=None):
conn = self._publish_connection(connection)
self.logger.debug(, exchange,
... | Publish a message to RabbitMQ on the same channel the original
message was received on. If
`publisher confirmations <https://www.rabbitmq.com/confirms.html>`_
are enabled, the method will return a
:class:`~tornado.concurrent.Future` that will resolve a :class:`bool`
that indicate... |
337,215 | def fast(self):
if self.sorting == TraceSortingFormat.INLINE_SORTING:
return self.iline
elif self.sorting == TraceSortingFormat.CROSSLINE_SORTING:
return self.xline
else:
raise RuntimeError("Unknown sorting.") | Access the 'fast' dimension
This mode yields iline or xline mode, depending on which one is laid
out `faster`, i.e. the line with linear disk layout. Use this mode if
the inline/crossline distinction isn't as interesting as traversing in
a fast manner (typically when you want to apply a... |
337,216 | def negative_binomial(k=1, p=1, shape=_Null, dtype=_Null, ctx=None,
out=None, **kwargs):
return _random_helper(_internal._random_negative_binomial,
_internal._sample_negative_binomial,
[k, p], shape, dtype, ctx, out, kwargs) | Draw random samples from a negative binomial distribution.
Samples are distributed according to a negative binomial distribution
parametrized by *k* (limit of unsuccessful experiments) and *p* (failure
probability in each experiment). Samples will always be returned as a
floating point data type.
... |
337,217 | def extract(self, text):
_extracted = []
if text.strip() == "":
return _extracted
parsed_sentences = self._parse_text(text)
for s in parsed_sentences:
tokens = s.split()
new_np = []
for t in tokens:
w, tag, phrase, ... | Return a list of noun phrases (strings) for a body of text.
:param str text: A string. |
337,218 | def serializable(obj: Any, on_filter: Callable[[Any, str], bool] = None) -> Any:
def _serializable(parent_obj: Any, obj: Any,
on_filter: Callable[[Any, str], bool]) -> Any:
if obj is None:
return obj
elif isinstance(obj, IntFlag):
... | Ensures the specified object is serializable, converting if necessary.
:param obj: the object to use.
:param on_filter: optional function that can be used to filter which
properties on the object will be included.
:return value representing the object, which is serializable. |
337,219 | def _preprocess_yml(path):
with open(path) as f:
tmp_yaml = f.read()
return re.sub(r"unicode", "str", tmp_yaml) | Dynamically create PY3 version of the file by re-writing 'unicode' to 'str'. |
337,220 | def _update_projection_matrix(self):
ff = 1./np.tan(np.radians(self.fov_y / 2.))
zn, zf = self.z_near, self.z_far
persp_mat = np.array([[ff/self.aspect, 0., 0., 0.],
[ 0., ff, 0., ... | np.array: The Camera's Projection Matrix. Will be an Orthographic matrix if ortho_mode is set to True. |
337,221 | def update(self, y, exogenous=None, maxiter=None, **kwargs):
check_is_fitted(self, )
model_res = self.arima_res_
y = c1d(check_array(y, ensure_2d=False, force_all_finite=False,
copy=True, dtype=DTYPE))
n_samples = y.shape[0]
... | Update the model fit with additional observed endog/exog values.
Updating an ARIMA adds new observations to the model, updating the
MLE of the parameters accordingly by performing several new iterations
(``maxiter``) from the existing model parameters.
Parameters
----------
... |
337,222 | def _get_adjtime_timezone():
adjtime_file =
if os.path.exists(adjtime_file):
cmd = [, , , adjtime_file]
return __salt__[](cmd, python_shell=False)
elif os.path.exists():
raise CommandExecutionError(
+ adjtime_file
)
else:
return None | Return the timezone in /etc/adjtime of the system clock |
337,223 | def build_debian(config, os_versions, os_type=):
def build_pkg(config, os_type, os_version):
result = _build_package(config, os_type, os_version)
if not result.succeeded:
print(result.cli)
raise DebianError(result, os_type, os_version, frame=gfi(cf()))
error = 0
... | build_debian
Builds for a specific debian operating system with os version
specified. By default, it will use os_type='ubuntu' |
337,224 | def _set_step(self, step):
new_tab = self.tab_widget.currentIndex() + step
assert new_tab < self.tab_widget.count() and new_tab >= 0
if new_tab == self.tab_widget.count()-1:
try:
self.table_widget.open_data(self._get_plain_text(),
... | Proceed to a given step |
337,225 | def extract_version(txt):
words = txt.replace(, ).split()
version = None
for x in reversed(words):
if len(x) > 2:
if x[0].lower() == :
x = x[1:]
if in x and x[0].isdigit():
version = x
break
return version | This function tries to extract the version from the help text of any
program. |
337,226 | def create_database(self, name, owner=None):
statement = ddl.CreateDatabase(name, owner=owner)
self._execute(statement) | Create a new MapD database
Parameters
----------
name : string
Database name |
337,227 | def tokenize(self, text: str, customize=True, disable=[]) -> List[Token]:
if not self.keep_multi_space:
text = re.sub(, , text)
tokens = self.nlp(text, disable=disable)
if customize:
tokens = [self.custom_token(a_token) for a_token in tokens]
... | Tokenize the given text, returning a list of tokens. Type token: class spacy.tokens.Token
Args:
text (string):
Returns: [tokens] |
337,228 | def read_data(self, **kwargs):
trigger_id = kwargs.get()
trigger = Pushbullet.objects.get(trigger_id=trigger_id)
date_triggered = kwargs.get()
data = list()
pushes = self.pushb.get_pushes()
for p in pushes:
title =
created = arrow.get(p.g... | get the data from the service
as the pushbullet service does not have any date
in its API linked to the note,
add the triggered date to the dict data
thus the service will be triggered when data will be found
:param kwargs: contain keyword args : trigger_id a... |
337,229 | def sort_common_members():
filename = PREFIX +
sorted_json_data = {}
json_data = read_json(filename)
all_keys = []
for key, value in json_data.items():
all_keys.append(key)
sorted_keys = sorted(all_keys)
for key in sorted_keys:
if len(json_data[key]) > 0:
... | Sorts the keys and members |
337,230 | def expect(self, value, message=, operator=):
if operator not in self.valid_operators:
raise ValueError()
self.items.put(ChainItem(value, self.expect, message, operator=operator))
return self | Add an 'assertion' action to the steps. This will evaluate the return value of the last 'do' step and
compare it to the value passed here using the specified operator.
Checks that the first function will return 2
>>> AssertionChain().do(lambda: 1 + 1, 'add 1 + 1').expect(2)
This will c... |
337,231 | def report_urls(impact_function):
report_path = impact_function.impact_report.output_folder
standard_report_metadata = impact_function.report_metadata
def retrieve_components(tags):
products = []
for report_metadata in standard_report_metadata:
products += (report_... | Get report urls for all report generated by the ImpactFunction.
:param impact_function: The ImpactFunction
:type impact_function: ImpactFunction
:return: Dictionary of all generated report urls by its product type
eg:
{
'html_product_tag': {
'action-... |
337,232 | def _start_nodes_parallel(self, nodes, max_thread_pool_size):
thread_pool_size = min(len(nodes), max_thread_pool_size)
thread_pool = Pool(processes=thread_pool_size)
log.debug("Created pool of %d threads", thread_pool_size)
keep_running = True
... | Start the nodes using a pool of multiprocessing threads for speed-up.
Return set of nodes that were actually started. |
337,233 | def import_boundary_event_to_graph(diagram_graph, process_id, process_attributes, element):
element_id = element.getAttribute(consts.Consts.id)
boundary_event_definitions = {, , ,
, , }
BpmnDiagramGraphImport.import_flow_node_to_graph(diagram_graph,... | Adds to graph the new element that represents BPMN boundary event.
Boundary event inherits sequence of eventDefinitionRef from Event type.
Separate methods for each event type are required since each of them has different variants
(Message, Error, Signal etc.).
:param diagram_graph: Net... |
337,234 | def _locations_mirror(x):
if hasattr(x, ):
if hasattr(x[0], ):
return list(map(_locations_mirror, x))
else:
return list(x[::-1])
else:
return x | Mirrors the points in a list-of-list-of-...-of-list-of-points.
For example:
>>> _locations_mirror([[[1, 2], [3, 4]], [5, 6], [7, 8]])
[[[2, 1], [4, 3]], [6, 5], [8, 7]] |
337,235 | def replace_contractions_with_full_words_and_replace_numbers_with_digits(
text = None,
remove_articles = True
):
words = text.split()
text_translated = ""
for word in words:
if remove_articles and word in ["a", "an", "the"]:
continue
contractions_expan... | This function replaces contractions with full words and replaces numbers
with digits in specified text. There is the option to remove articles. |
337,236 | def beta(returns, factor_returns, risk_free=0.0, out=None):
if not (isinstance(returns, np.ndarray) and
isinstance(factor_returns, np.ndarray)):
returns, factor_returns = _aligned_series(returns, factor_returns)
return beta_aligned(
returns,
factor_returns,
risk... | Calculates beta.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns : pd.Series
Daily noncumulative returns of the factor to which beta is
computed. Usua... |
337,237 | def reflection(normal, origin=(0, 0, 0)):
n = np.array(normal, dtype=float) / np.linalg.norm(normal)
u, v, w = n
translation = np.eye(4)
translation[0:3, 3] = -np.array(origin)
xx = 1 - 2 * u ** 2
yy = 1 - 2 * v ** 2
zz = 1 - 2 * w ** 2
... | Returns reflection symmetry operation.
Args:
normal (3x1 array): Vector of the normal to the plane of
reflection.
origin (3x1 array): A point in which the mirror plane passes
through.
Returns:
SymmOp for the reflection about the plane |
337,238 | def _get_data_from_empty_list(source, fields=, first_row=0, count=-1, schema=None):
fields = get_field_list(fields, schema)
return {: _get_cols(fields, schema), : []}, 0 | Helper function for _get_data that handles empty lists. |
337,239 | def _get_ids_from_label(self, label):
keys = self.list_keys()
results = []
for key in keys:
if key[] == label:
results.append(key[])
return results | Return sshkey IDs which match the given label. |
337,240 | def evaluate(dataset):
with tf.Graph().as_default():
images, labels = image_processing.inputs(dataset)
num_classes = dataset.num_classes() + 1
logits, _ = inception.inference(images, num_classes)
top_1_op = tf.nn.in_top_k(logits, labels, 1)
top_5_op = tf.nn.in_t... | Evaluate model on Dataset for a number of steps. |
337,241 | def find(self, path, all=False):
bits = path.split()
dirs_to_serve = [, settings.SYSTEMJS_OUTPUT_DIR]
if not bits or bits[0] not in dirs_to_serve:
return []
return super(SystemFinder, self).find(path, all=all) | Only allow lookups for jspm_packages.
# TODO: figure out the 'jspm_packages' dir from packag.json. |
337,242 | def int_global_to_local_start(self, index, axis=0):
if index >= self.__mask[axis].stop-self.__halos[1][axis]:
return None
if index < self.__mask[axis].start:
return 0
return index-self.__mask[axis].start | Calculate local index from global index from start_index
:param index: global index as integer
:param axis: current axis to process
:return: |
337,243 | def compile_authors(authors):
author_list = []
for person in authors:
author_list.append({: person[] + ", " + person[]})
return author_list | Compiles authors "Last, First" into a single list
:param list authors: Raw author data retrieved from doi.org
:return list: Author objects |
337,244 | def connect(self):
if not (self.consumer_key and self.consumer_secret and self.access_token
and self.access_token_secret):
raise RuntimeError("MissingKeys")
if self.client:
log.info("closing existing http session")
self.client.close()
... | Sets up the HTTP session to talk to Twitter. If one is active it is
closed and another one is opened. |
337,245 | def aligned_array(size, dtype, align=64):
n = size * dtype.itemsize
empty = np.empty(n + (align - 1), dtype=np.uint8)
data_align = empty.ctypes.data % align
offset = 0 if data_align == 0 else (align - data_align)
output = empty[offset:offset + n].view(dtype)
assert len(output) == size, le... | Returns an array of a given size that is 64-byte aligned.
The returned array can be efficiently copied into GPU memory by TensorFlow. |
337,246 | def _add_result(self, dict_entry, entry, dt, start_time):
time_entry = {}
time_entry[] = dt
time_entry[] = start_time
dict_entry[entry] = time_entry | Adds a result to the dictionary.
Args:
dict_entry: main dict to add entry
entry: slot for this entry (likely an integer)
dt: the timing for the entry
start_time: when the entry started unix time float |
337,247 | def set(self, k, v, obj=):
if k not in self:
self[k] = dict()
self[k][self.objname(obj)] = v
return v | obj is a Sheet instance, or a Sheet [sub]class. obj="override" means override all; obj="default" means last resort. |
337,248 | def from_code(
cls,
schema,
code,
uptodate=None,
extra_namespace=None,
):
if isinstance(code, string_types):
filename = "<document>"
code = compile(code, filename, "exec")
namespace = {"__file__": code.co_filen... | Creates a GraphQLDocument object from compiled code and the globals. This
is used by the loaders and schema to create a document object. |
337,249 | def HSV_to_RGB(cobj, target_rgb, *args, **kwargs):
H = cobj.hsv_h
S = cobj.hsv_s
V = cobj.hsv_v
h_floored = int(math.floor(H))
h_sub_i = int(h_floored / 60) % 6
var_f = (H / 60.0) - (h_floored // 60)
var_p = V * (1.0 - S)
var_q = V * (1.0 - var_f * S)
var_t = V * (1.0 - (1.0 - ... | HSV to RGB conversion.
H values are in degrees and are 0 to 360.
S values are a percentage, 0.0 to 1.0.
V values are a percentage, 0.0 to 1.0. |
337,250 | def Point(pos=(0, 0, 0), r=12, c="red", alpha=1):
if len(pos) == 2:
pos = (pos[0], pos[1], 0)
actor = Points([pos], r, c, alpha)
return actor | Create a simple point actor. |
337,251 | def putBlock(self, blockcontent, migration=False):
try:
self.logger.debug("insert configuration")
configList = self.insertOutputModuleConfig(
blockcontent[], migration)
self.logger.debug("insert dataset")... | Insert the data in sereral steps and commit when each step finishes or rollback if there is a problem. |
337,252 | def batchseeds(args):
from jcvi.formats.pdf import cat
xargs = args[1:]
p = OptionParser(batchseeds.__doc__)
opts, args, iopts = add_seeds_options(p, args)
if len(args) != 1:
sys.exit(not p.print_help())
folder, = args
folder = folder.rstrip()
outdir = folder + "-debug"
... | %prog batchseeds folder
Extract seed metrics for each image in a directory. |
337,253 | def update_user(self, user_name, new_user_name=None, new_path=None):
params = { : user_name}
if new_user_name:
params[] = new_user_name
if new_path:
params[] = new_path
return self.get_response(, params) | Updates name and/or path of the specified user.
:type user_name: string
:param user_name: The name of the user
:type new_user_name: string
:param new_user_name: If provided, the username of the user will be
changed to this username.
:type new_path... |
337,254 | def update_email_template(self, template_id, template_dict):
return self._create_put_request(
resource=EMAIL_TEMPLATES,
billomat_id=template_id,
send_data=template_dict
) | Updates a emailtemplate
:param template_id: the template id
:param template_dict: dict
:return: dict |
337,255 | def create_apppool(name):
ret = {: name,
: {},
: None,
: }
current_apppools = __salt__[]()
if name in current_apppools:
ret[] = .format(name)
ret[] = True
elif __opts__[]:
ret[] = .format(name)
ret[] = {: None,
... | Create an IIS application pool.
.. note:
This function only validates against the application pool name, and will return
True even if the application pool already exists with a different configuration.
It will not modify the configuration of an existing application pool.
:param str na... |
337,256 | def lambda_max(self):
return ((const.b_wien.value / self.temperature) * u.m).to(u.AA).value | Peak wavelength in Angstrom when the curve is expressed as
power density. |
337,257 | def index_tuple(self,tables_dict,index,is_set):
"helper for rowget/rowset"
if not self.aonly_resolved: raise RuntimeError()
with tables_dict.tempkeys():
tables_dict.update(self.aonly)
else: return (tindex,)
else: return (tindex,tables_dict[tname].lookup(index.attr).index)
... | helper for rowget/rowset |
337,258 | def form_valid(self, form):
startDate = form.cleaned_data[]
endDate = form.cleaned_data[]
startTime = form.cleaned_data[]
endTime = form.cleaned_data[]
instructor = form.cleaned_data[]
interval_minutes = getConstant()
this_date = startDate
while... | Create slots and return success message. |
337,259 | def _unwrap(variable_parts: VariablePartsType):
curr_parts = variable_parts
var_any = []
while curr_parts:
curr_parts, (var_type, part) = curr_parts
if var_type == Routes._VAR_ANY_NODE:
var_any.append(part)
continue
if var_type == Routes._VAR_ANY_BREAK... | Yield URL parts. The given parts are usually in reverse order. |
337,260 | def add_callback(self, callback: _Callable, *args, **kwargs) -> None:
self.loop.add_callback(callback, *args, **kwargs) | Add a callback to the event loop |
337,261 | def create_choice_model(data,
alt_id_col,
obs_id_col,
choice_col,
specification,
model_type,
intercept_ref_pos=None,
shape_ref_pos=None,
... | Parameters
----------
data : string or pandas dataframe.
If `data` is a string, it should be an absolute or relative path to
a CSV file containing the long format data for this choice model.
Note long format has one row per available alternative for each
observation. If `data` is... |
337,262 | def make_request(method, url, params=None, data=None, headers=None, auth=None):
http = httplib2.Http(
ca_certs=get_cert_file(),
)
if auth is not None:
http.add_credentials(auth[0], auth[1])
if params is not None:
enc_params = urlencode(params, doseq=True)
if urlpa... | Make an HTTP request.
:param str method: "POST", "GET", "PUT" or "DELETE"
:param str url: URL to process request.
:param dict params: Params to add to the URL.
:param dict data: Form data.
:param dict headers: Headers to request.
:param tuple auth: Username and token. |
337,263 | def from_dict(cls, d):
structure = SlabEntry.from_dict(d["structure"])
energy = SlabEntry.from_dict(d["energy"])
miller_index = d["miller_index"]
label = d["label"]
coverage = d["coverage"]
adsorbates = d["adsorbates"]
clean_entry = d["clean_entry"] = se... | Returns a SlabEntry by reading in an dictionary |
337,264 | def get_jsapi_card_params(self, card_ticket, card_type, **kwargs):
card_signature_dict = {
: card_type,
: kwargs.get(, random_string()),
: card_ticket,
: self.appid,
: kwargs.get(, str(int(time.time()))),
}
list_before_sign = s... | 参数意义见微信文档地址:http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html
:param card_ticket: 用于卡券的微信 api_ticket
:param card_type:
:param kwargs: 非必须参数:noncestr, timestamp, code, openid, fixed_begintimestamp, outer_str
:return: 包含调用jssdk所有所需参数的 dict |
337,265 | def _load_common_err_data(self, common_err_data_path):
common_err = {}
try:
with open(common_err_data_path, newline=) as f:
reader = csv.reader(f, delimiter=)
for line in reader:
if len(line) != 2:
continue
try:
assert line[0] not in common_err
assert all([char in self.ip... | Loads and returns the {bad: good} dictionary stored in the common
errors data file. Note that the dict's keys are single characters while
the values do not have to be. The method also asserts that all the
values are valid IPA strings. |
337,266 | def get_logging_session_for_log(self, log_id, proxy):
if not self.supports_logging():
raise errors.Unimplemented()
return sessions.LoggingSession(log_id, proxy, self._runtime) | Gets the ``OsidSession`` associated with the logging service for the given log.
arg: log_id (osid.id.Id): the ``Id`` of the ``Log``
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.logging.LoggingSession) - a ``LoggingSession``
raise: NotFound - no ``Log`` found by the given ... |
337,267 | def cmd_config_set(key, value):
habucfg = loadcfg(environment=False)
habucfg[key.upper()] = value
with Path().expanduser().open() as f:
f.write(json.dumps(habucfg, indent=4, sort_keys=True)) | Set VALUE to the config KEY.
Note: By default, KEY is converted to uppercase.
Example:
\b
$ habu.config.set DNS_SERVER 8.8.8.8 |
337,268 | def get_series_all_releases(self, series_id):
url = "%s/series/observations?series_id=%s&realtime_start=%s&realtime_end=%s" % (self.root_url,
series_id,
... | Get all data for a Fred series id including first releases and all revisions. This returns a DataFrame
with three columns: 'date', 'realtime_start', and 'value'. For instance, the US GDP for Q4 2013 was first released
to be 17102.5 on 2014-01-30, and then revised to 17080.7 on 2014-02-28, and then revis... |
337,269 | def _init_client(self, from_archive=False):
return StackExchangeClient(self.site, self.tagged, self.api_token, self.max_questions,
self.archive, from_archive) | Init client |
337,270 | def add(self, task_cls):
registry_tag = task_cls.__registry_tag__
if registry_tag not in self.__registry.keys():
self.__registry[registry_tag] = [task_cls]
elif self.__multiple_tasks_per_tag__ is True:
self.__registry[registry_tag].append(task_cls)
else:
raise RuntimeError() | Add task to this storage. Depends on :attr:`.WTaskRegistryStorage.__multiple_tasks_per_tag__`
tasks with the same __registry_tag__ can be treated as error.
:param task_cls: task to add
:return: None |
337,271 | def summary(self):
if not self.bug.resolution:
return self.bug.summary
if (self.bug.resolution.lower() in self.parent.resolutions
or "all" in self.parent.resolutions):
return "{0} [{1}]".format(
self.bug.summary, self.bug.resolution.lower(... | Bug summary including resolution if enabled |
337,272 | def get_postadres_by_subadres(self, subadres):
try:
id = subadres.id
except AttributeError:
id = subadres
def creator():
res = crab_gateway_request(
self.client, , id
)
if res == None:
raise Gat... | Get the `postadres` for a :class:`Subadres`.
:param subadres: The :class:`Subadres` for which the \
`postadres` is wanted. OR A subadres id.
:rtype: A :class:`str`. |
337,273 | def _get_char_offsets(self, char_offsets):
if char_offsets:
char_offsets = char_offsets
char_offsets.append(len(self.text))
else:
char_offsets = np.zeros(len(self.tokens) + 1)
for i, tok in enumerate(self.tokens):
... | Store or calculate char_offsets, adding the offset of the doc end |
337,274 | def middleware(self, middleware_or_request):
if callable(middleware_or_request):
return self.register_middleware(middleware_or_request)
else:
return partial(
self.register_middleware, attach_to=middleware_or_request
) | Decorate and register middleware to be called before a request.
Can either be called as *@app.middleware* or
*@app.middleware('request')*
:param: middleware_or_request: Optional parameter to use for
identifying which type of middleware is being registered. |
337,275 | def _to_dict(self):
_dict = {}
if hasattr(self, ) and self.text is not None:
_dict[] = self.text
if hasattr(self, ) and self.created is not None:
_dict[] = datetime_to_string(self.created)
if hasattr(self, ) and self.updated is not None:
_dict... | Return a json dictionary representing this model. |
337,276 | def node_as_tree(
self,
node,
visitor=lambda self, node: self._default_node_visitor(node),
children=lambda self, node, visitor, children: self._default_node_children(
node, visitor, children
),
):
tree = visitor(self, node)
tree.update(chi... | Visits a :class:`CTENode` `node` and delegates to the (optional)
`visitor` callback, as well as the (optional) `children` callback,
in order to generate a dictionary representation of the node along
with its children nodes.
:param node: the :class:`CTENode` for which to ... |
337,277 | def synchronise_device_state(self, device_state, authentication_headers):
payload = {
: device_state,
: {
: {
: ,
: ,
:
},
: {}
}
}
multipart... | Synchronizing the component states with AVS
Components state must be synchronised with AVS after establishing the
downchannel stream in order to create a persistent connection with AVS.
Note that currently this function is paying lip-service synchronising
the device state: the device s... |
337,278 | def particles(category=None):
filepath = os.path.join(os.path.dirname(__file__), )
with open(filepath) as f:
try:
particles = json.load(f)
except ValueError as e:
log.error(.format(filepath))
else:
if category:
if category in parti... | Returns a dict containing old greek particles grouped by category. |
337,279 | def _valuePivot(self, session, mapTable, contaminant, replaceParaFile):
indexes = session.query(MTIndex). \
join(MTValue.index). \
filter(MTValue.mapTable == mapTable). \
filter(MTValue.contaminant == contaminant). \
order_by(MTIndex.index). \
... | This function retrieves the values of a mapping table from the database and pivots them into the format that is
required by the mapping table file. This function returns a list of strings that can be printed to the file
directly. |
337,280 | def one(cls, path=, index=0):
url = urljoin(cls._meta.base_url, path)
pq_items = cls._get_items(url=url, **cls._meta._pyquery_kwargs)
item = pq_items.eq(index)
if not item:
raise ItemDoesNotExist("%s not found" % cls.__name__)
return cls(item=item) | Return ocurrence (the first one, unless specified) of the item. |
337,281 | def computeUniquePointsSensed(nCols, nPoints, s):
if nCols == 1:
return min(s, nPoints)
elif nCols < nPoints:
q = float(nCols) / nPoints
unique = min(int(round(( 1.0 - math.pow(1.0 - q, s)) * nPoints)),
nPoints)
return unique
else:
return nPoints | If a network with nCols columns senses an object s times, how many
unique points are actually sensed? The number is generally <= nCols * s
because features may be repeated across sensations. |
337,282 | def append_with(self, obj, **properties):
for prop, val in properties.items():
val = self.serialize(val)
self._meta.setdefault(prop, {}).setdefault(val, []).append(obj)
self.append(obj) | Add an item to the dictionary with the given metadata properties |
337,283 | def done(self, on_success=None, on_failure=None):
if on_success is not None:
if self._state == :
self._callbacks.append(on_success)
elif self._state == :
on_success(self.value)
if on_failure is not None:
if self._state == :
... | Attaches some callbacks to the promise and returns the promise. |
337,284 | def dump(obj, fp, *args, **kwargs):
kwargs[] = object2dict
json.dump(obj, fp, *args, **kwargs) | Serialize a object to a file object.
Basic Usage:
>>> import simplekit.objson
>>> from cStringIO import StringIO
>>> obj = {'name': 'wendy'}
>>> io = StringIO()
>>> simplekit.objson.dump(obj, io)
>>> print io.getvalue()
:param obj: a object which need to dump
:param fp: a instance... |
337,285 | def semidefinite_relaxation(edm_missing, lamda, W=None, print_out=False, **kwargs):
from .algorithms import reconstruct_mds
def kappa(gram):
n = len(gram)
e = np.ones(n)
return np.outer(np.diag(gram), e) + np.outer(e, np.diag(gram).T) - 2 * gram
def kappa_cvx(gram, n):
... | Complete and denoise EDM using semidefinite relaxation.
Returns solution to the relaxation of the following problem:
D = argmin || W * (D - edm_missing) ||
s.t. D is EDM
where edm_missing is measured matrix, W is a weight matrix, and * is pointwise multiplication.
Refer to paper "Eu... |
337,286 | def zincrby(self, name, value, amount=1):
with self.pipe as pipe:
return pipe.zincrby(self.redis_key(name),
value=self.valueparse.encode(value),
amount=amount) | Increment the score of the item by `value`
:param name: str the name of the redis key
:param value:
:param amount:
:return: |
337,287 | def update_topic(self, topic_id, title, content):
xml = self.api.req(API_GROUP_UPDATE_TOPIC % topic_id, , data={
: self.api.ck(),
: title,
: content,
: ,
})
return not xml.url.startswith(API_GROUP_UPDATE_TOPIC % topic_id) | 更新话题
:param topic_id: 话题ID
:param title: 标题
:param content: 内容
:return: bool |
337,288 | def insert(self, context):
status_code, msg = self.__endpoint.post(
"/resources/connector-connection-pool",
data={
"id": self.__name,
"resourceAdapterName": self.__res_adapter_name,
"connectiondefinitionname": self.__conn_def_name,
"property": props_value(self.__props)
}
)
self.__... | Create connection pool.
:param resort.engine.execution.Context context:
Current execution context. |
337,289 | def set_data(self, pos=None, color=None):
if pos is not None:
pos = float(pos)
xy = self._pos
if self._is_vertical:
xy[0, 0] = pos
xy[0, 1] = -1
xy[1, 0] = pos
xy[1, 1] = 1
else:
... | Set the data
Parameters
----------
pos : float
Position of the line along the axis.
color : list, tuple, or array
The color to use when drawing the line. If an array is given, it
must be of shape (1, 4) and provide one rgba color per vertex. |
337,290 | def _get_securitygroupname_id(securitygroupname_list):
securitygroupid_set = set()
if not isinstance(securitygroupname_list, list):
securitygroupname_list = [securitygroupname_list]
params = {: }
for sg in aws.query(params, location=get_location(),
provider=get_provi... | Returns the SecurityGroupId of a SecurityGroupName to use |
337,291 | def bool_attribute(element, attribute, default=True):
attribute_value = element.get(attribute)
if attribute_value:
return attribute_value ==
return default | Returns the bool value of an attribute, or a default if it's not defined
:param element: The XML Element object
:type element: etree._Element
:param attribute: The name of the attribute to evaluate
:type attribute: str
:param default: The default boolean to return if the attribute is not defined... |
337,292 | def getSets(self):
sets = lock_and_call(
lambda: self._impl.getSets(),
self._lock
)
return EntityMap(sets, Set) | Get all the sets declared. |
337,293 | def interpolate(self, factor, minGlyph, maxGlyph,
round=True, suppressError=True):
factor = normalizers.normalizeInterpolationFactor(factor)
if not isinstance(minGlyph, BaseGlyph):
raise TypeError(("Interpolation to an instance of %r can not be "
... | Interpolate the contents of this glyph at location ``factor``
in a linear interpolation between ``minGlyph`` and ``maxGlyph``.
>>> glyph.interpolate(0.5, otherGlyph1, otherGlyph2)
``factor`` may be a :ref:`type-int-float` or a tuple containing
two :ref:`type-int-float` values repre... |
337,294 | def batch_shape(self):
batch_shape = tf.TensorShape([])
for param in self.parameters:
batch_shape = tf.broadcast_static_shape(
batch_shape, param.prior.batch_shape)
return batch_shape | Static batch shape of models represented by this component.
Returns:
batch_shape: A `tf.TensorShape` giving the broadcast batch shape of
all model parameters. This should match the batch shape of
derived state space models, i.e.,
`self.make_state_space_model(...).batch_shape`. It may ... |
337,295 | def delete(self, url, **kwargs):
check_type(url, basestring, may_be_none=False)
erc = kwargs.pop(, EXPECTED_RESPONSE_CODE[])
self.request(, url, erc, **kwargs) | Sends a DELETE request.
Args:
url(basestring): The URL of the API endpoint.
**kwargs:
erc(int): The expected (success) response code for the request.
others: Passed on to the requests package.
Raises:
ApiError: If anything other than ... |
337,296 | def _iter_valid_subtotal_dicts(self):
for insertion_dict in self._insertion_dicts:
if not isinstance(insertion_dict, dict):
continue
if insertion_dict.get("function") != "subtotal":
continue
if ... | Generate each insertion dict that represents a valid subtotal. |
337,297 | def partitioned_probability(self, direction, partition):
repertoire = self.partitioned_repertoire(direction, partition)
return self.state_probability(direction, repertoire, partition.purview) | Compute the probability of the mechanism over the purview in
the partition. |
337,298 | def path(self, which=None):
if which in (
,
,
,
,
,
,
,
):
return .format(
super(Organization, self).path(which=),
which
)
... | Extend ``nailgun.entity_mixins.Entity.path``.
The format of the returned path depends on the value of ``which``:
download_debug_certificate
/organizations/<id>/download_debug_certificate
subscriptions
/organizations/<id>/subscriptions
subscriptions/upload
... |
337,299 | def get_taker_metadata(self):
metadata = dict(self._mdata[])
metadata.update({: self._my_map[]})
return Metadata(**metadata) | Gets the metadata for a resource to manually set which resource will be taking the assessment.
return: (osid.Metadata) - metadata for the resource
*compliance: mandatory -- This method must be implemented.* |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.