Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
338,500 | def _extract_direct(self, *, stream):
def normal_dct_rgb():
DEFAULT_CT_CMYK = 0
ct = self.filter_decodeparms[0][1].get(, DEFAULT_CT_CMYK)
return self.mode == and ct == DEFAULT_CT_CMYK
if self.filters == []:
... | Attempt to extract the image directly to a usable image file
If there is no way to extract the image without decompressing or
transcoding then raise an exception. The type and format of image
generated will vary.
Args:
stream: Writable stream to write data to |
338,501 | def _get_or_create_a(self, _type):
self.l.debug("get_or_create_a: %s" % _type)
stack = [Manager.GoCa_Plan(self, {_type: ()})]
while stack:
p = stack.pop()
if p.finished:
p.execute()
return p.get_a(_type)
for c in p.bran... | Gets or creates an instance of type <_type> |
338,502 | def _load_profile_imports(self, symbol_table):
results = []
if not in symbol_table:
return results
package = self._get_package(symbol_table)
profile_imports = symbol_table[]
for item in profile_imports:
if isinstance(item, str):
module_name, names = (item, None)
... | profile_imports is a list of module names or tuples
of (module_name, names to import)
in the form of ('.', names) it behaces like:
from . import name1, name2, name3
or similarly
import .name1, .name2, .name3
i.e. "name" in names becomes ".name" |
338,503 | def process_audiomack(vargs):
artist_url = vargs[]
if in artist_url:
mc_url = artist_url
else:
mc_url = + artist_url
filenames = scrape_audiomack_url(mc_url, num_tracks=vargs[], folders=vargs[], custom_path=vargs[])
if vargs[]:
open_files(filenames)
return | Main Audiomack path. |
338,504 | def handle_text(self, item):
doc = yield from self.handle_get(item)
if doc is None:
return None
return doc.value.c8_array.text or None | Helper method for fetching a text value. |
338,505 | def from_jsonstring(cls, s, selector_handler=None, strict=False, debug=False):
return cls._from_jsonlines(s.split("\n"),
selector_handler=selector_handler, strict=strict, debug=debug) | Create a Parselet instance from s (str) containing
the Parsley script as JSON
>>> import parslepy
>>> parsley_string = '{ "title": "h1", "link": "a @href"}'
>>> p = parslepy.Parselet.from_jsonstring(parsley_string)
>>> type(p)
<class 'parslepy.base.Parselet'>
>>>... |
338,506 | def execute_with_client(quiet=False,
bootstrap_server=False,
create_client=True):
def wrapper(f):
def wrapper2(self, *args, **kwargs):
client = self.current_client(
quiet=quiet,
bootstrap_server=bootstrap_serve... | Decorator that gets a client and performs an operation on it. |
338,507 | def login(self):
if self.has_cookies() and \
(not self.username and not self.password):
return
if self.basic and (self.username and self.password):
return
try:
... | Logs into the Splunk instance referred to by the :class:`Context`
object.
Unless a ``Context`` is created with an explicit authentication token
(probably obtained by logging in from a different ``Context`` object)
you must call :meth:`login` before you can issue requests.
The au... |
338,508 | def from_cli(cls, ifo, args, maxlen):
state_channel = analyze_flags = None
if args.state_channel and ifo in args.state_channel \
and args.analyze_flags and ifo in args.analyze_flags:
state_channel = .join([ifo, args.state_channel[ifo]])
analyze_flags = ar... | Initialize a StrainBuffer object (data reader) for a particular
detector. |
338,509 | def _partition(hours, partition = 3600.0):
partition = float(partition)
relative = hours - hours[0]
total_partitions = np.ceil(relative[-1] / partition + 10*np.finfo(np.float).eps).astype()
return [hours[np.floor(np.divide(relative, partition)) == i] for i in range(total_partitions)] | Partition a sorted list of numbers (or in this case hours).
Arguments:
hours -- sorted ndarray of hours.
partition -- maximum partition length (default: 3600.0) |
338,510 | def get_permissible_wcs(classname, f):
r
classes = [, , , , , , , ]
if classname not in classes or f == 5:
return
if f not in [3, 4]:
raise ValueError("f must be 3, 4, or 5.")
if classname == :
sector =
else:
sector = classname
... | r"""For some classes (in particular $\Delta F=1$), only a subset of Wilson
coefficients exist in WET-3 and WET-4. Therefore, depending on the number
of flavours `f`, the dimensionality of the ADM has to be reduced. |
338,511 | def number_of_each_lipid_per_layer(self):
if self._number_of_each_lipid_per_layer:
return self._number_of_each_lipid_per_layer
for lipid in self.lipids[:-1]:
self._number_of_each_lipid_per_layer.append(int(round(lipid[1] * self.n_lipids_per_layer)))
... | The number of each lipid per layer. |
338,512 | def cumulative_std(self):
from .. import extensions
agg_op = "__builtin__cum_std__"
return SArray(_proxy = self.__proxy__.builtin_cumulative_aggregate(agg_op)) | Return the cumulative standard deviation of the elements in the SArray.
Returns an SArray where each element in the output corresponds to the
standard deviation of all the elements preceding and including it. The
SArray is expected to be of numeric type, or a numeric vector type.
Retur... |
338,513 | def infer_x(self, y):
assert len(y) == self.fmodel.dim_y, "Wrong dimension for y. Expected %i, got %i" % (self.fmodel.dim_y, len(y))
if len(self.fmodel.dataset) == 0:
return [[0.0]*self.dim_x]
else:
_, index = self.fmodel.dataset.nn_y(y, k=1)
return [... | Infer probable x from input y
@param y the desired output for infered x. |
338,514 | def top_process(self):
key = next(iter(self.entries))
return self.entries[key].process_entry | :return: <ManagedProcessEntry> of the hierarchy's top entry |
338,515 | def enum(option, *options):
options = (option,) + options
rangeob = range(len(options))
try:
inttype = _inttypes[int(np.log2(len(options) - 1)) // 8]
except IndexError:
raise OverflowError(
%
len(options),
)
class _enum(Structure):
_fie... | Construct a new enum object.
Parameters
----------
*options : iterable of str
The names of the fields for the enum.
Returns
-------
enum
A new enum collection.
Examples
--------
>>> e = enum('a', 'b', 'c')
>>> e
<enum: ('a', 'b', 'c')>
>>> e.a
0
... |
338,516 | def get_connection(self, *args, **kwargs):
conn = super(SSLHTTPAdapter, self).get_connection(*args, **kwargs)
if conn.assert_hostname != self.assert_hostname:
conn.assert_hostname = self.assert_hostname
return conn | Ensure assert_hostname is set correctly on our pool
We already take care of a normal poolmanager via init_poolmanager
But we still need to take care of when there is a proxy poolmanager |
338,517 | def create(cls, values, **context):
schema = cls.schema()
model = cls
polymorphic_columns = schema.columns(flags=orb.Column.Flags.Polymorphic)
if polymorphic_columns:
polymorphic_column = polymorphic_columns.values()[0]
schema_name = values.get(... | Shortcut for creating a new record for this table.
:param values | <dict>
:return <orb.Table> |
338,518 | def scale_channel(self, ch, value):
v = value/10000.0
if v < -1:
v = -1
elif v > 1:
v = 1
if ch == 3 and self.mpstate.vehicle_type != :
if v < 0:
v = 0
return int(1000 + v*1000)
return int(1500 + v*500) | scale a channel to 1000/1500/2000 |
338,519 | def csv_to_obj(cls, file_path=None, text=, columns=None,
remove_empty_rows=True, key_on=None, deliminator=,
eval_cells=True):
lines = cls._get_lines(file_path, text, replace=u)
for i in range(len(lines)):
lines[i] = lines[i].replace(, )
... | This will convert a csv file or csv text into a seaborn table
and return it
:param file_path: str of the path to the file
:param text: str of the csv text
:param columns: list of str of columns to use
:param remove_empty_rows: bool if True will remove empty rows
w... |
338,520 | def _before_flush_handler(session, _flush_context, _instances):
dialect = get_dialect(session)
for row in session.dirty:
if isinstance(row, SavageModelMixin) and is_modified(row, dialect):
row.update_version_id() | Update version ID for all dirty, modified rows |
338,521 | def process(self, document):
self.logger.info("Processing group of tasks (parallel=%s)", self.get_parallel_mode())
self.pipeline.data.env_list[2] = {}
output, shells = [], []
result = Adapter({: True, : []})
for task_entry in document:
key, entry = list(task... | Processing a group of tasks. |
338,522 | def resource_absent(name, resource_type, resource_selector_property, resource_selector_value):
ret = {: name,
: {},
: None,
: }
if resource_selector_property:
resource_selector_value = _parse_value(resource_selector_value)
else:
resource_selector_v... | Ensure resource is absent
name : string
name of the zone
resource_type : string
type of resource
resource_selector_property : string
unique resource identifier
resource_selector_value : string
value for resource selection
.. warning::
Both resource_selector_... |
338,523 | def stretch_hist_equalize(self, ch_nb):
logger.info("Perform a histogram equalized contrast stretch.")
if(self.channels[ch_nb].size ==
np.ma.count_masked(self.channels[ch_nb])):
logger.warning("Nothing to stretch !")
return
arr = self.channels[ch_nb]... | Stretch the current image's colors by performing histogram
equalization on channel *ch_nb*. |
338,524 | def dad_status_output_dad_status_entries_index(self, **kwargs):
config = ET.Element("config")
dad_status = ET.Element("dad_status")
config = dad_status
output = ET.SubElement(dad_status, "output")
dad_status_entries = ET.SubElement(output, "dad-status-entries")
i... | Auto Generated Code |
338,525 | def list_newsgroups_gen(self, pattern=None):
args = pattern
code, message = self.command("LIST NEWSGROUPS", args)
if code != 215:
raise NNTPReplyError(code, message)
for line in self.info_gen(code, message):
parts = line.strip().split()
name... | Generator for the LIST NEWSGROUPS command.
Generates a list of newsgroups including the name and a short
description.
See <http://tools.ietf.org/html/rfc3977#section-7.6.6>
Args:
pattern: Glob matching newsgroups of intrest.
Yields:
A tuple containing ... |
338,526 | def on_state_changed(self, state):
if state:
self.editor.key_pressed.connect(self._on_key_pressed)
if self._highlight_caret:
self.editor.cursorPositionChanged.connect(
self._highlight_caret_scope)
self._block_nbr = -1
... | On state changed we (dis)connect to the cursorPositionChanged signal |
338,527 | def get_key_from_path_and_site(path, site_id):
key = .format(path, site_id)
key = hashlib.sha224(key.encode()).hexdigest()
return key | cache key has to be < 250 chars to avoid memcache.Client.MemcachedKeyLengthError
The best algoritm is SHA-224 whose output (224 chars) respects this limitations |
338,528 | def register_hdf5_array_io(array_type, format=, identify=True):
def from_hdf5(*args, **kwargs):
kwargs.setdefault(, array_type)
return read_hdf5_array(*args, **kwargs)
io_registry.register_reader(format, array_type, from_hdf5)
if issubclass(array_type, Series):
io_regi... | Registry read() and write() methods for the HDF5 format |
338,529 | def analyze(self):
log.debug("enable half sinus scan")
self.half_sinus = True
statistics = self._get_statistics()
width = 50
max_count = max(statistics.values())
print
print "Found this zeror crossing timings in the wave file:"
print
fo... | Example output:
394Hz ( 28 Samples) exist: 1
613Hz ( 18 Samples) exist: 1
788Hz ( 14 Samples) exist: 1
919Hz ( 12 Samples) exist: 329 *********
1002Hz ( 11 Samples) exist: 1704 **********************************************
1103Hz ( 10 Sam... |
338,530 | def parse(self, string):
fields = [i.split("=") for i in string.split()]
for what, val in fields:
what = what.strip()
val = val.split()
if what.endswith("head"):
self.head = val
elif what.endswith("link"):
self.lin... | Parse lipid definition from string:
alhead=C P, allink=A A, altail=TCC CCCC, alname=DPSM, charge=0.0 |
338,531 | def graph_nodes_sorted(self):
return sorted(self._graph.nodes(), key=lambda _: repr(_)) | Returns an (ascending) sorted list of graph's nodes (name is used as key).
Returns
-------
:any:`list`
Description #TODO check |
338,532 | def add(self, path, debug, children):
if path in self._stats_by_path:
print("%s is already being watched" % (path))
return
if "/" in self._stats_by_path:
print("/ is already being watched, so everything is watched")
ret... | Set a watch for path and (maybe) its children depending on the value
of children:
-1: all children
0: no children
> 0: up to level depth children
If debug is true, print each received events. |
338,533 | def to_api_repr(self):
s_types = {}
values = {}
for name, value in self.struct_values.items():
type_ = self.struct_types[name]
if type_ in ("STRUCT", "ARRAY"):
repr_ = value.to_api_repr()
s_types[name] = {"name": name, "type": repr... | Construct JSON API representation for the parameter.
:rtype: dict
:returns: JSON mapping |
338,534 | def current_offset(local_tz=None):
if local_tz is None:
local_tz = DEFAULT_LOCAL_TZ
dt = local_tz.localize(datetime.now())
return dt.utcoffset() | Returns current utcoffset for a timezone. Uses
DEFAULT_LOCAL_TZ by default. That value can be
changed at runtime using the func below. |
338,535 | def boundary_cell_fractions(self):
frac_list = []
for ax, (cvec, bmin, bmax) in enumerate(zip(
self.grid.coord_vectors, self.set.min_pt, self.set.max_pt)):
if len(cvec) == 1:
frac_list.append((1.0, 1.0))
else:
... | Return a tuple of contained fractions of boundary cells.
Since the outermost grid points can have any distance to the
boundary of the partitioned set, the "natural" outermost cell
around these points can either be cropped or extended. This
property is a tuple of (float, float) tuples, o... |
338,536 | def cycle(self, *args):
if not args:
raise TypeError()
return args[self.index0 % len(args)] | Cycles among the arguments with the current loop index. |
338,537 | def addsshkeyuser(self, user_id, title, key):
data = {: title, : key}
request = requests.post(
.format(self.users_url, user_id), headers=self.headers,
data=data, verify=self.verify_ssl, auth=self.auth, timeout=self.timeout)
if request.status_code == 201:
... | Add a new ssh key for the user identified by id
:param user_id: id of the user to add the key to
:param title: title of the new key
:param key: the key itself
:return: true if added, false if it didn't add it (it could be because the name or key already exists) |
338,538 | def setUp(self, masterqa_mode=False):
self.masterqa_mode = masterqa_mode
self.is_pytest = None
try:
self.is_pytest = sb_config.is_pytest
except Exception:
self.is_pytest = False
if self.is_pytest:
... | Be careful if a subclass of BaseCase overrides setUp()
You'll need to add the following line to the subclass setUp() method:
super(SubClassOfBaseCase, self).setUp() |
338,539 | def from_value(cls, value: str) -> T:
return [x for x in cls.__members__.values() if x.value[0] == value][0] | Create instance from symbol
:param value: unique symbol
:return: This instance
Usage:
>>> from owlmixin.samples import Animal
>>> Animal.from_value('cat').crow()
mewing |
338,540 | def get_build_metadata(key):
headers = {"Metadata-Flavor":"Google"}
url = "http://metadata.google.internal/computeMetadata/v1/instance/attributes/%s" %(key)
response = requests.get(url=url,headers=headers)
if response.status_code == 200:
return response.text
return None | get_build_metadata will return metadata about an instance from within it.
:param key: the key to look up |
338,541 | def process_bulk_vm_event(self, msg, phy_uplink):
LOG.info("In processing Bulk VM Event status %s", msg)
time.sleep(3)
if (not self.uplink_det_compl or
phy_uplink not in self.ovs_vdp_obj_dict):
phy_uplink=phy_uplink)
... | Process the VM bulk event usually after a restart. |
338,542 | def wrap(vtkdataset):
wrappers = {
: vtki.UnstructuredGrid,
: vtki.RectilinearGrid,
: vtki.StructuredGrid,
: vtki.PolyData,
: vtki.UniformGrid,
: vtki.UniformGrid,
: vtki.MultiBlock,
}
key = vtkdataset.GetClassName()
try:
wr... | This is a convenience method to safely wrap any given VTK data object
to its appropriate ``vtki`` data object. |
338,543 | def load_jsonf(fpath, encoding):
with codecs.open(fpath, encoding=encoding) as f:
return json.load(f) | :param unicode fpath:
:param unicode encoding:
:rtype: dict | list |
338,544 | def fit(self, X, y=None):
self.transformer_list = list(self.transformer_list)
self._validate_transformers()
with Pool(self.n_jobs) as pool:
transformers = pool.starmap(_fit_one_transformer,
((trans, X[trans[]] if hasattr(trans, ) else X, y) for _, tra... | Fit all transformers using X.
Parameters
----------
X : iterable or array-like, depending on transformers
Input data, used to fit transformers.
y : array-like, shape (n_samples, ...), optional
Targets for supervised learning.
Returns
-------
... |
338,545 | def store_info(self, info_dict, component, type_tag):
if not isinstance(info_dict, dict):
print % type(info_dict)
return
info_storage = {key:value for key, value in info_dict.iteritems() if not hasattr(value, )}
info_storage[] = typ... | Store information about a component. The component could be a
worker or a commands or a class, or whatever you want, the
only thing to be aware of is name collisions. |
338,546 | def reindex_content_structure(portal):
logger.info("*** Reindex content structure ***")
def reindex(obj, recurse=False):
if api.is_object(obj):
obj.reindexObject()
if recurse and hasattr(aq_base(obj), "objectValues"):
map(reindex, obj.objectValues())
s... | Reindex contents generated by Generic Setup |
338,547 | def flush(self):
if self.ro:
raise DatabaseROError()
if self.writequeue:
| write out all queued write-commands in order, each one in a separate
:meth:`atomic <notmuch.Database.begin_atomic>` transaction.
If this fails the current action is rolled back, stays in the write
queue and an exception is raised.
You are responsible to retry flushing at a later time if... |
338,548 | def reset_bios_to_default(self):
sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
try:
sushy_system.bios_settings.update_bios_to_default()
except sushy.exceptions.SushyError as e:
msg = (self._("The Redfish controller is unable to update bios "
... | Resets the BIOS settings to default values.
:raises: IloError, on an error from iLO. |
338,549 | def _convert_addrinfo(cls, results: List[tuple]) -> Iterable[AddressInfo]:
for result in results:
family = result[0]
address = result[4]
ip_address = address[0]
if family == socket.AF_INET6:
flow_info = address[2]
control_... | Convert the result list to address info. |
338,550 | def is_larger(unit_1, unit_2):
unit_1 = functions.value_for_key(INFORMATION_UNITS, unit_1)
unit_2 = functions.value_for_key(INFORMATION_UNITS, unit_2)
return ureg.parse_expression(unit_1) > ureg.parse_expression(unit_2) | Returns a boolean indicating whether unit_1 is larger than unit_2.
E.g:
>>> is_larger('KB', 'B')
True
>>> is_larger('min', 'day')
False |
338,551 | def populate(self, **values):
values = values.copy()
fields = list(self.iterate_with_name())
for _, structure_name, field in fields:
if structure_name in values:
field.__set__(self, values.pop(structure_name))
for name, _, field in fields:
... | Populate values to fields. Skip non-existing. |
338,552 | def remove_citation_metadata(graph):
for u, v, k in graph.edges(keys=True):
if CITATION not in graph[u][v][k]:
continue
for key in list(graph[u][v][k][CITATION]):
if key not in _CITATION_KEEP_KEYS:
del graph[u][v][k][CITATION][key] | Remove the metadata associated with a citation.
Best practice is to add this information programmatically. |
338,553 | def readline(prev, filename=None, mode=, trim=str.rstrip, start=1, end=sys.maxsize):
if prev is None:
if filename is None:
raise Exception()
elif is_str_type(filename):
file_list = [filename, ]
else:
file_list = filename
else:
file_list = ... | This pipe get filenames or file object from previous pipe and read the
content of file. Then, send the content of file line by line to next pipe.
The start and end parameters are used to limit the range of reading from file.
:param prev: The previous iterator of pipe.
:type prev: Pipe
:param filen... |
338,554 | def default_reverse_key_func(full_key):
match = reverse_key_re.match(full_key)
return match.group(3), match.group(1), int(match.group(2)) | Reverse of Django's default_key_func, i.e. undoing:
def default_key_func(key, key_prefix, version):
return '%s:%s:%s' % (key_prefix, version, key) |
338,555 | def reset(self):
self.scores = torch.FloatTensor(torch.FloatStorage())
self.targets = torch.LongTensor(torch.LongStorage())
self.weights = torch.FloatTensor(torch.FloatStorage()) | Resets the meter with empty member variables |
338,556 | def _fmt(self, string):
if not in string:
string = + string
return string.format(self.name) | Helper method to format our name into a string. |
338,557 | def _StripThenGetNicknameAndText(self, text):
stripped = self.STRIPPER.transformString(text)
structure = self.MSG_ENTRY.parseString(stripped)
text = structure.text.replace(, )
return structure.nickname, text | Strips decorators from text and gets <nickname> if available.
This method implements the XChat strip_color2 and fe_print_text
functions, slightly modified to get pure text. From the parsing point
of view, after having stripped, the code takes everything as is,
simply replacing tabs with spaces (as the ... |
338,558 | def perform_display_your_comments(user_info,
page_number=1,
selected_order_by_option="lcf",
selected_display_number_option="all",
selected_display_format_option="rc",
... | Display all comments submitted by the user.
:TODO: support reviews too
:param user_info: standard user info object.
:param comments: ordered list of tuples (id_bibrec, comid, date_creation, body, status, in_reply_to_id_cmtRECORDCOMMENT)
:param page_number: page on which the user is.
:type page_num... |
338,559 | def _stream_authorized(self, event):
with self.lock:
if event.stream != self.stream:
return
self.me = event.stream.me
self.peer = event.stream.peer
presence = self.settings[u"initial_presence"]
if presence:
self... | Handle the `AuthorizedEvent`. |
338,560 | def dst(self, dt):
if not self._is_dst(dt):
return datetime.timedelta(0)
offset = time.timezone - time.altzone
return datetime.timedelta(seconds=-offset) | Returns a difference in seconds between standard offset and
dst offset. |
338,561 | def rotate_left(self):
new_root = self.node.right.node
new_left_sub = new_root.left.node
old_root = self.node
self.node = new_root
old_root.right.node = new_left_sub
new_root.left.node = old_root | Left rotation |
338,562 | def delete_roles_request(request):
uuid_ = request.matchdict[]
posted_roles = request.json
with db_connect() as db_conn:
with db_conn.cursor() as cursor:
remove_role_requests(cursor, uuid_, posted_roles)
resp = request.response
resp.status_int = 200
return resp | Submission to remove a role acceptance request. |
338,563 | def _set_access_list(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=access_list.access_list, is_container=, presence=False, yang_name="access-list", rest_name="access-list", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, reg... | Setter method for access_list, mapped from YANG variable /ipv6_acl/ipv6/access_list (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_access_list is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set... |
338,564 | def answer_inline_query(self, inline_query_id, results, cache_time=None, is_personal=None, next_offset=None, switch_pm_text=None, switch_pm_parameter=None):
from pytgbot.api_types.sendable.inline import InlineQueryResult
assert_type_or_raise(inline_query_id, unicode_type, parameter_nam... | Use this method to send answers to an inline query. On success, True is returned.No more than 50 results per query are allowed.
https://core.telegram.org/bots/api#answerinlinequery
Parameters:
:param inline_query_id: Unique identifier for the answered query
:type inl... |
338,565 | def start_output (self):
super(GMLLogger, self).start_output()
if self.has_part("intro"):
self.write_intro()
self.writeln()
self.writeln(u"graph [")
self.writeln(u" directed 1")
self.flush() | Write start of checking info as gml comment. |
338,566 | def get_options(cls, items, options, warnfn):
"Given a keyword specification, validate and compute options"
options = cls.update_options(options, items)
for keyword in cls.defaults:
if keyword in items:
value = items[keyword]
allowed = cls.allowed[keyw... | Given a keyword specification, validate and compute options |
338,567 | def brew_query_parts(self):
columns, group_bys, filters, havings = [], [], set(), set()
for ingredient in self.ingredients():
if ingredient.query_columns:
columns.extend(ingredient.query_columns)
if ingredient.group_by:
group_bys.extend(in... | Make columns, group_bys, filters, havings |
338,568 | def makeGlu(segID, N, CA, C, O, geo):
CA_CB_length=geo.CA_CB_length
C_CA_CB_angle = geo.C_CA_CB_angle
N_C_CA_CB_diangle=geo.N_C_CA_CB_diangle
CB_CG_length=geo.CB_CG_length
CA_CB_CG_angle=geo.CA_CB_CG_angle
N_CA_CB_CG_diangle=geo.N_CA_CB_CG_diangle
CG_CD_length=geo.CG_CD_lengt... | Creates a Glutamic Acid residue |
338,569 | def _check_qargs(self, qargs):
if not all(isinstance(i, tuple) and
isinstance(i[0], QuantumRegister) and
isinstance(i[1], int) for i in qargs):
raise QiskitError("qarg not (QuantumRegister, int) tuple")
if not all(self.has_register(i[0]) for i i... | Raise exception if a qarg is not in this circuit or bad format. |
338,570 | def _generate_standard_transitions(cls):
allowed_transitions = cls.context.get_config(, {})
for key, transitions in allowed_transitions.items():
key = cls.context.new_meta[].translate(key)
new_transitions = set()
for trans in transitions:
if ... | Generate methods used for transitions. |
338,571 | def _import_data(self, data):
for key, value in data.items():
if key.startswith():
self._not_allowed_field(key)
continue
if not self.get_field_obj(key) and not self._define_new_field_by_value(key, value):
self._not_allowed_value(... | Set the fields established in data to the instance |
338,572 | def path(self, which=None):
if which == :
return .format(
super(RHCIDeployment, self).path(which=),
which
)
return super(RHCIDeployment, self).path(which) | Extend ``nailgun.entity_mixins.Entity.path``.
The format of the returned path depends on the value of ``which``:
deploy
/deployments/<id>/deploy
``super`` is called otherwise. |
338,573 | def check_pseudo_package(path):
if not os.path.isdir(path):
raise Exception("Please make sure pseudo-package %s exists." % path)
else:
assets = os.listdir(path)
if len(assets) == 0:
raise Exception("Please make sure pseudo-package %s is populated." % path) | Verifies that a fake subpackage path for assets (notebooks, svgs,
pngs etc) both exists and is populated with files. |
338,574 | def _extract_schema_if_given(table_name):
pattern =
m = re.match(pattern, table_name)
schema, table_name = m.group(2), m.group(3)
return schema, table_name | Return a pair (schema, table) derived from the given `table_name`
(anything before the first '.' if the name contains one; otherwise
the return value of `schema` is None).
Examples:
>>> _extract_schema_if_given('some_schema.my_table')
('some_schema', 'my_table')
>>> _extract_schem... |
338,575 | def depth_file_for_nir_file(video_filename, depth_file_list):
(root, filename) = os.path.split(video_filename)
needle_ts = int(filename.split()[2].split()[0])
haystack_ts_list = np.array(Kinect.timestamps_from_file_list(depth_file_list))
haystack_idx = np.flatnonzero(haystack_ts... | Returns the corresponding depth filename given a NIR filename |
338,576 | def _convert_item(self, obj):
if isinstance(obj, dict) and not isinstance(obj, DotDict):
obj = DotDict(obj)
elif isinstance(obj, list):
for i, item in enumerate(obj):
if isinstance(item, dict) and not isinstance(item, DotDict):
... | Convert obj into a DotDict, or list of DotDict.
Directly nested lists aren't supported.
Returns the result |
338,577 | def term_color(code):
def inner(text, rl=False):
c = code
if rl:
return "\001\033[38;5;%sm\002%s\001\033[0m\002" % (c, text)
else:
return "\033[38;5;%sm%s\033[0m" % (c, text)
return inner | 256 colors supported |
338,578 | def f_get_derived_parameters(self, fast_access=False, copy=True):
return self._return_item_dictionary(self._derived_parameters, fast_access, copy) | Returns a dictionary containing the full parameter names as keys and the parameters
or the parameter data items as values.
:param fast_access:
Determines whether the parameter objects or their values are returned
in the dictionary.
:param copy:
Whether t... |
338,579 | def Cache(fn):
def fnCache(*args, **kwargs):
key = (args and tuple(args) or None,
kwargs and frozenset(kwargs.items()) or None)
if key not in fn.__cached__:
fn.__cached__[key] = cache = fn(*args, **kwargs)
else:
cache = fn.__cached__[key]
return cache... | Function cache decorator |
338,580 | def _report_state(self):
LOG.debug("Report state task started")
self.keepalive_iteration += 1
if self.keepalive_iteration == self.report_iteration:
self._prepare_full_report_data()
self.keepalive_iteration = 0
LOG.debug("State report: %s", pprint.pfor... | Report state to the plugin.
This task run every `keepalive_interval` period.
Collects, creates and sends a summary of the services currently
managed by this agent. Data is collected from the service helper(s).
Refer the `configurations` dict for the parameters reported.
:return:... |
338,581 | def sents(self: object, fileids: str):
for para in self.paras(fileids):
for sent in sent_tokenize(para):
yield sent | Tokenizes documents in the corpus by sentence |
338,582 | def tune(self, job_name, strategy, objective_type, objective_metric_name,
max_jobs, max_parallel_jobs, parameter_ranges,
static_hyperparameters, input_mode, metric_definitions,
role, input_config, output_config, resource_config, stop_condition, tags,
warm_start_config... | Create an Amazon SageMaker hyperparameter tuning job
Args:
job_name (str): Name of the tuning job being created.
strategy (str): Strategy to be used for hyperparameter estimations.
objective_type (str): The type of the objective metric for evaluating training jobs. This valu... |
338,583 | def check_token(self, token, allowed_roles, resource, method):
resource_conf = config.DOMAIN[resource]
audiences = resource_conf.get(, config.JWT_AUDIENCES)
return self._perform_verification(token, audiences, allowed_roles) | This function is called when a token is sent throught the access_token
parameter or the Authorization header as specified in the oAuth 2 specification.
The provided token is validated with the JWT_SECRET defined in the Eve configuration.
The token issuer (iss claim) must be the one specified by... |
338,584 | def _parse_arguments(prog, argv):
param_util.handle_version_flag()
parser = provider_base.create_parser(prog)
parser.add_argument(
, , default=False, help=)
parser.add_argument(
,
default=False,
action=,
help=)
parser.add_argument(
,
help=)
parser.add_ar... | Parses command line arguments.
Args:
prog: The path of the program (dsub.py) or an alternate program name to
display in usage.
argv: The list of program arguments to parse.
Returns:
A Namespace of parsed arguments. |
338,585 | def add_state(self, state_name, initial_state, batch_size=None):
state_shape = initial_state.get_shape().as_list()
full_shape = [batch_size] + state_shape
if not batch_size:
shape_proto = self._as_shape_proto([0] + state_shape)
batch_size = 1
else:
... | Adds a state to the state saver.
Args:
state_name: The name of this state.
initial_state: The initial state vector. Only zeros are supported.
batch_size: The batch_size or None for unknown. |
338,586 | def _data_is_binary(self, data):
if isinstance(data, six.binary_type):
return True
elif isinstance(data, list):
return functools.reduce(
lambda a, b: a or b, [self._data_is_binary(item)
for item in data], False)
... | Check if the data contains binary components. |
338,587 | def differential_pressure_meter_solver(D, rho, mu, k, D2=None, P1=None, P2=None,
m=None, meter_type=ISO_5167_ORIFICE,
taps=None):
rISO 5167 orificelong radius nozzleISA 1932 nozzlevenuri nozzleas cast convergent venturi tubemachined con... | r'''Calculates either the mass flow rate, the upstream pressure, the second
pressure value, or the orifice diameter for a differential
pressure flow meter based on the geometry of the meter, measured pressures
of the meter, and the density, viscosity, and isentropic exponent of the
fluid. This solves ... |
338,588 | def _pop_index(self, index, has_default):
try:
if index is NOT_SET:
index = len(self._list) - 1
key, value = self._list.pop()
else:
key, value = self._list.pop(index)
if index < 0:
index += len(self._list) + 1
except IndexError:
if has_default:
return None, None, None
else:
... | Remove an element by index, or last element. |
338,589 | def _getMonitorInfo(self):
monitors = []
CCHDEVICENAME = 32
def _MonitorEnumProcCallback(hMonitor, hdcMonitor, lprcMonitor, dwData):
class MONITORINFOEX(ctypes.Structure):
_fields_ = [("cbSize", ctypes.wintypes.DWORD),
("rcMonitor"... | Returns info about the attached monitors, in device order
[0] is always the primary monitor |
338,590 | def pip_version_check(session):
import pip
pypi_version = None
try:
state = load_selfcheck_statefile()
current_time = datetime.datetime.utcnow()
if "last_check" in state.state and "pypi_version" in state.state:
last_check = datetime.datetime.strptime(
... | Check for an update for pip.
Limit the frequency of checks to once per week. State is stored either in
the active virtualenv or in the user's USER_CACHE_DIR keyed off the prefix
of the pip script path. |
338,591 | def flavor_present(name, params=None, **kwargs):
dry_run = __opts__[]
ret = {: name, : False, : , : {}}
if params is None:
params = {}
try:
kwargs.update({: {: None}})
object_list = __salt__[](**kwargs)
object_exists = True if object_list[name][] == name else False... | Creates Nova flavor if it does not exist
:param name: Flavor name
:param params: Definition of the Flavor (see Compute API documentation)
.. code-block:: yaml
nova-flavor-present:
nova.flavor_present:
- name: myflavor
- params:
ram: ... |
338,592 | def support_support_param_protocol(self, **kwargs):
config = ET.Element("config")
support = ET.SubElement(config, "support", xmlns="urn:brocade.com:mgmt:brocade-ras")
support_param = ET.SubElement(support, "support-param")
protocol = ET.SubElement(support_param, "protocol")
... | Auto Generated Code |
338,593 | def from_dict(cls, logical_id, resource_dict, relative_id=None, sam_plugins=None):
resource = cls(logical_id, relative_id=relative_id)
resource._validate_resource_dict(logical_id, resource_dict)
properties = resource_dict.get("Properties", {})
if sam_plugin... | Constructs a Resource object with the given logical id, based on the given resource dict. The resource dict
is the value associated with the logical id in a CloudFormation template's Resources section, and takes the
following format. ::
{
"Type": "<resource type>",
... |
338,594 | def _parse_pet_record(self, root):
record = {
"breeds": [],
"photos": [],
"options": [],
"contact": {},
}
straight_copy_fields = [
"id", "shelterId", "shelterPetId", "name", "animal", "mix",
"age"... | Given a <pet> Element from a pet.get or pet.getRandom response, pluck
out the pet record.
:param lxml.etree._Element root: A <pet> tag Element.
:rtype: dict
:returns: An assembled pet record. |
338,595 | def quit(self, reason=):
with self.lock:
self.keep_going = False
self._quit(reason)
self._socket.shutdown(self._m_socket.SHUT_RDWR)
self._socket.close() | Sends a QUIT message, closes the connection and -
ends Lurklib's main loop.
Optional arguments:
* reason='' - Reason for quitting. |
338,596 | def replace_all(text, replace_dict):
for i, j in replace_dict.items():
text = text.replace(i, j)
return text | Replace multiple strings in a text.
.. note::
Replacements are made successively, without any warranty on the order \
in which they are made.
:param text: Text to replace in.
:param replace_dict: Dictionary mapping strings to replace with their \
substitution.
:returns: T... |
338,597 | def make_shp_filename(place_name):
name_pieces = list(reversed(place_name.split()))
filename = .join(name_pieces).lower().replace(,)
filename = re.sub(, , filename)
return filename | Create a filename string in a consistent format from a place name string.
Parameters
----------
place_name : string
place name to convert into a filename
Returns
-------
string |
338,598 | def ramp_down_sp(self):
self._ramp_down_sp, value = self.get_attr_int(self._ramp_down_sp, )
return value | Writing sets the ramp down setpoint. Reading returns the current value. Units
are in milliseconds and must be positive. When set to a non-zero value, the
motor speed will decrease from 0 to 100% of `max_speed` over the span of this
setpoint. The actual ramp time is the ratio of the difference be... |
338,599 | def add_node(self, name, desc, layout, node_x, node_y):
existing_node = get_session().query(Node).filter(Node.name==name, Node.network_id==self.id).first()
if existing_node is not None:
raise HydraError("A node with name %s is already in network %s"%(name, self.id))
node = ... | Add a node to a network. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.