code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def requestManager( self, timeout = 120 ): <NEW_LINE> <INDENT> if not self.__requestManager: <NEW_LINE> <INDENT> url = PathFinder.getServiceURL( "RequestManagement/RequestManager" ) <NEW_LINE> if not url: <NEW_LINE> <INDENT> raise RuntimeError( "CS option RequestManagement/RequestManager URL is not set!" ) <NEW_LINE> <...
facade for RequestManager RPC client
625941da4d74a7450ccd447f
def v_obs(self): <NEW_LINE> <INDENT> __vars = ["obstime", "ra", "dec"] <NEW_LINE> self.__check_args(__vars) <NEW_LINE> v_sun = 20 * u.km / u.s <NEW_LINE> dir_sun = SkyCoord( ra=18 * 15 * u.deg, dec=30 * u.deg, frame="fk4", equinox=Time("B1900"), ).galactic <NEW_LINE> U = v_sun * np.cos(dir_sun.b) * np.cos(dir_sun.l) <N...
Observer's verocity relative to LSR. Calcurate line-of-sight component of observer's velocity relative to LSR due to solar motion, the Earth's rotation and revolution. Returns ------- astropy.units.quantity.Quantity Velocity relative to LSR, along the line of sight. Notes ----- Parameters ['obstime', 'ra', 'dec'...
625941da4d74a7450ccd4480
def read(self): <NEW_LINE> <INDENT> requests.packages.urllib3.disable_warnings() <NEW_LINE> resp = requests.get(self.build_request_url(), verify=False) <NEW_LINE> if resp.status_code != 200: <NEW_LINE> <INDENT> raise CheckError('Expected status code: 200 (OK), returned' ' status code was: %d' % resp.status_code) <NEW_L...
Performs a request with a given command to the XML API and reads the output. :return: The XML output parsed by soup.
625941da91f36d47f21ac7b1
def site_content(self, election_day): <NEW_LINE> <INDENT> from electionnight.models import PageType <NEW_LINE> page_type = PageType.objects.get( model_type=ContentType.objects.get( app_label="election", model="electionday" ), election_day=election_day, ) <NEW_LINE> site_content = self.get( content_type=ContentType.obje...
Site content represents content for the entire site on a given election day.
625941da96565a6dacc8f987
def get(file,head=False,get=False,binary=False,size=None,timeout=30): <NEW_LINE> <INDENT> if not re.search(r'^http',file,flags=re.I): <NEW_LINE> <INDENT> file='http://'+file <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> response=urllib.request.urlopen(file) <NEW_LINE> if head: <NEW_LINE> <INDENT> return response <NEW_LI...
get the file if size is less than 100KB
625941daf9cc0f698b1408b5
def print_log(self, details, types='info', log=True): <NEW_LINE> <INDENT> if log: <NEW_LINE> <INDENT> if types == 'critical': <NEW_LINE> <INDENT> self.logger.critical(details) <NEW_LINE> <DEDENT> elif types == 'error': <NEW_LINE> <INDENT> self.logger.error(details) <NEW_LINE> <DEDENT> elif types == 'exception': <NEW_LI...
Print the log details and save to logfile. :param details: LogRecord details. :param types: str, logging types, default 'info'. In (critical, error, exception, warning, info, debug). :param log: the switch to log, default True.
625941da24f1403a92600e20
def servo_neutral(self): <NEW_LINE> <INDENT> self.spi_command(CMD_SERVO_NEUTRAL, delay=0.008)
Set all servos to 1500us.
625941da5f7d997b87174d56
def produce_reversed_images(source_dir, save_dir): <NEW_LINE> <INDENT> if os.path.exists(source_dir) is False: <NEW_LINE> <INDENT> os.makedirs(source_dir) <NEW_LINE> <DEDENT> if os.path.exists(save_dir) is False: <NEW_LINE> <INDENT> os.makedirs(save_dir) <NEW_LINE> <DEDENT> reversed_images_index = 0 <NEW_LINE> source_i...
Produce the reversed images
625941da796e427e537b0884
def get_active_units(sorted_trials): <NEW_LINE> <INDENT> N = next(sorted_trials.itervalues()).shape[0] <NEW_LINE> units = [] <NEW_LINE> for i in xrange(N): <NEW_LINE> <INDENT> active = False <NEW_LINE> for r in sorted_trials.values(): <NEW_LINE> <INDENT> if is_active(r[i]): <NEW_LINE> <INDENT> active = True <NEW_LINE> ...
Get units that do something.
625941da50812a4eaa59c5db
def print_max_dihedrals_per_atom(self): <NEW_LINE> <INDENT> self.print_maximum_per_atom("dihedral")
Return the maximum number of dihedrals per atom.
625941da0383005118ecf89e
def project_changed(self, path): <NEW_LINE> <INDENT> self.repository.path = path <NEW_LINE> self.save_defaults()
Project path change listener that change repository path when project path is changed
625941dab545ff76a89140d1
def compute_boundary_ts(ops): <NEW_LINE> <INDENT> ops = util.make_list_of_op(ops) <NEW_LINE> input_ts = _get_input_ts(ops) <NEW_LINE> output_ts = _get_output_ts(ops) <NEW_LINE> output_ts_set = frozenset(output_ts) <NEW_LINE> ops_set = frozenset(ops) <NEW_LINE> inside_ts = [] <NEW_LINE> only_inside_ts = [] <NEW_LINE> fo...
Compute the tensors at the boundary of a set of ops. This function looks at all the tensors connected to the given ops (in/out) and classify them into three categories: 1) input tensors: tensors whose generating operation is not in ops. 2) output tensors: tensors whose consumer operations are not in ops 3) inside tens...
625941da4527f215b584c711
def __enter__(self): <NEW_LINE> <INDENT> return self.con, self.cur
DatabaseConnection -> Object, Object When called using 'with', return the database connection and cursor objects.
625941da4f6381625f114cf8
@click.command() <NEW_LINE> @click.argument("files", nargs=-1, type=click.Path(exists=True)) <NEW_LINE> @click.option( "--x-units", default=None, help="Units to use for the x-axis: 'dim' (dimensions), 'synapses', or 'neurons'. " "By default, will choose a value based on the benchmark record. All records must " "use the...
View benchmarking results. FILES is one or more benchmarking .pkl record files to view.
625941da10dbd63aa1bd2e5f
def count_words(subreddit, word_list, after='', occurs={}): <NEW_LINE> <INDENT> url = 'https://api.reddit.com/r/' + subreddit + '?limit=100&after=' + after <NEW_LINE> response = requests.get(url, headers=headers) <NEW_LINE> try: <NEW_LINE> <INDENT> data = response.json() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> ...
Javascript should count as javascript, but java should not).
625941da5fc7496912cc3c3a
def cov_rq(x1, x2,alpha=0.5, l=1): <NEW_LINE> <INDENT> diff = distance_matrix(x1,x2) <NEW_LINE> return (1+diff**2 / (2*alpha*l))**-alpha
Rational Quadratic Covariance Function
625941da9c8ee82313fbba32
def three_five(lower=1, upper=101): <NEW_LINE> <INDENT> result = [] <NEW_LINE> if _check_if_range_boundaries_are_valid(lower=lower, upper=upper): <NEW_LINE> <INDENT> result = [_three_five_threefive_or_value(_num) for _num in range(lower, upper)] <NEW_LINE> <DEDENT> return result
:param lower: start value for desired range :param upper: upper - 1 indicates the last value on the range as python range excludes the last number :return: list containing the int, "Three", "Five" or "ThreeFive"
625941da8a43f66fc4b5431f
def find_top_left_corner(img, template): <NEW_LINE> <INDENT> match_val, match_pos = best_match(img, template) <NEW_LINE> top_left_sign = (match_pos[0] + template.shape[1], match_pos[1]) <NEW_LINE> return top_left_sign
returns the position of the top left corner of the region bounded on the left by the location of the template.
625941da090684286d50efa4
def getnowtime(): <NEW_LINE> <INDENT> nows = time.strftime("%Y-%m-%d %H:%M:%S") <NEW_LINE> return nows
:return: 返回当前时间y-m-d
625941dabe8e80087fb20efc
def __init__(self, store, max_candidates=10, min_similarity=75, max_length=70, comparer=None, usefuzzy=False): <NEW_LINE> <INDENT> if comparer is None: <NEW_LINE> <INDENT> comparer = lshtein.LevenshteinComparer(max_length) <NEW_LINE> <DEDENT> self.comparer = comparer <NEW_LINE> self.setparameters(max_candidates, min_si...
max_candidates is the maximum number of candidates that should be assembled, min_similarity is the minimum similarity that must be attained to be included in the result, comparer is an optional Comparer with similarity() function
625941da099cdd3c635f0f17
def write_country_state_city(self, header_rows, rows, ip_position, output_file): <NEW_LINE> <INDENT> if output_file is None: <NEW_LINE> <INDENT> the_output_file = sys.stdout <NEW_LINE> <DEDENT> elif type(output_file) == str: <NEW_LINE> <INDENT> the_output_file = open(output_file, 'w') <NEW_LINE> <DEDENT> else: <NEW_LIN...
The actual lookup: @param header_rows: possibly empty row of header lines @type header_rows: [[str]] @param rows: rows containing IP addresses to resolve to countries @type rows: [[str]] @param ip_position: zero-origin index to IP-containing column in each rows. @type ip_position: int @param output_file: output file; ...
625941da30bbd722463cc085
def __init__(self, cmd, parameters, usage): <NEW_LINE> <INDENT> self.cmd = cmd <NEW_LINE> self.parameters = parameters <NEW_LINE> self.usage = usage <NEW_LINE> if 'dir_op' not in parameters: <NEW_LINE> <INDENT> self.parameters['dir_op'] = False <NEW_LINE> <DEDENT> if 'follow_symlinks' not in parameters: <NEW_LINE> <IND...
Stores command name and parameters. Ensures that the ``dir_op`` flag is true if a certain command is being used. :param cmd: The name of the command, e.g. "rm". :param parameters: A dictionary of parameters. :param usage: A usage string
625941da32920d7e50b2848f
def readRates( infile ): <NEW_LINE> <INDENT> from rpy import r as R <NEW_LINE> import rpy <NEW_LINE> handle, name = tempfile.mkstemp() <NEW_LINE> os.close(handle) <NEW_LINE> outfile = open(name, "w") <NEW_LINE> first = True <NEW_LINE> headers = [] <NEW_LINE> for line in infile: <NEW_LINE> <INDENT> if line[0] == "#": co...
read rates and G+C from a tab-separated file.
625941da377c676e91272465
def drag_and_drop(self, el_css, ta_css): <NEW_LINE> <INDENT> t1 = time.time() <NEW_LINE> try: <NEW_LINE> <INDENT> self.element_wait(el_css) <NEW_LINE> element = self.get_element(el_css) <NEW_LINE> self.element_wait(ta_css) <NEW_LINE> target = self.get_element(ta_css) <NEW_LINE> ActionChains(self.driver).drag_and_drop(e...
Drags an element a certain distance and then drops it. 拖动一个元素一定的距离,然后丢弃它。 Usage: driver.drag_and_drop("id->kw","id->su")
625941da5510c4643540f69b
def __init__(self, name, variables, nonlinearSpecs): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.variables = variables <NEW_LINE> self.genericForbiden = len(self.variables) <= 1 <NEW_LINE> self.generic = not self.genericForbiden <NEW_LINE> self.alwaysActive = False <NEW_LINE> self.active = False <NEW_LINE> sel...
Ctor :param name: name of the group of variables :type name: str :param variables: list of variables in the group :type varariables: list(variable) :param nonlinearSpecs: list of possible nonlinear specifications :type nonlinearSpecs: list(function)
625941da2ae34c7f2600d3ee
def test_02_desktop(self): <NEW_LINE> <INDENT> nsoup = NewsSoup(self.url, refresh=True, mobile=False) <NEW_LINE> self.assertEqual('ltn', nsoup.channel) <NEW_LINE> self.assertIn('疑因病厭世 男子國小圖書館上吊身亡', nsoup.title()) <NEW_LINE> self.assertEqual('2018-10-15 23:51:00', nsoup.date().strftime(self.dtf)) <NEW_LINE> self.assertE...
測試桌面版網頁解構 * 務必開啟強制更新,確保解構程式能跟進網站最新版本 * 實際新聞內容有可能更新,需要同步單元測試的預期值
625941daec188e330fd5aa57
def _with_namespace(f, include_app): <NEW_LINE> <INDENT> @wraps(f) <NEW_LINE> def inner(parsed_args): <NEW_LINE> <INDENT> parsed_args = vars(parsed_args) <NEW_LINE> parsed_args.pop('_functions_stack', None) <NEW_LINE> if not include_app: <NEW_LINE> <INDENT> parsed_args.pop('app') <NEW_LINE> <DEDENT> return f(**parsed_a...
Call the function with the parsed arguments.
625941daeab8aa0e5d26de15
def test_apply_no_keyid_default(self): <NEW_LINE> <INDENT> env, ui = self._make_ui_mock() <NEW_LINE> with mock.patch('alot.commands.envelope.settings.get_account_by_address', mock.Mock(return_value=mock.Mock(gpg_key='sentinel'))): <NEW_LINE> <INDENT> cmd = envelope.SignCommand(action='sign', keyid=None) <NEW_LINE> cmd....
If there is no keyid and the account has a gpg key, then that should be used.
625941da24f1403a92600e21
def _parseServerPorts(self, document, instanceNumber, hostname): <NEW_LINE> <INDENT> portDeclarations = document.findIndexedValues('icm/server_port') <NEW_LINE> parsePortDeclaration = fptools.partiallyApply( InstanceProfileParser._parsePortDeclarationToEndpoint, fptools._, instanceNumber, hostname) <NEW_LINE> return fi...
@types: IniDocument -> tuple[Endpoint]
625941daac7a0e7691ed4385
def CargaServiciosMesaNormal(ListaComandas,treeServicios,idMesa): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> cur.execute("SELECT max(idfactura) from factura where idmesa="+str(idMesa)+"") <NEW_LINE> cursor = cur.fetchall() <NEW_LINE> for row in cursor: <NEW_LINE> <INDENT> idFactu = row[0] <NEW_LINE> <DEDENT> <DEDENT>...
# Accion que carga los servicios de cualquier mesa, da igual si está ocupada o no
625941da91af0d3eaac9bcd8
def dot_product_attention(q, k, v, bias, dropout_rate=0.0, image_shapes=None, name=None, make_image_summary=True, save_weights_to=None, dropout_broadcast_dims=None): <NEW_LINE> <INDENT> with tf.variable_scope( name, default_name="dot_product_attention", values=[q, k, v]) as scope: <NEW_LINE> <INDENT> logits = tf.matmul...
dot-product attention. Args: q: a Tensor with shape [batch, heads, length_q, depth_k] k: a Tensor with shape [batch, heads, length_kv, depth_k] v: a Tensor with shape [batch, heads, length_kv, depth_v] bias: bias Tensor (see attention_bias()) dropout_rate: a floating point number image_shapes: optional tup...
625941da498bea3a759b9d6c
def beta_alpha(self, market): <NEW_LINE> <INDENT> beta, alpha = np.polyfit(market["nml_close"], self.total/self.total[0], 1) <NEW_LINE> return beta, alpha
market is a Equity representing the market. It can be S&P 500, Russel 2000, or your choice of market indicator.
625941da6aa9bd52df037062
@register_model <NEW_LINE> def efficientnet_b1(pretrained=False, **kwargs): <NEW_LINE> <INDENT> kwargs['bn_eps'] = BN_EPS_TF_DEFAULT <NEW_LINE> model = _gen_efficientnet( 'efficientnet_b1', channel_multiplier=1.0, depth_multiplier=1.1, pretrained=pretrained, **kwargs) <NEW_LINE> return model
EfficientNet-B1
625941da5fcc89381b1e197f
def update_appleosx_device_profile(self, profile_id, data): <NEW_LINE> <INDENT> url = 'mdm/profiles/platforms/appleosx/update' <NEW_LINE> assert isinstance(profile_id, (int, )) <NEW_LINE> cpd = self.get_profile(profile_id) <NEW_LINE> cpdg = cpd['General'] <NEW_LINE> payload = data <NEW_LINE> payload['General'] = { 'Ass...
Updates an Apple device profile identified by its numeric ID. This endpoint requires a lot of data. We use the strategy of automatically filling in all this data from what the profile already has set. This makes the process of altering only the settings easier since you don't have to worry about all the other payload ...
625941da44b2445a33932351
def get_pages(): <NEW_LINE> <INDENT> i = 0 <NEW_LINE> last_page = None <NEW_LINE> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> html = get_page(i) <NEW_LINE> <DEDENT> except HTTPError as err: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> except URLError as err: <NEW_LINE> <INDENT> logger.warn("Failed to retr...
Returns a generator that retrieves Reports and Decisions pages and parses them as HTML.
625941da07f4c71912b11741
def convertirASegundos(h, m, s): <NEW_LINE> <INDENT> calculo = (h * 3600) + (m * 60) + s <NEW_LINE> return calculo
Esta función recibe tres parámetros h (horas), m (minutos) y s (segundos) y devuelve ese intervalo en segundos.
625941da99fddb7c1c9de64d
def sort_modes(evals, evecs): <NEW_LINE> <INDENT> evalsorg = np.zeros_like(evals) <NEW_LINE> evecsorg = np.zeros_like(evecs) <NEW_LINE> evalsorg[0] = evals[0] <NEW_LINE> evecsorg[0] = evecs[0] <NEW_LINE> for i, speed in enumerate(evals): <NEW_LINE> <INDENT> if i == evals.shape[0] - 1: <NEW_LINE> <INDENT> break <NEW_LIN...
Sort a series of eigenvalues and eigenvectors into modes. Parameters ---------- evals : ndarray, shape (n, m) eigenvalues evecs : ndarray, shape (n, m, m) eigenvectors
625941da167d2b6e31218e52
@strategies.composite <NEW_LINE> def timespans(draw, dates=None, unbounds="any", always_valid=True): <NEW_LINE> <INDENT> from xotl.tools.future.datetime import TimeSpan <NEW_LINE> if dates is None: <NEW_LINE> <INDENT> dates = strategies.dates() <NEW_LINE> <DEDENT> maybe = strategies.none() | dates <NEW_LINE> if unbound...
A strategy that generates `xotl.tools.future.datetime.TimeSpan`:class:. This is a `hypothesis`_ strategy. `dates` should be None or generator of `datetime.date`:class: objects. It defaults to `hypothesis.strategies.dates`:func: `unbounds` should be one of the strings 'none', 'any', 'past', 'future'. If 'any' then th...
625941dab7558d58953c51cd
def google_translate(content, from_lang='zh-CN', to='en'): <NEW_LINE> <INDENT> langs_mapping = {"zh": 'zh-CN', 'en': 'en'} <NEW_LINE> from_lang = langs_mapping[from_lang] <NEW_LINE> to = langs_mapping[to] <NEW_LINE> data = { "client": "t", "sl": from_lang, "tl": to, "hl": "zh-CN", "dt": "at", "dt": "bd", "dt": "ex", "d...
需要翻墙,自己先准备梯子 support languages: 中文 - zh-CN 英文 - en 日文 - ja 韩文 - ko 法文 - fr 德文 - de Return: list of string
625941da66656f66f7cbc469
def getDeviceIpAddress(self): <NEW_LINE> <INDENT> d = self.device() <NEW_LINE> if d: <NEW_LINE> <INDENT> int = d.getManageInterface() <NEW_LINE> if int: <NEW_LINE> <INDENT> return int.getIpAddress() <NEW_LINE> <DEDENT> <DEDENT> return ""
Get the management ip with netmask (1.1.1.1/24) of a device
625941dabe7bc26dc91cd8b9
def make_all_pages(document, root_box): <NEW_LINE> <INDENT> prefix = 'first_' <NEW_LINE> page_break = root_box.style.page_break_before <NEW_LINE> if page_break == 'right': <NEW_LINE> <INDENT> right_page = True <NEW_LINE> <DEDENT> if page_break == 'left': <NEW_LINE> <INDENT> right_page = False <NEW_LINE> <DEDENT> else: ...
Return a list of laid out pages without margin boxes.
625941dacdde0d52a9e532f2
def checkRisk(self, orderReq): <NEW_LINE> <INDENT> if not self.active: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if orderReq.volume > self.orderSizeLimit: <NEW_LINE> <INDENT> self.writeRiskLog(u'单笔委托数量%s,超过限制%s' %(orderReq.volume, self.orderSizeLimit)) <NEW_LINE> self.mainEngine.writeWarning(u'单笔委托数量%s,超过限制%s...
检查风险
625941dad6c5a1020814430a
def getWidth(self) : <NEW_LINE> <INDENT> width = 0; <NEW_LINE> if not np.isinf(self._cap) : <NEW_LINE> <INDENT> width += math.ceil(math.log10(self._cap)); <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> return None; <NEW_LINE> <DEDENT> width += 1; <NEW_LINE> width += self._precision; <NEW_LINE> return max(width, len(sel...
Returns column width.
625941da38b623060ff0b0ab
def set_report(self, report): <NEW_LINE> <INDENT> self.report = report
Update the report on this value.
625941da57b8e32f5248375a
def initializeUniformly(self, gameState): <NEW_LINE> <INDENT> self.particles = [] <NEW_LINE> ghosts = list(itertools.product(self.legalPositions, repeat = self.numGhosts)) <NEW_LINE> random.shuffle(ghosts) <NEW_LINE> while(len(self.particles) < self.numParticles): <NEW_LINE> <INDENT> self.particles = self.particles + g...
Initialize particles to be consistent with a uniform prior. Particles should be evenly distributed across positions in order to ensure a uniform prior.
625941da2c8b7c6e89b35a7d
def setcycle(self,cycle): <NEW_LINE> <INDENT> cycle=to_datetime(cycle) <NEW_LINE> strcycle=cycle.strftime('%Y%m%d%H') <NEW_LINE> self._conf.set('config','cycle',strcycle) <NEW_LINE> self._cycle=cycle <NEW_LINE> self.set_time_vars()
!set the analysis time Sets the analysis time of this workflow. Also sets the [config] section's "cycle" option. Accepts anything that produtil.numerics.to_datetime recognizes.
625941da4f88993c3716c323
def get_config(): <NEW_LINE> <INDENT> cfg = VersioneerConfig() <NEW_LINE> cfg.VCS = "git" <NEW_LINE> cfg.style = "pep440" <NEW_LINE> cfg.tag_prefix = "v" <NEW_LINE> cfg.parentdir_prefix = "pyhector-" <NEW_LINE> cfg.versionfile_source = "pyhector/_version.py" <NEW_LINE> cfg.verbose = False <NEW_LINE> return cfg
Create, populate and return the VersioneerConfig() object.
625941da6fb2d068a760f35e
def test_create_user(user_dict): <NEW_LINE> <INDENT> user = User(**user_dict) <NEW_LINE> with db_session() as session: <NEW_LINE> <INDENT> session.add(user) <NEW_LINE> session.commit() <NEW_LINE> persisted_user = session.query(User).filter_by( phone_number=user_dict['phone_number']).one() <NEW_LINE> assert isinstance(p...
successfully creates a user record
625941da851cf427c661a7ca
def hinge_loss(pos_scores, neg_scores): <NEW_LINE> <INDENT> loss = 1.0 + neg_scores - pos_scores <NEW_LINE> return T.mean((loss > 0) * loss)
:param pos_scores: 1D: batch, 2D: n_labels :param neg_scores: 1D: batch, 2D: n_labels :return: avg hinge_loss: float
625941da66673b3332b9234f
def forward(self, x, encoder_padding_mask: Optional[Tensor], attn_mask: Optional[Tensor] = None): <NEW_LINE> <INDENT> if attn_mask is not None: <NEW_LINE> <INDENT> attn_mask = attn_mask.masked_fill(attn_mask.to(torch.bool), -1e8) <NEW_LINE> <DEDENT> residual = x <NEW_LINE> if self.normalize_before: <NEW_LINE> <INDENT> ...
Args: x (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)` encoder_padding_mask (ByteTensor): binary ByteTensor of shape `(batch, seq_len)` where padding elements are indicated by ``1``. attn_mask (ByteTensor): binary tensor of shape `(tgt_len, src_len)`, where `tgt_len` is ...
625941da6fece00bbac2d9ff
@registry.register_hparams <NEW_LINE> def transformer_wikitext103_l4k_v0(): <NEW_LINE> <INDENT> hparams = transformer_big() <NEW_LINE> hparams.optimizer = "Adafactor" <NEW_LINE> hparams.learning_rate_schedule = "rsqrt_decay" <NEW_LINE> hparams.learning_rate_warmup_steps = 10000 <NEW_LINE> hparams.num_heads = 4 <NEW_LIN...
HParams for training languagemodel_wikitext103_l4k.
625941daf8510a7c17cf99bb
def get_class(class_name, module_name=None): <NEW_LINE> <INDENT> if module_name is None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> module_name, class_name = class_name.rsplit(".", 1) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise ImportError( "Class name '%s' must be fully-qualified when no module ...
Returns the class specified by the given class string, loading the parent module if necessary. Args: class_name: the "ClassName" or a fully-qualified class name like "eta.core.utils.ClassName" module_name: the fully-qualified module name like "eta.core.utils", or None if class_name includes the...
625941dad8ef3951e32437fb
def receive_end_effector_wrench(self, msg): <NEW_LINE> <INDENT> self.end_effector_wrench = msg.wrench
Callback for '/j2n6s300_driver/out/end/tool_wrench'. :param msg: end-effector wrench :return: None
625941da656771135c3ebb2f
def load_sample(self, scene, start_frame, target_size): <NEW_LINE> <INDENT> grayscale, y = dataset.read_frame_lab(scene, start_frame + self.contiguous_count, target_size) <NEW_LINE> state = [ dataset.read_frame_lab(scene, start_frame + i, target_size)[0] for i in range(self.contiguous_count) ] <NEW_LINE> return state +...
Load a sample to build a batch.
625941daadb09d7d5db6ca4c
def new_url(**kwargs): <NEW_LINE> <INDENT> url_base = "/axapi/v3/health/monitor/{monitor_name}/method/icmp" <NEW_LINE> f_dict = {} <NEW_LINE> f_dict["monitor_name"] = kwargs["monitor_name"] <NEW_LINE> return url_base.format(**f_dict)
Return the URL for creating a resource
625941da9b70327d1c4e1093
def _fill_templates(self): <NEW_LINE> <INDENT> for filename in self._filename_factory(): <NEW_LINE> <INDENT> network_file = OVZNetworkFile(filename) <NEW_LINE> self.iface_file = str( Template.Template(self.template, searchList=[ {'interfaces': self.interface_info, 'use_ipv6': CONF.use_ipv6}])) <NEW_LINE> with network_f...
Iterate through each file necessary for creating interfaces on a given platform, open the file and write the contents of the template to the file.
625941da63f4b57ef00013d0
def post_message(consumers, lti_key, url, body): <NEW_LINE> <INDENT> content_type = 'application/xml' <NEW_LINE> method = 'POST' <NEW_LINE> (_, content) = _post_patched_request( consumers, lti_key, body, url, method, content_type, ) <NEW_LINE> is_success = "<imsx_codeMajor>success</imsx_codeMajor>" in content <NEW_LINE...
Posts a signed message to LTI consumer :param consumers: consumers from config :param lti_key: key to find appropriate consumer :param url: post url :param body: xml body :return: success
625941da3cc13d1c6d3c7637
def get_feats_that_can_be_converted_to_int(df, seed=27, n_samples=100): <NEW_LINE> <INDENT> cols_to_int = [] <NEW_LINE> for col in df.columns: <NEW_LINE> <INDENT> if df[col].dtype.name not in ['object', 'category', 'int8', 'int16', 'int32', 'int64']: <NEW_LINE> <INDENT> convert_to_int_possible = df.loc[df[col].notnull(...
This method returns features that can be potentially down-casted to int. It uses random subsample of data of size n_samples and checks np.allclose(x, int(x), rtol=0, atol=0)) condition. If all samples are True -> feature can be potentially down-casted to int data type. :param df: pandas DF containing both train and tes...
625941da097d151d1a223116
def run_linter(self, settings, code, filename): <NEW_LINE> <INDENT> errors = [] <NEW_LINE> if settings.get("pep8", True): <NEW_LINE> <INDENT> check_params = { 'ignore': settings.get('pep8_ignore', []), 'max_line_length': settings.get( 'pep8_max_line_length', pep8.MAX_LINE_LENGTH ) } <NEW_LINE> errors.extend(self.pep8_c...
Check the code to find errors
625941da8a43f66fc4b54320
def testCase000(self): <NEW_LINE> <INDENT> start =os.path.normpath( '//hostname/tests//////a/b/hostname//c////////d/tests/b///c') <NEW_LINE> startRef = ('SHARE', 'hostname', 'tests', os.path.normpath('a/b/hostname/c/d/tests/b/c')) <NEW_LINE> ret = filesysobjects.FileSysObjects.splitAppPrefix(start) <NEW_LINE> self.asse...
Respect 'hostname', which is actual hostname, and a node name.
625941da091ae35668667218
def test_become_ordinary(self): <NEW_LINE> <INDENT> with api.env.adopt_user(username='worker'): <NEW_LINE> <INDENT> self.should_allow([ 'public_method', 'pp_method', ]) <NEW_LINE> self.should_forbid([ 'private_method', 'qq_method', 'rr_method', ]) <NEW_LINE> <DEDENT> self.test_test_defaults()
Tests that becoming a user with fewer permissions works.
625941da8e05c05ec3eea634
def train_completion_network_and_discriminator_jointly(self, images, mask_c, local_area_top_left_c, local_area_top_left_d): <NEW_LINE> <INDENT> global_step = self._global_step.eval(self._sess) <NEW_LINE> feed_dict = {self._ground_truth_ph: images, self._mask_c_ph: mask_c, self._local_area_top_left_c_ph: local_area_top_...
:param images: 4-D array or tensor :param mask_c: 4-D array or tensor, has same shape of images :param local_area_top_left_c: 1*2 vector, top left point position of local area of mask_c in images :param local_area_top_left_d: 1*2 vector, top left point position of local area of mask_d in images :return:
625941da9c8ee82313fbba33
def write(self, line=None): <NEW_LINE> <INDENT> if not self._initialized: <NEW_LINE> <INDENT> self.initialize() <NEW_LINE> <DEDENT> if shell.check_windows(): <NEW_LINE> <INDENT> self._file.write(line.replace('\\"', '"')) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._file.write(line)
Write a string in the manifest, no new line
625941da7d43ff24873a2f5f
def test_json_wrap_exception(self): <NEW_LINE> <INDENT> self.result.content = '{"' <NEW_LINE> self.assertRaises(http.ClientException, http.json_wrap(self.function))
Raises a generalized exception for failed 200s
625941da99cbb53fe6792ea4
def take_turn(self, player: Player, game: Game, sink: CommandsSink): <NEW_LINE> <INDENT> cancelled = True <NEW_LINE> def make_select(command: commands.InteractiveCommand, choice): <NEW_LINE> <INDENT> return lambda: command.select(choice) <NEW_LINE> <DEDENT> def make_exec(command: commands.Command): <NEW_LINE> <INDENT> ...
Should execute commands via sink
625941da4e4d5625662d4693
def test_rasterize_invalid_stdin(tmpdir, runner): <NEW_LINE> <INDENT> output = str(tmpdir.join('test.tif')) <NEW_LINE> result = runner.invoke( main_group, ['rasterize', output], input='BOGUS') <NEW_LINE> assert result.exit_code
Invalid value for stdin should fail with exception
625941da30c21e258bdfa75d
def decorator(method): <NEW_LINE> <INDENT> self.examples[method.__name__] = example <NEW_LINE> @wraps(method) <NEW_LINE> def decorated(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> params = json.loads(request.values['q']) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return jsonify(error_msg='Missing input...
the decorator returned by rpc
625941dab7558d58953c51ce
def verifyLineageSet(self, markerSetFile, bRequireTaxonomy): <NEW_LINE> <INDENT> with open(markerSetFile) as f: <NEW_LINE> <INDENT> f.readline() <NEW_LINE> for line in f: <NEW_LINE> <INDENT> if line.strip() != '': <NEW_LINE> <INDENT> lineSplit = line.split('\t') <NEW_LINE> binId = lineSplit[0] <NEW_LINE> _numMarkers = ...
Verify output of lineage set command.
625941dacc0a2c11143dd14f
def putData(self, D): <NEW_LINE> <INDENT> if not(isinstance(D, numpy.ndarray)) or len(D.shape) != 2: <NEW_LINE> <INDENT> raise ValueError( 'Data must be given as a NUMPY array (samples x channels)') <NEW_LINE> <DEDENT> nSamp = D.shape[0] <NEW_LINE> nChan = D.shape[1] <NEW_LINE> (dataType, dataBuf) = serialize(D) <NEW_L...
putData(D) -- writes samples that must be given as a NUMPY array, samples x channels. The type of the samples (D) and the number of channels must match the corresponding quantities in the FieldTrip buffer.
625941dadd821e528d63b465
def __init__(self, File): <NEW_LINE> <INDENT> StringOutputStreamBase.__init__(self) <NEW_LINE> self.file = open(File, 'w')
Creates a new file ouput stream from the given file name.
625941da63d6d428bbe447ae
def matimport(mfilename): <NEW_LINE> <INDENT> print(f"Importing {mfilename} …") <NEW_LINE> mat = scio.loadmat(mfilename) <NEW_LINE> mat_id = mat['id'].astype(np.uint32) <NEW_LINE> mat_trace = mat['trace'].astype(np.uint16) <NEW_LINE> mat_t_event = mat['t_event'].astype(np.float64) <NEW_LINE> mat_delay = mat['delay'].as...
Import event times as `pandas.DataFrame`. The argument `mfilename` must be a string of a path at which a Matlab matfile with a version earlier than 7.3 is located. The matfile at this path is read and returned as `pandas.DataFrame`. The following variables are expected in the matfile: * `id`: an integer array of uniq...
625941daf7d966606f6aa2c5
def test_add_event_success(self): <NEW_LINE> <INDENT> payload = {"eid": "16", "name": "一加8手机发布会", "limit": 2000, "status": "0", "address": "深圳宝体会展中心", "start_time": "2018-09-15 22:40:00", 'time': self.client_time, 'sign': self.sign_md5} <NEW_LINE> r = requests.post(self.url, data=payload) <NEW_LINE> result = r.json() <...
添加成功
625941da55399d3f05588973
def pdf(self, eXB): <NEW_LINE> <INDENT> raise NotImplementedError
NotImplemented
625941dad268445f265b512c
def delete(self, node_to_delete): <NEW_LINE> <INDENT> data = node_to_delete.data <NEW_LINE> if node_to_delete is self.head and node_to_delete is self.tail: <NEW_LINE> <INDENT> self.head = None <NEW_LINE> self.tail = None <NEW_LINE> <DEDENT> elif node_to_delete is self.head: <NEW_LINE> <INDENT> self.head = self.head.nex...
더블리 링크드 리스트 삭제 연산 메소드
625941daa05bb46b383ecade
def findCaller(self, stack_info=False): <NEW_LINE> <INDENT> f = currentframe() <NEW_LINE> if f is not None: <NEW_LINE> <INDENT> f = f.f_back <NEW_LINE> <DEDENT> rv = "(unknown file)", 0, "(unknown function)", None <NEW_LINE> while hasattr(f, "f_code"): <NEW_LINE> <INDENT> co = f.f_code <NEW_LINE> filename = os.path.nor...
Find the stack frame of the caller so that we can note the source file name, line number and function name.
625941dad8ef3951e32437fc
def update(self): <NEW_LINE> <INDENT> self._update(forced=True)
Perform a TurtleScreen update. Especially useful to control screen updates when tracer(False) is set. Example (for a Pen instance named turtle): >>> tracer(0) >>> for i in range(36): for j in range(5): turtle.fd(100) turtle.lt(72) turtle.update() # draws a pentagon at on...
625941daf9cc0f698b1408b7
def STO(): <NEW_LINE> <INDENT> MEM[MEM[-2]] = MEM[-1] <NEW_LINE> MEM.pop(-1) <NEW_LINE> MEM.pop(-1)
Stocke la valeur au sommet à l'adresse indiquée par le sous-sommet, dépile 2 fois
625941da851cf427c661a7cb
@handler('interface', 'xmi2uml', 'hierarchygenerator', 'interface') <NEW_LINE> def interface(self, source, target): <NEW_LINE> <INDENT> interface = Interface() <NEW_LINE> assignxmiprops(interface,source) <NEW_LINE> target.anchor[source.attributes['name']] = interface <NEW_LINE> target.finalize(source, interface)
Create interfaces.
625941da01c39578d7e750fa
def get_binwidth(self): <NEW_LINE> <INDENT> width_in_seconds = self._bin_width * 1e-9 <NEW_LINE> return width_in_seconds
Returns the width of a single timebin in the timetrace in seconds.
625941dadd821e528d63b466
def create_test_case(self, title, section_id): <NEW_LINE> <INDENT> return self.tr_post('add_case/{}'.format(section_id), {"title": title})
Creates a new test case in TestRail :param title: Title of the test-case :param section_id: ID of the subsection to create the test case in :return: response object
625941da4e696a04525c970a
def isSubsequence(self, s, t): <NEW_LINE> <INDENT> i=0 <NEW_LINE> for c in t: <NEW_LINE> <INDENT> if i==len(s): break <NEW_LINE> if c==s[i]: i+=1 <NEW_LINE> <DEDENT> return i==len(s)
:type s: str :type t: str :rtype: bool
625941da435de62698dfdf0b
def debug_smug(): <NEW_LINE> <INDENT> config["smugofile_file"] = os.path.join("..", config["smugofile_file"]) <NEW_LINE> if len(sys.argv) not in [1, 2] : <NEW_LINE> <INDENT> debug_help() <NEW_LINE> exit(-1) <NEW_LINE> <DEDENT> elif len(sys.argv) == 2 and sys.argv[1] == "-h": <NEW_LINE> <INDENT> debug_help() <NEW_LINE> ...
This is the debug mode function. If you need to do some debugging without using blogofile.
625941dab5575c28eb68e2c1
def _start(self): <NEW_LINE> <INDENT> s = SimpleXMLRPCServer(("", get_port(self.url)), logRequests=False) <NEW_LINE> s.register_instance(self) <NEW_LINE> s.serve_forever()
供内部用来启动XML-RPC服务器
625941da4527f215b584c713
def read_dot(path): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> import pydot <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> raise ImportError("read_dot() requires pydot", "http://dkbza.org/pydot.html/") <NEW_LINE> <DEDENT> fh=_get_fh(path,'r') <NEW_LINE> data=fh.read() <NEW_LINE> P=pydot.graph_from_dot_da...
Return a NetworkX MultiGraph or MultiDiGraph from a dot file on path. Parameters ---------- path : filename or file handle Returns ------- G : NetworkX multigraph A MultiGraph or MultiDiGraph. Notes ----- Use G=nx.Graph(nx.read_dot(path)) to return a Graph instead of a MultiGraph.
625941dabe383301e01b5740
def __init__(self, mtype=None, amount=None, recipient_id=None, options=None): <NEW_LINE> <INDENT> self.mtype = mtype <NEW_LINE> self.amount = amount <NEW_LINE> self.recipient_id = recipient_id <NEW_LINE> self.options = options
Constructor for the CreateSplitRequest class
625941da5fc7496912cc3c3c
def test_mailing_list_7(self): <NEW_LINE> <INDENT> base = os.path.sep.join([COMPRESSED_DIR, 'mlstats.org/pipermail/mlstats-list/']) <NEW_LINE> ml = MailingList(base) <NEW_LINE> target = base.strip(os.path.sep) <NEW_LINE> expected = { 'location': base.rstrip(os.path.sep), 'alias': 'mlstats-list', 'compressed_dir': os.pa...
Local directory in .mlstats with trailing slash
625941da3317a56b86939f11
def isValidSudoku(self, board): <NEW_LINE> <INDENT> row_dic = {} <NEW_LINE> col_dic = {} <NEW_LINE> dic = {} <NEW_LINE> for i in range(len(board)): <NEW_LINE> <INDENT> for j in range(len(board[i])): <NEW_LINE> <INDENT> if board[i][j] == ".": <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> val = i*10 + int(board[i][j])...
:param board:list[list[str]] :return: bool
625941daf8510a7c17cf99bc
def refresh_dataset(self): <NEW_LINE> <INDENT> return self.prescience.refresh_dataset(dataset_id=self.dataset_id())
Launch a refresh task on the current dataset :return: The refresh task object
625941da26238365f5f0f130
def valid(b, t): <NEW_LINE> <INDENT> if '_valid' in b: <NEW_LINE> <INDENT> for a, b in b['_valid']: <NEW_LINE> <INDENT> if t >= a and t <= b: return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> elif '_tmin' in b: <NEW_LINE> <INDENT> if '_tmax' in b and b['_tmax'] is not None: <NEW_LINE> <INDENT> return t >...
>>> valid({ '_valid': [] }, 123) False >>> valid({ }, 123) False >>> valid({ '_tmax': 0 }, 123) False >>> valid({ '_valid': [(100, 200), (350, 400)] }, 100) True >>> valid({ '_valid': [(100, 200), (350, 400)] }, 101) True >>> valid({ '_valid': [(100, 200), (350, 400)] }, 357.2) True >>> valid({ '_valid': [(100, 200), ...
625941dab545ff76a89140d4
def clear_frame_memory(self, color): <NEW_LINE> <INDENT> self.set_memory_area(0, 0, self.width - 1, self.height - 1) <NEW_LINE> self.set_memory_pointer(0, 0) <NEW_LINE> self.send_command(WRITE_RAM) <NEW_LINE> for i in range(0, self.width / 8 * self.height): <NEW_LINE> <INDENT> self.send_data(color)
@brief: clear the frame memory with the specified color. this won't update the display.
625941da090684286d50efa6
def relu_backward(dout, cache): <NEW_LINE> <INDENT> x = cache <NEW_LINE> dx = dout <NEW_LINE> dx[x <= 0] = 0 <NEW_LINE> return dx
Compute backward pass/find gradients of a fully connected layer :param dout: gradient of output :param cache: cache of full and relu layers :return: gradient of x
625941da1f037a2d8b9464bc
def test_build_endpoint(self): <NEW_LINE> <INDENT> expected = 'http://dev.markitondemand.com/MODApis/Api/v2/quote/json?symbol=tsla' <NEW_LINE> result = wrapper.build_endpoint(wrapper.FUNCTION_QUOTE, 'tsla') <NEW_LINE> self.assertEqual(result, expected, 'Invalid QUOTE endpoint "{}"'.format(result)) <NEW_LINE> expected =...
Tests MarkitOnDemand.build_endpoint(Quote | Lookup |Invalid function name).
625941da15fb5d323cde0dd2
def _time_sort_key(d): <NEW_LINE> <INDENT> container_id = d.get('container_id') or '' <NEW_LINE> attempt_parts = (d.get('attempt_id') or d.get('task_id') or d.get('job_id') or d.get('application_id') or _to_job_id(container_id) or '').split('_') <NEW_LINE> container_parts = container_id.split('_') <NEW_LINE> timestamp_...
Sort key to sort the dictionaries containing IDs roughly by time (earliest first). We consider higher attempt_nums "later" than higher task_nums (of the same step type) because fatal errors usually occur on the final attempt of a task. If we can, we convert (YARN) container IDs to attempt IDs. Unconverted container I...
625941dad10714528d5fffa4
def get_robots_content(self) -> str: <NEW_LINE> <INDENT> index = getattr(self, 'index', None) <NEW_LINE> follow = getattr(self, 'follow', None) <NEW_LINE> if index and follow: <NEW_LINE> <INDENT> return f'{index}, {follow}' <NEW_LINE> <DEDENT> return ''
Return robots content
625941da956e5f7376d7112a
def run(self): <NEW_LINE> <INDENT> salt.utils.appendproctitle(self.__class__.__name__) <NEW_LINE> self.event = get_event('master', opts=self.opts) <NEW_LINE> events = self.event.iter_events(full=True) <NEW_LINE> self.event.fire_event({}, 'salt/event_listen/start') <NEW_LINE> event_queue = [] <NEW_LINE> try: <NEW_LINE> ...
Spin up the multiprocess event returner
625941dafb3f5b602dac3955
def _score_ttest(self, X, y): <NEW_LINE> <INDENT> mdm = self.mdm.fit(X, y) <NEW_LINE> covmeans = numpy.array(mdm.covmeans_) <NEW_LINE> n_classes = len(covmeans) <NEW_LINE> pairs = pairwise_distance(covmeans, metric=mdm.metric_dist) <NEW_LINE> mean_dist = numpy.triu(pairs).sum() <NEW_LINE> mean_dist /= (n_classes * (n_c...
Get the score
625941da32920d7e50b28491
def map_wires(wires: list, qc_wires: list) -> dict: <NEW_LINE> <INDENT> if wires is None: <NEW_LINE> <INDENT> return dict(zip(qc_wires, range(len(qc_wires)))) <NEW_LINE> <DEDENT> if len(qc_wires) == len(wires): <NEW_LINE> <INDENT> return dict(zip(qc_wires, wires)) <NEW_LINE> <DEDENT> raise qml.QuantumFunctionError("The...
Utility function mapping the wires specified in a quantum circuit with the wires specified by the user for the template. Args: wires (list): wires specified for the template qc_wires (list): wires from the converted quantum circuit Returns: wire_map (dict): map from quantum circuit wires to the user defin...
625941da45492302aab5e585
def __getstate__(cfg): <NEW_LINE> <INDENT> return cfg.__dict__
FIXME Example: >>> # ENABLE_DOCTEST >>> from dtool_ibeis.base import * # NOQA >>> from dtool_ibeis.example_depcache import DummyKptsConfig >>> from six.moves import cPickle as pickle >>> cfg = DummyKptsConfig() >>> ser = pickle.dumps(cfg) >>> cfg2 = pickle.loads(ser) >>> assert cfg == ...
625941dacb5e8a47e48b7d65
def report(user_id=None, type=None, comment=None): <NEW_LINE> <INDENT> params = { 'user_id': user_id, 'type': type, 'comment': comment } <NEW_LINE> result = call('users.report', **params) <NEW_LINE> return parse_response(result)
Reports (submits a complain about) a user. https://vk.com/dev/users.report
625941da4a966d76dd5512d0
def _start_allocator(vm, session, timeout): <NEW_LINE> <INDENT> logging.debug("Starting guest script on guest %s", vm.name) <NEW_LINE> session.sendline("$(command -v python python3 | head -1) " "/tmp/ksm_overcommit_guest.py") <NEW_LINE> try: <NEW_LINE> <INDENT> _ = session.read_until_last_line_matches(["PASS:", "FAIL:"...
Execute guest script and wait until it is initialized. :param vm: VM object. :param session: Remote session to a VM object. :param timeout: Timeout that will be used to verify if guest script started properly.
625941daa4f1c619b28b02f3