code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def load_module(self, chain): <NEW_LINE> <INDENT> module_names = chain.split('.') <NEW_LINE> if module_names[0] in MODULES: <NEW_LINE> <INDENT> base_module = MODULES[module_names[0]] <NEW_LINE> for module in module_names: <NEW_LINE> <INDENT> if (isinstance(base_module, ModuleType) and module in base_module.submodules):...
Finds the module in the set of available modules. Args: chain (str): A chain of module imports (e.g., "matplotlib.pyplot") Returns: ModuleType: The specific module with its members, or an empty module type.
625941b9c432627299f04abb
def make_move_on_list(numbers): <NEW_LINE> <INDENT> assert len(numbers) == 4 <NEW_LINE> numbers.sort(key=bool, reverse=True) <NEW_LINE> newLst = [] <NEW_LINE> i = 0 <NEW_LINE> while i < 4: <NEW_LINE> <INDENT> newLst.append(numbers[i]) <NEW_LINE> if not numbers[i] or i == 3: <NEW_LINE> <INDENT> break; <NEW_LINE> <DEDENT...
Make a move given a list of 4 numbers using the rules of the 2048 game. Argument: numbers -- a list of 4 numbers Return value: the list after moving the numbers to the left.
625941b930dc7b76659017e1
def update_site_forward(apps, schema_editor): <NEW_LINE> <INDENT> Site = apps.get_model('sites', 'Site') <NEW_LINE> Site.objects.update_or_create( id=settings.SITE_ID, defaults={ 'domain': '127.0.0.1:8000', 'name': 'sozluk' } )
Set site domain and name.
625941b95510c4643540f26e
def OnTouchLeave(self,*args): <NEW_LINE> <INDENT> pass
OnTouchLeave(self: ContentElement,e: TouchEventArgs) Provides class handling for the System.Windows.ContentElement.TouchLeave routed event that occurs when a touch moves from inside to outside the bounds of this element. e: A System.Windows.Input.TouchEventArgs that contains the event data.
625941b929b78933be1e5530
def s_bigword(x): <NEW_LINE> <INDENT> return s_long(x, endian=BIG_ENDIAN)
Big word.
625941b9e1aae11d1e749b2b
def roles_from_payload( self, payload: discord.RawReactionActionEvent ) -> List[discord.Role]: <NEW_LINE> <INDENT> cursor = self.bot.database.execute( "SELECT data FROM rolekiosk_entries WHERE oid=:oid", { "oid": self.bot.objects.by_data( m=[payload.channel_id, payload.message_id] ) }, ) <NEW_LINE> result = cursor.fetc...
Turn a reaction payload into a list of roles to apply or take away.
625941b9d99f1b3c44c6740e
def read_pressure(self): <NEW_LINE> <INDENT> UT = self.read_raw_temp() <NEW_LINE> UP = self.read_raw_pressure() <NEW_LINE> X1 = ((UT - self.cal_AC6) * self.cal_AC5) >> 15 <NEW_LINE> X2 = (self.cal_MC << 11) / (X1 + self.cal_MD) <NEW_LINE> B5 = X1 + X2 <NEW_LINE> B6 = B5 - 4000 <NEW_LINE> X1 = (self.cal_B2 * (B6 * B6) >...
Gets the compensated pressure in Pascals.
625941b9baa26c4b54cb0f9a
def ldap_connect(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> conn = ldap.initialize(settings.LDAP_SERVER) <NEW_LINE> conn.simple_bind_s(settings.LDAP_AUTH_DN, settings.LDAP_PASS) <NEW_LINE> print("\nConnected to LDAP server {server}\n".format(server=settings.LDAP_SERVER)) <NEW_LINE> return conn <NEW_LINE> <DEDENT> ...
Returns an LDAP connection object, to be used by various search functions.
625941b90c0af96317bb8060
def testGetVotersToDial(self): <NEW_LINE> <INDENT> voters1 = self.campaign1.getVotersToDial() <NEW_LINE> voters2 = self.campaign2.getVotersToDial() <NEW_LINE> self.assertEqual(voters2.count(), 1) <NEW_LINE> self.assertFalse(voters2.filter(pk__in=[3,4,5,6]).exists()) <NEW_LINE> self.assertTrue(voters1.filter(pk=7).exist...
Test the Campaign model's getVotersToDial method, which should filter the query set returned by the method getVotersToContact voters without valid phone contact information. Phone contact information is invalid if both phone_numberX fields are blank or if no available phone number has less than two reports of being in...
625941b92c8b7c6e89b3563a
def __init__(self, dbconn): <NEW_LINE> <INDENT> self.dbconn = dbconn <NEW_LINE> self.db = None
Initialize the database :param dbconn: a DbConnection object
625941b910dbd63aa1bd2a26
def fitness(self, outputs): <NEW_LINE> <INDENT> names = outputs.keys() <NEW_LINE> names.sort() <NEW_LINE> values = [(outputs[k], self.targets[k][0]) for k in names] <NEW_LINE> weights = np.array([self.targets[k][1] for k in names]) <NEW_LINE> norm_error = lambda v: ((max(v)-min(v))/float(max(v)))**2 <NEW_LINE> errors =...
Gets scalar objective fitness value for a set of output criteria
625941b9a17c0f6771cbdecb
def _predict(self, X): <NEW_LINE> <INDENT> self._find_neighbours(X) <NEW_LINE> return [max_occurence(row) for row in self._neighbours]
Prediction using a majority classifier :return:
625941b9435de62698dfdacb
def is_same_entry(entry_1, entry_2): <NEW_LINE> <INDENT> if entry_1 == entry_2: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if os.path.realpath(entry_1) == os.path.realpath(entry_2): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if (os.path.basename(entry_1) == os.path.basename(entry_2) and (os.path.basen...
Return True iff both paths can be considered to point to the same module. This is the case if and only if at least one of these conditions holds: - They are equal. - Their real paths are equal. - They share the same temporary work directory and module file name.
625941b921bff66bcd6847cc
def tcl_set_generic(self, name, value): <NEW_LINE> <INDENT> return 'set_parameter -name ' + str(name) + ' ' + str(value) + '\n'
Return the Quartus API TCL command string: set_parameter -name *<name>* *<value>*
625941b9b57a9660fec336f8
def extract_absolute_tempo_envelope(self, start_beat: float = 0, step_size: float = 0.1, tolerance: float = 0.005) -> TempoEnvelope: <NEW_LINE> <INDENT> if self.is_master(): <NEW_LINE> <INDENT> return self.tempo_history.as_tempo_envelope() <NEW_LINE> <DEDENT> clocks = self.inheritance() <NEW_LINE> tempo_histories = [de...
Extracts this clock's absolute TempoHistory (as opposed to the TempoHistory relative to parent clock). Used when creating a score from this clock's point of view. :param start_beat: where on the TempoHistory to start :param step_size: granularity :param tolerance: error tolerance with which we allow a step to simply e...
625941b95e10d32532c5eda6
def post(self): <NEW_LINE> <INDENT> if request.data["username"].strip() and request.data["password"].strip(): <NEW_LINE> <INDENT> user = User.query.filter_by( username=request.data["username"]).first() <NEW_LINE> if user: <NEW_LINE> <INDENT> res = { "message": "User already exists. Please login" } <NEW_LINE> return mak...
for requests of kind post from /auth/register/
625941b9099cdd3c635f0ad4
def list( self, filter=None, top=None, skiptoken=None, custom_headers=None, raw=False, **operation_config): <NEW_LINE> <INDENT> def internal_paging(next_link=None, raw=False): <NEW_LINE> <INDENT> if not next_link: <NEW_LINE> <INDENT> url = self.list.metadata['url'] <NEW_LINE> path_format_arguments = { 'subscriptionId':...
Lists the marketplaces for a scope by subscriptionId. Marketplaces are available via this API only for May 1, 2014 or later. :param filter: May be used to filter marketplaces by properties/usageEnd (Utc time), properties/usageStart (Utc time), properties/resourceGroup, properties/instanceName or properties/instance...
625941b9796e427e537b043a
def encoder_cfg(self, max_rpm: int, encdr_res: int, res_power: int, stall_ms: int): <NEW_LINE> <INDENT> darr = [] <NEW_LINE> darr.extend(split_high_low(max_rpm)) <NEW_LINE> darr.extend(split_high_low(encdr_res)) <NEW_LINE> darr.append(res_power) <NEW_LINE> darr.append(stall_ms) <NEW_LINE> self.b.write_i2c_block_data(se...
Write encoder configuration data to the device.
625941b973bcbd0ca4b2bef5
def on_open_database(self, event): <NEW_LINE> <INDENT> dialog = wx.FileDialog( parent=self, message="Open", defaultFile="", wildcard="Skype database (*.db)|*.db|All files|*.*", style=wx.FD_FILE_MUST_EXIST | wx.FD_OPEN | wx.RESIZE_BORDER ) <NEW_LINE> if wx.ID_OK == dialog.ShowModal(): <NEW_LINE> <INDENT> filename = dial...
Handler for open database menu or button, displays a file dialog and loads the chosen database.
625941b97b25080760e392d2
def productExceptSelf(self, nums): <NEW_LINE> <INDENT> result = [1] * len(nums) <NEW_LINE> l, r = 1, 1 <NEW_LINE> for i in range(len(nums)): <NEW_LINE> <INDENT> result[i] *= l <NEW_LINE> l *= nums[i] <NEW_LINE> result[len(nums) - i - 1] *= r <NEW_LINE> r *= nums[len(nums) - i - 1] <NEW_LINE> <DEDENT> return result
:type nums: List[int] :rtype: List[int]
625941b95166f23b2e1a4fd1
def pr_request_grandfather_name(default): <NEW_LINE> <INDENT> root_org = current.auth.root_org_name() <NEW_LINE> if root_org in (ARCS, BRCS, IRCS): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False
Whether to request GrandFather's Name in AddPersonWidget2
625941b9be383301e01b5304
def load(self): <NEW_LINE> <INDENT> return dict()
load from file and return a dict. subclass of BaseParser should overwrite this method. :return: a list of loaded values. each value is a dict with all keys in config and its value.
625941b930c21e258bdfa315
def get(self, sid): <NEW_LINE> <INDENT> return FunctionVersionContext( self._version, service_sid=self._solution['service_sid'], function_sid=self._solution['function_sid'], sid=sid, )
Constructs a FunctionVersionContext :param sid: The SID that identifies the Function Version resource to fetch :returns: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionContext :rtype: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionContext
625941b963f4b57ef0000f99
def AdamOptimizer(loss, learningRate, clipGrads=False): <NEW_LINE> <INDENT> optimizer = tf.train.AdamOptimizer(learningRate) <NEW_LINE> if clipGrads: <NEW_LINE> <INDENT> gradients, variables = zip(*optimizer.compute_gradients(loss)) <NEW_LINE> gradients, _ = tf.clip_by_global_norm(gradients, 5.0) <NEW_LINE> trainOperat...
Given the network loss, constructs the training op needed to train the network using adam optimization. Returns: the operation that begins the backpropogation through the network (i.e., the operation that minimizes the loss function).
625941b94d74a7450ccd403a
def extract_model_info(self, ell_model, labels_file): <NEW_LINE> <INDENT> if not ell_model: <NEW_LINE> <INDENT> self.model_name = "d_I160x160x3CMCMCMCMCMCMC1AS" <NEW_LINE> self.ell_model = self.model_name + ".ell" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.ell_model = ell_model <NEW_LINE> name,ext = os.path.spl...
Extracts information about a model
625941b9c4546d3d9de728a8
def tearDown(self): <NEW_LINE> <INDENT> self.router.connect() <NEW_LINE> self.router.purge() <NEW_LINE> self.message_worker.connect() <NEW_LINE> self.message_worker.purge()
Manually purge the router We need a persistent message router to test features since we send the message THEN start the router but we don't want message to remain in the queue between to test
625941b955399d3f0558852b
def passive_power_spectrum_model_hydro( f, fc, diffusion_constant, gamma0, bead_radius, rho_sample, rho_bead, distance_to_surface, ): <NEW_LINE> <INDENT> re_drag, im_drag = calculate_complex_drag( f, gamma0, rho_sample, bead_radius, distance_to_surface ) <NEW_LINE> frequency_m = calculate_dissipation_frequency(gamma0, ...
Theoretical model for the hydrodynamically correct power spectrum. Parameters ---------- f : numpy.ndarray Frequency values, in Hz. fc : float Corner frequency, in Hz. diffusion_constant : float Diffusion constant, in (a.u.)^2/s gamma0 : float Drag coefficient, in mPas. bead_radius : float Bead rad...
625941b997e22403b379ce11
def isEqualWithoutConsideringStr(self, *args): <NEW_LINE> <INDENT> return _MEDCalculator.MEDCouplingTimeDiscretization_isEqualWithoutConsideringStr(self, *args)
isEqualWithoutConsideringStr(self, MEDCouplingTimeDiscretization other, double prec) -> bool 1
625941b966656f66f7cbc022
def train_network(model, epochs = 5): <NEW_LINE> <INDENT> modelname = "model" <NEW_LINE> print(model.summary()) <NEW_LINE> data = DataFeeder() <NEW_LINE> callbacks = [ModelCheckpoint('model{epoch:02d}.h5')] <NEW_LINE> model.compile(optimizer = "adam", loss = "mse") <NEW_LINE> history = model.fit_generator(data.fetch_tr...
Main script for training the Behavioral Cloning Network model
625941b9a79ad161976cbfbd
def example_game(self): <NEW_LINE> <INDENT> animations = [] <NEW_LINE> animations.append(self.flip_cell(2, 2)) <NEW_LINE> animations.append(self.flip_cell(2, 3)) <NEW_LINE> self.play(*animations) <NEW_LINE> animations = [] <NEW_LINE> animations.append(self.flip_cell(5, 6)) <NEW_LINE> animations.append(self.flip_cell(6,...
An example of how the animation can be done
625941b98a43f66fc4b53ee1
def play(self): <NEW_LINE> <INDENT> print(self.state.instructions) <NEW_LINE> print(self.state + '\n') <NEW_LINE> while self.state.possible_next_moves(): <NEW_LINE> <INDENT> if self.state.next_player == 'p1': <NEW_LINE> <INDENT> m = self.state.get_move() <NEW_LINE> while not m in self.state.possible_next_moves(): <NEW_...
(GameView) -> NoneType Play a game.
625941b9046cf37aa974cbc2
def check_aliens_bottom(ai_settings, stats, screen, ship, aliens, bullets): <NEW_LINE> <INDENT> screen_rect = screen.get_rect() <NEW_LINE> for alien in aliens.sprites(): <NEW_LINE> <INDENT> if alien.rect.bottom >= screen_rect.bottom: <NEW_LINE> <INDENT> ship_hit(ai_settings, stats, screen, ship, aliens, bullets) <NEW_L...
Checks of any aliens have reached the bottom of the screen
625941b96aa9bd52df036c1a
def calDesviacionEstandar(self): <NEW_LINE> <INDENT> return math.sqrt(self.sumatoriaMedia()/(self.numero-1))
Esta funcion calcula la Desviacion estandar de una sumatoria regresa el calculo
625941b999fddb7c1c9de20b
def raise_deprecation_error( *, deprecated_qual_name_usage: str, new_qual_name_usage: str, to_be_removed_in_version: str, ) -> NoReturn: <NEW_LINE> <INDENT> check_overdue(deprecated_qual_name_usage, to_be_removed_in_version) <NEW_LINE> message = ( f"Usage of {deprecated_qual_name_usage!r} was deprecated, " f"use {new_q...
Raise :class:`GlotaranDeprectedApiError` error, with formatted message. This should only be used if there is no reasonable way to keep the deprecated usage functional! Parameters ---------- deprecated_qual_name_usage : str Old usage with fully qualified name e.g.: ``'glotaran.read_model_from_yaml(model_yml_st...
625941b930dc7b76659017e2
def check_directions(next_door, current_node, goal_node, chip, crossroad, travelled_path, colide): <NEW_LINE> <INDENT> if next_door[2] < 0 or next_door[2] > 7: <NEW_LINE> <INDENT> return crossroad <NEW_LINE> <DEDENT> if next_door[0] < 0 or next_door[0] > chip.width - 1 or next_door[1] < 0 or next_door[1] > chip.height ...
Check a neighbouring coordinate on validity. Args: next_door (int): Coordinates of a crossing next to the current coordinate current_node (object): The heuristics form the current coordinates goal_node (object): The heuristics from the goal coordinates target_coords (int): The gate coordinates which th...
625941b9046cf37aa974cbc3
def crawler(url, keyword): <NEW_LINE> <INDENT> code = requests.get(url) <NEW_LINE> plain = code.text <NEW_LINE> s = BeautifulSoup(plain, "html.parser") <NEW_LINE> answer = '' <NEW_LINE> for text in s.findAll('a', string=re.compile('.* {0} .*'.format(keyword)), recursive=True,): <NEW_LINE> <INDENT> href = text.get('href...
Crawler uses BeautifulSoup for crawling a webpage :url - the url to crawl from :keyword - the keyword to search for :return string with the
625941b9e8904600ed9f1da1
def test_creation_OnUpdateSchedule_success_with_exec_on_load_True(self): <NEW_LINE> <INDENT> sc = schedules.OnUpdateSchedule(exec_on_load=True) <NEW_LINE> self.assertEqual(sc.exec_on_load, True) <NEW_LINE> self.assertEqual(sc.activation_metrics, []) <NEW_LINE> self.assertEqual(sc.meets(), False)
creating a OnUpdateSchedule object should succeed with exec_on_load True
625941b915fb5d323cde0982
def symbol(self): <NEW_LINE> <INDENT> cur = self.currentToken <NEW_LINE> self.advance() <NEW_LINE> return cur
Returns the character which is the current token, and advances the input. Should be called only when tokenType() is SYMBOL.
625941b97d43ff24873a2b1c
def insertplainheader(lines, header, value): <NEW_LINE> <INDENT> newprio = PLAINHEADERS[header.lower()] <NEW_LINE> bestpos = len(lines) <NEW_LINE> for i, line in enumerate(lines): <NEW_LINE> <INDENT> if ':' in line: <NEW_LINE> <INDENT> lheader = line.split(':', 1)[0].strip().lower() <NEW_LINE> lprio = PLAINHEADERS.get(...
For lines containing a plain patch header, add a header line with value. >>> insertplainheader([], 'Date', 'z') ['Date: z'] >>> insertplainheader([''], 'Date', 'z') ['Date: z', ''] >>> insertplainheader(['x'], 'Date', 'z') ['Date: z', '', 'x'] >>> insertplainheader(['From: y', 'x'], 'Date', 'z') ['From: y', 'Date: z', ...
625941b9fbf16365ca6f6035
def decode_pasv_reply(raw_reply): <NEW_LINE> <INDENT> reply = raw_reply.decode() <NEW_LINE> h1, h2, h3, h4, p1, p2 = reply[reply.find('(') + 1:reply.find(')')].split(',') <NEW_LINE> host = '.'.join([h1, h2, h3, h4]) <NEW_LINE> port = int(p1)*256 + int(p2) <NEW_LINE> return host, port
:type raw_reply: bytes
625941b9c432627299f04abc
def create_fd (self): <NEW_LINE> <INDENT> if self.filename is None: <NEW_LINE> <INDENT> return i18n.get_encoded_writer(encoding=self.output_encoding, errors=self.codec_errors) <NEW_LINE> <DEDENT> return codecs.open(self.filename, "wb", self.output_encoding, self.codec_errors)
Create open file descriptor.
625941b98e71fb1e9831d625
def delete(self, imageUrl): <NEW_LINE> <INDENT> print("开始删除图片") <NEW_LINE> deleteUrl = imageUrl.delete <NEW_LINE> r = requests.get(deleteUrl) <NEW_LINE> if r.status_code == 200: <NEW_LINE> <INDENT> return [0, "删除成功"] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [-1, "未知异常"]
删除图片 :param imageUrl: 待上传图片的ImageUrl对象 :return: [int, string] 状态码,状态
625941b98e7ae83300e4ae44
def add_to_sample_data(self, forecast, outfit, athlete_name='default', **kwargs): <NEW_LINE> <INDENT> if self._sample_data is None: <NEW_LINE> <INDENT> self._sample_data = self.get_dataframe_format() <NEW_LINE> <DEDENT> forecast = vars(forecast) if type(forecast) is not dict else forecast <NEW_LINE> fields = {x: outfit...
Add a row of sample data to a model file. :param forecast: :param outfit: :param athlete_name: :return:
625941b955399d3f0558852c
def class2size(pred_cls, residual): <NEW_LINE> <INDENT> mean_size = g_type_mean_size[g_class2type[pred_cls]] <NEW_LINE> return mean_size + residual
Inverse function to size2class.
625941b938b623060ff0ac67
def getFileDataLines(self, fileName, lineNo): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> lines = linecache.getlines(fileName, lineNo) <NEW_LINE> return lines[lineNo-1:] <NEW_LINE> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> self.log.error("{}".format(err))
Desc: get data from file
625941b930bbd722463cbc3b
def map_extra_regions(pt): <NEW_LINE> <INDENT> mappings = [] <NEW_LINE> for entry in args.map: <NEW_LINE> <INDENT> elements = entry.split(',') <NEW_LINE> if len(elements) < 2: <NEW_LINE> <INDENT> error("Not enough arguments for --map %s" % entry) <NEW_LINE> <DEDENT> one_map = {} <NEW_LINE> one_map['cmdline'] = entry <N...
Map extra regions specified in command line
625941b91f037a2d8b946077
def __inner_eval(self, data_name, data_idx, feval=None): <NEW_LINE> <INDENT> if data_idx >= self.__num_dataset: <NEW_LINE> <INDENT> raise ValueError("data_idx should be smaller than number of dataset") <NEW_LINE> <DEDENT> self.__get_eval_info() <NEW_LINE> ret = [] <NEW_LINE> if self.__num_inner_eval > 0: <NEW_LINE> <IN...
Evaulate training or validation data
625941b9adb09d7d5db6c60b
def create(self, match_report: MatchReport): <NEW_LINE> <INDENT> self._db_session.merge(match_report) <NEW_LINE> self._db_session.commit()
Creates a new row of match report in the database :param match_report: Match report object containing all the information
625941b950485f2cf553cc11
def get_sections(df): <NEW_LINE> <INDENT> dfd = df.dropna(how='all') <NEW_LINE> secheads = [re.match('//(.*)', s) for s in dfd.iloc[:, 0]] <NEW_LINE> indheads = np.where(secheads)[0] <NEW_LINE> sections = {} <NEW_LINE> for n in range(len(indheads)): <NEW_LINE> <INDENT> secname = secheads[indheads[n]].group(1) <NEW_LINE...
Split into sections indicated by //.*, remove empty rows
625941b938b623060ff0ac68
def xmlOneDotOne(data): <NEW_LINE> <INDENT> desiredOutput = { "display_name": "displayName", "display_short_name": "displayShortName", "incoming_hostname": "hostname", "incoming_port": "port", "incoming_socket_type": "socketType", "incoming_username_form": "username", "incoming_authentication": "authentication", "outgo...
Return the configuration using the XML document that Thunderbird is expecting.
625941b94c3428357757c1a3
def __init__(self,SRQ=0,RFC=0,Site='NLCWIT',Client='None',Requestor='None',Description='None'): <NEW_LINE> <INDENT> self.SRQ = SRQ <NEW_LINE> self.RFC = RFC <NEW_LINE> self.Site = Site <NEW_LINE> self.Client = Client <NEW_LINE> self.Requestor = Requestor <NEW_LINE> self.Description= ...
Initialise default values for SRQProject object
625941b90a366e3fb873e690
def test_timeout_replace_only_when_necessary(self): <NEW_LINE> <INDENT> self.assertEqual( converge( DesiredGroupState(server_config={}, capacity=2), set([server('slowpoke', ServerState.BUILD, created=0), server('old-ok', ServerState.ACTIVE, created=0), server('new-ok', ServerState.ACTIVE, created=3600)]), set(), 3600),...
If a server is timing out *and* we're over capacity, it will be deleted without replacement.
625941b9099cdd3c635f0ad5
def test_transform_record_default_schema(): <NEW_LINE> <INDENT> serializer = SimpleMarshmallowSerializer() <NEW_LINE> data = serializer.transform_record( PersistentIdentifier(pid_type='recid', pid_value='1'), Record({'title': 'test'}) ) <NEW_LINE> assert data == { 'id': '1', 'created': None, 'links': {}, 'metadata': {'...
Test marshmallow serializer without providing a schema.
625941b9ec188e330fd5a61f
def undo_cat(col, lim): <NEW_LINE> <INDENT> def cat_decode(x, limits): <NEW_LINE> <INDENT> for k, v in limits.items(): <NEW_LINE> <INDENT> if x < k: <NEW_LINE> <INDENT> return v <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return col.apply(lambda x: cat_decode(x, lim))
Convert the categorical column to normalized valus Arguments: col {Column} -- The dataframe's column lim {Dict} -- The dictionary containing the limits per catergorical column Returns: Column -- The new column
625941b93d592f4c4ed1cef8
def gyy(xp, yp, zp, prisms): <NEW_LINE> <INDENT> if xp.shape != yp.shape != zp.shape: <NEW_LINE> <INDENT> raise ValueError("Input arrays xp, yp, and zp must have same shape!") <NEW_LINE> <DEDENT> res = 0 <NEW_LINE> for prism in prisms: <NEW_LINE> <INDENT> if prism is None or 'density' not in prism.props: <NEW_LINE> <IN...
yy component of the gravity gradient tensor of a polygonal prism. .. note:: The coordinate system of the input parameters is to be x -> North, y -> East and z -> Down. .. note:: All input values in SI units and output in Eotvos! Parameters: * xp, yp, zp : arrays The x, y, and z coordinates of the computatio...
625941b9e8904600ed9f1da2
def find_vstructures(self,startTraitIdx=0, nTraits=np.inf): <NEW_LINE> <INDENT> T = self.phenoreader.get_nrows() <NEW_LINE> self.vstructures = vstructures.VstructureList() <NEW_LINE> for t in range(startTraitIdx, min(startTraitIdx + nTraits,T)): <NEW_LINE> <INDENT> for isnps, igenes in self.find_vstructures_given_focal...
returns an iterator over all (snp,orth_gene) pairs where snp -> anchor gene -> gene t <- orth gene
625941b9379a373c97cfa9c3
def view(self): <NEW_LINE> <INDENT> return self.__d.treeView
@return QTreeView
625941b9be7bc26dc91cd47e
def run(): <NEW_LINE> <INDENT> run_container("expel-server-run", run_mounts(), ["--publish", "7777:7777/udp"], [])
Run an EXILED server to test your plugin
625941b9a05bb46b383ec6a6
def _ucb_halluc_acq(x): <NEW_LINE> <INDENT> mu, sigma = gp.eval_with_hallucinated_observations(x, halluc_pts, uncert_form='std') <NEW_LINE> return mu + beta_th * sigma
Computes GP-UCB acquisition with hallucinated observations.
625941b9925a0f43d2549ced
def __init__(self, win, cam, forcex=0, forcey=0): <NEW_LINE> <INDENT> if FilterManager.notify is None: <NEW_LINE> <INDENT> FilterManager.notify = directNotify.newCategory("FilterManager") <NEW_LINE> <DEDENT> region = None <NEW_LINE> for dr in win.getDisplayRegions(): <NEW_LINE> <INDENT> drcam = dr.getCamera() <NEW_LINE...
The FilterManager constructor requires you to provide a window which is rendering a scene, and the camera which is used by that window to render the scene. These are henceforth called the 'original window' and the 'original camera.'
625941b9d99f1b3c44c67410
def testNormalizer(self): <NEW_LINE> <INDENT> from spatialdata.units.Nondimensional import Nondimensional <NEW_LINE> normalizer = Nondimensional() <NEW_LINE> normalizer._configure() <NEW_LINE> self.friction.normalizer(normalizer) <NEW_LINE> return
Test normalizer().
625941b90c0af96317bb8062
def test_POST_delete_background(self): <NEW_LINE> <INDENT> self.site_location.background = File(file(self._data_file('logo.png'))) <NEW_LINE> self.site_location.save() <NEW_LINE> c = Client() <NEW_LINE> c.login(username='admin', password='admin') <NEW_LINE> self.POST_data['delete_background'] = 'yes' <NEW_LINE> POST_re...
A POST request to the edit_content view with POST['delete_background'] should remove the background image and redirect back to the edit design view.
625941b90c0af96317bb8063
def receive_packet_out(logical_device_id, egress_port_no, msg): <NEW_LINE> <INDENT> pass
Pass a packet_out message content to adapter so that it can forward it out to the device. This is only called on root devices. :param logical_device_id: :param egress_port: egress logical port number :param msg: actual message :return: None
625941b95166f23b2e1a4fd2
def Conv(X, nbFilters, kernel, stride): <NEW_LINE> <INDENT> channels = X.shape.as_list()[-1] <NEW_LINE> F = tf.get_variable('kernel', [kernel, kernel, channels, nbFilters], tf.float32, tf.contrib.layers.xavier_initializer()) <NEW_LINE> b = tf.get_variable('Cbias', [nbFilters], tf.float32, tf.zeros_initializer()) <NEW_L...
:param X: input tensor :param nbFilters: number of filters :param kernel: kernel shape for convolution operation :param stride: stride for convolution operation :return: Convolution operation with bias
625941b967a9b606de4a7d36
def next_url(request): <NEW_LINE> <INDENT> next_page = request.REQUEST.get("next", "") <NEW_LINE> host = request.get_host() <NEW_LINE> return next_page if next_page and is_safe_url( next_page, host=host) else None
Returns URL to redirect to from the ``next`` param in the request.
625941b921bff66bcd6847cf
def die(*args): <NEW_LINE> <INDENT> print_err(*args) <NEW_LINE> sys.exit(2)
Prints an error message on stderr and aborts execution with return code set to 2.
625941b93617ad0b5ed67d79
def findRightInterval(self, intervals): <NEW_LINE> <INDENT> data = [] <NEW_LINE> for i, interval in enumerate(intervals): <NEW_LINE> <INDENT> data.append((interval.start, True, i)) <NEW_LINE> data.append((interval.end, False, i)) <NEW_LINE> <DEDENT> data.sort() <NEW_LINE> ri = {} <NEW_LINE> n = len(data) <NEW_LINE> sp ...
:type intervals: List[Interval] :rtype: List[int]
625941b985dfad0860c3acd2
@socketio.on('joined', namespace='/chat') <NEW_LINE> def joined(message): <NEW_LINE> <INDENT> room = session.get('room') <NEW_LINE> join_room(room) <NEW_LINE> emit('status', {'msg': session.get('name') + ' joined'}, room=room)
Sent by clients when they enter a room. A status message is broadcast to all people in the room.
625941b98e7ae83300e4ae45
def get_story_summary_from_model(story_summary_model): <NEW_LINE> <INDENT> return story_domain.StorySummary( story_summary_model.id, story_summary_model.title, story_summary_model.language_code, story_summary_model.version, story_summary_model.node_count, story_summary_model.story_model_created_on, story_summary_model....
Returns a domain object for an Oppia story summary given a story summary model. Args: story_summary_model: StorySummaryModel. Returns: StorySummary.
625941b9293b9510aa2c3112
def book_isbn_to_id(self, isbn): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> response = self.get('book/isbn_to_id', {'isbn': isbn})
Get the Goodreads book ID given an ISBN: http://www.goodreads.com/api#book.isbn_to_id
625941b9cc0a2c11143dcd12
def get_form_kwargs(self, step=None): <NEW_LINE> <INDENT> if step in ('token', 'backup'): <NEW_LINE> <INDENT> return { 'user': self.get_user(), 'initial_device': self.get_device(step), } <NEW_LINE> <DEDENT> return {}
AuthenticationTokenForm requires the user kwarg.
625941b9090684286d50eb5a
def angle_cycle(self): <NEW_LINE> <INDENT> return self._cmd('ang')
Cycles through available camera angles
625941b930c21e258bdfa317
def allocate(self, value=0, **kwargs): <NEW_LINE> <INDENT> if value in ['random', 'random_int']: <NEW_LINE> <INDENT> out = self.get_uniform_copy() <NEW_LINE> shape = out.as_array().shape <NEW_LINE> seed = kwargs.get('seed', None) <NEW_LINE> if seed is not None: <NEW_LINE> <INDENT> numpy.random.seed(seed) <NEW_LINE> <DE...
Alias to get_uniform_copy for CIL/SIRF compatibility.
625941b963f4b57ef0000f9b
def AddLinks(sf_name, src_dir, dest_dir): <NEW_LINE> <INDENT> sf_path_in = os.path.join(src_dir, sf_name) <NEW_LINE> sf_path_basename = os.path.join(sf_path_in, sf_name) <NEW_LINE> sf_path_out = os.path.join(dest_dir, sf_name) <NEW_LINE> gdf = gpd.read_file(sf_path_in) <NEW_LINE> with fiona.open(sf_path_basename + '.sh...
Adds 3 urls to each feature in shape file, if shape file contains a column named 'API'. Writes shape file to destination folder and copies ancillary files from the source to the dest Arguments: sf_name: string, name of the shapefile, folder in src_dir src_dir: directory (folder) that contains sf_name dest_d...
625941b997e22403b379ce13
def dump_odict_yaml(data, stream=None, Dumper=yaml.Dumper, **kwds): <NEW_LINE> <INDENT> class OrderedDumper(Dumper): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def _dict_representer(dumper, data): <NEW_LINE> <INDENT> return dumper.represent_mapping( yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, data.items() ) <NEW_...
* Function: Dump an OrderedDict onto a yaml file * -----------{returns}------------ * Serialised OrderedDict object into yaml . . . * ------------{usage}------------- >>> dump_odict_yaml(data, Dumper=yaml.SafeDumper)
625941b950812a4eaa59c19f
def is_finished(self, quest_key): <NEW_LINE> <INDENT> return quest_key in self.finished_quests
Whether the character finished this quest or not. Args: quest_key: (string) quest's key Returns: None
625941b90a366e3fb873e691
def is_alive(self): <NEW_LINE> <INDENT> return self.last_hello + timedelta(seconds=10) >= datetime.now().replace(microsecond=0)
:return: client is alive
625941b9e5267d203edcdb1b
def ping(self, t: int) -> int: <NEW_LINE> <INDENT> in_range_count = 0 <NEW_LINE> self.requests.append(t) <NEW_LINE> i = 0 <NEW_LINE> for req in reversed(self.requests): <NEW_LINE> <INDENT> if t - 3000 <= req <= t: <NEW_LINE> <INDENT> in_range_count += 1 <NEW_LINE> <DEDENT> elif req > t: <NEW_LINE> <INDENT> break <NEW_L...
It is guaranteed that every call to ping uses a strictly larger value of t than the previous call.
625941b985dfad0860c3acd3
def cmd_exec_stdout(self, command, errormsg='', log=True): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> log and Log.debug(self, "Running command: {0}".format(command)) <NEW_LINE> with subprocess.Popen([command], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) as proc: <NEW_LINE> <INDENT> (cmd_stdout_bytes, ...
Run shell command from Python
625941b9507cdc57c6306b4e
def set_filename(self, kwdict): <NEW_LINE> <INDENT> self.kwdict = kwdict <NEW_LINE> self.temppath = self.prefix = "" <NEW_LINE> ext = kwdict["extension"] <NEW_LINE> kwdict["extension"] = self.extension = self.extension_map(ext, ext) <NEW_LINE> if self.extension: <NEW_LINE> <INDENT> self.build_path() <NEW_LINE> <DEDENT>...
Set general filename data
625941b90fa83653e4656e37
def _clearOldMessages(self): <NEW_LINE> <INDENT> cherrypy.response.headerMap["cache-control"] = "no-cache" <NEW_LINE> global _currentMesages <NEW_LINE> now = time.time() <NEW_LINE> idx = len(_currentMesages) <NEW_LINE> while idx > 0: <NEW_LINE> <INDENT> idx -= 1 <NEW_LINE> msg = _currentMesages[idx] <NEW_LINE> if msg._...
Check for obsolete messages in the _currentMessages
625941b930dc7b76659017e4
@slash_blueprint.route('/upcoming', methods=["POST"]) <NEW_LINE> def slack_upcoming_leaves(): <NEW_LINE> <INDENT> upcoming_leaves = EmployeeLeaveModel.query.filter( and_( EmployeeLeaveModel.slackTeamId == g.team_id, EmployeeLeaveModel.endDate >= date.today() ) ).order_by(EmployeeLeaveModel.startDate).all() <NEW_LINE> i...
Show all the ooo or wfh of all the users for the requested day :return:
625941b9d10714528d5ffb59
def get_email2(self, principal): <NEW_LINE> <INDENT> if isinstance(principal, types.StringTypes) and self.is_inbox(principal): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> elif ICatalogBrain.providedBy(principal) and brain_is_contact(principal): <NEW_LINE> <INDENT> return principal....
Returns the second email address of a `principal`.
625941b992d797404e304003
def display(values): <NEW_LINE> <INDENT> width = 1 + max(len(values[s]) for s in values) <NEW_LINE> line = '+'.join(['-' * (width * 3)] * 3) <NEW_LINE> for r in rows: <NEW_LINE> <INDENT> print(''.join(values[r + c].center(width) + ('|' if c in '36' else '') for c in cols)) <NEW_LINE> if r in 'CF': print(line) <NEW_LINE...
Display the values as a 2-D grid. Args: values(dict): The sudoku in dictionary form
625941b9a17c0f6771cbdece
def assign_texture(self, key, tex_id): <NEW_LINE> <INDENT> self._texture_assignments[key] = tex_id
Assign texture to a key (for example object id). key will usually be a game object
625941b9fbf16365ca6f6037
def ctraj(t0, t1, r): <NEW_LINE> <INDENT> if isinstance(r,(int,int32,float,float64)): <NEW_LINE> <INDENT> i = mat(range(1,r+1)) <NEW_LINE> r = (i-1.)/(r-1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> r = arg2array(r); <NEW_LINE> <DEDENT> if any(r>1) or any(r<0): <NEW_LINE> <INDENT> raise 'path position values (R) mus...
Compute a Cartesian trajectory between poses C{t0} and C{t1}. The number of points is the length of the path distance vector C{r}. Each element of C{r} gives the distance along the path, and the must be in the range [0 1]. If {r} is a scalar it is taken as the number of points, and the points are equally spaced betw...
625941b94a966d76dd550e87
def setSpeeds(self, speeds: list): <NEW_LINE> <INDENT> for module, speed in zip(self.modules, speeds): <NEW_LINE> <INDENT> module.setWheelSpeed(speed)
Sets the speeds of the wheels in inches per second. It takes a list. Please use setUniformModuleSpeed if you want to set the same speed amongst all the modules.
625941b94527f215b584c2d5
def __init__(self): <NEW_LINE> <INDENT> self.__homedir = os.getenv('USERPROFILE') or os.getenv('HOME') <NEW_LINE> self.__projdir = os.path.join(self.__homedir, User.PROJECT_DIR) <NEW_LINE> self.__servers = None <NEW_LINE> self.load()
Constructor
625941b92ae34c7f2600cfac
def _ProcessLogContainer(self, logs_container: containers.GCPLogs) -> None: <NEW_LINE> <INDENT> if not logs_container.path: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> output_file = tempfile.NamedTemporaryFile( mode='w', encoding='utf-8', delete=False, suffix='.jsonl') <NEW_LINE> output_path = output_file.name <NEW_...
Processes a GCP logs container. Args: logs_container (GCPLogs): logs container.
625941b9be383301e01b5307
def iPhone_connection(status): <NEW_LINE> <INDENT> for a in range(0,3): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> sleep(0.1); requests.get('http://192.168.1.176/control/rf433/i_am_home/' + ('on' if status else 'off')) <NEW_LINE> sleep(0.1); requests.get('http://192.168.1.176/control/color/' + ('green' if status else...
True / False
625941b9d10714528d5ffb5a
def renameVar(self, key, newkey, **loginfo): <NEW_LINE> <INDENT> val = self.getVar(key, 0, parsing=True) <NEW_LINE> if val is not None: <NEW_LINE> <INDENT> loginfo['variable'] = newkey <NEW_LINE> loginfo['op'] = 'rename from %s' % key <NEW_LINE> loginfo['detail'] = val <NEW_LINE> self.varhistory.record(**loginfo) <NEW_...
Rename the variable key to newkey
625941b957b8e32f5248331a
def _constraints_satisfied(self, state, step): <NEW_LINE> <INDENT> if not super()._constraints_satisfied(state, step=step): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> i, sz = step <NEW_LINE> px = state[i].price <NEW_LINE> newpos_mv = state[i].shares * px + sz <NEW_LINE> trdtoday = newpos_mv - self._bod_positi...
Test whether step satisfies the various hard/soft/restriction/etc. constraints. For this implementation of this method, we assume the constraints are satisfied for the given state, so we only test the constraints having to do with the state elements corresponding to the step. @param state: State vector. @param step: (...
625941b94e4d5625662d4257
@blueprint.route("/register", methods=['GET', 'POST']) <NEW_LINE> def register(): <NEW_LINE> <INDENT> register_form = RegisterForm() <NEW_LINE> if not register_form.validate(): <NEW_LINE> <INDENT> return jsonify({ "errors": register_form.errors.items(), "success": False, "user": None, "sent_json": request.json }) <NEW_...
Handles the register logic as well as displaying the form :return:
625941b94f88993c3716beee
def poll(self, write_only=False): <NEW_LINE> <INDENT> events = self._poll.poll(int(SelectPoller.TIMEOUT * 1000)) <NEW_LINE> if events: <NEW_LINE> <INDENT> LOGGER.debug("Calling %s with %d events", self._handler, len(events)) <NEW_LINE> for fileno, event in events: <NEW_LINE> <INDENT> self._handler(fileno, event, write_...
Poll until TIMEOUT waiting for an event :param bool write_only: Only process write events
625941b9711fe17d825421ed
def serialize_numpy(self, buff, numpy): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _x = self <NEW_LINE> buff.write(_get_struct_2h().pack(_x.left_hz, _x.right_hz)) <NEW_LINE> <DEDENT> except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', sel...
serialize message with numpy array types into buffer :param buff: buffer, ``StringIO`` :param numpy: numpy python module
625941b97b180e01f3dc4680
def add(self, message): <NEW_LINE> <INDENT> keys = self.keys() <NEW_LINE> if len(keys) == 0: <NEW_LINE> <INDENT> new_key = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> new_key = max(keys) + 1 <NEW_LINE> <DEDENT> new_path = os.path.join(self._path, str(new_key)) <NEW_LINE> f = _create_carefully(new_path) <NEW_LINE> c...
Add message and return assigned key.
625941b9d8ef3951e32433b8
def defineFileGroups(self, mergeableFiles): <NEW_LINE> <INDENT> fileGroups = {} <NEW_LINE> foundFiles = [] <NEW_LINE> for mergeableFile in mergeableFiles: <NEW_LINE> <INDENT> if mergeableFile["file_lfn"] not in foundFiles: <NEW_LINE> <INDENT> foundFiles.append(mergeableFile["file_lfn"]) <NEW_LINE> <DEDENT> else: <NEW_L...
_defineFileGroups_ Group mergeable files by their SE name and run number so that we don't try to merge together files on different SEs. Merging against across run boundaries is configurable.
625941b97d847024c06be13b
def on_experiment_end(self, runner: "IRunner") -> None: <NEW_LINE> <INDENT> if runner.engine.process_index == 0: <NEW_LINE> <INDENT> log_message = "Top models:\n" <NEW_LINE> log_message += "\n".join( [ f"{checkpoint.logpath}\t{checkpoint.metric:3.4f}" for checkpoint in self._storage ] ) <NEW_LINE> print(log_message) <N...
Event handler.
625941b96fece00bbac2d5b6
def test_pickle_dictionary_type_string_true(self): <NEW_LINE> <INDENT> the_type = str <NEW_LINE> data = {0: {"1ID": "A23", "Gender": "Male", "Age": 22, "Sales": 245, "BMI": "normal", "salary": 20, "Birthday": "24/06/1995"}, 1: {"IhD": "A2f3", "Gender": "Male", "Age": 22, "Sales": 245, "BMI": "normal", "salary": 20, "Bi...
True if a value in dictionary are of type 'string'
625941b9ab23a570cc24fffa
def signal_handler(self, _signum, _frame): <NEW_LINE> <INDENT> print("CTRL+C...") <NEW_LINE> self.stop_event.set()
Handles CTR+C
625941b98a43f66fc4b53ee4