code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def multiplesOf(n): <NEW_LINE> <INDENT> return map(lambda x: x*n, integers())
3 -> [3,6,9,...]
625941de287bf620b61d3db0
def download_videos(dir_videos, links): <NEW_LINE> <INDENT> ydl_opts = { 'format': 'mp4', 'noplaylist' : True, 'outtmpl': os.path.join(dir_videos, '%(title)s.%(ext)s') } <NEW_LINE> for link in links: <NEW_LINE> <INDENT> if "youtube.com" in link: <NEW_LINE> <INDENT> with youtube_dl.YoutubeDL(ydl_opts) as ydl: <NEW_LINE>...
Download youtube videos from provided list using youtube-dl module. :param dir_videos: Path to directory with downloaded videos. :param links: List with youtube links to download. :return: None.
625941de16aa5153ce3627c7
def test_plot3d(): <NEW_LINE> <INDENT> n_mer, n_long = 6, 11 <NEW_LINE> dphi = np.pi / 1000.0 <NEW_LINE> phi = np.arange(0.0, 2 * np.pi + 0.5 * dphi, dphi) <NEW_LINE> mu = phi * n_mer <NEW_LINE> x = np.cos(mu) * (1 + np.cos(n_long * mu / n_mer) * 0.5) <NEW_LINE> y = np.sin(mu) * (1 + np.cos(n_long * mu / n_mer) * 0.5) ...
Generates a pretty set of lines.
625941debaa26c4b54cb146b
def get(self, timeout=None, **kwargs): <NEW_LINE> <INDENT> return self._sink.get(self.topic, timeout=timeout)
Get data from SINK :param timeout: float (or None) (see Queue.put())
625941de7c178a314d6ef7b3
def build_generators(generator_list, oeis_): <NEW_LINE> <INDENT> for generator in map(lambda g: getattr(generators, g), generator_list): <NEW_LINE> <INDENT> generator_name = generator.__name__ <NEW_LINE> if generator_name.startswith("g"): <NEW_LINE> <INDENT> oeis_.register(generator_name.strip("g"), generator, meta=Tru...
Register all Included Generators.
625941ded486a94d0b98e496
def New(*args, **kargs): <NEW_LINE> <INDENT> obj = itkBoxSpatialObject2.__New_orig__() <NEW_LINE> import itkTemplate <NEW_LINE> itkTemplate.New(obj, *args, **kargs) <NEW_LINE> return obj
New() -> itkBoxSpatialObject2 Create a new object of the class itkBoxSpatialObject2 and set the input and the parameters if some named or non-named arguments are passed to that method. New() tries to assign all the non named parameters to the input of the new objects - the first non named parameter in the first input...
625941debd1bec0571d9097d
def print_usage(): <NEW_LINE> <INDENT> print("Usage: %s [footsteps] [solver]" % sys.argv[0]) <NEW_LINE> print("Footstep plans:") <NEW_LINE> print(" --elliptic Elliptic stairase scenario") <NEW_LINE> print(" --flat Flat floor scenario") <NEW_LINE> print(" --regular Regular stairase scenar...
Tell the user how to call this script.
625941ded10714528d600035
def comp_proj_lyap_res_norm(Z, amat=None, mmat=None, wmat=None, jmat=None, umat=None, vmat=None, Sinv=None): <NEW_LINE> <INDENT> if Z.shape[1] >= Z.shape[0]: <NEW_LINE> <INDENT> raise Warning('TODO: catch cases where Z has more cols than rows') <NEW_LINE> <DEDENT> if Sinv is None: <NEW_LINE> <INDENT> Mlu = spsla.factor...
compute the squared f norm of projected lyap residual res = Pt*[ Ft*ZZt*M + Mt*ZZt*F + W*Wt ]*P
625941de442bda511e8be763
def vstack(tables, join_type='outer', metadata_conflicts='warn'): <NEW_LINE> <INDENT> tables = _get_list_of_tables(tables) <NEW_LINE> if len(tables) == 1: <NEW_LINE> <INDENT> return tables[0] <NEW_LINE> <DEDENT> col_name_map = OrderedDict() <NEW_LINE> out = _vstack(tables, join_type, col_name_map, metadata_conflicts) <...
Stack tables vertically (along rows) A ``join_type`` of 'exact' means that the tables must all have exactly the same column names (though the order can vary). If ``join_type`` is 'inner' then the intersection of common columns will be the output. A value of 'outer' (default) means the output will have the union of al...
625941dea934411ee37519e3
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, WaterLevelSensor): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__
Returns true if both objects are equal
625941de7b25080760e397a6
def test_start_end(self): <NEW_LINE> <INDENT> start = pd.Timestamp('2010-1-3', tz=UTC) <NEW_LINE> end = pd.Timestamp('2010-1-10', tz=UTC) <NEW_LINE> calendar = self.calendar_class(start=start, end=end) <NEW_LINE> self.assertEqual( calendar.first_trading_session, self.TEST_START_END_EXPECTED_FIRST, ) <NEW_LINE> self.ass...
Check TradingCalendar with defined start/end dates.
625941de1b99ca400220ae01
def outputs_iter(self): <NEW_LINE> <INDENT> dirs = list(s.simulation_dir for s in self.series) <NEW_LINE> print(dirs) <NEW_LINE> return ( { 'simulation_dir': d, 'statvar': OPJ(d, 'outputs', 'statvar.dat'), 'data': OPJ(d, 'inputs', 'data'), 'parameters': OPJ(d, 'inputs', 'parameters') } for d in dirs )
Return a :class:`generator` of directories with the path to the ``simulation_dir`` as well as paths to the *statvar.dat* output file, and *data* and *parameters* input files used in the simulation. Yields: :obj:`dict`: dictionary of paths to simulation directory, input, and output files. Example: >>...
625941de6e29344779a6295f
def logtrick_minimizer(minimizer): <NEW_LINE> <INDENT> @wraps(minimizer) <NEW_LINE> def new_minimizer(fun, x0, jac=True, bounds=None, **minimizer_kwargs): <NEW_LINE> <INDENT> if bounds is None: <NEW_LINE> <INDENT> return minimizer(fun, x0, jac=jac, bounds=bounds, **minimizer_kwargs) <NEW_LINE> <DEDENT> logx, expx, grad...
Log-Trick decorator for optimizers. This decorator implements the "log trick" for optimizing positive bounded variables. It will apply this trick for any variables that correspond to a Positive() bound. Examples -------- >>> from scipy.optimize import minimize as sp_min >>> from ..btypes import Bound, Positive Here ...
625941debd1bec0571d9097e
def protocol_ssh(self, protocol, target_type, sub_type): <NEW_LINE> <INDENT> if protocol == 'SCP': <NEW_LINE> <INDENT> self.group_copy(self.ffdc_actions[target_type][sub_type]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.collect_and_copy_ffdc(self.ffdc_actions[target_type][sub_type])
Perform actions using SSH and SCP protocols. Description of argument(s): protocol Protocol to execute. target_type OS Type of remote host. sub_type Group type of commands.
625941de091ae356686672a8
def test_translate_xml_text_entity_unescaped(self): <NEW_LINE> <INDENT> terms = [] <NEW_LINE> source = "Blah&nbsp;blah&nbsp;blah" <NEW_LINE> with self.assertRaises(XMLSyntaxError): <NEW_LINE> <INDENT> xml_translate(terms.append, source)
Test xml_translate() on plain text with HTML entities.
625941ded7e4931a7ee9e26e
def test_borrow_book(self): <NEW_LINE> <INDENT> access_token = UserTestCase.register_login_user(self) <NEW_LINE> response = self.client.post('/api/v2/users/book/1', headers={'content-type': 'application/json', 'Authorization': 'Bearer {}'.format(access_token)}) <NEW_LINE> self.assertEqual(response.status_code, 403) <NE...
Tests whether a logged in user can borrow a book :return:
625941de046cf37aa974d094
def load_data(path): <NEW_LINE> <INDENT> sentences = [] <NEW_LINE> with io.open(path, encoding='utf-8') as f: <NEW_LINE> <INDENT> for line in f: <NEW_LINE> <INDENT> for sent in sent_tokenize(line): <NEW_LINE> <INDENT> sentences.append(sent) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return sentences
loading data: reads the document and divides it into sentences :param path: Path of the file to summarize :return: array of sentences
625941de099cdd3c635f0fa9
def _fit_sum_of_2gaussians(x, x0=(400., 15000., 1., 10.), μ_bounds=(0., 70000.), σ_bounds=(.01, 3000.)): <NEW_LINE> <INDENT> assert len(x) <= 30000, 'Too many values will make this over/underflow.' <NEW_LINE> bounds = (μ_bounds, μ_bounds, σ_bounds, σ_bounds) <NEW_LINE> def nll(args): <NEW_LINE> <INDENT> μ1, μ2, σ1, σ2 ...
:param x: array of observations to fit (should be float64) :param x0: starts (μ1, μ2, σ1, σ2) :param μ_bounds: bounds for the mean (loc) parameters. Will be used for both gaussians. :param σ_bounds: bounds for std parameter (scale). Will be used for both gaussians. :return:
625941de97e22403b379d2ea
def process(self, state): <NEW_LINE> <INDENT> self.db.events.insert_many(state.events) <NEW_LINE> return state
Persists the events in the state to the database.
625941dee8904600ed9f2280
def read_default(self, path=None, file_name='fort.13'): <NEW_LINE> <INDENT> if path == None: <NEW_LINE> <INDENT> path = self.path <NEW_LINE> <DEDENT> return f13.read_default(self, path, file_name)
Read in default nodal value from a ``*.13`` file :type path: string or None :param path: directory containing ``fort.13`` formatted file :param string file_name: ``fort.13`` formatted file name :returns: See :meth:`~polyadcirc.pyADCIRCfort13_management.read_default`
625941de5fcc89381b1e1a10
def backprop(self, do_dx): <NEW_LINE> <INDENT> if self._source is not None: <NEW_LINE> <INDENT> return self._source.backprop(do_dx) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return []
Give this port a backpropagation accumulator to pass on. Typically called by the owning module. Parameters ---------- do_dx : Numpy 2D array Jacobian[i,j] of tree outputs[i] w.r.t. this input port elements[j]. Returns ------- ready : List of modules to backprop next.
625941dede87d2750b8600e4
def user_timesheet(self, user, project=None): <NEW_LINE> <INDENT> logs = TaskLog.objects.filter(task__member__employee=user) <NEW_LINE> if project: <NEW_LINE> <INDENT> logs = logs.filter(task__member__project=project) <NEW_LINE> <DEDENT> return logs
Check user timesheet
625941deb57a9660fec33bd8
def closed_form(n, m): <NEW_LINE> <INDENT> return factorial(n + m) / (factorial(n) * factorial(m))
Finds the number of paths between two points with manhattan distance n + m. The implementation is the closed form solution, n + m choose m.
625941de56b00c62f0f149aa
def __ne__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, MatchTimeseries2018): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self.to_dict() != other.to_dict()
Returns true if both objects are not equal
625941ded53ae8145f87a5b9
def __pow__(self,other): <NEW_LINE> <INDENT> assert type(other) is not Modular or self._modulus == other._modulus, 'Modular.__pow__: Incompatible modulii' <NEW_LINE> if type(other) is Modular: <NEW_LINE> <INDENT> return Modular(self._value ** other._value, self._modulus) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> re...
Overload power operator: *
625941de07d97122c4178be1
def try_create_config_from_repo( repo: str, config: config_mod.Config ) -> config_mod.ClientConfig: <NEW_LINE> <INDENT> path_to_repo = normalize_path_arg(repo) <NEW_LINE> if not path_to_repo or not os.path.isdir(path_to_repo): <NEW_LINE> <INDENT> ex = config.create_no_such_repository_exception(repo) <NEW_LINE> raise ex...
Checks if repo is a path to a Git or Hg repository, and if so, creates an appropriate ClientConfig for that repository. Throws an Exception if repo does not identify a Git or Hg repository.
625941de4c3428357757c675
def test_findNoFailureInExceptionHandler(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> 1 / 0 <NEW_LINE> <DEDENT> except BaseException: <NEW_LINE> <INDENT> self.assertIsNone(failure.Failure._findFailure()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.fail("No exception raised from 1/0!?")
Within an exception handler, _findFailure should return L{None} in case no Failure is associated with the current exception.
625941ded10714528d600036
def test_watching_now_type(self): <NEW_LINE> <INDENT> self.assertIsInstance(self.movie.watching_now[0], User)
Test the type of a Movie's watching now
625941deab23a570cc2504d4
def str_to_int(nums_str): <NEW_LINE> <INDENT> nums = 0 <NEW_LINE> re_math = re.search("(\d+)", nums_str) <NEW_LINE> if re_math: <NEW_LINE> <INDENT> nums = int(re_math.group(1)) <NEW_LINE> if "万" in nums_str: <NEW_LINE> <INDENT> nums *= 10000 <NEW_LINE> <DEDENT> <DEDENT> return nums
char数字 -> int数字
625941deff9c53063f47c541
def palanaeum_context(request): <NEW_LINE> <INDENT> if hasattr(request, 'user') and request.user.is_staff: <NEW_LINE> <INDENT> suggestions = Entry.objects.filter(versions__is_approved=False).distinct().count() <NEW_LINE> suggestions += AudioSource.objects.filter(is_approved=False).count() <NEW_LINE> suggestions += Imag...
Put all useful information into context, like page title.
625941de090684286d50f038
def router(self, recipient, action, **kwargs): <NEW_LINE> <INDENT> responderInstances = {} <NEW_LINE> method = None <NEW_LINE> try: <NEW_LINE> <INDENT> if recipient == '_': <NEW_LINE> <INDENT> responderInstances = { responder: self.responders[responder] for responder in self.responders.keys() if responder != 'app' } <N...
Route a message between elements the framework to a responder Arguments: recipient {str} -- Recipient responder action {[str]} -- Message to pass **kwargs {[mixed]} -- Additional arguments to pass through
625941de8e71fb1e9831daf7
def _fetch_known_hosts(): <NEW_LINE> <INDENT> if env.gateway is None: <NEW_LINE> <INDENT> raise RuntimeError("Tried to _fetch_known_hosts with no env.gateway set!") <NEW_LINE> <DEDENT> known_hosts_file = os.path.join(SSH_DIR, env.gateway) <NEW_LINE> remote_known_hosts_file = "/etc/ssh/ssh_known_hosts" <NEW_LINE> if _kn...
Fetch the system known_hosts file for the selected gateway. This downloads the remote gateway's system known_hosts file and installs it to where Fabric will look for it. If your host keys are out of date, you can simply blow away SSH_DIR and rerun the command. Fabric should re-download the known_hosts file from the ga...
625941de1f5feb6acb0c4e9a
def str_color(self): <NEW_LINE> <INDENT> return self.color.colorize(str(self))
Colorized string for this card.
625941de236d856c2ad44b2e
def in_sphere(self, sphere): <NEW_LINE> <INDENT> return distance3d(sphere.position, self) <= sphere.radius
Returns true if this vector (treated as a position) is contained in the given sphere.
625941debe7bc26dc91cd949
def part1(file): <NEW_LINE> <INDENT> return max(seat_id(boarding_pass) for boarding_pass in file)
O(n) time and space :param file: :return:
625941de01c39578d7e7518b
def __init__( self, char_index: dict, ): <NEW_LINE> <INDENT> self._char_index = char_index
Class initialization. :param char_index: character-index mapping generated by :class:'VocabularyUnit'.
625941dea17c0f6771cbe39f
def _put_named_file(self, path, contents): <NEW_LINE> <INDENT> path = path.lstrip(os.path.sep) <NEW_LINE> with GitFile(os.path.join(self.controldir(), path), 'wb') as f: <NEW_LINE> <INDENT> f.write(contents)
Write a file to the control dir with the given name and contents. :param path: The path to the file, relative to the control dir. :param contents: A string to write to the file.
625941de6fb2d068a760f3f1
def read_fasta(fp): <NEW_LINE> <INDENT> name, seq = None, [] <NEW_LINE> for line in fp: <NEW_LINE> <INDENT> line = line.rstrip() <NEW_LINE> if line.startswith(">"): <NEW_LINE> <INDENT> if name: <NEW_LINE> <INDENT> yield (name, ''.join(seq)) <NEW_LINE> <DEDENT> name, seq = line[1:], [] <NEW_LINE> <DEDENT> else: <NEW_LIN...
https://stackoverflow.com/a/7655072
625941decc0a2c11143dd1e1
def connect_to_db(): <NEW_LINE> <INDENT> cloud_server = 'postgresql+psycopg2://{user}:{pw}@/{db_name}'.format(user=Config.db_user, pw=Config.db_pw, db_name=Config.db_name) <NEW_LINE> cloud_server += '?host=/cloudsql/{db_instance}'.format(db_instance=Config.db_instance) <NEW_LINE> logger.debug('Cloud DB: {}'.format(clou...
Connect to the CloudSQL database, returning both the ORM connection (db) and a cursor (dbsql).
625941de67a9b606de4a8207
def __init__(self, name): <NEW_LINE> <INDENT> Thread.__init__(self) <NEW_LINE> self.name=name
init a thread :param name:
625941de26238365f5f0f1c2
def _precession_matrix_besselian(epoch1, epoch2): <NEW_LINE> <INDENT> from .angles import rotation_matrix <NEW_LINE> t1 = (epoch1 - 1850.0) / 1000.0 <NEW_LINE> t2 = (epoch2 - 1850.0) / 1000.0 <NEW_LINE> dt = t2 - t1 <NEW_LINE> zeta1 = 23035.545 + t1 * 139.720 + 0.060 * t1 * t1 <NEW_LINE> zeta2 = 30.240 - 0.27 * t1 <NEW...
computes the precession matrix from one Besselian epoch to another using Newcomb's method. ``epoch1`` and ``epoch2`` are in besselian year numbers
625941ded18da76e23532829
def get(self): <NEW_LINE> <INDENT> self.response.headers['Content-Type'] = 'application/json' <NEW_LINE> fields = self.request.GET.get('f') <NEW_LINE> timestamp_gt = self.request.GET.get('timestamp_gt') <NEW_LINE> timestamp_lt = self.request.GET.get('timestamp_lt') <NEW_LINE> fields = fields.split(',') if fields else N...
Returns a JSON containing the Trades in the system. Fields returned are filtered by the get parameter 'f'. Trades are filtered by timestamp: 'timestamp_gt': All the trades with a timestamp greater than 'timestamp_lt': All the trades with a timestamp lesser than
625941de498bea3a759b9dfe
def reset_manager(self): <NEW_LINE> <INDENT> return self._execute_action( RESOURCES.manager, '#Manager.Reset', ResetType='GracefulRestart', )
Reset the iDRAC
625941de3c8af77a43ae3af3
def classifyX(p2,mu2,vary2,x,p3,mu3,vary3): <NEW_LINE> <INDENT> pxGivenD1 = np.exp(mogLogProb(p2,mu2,vary2,x)) <NEW_LINE> pxGivenD2 = np.exp(mogLogProb(p3,mu3,vary3,x)) <NEW_LINE> px = pxGivenD1*0.5 + pxGivenD2*0.5 <NEW_LINE> pd1 = pxGivenD1*0.5/px <NEW_LINE> pd2 = pxGivenD2*0.5/px <NEW_LINE> value = np.zeros(pd1.shape...
Calculate the p(x|d=1) and p(x|d=2). Use bayes rule to get p(d=1|x) and p(d=2|x). Assign the value to 1 if p(d=1|x) > p(d=2|x) else assign the value to 2 Return value
625941de92d797404e3044db
def set_defaults(self): <NEW_LINE> <INDENT> for field in self.fields: <NEW_LINE> <INDENT> self.set_default_for_field(field)
Set default values for configuration parameters that will appear in MyData.cfg for fields in the Settings Dialog's Filter tab
625941df377c676e912724f7
def coloring(self, k=None, solver=None, verbose=0): <NEW_LINE> <INDENT> if k is None: <NEW_LINE> <INDENT> for k in range(self.num_points()+1): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.coloring(k) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if k =...
Compute a (weak) `k`-coloring of the hypergraph A weak coloring of a hypergraph `\mathcal H` is an assignment of colors to its vertices such that no set is monochromatic. INPUT: - ``k`` (integer) -- compute a coloring with `k` colors if an integer is provided, otherwise returns an optimal coloring (i.e. with the m...
625941dfd6c5a1020814439d
def cancelar_ordem(self,ordem:Ordem): <NEW_LINE> <INDENT> if ordem.ativo_parte not in self.moedas_negociaveis: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> if self.nome == 'MercadoBitcoin': <NEW_LINE> <INDENT> return MercadoBitcoin().cancelar_ordem(ordem.id) <NEW_LINE> <DEDENT> elif sel...
cancela ordem em aberto a partir do id
625941dfd164cc617578309e
def test_get_versions(self): <NEW_LINE> <INDENT> pid = 1 <NEW_LINE> project = model.Project.get(self.session, pid) <NEW_LINE> exp = [ '3.7.3', '3.7.4', '3.7.4.1', '3.8.0', '3.8.1', '3.9.0', '3.9.0.1', '3.9.0.2', '3.9.0.3', '3.9.0.4', '3.9.0.5', '3.9.0.6' ] <NEW_LINE> obs = backend.SourceforgeBackend.get_ordered_version...
Test the get_versions function of the sourceforge backend.
625941dfeab8aa0e5d26dea9
def mat_keys_from_py(ppc_keys): <NEW_LINE> <INDENT> keys_to_ignore = set(['__globals__', '__header__', '__version__']) <NEW_LINE> return set([k for k in ppc_keys if k not in keys_to_ignore])
If saved case format will be mat file, ignore Python-only dict keys.
625941df2eb69b55b151cc03
def search_and_replace(file_path, search_pattern, replacement, out_path=None, backup=True): <NEW_LINE> <INDENT> with open(file_path, "r") as f: <NEW_LINE> <INDENT> file_data = f.read() <NEW_LINE> <DEDENT> file_data = file_data.replace(search_pattern, replacement) <NEW_LINE> if not out_path: <NEW_LINE> <INDENT> out_path...
Searches for a pattern in a text file and replaces it with the replacement :param file_path: (str) path to the file to search :param search_pattern: (str) pattern to search for :param replacement: (str) string that replaces the search_pattern in the output file :param out_path: (str) pa...
625941dfb830903b967e9c58
def random_forest_classifier(self, trees=200, scoring_metric='roc_auc', hyperparameter_grid=None, randomized_search=True, number_iteration_samples=5): <NEW_LINE> <INDENT> self.validate_classification('Random Forest Classifier') <NEW_LINE> if hyperparameter_grid is None: <NEW_LINE> <INDENT> max_features = hcai_helpers.c...
A light wrapper for Sklearn's random forest classifier that performs randomized search over an overridable default hyperparameter grid. Args: trees (int): number of trees to use if not performing a randomized grid search scoring_metric (str): Any sklearn scoring metric appropriate for classification hyp...
625941df379a373c97cfae96
def main(args): <NEW_LINE> <INDENT> V = int(input()) <NEW_LINE> n = int(input()) <NEW_LINE> arr = list(map(int, input().rstrip().split())) <NEW_LINE> result = introTutorial(V, arr) <NEW_LINE> fptr.write(str(result) + '\n') <NEW_LINE> fptr.close()
This is the main function to be called in test_functions.py. This should emulate the logic in HackerRank's if __name__ == '__main__' logic block and process #args# accordingly. Params ====== args: str A single line string
625941df91af0d3eaac9bd6b
def test_start_dry_loop(self): <NEW_LINE> <INDENT> old_dry = self._adpd.dry <NEW_LINE> old_file = self._adpd.file <NEW_LINE> dir = tempfile.mkdtemp() <NEW_LINE> test_file = os.path.join(dir, os.path.basename(self._test_file)) <NEW_LINE> copy_file(self._test_file, os.path.join(dir, test_file)) <NEW_LINE> self._adpd.set_...
ADP bulk load _start dry loop.
625941dff548e778e58cd8cf
def __init__(self, coeffring, number_of_variables=1): <NEW_LINE> <INDENT> if not isinstance(coeffring, ring.Ring): <NEW_LINE> <INDENT> raise TypeError("%s should not be passed as ring" % coeffring.__class__) <NEW_LINE> <DEDENT> ring.CommutativeRing.__init__(self) <NEW_LINE> self._coefficient_ring = coeffring <NEW_LINE>...
PolynomialRing(coeffring) creates a polynomial ring for univariate polynomials, while PolynomialRing(coeffring, n) creates a polynomial ring for multivariate polynomials.
625941dfe1aae11d1e74a00a
def run(self): <NEW_LINE> <INDENT> self.logger.info("Running MQTT") <NEW_LINE> self.connect() <NEW_LINE> self.alive = True <NEW_LINE> self.processQueue()
Thread start method
625941df1d351010ab855e6b
def cancel_response_callback(self, future: rclpy.task.Future): <NEW_LINE> <INDENT> cancel_response = future.result() <NEW_LINE> if len(cancel_response.goals_canceling) > 0: <NEW_LINE> <INDENT> self.node.get_logger().info('Goal successfully cancelled') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.node.get_logger()...
Cancel response callback Args: future: details returning from the server about the cancel request
625941dfd58c6744b4257fae
def toModel(self): <NEW_LINE> <INDENT> return self._actWidget.model()
Provides Language Component model interface to script. :rtype: language.Act :raises: language.GapError
625941df99cbb53fe6792f36
def cli_docs(): <NEW_LINE> <INDENT> import pydoc <NEW_LINE> pydoc.browse() <NEW_LINE> return 0
CLI option for invoking pydoc.
625941dfa05bb46b383ecb6f
def logger_sessions(self): <NEW_LINE> <INDENT> print('logger sessions ') <NEW_LINE> r=self.scu_get('/datalogging/sessions') <NEW_LINE> return(r)
GET all sessions
625941df6fece00bbac2da92
def test_fold(): <NEW_LINE> <INDENT> X = T.reshape(T.arange(24), (3, 4, 2)) <NEW_LINE> unfoldings = [T.tensor([[0, 1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14, 15], [16, 17, 18, 19, 20, 21, 22, 23]]), T.tensor([[0, 1, 8, 9, 16, 17], [2, 3, 10, 11, 18, 19], [4, 5, 12, 13, 20, 21], [6, 7, 14, 15, 22, 23]]), T.tensor(...
Test for fold
625941dfad47b63b2c50a2ce
def api_get_monthly_host_enrollment_counts(request): <NEW_LINE> <INDENT> rows = [] <NEW_LINE> counters = {} <NEW_LINE> db_session = DBSession() <NEW_LINE> hosts = get_host_list(db_session) <NEW_LINE> for host in hosts: <NEW_LINE> <INDENT> key = (host.created_time.year, host.created_time.month) <NEW_LINE> if key in coun...
GET: http://localhost:5000/api/v1/executive_dashboard/api_get_monthly_host_enrollment_counts
625941dfbe383301e01b57d0
def add_entities(entity_dicts, create_function, batch_size, kind, store_all): <NEW_LINE> <INDENT> batch_count = (len(entity_dicts) + batch_size - 1)/batch_size <NEW_LINE> for i, batch in enumerate(next_n(entity_dicts, batch_size)): <NEW_LINE> <INDENT> entities = [create_function(d) for d in batch] <NEW_LINE> entities =...
Adds the data in entity_dicts to storage as entities using create_function. Uses next_n to group the entity_dicts into batches which get stored using model.db.put(...), after being converted into entities using create_function. Args: entity_dicts: an iterable of dictionaries containing data to be stored create_fu...
625941df1f037a2d8b94654d
def send(self, stream, msg_or_type, content=None, parent=None, ident=None, buffers=None, track=False, header=None, metadata=None): <NEW_LINE> <INDENT> if not isinstance(stream, zmq.Socket): <NEW_LINE> <INDENT> track = False <NEW_LINE> <DEDENT> if isinstance(msg_or_type, (Message, dict)): <NEW_LINE> <INDENT> msg = msg_o...
Build and send a message via stream or socket. The message format used by this function internally is as follows: [ident1,ident2,...,DELIM,HMAC,p_header,p_parent,p_content, buffer1,buffer2,...] The serialize/deserialize methods convert the nested message dict into this format. Parameters ---------- stream : zmq.S...
625941dfb7558d58953c525f
def words(self): <NEW_LINE> <INDENT> return self._word2index.keys()
Words :return:
625941df711fe17d825426b4
def __init__(self, training_data_set, training_data_label, test_set, test_label_set, vocabulary_list, plot=False): <NEW_LINE> <INDENT> self.training_set = training_data_set <NEW_LINE> self.training_label = training_data_label <NEW_LINE> self.test_set = test_set <NEW_LINE> self.test_label = test_label_set <NEW_LINE> sel...
Class initialization. :param training_data_set: training data set (message set) :param training_data_label: each training message's label in training data set :param test_set: data set that contains test messages :param test_label_set: each test message's label in test data set :param vocabulary_list: vocabulary list f...
625941df3d592f4c4ed1d3b6
def func(string): <NEW_LINE> <INDENT> new_string = [] <NEW_LINE> for word in string.split(): <NEW_LINE> <INDENT> new_word = [] <NEW_LINE> for i in range(len(word)): <NEW_LINE> <INDENT> if i % 2 == 0: <NEW_LINE> <INDENT> new_word += word[i].upper() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> new_word += word[i] <NEW_L...
Write a function toWeirdCase (weirdcase in Ruby) that accepts a string, and returns the same string with all even indexed characters in each word upper cased, and all odd indexed characters in each word lower cased. The indexing just explained is zero based, so the zero-ith index is even, therefore that character shoul...
625941df796e427e537b0918
@task() <NEW_LINE> def replicated_bag_mv(bag,bag_dest,s3_bucket="ul-bagit"): <NEW_LINE> <INDENT> data = _api_get(bag) <NEW_LINE> inventory_metadata=None <NEW_LINE> if data['count']>0: <NEW_LINE> <INDENT> inventory_metadata = data['results'][0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception("Bag was not f...
args: bag (bagname or path to bag: bagname or preservation/bagname or shareok/bagname or private/bagename) bag_dest (bagname or shareok/bagname or private/bagename or preservation/bagname)
625941df7b180e01f3dc4b47
def check_ACL(model_name, operation, groups, user, session): <NEW_LINE> <INDENT> conn = Connection() <NEW_LINE> acl_rules = conn.db["base.acl"].find( { "active": True, "model": model_name, "$or": [ {"group_id": {"$in": groups}}, {"group_id": None}]}, session=session) <NEW_LINE> allow_list = [rule[acl_operation_field_ma...
Computes the ACL (Access Control List) Raises AccessError if the given user cannot perform the requested operation on the requested model.
625941dfe76e3b2f99f3ab57
def prepare_data() -> tuple: <NEW_LINE> <INDENT> (train_img, train_label), (test_img, test_label) = mnist.load_data() <NEW_LINE> train_img = train_img / 255. <NEW_LINE> test_img = test_img / 255. <NEW_LINE> return train_img, train_label, test_img, test_label
Function to read and process data
625941dfcc40096d61595c9f
def lookupFromSelf(self, name, loc, mayBeAssignment=False, ignoreDefnOrder=False): <NEW_LINE> <INDENT> defnScope = self <NEW_LINE> while defnScope is not None and not defnScope.isBound(name): <NEW_LINE> <INDENT> defnScope = defnScope.parent <NEW_LINE> <DEDENT> if defnScope is None: <NEW_LINE> <INDENT> if mayBeAssignmen...
Resolves a reference to a symbol from this scope. The symbol may be defined in a parent scope. Returns NameInfo if the symbol is found. For overloaded symbols, there may be several functions in there. If the symbol is not found, a ScopeException is raised. Callers should call `use` if they actually use the symbol.
625941df9b70327d1c4e1126
def _pull_predefined_dockerimages(self): <NEW_LINE> <INDENT> dc = DockerClient() <NEW_LINE> for url in list(self.remote_docker_image_urls.values()): <NEW_LINE> <INDENT> if not FORCE_PULL: <NEW_LINE> <INDENT> if len(dc.images.list(name=url)) > 0: <NEW_LINE> <INDENT> LOG.debug("Image %r present. Skipping pull." % url) <N...
If the package contains URLs to pre-build Docker images, we download them with this method.
625941df4e696a04525c979d
def delTask(self, groupname, taskname): <NEW_LINE> <INDENT> for group in self.groups: <NEW_LINE> <INDENT> if groupname == group.getName(): <NEW_LINE> <INDENT> for task in group: <NEW_LINE> <INDENT> if task == taskname: <NEW_LINE> <INDENT> group.delTask(task) <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDE...
Deletes task from the specified group
625941dfd486a94d0b98e497
def action_json(self, action_name, **kwargs): <NEW_LINE> <INDENT> return json.loads(self.action_data(action_name, **kwargs))
Method calls resource with action_name and returns object obtained via deserialization of output.
625941dfab23a570cc2504d5
def multi(self, keys): <NEW_LINE> <INDENT> self.type = "multi" <NEW_LINE> self.buf.append((self.name, keys)) <NEW_LINE> return self
Performs a multi command, checks for multiple keys in the filter
625941df91af0d3eaac9bd6c
def main(): <NEW_LINE> <INDENT> os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'crutch.settings') <NEW_LINE> try: <NEW_LINE> <INDENT> from django.core.management import execute_from_command_line <NEW_LINE> <DEDENT> except ImportError as exc: <NEW_LINE> <INDENT> raise ImportError( "Couldn't import Django. Are you sure ...
Run administrative tasks.
625941df76d4e153a657ee83
def getDocumentationFiles(runOne=False): <NEW_LINE> <INDENT> from music21 import common <NEW_LINE> music21basedir = common.getRootFilePath() <NEW_LINE> builddocRstDir = os.path.join(music21basedir, 'documentation', 'source') <NEW_LINE> if not os.path.exists(builddocRstDir): <NEW_LINE> <INDENT> raise Music21Exception( "...
returns a list of namedtuples for each module that should be run >>> from music21.test import testDocumentation >>> testDocumentation.getDocumentationFiles() [ModTuple(module='index.rst', fullModulePath='...music21/documentation/autogenerated/index.rst', moduleNoExtension='index', autoGen=False), ..., ModTuple(module=...
625941dfdc8b845886cb5887
def get_values(self): <NEW_LINE> <INDENT> attrs = super().get_values() <NEW_LINE> if '_owner_type' in attrs and attrs['_owner_type'] is not None: <NEW_LINE> <INDENT> attrs['owner_type'] = attrs.pop('_owner_type') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> attrs.pop('_owner_type') <NEW_LINE> <DEDENT> return attrs
Correctly set the ``owner_type`` attribute.
625941df956e5f7376d711bd
def is_uuid(string): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> val = UUID(string, version=4) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return val.hex == string.replace("-", "")
Tells if a given string is a UUID
625941dfbf627c535bc13520
def cli_authentication(self): <NEW_LINE> <INDENT> self.github_user = input("GitHub Username :: ") <NEW_LINE> self.github_email = input("GitHub Email :: ") <NEW_LINE> self.github_key = getpass("GitHub Authorization Token :: ")
cli_authentication Uses getpass module to get user's GitHub credentials from standard input. Used only if auth_method keyword passed to class instance is *not* "env"
625941df9c8ee82313fbbac6
def suite(): <NEW_LINE> <INDENT> loader = unittest.TestLoader() <NEW_LINE> return loader.loadTestsFromTestCase(SearchAPIClientTestCase)
Create and return a test suite with all the tests we need to run.
625941df30c21e258bdfa7f0
def __init__(self, pzlType='Puzzle 15'): <NEW_LINE> <INDENT> self.pzlType = pzlType <NEW_LINE> wx.App.__init__(self)
Initializes the application.
625941df56ac1b37e626451a
def returner(ret): <NEW_LINE> <INDENT> _options = _get_options(ret) <NEW_LINE> user = _options.get('user') <NEW_LINE> device = _options.get('device') <NEW_LINE> token = _options.get('token') <NEW_LINE> title = _options.get('title') <NEW_LINE> priority = _options.get('priority') <NEW_LINE> expire = _options.get('expire'...
Send an PushOver message with the data
625941df94891a1f4081bdfb
def process_result_value(self, value: str, dialect: Dialect) -> rrule: <NEW_LINE> <INDENT> if value is None: <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> return rrulestr(value)
Convert the stored string to an rrule.
625941df5fdd1c0f98dc0585
def calc_horizontal_infrared(sky_cover, dry_bulb, dew_point): <NEW_LINE> <INDENT> SIGMA = 5.6697e-8 <NEW_LINE> db_k = dry_bulb + 273.15 <NEW_LINE> dp_k = dew_point + 273.15 <NEW_LINE> sky_emiss = (0.787 + (0.764 * math.log(dp_k / 273.15))) * (1 + (0.022 * sky_cover) - (0.0035 * (sky_cover ** 2)) + (0.00028 * (sk...
Calculate horizontal infrared radiation intensity. See EnergyPlus Engineering Reference for more information: https://bigladdersoftware.com/epx/docs/8-9/engineering-reference/climate-calculations.html#sky-radiation-modeling Note: [1] Walton, G. N. 1983. Thermal Analysis Research Program Reference Manual. NBSS...
625941dfbd1bec0571d9097f
def simple_append(self, dest, contents, truncate=False): <NEW_LINE> <INDENT> open(self.ospath(dest), truncate and 'w' or 'a').write(contents)
Append CONTENTS to file DEST, optionally truncating it first. DEST is a relpath relative to the WC.
625941df26068e7796caf034
def test_class_len_doc(self): <NEW_LINE> <INDENT> self.assertGreater(len(__import__("models").place. Place.__doc__), 40)
Test the documentation
625941dfd18da76e2353282a
def get_people(self, people, entity="", entityID=""): <NEW_LINE> <INDENT> args = {} <NEW_LINE> args["options"] = people <NEW_LINE> args["method"] = "get_people" <NEW_LINE> args["entity"] = entity <NEW_LINE> args["entityID"] = entityID <NEW_LINE> return self.make_request(args)
Get a list of people.
625941df50485f2cf553d0ec
def test_add_ascii2(self): <NEW_LINE> <INDENT> doc = { 'reference': "nonasciitest", 'importance': 1.0, 'title': 'Schließung Köln' } <NEW_LINE> self.assertRaises(solr.SolrException, self.connection.add, doc) <NEW_LINE> self.connection.commit()
Versuch 2, Dokument mit Nicht-ASCII-Zeichen anzulegen
625941df9c8ee82313fbbac7
def xs_vector(ploop, cocode): <NEW_LINE> <INDENT> return Xsp2_Co1([("x", ploop), ("d", Cocode(cocode))]).as_xsp()
Convert entry of table TYPE_DATA to a Leech lattice vector Calling ``xs_vector(ploop, cocode)``, where ``ploop`` and ``cocode`` are taken from an entry of the list TYPE_DATA, returns the vector in the Leech lattice mod 2 corresponding to that entry in Leech lattice encoding.
625941df091ae356686672aa
def mask_unphysical(self, data): <NEW_LINE> <INDENT> if not self.valid_range: <NEW_LINE> <INDENT> return data <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return np.ma.masked_outside(data, np.min(self.valid_range), np.max(self.valid_range))
Mask data array where values are outside physically valid range.
625941dfbd1bec0571d90980
def finish_vertex(self, u): <NEW_LINE> <INDENT> return
This is invoked on a vertex when it is added to the CLOSED list, which happens after all of its out edges have been examined.
625941dfe1aae11d1e74a00b
def getKeystoneToken(): <NEW_LINE> <INDENT> warnings.warn("Using SciServer.LoginPortal.getKeystoneToken is deprecated. Use SciServer.Authentication.getToken instead.", DeprecationWarning, stacklevel=2); <NEW_LINE> return SciServer.Authentication.getKeystoneToken();
.. warning:: Deprecated. Use Authentication.getToken instead. Returns the users keystone token passed into the python instance with the --ident argument. :return: authentication token (string) :example: token = Authentication.getKeystoneToken() .. seealso:: Authentication.getKeystoneUserWithToken, Authentication.lo...
625941df0fa83653e465730a
def params_args(args=None): <NEW_LINE> <INDENT> params = argparse.ArgumentParser(description='Run distribute model simnet bow.') <NEW_LINE> params.add_argument("--name", type=str, default="simnet_bow", help="The name of current model") <NEW_LINE> params.add_argument("--train_files_path", type=str, default="train_data",...
Parse command line arguments :param args: command line arguments or None (default) :return: dictionary of parameters
625941df30bbd722463cc118
def parse_enterprise_attack_techniques(text): <NEW_LINE> <INDENT> data = ioc_grammars.enterprise_attack_techniques_grammar.searchString(text) <NEW_LINE> return _listify(data)
.
625941dfe8904600ed9f2282
def find_str_in_col(s, col, df): <NEW_LINE> <INDENT> return df[df[col].str.contains(s)]
Finds string 's' in column 'col' of dataframe 'df' Input string in case format (lower, upper) that matches dataframe
625941df009cb60464c63700
def add_stylesheet(self, href, title, alternate="no", media="screen"): <NEW_LINE> <INDENT> self._stylesheets.append((href, title, alternate, media))
Add a stylesheet reference. :param string href: link to stylesheet <URI> :param string title: name of stylesheet :param string alternate: ``'yes'|'no'`` :param string media: ``'all | aureal | braille | embossed | handheld | print | projection | screen | tty | tv'``
625941df009cb60464c63701
def calculate_file_hash_from_path( file_path: Path, hasher: Any, block_size: int = 65536, as_hex_str: bool = True ) -> Union[ByteString, str]: <NEW_LINE> <INDENT> if not file_path.exists() or not file_path.is_file(): <NEW_LINE> <INDENT> raise ValueError(f"{file_path} is not a file or does not exist") <NEW_LINE> <DEDENT...
Calculate a hash digest for a given file path. https://stackoverflow.com/a/21565932/105844 :param file_path: The `pathlib.Path` to a file. :param hasher: The hash function from `hashlib` :param block_size: The size of the block bytes to read from the file, by default 65536 :param as_hex_str: Return the digest as byte...
625941df23849d37ff7b33de
def get_query(query_string, search_fields): <NEW_LINE> <INDENT> query = None <NEW_LINE> terms = normalize_query(query_string) <NEW_LINE> for term in terms: <NEW_LINE> <INDENT> or_query = None <NEW_LINE> for field_name in search_fields: <NEW_LINE> <INDENT> q = Q(**{"%s__icontains" % field_name: term}) <NEW_LINE> if or_q...
Returns a query as a combination of Q objects that query the specified search fields.
625941df29b78933be1e59f8
def __new__(cls, *args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if len(kwargs) > 0: <NEW_LINE> <INDENT> assert os.access(kwargs.get('filename'), os.R_OK) <NEW_LINE> <DEDENT> if len(kwargs) > 1: <NEW_LINE> <INDENT> if not kwargs.get('duration') or not kwargs.get('start_time') or no...
Checks if the file exists and abort instance creation if not. Args: **dict: media file input params Returns: MediaFile: A representation of the media file
625941dfaad79263cf390d97
def _RegisterCollection(self, collection_info): <NEW_LINE> <INDENT> api_name = collection_info.api_name <NEW_LINE> api_version = collection_info.api_version <NEW_LINE> parser = _ResourceParser(collection_info) <NEW_LINE> collection_parsers = (self.parsers_by_collection.setdefault(api_name, {}) .setdefault(api_version, ...
Registers given collection with registry. Args: collection_info: CollectionInfo, description of resource collection. Raises: AmbiguousAPIException: If the API defines a collection that has already been added. AmbiguousResourcePath: If api uses same path for multiple resources.
625941df67a9b606de4a8208