Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
388,300 | def fixpointmethod(self, cfg_node):
JOIN = self.join(cfg_node)
if isinstance(cfg_node, AssignmentNode):
arrow_result = JOIN
if cfg_node.left_hand_side not in cfg_node.right_hand_side_variables:
arrow_result = self.a... | The most important part of PyT, where we perform
the variant of reaching definitions to find where sources reach. |
388,301 | def animate(self, animation, static, score, best, appear):
surface = pygame.Surface((self.game_width, self.game_height), 0)
surface.fill(self.BACKGROUND)
for y in range(self.COUNT_Y):
for x in range(self.COUNT_X):
x1, y1 = self.get_tile_lo... | Handle animation. |
388,302 | def compute(self, inputVector, learn, activeArray, applyLateralInhibition=True):
if not isinstance(inputVector, np.ndarray):
raise TypeError("Input vector must be a numpy array, not %s" %
str(type(inputVector)))
if inputVector.size != self._numInputs:
raise ValueError(
... | This is the primary public method of the LateralPooler class. This
function takes a input vector and outputs the indices of the active columns.
If 'learn' is set to True, this method also updates the permanences of the
columns and their lateral inhibitory connection weights. |
388,303 | def get_page(self, index=None):
if index is None:
widget = self.pages_widget.currentWidget()
else:
widget = self.pages_widget.widget(index)
return widget.widget() | Return page widget |
388,304 | def _adaptSynapses(self, inputVector, activeColumns, synPermActiveInc, synPermInactiveDec):
inputIndices = numpy.where(inputVector > 0)[0]
permChanges = numpy.zeros(self.getNumInputs(), dtype=REAL_DTYPE)
permChanges.fill(-1 * synPermInactiveDec)
permChanges[inputIndices] = synPermActiveInc
perm... | The primary method in charge of learning. Adapts the permanence values of
the synapses based on the input vector, and the chosen columns after
inhibition round. Permanence values are increased for synapses connected to
input bits that are turned on, and decreased for synapses connected to
inputs bits th... |
388,305 | def to_array(tensor):
if tensor.HasField("segment"):
raise ValueError(
"Currently not supporting loading segments.")
if tensor.data_type == TensorProto.UNDEFINED:
raise ValueError("The data type is not defined.")
tensor_dtype = tensor.data_type
np_dtype = mapping.TENS... | Converts a tensor def object to a numpy array.
Inputs:
tensor: a TensorProto object.
Returns:
arr: the converted array. |
388,306 | def calculate_incorrect_name_dict(graph: BELGraph) -> Mapping[str, str]:
missing = defaultdict(list)
for _, e, ctx in graph.warnings:
if not isinstance(e, (MissingNamespaceNameWarning, MissingNamespaceRegexWarning)):
continue
missing[e.namespace].append(e.name)
return dict... | Group all of the incorrect identifiers in a dict of {namespace: list of erroneous names}.
:return: A dictionary of {namespace: list of erroneous names} |
388,307 | def delta(feat, N):
if N < 1:
raise ValueError()
NUMFRAMES = len(feat)
denominator = 2 * sum([i**2 for i in range(1, N+1)])
delta_feat = numpy.empty_like(feat)
padded = numpy.pad(feat, ((N, N), (0, 0)), mode=)
for t in range(NUMFRAMES):
delta_feat[t] = numpy.dot(numpy.ara... | Compute delta features from a feature vector sequence.
:param feat: A numpy array of size (NUMFRAMES by number of features) containing features. Each row holds 1 feature vector.
:param N: For each frame, calculate delta features based on preceding and following N frames
:returns: A numpy array of size (NUM... |
388,308 | def log_level_from_string(str_level):
levels = {
: logging.CRITICAL,
: logging.ERROR,
: logging.WARNING,
: logging.INFO,
: logging.DEBUG,
}
try:
return levels[str_level.upper()]
except KeyError:
pass
except AttributeError:
if str_l... | Returns the proper log level core based on a given string
:param str_level: Log level string
:return: The log level code |
388,309 | def extend_schema(schema, documentAST=None):
assert isinstance(schema, GraphQLSchema), "Must provide valid GraphQLSchema"
assert documentAST and isinstance(
documentAST, ast.Document
), "Must provide valid Document AST"
type_definition_map = {}
type_extensions_map = defaultdict(l... | Produces a new schema given an existing schema and a document which may
contain GraphQL type extensions and definitions. The original schema will
remain unaltered.
Because a schema represents a graph of references, a schema cannot be
extended without effectively making an entire copy. We do not know un... |
388,310 | def _get_normalized_args(parser):
env = os.environ
if in env and env[] != sys.argv[0] and len(sys.argv) >= 1 and " " in sys.argv[1]:
return parser.parse_args(shlex.split(sys.argv[1]) + sys.argv[2:])
else:
return parser.parse_args() | Return the parsed command line arguments.
Support the case when executed from a shebang, where all the
parameters come in sys.argv[1] in a single string separated
by spaces (in this case, the third parameter is what is being
executed) |
388,311 | def reload_config(self, async=True, verbose=False):
api_version = float(self.api_version()[])
if api_version < 4.5:
async = False
url = .format(
self.rest_url, , if async else
)
return self.__auth_req_post(url, verbose=verbose) | Initiate a config reload. This may take a while on large installations. |
388,312 | def get_user_contact_lists_contacts(self, id, contact_list_id, **data):
return self.get("/users/{0}/contact_lists/{0}/contacts/".format(id,contact_list_id), data=data) | GET /users/:id/contact_lists/:contact_list_id/contacts/
Returns the :format:`contacts <contact>` on the contact list
as ``contacts``. |
388,313 | def empty(cls: Type[BoardT], *, chess960: bool = False) -> BoardT:
return cls(None, chess960=chess960) | Creates a new empty board. Also see :func:`~chess.Board.clear()`. |
388,314 | def coordinate(self, panes=[], index=0):
y = 0
for i, element in enumerate(self.panes):
x = 0
if isinstance(element, list):
current_height = 0
for j, pane in enumerate(element):
if pane.hidden: continue
... | Update pane coordinate tuples based on their height and width relative to other panes
within the dimensions of the current window.
We account for panes with a height of 1 where the bottom coordinates are the same as the top.
Account for floating panes and self-coordinating panes adjacent to pan... |
388,315 | def _is_dynamic(v: Var) -> bool:
return (
Maybe(v.meta)
.map(lambda m: m.get(SYM_DYNAMIC_META_KEY, None))
.or_else_get(False)
) | Return True if the Var holds a value which should be compiled to a dynamic
Var access. |
388,316 | def as_create_table(self, table_name, overwrite=False):
exec_sql =
sql = self.stripped()
if overwrite:
exec_sql = f
exec_sql += f
return exec_sql | Reformats the query into the create table as query.
Works only for the single select SQL statements, in all other cases
the sql query is not modified.
:param superset_query: string, sql query that will be executed
:param table_name: string, will contain the results of the
qu... |
388,317 | def _format_vector(self, vecs, form=):
if form == :
return np.meshgrid(*vecs, indexing=)
elif form == :
vecs = np.meshgrid(*vecs, indexing=)
return np.rollaxis(np.array(np.broadcast_arrays(*vecs)),0,self.dim+1)
elif form == :
return vecs
... | Format a 3d vector field in certain ways, see `coords` for a description
of each formatting method. |
388,318 | def focus_window(winhandle, path=None, name=None, sleeptime=.01):
import utool as ut
import time
print( + winhandle)
args = [, , winhandle]
ut.cmd(*args, verbose=False, quiet=True)
time.sleep(sleeptime) | sudo apt-get install xautomation
apt-get install autokey-gtk
wmctrl -xa gnome-terminal.Gnome-terminal
wmctrl -xl |
388,319 | def _next_state(index, event_time, transition_set, population_view):
if len(transition_set) == 0 or index.empty:
return
outputs, decisions = transition_set.choose_new_state(index)
groups = _groupby_new_state(index, outputs, decisions)
if groups:
for output, affected_index in sort... | Moves a population between different states using information from a `TransitionSet`.
Parameters
----------
index : iterable of ints
An iterable of integer labels for the simulants.
event_time : pandas.Timestamp
When this transition is occurring.
transition_set : TransitionSet
... |
388,320 | def message(self, value):
if value is not None:
assert type(value) in (unicode, QString), \
" attribute: type is not or !".format("message", value)
self.__message = value | Setter for **self.__message** attribute.
:param value: Attribute value.
:type value: unicode |
388,321 | def guess_message_type(message):
if isinstance(message, APPConfigMessage):
return MsgType.CONFIG
elif isinstance(message, APPJoinMessage):
return MsgType.JOIN
elif isinstance(message, APPDataMessage):
return MsgType.DATA
elif isinstance(message, APPUpdateMessage):
... | Guess the message type based on the class of message
:param message: Message to guess the type for
:type message: APPMessage
:return: The corresponding message type (MsgType) or None if not found
:rtype: None | int |
388,322 | def pp_prep(self, mlt_df):
if len(self.pp_props) == 0:
return
if self.pp_space is None:
self.logger.warn("pp_space is None, using 10...\n")
self.pp_space=10
if self.pp_geostruct is None:
self.logger.warn("pp_geostruct is None,"\
... | prepare pilot point based parameterizations
Parameters
----------
mlt_df : pandas.DataFrame
a dataframe with multiplier array information
Note
----
calls pyemu.pp_utils.setup_pilot_points_grid() |
388,323 | def filter_minreads_samples_from_table(table, minreads=1, inplace=True):
logger = logging.getLogger(__name__)
logger.debug( % minreads)
samp_sum = table.sum(axis=)
samp_ids = table.ids(axis=)
bad_samples = samp_ids[samp_sum < minreads]
if len(bad_samples) > 0:
logger.warn(
... | Filter samples from biom table that have less than
minreads reads total
Paraneters
----------
table : biom.Table
the biom table to filter
minreads : int (optional)
the minimal number of reads in a sample in order to keep it
inplace : bool (optional)
if True, filter the b... |
388,324 | def get(self, sid):
return ReservationContext(
self._version,
workspace_sid=self._solution[],
worker_sid=self._solution[],
sid=sid,
) | Constructs a ReservationContext
:param sid: The sid
:returns: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationContext
:rtype: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationContext |
388,325 | def solveAndNotify(proto, exercise):
exercise.solvedBy(proto.user)
proto.callRemote(ce.NotifySolved,
identifier=exercise.identifier,
title=exercise.title) | The user at the given AMP protocol has solved the given exercise.
This will log the solution and notify the user. |
388,326 | def make_type(typename, lineno, implicit=False):
assert isinstance(typename, str)
if not SYMBOL_TABLE.check_is_declared(typename, lineno, ):
return None
type_ = symbols.TYPEREF(SYMBOL_TABLE.get_entry(typename), lineno, implicit)
return type_ | Converts a typename identifier (e.g. 'float') to
its internal symbol table entry representation.
Creates a type usage symbol stored in a AST
E.g. DIM a As Integer
will access Integer type |
388,327 | def to_import(self):
properties = self.get_properties()
fw_uid = self.get_framework_uuid()
try:
name = properties[pelix.remote.PROP_ENDPOINT_NAME]
except KeyError:
name = "{0}.{1}".format(fw_... | Converts an EndpointDescription bean to an ImportEndpoint
:return: An ImportEndpoint bean |
388,328 | def revnet_cifar_base():
hparams = revnet_base()
hparams.num_channels_init_block = 32
hparams.first_batch_norm = [False, True, True]
hparams.init_stride = 1
hparams.init_kernel_size = 3
hparams.init_maxpool = False
hparams.strides = [1, 2, 2]
hparams.batch_size = 128
hparams.weight_decay = 1e-4
... | Tiny hparams suitable for CIFAR/etc. |
388,329 | def api_representation(self, content_type):
payload = dict(Subject=self.subject, Body=dict(ContentType=content_type, Content=self.body))
if self.sender is not None:
payload.update(From=self.sender.api_representation())
if any(isinstance(item, str) for item in self... | Returns the JSON representation of this message required for making requests to the API.
Args:
content_type (str): Either 'HTML' or 'Text' |
388,330 | def get_albums_for_artist(self, artist, full_album_art_uri=False):
subcategories = [artist]
result = self.get_album_artists(
full_album_art_uri=full_album_art_uri,
subcategories=subcategories,
complete_result=True)
reduced = [item for item in result ... | Get an artist's albums.
Args:
artist (str): an artist's name.
full_album_art_uri: whether the album art URI should be
absolute (i.e. including the IP address). Default `False`.
Returns:
A `SearchResult` instance. |
388,331 | def disable_hostgroup_svc_checks(self, hostgroup):
for host_id in hostgroup.get_hosts():
if host_id in self.daemon.hosts:
for service_id in self.daemon.hosts[host_id].services:
if service_id in self.daemon.services:
self.disable_sv... | Disable service checks for a hostgroup
Format of the line that triggers function call::
DISABLE_HOSTGROUP_SVC_CHECKS;<hostgroup_name>
:param hostgroup: hostgroup to disable
:type hostgroup: alignak.objects.hostgroup.Hostgroup
:return: None |
388,332 | def discover_engines(self, executor=None):
if executor is None:
executor = getattr(settings, , {}).get(, )
self.executor = self.load_executor(executor)
logger.info(
__("Loaded executor.", str(self.executor.__class__.__module__).replace(, ))
)
ex... | Discover configured engines.
:param executor: Optional executor module override |
388,333 | def _sign(private_key, data, hash_algorithm, rsa_pss_padding=False):
if not isinstance(private_key, PrivateKey):
raise TypeError(pretty_message(
,
type_name(private_key)
))
if not isinstance(data, byte_cls):
raise TypeError(pretty_message(
,
... | Generates an RSA, DSA or ECDSA signature
:param private_key:
The PrivateKey to generate the signature with
:param data:
A byte string of the data the signature is for
:param hash_algorithm:
A unicode string of "md5", "sha1", "sha224", "sha256", "sha384" or "sha512"
:param rsa... |
388,334 | def get_data_home(data_home=None):
data_home_default = Path(__file__).ancestor(3).child(,
)
if data_home is None:
data_home = os.environ.get(, data_home_default)
if not os.path.exists(data_home):
os.makedirs(data_home)
retu... | Return the path of the revrand data dir.
This folder is used by some large dataset loaders to avoid
downloading the data several times.
By default the data dir is set to a folder named 'revrand_data'
in the user home folder.
Alternatively, it can be set by the 'REVRAND_DATA' environment
varia... |
388,335 | def insert_many(objects, using="default"):
if not objects:
return
import django.db.models
from django.db import connections
from django.db import transaction
con = connections[using]
model = objects[0].__class__
fields = [f for f in model._meta.fields
if not isin... | Insert list of Django objects in one SQL query. Objects must be
of the same Django model. Note that save is not called and signals
on the model are not raised.
Mostly from: http://people.iola.dk/olau/python/bulkops.py |
388,336 | def exists(self, filename):
if is_package(filename):
filepath = os.path.join(self.connection["mount_point"],
"Packages", filename)
else:
filepath = os.path.join(self.connection["mount_point"],
"Scrip... | Report whether a file exists on the distribution point.
Determines file type by extension.
Args:
filename: Filename you wish to check. (No path! e.g.:
"AdobeFlashPlayer-14.0.0.176.pkg") |
388,337 | def create(self, validated_data):
courses = validated_data.pop("courses", [])
encoded_videos = validated_data.pop("encoded_videos", [])
video = Video.objects.create(**validated_data)
EncodedVideo.objects.bulk_create(
EncodedVideo(video=video, **video_data)
... | Create the video and its nested resources. |
388,338 | def array(self):
return np.geomspace(self.start, self.stop, self.num, self.endpoint) | return the underlying numpy array |
388,339 | def cal_k_vinet_from_v(v, v0, k0, k0p):
x = v / v0
y = np.power(x, 1. / 3.)
eta = 1.5 * (k0p - 1.)
k = k0 * np.power(y, -2.) * (1. + (eta * y + 1.) * (1. - y)) * \
unp.exp((1. - y) * eta)
return k | calculate bulk modulus in GPa
:param v: unit-cell volume in A^3
:param v0: unit-cell volume in A^3 at 1 bar
:param k0: bulk modulus at reference conditions
:param k0p: pressure derivative of bulk modulus at reference conditions
:return: bulk modulus at high pressure in GPa |
388,340 | def _CreatePlacemark(self, parent, name, style_id=None, visible=True,
description=None):
placemark = ET.SubElement(parent, )
placemark_name = ET.SubElement(placemark, )
placemark_name.text = name
if description is not None:
desc_tag = ET.SubElement(placemark, )
de... | Create a KML Placemark element.
Args:
parent: The parent ElementTree.Element instance.
name: The placemark name as a string.
style_id: If not None, the id of a style to use for the placemark.
visible: Whether the placemark is initially visible or not.
description: A description string... |
388,341 | def optimize(lattice,
positions,
numbers,
displacements,
forces,
alm_options=None,
p2s_map=None,
p2p_map=None,
log_level=0):
from alm import ALM
with ALM(lattice, positions, numbers) as alm:
nat... | Calculate force constants
lattice : array_like
Basis vectors. a, b, c are given as column vectors.
shape=(3, 3), dtype='double'
positions : array_like
Fractional coordinates of atomic points.
shape=(num_atoms, 3), dtype='double'
numbers : array_like
Atomic numbers.
... |
388,342 | def get_or_create_hosted_zone(client, zone_name):
zone_id = get_hosted_zone_by_name(client, zone_name)
if zone_id:
return zone_id
logger.debug("Zone %s does not exist, creating.", zone_name)
reference = uuid.uuid4().hex
response = client.create_hosted_zone(Name=zone_name,
... | Get the Id of an existing zone, or create it.
Args:
client (:class:`botocore.client.Route53`): The connection used to
interact with Route53's API.
zone_name (string): The name of the DNS hosted zone to create.
Returns:
string: The Id of the Hosted Zone. |
388,343 | def modify_server(self, UUID, **kwargs):
body = dict()
body[] = {}
for arg in kwargs:
if arg not in Server.updateable_fields:
Exception(.format(arg))
body[][arg] = kwargs[arg]
res = self.request(, .format(UUID), body)
server = res... | modify_server allows updating the server's updateable_fields.
Note: Server's IP-addresses and Storages are managed by their own add/remove methods. |
388,344 | def _get_generator(parser, extract, keep, check_maf):
if extract is not None:
parser = Extractor(parser, names=extract)
for data in parser.iter_genotypes():
data.genotypes = data.genotypes[keep]
if check_maf:
data.code_minor()
yield data | Generates the data (with extract markers and keep, if required. |
388,345 | def _process_reservations(self, reservations):
reservations = reservations[]
private_ip_addresses = []
private_hostnames = []
public_ips = []
public_hostnames = []
for reservation in reservations:
for instance in reservation[]:
priva... | Given a dict with the structure of a response from boto3.ec2.describe_instances(...),
find the public/private ips.
:param reservations:
:return: |
388,346 | def xread(self, streams, count=None, block=None):
pieces = []
if block is not None:
if not isinstance(block, (int, long)) or block < 0:
raise DataError()
pieces.append(Token.get_token())
pieces.append(str(block))
if count is not None:
... | Block and monitor multiple streams for new data.
streams: a dict of stream names to stream IDs, where
IDs indicate the last ID already seen.
count: if set, only return this many items, beginning with the
earliest available.
block: number of milliseconds to wait,... |
388,347 | def get_nn_shell_info(self, structure, site_idx, shell):
all_nn_info = self.get_all_nn_info(structure)
sites = self._get_nn_shell_info(structure, all_nn_info, site_idx, shell)
output = []
for info in sites:
orig_site = structure[info[]]
... | Get a certain nearest neighbor shell for a certain site.
Determines all non-backtracking paths through the neighbor network
computed by `get_nn_info`. The weight is determined by multiplying
the weight of the neighbor at each hop through the network. For
example, a 2nd-nearest-neighbor ... |
388,348 | def update(self, time):
total_acceleration = Vector.null()
max_jerk = self.max_acceleration
for behavior in self.behaviors:
acceleration, importance = behavior.update()
weighted_acceleration = acceleration * importance
... | Update acceleration. Accounts for the importance and
priority (order) of multiple behaviors. |
388,349 | def subscribe(self, handler, topic=None, options=None):
def proxy_handler(*args, **kwargs):
return self._callbacks_runner.put(partial(handler, *args, **kwargs))
return self._async_session.subscribe(proxy_handler, topic=topic, options=options) | Subscribe to a topic for receiving events.
Replace :meth:`autobahn.wamp.interface.IApplicationSession.subscribe` |
388,350 | def join_room(self, room_name):
logging.debug(.format(ro=room_name))
for room in self.rooms:
if room.name == room_name:
room.add_user(self)
self._rooms[room_name] = room
room.welcome(self)
break
... | Connects to a given room
If it does not exist it is created |
388,351 | def get_template_dirs():
temp_glob = rel_to_cwd(, , , )
temp_groups = glob(temp_glob)
temp_groups = [get_parent_dir(path, 2) for path in temp_groups]
return set(temp_groups) | Return a set of all template directories. |
388,352 | def pass_outflow_v1(self):
flu = self.sequences.fluxes.fastaccess
out = self.sequences.outlets.fastaccess
out.q[0] += flu.outflow | Update the outlet link sequence |dam_outlets.Q|. |
388,353 | def replace_namespaced_horizontal_pod_autoscaler_status(self, name, namespace, body, **kwargs):
kwargs[] = True
if kwargs.get():
return self.replace_namespaced_horizontal_pod_autoscaler_status_with_http_info(name, namespace, body, **kwargs)
else:
(data) = self.re... | replace status of the specified HorizontalPodAutoscaler
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_horizontal_pod_autoscaler_status(name, namespace, body, async_req=True)
>>... |
388,354 | def get_project(self, project_id, include_capabilities=None, include_history=None):
route_values = {}
if project_id is not None:
route_values[] = self._serialize.url(, project_id, )
query_parameters = {}
if include_capabilities is not None:
query_paramete... | GetProject.
Get project with the specified id or name, optionally including capabilities.
:param str project_id:
:param bool include_capabilities: Include capabilities (such as source control) in the team project result (default: false).
:param bool include_history: Search within renamed... |
388,355 | def strip_cdata(text):
if not is_cdata(text):
return text
xml = "<e>{0}</e>".format(text)
node = etree.fromstring(xml)
return node.text | Removes all CDATA blocks from `text` if it contains them.
Note:
If the function contains escaped XML characters outside of a
CDATA block, they will be unescaped.
Args:
A string containing one or more CDATA blocks.
Returns:
An XML unescaped string with CDATA block qualifier... |
388,356 | def _writeData(self, command, device, params=()):
sequence = []
if self._compact:
sequence.append(command | 0x80)
else:
sequence.append(self._BAUD_DETECT)
sequence.append(device)
sequence.append(command)
for param in params:
... | Write the data to the device.
:Parameters:
command : `int`
The command to write to the device.
device : `int`
The device is the integer number of the hardware devices ID and
is only used with the Pololu Protocol.
params : `tuple`
Seq... |
388,357 | def list(self, end_date=values.unset, friendly_name=values.unset,
minutes=values.unset, start_date=values.unset,
task_channel=values.unset, split_by_wait_time=values.unset, limit=None,
page_size=None):
return list(self.stream(
end_date=end_date,
... | Lists TaskQueuesStatisticsInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before returning.
:param datetime end_date: Filter cumulative statistics by an end date.
:param unicode friendly_name: Filter the TaskQue... |
388,358 | def dispatch(self, tree):
for omp in metadata.get(tree, openmp.OMPDirective):
deps = list()
for dep in omp.deps:
old_file = self.f
self.f = io.StringIO()
self.dispatch(dep)
deps.append(self.f.getvalue())
... | Dispatcher function, dispatching tree type T to method _T. |
388,359 | def add_trits(left, right):
target_len = max(len(left), len(right))
res = [0] * target_len
left += [0] * (target_len - len(left))
right += [0] * (target_len - len(right))
carry = 0
for i in range(len(res)):
res[i], carry = _full_add_trits(left[i], right[i], carry)
return... | Adds two sequences of trits together.
The result is a list of trits equal in length to the longer of the
two sequences.
.. note::
Overflow is possible.
For example, ``add_trits([1], [1])`` returns ``[-1]``. |
388,360 | def npartitions(self):
if self.mode == :
return self.tordd().getNumPartitions()
else:
notsupported(self.mode) | Get number of partitions (Spark only). |
388,361 | def select_best_url(self):
best_url = self.parsed_urls[0]
try:
yield best_url
except Exception:
self.unsuccessful_calls[best_url] += 1
if self.unsuccessful_calls[best_url] > self.max_failures:
self.parsed_urls.rotate(-1)
self.unsuccessful_calls[best_url] = 0
... | Select `best` url.
Since urls are pre-sorted w.r.t. their ping times, we simply return the first element
from the list. And we always return the same url unless we observe greater than max
allowed number of consecutive failures. In this case, we would return the next `best`
url, and append the previous... |
388,362 | def send_like(self, *, user_id, times=1):
return super().__getattr__() \
(user_id=user_id, times=times) | 发送好友赞
------------
:param int user_id: 对方 QQ 号
:param int times: 赞的次数,每个好友每天最多 10 次
:return: None
:rtype: None |
388,363 | def config(self):
return self._h._get_resource(
resource=(, self.name, ),
obj=ConfigVars, app=self
) | The envs for this app. |
388,364 | def centralManager_didConnectPeripheral_(self, manager, peripheral):
logger.debug()
peripheral.setDelegate_(self)
peripheral.discoverServices_(None)
device = device_list().get(peripheral)
if device is not None:
device._set_connected... | Called when a device is connected. |
388,365 | def portfolio_prices(
symbols=("AAPL", "GLD", "GOOG", "$SPX", "XOM", "msft"),
start=datetime.datetime(2005, 1, 1),
end=datetime.datetime(2011, 12, 31),
normalize=True,
allocation=None,
price_type=,
):
symbols = normalize_symbols(symbols)
start = util.normalize_date(start)... | Calculate the Sharpe Ratio and other performance metrics for a portfolio
Arguments:
symbols (list of str): Ticker symbols like "GOOG", "AAPL", etc
start (datetime): The date at the start of the period being analyzed.
end (datetime): The date at the end of the period being analyzed.
normaliz... |
388,366 | def run_as(user, domain, password, filename, logon_flag=1, work_dir="",
show_flag=Properties.SW_SHOWNORMAL):
ret = AUTO_IT.AU3_RunAs(
LPCWSTR(user), LPCWSTR(domain), LPCWSTR(password), INT(logon_flag),
LPCWSTR(filename), LPCWSTR(work_dir), INT(show_flag)
)
return ret | Runs an external program.
:param user: username The user name to use.
:param domain: The domain name to use.
:param password: The password to use.
:param logon_flag: 0 = do not load the user profile, 1 = (default) load
the user profile, 2 = use for net credentials only
:param filename: The n... |
388,367 | def root(self, scope, names):
parent = scope.scopename
if parent:
parent = parent[-1]
if parent.parsed:
parsed_names = []
for name in names:
ampersand_count = name.count()
if ampersand_count:
... | Find root of identifier, from scope
args:
scope (Scope): current scope
names (list): identifier name list (, separated identifiers)
returns:
list |
388,368 | def update_scheme(current, target):
target_p = urlparse(target)
if not target_p.scheme and target_p.netloc:
return "{0}:{1}".format(urlparse(current).scheme,
urlunparse(target_p))
elif not target_p.scheme and not target_p.netloc:
return "{0}://{1}".format... | Take the scheme from the current URL and applies it to the
target URL if the target URL startswith // or is missing a scheme
:param current: current URL
:param target: target URL
:return: target URL with the current URLs scheme |
388,369 | def _encrypt(cipher, key, data, iv, padding):
if not isinstance(key, byte_cls):
raise TypeError(pretty_message(
,
type_name(key)
))
if not isinstance(data, byte_cls):
raise TypeError(pretty_message(
,
type_name(data)
))
... | Encrypts plaintext
:param cipher:
A unicode string of "aes128", "aes192", "aes256", "des",
"tripledes_2key", "tripledes_3key", "rc2", "rc4"
:param key:
The encryption key - a byte string 5-32 bytes long
:param data:
The plaintext - a byte string
:param iv:
The... |
388,370 | def rst_table(self, array):
cell_dict = {}
for i, row in enumerate(array):
for j, val in enumerate(row):
if j not in cell_dict:
cell_dict[j] = []
cell_dict[j].append(val)
for item in cell_dict:
cell_dic... | Given an array, the function formats and returns and table in rST format. |
388,371 | def ssn(self):
def _checksum(digits):
factors = (9, 8, 7, 6, 5, 4, 3, 2, -1)
s = 0
for i in range(len(digits)):
s += digits[i] * factors[i]
return s
while True:
digits = self.generator.random.samp... | Returns a 9 digits Dutch SSN called "burgerservicenummer (BSN)".
the Dutch "burgerservicenummer (BSN)" needs to pass the "11-proef",
which is a check digit approach; this function essentially reverses
the checksum steps to create a random valid BSN (which is 9 digits). |
388,372 | def index(self, weighted=True, prune=False):
warnings.warn(
"CrunchCube.index() is deprecated. Use CubeSlice.index_table().",
DeprecationWarning,
)
return Index.data(self, weighted, prune) | Return cube index measurement.
This function is deprecated. Use index_table from CubeSlice. |
388,373 | def set_outgoing(self, value):
if not isinstance(value, list):
raise TypeError("OutgoingList new value must be a list")
for element in value:
if not isinstance(element, str):
raise TypeError("OutgoingList elements in variable must be of String class")
... | Setter for 'outgoing' field.
:param value - a new value of 'outgoing' field. Must be a list of IDs (String type) of outgoing flows. |
388,374 | def get(self, *args, **kwargs):
return self.model._default_manager.get(*args, **kwargs) | Quick and dirty hack to fix change_view and delete_view; they use
self.queryset(request).get(...) to get the object they should work
with. Our modifications to the queryset when INCLUDE_ANCESTORS is
enabled make get() fail often with a MultipleObjectsReturned
exception. |
388,375 | def batch(self, client=None):
client = self._require_client(client)
return Batch(self, client) | Return a batch to use as a context manager.
:type client: :class:`~google.cloud.logging.client.Client` or
``NoneType``
:param client: the client to use. If not passed, falls back to the
``client`` stored on the current topic.
:rtype: :class:`Batch`... |
388,376 | def get_user_bookmarks(self, id, **data):
return self.get("/users/{0}/bookmarks/".format(id), data=data) | GET /users/:id/bookmarks/
Gets all the user's saved events.
In order to update the saved events list, the user must unsave or save each event.
A user is authorized to only see his/her saved events. |
388,377 | def split_key(key):
if key == KEY_SEP:
return ()
key_chunks = tuple(key.strip(KEY_SEP).split(KEY_SEP))
if key_chunks[0].startswith(KEY_SEP):
return (key_chunks[0][len(KEY_SEP):],) + key_chunks[1:]
else:
return key_chunks | Splits a node key. |
388,378 | def load_airpassengers(as_series=False):
rslt = np.array([
112, 118, 132, 129, 121, 135, 148, 148, 136, 119, 104, 118,
115, 126, 141, 135, 125, 149, 170, 170, 158, 133, 114, 140,
145, 150, 178, 163, 172, 178, 199, 199, 184, 162, 146, 166,
171, 180, 193, 181, 183, 218, 230, 242, ... | Monthly airline passengers.
The classic Box & Jenkins airline data. Monthly totals of international
airline passengers, 1949 to 1960.
Parameters
----------
as_series : bool, optional (default=False)
Whether to return a Pandas series. If False, will return a 1d
numpy array.
Ret... |
388,379 | def _add_cadd_score(self, variant_obj, info_dict):
cadd_score = info_dict.get()
if cadd_score:
logger.debug("Updating cadd_score to: {0}".format(
cadd_score))
variant_obj.cadd_score = float(cadd_score) | Add the cadd score to the variant
Args:
variant_obj (puzzle.models.Variant)
info_dict (dict): A info dictionary |
388,380 | def parse_device(lines):
name, status_line, device = parse_device_header(lines.pop(0))
if not status_line:
status_line = lines.pop(0)
status = parse_device_status(status_line, device["personality"])
bitmap = None
resync = None
for line in lines:
if line.sta... | Parse all the lines of a device block.
A device block is composed of a header line with the name of the device and
at least one extra line describing the device and its status. The extra
lines have a varying format depending on the status and personality of the
device (e.g. RAID1 vs RAID5, healthy vs ... |
388,381 | def shell(self, name=, user=None, password=None, root=0, verbose=1, write_password=1, no_db=0, no_pw=0):
raise NotImplementedError | Opens a SQL shell to the given database, assuming the configured database
and user supports this feature. |
388,382 | def course_or_program_exist(self, course_id, program_uuid):
course_exists = course_id and CourseApiClient().get_course_details(course_id)
program_exists = program_uuid and CourseCatalogApiServiceClient().program_exists(program_uuid)
return course_exists or program_exists | Return whether the input course or program exist. |
388,383 | def image_info(call=None, kwargs=None):
if call != :
raise SaltCloudSystemExit(
)
if kwargs is None:
kwargs = {}
name = kwargs.get(, None)
image_id = kwargs.get(, None)
if image_id:
if name:
log.warning(
image_id\name\
... | Retrieves information for a given image. Either a name or an image_id must be
supplied.
.. versionadded:: 2016.3.0
name
The name of the image for which to gather information. Can be used instead
of ``image_id``.
image_id
The ID of the image for which to gather information. Can... |
388,384 | def AddLeNetModel(model, data):
conv1 = brew.conv(model, data, , dim_in=1, dim_out=20, kernel=5)
pool1 = brew.max_pool(model, conv1, , kernel=2, stride=2)
conv2 = brew.conv(model, pool1, , dim_in=20, dim_out=100, kernel=5)
pool2 = brew.max_pool(model, conv2, , kernel=2, stride=2... | This part is the standard LeNet model: from data to the softmax prediction.
For each convolutional layer we specify dim_in - number of input channels
and dim_out - number or output channels. Also each Conv and MaxPool layer changes the
image size. For example, kernel of size 5 reduces each side of an image... |
388,385 | def mount(cls, device, mount_directory, fs=None, options=None, cmd_timeout=None, sudo=False):
cmd = [] if sudo is False else []
cmd.extend([, device, os.path.abspath(mount_directory)])
if fs is not None:
cmd.extend([, fs])
if options is not None and len(options) > 0:
cmd.append()
cmd.extend(options)... | Mount a device to mount directory
:param device: device to mount
:param mount_directory: target directory where the given device will be mounted to
:param fs: optional, filesystem on the specified device. If specifies - overrides OS filesystem \
detection with this value.
:param options: specifies mount opti... |
388,386 | def _pool_one_shape(features_2d, area_width, area_height, batch_size,
width, height, depth, fn=tf.reduce_max, name=None):
with tf.name_scope(name, default_name="pool_one_shape"):
images = []
for y_shift in range(area_height):
image_height = tf.maximum(height - area_height + 1 + y_... | Pools for an area in features_2d.
Args:
features_2d: a Tensor in a shape of [batch_size, height, width, depth].
area_width: the max width allowed for an area.
area_height: the max height allowed for an area.
batch_size: the batch size.
width: the width of the memory.
height: the height of the... |
388,387 | def _remove_prefix(name):
if isinstance(name, str):
return _do_remove_prefix(name)
return [_do_remove_prefix(nm) for nm in name] | Strip the possible prefix 'Table: ' from one or more table names. |
388,388 | def subst_quoted_strings(sql, params):
parts = sql.split()
params_dont_match = "number of parameters doesn%s\\\\\\", "\\\'.join(out) | Reverse operation to mark_quoted_strings - substitutes '@' by params. |
388,389 | def get_name(self, use_alias=True):
if self.desc:
direction =
else:
direction =
if use_alias:
return .format(self.field.get_identifier(), direction)
return .format(self.field.get_select_sql(), direction) | Gets the name to reference the sorted field
:return: the name to reference the sorted field
:rtype: str |
388,390 | def combine(self, other, func, fill_value=None, overwrite=True):
other_idxlen = len(other.index)
this, other = self.align(other, copy=False)
new_index = this.index
if other.empty and len(new_index) == len(self.index):
return self.copy()
if self.empty and... | Perform column-wise combine with another DataFrame.
Combines a DataFrame with `other` DataFrame using `func`
to element-wise combine columns. The row and column indexes of the
resulting DataFrame will be the union of the two.
Parameters
----------
other : DataFrame
... |
388,391 | def to_method(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args[1:], **kwargs)
return wrapper | Lift :func:`func` to a method; it will be called with the first argument
'self' ignored.
:param func: Any callable object |
388,392 | def verify_embedding(emb, source, target, ignore_errors=()):
for error in diagnose_embedding(emb, source, target):
eclass = error[0]
if eclass not in ignore_errors:
raise eclass(*error[1:])
return True | A simple (exception-raising) diagnostic for minor embeddings.
See :func:`diagnose_embedding` for a more detailed diagnostic / more information.
Args:
emb (dict): a dictionary mapping source nodes to arrays of target nodes
source (graph or edgelist): the graph to be embedded
target (gra... |
388,393 | def _range_from_slice(myslice, start=None, stop=None, step=None, length=None):
assert isinstance(myslice, slice)
step = myslice.step if myslice.step is not None else step
if step is None:
step = 1
start = myslice.start if myslice.start is not None else start
if start is None:
... | Convert a slice to an array of integers. |
388,394 | def get_certificates(self):
for certificate in self.user_data.certificates:
certificate[] = certificate[].strip()
return self.user_data.certificates | Get user's certificates. |
388,395 | def from_header(self, header):
if header is None:
return SpanContext()
try:
match = re.search(_TRACE_CONTEXT_HEADER_RE, header)
except TypeError:
logging.warning(
.format(header.__class__.__name__))
raise
... | Generate a SpanContext object using the trace context header.
The value of enabled parsed from header is int. Need to convert to
bool.
:type header: str
:param header: Trace context header which was extracted from the HTTP
request headers.
:rtype: :class:... |
388,396 | def _render_template_block_nodelist(nodelist, block_name, context):
for node in nodelist:
if isinstance(node, BlockNode):
context.render_context[BLOCK_CONTEXT_KEY].push(node.name, node)
| Recursively iterate over a node to find the wanted block. |
388,397 | def f_contains(self, item, with_links=True, shortcuts=False, max_depth=None):
try:
search_string = item.v_full_name
parent_full_name = self.v_full_name
if not search_string.startswith(parent_full_name):
return False
if parent_f... | Checks if the node contains a specific parameter or result.
It is checked if the item can be found via the
:func:`~pypet.naturalnaming.NNGroupNode.f_get` method.
:param item: Parameter/Result name or instance.
If a parameter or result instance is supplied it is also checked if
... |
388,398 | def _RunIpRoute(self, args=None, options=None):
args = args or []
options = options or {}
command = [, ]
command.extend(args)
for item in options.items():
command.extend(item)
try:
process = subprocess.Popen(
command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
... | Run a command with ip route and return the response.
Args:
args: list, the string ip route command args to execute.
options: dict, the string parameters to append to the ip route command.
Returns:
string, the standard output from the ip route command execution. |
388,399 | def finalize(self, **kwargs):
self.set_title("")
self.ax.legend(loc="best", frameon=True)
if self.hist:
plt.setp(self.xhax.get_xticklabels(), visible=False)
plt.setp(self.yhax.get... | Finalize executes any remaining image modifications making it ready to show. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.