Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
346,000 | def convert_concat(node, **kwargs):
name, input_nodes, attrs = get_inputs(node, kwargs)
axis = int(attrs.get("dim", 1))
concat_node = onnx.helper.make_node(
"Concat",
input_nodes,
[name],
axis=axis,
name=name
)
return [concat_node] | Map MXNet's Concat operator attributes to onnx's Concat operator
and return the created node. |
346,001 | def _init_dut(self):
if self.auto_dut:
self.dut = None
return
dut_port = settings.DUT_DEVICE[0]
dut = OpenThreadController(dut_port)
self.dut = dut | Initialize the DUT.
DUT will be restarted. and openthread will started. |
346,002 | def _serialize(self, entity, pb, prefix=, parent_repeated=False,
projection=None):
values = self._get_base_value_unwrapped_as_list(entity)
name = prefix + self._name
if projection and name not in projection:
return
if self._indexed:
create_prop = lambda: pb.add_propert... | Internal helper to serialize this property to a protocol buffer.
Subclasses may override this method.
Args:
entity: The entity, a Model (subclass) instance.
pb: The protocol buffer, an EntityProto instance.
prefix: Optional name prefix used for StructuredProperty
(if present, must en... |
346,003 | def head(self, uuid):
url = "%(base)s/%(uuid)s" % {
: self.local_base_url,
: uuid
}
return self.core.head(url) | Get one thread. |
346,004 | def age(self):
created = self.created()
age_secs = time() - created
age_mins = 0 if (age_secs < 60) else (age_secs / 60)
age_hours = 0 if (age_secs < 3600) else (age_mins / 60)
age_days = 0 if (age_secs < 86400) else (age_hours / 24... | Get the age of the PID file. |
346,005 | def dirpaths(self):
parts = self.parts()
result = [DotPath(parts[0] or )]
for name in parts[1:]:
result.append(result[-1] / name)
return result | Split the dirname into individual directory names
An absolute path starts with an empty string, a relative path does not
>>> p = DotPath(u'/path/to/x.py')
>>> p.paths == p.dirpaths()
True |
346,006 | def _CallFunc(self, t):
self._dispatch(t.node)
self._write("(")
comma = False
for e in t.args:
if comma: self._write(", ")
else: comma = True
self._dispatch(e)
if t.star_args:
if comma: self._write(", ")
else: c... | Function call. |
346,007 | def parse_cores(cores, pm, default):
cores = cores or getattr(pm, "cores", default)
return int(cores) | Framework to finalize number of cores for an operation.
Some calls to a function may directly provide a desired number of cores,
others may not. Similarly, some pipeline managers may define a cores count
while others will not. This utility provides a single via which the
count of cores to use for an op... |
346,008 | def validate_slackpost(attr, value):
if attr in ("channel", "credentials"):
if not isinstance(value, str):
raise InvalidMessageInputError("SlackPost", attr, value, "string")
elif attr in ("attachments"):
check_valid("SlackPost", attr, value, validus.isurl, "url") | SlackPost input validator function. |
346,009 | async def _asyncio_send(loop, req, *, timeout=10, max_redirects=10):
if not any(h.lower() == for h in req.headers):
req = req.with_headers({: _ASYNCIO_USER_AGENT})
url = urllib.parse.urlsplit(
req.url + + urllib.parse.urlencode(req.params))
open_ = partial(asyncio.open_connection, url... | A rudimentary HTTP client using :mod:`asyncio` |
346,010 | def abbreviate(s, maxlength=25):
assert maxlength >= 4
skip = False
abbrv = None
i = 0
for j, c in enumerate(s):
if c == :
skip = True
elif skip:
if c == :
skip = False
else:
i += 1
if i == maxlength - 1:
... | Color-aware abbreviator |
346,011 | def bag_to_dataframe(bag_name, include=None, exclude=None, parse_header=False, seconds=False):
yaml_info = get_bag_info(bag_name)
bag_topics = get_topics(yaml_info)
bag_topics = prune_topics(bag_topics, include, exclude)
length = get_length(bag_topics, yaml_info)
msgs_to_read, msg_type = g... | Read in a rosbag file and create a pandas data frame that
is indexed by the time the message was recorded in the bag.
:bag_name: String name for the bag file
:include: None, String, or List Topics to include in the dataframe
if None all topics added, if string it is used as regular
... |
346,012 | def bb_range(data, period, std=2.0):
catch_errors.check_for_period_error(data, period)
period = int(period)
bb_range = (upper_bollinger_band(data, period, std) -
lower_bollinger_band(data, period, std)
)
return bb_range | Range.
Formula:
bb_range = u_bb - l_bb |
346,013 | def get_subscription(self, topic_name, subscription_name):
_validate_not_none(, topic_name)
_validate_not_none(, subscription_name)
request = HTTPRequest()
request.method =
request.host = self._get_host()
request.path = + \
_str(topic_name) + + _st... | Gets an existing subscription.
topic_name:
Name of the topic.
subscription_name:
Name of the subscription. |
346,014 | def update_data(self, data):
oldn_dim = self.n_dim
if data.dtype != np.float32:
print("Warning: data was not float32. A 32-bit copy was made")
self._data = np.float32(data)
else:
self._data = data
self.n_vectors, self.n_dim = data.shape
... | Change the data set in the Somoclu object. It is useful when the
data is updated and the training should continue on the new data.
:param data: The training data.
:type data: 2D numpy.array of float32. |
346,015 | def files_size(fs0, fs1, files):
for file_meta in files[]:
file_meta[] = fs0.stat(file_meta[])[]
for file_meta in files[] + files[]:
file_meta[] = fs1.stat(file_meta[])[]
return files | Gets the file size of the given files. |
346,016 | def get(self, key):
return SyncMapItemContext(
self._version,
service_sid=self._solution[],
map_sid=self._solution[],
key=key,
) | Constructs a SyncMapItemContext
:param key: The key
:returns: twilio.rest.preview.sync.service.sync_map.sync_map_item.SyncMapItemContext
:rtype: twilio.rest.preview.sync.service.sync_map.sync_map_item.SyncMapItemContext |
346,017 | def validateMasterArgument(self, master_arg):
if master_arg[:5] == "http:":
raise usage.UsageError("<master> is not a URL - do not use URL")
if ":" not in master_arg:
master = master_arg
port = 9989
else:
master, port = master_arg.split("... | Parse the <master> argument.
@param master_arg: the <master> argument to parse
@return: tuple of master's host and port
@raise UsageError: on errors parsing the argument |
346,018 | def volt_sensor_send(self, r2Type, voltage, reading2, force_mavlink1=False):
return self.send(self.volt_sensor_encode(r2Type, voltage, reading2), force_mavlink1=force_mavlink1) | Transmits the readings from the voltage and current sensors
r2Type : It is the value of reading 2: 0 - Current, 1 - Foreward Sonar, 2 - Back Sonar, 3 - RPM (uint8_t)
voltage : Voltage in uS of PWM. 0 uS = 0V, 20 uS = 21.5V (uint16_t)
... |
346,019 | def get_times():
if f.root.stopped:
return copy.deepcopy(f.root.times)
else:
t = timer()
times = collapse.collapse_times()
f.root.self_cut += timer() - t
return times | Produce a deepcopy of the current timing data (no risk of interference
with active timing or other operaitons).
Returns:
Times: gtimer timing data structure object. |
346,020 | def add_batchnorm(self, name, channels, gamma, beta,
mean = None, variance = None,
input_name = , output_name = ,
compute_mean_var = False,
instance_normalization = False, epsilon = 1e-5):
spec = self.spec
... | Add a Batch Normalization layer. Batch Normalization operation is
defined as:
`y = gamma * (x - mean) / sqrt(variance + epsilon) + beta`
Parameters
----------
name: str
The name of this layer.
channels: int
Number of channels of the input blob.
... |
346,021 | def diff(self):
latest = self.latest
current = NetJsonParser(self.json())
return diff(current, latest) | shortcut to netdiff.diff |
346,022 | async def report_winner(self, winner: Participant, scores_csv: str):
await self._report(scores_csv, winner._id) | report scores and give a winner
|methcoro|
Args:
winner: :class:Participant instance
scores_csv: Comma separated set/game scores with player 1 score first (e.g. "1-3,3-0,3-2")
Raises:
ValueError: scores_csv has a wrong format
APIException |
346,023 | def general_neg_loglik(self, beta):
mu, Y = self._model(beta)
parm = np.array([self.latent_variables.z_list[k].prior.transform(beta[k]) for k in range(beta.shape[0])])
model_scale, model_shape, model_skewness = self._get_scale_and_shape(parm)
return self.family.ne... | Calculates the negative log-likelihood of the model
Parameters
----------
beta : np.ndarray
Contains untransformed starting values for latent variables
Returns
----------
The negative logliklihood of the model |
346,024 | def validateNum(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, _numType=,
min=None, max=None, lessThan=None, greaterThan=None, excMsg=None):
_validateGenericParameters(blank=blank, strip=strip, allowlistRegexes=None, blocklistRegexes=blocklistRegexes)
_v... | Raises ValidationException if value is not a float or int.
Returns value, so it can be used inline in an expression:
print(2 + validateNum(your_number))
Note that since int() and float() ignore leading or trailing whitespace
when converting a string to a number, so does this validateNum().
*... |
346,025 | def check_target_integrity(key, values, meta=False, all=False, parent=None):
if all:
if not values:
print("Warning: target is empty")
return True
errmes = "target is not allowed to be missing a help message\n"
if meta:
if "help" not i... | Checks the integrity of a specific target. Gets called
multiple times from check_integrity()
Args:
The target name
The dictionary values of that target
A boolean representing whether it is a meta-target
A boolean representing whether it is the "all" target
A string repre... |
346,026 | def return_resource(self, resource, status=200, statusMessage="OK"):
self.set_status(status, statusMessage)
self.write(json.loads(json_util.dumps(resource))) | Return a resource response
:param str resource: The JSON String representation of a resource response
:param int status: Status code to use
:param str statusMessage: The message to use in the error response |
346,027 | def apply(self,word,ctx=None):
chars = get_letters(word)
flag = True
reason = None
prev_letter = None
for char in chars:
if prev_letter == char:
flag = False
break
prev_letter = char
if not flag:
... | ignore ctx information right now |
346,028 | def get_from_cache(key):
try:
value = cache.get(key)
return json.loads(value), key if value else None
except Exception as e:
return None | Args:
key (str):
Return:
(dict): from json string |
346,029 | def QueueMessages(self, messages):
for message in messages:
self._in_queue.put(message, block=True) | Push messages to the input queue. |
346,030 | def get_fqhostname():
fqdn = None
try:
addrinfo = socket.getaddrinfo(
socket.gethostname(), 0, socket.AF_UNSPEC, socket.SOCK_STREAM,
socket.SOL_TCP, socket.AI_CANONNAME
)
for info in addrinfo:
if len(inf... | Returns the fully qualified hostname |
346,031 | def strip_lock_quality(self, idx):
idx = Radiotap.align(idx, 2)
lock_quality, = struct.unpack_from(, self._rtap, idx)
return idx + 2, lock_quality | strip(2 byte) lock quality
:idx: int
:return: int
idx
:return: int |
346,032 | def _excel_date_number(self, date_1904):
date, label = datetime.date, self._label
date_ = date(label.year, label.month, label.day)
epoch = date(1904, 1, 1) if date_1904 else date(1899, 12, 31)
delta = date_ - epoch
excel_day_number = delta.days
... | Return an integer representing the date label of this category as the
number of days since January 1, 1900 (or 1904 if date_1904 is
|True|). |
346,033 | def set(self, path, value):
_log.debug(
"ZK: Setting {path} to {value}".format(path=path, value=value)
)
return self.zk.set(path, value) | Sets and returns new data for the specified node. |
346,034 | def sendPinnedLocation(
self, location, message=None, thread_id=None, thread_type=None
):
self._sendLocation(
location=location,
current=False,
message=message,
thread_id=thread_id,
thread_type=thread_type,
) | Sends a given location to a thread as a pinned location
:param location: Location to send
:param message: Additional message
:param thread_id: User/Group ID to send to. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_threads`
:type location: models.LocationAttachmen... |
346,035 | def handle_return(self, frame, return_value):
self.obj_cache[id(return_value)] = return_value
self.extra_vars[] = return_value
fun = frame.f_code.co_name
log.info( % (fun, return_value))
init = % dump({
: ,
: self.safe_better_repr(return_value)
... | This function is called when a return trap is set here. |
346,036 | def _forward_mode(self, *args):
X: np.ndarray
dX: np.ndarray
X, dX = self.f._forward_mode(*args)
Y: np.ndarray
dY: np.ndarray
Y, dY = self.g._forward_mode(*args)
val = self.func(X,Y)
diff = self.deriv(X,Y)
return... | Forward mode differentiation for a constant |
346,037 | def luid(self):
p_elem = self.parent_pipeline.get()
if not p_elem:
p_elem = self.parent_pipeline[]
s_elem = self.name
if not s_elem:
s_elem = self.uid
return % (p_elem, s_elem) | Unique ID of the current stage (fully qualified).
example:
>>> stage.luid
pipe.0001.stage.0004
:getter: Returns the fully qualified uid of the current stage
:type: String |
346,038 | def addLogger(self, logger, level=logging.INFO):
if isinstance(logger, logging.Logger):
logger = logger.name
if logger in self._loggers:
return
if logger == :
_log = logging.getLogger()
else:
_... | Adds the inputed logger to the list of loggers that are being tracked
with this widget.
:param logger | <logging.Logger> || <str>
level | <logging.LEVEL> |
346,039 | def read_internal_strain_tensor(self):
search = []
def internal_strain_start(results, match):
results.internal_strain_ion = int(match.group(1)) - 1
results.internal_strain_tensor.append(np.zeros((3, 6)))
search.append([r"INTERNAL STRAIN TENSOR FOR ION\s+(\d+)\s... | Reads the internal strain tensor and populates self.internal_strain_tensor with an array of voigt notation
tensors for each site. |
346,040 | def get_wf_from_path(self, path):
with open(path) as fp:
content = fp.read()
return [(os.path.basename(os.path.splitext(path)[0]), content), ] | load xml from given path
Args:
path: diagram path
Returns: |
346,041 | def taskotron_task(config, message, task=None):
if not taskotron_result_new(config, message):
return False
if not task:
return False
tasks = [item.strip().lower() for item in task.split()]
return message[][].get().lower() in tasks | Particular taskotron task
With this rule, you can limit messages to only those of particular
`taskotron <https://taskotron.fedoraproject.org/>`_ task.
You can specify several tasks by separating them with a comma ',',
i.e.: ``dist.depcheck,dist.rpmlint``. |
346,042 | def get_pixel_size_from_nside(nside):
order = int(np.log2(nside))
if order < 0 or order > 13:
raise ValueError( % order)
return HPX_ORDER_TO_PIXSIZE[order] | Returns an estimate of the pixel size from the HEALPix nside coordinate
This just uses a lookup table to provide a nice round number for each
HEALPix order. |
346,043 | def wait_for_property(self, name, cond=lambda val: val, level_sensitive=True):
sema = threading.Semaphore(value=0)
def observer(name, val):
if cond(val):
sema.release()
self.observe_property(name, observer)
if not level_sensitive or not cond(getattr(s... | Waits until ``cond`` evaluates to a truthy value on the named property. This can be used to wait for
properties such as ``idle_active`` indicating the player is done with regular playback and just idling around |
346,044 | def set_package_releases(self, project_name, versions):
self.packages[project_name] = sorted(versions, reverse=True) | Storage package information in ``self.packages``
Args:
project_name (str): This will be used as a the key in the
dictionary.
versions (list): List of ``str`` representing the available
versions of a project. |
346,045 | def cc(self):
_years = range(self._start, self._end+1)
try:
return list(zip(_years, [d.get() for d in self._citeInfoMatrix[]]))
except AttributeError:
return list(zip(_years, [0]*len(_years))) | List of tuples of yearly number of citations
for specified years. |
346,046 | def add_virtual_columns_distance_from_parallax(self, parallax="parallax", distance_name="distance", parallax_uncertainty=None, uncertainty_postfix="_uncertainty"):
import astropy.units
unit = self.unit(parallax)
distance_expression = "1/%s" % (parallax)
self.ucds[distance_n... | Convert parallax to distance (i.e. 1/parallax)
:param parallax: expression for the parallax, e.g. "parallax"
:param distance_name: name for the virtual column of the distance, e.g. "distance"
:param parallax_uncertainty: expression for the uncertainty on the parallax, e.g. "parallax_error"
:param uncer... |
346,047 | def _download_source_sciobj_bytes_to_store(self, client, pid):
if d1_gmn.app.sciobj_store.is_existing_sciobj_file(pid):
self._events.log_and_count(
"Skipped download of existing sciobj bytes", .format(pid)
)
else:
with d1_gmn.app.sciobj_store.... | Args:
client: pid: |
346,048 | def main():
print("Generating research notes...")
if os.path.exists(fname):
os.remove(fname)
append_rst()
append_rst()
append_rst()
append_rst()
append_rst(open(, ).read())
append_rst(res_core_data_mthd1.get_method())
append_rst(res_core_data_mthd2.get_method... | This generates the research document based on the results of
the various programs and includes RST imports for introduction
and summary |
346,049 | def scan(self):
for iteration in range(0, self.global_iterations):
if self.stop_run.is_set():
break
logging.info("Global tuning step %d / %d", iteration + 1, self.global_iterations)
self.set_scan_parameters(global_step=self.scan_parameters.glob... | Metascript that calls other scripts to tune the FE.
Parameters
----------
cfg_name : string
Name of the config to be created. This config holds the tuning results.
target_threshold : int
The target threshold value in PlsrDAC.
target_charge : int
... |
346,050 | def get_withdrawal(self, withdrawal_id, **params):
return self.api_client.get_withdrawal(self.id, withdrawal_id, **params) | https://developers.coinbase.com/api/v2#show-a-withdrawal |
346,051 | def close(self):
if self.fd:
os.close(self.fd)
self.fd = None | Close the i2c connection. |
346,052 | def char2features(sentence, i):
char = sentence[i]
length = len(sentence)
features = [
.format(char.lower()),
.format(char.isupper()),
.format(char.isnumeric()),
]
if i == 0:
features.extend([])
if i > 0:
char = sentence[i - 1]
features.ext... | Returns features of char at position `i` in given sentence
When it possible, result features list also includes features for 2 characters
ahead and behind current position (like bigrams, or something like it)
Currently, used features is:
1. lower-cased value of character
2. result of calling `charac... |
346,053 | def replace_headers(source_pdb_content, target_pdb_content):
s = PDB(source_pdb_content)
t = PDB(target_pdb_content)
source_headers = []
for l in s.lines:
if l[:6].strip() in non_header_records:
break
else:
source_headers.... | Takes the headers from source_pdb_content and adds them to target_pdb_content, removing any headers that
target_pdb_content had.
Only the content up to the first structural line are taken from source_pdb_content and only the content from
the first structural line in target_pdb_content a... |
346,054 | def validate_card_issue_modes(issue_mode: int, cards: list) -> list:
supported_mask = 63
if not bool(issue_mode & supported_mask):
return []
for i in [1 << x for x in range(len(IssueMode))]:
if bool(i & issue_mode):
try:
parser_fn = cast(
... | validate cards against deck_issue modes |
346,055 | def next(self):
if self.iter_next():
self.data, self.label = self._read()
return {self.data_name : self.data[0][1],
self.label_name : self.label[0][1]}
else:
raise StopIteration | return one dict which contains "data" and "label" |
346,056 | def _getSortKey(self, planet):
value = eval(+self._planetProperty)
if self.unit is not None:
try:
value = value.rescale(self.unit)
except AttributeError:
pass
return _sortValueIntoGroup(self._allowedKeys[:-1], self._... | Takes a planet and turns it into a key to be sorted by
:param planet:
:return: |
346,057 | def database_to_csv(self, path, orderby=):
tableinfo = self.get_table_info()
stats_master = database_to_json(self.dbcon_master, tableinfo)
stats_partial = database_to_json(self.dbcon_part, tableinfo)
with open(path, ) as f:
csvfile = csv.writer(f)
csvfile... | Create a CSV file for the latest usage stats.
:param path: path to output CSV file
:param dbconn_master: master database connection
:param dbconn_part: partial database connection
:param tableinfo: table header information |
346,058 | def post(self, path=None, method=, **options):
return self.route(path, method, **options) | Equals :meth:`route` with a ``POST`` method parameter. |
346,059 | def db_optimize(name,
table=None,
**connection_args):
*
ret = []
if table is None:
tables = db_tables(name, **connection_args)
for table in tables:
log.info(%s\%s\, name, table)
ret.append(__optimize_table(name, table, **connection... | Optimizes the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_optimize dbname |
346,060 | def _vcf_info(start, end, mate_id, info=None):
out = "SVTYPE=BND;MATEID={mate};IMPRECISE;CIPOS=0,{size}".format(
mate=mate_id, size=end-start)
if info is not None:
extra_info = ";".join("{0}={1}".format(k, v) for k, v in info.iteritems())
out = "{0};{1}".format(out, extra_info)
... | Return breakend information line with mate and imprecise location. |
346,061 | def ParseMultiple(self, result_dicts):
for result_dict in result_dicts:
result = result_dict.ToDict()
winvolume = rdf_client_fs.WindowsVolume(
drive_letter=result.get("DeviceID"),
drive_type=result.get("DriveType"))
try:
size = int(result.get("Size"))
except... | Parse the WMI packages output. |
346,062 | def download(self, filename, representation, overwrite=False):
download(self.input, filename, representation, overwrite, self.resolvers, self.get3d, **self.kwargs) | Download the resolved structure as a file.
:param string filename: File path to save to
:param string representation: Desired output representation
:param bool overwrite: (Optional) Whether to allow overwriting of an existing file |
346,063 | def _capitalize_first_letter(word):
if word[0].isalpha():
if word[0].isupper():
return "[" + word[0].swapcase() + word[0] + "]" + word[1:]
else:
return "[" + word[0] + word[0].swapcase() + "]" + word[1:]
return word | Return a regex pattern with the first letter.
Accepts both lowercase and uppercase. |
346,064 | def find_file(path, tgt_env=, **kwargs):
fnd = {: ,
: }
if os.path.isabs(path) or tgt_env not in envs():
return fnd
dest = os.path.join(__opts__[], , tgt_env, path)
hashes_glob = os.path.join(__opts__[],
,
tgt_env,
... | Find the first file to match the path and ref, read the file out of hg
and send the path to the newly cached file |
346,065 | def new_action(self, method=, **kwargs):
if method not in self.methods:
raise TypeError(.format(method, self.methods))
return Action(self, method, **kwargs) | Create a new Action linked to this endpoint with the given args. |
346,066 | def from_array(array):
if array is None or not array:
return None
assert_type_or_raise(array, dict, parameter_name="array")
data = {}
data[] = User.from_array(array.get())
data[] = u(array.get())
data[] = int(array.get()) if array.get() is n... | Deserialize a new ChatMember from a given dictionary.
:return: new ChatMember instance.
:rtype: ChatMember |
346,067 | def post_save_stop(sender, instance, **kwargs):
from multigtfs.models.trip import Trip
trip_ids = instance.stoptime_set.filter(
trip__shape=None).values_list(, flat=True).distinct()
for trip in Trip.objects.filter(id__in=trip_ids):
trip.update_geometry() | Update related objects when the Stop is updated |
346,068 | def isin(elems, line):
found = False
for e in elems:
if e in line.lower():
found = True
break
return found | Check if an element from a list is in a string.
:type elems: list
:type line: str |
346,069 | def markPairs(self, labeled_pairs):
self._checkTrainingPairs(labeled_pairs)
for label, examples in labeled_pairs.items():
self.training_pairs[label].extend(examples)
if self.active_learner:
examples, y = flatten_training(labeled_pairs)
self.active_l... | Argument :
labeled_pairs -- A dictionary with two keys, `match` and `distinct`
the values are lists that can contain pairs of records |
346,070 | def _src_path_stats(self, src_path):
violation_lines = self.violation_lines(src_path)
violations = sorted(self._diff_violations()[src_path].violations)
if self.INCLUDE_SNIPPETS:
try:
snippets = Snippet.load_snippets_html(src_path,... | Return a dict of statistics for the source file at `src_path`. |
346,071 | def flatten4d3d(x):
xshape = shape_list(x)
result = tf.reshape(x, [xshape[0], xshape[1] * xshape[2], xshape[3]])
return result | Flatten a 4d-tensor into a 3d-tensor by joining width and height. |
346,072 | def graph_simplify(G):
spurs = []
path_nodes = []
for k, d in G.degree().iteritems():
if d == 1:
spurs.append(k)
elif d == 2:
path_nodes.append(k)
logging.debug("Remove {0} spurs.".format(len(spurs)))
G.remove_nodes_from(spurs)
SG = G.subgraph(path_... | Simplify big graphs: remove spurs and contract unique paths. |
346,073 | def get_user_by_id(bridge_id, include_course_summary=True):
url = author_id_url(bridge_id) + "?%s" % CUSTOM_FIELD
if include_course_summary:
url = "%s&%s" % (url, COURSE_SUMMARY)
resp = get_resource(url)
return _process_json_resp_data(resp) | :param bridge_id: integer
Return a list of BridgeUsers objects with custom fields |
346,074 | def get_model(client, model_id):
from google.cloud import bigquery
model = client.get_model(model_id)
full_model_id = "{}.{}.{}".format(model.project, model.dataset_id, model.model_id)
friendly_name = model.friendly_name
print(
"Got model with friendly_nam... | Sample ID: go/samples-tracker/1510 |
346,075 | def _syndic_return(self, load):
loads = load.get()
if not isinstance(loads, list):
loads = [load]
for load in loads:
if any(key not in load for key in (, , )):
continue
if load.get():
fstr = ... | Receive a syndic minion return and format it to look like returns from
individual minions.
:param dict load: The minion payload |
346,076 | def str_rjust(x, width, fillchar=):
sl = _to_string_sequence(x).pad(width, fillchar, True, False)
return column.ColumnStringArrow(sl.bytes, sl.indices, sl.length, sl.offset, string_sequence=sl) | Fills the left side of string samples with a specified character such that the strings are left-hand justified.
:param int width: The minimal width of the strings.
:param str fillchar: The character used for filling.
:returns: an expression containing the filled strings.
Example:
>>> import vaex
... |
346,077 | def setKstar(self,term_i,Ks):
assert Ks.shape[0]==self.N
self.vd.getTerm(term_i).getKcf().setK0cross(Ks) | Set the kernel for predictions
Args:
term_i: index of the term we are interested in
Ks: (TODO: is this the covariance between train and test or the covariance between test points?) |
346,078 | def logger(name=, pattern=,
date_format=, handler=logging.StreamHandler(sys.stdout)):
_logger = logging.getLogger(name)
_logger.setLevel(config.log_level())
if not _logger.handlers:
formatter = logging.Formatter(pattern, date_format)
handler.setFormatter(formatter)
ha... | Retrieves the logger instance associated to the given name.
:param name: The name of the logger instance.
:type name: str
:param pattern: The associated pattern.
:type pattern: str
:param date_format: The date format to be used in the pattern.
:type date_format: str
:param handler: The logg... |
346,079 | def add(self, item, header_flag=False, align=None):
if self._is_stringable(item) or self._is_qstring(item):
self.cells.append(Cell(item, header=header_flag, align=align))
elif isinstance(item, Cell):
self.cells.append(item)
elif isinstance(item, Image):
... | Add a Cell to the row
:param item: An element to add to the Cells can be list or Cell object.
:type item: basestring, QString, list, Cell
:param header_flag: Flag indicating it the item is a header or not.
:type header_flag: bool
:param align: Optional alignment qualifier for ... |
346,080 | def repo(
state, host, name, baseurl,
present=True, description=None, enabled=True, gpgcheck=True, gpgkey=None,
):
description = description or name
filename = .format(name)
repo = StringIO(repo)
yield files.put(state, host, repo, filename) | Add/remove/update yum repositories.
+ name: filename for the repo (in ``/etc/yum/repos.d/``)
+ baseurl: the baseurl of the repo
+ present: whether the ``.repo`` file should be present
+ description: optional verbose description
+ gpgcheck: whether set ``gpgcheck=1``
+ gpgkey: the URL to the gpg... |
346,081 | def data(self):
d = {}
for key in self._data:
if key == "plugins":
d[key] = self.plugins.data()
else:
try:
d[key] = getattr(self, key)
except AttributeError:
pass
return d | Returns the entire configuration as a dict.
Note that this will force all plugins to be loaded. |
346,082 | def frequency_axis(self):
return numpy.linspace(-self.sw / 2, self.sw / 2, self.np, endpoint=False) | Returns an array of frequencies in Hertz ranging from -sw/2 to
sw/2.
:return: an array of frequencies in Hertz ranging from -sw/2 to sw/2. |
346,083 | def parse_assessor_content(experiment_config):
if experiment_config.get():
if experiment_config[].get():
experiment_config[][] = experiment_config[][]
else:
validate_customized_file(experiment_config, ) | Validate whether assessor in experiment_config is valid |
346,084 | def fetch_options(self, element):
tfis = self.fetch_option_taskfileinfos(element)
return self.create_options_model(tfis), tfis | Fetch the options for possible files to
load replace etc for the given element.
Options from which to choose a file to load or replace.
The options are a :class:`jukeboxcore.gui.treemodel.TreeModel`
with :class:`jukeboxcore.filesys.TaskFileInfo` as leafes internal data.
I explic... |
346,085 | def restrict_chat_member(self, chat_id, user_id, until_date=None, can_send_messages=None, can_send_media_messages=None, can_send_other_messages=None, can_add_web_page_previews=None):
assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id")
assert_type_or_raise(user_... | Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate admin rights. Pass True for all boolean parameters to lift restrictions from a user. Returns True on success.
https://core.telegram.org/bots/api#restrictchatmemb... |
346,086 | def to_dict(self):
data = {
: self.name,
: self.video_id,
: self.time,
: self.force_stop,
: self.type,
: self.metadata}
for key in data.keys():
if data[key] == None:
data.pop(key)
return ... | Converts object into a dictionary. |
346,087 | def parse_units(units_str):
if not len(units_str):
return units_str, (None, None)
if units_str[-1] == :
units, lims = units_str.rsplit()
else:
units = units_str
lims =
lims = tuple([float(x) if x.strip() != else None for x in lims.strip().split()])
return ... | Extract and parse the units
Extract the bounds over which the expression is assumed to apply.
Parameters
----------
units_str
Returns
-------
Examples
--------
>>> parse_units('Widgets/Month [-10,10,1]')
('Widgets/Month', (-10,10,1))
>>> parse_units('Month [0,?]')
('M... |
346,088 | def get(self, request, *_args, **_kwargs):
access_token = self.access_token
scope_string = request.GET.get()
scope_request = scope_string.split() if scope_string else None
claims_string = request.GET.get()
claims_request = json.loads(claims_string) if claims_string el... | Respond to a UserInfo request.
Two optional query parameters are accepted, scope and claims.
See the references above for more details. |
346,089 | def analytic_false_alarm_probability(lspinfo,
times,
conservative_nfreq_eff=True,
peakvals=None,
inplace=True):
t actually work. Fix later.
The calculation follows... | This returns the analytic false alarm probabilities for periodogram
peak values.
FIXME: this doesn't actually work. Fix later.
The calculation follows that on page 3 of Zechmeister & Kurster (2009)::
FAP = 1 − [1 − Prob(z > z0)]**M
where::
M is the number of independent frequencies
... |
346,090 | def create_dir(path):
import sys
import errno
try:
os.makedirs(path)
except OSError as exc:
if exc.errno == errno.EEXIST:
if os.path.isdir(path):
pass
else:
raise
elif exc.errno == errno.EACCES:
sys.stde... | Creates a directory. Warns, if the directory can't be accessed. Passes,
if the directory already exists.
modified from http://stackoverflow.com/a/600612
Parameters
----------
path : str
path to the directory to be created |
346,091 | def create_host(url="local://local:6666/host"):
if url in util.hosts.keys():
raise HostError( +
)
else:
if not util.hosts:
util.main_host = Host(url)
util.hosts[url] = util.main_host
else:
util.hosts[url] = Host(url)
... | This is the main function to create a new Host to which you can
spawn actors. It will be set by default at local address if no
parameter *url* is given, which would result in remote
incomunication between hosts. This function shuould be called once
for execution or after callig :meth:`~.shutdown` to the... |
346,092 | def to_string(self, nspair=None):
if not nspair and self.c_ns_prefix:
nspair = self.c_ns_prefix
if nspair:
self.register_prefix(nspair)
return ElementTree.tostring(self._to_element_tree(), encoding="UTF-8") | Converts the Saml object to a string containing XML.
:param nspair: A dictionary of prefixes and uris to use when
constructing the text representation.
:return: String representation of the object |
346,093 | def set_from_json(self, obj, json, models=None, setter=None):
if isinstance(json, dict):
old = getattr(obj, self.name)
if old is not None:
try:
self.property._type.validate(old, False)
if in json:... | Sets the value of this property from a JSON value.
This method first
Args:
obj (HasProps) :
json (JSON-dict) :
models(seq[Model], optional) :
setter (ClientSession or ServerSession or None, optional) :
This is used to prevent "boomeran... |
346,094 | def has_next(self):
if self._state == PhoneNumberMatcher._NOT_READY:
self._last_match = self._find(self._search_index)
if self._last_match is None:
self._state = PhoneNumberMatcher._DONE
else:
self._search_index = self._last_match.end
... | Indicates whether there is another match available |
346,095 | def set_doc_comment(self, doc, comment):
if not self.doc_comment_set:
self.doc_comment_set = True
doc.comment = comment
else:
raise CardinalityError() | Sets document comment, Raises CardinalityError if
comment already set. |
346,096 | def read_image(img_path, image_dims=None, mean=None):
import urllib
filename = img_path.split("/")[-1]
if img_path.startswith():
urllib.urlretrieve(img_path, filename)
img = cv2.imread(filename)
else:
img = cv2.imread(img_path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RG... | Reads an image from file path or URL, optionally resizing to given image dimensions and
subtracting mean.
:param img_path: path to file, or url to download
:param image_dims: image dimensions to resize to, or None
:param mean: mean file to subtract, or None
:return: loaded image, in RGB format |
346,097 | def is_LaTeX(flist,env,abspath):
savedpath = modify_env_var(env, , abspath)
paths = env[][]
if SCons.Util.is_List(paths):
pass
else:
paths = paths.split(os.pathsep)
if savedpath is _null:
try:
del env[][]
except KeyErro... | Scan a file list to decide if it's TeX- or LaTeX-flavored. |
346,098 | def get_set_voltage(self, channel):
ret = self.ask("V%d?" % channel)
if ret[:3] != "V%d " % channel:
print("ttiQl355tp.get_voltage() format error", ret)
return None
return float(ret[3:]) | channel: 1=OP1, 2=OP2, AUX is not supported |
346,099 | def _create_session(team, auth):
session = requests.Session()
session.hooks.update(dict(
response=partial(_handle_response, team)
))
session.headers.update({
"Content-Type": "application/json",
"Accept": "application/json",
"User-Agent": "quilt-cli/%s (%s %s) %s/%s" ... | Creates a session object to be used for `push`, `install`, etc. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.