content
stringlengths
27
928k
path
stringlengths
4
230
size
int64
27
928k
nl_text
stringlengths
21
396k
nl_size
int64
21
396k
nl_language
stringlengths
2
3
nl_language_score
float64
0.04
1
# Copyright 2012, VMware, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agre...
neutron/tests/unit/agent/linux/test_utils.py
8,292
Copyright 2012, VMware, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, ...
599
en
0.859696
import logging from urllib.parse import urljoin import scrapy from scrapy import Request from scrapy_selenium import SeleniumRequest from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from sainsburys.items import SainsburysItem logger = logging.getLogger('s...
sainsburys/sainsburys/spiders/basic.py
2,385
yield response.follow(url, callback=self.parse_product)
55
en
0.157362
import pickle import torch from torch.utils.data import Dataset, DataLoader import numpy as np import torch.nn as nn def load_pickle(pickle_file): try: with open(pickle_file, 'rb') as f: pickle_data = pickle.load(f) except UnicodeDecodeError as e: with open(pickle_file, 'rb') as f:...
deprecated/dataloaders/affect/humor_dataset.py
5,222
left padding with zero vector upto maximum number of words in a sentence * glove embedding dimension left padding with zero vector upto maximum number of words in a sentence * covarep dimension left padding with zero vector upto maximum number of words in a sentence * openface dimension left padding with zero vector...
465
en
0.689097
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "travel.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the ...
travel/manage.py
804
!/usr/bin/env python The above import may fail for some other reason. Ensure that the issue is really that Django is missing to avoid masking other exceptions on Python 2.
171
en
0.863733
class Solution: def maxChunksToSorted(self, arr): """ :type arr: List[int] :rtype: int """ stacks = [] for num in arr: if not stacks: stacks.append([num]) elif num >= stacks[-1][0]: stacks.append([num]) ...
p768_max_chunks_to_make_sorted_ii.py
919
:type arr: List[int] :rtype: int num < stacks[-1][0] print(stacks)
68
en
0.244743
from operator import attrgetter import pyangbind.lib.xpathhelper as xpathhelper from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType from pyangbind.lib.base import PybindBase from d...
pybind/slxos/v17r_1_01a/brocade_mpls_rpc/show_mpls_lsp_extensive/output/lsp/show_mpls_lsp_extensive_info/show_mpls_lsp_sec_path_info/sec_path/lsp_sec_path_config_admin_groups/lsp_admin_group/lsp_admin_group_include_any/__init__.py
7,563
This class was auto-generated by the PythonClass plugin for PYANG from YANG module brocade-mpls - based on the path /brocade_mpls_rpc/show-mpls-lsp-extensive/output/lsp/show-mpls-lsp-extensive-info/show-mpls-lsp-sec-path-info/sec-path/lsp-sec-path-config-admin-groups/lsp-admin-group/lsp-admin-group-include-any. Each me...
1,436
en
0.470591
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: sprint.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf impo...
easy_work_service_sdk/model/topboard/sprint_pb2.py
6,211
-*- coding: utf-8 -*- Generated by the protocol buffer compiler. DO NOT EDIT! source: sprint.proto @@protoc_insertion_point(imports) @@protoc_insertion_point(class_scope:topboard.Sprint) @@protoc_insertion_point(module_scope)
226
en
0.539846
from __future__ import print_function from __future__ import absolute_import from __future__ import division try: basestring except NameError: basestring = str import compas_rhino from compas.utilities import iterable_like from compas_rhino.artists._primitiveartist import PrimitiveArtist __all__ = ['LineArt...
src/compas_rhino/artists/lineartist.py
3,307
Artist for drawing lines. Parameters ---------- primitive : :class:`compas.geometry.Line` A COMPAS line. Notes ----- See :class:`compas_rhino.artists.PrimitiveArtist` for all other parameters. Draw the line. Returns ------- list The GUIDs of the created Rhino objects. Draw a collection of lines. Parameters ...
1,145
en
0.478219
# Copyright (C) 2021 Xilinx, Inc # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
setup.py
1,357
Setup file for logicnets. Use setup.cfg to configure your project. This file was generated with PyScaffold 3.2.3. PyScaffold helps you to put up the scaffold of your new Python project. Learn more under: https://pyscaffold.org/ Copyright (C) 2021 Xilinx, Inc Licensed under the Apache License, Version 2.0 (the "Lic...
1,001
en
0.873573
# Copyright (C) 2017-2019 Apple Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and ...
Tools/Scripts/webkitpy/port/device.py
4,453
Copyright (C) 2017-2019 Apple Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following ...
1,291
en
0.892219
import datetime from datetime import timedelta import csv from module.stock import Stock, Market # Historic Files DAX = 'DAX.csv' DOW = 'Dow.csv' FTSE = 'FTSE.csv' # Output File OUTPUT = 'output.txt' def import_csv(file_name): data = [] with open(file_name) as file: reader = csv.reader(file) ...
d.py
1,082
Historic Files Output File Import historic stock performance Sorts into date order Name, price, units
101
en
0.710626
# -*- coding: utf-8 -*- from __future__ import unicode_literals import flask from flask import Blueprint, request import flask_restx as restx # Add a dummy Resource to verify that the app is properly set. class HelloWorld(restx.Resource): def get(self): return {} class GoodbyeWorld(restx.Resource): ...
tests/legacy/test_api_with_blueprint.py
6,919
-*- coding: utf-8 -*- Add a dummy Resource to verify that the app is properly set.
82
en
0.844923
# pyOCD debugger # Copyright (c) 2019 Arm Limited # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # ...
pyocd/target/family/__init__.py
1,208
pyOCD debugger Copyright (c) 2019 Arm Limited SPDX-License-Identifier: Apache-2.0 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by app...
910
en
0.8254
import argparse import RDT import time import rdt_3_0 def makePigLatin(word): m = len(word) vowels = "a", "e", "i", "o", "u", "y" if m < 3 or word == "the": return word else: for i in vowels: if word.find(i) < m and word.find(i) != -1: m = word.find(i) ...
submission_files/server_3_0.py
1,535
close connection if no new data within 5 seconds try to receiver message before timeout msg_S = rdt.rdt_2_1_receive() convert and reply rdt.rdt_2_1_send(rep_msg_S)
163
en
0.599335
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # C...
venv/lib/python3.8/site-packages/azure/mgmt/datalake/analytics/catalog/models/usql_external_data_source.py
2,339
A Data Lake Analytics catalog U-SQL external datasource item. :param compute_account_name: the name of the Data Lake Analytics account. :type compute_account_name: str :param version: the version of the catalog item. :type version: str :param database_name: the name of the database. :type database_name: str :param nam...
1,157
en
0.558444
# This module just exists as a shortcut for running the main Kivy app if __name__ == '__main__': from naturtag.app.app import NaturtagApp NaturtagApp().run()
naturtag/ui.py
167
This module just exists as a shortcut for running the main Kivy app
67
en
0.809556
#!C:\Users\John\PycharmProjects\arcadePython\venv\Scripts\python.exe # EASY-INSTALL-ENTRY-SCRIPT: 'pip==10.0.1','console_scripts','pip3.6' __requires__ = 'pip==10.0.1' import re import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys...
venv/Scripts/pip3.6-script.py
421
!C:\Users\John\PycharmProjects\arcadePython\venv\Scripts\python.exe EASY-INSTALL-ENTRY-SCRIPT: 'pip==10.0.1','console_scripts','pip3.6'
135
en
0.371472
from django.db import models from osc_bge.users import models as user_models # Create your models here. class TimeStampedModel(models.Model): created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True, null=True) class Meta: abstract = True #...
osc_bge/agent/models.py
5,611
Create your models here.Agent Head TableAgent Branch Table
58
en
0.56847
''' First Version: Tweets contents from subreddits ''' from time import sleep from reddit import Reddit from twitter import Twitter def main(): ''' connects the pieces to grab posts from reddit and throw them on twitter ''' reddit = Reddit() twitter = Twitter() tweets = reddit.get_tweets() ...
tweet_bot.py
596
connects the pieces to grab posts from reddit and throw them on twitter First Version: Tweets contents from subreddits
118
en
0.892743
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright © 2017 Matthew Stone <mstone5@mgh.harvard.edu> # Distributed under terms of the MIT license. """ Calculate enrichment of clipped reads or discordant pairs at SV breakpoints. """ import argparse import sys import pysam import pandas as pd from svtk.pesr impor...
src/svtk/svtk/cli/pesr_test.py
14,259
Calculate enrichment of clipped reads or discordant pairs at SV breakpoints. !/usr/bin/env python -*- coding: utf-8 -*- Copyright © 2017 Matthew Stone <mstone5@mgh.harvard.edu> Distributed under terms of the MIT license. TODO: add normalization Print help if no arguments specified counts[cols].to_csv(fout, header=Fal...
577
en
0.295601
#!/usr/bin/python3 def lowestPositiveInt(A): A.sort() index = -1 try: index = A.index(1) except ValueError: return 1 # Remove all negatives and zero if 1 is found # if index >= 0: A = A[index:] length = len(A) i = 1 found = 0 while i ...
codingTestIterative.py
891
!/usr/bin/python3 Remove all negatives and zero if 1 is found if index >= 0:
76
en
0.526975
from keras_vggface.utils import preprocess_input from keras_vggface.vggface import VGGFace import numpy as np import pickle from sklearn.metrics.pairwise import cosine_similarity import cv2 from mtcnn import MTCNN from PIL import Image feature_list = np.array(pickle.load(open('artifacts/extracted_features/embedding.pk...
src/testing.py
1,571
detect face load img -> face detection extract its features print(result) print(result.shape) print(result.reshape(1,-1)) find the cosine distance of current image with all the 8664 features print(len(similarity))recommend that image
234
en
0.80239
#!/usr/bin/env python # GenerateJSONOutput.py # # Command-line interface for turning output root files into JSON files for further processing. # # By: Larry Lee - Dec 2017 import argparse import sys import os import ROOT ROOT.gSystem.Load(f"{os.getenv('HISTFITTER')}/lib/libSusyFitter.so") ROOT.gROOT.SetBatch() pa...
scripts/GenerateJSONOutput.py
5,344
!/usr/bin/env python GenerateJSONOutput.py Command-line interface for turning output root files into JSON files for further processing. By: Larry Lee - Dec 2017 Print out the settings grab just the filename an entry is one hypo test result each item of the result parse input arguments, thanks to Larry for regex suggest...
348
en
0.646568
import csv import logging import random import re from collections import OrderedDict from enum import IntEnum from pathlib import Path from typing import Optional, Tuple, List import attr from torch.utils.data import Dataset from syntok import segmenter from sklearn.model_selection import train_test_split logger = ...
gendered-pronoun-resolution/data.py
5,257
exclusive exclusive exclusive exclusive Split tokens on additional characters not handled by syntok whitespace
110
en
0.751839
# Generated by Django 2.2.24 on 2021-12-13 07:54 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("taskflow3", "0017_auto_20211116_1526"), ] operations = [ migrations.AlterModelOptions( name="autoretrynodestrategy", ...
gcloud/taskflow3/migrations/0018_auto_20211213_1554.py
1,695
Generated by Django 2.2.24 on 2021-12-13 07:54
46
en
0.735742
""" Django settings for app project. Generated by 'django-admin startproject' using Django 2.1.15. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # Bu...
app/app/settings.py
3,625
Django settings for app project. Generated by 'django-admin startproject' using Django 2.1.15. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ Build paths inside the...
1,188
en
0.662332
""" Provide classes to perform the groupby aggregate operations. These are not exposed to the user and provide implementations of the grouping operations, primarily in cython. These classes (BaseGrouper and BinGrouper) are contained *in* the SeriesGroupBy and DataFrameGroupBy objects. """ from __future__ import annota...
pandas/core/groupby/ops.py
40,148
This is an internal Grouper class, which actually holds the generated groups Parameters ---------- axis : Index groupings : Sequence[Grouping] all the grouping instances to handle in this grouper for example for grouper list to groupby, need to pass the list sort : bool, default True whether this grouper w...
8,479
en
0.754825
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
tensorflow/python/ops/math_ops.py
129,354
Use Python2/Python3 division delegation to implement divide for tensors. Common shape function for binary operators that broadcast their inputs. Register operators with different tensor and scalar versions. If `clazz_object` is `SparseTensor`, assumes `func` takes `(sp_indices, sp_values, sp_shape, dense)` and outputs...
71,765
en
0.744922
""" Median and Mean for Cauchy distribution --------------------------------------- This plot shows graphically that mean-based statistics are not robust for the Cauchy distribution. Median-based statistics should be used instead. """ # Author: Jake VanderPlas # License: BSD # The figure produced by this code is pu...
book_figures/chapter3/fig_cauchy_median_mean.py
3,753
Compute the robust mean iteratively After computing the mean, points further than 3 sigma from the mean are removed and the result is repeated until convergence. Compute the mean via a mixture of two Gaussians One Gaussian accounts for outliers, and one Gaussian accounts for the true distribution. This cannot be co...
1,535
en
0.814881
""" Utilities for fast persistence of big data, with optional compression. """ # Author: Gael Varoquaux <gael dot varoquaux at normalesup dot org> # Copyright (c) 2009 Gael Varoquaux # License: BSD Style, 3 clauses. import pickle import traceback import os import zlib import warnings from io import BytesIO from ._co...
Sklearn_scipy_numpy/source/sklearn/externals/joblib/numpy_pickle.py
17,419
An object to be persisted instead of numpy arrays. The only thing this object does, is to carry the filename in which the array has been persisted, and the array subclass. A pickler to persist of big data efficiently. The main features of this object are: * persistence of numpy arrays in separate .npy files, for wh...
6,865
en
0.869886
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. try: from collections.abc import Iterable except ImportError: from collections import Iterable import contextlib import itertools impo...
fairseq/data/data_utils.py
21,283
Yield mini-batches of indices bucketed by size. Batches may contain sequences of different lengths. Args: indices (List[int]): ordered list of dataset indices num_tokens_fn (callable): function that returns the number of tokens at a given index num_tokens_vec (List[int], optional): precomputed vect...
4,809
en
0.751023
from flask import Flask from flask_bootstrap import Bootstrap from config import config_options bootstrap = Bootstrap() def create_app(config_name): app = Flask(__name__) # create ap configurations app.config.from_object(config_options[config_name]) # initialize flask extensions bootstrap.init...
app/__init__.py
560
create ap configurations initialize flask extensions Registering the blueprint setting config
93
en
0.404373
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from pathlib import Path import pandas as pd from watchdog.events import FileSystemEventHandler from watchdog.observers ...
src/budget/watcher.py
1,241
This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
192
en
0.934305
#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutTuples(Koan): def test_creating_a_tuple(self): count_of_three = (1, 2, 5) self.assertEqual(5, count_of_three[2]) def test_tuples_are_immutable_so_item_assignment_is_not_possible(self): count_of_three =...
python3/koans/about_tuples.py
2,347
!/usr/bin/env python -*- coding: utf-8 -*- Note, assertRegexpMatches() uses regular expression pattern matching, so you don't have to copy the whole message. Tuples are less flexible than lists, but faster.Sometimes less confusing
230
en
0.813063
# Generated by Django 2.2.1 on 2019-05-17 22:55 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('wells', '0088_fieldsprovided'), ('wells', '0088_remove_well_ems_id'), ] operations = [ ]
app/backend/wells/migrations/0089_merge_20190517_2255.py
265
Generated by Django 2.2.1 on 2019-05-17 22:55
45
en
0.537287
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models from django.contrib.contenttypes import generic class Migration(SchemaMigration): def forwards(self, orm): # renaming ExperimentACL to 'ObjectACL' db.rename_table('tar...
tardis/tardis_portal/south_migrations/0022_object_acl_1.py
21,000
-*- coding: utf-8 -*- renaming ExperimentACL to 'ObjectACL' changing experiment to content_types renaming ExperimentACL to 'ObjectACL'raise RuntimeError('Cannot reverse this migration.')
186
en
0.559006
import discord from discord.ext import commands import asyncio import wolframalpha from aiohttp import ClientSession from html2text import html2text from random import choice, randint from re import sub #setup wolframalpha API client = wolframalpha.Client(open('WA_KEY').readline().rstrip()) class Api(commands.Cog): ...
extensions/api.py
7,242
Get random cute pics setup wolframalpha API
44
en
0.258199
""" Copyright 2020 Qiniu Cloud (qiniu.com) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, softw...
pdr_python_sdk/pdr_python_sdk/spl/spl_streaming_batch_command.py
1,097
Copyright 2020 Qiniu Cloud (qiniu.com) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software ...
557
en
0.849154
import argparse import configparser import json import os import sys import time import requests sys.path.append(os.path.join(os.path.dirname(__file__), "..")) from util import logger class ConversationScraper: """Scraper that retrieves, process and stores all messages belonging to a specific Facebook conversat...
src/util/conversationScraper.py
10,522
Scraper that retrieves, process and stores all messages belonging to a specific Facebook conversation Executes the POST request and retrieves the correspondent response content. Request headers are generated here :return: the response content Generate the data for the POST request. :return: the generated data Retrieves...
1,099
en
0.848166
# 033 # Ask the user to enter two numbers. Use whole number division to divide # the first number by the second and also work out the remainder and # display the answer in a user-friendly way # (e.g. if they enter 7 and 2 display “7 divided by 2 is 3 # with 1 remaining”). from typing import List def check_num_list(p...
150-Challenges/Challenges 27 - 34/Challenge 33.py
1,668
Function to check if users input is a number, splitting number by spaces and checking that the correct amount of numbers are entered, returning them in a list 033 Ask the user to enter two numbers. Use whole number division to divide the first number by the second and also work out the remainder and display the answe...
421
en
0.890763
# Code made for Sergio Andrés Díaz Ariza # 23 March 2021 # License MIT # Transport Phenomena: Python Program-Assesment 3.3 import matplotlib.pyplot as plt import seaborn as sns import numpy as np sns.set() class Wire_Param: def Power_from_volt(self, V, R_Km, Dis_insul, Diameter_mm): As = (np.pi * (Diam...
Heat_Transfer/3.3-Wire_Isolation_Base__Fin.py
2,514
Code made for Sergio Andrés Díaz Ariza 23 March 2021 License MIT Transport Phenomena: Python Program-Assesment 3.3 Power generated = Egen [w/m^3] [W/m^3] Value L--> must be positive fo calculus A_inv = np.linalg.inv(A) ---> We can find the solution directly solve for Temperature Profile
287
en
0.575088
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- """Factory method for easily getting imdbs by name.""" from __future__ ...
lib/datasets/factory.py
2,716
Get an imdb (image database) by name. List all registered imdbs. Factory method for easily getting imdbs by name. -------------------------------------------------------- Fast R-CNN Copyright (c) 2015 Microsoft Licensed under The MIT License [see LICENSE for details] Written by Ross Girshick -------------------------...
728
en
0.541779
#!/usr/bin/python # -*- coding: utf-8 -*- """ Script to upload the mappings of Freebase to Wikidata. Can be easily adapted to upload other String identifiers as well This bot needs the dump from https://developers.google.com/freebase/data#freebase-wikidata-mappings The script takes a single parameter: -filename: th...
scripts/freebasemappingupload.py
4,148
Freebase Mapping bot. Initializer. Process command line arguments and invoke bot. If args is an empty list, sys.argv is used. @param args: command line arguments @type args: str Process a single line. Run the bot. Script to upload the mappings of Freebase to Wikidata. Can be easily adapted to upload other String ide...
1,050
en
0.666926
#!/usr/bin/python3.5 import yaml import os.path import logging logger = logging.getLogger('rsync_backup') config = None cmd = '/usr/bin/rsync' # load the configuration file in def load_config(filepath): global config with open(filepath, "r") as file_descriptor: config = yaml.load(fi...
bin/utils/config.py
3,034
!/usr/bin/python3.5 load the configuration file in Returns a list of tuplets (of commands src and destination) Test to see if the source and destination locations exist/are accessible Compile the commandsnoexec_cmd_str = " ".join(noexec_cmd) Test to see if the source and destination locations exist/are accessibleexit()
320
en
0.637354
""" sphinx.domains.cpp ~~~~~~~~~~~~~~~~~~ The C++ language domain. :copyright: Copyright 2007-2020 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re from typing import ( Any, Callable, Dict, Generator, Iterator, List, Tuple, Type, TypeVar, Union ) from do...
sphinx/domains/cpp.py
288,143
C++ language domain. There are two 'object type' attributes being used:: - Each object created from directives gets an assigned .objtype from ObjectDescription.run. This is simply the directive name. - Each declaration (see the distinction in the directives dict below) has a nested .ast of type ASTDeclaration. Th...
23,673
en
0.795698
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables from...
sdk/python/pulumi_azure_native/web/v20200901/web_app_site_push_settings_slot.py
9,647
Push settings for the App. :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] dynamic_tags_json: Gets or sets a JSON string containing a list of dynamic tags that will be evaluated from user claims in the push registration endpoint...
2,474
en
0.659273
""" This software was developed by the University of Tennessee as part of the Distributed Data Analysis of Neutron Scattering Experiments (DANSE) project funded by the US National Science Foundation. See the license text in license.txt copyright 2008, 2009, University of Tennessee """ import wx import sys from sas....
src/sas/sasgui/perspectives/calculator/kiessig_calculator_panel.py
9,529
Provides the Kiessig thickness calculator GUI. Define the main sizers building to build this application. Draw window content Do the layout for the button widgets Fill the sizer containing dq name Fill the sizer containing hint Fill the sizer containing thickness information On Text_enter_callback, perform compute Ret...
1,630
en
0.809921
import unittest from typing import Optional from pathlib import Path from time import strftime, gmtime from github import Github import json import yaml from .. import get_repo_meta, clone_and_archive from ..get_github import dump_list from pathlib import Path class TestGetGithub(unittest.TestCase): """ Te...
github_archive/test/test_get_github.py
6,815
Test coverage for the get_github module Given a directory (with ``None`` implying the current directory) assumed to be at or under this project's root, find the project root directory. This implementation attempts to find a directory having both a ``.git/`` child directory and a ``.env`` file. Parameters ---------- cur...
1,159
en
0.647168
# Copyright 2020 Google Research. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law...
efficientdet/aug/autoaugment.py
66,666
Applies augmentation_func to the subsection of image indicated by bbox. Args: image: 3D uint8 Tensor. bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x) of type float that represents the normalized coordinates between 0 and 1. augmentation_func: Augmentation function that will be applied to the...
27,376
en
0.829549
""" mbed SDK Copyright (c) 2011-2015 ARM Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in wr...
packages/mbed-host-tests/mbed_host_tests/host_tests_plugins/module_copy_silabs.py
761
mbed SDK Copyright (c) 2011-2015 ARM Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writin...
624
en
0.801932
""" Tests for the linecache module """ import linecache import unittest import os.path from test import support FILENAME = linecache.__file__ INVALID_NAME = '!@$)(!@#_1' EMPTY = '' TESTS = 'inspect_fodder inspect_fodder2 mapping_tests' TESTS = TESTS.split() TEST_PATH = os.path.dirname(__file__) MODULES = "linecache ...
Src/StdLib/Lib/test/test_linecache.py
4,691
Tests for the linecache module No ending newline Bad values for line number should return an empty string Float values currently raise TypeError, should it? Bad filenames should return an empty string Check whether lines correspond to those from file iteration Check module loading Check that bogus data isn't returne...
605
en
0.719135
import torch import os import os.path import shutil import numpy as np import soundfile as sf from pathlib import PurePath from torch import nn from torch.utils.data import DataLoader, random_split from asteroid.data import TimitDataset from asteroid.data.utils import CachedWavSet, RandomMixtureSet, FixedMixtureSet fr...
notebooks/train_tasnet.py
4,814
could be more on cluster, test if larger one work as agreed upon average track len in TIMIT magic number :) fixed SNRs for validation set Reproducibility - fix all random seeds Load noises, resample and save into the memory Load clean data and split it into train and val Training data mixes crops randomly on the fly wi...
1,298
en
0.852977
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import logging import datetime import sqlalchemy as sa from random import randint from flask import Blueprint from f...
relengapi/blueprints/archiver/__init__.py
9,256
delete any tracker task if it is older than the time a task can live for. A generic getter for retrieving an s3 location of an archive where the archive is based off a src_url. sub-dir: hg.mozilla.org supports archives of sub directories within a repository. This flexibility allows for creating archives of only a port...
2,972
en
0.854273
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
tensor2tensor/bin/make_tf_configs.py
2,369
Output command line arguments and json-encoded TF_CONFIGs. Usage: `make_tf_configs.py --workers="server1:1234" --ps="server3:2134,server4:2334"` Outputs 1 line per job to stdout, first the workers, then the parameter servers. Each line has the TF_CONFIG, then a tab, then the command line flags for that job. If ther...
948
en
0.795617
# coding: utf-8 from __future__ import unicode_literals import re import base64 from .common import InfoExtractor from ..compat import ( compat_urlparse, compat_parse_qs, ) from ..utils import ( clean_html, ExtractorError, int_or_none, unsmuggle_url, smuggle_url, ) class KalturaIE(InfoEx...
youtube_dl/extractor/kaltura.py
14,728
coding: utf-8 See https://github.com/kaltura/server/blob/master/plugins/content/caption/base/lib/model/enums/CaptionType.php video with subtitles video with ttml subtitles (no fileExt) Embed codes: https://knowledge.kaltura.com/embedding-kaltura-media-players-your-site JSON, 2 = XML, 3 = PHP Unfortunately, data returne...
903
en
0.776964
from conans import ConanFile, CMake, tools import os class TestPackageConan(ConanFile): settings = "os", "arch", "compiler", "build_type" generators = "cmake", "cmake_find_package_multi" def build_requirements(self): if self.settings.os == "Macos" and self.settings.arch == "armv8": # ...
recipes/librasterlite/all/test_package/conanfile.py
1,008
Workaround for CMake bug with error message: Attempting to use @rpath without CMAKE_SHARED_LIBRARY_RUNTIME_C_FLAG being set. This could be because you are using a Mac OS X version less than 10.5 or because CMake's platform configuration is corrupt. FIXME: Remove once CMake on macOS/M1 CI runners is upgraded.
309
en
0.898917
""" Tests for grph.py """ import os import platform import random import re import string from subprocess import getstatusoutput PRG = './grph.py' RUN = f'python {PRG}' if platform.system() == 'Windows' else PRG SAMPLE1 = './tests/inputs/1.fa' SAMPLE2 = './tests/inputs/2.fa' SAMPLE3 = './tests/inputs/3.fa' # ------...
09_grph/tests/grph_test.py
2,997
Generate a random string Run with args Runs OK Runs OK Runs OK Runs OK Runs OK Runs OK Runs OK Runs OK Runs OK Dies on bad file Dies on bad k Program exists Usage Tests for grph.py -------------------------------------------------- -------------------------------------------------- --------------------...
962
en
0.250365
import six import pytest from pymemcache.test.utils import MockMemcacheClient @pytest.mark.unit() def test_get_set(): client = MockMemcacheClient() assert client.get(b"hello") is None client.set(b"hello", 12) assert client.get(b"hello") == 12 @pytest.mark.unit() def test_get_set_unicide_key(): ...
pymemcache/test/test_utils.py
2,650
This is the value of msgpack.packb('non_ascii') Convert keys into bytes These are the values of calling msgpack.packb() on '1', '2', and '3' Convert keys into bytes
164
en
0.747367
# Copyright 2021 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
tfx/orchestration/experimental/core/testing/test_async_pipeline.py
2,933
Creates an async pipeline for testing. Async pipeline for testing. Copyright 2021 Google LLC. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses...
874
en
0.809199
'''Escreva um programa que receba um número inteiro na entrada e verifique se o número recebido possui ao menos um dígito com um dígito adjacente igual a ele. Caso exista, imprima "sim"; se não existir, imprima "não". ''' num = int(input('Digite um número inteiro: ')) alg1 = num % 10 while num > 0: num = num //...
Exercicios/digitos_adjacentes.py
524
Escreva um programa que receba um número inteiro na entrada e verifique se o número recebido possui ao menos um dígito com um dígito adjacente igual a ele. Caso exista, imprima "sim"; se não existir, imprima "não".
216
pt
0.979442
#from fake_useragent import UserAgent from selenium import webdriver from selenium.webdriver.common.by import By import time import os # 订阅,0关闭 dingyue = 1 # 短信,0关闭 duanxin = 1 # 设置翻页范围 start_page = 1 end_page = 1 def main(): # 当前版本仅支持订阅一个手机号码 _list = [ ['18888888888', '张三'] ] ...
main/JW/main.py
16,048
from fake_useragent import UserAgent 订阅,0关闭 短信,0关闭 设置翻页范围 当前版本仅支持订阅一个手机号码 option.add_argument('--disable-gpu')citys = ['xm'] 遍历城市列表 打开page页 从page页获取楼盘链接存入houses[] 逐个打开楼盘页并处理 打开楼盘页 删除遮挡元素 操作 发送地址给手机 输入电话 点击领取 关闭窗口 降价通知 输入电话 点击提交 关闭窗口 组团砍价 输入电话 点击提交 关闭窗口 新信息通知 输入电话 点击提交 关闭窗口 开盘通知我 输入电话 点击领取 关闭窗口 新动态通知我 输入电话 点击提交 关闭...
322
zh
0.961164
#!/usr/bin/env python from django.urls import reverse_lazy from django.shortcuts import Http404 from django.utils.translation import ugettext as _ from vanilla import ListView, CreateView, DetailView, UpdateView, DeleteView, TemplateView from .forms import ArticleForm, ArticleSearchForm from .models import Article, Fol...
pergamum/bibloi/views.py
2,543
!/usr/bin/env pythonclass ArticleCreate(CreateView): model = Article form_class = ArticleForm success_url = reverse_lazy('bibloi:list')class ArticleUpdate(UpdateView): model = Article form_class = ArticleForm success_url = reverse_lazy('bibloi:list')class ArticleDelete(DeleteView): model = Article ...
364
en
0.477143
""" Get absolute URLs for static assets. """ from urllib.parse import ParseResult, urlparse, urlunparse from django import template from django.templatetags.static import StaticNode from django.urls import reverse register = template.Library() class AbstaticNode(StaticNode): """ {% abstatic %} is like Djan...
src/CreeDictionary/CreeDictionary/templatetags/url_extras.py
2,553
{% abstatic %} is like Django's {% static %} tag, but always returns an absolute URI. Given a relative path to a static asset, return the absolute path to the asset. Derived from: https://github.com/django/django/blob/635d53a86a36cde7866b9caefeb64d809e6bfcd9/django/templatetags/static.py#L143-L159 Returns True if the ...
1,467
en
0.769448
""" hubspot engagements api """ from hubspot3.base import BaseClient from hubspot3.utils import get_log from typing import Dict, List ENGAGEMENTS_API_VERSION = "1" class EngagementsClient(BaseClient): """ The hubspot3 Engagements client uses the _make_request method to call the API for data. It returns...
hubspot3/engagements.py
3,513
The hubspot3 Engagements client uses the _make_request method to call the API for data. It returns a python object translated from the json returned get full subpath Get a HubSpot engagement. get all engagements get all engagements associated with the given object :param object_type: type of object to get associations...
601
en
0.74581
# coding: utf-8 """ Copyright 2017 Square, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable la...
squareconnect/models/v1_list_items_request.py
3,533
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. Returns true if both objects are equal V1ListItemsRequest - a model defined in Swagger :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict att...
1,616
en
0.793423
# coding: utf-8 """ Swaggy Jenkins Jenkins API clients generated from Swagger / Open API specification # noqa: E501 The version of the OpenAPI document: 1.1.2-pre.0 Contact: blah@cliffano.com Generated by: https://openapi-generator.tech """ from __future__ import absolute_import import unitte...
clients/python-legacy/generated/test/test_queue.py
9,671
Queue unit test stubs Test Queue include_option is a boolean, when False only required params are included, when True both required and optional params are included Test Queue Swaggy Jenkins Jenkins API clients generated from Swagger / Open API specification # noqa: E501 The version of the OpenAPI document: 1.1.2-p...
480
en
0.709678
# Code generated by lark_sdk_gen. DO NOT EDIT. import typing from pylark.lark_request import Response from pylark.api_service_hire_job_get import ( GetHireJobReq, GetHireJobResp, _gen_get_hire_job_req, ) from pylark.api_service_hire_job_manager_get import ( GetHireJobManagerReq, GetHireJobManagerR...
pylark/api_service_hire.py
10,069
Code generated by lark_sdk_gen. DO NOT EDIT.
44
en
0.515403
"""Run experiment. This module is intended to be run as a script: $ python src/experiment.py """ import os import pandas as pd from bert import BERT from constants import LANGUAGES, MASK, MISSING from filenames import CLOZE_DIR, EXPERIMENTS_DIR, FEATURES_DIR from utils import refresh ENGLISH_MODEL = "bert-base...
src/experiment.py
5,693
Return index of the masked word in `sentence` using `bert`'s' tokenizer. We use this function to calculate the linear distance between the target and controller as BERT sees it. Parameters ---------- sentence : str Returns ------- int Run the experiment for `language`. Parameters ---------- language : str force_mul...
1,910
en
0.84095
# Python Object Oriented Programming import datetime class Employee: num_of_emps = 0 # Class Variable raise_amount = 1.02 # Class Variable def __init__(self, FirstName, LastName, salary): self.FirstName = FirstName self.LastName = LastName self.salary = int(salary) self.em...
Object Oriented Programming/5 - Special Methods/index.py
2,539
Python Object Oriented Programming Class Variable Class Variable Class Variable
79
en
0.522726
# -*- coding: utf-8 -*- """ Key classification using multiclass Support Vector Machine (SVM) reference: Date: Jun 05, 2017 @author: Thuong Tran @Library: scikit-learn """ import os, glob, random import numpy as np from pandas import DataFrame from sklearn.feature_extraction.text import CountVectorizer, TfidfTransf...
TrainValue/multiclass_svm.py
5,500
This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. Key classification using multiclass Support Vector Machine (SVM) reference: Date: Jun 05, 2017 @author: Thuong Tran @Library: scikit-learn -*- coding: utf-8 -*- folders = [d for d in os.listdir(data_dir) ...
1,227
en
0.491376
import math import collections from gym_jsbsim import utils class BoundedProperty(collections.namedtuple('BoundedProperty', ['name', 'description', 'min', 'max'])): def get_legal_name(self): return utils.AttributeFormatter.translate(self.name) class Property(collections.namedtuple('Property', ['name', '...
gym_jsbsim/properties.py
6,721
Returns difference between two coords as (delta_lat, delta_long) Return a GeodeticPosition object with lat and lon from simulation Calculate heading in degrees of vector from origin Determines heading in degrees of course between self and destination position and attitude velocities accelerations controls state e...
373
en
0.887022
import re import os import time import tweepy import neologdn import emoji TRAINFILE = "./data/train.tsv" DEVFILE = "./data/dev.tsv" TESTFILE = "./data/test.tsv" dup = [] if os.path.exists(TRAINFILE): with open(TRAINFILE) as f: dup += f.readlines() if os.path.exists(DEVFILE): with open(DEVFILE) as f: ...
collect_tweet.py
4,746
is bot include URL is hashtag reply to multi user too long text = re.sub(r"\d+", "0", tmp) is not reply filter append lookup id collect 100 tweets is same user
159
en
0.917604
""" WSGI config for kubeoperator project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_...
core/apps/kubeoperator/wsgi.py
401
WSGI config for kubeoperator project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/
218
en
0.776478
"""The tests for the MQTT switch platform.""" import json from unittest.mock import ANY from asynctest import patch import pytest from homeassistant.components import mqtt, switch from homeassistant.components.mqtt.discovery import async_start from homeassistant.const import ( ATTR_ASSUMED_STATE, STATE_OFF, STATE...
tests/components/mqtt/test_switch.py
20,076
Initialize components. The tests for the MQTT switch platform. Change json_attributes_topic Verify we are no longer subscribing to the old topic Verify we are subscribing to the new topic all switches group is 1, unique id created is 1
237
en
0.816256
import torch from utils.distmat import compute_distmat def init_feedback_indices(q, g, device=None): return torch.zeros((q, g), dtype=torch.bool, device=device) def init_feedback_indices_qg(q, g, positive=False, device=None): indices = torch.zeros(q, q + g, dtype=torch.bool, device=device) if positive:...
hitl/feedback.py
2,870
Update positive_indices, negative_indices with one round of feedback. Provide feedback for top-ranked gallery. Note that distmat is corrupted if inplace=True. :param distmat: q x g Tensor (adjusted query to gallery) :param q_pids: q :param g_pids: g :param positive_indices: q x g :param negative_indices: q x g :return...
532
en
0.651046
#Licenced under MIT License #charset = "utf-8" #Language = "Python3" #Bot Framework = "python-telegram-bot" #The Code is without Proxy, Actual code contains Proxy #Proxy should be used is of the type SOCKS5 #Special thanks to cyberboySumanjay #The bot will work till you press ctrl+c in the terminal or command line., #...
mirror.py
2,906
Licenced under MIT Licensecharset = "utf-8"Language = "Python3"Bot Framework = "python-telegram-bot"The Code is without Proxy, Actual code contains ProxyProxy should be used is of the type SOCKS5Special thanks to cyberboySumanjayThe bot will work till you press ctrl+c in the terminal or command line.,import the require...
684
en
0.529391
# -*- coding: utf-8 -*- # This file is part of the Ingram Micro Cloud Blue Connect connect-cli. # Copyright (c) 2021 Ingram Micro. All Rights Reserved. import os import sys def unimport(): for m in ('connect.cli.plugins.play.commands', 'connect.cli.ccli'): if m in sys.modules: del sys.modules...
tests/plugins/play/test_play_commands.py
967
-*- coding: utf-8 -*- This file is part of the Ingram Micro Cloud Blue Connect connect-cli. Copyright (c) 2021 Ingram Micro. All Rights Reserved.
145
en
0.824047
import json from urllib import urlencode from corehq.apps.registration.utils import create_30_day_trial from dimagi.utils.couch import CriticalSection from dimagi.utils.couch.resource_conflict import retry_resource from django.contrib.auth.decorators import login_required from django.core.urlresolvers import reverse f...
corehq/apps/appstore/views.py
14,299
json.dumps(persistent_params) sign new project up for trial get facets
70
en
0.595297
#! /usr/bin/env python # coding=utf-8 # Copyright (c) 2019 Uber Technologies, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unles...
ludwig/features/image_feature.py
17,799
Helper method to determine the height, width and number of channels for preprocessing the image data. This is achieved by looking at the parameters provided by the user. When there are some missing parameters, we fall back on to the first image in the dataset. The assumption being that all the images in the data are ex...
2,803
en
0.839745
#!/usr/bin/env python # -*- coding: utf-8 -*- # Author: David McCue import sqlite3, re, os from bottle import route, run, debug, template, request, static_file, error, response db_filename=os.path.dirname(os.path.realpath(__file__)) + '/db/kickstarter.db' # Validate currency values def valid_amount(amount): amoun...
server.py
4,742
!/usr/bin/env python -*- coding: utf-8 -*- Author: David McCue Validate currency values Validate names Calculate luhn checksum Credit: wikipedia Validate credit card retrieve project by name add project add transaction Validate inputs Check credit card is unique to this user name Get project id from name retrieve backe...
340
en
0.630326
from logs import logDecorator as lD import jsonref, sqlite3 config = jsonref.load(open('../config/config.json')) logBase = config['logging']['logBase'] + '.databaseIO.sqLiteIO' @lD.log(logBase + '.getAllData') def getAllData(logger, query, values=None, dbName=None): '''query data from the database ...
src/lib/databaseIO/sqLiteIO.py
11,830
query data from the database Query the data over here. If there is a problem with the data, it is going to return the value of ``None``, and log the error. Your program needs to check whether there was an error with the query by checking for a ``None`` return value Parameters ---------- logger : {logging.logger} ...
4,828
en
0.721411
#!\usr\bin\python from numpy import array from scipy.special import erf from scipy.optimize import minimize from math import pi, sin, cos, exp, sqrt #import dicom line_array = [] ## global def read_line (file_name ): with open( file_name ) as f: for line in f: line_array.append( [float( lin...
minimize/retic_xmm_2gauss/2minimize_4mv.py
1,736
!\usr\bin\pythonimport dicom global global 0 1 2 3 4 5 6 b is np.array of these parameters: [sigma_1, sigma_2, w_1, x_sh, bkg, B, b] x in mm [sigma_1, sigma_2, w_1, x_sh, bkg, B, b ] initial values for minimize print out the whole line x in milimiters
300
en
0.488345
import pandas as pd import numpy as np import scipy as sp from scipy.optimize import linprog, minimize, NonlinearConstraint from .pdf_quantile_functions import pdf_quantile_builder from .support import diffMatMetalog, pdfMetalog, quantileMetalog, newtons_method_metalog import time import warnings def a_vector_OLS_an...
pymetalog/a_vector.py
15,097
TODO: write docstring TODO: write docstring Main workhorse function of pymetalog package. Called during metalog.__init__ method call. Args: m_dict (:obj:`dict` with keys ['params', 'dataValues', 'Y']): Initialized output_dict variable from metalog class. - m_dict['params']: (:obj:`dict` wit...
6,771
en
0.562292
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modif...
artifacts/old_dataset_versions/minimal_commits/qiskit-terra/qiskit-terra#2704/after/test_basic_scheduler.py
14,036
Scheduling tests. Test a schedule that was recommended by David McKay :D Test that ALAP always acts as though there is a final global barrier. Test ALAP scheduling. Test that the ALAP pass properly respects busy resources when backwards scheduling. For instance, a CX on 0 and 1 followed by an X on only 1 must respect ...
2,136
en
0.933343
""" >>> sd = SliceDump() >>> sd[1] 1 >>> sd[2:5] slice(2, 5, None) >>> sd[:2] slice(None, 2, None) >>> sd[7:] slice(7, None, None) >>> sd[:] slice(None, None, None) >>> sd[1:9:3] slice(1, 9, 3) >>> sd[1:9:3, 2:3] (slice(1, 9, 3), slice(2, 3, None)) >>> s ...
attic/sequences/slice_dump.py
548
>>> sd = SliceDump() >>> sd[1] 1 >>> sd[2:5] slice(2, 5, None) >>> sd[:2] slice(None, 2, None) >>> sd[7:] slice(7, None, None) >>> sd[:] slice(None, None, None) >>> sd[1:9:3] slice(1, 9, 3) >>> sd[1:9:3, 2:3] (slice(1, 9, 3), slice(2, 3, None)) >>> s = sd[1:9:3] >>> s.indices(20) (1, 9, 3) >>> s.indices(5) (1, 5, 3) >>...
371
en
0.475071
""" utility functions for breaking down a given block of text into it's component syntactic parts. """ import nltk from nltk.tokenize import RegexpTokenizer from . import syllables_en TOKENIZER = RegexpTokenizer('(?u)\W+|\$[\d\.]+|\S+') SPECIAL_CHARS = ['.', ',', '!', '?'] def get_char_count(words): characters...
opm/readability/utils.py
2,162
utility functions for breaking down a given block of text into it's component syntactic parts. This method must be enhanced. At the moment it onlyconsiders the number of syllables in a word.This often results in that too many complex words are detected.Checking proper nouns. If a word starts with a capital letterand i...
390
en
0.911614
import requests import json from simplegist.mygist import Mygist from simplegist.do import Do from comments import Comments try: from simplegist.config import USERNAME, API_TOKEN, BASE_URL, GIST_URL except: pass class Simplegist: """ Gist Base Class This class is to used to instantiate the wrapper and authentica...
simplegist/simplegist.py
2,459
Gist Base Class This class is to used to instantiate the wrapper and authenticate. Authenticate with providing Github Username and API-Token to use it for all future API requests Save our username and api_token (If given) for later use. Set header information in every request.
281
en
0.776873
from pathlib import Path from urllib.parse import urljoin, urlparse, unquote def _get_url_file_name(url): path = urlparse(url).path try: path = unquote(path) except (TypeError, ValueError): pass return Path(path).name def dav_index(context, data): """List files in a WebDAV direct...
memorious/operations/webdav.py
1,167
List files in a WebDAV directory. This is made to work with ownCloud/nextCloud, but some rumor has it they are "standards compliant" and it should thus work for other DAV servers.
181
en
0.967719
""" Name : c9_01_optimize.py Book : Python for Finance (2nd ed.) Publisher: Packt Publishing Ltd. Author : Yuxing Yan Date : 6/6/2017 email : yany@canisius.edu paulyxy@hotmail.com """ from scipy.optimize import minimize def myFunction(x): return (3.2+5*x**2) x0=100 res =...
Chapter09/c9_01_optimize.py
402
Name : c9_01_optimize.py Book : Python for Finance (2nd ed.) Publisher: Packt Publishing Ltd. Author : Yuxing Yan Date : 6/6/2017 email : yany@canisius.edu paulyxy@hotmail.com
204
en
0.519011
# coding=utf-8 # Copyright 2020 The Real-World RL Suite Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
realworldrl_suite/utils/evaluators_test.py
3,096
Tests for evaluators. coding=utf-8 Copyright 2020 The Real-World RL Suite Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by ...
716
en
0.844294
# Copyright 2020 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
src/transformers/data/data_collator.py
36,353
Data collator used for language modeling. Inputs are dynamically padded to the maximum length of a batch if they are not all of the same length. Args: tokenizer (:class:`~transformers.PreTrainedTokenizer` or :class:`~transformers.PreTrainedTokenizerFast`): The tokenizer used for encoding the data. mlm ...
14,317
en
0.767689
# -*- coding: utf-8 -*- ########################################################################### # Copyright (c), The AiiDA team. All rights reserved. # # This file is part of the AiiDA code. # # ...
tests/cmdline/commands/test_group.py
11,059
Tests for the `verdi group` command. Create runner object to run tests. Test `verdi group remove-nodes` command. Test `verdi group copy` command. Test user is prompted to continue if destination group exists and is not empty Test `verdi group create` command. Test `verdi group delete` command. Test `verdi group descrip...
2,163
en
0.833617
''' This module provides little helper functions that interpret the Handle Server's response codes and the HTTP status codes. All helpers functions test one possible outcome and return True or False. Author: Merret Buurman (DKRZ), 2015-2016 ''' import json from b2handle.compatibility_helper import decode...
b2handle/hsresponses.py
2,540
This module provides little helper functions that interpret the Handle Server's response codes and the HTTP status codes. All helpers functions test one possible outcome and return True or False. Author: Merret Buurman (DKRZ), 2015-2016 need to put 'OR' because the HS responseCode is not always received!...
350
en
0.719631
""" auth.blueprints ~~~~~~~~~~~~~~~ """ from .simpleidp import blueprint as idpblueprint
auth/blueprints/__init__.py
98
auth.blueprints ~~~~~~~~~~~~~~~
31
en
0.262702
# -*- coding: utf-8 -*- # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "...
python/pyarrow/tests/test_convert_builtin.py
5,264
-*- coding: utf-8 -*- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you...
843
en
0.871013
# Most of this code is stolen from myself, but it's an app about pirating so whatev import os import sys import time import datetime import subprocess import pycurl import spotipy import spotipy.util from StringIO import StringIO from collections import deque import sys # If this seems like overkill, that's becaus...
pirate.py
12,633
Most of this code is stolen from myself, but it's an app about pirating so whatev If this seems like overkill, that's because it is. I wrote this get_args code for general use, this function is not specific to this this is just the name of the program single multi-character flag it makes my life easier if they do this ...
1,637
en
0.851483
import time import torch import torch.nn as nn import torch.nn.parallel import torch.utils.data from torch import optim from torch.utils import data from tqdm import tqdm from networks import LATENT_CODE_SIZE, device # from train_autoencoder import SDFSampleDataset, save_checkpoint, SIGMA class SDFNet(nn.Module): ...
networks/sdf_net_decoder.py
4,295
input: [B, N, latent_size + point_dim] :param latent_codes: [B, N, LATENT_CODE_DIM] :param points: [B, N, 3] :return: sdf_pred: [B, N] from train_autoencoder import SDFSampleDataset, save_checkpoint, SIGMA the decoder should only have xyz information, without sdf values if __name__ == '__main__': experiment = '5_...
2,227
en
0.453643
''' Copyright 2022 Airbus SAS Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software dis...
climateeconomics/tests/_l1_test_gradient_services_discipline.py
8,163
Copyright 2022 Airbus SAS Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distrib...
851
en
0.811302
import logging import json from http import HTTPStatus from typing import Any, Dict # noqa: F401 from flask import Response, jsonify, make_response, request from flask import current_app as app from flask.blueprints import Blueprint from amundsen_application.log.action_log import action_logging from amundsen_appli...
amundsen_application/api/search/v0.py
7,294
Call the search service endpoint and return matching results Search service logic defined here: https://github.com/lyft/amundsensearchlibrary/blob/master/search_service/api/table.py :return: a json output containing search results array as 'results' Call the search service endpoint and return matching results Search s...
843
en
0.691593
"""Python wrappers around TensorFlow ops. This file is MACHINE GENERATED! Do not edit. Original C++ source file: gen_dataset_ops.cc """ import collections as _collections import six as _six from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow from tensorflow.python.eager import context as _context f...
venv/lib/python3.7/site-packages/tensorflow_core/contrib/ignite/python/ops/gen_dataset_ops.py
8,002
IgniteDataset that allows to get data from Apache Ignite. Apache Ignite is a memory-centric distributed database, caching, and processing platform for transactional, analytical, and streaming workloads, delivering in-memory speeds at petabyte scale. This contrib package contains an integration between Apache Ignite an...
2,298
en
0.655406