code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import os
from django.db import models
from django.contrib.postgres.fields import ArrayField
from django.db.models import signals
from django.core.files.base import File
from datetime import *
class Application(models.Model):
applicant = models.ForeignKey('users.Users', on_delete=models.CASCADE)
job = models.F... | [
"django.db.models.OneToOneField",
"django.db.models.DateField",
"django.db.models.TextField",
"django.db.models.ForeignKey",
"django.db.models.FileField",
"os.path.isfile",
"django.core.files.base.File",
"django.db.models.CharField",
"os.remove"
] | [((243, 301), 'django.db.models.ForeignKey', 'models.ForeignKey', (['"""users.Users"""'], {'on_delete': 'models.CASCADE'}), "('users.Users', on_delete=models.CASCADE)\n", (260, 301), False, 'from django.db import models\n'), ((312, 374), 'django.db.models.ForeignKey', 'models.ForeignKey', (['"""postjob.Jobform"""'], {'... |
"""Defines preprocessor to set flash messages to session."""
from aiohttp import web
from aiohttp_session import get_session
from src.utils.globals import (
FLASH_NEW_REQUEST_KEY, FLASH_OLD_REQUEST_KEY, FLASH_SESSION_KEY
)
@web.middleware
async def flash_middleware(request, handler):
"""Save new flash under F... | [
"aiohttp_session.get_session"
] | [((387, 407), 'aiohttp_session.get_session', 'get_session', (['request'], {}), '(request)\n', (398, 407), False, 'from aiohttp_session import get_session\n')] |
#!/usr/bin/env python3
import argparse
import subprocess
import re
import sys
import os
from itertools import chain
# Commands that will require a load db
LOAD_DB_COMMANDS = ["load-db", "load-db-france"]
def exec_command(command, debug=False):
if debug:
print("===>", " ".join(command), file=sys.stderr, ... | [
"os.listdir",
"argparse.ArgumentParser",
"subprocess.Popen",
"re.match",
"sys.exit"
] | [((341, 366), 'subprocess.Popen', 'subprocess.Popen', (['command'], {}), '(command)\n', (357, 366), False, 'import subprocess\n'), ((1730, 2069), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'prog': '"""kartotherian_docker"""', 'formatter_class': 'argparse.RawDescriptionHelpFormatter', 'description': '""... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
#####
Tools
#####
*Created on Thu Jul 2 10:07:56 2015 by <NAME>*
A set of tools to use with the `RDKit <http://rdkit.org>`_ in the IPython notebook.
"""
import time
import sys
import base64
import os
import os.path as op
import random
import csv
import gzip
import ... | [
"csv.DictWriter",
"rdkit.Chem.AllChem.CalcMolFormula",
"csv.DictReader",
"rdkit.Chem.AllChem.GetMolFrags",
"numpy.log10",
"IPython.core.display.display",
"gzip.open",
"PIL.Image.new",
"rdkit.Chem.AllChem.MolFromSmiles",
"rdkit.Chem.AllChem.Compute2DCoords",
"rdkit.Chem.Descriptors.MolLogP",
"r... | [((2527, 2564), 'os.path.isfile', 'op.isfile', (['"""lib/jsme/jsme.nocache.js"""'], {}), "('lib/jsme/jsme.nocache.js')\n", (2536, 2564), True, 'import os.path as op\n'), ((2236, 2260), 'misc_tools.apl_tools.get_commit', 'apt.get_commit', (['__file__'], {}), '(__file__)\n', (2250, 2260), True, 'from misc_tools import ap... |
from flow.src.withdrawal import Withdrawal
from flow.src.deposit import Deposit
from datetime import datetime
first = Deposit(ID = 1, details = "Income", total = 4.5)
print(first)
print()
first = Withdrawal(ID = 1,
details = "Bike shoes",
date = datetime(2021, 2,4,5,6),
unit_price = 4,
amount = 5)
... | [
"datetime.datetime",
"flow.src.deposit.Deposit"
] | [((119, 161), 'flow.src.deposit.Deposit', 'Deposit', ([], {'ID': '(1)', 'details': '"""Income"""', 'total': '(4.5)'}), "(ID=1, details='Income', total=4.5)\n", (126, 161), False, 'from flow.src.deposit import Deposit\n'), ((257, 283), 'datetime.datetime', 'datetime', (['(2021)', '(2)', '(4)', '(5)', '(6)'], {}), '(2021... |
import json
import msgpack
from django.test import SimpleTestCase
from django.test.client import RequestFactory
from django_api_forms import Form
from django_api_forms.exceptions import UnsupportedMediaType
class FormTests(SimpleTestCase):
def test_create_from_request(self):
# TEST: Form.create_from_requ... | [
"msgpack.packb",
"django_api_forms.Form.create_from_request",
"django.test.client.RequestFactory"
] | [((371, 387), 'django.test.client.RequestFactory', 'RequestFactory', ([], {}), '()\n', (385, 387), False, 'from django.test.client import RequestFactory\n'), ((610, 643), 'django_api_forms.Form.create_from_request', 'Form.create_from_request', (['request'], {}), '(request)\n', (634, 643), False, 'from django_api_forms ... |
import cloudpassage
import os
import pytest
config_file_name = "portal.yaml.local"
tests_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "../"))
config_file = os.path.join(tests_dir, "configs/", config_file_name)
session_info = cloudpassage.ApiKeyManager(config_file=config_file)
key_id = session_info.k... | [
"cloudpassage.ApiKeyManager",
"cloudpassage.CveExceptions",
"os.path.join",
"cloudpassage.Server",
"cloudpassage.HaloSession",
"os.path.dirname",
"pytest.raises"
] | [((175, 228), 'os.path.join', 'os.path.join', (['tests_dir', '"""configs/"""', 'config_file_name'], {}), "(tests_dir, 'configs/', config_file_name)\n", (187, 228), False, 'import os\n'), ((245, 296), 'cloudpassage.ApiKeyManager', 'cloudpassage.ApiKeyManager', ([], {'config_file': 'config_file'}), '(config_file=config_f... |
import os
import random
def get_project_root():
return os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
def select_random_directory(basedir):
files = os.listdir(basedir)
directories = [f for f in files if os.path.isdir(os.path.join(basedir, f))]
return random.choice(directories)
| [
"os.path.dirname",
"os.listdir",
"os.path.join",
"random.choice"
] | [((173, 192), 'os.listdir', 'os.listdir', (['basedir'], {}), '(basedir)\n', (183, 192), False, 'import os\n'), ((284, 310), 'random.choice', 'random.choice', (['directories'], {}), '(directories)\n', (297, 310), False, 'import random\n'), ((93, 118), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)... |
from torchtext import data
from torch.utils.data import DataLoader
from graph import MTBatcher, get_mt_dataset, MTDataset, DocumentMTDataset
from modules import make_translation_model
from optim import get_wrapper
from loss import LabelSmoothing
import numpy as np
import torch as th
import torch.optim as optim
import ... | [
"graph.get_mt_dataset",
"loss.LabelSmoothing",
"yaml.load",
"optim.get_wrapper",
"torch.distributed.barrier",
"os.path.exists",
"argparse.ArgumentParser",
"modules.make_translation_model",
"graph.DocumentMTDataset",
"numpy.random.seed",
"os.mkdir",
"torchtext.data.Field",
"torch.distributed.... | [((412, 442), 'torch.manual_seed', 'th.manual_seed', (["config['seed']"], {}), "(config['seed'])\n", (426, 442), True, 'import torch as th\n'), ((447, 477), 'numpy.random.seed', 'np.random.seed', (["config['seed']"], {}), "(config['seed'])\n", (461, 477), True, 'import numpy as np\n'), ((482, 521), 'torch.cuda.manual_s... |
#!/usr/bin/python
import os
import re
import platform
from Bio import AlignIO
from Bio.Seq import Seq
from Bio.Align import AlignInfo
from Bio.Align.Applications import MuscleCommandline
# define constants
HEADER = 1
SEQUENCE = 2
FORWARD = 1
REVERSE = 2
FA_LINES_PER_READ = 2
FQ_LINES_PER_READ = 4
class SequenceDat... | [
"os.listdir",
"Bio.AlignIO.read",
"os.makedirs",
"Bio.Align.AlignInfo.SummaryInfo",
"Bio.Seq.Seq",
"os.path.join",
"Bio.Align.Applications.MuscleCommandline",
"os.chdir",
"os.path.dirname",
"platform.system",
"os.system",
"os.path.expanduser",
"re.search"
] | [((5840, 5893), 'os.makedirs', 'os.makedirs', (['telomeric_reads_directory'], {'exist_ok': '(True)'}), '(telomeric_reads_directory, exist_ok=True)\n', (5851, 5893), False, 'import os\n'), ((7458, 7472), 'os.chdir', 'os.chdir', (['""".."""'], {}), "('..')\n", (7466, 7472), False, 'import os\n'), ((7481, 7549), 'os.syste... |
from stretch_body.dynamixel_hello_XL430 import DynamixelHelloXL430
from stretch_body.hello_utils import *
class WristPitch(DynamixelHelloXL430):
def __init__(self, chain=None):
DynamixelHelloXL430.__init__(self, 'wrist_pitch', chain)
self.poses = {'tool_up': deg_to_rad(45),
't... | [
"stretch_body.dynamixel_hello_XL430.DynamixelHelloXL430.__init__"
] | [((190, 246), 'stretch_body.dynamixel_hello_XL430.DynamixelHelloXL430.__init__', 'DynamixelHelloXL430.__init__', (['self', '"""wrist_pitch"""', 'chain'], {}), "(self, 'wrist_pitch', chain)\n", (218, 246), False, 'from stretch_body.dynamixel_hello_XL430 import DynamixelHelloXL430\n')] |
from sqlalchemy.sql.expression import false
from . import db
from flask_login import UserMixin
from sqlalchemy.sql import func
class User(db.Model,UserMixin):
id = db.Column(db.Integer, primary_key=True)
email =db.Column(db.String(150),unique=True)
firstname = db.Column(db.String(150))
lastname = db.C... | [
"sqlalchemy.sql.func.now"
] | [((490, 500), 'sqlalchemy.sql.func.now', 'func.now', ([], {}), '()\n', (498, 500), False, 'from sqlalchemy.sql import func\n'), ((851, 861), 'sqlalchemy.sql.func.now', 'func.now', ([], {}), '()\n', (859, 861), False, 'from sqlalchemy.sql import func\n')] |
import os
from haikunator import Haikunator
from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.eventgrid import EventGridManagementClient
from azure.mgmt.eventgrid.models import Topic, EventSubscriptionFilter, EventSubscription, We... | [
"haikunator.Haikunator",
"os.environ.get",
"azure.mgmt.resource.ResourceManagementClient",
"azure.mgmt.eventgrid.models.EventSubscription",
"azure.mgmt.eventgrid.EventGridManagementClient",
"azure.mgmt.eventgrid.models.WebHookEventSubscriptionDestination",
"azure.mgmt.eventgrid.models.EventSubscriptionF... | [((453, 465), 'haikunator.Haikunator', 'Haikunator', ([], {}), '()\n', (463, 465), False, 'from haikunator import Haikunator\n'), ((2214, 2293), 'os.environ.get', 'os.environ.get', (['"""AZURE_SUBSCRIPTION_ID"""', '"""11111111-1111-1111-1111-111111111111"""'], {}), "('AZURE_SUBSCRIPTION_ID', '11111111-1111-1111-1111-11... |
import yaml
import inspect
from pcl2depth import velo_points_2_pano
import scipy.io
import numpy as np
import os
from os.path import join
import sys
from tqdm import tqdm
import matplotlib.pyplot as plt
import cv2
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.pat... | [
"os.path.exists",
"cv2.imwrite",
"sys.path.insert",
"os.listdir",
"os.makedirs",
"inspect.currentframe",
"os.path.join",
"numpy.bitwise_and",
"os.path.dirname",
"yaml.safe_load",
"numpy.array",
"numpy.zeros",
"numpy.concatenate",
"cv2.resize",
"sys.path.append",
"pcl2depth.velo_points_... | [((314, 341), 'os.path.dirname', 'os.path.dirname', (['currentdir'], {}), '(currentdir)\n', (329, 341), False, 'import os\n'), ((342, 368), 'sys.path.append', 'sys.path.append', (['parentdir'], {}), '(parentdir)\n', (357, 368), False, 'import sys\n'), ((369, 398), 'sys.path.insert', 'sys.path.insert', (['(1)', 'parentd... |
"""
License
-------
The MIT License (MIT)
Copyright (c) 2018 Snappy2 Project
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation ... | [
"utils.Utility.Utility.reverse_nn_normalization",
"os.path.join",
"numpy.array",
"os.path.dirname",
"cv2.resize"
] | [((1054, 1079), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (1069, 1079), False, 'import os\n'), ((1143, 1236), 'os.path.join', 'os.path.join', (['base_folder', '"""../resource/haarcascades/haarcascade_frontalface_default.xml"""'], {}), "(base_folder,\n '../resource/haarcascades/haarcas... |
from qutebrowser.api import interceptor, message
from PyQt5.QtCore import QUrl
from cconfig import CConfig
def redir(r: interceptor.Request, target, dst):
url = r.request_url
furl = r.first_party_url
# don't redirect if coming from destination
# some alt-sites such as libreddit have a link to the orig... | [
"qutebrowser.api.interceptor.register",
"cconfig.CConfig"
] | [((1284, 1314), 'qutebrowser.api.interceptor.register', 'interceptor.register', (['redirect'], {}), '(redirect)\n', (1304, 1314), False, 'from qutebrowser.api import interceptor, message\n'), ((823, 838), 'cconfig.CConfig', 'CConfig', (['config'], {}), '(config)\n', (830, 838), False, 'from cconfig import CConfig\n')] |
from pathlib import Path
from shutil import rmtree
from aut import WebArchive
from pyspark import SparkContext
from pyspark.sql import SparkSession
from links_in_context.filter_records import (
decode_pages,
get_links_in_context,
filter_links_in_context,
exclude_dest_hosts,
merge_links_in_context,... | [
"links_in_context.filter_records.keep_valid_pages",
"links_in_context.filter_records.merge_links_in_context",
"pyspark.sql.SparkSession.builder.getOrCreate",
"pathlib.Path",
"links_in_context.filter_records.get_links_in_context",
"links_in_context.filter_records.filter_links_in_context",
"pyspark.sql.Sp... | [((374, 400), 'pyspark.SparkContext.getOrCreate', 'SparkContext.getOrCreate', ([], {}), '()\n', (398, 400), False, 'from pyspark import SparkContext\n'), ((414, 448), 'pyspark.sql.SparkSession.builder.getOrCreate', 'SparkSession.builder.getOrCreate', ([], {}), '()\n', (446, 448), False, 'from pyspark.sql import SparkSe... |
# -*- coding: utf-8 -*-
"""Console script for tmm."""
import click
import re
import tm
@click.group(invoke_without_command=True, help="Create, Kill & Resume tmux sessions") # noqa
@click.pass_context
def main(ctx):
"""This is my custom help message"""
if ctx.invoked_subcommand is None:
sessions =... | [
"tm.resume_session",
"click.prompt",
"click.group",
"tm.kill_session",
"click.echo",
"tm.tmux_sessions",
"tm.cmd",
"tm.list_tmux_sessions",
"re.search"
] | [((92, 181), 'click.group', 'click.group', ([], {'invoke_without_command': '(True)', 'help': '"""Create, Kill & Resume tmux sessions"""'}), "(invoke_without_command=True, help=\n 'Create, Kill & Resume tmux sessions')\n", (103, 181), False, 'import click\n'), ((969, 1001), 'click.prompt', 'click.prompt', (['"""Name ... |
from typing import NamedTuple, Tuple, Dict, List, Any
from .quiche_tree import QuicheTree
from .rewrite import Rule
class EClassID:
def __init__(self, id, parent: "EClassID" = None):
self.id = id
self.parent = parent
# List of tuples of (ENode, EClassID) of enodes that use this EClassID
... | [
"graphviz.Digraph"
] | [((3227, 3281), 'graphviz.Digraph', 'Digraph', ([], {'node_attr': "{'shape': 'record', 'height': '.1'}"}), "(node_attr={'shape': 'record', 'height': '.1'})\n", (3234, 3281), False, 'from graphviz import Digraph\n')] |
import xadmin
from .models import Video, HotSearchWords
class VideoAdmin(object):
list_display = ["content", "cover_duration", "cover_start_second", "video", "longitude", "latitude" , "poi_name", "poi_address", "first_create_time", "source"]
search_fields = ['content', ]
list_editable = ["is_hot", ]
li... | [
"xadmin.site.register"
] | [((532, 571), 'xadmin.site.register', 'xadmin.site.register', (['Video', 'VideoAdmin'], {}), '(Video, VideoAdmin)\n', (552, 571), False, 'import xadmin\n'), ((572, 624), 'xadmin.site.register', 'xadmin.site.register', (['HotSearchWords', 'HotSearchAdmin'], {}), '(HotSearchWords, HotSearchAdmin)\n', (592, 624), False, '... |
from django.contrib.auth.models import User
from django.test import Client, TestCase
from mixer.backend.django import mixer
from .models import *
class ViewsTest(TestCase):
def setUp(self):
self.client = Client()
self.doctor = mixer.blend(Doctor)
User.objects.create_user(
use... | [
"django.contrib.auth.models.User.objects.create_superuser",
"mixer.backend.django.mixer.blend",
"django.contrib.auth.models.User.objects.create_user",
"django.test.Client"
] | [((220, 228), 'django.test.Client', 'Client', ([], {}), '()\n', (226, 228), False, 'from django.test import Client, TestCase\n'), ((251, 270), 'mixer.backend.django.mixer.blend', 'mixer.blend', (['Doctor'], {}), '(Doctor)\n', (262, 270), False, 'from mixer.backend.django import mixer\n'), ((279, 385), 'django.contrib.a... |
# -*- coding: utf-8 -*-
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
from serial_data import SerialData
import logging
import pika
import argparse
import time
import json
LOG_FORMAT = ('%(levelname) -10s %(asctime)s %(name) -30s %(funcName) '
'-35s %(lineno) -5d: %(message)s')
LOGGER = logging.g... | [
"logging.getLogger",
"logging.basicConfig",
"logging.debug",
"argparse.ArgumentParser",
"pika.URLParameters",
"time.sleep",
"serial_data.SerialData",
"AWSIoTPythonSDK.MQTTLib.AWSIoTMQTTClient",
"logging.info"
] | [((311, 338), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (328, 338), False, 'import logging\n'), ((6559, 6584), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (6582, 6584), False, 'import argparse\n'), ((8206, 8238), 'logging.basicConfig', 'logging.basicConfig... |
#!/usr/bin/env python
import argparse
import constants as const
import os
import sys
import utils
def main():
"""Main function for compare.py. Receives arguments and starts
compare()."""
help_description = """Compare segmentation results between a fully
convolutional network and the gold standard for... | [
"sys.exit",
"argparse.ArgumentParser",
"os.path.join",
"utils.prediction_folder",
"utils.measure_roc_and_auc",
"utils.measure_all_coefficients",
"utils.read_data",
"utils.check_path",
"utils.check_tiramisu_layers"
] | [((824, 892), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': 'help_description', 'add_help': '(True)'}), '(description=help_description, add_help=True)\n', (847, 892), False, 'import argparse\n'), ((2574, 2617), 'utils.check_tiramisu_layers', 'utils.check_tiramisu_layers', (['tiramisu_model'... |
import json
with open('3-31-daily.json', 'r') as myfile:
data = myfile.read()
obj = json.loads(data)
obj_list = list(obj[0].items())
new_china = {}
new_canada = {}
new_australia = {}
for i in range (0,len(obj_list)):
new_china[obj_list[i][0]] = 0
new_canada[obj_list[i][0]] = 0
new_australia[obj_list... | [
"json.loads",
"json.dumps"
] | [((89, 105), 'json.loads', 'json.loads', (['data'], {}), '(data)\n', (99, 105), False, 'import json\n'), ((1627, 1642), 'json.dumps', 'json.dumps', (['obj'], {}), '(obj)\n', (1637, 1642), False, 'import json\n')] |
"""Bloch contiuous rotation experiment"""
import importlib as imp
import os,numpy as np
from subprocess import Popen
from typing import TYPE_CHECKING, Dict, Iterable, Optional, Sequence, Union
from utils import displayStandards as dsp #;imp.reload(dsp)
from EDutils import display as EDdisp #;imp.reload(EDdisp)
... | [
"os.path.exists",
"tifffile.imread",
"subprocess.Popen",
"os.path.join",
"EDutils.viewers.Base_Viewer"
] | [((883, 914), 'os.path.join', 'os.path.join', (['self.path', '"""tiff"""'], {}), "(self.path, 'tiff')\n", (895, 914), False, 'import os, numpy as np\n'), ((1919, 1957), 'EDutils.viewers.Base_Viewer', 'vw.Base_Viewer', (['self.figpath'], {}), '(self.figpath, **kwargs)\n', (1933, 1957), True, 'from EDutils import viewers... |
# Author of Aqsa: <NAME>
from aqsa_apps.wallet_tag_etc import models as wte_m
from aqsa_apps import sql_custom as sql
from . import models as m
from django.contrib.auth.mixins import LoginRequiredMixin
from aqsa_apps import mixins as mix
from django.utils.translation import ugettext as _
from django.views.generic.edit ... | [
"django.utils.translation.ugettext",
"aqsa_apps.sql_custom.sql",
"aqsa_apps.wallet_tag_etc.models.Category.objects.filter"
] | [((2858, 2878), 'aqsa_apps.sql_custom.sql', 'sql.sql', ([], {'query': 'query'}), '(query=query)\n', (2865, 2878), True, 'from aqsa_apps import sql_custom as sql\n'), ((4038, 4058), 'aqsa_apps.sql_custom.sql', 'sql.sql', ([], {'query': 'query'}), '(query=query)\n', (4045, 4058), True, 'from aqsa_apps import sql_custom a... |
# -*- coding: utf-8 -*-
import math
import random
from io import BytesIO
from PIL import Image, ImageDraw, ImageFont
def generate_example(level):
answer, s, draw_data = gen(level)
image = Image.new('RGBA', (700, 540))
frame = Image.open('assets/frame.png')
image.paste(frame)
draw = ImageDraw.D... | [
"PIL.Image.open",
"random.choice",
"math.gcd",
"PIL.Image.new",
"io.BytesIO",
"PIL.ImageFont.truetype",
"PIL.ImageDraw.Draw",
"random.randint"
] | [((200, 229), 'PIL.Image.new', 'Image.new', (['"""RGBA"""', '(700, 540)'], {}), "('RGBA', (700, 540))\n", (209, 229), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((243, 273), 'PIL.Image.open', 'Image.open', (['"""assets/frame.png"""'], {}), "('assets/frame.png')\n", (253, 273), False, 'from PIL import Imag... |
import pandas as pd
import numpy as np
def preprocess_data(df):
df = df.drop(columns = ['FEINumberRecall','RecallingFirmName','RecallEventID','RecallEventClassification','RefusalFEINumber',
'RefusedDate','AnalysisDone','OutbreakLevel','Id','ImportingCountry'])
a = df[df['OriginCountry'].isin(['-'])]['Orig... | [
"numpy.where",
"pandas.factorize",
"pandas.read_csv"
] | [((10855, 10903), 'pandas.read_csv', 'pd.read_csv', (['"""data/raw_data/seafood_imports.csv"""'], {}), "('data/raw_data/seafood_imports.csv')\n", (10866, 10903), True, 'import pandas as pd\n'), ((10075, 10102), 'numpy.where', 'np.where', (['(corr_matrix > 0.8)'], {}), '(corr_matrix > 0.8)\n', (10083, 10102), True, 'imp... |
from aioresponses import CallbackResult
def callback_201(*args, **kwargs):
return CallbackResult(status=201)
def callback_401(*args, **kwargs):
return CallbackResult(status=401)
| [
"aioresponses.CallbackResult"
] | [((88, 114), 'aioresponses.CallbackResult', 'CallbackResult', ([], {'status': '(201)'}), '(status=201)\n', (102, 114), False, 'from aioresponses import CallbackResult\n'), ((163, 189), 'aioresponses.CallbackResult', 'CallbackResult', ([], {'status': '(401)'}), '(status=401)\n', (177, 189), False, 'from aioresponses imp... |
# encoding:utf-8
from app import app, rabbitmq, db
from app.common.models import RoleName
from app.problem.models import Problem
from app.submission.models import Submission
from app.judgement.models import JudgementTask
from app.auth.main import auth
from utils import get_uuid, logger
import os
import re
from flask im... | [
"app.db.session.commit",
"app.auth.main.auth",
"os.path.exists",
"app.problem.models.Problem.query.filter_by",
"re.findall",
"app.submission.models.Submission",
"utils.get_uuid",
"app.app.route",
"app.db.session.add",
"os.mkdir",
"app.judgement.models.JudgementTask",
"flask_expects_json.expect... | [((628, 665), 'app.app.route', 'app.route', (['"""/judge"""'], {'methods': "['POST']"}), "('/judge', methods=['POST'])\n", (637, 665), False, 'from app import app, rabbitmq, db\n'), ((667, 691), 'app.auth.main.auth', 'auth', ([], {'role': 'RoleName.USER'}), '(role=RoleName.USER)\n', (671, 691), False, 'from app.auth.ma... |
from .config import _which_ffprobe
from .utils import _check_file_exists, _real_type
import os
import re
import subprocess
import ntpath
import configparser
def _ffprobe(file_path, pformat='ini', pstdout=subprocess.PIPE, psubprocess='call'):
if psubprocess == 'call':
return subprocess.call([_which_... | [
"re.split",
"ntpath.basename",
"configparser.ConfigParser"
] | [((863, 890), 'configparser.ConfigParser', 'configparser.ConfigParser', ([], {}), '()\n', (888, 890), False, 'import configparser\n'), ((3026, 3063), 'ntpath.basename', 'ntpath.basename', (['self.input_file[:-3]'], {}), '(self.input_file[:-3])\n', (3041, 3063), False, 'import ntpath\n'), ((4017, 4064), 're.split', 're.... |
import os
import sys
import base64
import json
import rsa
import urllib3
from urllib.parse import urlencode
from datetime import datetime, timedelta, timezone
private_key_path = './private.pem' # Change to private key path
profile_id = '' # Change to profile ID
account_id = '' ... | [
"os.path.exists",
"json.loads",
"os.getenv",
"base64.b64encode",
"datetime.timedelta",
"datetime.datetime.now",
"urllib3.PoolManager",
"sys.exit",
"urllib.parse.urlencode",
"rsa.PrivateKey.load_pkcs1"
] | [((790, 812), 'os.getenv', 'os.getenv', (['"""API_TOKEN"""'], {}), "('API_TOKEN')\n", (799, 812), False, 'import os\n'), ((846, 867), 'urllib3.PoolManager', 'urllib3.PoolManager', ([], {}), '()\n', (865, 867), False, 'import urllib3\n'), ((400, 422), 'os.getenv', 'os.getenv', (['"""API_TOKEN"""'], {}), "('API_TOKEN')\n... |
from collections import OrderedDict
from decimal import Decimal
import re
import sys
import os
from . import exception
from .__about__ import (
__author__, __copyright__, __email__, __license__, __summary__, __title__,
__uri__, __version__
)
import xml.etree.ElementTree as ET
import json
PY2 = sys.version_in... | [
"os.path.exists",
"json.loads",
"re.compile",
"xml.etree.ElementTree.iterparse",
"io.StringIO",
"urllib.request.urlopen",
"decimal.Decimal"
] | [((1311, 1365), 're.compile', 're.compile', (["b'\\\\<p\\\\>(?P<msg>\\\\<strong\\\\s.*?)\\\\</p\\\\>'"], {}), "(b'\\\\<p\\\\>(?P<msg>\\\\<strong\\\\s.*?)\\\\</p\\\\>')\n", (1321, 1365), False, 'import re\n'), ((1393, 1416), 're.compile', 're.compile', (["b'<[^>]*?>'"], {}), "(b'<[^>]*?>')\n", (1403, 1416), False, 'impo... |
# 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 logging
from fairseq.data.audio.frm_text_to_speech_dataset import FrmTextToSpeechDatasetCreator
from fairseq.tasks import regi... | [
"logging.basicConfig",
"fairseq.tasks.register_task",
"logging.getLogger",
"fairseq.tasks.text_to_speech.TextToSpeechTask.add_args",
"fairseq.data.audio.frm_text_to_speech_dataset.FrmTextToSpeechDatasetCreator.from_tsv"
] | [((394, 535), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s | %(levelname)s | %(name)s | %(message)s"""', 'datefmt': '"""%Y-%m-%d %H:%M:%S"""', 'level': 'logging.INFO'}), "(format=\n '%(asctime)s | %(levelname)s | %(name)s | %(message)s', datefmt=\n '%Y-%m-%d %H:%M:%S', level=loggi... |
# -*- coding: utf-8 -*-
#
# Author: <NAME>, Finland 2019
#
# This file is part of Kunquat.
#
# CC0 1.0 Universal, http://creativecommons.org/publicdomain/zero/1.0/
#
# To the extent possible under law, Kunquat Affirmers have waived all
# copyright and related or neighboring rights to Kunquat.
#
from collections impor... | [
"os.path.exists",
"collections.deque",
"os.path.splitdrive",
"os.scandir",
"sys.platform.startswith",
"os.path.split",
"os.path.normpath",
"os.getcwd",
"time.time"
] | [((5068, 5087), 'os.path.split', 'os.path.split', (['path'], {}), '(path)\n', (5081, 5087), False, 'import os\n'), ((677, 704), 'os.path.normpath', 'os.path.normpath', (['start_dir'], {}), '(start_dir)\n', (693, 704), False, 'import os\n'), ((2769, 2802), 'os.path.exists', 'os.path.exists', (['self._current_dir'], {}),... |
from celery import shared_task
from django.core.mail import send_mail
from django_celery_email import settings
from time import sleep
@shared_task
def sleepy(duration):
sleep(duration)
return None
@shared_task
def send_email_task():
sleep(2)
send_mail(
'Celery Task Worked!',
'이것은 자동 ... | [
"django.core.mail.send_mail",
"time.sleep"
] | [((176, 191), 'time.sleep', 'sleep', (['duration'], {}), '(duration)\n', (181, 191), False, 'from time import sleep\n'), ((249, 257), 'time.sleep', 'sleep', (['(2)'], {}), '(2)\n', (254, 257), False, 'from time import sleep\n'), ((262, 350), 'django.core.mail.send_mail', 'send_mail', (['"""Celery Task Worked!"""', '"""... |
#!/usr/bin/env python
import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
dependencies = ['dataclasses-json>=0.5.2',
'tabulate>=0.8.7']
setuptools.setup(
name="gistcafe",
version="0.0.3",
author="ServiceStack, Inc.",
author_email="<... | [
"setuptools.find_packages"
] | [((642, 668), 'setuptools.find_packages', 'setuptools.find_packages', ([], {}), '()\n', (666, 668), False, 'import setuptools\n')] |
#!/usr/bin/env python
import os
import sys
import django
from django.test.runner import DiscoverRunner
os.environ['DJANGO_SETTINGS_MODULE'] = 'licensing.test_settings'
django.setup()
test_runner = DiscoverRunner(verbosity=1)
failures = test_runner.run_tests(['tests'])
if failures:
sys.exit(failures)
| [
"django.test.runner.DiscoverRunner",
"django.setup",
"sys.exit"
] | [((172, 186), 'django.setup', 'django.setup', ([], {}), '()\n', (184, 186), False, 'import django\n'), ((201, 228), 'django.test.runner.DiscoverRunner', 'DiscoverRunner', ([], {'verbosity': '(1)'}), '(verbosity=1)\n', (215, 228), False, 'from django.test.runner import DiscoverRunner\n'), ((291, 309), 'sys.exit', 'sys.e... |
# Solution of;
# Project Euler Problem 70: Totient permutation
# https://projecteuler.net/problem=70
#
# Euler's Totient function, φ(n) [sometimes called the phi function], is used
# to determine the number of positive numbers less than or equal to n which
# are relatively prime to n. For example, as 1, 2, 4, 5, 7, ... | [
"timed.caller"
] | [((859, 893), 'timed.caller', 'timed.caller', (['dummy', 'n', 'i', 'prob_id'], {}), '(dummy, n, i, prob_id)\n', (871, 893), False, 'import timed\n')] |
import factory
from django_google_optimize.models import (
ExperimentCookie,
ExperimentVariant,
GoogleExperiment,
)
# pylint: disable=too-few-public-methods
class GoogleExperimentFactory(factory.django.DjangoModelFactory):
class Meta:
model = GoogleExperiment
experiment_id = factory.Fake... | [
"factory.Faker",
"factory.SubFactory"
] | [((308, 329), 'factory.Faker', 'factory.Faker', (['"""sha1"""'], {}), "('sha1')\n", (321, 329), False, 'import factory\n'), ((353, 374), 'factory.Faker', 'factory.Faker', (['"""city"""'], {}), "('city')\n", (366, 374), False, 'import factory\n'), ((566, 587), 'factory.Faker', 'factory.Faker', (['"""city"""'], {}), "('c... |
import re
from urllib.parse import urlparse
from django.conf import settings
from django.urls import reverse
ENTITY_NAMES = [
'Thing', 'Datastream', 'MultiDatastream', 'Sensor', 'Observation', 'ObservedProperty', 'FeatureOfInterest',
'HistoricalLocation', 'Location'
]
ENTITY_NAMES_PLURAL_TO_SINGULAR_MAP = {
... | [
"re.match",
"urllib.parse.urlparse",
"django.urls.reverse"
] | [((1869, 1882), 'urllib.parse.urlparse', 'urlparse', (['url'], {}), '(url)\n', (1877, 1882), False, 'from urllib.parse import urlparse\n'), ((2960, 3026), 'django.urls.reverse', 'reverse', (['"""gatekeeper:index"""'], {'kwargs': "{'path': settings.STA_VERSION}"}), "('gatekeeper:index', kwargs={'path': settings.STA_VERS... |
import pandas as pd
import numpy
import matplotlib
import sklearn_crfsuite
from sklearn import preprocessing
from sklearn.preprocessing import LabelEncoder
from sklearn_crfsuite import metrics
from sklearn.model_selection import train_test_split
from sklearn.metrics import make_scorer
from sklearn.cross_validation i... | [
"sklearn.grid_search.RandomizedSearchCV",
"numpy.unique",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"sklearn_crfsuite.CRF",
"glob.glob"
] | [((972, 1039), 'glob.glob', 'glob', (['"""/Users/karanjani/Desktop/csvWithVecs/TrainCSV_Updated/*.csv"""'], {}), "('/Users/karanjani/Desktop/csvWithVecs/TrainCSV_Updated/*.csv')\n", (976, 1039), False, 'from glob import glob\n'), ((1750, 1809), 'sklearn.model_selection.train_test_split', 'train_test_split', (['featureM... |
"""Command to set a user to have all admin permissions"""
from django.core.management.base import BaseCommand, CommandError
from accounts.models import User
class Command(BaseCommand):
"""Command to turn a user into a superuser with all permissions"""
help = "Give a user with a specified email address all ad... | [
"accounts.models.User.objects.get"
] | [((929, 999), 'accounts.models.User.objects.get', 'User.objects.get', ([], {'email__iexact': 'email', 'organization_id': 'organization_id'}), '(email__iexact=email, organization_id=organization_id)\n', (945, 999), False, 'from accounts.models import User\n')] |
#!/usr/bin/env python3
"""
Equivalent kubectl commands are much less readable:
k get ds -n kube-system kube-flannel-ds -oyaml
k get ds -n kube-system kube-flannel-ds -o=custom-columns=IFACE:.spec.template.spec.containers[0].args
# Not sure of the next one:
kubectl patch ds -n kube-system kube-flannel-ds -p '{"spec":{"... | [
"yaml.load_all",
"yaml.dump_all"
] | [((877, 929), 'yaml.dump_all', 'yaml.dump_all', (['eph_yaml', 'f'], {'default_flow_style': '(False)'}), '(eph_yaml, f, default_flow_style=False)\n', (890, 929), False, 'import yaml\n'), ((513, 553), 'yaml.load_all', 'yaml.load_all', (['f'], {'Loader': 'yaml.FullLoader'}), '(f, Loader=yaml.FullLoader)\n', (526, 553), Fa... |
import pygame
class Peashooter(pygame.sprite.Sprite):
def __init__(self):
super(Peashooter,self).__init__()
self.image = pygame.image.load('material/images/Peashooter_00.png').convert_alpha()
self.images = [pygame.image.load('material/images/Peashooter_{:02d}.png'.format(i)).convert_alpha()... | [
"pygame.image.load"
] | [((142, 196), 'pygame.image.load', 'pygame.image.load', (['"""material/images/Peashooter_00.png"""'], {}), "('material/images/Peashooter_00.png')\n", (159, 196), False, 'import pygame\n')] |
import unittest
import json
from stampman.helpers import mail_, config_
class EmailTest(unittest.TestCase):
"""Tests for the Email helper class"""
def setUp(self):
self._valid_sender = ("Test", "<EMAIL>")
self._invalid_sender = ("Test", "this_is_not_a_valid_e_mail_address")
self._val... | [
"json.dumps",
"stampman.helpers.config_.ServiceConfig",
"stampman.helpers.mail_.Email",
"stampman.helpers.config_.get_domain_pools",
"stampman.helpers.config_.load_json_file"
] | [((2784, 3017), 'stampman.helpers.mail_.Email', 'mail_.Email', ([], {'sender': 'self._valid_sender', 'recipients': 'self._valid_e_mail_list', 'subject': 'self._valid_string', 'content': 'self._valid_string', 'cc': 'self._valid_e_mail_list', 'bcc': 'self._valid_e_mail_list', 'reply_to': 'self._valid_sender[1]'}), '(send... |
import os
import glob
import numpy as np
import tabulate
def pprint_dict(x):
"""
:param x: a dict
:return: a string of pretty representation of the dict
"""
def helper(d):
ret = {}
for k, v in d.items():
if isinstance(v, dict):
ret[k] = helper(v)
... | [
"tabulate.tabulate",
"parse.parse",
"torch.load",
"os.path.join",
"os.path.isfile",
"numpy.stack",
"os.path.dirname",
"torch.save",
"numpy.dtype"
] | [((1171, 1220), 'tabulate.tabulate', 'tabulate.tabulate', (['data', 'headers'], {'tablefmt': '"""psql"""'}), "(data, headers, tablefmt='psql')\n", (1188, 1220), False, 'import tabulate\n'), ((1295, 1340), 'os.path.join', 'os.path.join', (['dir', "('%s.%d' % (filename, step))"], {}), "(dir, '%s.%d' % (filename, step))\n... |
# Imports
import os
# Package imports
from nose.tools import assert_true, assert_equal, assert_in
# Project imports
from amos3.data import build_image_database, build_camera_database
def test_build_camera_database():
"""
Test build_camera_database.
:return:
"""
camera_list = build_camera_databas... | [
"amos3.data.build_image_database",
"os.path.exists",
"amos3.data.build_camera_database",
"nose.tools.assert_in"
] | [((300, 337), 'amos3.data.build_camera_database', 'build_camera_database', ([], {'num_cameras': '(10)'}), '(num_cameras=10)\n', (321, 337), False, 'from amos3.data import build_image_database, build_camera_database\n'), ((468, 499), 'nose.tools.assert_in', 'assert_in', (['"""id"""', 'camera_list[0]'], {}), "('id', came... |
import os
import tempfile
from decimal import Decimal
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from PIL import Image
from rest_framework import status
from rest_framework.response import Response
from rest_framework.test import APIClient
from core... | [
"core.models.Recipe.objects.create",
"os.path.exists",
"django.contrib.auth.get_user_model",
"recipe.serializers.RecipeSerializer",
"core.models.Tag.objects.create",
"PIL.Image.new",
"core.models.Recipe.objects.all",
"rest_framework.test.APIClient",
"tempfile.NamedTemporaryFile",
"core.models.Reci... | [((463, 492), 'django.urls.reverse', 'reverse', (['"""recipe:recipe-list"""'], {}), "('recipe:recipe-list')\n", (470, 492), False, 'from django.urls import reverse\n'), ((585, 640), 'django.urls.reverse', 'reverse', (['"""recipe:recipe-upload-image"""'], {'args': '[recipe_id]'}), "('recipe:recipe-upload-image', args=[r... |
import asyncio
import logging
import re
import socket
import warnings
from asyncio import AbstractEventLoop
from ipaddress import ip_address, IPv4Network
from abc import ABCMeta
from abc import abstractmethod
from typing import Callable
from typing import List
from typing import Optional
from typing import Tuple
M... | [
"logging.getLogger",
"socket.gethostbyname",
"re.compile",
"asyncio.open_connection",
"asyncio.wait_for",
"warnings.warn",
"asyncio.get_event_loop",
"ipaddress.ip_address",
"asyncio.Future"
] | [((1876, 1982), 're.compile', 're.compile', (['"""\\\\("(.*?)" "(.*?)" "(.*?)" "(.*?)" "(.*?)" "(.*?)" (\\\\d+) "(.*?)" (\\\\d+) (\\\\d+)\\\\)"""'], {}), '(\n \'\\\\("(.*?)" "(.*?)" "(.*?)" "(.*?)" "(.*?)" "(.*?)" (\\\\d+) "(.*?)" (\\\\d+) (\\\\d+)\\\\)\'\n )\n', (1886, 1982), False, 'import re\n'), ((1992, 2008)... |
import json
import pytest
from clld.db.models.common import Parameter, Language
from clld.web.adapters import geojson
from clld.web.datatables.base import DataTable
geojson.pacific_centered()
def test_GeoJson(mocker):
adapter = geojson.GeoJson(None)
assert len(list(adapter.feature_iterator(None, None))) ==... | [
"pytest.approx",
"clld.web.adapters.geojson.GeoJsonLanguages",
"clld.db.models.common.Language.first",
"clld.db.models.common.Parameter.get",
"clld.web.adapters.geojson.GeoJson",
"clld.web.adapters.geojson.GeoJsonParameterFlatProperties",
"clld.web.adapters.geojson.get_feature",
"clld.db.models.common... | [((168, 194), 'clld.web.adapters.geojson.pacific_centered', 'geojson.pacific_centered', ([], {}), '()\n', (192, 194), False, 'from clld.web.adapters import geojson\n'), ((237, 258), 'clld.web.adapters.geojson.GeoJson', 'geojson.GeoJson', (['None'], {}), '(None)\n', (252, 258), False, 'from clld.web.adapters import geoj... |
import os
import json
from numbers import Number
from collections import Iterable, Mapping
from operator import itemgetter
from .config import set_class_path, JavaSettingsConstructorParams
set_class_path()
from jnius import autoclass, MetaJavaClass
# Java DataTypes
jMap = autoclass('java.util.HashMap')
jArrayList = ... | [
"operator.itemgetter",
"jnius.autoclass",
"json.loads"
] | [((276, 306), 'jnius.autoclass', 'autoclass', (['"""java.util.HashMap"""'], {}), "('java.util.HashMap')\n", (285, 306), False, 'from jnius import autoclass, MetaJavaClass\n'), ((320, 352), 'jnius.autoclass', 'autoclass', (['"""java.util.ArrayList"""'], {}), "('java.util.ArrayList')\n", (329, 352), False, 'from jnius im... |
from django.shortcuts import render
from django.http import HttpResponse
from .models import FireCart
# Create your views here.
def my_carts(req):
#拿数据
data = FireCart.objects.filter(speed__lte=500).order_by("speed")
#准备返回数据
result ={
"title":"火cart",
"carts":data
}
return render... | [
"django.shortcuts.render"
] | [((314, 348), 'django.shortcuts.render', 'render', (['req', '"""trains.html"""', 'result'], {}), "(req, 'trains.html', result)\n", (320, 348), False, 'from django.shortcuts import render\n'), ((834, 876), 'django.shortcuts.render', 'render', (['req', '"""trains.html"""', "{'carts': res}"], {}), "(req, 'trains.html', {'... |
from django.urls import path
from django.conf.urls import url
from project_first_app.views import *
urlpatterns = [
path(r'getowners/<int:ow_id>',detail,name='detail'),
path(r'allowners',show_owners,name='showowners'),
path(r'allcars', Show_cars.as_view(template_name="cars_list.html")),
path(r'... | [
"django.urls.path"
] | [((126, 178), 'django.urls.path', 'path', (['"""getowners/<int:ow_id>"""', 'detail'], {'name': '"""detail"""'}), "('getowners/<int:ow_id>', detail, name='detail')\n", (130, 178), False, 'from django.urls import path\n'), ((184, 233), 'django.urls.path', 'path', (['"""allowners"""', 'show_owners'], {'name': '"""showowne... |
# -*- coding: utf-8 -*-
"""OpenBabel toolkit for DeCAF"""
from decaf import PHARS, Pharmacophore
import pybel
import openbabel as ob
import numpy as np
from collections import deque
import math
PATTERNS = {phar: pybel.Smarts(smarts) for (phar, smarts) in PHARS.items()}
def __count_bonds(a1, a2, exclude):
"""Co... | [
"pybel.Smarts",
"collections.deque",
"math.ceil",
"decaf.PHARS.items",
"numpy.zeros",
"openbabel.OBAtomAtomIter",
"decaf.Pharmacophore",
"openbabel.OBMol"
] | [((215, 235), 'pybel.Smarts', 'pybel.Smarts', (['smarts'], {}), '(smarts)\n', (227, 235), False, 'import pybel\n'), ((726, 742), 'collections.deque', 'deque', (['[(a1, 0)]'], {}), '([(a1, 0)])\n', (731, 742), False, 'from collections import deque\n'), ((2082, 2102), 'numpy.zeros', 'np.zeros', (['(idx, idx)'], {}), '((i... |
import datetime
import pytz
import tempfile
import uuid
from django.contrib.auth.models import User
from django.test import TestCase
from django.utils import timezone
from dateutil import tz
from dateutil.parser import parse
from mock import patch
from stardate.models import Blog, Post
from stardate.parsers import F... | [
"datetime.datetime",
"mock.patch",
"stardate.parsers.FileParser",
"dateutil.tz.gettz",
"datetime.date",
"stardate.models.Blog.objects.all",
"django.contrib.auth.models.User.objects.create",
"django.contrib.auth.models.User.objects.all",
"stardate.models.Blog.objects.create",
"tempfile.mkstemp"
] | [((6479, 6511), 'mock.patch', 'patch', (['"""stardate.parsers.logger"""'], {}), "('stardate.parsers.logger')\n", (6484, 6511), False, 'from mock import patch\n'), ((447, 459), 'stardate.parsers.FileParser', 'FileParser', ([], {}), '()\n', (457, 459), False, 'from stardate.parsers import FileParser\n'), ((823, 862), 'dj... |
import time
import redis
import os
if __name__ == '__main__':
redis_host = os.environ['REDIS_HOST']
redis_port = int(os.environ['REDIS_PORT'])
redis_channel = os.environ['REDIS_CHANNEL']
pubsub = redis.Redis(host=redis_host, port=redis_port, db=0).pubsub()
pubsub.subscribe([redis_channel])
fo... | [
"redis.Redis"
] | [((215, 266), 'redis.Redis', 'redis.Redis', ([], {'host': 'redis_host', 'port': 'redis_port', 'db': '(0)'}), '(host=redis_host, port=redis_port, db=0)\n', (226, 266), False, 'import redis\n')] |
import pymel.core as pm
from mymaya.tools import select
def copy(sel, delete_original=True):
"""
Copies shape node of first item to others in list
@param sel: list of objects, first item must have shape node to copy
@type sel: list
@param delete_original: delete original shape node object, default... | [
"pymel.core.duplicate",
"mymaya.tools.select.shape_node",
"pymel.core.ls",
"pymel.core.delete",
"pymel.core.parent"
] | [((1064, 1078), 'pymel.core.ls', 'pm.ls', ([], {'sl': '(True)'}), '(sl=True)\n', (1069, 1078), True, 'import pymel.core as pm\n'), ((514, 539), 'mymaya.tools.select.shape_node', 'select.shape_node', (['object'], {}), '(object)\n', (531, 539), False, 'from mymaya.tools import select\n'), ((989, 1006), 'pymel.core.delete... |
"""One shared terminal per URL endpoint
Plus a /new URL which will create a new terminal and redirect to it.
"""
from __future__ import print_function, absolute_import
import logging
import os.path
import sys
import tornado.web
# This demo requires tornado_xstatic and XStatic-term.js
import tornado_xstatic
from term... | [
"terminado.NamedTermManager",
"common_demo_stuff.run_and_show_browser",
"tornado_xstatic.url_maker"
] | [((1105, 1180), 'terminado.NamedTermManager', 'NamedTermManager', ([], {'shell_command': "['tmux', '-L', 'socket']", 'max_terminals': '(100)'}), "(shell_command=['tmux', '-L', 'socket'], max_terminals=100)\n", (1121, 1180), False, 'from terminado import TermSocket, NamedTermManager\n'), ((1893, 1963), 'common_demo_stuf... |
import shutil
import openpyxl
import num2t4ru
from num2t4ru import num2text, decimal2text
from decimal import *
from openpyxl.styles.borders import Border, Side
thin_border = Border(left=Side(style='thin'),
right=Side(style='thin'),
top=Side(style='thin'),
... | [
"openpyxl.load_workbook",
"openpyxl.styles.borders.Side",
"shutil.copy"
] | [((695, 732), 'openpyxl.load_workbook', 'openpyxl.load_workbook', (['src_file_name'], {}), '(src_file_name)\n', (717, 732), False, 'import openpyxl\n'), ((195, 213), 'openpyxl.styles.borders.Side', 'Side', ([], {'style': '"""thin"""'}), "(style='thin')\n", (199, 213), False, 'from openpyxl.styles.borders import Border,... |
import json
import os
import sys
import argparse
import codecs
import re
from pathlib import Path
parser = argparse.ArgumentParser()
parser.add_argument('-b', dest='base', type=str)
parser.add_argument('-s', dest='source', type=str)
parser.add_argument('-d', dest='destination', type=str)
parser.add_argument('--debug',... | [
"argparse.ArgumentParser",
"pathlib.Path",
"os.path.split",
"re.findall",
"codecs.open",
"re.search"
] | [((108, 133), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (131, 133), False, 'import argparse\n'), ((590, 625), 'codecs.open', 'codecs.open', (['file'], {'encoding': '"""utf-8"""'}), "(file, encoding='utf-8')\n", (601, 625), False, 'import codecs\n'), ((1506, 1529), 'os.path.split', 'os.path... |
import tensorflow as tf
from tensorstream.common import roll
from tensorstream.streamable import Streamable
class Lag(Streamable):
def __init__(self, period):
super().__init__()
self.period = period
def step(self, value, buffer_state=None):
if buffer_state is None:
shape = self.concat([self.per... | [
"tensorflow.shape",
"tensorflow.zeros",
"tensorstream.common.roll"
] | [((450, 475), 'tensorstream.common.roll', 'roll', (['value', 'buffer_state'], {}), '(value, buffer_state)\n', (454, 475), False, 'from tensorstream.common import roll\n'), ((364, 392), 'tensorflow.zeros', 'tf.zeros', (['shape', 'value.dtype'], {}), '(shape, value.dtype)\n', (372, 392), True, 'import tensorflow as tf\n'... |
import timeit
from random import randint
#在-10到10之间生成10个元素
data = [randint(-10,10) for _ in range(10)]
def is_max(n):
return n >=0
print(data)
#py2跟py3不一样 py3返回是一个迭代器 加上list将迭代器转换成列表
res = list(filter(lambda x:x >=0,data))
print(res)
#列表解析
data1 = [randint(-20,20) for _ in range(10)]
res1 = [x for x in data... | [
"random.randint"
] | [((68, 84), 'random.randint', 'randint', (['(-10)', '(10)'], {}), '(-10, 10)\n', (75, 84), False, 'from random import randint\n'), ((260, 276), 'random.randint', 'randint', (['(-20)', '(20)'], {}), '(-20, 20)\n', (267, 276), False, 'from random import randint\n')] |
#!/usr/bin/env python3
################################################################################
# parse arguments first
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--min_2d_power', type=int, default=3)
parser.add_argument('--max_2d_power', type=int, default=15)
parser.add_argument... | [
"common.get_marcher_plot_name",
"sys.path.insert",
"numpy.sqrt",
"common3d.get_marcher_plot_name",
"argparse.ArgumentParser",
"numpy.arange",
"pyolim.FacCenter3d",
"numpy.where",
"matplotlib.pyplot.style.use",
"numpy.linspace",
"common.get_marcher_name",
"pyolim.FacCenter",
"common3d.get_mar... | [((156, 181), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (179, 181), False, 'import argparse\n'), ((623, 674), 'sys.path.insert', 'sys.path.insert', (['(0)', "('../build/%s' % args.build_type)"], {}), "(0, '../build/%s' % args.build_type)\n", (638, 674), False, 'import sys\n'), ((675, 707),... |
import os
import sys
import re
import argparse
def gen_repeate_macro(out,format,count,start=1):
for num in range(start, count):
out.write(format.format(no=num,dec=num-1,inc=num+1))
out.write('\n')
def KAGUYA_PP_REPEAT(out,count):
out.write('#define KAGUYA_PP_REPEAT0(MACRO)\n')
gen_repeate... | [
"argparse.ArgumentParser"
] | [((2721, 2746), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (2744, 2746), False, 'import argparse\n')] |
"""Author: <NAME>
Email: <EMAIL>
network.py is a basic implementation of a one layer linear neural network, to
examine an implementation of backpropagation. It is based on the basic model
of the Perceptron. Information on that can be found at:
https://en.wikipedia.org/wiki/Perceptron
The intent of this specific ... | [
"sklearn.utils.resample",
"sklearn.datasets.load_digits"
] | [((9803, 9825), 'sklearn.datasets.load_digits', 'datasets.load_digits', ([], {}), '()\n', (9823, 9825), False, 'from sklearn import datasets, utils\n'), ((9839, 9887), 'sklearn.utils.resample', 'utils.resample', (['temp_digits.data'], {'random_state': '(0)'}), '(temp_digits.data, random_state=0)\n', (9853, 9887), False... |
import os
from discord.ext import commands
PREFIX = '\\'
TOKEN = os.environ['BOT_TOKEN']
bot = commands.Bot(command_prefix=PREFIX, help_command=None)
def main():
bot.load_extension('core')
bot.load_extension('cogs')
bot.run(TOKEN)
| [
"discord.ext.commands.Bot"
] | [((98, 152), 'discord.ext.commands.Bot', 'commands.Bot', ([], {'command_prefix': 'PREFIX', 'help_command': 'None'}), '(command_prefix=PREFIX, help_command=None)\n', (110, 152), False, 'from discord.ext import commands\n')] |
# Copyright 2020 <NAME>, <NAME>, <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | [
"numpy.mean",
"numpy.abs",
"numpy.sqrt",
"numpy.zeros",
"numpy.random.RandomState",
"random.SystemRandom",
"numpy.round"
] | [((1946, 1981), 'numpy.zeros', 'np.zeros', (['(2 ** N)'], {'dtype': 'np.complex_'}), '(2 ** N, dtype=np.complex_)\n', (1954, 1981), True, 'import numpy as np\n'), ((2634, 2658), 'numpy.random.RandomState', 'np.random.RandomState', (['a'], {}), '(a)\n', (2655, 2658), True, 'import numpy as np\n'), ((2834, 2876), 'numpy.... |
from rest_framework import serializers
from . import models
class HashtagSerializer(serializers.ModelSerializer):
class Meta:
model = models.Hashtag
fields = '__all__'
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = models.User
fields = '__all__'
cla... | [
"rest_framework.serializers.DateTimeField"
] | [((393, 444), 'rest_framework.serializers.DateTimeField', 'serializers.DateTimeField', ([], {'format': '"""%d/%m/%Y %H:%M"""'}), "(format='%d/%m/%Y %H:%M')\n", (418, 444), False, 'from rest_framework import serializers\n')] |
"""Machine Learning 2 Section 10 @ GWU
Quiz 4 - Solution for Q4
Author: Xiaochi (George) Li"""
import torch
import numpy as np
from torch.autograd import Variable
import matplotlib.pyplot as plt
torch.manual_seed(42)
size = 100
p = np.linspace(-3, 3, size)
t = np.exp(-np.abs(p)) * np.sin(np.pi * p)
p = Variable(tor... | [
"torch.manual_seed",
"torch.nn.ReLU",
"numpy.abs",
"matplotlib.pyplot.plot",
"torch.from_numpy",
"torch.nn.MSELoss",
"numpy.linspace",
"matplotlib.pyplot.scatter",
"torch.nn.Linear",
"numpy.sin",
"matplotlib.pyplot.title",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.show"
] | [((198, 219), 'torch.manual_seed', 'torch.manual_seed', (['(42)'], {}), '(42)\n', (215, 219), False, 'import torch\n'), ((235, 259), 'numpy.linspace', 'np.linspace', (['(-3)', '(3)', 'size'], {}), '(-3, 3, size)\n', (246, 259), True, 'import numpy as np\n'), ((691, 709), 'torch.nn.MSELoss', 'torch.nn.MSELoss', ([], {})... |
import os
def drawLines(array_of_lines):
num_lines = len(array_of_lines)
if (num_lines > 10):
raise Exception("too many lines")
f = open("f.txt", "wt")
for i in range(len(array_of_lines[0])):
line = []
for j in range(num_lines):
line.append(str(array_of_lines[j][i... | [
"os.remove"
] | [((557, 575), 'os.remove', 'os.remove', (['"""f.txt"""'], {}), "('f.txt')\n", (566, 575), False, 'import os\n')] |
import json
import os
import numpy as np
from app import app
from app import r
from app.models import Student, Grade, Course
from bson import json_util
from flask import render_template, request, jsonify, Response, send_from_directory
from flask.json import JSONEncoder
from mongoengine.base import BaseDocument
from mo... | [
"flask.render_template",
"app.models.Student.objects.get",
"app.r.get",
"app.models.Course.objects",
"app.r.expire",
"app.models.Course.objects.get",
"flask.jsonify",
"flask_httpauth.HTTPBasicAuth",
"flask.send_from_directory",
"json.dumps",
"flask.request.form.get",
"app.app.route",
"json.l... | [((413, 428), 'flask_httpauth.HTTPBasicAuth', 'HTTPBasicAuth', ([], {}), '()\n', (426, 428), False, 'from flask_httpauth import HTTPBasicAuth\n'), ((872, 893), 'app.app.route', 'app.route', (['"""/manager"""'], {}), "('/manager')\n", (881, 893), False, 'from app import app\n'), ((970, 1016), 'app.app.route', 'app.route... |
import os
import sys
import requests
import wget
from tqdm import tqdm
if len(sys.argv) != 2:
print('You must enter the model name as a parameter, e.g.: download_model.py 117M')
sys.exit(1)
if sys.argv[1] == '117M':
model = sys.argv[1]
subdir = os.path.join('models', model)
if not os.... | [
"os.path.exists",
"wget.download",
"os.makedirs",
"os.path.join",
"os.chdir",
"sys.exit"
] | [((195, 206), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (203, 206), False, 'import sys\n'), ((275, 304), 'os.path.join', 'os.path.join', (['"""models"""', 'model'], {}), "('models', model)\n", (287, 304), False, 'import os\n'), ((317, 339), 'os.path.exists', 'os.path.exists', (['subdir'], {}), '(subdir)\n', (331,... |
import traceback
from logging import getLogger
from time import time
from django.conf import settings
from django.core.mail import mail_admins
from django.http import HttpResponseServerError
Logger = getLogger("airone")
class LoggingRequestMiddleware:
def __init__(self, get_response):
self.get_response ... | [
"logging.getLogger",
"traceback.format_exc",
"django.http.HttpResponseServerError",
"time.time",
"django.core.mail.mail_admins"
] | [((202, 221), 'logging.getLogger', 'getLogger', (['"""airone"""'], {}), "('airone')\n", (211, 221), False, 'from logging import getLogger\n'), ((390, 396), 'time.time', 'time', ([], {}), '()\n', (394, 396), False, 'from time import time\n'), ((1054, 1076), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n... |
# Copyright (c) 2011, <NAME> and <NAME>.
# Licensed under the Academic Free License 3.0.
import utility
def GetResult(fw, data):
arg1 = data[0]
(i, sz, ans) = (0, len(arg1), "")
while i<sz:
ct = 0
for j in range(fw-1, -1, -1):
if arg1[i+j]=="1":
break
ct += 1
ans += utility.GetBinaryRepresentat... | [
"utility.GetBinaryRepresentation"
] | [((292, 331), 'utility.GetBinaryRepresentation', 'utility.GetBinaryRepresentation', (['fw', 'ct'], {}), '(fw, ct)\n', (323, 331), False, 'import utility\n')] |
import csv
import os
import re
import sys
from urllib.parse import urlparse
import dates
import requests
from bs4 import BeautifulSoup
def crawl(url, file_name):
page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser')
magazine = soup.find("div", {"class": "responsive-magazyn"})
ti... | [
"os.path.exists",
"urllib.parse.urlparse",
"csv.writer",
"requests.get",
"bs4.BeautifulSoup",
"dates.to_datetime"
] | [((176, 193), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (188, 193), False, 'import requests\n'), ((205, 247), 'bs4.BeautifulSoup', 'BeautifulSoup', (['page.content', '"""html.parser"""'], {}), "(page.content, 'html.parser')\n", (218, 247), False, 'from bs4 import BeautifulSoup\n'), ((716, 756), 'dates.t... |
from setuptools import setup
setup(name='wiggum',
version='0.2',
description='utilities to detect simpson\'s paradox',
url='http://github.com/brownsarahm/DetectSimpsonParadox',
author='<NAME>, <NAME>, <NAME>',
author_email='<EMAIL>',
license='MIT',
packages=['wiggum', 'wiggum_... | [
"setuptools.setup"
] | [((30, 546), 'setuptools.setup', 'setup', ([], {'name': '"""wiggum"""', 'version': '"""0.2"""', 'description': '"""utilities to detect simpson\'s paradox"""', 'url': '"""http://github.com/brownsarahm/DetectSimpsonParadox"""', 'author': '"""<NAME>, <NAME>, <NAME>"""', 'author_email': '"""<EMAIL>"""', 'license': '"""MIT"... |
# standart modules
import os
# blender modules
import bpy
import bpy_extras
# addon modules
from . import imp
from . import exp
from .. import icons
from .. import log
from .. import contexts
from .. import version_utils
from .. import ie_props
from .. import utils
def menu_func_import(self, context):
icon = ic... | [
"bpy.utils.unregister_class",
"os.path.exists",
"bpy.props.StringProperty",
"bpy.props.CollectionProperty",
"os.path.join",
"bpy.utils.register_class"
] | [((1166, 1227), 'bpy.props.StringProperty', 'bpy.props.StringProperty', ([], {'default': '"""*.ogf"""', 'options': "{'HIDDEN'}"}), "(default='*.ogf', options={'HIDDEN'})\n", (1190, 1227), False, 'import bpy\n'), ((1260, 1327), 'bpy.props.StringProperty', 'bpy.props.StringProperty', ([], {'subtype': '"""DIR_PATH"""', 'o... |
from operator import itemgetter
from re import sub
from html.parser import HTMLParser
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import linear_kernel
class MLStripper(HTMLParser):
'''
From http://stackoverflow.com/questions/11061058/using-htmlparser-in-python-3... | [
"operator.itemgetter",
"sklearn.feature_extraction.text.TfidfVectorizer",
"sklearn.metrics.pairwise.linear_kernel"
] | [((2208, 2233), 'operator.itemgetter', 'itemgetter', (['*most_similar'], {}), '(*most_similar)\n', (2218, 2233), False, 'from operator import itemgetter\n'), ((1531, 1548), 'sklearn.feature_extraction.text.TfidfVectorizer', 'TfidfVectorizer', ([], {}), '()\n', (1546, 1548), False, 'from sklearn.feature_extraction.text ... |
# Generated by Django 3.0.5 on 2020-04-28 02:56
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('vi_lomas_changes', '0010_auto_20200428_0252'),
]
operations = [
migrations.RenameField(
model_name='raster',
old_name='area_... | [
"django.db.migrations.RenameField"
] | [((236, 330), 'django.db.migrations.RenameField', 'migrations.RenameField', ([], {'model_name': '"""raster"""', 'old_name': '"""area_geom"""', 'new_name': '"""extent_geom"""'}), "(model_name='raster', old_name='area_geom', new_name=\n 'extent_geom')\n", (258, 330), False, 'from django.db import migrations\n')] |
# model class structure adapted from <NAME>
# https://danijar.com/structuring-your-tensorflow-models/
# https://gist.github.com/danijar/8663d3bbfd586bffecf6a0094cd116f2
from math import ceil
import functools
from collections import namedtuple
import tensorflow as tf
def doublewrap(function):
"""
A decorator ... | [
"tensorflow.unstack",
"tensorflow.reduce_mean",
"tensorflow.cast",
"tensorflow.Graph",
"tensorflow.random_normal",
"tensorflow.placeholder",
"functools.wraps",
"tensorflow.layers.conv2d",
"tensorflow.matmul",
"tensorflow.train.AdamOptimizer",
"tensorflow.summary.scalar",
"tensorflow.summary.me... | [((472, 497), 'functools.wraps', 'functools.wraps', (['function'], {}), '(function)\n', (487, 497), False, 'import functools\n'), ((1401, 1426), 'functools.wraps', 'functools.wraps', (['function'], {}), '(function)\n', (1416, 1426), False, 'import functools\n'), ((4618, 4628), 'tensorflow.Graph', 'tf.Graph', ([], {}), ... |
import hashlib
from pyclient import client as pyclient
import pytest
from aioresponses import aioresponses
SERVER_URL = 'example.com:8080'
URL_MAP = pyclient.Client.SERVER_URLMAP
LIST_DATA_URL = f'http://{SERVER_URL}/{URL_MAP["list_data"]}'
CHECK_DATA_URL = f'http://{SERVER_URL}/{URL_MAP["check_data"]}'
SUBMIT_DATA... | [
"hashlib.sha256",
"pyclient.client.Client",
"pytest.mark.parametrize",
"pytest.raises",
"aioresponses.aioresponses"
] | [((703, 768), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""payload,expected"""', 'list_data_parameters'], {}), "('payload,expected', list_data_parameters)\n", (726, 768), False, 'import pytest\n'), ((2196, 2363), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""status,exc,exc_msg"""', "[(404, ... |
import sys
import copy
data = list(map(list, sys.stdin.read().strip().split('\n')))
content = """L.LL.LL.LL
LLLLLLL.LL
L.L.L..L..
LLLL.LL.LL
L.LL.LL.LL
L.LLLLL.LL
..L.L.....
LLLLLLLLLL
L.LLLLLL.L
L.LLLLL.LL"""
#data = list(map(list, content.strip().split('\n')))
rows = [[0] * (len(data[0]) + 2)]
rows += [[0] + x + [0]... | [
"sys.stdin.read",
"copy.deepcopy"
] | [((383, 402), 'copy.deepcopy', 'copy.deepcopy', (['rows'], {}), '(rows)\n', (396, 402), False, 'import copy\n'), ((1259, 1282), 'copy.deepcopy', 'copy.deepcopy', (['nextdata'], {}), '(nextdata)\n', (1272, 1282), False, 'import copy\n'), ((45, 61), 'sys.stdin.read', 'sys.stdin.read', ([], {}), '()\n', (59, 61), False, '... |
import FWCore.ParameterSet.Config as cms
ecalSCDynamicDPhiParametersESProducer = cms.ESProducer("EcalSCDynamicDPhiParametersESProducer",
# Parameters from the analysis by <NAME> [https://indico.cern.ch/event/949294/contributions/3988389/attachments/2091573/3514649/2020_08_26_Clustering.pdf]
# dynamic dPhi para... | [
"FWCore.ParameterSet.Config.double"
] | [((455, 470), 'FWCore.ParameterSet.Config.double', 'cms.double', (['(0.0)'], {}), '(0.0)\n', (465, 470), True, 'import FWCore.ParameterSet.Config as cms\n'), ((492, 507), 'FWCore.ParameterSet.Config.double', 'cms.double', (['(2.0)'], {}), '(2.0)\n', (502, 507), True, 'import FWCore.ParameterSet.Config as cms\n'), ((530... |
# ======================================================================
# Disk Defragmenter
# Advent of Code 2017 Day 14 -- <NAME> -- https://adventofcode.com
#
# Computer simulation by Dr. <NAME> III
# ======================================================================
# ========================================... | [
"knots.Knots"
] | [((2853, 2888), 'knots.Knots', 'knots.Knots', ([], {'length': '(256)', 'part2': '(True)'}), '(length=256, part2=True)\n', (2864, 2888), False, 'import knots\n')] |
from collections import Counter
from copy import deepcopy
from core.games.Game import Game, GAMES_INFO
class ConnectFour(Game):
title = GAMES_INFO[1]["title"]
rows = 6
cols = 7
need_players = 2
current_turn = 0
cell_empty_value = "*"
cell_values = ("X", "O")
render_values_map = {cell_... | [
"collections.Counter",
"copy.deepcopy"
] | [((594, 615), 'collections.Counter', 'Counter', (['linear_board'], {}), '(linear_board)\n', (601, 615), False, 'from collections import Counter\n'), ((3749, 3770), 'collections.Counter', 'Counter', (['linear_board'], {}), '(linear_board)\n', (3756, 3770), False, 'from collections import Counter\n'), ((3948, 3963), 'cop... |
#!/usr/bin/python3
import re
def catch_input():
password = input(f'\n\033[1;31m *Enter Your Password for Validation:\033[0m ')
return password
def password_validator_rules(input_rule, given_password):
rules = re.compile(input_rule)
pattern = re.search(rules, given_password)
return True if patt... | [
"re.search",
"re.compile"
] | [((226, 248), 're.compile', 're.compile', (['input_rule'], {}), '(input_rule)\n', (236, 248), False, 'import re\n'), ((263, 295), 're.search', 're.search', (['rules', 'given_password'], {}), '(rules, given_password)\n', (272, 295), False, 'import re\n')] |
# Copyright (C) 2019-2021, TomTom (http://tomtom.com).
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | [
"asciidoxy.generator.navigation.DocumentTreeNode",
"pathlib.Path",
"pytest.raises",
"asciidoxy.generator.context.StackFrame",
"asciidoxy.generator.context.stacktrace"
] | [((2634, 2646), 'pathlib.Path', 'Path', (['"""path"""'], {}), "('path')\n", (2638, 2646), False, 'from pathlib import Path\n'), ((2869, 2888), 'pathlib.Path', 'Path', (['"""file_1.adoc"""'], {}), "('file_1.adoc')\n", (2873, 2888), False, 'from pathlib import Path\n'), ((3077, 3096), 'pathlib.Path', 'Path', (['"""file_2... |
"""Test module `analyze`."""
import pandas as pd
from psa_prizes.analyze import _str_comp_ann_g
def test_str_comp_ann_g() -> None:
"""Test a pd.DataFrame with 100% CAGR, missing and multiple entries per year."""
data = {
"date": ["10/06/2010", "10/06/2011", "10/06/2011", "10/06/2013", "10/06/2015"],
... | [
"pandas.DataFrame",
"pandas.DatetimeIndex",
"psa_prizes.analyze._str_comp_ann_g"
] | [((379, 424), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {'columns': "['date', 'prize']"}), "(data, columns=['date', 'prize'])\n", (391, 424), True, 'import pandas as pd\n'), ((442, 470), 'pandas.DatetimeIndex', 'pd.DatetimeIndex', (["df['date']"], {}), "(df['date'])\n", (458, 470), True, 'import pandas as pd\n'), ... |
# RESPUESTA 6
import plotly.plotly as py
import plotly.graph_objs as go
import plotly.tools as tls
import matplotlib.pyplot as plt
from funciones import experimento_geometrica
# hago los experimentos
datos_equilibrada = experimento_geometrica(0.5)
data = [go.Histogram(x=datos_equilibrada )]
py.plot(data, filename='hi... | [
"plotly.graph_objs.Histogram",
"funciones.experimento_geometrica",
"plotly.plotly.plot"
] | [((222, 249), 'funciones.experimento_geometrica', 'experimento_geometrica', (['(0.5)'], {}), '(0.5)\n', (244, 249), False, 'from funciones import experimento_geometrica\n'), ((294, 349), 'plotly.plotly.plot', 'py.plot', (['data'], {'filename': '"""histograma-moneda-equilibrada"""'}), "(data, filename='histograma-moneda... |
import pygame
from src.utils import constants as const
class DrawBoard(object):
def __init__(self, state, screen, color):
self.state = state
self.screen = screen
self.color = color
self.colors = [
const.COLORS[self.color][0],
const.COLORS[self.color][1]
... | [
"pygame.Rect",
"pygame.Surface"
] | [((7280, 7326), 'pygame.Surface', 'pygame.Surface', (['(const.SQ_SIZE, const.SQ_SIZE)'], {}), '((const.SQ_SIZE, const.SQ_SIZE))\n', (7294, 7326), False, 'import pygame\n'), ((6232, 6278), 'pygame.Surface', 'pygame.Surface', (['(const.SQ_SIZE, const.SQ_SIZE)'], {}), '((const.SQ_SIZE, const.SQ_SIZE))\n', (6246, 6278), Fa... |
'''This is the Channel module
It can simulate a river channel basing on the inputs it is provided.
It consists of a centerline, an inner channel, and arbitrary number of
outer banks.
All functions apply to it should be continuous.
The offsets from banks to centerline are in sn coordinate system, and
transform into xy... | [
"math.floor",
"matplotlib.pyplot.ylabel",
"math.log",
"numpy.array",
"numpy.arange",
"numpy.cross",
"numpy.where",
"matplotlib.pyplot.xlabel",
"numpy.linspace",
"numpy.argmin",
"numpy.meshgrid",
"numpy.maximum",
"numpy.round",
"numpy.random.normal",
"random.sample",
"numpy.amax",
"nu... | [((2131, 2151), 'numpy.array', 'np.array', (['x_v_valley'], {}), '(x_v_valley)\n', (2139, 2151), True, 'import numpy as np\n'), ((2236, 2255), 'numpy.amax', 'np.amax', (['x_v_valley'], {}), '(x_v_valley)\n', (2243, 2255), True, 'import numpy as np\n'), ((2697, 2712), 'numpy.array', 'np.array', (['out_x'], {}), '(out_x)... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def import_data(file_name, time_column_index=None, mode='csv', header=True, room_name=None, tz=0):
"""
Load raw data from the disk.
:type file_name: str
:param file_name: the name of the raw data file
:type time_column_index: int
:param time_col... | [
"dateutil.parser.parse",
"numpy.asarray",
"csv.reader"
] | [((1227, 1260), 'csv.reader', 'reader', (['input_file'], {'delimiter': '""","""'}), "(input_file, delimiter=',')\n", (1233, 1260), False, 'from csv import reader\n'), ((1984, 2010), 'numpy.asarray', 'asarray', (['data'], {'dtype': 'float'}), '(data, dtype=float)\n', (1991, 2010), False, 'from numpy import nan, asarray\... |
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from bs4 import BeautifulSoup
import re
s = input("input: ")
def cleanhtml(raw_html):
cleanr = re.compile('<.*?>|&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-f]{1,6});')
cleantext = re.sub(cleanr, '', raw_html)
return cleantext
if ... | [
"selenium.webdriver.chrome.options.Options",
"re.compile",
"selenium.webdriver.Chrome",
"bs4.BeautifulSoup",
"re.sub"
] | [((187, 248), 're.compile', 're.compile', (['"""<.*?>|&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-f]{1,6});"""'], {}), "('<.*?>|&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-f]{1,6});')\n", (197, 248), False, 'import re\n'), ((265, 293), 're.sub', 're.sub', (['cleanr', '""""""', 'raw_html'], {}), "(cleanr, '', raw_html)\n", (271, 293), False, '... |
# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
# See https://llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
# Also available under a BSD-style license. See LICENSE.
# A pretrained model to classify the input sentence.
# https://h... | [
"torch.jit.trace_module",
"torch.manual_seed",
"transformers.AutoModelForSequenceClassification.from_pretrained",
"transformers.AutoTokenizer.from_pretrained",
"torch_mlir_e2e_test.torchscript.annotations.export",
"torch_mlir_e2e_test.torchscript.annotations.annotate_args"
] | [((678, 698), 'torch.manual_seed', 'torch.manual_seed', (['(0)'], {}), '(0)\n', (695, 698), False, 'import torch\n'), ((775, 814), 'transformers.AutoTokenizer.from_pretrained', 'AutoTokenizer.from_pretrained', (['hf_model'], {}), '(hf_model)\n', (804, 814), False, 'from transformers import AutoTokenizer, AutoModelForSe... |
import unittest, penmon as pm
class Test(unittest.TestCase):
def test_daylight_hours(self):
station = pm.Station(41.42, 109)
day = station.day_entry(135)
day.temp_min = 19.5
day.temp_max = 28
self.assertEqual(day.daylight_hours(), 14.3, "daylighth_hours")
if _... | [
"unittest.main",
"penmon.Station"
] | [((348, 363), 'unittest.main', 'unittest.main', ([], {}), '()\n', (361, 363), False, 'import unittest, penmon as pm\n'), ((121, 143), 'penmon.Station', 'pm.Station', (['(41.42)', '(109)'], {}), '(41.42, 109)\n', (131, 143), True, 'import unittest, penmon as pm\n')] |
#!/usr/bin/env python3
""" Cronjob to copy Novogene fastq data from GIS to NSCC
"""
# standard library imports
import logging
import sys
import os
import argparse
import subprocess
import glob
#--- third party imports
#
import pymongo
import yaml
import requests
# project specific imports
#
# add lib dir for this pip... | [
"logging.getLogger",
"logging.StreamHandler",
"sys.path.insert",
"sys.exit",
"os.path.exists",
"argparse.ArgumentParser",
"pipelines.is_devel_version",
"subprocess.check_output",
"pipelines.is_production_user",
"mongodb.mongodb_conn",
"requests.get",
"readunits.readunits_for_sampledir",
"pip... | [((1063, 1090), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1080, 1090), False, 'import logging\n'), ((1101, 1124), 'logging.StreamHandler', 'logging.StreamHandler', ([], {}), '()\n', (1122, 1124), False, 'import logging\n'), ((490, 518), 'sys.path.insert', 'sys.path.insert', (['(0)',... |
import numpy as np
N = 17 #607 #17
matrix = []
for i in range(N):
matrix.append([0]*N)
matrix = np.matrix(matrix)
findn = 211 #368078 #211
find = [0,0]
fn = 1
x = N//2
y = N//2
expo = 1
while(fn < N*N):
per = expo**2 - (expo-2)**2
if per == 0:
matrix[x,y] = 1
if findn == fn : find = [x,y]
else: ... | [
"numpy.matrix"
] | [((100, 117), 'numpy.matrix', 'np.matrix', (['matrix'], {}), '(matrix)\n', (109, 117), True, 'import numpy as np\n')] |
import sys
import csv
import os
COURSE_TABLE='.courses.csv'
COURSE_SCHEMA =['name','instructed_by','dificulty']
courses = []
def _initialize_courses_from_storage():
with open(COURSE_TABLE, mode='r') as f:
reader= csv.DictReader(f,fieldnames=COURSE_SCHEMA)
for row in reader:
courses.append(row)
def _save_c... | [
"csv.DictWriter",
"os.rename",
"csv.DictReader",
"os.remove"
] | [((218, 261), 'csv.DictReader', 'csv.DictReader', (['f'], {'fieldnames': 'COURSE_SCHEMA'}), '(f, fieldnames=COURSE_SCHEMA)\n', (232, 261), False, 'import csv\n'), ((465, 508), 'csv.DictWriter', 'csv.DictWriter', (['f'], {'fieldnames': 'COURSE_SCHEMA'}), '(f, fieldnames=COURSE_SCHEMA)\n', (479, 508), False, 'import csv\... |
from transformers.tokenization_bert import BertTokenizer
from transformersx.data import *
from transformersx.data.data_models import FeaturesSerializer
import torch
import time
def create_test_examples(type, count):
return [TaskInputExample(guid=str(i), text_a=type + '_text_a_' + str(i), text_b=type + '_text_b_'... | [
"transformersx.data.data_models.FeaturesSerializer",
"time.time",
"torch.save",
"transformers.tokenization_bert.BertTokenizer.from_pretrained"
] | [((415, 468), 'transformers.tokenization_bert.BertTokenizer.from_pretrained', 'BertTokenizer.from_pretrained', (['"""../dataset/vocab.txt"""'], {}), "('../dataset/vocab.txt')\n", (444, 468), False, 'from transformers.tokenization_bert import BertTokenizer\n'), ((2117, 2128), 'time.time', 'time.time', ([], {}), '()\n', ... |