Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
3,200
def unicode_to_string(self): for tag in self.tags: self.ununicode.append(str(tag))
Convert unicode in string
3,201
def syscall_direct(*events): def _syscall(scheduler, processor): for e in events: processor(e) return _syscall
Directly process these events. This should never be used for normal events.
3,202
def schedule_downtime(scope, api_key=None, app_key=None, monitor_id=None, start=None, end=None, message=None, recurrence=None, timezone=None, ...
Schedule downtime for a scope of monitors. CLI Example: .. code-block:: bash salt-call datadog.schedule_downtime 'host:app2' \\ stop=$(date --date='30 minutes' +%s) \\ app_key='0123456789' \\ ...
3,203
def is_complete(self): return all( [node.route_allocation() is not None for node in list(self._nodes.values()) if node != self._problem.depot()] )
Returns True if this is a complete solution, i.e, all nodes are allocated Returns ------- bool True if all nodes are llocated.
3,204
def getVisibility(self): try: if self.map[GET_VISIBILITY_PROPERTY] == : return VISIBLE elif self.map[GET_VISIBILITY_PROPERTY] == : return INVISIBLE elif self.map[GET_VISIBILITY_PROPERTY] == : return GONE el...
Gets the View visibility
3,205
def download(self, url, dest_path=None): if os.path.exists(dest_path): os.remove(dest_path) resp = get(url, stream=True) size = int(resp.headers.get("content-length")) label = "Downloading {filename} ({size:.2f}MB)".format( ...
:param url: :type url: str :param dest_path: :type dest_path: str
3,206
def pow2_quantized_affine(inp, n_outmaps, base_axis=1, w_init=None, b_init=None, fix_parameters=False, rng=None, with_bias=True, quantize_w=True, sign_w=True, with_zero_w=False, n_w=8, m_w=2, ste_fine_grained_w=True,...
Pow2 Quantized Affine. Pow2 Quantized Affine is the affine function, except the definition of the inner product is modified. The input-output relation of this function is as follows: .. math:: y_j = \sum_{i} Q(w_{ji}) x_i, where :math:`Q(w_{ji})` is the power-of-2 quantization function. ...
3,207
def stage(self): if not in os.environ or not in os.environ: raise BuildError("You must set the PYPI_USER and PYPI_PASS environment variables") try: import twine except ImportError: raise BuildError("You must install twine in order to release pytho...
Stage python packages for release, verifying everything we can about them.
3,208
def get_build_configuration(id=None, name=None): data = get_build_configuration_raw(id, name) if data: return utils.format_json(data)
Retrieve a specific BuildConfiguration
3,209
def _set_serial_console(self): yield from self._modify_vm("--uart1 0x3F8 4") pipe_name = self._get_pipe_name() args = [self._vmname, "--uartmode1", "server", pipe_name] yield from self.manager.execute("modifyvm", args)
Configures the first serial port to allow a serial console connection.
3,210
def process_file(source_file): if source_file.endswith((, )): txt = extract_pdf(source_file) elif source_file.endswith((, , , )): with open(source_file, ) as f: txt = f.read() else: logger.info("Unsupported file extension for file {}".format(source_file)) ret...
Extract text from a file (pdf, txt, eml, csv, json) :param source_file path to file to read :return text from file
3,211
def rollsd(self, scale=1, **kwargs): sd ts = self.rollapply(, **kwargs) if scale != 1: ts *= scale return ts
A :ref:`rolling function <rolling-function>` for stadard-deviation values: Same as:: self.rollapply('sd', **kwargs)
3,212
def _fix_lsm_bitspersample(self, parent): if self.code != 258 or self.count != 2: return log.warning(, self.code) value = struct.pack(, *self.value) self.valueoffset = struct.unpack(, value)[0] parent.filehandle.seek(self.valueoffset) self.va...
Correct LSM bitspersample tag. Old LSM writers may use a separate region for two 16-bit values, although they fit into the tag value element of the tag.
3,213
def run( self, for_time=None ): self.for_time = for_time try: self.is_initialised() except AttributeError: raise if self.number_of_equilibration_jumps > 0: for step in range( self.number_of_equilibration_jumps ): self.lattice.j...
Run the simulation. Args: for_time (:obj:Float, optional): If `for_time` is set, then run the simulation until a set amount of time has passed. Otherwise, run the simulation for a set number of jumps. Defaults to None. Returns: None
3,214
def filter(self, dict_name, priority_min=, priority_max=, start=0, limit=None): conn = redis.Redis(connection_pool=self.pool) script = conn.register_script() if limit is None: limit = -1 res = script(keys=[self._lock_name, self._namespac...
Get a subset of a dictionary. This retrieves only keys with priority scores greater than or equal to `priority_min` and less than or equal to `priority_max`. Of those keys, it skips the first `start` ones, and then returns at most `limit` keys. With default parameters, this ret...
3,215
def denoise_grid(self, val, expand=1): updated_grid = [[self.grd.get_tile(y,x) \ for x in range(self.grd.grid_width)] \ for y in range(self.grd.grid_height)] for row in range(self.grd.get_grid_height() - expand): for col in ra...
for every cell in the grid of 'val' fill all cells around it to de noise the grid
3,216
def _make_shred(self, c, name, feature_extractors, sheet_name): height, width, channels = self.orig_img.shape r_x, r_y, r_w, r_h = cv2.boundingRect(c) epsilon = 0.01 * cv2.arcLength(c, True) simplified_contour = cv2.approxPolyDP(c, epsilon, True) ...
Creates a Shred instances from a given contour. Args: c: cv2 contour object. name: string shred name within a sheet. feature_extractors: iterable of AbstractShredFeature instances. Returns: A new Shred instance or None on failure.
3,217
def not_has_branch(branch): if _has_branch(branch): msg = .format(branch) raise temple.exceptions.ExistingBranchError(msg)
Raises `ExistingBranchError` if the specified branch exists.
3,218
def before_app_websocket(self, func: Callable) -> Callable: self.record_once(lambda state: state.app.before_websocket(func)) return func
Add a before request websocket to the App. This is designed to be used as a decorator, and has the same arguments as :meth:`~quart.Quart.before_websocket`. It applies to all requests to the app this blueprint is registered on. An example usage, .. code-block:: python bluep...
3,219
def channels_open(self, room_id, **kwargs): return self.__call_api_post(, roomId=room_id, kwargs=kwargs)
Adds the channel back to the user’s list of channels.
3,220
def run(self): self.fenum.write() self.fcpp = open(os.path.join(os.path.abspath(self.ctp_dir), ), ) for idx, line in enumerate(self.fcpp): l = self.process_line(idx, line) self.f_data_type.write(l) self.fcpp.close() self.f_data_type.clo...
主函数
3,221
def init_model(engine, create=True, drop=False): meta.engine = engine meta.metadata = MetaData(bind=meta.engine) meta.Session = scoped_session(sessionmaker(bind=meta.engine)) model.setup_tables(create=create, drop=drop)
Initializes the shared SQLAlchemy state in the L{coilmq.store.sa.model} module. @param engine: The SQLAlchemy engine instance. @type engine: C{sqlalchemy.Engine} @param create: Whether to create the tables (if they do not exist). @type create: C{bool} @param drop: Whether to drop the tables (if t...
3,222
def __event_exist(self, event_type): for i in range(self.len()): if self.events_list[i][1] < 0 and self.events_list[i][3] == event_type: return i return -1
Return the event position, if it exists. An event exist if: * end is < 0 * event_type is matching Return -1 if the item is not found.
3,223
def _maybe_throw(self): if self._err: ex_cls, ex_obj, ex_bt = self._err self._err = None PyCBC.raise_helper(ex_cls, ex_obj, ex_bt)
Throw any deferred exceptions set via :meth:`_add_err`
3,224
def GET(self, func, data): if func not in []: s, message = self.checkAccount() if s is False: return False, message url = nurls[func] r = self.session.get(url, params = data) r.encoding = if self.debug: print r.text...
Send GET request to execute Ndrive API :param func: The function name you want to execute in Ndrive API. :param params: Parameter data for HTTP request. :returns: metadata when success or False when failed
3,225
def add_plot_parser(subparsers): argparser_replot = subparsers.add_parser("replot", help="Reproduce GSEA desktop output figures.") group_replot = argparser_replot.add_argument_group("Input arguments") group_replot.add_argument("-i", "--indir", action="store", dest="indir", required=True, metavar=, ...
Add function 'plot' argument parsers.
3,226
def get_opcodes_from_bp_table(bp): x = len(bp) - 1 y = len(bp[0]) - 1 opcodes = [] while x != 0 or y != 0: this_bp = bp[x][y] opcodes.append(this_bp) if this_bp[0] == EQUAL or this_bp[0] == REPLACE: x = x - 1 y = y - 1 elif this_bp[0] == INSER...
Given a 2d list structure, collect the opcodes from the best path.
3,227
def add_constraint(self, name, coefficients={}, ub=0): if name in self._constraints: raise ValueError( "A constraint named " + name + " already exists." ) self._constraints[name] = len(self._constraints) self.upper_bounds = np.append(self.upper_bo...
Add a constraint to the problem. The constrain is formulated as a dictionary of variable names to linear coefficients. The constraint can only have an upper bound. To make a constraint with a lower bound, multiply all coefficients by -1.
3,228
def register(self, config_file, contexts, config_template=None): self.templates[config_file] = OSConfigTemplate( config_file=config_file, contexts=contexts, config_template=config_template ) log(.format(config_file), level=INFO)
Register a config file with a list of context generators to be called during rendering. config_template can be used to load a template from a string instead of using template loaders and template files. :param config_file (str): a path where a config file will be rendered :param ...
3,229
def pmdec(self,*args,**kwargs): out= self._orb.pmdec(*args,**kwargs) if len(out) == 1: return out[0] else: return out
NAME: pmdec PURPOSE: return proper motion in declination (in mas/yr) INPUT: t - (optional) time at which to get pmdec (can be Quantity) obs=[X,Y,Z,vx,vy,vz] - (optional) position and velocity of observer in the Galactocentric fr...
3,230
def register(self, name): def register_func(func): self.store[name] = func return func return register_func
Decorator for registering a function with PyPhi. Args: name (string): The name of the function
3,231
def get_auth_basic(self): username = password = auth_header = self.get_header() if auth_header: m = re.search(r"^Basic\s+(\S+)$", auth_header, re.I) if m: auth_str = Base64.decode(m.group(1)) username, password = auth_str...
return the username and password of a basic auth header if it exists
3,232
def set(self, tclass, tnum, tlvt=0, tdata=b): if isinstance(tdata, bytearray): tdata = bytes(tdata) elif not isinstance(tdata, bytes): raise TypeError("tag data must be bytes or bytearray") self.tagClass = tclass self.tagNumber = tnum self.tagLVT...
set the values of the tag.
3,233
def show_linkinfo_output_show_link_info_linkinfo_domain_reachable(self, **kwargs): config = ET.Element("config") show_linkinfo = ET.Element("show_linkinfo") config = show_linkinfo output = ET.SubElement(show_linkinfo, "output") show_link_info = ET.SubElement(output, "sho...
Auto Generated Code
3,234
def add_exit(self, guard, dst, jk, ip): self.irsb.statements.append(Exit(guard, dst.con, jk, ip))
Add an exit out of the middle of an IRSB. (e.g., a conditional jump) :param guard: An expression, the exit is taken if true :param dst: the destination of the exit (a Const) :param jk: the JumpKind of this exit (probably Ijk_Boring) :param ip: The address of this exit's source
3,235
def delay(self, func, args=None, kwargs=None, queue=None, hard_timeout=None, unique=None, lock=None, lock_key=None, when=None, retry=None, retry_on=None, retry_method=None, max_queue_size=None): task = Task(self, func, args=args, kwargs=kwargs, queue=queue, ...
Queues a task. See README.rst for an explanation of the options.
3,236
def has_code(state, text, pattern=True, not_typed_msg=None): if not not_typed_msg: if pattern: not_typed_msg = "Could not find the correct pattern in your code." else: not_typed_msg = "Could not find the following text in your code: %r" % text student_code = state.s...
Test the student code. Tests if the student typed a (pattern of) text. It is advised to use ``has_equal_ast()`` instead of ``has_code()``, as it is more robust to small syntactical differences that don't change the code's behavior. Args: text (str): the text that is searched for pattern (b...
3,237
def __embed_frond(node_u, node_w, dfs_data, as_branch_marker=False): d_u = D(node_u, dfs_data) d_w = D(node_w, dfs_data) comp_d_w = abs(d_w) if as_branch_marker: d_w *= -1 if dfs_data[] == : __insert_frond_RF(d_w, d_u, dfs_data) else: __...
Embeds a frond uw into either LF or RF. Returns whether the embedding was successful.
3,238
def _sparse_blockify(tuples, dtype=None): new_blocks = [] for i, names, array in tuples: array = _maybe_to_sparse(array) block = make_block(array, placement=[i]) new_blocks.append(block) return new_blocks
return an array of blocks that potentially have different dtypes (and are sparse)
3,239
def _leftMouseDragged(self, stopCoord, strCoord, speed): appPid = self._getPid() if strCoord == (0, 0): loc = AppKit.NSEvent.mouseLocation() strCoord = (loc.x, Quartz.CGDisplayPixelsHigh(0) - loc.y) appPid = self._getPid() ...
Private method to handle generic mouse left button dragging and dropping. Parameters: stopCoord(x,y) drop point Optional: strCoord (x, y) drag point, default (0,0) get current mouse position speed (int) 1 to unlimit, simulate mouse moving ac...
3,240
def tagfunc(nargs=None, ndefs=None, nouts=None): def wrapper(f): return wraps(f)(FunctionWithTag(f, nargs=nargs, nouts=nouts, ndefs=ndefs)) return wrapper
decorate of tagged function
3,241
def _parser(): launcher = % sys.version_info.major parser = argparse.ArgumentParser( description= % __description__, epilog= % launcher, prog=launcher) parser.add_argument( , action=, version= + __version__) subparsers = parser.add_...
Parse command-line options.
3,242
def execute(self): logging.info( % self.project_name) project_csv_meta = self.rws_connection.send_request(ProjectMetaDataRequest(self.project_name)) self.db_adapter.processMetaData(project_csv_meta) for dataset_name in self.db_adapter.datasets.keys(): ...
Generate local DB, pulling metadata and data from RWSConnection
3,243
def edit_account_info(self, short_name=None, author_name=None, author_url=None): return self._telegraph.method(, values={ : short_name, : author_name, : author_url })
Update information about a Telegraph account. Pass only the parameters that you want to edit :param short_name: Account name, helps users with several accounts remember which they are currently using. Displayed to the user above the "Edit/Publis...
3,244
def fetch_mim_files(api_key, mim2genes=False, mimtitles=False, morbidmap=False, genemap2=False): LOG.info("Fetching OMIM files from https://omim.org/") mim2genes_url = mimtitles_url= .format(api_key) morbidmap_url = .format(api_key) genemap2_url = .format(api_key) mim_files = {...
Fetch the necessary mim files using a api key Args: api_key(str): A api key necessary to fetch mim data Returns: mim_files(dict): A dictionary with the neccesary files
3,245
def generate_data_key(key_id, encryption_context=None, number_of_bytes=None, key_spec=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): alias/mykey conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: ...
Generate a secure data key. CLI example:: salt myminion boto_kms.generate_data_key 'alias/mykey' number_of_bytes=1024 key_spec=AES_128
3,246
def _get_axis_bounds(self, dim, bunch): if dim in self.attributes: vmin, vmax = bunch[] assert vmin is not None assert vmax is not None return vmin, vmax return (-1. / self.scaling, +1. / self.scaling)
Return the min/max of an axis.
3,247
def load_remote_db(self): signature_version = self.settings_dict.get("SIGNATURE_VERSION", "s3v4") s3 = boto3.resource( , config=botocore.client.Config(signature_version=signature_version), ) if not in self.settings_dict[]: try: ...
Load remote S3 DB
3,248
def _query_ned_and_add_results_to_database( self, batchCount): self.log.debug( ) tableName = self.dbTableName converter = unit_conversion( log=self.log ) totalCount = len(self.theseIds) print "re...
query ned and add results to database **Key Arguments:** - ``batchCount`` - the index number of the batch sent to NED .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples a...
3,249
def list_fonts(): vals = _list_fonts() for font in _vispy_fonts: vals += [font] if font not in vals else [] vals = sorted(vals, key=lambda s: s.lower()) return vals
List system fonts Returns ------- fonts : list of str List of system fonts.
3,250
def circ_corrcl(x, y, tail=): from scipy.stats import pearsonr, chi2 x = np.asarray(x) y = np.asarray(y) if x.size != y.size: raise ValueError() x, y = remove_na(x, y, paired=True) n = x.size rxs = pearsonr(y, np.sin(x))[0] rxc = pearsonr(y, np.cos(x))[0] ...
Correlation coefficient between one circular and one linear variable random variables. Parameters ---------- x : np.array First circular variable (expressed in radians) y : np.array Second circular variable (linear) tail : string Specify whether to return 'one-sided' or ...
3,251
def process(self): if WINDOWS: select_inputs = [] for i in self.inputs: if not isinstance(i, SelectableObject): warning("Unknown ignored object type: %s", type(i)) elif i.__selectable_force_select__: ...
Entry point of SelectableSelector
3,252
def create(cls, name, template=None): command = [, , name] if template: command.extend([, template]) subwrap.run(command)
Creates an LXC
3,253
def filter(self, scored_list): top_n_key = -1 * self.top_n top_n_list = sorted(scored_list, key=lambda x: x[1])[top_n_key:] result_list = sorted(top_n_list, key=lambda x: x[0]) return result_list
Filtering with top-n ranking. Args: scored_list: The list of scoring. Retruns: The list of filtered result.
3,254
def content(self, content): allowed_values = ["UNRELEASED", "EARLYACCESS", "SUPPORTED", "EXTENDED_SUPPORT", "EOL"] if not set(content).issubset(set(allowed_values)): raise ValueError( "Invalid values for `content` [{0}], must be a subset of [{1}]" .fo...
Sets the content of this SupportLevelPage. :param content: The content of this SupportLevelPage. :type: list[str]
3,255
def get_tabs(self, request, **kwargs): if self._tab_group is None: self._tab_group = self.tab_group_class(request, **kwargs) return self._tab_group
Returns the initialized tab group for this view.
3,256
def remove_dashboard_tag(self, id, tag_value, **kwargs): kwargs[] = True if kwargs.get(): return self.remove_dashboard_tag_with_http_info(id, tag_value, **kwargs) else: (data) = self.remove_dashboard_tag_with_http_info(id, tag_value, **kwargs) r...
Remove a tag from a specific dashboard # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.remove_dashboard_tag(id, tag_value, async_req=True) >>> result = thread....
3,257
async def write(self, item): await self._queue.put(item) self._can_read.set() if self._queue.full(): self._can_write.clear()
Write an item in the queue. :param item: The item.
3,258
def byname(nlist): warnings.warn("The internal byname() function has been deprecated, with " "no replacement.", DeprecationWarning, stacklevel=_stacklevel_above_module(__name__)) return OrderedDict([(x.name, x) for x in nlist])
**Deprecated:** Convert a list of named objects into an ordered dictionary indexed by name. This function is internal and has been deprecated in pywbem 0.12.
3,259
def iter_chunks_class(self): for m in self.get_metadata(): try: yield self.chunkclass(self.get_chunk(m.x, m.z)) except RegionFileFormatError: pass
Yield each readable chunk present in the region. Chunks that can not be read for whatever reason are silently skipped. This function returns a :class:`nbt.chunk.Chunk` instance.
3,260
def _win32_read_junction(path): if not jwfs.is_reparse_point(path): raise ValueError() handle = jwfs.api.CreateFile( path, 0, 0, None, jwfs.api.OPEN_EXISTING, jwfs.api.FILE_FLAG_OPEN_REPARSE_POINT | jw...
Returns the location that the junction points, raises ValueError if path is not a junction. CommandLine: python -m ubelt._win32_links _win32_read_junction Example: >>> # xdoc: +REQUIRES(WIN32) >>> import ubelt as ub >>> root = ub.ensure_app_cache_dir('ubelt', 'win32_junctio...
3,261
def from_json_file(file: TextIO, check_version=True) -> BELGraph: graph_json_dict = json.load(file) return from_json(graph_json_dict, check_version=check_version)
Build a graph from the Node-Link JSON contained in the given file.
3,262
def _generic_signal_handler(self, signal_type): print("</pre>") message = "Got " + signal_type + ". Failing gracefully..." self.timestamp(message) self.fail_pipeline(KeyboardInterrupt(signal_type), dynamic_recover=True) sys.exit(1)
Function for handling both SIGTERM and SIGINT
3,263
def stop_playback(self): self._sink.flush() self._sink.stop() self._playing = False
Stop playback from the audio sink.
3,264
def __setAsOrphaned(self): cmplReason = ClientJobsDAO.CMPL_REASON_ORPHAN cmplMessage = "Killed by Scheduler" self._jobsDAO.modelSetCompleted(self._modelID, cmplReason, cmplMessage)
Sets the current model as orphaned. This is called when the scheduler is about to kill the process to reallocate the worker to a different process.
3,265
def abort(self, jobs=None, targets=None, block=None): block = self.block if block is None else block jobs = jobs if jobs is not None else list(self.outstanding) targets = self._build_targets(targets)[0] msg_ids = [] if isinstance(jobs, (basestring,AsyncResult)):...
Abort specific jobs from the execution queues of target(s). This is a mechanism to prevent jobs that have already been submitted from executing. Parameters ---------- jobs : msg_id, list of msg_ids, or AsyncResult The jobs to be aborted If ...
3,266
def clean_egginfo(self): dir_name = os.path.join(self.root, self.get_egginfo_dir()) self._clean_directory(dir_name)
Clean .egginfo directory
3,267
def Run(self): "Execute the action" inputs = self.GetInput() return SendInput( len(inputs), ctypes.byref(inputs), ctypes.sizeof(INPUT))
Execute the action
3,268
def FindEnumTypeByName(self, full_name): full_name = _NormalizeFullyQualifiedName(full_name) if full_name not in self._enum_descriptors: self.FindFileContainingSymbol(full_name) return self._enum_descriptors[full_name]
Loads the named enum descriptor from the pool. Args: full_name: The full name of the enum descriptor to load. Returns: The enum descriptor for the named type.
3,269
def _scipy_distribution_positional_args_from_dict(distribution, params): params[] = params.get(, 0) if not in params: params[] = 1 if distribution == : return params[], params[] elif distribution == : return params[], params[], params[], params[] elif distribution == ...
Helper function that returns positional arguments for a scipy distribution using a dict of parameters. See the `cdf()` function here https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.beta.html#Methods\ to see an example of scipy's positional arguments. This function returns the arguments s...
3,270
def source_start(base=, book_id=): repo_htm_path = "{book_id}-h/{book_id}-h.htm".format(book_id=book_id) possible_paths = ["book.asciidoc", repo_htm_path, "{}-0.txt".format(book_id), "{}-8.txt".format(book_id), "{}.txt"...
chooses a starting source file in the 'base' directory for id = book_id
3,271
def set_data(self, capacity, voltage=None, capacity_label="q", voltage_label="v" ): logging.debug("setting data (capacity and voltage)") if isinstance(capacity, pd.DataFrame): logging.debug("recieved a pandas.DataFrame") self.capacity ...
Set the data
3,272
def filter_kwargs(_function, *args, **kwargs): if has_kwargs(_function): return _function(*args, **kwargs) func_code = six.get_function_code(_function) function_args = func_code.co_varnames[:func_code.co_argcount] filtered_kwargs = {} for kwarg, value in list(kwargs.items())...
Given a function and args and keyword args to pass to it, call the function but using only the keyword arguments which it accepts. This is equivalent to redefining the function with an additional \*\*kwargs to accept slop keyword args. If the target function already accepts \*\*kwargs parameters, no f...
3,273
def stoch(df, window=14, d=3, k=3, fast=False): my_df = pd.DataFrame(index=df.index) my_df[] = df[].rolling(window).max() my_df[] = df[].rolling(window).min() my_df[] = 100 * (df[] - my_df[])/(my_df[] - my_df[]) my_df[] = my_df[].rolling(d).mean() if fast: return my_df.loc[:, [,...
compute the n period relative strength indicator http://excelta.blogspot.co.il/2013/09/stochastic-oscillator-technical.html
3,274
def NetFxSDKIncludes(self): if self.vc_ver < 14.0 or not self.si.NetFxSdkDir: return [] return [os.path.join(self.si.NetFxSdkDir, r)]
Microsoft .Net Framework SDK Includes
3,275
def parallel_part(data, parallel): if parallel is None or "SGE_TASK_ID" not in os.environ: return data data_per_job = int(math.ceil(float(len(data)) / float(parallel))) task_id = int(os.environ[]) first = (task_id-1) * data_per_job last = min(len(data), task_id * data_per_job) return data[first:last...
parallel_part(data, parallel) -> part Splits off samples from the the given data list and the given number of parallel jobs based on the ``SGE_TASK_ID`` environment variable. **Parameters:** ``data`` : [object] A list of data that should be split up into ``parallel`` parts ``parallel`` : int or ``None``...
3,276
def hist(sample, options={}, **kwargs): kwargs[] = sample scales = kwargs.pop(, {}) if not in scales: dimension = _get_attribute_dimension(, Hist) if dimension in _context[]: scales[] = _context[][dimension] else: scales[] = LinearScale(**options.get(, {...
Draw a histogram in the current context figure. Parameters ---------- sample: numpy.ndarray, 1d The sample for which the histogram must be generated. options: dict (default: {}) Options for the scales to be created. If a scale labeled 'counts' is required for that mark, options[...
3,277
def has_started(self): timeout = False auth_in_progress = False if self._handler._connection.cbs: timeout, auth_in_progress = self._handler._auth.handle_token() if timeout: raise EventHubError("Authorization timeout.") if auth_in_progress...
Whether the handler has completed all start up processes such as establishing the connection, session, link and authentication, and is not ready to process messages. **This function is now deprecated and will be removed in v2.0+.** :rtype: bool
3,278
def keyword( name: str, ns: Optional[str] = None, kw_cache: atom.Atom["PMap[int, Keyword]"] = __INTERN, ) -> Keyword: h = hash((name, ns)) return kw_cache.swap(__get_or_create, h, name, ns)[h]
Create a new keyword.
3,279
async def edit_2fa( self, current_password=None, new_password=None, *, hint=, email=None, email_code_callback=None): if new_password is None and current_password is None: return False if email and not callable(email_code_callback): raise ValueErr...
Changes the 2FA settings of the logged in user, according to the passed parameters. Take note of the parameter explanations. Note that this method may be *incredibly* slow depending on the prime numbers that must be used during the process to make sure that everything is safe. ...
3,280
def _init(self): group_stack = [self] clip_stack = [] last_layer = None for record, channels in self._record._iter_layers(): current_group = group_stack[-1] blocks = record.tagged_blocks end_of_group = False divider = blocks.get_...
Initialize layer structure.
3,281
def run_one(self, set_title=False): s title with the work unit name :return: :const:`True` if there was a job (even if it failed) No work to do; stopping.re already quitting everything, but this is weirdly bad. logger.error(, xunit.work_spec_name, xunit.key, ex...
Get exactly one job, run it, and return. Does nothing (but returns :const:`False`) if there is no work to do. Ignores the global mode; this will do work even if :func:`rejester.TaskMaster.get_mode` returns :attr:`~rejester.TaskMaster.TERMINATE`. :param set_title: if true, set ...
3,282
def encode(self, word, max_length=-1, keep_vowels=False, vowel_char=): r word = unicode_normalize(, text_type(word.upper())) word = word.replace(, ) word = .join(c for c in word if c in self._uc_set) if word[:3] in {, , }: word = + word[3:] ...
r"""Return the Dolby Code of a name. Parameters ---------- word : str The word to transform max_length : int Maximum length of the returned Dolby code -- this also activates the fixed-length code mode if it is greater than 0 keep_vowels : bool...
3,283
def insert_before(self, value: Union[RawValue, Value], raw: bool = False) -> "ArrayEntry": return ArrayEntry(self.index, self.before, self.after.cons(self.value), self._cook_value(value, raw), self.parinst, self.schema_node, date...
Insert a new entry before the receiver. Args: value: The value of the new entry. raw: Flag to be set if `value` is raw. Returns: An instance node of the new inserted entry.
3,284
def fetch_credential(self, credential=None, profile=None): q = self.db.get(self.query.profile == profile) if q is not None: return q.get(credential)
Fetch credential from credentials file. Args: credential (str): Credential to fetch. profile (str): Credentials profile. Defaults to ``'default'``. Returns: str, None: Fetched credential or ``None``.
3,285
def flow_ramp(self): return np.linspace(1 / self.n_rows, 1, self.n_rows)*self.q
An equally spaced array representing flow at each row.
3,286
def read_certificate_signing_request(self, name, **kwargs): kwargs[] = True if kwargs.get(): return self.read_certificate_signing_request_with_http_info(name, **kwargs) else: (data) = self.read_certificate_signing_request_with_http_info(name, **kwargs) ...
read_certificate_signing_request # noqa: E501 read the specified CertificateSigningRequest # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_certificate_signing_request(name, asy...
3,287
def remove_entity(self, name): self.entities.remove(name) self.padaos.remove_entity(name)
Unload an entity
3,288
def serialzeValueToTCL(self, val, do_eval=False) -> Tuple[str, str, bool]: if isinstance(val, int): val = hInt(val) if do_eval: val = val.staticEval() if isinstance(val, RtlSignalBase): ctx = VivadoTclExpressionSerializer.getBaseContext() ...
:see: doc of method on parent class
3,289
def set_app_id(self, id, version, icon): return libvlc_set_app_id(self, str_to_bytes(id), str_to_bytes(version), str_to_bytes(icon))
Sets some meta-information about the application. See also L{set_user_agent}(). @param id: Java-style application identifier, e.g. "com.acme.foobar". @param version: application version numbers, e.g. "1.2.3". @param icon: application icon name, e.g. "foobar". @version: LibVLC 2.1...
3,290
def expect_re(regexp, buf, pos): match = regexp.match(buf, pos) if not match: return None, len(buf) return buf[match.start(1):match.end(1)], match.end(0)
Require a regular expression at the current buffer position.
3,291
def get_queryset(self): queryset = super(PageList, self).get_queryset() if hasattr(self.request, ): queryset = queryset.filter(site_id=self.request.site_id) return queryset
If MultiTenantMiddleware is used, filter queryset by request.site_id
3,292
def write(self, location=None): if location is not None: self.location = location assert self.location for io in self.editor.io_backends: if io.can_open_location(self.location): break else: self.editor.show_m...
Write file to I/O backend.
3,293
def move_forward(columns=1, file=sys.stdout): move.forward(columns).write(file=file)
Move the cursor forward a number of columns. Esc[<columns>C: Moves the cursor forward by the specified number of columns without changing lines. If the cursor is already in the rightmost column, ANSI.SYS ignores this sequence.
3,294
def wait_until(predicate, success_description, timeout=10): start = time.time() while True: retval = predicate() if retval: return retval if time.time() - start > timeout: raise AssertionError("Didn't ever %s" % success_description) time.sleep(0.1)
Wait up to 10 seconds (by default) for predicate to be true. E.g.: wait_until(lambda: client.primary == ('a', 1), 'connect to the primary') If the lambda-expression isn't true after 10 seconds, we raise AssertionError("Didn't ever connect to the primary"). Returns the pred...
3,295
def clear_all(): sure = input("Are you sure to drop the complete database content? (Type " "in upppercase YES)") if not (sure == ): db_log() sys.exit(5) client = pymongo.MongoClient(host=dbhost, port=dbport) db = client[dbname] for col in db.collection_names(...
DANGER! *This command is a maintenance tool and clears the complete database.*
3,296
def train(net, X_train, y_train, epochs, verbose_epoch, learning_rate, weight_decay, batch_size): dataset_train = gluon.data.ArrayDataset(X_train, y_train) data_iter_train = gluon.data.DataLoader(dataset_train, batch_size, shuffle=True) trainer = gl...
Trains the model.
3,297
def main_make_views(gtfs_fname): print("creating views") conn = GTFS(fname_or_conn=gtfs_fname).conn for L in Loaders: L(None).make_views(conn) conn.commit()
Re-create all views.
3,298
async def get_blueprint_params(request, left: int, right: int) -> str: res = left * right return "{left}*{right}={res}".format(left=left, right=right, res=res)
API Description: Multiply, left * right. This will show in the swagger page (localhost:8000/api/v1/).
3,299
def lookup_defs(self, variable, size_threshold=32): live_def_locs = set() if isinstance(variable, SimRegisterVariable): if variable.reg is None: l.warning() return live_def_locs size = min(variable.size, size_threshold) off...
Find all definitions of the varaible :param SimVariable variable: The variable to lookup for. :param int size_threshold: The maximum bytes to consider for the variable. For example, if the variable is 100 byte long, only the first `size_threshold` bytes are considered...