code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def test_remove_all_solar_no_solar_present(self): <NEW_LINE> <INDENT> mgr = glm.GLMManager(model=TEST_FILE) <NEW_LINE> solar = mgr.get_objects_by_type(object_type='solar') <NEW_LINE> self.assertIsNone(solar) <NEW_LINE> with self.assertLogs(logger=mgr.log, level='WARNING'): <NEW_LINE> <INDENT> mgr.remove_all_solar() | Test remove_all_solar operates correctly when the initial
model does not have any solar in it. | 625941f582261d6c526abadb |
def _exploration(model_z, state, epsilon, game, replay_memory, output_size): <NEW_LINE> <INDENT> model_z.eval() <NEW_LINE> state = process_state(state) <NEW_LINE> action = construct_action(epsilon, model_z, state, output_size) <NEW_LINE> new_state, reward, finish = game.action(torch.argmax(action)) <NEW_LINE> replay_me... | Exploring the game possibilities to learn new strategies
:param model_z: The model that is being trained
:param state: the current state of the game
:param epsilon: the probability of exploration versus optimized playing
:param game: the game
:param replay_memory: the memory of previous games
:return: the new state of ... | 625941f576e4537e8c351caa |
def _check_init(A, shape, whom): <NEW_LINE> <INDENT> A = check_array(A) <NEW_LINE> if np.shape(A) != shape: <NEW_LINE> <INDENT> raise ValueError('Array with wrong shape passed to %s. Expected %s, ' 'but got %s ' % (whom, shape, np.shape(A))) <NEW_LINE> <DEDENT> check_non_negative(A, whom) <NEW_LINE> if np.max(A) == 0: ... | Check initialization of A.
Method copied from scikit-learn NMF source code | 625941f5656771135c3ebea8 |
@bp.route('/lastclobber/branch/by-builder/<string:branch>', methods=['GET']) <NEW_LINE> @apimethod({unicode: [rest.ClobberTime]}, unicode) <NEW_LINE> def lastclobber_by_builder(branch): <NEW_LINE> <INDENT> session = g.db.session(DB_DECLARATIVE_BASE) <NEW_LINE> max_ct_sub_query = session.query( func.max(ClobberTime.last... | Return a dictionary of most recent ClobberTimes grouped by buildername. | 625941f5097d151d1a223487 |
def get_redirect_url(self, pk): <NEW_LINE> <INDENT> quest = Quest.objects.get(pk=pk) <NEW_LINE> if self.request.user != quest.relation.quester or quest.status != 'A': <NEW_LINE> <INDENT> return reverse('quests:list') <NEW_LINE> <DEDENT> quest.status = 'M' <NEW_LINE> quest.save() <NEW_LINE> messages.add_message(self.req... | Checks if the current user has permission to complete the quest.
Completes the quest and informs the owner if successful.
Returns the redirect URL as a string. | 625941f5be383301e01b5aab |
def wrap_cls( klass: Type[ObjectT], *, delay: bool = False, strict: StrictModeT = STRICT_MODE, jsonschema: bool = True, serde: SerdeFlags = SerdeFlags(), always: bool = None, ) -> Type[WrappedObjectT[ObjectT]]: <NEW_LINE> <INDENT> def cls_wrapper(cls_: Type[ObjectT]) -> Type[WrappedObjectT[ObjectT]]: <NEW_LINE> <INDENT... | Wrap a class to automatically enforce type-coercion on init.
Notes
-----
While `Coercer.wrap` will work with classes alone, it changes the signature of the
object to a function, there-by breaking inheritance. This follows a similar pattern to
:func:`dataclasses.dataclasses`, which executes the function when wrapped, p... | 625941f5a8ecb033257d36fc |
def invalidate_star_import_cache(module, only_main=False): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> t, mods = star_import_cache[module] <NEW_LINE> del star_import_cache[module] <NEW_LINE> for m in mods: <NEW_LINE> <INDENT> invalidate_star_import_cache(m, only_main=True) <NEW_LINE> <DEDENT> <DEDENT> except KeyError:... | Important if some new modules are being reparsed | 625941f5f9cc0f698b140c27 |
def attribute( self, inputs: TensorOrTupleOfTensorsGeneric, target: TargetType = None, additional_forward_args: Any = None, ) -> TensorOrTupleOfTensorsGeneric: <NEW_LINE> <INDENT> is_inputs_tuple = _is_tuple(inputs) <NEW_LINE> inputs = _format_input(inputs) <NEW_LINE> gradient_mask = apply_gradient_requirements(inputs)... | Computes attribution by overriding relu gradients. Based on constructor
flag use_relu_grad_output, performs either GuidedBackpropagation if False
and Deconvolution if True. This class is the parent class of both these
methods, more information on usage can be found in the docstrings for each
implementing class. | 625941f54527f215b584ca83 |
def find_best_answer_for_passage(self, start_probs, end_probs, passage_len=None): <NEW_LINE> <INDENT> if passage_len is None: <NEW_LINE> <INDENT> passage_len = len(start_probs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> passage_len = min(len(start_probs), passage_len) <NEW_LINE> <DEDENT> best_start, best_end, max_pr... | Finds the best answer with the maximum start_prob * end_prob from a single passage | 625941f5283ffb24f3c55f2c |
def test_permissions(self): <NEW_LINE> <INDENT> path = "/test" <NEW_LINE> openid = "openid_test_permissions" <NEW_LINE> permission = WeChatAuthenticated() <NEW_LINE> user_dict = dict(openid=openid) <NEW_LINE> WeChatUser.objects.upsert_by_dict(user_dict, self.app) <NEW_LINE> request = self._create_request(path) <NEW_LIN... | 测试WeChatAuthenticated权限 | 625941f5ab23a570cc2507ba |
def deactive_previous_agents(self,last_agent): <NEW_LINE> <INDENT> for agent in self.agents: <NEW_LINE> <INDENT> if agent != last_agent: <NEW_LINE> <INDENT> agent.s2close_only() | 仅用于只允许出现单agent的情形, 把最新agent之外的所有其它均关闭
将所有last_group之前的agent都设定为CLOSE_ONLY
如有必要,应该由子类继承check_agent_state时调用 | 625941f530bbd722463cc3fc |
def get_primary_axis(id_axis, first_child_delay): <NEW_LINE> <INDENT> if id_axis == 'MS': <NEW_LINE> <INDENT> primary_id_axis = id_axis <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> id_axis = id_axis[1:] <NEW_LINE> while '.' in id_axis: <NEW_LINE> <INDENT> id_axis_split = id_axis.rsplit('.', 2) <NEW_LINE> last_pos = in... | Calculate the primary axis of *id_axis*.
:Parameters:
- `id_axis` (:class:`str`) - the botanical position of the axis.
- `first_child_delay` (:class:`int`) - the delay between the axis and its
first child.
:Returns:
the primary axis of *id_axis*.
:Returns Type:
:class:`str`
:Exa... | 625941f5d7e4931a7ee9e552 |
def apply(self, page): <NEW_LINE> <INDENT> assert len(page.system) == 1 <NEW_LINE> systems_map = dict( (i, (i, i)) for i in moves.xrange(len(page.system[0].staff))) <NEW_LINE> for start, end in zip(self.barline_staff_start, self.barline_staff_end): <NEW_LINE> <INDENT> for staff in moves.xrange(start, end + 1): <NEW_LIN... | Splits the staves in the page into systems with barlines. | 625941f5be7bc26dc91cdc26 |
def tenant(self, request): <NEW_LINE> <INDENT> context = request.context <NEW_LINE> if not context.tenant_id: <NEW_LINE> <INDENT> raise webob.exc.HTTPBadRequest('invalid tenant') <NEW_LINE> <DEDENT> return {'tenant': {'tenant_id': context.tenant_id}} | Retrieve the tenant info in context. | 625941f5b7558d58953c5538 |
def move_by_arrow_keys(accel_group, acceleratable, keyval, modifier): <NEW_LINE> <INDENT> key, view = Gdk.keyval_name(keyval), map_view <NEW_LINE> factor = (0.45 if key in ('Up', 'Left') else 0.55) <NEW_LINE> lat = view.get_center_latitude() <NEW_LINE> lon = view.get_center_longitude() <NEW_LINE> if key ... | Move the map view by 5% of its length in the given direction. | 625941f55e10d32532c5f557 |
def estimate_noise(img): <NEW_LINE> <INDENT> height, width = img.shape <NEW_LINE> kernel = [[1, -2, 1], [-2, 4, -2], [1, -2, 1]] <NEW_LINE> sigma = np.sum(np.sum(np.absolute(convolve2d(img, kernel)))) <NEW_LINE> sigma = sigma * math.sqrt(0.5 * math.pi) / (6 * (width - 2) * (height - 2)) <NEW_LINE> return sigma | Returns estimated noise level, lower is better. Good images have about 0-2 | 625941f5cb5e8a47e48b80d1 |
def save_image(content): <NEW_LINE> <INDENT> file_path_name = '{0}/images/{1}.{2}'.format(os.getcwd(), md5(content).hexdigest(), 'jpg') <NEW_LINE> if not os.path.exists(file_path_name): <NEW_LINE> <INDENT> with open(file_path_name, 'wb') as f : <NEW_LINE> <INDENT> f.write(content) <NEW_LINE> f.clos... | 定义保存的图片函数,路径,文件名
- 定义下载保存图片的路径,md5()方法随机生成文件名,传入content内容为图片详情, | 625941f54f88993c3716c692 |
def compile(source, modulename='untitled', extra_args='', verbose=True, source_fn=None, extension='.f' ): <NEW_LINE> <INDENT> import tempfile <NEW_LINE> import shlex <NEW_LINE> if source_fn is None: <NEW_LINE> <INDENT> f, fname = tempfile.mkstemp(suffix=extension) <NEW_LINE> os.close(f) <NEW_LINE> <DEDENT> else: <NEW_L... | Build extension module from a Fortran 77 source string with f2py.
Parameters
----------
source : str or bytes
Fortran source of module / subroutine to compile
.. versionchanged:: 1.16.0
Accept str as well as bytes
modulename : str, optional
The name of the compiled python module
extra_args : str o... | 625941f5bf627c535bc13802 |
def playback_queue_cleared(self): <NEW_LINE> <INDENT> header = {'namespace': 'AudioPlayer', 'name': 'PlaybackQueueCleared'} <NEW_LINE> self._connection.send_event(header) | notifies AVS that the playback queue was cleared | 625941f53cc13d1c6d3c79a9 |
def get_property(self, value_name): <NEW_LINE> <INDENT> return getattr(self, value_name, 'non name') | Get properties of this class.
| 625941f5f9cc0f698b140c28 |
def delete_wim(wim_uuid): <NEW_LINE> <INDENT> url = env.ia_api + '/wims/' + wim_uuid <NEW_LINE> resp = requests.delete(url, timeout=env.timeout, headers=env.header) <NEW_LINE> env.set_return_header(resp.headers) <NEW_LINE> if resp.status_code != 200: <NEW_LINE> <INDENT> LOG.debug("Request for wims returned with " + (st... | Delete a wim.
:param wim_uuid: uuid of the wim to be deleted.
:returns: A tuple. [0] is a bool with the result. [1] is response message. | 625941f5fff4ab517eb2fa73 |
def history_add(paths): <NEW_LINE> <INDENT> state = _open_state() <NEW_LINE> if HISTORY_KEY not in state: <NEW_LINE> <INDENT> state[HISTORY_KEY] = set() <NEW_LINE> <DEDENT> state[HISTORY_KEY].add(tuple(paths)) <NEW_LINE> _save_state(state) | Indicate that the import of the album in `paths` is completed and
should not be repeated in incremental imports. | 625941f5bd1bec0571d90c61 |
def test_pvcreate(self): <NEW_LINE> <INDENT> self.assertEqual(linux_lvm.pvcreate(''), 'Error: at least one device is required') <NEW_LINE> self.assertEqual(linux_lvm.pvcreate('A'), 'A does not exist') <NEW_LINE> with patch.object(os.path, 'exists', return_value=True): <NEW_LINE> <INDENT> mock = MagicMock(return_value='... | Tests for set a physical device to be used as an LVM physical volume | 625941f521a7993f00bc832e |
def print_timing(name, start_time): <NEW_LINE> <INDENT> if debug_print_timing(): <NEW_LINE> <INDENT> print(name + " took: {:.3} s".format(timer() - start_time)) | for debugging: print elapsed time, with start_time = timer(). | 625941f5b57a9660fec33ebf |
def mask_conv2d_spatial(mask_type, height, width): <NEW_LINE> <INDENT> mask = torch.ones([1, 1, height, width]) <NEW_LINE> mask[:, :, height // 2, width // 2 + (mask_type == 'B'):] = 0 <NEW_LINE> mask[:, :, height // 2 + 1:] = 0 <NEW_LINE> return mask | Creates a mask for Conv2d such that it becomes autoregressive in
the spatial dimensions.
Input:
mask_type: str
Either 'A' or 'B'. 'A' for first layer of network, 'B' for all others.
height: int
Kernel height for layer.
width: int
Kernel width for layer.
Output:
mask: torch.Float... | 625941f532920d7e50b28808 |
def is_free(self,x,y): <NEW_LINE> <INDENT> self.insist_valid(x,y) <NEW_LINE> return self.grid[y][x] == " " | Is the cell at (x,y) free? | 625941f5a8370b7717052ecf |
def connectivity_from_range(range_tuple, close_loop=False): <NEW_LINE> <INDENT> return connectivity_from_array( np.arange(*range_tuple), close_loop=close_loop) | Build the connectivity over a range. For example, given ::
range_array = np.arange(3)
Generate the connectivity of ::
[(0, 1), (1, 2), (2, 3)]
If ``close_loop`` is true, add an extra connection from the last point to
the first. | 625941f5fb3f5b602dac3ccd |
def get_disk_info(os): <NEW_LINE> <INDENT> print() <NEW_LINE> print ("disk_info:") <NEW_LINE> if os == "Windows": <NEW_LINE> <INDENT> tmplist = [] <NEW_LINE> c = wmi.WMI () <NEW_LINE> for physical_disk in c.Win32_DiskDrive(): <NEW_LINE> <INDENT> if physical_disk.Size: <NEW_LINE> <INDENT> print ('\t' + str(physical_disk... | 获取物理磁盘信息。 | 625941f515baa723493c45ad |
def __init__(self, control): <NEW_LINE> <INDENT> self.control = control <NEW_LINE> ch = self.control.channel.split(":") <NEW_LINE> self.channel = ch[0] <NEW_LINE> self.sub_channel = int(ch[1]) <NEW_LINE> self.dio = drf.DigitalRFReader(self.control.path) <NEW_LINE> if self.control.verbose: <NEW_LINE> <INDENT> print("cha... | Initialize a data plotter for STI plotting. | 625941f592d797404e3047bf |
def append(self, msg): <NEW_LINE> <INDENT> if len(self.queue) > 0: <NEW_LINE> <INDENT> last_msg = self.queue[-1] <NEW_LINE> if msg.primary == last_msg.primary: <NEW_LINE> <INDENT> self.queue[-1] = msg <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> self.queue.append(msg) | push back and filtering with primary value
:param msg:
:return: | 625941f5fbf16365ca6f6804 |
def find_disk(vm, cmd): <NEW_LINE> <INDENT> if params.get("os_type") == "linux": <NEW_LINE> <INDENT> pattern = params.get("get_disk_pattern", "^/dev/vd[a-z]*$") <NEW_LINE> <DEDENT> elif params.get("os_type") == "windows": <NEW_LINE> <INDENT> pattern = r"^\d+" <NEW_LINE> cmd = params.get("get_disk_index", "wmic diskdriv... | Find all disks in guest. | 625941f58e7ae83300e4b601 |
def readMemory(self): <NEW_LINE> <INDENT> self.display.setText(str(self.sumInMemory)) <NEW_LINE> self.wait = True | 讀取記憶體鍵按下後的處理方法 | 625941f5ff9c53063f47c822 |
def writePushPop(self, command, segment, index): <NEW_LINE> <INDENT> if command == CommandType.C_PUSH: <NEW_LINE> <INDENT> self.__writePush(segment, index) <NEW_LINE> <DEDENT> elif command == CommandType.C_POP: <NEW_LINE> <INDENT> self.__writePop(segment, index) | Write the assembly for the provided push/pop command to the file | 625941f55fc7496912cc3fb0 |
def main(): <NEW_LINE> <INDENT> args, parser = parse_commands() <NEW_LINE> cidr = args.cidr[0].split("/") <NEW_LINE> if len(cidr) != 2: <NEW_LINE> <INDENT> print(f"\nError: incorrect notation {args.cidr}") <NEW_LINE> exit(f"{parser.format_usage()}") <NEW_LINE> <DEDENT> ipstring = cidr[0] <NEW_LINE> try: <NEW_LINE> <IND... | Verify command line arguments are valid:
- correct CIDR (i.e., dash "/") notation
- CIDR prefix is an integer
- IPv4 address is correct length
- IPv4 address is numeric
If invalid, print reason for error and usage example upon exit.
If valid, proceed with program logic. | 625941f531939e2706e4d493 |
def norm(self, ord=None): <NEW_LINE> <INDENT> vals = list(self.values()) or [0] <NEW_LINE> if self.rows == 1 or self.cols == 1: <NEW_LINE> <INDENT> if ord == 2 or ord is None: <NEW_LINE> <INDENT> return sqrt(Add(*(abs(i) ** 2 for i in vals))) <NEW_LINE> <DEDENT> elif ord == 1: <NEW_LINE> <INDENT> return Add(*(abs(i) fo... | Return the Norm of a Matrix or Vector.
In the simplest case this is the geometric size of the vector
Other norms can be specified by the ord parameter
===== ============================ ==========================
ord norm for matrices norm for vectors
===== ============================ ============... | 625941f523849d37ff7b36bc |
def findMelOnlyCommands(): <NEW_LINE> <INDENT> pass | Using maya's documentation, find commands which were not ported to python. | 625941f57b180e01f3dc4e22 |
def __init__(self, columns, refcolumns, name=None, onupdate=None, ondelete=None, deferrable=None, initially=None, use_alter=False, link_to_name=False, match=None, table=None, info=None, **dialect_kw): <NEW_LINE> <INDENT> Constraint.__init__( self, name=name, deferrable=deferrable, initially=initially, info=info, **dial... | Construct a composite-capable FOREIGN KEY.
:param columns: A sequence of local column names. The named columns
must be defined and present in the parent Table. The names should
match the ``key`` given to each column (defaults to the name) unless
``link_to_name`` is True.
:param refcolumns: A sequence of foreign... | 625941f596565a6dacc8fcfc |
@Rename('eq?') <NEW_LINE> def _eq(*args): <NEW_LINE> <INDENT> _equalSign(*args) | Tests if two things point to the same memory. | 625941f5b830903b967e9f36 |
def _is_section_end(self, line): <NEW_LINE> <INDENT> raise NotImplementedError | returns True if section end is reached | 625941f515fb5d323cde114c |
def is_event_loop_running_kivy(app=None): <NEW_LINE> <INDENT> if app is None: <NEW_LINE> <INDENT> app = get_app_kivy() <NEW_LINE> <DEDENT> if hasattr(app, '_in_event_loop'): <NEW_LINE> <INDENT> return app._in_event_loop <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> from kivy.base import EventLoop <NEW_LINE> if EventLoo... | Is the wx event loop running. | 625941f5004d5f362079a961 |
def find_subsets(original): <NEW_LINE> <INDENT> if not original: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> result.add(tuple(original)) <NEW_LINE> for num in original: <NEW_LINE> <INDENT> original.remove(num) <NEW_LINE> find_subsets(original) <NEW_LINE> original.add(num) | Adds all subsets of array to result.
| 625941f5009cb60464c639df |
def fitCCEMPhi(f, phi, ePhi=0.001, lam=1000., mpar=(0.2, 0, 1), taupar=(1e-2, 1e-5, 100), cpar=(0.25, 0, 1), empar=(1e-7, 1e-9, 1e-5), verbose=True): <NEW_LINE> <INDENT> fCCEM = PeltonPhiEM(f) <NEW_LINE> fCCEM.region(0).setParameters(*mpar) <NEW_LINE> fCCEM.region(1).setParameters(*taupar) <NEW_LINE> fCCEM.region(2).s... | Fit a Cole-Cole term with additional EM term to phase. | 625941f59f2886367277aeba |
def testConnectorsLinks(self): <NEW_LINE> <INDENT> pass | Test ConnectorsLinks | 625941f5851cf427c661ab3c |
def format_outputter(raster_dict): <NEW_LINE> <INDENT> with open("/Users/Gabe/Desktop/prism_precip_checker_output.txt", "w") as write_file: <NEW_LINE> <INDENT> write_file.write("Prism Output \n \n \n \n ") <NEW_LINE> for key, value in raster_dict.iteritems(): <NEW_LINE> <INDENT> print("value[0]", value[0]) <NEW_LINE> p... | Formats a text file of statistics for each raster of prior dates.
:param raster_dict:
:return: | 625941f5cad5886f8bd2760b |
def dispatch(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!') | dispatch span to haystack agent
| 625941f50c0af96317bb8819 |
def __randomize(items, random_state): <NEW_LINE> <INDENT> randomized_items = list(items) <NEW_LINE> random_state.shuffle(randomized_items) <NEW_LINE> return randomized_items | Returns a List containing a random permutation of items | 625941f5cdde0d52a9e5366c |
def __getitem__(self, k): <NEW_LINE> <INDENT> j = self._find_index(k, 0, len(self._table) - 1) <NEW_LINE> if j == len(self._table) or self._table[j]._key != k: <NEW_LINE> <INDENT> raise KeyError('Key Error: ' + repr(k)) <NEW_LINE> <DEDENT> return self._table[j]._value | Return value associated with key k (rasie KeyError if not found) | 625941f563b5f9789fde7719 |
def spending_by_payee(session, user, budget_id, filter=None): <NEW_LINE> <INDENT> check_session(session) <NEW_LINE> check_user(user) <NEW_LINE> _load_budget(session, user, budget_id) <NEW_LINE> q = q_report_by_payee(session, budget_id, filter=filter) <NEW_LINE> data = [] <NEW_LINE> for payee_id, amount, currency in q.a... | Report the user's spending by payee. | 625941f5d4950a0f3b08c978 |
def ToFile( message: ProtocolBuffer, path: pathlib.Path, exist_ok: bool = True, assume_filename: typing.Optional[typing.Union[str, pathlib.Path]] = None, ) -> ProtocolBuffer: <NEW_LINE> <INDENT> if not exist_ok and path.exists(): <NEW_LINE> <INDENT> raise FileExistsError(f"Refusing to overwrite {path}") <NEW_LINE> <DED... | Write a protocol buffer to a file.
This method uses attempts to guess the encoding from the path suffix,
supporting binary, text, and json formatted messages. The mapping of suffixes
to formatting is, in order:
*.txt.gz: Gzipped text format.
*.txt: Text format.
*.pbtxt.gz: Gzipped text format.
*.pbtxt:... | 625941f510dbd63aa1bd31d4 |
def set_states(self, states): <NEW_LINE> <INDENT> assert(len(states) == self.num_dof), f'Expecting {self.num_dof} D.O.F., got {len(x)}' <NEW_LINE> states = np.reshape(states, (self.num_body, 3)) <NEW_LINE> for name, idx in self.idx_dict.items(): <NEW_LINE> <INDENT> pose = states[idx] <NEW_LINE> self.bodies[name].pose =... | For a given vector, set all the D.O.F. of the system.
The D.O.F. are essentially the position and orientaiton of the rigid bodies. | 625941f563f4b57ef0001739 |
def filter_offsets(self, ra, dec, offset_filter=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> filter_dict = { 'r': {'ra': None, 'dec': None}, 'g': {'ra': None, 'dec': None}, 'i': {'ra': None, 'dec': None}, 'u': {'ra': None, 'dec': None}, 'ifu': {'ra': None, 'dec': None} } <NEW_LINE> if not offset_filter: <NEW_LIN... | Get a filter offset dictionary
:param ra:
:param dec:
:param offset_filter:
:return: | 625941f53539df3088e2e97e |
def start_turn(self): <NEW_LINE> <INDENT> self.turn += 1 <NEW_LINE> self.revealed_water = [[] for _ in range(self.num_players)] <NEW_LINE> self.removed_food = [[] for _ in range(self.num_players)] <NEW_LINE> self.orders = [[] for _ in range(self.num_players)] | Called by engine at the start of the turn | 625941f51f037a2d8b94682f |
def get_relative_path(self, path): <NEW_LINE> <INDENT> return os.path.relpath(path, self.tree.root.path) | Get the relative path according to tree root. | 625941f5f8510a7c17cf9d34 |
def post_order(self): <NEW_LINE> <INDENT> l = self.post_order_helper(self.top, []) <NEW_LINE> for num in l: <NEW_LINE> <INDENT> yield num | Return a generator of the values using post order traversal | 625941f55f7d997b871750d1 |
def _get__cmp__items(self): <NEW_LINE> <INDENT> items = [ self.arguments, self.return_type, self.has_extern, self.does_throw, self.exceptions.sort(), self.demangled_name, self.has_inline] <NEW_LINE> items.extend(self._get__cmp__call_items()) <NEW_LINE> return items | Implementation detail. | 625941f573bcbd0ca4b2c6a8 |
def is_running(self): <NEW_LINE> <INDENT> return self.socket is not None | Check if socket is open. | 625941f550485f2cf553d3cf |
def word_shuffle(self, x, l): <NEW_LINE> <INDENT> if self.shuffle_weight == 0: <NEW_LINE> <INDENT> return x, l <NEW_LINE> <DEDENT> noise = np.random.uniform(0, self.shuffle_weight, size=(x.size(0) - 1, x.size(1))) <NEW_LINE> noise[0] = -1 <NEW_LINE> assert self.shuffle_weight > 1 <NEW_LINE> x2 = x.clone() <NEW_LINE> fo... | Randomly shuffle input words.
Args:
words (LongTensor): the word ids, (seq_len, batch_size)
lengths (LongTensor): (batch_size) | 625941f5be8e80087fb2126a |
def histogram(self, img): <NEW_LINE> <INDENT> hist = [] <NEW_LINE> if self.isGrayscale(img): <NEW_LINE> <INDENT> [bins, hist_vals] = ski.exposure.histogram(img) <NEW_LINE> bins = bins.tolist() <NEW_LINE> hist_vals = hist_vals.tolist() <NEW_LINE> hist_temp = (bins, hist_vals) <NEW_LINE> hist.append(hist_temp) <NEW_LINE>... | Generates a list of histograms with intensity values for each
channel in the image.
Each item in the list consists of a 2D numpy array, in which the
first dimension is the histogram itself, and the second dimension
is the bin values. A histogram item from this list could be plotted
as plt.plot(histogram_item[1], histo... | 625941f54428ac0f6e5bae2b |
def __repr__(self): <NEW_LINE> <INDENT> def remove_unnecessary_lines(text): <NEW_LINE> <INDENT> return "\n".join([line.rstrip() for line in text.splitlines()]) <NEW_LINE> <DEDENT> self.description = remove_unnecessary_lines(self.description) <NEW_LINE> self.precode = remove_unnecessary_lines(self.precode) <NEW_LINE> se... | Returns string representation of ProblemPart. | 625941f563d6d428bbe44b24 |
def test_add_clean(self): <NEW_LINE> <INDENT> self.assertFalse(self.obj_cache.is_dirty) <NEW_LINE> self.obj_cache.add('answer', 42) <NEW_LINE> self.assertEqual(42, self.obj_cache.get('answer')) <NEW_LINE> self.assertTrue(self.obj_cache.is_dirty) <NEW_LINE> self.obj_cache.mark_clean() <NEW_LINE> self.assertFalse(self.ob... | Adding a value to the cache with the same value does not make dirty. | 625941f53317a56b8693a27b |
def svn_utf_cstring_from_utf8_ex2(*args): <NEW_LINE> <INDENT> return _core.svn_utf_cstring_from_utf8_ex2(*args) | svn_utf_cstring_from_utf8_ex2(char src, char topage, apr_pool_t pool) -> svn_error_t | 625941f5b830903b967e9f37 |
def saveCouch(self, couchUrl, couchDBName, metadata={}): <NEW_LINE> <INDENT> import WMCore.Database.CMSCouch <NEW_LINE> server = WMCore.Database.CMSCouch.CouchServer(couchUrl) <NEW_LINE> database = server.connectDatabase(couchDBName) <NEW_LINE> uri = '/%s/%s' % (couchDBName, self.name()) <NEW_LINE> specuri = uri + '/sp... | Save this spec in CouchDB. Returns URL | 625941f585dfad0860c3b490 |
def maskloss(pred, label, average = True, use_cuda = False): <NEW_LINE> <INDENT> loss = nn.CrossEntropyLoss(reduction = 'none') <NEW_LINE> stop_index = torch.Tensor(list(map(lambda x : len(x[x!=10]), label))).long() + 1 <NEW_LINE> label_mask = torch.randint(low=0,high=1, size=label.shape) <NEW_LINE> for i in range(len(... | 只计算字符+终止符的loss | 625941f5fbf16365ca6f6805 |
def getAsV9t9(self): <NEW_LINE> <INDENT> return self.fd.getV9t9Header() + self.getData() | return file contents in v9t9 format | 625941f5a4f1c619b28b065c |
def StringifyCommand(cmd, stdin_contents=None): <NEW_LINE> <INDENT> stdin_str = "" <NEW_LINE> if stdin_contents: <NEW_LINE> <INDENT> stdin_str = "echo \"\"\"" + EscapeEcho(stdin_contents) + "\"\"\" | " <NEW_LINE> <DEDENT> return stdin_str + PrettyStringify(cmd) | Return a string for reproducing the command "cmd", which will be
fed stdin_contents through stdin. | 625941f510dbd63aa1bd31d5 |
def key_pair_paths(key_name): <NEW_LINE> <INDENT> public_key_path = os.path.expanduser("~/.ssh/{}.pub".format(key_name)) <NEW_LINE> private_key_path = os.path.expanduser("~/.ssh/{}.pem".format(key_name)) <NEW_LINE> return public_key_path, private_key_path | Returns public and private key paths for a given key_name. | 625941f5a934411ee3751cc8 |
def entry_to_offset(n): <NEW_LINE> <INDENT> return n * (4*7) | Convert an entry number to an actual bytes offset. | 625941f50fa83653e46575ea |
def on_checks_validation_ready(self): <NEW_LINE> <INDENT> if self.is_done(): <NEW_LINE> <INDENT> nextbutton = self.wizard().button(QtGui.QWizard.NextButton) <NEW_LINE> nextbutton.setFocus() <NEW_LINE> full_domain = self.field('provider_domain') <NEW_LINE> domain, port = get_https_domain_and_port(full_domain) <NEW_LINE>... | called after _do_checks has finished
(connected to checker thread finished signal) | 625941f5eab8aa0e5d26e18e |
def _format(self, dev, **kwargs ): <NEW_LINE> <INDENT> mac = dev.mac <NEW_LINE> resolve_mac = kwargs.get("resolve_mac", True) <NEW_LINE> if resolve_mac and conf.manufdb and mac: <NEW_LINE> <INDENT> mac = conf.manufdb._resolve_MAC(mac) <NEW_LINE> <DEDENT> index = str(dev.index) <NEW_LINE> return (index, dev.description,... | Returns the elements used by show()
If a tuple is returned, this consist of the strings that will be
inlined along with the interface.
If a list of tuples is returned, they will be appended one above the
other and should all be part of a single interface. | 625941f524f1403a92601194 |
def partition(self, s): <NEW_LINE> <INDENT> ret = [] <NEW_LINE> self.dfs(s, 0, ret, []) <NEW_LINE> return ret | :type s: str
:rtype: List[List[str]] | 625941f582261d6c526abadc |
def test_cost_invoicing(self): <NEW_LINE> <INDENT> serv_cost = self.env.ref('product.service_cost_01') <NEW_LINE> prod_gap = self.env.ref('product.product_product_1') <NEW_LINE> so = self.env['sale.order'].create({ 'partner_id': self.partner.id, 'partner_invoice_id': self.partner.id, 'partner_shipping_id': self.partner... | Test confirming a vendor invoice to reinvoice cost on the so | 625941f5be7bc26dc91cdc27 |
def correrByteDerecha(self, cadenaHex): <NEW_LINE> <INDENT> temp = cadenaHex[-1] <NEW_LINE> for i in range(len(cadenaHex)-1, 0, -1): <NEW_LINE> <INDENT> cadenaHex[i] = cadenaHex[i-1] <NEW_LINE> <DEDENT> cadenaHex[0] = temp <NEW_LINE> return self.listaToString(cadenaHex) | Función para correr la cadena de hexadecimales un byte hacia la derecha.
:param cadenaHex: Lista con los hexadecimales del bloque que se desea correr.
:type cadenaHex:list
:return: Lista actualizada con el corrimiento de 1 byte.
:rtype: str | 625941f5d268445f265b54a3 |
def filter_stop_words(words_list,stop_words_dict = base_stopwords): <NEW_LINE> <INDENT> return [word for word in words_list if word not in stop_words_dict ] | 过滤停用词 | 625941f5627d3e7fe0d69485 |
def decode_bmp(contents, channels=0, name=None): <NEW_LINE> <INDENT> _ctx = _context._context or _context.context() <NEW_LINE> tld = _ctx._thread_local_data <NEW_LINE> if tld.is_eager: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _result = pywrap_tfe.TFE_Py_FastPathExecute( _ctx._context_handle, tld.device_name, "Decod... | Decode the first frame of a BMP-encoded image to a uint8 tensor.
The attr `channels` indicates the desired number of color channels for the
decoded image.
Accepted values are:
* 0: Use the number of channels in the BMP-encoded image.
* 3: output an RGB image.
* 4: output an RGBA image.
Args:
contents: A `Te... | 625941f5187af65679ca5754 |
def transform(self,matrix): <NEW_LINE> <INDENT> m = matrix.mul(TransformMatrix([self.rx*math.cos(self.ax),self.rx*math.sin(self.ax), -self.ry*math.sin(self.ax),self.ry*math.cos(self.ax), self.center.x,self.center.y])) <NEW_LINE> d = m.matrix[0]**2+m.matrix[1]**2-m.matrix[2]**2-m.matrix[3]**2 <NEW_LINE> if d == 0: <NEW_... | transform the object
matrix TransformMatrix
return the object
Example:
>>> a = Arc(Point(2,3),4,2,0,0,math.pi/2)
>>> a.transform(TransformMatrix([2,0,0,-1,0,2]))
>>> print((round(a.center.x,3),round(a.center.y,3)),a.rx,a.ry,round(a.ax,3),round(a.a1,3),round(a.a2,3))
(4.0, -1.0) 8.0 2.0 0.0 0.0 -1.571 | 625941f5287bf620b61d4093 |
def p_IfBlock(p): <NEW_LINE> <INDENT> if isinstance(p[1], basestring): <NEW_LINE> <INDENT> p[0] = IfBlock(None, p[2], p[4], p[5]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> p[0] = IfBlock(p[1], p[3], p[5], p[6]) | IfBlock : IF Expression COLON Terminator Block
| IfBlock ELIF Expression COLON Terminator Block | 625941f51d351010ab85614e |
def ex_list_listener_rules( self, listener_rule_names: List[str] = None, dry_run: bool = False ): <NEW_LINE> <INDENT> action = "ReadListenerRules" <NEW_LINE> data = {"DryRun": dry_run, "Filters": {}} <NEW_LINE> if listener_rule_names is not None: <NEW_LINE> <INDENT> data["Filters"].update({ "ListenerRuleNames": listene... | Describes one or more listener rules. By default, this action returns
the full list of listener rules for the account.
:param listener_rule_names: The names of the listener rules.
:type listener_rule_names: ``list`` of ``str``
:param dry_run: If true, checks whether you have the required
permissions t... | 625941f563d6d428bbe44b25 |
def _gwf_channel(path, series_class=TimeSeries, verbose=False): <NEW_LINE> <INDENT> channels = list(io_gwf.iter_channel_names(file_path(path))) <NEW_LINE> if issubclass(series_class, StateVector): <NEW_LINE> <INDENT> regex = DQMASK_CHANNEL_REGEX <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> regex = STRAIN_CHANNEL_REGEX... | Find the right channel name for a LOSC GWF file
| 625941f5cc0a2c11143dd4c5 |
def test_no_file_specified(self): <NEW_LINE> <INDENT> with self.assertRaisesRegexp(CommandError, "A file containing JSON must be specified"): <NEW_LINE> <INDENT> _run_command(username=self.test_username) | Tests the error handling when no JSON file is supplied. | 625941f56aa9bd52df0373dc |
def _load_premis(data, mwfile): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> premis_object = mwfile.get_premis_objects()[0] <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> props = ( "size", "format_name", "format_version", "format_registry_name", "format_registry_key", ) <NEW_LINE>... | Update ``data`` dictionary with relevant ``PREMIS:OBJECT`` attrs. | 625941f560cbc95b062c6b77 |
def frequency(self, word_list): <NEW_LINE> <INDENT> for word in word_list: <NEW_LINE> <INDENT> if word in self.freq.keys(): <NEW_LINE> <INDENT> self.freq[word] += word_list.count(word) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.freq[word] = word_list.count(word) | passes in the list of words from a given web page and adds there counts to freq attribute
Parameters
----------
word_list : list
list of words scraped from website | 625941f58e05c05ec3eea9ae |
def p_type(p): <NEW_LINE> <INDENT> p[0] = p[1] | type : INTDECL
| FLOATDECL | 625941f5a8ecb033257d36fe |
def binary_dump(obj, fp, alt_format=False): <NEW_LINE> <INDENT> if not isinstance(obj, Mapping): <NEW_LINE> <INDENT> raise TypeError("Expected obj to be type of Mapping") <NEW_LINE> <DEDENT> if not hasattr(fp, 'write'): <NEW_LINE> <INDENT> raise TypeError("Expected fp to have write() method") <NEW_LINE> <DEDENT> for ch... | Serialize ``obj`` to a binary VDF formatted ``bytes`` and write it to ``fp`` filelike object | 625941f57047854f462a1a36 |
def delete(self): <NEW_LINE> <INDENT> base_path = os.path.join(current_app.config['UPLOAD_BASE'], str(self.id)) <NEW_LINE> if os.path.exists(base_path): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> shutil.rmtree(base_path, ignore_errors=True) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DED... | Delete project | 625941f563f4b57ef000173a |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, VidChecker8Body): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.to_dict() == other.to_dict() | Returns true if both objects are equal | 625941f50383005118ecfc14 |
def getKeyframeContainer(self, *args): <NEW_LINE> <INDENT> return _osgAnimation.Vec3LinearSampler_getKeyframeContainer(self, *args) | getKeyframeContainer(Vec3LinearSampler self) -> KeyframeContainer
getKeyframeContainer(Vec3LinearSampler self) -> KeyframeContainer | 625941f530dc7b7665901f93 |
def totalCost(routes, graph): <NEW_LINE> <INDENT> cost = 0 <NEW_LINE> for route in routes: <NEW_LINE> <INDENT> for i in range(1, len(route)): <NEW_LINE> <INDENT> cost += graph.distances[route[i-1], route[i]] <NEW_LINE> <DEDENT> <DEDENT> return cost | Funcao q computa o somatorio das distancias de todas as rotas
:param routes:
:param graph:
:return: | 625941f5460517430c3947a7 |
def create(self, cr, uid, vals, context=None): <NEW_LINE> <INDENT> if context is None: <NEW_LINE> <INDENT> context = {} <NEW_LINE> <DEDENT> cotizacion_id = super(sale_cotizacion, self).create(cr, uid, vals,context=context) <NEW_LINE> ctx = context.copy() <NEW_LINE> shop_id = vals.get('shop_id', []) <NEW_LINE> shop = se... | Rewrite Create method.
This method spend new sequence when create (not default value)
:param vals: dicc
:return order_id | 625941f5379a373c97cfb17b |
def conformal2geodetic(conformal_lat: ndarray, ell: Ellipsoid = None, deg: bool = True) -> ndarray: <NEW_LINE> <INDENT> conformal_lat, ell = sanitize(conformal_lat, ell, deg) <NEW_LINE> e = ell.eccentricity <NEW_LINE> f1 = e ** 2 / 2 + 5 * e ** 4 / 24 + e ** 6 / 12 + 13 * e ** 8 / 360 <NEW_LINE> f2 = 7 * e ** 4 / 48 + ... | converts from conformal latitude to geodetic latitude
like Matlab map.geodesy.ConformalLatitudeConverter.inverse()
Parameters
----------
conformal_lat : float
conformal latitude
ell : Ellipsoid, optional
reference ellipsoid (default WGS84)
deg : bool, optional
degrees input/output (False: radians in/out)... | 625941f58da39b475bd655b0 |
def recv_focus(s): <NEW_LINE> <INDENT> msg = None <NEW_LINE> try: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> new_msg = recv_nonblocking(s) <NEW_LINE> if new_msg is None: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> msg = new_msg <NEW_LINE> <DEDENT> <DEDENT> except socket.error as e: <NEW_LINE> <INDENT> err = ... | Receive the latest focus event. | 625941f521bff66bcd684f80 |
def error(self, msg): <NEW_LINE> <INDENT> pass | error log.
Keyword arguments:
msg -- message to print | 625941f5090684286d50f325 |
def ttt_board(self): <NEW_LINE> <INDENT> idx = [index for index, value in enumerate( list(board)) if value == '0'] <NEW_LINE> print("!!!!! Welcome to Tic Tac toe game !!!!!\n") <NEW_LINE> print("You have to provide input between 1 to 9") <NEW_LINE> print(board) <NEW_LINE> return idx | draw empty board and get the all the valid index from board | 625941f53317a56b8693a27c |
def smooth_axis(data, window=15): <NEW_LINE> <INDENT> smooth = im.median_filter(data, size=(window,), mode="nearest") <NEW_LINE> return smooth | Smooth a 1D data array with a median filter of `width`.
See Also
--------
smooth_axis_monotone | 625941f530bbd722463cc3fe |
def __len__(self) -> int: <NEW_LINE> <INDENT> return len(self.parameters) | Return the length of the parameter set.
:return: length of parameter set. | 625941f5498bea3a759ba0e1 |
def on_site(self, site_id=None): <NEW_LINE> <INDENT> if settings.PAGES_USE_SITE_ID: <NEW_LINE> <INDENT> if not site_id: <NEW_LINE> <INDENT> site_id = settings.SITE_ID <NEW_LINE> <DEDENT> return self.get_queryset().filter(sites=site_id) <NEW_LINE> <DEDENT> return self.all() | Return a :class:`QuerySet` of pages that are published on the site
defined by the ``SITE_ID`` setting.
:param site_id: specify the id of the site object to filter with. | 625941f5b7558d58953c553a |
def __init__(self, values, indices, length = 0, zero_test = lambda x : (x == 0)): <NEW_LINE> <INDENT> super(SparseVector, self).__init__(values, zero_test) <NEW_LINE> self.data = values <NEW_LINE> self.indices = indices <NEW_LINE> self.length = length <NEW_LINE> self.zero_test = zero_test | 'values' argument is the list of non-zero values and the corresponding indices are in the list 'indices'
Uses the base (parent) class attributes data (this is where 'values' are kept) and zero_test
Length is the length of the vector - the number of entries in 'values' is just the number of non-zero entries
You can assu... | 625941f52c8b7c6e89b35def |
def load_vgg(self): <NEW_LINE> <INDENT> self.vgg = load_vgg_sol.VGG(self.input_img) <NEW_LINE> self.vgg.load() <NEW_LINE> self.content_img -= self.vgg.mean_pixels <NEW_LINE> self.style_img -= self.vgg.mean_pixels | Load the saved model parameters of VGG-19, using the input_img
as the input to compute the output at each layer of vgg.
During training, VGG-19 mean-centered all images and found the mean pixels
to be [123.68, 116.779, 103.939] along RGB dimensions. We have to subtract
this mean from our images. | 625941f5cb5e8a47e48b80d3 |
def getPropertyValue(self, prop: str) -> str: <NEW_LINE> <INDENT> return self.get(prop, '') | Return value of the css property.
If the property is not included, return empty string. | 625941f54d74a7450ccd47fa |
def backup_wallet(self, destination): <NEW_LINE> <INDENT> payload = { 'destination': destination, } <NEW_LINE> return self.http.get(wallet_constants.BACKUP_URL, payload) | Creates a backup of the wallet settings. | 625941f5bf627c535bc13804 |
@with_patched_object( 'fabric.state', 'env', _AttributeDict({'roledefs': fake_roles}) ) <NEW_LINE> @raises(SystemExit) <NEW_LINE> @mock_streams('stderr') <NEW_LINE> def test_aborts_on_nonexistent_roles(): <NEW_LINE> <INDENT> _merge([], ['badrole']) | Aborts if any given roles aren't found | 625941f56fece00bbac2dd7a |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.