code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def calculate_next_q_value_memory(self, next_state: torch.Tensor) -> torch.Tensor: <NEW_LINE> <INDENT> next_q_values = self.model(next_state) <NEW_LINE> return torch.max(next_q_values, 1)[0]
Method that calculates the next Q value given the next state. Used to calculate the loss when the memory is in used. This method handle a list of states. :param next_state: list of states of the environment after acting :return: estimation of the next state q value
625941bf96565a6dacc8f619
def _negotiate_SOCKS5(self, dest_addr, dest_port): <NEW_LINE> <INDENT> proxy_type, addr, port, rdns, username, password = self.proxy <NEW_LINE> if username and password: <NEW_LINE> <INDENT> self.sendall(b"\x05\x02\x00\x02") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.sendall(b"\x05\x01\x00") <NEW_LINE> <DEDENT> ...
Negotiates a connection through a SOCKS5 server.
625941bfd18da76e23532420
def mifareCloneCard(self): <NEW_LINE> <INDENT> cmd = '%s%s\x00\x00\x00' %(chr(self.CLA_MIFARE), chr(R502SpyLibrary.INS_MIFARE_CLONE)) <NEW_LINE> rsp = self.__scInterface.transmit(cmd) <NEW_LINE> if rsp[-2 : ] == '\x90\x00': <NEW_LINE> <INDENT> return True, rsp[ : -2] <NEW_LINE> <DEDENT> return False, rsp[0]
@brief: @return: True and response data / False and the error code.
625941bf67a9b606de4a7e09
def _do_insert(self, sql, timestamp, value): <NEW_LINE> <INDENT> timestamp_utc = _timestamp_to_utc(timestamp) <NEW_LINE> self._cursor.execute(sql, (timestamp_utc.strftime(_TIMESTAMP_FORMAT), value)) <NEW_LINE> self._connection.commit()
Executes and commits a SQL insert command. Args: sql: SQL query string for the insert command. timestamp: datetime instance representing the record timestamp. value: Value to insert for the record.
625941bf24f1403a92600ab6
def load_config(self, sep="\t"): <NEW_LINE> <INDENT> f = open(self.path) <NEW_LINE> lines = f.readlines() <NEW_LINE> self.load_summary(lines[0].strip(), sep) <NEW_LINE> total_features = self.get_total_features() <NEW_LINE> for i in range(total_features): <NEW_LINE> <INDENT> self.load_feature(lines[i + 1].strip(), sep) ...
load the config file to get data set description :param sep: separator to parse each line in the file :return: configuration of the data set
625941bfbe7bc26dc91cd552
def loadFiringRates(exp,area,typeunit): <NEW_LINE> <INDENT> filename = join(ROOT, 'data', 'Polished', exp, 'neuronDB.h5') <NEW_LINE> f = h5py.File(filename, 'r') <NEW_LINE> if typeunit == 'mua': <NEW_LINE> <INDENT> x = f['/' + area + '/mua/data/count'][:, 0:1440] <NEW_LINE> <DEDENT> if typeunit == 'su': <NEW_LINE> <IND...
Load firing rates matrix of a specific combination of experiment (Control, Experimental, Naive), area (v1, ll) and type of unit (mua,su,all). Returns a matrix of the form (n.of stimuli, n.of neurons)
625941bf10dbd63aa1bd2af3
def get_params_from_yaml(self, keyname): <NEW_LINE> <INDENT> return { self.PARAM_GROUP : LocalState.get_group(keyname), self.PARAM_KEYNAME : keyname, self.PARAM_PROJECT : LocalState.get_project(keyname), self.PARAM_SECRETS : LocalState.get_client_secrets_location(keyname), self.PARAM_VERBOSE : False }
Searches through the locations.yaml file to build a dict containing the parameters necessary to interact with Google Compute Engine. Args: keyname: A str that uniquely identifies this AppScale deployment. Returns: A dict containing all of the credentials necessary to interact with Google Compute Engine.
625941bfcb5e8a47e48b79fb
def uniquify(conc_lines): <NEW_LINE> <INDENT> from collections import OrderedDict <NEW_LINE> unique_lines = [] <NEW_LINE> checking = [] <NEW_LINE> for index, (_, speakr, start, middle, end) in enumerate(conc_lines): <NEW_LINE> <INDENT> joined = ' '.join([speakr, start, 'MIDDLEHERE:', middle, ':MIDDLEHERE', end]) <NEW_L...
get unique concordance lines
625941bf596a897236089a11
def judgeCjdltOpen(self): <NEW_LINE> <INDENT> list=[2,4,7] <NEW_LINE> if self.todayWeek in list: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False
二、四、日是超级大乐透开机号创建日期
625941bf4c3428357757c277
def _prepare_cmd(self): <NEW_LINE> <INDENT> return [ "mke2fs -q -F -O journal_dev -b 4096 %s" % self.comp.dev ]
Return target journal device format command line.
625941bf566aa707497f44ba
def id_rem2(a, b, details=2): <NEW_LINE> <INDENT> return 'Polynome([[%r, 1], [%r, 0]], details=%s)**2' % (a, -b, details)
Construit un Polynome de la forme (ax-b)^2 Renvoie une chaine
625941bf796e427e537b0511
def _update_fields_values(self, values, fields): <NEW_LINE> <INDENT> for field, value in zip(fields, values): <NEW_LINE> <INDENT> field.update_value(value, self.lastwritetime)
update the field values once data successfully written
625941bf956e5f7376d70dbc
def process_performance_results( program_objects, first_date, last_date, results_type, exercise_property, property_value): <NEW_LINE> <INDENT> first = first_date.toPyDate().strftime("%Y-%m-%d") <NEW_LINE> last = last_date.toPyDate().strftime("%Y-%m-%d") <NEW_LINE> result_dates = [] <NEW_LINE> result_values = [] <NEW_LI...
Return a performance results data set that can be plotted. This function iterates over the user's Program record objects to find all Programs with constituent Workout period began dates between the first_date and last_date args. Calls each applicable Program's performance_results method with the results_type and exerc...
625941bf44b2445a33931fe5
def brown(num_points=1024, b_minus2=1.0, fs=1.0): <NEW_LINE> <INDENT> return (1.0/float(fs))*numpy.cumsum( white(num_points, b0=b_minus2*(4.0*math.pi*math.pi), fs=fs))
Brownian or random walk (diffusion) noise with 1/f^2 PSD Not really a color... rather Brownian or random-walk. Obtained by integrating white-noise. Parameters ---------- num_points: int, optional number of samples b_minus2: float, optional desired power-spectral density is b2*f^-2 fs: float, optional samp...
625941bfbde94217f3682d41
def testValidateFound(self): <NEW_LINE> <INDENT> event = { 'basePath': { 'p': 'value' } } <NEW_LINE> sut = APIGateway(mockLoggerFactory, event) <NEW_LINE> validator = MagicMock() <NEW_LINE> sut.getParameter('param', 'basePath', 'p', False, validator) <NEW_LINE> validator.assert_called_once_with('value')
APIGateway.getParameter() should call the validator if passed [with found param]
625941bf4e696a04525c939a
def patch(self, url, **kwargs): <NEW_LINE> <INDENT> return self.request('PATCH', url, **kwargs)
Sends a PATCH request and returns a :class:`HttpResponse` object. :params url: url for the new :class:`HttpRequest` object. :param \*\*kwargs: Optional arguments for the :meth:`request` method.
625941bf4d74a7450ccd4111
def delete_vcard(self, href, etag): <NEW_LINE> <INDENT> self._check_write_support() <NEW_LINE> remotepath = str(self.url.base + href) <NEW_LINE> headers = self.headers <NEW_LINE> headers['content-type'] = 'text/vcard' <NEW_LINE> if etag is not None: <NEW_LINE> <INDENT> headers['If-Match'] = etag <NEW_LINE> <DEDENT> res...
deletes vcard from server deletes the resource at href if etag matches, if etag=None delete anyway :param href: href of card to be deleted :type href: str() :param etag: etag of that card, if None card is always deleted :type href: str() :returns: nothing
625941bf4a966d76dd550f5b
def should_include_node(ctx, directives): <NEW_LINE> <INDENT> if directives: <NEW_LINE> <INDENT> skip_ast = None <NEW_LINE> for directive in directives: <NEW_LINE> <INDENT> if directive.name.value == GraphQLSkipDirective.name: <NEW_LINE> <INDENT> skip_ast = directive <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if ski...
Determines if a field should be included based on the @include and @skip directives, where @skip has higher precidence than @include.
625941bf0383005118ecf532
def gauss(x): <NEW_LINE> <INDENT> c = 1/(np.sqrt(2*np.pi)) <NEW_LINE> gauss = c*np.exp(-x**2/2) <NEW_LINE> return gauss
Returns the Gaussian function dependent on the input float
625941bf3346ee7daa2b2cb8
def handle_nulls(s, drop_na=False, fill_value=0): <NEW_LINE> <INDENT> if drop_na: <NEW_LINE> <INDENT> return s.dropna() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return fill_nulls(s, fill_value)
Handles null values in a series. Parameters: ----------- s: pandas.Series Series to evaluate drop_na: bool, default False If true, null values are dropped. If false nulls are replaced by the fill_value fill_value: optional, default 0 The value to fill nas with. Ignored if nulls are being dropped. ...
625941bf287bf620b61d39b3
def login(manifesto_file, username): <NEW_LINE> <INDENT> with open(manifesto_file) as file: <NEW_LINE> <INDENT> list_of_usernames = file.readlines() <NEW_LINE> <DEDENT> if list_of_usernames: <NEW_LINE> <INDENT> for name in list_of_usernames: <NEW_LINE> <INDENT> if username == name.split(', ')[0]: <NEW_LINE> <INDENT> re...
(file, str) -> NoneType, bool Checks to see if the provided username is in the file
625941bf10dbd63aa1bd2af4
def choose_backend(backend): <NEW_LINE> <INDENT> if backend is None: <NEW_LINE> <INDENT> return cdf, pdf, ppf <NEW_LINE> <DEDENT> elif backend == 'mpmath': <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> import mpmath <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> raise ImportError('Install "mpmath" to use th...
Returns a tuple containing cdf, pdf, ppf from the chosen backend. >>> cdf, pdf, ppf = choose_backend(None) >>> cdf(-10) 7.619853263532764e-24 >>> cdf, pdf, ppf = choose_backend('mpmath') >>> cdf(-10) mpf('7.6198530241605255e-24') .. versionadded:: 0.3
625941bffb3f5b602dac35de
def setUp(self): <NEW_LINE> <INDENT> Revision.objects.all().delete() <NEW_LINE> self.model.objects.all().delete() <NEW_LINE> reversion.register(self.model) <NEW_LINE> with reversion.revision: <NEW_LINE> <INDENT> self.test = self.model.objects.create(name="test1.0") <NEW_LINE> <DEDENT> with reversion.revision: <NEW_LINE...
Sets up the ReversionTestModel.
625941bf31939e2706e4cdbb
def relabel(self): <NEW_LINE> <INDENT> vim_buffer = self.copy_vim_buffer() <NEW_LINE> buf = Buffer.init(vim_buffer) <NEW_LINE> curpos_point = self.get_cursor_point() <NEW_LINE> rect = buf.get_rect_on_cursor(curpos_point) <NEW_LINE> label_start_pos = None <NEW_LINE> if rect is not None: <NEW_LINE> <INDENT> rect.delete_l...
+-------+ || +-------+
625941bf9b70327d1c4e0d22
def compute_ngrams(toks, n=2): <NEW_LINE> <INDENT> ngrams = {} <NEW_LINE> for i in range(len(toks) - n + 1): <NEW_LINE> <INDENT> if toks[i] in ngrams: <NEW_LINE> <INDENT> ngrams[toks[i]].append(tuple(toks[i + 1:i + n])) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ngrams[toks[i]] = [tuple(toks[i + 1:i + n])] <NEW_LINE...
Returns an n-gram dictionary based on the provided list of tokens.
625941bf55399d3f05588601
def test(offset): <NEW_LINE> <INDENT> print("[*] Payload set to only overwrite the EIP") <NEW_LINE> buf = '\x11(setup sound ' <NEW_LINE> buf += '\x41' * offset <NEW_LINE> buf += struct.pack('<L', 0x42424242) <NEW_LINE> buf += '\x43' * 7 <NEW_LINE> buf += '\x90\x00#' <NEW_LINE> return buf
Test offset
625941bf8c3a873295158305
def test_broken_meta() -> None: <NEW_LINE> <INDENT> with pytest.raises(ParseError): <NEW_LINE> <INDENT> parse("Args:") <NEW_LINE> <DEDENT> with pytest.raises(ParseError): <NEW_LINE> <INDENT> parse("Args:\n herp derp")
Test parsing broken meta.
625941bf96565a6dacc8f61a
def getDetailsByID(self, server, token, userID): <NEW_LINE> <INDENT> self.uri = '/api/v1/users/{0}'.format(userID) <NEW_LINE> self.server = server + self.uri <NEW_LINE> headers = {'Content-Type': 'application/json','Authorization': 'Bearer {0}'.format(token)} <NEW_LINE> results = requests.get(self.server, headers=heade...
Get detailed information of user by ID Arguments: server {string} -- Server URI token {string} -- Token value to be used for accessing the API userID {string} -- ID of the user Returns: string -- Detailed information of user by ID
625941bfbe8e80087fb20b94
def create_comments(self): <NEW_LINE> <INDENT> for comment in self.comments: <NEW_LINE> <INDENT> comment.execute()
Creates all of the comments in :prop:comments
625941bf3c8af77a43ae36ec
def handle(text, mic, profile): <NEW_LINE> <INDENT> getresults(text, mic)
Responds to user-input, by telling word meanings". Arguments: text -- user-input, ex - "Find meaning of 'elephant'" mic -- used to interact with the user (for both input and output) profile -- contains information related to the user
625941bf26068e7796caec29
def tearDown(self): <NEW_LINE> <INDENT> super(A2SSTestCase, self).tearDown()
Override teardown actions (for every test).
625941bf60cbc95b062c6491
def rename_pct_cols(df, ver): <NEW_LINE> <INDENT> return df.rename(columns={'R_pct': ver + '_R_pct', 'M_pct': ver + '_M_pct'})
Renames the percent columns to be prefaced with the version. i.e. R_pct becomes 15v1_R_pct
625941bf6aa9bd52df036cf0
def addOneRow(self, root, v, d): <NEW_LINE> <INDENT> if d == 1: <NEW_LINE> <INDENT> node = TreeNode(v) <NEW_LINE> node.left = root <NEW_LINE> root = node <NEW_LINE> return root <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self._addOneRow(root,v,d)
:type root: TreeNode :type v: int :type d: int :rtype: TreeNode
625941bf07f4c71912b113cf
def on_success(self, data): <NEW_LINE> <INDENT> if 'delete' in data: <NEW_LINE> <INDENT> self.on_delete(data.get('delete')) <NEW_LINE> <DEDENT> elif 'limit' in data: <NEW_LINE> <INDENT> self.on_limit(data.get('limit')) <NEW_LINE> <DEDENT> elif 'disconnect' in data: <NEW_LINE> <INDENT> self.on_disconnect(data.get('disco...
Called when data has been successfull received from the stream Feel free to override this to handle your streaming data how you want it handled. See https://dev.twitter.com/docs/streaming-apis/messages for messages sent along in stream responses. :param data: data recieved from the stream :type data: dict
625941bf498bea3a759b99fe
def test_get_bound_height_out_of_range(): <NEW_LINE> <INDENT> p = np.arange(900, 300, -100) * units.hPa <NEW_LINE> h = np.arange(1, 7) * units.kilometer <NEW_LINE> with pytest.raises(ValueError): <NEW_LINE> <INDENT> _get_bound_pressure_height(p, 8 * units.kilometer, height=h) <NEW_LINE> <DEDENT> with pytest.raises(Valu...
Test when bound is out of data range in height.
625941bf63b5f9789fde7033
def _do_extra_actions(api_content, cc_content, request_fields, actions_form, context): <NEW_LINE> <INDENT> for field, form_value in actions_form.cleaned_data.items(): <NEW_LINE> <INDENT> if field in request_fields and form_value != api_content[field]: <NEW_LINE> <INDENT> api_content[field] = form_value <NEW_LINE> if fi...
Perform any necessary additional actions related to content creation or update that require a separate comments service request.
625941bf8e71fb1e9831d6f8
def get(self, key, default=None, mb=None, account=None): <NEW_LINE> <INDENT> if account: <NEW_LINE> <INDENT> if mb: <NEW_LINE> <INDENT> if key in self.config[account][mb].keys(): <NEW_LINE> <INDENT> return self.config[account][mb][key] <NEW_LINE> <DEDENT> if key in self.config[account].keys(): <NEW_LINE> <INDENT> retur...
>>> conf = '''a = 1 ... c = 1 ... ta1 { ... a = 2 ... b = 1 ... tmb1 { ... b = 2 ... c = 2 ... d = 1 ... } ... }''' >>> c = Config() >>> ctx = Config.Context() >>> for line in conf.splitlines(): ... c.parse_line(line, ctx) >>> c.get('a', default='test', mb='tmb1', account='ta1') '2' >>> c.get('b...
625941bf30bbd722463cbd12
def test_put_employee_too_long_name_fail(self): <NEW_LINE> <INDENT> url = reverse('employee-detail', kwargs={'pk':'1'}) <NEW_LINE> data = { 'first_name': 'Johniddasfeufhfweffsdfdsbvsdvdsuhfiuhwefwef', 'last_name': 'Doe', 'title':'Manager'} <NEW_LINE> response = self.client.put(url, data, format='json', HTTP_AUTHORIZATI...
Test failing a PUT if the first_name is too long
625941bf6aa9bd52df036cf1
def moveZeroes(self, nums): <NEW_LINE> <INDENT> if not nums or len(nums) == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> i, j = 0, 0 <NEW_LINE> while j < len(nums): <NEW_LINE> <INDENT> if nums[j] != 0: <NEW_LINE> <INDENT> nums[i], nums[j] = nums[j], nums[i] <NEW_LINE> i += 1 <NEW_LINE> <DEDENT> j += 1 <NEW_LINE> <...
:type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead.
625941bf236d856c2ad44725
def run_test(self): <NEW_LINE> <INDENT> with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor: <NEW_LINE> <INDENT> futures = [ executor.submit(self.regression, i) for i in range(self.train.shape[1]) ] <NEW_LINE> for idx, future in tqdm(enumerate(concurrent.futures.as_completed(future...
run all segments
625941bf7c178a314d6ef3a9
def stats(filename): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(filename, "r") as file: <NEW_LINE> <INDENT> file_content = file.read() <NEW_LINE> lines = file_content.splitlines() <NEW_LINE> words = file_content.split() <NEW_LINE> lines_count = len(lines) <NEW_LINE> words_count = len(words) <NEW_LINE> file_...
This function returns four values: - lines in the file, - words in the file, - size of the file, - file name
625941bfd58c6744b4257bae
def test_unsupported_version_response(self): <NEW_LINE> <INDENT> async def _unsupported_version_response(self): <NEW_LINE> <INDENT> packet = await SFTPHandler.recv_packet(self) <NEW_LINE> self.send_packet(FXP_VERSION, None, UInt32(99)) <NEW_LINE> return packet <NEW_LINE> <DEDENT> with patch('asyncssh.sftp.SFTPServerHan...
Test sending an unsupported version in response to init
625941bf99fddb7c1c9de2e0
def get_source(self): <NEW_LINE> <INDENT> wd = self.workdir + "mate-dock-applet" <NEW_LINE> if self.get_applet_version() == "current": <NEW_LINE> <INDENT> if not os.path.exists(wd): <NEW_LINE> <INDENT> self.run_shell_command("git clone https://github.com/robint99/mate-dock-applet.git", self.workdir) <NEW_LINE> <DEDENT>...
Get the source for the dock applet. If we're getting the source from git do a git clone if we don't already have any source code, otherwise do go pull origin master. If we're getting a specific version, hmmmm... Note: the working directory must have been created before calling this ....
625941bfb545ff76a8913d64
def testTargetFound(self): <NEW_LINE> <INDENT> self.injectEvent(vision.EventType.TARGET_FOUND, vision.TargetEvent, 0, 0, 0, 0, x = 0.5, y = -0.5, range = 4, squareNess = 1) <NEW_LINE> self.assertGreaterThan(self.controller.depth, self.estimator.depth) <NEW_LINE> self.assertGreaterThan(self.controller.speed, 0) <NEW_LIN...
Make sure new found events move the vehicle
625941bf57b8e32f524833e8
def factor(n): <NEW_LINE> <INDENT> prime_factors = [] <NEW_LINE> divisor = 2 <NEW_LINE> while n != 1: <NEW_LINE> <INDENT> exponent = 0 <NEW_LINE> while n % divisor == 0: <NEW_LINE> <INDENT> exponent += 1 <NEW_LINE> n = n / divisor <NEW_LINE> <DEDENT> if exponent > 0: <NEW_LINE> <INDENT> prime_factors.append((divisor, e...
Given n, computre its prime factorization and return in list of tuples of (prime, exponent) where exponent is nonzero TODO Probably needs to be programmed defensively, check that input >1, etc
625941bf23e79379d52ee4b4
def solve_polinom(koefs, x_value): <NEW_LINE> <INDENT> return sum([koef(x_value) for koef in koefs])
Вычисляет значение интерполянта в точке x :param koefs: коэффициенты Лагранжа :param x_value: значение точки x :return:
625941bf7c178a314d6ef3aa
def zlib_stream(data): <NEW_LINE> <INDENT> return BytesIO(compress(data.encode()))
Return test data as a zlib-compressed stream.
625941bf4e4d5625662d4329
def process_request(self, request): <NEW_LINE> <INDENT> google_user = users.get_current_user() <NEW_LINE> account = None <NEW_LINE> is_admin = False <NEW_LINE> logging.info(request.META['HTTP_USER_AGENT']) <NEW_LINE> if google_user: <NEW_LINE> <INDENT> user_id = google_user.user_id() <NEW_LINE> is_admin = users.is_curr...
This function sets up the user object Depending on the value of require_login, it can return None as 'profile'.
625941bf377c676e912720f7
def find_boundary_marker(self, face_index, markers): <NEW_LINE> <INDENT> for boundary_marker in markers: <NEW_LINE> <INDENT> for face in self.boundary_faces[boundary_marker]: <NEW_LINE> <INDENT> if face_index == face[0]: <NEW_LINE> <INDENT> return boundary_marker
Returns the boundary marker containing face_index.
625941bf8e71fb1e9831d6f9
def android(request): <NEW_LINE> <INDENT> return render(request, 'applications/applications_android.jade')
Applications > Android
625941bf460517430c3940d9
def _uninstall( action='remove', name=None, version=None, pkgs=None, normalize=True, ignore_epoch=False, **kwargs): <NEW_LINE> <INDENT> if action not in ('remove', 'purge'): <NEW_LINE> <INDENT> return {'name': name, 'changes': {}, 'result': False, 'comment': 'Invalid action \'{0}\'. ' 'This is probably a bug.'.format(a...
Common function for package removal
625941bf63f4b57ef000106e
def samplemixinmethod(method): <NEW_LINE> <INDENT> method.__issamplemixin__ = True <NEW_LINE> return method
Marks a method as being a mixin. Adds the '__issamplemixin__' attribute with value True to the decorated function. Examples: >>> @samplemixinmethod >>> def f(): ... pass >>> f.__issamplemixin__ True
625941bfec188e330fd5a6f2
def shift_down(self, num = 1): <NEW_LINE> <INDENT> return self.shift(0, num)
Moves the selector down, but number of rows given by "num" parameter.
625941bff548e778e58cd4cb
def in_place_uniform_shuffle(the_list): <NEW_LINE> <INDENT> n = len(the_list) <NEW_LINE> for i in xrange(0, n - 1): <NEW_LINE> <INDENT> j = get_random(i, n - 1) <NEW_LINE> the_list[i], the_list[j] = the_list[j], the_list[i]
in place shuffle of a the_list
625941bf7d847024c06be208
@app.route('/restart') <NEW_LINE> @requires_auth <NEW_LINE> def app_restart_parsec(): <NEW_LINE> <INDENT> ext = kill_process('parsecd.exe') <NEW_LINE> print('We tried to kill parsec with response:\n', ext) <NEW_LINE> error = 'An unknown error has happened. I think you should take a peak at the console for this!' <NEW_L...
Kills parsec's daemon and returns a HTTP response
625941bf379a373c97cfaa92
def initial_solution(weights1, weights2, max_cost): <NEW_LINE> <INDENT> from subprocess import check_output <NEW_LINE> max_weights = max(np.max(weights1), np.max(weights2)) <NEW_LINE> inarg = '{} {}\n{} {}\n'.format(weights1.size, weights2.size, max_cost, max_weights) <NEW_LINE> inarg += ' '.join([str(float(_)) for _ i...
Find an initial solution using russel method from the Yossi Rubner implemention.
625941bf24f1403a92600ab7
def solid(self, color=_dark): <NEW_LINE> <INDENT> for led in range(LED_COUNT): <NEW_LINE> <INDENT> self.leds[led] = color <NEW_LINE> <DEDENT> self.__show()
Light all leds in single colour
625941c03c8af77a43ae36ed
def __auth(self, json_received, request): <NEW_LINE> <INDENT> print(json_received) <NEW_LINE> user = self.__return_username(json_received) <NEW_LINE> if user is not None: <NEW_LINE> <INDENT> self.common_request.update({user: request}) <NEW_LINE> json_response = (self.__make_json_from_attribute_user (self.__get_attribut...
метод аутентификации :param json: аутентификации :param request: сокет - соединение :return: сообщение клиенту
625941c06e29344779a62563
def load(self): <NEW_LINE> <INDENT> if os.path.isfile(self.filename): <NEW_LINE> <INDENT> logger.debug('loading code database...') <NEW_LINE> f = file(self.filename, 'rb') <NEW_LINE> self._database = cPickle.load(f) <NEW_LINE> f.close() <NEW_LINE> logger.debug('code database loaded.') <NEW_LINE> <DEDENT> else: <NEW_LIN...
Load the code browser 'database'.
625941c0656771135c3eb7bb
def stop(self): <NEW_LINE> <INDENT> self.doQuit.set()
Set a flag to indicate that the sound thread should end.
625941c0187af65679ca506d
def deleteDuplicates(self, head): <NEW_LINE> <INDENT> curr = head <NEW_LINE> while curr and curr.next: <NEW_LINE> <INDENT> if curr.val == curr.next.val: <NEW_LINE> <INDENT> curr.next=curr.next.next <NEW_LINE> <DEDENT> if curr.next is not None: <NEW_LINE> <INDENT> if curr.val!=curr.next.val: <NEW_LINE> <INDENT> curr = c...
:type head: ListNode :rtype: ListNode
625941c01f037a2d8b94614d
def test_future_question(self): <NEW_LINE> <INDENT> future_question = create_question(question_text="Future question", days=5) <NEW_LINE> url = reverse("polls:results", args=(future_question.id,)) <NEW_LINE> response = self.client.get(url) <NEW_LINE> self.assertEqual(response.status_code, 404)
Test that the Result View won't show any future question (ResultView.get_queryset works)
625941c0bd1bec0571d9057d
def keltner_channel(df, n): <NEW_LINE> <INDENT> KelChM = pd.Series(((df['High'] + df['Low'] + df['Close']) / 3).rolling(n, min_periods=n).mean(), name='KelChM_' + str(n)) <NEW_LINE> KelChU = pd.Series(((4 * df['High'] - 2 * df['Low'] + df['Close']) / 3).rolling(n, min_periods=n).mean(), name='KelChU_' + str(n)) <NEW_LI...
Calculate Keltner Channel for given data. :param df: pandas.DataFrame :param n: :return: pandas.DataFrame
625941c015fb5d323cde0a5b
def _nodal_planes(self, obj, element): <NEW_LINE> <INDENT> subelement = etree.Element('nodalPlanes') <NEW_LINE> if obj.nodal_plane_1: <NEW_LINE> <INDENT> el = etree.Element('nodalPlane1') <NEW_LINE> self._value(obj.nodal_plane_1.strike, obj.nodal_plane_1.strike_errors, el, 'strike') <NEW_LINE> self._value(obj.nodal_pla...
Converts a NodalPlanes into etree.Element object. :type pick: :class:`~obspy.core.event.NodalPlanes` :rtype: etree.Element
625941c0b5575c28eb68df4e
def getNextNode(self, point, axis, amount): <NEW_LINE> <INDENT> p = list(point) <NEW_LINE> p[axis] += amount <NEW_LINE> return tuple(p)
Increments the <axis> dimension in the point by <amount>
625941c04f88993c3716bfb9
def test_create_wrapper_validator(self): <NEW_LINE> <INDENT> inmap = self.std_map() <NEW_LINE> inmap.update({'foreign data wrapper fdw1': { 'validator': 'postgresql_fdw_validator'}}) <NEW_LINE> sql = self.to_sql(inmap) <NEW_LINE> assert fix_indent(sql[0]) == "CREATE FOREIGN DATA WRAPPER fdw1 " "VALIDATOR pos...
Create a foreign data wrapper with a validator function
625941c08a43f66fc4b53fb6
def qryMarketData(self): <NEW_LINE> <INDENT> self.reqID += 1 <NEW_LINE> req = {} <NEW_LINE> self.reqQryDepthMarketData(req, self.reqID)
查询合约截面数据
625941c08a43f66fc4b53fb7
def trunk_add_subports(self, tenant_id, trunk_id, sub_ports): <NEW_LINE> <INDENT> spec = { 'tenant_id': tenant_id, 'sub_ports': sub_ports, } <NEW_LINE> trunk = self.client.trunk_add_subports(trunk_id, spec) <NEW_LINE> sub_ports_to_remove = [ sub_port for sub_port in trunk['sub_ports'] if sub_port in sub_ports] <NEW_LIN...
Add subports to the trunk. :param tenant_id: ID of the tenant. :param trunk_id: ID of the trunk. :param sub_ports: List of subport dictionaries to be added in format {'port_id': <ID of neutron port for subport>, 'segmentation_type': 'vlan', 'segmentation_id': <VLAN tag>}
625941c0090684286d50ec32
def organization_update( context: Context, data_dict: DataDict) -> ActionResult.OrganizationUpdate: <NEW_LINE> <INDENT> return _group_or_org_update(context, data_dict, is_org=True)
Update a organization. You must be authorized to edit the organization. .. note:: Update methods may delete parameters not explicitly provided in the data_dict. If you want to edit only a specific attribute use `organization_patch` instead. For further parameters see :py:func:`~ckan.logic.action.create.organ...
625941c0fff4ab517eb2f389
def handle(self, msgType, di): <NEW_LINE> <INDENT> assert self.notify.debugCall() <NEW_LINE> if msgType not in self.__type2message: <NEW_LINE> <INDENT> self.notify.warning('Received unknown message: %d' % msgType) <NEW_LINE> return <NEW_LINE> <DEDENT> message = self.__type2message[msgType] <NEW_LINE> sentArgs=loads(di....
Send data from the net on the local netMessenger.
625941c076d4e153a657ea7f
def test_create_should_register_new_session_with_keys(self): <NEW_LINE> <INDENT> label = self.session.create_dynamodb_session(access_key='key', secret_key='secret') <NEW_LINE> try: <NEW_LINE> <INDENT> self.session._cache.switch(label) <NEW_LINE> <DEDENT> except RuntimeError: <NEW_LINE> <INDENT> self.fail("Label '%s' sh...
Create session should successfully register new session with keys.
625941c0d486a94d0b98e094
def main(): <NEW_LINE> <INDENT> factorions = [] <NEW_LINE> for x in range(10,50001): <NEW_LINE> <INDENT> fac_sum = 0 <NEW_LINE> s = str(x) <NEW_LINE> for digit in s: <NEW_LINE> <INDENT> num = int(digit) <NEW_LINE> fac_sum += factorial(num) <NEW_LINE> <DEDENT> if fac_sum == x: <NEW_LINE> <INDENT> factorions.append(x) <N...
Finds the sum off all factorions (exluding 1 and 2).
625941c0cad5886f8bd26f29
def predict(self, x_test, k=5, wt='distance'): <NEW_LINE> <INDENT> target = self.data_raw.shape[1]-1 <NEW_LINE> x_train = self.codebook.matrix[:, :target] <NEW_LINE> y_train = self.codebook.matrix[:, target] <NEW_LINE> clf = neighbors.KNeighborsRegressor(k, weights=wt) <NEW_LINE> clf.fit(x_train, y_train) <NEW_LINE> x_...
Similar to SKlearn we assume that we have X_tr, Y_tr and X_test. Here it is assumed that target is the last column in the codebook and data has dim-1 columns :param x_test: input vector :param k: number of neighbors to use :param wt: method to use for the weights (more detail in KNeighborsRegressor docs) :returns: pre...
625941c038b623060ff0ad3d
def load_sample_images(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> from scipy.misc import imread <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> from scipy.misc.pilutil import imread <NEW_LINE> <DEDENT> <DEDENT> except ImportError: <NEW_LINE> <INDENT> raise ImportError("The Pyth...
Load sample images for image manipulation. Loads both, ``china`` and ``flower``. Return ------ data : Bunch Dictionary-like object with the following attributes : 'images', the two sample images, 'filenames', the file names for the images, and 'DESCR' the full description of the dataset. Examples ----...
625941c00c0af96317bb8137
@register.inclusion_tag('rbac/breadcrumb.html') <NEW_LINE> def breadcrumb(request): <NEW_LINE> <INDENT> return {'breadcrumb_list': request.breadcrumb_list}
面包屑导航
625941c0293b9510aa2c31e7
def test_get_base_players(self): <NEW_LINE> <INDENT> players = self.x.get_base_players() <NEW_LINE> player = random.choice(players) <NEW_LINE> logging.info(player) <NEW_LINE> self.assertIsInstance(players, list) <NEW_LINE> self.assertGreater(len(players), 50) <NEW_LINE> self.assertIn('player_id', player.keys())
Returns:
625941c01d351010ab855a6c
def sigmoid(self, x): <NEW_LINE> <INDENT> return 1 / (1 + np.exp(-x))
pega os valores das somas do input e normaliza esses valores atraves de uma sigmoid ou seja os valores das somas dos inputs estarão entre 0 e 1
625941c08e05c05ec3eea2c2
def remove(self, key): <NEW_LINE> <INDENT> if self.key == key: <NEW_LINE> <INDENT> if self.right and self.left: <NEW_LINE> <INDENT> [psucc, succ] = self.right._findMin(self) <NEW_LINE> if psucc.left == succ: <NEW_LINE> <INDENT> psucc.left = succ.right <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> psucc.right = succ.rig...
Delete node and balance the tree Case 1: not left or right child Case 2: has one left or right child Case 3: has left and right child :param key: :return:
625941c0091ae35668666eb2
def menu_func (self, context): <NEW_LINE> <INDENT> self.layout.operator (import_dsf_pose.bl_idname, text = 'dsf-pose (.d[su]f)')
display the menu entry for calling the importer.
625941c097e22403b379cee8
def encode_check(payload): <NEW_LINE> <INDENT> checksum = double_sha256(payload, True)[:4] <NEW_LINE> if payload[0] == 0x00: <NEW_LINE> <INDENT> return b58encode(b'\x00') + b58encode(payload[1:] + checksum) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return b58encode(payload + checksum)
Returns the base58 encoding with a 4-byte checksum. :param payload: The data (as bytes) to encode.
625941c067a9b606de4a7e0a
def get_hardware_fcport(self, hardware_fcport_id, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('async'): <NEW_LINE> <INDENT> return self.get_hardware_fcport_with_http_info(hardware_fcport_id, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (data) = self.get_har...
get_hardware_fcport # noqa: E501 Get one fibre-channel port # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_hardware_fcport(hardware_fcport_id, async=True) >>> result = thread.get() :param async bool :param int h...
625941c03617ad0b5ed67e48
def example_H2O2_TS(): <NEW_LINE> <INDENT> h2o2 = molkit.from_smarts('[H]OO[H]') <NEW_LINE> dihe = Dihedral(1, 2, 3, 4) <NEW_LINE> s1 = Settings() <NEW_LINE> s1.constraint.update(dihe.get_settings(0.0)) <NEW_LINE> dftb_opt = dftb(templates.geometry.overlay(s1), h2o2) <NEW_LINE> dftb_freq = dftb(templates.freq, dftb_opt...
This example generates an approximate TS for rotation in hydrogen peroxide using DFTB, and performs a full TS optimization in Orca. It illustrates using a hessian from one package, DFTB in this case, to initialize a TS optimization in another, i.e. Orca in this case
625941c0de87d2750b85fcdf
def from_vector(self, vector, order=None): <NEW_LINE> <INDENT> if order is None: <NEW_LINE> <INDENT> order = self.get_order() <NEW_LINE> <DEDENT> return self._from_dict({order[index]: coeff for (index, coeff) in vector.items()})
Build an element of ``self`` from a (sparse) vector. .. SEEALSO:: :meth:`get_order`, :meth:`CombinatorialFreeModule.Element._vector_` EXAMPLES:: sage: QS3 = SymmetricGroupAlgebra(QQ, 3) sage: b = QS3.from_vector(vector((2, 0, 0, 0, 0, 4))); b 2*[1, 2, 3] + 4*[3, 2, 1] sage: a = 2*QS3([1,2,3])+4*QS3([...
625941c01f5feb6acb0c4aa3
def __init__(self, data_path): <NEW_LINE> <INDENT> self.data_path = data_path <NEW_LINE> with open(os.path.join(self.data_path, 'config.yaml')) as fin: <NEW_LINE> <INDENT> self.config = yaml.load(fin) <NEW_LINE> <DEDENT> for p in [self.exif_path(), self.feature_path(), self.robust_matches_path()]: <NEW_LINE> <INDENT> t...
Create dataset instance. Empty directories (for EXIF, robust matches, etc) will be created if they don't exist already. :param data_path: Path to directory containing dataset
625941c030c21e258bdfa3eb
def __init__(self, py_dict=None): <NEW_LINE> <INDENT> super(DNSSettingsSchema, self).__init__() <NEW_LINE> self.domain_name = None <NEW_LINE> self.primary_dns = None <NEW_LINE> self.secondary_dns = None <NEW_LINE> if py_dict is not None: <NEW_LINE> <INDENT> self.get_object_from_py_dict(py_dict)
Constructor to create DNSSettingsSchema object @param py_dict : python dictionary to construct this object
625941c0596a897236089a13
def _frame_generator(self, a): <NEW_LINE> <INDENT> for i in a: <NEW_LINE> <INDENT> yield self[i]
Return a generator that produces each frame identified by ID in `a`.
625941c08c0ade5d55d3e908
def __init__(self, code, fam=None, user=None, sysop=None): <NEW_LINE> <INDENT> if code.lower() != code: <NEW_LINE> <INDENT> pywikibot.log(u'BaseSite: code "%s" converted to lowercase' % code) <NEW_LINE> code = code.lower() <NEW_LINE> <DEDENT> if not all(x in pywikibot.family.CODE_CHARACTERS for x in str(code)): <NEW_LI...
Constructor. @param code: the site's language code @type code: str @param fam: wiki family name (optional) @type fam: str or Family @param user: bot user name (optional) @type user: str @param sysop: sysop account user name (optional) @type sysop: str
625941c0b830903b967e985d
def find_inorder_first_node(p): <NEW_LINE> <INDENT> if p is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> node = p <NEW_LINE> while not node.ltag and node.left is not None: <NEW_LINE> <INDENT> node = node.left <NEW_LINE> <DEDENT> return node
找到子树 p 的中序序列的第一个节点
625941c0566aa707497f44bc
def ts(self): <NEW_LINE> <INDENT> from .timeseries import TimeSeries <NEW_LINE> s = TimeSeries(client=self) <NEW_LINE> return s
Access the timeseries namespace, providing support for redis timeseries data.
625941c0d6c5a10208143f98
def check_command_type_struct_fields( ctxt: IDLCompatibilityContext, old_type: syntax.Struct, new_type: syntax.Struct, cmd_name: str, old_idl_file: syntax.IDLParsedSpec, new_idl_file: syntax.IDLParsedSpec, old_idl_file_path: str, new_idl_file_path: str): <NEW_LINE> <INDENT> for old_field in old_type.fields or []: <NEW_...
Check compatibility between old and new type fields.
625941c0167d2b6e31218ae6
def SetExpanded(self, expanded): <NEW_LINE> <INDENT> if expanded != self.IsExpanded(): <NEW_LINE> <INDENT> self.Collapse(not expanded) <NEW_LINE> self.OnPaneChanged()
Set whether the contained widget is collapsed or expanded. If there will be no change, don't do anything.
625941c050485f2cf553cce8
def seek(self, time): <NEW_LINE> <INDENT> command = 'seek ' + str(time) <NEW_LINE> self.run_command(command)
Seek in seconds, for instance 'seek 12'.
625941c04c3428357757c27a
def parse_gc_dist(self, f): <NEW_LINE> <INDENT> s_name = self.get_s_name(f) <NEW_LINE> d = dict() <NEW_LINE> reference_species = None <NEW_LINE> reference_d = dict() <NEW_LINE> avg_gc = 0 <NEW_LINE> for l in f['f']: <NEW_LINE> <INDENT> if l.startswith('#'): <NEW_LINE> <INDENT> sections = l.strip("\n").split("\t", 3) <N...
Parse the contents of the Qualimap BamQC Mapped Reads GC content distribution file
625941c097e22403b379cee9
def read_var_header(self): <NEW_LINE> <INDENT> hdr = self._matrix_reader.read_header() <NEW_LINE> n = reduce(lambda x, y: x*y, hdr.dims, 1) <NEW_LINE> remaining_bytes = hdr.dtype.itemsize * n <NEW_LINE> if hdr.is_complex and not hdr.mclass == mxSPARSE_CLASS: <NEW_LINE> <INDENT> remaining_bytes *= 2 <NEW_LINE> <DEDENT> ...
Read and return header, next position Parameters ---------- None Returns ------- header : object object that can be passed to self.read_var_array, and that has attributes ``name`` and ``is_global`` next_position : int position in stream of next variable
625941c0507cdc57c6306c25
def draw(self, objects): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> for obj in objects: <NEW_LINE> <INDENT> obj.draw(self.__screen) <NEW_LINE> <DEDENT> <DEDENT> except TypeError: <NEW_LINE> <INDENT> objects.draw(self.__screen)
Draws all of the given objects onto the screen. :param objects: The objects to draw onto the screen. Can be a single object or a list of objects
625941c09c8ee82313fbb6c4
def __init__(self, returnType, name, *arguments, **kargs): <NEW_LINE> <INDENT> super(ApiFunction, self).__init__(returnType) <NEW_LINE> self.tagName = name <NEW_LINE> self.name = name <NEW_LINE> self.returnAttribute = None <NEW_LINE> self.fixedAttributes = {} <NEW_LINE> if kargs: <NEW_LINE> <INDENT> if 'tagName' in kar...
function arguments are expected to be tuples containing: (type, name, isReference) Keyword arguments allowed: tagName - POSXML tag to be generated returnAttribute - POSXML tag attribute that represents the return value of the function.
625941c0f7d966606f6a9f51
def unif(n): <NEW_LINE> <INDENT> return np.ones((n,))/n
return a uniform histogram of length n (simplex) Parameters ---------- n : int number of bins in the histogram Returns ------- h : np.array (n,) histogram of length n such that h_i=1/n for all i
625941c030dc7b76659018b8
def __init__(self, name, lSites, lDirection, lDepth, lWidth=0.5): <NEW_LINE> <INDENT> GPE.__init__(self, name) <NEW_LINE> self.setString("externalPotential", "lattice") <NEW_LINE> self.set("latticeSites", lSites) <NEW_LINE> self.set("latticeDirection", lDirection) <NEW_LINE> self.set("latticeDepth", lDepth) <NEW_LINE> ...
lSites: number of lattice sites lDirection: 0, 1, 2 for x, y or z direction lDepth: prefactor of the potential V0: - V0 * exp(...) lWidth: either a single number or a vector of 3 different widths of the single well
625941c0e64d504609d74790
def configurar_gnome(): <NEW_LINE> <INDENT> shell = Shell(AcaoQuandoOcorrerErro.REPETIR_E_IGNORAR, 10) <NEW_LINE> shell.executar("gsettings set org.gnome.desktop.interface enable-hot-corners false") <NEW_LINE> shell.executar("gsettings set org.gnome.desktop.interface clock-show-seconds true") <NEW_LINE> shell.executar(...
Configura o Gnome personalizando as configurações.
625941c0090684286d50ec33
def _parse(url): <NEW_LINE> <INDENT> url = url.strip() <NEW_LINE> if not re.match(r'^\w+://', url): <NEW_LINE> <INDENT> url = '//' + url <NEW_LINE> <DEDENT> parsed = urlparse(url) <NEW_LINE> return _parsed_url_args(parsed)
Return tuple of (scheme, netloc, host, port, path), all in bytes except for port which is int. Assume url is from Request.url, which was passed via safe_url_string and is ascii-only.
625941c0287bf620b61d39b5