code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def test_with_expr_four(self, query_expression_w_joinedload_fixture): <NEW_LINE> <INDENT> User = query_expression_w_joinedload_fixture <NEW_LINE> stmt = ( select(User) .options( with_expression(User.value, null()), joinedload(User.addresses) ) .limit(1) ) <NEW_LINE> self.assert_compile( stmt, "SELECT anon_2.anon_1, ano...
test :ticket:`6259`
625941c950812a4eaa59c3a1
def init_srv(self, srv): <NEW_LINE> <INDENT> if not srv: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.srv = srv <NEW_LINE> symkey = getattr(self.srv, 'symkey', None) <NEW_LINE> if symkey is not None and symkey == "": <NEW_LINE> <INDENT> msg = "CookieDealer.srv.symkey can not be an empty value" <NEW_LINE> raise I...
Make sure the server has the necessary attributes :param srv: A server instance
625941c9b545ff76a8913e95
def __remove_from_playback(self, action, variant): <NEW_LINE> <INDENT> for album in App().player.albums: <NEW_LINE> <INDENT> if album.id == self.__track.album.id: <NEW_LINE> <INDENT> if self.__track.id in album.track_ids: <NEW_LINE> <INDENT> index = album.track_ids.index(self.__track.id) <NEW_LINE> track = album.tracks...
Delete track id from playback @param Gio.SimpleAction @param GLib.Variant
625941c973bcbd0ca4b2c0f5
def test_def_presense(self): <NEW_LINE> <INDENT> test = create_presence() <NEW_LINE> test[TIME] = 1.1 <NEW_LINE> self.assertEqual(test, {ACTION: PRESENCE, TIME: 1.1, USER: {ACCOUNT_NAME: 'Guest'}})
Тест коректного запроса
625941c9379a373c97cfabc3
def subredditsList(request): <NEW_LINE> <INDENT> subs = SubredditsList.objects.all() <NEW_LINE> for sub in subs: <NEW_LINE> <INDENT> print(sub.subreddit) <NEW_LINE> <DEDENT> return HttpResponse()
View the subreddits list in the db set it if it's empty
625941c95fdd1c0f98dc02b2
def is_8bit(char): <NEW_LINE> <INDENT> return ord(char) < 256
Returns True if ord(char) < 256, False otherwise
625941c98c3a873295158439
@pytest.fixture(scope="module") <NEW_LINE> def test_files(tmpdir_factory): <NEW_LINE> <INDENT> tmpdir = tmpdir_factory.mktemp("files") <NEW_LINE> filename1 = osp.join(tmpdir.strpath, 'foo1.py') <NEW_LINE> with open(filename1, 'w') as f: <NEW_LINE> <INDENT> f.write("# -*- coding: utf-8 -*-\n" "def foo:\n" " print(Hel...
Create and save some python codes and text in temporary files.
625941c9287bf620b61d3ae3
def test_depth_buffer_saving(image_test): <NEW_LINE> <INDENT> image_test.create_window(width=800, height=600) <NEW_LINE> image_test.show_triangle_left = True <NEW_LINE> image_test.show_text = False <NEW_LINE> image_test.show_checkerboard = False <NEW_LINE> def step(dt): <NEW_LINE> <INDENT> image_test.save_and_load_dept...
Test depth buffer save. A scene consisting of a single coloured triangle will be rendered. The depth buffer will then be saved to a stream and loaded as a texture. You might see the original scene first for up to several seconds before the depth buffer image appears (because retrieving and saving the image is a slow...
625941c9dc8b845886cb55b3
def update_map(self): <NEW_LINE> <INDENT> for (id,cube) in self.robot.world.light_cubes.items(): <NEW_LINE> <INDENT> self.update_cube(cube) <NEW_LINE> <DEDENT> if self.robot.world.charger: self.update_charger() <NEW_LINE> for face in self.robot.world._faces.values(): <NEW_LINE> <INDENT> if face.face_id == face.updated_...
Called to update the map after every camera image, after object_observed and object_moved events, and just before the path planner runs.
625941c9ec188e330fd5a81f
def is_load_module(self): <NEW_LINE> <INDENT> return self.wants_groups.value
Marks this module as a module that affects the image sets Groups is a load module because it can reorder image sets, but only if grouping is turned on.
625941c97b25080760e394d8
def get_uids_for_roles(nodes, roles): <NEW_LINE> <INDENT> uids = set() <NEW_LINE> if roles == consts.ALL_ROLES: <NEW_LINE> <INDENT> uids.update([n.uid for n in nodes]) <NEW_LINE> <DEDENT> elif roles == consts.MASTER_ROLE: <NEW_LINE> <INDENT> return [consts.MASTER_ROLE] <NEW_LINE> <DEDENT> elif isinstance(roles, list): ...
Returns list of uids for nodes that matches roles :param nodes: list of nodes :param roles: list of roles or consts.ALL_ROLES :returns: list of strings
625941c96fece00bbac2d7bc
def non_existent_wc_target(): <NEW_LINE> <INDENT> non_existent_path = sbox.ospath('non-existent') <NEW_LINE> expected_err = ".*W155010.*" <NEW_LINE> svntest.actions.run_and_verify_svn2(None, expected_err, 1, 'ls', non_existent_path)
non-existent wc target
625941c99f2886367277a90d
def get_intersect(x, y): <NEW_LINE> <INDENT> def py_get_intersect(x, y): <NEW_LINE> <INDENT> inter_mask = np.in1d(x, y) <NEW_LINE> inter_values = x[inter_mask] <NEW_LINE> inter_ids = np.where(inter_mask == True)[0] <NEW_LINE> return inter_ids, inter_values <NEW_LINE> <DEDENT> x = tf.to_int64(x) <NEW_LINE> y = tf.to_int...
Find the intersection of 2 1-D arrays. Args: x: The first Int 1-D Tensor. y: The second Int 1-D Tensor. Returns: inter_ids: The Int 1_D Tensor containing intersection ids. inter_values: The Int 1_D Tensor containing intersection elements.
625941c97047854f462a148a
def mod_bias_hungarian_algorithm(picks, total=6): <NEW_LINE> <INDENT> random.shuffle(picks) <NEW_LINE> matrix = [] <NEW_LINE> for pick in picks: <NEW_LINE> <INDENT> matrix.append(pick.prefs) <NEW_LINE> <DEDENT> m = Munkres() <NEW_LINE> indices = m.compute(matrix) <NEW_LINE> assignments = [None]*(total) <NEW_LINE> for r...
tl;dr Numbers go in, numbers come out. Uses the Hungarian Algorithm, aka Munkres Assignment Algorithm, to assign hosts to slots with maximum respect for preferences: https://en.wikipedia.org/wiki/Hungarian_algorithm
625941c9baa26c4b54cb119f
def import_cmdset(python_path, cmdsetobj, emit_to_obj=None, no_logging=False): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> wanted_cache_key = python_path <NEW_LINE> cmdsetclass = _CACHED_CMDSETS.get(wanted_cache_key, None) <NEW_LINE> errstring = "" <NEW_LINE> if not cmdsetclass: <NEW_LINE> <IN...
This helper function is used by the cmdsethandler to load a cmdset instance from a python module, given a python_path. It's usually accessed through the cmdsethandler's add() and add_default() methods. python_path - This is the full path to the cmdset object. cmdsetobj - the database object/typeclass on which this cmds...
625941c94c3428357757c3a7
def map(self, asp, lo=0, hi=(1<<32)): <NEW_LINE> <INDENT> chunks = [] <NEW_LINE> for slo, shi in self.sections(): <NEW_LINE> <INDENT> if shi <= lo or slo >= hi: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> slo = max(lo, slo) <NEW_LINE> shi = min(hi, shi) <NEW_LINE> m = mem.ByteMem(slo, shi) <NEW_LINE> asp.map(m, sl...
Map a set of S-records into an address space
625941c9ac7a0e7691ed414d
def add_or_modify_control(lines, filename='control'): <NEW_LINE> <INDENT> arglist = list() <NEW_LINE> for line in lines: <NEW_LINE> <INDENT> arglist.append(line.split(' ', 1)[0]) <NEW_LINE> <DEDENT> remove_control(arglist, filename) <NEW_LINE> control_file = read_clean_file(filename) <NEW_LINE> del control_file[-1] <NE...
Adds or modifies lines in control.
625941c9c432627299f04cc4
def init_env_variables(): <NEW_LINE> <INDENT> os.environ['SENDGRID_USERNAME'] = SENDGRID_TEST_USERNAME <NEW_LINE> os.environ['SENDGRID_AUTHENTICATION'] = SENDGRID_TEST_AUTHENTICATION <NEW_LINE> os.environ['MAILGUN_USERNAME'] = MAILGUN_TEST_DOMAIN <NEW_LINE> os.environ['MAILGUN_AUTHENTICATION'] = MAILGUN_TEST_AUTHENTICA...
Initializes environment variables for the supported providers.
625941c997e22403b379d019
def isLinear(self): <NEW_LINE> <INDENT> loc = self.location <NEW_LINE> num = self.numcells <NEW_LINE> for i in range(num): <NEW_LINE> <INDENT> if loc[i][0] != loc[0][0] and loc[i][1] != loc[0][1]: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True
returns True if the cage is linear and False if it is not
625941c97b25080760e394d9
def db_lap(s,l,alpha): <NEW_LINE> <INDENT> return 0.5*(b_lap(s+1,l+1,alpha)+b_lap(s+1,l-1,alpha))-alpha*b_lap(s+1,l,alpha)
Derivative with respect to alpha of the Laplace coefficients. See b_lap. Inputs: s : half integer. In this project, we usually have s=1/2 l : index of the Fourier coefficient alpha : semi-major axis ratio, <1
625941c9d164cc6175782dcc
def __init__(self, parent, request, sshlib): <NEW_LINE> <INDENT> threading.Thread.__init__(self) <NEW_LINE> self.stopEvent = threading.Event() <NEW_LINE> self.__mutex__ = threading.RLock() <NEW_LINE> self.__mutexActionId__ = threading.RLock() <NEW_LINE> self.parent = parent <NEW_LINE> self.request = request <NEW_LINE> ...
Individual socket
625941c94527f215b584c4d7
def foo_key(row): <NEW_LINE> <INDENT> d = row['datestop'][:-4] <NEW_LINE> return d if d else "NA"
row is a dict that contains 'datestop' `datestop` is a string like `1012012` Returns: string "101", e.g. Jan 1, but it doesn't really matter
625941c9fbf16365ca6f6242
def ValidateOptions(self, arg_parse_result): <NEW_LINE> <INDENT> if arg_parse_result.complexity < 1.0 or arg_parse_result.complexity > 2.0: <NEW_LINE> <INDENT> newComplexity = max(min(2.0, arg_parse_result.complexity), 1.0) <NEW_LINE> print >> sys.stderr, "WARNING: complexity %.1f is out of range " "[1.0...
Validate and potentially modifies the parsed arguments return True if the UsdView Process can launch. If a child has overridden ParseOptions, ValidateOptions is an opportunity to move
625941c9adb09d7d5db6c80f
def set_label(self, searchindex_id, event_id, event_type, sketch_id, user_id, label, toggle=False, single_update=True): <NEW_LINE> <INDENT> return
Mock adding a label to an event.
625941c9d8ef3951e32435bc
def pickaxe_description_2(): <NEW_LINE> <INDENT> with open("rooms.json", "r") as json_file: <NEW_LINE> <INDENT> data = json.load(json_file) <NEW_LINE> <DEDENT> description = data["game"][2]["objects"]["pickaxe"]["description"][1] <NEW_LINE> return description
pickaxe description
625941c966656f66f7cbc22a
def plot_text(self, location, text, **kwargs): <NEW_LINE> <INDENT> location = self._handle_location(location) <NEW_LINE> if 'transform' not in kwargs and self.transform: <NEW_LINE> <INDENT> kwargs['transform'] = self.transform <NEW_LINE> <DEDENT> text_collection = self.ax.scattertext(self.x, self.y, text, loc=location,...
At the specified location in the station model plot a collection of text. This specifies that at the offset `location`, the strings in `text` should be plotted. Additional keyword arguments given will be passed onto the actual plotting code; this is useful for specifying things like color or font properties. If some...
625941c94e4d5625662d4458
def info_plugin(self, plugin): <NEW_LINE> <INDENT> self.cu.execute("select name, author, cms, scope, description, " "reference from plugins where name=?", (plugin,)) <NEW_LINE> return self.cu.fetchone()
显示插件信息 :param plugin: string, 插件名 :return: string, 插件信息
625941c98a349b6b435e81f2
def check_key(key_num): <NEW_LINE> <INDENT> if key_num % 26 == 0 or key_num == 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> elif isinstance(key_num, float): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> elif isinstance(key_num, str): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE...
Check if the key value is eligible for encoding or decoding. Parameters ---------- key_num: int The key value that indicates the number of shifts. Returns ------ Boolean If the key value is eligible for encoding or decoding (not neither equal to 0 nor the multuples of 26 nor a float nor a string), return ...
625941c9f8510a7c17cf977b
def _compute_diff_prop(self, k, j, epsilon): <NEW_LINE> <INDENT> dyn = self.parent <NEW_LINE> dgt_eps = (dyn._get_phased_dyn_gen(k) + epsilon*dyn._get_phased_ctrl_dyn_gen(k, j))*dyn.tau[k] <NEW_LINE> if dyn.oper_dtype == Qobj: <NEW_LINE> <INDENT> prop_eps = dgt_eps.expm() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> p...
Calculate the propagator from the current point to a trial point a distance 'epsilon' (change in amplitude) in the direction the given control j in timeslot k Returns the propagator
625941c9b545ff76a8913e96
def test_view_delete(self): <NEW_LINE> <INDENT> with mock.patch.object(User, 'delete') as delete_prop: <NEW_LINE> <INDENT> response = self.client.delete(self.end_point) <NEW_LINE> <DEDENT> self.assertEqual(response.status_code, self.expected_response) <NEW_LINE> self.assertEqual(delete_prop.call_count, self.expected_de...
In this test we will hit _property list endpoint and assert responses.
625941c93346ee7daa2b2dea
def output(self): <NEW_LINE> <INDENT> return luigi.LocalTarget(path='/tmp/transformed-%s.n3' % self.filename)
Returns the target output for this task. In this case, a successful execution of this task will create a file on the local filesystem. :return: the target output for this task. :rtype: object (:py:class:`luigi.target.Target`)
625941c9ff9c53063f47c273
def NameMangler(prefix='', postfix=''): <NEW_LINE> <INDENT> return functools.partial(mangle_name, prefix=prefix, postfix=postfix)
Creates a callable that will mangle a given name with the preset *prefix* and *postfix* given :param prefix: *optional* - defaults to '' - prefix to put at the beginning of the name to mangle it :param postfix: *optional* - defaults to '' - postfix to put at the ending of the name to mangle it :return: a callable that ...
625941c9cb5e8a47e48b7b2b
def get_windows_size(self): <NEW_LINE> <INDENT> windows_size = self.driver.get_window_size() <NEW_LINE> return windows_size
获取屏幕大小
625941c9bde94217f3682e71
def identify(self, text: Union[str, TextIO], **kwargs) -> DetailedResponse: <NEW_LINE> <INDENT> if text is None: <NEW_LINE> <INDENT> raise ValueError('text must be provided') <NEW_LINE> <DEDENT> headers = {} <NEW_LINE> sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V3', operation...
Identify language. Identifies the language of the input text. :param str text: Input text in UTF-8 format. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `Identif...
625941c93539df3088e2e3ca
def readlineAvailable(): <NEW_LINE> <INDENT> return readline._readline is not None
Check if the readline is available. By default it is not in Python default installation on Windows
625941c9293b9510aa2c3316
def removeNthFromEnd(self, head, n): <NEW_LINE> <INDENT> length = 1 <NEW_LINE> node_dict = dict() <NEW_LINE> pointer = head <NEW_LINE> while pointer.next != None and n: <NEW_LINE> <INDENT> length += 1 <NEW_LINE> node_dict[length] = pointer <NEW_LINE> pointer = pointer.next <NEW_LINE> <DEDENT> pos = length - n + 1 <NEW_...
:type head: ListNode :type n: int :rtype: ListNode Examples: >>> s = Solution() >>> head = ListNode(1) >>> t, i = head, 2 >>> while i != 6: ... node = ListNode(i) ... t.next, t = node, node ... i += 1 ... >>> t = head >>> while t != None: ... print(t.val, en...
625941c9167d2b6e31218c15
def download_images_to_dir(self, images, save_directory): <NEW_LINE> <INDENT> num_images = len(images) <NEW_LINE> for i, (url, image_type) in enumerate(images): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> logger.info("Making request (%d/%d): %s", i, num_images, url) <NEW_LINE> raw_image = self._get_raw_image(url) <NEW...
Download a set of image urls to disk Args: images (list of tuples): List of images urls and image types. save_directory (str): Folder. Examples: >>> client = ImageDownloader() >>> with TemporaryDirectory() as td: ... r = [("https://raw.githubusercontent.com/miguelgfierro/pybase/master/share/Le...
625941c963d6d428bbe4456f
def get_classes(self): <NEW_LINE> <INDENT> characters = string.digits + string.ascii_uppercase + string.ascii_lowercase <NEW_LINE> num_classes = len(characters) <NEW_LINE> labels_dict = dict() <NEW_LINE> for i in range(len(characters)): <NEW_LINE> <INDENT> self.id2char[i + 1] = characters[i] <NEW_LINE> zeros = np.zeros...
Returns the number of classes and an array with all the characters.
625941c9099cdd3c635f0cdb
def getValue(self): <NEW_LINE> <INDENT> status = self._initGpio() <NEW_LINE> if status == _EXIT_SUCCESS: <NEW_LINE> <INDENT> gpioFile = self.path + '/' + GPIO_VALUE_FILE <NEW_LINE> value = 0 <NEW_LINE> with open(gpioFile, 'r') as fd: <NEW_LINE> <INDENT> value = fd.read() <NEW_LINE> fd.close() <NEW_LINE> <DEDENT> status...
Read current GPIO value
625941c98a43f66fc4b540e6
def __str__(self): <NEW_LINE> <INDENT> if self.is_set: <NEW_LINE> <INDENT> if self._comment: <NEW_LINE> <INDENT> return (f"{self.checked_target}: {self._check_name}: " f"{self._verdict.value}: {self._comment}") <NEW_LINE> <DEDENT> return (f"{self.checked_target}: {self._check_name}: " f"{self._verdict.value}") <NEW_LIN...
String representation of the single check
625941c9498bea3a759b9b2f
def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, OrderedList) and self.head == other.head and self.tail == other.tail and self.num_items == other.num_items
Returns if 2 Ordered list are equivalent to each other
625941c930c21e258bdfa51c
def getShortCurrentFile(self): <NEW_LINE> <INDENT> return QFileInfo(self.curFile).fileName()
TOWRITE :rtype: QString
625941c930bbd722463cbe45
def push_link(self, uri, parent, expected=None): <NEW_LINE> <INDENT> if parent is None: <NEW_LINE> <INDENT> self.push(createTransaction(uri, 0, -1, 'GET', dict(), expected), None) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> t = createTransaction(uri, parent.depth + 1, parent.idno, 'GET', dict(), expected) <NEW_LINE> ...
Push link into queue. Transactions are created, proper Referer header is set.
625941c9167d2b6e31218c16
def sql(self, context=None): <NEW_LINE> <INDENT> return "{} {}".format(self.fieldref.sql(context=context), self.collation)
Render me as an SQL expression
625941c994891a1f4081bb29
def __init__(self, app): <NEW_LINE> <INDENT> self.parse_args() <NEW_LINE> self.app = app <NEW_LINE> self.daemon_context = DaemonContext() <NEW_LINE> self.daemon_context.stdout = open(app.stdout_path, 'a+') <NEW_LINE> self.daemon_context.stderr = open(app.stderr_path, 'a+') <NEW_LINE> self.pidfile = None <NEW_LINE> if a...
Set up the parameters of a new runner. The `app` argument must have the following attributes: * `stdin_path`, `stdout_path`, `stderr_path`: Filesystem paths to open and replace the existing `sys.stdin`, `sys.stdout`, `sys.stderr`. * `pidfile_path`: Absolute filesystem path to a file that will be used as the PI...
625941c94e696a04525c94cb
def write_architecture(file_ptr, pp_list, exp_prime): <NEW_LINE> <INDENT> file_ptr.write("architecture behavioral of mod_mul is\n\n") <NEW_LINE> write_dsp_component(file_ptr) <NEW_LINE> signal_list = write_signal_declaration(file_ptr, pp_list, len(pp_list)) <NEW_LINE> file_ptr.write("\t begin\n\n") <NEW_LINE> write_gen...
Declare architecture in VHDL code.
625941c95f7d997b87174b17
def _teacher_action(self, obs, ended): <NEW_LINE> <INDENT> a = np.zeros(len(obs), dtype=np.int64) <NEW_LINE> for i, ob in enumerate(obs): <NEW_LINE> <INDENT> if ended[i]: <NEW_LINE> <INDENT> a[i] = args.ignoreid <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for k, candidate in enumerate(ob['candidate']): <NEW_LINE> <IN...
Extract teacher actions into variable. :param obs: The observation. :param ended: Whether the action seq is ended :return:
625941c94428ac0f6e5ba872
def eclean_pkg( destructive=False, package_names=False, time_limit=0, exclude_file="/etc/eclean/packages.exclude", ): <NEW_LINE> <INDENT> if exclude_file is None: <NEW_LINE> <INDENT> exclude = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> exclude = _parse_exclude(exclude_file) <NEW_LINE> <...
Clean obsolete binary packages destructive Only keep minimum for reinstallation package_names Protect all versions of installed packages. Only meaningful if used with destructive=True time_limit <time> Don't delete distfiles files modified since <time> <time> is an amount of time: "1y" is "one ye...
625941c991af0d3eaac9ba98
def test_packager_acl(self): <NEW_LINE> <INDENT> output = self.app.get('/api/packager/acl/') <NEW_LINE> self.assertEqual(output.status_code, 500) <NEW_LINE> data = json.loads(output.data) <NEW_LINE> self.assertEqual( data, { "output": "notok", "error": "Invalid request", } ) <NEW_LINE> output = self.app.get('/api/packa...
Test the api_packager_acl function.
625941c92ae34c7f2600d1b1
def get_proficiency_admin_session(self): <NEW_LINE> <INDENT> if not self.supports_proficiency_admin(): <NEW_LINE> <INDENT> raise errors.Unimplemented() <NEW_LINE> <DEDENT> return sessions.ProficiencyAdminSession(runtime=self._runtime)
Gets the ``OsidSession`` associated with the proficiency administration service. return: (osid.learning.ProficiencyAdminSession) - a ``ProficiencyAdminSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_proficiency_admin()`` is ``false`` *compliance: optio...
625941c9009cb60464c63432
def example13(): <NEW_LINE> <INDENT> def f(x, y): <NEW_LINE> <INDENT> return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2) <NEW_LINE> <DEDENT> n = 10 <NEW_LINE> x = np.linspace(-3, 3, 4*n) <NEW_LINE> y = np.linspace(-3, 3, 4*n) <NEW_LINE> X , Y = np.meshgrid(x, y) <NEW_LINE> plt.imshow(f(X,Y)) <NEW_LINE> plt...
imshow
625941c9a934411ee3751714
def seek(self, position): <NEW_LINE> <INDENT> if self.locked or self._current_track.id is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if position >= self._current_track.duration: <NEW_LINE> <INDENT> self.next() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._playbin.seek_simple(Gst.Format.TIME, Gst.SeekFla...
Seek current track to position @param position as seconds
625941c93617ad0b5ed67f78
def __getattr__(self, name): <NEW_LINE> <INDENT> if name in TIFF.FRAME_ATTRS: <NEW_LINE> <INDENT> return getattr(self.keyframe, name) <NEW_LINE> <DEDENT> raise AttributeError("'%s' object has no attribute '%s'" % (self.__class__.__name__, name))
Return attribute from keyframe.
625941c95fcc89381b1e173e
def create_image_lists(image_dir, testing_percentage, validation_percentage): <NEW_LINE> <INDENT> if not os.path.exists(image_dir): <NEW_LINE> <INDENT> logger.error("Image directory '" + image_dir + "' not found.") <NEW_LINE> return None <NEW_LINE> <DEDENT> result = {} <NEW_LINE> sub_dirs = [os.path.basename(x) for x i...
Builds a list of training images from the file system. Analyzes the sub folders in the image directory, splits them into stable training, testing, and validation sets, and returns a data structure describing the lists of images for each label and their paths. Args: image_dir: String path to a folder containing subf...
625941c985dfad0860c3aedb
def _remove_job(self, id_): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> del self.status[id_] <NEW_LINE> if id_ in self.config: <NEW_LINE> <INDENT> del self.config[id_] <NEW_LINE> <DEDENT> if id_ in self.sched: <NEW_LINE> <INDENT> del self.sched[id_] <NEW_LINE> <DEDENT> if id_ in self.last_start: <NEW_LINE> <INDENT> de...
Removes a job from the instance data structures.
625941c9851cf427c661a590
def execute(self): <NEW_LINE> <INDENT> with self.report.add_entry(ip="192.168.42.235", domain="Global", offline=True) as entry: <NEW_LINE> <INDENT> entry.snmp_community = "Cisco" <NEW_LINE> entry.sys_object_id = "-" <NEW_LINE> entry.description = "-" <NEW_LINE> entry.vendor = "-" <NEW_LINE> entry.model_type = "switch" ...
Execute echo report file command :return:
625941c992d797404e30420a
def ao_server_msg(self, msg_text, readable_socket): <NEW_LINE> <INDENT> return
Function called "ActionsOn_server_msg" This could be used for cross-server communication, site transfers etc.
625941c98c0ade5d55d3ea3b
def sort_population(individuals: List[Individual]) -> List[Individual]: <NEW_LINE> <INDENT> individuals = sorted(individuals, key=lambda x: x.fitness, reverse=True) <NEW_LINE> return individuals
Return a list sorted on the fitness value of the individuals in the population. Descending order. :param individuals: The population of individuals :type individuals: list :return: Population of individuals sorted by fitness in descending order :rtype: list
625941c90c0af96317bb8268
def save_confusion_matrix(y_target, y_predictions, labels, figure_path, figure_size=(20,20)): <NEW_LINE> <INDENT> cnf_matrix = confusion_matrix(y_target, y_predictions) <NEW_LINE> plt.figure(figsize=figure_size) <NEW_LINE> plot_confusion_matrix(cnf_matrix, classes=labels, title='Confusion matrix, without normalization'...
Generate two confusion matrices plots: with and without normalization. :param y_target: Tags groud truth :param y_predictions: Tags predictions :param labels: Predictions classes to use :param figure_path: Path the save figures :param figure_size: Size of the generated figures :return: Nothing
625941c94f88993c3716c0e8
def Files(self): <NEW_LINE> <INDENT> file_list = self.GetListFile() <NEW_LINE> if not os.path.exists(file_list): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> with open(self.GetListFile()) as f: <NEW_LINE> <INDENT> for line in f: <NEW_LINE> <INDENT> yield line.strip()
Yields the list of files currently installed by this package.
625941c9be383301e01b5507
def get_ns_variable(self, var_id, ns): <NEW_LINE> <INDENT> config_name = self.util.split_full_ns(self.data, ns)[0] <NEW_LINE> config_data = self.data.config[config_name] <NEW_LINE> sect, opt = self.util.get_section_option_from_id(var_id) <NEW_LINE> var = config_data.vars.get_var(sect, opt) <NEW_LINE> if var is None: <N...
Return a variable with this id in the config specified by ns.
625941c9442bda511e8be49a
def longestCommonPrefix(self, strs): <NEW_LINE> <INDENT> if len(set(strs)) >= 2: <NEW_LINE> <INDENT> final = '' <NEW_LINE> len_list = [] <NEW_LINE> pre_list = [''] * len(strs) <NEW_LINE> for i, val in enumerate(strs): <NEW_LINE> <INDENT> len_list.append(len(val)) <NEW_LINE> <DEDENT> min_length = min(len_list) <NEW_LINE...
:type strs: List[str] :rtype: str
625941c9a17c0f6771cbe0d1
def send_sms(from_email, from_pass, to_email_list, msg): <NEW_LINE> <INDENT> import smtplib <NEW_LINE> if not isinstance(from_email, str): <NEW_LINE> <INDENT> raise ValueError('Argument {} not a string'.format(from_email)) <NEW_LINE> <DEDENT> if not isinstance(from_pass, str): <NEW_LINE> <INDENT> raise ValueError('Argu...
To send sms using email send_sms(from_email, from_pass, to_email_list, msg) from_email: Email from which emails for sms are send from_pass: Passwork of email from which emails for sms are send to_email_list: list of mobile numbers with appropriate email extension for example, '1234567890@@mms.att.net' m...
625941c907f4c71912b11502
def vector_insert2_make(data, periodicity, offset): <NEW_LINE> <INDENT> return _cdma_swig.vector_insert2_make(data, periodicity, offset)
vector_insert2_make(pmt_vector_cfloat data, int periodicity, int offset) -> vector_insert2_sptr Return a shared_ptr to a new instance of cdma::vector_insert2. To avoid accidental use of raw pointers, cdma::vector_insert2's constructor is in a private implementation class. cdma::vector_insert2::make is the public inte...
625941c92ae34c7f2600d1b2
def add_additional_metadata(self, data): <NEW_LINE> <INDENT> data['org_units'] = [ queryMultiAdapter((org_unit, self.request), ISerializeToJson)() for org_unit in self.context.org_units]
Add list of org_units summaries
625941c95166f23b2e1a51da
def unbound_method(method): <NEW_LINE> <INDENT> return getattr(method.__self__.__class__, method.__name__)
Returns ------- function Unbounded function.
625941c957b8e32f5248351b
def pftas(img, T=None): <NEW_LINE> <INDENT> if T is None: <NEW_LINE> <INDENT> T = otsu(img) <NEW_LINE> <DEDENT> pixels = img[img > T].ravel() <NEW_LINE> std = pixels.std() <NEW_LINE> return _tas(img, T, std)
values = pftas(img, T={mahotas.threshold.otsu(img)}) Compute parameter free Threshold Adjacency Statistics TAS were presented by Hamilton et al. in "Fast automated cell phenotype image classification" (http://www.biomedcentral.com/1471-2105/8/110) The current version is an adapted version which is free of parameter...
625941c9dd821e528d63b22a
def remove_mockcache(connection_name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> mockcache_dir = get_mockcache_dir(connection_name) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> file_list = glob.glob(os.path.join(mockcache_dir, '*')) <NEW_LINE> for _file in file_list: <NEW_LIN...
Remove mock cache for a connection name.
625941c90c0af96317bb8269
def get_name(prompt): <NEW_LINE> <INDENT> wrong_name = True <NEW_LINE> name = "" <NEW_LINE> while wrong_name: <NEW_LINE> <INDENT> name = input(prompt) <NEW_LINE> if len(name) == 0 or name.isdecimal(): <NEW_LINE> <INDENT> wrong_name = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> wrong_name = False <NEW_LINE> <DEDE...
Gets a name from the console. Get a name from the console input. If it's doesn't pass check, try again. Returns a valid name or an empty string
625941c90383005118ecf663
def dict_to_duration(time_dict: Optional[Dict[str, int]]) -> Duration: <NEW_LINE> <INDENT> if time_dict: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if (Duration(seconds=time_dict['sec'], nanoseconds=time_dict['nsec']) < Duration(seconds=0)): <NEW_LINE> <INDENT> raise ValueError('Time duration may not be a negative va...
Convert a QoS duration profile from YAML into an rclpy Duration.
625941c907d97122c417890a
def get_cli_event_returns( self, jid, minions, timeout=None, tgt='*', tgt_type='glob', verbose=False, progress=False, show_timeout=False, show_jid=False, **kwargs): <NEW_LINE> <INDENT> log.trace('func get_cli_event_returns()') <NEW_LINE> if 'expr_form' in kwargs: <NEW_LINE> <INDENT> salt.utils.warn_until( 'Fluorine', '...
Get the returns for the command line interface via the event system
625941c963f4b57ef000119c
def initialize_conditions(segment): <NEW_LINE> <INDENT> climb_rate = segment.climb_rate <NEW_LINE> alt0 = segment.altitude_start <NEW_LINE> altf = segment.altitude_end <NEW_LINE> t_nondim = segment.state.numerics.dimensionless.control_points <NEW_LINE> t_initial = segment.state.conditions.frames.inertial...
Sets the specified conditions which are given for the segment type. Assumptions: Climb segment with a constant rate of climb. Source: N/A Inputs: segment.altitude_start [meters] segment.altitude_end [meters] segment.climb_rate ...
625941c9be383301e01b5508
def test_contact_form_invalid_subject(self): <NEW_LINE> <INDENT> form = ContactForm({ 'email': 'test@email.com', 'subject': '', 'message': 'test message' }) <NEW_LINE> self.assertFalse(form.is_valid())
Test full working contact form
625941c950812a4eaa59c3a3
def qualifiedModelName(model): <NEW_LINE> <INDENT> return '.'.join([model.__module__,modelName(model)])
Return the long model name with the module included
625941c9a05bb46b383ec8a3
def _generate_wave_table( wave_type: str, data_type: str, table_size: int, min: float, max: float, phase: float, device: torch.device, ) -> Tensor: <NEW_LINE> <INDENT> phase_offset = int(phase / math.pi / 2 * table_size + 0.5) <NEW_LINE> t = torch.arange(table_size, device=device, dtype=torch.int32) <NEW_LINE> point = ...
A helper fucntion for phaser. Generates a table with given parameters Args: wave_type (str): SINE or TRIANGULAR data_type (str): desired data_type ( `INT` or `FLOAT` ) table_size (int): desired table size min (float): desired min value max (float): desired max value phase (float): desired phase...
625941c9bde94217f3682e72
def bot_init(self): <NEW_LINE> <INDENT> self.config['api_key'] = keys.consumer_key <NEW_LINE> self.config['api_secret'] = keys.consumer_secret <NEW_LINE> self.config['access_key'] = keys.access_token <NEW_LINE> self.config['access_secret'] = keys.access_token_secret <NEW_LINE> self.config['tweet_interval_range'] = (5*6...
Initialize and configure your bot! Use this function to set options and initialize your own custom bot state (if any).
625941c973bcbd0ca4b2c0f7
def test_unitless_no_vTh(self): <NEW_LINE> <INDENT> T_e = self.T_e.to(u.K, equivalencies=u.temperature_energy()) <NEW_LINE> T_e = T_e.si.value <NEW_LINE> distFunc = Maxwellian_1D(v=self.v.si.value, T=T_e, particle=self.particle, units="unitless") <NEW_LINE> errStr = (f"Distribution function should be {self.distFuncTrue...
Tests distribution function without units, and not passing vTh.
625941c926068e7796caed5e
def __get_s3_latest_policy_file(self, policy: str): <NEW_LINE> <INDENT> return self.__s3_operation.get_last_objects(bucket=self.__bucket, logs_bucket_key=f'{self.__logs_bucket_key}/{self.__region}', policy=policy)
This method return latest policy logs @param policy: @return:
625941c9aad79263cf390ac1
def test__get_tunable_condition_match_null(self): <NEW_LINE> <INDENT> init_params = { 'a_condition': 'a_match' } <NEW_LINE> hyperparameters = { 'tunable': { 'this_is_not_conditional': { 'type': 'int', 'default': 1, 'range': [1, 10] }, 'this_is_conditional': { 'type': 'conditional', 'condition': 'a_condition', 'default'...
If there is a match and it is null (None), this param is not included. This stands even if the default is not null.
625941c96fb2d068a760f11d
def test_normalise_slug_known_bad(self): <NEW_LINE> <INDENT> known_bad_slug = "This is a completely invalid slug :/?#[]@!$&'()*+,;=" <NEW_LINE> expected = 'this-is-a-completely-invalid-slug' <NEW_LINE> new_slug = utils.normalise_slug(known_bad_slug) <NEW_LINE> self.assertEqual(new_slug, expected)
normalise_slug correctly normalises known bad slug
625941c95fdd1c0f98dc02b4
def populate(count): <NEW_LINE> <INDENT> population = [] <NEW_LINE> available_indexes = [] <NEW_LINE> for _ in range(0,count): <NEW_LINE> <INDENT> indexes_list = [] <NEW_LINE> available_indexes = list(range(len(cities))) <NEW_LINE> while (len(available_indexes) > 0): <NEW_LINE> <INDENT> index = random.randrange(0, len(...
Crée une population de n individus selon la liste de ville auparavant déterminée
625941c9004d5f362079a3b4
def test_EvalInlineSourceExpression_match(self): <NEW_LINE> <INDENT> srcExprEval = SourceExpression.UNSAFE_EVAL() <NEW_LINE> srcExprInline = SourceExpression.UNSAFE_INLINE() <NEW_LINE> selfURI = SourceExpressionTest.uri_chromeExtension <NEW_LINE> assert not srcExprEval.matches(SourceExpressionTest.uri_empty, selfURI) <...
The source expressions 'unsafe-inline' and 'unsafe-eval' do not match any URI.
625941c92c8b7c6e89b35842
def get_team_by_seed(self, seed): <NEW_LINE> <INDENT> Misc.check_input_data("Kaggle", "tourney_seeds") <NEW_LINE> df = Constants.INPUT_DATA['Kaggle']['tourney_seeds'] <NEW_LINE> team_df = df[(df.season == self.season_id) & (df.seed == seed)] <NEW_LINE> if not team_df.empty: <NEW_LINE> <INDENT> team_id = team_df.team.il...
:method: Get team object from tournament seed string. :param string seed: tournament seed string :returns: Team object :rtype: object
625941c9460517430c394208
def set_home(self, x=None, y=None, **kwargs): <NEW_LINE> <INDENT> args = self._format_args(x, y, kwargs) <NEW_LINE> self.write('G92 ' + args) <NEW_LINE> self._update_current_position(mode='absolute', x=x, y=y, **kwargs)
Set the current position to the given position without moving. Example ------- >>> # set the current position to X=0, Y=0 >>> g.set_home(0, 0)
625941c99f2886367277a90f
def encode_tuple(r,s): <NEW_LINE> <INDENT> R = crypturd.int2bigendian(r) <NEW_LINE> S = crypturd.int2bigendian(s) <NEW_LINE> return chr(len(R))+R+S
Encode pair of integers as a string
625941c9283ffb24f3c55983
def __repr__(self): <NEW_LINE> <INDENT> str_list = [] <NEW_LINE> for key, val in self._p2v.items(): <NEW_LINE> <INDENT> str_list.append("{k}: {v},".format(k=key, v=val)) <NEW_LINE> <DEDENT> if str_list: <NEW_LINE> <INDENT> str_list[-1] = str_list[-1][:-1] <NEW_LINE> <DEDENT> return "Layout({\n" + "\n".join(str_list) + ...
Representation of a Layout
625941c930dc7b76659019e8
def test_user_has_all_perms_on_model(self): <NEW_LINE> <INDENT> group0 = self.test_save('TestGroup0', user0) <NEW_LINE> group1 = self.test_save('TestGroup1', user1) <NEW_LINE> object2 = TestModel.objects.create() <NEW_LINE> object2.save() <NEW_LINE> object3 = TestModel.objects.create() <NEW_LINE> object3.save() <NEW_LI...
Test checking if a user has all of the perms on any instance of the model
625941c997e22403b379d01a
def get_user_class(source): <NEW_LINE> <INDENT> raise Exception("User class for source %s not found" % source)
Return User Class for a given source Generic method (from peak). Authentication system implements this method. In: - ``source`` -- login source (i.e application, google...) Return: - the user class
625941c9462c4b4f79d1d752
def check_for_win(board, win_rows, player_mark, game_status): <NEW_LINE> <INDENT> row_list = [] <NEW_LINE> for row in win_rows: <NEW_LINE> <INDENT> for s in row: <NEW_LINE> <INDENT> row_list.append(board[s]) <NEW_LINE> <DEDENT> if row_list.count(player_mark) == 3: <NEW_LINE> <INDENT> game_status = 'player_win' <NEW_LIN...
Checks to see if a winning row is present
625941c9009cb60464c63433
def generateKeys(self): <NEW_LINE> <INDENT> p = self.prime_number() <NEW_LINE> q = self.prime_number() <NEW_LINE> fn = (p - 1) * (q - 1) <NEW_LINE> e = random.randint(1, fn) <NEW_LINE> n = p * q <NEW_LINE> d = self.modinv(e, fn) <NEW_LINE> if d is not None and d > e: <NEW_LINE> <INDENT> publicKey = [e, n] <NEW_LINE> pr...
Generate and display the keys
625941c98a349b6b435e81f4
@contextlib.contextmanager <NEW_LINE> def stdout_display(): <NEW_LINE> <INDENT> yield SmartBuffer(sys.stdout)
Print results straight to stdout
625941c9a4f1c619b28b00bc
def samtools_view(sam_file): <NEW_LINE> <INDENT> bam_file = '{}.bam'.format(sam_file.split('.sam')[0]) <NEW_LINE> command_list = ['samtools', 'view', '-Suh', sam_file, '|', 'samtools', 'sort', '-@6', '-o', bam_file, '-'] <NEW_LINE> command = ' '.join(command_list) <NEW_LINE> subprocess.call(command, shell=True)
Samtools view command and process
625941c971ff763f4b54970b
def copyPatchTreeToDest(self, src, dst): <NEW_LINE> <INDENT> log.info('Patching: now in %s', src) <NEW_LINE> names = os.listdir(src) <NEW_LINE> errors = [] <NEW_LINE> for name in names: <NEW_LINE> <INDENT> srcname = os.path.join(src, name) <NEW_LINE> dstname = os.path.join(dst, name) <NEW_LINE> try: <NEW_LINE> <INDENT>...
Patch a tarball build with alternate files as required. At this stage do not allow new directories to be made or new files to be added, just replace existing files.
625941c90a50d4780f666f13
def test_variables_dont_raise_warning(model, caplog): <NEW_LINE> <INDENT> caplog.set_level(logging.WARNING) <NEW_LINE> DecayLROnPlateau(model=model, decay_type='multiply', long_term=4, short_term=3) <NEW_LINE> assert caplog.record_tuples == []
Test if initialization of ``DecayLROnPlateau`` does not raise warnings for variables that are specific for parent hooks only (not shared among both). See emloop issue #14 for more details.
625941c93346ee7daa2b2dec
def __miner_set_gas_price(self, gas_price): <NEW_LINE> <INDENT> return [format_quantity(gas_price)]
https://github.com/ethereum/go-ethereum/wiki/Management-APIs#miner_setgasprice Geth only. :param gas_price: gas price for each paid gas.
625941c95f7d997b87174b18
def render_to_bytes(self, url): <NEW_LINE> <INDENT> format = self.format <NEW_LINE> image = self.render(url) <NEW_LINE> qBuffer = QBuffer() <NEW_LINE> image.save(qBuffer, format) <NEW_LINE> return qBuffer.buffer().data()
Renders the image into an object of type 'str'
625941c9ff9c53063f47c275
def onetime_cal(args): <NEW_LINE> <INDENT> data, data_week, found_date, date = args <NEW_LINE> timeranges = [[5, 0, 0], [3, 0, 0], [2, 0, 0], [1, 0, 0], [0, 6, 0], [0, 3, 0], [0, 2, 0], [0, 1, 0], [0, 0, 1]] <NEW_LINE> info = map(bione_cal, map(lambda x: (x[0], x[1], x[2], date, found_date, data, data_week), timeranges...
计算单个基金在一个时间点,过往不同时间段相关指标。 时间段包括:past 5 years, 3 years, 2 years, 1 years, 6 months, 3 months, 2 months, 1 months, 1 weeks
625941c9dc8b845886cb55b6
def echo(data): <NEW_LINE> <INDENT> data = re.sub(r'(^\s*.*?):(\s)', r'\033[38;5;12m\1\033[38;5;11m:\033[0m\2', data, flags=re.MULTILINE) <NEW_LINE> data = re.sub(r'(^\s*-\s)', r'\033[38;5;9m\1\033[0m', data, flags=re.MULTILINE) <NEW_LINE> os.environ['LESS'] = os.environ.get('LESS', 'FRX') <NEW_LINE> click.echo_via_pag...
Print data to stdout or via a pager if it doesn't fit on screen.
625941c9a79ad161976cc1c7
def test_get_attributes(self): <NEW_LINE> <INDENT> from vertex import Vertex <NEW_LINE> v = Vertex("Student", "Bryant Collaguazo", 21, 2019) <NEW_LINE> self.assertEqual(v.get_group(), "Student") <NEW_LINE> self.assertEqual(v.get_key(), "Bryant Collaguazo") <NEW_LINE> self.assertEqual(v.get_value1(), 21) <NEW_LINE> self...
Check if attributes are being properly stored inside the vertex :return: None
625941c93539df3088e2e3cc
def __fromPersonToDict(self, person): <NEW_LINE> <INDENT> return {_ID_KEY : person.getCPF(), _NAME_KEY : person.getName(), _ALLOWED_ROOMS_KEY : list(person.getAllowedRooms()), _IDENTIFICATIONS_KEY : [_id.toDict() for _id in person.getIDs()] }
Converts a Person object to a dict, so it can be saved on the database. @param self: The Person DAO object instance. @param person: The Person object instance.
625941c9956e5f7376d70eef