Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
9,500
def partition(list_, columns=2): iter_ = iter(list_) columns = int(columns) rows = [] while True: row = [] for column_number in range(1, columns + 1): try: value = six.next(iter_) except StopIteration: pass else: ...
Break a list into ``columns`` number of columns.
9,501
def stream(self, area_code=values.unset, contains=values.unset, sms_enabled=values.unset, mms_enabled=values.unset, voice_enabled=values.unset, exclude_all_address_required=values.unset, exclude_local_address_required=values.unset, exclude_forei...
Streams VoipInstance records from the API as a generator stream. This operation lazily loads records as efficiently as possible until the limit is reached. The results are returned as a generator, so this operation is memory efficient. :param unicode area_code: The area code of the phon...
9,502
def _fmt_float(cls, x, **kw): n = kw.get() return % (n, cls._to_float(x))
Float formatting class-method. - x parameter is ignored. Instead kw-argument f being x float-converted will be used. - precision will be taken from `n` kw-argument.
9,503
def _api_get(self, url, **kwargs): kwargs[] = self.url + url kwargs[] = self.auth headers = deepcopy(self.headers) headers.update(kwargs.get(, {})) kwargs[] = headers return self._get(**kwargs)
A convenience wrapper for _get. Adds headers, auth and base url by default
9,504
def remove_aspera_coordinator(self, transfer_coordinator): if self._in_waiting_queue(transfer_coordinator): logger.info("Remove from waiting queue count=%d" % self.waiting_coordinator_count()) with self._lockw: self._waiting_transfer_coordinators.remove(...
remove entry from the waiting waiting or remove item from processig queue and add to processed quque notify background thread as it may be able to process watiign requests
9,505
def train_associations_SingleSNP(X, Y, U, S, C, numintervals, ldeltamin, ldeltamax): return _core.train_associations_SingleSNP(X, Y, U, S, C, numintervals, ldeltamin, ldeltamax)
train_associations_SingleSNP(MatrixXd const & X, MatrixXd const & Y, MatrixXd const & U, MatrixXd const & S, MatrixXd const & C, int numintervals, double ldeltamin, double ldeltamax) Parameters ---------- X: MatrixXd const & Y: MatrixXd const & U: MatrixXd const & S: MatrixXd const & C: Mat...
9,506
def add_layer_timing_signal_sinusoid_1d(x, layer, num_layers): channels = common_layers.shape_list(x)[-1] signal = get_layer_timing_signal_sinusoid_1d(channels, layer, num_layers) return x + signal
Add sinusoids of different frequencies as layer (vertical) timing signal. Args: x: a Tensor with shape [batch, length, channels] layer: layer num num_layers: total number of layers Returns: a Tensor the same shape as x.
9,507
def ws010c(self, value=None): if value is not None: try: value = float(value) except ValueError: raise ValueError( .format(value)) self._ws010c = value
Corresponds to IDD Field `ws010c` Wind speed corresponding to 1.0% cumulative frequency of occurrence for coldest month; Args: value (float): value for IDD Field `ws010c` Unit: m/s if `value` is None it will not be checked against the ...
9,508
def is_valid_int_param(param): if param is None: return False try: param = int(param) if param < 0: return False except (TypeError, ValueError): return False return True
Verifica se o parâmetro é um valor inteiro válido. :param param: Valor para ser validado. :return: True se o parâmetro tem um valor inteiro válido, ou False, caso contrário.
9,509
def _init_bins(self, binset): if binset is None: if self.bandpass.waveset is not None: self._binset = self.bandpass.waveset elif self.spectrum.waveset is not None: self._binset = self.spectrum.waveset log.info( ...
Calculated binned wavelength centers, edges, and flux. By contrast, the native waveset and flux should be considered samples of a continuous function. Thus, it makes sense to interpolate ``self.waveset`` and ``self(self.waveset)``, but not `binset` and `binflux`.
9,510
def p_ComplianceModules(self, p): n = len(p) if n == 3: p[0] = (, p[1][1] + [p[2]]) elif n == 2: p[0] = (, [p[1]])
ComplianceModules : ComplianceModules ComplianceModule | ComplianceModule
9,511
def peek(self, n): return int.from_bytes( self.data[self.pos>>3:self.pos+n+7>>3], )>>(self.pos&7) & (1<<n)-1
Peek an n bit integer from the stream without updating the pointer. It is not an error to read beyond the end of the stream. >>> olleke.data[:2]==b'\x1b\x2e' and 0x2e1b==11803 True >>> olleke.peek(15) 11803 >>> hex(olleke.peek(32)) '0x2e1b'
9,512
def websocket_url_for_server_url(url): if url.startswith("http:"): reprotocoled = "ws" + url[4:] elif url.startswith("https:"): reprotocoled = "wss" + url[5:] else: raise ValueError("URL has unknown protocol " + url) if reprotocoled.endswith("/"): return reprotocoled...
Convert an ``http(s)`` URL for a Bokeh server websocket endpoint into the appropriate ``ws(s)`` URL Args: url (str): An ``http(s)`` URL Returns: str: The corresponding ``ws(s)`` URL ending in ``/ws`` Raises: ValueError: If the input URL is n...
9,513
def create_pool(self, name, raid_groups, description=None, **kwargs): return UnityPool.create(self._cli, name=name, description=description, raid_groups=raid_groups, **kwargs)
Create pool based on RaidGroupParameter. :param name: pool name :param raid_groups: a list of *RaidGroupParameter* :param description: pool description :param alert_threshold: Threshold at which the system will generate alerts about the free space in the pool, specified a...
9,514
def get_foreign_keys_in_altered_table(self, diff): foreign_keys = diff.from_table.get_foreign_keys() column_names = self.get_column_names_in_altered_table(diff) for key, constraint in foreign_keys.items(): changed = False local_columns = [] for colum...
:param diff: The table diff :type diff: eloquent.dbal.table_diff.TableDiff :rtype: list
9,515
def startproject(project_name): dst_path = os.path.join(os.getcwd(), project_name) start_init_info(dst_path) _mkdir_p(dst_path) os.chdir(dst_path) init_code(, _manage_admin_code) init_code(, _requirement_admin_code) init_code(, _config_sql_code) app_path ...
build a full status project
9,516
def res_obs_v_sim(pst,logger=None, filename=None, **kwargs): if logger is None: logger=Logger(,echo=False) logger.log("plot res_obs_v_sim") if "ensemble" in kwargs: try: res=pst_utils.res_from_en(pst,kwargs[]) except: logger.statement("res_1to1: could n...
timeseries plot helper...in progress
9,517
def display_for_value(value, request=None): from is_core.utils.compatibility import admin_display_for_value if request and isinstance(value, Model): return render_model_object_with_link(request, value) else: return ( (value and ugettext() or ugettext()) if isinstance(value,...
Converts humanized value examples: boolean True/Talse ==> Yes/No objects ==> object display name with link if current user has permissions to see the object datetime ==> in localized format
9,518
def min_value(self): if self._is_completely_masked: return np.nan * self._data_unit else: return np.min(self.values)
The minimum pixel value of the ``data`` within the source segment.
9,519
def dshield_ip_check(ip): if not is_IPv4Address(ip): return None headers = {: useragent} url = response = requests.get(.format(url, ip), headers=headers) return response.json()
Checks dshield for info on an IP address
9,520
def remove_binding(site, hostheader=, ipaddress=, port=80): *site0example.com*80 name = _get_binding_info(hostheader, ipaddress, port) current_bindings = list_bindings(site) if name not in current_bindings: log.debug(, name) return True ps_cmd = [, , "".format(hosthead...
Remove an IIS binding. Args: site (str): The IIS site name. hostheader (str): The host header of the binding. ipaddress (str): The IP address of the binding. port (int): The TCP port of the binding. Returns: bool: True if successful, otherwise False CLI Example: ...
9,521
def leaveEvent( self, event ): item = self.trackerItem() if ( item ): item.setVisible(False)
Toggles the display for the tracker item.
9,522
def _authenticate_cram_md5(credentials, sock_info): source = credentials.source username = credentials.username password = credentials.password passwd = _password_digest(username, password) cmd = SON([(, 1), (, ), (, Binary(b)), (, 1)]) ...
Authenticate using CRAM-MD5 (RFC 2195)
9,523
def _grouper(iterable, n_args, fillvalue=None): args = [iter(iterable)] * n_args return zip_longest(*args, fillvalue=fillvalue)
Banana banana
9,524
def get(self, query, sort, page, size): urlkwargs = { : query, : sort, : size, } communities = Community.filter_communities(query, sort) page = communities.paginate(page, size) links = default_links_pagination_factory(page, urlkwargs...
Get a list of all the communities. .. http:get:: /communities/(string:id) Returns a JSON list with all the communities. **Request**: .. sourcecode:: http GET /communities HTTP/1.1 Accept: application/json Content-Type: applicat...
9,525
async def async_enqueue_sync(self, func, *func_args): worker = self.pick_sticky(0) args = (func,) + func_args await worker.enqueue(enums.Task.FUNC, args)
Enqueue an arbitrary synchronous function.
9,526
def _list_templates(settings): for idx, option in enumerate(settings.config.get("project_templates"), start=1): puts(" {0!s:5} {1!s:36}".format( colored.yellow("[{0}]".format(idx)), colored.cyan(option.get("name")) )) if option.get("url"): puts(" ...
List templates from settings.
9,527
def output_selector_schema(config_cls): config_type = resolve_config_cls_arg(config_cls) check.param_invariant(config_type.is_selector, ) def _wrap(func): def _selector(context, config_value, runtime_value): selector_key, selector_value = single_item(config_value) retur...
A decorator for a annotating a function that can take the selected properties of a ``config_value`` and an instance of a custom type and materialize it. Args: config_cls (Selector):
9,528
def _join_all_filenames_and_text( self): self.log.info() contentString = u"" for i in self.directoryContents: contentString += u"%(i)s\n" % locals() if os.path.isfile(os.path.join(i)): if i[-4:] in [".png", ".jpg", ".gif"]: ...
*join all file names, driectory names and text content together*
9,529
def predict_encoding(file_path, n_lines=20): import chardet with open(file_path, ) as f: rawdata = b.join([f.readline() for _ in range(n_lines)]) return chardet.detect(rawdata)[]
Get file encoding of a text file
9,530
def pdf_rotate( input: str, counter_clockwise: bool = False, pages: [str] = None, output: str = None, ): infile = open(input, "rb") reader = PdfFileReader(infile) writer = PdfFileWriter() if pages is None: source_pages = reader.pages else: pages = parse_ran...
Rotate the given Pdf files clockwise or counter clockwise. :param inputs: pdf files :param counter_clockwise: rotate counter clockwise if true else clockwise :param pages: list of page numbers to rotate, if None all pages will be rotated
9,531
def _fmt_auto(cls, x, **kw): f = cls._to_float(x) if abs(f) > 1e8: fn = cls._fmt_exp else: if f - round(f) == 0: fn = cls._fmt_int else: fn = cls._fmt_float return fn(x, **kw)
auto formatting class-method.
9,532
def run_pipelines(pipeline_id_pattern, root_dir, use_cache=True, dirty=False, force=False, concurrency=1, verbose_logs=True, progress_cb=None, slave=False): with concu...
Run a pipeline by pipeline-id. pipeline-id supports the '%' wildcard for any-suffix matching. Use 'all' or '%' for running all pipelines
9,533
def from_url(cls, db_url=ALL_SETS_ZIP_URL): r = requests.get(db_url) r.raise_for_status() if r.headers[] == : return cls(json.loads(r.text)) if r.headers[] == : with zipfile.ZipFile(six.BytesIO(r.content), ) as zf: names = zf.namelist() ...
Load card data from a URL. Uses :func:`requests.get` to fetch card data. Also handles zipfiles. :param db_url: URL to fetch. :return: A new :class:`~mtgjson.CardDb` instance.
9,534
def detach_framebuffer(self, screen_id, id_p): if not isinstance(screen_id, baseinteger): raise TypeError("screen_id can only be an instance of type baseinteger") if not isinstance(id_p, basestring): raise TypeError("id_p can only be an instance of type basestring") ...
Removes the graphics updates target for a screen. in screen_id of type int in id_p of type str
9,535
def compute_evolution_by_frequency( df, id_cols: List[str], date_col: Union[str, Dict[str, str]], value_col: str, freq=1, method: str = , format: str = , offseted_suffix: str = , evolution_col_name: str = , missing_date_as_zero: bool = False, raise_duplicate_error: bool = Tru...
This function answers the question: how has a value changed on a weekly, monthly, yearly basis ? --- ### Parameters *mandatory :* - `id_cols` (*list*): name of the columns used to create each group. - `date_col` (*str or dict*): either directly the name of the column containing the date or a dict...
9,536
def controller(self, *paths, **query_kwargs): kwargs = self._normalize_params(*paths, **query_kwargs) if self.controller_path: if "path" in kwargs: paths = self.normalize_paths(self.controller_path, kwargs["path"]) kwargs["path"] = "/".join(paths) ...
create a new url object using the controller path as a base if you have a controller `foo.BarController` then this would create a new Url instance with `host/foo/bar` as the base path, so any *paths will be appended to `/foo/bar` :example: # controller foo.BarController ...
9,537
def table(self, name=DEFAULT_TABLE, **options): if name in self._table_cache: return self._table_cache[name] table_class = options.pop(, self._cls_table) table = table_class(self._cls_storage_proxy(self._storage, name), name, **options) self._table_cache[name] = t...
Get access to a specific table. Creates a new table, if it hasn't been created before, otherwise it returns the cached :class:`~tinydb.Table` object. :param name: The name of the table. :type name: str :param cache_size: How many query results to cache. :param table_cla...
9,538
def tileAddress(self, zoom, point): "Returns a tile address based on a zoom level and \ a point in the tile" [x, y] = point assert x <= self.MAXX and x >= self.MINX assert y <= self.MAXY and y >= self.MINY assert zoom in range(0, len(self.RESOLUTIONS)) tileS = se...
Returns a tile address based on a zoom level and \ a point in the tile
9,539
def return_hdr(self): self.fdtfile = None try: self.EEG = loadmat(str(self.filename), struct_as_record=False, squeeze_me=True)[] self.hdf5 = False except NotImplementedError: self.hdf5 = True if not self.hdf5:...
subj_id : str subject identification code start_time : datetime start time of the dataset s_freq : float sampling frequency chan_name : list of str list of all the channels n_samples : int number of samples in the dataset ...
9,540
def accel_zoom_in(self, *args): for term in self.get_notebook().iter_terminals(): term.increase_font_size() return True
Callback to zoom in.
9,541
def _se_all(self): err = np.expand_dims(self._ms_err, axis=1) t1 = np.diagonal( np.linalg.inv(np.matmul(self.xwins.swapaxes(1, 2), self.xwins)), axis1=1, axis2=2, ) return np.squeeze(np.sqrt(t1 * err))
Standard errors (SE) for all parameters, including the intercept.
9,542
def _post_run_hook(self, runtime): outputs = self.aggregate_outputs(runtime=runtime) self._anat_file = os.path.join(outputs.subjects_dir, outputs.subject_id, , ) self._contour = os.path.join(outputs.subjects_d...
generates a report showing nine slices, three per axis, of an arbitrary volume of `in_files`, with the resulting segmentation overlaid
9,543
def _get_stddevs(self, C, stddev_types, num_sites): sigma_inter = C[] + np.zeros(num_sites) sigma_intra = C[] + np.zeros(num_sites) std = [] for stddev_type in stddev_types: if stddev_type == const.StdDev.TOTAL: s...
Return total standard deviation as described in paragraph 5.2 pag 200.
9,544
def docs(ctx, clean=False, browse=False, watch=False): if clean: clean_docs(ctx) if watch: watch_docs(ctx, browse=browse) else: build_docs(ctx, browse=browse)
Build the docs.
9,545
def elastic_install(self): with cd(): if not exists(): sudo(.format( bigdata_conf.elastic_download_url )) sudo() sudo()
elasticsearch install :return:
9,546
def match(self, metadata, user = None): assert isinstance(metadata, self.formatclass) return self.generate(metadata,user)
Does the specified metadata match this template? returns (success,metadata,parameters)
9,547
def configure_cache(app): log = logging.getLogger() log.debug() if not getattr(app, , None): app._cache = {}
Sets up an attribute to cache data in the app context
9,548
def alias_action(self, *args, **kwargs): to = kwargs.pop(, None) if not to: return error_message = ("You can't specify target ({}) as alias " "because it is real action name".format(to) ) if to in list(itertools.chain...
Alias one or more actions into another one. self.alias_action('create', 'read', 'update', 'delete', to='crud')
9,549
def set_memory_params(self, ksm_interval=None, no_swap=None): self._set(, ksm_interval) self._set(, no_swap, cast=bool) return self._section
Set memory related parameters. :param int ksm_interval: Kernel Samepage Merging frequency option, that can reduce memory usage. Accepts a number of requests (or master process cycles) to run page scanner after. .. note:: Linux only. * http://uwsgi.readthedocs.io/en/latest/...
9,550
def create_folder(name, location=): r\\minion-id if name in list_folders(location): return .format(name) with salt.utils.winapi.Com(): task_service = win32com.client.Dispatch("Schedule.Service") task_service.Connect() task_folder = task_service.GetFolder(loc...
r''' Create a folder in which to create tasks. :param str name: The name of the folder. This will be displayed in the task scheduler. :param str location: A string value representing the location in which to create the folder. Default is '\\' which is the root for the task schedule...
9,551
def locate_ranges(self, starts, stops, strict=True): loc, found = self.locate_intersection_ranges(starts, stops) if strict and np.any(~found): raise KeyError(starts[~found], stops[~found]) return loc
Locate items within the given ranges. Parameters ---------- starts : array_like, int Range start values. stops : array_like, int Range stop values. strict : bool, optional If True, raise KeyError if any ranges contain no entries. Retu...
9,552
def forwards(apps, schema_editor): Work = apps.get_model(, ) for work in Work.objects.all(): if not work.slug: work.slug = generate_slug(work.pk) work.save()
Re-save all the Works because something earlier didn't create their slugs.
9,553
def _GetTable(self): result = [] lstr = str for row in self._table: result.append( % self.separator.join(lstr(v) for v in row)) return .join(result)
Returns table, with column headers and separators. Returns: The whole table including headers as a string. Each row is joined by a newline and each entry by self.separator.
9,554
def connection_made(self, transport): self.transport = transport self.remote_ip, self.port = transport.get_extra_info()[:2] logging.debug( .format(self.remote_ip, self.port)) self.future = self.send_package( protomap.CPROTO_REQ_INFO, ...
override _SiriDBProtocol
9,555
def compound_powerspec(data, tbin, Df=None, pointProcess=False): return powerspec([np.sum(data, axis=0)], tbin, Df=Df, units=True, pointProcess=pointProcess)
Calculate the power spectrum of the compound/sum signal. data is first summed across units, then the power spectrum is calculated. If pointProcess=True, power spectra are normalized by the length T of the time series. Parameters ---------- data : numpy.ndarray, 1st axis unit, 2nd...
9,556
def l2traceroute_result_output_l2_hop_results_l2_hop_ingress_interface_name(self, **kwargs): config = ET.Element("config") l2traceroute_result = ET.Element("l2traceroute_result") config = l2traceroute_result output = ET.SubElement(l2traceroute_result, "output") l2_hop_re...
Auto Generated Code
9,557
async def writelines(self, lines, eof = False, buffering = True): for l in lines: await self.write(l, False, buffering) if eof: await self.write(b, eof, buffering)
Write lines to current output stream
9,558
def __collapseLineOrCol(self, line, d): if (d == Board.LEFT or d == Board.UP): inc = 1 rg = xrange(0, self.__size-1, inc) else: inc = -1 rg = xrange(self.__size-1, 0, inc) pts = 0 for i in rg: if line[i] == 0: ...
Merge tiles in a line or column according to a direction and return a tuple with the new line and the score for the move on this line
9,559
def render_in_page(request, template): from leonardo.module.web.models import Page page = request.leonardo_page if hasattr( request, ) else Page.objects.filter(parent=None).first() if page: try: slug = request.path_info.split("/")[-2:-1][0] except KeyError: ...
return rendered template in standalone mode or ``False``
9,560
def _get_rules_from_aws(self): list_of_rules = list() if self.profile: boto3.setup_default_session(profile_name=self.profile) if self.region: ec2 = boto3.client(, region_name=self.region) else: ec2 = boto3.client() security_groups =...
Load the EC2 security rules off AWS into a list of dict. Returns: list
9,561
def force_constants(self, force_constants): if type(force_constants) is np.ndarray: fc_shape = force_constants.shape if fc_shape[0] != fc_shape[1]: if self._primitive.get_number_of_atoms() != fc_shape[0]: msg = ("Force constants shape disagre...
Set force constants Parameters ---------- force_constants : array_like Force constants matrix. If this is given in own condiguous ndarray with order='C' and dtype='double', internal copy of data is avoided. Therefore some computational resources are saved. ...
9,562
def scan(host, port=80, url=None, https=False, timeout=1, max_size=65535): starts = OrderedDict() ends = OrderedDict() port = int(port) result = dict( host=host, port=port, state=, durations=OrderedDict() ) if url: timeout = 1 result[] = None starts[] = starts[]...
Scan a network port Parameters ---------- host : str Host or ip address to scan port : int, optional Port to scan, default=80 url : str, optional URL to perform get request to on the host and port specified https : bool, optional Perform ssl connection on the ...
9,563
def disableGroup(self): radioButtonListInGroup = PygWidgetsRadioButton.__PygWidgets__Radio__Buttons__Groups__Dicts__[self.group] for radioButton in radioButtonListInGroup: radioButton.disable()
Disables all radio buttons in the group
9,564
def reqHeadTimeStamp( self, contract: Contract, whatToShow: str, useRTH: bool, formatDate: int = 1) -> datetime.datetime: return self._run( self.reqHeadTimeStampAsync( contract, whatToShow, useRTH, formatDate))
Get the datetime of earliest available historical data for the contract. Args: contract: Contract of interest. useRTH: If True then only show data from within Regular Trading Hours, if False then show all data. formatDate: If set to 2 then the result ...
9,565
def dump_np_vars(self, store_format=, delimiter=): ret = False if self.system.files.no_output is True: logger.debug() return True if self.write_lst() and self.write_np_dat(store_format=store_format, delimiter=delimiter): ret = True return ...
Dump the TDS simulation data to files by calling subroutines `write_lst` and `write_np_dat`. Parameters ----------- store_format : str dump format in `('csv', 'txt', 'hdf5')` delimiter : str delimiter for the `csv` and `txt` format Returns ...
9,566
def _concat_translations(translations: List[Translation], stop_ids: Set[int], length_penalty: LengthPenalty, brevity_penalty: Optional[BrevityPenalty] = None) -> Translation: target_ids = [] attention_matrices = [] beam_his...
Combines translations through concatenation. :param translations: A list of translations (sequence starting with BOS symbol, attention_matrix), score and length. :param stop_ids: The EOS symbols. :param length_penalty: Instance of the LengthPenalty class initialized with alpha and beta. :param brevity_...
9,567
def load_map(path, value): tmplstr = textwrap.dedent(.format(path=path, value=value)) return salt.template.compile_template_str( tmplstr, salt.loader.render(__opts__, __salt__), __opts__[], __opts__[], __opts__[])
Loads the map at the specified path, and returns the specified value from that map. CLI Example: .. code-block:: bash # Assuming the map is loaded in your formula SLS as follows: # # {% from "myformula/map.jinja" import myformula with context %} # # the following s...
9,568
def adaptive_model_average(X, penalization, method): n_trials = 100 print("Adaptive ModelAverage with:") print(" estimator: QuicGraphicalLasso (default)") print(" n_trials: {}".format(n_trials)) print(" penalization: {}".format(penalization)) print(" adaptive-method: {}".format(meth...
Run ModelAverage in default mode (QuicGraphicalLassoCV) to obtain proportion matrix. NOTE: Only method = 'binary' really makes sense in this case.
9,569
def plot_calibrated_diode(dio_cross,chan_per_coarse=8,feedtype=,**kwargs): obs = Waterfall(dio_cross,max_load=150) freqs = obs.populate_freqs() tsamp = obs.header[] data = obs.data obs = None I,Q,U,V = get_stokes(data,feedtype) data = None psis = phase_offsets(I,Q,U,V,tsa...
Plots the corrected noise diode spectrum for a given noise diode measurement after application of the inverse Mueller matrix for the electronics chain.
9,570
def _grab_raw_image(self): m = self.ale.getScreenRGB() return m.reshape((self.height, self.width, 3))
:returns: the current 3-channel image
9,571
def start(self, blocking=True): self.setup_zmq() if blocking: self.serve() else: eventlet.spawn(self.serve) eventlet.sleep(0)
Start the producer. This will eventually fire the ``server_start`` and ``running`` events in sequence, which signify that the incoming TCP request socket is running and the workers have been forked, respectively. If ``blocking`` is False, control .
9,572
def is_module_function(obj, prop): python_version = sys.version_info[0] if python_version == 3: unicode = str if prop and (isinstance(prop, str) or isinstance(prop, unicode)): if prop in dir(obj): if ( isinstance(getattr(obj, prop), FunctionType) ...
Checking and setting type to MODULE_FUNCTION Args: obj: ModuleType prop: FunctionType Return: Boolean Raise: prop_type_error: When the type of prop is not valid prop_in_obj_error: When prop is not in the obj(module/class) prop_is_func_error: When prop is not a...
9,573
def getargspec(func): if inspect.ismethod(func): func = func.__func__ parts = 0, () if type(func) is partial: keywords = func.keywords if keywords is None: keywords = {} parts = len(func.args), keywords.keys() func = func.func if not inspec...
Used because getargspec for python 2.7 does not accept functools.partial which is the type for pytest fixtures. getargspec excerpted from: sphinx.util.inspect ~~~~~~~~~~~~~~~~~~~ Helpers for inspecting Python modules. :copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS. :licens...
9,574
def from_events(self, instance, ev_args, ctx): def make_from_args(ev_args, parent): el = etree.SubElement(parent, tag_to_str((ev_args[0], ev_args[1]))) for key, value in ev_args[2].items(): el.set(tag_to_str(k...
Collect the events and convert them to a single XML subtree, which then gets appended to the list at `instance`. `ev_args` must be the arguments of the ``"start"`` event of the new child. This method is suspendable.
9,575
def as_python(self, infile, include_original_shex: bool=False): self._context.resolve_circular_references() body = for k in self._context.ordered_elements(): v = self._context.grammarelts[k] if isinstance(v, (JSGLexerRuleBlock, JSGObjectExpr)): ...
Return the python representation of the document
9,576
def return_xyz(self, labels=None): all_labels = self.return_label() if labels is None: labels = all_labels xyz = [] for one_label in labels: idx = all_labels.index(one_label) xyz.append(self.chan[idx].xyz) return asarray(xyz)
Returns the location in xy for some channels. Parameters ---------- labels : list of str, optional the names of the channels. Returns ------- numpy.ndarray a 3xn vector with the position of a channel.
9,577
def poa_horizontal_ratio(surface_tilt, surface_azimuth, solar_zenith, solar_azimuth): cos_poa_zen = aoi_projection(surface_tilt, surface_azimuth, solar_zenith, solar_azimuth) cos_solar_zenith = tools.cosd(solar_zenith) ratio = cos_poa_ze...
Calculates the ratio of the beam components of the plane of array irradiance and the horizontal irradiance. Input all angles in degrees. Parameters ---------- surface_tilt : numeric Panel tilt from horizontal. surface_azimuth : numeric Panel azimuth from north. solar_zenith...
9,578
def mark(self, partition, offset): max_offset = max(offset + 1, self.high_water_mark.get(partition, 0)) self.logger.debug("Setting high-water mark to: %s", {partition: max_offset}) self.high_water_mark[partition] = max_offset
Set the high-water mark in the current context. In order to know the current partition, it is helpful to initialize the consumer to provide partition info via: .. code:: python consumer.provide_partition_info()
9,579
def char_sets(): if not hasattr(char_sets, ): clist = [] try: data = requests.get( ) except requests.exceptions.RequestException: return [] for line in data.iter_lines(): if line: line = line.de...
Return a list of the IANA Character Sets, or an empty list if the IANA website is unreachable. Store it as a function attribute so that we only build the list once.
9,580
def parse_translation(f, lineno): line = f.readline() def get_line(f, line, need_keys, lineno, default=): line = line.rstrip() if not line: return lineno, need_keys[0], default, line key, value = line.split(, 1) if key not in need_keys: ...
Read a single translation entry from the file F and return a tuple with the comments, msgid and msgstr. The comments is returned as a list of lines which do not end in new-lines. The msgid and msgstr are strings, possibly with embedded newlines
9,581
def _render_reward(self, r: np.float32) -> None: print("reward = {:.4f}".format(float(r))) print()
Prints reward `r`.
9,582
def get_flexports_output_flexport_list_port_id(self, **kwargs): config = ET.Element("config") get_flexports = ET.Element("get_flexports") config = get_flexports output = ET.SubElement(get_flexports, "output") flexport_list = ET.SubElement(output, "flexport-list") ...
Auto Generated Code
9,583
def associate_keys(user_dict, client): added_keys = user_dict[] print ">>>Updating Keys-Machines association" for key in added_keys: machines = added_keys[key][] if machines: try: for machine in machines: cloud_id = machine[0] ...
This whole function is black magic, had to however cause of the way we keep key-machine association
9,584
def gc(cn, ns=None, lo=None, iq=None, ico=None, pl=None): return CONN.GetClass(cn, ns, LocalOnly=lo, IncludeQualifiers=iq, IncludeClassOrigin=ico, PropertyList=pl)
This function is a wrapper for :meth:`~pywbem.WBEMConnection.GetClass`. Retrieve a class. Parameters: cn (:term:`string` or :class:`~pywbem.CIMClassName`): Name of the class to be retrieved (case independent). If specified as a `CIMClassName` object, its `host` attribute will b...
9,585
def get_res(ds, t_srs=None, square=False): gt = ds.GetGeoTransform() ds_srs = get_ds_srs(ds) res = [gt[1], np.abs(gt[5])] if square: res = [np.mean(res), np.mean(res)] if t_srs is not None and not ds_srs.IsSame(t_srs): if True: ...
Get GDAL Dataset raster resolution
9,586
def fit(self, X, y): self._word_vocab.add_documents(X) self._label_vocab.add_documents(y) if self._use_char: for doc in X: self._char_vocab.add_documents(doc) self._word_vocab.build() self._char_vocab.build() self._label_vocab.build()...
Learn vocabulary from training set. Args: X : iterable. An iterable which yields either str, unicode or file objects. Returns: self : IndexTransformer.
9,587
def commit_sell(self, account_id, sell_id, **params): response = self._post( , , account_id, , sell_id, , data=params) return self._make_api_object(response, Sell)
https://developers.coinbase.com/api/v2#commit-a-sell
9,588
def to_dict(self): out = {} for key in self.__dict__.keys(): if key not in [, , , ]: out[key] = self.__dict__[key] return out
Return the node as a dictionary. Returns ------- dict: All the attributes of this node as a dictionary (minus the left and right).
9,589
def copy_directory(src, dest, force=False): if os.path.exists(dest) and force is True: shutil.rmtree(dest) try: shutil.copytree(src, dest) except OSError as e: sys.exit(1)
Copy an entire directory recursively
9,590
def info(self, msg, indent=0, **kwargs): return self.logger.info(self._indent(msg, indent), **kwargs)
invoke ``self.info.debug``
9,591
def _collapse_outgroup(tree, taxdicts): outg = taxdicts[0]["p4"] if not all([i["p4"] == outg for i in taxdicts]): raise Exception("no good") tre = ete.Tree(tree.write(format=1)) alltax = [i for i in tre.get_leaf_names() if i not in outg] alltax += [outg[0]] tre.prune(...
collapse outgroup in ete Tree for easier viewing
9,592
def request_fetch(self, user, repo, request, pull=False, force=False): raise NotImplementedError
Fetches given request as a branch, and switch if pull is true :param repo: name of the repository to create Meant to be implemented by subclasses
9,593
def enable_llama_ha(self, new_llama_host_id, zk_service_name=None, new_llama_role_name=None): args = dict( newLlamaHostId = new_llama_host_id, zkServiceName = zk_service_name, newLlamaRoleName = new_llama_role_name ) return self._cmd(, data=args, api_version=8)
Enable high availability for an Impala Llama ApplicationMaster. This command only applies to CDH 5.1+ Impala services. @param new_llama_host_id: id of the host where the second Llama role will be added. @param zk_service_name: Name of the ZooKeeper service to use for ...
9,594
def start(vm_name, call=None): start on the instance. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt-cloud -a start myinstance actionThe start action must be called with -a or --action.cloud.fire_eventeventstart instancesalt/cloud/{0}/startingnamesock_dirtransportcloud...
Call GCE 'start on the instance. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt-cloud -a start myinstance
9,595
def get_command_arg_list(self, command_name: str, to_parse: Union[Statement, str], preserve_quotes: bool) -> Tuple[Statement, List[str]]: if not isinstance(to_parse, Statement): to_parse = self.parse(command_name + + to_parse, expand=False) if...
Called by the argument_list and argparse wrappers to retrieve just the arguments being passed to their do_* methods as a list. :param command_name: name of the command being run :param to_parse: what is being passed to the do_* method. It can be one of two types: 1. An ...
9,596
def _HasId(self, schedule, entity_id): try: self._GetById(schedule, entity_id) has = True except KeyError: has = False return has
Check if the schedule has an entity with the given id. Args: schedule: The transitfeed.Schedule instance to look in. entity_id: The id of the entity. Returns: True if the schedule has an entity with the id or False if not.
9,597
def find_segment(self, ea): for seg in self.seglist: if seg.startea <= ea < seg.endea: return seg
do a linear search for the given address in the segment list
9,598
def edit_by_id( self, id_equip_acesso, id_tipo_acesso, fqdn, user, password, enable_pass): if not is_valid_int_param(id_tipo_acesso): raise InvalidParameterError( u) equipamento_ace...
Edit access type, fqdn, user, password and enable_pass of the relationship of equipment and access type. :param id_tipo_acesso: Access type identifier. :param id_equip_acesso: Equipment identifier. :param fqdn: Equipment FQDN. :param user: User. :param password: Password...
9,599
def find_visible_elements(self, selector, by=By.CSS_SELECTOR, limit=0): self.wait_for_ready_state_complete() if page_utils.is_xpath_selector(selector): by = By.XPATH if page_utils.is_link_text_selector(selector): selector = page_utils.get_link_text_from_selector(...
Returns a list of matching WebElements that are visible. If "limit" is set and > 0, will only return that many elements.