code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def __init__(self, estado_inicial, estado_final=None): <NEW_LINE> <INDENT> self.estado_inicial = estado_inicial <NEW_LINE> self.estado_final = estado_final
El constructor de la clase especifica el estado inicial y puede que un estado_final, si es que es único. Las subclases podrían añadir otros argumentos
625941e34a966d76dd5513eb
def test_package_info_correctness(self): <NEW_LINE> <INDENT> descr_pkgs = self.softinfo.get_pkg_info(*[name[0] for name in self.test_pkgs]) <NEW_LINE> for name, version, release, vendor in self.test_pkgs: <NEW_LINE> <INDENT> self.assertTrue(name in descr_pkgs) <NEW_LINE> self.assertEqual(version, descr_pkgs.get(name).g...
Get ten random packages from the current system, get their info and verify. :return:
625941e3d164cc6175783127
def _do_init(self, line): <NEW_LINE> <INDENT> if 'build dependencies' in line: <NEW_LINE> <INDENT> self._set_icon(1, Gtk.Spinner()) <NEW_LINE> self._state = 'builddeps' <NEW_LINE> dialog = self.builder.get_object("main_dlg") <NEW_LINE> try: <NEW_LINE> <INDENT> self._package = line.split(':')[0] <NEW_LINE> dialog.set_ti...
Setup default GUI.
625941e350812a4eaa59c6f6
@app.route('/add_review_committee') <NEW_LINE> def add_review_committee(): <NEW_LINE> <INDENT> statuses = query_db("""SELECT statustype from status_list""") <NEW_LINE> return render_template('add_review_committee.html', statuses=statuses, reviews=reviews)
Add review committee information
625941e3d164cc6175783128
def All_online_list_append(name): <NEW_LINE> <INDENT> for username in client_online: <NEW_LINE> <INDENT> recv_conn, recv_addr = client_online[username] <NEW_LINE> send_messages(recv_conn, f"!CONNECT {name}") <NEW_LINE> <DEDENT> time.sleep(1)
s => Thêm name vào online_list của những người dùng khác param name: tên người dùng được thêm vào return: None
625941e376e4537e8c351a4e
def initialize_DB(db): <NEW_LINE> <INDENT> db.execute( """CREATE TABLE IF NOT EXISTS events (event_type TEXT, event_timestamp INTEGER, gps_coord TEXT);""")
Creating event table if it doesn't already exist. The event table has two keys: 1-A key generated on the edge gateway when an event detected. 2-The sqlite3 rowid: http://www.sqlitetutorial.net/sqlite-autoincrement/
625941e34c3428357757c6fe
def __createNetwork__(self, amount_nodes, amount_links): <NEW_LINE> <INDENT> raise NotImplementedError
Method overwritten by subclasses, nothing to do here
625941e30c0af96317bb85c0
def load_sample_images(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> from scipy.misc import imread <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> from scipy.misc.pilutil import imread <NEW_LINE> <DEDENT> <DEDENT> except ImportError: <NEW_LINE> <INDENT> raise ImportError("The Pyth...
Load sample images for image manipulation. Loads both, ``china`` and ``flower``. Returns ------- data : Bunch Dictionary-like object with the following attributes : 'images', the two sample images, 'filenames', the file names for the images, and 'DESCR' the full description of the dataset. Examples --...
625941e3711fe17d8254273b
def get_dependencies(): <NEW_LINE> <INDENT> deps = { 'shade': HAS_SHADE, 'os_client_config': HAS_SHADE, } <NEW_LINE> return config.check_driver_dependencies( __virtualname__, deps )
Warn if dependencies aren't met.
625941e3925a0f43d254a253
def __repr__(self): <NEW_LINE> <INDENT> s = '' <NEW_LINE> for row in range(self.height): <NEW_LINE> <INDENT> s += '|' <NEW_LINE> for col in range(self.width): <NEW_LINE> <INDENT> s += self.slots[row][col] + '|' <NEW_LINE> <DEDENT> s += '\n' <NEW_LINE> <DEDENT> a = self.width + (self.width + 1) <NEW_LINE> s += "-" * a <...
Returns a string representation for a Board object.
625941e382261d6c526ab87e
def chdir(self, path): <NEW_LINE> <INDENT> if self._cwd is None: <NEW_LINE> <INDENT> self._cwd = os.getcwd() <NEW_LINE> <DEDENT> if hasattr(path, "chdir"): <NEW_LINE> <INDENT> path.chdir() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> os.chdir(path)
change the current working directory to the specified path path can be a string or a py.path.local object
625941e3596a897236089e94
def _check_url(self, url): <NEW_LINE> <INDENT> allow_localhost = getattr(settings, "SIMPL_WEBHOOK_ALLOW_LOCALHOST", False) <NEW_LINE> if not allow_localhost and 'localhost' in url: <NEW_LINE> <INDENT> raise ValueError("Simpl is not configured to allow localhost URLs") <NEW_LINE> <DEDENT> allow_http = getattr(settings, ...
Determine if our URL is ok
625941e35166f23b2e1a5532
def validate_supported_runtime(): <NEW_LINE> <INDENT> if not __is_supported_version(): <NEW_LINE> <INDENT> raise RuntimeError('Python 3.5 or newer is required.')
Raises a RuntimeError exception when the runtime is not supported.
625941e37b25080760e39830
def setup_app(loop=asyncio.get_event_loop(), config=load_config()[0]): <NEW_LINE> <INDENT> if config.get("sentry_dsn", None): <NEW_LINE> <INDENT> sentry_sdk.init( dsn=config["sentry_dsn"], integrations=[AioHttpIntegration()], release=f"cherrydoor@{__version__}", ) <NEW_LINE> <DEDENT> app = web.Application(loop=loop) <N...
Create the app and initiate all services (database, security, etc). Parameters ---------- loop : asyncio.EventLoop The event loop to use. config : AttrDict a dictionary with configuration values Returns ------- app : web.Application The application instance.
625941e33617ad0b5ed682cf
def __init__( self, stats_fn: PartitionedStatsFn, num_partitions: int, min_partitions_stat_presence: int, seed: int, max_examples_per_partition: int, batch_size: int = 1000, name: Text = 'NonStreamingCustomStatsGenerator') -> None: <NEW_LINE> <INDENT> super(NonStreamingCustomStatsGenerator, self).__init__( name=name, p...
Initializes NonStreamingCustomStatsGenerator. Args: stats_fn: The PartitionedStatsFn that will be run on each sample. num_partitions: The number of partitions the stat will be calculated on. min_partitions_stat_presence: The minimum number of partitions a stat computation must succeed in for the result to be...
625941e376d4e153a657ef0b
def camera_image(self): <NEW_LINE> <INDENT> now = utcnow() <NEW_LINE> if self._ready_for_snapshot(now) or True: <NEW_LINE> <INDENT> image = self._device.camera_get_image(self._uuid, now) <NEW_LINE> self._next_snapshot_at = now + self._time_between_snapshots <NEW_LINE> self._last_image = image <NEW_LINE> <DEDENT> return...
Return a still image response from the camera.
625941e323849d37ff7b3465
def refresh_cached_ballot_item_measure_info(self, ballot_item, contest_measure=None): <NEW_LINE> <INDENT> values_changed = False <NEW_LINE> measure_found = False <NEW_LINE> contest_measure_manager = ContestMeasureManager() <NEW_LINE> results = {} <NEW_LINE> if contest_measure and hasattr(contest_measure, 'measure_title...
The BallotItem tables cache information from other tables. This function reaches out to the source tables and copies over the latest information to the BallotItem table. :param ballot_item: :param contest_measure: No need to retrieve again if passed in :return:
625941e3be7bc26dc91cd9d2
def __call__(self, role, privilege, resource, acl): <NEW_LINE> <INDENT> return self._delegate(role, privilege, resource, acl)
:type role: simpleacl.interfaces.IRole :type privilege: simpleacl.interfaces.IPrivilege :type resource: simpleacl.interfaces.IResource :type acl: simpleacl.interfaces.IAcl :rtype: bool or None
625941e39f2886367277ac63
def extrude_faces_move(MESH_OT_extrude_faces_indiv=None, TRANSFORM_OT_shrink_fatten=None): <NEW_LINE> <INDENT> pass
Extrude faces and move result Arguments: @MESH_OT_extrude_faces_indiv (MESH_OT_extrude_faces_indiv): Extrude individual faces only (optional) @TRANSFORM_OT_shrink_fatten (TRANSFORM_OT_shrink_fatten): Shrink/fatten selected vertices along normals (optional)
625941e3091ae35668667330
def __get__(self, instance, cls): <NEW_LINE> <INDENT> return types.MethodType(self, instance, cls)
Descriptor to make this callable bind to a handler. Args: instance: A (likely Handler) object which owns this callable. cls: The (unused) class of `instance`. See: http://stackoverflow.com/a/10421444/1068170 http://stackoverflow.com/a/12505646/1068170 https://docs.python.org/2/howto/descriptor.html Returns...
625941e3d53ae8145f87a641
def profile_running(profile): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> client = Client(profile=profile) <NEW_LINE> return True <NEW_LINE> <DEDENT> except OSError as os_err: <NEW_LINE> <INDENT> print("Caught OSError while attempting to connect to {}: {}.".format(profile, os_err)) <NEW_LINE> return False <NEW_LINE> <...
Checks if there is an ipyparallel cluster running with profile Args: profile: name of profile Returns: is_running: true if found
625941e3ac7a0e7691ed449e
def get_action_url(self, obj): <NEW_LINE> <INDENT> action_url = obj.action_actor.profile.get_absolute_url() <NEW_LINE> if obj.action_object is not None: <NEW_LINE> <INDENT> if hasattr(obj.action_object, 'get_absolute_url'): <NEW_LINE> <INDENT> action_url = obj.action_object.get_absolute_url() <NEW_LINE> <DEDENT> <DEDEN...
Try to find most appropriate url for this kind of notification.
625941e33d592f4c4ed1d43c
def __init__(self, params=None): <NEW_LINE> <INDENT> super(DeleteSubscribeRequest, self).__init__(params) <NEW_LINE> if params is None: <NEW_LINE> <INDENT> self.__lobby_name = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.set_lobby_name(params['lobbyName'] if 'lobbyName' in params.keys() else None) <NEW_LINE>...
コンストラクタ :param params: 辞書配列形式のパラメータ初期値リスト :type params: dict|None
625941e3a79ad161976cc51e
def child_task(self): <NEW_LINE> <INDENT> mp_util.child_close_fds() <NEW_LINE> from MAVProxy.modules.lib.wx_loader import wx <NEW_LINE> app = wx.App(False) <NEW_LINE> app.frame = ChecklistFrame(state=self, title=self.title) <NEW_LINE> app.frame.Show() <NEW_LINE> app.MainLoop()
child process - this holds all the GUI elements
625941e32eb69b55b151cc8e
@profiler.trace("db") <NEW_LINE> def create_zun_service(values): <NEW_LINE> <INDENT> return _get_dbdriver_instance().create_zun_service(values)
Create a new zun_service record. :param values: A dict containing several items used to identify and define the zun_service record. :returns: A zun_service record.
625941e35510c4643540f7b4
def load(self): <NEW_LINE> <INDENT> with open(self.settings_file, 'rb') as settings_file: <NEW_LINE> <INDENT> self.settings = pickle.load(settings_file)
Load from Settings.msh
625941e33539df3088e2e724
def fatal_exception(self, message, e): <NEW_LINE> <INDENT> self.logger.error( message ) <NEW_LINE> self.logger.error( str(e) ) <NEW_LINE> self.logger.error( traceback.format_exc() )
Prints an exception 'e' with 'message'. Also outputs the traceback.
625941e3287bf620b61d3e3b
def service_ceiling(w_s,h): <NEW_LINE> <INDENT> V_vs=0.508 <NEW_LINE> rho,temp=atmosphere.densityGradient(h) <NEW_LINE> tw=V_vs/(2/rho*w_s*(k/(3*C_D0))**0.5)**0.5+4*(k*C_D0/3)**0.5 <NEW_LINE> pw=power_calc(tw,V) <NEW_LINE> return tw
r = air density at the desired altitude. V_v =0.508 m/s if using the SI-system
625941e3796e427e537b09a2
def write_special_indexes(): <NEW_LINE> <INDENT> project_index_file = _get_project_index_file() <NEW_LINE> with allow_mode_write(): <NEW_LINE> <INDENT> with open(project_index_file, "w") as stream: <NEW_LINE> <INDENT> stream.write(yaml.dump(_project_special_indexes))
Writes the project-specific indexes to the project djangaeidx.yaml
625941e3a8370b7717052c77
def get_A(self): <NEW_LINE> <INDENT> return self.A
Get the matrix representation of the learned metric
625941e32ae34c7f2600d50a
def insert(self, value): <NEW_LINE> <INDENT> self.head = Node(value, self.head)
Adds value to beginning (aka head) of list
625941e363d6d428bbe448ca
def crop(ar, crop_width, copy=False, order='K'): <NEW_LINE> <INDENT> ar = np.array(ar, copy=False) <NEW_LINE> crops = _validate_lengths(ar, crop_width) <NEW_LINE> slices = [slice(a, ar.shape[i] - b) for i, (a, b) in enumerate(crops)] <NEW_LINE> if copy: <NEW_LINE> <INDENT> cropped = np.array(ar[slices], order=order, co...
Crop array `ar` by `crop_width` along each dimension. Parameters ---------- ar : array-like of rank N Input array. crop_width : {sequence, int} Number of values to remove from the edges of each axis. ``((before_1, after_1),`` ... ``(before_N, after_N))`` specifies unique crop widths at the start and en...
625941e3a17c0f6771cbe429
def level_sums(n,r,s): <NEW_LINE> <INDENT> from copy import copy <NEW_LINE> OutSet=[] <NEW_LINE> a=[0 for i in range(r)] <NEW_LINE> if(s): <NEW_LINE> <INDENT> t=n <NEW_LINE> h=-1 <NEW_LINE> a[0]=n <NEW_LINE> s=False <NEW_LINE> OutSet.append(copy(a)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return OutSet <NEW_LINE>...
Return a vector of length r such that sum_i vec_i = n
625941e397e22403b379d375
def __init__(self, suppress_notifications=None, ignore_teams_from_payload=None, ignore_recipients_from_payload=None, recipients=None, is_advanced=None, ignore_responders_from_payload=None, ignore_tags_from_payload=None, ignore_extra_properties_from_payload=None, responders=None, priority=None, custom_priority=None, tag...
LightstepIntegration - a model defined in Swagger
625941e30a366e3fb873ebf7
def reverse_run(self, payload, expected, expect_failure=False, skiptest_on_failure=False): <NEW_LINE> <INDENT> cls = type(self) <NEW_LINE> result = self._make_request(self.geocoder.reverse, **payload) <NEW_LINE> if result is None: <NEW_LINE> <INDENT> if expect_failure: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> eli...
Calls geocoder.reverse(**payload), then checks against `expected`.
625941e3f548e778e58cd958
def get_urn_details(urn_string): <NEW_LINE> <INDENT> check_urn(urn_string) <NEW_LINE> out = urn_mapping.get(urn_string, None) <NEW_LINE> if out is None: <NEW_LINE> <INDENT> raise KeyError( 'Got correctly formatted, but unmapped SIDD urn {}.'.format(urn_string)) <NEW_LINE> <DEDENT> return out
Gets the associated details for the given SIDD urn, or raise an exception for poorly formatted or unrecognized urn. Parameters ---------- urn_string Returns ------- dict
625941e34e696a04525c9826
def contourf(self, X, Y, Z, *args, zdir='z', offset=None, **kwargs): <NEW_LINE> <INDENT> had_data = self.has_data() <NEW_LINE> jX, jY, jZ = art3d.rotate_axes(X, Y, Z, zdir) <NEW_LINE> cset = super().contourf(jX, jY, jZ, *args, **kwargs) <NEW_LINE> self.add_contourf_set(cset, zdir, offset) <NEW_LINE> self.auto_scale_xyz...
Create a 3D filled contour plot. Parameters ---------- X, Y, Z : array-likes Input data. zdir : {'x', 'y', 'z'} The direction to use; defaults to 'z'. offset : scalar If specified, plot a projection of the contour lines at this position in a plane normal to zdir *args, **kwargs Other arguments are ...
625941e3187af65679ca54fa
def build(self, memory, last_quadruple): <NEW_LINE> <INDENT> self.memory = memory <NEW_LINE> self.last_quadruple = last_quadruple
Build Memory Generates one memory object
625941e3b5575c28eb68e3dd
def check_note(inst, note): <NEW_LINE> <INDENT> if inst < 0 or inst > 128 or note < 0 or note > 128: <NEW_LINE> <INDENT> return False; <NEW_LINE> <DEDENT> return MIDIConstants.MIDI_VALID_NOTES[inst][0] <= note <= MIDIConstants.MIDI_VALID_NOTES[inst][1]
Tells if the real instrument can play the given note :param inst: instrument number :param note: played note :return: boolean telling if instrument can play the given note
625941e3de87d2750b860170
def _resident_set_size() -> int: <NEW_LINE> <INDENT> statm = _PATH.read_text() <NEW_LINE> fields = statm.split() <NEW_LINE> return int(fields[1]) * _PAGESIZE
Return the current resident set size in bytes.
625941e3d7e4931a7ee9e2f8
def _anglesSlow(self): <NEW_LINE> <INDENT> if not self.btype == 'angle': <NEW_LINE> <INDENT> raise TypeError("TopologyGroup is not of type 'angle'") <NEW_LINE> <DEDENT> vec1 = self._ags[0].positions - self._ags[1].positions <NEW_LINE> vec2 = self._ags[2].positions - self._ags[1].positions <NEW_LINE> angles = np.array([...
Slow version of angle (numpy implementation)
625941e338b623060ff0b1c7
def test_parse_blank_line_mid(self): <NEW_LINE> <INDENT> self._test_parse_line(source="First\n\nLast", offset=6, length=1, eol="\n")
Test parsing a blank line in the middle of the input string.
625941e330dc7b7665901d3c
def get_ip(self): <NEW_LINE> <INDENT> return self._ip
@return: The IP address of the associated MonitoredPeer instance.
625941e34e4d5625662d47ac
def decode(self, val, attr): <NEW_LINE> <INDENT> if isinstance(val, str): <NEW_LINE> <INDENT> target_type = self.get_attribute_type(attr) <NEW_LINE> try: <NEW_LINE> <INDENT> if target_type is str: <NEW_LINE> <INDENT> return val <NEW_LINE> <DEDENT> elif target_type is unicode: <NEW_LINE> <INDENT> return val.decode('utf-...
Decode attribute value from LDAP representation (str).
625941e3293b9510aa2c366c
def is_opponent(self, piece): <NEW_LINE> <INDENT> test = self.get_player(piece) <NEW_LINE> if test == self.player + 3 or test == self.player + 1 or test == self.player -3 or test == self.player -1: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False
Test if a given piece is the opponent of a player
625941e34e696a04525c9827
def get_from_filename(filename, default=None): <NEW_LINE> <INDENT> name, ext = os.path.splitext(os.path.basename(filename)) <NEW_LINE> return EXTENSION_MIME_TYPE_MAP.get(ext, default)
Tries to determine the mime type from the given filename.
625941e33c8af77a43ae3b7e
def push(from_, to, content, redirect): <NEW_LINE> <INDENT> access_token = config.get("token", "access_token") <NEW_LINE> url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s" % access_token <NEW_LINE> requests_body = {'touser': to, 'template_id': template_id, 'url': redirect, 'topcolor': '#FF...
使用微信公众号测试接口推送消息 :param from_: 发件人,对应消息模板的参数 :param to: 收件人的openID :param content: 消息内容 :return: None
625941e33d592f4c4ed1d43d
def change_title(self, name): <NEW_LINE> <INDENT> self._debug('Change process title to %r.', name) <NEW_LINE> set_process_title(name)
Change process title.
625941e356b00c62f0f14a35
def getLocalTimeShiftInSecond(utctime, localtimezone, logger = None): <NEW_LINE> <INDENT> from datetime import datetime <NEW_LINE> from dateutil import tz <NEW_LINE> if logger: <NEW_LINE> <INDENT> logger.information("Input UTC time = %s" % (str(utctime))) <NEW_LINE> <DEDENT> if localtimezone == "UTC": <NEW_LINE> <INDEN...
Calculate the difference between UTC time and local time of given DataAndTime
625941e30fa83653e4657392
def transform_last(self): <NEW_LINE> <INDENT> if self.nruns == 0: <NEW_LINE> <INDENT> print("No imager runs yet!") <NEW_LINE> return <NEW_LINE> <DEDENT> return self._transform_list[-1]
Return last image transform used.
625941e3dd821e528d63b580
def download_bucket(bucket_name): <NEW_LINE> <INDENT> s3 = boto3.resource('s3', aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY) <NEW_LINE> bucket_obj = s3.Bucket(bucket_name) <NEW_LINE> all_files = [] <NEW_LINE> for key in bucket_obj.objects.all(): <NEW_LINE> <INDENT> all_files.append(key.key) <NEW_LINE...
Downloads an entire bucket! Just provide the bucket_name
625941e3d4950a0f3b08c723
def log_matches(matches, log_return=True): <NEW_LINE> <INDENT> for match in matches: <NEW_LINE> <INDENT> mark = '\u2713' if match[1] else 'x' <NEW_LINE> print(f"[{mark}] {match[0].to_string(log_return)}")
Parameters ---------- matches : iterable Iterable of tuples (Signature, bool)
625941e3aad79263cf390e21
def _run_point_mutation_tests(self, parser): <NEW_LINE> <INDENT> structure = parser.get_structure("example", "PDB/3JQH.cif") <NEW_LINE> res_1 = structure[0]["A"][1] <NEW_LINE> res_15 = structure[0]["A"][15] <NEW_LINE> self.assertTrue(res_1.is_disordered(), "Residue 1 is disordered") <NEW_LINE> self.assertTrue(res_15.is...
Shared test code for testing point mutations.
625941e367a9b606de4a8291
def anagramSolution1(s1, s2): <NEW_LINE> <INDENT> alist = list(s2) <NEW_LINE> pos1 = 0 <NEW_LINE> stillOK = True <NEW_LINE> while pos1 < len(s1) and stillOK: <NEW_LINE> <INDENT> pos2 = 0 <NEW_LINE> found = False <NEW_LINE> while pos2 < len(alist) and not found: <NEW_LINE> <INDENT> if s1[pos1] == alist[pos2]: <NEW_LINE>...
方案1:检查,复杂度为O(n^2) 先把第二个字符串转换成列表,然后检查第一个字符串中每一个元素是否存在于第二个列表, 如果存在则把对应位置的替换成None,否则直接返回False 参数: s1: 第一个字符串 s2: 第二个字符串
625941e385dfad0860c3b235
def New(*args, **kargs): <NEW_LINE> <INDENT> obj = itkWrapPadImageFilterIUC3IUC3.__New_orig__() <NEW_LINE> import itkTemplate <NEW_LINE> itkTemplate.New(obj, *args, **kargs) <NEW_LINE> return obj
New() -> itkWrapPadImageFilterIUC3IUC3 Create a new object of the class itkWrapPadImageFilterIUC3IUC3 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 ...
625941e3435de62698dfe027
@register.filter(name='cut') <NEW_LINE> def cut(value,arg): <NEW_LINE> <INDENT> return value.replace(arg,'')
This cuts our all values of "arg" from the string!
625941e37b180e01f3dc4bd0
def is_continuous(self): <NEW_LINE> <INDENT> return self.root.is_continuous()
Determines which marginals are continuous. Returns ------- is_continuous : array_like List of boolean values of length d, where d is the number of marginals and element i is `True` if marginal i is continuous.
625941e356ac1b37e62645a2
def _get_property_id(self, source_id, shared_details): <NEW_LINE> <INDENT> if source_id in self._unlinkable_pm_ids: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> target_property_ids = self._source_to_property_ids.get(source_id, None) <NEW_LINE> if target_property_ids is not None: <NEW_LINE> <INDENT> shared_detai...
Using pm_property_id, find and cache property_ids to avoid querying for the same property_id more than once. Return True when a property_id is found. If no ProperyStates (and subsequent Properties) are found, flag the PM ID as unlinkable, and False is returned.
625941e3090684286d50f0c4
def put(self, item, block=True, timeout=None): <NEW_LINE> <INDENT> self.not_full.acquire() <NEW_LINE> try: <NEW_LINE> <INDENT> if self.maxsize > 0: <NEW_LINE> <INDENT> if not block: <NEW_LINE> <INDENT> if self._qsize() >= self.maxsize: <NEW_LINE> <INDENT> raise Full <NEW_LINE> <DEDENT> <DEDENT> elif timeout is None: <N...
Put an item into the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until a free slot is available. If 'timeout' is a positive number, it blocks at most 'timeout' seconds and raises the Full exception if no free slot was available within that time. Otherwise ('block' is...
625941e3167d2b6e31218f6f
def _rebuild_pls_frequency_table_threshold(self): <NEW_LINE> <INDENT> pls_threshold = int(self.env['ir.config_parameter'].sudo().get_param('crm.pls_rebuild_threshold')) <NEW_LINE> if pls_threshold: <NEW_LINE> <INDENT> lead_count = self.env['crm.lead'].sudo().search_count([]) <NEW_LINE> if lead_count < pls_threshold: <N...
Called by action_set_lost and action_set_won. Will run the cron to update the frequency table only if the number of lead is above a specified value (from config_parameter) for onboarding purpose. Once the threshold is reached, the config_param is set to 0 to avoid re-run the cron and, mainly, to avoid making useless se...
625941e3f7d966606f6aa3e3
def get_fans(browser, username, relationship_data, live_match, store_locally, logger, logfolder): <NEW_LINE> <INDENT> if username is None or type(username) != str: <NEW_LINE> <INDENT> logger.info("Please enter a username to pick Fans ~leaving out of an invalid value") <NEW_LINE> return [] <NEW_LINE> <DEDENT> all_follo...
Find Fans of a given user
625941e315baa723493c4352
def project_along_line(line, fld, interp_kind='trilin'): <NEW_LINE> <INDENT> fld_on_verts = viscid.interp(fld, line, kind=interp_kind) <NEW_LINE> dsvec = line[:, 2:] - line[:, :-2] <NEW_LINE> dsvec = np.concatenate([dsvec[:, 0:1], dsvec, dsvec[:, -2:-1]], axis=1) <NEW_LINE> dsvec = dsvec / np.linalg.norm(dsvec, axis=0)...
Project a Vector Field Parallel to a streamline Args: line (ndarray): 3xN of points along the fld (VectorField): Field to interpolate and project onto the line interp_kind (str): which interpolation to use, const or trilin
625941e3460517430c394555
def enum_process_schema(enum: Type[Enum], *, field: Optional[ModelField] = None) -> Dict[str, Any]: <NEW_LINE> <INDENT> from inspect import getdoc <NEW_LINE> schema_: Dict[str, Any] = { 'title': enum.__name__, 'description': getdoc(enum), 'enum': [item.value for item in cast(Iterable[Enum], enum)], } <NEW_LINE> add_fie...
Take a single `enum` and generate its schema. This is similar to the `model_process_schema` function, but applies to ``Enum`` objects.
625941e3d7e4931a7ee9e2f9
def sorted_strnum(elems: List[str]) -> List[str]: <NEW_LINE> <INDENT> maxlen = max(len(x) for x in elems) <NEW_LINE> return sorted(elems, key=lambda s: f"{s:0>{maxlen}}")
Ordena cadenas, teniendo en cuenta su valor numérico. Por ejemplo, sorted_strnum(["11", "9"]) devuelve ["9", "11"]. Y sorted_strnum(["a", "11", "9"]) devuelve ["9", "11", "a"].
625941e38c3a873295158799
def _set_enable(self, v, load=False): <NEW_LINE> <INDENT> if hasattr(v, "_utype"): <NEW_LINE> <INDENT> v = v._utype(v) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> t = YANGDynClass(v,base=YANGBool, is_leaf=True, yang_name="enable", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=...
Setter method for enable, mapped from YANG variable /telemetry_model_driven/enable (empty) If this variable is read-only (config: false) in the source YANG file, then _set_enable is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_enable() directly. YANG ...
625941e3bd1bec0571d90a09
def load_models_using_filepattern( self, filename_pattern, model, glob_args, is_main_model=False, encoding='utf-8', add_to_local_models=True, model_params=None): <NEW_LINE> <INDENT> from textx import get_metamodel <NEW_LINE> if model is not None: <NEW_LINE> <INDENT> self.update_model_in_repo_based_on_filename(model) <N...
Add a new model to all relevant objects. Args: filename_pattern: models to be loaded model: model holding the loaded models in its _tx_model_repository field (may be None). glob_args: arguments passed to the glob.glob function. Returns: the list of loaded models
625941e391f36d47f21ac8d1
def execute_workload (workload, planner, overlay_mgr, workload_mgr, strategy=troy.AUTOMATIC) : <NEW_LINE> <INDENT> if strategy == troy.AUTOMATIC : <NEW_LINE> <INDENT> if 'plugin_strategy' in workload.session.cfg : <NEW_LINE> <INDENT> strategy = workload.session.cfg['plugin_strategy'] <NEW_LINE> <DEDENT> else : <NEW_L...
Execute the given workload -- i.e., translate, bind and dispatch it, and then wait until its execution is completed. For that to happen, we also need to plan, translate, schedule and dispatch an overlay, obviously...
625941e396565a6dacc8faa4
@jit(nopython=True, cache=True) <NEW_LINE> def load_domains(data, domain_mask, vmap, variables): <NEW_LINE> <INDENT> index = 0 <NEW_LINE> while index < data.size: <NEW_LINE> <INDENT> buf = data[index: index + 8] <NEW_LINE> reverse_array(buf) <NEW_LINE> variableId = np.frombuffer(buf, dtype=np.int64)[0] <NEW_LINE> index...
TODO.
625941e39b70327d1c4e11b1
def getDAQName(self): <NEW_LINE> <INDENT> with self.lock: <NEW_LINE> <INDENT> return self.config['commandChannel']['device']
Return the DAQ name used by this device. (assumes there is only one DAQ for now)
625941e36fece00bbac2db1d
def uri_scope_key(uri, userid=None, group=None): <NEW_LINE> <INDENT> normalized_uri = normalize_uri(uri) <NEW_LINE> if userid: <NEW_LINE> <INDENT> username = username_from_userid(userid) <NEW_LINE> return f'{normalized_uri}|u:{username}' <NEW_LINE> <DEDENT> elif group: <NEW_LINE> <INDENT> return f'{normalized_uri}|g:{g...
Return the (URI, scope) key associated with a given URI and scope.
625941e3d268445f265b5249
def parse_args(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser(description="MOTChallenge evaluation") <NEW_LINE> parser.add_argument( "--mot_dir", help="Path to MOTChallenge directory (train or test)", required=True) <NEW_LINE> parser.add_argument( "--detection_dir", help="Path to detections.", default="detecti...
Parse command line arguments.
625941e3a934411ee3751a6f
def getControllerVibrationState(session, controllerType, outState): <NEW_LINE> <INDENT> result = libovr.ovr_GetControllerVibrationState(session, controllerType, byref(outState)) <NEW_LINE> _checkResult(result, "getControllerVibrationState") <NEW_LINE> return result
Gets the Haptics engine playback state of a specific Touch controller. \param[in] session Specifies an ovrSession previously returned by ovr_Create. \param[in] controllerType Controller where the Haptics buffer wil be played. \param[in] outState State of the haptics engine. eturn Returns ovrSuccess upon success. \see...
625941e32ae34c7f2600d50b
def match(pat: list, msg: str, rules: dict) -> Optional[str]: <NEW_LINE> <INDENT> if pat and not msg: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> elif not pat: <NEW_LINE> <INDENT> return msg <NEW_LINE> <DEDENT> elif pat[0] == msg[0]: <NEW_LINE> <INDENT> return match(pat[1:], msg[1:], rules) <NEW_LINE> <DEDENT> ...
Given pat [4, 1, 5] msg 'ababbb' return ['a', 1, 5] ababbb return [1, 5] babbb ... return [] ''
625941e3d6c5a10208144428
def get_angle(self,ch): <NEW_LINE> <INDENT> response = self.query("GA")[3:].split(',') <NEW_LINE> print("angle in microdegree:", response[0]) <NEW_LINE> print("revolutions:", response[1]) <NEW_LINE> return response
returns the absolute angle and revolutions of the given positioner channel ch
625941e3c4546d3d9de72e12
@data_routes.route('/data', methods=['GET', 'POST']) <NEW_LINE> @requires_access_level('Admin') <NEW_LINE> def data(): <NEW_LINE> <INDENT> meas_id = request.args.get('id', type=int) <NEW_LINE> plot_form = PlotterForm() <NEW_LINE> plot_form.pv_modul.choices = [(measurement.pv_module_id, str(measurement.pv_module.manufac...
Plot the functions U-I and U-P with buttons to query different measurements
625941e35166f23b2e1a5533
def add(*numbers): <NEW_LINE> <INDENT> return reduce(lambda x, y: x + y, numbers)
Add some numbers! add two numbers: >>> add(1, 2) 3 add three numbers: >>> add(1, 2, 3) 6 strings are concatenated: >>> add('1', '2') '12'
625941e350812a4eaa59c6f8
def scheduleintegration_deleteitemsbymasterid_with_http_info(self, **kwargs): <NEW_LINE> <INDENT> local_var_params = locals() <NEW_LINE> all_params = [ 'unknown_base_type' ] <NEW_LINE> all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) <NEW_LINE> for key, val in six.i...
Delete multiple schedule items looking up by a third party master ID # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.scheduleintegration_deleteitemsbymasterid_with_http_info(async_req=True) >>> result = thread.get(...
625941e3b830903b967e9ce1
def parse_datetime(string): <NEW_LINE> <INDENT> return dates.parse_datetime(string, locale=get_locale())
Parse a datetime from a string.
625941e36fb2d068a760f47e
def test_service_field_hidden_true(self): <NEW_LINE> <INDENT> ui = [{ 'appConfiguration': {'fields': [{'hidden': True, 'type': 'string', 'name': 'title'}]} }] <NEW_LINE> service = services.Service(cleaned_data={}, version=2, fqn='io.murano.Test', application=self.application, forms=ui) <NEW_LINE> form = next(e for e in...
Test hidden widget `hidden: true` in UI definition results to HiddenInput in Django form.
625941e326238365f5f0f24e
def get_target(target_fqn): <NEW_LINE> <INDENT> module_fqn = target_fqn.split('.') <NEW_LINE> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> module = __import__('.'.join(module_fqn)) <NEW_LINE> break <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> module_fqn.pop() <NEW_LINE> if len(module_fqn) == ...
This function returns the target object, module object, and the module's fully qualified name based on the provided fully qualified target name.
625941e3236d856c2ad44bba
def on_message(self, unused_channel, basic_deliver, properties, body): <NEW_LINE> <INDENT> LOGGER.info('Received message # %s from %s: %s', basic_deliver.delivery_tag, properties.app_id, body) <NEW_LINE> if self.message_received(body): <NEW_LINE> <INDENT> self.acknowledge_message(basic_deliver.delivery_tag)
Invoked by pika when a message is delivered from RabbitMQ. The channel is passed for your convenience. The basic_deliver object that is passed in carries the exchange, routing key, delivery tag and a redelivered flag for the message. The properties passed in is an instance of BasicProperties with the message properties...
625941e37b25080760e39831
def set_attributes(self, **kwargs): <NEW_LINE> <INDENT> if self._subresource_map: <NEW_LINE> <INDENT> self.set_subresources(**kwargs) <NEW_LINE> for key in self._subresource_map.keys(): <NEW_LINE> <INDENT> kwargs.pop(key, None) <NEW_LINE> <DEDENT> <DEDENT> for field, value in kwargs.items(): <NEW_LINE> <INDENT> if fiel...
Set the resource attributes from the kwargs. Only sets items in the `self.Meta.attributes` white list. Subclass this method to customise attributes. Args: kwargs: Keyword arguements passed into the init of this class
625941e38da39b475bd65353
def __init__(self, number_of_elements=None, content=None, total_elements=None): <NEW_LINE> <INDENT> self._number_of_elements = None <NEW_LINE> self._content = None <NEW_LINE> self._total_elements = None <NEW_LINE> self.discriminator = None <NEW_LINE> if number_of_elements is not None: <NEW_LINE> <INDENT> self.number_of...
NetworkDomainResult - a model defined in Swagger
625941e3596a897236089e96
def predict(self, x): <NEW_LINE> <INDENT> if isinstance(x, RDD): <NEW_LINE> <INDENT> return self.call("predict", x.map(_convert_to_vector)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.call("predict", _convert_to_vector(x))
Predict values for a single data point or an RDD of points using the model trained. Note: In Python, predict cannot currently be used within an RDD transformation or action. Call predict directly on the RDD instead.
625941e30383005118ecf9bc
def cleanComment(response:str) ->str: <NEW_LINE> <INDENT> response = re.sub(r'<!--[.\s\S]*?-->', '', response) <NEW_LINE> return response
clean html comment :param response: :return: type<str>
625941e396565a6dacc8faa5
def helper(self, s, left_end): <NEW_LINE> <INDENT> res = len(s) <NEW_LINE> for i in range(len(s)): <NEW_LINE> <INDENT> if s[i] == "0" and i < left_end: <NEW_LINE> <INDENT> res += 1 <NEW_LINE> <DEDENT> elif s[i] == "1" and i >= left_end: <NEW_LINE> <INDENT> res += 1 <NEW_LINE> <DEDENT> <DEDENT> return res
Args: s: str left_end: int Return: int
625941e397e22403b379d376
def make_plot_titles(nt, options): <NEW_LINE> <INDENT> if type(options["title"]) == str: <NEW_LINE> <INDENT> options["title"] = [options["title"]] * nt <NEW_LINE> <DEDENT> elif type(options["title"]) == list: <NEW_LINE> <INDENT> if len(options["title"]) > nt: <NEW_LINE> <INDENT> warnings.warn( "Dimension of time and le...
Creates the array of plot titles passed to the plotting function. This function allows dynamic plot titles such as the frame number or time. When the user has just passed in a fixed string, this is repeated to be the same length as the time dimension. Parameters ---------- nt : int Length of the time dimension. ...
625941e3d10714528d6000c2
def find_targets(my_id, game_map, data): <NEW_LINE> <INDENT> assigned_pieces = [] <NEW_LINE> remaining_pieces = data["pieces"] <NEW_LINE> def assign_pieces_to_target(remaining_pieces, target): <NEW_LINE> <INDENT> assigned_pieces = [] <NEW_LINE> closest_remaining = sort_pieces_by_distance(game_map, remaining_pieces, tar...
Updates data["targets"], data["target_locs"], and returns lists of pieces assigned to targets.
625941e36e29344779a629eb
def __init__(self): <NEW_LINE> <INDENT> if BlinktCommand.__instance is None: <NEW_LINE> <INDENT> BlinktCommand.__instance = self <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logging.getLogger("BlinktCommand").warning("Singleton already activated, use get instance")
Initializes a singleton instance of BlinktCommand.
625941e315baa723493c4353
def eval(self, layer, input, output): <NEW_LINE> <INDENT> super(DeferredHook, self).eval(layer, input, output) <NEW_LINE> self.output = output
Evaluates layerFcn, inputFcn and outputFcn over the bound layer, storing its input and output afterwards Parameters ---------- layer : torch.nn.Module the hooked layer input : object the layer input output : object the layer output Returns ------- None
625941e366656f66f7cbc587
def test_basic(self): <NEW_LINE> <INDENT> mysite = self.site <NEW_LINE> rc = list(mysite.recentchanges(total=10)) <NEW_LINE> self.assertLessEqual(len(rc), 10) <NEW_LINE> self.assertTrue(all(isinstance(change, dict) for change in rc))
Test the site.recentchanges() method.
625941e35510c4643540f7b5
def predict(self, X): <NEW_LINE> <INDENT> X=X.astype(np.float64) <NEW_LINE> X = (X - np.mean(X, axis=0)) / np.std(X, axis=0) <NEW_LINE> pred_prob = self.logistic_func(self.theta, X) <NEW_LINE> y = np.where(pred_prob >= 0.5, 1, 0) <NEW_LINE> return y
your code here
625941e321bff66bcd684d2a
def split_doc(doc): <NEW_LINE> <INDENT> GROUP_LENGTH = 0 <NEW_LINE> curr = [] <NEW_LINE> curr_len = 0 <NEW_LINE> for split in re.split(r'\n+', doc): <NEW_LINE> <INDENT> split = split.strip() <NEW_LINE> if len(split) == 0: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if len(curr) > 0 and curr_len + len(split) > GROU...
Given a doc, split it into chunks (by paragraph).
625941e34527f215b584c82e
def get_num_physical_lines(self, filename): <NEW_LINE> <INDENT> if PY_VERS < 3: <NEW_LINE> <INDENT> inf = open_(filename, "r", encoding=self.encoding) <NEW_LINE> src = inf.readline <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> inf = open(filename, "r", encoding=self.encoding) <NEW_LINE> src = inf.readline <NEW_LINE> <D...
Returns the line nummer where a logical line ends. The converter works with a list of logical lines, not physical lines. Args: filename -- the file name Returns: int(lineno)
625941e399fddb7c1c9de76a
def diff(x, y, smoothing=1): <NEW_LINE> <INDENT> aux = [ [x[i], (y[i - smoothing] - y[i + smoothing]) / (x[i - smoothing] - x[i + smoothing])] for i in range(smoothing, len(x) - smoothing)] <NEW_LINE> out = np.array(aux) <NEW_LINE> return out
625941e371ff763f4b549a6d
def delete(self, command, json_req): <NEW_LINE> <INDENT> self.r.delete(json_req['key']) <NEW_LINE> return self.ok()
Pretty command - actual command is del.
625941e36aa9bd52df037181
def numElements(self): <NEW_LINE> <INDENT> self.checkValid() <NEW_LINE> return self._CyObject__data['mplug'].numElements()
マルチアトリビュートの評価済みの要素数を得る。 この数に基づいて要素を得るには `element` を利用できる。 :rtype: `int` .. warning:: コネクトされていても未評価のプラグはカウントされない点に注意。 評価を保証したい場合は `evaluateNumElements` を使用すること。 `evaluateNumElements` を呼び出した後は、このメソッドも同じ値を 返すようになり、これに依存した操作も期待通り動作する。
625941e3566aa707497f493e
def get_command_args(args): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser(description=constants.MAINDOC, prog='extract_msg') <NEW_LINE> parser.add_argument('--use-content-id', '--cid', dest='cid', action='store_true', help='Save attachments by their Content ID, if they have one. Useful when working with the HTML...
Parse command-line arguments
625941e3b545ff76a89141f0
def random_color(self): <NEW_LINE> <INDENT> for i in range(self._game.get_num()**2): <NEW_LINE> <INDENT> if i in self._game.get_buttonlist(): <NEW_LINE> <INDENT> self._buttons[i].config(bg="black", state='disabled') <NEW_LINE> self._buttons[i].after(self._time, lambda: self.change_back())
This method will start the game by making the boxes blink
625941e3d4950a0f3b08c724
def union(self,x,y): <NEW_LINE> <INDENT> xRoot = self.dictionary[self.find(x)] <NEW_LINE> yRoot = self.dictionary[self.find(y)] <NEW_LINE> if xRoot.rank > yRoot.rank: <NEW_LINE> <INDENT> yRoot.parent = xRoot <NEW_LINE> <DEDENT> elif xRoot.rank < yRoot.rank: <NEW_LINE> <INDENT> xRoot.parent = yRoot <NEW_LINE> <DEDENT> e...
Adds together two trees with given elements
625941e3c432627299f05024