code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def __init__(self, pad_val=0, **kwargs): <NEW_LINE> <INDENT> self.pad_val = pad_val | :param List[Any] contents: 传入的element是inplace的,即直接修改element可能导致数据变化,建议inplace修改之前
deepcopy一份。
:param str, field_name: field的名称。
:param np.int64,np.float64,np.str,None, field_ele_dtype: 该field的内层元素的类型。如果该field的ignore_type为True,该这个值为None。
:return: np.array([padded_element]) | 625941f171ff763f4b549c51 |
def test_auth_register_user_invalid_payload(self): <NEW_LINE> <INDENT> with self.client: <NEW_LINE> <INDENT> response = self.client.post( '/auth/signup', data=json.dumps(dict(email='habu')), content_type='application/json' ) <NEW_LINE> data = json.loads(response.data.decode()) <NEW_LINE> self.assertEqual(response.statu... | Register a user with invalid payload | 625941f11f037a2d8b9467b7 |
def serial_out(self,p): <NEW_LINE> <INDENT> f = self._f_dsl <NEW_LINE> work_array = self._work_array <NEW_LINE> diwrk0 = self._work_array.array_index() <NEW_LINE> diwrk1 = self._work_array.special_array_index_dict()['contract'] <NEW_LINE> contract_array = self._contract_array <NEW_LINE> dn_pre ... | Output serial variant of contract function using printer object p. | 625941f185dfad0860c3b418 |
def __init__(self, options=None): <NEW_LINE> <INDENT> import parameters_new as parameters <NEW_LINE> self.name = "Aug30" <NEW_LINE> self.Nmin = 280 <NEW_LINE> self.Nmax = 560 <NEW_LINE> self.buried_cutoff = 15.00; self.buried_cutoff_sqr = self.buried_cutoff*self.buried_cutoff ... | Rules of action for version Aug30 | 625941f138b623060ff0b3a8 |
@blueprint.route("/user", methods=["GET"]) <NEW_LINE> @user.login_required <NEW_LINE> def list_user_data(): <NEW_LINE> <INDENT> user_orders = list( flask.g.db["orders"].find({"editors": flask.session["user_id"]}, {"datasets": 1}) ) <NEW_LINE> uuids = list(ds for entry in user_orders for ds in entry["datasets"]) <NEW_LI... | List all datasets belonging to current user. | 625941f157b8e32f52483a5a |
def cache_installed(): <NEW_LINE> <INDENT> return settings.CACHES and not settings.TESTING and set(( "mezzanine.core.middleware.UpdateCacheMiddleware", "mezzanine.core.middleware.FetchFromCacheMiddleware", )).issubset(set(settings.MIDDLEWARE_CLASSES)) | Returns ``True`` if a cache backend is configured, and the
cache middlware classes are present. | 625941f1dd821e528d63b75f |
def oxe_system_law(host, token, law): <NEW_LINE> <INDENT> payload = { 'Law': law } <NEW_LINE> packages.urllib3.disable_warnings(packages.urllib3.exceptions.InsecureRequestWarning) <NEW_LINE> try: <NEW_LINE> <INDENT> modification = put( 'https://' + host + '/api/mgt/1.0/Node/1/System_Parameters/1/System_Parameters_2/1/S... | Summary
Args:
host (TYPE): Description
token (TYPE): Description
law (TYPE): Description
Returns:
TYPE: Description | 625941f167a9b606de4a8471 |
def install(self): <NEW_LINE> <INDENT> super().install() <NEW_LINE> self.path = self.mkdtemp() <NEW_LINE> logger.debug(f"HomeBox.install made a home in {self.path}") | Create a temp dir and store it in `self.path` | 625941f13539df3088e2e906 |
def statistical_analysis_weighted(line, N, ground_truth, temp_folder, output_folder, name, step=1.): <NEW_LINE> <INDENT> from scipy.stats import norm, gaussian_kde <NEW_LINE> minv = int(math.floor(min(line))) <NEW_LINE> negative = np.setdiff1d(range(len(line)), ground_truth) <NEW_LINE> indx = np.arange(minv, int(math.c... | Plots the similarity distribution and gaussian theoretical distribution in the case of a weighted similarity (negative samples).
Args:
* ``line`` (*list*): similarities for the considered sample x.
* ``N`` (*int*): standard deviation of the gaussian.
* ``ground_truth`` (*list*): indices of the samples in the same c... | 625941f1bf627c535bc1378a |
def generate_filename( self, directory=os.getcwd(), prefix="tile", format="png", path=True ): <NEW_LINE> <INDENT> filename = prefix + "_{col:02d}_{row:02d}.{ext}".format( col=self.column, row=self.row, ext=format.lower().replace("jpeg", "jpg") ) <NEW_LINE> if not path: <NEW_LINE> <INDENT> return filename <NEW_LINE> <DE... | Construct and return a filename for this tile. | 625941f13c8af77a43ae3d62 |
def aggregate_metadata_get(context, aggregate_id, read_deleted='no'): <NEW_LINE> <INDENT> return IMPL.aggregate_metadata_get(context, aggregate_id, read_deleted) | Get metadata for the specified aggregate. | 625941f15166f23b2e1a5714 |
def getNthDerivative(self, t, i): <NEW_LINE> <INDENT> return 0 | Return n'th derivative at time 't' and index 'i'. | 625941f1167d2b6e31219150 |
def tearDown(self): <NEW_LINE> <INDENT> del self.location | Clean up the location instance after each test method. | 625941f1462c4b4f79d1dc8a |
def __detect_geometric_decomposition(pet: PETGraphX, root: CUNode) -> bool: <NEW_LINE> <INDENT> for child in pet.subtree_of_type(root, NodeType.LOOP): <NEW_LINE> <INDENT> if not (child.reduction or child.do_all): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> for child in pet.direct_children_of_type(root... | Detects geometric decomposition pattern
:param pet: PET graph
:param root: root node
:return: true if GD pattern was discovered | 625941f192d797404e304748 |
def validate_instance_nics(context, instances): <NEW_LINE> <INDENT> instance_nics = [] <NEW_LINE> for instance in instances: <NEW_LINE> <INDENT> nics = instance.get('nics') <NEW_LINE> if nics: <NEW_LINE> <INDENT> instance_nics.append(nics[0].get('net-id')) <NEW_LINE> <DEDENT> <DEDENT> if len(set(instance_nics)) > 1: <N... | Checking networks are same for the cluster. | 625941f13c8af77a43ae3d63 |
def __init__( self, neighbourhood_matching_costs: NeighbourHoodMatchingCosts): <NEW_LINE> <INDENT> matches = {tuple(k): v for k, v in zip( *group_by(['v', 'u'], neighbourhood_matching_costs))} <NEW_LINE> neighbours = { k: group_by_first(['v', 'u', 'vv'], v)[['vv', 'uu']].tolist() for k, v in matches.items() } <NEW_LINE... | Initialise a refiner using a Frame instance
For each pair (v, u) find the lowest cost adjacent pair (vv, uu)
Arguments:
frame {[Frame]} -- A frame constructed
records returned by the database | 625941f123849d37ff7b3646 |
def get_exif_data(fname): <NEW_LINE> <INDENT> ret = {} <NEW_LINE> try: <NEW_LINE> <INDENT> img = Image.open(fname) <NEW_LINE> if hasattr( img, '_getexif' ): <NEW_LINE> <INDENT> exifinfo = img._getexif() <NEW_LINE> if exifinfo != None: <NEW_LINE> <INDENT> for tag, value in exifinfo.items(): <NEW_LINE> <INDENT> decoded =... | Get embedded EXIF data from image file. | 625941f145492302aab5e885 |
def kurtosistest(a, axis=0, nan_policy='propagate'): <NEW_LINE> <INDENT> a, axis = _chk_asarray(a, axis) <NEW_LINE> contains_nan, nan_policy = _contains_nan(a, nan_policy) <NEW_LINE> if contains_nan and nan_policy == 'omit': <NEW_LINE> <INDENT> a = ma.masked_invalid(a) <NEW_LINE> return mstats_basic.kurtosistest(a, axi... | Tests whether a dataset has normal kurtosis
This function tests the null hypothesis that the kurtosis
of the population from which the sample was drawn is that
of the normal distribution: ``kurtosis = 3(n-1)/(n+1)``.
Parameters
----------
a : array
array of the sample data
axis : int or None, optional
Axis alo... | 625941f10c0af96317bb87a2 |
def from_path(self, path: str) -> "Wallet": <NEW_LINE> <INDENT> self._hdwallet.from_path(path=path) <NEW_LINE> return self | Drive Ethereum wallet from path.
:param path: Ethereum wallet path.
:type path: str
:returns: Wallet -- Ethereum wallet instance.
>>> from swap.providers.ethereum.wallet import Wallet
>>> wallet: Wallet = Wallet(network="testnet")
>>> wallet.from_entropy(entropy="ed0802d701a033776811601dd6c5c4a9")
>>> wallet.from_pa... | 625941f115baa723493c4535 |
@pytest.mark.integration <NEW_LINE> def test_one_to_many(engine, sessionmaker): <NEW_LINE> <INDENT> spec = { "components": { "schemas": { "RefTable": { "properties": { "id": {"type": "integer", "x-primary-key": True}, "name": {"type": "string"}, }, "x-tablename": "ref_table", "x-backref": "table", "type": "object", }, ... | GIVEN specification with a schema with a one to many object relationship
WHEN schema is created, values inserted in both tables and queried
THEN the data is returned as it was inserted. | 625941f1e64d504609d74dfb |
def parse_file(self, path): <NEW_LINE> <INDENT> source_coding = get_py_file_encoding(path) <NEW_LINE> doc_strings = self._get_doc_strings(path, source_coding) <NEW_LINE> if doc_strings: <NEW_LINE> <INDENT> self.documentation_filepaths.append(path) <NEW_LINE> previous_elements_paths = [] <NEW_LINE> for doc_string in doc... | * Parses file from given path and collects documentation data from it.
@method .parse_file
@param self
@param path {str} - path to source file | 625941f1566aa707497f4b1b |
@Image(".orb@kep2rec", bod=Node(evs=(), args=("mu",), ins=(), reqs=(), outs=(), pros=()), orb=Node(evs=(6,), args=(), ins=(), reqs=("kep",), outs=(True,), pros=("r_bar", "v_bar"))) <NEW_LINE> def kep2rec(bod, orb): <NEW_LINE> <INDENT> mu, = bod.args <NEW_LINE> yield <NEW_LINE> while True: <NEW_LINE> <INDENT> liborbele.... | Kepler elements to state vectors | 625941f163f4b57ef00016c3 |
def _pick_server (self, key, inport): <NEW_LINE> <INDENT> server_list = self.live_servers.keys() <NEW_LINE> self.last_server = (self.last_server + 1) % len(server_list) <NEW_LINE> return server_list[self.last_server] | Pick a server for a (hopefully) new connection | 625941f150812a4eaa59c8d6 |
def label_figure(axes, n_subplots, time_units, sig_name, sig_units, ylabel, title): <NEW_LINE> <INDENT> if title: <NEW_LINE> <INDENT> axes[0].set_title(title) <NEW_LINE> <DEDENT> if not ylabel: <NEW_LINE> <INDENT> ylabel = [] <NEW_LINE> if not sig_name: <NEW_LINE> <INDENT> sig_name = ['ch_'+str(i) for i in range(n_subp... | Add title, and axes labels | 625941f1099cdd3c635f1213 |
def get_geometry_occlusion(self, listener, source): <NEW_LINE> <INDENT> listener = VECTOR.from_list(listener) <NEW_LINE> source = VECTOR.from_list(source) <NEW_LINE> direct = c_float() <NEW_LINE> reverb = c_float() <NEW_LINE> ckresult( _dll.FMOD_System_GetGeometryOcclusion( self._ptr, byref(listener), byref(source), by... | Calculate geometry occlusion between a listener and a sound
source.
If single sided polygons have been created, it is important to get the
source and listener positions around the right way, as the occlusion
from point A to point B may not be the same as the occlusion from point
B to point A.
:param list listener: Th... | 625941f121a7993f00bc82b6 |
def link_bg_endpoint(bg_id, ep_id, x_rhid): <NEW_LINE> <INDENT> headers = {"x-rh-identity": x_rhid} <NEW_LINE> ep_list = [ep_id] <NEW_LINE> r = requests.put(notifications_prefix + "/notifications/behaviorGroups/" + bg_id + "/actions", json=ep_list, headers=headers) | Link the behavior group to the endpoint | 625941f1379a373c97cfb102 |
def test_canNotConnectTemporarily(self): <NEW_LINE> <INDENT> self.changeUser('admin') <NEW_LINE> document = createDocument(self.portal) <NEW_LINE> viewlet = PloneMeetingInfosViewlet(document, self.request, None, None) <NEW_LINE> viewlet.update() <NEW_LINE> item = self._sendToPloneMeeting(document) <NEW_LINE> self.asser... | Test a connection problem in PloneMeeting after an item has already been sent
- connect to PM successfully
- send the item successfully
- break settings
- check what is going on while not being able to show PM related informations | 625941f101c39578d7e753f7 |
def select_in_rectangle(self, rect): <NEW_LINE> <INDENT> items = self._qtree.find_inside(rect) <NEW_LINE> list(map(self.select_item, items)) | Select all items who have their bounding box within the
rectangle @rect. | 625941f1462c4b4f79d1dc8b |
def test_invoice_line_dimension(self): <NEW_LINE> <INDENT> partner = self.env.ref('base.res_partner_2') <NEW_LINE> account = self.account_obj.create({ 'code': 'test_dimension_acc_02', 'name': 'test dimension account', 'user_type_id': self.account_user_type.id, 'reconcile': True, }) <NEW_LINE> invoice = self.env['accoun... | Test dimension creation on account invoice line creation
| 625941f166673b3332b9264d |
def publish_message(self, message: Message): <NEW_LINE> <INDENT> properties = pika.BasicProperties( content_type="application/json", content_encoding="utf8" ) <NEW_LINE> try: <NEW_LINE> <INDENT> self.channel.basic_publish( exchange=self.exchange, routing_key=self.queue, body=json.dumps(message, ensure_ascii=False), pro... | Publish a message to rabbitmq | 625941f18e05c05ec3eea935 |
def interface_lookup(interfaces, hwaddr, address_type): <NEW_LINE> <INDENT> for interface in interfaces.values(): <NEW_LINE> <INDENT> if interface.get('hwaddr') == hwaddr: <NEW_LINE> <INDENT> for address in interface.get('addrs'): <NEW_LINE> <INDENT> if address.get('type') == address_type: <NEW_LINE> <INDENT> return ad... | Search the address within the interface list. | 625941f171ff763f4b549c52 |
def assignFrames(self): <NEW_LINE> <INDENT> if self.inDirectionOfTranscription(): <NEW_LINE> <INDENT> iStart = 0 <NEW_LINE> iEnd = len(self.exons) <NEW_LINE> iDir = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iStart = len(self.exons)-1 <NEW_LINE> iEnd = -1 <NEW_LINE> iDir = -1 <NEW_LINE> <DEDENT> cdsOff = 0 <NEW_LI... | set frames on exons, assuming no frame shift | 625941f1ec188e330fd5ad4e |
def strip_harakat(text): <NEW_LINE> <INDENT> if not text: <NEW_LINE> <INDENT> return text <NEW_LINE> <DEDENT> elif is_vocalized(text): <NEW_LINE> <INDENT> for char in HARAKAT: <NEW_LINE> <INDENT> text = text.replace(char, "") <NEW_LINE> <DEDENT> <DEDENT> return text | Strip Harakat from arabic word except Shadda.
The striped marks are :
- FATHA, DAMMA, KASRA
- SUKUN
- FATHATAN, DAMMATAN, KASRATAN,
@param text: arabic text.
@type text: unicode.
@return: return a striped text.
@rtype: unicode. | 625941f167a9b606de4a8472 |
def test_validate_validates_required_fields_on_create(self): <NEW_LINE> <INDENT> owner = User.objects.get(username=self.username) <NEW_LINE> data = {'name': 'Pipeline2', 'owner': owner} <NEW_LINE> pipeline_serializer = PipelineSerializer(data=data) <NEW_LINE> with self.assertRaises(serializers.ValidationError): <NEW_LI... | Test whether overriden validate method validates that 'plugin_tree' field
must be provided when creating a new pipeline. | 625941f10a50d4780f667453 |
def is_cval(fp): <NEW_LINE> <INDENT> return False if fp.rsplit('/', 1)[-1].find('cval') == -1 else True | return true if cval. | 625941f1be7bc26dc91cdbb1 |
def random_arrayX(self, shape='loc'): <NEW_LINE> <INDENT> shape = shape.lower() <NEW_LINE> if shape == 'loc': <NEW_LINE> <INDENT> shapeX = self.shapeX_loc <NEW_LINE> <DEDENT> elif shape == 'seq': <NEW_LINE> <INDENT> shapeX = self.shapeX_seq <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('shape should be... | Return a random array in real space. | 625941f1cc0a2c11143dd44d |
@allow_enum_members.parametrize <NEW_LINE> def test_allow_enum_members(code): <NEW_LINE> <INDENT> class Foo: <NEW_LINE> <INDENT> def __init__(self, choice): <NEW_LINE> <INDENT> self.choice = choice <NEW_LINE> <DEDENT> <DEDENT> foo = code(Foo) <NEW_LINE> assert foo.choice is Choices.one | Allow to inject enum members. | 625941f110dbd63aa1bd315e |
def clean_username(self): <NEW_LINE> <INDENT> cleaned_data = super(AuthorForm, self).clean() <NEW_LINE> users = [] <NEW_LINE> for username in cleaned_data.get('username').split(','): <NEW_LINE> <INDENT> user = Profile.objects.filter(user__username__iexact=username.strip().lower()).first() <NEW_LINE> if user is not None... | Check every username and send it to the cleaned_data['user'] list
:return: a dictionary of all treated data with the users key added | 625941f1236d856c2ad44d9f |
def cluster_ready(): <NEW_LINE> <INDENT> min_size = config('min-cluster-size') <NEW_LINE> units = 1 <NEW_LINE> for relation_id in relation_ids('cluster'): <NEW_LINE> <INDENT> units += len(related_units(relation_id)) <NEW_LINE> <DEDENT> if not min_size: <NEW_LINE> <INDENT> min_size = units <NEW_LINE> <DEDENT> if not is_... | Determine if each node in the cluster is ready and the cluster is
complete with the expected number of peers.
Once cluster_ready returns True it is safe to execute client relation
hooks. Having min-cluster-size set will guarantee cluster_ready will not
return True until the expected number of peers are clustered and r... | 625941f1099cdd3c635f1214 |
def write_user(self, parent): <NEW_LINE> <INDENT> keymap = dict( name="bss_user_info_contact", affiliation="bss_user_info_institution", email="bss_user_info_email", facility_user_id="bss_user_info_badge", ) <NEW_LINE> try: <NEW_LINE> <INDENT> links = {k: self.get_stream_link(v) for k, v in keymap.items()} <NEW_LINE> <D... | group: /entry/contact:NXuser | 625941f197e22403b379d558 |
@spiceErrorCheck <NEW_LINE> @spiceFoundExceptionThrower <NEW_LINE> def frinfo(frcode): <NEW_LINE> <INDENT> frcode = ctypes.c_int(frcode) <NEW_LINE> cent = ctypes.c_int() <NEW_LINE> frclss = ctypes.c_int() <NEW_LINE> clssid = ctypes.c_int() <NEW_LINE> found = ctypes.c_bool() <NEW_LINE> libspice.frinfo_c(frcode, ctypes.b... | http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/frinfo_c.html
:param frcode: the idcode for some frame.
:type frcode: int
:return: a tuple of attributes associated with the frame.
:rtype: tuple | 625941f156ac1b37e626477f |
def _require_homogeneous_targets(self, accept_predicate, reject_predicate): <NEW_LINE> <INDENT> if len(self.context.target_roots) == 0: <NEW_LINE> <INDENT> raise self.NoActivationsError('No target specified.') <NEW_LINE> <DEDENT> accepted = self.context.targets(accept_predicate) <NEW_LINE> rejected = self.context.targe... | Ensures that there is no ambiguity in the context according to the given predicates.
If any targets in the context satisfy the accept_predicate, and no targets satisfy the
reject_predicate, returns the accepted targets.
If no targets satisfy the accept_predicate, returns None.
Otherwise throws TaskError. | 625941f1fbf16365ca6f678c |
def p_INPUT(self, p): <NEW_LINE> <INDENT> print("\tCORRECTO INPUT") | INPUT : ID COMMA INPUT
| ID IS_VALUE READ OPEN_PARENTHESIS CLOSE_PARENTHESIS | 625941f1baa26c4b54cb16d5 |
def perform(self, director, routine=None, debug=False): <NEW_LINE> <INDENT> if routine is None: <NEW_LINE> <INDENT> routine = "default" <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> behavior = self.__getattribute__(routine) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> self._info.log("routine '%s' is no... | construct an actual page by invoking the requested routine | 625941f131939e2706e4d41d |
def get_last_n_tasks(self, host, owner, suite, task_state, point_string): <NEW_LINE> <INDENT> key = (host, owner, suite) <NEW_LINE> if (key not in self.tasks_by_state or task_state not in self.tasks_by_state[key]): <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> tasks = list(self.tasks_by_state[key][task_state]) <NEW... | Returns a list of the last 'n' tasks with the provided state for
the provided suite. | 625941f15fc7496912cc3f39 |
def faq_matcher_create(self, create_details, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('async_req'): <NEW_LINE> <INDENT> return self.faq_matcher_create_with_http_info(create_details, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (data) = self.faq_matcher_c... | Create an FAQ matcher. # noqa: E501
Create a new faq matcher or reload one from the trash. Returns the details of the instance. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.faq_matcher_create(create_details, as... | 625941f13eb6a72ae02ecaaa |
def data_model_format(self, data, timestamps): <NEW_LINE> <INDENT> data_lst = [] <NEW_LINE> for item_name, item_value in data.items(): <NEW_LINE> <INDENT> if item_name not in self.ignore: <NEW_LINE> <INDENT> item_dict = { "metrics": item_name, "timestamp": timestamps, "step": self.interval, "value": item_value, "counte... | data build format | 625941f13d592f4c4ed1d619 |
def _create_user_analytics(self, user_projector): <NEW_LINE> <INDENT> filename = './data/%s/student_usage_analytics.csv' % self.course_name <NEW_LINE> if file_exists(filename): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> user_analytics = self.canvas.get_student_summary_analytics(self.course_id) <NEW_LINE> user_analy... | Saves usage data for each student in the course. (aggregated number of views, participations etc)
Also, saves a file for each user, that contains detailed usage analytics
:param course_id: string
:param user_projector: dict
:return: | 625941f15fdd1c0f98dc07f1 |
def createCampsitePriceHistory(self,data): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with transaction.atomic(): <NEW_LINE> <INDENT> for c in self.campsites.all(): <NEW_LINE> <INDENT> cr = CampsiteRate(**data) <NEW_LINE> cr.campsite = c <NEW_LINE> cr.save() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except Exception as e:... | Create Multiple campsite rates
| 625941f130c21e258bdfaa60 |
def render_element(self, context): <NEW_LINE> <INDENT> self.text_model = [[(3,0.5), "${ref}", True], [(3,None), "Ss=${ps_mw}+j${qs_mvar}MVA", True], [(3,None), "Sz=${pz_mw}+j${qz_mvar}MVA", True], [(3,None), "${name}", True]] <NEW_LINE> if self.fields['in_service']['value']: <NEW_LINE> <INDENT> self.render_model(contex... | Render element to context | 625941f107d97122c4178e56 |
def validate(self, all_json_data: Iterable[dict]) -> bool: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> for data in all_json_data: <NEW_LINE> <INDENT> jsonschema.validate(instance=data, schema=self.schema) <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> except jsonschema.exceptions.ValidationError as err: <NEW_LINE... | Returns whether an iterable of dicts conforms to the Validator's schema
Args:
all_json_data (Iterable[dict]): Iterable of dictionaries conforming to Validator's schema
Returns:
bool: True if all items in all_json_data conform to schema, False otherwise | 625941f18a43f66fc4b5461b |
def new_launch_error(self, launch_failure): <NEW_LINE> <INDENT> self.logger.error("received error from chromecast %s: %s" % (self.device_name, launch_failure)) | PyChromecast error callback. | 625941f1d18da76e23532a9a |
def list(self, resource, offset=0, limit=0): <NEW_LINE> <INDENT> objs = [] <NEW_LINE> result = self._list(resource, offset=offset) <NEW_LINE> objs.extend(result[0]) <NEW_LINE> pages = result[1]['pages'] - 1 <NEW_LINE> while pages > 0: <NEW_LINE> <INDENT> offset += len(result[0]) <NEW_LINE> logger.debug('pages ' + str(p... | :param resource:
:param offset:
:param limit: if 0 then all the records are returned
:return: | 625941f16fece00bbac2dd02 |
def GetIdent(self): <NEW_LINE> <INDENT> return _itkQuadEdgeMeshLineCellPython.itkQuadEdgeMeshLineCellCIDQEMCTIF2_GetIdent(self) | GetIdent(self) -> unsigned long | 625941f1442bda511e8be9cc |
def __iter__(self): <NEW_LINE> <INDENT> self.__dict__['_index'] = -1 <NEW_LINE> return self | Called by Python automatically when iterating over this set and python wants to start
the iteration process.
`self._index` internally controls the which one is the current item in an iteration over
an production | 625941f1596a89723608a074 |
def selectController(self, address): <NEW_LINE> <INDENT> assert((0 <= address) and (address <= 15)) <NEW_LINE> self._sendSetCommand("SC%d\r" % address) | Tell the currently selected controller that the given controller is selected
Useless but for tests (or in macros) | 625941f1fbf16365ca6f678d |
def getTMPredictedActiveCells(self): <NEW_LINE> <INDENT> return [set(column.getOutputData("predictedActiveCells").nonzero()[0]) for column in self.TMRegions] | Returns the cells in TM that were predicted at the beginning of the most
recent call to 'compute' and are currently active. | 625941f1a8ecb033257d3687 |
def report(self, statement): <NEW_LINE> <INDENT> print(statement) <NEW_LINE> if self.ReportFileExist: <NEW_LINE> <INDENT> self._reportfile.write(statement+'\n') | Print statement on screen and write it into reportfile
Args:
statement(str) | 625941f18c3a87329515897e |
def test_wtf_csrf_enabled(self): <NEW_LINE> <INDENT> self.assertTrue(self.app.config.get('WTF_CSRF_ENABLED')) | test CSRF protection is enabled | 625941f131939e2706e4d41e |
def chi2_floating(var, db1): <NEW_LINE> <INDENT> ley = LabelEncoder() <NEW_LINE> y = ley.fit_transform(db1['Sales']) <NEW_LINE> c, pval = chi2(db1[var].as_matrix().reshape(-1, 1), y) <NEW_LINE> return c[0], pval[0] | chi2 test for floating features
Args:
var (str): Feature name
db1 (pandas.DataFrame): data
db1_train (pandas.Index): indexes of the train set
db1_test (pandas.Index): indexes of the test set
Returns:
c (float): chi-square
pval (float): p-value | 625941f15510c4643540f991 |
def _get_element(self, **kwargs) -> _html.Element: <NEW_LINE> <INDENT> return _html.Div( uid=self.uid, css='fb-comments', data_href=self._href, data_width='100%' ) | Get an HTML element representation of the widget.
:param **kwargs: | 625941f19b70327d1c4e1394 |
def nextH(ph): <NEW_LINE> <INDENT> return _toolkit.nextH(ph) | nextH(ph) -> int
Parameters
----------
ph: EN_Project | 625941f1e76e3b2f99f3adbe |
def _pop(self, index=None): <NEW_LINE> <INDENT> value = self._stack.pop(len(self._stack)-1 if index == None else index) <NEW_LINE> if value == int(value): <NEW_LINE> <INDENT> value = int(value) <NEW_LINE> <DEDENT> return value | Pop and return a value from the current stack.
Keyword arguments:
index -- the index to pop from (default: end of stack) | 625941f15fcc89381b1e1c80 |
def reraise_client_error(self, exc): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> url = exc.response.request.url.split('?')[0] <NEW_LINE> body = exc.response.body.decode('utf8', 'replace').strip() <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> url = 'url' <NEW_LINE> body = '' <NEW_LINE> <DEDENT> str_exc... | Remote fetch raised an error | 625941f1596a89723608a075 |
def YumUninstall(vm): <NEW_LINE> <INDENT> _Uninstall(vm) | Stops collectd on 'vm'. | 625941f1d486a94d0b98e703 |
def trim_line(line: str, value, max_len: int = 75) -> str: <NEW_LINE> <INDENT> if len(line) > max_len: <NEW_LINE> <INDENT> if isinstance(value, Model): <NEW_LINE> <INDENT> line = cut_by_comma(line, ', ...)', max_len) <NEW_LINE> <DEDENT> elif isinstance(value, list) and '(' in line: <NEW_LINE> <INDENT> line = cut_by_com... | Trim line based on field type. | 625941f11f037a2d8b9467b8 |
def splitTable(self, tempTable): <NEW_LINE> <INDENT> colWidths = tempTable._colWidths <NEW_LINE> rowHeights = tempTable._rowHeights <NEW_LINE> total = 0 <NEW_LINE> colNo = 0 <NEW_LINE> colSplit = [] <NEW_LINE> newColWidth = [] <NEW_LINE> pageColWidth = [] <NEW_LINE> for colW in colWidths: <NEW_LINE> <INDENT> if colNo >... | Internally used method to split the table across columns so that it
will fit into the available space on the page. | 625941f138b623060ff0b3a9 |
def test_set_clipboard(self): <NEW_LINE> <INDENT> pass | Test for . | 625941f15f7d997b8717505a |
def get_queryset(self): <NEW_LINE> <INDENT> queryset = self.model.objects.all() if self.request.GET.get('show_inactive') else self.model.get_active() <NEW_LINE> return queryset.order_by('-creationDate') | Return the list of projects applting filters and ordering | 625941f1377c676e91272763 |
def store_model_info( timestamp, batch_comment, batch_timestamp, config, paths={}): <NEW_LINE> <INDENT> model_comment = config['model_comment'] <NEW_LINE> query = ( " INSERT INTO results.models( run_time, batch_run_time, model_type, model_parameters, model_comment, batch_comment, config, test) " " VALUES( %s, %s, %... | Write model configuration into the results.model table
:param str timestamp: the timestamp at which this model was run.
:param str batch_comment: the user-defined comment string.
:param str batch_timestamp: the timestamp that this batch of models was run.
:param dict config: the configuration dictionary that contains ... | 625941f18da39b475bd65538 |
@pytest.fixture <NEW_LINE> def red_ejemplo(): <NEW_LINE> <INDENT> g = ig.Graph() <NEW_LINE> g.add_vertices(7) <NEW_LINE> g.add_edges([(0, 1), (0, 2), (2, 1), (0, 3), (3, 4), (4, 5), (5, 3), (6, 5)]) <NEW_LINE> clusters = g.community_infomap() <NEW_LINE> p = [ 1 - (2/3)**2 - (1/3)**2, 1 - (2/2)**2 - (0/2)**2, 1 - (2/2)*... | Hago una red con dos comunidades para testear | 625941f14e4d5625662d498c |
def loadAppIcon(self): <NEW_LINE> <INDENT> app_icon = QIcon() <NEW_LINE> app_icon.addFile('images/logo_16.png', QSize(16, 16)) <NEW_LINE> app_icon.addFile('images/logo_24.png', QSize(24, 24)) <NEW_LINE> app_icon.addFile('images/logo_32.png', QSize(32, 32)) <NEW_LINE> app_icon.addFile('images/logo_48.png', QSize(48, 48)... | Load application default icon, for all windows + taskbar | 625941f107f4c71912b11a42 |
def get_dependent_objective_query(self): <NEW_LINE> <INDENT> raise errors.Unimplemented() | Gets the query for a dependent objective.
Multiple retrievals produce a nested ``OR`` term.
return: (osid.learning.ObjectiveQuery) - the objective query
raise: Unimplemented - ``supports_dependent_objective_query()``
is ``false``
*compliance: optional -- This method must be implemented if
``supports_depend... | 625941f1d53ae8145f87a821 |
def _fetch(self, obj=None): <NEW_LINE> <INDENT> if obj is None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if self.__coll_id__: <NEW_LINE> <INDENT> obj = pychronos._raw_collection_api_instance.app_api_collection_raw_get(coll_id=self.__coll_id__) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> obj = pychronos._collectio... | fetch collection | 625941f14428ac0f6e5badb4 |
def chooseAction(self, time_step): <NEW_LINE> <INDENT> action = np.zeros(self.current_action.shape) <NEW_LINE> if time_step%self.K == 0: <NEW_LINE> <INDENT> if random.random() <= self.Epsilon: <NEW_LINE> <INDENT> index = [random.randint(0, i-1) for i in action.shape] <NEW_LINE> action[index] = 1 <NEW_LINE> <DEDENT> els... | Choose an action based on the current state. | 625941f1d8ef3951e3243afa |
def _redirect_eliot_logs_for_trial(): <NEW_LINE> <INDENT> import os <NEW_LINE> import sys <NEW_LINE> if os.path.basename(sys.argv[0]) == "trial": <NEW_LINE> <INDENT> from eliot.twisted import redirectLogsForTrial <NEW_LINE> redirectLogsForTrial() | Enable Eliot logging to the ``_trial/test.log`` file.
This wrapper function allows flocker/__version__.py to be imported by
packaging tools without them having to install all the Flocker Eliot
dependencies. | 625941f19c8ee82313fbbd34 |
def check_is_running(cbdir): <NEW_LINE> <INDENT> fp = os.path.join(cbdir, _PID_FILENAME) <NEW_LINE> if os.path.isfile(fp): <NEW_LINE> <INDENT> with open(fp) as fd: <NEW_LINE> <INDENT> pid_data_str = fd.read() <NEW_LINE> try: <NEW_LINE> <INDENT> pid_data = json.loads(pid_data_str) <NEW_LINE> pid = int(pid_data['pid']) <... | Check if a Crossbar.io node is already running on a Crossbar.io node directory.
:param cbdir: The Crossbar.io node directory to check.
:type cbdir: str
:returns: The PID of the running Crossbar.io controller process or ``None``
:rtype: int or None | 625941f157b8e32f52483a5c |
def draw(self, axes, feature, bbox, loc, style_param): <NEW_LINE> <INDENT> n_turns = np.ceil((loc.last - loc.first + 1) / 3.6) <NEW_LINE> x_val = np.linspace(0, n_turns * 2*np.pi, 100) <NEW_LINE> y_val = (-0.4*np.sin(x_val) + 1) / 2 <NEW_LINE> x_val *= bbox.width / (n_turns * 2*np.pi) <NEW_LINE> x_val += bbox.x0 <NEW_L... | The drawing function that create helix visualization
Args:
axes, feature, bbox, loc, style_param : matplotlib parameters to create the plot that will be gave by ProteinPlotter class | 625941f163b5f9789fde76a3 |
def all_dataset_elements(self): <NEW_LINE> <INDENT> elements = [] <NEW_LINE> roots = [self.topLevelItem(i) for i in range(self.topLevelItemCount())] <NEW_LINE> for r in roots: <NEW_LINE> <INDENT> entries = [r.child(i) for i in range(r.childCount())] <NEW_LINE> topleveldatasets = [x for x in entries if type(x.getData())... | returns all the elements in the tree | 625941f1090684286d50f2ad |
def evaluate(self, input_fn, params): <NEW_LINE> <INDENT> def generate_features(): <NEW_LINE> <INDENT> ds = input_fn(params) <NEW_LINE> iterator = ds.make_one_shot_iterator() <NEW_LINE> next_element = iterator.get_next() <NEW_LINE> with tf.Session() as sess: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> while True: <NEW... | Predicts and returns a list of results from input_fn. | 625941f1b57a9660fec33e49 |
def check_withdrawal(self, amount): <NEW_LINE> <INDENT> if amount > self.balance: <NEW_LINE> <INDENT> return "You have sufficient funds for this withdrawal." <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return f"You have insufficient funds. Your current balance is: ${round(self.balance, 2)}" | Checks if a withdrawal is possible | 625941f1293b9510aa2c384d |
def reduce(self, f): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> strat = self._groebner_strategy() <NEW_LINE> return strat.normal_form(f) <NEW_LINE> <DEDENT> except (TypeError, NotImplementedError, ValueError): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> gb = self.groebner_basis() <NEW_LINE> return f.reduce(gb) | Reduce an element modulo the reduced Groebner basis for this ideal.
This returns 0 if and only if the element is in this ideal. In any
case, this reduction is unique up to monomial orders.
EXAMPLES::
sage: R.<x,y> = PolynomialRing(QQ, 2)
sage: I = (x^3 + y, y)*R
sage: I.reduce(y)
0
sage: I.reduce(... | 625941f1baa26c4b54cb16d6 |
def inputFormats(self): <NEW_LINE> <INDENT> pass | QPictureIO.inputFormats() -> list-of-QByteArray | 625941f12c8b7c6e89b35d79 |
def call_run_ws_client(className, add_args=[], renderclient=None, memGB=None, client_script=None, **kwargs): <NEW_LINE> <INDENT> logger.debug('call_run_ws_client -- classname:{} add_args:{} ' 'client_script:{} memGB:{}'.format( className, add_args, client_script, memGB)) <NEW_LINE> if renderclient is not None: <NEW_LIN... | simple call for run_ws_client.sh -- all arguments set in add_args
Parameters
----------
className : str
Render java client classname to call as first argv for
Render's call_run_ws_client.sh wrapper script
add_args : :obj:`list` of :obj:`str`, optional
command line arguments
renderclient : :class:`renderapi... | 625941f1d6c5a1020814460d |
def EnterMaintenanceMode_Task(self, timeout, evacuatePoweredOffVms=None): <NEW_LINE> <INDENT> return self.delegate("EnterMaintenanceMode_Task")(timeout, evacuatePoweredOffVms) | Puts the host in maintenance mode. While this task is running and when the host
is in maintenance mode, no virtual machines can be powered on and no
provisioning operations can be performed on the host. Once the call completes,
it is safe to turn off a host without disrupting any virtual machines.Puts the
host in maint... | 625941f1d164cc617578330c |
def __init__(self, address_line1=None, address_line2=None, city=None, region=None, postal_code=None, country=None): <NEW_LINE> <INDENT> self._address_line1 = None <NEW_LINE> self._address_line2 = None <NEW_LINE> self._city = None <NEW_LINE> self._region = None <NEW_LINE> self._postal_code = None <NEW_LINE> self._countr... | Address - a model defined in Swagger | 625941f1498bea3a759ba06b |
def guard_is_time_to_retry(guard, time): <NEW_LINE> <INDENT> if (guard['last_attempted'] < guard['unreachable_since']): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> diff = time - guard['unreachable_since'] <NEW_LINE> if (diff < 6*60*60): <NEW_LINE> <INDENT> return (time > (guard['last_attempted'] + 60*60)) <NEW_... | Tests if enough time has passed to retry an unreachable
(i.e. hibernating) guard. Derived from entry_is_time_to_retry() in
entrynodes.c. | 625941f1009cb60464c6396a |
def dist_ors(self, tree): <NEW_LINE> <INDENT> if tree[0] == '|' and type(tree[2]) is ListType and tree[2][0] == '&': <NEW_LINE> <INDENT> new_tree = ['&', ['|', tree[1], tree[2][1]], ['|', tree[1], tree[2][2]]] <NEW_LINE> return logicparser.apply_func(new_tree, self.dist_ors) <NEW_LINE> <DEDENT> if tree[0] == '|' and ty... | Distribute | over &.
INPUT:
- ``self`` -- calling object
_ ``tree`` -- a list. This represents a branch of
a parse tree.
OUTPUT:
A new list
EXAMPLES:
This example illustrates the distribution of '|' over '&'.
::
sage: import sage.logic.propcalc as propcalc, sage.logic.logicparser as logicparser
sage:... | 625941f1627d3e7fe0d6940f |
def ensemble(data, w, method='arithmetic'): <NEW_LINE> <INDENT> submission = pd.DataFrame({'id': data[list(data.keys())[0]]['id']}) <NEW_LINE> assert(method in ['arithmetic', 'geometric']) <NEW_LINE> if method == 'arithmetic': <NEW_LINE> <INDENT> submission['visitors'] = 0.0 <NEW_LINE> for key in data.keys(): <NEW_LINE... | @params: data: a dict of dataframes, <(str)filename: dataframe>
w: a dict of weights, <(str)filename: (int or float)weight>
method: either arithmetic mean or geometric mean.
@return: a new dataframe for submission | 625941f1b830903b967e9ec2 |
def sum_layout_dimensions(dimensions): <NEW_LINE> <INDENT> min = sum([d.min for d in dimensions if d.min is not None]) <NEW_LINE> max = sum([d.max for d in dimensions if d.max is not None]) <NEW_LINE> preferred = sum([d.preferred for d in dimensions]) <NEW_LINE> return LayoutDimension(min=min, max=max, preferred=prefer... | Sum a list of `LayoutDimension` instances. | 625941f1e64d504609d74dfd |
def create_object(self, row): <NEW_LINE> <INDENT> course_type_class = self.import_relative_path('cruds.crud_course_type.models.CourseType') <NEW_LINE> course_type = self.session.query(course_type_class).get(row[0]) <NEW_LINE> if course_type: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> obj = course_type_class() <NEW_... | row[0] - id;
row[1] - description; | 625941f16fece00bbac2dd03 |
def separate_scalar_factor(monomial): <NEW_LINE> <INDENT> scalar_factor = 1 <NEW_LINE> if isinstance(monomial, int): <NEW_LINE> <INDENT> return S.One, monomial <NEW_LINE> <DEDENT> if monomial == 0: <NEW_LINE> <INDENT> return S.One, 0 <NEW_LINE> <DEDENT> comm_factors, non_commfactors = split_commutative_parts(monomial) ... | Separate the constant factor from a monomial.
| 625941f194891a1f4081c069 |
def _set_page_info(self, type, api_response): <NEW_LINE> <INDENT> attribute = 'next_%s_page' % type <NEW_LINE> setattr(self, attribute, api_response.get('nextPageToken')) <NEW_LINE> attribute = '%s_pages' % type <NEW_LINE> setattr(self, attribute, self._count_pages(api_response['pageInfo'])) | Method for setting next page info for channel/video api request | 625941f163f4b57ef00016c5 |
def do_GET(self): <NEW_LINE> <INDENT> self.send_response(200) <NEW_LINE> self.send_header('Content-type','image/png') <NEW_LINE> self.end_headers() <NEW_LINE> with open('logo.png', 'rb') as f: <NEW_LINE> <INDENT> self.wfile.write(f.read()) <NEW_LINE> self.wfile.write('My dream is to fly over the rainbow, so high!') | Handler for GET requests | 625941f197e22403b379d559 |
def distance_approximation(fuel_consumption_100km, actual_fuel_value): <NEW_LINE> <INDENT> approximately_distance_km = round(( actual_fuel_value / fuel_consumption_100km )*0.8) <NEW_LINE> return approximately_distance_km | >>> distance_approximation(10,100)
8 | 625941f1099cdd3c635f1215 |
def write_packet(self, ts_sec, ts_usec, aa, packet): <NEW_LINE> <INDENT> payload = self.payload(aa, packet) <NEW_LINE> self.write_packet_header(ts_sec, ts_usec, len(payload)) <NEW_LINE> self.output.write(payload) <NEW_LINE> self.write_fifo(payload) <NEW_LINE> self.flush_fifo() | Add packet to PCAP output.
Basically, generates payload and encapsulates in a header. | 625941f194891a1f4081c06a |
def delete(self, pid, sid, mid): <NEW_LINE> <INDENT> project_handler = projects_manager.get_project_handler(pid) <NEW_LINE> return project_handler.remove_message_from_symbol(sid, mid) | Remove a message from a symbol | 625941f1de87d2750b860357 |
def get_xenon1t_afterpulses(self, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> return self.get_xenon1t_afterpulses_with_http_info(**kwargs) | Retrieves one or more Xenon1tAfterpulses # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_xenon1t_afterpulses(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:par... | 625941f1c432627299f05208 |
def get_instance_data(content): <NEW_LINE> <INDENT> if "$INSTANCE" in content: <NEW_LINE> <INDENT> lst = list(map(int, get_opt("INSTANCE", content).split())) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> lst = [] <NEW_LINE> for value in content.split(): <NEW_LINE> <INDENT> if int(value) != float(value): <NEW_LINE> <IND... | Extract the instance data from the content of a .vbp/.afg file. | 625941f110dbd63aa1bd315f |
def combine_image_and_heatmap(img,heatmap): <NEW_LINE> <INDENT> cmap = plt.get_cmap('jet') <NEW_LINE> heatmap = heatmap - np.min(heatmap) <NEW_LINE> heatmap /= np.max(heatmap) <NEW_LINE> heatmap = cmap(np.max(heatmap)-heatmap) <NEW_LINE> if np.max(heatmap) < 255.: <NEW_LINE> <INDENT> heatmap *= 255 <NEW_LINE> <DEDENT> ... | Takes in a numpy array for an image and the similarity heatmap.
Blends the two images together and returns a np array of the blended image. | 625941f14e696a04525c9a0b |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.