Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
364,900 | def _create_tensor_summary(
name,
true_positive_counts,
false_positive_counts,
true_negative_counts,
false_negative_counts,
precision,
recall,
num_thresholds=None,
display_name=None,
description=None,
collections=None):
import tensorflow.compat.v1 as tf
summa... | A private helper method for generating a tensor summary.
We use a helper method instead of having `op` directly call `raw_data_op`
to prevent the scope of `raw_data_op` from being embedded within `op`.
Arguments are the same as for raw_data_op.
Returns:
A tensor summary that collects data for PR curves. |
364,901 | def is_sparse_vector(x):
return sp.issparse(x) and len(x.shape) == 2 and x.shape[0] == 1 | x is a 2D sparse matrix with it's first shape equal to 1. |
364,902 | def create_config(case=None, Exp=, Type=,
Lim=None, Bump_posextent=[np.pi/4., np.pi/4],
R=2.4, r=1., elong=0., Dshape=0.,
divlow=True, divup=True, nP=200,
out=, SavePath=):
if case is not None:
conf = _create_config_testcase(confi... | Create easily a tofu.geom.Config object
In tofu, a Config (short for geometrical configuration) refers to the 3D
geometry of a fusion device.
It includes, at least, a simple 2D polygon describing the first wall of the
fusion chamber, and can also include other structural elements (tiles,
limiters..... |
364,903 | def remove_arrays(code, count=1):
res =
last =
replacements = {}
for e in bracket_split(code, []):
if e[0] == :
if is_array(last):
name = ARRAY_LVAL % count
res += + name
replacements[name] = e
count += 1
... | removes arrays and replaces them with ARRAY_LVALS
returns new code and replacement dict
*NOTE* has to be called AFTER remove objects |
364,904 | def _parse(self, infile):
temp_list_values = self.list_values
if self.unrepr:
self.list_values = False
comment_list = []
done_start = False
this_section = self
maxline = len(infile) - 1
cur_index = -1
reset_comment = False
wh... | Actually parse the config file. |
364,905 | def _format_issue(issue):
ret = {: issue.get(),
: issue.get(),
: issue.get(),
: issue.get(),
: issue.get().get(),
: issue.get()}
assignee = issue.get()
if assignee:
assignee = assignee.get()
labels = issue.get()
label_names = []
... | Helper function to format API return information into a more manageable
and useful dictionary for issue information.
issue
The issue to format. |
364,906 | def set_seeds(self, seeds):
if self.img.shape != seeds.shape:
raise Exception("Seeds must be same size as input image")
self.seeds = seeds.astype("int8")
self.voxels1 = self.img[self.seeds == 1]
self.voxels2 = self.img[self.seeds == 2] | Function for manual seed setting. Sets variable seeds and prepares
voxels for density model.
:param seeds: ndarray (0 - nothing, 1 - object, 2 - background,
3 - object just hard constraints, no model training, 4 - background
just hard constraints, no model training) |
364,907 | def list_files(
client, fileshare, prefix, recursive, timeout=None, snapshot=None):
_check = check_if_single_file(client, fileshare, prefix, timeout)
if _check[0]:
yield _check[1]
return
if snapshot is None:
fileshare, snapshot = \
blobxfe... | List files in path
:param azure.storage.file.FileService client: file client
:param str fileshare: file share
:param str prefix: path prefix
:param bool recursive: recursive
:param int timeout: timeout
:param str snapshot: snapshot
:rtype: azure.storage.file.models.File
:return: generato... |
364,908 | def plotplanarPotentials(Pot,*args,**kwargs):
Pot= flatten(Pot)
Rrange= kwargs.pop(,[0.01,5.])
xrange= kwargs.pop(,[-5.,5.])
yrange= kwargs.pop(,[-5.,5.])
if _APY_LOADED:
if hasattr(Pot,):
tro= Pot._ro
else:
tro= Pot[0]._ro
if isinstance(Rrange[0]... | NAME:
plotplanarPotentials
PURPOSE:
plot a planar potential
INPUT:
Rrange - range (can be Quantity)
xrange, yrange - if relevant (can be Quantity)
grid, gridx, gridy - number of points to plot
savefilename - save to or restore from this savefile (pickle)
... |
364,909 | def sbo_case_insensitive(self):
if "--case-ins" in self.flag:
data = SBoGrep(name="").names()
data_dict = Utils().case_sensitive(data)
for key, value in data_dict.iteritems():
if key == self.name.lower():
self.name = value | Matching packages distinguish between uppercase and
lowercase for sbo repository |
364,910 | def __get_pending_revisions(self):
dttime = time.mktime(datetime.datetime.now().timetuple())
changes = yield self.revisions.find({
"toa" : {
"$lt" : dttime,
},
"processed": False,
"inProcess": None
})
if len(changes... | Get all the pending revisions after the current time
:return: A list of revisions
:rtype: list |
364,911 | def intranges_from_list(list_):
sorted_list = sorted(list_)
ranges = []
last_write = -1
for i in range(len(sorted_list)):
if i+1 < len(sorted_list):
if sorted_list[i] == sorted_list[i+1]-1:
continue
current_range = sorted_list[last_write+1:i+1]
r... | Represent a list of integers as a sequence of ranges:
((start_0, end_0), (start_1, end_1), ...), such that the original
integers are exactly those x such that start_i <= x < end_i for some i.
Ranges are encoded as single integers (start << 32 | end), not as tuples. |
364,912 | def remove_non_ascii(input_string):
no_ascii = "".join(i for i in input_string if ord(i) < 128)
return no_ascii | Remove non-ascii characters
Source: http://stackoverflow.com/a/1342373 |
364,913 | def _generate_base_anchors(base_size, scales, ratios):
base_anchor = np.array([1, 1, base_size, base_size]) - 1
ratio_anchors = AnchorGenerator._ratio_enum(base_anchor, ratios)
anchors = np.vstack([AnchorGenerator._scale_enum(ratio_anchors[i, :], scales)
for... | Generate anchor (reference) windows by enumerating aspect ratios X
scales wrt a reference (0, 0, 15, 15) window. |
364,914 | def _get_firewall_policy(kwargs):
fp_name = kwargs.get(, None)
fp_description = kwargs.get(, None)
firewallPolicy = FirewallPolicy(
name=fp_name,
description=fp_description
)
fpr_json = kwargs.get(, None)
jdata = json.loads(fpr_json)
rules = []
for fwpr in jdata:
... | Construct FirewallPolicy and FirewallPolicy instances from passed arguments |
364,915 | def init_properties(self) -> :
self._pigalle = {
PygalleBaseClass.__KEYS.INTERNALS: dict(),
PygalleBaseClass.__KEYS.PUBLIC: dict()
}
return self | Initialize the Pigalle properties.
# Returns:
PygalleBaseClass: The current instance. |
364,916 | def propagate_paths_and_modules(self, context, paths, modules):
for path in paths:
self.propagate_to(context, mitogen.core.to_text(path))
self.router.responder.forward_modules(context, modules) | One size fits all method to ensure a target context has been preloaded
with a set of small files and Python modules. |
364,917 | def dict_deep_merge(tgt, src):
for k, v in src.items():
if k in tgt:
if isinstance(tgt[k], dict) and isinstance(v, dict):
dict_deep_merge(tgt[k], v)
else:
tgt[k].extend(deepcopy(v))
else:
tgt[k] = deepcopy(v) | Utility function to merge the source dictionary `src` to the target
dictionary recursively
Note:
The type of the values in the dictionary can only be `dict` or `list`
Parameters:
tgt (dict): The target dictionary
src (dict): The source dictionary |
364,918 | def _ParseComment(self, structure):
if structure[1] == :
self._year, self._month, self._day_of_month, _, _, _ = structure.date_time
elif structure[1] == :
self._ParseFieldsMetadata(structure) | Parses a comment.
Args:
structure (pyparsing.ParseResults): structure parsed from the log file. |
364,919 | def get_proxy_session(self):
if not self.supports_proxy():
raise Unimplemented()
try:
from . import sessions
except ImportError:
raise
try:
session = sessions.ProxySession()
except AttributeError:
raise
... | Gets a ``ProxySession`` which is responsible for acquiring authentication credentials on behalf of a service client.
:return: a proxy session for this service
:rtype: ``osid.proxy.ProxySession``
:raise: ``OperationFailed`` -- unable to complete request
:raise: ``Unimplemented`` -- ``sup... |
364,920 | def element_wise(self, func, *args, **kwargs):
s = self.shape
emat = [func(o, *args, **kwargs) for o in self.matrix.ravel()]
return Matrix(np_array(emat).reshape(s)) | Apply a function to each matrix element and return the result in a
new operator matrix of the same shape.
Args:
func (FunctionType): A function to be applied to each element. It
must take the element as its first argument.
args: Additional positional arguments to... |
364,921 | def parse_set(string):
string = string.strip()
if string:
return set(string.split(","))
else:
return set() | Parse set from comma separated string. |
364,922 | def pack_column_flat(self, value, components=None, offset=False):
if components:
if isinstance(components, str):
components = [components]
elif isinstance(components, list):
components = components
else:
raise TypeError... | TODO: add documentation |
364,923 | def ilxSearches(self,
ilx_ids=None,
LIMIT=25,
_print=True,
crawl=False):
url_base = self.base_url + "/api/1/ilx/search/identifier/{identifier}?key={APIKEY}"
urls = [url_base.format(identifier=ilx_id.replace(, ), API... | parameters( data = "list of ilx_ids" ) |
364,924 | def show_xys(self, xs, ys)->None:
"Show the `xs` (inputs) and `ys` (targets)."
from IPython.display import display, HTML
items,names = [], xs[0].names + []
for i, (x,y) in enumerate(zip(xs,ys)):
res = []
cats = x.cats if len(x.cats.size()) > 0 else []
... | Show the `xs` (inputs) and `ys` (targets). |
364,925 | def findLowest(self, symorders):
_range = range(len(symorders))
stableSymorders = map(None, symorders, _range)
stableSymorders.sort()
lowest = None
for index in _range:
if stableSymorders[index][0] == lowest:
return stableSy... | Find the position of the first lowest tie in a
symorder or -1 if there are no ties |
364,926 | def easeOutElastic(n, amplitude=1, period=0.3):
_checkRange(n)
if amplitude < 1:
amplitude = 1
s = period / 4
else:
s = period / (2 * math.pi) * math.asin(1 / amplitude)
return amplitude * 2**(-10*n) * math.sin((n-s)*(2*math.pi / period)) + 1 | An elastic tween function that overshoots the destination and then "rubber bands" into the destination.
Args:
n (float): The time progress, starting at 0.0 and ending at 1.0.
Returns:
(float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine(). |
364,927 | def _remove_mapper_from_plotter(plotter, actor, reset_camera):
try:
mapper = actor.GetMapper()
except AttributeError:
return
for name in list(plotter._scalar_bar_mappers.keys()):
try:
plotter._scalar_bar_mappers[name].remove(mapper)
except ValueError:
... | removes this actor's mapper from the given plotter's _scalar_bar_mappers |
364,928 | def plot(self, *args, **kwargs):
import sys
assert "matplotlib" in sys.modules, "matplotlib package has not been imported."
from ...plotting.matplot_dep import variational_plots
return variational_plots.plot_SpikeSlab(self,*args, **kwargs) | Plot latent space X in 1D:
See GPy.plotting.matplot_dep.variational_plots |
364,929 | def _update_zipimporter_cache(normalized_path, cache, updater=None):
for p in _collect_zipimporter_cache_entries(normalized_path, cache):
old_entry = cache[p]
del cache[p]
new_entry = updater and updater(p,... | Update zipimporter cache data for a given normalized path.
Any sub-path entries are processed as well, i.e. those corresponding to zip
archives embedded in other zip archives.
Given updater is a callable taking a cache entry key and the original entry
(after already removing the entry from the cache),... |
364,930 | def required_max_memory(cls, id, memory):
best = int(max(2 ** math.ceil(math.log(memory, 2)), 2048))
actual_vm = cls.info(id)
if (actual_vm[] ==
and actual_vm[] != best):
return best | Recommend a max_memory setting for this vm given memory. If the
VM already has a nice setting, return None. The max_memory
param cannot be fixed too high, because page table allocation
would cost too much for small memory profile. Use a range as below. |
364,931 | def average_sources(source_encoded: mx.sym.Symbol, source_encoded_length: mx.sym.Symbol) -> mx.nd.NDArray:
source_masked = mx.sym.SequenceMask(data=source_encoded,
axis=1,
sequence_length=source_encoded_len... | Calculate the average of encoded sources taking into account their lengths.
:param source_encoded: Encoder representation for n elements. Shape: (n, source_encoded_length, hidden_size).
:param source_encoded_length: A vector of encoded sequence lengths. Shape: (n,).
:return: Average vectors. Sh... |
364,932 | def get_header(self, service_id, version_number, name):
content = self._fetch("/service/%s/version/%d/header/%s" % (service_id, version_number, name))
return FastlyHeader(self, content) | Retrieves a Header object by name. |
364,933 | def u2i(uint32):
mask = (2 ** 32) - 1
if uint32 & (1 << 31):
v = uint32 | ~mask
else:
v = uint32 & mask
return v | Converts a 32 bit unsigned number to signed.
uint32:= an unsigned 32 bit number
...
print(u2i(4294967272))
-24
print(u2i(37))
37
... |
364,934 | def value_equality(cls: type = None,
*,
unhashable: bool = False,
distinct_child_types: bool = False,
manual_cls: bool = False,
approximate: bool = False
) -> Union[Callable[[type], type], type]:
... | Implements __eq__/__ne__/__hash__ via a _value_equality_values_ method.
_value_equality_values_ is a method that the decorated class must implement.
_value_equality_approximate_values_ is a method that the decorated class
might implement if special support for approximate equality is required.
This is... |
364,935 | def _output_format(cls, func, override=None):
@wraps(func)
def _format_wrapper(self, *args, **kwargs):
call_response, data_key, meta_data_key = func(
self, *args, **kwargs)
if in self.output_format.lower() or \
in self.output_format.... | Decorator in charge of giving the output its right format, either
json or pandas
Keyword Arguments:
func: The function to be decorated
override: Override the internal format of the call, default None |
364,936 | def build_from_node(package, node):
team, owner, pkg, subpath = parse_package(package, allow_subpath=True)
_check_team_id(team)
store = PackageStore()
pkg_root = get_or_create_package(store, team, owner, pkg, subpath)
if not subpath and not isinstance(node, nodes.GroupNode):
raise Com... | Compile a Quilt data package from an existing package node. |
364,937 | def _start_server(self, *args):
self.log("Starting server", args)
secure = self.certificate is not None
if secure:
self.log("Running SSL server with cert:", self.certificate)
else:
self.log("Running insecure server without SSL. Do not use without SSL pro... | Run the node local server |
364,938 | def add_albumart(albumart, song_title):
try:
img = urlopen(albumart)
except Exception:
log.log_error("* Could not add album art", indented=True)
return None
audio = EasyMP3(song_title, ID3=ID3)
try:
audio.add_tags()
except _util.error:
pass
audi... | Adds the album art to the song |
364,939 | def fill_luis_event_properties(
self,
recognizer_result: RecognizerResult,
turn_context: TurnContext,
telemetry_properties: Dict[str, str] = None,
) -> Dict[str, str]:
intents = recognizer_result.intents
top_two_intents = (
sorted(intents.keys(),... | Fills the event properties for LuisResult event for telemetry.
These properties are logged when the recognizer is called.
:param recognizer_result: Last activity sent from user.
:type recognizer_result: RecognizerResult
:param turn_context: Context object containing information ... |
364,940 | def default_metadata_db_path():
home = expanduser("~")
home = os.path.abspath(os.path.join(home, , ))
return home | Helper to get the default path for the metadata file.
:returns: The path to where the default location of the metadata
database is. Maps to which is ~/.inasafe.metadata35.db
:rtype: str |
364,941 | def human_filesize(i):
bytes = float(i)
if bytes < 1024:
return u"%d Byte%s" % (bytes, bytes != 1 and u"s" or u"")
if bytes < 1024 * 1024:
return u"%.1f KB" % (bytes / 1024)
if bytes < 1024 * 1024 * 1024:
return u"%.1f MB" % (bytes / (1024 * 1024))
return u"%.1f GB" % (b... | 'human-readable' file size (i.e. 13 KB, 4.1 MB, 102 bytes, etc). |
364,942 | def getParameterByName(self, name):
result = None
for parameter in self.getParameters():
nameParam = parameter.getName()
if nameParam == name:
result = parameter
break
return result | Searchs a parameter by name and returns it. |
364,943 | def meff_lh_110(self, **kwargs):
return 2. / (2 * self.luttinger1(**kwargs) + self.luttinger2(**kwargs)
+ 3 * self.luttinger3(**kwargs)) | Returns the light-hole band effective mass in the [110] direction,
meff_lh_110, in units of electron mass. |
364,944 | def _load_relation(self, models, name, constraints):
relation = self.get_relation(name)
relation.add_eager_constraints(models)
if callable(constraints):
constraints(relation)
else:
relation.merge_query(constraints)
models = relation.init_relati... | Eagerly load the relationship on a set of models.
:rtype: list |
364,945 | def intrinsics_multi_constructor(loader, tag_prefix, node):
tag = node.tag[1:]
prefix = "Fn::"
if tag in ["Ref", "Condition"]:
prefix = ""
cfntag = prefix + tag
if tag == "GetAtt" and isinstance(node.value, six.string_types):
value = node... | YAML constructor to parse CloudFormation intrinsics.
This will return a dictionary with key being the instrinsic name |
364,946 | def unArrayify(self, gene):
g = 0
for layer in self.layers:
if layer.type != :
for i in range(layer.size):
layer.weight[i] = float( gene[g])
g += 1
for connection in self.connections:
for i in range... | Copies gene bias values and weights to network bias values and
weights. |
364,947 | def age_simulants(self, event: Event):
population = self.population_view.get(event.index, query="alive == ")
population[] += event.step_size / pd.Timedelta(days=365)
self.population_view.update(population) | Updates simulant age on every time step.
Parameters
----------
event :
An event object emitted by the simulation containing an index
representing the simulants affected by the event and timing
information. |
364,948 | def multiple_outputs_from_file(cls, filename, keep_sub_files=True):
to_return = []
with zopen(filename, ) as f:
text = re.split(r,
f.read())
if text[0] == :
text = text[1:]
for i, sub_text in enumerate(text):
temp =... | Parses a QChem output file with multiple calculations
1.) Seperates the output into sub-files
e.g. qcout -> qcout.0, qcout.1, qcout.2 ... qcout.N
a.) Find delimeter for multiple calcualtions
b.) Make seperate output sub-files
2.) Creates seperate Q... |
364,949 | def p_x_commalist(self,t):
if len(t) == 2: t[0] = CommaX([t[1]])
elif len(t) == 4: t[0] = CommaX(t[1].children+[t[3]])
else: raise NotImplementedError(,len(t)) | commalist : commalist ',' expression
| expression |
364,950 | def _assert_refspec(self):
config = self.config_reader
unset =
try:
if config.get_value(, default=unset) is unset:
msg = "Remote has no refspec set.\n"
msg += "You can set it as follows:"
msg += " ."
raise Ass... | Turns out we can't deal with remotes if the refspec is missing |
364,951 | def get_overlapping_ranges(self, collection_link, sorted_ranges):
if not self._is_sorted_and_non_overlapping(sorted_ranges):
raise ValueError("the list of ranges is not a non-overlapping sorted ranges")
target_partition_key_ranges = []
it ... | Given the sorted ranges and a collection,
Returns the list of overlapping partition key ranges
:param str collection_link:
The collection link.
:param (list of routing_range._Range) sorted_ranges: The sorted list of non-overlapping ranges.
:return:
List o... |
364,952 | def fail(self, err=, *args, **kwargs):
kwargs.setdefault(, 0)
kwargs[] |= REPLY_FLAGS[]
kwargs[] = err
self.replies(*args, **kwargs)
return True | Reply to a query with the QueryFailure flag and an '$err' key.
Returns True so it is suitable as an `~MockupDB.autoresponds` handler. |
364,953 | def save_current_nb_as_html(info=False):
assert in_ipynb()
full_path = get_notebook_name()
path, filename = os.path.split(full_path)
wd_save = os.getcwd()
os.chdir(path)
cmd = .format(filename)
os.system(cmd)
os.chdir(wd_save)
if info:
print("target dir: ", path)
... | Save the current notebook as html file in the same directory |
364,954 | def convert_command_output(*command):
captured_output = capture(command)
converted_output = convert(captured_output)
if connected_to_terminal():
fd, temporary_file = tempfile.mkstemp(suffix=)
with open(temporary_file, ) as handle:
handle.write(converted_output)
webbr... | Command line interface for ``coloredlogs --to-html``.
Takes a command (and its arguments) and runs the program under ``script``
(emulating an interactive terminal), intercepts the output of the command
and converts ANSI escape sequences in the output to HTML. |
364,955 | def __send_static_file(self, path=None):
if not path:
path =
file_name = join(self.folder_path, path)
if self.dynamic_url and path == :
return self.__send_api_file(file_name)
if self.allow_absolute_url and path == :
retu... | Send apidoc files from the apidoc folder to the browser.
:param path: the apidoc file. |
364,956 | def parse_declaration_expressn_fncall_SUBparams(self, params):
if isinstance(params, wdl_parser.Terminal):
raise NotImplementedError
elif isinstance(params, wdl_parser.Ast):
raise NotImplementedError
elif isinstance(params, wdl_parser.AstList):
... | Needs rearrangement:
0 1 2
WDL native params: sub(input, pattern, replace)
1 2 0
Python's re.sub() params: sub(pattern, replace, input)
:param params:
:param es:
:return: |
364,957 | def auth_stage2(self,stanza):
self.lock.acquire()
try:
self.__logger.debug("Procesing auth response...")
self.available_auth_methods=[]
if (stanza.xpath_eval("a:query/a:digest",{"a":"jabber:iq:auth"}) and self.stream_id):
self.available_auth_m... | Handle the first stage authentication response (result of the <iq
type="get"/>).
[client only] |
364,958 | def get_field(hologram, sideband=+1, filter_name="disk", filter_size=1 / 3,
subtract_mean=True, zero_pad=True, copy=True):
if copy:
hologram = hologram.astype(dtype=np.float, copy=True)
if subtract_mean:
if issubclass(hologram.dtype.type, np.integer... | Compute the complex field from a hologram using Fourier analysis
Parameters
----------
hologram: real-valued 2d ndarray
hologram data
sideband: +1, -1, or tuple of (float, float)
specifies the location of the sideband:
- +1: sideband in the upper half in Fourier space,
... |
364,959 | def get_as_string(self, s3_path, encoding=):
content = self.get_as_bytes(s3_path)
return content.decode(encoding) | Get the contents of an object stored in S3 as string.
:param s3_path: URL for target S3 location
:param encoding: Encoding to decode bytes to string
:return: File contents as a string |
364,960 | def query_struct(self, name):
sql = \
self.cursor.execute(sql, (name,))
for i in self.cursor.fetchall():
sql = \
self.cursor.execute(sql, (i[0],))
members = self.cursor.fetchall()
if members:
... | Query struct. |
364,961 | def _check_pending(self, tag, match_func=None):
if match_func is None:
match_func = self._get_match_func()
old_events = self.pending_events
self.pending_events = []
ret = None
for evt in old_events:
if match_func(evt[], tag):
if re... | Check the pending_events list for events that match the tag
:param tag: The tag to search for
:type tag: str
:param tags_regex: List of re expressions to search for also
:type tags_regex: list[re.compile()]
:return: |
364,962 | def _obj_index(self, uri, base_path, marked_path, headers, spr=False):
object_list = list()
l_obj = None
container_uri = uri.geturl()
while True:
marked_uri = urlparse.urljoin(container_uri, marked_path)
resp = self.http.get(url=marked_uri, headers=heade... | Return an index of objects from within the container.
:param uri:
:param base_path:
:param marked_path:
:param headers:
:param spr: "single page return" Limit the returned data to one page
:type spr: ``bol``
:return: |
364,963 | def _deserialization_helper(self, state, ray_forking):
worker = ray.worker.get_global_worker()
worker.check_connected()
if state["ray_forking"]:
actor_handle_id = state["actor_handle_id"]
else:
... | This is defined in order to make pickling work.
Args:
state: The serialized state of the actor handle.
ray_forking: True if this is being called because Ray is forking
the actor handle and false if it is being called by pickling. |
364,964 | def main(pub_port=None, sub_port=None):
try:
if sub_port is None:
sub_port = get_sub_port()
if pub_port is None:
pub_port = get_pub_port()
context = zmq.Context(1)
frontend = context.socket(zmq.SUB)
backend = context.socket(zmq.PUB)
front... | main of forwarder
:param sub_port: port for subscribers
:param pub_port: port for publishers |
364,965 | def build_sector_fundamentals(sector):
ll get the data we need for each stock
in the sector from IEX. Once we have the data, well put stocks that meet those
requirements into a dataframe along with all the data about them we
stocks = get_sector(sector)
if len(stocks) == 0:
raise ValueError("... | In this method, for the given sector, we'll get the data we need for each stock
in the sector from IEX. Once we have the data, we'll check that the earnings
reports meet our criteria with `eps_good()`. We'll put stocks that meet those
requirements into a dataframe along with all the data about them we'll ne... |
364,966 | def tags(self):
if in self._values:
return self._values[]
self._values[] = copy.deepcopy(self._defaults[])
return self._values[] | The tags property.
Returns:
(hash). the property value. (defaults to: {}) |
364,967 | def submit(self, command=, blocksize=1, job_name="parsl.auto"):
job_name = "parsl.auto.{0}".format(time.time())
[instance, *rest] = self.deployer.deploy(command=command, job_name=job_name, blocksize=1)
if not instance:
logger.error("Failed to submit request to Azure")
... | Submit command to an Azure instance.
Submit returns an ID that corresponds to the task that was just submitted.
Parameters
----------
command : str
Command to be invoked on the remote side.
blocksize : int
Number of blocks requested.
job_name : s... |
364,968 | def _children(self):
if isinstance(self.condition, CodeExpression):
yield self.condition
for codeobj in self.body._children():
yield codeobj
for codeobj in self.else_body._children():
yield codeobj | Yield all direct children of this object. |
364,969 | def is_false(self, e, extra_constraints=(), solver=None, model_callback=None):
if not isinstance(e, Base):
return self._is_false(self.convert(e), extra_constraints=extra_constraints, solver=solver, model_callback=model_callback)
try:
return self._fals... | Should return True if e can be easily found to be False.
:param e: The AST
:param extra_constraints: Extra constraints (as ASTs) to add to the solver for this solve.
:param solver: A solver, for backends that require it
:param model_callback: a func... |
364,970 | def setup_simulation(components: List, input_config: Mapping=None,
plugin_config: Mapping=None) -> InteractiveContext:
simulation = initialize_simulation(components, input_config, plugin_config)
simulation.setup()
return simulation | Construct a simulation from a list of components and call its setup
method.
Parameters
----------
components
A list of initialized simulation components. Corresponds to the
components block of a model specification.
input_config
A nested dictionary with any additional simula... |
364,971 | def stdout():
byte_stdout = sys.stdout
if sys.version_info.major > 2:
byte_stdout = sys.stdout.buffer
return byte_stdout | Returns the stdout as a byte stream in a Py2/PY3 compatible manner
Returns
-------
io.BytesIO
Byte stream of Stdout |
364,972 | def get_unique_named_object(root, name):
a = get_children(lambda x: hasattr(x, ) and x.name == name, root)
assert len(a) == 1
return a[0] | retrieves a unique named object (no fully qualified name)
Args:
root: start of search
name: name of object
Returns:
the object (if not unique, raises an error) |
364,973 | def to_browser_mode(self):
for message_no in range(len(self.messages)):
self.__to_browser(message_no) | Write all the messages to files and open them in the browser |
364,974 | def fetch_chain(self, certr, max_length=10):
action = LOG_ACME_FETCH_CHAIN()
with action.context():
if certr.cert_chain_uri is None:
return succeed([])
elif max_length < 1:
raise errors.ClientError()
return (
De... | Fetch the intermediary chain for a certificate.
:param acme.messages.CertificateResource certr: The certificate to
fetch the chain for.
:param int max_length: The maximum length of the chain that will be
fetched.
:rtype: Deferred[List[`acme.messages.CertificateResource`... |
364,975 | def Nu_Xu(Re, Pr, rho_w=None, rho_b=None, mu_w=None, mu_b=None):
ran Jiaotong University 39,
468-471.
.. [2] Chen, Weiwei, Xiande Fang, Yu Xu, and Xianghui Su. "An Assessment of
Correlations of Forced Convection Heat Transfer to Water at
Supercritical Pressure." Annals of Nuclear Energy 7... | r'''Calculates internal convection Nusselt number for turbulent vertical
upward flow in a pipe under supercritical conditions according to [1]_.
.. math::
Nu_b = 0.02269 Re_b^{0.8079} \bar{Pr}_b^{0.9213}
\left(\frac{\rho_w}{\rho_b}\right)^{0.6638}
\left(\frac{\mu_w}{\mu_b}\right... |
364,976 | def get_end_date_metadata(self):
metadata = dict(self._mdata[])
metadata.update({: self._my_map[]})
return Metadata(**metadata) | Gets the metadata for an end date.
return: (osid.Metadata) - metadata for the date
*compliance: mandatory -- This method must be implemented.* |
364,977 | def get_authors_by_keyword(keyword: str, graph=None, authors=None) -> Set[str]:
keyword_lower = keyword.lower()
if authors is not None:
return {
author
for author in authors
if keyword_lower in author.lower()
}
if graph is None:
raise ValueE... | Get authors for whom the search term is a substring.
:param pybel.BELGraph graph: A BEL graph
:param keyword: The keyword to search the author strings for
:param set[str] authors: An optional set of pre-cached authors calculated from the graph
:return: A set of authors with the keyword as a substri... |
364,978 | def recent_update_frequencies(self):
return list(reversed([(1.0 / p) for p in numpy.diff(self._recent_updates)])) | Returns the 10 most recent update frequencies.
The given frequencies are computed as short-term frequencies!
The 0th element of the list corresponds to the most recent frequency. |
364,979 | def execute(sql, args=None, key=):
database = __db[key]
return database.execute(sql, args) | It is used for update, delete records.
:param sql string: the sql stamtement like 'select * from %s'
:param args list: Wen set None, will use dbi execute(sql), else
dbi execute(sql, args), the args keep the original rules, it shuld be tuple or list of list
:param key: a key for your dabtabase ... |
364,980 | def mtf_bitransformer_all_layers_tiny():
hparams = mtf_bitransformer_tiny()
hparams.moe_num_experts = 4
hparams.moe_expert_x = 4
hparams.moe_expert_y = 4
hparams.moe_hidden_size = 512
hparams.encoder_layers = [
"self_att", "local_self_att", "moe_1d", "moe_2d", "drd"]
hparams.decoder_layers = [
... | Test out all the layers on local CPU. |
364,981 | def add_tar_opts (cmdlist, compression, verbosity):
progname = os.path.basename(cmdlist[0])
if compression == :
cmdlist.append()
elif compression == :
cmdlist.append()
elif compression == :
cmdlist.append()
elif compression in (, ) and progname == :
cmdlist.appen... | Add tar options to cmdlist. |
364,982 | def _modules_to_main(modList):
if not modList:
return
main = sys.modules[]
for modname in modList:
if isinstance(modname, str):
try:
mod = __import__(modname)
except Exception:
sys.stderr.write(
% modname)
print_exec(sys.stderr... | Force every module in modList to be placed into main |
364,983 | def put(request, obj_id=None):
res = Result()
data = request.PUT or json.loads(request.body)[]
if obj_id:
tag = Tag.objects.get(pk=obj_id)
tag.name = data.get(, tag.name)
tag.artist = data.get(, tag.artist)
tag.save()
else:
tags = [_ for _ in data.ge... | Adds tags from objects resolved from guids
:param tags: Tags to add
:type tags: list
:param guids: Guids to add tags from
:type guids: list
:returns: json |
364,984 | def _scaleTo8bit(self, img):
r = scaleSignalCutParams(img, 0.02)
self.signal_ranges.append(r)
return toUIntArray(img, dtype=np.uint8, range=r) | The pattern comparator need images to be 8 bit
-> find the range of the signal and scale the image |
364,985 | def loadedfields(self):
if self._loadedfields is None:
for field in self._meta.scalarfields:
yield field
else:
fields = self._meta.dfields
processed = set()
for name in self._loadedfields:
if name in processed:
... | Generator of fields loaded from database |
364,986 | def _add_timedelta(self, delta):
if isinstance(delta, pendulum.Period):
return self.add(
years=delta.years,
months=delta.months,
weeks=delta.weeks,
days=delta.remaining_days,
hours=delta.hours,
m... | Add timedelta duration to the instance.
:param delta: The timedelta instance
:type delta: pendulum.Duration or datetime.timedelta
:rtype: DateTime |
364,987 | def write_to(self, group, append=False):
write_index(self, group, append)
self._entries[].write_to(group)
self._entries[].write_to(group, append)
self._entries[].write_to(group)
if self.has_properties():
self._entries[].write_to(group, append=append) | Write the data to the given group.
:param h5py.Group group: The group to write the data on. It is
assumed that the group is already existing or initialized
to store h5features data (i.e. the method
``Data.init_group`` have been called.
:param bool append: If False, ... |
364,988 | def add_error(self, txt):
self.configuration_errors.append(txt)
self.conf_is_correct = False | Add a message in the configuration errors list so we can print them
all in one place
Set the object configuration as not correct
:param txt: error message
:type txt: str
:return: None |
364,989 | def get_did_providers(self, did):
register_values = self.contract_concise.getDIDRegister(did)
if register_values and len(register_values) == 5:
return DIDRegisterValues(*register_values).providers
return None | Return the list providers registered on-chain for the given did.
:param did: hex str the id of an asset on-chain
:return:
list of addresses
None if asset has no registerd providers |
364,990 | def tpu_conv1d(inputs, filters, kernel_size, padding="SAME", name="tpu_conv1d"):
if kernel_size == 1:
return dense(inputs, filters, name=name, use_bias=True)
if padding == "SAME":
assert kernel_size % 2 == 1
first_offset = -((kernel_size - 1) // 2)
else:
assert padding == "LEFT"
first_offse... | Version of conv1d that works on TPU (as of 11/2017).
Args:
inputs: a Tensor with shape [batch, length, input_depth].
filters: an integer.
kernel_size: an integer.
padding: a string - "SAME" or "LEFT".
name: a string.
Returns:
a Tensor with shape [batch, length, filters]. |
364,991 | def get_address(name, hash, db, target=None):
key = DB.pkey([EZO.DEPLOYED, name, target, hash])
d, err = db.get(key)
if err:
return None, err
if not d:
return None, None
return d[].lower(), None | fetches the contract address of deployment
:param hash: the contract file hash
:return: (string) address of the contract
error, if any |
364,992 | def decode_body(cls, header, f):
assert header.packet_type == MqttControlPacketType.pingreq
if header.remaining_len != 0:
raise DecodeError()
return 0, MqttPingreq() | Generates a `MqttPingreq` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `pingreq`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
Raises
------
DecodeError
... |
364,993 | def list(self, *kinds, **kwargs):
if len(kinds) == 0:
kinds = self.kinds
if len(kinds) == 1:
kind = kinds[0]
logging.debug("Inputs.list taking short circuit branch for single kind.")
path = self.kindpath(kind)
logging.debug("Path for i... | Returns a list of inputs that are in the :class:`Inputs` collection.
You can also filter by one or more input kinds.
This function iterates over all possible inputs, regardless of any arguments you
specify. Because the :class:`Inputs` collection is the union of all the inputs of each
ki... |
364,994 | def wunique_(self, col):
try:
s = pd.value_counts(self.df[col].values)
df = pd.DataFrame(s, columns=["Number"])
return df
except Exception as e:
self.err(e, "Can not weight unique data") | Weight unique values: returns a dataframe with a count
of unique values |
364,995 | def all_phrase_translations(phrase):
if not trees:
init()
phrase = phrase.split(string.whitespace)
for word in phrase:
for x in range(len(word)):
for translation in _words_at_the_beginning(
word[x+1:],
trees[][word[x]],
... | Return the set of translations for all possible words in a full
phrase. Chinese is sometimes ambiguous. We do not attempt to
disambiguate, or handle unknown letters especially well. Full
parsing is left to upstream logic. |
364,996 | def _hue(color, **kwargs):
h = colorsys.rgb_to_hls(*[x / 255.0 for x in color.value[:3]])[0]
return NumberValue(h * 360.0) | Get hue value of HSL color. |
364,997 | def dependent_on_composite_state(self):
composite_state = NodesCompositeState()
for dependent_on in self.tree.dependent_on:
node_b = self.find_counterpart_in(dependent_on)
if node_b is None:
continue
... | method iterates over all nodes that provide dependency to the current node,
and compile composite state of them all
:return instance of <NodesCompositeState> |
364,998 | def get_year_start(day=None):
day = add_timezone(day or datetime.date.today())
return day.replace(month=1).replace(day=1) | Returns January 1 of the given year. |
364,999 | def _construct_key(self, rule_id: str, spacy_rule_id:int) -> int:
hash_key = (rule_id, spacy_rule_id)
hash_v = hash(hash_key) + sys.maxsize + 1
self._hash_map[hash_v] = hash_key
return hash_v | Use a mapping to store the information about rule_id for each matches, create the mapping key here
Args:
rule_id: str
spacy_rule_id:int
Returns: int |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.