code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def warning(self, code, **args): <NEW_LINE> <INDENT> self.error_or_warning(code, severity='warning', **args) <NEW_LINE> self.num_warnings += 1 | Add warning code to self.codes. | 625941d7046cf37aa974cfa2 |
def fos_name_level_dict_query(fos_ids): <NEW_LINE> <INDENT> fos_target = ['NormalizedName', 'Level'] <NEW_LINE> fos_s = Search(index = 'fieldsofstudy', using = client) <NEW_LINE> fos_s = fos_s.query('terms', FieldOfStudyId=fos_ids) <NEW_LINE> fos_s = fos_s.source(fos_target) <NEW_LINE> fos_s = fos_s.params(request_time... | Find field of study name from id.
| 625941d766673b3332b922ed |
def formatOutputStreamList(streamlist, output_type): <NEW_LINE> <INDENT> if output_type == "json": <NEW_LINE> <INDENT> print(json.dumps(streamlist, indent=2)) <NEW_LINE> <DEDENT> if output_type == "text": <NEW_LINE> <INDENT> ParentTable = tt.Texttable() <NEW_LINE> ParentTable.set_cols_width([8,20,15,25,20,12]) <NEW_LIN... | Formats the output on a given format (json or text) | 625941d7377c676e91272404 |
def check_config(self): <NEW_LINE> <INDENT> self.ensure_w_config( ("step_config", "wgs_cnv_export", "path_wgs_cnv_annotation"), "Path to WGS SV annotation not configured but required for WGS SV export", ) | Check that the path to the NGS mapping is present | 625941d7d8ef3951e3243799 |
def add_replica(self, cluster_name, shard_index, host, port): <NEW_LINE> <INDENT> def on_shard(cluster_element, cluster_element_index, shard_element, shard_element_index): <NEW_LINE> <INDENT> if cluster_element.tag != cluster_name: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if shard_element_index != shard_index: <N... | Add new replica with host:port into cluster named cluster_name, shard with index shard_index
:param cluster_name:
:param shard_index:
:param host:
:param port:
:return: | 625941d773bcbd0ca4b2c2d1 |
def get_vocabulary(sources, emb, unidecode_lower=False): <NEW_LINE> <INDENT> if unidecode_lower: <NEW_LINE> <INDENT> vocabulary = list(set([unidecode(w).lower() for s in sources for w in s.split(' ')])) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> vocabulary = list(set([w for s in sources for w in s.split(' ')])) <NEW... | Gets vocabulary from the sources & creates word to index and index to word dictionaries
Inputs:
-> sources, list of string (to be interesting, you must clean your sentences before)
-> emb, fasttext embeddings
-> unidecode_lower, boolean, whether or not to decode and lowerizing words
Outputs:
-> vocabulary, li... | 625941d773bcbd0ca4b2c2d2 |
def __init__(self, id_node, config): <NEW_LINE> <INDENT> self._id = id_node <NEW_LINE> self._state = Node.IDLE <NEW_LINE> self._env = bgp_sim.Sim.Instance().env <NEW_LINE> Module.__init__(self) <NEW_LINE> self.event_store = simpy.Store(self._env) <NEW_LINE> self.routing_table = RoutingTable() <NEW_LINE> self.implicit_w... | __init__.
:param id_node: identifier of the node
:param config: Configuration file | 625941d73539df3088e2e5a6 |
def test_priority_set_successful(self): <NEW_LINE> <INDENT> panel = PriorityAdminPanel(self.env) <NEW_LINE> self.assertItemsEqual(panel.get_enum_list(), self.default['priority']) <NEW_LINE> self.env.config.set('ticket-field-config', 'priority', ','.join(self.new['priority'])) <NEW_LINE> admin_command = TicketFieldConfi... | When we add custom priority enum values to the config
and call TicketFieldConfigCommand.set_fields_from_config()
we expect the Trac environments priority enums to be updated with our
custom values and removal of the default values. | 625941d756ac1b37e6264428 |
def __init__(self, field_to_send, attrs=None, choices=()): <NEW_LINE> <INDENT> BootstrapTable.__init__(self) <NEW_LINE> Widget.__init__(self, attrs) <NEW_LINE> self._choices = None <NEW_LINE> self.choices = list(choices) <NEW_LINE> self.set(clickToSelect=True) <NEW_LINE> self.set(idField=field_to_send) | Initializes parent classes BootstrapTable and Widget and sets some
variables to allow imitating Select widget with use of BootstrapTable.
Args:
field_to_send: name of field, from which value will be send to server,
when submitting your form.
attrs: standard Django's attributes, to pass into Widget initializer.
choi... | 625941d7a17c0f6771cbe2ab |
def execute(self, value=None): <NEW_LINE> <INDENT> if not self.setpoints or (self.setpoints and self.setpoints.apply(value)): <NEW_LINE> <INDENT> if value == _const_psdev.PwrStateSel.On: <NEW_LINE> <INDENT> self.turn_on.execute() <NEW_LINE> <DEDENT> elif value == _const_psdev.PwrStateSel.Off: <NEW_LINE> ... | Execute Command. | 625941d77d43ff24873a2efc |
def _makeBugTargetProduct(self, bug_tracker=None, packaging=False, product_name=None): <NEW_LINE> <INDENT> product = self.factory.makeProduct(name=product_name) <NEW_LINE> if bug_tracker is not None: <NEW_LINE> <INDENT> with person_logged_in(product.owner): <NEW_LINE> <INDENT> if bug_tracker == 'launchpad': <NEW_LINE> ... | Return a product that may use Launchpad or an external bug tracker.
bug_tracker may be None, 'launchpad', or 'external'. | 625941d75fc7496912cc3bd9 |
def faz_download(url): <NEW_LINE> <INDENT> return ( urllib.request.urlopen(url, context=ssl.SSLContext(ssl.PROTOCOL_TLSv1)) .read() .decode("utf-8") ) | Captura a saída de uma requisição wed a url designada | 625941d70383005118ecf83d |
def set(self, valeur): <NEW_LINE> <INDENT> key = self.hash(valeur) <NEW_LINE> self.tab[key].append(valeur) | ajoute valeur dans la hashtable
:param valeur: le mot qu'on ajoute dans le hashTable | 625941d7dd821e528d63b403 |
def merge_states(self, states): <NEW_LINE> <INDENT> if not len(states): <NEW_LINE> <INDENT> raise ValueError("Cannot merge empty list of states!") <NEW_LINE> <DEDENT> if any(s.is_final != states[0].is_final for s in states): <NEW_LINE> <INDENT> raise ValueError("Cannot merge final and non-final states!") <NEW_LINE> <DE... | Merge a list of states in the automaton | 625941d7ac7a0e7691ed4324 |
@pytest.fixture(scope="function") <NEW_LINE> def closed_discussion(request, test_session, discussion): <NEW_LINE> <INDENT> from assembl.models import Role, DiscussionPermission, Permission <NEW_LINE> discussion.preferences['authorization_server_backend'] = 'google-oauth2' <NEW_LINE> role = test_session.query(Role).filt... | An empty Discussion fixture restricted-to-social login | 625941d7b830903b967e9b65 |
def colorize(self,p,incremental=False,interruptable=True): <NEW_LINE> <INDENT> trace = False and not g.unitTesting <NEW_LINE> verbose = True <NEW_LINE> self.count += 1 <NEW_LINE> if not incremental: <NEW_LINE> <INDENT> self.full_recolor_count += 1 <NEW_LINE> <DEDENT> s = p.b <NEW_LINE> if not s.strip(): <NEW_LINE> <IND... | The main colorizer entry point. | 625941d726238365f5f0f0cd |
def onWeather (target, source, effect): <NEW_LINE> <INDENT> pass | function (target, source, effect) {
if (target.hasItem('utilityumbrella'))
return;
if (effect.id === 'sunnyday' || effect.id === 'desolateland') {
this.damage(target.baseMaxhp / 8, target, target);
}
} | 625941d72c8b7c6e89b35a1b |
def find_student_sets(df: pd.DataFrame, student_set: Dict) -> Dict: <NEW_LINE> <INDENT> unique_students = np.unique(df[STUDENT_IDX].values) <NEW_LINE> unique_students.sort() <NEW_LINE> student_nb = len(unique_students) <NEW_LINE> if not student_set: <NEW_LINE> <INDENT> print("Creating student map for %d students" % len... | Get unique student sets and index
:param df: Input dataset
:param skill_set: Pre-define student set
:return: Dictionary of students and unique student number | 625941d7435de62698dfdea9 |
def cross_smas(data, smas=[10, 20], emas=[10]): <NEW_LINE> <INDENT> if data.Last.rolling(smas[0]).mean().iloc[-1] < data.Last.rolling(smas[1]).mean().iloc[-1] and data.Last.rolling(smas[0]).mean().iloc[-2] > data.Last.rolling(smas[1]).mean().iloc[-2]: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT... | Checks if it's an exit point based on crossed smas. | 625941d7596a897236089d1a |
def threshold_check(candidates, st_th): <NEW_LINE> <INDENT> num_limit = 1000 <NEW_LINE> values = list(candidates.values()) <NEW_LINE> num = num_limit + 1 <NEW_LINE> while num > num_limit: <NEW_LINE> <INDENT> st_th += 1 <NEW_LINE> num = sum(list(map(lambda x: 1 if x >= st_th else 0, values))) <NEW_LINE> <DEDENT> return ... | 动态计算阈值,调节倒排表中匹配的数量
阈值:两个句子有多少单词相同
:param candidates: dict 备选问题字典
:param st_th: int 初始阈值
:return:
st_th: int 调节后阈值
num: int 调节后备选集数量 | 625941d7090684286d50ef43 |
def getSmartDashboardType(self): <NEW_LINE> <INDENT> raise NotImplementedError | :returns: the string representation of the named data type that
will be used by the smart dashboard for this sendable | 625941d7656771135c3ebacc |
def load_answer(self, jid): <NEW_LINE> <INDENT> return self._connection.hget(name=self.ANSWER_KEY, key=jid) | Loads saved answer text | 625941d78e05c05ec3eea5d2 |
def __contains__(self, item): <NEW_LINE> <INDENT> if isinstance(item, BaseModel) and self._name == item._name: <NEW_LINE> <INDENT> return len(item) == 1 and item.id in self._ids <NEW_LINE> <DEDENT> elif isinstance(item, str): <NEW_LINE> <INDENT> return item in self._fields <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ... | Test whether ``item`` (record or field name) is an element of ``self``.
In the first case, the test is fully equivalent to::
any(item == record for record in self) | 625941d7442bda511e8be671 |
def cast(*args): <NEW_LINE> <INDENT> return _itkInPlaceImageFilterBPython.itkInPlaceImageFilterIUL2VIUL2_cast(*args) | cast(itkLightObject obj) -> itkInPlaceImageFilterIUL2VIUL2 | 625941d7507cdc57c6306f3b |
def check_float(str): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> float(str) <NEW_LINE> return True <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return False | Returns True if the input string represents a floating point number
Input:
- str: a string that should represent a floating-point number | 625941d729b78933be1e5905 |
def build_index(embedding_files_pattern, index_filename, vector_length, metric='angular', num_trees=100): <NEW_LINE> <INDENT> annoy_index = annoy.AnnoyIndex(vector_length, metric=metric) <NEW_LINE> mapping = {} <NEW_LINE> embed_files = tf.io.gfile.glob(embedding_files_pattern) <NEW_LINE> num_files = len(embed_files) <N... | Builds an ANNOY index | 625941d7ec188e330fd5a9f7 |
def OnQueryCursor(self,*args): <NEW_LINE> <INDENT> pass | OnQueryCursor(self: ContentElement,e: QueryCursorEventArgs)
Invoked when an unhandled System.Windows.Input.Mouse.QueryCursor�attached event reaches an
element in its route that is derived from this class. Implement this method to add class
handling for this event.
e: The System.Windows.Input.QueryCursor... | 625941d745492302aab5e522 |
def get_swagger_view(title=None, url=None): <NEW_LINE> <INDENT> return get_schema_view( title=title, url=url, renderer_classes=[ CoreJSONRenderer, OpenAPIRenderer, SwaggerUIRenderer ] ) | Returns schema view which renders Swagger/OpenAPI using custom get_schema_view. | 625941d7fbf16365ca6f6422 |
def load_files_list(self) -> List: <NEW_LINE> <INDENT> files_list = [] <NEW_LINE> for file in glob.glob(os.path.join(self.path, self.img_ext)): <NEW_LINE> <INDENT> files_list.append(file) <NEW_LINE> <DEDENT> return files_list | Get all files paths inside the dataset path
Returns
------- | 625941d701c39578d7e75097 |
def test_unavailable_items_not_displayed(self): <NEW_LINE> <INDENT> number = 5 <NEW_LINE> some_items = self.get_list_of_menu_items(number) <NEW_LINE> index = randint(0, number - 1) <NEW_LINE> unavailable = some_items.pop(index) <NEW_LINE> unavailable.available = False <NEW_LINE> unavailable.save() <NEW_LINE> expected_q... | MenuItem-s which have 'available' field set to False
are not returned for object list. | 625941d7287bf620b61d3cbe |
def test_new_user_email_normalized(self): <NEW_LINE> <INDENT> email = 'test@LONDONAPPDEV.COM' <NEW_LINE> user = get_user_model().objects.create_user(email, 'Test123') <NEW_LINE> self.assertEqual(user.email, email.lower()) | Test the email for a new user is normalized | 625941d73617ad0b5ed68152 |
def transform( self, parameters: mcu_pb.Parameters, alarm_limits: mcu_pb.AlarmLimits, sensor_measurements: mcu_pb.SensorMeasurements, events_log: alarms.Manager ) -> None: <NEW_LINE> <INDENT> if not parameters.ventilating: <NEW_LINE> <INDENT> events_log.input(alarms.AlarmDeactivationEvent( codes=self.ALARM_CODES )) <NE... | Update the simulation. | 625941d7498bea3a759b9d0b |
def _write(self): <NEW_LINE> <INDENT> if not HAS_MSGPACK: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> with salt.utils.fopen(self._path, 'w+') as fp_: <NEW_LINE> <INDENT> cache = { "CacheDisk_data": self._dict, "CacheDisk_cachetime": self._key_cache_time } <NEW_LINE> msgpack.dump(cache, fp_) | Write out to disk | 625941d7a934411ee37518f0 |
def eval_legendre_diff ( x, n ): <NEW_LINE> <INDENT> return n*x/(x ** 2 -1 ) * eval_legendre( x, n ) -n/(x ** 2 - 1) * eval_legendre( x, n-1 ) | Function for evaluating the derivative of the Legendre
polynomial of order n.
INPUT:
x: Real - point to be evaluated.
n: Integer - order of Legendre polynomial.
OUTPUT:
P_n'(x): Real. | 625941d750812a4eaa59c57c |
def getCodificacio(self): <NEW_LINE> <INDENT> return self.PARAM_CODIFICACIO + self.codificacio | Retorna la codificacio especificada | 625941d791f36d47f21ac750 |
def update_from_unit(self, translation, unit, pos, template=None): <NEW_LINE> <INDENT> if template is None: <NEW_LINE> <INDENT> src = get_source(unit) <NEW_LINE> ctx = get_context(unit) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> src = get_target(template) <NEW_LINE> ctx = get_context(template) <NEW_LINE> <DEDENT> ch... | Process translation toolkit unit and stores/updates database entry. | 625941d72eb69b55b151cb0d |
def load_cube_custom(file, var_name=None, file_convention=None, perform_fmt_checks=None): <NEW_LINE> <INDENT> if isinstance(file, Path): <NEW_LINE> <INDENT> file = str(file) <NEW_LINE> <DEDENT> if perform_fmt_checks is None: <NEW_LINE> <INDENT> perform_fmt_checks = const.GRID_IO.PERFORM_FMT_CHECKS <NEW_LINE> <DEDENT> c... | Load netcdf file as iris.Cube
Parameters
----------
file : str
netcdf file
var_name : str
name of variable to read
quality_check : bool
if True, then a quality check of data is performed against the
information provided in the filename
file_convention : :obj:`FileConventionRead`, optional
Aerocom f... | 625941d7a8ecb033257d3328 |
@process_request_body <NEW_LINE> def json_processor(entity): <NEW_LINE> <INDENT> if six.PY2: <NEW_LINE> <INDENT> body = entity.fp.read() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> contents = BytesIO() <NEW_LINE> body = entity.fp.read(fp_out=contents) <NEW_LINE> contents.seek(0) <NEW_LINE> body = salt.utils.stringuti... | Unserialize raw POST data in JSON format to a Python data structure.
:param entity: raw POST data | 625941d716aa5153ce3626d4 |
def block(self, node): <NEW_LINE> <INDENT> self.__add(node, PlaceHolder) | Reserve a name in the table. | 625941d70c0af96317bb8445 |
def create_ingress_security_policy(self): <NEW_LINE> <INDENT> if not VncSecurityPolicy.ingress_svc_fw_policy_uuid: <NEW_LINE> <INDENT> ingress_svc_fw_policy_uuid = VncSecurityPolicy.create_firewall_policy(self._k8s_event_type, None, None, is_global=True) <NEW_LINE> VncSecurityPolicy.add_firewall_policy(i... | Create a FW policy to house all ingress-to-service rules. | 625941d7287bf620b61d3cbf |
def include_cue(cue): <NEW_LINE> <INDENT> if __validate_cue(cue) == True: <NEW_LINE> <INDENT> return "13," + str(cue) + "H" | include cue | 625941d75fdd1c0f98dc0490 |
def envelope_fields(data): <NEW_LINE> <INDENT> fields = "Date Subject From Sender Reply-To To Cc Bcc In-Reply-To Message-Id" <NEW_LINE> fields = fields.split() <NEW_LINE> env = data['ENVELOPE'] <NEW_LINE> assert len(env) == len(fields) <NEW_LINE> result= dict(zip(fields, env)) <NEW_LINE> tuple_fields = 'From Sender Rep... | Extracts/normalizes the header fields from an IMAP response packet. | 625941d78c0ade5d55d3ec18 |
def _send_roster_unavailable_message(self, client): <NEW_LINE> <INDENT> msg = { 'channel':'/session/roster/unavailable', 'data': { 'username':client.username, 'siteId':client.siteId } } <NEW_LINE> self.publish(msg) | Sends a roster removal to all clients. | 625941d757b8e32f524836f8 |
def __call__(self, data): <NEW_LINE> <INDENT> assert self._file is not None, 'Reader is finalized' <NEW_LINE> if data != b'': <NEW_LINE> <INDENT> self._size += len(data) <NEW_LINE> length = self._requestCnt.length <NEW_LINE> if length is not None: <NEW_LINE> <INDENT> if self._size > length: <NEW_LINE> <INDENT> dif = se... | Push data into the reader. | 625941d799cbb53fe6792e43 |
def return_all_accounts(): <NEW_LINE> <INDENT> return r.eval( lua_accounts, 1, 'account:atomic', 0, 9999999, 'WITHSCORES') | Returns a list of all unique accounts with transactions. | 625941d78c0ade5d55d3ec19 |
def mock_strict_redis_client(**kwargs): <NEW_LINE> <INDENT> return MockRedis(strict=True, **kwargs) | Mock common.util.redis_client so we
can return a MockRedis object
instead of a StrictRedis object. | 625941d757b8e32f524836f9 |
def get_text(self, event=None): <NEW_LINE> <INDENT> self.dataDict["timeStamp"] = datetime.now() <NEW_LINE> self.dataDict["action"] = "TextInput" <NEW_LINE> self.dataDict["question"] = self.get_tab_name() <NEW_LINE> self.dataDict["answer"] = self.variables[self.pos].get() <NEW_LINE> self.saveDataDictToDB() | get text value | 625941d7e64d504609d74a9c |
def err5xx(request, code=500, msg="", extra_ctx=None): <NEW_LINE> <INDENT> return errxxx(request, 'err5xx.html', code, msg, extra_ctx) | Generic response for 5xx server-side error codes as per rfc2616
:returns resp: Our DoctorCom'ish err5xx | 625941d7a8370b7717052afb |
def draw_scoop_points(x, y, z, ax, color='g', size=100, random_offset=False): <NEW_LINE> <INDENT> if random_offset: <NEW_LINE> <INDENT> x = x + random.uniform(0, 0.005) <NEW_LINE> y = y + random.uniform(0, 0.005) <NEW_LINE> z = z + random.uniform(0, 0.005) <NEW_LINE> <DEDENT> ax.scatter(x, y, z, color=color, s=size) | Draw a scoop point on a 3D plot.
Optionally add random offset to easily visualize overlapping scoops. | 625941d7596a897236089d1b |
def aggregate_gradients_using_copy_with_variable_colocation( tower_grads, use_mean): <NEW_LINE> <INDENT> agg_grads = [] <NEW_LINE> for _, single_grads in enumerate(zip(*tower_grads)): <NEW_LINE> <INDENT> var = single_grads[0][1] <NEW_LINE> for _, v in single_grads: <NEW_LINE> <INDENT> assert v == var <NEW_LINE> <DEDENT... | Aggregate gradients, colocating computation with the gradient's variable.
Args:
tower_grads: List of lists of (gradient, variable) tuples. The outer list
is over individual gradients. The inner list is over the gradient
calculation for each tower.
use_mean: if True, mean is taken, else sum of gradients is ... | 625941d7a8ecb033257d3329 |
def test_genome_region(self, tr_fusion): <NEW_LINE> <INDENT> assert tr_fusion.genome_region == ('16', 52141017, 52141095) | Tests genome_region property. | 625941d77c178a314d6ef6bf |
def predict_proba(self, X, return_std=False): <NEW_LINE> <INDENT> if self.trace is None: <NEW_LINE> <INDENT> raise NotFittedError('Run fit on the model before predict.') <NEW_LINE> <DEDENT> if self.cached_model is None: <NEW_LINE> <INDENT> self.cached_model = self.create_model() <NEW_LINE> <DEDENT> self._set_shared_var... | Predicts probabilities of new data with a trained Dirichlet Process
Mixture Model
Parameters
----------
X : numpy array, shape [n_samples, n_features]
cats : numpy array, shape [n_samples, ]
return_std : Boolean flag
Boolean flag of whether to return standard deviations with mean
probabilities. Defaults to Fal... | 625941d731939e2706e4d0c4 |
def ls_dirs(dirpath: str = ".", abs: bool = False) -> List[str]: <NEW_LINE> <INDENT> dirs = (dir for dir in ls(dirpath, abs=True) if path.isdir(dir)) <NEW_LINE> if not abs: <NEW_LINE> <INDENT> return list(map(lambda el: el.replace(dirpath, "."), dirs)) <NEW_LINE> <DEDENT> return list(dirs) | :param dirpath:
:param abs:
:return: | 625941d7a219f33f34628bc3 |
@plugin.route("/search") <NEW_LINE> def search(): <NEW_LINE> <INDENT> query = get_arg("q") <NEW_LINE> page = int(get_arg("page", 1)) <NEW_LINE> category = get_arg("category") <NEW_LINE> if get_arg("delete"): <NEW_LINE> <INDENT> eafa.searches.remove(query) <NEW_LINE> xbmc.executebuiltin("Container.Refresh()") <NEW_LINE>... | Shows saved searches menu and handles new searches | 625941d791af0d3eaac9bc77 |
def test_Tmin(self): <NEW_LINE> <INDENT> self.assertAlmostEqual(self.surfarr.Tmin.value_si, self.Tmin, 6) | Test that the SurfaceArrhenius Tmin property was properly set. | 625941d7bde94217f368304c |
def __init__(self, artists, x = [], y = [], tolerance = 5, offsets = (-20, 20), formatter = fmt, display_all = False): <NEW_LINE> <INDENT> self._points = np.column_stack((x,y)) <NEW_LINE> self.formatter = formatter <NEW_LINE> self.offsets = offsets <NEW_LINE> self.display_all = display_all <NEW_LINE> if not cbook.itera... | Create the data cursor and connect it to the relevant figure.
"artists" is the matplotlib artist or sequence of artists that will be
selected.
"tolerance" is the radius (in points) that the mouse click must be
within to select the artist.
"offsets" is a tuple of (x,y) offsets in points from the selected
p... | 625941d730c21e258bdfa6fb |
def create_virtual_machine(module, profitbricks): <NEW_LINE> <INDENT> datacenter = module.params.get('datacenter') <NEW_LINE> name = module.params.get('name') <NEW_LINE> auto_increment = module.params.get('auto_increment') <NEW_LINE> count = module.params.get('count') <NEW_LINE> lan = module.params.get('lan') <NEW_LINE... | Create new virtual machine
module : AnsibleModule object
profitbricks: authenticated profitbricks object
Returns:
True if a new virtual machine was created, false otherwise | 625941d76fb2d068a760f2fd |
def add_invalid_product_to_buy(self, buyer, wrong_id=False): <NEW_LINE> <INDENT> p = self.random_product() <NEW_LINE> self.not_exist_product_id = 123456 <NEW_LINE> large_quantity = p.get_quantity() + 2 <NEW_LINE> if wrong_id: <NEW_LINE> <INDENT> self.add_product( buyer, self.gen_product_json( self.not_exist_product_id,... | add invalid product (This method will return product id) | 625941d730dc7b7665901bc1 |
def get_output_template(by_age: bool, by_sex: bool, by_year: bool, **_) -> OutputTemplate: <NEW_LINE> <INDENT> template = "${measure}" <NEW_LINE> if by_year: <NEW_LINE> <INDENT> template += "_in_${year}" <NEW_LINE> <DEDENT> if by_sex: <NEW_LINE> <INDENT> template += "_among_${sex}" <NEW_LINE> <DEDENT> if by_age: <NEW_L... | Gets a template string for output metrics.
The template string should be filled in using filter criteria for
measure, age, sex, and year in the observer using this function.
Parameters
----------
by_age
Whether the template should include age criteria.
by_sex
Whether the template should include sex criteria.
... | 625941d7d8ef3951e324379a |
@auth.requires_login() <NEW_LINE> def connect_exploits(): <NEW_LINE> <INDENT> form = SQLFORM.factory( Field('f_taskit', type='boolean', default=auth.user.f_scheduler_tasks, label=T('Run in background task')), ) <NEW_LINE> from skaldship.exploits import connect_exploits <NEW_LINE> if form.accepts(request.vars, session):... | Call the connect_exploits() function which links known vulnerabilities to
exploits based on f_vulnid or f_cve | 625941d7fbf16365ca6f6423 |
def __load_repo(self): <NEW_LINE> <INDENT> repo_data = {} <NEW_LINE> repo_file_content = open(self._user_repo_config, 'r') <NEW_LINE> line = repo_file_content.readline().strip() <NEW_LINE> repo = '' <NEW_LINE> while line != '': <NEW_LINE> <INDENT> if line.startswith('repo'): <NEW_LINE> <INDENT> line_split = line.split(... | Read gitolite config file | 625941d78a349b6b435e83d0 |
def test03a_namespace_lookup_on_update(self): <NEW_LINE> <INDENT> import cppyy <NEW_LINE> gbl = cppyy.gbl <NEW_LINE> lib2 = cppyy.load_reflection_info("advancedcpp2Dict.so") <NEW_LINE> assert gbl.a_ns is gbl.a_ns <NEW_LINE> assert gbl.a_ns.d_ns is gbl.a_ns.d_ns <NEW_LINE> assert gbl.a_ns.g_class is gb... | Test whether namespaces can be shared across dictionaries. | 625941d7b7558d58953c516d |
def attribut_optimal(self, donnees, attributs): <NEW_LINE> <INDENT> entropies_attributs = [] <NEW_LINE> for attribut, set_value in attributs.items(): <NEW_LINE> <INDENT> entropie_minimale = 10000 <NEW_LINE> valeur_partitionnement = str() <NEW_LINE> for value in set_value: <NEW_LINE> <INDENT> entropie = self.h_C_A(donne... | Cherche l'attribut et sa valeur qui minimisent l'entropie
Retourne l'attribut et la valeur pour partitionner
:param: donnees : les donnees d'apprentissage
:param: attributs : tous les attributs et leur domaine de valeur
{attribut : {valeurs}}
:return: attribut_optimal : un tuple (nom... | 625941d763b5f9789fde7342 |
def loadconfig(self): <NEW_LINE> <INDENT> self.riders.clear() <NEW_LINE> cr = ConfigParser.ConfigParser({'startlist':'', 'start':'', 'lstart':'', 'places':'', 'limit':'' }) <NEW_LINE> cr.add_section('race') <NEW_LINE> cr.add_section('riders') <NEW_LINE> if os.path.isfile(self.configpath): <NEW_LINE> <INDENT> self.log.d... | Load race config from disk. | 625941d7b7558d58953c516e |
def test_generic_2650_name(self, a: ClassUnderTest) -> None: <NEW_LINE> <INDENT> hypothesis.assume(not a.closed) <NEW_LINE> self.assertIsInstance(a.mode, str) <NEW_LINE> name = a.name <NEW_LINE> if isinstance(name, int): <NEW_LINE> <INDENT> self.assertEqual(name, a.fileno()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT... | io.FileIO.name | 625941d73346ee7daa2b2fca |
def __init__(self, type=None, id=None): <NEW_LINE> <INDENT> self._type = None <NEW_LINE> self._id = None <NEW_LINE> if type is not None: <NEW_LINE> <INDENT> self.type = type <NEW_LINE> <DEDENT> if id is not None: <NEW_LINE> <INDENT> self.id = id | TripResourceRelationshipsServiceData - a model defined in Swagger | 625941d794891a1f4081bd07 |
def onTimer(self, tid, userArg): <NEW_LINE> <INDENT> if userArg == 1: <NEW_LINE> <INDENT> if self.TerritoryControllerId <= 0: <NEW_LINE> <INDENT> self.AddTerritory() | 引擎回调timer触发 | 625941d79b70327d1c4e1033 |
def delete_finished_deferred_tasks(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> user_tasks_list = self.tasks_collection.find({}) <NEW_LINE> for user_tasks in user_tasks_list: <NEW_LINE> <INDENT> if Keys.TASKS_KEY in user_tasks: <NEW_LINE> <INDENT> new_list = [] <NEW_LINE> for task in user_tasks[Keys.TASKS_KEY]: ... | Delete method for removing deferred tasks that are completed. | 625941d723849d37ff7b32eb |
def get_attribute( self, key=None, category=None, value=None, strvalue=None, obj=None, attrtype=None, **kwargs ): <NEW_LINE> <INDENT> dbmodel = self.model.__dbclass__.__name__.lower() <NEW_LINE> query = [("attribute__db_attrtype", attrtype), ("attribute__db_model", dbmodel)] <NEW_LINE> if obj: <NEW_LINE> <INDENT> query... | Return Attribute objects by key, by category, by value, by
`strvalue`, by object (it is stored on) or with a combination of
those criteria.
Args:
key (str, optional): The attribute's key to search for.
category (str, optional): The category of the attribute(s)
to search for.
value (str, optional): ... | 625941d7091ae356686671b8 |
def plotHDD(HDD, B, M, s): <NEW_LINE> <INDENT> hpars, deltaM, Bdm = plotHYS( HDD['hyst'], B, M, s) <NEW_LINE> DdeltaM = [] <NEW_LINE> Mhalf = "" <NEW_LINE> for k in range(2, len(Bdm)): <NEW_LINE> <INDENT> DdeltaM.append( old_div(abs(deltaM[k] - deltaM[k - 2]), (Bdm[k] - Bdm[k - 2]))) <NEW_LINE> <DEDENT> for k in range(... | function to make hysteresis, deltaM and DdeltaM plots | 625941d721bff66bcd684bae |
def getName(self): <NEW_LINE> <INDENT> return self.name | retorna el name del canal | 625941d75510c4643540f63d |
def get_search_dict(self, actor_id): <NEW_LINE> <INDENT> _dict = { "size": self.max_link_size, "query": {"bool": {"must": {"term": {"actor_id": actor_id}}}}, "sort": [{"linked": {"order": "desc"}}], } <NEW_LINE> return _dict | Constructs a ES search that will be used to search for the network of actor_id
:param actor_id: The actor to search for its network links
:return: A dict that will be passes to ES | 625941d74e696a04525c96a9 |
def list_path(root_path): <NEW_LINE> <INDENT> files=[] <NEW_LINE> dirs=[] <NEW_LINE> for x in os.listdir(root_path): <NEW_LINE> <INDENT> if os.path.isfile(os.path.join(root_path,x)): <NEW_LINE> <INDENT> files.append(x) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dirs.append(x) <NEW_LINE> <DEDENT> <DEDENT> return file... | 列出路径下的文件、目录 | 625941d7f548e778e58cd7dc |
def refresh(self, conditional=False): <NEW_LINE> <INDENT> headers = getattr(self, 'CUSTOM_HEADERS', {}) <NEW_LINE> if conditional: <NEW_LINE> <INDENT> if self.last_modified: <NEW_LINE> <INDENT> headers['If-Modified-Since'] = self.last_modified <NEW_LINE> <DEDENT> elif self.etag: <NEW_LINE> <INDENT> headers['If-None-Mat... | Re-retrieve the information for this object.
The reasoning for the return value is the following example: ::
repos = [r.refresh() for r in g.repositories_by('kennethreitz')]
Without the return value, that would be an array of ``None``'s and you
would otherwise have to do: ::
repos = [r for i in g.repositori... | 625941d7d58c6744b4257ebc |
def aprovats(assig,quadri,an): <NEW_LINE> <INDENT> f1 = open('NouFitxer.csv','r') <NEW_LINE> c = 0 <NEW_LINE> for linea in f1: <NEW_LINE> <INDENT> linea = linea.strip() <NEW_LINE> l = linea.split(';') <NEW_LINE> if l[2] == assig: <NEW_LINE> <INDENT> if l[3] == an: <NEW_LINE> <INDENT> if l[4] == quadri: <NEW_LINE> <INDE... | retorna el nombre d'aprovats per assignatura, quadrimestre i any | 625941d7097d151d1a2230b5 |
def x_y_proc( self, y: str = "ptime", x: str = "time", xmethod: str = "m", meanlength: int = invalidint, ) -> Tuple[np.ndarray, np.ndarray]: <NEW_LINE> <INDENT> x = self.get(field=x, method=xmethod, meanlength=meanlength) <NEW_LINE> y = np.array( [ self.get(field=y, method=f"p{proc}", meanlength=meanlength) for proc in... | Return two data fields as named in 'x' and 'y'.
The returned values can be directly plotted with matplotlib.
'y' contains the individual datas obtained from each thread.
Valid field names for x and y are listed in self.datanames
'methodx' and 'meanlength' parameters are as defined in get method.
@param y: field na... | 625941d744b2445a339322f2 |
def remove(table, id_): <NEW_LINE> <INDENT> table = data_manager.get_table_from_file("accounting/items.csv") <NEW_LINE> for lines in table: <NEW_LINE> <INDENT> if str(lines[0]) == id_[0]: <NEW_LINE> <INDENT> table.remove(lines) <NEW_LINE> <DEDENT> <DEDENT> table_remove = data_manager.write_table_to_file("accounting/ite... | Remove a record with a given id from the table.
Args:
table (list): table to remove a record from
id_ (str): id of a record to be removed
Returns:
list: Table without specified record. | 625941d730bbd722463cc025 |
def reveal_at(self, x, y): <NEW_LINE> <INDENT> pboard = json.loads(self.player_board) <NEW_LINE> if pboard[y][x] != 'v': <NEW_LINE> <INDENT> pboard[y][x] = 'v' <NEW_LINE> self.player_board = json.dumps(pboard) <NEW_LINE> board = json.loads(self.board) <NEW_LINE> rows, cols = len(board), len(board[0]) <NEW_LINE> if boar... | Reveals a field in point (x,y)
If if is already revealed ('v') exits the function.
Else it marks the field as revealed. Also if the field has not adjacent fields with mines in them, it calls the
function recursively in order to reveal all the adj fields until a field with value > 0 is found. | 625941d7925a0f43d254a0d6 |
def _verbose_reporter(self, run_details=None): <NEW_LINE> <INDENT> if run_details is None: <NEW_LINE> <INDENT> print(' |{:^25}|{:^42}|'.format('Population Average', 'Best Individual')) <NEW_LINE> print('-' * 4 + ' ' + '-' * 25 + ' ' + '-' * 42 + ' ' + '-' * 10) <NEW_LINE> line_format = '{:>4} {:>8} {:>16} {:>8} {:>1... | A report of the progress of the evolution process.
Parameters
----------
run_details : dict
Information about the evolution. | 625941d77b180e01f3dc4a57 |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, SurveyLinkFilter): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.to_dict() == other.to_dict() | Returns true if both objects are equal | 625941d766656f66f7cbc40a |
def __init__(self, arg1, arg2): <NEW_LINE> <INDENT> pass | Init for AnotherClass.
:param arg1: This is the description arg1.
:type arg1: str
:param arg2: This is the description for arg2.
:type arg2: ing | 625941d7ab23a570cc2503e1 |
def lynch(self, target, *args): <NEW_LINE> <INDENT> return self.PlayerList[self.authorname.split('!')[0]].lynch(target) | Lynch lynch lynch lynch :O | 625941d766673b3332b922ef |
def validate_account(self, step, user_id, pin): <NEW_LINE> <INDENT> is_valid = User.objects(user_id=user_id, pin=pin).count() > 0 <NEW_LINE> print('Validación de cuenta de usuario: ', 'Válida' if is_valid else 'Inválida') <NEW_LINE> Execution( workflow=str(self.workflow.pk), name=step['id'], type=Execution.TYPE_STEP, r... | Valída que la cuenta del usuario solicitado sea válida. | 625941d773bcbd0ca4b2c2d3 |
@pytest.fixture(scope='module') <NEW_LINE> def new_booking(init_db, new_property, new_user): <NEW_LINE> <INDENT> new_user.save() <NEW_LINE> new_property.save() <NEW_LINE> return Booking(user_id=new_user.id, property_id=new_property.id, checkin_date=datetime.strptime('2025-01-01', DATE_FORMAT), checkout_date=datetime.st... | New property fixture | 625941d797e22403b379d1f8 |
def _get_server_version_info(self, connection, **kw): <NEW_LINE> <INDENT> stmt = select([text('InfoData')], from_obj=[text('dbc.dbcinfov')]). where(text('InfoKey=\'VERSION\'')) <NEW_LINE> res = connection.execute(stmt).scalar() <NEW_LINE> return res | Returns the Teradata Database software version. | 625941d7498bea3a759b9d0c |
def make_plan(self, prev_success): <NEW_LINE> <INDENT> raise NotImplementedError() | return (plan, plan_checker) | 625941d7293b9510aa2c34f1 |
def Parse(self, resource_path, project_path=''): <NEW_LINE> <INDENT> if '/' in resource_path: <NEW_LINE> <INDENT> match = self._RegexMatch(resource_path) <NEW_LINE> if match is None: <NEW_LINE> <INDENT> raise sdk_ex.HttpException( 'Invalid {0} Identifier'.format(self._ResourceType().capitalize())) <NEW_LINE> <DEDENT> s... | Initializes a new ResourceIdentifier.
Args:
resource_path: (string) Full (e.g., projects/my-proj/topics/my-topic)
or partial (my-topic) resource path.
project_path: (string) Full (projects/my-project) or
partial (my-project) project path.
If empty, the SDK environme... | 625941d7cdde0d52a9e53292 |
def declare(self): <NEW_LINE> <INDENT> for ability in self.context.attacker.get_abilities(action='attack', trigger=self.current_step) + self.context.defender.get_abilities(action='defense', trigger=self.current_step): <NEW_LINE> <INDENT> ability.apply(self) | Declare target (step 1). | 625941d78e71fb1e9831da06 |
def __init__( self, tile_config_xml ): <NEW_LINE> <INDENT> self.root = xml.etree.ElementTree.parse( tile_config_xml ).getroot() | Init the google map manager, responsible for reading the google map config file | 625941d7379a373c97cfada3 |
def remove_directory(name: "TPathLike") -> None: <NEW_LINE> <INDENT> path_name = Path(name) <NEW_LINE> if path_name.exists() and path_name.is_dir(): <NEW_LINE> <INDENT> logger.info(f"Removing directory '{name!s}'") <NEW_LINE> shutil.rmtree(path_name) | Remove directory recursively and print a log message. | 625941d7ac7a0e7691ed4326 |
def __init__(self, loss_function, iterations=100, n_candidates=100, n_kept_best=0, learning_rate=0.1, regularization=10., verbose=False): <NEW_LINE> <INDENT> self.loss_function = loss_function <NEW_LINE> self.iterations = iterations <NEW_LINE> self.n_candidates = n_candidates <NEW_LINE> self.n_kept_best = n_kept_best <... | Represents basic pruning algorithm, which greedily adds trees
:param loss_function: loss function (following hep_ml convention for losses)
:param iterations: int, how many estimators we shall leave
:param n_candidates: how many candidate_trees we check on each iteration
:param n_kept_best: how many classifiers saved fr... | 625941d7b830903b967e9b67 |
def filter_src_file(filepath: Path) -> gpd.GeoDataFrame: <NEW_LINE> <INDENT> ids_to_omit = [ 10, 21, 39, 41, 56, 93, 96, 105, 253, ] <NEW_LINE> gdf = gpd.read_file(filepath) <NEW_LINE> return gdf[~gdf["dvrpc_id"].isin(ids_to_omit)] | Read source geofile, omitting features in the list of IDs omit | 625941d7e5267d203edcdef8 |
def get_all_top(self): <NEW_LINE> <INDENT> return self.execute(TABELLE['top']['select']['all']) | Prende tutti gli user in top
@:return: lista (o dizionario dipende da quanti user ci sono) di utenti | 625941d7596a897236089d1c |
def to_absolute_coordinates(rboxlist, height, width, check_range=False, scope=None): <NEW_LINE> <INDENT> with tf.name_scope(scope, 'ToAbsoluteCoordinatesRbox'): <NEW_LINE> <INDENT> height = tf.cast(height, tf.float32) <NEW_LINE> width = tf.cast(width, tf.float32) <NEW_LINE> if check_range: <NEW_LINE> <INDENT> cy, cx, _... | Converts normalized box coordinates to absolute pixel coordinates.
This function raises an assertion failed error when the maximum box coordinate
value is larger than 1.01 (in which case coordinates are already absolute).
Args:
rboxlist: BoxList with coordinates in range [0, 1].
height: Maximum value for height o... | 625941d75fc7496912cc3bdc |
def sample_ccdesign(self, **kwargs): <NEW_LINE> <INDENT> dim = len(self.designvars) <NEW_LINE> dv0 = list(self.designvars.values())[0] <NEW_LINE> doe = pd.DataFrame(columns=[x.name for x in self.designvars.values()]) <NEW_LINE> doe_cc_raw = pd.DataFrame(pydoe.ccdesign(dim, face='ccf'), columns=[x.name for x in self.des... | Central composite design
:param n: number of sample points
:return: doe | 625941d78e05c05ec3eea5d4 |
def testEnumAnalogInBits(self): <NEW_LINE> <INDENT> nBits = dwf.EnumAnalogInBits(self.idxDevice) | Test EnumAnalogInBits | 625941d729b78933be1e5906 |
def add_jobflow_steps(self, jobflow_id, steps): <NEW_LINE> <INDENT> if type(steps) != types.ListType: <NEW_LINE> <INDENT> steps = [steps] <NEW_LINE> <DEDENT> params = {} <NEW_LINE> params['JobFlowId'] = jobflow_id <NEW_LINE> step_args = [self._build_step_args(step) for step in steps] <NEW_LINE> params.update(self._buil... | Adds steps to a jobflow
:type jobflow_id: str
:param jobflow_id: The job flow id
:type steps: list(boto.emr.Step)
:param steps: A list of steps to add to the job | 625941d71b99ca400220ad10 |
def parse(self, response): <NEW_LINE> <INDENT> sel = Selector(response) <NEW_LINE> sites = sel.xpath('//td[@class="title"]') <NEW_LINE> items = [] <NEW_LINE> for site in sites: <NEW_LINE> <INDENT> item = Website() <NEW_LINE> item['name'] = site.xpath('a/text()').extract() <NEW_LINE> item['url'] = site.xpath('a/@href').... | The lines below is a spider contract. For more info see:
http://doc.scrapy.org/en/latest/topics/contracts.html
@url http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/
@scrapes name | 625941d7de87d2750b85fff2 |
def refresh(self, event): <NEW_LINE> <INDENT> xsize = int((event.width-1)/ self.columns) <NEW_LINE> ysize = int((event.height-1)/ self.rows) <NEW_LINE> self.size = min(xsize, ysize) <NEW_LINE> self.canvas.delete("square") <NEW_LINE> color = self.color2 <NEW_LINE> for row in range(self.rows): <NEW_LINE> <INDENT> color =... | Redraw the board, because of window resizing or other event | 625941d77b25080760e396b6 |
def __init__( self, inFileOrFolder, outFile, compression=True, globalSettingsFile=None, searchSettingsFile=True, includeChannelList=None, discardChannelList=None, ): <NEW_LINE> <INDENT> inFiles = [] <NEW_LINE> if os.path.isfile(inFileOrFolder): <NEW_LINE> <INDENT> inFiles.append(inFileOrFolder) <NEW_LINE> <DEDENT> elif... | Convert the given cfs file to NWB. By default all ADC channel are written in to the NWB file.
Keyword arguments:
inFileOrFolder -- input file, or folder with multiple files, in cfs v2 format
outFile -- target filepath (must not exist)
compression -- Toggle compression for HDF5 datasets
s... | 625941d7167d2b6e31218df3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.