code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def right_lobe(self): <NEW_LINE> <INDENT> right_lobe_array = [] <NEW_LINE> lower_limit = (self.num_points - 1) * (1 - 0.5 * self.alpha) <NEW_LINE> upper_limit = self.num_points - 1 <NEW_LINE> for point in range(int(lower_limit), int(upper_limit)): <NEW_LINE> <INDENT> fpoint = float(point) <NEW_LINE> right_lobe_array.ap...
Returns the right cosine lobe of the window
625941c4e64d504609d7482c
def __init__(self, imgsurface, size, mapping=None): <NEW_LINE> <INDENT> if mapping is None: <NEW_LINE> <INDENT> self.mapping = list(BitmapFont.DEFAULTMAP) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.mapping = mapping <NEW_LINE> <DEDENT> self.offsets = {} <NEW_LINE> if isinstance(imgsurface, SoftwareSprite): <NEW...
Creates a new BitmapFont instance from the passed image. Each character is expected to be of the same size (a 2-value tuple denoting the width and height) and to be in order of the passed mapping.
625941c43317a56b86939c48
def check_events(ai_settings, screen, ship, bullets): <NEW_LINE> <INDENT> for event in pygame.event.get(): <NEW_LINE> <INDENT> if event.type == pygame.QUIT: <NEW_LINE> <INDENT> sys.exit() <NEW_LINE> <DEDENT> elif event.type == pygame.KEYDOWN: <NEW_LINE> <INDENT> check_keydown_events(event, ai_settings, screen, ship, bu...
Respond to keyscreens and mouse events.
625941c4090684286d50ecd0
def get_frame(fname, framenum, frame_size, med_filter=False): <NEW_LINE> <INDENT> framesize = frame_size <NEW_LINE> data_fmt = 'I' * np.int(framesize / 4) <NEW_LINE> x_start = framesize * framenum <NEW_LINE> frame_dim_1 = 127 <NEW_LINE> frame_dim_2 = 255 <NEW_LINE> with open(fname, 'rb') as fh: <NEW_LINE> <INDENT> fh.s...
Requires raw filename, desired frame number, and size of frame as arguments.
625941c431939e2706e4ce58
def _compare(self, a, b, compare): <NEW_LINE> <INDENT> return compare_generic(a, b, compare['comparison'], compare['type'])
Compare values a and b as described in compare.
625941c457b8e32f52483486
def cache_clear(): <NEW_LINE> <INDENT> with lock: <NEW_LINE> <INDENT> cache.clear() <NEW_LINE> root = nonlocal_root[0] <NEW_LINE> root[:] = [root, root, None, None] <NEW_LINE> stats[:] = [0.0, 0, 0]
Clear the cache and cache statistics
625941c4287bf620b61d3a51
def __isub__(self, elem, *args, **kwargs): <NEW_LINE> <INDENT> self.difference_update(elem) <NEW_LINE> return self.unique
Return self-=value.
625941c4097d151d1a222e47
def get_card_config_files(sourcedir, channel, period, category, ana='sm'): <NEW_LINE> <INDENT> base_dir = os.path.join(sourcedir, channel) <NEW_LINE> cgs = 'cgs-%s-%s-%s.conf' % (ana, period, category) <NEW_LINE> unc_c = 'unc-%s-%s-%s.conf' % (ana, period, category) <NEW_LINE> unc_v = 'unc-%s-%s-%s.vals' % (ana, period...
Get the configuration files (cgs, unc.vals, etc) Returns a tuple of paths to the cgs, unc.conf, and unc.vals
625941c4f7d966606f6a9fef
def to_jx(self, schema): <NEW_LINE> <INDENT> return self
:param schema: THE SCHEMA USED TO INTERPRET THIS EXPRESSION :return: SOMETHING BETTER
625941c48c3a8732951583a5
def __call__(self, k): <NEW_LINE> <INDENT> k = numpy.asarray(k) <NEW_LINE> nonzero = k>0 <NEW_LINE> linearP = self.cosmo.get_pklin(k[nonzero], self.redshift) / self.cosmo.h**3 <NEW_LINE> primordialP = (k[nonzero]*self.cosmo.h)**self.cosmo.n_s <NEW_LINE> Tk = numpy.ones(nonzero.shape) <NEW_LINE> Tk[~nonzero] = self.cosm...
Return the CLASS linear transfer function at :attr:`redshift`. This computes the transfer function from the CLASS linear power spectrum using: .. math:: T(k) = \left [ P_L(k) / k^n_s \right]^{1/2}. We normalize the transfer function :math:`T(k)` to unity as :math:`k \rightarrow 0` at :math:`z=0`. Parameters --...
625941c47c178a314d6ef449
def parse_readlen(target): <NEW_LINE> <INDENT> readlen = target.split('_')[-1] <NEW_LINE> return 500 if readlen == '50to500' else int(readlen)
Based on Makefile target name, parse the read length
625941c40fa83653e4656fa8
def calculate_hand_for_basins(out_raster: Union[str, Path], geometries: GeometryCollection, dem_file: Union[str, Path]): <NEW_LINE> <INDENT> with rasterio.open(dem_file) as src: <NEW_LINE> <INDENT> basin_mask, basin_affine_tf, basin_window = rasterio.mask.raster_geometry_mask( src, geometries, all_touched=True, crop=T...
Calculate the Height Above Nearest Drainage (HAND) for watershed boundaries (hydrobasins). For watershed boundaries, see: https://www.hydrosheds.org/page/hydrobasins Args: out_raster: HAND GeoTIFF to create geometries: watershed boundary (hydrobasin) polygons to calculate HAND over dem_file: DEM raster co...
625941c4a4f1c619b28b0029
def login(self, username, password): <NEW_LINE> <INDENT> raise NotImplementedError
:param username: The user name for login :param password: The password for login :return:
625941c499fddb7c1c9de37e
def get_attrib_list(self, name): <NEW_LINE> <INDENT> if name in self.attribs: <NEW_LINE> <INDENT> if isinstance(self.attribs[name], list): <NEW_LINE> <INDENT> return self.attribs[name] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [self.attribs[name]] <NEW_LINE> <DEDENT> <DEDENT> return None
Return all values for specified attribute as a list.
625941c4460517430c394175
def add(self,point,data=None): <NEW_LINE> <INDENT> if self.method == 'kdtree': <NEW_LINE> <INDENT> self.kdtree.add(point, data) <NEW_LINE> self.kdtree.rebalance() <NEW_LINE> if check_kdtree: self.checker.add(point, data) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.nodes.append((point,data))
Adds a point with an associated datum.
625941c463b5f9789fde70d2
def is_988(self): <NEW_LINE> <INDENT> return self.num == 988
Verify whether num property is 988
625941c4be8e80087fb20c31
def plugins(self, node_uuid): <NEW_LINE> <INDENT> plugins = self.connector.glob.actual.get_all_plugins_ids( self.sysid, self.tenantid, node_uuid) <NEW_LINE> return plugins
Gets the list of plugins in the given node parameters ---------- node_uuid : string UUID of the node returns ------- string list
625941c4d53ae8145f87a25f
def unlink(self): <NEW_LINE> <INDENT> cmd = self.command_set.unlink() <NEW_LINE> self.send(cmd)
Unlink linked lights.
625941c48e71fb1e9831d796
def __str__(self): <NEW_LINE> <INDENT> return self._format_string
String representation of note-head. :: >>> str(note_head) "cs''" Returns string.
625941c4b545ff76a8913e03
def test_dimension_empty(self): <NEW_LINE> <INDENT> _config_reset() <NEW_LINE> with pytest.raises(DimensionError): <NEW_LINE> <INDENT> _config.parsedimension("") <NEW_LINE> <DEDENT> with pytest.raises(DimensionError): <NEW_LINE> <INDENT> _config.parsedimension(" ") <NEW_LINE> <DEDENT> with pytest.raises(DimensionEr...
Dimension cannot be empty string...
625941c499cbb53fe6792bd3
def changes(self, q="", n=25, o=[]): <NEW_LINE> <INDENT> return self._request('changes', q=q, n=n, o=o)
Submits a request to the /changes/ REST API. Parameters: * q - the query string, * n - the maximum number of results to return - 25 by default, * o - the list of options to pass. CURRENT_REVISION and CURRENT_FILES by default. See https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html for more detai...
625941c431939e2706e4ce59
def customForward(self, x): <NEW_LINE> <INDENT> x = x.view(x.size(0), -1) <NEW_LINE> x1 = self.activation_fn(self.fc1(x)) <NEW_LINE> x2 = self.activation_fn(self.fc2(x1)) <NEW_LINE> x = self.activation_fn(self.fc3(x2)) <NEW_LINE> return x, x1, x2
Return intermediate results
625941c4d268445f265b4e5b
def UNL(self): <NEW_LINE> <INDENT> return '-->'.join([i.h for i in self.path])
Return the UNL string leading to this node
625941c47b180e01f3dc47ed
def make(self, type_, **attrs): <NEW_LINE> <INDENT> return type_(**self.attributes(type_, **attrs))
Make the attributes for a sample object of the specified ``type_`` using the default attributes for that type in this :class:`Collection`. The ``attrs`` mapping will be overlayed onto the sample attributes and returned as a :class:`dict`.
625941c4796e427e537b05b1
def read_rules_and_passwords(lines: Collection[str]) -> List[RuleAndPassword]: <NEW_LINE> <INDENT> rules_and_data: List[RuleAndPassword] = [] <NEW_LINE> for line in lines: <NEW_LINE> <INDENT> line_fragments: List[str] = line.split(" ") <NEW_LINE> number_fragments: List[str] = line_fragments[0].split("-") <NEW_LINE> min...
Parse `RuleAndPassword`s from a `Collection` of lines. Parameters ---------- lines : `Collection[str]` The lines in the file. Returns ------- `List[RuleAndPassword]` A list of `RuleAndPassword`s.
625941c4e1aae11d1e749ca2
def search(values): <NEW_LINE> <INDENT> values = reduce_puzzle(values) <NEW_LINE> if values is False: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if all(len(values[s]) == 1 for s in boxes): <NEW_LINE> <INDENT> return values <NEW_LINE> <DEDENT> n,s = min((len(values[s]), s) for s in boxes if len(values[s]) > 1)...
Apply depth first search to solve Sudoku puzzles in order to solve puzzles that cannot be solved by repeated reduction alone. Parameters ---------- values(dict) a dictionary of the form {'box_name': '123456789', ...} Returns ------- dict or False The values dictionary with all boxes assigned or False Notes -...
625941c423849d37ff7b307d
@mark.parametrize('toxi_code', ctl.toxic_map.keys()) <NEW_LINE> def test_decode_toxi(toxi_code): <NEW_LINE> <INDENT> assert ctl._decode_toxic(toxi_code)
GIVEN an shortned toxic code WHEN the code is given to the _decode_toxic() function THEN it receives back dictionary with the code
625941c467a9b606de4a7ea8
def test_bytes(self): <NEW_LINE> <INDENT> module = reflect.filenameToModuleName( os.path.join(self.path.encode("utf-8"), b'test_reflect.py')) <NEW_LINE> self.assertEqual(module, 'fakepackage.test.test_reflect')
L{filenameToModuleName} returns the correct module given a C{bytes} path to its file.
625941c4099cdd3c635f0c48
def __init__(self, *args, **kwds): <NEW_LINE> <INDENT> if args or kwds: <NEW_LINE> <INDENT> super(SetBehaviorResponse, self).__init__(*args, **kwds) <NEW_LINE> if self.result is None: <NEW_LINE> <INDENT> self.result = False <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.result = False
Constructor. Any message fields that are implicitly/explicitly set to None will be assigned a default value. The recommend use is keyword arguments as this is more robust to future message changes. You cannot mix in-order arguments and keyword arguments. The available fields are: result :param args: complete set ...
625941c4bde94217f3682ddf
def _get_args(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser(description=__doc__) <NEW_LINE> parser.add_argument('--env', '-e', type=str, default='SuperMarioBros-v0', help='The name of the environment to play' ) <NEW_LINE> parser.add_argument('--mode', '-m', type=str, default='human', choices=['human', 'random...
Parse command line arguments and return them.
625941c43d592f4c4ed1d05e
def reshape_to_3d(arr) : <NEW_LINE> <INDENT> arr.shape = shape_as_3d(arr.shape) <NEW_LINE> return arr
Returns n-d re-shaped to 3-d
625941c416aa5153ce362465
def _create_user(self, email, password, **extra_fields): <NEW_LINE> <INDENT> if not email: <NEW_LINE> <INDENT> raise ValueError('The given email must be set') <NEW_LINE> <DEDENT> email = self.normalize_email(email) <NEW_LINE> user = self.model(email=email, **extra_fields) <NEW_LINE> user.set_password(password) <NEW_LIN...
Save a user with the given email and password :param email: :param password: :param extra_fields: :return: user
625941c4b5575c28eb68dfec
def is_words(self, data): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> number_value = self.number_words.parseString(data)[0] <NEW_LINE> return True, number_value <NEW_LINE> <DEDENT> except ParseException: <NEW_LINE> <INDENT> return False, 0
determines if the data is textual numbers :param data: potential textual numbers :type data: str :return: data confirming or denying this is a textual numbers :rtype: tuple
625941c47b180e01f3dc47ee
def test_all_close(self, df1): <NEW_LINE> <INDENT> df2 = self.transform_floats(df1) <NEW_LINE> self.assert_test_case(df1, df2, True, all_close=True) <NEW_LINE> self.assert_test_case(df1, df2, False)
When all_close=True, compare floats in an np.isclose manner
625941c43317a56b86939c49
def patch(self, conversation_id, message_id): <NEW_LINE> <INDENT> result = get_messages(request, conversation_id, message_id) <NEW_LINE> if isinstance(result, dict): <NEW_LINE> <INDENT> return result, 404 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> update_result = update_resource(request, result) <NEW_LINE> if isinst...
Edit a message.
625941c424f1403a92600b55
def scale_bias(b, scale=75.): <NEW_LINE> <INDENT> return scale * np.abs(b)
Returns the scaled biased for the `plot.netviz` plot. :param b: the bias to scale :param scale: the scale parameter to be applied on the absolute value of `b`. Default=20
625941c494891a1f4081ba95
def solve(self, poly=None, algorithm=Algorithm.SECULAR_GA): <NEW_LINE> <INDENT> self.mpsolve(poly, algorithm) <NEW_LINE> return self.get_roots()
Simple shorthand for the combination of set_input_poly() and mpsolve(). This function directly returns the approximations that could otherwise be obtained by a call to the get_roots() method.
625941c471ff763f4b549676
def newroom(self, name): <NEW_LINE> <INDENT> if name in self.rooms: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> newrm = Room(name, self.roomno) <NEW_LINE> self.roomno += 1 <NEW_LINE> self.rooms[newrm.name] = newrm <NEW_LINE> return True
Creates new Room object instances and adds to rooms dictionary. Args: name (str) : the name of the room to be created. Returns: bool : True on success, False if room name is already in use.
625941c4adb09d7d5db6c77d
def run(self): <NEW_LINE> <INDENT> if self.seed == 'pause': <NEW_LINE> <INDENT> sleep(self.delay) <NEW_LINE> self.bot.send_text(chat_id=self.chat_id, text=self.message) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sleep(self.delay - 30) <NEW_LINE> if chats[f'{self.chat_id}'][0] == 'q3' and self.seed == chats[f'{self.c...
Класс потока, который вызывается вместе со start()
625941c4cc0a2c11143dce7d
def _build_condition_list(self): <NEW_LINE> <INDENT> conditions = [] <NEW_LINE> for i in range(self.MAX_EDGE_CONDITIONS): <NEW_LINE> <INDENT> conditions.extend(self._get_data_for_condition('edges', i + 1)) <NEW_LINE> conditions.extend(self._get_data_for_condition('levels', i + 1)) <NEW_LINE> <DEDENT> return conditions
Builds a condition list that encapsulates the UI in a way that can be understood by the GreatFET/GlitchKit API. Returns: a condition list suitable for passing to prime_trigger_on_event_count.
625941c4dc8b845886cb5521
def print_mistakes(num_guess_remain, secret_word, remaining_letters): <NEW_LINE> <INDENT> if 0 == num_guess_remain: <NEW_LINE> <INDENT> for i in range(len(secret_word)): <NEW_LINE> <INDENT> if '_' == remaining_letters[i]: <NEW_LINE> <INDENT> remaining_letters[i] = secret_word[i].upper() <NEW_LINE> <DEDENT> <DEDENT> <DE...
Prints to console standard out the number of remaining mistakes allowed before the secret word is revealed :param 1: num_guess_remain is the remaining number of guesses as integer :param 2: secret_word as the secret word not yet guessed as a string :param 2: remaining_letters is characters of the secret word that have ...
625941c43cc13d1c6d3c7368
def GSUplinkBehav(self, argument): <NEW_LINE> <INDENT> tok = self.list_append('GSUplink', argument) <NEW_LINE> resdict = {'GSUplink.uplinkedFlightSystem' : [tok]} <NEW_LINE> message = 'GSUplink input: %s ; GSUplink output: %s' % (argument, [tok]) <NEW_LINE> LOG.info(message) <NEW_LINE> resdict['message'] = message <NEW...
User written behavior
625941c4fbf16365ca6f61ae
def build_dict(filename): <NEW_LINE> <INDENT> di = {} <NEW_LINE> fp = open(filename) <NEW_LINE> for line in fp: <NEW_LINE> <INDENT> for word in line.rstrip().split(): <NEW_LINE> <INDENT> if word in di: <NEW_LINE> <INDENT> di[word] += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> di[word] = 1 <NEW_LINE> <DEDENT> <DEDE...
Builds a dictionary for the file. key = unique word in text value = frequency of wrod in text
625941c43c8af77a43ae378c
def add(self, record): <NEW_LINE> <INDENT> _checktype(record, Event, "batch records must be Events") <NEW_LINE> if len(self.records) >= MAX_BATCH_RECORDS: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if self.records: <NEW_LINE> <INDENT> if self.time_diff_exceeded(self.records[0], record): <NEW_LINE> <INDENT> re...
Return True if record was added to this batch, otherwise False Prereq: records are in timestamp order
625941c42ae34c7f2600d11f
def memory_add_im(self, elmt): <NEW_LINE> <INDENT> if not self.im_mem.any(): <NEW_LINE> <INDENT> self.im_mem = np.array([elmt]) <NEW_LINE> <DEDENT> elif len(self.im_mem) < self.N: <NEW_LINE> <INDENT> self.im_mem = np.insert(self.im_mem, len(self.im_mem), elmt, axis=0) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self....
Adds elmt in memory corresponding to mode.
625941c42eb69b55b151c89a
def do_xt(self,line): <NEW_LINE> <INDENT> args = line.split() <NEW_LINE> if not self.client or not self.client.connected: <NEW_LINE> <INDENT> print("No active connection") <NEW_LINE> return <NEW_LINE> <DEDENT> if len(args) != 4: <NEW_LINE> <INDENT> print("Not enough arguments") <NEW_LINE> <DEDENT> else: <NEW_LINE> <IND...
[xt subject1 subject2 target ticket isobject] xfer a rights ticket
625941c497e22403b379cf87
def get_course_progress(self, member=None): <NEW_LINE> <INDENT> lesson_count = len(self.get_lessons()) <NEW_LINE> if not lesson_count: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> completed_lessons = frappe.db.count("LMS Course Progress", { "course": self.name, "owner": member or frappe.session.user, "status": "Com...
Returns the course progress of the session user
625941c494891a1f4081ba96
def add(self, redditor, permissions=None, **other_settings): <NEW_LINE> <INDENT> other_settings = self._handle_permissions(permissions, other_settings) <NEW_LINE> super(ModeratorRelationship, self).add(redditor, **other_settings)
Add or invite ``redditor`` to be a moderator of the subreddit. :param redditor: A redditor name (e.g., ``'spez'``) or :class:`~.Redditor` instance. :param permissions: When provided (not ``None``), permissions should be a list of strings specifying which subset of permissions to grant. An empty list ``[]``...
625941c46e29344779a62601
def max_profit(prices): <NEW_LINE> <INDENT> if not prices: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> profit, purchase = 0, prices[0] <NEW_LINE> n = len(prices) <NEW_LINE> for i in range(1, n): <NEW_LINE> <INDENT> profit = max(profit, prices[i] - purchase) <NEW_LINE> purchase = min(purchase, prices[i]) <NEW_LINE>...
DP. 时间复杂度 O(N), 空间复杂度 O(1) 初始化: dp[0] = 0, purchase = prices[0]. purchase 为买入的股票价格。dp 为最大获利 DP 方程: dp[i] = max(dp[i-1], prices[i] - purchase). purchase = min(purchase, prices[i]). :param prices: (list[int]) :return: (int)
625941c4956e5f7376d70e5b
def _authenticate(self): <NEW_LINE> <INDENT> if self._token_expire and self._token_expire < _time(): <NEW_LINE> <INDENT> self._token = '' <NEW_LINE> <DEDENT> if not self._token: <NEW_LINE> <INDENT> credentials = json_read(get_accelize_cred()) <NEW_LINE> client_id = credentials['client_id'] <NEW_LINE> client_secret = cr...
Authenticate user from its credentials. Raises: apyfal.exceptions.ClientAuthenticationException: User credential are not valid.
625941c40c0af96317bb81d5
def createConnections(self): <NEW_LINE> <INDENT> self.actionsAndroidComboBox.currentIndexChanged.connect(self.onActionAndroidChanged) <NEW_LINE> self.addAndroidAction.clicked.connect(self.addStep) <NEW_LINE> self.valueAndroidCombo2.currentIndexChanged.connect(self.onValueAndroid2TypeChanged) <NEW_LINE> self.elementText...
Create qt connections
625941c4099cdd3c635f0c49
def get_status(): <NEW_LINE> <INDENT> rc, out, err = module.run_command('%s %s' % (MONIT, SUMMARY_COMMAND), check_rc=True) <NEW_LINE> for line in out.split('\n'): <NEW_LINE> <INDENT> parts = parse(line.split()) <NEW_LINE> if parts != '': <NEW_LINE> <INDENT> return parts <NEW_LINE> <DEDENT> <DEDENT> return ''
Return the status of the process in monit, or the empty string if not present.
625941c444b2445a33932084
def parse_args(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser(add_help=True, description=__doc__) <NEW_LINE> parser.add_argument( '-epochs', metavar='epochs', dest='epochs', type=int, default=10, help="Number of training epochs.", ) <NEW_LINE> parser.add_argument( '-repeat', metavar='repeat', dest='repeat', ty...
Parse arguments.
625941c4f9cc0f698b1405ea
def save_operator(self): <NEW_LINE> <INDENT> first_name = "'" + self.nameEntry.get() + "'" <NEW_LINE> family_name = "'" + self.famnameEntry.get() + "'" <NEW_LINE> if self.droneLicense.get() == 'Two': <NEW_LINE> <INDENT> drone_license = 2 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> drone_license = 1 <NEW_LINE> <DEDENT...
Updates the drone details and calls the save action.
625941c4293b9510aa2c3285
def genesisBlock(): <NEW_LINE> <INDENT> firstBlock = Data(0,"This is first block",None) <NEW_LINE> return firstBlock
Actually the first block created is never used in this program except for that its presence ensure smooth operation on database.
625941c46fece00bbac2d72a
def _remove_stw_from_verkeerssituaties(apps, schema_editor): <NEW_LINE> <INDENT> Category = apps.get_model('signals', 'Category') <NEW_LINE> Department = apps.get_model('signals', 'Department') <NEW_LINE> CategoryDepartment = apps.get_model('signals', 'CategoryDepartment') <NEW_LINE> v_or = Department.objects.get(code=...
Change responsible department voor de "Verkeerssituaties" category.
625941c4cb5e8a47e48b7a99
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, FieldResource): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__
Returns true if both objects are equal
625941c4e64d504609d7482d
def invoke(self): <NEW_LINE> <INDENT> if self._action_type in ActionMap.get_action_map(): <NEW_LINE> <INDENT> if self.config_manager and self.config_manager.valid(): <NEW_LINE> <INDENT> action_code = ActionMap.get_action_type(self._action_type) <NEW_LINE> return self.switch(action_code) <NEW_LINE> <DEDENT> else: <NEW_L...
:return:
625941c423e79379d52ee553
def add_delete_materialized_view_model(self, operation: DeleteModel): <NEW_LINE> <INDENT> _, args, kwargs = operation.deconstruct() <NEW_LINE> return self.add( operations.PostgresDeleteMaterializedViewModel(*args, **kwargs) )
Adds a :see:PostgresDeleteMaterializedViewModel operation to the list of operations to execute in the migration.
625941c4a05bb46b383ec811
def find_cell(self, x): <NEW_LINE> <INDENT> inf = self.a <NEW_LINE> sup = self.b <NEW_LINE> N = x.shape[0] <NEW_LINE> indices = numpy.zeros((N, self.d), dtype=int) <NEW_LINE> for i in range(self.d): <NEW_LINE> <INDENT> xi =(x[:,i] - inf[i])/(sup[i]-inf[i]) <NEW_LINE> ni = numpy.floor( xi*self.orders[i] ) <NEW_LINE> ni ...
@param x: Nxd array @return: Nxd array with line i containing the indices of cell containing x[i,:]
625941c4d18da76e235324c2
def blocks(text): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> lines = text.split('\n') <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> lines = text <NEW_LINE> <DEDENT> blocks = [] <NEW_LINE> block = [] <NEW_LINE> for l in lines: <NEW_LINE> <INDENT> if block and empty(l): <NEW_LINE> <INDENT> blocks.append(block) <NEW_L...
Split a text or a list of lines into text blocks, which were seperated by empty lines.
625941c45166f23b2e1a5147
def run_scenarios(scenarios, handler, deferred_exceptions=tuple()): <NEW_LINE> <INDENT> errors = [] <NEW_LINE> tracebacks = [] <NEW_LINE> for i, scenario in enumerate(scenarios, 1): <NEW_LINE> <INDENT> logger.debug("running scenario {}/{}: {}".format(i, len(scenarios), scenario)) <NEW_LINE> try: <NEW_LINE> <INDENT> han...
Runs multiple scenarios from within a single test method. "Scenarios" are mini-tests where a common procedure can be reused with several different configurations. They are intended for situations where complex/expensive setup isn't required and some shared state is acceptable (or trivial to reset). Arguments: scenari...
625941c463d6d428bbe444dd
def query( self, variables, evidence=None, virtual_evidence=None, elimination_order="MinFill", joint=True, show_progress=True, ): <NEW_LINE> <INDENT> evidence = evidence if evidence is not None else dict() <NEW_LINE> orig_model = self.model.copy() <NEW_LINE> common_vars = set(evidence if evidence is not None else []).i...
Parameters ---------- variables: list list of variables for which you want to compute the probability evidence: dict a dict key, value pair as {var: state_of_var_observed} None if no evidence virtual_evidence: list (default:None) A list of pgmpy.factors.discrete.TabularCPD representing the virtual ...
625941c4dc8b845886cb5522
def _setup_critic_optimizer(self, critic_target, scope): <NEW_LINE> <INDENT> if self.verbose >= 2: <NEW_LINE> <INDENT> print('setting up critic optimizer') <NEW_LINE> <DEDENT> with tf.compat.v1.variable_scope("loss", reuse=False): <NEW_LINE> <INDENT> q_obs1 = tf.minimum(critic_target[0], critic_target[1]) <NEW_LINE> ta...
Create the critic loss, gradient, and optimizer.
625941c4fb3f5b602dac367f
def attack_ctr(self, this_creature, attack_target): <NEW_LINE> <INDENT> attack_target.health -= (this_creature.attributes.base_damage*self.PREDATOR_BOOST - attack_target.attributes.armor) <NEW_LINE> return attack_target.health <= 0
<this_creature> attempts to deal damage to <attack_target> (creature). :param this_creature :param attack_target
625941c41d351010ab855b0a
def run(self): <NEW_LINE> <INDENT> self.best_so_far = np.min(self.candidates[:self.num_looks]) <NEW_LINE> for i in self.candidates[self.num_looks:]: <NEW_LINE> <INDENT> self.selected = i <NEW_LINE> if i < self.best_so_far: <NEW_LINE> <INDENT> break
Simulate the interview process.
625941c44f88993c3716c056
def parse_process_code(self): <NEW_LINE> <INDENT> line, num_line, eof = self.read_line() <NEW_LINE> while self.is_blank(line): <NEW_LINE> <INDENT> line, num_line, eof = self.read_line() <NEW_LINE> if eof: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> <DEDENT> process_code = "" <NEW_LINE> is_process_line, wsp_prefix...
Parse process code
625941c4236d856c2ad447c6
def loss(labels, logits): <NEW_LINE> <INDENT> cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits( labels=labels, logits=logits ) <NEW_LINE> return tf.reduce_mean(cross_entropy)
推論結果と正解ラベルとの間の誤差を定義 Args: labels:正解ラベルの値を持つ[batch_size]のTensor logits:推論結果の[batch_size, 47]のTensor Returns: 誤差を表すTensor
625941c430c21e258bdfa48a
def register_username(self): <NEW_LINE> <INDENT> logger.info("register username on bridge") <NEW_LINE> logger.error("[TODO] LIBRARY FUNCTION CALL NOT IMPLEMENTED, USE THE CLIP API DEBUGGER (debug/clip.html)")
function to register a username this is used as security concept. you have to register a username first (while pressing the button on the bridge), to access the bridge :return:
625941c456b00c62f0f14646
def mutate(self, mutation_model): <NEW_LINE> <INDENT> likelihood = mutation_model.mutation_likelihood <NEW_LINE> strength = mutation_model.mutation_strength * 2 <NEW_LINE> for layer_index in range(len(self.__layers)-1): <NEW_LINE> <INDENT> from_layer = self.__layers[layer_index] <NEW_LINE> to_layer = self.__layers[laye...
Mutates the brain and its neural weights. The mutation is determined by the given mutation_model. If a mutation of a weight occurs it will simply add a random delta (size depending on mutation_model) with an 80% chance. In the other 20% it will flip the sign of the weight.
625941c4283ffb24f3c558f1
def _to_m8(key): <NEW_LINE> <INDENT> if not isinstance(key, datetime): <NEW_LINE> <INDENT> key = Timestamp(key) <NEW_LINE> <DEDENT> return np.int64(lib.pydt_to_i8(key)).view('M8[ns]')
Timestamp-like => dt64
625941c460cbc95b062c6531
@protocolize() <NEW_LINE> def ext_eval_various_random_l2_grayscale_various_renderman(depends_on=('../config/exploratory_renderman_tasks_for_random_l2.py', '../config/various_random_l2_grayscale_models.py', '../config/ten_categories_images.py')): <NEW_LINE> <INDENT> protocols.extract_and_evaluate_protocol('../config/exp...
faces: max: 23.1 min: 12.5 mean: 18.73 std: 2.5 10-way: max: 33.5 min: 14.75 mean: 23.69 std: 3.97 Car vs plane: max: 80 min: 51 mean: 65.8 std: 5.9 Car vs plane with trans avg, max: max: 73.75 min: 42.6 mean: 62.7 std: 6.1 Car vs plane with trans avg: ...
625941c43617ad0b5ed67ee7
def _prepare_docker_env(conf: AiscalatorConfig, program, reason): <NEW_LINE> <INDENT> logger = logging.getLogger(__name__) <NEW_LINE> commands = [ "docker", "run", "--name", conf.step_container_name() + "_" + reason, "--rm" ] <NEW_LINE> for env in conf.user_env_file(conf.step_field("task.env")): <NEW_LINE> <INDENT> if ...
Assembles the list of commands to execute a docker run call When calling "docker run ...", this function also adds a set of additional parameters to mount the proper volumes and expose the correct environment for the call in the docker image mapped to the host directories. This is done so only some specific data and c...
625941c407d97122c4178876
def update(self, friendly_name=values.unset, max_size=values.unset): <NEW_LINE> <INDENT> data = values.of({'FriendlyName': friendly_name, 'MaxSize': max_size, }) <NEW_LINE> payload = self._version.update(method='POST', uri=self._uri, data=data, ) <NEW_LINE> return QueueInstance( self._version, payload, account_sid=self...
Update the QueueInstance :param unicode friendly_name: A string to describe this resource :param unicode max_size: The max number of calls allowed in the queue :returns: The updated QueueInstance :rtype: twilio.rest.api.v2010.account.queue.QueueInstance
625941c47cff6e4e81117974
def tests_finished(self): <NEW_LINE> <INDENT> pass
Callback when tests are finished
625941c4be383301e01b5477
def get_xml_records(fields, filename, xpath): <NEW_LINE> <INDENT> tree = ElementTree.parse(filename) <NEW_LINE> root = tree.getroot() <NEW_LINE> records = root.iterfind('%s%s' % (XML_NAMESPACE, xpath)) <NEW_LINE> return [get_record_from_xml(fields, rec) for rec in records]
Get all the records from the xml that correspond to the given xpath.
625941c4442bda511e8be408
def diff_all_modules_using_global(glob_first, glob_second, config): <NEW_LINE> <INDENT> result = Result(Result.Kind.NONE, glob_first.name, glob_second.name) <NEW_LINE> if glob_first.name != glob_second.name: <NEW_LINE> <INDENT> result.kind = Result.Kind.NOT_EQUAL <NEW_LINE> return result <NEW_LINE> <DEDENT> srcs_first ...
Compare semantics of all modules using given global variable. Finds all source files that use the given globals and compare all of them. :param glob_first: First global to compare :param glob_second: Second global to compare :param config: Configuration
625941c4377c676e91272197
def playerStandings(): <NEW_LINE> <INDENT> DB = connect() <NEW_LINE> c = DB.cursor() <NEW_LINE> c.execute("select * from standings order by total_wins desc") <NEW_LINE> results = c.fetchall() <NEW_LINE> DB.commit() <NEW_LINE> DB.close() <NEW_LINE> return results
Returns a list of the players and their win records, sorted by wins. The first entry in the list should be the player in first place, or a player tied for first place if there is currently a tie. Returns: A list of tuples, each of which contains (id, name, wins, matches): id: the player's unique id (assigned by...
625941c407f4c71912b1146f
def roundOneLess(self): <NEW_LINE> <INDENT> self.roundsToGo -= 1
Take one round out of the player.
625941c431939e2706e4ce5a
@pytest.mark.parametrize("value", [ dict({'ticks': 0, 'percent_rh': 0.0}), dict({'ticks': 65535, 'percent_rh': 100.0}), ]) <NEW_LINE> def test_humidity(value): <NEW_LINE> <INDENT> result = Shtc3Humidity(value.get('ticks')) <NEW_LINE> assert type(result) is Shtc3Humidity <NEW_LINE> assert type(result.ticks) is int <NEW_...
Test if the Humidity() type works as expected for different values.
625941c4d8ef3951e324352b
def how_many(aDict): <NEW_LINE> <INDENT> values=[] <NEW_LINE> n = [] <NEW_LINE> for v in aDict.values(): <NEW_LINE> <INDENT> for i in range(len(v)): <NEW_LINE> <INDENT> n.append(v[i]) <NEW_LINE> <DEDENT> <DEDENT> print(n) <NEW_LINE> return len(n)
aDict: A dictionary, where all the values are lists. returns: int, how many values are in the dictionary.
625941c48a43f66fc4b54055
def _client_thread(self, host, port): <NEW_LINE> <INDENT> time.sleep(1) <NEW_LINE> with open(self.TEST_FILE, 'rb') as f, client(self.HOST, self.PORT) as c: <NEW_LINE> <INDENT> msg = recv(c, 4096) <NEW_LINE> raw = read(f, 4096) <NEW_LINE> self.assertEqual(msg, raw)
ktls test client thread
625941c4ec188e330fd5a790
def testBasic(self): <NEW_LINE> <INDENT> graph=Graph() <NEW_LINE> dataShape = (1,10,10,10,1) <NEW_LINE> data = numpy.indices(dataShape) <NEW_LINE> precomputedData = data * 10 <NEW_LINE> computeCount = [0] <NEW_LINE> def compute(x): <NEW_LINE> <INDENT> computeCount[0] += 1 <NEW_LINE> return x*10 <NEW_LINE> <DEDENT> opSl...
Test the OpPrecomputedInput oeprator.
625941c430bbd722463cbdb3
def observation_input(ob_space, batch_size=None, name='Ob', scale=False): <NEW_LINE> <INDENT> if isinstance(ob_space, Discrete): <NEW_LINE> <INDENT> input_x = tf.placeholder(shape=(batch_size,), dtype=tf.int32, name=name) <NEW_LINE> processed_x = tf.to_float(tf.one_hot(input_x, ob_space.n)) <NEW_LINE> return input_x, p...
Build observation input with encoding depending on the observation space type When using Box ob_space, the input will be normalized between [1, 0] on the bounds ob_space.low and ob_space.high. :param ob_space: (Gym Space) The observation space :param batch_size: (int) batch size for input (default ...
625941c4435de62698dfdc3a
def _find(self, table='', where=None, field=None, order=None, limit=1, sql=None): <NEW_LINE> <INDENT> if not sql: <NEW_LINE> <INDENT> where = where if where else '1=1' <NEW_LINE> field = field if field else '*' <NEW_LINE> order = order if order else '' <NEW_LINE> limit = ('limit %s' % str(limit)) if limit else '' <NEW_...
内部调用函数 Args: @param table : 表名 @param where : 查询条件 @param field : 要查询的列 @param password : 密码 @param order : 排序,例:ORDER BY create_time DESC @param sql : 完整的SQL,前面的where、field、order均不在生效 Returns:
625941c426068e7796caeccb
def start( self, controllers ): <NEW_LINE> <INDENT> OVSSwitch.start( self, controllers ) <NEW_LINE> if self.switchIP is not None: <NEW_LINE> <INDENT> self.cmd( 'ifconfig', self, self.switchIP )
Start and set management IP address
625941c44f88993c3716c057
def test_encoder_callable(self): <NEW_LINE> <INDENT> with warnings.catch_warnings(record=True) as warn_cm: <NEW_LINE> <INDENT> encoded = json.dumps({"fidelity": lambda x: x}, cls=RuntimeEncoder) <NEW_LINE> decoded = json.loads(encoded, cls=RuntimeDecoder) <NEW_LINE> self.assertIsNone(decoded["fidelity"]) <NEW_LINE> sel...
Test encoding a callable.
625941c46fb2d068a760f08a
def __repr__(self): <NEW_LINE> <INDENT> if self.arc is None: <NEW_LINE> <INDENT> return str(self.initial) <NEW_LINE> <DEDENT> elif self.arc.action: <NEW_LINE> <INDENT> return (str(self.initial)+"\n --"+str(self.arc.action) +"--> "+str(self.arc.to_node)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return str(self.in...
returns a string representation of a path
625941c40fa83653e4656faa
def toNode(shape): <NEW_LINE> <INDENT> from pivy import coin <NEW_LINE> buf = shape.writeInventor(2,0.01) <NEW_LINE> buf = buf.replace("\n","") <NEW_LINE> buf = re.findall("point \[(.*?)\]",buf) <NEW_LINE> pts = [] <NEW_LINE> for c in buf: <NEW_LINE> <INDENT> pts.extend(c.split(",")) <NEW_LINE> <DEDENT> pc = [] <NEW_LI...
builds a linear pivy node from a shape
625941c4bf627c535bc131bd
def DBSCAN_radec(skycoo, arg_mdist=None, max_dist=2., min_N=1): <NEW_LINE> <INDENT> if (arg_mdist is None): <NEW_LINE> <INDENT> fd1 = lambda pos_x, pos_all: map(pos_x.separation, pos_all) <NEW_LINE> d1 = fd1(skycoo[0], skycoo) <NEW_LINE> logging.warning("Not parallel :|") <NEW_LINE> mdist = np.zeros((len(skycoo), len(s...
Clustering over RA-DEC coordinates. To do this, distance matrix needs to be calculated. Parameters ---------- skycoo: SkyCoord() sky coordinate object from astropy arg_mdist: ndarray either None to calculate the distance matrix, or a square matrix being the distance matrix max_dist: float maximum dist...
625941c44e696a04525c943a
def New(*args, **kargs): <NEW_LINE> <INDENT> obj = itkCropLabelMapFilterLM2.__New_orig__() <NEW_LINE> import itkTemplate <NEW_LINE> itkTemplate.New(obj, *args, **kargs) <NEW_LINE> return obj
New() -> itkCropLabelMapFilterLM2 Create a new object of the class itkCropLabelMapFilterLM2 and set the input and the parameters if some named or non-named arguments are passed to that method. New() tries to assign all the non named parameters to the input of the new objects - the first non named parameter in the fir...
625941c4a219f33f3462895a
def __create_cache(self, uri_list, smart = -1): <NEW_LINE> <INDENT> cn = self._getConnection() <NEW_LINE> c = cn.cursor() <NEW_LINE> r = 0 <NEW_LINE> uri_set = set(uri_list) <NEW_LINE> deleted = filter(lambda i: i not in uri_set, self.__meta_uri_list) <NEW_LINE> for uri in deleted: <NEW_LINE> <INDENT> c.execute(SQL_MCA...
create cache and return the number of newly created meta caches smart is how fast you want to do that: * 0 force regeneration of entire meta cache * 1 regenerate cache when hash differs (it would need to open every kitab) * 2 regenerate when mtime differs * -1 do not update cache for exiting meta (even...
625941c463b5f9789fde70d3
def PyQtColor(default="white", allow_none=False, **metadata): <NEW_LINE> <INDENT> if default is None: <NEW_LINE> <INDENT> allow_none = True <NEW_LINE> <DEDENT> if allow_none: <NEW_LINE> <INDENT> return Trait( default, None, standard_colors, convert_to_color, editor=get_color_editor, **metadata, ) <NEW_LINE> <DEDENT> re...
Defines PyQt-specific color traits.
625941c4711fe17d8254235d
def get_code_from_file(self, data): <NEW_LINE> <INDENT> return super(Listing, self).run()
Create CodeBlock nodes from file object content
625941c4ad47b63b2c509f6e
def reduce_armor(self, amount): <NEW_LINE> <INDENT> if self.armor - amount <= 0: <NEW_LINE> <INDENT> bees = list(self.place.bees) <NEW_LINE> for b in bees: <NEW_LINE> <INDENT> b.reduce_armor(self.damage) <NEW_LINE> <DEDENT> <DEDENT> return Insect.reduce_armor(self, amount)
Reduce armor by AMOUNT, and remove the FireAnt from its place if it has no armor remaining. If the FireAnt dies, damage each of the bees in the current place.
625941c4cc40096d6159593f
def create_volume( self, size, display_name, server_id=None, display_description=None, snapshot_id=None, imageRef=None, volume_type=None, metadata=None, project=None): <NEW_LINE> <INDENT> r = self.volumes_post( size, display_name, server_id=server_id, display_description=display_description, snapshot_id=snapshot_id, im...
:returns: (dict) new volumes' details
625941c4379a373c97cfab33
def tick(self): <NEW_LINE> <INDENT> self.theta += 3 <NEW_LINE> self.move()
隕石を移動する
625941c45fc7496912cc396d
def plot(data_dict, cols, title,resultdir,*, unique_keys=None, sort_by='size', inters_size_bounds=(1, np.inf), inters_degree_bounds=(1, np.inf), additional_plots=None, query=None): <NEW_LINE> <INDENT> query = [] if query is None else query <NEW_LINE> ap = [] if additional_plots is None else additional_plots <NEW_LINE> ...
Plots a main set of graph showing intersection size, intersection matrix and the size of base sets. If given, additional plots are placed below the main graph. :param data_dict: dictionary like {data_frame_name: data_frame} :param unique_keys: list. Specifies the names of the columns that, together, can uniquely iden...
625941c4c432627299f04c33
def __call__(self, dev): <NEW_LINE> <INDENT> if filter_device_by_class(dev.idVendor, dev.idProduct, dev.bDeviceClass): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> dev.get_active_configuration() <NEW_LINE> device_string = dev.product <NEW_LINE> <DEDENT> except usb.core.USBError as error...
Return True if this is a DAP device, False otherwise
625941c4009cb60464c633a1
def get_norm(self, component=None, summed=False): <NEW_LINE> <INDENT> raise NotImplementedError("'Wavepacket' is an abstract interface.")
Calculate the :math:`L^2` norm of the wavepacket :math:`|\Psi\rangle`. :raise NotImplementedError: Abstract interface.
625941c432920d7e50b281bd