code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def is_approx_distinct( self, column: str, assertion: Callable[[float], bool] = is_approx_one, hint: Optional[str] = None, ) -> "CheckWithLastConstraintFilterable": <NEW_LINE> <INDENT> return self._add_filterable_constraint( lambda filter_: approx_distinctness_constraint(column, assertion, filter_, hint) )
Creates a constraint that asserts that a column is distinct Parameters ---------- column: Column to run the assertion on assertion: Callable that receives a float input parameter and returns a boolean hint: A hint to provide additional context why a constraint could have failed
625941e24c3428357757c6ea
def add_planets_to_vicinity(vicinity, num_planets, gsd): <NEW_LINE> <INDENT> print("Adding", num_planets, "planets to the following systems:", vicinity) <NEW_LINE> acceptable_star_types_list = [ star_types_real, (fo.starType.noStar,), (fo.starType.neutron,), (fo.starType.blackHole,), ] <NEW_LINE> free_orbits_map = [] <...
Adds the specified number of planets to the specified systems.
625941e2ab23a570cc25054a
def _global_replace(self, original, replacement): <NEW_LINE> <INDENT> for referrer in gc.get_referrers(original): <NEW_LINE> <INDENT> if type(referrer) is not dict: <NEW_LINE> <INDENT> if VERBOSE: <NEW_LINE> <INDENT> log.info(" Skipping referrer %r" % referrer) <NEW_LINE> <DEDENT> continue <NEW_LINE> <DEDENT> if refer...
Replace all references to object 'original' with object 'replacement' in all dictionaries (i.e. module and class scopes for functions / methods). Based on Labix mocker's global_replace().
625941e267a9b606de4a827c
def test_one_nested_sublist_and_integers(self): <NEW_LINE> <INDENT> self.assertEqual(count_even([[2], 3, [4]]), 2, "count_even should return the number of even " + "integers in nested sublists and in the list passed " + "in.")
Test count_even on a list with at most one level of nested sublists in it mixed with integers.
625941e221a7993f00bc80bb
def u(self, point = -1): <NEW_LINE> <INDENT> return self.solution('u', point)
The axial velocity [m/s]
625941e297e22403b379d360
def test_post_order_wrong_menu_id(client): <NEW_LINE> <INDENT> resp = post_json_header(client, '/v1/users/orders', { "menu_id": 2, "quantity": 15}, headers={'Authorization': 'Bearer ' + signin(client)}) <NEW_LINE> assert resp.status_code == 404 <NEW_LINE> assert b'Menu Item does not exist' in resp.data
test posting order
625941e2e8904600ed9f22f7
def design_matrix(data: pd.DataFrame, categorical: list, numeric: list, base: dict, outcome: str): <NEW_LINE> <INDENT> data = data.copy() <NEW_LINE> for cat in categorical: <NEW_LINE> <INDENT> for col in sorted(set([i for row in data[cat].str.split(";") for i in row])): <NEW_LINE> <INDENT> data[cat+"_"+text_clean(col)]...
Create design matrix for regressions data: Cleaned pandas DataFrame categorical / numeric: Lists of separate variable types base: Base/omitted level for dummy variables outcome: String name of outcome variable
625941e2cc0a2c11143dd256
def decode_replay_game_events(contents): <NEW_LINE> <INDENT> decoder = BitPackedDecoder(contents, protocol.typeinfos) <NEW_LINE> for event in _decode_event_stream(decoder, protocol.game_eventid_typeid, protocol.game_event_types, decode_user_id=True): <NEW_LINE> <INDENT> yield event
Decodes and yields each game event from the contents byte string.
625941e20a366e3fb873ebe2
def bloquearItem(idv=None): <NEW_LINE> <INDENT> if(idv): <NEW_LINE> <INDENT> version=getVersionId(idv) <NEW_LINE> init_db() <NEW_LINE> version.estado="Bloqueado" <NEW_LINE> session.merge(version) <NEW_LINE> session.commit() <NEW_LINE> shutdown_session() <NEW_LINE> return True <NEW_LINE> <DEDENT> return False
Bloquea un item, recibe el id de la version del item
625941e276d4e153a657eef7
def image_upload_url(recipe_id) -> str: <NEW_LINE> <INDENT> return reverse("recipe:recipe-upload-image", args=[recipe_id])
Return url for recipe image upload
625941e2f8510a7c17cf9ac4
def verify(self, base_url): <NEW_LINE> <INDENT> url = base_url + self.db_url <NEW_LINE> body = self._curl(url) <NEW_LINE> if body is None: <NEW_LINE> <INDENT> return [('fail','No response', url)] <NEW_LINE> <DEDENT> elif len(body) == 0: <NEW_LINE> <INDENT> return [('fail','Empty Response', url)] <NEW_LINE> <DEDENT> try...
Ensures body is valid JSON with a key 'id' and a key 'randomNumber', both of which must map to integers
625941e20c0af96317bb85ad
def get_cell_vertices(self, *args, **kwargs): <NEW_LINE> <INDENT> nn = None <NEW_LINE> if kwargs: <NEW_LINE> <INDENT> if "node" in kwargs: <NEW_LINE> <INDENT> nn = kwargs.pop("node") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> i = kwargs.pop("i") <NEW_LINE> j = kwargs.pop("j") <NEW_LINE> <DEDENT> <DEDENT> if len(args...
Method to get a set of cell vertices for a single cell used in the Shapefile export utilities and plotting code :param node: (int) node number :param i: (int) cell row number :param j: (int) cell column number Returns ------- list of x,y cell vertices
625941e24f6381625f114e01
def evaluateCoherence(self,v1,v2,use_cwt=True): <NEW_LINE> <INDENT> assert len(v1)==len(v2) <NEW_LINE> if not use_cwt: <NEW_LINE> <INDENT> self.f,self.C = coherence(v1,v2, fs=self.sampleFreq, nperseg=self.windowLength, nfft=2 * self.windowLength, noverlap=self.windowLength//4) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDE...
Returns average coherence between current v and v_av data vectors. Parameters ---------- v1 : ndarray Vector. v2 : ndarray Vector. Returns ------- avg_coh : float
625941e2462c4b4f79d1da94
def _MakeObserver(numpy_array): <NEW_LINE> <INDENT> def Closure(caller, event): <NEW_LINE> <INDENT> foo = numpy_array <NEW_LINE> <DEDENT> return Closure
Internal function used to attach a numpy array to a vtk array
625941e230c21e258bdfa865
def change_id(self, new_id_for_id): <NEW_LINE> <INDENT> if len(set(new_id_for_id.values())) < len(new_id_for_id): <NEW_LINE> <INDENT> raise ValueError('each id must be unique.') <NEW_LINE> <DEDENT> for new_id in new_id_for_id.values(): <NEW_LINE> <INDENT> if self.ping(new_id): <NEW_LINE> <INDENT> raise ValueError('id {...
Changes the id of the specified motors (each id must be unique on the bus).
625941e24c3428357757c6eb
def display(values): <NEW_LINE> <INDENT> width = 1+max(len(values[s]) for s in boxes) <NEW_LINE> line = '+'.join(['-'*(width*3)]*3) <NEW_LINE> for r in rows: <NEW_LINE> <INDENT> print(''.join(values[r+c].center(width)+('|' if c in '36' else '') for c in cols)) <NEW_LINE> if r in 'CF': print(line) <NEW_LINE> <DEDENT> pr...
Display the values as a 2-D grid. Args: values(dict): The sudoku in dictionary form
625941e2be8e80087fb21002
def setUp(self): <NEW_LINE> <INDENT> self.working_dir = mkdtemp() <NEW_LINE> deblur_working_dir = join(self.working_dir, "deblur_working_dir") <NEW_LINE> makedirs(deblur_working_dir) <NEW_LINE> self.test_data_dir = join(dirname(abspath(__file__)), 'data') <NEW_LINE> self.seqs_s1_fp = join(self.test_data_dir, 'seqs_s1.f...
Create working directory and two FASTA input files corresponding to two samples (s1 and s2). Each input file contains 120 sequences, of which 100 are 16S amplicons (ART simulator), 10 are chimeric sequences (Grinder) and 10 are PhiX artifacts (ART). The 100 amplicon sequences intend to evenly represent a community of 1...
625941e28a349b6b435e8538
def clickedOpenHud(x,y): <NEW_LINE> <INDENT> if ( y > SCREEN_HEIGHT-MARGIN_HEIGHT ) and ( x > MARGIN_WIDTH ) and ( x < SCREEN_WIDTH-MARGIN_WIDTH ): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False
Takes coordinate of click, determines if open hud button.
625941e2925a0f43d254a240
def AddSliceTags(self, per_slice=2): <NEW_LINE> <INDENT> if not self.slice_type_ids: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for slice_id in self.slice_ids: <NEW_LINE> <INDENT> slice = self.api.GetSlices([slice_id])[0] <NEW_LINE> for i in range(per_slice): <NEW_LINE> <INDENT> for tag_type_id in random.sample(sel...
Add a number of random slices per site.
625941e24a966d76dd5513d8
def get_episode_dict_with_matching_checksums(self, checksum): <NEW_LINE> <INDENT> episode_dict = {} <NEW_LINE> for implementation in self.dictionary: <NEW_LINE> <INDENT> for key in self.dictionary[implementation]: <NEW_LINE> <INDENT> for movieclip in self.dictionary[implementation][key]: <NEW_LINE> <INDENT> if moviecli...
This function searches for the given checksum in the internal data structures. It returns two lists as a tuple. The first being a list of episodes. The second being a list of movie clips which match the checksum.
625941e2287bf620b61d3e27
def update(self, state, action, next_state, reward): <NEW_LINE> <INDENT> if len(self.getLegalActions(next_state)) == 0: <NEW_LINE> <INDENT> utility = reward <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> possible_future_reward = [self.getQValue(next_state, next_action) for next_action in self.getLegalActions(next_state)...
The parent class calls this to observe a state = action => nextState and reward transition. You should do your Q-Value update here NOTE: You should never call this function, it will be called on your behalf
625941e2cb5e8a47e48b7e6a
def make_definition( enum: Enum, *, primary_type: typing.Optional[PrimaryType] = None, value_type: typing.Optional[str] = None, ) -> EnumDefinition: <NEW_LINE> <INDENT> if isinstance(enum, EnumDefinition): <NEW_LINE> <INDENT> return enum <NEW_LINE> <DEDENT> if isinstance(enum, py_enum.EnumMeta): <NEW_LINE> <INDENT> enu...
Make :class:`EnumDefinition` instance from various types This function is used to convert various kinds of enum definitions (standard Python :class:`enum.Enum` types, :class:`dict` instances etc.) into an :class:`EnumDefinition` instance usable by the code generator. It allows for an user to provide a simpler enum def...
625941e24f88993c3716c429
def updt_rel_rpy_ini(self): <NEW_LINE> <INDENT> self.updt_rel_rpy() <NEW_LINE> self.roll_rel_ini = self.roll_rel <NEW_LINE> self.pitch_rel_ini = self.pitch_rel <NEW_LINE> self.yaw_rel_ini = self.yaw_rel
Update initial relative rpy
625941e2ab23a570cc25054b
def _args_kwargs(params): <NEW_LINE> <INDENT> args, kwargs = [], {} <NEW_LINE> parse_kwargs = False <NEW_LINE> for param in params: <NEW_LINE> <INDENT> _valid_param(param) <NEW_LINE> if '=' in param: <NEW_LINE> <INDENT> parse_kwargs = True <NEW_LINE> key, value = param.split('=', 1) <NEW_LINE> if value: <NEW_LINE> <IND...
Separate args and kwargs from params. `args` must all be at first and `kwargs` at the end Space are forbidden as well as incomplete kwargs without name. >>> expected = (['a', 'b', 'c'], {'e': 'f', 'g': 'h'}) >>> _args_kwargs(['a', 'b', 'c', 'e=f', 'g=h']) == expected True >>> _args_kwargs(['a', 'b', 'c']) == (['a',...
625941e20a366e3fb873ebe3
def followAUser(self, _response, sessionKey, userId): <NEW_LINE> <INDENT> _os = Serializer() <NEW_LINE> _os.startToWrite() <NEW_LINE> _os.writeByte(RmiDataType.RmiCall) <NEW_LINE> _os.writeString(self.name) <NEW_LINE> _os.writeString('followAUser') <NEW_LINE> if _response: <NEW_LINE> <INDENT> _msgId = self.getMsgId() <...
:type _response: IPostOper_Followauser_Response :type sessionKey: str :type userId: str
625941e2b5575c28eb68e3c9
def predict(self, arriving: bool, hour: int) -> List[ModelOutput]: <NEW_LINE> <INDENT> dt = datetime.datetime.now() <NEW_LINE> eastern = pytz.timezone('US/Eastern') <NEW_LINE> est_hour = eastern.localize(dt).hour <NEW_LINE> current_hour = est_hour <NEW_LINE> station_infos = self.station_service.get_capacity() <NEW_LINE...
Predict the best station to use :param arriving: true = arriving :param hour: :return: Sorted list where entry[0] is the best
625941e2dd821e528d63b56b
@with_config(DEBUG=True, ASSETS_DEBUG=True) <NEW_LINE> def test_unmergable(): <NEW_LINE> <INDENT> b = Bundle('s1', 's2', Bundle('s3', debug=False, filters=css, output="bar"), output='foo', filters=js) <NEW_LINE> jl = bundle_to_joblist(b) <NEW_LINE> assert len(jl) == 3 <NEW_LINE> assert 's1' in jl and 's2' in jl <NEW_LI...
A subbundle that is unmergable will be pulled into a separate job.
625941e2d7e4931a7ee9e2e4
def getColumns(self, x, limit=100, offset=0): <NEW_LINE> <INDENT> if x is None: <NEW_LINE> <INDENT> uri = '/column' <NEW_LINE> for result in self._GET_paginated(uri, limit=limit, offset=offset): <NEW_LINE> <INDENT> yield Column(**result) <NEW_LINE> <DEDENT> <DEDENT> elif isinstance(x, (list, tuple)): <NEW_LINE> <INDENT...
Get the columns defined in Synapse either (1) corresponding to a set of column headers, (2) those for a given schema, or (3) those whose names start with a given prefix. :param x: a list of column headers, a Table Entity object (Schema/EntityViewSchema), a Table's Synapse ID, or a string prefix :...
625941e24e4d5625662d4798
def testRound3(self): <NEW_LINE> <INDENT> inputNum = 1.3426789 <NEW_LINE> numDecimals = 2 <NEW_LINE> expected = 1.34 <NEW_LINE> actual = decimalRound(inputNum, numDecimals) <NEW_LINE> self.assertEqual(actual, expected)
Test rounding number (down) to given decimal point
625941e2462c4b4f79d1da95
def __init__(self, number_of_neurons: int, activation_function, inputs=None): <NEW_LINE> <INDENT> self.uid = None <NEW_LINE> self.number_of_neurons = number_of_neurons <NEW_LINE> self.activation_function = activation_function <NEW_LINE> self.inputs = inputs <NEW_LINE> self.shape = None <NEW_LINE> self.data_shape = None...
Create a layer with Layer(number of neurons, activation function)
625941e257b8e32f52483863
def portal_image_folders_id_delete(self, id, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('callback'): <NEW_LINE> <INDENT> return self.portal_image_folders_id_delete_with_http_info(id, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (data) = self.portal_image_f...
Delete a model instance by {{id}} from the data source. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.porta...
625941e24e696a04525c9812
def _set_config(self, config=None): <NEW_LINE> <INDENT> if not config: <NEW_LINE> <INDENT> config = {} <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.config = self.componentmodel(config) <NEW_LINE> try: <NEW_LINE> <INDENT> name = self.config.name <NEW_LINE> self.log("Name set to: ", name, lvl=verbose) <NEW_LINE> <DE...
Set this component's initial configuration
625941e230dc7b7665901d28
def parse_graylog_response(graylog_response): <NEW_LINE> <INDENT> reader = csv.reader(graylog_response.iter_lines(), delimiter=',') <NEW_LINE> try: <NEW_LINE> <INDENT> header = reader.next() <NEW_LINE> <DEDENT> except StopIteration: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> dicts = [] <NEW_LINE> for row in reader: <...
Parse the graylog response as a list of dictionaries in reverse time order Args: graylog_response(response object): Response returned by graylog_request() Returns: list of dict: Graylog search results as a list of dictionaries sorted in reverse time order.
625941e24d74a7450ccd458a
def __init__( self, controller, msn ): <NEW_LINE> <INDENT> Plugin.Plugin.__init__( self, controller, msn ) <NEW_LINE> self.description = _( 'View or remove the annoying colors in nicknames' ) <NEW_LINE> self.authors = { 'Roger Duran' : 'RogerDuran at gmail dot com', 'Mohr Tutchy' : 'mohr dot tutchy at gmail dot com'} <...
Contructor
625941e25e10d32532c5f2eb
def list_view(model=None, queryset=None, paginate=False, page_size='page_size', paginate_orphans=0, page_kwarg='page', allow_empty=True, methods=None): <NEW_LINE> <INDENT> def decorate(func): <NEW_LINE> <INDENT> @wraps(func) <NEW_LINE> def wrapper(request, *args, **kwargs): <NEW_LINE> <INDENT> qs = _get_qs_or_404(model...
A list view. Note unlike Django's ListView this does not return a rendered template (see *template_list_view* for that). This decorator requires either *model* or *queryset* (but not both) to be passed to it. The decorated view will be called with a keyword argument whose key is the "plural name" of the model...
625941e23d592f4c4ed1d429
def get_connected_components_from_bus(self, bus_name): <NEW_LINE> <INDENT> components = {} <NEW_LINE> components["generators"] = self.generators_df.loc[ self.generators_df.bus == bus_name ] <NEW_LINE> components["loads"] = self.loads_df.loc[self.loads_df.bus == bus_name] <NEW_LINE> components["charging_points"] = self....
Returns dictionary of components connected to specified bus. Parameters ---------- bus_name : str Identifier of bus to get connected components for. Returns ------- dict of :pandas:`pandas.DataFrame<DataFrame>` Dictionary of connected components with keys 'generators', 'loads', 'charging_points', 'storag...
625941e2be383301e01b5844
def bellman_ford(graph, start_node): <NEW_LINE> <INDENT> A = np.array(graph) <NEW_LINE> G = nx.from_numpy_matrix(A, create_using=nx.DiGraph()) <NEW_LINE> try: <NEW_LINE> <INDENT> predescesor, distance = nx.bellman_ford(G, start_node) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return [x for x in range(len(graph)-2)...
return predecessors and shortest path lengths on shortest path in weighted graph https://networkx.github.io/documentation/networkx-1.9/reference/generated/networkx.algorithms.shortest_paths.weighted.bellman_ford.html
625941e25fcc89381b1e1a87
def test_bookmark_popular_user(self): <NEW_LINE> <INDENT> self._get_good_request(content=True, second_bmark=True) <NEW_LINE> res = self.testapp.get('/admin/redirect/' + GOOGLE_HASH) <NEW_LINE> res = self.testapp.get('/admin/redirect/' + GOOGLE_HASH) <NEW_LINE> res = self.testapp.get('/api/v1/admin/bmarks/popular?api_ke...
Test that we can get list of bookmarks ordered by clicks
625941e2d4950a0f3b08c70f
def result(self, state, action): <NEW_LINE> <INDENT> return action
Apply the chosen action
625941e2dd821e528d63b56c
def collect_results(self): <NEW_LINE> <INDENT> return self.dj_hook.query(self.job_param_def)
Prints the results of the workflow
625941e2b7558d58953c52d2
def bulk_Suggest_Data(self, index_name, index_type, list): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ACTIONS = [] <NEW_LINE> for line in list: <NEW_LINE> <INDENT> action = { "_index": index_name, "_id": line["id"], "_source": { "name": line.get("name", "NULL"), "describe": line.get("describe", "NULL"), "namekeyword"...
用bulk将批量数据存储到es :return:
625941e21f5feb6acb0c4f0f
def _index_object(self, documentId, obj, threshold=None, attr=''): <NEW_LINE> <INDENT> returnStatus = 0 <NEW_LINE> datum = self._get_object_datum(obj, attr) <NEW_LINE> if datum is not _marker: <NEW_LINE> <INDENT> datum = int(bool(datum)) <NEW_LINE> <DEDENT> oldDatum = self._unindex.get(documentId, _marker) <NEW_LINE> i...
index and object 'obj' with integer id 'documentId'
625941e2f9cc0f698b1409be
@task <NEW_LINE> def ltunnel(tunnel=None): <NEW_LINE> <INDENT> tc.check_host_connection(env, 'ltunnel') <NEW_LINE> tc.check_tunnel(tunnel_config, tunnel) <NEW_LINE> config = tunnel_config[tunnel] <NEW_LINE> local_tunnel_ssh(env, config['local'], config['domain'], config['remote'])
make a remotely-visible port accessible locally
625941e266673b3332b92457
def merge_dicts(dict_a, dict_b): <NEW_LINE> <INDENT> merge_result = dict_a.copy() <NEW_LINE> for key in dict_b: <NEW_LINE> <INDENT> if key in dict_a and isinstance(dict_a[key], dict) and isinstance(dict_b[key], dict): <NEW_LINE> <INDENT> merge_result[key] = merge_dicts(dict_a[key], dict_b[key]) <NEW_LINE> <DEDENT> else...
Performs a recursive merge of two dicts dict_a and dict_b, wheras dict_b always overwrites the values of dict_a :param dict_a: the first dictionary. This is the weak dictionary which will always be overwritten by dict_b (dict_a therefore is a default dictionary type :param dict_b: the second dictionary....
625941e267a9b606de4a827d
def __call__(self, request): <NEW_LINE> <INDENT> if not request.user.is_anonymous: <NEW_LINE> <INDENT> if not request.user.is_staff: <NEW_LINE> <INDENT> profile = request.user.profile <NEW_LINE> if not profile.profile_picture or not profile.bio: <NEW_LINE> <INDENT> if request.path not in [reverse('users:update'), rever...
Codigo ejecutado cada request, antes de la llamada al view.
625941e23317a56b8693a015
def _parse_qresult(self): <NEW_LINE> <INDENT> self._read_until(lambda line: line.startswith('Query:')) <NEW_LINE> while self.line: <NEW_LINE> <INDENT> regx = re.search(_QRE_ID_LEN, self.line) <NEW_LINE> qid = regx.group(1).strip() <NEW_LINE> qresult_attrs = { 'seq_len': int(regx.group(2)), 'program': self._meta.get('pr...
Parses a HMMER3 query block.
625941e2460517430c394542
def get_figure(self): <NEW_LINE> <INDENT> return self._fig
Returns a list representation figure (to make indexing, for example).
625941e2cc40096d61595d15
def remove_tag(tag_name): <NEW_LINE> <INDENT> cmd = 'git tag -d %s' % tag_name <NEW_LINE> stat, output = get_status_text_output(cmd) <NEW_LINE> if not stat: raise ShellCmdErrorException('error: ' + cmd)
Remove the tag of name 'tag_name'
625941e2796e427e537b098f
def post(self, user, data): <NEW_LINE> <INDENT> return super(CourseAPI, self).post(user, data)
The POST HTTP method
625941e226068e7796caf0aa
def test_empty(pool): <NEW_LINE> <INDENT> assert pool.empty() <NEW_LINE> r = pool.get_resource() <NEW_LINE> assert pool.empty() <NEW_LINE> r.close() <NEW_LINE> assert not pool.empty()
Test if pool is empty.
625941e2d7e4931a7ee9e2e5
@FLASK_APP.route('/shoppinglists') <NEW_LINE> def shopping_list(): <NEW_LINE> <INDENT> user = get_user() <NEW_LINE> shopping_lists = user.shopping_lists <NEW_LINE> return render_template('shoppinglists.html', shopping_lists=shopping_lists)
View Shopping lists
625941e276d4e153a657eef8
def get_cont_of_weibo(mid): <NEW_LINE> <INDENT> url = base_url.format(mid) <NEW_LINE> html = get_page(url, user_verify=False) <NEW_LINE> if html: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> html = json.loads(html, encoding='utf-8').get('data').get('html') <NEW_LINE> cont = filters.text_filter(html) <NEW_LINE> <DEDENT>...
:param mid: weibo's mid :return: all cont of the weibo
625941e2fbf16365ca6f6591
def find_by_query(self, query, access_args=None): <NEW_LINE> <INDENT> qual_ds_name = self._get_datastore_name() <NEW_LINE> pqb = PostgresQueryBuilder(query, qual_ds_name) <NEW_LINE> if self.profile == DataStore.DS_PROFILE.RESOURCES: <NEW_LINE> <INDENT> pqb.where = self._add_access_filter(access_args, qual_ds_name, pqb....
Find resources given a datastore query expression dict. @param query a dict representation of a datastore query @retval list of resource ids or resource objects matching query (dependent on id_only value)
625941e21f037a2d8b9465c3
def get_file_path(input_file, config_file): <NEW_LINE> <INDENT> return os.path.join(os.path.dirname(os.path.abspath(input_file)), config_file)
Good for getting the current path of the python script by using __file__ and then joining a config name to it.
625941e28a43f66fc4b54427
def bounce(text): <NEW_LINE> <INDENT> time.sleep(0.05)
argument(s): text :: text. side effects: step by step, change the font size of t from 5 to 32. return value: none.
625941e28e05c05ec3eea73e
def get_example_tree(): <NEW_LINE> <INDENT> retval = {"name":"parent","children":[]} <NEW_LINE> for i in range(10): <NEW_LINE> <INDENT> retval['children'].append({"name":"child " + str(i)}) <NEW_LINE> retval['children'][i]['children']=[] <NEW_LINE> for j in range(10): <NEW_LINE> <INDENT> retval['children'][i]['children...
generate a quick 100 leaf tree for demo purposes
625941e24527f215b584c819
def load_model(model_cls, config_name, exp_uid): <NEW_LINE> <INDENT> config = load_config(config_name) <NEW_LINE> model_uid = common.get_model_uid(config_name, exp_uid) <NEW_LINE> m = model_cls(config, name=model_uid) <NEW_LINE> m() <NEW_LINE> return m
Load a model. Args: model_cls: A sonnet Class that is the factory of model. config_name: A string indicating the name of config to parameterize the model. exp_uid: A string representing the unique id of experiment to be used in model. Returns: An instance of sonnet model.
625941e22ae34c7f2600d4f7
def destroy_all_by_project_and_user(self, context, project_id, user_id): <NEW_LINE> <INDENT> self._driver.destroy_all_by_project_and_user(context, project_id, user_id)
Destroy metadata associated with a project and user. Destroy all quotas, usages, and reservations associated with a project and user. :param context: The request context, for access checks. :param project_id: The ID of the project being deleted. :param user_id: The ID of the user being deleted.
625941e2a934411ee3751a5b
def simplex_vs_y(self, **kwargs): <NEW_LINE> <INDENT> file = self.filename + ".txt" <NEW_LINE> usecols = kwargs.pop("usecols", (0, 1)) <NEW_LINE> xlabel = kwargs.pop("xlabel", "x") <NEW_LINE> ylabel = kwargs.pop("ylabel", "y") <NEW_LINE> color = kwargs.pop("color", "g") <NEW_LINE> linestyle = kwargs.pop("linestyle", "-...
Plot 2 columns given a text file
625941e2be7bc26dc91cd9bf
def get_unresolved_run_targets(self, dataCache): <NEW_LINE> <INDENT> unresolved = [] <NEW_LINE> for target in self.run_names_index: <NEW_LINE> <INDENT> if target in dataCache.ignored_dependencies: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if self.run_names_index.index(target) in self.failed_rdeps: <NEW_LINE> <IN...
Return a list of runtime targets who's providers are unknown.
625941e232920d7e50b2859a
def fea_gen(self): <NEW_LINE> <INDENT> n = self.n <NEW_LINE> deg_list = degr_net(self.ajm) <NEW_LINE> graph = self.graph <NEW_LINE> state = self.sta_curr <NEW_LINE> ac_list = act_list(n, graph, state) <NEW_LINE> por_list = [ac / deg for deg, ac in zip(deg_list, ac_list)] <NEW_LINE> tri_list = trg_list(self.ajm) <NEW_LI...
"" features to descript influence: the active and inactive means of 1. Degree of each node: deg_ac, deg_ina 2. Number of each node’s neighbors that are active: nei_ac, nei_ina 3. Proportion of each node’s neighbors that are active: por_ac, por_ina 4. Number of triangles each node is involved: tri_ac, tri_ina totally 8 ...
625941e2d486a94d0b98e50d
def retrieve_csgo_stats_crashkid() -> dict: <NEW_LINE> <INDENT> cfg = configparser.ConfigParser() <NEW_LINE> cfg.read(local.LOCAL_API_KEYS_FILE) <NEW_LINE> if len(cfg.items()) > 0: <NEW_LINE> <INDENT> auth_key = cfg["steam"]["auth_key"] <NEW_LINE> userid = cfg["steam"]["userid"] <NEW_LINE> csgoid = cfg["steam"]["csgo_a...
Requests stats from the official Valve API
625941e2ec188e330fd5ab5e
def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> if hasattr(self, attr): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr...
Returns the model properties as a dict
625941e28a349b6b435e8539
def t_preprocessor(t): <NEW_LINE> <INDENT> t.lexer.lineno += 1
\#(.)*?\n
625941e21f037a2d8b9465c4
def add(self, characts_dict: Dict[str, Any]) -> None: <NEW_LINE> <INDENT> characts_dict['id'] = self.next_id <NEW_LINE> self.next_id += 1 <NEW_LINE> self.db.insert(characts_dict)
Receives a dictionary with string keys and any values and saves it. Returns nothing. :Dict[str, Any] characts_dict: Dictionary with file data to be saved. :NoneType retval: None
625941e25166f23b2e1a5520
def start_monitor_mode(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> subprocess.check_output(["./scripts/start_monitor_mode.sh"]) <NEW_LINE> <DEDENT> except subprocess.CalledProcessError: <NEW_LINE> <INDENT> print("Error: Could not start the monitor mode.")
Starts the WiFi monitor mode
625941e26e29344779a629d7
def test_advice(self): <NEW_LINE> <INDENT> self._test_page('/legal/advice')
It should return a 200 for advice page.
625941e2097d151d1a22321e
def add_particles_to_store(self, keys, attributes = [], values = []): <NEW_LINE> <INDENT> self._private.keys = None <NEW_LINE> self._private.set_of_keys = set([]) <NEW_LINE> self._private.version = -1 <NEW_LINE> self._private.particles.add_particles_to_store(keys, attributes, values)
Adds particles from to the subset, also adds the particles to the superset
625941e2e5267d203edce05f
def generate_triples_krf(self, path_to_triples_txt, path_to_output_file, microtheory=None): <NEW_LINE> <INDENT> with open(path_to_triples_txt, encoding="utf8") as f: <NEW_LINE> <INDENT> list_of_lines = f.readlines() <NEW_LINE> <DEDENT> out_f = open(path_to_output_file, "w+", encoding="utf8") <NEW_LINE> if microtheory i...
Generates a properly formatted krf file with triples in the given microtheory. :param path_to_triples_txt: The filepath to a text file of triples in the format: ('pred' 'arg1' 'arg2'), i.e. tuples of strings :param path_to_output_file: The filepath to the krf file. :param microtheory: The mi...
625941e24c3428357757c6ec
def get_track(self, gender): <NEW_LINE> <INDENT> return self.men_track if gender == 'men' else self.women_track
Gets the track of this tournament for a gender. :param gender: The gender of the track to get. :return the track.
625941e2d18da76e235328a1
def haeValmistettavat( kirja, jaakaappi, puuttuvia = 0, allergiat = None): <NEW_LINE> <INDENT> valmistettavat = [] <NEW_LINE> for aines in jaakaappi.ruokaAineet: <NEW_LINE> <INDENT> tulos = kirja.haeAinesosalla( aines.nimi) <NEW_LINE> for t in tulos: <NEW_LINE> <INDENT> if (t.nimi not in valmistettavat): <NEW_LINE> <IN...
Hakee valmistettavat ruoat (tai josta puuttuu 'puuttuvia' kpl ainesosia). Laiskassa tilassa ohjelma myös antaa pienet määrälliset puutteet anteeksi
625941e2d6c5a10208144415
def test_list_unity_versions(self): <NEW_LINE> <INDENT> pass
Test case for list_unity_versions List all unity versions
625941e2dc8b845886cb58fd
def test_get_non_existant_config_option(self): <NEW_LINE> <INDENT> config = {'ldap': {'url': uuid.uuid4().hex}} <NEW_LINE> self.domain_config_api.create_config(self.domain['id'], config) <NEW_LINE> self.get('/domains/%(domain_id)s/config/ldap/user_tree_dn' % { 'domain_id': self.domain['id']}, expected_status=404)
Call ``GET /domains{domain_id}/config/group/{option_not_exist}``.
625941e2ab23a570cc25054c
def get_stored_username(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(filename) as f_obj: <NEW_LINE> <INDENT> username = json.load(f_obj) <NEW_LINE> <DEDENT> <DEDENT> except FileNotFoundError: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return username
如果存储了用户名,就获取它
625941e2e8904600ed9f22f9
def parse(self, charSet, file): <NEW_LINE> <INDENT> inpsrc = InputSource() <NEW_LINE> inpsrc.setByteStream(file) <NEW_LINE> inpsrc.setEncoding(charSet) <NEW_LINE> return self.parseInputSource(inpsrc)
Parses the provided content. @param charSet: string The character set of the content. @param file: byte file The bytes file object providing the content. @return: object The object obtained from parsing.
625941e28e71fb1e9831db6f
def generate_time(n=50, bounds=(0, 50), random=False): <NEW_LINE> <INDENT> if not isinstance(n, int): <NEW_LINE> <INDENT> raise ValueError('`n` must be an integer') <NEW_LINE> <DEDENT> if not isinstance(bounds, tuple): <NEW_LINE> <INDENT> raise ValueError('`bounds` must be a tuple') <NEW_LINE> <DEDENT> bounds = np.asar...
Generates time array Args: n (int): Number of time instants to generate bounds (tuple): t ∈ [bounds[0], bounds[1]] random (bool): True: random False: linear time spacing period (float): Sinusoidal period amplitude (float): Sinuoidal amplitude noise_std (float): Gaussian noise st...
625941e2287bf620b61d3e28
def _populateEntries(self): <NEW_LINE> <INDENT> widgets = self.setting.getWidgetList() <NEW_LINE> names = widgets.keys() <NEW_LINE> names.sort() <NEW_LINE> utils.populateCombo(self, names)
Build up a list of widgets for combobox.
625941e2fff4ab517eb2f805
def bottleneck(nb_filter, init_subsample=(1, 1, 1), is_first_block_of_first_layer=False): <NEW_LINE> <INDENT> def f(input): <NEW_LINE> <INDENT> if is_first_block_of_first_layer: <NEW_LINE> <INDENT> conv_1_1 = Convolution3D(nb_filter=nb_filter, kernel_dim1=1, kernel_dim2=1, kernel_dim3=1, subsample=init_subsample, init=...
Bottleneck architecture for > 34 layer resnet. Follows improved proposed scheme in http://arxiv.org/pdf/1603.05027v2.pdf Returns: A final conv layer of nb_filter * 4
625941e21d351010ab855ee2
def product_pdf_color_profiles_id_patch_with_http_info(self, id, **kwargs): <NEW_LINE> <INDENT> all_params = ['id', 'data'] <NEW_LINE> all_params.append('callback') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> params = locals() <NEW_LINE> for key, val in iteritems(params['kwargs']): <NEW_LINE> <IND...
Patch attributes for a model instance and persist it into the data source. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>>...
625941e2d58c6744b4258025
def drawEdges(self): <NEW_LINE> <INDENT> return (self.incomingDrawEdgeList + self.outgoingDrawEdgeList)
Return all incoming and outgoing edges in a list.
625941e263d6d428bbe448b7
def main(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser(description="Selects a single pocket in the outputs of the fpocket building block from a given parameter.", formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=99999)) <NEW_LINE> parser.add_argument('--config', required=False, help='Con...
Command line execution of this building block. Please check the command line documentation.
625941e2956e5f7376d71233
def __truediv__(self, other): <NEW_LINE> <INDENT> if isinstance(other, (float, str)): <NEW_LINE> <INDENT> raise TypeError <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return float(self) / float(other)
Der überladene Operator / Division gibt das Ergebnis zweier zu durcheinander teilenden Brüche zurück :param other: :return:
625941e267a9b606de4a827e
def GetFamily(intValue): <NEW_LINE> <INDENT> intValue = int(round(intValue)) <NEW_LINE> if intValue <= 4: <NEW_LINE> <INDENT> return 1.0 <NEW_LINE> <DEDENT> elif intValue >= 5: <NEW_LINE> <INDENT> return 0.0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('Error in GetFamily: ', intValue)
Returns if the given value represents Family or not. Helper function for Split4Columns() INPUT: intValue: Integer representing Family or Business OUTPUT: Binary value depending on whether input represents Family
625941e20a366e3fb873ebe4
def __init__(self): <NEW_LINE> <INDENT> self.last_name = 0 <NEW_LINE> self.first_name = 0 <NEW_LINE> self.organization_name = 0 <NEW_LINE> self.inventor = 0 <NEW_LINE> self.assignee = 0 <NEW_LINE> self.country_code = 0 <NEW_LINE> self.document_date = 0 <NEW_LINE> self.pct_application = 0 <NEW_LINE> self.title = 0 <NEW_...
xml elements
625941e26fb2d068a760f46a
def __init__(self, obs_dim): <NEW_LINE> <INDENT> self.vars = np.zeros(obs_dim) <NEW_LINE> self.means = np.zeros(obs_dim) <NEW_LINE> self.m = 0 <NEW_LINE> self.first_pass = True
Args: obs_dim: dim of the observation
625941e266656f66f7cbc573
def get_voice_mail_number(log, ad): <NEW_LINE> <INDENT> voice_mail_number = get_voice_mail_check_number(get_operator_name(log, ad)) <NEW_LINE> if voice_mail_number is None: <NEW_LINE> <INDENT> return get_phone_number(log, ad) <NEW_LINE> <DEDENT> return voice_mail_number
function to get the voice mail number
625941e276d4e153a657eef9
def __set(self, section, option, value, verbose): <NEW_LINE> <INDENT> if not self.has_section(section): <NEW_LINE> <INDENT> self.add_section( section ) <NEW_LINE> <DEDENT> if not is_text_string(value): <NEW_LINE> <INDENT> value = repr( value ) <NEW_LINE> <DEDENT> if verbose: <NEW_LINE> <INDENT> print('%s[ %s ] = %s' % ...
Private set method
625941e2cc0a2c11143dd259
def fetchRunLength(self, runLengthParam='nRun'): <NEW_LINE> <INDENT> if 'Config' not in self.tables: <NEW_LINE> <INDENT> print('Cannot access Config table to retrieve runLength; using default 10 years') <NEW_LINE> runLength = 10.0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> table = self.tables['Config'] <NEW_LINE> ru...
Returns the run length for a particular opsim run (years). runLengthParam = the 'paramName' in the config table identifying the run length (default nRun).
625941e2e64d504609d74c07
def _check_event(self, event): <NEW_LINE> <INDENT> if self._valid_events and event not in self._valid_events: <NEW_LINE> <INDENT> raise RuntimeError( "Invalid event '{event}'. Expected one of: {events}", event=event, events=', '.join(self._valid_events), )
Internal helper. Throws RuntimeError if we have a valid_events list, and the given event isnt' in it. Does nothing otherwise.
625941e2dc8b845886cb58fe
def display_discovery_summary(req): <NEW_LINE> <INDENT> output = discovery_wrapper() <NEW_LINE> return discovery_summary_parser(output)
Returns a dictionary of all data for all discovery records
625941e2099cdd3c635f1020
def test_audit_compare_override(self): <NEW_LINE> <INDENT> self.test_model._meta.fields.update({'other': False}) <NEW_LINE> self.test_model.save() <NEW_LINE> self.assertEqual(0, Audit.objects.count())
check that any changes to the 'other' field are ignored because of audit_compare()
625941e2091ae3566866731e
def _get_volume_group_folder(self, datacenter, project_id, snapshot=False): <NEW_LINE> <INDENT> volume_folder_name = self.configuration.vmware_volume_folder <NEW_LINE> project_folder_name = "Project (%s)" % project_id <NEW_LINE> folder_names = ['OpenStack', project_folder_name, volume_folder_name] <NEW_LINE> if snapsho...
Get inventory folder for organizing volume backings and snapshots. The inventory folder for organizing volume backings has the following hierarchy: <Datacenter_vmFolder>/OpenStack/Project (<project_id>)/ <volume_folder> where volume_folder is the vmdk driver config option "vmware_volume_folder". A sub-f...
625941e29f2886367277ac52
def untangle_random_search(link1, link2, labels1, labels2, R=100, L=1.5): <NEW_LINE> <INDENT> lindex1 = leaf_order(link1, labels1, as_dict=True) <NEW_LINE> lindex2 = leaf_order(link2, labels2, as_dict=True) <NEW_LINE> min_entang = entanglement(lindex1, lindex2, L=L) <NEW_LINE> for i in range(int(R)): <NEW_LINE> <INDENT...
Untangle dendrogram using a simple random search. Shuffle trees and see if entanglement got better. Parameters ---------- link1,link2 : scipy.cluster.hierarchy.linkage Linkages to (better) align by shuffling. labels1,labels2 : list Labels for link1 and link2, respective...
625941e28c3a873295158786
def literal(self, label): <NEW_LINE> <INDENT> raise NotImplementedError('abstract method')
Return an SDD node representing a literal. :param label: label of the literal :type label: int :return: internal node representing the literal
625941e2925a0f43d254a242
def __init__(self, food=0, wood=0, gold=0, stone=0, ore=0): <NEW_LINE> <INDENT> self.food = food <NEW_LINE> self.wood = wood <NEW_LINE> self.gold = gold <NEW_LINE> self.stone = stone <NEW_LINE> self.ore = ore
Create Resource container for a player Args: food (int): starting food wood (int): starting wood gold (int): starting gold stone (int): starting stone ore (int): starting ore. unused
625941e201c39578d7e75203
def login_user_via_session(client, user=None, email=None): <NEW_LINE> <INDENT> if not user: <NEW_LINE> <INDENT> user = _datastore.find_user(email=email) <NEW_LINE> <DEDENT> with client.session_transaction() as sess: <NEW_LINE> <INDENT> sess['_user_id'] = user.get_id()
Login a user via the session. :param client: The CLI test client. :param user: The :class:`invenio_accounts.models.User` instance. Optional. (Default: ``None``) :param email: Load the user by the email. Optional. (Default: ``None``)
625941e22eb69b55b151cc7c
def build_option_parser(self, description, version, argparse_kwargs=None): <NEW_LINE> <INDENT> kwargs = {"conflict_handler": "resolve"} <NEW_LINE> parser = super().build_option_parser(description, version, kwargs) <NEW_LINE> parser.add_argument( "--log-file", action="store", default=None, help="Specify a file to log ou...
Return an Argparse option parser for Mariner. Args: description: Mariner description. version: Mariner version.
625941e2baa26c4b54cb14e3
def handle_raw_keyboard_input(k): <NEW_LINE> <INDENT> input = [k] <NEW_LINE> for f in keyboard_filter_stack: <NEW_LINE> <INDENT> input = f(input) <NEW_LINE> <DEDENT> for k in input: <NEW_LINE> <INDENT> with td.orm_session(): <NEW_LINE> <INDENT> handle_keyboard_input(k)
Deal with input from the user This input is passed through the keyboard filter stack before being passed on to the handle_keyboard_input() function. The filter stack will typically recognise sequences (eg. "[A01]") and convert them into keycode objects.
625941e230bbd722463cc18f
def information_gain(sample, labels): <NEW_LINE> <INDENT> global_entropy = entropy(labels) <NEW_LINE> cardinality = float(sample.shape[0]) <NEW_LINE> indexes = np.argsort(sample) <NEW_LINE> flag = labels[indexes][0] <NEW_LINE> splits_indexes = {} <NEW_LINE> for pos, element in enumerate(labels[indexes]): <NEW_LINE> <IN...
sample = [31, 34, 32, 20, 11, 10, 8, 23, 7, 21, 23] labels = [0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1] # we will sort the first array, and also the second one # labels = [1, 1, 1, 1, 1, | 0, 0, | 1, | 0, 0, 0] # we calculate the information gain from each split and we return the # higher value
625941e2187af65679ca54e7
def browse_imdb(id): <NEW_LINE> <INDENT> imdb_url = IMDB_URL + id <NEW_LINE> try: <NEW_LINE> <INDENT> imdb_page = requests.get(imdb_url).text <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logger.warning('Exception {} occurs in browse_imdb, will retry once'.format(e)) <NEW_LINE> time.sleep(1) <NEW_LINE>...
this function will browse the imdb page for movie with ID `id`, and obtain its name and release date params: id - the IMDb primary key of a specific movie return value: id - same as input name - movie name with its release year, such as "The Fate of The Furious (2017)"
625941e24d74a7450ccd458b