code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def nth(iterable, index): <NEW_LINE> <INDENT> return next(itertools.islice(iterable, index - 1, None))
Return the nth 1-index in an iterable. >>> nth([10, 20, 30], 1) 10
625941cb4f88993c3716c124
def EncodeException(err): <NEW_LINE> <INDENT> return (err.__class__.__name__, err.args)
Encodes an exception into a format that L{MaybeRaise} will recognise. The passed L{err} argument will be formatted as a tuple (exception name, arguments) that the MaybeRaise function will recognise. @type err: GenericError child @param err: usually a child of GenericError (but any exception will be accepted) @rty...
625941cb21a7993f00bc7dac
def update_tags( self, resource_group_name, virtual_network_name, tags=None, custom_headers=None, raw=False, polling=True, **operation_config): <NEW_LINE> <INDENT> raw_result = self._update_tags_initial( resource_group_name=resource_group_name, virtual_network_name=virtual_network_name, tags=tags, custom_headers=custom...
Updates a virtual network tags. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param virtual_network_name: The name of the virtual network. :type virtual_network_name: str :param tags: Resource tags. :type tags: dict[str, str] :param dict custom_headers: headers that will b...
625941cb460517430c394243
def add_to_default_SG( self, conn, volumeInstance, storageSystemName, targetFastPolicyName, volumeName): <NEW_LINE> <INDENT> controllerConfigurationService = ( self.utils.find_controller_configuration_service( conn, storageSystemName)) <NEW_LINE> assocDefaultStorageGroupName = ( self.fast .add_volume_to_default_storage...
For FAST, add volume to default storage group. :param conn: connection info to ECOM :param volumeInstance: the volume instance :param storageSystemName: the storage system name :param targetFastPolicyName: the target FAST policy name :param volumeName: the volume Name :returns: boolean True/False :returns: int, the r...
625941cbd4950a0f3b08c40d
def slice_dataframe_by_columns(df, selected_columns): <NEW_LINE> <INDENT> return slice_dataframe(df, start_row='', end_row='', selected_columns=selected_columns)
Slice by columns only
625941cb71ff763f4b549748
def run(self): <NEW_LINE> <INDENT> with open('src/gvar/__init__.py', 'a') as gvfile: <NEW_LINE> <INDENT> gvfile.write("\n__version__ = '%s'\n" % GVAR_VERSION) <NEW_LINE> <DEDENT> _build_py.run(self)
Append version number to gvar/__init__.py
625941cbb7558d58953c4fd2
def into_buffer(self, buf, offset): <NEW_LINE> <INDENT> self.payload = containerize(exclude_fields(self)) <NEW_LINE> self.parser = MsgEphemerisSbasDepB._parser <NEW_LINE> self.stream_payload.reset(buf, offset) <NEW_LINE> return self.pack_into(buf, offset, self._build_payload)
Produce a framed/packed SBP message into the provided buffer and offset.
625941cb23849d37ff7b314d
def get(self, key): <NEW_LINE> <INDENT> for table in reversed(self._tables): <NEW_LINE> <INDENT> item = table.get(key) <NEW_LINE> if item is not None: <NEW_LINE> <INDENT> return item
Gets item from group of SSTables Args: key (str): Item key Returns: (str, boolean): Item value or None, boolean flag will be true if None value means Tombstone(item has been deleted)
625941cb009cb60464c6346f
def p_sup_aj(self,donnees,attribut,valeur): <NEW_LINE> <INDENT> return 1 - self.p_inf_aj(donnees,attribut,valeur)
p(>a_j) - la probabilité que la valeur de l'attribut A soit suppérieure à a_j. :param list donnees: les données d'apprentissage. :param attribut: l'attribut A. :param valeur: la valeur a_j de l'attribut A. :return: p(a_j)
625941cb01c39578d7e74ef9
def __init__(self): <NEW_LINE> <INDENT> self.displaytext = None <NEW_LINE> self.typeInfo['displaytext'] = 'string' <NEW_LINE> self.success = None <NEW_LINE> self.typeInfo['success'] = 'boolean'
any text associated with the success or failure
625941cb7c178a314d6ef51d
def unflatten(arr): <NEW_LINE> <INDENT> return (int(arr[0]) << 32 | int(arr[1]), reduce(lambda tl, hd: (int(hd), tl), reversed(arr[2:]), ()))
Unflatten a 1d numpy array into a rANS message.
625941cb63d6d428bbe445ad
def twoSum(self, nums, target): <NEW_LINE> <INDENT> dic = {} <NEW_LINE> len1 = len(nums) <NEW_LINE> for i in range(len1): <NEW_LINE> <INDENT> if nums[i] in dic.keys(): <NEW_LINE> <INDENT> dic[nums[i]].append(i) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dic[nums[i]] = [i] <NEW_LINE> <DEDENT> <DEDENT> for i in range(...
:type nums: List[int] :type target: int :rtype: List[int]
625941cb004d5f362079a3f1
def get_amazon_reviews(asin, tld, class_=None, limit=10): <NEW_LINE> <INDENT> review_base_url = "http://www.amazon.{TLD}/product-reviews/" <NEW_LINE> valid_tlds = ['com.au', 'com.br', 'ca', 'cn', 'fr', 'de', 'in', 'it', 'co.jp', 'com.mx', 'nl', 'es', 'co.uk', 'com'] <NEW_LINE> if tld not in valid_tlds: <NEW_LINE> <INDE...
Fetch customer reviews for any Amazon product. Args: asin: Amazon Standard Identification Number. tld: top level domain of the Amazon store for this ASIN. limit: maximum number of reviews to fetch. class_: class of reviews to fetch => +/-/None Returns: A list of reviews. Raises: HTTPError ...
625941cbe5267d203edcdd5c
@task <NEW_LINE> def delete_intents(c, intent_id='', display_name_regex='', project='catbot-test'): <NEW_LINE> <INDENT> if intent_id: <NEW_LINE> <INDENT> repos = IntentRepository(project) <NEW_LINE> repos.delete(intent_id) <NEW_LINE> <DEDENT> elif display_name_regex: <NEW_LINE> <INDENT> repos = IntentRepository(project...
Intent IDを指定してIntentを一件削除します。 Examples: $ pipenv run inv delete-intents --intent-id 1c5e9b44-1822-4b7a-9e97-f00e789c0ff3 $ pipenv run inv delete-intents --display-name-regex '^test_'
625941cbb830903b967e99c9
def get_diagnostic(self, test_id): <NEW_LINE> <INDENT> response = self._get(url=self._url(path='diagnostic/{}'.format(test_id))) <NEW_LINE> if self._verify(response): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return response.json() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDE...
Get a specific diagnostic, by test_id Parameters: test_id (required)
625941cb0a366e3fb873e8d7
def get_jinja_env(): <NEW_LINE> <INDENT> templates_directory = os.path.abspath(os.path.join(__file__, '..', '..', templates)) <NEW_LINE> jinja_environment = jinja2.Environment(loader=jinja2.FileSystemLoader(templates_directory)) <NEW_LINE> return jinja_environment
Returns a Jinja environment with a FileSystemLoader for our templates
625941cb07f4c71912b1153f
def create(width: int, signed: bool, lsb_first: bool = False, reverse_group_width: int = None) -> Tuple[int, ...]: <NEW_LINE> <INDENT> bits = list((1 << n) for n in range(width)) <NEW_LINE> if signed: <NEW_LINE> <INDENT> bits.append(-bits.pop()) <NEW_LINE> <DEDENT> if not lsb_first: <NEW_LINE> <INDENT> bits.reverse() <...
Create bit masks for any integer type. Args: width: Number of bits in the integer. signed: Whether the integer is signed. If so, the most significant bit mask will be negative to provide sign extension when combining. lsb_first: Whether the least significant bit is first. reverse_group_width...
625941cb29b78933be1e576a
def setup(use_petsc=False,outdir='./_output',solver_type='classic'): <NEW_LINE> <INDENT> from clawpack import riemann <NEW_LINE> if use_petsc: <NEW_LINE> <INDENT> import clawpack.petclaw as pyclaw <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> from clawpack import pyclaw <NEW_LINE> <DEDENT> if solver_type=='sharpclaw': ...
Example python script for solving the 2d KPP equations.
625941cb7b25080760e39517
def active_plugin_classes(): <NEW_LINE> <INDENT> return Plugin._plugin_classes
Get the loaded plugin classes
625941cb0a366e3fb873e8d8
def index_files(self, directory): <NEW_LINE> <INDENT> files = os.listdir(directory) <NEW_LINE> for file in files: <NEW_LINE> <INDENT> file = os.path.join(directory, file) <NEW_LINE> if os.path.isfile(file) is True: <NEW_LINE> <INDENT> check = os.path.splitext(file) <NEW_LINE> if check[1] == ".txt": <NEW_LINE> <INDENT> ...
Indexes all text files in a given directory :param directory: The directory where all the files are stored :return: an inverted index
625941cbbaa26c4b54cb11de
def _session_post(self, url, **kwargs): <NEW_LINE> <INDENT> return self.session.post(url, **kwargs)
Make a request using the current session.
625941cbcb5e8a47e48b7b69
def get_number_of_moves(self): <NEW_LINE> <INDENT> return self._number_of_moves
Returns the number of moves since the beginning of game
625941cb0fa83653e4657079
def __init__(self, control): <NEW_LINE> <INDENT> assert isinstance(control, (QtGui.QPlainTextEdit, QtGui.QTextEdit)) <NEW_LINE> self.control = control <NEW_LINE> self.filename = 'ipython.html' <NEW_LINE> self.image_tag = None <NEW_LINE> self.inline_png = None
Creates an HtmlExporter for the given Q(Plain)TextEdit.
625941cba8370b771705295e
def _viterbi_decode(self, feats): <NEW_LINE> <INDENT> T = feats.shape[1] <NEW_LINE> batch_size = feats.shape[0] <NEW_LINE> log_delta = torch.Tensor(batch_size, 1, self.num_labels).fill_(-10000.).to(self.device) <NEW_LINE> log_delta[:, 0, self.start_label_id] = 0 <NEW_LINE> psi = torch.zeros((batch_size, T, self.num_lab...
Max-Product Algorithm or viterbi algorithm, argmax(p(z_0:t|x_0:t))
625941cb7047854f462a14c8
def KeyPressValidation(): <NEW_LINE> <INDENT> conn = sqlite3.connect(DATASET_PATH) <NEW_LINE> rows = conn.execute('select bar_index, data, song_id from BarInfo where mark=\'main\'') <NEW_LINE> note_location_points_list = [-4, 2, 1, 2, 0, 2, 1, 2, -3, 2, 1, 2, 0, 2, 1, 2, -3, 2, 1, 2, 0, 2, 1, 2, -3, 2, 1, 2, 0, 2, 1, 2...
检查按键的位置是否正确
625941cb009cb60464c63470
def get_file_metadata(self, file_id): <NEW_LINE> <INDENT> return self._service.files().get( fileId=file_id, supportsTeamDrives=True).execute()
Gets metadata about the file with the given ID. Args: file_id: the ID of a file (or folder) Returns: a dictionary containing the available metadata about the file, including at least `name`, `kind`, and `mimeType`
625941cbb5575c28eb68e0be
def qryOrders(self): <NEW_LINE> <INDENT> self.getOrders({})
查询委托
625941cb4c3428357757c3e6
def change_membership( self, room: str, src: str, targ: str, membership: str, extra_data: Optional[dict] = None, tok: Optional[str] = None, expect_code: int = 200, expect_errcode: Optional[str] = None, ) -> None: <NEW_LINE> <INDENT> temp_id = self.auth_user_id <NEW_LINE> self.auth_user_id = src <NEW_LINE> path = "/_mat...
Send a membership state event into a room. Args: room: The ID of the room to send to src: The mxid of the event sender targ: The mxid of the event's target. The state key membership: The type of membership event extra_data: Extra information to include in the content of the event tok: The user ...
625941cb82261d6c526ab55d
def readPrimes(maximum = 100): <NEW_LINE> <INDENT> primeFile = open("1000000primes.txt", 'r') <NEW_LINE> for line in primeFile: <NEW_LINE> <INDENT> primesList = line.split() <NEW_LINE> for prime in primesList: <NEW_LINE> <INDENT> if int(prime) >= maximum: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> primes.append(int...
Function that reads primes and adds them to the list of primes
625941cb9c8ee82313fbb833
def _get_applied_time(self, worked_hours, pol_active_after, pol_duration=None): <NEW_LINE> <INDENT> applied_min = (worked_hours * 60) - pol_active_after <NEW_LINE> if applied_min > 0.01: <NEW_LINE> <INDENT> applied_min = (pol_duration != None and applied_min > pol_duration) and pol_duration or applied_min <NEW_LINE> <D...
Returns worked time in hours according to pol_active_after and pol_duration.
625941cb435de62698dfdd0a
def page_view(request, name=None): <NEW_LINE> <INDENT> page = Page.find_with_name(name) <NEW_LINE> series = ( get_object_or_404(Series, name=request.series_name) if hasattr(request, "series_name") else None ) <NEW_LINE> page.set_context({"series": series}, request) <NEW_LINE> return render( request, "about/page.html", ...
Display the page with this name, or the index page.
625941cbcad5886f8bd27097
def _last_lookup(self, entity, method, *args): <NEW_LINE> <INDENT> if any(not s for s in args): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> key = u'{0}.{1}'.format(entity, u'-'.join(unicode(a) for a in args)) <NEW_LINE> if key in self._genre_cache: <NEW_LINE> <INDENT> return self._genre_cache[key] <NEW_LINE> <D...
Get a genre based on the named entity using the callable `method` whose arguments are given in the sequence `args`. The genre lookup is cached based on the entity name and the arguments. Before the lookup, each argument is has some Unicode characters replaced with rough ASCII equivalents in order to return better resul...
625941cb1f037a2d8b9462bc
def helix(rad, angle, turns, eps=1e-12): <NEW_LINE> <INDENT> full_angle = _math.pi / 2 <NEW_LINE> frac_parts = 4 * turns <NEW_LINE> num_parts = int(frac_parts) <NEW_LINE> rem_parts = frac_parts - num_parts <NEW_LINE> if abs(rem_parts) > eps: <NEW_LINE> <INDENT> print('Error: Fractional turns not currently supported.') ...
Returns a wire that is a helix centered at (0.0, 0.0, 0.0) with given radius, helix angle, and number of turns. turns currently must be an integer multiple of 0.25. This used to return an edge. I found a way for an exact edge, but the underlying curve was a spline, and it degenerated over many turns. I replaced it ...
625941cb15fb5d323cde0bcd
def read(fp, format=None, into=None, verify=True, mode='U', **kwargs): <NEW_LINE> <INDENT> if format is None and into is None: <NEW_LINE> <INDENT> raise ValueError("`format` and `into` cannot both be None.") <NEW_LINE> <DEDENT> if format is None: <NEW_LINE> <INDENT> format, fmt_kwargs = sniff(fp, cls=into, mode=mode) <...
Read a supported skbio file format into an instance or a generator. This function is able to reference and execute all *registered* read operations in skbio. Parameters ---------- fp : filepath or filehandle The location to read the given `format` `into`. Filepaths or HTTP/HTTPS URLs are automatically closed ...
625941cb56ac1b37e626428e
def workers_fds_count(self): <NEW_LINE> <INDENT> pass
This doesn't work on FreeBSD
625941cb287bf620b61d3b22
def generate(self, spec): <NEW_LINE> <INDENT> self.gen_file_header() <NEW_LINE> self._writer.write_unindented_line('#pragma once') <NEW_LINE> self.write_empty_line() <NEW_LINE> header_list = [ 'algorithm', 'boost/optional.hpp', 'cstdint', 'string', 'vector', ] <NEW_LINE> header_list.sort() <NEW_LINE> for include in hea...
Generate the C++ header to a stream.
625941cb293b9510aa2c3355
def read_image_batch(image_paths, image_size=None, as_list=False): <NEW_LINE> <INDENT> images = None <NEW_LINE> for i, image_path in enumerate(image_paths): <NEW_LINE> <INDENT> im = load_img(image_path) <NEW_LINE> if image_size is not None: <NEW_LINE> <INDENT> im = im.resize(image_size, Image.LANCZOS) <NEW_LINE> <DEDEN...
Reads image array of np.uint8 and shape (num_images, *image_shape) * image_paths: list of image paths * image_size: if not None, image is resized * as_list: if True, return list of images, else return np.ndarray (default) :return: np.ndarray or list
625941cbbf627c535bc1328d
def get_data_image(self, id=None): <NEW_LINE> <INDENT> self._prepare_imageobj(id, self._dataimage) <NEW_LINE> return self._dataimage
Return the data used by image_data. Parameters ---------- id : int or str, optional The data set. If not given then the default identifier is used, as returned by `get_default_id`. Returns ------- data_img : a `sherpa.image.DataImage` instance The ``y`` attribute contains the ratio values as a 2D NumPy ar...
625941cbaad79263cf390aff
def test_code_cb_24(gb): <NEW_LINE> <INDENT> gb.cpu.register.H = 0b11100010 <NEW_LINE> cycles = op.code_cb_24(gb) <NEW_LINE> assert cycles == 8 <NEW_LINE> assert_registers(gb, H=0b11000100, F=0b00010000) <NEW_LINE> gb.cpu.register.H = 0b00000000 <NEW_LINE> cycles = op.code_cb_24(gb) <NEW_LINE> assert cycles == 8 <NEW_L...
SLA H - Copy H bit 7 to temp, replace H bit 7 w/ zero, rotate H left, copy temp to Carry flag
625941cb0c0af96317bb82a6
def __init__(self, config): <NEW_LINE> <INDENT> self.config = config <NEW_LINE> engine = self.config.get("database", "engine") <NEW_LINE> self.dbhost = self.config.get("database", "host") <NEW_LINE> self.dbuser = config.get(engine, "user") <NEW_LINE> self.dbpassword = config.get(engine, "password") <NEW_LINE> if self.c...
Install if necessary.
625941cb498bea3a759b9b6d
def get_position_mode(self) -> any: <NEW_LINE> <INDENT> response = call_sync(self.request_impl.get_position_mode()) <NEW_LINE> self.refresh_limits(response[1]) <NEW_LINE> return response[0]
Get Current Position Mode (USER_DATA) GET /fapi/v1/positionSide/dual (HMAC SHA256) Get user's position mode (Hedge Mode or One-way Mode ) on EVERY symbol
625941cb2ae34c7f2600d1ef
def compute_partials(self, inputs, partials): <NEW_LINE> <INDENT> for name, options in iteritems(self._output_vars): <NEW_LINE> <INDENT> lhs_name = options['lhs_name'] <NEW_LINE> rhs_name = options['rhs_name'] <NEW_LINE> lhs = inputs[lhs_name] <NEW_LINE> rhs = inputs[rhs_name] <NEW_LINE> if options['normalize']: <NEW_L...
Compute sub-jacobian parts. The model is assumed to be in an unscaled state. Parameters ---------- inputs : Vector unscaled, dimensional input variables read via inputs[key] partials : Jacobian sub-jac components written to partials[output_name, input_name]
625941cb3617ad0b5ed67fb6
def collection_timestamp(self, resource, user_id): <NEW_LINE> <INDENT> raise NotImplementedError
Get the highest timestamp of every records in this resource for this user. :note: This should take deleted records into account. :param resource: the record associated resource :type resource: :class:`cliquet.resource.BaseResource` :param user_id: the owner of the record :type user_id: unicode :returns: the lat...
625941cb6fb2d068a760f15b
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, AckOrResolveResponse): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__
Returns true if both objects are equal
625941cbe1aae11d1e749d75
def testReadEntries(self): <NEW_LINE> <INDENT> timestamp_list = [] <NEW_LINE> pfilter.TimeRangeCache.ResetTimeConstraints() <NEW_LINE> pfilter.TimeRangeCache.SetUpperTimestamp(self.last) <NEW_LINE> pfilter.TimeRangeCache.SetLowerTimestamp(self.first) <NEW_LINE> storage_file = storage.StorageFile(self._test_file, read_o...
Ensure returned EventObjects from the storage are within timebounds.
625941cb925a0f43d2549f35
def stats(data,labels,info=None,verbose=False): <NEW_LINE> <INDENT> return Statistics(data,labels,info=info).make(verbose=verbose)
Make statistics on the given data and labels
625941cbdc8b845886cb55f3
def add_button(self, name, callback=None): <NEW_LINE> <INDENT> if callback: <NEW_LINE> <INDENT> button = urwid.Button(name, callback) <NEW_LINE> <DEDENT> button_map = urwid.AttrWrap(button, 'selectable', 'focus') <NEW_LINE> self.buttons.append(button_map) <NEW_LINE> return button_map
Add a button into the footer of a frame
625941cb23e79379d52ee623
def image_preprocessing(image, train, thread_id=0): <NEW_LINE> <INDENT> height = IMAGE_SIZE <NEW_LINE> width = IMAGE_SIZE <NEW_LINE> if train: <NEW_LINE> <INDENT> image = distort_image(image, height, width, thread_id) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> image = eval_image(image, height, width) <NEW_LINE> <DED...
Decode and preprocess one image for evaluation or training. Args: image: Tensor train: boolean thread_id: integer indicating preprocessing thread Returns: 3-D float Tensor containing an appropriately scaled image Raises: ValueError: if user does not provide bounding box
625941cb283ffb24f3c559c0
@cpython_api([PyObject], rffi.INT_real, error=CANNOT_FAIL) <NEW_LINE> def PyAnySet_Check(space, p): <NEW_LINE> <INDENT> raise NotImplementedError
Return true if p is a set object, a frozenset object, or an instance of a subtype.
625941cb442bda511e8be4d7
def block_bruteforce_attempt(self, counter, max_tries): <NEW_LINE> <INDENT> for connection, count in counter: <NEW_LINE> <INDENT> if count > max_tries: <NEW_LINE> <INDENT> src_ip = connection.split()[0] <NEW_LINE> dst_ip = '.'.join(connection.split()[2].split('.')[:-1]) <NEW_LINE> port = connection.split()[2].split('.'...
Add a firewall rule based on number of new connections defined in '-n' parameter
625941cbfff4ab517eb2f4fb
def test_handle_options_set(self): <NEW_LINE> <INDENT> bc = BaseClient() <NEW_LINE> bc.handle_options(test='a', another=20) <NEW_LINE> self.assertEqual(bc.options['test'], 'a') <NEW_LINE> self.assertEqual(bc.options['another'], 20) <NEW_LINE> self.assertFalse(bc.options['sliceable'])
Can set options
625941cb796e427e537b0684
def save(self, new_setup): <NEW_LINE> <INDENT> SetupValidator().validate(new_setup) <NEW_LINE> self.setup_file.save_setup(new_setup) <NEW_LINE> self.setup_file.rotate_screen(new_setup["screen"]["rotate"]) <NEW_LINE> self._load_user_preferences() <NEW_LINE> self._init_resources()
Save a new setup
625941cb3cc13d1c6d3c7439
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, MissingParameter): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.to_dict() == other.to_dict()
Returns true if both objects are equal
625941cb3eb6a72ae02ec59b
def onMessage(self, client_id: str, message: dict): <NEW_LINE> <INDENT> if message['type'] == 'HelloIWannaPlay': <NEW_LINE> <INDENT> client = Player(client_id=client_id, name=message['user_name']) <NEW_LINE> self.waiting_for_game_players.append(client) <NEW_LINE> if len(self.waiting_for_game_players) >= self.PLAYERS_NE...
Отклик сервера на различные сообщения
625941cbfb3f5b602dac3751
def _test_euclidean_degree(self, **options): <NEW_LINE> <INDENT> tester = self._tester(**options) <NEW_LINE> S = [s for s in tester.some_elements() if not s.is_zero()] <NEW_LINE> min_degree = self.one().euclidean_degree() <NEW_LINE> from sage.rings.all import NN <NEW_LINE> for a in S: <NEW_LINE> <INDENT> tester.assertI...
Test that the assumptions on an Euclidean degree are met. EXAMPLES:: sage: R.<x> = QQ[] sage: R._test_euclidean_degree() .. SEEALSO:: :meth:`_test_quo_rem`
625941cb0383005118ecf6a1
def mmc(a,b): <NEW_LINE> <INDENT> if mdc(a,b) != 0: <NEW_LINE> <INDENT> return (a*b)//(mdc(a,b)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "O mdc deve ser diferente de zero"
Função que cálcula o mmc entre dois números
625941cbeab8aa0e5d26dc16
def start(self): <NEW_LINE> <INDENT> if self.backend == 'bluemuse': <NEW_LINE> <INDENT> address = self.address if self.address is not None else self.name <NEW_LINE> if address is None: <NEW_LINE> <INDENT> subprocess.call( 'start bluemuse://start?streamfirst=true', shell=True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDEN...
Start streaming.
625941cbf548e778e58cd63c
def get_progress(self): <NEW_LINE> <INDENT> progress = [] <NEW_LINE> pb_max = self.count_badges() <NEW_LINE> percentace_consumed_for_inflation = 0 <NEW_LINE> for pb_class, pb_text, pb_value in [ ('progress-bar-success', u'Tulostettu', self.count_printed_badges()), ('progress-bar-danger', u'Mitätöity', self.count_revoke...
We build a progress bar widget that shows percentages of badges in different states. However, if the percentage is really small, the progress segment in the progress bar would get too small. We account for that by "inflating" segments that are too small, and "deflating" segments that are big enough so that taking away ...
625941cb97e22403b379d058
def sample(self): <NEW_LINE> <INDENT> random_array = np.random.rand(self.num_discrete_space) <NEW_LINE> return [int(x) for x in np.floor(np.multiply((self.high - self.low + 1.), random_array) + self.low)]
Returns a array with one sample from each discrete action space
625941cb76e4537e8c351731
def get_queryset(self): <NEW_LINE> <INDENT> queryset = super(ConnectorManager, self).get_queryset() <NEW_LINE> return _fitered_queryset(queryset)
Restrict to only organization's connectors
625941cbbe7bc26dc91cd6c0
def get_input_files_dict(input_files, server_base_url): <NEW_LINE> <INDENT> input_files_dict = {} <NEW_LINE> for input_file in input_files: <NEW_LINE> <INDENT> if server_base_url.endswith('/'): <NEW_LINE> <INDENT> public_url = f'{server_base_url[:-1]}{RUN_CONFIG.get("base_path")}{input_file.public_url}' <NEW_LINE> <DED...
:param input_files: the list of InputFile objects of the job :param server_base_url: the server base url to build the urls from it :return: a dict describing the input files of a job. To be used for generating a public dict describing a job
625941cb32920d7e50b2828e
def chunks(l, n): <NEW_LINE> <INDENT> n = max(1, n) <NEW_LINE> return list(l[i:i+n] for i in range(0, len(l), n))
splits a list of arbitrary lenght in a list of lists of lenght n while keeping the original order :param l: list that is to split :param n: length of returned sublists :return: list of sublists
625941cb8e7ae83300e4b08b
def _run_command(self, job, config): <NEW_LINE> <INDENT> if job.command is None: <NEW_LINE> <INDENT> return None, () <NEW_LINE> <DEDENT> delegate, io_log_gen = self._prepare_io_handling(job, config) <NEW_LINE> extcmd_popen = extcmd.ExternalCommandWithDelegate(delegate) <NEW_LINE> record_path = os.path.join( self._jobs_...
Run the shell command associated with the specified job. :returns: (return_code, record_path) where return_code is the number returned by the exiting child process while record_path is a pathname of a gzipped content readable with :class:`IOLogRecordReader`
625941cb0383005118ecf6a2
def run(self): <NEW_LINE> <INDENT> grouping = Grouping(group_by=lambda x: (x.namespace, x.pattern)) <NEW_LINE> logfile = self.mloginfo.logfile <NEW_LINE> if logfile.start and logfile.end: <NEW_LINE> <INDENT> progress_start = self.mloginfo._datetime_to_epoch(logfile.start) <NEW_LINE> progress_total = self.mloginfo._date...
run this section and print out information.
625941cb60cbc95b062c6602
def boolean(self, chance_of_getting_true: int = 50) -> bool: <NEW_LINE> <INDENT> return self.generator.random.randint(1, 100) <= chance_of_getting_true
Generate a random boolean value based on ``chance_of_getting_true``. :sample: chance_of_getting_true=25 :sample: chance_of_getting_true=50 :sample: chance_of_getting_true=75
625941cb7d43ff24873a2d5f
def __init__(self, host, destdir, username=None, port=22, privatekeyfile=None, connect_timeout=60, missing_host_key_policy=None, passphrase=None): <NEW_LINE> <INDENT> super(SftpTransfer, self).__init__() <NEW_LINE> self._host = host <NEW_LINE> self._destdir = destdir <NEW_LINE> self._username = username <NEW_LINE> if p...
Constructor :param config: configparser.ConfigParser object set with with values set as described in constructor documentation
625941cb090684286d50eda4
def exist_judge(self, search_title: str, torrent_file_name: str) -> int: <NEW_LINE> <INDENT> tag = 0 <NEW_LINE> for test_id in sorted(self.search_list(key=search_title), reverse=True)[:8]: <NEW_LINE> <INDENT> test_title = self.exist_torrent_title(tag=test_id) <NEW_LINE> if torrent_file_name == test_title: <NEW_LINE> <I...
If exist in this site, return the exist torrent's id, else return 0. Warning: if the exist torrent is not same as the pre-reseed torrent, will return -1
625941cb30dc7b7665901a26
def test_exceptions(self): <NEW_LINE> <INDENT> with self.assertRaises(RangeNonsensicalBinOpError): <NEW_LINE> <INDENT> Range(12).__rdivmod__(str) <NEW_LINE> <DEDENT> with self.assertRaises(RangeNonsensicalBinOpValueError): <NEW_LINE> <INDENT> Range(0).__rdivmod__(Range(12)) <NEW_LINE> <DEDENT> with self.assertRaises(Ra...
Test that exceptions are thrown.
625941cb92d797404e304249
def update_all_group(self, side): <NEW_LINE> <INDENT> self.lock.acquire() <NEW_LINE> allied_users = memory.get_players_with(self.db, side=side, recruited=True) <NEW_LINE> memory.update_list(side, 'all', allied_users) <NEW_LINE> self.lock.release() <NEW_LINE> return None
Updates the 'all' group of the active side to reflect actual users. In other words, this prevents members of the opposite team from receiving messages meant for this team. :param user: username of active bot :param side: side of active bot :return: None
625941cbdd821e528d63b268
def do_stats(self, arg): <NEW_LINE> <INDENT> print_color( self.fighter.battle_env.fightChartOne( self.fighter, color=cfg_engine.GAME_DISPLAY_STATS_COLOR_MODE )[0] ) <NEW_LINE> print() <NEW_LINE> self.updateCmdqueue(arg)
View your current stats. Usage: stats [future commands]
625941cb9c8ee82313fbb834
def getColor(self): <NEW_LINE> <INDENT> self.message = lumencor_httpcommand(command ='GET CHMAP', ip=self.ip) <NEW_LINE> colors = self.message['message'].split(' ')[2:] <NEW_LINE> return colors[int(self.laser_id)]
Returns the color of the current laser
625941cb9f2886367277a94d
def test_picture(self): <NEW_LINE> <INDENT> song = Song.objects.create(artist='Van Morrison', album='The Healing Game', title='Sometimes We Cry', genre='Blues', score=0, played=0, family=0, global_score=0, cover='htt://foo.bar/img.png') <NEW_LINE> response = picture(song) <NEW_LINE> attend = {'picture': song.cover} <NE...
Test with a picture with cover
625941cb462c4b4f79d1d790
def rule_NN(self, poiid, destcatid): <NEW_LINE> <INDENT> assert(destcatid in self.catpoidict) <NEW_LINE> assert(len(self.catpoidict[destcatid]) > 0) <NEW_LINE> mindist = -1 <NEW_LINE> destpoi = -1 <NEW_LINE> lng1 = self.poidata[poiid][0] <NEW_LINE> lat1 = self.poidata[poiid][1] <NEW_LINE> for pid in self.catpoidict[des...
Nearest Neighbor Rule to select a POI within a certain category Return the index of target POI
625941cb925a0f43d2549f36
def delete(self, request, *args, **kwargs): <NEW_LINE> <INDENT> if self.get_object().primary: <NEW_LINE> <INDENT> return Response({'detail': _("You can't delete your primary address")}, status=400) <NEW_LINE> <DEDENT> elif EmailAddress.objects.filter(user=request.user).count() <= 1: <NEW_LINE> <INDENT> return Response(...
can't delete if only 1 email address
625941cb96565a6dacc8f78b
def delete_attachment(self, doc, attachment_name, datastore_name=""): <NEW_LINE> <INDENT> if not isinstance(attachment_name, str): <NEW_LINE> <INDENT> raise BadRequest("attachment_name is not a string") <NEW_LINE> <DEDENT> if isinstance(doc, str): <NEW_LINE> <INDENT> doc = self.read_doc(doc_id=doc, datastore_name=datas...
Deletes an attachment from a document.
625941cb50812a4eaa59c3e1
def make_character(info, value, in_set=False): <NEW_LINE> <INDENT> if in_set: <NEW_LINE> <INDENT> return Character(value) <NEW_LINE> <DEDENT> return Character(value, case_flags=info.flags & CASE_FLAGS)
Makes a character literal.
625941cbe1aae11d1e749d76
def get_data(self): <NEW_LINE> <INDENT> return self.__data
暗号化されたデータを取得 :return: 暗号化されたデータ :rtype: unicode
625941cb4f88993c3716c126
def init_errors(flask_app, config): <NEW_LINE> <INDENT> def http_error_handler(error): <NEW_LINE> <INDENT> if not isinstance(error, HTTPException): <NEW_LINE> <INDENT> raise error <NEW_LINE> <DEDENT> mimetype = request.headers.get('accept', '').strip() <NEW_LINE> if hasattr(error, 'description'): <NEW_LINE> <INDENT> de...
Initialize error handlers.
625941cb4f88993c3716c127
def __init__(self, properties=None, element_id=None, api_configuration=None): <NEW_LINE> <INDENT> self._properties = None <NEW_LINE> self._element_id = None <NEW_LINE> self._api_configuration = None <NEW_LINE> self.discriminator = None <NEW_LINE> if properties is not None: <NEW_LINE> <INDENT> self.properties = properti...
BTElementPropertiesParams - a model defined in OpenAPI
625941cb71ff763f4b54974a
def multiplication_1(a, b): <NEW_LINE> <INDENT> if b == 1: <NEW_LINE> <INDENT> return a <NEW_LINE> <DEDENT> return a + multiplication_1(a, b - 1)
Write a function that takes in two numbers and recursively multiplies them together. :param a: :param b: :return:
625941cbbaa26c4b54cb11df
def linear_grid_interp (self, y, g1, g2): <NEW_LINE> <INDENT> if g2[0] != 0.0 or g1[0] != 0.0 or g2[-1] != 1.0 or g1[-1] != 1.0 : <NEW_LINE> <INDENT> print('Improper range for grids') <NEW_LINE> print('grid1[0] = ', g1[0], ' grid1[-1] = ', g1[-1]) <NEW_LINE> print('grid2[0] = ', g2[0], ' grid2[-1] = ', g2[-1]) <NEW_...
Simple Q&D linear interpolator for profiles, y, defined on Plasma State rho grid, g1, to rho grid, g2. Both grids must begin at 0.0 and end at 1.0 and be monotonically increasing.
625941cbbe383301e01b5545
@pytest.mark.parametrize( "ufunc", [ pytest.param( "isreal", marks=pytest.mark.filterwarnings("ignore::FutureWarning") ), "iscomplex", pytest.param("real", marks=pytest.mark.filterwarnings("ignore::FutureWarning")), pytest.param("imag", marks=pytest.mark.filterwarnings("ignore::FutureWarning")), "angle", "fix", "i0", "...
some np.ufuncs doesn't call __array_wrap__ (or __array_ufunc__ starting from numpy v.1.13.0), it should work as below - da.ufunc(dd.Series) => dd.Series - da.ufunc(pd.Series) => np.ndarray - np.ufunc(dd.Series) => np.ndarray - np.ufunc(pd.Series) => np.ndarray
625941cbd58c6744b4257d1f
def amplitude_by_fft(self, data_frame): <NEW_LINE> <INDENT> signal_length = len(data_frame.filtered_signal) <NEW_LINE> normalised_transformed_signal = data_frame.transformed_signal.values / signal_length <NEW_LINE> k = np.arange(signal_length) <NEW_LINE> T = signal_length / self.sampling_frequency <NEW_LINE> f = k / T ...
This methods extract the fft components and sum the ones from lower to upper freq as per :cite:`Kassavetis2015` :param data_frame: the data frame :type data_frame: pandas.DataFrame :return ampl: the ampl :rtype ampl: float :return freq: the freq :rtype freq: float
625941cb8e7ae83300e4b08c
def test_s3_timestamp(self): <NEW_LINE> <INDENT> ts1 = 'Wed, 12 Oct 2009 17:50:00 GMT' <NEW_LINE> self.assertEqual(s3time_as_datetime(ts1), datetime.datetime(2009,10,12,17,50)) <NEW_LINE> ts2 = '2015-07-08T14:50:48.000Z' <NEW_LINE> self.assertEqual(s3time_as_datetime(ts2), datetime.datetime(2015,7,8,14,50,48)) <NEW_LIN...
Verify that both kinds of s3 timestamps are handled properly
625941cb63f4b57ef00011da
def get(self, request, public_key, minified): <NEW_LINE> <INDENT> start_time = time.time() <NEW_LINE> key = None <NEW_LINE> try: <NEW_LINE> <INDENT> key = ProjectKey.objects.get_from_cache(public_key=public_key) <NEW_LINE> <DEDENT> except ProjectKey.DoesNotExist: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_...
Returns a js file that can be integrated into a website
625941cb4a966d76dd5510ce
def MannWhitneyU(x, y, Z_MAX=6.0, axis=0): <NEW_LINE> <INDENT> x = _fixScalar(x) <NEW_LINE> y = _fixScalar(y) <NEW_LINE> if cdms2.isVariable(x) : xatt=x.attributes <NEW_LINE> if cdms2.isVariable(y) : yatt=y.attributes <NEW_LINE> x1,y,weights,axis,ax=__checker(x,y,None,axis) <NEW_LINE> if numpy.ma.isMA(Z_MAX): <NEW_LINE...
This method performs a Mann Whitney U test for unmatched samples on 2 data vectors. :Example: .. doctest:: bigu, smallu, z, prob = MannWhitneyU(data1, data2, Z_MAX=6.0, axis=axisoptions) :param axis: 'x' | 'y' | 'z' | 't' | '(dimension_name)' | 0 | 1 ... | n default value = 0. You can pass the name o...
625941cb7c178a314d6ef51f
@edit_page.route("/note/remove/<request_id>", methods=["POST"]) <NEW_LINE> @login_required <NEW_LINE> def note_remove(request_id: str): <NEW_LINE> <INDENT> user_id = get_user_id() <NEW_LINE> user = User.query.get(user_id) <NEW_LINE> username = user.first_name <NEW_LINE> if "confirm" not in request.form.keys(): <NEW_LIN...
Allows deleting a specific note
625941cbfbf16365ca6f6283
def get_params(): <NEW_LINE> <INDENT> poisson_ratio = okada_pr[10] <NEW_LINE> mu = 30 <NEW_LINE> lmda = (2 * mu * poisson_ratio) / (1 - 2 * poisson_ratio) <NEW_LINE> alpha = (lmda + mu) / (lmda + 2 * mu) <NEW_LINE> x0 = [ okada_pr[0], okada_pr[1], - okada_pr[2] ] <NEW_LINE> depth = okada_pr[2] <NEW_LINE> dip = okada_pr...
okada_pr are the okada parameters that matlab program gives us as the okada fit doesn't work on python
625941cb63d6d428bbe445af
def retourMenu(self): <NEW_LINE> <INDENT> global timerstate <NEW_LINE> timerstate = True <NEW_LINE> self.bouton.destroy() <NEW_LINE> self.tonbou.destroy() <NEW_LINE> self.appui.destroy() <NEW_LINE> self.recommencer.destroy() <NEW_LINE> self.timeText.destroy() <NEW_LINE> self.canvas.delete("all") <NEW_LINE> self.menuing...
Passage au menu d'accueil
625941cb76e4537e8c351732
def test_bifnt_scan_titled(self): <NEW_LINE> <INDENT> teststr = "Epstein, Brian, The Fifth Beatle" <NEW_LINE> output = self.scan(teststr) <NEW_LINE> anticipated = {'TOKEN_TAG_LIST': ['lastnames', 'nonlastnames', 'titles', 'raw'], 'lastnames': ['Epstein'], 'nonlastnames': ['Brian'], 'titles': ['The Fifth Beatle'], 'raw'...
BibIndexAuthorTokenizer - scanning title-bearing: last, first, title
625941cbe64d504609d748ff
def format(self,record): <NEW_LINE> <INDENT> self._formattime(record) <NEW_LINE> jsondata = self._getjsondata(record) <NEW_LINE> formattedjson = dumps(jsondata, cls=self.customjson) <NEW_LINE> return formattedjson
overridden from the ancestor class to take a log record and output a JSON formatted string. Args: record : log record to output to JSON log Returns: A JSON formatted string
625941cbe5267d203edcdd5e
def get_av_packages(self): <NEW_LINE> <INDENT> return self._structures_list(StructPackage, 'packages')
Returns a list of antivirus agent download URLs for various platforms. :return: list of dictionaries with av packages data :raises: :class:`AVDeskError` on failure Example:: av_packages = station.get_av_packages() An extract from returned list:: [ { 'url': 'http://localhost/download/dow...
625941cb8c0ade5d55d3ea7a
def load_cifar(data_name): <NEW_LINE> <INDENT> if data_name == 'cifar100': <NEW_LINE> <INDENT> (X_train, y_train), (X_test, y_test) = cifar100.load_data() <NEW_LINE> n_classes = 100 <NEW_LINE> <DEDENT> elif data_name == 'cifar10': <NEW_LINE> <INDENT> (X_train, y_train), (X_test, y_test) = cifar10.load_data() <NEW_LINE>...
useage: X_train, X_test, Y_train, Y_test, y_train, y_test, data_info = load_cifar(data_name) [n_classes, img_rows, img_cols, img_channels] = data_info
625941cb4e696a04525c950b
def get_models(_, response, app): <NEW_LINE> <INDENT> root = get_slumber_root() <NEW_LINE> response['models'] = dict([(n, root + m.path) for n, m in app.models.items()])
Return the models that comprise an application.
625941cbff9c53063f47c2b3
def get_gtk_keymap(ignore_keys=[None, "VoidSymbol", "0xffffff"]): <NEW_LINE> <INDENT> from xpra.gtk_common.gtk_util import get_default_keymap, import_gdk, is_gtk3 <NEW_LINE> gdk = import_gdk() <NEW_LINE> keymap = get_default_keymap() <NEW_LINE> keycodes=[] <NEW_LINE> for i in range(0, 2**8): <NEW_LINE> <INDENT> entries...
Augment the keymap we get from gtk.gdk.keymap_get_default() by adding the keyval_name. We can also ignore some keys
625941cb1b99ca400220ab71
def listAssets(params): <NEW_LINE> <INDENT> _cloudApiOnly('listAssets') <NEW_LINE> assets = {'assets': []} <NEW_LINE> if 'parent' in params and _cloud_api_utils.is_asset_root(params['parent']): <NEW_LINE> <INDENT> params['parent'] = re.sub('/assets/?$', '', params['parent']) <NEW_LINE> cloud_resource_root = _get_cloud_...
Returns the assets in a folder.
625941cb099cdd3c635f0d1a
def test_get_change(self): <NEW_LINE> <INDENT> self.client.force_login(self.admin) <NEW_LINE> response = self.client.get(reverse('admin:django_pain_bankaccount_change', args=(self.account.pk,))) <NEW_LINE> self.assertContains(response, '123456/0300') <NEW_LINE> self.assertContains(response, '<div class="readonly">EUR</...
Test GET request on bank account change.
625941cbd53ae8145f87a330
def _search_tokens(self, song_name): <NEW_LINE> <INDENT> logger.debug("Searching [{}] in the cache at [{}]".format(song_name, self.dir)) <NEW_LINE> song_name = remove_stopwords(remove_multiple_spaces(song_name).lower()) <NEW_LINE> song_name = remove_punct(song_name) <NEW_LINE> tokens1 = song_name.split() <NEW_LINE> cac...
Search song in the cache based on simple each word matching.
625941cb8e05c05ec3eea434
def _check_input(self) : <NEW_LINE> <INDENT> if self.noise is None : <NEW_LINE> <INDENT> if any(self.data < 0) : <NEW_LINE> <INDENT> self._error("No Noise given, and some pixels have negative data value") <NEW_LINE> <DEDENT> self.noise == sqrt(self.data) <NEW_LINE> <DEDENT> self.npix = len(self.xin) <NEW_LINE> if self....
Check consistency of input data
625941cbec188e330fd5a85f
def log_likelihood_pred(self, pred_dict, exclude_observables=None, delta=False): <NEW_LINE> <INDENT> ll = 0. <NEW_LINE> for measurement in self.get_measurements: <NEW_LINE> <INDENT> m_obj = flavio.Measurement[measurement] <NEW_LINE> m_obs = set(m_obj.all_parameters) <NEW_LINE> exclude_observables = set(exclude_observab...
Return the logarithm of the likelihood function as a function of a dictionary of observable predictions `pred_dict`
625941cb5f7d997b87174b57