code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
# Generated by Django 2.0.5 on 2018-06-19 16:43
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('owner', '0018_auto_20180... | [
"django.db.migrations.RemoveField",
"django.db.models.ForeignKey",
"django.db.models.BooleanField",
"django.db.models.DateTimeField",
"django.db.migrations.swappable_dependency"
] | [((227, 284), 'django.db.migrations.swappable_dependency', 'migrations.swappable_dependency', (['settings.AUTH_USER_MODEL'], {}), '(settings.AUTH_USER_MODEL)\n', (258, 284), False, 'from django.db import migrations, models\n'), ((366, 429), 'django.db.migrations.RemoveField', 'migrations.RemoveField', ([], {'model_name... |
import sqlite3
conexion = sqlite3.connect('RandUser.db')
cursor = conexion.cursor()
cursor.execute('''
CREATE TABLE Users(
Gender TEXT NOT NULL,
First TEXT NOT NULL,
Last TEXT NOT NULL,
Location TEXT NOT NULL,
Email TEXT NOT NULL)
''')
conexion.close()
| [
"sqlite3.connect"
] | [((27, 57), 'sqlite3.connect', 'sqlite3.connect', (['"""RandUser.db"""'], {}), "('RandUser.db')\n", (42, 57), False, 'import sqlite3\n')] |
import datetime
import uuid
from src.database.connection import SessionLocal
from src.database.models.posts import Posts
from src.exceptions import ResourceAlreadySynced
from src.serializers.posts import PostsModel
db = SessionLocal()
def delete_post_from_database(post_to_delete: Posts) -> None:
post_to_delete... | [
"datetime.datetime.now",
"uuid.uuid4",
"src.exceptions.ResourceAlreadySynced",
"src.database.connection.SessionLocal"
] | [((223, 237), 'src.database.connection.SessionLocal', 'SessionLocal', ([], {}), '()\n', (235, 237), False, 'from src.database.connection import SessionLocal\n'), ((334, 357), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (355, 357), False, 'import datetime\n'), ((929, 967), 'src.exceptions.Resourc... |
import torch
import torch.nn as nn
import numpy
class NoisyLinear(torch.nn.Module):
def __init__(self, in_features, out_features, sigma = 1.0):
super(NoisyLinear, self).__init__()
self.out_features = out_features
self.in_features = in_features
self.sigma = sig... | [
"torch.nn.init.xavier_uniform_",
"torch.zeros",
"torch.randn"
] | [((1593, 1623), 'torch.randn', 'torch.randn', (['(10, in_features)'], {}), '((10, in_features))\n', (1604, 1623), False, 'import torch\n'), ((408, 450), 'torch.nn.init.xavier_uniform_', 'torch.nn.init.xavier_uniform_', (['self.weight'], {}), '(self.weight)\n', (437, 450), False, 'import torch\n'), ((605, 653), 'torch.n... |
"""
One of the most straightforward problems we can solve recursively is to print every number from n down to zero in succession.
We can do that simply by writing a function that prints n, then calls itself for n-1:
"""
import sys
sys.setrecursionlimit(10005) # Sets recursion depth limit
N = 10000
# def countdown_i(n):... | [
"sys.setrecursionlimit"
] | [((231, 259), 'sys.setrecursionlimit', 'sys.setrecursionlimit', (['(10005)'], {}), '(10005)\n', (252, 259), False, 'import sys\n')] |
# 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.
import os
import subprocess
import threading
from pathlib import Path
import numpy as np
import torch
def fasta_file_path(pre... | [
"subprocess.check_output",
"threading.local",
"pathlib.Path",
"numpy.fromstring",
"numpy.stack",
"numpy.load"
] | [((638, 655), 'threading.local', 'threading.local', ([], {}), '()\n', (653, 655), False, 'import threading\n'), ((678, 707), 'pathlib.Path', 'Path', (['f"""{path}.fasta.idx.npy"""'], {}), "(f'{path}.fasta.idx.npy')\n", (682, 707), False, 'from pathlib import Path\n'), ((1861, 2004), 'subprocess.check_output', 'subproce... |
#!/usr/bin/env python
# coding: utf-8
# GITHUB USERNAME SAIAJAY1
import math, random
def generateOTP() :
digits = "0123456789"
OTP = ""
for i in range(4) :
OTP += digits[math.floor(random.random() * 10)]
return OTP
if __name__ == "__main__" :
print("OTP of 4 digits:", generateOTP())
# MADE BY <NAME... | [
"random.random"
] | [((192, 207), 'random.random', 'random.random', ([], {}), '()\n', (205, 207), False, 'import math, random\n')] |
# -*- coding: utf-8 -*-
from litNlp.predict import SA_Model_Predict
import numpy as np
# 加载模型的字典项
tokenize_path = 'model/tokenizer.pickle'
# train_method : 模型训练方式,默认 textcnn ,可选:bilstm , gru
train_method = 'textcnn'
# 模型的保存位置,后续用于推理
sa_model_path_m = 'model/{}.h5'.format(train_method)
# 开始输入待测样例
predict_text = ['这个... | [
"litNlp.predict.SA_Model_Predict",
"numpy.asarray"
] | [((352, 413), 'litNlp.predict.SA_Model_Predict', 'SA_Model_Predict', (['tokenize_path', 'sa_model_path_m'], {'max_len': '(100)'}), '(tokenize_path, sa_model_path_m, max_len=100)\n', (368, 413), False, 'from litNlp.predict import SA_Model_Predict\n'), ((475, 495), 'numpy.asarray', 'np.asarray', (['sa_score'], {}), '(sa_... |
import pathlib
import sys
from typing import List, Tuple, Dict, Any
import matplotlib.colors as mcolors
import matplotlib.pyplot as plt
from hcb.artifacts.make_lambda_plots import DesiredLineFit, project_intersection_of_both_observables
from hcb.artifacts.make_threshold_plots import make_threshold_plots
from hcb.tool... | [
"hcb.artifacts.make_threshold_plots.make_threshold_plots",
"pathlib.Path",
"hcb.artifacts.make_lambda_plots.DesiredLineFit",
"hcb.tools.analysis.collecting.MultiStats.from_recorded_data",
"matplotlib.pyplot.show"
] | [((2005, 2055), 'hcb.artifacts.make_threshold_plots.make_threshold_plots', 'make_threshold_plots', ([], {'data': 'all_data', 'groups': 'groups'}), '(data=all_data, groups=groups)\n', (2025, 2055), False, 'from hcb.artifacts.make_threshold_plots import make_threshold_plots\n'), ((2176, 2186), 'matplotlib.pyplot.show', '... |
import os
import glob
import random
import numpy as np
import torchaudio as T
from torch.utils.data import Dataset, DataLoader
from torch.utils.data.distributed import DistributedSampler
def create_dataloader(params, train, is_distributed=False):
dataset = AudioDataset(params, train)
return DataLoader(
... | [
"random.shuffle",
"os.path.join",
"torchaudio.transforms.Resample",
"numpy.random.randint",
"torch.utils.data.distributed.DistributedSampler",
"os.path.basename",
"torchaudio.load_wav"
] | [((924, 1033), 'torchaudio.transforms.Resample', 'T.transforms.Resample', (['params.new_sample_rate', 'params.sample_rate'], {'resampling_method': '"""sinc_interpolation"""'}), "(params.new_sample_rate, params.sample_rate,\n resampling_method='sinc_interpolation')\n", (945, 1033), True, 'import torchaudio as T\n'), ... |
from easy_dna import (
dna_pattern_to_regexpr,
record_with_different_sequence,
sequence_to_biopython_record,
annotate_record,
list_common_enzymes,
)
def test_record_with_different_sequence():
record = sequence_to_biopython_record("ATGCATGCATGC")
annotate_record(record, (0, 5), label="my_la... | [
"easy_dna.list_common_enzymes",
"easy_dna.record_with_different_sequence",
"easy_dna.sequence_to_biopython_record",
"easy_dna.annotate_record"
] | [((227, 271), 'easy_dna.sequence_to_biopython_record', 'sequence_to_biopython_record', (['"""ATGCATGCATGC"""'], {}), "('ATGCATGCATGC')\n", (255, 271), False, 'from easy_dna import dna_pattern_to_regexpr, record_with_different_sequence, sequence_to_biopython_record, annotate_record, list_common_enzymes\n'), ((276, 325),... |
# Libraries
import re
import ast
import yaml
import json
import copy
import logging
import numpy as np
import pandas as pd
import logging.config
# Specific
from pathlib import Path
# Own libraries
from datablend.utils.pandas import save_xlsx
from datablend.utils.pandas import save_df_dict
from datablend.core.blend.co... | [
"logging.getLogger",
"datablend.core.widgets.stack.StackWidget",
"pandas.read_csv",
"pathlib.Path",
"datablend.utils.pandas.save_xlsx",
"datablend.core.widgets.tidy.TidyWidget",
"datablend.core.blend.config.BlenderConfig",
"datablend.core.blend.template.BlenderTemplate",
"pandas.read_excel",
"copy... | [((671, 695), 'logging.getLogger', 'logging.getLogger', (['"""dev"""'], {}), "('dev')\n", (688, 695), False, 'import logging\n'), ((1571, 1630), 'pandas.read_excel', 'pd.read_excel', (['filepath'], {'sheet_name': 'None', 'engine': '"""openpyxl"""'}), "(filepath, sheet_name=None, engine='openpyxl')\n", (1584, 1630), Tru... |
from sopel.module import commands
from sopel.config import ConfigurationError
from sopel.config.types import StaticSection, ValidatedAttribute
import urllib, json
class LastFMsection(StaticSection):
path = ValidatedAttribute('apikey')
def setup(bot):
bot.config.define_section('lastfm', LastFMsection)
def co... | [
"sopel.config.types.ValidatedAttribute",
"sopel.module.commands"
] | [((471, 489), 'sopel.module.commands', 'commands', (['"""lastfm"""'], {}), "('lastfm')\n", (479, 489), False, 'from sopel.module import commands\n'), ((212, 240), 'sopel.config.types.ValidatedAttribute', 'ValidatedAttribute', (['"""apikey"""'], {}), "('apikey')\n", (230, 240), False, 'from sopel.config.types import Sta... |
import os
import numpy as np
import torch
from config.adacrowd import cfg
from datasets.adacrowd.WE.loading_data import loading_data
from datasets.adacrowd.WE.setting import cfg_data
from trainer_adacrowd import Trainer_AdaCrowd
seed = cfg.SEED
if seed is not None:
np.random.seed(seed)
torch.manual_seed(seed... | [
"torch.manual_seed",
"os.path.realpath",
"trainer_adacrowd.Trainer_AdaCrowd",
"numpy.random.seed",
"torch.cuda.manual_seed",
"torch.cuda.set_device"
] | [((698, 743), 'trainer_adacrowd.Trainer_AdaCrowd', 'Trainer_AdaCrowd', (['loading_data', 'cfg_data', 'pwd'], {}), '(loading_data, cfg_data, pwd)\n', (714, 743), False, 'from trainer_adacrowd import Trainer_AdaCrowd\n'), ((273, 293), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (287, 293), True, 'i... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
sys.stdout.write("#include <stdint.h>\n")
sys.stdout.write("const uint8_t rb528_table[32] = {\n")
for i in range(32):
if not (i % 8):
sys.stdout.write(" ")
sys.stdout.write("%3d" % (((i * 255) + 15.5) // 31))
if (i + 1) % 8:
sys.s... | [
"sys.stdout.write"
] | [((58, 99), 'sys.stdout.write', 'sys.stdout.write', (['"""#include <stdint.h>\n"""'], {}), "('#include <stdint.h>\\n')\n", (74, 99), False, 'import sys\n'), ((101, 156), 'sys.stdout.write', 'sys.stdout.write', (['"""const uint8_t rb528_table[32] = {\n"""'], {}), "('const uint8_t rb528_table[32] = {\\n')\n", (117, 156),... |
import sys
import csv
import argparse
import parse
import os
from settings import HASH_HEADERS, PATHS, HASH_TYPES
from dateutil import parser as dateutil_parser
csv.field_size_limit(sys.maxsize)
OBJECT_HEADERS_V2 = ['id','name','type','description','self_uri','size','created_time','updated_time','version','mime_type'... | [
"csv.field_size_limit",
"dateutil.parser.parse",
"csv.DictWriter",
"csv.DictReader",
"parse.parse",
"argparse.ArgumentParser",
"os.environ.get"
] | [((162, 195), 'csv.field_size_limit', 'csv.field_size_limit', (['sys.maxsize'], {}), '(sys.maxsize)\n', (182, 195), False, 'import csv\n'), ((1064, 1101), 'dateutil.parser.parse', 'dateutil_parser.parse', (["d['timestamp']"], {}), "(d['timestamp'])\n", (1085, 1101), True, 'from dateutil import parser as dateutil_parser... |
import pytest
import bz2
import importlib.resources
import gzip
import lzma
import uuid
import zlib
from dataclasses import make_dataclass
from fondat.error import InternalServerError, NotFoundError
from fondat.file import directory_resource, file_resource
from fondat.pagination import paginate
from fondat.stream imp... | [
"tempfile.TemporaryDirectory",
"uuid.UUID",
"fondat.stream.BytesStream",
"fondat.file.file_resource",
"dataclasses.make_dataclass",
"fondat.pagination.paginate",
"fondat.file.directory_resource",
"pytest.raises"
] | [((460, 524), 'dataclasses.make_dataclass', 'make_dataclass', (['"""DC"""', "(('key', str), ('foo', str), ('bar', int))"], {}), "('DC', (('key', str), ('foo', str), ('bar', int)))\n", (474, 524), False, 'from dataclasses import make_dataclass\n'), ((949, 1013), 'dataclasses.make_dataclass', 'make_dataclass', (['"""DC""... |
# -*- coding: utf-8 -*-
from django.db import models, migrations
import django.utils.timezone
import django.core.validators
class Migration(migrations.Migration):
dependencies = [("auth", "0001_initial"), ("typeclasses", "0001_initial")]
operations = [
migrations.CreateModel(
name="Acc... | [
"django.db.models.EmailField",
"django.db.models.TextField",
"django.db.models.ManyToManyField",
"django.db.models.BooleanField",
"django.db.models.AutoField",
"django.db.models.DateTimeField",
"django.db.models.CharField"
] | [((414, 507), 'django.db.models.AutoField', 'models.AutoField', ([], {'verbose_name': '"""ID"""', 'serialize': '(False)', 'auto_created': '(True)', 'primary_key': '(True)'}), "(verbose_name='ID', serialize=False, auto_created=True,\n primary_key=True)\n", (430, 507), False, 'from django.db import models, migrations\... |
from django.db import models
from datetime import datetime, timedelta, timezone
from clientmanagement import sendemail
from django.conf import settings
from clientmanagement.widget import quill
import pytz
def time_now(instance=None):
return datetime.now(pytz.utc)
class SystemUpdates(models.Model):
ver... | [
"django.db.models.TextField",
"django.db.models.BooleanField",
"datetime.datetime.now",
"clientmanagement.sendemail.sendemaileveryone",
"clientmanagement.widget.quill.QuillObject",
"django.db.models.DateTimeField",
"datetime.timedelta",
"django.db.models.CharField"
] | [((248, 270), 'datetime.datetime.now', 'datetime.now', (['pytz.utc'], {}), '(pytz.utc)\n', (260, 270), False, 'from datetime import datetime, timedelta, timezone\n'), ((327, 394), 'django.db.models.CharField', 'models.CharField', (['"""Version"""'], {'max_length': '(50)', 'null': '(False)', 'blank': '(False)'}), "('Ver... |
import argparse
import os
import traceback
import nest_py.ops.docker_ops as docker_ops
from nest_py.ops.ops_logger import log
import nest_py.ops.container_users as container_users
PYTEST_CMD_HELP = """Run one or all python unit tests.
"""
PYTEST_CMD_DESCRIPTION = PYTEST_CMD_HELP + """
"""
SPAWN_CONTAINER_ARG_HELP = ... | [
"os.path.join",
"pytest.main",
"nest_py.ops.docker_ops._run_docker_shell_script"
] | [((2706, 2764), 'os.path.join', 'os.path.join', (['project_root_dir', '"""nest_py"""', '"""tests"""', '"""unit"""'], {}), "(project_root_dir, 'nest_py', 'tests', 'unit')\n", (2718, 2764), False, 'import os\n'), ((3982, 4022), 'os.path.join', 'os.path.join', (['project_root_dir', '"""docker"""'], {}), "(project_root_dir... |
#!/usr/bin/env python
import astropy.units as u
from typing import Union
from dataclasses import dataclass, field, is_dataclass
from cached_property import cached_property
import copy
from typing import ClassVar
from schema import Or
from tollan.utils.dataclass_schema import add_schema
from tollan.utils.log import ge... | [
"tollan.utils.log.get_logger",
"tollan.utils.fmt.pformat_yaml",
"tollan.utils.log.logit",
"tollan.utils.log.log_to_file",
"copy.deepcopy",
"dataclasses.is_dataclass",
"dataclasses.field"
] | [((5733, 5798), 'dataclasses.field', 'field', ([], {'metadata': "{'description': 'The unique identifier the job.'}"}), "(metadata={'description': 'The unique identifier the job.'})\n", (5738, 5798), False, 'from dataclasses import dataclass, field, is_dataclass\n'), ((5866, 6044), 'dataclasses.field', 'field', ([], {'m... |
from flask import render_template
from app import app
from app.models.tables import AtividadeProfissional
@app.route('/atividades')
def atividades():
lista = AtividadeProfissional.query.all()
return render_template("listar_ativProfissional.html", lista=lista)
| [
"flask.render_template",
"app.models.tables.AtividadeProfissional.query.all",
"app.app.route"
] | [((108, 132), 'app.app.route', 'app.route', (['"""/atividades"""'], {}), "('/atividades')\n", (117, 132), False, 'from app import app\n'), ((163, 196), 'app.models.tables.AtividadeProfissional.query.all', 'AtividadeProfissional.query.all', ([], {}), '()\n', (194, 196), False, 'from app.models.tables import AtividadePro... |
from flask import render_template
from data import tours
import random
def index_html():
tours6 ={}
for i in range(1,7):
tours6[i] = tours[i]
return render_template('index.html',tour = tours6) | [
"flask.render_template"
] | [((170, 212), 'flask.render_template', 'render_template', (['"""index.html"""'], {'tour': 'tours6'}), "('index.html', tour=tours6)\n", (185, 212), False, 'from flask import render_template\n')] |
import json
import mock
from nose.tools import eq_, ok_
from ..forms import (CreateBankDetailsForm,
CreateBillingConfigurationForm as BillingForm, EventForm,
PriceForm, VatNumberForm)
from .samples import (event_notification, good_bank_details,
good_bill... | [
"mock.patch",
"nose.tools.eq_",
"lib.transactions.models.Transaction.objects.create",
"json.dumps",
"lib.sellers.models.Seller.objects.create",
"lib.sellers.models.SellerProduct.objects.create",
"nose.tools.ok_"
] | [((510, 554), 'mock.patch', 'mock.patch', (['"""lib.bango.forms.URLField.clean"""'], {}), "('lib.bango.forms.URLField.clean')\n", (520, 554), False, 'import mock\n'), ((1131, 1175), 'mock.patch', 'mock.patch', (['"""lib.bango.forms.URLField.clean"""'], {}), "('lib.bango.forms.URLField.clean')\n", (1141, 1175), False, '... |
"""
Functions to test if two floats are equal to within relative and absolute
tolerances. This dynamically chooses a cython implementation if available.
"""
from debtcollector import removals
from numpy import allclose as _allclose, isinf
from dit import ditParams
__all__ = (
'close',
'allclose',
)
@remov... | [
"debtcollector.removals.remove",
"numpy.isinf",
"numpy.allclose"
] | [((315, 384), 'debtcollector.removals.remove', 'removals.remove', ([], {'message': '"""Use numpy.isclose instead"""', 'version': '"""1.0.2"""'}), "(message='Use numpy.isclose instead', version='1.0.2')\n", (330, 384), False, 'from debtcollector import removals\n'), ((633, 702), 'debtcollector.removals.remove', 'removal... |
from django import forms
from django.contrib import admin
from django.utils.translation import gettext_lazy as _
from election.models import ElectionDay
from electionnight.models import PageContentBlock
class BlockAdminForm(forms.ModelForm):
# content = forms.CharField(widget=CKEditorWidget()) # TODO: To markdown... | [
"election.models.ElectionDay.objects.all",
"django.utils.translation.gettext_lazy"
] | [((601, 619), 'django.utils.translation.gettext_lazy', '_', (['"""Election date"""'], {}), "('Election date')\n", (602, 619), True, 'from django.utils.translation import gettext_lazy as _\n'), ((782, 807), 'election.models.ElectionDay.objects.all', 'ElectionDay.objects.all', ([], {}), '()\n', (805, 807), False, 'from e... |
# !/usr/local/python/bin/python
# -*- coding: utf-8 -*-
# (C) <NAME>, 2020
# All rights reserved
# @Author: '<NAME> <<EMAIL>>'
# @Time: '2020-12-22 13:03'
import json
from flask import make_response, Flask
from pre_request import pre, Rule
app = Flask(__name__)
app.config["TESTING"] = True
client = app.test_client()
... | [
"pre_request.Rule",
"flask.Flask",
"json.dumps",
"pre_request.pre.catch",
"flask.make_response"
] | [((248, 263), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (253, 263), False, 'from flask import make_response, Flask\n'), ((916, 931), 'pre_request.pre.catch', 'pre.catch', (['args'], {}), '(args)\n', (925, 931), False, 'from pre_request import pre, Rule\n'), ((358, 376), 'json.dumps', 'json.dumps', (['... |
from django.contrib import admin
from django.contrib import admin
from employees.models import Employee, Department, Payroll
class Departments(admin.ModelAdmin):
list_display = ('id', 'name', 'budget', 'description')
list_display_links = ('id', 'name')
search_fields = ('name', 'description')
# registro ... | [
"django.contrib.admin.site.register"
] | [((345, 389), 'django.contrib.admin.site.register', 'admin.site.register', (['Department', 'Departments'], {}), '(Department, Departments)\n', (364, 389), False, 'from django.contrib import admin\n'), ((671, 711), 'django.contrib.admin.site.register', 'admin.site.register', (['Employee', 'Employees'], {}), '(Employee, ... |
import pandas as pd
from Stock import get_stock_data_2min_56days
from Twitter_CEO import get_CEOs_twitter_posts
from Twitter_Company import get_company_twitter_posts
from Analysis import find_stock_movement
from statistical_tests import contingency_table_company, contingency_table_ceo, run_chisquared_company, run_chis... | [
"Analysis.find_stock_movement",
"statistical_tests.contingency_table_company",
"statistical_tests.contingency_table_ceo",
"statistical_tests.run_chisquared_company",
"numpy.sqrt",
"pandas.read_csv",
"statistical_tests.run_chisquared_ceo",
"numpy.array",
"numpy.sum",
"Twitter_Company.get_company_tw... | [((519, 561), 'pandas.read_csv', 'pd.read_csv', (['"""assets/twitter_accounts.csv"""'], {}), "('assets/twitter_accounts.csv')\n", (530, 561), True, 'import pandas as pd\n'), ((636, 671), 'Stock.get_stock_data_2min_56days', 'get_stock_data_2min_56days', (['symbols'], {}), '(symbols)\n', (662, 671), False, 'from Stock im... |
import numpy as np
import pandas as pd
import simpy
from sim_utils.audit import Audit
from sim_utils.data import Data
from sim_utils.patient import Patient
import warnings
warnings.filterwarnings("ignore")
class Model(object):
def __init__(self, scenario):
"""
"""
self.env = simpy.En... | [
"pandas.Series",
"numpy.random.normal",
"numpy.mean",
"sim_utils.patient.Patient",
"simpy.Environment",
"numpy.max",
"numpy.sum",
"numpy.zeros",
"sim_utils.audit.Audit",
"pandas.DataFrame",
"sim_utils.data.Data",
"warnings.filterwarnings"
] | [((175, 208), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (198, 208), False, 'import warnings\n'), ((312, 331), 'simpy.Environment', 'simpy.Environment', ([], {}), '()\n', (329, 331), False, 'import simpy\n'), ((383, 400), 'sim_utils.data.Data', 'Data', (['self.params']... |
import requests
import json
import numpy as np
supportedCurrencies = []
def notValidCurrencyError():
raise Exception(f"Currency not supported \n Supported currencies are: {supportedCurrencies}")
class Currency:
def __init__(self, shorthand, amount):
self.shorthand = shorthand
self.amount = a... | [
"requests.get"
] | [((582, 659), 'requests.get', 'requests.get', (['f"""https://api.exchangeratesapi.io/latest?base={base.shorthand}"""'], {}), "(f'https://api.exchangeratesapi.io/latest?base={base.shorthand}')\n", (594, 659), False, 'import requests\n'), ((947, 1001), 'requests.get', 'requests.get', (['"""https://api.exchangeratesapi.io... |
"""
Contains tests for app.wall_e.models.canvas_api.Canvas class
"""
# pylint: disable=unused-argument, disable=protected-access
from unittest import mock
import pytest
from tests.mock.mock_requester import get_mocked_canvas_set_response
@mock.patch('app.wall_e.models.requester.Requester._base_request')
def test_init... | [
"unittest.mock.patch",
"tests.mock.mock_requester.get_mocked_canvas_set_response",
"pytest.raises"
] | [((241, 306), 'unittest.mock.patch', 'mock.patch', (['"""app.wall_e.models.requester.Requester._base_request"""'], {}), "('app.wall_e.models.requester.Requester._base_request')\n", (251, 306), False, 'from unittest import mock\n'), ((768, 833), 'unittest.mock.patch', 'mock.patch', (['"""app.wall_e.models.requester.Requ... |
"""This module provides configuration values used by the application."""
import logging
import os
from collections.abc import Mapping, Sequence
from logging import config as lc
from typing import Any, Optional, Union, final
import jinja2
import yaml
from pydantic import AnyHttpUrl, BaseModel, BaseSettings, EmailStr, H... | [
"logging.getLogger",
"document.domain.model.HtmlContent",
"pydantic.validator",
"logging.config.dictConfig",
"os.environ.get"
] | [((1293, 1331), 'document.domain.model.HtmlContent', 'model.HtmlContent', (['"""<div class=\'row\'>"""'], {}), '("<div class=\'row\'>")\n', (1310, 1331), False, 'from document.domain import model\n'), ((1356, 1383), 'document.domain.model.HtmlContent', 'model.HtmlContent', (['"""</div>"""'], {}), "('</div>')\n", (1373,... |
import re
import json
from Configurable.ProjectConstants import Constants
from DatasetHandler.ContentSupport import isNotNone
class Reader:
"""
This class provides a FileReader for text containing files with an [otpional] delimiter.
"""
def __init__(self, path:str =None, seperator_regex:str =None):
... | [
"Configurable.ProjectConstants.Constants",
"re.split",
"DatasetHandler.ContentSupport.isNotNone",
"json.load"
] | [((650, 661), 'Configurable.ProjectConstants.Constants', 'Constants', ([], {}), '()\n', (659, 661), False, 'from Configurable.ProjectConstants import Constants\n'), ((695, 710), 'DatasetHandler.ContentSupport.isNotNone', 'isNotNone', (['path'], {}), '(path)\n', (704, 710), False, 'from DatasetHandler.ContentSupport imp... |
#!/usr/bin/env python3
import sys
from nltk.tree import Tree
#Converts Penn Treebank to Alto-compatible format
phrase_levels = [
"ADJP",
"ADVP",
"CONJP",
"FRAG",
"INTJ",
"LST",
"NAC",
"NP",
"NX",
"PP",
"PRN",
"PRT",
"QP",
"RRC",
"UCP",
"VP",
"WHADJP... | [
"nltk.tree.Tree.fromstring"
] | [((474, 495), 'nltk.tree.Tree.fromstring', 'Tree.fromstring', (['line'], {}), '(line)\n', (489, 495), False, 'from nltk.tree import Tree\n')] |
import sublime
import sublime_plugin
def char_at(view, point):
return view.substr(sublime.Region(point, point + 1))
def is_space(view, point):
return char_at(view, point).isspace()
def is_newline(view, point):
return char_at(view, point) == "\n"
class CommentFoldCommand(sublime_plugin.TextCommand):
... | [
"sublime.Region"
] | [((88, 120), 'sublime.Region', 'sublime.Region', (['point', '(point + 1)'], {}), '(point, point + 1)\n', (102, 120), False, 'import sublime\n'), ((931, 951), 'sublime.Region', 'sublime.Region', (['a', 'b'], {}), '(a, b)\n', (945, 951), False, 'import sublime\n')] |
import gzip
import io
import logging
import os
import six
import arff
import numpy as np
import scipy.sparse
from six.moves import cPickle as pickle
import xmltodict
from .data_feature import OpenMLDataFeature
from ..exceptions import PyOpenMLError
from .._api_calls import _perform_api_call
logger = logging.getLogg... | [
"logging.getLogger",
"struct.calcsize",
"os.path.exists",
"os.path.getsize",
"xmltodict.parse",
"gzip.open",
"six.moves.cPickle.load",
"arff.ArffDecoder",
"six.moves.cPickle.dump",
"io.open",
"numpy.array",
"numpy.sum",
"sys.stdout.flush",
"six.moves.zip"
] | [((305, 332), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (322, 332), False, 'import logging\n'), ((6772, 6792), 'struct.calcsize', 'struct.calcsize', (['"""P"""'], {}), "('P')\n", (6787, 6792), False, 'import struct\n'), ((7200, 7218), 'arff.ArffDecoder', 'arff.ArffDecoder', ([], {}),... |
from pyx import canvas, color, deco, path, text, trafo, unit
text.set(text.LatexRunner)
color0 = color.rgb(0.8, 0, 0)
color1 = color.rgb(0, 0, 0.8)
text.preamble(r'\usepackage[sfdefault,scaled=.85,lining]{FiraSans}\usepackage{newtxsf}')
text.preamble(r'\usepackage{color}')
text.preamble(r'\definecolor{axis0}{rgb}{%s, ... | [
"pyx.text.set",
"pyx.text.preamble",
"pyx.unit.set",
"pyx.trafo.rotate",
"pyx.color.rgb",
"pyx.canvas.canvas"
] | [((62, 88), 'pyx.text.set', 'text.set', (['text.LatexRunner'], {}), '(text.LatexRunner)\n', (70, 88), False, 'from pyx import canvas, color, deco, path, text, trafo, unit\n'), ((98, 118), 'pyx.color.rgb', 'color.rgb', (['(0.8)', '(0)', '(0)'], {}), '(0.8, 0, 0)\n', (107, 118), False, 'from pyx import canvas, color, dec... |
import pathlib
import warnings
import numpy as np
import pytest
import xarray as xr
from tests.fixtures import generate_dataset
from xcdat.dataset import (
_has_cf_compliant_time,
_keep_single_var,
_postprocess_dataset,
_preprocess_non_cf_dataset,
_split_time_units_attr,
decode_non_cf_time,
... | [
"numpy.array",
"xcdat.dataset._postprocess_dataset",
"pytest.fixture",
"xcdat.dataset.open_mfdataset",
"pathlib.Path",
"numpy.datetime64",
"warnings.simplefilter",
"numpy.dtype",
"xcdat.dataset._preprocess_non_cf_dataset",
"xarray.Dataset",
"xcdat.dataset.open_dataset",
"xcdat.dataset.decode_n... | [((413, 465), 'xcdat.logger.setup_custom_logger', 'setup_custom_logger', (['"""xcdat.dataset"""'], {'propagate': '(True)'}), "('xcdat.dataset', propagate=True)\n", (432, 465), False, 'from xcdat.logger import setup_custom_logger\n'), ((496, 524), 'pytest.fixture', 'pytest.fixture', ([], {'autouse': '(True)'}), '(autous... |
# Copyright 2017 BBVA
#
# 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, softwar... | [
"datarefinery.FieldOperations.replace_if_else"
] | [((837, 872), 'datarefinery.FieldOperations.replace_if_else', 'replace_if_else', (['_fn_cond', '_fn_then'], {}), '(_fn_cond, _fn_then)\n', (852, 872), False, 'from datarefinery.FieldOperations import replace_if_else\n'), ((1174, 1219), 'datarefinery.FieldOperations.replace_if_else', 'replace_if_else', (['_fn_cond', '_f... |
# Copyright (c) 2021 PaddlePaddle 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 app... | [
"json.load"
] | [((900, 912), 'json.load', 'json.load', (['f'], {}), '(f)\n', (909, 912), False, 'import json\n')] |
from django.db import models
from django.urls import reverse
from django.contrib.auth.models import AbstractUser
from django.templatetags.static import static
from .constants import CHAR_FIELD_MAX_LENGTH
class User(AbstractUser):
github_url = models.CharField(max_length=CHAR_FIELD_MAX_LENGTH, blank=True)
pro... | [
"django.urls.reverse",
"django.templatetags.static.static",
"django.db.models.CharField",
"django.db.models.BooleanField"
] | [((250, 312), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': 'CHAR_FIELD_MAX_LENGTH', 'blank': '(True)'}), '(max_length=CHAR_FIELD_MAX_LENGTH, blank=True)\n', (266, 312), False, 'from django.db import models\n'), ((337, 399), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '... |
from collections import Counter, defaultdict
import random
from words import *
from colorama import init, Back, Fore
from termcolor import colored
init(autoreset=True)
log_enabled = False
def init_wordle_ai(num_vowels, logging):
global wordle_len
global answer
global num_guesses
global words_guessed
... | [
"collections.Counter",
"collections.defaultdict",
"random.randint",
"colorama.init"
] | [((148, 168), 'colorama.init', 'init', ([], {'autoreset': '(True)'}), '(autoreset=True)\n', (152, 168), False, 'from colorama import init, Back, Fore\n'), ((4541, 4557), 'collections.defaultdict', 'defaultdict', (['int'], {}), '(int)\n', (4552, 4557), False, 'from collections import Counter, defaultdict\n'), ((4758, 47... |
from django.shortcuts import render,get_object_or_404
from blog.models import PostModel
from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger
# Create your views here.
def blog_view(request,**kwargs):
posts = PostModel.objects.filter(status=1)
if kwargs.get('cat_name')!=None :
posts... | [
"django.shortcuts.render",
"django.shortcuts.get_object_or_404",
"blog.models.PostModel.objects.filter",
"django.core.paginator.Paginator"
] | [((234, 268), 'blog.models.PostModel.objects.filter', 'PostModel.objects.filter', ([], {'status': '(1)'}), '(status=1)\n', (258, 268), False, 'from blog.models import PostModel\n'), ((525, 544), 'django.core.paginator.Paginator', 'Paginator', (['posts', '(3)'], {}), '(posts, 3)\n', (534, 544), False, 'from django.core.... |
"""
Copyright (c) 2022, Magentix
This code is licensed under simplified BSD license (see LICENSE for details)
StaPy JsMin Plugin - Version 1.0.0
Requirements:
- jsmin
"""
from pathlib import Path
import jsmin
import os
def file_content_opened(content, args: dict) -> str:
if _get_file_extension(args['path']) != '... | [
"os.path.splitext",
"os.path.realpath",
"os.path.dirname",
"os.path.normpath",
"os.path.basename"
] | [((1498, 1520), 'os.path.splitext', 'os.path.splitext', (['file'], {}), '(file)\n', (1514, 1520), False, 'import os\n'), ((1075, 1096), 'os.path.dirname', 'os.path.dirname', (['path'], {}), '(path)\n', (1090, 1096), False, 'import os\n'), ((1231, 1257), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__fi... |
from functools import partial
from . import utils
import numpy as np
import jax.numpy as jnp
import jax.random as random
from jax import grad, jit, vmap, lax, jacrev, jacfwd, jvp, vjp, hessian
#class Lattice(seed, cell_params, sim_params,
def random_c0(subkeys, odds_c, n):
"""Make random initial conditions g... | [
"numpy.sqrt",
"jax.lax.fori_loop",
"jax.numpy.log",
"numpy.array",
"jax.numpy.matmul",
"numpy.arange",
"jax.random.split",
"jax.numpy.eye",
"numpy.ndim",
"numpy.linspace",
"numpy.random.normal",
"jax.random.uniform",
"numpy.add.outer",
"jax.numpy.logical_xor",
"jax.numpy.ones",
"jax.vm... | [((3941, 4018), 'jax.vmap', 'vmap', (['local_alignment_change'], {'in_axes': '(None, None, None, None, 0, None, None)'}), '(local_alignment_change, in_axes=(None, None, None, None, 0, None, None))\n', (3945, 4018), False, 'from jax import grad, jit, vmap, lax, jacrev, jacfwd, jvp, vjp, hessian\n'), ((4794, 4832), 'func... |
#!/usr/bin/env python
# Copyright 2021 <NAME>
# License: Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
import torch as th
import torch.nn as nn
import torch.nn.functional as tf
from typing import Optional, Dict
from aps.libs import Register
from aps.asr.transformer.impl import RelMultiheadAttention
from ap... | [
"aps.libs.Register",
"torch.nn.LayerNorm",
"torch.tensor",
"torch.einsum",
"torch.nn.functional.pad",
"torch.cat"
] | [((463, 503), 'aps.libs.Register', 'Register', (['"""streaming_xfmr_encoder_layer"""'], {}), "('streaming_xfmr_encoder_layer')\n", (471, 503), False, 'from aps.libs import Register\n'), ((1336, 1348), 'torch.tensor', 'th.tensor', (['(0)'], {}), '(0)\n', (1345, 1348), True, 'import torch as th\n'), ((1372, 1384), 'torch... |
import unittest, os, sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../..')))
from generators import MarkdownGenerator
class TestMarkdownGenerator(unittest.TestCase):
results_folder = f"{os.path.dirname(os.path.abspath(__file__))}/test_results_dir"
ignorelist = [
{
... | [
"unittest.main",
"os.path.dirname",
"generators.MarkdownGenerator.MarkdownGenerator",
"os.path.abspath"
] | [((17456, 17471), 'unittest.main', 'unittest.main', ([], {}), '()\n', (17469, 17471), False, 'import unittest, os, sys\n'), ((704, 1213), 'generators.MarkdownGenerator.MarkdownGenerator', 'MarkdownGenerator.MarkdownGenerator', (['[TestMarkdownGenerator.results_folder]'], {'snapshot': '"""TEST_SNAPSHOT"""', 'branch': '"... |
#!/usr/bin/env python
import sys
import re
import despydmdb.desdmdbi as desdmdbi
import despymisc.miscutils as miscutils
def delete_using_run_vals(dbh, tablename, reqnum, unitname, attnum, verbose=0):
if verbose >= 1:
print("%25s" % tablename, end=' ')
sql = "delete from %s where unitname='%s' and r... | [
"despydmdb.desdmdbi.DesDmDbi",
"sys.exit",
"sys.stdin.read",
"despymisc.miscutils.pretty_print_dict",
"re.search"
] | [((5742, 5784), 're.search', 're.search', (['"""([^_]+)_r([^p]+)p([^_]+)"""', 'run'], {}), "('([^_]+)_r([^p]+)p([^_]+)', run)\n", (5751, 5784), False, 'import re\n'), ((6067, 6086), 'despydmdb.desdmdbi.DesDmDbi', 'desdmdbi.DesDmDbi', ([], {}), '()\n', (6084, 6086), True, 'import despydmdb.desdmdbi as desdmdbi\n'), ((63... |
import logging
import math
logging.basicConfig(level=logging.DEBUG,
handlers=[logging.FileHandler('logs.log', 'a', 'utf-8')],
format="%(asctime)s %(levelname)-6s - %(funcName)-8s - %(filename)s - %(lineno)-3d - %(message)s",
datefmt="[%Y-%m-%d] %H:%M:%S - ",
... | [
"logging.debug",
"math.sqrt",
"logging.exception",
"logging.FileHandler",
"logging.info"
] | [((343, 378), 'logging.info', 'logging.info', (['"""This is an info log"""'], {}), "('This is an info log')\n", (355, 378), False, 'import logging\n'), ((404, 452), 'logging.debug', 'logging.debug', (['f"""Getting the square root of {x}"""'], {}), "(f'Getting the square root of {x}')\n", (417, 452), False, 'import logg... |
import os
import platform
import textwrap
import pytest
from conans.test.utils.tools import TestClient
@pytest.mark.skipif(platform.system() != "Darwin", reason="Only for MacOS")
@pytest.mark.tool_cmake
@pytest.mark.tool_xcodebuild
@pytest.mark.tool_xcodegen
def test_xcodedeps_components():
"""
tcp/1.0 is a... | [
"conans.test.utils.tools.TestClient",
"platform.system",
"os.path.join",
"textwrap.dedent"
] | [((821, 855), 'conans.test.utils.tools.TestClient', 'TestClient', ([], {'path_with_spaces': '(False)'}), '(path_with_spaces=False)\n', (831, 855), False, 'from conans.test.utils.tools import TestClient\n'), ((950, 1026), 'textwrap.dedent', 'textwrap.dedent', (['"""\n #pragma once\n void {name}();\n ... |
import jieba
import jieba.analyse
import six
import re
import operator
import io
import jieba.posseg as pseg
def is_number(s):
try:
float(s) if '.' in s else int(s)
return True
except ValueError:
return False
def load_stop_words(stop_word_file):
"""
Utility function to load s... | [
"re.split",
"jieba.cut",
"jieba.posseg.cut",
"io.open",
"jieba.analyse.get_idf_jieba",
"operator.itemgetter",
"re.sub",
"six.iteritems"
] | [((1133, 1163), 'jieba.cut', 'jieba.cut', (['text'], {'cut_all': '(False)'}), '(text, cut_all=False)\n', (1142, 1163), False, 'import jieba\n'), ((1905, 1933), 're.split', 're.split', (['regexPattern', 'text'], {}), '(regexPattern, text)\n', (1913, 1933), False, 'import re\n'), ((2733, 2749), 'jieba.posseg.cut', 'pseg.... |
from typing import TYPE_CHECKING, Iterable, Iterator
import logging
from shapely.geometry import shape, mapping
from shapely.strtree import STRtree
from rastervision.core.data import ActivateMixin, RasterizedSource
from rastervision.core.data.vector_source import GeoJSONVectorSourceConfig
from rastervision.core.evalu... | [
"logging.getLogger",
"rastervision.core.data.vector_source.GeoJSONVectorSourceConfig",
"shapely.geometry.mapping",
"rastervision.core.evaluation.SemanticSegmentationEvaluation",
"shapely.geometry.shape",
"rastervision.core.data.ActivateMixin.compose"
] | [((440, 467), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (457, 467), False, 'import logging\n'), ((1808, 1857), 'rastervision.core.evaluation.SemanticSegmentationEvaluation', 'SemanticSegmentationEvaluation', (['self.class_config'], {}), '(self.class_config)\n', (1838, 1857), False, '... |
import json
import argparse
from prepare_data import setup
# Support command-line options
parser = argparse.ArgumentParser()
parser.add_argument('--big-model', action='store_true', help='Use the bigger model with more conv layers')
parser.add_argument('--use-data-dir', action='store_true', help='Use custom data direct... | [
"numpy.savez",
"argparse.ArgumentParser",
"prepare_data.setup"
] | [((100, 125), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (123, 125), False, 'import argparse\n'), ((594, 618), 'prepare_data.setup', 'setup', (['args.use_data_dir'], {}), '(args.use_data_dir)\n', (599, 618), False, 'from prepare_data import setup\n'), ((1072, 1310), 'numpy.savez', 'np.savez... |
from tabcmd.execution.logger_config import log
from tabcmd.parsers.refresh_extracts_parser import RefreshExtractsParser
import tableauserverclient as TSC
from tabcmd.execution.logger_config import log
from ..auth.session import Session
from ..extracts.extracts_command import ExtractsCommand
class RefreshExtracts(Extr... | [
"tabcmd.execution.logger_config.log",
"tabcmd.parsers.refresh_extracts_parser.RefreshExtractsParser.refresh_extracts_parser"
] | [((519, 566), 'tabcmd.parsers.refresh_extracts_parser.RefreshExtractsParser.refresh_extracts_parser', 'RefreshExtractsParser.refresh_extracts_parser', ([], {}), '()\n', (564, 566), False, 'from tabcmd.parsers.refresh_extracts_parser import RefreshExtractsParser\n'), ((632, 665), 'tabcmd.execution.logger_config.log', 'l... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# BCDI: tools for pre(post)-processing Bragg coherent X-ray diffraction imaging data
# (c) 07/2017-06/2019 : CNRS UMR 7344 IM2NP
# (c) 07/2019-present : DESY PHOTON SCIENCE
# authors:
# <NAME>, <EMAIL>
try:
import hdf5plugin # for P10, should be im... | [
"numpy.sqrt",
"matplotlib.pyplot.ylabel",
"bcdi.graph.colormap.ColormapFactory",
"scipy.interpolate.interp1d",
"scipy.ndimage.measurements.center_of_mass",
"sys.exit",
"matplotlib.pyplot.imshow",
"pathlib.Path",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.fft.fftn",
"numpy.dif... | [((2623, 2632), 'matplotlib.pyplot.ion', 'plt.ion', ([], {}), '()\n', (2630, 2632), True, 'from matplotlib import pyplot as plt\n'), ((2640, 2647), 'tkinter.Tk', 'tk.Tk', ([], {}), '()\n', (2645, 2647), True, 'import tkinter as tk\n'), ((2676, 2797), 'tkinter.filedialog.askopenfilename', 'filedialog.askopenfilename', (... |
from typing import Any, Mapping, Optional, Union
import copy
import os
import re
import yaml
from machinable.errors import ConfigurationError
from machinable.utils import sentinel, unflatten_dict, update_dict
class Loader(yaml.SafeLoader):
def __init__(self, stream, cwd="./"):
if isinstance(stream, str)... | [
"os.path.isabs",
"re.compile",
"machinable.errors.ConfigurationError",
"machinable.utils.update_dict",
"os.path.join",
"os.path.split",
"os.path.isfile",
"os.path.dirname",
"copy.deepcopy",
"machinable.utils.unflatten_dict"
] | [((936, 965), 're.compile', 're.compile', (['"""\\\\$\\\\/([^#^ ]*)"""'], {}), "('\\\\$\\\\/([^#^ ]*)')\n", (946, 965), False, 'import re\n'), ((1081, 1385), 're.compile', 're.compile', (['"""^(?:\n [-+]?(?:[0-9][0-9_]*)\\\\.[0-9_]*(?:[eE][-+]?[0-9]+)?\n |[-+]?(?:[0-9][0-9_]*)(?:[eE][-+]?[0-9]+)\n ... |
"""Redis backends for sessions."""
from datetime import timedelta
from json import dumps, loads
from secrets import token_hex
from time import time
from typing import TYPE_CHECKING, Annotated, Optional, TypeVar
from attrs import frozen
from .. import App, Cookie, Headers
from ..cookies import CookieSettings, set_coo... | [
"secrets.token_hex",
"json.loads",
"json.dumps",
"datetime.timedelta",
"time.time",
"typing.TypeVar"
] | [((380, 393), 'typing.TypeVar', 'TypeVar', (['"""T1"""'], {}), "('T1')\n", (387, 393), False, 'from typing import TYPE_CHECKING, Annotated, Optional, TypeVar\n'), ((399, 412), 'typing.TypeVar', 'TypeVar', (['"""T2"""'], {}), "('T2')\n", (406, 412), False, 'from typing import TYPE_CHECKING, Annotated, Optional, TypeVar\... |
from typing import Tuple
import numpy as np
class ParallelEnv:
def __init__(self, envs):
self.env = envs
self.num_envs = len(envs)
self.seed(0)
def seed(self, seed: int):
[env.seed(seed + idx) for idx, env in enumerate(self.env)]
def reset(self) -> np.ndarray:
s ... | [
"numpy.concatenate"
] | [((368, 393), 'numpy.concatenate', 'np.concatenate', (['s'], {'axis': '(0)'}), '(s, axis=0)\n', (382, 393), True, 'import numpy as np\n'), ((725, 750), 'numpy.concatenate', 'np.concatenate', (['s'], {'axis': '(0)'}), '(s, axis=0)\n', (739, 750), True, 'import numpy as np\n'), ((763, 788), 'numpy.concatenate', 'np.conca... |
from pathlib import Path
import joblib
class Loader:
@staticmethod
def load_model(path:str):
p = Path(path)
joblib.load(p) | [
"joblib.load",
"pathlib.Path"
] | [((114, 124), 'pathlib.Path', 'Path', (['path'], {}), '(path)\n', (118, 124), False, 'from pathlib import Path\n'), ((133, 147), 'joblib.load', 'joblib.load', (['p'], {}), '(p)\n', (144, 147), False, 'import joblib\n')] |
from datetime import datetime
from elasticsearch import Elasticsearch,helpers
import csv
import json
def actions_generator(elastic_instance,index_name,bulk_function, data):
def generator():
size = len(data)
for i in range(size):
yield{
'_index': index_name,
... | [
"csv.DictReader"
] | [((648, 665), 'csv.DictReader', 'csv.DictReader', (['f'], {}), '(f)\n', (662, 665), False, 'import csv\n')] |
# <auto-generated>
# This code was generated by the UnitCodeGenerator tool
#
# Changes to this file will be lost if the code is regenerated
# </auto-generated>
import unittest
import units.pressure.pascals
class TestPascalsMethods(unittest.TestCase):
def test_convert_known_pascals_to_atmospheres(self):
self.asser... | [
"unittest.main"
] | [((1528, 1543), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1541, 1543), False, 'import unittest\n')] |
# IMPORTS
import hashlib
import re
import csv
from random import choice
CHARACTERS = 'ACEFGHJKLMNPRTUVWXY379'
# FUNCTIONS
def random_code(digits):
# All possibilities, except the letters and numbers that can
# be confusing ( 0 and O, etc )
digits = [choice(CHARACTERS) for _ in range(digits)]
return '... | [
"csv.writer",
"hashlib.sha256",
"random.choice",
"re.match"
] | [((373, 389), 'hashlib.sha256', 'hashlib.sha256', ([], {}), '()\n', (387, 389), False, 'import hashlib\n'), ((674, 694), 're.match', 're.match', (['CODE', 'code'], {}), '(CODE, code)\n', (682, 694), False, 'import re\n'), ((265, 283), 'random.choice', 'choice', (['CHARACTERS'], {}), '(CHARACTERS)\n', (271, 283), False,... |
def gen_snpid(chr, pos, a1, a2, build):
res = []
for x1, x2, x3, x4 in zip(chr, pos, a1, a2):
res.append(f'chr{x1}_{x2}_{x3}_{x4}_{build}')
return res
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(prog='gen_lookup_table.py', description='''
Generate loo... | [
"logging.basicConfig",
"argparse.ArgumentParser",
"pandas.read_csv",
"pandas.merge",
"pyutil.load_list",
"lib.liftover",
"logging.info"
] | [((232, 489), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'prog': '"""gen_lookup_table.py"""', 'description': '"""\n Generate lookup table for HapMap SNP list.\n CAUTION: Need to have path to \n misc-tools/liftover_snp and misc-tools/pyutil\n in the PYTHONPATH!\n """'}), '... |
import os
import pickle
from typing import List, Optional, Dict, Union, Any
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from .logger import Log
class GMailAPI:
"""Methods for establishing and building a store... | [
"os.path.exists",
"pickle.dump",
"google.auth.transport.requests.Request",
"pickle.load",
"os.path.join",
"google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file"
] | [((592, 639), 'os.path.join', 'os.path.join', (['"""creds"""', '"""gmail-credentials.json"""'], {}), "('creds', 'gmail-credentials.json')\n", (604, 639), False, 'import os\n'), ((666, 703), 'os.path.join', 'os.path.join', (['"""creds"""', '"""token.pickle"""'], {}), "('creds', 'token.pickle')\n", (678, 703), False, 'im... |
import time
import numpy as np
from PIL import Image as pil_image
from keras.preprocessing.image import save_img
from keras import layers
from keras.applications import vgg16
from keras import backend as K
import matplotlib.pyplot as plt
def normalize(x):
"""utility function to normalize a tensor.
# Argument... | [
"numpy.clip",
"keras.applications.vgg16.VGG16",
"keras.backend.gradients",
"matplotlib.pyplot.imshow",
"keras.backend.image_data_format",
"numpy.random.random",
"keras.backend.square",
"numpy.diff",
"keras.backend.epsilon",
"numpy.abs",
"numpy.random.randn",
"time.time",
"matplotlib.pyplot.s... | [((903, 919), 'numpy.clip', 'np.clip', (['x', '(0)', '(1)'], {}), '(x, 0, 1)\n', (910, 919), True, 'import numpy as np\n'), ((10772, 10822), 'keras.applications.vgg16.VGG16', 'vgg16.VGG16', ([], {'weights': '"""imagenet"""', 'include_top': '(False)'}), "(weights='imagenet', include_top=False)\n", (10783, 10822), False,... |
#! /usr/bin/env python3
# __author__ = "<NAME>"
# __credits__ = []
# __version__ = "0.1.1"
# __maintainer__ = "<NAME>"
# __email__ = "<EMAIL>"
# __status__ = "Prototype"
from qs_backend.models.stock_model import StockModel
from qs_backend.dal.user_stock_pref_dal import UserStockPrefDAL
from qs_back... | [
"qs_backend.dal.user_stock_pref_dal.UserStockPrefDAL",
"qs_backend.decorators.temp.users_topic_manager.UserTopicManager"
] | [((479, 497), 'qs_backend.dal.user_stock_pref_dal.UserStockPrefDAL', 'UserStockPrefDAL', ([], {}), '()\n', (495, 497), False, 'from qs_backend.dal.user_stock_pref_dal import UserStockPrefDAL\n'), ((2709, 2727), 'qs_backend.decorators.temp.users_topic_manager.UserTopicManager', 'UserTopicManager', ([], {}), '()\n', (272... |
# 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
# d... | [
"neutron.common.exceptions.TenantIdProjectIdFilterConflict",
"copy.deepcopy"
] | [((670, 691), 'copy.deepcopy', 'copy.deepcopy', (['kwargs'], {}), '(kwargs)\n', (683, 691), False, 'import copy\n'), ((775, 819), 'neutron.common.exceptions.TenantIdProjectIdFilterConflict', 'exceptions.TenantIdProjectIdFilterConflict', ([], {}), '()\n', (817, 819), False, 'from neutron.common import exceptions\n')] |
import random
import xarray as xr
import numpy as np
import scipy as sp
import networkx as nx
from collections import deque
from skimage.morphology import cube
from scipy.interpolate import interp1d
from statsmodels.distributions.empirical_distribution import ECDF
from joblib import Parallel, delayed
def label_functi... | [
"random.sample",
"collections.deque",
"numpy.unique",
"numpy.random.rand",
"numpy.float64",
"scipy.ndimage.find_objects",
"networkx.Graph",
"scipy.interpolate.interp1d",
"joblib.Parallel",
"numpy.array",
"numpy.any",
"statsmodels.distributions.empirical_distribution.ECDF",
"numpy.random.rand... | [((419, 426), 'collections.deque', 'deque', ([], {}), '()\n', (424, 426), False, 'from collections import deque\n'), ((587, 615), 'numpy.unique', 'np.unique', (['pore_object[mask]'], {}), '(pore_object[mask])\n', (596, 615), True, 'import numpy as np\n'), ((966, 978), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', ... |
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and its affiliates. All Rights Reserved
import math
from typing import Optional, Tuple
import torch
import torch.nn as nn
Past = Tuple[torch.Tensor, torch.Tensor]
class BaseAttention(nn.Module):
"""
Tensor Type Shape
======... | [
"torch.nn.Dropout",
"torch.nn.Softmax",
"torch.tensor",
"torch.matmul",
"torch.nn.Linear",
"torch.cat",
"torch.ones"
] | [((982, 1001), 'torch.nn.Dropout', 'nn.Dropout', (['dropout'], {}), '(dropout)\n', (992, 1001), True, 'import torch.nn as nn\n'), ((2270, 2288), 'torch.matmul', 'torch.matmul', (['x', 'v'], {}), '(x, v)\n', (2282, 2288), False, 'import torch\n'), ((4884, 4905), 'torch.nn.Linear', 'nn.Linear', (['dims', 'dims'], {}), '(... |
from django.db import models
from django.utils.timezone import now
# Create your models here.
class ErrorLog(models.Model):
""" возникшие ошибки с полным описанием """
url = models.CharField(max_length=250, verbose_name='Url, где произошла ошибка')
exception_name = models.CharField(max_length=250, verbose... | [
"django.db.models.DateTimeField",
"django.db.models.TextField",
"django.db.models.CharField"
] | [((184, 258), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(250)', 'verbose_name': '"""Url, где произошла ошибка"""'}), "(max_length=250, verbose_name='Url, где произошла ошибка')\n", (200, 258), False, 'from django.db import models\n'), ((280, 343), 'django.db.models.CharField', 'models.CharF... |
import torch
import torch.nn as nn
import torch.autograd as autograd
# user-defined loss function: standard L1 loss
class MyL1Loss(nn.Module):
def __init__(self):
super(MyL1Loss, self).__init__()
def forward(self, Generate, Original):
# to train on CPU, make sure to call contiguous() on x and... | [
"torch.abs",
"torch.mean",
"torch.cuda.is_available",
"torch.autograd.grad",
"torch.rand"
] | [((2233, 2264), 'torch.rand', 'torch.rand', (['batch_size', '(1)', '(1)', '(1)'], {}), '(batch_size, 1, 1, 1)\n', (2243, 2264), False, 'import torch\n'), ((669, 685), 'torch.abs', 'torch.abs', (['(x - y)'], {}), '(x - y)\n', (678, 685), False, 'import torch\n'), ((1331, 1348), 'torch.mean', 'torch.mean', (['Error'], {}... |
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from . import Base
class Chrome(Base):
def get_options(self):
return Options()
def boot_driver(self):
self.log.debug("chrome: %s", self.browser_args)
return webdriver.Chrome(**self.browser_args)
... | [
"selenium.webdriver.chrome.options.Options",
"selenium.webdriver.Chrome"
] | [((168, 177), 'selenium.webdriver.chrome.options.Options', 'Options', ([], {}), '()\n', (175, 177), False, 'from selenium.webdriver.chrome.options import Options\n'), ((277, 314), 'selenium.webdriver.Chrome', 'webdriver.Chrome', ([], {}), '(**self.browser_args)\n', (293, 314), False, 'from selenium import webdriver\n')... |
# Copyright (c) 2021 aerocyber
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
import os
import json
import hashlib
"""Decode and decrypt .omio file which contain osmations."""
class InValidOMIO(Exception):
"""Exception raised if the .omio file is invalid.
Args:
... | [
"json.load",
"hashlib.sha256",
"os.path.normcase"
] | [((1177, 1189), 'json.load', 'json.load', (['f'], {}), '(f)\n', (1186, 1189), False, 'import json\n'), ((1030, 1057), 'os.path.normcase', 'os.path.normcase', (['OMIO_Path'], {}), '(OMIO_Path)\n', (1046, 1057), False, 'import os\n'), ((1833, 1853), 'hashlib.sha256', 'hashlib.sha256', (['data'], {}), '(data)\n', (1847, 1... |
# math3d_sphere.py
import math
from math3d_side import Side
from math3d_vector import Vector
class Sphere(object):
def __init__(self, center, radius):
self.center = center
self.radius = radius
def clone(self):
return Sphere(self.center, self.radius)
def side(self, point, eps=1e-... | [
"math3d_triangle.Triangle",
"math3d_triangle_mesh.TriangleMesh.make_polyhedron"
] | [((829, 881), 'math3d_triangle_mesh.TriangleMesh.make_polyhedron', 'TriangleMesh.make_polyhedron', (['Polyhedron.ICOSAHEDRON'], {}), '(Polyhedron.ICOSAHEDRON)\n', (857, 881), False, 'from math3d_triangle_mesh import TriangleMesh, Polyhedron\n'), ((1448, 1458), 'math3d_triangle.Triangle', 'Triangle', ([], {}), '()\n', (... |
import numpy as np
import matplotlib
import pylab as pl
import pandas
from ae_measure2 import *
from feature_extraction import *
import glob
import os
import pandas as pd
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
from sklearn.metrics import davies_bouldin_score
from sklearn.pr... | [
"sklearn.cluster.KMeans",
"numpy.hstack",
"numpy.where",
"sklearn.metrics.adjusted_rand_score",
"sklearn.preprocessing.StandardScaler",
"numpy.vstack"
] | [((607, 641), 'sklearn.cluster.KMeans', 'KMeans', ([], {'n_clusters': 'k', 'n_init': '(20000)'}), '(n_clusters=k, n_init=20000)\n', (613, 641), False, 'from sklearn.cluster import KMeans\n'), ((878, 894), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (892, 894), False, 'from sklearn.prepro... |
'''
create_schemas.py does the following:
* Creates a database named steam_recommender if it does not exist within a local instance of PostgreSQL
* Creates schemas for our set of csv data in steam_recommender
requirements:
* in lines 24 and 27 you need to specify the file paths to the csv source files
* import your Po... | [
"os.listdir",
"sqlalchemy_utils.database_exists",
"pandas.read_csv",
"sqlalchemy.create_engine",
"os.path.join",
"sqlalchemy_utils.create_database"
] | [((844, 955), 'sqlalchemy.create_engine', 'create_engine', (['f"""postgresql+psycopg2://{user_name}:{password}@localhost/Steam_Recommender"""'], {'echo': '(True)'}), "(\n f'postgresql+psycopg2://{user_name}:{password}@localhost/Steam_Recommender'\n , echo=True)\n", (857, 955), False, 'from sqlalchemy import creat... |
# Generated by Django 3.1.8 on 2021-08-28 02:17
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('stations', '0010_auto_20210322_2029'),
]
operations = [
migrations.RemoveField(
model_name='station',
name='lat',
),... | [
"django.db.migrations.DeleteModel",
"django.db.migrations.RemoveField"
] | [((228, 284), 'django.db.migrations.RemoveField', 'migrations.RemoveField', ([], {'model_name': '"""station"""', 'name': '"""lat"""'}), "(model_name='station', name='lat')\n", (250, 284), False, 'from django.db import migrations\n'), ((329, 385), 'django.db.migrations.RemoveField', 'migrations.RemoveField', ([], {'mode... |
from analizer.abstract.expression import Expression
from analizer.abstract.expression import TYPE
from analizer.statement.expressions import code
class Ternary(Expression):
def __init__(self,temp1,temp2, exp1, exp2, exp3, operator, row, column):
super().__init__(row, column)
self.temp1 = temp1
... | [
"analizer.statement.expressions.code.C3D"
] | [((678, 717), 'analizer.statement.expressions.code.C3D', 'code.C3D', (['""""""', '""""""', 'self.row', 'self.column'], {}), "('', '', self.row, self.column)\n", (686, 717), False, 'from analizer.statement.expressions import code\n'), ((1318, 1365), 'analizer.statement.expressions.code.C3D', 'code.C3D', (['self.temp', '... |
#
# Copyright 2022 Red Hat Inc.
# SPDX-License-Identifier: Apache-2.0
#
import logging
import os
import psycopg2
from psycopg2.extras import RealDictCursor
RELEASE = 0
MAJOR = 1
MINOR = 2
TERMINATE_ACTION = "terminate"
CANCEL_ACTION = "cancel"
SERVER_VERSION = []
LOG = logging.getLogger(__name__)
class DBPerfor... | [
"logging.getLogger",
"psycopg2.connect"
] | [((276, 303), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (293, 303), False, 'import logging\n'), ((1854, 1914), 'psycopg2.connect', 'psycopg2.connect', ([], {'cursor_factory': 'RealDictCursor'}), '(cursor_factory=RealDictCursor, **conn_args)\n', (1870, 1914), False, 'import psycopg2\n... |
# 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
# d... | [
"opflexagent.gbp_agent.create_agent_config_map",
"mock.Mock",
"opflexagent.utils.port_managers.async_port_manager.AsyncPortManager",
"oslo_config.cfg.CONF.set_default",
"mock.call",
"oslo_config.cfg.CONF.register_opts"
] | [((622, 633), 'mock.Mock', 'mock.Mock', ([], {}), '()\n', (631, 633), False, 'import mock\n'), ((661, 672), 'mock.Mock', 'mock.Mock', ([], {}), '()\n', (670, 672), False, 'import mock\n'), ((1053, 1098), 'oslo_config.cfg.CONF.register_opts', 'cfg.CONF.register_opts', (['dhcp_config.DHCP_OPTS'], {}), '(dhcp_config.DHCP_... |
# 从 https://github.com/Vonng/adcode/tree/master/data/adcode 同步需要的数据
import requests
import json
import base64
from io import StringIO
import csv
from progress.bar import Bar
adcode_dir_url = "https://api.github.com/repos/Vonng/adcode/git/trees/55df6cf713cdac2ac5220c972edf68553d2d4afa"
# 代表整个中国 adcode
china_base_adcod... | [
"csv.writer",
"base64.b64decode",
"requests.get",
"io.StringIO",
"csv.reader"
] | [((368, 436), 'requests.get', 'requests.get', (['url'], {'timeout': '(30)', 'headers': "{'user-agent': 'Mozilla/5.0'}"}), "(url, timeout=30, headers={'user-agent': 'Mozilla/5.0'})\n", (380, 436), False, 'import requests\n'), ((678, 691), 'csv.writer', 'csv.writer', (['f'], {}), '(f)\n', (688, 691), False, 'import csv\n... |
import pickle
import suite
model = pickle.loads(open("pretrained_model.p","rb").read())
def predict_text(text):
return suite.get_prediction(text,model)
| [
"suite.get_prediction"
] | [((122, 155), 'suite.get_prediction', 'suite.get_prediction', (['text', 'model'], {}), '(text, model)\n', (142, 155), False, 'import suite\n')] |
import os
from pathlib import Path
from bauh.api.constants import CACHE_PATH, CONFIG_PATH, TEMP_DIR
from bauh.commons import resource
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
BUILD_DIR = '{}/arch'.format(TEMP_DIR)
ARCH_CACHE_PATH = CACHE_PATH + '/arch'
CATEGORIES_FILE_PATH = ARCH_CACHE_PATH + '/categorie... | [
"os.path.abspath",
"pathlib.Path.home",
"bauh.commons.resource.get_path"
] | [((163, 188), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (178, 188), False, 'import os\n'), ((475, 486), 'pathlib.Path.home', 'Path.home', ([], {}), '()\n', (484, 486), False, 'from pathlib import Path\n'), ((792, 835), 'bauh.commons.resource.get_path', 'resource.get_path', (['"""img/arch... |
import epydemic
import networkx as nx
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
class MonitoredSIR(epydemic.SIR):
INTERVAL = 'interval'
PROGRESS = 'progress'
def setUp(self, params):
"""Schedule the monitoring event.
:param pa... | [
"matplotlib.pyplot.plot",
"networkx.erdos_renyi_graph",
"matplotlib.pyplot.subplot",
"networkx.draw",
"matplotlib.pyplot.show"
] | [((1339, 1367), 'networkx.erdos_renyi_graph', 'nx.erdos_renyi_graph', (['N', 'phi'], {}), '(N, phi)\n', (1359, 1367), True, 'import networkx as nx\n'), ((1478, 1494), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(121)'], {}), '(121)\n', (1489, 1494), True, 'import matplotlib.pyplot as plt\n'), ((1500, 1521), 'network... |
import os
import subprocess
CLUSTAL_PATH = os.environ.get("CLUSTAL_PATH")
def cmd(command):
process = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True,
)
out, error = process.communicate()
print(out, error)
return out, error
d... | [
"subprocess.Popen",
"os.environ.get"
] | [((44, 74), 'os.environ.get', 'os.environ.get', (['"""CLUSTAL_PATH"""'], {}), "('CLUSTAL_PATH')\n", (58, 74), False, 'import os\n'), ((109, 198), 'subprocess.Popen', 'subprocess.Popen', (['command'], {'stdout': 'subprocess.PIPE', 'stderr': 'subprocess.PIPE', 'shell': '(True)'}), '(command, stdout=subprocess.PIPE, stder... |
"""Urls for the Zinnia authors"""
from django.conf.urls import url
from django.conf.urls import patterns
from zinnia.urls import _
from zinnia.views.authors import AuthorList
from zinnia.views.authors import AuthorDetail
urlpatterns = patterns(
'',
url(r'^$',
AuthorList.as_view(),
name='autho... | [
"zinnia.views.authors.AuthorDetail.as_view",
"zinnia.views.authors.AuthorList.as_view",
"zinnia.urls._"
] | [((279, 299), 'zinnia.views.authors.AuthorList.as_view', 'AuthorList.as_view', ([], {}), '()\n', (297, 299), False, 'from zinnia.views.authors import AuthorList\n'), ((338, 390), 'zinnia.urls._', '_', (['"""^(?P<username>[.+-@\\\\w]+)/page/(?P<page>\\\\d+)/$"""'], {}), "('^(?P<username>[.+-@\\\\w]+)/page/(?P<page>\\\\d... |
from flask import Flask, jsonify, request
from flask_restful import Api, Resource
app = Flask(__name__)
api = Api(app)
def checkPostedData(postedData, functionName):
if ("x" not in postedData or "y" not in postedData):
return 301
else:
return 200
class Add(Resource):
def post(self):
postedData = r... | [
"flask.jsonify",
"flask_restful.Api",
"flask.request.get_json",
"flask.Flask"
] | [((89, 104), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (94, 104), False, 'from flask import Flask, jsonify, request\n'), ((111, 119), 'flask_restful.Api', 'Api', (['app'], {}), '(app)\n', (114, 119), False, 'from flask_restful import Api, Resource\n'), ((319, 337), 'flask.request.get_json', 'request.g... |
import json, urllib.request
from urllib.request import HTTPError, URLError, socket
from .bunk_exception import BunkException
async def http_get(url: str) -> json:
try:
http_result = urllib.request.urlopen(url, timeout=1).read()
return json.loads(http_result)
except socket.timeout:
... | [
"json.loads"
] | [((265, 288), 'json.loads', 'json.loads', (['http_result'], {}), '(http_result)\n', (275, 288), False, 'import json, urllib.request\n')] |
import json
import os
from datetime import datetime, timedelta
from django.conf import settings
from django.http import HttpResponse
from django.shortcuts import render
from mad_web.labstatus.cron_tasks import ArchiveLabsResponse
from mad_web.labstatus.models import UTCSService, UTCSBackend, LabsResponse
def main_a... | [
"django.shortcuts.render",
"json.loads",
"mad_web.labstatus.models.UTCSBackend",
"django.http.HttpResponse",
"mad_web.labstatus.models.LabsResponse",
"json.dumps",
"os.path.isfile",
"datetime.datetime.now",
"mad_web.labstatus.cron_tasks.ArchiveLabsResponse.response_paths_for_datetime_window",
"dat... | [((344, 456), 'django.shortcuts.render', 'render', (['request', '"""labstatus/main.html"""', "{'description': 'See which machines are available in the UTCS labs'}"], {}), "(request, 'labstatus/main.html', {'description':\n 'See which machines are available in the UTCS labs'})\n", (350, 456), False, 'from django.shor... |
import json
import logging
from typing import Any, AsyncIterable, Optional, TextIO
import confuse
from .. import git
from ..util.io import json_defaults
logger = logging.getLogger(__name__)
async def cli_main(
config: confuse.Configuration,
*,
output: TextIO,
from_rev: Optional[str],
from_last_... | [
"logging.getLogger",
"json.dumps",
"confuse.StrSeq"
] | [((165, 192), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (182, 192), False, 'import logging\n'), ((920, 959), 'json.dumps', 'json.dumps', (['item'], {'default': 'json_defaults'}), '(item, default=json_defaults)\n', (930, 959), False, 'import json\n'), ((1388, 1415), 'confuse.StrSeq', ... |
"""
Copyright (c) Facebook, Inc. and its affiliates.
All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import os
import sox
def fi... | [
"sox.Transformer",
"os.path.join",
"os.path.dirname",
"sox.file_info.duration",
"os.walk"
] | [((392, 404), 'os.walk', 'os.walk', (['dir'], {}), '(dir)\n', (399, 404), False, 'import os\n'), ((653, 670), 'sox.Transformer', 'sox.Transformer', ([], {}), '()\n', (668, 670), False, 'import sox\n'), ((1225, 1250), 'os.path.dirname', 'os.path.dirname', (['filename'], {}), '(filename)\n', (1240, 1250), False, 'import ... |
# -*- coding: utf-8 -*-}
import logging
import uuid
from flask import request, g
from flask_babel import gettext
from flask_restful import Resource
from tahiti.app_auth import requires_auth
from tahiti.schema import *
from tahiti.workflow_api import get_workflow
log = logging.getLogger(__name__)
class WorkflowFrom... | [
"logging.getLogger",
"tahiti.workflow_api.get_workflow",
"uuid.uuid4"
] | [((272, 299), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (289, 299), False, 'import logging\n'), ((573, 598), 'tahiti.workflow_api.get_workflow', 'get_workflow', (['workflow_id'], {}), '(workflow_id)\n', (585, 598), False, 'from tahiti.workflow_api import get_workflow\n'), ((1417, 142... |
'''
Created on 30 aug. 2019
@author: LG
'''
from jinja2 import Environment
from jinja2.loaders import FileSystemLoader
import yaml
from pathlib import Path
import pymzn
import re
import platform
from _collections import OrderedDict
import pkg_resources
import os
import json
dummy_model = '''
... | [
"json.dumps",
"jinja2.loaders.FileSystemLoader",
"pkg_resources.resource_filename",
"pymzn.minizinc",
"platform.system",
"yaml.safe_load_all"
] | [((708, 725), 'platform.system', 'platform.system', ([], {}), '()\n', (723, 725), False, 'import platform\n'), ((1688, 1730), 'pymzn.minizinc', 'pymzn.minizinc', (['model'], {'data': 'mzn_model_data'}), '(model, data=mzn_model_data)\n', (1702, 1730), False, 'import pymzn\n'), ((4548, 4626), 'pkg_resources.resource_file... |
import os
import time
from shutil import copytree, copyfile
from shminspector.util.error_handling import raised_to_none_wrapper
from shminspector.util.logger import NOOP_LOGGER
def mkdir(path):
os.mkdir(path)
def path_exists(path):
return os.path.exists(path)
def file_path(path, *paths):
return os.pa... | [
"os.path.exists",
"os.path.join",
"os.path.split",
"os.mkdir",
"time.time",
"shminspector.util.error_handling.raised_to_none_wrapper"
] | [((201, 215), 'os.mkdir', 'os.mkdir', (['path'], {}), '(path)\n', (209, 215), False, 'import os\n'), ((252, 272), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (266, 272), False, 'import os\n'), ((315, 341), 'os.path.join', 'os.path.join', (['path', '*paths'], {}), '(path, *paths)\n', (327, 341), Fals... |
# coding: utf-8
import torch
from torch import nn
from torch.nn import functional as F
from .chess_board import ChessBoard
class ConvBlock(nn.Module):
""" 卷积块 """
def __init__(self, in_channels: int, out_channel: int, kernel_size, padding=0):
super().__init__()
self.conv = nn.Conv2d(in_chann... | [
"torch.nn.BatchNorm2d",
"torch.nn.ReLU",
"torch.nn.Tanh",
"torch.exp",
"torch.nn.Conv2d",
"torch.nn.Linear",
"torch.nn.functional.log_softmax",
"torch.nn.functional.relu",
"torch.device"
] | [((302, 379), 'torch.nn.Conv2d', 'nn.Conv2d', (['in_channels', 'out_channel'], {'kernel_size': 'kernel_size', 'padding': 'padding'}), '(in_channels, out_channel, kernel_size=kernel_size, padding=padding)\n', (311, 379), False, 'from torch import nn\n'), ((436, 463), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['out_chan... |
from typing import List
import torch
def random_split(ds: torch.utils.data.Dataset, parts: List[float]) -> List[torch.utils.data.Dataset]:
total_length = len(ds)
assert len(parts) > 0, "parts must contain at least 1 float value"
assert sum(parts) == 1, "sum of parts must be equal to 1 but found {}".format... | [
"torch.utils.data.random_split"
] | [((481, 523), 'torch.utils.data.random_split', 'torch.utils.data.random_split', (['ds', 'lengths'], {}), '(ds, lengths)\n', (510, 523), False, 'import torch\n')] |
import turtle
t = turtle.Pen()
t.forward(50)
t.left(90)
t.forward(50)
t.left(90)
t.forward(50)
t.left(90)
t.forward(50)
t.left(90)
t.reset()
t.clear()
t.reset()
t.backward(100)
t.up()
t.right(90)
t.forward(20)
t.left(90)
t.down()
t.forward(100)
| [
"turtle.Pen"
] | [((18, 30), 'turtle.Pen', 'turtle.Pen', ([], {}), '()\n', (28, 30), False, 'import turtle\n')] |
# import dependencies
from numerapi import NumerAPI
from os import environ, path, getcwd
from yaml import safe_load
# Load your API keys and model from config.yml
with open("config.yml", "r") as yml:
numerai_conf = safe_load(yml)
# Set your API keys and model_id
public_id = numerai_conf["public_id"] if numerai_co... | [
"numerapi.NumerAPI",
"yaml.safe_load",
"os.path.isdir"
] | [((616, 686), 'numerapi.NumerAPI', 'NumerAPI', ([], {'public_id': 'public_id', 'secret_key': 'secret_key', 'verbosity': '"""info"""'}), "(public_id=public_id, secret_key=secret_key, verbosity='info')\n", (624, 686), False, 'from numerapi import NumerAPI\n'), ((220, 234), 'yaml.safe_load', 'safe_load', (['yml'], {}), '(... |
"""
This file is based on dominant_invariant_subspace.m from the manopt MATLAB
package.
The optimization is performed on the Grassmann manifold, since only the
space spanned by the columns of X matters. The implementation is short to
show how Manopt can be used to quickly obtain a prototype. To make the
implementation... | [
"numpy.sqrt",
"pymanopt.solvers.TrustRegions",
"pymanopt.Problem",
"theano.tensor.matrix",
"pymanopt.manifolds.Grassmann",
"numpy.isreal",
"numpy.linalg.norm",
"numpy.random.randn",
"numpy.spacing",
"theano.tensor.dot"
] | [((2022, 2037), 'pymanopt.manifolds.Grassmann', 'Grassmann', (['n', 'p'], {}), '(n, p)\n', (2031, 2037), False, 'from pymanopt.manifolds import Grassmann\n'), ((2046, 2056), 'theano.tensor.matrix', 'T.matrix', ([], {}), '()\n', (2054, 2056), True, 'import theano.tensor as T\n'), ((2140, 2178), 'pymanopt.Problem', 'Prob... |