code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def check_hash(pwhash: str, password: str) -> bool: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return bcrypt.checkpw(password.encode(), pwhash.encode()) <NEW_LINE> <DEDENT> except ValueError as ex: <NEW_LINE> <INDENT> return False | Validate hased password | 625941f2c4546d3d9de7301f |
def search(self, category, name, page): <NEW_LINE> <INDENT> category_Q = Q() <NEW_LINE> if category: <NEW_LINE> <INDENT> category_Q = Q(category=category) <NEW_LINE> <DEDENT> name_Q = Q() <NEW_LINE> if name: <NEW_LINE> <INDENT> name_Q = Q(name__contains=name) <NEW_LINE> <DEDENT> start = page*self.page_size <NEW_LINE> e... | Search clothings | 625941f28da39b475bd65561 |
def _event_pull_request_closed(self, body): <NEW_LINE> <INDENT> event, data = self._event_base(body) <NEW_LINE> event.action = 'closed' <NEW_LINE> return event | Handles pull request closed event | 625941f22c8b7c6e89b35da1 |
def set_transform_event(self, event): <NEW_LINE> <INDENT> if event == self.transform_event: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.transform_event = event <NEW_LINE> if self.transform_event_responder: <NEW_LINE> <INDENT> renpy.display.render.redraw(self, 0) | Sets the transform event of this displayable to event. | 625941f25fc7496912cc3f62 |
def read_icd_diagnoses_table(mimic3_path, use_db=False, conn_info=None): <NEW_LINE> <INDENT> if use_db == False: <NEW_LINE> <INDENT> codes = DataFrame.from_csv(os.path.join(mimic3_path, 'D_ICD_DIAGNOSES.csv')) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> codes = query("SELECT * FROM D_ICD_DIAGNOSES", conn_info) <NEW_L... | :param mimic3_path path file to csv files
:param use_db Default False, if true, uses sql connection
:param conn_info Default None, only useful if
use_db was set to True. Used to instantiate a connection to db
:return processed DataFrame | 625941f221a7993f00bc82e0 |
def __init__(self, params, train): <NEW_LINE> <INDENT> self.train = train <NEW_LINE> self.params = params <NEW_LINE> self.embedding_softmax_layer = embedding_layer.EmbeddingSharedWeights( params["vocab_size"], params["hidden_size"], method="matmul" if params["tpu"] else "gather") <NEW_LINE> self.segment_embedding_layer... | Initialize layers to build Transformer model.
Args:
params: hyperparameter object defining layer sizes, dropout values, etc.
train: boolean indicating whether the model is in training mode. Used to
determine if dropout layers should be added. | 625941f20a366e3fb873ee05 |
def set_name(self, name): <NEW_LINE> <INDENT> self.name = name | :param str name: | 625941f2097d151d1a22343b |
def __init__(self, showID, epSeason): <NEW_LINE> <INDENT> self.__showID = showID <NEW_LINE> self.__epSeason = epSeason <NEW_LINE> self.__episodeJSON = None | Constructor for FlaskTvEpisodes class
Arguments:
showID: ID for show from CLI
epSeason: season number, from CLI, used to get episodes from
Returns: creates FlaskTvEpisodes class object | 625941f23617ad0b5ed684dc |
def pl_1_create(self): <NEW_LINE> <INDENT> self.api.create_playlist('test playlist') <NEW_LINE> self.playlists = self.api.get_all_playlist_ids()['user'] | Create a playlist. | 625941f23cc13d1c6d3c795c |
def generate_file_path(filename): <NEW_LINE> <INDENT> if getattr(sys, 'frozen', False): <NEW_LINE> <INDENT> datadir = os.path.dirname(sys.executable) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> datadir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) + '\\data\\' <NEW_LINE> <DEDENT> return ... | Returns a valid filepath, if file 'filename' exists. | 625941f2a17c0f6771cbe634 |
def make_random_prime_and_g(min=151, max=1000000): <NEW_LINE> <INDENT> count = 0 <NEW_LINE> count_match = random.randint(1, 100) <NEW_LINE> for prime in range(min, max, 2): <NEW_LINE> <INDENT> if check_prime(prime): <NEW_LINE> <INDENT> if check_prime(prime*2+1): <NEW_LINE> <INDENT> count += 1 <NEW_LINE> if count == cou... | 랜덤한 안전 소수 구해보기
min에서 max까지 min기준으로 x번째 소피제르맹 소수(이걸로 안전소수 리턴)
min을 반드시 홀수로 | 625941f2796e427e537b0bb0 |
def is_palindrome(i): <NEW_LINE> <INDENT> return str(i) == str(i)[::-1] | :param i: String or integer
:return: whether i is an palindrome | 625941f2b5575c28eb68e5eb |
def _save_csv_explicit(data, csvname): <NEW_LINE> <INDENT> with open(csvname, 'w') as f: <NEW_LINE> <INDENT> for r in data: <NEW_LINE> <INDENT> p = ",".join(["%s=%s" % (k,v) for k,v in r[1].items()]) <NEW_LINE> f.write(",".join([r[0], p, ",".join(r[2])]) + "\n") | export the CFS in CSV2 format (explicit).
example:
PV,machine=xxx,elemIndex=xxx,elemPosition=xxx,elemName=xxx,elemHandle=xxx,elemField=xxx,elemType=xxx,tag1,tag2 | 625941f2462c4b4f79d1dcb5 |
def plot_image(X, y, index): <NEW_LINE> <INDENT> plt.imshow(X[index]) <NEW_LINE> plt.axis('off') <NEW_LINE> plt.show() | Visualize an example image in the dataset. | 625941f20fa83653e465759c |
def save_screenshot(driver: Remote, screenshot_name: str): <NEW_LINE> <INDENT> logger.info('Saving screenshot') <NEW_LINE> os.makedirs(SCREENSHOTS_PATH, exist_ok=True) <NEW_LINE> try: <NEW_LINE> <INDENT> driver.save_screenshot(os.path.join(SCREENSHOTS_PATH, screenshot_name)) <NEW_LINE> <DEDENT> except WebDriverExceptio... | Save screenshot from the browser
:param driver: WebDriver object
:param screenshot_name: filename of the screenshot without path | 625941f22ae34c7f2600d716 |
def conv_ast_to_sym(self, math_ast): <NEW_LINE> <INDENT> if type(math_ast) is c_ast.ID: <NEW_LINE> <INDENT> return symbol_pos_int(math_ast.name) <NEW_LINE> <DEDENT> elif type(math_ast) is c_ast.Constant: <NEW_LINE> <INDENT> return sympy.Integer(math_ast.value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> op = { '*': o... | Convert mathematical expressions to a sympy representation.
May only contain paranthesis, addition, subtraction and multiplication from AST. | 625941f2a934411ee3751c7b |
def __init__(self, url, token, timeout = 30): <NEW_LINE> <INDENT> self.url = url <NEW_LINE> self.token = token <NEW_LINE> self.timeout = timeout <NEW_LINE> user_agent_string = 'sentimo-webservice-python-sdk-' <NEW_LINE> user_agent_string += ' ' + platform.system() <NEW_LINE> user_agent_string += ' ' + platform.release(... | Construct a new client for Sentimo Service
:param url URL path of service
:param token certified PID of target service
:param timeout HTTP timeout value | 625941f2cc40096d61595f33 |
def run(self): <NEW_LINE> <INDENT> logging.getLogger("conftool").setLevel(logging.WARNING) <NEW_LINE> for host in self.hosts.split(1): <NEW_LINE> <INDENT> self.upgrade_host(host) | Required by the Spicerack API. | 625941f27cff6e4e81117f6b |
def testSimpleIntegrate(self): <NEW_LINE> <INDENT> self.setupTransfer() <NEW_LINE> inside = localDirectory(self.source.client_root, "inside") <NEW_LINE> inside_file1 = os.path.join(inside, "inside_file1") <NEW_LINE> create_file(inside_file1, "Test content") <NEW_LINE> self.source.p4cmd('add', inside_file1) <NEW_LINE> s... | Simple integration options - inside client workspace view | 625941f21d351010ab856100 |
def Hist(hist, **options): <NEW_LINE> <INDENT> xs, ys = hist.Render() <NEW_LINE> try: <NEW_LINE> <INDENT> xs[0] - xs[0] <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> labels = [str(x) for x in xs] <NEW_LINE> xs = np.arange(len(xs)) <NEW_LINE> pyplot.xticks(xs+0.5, labels) <NEW_LINE> <DEDENT> if 'width' not i... | Plots a Pmf or Hist with a bar plot.
The default width of the bars is based on the minimum difference
between values in the Hist. If that's too small, you can override
it by providing a width keyword argument, in the same units
as the values.
Args:
hist: Hist or Pmf object
options: keyword args passed to pyplot.... | 625941f27b180e01f3dc4dd5 |
def setUp(self): <NEW_LINE> <INDENT> super().setUp() <NEW_LINE> DataGen.create_defaults() | Runs before every test and clears relevant tables | 625941f2046cf37aa974d327 |
def get_filenames(folder): <NEW_LINE> <INDENT> folder = Path(folder) <NEW_LINE> sorter = lambda p: int(p.stem.split("_")[2]) <NEW_LINE> data_filenames1 = sorted(folder.glob("Spectrometer_1105161U2_*_pix.txt"), key=sorter) <NEW_LINE> data_filenames2 = sorted(folder.glob("Spectrometer_1105162U2_*_pix.txt"), key=sorter) <... | Get the filenames for both spectrometers from a given folder. | 625941f2bde94217f36833d1 |
def visit_unary(self, expr): <NEW_LINE> <INDENT> self.resolve(expr.right) | Visits a unary node | 625941f2ab23a570cc25076d |
def addBoldTag(self, s, dict): <NEW_LINE> <INDENT> start = end = -1 <NEW_LINE> ans = "" <NEW_LINE> for i, ch in enumerate(s): <NEW_LINE> <INDENT> maxlen = 0 <NEW_LINE> for word in dict: <NEW_LINE> <INDENT> if s[i:].startswith(word): <NEW_LINE> <INDENT> maxlen = max(maxlen, len(word)) <NEW_LINE> <DEDENT> <DEDENT> if max... | :type s: str
:type dict: List[str]
:rtype: str | 625941f229b78933be1e5c8a |
def save_users(): <NEW_LINE> <INDENT> with open('usuarios.json', 'w') as f: json.dump(usuarios, f, indent=2) | Guarda los usuarios en nuestro fichero de usuarios | 625941f3f9cc0f698b140bdc |
def draw_contours_and_centroids(self): <NEW_LINE> <INDENT> for contour, center in zip(self.contours, self.centroids): <NEW_LINE> <INDENT> cv2.drawContours(self.processed_frame, [contour], 0, (0, 255, 0), 3) <NEW_LINE> cv2.circle(self.processed_frame, center, 10, (255, 0, 0), -1) <NEW_LINE> if self.identifier_running: <... | Desenha os centroides e o contorno obtido para cada laranja. | 625941f2b545ff76a89143fb |
def initialise_network(X, y, layers=(2,)): <NEW_LINE> <INDENT> network = [2 * np.random.random((X.shape[1] + 1, layers[0])) - 1] <NEW_LINE> for layer, nodes in enumerate(layers): <NEW_LINE> <INDENT> if layer == len(layers) - 1: <NEW_LINE> <INDENT> network.append(2 * np.random.random((nodes + 1, y.shape[1])) - 1) <NEW_L... | Initialise a network with random weight vectors | 625941f3e64d504609d74e25 |
def setup_loaders(labels, meta_dict): <NEW_LINE> <INDENT> loaders = {} <NEW_LINE> loader_kwargs = {} <NEW_LINE> for k in labels.keys(): <NEW_LINE> <INDENT> k, l = loader_from_key(k) <NEW_LINE> if l is not None: <NEW_LINE> <INDENT> loaders[k] = l <NEW_LINE> <DEDENT> <DEDENT> meta_loaders = retrieve(meta_dict, "loaders",... | Creates a map of key -> function pairs, which can be used to postprocess
label values at each ``__getitem__`` call.
Loaders defined in :attr:`meta_dict` supersede those definde in the label
keys.
Parameters
----------
labels : dict(str, numpy.memmap)
Labels contain all load-easy dataset relevant data. If the key ... | 625941f3adb09d7d5db6cd71 |
def test_duplicate(self): <NEW_LINE> <INDENT> self.assertEqual(duplicate([1, 2, 3, 3, 4, 5]), [1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 5, 5]) <NEW_LINE> self.assertEqual(duplicate(['a', 'b', 'c', 'd']), ['a', 'a', 'b', 'b', 'c', 'c', 'd', 'd']) <NEW_LINE> self.assertRaises(TypeError, duplicate, {}) | Test duplicate (P14). | 625941f38e05c05ec3eea95f |
def forward(self, state): <NEW_LINE> <INDENT> x = F.relu(self.fc1(state)) <NEW_LINE> x = F.relu(self.fc2(x)) <NEW_LINE> return F.softmax(self.fc5(x), dim=0) | Build a network that maps state -> action values. | 625941f34f6381625f115021 |
@cli.command() <NEW_LINE> @click.option('--xmlrpc', is_flag=True, help="Enable xmlrpc (Default=True)") <NEW_LINE> @click.option('--no-xmlrpc', is_flag=True, help="Disable xmlrpc") <NEW_LINE> @click.option('--xmlrpc-host', default='0.0.0.0') <NEW_LINE> @click.option('--xmlrpc-port', envvar='FETCHER_XMLRPC_PORT', default... | Run Fetcher. | 625941f3be7bc26dc91cdbda |
def test_db(testapp, db): <NEW_LINE> <INDENT> with testapp.app_context(): <NEW_LINE> <INDENT> assert 'records_metadata' in db.metadata.tables <NEW_LINE> assert 'records_metadata_version' in db.metadata.tables <NEW_LINE> assert 'transaction' in db.metadata.tables <NEW_LINE> <DEDENT> schema = { 'type': 'object', 'propert... | Test database backend. | 625941f3460517430c39475a |
def unzip_files(self): <NEW_LINE> <INDENT> os.mkdir(self.temp_diretory) <NEW_LINE> zip = zipfile.ZipFile(self.filename) <NEW_LINE> try: <NEW_LINE> <INDENT> zip.extractall(self.temp_diretory) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> zip.close() | 将压缩文件解压到临时目录 | 625941f3ec188e330fd5ad78 |
def _tcp_client_setup(self): <NEW_LINE> <INDENT> self._tcp_client = Client('localhost', 80, self.pooling_period) <NEW_LINE> self._tcp_client_timer = QTimer() <NEW_LINE> self._tcp_client_timer.setInterval(int(self.pooling_period * 1e3)) <NEW_LINE> self._tcp_client_timer.timeout.connect(self._handle_tcp_client_request) <... | Инициализация TCP-клиента | 625941f3097d151d1a22343c |
def _begin_request(self, op, args): <NEW_LINE> <INDENT> self.request_container.operation = op <NEW_LINE> self.request_container.args = args <NEW_LINE> resource = self.request_container.resource <NEW_LINE> operation = self.request_container.operation <NEW_LINE> request = self.resource_provider.get_path(resource, oper... | callback for operations provider | 625941f37b180e01f3dc4dd6 |
def get_upstream_deps_for_components(components): <NEW_LINE> <INDENT> component_dependencies = defaultdict(set) <NEW_LINE> for configuration in CONFIGURATIONS_WITH_DEPENDENCIES: <NEW_LINE> <INDENT> logger.info("Looking for dependencies in '%s' configuration" % configuration) <NEW_LINE> cmd = ["./gradlew"] <NEW_LINE> fo... | Return the full list of local upstream dependencies of a component. | 625941f3a219f33f34628f47 |
def IsEnabled(self): <NEW_LINE> <INDENT> return self._status != "Disabled" | Returns ``True`` if this instance of :class:`ButtonInfo` is enabled for input,
``False`` otherwise. | 625941f37c178a314d6efa50 |
def close(self): <NEW_LINE> <INDENT> if self._device is not None: <NEW_LINE> <INDENT> self._device.close() <NEW_LINE> return <NEW_LINE> <DEDENT> print('Newport device is already closed') | Close connection to device. | 625941f382261d6c526aba8f |
def withoutNoBall(ballResult, ballNumber, strickPlayer, nonStrickPlayer): <NEW_LINE> <INDENT> if ballResult.isdigit(): <NEW_LINE> <INDENT> strickPlayer, nonStrickPlayer = legalDelivery(ballResult, ballNumber, strickPlayer, nonStrickPlayer) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> strickPlayer, nonStrickPlayer = il... | taking ballResult, ballNumber, strickPlayer, nonStrickPlayer and
working on runs/Wide/Wicket and return strick and non-strick | 625941f37b25080760e39a3b |
def _clear(confirm=True): <NEW_LINE> <INDENT> if not os.path.isdir(PGDATA): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if confirm and not click.confirm('Are you absolutely sure?'): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if os.path.isfile(os.path.join(PGDATA, 'postmaster.pid')): <NEW_LINE> <INDENT> click.sec... | Removes all files unker PGDATA. Backup is recommended! | 625941f326238365f5f0f45c |
def formfield_for_dbfield(self, db_field, **kwargs): <NEW_LINE> <INDENT> request = kwargs.pop("request", None) <NEW_LINE> if db_field.choices is not None: <NEW_LINE> <INDENT> return self.formfield_for_choice_field(db_field, request, **kwargs) <NEW_LINE> <DEDENT> if isinstance(db_field, ListField) and isinstance(db_fiel... | Hook for specifying the form Field instance for a given database Field
instance.
If kwargs are given, they're passed to the form Field's constructor. | 625941f324f1403a92601147 |
def render(opts, functions): <NEW_LINE> <INDENT> extra_dirs = [] <NEW_LINE> if 'render_dirs' in opts: <NEW_LINE> <INDENT> extra_dirs = opts['render_dirs'] <NEW_LINE> <DEDENT> module_dirs = [ os.path.join(salt_base_path, 'renderers'), ] + extra_dirs <NEW_LINE> load = Loader(module_dirs, opts) <NEW_LINE> pack = {'name': ... | Returns the render modules | 625941f3091ae3566866753a |
def prepare(self): <NEW_LINE> <INDENT> mob = self.get_cookie('mob', None) <NEW_LINE> if mob == '1': <NEW_LINE> <INDENT> self.templdir = 'mob/' <NEW_LINE> <DEDENT> elif mob == '0': <NEW_LINE> <INDENT> self.templdir = '' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> UA = self.request.headers.get('User-Agent', '').lower()... | Check mobile browser of not.
First check from cookie, if not found detect from User Agent. | 625941f3442bda511e8be9f5 |
def plot_simpel(x , y , title , ylabel , xlabel ,boolean, tekst , color): <NEW_LINE> <INDENT> fig , ax = plt.subplots() <NEW_LINE> ax = fig.add_axes([0,0,1,1]) <NEW_LINE> plt.plot(x, y , color = color) <NEW_LINE> plt.title(title) <NEW_LINE> plt.xlabel(xlabel) <NEW_LINE> plt.ylabel(ylabel) <NEW_LINE> if boolean == True:... | Simpel plot function with x, y, title, ylabel, xlabel, boolean for tekst box, tekst, color | 625941f37047854f462a19e9 |
def h5py_attr_completer(context, command): <NEW_LINE> <INDENT> base, attr = re_attr_match.split(command)[1:3] <NEW_LINE> base = base.strip() <NEW_LINE> try: <NEW_LINE> <INDENT> obj = _retrieve_obj(base, context) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> attrs = dir(obj) <NE... | Compute possible attr matches for nested dict-like objects | 625941f391f36d47f21acae0 |
def _build_runlist(self): <NEW_LINE> <INDENT> if self.seed is not None: <NEW_LINE> <INDENT> np.random.seed(self.seed) <NEW_LINE> <DEDENT> for i in moves.range(self.num_samples): <NEW_LINE> <INDENT> sample = [] <NEW_LINE> for key, meta in iteritems(self.get_desvar_metadata()): <NEW_LINE> <INDENT> nval = meta['size'] <NE... | Build a runlist based on a uniform distribution. | 625941f399cbb53fe67931cb |
def move_down( game_obj ): <NEW_LINE> <INDENT> for x in range(0, TILE_ORDER): <NEW_LINE> <INDENT> for y in range( 1-TILE_ORDER, 1): <NEW_LINE> <INDENT> if not is_tile( (x,y), game_obj.tile_ins ) : <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> for srh_y in range(y-1, -TILE_ORDER, -1): <NEW_LINE> <INDENT> if is_tile( ... | moves tiles DOWN
| 625941f355399d3f05588c9f |
def run(self): <NEW_LINE> <INDENT> print('CAN thread running...') <NEW_LINE> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> msg = self.buffer.get_message() <NEW_LINE> self.CANData[msg.arbitration_id] = msg <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> print('CAN Bus read error...') | Data reader | 625941f3442bda511e8be9f6 |
def handle(self, *args, **kwargs): <NEW_LINE> <INDENT> username = 'admin' <NEW_LINE> first_name = 'Admin' <NEW_LINE> last_name = 'Admin' <NEW_LINE> email = 'admin@email.com' <NEW_LINE> user = Employee.objects.create( username=username, first_name=first_name, last_name=last_name, email=email, gender='I' ) <NEW_LINE> use... | Cria um Employee.
Precisamos de Employee para fazer todas as transações no sistema. | 625941f3cc0a2c11143dd478 |
def render_panels(mapnik_file, image_size, output_list): <NEW_LINE> <INDENT> r = Renderer(mapnik_file, image_size) <NEW_LINE> for (bound, filename) in output_list: <NEW_LINE> <INDENT> r.render(bound, filename) | Render multiple panel images from the same map. Each one needs to be 'image_size' in pixel width/height. | 625941f31f5feb6acb0c512f |
def softmax_loss_vectorized(W, X, y, reg): <NEW_LINE> <INDENT> loss = 0.0 <NEW_LINE> dW = np.zeros_like(W) <NEW_LINE> num_train = X.shape[0] <NEW_LINE> scores = X.dot(W) <NEW_LINE> scores -= np.max(scores,1,keepdims=True) <NEW_LINE> exp_scores = np.exp(scores) <NEW_LINE> sums = np.sum(exp_scores,1,keepdims=True) <NEW_L... | Softmax loss function, vectorized version.
Inputs and outputs are the same as softmax_loss_naive. | 625941f30a50d4780f66747d |
def partition_ordered_list_equal_sum(a, k): <NEW_LINE> <INDENT> if k <= 1: <NEW_LINE> <INDENT> return [a] <NEW_LINE> <DEDENT> if k >= len(a): <NEW_LINE> <INDENT> return [[x] for x in a] <NEW_LINE> <DEDENT> partition_between = [(i + 1) * len(a) // k for i in range(k - 1)] <NEW_LINE> average_height = float(sum(a)) / k <N... | Partition a sorted list a into k partitions
Reference:
https://stackoverflow.com/a/35518205
https://gist.github.com/laowantong/ee675108eee64640e5f94f00d8edbcb4
CommandLine:
python -m ibeis.other.ibsfuncs partition_ordered_list_equal_sum
Example:
>>> # DISABLE_DOCTEST
>>> import random
>>> fro... | 625941f33317a56b8693a22f |
def test_contextualize_text_with_non_ascii_context(self): <NEW_LINE> <INDENT> key = u'あなた$a $b' <NEW_LINE> text = '$' + key <NEW_LINE> context = {'a': u'あなたあなたあなた', 'b': u'あなたhi'} <NEW_LINE> expected_text = '$あなたあなたあなたあなた あなたhi' <NEW_LINE> contextual_text = contextualize_text(text, context) <NEW_LINE> assert expected_t... | Verify that variable substitution works as intended with non-ascii characters. | 625941f38a349b6b435e8759 |
def remove(src): <NEW_LINE> <INDENT> if os.path.isdir(src): <NEW_LINE> <INDENT> shutil.rmtree(src) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> os.remove(src) | Remove file or folder | 625941f34e4d5625662d49b5 |
def zw_stk_anz_mx(myZwDatX, indexFile, path): <NEW_LINE> <INDENT> columns = [ 'inxFile' , 'month' , 'numStk' , 'numSum' , 'numInc' , 'numDec' , 'preInc' , 'preDec' ] <NEW_LINE> df = pd.DataFrame(columns=columns) <NEW_LINE> filename = "temp/monTotal_" + indexFile + ".csv" <NEW_LINE> for i in range(12): <NEW_LINE> <INDEN... | 按每个股票索引文件,生成相应的csv文件
:param myZwDatX: zwDatX类的实例
:param indexFile: 股票索引文件名,用于输出csv文件名
:param path: 相应的csv数据文件存放的目录 例如'./zwDat/cn/xday/'
:return: 空 | 625941f373bcbd0ca4b2c65c |
def run(self, ket: State) -> State: <NEW_LINE> <INDENT> qubits = self.qubits <NEW_LINE> indices = [ket.qubits.index(q) for q in qubits] <NEW_LINE> tensor = bk.tensormul(self.tensor, ket.tensor, indices) <NEW_LINE> return State(tensor, ket.qubits, ket.memory) | Apply the action of this gate upon a state | 625941f3eab8aa0e5d26e141 |
def datos_nad(numero_de_lista_elegida): <NEW_LINE> <INDENT> lista_elegida = diccionario_referencia_numero_directorio[numero_de_lista_elegida] <NEW_LINE> ruta_de_lista = directorios_finales[lista_elegida] <NEW_LINE> datos = datos_de_la_lista(ruta_de_lista) <NEW_LINE> return datos | Resume el proceso de usar diccionarios y funciones que se describen y ven adelante.
:param numero_de_lista_elegida: usando el diccionario con referencia en números a la lista elegida podemos usar
dicho número para acceder al nombre de la lista, con ese nombre usamos otro diccionario para acceder a la ruta y
con la ruta... | 625941f35510c4643540f9bb |
def testAddressBookItem(self): <NEW_LINE> <INDENT> pass | Test AddressBookItem | 625941f39b70327d1c4e13bf |
def generate_samples(grammar_dir, outfiles): <NEW_LINE> <INDENT> f = open(os.path.join(grammar_dir, 'template.php')) <NEW_LINE> template = f.read() <NEW_LINE> f.close() <NEW_LINE> phpgrammar = Grammar() <NEW_LINE> err = phpgrammar.parse_from_file(os.path.join(grammar_dir, 'php.txt')) <NEW_LINE> if err > 0: <NEW_LINE> <... | Generates a set of samples and writes them to the output files.
Args:
grammar_dir: directory to load grammar files from.
outfiles: A list of output filenames. | 625941f34f88993c3716c647 |
def get_target_from_url(url, marker=False): <NEW_LINE> <INDENT> cls, args, kwargs = get_target_class_from_url(url, marker) <NEW_LINE> return cls(*args, **kwargs) | Returns a luigi target based on the url scheme | 625941f3090684286d50f2d7 |
def _sliding_chunks_matmul_attn_probs_value( self, attn_probs: torch.Tensor, value: torch.Tensor, window_overlap: int ): <NEW_LINE> <INDENT> batch_size, seq_len, n_heads, key_value_proj_dim = value.size() <NEW_LINE> assert seq_len % (window_overlap * 2) == 0 <NEW_LINE> assert attn_probs.size()[:3] == value.size()[:3] <... | Same as _sliding_chunks_query_key_matmul but for attn_probs and value tensors. Returned tensor will be of the
same shape as `attn_probs` | 625941f385dfad0860c3b444 |
def insert(bot, update): <NEW_LINE> <INDENT> expr = clean(update.message.text) <NEW_LINE> state = expr.split()[0] <NEW_LINE> accumulator(bot, update, insert=state) <NEW_LINE> update.message.reply_text(text='Inserted "{}" into markov states.'.format(state)) | insert new state in markov states | 625941f33317a56b8693a230 |
def getRequestTargets(self, user, status=None): <NEW_LINE> <INDENT> if status is None: <NEW_LINE> <INDENT> status_clause = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> status_clause = (TranslationImportQueueEntry.status == status) <NEW_LINE> <DEDENT> distroseries = list_distroseries_request_targets(status_clause)... | See `ITranslationImportQueue`. | 625941f33d592f4c4ed1d643 |
def index(): <NEW_LINE> <INDENT> module_name = settings.modules[module].name_nice <NEW_LINE> response.title = module_name <NEW_LINE> return dict(module_name=module_name) | Module's Home Page | 625941f3498bea3a759ba094 |
def get_running_slope(values, Nslope=2, N="", NoData=NoDataVal): <NEW_LINE> <INDENT> if not N: <NEW_LINE> <INDENT> N = len(values) <NEW_LINE> <DEDENT> slopes = [NoData] * (N) <NEW_LINE> Nact = 0 <NEW_LINE> Nsets = N - Nslope <NEW_LINE> for i in range(Nsets): <NEW_LINE> <INDENT> if values[i] == NoData or values[i + Nslo... | This function computes running slopes between values at 0 and Nslope
and reports the results as an array of length N. The returned
array is padded at the end with NoData so that the
average values are centered. | 625941f3f548e778e58cdb67 |
def _low_profit(self, date_now: datetime, pair: str) -> ProtectionReturn: <NEW_LINE> <INDENT> look_back_until = date_now - timedelta(minutes=self._lookback_period) <NEW_LINE> trades = Trade.get_trades_proxy(pair=pair, is_open=False, close_date=look_back_until) <NEW_LINE> if len(trades) < self._trade_limit: <NEW_LINE> <... | Evaluate recent trades for pair | 625941f31f037a2d8b9467e3 |
def get_account_history(self, account, end=100, limit=100, only_ops=[]): <NEW_LINE> <INDENT> r = [] <NEW_LINE> for op in self.loop_account_history(account, end, limit, only_ops): <NEW_LINE> <INDENT> r.append(op) <NEW_LINE> <DEDENT> return r | Returns the transaction history of an account
:param str account: account name to get history for
:param int end: sequence number of the last transaction to return
:param int limit: limit number of transactions to return
:param array only_ops: Limit generator by these operations | 625941f37c178a314d6efa51 |
def general_trapezoid_identity(d, g, dim=4): <NEW_LINE> <INDENT> out = Seq(Sig(d) + Sig(1).iter_add(dim-2)) <NEW_LINE> for k in range(1, len(g) + 1): <NEW_LINE> <INDENT> out += g[k - 1] * (x ** (2 * k - 1) - x ** (2 * k) * Seq((Sig(d) + Sig(1).iter_add(dim-2)))) <NEW_LINE> <DEDENT> return out | The closed form for general trapezoids where g is a single sequence
:param d: The base of the algorithm
:param g: The secondary signature of the algorithm
:param dim: The number of dimensions
:return: The generated identity | 625941f326238365f5f0f45d |
def test_killall_job_batched(self): <NEW_LINE> <INDENT> mock_context = FakeAuroraCommandContext() <NEW_LINE> mock_monitor = self.get_monitor_mock() <NEW_LINE> with contextlib.nested( patch('apache.aurora.client.cli.jobs.Job.create_context', return_value=mock_context), patch('apache.aurora.client.cli.jobs.JobMonitor', r... | Test killall command with batching. | 625941f3283ffb24f3c55ee1 |
def _send_http_request(self, xml_request): <NEW_LINE> <INDENT> headers = {"Host": self._host, "Content-Type": "text/xml", "Recipient": self._storage} <NEW_LINE> try: <NEW_LINE> <INDENT> self._connection.request("POST", self._selector_url, xml_request, headers) <NEW_LINE> response = self._connection.getresponse() <NEW_L... | Send a request via HTTP protocol.
Args:
xml_request -- A fully formed xml request string for the CPS.
Returns:
The raw xml response string. | 625941f36e29344779a62bf8 |
def receiveCase(self,request): <NEW_LINE> <INDENT> if 'case' in request.POST: <NEW_LINE> <INDENT> caseJson=None <NEW_LINE> caseJson=json.loads(request.POST['case']) <NEW_LINE> case=models.Case(date=caseJson['date'], court=caseJson['court'], plaintiff=caseJson['plaintiff'], caseFile=caseJson['case_file'], defendant=case... | Method to receive a case from other nodes | 625941f3e1aae11d1e74a2a4 |
def highlight_usages_for_vim_win(): <NEW_LINE> <INDENT> win = vim.current.window <NEW_LINE> cur_matchids = win.vars.get('_jedi_usages_vim_matchids') <NEW_LINE> if cur_matchids: <NEW_LINE> <INDENT> if cur_matchids[0] == vim.current.buffer.number: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for matchid in cur_matchids... | Highlight usages in the current window.
It stores the matchids in a window-local variable.
(matchaddpos() only works for the current window.) | 625941f32c8b7c6e89b35da2 |
def calculate_equity_at_month(self, month, additional_monthly_payment = 0.0): <NEW_LINE> <INDENT> property_value = self.get_property_value_at_month(month) <NEW_LINE> remaining_debt = self.mortgage_.calculate_debt_at_month( month, additional_monthly_payment) <NEW_LINE> return property_value - remaining_debt | Calculates the total equity after a number of months.
Args:
* month: the number of months since the initial purchase.
* additional_monthly_payment: the amount paid each month beyond the
minimum required by the mortgage.
Returns:
* the equity in a property after a specified number of months. | 625941f3377c676e9127278d |
def __le__(self, other): <NEW_LINE> <INDENT> floater = self.numer/self.denom <NEW_LINE> otherFloater = other.numer/other.denom <NEW_LINE> if floater == otherFloater: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif floater<otherFloater: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDE... | less than or equal: return true if le or false if otherwise | 625941f32c8b7c6e89b35da3 |
def get(self, request, format=None): <NEW_LINE> <INDENT> an_apiview = [ 'Uses HTTP methods as function (get, post, put, patch, delete)', 'Is similar to a traditional Django View', 'Gives you the most control over your application logic', 'Is mapped manually to URLs' ] <NEW_LINE> return Response({'message':'Hello!', 'an... | Returns a list of APIViews features | 625941f3925a0f43d254a464 |
def isLeaf(self, p): <NEW_LINE> <INDENT> return self.numOfChildren(p) == 0 | Returns True if Position p is a leaf
:param p: position in question
:return: Boolean | 625941f321a7993f00bc82e2 |
def get_variables(cnx, pattern=None, variables=None, global_vars=False): <NEW_LINE> <INDENT> format_vars = { 'where_clause': '', 'where': '', } <NEW_LINE> if global_vars is True: <NEW_LINE> <INDENT> format_vars['table'] = 'GLOBAL_VARIABLES' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> format_vars['table'] = 'SESSION_V... | Get session or global system variables
We use the MySQL connection cnx to query the INFORMATION_SCHEMA
table SESSION_VARIABLES or, when global_vars is True, the table
GLOBAL_VARIABLES.
:param cnx: Valid MySQL connection
:param pattern: Pattern to use (used for LIKE)
:param variables: Variables to query for
:return: D... | 625941f30c0af96317bb87ce |
@pytest.mark.ds51102 <NEW_LINE> @pytest.mark.bz1836428 <NEW_LINE> @pytest.mark.skipif(ds_is_older('1.4.1'), reason='Not implemented') <NEW_LINE> def test_dsreplcheck_timeout_connection_mechanisms(topo_tls_ldapi): <NEW_LINE> <INDENT> OUTPUT = 'Supplier and Replica are in perfect synchronization' <NEW_LINE> m1 = topo_tls... | Check that ds-replcheck timeout option works with various connection mechanisms
:id: aeeb99c9-09e2-45dc-bd75-9f95409babe7
:customerscenario: True
:setup: Two supplier replication
:steps:
1. Create two suppliers with various connection mechanisms configured
2. Run ds-replcheck with -t option
:expectedresults:
... | 625941f3aad79263cf391031 |
def get_gap_class_weights(n_classes=2): <NEW_LINE> <INDENT> gap_class_weights = {} <NEW_LINE> gap_class_weights[2] = [0.19, 0.81] <NEW_LINE> return gap_class_weights[n_classes] | Returns class weights for GAP dataset
@Arguments:
n_classes: Number of classes for which the weights are required
@Returns:
class weights as a list | 625941f363d6d428bbe44ad8 |
def fake_strategy_report(self, strategy, budget): <NEW_LINE> <INDENT> audited_adverts = filter(lambda a: a.state.audited, strategy.advert_set.all()) <NEW_LINE> advert_count = len(audited_adverts) <NEW_LINE> if not advert_count: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> metrics = self.get_randomized_metrics(budget,... | Fake all reports related to Strategy model for a single strategy
:return: sums of faked simple metrics like {'imp': 100, }
:rtype dict: | 625941f3287bf620b61d4047 |
def _enable_login_popup(self, do_enable: bool) -> None: <NEW_LINE> <INDENT> login_popup = self.login_popup <NEW_LINE> txt = self.uname_text <NEW_LINE> if do_enable: <NEW_LINE> <INDENT> login_popup.attach_opener(self.ledlst[WCstatus.QAI_ROW]) <NEW_LINE> if self.is_QAI_logged_in(): <NEW_LINE> <INDENT> login_popup.remove_... | Enable or disable the login popup.
Args:
do_enable: True will enable the QAI login popup.
Note:
The popup should be disabled if the websocket comms are down, as its
the stocky server that will ultimately communicate with the QAI server. | 625941f3d7e4931a7ee9e507 |
def test_table(self): <NEW_LINE> <INDENT> table = sqlalchemy.Table() <NEW_LINE> with BannedDBSchemaOperations(banned_resources=['Table']): <NEW_LINE> <INDENT> self.assertRaises(DBOperationNotAllowed, table.drop) <NEW_LINE> self.assertRaises(DBOperationNotAllowed, table.alter) | Test table drops and alters raise DBOperationNotAllowed. | 625941f3c432627299f05232 |
def after_suite(self, test_report, teardown_flag=None): <NEW_LINE> <INDENT> if self._start_time is not None: <NEW_LINE> <INDENT> self._run(test_report) | Run after suite. | 625941f367a9b606de4a849d |
def batch_dummy_encode_catagorical_variable(self, data, variables, remove=[]): <NEW_LINE> <INDENT> variables_cnt = len(variables) <NEW_LINE> if variables_cnt < 1: <NEW_LINE> <INDENT> raise ValueError("Empty variable list.") <NEW_LINE> <DEDENT> if not remove: <NEW_LINE> <INDENT> remove = [False] * len(variables) <NEW_LI... | dummy encode the given list of catagorical variables within data frame in a batch manner
Args:
data (pandas data frame): the data frame user works on
variables ([str*]): names of catagorical variables user wants to dummy encode
remove ([bool*]): whether to remove each of the catagorical variable or not
Retu... | 625941f3167d2b6e3121917b |
def getTotalDisplacement(velocity): <NEW_LINE> <INDENT> tDisp = 0.0 <NEW_LINE> for val, vel in velocity.items(): <NEW_LINE> <INDENT> tDisp += vel <NEW_LINE> <DEDENT> return tDisp | Adds all velocities in the dictionary to get total displacement | 625941f3796e427e537b0bb2 |
def send_email(subject='', to_address=[], from_address=from_addr, content=''): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> msg = MIMEText(content) <NEW_LINE> msg['Subject'] = "[{0}] {1} {2}".format(site_domain, subject, date.today().strftime("%Y%m%d")) <NEW_LINE> msg['To'] = EMAIL_SPACE.join(to_address) <NEW_LINE> msg... | Send an email to a specified user or users.
This is a basic wrapper around python's STMPLIB library that allows us to
send emails to the users in case it's necessary. Any failure of this
script is considered fatal. | 625941f3956e5f7376d71452 |
def push_front(self, a): <NEW_LINE> <INDENT> pass | void QByteArray.push_front(QByteArray a) | 625941f3a8ecb033257d36b2 |
@pytest.fixture(scope='module') <NEW_LINE> def image_uuid(image_object): <NEW_LINE> <INDENT> return u'{}:{}:{}'.format( image_object.bucket_id, image_object.version_id, image_object.key ) | Get image UUID (Flask-IIIF term, not actual an UUID). | 625941f3fbf16365ca6f67b8 |
def settings_vars(request): <NEW_LINE> <INDENT> smap = {} <NEW_LINE> smap['DEBUG'] = settings.DEBUG <NEW_LINE> smap['TRANSLATED_LANGUAGES'] = sorted(settings.TRANSLATED_LANGUAGES) <NEW_LINE> smap['SPLASH_LANGUAGES'] = sorted(settings.SPLASH_LANGUAGES) <NEW_LINE> smap['SPOKEN_LANGUAGES'] = settings.SPOKEN_LANGUAGES <NEW... | set context variables | 625941f3d10714528d6002d2 |
def click_latest_year_reminder_msg(self): <NEW_LINE> <INDENT> browser().find_element_by_class_name("reminderMessage").find_element_by_tag_name("a").click() <NEW_LINE> wait_for(expected_conditions.invisibility_of_element_located((By.CLASS_NAME, "reminderMessage"))) | Click on the latest year link from the previous year reminder message | 625941f3a934411ee3751c7d |
def is_overlapped(det1: bf_codecs.Detection, det2: bf_codecs.Detection) -> bool: <NEW_LINE> <INDENT> coords1_sorted_x = sorted([c[0] for c in det1.coords]) <NEW_LINE> coords2_sorted_x = sorted([c[0] for c in det2.coords]) <NEW_LINE> coords1_sorted_y = sorted([c[1] for c in det1.coords]) <NEW_LINE> coords2_sorted_y = so... | :param det1: First Detection
:param det2: Second Detection
:return: If the two Detections' bboxes are overlapped | 625941f373bcbd0ca4b2c65d |
def get_type(self): <NEW_LINE> <INDENT> return javabridge.call(self.jobject, "type", "()I") | Returns the type of the attribute. See weka.core.Attribute Javadoc.
:return: the type
:rtype: int | 625941f3cdde0d52a9e53620 |
def score(self,X_test,y_test): <NEW_LINE> <INDENT> y_predict = self.predict(X_test) <NEW_LINE> return accuracy_score(y_test,y_predict) | 根据测试数据集X_test 和 y_test确定当前模型的准确度 | 625941f3187af65679ca5708 |
def _write_pcap_files(self, iface_pkts_map): <NEW_LINE> <INDENT> for iface, pkts in iface_pkts_map.items(): <NEW_LINE> <INDENT> direction = "in" <NEW_LINE> infile = self.filename(iface, direction) <NEW_LINE> fp = RawPcapWriter(infile, linktype=1) <NEW_LINE> fp._write_header(None) <NEW_LINE> for pkt_data in pkts: <NEW_L... | Writes the collected packets to their respective interfaces.
This is done by creating a pcap file with the corresponding name. | 625941f3b545ff76a89143fd |
def _parse_and_execute(self, process, wps_request, uuid): <NEW_LINE> <INDENT> LOGGER.debug('Checking if datainputs is required and has been passed') <NEW_LINE> if process.inputs: <NEW_LINE> <INDENT> if wps_request.inputs is None: <NEW_LINE> <INDENT> raise MissingParameterValue('', 'datainputs') <NEW_LINE> <DEDENT> <DED... | Parse and execute request
| 625941f3adb09d7d5db6cd73 |
def longestCommonPrefix(self, strs): <NEW_LINE> <INDENT> ln = 0 if strs == None else len(strs) <NEW_LINE> if ln == 0: return "" <NEW_LINE> sn = (1 << 31) - 1 <NEW_LINE> for i in range(ln): <NEW_LINE> <INDENT> sn = min(sn, 0 if strs[i] == None else len(strs[i])) <NEW_LINE> <DEDENT> for j in range(sn): <NEW_LINE> <INDENT... | :type strs: List[str]
:rtype: str | 625941f3d268445f265b5457 |
def toDegrees(self): <NEW_LINE> <INDENT> return copysign(abs(self.d)+Decimal(self.m)/60 +Decimal(self.s)/3600,self.d) | return the dec as a Decimal approximation | 625941f38a349b6b435e875a |
def main(): <NEW_LINE> <INDENT> os.environ.setdefault( "DJANGO_SETTINGS_MODULE", "listings.config.settings.base" ) <NEW_LINE> try: <NEW_LINE> <INDENT> from django.core.management import execute_from_command_line <NEW_LINE> <DEDENT> except ImportError as exc: <NEW_LINE> <INDENT> raise ImportError( "Couldn't import Djang... | Run administrative tasks. | 625941f3eab8aa0e5d26e142 |
def model_fingerprint(config_file: Text, domain_file: Optional[Text] = None, nlu_data: Optional[Text] = None, stories: Optional[Text] = None) -> Fingerprint: <NEW_LINE> <INDENT> import rasa_core <NEW_LINE> import rasa_nlu <NEW_LINE> import rasa <NEW_LINE> import time <NEW_LINE> return { FINGERPRINT_CONFIG_KEY: _get_has... | Creates a model fingerprint from its used configuration and training
data.
Args:
config_file: Path to the configuration file.
domain_file: Path to the models domain file.
nlu_data: Path to the used NLU training data.
stories: Path to the used story training data.
Returns:
The fingerprint. | 625941f31b99ca400220b09c |
def parse(start_symbol, text, grammar): <NEW_LINE> <INDENT> tokenizer = grammar[' '] + '(%s)' <NEW_LINE> def parse_sequence(sequence, text): <NEW_LINE> <INDENT> result = [] <NEW_LINE> for atom in sequence: <NEW_LINE> <INDENT> tree, text, = parse_atom(atom, text) <NEW_LINE> if text is None: return Fail <NEW_LINE> result... | Example call: parse('Exp', '3*x + b', G).
Returns a (tree, remainder) pair. If remainder is '', it parsed
the whole string. Failure iff remainder is None. This is a deterministic
Parse Expression Grammar (PEG) parser, so rule order (left-to-right) matters.
Do 'E' => T op E | T' putting the longest parse first; dont' do... | 625941f397e22403b379d584 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.