code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def open_policy_text(self): <NEW_LINE> <INDENT> self.q(css='#policy-dropdown-link').click() <NEW_LINE> self.wait_for_element_visibility( '#consent-policy', "wait for policy text" ) | Click on the policy link to open policy text | 625941dca05bb46b383ecb27 |
def mk_page_url_path(self): <NEW_LINE> <INDENT> return '{}/accounts/{}/deviceprofiles?pageNo={}&pageSize={}' | :return: | 625941dc1b99ca400220adba |
def qstat(logger=None): <NEW_LINE> <INDENT> if logger is None: <NEW_LINE> <INDENT> logger = _get_null_logger() <NEW_LINE> <DEDENT> stdout, _, returncode = run_cli_cmd(["qstat"], attempts=3, interval=30, logger=logger, timeout=30) <NEW_LINE> if returncode != 0: <NEW_LINE> <INDENT> logger.warning("qstat returned %s: If G... | Return a mapping of job ids to a dict of GE information about each job.
If qstat hangs or returns an error, wait 30 sec and call it again. Do this
three times. If the final attempt returns an error, log it, and return an
empty dictionary, which is the same behavior you'd get if all known jobs
had exited. (If qstat is ... | 625941dcd268445f265b5176 |
def formata_all_media(Model=None): <NEW_LINE> <INDENT> logger.warning("You are using formata_all_media function which is marked " "as DEPRECATED. Please use Celery instead.") <NEW_LINE> from social_layer.mediautils.utils import format_media <NEW_LINE> list_media = Model.objects.filter(formated=False) <NEW_LINE> for pos... | Manipulate media files as needed
Will need to use this if you don't want to use celery
DEPRECATED This will be deprecated in a future release. | 625941dc82261d6c526ab7ab |
def _BINARY_to_python(self, ctx): <NEW_LINE> <INDENT> return lambda value: ctx['fmt'].format(binary_to_python(value)) | BINARY to a string formatted by BINARY_OUTPUT_FORMAT. | 625941dc66673b3332b92399 |
def extract_relations(self, relation_rows: Iterator[Tuple[Cell, ...]]) -> None: <NEW_LINE> <INDENT> header = [cell.value for cell in next(relation_rows)] <NEW_LINE> stmts = [] <NEW_LINE> for row in relation_rows: <NEW_LINE> <INDENT> row_values = [r.value for r in row] <NEW_LINE> row_dict = {h: v for h, v in zip(header,... | Extract Influence statements from relation events
Parameters
----------
relation_rows :
The extracted relation data from an Excel document | 625941dc2eb69b55b151cbba |
def match(self, record, action=None): <NEW_LINE> <INDENT> return False | Do something with the Record passed with a new service, new info about a service or a removed one.
return True to have the Record stored in the service index
return false to let other filters decide | 625941dc7d43ff24873a2faa |
def testApiMethods(self): <NEW_LINE> <INDENT> self.assertType(mainpage.get(), unicode) <NEW_LINE> self.assertType(maintalk.get(), unicode) <NEW_LINE> self.assertRaises(pywikibot.NoPage, badpage.get) <NEW_LINE> self.assertType(mainpage.latestRevision(), int) <NEW_LINE> self.assertType(mainpage.userName(), unicode) <NEW_... | Test various methods that rely on API. | 625941dc566aa707497f486d |
def hexint_aligned(s): <NEW_LINE> <INDENT> i = hexint(s) <NEW_LINE> if i & 3: <NEW_LINE> <INDENT> raise UsageError("Value must be word aligned: %x" % i) <NEW_LINE> <DEDENT> return i | A hexint() that must be word aligned | 625941dc379a373c97cfae4e |
def _registerEvents(self): <NEW_LINE> <INDENT> self.ctrl.onUpdateTags(self.recreateTagsList) <NEW_LINE> self.ctrl.onUpdateAvailableMetatags(self.updateMetatagSelector) <NEW_LINE> self.ctrl.onUpdateAvailableTags(self.updateTagsList) <NEW_LINE> self.ctrl.onUpdateFiles(self.updateFilesList) <NEW_LINE> self.ctrl.onUpdateUs... | Register the event listeners on the controller. | 625941dc63d6d428bbe447f8 |
def keywords_as_dictEnum(**kwargs): <NEW_LINE> <INDENT> print("the number of elements in the dict is: ", len(kwargs)) <NEW_LINE> for k in kwargs.items(): <NEW_LINE> <INDENT> print(k) | Returns the keyword arguments as a dict but using an enumerator | 625941dc44b2445a3393239c |
def get_baseband_version(self): <NEW_LINE> <INDENT> raise DeviceException(DeviceException.FEATURE_NOT_IMPLEMENTED) | Get the Baseband Version of the device.
(Modem sw release)
:rtype: str
:return: Baseband Version | 625941dc4d74a7450ccd44cc |
def postorderHelper(self, root,l): <NEW_LINE> <INDENT> if(root != None): <NEW_LINE> <INDENT> self.postorderHelper(root.left,l) <NEW_LINE> self.postorderHelper(root.right,l) <NEW_LINE> l.append(root.val) | :type root: TreeNode
:type l: List[int]
:rtype: nothing | 625941dccdde0d52a9e5333d |
def fit(self, X, y): <NEW_LINE> <INDENT> n_samples = X.shape[0] <NEW_LINE> n_features = X.shape[1] <NEW_LINE> n_classes = 2 <NEW_LINE> n_fvalues = 2 <NEW_LINE> if n_samples != len(y): <NEW_LINE> <INDENT> raise ValueError('Mismatched number of samples.') <NEW_LINE> <DEDENT> nY = np.zeros(n_classes, dtype=np.int) <NEW_LI... | Fitting Model
Parameters
----------
X: array_like, shape=(n_samples, n_features), dtype=int
feature values of training samples
y: array_like, shape=(n_samples), dtype=int
class labels of training samples | 625941dc596a897236089dc5 |
def __init__(self, handler_class, path, keyfile=None, certfile=None): <NEW_LINE> <INDENT> if certfile is not None and keyfile is not None: <NEW_LINE> <INDENT> endpoint_id = "https://{}".format(path) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> endpoint_id = "http://{}".format(path) <NEW_LINE> <DEDENT> super().__init__... | Initialize new UnixSocketHTTPEndpoint object
Args:
handler_class (obj): a request handler class that will be handling
requests received by internal httpd server
path (str): Unix socket path, that internal httpd server will listen
on | 625941dc925a0f43d254a181 |
def process_log_data(spark, input_data, output_data): <NEW_LINE> <INDENT> log_data = os.path.join(input_data, 'log-data/*/*/*.json') <NEW_LINE> df = spark.read.json(log_data) <NEW_LINE> log_df = df.filter(df.page == 'NextSong') .select('ts', 'userId', 'level', 'song', 'artist', 'sessionId', 'location',... | Reads data from S3 bucket (parameter input_data) into a data frame, processes it using Spark and loads data back to S3 in users, time, and songplays table
:param spark: Spark session
:param input_data: source S3 bucket
:param output_data: destination S3 bucket | 625941dc1f037a2d8b946505 |
def solve(option, file_path): <NEW_LINE> <INDENT> logger.debug("Using %s option with file %s", option, file_path) <NEW_LINE> result = print_first10(option, file_path) <NEW_LINE> return result | Hàm `solve` sử dụng với mục đích `test`, học viên không cần chỉnh
sửa gì thêm
:param option: tùy chọn để in ra các dòng đầu hoặc cuối: -h hoặc -t
:param file_path: đường dẫn tới file
:rtype list: | 625941dc5510c4643540f6e5 |
def build_person(person, first, last, middle="", age=None): <NEW_LINE> <INDENT> if last not in person: <NEW_LINE> <INDENT> person[last] = {} <NEW_LINE> <DEDENT> person[last]['first'] = first <NEW_LINE> if middle: <NEW_LINE> <INDENT> person[last]['middle'] = middle <NEW_LINE> <DEDENT> if age: <NEW_LINE> <INDENT> person[... | return a dictionary of persons | 625941dcbf627c535bc134d7 |
def return_node(self, node_id): <NEW_LINE> <INDENT> assert isinstance(node_id, int) or isinstance(node_id, float), 'Must pass integer' <NEW_LINE> node_id = int(node_id) <NEW_LINE> return self.data.get(node_id) | Returns a pointer to the node with the given id number | 625941dcdd821e528d63b4af |
def __repr__(self): <NEW_LINE> <INDENT> return '<Twilio.Verify.V2.VerificationCheckInstance>' | Provide a friendly representation
:returns: Machine friendly representation
:rtype: str | 625941dc4e696a04525c9754 |
@host_context <NEW_LINE> def reload_nginx(): <NEW_LINE> <INDENT> symlink_nginx() <NEW_LINE> if run('nginx -t').succeeded: <NEW_LINE> <INDENT> pid = run('supervisorctl pid nginx') <NEW_LINE> run('kill -HUP {0}'.format(pid)) <NEW_LINE> <DEDENT> elif not confirm(yellow('nginx config test failed. continue?')): <NEW_LINE> <... | Reloads nginx if the config test succeeds. | 625941dc498bea3a759b9db6 |
def get_onehot(y, num_classes): <NEW_LINE> <INDENT> hot = np.zeros((len(y), num_classes), dtype=np.int32) <NEW_LINE> for i, c in enumerate(y): <NEW_LINE> <INDENT> hot[i][int(c) - 1] = 1 <NEW_LINE> <DEDENT> return hot | y is a vector of numbers (1, number of classes) | 625941dc8e71fb1e9831dab0 |
@remoteserviceHandle('gate') <NEW_LINE> def share_2102(pro_data, player): <NEW_LINE> <INDENT> response = CommonResponse() <NEW_LINE> result = remote_gate['world'].share_hjqy_remote(player.base_info.id) <NEW_LINE> friend_ids = player.friends.friends <NEW_LINE> boss_info = remote_gate['world'].get_boss_info_remote(player... | 分享hjqy, 广播协议号2112
| 625941dcadb09d7d5db6ca96 |
def _netns_resolvconf(netns): <NEW_LINE> <INDENT> ret = os.system('mkdir -p /etc/netns/'+netns) <NEW_LINE> with open('/etc/netns/'+netns+'/resolv.conf', 'w+') as f: <NEW_LINE> <INDENT> f.write('nameserver '+ma.get_address(bridge_ipv4_multiaddr)) | Each network namespace will now send dns requests to the bridge | 625941dc090684286d50eff1 |
def main(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser(description=__doc__) <NEW_LINE> num_group = parser.add_mutually_exclusive_group() <NEW_LINE> num_group.add_argument( '-n', '--number-circles', help='number of circles of points (default: 6)', type=anti_lib.read_positive_int, default=6) <NEW_LINE> num_grou... | Entry point | 625941dc63b5f9789fde73ee |
def get_data(self,short_name): <NEW_LINE> <INDENT> len_list = len(self.ship_data) <NEW_LINE> for i in range(len_list): <NEW_LINE> <INDENT> if self.ship_data[i][0] == short_name: <NEW_LINE> <INDENT> return self.ship_data[i] <NEW_LINE> <DEDENT> i+=1 <NEW_LINE> <DEDENT> return None | Getting specific data ex. mt | 625941dc8da39b475bd6527f |
def findname(self,name): <NEW_LINE> <INDENT> matches = self.getmember(name) <NEW_LINE> if not matches: return None <NEW_LINE> foundname = False <NEW_LINE> checkmembers = iter([matches['matchingmembers'][0]['name']] + matches['closematches']) <NEW_LINE> while not foundname: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> c... | returns a name if within the list
if name wasn't found, None is returned
any age checking needs to be done outside this method
:param name: name to search for
:rtype: name or None if not found | 625941dcf9cc0f698b140901 |
def _transform_hint_font(val): <NEW_LINE> <INDENT> match = re.fullmatch(r'(.*\d+p[xt]) Monospace', val) <NEW_LINE> if match: <NEW_LINE> <INDENT> return match.group(1) + ' ${_monospace}' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return val | Transformer for fonts -> hints. | 625941dc377c676e912724b0 |
def _transfer( self, shape, pixel_size, energy, offset, exponent=False, t=None, queue=None, out=None, check=True, block=False, ): <NEW_LINE> <INDENT> raise NotImplementedError | Transfer function implementation. | 625941dcbe7bc26dc91cd903 |
def flow_model(z_ary,alpha,a,b,U,dpdx,mu): <NEW_LINE> <INDENT> C = (dpdx*(-0.5*alpha**2*b**2+exp(log(alpha*b)-alpha*a)-exp(-alpha*a)+1) + U*alpha**2*mu)/(alpha**2*mu*(exp(log(alpha*b)-2*alpha*a)+alpha*b- exp(-2*alpha*a)+1)) <NEW_LINE> D = (dpdx*(exp(log(0.5*alpha**2*b**2)-2*alpha*a)+exp(log(alpha*b)-alpha*a)+ exp(-alph... | Evaluate the analytical 2D flow model at and above the porous tower.
Flow is assumed to be moving in the x direction with constant velocity in
that direction for a given value of z.
Arguments:
z_ary: position in the z direction. ndarray
The base of the domain is -a, the top b, and the top of the cylinder
... | 625941dc94891a1f4081bdb3 |
def grid_graph(dim, periodic=False): <NEW_LINE> <INDENT> dlabel = "%s" % dim <NEW_LINE> if not dim: <NEW_LINE> <INDENT> G = empty_graph(0) <NEW_LINE> G.name = "grid_graph(%s)" % dlabel <NEW_LINE> return G <NEW_LINE> <DEDENT> func = cycle_graph if periodic else path_graph <NEW_LINE> G = func(dim[0]) <NEW_LINE> for curre... | Returns the *n*-dimensional grid graph.
The dimension *n* is the length of the list `dim` and the size in
each dimension is the value of the corresponding list element.
Parameters
----------
dim : list or tuple of numbers or iterables of nodes
'dim' is a tuple or list with, for each dimension, either a number
... | 625941dc4e4d5625662d46dd |
def create_endpoint( clipper_conn, name, input_type, func, pyspark_model, sc, default_output="None", version=1, slo_micros=3000000, labels=None, registry=None, base_image="clipper/pyspark-container:{}".format(__version__), num_replicas=1, batch_size=-1): <NEW_LINE> <INDENT> clipper_conn.register_application(name, input... | Registers an app and deploys the provided predict function with PySpark model as
a Clipper model.
Parameters
----------
clipper_conn : :py:meth:`clipper_admin.ClipperConnection`
A ``ClipperConnection`` object connected to a running Clipper cluster.
name : str
The name to be assigned to both the registered appl... | 625941dcbf627c535bc134d8 |
def cube(x): <NEW_LINE> <INDENT> return x * x * x | Given a number x, returns its cube (x^3) | 625941dcc432627299f04f50 |
def PresRatio(gam,M): <NEW_LINE> <INDENT> TR = TempRatio(gam,M) <NEW_LINE> PR = (TR)**(gam/(gam-1)) <NEW_LINE> return PR | return pressure ratio | 625941dcf8510a7c17cf9a07 |
def test_jid_from_dict(): <NEW_LINE> <INDENT> item = JID({'bare': 'user@domain.com', 'nick': 'user', 'domain': 'domain.com', 'full': 'user@domain.com/resource', 'resource': 'resource'}) <NEW_LINE> item.full.should.equal('user@domain.com/resource') <NEW_LINE> item.bare.should.equal('user@domain.com') <NEW_LINE> item.nic... | JID() should accept a dict | 625941dcc4546d3d9de72d3f |
def test_protein_refseq2(self): <NEW_LINE> <INDENT> self.loop("GenBank/protein_refseq2.gb", "gb") | GenBank file to BioSQL and back to a GenBank file, protein_refseq2. | 625941dc9c8ee82313fbba7e |
def __init__(self, bin: str): <NEW_LINE> <INDENT> self._fixed = {_Keys.BIN_KEY: bin} | Args:
bin (str): Bin name.
:return: (geojson bin)
Example::
#GeoJSON bin "a" contained by GeoJSON bin "b".
expr = exp.CmpGeo(GeoBin("a"), exp.GeoBin("b")).compile() | 625941dc3cc13d1c6d3c7682 |
def test_with_now_minus_3_days(self): <NEW_LINE> <INDENT> self.assertEqual(ageid(self.now - timedelta(3)), 'age4') | Testing {% ageid %} with three days ago | 625941dc1f037a2d8b946506 |
def diameterOfBinaryTree(self, root): <NEW_LINE> <INDENT> if not root: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> self.revalueTree(root) <NEW_LINE> listroot=[root] <NEW_LINE> rep=0 <NEW_LINE> while listroot: <NEW_LINE> <INDENT> len_listroot=len(listroot) <NEW_LINE> for i in range(len_listroot): <NEW_LINE> <INDENT... | :type root: TreeNode
:rtype: int | 625941dc76d4e153a657ee3b |
@blueprint.route( "/<name:dbname>/<name:viewname>/edit", methods=["GET", "POST", "DELETE"] ) <NEW_LINE> @utils.login_required <NEW_LINE> def edit(dbname, viewname): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> db = dbshare.db.get_check_write(dbname) <NEW_LINE> <DEDENT> except (KeyError, ValueError) as error: <NEW_LINE>... | Edit the metadata of the view. Or delete the view. | 625941dc66673b3332b9239a |
def l1_regularizer(scale=0.001, name='l1Regularizer', collect=True): <NEW_LINE> <INDENT> def inner_regularizer(x): <NEW_LINE> <INDENT> return tf.multiply(x=tf.reduce_sum(tf.abs(x)), y=scale, name=name) <NEW_LINE> <DEDENT> return built_regularizer(inner_regularizer, collect) | Returns a function that can be used to apply L1 regularization to a tensor.
Computes the L1 norm of a tensor:
output = sum(|t|) * scale
Args:
scale: `float`. A scalar multiplier `Tensor`. 0.0 disables the regularizer.
name: name of the app.
collect: add to regularization losses
Returns:
The regula... | 625941dcff9c53063f47c4fb |
def __init__(self, parent): <NEW_LINE> <INDENT> super(Hands05, self).__init__(parent) <NEW_LINE> _pins_airhand = [self.DIO_27, self.DIO_28, self.DIO_25, self.DIO_26] <NEW_LINE> _pins_gripper = [self.DIO_23, self.DIO_24, self.DIO_21, self.DIO_22] <NEW_LINE> _pins_handlight = [self.DIO_18, self.DIO_17] <NEW_LINE> _pins_t... | @see: AbsractIros13Hands.__init__ | 625941dc287bf620b61d3d6b |
def get_L_ranges(iL): <NEW_LINE> <INDENT> L = [] <NEW_LINE> from_ = None <NEW_LINE> to = None <NEW_LINE> for x in iL: <NEW_LINE> <INDENT> if from_ is None: <NEW_LINE> <INDENT> from_ = x <NEW_LINE> to = x <NEW_LINE> <DEDENT> elif x != to+1: <NEW_LINE> <INDENT> L.append((from_, to+1)) <NEW_LINE> from_ = x <NEW_LINE> to =... | Appends the "from" and "to" positions whenever integers
in iterable `iL` are found that aren't consecutive.
e.g. get_L_ranges([0, 1, 2, 4, 5, 6]) -> [(0, 3), (4, 7)] | 625941dc26068e7796caefeb |
def __init__(self, neighbours=5, dist='minkowski', normalize=False): <NEW_LINE> <INDENT> self.neighbours = neighbours <NEW_LINE> self.dist = dist <NEW_LINE> self.normalize = normalize | dist: Distance metrics - euclidean, minkowski
neighbours: Nearest neighbours | 625941dc99cbb53fe6792eef |
def __init__(self, parent): <NEW_LINE> <INDENT> super().__init__(parent) <NEW_LINE> self.parent = parent <NEW_LINE> self.parent.title('BeatBoxer') <NEW_LINE> self.parent.iconbitmap(ICON_PATH) <NEW_LINE> self.initialize() <NEW_LINE> self.make_menu() | Main window of the GUI. | 625941dc24f1403a92600e6d |
def face_detector(image): <NEW_LINE> <INDENT> img = cv2.imdecode(image, cv2.IMREAD_COLOR) <NEW_LINE> gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) <NEW_LINE> faces = face_cascade.detectMultiScale(gray) <NEW_LINE> return len(faces) > 0 | Input: image file as numpy array.
Returns True if face is detected in the image by the OpenCV face detector. | 625941dc63f4b57ef000141a |
def normalise(self): <NEW_LINE> <INDENT> vct = math.sqrt(self.x**2 + self.y**2) <NEW_LINE> self.x /= vct <NEW_LINE> self.y /= vct | Normalizes the vector | 625941dc99fddb7c1c9de699 |
def _initialize_chain(self): <NEW_LINE> <INDENT> assert self.num_nodes <= MAX_NODES <NEW_LINE> create_cache = False <NEW_LINE> for i in range(MAX_NODES): <NEW_LINE> <INDENT> if not os.path.isdir(os.path.join(self.options.cachedir, 'node' + str(i))): <NEW_LINE> <INDENT> create_cache = True <NEW_LINE> break <NEW_LINE> <D... | Initialize a pre-mined blockchain for use by the test.
Create a cache of a 200-block-long chain (with wallet) for MAX_NODES
Afterward, create num_nodes copies from the cache. | 625941dce64d504609d74b49 |
def serialize(self, buff): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _x = self.topic <NEW_LINE> length = len(_x) <NEW_LINE> if python3 or type(_x) == unicode: <NEW_LINE> <INDENT> _x = _x.encode('utf-8') <NEW_LINE> length = len(_x) <NEW_LINE> <DEDENT> if python3: <NEW_LINE> <INDENT> buff.write(struct.pack('<I%sB'%len... | serialize message into buffer
:param buff: buffer, ``StringIO`` | 625941dcbe8e80087fb20f48 |
def Test7(self, data): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> driver = self.driver <NEW_LINE> redis = GetRedis() <NEW_LINE> value = redis.GetDate(data) <NEW_LINE> value = ast.literal_eval(value) <NEW_LINE> driver.input('x,//*[@id="home"]/main/div/div/div[2]/table/tr[2]/td[3]/input', value['p1']) <NEW_LINE> driver... | :param self:
:param data:
:return: | 625941dc0a366e3fb873eb25 |
def __update_monitors(self): <NEW_LINE> <INDENT> with self.__lock: <NEW_LINE> <INDENT> if self.props.monitored: <NEW_LINE> <INDENT> for directory in common.walk_directories(self.__root): <NEW_LINE> <INDENT> monitor = directory.monitor_directory() <NEW_LINE> monitor.connect('changed', self.on_location_changed) <NEW_LINE... | Sets up or removes library monitors | 625941dca934411ee375199d |
def _multipart_upload_enc(client, bucket_name, key, size, part_size, init_headers, part_headers, metadata, resend_parts): <NEW_LINE> <INDENT> if client == None: <NEW_LINE> <INDENT> client = get_client() <NEW_LINE> <DEDENT> lf = (lambda **kwargs: kwargs['params']['headers'].update(init_headers)) <NEW_LINE> client.meta.e... | generate a multi-part upload for a random file of specifed size,
if requested, generate a list of the parts
return the upload descriptor | 625941dc796e427e537b08d1 |
def bevel(*args, **kwargs): <NEW_LINE> <INDENT> pass | The bevel command creates a new bevel surface for the specified curve. The curve can be any nurbs curves.
Flags:
- bevelShapeType : bst (int) [create,query,edit]
Shape type: 1 - straight cut, 2 - curve out, 3 - curve inDefault:1Advanced flags
- caching : cch (bool) ... | 625941dc30bbd722463cc0d2 |
def user_db_access(self, username, dbname): <NEW_LINE> <INDENT> cmd = 'echo "GRANT ALL PRIVILEGES ON {dbname}.* TO {username}@localhost WITH GRANT OPTION;" | mysql'.format( dbname=dbname, username=username ) <NEW_LINE> j.sal.process.execute(cmd, die=False) | give use right to this database (fully)
username {string} -- username to be granted the access
dbname {string} -- database name to which access would be granted | 625941dcd6c5a10208144356 |
def _build_obj_dict(self): <NEW_LINE> <INDENT> _obj_class_list = (Person, Family, Event, Place, Source, Citation, MediaObject, Repository, Note, Tag) <NEW_LINE> self.obj_dict = defaultdict(lambda: defaultdict(set)) <NEW_LINE> self.bkref_dict = defaultdict(lambda: defaultdict(set)) <NEW_LINE> for obj_class in _obj_class... | Construct the dictionaries of objects to be included in the reports. There
are two dictionaries, which have the same structure: they are two level
dictionaries,the first key is the class of object (e.g. gen.lib.Person).
The second key is the handle of the object.
For the obj_dict, the value is a tuple containing:
- t... | 625941dc38b623060ff0b0f6 |
def getsongs(self, playlist_id): <NEW_LINE> <INDENT> results = self.sp.user_playlist_tracks(self.id,playlist_id) <NEW_LINE> tracks = results['items'] <NEW_LINE> song_ids = [] <NEW_LINE> while results['next']: <NEW_LINE> <INDENT> results = self.sp.next(results) <NEW_LINE> tracks.extend(results['items']) <NEW_LINE> <DEDE... | Gets all songs from a chosen playlist, returns a lsit of all song ids | 625941dc3617ad0b5ed681ff |
def __init__(self, ai_settings): <NEW_LINE> <INDENT> self.ai_settings = ai_settings <NEW_LINE> self.game_active = True <NEW_LINE> self.reset_stats() | 初始化统计信息 | 625941dcfbf16365ca6f64d2 |
def get_results(self): <NEW_LINE> <INDENT> equity_s = pd.Series(self.equity).sort_index() <NEW_LINE> returns_s = equity_s.pct_change().fillna(0.0) <NEW_LINE> rolling = returns_s.rolling(window=self.periods) <NEW_LINE> rolling_sharpe_s = np.sqrt(self.periods) * ( rolling.mean() / rolling.std() ) <NEW_LINE> cum_returns_s... | Return a dict with all important results & stats. | 625941dcab23a570cc25048e |
def __init__(self, a_file_name, a_sample_dir): <NEW_LINE> <INDENT> self.sample_graph_cache = None <NEW_LINE> f_file_name = str(a_file_name) <NEW_LINE> self._file = None <NEW_LINE> self.sample_dir = str(a_sample_dir) <NEW_LINE> self.sample_dir_file = None <NEW_LINE> self.timestamp = None <NEW_LINE> self.channels = None ... | a_file_name: The full path to /.../sample_graphs/uid
a_sample_dir: The project's sample dir | 625941dcd58c6744b4257f68 |
def rotate(self, *args, **kwargs): <NEW_LINE> <INDENT> pass | Has no effect. Provided for compatibility with
:class:`sge.gfx.Sprite`. | 625941dc167d2b6e31218e9e |
def __get_yesterday(self, day: str) -> str: <NEW_LINE> <INDENT> day = self.__get_full_day(day) <NEW_LINE> curr_index: int = self.ORDERED_DAYS.index(day) <NEW_LINE> return self.ORDERED_DAYS[(curr_index - 1) % len(self.ORDERED_DAYS)] | Gets the day before the given day.
Parameters
----------
day : `str`
Name of day as a string.
Returns
----------
A string representing the day before the given day in all caps.
Raises
----------
`AssertionError`: If the given day is not a full day. | 625941dc8a43f66fc4b5436b |
@error_context.context_aware <NEW_LINE> def run(test, params, env): <NEW_LINE> <INDENT> if params.get("start_vm") == 'no': <NEW_LINE> <INDENT> num_bus = params.get_numeric("numberic_bus") <NEW_LINE> for i in range(2, num_bus + 1): <NEW_LINE> <INDENT> serial_name = 'vs%d' % i <NEW_LINE> params['serials'] = '%s %s' % (pa... | Test guest with virtio-serial-device with multiple virtserialports
Scenario 1:
1.1. Boot a guest with 1 virtio-serial-bus with 3 serial ports
1.2. Transfer data via every port
Scenario 2:
2.1. Start guest with 2 virtio-serial-pci,
2.2. Each virtio-serial-pci has 3 virtio-serial-ports
2.3. Transfer d... | 625941dce8904600ed9f223a |
@conf <NEW_LINE> def CHECK_CODE(conf, code, define, always=False, execute=False, addmain=True, add_headers=True, mandatory=False, headers=None, msg=None, cflags='', includes='# .', local_include=True, lib=None, link=True, define_ret=False, quote=False, on_target=True, strict=False): <NEW_LINE> <INDENT> if CONFIG_SET(co... | check if some code compiles and/or runs | 625941dc0c0af96317bb84f1 |
def run(self, tempest_conf=None, testr_arg=None, log_file=None): <NEW_LINE> <INDENT> if tempest_conf and os.path.isfile(tempest_conf): <NEW_LINE> <INDENT> self.config_file = tempest_conf <NEW_LINE> self._generate_env() <NEW_LINE> <DEDENT> test_cmd = ( "%(venv)s testr run --parallel --subunit %(arg)s " "| tee %(log_file... | Launch tempest with given arguments
:param tempest_conf: User specified tempest.conf location
:param testr_arg: argument which will be transmitted into testr
:type testr_arg: str
:param log_file: file name for raw subunit results of tests. If not
specified, value from "self.log_file_raw"
... | 625941dc507cdc57c6306feb |
def tagData(dFile, position, bit, seek=0): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> dFile.seek(position, seek) <NEW_LINE> tagdata = dFile.read(bit) <NEW_LINE> <DEDENT> except: sys.stderr.write("Error al obtener el Tag Data") <NEW_LINE> return tagdata | Toma un punto de partida (position), cantidad de bit y un punto de
referencia para leer los bit(según el método seek() de los fichero).
Además dataFile el cual es objeto StringIO. | 625941dc92d797404e304495 |
def DrawText(self, text, location, color='black', font=None, angle=0, text_location=TEXT_LOCATION_CENTER): <NEW_LINE> <INDENT> text = str(text) <NEW_LINE> if location == (None, None): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> converted_point = self._convert_xy_to_canvas_xy(location[0], location[1]) <NEW_LINE> if s... | Draw some text on your graph. This is how you label graph number lines for example
:param text: text to display
:type text: (str)
:param location: location to place first letter
:type location: Union[Tuple[int, int], Tuple[float, float]]
:param color: text color
:type color: (str)
:param font: specifies the font fami... | 625941dc8da39b475bd65280 |
def _WriteHTMLDocResponse(response, values, title='All Variables'): <NEW_LINE> <INDENT> content = ''.join(vars_export.GetVarDocHTML(var) for var in values) <NEW_LINE> response.headers.add_header('Content-Type', 'text/html; charset=UTF-8') <NEW_LINE> response.start_response(200) <NEW_LINE> response.out.write(_HTML_HEADE... | Write the HTTP response for a /vars?output=htmldoc request.
Args:
title: The page title.
response: The HTTP response object.
values: A dictionary containing (name, value) mappings to be written. | 625941dc21bff66bcd684c59 |
def _RunBinman(self, *args, **kwargs): <NEW_LINE> <INDENT> result = command.RunPipe([[self._binman_pathname] + list(args)], capture=True, capture_stderr=True, raise_on_error=False) <NEW_LINE> if result.return_code and kwargs.get('raise_on_error', True): <NEW_LINE> <INDENT> raise Exception("Error running '%s': %s" % (' ... | Run binman using the command line
Args:
Arguments to pass, as a list of strings
kwargs: Arguments to pass to Command.RunPipe() | 625941dc1d351010ab855e25 |
def key_dict(self): <NEW_LINE> <INDENT> result = self.predicates.copy() <NEW_LINE> result["model"] = self.model <NEW_LINE> return result | Return a dict containing view registration info,
for instance model, request_method, etc. | 625941dc85dfad0860c3b165 |
def getAction(self, gameState): <NEW_LINE> <INDENT> numAgents = gameState.getNumAgents() <NEW_LINE> return self.bounded_minimax(gameState, self.depth*numAgents, numAgents)[1] | Returns the minimax action from the current gameState using self.depth
and self.evaluationFunction.
Here are some method calls that might be useful when implementing minimax.
gameState.getLegalActions(agentIndex):
Returns a list of legal actions for an agent
agentIndex=0 means Pacman, ghosts are >= 1
gameState.g... | 625941dcbaa26c4b54cb1426 |
def dataset_resource(self, ref_id, friendly_name=None, description=None, access=None, location=None): <NEW_LINE> <INDENT> data = { "datasetReference": { "datasetId": ref_id, "projectId": self.project_id } } <NEW_LINE> if friendly_name: <NEW_LINE> <INDENT> data["friendlyName"] = friendly_name <NEW_LINE> <DEDENT> if desc... | See
https://developers.google.com/bigquery/docs/reference/v2/datasets#resource
Parameters
----------
ref_id : str
Dataset id (the reference id, not the integer id)
friendly_name : str, optional
An optional descriptive name for the dataset
description : str, optional
An optional description for the dataset
... | 625941dc21a7993f00bc7ffe |
def _filter(t, h, spk): <NEW_LINE> <INDENT> u = 1 * pq.s <NEW_LINE> try: <NEW_LINE> <INDENT> t_sec = t.rescale(u).magnitude <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> raise ValueError("t must be a quantities object") <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> h_sec = h.rescale(u).magnitude <NEW_LI... | This function calculates the difference of spike counts in the left and right
side of a window of size h centered in t and normalized by its variance.
The variance of this count can be expressed as a combination of mean and var
of the I.S.I. lying inside the window.
Parameters
----------
h : quantity
windo... | 625941dcb7558d58953c5219 |
def awps(self, REQUEST): <NEW_LINE> <INDENT> if not _is_authenticated(REQUEST): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> country_code = REQUEST.form.get("nfp", 'eea') <NEW_LINE> country_name = code_to_name(country_code) <NEW_LINE> agent = self._get_ldap_agent() <NEW_LINE> if not self._allowed(agent, REQUEST, countr... | view awp roles and members in these roles | 625941dcd268445f265b5178 |
def get_build_target_location_from_freestyle(console): <NEW_LINE> <INDENT> console = console.encode('ISO-8859-1').decode('utf-8', errors='ignore') <NEW_LINE> for line in console.splitlines(): <NEW_LINE> <INDENT> if re.search('storage_dir', line): <NEW_LINE> <INDENT> print(line) <NEW_LINE> return line <NEW_LINE> <DEDENT... | 从输出中解析固件地址
:param console: 终端输入内容
:return: 解析出的固件地址 | 625941dc283ffb24f3c55c08 |
def logistic_regression_head( weight_column=None, loss_reduction=losses.Reduction.SUM_OVER_BATCH_SIZE, name=None): <NEW_LINE> <INDENT> def _logistic_loss(labels, logits): <NEW_LINE> <INDENT> labels = head_lib._assert_range( labels, n_classes=2, message='Labels must be in range [0, 1]') <NEW_LINE> return nn.sigmoid_cros... | Creates a `_Head` for logistic regression.
Uses `sigmoid_cross_entropy_with_logits` loss, which is the same as
`binary_classification_head`. The differences compared to
`binary_classification_head` are:
* Does not support `label_vocabulary`. Instead, labels must be float in the
range [0, 1].
* Does not calculate so... | 625941dc6fb2d068a760f3ab |
def coinChange(self, coins, amount): <NEW_LINE> <INDENT> memo = [0 for _ in range(amount + 1)] <NEW_LINE> return count_coins(coins, amount, memo) | :type coins: List[int]
:type amount: int
:rtype: int | 625941dc66673b3332b9239b |
def __init__(self, country='spain', *args, **kwargs): <NEW_LINE> <INDENT> super(MinubeSpider, self).__init__(*args, **kwargs) <NEW_LINE> self.start_urls = ['http://www.minube.co.uk/what-to-see/%s' % country] <NEW_LINE> self.poi_list = '' <NEW_LINE> self.country_name = country | In the init method we retrieve the country parameter and initialize the html poi list
as an empty string. | 625941dc5f7d997b87174da4 |
def delete(self): <NEW_LINE> <INDENT> return self._handle.delete(self.id) | Updates project using the current state
:rtype: :py:class:`.OperationResult` | 625941dc2eb69b55b151cbbc |
def release(self, number): <NEW_LINE> <INDENT> self.s.add(number) | Recycle or release a number.
:type number: int
:rtype: None | 625941dc1f5feb6acb0c4e55 |
def assign_stars(pvals, star_ths): <NEW_LINE> <INDENT> n_stars = np.zeros(len(pvals)) <NEW_LINE> for ii, star in enumerate(star_ths): <NEW_LINE> <INDENT> n_stars[pvals < star] = ii+1 <NEW_LINE> <DEDENT> return n_stars | Assign significance stars based on pvalue thresholds.
Parameters
----------
pvals : np.array
pvalues of data
star_ths :
iith entry is ii+1 star max threshold
Returns
-------
number_stars : np.array
number of stars for datapoints in pvals | 625941dc63d6d428bbe447fa |
def test_ref_detached_hash(self): <NEW_LINE> <INDENT> self._repo._git_current_branch = self._git_current_branch(False, '') <NEW_LINE> self._repo._git_current_tag = self._git_current_tag(False, '') <NEW_LINE> self._repo._git_current_hash = self._git_current_hash(True, 'abc123') <NEW_LINE> expected = 'abc123' <NEW_LINE> ... | Test that we can identify ref is detached at a hash
| 625941dc566aa707497f486f |
def means_chosen_value(self, key, time_window): <NEW_LINE> <INDENT> xs_A, ys_A, xs_B, ys_B = [], [], [], [] <NEW_LINE> for x_A, x_B, r_cv, choice in self.tuning_curve(key, time_window): <NEW_LINE> <INDENT> if choice == 'A': <NEW_LINE> <INDENT> xs_A.append(x_A * self.model.δ_J_stim['1']) <NEW_LINE> ys_A.append(r_cv) <NE... | Get firing rate in function of chosen value (Fig. 4L) | 625941dc090684286d50eff2 |
def configure(self, filepath): <NEW_LINE> <INDENT> self.targets.load(filepath) | Configure the Collector from file.
Args:
filepath: (str) where the configuration is located | 625941dc15baa723493c4281 |
def init(self, **kwargs): <NEW_LINE> <INDENT> self.code = kwargs.get('Code') <NEW_LINE> self.symbol = kwargs.get('Symbol') <NEW_LINE> self.space_between_amount_and_symbol = kwargs.get('SpaceBetweenAmountAndSymbol') <NEW_LINE> self.symbol_on_left = kwargs.get('SymbolOnLeft') <NEW_LINE> self.decimal_separator = kwargs.ge... | Initializes attributes for object
:param kwargs:
:return: | 625941dcd486a94d0b98e451 |
@when('I enter the account number "(?P<account_number>[^"]*)"') <NEW_LINE> def step_impl(context, account_number): <NEW_LINE> <INDENT> form = context.response.forms['account-form'] <NEW_LINE> form['account_number'] = account_number <NEW_LINE> context.form_response = form.submit() <NEW_LINE> assert_equal(context.form_re... | @type context behave.runner.Context
@type account_number str | 625941dccdde0d52a9e5333f |
def _update_weights_vec(weights_org, weights_new, corr, step_size): <NEW_LINE> <INDENT> full_exp = full_exposure(weights=weights_new, corr=corr) <NEW_LINE> weights_dif = full_exp - weights_org <NEW_LINE> max_abs_dif = np.max(np.abs(weights_dif)) <NEW_LINE> with np.errstate(divide='ignore', invalid='ignore'): <NEW_LINE>... | Helper-function for the function `adjust_weights` which performs a single
update of the portfolio weights. This is the vectorized version which uses
Numpy to update all the weights simultaneously.
This algorithm is described in Section 8.7 of the paper linked above.
:param weights_org:
Numpy array with the origin... | 625941dc5e10d32532c5f230 |
def _get_filename(filename): <NEW_LINE> <INDENT> directory = os.path.dirname(os.path.realpath(__file__)) <NEW_LINE> return os.path.join(directory, filename) | Get filename. | 625941dca05bb46b383ecb2a |
def test_no_rescale_grades(): <NEW_LINE> <INDENT> pass | >>> profile = Profile(preferences_ut=[
... [ 0. , -0.5, -1. ],
... [ 1. , -1. , 0.5],
... [ 0.5, 0.5, -0.5],
... [ 0.5, 0. , 1. ],
... [-1. , -1. , 1. ],
... ], preferences_rk=[
... [0, 1, 2],
... [0, 2, 1],
... [1, 0, 2],
... [2, 0, 1],
... [2, 1, 0],
... ])
>>> rule = Rule... | 625941dc30c21e258bdfa7a9 |
def apply_driver_hacks(self, app, info, options): <NEW_LINE> <INDENT> if info.drivername.startswith('mysql'): <NEW_LINE> <INDENT> info.query.setdefault('charset', 'utf8') <NEW_LINE> if info.drivername != 'mysql+gaerdbms': <NEW_LINE> <INDENT> options.setdefault('pool_size', 10) <NEW_LINE> options.setdefault('pool_recycl... | This method is called before engine creation and used to inject
driver specific hacks into the options. The `options` parameter is
a dictionary of keyword arguments that will then be used to call
the :func:`sqlalchemy.create_engine` function.
The default implementation provides some saner defaults for things
like pool... | 625941dcaad79263cf390d4f |
def list_available_ssl_options( self, **kwargs ): <NEW_LINE> <INDENT> cls = kwargs.pop('cls', None) <NEW_LINE> error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } <NEW_LINE> error_map.update(kwargs.pop('error_map', {})) <NEW_LINE> api_version = "2017-10-01" <NEW_LINE> ac... | Lists available Ssl options for configuring Ssl policy.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ApplicationGatewayAvailableSslOptions, or the result of cls(response)
:rtype: ~azure.mgmt.network.v2017_10_01.models.ApplicationGatewayAvailableSslOptions
:raises: ~... | 625941dc009cb60464c636ba |
def main(): <NEW_LINE> <INDENT> directory = create_data_storage(game) <NEW_LINE> """ INITIALIZE AGENT TRAINING CLASS """ <NEW_LINE> algorithm = TRAIN_AGENT(game) <NEW_LINE> """ SET OPTIM PROBABILITIES """ <NEW_LINE> optim_probabilities = optim_prob*torch.ones((trajectory_length)) <NEW_LINE> """ TRAIN AGENT AND GENERATE... | PICK TASK:
CURRENTLY IMPLENTED TASKS INCLUDE,
1. CARTPOLE
2. PENDULUM
3. ACROBOT
4. MOUNTAIN-CAR DISCRETE | 625941dc236d856c2ad44ae8 |
def run_DCA_static(df, day, monthly_investment = 500, start = 0): <NEW_LINE> <INDENT> if type(day) is not str: <NEW_LINE> <INDENT> raise error("Wrong type for argument 'day', expected " + str(type("")) + " but got "+str(type(day)) +" instead") <NEW_LINE> <DEDENT> returns = np.array(df['daily_return']) <NEW_LINE> monthl... | Runs a simulation of a monthly investment on the same day each month using the market data provided
Input:
df : Pandas DataFrame, market day
- column 'DATE' : dates of format '1970-01-01 00:00:00'
- column 'daily_return : floats indicating the return of that day
- column 'market' : floats ... | 625941dc293b9510aa2c359d |
def press(self, event): <NEW_LINE> <INDENT> if event.key == 'q' or event.key == 'Q': <NEW_LINE> <INDENT> self.file.close() <NEW_LINE> plt.close() <NEW_LINE> <DEDENT> if event.key == 'w' or event.key == 'W': <NEW_LINE> <INDENT> for i in range(len(self.tablecmd)): <NEW_LINE> <INDENT> for j in range(len(self.tablespeed[i]... | Keyboard events during plotting | 625941dc45492302aab5e5d1 |
def ch2_writing_I_A_2(show=True, *arguments, **keywords): <NEW_LINE> <INDENT> pass | p. 14
| 625941dcadb09d7d5db6ca98 |
def irods_connection(self): <NEW_LINE> <INDENT> return iRODS(self.dm_irods_config.config_file, self.dm_irods_config.irods_auth_file, connection_timeout=self.config.get('connection_timeout', None), resource_name=self.config.get('resource_name', None), is_resource_server=self.config.get('is_resource_server', None), logge... | Create iRODS session object | 625941dc435de62698dfdf57 |
def MStep(self): <NEW_LINE> <INDENT> gamma = self.EStep() <NEW_LINE> self.pi = np.sum(gamma, axis=0) / len(gamma) <NEW_LINE> for k in range(self.num_mixt): <NEW_LINE> <INDENT> XTD = np.dot(self.X.T, np.diag(gamma[:, k])) <NEW_LINE> self.w[:, k] = np.dot(np.linalg.inv(np.dot(XTD, self.X)), np.dot(XTD, self.Y)) <NEW_LINE... | Does the M-Step of the EM-Algorithm
- Updates pi_1, ..., pi_k
- Updates the weights. | 625941dc63b5f9789fde73f0 |
def on_RPCMethodComboBox_changed(self, object): <NEW_LINE> <INDENT> method = self.rpc_method_list_store[self.builder.get_object("RPCMethodComboBox").get_active()][0] <NEW_LINE> self.builder.get_object("RPCMethodDescriptionLabel").set_text(self.RPCCommands[method]['Description']) <NEW_LINE> transaction_hash = "" <NEW_LI... | Called by GTK when the selected RPC method is changed | 625941dc15baa723493c4282 |
def getSpecularTint(self): <NEW_LINE> <INDENT> pass | Returns the attribute's value | 625941dcd6c5a10208144357 |
def checkFolder(path): <NEW_LINE> <INDENT> if path is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> path = os.path.expanduser(path) <NEW_LINE> path = os.path.abspath(path) <NEW_LINE> if os.path.isdir(path): <NEW_LINE> <INDENT> return path <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None | Returns absolute version of path and checks that folder is existent | 625941dc21a7993f00bc7fff |
def strip_markup(text, normalize=True, collapse=True): <NEW_LINE> <INDENT> wikicode = mwparserfromhell.parse(text) <NEW_LINE> return wikicode.strip_code(normalize, collapse) | Parses the given text and returns the text after stripping all MediaWiki
markup, leaving only the plain text.
:param normalize: passed to :py:func:`mwparserfromhell.wikicode.Wikicode.strip_code`
:param collapse: passed to :py:func:`mwparserfromhell.wikicode.Wikicode.strip_code`
:returns: :py:obj:`str` | 625941dc07d97122c4178b9c |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.