code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import unittest
from time import time
from pickle import load, dump
from tempfile import mkstemp
from random import choice, randint
from string import ascii_letters
from numpy import corrcoef, random, abs, max, asarray, round, zeros_like
from trlda.models import BatchLDA
from trlda.utils import sample_dirichlet
class... | [
"unittest.main",
"trlda.models.BatchLDA",
"pickle.dump",
"numpy.zeros_like",
"numpy.abs",
"random.randint",
"tempfile.mkstemp",
"pickle.load",
"numpy.random.rand"
] | [((2869, 2884), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2882, 2884), False, 'import unittest\n'), ((438, 495), 'trlda.models.BatchLDA', 'BatchLDA', ([], {'num_words': 'W', 'num_topics': 'K', 'alpha': 'alpha', 'eta': 'eta'}), '(num_words=W, num_topics=K, alpha=alpha, eta=eta)\n', (446, 495), False, 'from tr... |
from django.test import TestCase
from custom.icds_reports.reports.poshan_progress_dashboard_data import get_poshan_progress_dashboard_data
class TestPPDData(TestCase):
def test_get_ppr_data_comparative_month(self):
self.maxDiff = None
data = get_poshan_progress_dashboard_data(
'icds-... | [
"custom.icds_reports.reports.poshan_progress_dashboard_data.get_poshan_progress_dashboard_data"
] | [((266, 404), 'custom.icds_reports.reports.poshan_progress_dashboard_data.get_poshan_progress_dashboard_data', 'get_poshan_progress_dashboard_data', (['"""icds-cas"""', '(2017)', '(5)', '(2)', '"""month"""', '"""comparative"""', "{'aggregation_level': 2, 'state_id': 'st1'}", '(False)'], {}), "('icds-cas', 2017, 5, 2, '... |
#!/usr/bin/env python
"""
This example illustrates embedding a visvis figure in an FLTK application.
"""
import fltk
import visvis as vv
# Create a visvis app instance, which wraps an fltk application object.
# This needs to be done *before* instantiating the main window.
app = vv.use('fltk')
class MainWindow(flt... | [
"fltk.Fl.run",
"visvis.use",
"fltk.Fl_Window.__init__",
"visvis.clf",
"visvis.plot",
"fltk.Fl_Button",
"fltk.Fl_Box",
"visvis.backends.backend_fltk.Figure",
"visvis.legend"
] | [((283, 297), 'visvis.use', 'vv.use', (['"""fltk"""'], {}), "('fltk')\n", (289, 297), True, 'import visvis as vv\n'), ((1522, 1535), 'fltk.Fl.run', 'fltk.Fl.run', ([], {}), '()\n', (1533, 1535), False, 'import fltk\n'), ((366, 426), 'fltk.Fl_Window.__init__', 'fltk.Fl_Window.__init__', (['self', '(560)', '(420)', '"""E... |
#!/usr/bin/env python
import math
import numpy as np
from . import linalg as la
from . import eulang
#Euler angle sequence: XYZ (world). First rotation about X, second rotation
#about Y, and the third rotation about Z axis of the world(i.e. fixed) frame.
#This is the same as the sequence used in Blender.
#In contrast... | [
"numpy.trace",
"numpy.empty",
"numpy.einsum",
"numpy.sin",
"numpy.linalg.norm",
"numpy.diag",
"math.fmod",
"numpy.copy",
"numpy.identity",
"math.cos",
"numpy.linalg.det",
"math.sqrt",
"numpy.cross",
"math.sin",
"numpy.cos",
"numpy.dot",
"numpy.vstack",
"numpy.zeros",
"math.acos",... | [((784, 813), 'math.fmod', 'math.fmod', (['angle', '(2 * math.pi)'], {}), '(angle, 2 * math.pi)\n', (793, 813), False, 'import math\n'), ((1187, 1201), 'numpy.zeros', 'np.zeros', (['(3,)'], {}), '((3,))\n', (1195, 1201), True, 'import numpy as np\n'), ((1561, 1582), 'numpy.sqrt', 'np.sqrt', (['(1.0 - zetasq)'], {}), '(... |
#! /usr/bin/python3
import argparse
import hashlib
import mmap
import os
import posixpath
import stat
import sys
from collections import namedtuple
exclusions = ('lost+found', 'restore', 'backup', 'Newsfeed', '.pki', 'Jenkins')
joinpath = posixpath.join
FileDesc = namedtuple('FileDesc', ['full_path', 'item_type'... | [
"hashlib.md5",
"stat.S_ISREG",
"os.stat",
"argparse.ArgumentParser",
"os.walk",
"posixpath.join",
"collections.namedtuple",
"os.utime",
"stat.S_ISDIR",
"os.path.join"
] | [((272, 351), 'collections.namedtuple', 'namedtuple', (['"""FileDesc"""', "['full_path', 'item_type', 'size', 'mtime', 'checksum']"], {}), "('FileDesc', ['full_path', 'item_type', 'size', 'mtime', 'checksum'])\n", (282, 351), False, 'from collections import namedtuple\n'), ((481, 508), 'stat.S_ISREG', 'stat.S_ISREG', (... |
import sklearn.datasets as datasets
from numpywren.matrix import BigMatrix
from numpywren import matrix_utils, binops
from numpywren.matrix_init import shard_matrix
import pytest
import numpy as np
import pywren
import unittest
class IndexingTestClass(unittest.TestCase):
def test_single_shard_index_get(self):
... | [
"numpywren.matrix_init.shard_matrix",
"numpywren.matrix.BigMatrix",
"numpy.all",
"numpy.random.randn"
] | [((329, 354), 'numpy.random.randn', 'np.random.randn', (['(128)', '(128)'], {}), '(128, 128)\n', (344, 354), True, 'import numpy as np\n'), ((375, 430), 'numpywren.matrix.BigMatrix', 'BigMatrix', (['"""test_0"""'], {'shape': 'X.shape', 'shard_sizes': 'X.shape'}), "('test_0', shape=X.shape, shard_sizes=X.shape)\n", (384... |
# Generated by Django 2.2.10 on 2020-04-10 22:28
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0023_game_max_words'),
]
operations = [
migrations.RenameField(
model_name='game',
old_name='max_words',
... | [
"django.db.migrations.RenameField"
] | [((221, 318), 'django.db.migrations.RenameField', 'migrations.RenameField', ([], {'model_name': '"""game"""', 'old_name': '"""max_words"""', 'new_name': '"""words_per_player"""'}), "(model_name='game', old_name='max_words', new_name=\n 'words_per_player')\n", (243, 318), False, 'from django.db import migrations\n')] |
# (C) Copyright 2017 Hewlett Packard Enterprise Development LP.
#
# 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 applic... | [
"tempfile.NamedTemporaryFile",
"subprocess.Popen",
"oslo_log.log.getLogger",
"oslo_config.cfg.SubCommandOpt",
"catena.common.utils.decrypt_private_rsakey",
"catena.db.sqlalchemy.api.get_chain",
"catena.common.config.parse_args",
"catena.db.sqlalchemy.models.register_models",
"catena.common.utils.dec... | [((1050, 1073), 'oslo_log.log.getLogger', 'log.getLogger', (['__name__'], {}), '(__name__)\n', (1063, 1073), False, 'from oslo_log import log\n'), ((1113, 1145), 'oslo_db.sqlalchemy.enginefacade.writer.get_engine', 'enginefacade.writer.get_engine', ([], {}), '()\n', (1143, 1145), False, 'from oslo_db.sqlalchemy import ... |
import os
import sys
import discord
from bot import init_cfg, init_bot
from template import handle, Context
DEBUG = True
TOKEN = ""
def init():
if len(sys.argv) <= 1:
sys.exit("start template: python main.py <TOKEN>")
global TOKEN
TOKEN = sys.argv[1]
if __name__ == "__main__":
init()
... | [
"bot.init_bot",
"os.mkdir",
"template.Context",
"os.path.exists",
"sys.exit",
"bot.init_cfg",
"discord.Client"
] | [((185, 235), 'sys.exit', 'sys.exit', (['"""start template: python main.py <TOKEN>"""'], {}), "('start template: python main.py <TOKEN>')\n", (193, 235), False, 'import sys\n'), ((363, 384), 'os.path.exists', 'os.path.exists', (['"""cfg"""'], {}), "('cfg')\n", (377, 384), False, 'import os\n'), ((394, 409), 'os.mkdir',... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from xy.device import Device
def main(args):
from modules.utils import get_paths_from_n_files as get
pattern = args.pattern
steps = args.steps
stride = args.stride
skip = args.skip
paths = get(pattern, skip, steps, stride, spatial_concat=True, spatial_concat_e... | [
"modules.utils.get_paths_from_n_files",
"argparse.ArgumentParser",
"xy.device.Device"
] | [((249, 335), 'modules.utils.get_paths_from_n_files', 'get', (['pattern', 'skip', 'steps', 'stride'], {'spatial_concat': '(True)', 'spatial_concat_eps': '(0.0001)'}), '(pattern, skip, steps, stride, spatial_concat=True, spatial_concat_eps=\n 0.0001)\n', (252, 335), True, 'from modules.utils import get_paths_from_n_f... |
from functiontools import wraps
from benchmark import benchmark
def memo(func):
cache = {}
@wraps(func)
def wrap(*args):
if args not in cache:
cache[args] = func(*args)
return cache[args]
return wrap
def fib(n):
if n < 2:
return 1
else:
return ... | [
"functiontools.wraps"
] | [((106, 117), 'functiontools.wraps', 'wraps', (['func'], {}), '(func)\n', (111, 117), False, 'from functiontools import wraps\n')] |
import os
# from resticweb.dictionary.resticweb_constants import Repository as Rep
from resticweb.models.general import Repository, Snapshot, SnapshotObject, JobParameter, RepositoryType
from resticweb.tools.local_session import LocalSession
from resticweb.misc.credential_manager import credential_manager
# from .repos... | [
"resticweb.misc.credential_manager.credential_manager.get_credential",
"json.loads",
"resticweb.misc.credential_manager.credential_manager.set_service_id",
"resticweb.misc.credential_manager.credential_manager.get_group_credentials",
"json.dumps",
"resticweb.tools.local_session.LocalSession",
"resticweb... | [((637, 669), 'logging.getLogger', 'logging.getLogger', (['"""debugLogger"""'], {}), "('debugLogger')\n", (654, 669), False, 'import logging\n'), ((820, 834), 'resticweb.tools.local_session.LocalSession', 'LocalSession', ([], {}), '()\n', (832, 834), False, 'from resticweb.tools.local_session import LocalSession\n'), (... |
import abc
import torch
from code_slac.network.base import BaseNetwork
from latent_with_splitseqs.config.fun.get_obs_dims_used_df import get_obs_dims_used_df
class SplitSeqClassifierBase(BaseNetwork, metaclass=abc.ABCMeta):
def __init__(self,
obs_dim,
seq_len,
... | [
"latent_with_splitseqs.config.fun.get_obs_dims_used_df.get_obs_dims_used_df",
"torch.no_grad"
] | [((486, 599), 'latent_with_splitseqs.config.fun.get_obs_dims_used_df.get_obs_dims_used_df', 'get_obs_dims_used_df', ([], {'obs_dim': 'obs_dim', 'obs_dims_used': 'obs_dims_used', 'obs_dims_used_except': 'obs_dims_used_except'}), '(obs_dim=obs_dim, obs_dims_used=obs_dims_used,\n obs_dims_used_except=obs_dims_used_exce... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by <NAME> at 2019-05-27
"""Step_01_model_comparison.py
:description : script
:param :
:returns:
:rtype:
"""
import os
import cobra
from matplotlib import pyplot as plt
from matplotlib_venn import venn2
import pandas as pd
import My_def
from My_def.model_repor... | [
"matplotlib.pyplot.show",
"pandas.read_csv",
"cobra.io.load_json_model",
"matplotlib.pyplot.subplots",
"os.chdir"
] | [((365, 421), 'os.chdir', 'os.chdir', (['"""../../ComplementaryData/Step_02_DraftModels/"""'], {}), "('../../ComplementaryData/Step_02_DraftModels/')\n", (373, 421), False, 'import os\n'), ((457, 505), 'cobra.io.load_json_model', 'cobra.io.load_json_model', (['"""CarveMe/Lreu_ca.json"""'], {}), "('CarveMe/Lreu_ca.json'... |
from gensim import models
import json
import numpy as np
MODEL_VERSION = "glove-wiki-gigaword-300"
model = models.KeyedVectors.load_word2vec_format(MODEL_VERSION)
def get_word_vec(word_list):
"""
This method will get the vector of the given word
:param word_list: list of a single word string
:return... | [
"json.load",
"numpy.array",
"gensim.models.KeyedVectors.load_word2vec_format",
"json.dumps"
] | [((109, 164), 'gensim.models.KeyedVectors.load_word2vec_format', 'models.KeyedVectors.load_word2vec_format', (['MODEL_VERSION'], {}), '(MODEL_VERSION)\n', (149, 164), False, 'from gensim import models\n'), ((3927, 3945), 'json.dumps', 'json.dumps', (['result'], {}), '(result)\n', (3937, 3945), False, 'import json\n'), ... |
from time import sleep
from re import search, finditer
from copy import copy
# from pprint import pprint
from slackclient import SlackClient
from bot.message import Message
class Bot:
def __init__(self, conf):
# instantiate Slack client
self.slack_client = SlackClient(conf.slack_bot_token)
... | [
"bot.message.Message",
"re.finditer",
"slackclient.SlackClient",
"copy.copy",
"time.sleep",
"re.search"
] | [((282, 315), 'slackclient.SlackClient', 'SlackClient', (['conf.slack_bot_token'], {}), '(conf.slack_bot_token)\n', (293, 315), False, 'from slackclient import SlackClient\n'), ((1822, 1862), 're.search', 'search', (['self.MENTION_REGEX', 'message_text'], {}), '(self.MENTION_REGEX, message_text)\n', (1828, 1862), False... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import os
project_name = "reco-tut-mlh"; branch = "main"; account = "sparsh-ai"
project_path = os.path.join('/content', project_name)
# In[2]:
if not os.path.exists(project_path):
get_ipython().system(u'cp /content/drive/MyDrive/mykeys.py /content')
import m... | [
"tensorflow.python.framework.ops.disable_eager_execution",
"numpy.random.seed",
"models.GCN.LightGCN",
"pandas.read_csv",
"build_features.AffinityMatrix",
"os.path.join",
"metrics.mean_average_precision",
"numpy.mat",
"pandas.DataFrame",
"sys.path.append",
"numpy.power",
"pandas.merge",
"sur... | [((145, 183), 'os.path.join', 'os.path.join', (['"""/content"""', 'project_name'], {}), "('/content', project_name)\n", (157, 183), False, 'import os\n'), ((1194, 1222), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""./code"""'], {}), "(0, './code')\n", (1209, 1222), False, 'import sys\n'), ((2517, 2556), 'os.path.... |
import atexit
import os
import sys
import time
from contextlib import suppress
from signal import SIGTERM
class Daemon:
def __init__(self, pidfile=None):
self.pidfile = pidfile or os.path.join("/var/run/exhal.service")
def start(self):
try:
self.get_pidfile()
except IOErro... | [
"atexit.register",
"os.remove",
"os.getpid",
"contextlib.suppress",
"time.sleep",
"os.umask",
"os.kill",
"os.setsid",
"os.fork",
"sys.stderr.write",
"os.path.join",
"os.chdir",
"sys.exit"
] | [((873, 886), 'os.chdir', 'os.chdir', (['"""/"""'], {}), "('/')\n", (881, 886), False, 'import os\n'), ((895, 906), 'os.setsid', 'os.setsid', ([], {}), '()\n', (904, 906), False, 'import os\n'), ((915, 926), 'os.umask', 'os.umask', (['(0)'], {}), '(0)\n', (923, 926), False, 'import os\n'), ((957, 993), 'atexit.register... |
import asyncio
import os
from asyncio import StreamReader, StreamWriter, AbstractEventLoop, \
WriteTransport, Task, BaseTransport
from io import BytesIO
from typing import Any, List, Optional, Mapping
from bitstring import tokenparser, BitStream
def random_byte_array(size: int) -> bytes:
return os.urandom(si... | [
"bitstring.tokenparser",
"asyncio.StreamReader",
"asyncio.StreamWriter",
"os.urandom",
"bitstring.BitStream"
] | [((307, 323), 'os.urandom', 'os.urandom', (['size'], {}), '(size)\n', (317, 323), False, 'import os\n'), ((501, 512), 'bitstring.BitStream', 'BitStream', ([], {}), '()\n', (510, 512), False, 'from bitstring import tokenparser, BitStream\n'), ((620, 636), 'bitstring.tokenparser', 'tokenparser', (['fmt'], {}), '(fmt)\n',... |
import os
import json
from app.config import DATA_PATH
from app.utils.mass import string_to_md5
"""
cover:
link:
text:
type:
top:
"""
def get_posters():
with open(os.path.join(DATA_PATH, 'poster.json'), 'r') as f:
data = json.load(f)
return data['data']
def save_poster(data):
with open(os.... | [
"json.dump",
"json.load",
"os.path.join",
"app.utils.mass.string_to_md5"
] | [((477, 504), 'app.utils.mass.string_to_md5', 'string_to_md5', (["post['link']"], {}), "(post['link'])\n", (490, 504), False, 'from app.utils.mass import string_to_md5\n'), ((236, 248), 'json.load', 'json.load', (['f'], {}), '(f)\n', (245, 248), False, 'import json\n'), ((376, 404), 'json.dump', 'json.dump', (["{'data'... |
from __future__ import print_function, unicode_literals
import sys
import os
import traceback
import time
from requests.utils import quote
from requests.exceptions import ConnectionError
import click
from stable_world.py_helpers import platform_uname
from stable_world import __version__ as version
from stable_world imp... | [
"stable_world.py_helpers.platform_uname",
"traceback.format_exception",
"click.echo",
"time.ctime",
"click.secho",
"os.path.join"
] | [((567, 615), 'os.path.join', 'os.path.join', (['cache_dirname', '"""logs"""', '"""debug.txt"""'], {}), "(cache_dirname, 'logs', 'debug.txt')\n", (579, 615), False, 'import os\n'), ((685, 701), 'stable_world.py_helpers.platform_uname', 'platform_uname', ([], {}), '()\n', (699, 701), False, 'from stable_world.py_helpers... |
from prompt_toolkit.application import Application
from prompt_toolkit.formatted_text import merge_formatted_text, to_formatted_text
from prompt_toolkit.key_binding import KeyBindings
from prompt_toolkit.layout.containers import HSplit, VSplit, Window
from prompt_toolkit.layout.layout import Layout
from prompt_toolkit.... | [
"prompt_toolkit.layout.layout.Layout",
"prompt_toolkit.widgets.TextArea",
"prompt_toolkit.key_binding.KeyBindings",
"prompt_toolkit.layout.containers.HSplit",
"lira.app.LiraApp",
"prompt_toolkit.layout.containers.Window",
"lira.book.Book",
"prompt_toolkit.formatted_text.to_formatted_text",
"prompt_t... | [((445, 458), 'prompt_toolkit.key_binding.KeyBindings', 'KeyBindings', ([], {}), '()\n', (456, 458), False, 'from prompt_toolkit.key_binding import KeyBindings\n'), ((1014, 1091), 'prompt_toolkit.widgets.TextArea', 'TextArea', ([], {'height': '(40)', 'width': '(25)', 'style': "styles['Text']", 'text': '"""Python-Tutori... |
import yaml
import numpy as np
import logging
logger = logging.getLogger("cm.conf")
class ControlModelParameters:
"""
Load parameters from .yaml file.
"""
def __init__(self):
self._config = None
self.wind_farm = None
self.turbine = None
self.simulation = None
... | [
"yaml.load",
"numpy.deg2rad",
"yaml.dump",
"numpy.array",
"logging.getLogger"
] | [((56, 84), 'logging.getLogger', 'logging.getLogger', (['"""cm.conf"""'], {}), "('cm.conf')\n", (73, 84), False, 'import logging\n'), ((991, 1039), 'yaml.load', 'yaml.load', ([], {'stream': 'stream', 'Loader': 'yaml.SafeLoader'}), '(stream=stream, Loader=yaml.SafeLoader)\n', (1000, 1039), False, 'import yaml\n'), ((107... |
# !/usr/bin/python
# -*- coding:UTF-8 -*-
# -----------------------------------------------------------------------#
# File Name: textrank_keyword
# Author: <NAME>
# Mail: <EMAIL>
# Created Time: 2021-09-04
# Description:
# -----------------------------------------------------------------------#
import networkx as nx... | [
"knlp.utils.util.get_default_stop_words_file",
"networkx.from_numpy_matrix",
"networkx.pagerank",
"knlp.utils.util.AttrDict",
"numpy.zeros"
] | [((874, 903), 'knlp.utils.util.get_default_stop_words_file', 'get_default_stop_words_file', ([], {}), '()\n', (901, 903), False, 'from knlp.utils.util import get_default_stop_words_file, AttrDict\n'), ((4301, 4339), 'numpy.zeros', 'np.zeros', (['(words_number, words_number)'], {}), '((words_number, words_number))\n', (... |
import os,sys
from PIL import Image
import numpy
LETTER_NB = 5
LETTER_SPACE = 1
LETTER_SIZE = 8
LETTER_LEFT = 10
LETTER_RIGHT = 16
class CaptchaReader(object):
"""docstring for CaptchaReader"""
def __init__(self, folderDico):
super(CaptchaReader, self).__init__()
self.folderDico = folderDico + "/"
def read(s... | [
"PIL.Image.open",
"PIL.Image.fromarray",
"numpy.array",
"numpy.array_equal",
"os.listdir"
] | [((1149, 1189), 'numpy.array_equal', 'numpy.array_equal', (['symb_np', '(im_dic / 255)'], {}), '(symb_np, im_dic / 255)\n', (1166, 1189), False, 'import numpy\n'), ((1794, 1814), 'PIL.Image.open', 'Image.open', (['filename'], {}), '(filename)\n', (1804, 1814), False, 'from PIL import Image\n'), ((1824, 1846), 'numpy.ar... |
from pipeline.io import unique_id, video_generator
def test_video_generator_2015(bees_video, filelists_path):
gen = video_generator(bees_video, ts_format="2015", path_filelists=filelists_path)
results = list(gen)
assert len(results) == 3
prev_ts = 0.0
for _, _, ts in results:
assert ts > p... | [
"pipeline.io.video_generator",
"pipeline.io.unique_id"
] | [((122, 198), 'pipeline.io.video_generator', 'video_generator', (['bees_video'], {'ts_format': '"""2015"""', 'path_filelists': 'filelists_path'}), "(bees_video, ts_format='2015', path_filelists=filelists_path)\n", (137, 198), False, 'from pipeline.io import unique_id, video_generator\n'), ((408, 479), 'pipeline.io.vide... |
import argparse
from .env_viewer import viewer
from .envs.bm_config import BM_Config
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Assistive Gym Environment Viewer')
parser.add_argument('--env', default='ScratchItchJaco-v1',
help='Environment to test (default:... | [
"argparse.ArgumentParser"
] | [((126, 197), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Assistive Gym Environment Viewer"""'}), "(description='Assistive Gym Environment Viewer')\n", (149, 197), False, 'import argparse\n')] |
import tweepy
import json
import pymongo
#from src_python import utilities
# Initialize the API consumer keys and access tokens
consumer_key = "LukFsjKDofVcCdiKsCnxiLx2V"
consumer_secret = "<KEY>"
access_token = "<KEY>"
access_token_secret = "<KEY>"
# Authenticate tweepy using the keys
auth = tweepy.OAuthHandler(con... | [
"tweepy.OAuthHandler",
"tweepy.Cursor",
"tweepy.API"
] | [((297, 347), 'tweepy.OAuthHandler', 'tweepy.OAuthHandler', (['consumer_key', 'consumer_secret'], {}), '(consumer_key, consumer_secret)\n', (316, 347), False, 'import tweepy\n'), ((412, 507), 'tweepy.API', 'tweepy.API', (['auth'], {'wait_on_rate_limit': '(True)', 'wait_on_rate_limit_notify': '(True)', 'compression': '(... |
import xlrd
# from xlutils.copy import copy as xlscopy
import shutil
import os
from numpy import sqrt, abs
import sys
sys.path.append('../..') # 如果最终要从main.py调用,则删掉这句
from GeneralMethod.PyCalcLib import Fitting
from GeneralMethod.PyCalcLib import Method
from reportwriter.ReportWriter import ReportWriter
c... | [
"sys.path.append",
"numpy.abs",
"GeneralMethod.PyCalcLib.Fitting.linear",
"reportwriter.ReportWriter.ReportWriter",
"xlrd.open_workbook",
"GeneralMethod.PyCalcLib.Method.a_uncertainty",
"sys.exit",
"os.startfile"
] | [((126, 150), 'sys.path.append', 'sys.path.append', (['"""../.."""'], {}), "('../..')\n", (141, 150), False, 'import sys\n'), ((6025, 6087), 'GeneralMethod.PyCalcLib.Fitting.linear', 'Fitting.linear', (['list_time1', 'list_temperature1'], {'show_plot': '(False)'}), '(list_time1, list_temperature1, show_plot=False)\n', ... |
# -*- coding: utf-8 -*-
from django_filters import (FilterSet, CharFilter, DateTimeFilter,
NumberFilter, BooleanFilter)
from guardian.shortcuts import get_objects_for_user
from rest_framework import filters
from chat.models import Post, Channel
def get_readable_channel_ids(user):
"""
... | [
"django_filters.CharFilter",
"chat.models.Channel.objects.filter",
"django_filters.NumberFilter",
"django_filters.DateTimeFilter",
"guardian.shortcuts.get_objects_for_user",
"django_filters.BooleanFilter"
] | [((561, 625), 'guardian.shortcuts.get_objects_for_user', 'get_objects_for_user', (['user', '"""chat.read_channel"""'], {'use_groups': '(True)'}), "(user, 'chat.read_channel', use_groups=True)\n", (581, 625), False, 'from guardian.shortcuts import get_objects_for_user\n'), ((747, 782), 'chat.models.Channel.objects.filte... |
import uuid
from typing import List, Optional
from todo_api.extensions import db
from todo_api.models import Todo
def create_todo(text: str, user_id: int) -> Todo:
todo = Todo(public_id=uuid.uuid4(), text=text, user_id=user_id)
db.session.add(todo)
db.session.commit()
return todo
def get_all_todo... | [
"uuid.uuid4",
"todo_api.extensions.db.session.add",
"todo_api.models.Todo.query.delete",
"todo_api.models.Todo.query.all",
"todo_api.extensions.db.session.commit",
"todo_api.models.Todo.query.filter_by",
"todo_api.extensions.db.session.delete"
] | [((240, 260), 'todo_api.extensions.db.session.add', 'db.session.add', (['todo'], {}), '(todo)\n', (254, 260), False, 'from todo_api.extensions import db\n'), ((265, 284), 'todo_api.extensions.db.session.commit', 'db.session.commit', ([], {}), '()\n', (282, 284), False, 'from todo_api.extensions import db\n'), ((350, 36... |
# Authors: <NAME> (lambertt) and <NAME> (odafaluy)
import numpy
import scipy
import scipy.linalg
import plot
class Matrix:
"""
Provides Methods for operations with an hilbert- or a special triangular matrix.
"""
def __init__(self, mtype, dim, dtype):
"""
Initializes the class instan... | [
"scipy.linalg.hilbert",
"scipy.linalg.solve_triangular",
"numpy.identity",
"scipy.linalg.lu",
"scipy.linalg.inv",
"numpy.array",
"numpy.linalg.norm",
"numpy.dot",
"plot.plot"
] | [((4016, 4028), 'plot.plot', 'plot.plot', (['n'], {}), '(n)\n', (4025, 4028), False, 'import plot\n'), ((4435, 4465), 'numpy.identity', 'numpy.identity', (['n'], {'dtype': 'dtype'}), '(n, dtype=dtype)\n', (4449, 4465), False, 'import numpy\n'), ((1860, 1894), 'numpy.array', 'numpy.array', (['arr'], {'dtype': 'self.dtyp... |
import pygame
import random
from toast.quadtree import QuadTree
from toast.scene_graph import GameObject, Scene
from toast.camera import Camera
from toast.event_manager import EventManager
from examples.demo_game import DemoGame
class QuadTreeVisualizer(GameObject):
def __init__(self, quadtree):
super(Qu... | [
"random.randint",
"pygame.draw.rect",
"examples.demo_game.DemoGame",
"examples.demo_game.DemoGame.camera_to_world",
"toast.quadtree.QuadTree",
"toast.event_manager.EventManager.subscribe"
] | [((2592, 2622), 'examples.demo_game.DemoGame', 'DemoGame', (['(512, 512)', 'NewScene'], {}), '((512, 512), NewScene)\n', (2600, 2622), False, 'from examples.demo_game import DemoGame\n'), ((571, 631), 'pygame.draw.rect', 'pygame.draw.rect', (['surface', '(255, 0, 0)', 'quadtree.quadrant', '(1)'], {}), '(surface, (255, ... |
"""empty message
Revision ID: c1ca0249cb60
Revises: 0b986a10b559
Create Date: 2020-01-07 08:36:09.067866
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'c1ca0249cb60'
down_revision = '0b986a10b559'
branch_labels = None
depends_on = None
def upgrade():
# ... | [
"alembic.op.drop_column",
"sqlalchemy.Float"
] | [((652, 684), 'alembic.op.drop_column', 'op.drop_column', (['"""tiles"""', '"""min_x"""'], {}), "('tiles', 'min_x')\n", (666, 684), False, 'from alembic import op\n'), ((689, 721), 'alembic.op.drop_column', 'op.drop_column', (['"""tiles"""', '"""max_y"""'], {}), "('tiles', 'max_y')\n", (703, 721), False, 'from alembic ... |
import unittest
from testutils import getZserioApi
class FullConstTypeTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.api = getZserioApi(__file__, "expressions.zs").full_const_type
def testBitSizeOfWithOptional(self):
fullConstTypeExpression = self.api.FullConstTypeExpressi... | [
"testutils.getZserioApi"
] | [((157, 197), 'testutils.getZserioApi', 'getZserioApi', (['__file__', '"""expressions.zs"""'], {}), "(__file__, 'expressions.zs')\n", (169, 197), False, 'from testutils import getZserioApi\n')] |
from __future__ import annotations
from dataclasses import dataclass
import logging
from typing import Tuple, Optional
from typing_extensions import Literal
log = logging.getLogger(__name__)
GripperName = Literal["gripper"]
GripperModel = Literal["gripper_v1"]
DEFAULT_GRIPPER_CALIBRATION_OFFSET = [0.0, 0.0, 0.0]
@... | [
"dataclasses.dataclass",
"logging.getLogger"
] | [((164, 191), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (181, 191), False, 'import logging\n'), ((320, 342), 'dataclasses.dataclass', 'dataclass', ([], {'frozen': '(True)'}), '(frozen=True)\n', (329, 342), False, 'from dataclasses import dataclass\n')] |
import matplotlib.pyplot as plt
import pandas as pd
from app.requester import ExchangeRateRequester
class Grapher:
def __init__(self) -> None:
self.exchange_rate_requester = ExchangeRateRequester()
def _create_historical_rates_df(self, transactions) -> pd.DataFrame:
assert transactions, "The... | [
"pandas.DataFrame",
"matplotlib.pyplot.title",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.show",
"app.requester.ExchangeRateRequester",
"pandas.merge",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.grid"
] | [((189, 212), 'app.requester.ExchangeRateRequester', 'ExchangeRateRequester', ([], {}), '()\n', (210, 212), False, 'from app.requester import ExchangeRateRequester\n'), ((1658, 1746), 'pandas.DataFrame', 'pd.DataFrame', (['transactions'], {'columns': "['date', 'transaction[+/-]', 'transaction_rate']"}), "(transactions,... |
# -*- coding: utf-8 -*-
"""Workflow encapsulation package for performing actions using the Tanium API."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import datetime
import json
import time
from collections import... | [
"json.loads",
"time.sleep",
"datetime.datetime.utcnow",
"datetime.timedelta",
"collections.OrderedDict"
] | [((3276, 3302), 'datetime.datetime.utcnow', 'datetime.datetime.utcnow', ([], {}), '()\n', (3300, 3302), False, 'import datetime\n'), ((11258, 11307), 'json.loads', 'json.loads', (["(self.obj.parameter_definition or '{}')"], {}), "(self.obj.parameter_definition or '{}')\n", (11268, 11307), False, 'import json\n'), ((118... |
import subprocess
import base64
import json
import re
import hashlib
import tempfile
import os
from lxml import etree
import pprint
from math_tools import percentile
def get_blast_databases(exe_loc, db_loc):
"""
Look for BLAST databases using in given path and return a list
Args:
exe_loc: Locat... | [
"subprocess.Popen",
"lxml.etree.fromstring",
"os.path.getsize",
"subprocess.check_output",
"re.findall",
"re.sub"
] | [((811, 911), 'subprocess.check_output', 'subprocess.check_output', (['[exe_loc + \'blastdbcmd\', \'-list\', db_loc, \'-list_outfmt\', "\'%f %p %t\'"]'], {}), '([exe_loc + \'blastdbcmd\', \'-list\', db_loc,\n \'-list_outfmt\', "\'%f %p %t\'"])\n', (834, 911), False, 'import subprocess\n'), ((3052, 3110), 're.findall... |
from distutils.core import setup
import py2exe
setup(console=['Single Stock Scraper.py'])
| [
"distutils.core.setup"
] | [((51, 93), 'distutils.core.setup', 'setup', ([], {'console': "['Single Stock Scraper.py']"}), "(console=['Single Stock Scraper.py'])\n", (56, 93), False, 'from distutils.core import setup\n')] |
'''
Created on 02-Jul-2016
@author: <NAME>
@version: 1.0
@since: 1.0
'''
from flask_sqlalchemy import SQLAlchemy
from restful.tiny_routes import app
db = SQLAlchemy(app)
class UrlMap(db.Model):
'''
A model responsible for storing shortened to long url mapping.
'''
id = db.Column('id', db.Integer, pri... | [
"flask_sqlalchemy.SQLAlchemy"
] | [((156, 171), 'flask_sqlalchemy.SQLAlchemy', 'SQLAlchemy', (['app'], {}), '(app)\n', (166, 171), False, 'from flask_sqlalchemy import SQLAlchemy\n')] |
from twitter_ads.campaign import Tweet
from twitter_ads.client import Client
from twitter_ads.creative import MediaLibrary, PollCard
from twitter_ads.enum import MEDIA_TYPE
CONSUMER_KEY = ''
CONSUMER_SECRET = ''
ACCESS_TOKEN = ''
ACCESS_TOKEN_SECRET = ''
ACCOUNT_ID = ''
# initialize the client
client = Client(CONSUM... | [
"twitter_ads.creative.MediaLibrary",
"twitter_ads.client.Client",
"twitter_ads.campaign.Tweet.create",
"twitter_ads.creative.PollCard"
] | [((307, 379), 'twitter_ads.client.Client', 'Client', (['CONSUMER_KEY', 'CONSUMER_SECRET', 'ACCESS_TOKEN', 'ACCESS_TOKEN_SECRET'], {}), '(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET)\n', (313, 379), False, 'from twitter_ads.client import Client\n'), ((629, 646), 'twitter_ads.creative.PollCard', 'Pol... |
# Generated by Django 2.2.7 on 2020-01-13 02:32
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('base', '0003_auto_20200113_0225'),
]
operations = [
migrations.RemoveField(
model_name='photo',
name='user',
... | [
"django.db.migrations.RemoveField",
"django.db.models.CharField"
] | [((232, 287), 'django.db.migrations.RemoveField', 'migrations.RemoveField', ([], {'model_name': '"""photo"""', 'name': '"""user"""'}), "(model_name='photo', name='user')\n", (254, 287), False, 'from django.db import migrations, models\n'), ((429, 473), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(... |
import sys
import logging
import click
import entrypoints
LOG_LEVEL_CODES = {
"debug": logging.DEBUG,
"info": logging.INFO,
"warning": logging.WARNING,
"error": logging.ERROR,
}
def merge_extensions(click_group):
"""
Each extension is called with click group for
ultimate agility while p... | [
"entrypoints.get_group_all",
"click.argument",
"kibitzr.storage.PageHistory.clean",
"kibitzr.app.Application",
"kibitzr.stash.Stash.print_content",
"click.group",
"kibitzr.app.Application.bootstrap"
] | [((623, 636), 'click.group', 'click.group', ([], {}), '()\n', (634, 636), False, 'import click\n'), ((1262, 1294), 'click.argument', 'click.argument', (['"""name"""'], {'nargs': '(-1)'}), "('name', nargs=-1)\n", (1276, 1294), False, 'import click\n'), ((1538, 1570), 'click.argument', 'click.argument', (['"""name"""'], ... |
"""Tests for the create_protocol_runner factory."""
import pytest
from pathlib import Path
from opentrons.hardware_control import API as HardwareAPI
from opentrons.protocol_engine import ProtocolEngine, create_protocol_engine
from opentrons.file_runner import (
ProtocolFileType,
ProtocolFile,
JsonFileRunne... | [
"opentrons.file_runner.create_file_runner",
"opentrons.file_runner.ProtocolFile",
"opentrons.protocol_engine.create_protocol_engine"
] | [((773, 848), 'opentrons.file_runner.ProtocolFile', 'ProtocolFile', ([], {'file_type': 'ProtocolFileType.JSON', 'file_path': 'json_protocol_file'}), '(file_type=ProtocolFileType.JSON, file_path=json_protocol_file)\n', (785, 848), False, 'from opentrons.file_runner import ProtocolFileType, ProtocolFile, JsonFileRunner, ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2022/4/18 11:45 上午
# @File : test_api.py
# @Author:
# @Desc : 测试
import unittest
import requests
import time, os
import json
import base64
import random
import string
import pickle
import sys
class LSTMKQGATestCase(unittest.TestCase):
host_server = f'http:... | [
"json.dumps"
] | [((674, 692), 'json.dumps', 'json.dumps', (['params'], {}), '(params)\n', (684, 692), False, 'import json\n'), ((2156, 2174), 'json.dumps', 'json.dumps', (['params'], {}), '(params)\n', (2166, 2174), False, 'import json\n')] |
"""Trajectory Generator for in-place stepping motion for quadruped robot."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import numpy as np
TWO_PI = 2 * math.pi
def _get_actions_asymmetric_sine(phase, tg_params):
"""Returns the leg exte... | [
"numpy.sin",
"numpy.where",
"numpy.array",
"numpy.fmod"
] | [((843, 943), 'numpy.where', 'np.where', (['(phase < stance_lift_cutoff)', "tg_params['amplitude_stance']", "tg_params['amplitude_lift']"], {}), "(phase < stance_lift_cutoff, tg_params['amplitude_stance'],\n tg_params['amplitude_lift'])\n", (851, 943), True, 'import numpy as np\n'), ((978, 1132), 'numpy.where', 'np.... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# main.py
#
import RPi.GPIO as GPIO
import time
import subprocess
import os
PIR_PIN = 11 # GPIO11
GPIO.setmode(GPIO.BOARD) # Use header pin numbers
GPIO.setup(PIR_PIN, GPIO.IN)
running = False # Is a video currently playing?
player ... | [
"RPi.GPIO.setmode",
"subprocess.Popen",
"RPi.GPIO.cleanup",
"RPi.GPIO.setup",
"time.sleep",
"RPi.GPIO.input"
] | [((170, 194), 'RPi.GPIO.setmode', 'GPIO.setmode', (['GPIO.BOARD'], {}), '(GPIO.BOARD)\n', (182, 194), True, 'import RPi.GPIO as GPIO\n'), ((227, 255), 'RPi.GPIO.setup', 'GPIO.setup', (['PIR_PIN', 'GPIO.IN'], {}), '(PIR_PIN, GPIO.IN)\n', (237, 255), True, 'import RPi.GPIO as GPIO\n'), ((1097, 1111), 'RPi.GPIO.cleanup', ... |
###
# Copyright 2015-2019, Institute for Systems Biology
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | [
"io.StringIO",
"bq_data_access.v2.feature_id_utils.FeatureDataTypeHelper.get_feature_def_provider_from_data_type",
"os.environ.setdefault",
"django.setup",
"logging.basicConfig",
"click.argument",
"bq_data_access.v2.feature_id_utils.FeatureDataTypeHelper.get_feature_def_default_config_dict_from_data_typ... | [((681, 715), 'future.standard_library.install_aliases', 'standard_library.install_aliases', ([], {}), '()\n', (713, 715), False, 'from future import standard_library\n'), ((903, 970), 'os.environ.setdefault', 'os.environ.setdefault', (['"""DJANGO_SETTINGS_MODULE"""', '"""isb_cgc.settings"""'], {}), "('DJANGO_SETTINGS_... |
import abna
import json
import settings
class ABNClient:
mutations = None
new_last_transaction = None
FILENAME = "last_transactions.json"
def __init__(self):
self.sess = abna.Session(settings.ABNA_ACCOUNT)
self.sess.login(settings.ABNA_PASSNUMBER, settings.ABNA_PASSWORD)
self.... | [
"json.dump",
"abna.Session",
"json.load"
] | [((197, 232), 'abna.Session', 'abna.Session', (['settings.ABNA_ACCOUNT'], {}), '(settings.ABNA_ACCOUNT)\n', (209, 232), False, 'import abna\n'), ((1285, 1321), 'json.dump', 'json.dump', (['self.last_transactions', 'f'], {}), '(self.last_transactions, f)\n', (1294, 1321), False, 'import json\n'), ((1453, 1465), 'json.lo... |
# Adapted from:
# https://www.analyticsvidhya.com/blog/2016/08/beginners-guide-to-topic-modeling-in-python/
import read_bibtex
import os, shutil
from nltk.corpus import stopwords
from nltk.stem.wordnet import WordNetLemmatizer
from nltk.stem.porter import PorterStemmer
import string
import gensim
from gensim import c... | [
"os.mkdir",
"shutil.rmtree",
"nltk.stem.porter.PorterStemmer",
"gensim.corpora.Dictionary",
"numpy.array",
"nltk.corpus.stopwords.words",
"nltk.stem.wordnet.WordNetLemmatizer",
"read_bibtex.bibtex_tostring_from",
"os.listdir"
] | [((670, 689), 'nltk.stem.wordnet.WordNetLemmatizer', 'WordNetLemmatizer', ([], {}), '()\n', (687, 689), False, 'from nltk.stem.wordnet import WordNetLemmatizer\n'), ((700, 715), 'nltk.stem.porter.PorterStemmer', 'PorterStemmer', ([], {}), '()\n', (713, 715), False, 'from nltk.stem.porter import PorterStemmer\n'), ((397... |
import tensorflow as tf
from tensorflow.contrib import slim
import tensorflow.contrib.layers as layers
from ..configuration import *
from .text_classification_train import main
class ModelSimple(object):
"""
Base class to create models for text classification. It uses several layers of GRU cells.
"""
... | [
"tensorflow.reshape",
"tensorflow.train.RMSPropOptimizer",
"tensorflow.nn.rnn_cell.DropoutWrapper",
"tensorflow.greater_equal",
"tensorflow.reduce_max",
"tensorflow.split",
"tensorflow.nn.softmax",
"tensorflow.one_hot",
"tensorflow.nn.softmax_cross_entropy_with_logits",
"tensorflow.gather",
"ten... | [((1325, 1378), 'tensorflow.reshape', 'tf.reshape', (['input_text_begin', '[batch_size, MAX_WORDS]'], {}), '(input_text_begin, [batch_size, MAX_WORDS])\n', (1335, 1378), True, 'import tensorflow as tf\n'), ((2638, 2659), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['logits'], {}), '(logits)\n', (2651, 2659), True, 'impo... |
import urllib.request as req
import ventura._hpath as hpath
import os
def download(url, file_name):
response = req.urlopen(url)
# Create folders if need
hpath.create_dir(file_name)
file = open(file_name,'wb')
file.write(response.read())
file.close()
def get_page(url):
response = req.urlopen(url)
return r... | [
"ventura._hpath.create_dir",
"urllib.request.urlopen"
] | [((113, 129), 'urllib.request.urlopen', 'req.urlopen', (['url'], {}), '(url)\n', (124, 129), True, 'import urllib.request as req\n'), ((159, 186), 'ventura._hpath.create_dir', 'hpath.create_dir', (['file_name'], {}), '(file_name)\n', (175, 186), True, 'import ventura._hpath as hpath\n'), ((294, 310), 'urllib.request.ur... |
import os
from tsserver import app
def get_upload_dir():
return os.path.join(app.root_path, app.config['PHOTOS_UPLOAD_FOLDER'])
| [
"os.path.join"
] | [((71, 134), 'os.path.join', 'os.path.join', (['app.root_path', "app.config['PHOTOS_UPLOAD_FOLDER']"], {}), "(app.root_path, app.config['PHOTOS_UPLOAD_FOLDER'])\n", (83, 134), False, 'import os\n')] |
from django.shortcuts import render, HttpResponseRedirect
from django.urls import reverse
import Store.views
from Store.models.productModel import *
from .forms import CustomerPaymentForm
from .models import *
from Store.models.productModel import CustomerOrders
def cart_view(request):
try:
the_id = reque... | [
"django.shortcuts.render",
"Store.models.productModel.CustomerOrders",
"django.urls.reverse"
] | [((1033, 1067), 'django.shortcuts.render', 'render', (['request', 'template', 'context'], {}), '(request, template, context)\n', (1039, 1067), False, 'from django.shortcuts import render, HttpResponseRedirect\n'), ((3646, 3693), 'django.shortcuts.render', 'render', (['request', '"""payment.html"""', "{'form': form}"], ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='GoogleCivicCandidateCampaign',
fields=[
('id', ... | [
"django.db.models.CharField",
"django.db.models.URLField",
"django.db.models.BooleanField",
"django.db.models.AutoField"
] | [((320, 413), '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", (336, 413), False, 'from django.db import models, migrations\... |
import unittest
from unittest.mock import patch
from nose.tools import eq_
from buoy.client.network import ip
class MockResponse:
def __init__(self, **kwargs):
self.content = str.encode(kwargs.pop('content', ""))
self.status_code = kwargs.pop('status_code', 404)
class TestPublicIP(unittest.Tes... | [
"unittest.main",
"unittest.mock.patch.object",
"nose.tools.eq_",
"buoy.client.network.ip.get_public_ip"
] | [((518, 541), 'unittest.mock.patch.object', 'patch.object', (['ip', '"""get"""'], {}), "(ip, 'get')\n", (530, 541), False, 'from unittest.mock import patch\n'), ((1148, 1171), 'unittest.mock.patch.object', 'patch.object', (['ip', '"""get"""'], {}), "(ip, 'get')\n", (1160, 1171), False, 'from unittest.mock import patch\... |
import json
import numpy as np
import pandas as pd
pd.options.mode.chained_assignment = None
from sklearn.preprocessing import Imputer, StandardScaler
import DataSource
import os.path
class NYK(DataSource.DataSource):
def __init__(self, app, dsrc_name='', dsrc_type='csv', dsrc_path='data/', file_name='', header_r... | [
"DataSource.DataSource.__init__",
"sklearn.preprocessing.StandardScaler",
"sklearn.preprocessing.Imputer",
"numpy.tan",
"pandas.to_datetime"
] | [((417, 469), 'DataSource.DataSource.__init__', 'DataSource.DataSource.__init__', (['self', 'app', 'dsrc_name'], {}), '(self, app, dsrc_name)\n', (447, 469), False, 'import DataSource\n'), ((1863, 1918), 'sklearn.preprocessing.Imputer', 'Imputer', ([], {'missing_values': 'np.nan', 'strategy': 'method', 'axis': '(1)'}),... |
#!/usr/bin/env python3
# Created on 05/07/2018
# @author: <NAME>
# @license: MIT-license
# Purpose: example of multiple agent flocking behavior
# Explanation:
import pygame, sys, random, math
pygame.init()
stopped = False
window_height = 800
window_width = 600
black = (0,0,0)
white = (255,255,255)
class agent:
... | [
"pygame.event.get",
"pygame.mouse.get_pos",
"pygame.init"
] | [((195, 208), 'pygame.init', 'pygame.init', ([], {}), '()\n', (206, 208), False, 'import pygame, sys, random, math\n'), ((471, 489), 'pygame.event.get', 'pygame.event.get', ([], {}), '()\n', (487, 489), False, 'import pygame, sys, random, math\n'), ((579, 601), 'pygame.mouse.get_pos', 'pygame.mouse.get_pos', ([], {}), ... |
import numpy as np
import torch
from .base_wrapper import BaseWrapper
from torch.autograd.functional import hvp, vhp, hessian
from typing import List, Tuple, Dict, Union, Callable
from torch import nn, Tensor
class TorchWrapper(BaseWrapper):
def __init__(self, func, precision='float32', hvp_type='vhp', device='cp... | [
"torch.autograd.functional.hessian",
"numpy.concatenate",
"torch.autograd.grad",
"torch.cat",
"numpy.reshape",
"torch.device",
"torch.is_tensor",
"torch.tensor"
] | [((1248, 1289), 'torch.autograd.grad', 'torch.autograd.grad', (['loss', 'input_var_grad'], {}), '(loss, input_var_grad)\n', (1267, 1289), False, 'import torch\n'), ((2621, 2686), 'torch.tensor', 'torch.tensor', (['input_var'], {'dtype': 'self.precision', 'device': 'self.device'}), '(input_var, dtype=self.precision, dev... |
import logging
from django.core.management.base import LabelCommand
from corehq.apps.accounting.models import Currency
from corehq.apps.sms.models import INCOMING, OUTGOING
from corehq.apps.smsbillables.models import SmsGatewayFee
from corehq.apps.unicel.api import UnicelBackend
logger = logging.getLogger('accounting... | [
"corehq.apps.accounting.models.Currency.objects.get",
"logging.getLogger",
"corehq.apps.unicel.api.UnicelBackend.get_api_id"
] | [((291, 322), 'logging.getLogger', 'logging.getLogger', (['"""accounting"""'], {}), "('accounting')\n", (308, 322), False, 'import logging\n'), ((502, 528), 'corehq.apps.unicel.api.UnicelBackend.get_api_id', 'UnicelBackend.get_api_id', ([], {}), '()\n', (526, 528), False, 'from corehq.apps.unicel.api import UnicelBacke... |
import os
import os.path
from inspect import getmembers
import manhole
from .log_init import init_logging
from .web import Web
from ..core.playbooks.playbooks_event_handler_impl import PlaybooksEventHandlerImpl
from .. import api as robusta_api
from .config_loader import ConfigLoader
from ..model.config import Registr... | [
"os.environ.get",
"inspect.getmembers"
] | [((495, 536), 'os.environ.get', 'os.environ.get', (['"""ENABLE_MANHOLE"""', '"""false"""'], {}), "('ENABLE_MANHOLE', 'false')\n", (509, 536), False, 'import os\n'), ((592, 615), 'inspect.getmembers', 'getmembers', (['robusta_api'], {}), '(robusta_api)\n', (602, 615), False, 'from inspect import getmembers\n')] |
from rest_framework import viewsets, mixins
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from .serializers import TagSerializer, IngredientSerializer, RecipeSerializer
from core.models import Tag, Ingredient, Recipe
class BaseRecipeAttrViewSet(vi... | [
"core.models.Ingredient.objects.all",
"core.models.Recipe.objects.all",
"core.models.Tag.objects.all"
] | [((1090, 1107), 'core.models.Tag.objects.all', 'Tag.objects.all', ([], {}), '()\n', (1105, 1107), False, 'from core.models import Tag, Ingredient, Recipe\n'), ((1263, 1287), 'core.models.Ingredient.objects.all', 'Ingredient.objects.all', ([], {}), '()\n', (1285, 1287), False, 'from core.models import Tag, Ingredient, R... |
""" Serializers used by the sample app """
from authentic.entities import Account
from protean.context import context
from protean_flask.core.serializers import EntitySerializer
from protean_flask.core.serializers import ma
from .entities import Human
class AccountSerializer(EntitySerializer):
""" Serializer for... | [
"protean_flask.core.serializers.ma.fields.Integer",
"protean_flask.core.serializers.ma.fields.Method"
] | [((348, 367), 'protean_flask.core.serializers.ma.fields.Integer', 'ma.fields.Integer', ([], {}), '()\n', (365, 367), False, 'from protean_flask.core.serializers import ma\n'), ((656, 695), 'protean_flask.core.serializers.ma.fields.Method', 'ma.fields.Method', (['"""get_current_account"""'], {}), "('get_current_account'... |
#### NOT WORKING
import logging
import configs
import tweepy
import pymongo
import json
# TWITTER PARAMS
HASHTAGS_LIST = configs.HASHTAGS_LIST
# MONGODB PARAMS
MONGO_COL_TWEETS = configs.MONGO_COL_TWEETS
MONGO_COL_USER = configs.MONGO_COL_USER
MONGO_COL_TTAGS = configs.MONGO_COL_TTAGS
MONGO_COL_LOCALE = configs.MONG... | [
"logging.info",
"configs.cleanup_collection"
] | [((419, 474), 'logging.info', 'logging.info', (['"""entrando na funcao get_user_locale_info"""'], {}), "('entrando na funcao get_user_locale_info')\n", (431, 474), False, 'import logging\n'), ((1119, 1167), 'logging.info', 'logging.info', (['"""entrando na funcao get_user_info"""'], {}), "('entrando na funcao get_user_... |
# coding=utf-8
import http.client
import hashlib
import urllib
import random
import json
class BaiduTranslate:
appid = '' # 填写你的appid
secretKey = '' # 填写你的密钥
httpClient = None
def __init__(self, appid, secretKey):
self.appid = appid
self.secretKey = secretKey
def translate(se... | [
"urllib.parse.quote",
"random.randint",
"json.loads"
] | [((450, 478), 'random.randint', 'random.randint', (['(32768)', '(65536)'], {}), '(32768, 65536)\n', (464, 478), False, 'import random\n'), ((1074, 1096), 'json.loads', 'json.loads', (['result_all'], {}), '(result_all)\n', (1084, 1096), False, 'import json\n'), ((663, 684), 'urllib.parse.quote', 'urllib.parse.quote', ([... |
import requests
from dataset import Dataset
from exceptions import (
InsufficientMetadataError, MethodNotAllowedError, OperationFailedError,
ConnectionError
)
from utils import get_element, get_elements, sanitize
class Dataverse(object):
def __init__(self, connection, collection):
self.connection... | [
"exceptions.MethodNotAllowedError",
"exceptions.InsufficientMetadataError",
"utils.get_elements",
"requests.delete",
"dataset.Dataset.from_dataverse",
"requests.get",
"requests.post",
"exceptions.ConnectionError",
"exceptions.OperationFailedError",
"utils.get_element"
] | [((610, 726), 'utils.get_element', 'get_element', (['collection_info'], {'namespace': '"""http://purl.org/net/sword/terms/state"""', 'tag': '"""dataverseHasBeenReleased"""'}), "(collection_info, namespace=\n 'http://purl.org/net/sword/terms/state', tag='dataverseHasBeenReleased')\n", (621, 726), False, 'from utils i... |
# -*- encoding: utf-8 -*-
#
# Copyright © 2018–2021 Mergify SAS
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | [
"mergify_engine.context.Context.create",
"yaml.dump"
] | [((3562, 3614), 'mergify_engine.context.Context.create', 'context.Context.create', (['self.repository_ctxt', 'p1', '[]'], {}), '(self.repository_ctxt, p1, [])\n', (3584, 3614), False, 'from mergify_engine import context\n'), ((1337, 1353), 'yaml.dump', 'yaml.dump', (['rules'], {}), '(rules)\n', (1346, 1353), False, 'im... |
import msal
import logging
import requests
import json
config = {
"authority": "https://login.microsoftonline.com/9f4083b0-0ac6-4dee-b0bb-b78b1436f9f3",
"client_id": "d584a43a-c4c1-4fbe-9c1c-3cae87420e6e",
"scope": [ "https://graph.microsoft.com/.default" ],
"secret": "<KEY>",
"endpoint": "https://... | [
"json.dumps",
"logging.info",
"requests.get",
"requests.post",
"msal.ConfidentialClientApplication"
] | [((439, 566), 'msal.ConfidentialClientApplication', 'msal.ConfidentialClientApplication', (["config['client_id']"], {'authority': "config['authority']", 'client_credential': "config['secret']"}), "(config['client_id'], authority=config[\n 'authority'], client_credential=config['secret'])\n", (473, 566), False, 'impo... |
# Copyright (c) 2014-2021, Dr <NAME>, Raysect Project
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# thi... | [
"unittest.main",
"raysect.core.math.cython.tetrahedra._test_barycentric_inside_tetrahedra"
] | [((4500, 4515), 'unittest.main', 'unittest.main', ([], {}), '()\n', (4513, 4515), False, 'import unittest\n'), ((2241, 2337), 'raysect.core.math.cython.tetrahedra._test_barycentric_inside_tetrahedra', 'inside_tetrahedra', (['v1x', 'v1y', 'v1z', 'v2x', 'v2y', 'v2z', 'v3x', 'v3y', 'v3z', 'v4x', 'v4y', 'v4z', 'v1x', 'v1y'... |
from django.db import models
from django.contrib.auth.models import User
from blog.models import Post
class Comment(models.Model):
STATUS_ITEMS = (
(1,'正常'),
(2,'删除'),
)
target = models.CharField(max_length=200, null=True, verbose_name='评论目标')
content = models.CharField(max_length=20... | [
"django.db.models.URLField",
"django.db.models.CharField",
"django.db.models.PositiveIntegerField",
"django.db.models.EmailField",
"django.db.models.DateTimeField"
] | [((211, 275), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(200)', 'null': '(True)', 'verbose_name': '"""评论目标"""'}), "(max_length=200, null=True, verbose_name='评论目标')\n", (227, 275), False, 'from django.db import models\n'), ((290, 342), 'django.db.models.CharField', 'models.CharField', ([], {... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
from torch import nn
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from torch.nn.modules.utils import _pair
from mmdet import _Custom as _C
from apex import amp
class _RROIAli... | [
"mmdet._Custom.rotate_roi_align_forward",
"torch.nn.modules.utils._pair"
] | [((455, 470), 'torch.nn.modules.utils._pair', '_pair', (['out_size'], {}), '(out_size)\n', (460, 470), False, 'from torch.nn.modules.utils import _pair\n'), ((716, 804), 'mmdet._Custom.rotate_roi_align_forward', '_C.rotate_roi_align_forward', (['features', 'rois', 'spatial_scale', 'out_h', 'out_w', 'sample_num'], {}), ... |
from torch import nn
from attrdict import AttrDict
import torch
import torch.nn.functional as F
from lie_conv.dynamicsTrainer import Partial
from torchdiffeq import odeint
from lie_conv.hamiltonian import SpringV, SpringH, HamiltonianDynamics, KeplerV, KeplerH
class DynamicsPredictor(nn.Module):
"""This class i... | [
"lie_conv.dynamicsTrainer.Partial",
"lie_conv.hamiltonian.SpringV",
"torchdiffeq.odeint",
"torch.no_grad",
"lie_conv.hamiltonian.HamiltonianDynamics",
"attrdict.AttrDict"
] | [((917, 957), 'lie_conv.dynamicsTrainer.Partial', 'Partial', (['self.predictor'], {'sysP': 'sys_params'}), '(self.predictor, sysP=sys_params)\n', (924, 957), False, 'from lie_conv.dynamicsTrainer import Partial\n'), ((971, 1022), 'torchdiffeq.odeint', 'odeint', (['dynamics', 'z0', 'ts[0]'], {'rtol': 'tol', 'method': '"... |
import numpy as np
from utils import pick_discrete
class PseudoMarginalData(object):
def __init__(self, data, interim_prior):
# Data should have dims [NOBJ, NSAMPLE, NDIM] or [NOBJ, NSAMPLE] if NDIM is 1
# interim_prior should have dims [NOBJ, NSAMPLE]
self.data = data
self.interim... | [
"numpy.sum",
"utils.pick_discrete"
] | [((1570, 1588), 'numpy.sum', 'np.sum', (['ps'], {'axis': '(1)'}), '(ps, axis=1)\n', (1576, 1588), True, 'import numpy as np\n'), ((1642, 1658), 'utils.pick_discrete', 'pick_discrete', (['p'], {}), '(p)\n', (1655, 1658), False, 'from utils import pick_discrete\n')] |
#!/usr/bin/python3
"""
This module contains classes for parsing the imgur.com site. It consists of three
classes:
~ ImgurException
~ ImgurFileFormats
~ Imgur
Imgur is the main class and it obtains list of direct image urls that could be
used to download images. Example usage:
```python3
imgur = Imgur('http://imgur... | [
"re.findall",
"re.match",
"collections.deque",
"urllib.request.urlopen"
] | [((2573, 2580), 'collections.deque', 'deque', ([], {}), '()\n', (2578, 2580), False, 'from collections import deque\n'), ((2777, 2830), 're.match', 're.match', (['"""https?\\\\:\\\\/\\\\/(i\\\\.)?imgur\\\\.com\\\\/"""', 'url'], {}), "('https?\\\\:\\\\/\\\\/(i\\\\.)?imgur\\\\.com\\\\/', url)\n", (2785, 2830), False, 'im... |
import pefile
import numpy as np
# import os
execs = [
"1F2EB7B090018D975E6D9B40868C94CA",
"33DE5067A433A6EC5C328067DC18EC37",
"65018CD542145A3792BA09985734C12A",
"<KEY>",
"<KEY>",
"<KEY>",
"<KEY>",
"<KEY>",
"A316D5AECA269CA865077E7FFF356E7D",
"<KEY>",
"AL65_DB05DF0498B59B42A8E493CF3C10C578",
"B07322743778B5868475DBE... | [
"pandas.DataFrame",
"pefile.PE",
"numpy.array",
"numpy.unique"
] | [((5899, 5923), 'pandas.DataFrame', 'pd.DataFrame', (['granPrueba'], {}), '(granPrueba)\n', (5911, 5923), True, 'import pandas as pd\n'), ((2017, 2029), 'pefile.PE', 'pefile.PE', (['a'], {}), '(a)\n', (2026, 2029), False, 'import pefile\n'), ((5981, 5996), 'numpy.array', 'np.array', (['list1'], {}), '(list1)\n', (5989,... |
# -*- coding: utf-8 -*-
''' The main script to run, enables profiling. '''
import numpy as np
import math
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from crystal import *
from plot_init_tools import *
def main(num_of_growths):
''' Main method to start simulation. Uncomment specific ... | [
"pstats.Stats",
"cProfile.run"
] | [((1650, 1684), 'cProfile.run', 'cProfile.run', (['"""main(50)"""', '"""pstats"""'], {}), "('main(50)', 'pstats')\n", (1662, 1684), False, 'import cProfile\n'), ((1722, 1737), 'pstats.Stats', 'Stats', (['"""pstats"""'], {}), "('pstats')\n", (1727, 1737), False, 'from pstats import Stats\n')] |
# -*- coding: utf-8 -*-
from os import path, getcwd, makedirs, listdir, remove
from typing import *
import pickle
from abc import ABCMeta, abstractmethod
from sgfmill.sgf import Sgf_game
import numpy as np
from .go_types import *
__all__ = ["set_cache_dir", "get_cache_dir", "get_game_dir", "get_archive_dir",
... | [
"os.remove",
"pickle.dump",
"os.getcwd",
"os.path.realpath",
"pickle.load",
"os.path.join"
] | [((546, 574), 'os.path.join', 'path.join', (['cache_dir', '""".kgs"""'], {}), "(cache_dir, '.kgs')\n", (555, 574), False, 'from os import path, getcwd, makedirs, listdir, remove\n'), ((589, 618), 'os.path.join', 'path.join', (['cache_dir', '""".game"""'], {}), "(cache_dir, '.game')\n", (598, 618), False, 'from os impor... |
from collections import defaultdict
import gzip
import os
import random
import textwrap
class Heresy(Exception):
"""You have defiled the word of God!"""
pass
def bits(byte_string):
"""Generates a sequence of bits from a byte stream"""
for byte in byte_string:
for bit_num in range(8):
... | [
"gzip.decompress",
"random.choice",
"os.path.abspath",
"gzip.compress"
] | [((2267, 2294), 'gzip.compress', 'gzip.compress', (['unholy_bytes'], {}), '(unholy_bytes)\n', (2280, 2294), False, 'import gzip\n'), ((2366, 2400), 'random.choice', 'random.choice', (['self.capital_tuples'], {}), '(self.capital_tuples)\n', (2379, 2400), False, 'import random\n'), ((2981, 3014), 'random.choice', 'random... |
import socket
import os
import pytest
import pyvista
from pyansys.misc import get_ansys_bin
import pyansys
from pyansys.errors import MapdlExitedError
pyvista.OFF_SCREEN = True
# check for a valid MAPDL install with CORBA
valid_rver = ['182', '190', '191', '192', '193', '194', '195', '201']
EXEC_FILE = None
for rv... | [
"pyansys.launch_mapdl",
"pyansys.misc.get_ansys_bin",
"pytest.fixture",
"socket.gethostname",
"pytest.raises",
"pytest.mark.skipif",
"os.path.isfile"
] | [((548, 616), 'pytest.mark.skipif', 'pytest.mark.skipif', (['(not HAS_ANSYS)'], {'reason': '"""Requires ANSYS installed"""'}), "(not HAS_ANSYS, reason='Requires ANSYS installed')\n", (566, 616), False, 'import pytest\n'), ((803, 848), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""', 'params': 'modes'... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Description: Build a structural data from orginial Cranfield collection and
# implement the BM25 alogrithm information retrieval;
# also 5 evaluation methods (precision, recall, MAP, P at N and
# NDCG at N) are applied.
# ... | [
"json.load",
"porter.PorterStemmer",
"argparse.ArgumentParser",
"math.sqrt",
"os.path.exists",
"math.log"
] | [((2791, 3065), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""A script used to build BM25 model and relative evaluation methods. If the index JSON file is not available, just type `python3 bm25.py` to generate one in the working directory and extra arguments will be ignored in this case... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2018-11-14 19:30
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("variants", "0012_auto_20181114_1914")]
operations = [
migrations.AddField(
... | [
"django.db.models.CharField"
] | [((403, 570), 'django.db.models.CharField', 'models.CharField', ([], {'choices': "[('positive', 'positive'), ('uncertain', 'uncertain'), ('negative',\n 'negative'), ('empty', 'empty')]", 'default': '"""empty"""', 'max_length': '(32)'}), "(choices=[('positive', 'positive'), ('uncertain',\n 'uncertain'), ('negative... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# /*******************************************************
# * Copyright (C) 2013-2014 CloudRunner.io <<EMAIL>>
# *
# * Proprietary and confidential
# * This file is part of CloudRunner Server.
# *
# * CloudRunner Server can no... | [
"pecan.request.db.rollback",
"cloudrunner_server.api.decorators.wrap_command",
"pecan.request.db.query",
"cloudrunner_server.api.policy.decorators.check_policy",
"pecan.request.db.commit",
"pecan.expose",
"pecan.request.db.delete",
"pecan.request.db.add",
"cloudrunner_server.api.model.Role",
"clou... | [((812, 831), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (829, 831), False, 'import logging\n'), ((862, 890), 'pecan.expose', 'expose', (['"""json"""'], {'generic': '(True)'}), "('json', generic=True)\n", (868, 890), False, 'from pecan import expose, request\n'), ((896, 920), 'cloudrunner_server.api.po... |
"""
A client api for couchdb attachments
"""
"""Main module."""
import logging
import fnmatch
import io
import mimetypes
import os
import pathlib
import re
import tempfile
from contextlib import contextmanager
import requests
logger = logging.getLogger(__file__)
echo = logger.info
class CouchDBClientException(Exc... | [
"os.unlink",
"os.walk",
"os.path.isfile",
"pathlib.Path",
"requests.post",
"os.path.join",
"mimetypes.guess_type",
"os.path.abspath",
"requests.get",
"requests.put",
"io.BytesIO",
"requests.head",
"os.path.basename",
"fnmatch.translate",
"re.compile",
"tempfile.NamedTemporaryFile",
"... | [((240, 267), 'logging.getLogger', 'logging.getLogger', (['__file__'], {}), '(__file__)\n', (257, 267), False, 'import logging\n'), ((753, 778), 're.compile', 're.compile', (['CONNECTION_RE'], {}), '(CONNECTION_RE)\n', (763, 778), False, 'import re\n'), ((4038, 4067), 're.compile', 're.compile', (['"""[\\\\*\\\\?\\\\[\... |
# http://www.codewars.com/kata/5390bac347d09b7da40006f6/
import string
def to_jaden_case(s):
return string.capwords(s)
| [
"string.capwords"
] | [((107, 125), 'string.capwords', 'string.capwords', (['s'], {}), '(s)\n', (122, 125), False, 'import string\n')] |
"""
<NAME> 2017
scripts/annotate_variants.py
Use ANNOVAR to first convert a sample into annovar format and then annotate
"""
import os
import argparse
import subprocess
parser = argparse.ArgumentParser()
parser.add_argument('-m', '--merged', action='store_true',
help='use directory for merged VCF... | [
"argparse.ArgumentParser",
"os.path.isfile",
"subprocess.call",
"os.path.join",
"os.listdir"
] | [((181, 206), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (204, 206), False, 'import argparse\n'), ((1209, 1243), 'os.path.join', 'os.path.join', (['"""modules"""', '"""annovar"""'], {}), "('modules', 'annovar')\n", (1221, 1243), False, 'import os\n'), ((1258, 1295), 'os.path.join', 'os.path... |
import numpy as np
#TODO:
#1. create a streamlined and replicable gif creation set of functions in this file.
#2. implement these functions into the generation algorithms available.
def convert_2d(index, cols):
return (index // cols, index % cols)
def bounds_check(index, rows, cols):
if index[0] < 0 or index[... | [
"numpy.array_equal"
] | [((3427, 3462), 'numpy.array_equal', 'np.array_equal', (['newIMG', 'gif_arr[-1]'], {}), '(newIMG, gif_arr[-1])\n', (3441, 3462), True, 'import numpy as np\n'), ((3805, 3840), 'numpy.array_equal', 'np.array_equal', (['newIMG', 'gif_arr[-1]'], {}), '(newIMG, gif_arr[-1])\n', (3819, 3840), True, 'import numpy as np\n')] |
#use python3
import sys
def getNthFib(n):
if n == 2:
return 1
elif n == 1:
return 0
previous = 0
current = 1
for _ in range(n-2):
previous, current = current, previous + current
return current
if __name__ == '__main__':
# Expected only one inte... | [
"sys.stdin.read"
] | [((346, 362), 'sys.stdin.read', 'sys.stdin.read', ([], {}), '()\n', (360, 362), False, 'import sys\n')] |
from os.path import join
import yaml
class Story:
def __init__(self, path):
self.path = path
self.author = None
self.title = None
self.scene = None
self.synopsis = None
def load(self):
f = open(self.filename(), 'r')
text = f.read()
f.close()
... | [
"yaml.load",
"os.path.join"
] | [((333, 348), 'yaml.load', 'yaml.load', (['text'], {}), '(text)\n', (342, 348), False, 'import yaml\n'), ((511, 540), 'os.path.join', 'join', (['self.path', '"""story.yaml"""'], {}), "(self.path, 'story.yaml')\n", (515, 540), False, 'from os.path import join\n'), ((826, 841), 'yaml.load', 'yaml.load', (['text'], {}), '... |
import contextlib
import logging
import logging.config
import random
import time
from pathlib import Path
import hp_transfer_benchmarks # pylint: disable=unused-import
import hp_transfer_optimizers # pylint: disable=unused-import
import hydra
import numpy as np
import yaml
from gitinfo import gitinfo
from hp_trans... | [
"omegaconf.OmegaConf.to_yaml",
"hp_transfer_aa_experiments.analyse.read_results.get_batch_result_row",
"numpy.random.seed",
"hydra.utils.to_absolute_path",
"hydra.utils.instantiate",
"contextlib.suppress",
"time.sleep",
"hp_transfer_optimizers.core.result.TrajectoryResult",
"pathlib.Path",
"random... | [((608, 659), 'logging.getLogger', 'logging.getLogger', (['"""hp_transfer_aa_experiments.run"""'], {}), "('hp_transfer_aa_experiments.run')\n", (625, 659), False, 'import logging\n'), ((7222, 7274), 'hydra.main', 'hydra.main', ([], {'config_path': '"""configs"""', 'config_name': '"""run"""'}), "(config_path='configs', ... |
from qiniu import Auth, put_data
#需要填写你的 Access Key 和 Secret Key
access_key = '<KEY>'
secret_key = '<KEY>'
def image_url(image_data):
#构建鉴权对象
q = Auth(access_key, secret_key)
#要上传的空间
bucket_name = 'new3333'
#上传后保存的文件名
key = None
# 处理上传结果
token = q.upload_token(bucket_name, key, 3600... | [
"qiniu.put_data",
"qiniu.Auth"
] | [((156, 184), 'qiniu.Auth', 'Auth', (['access_key', 'secret_key'], {}), '(access_key, secret_key)\n', (160, 184), False, 'from qiniu import Auth, put_data\n'), ((338, 370), 'qiniu.put_data', 'put_data', (['token', 'key', 'image_data'], {}), '(token, key, image_data)\n', (346, 370), False, 'from qiniu import Auth, put_d... |
from tests.unit.dataactcore.factories.staging import DetachedAwardFinancialAssistanceFactory
from tests.unit.dataactvalidator.utils import number_of_errors, query_columns
_FILE = 'fabsreq9_detached_award_financial_assistance'
def test_column_headers(database):
expected_subset = {'row_number', 'awardee_or_recipie... | [
"tests.unit.dataactvalidator.utils.number_of_errors",
"tests.unit.dataactcore.factories.staging.DetachedAwardFinancialAssistanceFactory",
"tests.unit.dataactvalidator.utils.query_columns"
] | [((666, 780), 'tests.unit.dataactcore.factories.staging.DetachedAwardFinancialAssistanceFactory', 'DetachedAwardFinancialAssistanceFactory', ([], {'correction_delete_indicatr': '"""C"""', 'awardee_or_recipient_legal': '"""REDACTED"""'}), "(correction_delete_indicatr='C',\n awardee_or_recipient_legal='REDACTED')\n", ... |
import numpy as np
import pytest
from packaging.utils import Version
import fast_numpy_loops
old_numpy = Version(np.__version__) < Version('1.18')
@pytest.fixture(scope='session')
def initialize_fast_numpy_loops():
fast_numpy_loops.initialize()
@pytest.fixture(scope='function')
def rng():
if old_numpy:
... | [
"numpy.random.default_rng",
"fast_numpy_loops.initialize",
"pytest.fixture",
"packaging.utils.Version"
] | [((150, 181), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (164, 181), False, 'import pytest\n'), ((253, 285), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""'}), "(scope='function')\n", (267, 285), False, 'import pytest\n'), ((106, 129), 'packaging.uti... |
#!/usr/bin/python3
"""
Bunch of country related function to help get extended data.
"""
import json
import requests
# Load country codes file and store into variable
countries_file = open('assets/country-codes.json')
countries = json.load(countries_file)
countries_file.close()
# Load country lat and long file and st... | [
"json.load"
] | [((231, 256), 'json.load', 'json.load', (['countries_file'], {}), '(countries_file)\n', (240, 256), False, 'import json\n'), ((417, 447), 'json.load', 'json.load', (['country_latlng_file'], {}), '(country_latlng_file)\n', (426, 447), False, 'import json\n'), ((2644, 2666), 'json.load', 'json.load', (['cities_file'], {}... |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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... | [
"mindspore.ops.BroadcastTo",
"mindspore.numpy.amax",
"mindspore.ops.Cast",
"mindspore.numpy.full",
"mindspore.ops.ReduceSum",
"mindspore.numpy.mean",
"mindspore.ops.ReduceMax",
"mindspore.ops.Equal",
"mindspore.ops.Pow",
"mindspore.numpy.maximum",
"mindspore.numpy.zeros",
"mindspore.ops.Reduce... | [((1132, 1162), 'mindspore.ops.ReduceSum', 'ops.ReduceSum', ([], {'keep_dims': '(False)'}), '(keep_dims=False)\n', (1145, 1162), True, 'import mindspore.ops as ops\n'), ((1230, 1286), 'mindspore.numpy.maximum', 'np.maximum', (['(0)', '(-target * (input1 - input2) + self.margin)'], {}), '(0, -target * (input1 - input2) ... |
from pathlib import Path
from unittest import TestCase
from gains.io import FitbodLoader
class TestFitbodLoader(TestCase):
data_filename = Path(__file__).parent / "data.csv"
def test_loading_data(self):
loader = FitbodLoader(self.data_filename)
analysis = loader.analysis
exercises ... | [
"pathlib.Path",
"gains.io.FitbodLoader"
] | [((233, 265), 'gains.io.FitbodLoader', 'FitbodLoader', (['self.data_filename'], {}), '(self.data_filename)\n', (245, 265), False, 'from gains.io import FitbodLoader\n'), ((147, 161), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (151, 161), False, 'from pathlib import Path\n')] |
from django.test import TestCase
from django_enum_choices.forms import EnumChoiceField
from .testapp.enumerations import CharTestEnum
class FormFieldTests(TestCase):
def test_field_instance_creates_choices_correctly(self):
instance = EnumChoiceField(CharTestEnum)
choices = instance.build_choices... | [
"django_enum_choices.forms.EnumChoiceField"
] | [((250, 279), 'django_enum_choices.forms.EnumChoiceField', 'EnumChoiceField', (['CharTestEnum'], {}), '(CharTestEnum)\n', (265, 279), False, 'from django_enum_choices.forms import EnumChoiceField\n'), ((685, 745), 'django_enum_choices.forms.EnumChoiceField', 'EnumChoiceField', (['CharTestEnum'], {'choice_builder': 'cho... |
import xarray as xr
from mapshader.transforms import squeeze
from mapshader.transforms import cast
from mapshader.transforms import orient_array
from mapshader.transforms import flip_coords
from mapshader.transforms import reproject_raster
def run_float(input_file, output_file, chunks=(512, 512),
name=... | [
"mapshader.transforms.squeeze",
"argparse.ArgumentParser",
"xarray.open_rasterio",
"mapshader.transforms.flip_coords",
"mapshader.transforms.reproject_raster",
"mapshader.transforms.orient_array",
"os.path.expanduser",
"mapshader.transforms.cast"
] | [((375, 403), 'xarray.open_rasterio', 'xr.open_rasterio', (['input_file'], {}), '(input_file)\n', (391, 403), True, 'import xarray as xr\n'), ((414, 434), 'mapshader.transforms.squeeze', 'squeeze', (['arr', '"""band"""'], {}), "(arr, 'band')\n", (421, 434), False, 'from mapshader.transforms import squeeze\n'), ((445, 4... |
# -*- encoding: utf-8 -*-
def extract_feature_pixel(img, mask_1, mask_0=[], mask_2=[], mask_3=[], mask_4=[], mask_5=[], dim_prof=0):
import numpy as np
#Função de leitura da imagem e máscaras, e retorna array de pixel como atributo
n = img.shape[dim_prof]
t1 = img[mask_1].size/n
t0 = img[mask_0].... | [
"numpy.vstack",
"numpy.zeros",
"numpy.ones",
"numpy.concatenate"
] | [((451, 467), 'numpy.ones', 'np.ones', (['(t1, 1)'], {}), '((t1, 1))\n', (458, 467), True, 'import numpy as np\n'), ((523, 560), 'numpy.concatenate', 'np.concatenate', (['(eval1, ones)'], {'axis': '(1)'}), '((eval1, ones), axis=1)\n', (537, 560), True, 'import numpy as np\n'), ((596, 613), 'numpy.zeros', 'np.zeros', ([... |
from django.urls import include, path, re_path
from . import views as school_views
from django.views.generic import TemplateView
app_name = 'schools'
urlpatterns = [
# if blank show districts(Thissur, palakkad...)
# path('', school_views.states, name='states'),
# if digit, view school information
re_path(r'^(?P<c... | [
"django.urls.re_path",
"django.urls.path"
] | [((304, 398), 'django.urls.re_path', 're_path', (['"""^(?P<code>\\\\d{5})/"""', 'school_views.school_view_kerala'], {'name': '"""school_view_kerala"""'}), "('^(?P<code>\\\\d{5})/', school_views.school_view_kerala, name=\n 'school_view_kerala')\n", (311, 398), False, 'from django.urls import include, path, re_path\n'... |