code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def handler(self, scheme=None, category=None, unconfigured=False): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> hasher = self._get_record(scheme, category) <NEW_LINE> if unconfigured: <NEW_LINE> <INDENT> return hasher._Context__orig_handler <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return hasher <NEW_LINE> <DEDENT>... | helper to resolve name of scheme -> :class:`~passlib.ifc.PasswordHash` object used by scheme.
:arg scheme:
This should identify the scheme to lookup.
If omitted or set to ``None``, this will return the handler
for the default scheme.
:arg category:
If a user category is specified, and no scheme is pro... | 625941e5cb5e8a47e48b7ed4 |
def judgeCircle(moves): <NEW_LINE> <INDENT> x=0 <NEW_LINE> y=0 <NEW_LINE> for move in moves: <NEW_LINE> <INDENT> print(move) <NEW_LINE> if(move == 'U'): <NEW_LINE> <INDENT> y = y+1 <NEW_LINE> <DEDENT> if(move == 'D'): <NEW_LINE> <INDENT> y = y-1 <NEW_LINE> <DEDENT> if(move == 'L'): <NEW_LINE> <INDENT> x = x-1 <NEW_LINE... | :type moves: str
:rtype: bool | 625941e5bd1bec0571d90a5f |
def nitems_written(self, *args, **kwargs): <NEW_LINE> <INDENT> return _gnuradio_core_general.gr_vector_to_streams_sptr_nitems_written(self, *args, **kwargs) | nitems_written(self, unsigned int which_output) -> uint64_t | 625941e5d4950a0f3b08c779 |
def edit_profile(request, form_class=None, success_url=None, template_name='profiles/edit_profile.html', extra_context=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> profile_obj = request.user.get_profile() <NEW_LINE> <DEDENT> except ObjectDoesNotExist: <NEW_LINE> <INDENT> return HttpResponseRedirect(reverse('prof... | Edit the current user's profile.
If the user does not already have a profile (as determined by
``User.get_profile()``), a redirect will be issued to the
:view:`profiles.views.create_profile` view; if no profile model
has been specified in the ``AUTH_PROFILE_MODULE`` setting,
``django.contrib.auth.models.SiteProfileNot... | 625941e510dbd63aa1bd2fd2 |
def late_import(): <NEW_LINE> <INDENT> global gap, gap3, libgap <NEW_LINE> global GapElement_Integer, GapElement_Rational, GapElement_Cyclotomic <NEW_LINE> from sage.libs.gap.libgap import libgap <NEW_LINE> from sage.libs.gap.element import ( GapElement_Integer, GapElement_Rational, GapElement_Cyclotomic) <NEW_LINE> fr... | This function avoids importing libgap on startup. It is called once through
the constrcturo of :class:`UniversalCyclotomicField`.
EXAMPLES::
sage: import sage.rings.universal_cyclotomic_field as ucf
sage: _ = UniversalCyclotomicField() # indirect doctest
sage: ucf.libgap is None # indirect... | 625941e5ad47b63b2c50a3af |
def findSubstringInWraproundString(self, p: str) -> int: <NEW_LINE> <INDENT> if not p: return 0 <NEW_LINE> n = len(p) <NEW_LINE> existHash = {} <NEW_LINE> preSum = [0] * (n + 1) <NEW_LINE> w = 1 <NEW_LINE> for i in range(n): <NEW_LINE> <INDENT> existHash.setdefault(p[i], 0) <NEW_LINE> if i > 0 and (ord(p[i]) - ord(p[i ... | preSum 求和 | 625941e5d8ef3951e324396e |
def DescribeBasicAlarmList(self, request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> params = request._serialize() <NEW_LINE> body = self.call("DescribeBasicAlarmList", params) <NEW_LINE> response = json.loads(body) <NEW_LINE> if "Error" not in response["Response"]: <NEW_LINE> <INDENT> model = models.DescribeBasicAl... | 获取基础告警列表
:param request: Request instance for DescribeBasicAlarmList.
:type request: :class:`tencentcloud.monitor.v20180724.models.DescribeBasicAlarmListRequest`
:rtype: :class:`tencentcloud.monitor.v20180724.models.DescribeBasicAlarmListResponse` | 625941e576d4e153a657ef62 |
def mangle_volume(citation_elements): <NEW_LINE> <INDENT> volume_re = re.compile(r"(\d+)([A-Z])", re.U | re.I) <NEW_LINE> for el in citation_elements: <NEW_LINE> <INDENT> if el['type'] == 'JOURNAL': <NEW_LINE> <INDENT> matches = volume_re.match(el['volume']) <NEW_LINE> if matches: <NEW_LINE> <INDENT> el['volume'] = mat... | Make sure the volume letter is before the volume number
e.g. transforms 100B to B100 | 625941e5bde94217f368321d |
def __str__(self): <NEW_LINE> <INDENT> return self.get() | Return the bars. | 625941e563d6d428bbe44921 |
def param_print(self, paramD, row_tickL=None, const_col_w=True, col_tickL=None, header='', x_axis_label='', y_axis_label='', none_str='*'): <NEW_LINE> <INDENT> rows_outL = [] <NEW_LINE> for row in self.s_hash_rowL: <NEW_LINE> <INDENT> outL = [] <NEW_LINE> for s_hash in row: <NEW_LINE> <INDENT> if (s_hash in paramD) and... | parameter values are in dictionary paramD
paramD index=s_hash, value=string | 625941e52c8b7c6e89b35bee |
def main(args): <NEW_LINE> <INDENT> options = process_args(args) <NEW_LINE> logging.debug("Processed args: options=%s", options) <NEW_LINE> if not options.swig_executable or len(options.swig_executable) == 0: <NEW_LINE> <INDENT> if options.find_swig: <NEW_LINE> <INDENT> must_exist = not options.allow_static_binding <NE... | Drives the main script preparation steps.
@param args list of command line arguments. | 625941e5cad5886f8bd27409 |
def import_csv(self, csvfileobject): <NEW_LINE> <INDENT> self._tracks = [] <NEW_LINE> self._selected = None <NEW_LINE> for row in csvfileobject: <NEW_LINE> <INDENT> if row[0] == "T": <NEW_LINE> <INDENT> track = self.addTrack() <NEW_LINE> track.properties = row <NEW_LINE> <DEDENT> elif row[0] == "P": <NEW_LINE> <INDENT>... | Extracts info from a file object and stores it in memory in
order to display it on the timeline.
Refer to the `export` method to learn about input file format
and structure. | 625941e5fff4ab517eb2f86f |
def handle_hooks(stage, hooks, region, namespace, mappings, parameters): <NEW_LINE> <INDENT> if not hooks: <NEW_LINE> <INDENT> logger.debug("No %s hooks defined.", stage) <NEW_LINE> return <NEW_LINE> <DEDENT> hook_paths = [] <NEW_LINE> for i, h in enumerate(hooks): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> hook_path... | Used to handle pre/post_build hooks.
These are pieces of code that we want to run before/after the builder
builds the stacks. | 625941e5b830903b967e9d37 |
def __init__(self, readonly : bool = True): <NEW_LINE> <INDENT> if os.path.exists('token.pickle'): <NEW_LINE> <INDENT> with open('token.pickle', 'rb') as token: <NEW_LINE> <INDENT> self.__creds = pickle.load(token) <NEW_LINE> <DEDENT> <DEDENT> if not self.__creds or not self.__creds.valid: <NEW_LINE> <INDENT> if self._... | creator for read-only access
:param readonly: bool
create a read-only version of the class | 625941e5a934411ee3751ac5 |
def is_termux(): <NEW_LINE> <INDENT> return "com.termux" in os.environ["PATH"] and find_executable("termux-open-url") | Return whether we are running under the Termux application for Android | 625941e530c21e258bdfa8d1 |
def print_info(self): <NEW_LINE> <INDENT> Students.sid += 1 <NEW_LINE> print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nSitudrnt ID :{}".format( Students.sid)) <NEW_LINE> print( 'Student Name :{} ' '\nStudent Departement : {}' '\nStudent Age :{} ' '\nStudent Lvl :{} ' '\nStudent Marks ... | Regular method Pass III inistance > as the first argument (SELF....) | 625941e55e10d32532c5f355 |
def create_prime_list(max_value): <NEW_LINE> <INDENT> prime_list = [] <NEW_LINE> for x in range(2,max_value+1): <NEW_LINE> <INDENT> temp_list = create_factor_list(x) <NEW_LINE> if len(temp_list)==2: <NEW_LINE> <INDENT> prime_list.append(x) <NEW_LINE> <DEDENT> <DEDENT> return(prime_list) | Returns a list of primes that occur less than or equal to max_value. | 625941e5de87d2750b8601c7 |
@register.simple_tag(takes_context=True) <NEW_LINE> def get_value_from_view(context, field): <NEW_LINE> <INDENT> view = context['view'] <NEW_LINE> obj = None <NEW_LINE> if 'object' in context: <NEW_LINE> <INDENT> obj = context['object'] <NEW_LINE> <DEDENT> value = view.lookup_field_value(context, obj, field) <NEW_LINE>... | Responsible for deriving the displayed value for the passed in 'field'.
This first checks for a particular method on the ListView, then looks for a method
on the object, then finally treats it as an attribute. | 625941e5293b9510aa2c36c2 |
def is_unavailable(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> product_quantity = api.get_storage_quantity(self.product) <NEW_LINE> <DEDENT> except models.ObjectDoesNotExist: <NEW_LINE> <INDENT> product_quantity = 0 <NEW_LINE> <DEDENT> for publishing in self.publishings.all(): <NEW_LINE> <INDENT> if publishing.... | Returns True when products stock cannot satisfy published listings | 625941e55fdd1c0f98dc0665 |
def top(self): <NEW_LINE> <INDENT> while self.stack and len(self.stack) - 1 in self.toPop_stack: <NEW_LINE> <INDENT> x = self.stack.pop() <NEW_LINE> self.toPop_stack.remove(len(self.stack)) <NEW_LINE> <DEDENT> return self.stack[-1] | :rtype: int | 625941e5d18da76e2353290b |
@get('/SDNproxy') <NEW_LINE> def proxy_listing_handler(): <NEW_LINE> <INDENT> response.headers['Content-Type'] = 'application/json' <NEW_LINE> response.headers['Cache-Control'] = 'no-cache' <NEW_LINE> if check_auth_header(request.headers): <NEW_LINE> <INDENT> logger.debug("Listing SDNproxies with full details!") <NEW_L... | Handles name listing | 625941e599cbb53fe6793015 |
def rotate(self, matrix): <NEW_LINE> <INDENT> l_matrix = len(matrix) <NEW_LINE> self.rotateR(0, l_matrix - 1, matrix) | :type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead. | 625941e57d847024c06be6f0 |
def test_Priority_up(self): <NEW_LINE> <INDENT> homepage = HomePage(self.driver) <NEW_LINE> driver = self.driver <NEW_LINE> domain = driver.find_element_by_xpath('//*[@id="table"]/tbody/tr[1]/td[3]').text <NEW_LINE> domain1 = driver.find_element_by_xpath('//*[@id="table"]/tbody/tr[2]/td[3]').text <NEW_LINE> encoding = ... | 优先级上移 | 625941e573bcbd0ca4b2c4a6 |
def isEmpty(self): <NEW_LINE> <INDENT> return (self._size == 0) | Check if a 'Queue' object is empty.
@return: A boolean value: 'True' if queue is empty, otherwise 'False' | 625941e5099cdd3c635f1089 |
@blueprint.route('tweet/update/<project>', methods=['POST']) <NEW_LINE> def add_to_pq(project): <NEW_LINE> <INDENT> data = request.get_json() <NEW_LINE> logger.debug('Incoming request with data {}'.format(data)) <NEW_LINE> if data is None or 'user_id' not in data or 'tweet_id' not in data: <NEW_LINE> <INDENT> report_er... | Update priority score in queue and remember that a user has already classified a tweet | 625941e501c39578d7e7526c |
def findMaxConsecutiveOnes(self, nums): <NEW_LINE> <INDENT> counter = 0 <NEW_LINE> temp = 0 <NEW_LINE> for num in nums: <NEW_LINE> <INDENT> if num == 1: <NEW_LINE> <INDENT> temp += 1 <NEW_LINE> if temp >= counter: <NEW_LINE> <INDENT> counter = temp <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> temp = 0 <NEW_LI... | :type nums: List[int]
:rtype: int | 625941e567a9b606de4a82e7 |
def calculate(self): <NEW_LINE> <INDENT> result = 1 <NEW_LINE> cur = self.n <NEW_LINE> while cur != 1: <NEW_LINE> <INDENT> if cur % 2: <NEW_LINE> <INDENT> result += 1 <NEW_LINE> cur -= 1 <NEW_LINE> <DEDENT> while not cur % 2: <NEW_LINE> <INDENT> cur //= 2 <NEW_LINE> <DEDENT> <DEDENT> return str(result) | Main calcualtion function of the class | 625941e54e4d5625662d4802 |
def main(): <NEW_LINE> <INDENT> args = parseArgs() <NEW_LINE> completed_classes = [] <NEW_LINE> for class_name in args.class_names: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> logging.info('Downloading class: %s', class_name) <NEW_LINE> if download_class(args, class_name): <NEW_LINE> <INDENT> completed_classes.append(... | Main entry point for execution as a program (instead of as a module). | 625941e5cc0a2c11143dd2c2 |
def convert_standard_normal(data): <NEW_LINE> <INDENT> return data.sub(data.mean(axis=1), axis=0) | Subtract Each row from its Mean | 625941e5ec188e330fd5abc7 |
def squared_loss(y_hat, y): <NEW_LINE> <INDENT> return (y_hat - d2l.reshape(y, y_hat.shape)) ** 2 / 2 | 均方损失
Defined in :numref:`sec_linear_scratch` | 625941e556b00c62f0f14a8d |
def test_get(self): <NEW_LINE> <INDENT> pass | Test case for get
Get information of a single input on this node | 625941e54e4d5625662d4803 |
def get_reservoir_data_for_data_aug(reservoir_data_receive, data_aug): <NEW_LINE> <INDENT> reservoir_data_list = [] <NEW_LINE> if int((reservoir_data_receive[-1][2]-reservoir_data_receive[0][1]-data_aug[0])/data_aug[1]) <=0: <NEW_LINE> <INDENT> reservoir_data_list.append(reservoir_data_receive) <NEW_LINE> <DEDENT> else... | 根据滑动窗口生成不同的目标层段
:param reservoir_data_receive: 专家划定的目标层段 ,里面的元素有 4 项,分别是 well_name , depth_bottom , depth_top , reservoir_Info,其中的储层顶和底都是用时间表示的
:param data_aug: 是一个list, 表示滑动窗口的大小和滑动距离
:return: reservoir_data_list : 表示生成的目标层段的 list | 625941e58e7ae83300e4b3ff |
def __init__(self, url=default_url, **kwargs): <NEW_LINE> <INDENT> WatsonService.__init__( self, 'personality_insights', url, **kwargs) | Construct an instance. Fetches service parameters from VCAP_SERVICES
runtime variable for Bluemix, or it defaults to local URLs. | 625941e5e1aae11d1e74a0ec |
def init_db(): <NEW_LINE> <INDENT> db.create_all() | Binds the database to the specific class tables
and creates them if needed
:param db_uri: URI to the database
:return: None | 625941e5d164cc6175783180 |
def solve(self, system0: Optional[System] = None, system1: Optional[System] = None, neighbors: Optional[NeighborList] = None, cutoff: Optional[float] = None, reference: Optional[int] = None): <NEW_LINE> <INDENT> if system0 is not None: <NEW_LINE> <INDENT> self.__system0 = system0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <I... | Solves the differential displacement vectors.
Parameters
----------
system0 : atomman.system, optional
The base/reference system to use.
system1 : atomman.system, optional
The defect/current system to use.
neighbors : atomman.NeighborList, optional
The neighbor list to use.
cutoff : float, optional
C... | 625941e563b5f9789fde7517 |
def test_get_not_found_component_list(self): <NEW_LINE> <INDENT> u <NEW_LINE> response = self.client.get(reverse('bugwaz-component-list', kwargs = {'product': 0})) <NEW_LINE> self.assertEqual(response.status_code, 404) | 存在しないプロダクトからコンポーネント一覧を取得しようとすると404エラー | 625941e55166f23b2e1a558a |
@api_bp.route("/products/elastic/document/fields/code_signature", methods=['GET']) <NEW_LINE> def socfaker_elasticecsfields_code_signature(): <NEW_LINE> <INDENT> if validate_request(request): <NEW_LINE> <INDENT> return jsonify(str(socfaker.products.elastic.document.fields.code_signature)) | Returns an ECS Code Signature dictionary
Returns:
dict: Returns a dictionary of ECS
Code Signature fields/properties
| 625941e53346ee7daa2b31a0 |
def Tree(): <NEW_LINE> <INDENT> return collections.defaultdict(Tree) | Initializes a Python tree with arbitrary depth.
Member functions should be customized for adding nodes. | 625941e53317a56b8693a07f |
def recipe_detail(): <NEW_LINE> <INDENT> global loaded_recipe <NEW_LINE> if loaded_recipe is None: <NEW_LINE> <INDENT> menu_message = "No loaded recipe." <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> menu_message = "Recipe details for: {}".format(loaded_recipe['recipe']['name']) <NEW_LINE> <DEDENT> decorator = ("-=" * ... | Show recipe details | 625941e54e696a04525c987e |
def test_fulltext_tag_virtual_indexes_on(self): <NEW_LINE> <INDENT> self.assertEqual(('fulltext',), zip(*get_marc_tag_indexes('8564_u'))[1]) | bibindex - checks if 'get_marc_tag_indexes' for tag 8564_u will find only 'fulltext' index | 625941e5ec188e330fd5abc8 |
def reset_mtimes(): <NEW_LINE> <INDENT> set_mtime( str(EXAMPLE_DIR / '2004-05-07 20.16.31.jpg'), datetime(2004, 5, 7, 11, 16, 31)) <NEW_LINE> set_mtime( str(EXAMPLE_DIR / '2006-09-09 07.00.24.jpg'), datetime(2006, 9, 8, 22, 0, 24)) <NEW_LINE> set_mtime( str(EXAMPLE_DIR / '2006-09-09 07.00.24-alt.jpg'), datetime(2006, 9... | Reset the mtimes on our test files because git doesn't keep them. | 625941e5a79ad161976cc576 |
def add_row(self, row): <NEW_LINE> <INDENT> if len(row) != self._row_length: <NEW_LINE> <INDENT> raise RuntimeError("Invalid row length") <NEW_LINE> <DEDENT> self._rows.append(row) | Append a new row of data.
| 625941e5e64d504609d74c71 |
def _cancelled(self, url, item): <NEW_LINE> <INDENT> log.downloads.debug("MHTML download cancelled by user: {}".format(url)) <NEW_LINE> item.fileobj.seek(0) <NEW_LINE> item.fileobj.truncate() | Callback when a download is cancelled by the user.
Args:
url: The original url of the asset as QUrl.
item: The DownloadItem given by the DownloadManager. | 625941e521a7993f00bc8128 |
def get(endpoint_id): <NEW_LINE> <INDENT> return database.get(Endpoint, endpoint_id) | Retrieves an endpoint given it's ID
:param endpoint_id:
:return: | 625941e556ac1b37e62645f8 |
@curry <NEW_LINE> def filter(fun, values): <NEW_LINE> <INDENT> return (value for value in values if fun(value)) | A function that filters a list of values by a predicate function and returns
a generator.
Complexity: O(n*k) where k is the complexity of the given function
params:
fun: the fucntion that should be applied
values: the list of values we should filter
returns:
the new generator | 625941e57cff6e4e81117db7 |
def CloseProVersion(self, request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> params = request._serialize() <NEW_LINE> body = self.call("CloseProVersion", params) <NEW_LINE> response = json.loads(body) <NEW_LINE> if "Error" not in response["Response"]: <NEW_LINE> <INDENT> model = models.CloseProVersionResponse() <NE... | 本接口 (CloseProVersion) 用于关闭专业版。
:param request: Request instance for CloseProVersion.
:type request: :class:`tencentcloud.cwp.v20180228.models.CloseProVersionRequest`
:rtype: :class:`tencentcloud.cwp.v20180228.models.CloseProVersionResponse` | 625941e5f548e778e58cd9b1 |
def create_resource(options): <NEW_LINE> <INDENT> deserializer = wsgi.JSONRequestDeserializer() <NEW_LINE> return wsgi.Resource(WatchController(options), deserializer) | Watch resource factory method. | 625941e5f7d966606f6aa43a |
def get_middle_point(self): <NEW_LINE> <INDENT> num_rows, num_cols = self.lons.shape <NEW_LINE> mid_row = num_rows // 2 <NEW_LINE> depth = 0 <NEW_LINE> if num_rows & 1 == 1: <NEW_LINE> <INDENT> mid_col = num_cols // 2 <NEW_LINE> if num_cols & 1 == 1: <NEW_LINE> <INDENT> if self.depths is not None: <NEW_LINE> <INDENT> d... | Return the middle point of the mesh.
:returns:
An instance of :class:`~openquake.hazardlib.geo.point.Point`.
The middle point is taken from the middle row and a middle column
of the mesh if there are odd number of both. Otherwise the geometric
mean point of two or four middle points. | 625941e55fc7496912cc3daf |
def probability_outcome_given_token(self, token, outcome): <NEW_LINE> <INDENT> token_probability = ( sum([self.outcomes[other_outcome].probability_token_given_outcome(token) * self.probability_outcome(other_outcome) for other_outcome in self.outcomes.keys()])) <NEW_LINE> if token_probability <= 0.0000001: <NEW_LINE> <I... | Give P(O | T) for outcome O and token T. | 625941e5462c4b4f79d1db00 |
def gap_name(name=None): <NEW_LINE> <INDENT> if name is None: <NEW_LINE> <INDENT> st,res = _check(_at("AT+GAPDEVNAME")) <NEW_LINE> if st: <NEW_LINE> <INDENT> return res <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> st,res = _check(_at("AT+GAPDEVNAME="+str(name))) <NEW_LINE> if st: <NEW_... | .. function:: gap_name(name=None)
If *name* is None, returns the current Bluefruit device name. Otherwise changes the current name to *name*.
Returns True on success.
| 625941e5090684286d50f11d |
@BackportTest(None) <NEW_LINE> def backport_double_conflict(sbox): <NEW_LINE> <INDENT> sbox.simple_append('branch/iota', 'Conflicts with first change') <NEW_LINE> sbox.simple_commit(message="Conflicting change on iota") <NEW_LINE> sbox.simple_update() <NEW_LINE> sbox.simple_append('subversion/trunk/iota', 'Third line\n... | two-revisioned entry with two conflicts | 625941e52eb69b55b151cce6 |
def __init__(self, data, metadata, chunks=None, daskify=True, thread_safe=True, fancy_index=True, order=True, ch_offsets=None): <NEW_LINE> <INDENT> if not isinstance(data, list): <NEW_LINE> <INDENT> data = [data] <NEW_LINE> <DEDENT> if not isinstance(metadata, list): <NEW_LINE> <INDENT> metadata = [metadata] <NEW_LINE>... | Constructor for time series data objects.
Parameters
----------
data : list
List of arrays of input data.
metadata : list
List of experiment metadata dictionaries.
chunks : None, list
Dask chunks of the input data, or None to pull the chunks from the input data.
daskify : bool
Set to True to convert in... | 625941e563f4b57ef000153e |
def sort_opts(self, opts): <NEW_LINE> <INDENT> def sort_cfg(cfg): <NEW_LINE> <INDENT> return cfg.name <NEW_LINE> <DEDENT> return sorted(opts, key=sort_cfg) | Sort oslo config options by name
:param opts: list of olo cfg opts
:return list - sorted by name | 625941e526068e7796caf116 |
def lower(self, actual, lower, msg=None): <NEW_LINE> <INDENT> _msg = self.message("assert_lower", actual, lower, msg=msg) <NEW_LINE> if actual > lower: <NEW_LINE> <INDENT> raise AssertionError(actual, lower, _msg) <NEW_LINE> <DEDENT> return True | Allow to encapsulate method assertLower(a, b, msg=msg) | 625941e5a8370b7717052ccf |
def get_carrier_cert(self, req_id): <NEW_LINE> <INDENT> uri = "http://{}:{}/ctl-application/application/{}/report?type=1".format(self.host, self.port, req_id) <NEW_LINE> return get_json(uri) | :return:
{
"appId": "41f092d0-87ee-11e7-a55d-00163e0f04ac",
"token": "85d27d31b27c4a2fbc462ee753c78e90",
"mobile": "13012343123",
"name": "jiaoh",
"idCard": "372929199305160070",
"taskId": "30b415c0-9373-11e7-807a-00163e0cb266"
} | 625941e5099cdd3c635f108a |
def getPresentation(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if len(self.presentation.raw) < 6: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.presentation.raw <NEW_LINE> <DEDENT> <DEDENT> except Exception: <NEW_LINE> <INDENT> return False | :return: Le texte en format ``raw`` s'il existe.
Sinon ``False`` | 625941e5796e427e537b09fb |
def update_visibility(self, id: str, *, extendable: bool = None, include: 'VisibilityDetail' = None, exclude: 'VisibilityDetail' = None, account: str = None, **kwargs ) -> DetailedResponse: <NEW_LINE> <INDENT> if id is None: <NEW_LINE> <INDENT> raise ValueError('id must be provided') <NEW_LINE> <DEDENT> if include is n... | Update visibility.
Update an Object's Visibility. You must have an administrator role in the scope of
the provided token. This endpoint is ETag enabled.
:param str id: The object's unique ID.
:param bool extendable: (optional) Allows the visibility to be extenable.
:param VisibilityDetail include: (optional) Visibili... | 625941e5851cf427c661a93d |
def menu(exits): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> print_menu(exits) <NEW_LINE> print_menu(exits, room_items, inv_items) <NEW_LINE> user_input = input("> ") <NEW_LINE> normalised_user_input = normalise_input(user_input) <NEW_LINE> if is_valid_exit(exits, normalised_user_input): <NEW_LINE> <INDENT> ret... | This function, given a dictionary of possible exits from a room, prints the
menu of exits using print_menu() function. It then prompts the player to type
a name of an exit where she wants to go. The players's input is normalised
using the normalise_input() function before further checks are done. The
function then che... | 625941e550812a4eaa59c74f |
@app.route("/sms", methods=['POST']) <NEW_LINE> def sms_reply(): <NEW_LINE> <INDENT> msg = request.form.get('Body') <NEW_LINE> if msg == "hello": <NEW_LINE> <INDENT> resp = MessagingResponse() <NEW_LINE> resp.message("enter the roll number and password \n example:- 17EE01011<space>password") <NEW_LINE> return str(resp)... | Respond to incoming calls with a simple text message. | 625941e58e71fb1e9831dbd9 |
def _create_fixed_ips(self, context, network_id, fixed_cidr=None): <NEW_LINE> <INDENT> network = self._get_network_by_id(context, network_id) <NEW_LINE> bottom_reserved = self._bottom_reserved_ips <NEW_LINE> top_reserved = self._top_reserved_ips <NEW_LINE> if not fixed_cidr: <NEW_LINE> <INDENT> fixed_cidr = netaddr.IPN... | Create all fixed ips for network. | 625941e5d58c6744b425808f |
def backprop(self, x, y): <NEW_LINE> <INDENT> ZH = self.mWeightsH @ x + self.mBiasesH <NEW_LINE> AH = sigmoid(ZH) <NEW_LINE> ZO = self.mWeightsO @ AH + self.mBiasesO <NEW_LINE> AO = sigmoid(ZO) <NEW_LINE> epsilonO = (AO - y) <NEW_LINE> nabla_BO = epsilonO <NEW_LINE> nabla_WO = epsilonO @ AH.transpose() <NEW_LINE> epsi... | Backpropagation to calculate the gradient for the cost function
x: training inputs
y: correct result for inputs x | 625941e5379a373c97cfaf78 |
def build_from_netrc(endpoint_url: str = DEFAULT_ENDPOINT_URL) -> Resource: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> netrc_hosts = netrc.netrc().hosts <NEW_LINE> <DEDENT> except FileNotFoundError as e: <NEW_LINE> <INDENT> raise AnnofabApiException(e) from e <NEW_LINE> <DEDENT> annofab_hostname = (urlparse(endpoint_... | ``.netrc`` ファイルから、annofabapi.Resourceインスタンスを生成する。
Args:
endpoint_url: AnnoFab APIのエンドポイント。
Returns:
annofabapi.Resourceインスタンス | 625941e56fece00bbac2db75 |
def chess_rook_find_min(n: int, m: int): <NEW_LINE> <INDENT> f = [[(n+m) if n*m == 0 else 0 for m in range(m+1)] for n in range(n+1)] <NEW_LINE> f[1][1] = 0 <NEW_LINE> for n in range(1, n+1): <NEW_LINE> <INDENT> for m in range(1, m+1): <NEW_LINE> <INDENT> if n*m == 1: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> f[... | A chess rook is placed on chess board size of N*M
The rook can make only 1 step horizontally or vertically for 1 move
What minimal number of moves required to reach point (N,M)?
|R|_|_|_|
|_|_|_|_|
|_|_|_|_|
|_|_|_|x|
Recursive function... | 625941e59c8ee82313fbbba8 |
def gyf2gms_list(gyf_list): <NEW_LINE> <INDENT> gms_list = [] <NEW_LINE> for i in gyf_list: <NEW_LINE> <INDENT> gms_list.append((gyf2gms(i[0]), gyf2gms(i[1]))) <NEW_LINE> <DEDENT> return gms_list | Conversion (g0.ggg,g1.ggg) --> ((g0,mm,ss.sss),(g1,mm,ss.sss)) masiva.
Por ejemplo: gyf_list = [(-61.5,-31.456),(-63.456,31.3333),...] | 625941e5f9cc0f698b140a29 |
def dailyTemperatures(self, temperatures): <NEW_LINE> <INDENT> stack = [] <NEW_LINE> solution = [] <NEW_LINE> for index, value in enumerate(reversed(temperatures)): <NEW_LINE> <INDENT> while len(stack) != 0 and stack[-1][1] <= value: <NEW_LINE> <INDENT> del stack[-1] <NEW_LINE> <DEDENT> if len(stack) == 0: <NEW_LINE> <... | :type temperatures: List[int]
:rtype: List[int] | 625941e515fb5d323cde0f47 |
def get_data(self, path): <NEW_LINE> <INDENT> with _io.FileIO(path, 'r') as file: <NEW_LINE> <INDENT> return file.read() | Return the data from path as raw bytes. | 625941e507f4c71912b118b6 |
def test_hashing_based_on_eq_same_object(self): <NEW_LINE> <INDENT> tenant, relation = self.create_attached_relation() <NEW_LINE> tenant2, relation2 = self.create_attached_relation() <NEW_LINE> test_dic = {} <NEW_LINE> test_dic[relation] = 5 <NEW_LINE> test_dic[relation2] = 10 <NEW_LINE> self.assertEqual(len(test_dic),... | Test that the __hash__ works according to __eq__
Details: https://github.com/datacenter/acitoolkit/issues/233 | 625941e5b57a9660fec33cbc |
def getVars(self): <NEW_LINE> <INDENT> vars = wcomponents.WTemplated.getVars(self) <NEW_LINE> plugin = self._register.getPluginByName(self._activeTab, instantiate=False) <NEW_LINE> if self._contribId is not None: <NEW_LINE> <INDENT> vars["report"] = plugin.getContributionReport(self._startDate, self._endDate, self._con... | In this method it is expected that any implementations of statistics
have both a getContributionReport and getConferenceReport method
defined, the results of which are the data for the view. | 625941e5bd1bec0571d90a60 |
def __init__(self, entry_matcher_obj_1, entry_matcher_obj_2): <NEW_LINE> <INDENT> self.list_1 = entry_matcher_obj_1.match_result <NEW_LINE> self.list_2 = entry_matcher_obj_2.match_result | Init function
Arguments:
entry_matcher_obj_1 -- the first EntryMatcher() instance name you want to pass to this metawrapper
entry_matcher_obj_2 -- the second EntryMatcher() instance name you want to pass to this metawrapper | 625941e592d797404e3045be |
def queueTask(self, id, task, args=None): <NEW_LINE> <INDENT> if self.__isJoining: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if not callable(task): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> self.__tasks.put((id, task, args)) <NEW_LINE> return True | Insert a task into the queue. task must be callable;
args can be None. | 625941e5167d2b6e31218fc7 |
def updateDataPoints(self, dict): <NEW_LINE> <INDENT> if dict: <NEW_LINE> <INDENT> for k in dict.keys(): <NEW_LINE> <INDENT> if "name" in str(k): <NEW_LINE> <INDENT> if not hasattr(self.datapoints, dict[k]): <NEW_LINE> <INDENT> self.manage_addRRDDataPoint(str(dict[k])) <NEW_LINE> <DEDENT> if not hasattr(self.datapoints... | update datapoints is called from Zuul/facades/templatefacade.py
we try/except the method from there and then check it closely here | 625941e5d7e4931a7ee9e351 |
def test_many_words_mixed_value_limit_less_geq_greater(self): <NEW_LINE> <INDENT> arg1 = {'hello': 2, 'bye': 2, 'ok': 1, 'big': 3} <NEW_LINE> arg2 = 2 <NEW_LINE> exp_arg1 = {'big': 3} <NEW_LINE> act_return = tweets.common_words(arg1, arg2) <NEW_LINE> exp_return = None <NEW_LINE> msg = "Expected {}, but returned {}".for... | Dictionary with more than one word a few with same values and a
few with unique values and limit is less than the keys in the dictionary
and the limit is equal to the amount of words with the same values where
the unique values and one key contains a maximum value | 625941e58da39b475bd653ab |
def reset(self): <NEW_LINE> <INDENT> self._componentValues = noValue <NEW_LINE> return self | Remove all components and become a |ASN.1| schema object.
See :meth:`isValue` property for more information on the
distinction between value and schema objects. | 625941e5287bf620b61d3e93 |
def multiply_fn(obj, env): <NEW_LINE> <INDENT> obj.evaluate_all_args() <NEW_LINE> ret = 1 <NEW_LINE> for item in obj.args: <NEW_LINE> <INDENT> if is_symbol(item): <NEW_LINE> <INDENT> raise Exception("You can't add a non-defined symbol - %s" % item) <NEW_LINE> <DEDENT> ret *= float(item) <NEW_LINE> <DEDENT> return str(r... | Returns string value of product of self.args. It is assumed that item in self.args is a symbol,
it is assumed it does not exist in env and an Exception is raised.
>>> dummyCls = type('temp', (object,), {'args': ['9.4', '-2', '5'], 'evaluate_all_args': lambda x: True})
>>> dummy = dummyCls()
>>> pr = multiply_fn(dummy,... | 625941e52eb69b55b151cce7 |
def prepare_request(self): <NEW_LINE> <INDENT> user_agent = self.random_user_agent() <NEW_LINE> self.captcha_headers['User-Agent'] = user_agent <NEW_LINE> ts = int(time.time()) <NEW_LINE> val_url = 'http://iir.circ.gov.cn/web/servlet/ValidateCode?time={}'.format(ts) <NEW_LINE> current_path = os.path.dirname(os.path.abs... | :return: cookie对象, 验证码图片文件名 | 625941e5091ae35668667389 |
@login_required <NEW_LINE> def change_password(request): <NEW_LINE> <INDENT> if request.method == 'POST': <NEW_LINE> <INDENT> if request.POST["new_password"] and request.POST["new_password_confirmation"] and request.POST["password"] and request.POST["password_confirmation"]: <NEW_LINE> <INDENT> new_password = request.P... | Changes password in User model. | 625941e5a8ecb033257d34fd |
def unregisterEventReader(self, callback): <NEW_LINE> <INDENT> self.eventReaders.remove(callback) | Unregisters a event reader
@param callback: The function that should be unregistered | 625941e57047854f462a1837 |
def timestamp_delta_seconds(timestamp: datetime.datetime) -> float: <NEW_LINE> <INDENT> return (datetime.datetime.now() - timestamp).total_seconds() | What's the time difference, in seconds, of our clock vs the timestamp in the message? | 625941e59b70327d1c4e1209 |
def trace(s, save=False, larg=16,haut=9): <NEW_LINE> <INDENT> if not isMotzkin(s): raise MotzkinError(s) <NEW_LINE> plt.figure(figsize=(larg,haut)) <NEW_LINE> plt.suptitle("Code de Motzkin {}".format(s), fontsize=24) <NEW_LINE> plt.subplot(2,2,1) <NEW_LINE> plt.axis('off') <NEW_LINE> col=(1,.5,.2) <NEW_LINE> plt.plot(*... | Trace pour un code de Motzkin s, sur une même figure
--> le cercle avec les cordes disjointes
--> le mot de Motzkin
--> le chemin de Motzkin
--> l'arbre unaire-binaire
comme ils ont été définis dans la vidéo
l'option save à True enregsitre le fichier sous le nom Code, suivi d'un numéro
obtenu en ajoutant 1 à ... | 625941e529b78933be1e5ad9 |
@exporter.export <NEW_LINE> def add_station_lat_lon(df, stn_var): <NEW_LINE> <INDENT> df['latitude'] = None <NEW_LINE> df['longitude'] = None <NEW_LINE> for stn in df[stn_var].unique(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> info = station_info[stn] <NEW_LINE> df.loc[df[stn_var] == stn, 'latitude'] = info.latitud... | Lookup station information to add the station latitude and longitude to the DataFrame.
This function will add two columns to the DataFrame ('latitude' and 'longitude') after
looking up all unique station identifiers available in the DataFrame.
Parameters
----------
df : `pandas.DataFrame`
The DataFrame that conta... | 625941e5b545ff76a8914247 |
def get_chromecasts( tries=None, retry_wait=None, timeout=None, blocking=True, callback=None, zeroconf_instance=None, known_hosts=None, ): <NEW_LINE> <INDENT> if blocking: <NEW_LINE> <INDENT> devices, browser = discover_chromecasts(known_hosts=known_hosts) <NEW_LINE> cc_list = [] <NEW_LINE> for device in devices: <NEW_... | Searches the network for chromecast devices and creates a Chromecast object
for each discovered device.
Returns a tuple of:
A list of Chromecast objects, or an empty list if no matching chromecasts were
found.
A service browser to keep the Chromecast mDNS data updated. When updates
are (no longer) needed, call... | 625941e5b5575c28eb68e436 |
def test_get_role_assignments(self): <NEW_LINE> <INDENT> user1 = unit.new_user_ref(domain_id=self.domain['id']) <NEW_LINE> user1 = self.identity_api.create_user(user1) <NEW_LINE> collection_url = '/role_assignments' <NEW_LINE> r = self.get(collection_url) <NEW_LINE> self.assertValidRoleAssignmentListResponse(r, resourc... | Call ``GET /role_assignments``.
The sample data set up already has a user, group and project
that is part of self.domain. We use these plus a new user
we create as our data set, making sure we ignore any
role assignments that are already in existence.
Since we don't yet support a first class entity for role
assignmen... | 625941e5377c676e912725d9 |
def reset_adc_min_max(self): <NEW_LINE> <INDENT> for k in self.adc_labels: <NEW_LINE> <INDENT> self.adc_min[k] = self.adc[k] <NEW_LINE> self.adc_max[k] = self.adc[k] | Set adc values to initial values | 625941e560cbc95b062c6976 |
def draw_line( artist, x1, y1, x2, y2 ): <NEW_LINE> <INDENT> artist.penup() <NEW_LINE> artist.setposition( x1, y1 ) <NEW_LINE> artist.pendown() <NEW_LINE> artist.setposition( x2, y2 ) | Draws a line between the two given points.
:param turtle.Turtle artist: The turtle to do the drawing.
:param int x1: The x-coordinate of the first endpoint of the line.
:param int y1: The y-coordinate of the first endpoint of the line.
:param int x2: The x-coordinate of the second endpoint of the line.
:param int y2: ... | 625941e5e5267d203edce0c9 |
@BBuiltin('>n', 'Readline') <NEW_LINE> @signature() <NEW_LINE> def builtin_readline(): <NEW_LINE> <INDENT> return BStr(sys.stdin.readline()) | Read up to a newline from standard input. | 625941e50383005118ecfa13 |
def _rencontre(individu): <NEW_LINE> <INDENT> x1 = deepcopy(individu.position[0]) <NEW_LINE> y1 = deepcopy(individu.position[1]) <NEW_LINE> x2 = deepcopy(individu.ennemi.position[0]) <NEW_LINE> y2 = deepcopy(individu.ennemi.position[1]) <NEW_LINE> if x1 < x2 and self._toint(self.matrice[x1 + 1, y1]) < 100 and self._toi... | Gère le déplacement d'un individu vers un autre. | 625941e530c21e258bdfa8d3 |
def plunging(self,solver,curr_node): <NEW_LINE> <INDENT> self.plunge_count_max = max(self.plunge_count_max,int(self.plunge_rate * curr_node.level),1) <NEW_LINE> if self.plunge_count < self.plunge_count_max: <NEW_LINE> <INDENT> if len(curr_node.childs) > 0: <NEW_LINE> <INDENT> childs = curr_node.childs <NEW_LINE> if len... | plunging可以看成是简化版的dfs | 625941e53317a56b8693a080 |
def ui_action_help_about(self) -> None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> program_name = app_util.get_property('ProgramName') <NEW_LINE> version = app_util.get_property('ProgramVersion') <NEW_LINE> version_date = app_util.get_property('ProgramVersionDate') <NEW_LINE> qt_util.info_message_box( program_name + ... | Display the Help / About dialog.
Returns:
None | 625941e51b99ca400220aee6 |
def ad_hoc_analysis(): <NEW_LINE> <INDENT> raw_genders = [row['Gender'] for row in csv.DictReader(open('Data Mining - Spring 2017.csv'))] <NEW_LINE> gender_frequencies = data_mining_utilities.histogram_nominal(raw_genders) <NEW_LINE> return gender_frequencies | Histogram of genders (used to create cleaning rules in the 'clean_gender' function) | 625941e55fdd1c0f98dc0667 |
def file_search(self, dirname, blob): <NEW_LINE> <INDENT> raise NotImplementedError | Search for file blob in dirname directory
Search for all files in dirname matching blob. Returns a list
of filenames that match the search. | 625941e5379a373c97cfaf79 |
def build_shift_dict(self, shift): <NEW_LINE> <INDENT> diction = {} <NEW_LINE> strUpper = string.ascii_uppercase <NEW_LINE> for s in strUpper: <NEW_LINE> <INDENT> diction[s] = chr((ord(s)+shift-65)%26) <NEW_LINE> <DEDENT> strLower = string.ascii_lowercase <NEW_LINE> for s in strLower: <NEW_LINE> <INDENT> diction[s] = c... | Creates a dictionary that can be used to apply a cipher to a letter.
The dictionary maps every uppercase and lowercase letter to a
character shifted down the alphabet by the input shift. The dictionary
should have 52 keys of all the uppercase letters and all the lowercase
letters only.
shift (integer): the amo... | 625941e599cbb53fe6793018 |
def getRoot(self): <NEW_LINE> <INDENT> return self.getNodeByBrowseName("Root") | Returns the first node instance with the browseName "Root".
| 625941e55f7d997b87174ece |
def serialize_numpy(self, buff, numpy): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _x = self <NEW_LINE> buff.write(_struct_4i.pack(_x.pwm_left, _x.pwm_right, _x.sonic_distance_left, _x.sonic_distance_right)) <NEW_LINE> <DEDENT> except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (... | serialize message with numpy array types into buffer
:param buff: buffer, ``StringIO``
:param numpy: numpy python module | 625941e54428ac0f6e5bac28 |
def plot_corr(df, cmap_name="RdBu", method="pearson"): <NEW_LINE> <INDENT> df = df.copy() <NEW_LINE> cmap = cm.get_cmap(name=cmap_name) <NEW_LINE> cmapX = lambda x: rgb2hex(cmap((x+1)/2)) <NEW_LINE> corrP = df.corr(method="pearson") <NEW_LINE> corrS = df.corr(method="spearman") <NEW_LINE> cols = list(corrP.columns) <N... | Function plots a graphical correlation matrix for each pair of columns in the dataframe.
Input:
df: pandas DataFrame
cmap: string name of matplotlib colormap
method: method for calculating correlation, one of: (pearson, spearman). Both
will be displayed in the tooltip, for now | 625941e585dfad0860c3b28e |
def format_lines(statements, lines): <NEW_LINE> <INDENT> pairs = [] <NEW_LINE> i = 0 <NEW_LINE> j = 0 <NEW_LINE> start = None <NEW_LINE> pairs = [] <NEW_LINE> while i < len(statements) and j < len(lines): <NEW_LINE> <INDENT> if statements[i] == lines[j]: <NEW_LINE> <INDENT> if start == None: <NEW_LINE> <INDENT> start =... | Nicely format a list of line numbers.
Format a list of line numbers for printing by coalescing groups of lines as
long as the lines represent consecutive statements. This will coalesce
even if there are gaps between statements.
For example, if `statements` is [1,2,3,4,5,10,11,12,13,14] and
`lines` is [1,2,5,10,11,13... | 625941e566656f66f7cbc5df |
def to_bytes(self, message_id: int) -> List[int]: <NEW_LINE> <INDENT> self.message_id = message_id <NEW_LINE> return [ self.category_id << 5 | (self.command_id & 0x1f), message_id, *self.parameters ] | Convert the message to bytes to be able to send it.
:param message_id: ID of the message to insert
:return: A list of bytes containing the message | 625941e5a05bb46b383ecc50 |
def get_full_name(self) -> str: <NEW_LINE> <INDENT> return self.full_name | Return full name, e.g. Angela William.
Returns:
The user's full name (see ``full_name``). | 625941e5dc8b845886cb5969 |
def define_parameters(self): <NEW_LINE> <INDENT> self.add_argument('--dir', dest='dir', type=ChrisApp.path, optional=False, help='look up directory') <NEW_LINE> self.add_argument('--sleepLength', dest='sleepLength', type=int, optional=True, default=0, help='time to sleep before performing plugin action') | Define the CLI arguments accepted by this plugin app.
Use self.add_argument to specify a new app argument. | 625941e55fcc89381b1e1af4 |
def _parse_selection( selection_ast: dict, validators: "Validators", path: "Path" ) -> Union["FieldNode", "FragmentSpreadNode", "InlineFragmentNode"]: <NEW_LINE> <INDENT> return _SELECTION_PARSER_MAPPING[selection_ast["kind"]]( selection_ast, validators, path ) | Creates and returns a SelectionNode instance from a selection's JSON AST
libgraphqlparser representation.
:param selection_ast: selection's JSON AST libgraphqlparser representation
:type selection_ast: dict
:param validators: the Validators object that will be used to validate these arguments
:param path: a Path object... | 625941e5cc0a2c11143dd2c5 |
def get_tree_count(map, velocity): <NEW_LINE> <INDENT> map_height = len(map) <NEW_LINE> map_width = len(map[0]) <NEW_LINE> tree_count = 0 <NEW_LINE> col, row = velocity <NEW_LINE> while row < map_height: <NEW_LINE> <INDENT> cell = map[row][col] <NEW_LINE> if cell == "#": <NEW_LINE> <INDENT> tree_count += 1 <NEW_LINE> <... | 625941e5ec188e330fd5abc9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.