Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
354,000 | def set_fields(self, changeset):
self.id = int(changeset.get())
self.user = changeset.get()
self.uid = changeset.get()
self.editor = changeset.get(, None)
self.review_requested = changeset.get(, False)
self.host = changeset.get(, )
self.bbox = changeset.g... | Set the fields of this class with the metadata of the analysed
changeset. |
354,001 | def _delete_account(self, username):
ds_user = self.get_user(username)
if ds_user is not None:
self._call(["delete", "user", "name=%s" % username])
return | Called when account is deleted. With username override. |
354,002 | def add_one_en_passant_move(self, direction, position):
try:
if self._is_en_passant_valid(direction(self.location), position):
yield self.create_move(
end_loc=self.square_in_front(direction(self.location)),
status=notation_const.EN_PAS... | Yields en_passant moves in given direction if it is legal.
:type: direction: function
:type: position: Board
:rtype: gen |
354,003 | def visit_Name(self, node):
if (isinstance(node.ctx, ast.Load) and
node.id not in self.local_decl and
node.id in self.to_expand):
self.update = True
return ast.Call(func=node,
args=[], keywords=[])
return node | Turn global variable used not shadows to function call.
We check it is a name from an assignment as import or functions use
should not be turn into call. |
354,004 | def tags(self):
tags = self.attrs.get()
if tags is None:
tags = []
return [tag for tag in tags if tag != ] | The image's tags. |
354,005 | def units(self):
if "units" in self.attrs.keys():
try:
self.attrs["units"] = self.attrs["units"].decode()
except AttributeError:
pass
return self.attrs["units"]
return None | Units. |
354,006 | def _with_rotation(self, w, h):
res_w = abs(w * math.cos(self.rotation) + h * math.sin(self.rotation))
res_h = abs(h * math.cos(self.rotation) + w * math.sin(self.rotation))
return res_w, res_h | calculate the actual dimensions after rotation |
354,007 | def csv_export(self, request):
response = HttpResponse(content_type=)
response[] =
writer = UnicodeWriter(response)
writer.writerow([
, , , , ,
, , , , ,
, ,
])
try:
... | Return a CSV document of the competition entry and its user
details |
354,008 | def create_entity(self, entity_type, term_ids, id=None):
new_entity = Centity(type=self.type)
if id is None:
n = 1 if self.entity_layer is None else len(self.entity_layer.map_entity_id_to_node) + 1
id = "e{n}".format(**locals())
new_entity.set_id(id)
new_... | Create a new (named) entity and add it to the entities layer
@type entity_type: string
@param entity_type: The type of the entity
@type term_ids: list
@param term_ids: list of term ids
@type id: string
@param id: optional id of the entity |
354,009 | def _flushBuffer(self, request):
assert request is self.requestSession.request
self.requestSession.writeData(self.buffer)
self.buffer = [] | Flush any pending data from the buffer to the request |
354,010 | def supports_ansi_escape_codes(fd):
if os.isatty(fd):
return True
if not is_win:
return False
handle = winapi._get_osfhandle(fd)
if handle == winapi.INVALID_HANDLE_VALUE:
return False
if winapi.GetFileType(handle) != winapi.FILE_TYPE_PIPE:
return False
... | Returns whether the output device is capable of interpreting ANSI escape
codes when :func:`print_` is used.
Args:
fd (int): file descriptor (e.g. ``sys.stdout.fileno()``)
Returns:
`bool` |
354,011 | def send(self, data):
self.logger.debug( % data)
self.client.sendall(data.encode()) | Send encoded instructions to Guacamole guacd server. |
354,012 | def serve(self, app_docopt=DEFAULT_DOC, description=):
exit_status = 0
if isinstance(app_docopt, str):
args = docopt(app_docopt, version=description)
elif isinstance(app_docopt, dict):
args = app_docopt
else:
raise ValueError(
... | Configure from cli and run the server |
354,013 | def info(self, byte_offset=0):
return self.buffer, self.byteLength, byte_offset + self.byteOffset | Get the underlying buffer info
:param byte_offset: byte offset from accessor
:return: buffer, byte_length, byte_offset |
354,014 | def init_editing_mode(self, e):
u
self._bind_exit_key(u)
self._bind_exit_key(u)
self._bind_key(u, self.self_insert)
self._bind_key(u, self.self_insert)
self._bind_key(u, self.accept_line)
self._bind_key(u, self... | u'''When in vi command mode, this causes a switch to emacs editing
mode. |
354,015 | def buildprior(self, prior, mopt=None, extend=False):
" Extract the model's parameters from prior. "
newprior = {}
intercept, slope = gv.get_dictkeys(
prior, [self.intercept, self.slope]
)
newprior[intercept] = prior[intercept]
if mopt is None:
... | Extract the model's parameters from prior. |
354,016 | def collections(self):
iterator = self._firestore_api.list_collection_ids(
self._database_string, metadata=self._rpc_metadata
)
iterator.client = self
iterator.item_to_value = _item_to_collection_ref
return iterator | List top-level collections of the client's database.
Returns:
Sequence[~.firestore_v1beta1.collection.CollectionReference]:
iterator of subcollections of the current document. |
354,017 | def run(self, dag):
swaps = dag.op_nodes(SwapGate)
for swap in swaps:
final_successor = []
for successor in dag.successors(swap):
final_successor.append(successor.type == or (successor.type == and
... | Return a new circuit that has been optimized. |
354,018 | def get_compaction_options(model):
if not model.__compaction__:
return {}
result = {:model.__compaction__}
def setter(key, limited_to_strategy = None):
mkey = "__compaction_{}__".format(key)
tmp = getattr(model, mkey)
if tmp and limited_to_strategy and limited... | Generates dictionary (later converted to a string) for creating and altering
tables with compaction strategy
:param model:
:return: |
354,019 | def file_save(self, name, filename=None, folder="", keep_ext=True) -> bool:
if name in self.files:
file_object = self.files[name]
clean_filename = secure_filename(file_object.filename)
if filename is not None and keep_ext:
clean_filename = filen... | Easy save of a file |
354,020 | def calc_pvalues(query, gene_sets, background=20000, **kwargs):
k = len(query)
query = set(query)
vals = []
if isinstance(background, set):
bg = len(background)
query = query.intersection(background)
elif isinstance(background, int):
bg = back... | calculate pvalues for all categories in the graph
:param set query: set of identifiers for which the p value is calculated
:param dict gene_sets: gmt file dict after background was set
:param set background: total number of genes in your annotated database.
:returns: pvalues
x: overlapped... |
354,021 | def create(self, name, suffix, description, default_value, display=None):
data = ApiParams()
data[] = name
data[] = suffix
data[] = description
data[] = default_value
data[] = display
return self._post(, data=data)[] | Create a new Metric
:param str name: Name of metric
:param str suffix: Metric unit
:param str description: Description of what the metric is measuring
:param int default_value: Default value to use when a point is added
:param int display: Display the chart on the status page
... |
354,022 | def _set_session(self, username, realname, email, language):
self._session.loggedin = True
self._session.email = email
self._session.username = username
self._session.realname = realname
self._session.language = language
self._session.token = None
if "lti... | Init the session. Preserves potential LTI information. |
354,023 | def route_table_present(name, vpc_name=None, vpc_id=None, routes=None,
subnet_ids=None, subnet_names=None, tags=None,
region=None, key=None, keyid=None, profile=None):
ret = {: name,
: True,
: ,
: {}
}
_ret = _rout... | Ensure route table with routes exists and is associated to a VPC.
This function requires boto3 to be installed if nat gatewyas are specified.
Example:
.. code-block:: yaml
boto_vpc.route_table_present:
- name: my_route_table
- vpc_id: vpc-123456
- routes:
... |
354,024 | def running_window(iterable, size):
if size > len(iterable):
raise ValueError("size can not be greater than length of iterable.")
fifo = collections.deque(maxlen=size)
for i in iterable:
fifo.append(i)
if len(fifo) == size:
yield list(fifo) | Generate n-size running window.
Example::
>>> for i in running_windows([1, 2, 3, 4, 5], size=3):
... print(i)
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
**中文文档**
简单滑窗函数。 |
354,025 | def on_get(resc, req, resp):
signals.pre_req.send(resc.model)
signals.pre_req_search.send(resc.model)
models = goldman.sess.store.search(resc.rtype, **{
: req.filters,
: req.pages,
: req.sorts,
})
props = to_rest_models(models, includes=req.includes)
resp.serializ... | Get the models identified by query parameters
We return an empty list if no models are found. |
354,026 | def _set_fabric_dport(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=fabric_dport.fabric_dport, is_container=, presence=False, yang_name="fabric-dport", rest_name="dport", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, regis... | Setter method for fabric_dport, mapped from YANG variable /interface/fortygigabitethernet/fabric/fabric_dport (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_fabric_dport is considered as a private
method. Backends looking to populate this variable should
do ... |
354,027 | def allocate_correlation_matrix(self, iteration = None):
if (self._ccore_sync_dynamic_pointer is not None):
return wrapper.sync_dynamic_allocate_correlation_matrix(self._ccore_sync_dynamic_pointer, iteration);
if ( (self._dynamic is None) or (len(self._dynami... | !
@brief Allocate correlation matrix between oscillators at the specified step of simulation.
@param[in] iteration (uint): Number of iteration of simulation for which correlation matrix should be allocated.
If iternation number is not specified, the last step of s... |
354,028 | def connect(workbench):
d = _getContextFactory(getDataPath(), workbench)
d.addCallback(_connectWithContextFactory, workbench)
return d | Connection inititalization routine. |
354,029 | def focus(self):
self._has_focus = True
self._frame.move_to(self._x, self._y, self._h)
if self._on_focus is not None:
self._on_focus() | Call this to give this Widget the input focus. |
354,030 | def check_block_spacing(
self,
first_block_type: LineType,
second_block_type: LineType,
error_message: str,
) -> typing.Generator[AAAError, None, None]:
numbered_lines = list(enumerate(self))
first_block_lines = filter(lambda l: l[1] is first_block_type, numb... | Checks there is a clear single line between ``first_block_type`` and
``second_block_type``.
Note:
Is tested via ``check_arrange_act_spacing()`` and
``check_act_assert_spacing()``. |
354,031 | def remote_call(request, cls, method, args, kw):
actor = request.actor
name = % cls.__name__
if not hasattr(actor, name):
object = cls(actor)
setattr(actor, name, object)
else:
object = getattr(actor, name)
method_name = % (PREFIX, method)
return getattr(object, me... | Command for executing remote calls on a remote object |
354,032 | def twirl_url(self):
return construct_api_url(self.input, , self.resolvers, False, self.get3d, False, **self.kwargs) | Url of a TwirlyMol 3D viewer. |
354,033 | def get_access_token(self):
if self._token:
now = time.time()
if self.token_expires_at - now > 60:
return self._token
json = self.grant_token()
self._token = json["access_token"]
self.token_expires_at = int(time.time()) + json["expires_in"... | 判断现有的token是否过期。
用户需要多进程或者多机部署可以手动重写这个函数
来自定义token的存储,刷新策略。
:return: 返回token |
354,034 | def addDesktopResource(self, pluginSubPath: bytes, resource: BasicResource) -> None:
pluginSubPath = pluginSubPath.strip(b)
self.__rootDesktopResource.putChild(pluginSubPath, resource) | Add Site Resource
Add a cusotom implementation of a served http resource.
:param pluginSubPath: The resource path where you want to serve this resource.
:param resource: The resource to serve.
:return: None |
354,035 | def update_columns_dict(self, kwargs):
super(Mesh, self).update_columns_dict(kwargs)
if kwargs.get(, None) is not None:
self.update_columns(visibilities=None, velocities=None) | TODO: add documentation |
354,036 | def get_template_request(configuration, spec):
req = RequestHolder()
req.api_method =
req.nonce = EBUtils.generate_nonce()
req.api_object = EBUtils.build_api_object(api_key=configuration.api_key, uo_id=0x1)
req.body = {"data": spec}
req.configuration = configura... | Builds API request block.
:param configuration:
:param spec:
:return: |
354,037 | def all_checks_enabled(self):
arming_mask = int(self.get_mav_param("ARMING_CHECK",0))
if arming_mask == 1:
return True
for bit in arming_masks.values():
if not arming_mask & bit and bit != 1:
return False
return True | returns true if the UAV is skipping any arming checks |
354,038 | def process_messages(self):
try:
msg = self.msgbackend.pop(self.incoming_message_mailbox)
self.handle_incoming_message(msg)
except queue.Empty:
logger.debug("Worker message queue currently empty.") | Read from the incoming_message_mailbox and report to the storage backend
based on the first message found there.
Returns: None |
354,039 | def tweets_for_user(screen_name, limit=1e10):
qu = Queue()
p = Thread(target=_tweets_for_user, args=(qu, screen_name, limit))
p.start()
p.join(910)
if p.is_alive():
sys.stderr.write( % screen_name)
return []
else:
return qu.get() | Collect the most recent 3200 tweets for this user, sleeping to deal with rate limits. |
354,040 | def put(self, klass, data, priority=None, tags=None, delay=None,
retries=None, jid=None, depends=None):
s less important. The `tags` argument
should be a JSON array of the tags associated with the instance and
the `valid after` argument should be in how many seconds the instance
... | Either create a new job in the provided queue with the provided
attributes, or move that job into that queue. If the job is being
serviced by a worker, subsequent attempts by that worker to either
`heartbeat` or `complete` the job should fail and return `false`.
The `priority` argument ... |
354,041 | def subvol_create(self, path):
args = {
: path
}
self._subvol_chk.check(args)
self._client.sync(, args) | Create a btrfs subvolume in the specified path
:param path: path to create |
354,042 | def main(config, log):
validate(config)
paths_and_urls = get_urls(config)
if not paths_and_urls:
log.warning()
return
total_size = 0
chunk_size = max(min(max(v[1] for v in paths_and_urls.values()) // 50, 1048576), 1024)
log.info(, if len(paths_and_urls) == 1 else , ch... | Main function. Runs the program.
:param dict config: Dictionary from get_arguments().
:param logging.Logger log: Logger for this function. Populated by with_log() decorator. |
354,043 | def _ask_if_attr_is_callable(self, attr):
self._tx.put((RetroWrapper.symbol, attr, {}))
return self._rx.get() | Returns whether or not the attribute is a callable. |
354,044 | def _get_indentword(source):
indent_word =
try:
for t in generate_tokens(source):
if t[0] == token.INDENT:
indent_word = t[1]
break
except (SyntaxError, tokenize.TokenError):
pass
return indent_word | Return indentation type. |
354,045 | def close(self):
if self._tempDir is not None and os.path.isdir(self._tempDir):
self.logger.debug("Removing temporary directory %r", self._tempDir)
shutil.rmtree(self._tempDir)
self._tempDir = None
return | Deletes temporary system objects/files. |
354,046 | def _is_related(parent_entry, child_entry):
if parent_entry.header.mft_record == child_entry.header.base_record_ref and \
parent_entry.header.seq_number == child_entry.header.base_record_seq:
return True
else:
return False | This function checks if a child entry is related to the parent entry.
This is done by comparing the reference and sequence numbers. |
354,047 | def init_widget(self):
w = self.window
d = self.declaration
self.set_background_color(d.background_color)
self.set_touchable(d.touchable)
self.set_outside_touchable(d.outside_touchable)
w.setOnDismissListener(w.getId())
w.onDismiss.connect(self.... | Set the listeners |
354,048 | def _set_mapping(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGListType("promis_pri_pvlan",mapping.mapping, yang_name="mapping", rest_name="mapping", parent=self, is_container=, user_ordered=False, path_helper=self._path_helper, yang_keys=, exte... | Setter method for mapping, mapped from YANG variable /interface/port_channel/switchport/private_vlan/mapping (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_mapping is considered as a private
method. Backends looking to populate this variable should
do so via call... |
354,049 | def validate(message, ssldir=None, **config):
for field in [, ]:
if field not in message:
_log.warn(, field)
return False
if not isinstance(message[field], six.text_type):
_log.error( % field)
try:
... | Validate the signature on the given message.
Four things must be true for the signature to be valid:
1) The X.509 cert must be signed by our CA
2) The cert must not be in our CRL.
3) We must be able to verify the signature using the RSA public key
contained in the X.509 cert.
4) T... |
354,050 | def stage_pywbem_result(self, ret, exc):
self._pywbem_result_ret = ret
self._pywbem_result_exc = exc | Set Result return info or exception info |
354,051 | def gaussfill(dem, size=3, newmask=None):
smooth = gauss_fltr_astropy(dem, size=size)
smooth[~dem.mask] = dem[~dem.mask]
if newmask is not None:
smooth = np.ma.array(smooth, mask=newmask)
return smooth | Gaussian filter with filling |
354,052 | def length(self, t0=0, t1=1, error=LENGTH_ERROR, min_depth=LENGTH_MIN_DEPTH):
if t0 == 0 and t1 == 1:
if self._length_info[] == self.bpoints() \
and self._length_info[] >= error \
and self._length_info[] >= min_depth:
return self._leng... | Calculate the length of the path up to a certain position |
354,053 | def get_project_actors_for_role_project(self, project_key, role_id):
url = .format(projectIdOrKey=project_key,
id=role_id)
return (self.get(url) or {}).get() | Returns the details for a given project role in a project.
:param project_key:
:param role_id:
:return: |
354,054 | def get_value(self, *args, **kwargs):
if self.qualifier in kwargs.keys():
return kwargs.get(self.qualifier)
return None | This method should be overriden by any subclass of Parameter, and should
be decorated with the @update_if_client decorator.
Please see the individual classes documentation:
* :meth:`FloatParameter.get_value`
* :meth:`ArrayParameter.get_value`
* :meth:`HierarchyParame... |
354,055 | def _parse_validators(valids):
outvals = []
for val in valids:
if isinstance(val, str):
args = []
elif len(val) > 1:
args = val[1:]
val = val[0]
else:
raise ValidationError("You must pass either an n-tuple or a string to define a val... | Parse a list of validator names or n-tuples, checking for errors.
Returns:
list((func_name, [args...])): A list of validator function names and a
potentially empty list of optional parameters for each function. |
354,056 | def _append_pairs(new_pairs):
desired_pairs = restore_pairs() or []
desired_pairs += new_pairs
print("Adding {} new pairs, queue has {} pairs".format(len(new_pairs), len(desired_pairs)))
save_pairs(desired_pairs) | Load the pairlist, add new stuff, save it out |
354,057 | def reverse_transform(self, col):
if isinstance(col, pd.Series):
col = col.to_frame()
output = pd.DataFrame(index=col.index)
output[self.col_name] = col.apply(self.safe_date, axis=1)
return output | Converts data back into original format.
Args:
col(pandas.DataFrame): Data to transform.
Returns:
pandas.DataFrame |
354,058 | def refresh_token(self, subid):
from expfactory.database.models import Participant
p = Participant.query.filter(Participant.id == subid).first()
if p is not None:
p.token = str(uuid.uuid4())
self.session.commit()
return p | refresh or generate a new token for a user |
354,059 | def new_struct(self, type, name, *parameters):
configs, parameters, _ = self._get_parameters_with_defaults(parameters)
self._add_struct_name_to_params(name, parameters)
self._message_stack.append(StructTemplate(type, name, self._current_container, parameters, length=configs.get(), align... | Defines a new struct to template.
You must call `End Struct` to end struct definition. `type` is the name
for generic type and `name` is the field name in containing structure.
Possible parameters are values for struct fields separated with colon
and optional struct length defined with ... |
354,060 | def get_py_source(file):
try:
response = None
pysource = ""
if regexp_py.search(file) is None:
response = {"error": "Only Python source files are allowed. (*.py)"}
else:
with open(file, ) as pyfile:
pysource = pyfile.read()
r... | Retrieves and returns the source code for any Python
files requested by the UI via the host agent
@param file [String] The fully qualified path to a file |
354,061 | def add_gauge(self, gauge):
if gauge is None:
raise ValueError
name = gauge.descriptor.name
with self._gauges_lock:
if name in self.gauges:
raise ValueError(
.format(name))
self.gauges[name] = g... | Add `gauge` to the registry.
Raises a `ValueError` if another gauge with the same name already
exists in the registry.
:type gauge: class:`LongGauge`, class:`DoubleGauge`,
:class:`opencensus.metrics.export.cumulative.LongCumulative`,
:class:`opencensus.metrics.export.cu... |
354,062 | def total_sparse_pixels_from_mask(mask, unmasked_sparse_grid_pixel_centres):
total_sparse_pixels = 0
for unmasked_sparse_pixel_index in range(unmasked_sparse_grid_pixel_centres.shape[0]):
y = unmasked_sparse_grid_pixel_centres[unmasked_sparse_pixel_index, 0]
x = unmasked_sparse_grid_pixe... | Given the full (i.e. without removing pixels which are outside the regular-masks) pixelization grid's pixel centers
and the regular-masks, compute the total number of pixels which are within the regular-masks and thus used by the
pixelization grid.
Parameters
-----------
mask : ccd.masks.Mask
... |
354,063 | def fastq_info(path):
numBases = 0
numReads = 0
readLengths = Counter()
GCTot = 0
with warnings.catch_warnings():
warnings.simplefilter("ignore")
handle = gzip.open(path, "rt")
for record in SeqIO.parse(handle, "fastq"):
numBases += len(record)
nu... | Found some info about how to ignore warnings in code blocks here:
- http://stackoverflow.com/questions/14463277/how-to-disable-python-warnings |
354,064 | def as_search_action(self, *, index, action):
if action not in ("index", "update", "delete"):
raise ValueError("Action must be , or .")
document = {
"_index": index,
"_type": self.search_doc_type,
"_op_type": action,
"_id": self.pk,
... | Return an object as represented in a bulk api operation.
Bulk API operations have a very specific format. This function will
call the standard `as_search_document` method on the object and then
wrap that up in the correct format for the action specified.
https://www.elastic.co/guide/en... |
354,065 | def fit_transform(self, X, u=None, sv=None, v=None):
self.fit(X, u, sv, v)
return self.embedding | Fit X into an embedded space and return that transformed
output.
Inputs
----------
X : array, shape (n_samples, n_features). X contains a sample per row.
Returns
-------
embedding : array, shape (n_samples, n_components)
Embedding of the training data... |
354,066 | def _parse_uri(uri_as_string):
if os.name == :
return Uri(scheme=parsed_uri.scheme, uri_path=uri_as_string)
elif parsed_uri.scheme in smart_open_ssh.SCHEMES:
return _parse_uri_ssh(parsed_uri)
else:
raise NotImplementedError(
"unknown URI scheme %r in %r" % (... | Parse the given URI from a string.
Supported URI schemes are:
* file
* hdfs
* http
* https
* s3
* s3a
* s3n
* s3u
* webhdfs
.s3, s3a and s3n are treated the same way. s3u is s3 but without SSL.
Valid URI examples::
* s3://my_bucket/my_key
... |
354,067 | def identify(s):
if is_pinyin(s):
return PINYIN
elif is_zhuyin(s):
return ZHUYIN
elif is_ipa(s):
return IPA
else:
return UNKNOWN | Identify a given string's transcription system.
*s* is the string to identify. The string is checked to see if its
contents are valid Pinyin, Zhuyin, or IPA. The :data:`PINYIN`,
:data:`ZHUYIN`, and :data:`IPA` constants are returned to indicate the
string's identity.
If *s* is not a valid transcrip... |
354,068 | def get_wrong_answers(self):
all_answers = self.my_osid_object._my_map[]
wrong_answers = [a for a in all_answers
if a[] == str(WRONG_ANSWER_GENUS_TYPE)]
return AnswerList(wrong_answers,
runtime=self.my_osid_object._runtime,
... | provide this method to return only wrong answers
:return: |
354,069 | def plot_dist(
values,
values2=None,
color="C0",
kind="auto",
cumulative=False,
label=None,
rotated=False,
rug=False,
bw=4.5,
quantiles=None,
contour=True,
fill_last=True,
textsize=None,
plot_kwargs=None,
fill_kwargs=None,
rug_kwargs=None,
contour_kwar... | Plot distribution as histogram or kernel density estimates.
By default continuous variables are plotted using KDEs and discrete ones using histograms
Parameters
----------
values : array-like
Values to plot
values2 : array-like, optional
Values to plot. If present, a 2D KDE or a he... |
354,070 | def create_connection(self):
try:
self.con = HTTPClient(address=self.satellite_map[],
port=self.satellite_map[],
short_timeout=self.short_timeout, long_timeout=self.long_timeout,
u... | Initialize HTTP connection with a satellite (con attribute) and
set its uri attribute
This is called on the satellite link initialization
:return: None |
354,071 | def strengths_und_sign(W):
W = W.copy()
n = len(W)
np.fill_diagonal(W, 0)
Spos = np.sum(W * (W > 0), axis=0)
Sneg = np.sum(W * (W < 0), axis=0)
vpos = np.sum(W[W > 0])
vneg = np.sum(W[W < 0])
return Spos, Sneg, vpos, vneg | Node strength is the sum of weights of links connected to the node.
Parameters
----------
W : NxN np.ndarray
undirected connection matrix with positive and negative weights
Returns
-------
Spos : Nx1 np.ndarray
nodal strength of positive weights
Sneg : Nx1 np.ndarray
... |
354,072 | def get_users(self, filter=None, sortBy=None, sortOrder=None,
startIndex=None, count=None):
self.assert_has_permission()
params = {}
if filter:
params[] = filter
if sortBy:
params[] = sortBy
if sortOrder:
params[] = sort... | Returns users accounts stored in UAA.
See https://docs.cloudfoundry.org/api/uaa/#list63
For filtering help, see:
http://www.simplecloud.info/specs/draft-scim-api-01.html#query-resources |
354,073 | def _get_fastq_files(ldetail, read, fastq_dir):
return glob.glob(os.path.join(fastq_dir, "Project_%s" % ldetail["project_name"],
"Sample_%s" % ldetail["name"],
"%s_*_%s_*.fastq.gz" % (ldetail["name"], read))) | Retrieve fastq files corresponding to the sample and read number. |
354,074 | def a_configuration_inconsistency(ctx):
ctx.msg = "This SDRclear configuration inconsistency' " \
"command is performed."
ctx.device.chain.connection.emit_message("Configuration inconsistency.", log_level=logging.ERROR)
ctx.finished = True
raise ConfigurationErrors("Configuration inc... | Raise the configuration inconsistency error. |
354,075 | def save_patt(patt, filename):
nrows = patt.nrows
ncols = patt.ncols
frmstr = "{0},{1},{2:.16e},{3:.16e}\n"
ar = patt.array
with open(filename, ) as f:
f.write("{0},{1}\n".format(nrows, ncols))
for nr in xrange(0, nrows):
for nc in xrange(0, ncols):
... | Saves ScalarPatternUniform object 'patt' to file. The first line of the
file has the number of rows and the number of columns in the pattern
separated by a comma (single sphere data). The remaining lines have the
form:
0, 1, 3.14, 2.718
The first two numbers are index for the row and in... |
354,076 | def _extract_progress(self, text):
find = partial(re.search, string=text.strip().decode(self.encoding))
regex = unit(self.progress_regex)
match = bind(regex, find)
result = bind(match, self._calculate_progress)
return result | Finds progress information in the text using the
user-supplied regex and calculation instructions |
354,077 | def is_tradetime_now():
cal = Calendar()
now_time = time.localtime()
today = Date(now_time[0], now_time[1], now_time[2])
if not cal.isBizDay(today):
return False
now = (now_time.tm_hour, now_time.tm_min, now_time.tm_sec)
if (9, 15, 0) <= now <= (11, 30, 0) or (13, 0, 0) <= now <= (1... | 判断目前是不是交易时间, 同时考虑节假日
:return: bool |
354,078 | def minvar(X, order, sampling=1., NFFT=default_NFFT):
r
errors.is_positive_integer(order)
errors.is_positive_integer(NFFT)
psi = np.zeros(NFFT, dtype=complex)
A, P, k = arburg (X, order - 1)
A = np.insert(A, 0, 1.+0j)
for... | r"""Minimum Variance Spectral Estimation (MV)
This function computes the minimum variance spectral estimate using
the Musicus procedure. The Burg algorithm from :func:`~spectrum.burg.arburg`
is used for the estimation of the autoregressive parameters.
The MV spectral estimator is given by:
.. mat... |
354,079 | def sign(self, data):
if self.signing_key is None:
raise MissingSigningKeyError("KeyPair does not contain secret key. "
"Use Keypair.from_seed method to create a new keypair with a secret key.")
return self.signing_key.sign(data) | Sign a bytes-like object using the signing (private) key.
:param bytes data: The data to sign
:return: The signed data
:rtype: bytes |
354,080 | def parse_band_request_termination(self, message):
self.log.debug("Service requests termination")
self._terminate_service()
if not self.restart_service:
self.shutdown = True | Service declares it should be terminated. |
354,081 | def create_customer(self, name, **kwargs):
data = self._wrap_dict("customer", kwargs)
data["customer"]["name"] = name
return self.post("/customers.json", data=data) | Creates a customer with a name. All other parameters are optional. They
are: `note`, `active_hourly_rate`, `hourly_rate`,
`hourly_rates_per_service`, and `archived`. |
354,082 | def readline(self, limit=-1):
if limit != -1:
raise NotImplementedError()
the_line = io.BytesIO()
while not (self._eof and len(self._buffer) == 0):
remaining_buffer = self.... | Read up to and including the next newline. Returns the bytes read. |
354,083 | def init(textCNN, vocab, model_mode, context, lr):
textCNN.initialize(mx.init.Xavier(), ctx=context, force_reinit=True)
if model_mode != :
textCNN.embedding.weight.set_data(vocab.embedding.idx_to_vec)
if model_mode == :
textCNN.embedding_extend.weight.set_data(vocab.embedding.idx_to_ve... | Initialize parameters. |
354,084 | def add_handler(self, func, type=):
if not callable(func):
raise ValueError("{} is not callable".format(func))
self._handlers[type].append(
(func, len(signature(func).parameters.keys()))
) | 为 BaseRoBot 实例添加一个 handler。
:param func: 要作为 handler 的方法。
:param type: handler 的种类。
:return: None |
354,085 | def _chooseBestSegmentPerColumn(cls, connections, matchingCells,
allMatchingSegments, potentialOverlaps,
cellsPerColumn):
candidateSegments = connections.filterSegmentsByCell(allMatchingSegments,
... | For all the columns covered by 'matchingCells', choose the column's matching
segment with largest number of active potential synapses. When there's a
tie, the first segment wins.
@param connections (SparseMatrixConnections)
@param matchingCells (numpy array)
@param allMatchingSegments (numpy array)... |
354,086 | def get_name_info(chunk_path, assert_one_date_hour=False, i_str=None,
chunk_type=Chunk):
-%(md5)s-
assert i_str is not None,
name_info = dict()
if i_str:
name_info[] = i_str
else:
name_info[] =
i_fname = i_str.split()[-1]
i_fname = i_fname.split()[0]
... | takes a chunk blob and obtains the date_hour, md5, num
makes fields:
i_str
input_fname
input_md5 - parsed from input filename if it contains '-%(md5)s-'
md5
num
epoch_ticks
target_names
doc_ids_8
date_hour
rand8
date_now
time_now
date_time_now |
354,087 | def Indentation( logical_line,
previous_logical,
indent_level,
previous_indent_level ):
comment = if logical_line else
if indent_level % 2:
code = if logical_line else
message = + comment
yield 0, code + message
if ( previous_logical.endswith(... | Use two spaces per indentation level. |
354,088 | def trigger(self, **event):
if not event:
raise ValueError("tried to trigger nothing")
for hook in self.hooks:
if hook.matches(event):
hook.execute(self, event) | Trigger an event.
Event parameters are passed as keyword arguments. Passing an `event`
argument isn't required, but generally recommended. |
354,089 | def get_domain(self, domain_name, validate=True):
domain = Domain(self, domain_name)
if validate:
self.select(domain, % domain_name)
return domain | Retrieves a :py:class:`boto.sdb.domain.Domain` object whose name
matches ``domain_name``.
:param str domain_name: The name of the domain to retrieve
:keyword bool validate: When ``True``, check to see if the domain
actually exists. If ``False``, blindly return a
... |
354,090 | def create_missing_task(self,
asana_workspace_id,
name,
assignee,
projects,
completed,
issue_number,
issue_html_url,
... | Creates a missing task. |
354,091 | def safe_add(a, b):
if isinstance(a, str) and isinstance(b, str) and len(a) + len(b) > MAX_STR_LEN:
raise RuntimeError("String length exceeded, max string length is {}".format(MAX_STR_LEN))
return a + b | safe version of add |
354,092 | def timex_starts(self):
if not self.is_tagged(TIMEXES):
self.tag_timexes()
return self.starts(TIMEXES) | The list of start positions of ``timexes`` layer elements. |
354,093 | def __IsInitialized(self):
is_initialized = False
iam_id = self.GetAccessKeyId()
if iam_id:
if core.CirrusAccessIdMetadata(self.s3, iam_id).IsInitialized():
is_initialized = True
return is_initialized | Returns true if IAM user initialization has completed. |
354,094 | def _guess_next_poll_interval(self):
time_elapsed = self._progress_data[-1][0] - self._progress_data[0][0]
real_progress = self._get_real_progress()
return min(0.2 * time_elapsed, 0.5 + (1 - real_progress)**0.5) | Determine when to query the progress status next.
This function is used if the external progress function did not return time interval for when it should be
queried next. |
354,095 | def compute_texptime(imageObjectList):
expnames = []
exptimes = []
start = []
end = []
for img in imageObjectList:
expnames += img.getKeywordList()
exptimes += img.getKeywordList()
start += img.getKeywordList()
end += img.getKeywordList()
exptime = 0.
ex... | Add up the exposure time for all the members in
the pattern, since 'drizzle' doesn't have the necessary
information to correctly set this itself. |
354,096 | def get_output_docs(self):
if not self.parsed:
self._parse()
lst = []
for e in self.docs_list:
lst.append(e[].get_raw_docs())
return lst | Return the output docstrings once formatted
:returns: the formatted docstrings
:rtype: list |
354,097 | def reduce(self, key, values):
dist, key, value = min(values, key=lambda x: x[0])
print( % dist)
yield key, value | Select the image with the minimum distance
Args:
key: (see mapper)
values: (see mapper)
Yields:
A tuple in the form of (key, value)
key: Image name
value: Image as jpeg byte data |
354,098 | def interp3d_core(x,y,t,Z,xout,yout,tout,**kwargs):
gx = np.reshape(np.repeat(x,y.size*t.size),(x.size,y.size,t.size))
gy = np.reshape(np.repeat(y,x.size*t.size),(y.size,x.size,t.size)).transpose((1,0,2))
gt = np.reshape(np.repeat(t,x.size*y.size),(t.size,x.size,y.size)).transpose((1,2,0... | INTERP3D : Interpolate values from a 3D matrix along a 1D trajectory
@param x: 1st dimension vector of size NX
@param y: 2nd dimension vector of size NY
@param t: 3rd dimension vector of size NT
@author: Renaud DUSSURGET, LER/PAC, Ifremer La Seyne |
354,099 | def update(dct, dct_merge):
for key, value in dct_merge.items():
if key in dct and isinstance(dct[key], dict):
dct[key] = update(dct[key], value)
else:
dct[key] = value
return dct | Recursively merge dicts. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.