code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def implicit_urldata(self, ud, d): <NEW_LINE> <INDENT> return [] | Get a list of FetchData objects for any implicit URLs that will also
be downloaded when we fetch the given URL. | 625941f05fdd1c0f98dc07c4 |
def __init__(self): <NEW_LINE> <INDENT> self.original_set={1,2,3,5,6,"Shardul"} <NEW_LINE> self.frozen_set={} | Initialize Two set frozen and original | 625941f08c0ade5d55d3ef4e |
def merge_k_lists(lists): <NEW_LINE> <INDENT> dummy = ListNode(None) <NEW_LINE> curr = dummy <NEW_LINE> q = PriorityQueue() <NEW_LINE> for node in lists: <NEW_LINE> <INDENT> if node: <NEW_LINE> <INDENT> q.put((node.val, node)) <NEW_LINE> <DEDENT> <DEDENT> while not q.empty(): <NEW_LINE> <INDENT> curr.next = q.get()[1] ... | Merge List | 625941f0ab23a570cc250716 |
def query_args_for_pagination(args): <NEW_LINE> <INDENT> query = args.copy() <NEW_LINE> if 'page' in query: <NEW_LINE> <INDENT> del query['page'] <NEW_LINE> return query <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return query | To use url_for for pagination next/prev page links
We need to not have the current page in the query args
:param request:
:return request args without page | 625941f0e8904600ed9f24c5 |
def forward(self, input, target): <NEW_LINE> <INDENT> gpu = input.is_cuda <NEW_LINE> ones = Variable(torch.zeros(input.size())) <NEW_LINE> if gpu: <NEW_LINE> <INDENT> ones = ones.cuda() <NEW_LINE> <DEDENT> a = torch.min(input, ones) <NEW_LINE> log_den = torch.log(torch.exp(a) + torch.exp(a - input)) - a <NEW_LINE> mask... | Inputs:
- input: N tensor of class scores
- target: N LongTensor giving ground-truth for elements of inputs;
each element should be an integer in the range [0, C];
if target[i] == 0 then input[i] should be negative for all classes. | 625941f0a8ecb033257d3659 |
def test_add_scopes(self): <NEW_LINE> <INDENT> with pytest.raises(github3.AuthenticationFailed): <NEW_LINE> <INDENT> self.instance.add_scopes() | Test that adding scopes requires authentication. | 625941f0b830903b967e9e93 |
def set_config_value(logger, name, value, uri, headers=None, timeout=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> local_headers = {} <NEW_LINE> if headers: <NEW_LINE> <INDENT> local_headers.update(headers) <NEW_LINE> <DEDENT> local_headers['Content-type'] = 'application/text' <NEW_LINE> do_api_call('PUT', get_ur... | Set configuration value.
:param logger: logger instance
:param name: name of the configuration field
:param value: field value
:param uri: web app URI
:param headers: optional dictionary of HTTP headers
:param timeout: optional request timeout
:return: True on success, False on failure | 625941f01d351010ab8560a9 |
def prepare_transformed_checkins_database(checkins_file, num_cells, shifted=False) -> dict: <NEW_LINE> <INDENT> data = datasethelper.load_dataset_gowalla(checkins_file) <NEW_LINE> transformed_data = dict() <NEW_LINE> for i in range(len(data)): <NEW_LINE> <INDENT> c = data[i] <NEW_LINE> x, y = rangeutil.map_point_to_cel... | Prepare a tranformed check-ins (i.e., from check-ins to grid index)
:param checkins_file: check-in file
:param num_cells: grid granularity
:param shifted: should the index be shifted?
:return: transformed check-ins | 625941f076d4e153a657f0c1 |
def remove_dependency(self, config, ext_service): <NEW_LINE> <INDENT> pass | Remove the dependency between this service and the external one
:return: | 625941f0d268445f265b53fd |
def write_excel(): <NEW_LINE> <INDENT> f = xlwt.Workbook() <NEW_LINE> sheet1 = f.add_sheet('students',cell_overwrite_ok=True) <NEW_LINE> row0 = ['id','性别','班级编号','姓名'] <NEW_LINE> for i in range(len(row0)): <NEW_LINE> <INDENT> sheet1.write(0,i,row0[i],set_style('宋体',200,True)) <NEW_LINE> <DEDENT> results=mysql_m() <NEW_... | 写表格
:return: | 625941f0e1aae11d1e74a24b |
def complete_set_parity(self, text, line, begidx, endidx): <NEW_LINE> <INDENT> return ['N' 'O'] | Autocomplete for set_parity command | 625941f0091ae356686674e3 |
def key_press_callback(self, event): <NEW_LINE> <INDENT> if not event.inaxes: return <NEW_LINE> if event.key=='t': <NEW_LINE> <INDENT> self.showverts = not self.showverts <NEW_LINE> self.line.set_visible(self.showverts) <NEW_LINE> if not self.showverts: self._ind = None <NEW_LINE> <DEDENT> elif event.key=='d': <NEW_LIN... | ketika kunci sudah ditekan | 625941f0d10714528d600278 |
def sumLimit(article, limit): <NEW_LINE> <INDENT> start = perf_counter() <NEW_LINE> """Process the article""" <NEW_LINE> content, total = process_article(article) <NEW_LINE> """Create a summary with a specified number of sentences""" <NEW_LINE> sort = sorted(total, reverse=True) <NEW_LINE> best = set() <NEW_LINE> if li... | Start Performance Counter | 625941f0cb5e8a47e48b802f |
def test_byteswap_complex_scalar(self): <NEW_LINE> <INDENT> for dtype in [np.dtype('<'+t) for t in np.typecodes['Complex']]: <NEW_LINE> <INDENT> z = np.array([2.2-1.1j], dtype) <NEW_LINE> x = z[0] <NEW_LINE> y = x.byteswap() <NEW_LINE> if x.dtype.byteorder == z.dtype.byteorder: <NEW_LINE> <INDENT> assert_equal(x, np.fr... | Ticket #1259 and gh-441 | 625941f0dd821e528d63b733 |
def get_masked_text(self): <NEW_LINE> <INDENT> return self.mask_char * len(self.get_edit_text()) | Get masked out text. | 625941f05e10d32532c5f4b3 |
def get_palabrastr(self): <NEW_LINE> <INDENT> return self.palabrastr | Devuelve el string que representa nuestra palabra a jugar | 625941f0236d856c2ad44d71 |
def plot_image(ax,im_path,band=1): <NEW_LINE> <INDENT> imobj = gdal.Open(im_path) <NEW_LINE> imarr = imobj.GetRasterBand(band).ReadAsArray() <NEW_LINE> ax.imshow(imarr,cmap='gray') | Add satellite image to ax object.
:param im_path: str path of image file.
:param band: int band to display (greyscale).
:return: none | 625941f0796e427e537b0b59 |
def _read_stimuli_texture(stimuli_path, stim_set, n_tasks=6, tr=2.4, glm=False): <NEW_LINE> <INDENT> if stim_set not in [1, 2]: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> if stim_set == 1: <NEW_LINE> <INDENT> conditions = np.load(stimuli_path + '1.npy') <NEW_LINE> conditions = np.array([cond[:2] ... | Reads stimuli for the Texture dataset and returns a numpy array of
shape [n_scans, n_classes] | 625941f029b78933be1e5c34 |
def open(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.conn = pymysql.connect( host=self.config["host"], port=self.config["port"], user=self.config["user"], passwd=self.config["passwd"], db=self.config["db"], charset=self.config["charset"] ) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> prin... | 根据配置打开数据库,返回对应表的cursor
:return: | 625941f0f7d966606f6aa59a |
def encode(string, divide=1024): <NEW_LINE> <INDENT> array = [] <NEW_LINE> for index in xrange(0, len(string), divide): <NEW_LINE> <INDENT> array.append(_encode(string[index:index+divide])) <NEW_LINE> <DEDENT> return '\1'.join(array) | Encode a string to base 255. | 625941f05fc7496912cc3f0c |
def test_is_valid_signature__signature_not_string(): <NEW_LINE> <INDENT> with pytest.raises(TypeError): <NEW_LINE> <INDENT> is_valid_signature( Web3.HTTPProvider("http://127.0.0.1:8545"), "0x6927e990021d23b1eb7b8789f6a6feaf98fe104bb0cf8259421b79f9a34222b" + "0", 123, "0x5409ed021d9299bf6814279a6a1411a7e866a631", ) | Test that passng a non-string signature raises a TypeError. | 625941f0cdde0d52a9e535c7 |
def copyPlatToNewCen(sourcePlat): <NEW_LINE> <INDENT> logging.debug('***** Copying Platform *****') <NEW_LINE> platContact = copyRPToNewCen(sourcePlat.contact) <NEW_LINE> p = Platform(abbrev = sourcePlat.abbrev, title = sourcePlat.title + ' (Example version)', centre = targetCentre, contact = platContact, compiler = so... | Copy a platform from one centre to another centre | 625941f0aad79263cf390fd8 |
def test_images(): <NEW_LINE> <INDENT> images_path = os.path.join(tests_path, 'images') <NEW_LINE> assert os.path.isdir(images_path), 'test images repo not present. run "git clone https://git.pileof.rocks/drewcassidy/quicktex-test-images.git tests/images" to download them' <NEW_LINE> assert os.path.isfile(os.path.join(... | Test for the images submodule | 625941f0bf627c535bc1375e |
def isMirrorNode(node): <NEW_LINE> <INDENT> return meta.hasMetaClass(node, MIRROR_METACLASS) | Return whether a node has mirroring data
Args:
node: A PyNode, MObject, or node name | 625941f038b623060ff0b37b |
def CountSketch(n, c): <NEW_LINE> <INDENT> h = choice(c, n) <NEW_LINE> s = choice([1.0, -1.0], n) <NEW_LINE> Pi = coo_matrix((s, (h, np.arange(n))), shape=(c, n)) <NEW_LINE> return Pi | Returns a sparse CountSketch matrix from n dimensions to c | 625941f016aa5153ce362a08 |
def last_element(list): <NEW_LINE> <INDENT> if list: <NEW_LINE> <INDENT> return list[-1] | Return last item in list (None if list is empty.
>>> last_element([1, 2, 3])
3
>>> last_element([]) is None
True | 625941f03539df3088e2e8da |
def __nonzero__(self): <NEW_LINE> <INDENT> return self.__bool__() | Python 2 dunder method for __bool__. Kept for compatibility. | 625941f055399d3f05588c47 |
def request_motd(self, origin, target): <NEW_LINE> <INDENT> if self.user_exists(origin): <NEW_LINE> <INDENT> if self.server_exists(target[0]) and target[1] == None: <NEW_LINE> <INDENT> self._callback(self.CALLBACK_REQUESTMOTD, origin, target) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ProtocolError( "MOTD can ... | Request the message of the day for the target server | 625941f0f8510a7c17cf9c8f |
def __call__(self, metricValue, slicer, userPlotDict, fignum=None): <NEW_LINE> <INDENT> if slicer.slicerName != 'OpsimFieldSlicer': <NEW_LINE> <INDENT> raise ValueError('OpsimHistogram is for use with OpsimFieldSlicer.') <NEW_LINE> <DEDENT> plotDict = {} <NEW_LINE> plotDict.update(self.defaultPlotDict) <NEW_LINE> plotD... | Histogram metricValue for all healpix points. | 625941f08c3a873295158951 |
def formatInitialData(self, deviceReports): <NEW_LINE> <INDENT> devices = [] <NEW_LINE> for deviceName, deviceGuard in self.dataProvider.getDevices(): <NEW_LINE> <INDENT> devices.append( self.createDevice(deviceName, deviceGuard, deviceReports[deviceName])) <NEW_LINE> <DEDENT> return devices | !
| 625941f07047854f462a1992 |
def handle_starnum(val, ranges=(0, 100), res=list()): <NEW_LINE> <INDENT> tmp = val.split('/') <NEW_LINE> val_step = int(tmp[1]) <NEW_LINE> if val_step < 1: <NEW_LINE> <INDENT> return res <NEW_LINE> <DEDENT> val_tmp = int(tmp[1]) <NEW_LINE> while val_tmp <= ranges[1]: <NEW_LINE> <INDENT> res.append(val_tmp) <NEW_LINE> ... | 星号/数字 组合 如 */3 | 625941f0167d2b6e31219123 |
def delete_volume(self, volume): <NEW_LINE> <INDENT> volume_name = volume['display_name'] <NEW_LINE> vcloud_volume_name = self._get_vcloud_volume_name(volume['id'], volume_name) <NEW_LINE> LOG.debug('Deleting volume %s', vcloud_volume_name) <NEW_LINE> result, resp = self._delete_volume(vcloud_volume_name) <NEW_LINE> if... | Delete a volume. | 625941f026238365f5f0f404 |
def play (tab, player): <NEW_LINE> <INDENT> valid = False <NEW_LINE> while not valid: <NEW_LINE> <INDENT> place = [-1,-1] <NEW_LINE> while not((0 <= place[0] < len(tab)) and (0 <= place[1] < len(tab))): <NEW_LINE> <INDENT> print ("Player ",player, end="") <NEW_LINE> print(", Please provide the row and the columm from 0... | (list, str) -> None
Plays a step of the game
Preconditions: tab is a reference to the n x n tab containing '-', 'X' and 'O'
The player is X or O
tab is modified (an elementis changed) | 625941f0ad47b63b2c50a50e |
def to_definition(self): <NEW_LINE> <INDENT> icon = { Name.Type.Root: icons.ICON_MIMETYPE, Name.Type.Division: icons.ICON_DIVISION, Name.Type.Section: icons.ICON_SECTION, Name.Type.Variable: icons.ICON_VAR, Name.Type.Paragraph: icons.ICON_FUNC }[self.node_type] <NEW_LINE> d = Definition(self.name, self.line, self.colum... | Converts the name instance to a pyqode.core.share.Definition | 625941f0d7e4931a7ee9e4ae |
def render_shedule_ui(self, user_id, time_details, duration): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> pr_user = ProctoruUser.objects.get(student=user_id) <NEW_LINE> <DEDENT> except ObjectDoesNotExist: <NEW_LINE> <INDENT> return {"status": "error"} <NEW_LINE> <DEDENT> api_exam_start_time = time_details.get("api_exa... | This function renders Schedule Exam UI.
input params: user_id, time_datails, duration
output params: Context | 625941f03c8af77a43ae3d36 |
def normalize(input_string): <NEW_LINE> <INDENT> normalized_string = '' <NEW_LINE> input_string.strip() <NEW_LINE> input_string_splited = input_string.split(' ') <NEW_LINE> for string in input_string_splited: <NEW_LINE> <INDENT> if string != '': <NEW_LINE> <INDENT> normalized_string += string.lower() + ' ' <NEW_LINE> <... | 인풋으로 받는 스트링에서 정규화된 스트링을 반환함
아래의 요건들을 충족시켜야함
* 모든 단어들은 소문자로 되어야함
* 띄어쓰기는 한칸으로 되어야함
* 앞뒤 필요없는 띄어쓰기는 제거해야함
Parameters:
input_string (string): 영어로 된 대문자, 소문자, 띄어쓰기, 문장부호, 숫자로 이루어진 string
ex - "This is an example.", " EXTRA SPACE "
Returns:
normalized_string (string): 위 요건을 충족시... | 625941f07cff6e4e81117f14 |
def Delete(name): <NEW_LINE> <INDENT> return _GetService().Delete( utils.GetMessagesModule().DatapolOrgsPolicyTaxonomiesDeleteRequest( name=name)) | Makes an API call to delete a taxonomy.
Args:
name: Resource name of the taxonomy.
Returns:
An Operation message which can be used to check on the progress of the
project creation. | 625941f0566aa707497f4af0 |
def read_s3_wrapper(func: Callable, config: Configuration) -> Callable: <NEW_LINE> <INDENT> @functools.wraps(func) <NEW_LINE> def wrapper(self, request: requests.Request, full_url, headers): <NEW_LINE> <INDENT> if request.method in ("GET", "HEAD"): <NEW_LINE> <INDENT> parsed_url = urlparse(full_url) <NEW_LINE> if is_re... | :param func: ResponseObject._<resource>_response method
:param config: The application level configuration
:return: Wrapped ResponseObject._<resource>_response method
Qu'est ce que fuck
This will attempt a normal read from mock S3, and if that throws and exception
it will try to read from the real S3. If that fails, ... | 625941f099fddb7c1c9de91d |
def _compute_loss(self, logits, targets, tgt_lang=None): <NEW_LINE> <INDENT> label_smoothing = self.label_smoothing if self.training else 0.0 <NEW_LINE> if isinstance(self.output_size, dict): <NEW_LINE> <INDENT> assert tgt_lang is not None, "A language ID is required for this softmax" <NEW_LINE> vocab_size = self.outpu... | :param logits: T x B x V or B x T x V tensor (output of decoder)
:param targets: T x B x V or B x T target tensor
:param tgt_lang: unit tensor
:return: | 625941f0293b9510aa2c381f |
def unpack_dtype(x): <NEW_LINE> <INDENT> return np.dtype(unpickle_from_array(x)) | Unpack dtype from a numpy array | 625941f0cad5886f8bd27567 |
def start(self, cfg): <NEW_LINE> <INDENT> logger.setLevel(cfg.get_debug_level()) <NEW_LINE> start_time = timeit.default_timer() <NEW_LINE> uri = create_mongodb_uri_string(cfg.user, cfg.password, cfg.host, cfg.port, cfg.authentication_db, cfg.ssl_enabled) <NEW_LINE> connect(cfg.database, host=uri) <NEW_LINE> try: <NEW_L... | Starts the program
:param cfg: configuration of class :class:`mailingshark.config.Config` | 625941f0f9cc0f698b140b85 |
def get_available_letters(letters_guessed): <NEW_LINE> <INDENT> return "".join([x for x in string.ascii_lowercase if x not in set(letters_guessed)]) | letters_guessed: list (of letters), which letters have been guessed so far
returns: string (of letters), comprised of letters that represents which letters have not
yet been guessed. | 625941f082261d6c526aba37 |
def wafFluxForme2(Ul, Ur, F, c): <NEW_LINE> <INDENT> flux = 0.5*(fluxC(Ul) + fluxC(Ur)) <NEW_LINE> for k in range(3): <NEW_LINE> <INDENT> DF = (0.5 * c[k+1]) * (F[k+1] - F[k]) <NEW_LINE> flux = flux - DF <NEW_LINE> <DEDENT> return flux | Forme2 : F = 0.5*(F(Ul) - F(Ur)) - 0.5*sum(c(k)*Delta_F(k))
| 625941f07b25080760e399e5 |
def ships(self) -> list: <NEW_LINE> <INDENT> return [obj for obj in self.map_objs if obj.ship or obj.torpedo_boat] | Return a list of map_objs that includes all shis currently in the match
Returns:
List of map_objs of found ships | 625941f0e64d504609d74dcf |
def is_game_over(self): <NEW_LINE> <INDENT> if self.board.game.is_winner(self.board.game.active_player) or self.board.game.is_loser(self.board.game.active_player): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False | return True if game over | 625941f0796e427e537b0b5a |
def _post(self, params: dict) -> dict: <NEW_LINE> <INDENT> upload_url = params[fields.upload_url] <NEW_LINE> project_id = str(params[fields.project]) <NEW_LINE> basename = os.path.basename(params[fields.name]) <NEW_LINE> filename, extension = os.path.splitext(basename) <NEW_LINE> new_filename = filename + extension <NE... | Saves the uploaded report file into the project's permanent storage
| 625941f0851cf427c661aa99 |
def RegisterFront(self, pszFrontAddress): <NEW_LINE> <INDENT> pass | 注册前置机网络地址
@param pszFrontAddress:前置机网络地址。
@remark 网络地址的格式为:“protocol:
ipaddress:port”,如:”tcp:
127.0.0.1:17001”。
@remark “tcp”代表传输协议,“127.0.0.1”代表服务器地址。”17001”代表服务器端口号。 | 625941f0d58c6744b42581ed |
def readlsb(data): <NEW_LINE> <INDENT> res=0 <NEW_LINE> shift=0 <NEW_LINE> for i in data: <NEW_LINE> <INDENT> res|=ord(i)<<shift <NEW_LINE> shift+=8 <NEW_LINE> <DEDENT> return res | Read binary data in lsb | 625941f091f36d47f21aca88 |
def test_add_get_remove_constraints(self): <NEW_LINE> <INDENT> clerk = self.clerk <NEW_LINE> pos_1, pos_2, pos_3 = [-2, 0, 0], [2, 0, 0], [6, 0, 0] <NEW_LINE> body_1 = getRigidBody(position=pos_1) <NEW_LINE> body_2 = getRigidBody(position=pos_2) <NEW_LINE> body_3 = getRigidBody(position=pos_3) <NEW_LINE> tID = '_templa... | Create some bodies. Then add/query/remove constraints.
This test only verifies that the Igor interface works. It does *not*
verify that the objects are really linked in the actual simulation. | 625941f050485f2cf553d32b |
def __init__(self, description=None, accessKeyType=None, accessKey=None): <NEW_LINE> <INDENT> self.description = description <NEW_LINE> self.accessKeyType = accessKeyType <NEW_LINE> self.accessKey = accessKey | :param description: (Optional) 描述
:param accessKeyType: (Optional) 密钥类型
:param accessKey: (Optional) Access Key | 625941f07cff6e4e81117f15 |
def input_signature(self): <NEW_LINE> <INDENT> return _Research_swig.rotation_cc_sptr_input_signature(self) | input_signature(rotation_cc_sptr self) -> io_signature_sptr | 625941f03539df3088e2e8db |
def testAddFollowersAfterRemoveViewpoint(self): <NEW_LINE> <INDENT> self._tester.RemoveViewpoint(self._cookie2, self._new_vp_id) <NEW_LINE> self._tester.AddFollowers(self._cookie, self._new_vp_id, ['Email:extra.user1@emailscrubbed.com']) | Test revival of removed follower after adding follower to viewpoint. | 625941f0b57a9660fec33e1c |
def run(): <NEW_LINE> <INDENT> interface = sop.interface <NEW_LINE> pktfilter = sop.filter <NEW_LINE> if sop.creds not in ('y', 'n'): <NEW_LINE> <INDENT> print(bc.FAIL + '\t[-] Wrong parameter in creds - only "y" and "n" is allowed.' + bc.ENDC) <NEW_LINE> return None <NEW_LINE> <DEDENT> if sop.ignore not in ('y', 'n')... | The main run function. | 625941f0be7bc26dc91cdb84 |
def test_if_a_person_name_is_correct(self): <NEW_LINE> <INDENT> paul = Person('Paul', 'Othis') <NEW_LINE> self.assertEqual('I am Paul Othis', paul.full_name()) | Test if the person name comprised of the first name and second name | 625941f00383005118ecfb70 |
def __init__(self, position_x, position_y): <NEW_LINE> <INDENT> self.position_x = position_x <NEW_LINE> self.position_y = position_y <NEW_LINE> self.position = (position_x, position_y) <NEW_LINE> self.item_is_on = True <NEW_LINE> self.collected = False | Item class constructor. | 625941f010dbd63aa1bd3132 |
def example_2_opposite(): <NEW_LINE> <INDENT> g = gen.opposite_priorities(io.load_generalized_from_file("assets/strong parity/example_2.txt")) <NEW_LINE> (a,c) = gp.generalized_parity_solver(g) <NEW_LINE> return op.are_lists_equal(a , []) and op.are_lists_equal(c , [1, 3, 4, 2]) | Solves a simple example. | 625941f0293b9510aa2c3820 |
def get_remotes(self): <NEW_LINE> <INDENT> remotes = set() <NEW_LINE> for line in self._do(['remote', '-v'], as_lines=True): <NEW_LINE> <INDENT> parts = line.split('\t') <NEW_LINE> remotes.add(Remote(parts[0], parts[1])) <NEW_LINE> <DEDENT> return remotes | Retrieve all remotes known in the local repository as a set of Remote objects. | 625941f01f037a2d8b94678c |
def grid_values(grid_string, blanks='.'): <NEW_LINE> <INDENT> values = [] <NEW_LINE> all_digits = '123456789' <NEW_LINE> for c in grid_string: <NEW_LINE> <INDENT> if c == '.': <NEW_LINE> <INDENT> values.append(blanks) <NEW_LINE> <DEDENT> elif c in all_digits: <NEW_LINE> <INDENT> values.append(c) <NEW_LINE> <DEDENT> <DE... | Convert grid into a dict of {square: char} with '123456789' for empties.
Args:
grid_string - A grid in string form.
blanks - what string to fill in the blanks with
Returns:
A grid in dictionary form
Keys: The boxes, e.g., 'A1'
Values: The value in each box, e.g., '8'. If the box has no value... | 625941f03c8af77a43ae3d37 |
def Binomial_Coefficient_Modulo(n: int, r: int, Mod:int): <NEW_LINE> <INDENT> assert Mod>0 <NEW_LINE> if r<0 or n<r: <NEW_LINE> <INDENT> return Modulo(0,Mod) <NEW_LINE> <DEDENT> X=Y=1 <NEW_LINE> r=min(r,n-r) <NEW_LINE> for i in range(r): <NEW_LINE> <INDENT> X*=n-i; X%=Mod <NEW_LINE> Y*=r-i; Y%=Mod <NEW_LINE> <DEDENT> r... | nCr (mod Mod) を愚直な方法で求める.
[入力]
n, r, Mod: 整数
Mod>0
[出力]
nCr (mod Mod)
[計算量]
O(r) | 625941f0711fe17d825428ee |
def func8(): <NEW_LINE> <INDENT> from functools import partial <NEW_LINE> RECORD_SIZE = 32 <NEW_LINE> with open(txt_file_name, 'r') as f: <NEW_LINE> <INDENT> records = iter(partial(f.read, RECORD_SIZE), '') <NEW_LINE> for r in records: <NEW_LINE> <INDENT> print(r) | 对固定大小的记录进行迭代
functools.partial()
iter()哨兵模式 | 625941f0bf627c535bc1375f |
def tokenize(input): <NEW_LINE> <INDENT> tokens = [] <NEW_LINE> for line in input: <NEW_LINE> <INDENT> tokens += word_tokenize(line) <NEW_LINE> <DEDENT> return tokens | Tokenize a plain text file.
Returns a list of tokens. | 625941f0f9cc0f698b140b86 |
def spectral_matrix_xy(Hw, cov): <NEW_LINE> <INDENT> nw = Hw.shape[-1] <NEW_LINE> Sw = np.empty( (2,2,nw), 'D') <NEW_LINE> t00 = cov[0,0]*Hw[0,0].conj() + cov[0,1]*Hw[0,1].conj() <NEW_LINE> t01 = cov[0,0]*Hw[1,0].conj() + cov[0,1]*Hw[1,1].conj() <NEW_LINE> t10 = cov[1,0]*Hw[0,0].conj() + cov[1,1]*Hw[0,1].conj() <NEW_LI... | Compute the spectral matrix S(w), from the convention:
X[t] + sum_{k=1}^P a[k]X[t-k] = Err[t]
The formulation follows from Ding, Chen, Bressler 2008,
pg 6 eqs (11) to (15)
The transfer function H(w) should be computed first from
transfer_function_xy()
Parameters
----------
Hw : ndarray (2, 2, Nfreqs)
Pre-compute... | 625941f060cbc95b062c6ad3 |
def myAtoi(self, s): <NEW_LINE> <INDENT> ls = list(s.strip()) <NEW_LINE> if len(ls) == 0 : return 0 <NEW_LINE> start = 0 <NEW_LINE> sign = -1 if ls[0] == '-' else 1 <NEW_LINE> if ls[0] in ['-','+'] : start = 1 <NEW_LINE> ret, i = 0, start <NEW_LINE> while i < len(ls) and ls[i].isdigit() : <NEW_LINE> <INDENT> ret = ret*... | :type str: str
:rtype: int | 625941f0be8e80087fb211c9 |
def load_map(self, file_path): <NEW_LINE> <INDENT> map_matrix = numpy.loadtxt(file_path, dtype=int) <NEW_LINE> self.path.clear() <NEW_LINE> self.wall.clear() <NEW_LINE> self.set_map_size(map_matrix.shape[1], map_matrix.shape[0]) <NEW_LINE> if len(numpy.argwhere(map_matrix == RABBIT)): <NEW_LINE> <INDENT> self.set_rabbi... | read the map from a numpy matrix | 625941f063f4b57ef0001698 |
@timer("check compression integrity") <NEW_LINE> def check_compression_integrity(orignal_file, compressed_file): <NEW_LINE> <INDENT> orig_font = ttLib.TTFont(orignal_file) <NEW_LINE> orig_gset = orig_font.getGlyphSet() <NEW_LINE> comp_font = ttLib.TTFont(compressed_file) <NEW_LINE> comp_gset = comp_font.getGlyphSet() <... | Compares two fonts to confirm they are functionally equivalent | 625941f05fc7496912cc3f0d |
def __init__(self, port_name='AppDefault'): <NEW_LINE> <INDENT> self._bakend = None <NEW_LINE> self._port_name = port_name <NEW_LINE> self._port = None | :param port_name: the port name
The port name can be:
* SysDefault - the system default port
* AppDefault - the app default port defined in the config file
* <port_name> - the port name | 625941f031939e2706e4d3f1 |
def downstream(self, request): <NEW_LINE> <INDENT> return NotImplemented | *** MANDATORY ***
Invoked when manufacturer's api intends to communicate with Muzzley's platform
to update device's information.
Receives,
request - A flask.request object received from manufacturer's API.
Returns a tuple as (case, data),
case - Expecting a dictionary with keys 'device_id' or 'channel_id', 'c... | 625941f0656771135c3ebe06 |
def testQRSpecificMatrixUseLast(self): <NEW_LINE> <INDENT> A = np.array([[12, -51, 4], [6, 167, -68], [-4, 24, -41]]) <NEW_LINE> Q, R, P = polyopt.linalg.qr(A, useLast=True) <NEW_LINE> self.assertLessEqual(np.linalg.norm(np.dot(Q, R) - A[:, P]), 1e-3) <NEW_LINE> self.assertEqual(P[0], 2) | Choosen matrix to dempose testing. | 625941f0bde94217f368337c |
def read_deductions_file(self, file_name: str) -> pd.DataFrame: <NEW_LINE> <INDENT> headers = ['Amount', 'Description'] <NEW_LINE> dat_type = [np.float32, str] <NEW_LINE> df = self.read_csv_columns_by_headers(file_name, headers, dat_type) <NEW_LINE> return df | :param file_name: The name and locations of the Deductions.csv
file
:return df: A pandas dataframe containing the contents of the
Deductions file.
This function reads the Deductions.csv file, which contains
all paycheck deductions. It is assumed that these debits are
deduction from t... | 625941f0a934411ee3751c25 |
def get_top_ngrams(self, max_ngrams=20): <NEW_LINE> <INDENT> freqs = [(ngram, self.training_data.getcol(idx).sum()) for ngram, idx in self.vocabulary.items()] <NEW_LINE> top_ngrams = sorted (freqs, key = lambda x: -x[1]) <NEW_LINE> if len(top_ngrams) >= max_ngrams: <NEW_LINE> <INDENT> return top_ngrams[:max_ngrams] <NE... | Get the top ngrams extracted from some dataset.
Calculate the ngrams weight based on the sum of
the respective tfidf or count value in the respective
column in the document term matrix.
Parameters
----------
max_ngrams : int
Max number of top ngrams to be retrived.
Returns
-------
top_ngrams : list ... | 625941f09f2886367277ae18 |
def test_IPv6_resource_reserved_deletion(self): <NEW_LINE> <INDENT> self.ipsv6_in_ix = mommy.make(IPv6Address, ix=self.ix, _quantity=1) <NEW_LINE> self.ipsv6_in_ix[0].reserve_this() <NEW_LINE> with self.assertRaises(ValidationError): <NEW_LINE> <INDENT> self.ipsv6_in_ix[0].delete() | Tries to delete a reserved resource
Returns: | 625941f05510c4643540f965 |
def reverseList(self, head): <NEW_LINE> <INDENT> prev = None <NEW_LINE> while head: <NEW_LINE> <INDENT> lnext = head.next <NEW_LINE> head.next = prev <NEW_LINE> prev = head <NEW_LINE> head = lnext <NEW_LINE> <DEDENT> return prev | 迭代
:type head: ListNode
:rtype: ListNode | 625941f05510c4643540f966 |
def add_leverage_by_conditions(self, new_positions): <NEW_LINE> <INDENT> for index, coin_data_to_invest in new_positions.copy().iterrows(): <NEW_LINE> <INDENT> if coin_data_to_invest['order_type'] == Consts.LONG: <NEW_LINE> <INDENT> if coin_data_to_invest[Consts.PROB_POSITIVE_HEADER] >= self.min_prob_for_leverage: <NEW... | if leverage condition is bigger then the prob_positive (in long case) or the prob_negative (in short case) then adds to leverage column the amount.
:param new_positions: df
:return: new_positions df with leverage column accordingly | 625941f05fdd1c0f98dc07c5 |
def _gen_L1_itemsets(self): <NEW_LINE> <INDENT> items = self._db.loc[:,self._db.sum(axis=0)>=self._minsup].columns <NEW_LINE> support = self._db.iloc[:,items].sum(axis=0) <NEW_LINE> for item,s in zip(items, support): <NEW_LINE> <INDENT> d = {"k": 1, "id": self._itemset_id, "itemset": item, "support": s} <NEW_LINE> self... | Creates L1 large itemsets as list of dictionaries. | 625941f099cbb53fe6793175 |
def unlock(self, layer, coord, auth, format): <NEW_LINE> <INDENT> mem = Client(self.servers) <NEW_LINE> key = tile_key(layer, coord, auth, format, self.revision, self.key_prefix) <NEW_LINE> mem.delete(key+'-lock') <NEW_LINE> mem.disconnect_all() | Release a cache lock for this tile.
| 625941f06fece00bbac2dcd6 |
def __init__(self, x, y): <NEW_LINE> <INDENT> self.node_x = x <NEW_LINE> self.node_y = y | Constructor.
:param node_x: X tile position of node.
:param node_y: Y tile position of node. | 625941f085dfad0860c3b3ed |
def printValues(starts,ends,lengths, areas): <NEW_LINE> <INDENT> line0 = '{0:<11}|{1:^10s}|{2:^10s}' <NEW_LINE> iteratedLine0 = '{0:>2d} ... {1:>3d} |{2:<10.3e}|{3:<10.3e}' <NEW_LINE> iteratedLine1 = '-'* 11 + '+' + '-'* 10 + '+' + '-'* 10 <NEW_LINE> print() <NEW_LINE> print(line0.format("start/end","length (m)"... | This function prints the output, which contains the data of all segments.
There are 10 segments total, according to the main() function.
Each segment will have data of:
start/end - which x values for starting point and ending point
length - length of the particular segment in m
area - surface area of the particular se... | 625941f04d74a7450ccd4755 |
def is_home_good(self, bar_results): <NEW_LINE> <INDENT> return not reduce(lambda x, y: x or y, bar_results) | bar_results: list containing the flag that indicates whether or not it
was good to go to the given bar
returns: true if no bar had more than the threshold | 625941f055399d3f05588c48 |
def calculate(gross_pay, fed_tax_rate, state_tax_rate): <NEW_LINE> <INDENT> fed_tax = gross_pay * fed_tax_rate <NEW_LINE> state_tax = gross_pay * state_tax_rate <NEW_LINE> netpay = gross_pay - fed_tax_rate - state_tax_rate <NEW_LINE> print() <NEW_LINE> print("The gross pay is: ", gross_pay) <NEW_LINE> print("The federa... | This function takes three parameters and outputs the results of calculating
net pay. It prints the results of these calculations.
You can assume that all input is correct (there is not user error) | 625941f08c0ade5d55d3ef50 |
def differs(self, master, master_vers, local_vers, centre, subcentre): <NEW_LINE> <INDENT> return (self._master != master or self._vers_master != master_vers or self._vers_local != local_vers or self._centre != centre or self._centre_sub != subcentre) | Test if the version etc. numbers differ from the table currently loaded | 625941f0283ffb24f3c55e8c |
def labels_to_string(self): <NEW_LINE> <INDENT> if self.layout.count() > 0: <NEW_LINE> <INDENT> labels = self.layout.itemAt(0).widget().text() <NEW_LINE> for i in range(1, self.layout.count()): <NEW_LINE> <INDENT> labels = labels + ', ' + self.layout.itemAt(i).widget().text() <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LIN... | Transforms a set of labels into a single string.
returns:
- A string representation of the widget's labels | 625941f030bbd722463cc35a |
def get_pandas_df(self, sql, parameters=None): <NEW_LINE> <INDENT> import pandas.io.sql as psql <NEW_LINE> conn = self.get_conn() <NEW_LINE> df = psql.read_sql(sql, con=conn) <NEW_LINE> conn.close() <NEW_LINE> return df | Executes the sql and returns a pandas dataframe | 625941f03eb6a72ae02eca7d |
@app.route("/api/v1.0/tobs") <NEW_LINE> def tobs(): <NEW_LINE> <INDENT> first_date_tobs = session.query(measurements.tobs,measurements.date).order_by(measurements.date.desc()).first() <NEW_LINE> last_date_tobs = datetime.datetime.strptime(str(first_date_tobs.date), '%Y-%m-%d') - datetime.timedelta(days=365) <NEW_LINE> ... | Returns a list of temperature observation data for the previous year | 625941f0d6c5a102081445e0 |
def uccsd_operator(single_amplitudes, double_amplitudes, anti_hermitian=True): <NEW_LINE> <INDENT> uccsd_generator = FermionOperator() <NEW_LINE> if (isinstance(single_amplitudes, numpy.ndarray) or isinstance(double_amplitudes, numpy.ndarray)): <NEW_LINE> <INDENT> single_amplitudes, double_amplitudes = uccsd_convert_am... | Create a fermionic operator that is the generator of uccsd.
This a the most straight-forward method to generate UCCSD operators,
however it is slightly inefficient. In particular, it parameterizes
all possible excitations, so it represents a generalized unitary coupled
cluster ansatz, but also does not explicitly enfo... | 625941f00383005118ecfb71 |
def p_expr_add(p): <NEW_LINE> <INDENT> p[0] = p[1] + p[3] | expr : expr PLUS expr | 625941f063b5f9789fde7677 |
def removeLastPoint(self): <NEW_LINE> <INDENT> if self.path.nodeSet[-1] == 'cycle': <NEW_LINE> <INDENT> del self.path.nodeSet[-2] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> del self.path.nodeSet[-1] <NEW_LINE> <DEDENT> del self.path.linkSet[-1] <NEW_LINE> self.path.computed = False <NEW_LINE> self.asyfied = False | Remove the last point in the path. If the path is cyclic, remove the node before the 'cycle'
node | 625941f029b78933be1e5c35 |
def __init__(self, iri: IRI): <NEW_LINE> <INDENT> self._iri = iri | Gets an instance of OWLDataProperty that has the specified IRI.
Args:
iri: The IRI. | 625941f067a9b606de4a8447 |
def dssm(seq_length = 5, num_neg = 6, V = 10, embedding_dim = 5): <NEW_LINE> <INDENT> query_input = Input(shape=(seq_length,)) <NEW_LINE> query, embedding_layer = bilstm_attention(query_input, V = V, embedding_dim = embedding_dim, seq_l... | Input:
Output: | 625941f0d18da76e23532a6e |
def process_file(n, prefix): <NEW_LINE> <INDENT> filename = ngram_filename(n, prefix) <NEW_LINE> path = os.path.join(args.input, filename) <NEW_LINE> print_status("Processing", filename) <NEW_LINE> out = dict() <NEW_LINE> with open(path, "r") as i: <NEW_LINE> <INDENT> for line in i: <NEW_LINE> <INDENT> l_original = lin... | Process a single file. Since ngrams will change size and partition, they
will be appended to existing files containing ngram counts from other prefix
files. As a result, changes introduces by partial processing of a file
cannot be rolled back easily -- there is no progress tracking, the whole
script needs to be restart... | 625941f07d847024c06be851 |
def unzip_stream(stream): <NEW_LINE> <INDENT> sio = StringIO.StringIO() <NEW_LINE> sio.write(stream.read()) <NEW_LINE> sio.seek(0) <NEW_LINE> return gzip.GzipFile(fileobj=sio, mode='rb') | Unzip the stream | 625941f00a366e3fb873edb0 |
def test_invalid_host(self): <NEW_LINE> <INDENT> import requests <NEW_LINE> fsapi = FSAPIDevice('INVALID_URL', '1234') <NEW_LINE> self.assertRaises(requests.exceptions.MissingSchema, fsapi.update) | Test that a host with a valid url is set when using a conf. | 625941f038b623060ff0b37d |
def _is_hashtag_comment(line): <NEW_LINE> <INDENT> comment_block = False <NEW_LINE> for letter in line: <NEW_LINE> <INDENT> if letter == '\'' or letter == '\"': <NEW_LINE> <INDENT> comment_block = False if comment_block else True <NEW_LINE> <DEDENT> if letter == '#' and comment_block is False: <NEW_LINE> <INDENT> retur... | Check if the '#' is a comment or into a string
:param line: line to control
:return True/False: boolean to indicate if '#' is a comment or into a string | 625941f021bff66bcd684ede |
def __init__(cls, name, bases, dct): <NEW_LINE> <INDENT> super(MetaOandaData, cls).__init__(name, bases, dct) <NEW_LINE> oandastore.OandaStore.DataCls = cls | Class has already been created ... register | 625941f0d486a94d0b98e6d7 |
def rm_pot(potential, puzzle, tl, br): <NEW_LINE> <INDENT> for y in range(tl[1], br[1]+1): <NEW_LINE> <INDENT> for x in range(tl[0], br[0]+1): <NEW_LINE> <INDENT> if puzzle[y][x] in potential: <NEW_LINE> <INDENT> potential.remove(puzzle[y][x]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return potential | Check through the puzzle array in the range delimited by top left (tl)
and bottom right (br) for values in 'potential'. Any value found that is
in 'potential' is removed so only missing values remain when it is
returned. | 625941f0be383301e01b5a0b |
def test_eventreg_removeuserfromall(self): <NEW_LINE> <INDENT> pass | Test case for eventreg_removeuserfromall
Remove a user from the registration to all courses # noqa: E501 | 625941f08a349b6b435e8703 |
def _get_account_by_kind(self, kind, company=None, silent=True): <NEW_LINE> <INDENT> Account = POOL.get('account.account') <NEW_LINE> Company = POOL.get('company.company') <NEW_LINE> if company is None: <NEW_LINE> <INDENT> company, = Company.search([], limit=1) <NEW_LINE> <DEDENT> accounts = Account.search([ ('kind', '... | Returns an account with given spec
:param kind: receivable/payable/expense/revenue
:param silent: dont raise error if account is not found | 625941f0d7e4931a7ee9e4b0 |
def _renamePathname(self, oldname, newname): <NEW_LINE> <INDENT> from os.path import join, isdir, normpath <NEW_LINE> self.log.info('Renaming %r to %r...', oldname, newname) <NEW_LINE> if (isdir(join(self.repository.basedir, normpath(oldname))) or isdir(join(self.repository.basedir, normpath(newname)))): <NEW_LINE> <IN... | Rename an entry | 625941f00fa83653e4657548 |
def make_merge(lst1, lst2): <NEW_LINE> <INDENT> result_list = [] <NEW_LINE> while len(lst1) > 0 or len(lst2) > 0: <NEW_LINE> <INDENT> if lst1 == []: <NEW_LINE> <INDENT> result_list.append(lst2.pop(0)) | Merge lists | 625941f099fddb7c1c9de91f |
def test_push_mentions_notifications_with_list(self): <NEW_LINE> <INDENT> mentions = ["user1", "user2"] <NEW_LINE> notice_txt = "{} mentioned you in a post for {}".format( self.admin.username, self.module.module_code ) <NEW_LINE> output = self.func(mentions, self.admin, self.entry) <NEW_LINE> self.assertEquals(output, ... | Test push mentions notifications with list option | 625941f0627d3e7fe0d693e3 |
def get_all_games(self): <NEW_LINE> <INDENT> all_games = {} <NEW_LINE> current_games = self.__get_current_games() <NEW_LINE> for current_game in current_games['TitleInfoList']['TitleInfo']: <NEW_LINE> <INDENT> path = urlparse(current_game['LinkURL']).path <NEW_LINE> head, gameid = os.path.split(path) <NEW_LINE> if chec... | Get all games in japan.
| 625941f0a4f1c619b28b05bc |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.