code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def test_quartile_positive(self): <NEW_LINE> <INDENT> x = quartile([1, 2, 2, 3], 0.9) <NEW_LINE> self.assertEqual(x, 3) | Positive unittest for correctness of function.
Checks if function returns correct result.
:returns: None; AssertionError -- if test fails | 625941d5462c4b4f79d1d8f5 |
@ensure_tag(['tc']) <NEW_LINE> def get_grid_span(tc): <NEW_LINE> <INDENT> w_namespace = get_namespace(tc, 'w') <NEW_LINE> grid_spans = tc.xpath('.//w:gridSpan', namespaces=tc.nsmap) <NEW_LINE> if len(grid_spans) != 1: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> grid_span = grid_spans[0] <NEW_LINE> return int(grid_... | gridSpan is what docx uses to denote that a table cell has a colspan. This
is much more simple than rowspans in that there is a one-to-one mapping
from gridSpan to colspan. | 625941d524f1403a92600d8a |
def on_user_identity_negotiation(self, user_id_type, primary_field, secondary_field): <NEW_LINE> <INDENT> raise NotImplementedError | Callback for when a peer requests user identity negotiations.
See PS3.7 Annex D.3.3.7.1
Experimental and will definitely change
Parameters
----------
user_id_type : int
The User Identity Type value (1, 2, 3, 4).
primary_field : bytes
The value of the Primary Field
secondary_field : bytes or None
The valu... | 625941d6dc8b845886cb575b |
def check_actions(self, actions): <NEW_LINE> <INDENT> map_car_values = {} <NEW_LINE> for cid in self.sim.set_present: <NEW_LINE> <INDENT> x, y = self.sim.traci.vehicle.getPosition(cid) <NEW_LINE> speed = self.sim.traci.vehicle.getSpeed(cid) <NEW_LINE> length = self.sim.traci.vehicle.getLength(cid) <NEW_LINE> map_car_va... | actions - vector of integers (0-8) chosen by policy for
all agents
Returns same vector, with invalid actions replaced | 625941d530dc7b7665901b8a |
def get_host_stats(self, refresh=False): <NEW_LINE> <INDENT> if refresh: <NEW_LINE> <INDENT> self.update_status() <NEW_LINE> <DEDENT> return self._stats | Return the current state of the host.
If 'refresh' is True, run update the stats first. | 625941d6283ffb24f3c55b25 |
def install(root_path): <NEW_LINE> <INDENT> sys.path_hooks.append(AnsibleModuleImporter) <NEW_LINE> sys.path.append(root_path) <NEW_LINE> _VALID_PATHS.append(root_path) | Installs the module importer, valid only for the specified root path.
This must be called explicitly so that the library isn't doing anything
behind the caller's back. The actual importer class will only look in the
provided `root_path`, so that it's not stomping on other python imports.
Use this before you want to i... | 625941d6d7e4931a7ee9e143 |
def test_configuration_mode_property(self): <NEW_LINE> <INDENT> self.assertEqual(self.tk.configuration_mode, self.tk.CENTRALIZED) | test api.configuration_mode property | 625941d6566aa707497f478c |
def add_task(self, cls, *args, **kwargs): <NEW_LINE> <INDENT> if 'cycle' not in kwargs: <NEW_LINE> <INDENT> kwargs['cycle'] = self <NEW_LINE> <DEDENT> task = cls(self.trial, *args, **kwargs) <NEW_LINE> self.tasks.append(task) <NEW_LINE> return task | Add a TrialTask for this cycle.
TrialTasks for cycles can only be created
by Trial objects. | 625941d6f8510a7c17cf9922 |
def get_image_manifest(repository_name, imageDigest): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> out = json.loads( run_command([ "aws", "ecr", "batch-get-image", "--repository-name", repository_name, "--image-ids", "imageDigest={}".format(imageDigest) ]).stdout) <NEW_LINE> <DEDENT> except subprocess.CalledProcessErro... | Call ecr batch-get-image to get the image manifest | 625941d60a366e3fb873ea41 |
def _getEpisodeWatchlist(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.EpisodeWatchlist = {'tvdb_id': {}, 'tvrage_id': {}} <NEW_LINE> TraktEpisodeWatchlist = self.trakt_api.traktRequest("sync/watchlist/episodes") <NEW_LINE> tvdb_id = 'tvdb' <NEW_LINE> tvrage_id = 'tvrage' <NEW_LINE> for watchlist_el in Trakt... | Get Watchlist and parse once into addressable structure | 625941d64c3428357757c54d |
def test_threshold_img_copy(): <NEW_LINE> <INDENT> img_ones = Nifti1Image(np.ones((10, 10, 10, 10)), np.eye(4)) <NEW_LINE> thresholded = threshold_img(img_ones, 2) <NEW_LINE> assert_array_equal(get_data(img_ones), np.ones((10, 10, 10, 10))) <NEW_LINE> assert_array_equal(get_data(thresholded), np.zeros((10, 10, 10, 10))... | Test the behavior of threshold_img's copy parameter. | 625941d6a17c0f6771cbe275 |
def __init__(self,MeshID=1): <NEW_LINE> <INDENT> self.Mesh=MeshID <NEW_LINE> self.Points={} <NEW_LINE> self.Edges={} <NEW_LINE> self.Points2={} <NEW_LINE> self.Edges2={} | Mesh constructor function | 625941d6a05bb46b383eca46 |
def iterate_clustering(data_mat, class_ixs, num_classes, N=100, dead_class_threshold=0): <NEW_LINE> <INDENT> updated_class_ixs = class_ixs <NEW_LINE> for iter_idx in range(N): <NEW_LINE> <INDENT> class_mean, class_cov, class_priors = compute_class_statistics(data_mat, updated_class_ixs, num_classes) <NEW_LINE> updated_... | Iterates through the Compute Class Statistics and Compute Posterior Probability & Assign to Class blocks
:param data_mat: (num_features, num_samples) data matrix (PC bands 1-N, leading order PCs)
:param class_ixs: (num_samples,) array containing class membership indices
:param num_classes: Number of classes to cluster ... | 625941d6460517430c3943a7 |
def merge(self, nums1, m, nums2, n): <NEW_LINE> <INDENT> p1 = m - 1 <NEW_LINE> p2 = n - 1 <NEW_LINE> p = m + n - 1 <NEW_LINE> while p1 >= 0 and p2 >= 0: <NEW_LINE> <INDENT> if nums1[p1] > nums2[p2]: <NEW_LINE> <INDENT> nums1[p] = nums1[p1] <NEW_LINE> p -= 1 <NEW_LINE> p1 -= 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDEN... | :type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: None Do not return anything, modify nums1 in-place instead. | 625941d6be8e80087fb20e66 |
def cancel_payments(self, transaction_uuid): <NEW_LINE> <INDENT> headers = { 'Content-Type': 'application/json', "Authorization": "Bearer {0}".format(self.token) } <NEW_LINE> response = requests.post("https://api.enzona.net/payment/v1.0.0/payments/{0}/cancel".format(transaction_uuid), headers=headers) <NEW_LINE> try: <... | Allows you to cancel a payment
:param transaction_uuid: Transaction Identifier
:return: Returns json object with cancellation data | 625941d68da39b475bd6519b |
def download_gists(self): <NEW_LINE> <INDENT> matches = re.finditer(GIST_RE, self.content) <NEW_LINE> for match in matches: <NEW_LINE> <INDENT> md_gist = gist_to_markdown(match.groups()[0]) <NEW_LINE> if md_gist: <NEW_LINE> <INDENT> self.content = self.content.replace(match.group(), md_gist) | If the post contains embedded gists, convert
them to markdown fenced code and contain them
in the contents. | 625941d6a219f33f34628b8d |
def __setattr__(self, name, value): <NEW_LINE> <INDENT> if '_properties' in self.__dict__ and name not in self.__dict__: <NEW_LINE> <INDENT> self.set_property(name, value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.__dict__[name] = value | Override default setattr behaviours to allow DBus object
properties to be exposed in the class for setting | 625941d6379a373c97cfad6b |
def convert_polimage_to_stokes(im: Image): <NEW_LINE> <INDENT> assert type(im) == Image <NEW_LINE> assert im.data.dtype == 'complex' <NEW_LINE> if im.polarisation_frame == PolarisationFrame('linear'): <NEW_LINE> <INDENT> cimarr = convert_linear_to_stokes(im.data) <NEW_LINE> return create_image_from_array(cimarr, im.wcs... | Convert a polarisation image to stokes (complex)
| 625941d6cdde0d52a9e5325a |
def _open(self) -> None: <NEW_LINE> <INDENT> self._modify_connection_params() <NEW_LINE> self.establish_connection() <NEW_LINE> self._try_session_preparation() | Decouple connection creation from __init__ for mocking. | 625941d6925a0f43d254a09e |
@verbose <NEW_LINE> def compute_proj_eog(raw, raw_event=None, tmin=-0.2, tmax=0.2, n_grad=2, n_mag=2, n_eeg=2, l_freq=1.0, h_freq=35.0, average=False, filter_length='10s', n_jobs=1, reject=dict(grad=2000e-13, mag=3000e-15, eeg=500e-6, eog=np.inf), flat=None, bads=[], avg_ref=False, no_proj=False, event_id=998, eog_l_fr... | Compute SSP/PCA projections for EOG artifacts.
.. note:: raw data must be preloaded.
Parameters
----------
raw : mne.io.Raw
Raw input file.
raw_event : mne.io.Raw or None
Raw file to use for event detection (if None, raw is used).
tmin : float
Time before event in seconds.
tmax : float
Time after even... | 625941d601c39578d7e75061 |
def test_config_EmptyArguments_ReturnList(self, config_file): <NEW_LINE> <INDENT> expected_status, expected_ret = True, self.generate_config_data() <NEW_LINE> status, ret = hubblestack.fdg.readfile.config(config_file) <NEW_LINE> assert expected_status == status <NEW_LINE> assert expected_ret == ret | Test that given empty arguemtsn, the function returns a list with lines as elements | 625941d667a9b606de4a80de |
def merge_user(self, obj, user, data): <NEW_LINE> <INDENT> need = Need('merge') <NEW_LINE> if not obj.can(user, need, obj): <NEW_LINE> <INDENT> raise need.exception() <NEW_LINE> <DEDENT> other_user = models.User.lookup(data['other_email']) <NEW_LINE> if not other_user: <NEW_LINE> <INDENT> raise BadValueError("Invalid u... | Merges this user with another user.
This user is the user that is "merged" -- no longer can login. | 625941d6c432627299f04e6d |
def testRepresentation(self): <NEW_LINE> <INDENT> repr(self.ss[-1]) | Test that the reference object's representation works
XXX Doesn't currently check the results, just that no error
is raised | 625941d663d6d428bbe44716 |
def cursorMoveStyle(self): <NEW_LINE> <INDENT> pass | cursorMoveStyle(self) -> Qt.CursorMoveStyle | 625941d616aa5153ce36269d |
def _initVersion(self, gitPath=None): <NEW_LINE> <INDENT> if not gitPath: <NEW_LINE> <INDENT> gitPath = "git" <NEW_LINE> self.log.debug("Git path not specified, using system path.") <NEW_LINE> <DEDENT> self._gitVersion = None <NEW_LINE> self._gitRevision = None <NEW_LINE> self._gitDirty = None <NEW_LINE> try: <NEW_LINE... | Initialize the version and GIT revision. | 625941d6e64d504609d74a66 |
def disconnect(self): <NEW_LINE> <INDENT> self.logout(login=None) <NEW_LINE> self._llcom.disconnect() <NEW_LINE> logging.debug("Connection to host closed") | logout of all open logins and close connection | 625941d685dfad0860c3b081 |
def transfer_files(self): <NEW_LINE> <INDENT> hosts_list = self._get_host_list() <NEW_LINE> trans_type = input("请选择传输类型【1.上传 2.下载】:\n") <NEW_LINE> localpath = input("请输入本地路径:\n").strip() <NEW_LINE> remotepath = input("请输入远程路径:\n").strip() <NEW_LINE> self.manager.transfer_files( hosts_list, trans_type, localpath, remote... | 根据用户输入,与指定主机传输文件. | 625941d682261d6c526ab6c7 |
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: <NEW_LINE> <INDENT> if not (l1 and l2): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> p1 = l1 <NEW_LINE> p2 = l2 <NEW_LINE> carry = 0 <NEW_LINE> result = ListNode(0) <NEW_LINE> cur = result <NEW_LINE> while p1 or p2: <NEW_LINE> <INDENT> s_val = carr... | 1. carry表示进位,要带到下一个节点val里边
2. 存在一个链表,返回为空
3. 最后两个链表都遍历完,需要处理向后进位 | 625941d629b78933be1e58cf |
def fit_loader(self, data_loader, epochs=1, verbose=1, callbacks=None, validation_loader=None, initial_epoch=0): <NEW_LINE> <INDENT> self._prepare() <NEW_LINE> callbacks_list = CallbackList(callbacks or [], trainer=self) <NEW_LINE> try: <NEW_LINE> <INDENT> callbacks_list.on_train_begin(initial_epoch) <NEW_LINE> for epo... | Fit PyTorch module to dataset (using PyTorch DataLoader class).
Args:
data_loader (torch.utils.data.DataLoader): Train data loader.
epochs (int): Final epoch after which training stops. (Default: 1)
verbose (int): Two levels of verbosity:
* 1 - show progress bar, (<- Default)
* 0 - show not... | 625941d607d97122c4178ab4 |
def SetValue(self, time_t): <NEW_LINE> <INDENT> self.timeCtrl.SetValue(wx.DateTimeFromTimeT(time_t)) | return time value | 625941d6236d856c2ad44a02 |
def filter(self, record): <NEW_LINE> <INDENT> record.hostname = ContextFilter.hostname <NEW_LINE> return True | Create the filter that holds the hostname. | 625941d6be8e80087fb20e67 |
def set_file(self, filename): <NEW_LINE> <INDENT> from aiida.common.exceptions import ParsingError <NEW_LINE> import aiida.common.utils <NEW_LINE> parsed_data = parse_upf(filename) <NEW_LINE> md5sum = aiida.common.utils.md5_file(filename) <NEW_LINE> try: <NEW_LINE> <INDENT> element = parsed_data['element'] <NEW_LINE> <... | I pre-parse the file to store the attributes. | 625941d6090684286d50ef0d |
def chat_userset_key(chat_channel): <NEW_LINE> <INDENT> return chat_channel + "_users" | return key for userset | 625941d6d53ae8145f87a493 |
def generate_result_file(golden_file, predict_file, eng_label_dic, type_dic, result_dir, mode='test'): <NEW_LINE> <INDENT> f_pre = open(predict_file, 'r') <NEW_LINE> f_res = open(os.path.join(result_dir, (mode + '_result.json')), 'w', encoding='utf-8') <NEW_LINE> with open(golden_file, 'r') as f: <NEW_LINE> <INDENT> pr... | 生成result文件 | 625941d6004d5f362079a559 |
def isFinished(self) : <NEW_LINE> <INDENT> return (self.fireZone == []) | void -> bool
returns true if there is no more fire | 625941d630bbd722463cbfed |
@login_required <NEW_LINE> def export_completed_crypto_orders(dir_path, file_name=None): <NEW_LINE> <INDENT> file_path = create_absolute_csv(dir_path, file_name, 'crypto') <NEW_LINE> all_orders = get_all_crypto_orders() <NEW_LINE> with open(file_path, 'w', newline='') as f: <NEW_LINE> <INDENT> csv_writer = writer(f) <N... | Write all completed crypto orders to a csv file
:param dir_path: Absolute or relative path to the directory the file will be written.
:type dir_path: str
:param file_name: An optional argument for the name of the file. If not defined, filename will be crypto_orders_{current date}
:type file_name: Optional[str] | 625941d63c8af77a43ae39c7 |
def __GetSpringDampingRatio(self): <NEW_LINE> <INDENT> return _Box2D.b2WheelJoint___GetSpringDampingRatio(self) | __GetSpringDampingRatio(self) -> float32 | 625941d616aa5153ce36269e |
@dvid_api_wrapper <NEW_LINE> def fetch_sizes_via_labelindex(server, uuid, instance, labels, supervoxels=False, *, batch_size=None, threads=None, processes=None, session=None): <NEW_LINE> <INDENT> if batch_size is None: <NEW_LINE> <INDENT> assert threads is None and processes is None, "Specify a batch size or... | Equivalent to fetch_sizes(), but uses the raw /labelindex endpoint
to obtain the sizes, rather than requesting the sizes from dvid.
In a single thread, this will be slower than simply callying fetch_sizes(),
but if you have more CPU cores than DVID does (or you want to save DVID a little bit of CPU load),
then you can... | 625941d67d43ff24873a2ec7 |
def add_initial_run_database(config_sql_server, product_connection): <NEW_LINE> <INDENT> LOG.debug("Creating database engine for CONFIG DATABASE...") <NEW_LINE> __engine = config_sql_server.create_engine() <NEW_LINE> product_session = sessionmaker(bind=__engine) <NEW_LINE> sess = product_session() <NEW_LINE> products =... | Create a default run database as SQLite in the config directory,
and add it to the list of products in the config database specified by
db_conn_string. | 625941d6c4546d3d9de72c5b |
def statistics_file(data): <NEW_LINE> <INDENT> data = filter(lambda d: '/.idea' not in d['path'], data) <NEW_LINE> data = filter(lambda d: '/target' not in d['path'], data) <NEW_LINE> result = {} <NEW_LINE> for d in data: <NEW_LINE> <INDENT> ext = d['ext'] <NEW_LINE> if ext not in result: <NEW_LINE> <INDENT> result[ext... | 统计文件类型,文件个数,代码行数 | 625941d68a43f66fc4b54289 |
def get_url(self, obj, view_name, request, format): <NEW_LINE> <INDENT> kwargs = {} <NEW_LINE> for model_field, url_param in self.lookup_fields: <NEW_LINE> <INDENT> attr = obj <NEW_LINE> for field in model_field.split('.'): <NEW_LINE> <INDENT> attr = getattr(attr, field) <NEW_LINE> <DEDENT> kwargs[url_param] = attr <NE... | Given an object, return the URL that hyperlinks to the object.
May raise a `NoReverseMatch` if the `view_name` and `lookup_field`
attributes are not configured to correctly match the URL conf. | 625941d6d7e4931a7ee9e144 |
def args_repr(args, **options): <NEW_LINE> <INDENT> count = options.get("count", 3) <NEW_LINE> cast = options.get("cast", lambda arg: type(arg).__name__) <NEW_LINE> item_format = options.get("item_format", "{}") <NEW_LINE> tail_format = options.get("tail_format", "...") <NEW_LINE> joiner = options.get("joiner", ", ") <... | Format positional arguments to use in exception handling.
:params args: tuple as obtained in arguments when declared in a function
as ``*args``.
:param options: some extra options could be used as excess keyword
arguments.
- count: maximum amount of actual parameters to process; after
r... | 625941d6435de62698dfde73 |
def _get_photo(self): <NEW_LINE> <INDENT> return self._config.get('photo', None) | Взять из ноды фото
:return: | 625941d64d74a7450ccd43e9 |
def searchTweets(self): <NEW_LINE> <INDENT> file = open(self.rawTextFile, "w+", encoding='utf-8') <NEW_LINE> batchID = 0 <NEW_LINE> listOfTweets = [] <NEW_LINE> numTweets = 0 <NEW_LINE> results = [] <NEW_LINE> while numTweets <= self.numberToPull: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> search = self.api.GetSearch... | :return results: List of tweet objects | 625941d699cbb53fe6792e0d |
def put(self,host,comm): <NEW_LINE> <INDENT> list_comm= comm.split() <NEW_LINE> tran = paramiko.Transport(host) <NEW_LINE> tran.connect(username='root', password='huayiqiu') <NEW_LINE> sftp = paramiko.SFTPClient.from_transport(tran) <NEW_LINE> try: <NEW_LINE> <INDENT> with self.lock: <NEW_LINE> <INDENT> sftp.put(list_c... | send files
sftp.put('D:/New folder/oldboy.txt','/tmp/from_windows')
:param host:
:param comm:
:return: | 625941d64d74a7450ccd43ea |
def solve_model(self, configuration): <NEW_LINE> <INDENT> model_dir = os.path.dirname(self.model_exec) <NEW_LINE> results_file_prefix = os.path.join(model_dir, "model") <NEW_LINE> results_file = results_file_prefix + "_RHS.dat" <NEW_LINE> if os.path.exists(results_file): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> os.... | Solve the given model and return a timeseries, or None
if solving the model has failed for some reason | 625941d61f5feb6acb0c4d74 |
def test_merge_leftequal( self ): <NEW_LINE> <INDENT> r = cr( 1, 5, 'Gap' ).merge( cr( 1, 3, 'Normal' ) ) <NEW_LINE> r2 = cr( 1, 5, 'Normal' ).merge( cr( 1, 3, 'Gap' ) ) <NEW_LINE> eq_( (cr( 1, 3, 'Normal'), cr( 4, 5, 'Gap' )), r ) <NEW_LINE> eq_( (cr( 1, 5, 'Normal'),), r2 ) | Left ends are equal but right ends do not. Diff rtype | 625941d6442bda511e8be63c |
def v3_add(matrix1, matrix2): <NEW_LINE> <INDENT> combined = [] <NEW_LINE> for row1, row2 in zip(matrix1, matrix2): <NEW_LINE> <INDENT> row = [ n + m for n, m in zip(row1, row2) ] <NEW_LINE> combined.append(row) <NEW_LINE> <DEDENT> return combined | Add corresponding numbers in given 2-D matrices.
Using a very fancy list comprehension to replace the creation of the
empty list - row = []. | 625941d644b2445a339322bb |
def refresh_asg(self, asg): <NEW_LINE> <INDENT> if not self.wait_for_clean_asg_refresh_status(asg, ['Successful', 'Cancelled', 'Failed'], 60)['success']: <NEW_LINE> <INDENT> logging.error("Timeout reached whilst waiting for ASG to become ready for another event. Try again later.") <NEW_LINE> return False <NEW_LINE> <DE... | Triggers and monitors an ASG refresh call of [asg]
Returns True on success and False on failure | 625941d6d53ae8145f87a494 |
def visit_call_expr(self, expr: CallExpr) -> None: <NEW_LINE> <INDENT> expr.callee.accept(self) <NEW_LINE> if refers_to_fullname(expr.callee, 'typing.cast'): <NEW_LINE> <INDENT> if not self.check_fixed_args(expr, 2, 'cast'): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> target = expr_to_unanal... | Analyze a call expression.
Some call expressions are recognized as special forms, including
cast(...), Undefined(...) and Any(...). | 625941d630dc7b7665901b8b |
def post(self, post_id): <NEW_LINE> <INDENT> key = db.Key.from_path('Post', int(post_id)) <NEW_LINE> self.post = db.get(key) <NEW_LINE> if self.user: <NEW_LINE> <INDENT> self.comment = self.request.get("newComment") <NEW_LINE> if self.comment: <NEW_LINE> <INDENT> c = Comments(comment = self.comment, createdBy = self.us... | This method adds the new comments entered by an user
to the datastore and displays the post along with
its comments | 625941d6de87d2750b85ffba |
def buildCurve(self, timeExt = None, timeStep = None, seaExt = None, ampExt = None, periodExt = None): <NEW_LINE> <INDENT> dt = float(timeStep) <NEW_LINE> so = float(seaExt[0]) <NEW_LINE> sm = float(seaExt[1]) <NEW_LINE> to = float(timeExt[0]) <NEW_LINE> tm = float(timeExt[1])+dt <NEW_LINE> Ao = float(ampExt[0]) <NEW_L... | Curve created which interpolate linearly the averaged values of sea-level
trends over the specified time period.
Parameters
----------
variable: timeExt
Extent of the simulation time: start/end time (in years)
variable: timeStep
Discretisation step for time range (in years).
variable: seaExt
Sea level va... | 625941d63617ad0b5ed6811d |
def load_rationale(path, regression): <NEW_LINE> <INDENT> label = [] <NEW_LINE> with open(path, 'r') as f: <NEW_LINE> <INDENT> next(f) <NEW_LINE> data = [] <NEW_LINE> for row in f: <NEW_LINE> <INDENT> row = row.strip().split('\t') <NEW_LINE> data.append({ 'label' : float(row[1]) if regression else int(float(row[1]))... | path: path to the tsv file that has machine generated rationales
regression: a binary variable indicating whether we are doing classification or regression | 625941d656b00c62f0f14881 |
def sync_metadata_to_storage(self, field_name: str, value: Any) -> None: <NEW_LINE> <INDENT> self._is_finalized() <NEW_LINE> update_data = {"{}.{}".format(DataSetIOReader.METADATA, field_name): value} <NEW_LINE> self._mongo_data_set_io.update_document(update_data) | Update or add metadata field to database.
Args:
field_name: Field that changed.
value: The new value. | 625941d68a43f66fc4b5428a |
def flags(self): <NEW_LINE> <INDENT> return super().flags() | QgsProcessingAlgorithm.FlagSupportsInPlaceEdits | Here we let QGIS know our algorithm supports edit-in-place | 625941d6d99f1b3c44c677b2 |
def naiveIsPalindromePermutation(inputString): <NEW_LINE> <INDENT> treatedString = treatString(inputString) <NEW_LINE> frequencies = characterCounts(treatedString).values() <NEW_LINE> oddCount = countOdds(frequencies) <NEW_LINE> isPalindrome = False <NEW_LINE> if len(treatedString) % 2 == 0: <NEW_LINE> <INDENT> if oddC... | Checks if the input string is a permutation of a palindrome.
This is inefficient as it has to go through the whole array before
returing the result. | 625941d6d4950a0f3b08c574 |
def update_network(self, site_id, settings=None, headers=None, payload=None, active_validation=True, **request_parameters): <NEW_LINE> <INDENT> check_type(headers, dict) <NEW_LINE> check_type(payload, dict) <NEW_LINE> check_type(site_id, basestring, may_be_none=False) <NEW_LINE> if headers is not None: <NEW_LINE> <INDE... | API to update network for DHCP and DNS center server settings. .
Args:
settings(object): Network Settings's settings.
site_id(basestring): siteId path parameter. Site id to update the network settings which is associated
with the site .
headers(dict): Dictionary of HTTP Headers to send with the Req... | 625941d64527f215b584c67c |
def load(self, filename=None): <NEW_LINE> <INDENT> fname = self.get_configfile() <NEW_LINE> if filename is not None and len(filename) > 0: <NEW_LINE> <INDENT> fname = filename <NEW_LINE> <DEDENT> if fname is None or not os.path.isfile(fname): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> confi... | Load configuration settings from the file filename, if filename | 625941d65166f23b2e1a537f |
def p_atomo(p): <NEW_LINE> <INDENT> pass | atomo : DECIMAL
| NUMERO | 625941d6de87d2750b85ffbb |
def hincrby(self, key, field, increment=1): <NEW_LINE> <INDENT> return self._conn.execute(b'HINCRBY', key, field, increment) | Increment the integer value of a hash field by the given number. | 625941d65166f23b2e1a5380 |
def __init__(self, layer, tmax): <NEW_LINE> <INDENT> self.tmax = tmax <NEW_LINE> self.W = [] <NEW_LINE> self.B = [] <NEW_LINE> self.RW = [] <NEW_LINE> self.RH = [] <NEW_LINE> self.RS = [] <NEW_LINE> for i in range(1, len(layer)): <NEW_LINE> <INDENT> self.W.append((n.random.random((layer[i-1], layer[i])) - 0.5)) <NEW_LI... | Diese Funktion initialisiert das KNN. Sie setzt Standard- bzw. Zufallswerte und baut die Datenstruktur für die
dynamische Berechnung auf.
:param layer: Der Aufbau des KNN wird hier übergeben. Diese Struktur ist wie folgt zu Verstehen:
Das KNN wird vom Input-Layer aus beschrieben mit jeweils einer ganzen Zahl größer Nu... | 625941d6bde94217f3683016 |
def setHighDensityCorrectionCubic(self,hdCorrectionCubic=None): <NEW_LINE> <INDENT> self._setDefaultParameter('hdCorrectionCubic',hdCorrectionCubic) | Set coefficient of cubic term of high density correction. | 625941d6851cf427c661a734 |
def int_from_str(s: str): <NEW_LINE> <INDENT> return int_from_bytes(s.encode()) | Convert string to integer | 625941d63346ee7daa2b2f93 |
def spi(self, SPIBytes, AutoCS=True, DisableDirConfig = False, SPIMode = 'A', SPIClockFactor = 0, CSPINNum = 1, CLKPinNum = 0, MISOPinNum = 3, MOSIPinNum = 2): <NEW_LINE> <INDENT> print(SPIBytes) <NEW_LINE> if not isinstance(SPIBytes, list): <NEW_LINE> <INDENT> raise LabJackException("SPIBytes MUST be a list of bytes")... | Name: UE9.spi(SPIBytes, AutoCS=True, DisableDirConfig = False,
SPIMode = 'A', SPIClockFactor = 0, CSPINNum = 1,
CLKPinNum = 0, MISOPinNum = 3, MOSIPinNum = 2)
Args: SPIBytes, a list of bytes to be transferred.
See Section 5.3.16 of the user's guide.
Desc: Sends and receives serial data u... | 625941d621a7993f00bc7f19 |
def __init__(self, aws_access_key_id=None, aws_secret_access_key=None, bucket_name=None, region_name=None, use_ssl=False, encryption=None, versioned=None, local_dev=False, endpoint_url=None): <NEW_LINE> <INDENT> self._s3 = None <NEW_LINE> self.region_name = region_name or os.getenv( 'AWS_S3_REGION') or self._DEFAULT_RE... | Initialize object, setup connection to the AWS S3. | 625941d60a50d4780f6670ba |
def get_diagnoses(): <NEW_LINE> <INDENT> return db.execute("SELECT * FROM diagnoses") | Returns list of diagnoses from database | 625941d6cb5e8a47e48b7ccf |
def penalty(self, sq, sq_prime, shift): <NEW_LINE> <INDENT> if sq == sq_prime or (sq, sq_prime) in self.whitelist: return 0 <NEW_LINE> prob = max(0, self.get_noise(sq, sq_prime, shift)) <NEW_LINE> return prob**2 * shift * self.unknown_cost | Using the whitelist average probability shifts, calculate penalty. | 625941d67b180e01f3dc4a21 |
def __new__(cls): <NEW_LINE> <INDENT> builder = get_builder('AboutEyeRefresher202020Dialog') <NEW_LINE> new_object = builder.get_object("about_eye_refresher_20_20_20_dialog") <NEW_LINE> new_object.finish_initializing(builder) <NEW_LINE> return new_object | Special static method that's automatically called by Python when
constructing a new instance of this class.
Returns a fully instantiated AboutDialog object. | 625941d6711fe17d82542590 |
@guarded <NEW_LINE> @require_owner_login <NEW_LINE> def delete_path(path): <NEW_LINE> <INDENT> visitor = get_visitor() <NEW_LINE> if 'storage' in request.args: <NEW_LINE> <INDENT> storage = store.storage.get(path) <NEW_LINE> if not storage.exist: <NEW_LINE> <INDENT> raise NotFound(path) <NEW_LINE> <DEDENT> storage.dele... | Delete file/directory
DELETE /img
DELETE /img/girl.jpg
Delete storage
DELETE /20180402_231528_2039_UTC?storage | 625941d62eb69b55b151cad8 |
def calculateSolutionOfDualProblem(colsOfIteration, function, totalMatrix): <NEW_LINE> <INDENT> if type(totalMatrix) != np.matrix or type(colsOfIteration) != np.ndarray or type(function) != np.ndarray or totalMatrix.shape[1] != len(function) or totalMatrix.shape[1] < len(colsOfIteration) or len(function) < len(colsOfIt... | This method receives the columns of the last iteration in a numpy array, the complete function vector in a numpy array with rational objects and
the initial matrix of the problem in a numpy matrix with rational objects. It returns the solution of the dual problem in a numpy array. If the parameters are not correct, it
... | 625941d61d351010ab855d42 |
def maxTurbulenceSize(self, arr: List[int]) -> int: <NEW_LINE> <INDENT> up, down = 1, 1 <NEW_LINE> res = 1 <NEW_LINE> for i in range(len(arr)-1): <NEW_LINE> <INDENT> if arr[i] > arr[i+1]: up, down = 1, up+1 <NEW_LINE> elif arr[i] < arr[i+1]: up, down = down+1, 1 <NEW_LINE> else: up, down = 1, 1 <NEW_LINE> res = max(res... | p978 medium
状态转换,有点DP的意思 | 625941d6adb09d7d5db6c9b5 |
def test_invkin_flip(self): <NEW_LINE> <INDENT> scara = Scara.Scara(l1=l1, l2=l2, flip_x=-1) <NEW_LINE> tool = RobotSpacePoint(-l2, -l1, 0, 0) <NEW_LINE> joints = scara.inverse_kinematics(tool) <NEW_LINE> self.assertAlmostEqual(joints.theta1, -pi / 2) <NEW_LINE> self.assertAlmostEqual(joints.theta2, pi / 2) <NEW_LINE> ... | Checks that inverse kinematics works with vertical flip | 625941d6c4546d3d9de72c5c |
def get_pr_id(self, account_id: str): <NEW_LINE> <INDENT> return self.get_user_pr_path(account_id).read_text() | Returns an API URL e.g.
https://api.github.com/repos/citizenlab/test-lists/pulls/800
Raises if the PR was never opened | 625941d65fc7496912cc3ba5 |
def markers(self, offset=0, from_first_marker=False): <NEW_LINE> <INDENT> abs_time = 0 <NEW_LINE> markers = [] <NEW_LINE> i = 0 <NEW_LINE> entries = self.entries_video_seconds() <NEW_LINE> for attr in self.session['children']: <NEW_LINE> <INDENT> if 'kdenlivedoc' in attr['name']: <NEW_LINE> <INDENT> for att in attr['ch... | by default return a dict of markers with timecodes relative to an origin
if from_first_marker=False: the origin is the first entry timecode
if from_first_marker=True: the origin is the first entry timecode before the first marker
offset: general origin offset | 625941d666673b3332b922b9 |
def GetOptionsDialog(self): <NEW_LINE> <INDENT> return self.opt_dialog | Returns the options dialog or None | 625941d6442bda511e8be63d |
def resume(self) -> None: <NEW_LINE> <INDENT> self.start_event.set() | Resume the process after pause.
:return: | 625941d6cdde0d52a9e5325b |
def only_allow_defined_args(function_to_decorate): <NEW_LINE> <INDENT> @functools.wraps(function_to_decorate) <NEW_LINE> def _return_wrapped(*args, **kwargs): <NEW_LINE> <INDENT> valid_names = get_defined_args(function_to_decorate) <NEW_LINE> for arg_name in kwargs: <NEW_LINE> <INDENT> if arg_name not in valid_names: <... | Decorator which only allows arguments defined to be used.
Note, we need to specify this, as Fire allows method chaining. This means
that extra kwargs are kept around and passed to future methods that are
called. We don't need this, and should fail early if this happens.
Args:
function_to_decorate: Function which to dec... | 625941d6925a0f43d254a09f |
def predict(self,X,Y,T,wv_X,wv_T,kind): <NEW_LINE> <INDENT> print ('predicting..向量化中...') <NEW_LINE> vec = TfidfVectorizer(use_idf=True, sublinear_tf=False, max_features=60000, binary=True) <NEW_LINE> vec.fit(X, Y) <NEW_LINE> X = vec.transform(X) <NEW_LINE> T = vec.transform(T) <NEW_LINE> print ('train size',X.shape,T.... | train and predict | 625941d6d486a94d0b98e36d |
def get_usnob1_cat(ra, dec, blim,radius=15.0*u.arcmin): <NEW_LINE> <INDENT> ra_u = ra * u.deg <NEW_LINE> dec_u = dec * u.deg <NEW_LINE> coords = SkyCoord(ra_u, dec_u, frame='icrs') <NEW_LINE> v = Vizier(columns=['USNO-B1.0', '_RAJ2000', '_DEJ2000', 'B1mag', 'R1mag', 'B2mag', 'R2mag', 'pmRA', 'pmDE', 'Imag', 'B1s/g', '_... | Assume that the ra,dec are given as float parameters in units of deg
if (type(ra) == float) & (type(dec) == float):
ra_u = ra*u.degree
dec_u = dec*u.degree
elif (type(ra) == np.float64) & (type(dec) == np.float64):
ra_u = ra*u.degree
dec_u = dec*u.degree
elif hasattr(ra,... | 625941d6d18da76e235326ff |
def update_bug(auth, bugid, bugdata): <NEW_LINE> <INDENT> return auth.rest_request('PUT', 'bug/%s' % bugid, bugdata) | Update an existing bug. Must pass in an existing bug as a data structure.
Mid-air collisions are possible. | 625941d6b57a9660fec33aae |
def Move(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!') | Move subnet to another folder.
| 625941d6d268445f265b5095 |
def uptime_win32(): <NEW_LINE> <INDENT> import win32api <NEW_LINE> return float(time.time()) - float(win32api.GetTickCount() / 1000) | Returns the number of seconds between the epoch and when the Windows system
was booted.
@rtype: C{float} | 625941d6aad79263cf390c6b |
def performers(self): <NEW_LINE> <INDENT> person = set() <NEW_LINE> ret = [] <NEW_LINE> IPClass = self.get_object_map("performance") <NEW_LINE> ICPClass = self.get_object_map("releaseperformance") <NEW_LINE> IClass = self.get_object_map("instrument") <NEW_LINE> for p in self.performance.all(): <NEW_LINE> <INDENT> if p.... | The performers on a concert are those who are in the performance relations,
both on the concert and the concerts recordings.
TODO: Should this return a performance object, or an artist? | 625941d6e64d504609d74a67 |
def read_tree(self,tree, rename): <NEW_LINE> <INDENT> newick_tree = Phylo.read(tree, 'newick') <NEW_LINE> if rename: <NEW_LINE> <INDENT> copied_tree = copy.deepcopy(newick_tree) <NEW_LINE> for node in copied_tree.get_nonterminals(order="postorder"): <NEW_LINE> <INDENT> leaves = node.find_clades() <NEW_LINE> leaves = [x... | Reads the NEWICK tree! DEPENDENCY: BioPython
:param tree: Path to the NEWICK tree
:param rename: boolean variable, that indicates whether the internal nodes of the tree are renamed
based on their children
:return: Some BioPython Object containing information of the tree. | 625941d6e5267d203edcdec2 |
def vm_load_pe_libs(vm, libs_name, libs, lib_path_base="win_dll", **kargs): <NEW_LINE> <INDENT> libs = {} <NEW_LINE> for fname in libs_name: <NEW_LINE> <INDENT> libs[fname] = vm_load_pe_lib(vm, fname, libs, lib_path_base, **kargs) <NEW_LINE> <DEDENT> return libs | Call vm_load_pe_lib on each @libs_name filename
@vm: VmMngr instance
@libs_name: list of str
@libs: libimp_pe instance
@lib_path_base: (optional) DLLs relative path
Return a dictionnary Filename -> PE instances
Extra arguments are passed to vm_load_pe_lib | 625941d64a966d76dd551238 |
def status(*packs): <NEW_LINE> <INDENT> ret = True <NEW_LINE> packs = resolve_package_spec(packs) <NEW_LINE> for pack in packs: <NEW_LINE> <INDENT> ret = status_pack(pack) or ret <NEW_LINE> <DEDENT> return ret | Prints status of a pack. | 625941d6566aa707497f478d |
def col_head_edit(self): <NEW_LINE> <INDENT> if not self._render_col_head_edit and self._col_head_edit_renderer: <NEW_LINE> <INDENT> self._render_col_head_edit = ModeWrapValueRenderer( "col_head_edit", TemplateWrapValueRenderer( col_head_wrapper_template, self._col_head_edit_renderer ) ) <NEW_LINE> <DEDENT> return self... | Returns a renderer object to display nothing on small media, or
a field label used as a column header on larger media when
editing an entity. | 625941d63cc13d1c6d3c75a1 |
def test_filesFromLibmseed(self): <NEW_LINE> <INDENT> path = os.path.join(self.path, "data", "encoding") <NEW_LINE> def_content = np.arange(1, 51, dtype='int32') <NEW_LINE> files = { os.path.join(path, "smallASCII.mseed"): ('|S1', 'a', 0, np.fromstring('ABCDEFGH', dtype='|S1')), os.path.join(path, "fullASCII.mseed"): (... | Tests reading of files that are created by libmseed.
This test also checks the files created by libmseed to some extend. | 625941d6090684286d50ef0e |
def test_srcdir_list(self): <NEW_LINE> <INDENT> src = self.fs.Dir('src') <NEW_LINE> bld = self.fs.Dir('bld') <NEW_LINE> sub1 = bld.Dir('sub') <NEW_LINE> sub2 = sub1.Dir('sub') <NEW_LINE> sub3 = sub2.Dir('sub') <NEW_LINE> self.fs.VariantDir(bld, src, duplicate=0) <NEW_LINE> self.fs.VariantDir(sub2, src, duplicate=0) <NE... | Test the Dir.srcdir_list() method
| 625941d6d8ef3951e3243765 |
def test_convert_wilhoit_to_nasa(self): <NEW_LINE> <INDENT> wilhoit = self.wilhoit <NEW_LINE> nasa = wilhoit.to_nasa(Tmin=10, Tmax=3000, Tint=1000) <NEW_LINE> Tlist = np.arange(10, 3000, 10) <NEW_LINE> for T in Tlist: <NEW_LINE> <INDENT> cp_wilhoit = wilhoit.get_heat_capacity(T) <NEW_LINE> cp_nasa = nasa.get_heat_capac... | Test the conversion of a Wilhoit model to a NASA model. | 625941d6cad5886f8bd27200 |
def setAttributeArray(self, *__args): <NEW_LINE> <INDENT> pass | QGLShaderProgram.setAttributeArray(int, sequence)
QGLShaderProgram.setAttributeArray(str, sequence) | 625941d6283ffb24f3c55b27 |
def main(args): <NEW_LINE> <INDENT> if len(args) < 2: <NEW_LINE> <INDENT> print(cli_string) <NEW_LINE> sys.exit(1) <NEW_LINE> <DEDENT> module_or_filename = args[1] <NEW_LINE> module, module_name = import_module(module_or_filename) <NEW_LINE> fire.Fire(module, name=module_name, command=args[2:]) | Entrypoint for fire when invoked as a module with python -m fire. | 625941d6bd1bec0571d90857 |
def default_convert(data): <NEW_LINE> <INDENT> elem_type = type(data) <NEW_LINE> if isinstance(data, torch.Tensor): <NEW_LINE> <INDENT> return data <NEW_LINE> <DEDENT> elif elem_type.__module__ == 'numpy' and elem_type.__name__ != 'str_' and elem_type.__name__ != 'string_': <NEW_LINE> <INDENT> if elem_type._... | Converts each NumPy array data field into a tensor | 625941d644b2445a339322bc |
def get_records(self, sql): <NEW_LINE> <INDENT> raise NotImplementedError() | Returns records for the sql query (for hooks that support SQL). | 625941d6f8510a7c17cf9924 |
def isom_normal(v,w, F, G, normal_basis_w = None, normal_basis_v = None): <NEW_LINE> <INDENT> p = F.characteristic() <NEW_LINE> n = F.degree() <NEW_LINE> if normal_basis_w is None: <NEW_LINE> <INDENT> normal_basis_w = [w] <NEW_LINE> for i in range(n): <NEW_LINE> <INDENT> normal_basis_w.append(normal_basis_w[-1]**p) <NE... | INPUT :
- ``v`` -- a normal element of a finite field F on GF(q).
- ``w`` -- a normal element of a finite field G on GF(q).
- ``F`` -- a finite field of q^n elements.
- ``G`` -- a finite field of q^n elements.
- ``normal_basis_w`` -- (default: None) a pre-calculated normal basis for w.
- ``normal_basis_v`` -- (d... | 625941d60fa83653e46571e2 |
def action_sysinfo(self): <NEW_LINE> <INDENT> sysinfo = self.cs.get_sysinfo() <NEW_LINE> sysinfo = self.cdictify(sysinfo) <NEW_LINE> meta = {'device': 'system'} <NEW_LINE> if self.location: <NEW_LINE> <INDENT> meta.update({'location': self.location}) <NEW_LINE> <DEDENT> self.sendEvent('system_update', sysinfo, meta) | Get system information | 625941d666656f66f7cbc3d3 |
def alamouti_ofdm_rx_make(*args, **kwargs): <NEW_LINE> <INDENT> return _mimo_swig.alamouti_ofdm_rx_make(*args, **kwargs) | alamouti_ofdm_rx_make(unsigned int occupied_carriers, unsigned int fft_length, unsigned int cplen) -> alamouti_ofdm_rx_sptr | 625941d623e79379d52ee789 |
def has_internet_connection(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> import socket <NEW_LINE> host = socket.gethostbyname("google.com") <NEW_LINE> socket.create_connection((host, 80), 2) <NEW_LINE> return True <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> return False | Return True if computer is connected to internet. | 625941d6b7558d58953c5139 |
def sqrt_update(x): <NEW_LINE> <INDENT> return average(x, a/x) | This function returns result of average function whiere a is already difind and x is guess | 625941d6ab23a570cc2503ab |
def do_plugin_list(cs, args): <NEW_LINE> <INDENT> plugins = cs.plugins.list() <NEW_LINE> columns = ('name', 'versions', 'title') <NEW_LINE> utils.print_list(plugins, columns, {'versions': _print_list_field('versions')}) | Print a list of available plugins. | 625941d6a05bb46b383eca49 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.