code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def test_hackerrank_sample2(self): <NEW_LINE> <INDENT> result = queens_attack_2(5, [4, 3], [[5, 5], [4, 2], [2, 3]]) <NEW_LINE> self.assertEquals(result, 10)
Description
625941e5b545ff76a891422f
def transform(self, dataset, structuring_element_id=0, radius=1, object_label=1, background_label=0): <NEW_LINE> <INDENT> self.progress.value = 0 <NEW_LINE> self.progress.maximum = 100 <NEW_LINE> STEP_PCT = [10, 30, 60, 90, 100] <NEW_LINE> try: <NEW_LINE> <INDENT> import itk <NEW_LINE> from tomviz import itkutils <NEW_...
Perform morphological closing on segmented objects with a given label by a spherically symmetric structuring element with a given radius.
625941e59b70327d1c4e11f1
def serialize_numpy(self, buff, numpy): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _x = self <NEW_LINE> buff.write(_struct_3I.pack(_x.header.seq, _x.header.stamp.secs, _x.header.stamp.nsecs)) <NEW_LINE> _x = self.header.frame_id <NEW_LINE> length = len(_x) <NEW_LINE> if python3 or type(_x) == unicode: <NEW_LINE> <IND...
serialize message with numpy array types into buffer :param buff: buffer, ``StringIO`` :param numpy: numpy python module
625941e59f2886367277aca4
def get_payoff(self): <NEW_LINE> <INDENT> return self.payoff_current
Return payoff of this individual.
625941e5bde94217f3683207
def move_elevators(self, elevators: List[Elevator], waiting: Dict[int, List[Person]], max_floor: int) -> List[Direction]: <NEW_LINE> <INDENT> directions = [] <NEW_LINE> for e in elevators: <NEW_LINE> <INDENT> if e.fullness(): <NEW_LINE> <INDENT> target = e.passengers[0].target <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDE...
Return a list of directions for each elevator to move to.
625941e560cbc95b062c695d
def __init__(self, employee_id: int, project_id: int) -> None: <NEW_LINE> <INDENT> ...
Construct. Args: employee_id: The employee_id of the EmployeeProject. project_id: The project_id of the EmployeeProject.
625941e521bff66bcd684d68
def __init__(self, device: Any, bridge: DynaliteBridge) -> None: <NEW_LINE> <INDENT> self._device = device <NEW_LINE> self._bridge = bridge <NEW_LINE> self._unsub_dispatchers: list[Callable[[], None]] = []
Initialize the base class.
625941e599fddb7c1c9de7a9
def _format_formats(formats): <NEW_LINE> <INDENT> for f in formats: <NEW_LINE> <INDENT> if not re.match('\.?[a-z0-9]+$', f, re.IGNORECASE): <NEW_LINE> <INDENT> raise ValueError( "Extensions in `formats` should be of form 'ext' or '.ext'." + "Got: {}".format(formats) ) <NEW_LINE> <DEDENT> <DEDENT> return ['.{}'.format(e...
Return list in which all items from `formats` have a leading period. If items in `formats` not of form 'ext' or '.ext', ValueError is raised (this is because they are compared against os.path.splitext()).
625941e571ff763f4b549aac
def test_invalid_subr_stmnt(self): <NEW_LINE> <INDENT> scheme_files = [os.path.join(self._sample_files_dir, "invalid_subr_stmnt.meta")] <NEW_LINE> with self.assertRaises(Exception) as context: <NEW_LINE> <INDENT> parse_scheme_files(scheme_files, self._run_env) <NEW_LINE> <DEDENT> self.assertTrue("Invalid dummy argument...
Test that invalid Fortran subroutine statements are correctly detected
625941e58a43f66fc4b5447b
def _open_and_lock(self): <NEW_LINE> <INDENT> locked = False <NEW_LINE> f = os.open(self._fname, os.O_RDWR, 0o600) <NEW_LINE> try: <NEW_LINE> <INDENT> fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB) <NEW_LINE> locked = True <NEW_LINE> return f <NEW_LINE> <DEDENT> except IOError as err: <NEW_LINE> <INDENT> if err.errno ==...
Try to open the file and lock it.
625941e5ad47b63b2c50a399
def get_host_acl_ip(session, host_acl_ip_id): <NEW_LINE> <INDENT> query = session.query( model.HostAclIp ).filter( model.HostAclIp.id == host_acl_ip_id ) <NEW_LINE> return query.first()
Return a specified HostAclIp via its identifier. :arg session: the session with which to connect to the database.
625941e57047854f462a181f
def get_team_ids_relegation(competition_id: str): <NEW_LINE> <INDENT> table = get_league_table(competition_id) <NEW_LINE> rel = list(filter( lambda x: x['leagueTableClass'] == 'bottom1', table)) <NEW_LINE> result = [] <NEW_LINE> for t in rel: <NEW_LINE> <INDENT> result.append(t['dbid']) <NEW_LINE> <DEDENT> return resul...
Returns list of team_ids of teams in relegation zone
625941e54c3428357757c740
def test_setup(self): <NEW_LINE> <INDENT> self.assertTrue(setup_component(self.hass, sensor.DOMAIN, { 'sensor': { 'platform': 'mold_indicator', 'indoor_temp_sensor': 'test.indoortemp', 'outdoor_temp_sensor': 'test.outdoortemp', 'indoor_humidity_sensor': 'test.indoorhumidity', 'calibration_factor': 2.0 } })) <NEW_LINE> ...
Test the mold indicator sensor setup.
625941e50383005118ecf9fb
def get_reply_dict_from_response(response: Response) -> Dict[str, str]: <NEW_LINE> <INDENT> txt = str(response) <NEW_LINE> d = {} <NEW_LINE> http_gap = "\r\n\r\n" <NEW_LINE> camcops_linesplit = "\n" <NEW_LINE> camcops_k_v_sep = ":" <NEW_LINE> try: <NEW_LINE> <INDENT> start_of_content = txt.index(http_gap) + len(http_ga...
For unit testing: convert the text in a :class:`Response` back to a dictionary, so we can check it was correct.
625941e507f4c71912b1189f
def test_raises_error_on_missing_id(self): <NEW_LINE> <INDENT> with self.coll.watch([{'$project': {'_id': 0}}]) as change_stream: <NEW_LINE> <INDENT> self.coll.insert_one({}) <NEW_LINE> with self.assertRaises(InvalidOperation): <NEW_LINE> <INDENT> next(change_stream) <NEW_LINE> <DEDENT> with self.assertRaises(StopItera...
ChangeStream will raise an exception if the server response is missing the resume token.
625941e5091ae35668667371
def test_dont_remove_nonintrons(self): <NEW_LINE> <INDENT> instructions = [] <NEW_LINE> instructions.append(Instruction(mode = 'read-input', target = 0, op = '+', source = 0)) <NEW_LINE> instructions.append(Instruction(mode = 'read-input', target = 0, op = '-', source = 0)) <NEW_LINE> instructions.append(Instruction(mo...
Ensures the algorithm is not removing valid instructions
625941e55510c4643540f7f4
def get_vendor(self, host, credential): <NEW_LINE> <INDENT> all_vendors = [o for o in os.listdir(self.vendors_dir) if os.path.isdir(os.path.join(self.vendors_dir, o)) and re.match(r'^[^\.]', o)] <NEW_LINE> logging.debug("[get_vendor]: %s ", all_vendors) <NEW_LINE> for vname in all_vendors: <NEW_LINE> <INDENT> vpath = o...
Check and get vendor of the switch. :param host: switch ip: :param credential: credential to access switch
625941e523e79379d52ee979
def SetInput2(self, *args): <NEW_LINE> <INDENT> return _itkContourDirectedMeanDistanceImageFilterPython.itkContourDirectedMeanDistanceImageFilterIUL2IUL2_SetInput2(self, *args)
SetInput2(self, itkImageUL2 image)
625941e5ac7a0e7691ed44df
def time_to_kill(unit, tower): <NEW_LINE> <INDENT> result = unit["hit_points"] / (tower["damage_per_shot"] * tower["rate_of_fire"]) <NEW_LINE> return result
returns the time it takes for the tower to kill the unit
625941e5a934411ee3751aaf
def sortColors(self, nums): <NEW_LINE> <INDENT> red_index = 0 <NEW_LINE> white_index = 0 <NEW_LINE> for blue_index in range(len(nums)): <NEW_LINE> <INDENT> color = nums[blue_index] <NEW_LINE> nums[blue_index] = 2 <NEW_LINE> if color < 2: <NEW_LINE> <INDENT> nums[white_index] = 1 <NEW_LINE> white_index += 1 <NEW_LINE> <...
:type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.
625941e50383005118ecf9fc
def __setattr__(self, name, value): <NEW_LINE> <INDENT> if name in self._parameters: <NEW_LINE> <INDENT> par = self._parameters[name] <NEW_LINE> if isinstance(value, Parameter): <NEW_LINE> <INDENT> par.value = value.value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> par.value = value <NEW_LINE> <DEDENT> return <NEW_LI...
Parameter access and object checking.
625941e50c0af96317bb8602
def test_standup_start_invalid_channel(): <NEW_LINE> <INDENT> clear() <NEW_LINE> user_one = auth_register('firstuser@gmail.com', '123abc!@#', 'First', 'User') <NEW_LINE> with pytest.raises(InputError): <NEW_LINE> <INDENT> standup_start(user_one['token'], 0, 10)
check an inputerror is raised if the channel_id is invalid; in this test any channel_id is invalid since no channels exist
625941e524f1403a92600f7d
def set_income(person_data): <NEW_LINE> <INDENT> if not_empty(person_data['income']): <NEW_LINE> <INDENT> return person_data['income']
Set income for person
625941e582261d6c526ab8c0
def resize(img_file, mode=MODE): <NEW_LINE> <INDENT> src_width, src_height = img_file.width, img_file.height <NEW_LINE> mode_map = { "WIDTH": (PHOTO_WIDTH, int(PHOTO_WIDTH/src_width * src_height)), "HEIGHT": (int(PHOTO_HEIGHT/src_height*src_width), PHOTO_HEIGHT), } <NEW_LINE> return img_file.resize(mode_map[mode])
Resize the width or height to make the picture fit our window Since the pictures have been cut as 224*224, resize function is not needed actually (Keep for the not-standard-picture test and reuse)
625941e55fdd1c0f98dc064f
def test_ModuleLoading(self): <NEW_LINE> <INDENT> tm = TestManager() <NEW_LINE> srd = SysrepodDaemonTester("Srd") <NEW_LINE> tester1 = SysrepoTester("First", SR_DS_STARTUP, SR_CONN_DAEMON_REQUIRED, False) <NEW_LINE> tester2 = SysrepoTester("Second", SR_DS_STARTUP, SR_CONN_DAEMON_REQUIRED, False) <NEW_LINE> tester3 = Sy...
Schemas are loaded on demand. Try to send multiple requests targeting the same model simultaneously. All of the should receive correct data.
625941e5be383301e01b5898
def update_image(self): <NEW_LINE> <INDENT> if self.vx > 0 & self.moving_right == False: <NEW_LINE> <INDENT> self.image = self.image_right <NEW_LINE> self.moving_right = True <NEW_LINE> <DEDENT> elif self.vx < 0 & self.moving_right: <NEW_LINE> <INDENT> self.image = self.image_left <NEW_LINE> self.moving_right = False
Update the image based off if mario is moving to the right or to the left
625941e560cbc95b062c695e
def _find_between_community_edges(edges, node_to_community): <NEW_LINE> <INDENT> between_community_edges = dict() <NEW_LINE> for (ni, nj) in edges: <NEW_LINE> <INDENT> ci = node_to_community[ni] <NEW_LINE> cj = node_to_community[nj] <NEW_LINE> if ci != cj: <NEW_LINE> <INDENT> if (ci, cj) in between_community_edges: <NE...
Convert the graph into a weighted network of communities.
625941e5099cdd3c635f1073
def __init__(self, image, typeCase: str, proba: int): <NEW_LINE> <INDENT> self.__proba: float = proba <NEW_LINE> self.__typeCase: str = typeCase <NEW_LINE> self.__image = image
Un case a une image pour s'afficher, un type et une probabilité d'evenement. Parameters ---------- image : pygame.image Image de la case typeCase : str Type de la case proba : int Probabilité d'avoir un évènement qui se lance quand l'équipe se déplace sur ce type de case
625941e5009cb60464c637c9
def adder(tall, med=1): <NEW_LINE> <INDENT> return tall + med
returnerer summen av tallene <tall> og <med>
625941e51b99ca400220aece
def get_csrf_token(response): <NEW_LINE> <INDENT> cookie_headers = [ h.decode('ascii') for h in response.headers.getlist("Set-Cookie") ] <NEW_LINE> if not cookie_headers: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> csrf_headers = [ h for h in cookie_headers if h.startswith("csrftoken=") ] <NEW_LINE> if not csrf...
Extract the CSRF token out of the "Set-Cookie" header of a response.
625941e591af0d3eaac9be37
def LeNet_impl(noise_layer = 0, noise_level = 1): <NEW_LINE> <INDENT> data_in = keras.Input(shape=(28,28,1)) <NEW_LINE> kernel_size=(5,5) <NEW_LINE> noise_level = noise_level / 100 <NEW_LINE> x = Conv2D(6, kernel_size, activation='relu', strides = (1,1), input_shape= (28,28,1), padding='same')(data_in) <NEW_LINE> if no...
LeNet 5 implementation. Noise level is inputted as an integer to make saving the models easier.
625941e53617ad0b5ed68311
def close(self): <NEW_LINE> <INDENT> if (self.port!= None) and self.State==1: <NEW_LINE> <INDENT> self.send_command("atz") <NEW_LINE> self.port.close() <NEW_LINE> <DEDENT> self.port = None <NEW_LINE> self.ELMver = "Unknown" <NEW_LINE> self.record.do_complete() <NEW_LINE> return
Resets device and closes all associated filehandles
625941e5046cf37aa974d15e
def time_weekend_feature(df): <NEW_LINE> <INDENT> import datetime <NEW_LINE> return df.apply(lambda x: True if datetime.datetime(int(x.time_year), int(x.time_month), int(x.time_day)).weekday() > 4 else False, axis=1)
checks if an incident was during the weekend reutrns: a colomn indictating whether it is the weekend (Saturday \ Sunday) or not rtype: [bool]
625941e5c4546d3d9de72e52
def run(self): <NEW_LINE> <INDENT> source = self.scan_task.source <NEW_LINE> credential = self.scan_task.source.credentials.all().first() <NEW_LINE> try: <NEW_LINE> <INDENT> connected = self.connect() <NEW_LINE> self._store_connect_data(connected, credential) <NEW_LINE> <DEDENT> except vim.fault.InvalidLogin as vm_erro...
Scan network range ang attempt connections.
625941e5dd821e528d63b5c0
def selectItem(a): <NEW_LINE> <INDENT> global cur_mas <NEW_LINE> global cur_dat <NEW_LINE> cur_mas = [] <NEW_LINE> cur_dat = [0] * 10 <NEW_LINE> curItem = tree.focus() <NEW_LINE> cur_mas = tree.item(curItem)['values'][1:11] <NEW_LINE> for cd in range(1, 11): <NEW_LINE> <INDENT> cur_dat[cd - 1] = (tree.heading(cd).get('...
Функция передает в массивы выбранную строчку, а также заголовки этих строк, в которых содержится дата отчетности
625941e5f9cc0f698b140a12
def _place(obs_settings, cradle_prop_name): <NEW_LINE> <INDENT> arena = arenas.Standard() <NEW_LINE> arm = robots.make_arm(obs_settings=obs_settings) <NEW_LINE> hand = robots.make_hand(obs_settings=obs_settings) <NEW_LINE> prop = props.Duplo( observable_options=observations.make_options( obs_settings, observations.FREE...
Configure and instantiate a Place task. Args: obs_settings: `observations.ObservationSettings` instance. cradle_prop_name: The name of the prop onto which the Duplo brick must be placed. Must be either 'duplo' or 'cradle'. Returns: An instance of `Place`. Raises: ValueError: If `prop_name` is neither 'du...
625941e5596a897236089ed6
def test_cx_gate_nondeterministic_minimal_basis_gates(self): <NEW_LINE> <INDENT> circuits = ref_2q_clifford.cx_gate_circuits_nondeterministic(final_measure=False) <NEW_LINE> targets = ref_2q_clifford.cx_gate_statevector_nondeterministic() <NEW_LINE> job = execute(circuits, StatevectorSimulator(), shots=1, basis_gates='...
Test cx-gate gate circuits compiling to U,CX
625941e530c21e258bdfa8bc
def __init__(self, level): <NEW_LINE> <INDENT> self.level = level
Construct the Translate_X class.
625941e566656f66f7cbc5c7
def set_figsize(figsize=(3.5, 2.5)): <NEW_LINE> <INDENT> use_svg_display() <NEW_LINE> d2l.plt.rcParams['figure.figsize'] = figsize
Set the figure size for matplotlib.
625941e50a50d4780f6672b0
def test_command_line_interface(): <NEW_LINE> <INDENT> runner = CliRunner() <NEW_LINE> result = runner.invoke(cli.main) <NEW_LINE> assert result.exit_code == 0 <NEW_LINE> help_result = runner.invoke(cli.main, ['--help']) <NEW_LINE> assert help_result.exit_code == 0 <NEW_LINE> assert 'Show this message and exit.' in hel...
Test the CLI.
625941e5e5267d203edce0b2
def centers_in_tof(self, centers_in_dspacing: Union[str, TableWorkspace], difc: Union[str, TableWorkspace], output_workspace: str): <NEW_LINE> <INDENT> dspacing_table, difc_table = mtd[str(centers_in_dspacing)], mtd[str(difc)] <NEW_LINE> assert dspacing_table.rowCount() == difc_table.rowCount() <NEW_LINE> table = Creat...
Convert the peak centers in dSpacing units (Angstroms) to TOF units (microseconds) @param centers_in_dspacing : "_dspacing" diagnostics table workspace, output from PDCalibration @param difc: "_difc" table workspace, output from PDCalibration @param output_workspace: name of the output table, equal to `centers_in_dspa...
625941e58e05c05ec3eea792
def get_geographical_set(): <NEW_LINE> <INDENT> file_path = get_package_path() + "/twitter/res/topics/geographical_set.txt" <NEW_LINE> topics = get_topic_set(file_path) <NEW_LINE> return topics
Returns a set of all the geographical attributes (e.g. uk, sweden) found in the SNOW dataset.
625941e57d847024c06be6da
def print_lst(self): <NEW_LINE> <INDENT> list1 = [] <NEW_LINE> for item in self.heap_array: <NEW_LINE> <INDENT> print(item, end='' + " ")
Prints the heap
625941e53cc13d1c6d3c7793
def initialize(self): <NEW_LINE> <INDENT> self._url = self._cfg.getURL() <NEW_LINE> if not self._url: <NEW_LINE> <INDENT> return S_ERROR("Could not build service URL for %s" % GatewayService.GATEWAY_NAME) <NEW_LINE> <DEDENT> gLogger.verbose("Service URL is %s" % self._url) <NEW_LINE> result = self._loadHandlerInit() <N...
This replaces the standard initialize from Service
625941e54e4d5625662d47ed
def reverseWords(s): <NEW_LINE> <INDENT> result = '' <NEW_LINE> t = [] <NEW_LINE> i = 0 <NEW_LINE> while i <= len(s): <NEW_LINE> <INDENT> if i < len(s) and s[i] is not ' ': <NEW_LINE> <INDENT> t.append(s[i]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> while t: <NEW_LINE> <INDENT> result += t.pop() <NEW_LINE> <DEDENT>...
:type s: str :rtype: str
625941e5dc8b845886cb5951
def _load_queue(self, filename): <NEW_LINE> <INDENT> return self.queue_class(filename)
Loads the queue from ``filename``.
625941e515baa723493c4393
def __init__(self, conf, title, headline, template, **kwargs): <NEW_LINE> <INDENT> super(StatsBase, self).__init__(**kwargs) <NEW_LINE> self._conf = conf <NEW_LINE> self.title = title <NEW_LINE> self.headline = headline <NEW_LINE> self.template = template
Base class for statistics Represents a stats "box" with a title, headline and some content derived from a conference. Each instance also holds the reference to the template used for rendering. It should be a template extending `events/registration/_stats_box.html`. :param conf: Conference -- the conference object :p...
625941e5187af65679ca553b
def __setitem__(self, key, value): <NEW_LINE> <INDENT> super(Serialize, self).__setitem__(key, value)
键值赋值
625941e531939e2706e4d27f
def print_info(func): <NEW_LINE> <INDENT> if not PRINT_INFO: <NEW_LINE> <INDENT> return func <NEW_LINE> <DEDENT> def inner(self, *args, **kwargs): <NEW_LINE> <INDENT> result = func(self, *args, **kwargs) <NEW_LINE> print('\n\n{0}'.format(func.__name__)) <NEW_LINE> print('============================') <NEW_LINE> if fun...
Prints some useful info.
625941e5442bda511e8be82d
def test_request9s_du_piz_ciu(self): <NEW_LINE> <INDENT> pass
Test case for request9s_du_piz_ciu Create an Endpoint # noqa: E501
625941e5287bf620b61d3e7c
def hash(self, key): <NEW_LINE> <INDENT> return (hash(key) and 0x7fffffff) % self.M
hash a key using a variation of python hashing function. mod M since there are only M slots in the hash set time: avg: O(1) worst case: O(k) | space: O(1) where k = len of key
625941e5435de62698dfe068
def setUp(self): <NEW_LINE> <INDENT> self.aclient = ArrayManagementClient() <NEW_LINE> self.example_url = '/UNIVERSE_SQL/dowjones_universe.yaml' <NEW_LINE> self.example_keywords = ("date_", "iticker") <NEW_LINE> self.array = self.aclient.aclient[self.example_url] <NEW_LINE> self.keyword_handler = KeywordHandler(self.ar...
There are four items needed for testing the KeywordHandler: 1. An array client backend instance. 2. Test yaml url that the client can connect to. This will be forced to reside relative to the client's basedir attribute. 3. When the client is constructed from the url, you need to have exposed some cond...
625941e510dbd63aa1bd2fbd
def uc_get_user(self,username,isuid=0): <NEW_LINE> <INDENT> frame = inspect.currentframe() <NEW_LINE> args, _, _, values = inspect.getargvalues(frame) <NEW_LINE> param = {k:values[k] for k in args if k!='self'} <NEW_LINE> result=self.post('user','get_user', **param) <NEW_LINE> if result=='0': <NEW_LINE> <INDENT> return...
:param username: :param isuid: :return: { 'email': '', 'uid': '', 'username': '' } 如果用户不存在返回None
625941e5851cf427c661a927
def test_custom_action_response_descriptor_octopus_server_web_api_actions_users_user_create_action(self): <NEW_LINE> <INDENT> pass
Test case for custom_action_response_descriptor_octopus_server_web_api_actions_users_user_create_action
625941e556ac1b37e62645e3
def reset_category_colors(self): <NEW_LINE> <INDENT> self.te_category_colors.setPlainText("\n".join(CATEGORY_COLORS_LIST)) <NEW_LINE> logging.debug("reset category colors to default")
reset category colors to default
625941e5a8370b7717052cb8
@pytest.mark.parametrize( 'test_input,encoding', [ (u'くらとみ', 'latin1'), (u'café', 'shift_jis'), ] ) <NEW_LINE> @pytest.mark.parametrize('errors', ['surrogate_or_strict', 'strict']) <NEW_LINE> def test_container_to_bytes_incomp_chars_and_encod(test_input, encoding, errors): <NEW_LINE> <INDENT> with pytest.raises(Unicode...
Test for passing incompatible characters and encodings container_to_bytes().
625941e57d43ff24873a30be
def test_parse_dns_correct1(self): <NEW_LINE> <INDENT> dns = main.ServerDns() <NEW_LINE> line = 'DNS : unicorn' <NEW_LINE> main.parse_dns(dns, line) <NEW_LINE> self.assertEqual(dns.domain_name, 'unicorn')
Test parse_dns() function with one dns
625941e5a17c0f6771cbe46b
def _add_items(self, source_field_name, target_field_name, *objs): <NEW_LINE> <INDENT> from django.db.models import Model <NEW_LINE> if objs: <NEW_LINE> <INDENT> new_ids = set() <NEW_LINE> for obj in objs: <NEW_LINE> <INDENT> if isinstance(obj, self.model): <NEW_LINE> <INDENT> if not router.allow_relation(obj, self.ins...
By default, auto_created through objects from form instances are saved using Manager.bulk_create(). Manager.bulk_create() is passed a list containing instances of the through model with the target and source foreign keys defined. In order to set the position field we need to tweak this logic (the modified lines are ma...
625941e5e8904600ed9f234e
def test_was_published_recently_with_future_quote(self): <NEW_LINE> <INDENT> time = timezone.now() + datetime.timedelta(days=30) <NEW_LINE> future_quote = Quote(pub_date=time) <NEW_LINE> self.assertIs(future_quote.was_published_recently(), False)
was_published_recently() returns False for quotes whose pub_date is in the future.
625941e521a7993f00bc8112
def point_in_poly(poly): <NEW_LINE> <INDENT> def fun(point): <NEW_LINE> <INDENT> return point_inside_polygon(point.x, point.y, poly) <NEW_LINE> <DEDENT> return fun
Return a function that determines for a geodin Point object if it's in the given polygon.
625941e5925a0f43d254a296
def run(self): <NEW_LINE> <INDENT> while self.workers: <NEW_LINE> <INDENT> p = self.queue.get() <NEW_LINE> if p is None: <NEW_LINE> <INDENT> self.workers -= 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.output.append(p) <NEW_LINE> <DEDENT> <DEDENT> print(len("".join(c for (i, c) in (sorted if self.sorting else i...
Extract items from the output queue and print until all done.
625941e5aad79263cf390e62
def implies( self, other: Optional[Comparable], context: Optional[ContextRegister] = None ) -> bool: <NEW_LINE> <INDENT> if other is None: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return any( register is not None for register in self.explanations_implication(other, context=context) )
Test whether ``self`` implies ``other``. When inherited by :class:`~nettlesome.groups.FactorGroup`\, this method will check whether every :class:`~nettlesome.statements.Statement` in ``other`` is implied by some Statement in ``self``. >>> from nettlesome import Entity, Comparison, Statement, FactorGroup >>> o...
625941e5c432627299f05064
def _send(self, email_message): <NEW_LINE> <INDENT> if not email_message.recipients(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> encoding = email_message.encoding or settings.DEFAULT_CHARSET <NEW_LINE> email_message.from_email = fix_address(email_message.from_email) <NEW_LINE> if self.return_path: <NEW_LINE>...
A helper method that does the actual sending.
625941e5956e5f7376d71287
def main(argv): <NEW_LINE> <INDENT> del argv <NEW_LINE> dataset = load_data(distorted=True, data_path=DATA_PATH, dataset='cifar100') <NEW_LINE> (x_train_distorted, _), (x_test_distorted, _) = dataset <NEW_LINE> dataset = load_data(distorted=False, data_path=DATA_PATH, dataset='cifar100') <NEW_LINE> (x_train, _), (x_tes...
Main function.
625941e526068e7796caf100
def prepare_terms(self, stopwords_file=None, quiet=False): <NEW_LINE> <INDENT> self.prepare_term_candidates(stopwords_file=stopwords_file, quiet=quiet) <NEW_LINE> self.lemmatize_sentences()
Init term candidates and sentences for getting profiles
625941e59b70327d1c4e11f2
def get_qa_size(data, lower_err, lower, upper, upper_err): <NEW_LINE> <INDENT> sizes = [] <NEW_LINE> for i in range(len(data)): <NEW_LINE> <INDENT> if lower == None or upper == None: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if data[i] <= lower_err: <NEW_LINE> <INDENT> sizes.append('9') <NEW_LINE> <DEDENT> if da...
takes in camera QA data and the acceptable threshold for that metric Args: data: array of QA data lower_err: array of lower thresholds that trigger errors lower: array of lower thresholds that trigger warnings upper: array of upper thresholds that trigger warnings upper_err: array of upper threshol...
625941e524f1403a92600f7e
def view_my_account(self): <NEW_LINE> <INDENT> from pages.accounts.profile import Profile <NEW_LINE> return self._select(locator=self._my_account_locator, destination=Profile, external=True)
View the user's profile on Accounts.
625941e5f7d966606f6aa425
def parse_http_date(date): <NEW_LINE> <INDENT> for regex in RFC1123_DATE, RFC850_DATE, ASCTIME_DATE: <NEW_LINE> <INDENT> m = regex.match(date) <NEW_LINE> if m is not None: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("%r is not in a valid HTTP date format" % date) <N...
Parse a date format as specified by HTTP RFC7231 section 7.1.1.1. The three formats allowed by the RFC are accepted, even if only the first one is still in widespread use. Return an integer expressed in seconds since the epoch, in UTC.
625941e5de87d2750b8601b2
def test_decode_null_content(immutable_list_schema, decode_mapping): <NEW_LINE> <INDENT> composite = Composite(immutable_list_schema) <NEW_LINE> content: List = [ { "inner_folder": { "nombre": None } } ] <NEW_LINE> expected: List[Dict] = [{"name": None}] <NEW_LINE> actual: List = list(composite.decode_list(decode_mappi...
Content that is explicitly null is decoded.
625941e530dc7b7665901d7d
def scan_hash(self, target: str, __send: bool = False) -> dict: <NEW_LINE> <INDENT> self.MetaLog.debug('Starting file scan.') <NEW_LINE> if os.path.exists(target) is False: <NEW_LINE> <INDENT> self.MetaLog.critical('{} not found or might not be accessed.'.format(target)) <NEW_LINE> raise FileNotFoundError('File not fou...
Perform SHA-256 calculation, send file hash to Metadefender and receive response in JSON. Method must receive path to file ('target'). If '__send' is True, in case of error HTTP code received, 'scan_file' with same target will be called. Return 2 dictionaries: 1st. Scan results. Looks like {'Antivirus': 'File_infe...
625941e597e22403b379d3b7
def equals(self, d2): <NEW_LINE> <INDENT> return self.year == d2.year and self.month == d2.month and self.day == d2.day
Decides if self and d2 represent the same calendar date, whether or not they are in the same place in memory
625941e5507cdc57c6307100
def timer(): <NEW_LINE> <INDENT> self.health_pointer = self.process.get_pointer(0x004e4dbc, offsets=[0xf4]) <NEW_LINE> self.ammo_pointer = self.process.get_pointer(0x004df73c, offsets=[0x378, 0x14, 0x0]) <NEW_LINE> self.grenade_pointer = self.process.get_pointer(0x004df73c, offsets=[0x35c, 0x14, 0x0]) <NEW_LINE> self.p...
This is the TIMER function that runs every 100 milliseconds and update the health, ammo and grenade.
625941e58da39b475bd65394
def test_accept_valid_aes_rejection(self): <NEW_LINE> <INDENT> self.cert.aes = 'X12345678901234' <NEW_LINE> self.cert.clean_fields()
Accept valid AES identifiers regex: r'X-d{14}'
625941e58e71fb1e9831dbc3
def __init__(self,main_ins,host_obj,expression_obj,specified_item =None): <NEW_LINE> <INDENT> self.host_obj =host_obj <NEW_LINE> self.expression_obj=expression_obj <NEW_LINE> self.main_ins=main_ins <NEW_LINE> self.service_redis_key = "Status_%s_%s_latest" %(host_obj.id,expression_obj.service.name) <NEW_LINE> self.time_...
:param main_ins DataHandler 实例: :param host_obj: :param expression_obj: :param specified_item: 计算单条表达式的结果
625941e55510c4643540f7f5
def logout(request, *args): <NEW_LINE> <INDENT> return Index(request).logout()
logout from the _install section
625941e52c8b7c6e89b35bd9
def find_string_in_dict_or_list(i): <NEW_LINE> <INDENT> d=i.get('dict',{}) <NEW_LINE> found='no' <NEW_LINE> wc=False <NEW_LINE> ss=i.get('search_string','') <NEW_LINE> if ss.find('*')>=0 or ss.find('?')>=0: <NEW_LINE> <INDENT> wc=True <NEW_LINE> import fnmatch <NEW_LINE> <DEDENT> bic=False <NEW_LINE> ic=i.get('ignore_c...
Input: { dict - dictionary 1 (search_string) - search string (ignore_case) - ignore case of letters } Output: { return - return code = 0, if successful > 0, if error (error) - error text if return ...
625941e55fcc89381b1e1add
def add(s): <NEW_LINE> <INDENT> numbers = [int(x) for x in re.findall('(-?\d+)', s)] <NEW_LINE> negatives = [x for x in numbers if x < 0] <NEW_LINE> if negatives: <NEW_LINE> <INDENT> raise Exception("negative numbers not allowed: %s" % negatives) <NEW_LINE> <DEDENT> return sum(numbers)
add numbers
625941e5287bf620b61d3e7d
def id(self, user): <NEW_LINE> <INDENT> return user.key.urlsafe()
return identity of this user
625941e529b78933be1e5ac3
def damage(spell): <NEW_LINE> <INDENT> spells_list = [('dai', 5), ('aine', 4), ('ain', 3), ('jee', 3), ('je', 2), ('ne', 2), ('ai', 2), ('fe', 1)] <NEW_LINE> damage = 0 <NEW_LINE> if (is_correct(spell)): <NEW_LINE> <INDENT> start_index = spell.find('fe') <NEW_LINE> end_index = spell.rfind('ai') + 2 <NEW_LINE> new_spell...
Function calculating damage :param str spell: string with spell :rtype: int :return: points of damage
625941e5442bda511e8be82e
def send_robust(self, sender, **named): <NEW_LINE> <INDENT> if not self.receivers or self.sender_receivers_cache.get(sender) is NO_RECEIVERS: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> responses = [] <NEW_LINE> for receiver in self._live_receivers(sender): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> response = ...
Send signal from sender to all connected receivers catching errors. Arguments: sender The sender of the signal. Can be any Python object (normally one registered with a connect if you actually want something to occur). named Named arguments which will be passed to receivers. T...
625941e515fb5d323cde0f31
def run(ceph_cluster, **kw): <NEW_LINE> <INDENT> config = kw.get("config") <NEW_LINE> command = config.pop("command") <NEW_LINE> log.info("Executing service %s service" % command) <NEW_LINE> orch = Orch(cluster=ceph_cluster, **config) <NEW_LINE> try: <NEW_LINE> <INDENT> method = fetch_method(orch, command) <NEW_LINE> m...
Executing the service operation using cephadm ceph orch remove|restart|start|stop|reconfigure|redeploy <service name>. Args: ceph_cluster kw: command and service are passed from the test case. Example: Testing ceph orch restart mon config: command: restart service: mon Returns: output...
625941e5cad5886f8bd273f5
def free_device(ptr): <NEW_LINE> <INDENT> cptr = c_void_ptr_t(ptr) <NEW_LINE> safe_call(backend.get().af_free_device(cptr))
Free the device memory allocated by alloc_device
625941e5bde94217f3683209
def get_exec_msg(self, key, callback): <NEW_LINE> <INDENT> http_client = tornado.httpclient.AsyncHTTPClient() <NEW_LINE> exec_callback = partial(self.return_exec_msg_code, callback) <NEW_LINE> http_client.fetch(self.url+"?q=%s"%key, exec_callback, method="GET", headers={"Accept": "application/json"})
See :meth:`db.DB.get_exec_msg`
625941e523e79379d52ee97a
@cli_base.command("down") <NEW_LINE> @click.argument("name") <NEW_LINE> def put_a_hit_out(name): <NEW_LINE> <INDENT> feed = resolve_name(name).decode() <NEW_LINE> d = feedparser.parse(feed) <NEW_LINE> print(d['feed']['title']) <NEW_LINE> if d.entries[0].enclosures: <NEW_LINE> <INDENT> with Database("settings") as s: <N...
Download a feed's most recent enclosure that we don't have
625941e5c432627299f05065
def output_net_routes(net, def_info, lef_info): <NEW_LINE> <INDENT> s = "" <NEW_LINE> num_route = 0 <NEW_LINE> first_route_done = False <NEW_LINE> for i in range(len(net.routed)): <NEW_LINE> <INDENT> if net.routed[i].get_layer() in GOOD_LAYERS: <NEW_LINE> <INDENT> num_route += 1 <NEW_LINE> if first_route_done: <NEW_LIN...
Return None if there are no routes in the :param net: a Net object :param def_info: a DefParser object that contains DEF info. :param lef_info: a LefParser object :return: routes if good route exists, None if no route available.
625941e566673b3332b924ad
def deduction_exists(self, to_deduce, deduce_from): <NEW_LINE> <INDENT> rules_applied = set() <NEW_LINE> deduced = deduce_from.copy() <NEW_LINE> new_rule_used = True <NEW_LINE> while new_rule_used: <NEW_LINE> <INDENT> new_rule_used = False <NEW_LINE> for rule in self.rules: <NEW_LINE> <INDENT> if rule not in rules_appl...
:param to_deduce: a Sentence :param deduce_from: set of Sentences :return: True, if to_deduce can be deduced from deduce_from
625941e58e71fb1e9831dbc4
def wall_collide( b, w ): <NEW_LINE> <INDENT> k = 0.8 <NEW_LINE> global velocity <NEW_LINE> perpen = rotate(w.axis, radians(90), vector(0,0,1)) <NEW_LINE> corner = [w.pos + norm(w.axis) * w.length/2.0 + norm(perpen) * w.height/2.0, w.pos - norm(w.axis) * w.length/2.0 + norm(perpen) * w.height/2.0, w.pos + norm(w.axis) ...
w is a wall (a box with a length and width) b is a ball (an object with a pos) returns True if b collides with w (in length or width) returns False otherwise
625941e591f36d47f21ac913
def get_device(self): <NEW_LINE> <INDENT> dev_path = None <NEW_LINE> om_iface_obj = dbus.Interface(self.bus.get_object(BLUEZ_SERVICE_NAME, "/"), DBUS_OM_IFACE) <NEW_LINE> self.ble_objs = om_iface_obj.GetManagedObjects() <NEW_LINE> for path, interfaces in self.ble_objs.items(): <NEW_LINE> <INDENT> if DEVICE_IFACE not in...
Discover device based on device name and device address and connect
625941e53317a56b8693a06a
def _visitFunc(self, args, dirname, names): <NEW_LINE> <INDENT> for fileName in names: <NEW_LINE> <INDENT> if fileName.endswith('py'): <NEW_LINE> <INDENT> fp = os.path.join(dirname, fileName) <NEW_LINE> if not os.path.isdir(fp): <NEW_LINE> <INDENT> self.modulePaths.append(fp)
append all module paths from _walk() to self.modulePaths. Utility function was called from os.path.walk() now called from os.walk
625941e5e64d504609d74c5c
def add_n_eager_fallback(inputs, name=None): <NEW_LINE> <INDENT> _ctx = _context.context() <NEW_LINE> if not isinstance(inputs, (list, tuple)): <NEW_LINE> <INDENT> raise TypeError( "Expected list for 'inputs' argument to " "'add_n' Op, not %r." % inputs) <NEW_LINE> <DEDENT> _attr_N = len(inputs) <NEW_LINE> _attr_T, inp...
This is the slowpath function for Eager mode. This is for function add_n
625941e55fc7496912cc3d9a
def _create_context_builder(self): <NEW_LINE> <INDENT> ctx = self._engine.context <NEW_LINE> ctx_name = str(ctx) <NEW_LINE> MaxScript.create_menu(ctx_name, self._ctx_var) <NEW_LINE> MaxScript.add_action_to_menu(self._jump_to_sg, 'Jump to Shotgun', self._ctx_var, self._engine) <NEW_LINE> if ctx.filesystem_locations: <NE...
Adds a context menu wich displays the current context :returns: Menu builder
625941e5956e5f7376d71288
def setSSH(self, enable): <NEW_LINE> <INDENT> if enable: <NEW_LINE> <INDENT> enablestr = "true" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> enablestr = "false" <NEW_LINE> <DEDENT> return self.set("ISAPI/System/Network/ssh.enabled",enablestr)
not tested
625941e52eb69b55b151ccd1
def DecNumber(name): <NEW_LINE> <INDENT> return TextualIntAdapter(GreedyRange(Digit(name)))
decimal number
625941e507f4c71912b118a1
def get_institute_details(self, institute): <NEW_LINE> <INDENT> logger.debug("Backend doesn't support getting institute details.") <NEW_LINE> return {}
Get institute's details.
625941e5091ae35668667373
def iceberg(): <NEW_LINE> <INDENT> model = models.Sequential() <NEW_LINE> model.add(layers.Conv2D(64, (3, 3), input_shape=(75, 75, 3))) <NEW_LINE> model.add(layers.Activation('relu')) <NEW_LINE> model.add(layers.BatchNormalization()) <NEW_LINE> model.add(layers.Conv2D(64, (3, 3))) <NEW_LINE> model.add(layers.Activation...
Model is defined here: Currently a 4-layer convnet. :return: model
625941e50fa83653e46573d4
def point_in_rect(point, rect): <NEW_LINE> <INDENT> return rect[0] <= point[0] <= rect[0] + rect[2] and rect[1] <= point[1] <= rect[1] + rect[3]
:param point: an (x, y) tuple and :param rect: rect is a (x, y, w, h) tuple where (x, y) is the top left coordinate :return: if point is inside rect (boundary included)
625941e555399d3f05588ad3
def goToPath(handle, sdPath): <NEW_LINE> <INDENT> sdPath = sanitizePath(sdPath) <NEW_LINE> sdPathLen = len(sdPath) <NEW_LINE> sdPathBytes = bytearray(sdPath, 'ascii') <NEW_LINE> ljm.eWriteName(handle, "FILE_IO_PATH_WRITE_LEN_BYTES", sdPathLen) <NEW_LINE> ljm.eWriteNameByteArray(handle, "FILE_IO_PATH_WRITE", sdPathLen, ...
Changes the SD card system's current working directory to the given path.
625941e5293b9510aa2c36ae
def list_languages(): <NEW_LINE> <INDENT> found = set(['en']) <NEW_LINE> languages = [('en', Locale('en'))] <NEW_LINE> sections = set(_settings['sections']) <NEW_LINE> for locale in os.listdir(_settings['path']): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> l = Locale.parse(locale) <NEW_LINE> <DEDENT> except (ValueErro...
Return a list of all languages we have translations for. The locales are ordered by display name. Languages without sections are not returned.
625941e576d4e153a657ef4f
def get_hashes(filepath, hash_alg): <NEW_LINE> <INDENT> hashes = {'sha256': '', 'md5': ''} <NEW_LINE> if "none" not in hash_alg: <NEW_LINE> <INDENT> size = stats2(filepath)['size'] <NEW_LINE> if size == "ERROR": <NEW_LINE> <INDENT> return hashes <NEW_LINE> <DEDENT> if 'sha256' in hash_alg: <NEW_LINE> <INDENT> try: <NEW...
Returns the hashes specified in the list hash_alg for the file at filepath.
625941e521bff66bcd684d6b
def pretty_date(datetime_field): <NEW_LINE> <INDENT> now = timezone.now() <NEW_LINE> diff = now - datetime_field <NEW_LINE> second_diff = diff.seconds <NEW_LINE> day_diff = diff.days <NEW_LINE> if day_diff < 0: <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> if day_diff == 0: <NEW_LINE> <INDENT> if second_diff < 10: ...
Get a datetime object or a int() Epoch timestamp and return a pretty string like 'an hour ago', 'Yesterday', '3 months ago', 'just now', etc
625941e54e4d5625662d47ee