code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def __init__(self, G : np.ndarray, omega : np.ndarray): <NEW_LINE> <INDENT> assert(np.min(G) >= 0) <NEW_LINE> assert(np.min(omega) >= 0 and np.max(omega) <= 1) <NEW_LINE> self.G = G <NEW_LINE> self.omega = omega <NEW_LINE> self.__LoadNumsFromMatrix(G) | Constructor | 625941d3656771135c3eba3e |
def all(self): <NEW_LINE> <INDENT> pass | Get all lists
Returns
- A list of cheddar list objects | 625941d36fb2d068a760f26d |
def __init__(self, error=None): <NEW_LINE> <INDENT> self.swagger_types = { 'error': 'str' } <NEW_LINE> self.attribute_map = { 'error': 'error' } <NEW_LINE> self._error = error | GetUniverseSchematicsSchematicIdNotFound - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition. | 625941d34f88993c3716c235 |
def reverse_with_qstring(url_namespace, already_reversed=False, **kwargs): <NEW_LINE> <INDENT> if not already_reversed: <NEW_LINE> <INDENT> url = f"{reverse(url_namespace)}" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> url = str(url_namespace) <NEW_LINE> <DEDENT> if kwargs: <NEW_LINE> <INDENT> i = 0 <NEW_LINE> for key... | Provides user with ability to create URL with appended querystring using cleaner syntax.
:param url_namespace: Either a Django URL namespace, or a reverse() instance.
:param already_reversed: Must be True if url_namespace is a reverse() instance.
:param kwargs: Each individual querystring for the URL.
E.g., Add... | 625941d37d43ff24873a2e6e |
def matrix_mul(a, b): <NEW_LINE> <INDENT> assert len(a[0]) == len(b) <NEW_LINE> ans = [[0] * len(a) for i in range(len(b[0]))] <NEW_LINE> for i in range(len(a)): <NEW_LINE> <INDENT> for j in range(len(b[0])): <NEW_LINE> <INDENT> for k in range(len(b)): <NEW_LINE> <INDENT> ans[i][j] += a[i][k] * b[k][j] <NEW_LINE> <DEDE... | 自己实现矩阵乘法 | 625941d307f4c71912b11651 |
def test_forward_pooling(): <NEW_LINE> <INDENT> for pool_type in ['AVG', 'MAX']: <NEW_LINE> <INDENT> _test_pooling(input_shape=[1, 3, 32, 32, 32], window_shape=[2, 2, 2], padding='VALID', pooling_type=pool_type, dilation_rate=[1, 1, 1], strides=[2, 2, 2]) <NEW_LINE> _test_pooling(input_shape=[1, 3, 32, 32, 32], window_... | Pooling | 625941d363d6d428bbe446be |
def copy_to_selected_button(all: bool = True): <NEW_LINE> <INDENT> pass | Copy property from this object to selected objects or bones
:param all: All, Copy to selected all elements of the array
:type all: bool | 625941d3aad79263cf390c11 |
def translate_it(file_for_tr, result_tr, from_lang, to_lang='ru'): <NEW_LINE> <INDENT> text = '' <NEW_LINE> with open(file_for_tr) as translate: <NEW_LINE> <INDENT> text = translate.read() <NEW_LINE> <DEDENT> params = { 'key': API_KEY, 'text': text, 'lang': '{}-{}'.format(from_lang, to_lang), } <NEW_LINE> response = re... | https://translate.yandex.net/api/v1.5/tr.json/translate ?
key=<API-ключ>
& text=<переводимый текст>
& lang=<направление перевода>
& [format=<формат текста>]
& [options=<опции перевода>]
& [callback=<имя callback-функции>]
:param to_lang:
:return: | 625941d3167d2b6e31218d63 |
def hogg_ser5(x): <NEW_LINE> <INDENT> return hogg_ser(x, 5.) | One-dimensional S'ersic profile at n=5.
Normalized to return 1. at x=1. | 625941d350812a4eaa59c4ef |
def test_print(): <NEW_LINE> <INDENT> tf.reset_default_graph() <NEW_LINE> nodes = util.make_caterpillar_graph(length=2) <NEW_LINE> linearize_lib.print_graph(linearize_lib.get_graph()) | Should print:
leaf1 -> merge1
leaf0 -> merge0
merge1 -> merge2
merge0 -> merge1
leaf2 -> merge2
leaf0/shape -> leaf0
leaf1/shape -> leaf1
leaf2/shape -> leaf2 | 625941d3596a897236089c8d |
def families(self): <NEW_LINE> <INDENT> return self.records('agents/families') | Streams all family agents from the ArchivesSpace instance. | 625941d30a50d4780f667062 |
def generate_per_app(self, project_id, app_info, output_dir=None): <NEW_LINE> <INDENT> release_app = app_info[0] <NEW_LINE> target_dataset = release_app["app_name"] <NEW_LINE> repo = next( (r for r in GleanPing.get_repos() if r["name"] == release_app["v1_name"]) ) <NEW_LINE> if ( repo["app_id"] == release_app["app_name... | Generate per-app ping views.
For the release channel of a glean app *only*, generate a
pointer view to the app-id specific view for that channel/app
combination | 625941d3851cf427c661a6dc |
def test_012(self): <NEW_LINE> <INDENT> form = BillForm(data={'money': '10.9', 'comment': '', }) <NEW_LINE> self.assertFalse(form.is_valid()) <NEW_LINE> self.assertEqual(form.errors['comment'], ['请输入内容!', ]) <NEW_LINE> form = BillForm( data={ 'money': '10.9', 'comment': '123456789012345678901234567890123', } ) <NEW_LIN... | 字段测试:comment
| 625941d3a8ecb033257d329a |
def get( self, resource_group_name, factory_name, dataset_name, custom_headers=None, raw=False, **operation_config): <NEW_LINE> <INDENT> url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataFactory/factories/{factoryName}/datasets/{datasetName}' <NEW_LINE> path_format_argume... | Gets a dataset.
:param resource_group_name: The resource group name.
:type resource_group_name: str
:param factory_name: The factory name.
:type factory_name: str
:param dataset_name: The dataset name.
:type dataset_name: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: return... | 625941d397e22403b379d169 |
def stop(self): <NEW_LINE> <INDENT> if self._player: <NEW_LINE> <INDENT> self._player.stop() <NEW_LINE> self._player = None | Stops playing audio. | 625941d37047854f462a15d6 |
def test_hmmer3tab_30_hmmscan_003(self): <NEW_LINE> <INDENT> filename = os.path.join('Hmmer', 'tab_30_hmmscan_003.out') <NEW_LINE> self.check_index(filename, self.fmt) | Test hmmer3-tab indexing, HMMER 3.0, single query, multiple hits | 625941d376e4537e8c351841 |
def __init__(self, A, P=None, solver_parameters=None, nullspace=None, options_prefix=None): <NEW_LINE> <INDENT> self.A = A <NEW_LINE> self.P = P if P is not None else A <NEW_LINE> parameters = solver_parameters.copy() if solver_parameters is not None else {} <NEW_LINE> parameters.setdefault("ksp_rtol", "1e-7") <NEW_LIN... | A linear solver for assembled systems (Ax = b).
:arg A: a :class:`~.Matrix` (the operator).
:arg P: an optional :class:`~.Matrix` to construct any
preconditioner from; if none is supplied :data:`A` is
used to construct the preconditioner.
:kwarg parameters: (optional) dict of solver parameters.
:kwarg nullsp... | 625941d3cdde0d52a9e53202 |
def isInitted(self): <NEW_LINE> <INDENT> return _AriaPy.ArVCC4_isInitted(self) | isInitted(self) -> bool | 625941d371ff763f4b54985c |
def get_version(version=None): <NEW_LINE> <INDENT> version = get_full_version(version) <NEW_LINE> parts = 3 <NEW_LINE> res = '.'.join(str(x) for x in version[:parts]) <NEW_LINE> if len(version) > 3: <NEW_LINE> <INDENT> res = "%s%s" % (res, version[3]) <NEW_LINE> <DEDENT> return str(res) | Returns a PEP 386-compliant version number.
See https://www.python.org/dev/peps/pep-0440/ | 625941d34e696a04525c961a |
def __init__(self, scheduler, symbol_table, scm, workspace=None, changes_since=None, diffspec=None): <NEW_LINE> <INDENT> self._scm = scm or get_scm() <NEW_LINE> self._scheduler = scheduler <NEW_LINE> self._symbol_table = symbol_table <NEW_LINE> self._mapper = EngineSourceMapper(self._scheduler) <NEW_LINE> self._workspa... | :param scheduler: The `Scheduler` instance to use for computing file to target mappings.
:param symbol_table: The symbol table.
:param scm: The `Scm` instance to use for change determination. | 625941d30c0af96317bb83b7 |
def find(upstream, downstream, working_dir): <NEW_LINE> <INDENT> revlist_output = git(['-C', working_dir, 'rev-list', '--no-merges', '%s..%s' % (upstream, downstream)]) <NEW_LINE> downstream_only_commits = set(revlist_output.splitlines()) <NEW_LINE> return downstream_only_commits | Finds downstream commits that are not upstream and are visible in the diff.
Args:
upstream: Upstream branch to be used as a baseline.
downstream: Downstream branch to search for commits missing upstream.
working_dir: Run as if git was started in thid directory.
Returns:
A set of downstream commits missing ups... | 625941d301c39578d7e7500a |
def eval_AP(ranked_labels): <NEW_LINE> <INDENT> n = len(ranked_labels) <NEW_LINE> pos = sum(ranked_labels) <NEW_LINE> neg = n - pos <NEW_LINE> tp = pos <NEW_LINE> tn = 0 <NEW_LINE> fn = 0 <NEW_LINE> fp = neg <NEW_LINE> sumprec = 0 <NEW_LINE> for x in ranked_labels: <NEW_LINE> <INDENT> precision = tp / (tp + fp) <NEW_LI... | Recovers AP from ranked labels | 625941d35510c4643540f5b0 |
def rotate2(self, matrix): <NEW_LINE> <INDENT> n = len(matrix) <NEW_LINE> for i in range(n): <NEW_LINE> <INDENT> for j in range(i, n): <NEW_LINE> <INDENT> tmp = matrix[i][j] <NEW_LINE> matrix[i][j] = matrix[j][i] <NEW_LINE> matrix[j][i] = tmp <NEW_LINE> <DEDENT> <DEDENT> for i in range(n): <NEW_LINE> <INDENT> matrix[i]... | :type matrix: List[List[int]]
:rtype: None Do not return anything, modify matrix in-place instead. | 625941d3b7558d58953c50e1 |
def input_process_request(self, data_sio, payload_len): <NEW_LINE> <INDENT> self.peer_req_count += 1 <NEW_LINE> block_data = (piece_index, block_start, block_length) = struct.unpack('>LLL', data_sio.read(payload_len)) <NEW_LINE> self.log2(12, 'Connection {0} got request for block p{1}, s{2}, l{3}'.format(self, piece_in... | Process REQUEST message | 625941d3be8e80087fb20e10 |
def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): <NEW_LINE> <INDENT> self._draw_text_as_path(gc, x, y, s, prop, angle, ismath) | Draw the text instance.
Parameters
----------
gc : `.GraphicsContextBase`
The graphics context.
x : float
The x location of the text in display coords.
y : float
The y location of the text baseline in display coords.
s : str
The text string.
prop : `matplotlib.font_manager.FontProperties`
The font ... | 625941d3e5267d203edcde6a |
def prepare( *, schema: types.Schema, schemas: types.Schemas, skip_name: typing.Optional[str] = None, ) -> types.Schema: <NEW_LINE> <INDENT> _, schema = ref_helper.resolve( name="", schema=schema, schemas=schemas, skip_name=skip_name ) <NEW_LINE> return all_of_helper.merge(schema=schema, schemas=schemas, skip_name=skip... | Resolve $ref and merge allOf.
Args:
schema: The schema to prepare.
schemas: The schemas from which to resolve any $ref.
skip_name (optional): Any schema name to skip.
Returns:
The prepared schema. | 625941d3283ffb24f3c55ace |
def run(self): <NEW_LINE> <INDENT> self._run_init() <NEW_LINE> _tmp_cmdline = self.__build_windows_cmdline() if self.__is_windows else shlex.split(self.__nmap_command_line) <NEW_LINE> try: <NEW_LINE> <INDENT> self.__nmap_proc = subprocess.Popen(args=_tmp_cmdline, stdin=subprocess.PIPE, stdout=subprocess.PIPE... | Public method which is usually called right after the constructor
of NmapProcess. This method starts the nmap executable's subprocess.
It will also bind a Process that will read from subprocess' stdout
and stderr and push the lines read in a python queue for futher
processing. This processing is waken-up each time data... | 625941d3d53ae8145f87a43d |
def getCountRate(self, rmf, arf, minenergy_keV, maxenergy_keV, NH_1022, T_keV, Z_solar, ne_cm3): <NEW_LINE> <INDENT> key = ( minenergy_keV, maxenergy_keV, self.cosmo.z, NH_1022, rmf, arf, XSpecHelper.abun, XSpecHelper.absorb, XSpecHelper.apecroot ) <NEW_LINE> if key not in self.ctcache: <NEW_LINE> <INDENT> self.addCoun... | get count rate in counts per cm3 for parcel of gas between energies
given. | 625941d382261d6c526ab66f |
def t_BEGIN_STRING(t): <NEW_LINE> <INDENT> t.lexer.string_start_position = t.lexpos <NEW_LINE> t.lexer.string_start_quote = t.value <NEW_LINE> t.lexer.string_num_newlines = 0 <NEW_LINE> t.lexer.begin('string') | ('''|"""|'|") | 625941d32c8b7c6e89b3598f |
def convert_tick(tick: int, old_res: int, target: tp.Union[UnitType, int, None], quantize=False): <NEW_LINE> <INDENT> if target is None: <NEW_LINE> <INDENT> return tick <NEW_LINE> <DEDENT> if isinstance(target, int): <NEW_LINE> <INDENT> return rescale_tick(tick, old_res, target) <NEW_LINE> <DEDENT> return Unit.get(targ... | Utility function to either rescale a tick to another PPQN resolution or to convert it to a musical unit
This function function has two behaviours:
* rescale given tick to another PPQN -> When given an integer as "target" parameter, which is then
used as new... | 625941d37d43ff24873a2e6f |
def timestamp(time=None): <NEW_LINE> <INDENT> import datetime <NEW_LINE> if not time: <NEW_LINE> <INDENT> time = datetime.datetime.utcnow() <NEW_LINE> <DEDENT> timestamp = time.strftime('%Y%m%d_%H%M%S') <NEW_LINE> return timestamp | :param time: a time object; if None provided, use now.
:return: A str timestamp in UTC, format: YYYYMMDD_HHmmSS | 625941d36e29344779a627e0 |
def getSimOptionSetting(self, settingtype): <NEW_LINE> <INDENT> value = ctypes.c_int() <NEW_LINE> errcode = self.SWMMlibobj.swmm_getSimulationAnalysisSetting( settingtype, ctypes.byref(value)) <NEW_LINE> self._error_check(errcode) <NEW_LINE> return bool(value.value) | Get Simulation Option Settings.
:param int settingtype: Analysis Option Setting
:return: Simulation Analysis option setting
:rtype: bool
Examples:
>>> swmm_model = PySWMM(r'\.inp',r'\.rpt',r'\.out')
>>> swmm_model.swmm_open()
>>> swmm_model.getSimAnalysisSetting(SimAnalysisSettings.AllowPonding)
>>> False
>>> swmm_m... | 625941d3a05bb46b383ec9f0 |
def call(self): <NEW_LINE> <INDENT> print("\nAvailable algorithms:") <NEW_LINE> algos = hashlib.algorithms_available <NEW_LINE> i = 0 <NEW_LINE> source = self.args.source[0] <NEW_LINE> chunksize = 128 <NEW_LINE> for algo in algos: <NEW_LINE> <INDENT> print(str(i) + ". " + algo) <NEW_LINE> i = i + 1 <NEW_LINE> <DEDENT> ... | Hashes a string or a file with a chosen algorithm. | 625941d38c3a87329515858a |
def bulk_create_from_usernames(self, usernames): <NEW_LINE> <INDENT> if settings.CRADMIN_LEGACY_USE_EMAIL_AUTH_BACKEND: <NEW_LINE> <INDENT> raise IllegalOperationError('You can not use bulk_create_from_usernames() when ' 'CRADMIN_LEGACY_USE_EMAIL_AUTH_BACKEND is True.') <NEW_LINE> <DEDENT> existing_usernames = set(User... | Bulk create users for all the usernames
in the given ``usernames`` iterator.
All users is created with unusable password.
We create a :class:`.UserName` object for each of the created
users. This UserName object has ``is_primary`` set to ``True``.
Raises:
devilry_account.exceptions.IllegalOperationError: If the
... | 625941d338b623060ff0afbc |
def get_posts(df): <NEW_LINE> <INDENT> posts = set() <NEW_LINE> for i, d in df.iterrows(): <NEW_LINE> <INDENT> post = Post(*d) <NEW_LINE> posts.add(post) <NEW_LINE> <DEDENT> return list(posts) | returns a list of Posts. Posts with the same text we be considered as duplicates
:param df: a dataframe - the source of the data
:return: all the posts in this dataset | 625941d33539df3088e2e51a |
def __init__(self, backing_file_name=None): <NEW_LINE> <INDENT> cluster_bits, self.image_size = self._size_params() <NEW_LINE> self.cluster_size = 1 << cluster_bits <NEW_LINE> self.header = FieldsList() <NEW_LINE> self.backing_file_name = FieldsList() <NEW_LINE> self.backing_file_format = FieldsList() <NEW_LINE> self.f... | Create a random valid qcow2 image with the correct header and stored
backing file name. | 625941d3bde94217f3682fbe |
def toc_parser(parser): <NEW_LINE> <INDENT> worktree_parser(parser) <NEW_LINE> parser.add_argument("-c", "--config", help="The configuration to use. " "It should match the name of a toolchain. " "The settings from <worktree>/.qi/<config>.cmake will " "also be used") <NEW_LINE> parser.add_argument("-p", "--profile", des... | Parser settings for every action using a toc dir
| 625941d3507cdc57c6306eac |
def del_partitions (self, specs, user_name=None): <NEW_LINE> <INDENT> self.logger.info("%s called del_partitions(%r)", user_name, specs) <NEW_LINE> self._partitions_lock.acquire() <NEW_LINE> try: <NEW_LINE> <INDENT> partitions = [ partition for partition in self._partitions.q_get(specs) if partition.name in self._manag... | Remove partitions from the list of managed partitions | 625941d33eb6a72ae02ec6af |
def test_download_py(self): <NEW_LINE> <INDENT> r = self.app.get('/downloads/client-suds.py') <NEW_LINE> assert 'text/plain' in r.headers['Content-Type'] <NEW_LINE> assert '#!/usr/bin/env python' in r.data | Download a Python example client for the web service. | 625941d330dc7b7665901b34 |
def plot_all_class_roc(label, predict, line_width, save_path): <NEW_LINE> <INDENT> fpr = dict() <NEW_LINE> tpr = dict() <NEW_LINE> roc_auc = dict() <NEW_LINE> for i in range(num_classes): <NEW_LINE> <INDENT> fpr[i], tpr[i], _ = roc_curve(label[:, i], predict[:, i]) <NEW_LINE> roc_auc[i] = auc(fpr[i], tpr[i]) <NEW_LINE>... | 根据预测结果绘制指定类的roc曲线图
:param label: 真实标注值
:param predict: 预测值
:param save_path:保存路径
:return: | 625941d323e79379d52ee731 |
def create_widgets(self,parent,layout): <NEW_LINE> <INDENT> self.control = QtGui.QDoubleSpinBox(parent) <NEW_LINE> self.control.setMinimum(self.min_value) <NEW_LINE> self.control.setMaximum(self.max_value) <NEW_LINE> self.control.setSingleStep(self.step) <NEW_LINE> self.control.setValue(self.value) <NEW_LINE> layout.ad... | Create a label and a spinbox in layout | 625941d3fff4ab517eb2f60b |
def aoeflush(self, aflag=True): <NEW_LINE> <INDENT> return self.run_and_check('ethdrvadm flush %s' % ('', '-a')[aflag]) | Call the driver's flush command. Return a ReturnCode object. | 625941d355399d3f05588883 |
def test_get_sharpness(self) -> int: <NEW_LINE> <INDENT> raise NotImplementedError | Sum of the image pixels after applying horizontal/vertical Sobel masks | 625941d315fb5d323cde0ce0 |
def __init__(self): <NEW_LINE> <INDENT> self.width = 924 <NEW_LINE> self.height = 512 <NEW_LINE> self.screen = pygame.display.set_mode((self.width, self.height)) <NEW_LINE> self.score = 0 <NEW_LINE> self.cannonPosition = [344, 393] <NEW_LINE> self.keysState = [False, False] <NEW_LINE> self.peanuts = [[40, 0]] <NEW_LINE... | Board class constructor. | 625941d36aa9bd52df036f73 |
def days_to_holiday(curr_dt, list_of_holidays=public_holiday_dts): <NEW_LINE> <INDENT> n_days_left = ( min(hol for hol in list_of_holidays if hol >= curr_dt) - curr_dt.date() ).days <NEW_LINE> return n_days_left | Calculate number of days left until next holiday.
Parameters:
-----------
curr_dt : datetime
Date for which days until next holiday is to be calculated
list_of_holidays: list
List of holiday dates
Returns:
--------
n_days_left : int
Number of days left until next holiday | 625941d38a43f66fc4b54233 |
def next_bucket_key(self, bucket, prefix): <NEW_LINE> <INDENT> objects = self.client.list_objects_v2(Bucket=bucket, Prefix=prefix) <NEW_LINE> most_recent = None <NEW_LINE> if "Contents" in objects: <NEW_LINE> <INDENT> most_recent = sorted(objects['Contents'], key=get_last_modified).pop()['Key'] <NEW_LINE> <DEDENT> retu... | Return the key of the most recently downloaded object, given a bucket and prefix | 625941d37b25080760e39628 |
def disconnectNCTRS3cmd(self, argv): <NEW_LINE> <INDENT> self.logMethod("disconnectNCTRS3cmd", "NCTRS") <NEW_LINE> CS.NCTRSclient.disconnectNCTRS3() | Decoded disconnectNCTRS3cmd command | 625941d391af0d3eaac9bbe9 |
def test_resolve_arg_action(self): <NEW_LINE> <INDENT> actions = MockActions(user=self.user) <NEW_LINE> actions.available_actions = [{ 'action': 'test:1234', 'name': "Test action" }] <NEW_LINE> resolution = actions.resolve_action(MockRequest( user=self.user, POST={'action': 'test:1234'}, )) <NEW_LINE> self.assertEqual(... | resolve_action returns valid action and argument | 625941d330bbd722463cbf96 |
def link_data_from_pretty(self, is_controller, data): <NEW_LINE> <INDENT> data_1, data_2, data_3 = super().link_data_from_pretty(is_controller, data) <NEW_LINE> if "group" in data: <NEW_LINE> <INDENT> if is_controller: <NEW_LINE> <INDENT> data_3 = data["group"] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> data_3 = dat... | Converts Link Data1-3 from Human Readable Attributes
This takes a dict of the human readable attributes as keys and their
associated values and returns a list of the data1-3 values.
Args:
is_controller (bool): True if the device is the controller, false
if it's the responder.
data (dict[3]): Dict ... | 625941d338b623060ff0afbd |
def test_user_exists(self): <NEW_LINE> <INDENT> payload = { 'email': 'test@test.com', 'password': 'test123', 'name': 'Test Name', } <NEW_LINE> create_user(**payload) <NEW_LINE> res = self.client.post(CREATE_USER_URL, payload) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) | Test creating user that already exists fails | 625941d33cc13d1c6d3c7549 |
def _set_network(self): <NEW_LINE> <INDENT> torch.manual_seed(self.seed) <NEW_LINE> self.network = tab_network.TabNet( self.input_dim, self.output_dim, n_d=self.n_d, n_a=self.n_a, n_steps=self.n_steps, gamma=self.gamma, cat_idxs=self.cat_idxs, cat_dims=self.cat_dims, cat_emb_dim=self.cat_emb_dim, n_independent=self.n_i... | Setup the network and explain matrix. | 625941d3e8904600ed9f20fe |
def chmod(self, path, permissions, recursive=False): <NEW_LINE> <INDENT> return list(self.get_bite().chmod(list_path(path), permissions, recursive)) | Use snakebite.chmod, if available.
:param path: update-able file(s)
:type path: either a string or sequence of strings
:param permissions: \*nix style permission number
:type permissions: octal
:param recursive: change just listed entry(ies) or all in directories
:type recursive: boolean, default is False
:return: lis... | 625941d36fece00bbac2d910 |
def __init__(self, x, fun, jac, hess, hessp=None, k_easy=0.1, k_hard=0.2): <NEW_LINE> <INDENT> self.x = x <NEW_LINE> self.fun = fun <NEW_LINE> self.jac = jac <NEW_LINE> self.hess = hess <NEW_LINE> self.hessp = hessp <NEW_LINE> self.k_easy = k_easy <NEW_LINE> self.k_hard = k_hard | ``k_easy`` and ``k_hard`` are parameters used
to determine the stop criteria to the iterative
subproblem solver. Take a look at the IterativeSubproblem class
for more info. | 625941d30a366e3fb873e9ea |
def cast(*args): <NEW_LINE> <INDENT> return _itkMaximumImageFilterPython.itkMaximumImageFilterIF2IF2IF2_Superclass_cast(*args) | cast(itkLightObject obj) -> itkMaximumImageFilterIF2IF2IF2_Superclass | 625941d32ae34c7f2600d300 |
def HM12(b, d, tokens): <NEW_LINE> <INDENT> return "HM12: " + " ".join([tokens[b-1], tokens[d-1]]) | HM1 eta HM2-ren konbinaketa. Combination of HM1 and HM2.
:param b: Lehenengo argumentuaren azkeneko posizioa.
:param d: Bigarren argumentuaren azkeneko posizioa.
:param tokens: Esaldiaren token seguida.
:return: HM1 eta HM2-ren konbinaketa. | 625941d30fa83653e465718a |
def saveState(self): <NEW_LINE> <INDENT> config.set(self._CONFIG_NAME, self._CONFIG_SECTION_LOCATIONS, "enabled", location.get(enabled=True)) <NEW_LINE> config.set(self._CONFIG_NAME, self._CONFIG_SECTION_LOCATIONS, "disabled", location.get(enabled=False)) | Saves paths to configuration. | 625941d3004d5f362079a502 |
def _batch_ready(preference): <NEW_LINE> <INDENT> session = models.Session() <NEW_LINE> try: <NEW_LINE> <INDENT> count = models.QueuedMessage.count_for(session, preference.user, preference.context) <NEW_LINE> if not count: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if preference.batch_count is not None and pr... | Determine if a message batch is ready for a user.
Args:
preference (models.Preference): The user preference entry which
contains the user's batch preferences.
Returns:
bool: True if there's a batch ready. | 625941d33c8af77a43ae3970 |
def move_to(self, direction: str) -> None: <NEW_LINE> <INDENT> if direction == "up": <NEW_LINE> <INDENT> self._y = (self._y - 1) % DRAW_HEIGHT <NEW_LINE> <DEDENT> elif direction == "right": <NEW_LINE> <INDENT> self._x = (self._x + 1) % DRAW_WIDTH <NEW_LINE> <DEDENT> elif direction == "down": <NEW_LINE> <INDENT> self._y... | Move to the next pixel in the specified direction.
:param direction: the direction to move | 625941d3627d3e7fe0d69020 |
def test_API(self): <NEW_LINE> <INDENT> user = util.create_vimma_user('a', 'a@example.com', 'p') <NEW_LINE> self.assertTrue(self.client.login(username='a', password='p')) <NEW_LINE> response = self.client.get(reverse('user-list')) <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_200_OK) <NEW_LINE> items = ... | Everyone can read all users. Only some fields are exposed.
The API doesn't allow writing. | 625941d363b5f9789fde72b5 |
def iterfragments(self, **kwargs): <NEW_LINE> <INDENT> self.build() <NEW_LINE> for chunk in json.JSONEncoder(**kwargs).iterencode(self.root_dict): <NEW_LINE> <INDENT> yield chunk | Iterate over chunks of serialised BioC JSON.
This method still creates an entire copy of the
structure in memory. | 625941d3d4950a0f3b08c51e |
def dis_der(self): <NEW_LINE> <INDENT> dis_der = np.zeros((2, self.bound[0], self.bound[1]), dtype=np.float64) <NEW_LINE> for d in range(2): <NEW_LINE> <INDENT> dis_der[d, ...] = ndimage.sobel(self.dis, axis=d, mode='constant', cval=0) / self.voxel_size[d] <NEW_LINE> <DEDENT> return dis_der | Applying sobel filter to nearest distance field to get and x and y gradient field
Returns:
dis_der: a float numpy array with shape [2,bound[0],bound[1]], dis_der[0] x gradient and dis_der[1] y gradient | 625941d3187af65679ca52ee |
def add_info_widget(self, widget): <NEW_LINE> <INDENT> if not self.screen: <NEW_LINE> <INDENT> self.log.debug("No screen instance to add widget") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.screen.add_info_widget(widget) | add right panel widget | 625941d33d592f4c4ed1d23b |
def read_all_sensors(self): <NEW_LINE> <INDENT> values = [] <NEW_LINE> for i in range(8): <NEW_LINE> <INDENT> values.append(self.read_sensor(i)) <NEW_LINE> <DEDENT> return values | reads all the sensors raw values, indices 0-7
returns list of 8 integers in range [0,4095] | 625941d366656f66f7cbc37c |
def set(self, input_string): <NEW_LINE> <INDENT> if not isinstance(input_string, str): <NEW_LINE> <INDENT> raise ParameterTypeError("StringFeature.set: " "Expected input_string type is str, not %s" % type(input_string)) <NEW_LINE> <DEDENT> writeable = self.is_writable() <NEW_LINE> if not writeable: <NEW_LINE> <INDENT> ... | :brief Setting string value
:param input_string[string]
:return: None | 625941d34428ac0f6e5ba9c2 |
def reset(self): <NEW_LINE> <INDENT> self.is_cancelled = False <NEW_LINE> self.result = None | Must be called every time the background task is finished.
Must be called from async thread. Caller must hold lock on async executor when calling. | 625941d3507cdc57c6306ead |
def StartRunning(self): <NEW_LINE> <INDENT> self.running = True <NEW_LINE> self.startTime = None <NEW_LINE> if self.table is not None: <NEW_LINE> <INDENT> self.table[kRunning] = True | This is used internally to mark that the command has been started.
The lifecycle of a command is:
startRunning() is called.
run() is called (multiple times potentially)
removed() is called
It is very important that startRunning and removed be called in order
or some assumptions of the code will be broken. | 625941d332920d7e50b283a1 |
def test_mutual_information_discrete_discrete(self): <NEW_LINE> <INDENT> joint = np.array([ [0, 4, 1, 0], [1, 0, 0, 8], [0, 11, 1, 0], [21, 1, 2, 1], ]) <NEW_LINE> acc = 0 <NEW_LINE> x = [] <NEW_LINE> y = [] <NEW_LINE> for i in range(joint.shape[0]): <NEW_LINE> <INDENT> for j in range(joint.shape[1]): <NEW_LINE> <INDEN... | Test the mutual information between pairs of discrete variables. | 625941d324f1403a92600d35 |
@node.commandWrap <NEW_LINE> def manipPivot(*args, **kwargs): <NEW_LINE> <INDENT> u <NEW_LINE> return cmds.manipPivot(*args, **kwargs) | :rtype: list|str|basestring|DagNode|AttrObject|ArrayAttrObject|Components1Base | 625941d344b2445a33932264 |
def write_disk_curve(self): <NEW_LINE> <INDENT> log.info("Writing the disk absorption curve ...") <NEW_LINE> self.disk_spectral_absorption_curve.saveto(self.disk_spectral_absorption_curve_path) | This function ...
:return: | 625941d3656771135c3eba3f |
def shell_cmd_timeout(cmd, timeout=0): <NEW_LINE> <INDENT> cmd_proc = subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, shell=True, preexec_fn=os.setsid) <NEW_LINE> pid = cmd_proc.pid <NEW_LINE> pgid = os.getpgid(pid) <NEW_LINE> if not cmd_proc: <NEW_LINE> <INDENT> return -1, '' <NEW_LINE> <DEDENT... | Execute shell command till timeout | 625941d357b8e32f5248366b |
def sync_state(self, _skip_moderation=True): <NEW_LINE> <INDENT> initial_state = self.state <NEW_LINE> regform = self.registration_form <NEW_LINE> invitation = self.invitation <NEW_LINE> moderation_required = (regform.moderation_enabled and not _skip_moderation and (not invitation or not invitation.skip_moderation)) <N... | Sync the state of the registration | 625941d356ac1b37e626439e |
def intersection(nums1, nums2): <NEW_LINE> <INDENT> records = {} <NEW_LINE> for n in nums1: <NEW_LINE> <INDENT> records[n] = records.get(n, 0) + 1 <NEW_LINE> <DEDENT> res = [] <NEW_LINE> for n in nums2: <NEW_LINE> <INDENT> if records.get(n, 0): <NEW_LINE> <INDENT> res.append(n) <NEW_LINE> records[n] -= 1 <NEW_LINE> <DE... | :type nums1: List[int]
:type nums2: List[int]
:rtype: List[int] | 625941d3cad5886f8bd271a8 |
def prepare_400(message): <NEW_LINE> <INDENT> response = { 'statusCode': 400, 'body': json.dumps({ 'message': message }) } <NEW_LINE> return response | Shortcut method for preparing 400 responses. | 625941d31f5feb6acb0c4d1e |
def ClusterData(data,nPts,distThresh,isDistData=False,distFunc=EuclideanDist): <NEW_LINE> <INDENT> if isDistData and len(data)>(nPts*(nPts-1)/2): <NEW_LINE> <INDENT> logger.warning("Distance matrix is too long") <NEW_LINE> <DEDENT> nbrLists = [None]*nPts <NEW_LINE> for i in range(nPts): nbrLists[i] = [] <NEW_LINE> dmId... | clusters the data points passed in and returns the list of clusters
**Arguments**
- data: a list of items with the input data
(see discussion of _isDistData_ argument for the exception)
- nPts: the number of points to be used
- distThresh: elements within this range of each other are considered
to be... | 625941d3dd821e528d63b378 |
def test_client_dequeue_dependent_change(self): <NEW_LINE> <INDENT> client = zuul.rpcclient.RPCClient('127.0.0.1', self.gearman_server.port) <NEW_LINE> self.addCleanup(client.shutdown) <NEW_LINE> self.executor_server.hold_jobs_in_build = True <NEW_LINE> A = self.fake_gerrit.addFakeChange('org/project', 'master', 'A') <... | Test that the RPC client can dequeue a change | 625941d3236d856c2ad449ab |
def other_features(filters=None): <NEW_LINE> <INDENT> if filters is None: <NEW_LINE> <INDENT> filters = [] <NEW_LINE> <DEDENT> brackets = [ 0.0, 0.08, 0.20, 0.80, 0.92 ] <NEW_LINE> bracket_range = "{" + ",".join(str(i) for i in range(len(brackets))) + "}" <NEW_LINE> features = [ ( "bracket", bracket_range, bracket(brac... | Returns an array of (attribute name, attribute range, function) | 625941d3be8e80087fb20e11 |
def add_embedding(self, prefix=''): <NEW_LINE> <INDENT> with tf.variable_scope(prefix + 'embed'): <NEW_LINE> <INDENT> if self.cfg.fix_emb: <NEW_LINE> <INDENT> assert (hasattr(self.cfg, 'W_emb')) <NEW_LINE> W_emb = pkl.load(open(self.cfg.W_emb_path, 'rb')) <NEW_LINE> W = tf.get_variable('W', initializer= W_emb, trainabl... | Customized function to transform x into embeddings | 625941d330bbd722463cbf97 |
def change_direction(self, directions): <NEW_LINE> <INDENT> data = self.turn.to_bytes(2, byteorder=env.endian) <NEW_LINE> for i in range(5): <NEW_LINE> <INDENT> data += directions[i].to_bytes(1, byteorder=env.endian) <NEW_LINE> <DEDENT> self.socket.send(data) <NEW_LINE> print('방향 변경 %s\n\n' % ''.join(map((lambda x: '→↑... | 슬라임들의 방향을 변경합니다.
:param directions: 슬라임들의 방향을 담고 있는 배열. →↑←↓ 순서로 0123에 대응된다. ex) [0, 1, 2, 1, 1] | 625941d366673b3332b92261 |
def create_dot1p_to_cos_mapping(self, ports, **kwargs): <NEW_LINE> <INDENT> raise UIException("Method isn't implemented") | Configure mapping of ingress VLAN priority to CoS per port or per switch (PortsDot1p2CoS mapping).
Args:
ports(list[int]): list of ports to be modified
**kwargs(dict): parameters to be modified
Returns:
None
Examples::
env.switch[1].ui.create_dot1p_to_cos_mapping([1, ], dotp7CoS=6) | 625941d3046cf37aa974cf16 |
def test_cgoolf_toolchain(self): <NEW_LINE> <INDENT> tc = self.get_toolchain("cgoolf", version="1.1.6") <NEW_LINE> tc.prepare() <NEW_LINE> self.assertEqual(tc.get_variable('CC'), 'clang') <NEW_LINE> self.assertEqual(tc.get_variable('CXX'), 'clang++') <NEW_LINE> self.assertEqual(tc.get_variable('F77'), 'gfortran') <NEW_... | Test for cgoolf toolchain. | 625941d3b5575c28eb68e1d1 |
@mock.patch('api.models.get_db') <NEW_LINE> def test_phone_bill_save(get_db, phone_bill): <NEW_LINE> <INDENT> phone_bill.exists_period = mock.Mock(return_value=False) <NEW_LINE> get_db.return_value.cursor.return_value.execute.return_value.rowcount = 1 <NEW_LINE> result = phone_bill.save() <NEW_LINE> assert result <NEW_... | Test save function from PhoneBill class. | 625941d38e05c05ec3eea545 |
def __init__(self, gameFrame, playerList): <NEW_LINE> <INDENT> self.setStyles() <NEW_LINE> self.currentRound = 1 <NEW_LINE> self.playerList = playerList <NEW_LINE> self.playerTotalScoreDict = dict.fromkeys(self.playerList, 0) <NEW_LINE> self.currentPlayer = self.playerList[0] <NEW_LINE> self.currentGameFrame = None <NE... | Constructor | 625941d3dc8b845886cb5706 |
def pa_obj_parser(xml): <NEW_LINE> <INDENT> pa_services, pa_addresses, pa_service_groups, pa_address_groups = ({} for i in range(4)) <NEW_LINE> services = tree.xpath(".//service/entry[@name]/protocol/*/port") <NEW_LINE> addresses = tree.xpath(".//address/entry[@name]/ip-netmask") <NEW_LINE> service_groups = tree.xpath(... | Retrieves all (shared) objects from a Palo Alto configuration file
:param xml: ElementTree of the configuration file(s)
:return: Dicts of service, address, service-group and address-group objects | 625941d33317a56b86939e25 |
def get_response(connection, filename): <NEW_LINE> <INDENT> BUFFER_SIZE = 4096 <NEW_LINE> header = read_line(connection) <NEW_LINE> if not check_http_response(header): <NEW_LINE> <INDENT> sys.stdout.write("Encabezado HTTP malformado: '%s'\n" % header.strip()) <NEW_LINE> return False <NEW_LINE> <DEDENT> else: <NEW_LINE>... | Recibe de `connection' una respuesta HTTP, y si es valida la descarga
en un archivo llamdo `filename'.
Devuelve True en caso de éxito, False en caso contrario | 625941d396565a6dacc8f89a |
def animate_standing_position(self): <NEW_LINE> <INDENT> orientacion = None <NEW_LINE> self.timer_rotacion += 1 <NEW_LINE> if self.timer_rotacion % 120 == 0 and self.head_direction != 'front': <NEW_LINE> <INDENT> if self.body_direction == 'izquierda': <NEW_LINE> <INDENT> if self.head_direction == 'left': <NEW_LINE> <IN... | It rotates the body to align it with the head at the same direction | 625941d371ff763f4b54985d |
def set_filters(self, display_type, display_id, active_filters): <NEW_LINE> <INDENT> display = self._get_display(display_type, display_id) <NEW_LINE> display.active_filters = active_filters <NEW_LINE> self._save_display_state(display_type, display_id) | Set the active filters
active_filters should be a set of filter key strings. | 625941d3090684286d50eeb6 |
def changenick(redditron,input): <NEW_LINE> <INDENT> msg = input.split() <NEW_LINE> if len(msg) ==2: <NEW_LINE> <INDENT> redditron.logger(strftime("%H:%M:%S")) <NEW_LINE> redditron.logger("changing nick to "+msg[1]) <NEW_LINE> redditron.nickch(msg[1]) <NEW_LINE> redditron.nick = msg[1] | self-explanatory | 625941d32c8b7c6e89b35990 |
def check_obj_func_exists(self, func_name, line_num): <NEW_LINE> <INDENT> var_ref = IdleCompiler.__interp.get_last_var() <NEW_LINE> type_name = var_ref.var_type <NEW_LINE> if DataType.exists(type_name): <NEW_LINE> <INDENT> IdleCompiler.__compiler_errors.append("line %i: Function '%s' not found in '%s'." % (line_num, fu... | Checks if a function exists within the class of var_ref
Assumes undeclared variable error has already been thrown if var_ref doesn't exist. | 625941d31b99ca400220ac81 |
def creer_matrice_proba_compatible(matE_compa, matE_proba): <NEW_LINE> <INDENT> liste_cols = matE_compa.columns.tolist() <NEW_LINE> matE_proba_compa = pd.DataFrame(index = liste_cols, columns = liste_cols) <NEW_LINE> liste_tuple = creer_tuples(matE_compa) <NEW_LINE> for elt_tuple in liste_tuple: <NEW_LINE> <INDENT> arc... | matE_proba_compa est la matrice de probabilite associee a la matrice matE_compa.
en d'autres termes la proba entre 2 arcs est ajoutee a cette matrice ssi il existe une adjacence dans matE_compa
matE_proba est la matrice de probabilites associe a une grandeur
retourne matE_proba_compa | 625941d399cbb53fe6792db6 |
def lazy_instance_access(cls, key_as_str=False): <NEW_LINE> <INDENT> class LazySingletonHolder(object): <NEW_LINE> <INDENT> def __getattribute__(self, item): <NEW_LINE> <INDENT> return cls.__getattribute__(cls.Instance(), item) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return cls.__getattribute__(cls.I... | Takes a singleton class and wraps it in an LazySingletonHolder
that constructs the instance on first access.
Historically, mantid <= v3.13, the singleton aliases mapped to the
instances rather than the class types, i.e. UsageService is the instance and not the type.
To preserve compatibility with existing scripts, wh... | 625941d391f36d47f21ac6c3 |
def pin_list_check(pin_list): <NEW_LINE> <INDENT> num_eff = sum(len(s) for s in pin_list) <NEW_LINE> ratio = num_eff / TOTAL_PINS <NEW_LINE> if not (0.4 <= ratio <= 0.6): <NEW_LINE> <INDENT> logger.info("Pin list ratio check failed: %s", ratio) <NEW_LINE> return False <NEW_LINE> <DEDENT> for n, pins in enumerate(pin_li... | Returns True if the supplied pin list meets Army procedure criteria.
To pass the check, the number of effective pins must be between 40-60%.
Furthermore, there cannot be more than 6 consecutive effective or
non-effective pins on any wheel. | 625941d3a4f1c619b28b0206 |
@log_call(namespace=__xmlrpc_namespace__) <NEW_LINE> def get(request, plan_id): <NEW_LINE> <INDENT> tp = TestPlan.objects.get(plan_id=plan_id) <NEW_LINE> response = tp.serialize() <NEW_LINE> response['default_product_version'] = response['product_version'] <NEW_LINE> tag_ids = tp.tag.values_list('id', flat=True) <NEW_L... | Description: Used to load an existing test plan from the database.
Params: $id - Integer/String: An integer representing the ID of this plan in the database
Returns: Hash: A blessed TestPlan object hash
Example:
>>> TestPlan.get(137) | 625941d3adb09d7d5db6c95f |
def __generator(self): <NEW_LINE> <INDENT> generator=Sequential() <NEW_LINE> generator.add(Dense(256*16*16, input_shape=(100,), activation='relu',kernel_regularizer=regularizers.l2(0.01))) <NEW_LINE> generator.add(Reshape((16,16,256))) <NEW_LINE> generator.add(UpSampling2D()) <NEW_LINE> generator.add(Conv2D(128, kernel... | Declare generator | 625941d315fb5d323cde0ce1 |
def stop(self): <NEW_LINE> <INDENT> self.__writeOnLog__("Un watchdog ha smesso di monitorare il thread "+self.thread+" nella board: "+self.board) <NEW_LINE> self.Attivo = False | Ferma il demone | 625941d32ae34c7f2600d301 |
def wakeup(self): <NEW_LINE> <INDENT> self._general_call(_MCP4728_GENERAL_CALL_WAKEUP_COMMAND) | Reset the Power-Down bits (PD1, PD0 = 0,0) and
Resumes Normal Operation mode | 625941d350812a4eaa59c4f1 |
def get_overlay_log(self): <NEW_LINE> <INDENT> return self.sessconfig['overlay_log'] | Returns the file to log messages to or None.
@return An absolute path name. | 625941d3d58c6744b4257e2f |
def test_stop_with_complete_true_after_running(self): <NEW_LINE> <INDENT> attr_start_val = 0 <NEW_LINE> attr_finish_val = 1 <NEW_LINE> anim_duration = 5.0 <NEW_LINE> tick_duration = 1.0 <NEW_LINE> test_obj = SimpleNamespace(attr=attr_start_val) <NEW_LINE> anim = animate(test_obj, duration=anim_duration, attr=attr_finis... | Stop, with complete True, an animation after it has run a bit. | 625941d329b78933be1e587a |
def step(self): <NEW_LINE> <INDENT> self.i += 1 <NEW_LINE> newPopulation = self.bestN(self.keep) <NEW_LINE> iterations = self.populationSize - self.keep <NEW_LINE> while iterations: <NEW_LINE> <INDENT> p1, p2 = self.selectParents() <NEW_LINE> childChromosome = self.crossover(p1[0], p2[0]) <NEW_LINE> childChromosome = s... | Runs one iteration of the genetic algorithm. In a single iteration,
we create a whole new population by first keeping the best units as
defined by elitism, then we iteratively select parents from the
current population, apply crossover and then mutation.
Function returns a tuple:
* boolean value indicating shoul... | 625941d3d99f1b3c44c6775d |
def open_by_distance_segments(num, distance=0., seed=0): <NEW_LINE> <INDENT> if seed == 0: <NEW_LINE> <INDENT> seed = n.random.randint(1000000) <NEW_LINE> <DEDENT> if distance > 1. or distance < 0.: <NEW_LINE> <INDENT> raise ValueError('distance must be between 0 and 1') <NEW_LINE> <DEDENT> distance *= 2. <NEW_LINE> ge... | Get a list of line vectors whose sum fails to close by the given distance fraction.
Parameters
----------
num : int
The number of segments
distance : float
The distance fraction (0 <= distance <= 1) by which their sum doesn't close.
seed : int
The random seed. | 625941d3442bda511e8be5e6 |
def _cmd_noop(self, argstr): <NEW_LINE> <INDENT> pass | stub command implementation | 625941d397e22403b379d16b |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.