code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def paint_canvas (self): <NEW_LINE> <INDENT> rows = len(self.mlist) <NEW_LINE> if self.title: <NEW_LINE> <INDENT> rows += 1 <NEW_LINE> <DEDENT> self.canvas = shape.Shape(width=60, height=rows, fill=" ") <NEW_LINE> line = 0 <NEW_LINE> if self.title: <NEW_LINE> <INDENT> self.write_on_canvas(self.title) <NEW_LINE> line = ...
Creates a Shape object filled with the menu data, that can then be displayed and scrolled through.
625941d466673b3332b92294
def done(self): <NEW_LINE> <INDENT> self.on_complete(self.value)
Sends the selected values to the complete callback
625941d45fc7496912cc3b80
def test_favours_shorter_matches(monkeypatch): <NEW_LINE> <INDENT> monkeypatch.setattr( process, 'extractBests', lambda *args, **kwargs: [ ('some long thing', 100), ('thing', 100) ] ) <NEW_LINE> monkeypatch.setattr( docset, 'index', lambda l: { 'thing': { 'path': 'path/for/thing', 'junk': "anything else can be in here;...
When tie between matches, favour shorter rather than first to occur
625941d43539df3088e2e54d
def complete_preprocessing_history_with_http_info(self, id, data_id, **kwargs): <NEW_LINE> <INDENT> all_params = ['id', 'data_id'] <NEW_LINE> all_params.append('async_req') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> all_params.append('_preload_content') <NEW_LINE> all_params.append('_request_time...
complete_preprocessing_history # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.complete_preprocessing_history_with_http_info(id, data_id, async_req=True) >>> result = thread.get() :param async_req bool :param int ...
625941d482261d6c526ab6a4
def create_get_data_job_script(self): <NEW_LINE> <INDENT> module_logger.debug(debug_utils.get_name()) <NEW_LINE> script_name = self.get_data_job_script_name <NEW_LINE> with contextlib.suppress(FileNotFoundError): <NEW_LINE> <INDENT> os.remove(script_name) <NEW_LINE> <DEDENT> script = open(script_name, 'w') <NEW_LINE> s...
Create the script to be submitted to perform the get data job
625941d4cc0a2c11143dd093
def main(): <NEW_LINE> <INDENT> n = input('Enter a number: ') <NEW_LINE> res = fun(n, 1, 0) <NEW_LINE> print(res)
main method which calls fun method
625941d450485f2cf553cf9d
@app.route("/api/user/logout", methods=["GET"]) <NEW_LINE> def api_user_logout(): <NEW_LINE> <INDENT> if current_user.is_anonymous: <NEW_LINE> <INDENT> return not_ok() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logout_user() <NEW_LINE> return ok()
Logout current user. Method: GET :return: If success: { "ok": True } Else: { "ok": False }
625941d4435de62698dfde50
def _get_full_name(self, node): <NEW_LINE> <INDENT> curr = node <NEW_LINE> items = [] <NEW_LINE> while not isinstance(curr, ast.Name): <NEW_LINE> <INDENT> if not isinstance(curr, ast.Attribute): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> items.append(curr.attr) <NEW_LINE> curr = curr.value <NEW_LINE> <DEDENT> ...
Traverse an Attribute node to generate a full name, e.g., "tf.foo.bar". This is the inverse of `full_name_node`. Args: node: A Node of type Attribute. Returns: a '.'-delimited full-name or None if node was not Attribute or Name. i.e. `foo()+b).bar` returns None, while `a.b.c` would return "a.b.c".
625941d4bde94217f3682ff2
def run(self): <NEW_LINE> <INDENT> self.get_time_list() <NEW_LINE> last_pic = self.get_thelast() <NEW_LINE> print("Time lapse should be finished at {!s} and saved to {}".format(last_pic['time'], last_pic['path'])) <NEW_LINE> while True: <NEW_LINE> <INDENT> the_queue = self.get_next_ones() <NEW_LINE> if not the_queue: <...
The main method, starts the actual time lapse process.
625941d4d10714528d5ffee7
def merge(merge, with_, lambda_=None): <NEW_LINE> <INDENT> return _params({"merge": merge, "with": with_}, {"lambda": lambda_})
See the `docs <https://docs.fauna.com/fauna/current/api/fql/functions/merge>`__.
625941d4167d2b6e31218d98
@post("/chat/create") <NEW_LINE> def creatChat(): <NEW_LINE> <INDENT> c = max(coll.distinct("idChat"))+1 <NEW_LINE> users_list = list(request.forms.getall("user_id")) <NEW_LINE> info = [] <NEW_LINE> for u in users_list: <NEW_LINE> <INDENT> user = {} <NEW_LINE> user_info = (coll.find({"idUser": int(u)}, {"userName": 1})...
crea un chat con usuarios y lo inserta en la api
625941d4442bda511e8be619
@login_required() <NEW_LINE> def edit_blogpost(request, post_id): <NEW_LINE> <INDENT> blogpost = BlogPost.objects.get(id=post_id) <NEW_LINE> if blogpost.owner != request.user: <NEW_LINE> <INDENT> raise Http404 <NEW_LINE> <DEDENT> if request.method != 'POST': <NEW_LINE> <INDENT> form = BlogPostForm(instance=blogpost) <N...
Edita um post existente
625941d4097d151d1a22305b
def to_representation(self, obj): <NEW_LINE> <INDENT> ret = super(UserProfileSerializer, self).to_representation(obj) <NEW_LINE> if 'password' in ret: <NEW_LINE> <INDENT> del ret['password'] <NEW_LINE> <DEDENT> request = self.context['request'] if 'request' in self.context else None <NEW_LINE> if 'email' in ...
Serialize objects -> primitives.
625941d445492302aab5e4c8
def test_handles_skip_test_line(self): <NEW_LINE> <INDENT> if sys.version_info[0] == 2 and sys.version_info[1] == 6: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> skip_line = self.factory.make_ok( directive_text='SKIP This is the reason.') <NEW_LINE> adapter = Adapter('fake.tap', skip_line) <NEW_LINE> result = self.fa...
Add a skip when a test line contains a skip directive.
625941d4be383301e01b5687
def list_equal(_list1, _list2): <NEW_LINE> <INDENT> return len(_list1) == len(_list2) and sorted(_list1) == sorted(_list2)
are 2x lists equal (deep check)
625941d499fddb7c1c9de594
def finish(self, now=None): <NEW_LINE> <INDENT> self.last['tfinish'] = now or datetime.now()
Add finish time to last; if none explicitly given, use current time.
625941d40a50d4780f667096
def _eval_content_variables(self, content): <NEW_LINE> <INDENT> variables_list = parser.extract_variables(content) <NEW_LINE> for variable_name in variables_list: <NEW_LINE> <INDENT> variable_value = self.get_bind_variable(variable_name) <NEW_LINE> if "${}".format(variable_name) == content: <NEW_LINE> <INDENT> content ...
replace all variables of string content with mapping value. @param (str) content @return (str) parsed content e.g. variable_mapping = { "var_1": "abc", "var_2": "def" } $var_1 => "abc" $var_1#XYZ => "abc#XYZ" /$var_1/$var_2/var3 => "/abc/def/var3" ${func($var_1, $var_2, xyz)} =>...
625941d4283ffb24f3c55b02
def takePicture(self, loc_path): <NEW_LINE> <INDENT> logger.debug("Taking picture...") <NEW_LINE> if self.connect(): <NEW_LINE> <INDENT> apn_path = gp.check_result(gp.gp_camera_capture(self.camera, gp.GP_CAPTURE_IMAGE)) <NEW_LINE> logger.debug("Downloading picture %s/%s ..." % (apn_path.folder, apn_path.name)) <NEW_LIN...
Takes a picture with the connected camera. @return target Path to the jpg stored in the camera
625941d4656771135c3eba73
def get_network(self): <NEW_LINE> <INDENT> raise NotImplementedError
Fetch the current sync network. :returns: Sync object :rtype: sync.Network
625941d4fbf16365ca6f63c8
def add_tags(self, *tags): <NEW_LINE> <INDENT> self.tags.add(*(set(tags)-set(self.tags.all())))
Adds the given tags if they don't exist :param tags :return:
625941d40383005118ecf7e5
@bp.route("/u/<username>") <NEW_LINE> @login_required <NEW_LINE> def show_user_profile(username): <NEW_LINE> <INDENT> if username != current_user.username: <NEW_LINE> <INDENT> flash("Sorry, you cannot view that page.") <NEW_LINE> return redirect(url_for("main.index")) <NEW_LINE> <DEDENT> return "Hello {}".format(userna...
show the user profile for the current user.
625941d4462c4b4f79d1d8d3
def get_installed_business_segment(shop): <NEW_LINE> <INDENT> return configuration.get(shop, SAMPLE_BUSINESS_SEGMENT_KEY)
Returns the installed business segment
625941d43539df3088e2e54e
@app.route('/users/<int:user_id>/edit', methods=['GET', 'POST']) <NEW_LINE> def edit_user(user_id): <NEW_LINE> <INDENT> user = session.query(User).filter_by(id=user_id).first() <NEW_LINE> user_types = session.query(Type) <NEW_LINE> if request.method == 'GET': <NEW_LINE> <INDENT> return render_template("edit-user.html",...
GET: Display edit page for a specific user POST: Update user and redirect to User Details page
625941d4956e5f7376d7106f
def n_stages(self): <NEW_LINE> <INDENT> return self.s
Return number of stages.
625941d4c432627299f04e4a
def rotatedDigits_WRONG(self, N): <NEW_LINE> <INDENT> f = [0]*5 <NEW_LINE> f[1] = 4 <NEW_LINE> for i in range(2, 5): <NEW_LINE> <INDENT> f[i] = 6*f[i-1] <NEW_LINE> f[i] += 4*(10**(i-1)) <NEW_LINE> <DEDENT> def helper(N, f): <NEW_LINE> <INDENT> if N < 1: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> highest = int(str...
:type N: int :rtype: int
625941d4bf627c535bc133d2
def set(self, key, val): <NEW_LINE> <INDENT> if miscutils.fwdebug_check(9, "WCL_DEBUG"): <NEW_LINE> <INDENT> miscutils.fwdebug_print("BEG key=%s, val=%s" % (key, val)) <NEW_LINE> <DEDENT> subkeys = key.split('.') <NEW_LINE> valkey = subkeys.pop() <NEW_LINE> wcldict = self <NEW_LINE> for k in subkeys: <NEW_LINE> <INDENT...
Sets value of key in wcl, follows section notation.
625941d44a966d76dd551213
def make_instance(self, include_optional): <NEW_LINE> <INDENT> if include_optional : <NEW_LINE> <INDENT> return InstitutionConsent( institution_id = '0' ) <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> return InstitutionConsent( )
Test InstitutionConsent include_option is a boolean, when False only required params are included, when True both required and optional params are included
625941d43317a56b86939e58
def __repr__(self): <NEW_LINE> <INDENT> return '<{}, {}>'.format(self.username, self.password)
Return LJ id.
625941d48e05c05ec3eea579
def process_server_response(res): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> typ = res['type'] <NEW_LINE> data = res['data'] <NEW_LINE> <DEDENT> except KeyError as err: <NEW_LINE> <INDENT> raise KeyError(err) <NEW_LINE> <DEDENT> if 'loadSimulator' in typ: <NEW_LINE> <INDENT> print("\nSimulator loaded with success! Re...
Process a response received from the server. Args: res (dict): server response Raises: KeyError: if the received data is corrupted KeyError: if the received data is invalid Returns: tuple: type of response, received data
625941d4aad79263cf390c46
def getpulldir(): <NEW_LINE> <INDENT> hdir = os.environ["HOME"] + os.sep <NEW_LINE> curdir = os.getcwd() <NEW_LINE> if not curdir.startswith(hdir): <NEW_LINE> <INDENT> logging.error("current directory not in user's home directory; exiting.") <NEW_LINE> sys.exit(3) <NEW_LINE> <DEDENT> gdir = curdir[len(hdir) :] <NEW_LIN...
Get the name of the directory we're pulling.
625941d426068e7796caeee5
@app.route('/api/v1/genres/<int:genre_id>/movies/<int:movies_name_id>/JSON') <NEW_LINE> def singleMovieJSON(genre_id, movies_name_id): <NEW_LINE> <INDENT> Movie_name = session.query(Movies_name).filter_by(id=movies_name_id).one() <NEW_LINE> return jsonify(Movie_name=Movie_name.serialize)
Returns JSON Of selected Movie
625941d4e76e3b2f99f3aa0c
def search_conflicts(queens): <NEW_LINE> <INDENT> conflicts = numpy.zeros(N,) <NEW_LINE> for i in range(N): <NEW_LINE> <INDENT> for j in range(i+1, N): <NEW_LINE> <INDENT> if abs(queens[j] - queens[i]) == abs(j - i): <NEW_LINE> <INDENT> conflicts[i] = 1 <NEW_LINE> conflicts[j] = 1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> ...
Search the conflicts between the queens. The positions of the queens are stored in a list. The index represents the column and the value the line number. There is no conflict in the column or the line, so we only need to check the diagonals. If the difference of the i and the j position are the same between the queen...
625941d4aad79263cf390c47
def main(): <NEW_LINE> <INDENT> files, newline, verbose, mode = getopts() <NEW_LINE> for path in files: <NEW_LINE> <INDENT> process_file(path, newline, verbose, mode)
Main
625941d40fa83653e46571be
def dump(self, **kwargs) -> None: <NEW_LINE> <INDENT> dates = self._get_file_dates() <NEW_LINE> assert isinstance(dates, set) or isinstance(dates, dict) <NEW_LINE> if isinstance(dates, dict): <NEW_LINE> <INDENT> dts = dates.copy() <NEW_LINE> dates = set(dates.keys()) <NEW_LINE> kwargs["dts"] = dts <NEW_LINE> <DEDENT> d...
Dump multiple days of data that are not present in the database
625941d40a50d4780f667097
def __init__(self): <NEW_LINE> <INDENT> py_config = HostPythonConfiguration() <NEW_LINE> self.py_debug = py_config.debug <NEW_LINE> self.py_inc_dir = py_config.inc_dir <NEW_LINE> self.py_venv_inc_dir = py_config.venv_inc_dir <NEW_LINE> self.py_lib_dir = py_config.lib_dir <NEW_LINE> self.py_platform = py_config.platform...
Initialise the configuration with default values.
625941d48c0ade5d55d3ebbf
def eurUsdConversionRate(): <NEW_LINE> <INDENT> s = __name__.split(".")[1] <NEW_LINE> r = sys._getframe().f_code.co_name <NEW_LINE> cr = core.request(s, r) <NEW_LINE> return core.get(core.hostname(s), cr, core.header(s), core.compression(s), core.timeout(s))
This function provide conversion rate between EUR and USD. :param String symbol: Symbol is currency pair. :return: The function return payload of http response. It is string which contains json object. Official description of object's keys is in the table. =========== ========================...
625941d430c21e258bdfa6a1
def create_more_restricted_mask(self, path, outdir): <NEW_LINE> <INDENT> filename = os.path.basename(path) <NEW_LINE> filename = os.path.splitext(filename)[0] <NEW_LINE> image, header = nrrd.read(path) <NEW_LINE> val = filters.threshold_otsu(image) <NEW_LINE> blobs = image > val <NEW_LINE> mask = morph.binary_dilation(...
create a mask using otsu thresholding
625941d44428ac0f6e5ba9f6
def stop_backup(self, backup_info): <NEW_LINE> <INDENT> self._backup_info_from_backup_label(backup_info) <NEW_LINE> self.current_action = "stopping postgres backup_method" <NEW_LINE> output.info("Finalising the backup.") <NEW_LINE> postgres = self.executor.server.postgres <NEW_LINE> current_xlog_info = postgres.current...
Manage the stop of an pg_basebackup backup The method retrieves the information necessary for the backup.info file reading the backup_label file. Due of the nature of the pg_basebackup, information that are gathered during the start of a backup performed using rsync, are retrieved here :param barman.infofile.BackupI...
625941d43eb6a72ae02ec6e4
def has_page(self, pagename): <NEW_LINE> <INDENT> return pagename.rstrip('/') in self.pages()
Whether a page with the specified name exists.
625941d496565a6dacc8f8ce
def ShowPane(self, window, show): <NEW_LINE> <INDENT> p = self.GetPane(window) <NEW_LINE> if p.IsOk(): <NEW_LINE> <INDENT> if p.IsNotebookPage(): <NEW_LINE> <INDENT> notebook = self._notebooks[p.notebook_id] <NEW_LINE> page_idx = notebook.GetPageIndex(p.window) <NEW_LINE> if page_idx >= 0: <NEW_LINE> <INDENT> notebook....
Shows or hides a pane based on the window passed as input. :param wx.Window `window`: any subclass or derivation of :class:`wx.Window`; :param bool `show`: ``True`` to show the pane, ``False`` otherwise.
625941d47d847024c06be4c1
def __init__(self,G,routingFunction=None,CW=DefaultCommMatrix()): <NEW_LINE> <INDENT> super(FasterVRBC,self).__init__(G,routingFunction,CW) <NEW_LINE> self._computeBetweenness() <NEW_LINE> pass
Running time: O(nm)
625941d49c8ee82313fbb979
@slackbot.respond_to(r".*") <NEW_LINE> @slackbot.listen_to(r".*") <NEW_LINE> def on_default(msg): <NEW_LINE> <INDENT> return bot.on_message(msg)
Wrapper around CSCBot.on_message, since the slackbot module doesn't pass the CSCBot instance properly.
625941d4d7e4931a7ee9e121
def test_label_for_field(self): <NEW_LINE> <INDENT> self.assertEqual( label_for_field("title", Article), "title" ) <NEW_LINE> self.assertEqual( label_for_field("hist", Article), "History" ) <NEW_LINE> self.assertEqual( label_for_field("hist", Article, return_attr=True), ("History", None) ) <NEW_LINE> self.assertEqual( ...
Tests for label_for_field
625941d4287bf620b61d3c67
def getHttpHead(skt): <NEW_LINE> <INDENT> rst = {} <NEW_LINE> line = getLine(skt) <NEW_LINE> while line: <NEW_LINE> <INDENT> r = line.split(r': ') <NEW_LINE> if len(r) == 2: <NEW_LINE> <INDENT> rst[r[0]] = r[1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> r = line.split(r' ') <NEW_LINE> rst['method'] = r[0] <NEW_LINE>...
得到传入socket的http请求头 :param skt: 通信的socket :return: 解析后的请求内容,字典形式
625941d423849d37ff7b3292
def load_hazard_map(hzd_path): <NEW_LINE> <INDENT> with rasterio.open(hzd_path) as src: <NEW_LINE> <INDENT> affine = src.affine <NEW_LINE> array = src.read(1) <NEW_LINE> array = numpy.array(array,dtype='int16') <NEW_LINE> <DEDENT> return array,affine
Load specific hazard map. Arguments: *hzd_path* : file path to location of the hazard map.
625941d471ff763f4b549892
def page(self, phone_number=values.unset, friendly_name=values.unset, page_token=values.unset, page_number=values.unset, page_size=values.unset): <NEW_LINE> <INDENT> params = values.of({ 'PhoneNumber': phone_number, 'FriendlyName': friendly_name, 'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) <...
Retrieve a single page of OutgoingCallerIdInstance records from the API. Request is executed immediately :param unicode phone_number: Filter by phone number :param unicode friendly_name: Filter by friendly name :param str page_token: PageToken provided by the API :param int page_number: Page Number, this value is simp...
625941d4ac7a0e7691ed42cd
def __init__(self, message=None): <NEW_LINE> <INDENT> if message: <NEW_LINE> <INDENT> self.cant_be_empty = message
Initialize validator Accepts an optional custom can't be empty message :param messages: str, dict, custom error message or dict :return: None
625941d4ec188e330fd5a9a0
def __init__(self, tags=None, tagmap=None): <NEW_LINE> <INDENT> self._tags = tags or self._DEFAULT_TAGS <NEW_LINE> self._tagmap = tagmap or self._DEFAULT_TAGMAP <NEW_LINE> super().__init__(str, str)
Initializes the processor :param tags: The tags the processor should check with Wikipedia on :type tags: list of str :param tagmap: A mapping from Wikipedia tags to TEI tags :type tagmap: dict of str: str
625941d48da39b475bd65179
def emit_actions(self): <NEW_LINE> <INDENT> actions_list = [] <NEW_LINE> fb_template = "%s_set_%s(%s,%s)" <NEW_LINE> hash_entry = "%s[%s].%s" <NEW_LINE> for fb in self.all_fbs: <NEW_LINE> <INDENT> hash_val = hash_entry % (self.strings_dict['table_name'], self.strings_dict['hidx_str'], fb) <NEW_LINE> action = fb_templat...
dump the code that executes the actions
625941d41f037a2d8b946401
def test_post_hls_to_edx(mocker, reqmocker, edx_api_scenario): <NEW_LINE> <INDENT> mocked_posts = [ reqmocker.register_uri( "POST", edx_endpoint.full_api_url, headers={ "Authorization": "JWT {}".format(edx_endpoint.access_token), }, status_code=200, ) for edx_endpoint in [ edx_api_scenario.collection_endpoint, ] ] <NEW...
post_hls_to_edx should make POST requests to all edX API endpoints that are configured for a video file's collection
625941d463d6d428bbe446f4
def my_timeit(f,n,*args,**kwargs): <NEW_LINE> <INDENT> avg_time=0 <NEW_LINE> for i in range(n): <NEW_LINE> <INDENT> t0=clock() <NEW_LINE> f(*args,**kwargs) <NEW_LINE> avg_time+=clock()-t0 <NEW_LINE> <DEDENT> return avg_time/n
My timing function for when timeit is fucking stupid. f - Function to time. n - Number of runs to avergage the time from. *args and **kwargs - The input parameters in the order they should be inputted to f.
625941d44f6381625f114c3f
@task() <NEW_LINE> def update_html(): <NEW_LINE> <INDENT> with cd(depc.deploy_dir + '/nginx/data/'): <NEW_LINE> <INDENT> print('解压dist.zip...') <NEW_LINE> run('unzip ./dist.zip') <NEW_LINE> run('rm -rf ./assets') <NEW_LINE> run('mv ./dist/* ./') <NEW_LINE> print('更新html代码完成')
更新html代码 :return:
625941d47d43ff24873a2ea4
def t_titleline_BOM(t): <NEW_LINE> <INDENT> pass
\ufeff
625941d463f4b57ef0001319
def mean_(self, x_cond, n_samples=None): <NEW_LINE> <INDENT> assert hasattr(self, '_get_mixture_components') <NEW_LINE> assert self.fitted, "model must be fitted" <NEW_LINE> x_cond = self._handle_input_dimensionality(x_cond) <NEW_LINE> means = np.zeros((x_cond.shape[0], self.ndim_y)) <NEW_LINE> weights, locs, _ = self....
Mean of the fitted distribution conditioned on x_cond Args: x_cond: different x values to condition on - numpy array of shape (n_values, ndim_x) Returns: Means E[y|x] corresponding to x_cond - numpy array of shape (n_values, ndim_y)
625941d456ac1b37e62643d1
def _load_csv(path, delimiter=','): <NEW_LINE> <INDENT> precise_points = np.genfromtxt(path, delimiter=delimiter, dtype=np.float64) <NEW_LINE> offset = np.mean(precise_points, axis=0, dtype=np.float64) <NEW_LINE> pc = pcl.PointCloud(np.array(precise_points - offset, dtype=np.float32)) <NEW_LINE> force_srs(pc, offset=of...
Load a set of points from a CSV file as a pointcloud Returns: pc : pcl.PointCloud
625941d41f037a2d8b946402
def __eq__(self, other: 'DefaultQueryParamsPassages') -> bool: <NEW_LINE> <INDENT> if not isinstance(other, self.__class__): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__
Return `true` when self and other are equal, false otherwise.
625941d4236d856c2ad449df
def string_split_mutate(self, reference_column: str, split_on: str, new_columns: Union[List[str], str], keep_index: Optional[Union[int, str]]='all'): <NEW_LINE> <INDENT> if keep_index.lower() == 'all': <NEW_LINE> <INDENT> self.data[new_columns] = self.data[ reference_column].str.split( split_on, expand=True) <NEW_LINE>...
Split a string column based on some 'split_on' character. User can choose to expand each split subsection into a new distinct column (by default with keep_index='all') or keep a specific split subsection by specifying its index after splitting. I.e.: if the user split 'NYC-New York" on '-' and only wanted to keep 'N...
625941d49f2886367277aa90
def policy_from_utility(tprob, u): <NEW_LINE> <INDENT> pass
Obtain policy based on utility function. Args: tprob: tensor of rank 3 containing transition probability table: tprob[snext, s, a] = P(snext | s, a) is probability of transition to next state 'snext' given current state 's' and action 'a' u: current vector of utilities (value function...
625941d4925a0f43d254a07c
def annotate(comment, loc=1, fontsize=26, xpad=0.05, ypad=0.05, ax=None, axtoplot=None): <NEW_LINE> <INDENT> if ax is None: ax = plt.gca() <NEW_LINE> if axtoplot is None: axtoplot = ax <NEW_LINE> xrang = getAxRange(ax, 0) <NEW_LINE> yrang = getAxRange(ax, 1) <NEW_LINE> xy = get_axis_limits(ax, upper=False)[0] + xpad * ...
Args: comment: text
625941d4ff9c53063f47c3f7
def get_class_weights(stats): <NEW_LINE> <INDENT> weights = 1. / stats <NEW_LINE> return [weight / sum(weights) for weight in weights]
Get the weights for each class Each class has a weight inversely proportional to the number of instances in the training set Args: stats: The number of instances of each class Returns: The weights for each class
625941d42ae34c7f2600d335
def test_help_parser_func_do_help(self): <NEW_LINE> <INDENT> args = self._parse_args(['help']) <NEW_LINE> self.assertEqual(args.func, main.do_help)
help action function is do_help
625941d44d74a7450ccd43c7
def quote_schema(self, schema, force=None): <NEW_LINE> <INDENT> return self.quote(schema, force)
Conditionally quote a schema name. The name is quoted if it is a reserved word, contains quote-necessary characters, or is an instance of :class:`.quoted_name` which includes ``quote`` set to ``True``. Subclasses can override this to provide database-dependent quoting behavior for schema names. :param schema: string...
625941d49b70327d1c4e0fd9
def test_create_living_space(self): <NEW_LINE> <INDENT> new_living_space = self.amity.create_room("Livingspace", "Mara") <NEW_LINE> self.assertEqual(new_living_space, "MARA living space created successfully")
tests it creates living space
625941d4f9cc0f698b1407fe
def _plot_posterior_pdf_node(bottom_node, axis, value_range=None, samples=10, bins=100, **kwargs): <NEW_LINE> <INDENT> if value_range is None: <NEW_LINE> <INDENT> raise NotImplementedError("value_range keyword argument must be supplied.") <NEW_LINE> <DEDENT> like = np.empty((samples, len(value_range)), dtype=np.float32...
Calculate posterior predictive for a certain bottom node. :Arguments: bottom_node : pymc.stochastic Bottom node to compute posterior over. axis : matplotlib.axis Axis to plot into. value_range : numpy.ndarray Range over which to evaluate the likelihood. :Optional: samples : i...
625941d421a7993f00bc7ef6
def add_camera(self, cam_idx, cam_res, proj_model, dist_model): <NEW_LINE> <INDENT> fx = focal_length(cam_res[0], 90.0) <NEW_LINE> fy = focal_length(cam_res[1], 90.0) <NEW_LINE> cx = cam_res[0] / 2.0 <NEW_LINE> cy = cam_res[1] / 2.0 <NEW_LINE> params = [fx, fy, cx, cy, 0.0, 0.0, 0.0, 0.0] <NEW_LINE> args = [cam_idx, ca...
Add camera
625941d45e10d32532c5f12b
def doPipeline_QueryTasks(self,query): <NEW_LINE> <INDENT> params = {} <NEW_LINE> params['context'] = self.context <NEW_LINE> params['query'] = self.fixTypes(query) <NEW_LINE> ret= self.runMultipart("/pipeline", "QUERYTASKS", params) <NEW_LINE> return ret['response']
Queries for pipeline statuses.
625941d5eab8aa0e5d26dd5d
def setRelatedReferences(self, entityRef, relationshipSpec, relatedRefs, context, append=True): <NEW_LINE> <INDENT> if not self.entityExists(entityRef, context): <NEW_LINE> <INDENT> raise exceptions.InvalidEntityReference(entityReference=entityRef) <NEW_LINE> <DEDENT> for r in relatedRefs: <NEW_LINE> <INDENT> if not se...
Creates a new relationship between the referenced entities. @param append bool, When True (default) new relationships will be added to any existing ones. If False, then any existing relationships with the supplied specification will first be removed. Though getRelatedReferences is an essential call, there is some asy...
625941d42eb69b55b151cab5
def test_no_abstract_syntax_match(self): <NEW_LINE> <INDENT> self.scp = DummyStorageSCP() <NEW_LINE> self.scp.start() <NEW_LINE> ae = AE() <NEW_LINE> ae.add_requested_context(CTImageStorage) <NEW_LINE> ae.acse_timeout = 5 <NEW_LINE> ae.dimse_timeout = 5 <NEW_LINE> assoc = ae.associate('localhost', 11112) <NEW_LINE> ass...
Test SCU when no accepted abstract syntax
625941d44d74a7450ccd43c8
def model_dump(self): <NEW_LINE> <INDENT> buffer = StringIO() <NEW_LINE> self.model_config.write(buffer) <NEW_LINE> str = buffer.getvalue() <NEW_LINE> buffer.close() <NEW_LINE> return str
model_save(self, file_pointer) --> string dumps the model configuration to a string.
625941d50383005118ecf7e6
@app.task(base=CallbackTask) <NEW_LINE> def action(i): <NEW_LINE> <INDENT> return 42
short task
625941d5d8ef3951e3243742
def d_norm(output, activation, input_shape, local_range, k, alpha, beta): <NEW_LINE> <INDENT> assert_numlike(activation) <NEW_LINE> assert_numlike(output) <NEW_LINE> res = output.op_d_norm(activation, input_shape, local_range, k, alpha, beta) <NEW_LINE> return res
Returns estimated impact of input of LRN layer on output of network. :param Numlike output: estimated impact of output of layer on output of network in shape (batch_size, number of channels, height, width) :param Numlike activation: estimated activation of input :param inp...
625941d456b00c62f0f1485e
def history(self, *, limit=100, before=None, after=None, around=None, reverse=None): <NEW_LINE> <INDENT> return HistoryIterator(self, limit=limit, before=before, after=after, around=around, reverse=reverse)
Return an :class:`AsyncIterator` that enables receiving the destination's message history. You must have :attr:`~.Permissions.read_message_history` permissions to use this. All parameters are optional. Parameters ----------- limit: Optional[int] The number of messages to retrieve. If ``None``, retrieves ever...
625941d45510c4643540f5e5
def set_title(title): <NEW_LINE> <INDENT> Backend.set_title(title)
set_title(title) Sets the text in the title bar of the current window. :param str title: The text to put in the title bar
625941d567a9b606de4a80bd
def join_bigrams_with_replacements( s: Iterable[Iterable['str']], replacements=lambda w, default: default) -> str: <NEW_LINE> <INDENT> s = iter(s) <NEW_LINE> first = next(s, None) <NEW_LINE> if first is None: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> first = replacements(" ".join(first), first) <NEW_LINE> strin...
Function to join a list of bigrams back into a sentence taking into account unigram replacements for bigrams. working version: 1.0 # does not work with generator input skip = False string = "" n = len(s) for i, w in enumerate(s): if skip: skip = False if i == n-1: string = string + " " ...
625941d5711fe17d8254256d
def parse_std_url(url): <NEW_LINE> <INDENT> prefix, _, basename = url.rpartition('/') <NEW_LINE> basename, _, _ = basename.rpartition('.') <NEW_LINE> bbs, _, board = prefix.rpartition('/') <NEW_LINE> bbs = bbs[1:] <NEW_LINE> return bbs, board, basename
Parse standard ptt url >>> parse_std_url('https://www.ptt.cc/bbs/Gossiping/M.1512057611.A.16B.html') ('https://www.ptt.cc/bbs', 'Gossiping', 'M.1512057611.A.16B')
625941d5442bda511e8be61a
def dicom_to_nifti_mt(dicom_dir, mton_name='mton.nii.gz', mtoff_name='mtoff.nii.gz'): <NEW_LINE> <INDENT> dicoms = [] <NEW_LINE> for f in os.listdir(dicom_dir): <NEW_LINE> <INDENT> filename = os.path.join(dicom_dir, f) <NEW_LINE> dicoms.append((filename, dicom.read_file(filename))) <NEW_LINE> <DEDENT> min_sar, max_sar ...
Convert a directory of DICOM images containing both MT/on and MT/off to NIFTI_GZ.
625941d53617ad0b5ed680fb
def generate_anchors(scales, ratios, shape, feature_stride, anchor_stride): <NEW_LINE> <INDENT> scales_copy = scales.copy() <NEW_LINE> scales, ratios = np.meshgrid(np.array(scales), np.array(ratios)) <NEW_LINE> scales = scales.flatten() <NEW_LINE> ratios = ratios.flatten() <NEW_LINE> scales = np.append(scales, scales_c...
scales: 1D array of anchor sizes in pixels. Example: [32, 64, 128] ratios: 1D array of anchor ratios of width/height. Example: [0.5, 1, 2] shape: [height, width] spatial shape of the feature map over which to generate anchors. feature_stride: Stride of the feature map relative to the image in pixels. anchor_str...
625941d5d58c6744b4257e63
def unset_max_noutput_items(self): <NEW_LINE> <INDENT> return _ccsds_swig.ldpc_decoder_sptr_unset_max_noutput_items(self)
unset_max_noutput_items(ldpc_decoder_sptr self)
625941d55166f23b2e1a535d
def __init__(self, config, input_dim, n_data, attack): <NEW_LINE> <INDENT> super().__init__(config) <NEW_LINE> if config.optimizer == "ekfac": <NEW_LINE> <INDENT> print("[!] Optimizer: EKFAC") <NEW_LINE> self.layer_collection = lc.LayerCollection(mode="ekfac") <NEW_LINE> <DEDENT> elif config.optimizer == "kfac": <NEW_L...
Initialize a class Model. :param config: Configuration Bundle. :param input_dim: int :param n_data: int
625941d5046cf37aa974cf4b
def test_objectFromJSONText_badInput(self) -> None: <NEW_LINE> <INDENT> self.assertRaises(JSONDecodeError, objectFromJSONText, "foo}")
:func:`objectFromJSONText` raises :exc:`JSONDecodeError` then given invalid JSON text.
625941d5cc0a2c11143dd095
def test_bad_last_checked(self): <NEW_LINE> <INDENT> config = get_jigconfig(self.gitrepodir) <NEW_LINE> config.set('jig', 'last_checked_for_updates', 'bad') <NEW_LINE> set_jigconfig(self.gitrepodir, config) <NEW_LINE> last_check = last_checked_for_updates(self.gitrepodir) <NEW_LINE> self.assertEqual(0, last_check)
If the repo has a bad last checked value.
625941d55fc7496912cc3b82
def changes_between(lhs, rhs): <NEW_LINE> <INDENT> changes = [] <NEW_LINE> if lhs == rhs: <NEW_LINE> <INDENT> return changes <NEW_LINE> <DEDENT> changes.extend(_local_changes(lhs, rhs)) <NEW_LINE> removed_children = _new_in_rhs(rhs.children, lhs.children) <NEW_LINE> changes.extend(map(_data_for_delete, removed_children...
Main entry point for this library. Recursively return a list of changes between the lhs and rhs. lhs and rhs should be FrozenNodes. This also accounts for reordering nodes, including moves due to subpart renames.
625941d5cb5e8a47e48b7cad
def get_version(): <NEW_LINE> <INDENT> return '.'.join(map(str, VERSION))
Return the Juju GUI server version as a string.
625941d54f6381625f114c40
def getSettings(print=True): <NEW_LINE> <INDENT> config_dict = {} <NEW_LINE> for entry in ['rhapsody_local_folder', 'rhapsody_training_dataset', 'EVmutation_local_folder', 'EVmutation_metrics']: <NEW_LINE> <INDENT> config_dict[entry] = pd.SETTINGS.get(entry) <NEW_LINE> <DEDENT> def_clsfs = getDefaultClassifiers() <NEW_...
Returns and prints essential information about the current Rhapsody configuration, such as the location of working directory and default classifiers
625941d5442bda511e8be61b
def __init__(self, group=None): <NEW_LINE> <INDENT> pygame.sprite.Sprite.__init__(self, group) <NEW_LINE> characterSurf = pygame.Surface((64, 64)) <NEW_LINE> pygame.draw.rect(characterSurf, (0, 255, 128), ((0, 0), (64, 64))) <NEW_LINE> pygame.draw.circle(characterSurf, (255, 0, 0), (32, 32), 32) <NEW_LINE> self.image =...
Initialise CharacterSprite object.
625941d5e5267d203edcdea0
def probability_of_measurement(self, measurement, predicted_measurement): <NEW_LINE> <INDENT> dd = predicted_measurement[0]-measurement[0] <NEW_LINE> dalpha = predicted_measurement[1]-measurement[1] <NEW_LINE> if dalpha>=0: <NEW_LINE> <INDENT> dalpha = dalpha%(2*pi) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dalpha ...
Given a measurement and a predicted measurement, computes probability.
625941d55fcc89381b1e18c5
def setup_cluster(api_client): <NEW_LINE> <INDENT> create_tiller_service_accounts(api_client) <NEW_LINE> run(["helm", "init", "--service-account=tiller"]) <NEW_LINE> use_gpus = cluster_has_gpu_nodes(api_client) <NEW_LINE> if use_gpus: <NEW_LINE> <INDENT> logging.info("GPUs detected in cluster.") <NEW_LINE> <DEDENT> els...
Setup a cluster. This function assumes kubectl has already been configured to talk to your cluster. Args: use_gpus
625941d526238365f5f0f075
def set_linecolor(self, color): <NEW_LINE> <INDENT> self.linecolor = GnuplotDraw.line_colors[color]
Change the color of lines.
625941d5be383301e01b5689
def atend_pt(self): <NEW_LINE> <INDENT> if self.normsubpaths: <NEW_LINE> <INDENT> return self.normsubpaths[-1].atend_pt() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise NormpathException("cannot return last point of empty path")
return coordinates of the end of last subpath in normpath in pts
625941d5fb3f5b602dac389a
@contextlib.contextmanager <NEW_LINE> def with_site_configuration_context(domain="test.localhost", configuration=None): <NEW_LINE> <INDENT> site, __ = Site.objects.get_or_create(domain=domain, name=domain) <NEW_LINE> site_configuration, created = SiteConfiguration.objects.get_or_create( site=site, defaults={"enabled": ...
A function to get a context manger to run a test with a configuration enabled. Args: domain (str): domain name for the test site. configuration (dict): configuration to use for the test site.
625941d515fb5d323cde0d16
def _detect_hardlinks(self, testdir): <NEW_LINE> <INDENT> hl_source = testdir.append("hardlinked_file1") <NEW_LINE> hl_dir = testdir.append("hl") <NEW_LINE> hl_dir.mkdir() <NEW_LINE> hl_dest = hl_dir.append("hardlinked_file2") <NEW_LINE> hl_source.touch() <NEW_LINE> try: <NEW_LINE> <INDENT> hl_dest.hardlink(hl_source.p...
Set self.hardlinks to true iff hard linked files can be made
625941d5d268445f265b5073
def function(self, simulation, period): <NEW_LINE> <INDENT> period = period.start.offset('first-of', 'month').period('year') <NEW_LINE> frag_exon = simulation.calculate('frag_exon', period) <NEW_LINE> frag_impo = simulation.calculate('frag_impo', period) <NEW_LINE> arag_exon = simulation.calculate('arag_exon', period) ...
Revenus agricoles 'ind' frag_exon (f5hn, f5in, f5jn) frag_impo (f5ho, f5io, f5jo) arag_exon (f5hb, f5ib, f5jb) arag_impg (f5hc, f5ic, f5jc) arag_defi (f5hf, f5if, f5jf) nrag_exon (f5hh, f5ih, f5jh) nrag_impg (f5hi, f5ii, f5ji) nrag_defi (f5hl, f5il, f5jl) nrag_ajag (f5hm, f5im, f5jm)
625941d57047854f462a160d
def decrypt_data(data): <NEW_LINE> <INDENT> vault = Vault(settings.SECRET_KEY) <NEW_LINE> return vault.load(data)
Decrypt the incoming data using SECRET_KEY. :param data: string data to be decrypted :returns: vault decrypted data as string
625941d54e4d5625662d45db
def parse_recipe_file(self, fn, appends=True, appendlist=None, config_data=None): <NEW_LINE> <INDENT> if self.tracking: <NEW_LINE> <INDENT> self.run_command('enableDataTracking') <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> if appends and appendlist == []: <NEW_LINE> <INDENT> appends = False <NEW_LINE> <DEDENT> if conf...
Parse the specified recipe file (with or without bbappends) and return a datastore object representing the environment for the recipe. Parameters: fn: recipe file to parse - can be a file path or virtual specification appends: True to apply bbappends, False otherwise appendlist: optional list of bba...
625941d5e8904600ed9f2134
def knight(): <NEW_LINE> <INDENT> limbs = ['other leg', 'leg', 'other arm', 'arm'] <NEW_LINE> combat = False <NEW_LINE> while limbs: <NEW_LINE> <INDENT> if not combat: <NEW_LINE> <INDENT> print('None shall pass.') <NEW_LINE> <DEDENT> user_action = input('What do you do? ') <NEW_LINE> if user_action.lower() == 'attack':...
Some vigorous exercise. (None)
625941d53539df3088e2e550
def extractGoogleNewsHeadlines(): <NEW_LINE> <INDENT> url = "https://news.google.com/?sdm=HEADLINE&authuser=0" <NEW_LINE> response = requests.get(url) <NEW_LINE> html = response.content <NEW_LINE> soup = BeautifulSoup(html, 'html.parser') <NEW_LINE> attributeA = soup.find_all('span', { "class" : "titletext" }) <NEW_LIN...
Scrapes the headlines from the Google News homepage (headline view) and returns all headlines. :param: none :returns: list as strings of headlines
625941d521bff66bcd684b56
def vlan_normal(self): <NEW_LINE> <INDENT> s1 = self.net.switches[ 0 ] <NEW_LINE> h1 = self.net.hosts[ 0 ] <NEW_LINE> h2 = self.net.hosts[ 1 ] <NEW_LINE> info("\n\n\n########## Test Case 1 - Adding VLAN and Ports ##########\n") <NEW_LINE> info("### Adding VLAN200 and ports 1,2 to bridge br0.", "Port1:access (tag=200), ...
H1[h1-eth0]<--->[1]S1[2]<--->[h2-eth0]H2 1.1 Add VLAN 200 to global VLAN table on Switch 1.2 Add port 1 and 2 with tag 200 on Switch (access mode) 1.3 Test Ping - should work
625941d5283ffb24f3c55b05
def remove_extra_words(): <NEW_LINE> <INDENT> global unique_words, word_frequency <NEW_LINE> unique_words = old_unique_words <NEW_LINE> word_frequency = old_word_frequency <NEW_LINE> print("Extra words are removed from the word list")
This function is used to remove the extra words added
625941d5be8e80087fb20e46
def main(): <NEW_LINE> <INDENT> print(parser("2.56+5*9/1+9*7"))
compute input line
625941d5a219f33f34628b6c
def _gradient_log_likelihood(self, coef): <NEW_LINE> <INDENT> train_label = self._encode_label(self.train_label) <NEW_LINE> n = self.train_data.shape[0] <NEW_LINE> gradient = np.zeros(coef.shape) <NEW_LINE> for i in range(n): <NEW_LINE> <INDENT> data = self.train_data[i].reshape(self.train_data[i].shape[0], 1) <NEW_LIN...
Calculate hypothesis :param coef: The matrix parameters of our hypothesis :return: gradient of log-likelihood with respect to coef
625941d530dc7b7665901b6a