code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def ruleitems(rules, items): <NEW_LINE> <INDENT> newrules = {} <NEW_LINE> for key, value in list(rules.items()): <NEW_LINE> <INDENT> newrules[key] = {} <NEW_LINE> for value2 in items: <NEW_LINE> <INDENT> if value2 in value: <NEW_LINE> <INDENT> newrules[key][value2] = value[value2] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> ...
Get the specified items from the rules. ``rules`` dict - The dict to grab from. ``items`` list - The items to grab from the dict. Returns: dict - The dict with the specified items.
625941f43eb6a72ae02ecb09
def test_handle_read__fullmessage(self): <NEW_LINE> <INDENT> self.obj_ut.process_msg = Mock() <NEW_LINE> self.assertEqual(self.obj_ut._iobuf.getvalue(), b'') <NEW_LINE> body = b'this is the drum roll' <NEW_LINE> extra = b'NEXT' <NEW_LINE> self.obj_ut._iobuf.write( b'\x84\x01\x00\x02\x03\x00\x00\x00\x15' + body + extra)...
Verify that handle_read() processes complete messages properly.
625941f4c4546d3d9de73055
def select_kernel(self, kernel): <NEW_LINE> <INDENT> pass
Convert the name of the kernel as string to the kernel class object of the surrogate. Parameters: kernel (str): Kernel string such as 'RBF' or depending on the surrogate also product and sum kernels such as 'RBF+Matern52'. Returns: object: Custom or imported kernel object. This is the function which bu...
625941f4851cf427c661ab23
@pytest.fixture(scope="session") <NEW_LINE> def tmpfile(tmpdir_factory): <NEW_LINE> <INDENT> def make(filename): <NEW_LINE> <INDENT> fn = tmpdir_factory.mktemp("data").join(filename) <NEW_LINE> return fn <NEW_LINE> <DEDENT> return make
Sets up a temporary file https://docs.pytest.org/en/latest/tmpdir.html#the-tmpdir-factory-fixture
625941f42eb69b55b151ced3
def RetentionInSecondsMatch(seconds): <NEW_LINE> <INDENT> return _RETENTION_IN_SECONDS().match(seconds)
Test whether the string matches retention in seconds pattern. Args: seconds: string to match for retention specified in seconds format. Returns: Returns a match object if the string matches the retention in seconds pattern. The match object will contain a 'number' group for the duration in number of seconds. ...
625941f4851cf427c661ab24
def GET(self): <NEW_LINE> <INDENT> callback_params = web.input() <NEW_LINE> oauth_session = OAuth2Session(session['api_key'], redirect_uri=session['redirect_uri'], scope=session['scope']) <NEW_LINE> token_response = fetch_token(oauth_session, session['oauth2_server']) <NEW_LINE> logging.info(token_response) <NEW_LINE> ...
This is where Bookshare calls back with the code we need to fetch a token
625941f4dd821e528d63b7be
def subroutine(a, b): <NEW_LINE> <INDENT> R | a <NEW_LINE> BS | (a,b) <NEW_LINE> R.H | a
Subroutine for the quantum program
625941f466673b3332b926ab
def hash(self, plaintext): <NEW_LINE> <INDENT> return self.hash_obj(plaintext).digest()
Produces a binary SHA-256 hash. >>> re = make(['rotate', 38]) >>> re.hash('hello, world') '\t\xca~N\xaan\x8a\xe9\xc7\xd2a\x16q)\x18H\x83dM\x07\xdf\xba|\xbf\xbcL\x8a.\x086\r[' >>> re.hash('a'*300) '\x985\xfak\xf4\xe2\n\x9b\x9e\xa8\x12Pc\x02\xe9\x89\x82r\x1al\xf8\xd2\xca\xe6z\xf5q)\xbf!\xae\x90'
625941f492d797404e3047a8
def local_asn(self, **kwargs): <NEW_LINE> <INDENT> local_as = kwargs.pop('local_as') <NEW_LINE> rbridge_id = kwargs.pop('rbridge_id', '1') <NEW_LINE> callback = kwargs.pop('callback', self._callback) <NEW_LINE> local_as_args = dict(local_as=local_as, rbridge_id=rbridge_id) <NEW_LINE> enable_bgp = getattr(self._rbridge,...
Set BGP local ASN. Args: local_as (str): Local ASN of NOS deice. rbridge_id (str): The rbridge ID of the device on which BGP will be configured in a VCS fabric. callback (function): A function executed upon completion of the method. The only parameter passed to `callback` will be the ...
625941f4a17c0f6771cbe669
def ls(**args): <NEW_LINE> <INDENT> snapper = _from_args(**args) <NEW_LINE> snapshots = snapper.list_snapshots() <NEW_LINE> for snap in snapshots: <NEW_LINE> <INDENT> print("- snapshot: {}".format(snap["snapshot"])) <NEW_LINE> print(" start_time: {}".format(snap["start_time"])) <NEW_LINE> print(" end_time: {}".format...
Do list
625941f430c21e258bdfaabf
def testIntermixedSubrepoDelete(self): <NEW_LINE> <INDENT> def doTest(prefix): <NEW_LINE> <INDENT> with GitRepository() as r1, GitRepository() as r2, GitRepository() as r3: <NEW_LINE> <INDENT> write(r1, "r1.py", data="data") <NEW_LINE> r1.add("r1.py") <NEW_LINE> r1.commit() <NEW_LINE> r3.remote("add...
Verify that deletion of subrepos imported directly and indirectly works as expected.
625941f43346ee7daa2b338d
def plotDistance(event, CRP, freq, path): <NEW_LINE> <INDENT> title = 'Pupil distance to eye center- Freq: '+freq+'c/d' <NEW_LINE> ax = CRP.plot(x='Time', y='pupil_dist',label='d',title=title) <NEW_LINE> ax.set_ylim(0.9*np.min(boundary['posdMin']),1.1*np.max(boundary['posdMax'])) <NEW_LINE> plt.ylabel('d [mm]') <NEW_LI...
Plot distance of pupil the eye center
625941f4a8370b7717052eb8
def opn(self, line, newline=True): <NEW_LINE> <INDENT> self.add(line, newline) <NEW_LINE> self.indent()
Used to open an html tag, adding a line containing the tag, and indenting the following text so it reflect the opened tag in the indentation.
625941f416aa5153ce362a94
def checkResponse(self, response, instance, former_mmr, former_characters): <NEW_LINE> <INDENT> form = response.context["form"] <NEW_LINE> self.assertFalse(form.is_valid()) <NEW_LINE> self.assertEqual( list(instance.characters.all()), former_characters, 'Characters should not be modified by invalid POST request' ) <NEW...
Check if response contains invalid form and nothing were created
625941f4d99f1b3c44c67b9d
def test_attempt_length_in_minutes(self): <NEW_LINE> <INDENT> self.attempt.created = aware_datetime(2014, 1, 1) <NEW_LINE> self.attempt.modified = aware_datetime(2014, 1, 2) <NEW_LINE> eq_(self.attempt.attempt_length_in_minutes, 1440)
Return the time, in minutes between the attempt creation time and last modification time.
625941f4e1aae11d1e74a2d8
def readCSV(self, path): <NEW_LINE> <INDENT> csv_file = pd.read_csv(path, header=-1) <NEW_LINE> self.i_values = OrderedDict() <NEW_LINE> indexes = {"A": 1, "B": 2, "C": 3, "D": 4, "E": 5, "F": 6, "G": 7, "H": 8, "I": 9} <NEW_LINE> pos = [] <NEW_LINE> for value in sorted(csv_file.values): <NEW_LINE> <INDENT> pos.extend(...
Fill sudoku table from a csv file
625941f44f88993c3716c67b
def import_object(name): <NEW_LINE> <INDENT> assert isinstance(name, str), "The module name must be a string" <NEW_LINE> parts = name.split('.') <NEW_LINE> assert len(parts) > 1, "'%s' is not a valid module name" % name <NEW_LINE> attr_name = parts[-1] <NEW_LINE> module_name = functools.reduce(lambda x, y: x + '.' + y,...
This function imports an object from a module. Can throw ImportError or AttributeError if object_name it is not valid.
625941f410dbd63aa1bd31bc
def spawn(self, func, pid, spec, fields): <NEW_LINE> <INDENT> args = (pid, spec, fields) <NEW_LINE> evt = Event() <NEW_LINE> if not pid in self._pids: <NEW_LINE> <INDENT> self._pids.add(pid) <NEW_LINE> task = (evt, pid, func, args) <NEW_LINE> self._tasks.put(task) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> evt.set...
Spawn new process for given function
625941f49f2886367277aea3
def __init__(self, msg_ids, info): <NEW_LINE> <INDENT> self.msg_ids = msg_ids <NEW_LINE> self.info = info
:param List[int] msg_ids: :param str info: Constructor for MsgsAllInfo: Instance of MsgsAllInfo.
625941f456b00c62f0f14c78
def cur(self): <NEW_LINE> <INDENT> if self.eof(): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self._data[self._index]
Return current token
625941f4925a0f43d254a498
def test_two_students_dont_see_each_other_pages(self): <NEW_LINE> <INDENT> email1 = 'user1@foo.com' <NEW_LINE> name1 = 'User 1' <NEW_LINE> email2 = 'user2@foo.com' <NEW_LINE> name2 = 'User 2' <NEW_LINE> actions.login(email1) <NEW_LINE> actions.register(self, name1) <NEW_LINE> actions.Permissions.assert_enrolled(self) <...
Test a user can't see another user pages.
625941f47047854f462a1a1d
def threaded_pvput(pv, value): <NEW_LINE> <INDENT> t0 = time.time() <NEW_LINE> print(' - threaded_pvput starting at ', pv.get()) <NEW_LINE> pv.put(value, wait=True, timeout=10.0) <NEW_LINE> print(' - threaded_pvput done (%.3f sec)' % (time.time()-t0))
put-with-wait for calling in a thread
625941f43539df3088e2e966
def run(database, document, object, item, trans): <NEW_LINE> <INDENT> sdb = SimpleAccess(database) <NEW_LINE> sdoc = SimpleDoc(document) <NEW_LINE> stab = SimpleTable(sdb) <NEW_LINE> sdoc.title(_("References for this %s") % trans) <NEW_LINE> sdoc.paragraph("\n") <NEW_LINE> stab.columns(_("Type"), _("Reference")) <NEW_L...
Display back-references for this object.
625941f4b545ff76a8914430
def find_vertices(self): <NEW_LINE> <INDENT> setattr(self, 'vertices', self.make_convex_hull().vertices)
Sets the convex vertices for the remaining points(towns) :return: None
625941f45510c4643540f9ef
def _load_modules(self, force_refresh=False): <NEW_LINE> <INDENT> modules_max_memory = False <NEW_LINE> if self.opts.get('modules_max_memory', -1) > 0 and HAS_PSUTIL and HAS_RESOURCE: <NEW_LINE> <INDENT> log.debug('modules_max_memory set, enforcing a maximum of {0}'.format(self.opts['modules_max_memory'])) <NEW_LINE> m...
Return the functions and the returners loaded up from the loader module
625941f4e76e3b2f99f3ae1c
def plot_routine(self, y, _ylabel, _title, plot_index, sci_format=False): <NEW_LINE> <INDENT> _plot = self.fig.add_subplot(self._size[0], self._size[1], plot_index) <NEW_LINE> _plot.plot(self.voltages, y) <NEW_LINE> _plot.set_xlabel("voltage (mV)") <NEW_LINE> _plot.set_ylabel(_ylabel) <NEW_LINE> _plot.set_title(_title,...
routine to plot currents or ion transport rates :param y: list of y axis data :param _ylabel: string to label the y axis :param _title: title to give the plot :param plot_index: what position to put the plot in, in the overall figure :param sci_format: turn on or off scientific plotting which scales the y axis :return:
625941f4eab8aa0e5d26e175
def test_source_directory_path_no_resource(self): <NEW_LINE> <INDENT> assert_equal( self.vcs_project.source_directory_path(), os.path.join(TEST_CHECKOUT_PATH, 'real_resources', 'templates') )
When searching for source directories, do not match directories that do not contain resource files.
625941f401c39578d7e75456
def get_leftmostchild_index(parent_index): <NEW_LINE> <INDENT> if (parent_index<<EXP2)+1>len(DATA): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return (parent_index<<EXP2)+1
Return the index of the leftmost child of the element at parent_index Use bit operators here - to multiply say n by 2^m - left shift n by m bits (written as n << m, in python)
625941f44e4d5625662d49ea
def handle_transparent(self, conn): <NEW_LINE> <INDENT> raise NotImplementedError
handle data in transparent mode. @raise NotImplementedError: this method is abstract.
625941f4187af65679ca573b
def get_user_temperature(self): <NEW_LINE> <INDENT> self._socketcommunication.send('GUT') <NEW_LINE> return self._socketcommunication.receive()
Returns the current user temperature or -0.100 to indicate the user temperature is not available. Units: Kelvin
625941f4a934411ee3751cb0
def GetPointeeType(self) -> 'SBType': <NEW_LINE> <INDENT> return _lldb.SBType_GetPointeeType(self)
GetPointeeType(SBType self) -> SBType
625941f4f8510a7c17cf9d1c
def filter_path(tarinfo): <NEW_LINE> <INDENT> if not dir_name in tarinfo.name: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> file_name = tarinfo.name.split(os.path.sep) <NEW_LINE> file_name = file_name[file_name.index(dir_name):] <NEW_LINE> tarinfo.name = os.path.sep.join(['.'] + file_name) <NEW_LINE> tarinfo.uid...
Change path of added files and reset owner.
625941f430c21e258bdfaac0
def _process_params(self, params): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> res = params <NEW_LINE> res = [self.converter.to_mysql(i) for i in res] <NEW_LINE> res = [self.converter.escape(i) for i in res] <NEW_LINE> res = [self.converter.quote(i) for i in res] <NEW_LINE> res = [str(i) for i in res] <NEW_LINE> <DEDE...
Process query parameters.
625941f4167d2b6e312191af
def verify_form_data(tform,oform,exp_sets,log): <NEW_LINE> <INDENT> valid = True <NEW_LINE> if tform.is_valid(): <NEW_LINE> <INDENT> log.info('Target information form validation: '+repr(tform.is_valid())) <NEW_LINE> log.info('Target information provided: '+repr(tform.cleaned_data['id'])) <NEW_LINE> <DEDENT> else: <NEW_...
Function to record the verification of the input data for an observation request, and to log information on faults, if any.
625941f4be383301e01b5a94
def notify(self, source, link, title, actions=[], hints={}): <NEW_LINE> <INDENT> keywords = self.cfg.get('main', 'ack_keywords').split(',') <NEW_LINE> if any(keyword.lower() in title.lower() for keyword in keywords): <NEW_LINE> <INDENT> hints = {'urgency': dbus.Byte(2)} <NEW_LINE> actions = ['0', 'Acknowledge'] <NEW_LI...
Method signature: https://developer.gnome.org/notification-spec/
625941f407f4c71912b11aa0
def _DM2NPDataType(self, dd): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> Type = self._DM2NPDataTypes[dd] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> Type = None <NEW_LINE> raise IOError('Unsupported binary data type during conversion to numpy dtype. DM dataType == {}'.format(dd)) <NEW_LINE> <DEDENT> exce...
Convert the DM data type value into a numpy dtype. Parameters ---------- dd : int The value encoded in the DM file header. Returns ------- Type : numpy dtype
625941f4462c4b4f79d1dcea
def LO(frequency, harmonic, IF=310.7e6): <NEW_LINE> <INDENT> return (frequency - IF) / harmonic
Calculate LO for HarmonicMixer. :param frequency: Target center frequency :param harmonic: Harmonic of mixer :param IF: IF frequency :returns: Frequency for LO source
625941f4adb09d7d5db6cda7
def remove_fields(a, names): <NEW_LINE> <INDENT> dt = a.dtype <NEW_LINE> keep_names = [name for name in dt.names if name not in names] <NEW_LINE> return fields_view(a, keep_names)
`a` must be a numpy structured array. `names` is the collection of field names to remove. Returns a view of the array `a` (not a copy).
625941f4a219f33f34628f7c
def _Open(self, mode='rb'): <NEW_LINE> <INDENT> if not self._path_spec.HasParent(): <NEW_LINE> <INDENT> raise errors.PathSpecError( 'Unsupported path specification without parent.') <NEW_LINE> <DEDENT> file_object = resolver.Resolver.OpenFileObject( self._path_spec.parent, resolver_context=self._resolver_context) <NEW_...
Opens the file system object defined by path specification. Args: mode (Optional[str]): file access mode. Raises: AccessError: if the access to open the file was denied. IOError: if the file system object could not be opened. PathSpecError: if the path specification is incorrect. ValueError: if the path spe...
625941f42eb69b55b151ced4
def rgb2hls(r, g, b): <NEW_LINE> <INDENT> return colorsys.rgb_to_hls(r/255.0, g/255.0, b/255.0)
Convert r,g,b in 0-255 range to hls in 0.1 :param r: red :param g: green :param b: blue :return: hue, luminance, saturation
625941f445492302aab5e8e5
def project_point(self, point, is_world_frame=True): <NEW_LINE> <INDENT> point = np.array(point) <NEW_LINE> if is_world_frame: <NEW_LINE> <INDENT> point = np.dot(point - self.pose.position, self.pose.matrix3) <NEW_LINE> <DEDENT> projected = np.dot(point, self.intrinsics.T) <NEW_LINE> projected = np.divide(projected, np...
Projects a point cloud onto the camera image plane. Args: point: 3D point to project onto the camera image plane. is_world_frame: True if the 3D point is defined in the world frame, False if it is defined in the camera frame. Returns: pixel: 2D pixel location in the camera image.
625941f4a79ad161976cc761
def get_worker_nodes(self): <NEW_LINE> <INDENT> self.clear_screen() <NEW_LINE> self.inventory_dict['csah']['vars']['compute_nodes'] = [] <NEW_LINE> self.inventory_dict['csah']['vars']['num_of_compute_nodes'] = len(self.nodes_inv['compute_nodes']) <NEW_LINE> self.inventory_dict = get_nodes_info(node_type='compute_nodes'...
get details about worker node
625941f4283ffb24f3c55f15
def test_single_lun_map_exist_parent_cg(self): <NEW_LINE> <INDENT> lunName = 'LuN' <NEW_LINE> lunSize = '1g' <NEW_LINE> parentConsistencyGroupName = 'Parent-CG' <NEW_LINE> initiatorGroupPrefix = 'IG' <NEW_LINE> initiatorGroupNumber = 3 <NEW_LINE> initiatorGroups = self._createInitiatorGroups(prefix= initiatorGroupPrefi...
Test verifies creation of single LUN mapped to existing parent consistency group.
625941f482261d6c526abac4
def get_object_position(canvas, current_row: int, current_column: int, frames: List[str], row_speed: int = 0, column_speed: int = 0, speed=1) -> Tuple[int, int, int, int]: <NEW_LINE> <INDENT> rocket_rows_direction, rocket_column_direction, _ = read_controls(canvas) <NEW_LINE> row_speed, column_speed = update_speed(row_...
Moves object according 'read_controls' actions if object inside canvas.
625941f450812a4eaa59c936
def prepare_count_bulletins(self, object): <NEW_LINE> <INDENT> roles = object.actorrole_set.all() <NEW_LINE> return Bulletin.objects.filter(actors_role__in=roles).count()
Returns count of bulletin objects associated with a given Actor
625941f48c0ade5d55d3efdc
def get_size(self): <NEW_LINE> <INDENT> return self.size
Returns the number of nodes in the BST O(1) time complexity :return: the number of nodes
625941f426238365f5f0f492
def de_hash(tags): <NEW_LINE> <INDENT> return [t.replace('#', '') for t in tags]
Remove optional leading pound signs.
625941f4e64d504609d74e5b
def groupby_feature_gen(num_col, group_col, data, raw_data, op_type): <NEW_LINE> <INDENT> new_cat_var = create_type_var(raw_data, group_col) <NEW_LINE> group_count = raw_data[new_cat_var].groupby(raw_data[new_cat_var]).count() <NEW_LINE> group_count = group_count.sort_values() <NEW_LINE> small_group = set(group_count.i...
data: already applied lgb prep, can be directly used for lgb train. raw_data: type_var before lgb prep, used for group_var and mean_var creation. test_data: full data, used to determine nan index. created feature follows format num_var__groupby__cat_var__op_type
625941f43317a56b8693a264
def toWm(latlon, lon=None, radius=R_MA, Wm=Wm, name=''): <NEW_LINE> <INDENT> r, e = radius, None <NEW_LINE> try: <NEW_LINE> <INDENT> lat, lon = latlon.lat, latlon.lon <NEW_LINE> if isinstance(latlon, _ELLB): <NEW_LINE> <INDENT> r = latlon.datum.ellipsoid.a <NEW_LINE> e = latlon.datum.ellipsoid.e <NEW_LINE> if not name:...
Convert a lat-/longitude point to a WM coordinate. @param latlon: Latitude (C{degrees}) or an (ellipsoidal or spherical) geodetic C{LatLon} point. @keyword lon: Optional longitude (C{degrees} or C{None}). @keyword radius: Optional earth radius (C{meter}). @keyword Wm: Optional (sub-)class for the WM coo...
625941f421bff66bcd684f68
def get_exc_before_and_after(self, string, func): <NEW_LINE> <INDENT> value = self.get_exception() <NEW_LINE> before = func(value) <NEW_LINE> add_string_to_exception(value, string) <NEW_LINE> after = func(value) <NEW_LINE> return (before, after)
Retrieve string representations of exceptions. Retrieve string representations of exceptions raised by code before and after calling add_string_to_exception.
625941f4462c4b4f79d1dceb
def add_connection(self, connection): <NEW_LINE> <INDENT> assert isinstance(connection, SSHConnection) <NEW_LINE> if connection.host not in self._connections: <NEW_LINE> <INDENT> self._connections[connection.host] = connection
Add an existing SSHConnection to the manager. This is useful for manually created connections which should also be available via the manager. Arguments: connection (:obj:`SSHConnection`): SSHconnection to add to the manager
625941f47d43ff24873a32c1
def _rsa_layout(self): <NEW_LINE> <INDENT> self.rsa = LFrRSA(self.options) <NEW_LINE> self.rsa.pack(expand=True, fill='x', padx=PADX, pady=PADY)
Initializes RSA layout. :return: None
625941f4283ffb24f3c55f16
def visit_FunctionDef(self, node): <NEW_LINE> <INDENT> self.generic_visit(node) <NEW_LINE> if node.name == "inner": <NEW_LINE> <INDENT> node.body[:1] = self.ast_setup.body <NEW_LINE> <DEDENT> return node
Fill in the setup statement
625941f497e22403b379d5b8
def Group_Objects_To_Rules(objects, rules, match_func): <NEW_LINE> <INDENT> for rule in rules: <NEW_LINE> <INDENT> rule['matches'] = [] <NEW_LINE> <DEDENT> for object in objects: <NEW_LINE> <INDENT> for rule in rules: <NEW_LINE> <INDENT> if match_func(object, **rule): <NEW_LINE> <INDENT> rule['matches'].append(object) ...
Matches objects against rules, and attaches matches to a rule['matches'] sublist. Each rule should be a dict with 'match_any', 'match_all', 'match_none' subrules, and may have other fields (except 'matches'). Returns nothing. Rules are annotated in-place. * objects - List of Macros or Componenets. * rules - List...
625941f4627d3e7fe0d6946e
def get_by_id(self, budget_id: int) -> Budget: <NEW_LINE> <INDENT> return self.__mapper.map( self.__repository.get_by_id(budget_id), Budget )
Gets a budget by its id. :param budget_id: the budget id :return: the budget
625941f482261d6c526abac5
def openmp(arg,threads=None,mpiimpl=None): <NEW_LINE> <INDENT> if mpiimpl is None: <NEW_LINE> <INDENT> mpiimpl=detect_mpi() <NEW_LINE> <DEDENT> return mpiimpl.openmp(arg,threads)
!Sets the number of OpenMP threads for the specified program. @warning Generally, when using MPI with OpenMP, the batch system must be configured correctly to handle this or unexpected errors will result. @param arg The "arg" argument must be from mpiserial, mpi, exe or bigexe. @param threads The optional "threads" ...
625941f467a9b606de4a84d1
def _updateDefaultCollectionFor(folderObj, default_uid): <NEW_LINE> <INDENT> if not IFacetedNavigable.providedBy(folderObj): <NEW_LINE> <INDENT> raise NoFacetedViewDefinedException(NO_FACETED_EXCEPTION_MSG) <NEW_LINE> <DEDENT> criterion = getCollectionLinkCriterion(folderObj) <NEW_LINE> ICriteria(folderObj).edit(criter...
Use p_default_uid as the default collection selected for the CollectionWidget used on p_folderObj.
625941f41b99ca400220b0d0
def Get(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> value, reg_type = winreg.QueryValueEx(_GetServiceKey(), "Transaction") <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if reg_type != winreg.REG_BINARY: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> ...
Return a GrrMessage instance from the transaction log or None.
625941f44428ac0f6e5bae14
def parse_mapping(mapping): <NEW_LINE> <INDENT> result = {} <NEW_LINE> if not mapping: <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> for index, mapping in enumerate(mapping): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if not mapping.strip(): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> product_id, group_name ...
Iterate over mapping and check that it can be sucessfully parsed. Ignore empty lines. :param mappings: List of pipe-delimited mappings in ``<product_id>|<group_id>`` format. :type mappings: list :rtype: dict :return: product_ids as keys, group_names as values >>> from niteoweb.jvzoo import parse_mapping Test f...
625941f4377c676e912727c2
def getEmptyGroup(pieces, x, y): <NEW_LINE> <INDENT> group = set() <NEW_LINE> visited = set() <NEW_LINE> return _getEmptyGroup(pieces, x, y, visited, group)
group is a set containing pieces of a group represented as (a, b, c) a is row b is column c is color
625941f4d486a94d0b98e762
@models.User.possession() <NEW_LINE> def uncollected_tickets(user): <NEW_LINE> <INDENT> return ( any(not x.cancelled and not x.collected for x in user.tickets) or ( user.held_ticket is not None and not user.held_ticket.collected ) )
Does the user have any uncollected tickets?
625941f44527f215b584ca6d
def compare_and_swap( self, key: str, old: typing.Optional[limit_data.LimitData], new: limit_data.LimitData, ) -> limit_data.LimitData: <NEW_LINE> <INDENT> with self.client.pipeline() as p: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> p.watch(key) <NEW_LINE> data = p.hgetall(key) <NEW_LINE> current_data = limit_data.Li...
Perform an atomic compare and swap operation.
625941f45fdd1c0f98dc0851
def grow_synapses(self, col, cell, seg_idx, count): <NEW_LINE> <INDENT> if count <= 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> idx = to_flat_segments(col, cell, seg_idx) <NEW_LINE> idx_toseg = self.seg_linkings[idx] <NEW_LINE> seta = set(self.winners.indices) <NEW_LINE> setb = set(self.seg_matrix.indices[ self.s...
For a given segment, grow up to a number of synapses to winner cells of the previous step.
625941f4bf627c535bc137eb
def testcheckElementInLibrary(self): <NEW_LINE> <INDENT> book1 = PhysicalBook() <NEW_LINE> book1.setISBN(9781503290563) <NEW_LINE> book1.setLibraryUser(None) <NEW_LINE> book1.setDamages('Back cover right corner: scribbled') <NEW_LINE> book1.setBookTitle('Pride and Prejudice') <NEW_LINE> book1.setBookAuthor('Jane Austen...
Checks if resourceX is in the catalogue list.
625941f4d486a94d0b98e763
def _freeze_state(self, pendulum): <NEW_LINE> <INDENT> M = np.array([[pendulum.c_m + pendulum.p_m , pendulum.p_m * pendulum.p_l * math.cos(pendulum.th)], [pendulum.p_m * pendulum.p_l * math.cos(pendulum.th), pendulum.p_j + pendulum.p_m * (pendulum.p_l**2.)]]) <NEW_LINE> N = np.array([[0.0, -pendulum.p_m * pendulum.p_l ...
freeze state Parameters ------------ pendulum : pendulum class
625941f43d592f4c4ed1d678
def goToShop(self, shop): <NEW_LINE> <INDENT> print("Name: " + self.name) <NEW_LINE> shop.printAffordableBikeList(self)
ask shop for the list of affordable bike models
625941f44e696a04525c9a6a
def listify(raw_text, lang="en"): <NEW_LINE> <INDENT> punctuation_to_replace = ["---", "--", "''"] <NEW_LINE> for punctuation in punctuation_to_replace: <NEW_LINE> <INDENT> raw_text = raw_text.replace(punctuation, " ") <NEW_LINE> <DEDENT> words = [x.lower() for x in re.findall( r"(?:[0-9][0-9,\.]*[0-9])|(?:http[s]*://[...
Make a list of words from a string.
625941f47047854f462a1a1e
def __init__(self, *args): <NEW_LINE> <INDENT> this = _engine_internal.new_RegionPair(*args) <NEW_LINE> try: self.this.append(this) <NEW_LINE> except: self.this = this
__init__(self) -> RegionPair __init__(self, __a, __b) -> RegionPair __init__(self, __p) -> RegionPair
625941f4ec188e330fd5adad
def thresholdlevel(self, nfalse=1): <NEW_LINE> <INDENT> import scipy.stats <NEW_LINE> return scipy.stats.norm.isf(nfalse/self.ntrials)
Sigma threshold for a given number of false positives per scan
625941f43cc13d1c6d3c7993
def postorder(T, sequence=None): <NEW_LINE> <INDENT> if sequence == None: <NEW_LINE> <INDENT> sequence = [] <NEW_LINE> <DEDENT> if T == None: <NEW_LINE> <INDENT> return sequence <NEW_LINE> <DEDENT> sequence = postorder(T.l, sequence) <NEW_LINE> sequence = postorder(T.r, sequence) <NEW_LINE> sequence.append(T.x) <NEW_LI...
left-right-root Time: O(num) Space: O(h) where h worst case = num , best/avg case = log num
625941f4099cdd3c635f1274
def quit(bot, event): <NEW_LINE> <INDENT> if _isadmin(event.sender) and event.firstword() == '!quit': <NEW_LINE> <INDENT> bot.quit(event.arguments())
Quit bot using !quit [message]
625941f4f9cc0f698b140c12
def get_hostname_no_domain(): <NEW_LINE> <INDENT> host_name = socket.gethostname().split('.') <NEW_LINE> return host_name[0]
Get the host name of the calling machine. Will not return the domain name with the host name Args: None Returns: A string containing the host name of the calling machine
625941f491f36d47f21acb16
def __init__(self, tile_size): <NEW_LINE> <INDENT> pygame.init() <NEW_LINE> self._tile_size = tile_size <NEW_LINE> self._images = {} <NEW_LINE> self._key_down = None
Initialize view, set grid's tile size in pixels.
625941f423849d37ff7b36a6
def init_hidden(self): <NEW_LINE> <INDENT> hidden = torch.zeros( self.num_layers, self.batch_size, self.hidden_size) <NEW_LINE> return hidden
This is used for the first mini-batch in an epoch, only.
625941f4b5575c28eb68e622
def build(self, **_opts): <NEW_LINE> <INDENT> tgen = get_topogen(self) <NEW_LINE> tgen.add_router("tor1") <NEW_LINE> tgen.add_router("tor2") <NEW_LINE> tgen.add_router("spine1") <NEW_LINE> switch = tgen.add_switch("sw1") <NEW_LINE> switch.add_link(tgen.gears["tor1"]) <NEW_LINE> switch = tgen.add_switch("sw2") <NEW_LINE...
Build function
625941f4fff4ab517eb2fa5d
def post(self, *args, **kwargs): <NEW_LINE> <INDENT> account = self.get_argument("account") <NEW_LINE> passw = self.get_argument("passw") <NEW_LINE> account = account.strip() <NEW_LINE> passw = passw.strip() <NEW_LINE> if passw=='' or account =='': <NEW_LINE> <INDENT> self.render("login_fail.html") <NEW_LINE> <DEDENT> ...
1.0版本不通过outh 认证,通过查询数据库 :param args: :param kwargs: :return:
625941f496565a6dacc8fce5
def get_R_stone_pinv(distance_matrix): <NEW_LINE> <INDENT> D = np.array(distance_matrix) <NEW_LINE> n = len(D) <NEW_LINE> D_pinv = scipy.linalg.pinv(D) <NEW_LINE> ones = np.ones((n, n)) <NEW_LINE> numerator = np.dot(D_pinv, np.dot(ones, D_pinv)) <NEW_LINE> denominator = sum(sum(D_pinv)) <NEW_LINE> R = D_pinv - numerato...
Return a function of the distance matrix (D^-1 - (D^-1)*1*1T*(D^-1)/(1T*D^-1*1)). Directly substitute the pseudoinverse for the inverse. The return value is negative one half of a graph Laplacian. @return: a function of the distance matrix
625941f44a966d76dd551632
def display_current_player(self, num_player): <NEW_LINE> <INDENT> for i, player in enumerate(self.names): <NEW_LINE> <INDENT> self.itemconfig(player, text=self.master.player_names[(num_player+i) % 4]) <NEW_LINE> <DEDENT> for i, score in enumerate(self.scores): <NEW_LINE> <INDENT> self.itemconfig(score, text=self.master...
Affiche les numéros de joueurs en faisant tourner, le joueur courant est toujours en haut à gauche. :param num_player: le numéro du joueur courant :type num_player: int
625941f431939e2706e4d47d
def notMentor(self): <NEW_LINE> <INDENT> self.isProfileActive() <NEW_LINE> if not self.data.mentorFor(self.data.url_ndb_org.key): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> raise exception.Forbidden( message=DEF_ALREADY_MENTOR % self.data.url_ndb_org.name)
Checks if the user is not a mentor.
625941f4c4546d3d9de73056
def get_binning_ce(probs, labels, p=2, debias=True, mode='marginal'): <NEW_LINE> <INDENT> return _get_ce(probs, labels, p, debias, None, binning_scheme=get_discrete_bins, mode=mode)
Estimate the calibration error of a binned model. Args: probs: A torch tensor of shape (n,) or (n, k). If the shape is (n,) then we assume binary classification and probs[i] is the model's confidence the i-th example is 1. Otherwise, probs[i][j] is the model's confidence the i-th example is...
625941f4cc0a2c11143dd4ae
def peekleft(self): <NEW_LINE> <INDENT> if self._doubly_linked_list.size() == 0: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self._doubly_linked_list.head.data
Get value of next node to be popped.
625941f429b78933be1e5cc1
def get_batch(self): <NEW_LINE> <INDENT> batch = self.batches[self.index] <NEW_LINE> self.index += 1 <NEW_LINE> if self.index >= len(self.batches): <NEW_LINE> <INDENT> self.index = 0 <NEW_LINE> self.load_batches() <NEW_LINE> <DEDENT> return np.array(batch)
Returns the next batch. Starts loading the next set of batches into memory if we reach the end
625941f49c8ee82313fbbd94
def create_package(self, infotype, mode, msg): <NEW_LINE> <INDENT> packet = deque((infotype, mode, msg)) <NEW_LINE> return packet
```python input: InfoType, ConnMode, PyObj return: Deque ``` constructs a package from supplied args.
625941f450485f2cf553d3b8
def await_startup(isamAppliance, wait_time=300, check_freq=5, start_time=None, check_mode=False, force=False): <NEW_LINE> <INDENT> if start_time is None: <NEW_LINE> <INDENT> ret_obj = get(isamAppliance) <NEW_LINE> start_time = ret_obj['data'][0]['start_time'] <NEW_LINE> <DEDENT> sec = 0 <NEW_LINE> warnings = [] <NEW_LI...
Wait for appliance to bootup or LMI to restart Checking lmi responding is best option from REST API perspective # Frequency (in seconds) when routine will check if server is up # check_freq (seconds) # Ideally start_time should be taken before restart request is send to LMI # start_time (REST API standard) # Time to...
625941f4b57a9660fec33ea9
def test_dict(self): <NEW_LINE> <INDENT> event_cache = [] <NEW_LINE> class A(HasTraits): <NEW_LINE> <INDENT> x = EventfulDict({c: c for c in 'abc'}) <NEW_LINE> <DEDENT> a = A() <NEW_LINE> a.x.on_events(lambda k, v: event_cache.append('add'), lambda k, v: event_cache.append('set'), lambda k: event_...
Does the EventfulDict work?
625941f43eb6a72ae02ecb0b
def CHECK_FILE(filename): <NEW_LINE> <INDENT> if os.path.isfile(filename): <NEW_LINE> <INDENT> logic = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logic = False <NEW_LINE> <DEDENT> return logic
Author: Nicholas Pike Email : Nicholas.pike@ulg.ac.be Purpose: Checks if the file "filename" exists in the current directory and outputs a boolean value indicating whether or not the file is found.
625941f45510c4643540f9f0
def set_if_greater(self, value: "Player") -> "Player": <NEW_LINE> <INDENT> self.parent.operator = ">" <NEW_LINE> return self.parent.handle_operator(self.name, value)
set_if_greater - Sets the scoreboard player to the value if it is greater than it Args: value (Player): The value to compare against and set if it is greater Returns: str: Command
625941f4004d5f362079a94b
def process_customer_shipments(config): <NEW_LINE> <INDENT> Shipment = Model.get('stock.shipment.out') <NEW_LINE> shipments = Shipment.find([('state', '=', 'waiting')]) <NEW_LINE> shipments = [x.id for x in shipments] <NEW_LINE> shipments = random.sample(shipments, int(0.8 * len(shipments))) <NEW_LINE> for shipment in ...
It randomly processes waiting customer shipments. 20% of existing waiting customer shipments are left in waiting state 80% are tried to be assigned (may not be assigned if stock is not enough) 90% of the assigned ones are packed 90% of the packed ones are done
625941f4c4546d3d9de73057
def n_queens(n): <NEW_LINE> <INDENT> board = [['E']*n for _ in range(n)] <NEW_LINE> num_of_queens = n <NEW_LINE> for i in range(n): <NEW_LINE> <INDENT> board[i][0] = 'Q' <NEW_LINE> helper(board, n,num_of_queens-1, [(i,0)]) <NEW_LINE> board[i][0] = 'E' <NEW_LINE> <DEDENT> printboard(solved_boards)
:type n: int, specifies board size and number of queen to be placed on it
625941f4851cf427c661ab26
def _moodleify_lab(self, path): <NEW_LINE> <INDENT> self._create_steps() <NEW_LINE> for step in self.stepobjects: <NEW_LINE> <INDENT> step.moodleify(path, self.topicpath, self.topic, self.courseid, self.sectionid)
| Configures each step in the Lab for being pushed to Moodle | This involves changing local navigation links to navigation links that will work in the Moodle environment | The moodlyify() method of each step in the lab is invoked | Check the documentation for a description of this method
625941f466656f66f7cbc7c9
def prepare_response( movies, movie_details, outbound_context_name, outbound_context_param): <NEW_LINE> <INDENT> if len(movies) > 0: <NEW_LINE> <INDENT> speech = "I found you the following movies: " + ', '.join(movies) + ". Do you want more?" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> speech = "Sorry, no ...
Helper function that prepares the return object we send to the user given a list of movies.
625941f4cdde0d52a9e53655
def _moog_par_format_plot (driver,plot): <NEW_LINE> <INDENT> if plot is None: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> val = str(plot) <NEW_LINE> if driver == 'synth' and val not in ('1','2'): <NEW_LINE> <INDENT> val = 0 <NEW_LINE> <DEDENT> elif (driver in ('abfind','blends')) and val in ('1','2'): <NEW_LINE> ...
moogpars['plot'] ``` plot 1 ```
625941f499cbb53fe6793201
def filter(self, expr): <NEW_LINE> <INDENT> rv = self._clone(mark_dirty=True) <NEW_LINE> rv._filters = list(self._filters or ()) <NEW_LINE> if callable(expr): <NEW_LINE> <INDENT> expr = _CallbackExpr(expr) <NEW_LINE> <DEDENT> rv._filters.append(expr) <NEW_LINE> return rv
Filters records by an expression.
625941f415fb5d323cde1136
def _list_sgfs(path): <NEW_LINE> <INDENT> _files = os.listdir(path) <NEW_LINE> return (os.path.join(path, f) for f in _files if _is_sgf(f))
helper function to get all SGF files in a directory (does not recurse)
625941f4b5575c28eb68e623
def test_x_gate_deterministic_default_basis_gates(self): <NEW_LINE> <INDENT> shots = 100 <NEW_LINE> circuits = ref_1q_clifford.x_gate_circuits_deterministic(final_measure=True) <NEW_LINE> targets = ref_1q_clifford.x_gate_counts_deterministic(shots) <NEW_LINE> qobj = compile(circuits, self.SIMULATOR, shots=shots) <NEW_L...
Test x-gate circuits compiling to backend default basis_gates.
625941f4460517430c394790
def run_game(): <NEW_LINE> <INDENT> pygame.init() <NEW_LINE> settings = Settings() <NEW_LINE> screen = pygame.display.set_mode( (settings.screen_width, settings.screen_height)) <NEW_LINE> event = pygame.event.poll() <NEW_LINE> pygame.mixer.music.load("music.mp3") <NEW_LINE> pygame.mixer.music.play(3, 0) <NEW_LINE> pyga...
initialize
625941f4287bf620b61d407c
def mul(x, y): <NEW_LINE> <INDENT> if issparse(x): <NEW_LINE> <INDENT> return x.multiply(y) <NEW_LINE> <DEDENT> elif issparse(y): <NEW_LINE> <INDENT> return y.multiply(x) <NEW_LINE> <DEDENT> return mul_dense(x, y)
Element-wise multiplication, dispatched to correct dense or sparse function. Parameters ---------- x : dense or sparse operator First array. y : dense or sparse operator Second array. Returns ------- dense or sparse operator Element wise product of ``x`` and ``y``.
625941f4a17c0f6771cbe66b
def close(self): <NEW_LINE> <INDENT> self.running = False <NEW_LINE> print('agent exited')
Deletes any object no needed any more, close connections, etc
625941f43346ee7daa2b338e
def order_by(*attrs): <NEW_LINE> <INDENT> return OrderBy(attrs, reverse=False)
Return a query ordering operator that will order an instance set based on attribute names passed. When ordering on multiple attributes is specified, the set will be sorted by the first attribute and then within each value of this, by the second attribute and so on. Usage example: >>> from xtuml import order_by >>> m ...
625941f4cad5886f8bd275f4
def __init__(self, language): <NEW_LINE> <INDENT> self.magic_no = 0x497E <NEW_LINE> self.packet_type = 0x0002 <NEW_LINE> self.language_code = language <NEW_LINE> self.year = None <NEW_LINE> self.month = None <NEW_LINE> self.day = None <NEW_LINE> self.hour = None <NEW_LINE> self.minute = None <NEW_LINE> self.length = No...
initialize
625941f4236d856c2ad44e00