code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def __str__(self): <NEW_LINE> <INDENT> return _engine_internal.UInt16Array___str__(self) | __str__(self) -> std::string | 625941e745492302aab5e73e |
def dispatch_request(self): <NEW_LINE> <INDENT> form = self.get_search_form(flask.request.args) <NEW_LINE> flask.g.search_form = form <NEW_LINE> if mydojo.const.FORM_ACTION_SUBMIT in flask.request.args: <NEW_LINE> <INDENT> if form.validate(): <NEW_LINE> <INDENT> form_data = form.data <NEW_LINE> self.mark_time( 'preproc... | Mandatory interface required by the :py:func:`flask.views.View.dispatch_request`.
Will be called by the **Flask** framework to service the request. | 625941e715baa723493c43ef |
def get_tags_on_commit(self, sha): <NEW_LINE> <INDENT> if self._all_tags is None: <NEW_LINE> <INDENT> self._load_tags() <NEW_LINE> <DEDENT> tags_and_dates = self._shas_to_tags.get(sha, []) <NEW_LINE> tags_and_dates.sort(key=lambda x: x[1]) <NEW_LINE> return [t[0] for t in tags_and_dates] | Return the tag(s) on a commit, in application order. | 625941e7236d856c2ad44c57 |
def _compute_top_membership_subset(memberships, membership_subset_size): <NEW_LINE> <INDENT> topk_idx = np.argpartition(memberships, -membership_subset_size, axis=0)[-membership_subset_size:] <NEW_LINE> top_memberships_mask = csr_matrix((np.ones((topk_idx.shape[0] * topk_idx.shape[1],)), (topk_idx.flatten(), np.... | Compute a mask of the `memberships` matrix. The mask is True `membership_subset_size` times in each column for
all indexes where the membership has one of the `membership_subset_size` highest value for this column.
Many thanks to RISSER-MAROIX Olivier and POUYET Adrien for their help. | 625941e7d58c6744b42580d5 |
def get_node_with_corresponding_exp_id(self, exp_id): <NEW_LINE> <INDENT> for node in self.nodes: <NEW_LINE> <INDENT> if node.exploration_id == exp_id: <NEW_LINE> <INDENT> return node <NEW_LINE> <DEDENT> <DEDENT> raise Exception('Unable to find the exploration id in any node: %s' % ( exp_id)) | Returns the node object which corresponds to a given exploration ids.
Returns:
StoryNode or None. The StoryNode object of the corresponding
exploration id if exist else None.
Raises:
Exception. Unable to find the exploration in any node. | 625941e7377c676e9127261d |
def regex_key_strategy(key): <NEW_LINE> <INDENT> return re.match(key_strategy, key) | Match keys according to key_strategy. | 625941e7e5267d203edce10e |
def getExons(sId, lCoords): <NEW_LINE> <INDENT> sGene = "" <NEW_LINE> for dCoords in lCoords: <NEW_LINE> <INDENT> dCoords["id"] = sId <NEW_LINE> sGene += "{id} {start} {stop}\n".format(**dCoords) <NEW_LINE> <DEDENT> return sGene | This function assumes that lCoords is a list of dictionaries
containing the positions of exons in a gene. | 625941e745492302aab5e73f |
def set_limit(size): <NEW_LINE> <INDENT> size_bytes = int(size * 1024 * 1024 * 1024) <NEW_LINE> if platform.system() == "Windows": <NEW_LINE> <INDENT> set_limit_windows(os.getpid(), size_bytes) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> set_limit_unix(size_bytes) | Set process memory limit and throw a MemoryError when exceeded
size {int} -- Memory limit in GiB | 625941e70383005118ecfa58 |
def login_required(fn): <NEW_LINE> <INDENT> def wrapper(*args, **kwargs): <NEW_LINE> <INDENT> session_id = request.cookies.get('session_id') <NEW_LINE> reg_flow = kwargs.get('reg_flow') <NEW_LINE> if reg_flow.login_required_url: <NEW_LINE> <INDENT> redirect_url = reg_flow.login_required_url <NEW_LINE> <DEDENT> else: <N... | Decorator that asserts a users session_id is present and valid. | 625941e7cc0a2c11143dd309 |
def test_leaf_WFD_task_updated_to_have_a_dependency_of_PREV_task(self): <NEW_LINE> <INDENT> self.test_task3.depends = [] <NEW_LINE> self.test_task9.status = self.status_wip <NEW_LINE> assert self.test_task9.status == self.status_wip <NEW_LINE> self.test_task3.depends.append(self.test_task9) <NEW_LINE> assert self.test_... | testing if it is possible to set a dependency between a task with
WFD status to a task with PREV status and the status of the task will
stay WFD | 625941e7d10714528d60015f |
def __iadd__(self, n: 'ptrdiff_t') -> "swig::SwigPyIterator &": <NEW_LINE> <INDENT> return _kinova_raw.SwigPyIterator___iadd__(self, n) | __iadd__(SwigPyIterator self, ptrdiff_t n) -> SwigPyIterator | 625941e715baa723493c43f0 |
def replace_operation(self, func_search, func_replace, *args, maxreplace=1, **kwargs): <NEW_LINE> <INDENT> idx = self.find_operation(func_search) <NEW_LINE> for i in idx: <NEW_LINE> <INDENT> self.remove_operation(i) <NEW_LINE> self.add_operation(func_replace, position=i, *args, **kwargs) | Replace the operation denoted by func_search by func_replace and the
new *args and **kwargs for this operation | 625941e74d74a7450ccd463b |
def setCurrentPath(self, path): <NEW_LINE> <INDENT> row = self.rowFromPath(path) <NEW_LINE> if row is not None: <NEW_LINE> <INDENT> self.view.setCurrentIndex(row.nameItem.index()) <NEW_LINE> return True <NEW_LINE> <DEDENT> return False | Set the current row by a name-path and return True
on success, False on failure. | 625941e74527f215b584c8c9 |
def minDeletionSize(self, A): <NEW_LINE> <INDENT> count = 0 <NEW_LINE> flag = False <NEW_LINE> for i in range(len(A[0])): <NEW_LINE> <INDENT> for j in range(len(A) - 1): <NEW_LINE> <INDENT> if not flag: <NEW_LINE> <INDENT> if A[j][i] > A[j + 1][i]: <NEW_LINE> <INDENT> flag = True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> i... | :type A: List[str]
:rtype: int | 625941e794891a1f4081bf22 |
def read_from_file(path, file_name, mode='r'): <NEW_LINE> <INDENT> if not os.path.isdir(path): <NEW_LINE> <INDENT> os.makedirs(path) <NEW_LINE> <DEDENT> file_path = os.path.join(path, file_name) <NEW_LINE> if not os.path.exists(file_path): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> f = open(file_path, mode) <NEW_LI... | 读文件内容
* 'path' 路径
* 'file_name' 文件名,需要包括文件拓展名
* 'mode' r=只读,w=只写,a=追加,r+,w+,a+ | 625941e7851cf427c661a982 |
def set_MediaID(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'MediaID', value) | Set the value of the MediaID input for this Choreo. ((required, string) The ID of the media to unlike.) | 625941e7c432627299f050c0 |
def createResolver(servers=None, resolvconf=None, hosts=None): <NEW_LINE> <INDENT> if platform.getType() == 'posix': <NEW_LINE> <INDENT> if resolvconf is None: <NEW_LINE> <INDENT> resolvconf = b'/etc/resolv.conf' <NEW_LINE> <DEDENT> if hosts is None: <NEW_LINE> <INDENT> hosts = b'/etc/hosts' <NEW_LINE> <DEDENT> theReso... | Create and return a Resolver.
@type servers: C{list} of C{(str, int)} or C{None}
@param servers: If not C{None}, interpreted as a list of domain name servers
to attempt to use. Each server is a tuple of address in C{str} dotted-quad
form and C{int} port number.
@type resolvconf: C{str} or C{None}
@param resolvconf: ... | 625941e78c3a873295158837 |
def grid_search_base_clf(self, X, y, search_params, clf_num, cv_params=None, inplace=True, n_jobs=-1): <NEW_LINE> <INDENT> if self.verbose: <NEW_LINE> <INDENT> print('Base classifier #{} ({}): Tuning the hyperparameters'.format(clf_num, self.name_base_clf[clf_num])) <NEW_LINE> <DEDENT> if not isinstance(search_params, ... | Perform hyper parameter search with cross-validation for the specified base classifier.
Parameter setting that gave the best results on the hold out data are assigned to this base classifier
Parameters
----------
X : np.ndarray, shape = [n_samples, n_features]
Training data, where n_samples is the number of sample... | 625941e7925a0f43d254a2f2 |
def run_client_cert_with_password_test(self, password): <NEW_LINE> <INDENT> done_receiving = Event() <NEW_LINE> client_certs = [] <NEW_LINE> def socket_handler(listener): <NEW_LINE> <INDENT> sock = listener.accept()[0] <NEW_LINE> sock = self._wrap_in_ssl(sock) <NEW_LINE> client_certs.append(sock.getpeercert()) <NEW_LIN... | Tests client certificate password functionality | 625941e7e64d504609d74cb7 |
def _parse_new_field_expression( self, lexer: TigerLexer ) -> Union[LValueExpression, AssignmentExpression]: <NEW_LINE> <INDENT> raise NotImplementedError("TODO") | fieldExp → lValue . id | 625941e7b7558d58953c5381 |
def main(dir, loop_count, client_count, config): <NEW_LINE> <INDENT> config_ini = configparser.ConfigParser() <NEW_LINE> config_ini.read(config, encoding = 'utf-8') <NEW_LINE> sql_files = glob.glob(dir + u"/*.sql") <NEW_LINE> global_start = datetime.datetime.now().strftime(u'%Y%m%d_%H%M%S') <NEW_LINE> benchmark_server ... | main -- 全体制御関数
入力値:
dir : クエリが格納されているディレクトリ
loop_count : ベンチマーク実行回数
client_count : 同時実行するクライアント数
config : Configファイル名 | 625941e771ff763f4b549b0a |
def convert_to_screen_rect(self, screenLocation): <NEW_LINE> <INDENT> pos = np.array([self.x, self.y]) <NEW_LINE> size = np.array([self.width, self.height]) <NEW_LINE> pos_screen = np.array(screenLocation, dtype='float') <NEW_LINE> new_size = np.multiply(size, pixel_factor) <NEW_LINE> new_pos = np.multiply(pos - pos_sc... | take a rect in game units and convert to pixel units
as well as translate onto visible screen | 625941e75e10d32532c5f39c |
def main(): <NEW_LINE> <INDENT> parser = ApiArgumentParser(formatter_class=lambda prog: HelpFormatter(prog,max_help_position=30)) <NEW_LINE> parser.add_argument('api_call', help="API endpoint expressed as a relative path " "(eg. /settings/get).") <NEW_LINE> parser.add_argument('-p', '--param... | Main entry point for CLI. This may be called by running the module directly
or by an executable installed onto the system path. | 625941e7a8370b7717052d14 |
def start(self, port: int = 2020): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> server = WebServer(self) <NEW_LINE> self.cron_job.start() <NEW_LINE> while not Tools.check_ready(): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> print( Tools.get_time(), "[Start] Listening WebServer on port {}".format(port) ) <NEW_LINE> ser... | Start web service
:param port: integer of port to listen online
:return: | 625941e7d164cc61757831c6 |
def build_text_part(name, thread, struct): <NEW_LINE> <INDENT> part_w = None <NEW_LINE> width = None <NEW_LINE> minw = 0 <NEW_LINE> maxw = None <NEW_LINE> width_tuple = struct['width'] <NEW_LINE> if width_tuple is not None: <NEW_LINE> <INDENT> if width_tuple[0] == 'fit': <NEW_LINE> <INDENT> minw, maxw = width_tuple[1:]... | create an urwid.Text widget (wrapped in approproate Attributes)
to display a plain text parts in a threadline.
create an urwid.Columns widget (wrapped in approproate Attributes)
to display a list of tag strings, as part of a threadline.
:param name: id of part to build
:type name: str
:param thread: the thread to get ... | 625941e7e8904600ed9f23ab |
def getEdgeSourceVertexType(self, edgeType): <NEW_LINE> <INDENT> edgeTypeDetails = self.getEdgeType(edgeType) <NEW_LINE> if edgeTypeDetails["FromVertexTypeName"] == "*": <NEW_LINE> <INDENT> return "*" <NEW_LINE> <DEDENT> fromVertexTypes = edgeTypeDetails["FromVertexTypeList"] <NEW_LINE> if len(fromVertexTypes) == 1: <N... | Returns the type of the edge type's source vertex.
Arguments:
- `edgeType`: The name of the edge type. | 625941e766673b3332b92508 |
def arg_min(input, dimension, name=None): <NEW_LINE> <INDENT> result = _op_def_lib.apply_op("ArgMin", input=input, dimension=dimension, name=name) <NEW_LINE> return result | Returns the index with the smallest value across dimensions of a tensor.
Args:
input: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int64`, `int32`, `uint8`, `uint16`, `int16`, `int8`, `complex64`, `complex128`, `qint8`, `quint8`, `qint32`, `half`.
dimension: A `Tensor` of type `int32`.
... | 625941e72c8b7c6e89b35c34 |
def _compute(self, batch): <NEW_LINE> <INDENT> return self.value | Compute the fixed loss.
Args:
batch (Batch): batch containing the states, actions, rewards, etc.
Returns:
torch.Tensor: loss scalar value | 625941e760cbc95b062c69bb |
def GetPointer(self): <NEW_LINE> <INDENT> return _itkBayesianClassifierInitializationImageFilterPython.itkBayesianClassifierInitializationImageFilterIUL2D_GetPointer(self) | GetPointer(self) -> itkBayesianClassifierInitializationImageFilterIUL2D | 625941e792d797404e304603 |
def _propagate_sigterm(self, signum, frame): <NEW_LINE> <INDENT> if os.getpid() != self.main_process_pid: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.stop_testing = True <NEW_LINE> for p in self._client_procs.values(): <NEW_LINE> <INDENT> assert p.pid != os.getpid(), "Signal handler should not reach this point ... | Handler SIGTERM and SIGINT by propagating SIGTERM to all client processes.
Note that multiprocessing processes are in the same process group as the main process, so Ctrl-C will
result in SIGINT being propagated to all client processes automatically. This may result in multiple SIGTERM
signals getting sent to client pr... | 625941e744b2445a3393250a |
def get_name(self): <NEW_LINE> <INDENT> if not self.is_connected: <NEW_LINE> <INDENT> raise NotConnectedError() <NEW_LINE> <DEDENT> HOST, PORT = self.ip_address, 730 <NEW_LINE> sock = socket.create_connection( (HOST, PORT), timeout=.2) <NEW_LINE> sock.send("DBGNAME\r\n") <NEW_LINE> sock.recv(1024) <NEW_LINE> name = soc... | Gets the name of the connected console | 625941e76fb2d068a760f51c |
def convert_namespaces(): <NEW_LINE> <INDENT> cmds.namespace(set=":") <NEW_LINE> done = 0 <NEW_LINE> while done == 0: <NEW_LINE> <INDENT> fails = [] <NEW_LINE> for obj in cmds.ls(): <NEW_LINE> <INDENT> if ":" in obj: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> cmds.rename(obj, obj.replace(":", "_")) <NEW_LINE> <DEDENT... | Converts all : to _ for each namespace in the scene | 625941e73317a56b8693a0c4 |
def get_gc_freq(seq): <NEW_LINE> <INDENT> iupac = { 'a': 0.0, 'c': 1.0, 'g': 1.0, 't': 0.0, 'u': 0.0, 'r': 0.5, 'y': 0.5, 'm': 0.5, 'k': 0.5, 'w': 0.0, 's': 1.0, 'b': 2.0/3.0, 'd': 1.0/3.0, 'h': 1.0/3.0, 'v': 2.0/3.0, 'n': 0.5, 'A': 0.0, 'C': 1.0, 'G': 1.0, 'T': 0.0, 'U': 0.0, 'R': 0.5, 'Y': 0.5, 'M': 0.5, 'K': 0.5, 'W... | Ambiguity-aware %GC calculation | 625941e7091ae356686673ce |
def get_resource_id(self): <NEW_LINE> <INDENT> return self.resource_id | Get the row's resource id.
Returns:
str: resource id. | 625941e75f7d997b87174f13 |
def __init__(self, path=None, pathmaker_name='default', _pathmaker=None, overwrite=False, include_arcname=False, splitext_arcname=False): <NEW_LINE> <INDENT> self.include_arcname = include_arcname <NEW_LINE> self.splitext_arcname = splitext_arcname <NEW_LINE> self.overwrite = overwrite <NEW_LINE> if _pathmaker: <NEW_LI... | Initialize the mapping, optionally with a path to an archive
file.
Mapping dict keys are names of file or directory, values are
either a tuple that represent a file, or a dict to represent a
directory. | 625941e78e71fb1e9831dc1f |
def _write_graph_dimacs_format(G,output_file): <NEW_LINE> <INDENT> print("c {}".format(G.name).strip(),file=output_file) <NEW_LINE> vertices=dict((name,index) for index,name in enumerate(G.nodes(),1)) <NEW_LINE> edges =G.edges() <NEW_LINE> print("p edge {} {}".format(len(vertices),len(edges)),file=output_file) <NEW_... | Wrire a graph to a file, in DIMACS format.
Parameters
----------
G : graph object
output_file : file object
file handle of the output | 625941e7be8e80087fb210b3 |
def get_corners(p, fov): <NEW_LINE> <INDENT> c = np.array([[0, 0], fov[::-1]]) <NEW_LINE> corners = np.c_[c[0], c[::-1, 0], c[1], c[:, 1]].T <NEW_LINE> corners = trans.rigid(corners, p) <NEW_LINE> return corners | Get corners relative to DSS coordinates. xy coords anti-clockwise | 625941e7187af65679ca5597 |
def test_network_create(self): <NEW_LINE> <INDENT> alias = dict(name='data_networks', address='192.168.1.0/24 192.168.2.0/24', descr='', type='network', detail='') <NEW_LINE> command = "create alias 'data_networks', type='network', address='192.168.1.0/24 192.168.2.0/24', descr='', detail=''" <NEW_LINE> self.do_alias_c... | test creation of a new network alias | 625941e75166f23b2e1a55d0 |
def serve_validation(self): <NEW_LINE> <INDENT> if {"code"} <= set(request.query): <NEW_LINE> <INDENT> code = request.query.get("code") <NEW_LINE> if self.validate_code(code): <NEW_LINE> <INDENT> return HTTPResponse(status=200) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return HTTPResponse(status=403) <NEW_LINE> <DE... | Handle alarm code validation. | 625941e730c21e258bdfa919 |
def read(self, command): <NEW_LINE> <INDENT> self.cmd_emiter.emit(str(command)) <NEW_LINE> answer = self.Instrument.ask(command) <NEW_LINE> return answer <NEW_LINE> pass | Read an arbitrary amount of data directly from the scope | 625941e7f9cc0f698b140a6f |
def ha_sync(token, ip, port): <NEW_LINE> <INDENT> client = ha_get_client(token, ip, port) <NEW_LINE> client.sync() <NEW_LINE> client.disconnect(send_close=True) <NEW_LINE> return 0 | Syncs Harmony hub to web service.
Args:
token (str): Session token obtained from hub
ip (str): Harmony hub IP address
port (str): Harmony hub port
Returns:
Completion status | 625941e7baa26c4b54cb1592 |
def dequeue(self): <NEW_LINE> <INDENT> current = self.front <NEW_LINE> if self._size > 0: <NEW_LINE> <INDENT> self._size -= 1 <NEW_LINE> <DEDENT> if not current: <NEW_LINE> <INDENT> self.back = None <NEW_LINE> raise IndexError("Queue is empty") <NEW_LINE> <DEDENT> self.front = current.next_node <NEW_LINE> return curren... | Remove Node from Front of queue, and assign next Node in line as
Front of queue. | 625941e7a8370b7717052d15 |
def get_inference_name_to_features(long_seq_length, global_seq_length): <NEW_LINE> <INDENT> name_to_features = { "long_token_ids": tf.FixedLenFeature([long_seq_length], tf.int64), "long_sentence_ids": tf.FixedLenFeature([long_seq_length], tf.int64), "long_paragraph_ids": tf.FixedLenFeature([long_seq_length], tf.int64),... | Returns the feature spec of the model. | 625941e73317a56b8693a0c5 |
def write(self, filehandle, section_keyword_blacklist=None, var_value_dict=None): <NEW_LINE> <INDENT> content_list = self.generate(self.__mk_section_list, section_keyword_blacklist, var_value_dict) <NEW_LINE> filehandle.write('\n'.join(content_list)) | Generate and write Makefile *without* contents of specified sections
See 'generate' method for detailed description (method and parameters).
Params:
filehandle: File object that the Makefile will be written to.
section_keyword_blacklist: List of strings with keywords for
filtering sections by their ti... | 625941e77cff6e4e81117dfd |
def post(self, request): <NEW_LINE> <INDENT> input_serializer = GameSerializer().load_data(request.POST) <NEW_LINE> game = Game.objects.create( created_by=request.user, name=input_serializer['name'], white=input_serializer.get('white'), black=input_serializer.get('black'), ) <NEW_LINE> output_serializer, errors = GameS... | Create a new game. | 625941e7d53ae8145f87a6de |
def __copy__(self): <NEW_LINE> <INDENT> new_obj = Organization(self.parent) <NEW_LINE> new_obj.animation_data.data = copy.copy(self.animation_data.data) <NEW_LINE> new_obj.animation_frame_data.data = copy.copy(self.animation_frame_data.data) <NEW_LINE> new_obj.capability_data.data = copy.copy(self.capability_data.data)... | On organization copy, return a safe object
Attempts to only copy the datastructures that may need to diverge | 625941e78e05c05ec3eea7f0 |
def addBinary(self, a, b): <NEW_LINE> <INDENT> def toInt(x): <NEW_LINE> <INDENT> result = 0 <NEW_LINE> n = 0 <NEW_LINE> for i in range(len(x)-1,-1,-1): <NEW_LINE> <INDENT> result += int(x[i])*pow(2,n) <NEW_LINE> n += 1 <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> c = toInt(a)+toInt(b) <NEW_LINE> res = '' <NEW_... | :type a: str
:type b: str
:rtype: str | 625941e773bcbd0ca4b2c4ed |
@tf_export('FakeQuantWithMinMaxVarsGradient') <NEW_LINE> def fake_quant_with_min_max_vars_gradient(gradients, inputs, min, max, num_bits=8, narrow_range=False, name=None): <NEW_LINE> <INDENT> if num_bits is None: <NEW_LINE> <INDENT> num_bits = 8 <NEW_LINE> <DEDENT> num_bits = _execute.make_int(num_bits, "num_bits") <NE... | Compute gradients for a FakeQuantWithMinMaxVars operation.
Args:
gradients: A `Tensor` of type `float32`.
Backpropagated gradients above the FakeQuantWithMinMaxVars operation.
inputs: A `Tensor` of type `float32`.
Values passed as inputs to the FakeQuantWithMinMaxVars operation.
min, max: Quantization... | 625941e7baa26c4b54cb1593 |
def fetch(self, request, callback=None, **kwargs): <NEW_LINE> <INDENT> if self._closed: <NEW_LINE> <INDENT> raise RuntimeError("fetch() called on closed AsyncHTTPClient") <NEW_LINE> <DEDENT> if not isinstance(request, HTTPRequest): <NEW_LINE> <INDENT> request = HTTPRequest(url=request, **kwargs) <NEW_LINE> <DEDENT> req... | Executes a request, asynchronously returning an `HTTPResponse`.
The request may be either a string URL or an `HTTPRequest` object.
If it is a string, we construct an `HTTPRequest` using any additional
kwargs: ``HTTPRequest(request, **kwargs)``
This method returns a `.Future` whose result is an
`HTTPResponse`. The ``... | 625941e7596a897236089f32 |
def handle_rp(self, slc): <NEW_LINE> <INDENT> self.log.debug('SLC RP: Repaint') | Handle SLC Repaint.
| 625941e7167d2b6e3121900c |
def plot_polygon(self, frame=None, ax=None, wrap_angle=360*u.deg, autolim=True, **kwargs): <NEW_LINE> <INDENT> import matplotlib as mpl <NEW_LINE> poly = self.get_polygon(frame=frame) <NEW_LINE> verts = np.stack(poly.to_lonlat()).T <NEW_LINE> verts[:, 0] = co.Angle(verts[:, 0]*u.deg).wrap_at(wrap_angle).degree <NEW_LIN... | Plot the footprint polygon
Parameters
----------
frame : `~astropy.coordinates.BaseCoordinateFrame` subclass instance (optional)
The coordinate frame to generate points in.
ax : `~matplotlib.axes.Axes` (optional)
The matplotlib axes object to plot on. If not specified, this will
plot on the current axes ob... | 625941e7287bf620b61d3ed8 |
def convert_beijing_to_utc(date_str,return_format="standard"): <NEW_LINE> <INDENT> _utc_date = "" <NEW_LINE> try: <NEW_LINE> <INDENT> _beijing_date = dateparser.parse(date_str).replace(tzinfo=timezone(timedelta(hours=8))) <NEW_LINE> _utc_date = _beijing_date.astimezone(timezone(timedelta(hours=0))) <NEW_LINE> if return... | 将北京时间转换为utc时间串
:param date_str: 东八区时间串
:param return_format: 返回的时间串格式,iso格式或者standard模式,前者包含T
:return: | 625941e7ff9c53063f47c669 |
def generate_menu(name, menu_text): <NEW_LINE> <INDENT> from . import persist <NEW_LINE> plugin_dir = os.path.join(sublime.packages_path(), persist.PLUGIN_DIRECTORY) <NEW_LINE> path = os.path.join(plugin_dir, '{}.sublime-menu.template'.format(name)) <NEW_LINE> with open(path, encoding='utf8') as f: <NEW_LINE> <INDENT> ... | Generate and return a sublime-menu from a template. | 625941e792d797404e304604 |
def run_script(): <NEW_LINE> <INDENT> list_dir = 'cube_lists' <NEW_LINE> cube_lists = open_lists(list_dir) <NEW_LINE> card_names = combine_lists(cube_lists) <NEW_LINE> with open('cube_combined.txt', 'w') as cube_file: <NEW_LINE> <INDENT> cube_file.write(''.join(card_names)) | Do the default thing for the script | 625941e7e1aae11d1e74a133 |
def get_symbols_in_REV(self, direction): <NEW_LINE> <INDENT> return self.right_eigen_vector[direction].atoms(EinsteinTerm).difference(self.right_eigen_vector[direction].atoms(ConstantObject)) | Retrieve the unique symbols present in the right rigenvector matrix for a given direction. | 625941e785dfad0860c3b2d4 |
def twos(dice): <NEW_LINE> <INDENT> return dice_counts(dice)[2] * 2 | Score the given roll in the 'Twos' category
>>> twos([1,2,3,4,5])
2
>>> twos([3,4,5,6,6])
0 | 625941e756ac1b37e626463e |
def compress(self, chars): <NEW_LINE> <INDENT> l, slow, fast = len(chars), 0, 0 <NEW_LINE> while fast < l and slow < l: <NEW_LINE> <INDENT> cur, count = chars[fast], 0 <NEW_LINE> while fast < l and chars[fast] == cur: <NEW_LINE> <INDENT> count += 1 <NEW_LINE> fast += 1 <NEW_LINE> <DEDENT> chars[slow] = cur <NEW_LINE> s... | :type chars: List[str]
:rtype: int | 625941e7d6c5a102081444c6 |
def __init__(self, parent, document): <NEW_LINE> <INDENT> VeuszDialog.__init__(self, parent, 'datacreate2d.ui') <NEW_LINE> self.document = document <NEW_LINE> self.createbutton = self.buttonBox.addButton( _("C&reate"), qt4.QDialogButtonBox.ApplyRole ) <NEW_LINE> self.createbutton.clicked.connect(self.createButtonClicke... | Initialise dialog with document. | 625941e7a4f1c619b28b04a6 |
def repair_buggy_sim_metrics(data: Dict, lprint=print, eprint=print): <NEW_LINE> <INDENT> if data["_args"]["mode"] == "sim": <NEW_LINE> <INDENT> lprint(f"Repair bugged Eval metrics calc for simultaneous mode ...") <NEW_LINE> evm = data["_eval_metrics"] <NEW_LINE> last_eval = data["_last_eval"] <NEW_LINE> acc = [] <NEW_... | Repair bugged Eval metrics calc for simultaneous mode | 625941e78a349b6b435e85ea |
def __init__(self, *args, **kwds): <NEW_LINE> <INDENT> if args or kwds: <NEW_LINE> <INDENT> super(AccelWithCovarianceStamped, self).__init__(*args, **kwds) <NEW_LINE> if self.header is None: <NEW_LINE> <INDENT> self.header = std_msgs.Header() <NEW_LINE> <DEDENT> if self.accel is None: <NEW_LINE> <INDENT> self.accel = g... | Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future message
changes. You cannot mix in-order arguments and keyword arguments.
The available fields are:
header,accel
:param args: complet... | 625941e796565a6dacc8fb42 |
def phi_t_pw(self, t): <NEW_LINE> <INDENT> B = 1 <NEW_LINE> r0 = 10 <NEW_LINE> r1 = 100 <NEW_LINE> q = self.q[t] <NEW_LINE> if (q < -B): <NEW_LINE> <INDENT> self.phi[t] = r1*q + (r1-r0)*B <NEW_LINE> <DEDENT> elif (q > B): <NEW_LINE> <INDENT> self.phi[t] = r1*q + (r0-r1)*B <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> s... | cal phi(t) from q | 625941e70c0af96317bb865f |
def median(rankings): <NEW_LINE> <INDENT> consensus = np.argsort( np.argsort( rankings.sum(axis=0) ) ) <NEW_LINE> return consensus | This function computes the central permutation (consensus ranking) given
several permutations.
Parameters
----------
rankings: ndarray
Matrix of several permutations
Returns
-------
ndarray
The central permutation of permutations given. | 625941e77b180e01f3dc4c6c |
def _create_image(self, context, instance, name, image_type, backup_type=None, rotation=None, extra_properties=None): <NEW_LINE> <INDENT> task_state = instance["task_state"] <NEW_LINE> instance_uuid = instance['uuid'] <NEW_LINE> properties = { 'instance_uuid': instance_uuid, 'user_id': str(context.user_id), 'image_type... | Create snapshot or backup for an instance on this host.
:param context: security context
:param instance: nova.db.sqlalchemy.models.Instance
:param name: string for name of the snapshot
:param image_type: snapshot | backup
:param backup_type: daily | weekly
:param rotation: int representing how many backups to keep ar... | 625941e75e10d32532c5f39d |
def get_queryset(self): <NEW_LINE> <INDENT> return Poll.objects.order_by('-pub_date')[:3] | Return the last three published polls. | 625941e74a966d76dd55148c |
def normalAt(self, p): <NEW_LINE> <INDENT> return self.u.cross(self.v).normalized() | Returns the normal of the triangle | 625941e72ae34c7f2600d5a8 |
def gens(self): <NEW_LINE> <INDENT> raise NotImplementedError("not implemented.") | Placeholder function to return generators of an elliptic curve.
.. note::
This functionality is implemented in certain derived
classes, such as EllipticCurve_rational_field.
EXAMPLES::
sage: R.<a1,a2,a3,a4,a6>=QQ[]
sage: E=EllipticCurve([a1,a2,a3,a4,a6])
sage: E.gens()
Traceback (most recent c... | 625941e7fbf16365ca6f6645 |
def generators(self) -> dict: <NEW_LINE> <INDENT> generators = dict() <NEW_LINE> for subset in next(os.walk(self._y))[1]: <NEW_LINE> <INDENT> if subset in {'.DS_Store'}: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> x_g = CropImageDataGenerator(**self.data_gen_args(subset)) <NEW_LINE> y_g = CropNumpyDataGenerator(**... | Return a dictionary with both training and validation generators. | 625941e7d18da76e23532954 |
def get_accounts(self, username=None): <NEW_LINE> <INDENT> accounts = self._find_msal_accounts(environment=self.authority.instance) <NEW_LINE> if not accounts: <NEW_LINE> <INDENT> for alias in self._get_authority_aliases(self.authority.instance): <NEW_LINE> <INDENT> accounts = self._find_msal_accounts(environment=alias... | Get a list of accounts which previously signed in, i.e. exists in cache.
An account can later be used in :func:`~acquire_token_silent`
to find its tokens.
:param username:
Filter accounts with this username only. Case insensitive.
:return: A list of account objects.
Each account is a dict. For now, we only do... | 625941e73cc13d1c6d3c77f0 |
def do_execute(self, code, silent=False, store_history=True, user_expressions=None, allow_stdin=True): <NEW_LINE> <INDENT> messages = self.GFRepl.handle_input(code) <NEW_LINE> for msg in messages: <NEW_LINE> <INDENT> if msg['file']: <NEW_LINE> <INDENT> file_name = msg['file'] <NEW_LINE> try: <NEW_LINE> <INDENT> with op... | Called when the user inputs code | 625941e73c8af77a43ae3c1e |
@use_np <NEW_LINE> def check_gluon_hybridize_consistency(net_builder, data_l, numpy_func=None, test_grad=True, rtol=1E-4, atol=1E-4): <NEW_LINE> <INDENT> class _NumpyParamDictInit(mx.init.Initializer): <NEW_LINE> <INDENT> def __init__(self, np_params): <NEW_LINE> <INDENT> super(_NumpyParamDictInit, self).__init__() <NE... | Check whether a HybridBlock has consistent output between the hybridized
v.s. non-hybridized versions
The network should not contain any random number generators.
Parameters
----------
net_builder : function
The builder of the HybridBlock that we are going to check the consistency.
Inside the implementation,... | 625941e7fff4ab517eb2f8b7 |
def _await_action(self, action): <NEW_LINE> <INDENT> if action and action.status == 'completed': <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif not action: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> with start_action(action_type=six.text_type( 'flocker:node:agents:do:await'), do_action_type=action.t... | Waits for an operation to complete
:param action: A action object to operate on
:type action: ``digitalocean.Action.Action``
:return: Whether the action was successful
:rtype: bool | 625941e7f7d966606f6aa482 |
def get_operation(request): <NEW_LINE> <INDENT> operations = Operation.objects.values() <NEW_LINE> operation_list = [] <NEW_LINE> for operation in operations: <NEW_LINE> <INDENT> operation_list.append(operation) <NEW_LINE> <DEDENT> return JsonResponse({'result': True, 'data': operation_list}) | 获取执行记录 | 625941e7442bda511e8be88a |
def safe_point(grid, indices, mu, window_size=5): <NEW_LINE> <INDENT> return safe_slope(analysis.gradient(grid, indices, window_size=window_size), mu) | Determine whether a point is safe for the probe to climb.
:param grid: 2-D grid of Z values
:param indices: indices of point
:param mu: coefficient of friction at point
:param window_size: window size for gradient fit calculation (default 5)
:return: | 625941e7b5575c28eb68e47c |
def handle_add_var( request, basket, product_id, quantity=1, unit_type='internal', **kwargs): <NEW_LINE> <INDENT> vars = dict((int(k.split("_")[-1]), int(v)) for (k, v) in six.iteritems(kwargs) if k.startswith("var_")) <NEW_LINE> var_product = ProductVariationResult.resolve(product_id, combination=vars) <NEW_LINE> if n... | Handle adding a complex variable product into the basket by resolving the combination variables.
This actually uses `kwargs`, expecting `var_XXX=YYY` to exist there, where `XXX` is the PK
of a ProductVariationVariable and YYY is the PK of a ProductVariationVariableValue. Confused yet?
:param quantity: Quantity of the ... | 625941e71f5feb6acb0c4fc1 |
def poorPigs(self, buckets, minutesToDie, minutesToTest): <NEW_LINE> <INDENT> val = minutesToTest // minutesToDie + 1 <NEW_LINE> res = 0 <NEW_LINE> while val ** res < buckets: <NEW_LINE> <INDENT> res += 1 <NEW_LINE> <DEDENT> return res | :type buckets: int
:type minutesToDie: int
:type minutesToTest: int
:rtype: int | 625941e791f36d47f21ac96f |
def main(args=None): <NEW_LINE> <INDENT> rclpy.init(args=args) <NEW_LINE> node = AStarPlanner() <NEW_LINE> rclpy.spin(node) <NEW_LINE> node.destroy_node() <NEW_LINE> rclpy.shutdown() | Main function. | 625941e7097d151d1a2232cf |
def to_dict(self): <NEW_LINE> <INDENT> parent_dict = super(FileObj, self).to_dict() <NEW_LINE> return parent_dict | Returns a dictionary representation of this File | 625941e7a8ecb033257d3544 |
def test_sanity(self): <NEW_LINE> <INDENT> for B in self._B: <NEW_LINE> <INDENT> if not set(['vL', 'vR', 'p', 'q']) <= set(B.get_leg_labels()): <NEW_LINE> <INDENT> raise ValueError("B has wrong labels " + repr(B.get_leg_labels())) <NEW_LINE> <DEDENT> <DEDENT> super().test_sanity() | Sanity check. Raises Errors if something is wrong. | 625941e730dc7b7665901dda |
def list_documents(self, limit=None): <NEW_LINE> <INDENT> limit_str = '' <NEW_LINE> if limit: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> limit_str = 'LIMIT {}'.format(int(limit)) <NEW_LINE> <DEDENT> except (TypeError, ValueError): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> query = ('SELECT vid FROM dataset... | Generates vids of all indexed datasets.
Args:
limit (int, optional): If not empty, the maximum number of results to return
Generates:
str: vid of the dataset. | 625941e71d351010ab855f93 |
def analyse(self): <NEW_LINE> <INDENT> bad_edges = list() <NEW_LINE> ss = OCC.ShapeAnalysis.ShapeAnalysis_Shell() <NEW_LINE> ss.LoadShells(self._wrapped_instance) <NEW_LINE> if ss.HasFreeEdges(): <NEW_LINE> <INDENT> bad_edges = [e for e in aocutils.topology.Topo(ss.BadEdges()).edges()] <NEW_LINE> <DEDENT> return bad_ed... | Bad edges of the shell | 625941e75fdd1c0f98dc06ad |
def init(self): <NEW_LINE> <INDENT> use_update_timer = self.get_property("useUpdateTimer") <NEW_LINE> if use_update_timer is None: <NEW_LINE> <INDENT> use_update_timer = True <NEW_LINE> <DEDENT> logging.getLogger("HWR").info( "SampleChanger: Using update timer is %s " % use_update_timer ) <NEW_LINE> if use_update_timer... | HardwareObject init method | 625941e7a934411ee3751b0d |
def __init__(self, *args, **kwds): <NEW_LINE> <INDENT> if args or kwds: <NEW_LINE> <INDENT> super(Game_Info, self).__init__(*args, **kwds) <NEW_LINE> if self.phase is None: <NEW_LINE> <INDENT> self.phase = 0 <NEW_LINE> <DEDENT> if self.state is None: <NEW_LINE> <INDENT> self.state = 0 <NEW_LINE> <DEDENT> if self.time i... | Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future message
changes. You cannot mix in-order arguments and keyword arguments.
The available fields are:
phase,state,time
:param args: com... | 625941e70383005118ecfa59 |
def _normalize_names(self, item_node): <NEW_LINE> <INDENT> normalized_names = { 'date': 'timerange_start', 'spatial': 'spatial', 'filename': 'Filename', 'eop:platform': 'FamilyName', 'eop:instrument': {'eop:shortname': 'InstrumentShortName', 'eop:description': 'InstrumentName'}, 'sar:polarisationchannels': 'Polarisatio... | Return a dictionary of metadata fields with normalized names. | 625941e726238365f5f0f2ed |
def chash(_alg, msg, it): <NEW_LINE> <INDENT> dig = getattr(hashlib, _alg) <NEW_LINE> for _ in range(it): <NEW_LINE> <INDENT> msg = dig(bytes(str(msg), "utf-8")).hexdigest() <NEW_LINE> <DEDENT> return msg | Wrapper for hashlib's digest operations that hashes a piece of data
repeatedly if needed. | 625941e7e5267d203edce10f |
def p_inteface_dcl(self, args): <NEW_LINE> <INDENT> root = nodes.InterfaceNode() <NEW_LINE> root.add_child(nodes.IdNode(args[1].attr)) <NEW_LINE> root.add_children([nodes.EmptyNode(), args[2]]) <NEW_LINE> return root | interface_dcl ::= INTERFACE ID interface_body | 625941e79c8ee82313fbbbef |
def _parse_includes(column_names): <NEW_LINE> <INDENT> dotted_names, columns = partition(column_names, lambda name: '.' in name) <NEW_LINE> relations = defaultdict(list) <NEW_LINE> for name in dotted_names: <NEW_LINE> <INDENT> relation, field = name.split('.', 1) <NEW_LINE> if relation in columns: <NEW_LINE> <INDENT> r... | Returns a pair, consisting of a list of column names to include on the
left and a dictionary mapping relation name to a list containing the names
of fields on the related model which should be included.
`column_names` must be a list of strings.
If the name of a relation appears as a key in the dictionary, then it will
... | 625941e76aa9bd52df03721f |
def findAll(self, selectorQuery): <NEW_LINE> <INDENT> return QWebElementCollection() | QWebElementCollection QWebElement.findAll(QString selectorQuery) | 625941e7ab23a570cc2505ff |
def get_materials_from_web(self, criteria, properties=None, max_request_size=1000): <NEW_LINE> <INDENT> if not properties: <NEW_LINE> <INDENT> properties = list(self.mapping.keys()) <NEW_LINE> <DEDENT> for data in self.get_properties_from_web( criteria, properties + ['aflowlib_date'], max_request_size=max_request_size)... | Produces propnet materials from AFLUX API using a Mongo-like query
construction. To use a MongoDB store, use get_materials_from_store().
Note: `criteria` cannot be complex. Simple equality, inequality, or '$in'
schema are supported.
Note: if `properties` is empty, only the AFLOW keywords listed in
AflowAdapt... | 625941e7f8510a7c17cf9b78 |
def report(self, experiment_name: str, experiment: ExperimentConfig, report_dir: Path) -> Any: <NEW_LINE> <INDENT> pass | report the results of an experiment
:param experiment_name: the name of the experiment.
:param experiment: the completed experiment.
:param report_dir: the directory in which to write the report
:return: the key metric value, it's assumed higher is better. | 625941e7cdde0d52a9e534af |
def __len__(self): <NEW_LINE> <INDENT> return sum(i['quantity'] for i in self.cart.values()) | Returns all items in the cart | 625941e7eab8aa0e5d26dfd2 |
def prune( self, element: Element, q_size: int = None, pipeline=None, invert: bool = False ) -> tuple[list[T], int]: <NEW_LINE> <INDENT> if q_size is None: <NEW_LINE> <INDENT> q_size = element.sorted_set_size(self.sorted_set_key) <NEW_LINE> <DEDENT> pruned = [] <NEW_LINE> while q_size > self.max_len: <NEW_LINE> <INDENT... | Prune to max length
Args:
q_size: Current size of the queue.
element: Element to use to communicate with metrics.
pipeline: Pipeline to use for metrics, else will just put it on the
element
invert: Whether we should invert the pruning logic
Returns:
List of items pruned | 625941e7236d856c2ad44c59 |
def __eq__(self, other): <NEW_LINE> <INDENT> if self and other: <NEW_LINE> <INDENT> if self is other: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif self.value != self.__class__(other).value: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> elif len(self) != len(other): <NEW_LINE> <INDENT> return False <N... | Checks for equality of two trees. | 625941e776e4537e8c351aee |
def import_module(module_name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return importlib.import_module(module_name) <NEW_LINE> <DEDENT> except ImportError as err: <NEW_LINE> <INDENT> raise UnknownModuleError(str(err)) | Given a dotted Python path, imports & returns the module.
If not found, raises ``UnknownModuleError``.
Ex::
mod = import_module('random')
:param module_name: The dotted Python path
:type module_name: string
:returns: module | 625941e799cbb53fe679305e |
@pytest.fixture <NEW_LINE> def unexpected_exception_event(): <NEW_LINE> <INDENT> return exception_event(ValueError("Unexpected!")) | Return an unexpected exception event that no filter should stop. | 625941e7711fe17d825427da |
def test_compress_response(self): <NEW_LINE> <INDENT> r = GZipMiddleware().process_response(self.req, self.resp) <NEW_LINE> self.assertEqual(self.decompress(r.content), self.compressible_string) <NEW_LINE> self.assertEqual(r.get('Content-Encoding'), 'gzip') <NEW_LINE> self.assertEqual(r.get('Content-Length'), str(len(r... | Compression is performed on responses with compressible content. | 625941e77047854f462a187d |
def worker(num): <NEW_LINE> <INDENT> print('Worker #{0}'.format(num)) <NEW_LINE> return True | Thread worker. | 625941e71f037a2d8b946676 |
def Remove(this, a_table_name, a_force=False): <NEW_LINE> <INDENT> num_rows = None <NEW_LINE> if this.dbOp.LOCK: <NEW_LINE> <INDENT> if a_force is True: <NEW_LINE> <INDENT> this.dbOp.LOCK = 0 <NEW_LINE> num_rows = this.dbOp.Remove(a_table_name) <NEW_LINE> this.dbOp.LOCK = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT>... | Remove data from table.
This is not dropping the table. | 625941e78e71fb1e9831dc20 |
def make_stata_side_effect(recognized = True): <NEW_LINE> <INDENT> def stata_side_effect(*args, **kwargs): <NEW_LINE> <INDENT> command = args[0] <NEW_LINE> match = helpers.command_match(command, 'stata') <NEW_LINE> if match.group('executable') == recognized: <NEW_LINE> <INDENT> script_name = match.group('source') <NE... | Make a side effect mocking the behaviour of
subprocess.check_output() when `recognized` is
the only recognised system command. | 625941e70383005118ecfa5a |
def angle_to(self, theta): <NEW_LINE> <INDENT> raw_diff = theta - self.theta <NEW_LINE> if raw_diff > np.pi: <NEW_LINE> <INDENT> return -(raw_diff - np.pi) <NEW_LINE> <DEDENT> elif raw_diff < - np.pi: <NEW_LINE> <INDENT> return -(raw_diff + np.pi) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return raw_diff | Return the shortest angular distance (in radians) between
two angles | 625941e7d268445f265b52e8 |
def test_tree(self): <NEW_LINE> <INDENT> with TemporaryDirectory() as tempdir: <NEW_LINE> <INDENT> self.populate_tree(tempdir, 2, width=2) <NEW_LINE> tree = StorageTree(tempdir) <NEW_LINE> names = ['0/0', '0/1', '1/0', '1/1'] <NEW_LINE> self.assertEqual( [k for k, v in tree.iter_storage()], names ) <NEW_LINE> for k, v ... | Test the basic functions of a tree. | 625941e70a50d4780f66730e |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.