Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
1,000
def domain(self, domain=None, last_domain=None): self._print_header() if domain: PyFunceble.INTERN["to_test"] = self._format_domain(domain) else: PyFunceble.INTERN["to_test"] = None if PyFu...
Manage the case that we want to test only a domain. :param domain: The domain or IP to test. :type domain: str :param last_domain: The last domain to test if we are testing a file. :type last_domain: str :param return_status: Tell us if we need to return the status...
1,001
def tvBrowserExposure_selection_changed(self): (is_compatible, desc) = self.get_layer_description_from_browser( ) self.lblDescribeBrowserExpLayer.setText(desc) self.parent.pbnNext.setEnabled(is_compatible)
Update layer description label.
1,002
def to_struct(self, value): if self.str_format: return value.strftime(self.str_format) return value.isoformat()
Cast `time` object to string.
1,003
def run(self): latest_track = Track.objects.all().order_by() latest_track = latest_track[0] if latest_track else None importer = self.get_importer() tracks = importer.run() for track in tracks: if not latest_track or not latest...
Run import.
1,004
def rgba(self, val): rgba = _user_to_rgba(val, expand=False) if self._rgba is None: self._rgba = rgba else: self._rgba[:, :rgba.shape[1]] = rgba
Set the color using an Nx4 array of RGBA floats
1,005
def apt_autoremove(purge=True, fatal=False): cmd = [, , ] if purge: cmd.append() _run_apt_command(cmd, fatal)
Purge one or more packages.
1,006
def _ExtractMetadataFromFileEntry(self, mediator, file_entry, data_stream): if file_entry.IsRoot() and file_entry.type_indicator not in ( self._TYPES_WITH_ROOT_METADATA): return if data_stream and not data_stream.IsDefault(): return display_name = mediator.GetD...
Extracts metadata from a file entry. Args: mediator (ParserMediator): mediates the interactions between parsers and other components, such as storage and abort signals. file_entry (dfvfs.FileEntry): file entry to extract metadata from. data_stream (dfvfs.DataStream): data stream or None...
1,007
def str_blockIndent(astr_buf, a_tabs=1, a_tabLength=4, **kwargs): str_tabBoundary = " " for key, value in kwargs.iteritems(): if key == : str_tabBoundary = value b_trailN = False length = len(astr_buf) ch_trailN = astr_buf[length - 1] if ch_trailN == : b_trailN = True ast...
For the input string <astr_buf>, replace each '\n' with '\n<tab>' where the number of tabs is indicated by <a_tabs> and the length of the tab by <a_tabLength> Trailing '\n' are *not* replaced.
1,008
def gen_method_keys(self, *args, **kwargs): token = args[0] for mro_type in type(token).__mro__[:-1]: name = mro_type.__name__ yield name
Given a node, return the string to use in computing the matching visitor methodname. Can also be a generator of strings.
1,009
def findBinomialNsWithLowerBoundSampleMinimum(confidence, desiredValuesSorted, p, numSamples, nMax): def P(n, numOccurrences): return 1 - SampleMinimumDistribution(numSamples, BinomialDistribution(n, p)).cdf( numOccurrences - 1) results = [] n = 0...
For each desired value, find an approximate n for which the sample minimum has a probabilistic lower bound equal to this value. For each value, find an adjacent pair of n values whose lower bound sample minima are below and above the desired value, respectively, and return a linearly-interpolated n between the...
1,010
def get(self, id): document = self._get_document(id) if document: session_json = document["session"] return json_loads(session_json) return {}
根据 id 获取数据。 :param id: 要获取的数据的 id :return: 返回取到的数据,如果是空则返回一个空的 ``dict`` 对象
1,011
def display_lookback_returns(self): return self.lookback_returns.apply( lambda x: x.map(.format), axis=1)
Displays the current lookback returns for each series.
1,012
def create_event(self, type, data, **kwargs): if type is None: raise ValueError() if data is None: raise ValueError() data = self._convert_model(data, EventData) headers = {} if in kwargs: headers.update(kwargs.get()) sdk_he...
Create event. The **Events** API can be used to create log entries that are associated with specific queries. For example, you can record which documents in the results set were \"clicked\" by a user and when that click occured. :param str type: The event type to be created. :p...
1,013
def aDiffCytoscape(df,aging_genes,target,species="caenorhabditis elegans",limit=None, cutoff=0.4,\ taxon=None,host=cytoscape_host,port=cytoscape_port): df=df.sort_values(by=["q_value"],ascending=True) df.reset_index(inplace=True, drop=True) tmp=df[:1999] df=tmp.copy() ...
Plots tables from aDiff/cuffdiff into cytoscape using String protein queries. Uses top changed genes as well as first neighbours and difusion fo generate subnetworks. :param df: df as outputed by aDiff for differential gene expression :param aging_genes: ENS gene ids to be labeled with a diagonal ...
1,014
def draw_zijderveld(self): self.fig1.clf() axis_bounds = [0, .1, 1, .85] self.zijplot = self.fig1.add_axes( axis_bounds, frameon=False, facecolor=, label=, zorder=0) self.zijplot.clear() self.zijplot.axis() self.zijplot.xaxis.set_visible(False) ...
Draws the zijderveld plot in the GUI on canvas1
1,015
def server_list(self): nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(): try: ret[item.name] = { : item.id, : item.name, : item.status, : item.accessIPv4, ...
List servers
1,016
def reverse_dummies(self, X, mapping): out_cols = X.columns.values.tolist() mapped_columns = [] for switch in mapping: col = switch.get() mod = switch.get() insert_at = out_cols.index(mod.columns[0]) X.insert(insert_at, col, 0) ...
Convert dummy variable into numerical variables Parameters ---------- X : DataFrame mapping: list-like Contains mappings of column to be transformed to it's new columns and value represented Returns ------- numerical: DataFrame
1,017
def generate_context(context_file=, default_context=None, extra_context=None): context = OrderedDict([]) try: with open(context_file) as file_handle: obj = json.load(file_handle, object_pairs_hook=OrderedDict) except ValueError as e: if default_con...
Generate the context for a Cookiecutter project template. Loads the JSON file as a Python object, with key being the JSON filename. :param context_file: JSON file containing key/value pairs for populating the cookiecutter's variables. :param default_context: Dictionary containing config to take in...
1,018
def update(self, name: str, value=None, default=None, description: str=None): if name in self._vars: description = description or self._vars[name].description default = default or self._vars[name].default elif name == : raise ConfigError(" is a reserved name ...
Like add, but can tolerate existing values; also updates the value. Mostly used for setting fields from imported INI files and modified CLI flags.
1,019
def get_max_bond_lengths(structure, el_radius_updates=None): jmnn = JmolNN(el_radius_updates=el_radius_updates) bonds_lens = {} els = sorted(structure.composition.elements, key=lambda x: x.Z) for i1 in range(len(els)): for i2 in range(len(els) - i1): bonds_lens[els[i1], e...
Provides max bond length estimates for a structure based on the JMol table and algorithms. Args: structure: (structure) el_radius_updates: (dict) symbol->float to update atomic radii Returns: (dict) - (Element1, Element2) -> float. The two elements are ordered by Z.
1,020
def unlock(self): try: self.os.remove(self.os.path.join(self.tmp_dir, )) except Exception: pass try: self.os.rmdir(self.tmp_dir) except Exception: pass
Remove current lock. This function does not crash if it is unable to properly delete the lock file and directory. The reason is that it should be allowed for multiple jobs running in parallel to unlock the same directory at the same time (e.g. when reaching their timeout limit).
1,021
def do_execute(self): self._stopped = False self._stopping = False not_finished_actor = self.owner.first_active pending_actors = [] finished = False actor_result = None while not (self.is_stopping() or self.is_stopped()) and not finished: ...
Actual execution of the director. :return: None if successful, otherwise error message :rtype: str
1,022
def get_tokens(self, *, payer_id, credit_card_token_id, start_date, end_date): payload = { "language": self.client.language.value, "command": PaymentCommand.GET_TOKENS.value, "merchant": { "apiLogin": self.client.api_login, "apiKey": s...
With this functionality you can query previously the Credit Cards Token. Args: payer_id: credit_card_token_id: start_date: end_date: Returns:
1,023
def get_fptr(self): cmpfunc = ctypes.CFUNCTYPE(ctypes.c_int, WPARAM, LPARAM, ctypes.POINTER(KBDLLHookStruct)) return cmpfunc(self.handle_input)
Get the function pointer.
1,024
def plot_labels(ax, label_fontsize=14, xlabel=None, xlabel_arg=None, ylabel=None, ylabel_arg=None, zlabel=None, zlabel_arg=None): xlabel = xlabel if xlabel is not None else ax.get_xlabel() or ylabel = ylabel if ylabel is not None else ax.get_ylabel() or ...
Sets the labels options of a matplotlib plot Args: ax: matplotlib axes label_fontsize(int): Size of the labels' font xlabel(str): The xlabel for the figure xlabel_arg(dict): Passsed into matplotlib as xlabel arguments ylabel(str): The ylabel for the figure ylabel_ar...
1,025
def remove_overlap(self, also_remove_contiguous: bool = False) -> None: overlap = True while overlap: overlap = self._remove_overlap_sub(also_remove_contiguous) self._sort()
Merges any overlapping intervals. Args: also_remove_contiguous: treat contiguous (as well as overlapping) intervals as worthy of merging?
1,026
def emissive_part_3x(self, tb=True): try: self._e3x = self._rad3x_t11 * (1 - self._r3x) except TypeError: LOG.warning( "Couldn't derive the emissive part \n" + "Please derive the relfect...
Get the emissive part of the 3.x band
1,027
def execute_ccm_remotely(remote_options, ccm_args): if not PARAMIKO_IS_AVAILABLE: logging.warn("Paramiko is not Availble: Skipping remote execution of CCM command") return None, None ssh_client = SSHClient(remote_options.ssh_host, remote_options.ssh_port, re...
Execute CCM operation(s) remotely :return A tuple defining the execution of the command * output - The output of the execution if the output was not displayed * exit_status - The exit status of remotely executed script :raises Exception if invalid options are passed for `--dse-...
1,028
def check_guest_exist(check_index=0): def outer(f): @six.wraps(f) def inner(self, *args, **kw): userids = args[check_index] if isinstance(userids, list): userids = [uid.upper() for uid in userids] new_args = (args[:check...
Check guest exist in database. :param check_index: The parameter index of userid(s), default as 0
1,029
def to_genshi(walker): text = [] for token in walker: type = token["type"] if type in ("Characters", "SpaceCharacters"): text.append(token["data"]) elif text: yield TEXT, "".join(text), (None, -1, -1) text = [] if type in ("StartTag", "Em...
Convert a tree to a genshi tree :arg walker: the treewalker to use to walk the tree to convert it :returns: generator of genshi nodes
1,030
def occupy(self, start, stop): self._occupied.append([start, stop]) self._occupied.sort(key=lambda x: x[0])
Mark a given interval as occupied so that the manager could skip the values from ``start`` to ``stop`` (**inclusive**). :param start: beginning of the interval. :param stop: end of the interval. :type start: int :type stop: int
1,031
def get_confirmation_url(email, request, name="email_registration_confirm", **kwargs): return request.build_absolute_uri( reverse(name, kwargs={"code": get_confirmation_code(email, request, **kwargs)}) )
Returns the confirmation URL
1,032
def load_nddata(self, ndd, naxispath=None): self.clear_metadata() ahdr = self.get_header() ahdr.update(ndd.meta) self.setup_data(ndd.data, naxispath=naxispath) if ndd.wcs is None: self.wcs = wcsinfo.wrapper_class(logger=self.logger) ...
Load from an astropy.nddata.NDData object.
1,033
def add(self, resource, replace=False): if isinstance(resource, collections.Iterable): for r in resource: self.resources.add(r, replace) else: self.resources.add(resource, replace)
Add a resource or an iterable collection of resources. Will throw a ValueError if the resource (ie. same uri) already exists in the ResourceList, unless replace=True.
1,034
def get_user_list(host_name, client_name, client_pass): request = construct_request(model_type="pers", client_name=client_name, client_pass=client_pass, command="getusrs", values...
Pulls the list of users in a client. Inputs: - host_name: A string containing the address of the machine where the PServer instance is hosted. - client_name: The PServer client name. - client_pass: The PServer client's password. Output: - user_id_list: A python list of user ids.
1,035
def updateGroup(self, group, vendorSpecific=None): response = self.updateGroupResponse(group, vendorSpecific) return self._read_boolean_response(response)
See Also: updateGroupResponse() Args: group: vendorSpecific: Returns:
1,036
def time_at_shadow_length(day, latitude, multiplier): latitude_rad = radians(latitude) declination = radians(sun_declination(day)) angle = arccot( multiplier + tan(abs(latitude_rad - declination)) ) numerator = sin(angle) - sin(latitude_rad)*sin(declination) denominator = ...
Compute the time at which an object's shadow is a multiple of its length. Specifically, determine the time the length of the shadow is a multiple of the object's length + the length of the object's shadow at noon This is used in the calculation for Asr time. Hanafi uses a multiplier of 2, and everyone...
1,037
def chunked(data, chunksize): if chunksize < 1: raise ValueError("Chunksize must be at least 1!") if int(chunksize) != chunksize: raise ValueError("Chunksize needs to be an integer") res = [] cur = [] for e in data: cur.append(e) if len(cur) >= chunksize: ...
Returns a list of chunks containing at most ``chunksize`` elements of data.
1,038
def calcAFunc(self,MaggNow,AaggNow): verbose = self.verbose discard_periods = self.T_discard update_weight = 1. - self.DampingFac total_periods = len(MaggNow) logAagg = np.log(AaggNow[discard_periods:total_periods]) logMagg = np.log(MaggNow[discard...
Calculate a new aggregate savings rule based on the history of the aggregate savings and aggregate market resources from a simulation. Parameters ---------- MaggNow : [float] List of the history of the simulated aggregate market resources for an economy. AaggNow : [f...
1,039
def audio_output_enumerate_devices(self): r = [] head = libvlc_audio_output_list_get(self) if head: i = head while i: i = i.contents d = [{: libvlc_audio_output_device_id (self, i.name, d), : libvlc...
Enumerate the defined audio output devices. @return: list of dicts {name:, description:, devices:}
1,040
def create_connection(self, *args, **kwargs): args = list(args) if len(args) == 0: kwargs[] = max(self._connect_timeout, kwargs.get(, self._connect_timeout*10)/10.0) elif len(args) == 1: args.append(self._connect_timeout) else: args[1] = ma...
This method is trying to establish connection with one of the zookeeper nodes. Somehow strategy "fail earlier and retry more often" works way better comparing to the original strategy "try to connect with specified timeout". Since we want to try connect to zookeeper more often (with the...
1,041
def _get_coordinator_for_group(self, consumer_group): if self.consumer_group_to_brokers.get(consumer_group) is None: yield self.load_consumer_metadata_for_group(consumer_group) returnValue(self.consumer_group_to_brokers.get(consumer_group))
Returns the coordinator (broker) for a consumer group Returns the broker for a given consumer group or Raises ConsumerCoordinatorNotAvailableError
1,042
def checksum(self): md5sum, md5sum64, = [], [] for line in self.SLACKBUILDS_TXT.splitlines(): if line.startswith(self.line_name): sbo_name = line[17:].strip() if line.startswith(self.line_md5_64): if sbo_name == self.name and line[26:].str...
Grab checksum string
1,043
def _all_same_area(self, dataset_ids): all_areas = [] for ds_id in dataset_ids: for scn in self.scenes: ds = scn.get(ds_id) if ds is None: continue all_areas.append(ds.attrs.get()) all_areas = [area for area...
Return True if all areas for the provided IDs are equal.
1,044
def open_file(self, path): if path: editor = self.tabWidget.open_document(path) editor.cursorPositionChanged.connect( self.on_cursor_pos_changed) self.recent_files_manager.open_file(path) self.menu_recents.update_actions()
Creates a new GenericCodeEdit, opens the requested file and adds it to the tab widget. :param path: Path of the file to open
1,045
def get_fragment(self, **kwargs): gen, namespaces, plan = self.get_fragment_generator(**kwargs) graph = ConjunctiveGraph() [graph.bind(prefix, u) for (prefix, u) in namespaces] [graph.add((s, p, o)) for (_, s, p, o) in gen] return graph
Return a complete fragment. :param gp: :return:
1,046
def sign_remote_certificate(argdic, **kwargs): *public_key/etc/pki/www.keysigning_policywwwwww1 if not in argdic: return if not isinstance(argdic, dict): argdic = ast.literal_eval(argdic) signing_policy = {} if in argdic: signing_policy = _get_signing_policy(argdic[]) ...
Request a certificate to be remotely signed according to a signing policy. argdic: A dict containing all the arguments to be passed into the create_certificate function. This will become kwargs when passed to create_certificate. kwargs: kwargs delivered from publish.publish ...
1,047
def global_request(self, kind, data=None, wait=True): if wait: self.completion_event = threading.Event() m = Message() m.add_byte(cMSG_GLOBAL_REQUEST) m.add_string(kind) m.add_boolean(wait) if data is not None: m.add(*data) self._l...
Make a global request to the remote host. These are normally extensions to the SSH2 protocol. :param str kind: name of the request. :param tuple data: an optional tuple containing additional data to attach to the request. :param bool wait: ``True`` i...
1,048
def readFromFile(self, filename): s = dict(np.load(filename)) try: self.coeffs = s[][()] except KeyError: self.coeffs = s try: self.opts = s[][()] except KeyError: pass return self.coeffs
read the distortion coeffs from file
1,049
def postalCodeLookup(self, countryCode, postalCode): params = {"country": countryCode, "postalcode": postalCode} d = self._call("postalCodeLookupJSON", params) d.addCallback(operator.itemgetter("postalcodes")) return d
Looks up locations for this country and postal code.
1,050
def is_connectable(host: str, port: Union[int, str]) -> bool: socket_ = None try: socket_ = socket.create_connection((host, port), 1) result = True except socket.timeout: result = False finally: if socket_: socket_.close() return result
Tries to connect to the device to see if it is connectable. Args: host: The host to connect. port: The port to connect. Returns: True or False.
1,051
def decrypt(ciphertext, secret, inital_vector, checksum=True, lazy=True): secret = _lazysecret(secret) if lazy else secret encobj = AES.new(secret, AES.MODE_CFB, inital_vector) try: padded = ciphertext + ( * (len(ciphertext) % 4)) decoded = base64.urlsafe_b64decode(str(padded)) ...
Decrypts ciphertext with secret ciphertext - encrypted content to decrypt secret - secret to decrypt ciphertext inital_vector - initial vector lazy - pad secret if less than legal blocksize (default: True) checksum - verify crc32 byte encoded checksum (default: True) ...
1,052
def clean_comment(self): comment = self.cleaned_data["text"] if settings.COMMENTS_ALLOW_PROFANITIES is False: bad_words = [w for w in settings.PROFANITIES_LIST if w in comment.lower()] if bad_words: raise forms.ValidationError(ungettext( ...
If COMMENTS_ALLOW_PROFANITIES is False, check that the comment doesn't contain anything in PROFANITIES_LIST.
1,053
def appendInputWithNSimilarValues(inputs, numNear = 10): numInputs = len(inputs) skipOne = False for i in xrange(numInputs): input = inputs[i] numChanged = 0 newInput = copy.deepcopy(input) for j in xrange(len(input)-1): if skipOne: skipOne = False continue if input[...
Creates a neighboring record for each record in the inputs and adds new records at the end of the inputs list
1,054
def new_action(project_id): project = get_data_or_404(, project_id) if project[] != get_current_user_id(): return jsonify(message=), 403 form = NewActionForm() if not form.validate_on_submit(): return jsonify(errors=form.errors), 400 data = form.data data[] = project_id ...
Add action.
1,055
def parse_args(self, command_selected, flags, _free_args): configs = self.function_name_to_configs[command_selected] suggested_configs = self.function_name_to_suggest_configs[command_selected] attribute_to_config = dict() for config in itertools.chain(config...
Parse the args and fill the global data Currently we disregard the free parameters :param command_selected: :param flags: :param _free_args: :return:
1,056
def retry_on_exception(num_retries, base_delay=0, exc_type=Exception): def _retry_on_exception_inner_1(f): def _retry_on_exception_inner_2(*args, **kwargs): retries = num_retries multiplier = 1 while True: try: return f(*args, **kw...
If the decorated function raises exception exc_type, allow num_retries retry attempts before raise the exception.
1,057
def load_emacs_open_in_editor_bindings(): registry = Registry() registry.add_binding(Keys.ControlX, Keys.ControlE, filter=EmacsMode() & ~HasSelection())( get_by_name()) return registry
Pressing C-X C-E will open the buffer in an external editor.
1,058
def installSite(self): for iface, priority in self.__getPowerupInterfaces__([]): self.store.powerUp(self, iface, priority)
Not using the dependency system for this class because it's only installed via the command line, and multiple instances can be installed.
1,059
def assemble_notification_request(method, params=tuple()): if not isinstance(method, (str, unicode)): raise TypeError() if not isinstance(params, (tuple, list)): raise TypeError("params must be a tuple/list.") return { "method": method, "...
serialize a JSON-RPC-Notification :Parameters: see dumps_request :Returns: | {"method": "...", "params": ..., "id": null} | "method", "params" and "id" are always in this order. :Raises: see dumps_request
1,060
def _drawContents(self, currentRti=None): table = self.table table.setUpdatesEnabled(False) try: table.clearContents() verticalHeader = table.verticalHeader() verticalHeader.setSectionResizeMode(QtWidgets.QHeaderView.Fixed) attri...
Draws the attributes of the currentRTI
1,061
def c_typedefs(self): defs = [] attrs = self.opts.attrs + if self.opts.attrs else for name, args in self.funcs: logging.debug(, name, args) defs.append( .format( args[0], attrs, self._c_type_name(name), ma...
Get the typedefs of the module.
1,062
def save_rst(self, file_name=, module_name=): if self.model is not None: with open(file_name, ) as fh: fh.write( % module_name) fh.write() fh.write() fh.write() model_str = pysb.export.export(self.model, ) ...
Save the assembled model as an RST file for literate modeling. Parameters ---------- file_name : Optional[str] The name of the file to save the RST in. Default: pysb_model.rst module_name : Optional[str] The name of the python function defining the mo...
1,063
def getTerms(self, term=None, getFingerprint=None, startIndex=0, maxResults=10): return self._terms.getTerm(self._retina, term, getFingerprint, startIndex, maxResults)
Get term objects Args: term, str: A term in the retina (optional) getFingerprint, bool: Configure if the fingerprint should be returned as part of the results (optional) startIndex, int: The start-index for pagination (optional) maxResults, int: Max results per pa...
1,064
def QA_indicator_BBI(DataFrame, N1=3, N2=6, N3=12, N4=24): C = DataFrame[] bbi = (MA(C, N1) + MA(C, N2) + MA(C, N3) + MA(C, N4)) / 4 DICT = {: bbi} return pd.DataFrame(DICT)
多空指标
1,065
def datetime( self, year, month, day, hour=0, minute=0, second=0, microsecond=0 ): if _HAS_FOLD: return self.convert( datetime(year, month, day, hour, minute, second, microsecond, fold=1) ) return self.convert( datetime(year, mo...
Return a normalized datetime for the current timezone.
1,066
def assert_valid_path(self, path): if not isinstance(path, str): raise NotFoundResourceException( "Resource passed to load() method must be a file path") if not os.path.isfile(path): raise NotFoundResourceException( .format(path))
Ensures that the path represents an existing file @type path: str @param path: path to check
1,067
def set_led(self, led_number, led_value): if 1 > led_number > 4: return write_led_value(hw_id=self.device_unique_name, led_name=.format(led_number), value=led_value)
Set front-panel controller LEDs. The DS3 controller has four, labelled, LEDs on the front panel that can be either on or off. :param led_number: Integer between 1 and 4 :param led_value: Value, set to 0 to turn the LED off, 1 to turn it on
1,068
def slice_image(image, axis=None, idx=None): if image.dimension < 3: raise ValueError() inpixeltype = image.pixeltype ndim = image.dimension if image.pixeltype != : image = image.clone() libfn = utils.get_lib_fn( % ndim) itkimage = libfn(image.pointer, axis, idx) retu...
Slice an image. Example ------- >>> import ants >>> mni = ants.image_read(ants.get_data('mni')) >>> mni2 = ants.slice_image(mni, axis=1, idx=100)
1,069
def _quantize_channelwise_linear(weight, nbits, axis=0): if len(weight.shape) == 1: weight = weight.reshape((1, weight.shape[0])) rank = len(weight.shape) if axis == 1: transposed_axis_order = (1,0) + tuple(range(2,rank)) weight = _np.transpose(weight, transposed_axis_order) ...
Linearly quantize weight blob. :param weight: numpy.array Weight to be quantized. :param nbits: int Number of bits per weight element :param axis: int Axis of the weight blob to compute channel-wise quantization, can be 0 or 1 Returns ------- quantized_weight: numpy.a...
1,070
def limit(self, n, skip=None): if self.query.limit is not None: raise MonSQLException() new_query_set = self.clone() new_query_set.query.limit = n new_query_set.query.skip = skip return new_query_set
Limit the result set. However when the query set already has limit field before, this would raise an exception :Parameters: - n : The maximum number of rows returned - skip: how many rows to skip :Return: a new QuerySet object so we can chain operations
1,071
def close_project(self): if self.current_active_project: self.switch_to_plugin() if self.main.editor is not None: self.set_project_filenames( self.main.editor.get_open_filenames()) path = self.current_active_project.root_pat...
Close current project and return to a window without an active project
1,072
def __make_thumbnail(self, width, height): (w, h) = self.size factor = max( (float(w) / width), (float(h) / height) ) w /= factor h /= factor return self.get_image((round(w), round(h)))
Create the page's thumbnail
1,073
def _get_sv_exclude_file(items): sv_bed = utils.get_in(items[0], ("genome_resources", "variation", "sv_repeat")) if sv_bed and os.path.exists(sv_bed): return sv_bed
Retrieve SV file of regions to exclude.
1,074
def _preprocess(project_dict): handlers = { (,): _list_if_none, (,): _list_if_none_or_string, (,): _list_if_none_or_string, } for k in (, ): handlers[(k,)] = _dict_if_none handlers[(k, )] = _dict_if_none handlers[(...
Pre-process certain special keys to convert them from None values into empty containers, and to turn strings into arrays of strings.
1,075
def build_options(payload, options, maxsize = 576, overload = OVERLOAD_FILE | OVERLOAD_SNAME, allowpartial = True): if maxsize < 576: maxsize = 576 max_options_size = maxsize - 240 options = [o for o in options if o.tag not in (OPTION_PAD, OPTION_END)] option_data = [(o.tag, o._to...
Split a list of options This is the reverse operation of `reassemble_options`, it splits `dhcp_option` into `dhcp_option_partial` if necessary, and set overload option if field overloading is used. :param options: a list of `dhcp_option` :param maxsize: Limit the maximum DHCP message ...
1,076
def run_cmd(cmd, return_output=False, ignore_status=False, log_output=True, **kwargs): logger.debug( % .join(cmd)) process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, **kwargs) output = process.communicate()[0] if...
run provided command on host system using the same user as you invoked this code, raises subprocess.CalledProcessError if it fails :param cmd: list of str :param return_output: bool, return output of the command :param ignore_status: bool, do not fail in case nonzero return code :param log_output: ...
1,077
def send_media_group(chat_id, media, reply_to_message_id=None, disable_notification=False, **kwargs): files = [] if len(media) < 2 or len(media) > 10: raise ValueError() for i, entry in media: if isinstance(entry.media, InputFile): ...
Use this method to send a group of photos or videos as an album. On success, an array of the sent Messages is returned. :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) :param media: A list of InputMedia objects to be sent, must include 2–...
1,078
def common_req(self, execute, send_body=True): "Common code for GET and POST requests" self._SERVER = {: self.client_address[0], : self.client_address[1]} self._to_log = True self._cmd = None self._payload ...
Common code for GET and POST requests
1,079
def derivative(self, x): return BroadcastOperator(*[op.derivative(x) for op in self.operators])
Derivative of the broadcast operator. Parameters ---------- x : `domain` element The point to take the derivative in Returns ------- adjoint : linear `BroadcastOperator` The derivative Examples -------- Example with an af...
1,080
def cancel_registration(self): iq = aioxmpp.IQ( to=self.client.local_jid.bare().replace(localpart=None), type_=aioxmpp.IQType.SET, payload=xso.Query() ) iq.payload.remove = True yield from self.client.send(iq)
Cancels the currents client's account with the server. Even if the cancelation is succesful, this method will raise an exception due to he account no longer exists for the server, so the client will fail. To continue with the execution, this method should be surrounded by a try/...
1,081
def masked_arith_op(x, y, op): xrav = x.ravel() assert isinstance(x, (np.ndarray, ABCSeries)), type(x) if isinstance(y, (np.ndarray, ABCSeries, ABCIndexClass)): dtype = find_common_type([x.dtype, y.dtype]) result = np.empty(x.size, dtype=dtype) yrav ...
If the given arithmetic operation fails, attempt it again on only the non-null elements of the input array(s). Parameters ---------- x : np.ndarray y : np.ndarray, Series, Index op : binary operator
1,082
def _get_columns(self, X, cols): if isinstance(X, DataSet): X = X[cols] return_vector = False if isinstance(cols, basestring): return_vector = True cols = [cols] if isinstance(X, list): X = [x[cols] for x in X] X = pd...
Get a subset of columns from the given table X. X a Pandas dataframe; the table to select columns from cols a string or list of strings representing the columns to select Returns a numpy array with the data from the selected columns
1,083
def valid_level(value): value = value.upper() if getattr(logging, value, None) is None: raise argparse.ArgumentTypeError("%s is not a valid level" % value) return value
Validation function for parser, logging level argument.
1,084
def get_filetypes(filelist, path=None, size=os.path.getsize): path = path or (lambda _: _) histo = defaultdict(int) for entry in filelist: ext = os.path.splitext(path(entry))[1].lstrip().lower() if ext and ext[0] == and ext[1:].isdigit(): ext = "rar" elif ext ...
Get a sorted list of file types and their weight in percent from an iterable of file names. @return: List of weighted file extensions (no '.'), sorted in descending order @rtype: list of (weight, filetype)
1,085
def to_frame(self, *args): if sys.version_info < (3, 6, 0): from collections import OrderedDict impls = OrderedDict() for name, obj in self.items(): impls[name] = obj._impl else: impls = get_impls(self) return _to_frame_i...
Convert the cells in the view into a DataFrame object. If ``args`` is not given, this method returns a DataFrame that has an Index or a MultiIndex depending of the number of cells parameters and columns each of which corresponds to each cells included in the view. ``args`` can ...
1,086
def _update_object_map(self, obj_map): creation_time = obj_map[] obj_map[] = dict() obj_map[][] = creation_time.year obj_map[][] = creation_time.month obj_map[][] = creation_time.day obj_map[][] = creation_time.hour obj_map[][] = creation_time.minute ...
stub
1,087
def invert(self): m = self.matrix d = m[0] * m[4] - m[1] * m[3] self.matrix = [ m[4] / d, -m[1] / d, 0, -m[3] / d, m[0] / d, 0, (m[3] * m[7] - m[4] * m[6]) / d, -(m[0] * m[7] - m[1] * m[6]) / d, 1 ]
Multiplying a matrix by its inverse produces the identity matrix.
1,088
def setHintColor(self, color): lineEdit = self.lineEdit() if isinstance(lineEdit, XLineEdit): lineEdit.setHintColor(color)
Sets the hint color for this combo box provided its line edit is an XLineEdit instance. :param color | <QColor>
1,089
def create_project_config_path( path, mode=0o777, parents=False, exist_ok=False ): project_path = Path(path).absolute().joinpath(RENKU_HOME) project_path.mkdir(mode=mode, parents=parents, exist_ok=exist_ok) return str(project_path)
Create new project configuration folder.
1,090
def _determine_supported_alleles(command, supported_allele_flag): try: supported_alleles_output = check_output([ command, supported_allele_flag ]) supported_alleles_str = supported_alleles_output.decode("ascii", "ignore") asse...
Try asking the commandline predictor (e.g. netMHCpan) which alleles it supports.
1,091
def write_document(self, gh_user, doc_id, file_content, branch, author, commit_msg=None): parent_sha = None fc = tempfile.NamedTemporaryFile() if is_str_type(file_content): fc.write(file_content) else: write_as_json(file_content, fc) fc.f...
Given a document id, temporary filename of content, branch and auth_info Deprecated but needed until we merge api local-dep to master...
1,092
def json_dumps(inbox): gc.disable() str_ = json.dumps(inbox[0]) gc.enable() return str_
Serializes the first element of the input using the JSON protocol as implemented by the ``json`` Python 2.6 library.
1,093
def _single_orbit_find_actions(orbit, N_max, toy_potential=None, force_harmonic_oscillator=False): if orbit.norbits > 1: raise ValueError("must be a single orbit") if toy_potential is None: toy_potential = fit_toy_potential( orbit, force_harmonic...
Find approximate actions and angles for samples of a phase-space orbit, `w`, at times `t`. Uses toy potentials with known, analytic action-angle transformations to approximate the true coordinates as a Fourier sum. This code is adapted from Jason Sanders' `genfunc <https://github.com/jlsanders/genfunc>...
1,094
def link(self, href, **kwargs): return link.Link(dict(href=href, **kwargs), self.base_uri)
Retuns a new link relative to this resource.
1,095
def __meta_metadata(self, field, key): mf = try: mf = str([f[key] for f in self.metadata if f[] == field][0]) except IndexError: print("%s not in metadata field:%s" % (key, field)) return mf else: return mf
Return the value for key for the field in the metadata
1,096
def copy(self): result = Scalar(self.size, self.deriv) result.v = self.v if self.deriv > 0: result.d[:] = self.d[:] if self.deriv > 1: result.dd[:] = self.dd[:] return result
Return a deep copy
1,097
def return_features_numpy_base(dbpath, set_object, points_amt, names): engine = create_engine( + dbpath) session_cl = sessionmaker(bind=engine) session = session_cl() tmp_object = session.query(set_object).get(1) if names == : columns_amt = 0 for feature in tmp_object.features:...
Generic function which returns a 2d numpy array of extracted features Parameters ---------- dbpath : string, path to SQLite database file set_object : object (either TestSet or TrainSet) which is stored in the database points_amt : int, number of data points in the database names : list of stri...
1,098
def running(concurrent=False): * ret = [] if concurrent: return ret active = __salt__[]() for data in active: err = ( ).format( data[], data[], salt.utils.jid.jid_to_time(data[]), data[], ) ...
Return a list of strings that contain state return data if a state function is already running. This function is used to prevent multiple state calls from being run at the same time. CLI Example: .. code-block:: bash salt '*' state.running
1,099
def tables_insert(self, table_name, schema=None, query=None, friendly_name=None, description=None): url = Api._ENDPOINT + \ (Api._TABLES_PATH % (table_name.project_id, table_name.dataset_id, , )) data = { : , : { : table_name.project_id, ...
Issues a request to create a table or view in the specified dataset with the specified id. A schema must be provided to create a Table, or a query must be provided to create a View. Args: table_name: the name of the table as a tuple of components. schema: the schema, if this is a Table creation....