code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def validate_answer(self, answer, team): <NEW_LINE> <INDENT> raise NotImplementedError( '%s does not implement validate_answer.' % type(self).__name__)
Validate the answer for the team.
625941db283ffb24f3c55be3
def test(): <NEW_LINE> <INDENT> import doctest <NEW_LINE> doctest.testmod(optionflags=doctest.ELLIPSIS)
Check examples in docstrings. If the actual output matches the expected output, doesn't print anything. Otherwise, it prints an error message showing the mismatch.
625941db5fdd1c0f98dc0519
def getIJSafe(self, *args): <NEW_LINE> <INDENT> return _MEDCouplingCorba.DataArrayDouble_getIJSafe(self, *args)
getIJSafe(self, int tupleId, int compoId) -> double 1
625941db66673b3332b92376
def launch_ec2(ami='ami-d015daa8', instance='t2.micro', key='isce-key', security_group='sg-eee2ef93'): <NEW_LINE> <INDENT> cmd = ('aws ec2 run-instances --image-id {0} --count 1 --instance-type {1}' ' --key-name {2} --security-group-ids {3}' ' --user-data file://run_interferogram.sh').format(ami,instance,key,security_g...
launch an ec2 with interferogram script Reasonable instances: 'c4.4xlarge'
625941dbcb5e8a47e48b7d8b
def _yql_query(yql): <NEW_LINE> <INDENT> url = _YAHOO_BASE_URL.format(urlencode({'q': yql})) <NEW_LINE> _LOGGER.debug("Send request to url: %s", url) <NEW_LINE> try: <NEW_LINE> <INDENT> request = urlopen(url) <NEW_LINE> rawData = request.read() <NEW_LINE> data = json.loads(rawData.decode("utf-8")) <NEW_LINE> _LOGGER.de...
Fetch data from Yahoo! Return a dict if successfull or None.
625941db4f88993c3716c34a
def reinitialize_driver(self): <NEW_LINE> <INDENT> for window in self.windows: <NEW_LINE> <INDENT> if self.main_window != window: <NEW_LINE> <INDENT> self.driver.close() <NEW_LINE> self.driver.switch_to.window(window) <NEW_LINE> self.main_window = window <NEW_LINE> logging.info('Chrome driver has changed to a new tab')...
chrome driver抛出Timeout Exception后,会导致之后的页面页无法正常加载,处理方法为: 1. 关闭当前tab 2. 切换到备用的tab加载剩余界面 3. 打开另一个新的tab作为备用
625941db1b99ca400220ad97
def import_comments(self, entry, comment_nodes): <NEW_LINE> <INDENT> for comment_node in comment_nodes: <NEW_LINE> <INDENT> title = 'Comment #%s' % comment_node.find( '{http://wordpress.org/export/1.0/}comment_id/').text <NEW_LINE> self.write_out(' > %s... ' % title) <NEW_LINE> content = comment_node.find( '{http://wor...
Loops over comments nodes and import then in django.contrib.comments
625941db66656f66f7cbc492
def _getObjectBufferIDs(): <NEW_LINE> <INDENT> ids = [] <NEW_LINE> channel_enable = 'c4d.COMPOSITINGTAG_ENABLECHN{}' <NEW_LINE> channel_id = 'c4d.COMPOSITINGTAG_IDCHN{}' <NEW_LINE> doc = c4d.documents.GetActiveDocument() <NEW_LINE> td = doc.GetTakeData() <NEW_LINE> for obj in core.ObjectIterator(doc.GetFirstObject(...
Private. Get a set of all unique Object Buffer ids set in compositing tags in the scene.
625941db92d797404e304470
def close(self, device): <NEW_LINE> <INDENT> rc = self.lib.pwm_close_device(device) <NEW_LINE> if rc < 0: <NEW_LINE> <INDENT> raise RuntimeError("Error %d closing device %d" % (rc, device))
Close PWM device.
625941db0383005118ecf8c7
def is_sorted(t): <NEW_LINE> <INDENT> if list.sort(t): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False
Checks whether a list is sorted. t: list returns: boolean Expected output: >>> is_sorted([1, 2, 2]) True >>> is_sorted(['b', 'a']) False
625941db5fcc89381b1e19a7
def get_filenames(split): <NEW_LINE> <INDENT> path = os.path.join(FLAGS.raw_timit_dir, "TIMIT", split, "*", "*", "*.WAV") <NEW_LINE> files = sorted(glob.glob(path)) <NEW_LINE> return files
Get all wav filenames from the TIMIT archive.
625941db1b99ca400220ad98
def build_graph(self, hparams, scope=None): <NEW_LINE> <INDENT> utils.print_out("# creating %s graph ..." % self.mode) <NEW_LINE> dtype = tf.float32 <NEW_LINE> with tf.variable_scope(scope or "dynamic_seq2seq", dtype=dtype): <NEW_LINE> <INDENT> encoder_outputs, encoder_state = self._build_encoder(hparams) <NEW_LINE> lo...
Subclass must implement this method. Creates a sequence-to-sequence model with dynamic RNN decoder API. Args: hparams: Hyperparameter configurations. scope: VariableScope for the created subgraph; default "dynamic_seq2seq". Returns: A tuple of the form (logits, loss, final_context_state), where: logits: f...
625941dbfff4ab517eb2f723
def test_topology_serialize(self): <NEW_LINE> <INDENT> prob = problem.rosenbrock(10) <NEW_LINE> alg = algorithm.jde(20) <NEW_LINE> archi = archipelago(alg, prob, 4, 20) <NEW_LINE> top = topology.ring(4) <NEW_LINE> top.set_weight(0, 1, 0.01) <NEW_LINE> top.set_weight(0, 3, 0.03) <NEW_LINE> top.set_weight(1, 2, 0.12) <NE...
Testing whether the weights are retained after serialization of an archipelago
625941db7d847024c06be5a4
def get_params(self): <NEW_LINE> <INDENT> return_params = dict() <NEW_LINE> config_params = self.data.config["params"][self.name] <NEW_LINE> for key, param in config_params.items(): <NEW_LINE> <INDENT> if self.name == "BOOST" and key == "max_depth": <NEW_LINE> <INDENT> return_params["base_estimator"] = [ tree.DecisionT...
Find and process all params from config
625941db8a349b6b435e8458
def _check_sklearn_support(caller_name: str): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> import sklearn <NEW_LINE> <DEDENT> except ImportError as e: <NEW_LINE> <INDENT> raise ImportError( f'{caller_name} requires sklearn. You can install scikit-learn with ' '`pip install scikit-learn`') from e
Raise ImportError with detailed error message if sklearn is not installed. Used by function that might need to import sklearn to have a default Transformer if one is not provided by the user. This is to avoid setting sklearn as a dependency. Parameters ---------- caller_name : str The name of the caller that requ...
625941db71ff763f4b549976
def _get_objects_name(self, handle): <NEW_LINE> <INDENT> objects_names = [ h.key for h in self.handles.input + self.handles.output if h.name == handle.objects and isinstance(h, hdls.SegmentedObjects) ] <NEW_LINE> if len(objects_names) == 0: <NEW_LINE> <INDENT> raise PipelineRunError( 'Invalid object for "%s" in module ...
Determines the name of the segmented objects that are referenced by a `Features` handle. Parameters ---------- handle: tmlib.workflow.jterator.handle.Features output handle with a `objects` attribute, which provides a reference to an input handle Returns ------- str name of the referenced segmented object...
625941db9f2886367277ab71
@pytest.mark.parametrize( "value", [True, False, "false", "true", "TRUE", "FALSE", " FALSE ", " TRUE "] ) <NEW_LINE> def test_values_that_can_be_parsed_as_bool(value): <NEW_LINE> <INDENT> assert can_be_parsed_as_bool(value)
config_file.parse_value.can_be_parsed_as_bool Returns True for values that can be parsed as a bool.
625941db3539df3088e2e630
def colorBased_on_helix(): <NEW_LINE> <INDENT> resetColor() <NEW_LINE> for helix_num in idx: <NEW_LINE> <INDENT> num_staples = len(vstrands[idx[helix_num]]['stap_colors']) <NEW_LINE> for staple_num in range(num_staples): <NEW_LINE> <INDENT> vstrands[idx[helix_num]]['stap_colors'][staple_num][1] = colorCycle(helix_num)
This funtions gives each staple that starts on the same helix, the same color. Dependends ---------- resetColor() findStaples()
625941db627d3e7fe0d69136
def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super().__init__(*args, **kwargs) <NEW_LINE> placeholders = { 'full_name': 'Full Name', 'email': 'Email Address', 'phone_number': 'Phone Number', 'postcode': 'Postal Code', 'town_or_city': 'Town or City', 'street_address1': 'Street Address 1', 'street_address2': ...
add placeholders and classes
625941dbcc0a2c11143dd176
def view(self): <NEW_LINE> <INDENT> recs = self.recs if len(self.recs) <= 5 else self.recs[-5:] <NEW_LINE> for rec in recs: <NEW_LINE> <INDENT> self.printer.print(rec, verbose=False) <NEW_LINE> <DEDENT> if self.recs and has_open_clock(self.last): <NEW_LINE> <INDENT> tdiff = datetime.now() - rec['tstamp'] <NEW_LINE> tdi...
View the last few records.
625941db596a897236089da3
@api_view(['GET']) <NEW_LINE> def get_all_restaurants(request, latitude, longitude): <NEW_LINE> <INDENT> response = [] <NEW_LINE> try: <NEW_LINE> <INDENT> url = GET_ALL_RESTAURANTS_API_URL.format(latitude, longitude) <NEW_LINE> api_response = requests.get(url, headers=FOOD_API_REQUEST_HEADERS) <NEW_LINE> api_response_j...
Returns restaurant details forecast for given city using coordinates :param request: :param latitude: :param longitude: :return: 503 if Zomato API fails :return: 200 successful
625941dbe76e3b2f99f3aaed
def __init__(self, title, data, x_title=None, y_title=None, x_categories=None): <NEW_LINE> <INDENT> self.chart_field = ChartField() <NEW_LINE> self.chart_field.set_type('line') <NEW_LINE> self.title_field = TitleField(text=title) <NEW_LINE> self.series_field = SeriesField() <NEW_LINE> for (n, d) in data: <NEW_LINE> <IN...
:param data: The data is represented in the following form: [ ('First Line', [[x1, y1], [x2, y2], ..., [xn, yn]]), ('Second Line', [[x1, y1], [x2, y2], ..., [xn, yn]]), ... ] where x, y represent the numerical values for the x axis and y axis respe...
625941db30c21e258bdfa784
def ctrl_y(self): <NEW_LINE> <INDENT> self._line.paste_from_clipboard(before=True)
Paste before cursor.
625941db4f88993c3716c34b
def __init__(self, nom: str, image, modDegat, modPrecision): <NEW_LINE> <INDENT> super(Arme, self).__init__(nom, image) <NEW_LINE> self._modDegat = modDegat <NEW_LINE> self._modPrecision = modPrecision
Une arme est un objet avec des attributs et des getter supplémentaire. Les différents Objets sont instancié à l'avance dans `src.Jeu` à partir du fichier `objet.json`. Attributes ---------- _nom : str Le nom de l'objet. _image : str L'image de l'objet. _stackable : int La quantité max de l'objet dans un s...
625941dbbaa26c4b54cb1402
def _pcubicroots(b, c, d): <NEW_LINE> <INDENT> return sum([rr[1] for rr in PolynomialRing(F, 'x')([F(d), F(c), F(b), F(1)]).roots()],0)
Local function returning the number of roots of `x^3 + b*x^2 + c*x + d` modulo `P`, counting multiplicities
625941db91af0d3eaac9bd01
def resample_spline(points, smooth=.001, count=None, degree=3): <NEW_LINE> <INDENT> from scipy.interpolate import splprep, splev <NEW_LINE> if count is None: <NEW_LINE> <INDENT> count = len(points) <NEW_LINE> <DEDENT> points = np.asanyarray(points) <NEW_LINE> closed = np.linalg.norm(points[0] - points[-1]) < tol.merge ...
Resample a path in space, smoothing along a b-spline. Parameters ----------- points : (n, dimension) float Points in space smooth : float Smoothing distance count : int or None Number of samples desired in output degree : int Degree of spline polynomial Returns --------- resampled : (count, dimension) float ...
625941dbbaa26c4b54cb1403
def browser_loge(msg): <NEW_LINE> <INDENT> global last_message_time <NEW_LINE> msg = format_eol(msg) <NEW_LINE> print_to_handle(browser_stderr_handle, msg) <NEW_LINE> browser_stderr_handle.flush() <NEW_LINE> last_message_time = tick()
Prints a message to the browser stderr output stream.
625941db29b78933be1e598d
def optimized_soln(nums): <NEW_LINE> <INDENT> return True if len(set(nums)) < len(nums) else False
More optimized soltuion (O(n)), Space complexity O(1)
625941db82261d6c526ab789
def BxToEz(dim, interpOrder): <NEW_LINE> <INDENT> if dim == 1: <NEW_LINE> <INDENT> return tupleToString((dim,interpOrder,1, 0, 1)) <NEW_LINE> <DEDENT> elif dim == 2: <NEW_LINE> <INDENT> return tupleToString((dim,interpOrder,2, 0,0, 0, dualToPrimal(interpOrder), 0.5)) <NEW_LINE> <DEDENT> elif dim==3: <NEW_LINE> <INDENT>...
pDd to pPd
625941db379a373c97cfae2c
def get_non_arabic(text): <NEW_LINE> <INDENT> prev_wd_nonar = False <NEW_LINE> out = [] <NEW_LINE> intermediate = [] <NEW_LINE> for w in str(text).split(): <NEW_LINE> <INDENT> if non_arabic(w): <NEW_LINE> <INDENT> intermediate.append(w) <NEW_LINE> prev_wd_nonar = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if pr...
Returns spans of non-Arabic unigrams, pipe-separated
625941db26238365f5f0f158
def ravel_multi_index(multi_index, dims, mode='raise', order='C'): <NEW_LINE> <INDENT> pass
ravel_multi_index(multi_index, dims, mode='raise', order='C') Converts a tuple of index arrays into an array of flat indices, applying boundary modes to the multi-index. Parameters ---------- multi_index : tuple of array_like A tuple of integer arrays, one array for each dimension. dim...
625941dbd99f1b3c44c67870
def testPig(self): <NEW_LINE> <INDENT> pig = Pig("Napoleon") <NEW_LINE> self.assertEqual(pig.sound(), "oink!") <NEW_LINE> self.assertFalse(pig.hasWings())
Tests the inhabitants of the farm
625941db8e05c05ec3eea65d
def test__api_files_HSTWFC3_no_versions_ib4v21gcq(self): <NEW_LINE> <INDENT> url = '/api/files/hst-11559-wfc3-ib4v21gcq.json' <NEW_LINE> self._run_json_equal_file(url, 'api_files_HSTWFC3_no_versions_ib4v21gcq.json')
[test_results_api.py] /api/files: HSTWFC3 no versions ib4v21gcq
625941db29b78933be1e598e
def SA_from_h(self, h, method='full'): <NEW_LINE> <INDENT> if method == 'full': <NEW_LINE> <INDENT> return SA_from_h(h, self.D, self.L, self.horizontal, self.sideA, self.sideB, self.sideA_a, self.sideB_a, self.sideA_f, self.sideA_k, self.sideB_f, self.sideB_k) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueEr...
Method to calculate the volume of liquid in a fully defined tank given a specified height `h`. `h` must be under the maximum height. Parameters ---------- h : float Height specified, [m] method : str, optional 'full' (calculated rigorously) ; nothing else is implemented Returns ------- SA : float Surface ...
625941db94891a1f4081bd90
def size_check(): <NEW_LINE> <INDENT> dart_file = os.path.join('samples', 'swarm', 'swarm.dart') <NEW_LINE> out_file = compile_dart2js(dart_file, False) <NEW_LINE> return call([ 'du', '-kh', '--apparent-size', out_file, ]) <NEW_LINE> os.remove(out_file) <NEW_LINE> os.remove(out_file + '.deps') <NEW_LINE> os.remove(out_...
Displays the dart2js size of swarm.
625941db4d74a7450ccd44aa
def no_field_blank(blog_title, blog_body): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if (blog_title == '') or (blog_body == ''): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return False
All fields must have content.
625941dbb830903b967e9bef
def list( self, resource_group_name, custom_headers=None, raw=False, **operation_config): <NEW_LINE> <INDENT> def internal_paging(next_link=None, raw=False): <NEW_LINE> <INDENT> if not next_link: <NEW_LINE> <INDENT> url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vi...
Gets all virtual network gateways by resource group. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config...
625941db1f037a2d8b9464e3
def resize_image_label_with_min_check(im, lb, resize_factor, min_height=None, min_width=None): <NEW_LINE> <INDENT> in_h = tf.cast(tf.shape(im)[-3], dtypes.float32) <NEW_LINE> in_w = tf.cast(tf.shape(im)[-2], dtypes.float32) <NEW_LINE> if min_width: <NEW_LINE> <INDENT> min_width = tf.cast(min_width + 1, dtypes.float32) ...
Resize an (image, label) pair. The label is of same kind of object as the image, i.e. a tensor of 3D or 4D [HxWxC] or [NxHxWxC], where each pixel in the image has a corresponding label. This is usually used for data augmentation in image (semantic) segmentation experiments. The resizing will be checked by min_height/w...
625941dbcdde0d52a9e5331b
def moveZeroes(self, nums): <NEW_LINE> <INDENT> i = 0 <NEW_LINE> for c in range(len(nums)): <NEW_LINE> <INDENT> if nums[i] == 0: <NEW_LINE> <INDENT> nums.pop(i) <NEW_LINE> nums.append(0) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> i+=1
:type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.
625941db73bcbd0ca4b2c35c
def seresnet200b(**kwargs): <NEW_LINE> <INDENT> return get_seresnet(blocks=200, conv1_stride=False, model_name="seresnet200b", **kwargs)
SE-ResNet-200 model with stride at the second convolution in bottleneck block from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. It's an experimental model. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.chain...
625941dba8ecb033257d33b2
def forwards(self, orm): <NEW_LINE> <INDENT> types = ( u"Семинар", u"Лекция", u"Концерт", u"Шоу", u"Театрализованное представление", u"Танцевальное мероприятие", u"Дискотека", u"Турнир", u"Другое", ) <NEW_LINE> for type in types: <NEW_LINE> <INDENT> orm.EventType.objects.create(name=type) <NEW_LINE> <DEDENT> places = (...
Write your forwards methods here.
625941db15baa723493c425d
def changeWorkingDirectory(self, path=None, update=False): <NEW_LINE> <INDENT> from PyQt5.QtWidgets import QFileDialog <NEW_LINE> if path is None: <NEW_LINE> <INDENT> path = QFileDialog.getExistingDirectory( self, "Choose Directory", os.getcwd(), QFileDialog.ShowDirsOnly | QFileDialog.DontUseNativeDialog, ) <NEW_LINE> ...
Updates current working dir to user choice and reads Elk input.
625941db60cbc95b062c682a
def grow(self, cluster, instances=None): <NEW_LINE> <INDENT> body = {"grow": instances} <NEW_LINE> return self._action(cluster, body)
Grow a cluster. :param cluster: The cluster to grow :param instances: List of instances to add
625941db5f7d997b87174d80
def couleur(self,i,j): <NEW_LINE> <INDENT> return self.__mat[i][j].couleur()
Retourne la couleur de la case a la ligne i et colonne j / return : int
625941dbde87d2750b86007b
def media_next_track(self): <NEW_LINE> <INDENT> self._firetv.action('media_next')
Send next track command (results in fast-forward).
625941db0a50d4780f66717b
def eq_(a, b, msg=None): <NEW_LINE> <INDENT> assert a == b, msg or "%r != %r" % (a, b)
Assert a == b, with repr messaging on failure.
625941db287bf620b61d3d48
def test_except_OrderedDict_p(self): <NEW_LINE> <INDENT> a = OrderedDict() <NEW_LINE> a.update({b'bytes should fail': 20}) <NEW_LINE> a.update({b'byteshash': 'Did you work?'}) <NEW_LINE> b = OrderedDict() <NEW_LINE> b.update({'works': 20}) <NEW_LINE> b.update({b'Should fail': 30}) <NEW_LINE> known_exceptions = ( ('n/a'...
Checking for known exceptions in OrderedDict positional
625941db07f4c71912b1176a
def remove_punctuation(docs): <NEW_LINE> <INDENT> print('Removing punctuation:') <NEW_LINE> modified_docs = list() <NEW_LINE> for doc in tqdm(docs): <NEW_LINE> <INDENT> modified_docs.append(list()) <NEW_LINE> for token in doc: <NEW_LINE> <INDENT> if token not in string.punctuation: <NEW_LINE> <INDENT> modified_docs[-1]...
Removes pure punctuation tokens from docs. And retransform each document back to a string. Parameters ---------- docs : list of list of string List of documents to modify. Each document is a list of tokens. Returns ------- modified_docs : list of list of strings List of documents with punctuation removed. Eac...
625941db7d847024c06be5a5
def print_room_items(room): <NEW_LINE> <INDENT> pass <NEW_LINE> present_items = (list_of_items(room["items"])) <NEW_LINE> if not present_items == "": <NEW_LINE> <INDENT> present_items = "There is " + present_items + " here." <NEW_LINE> print (present_items) <NEW_LINE> print ()
This function takes a room as an input and nicely displays a list of items found in this room (followed by a blank line). If there are no items in the room, nothing is printed. See map.py for the definition of a room, and items.py for the definition of an item. This function uses list_of_items() to produce a comma-sepa...
625941db31939e2706e4d14c
def toNumberH1(publicKeys, P1, message, P2, P3): <NEW_LINE> <INDENT> bKeys = _pointsToBytes(publicKeys) <NEW_LINE> bP1 = _pointsToBytes([P1]) <NEW_LINE> bP23 = _pointsToBytes([P2, P3]) <NEW_LINE> plainText = bKeys + bP1 + message + bP23 <NEW_LINE> hashed = HASHF(plainText).digest() <NEW_LINE> return utils.bytes2Int(ha...
Hash the following objects into an integer :param publicKeys: list of Publickeys :param P1: y Tilde :param message: message to be signed in bytes :param P2: Point :param P3: Point :return: integer
625941dbf8510a7c17cf99e4
def test_set_state(self): <NEW_LINE> <INDENT> remote.set_state(master_api, 'test.test', 'set_test') <NEW_LINE> state = hass.states.get('test.test') <NEW_LINE> self.assertIsNotNone(state) <NEW_LINE> self.assertEqual('set_test', state.state) <NEW_LINE> self.assertFalse(remote.set_state(broken_api, 'test.test', 'set_test'...
Test Python API set_state.
625941dbd268445f265b5155
def publish_admin_access_info(self, event): <NEW_LINE> <INDENT> if not self.peers.admin_password: <NEW_LINE> <INDENT> logging.info("Defering setup") <NEW_LINE> event.defer() <NEW_LINE> return <NEW_LINE> <DEDENT> if self._stored.enable_tls: <NEW_LINE> <INDENT> scheme = 'https' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDEN...
Publish creds and endpoint to related charms
625941db442bda511e8be6fb
def arccos(t: Tensor) -> Tensor: <NEW_LINE> <INDENT> return t_ops.arccos(make_tensor(t))
Arccosinus of elements of `Tensor`. Also it is calculate its gradient of operation if tensor's have_grad = True. Arccosinus in radian. Tensor elements should be in [-1, 1]. Arguments: ---------- t : Tensor For example: ----------- y = arcsin(a) + arcsin(b) If a.have_grad = True => a.grad can be calculated by ca...
625941dba17c0f6771cbe336
def ph_distance(ck1, ck2): <NEW_LINE> <INDENT> if ck1.ph is None or ck2.ph is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return math.fabs(ck1.ph - ck2.ph) / 14.0
Compute pH distance. :param cocktail ck1: First cocktail to compare :param cocktail ck2: Second cocktail to compare :returns: The distance score between 0 and 1 or None if cocktails are missing pH
625941dbaad79263cf390d2c
def flipLights(self, n, m): <NEW_LINE> <INDENT> if n == 0 or m == 0: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> if n == 1: <NEW_LINE> <INDENT> return 2 <NEW_LINE> <DEDENT> if n == 2: <NEW_LINE> <INDENT> return 3 if m == 1 else 4 <NEW_LINE> <DEDENT> if m == 1: <NEW_LINE> <INDENT> return 4 <NEW_LINE> <DEDENT> retur...
:type n: int :type m: int :rtype: int
625941dbe1aae11d1e749fa0
def _remove_stop_words(self, tokens): <NEW_LINE> <INDENT> return [token for token in tokens if not token in self.STOP_WORDS]
Removes stop words.
625941dbff9c53063f47c4d9
def standard_lc(lc, stdevs): <NEW_LINE> <INDENT> return np.array([coef*stdev for coef, stdev in zip(lc, stdevs)])
Standardizes the first derivatives in preparation for moment calculation. Parameters ---------- lc : array The first partial derivatives of a single output. stdevs : array The standard deviations for each input Returns ------- slc : array The standardized first-order derivatives
625941db21a7993f00bc7fdb
def parse_movie_detail(self, response): <NEW_LINE> <INDENT> title = response.xpath( "//div[@class='resource-tit']/h2/text()").extract_first().strip('"') <NEW_LINE> movie_id = response.meta['movie_id'] <NEW_LINE> movie_url = response.url <NEW_LINE> name = response.xpath( ".//div[@class='fl-info']/ul/li[1]/strong/text()"...
解析电影内容页
625941dbfb3f5b602dac397d
def _fix_range_type_from_cps(data): <NEW_LINE> <INDENT> return IN_RANGE_TYPE_MAP[data]
Convert range type from CPS
625941db23849d37ff7b3374
def substitute_hand(hand, letter): <NEW_LINE> <INDENT> if letter not in hand: <NEW_LINE> <INDENT> return hand <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> handcopy = hand.copy() <NEW_LINE> x = random.choice(VOWELS+CONSONANTS) <NEW_LINE> while x in hand: <NEW_LINE> <INDENT> x = random.choice(VOWELS+CONSONANTS) <NEW_LIN...
Allow the user to replace all copies of one letter in the hand (chosen by user) with a new letter chosen from the VOWELS and CONSONANTS at random. The new letter should be different from user's choice, and should not be any of the letters already in the hand. If user provide a letter not in the hand, the hand should b...
625941dbd58c6744b4257f45
def testWithdrawProposal(self): <NEW_LINE> <INDENT> old_number_of_proposals = self.profile.student_data.number_of_proposals <NEW_LINE> self.kwargs = { 'sponsor': self.sponsor.link_id, 'program': self.program.program_id, 'user': self.profile.profile_id, 'id': self.proposal.key().id() } <NEW_LINE> request = http.HttpRequ...
Tests that a proposal is successfully withdrawn if possible.
625941db091ae35668667240
def generate_month_constraint(month): <NEW_LINE> <INDENT> return Constraint( time=lambda cell: cell.point == PartialDateTime(month=month))
generate an :class:`iris.Constraint` on the time-axis for a specified month Args: * month (int): the desired month (1..jan, 12..dec) Returns: an :class:`iris.Constraint` on the time-axis
625941db7b180e01f3dc4adf
def normalize_response(response): <NEW_LINE> <INDENT> if isinstance(response, tuple): <NEW_LINE> <INDENT> if len(response) == 3: <NEW_LINE> <INDENT> status, headers, body = response <NEW_LINE> <DEDENT> elif len(response) == 2: <NEW_LINE> <INDENT> status = 200 <NEW_LINE> headers, body = response <NEW_LINE> <DEDENT> elif...
Normalize the given response, by always returning a 3-element tuple (status, headers, body). The body is not "resolved"; it is safe to call this function multiple times on the same response.
625941db67a9b606de4a819e
def get_properties(self): <NEW_LINE> <INDENT> return self._properties
Properties is a dict, because this function is called 2 times. On child-classes and in the render-function. Remove must not raise errors. Add elements must prevent duplicate items. Use `pop` to safe remove element from dict even if it not exists Use `update` to safe add element to dict even if it exists > def get_pr...
625941dbac7a0e7691ed43ae
def downloadSFTP(self): <NEW_LINE> <INDENT> port = 22 <NEW_LINE> transport = None <NEW_LINE> try: <NEW_LINE> <INDENT> transport = paramiko.Transport((self.url.host, port)) <NEW_LINE> <DEDENT> except (socket.timeout,error_perm,error_temp) as e : <NEW_LINE> <INDENT> raise ConnectionException("{}\nConnection error for {}"...
SFTP Download handler
625941dbbf627c535bc134b6
def start_english_words_test(problems): <NEW_LINE> <INDENT> for index, p in enumerate(problems): <NEW_LINE> <INDENT> x = p.split(",") <NEW_LINE> english = x[0] <NEW_LINE> japanese = x[1] <NEW_LINE> print("====第{}問目====".format(index + 1)) <NEW_LINE> print(english) <NEW_LINE> time.sleep(1.0) <NEW_LINE> print(japanese) <...
単語テストを開始する 英単語と日本語訳を表示
625941dbc4546d3d9de72d1d
def test_delete_rows_in_sheet_with_multiple_rows(self): <NEW_LINE> <INDENT> rw = self.sheet.makeRowWrapper(position='toTop') <NEW_LINE> r = rw.makeRow(); r[0] = "one"; rw.addRow(r) <NEW_LINE> r = rw.makeRow(); r[0] = "two"; rw.addRow(r) <NEW_LINE> r = rw.makeRow(); r[0] = "three"; rw.addRow(r) <NEW_LINE> r = rw.makeRow...
Delete Rows from a Sheet with multiple Rows.
625941dbfff4ab517eb2f724
def testClampTheta_clamp_high1(self): <NEW_LINE> <INDENT> pose = [random.uniform(0, 100), random.uniform(0, 100), random.uniform(-math.pi, math.pi)] <NEW_LINE> s = random.uniform(5, 10) <NEW_LINE> w = random.uniform(-math.pi/4, math.pi/4) <NEW_LINE> g = GroundVehicle(pose, s, w) <NEW_LINE> new_theta = g.clampTheta(3.2)...
Tests clamping function when input is above the upper bound
625941dbd18da76e235327c0
def get_build_info(self, build_number, *args): <NEW_LINE> <INDENT> with self.get_handler() as handler: <NEW_LINE> <INDENT> build_info = handler.get_build_info(self.name, build_number) <NEW_LINE> <DEDENT> if not args: <NEW_LINE> <INDENT> return build_info <NEW_LINE> <DEDENT> data = {} <NEW_LINE> if 'commit_hash' in args...
Get build information specified by args from jenkins. If args not provided, return handler.get_build_info(job_name, build_number). :param build_number: jenkins build number. ``str`` :param args: only support : commit_hash, build_result, scm_url. ``str`` :returns: dictionary of information, ``dict`` Example: get_...
625941db091ae35668667241
def test_bails_out_early_on_error(self): <NEW_LINE> <INDENT> resume_calls = [] <NEW_LINE> def maybe_kill(svc): <NEW_LINE> <INDENT> if svc == "keystone": <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> resume_calls.append(svc) <NEW_LINE> return True <NEW_LINE> <DEDENT> <DEDENT> self.servic...
Resume action fails early if there are errors starting a service.
625941dbd53ae8145f87a552
def getHypothesisByPosition(self, position): <NEW_LINE> <INDENT> stackBasicHyps = {} <NEW_LINE> rule = self.rules[position[0]] <NEW_LINE> sitesForRule = rule[1] <NEW_LINE> for idxPos in range(1,len(position)): <NEW_LINE> <INDENT> idxHyp = position[idxPos] <NEW_LINE> site = self.sitesInvolved[idxPos-1] <NEW_LINE> if sit...
Get Hypothesis by given position of cube 1. First dimension stands for rules 2. for each sites involved, if the site is the head node currently pruning, then we should find hyps in lexical stack. @type position: list of number @rtype: NovelDepStrHypothesis
625941dba05bb46b383ecb07
def _DoRepeatedSection(args, context, callback): <NEW_LINE> <INDENT> block = args <NEW_LINE> items = context.PushSection(block.section_name) <NEW_LINE> if items: <NEW_LINE> <INDENT> if not isinstance(items, list): <NEW_LINE> <INDENT> raise EvaluationError('Expected a list; got %s' % type(items)) <NEW_LINE> <DEDENT> las...
{repeated section foo}
625941db8e7ae83300e4b2b5
def get_jid(jid): <NEW_LINE> <INDENT> log.debug("sqlite3 returner <get_jid> called jid: %s", jid) <NEW_LINE> conn = _get_conn(ret=None) <NEW_LINE> cur = conn.cursor() <NEW_LINE> sql = """SELECT id, full_ret FROM salt_returns WHERE jid = :jid""" <NEW_LINE> cur.execute(sql, {"jid": jid}) <NEW_LINE> data = cur.fetchone() ...
Return the information returned from a specified jid
625941dbbd1bec0571d90916
def __init__(self, cam1=[], cam2=[], cam3=[], cam4=[], orientation='horizontal', sizeofcamera=4, subplot_spec=None, sharecolorbar=True, processingsteps=[], plotingredients=['image', 'time','colorbar'], **kwargs): <NEW_LINE> <INDENT> sizeofcamera = 4 <NEW_LINE> N = 4 <NEW_LINE> self.orientation = orientation <NEW_LINE>...
Parameters ---------- cam1, etc... : various a dictionary with keys of 'ccd1', 'ccd2', 'ccd3', 'ccd4' that each contain something that can initialize a sequence orientation : str 'horizontal' = camera 2 is right of camera 1 'vertical' = camera 2 is below camera 1 (not yet implemented) sizeofcamera : ...
625941db92d797404e304472
def setplot(plotdata): <NEW_LINE> <INDENT> from clawpack.visclaw import colormaps <NEW_LINE> plotdata.clearfigures() <NEW_LINE> plotfigure = plotdata.new_plotfigure(name='Stress', figno=0) <NEW_LINE> plotaxes = plotfigure.new_plotaxes() <NEW_LINE> plotaxes.xlimits = 'auto' <NEW_LINE> plotaxes.ylimits = 'auto' <NEW_LINE...
Specify what is to be plotted at each frame. Input: plotdata, an instance of visclaw.data.ClawPlotData. Output: a modified version of plotdata.
625941dbab23a570cc25046c
def _fight_for_lock(sleep_time): <NEW_LINE> <INDENT> nonlocal pool <NEW_LINE> nonlocal count <NEW_LINE> with pool.lock("nidaye"): <NEW_LINE> <INDENT> print("Thread '{thread_name}' get the lock!".format( thread_name=threading.currentThread().name)) <NEW_LINE> time.sleep(sleep_time) <NEW_LINE> print("Thread '{thread_name...
锁争夺
625941db187af65679ca5406
def test_create_game_no_duplicate_airports(self): <NEW_LINE> <INDENT> for i in range(10): <NEW_LINE> <INDENT> user = User.objects.create_user( username='user%s' % i, email='user%s@test.com' % i, password='test' ) <NEW_LINE> game = models.Game.objects.create_game( host=user.player, goals=1, airports=random.randint(10, 5...
Ensure games doesn't have duplicate airports
625941dbfff4ab517eb2f725
def get(self, uid, filters=None): <NEW_LINE> <INDENT> r = requests.get(self.apiurl + "/library-entries", headers=self.header, params=filters) <NEW_LINE> if r.status_code != 200: <NEW_LINE> <INDENT> raise ServerError <NEW_LINE> <DEDENT> jsd = r.json() <NEW_LINE> return jsd
Get a user's list of library entries. While individual entries on this list don't show what type of entry it is, you can use the filters provided by the Kitsu API to only select which ones you want :param uid: str: User ID to get library entries for :param filters: dict: Dictionary of filters for the library :return: ...
625941db1b99ca400220ad9a
def undo(self): <NEW_LINE> <INDENT> self.text_buffer.undo()
Undo the last change in the file. If we can't do anything, ignore.
625941db7d847024c06be5a6
def mock_navitia_query(self, query, q=None): <NEW_LINE> <INDENT> query_str = query <NEW_LINE> if q: <NEW_LINE> <INDENT> query_str += '?' <NEW_LINE> sep = '' <NEW_LINE> for param_name, param_value in q.iteritems(): <NEW_LINE> <INDENT> query_str += sep + param_name + '=' + param_value <NEW_LINE> sep = '&' <NEW_LINE> <DED...
mock the call to navitia wrapper. a file with the query name is looked for in the tests/fixtures dir
625941db71ff763f4b549978
def toGoatLatin(self, s): <NEW_LINE> <INDENT> prog = re.compile(r'^[aeiou]', re.IGNORECASE) <NEW_LINE> index = 1 <NEW_LINE> new_string = list() <NEW_LINE> for word in s.split(): <NEW_LINE> <INDENT> if prog.match(word): <NEW_LINE> <INDENT> word = word + 'ma' + 'a'*index <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> word...
:type S: str :rtype: str
625941db283ffb24f3c55be6
def getCheckeredLine(): <NEW_LINE> <INDENT> firstChar=str( raw_input("Enter First Char: ")) <NEW_LINE> secondChar=str(raw_input("Enter Second Char: ")) <NEW_LINE> print() <NEW_LINE> firstCharNum=ord(firstChar) <NEW_LINE> secondCharNum = ord(secondChar) <NEW_LINE> diff = abs(firstCharNum - secondCharNum) <NEW_LINE> stri...
it prints a string sequence of two characters as many times equal to their diff in ascii values
625941dba8370b7717052b85
def test_failed_gcode_file_throws_IOError(self): <NEW_LINE> <INDENT> mopen = mock_open() <NEW_LINE> mopen.side_effect = IOError <NEW_LINE> with patch('builtins.open', mopen): <NEW_LINE> <INDENT> with self.assertRaises(IOError): <NEW_LINE> <INDENT> utils.load_gcode_file(123)
Failure while loading a gcode file throws an IOError.
625941db796e427e537b08af
def print_ip_table(reachable, unreachable): <NEW_LINE> <INDENT> columns = ['Reachable', 'Unreachable'] <NEW_LINE> values = (reachable, unreachable) <NEW_LINE> return tabulate(values, headers=columns)
Функция ожидает как аргументы два списка: * список доступных IP-адресов * список недоступных IP-адресов
625941dbcb5e8a47e48b7d8e
def _label_to_value(k, obj): <NEW_LINE> <INDENT> return obj._options_dict[k]
Convert a label to a value, given a _Selection object.
625941db711fe17d8254264c
def test_app_url(cookies): <NEW_LINE> <INDENT> result = cookies.bake(extra_context=full_context) <NEW_LINE> urls_file_txt = result.project.join(full_context['app_name'], 'urls.py').read() <NEW_LINE> assert "app_name = \'{}\'".format(full_context['app_name']) in urls_file_txt <NEW_LINE> assert "url(r'^', TemplateView.as...
Test case to assert that the urls.py file has the basic template
625941db4f6381625f114d23
def setPlineMarker(self, wflow, pName): <NEW_LINE> <INDENT> if not wflow['PlineMarkers']: <NEW_LINE> <INDENT> wflow['PlineMarkers'] = [] <NEW_LINE> <DEDENT> wflow['PlineMarkers'].append(pName) <NEW_LINE> if pName not in wflow['RulesToClean']: <NEW_LINE> <INDENT> if pName in self.cleanupPipeNames: <NEW_LINE> <INDENT> wf...
A function intended to mark which is the pipeline currently working on the workflow. It is supposed to be called always as a first function in the pipeline. :param wflow: A MSRuleCleaner workflow representation :param pName: The name of the functional pipeline :return: The workflow object
625941db38b623060ff0b0d5
def __init__(self, data=None, mean=0., stddev=1.): <NEW_LINE> <INDENT> if data is None: <NEW_LINE> <INDENT> if stddev <= 0: <NEW_LINE> <INDENT> raise ValueError("stddev must be a positive value") <NEW_LINE> <DEDENT> self.mean = float(mean) <NEW_LINE> self.stddev = float(stddev) <NEW_LINE> <DEDENT> else: <NEW_LINE> <IND...
normal class constructor
625941dbadb09d7d5db6ca75
def result_cash(self, tax_rate, depreciation_period): <NEW_LINE> <INDENT> data = [ self.revenue, self.investment(), self.merchandise, self.operating_expenses(), self.income_tax(tax_rate, depreciation_period), self.net_cash_flow(tax_rate, depreciation_period), ] <NEW_LINE> index = [ "Revenue (kUSD)", "- Expense, Investm...
Return a DataFrame detailing the cash flow annual result, by year. Assume investment is paid in full in year 0.
625941db711fe17d8254264d
def process_amenities_shp(folder_path): <NEW_LINE> <INDENT> places = [] <NEW_LINE> shp_fpath = os.path.join(folder_path, "managua_nicaragua_osm_amenities") <NEW_LINE> shpreader = shapefile.Reader(shp_fpath) <NEW_LINE> shapes = shpreader.shapes() <NEW_LINE> records = shpreader.records() <NEW_LINE> places = [] <NEW_LINE>...
Transform managua_nicaragua_osm_amenities shapefiles into a data structure similar to places_xml_table
625941db63b5f9789fde73cd
def expand_mapping(mapping, details): <NEW_LINE> <INDENT> keys_to_expand = set(find_tokens(mapping)) & set(details.keys()) <NEW_LINE> for key in keys_to_expand: <NEW_LINE> <INDENT> info = details[key] <NEW_LINE> token = '{' + key + '}' <NEW_LINE> inner_mapping = info.get('mapping', token) <NEW_LINE> mapping = mapping.r...
Split the tokens in a mapping into subtokens, if any are available. Args: mapping (str): The mapping to expand. details (dict[str]): The information about the mapping that will be used to expand it. Returns: str: The expanded mapping.
625941db596a897236089da5
def __tfidf(self, _ngram_range=(1,1) ): <NEW_LINE> <INDENT> tf = TfidfVectorizer(analyzer='word', ngram_range=_ngram_range, min_df = 0, stop_words='english') <NEW_LINE> self.tfidf_matrix = tf.fit_transform(self.corpus) <NEW_LINE> self.features = tf.get_feature_names() <NEW_LINE> self.tfidf_weight = self.tfidf_matrix.to...
:arg: _ngram_range: tuple (min_n, max_n) The lower and upper boundary of the range of n-values for different n-grams to be extracted.
625941db009cb60464c63697
def interpolate(self, t): <NEW_LINE> <INDENT> if self._update_nordsieck: <NEW_LINE> <INDENT> nordsieck_start_index = 21+3*self.problem_info["dimRoot"] - 1 <NEW_LINE> hu, nqu ,nq ,nyh, nqnyh = get_lsod_common() <NEW_LINE> self._nordsieck_array = self._RWORK[nordsieck_start_index:nordsieck_start_index...
Helper method to interpolate the solution at time t using the Nordsieck history array. Wrapper to ODEPACK's subroutine DINTDY.
625941db1f5feb6acb0c4e34
def __init__(self, w, h, title="c64 draw"): <NEW_LINE> <INDENT> pygame.init() <NEW_LINE> self.show = True <NEW_LINE> self.screen = pygame.display.set_mode((w,h)) <NEW_LINE> pygame.display.set_caption(title) <NEW_LINE> self.background = pygame.Surface(self.screen.get_size()) <NEW_LINE> self.background = self.background....
Generates and shows a pygame window. :param w: window width :param h: window height
625941db5510c4643540f6c5
def max_windows(self): <NEW_LINE> <INDENT> self.driver.maximize_window()
最大化浏览器 :return:
625941db01c39578d7e75123
def __get_new_net(self): <NEW_LINE> <INDENT> new_net = self.net[:] <NEW_LINE> tmp = self.__expand(self.net) <NEW_LINE> tmp *= self.weights <NEW_LINE> bf_threshold = np.asarray([np.sum(tmp[:, j*3:j*3+3], axis = 1) for j in range(self.M)]).T <NEW_LINE> new_net[1:,:] = np.where(bf_threshold <= self.T, 0, 1) <NEW_LINE> new...
computes new network. the old one is kept
625941db293b9510aa2c357a
def _getURL(self): <NEW_LINE> <INDENT> return 'http://%s.%s' % (self.key, self.baseurl)
Fetch the url to make requests to. This comprises of api key plus the baseurl.
625941db91af0d3eaac9bd03
def get_text_from_sheet(proposal, field, isheet, registry): <NEW_LINE> <INDENT> retrieved_field = registry.content.get_sheet_field(proposal, IMercatorSubResources, field) <NEW_LINE> field_text = registry.content.get_sheet_field(retrieved_field, isheet, field) <NEW_LINE> return normalize_text(field_text)
Get text from sheetfields and return it.
625941db4f88993c3716c34d
def beta_to_kelvin(beta): <NEW_LINE> <INDENT> kb = 8.6173303E-5 <NEW_LINE> ev = 1.0 / float(beta) <NEW_LINE> T = ev / kb <NEW_LINE> return T
Convert :math:`\beta` to Kelvin. Parameters ---------- beta: float Inversion temperature. Returns ------- T: float Temperature (K).
625941db44b2445a3393237c
def files_with_suffix(base_path: str, suffix: str) -> Iterator[str]: <NEW_LINE> <INDENT> if os.path.isfile(base_path): <NEW_LINE> <INDENT> if base_path.endswith(suffix): <NEW_LINE> <INDENT> yield base_path <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for root, _, files in os.walk(base_path): <NEW_LINE> <INDEN...
Iterates over files in a given directory, providing filenames with a certain suffix. .. versionadded:: 1.2.0 :param base_path: directory to be iterated over :param suffix: filename suffix to look for :returns: iterator that yields the absolute path for files with the given suffix
625941db5166f23b2e1a5441