code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from datetime import datetime
from dateutil.parser import parse
import json
import logging
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect, HttpResponse, HttpResponseBadRequest
from django.utils.decora... | [
"logging.getLogger",
"dateutil.parser.parse",
"requests.post",
"django.http.HttpResponseBadRequest",
"django.http.HttpResponse",
"json.dumps",
"django.utils.decorators.method_decorator",
"requests.get",
"datetime.datetime.now"
] | [((480, 507), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (497, 507), False, 'import logging\n'), ((3759, 3791), 'django.utils.decorators.method_decorator', 'method_decorator', (['login_required'], {}), '(login_required)\n', (3775, 3791), False, 'from django.utils.decorators import met... |
# Copyright 2021 The Distla Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | [
"distla_core.analysis.pmaps.frobdiff",
"distla_core.analysis.pmaps.frobnorm",
"numpy.linalg.qr",
"numpy.arccos",
"distla_core.analysis.pmaps.eye",
"functools.reduce",
"distla_core.utils.pops.undistribute",
"distla_core.analysis.pmaps.matmul",
"functools.partial",
"distla_core.analysis.pmaps.transp... | [((1793, 1827), 'distla_core.analysis.pmaps.frobdiff', 'pmaps.frobdiff', (['matrix_a', 'matrix_b'], {}), '(matrix_a, matrix_b)\n', (1807, 1827), False, 'from distla_core.analysis import pmaps\n'), ((3329, 3380), 'distla_core.analysis.pmaps.eye', 'pmaps.eye', (['should_be_eye.shape', 'should_be_eye.dtype'], {}), '(shoul... |
'''This module contains classes used by pool core to interact with the rest of the pool.
Default implementation do almost nothing, you probably want to override these classes
and customize references to interface instances in your launcher.
(see launcher_demo.tac for an example).
'''
import time
from twisted.... | [
"DBInterface.DBInterface",
"time.time"
] | [((526, 551), 'DBInterface.DBInterface', 'DBInterface.DBInterface', ([], {}), '()\n', (549, 551), False, 'import DBInterface\n'), ((6780, 6791), 'time.time', 'time.time', ([], {}), '()\n', (6789, 6791), False, 'import time\n')] |
from enum import Enum
from deprecation import deprecated
@deprecated(details="""Enum-value statuses are deprecated since SLIMS 6.4.
Unless your SLIMS system still uses them (see Lab Settings),
you should use the Status table and cntn_fk_status for status queries.""")
class Status(Enum):
"... | [
"deprecation.deprecated"
] | [((61, 304), 'deprecation.deprecated', 'deprecated', ([], {'details': '"""Enum-value statuses are deprecated since SLIMS 6.4.\n Unless your SLIMS system still uses them (see Lab Settings),\n you should use the Status table and cntn_fk_status for status queries."""'}), '(details=\n """Enum-value... |
#!/usr/bin/python3
# Get Album lyrics from Bandcamp website and save them
"""Usage:
bandcamp-lyrics.py <url> [--output=<folder>]
bandcamp-lyrics.py (-h | --help)
bandcamp-lyrics.py (--version)
Options:
-h --help Show this screen.
-v --version Show version.
-o --output=<folder>... | [
"os.path.exists",
"os.makedirs",
"bs4.BeautifulSoup",
"os.chdir",
"docopt.docopt"
] | [((1582, 1628), 'docopt.docopt', 'docopt', (['__doc__'], {'version': '"""bandcamp-lyrics 2.3"""'}), "(__doc__, version='bandcamp-lyrics 2.3')\n", (1588, 1628), False, 'from docopt import docopt\n'), ((990, 1013), 'bs4.BeautifulSoup', 'BeautifulSoup', (['response'], {}), '(response)\n', (1003, 1013), False, 'from bs4 im... |
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
import utils.augmentations as aug
class DataTransform():
def __init__(self, input_size=300, rgb_means=(104, 117, 123)):
self.transform = {
'train': aug.Compose([
aug.ConvertFromInts(),
aug.ToAbsoluteCoords(),
... | [
"utils.augmentations.RandomMirror",
"utils.augmentations.Expand",
"utils.augmentations.Resize",
"utils.augmentations.ToAbsoluteCoords",
"utils.augmentations.ToPercentCoords",
"utils.augmentations.RandomSampleCrop",
"utils.augmentations.SubtractMeans",
"utils.augmentations.PhotometricDistort",
"utils... | [((255, 276), 'utils.augmentations.ConvertFromInts', 'aug.ConvertFromInts', ([], {}), '()\n', (274, 276), True, 'import utils.augmentations as aug\n'), ((294, 316), 'utils.augmentations.ToAbsoluteCoords', 'aug.ToAbsoluteCoords', ([], {}), '()\n', (314, 316), True, 'import utils.augmentations as aug\n'), ((334, 358), 'u... |
# March 31st 2021
# This file, data.py, is responsible for loading data for the
# EnCounter
import os
import sys
import json
global ROOT_DIR
global filepath
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
filepath = f"{ROOT_DIR}/data/encounters.json"
# Loading Data
def load_data():
globa... | [
"os.path.abspath",
"json.load",
"json.dump"
] | [((200, 225), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (215, 225), False, 'import os\n'), ((389, 408), 'json.load', 'json.load', (['datafile'], {}), '(datafile)\n', (398, 408), False, 'import json\n'), ((777, 813), 'json.dump', 'json.dump', (['jsawn', 'datafile'], {'indent': '(4)'}), '(... |
from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileAllowed
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired, ValidationError
class QuoteForm(FlaskForm):
author_guess = StringField('Your Guess:', validators=[DataRequired()])
submit = SubmitField('Gu... | [
"wtforms.validators.DataRequired",
"wtforms.SubmitField"
] | [((305, 325), 'wtforms.SubmitField', 'SubmitField', (['"""Guess"""'], {}), "('Guess')\n", (316, 325), False, 'from wtforms import StringField, SubmitField\n'), ((275, 289), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (287, 289), False, 'from wtforms.validators import DataRequired, ValidationErr... |
'''OpenGL extension SGIX.depth_texture
Overview (from the spec)
This extension defines a new depth texture format. An important
application of depth texture images is shadow casting, but separating
this from the shadow extension allows for the potential use of depth
textures in other applications such as image-... | [
"OpenGL.extensions.hasGLExtension",
"OpenGL.constant.Constant"
] | [((984, 1037), 'OpenGL.constant.Constant', 'constant.Constant', (['"""GL_DEPTH_COMPONENT16_SGIX"""', '(33189)'], {}), "('GL_DEPTH_COMPONENT16_SGIX', 33189)\n", (1001, 1037), False, 'from OpenGL import platform, constants, constant, arrays\n'), ((1069, 1122), 'OpenGL.constant.Constant', 'constant.Constant', (['"""GL_DEP... |
# Copyright (c) 2014, <NAME> (<EMAIL>)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# - Redistributions of source code must retain the above copyright notice,
# this list of conditions and ... | [
"numpy.zeros",
"csv.writer",
"numpy.genfromtxt",
"numpy.hstack"
] | [((1882, 1903), 'numpy.zeros', 'np.zeros', (['(79975, 37)'], {}), '((79975, 37))\n', (1890, 1903), True, 'import numpy as np\n'), ((2149, 2260), 'numpy.genfromtxt', 'np.genfromtxt', (['"""./raw_data/kaggle_submission.csv"""'], {'dtype': 'np.int32', 'delimiter': '""","""', 'skip_header': '(1)', 'usecols': '(0)'}), "('./... |
# -*- coding: utf-8 -*-
import re
import os
from completor import Completor
from completor.compat import to_bytes
word_patten = re.compile('\w+$')
trigger = re.compile('(\.|->|#|::)\s*(\w*)$')
def sanitize(menu):
if not menu:
return menu
# type
menu = menu.replace(b'[#', b'').replace(b'#]', b'... | [
"completor.compat.to_bytes",
"os.popen",
"os.getenv",
"re.compile"
] | [((131, 150), 're.compile', 're.compile', (['"""\\\\w+$"""'], {}), "('\\\\w+$')\n", (141, 150), False, 'import re\n'), ((160, 198), 're.compile', 're.compile', (['"""(\\\\.|->|#|::)\\\\s*(\\\\w*)$"""'], {}), "('(\\\\.|->|#|::)\\\\s*(\\\\w*)$')\n", (170, 198), False, 'import re\n'), ((1903, 1919), 'completor.compat.to_b... |
# -*- coding: UTF-8 -*-
import numpy as np
'''
此部分用于存储公共资源
'''
'''
船舶状态记录
A record in SHIPSTATUS is like:
{'mmsi': mmsi, 'lon': lon, 'lat': lat, 'shipspeed': shipspeed, 'heading': heading, 'sog': sog}
'''
SHIPSTATUS = []
SHIPJSON = []
# river作为公共资源共享, 初始即创建河床,不再在sim_env中初始河床.
RIVER = np.zeros((10000, 1000))
'''
船舶... | [
"numpy.zeros"
] | [((289, 312), 'numpy.zeros', 'np.zeros', (['(10000, 1000)'], {}), '((10000, 1000))\n', (297, 312), True, 'import numpy as np\n')] |
import threading, time
import RPi.GPIO as GPIO
from .. import pins
from .. import utils
from .. import queue_common
from .. import event
COMMAND_QUIT = -1
RESULT_TOO_LOW = 1
RESULT_TOO_HIGH = 2
RESULT_JUST_RIGHT = 3
TARGET_RATIO = 3.2
TIMEOUT = 3 # seconds
RESULT_TIMEOUT = 2 # seconds
WIN_RESULT_TIMEOUT = 30 # ... | [
"threading.Thread.__init__",
"RPi.GPIO.add_event_detect",
"time.sleep",
"time.time",
"RPi.GPIO.remove_event_detect"
] | [((728, 816), 'RPi.GPIO.add_event_detect', 'GPIO.add_event_detect', (['pins.ENC0', 'GPIO.FALLING'], {'callback': 'self.on_enc0', 'bouncetime': '(30)'}), '(pins.ENC0, GPIO.FALLING, callback=self.on_enc0,\n bouncetime=30)\n', (749, 816), True, 'import RPi.GPIO as GPIO\n'), ((821, 909), 'RPi.GPIO.add_event_detect', 'GP... |
from django.contrib import admin
from .models import (
IstochnikiFinansirovaniya,
Napravleniya,
TubesRegistration,
Issledovaniya,
Result,
FrequencyOfUseResearches,
CustomResearchOrdering,
RMISOrgs,
RMISServiceInactive,
Diagnoses,
TypeJob,
EmployeeJob,
KeyValue,
P... | [
"django.contrib.admin.site.register",
"django.contrib.admin.register"
] | [((613, 659), 'django.contrib.admin.site.register', 'admin.site.register', (['IstochnikiFinansirovaniya'], {}), '(IstochnikiFinansirovaniya)\n', (632, 659), False, 'from django.contrib import admin\n'), ((663, 691), 'django.contrib.admin.register', 'admin.register', (['Napravleniya'], {}), '(Napravleniya)\n', (677, 691... |
from django.db.utils import IntegrityError
from django.test import Client, TestCase
try:
from recipe_features.models import Ingredient
except ImportError:
assert False, 'Ingredient model does not find!'
try:
from users.models import User
except ImportError:
assert False, 'User model does not find!'
... | [
"recipe_features.models.Ingredient.objects.create",
"users.models.User.objects.create",
"users.models.User.objects.all",
"django.test.Client"
] | [((420, 542), 'users.models.User.objects.create', 'User.objects.create', ([], {'first_name': '"""Dima"""', 'last_name': '"""Smirnov"""', 'username': '"""Dimon"""', 'email': '"""<EMAIL>"""', 'password': '"""<PASSWORD>"""'}), "(first_name='Dima', last_name='Smirnov', username=\n 'Dimon', email='<EMAIL>', password='<PA... |
# Generated by Django 3.1.3 on 2021-01-10 10:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('emp_evaluation_system', '0006_auto_20210108_0834'),
]
operations = [
migrations.AddField(
model_name='evaluationsystempage',
... | [
"django.db.models.TextField"
] | [((367, 519), 'django.db.models.TextField', 'models.TextField', ([], {'blank': '(True)', 'default': '""""""', 'help_text': '"""Provide a description for this page to help other admin users to understand its purpose."""'}), "(blank=True, default='', help_text=\n 'Provide a description for this page to help other admi... |
# coding=utf-8
# Copyright 2020 Google LLC
#
# 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 ... | [
"tf_agents.networks.expand_dims_layer.ExpandDims",
"tensorflow.fill",
"tensorflow.keras.layers.Lambda",
"tensorflow.reduce_sum",
"tensorflow.test.main",
"tensorflow.TensorSpec",
"tensorflow.constant",
"tensorflow.ones_like",
"tf_agents.trajectories.time_step.time_step_spec"
] | [((995, 1027), 'tf_agents.networks.expand_dims_layer.ExpandDims', 'expand_dims_layer.ExpandDims', (['(-1)'], {}), '(-1)\n', (1023, 1027), False, 'from tf_agents.networks import expand_dims_layer\n'), ((3951, 3965), 'tensorflow.test.main', 'tf.test.main', ([], {}), '()\n', (3963, 3965), True, 'import tensorflow as tf\n'... |
from django.urls import path,include,re_path
from . import views
from django.contrib.auth import views as auth_views
app_name = "users"
urlpatterns = [
path('api/profile',views.ProfileList.as_view()),
path('profile/',views.profile,name = 'profile'),
#path('user_profile/',views.user_profile,name = 'us... | [
"django.urls.path"
] | [((216, 263), 'django.urls.path', 'path', (['"""profile/"""', 'views.profile'], {'name': '"""profile"""'}), "('profile/', views.profile, name='profile')\n", (220, 263), False, 'from django.urls import path, include, re_path\n'), ((338, 400), 'django.urls.path', 'path', (['"""edit_profile/"""', 'views.edit_profile'], {'... |
from collections import namedtuple
# Creates a new tuple subclass called Person
Person = namedtuple('Person', ['age', 'gender', 'name'])
# Can use new subclass to create tuple-like objects
row1 = Person(age=22, gender='male', name='Gryff')
print(row1.age)
row2 = Person(age=22, gender='female', name='Phoebe')
print(r... | [
"collections.namedtuple"
] | [((90, 137), 'collections.namedtuple', 'namedtuple', (['"""Person"""', "['age', 'gender', 'name']"], {}), "('Person', ['age', 'gender', 'name'])\n", (100, 137), False, 'from collections import namedtuple\n')] |
# MultiAgent 2.0
# (c) 2017-2018, NiL, <EMAIL>
import sys, os, time
import doctest
sys.path.append("..")
from mas.multiagent import *
def test_driver_basic() :
'''
>>> test_driver_basic()
Initialization.
Driver: <<multiagent.Driver has_context=1 has_schedule=1>>
Request: None
Response: None
... | [
"doctest.testmod",
"sys.path.append"
] | [((86, 107), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (101, 107), False, 'import sys, os, time\n'), ((2612, 2629), 'doctest.testmod', 'doctest.testmod', ([], {}), '()\n', (2627, 2629), False, 'import doctest\n')] |
import numpy as np
import cv2
import cv
# this just handles actually showing the window
# and the dots where you've clicked
class SelectView:
def __init__(self, winname, imsize):
self.im = np.zeros((imsize, imsize, 3), dtype=np.uint8)
self.clicks = []
self.winname = winname
cv2.nam... | [
"cv.SetMouseCallback",
"cv2.getPerspectiveTransform",
"cv2.findHomography",
"cv2.destroyWindow",
"cv2.imshow",
"cv.WaitKey",
"cv2.warpPerspective",
"numpy.zeros",
"numpy.linalg.inv",
"cv2.imread",
"cv2.namedWindow"
] | [((1202, 1255), 'cv2.findHomography', 'cv2.findHomography', (['src_pts', 'dst_pts', 'cv2.RANSAC', '(5.0)'], {}), '(src_pts, dst_pts, cv2.RANSAC, 5.0)\n', (1220, 1255), False, 'import cv2\n'), ((1522, 1567), 'cv2.getPerspectiveTransform', 'cv2.getPerspectiveTransform', (['src_pts', 'dst_pts'], {}), '(src_pts, dst_pts)\n... |
##
# .driver.dbapi20 - DB-API 2.0 Implementation
##
"""
DB-API 2.0 conforming interface using postgresql.driver.
"""
threadsafety = 1
paramstyle = 'pyformat'
apilevel = '2.0'
from operator import itemgetter
from functools import partial
import datetime
import time
import re
from .. import clientparameters as pg_param... | [
"postgresql.exceptions.DriverError",
"re.compile",
"functools.partial",
"postgresql.exceptions.Error",
"time.localtime"
] | [((674, 713), 're.compile', 're.compile', (['"""(?:%%)+|%(s|[(][^)]*[)]s)"""'], {}), "('(?:%%)+|%(s|[(][^)]*[)]s)')\n", (684, 713), False, 'import re\n'), ((3915, 3980), 'postgresql.exceptions.Error', 'Error', (['"""cursor is closed"""'], {'source': '"""CLIENT"""', 'creator': 'self.database'}), "('cursor is closed', so... |
""" Analyzing simulations done with FitSim. """
from __future__ import print_function, division, absolute_import
import os
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from matplotlib.widgets import Slider
from wmpl.Config import config
from wmpl.Utils.... | [
"numpy.sqrt",
"wmpl.Utils.Pickling.loadPickle",
"numpy.array",
"matplotlib.gridspec.GridSpecFromSubplotSpec",
"matplotlib.widgets.Slider",
"matplotlib.colors.LogNorm",
"numpy.mean",
"numpy.where",
"wmpl.MetSim.FitSim.calcVelocity",
"numpy.max",
"matplotlib.gridspec.GridSpec",
"numpy.linspace",... | [((796, 826), 'wmpl.MetSim.MetSim.loadInputs', 'loadInputs', (['meteor_inputs_file'], {}), '(meteor_inputs_file)\n', (806, 826), False, 'from wmpl.MetSim.MetSim import loadInputs\n'), ((887, 929), 'wmpl.Utils.Pickling.loadPickle', 'loadPickle', (['dir_path_mir', 'traj_pickle_file'], {}), '(dir_path_mir, traj_pickle_fil... |
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
from matplotlib import cm
nnodes = 5;
nvars = 1024;
nsteps = 100;
path = './npy/'
dat = np.zeros([nnodes*nsteps,nvars]);
x = np.linspace(0,32*np.pi,nvars)
#plt.figure()
#dat = np.zeros([nvars])
#fn = path+'uexact.npy'
#dat = np.loa... | [
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.colorbar",
"matplotlib.pyplot.plot",
"numpy.zeros",
"numpy.linspace",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.title",
"numpy.load",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.show"... | [((175, 209), 'numpy.zeros', 'np.zeros', (['[nnodes * nsteps, nvars]'], {}), '([nnodes * nsteps, nvars])\n', (183, 209), True, 'import numpy as np\n'), ((213, 246), 'numpy.linspace', 'np.linspace', (['(0)', '(32 * np.pi)', 'nvars'], {}), '(0, 32 * np.pi, nvars)\n', (224, 246), True, 'import numpy as np\n'), ((344, 356)... |
from mnistdp import IdxFile
import os
from PIL import Image
def dump_image(idx_file_name, output_dir):
idx_file = IdxFile.from_file(idx_file_name)
_, idx_file_fullname = os.path.split(idx_file_name)
idx_file_basename, _ = os.path.splitext(idx_file_fullname)
output_dir = os.path.join(output_dir, f"{idx... | [
"mnistdp.IdxFile.from_file",
"PIL.Image.fromarray",
"os.makedirs",
"os.path.join",
"os.path.splitext",
"os.path.split"
] | [((120, 152), 'mnistdp.IdxFile.from_file', 'IdxFile.from_file', (['idx_file_name'], {}), '(idx_file_name)\n', (137, 152), False, 'from mnistdp import IdxFile\n'), ((180, 208), 'os.path.split', 'os.path.split', (['idx_file_name'], {}), '(idx_file_name)\n', (193, 208), False, 'import os\n'), ((236, 271), 'os.path.splitex... |
import asyncio
from asyncio import sleep
from spangle.api import Api
from spangle.handler_protocols import RequestHandlerProtocol
from ward import fixture, raises, test, using
@fixture
def api():
return Api()
@fixture
@using(api=api)
def timeout(api: Api):
@api.route("/timeout")
class Timeout:
... | [
"spangle.api.Api",
"ward.raises",
"ward.using",
"asyncio.sleep",
"ward.test"
] | [((228, 242), 'ward.using', 'using', ([], {'api': 'api'}), '(api=api)\n', (233, 242), False, 'from ward import fixture, raises, test, using\n'), ((429, 486), 'ward.test', 'test', (['"""Client cancells a request after specified seconds"""'], {}), "('Client cancells a request after specified seconds')\n", (433, 486), Fal... |
# -*- coding: utf-8 -*-
# Copyright 2009-2014 <NAME>
#
# 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 the rights
# to use, copy, modify, mer... | [
"unittest.main",
"tidylib.tidy_document",
"tidylib.PersistentTidy",
"tidylib.Tidy"
] | [((4003, 4018), 'unittest.main', 'unittest.main', ([], {}), '()\n', (4016, 4018), False, 'import unittest\n'), ((1586, 1602), 'tidylib.tidy_document', 'tidy_document', (['h'], {}), '(h)\n', (1599, 1602), False, 'from tidylib import Tidy, PersistentTidy, tidy_document\n'), ((1787, 1824), 'tidylib.tidy_document', 'tidy_d... |
# Copyright 2021 The Narrenschiff Authors
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in... | [
"os.path.join",
"yaml.load",
"tests.mocks.MockKeychain",
"unittest.skip",
"io.StringIO"
] | [((1349, 1401), 'unittest.skip', 'unittest.skip', (['"""See CHANGELOG for v2.0.0 and v2.0.1"""'], {}), "('See CHANGELOG for v2.0.0 and v2.0.1')\n", (1362, 1401), False, 'import unittest\n'), ((882, 917), 'os.path.join', 'os.path.join', (['self.path', '"""dev.yaml"""'], {}), "(self.path, 'dev.yaml')\n", (894, 917), Fals... |
import numpy as np
from numba import jit
from .utils import ConfidenceModel, print_verbose, GPModel
from sklearn.ensemble import BaggingRegressor
from sklearn.tree import ExtraTreeRegressor
from sklearn.linear_model import LinearRegression
@jit(nopython=True)
def get_random_candidate(number, dimensionality, non_zero):... | [
"numpy.nanargmax",
"numpy.random.choice",
"numpy.argmax",
"numpy.zeros",
"numba.jit",
"numpy.random.randint",
"numpy.random.uniform",
"sklearn.ensemble.BaggingRegressor",
"sklearn.linear_model.LinearRegression"
] | [((242, 260), 'numba.jit', 'jit', ([], {'nopython': '(True)'}), '(nopython=True)\n', (245, 260), False, 'from numba import jit\n'), ((604, 638), 'numpy.zeros', 'np.zeros', (['(number, dimensionality)'], {}), '((number, dimensionality))\n', (612, 638), True, 'import numpy as np\n'), ((700, 734), 'numpy.random.randint', ... |
"""
Generate METRICS-%Y-%m-%d.json for all the repositories tracked by repos-to-include.txt
and save them in their respective _data directory.
"""
import datetime
import json
import os
import requests
import graphql_queries
print("LOG: Assuming the current path to be the root of the metrics repository.")
PATH_TO_MET... | [
"requests.post",
"os.makedirs",
"json.dumps",
"os.path.join",
"datetime.datetime.now",
"json.dump"
] | [((3490, 3551), 'json.dumps', 'json.dumps', (["{'owner': owner, 'repo': repo, 'endCursor': None}"], {}), "({'owner': owner, 'repo': repo, 'endCursor': None})\n", (3500, 3551), False, 'import json\n'), ((6310, 6340), 'json.dump', 'json.dump', (['PROJECTS_TRACKED', 'f'], {}), '(PROJECTS_TRACKED, f)\n', (6319, 6340), Fals... |
from conductor.client.http.models.task import Task
from conductor.client.http.models.task_result import TaskResult
from conductor.client.http.models.task_result_status import TaskResultStatus
from conductor.client.worker.worker_interface import WorkerInterface
from ctypes import cdll
class CppWrapper:
def __init_... | [
"ctypes.cdll.LoadLibrary"
] | [((374, 401), 'ctypes.cdll.LoadLibrary', 'cdll.LoadLibrary', (['file_path'], {}), '(file_path)\n', (390, 401), False, 'from ctypes import cdll\n')] |
# pylint: disable=missing-module-docstring
# pylint: disable=missing-class-docstring
# pylint: disable=too-few-public-methods
import json
from typing import Dict, Any
from pathlib import Path
from loren.parsers.base_parser import BaseParser
class JSONParser(BaseParser):
@classmethod
def _parse(
cls,
... | [
"json.loads"
] | [((491, 524), 'json.loads', 'json.loads', (["data['file_contents']"], {}), "(data['file_contents'])\n", (501, 524), False, 'import json\n')] |
import torch
import torch.nn as nn
import torch.optim as optim
import gensim
import pickle
import time
import numpy
import os
from tqdm import tqdm
from torch.utils.data import TensorDataset
from torch.utils.data import DataLoader
from perf_model import BiLSTM, AC_BiLSTM, Time_BiLSTM
from perf_train import ... | [
"sklearn.metrics.f1_score",
"argparse.ArgumentParser",
"sklearn.metrics.classification_report",
"torch.load",
"torch.max",
"perf_model.BiLSTM",
"sklearn.metrics.precision_score",
"torch.tensor",
"sklearn.metrics.recall_score",
"torch.cuda.is_available",
"perf_train.SeqDataset",
"torch.no_grad"... | [((1504, 1540), 'torch.tensor', 'torch.tensor', (['ret'], {'dtype': 'torch.float'}), '(ret, dtype=torch.float)\n', (1516, 1540), False, 'import torch\n'), ((2405, 2430), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (2428, 2430), False, 'import argparse\n'), ((3811, 3924), 'perf_model.BiLSTM',... |
# coding: utf-8
from django import forms
class FormOne(forms.Form):
""" Exmaple form with several types of fields.
"""
char_field = forms.CharField(label=u'CharField')
radio_field = forms.ChoiceField(
widget=forms.RadioSelect,
label=u'RadioSelect',
choices=((x, 'choice %s' % x... | [
"django.forms.BooleanField",
"django.forms.FileField",
"django.forms.CharField"
] | [((146, 181), 'django.forms.CharField', 'forms.CharField', ([], {'label': 'u"""CharField"""'}), "(label=u'CharField')\n", (161, 181), False, 'from django import forms\n'), ((647, 688), 'django.forms.BooleanField', 'forms.BooleanField', ([], {'label': 'u"""BooleanField"""'}), "(label=u'BooleanField')\n", (665, 688), Fal... |
import os
import datetime
import pytest
import pandas as pd
import geopandas as gpd
from shapely.geometry import Point
import trackintel as ti
@pytest.fixture
def testdata_sp_tpls_geolife_long():
"""Generate sp and tpls sequences of the original pfs for subsequent testing."""
pfs, _ = ti.io.dataset_reader.r... | [
"trackintel.analysis.tracking_quality.temporal_tracking_quality",
"trackintel.analysis.tracking_quality._get_tracking_quality_user",
"pandas.to_timedelta",
"trackintel.analysis.tracking_quality._split_overlaps",
"pandas.Timedelta",
"os.path.join",
"shapely.geometry.Point",
"datetime.timedelta",
"tra... | [((1246, 1314), 'trackintel.preprocessing.triplegs.generate_trips', 'ti.preprocessing.triplegs.generate_trips', (['sp', 'tpls'], {'gap_threshold': '(15)'}), '(sp, tpls, gap_threshold=15)\n', (1286, 1314), True, 'import trackintel as ti\n'), ((1481, 1503), 'shapely.geometry.Point', 'Point', (['(8.5067847)', '(47.4)'], {... |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative wo... | [
"numpy.asarray",
"copy.deepcopy"
] | [((3476, 3489), 'numpy.asarray', 'np.asarray', (['x'], {}), '(x)\n', (3486, 3489), True, 'import numpy as np\n'), ((1695, 1717), 'copy.deepcopy', 'copy.deepcopy', (['problem'], {}), '(problem)\n', (1708, 1717), False, 'import copy\n')] |
from flask import Blueprint, jsonify, make_response, request, g, abort
from http import HTTPStatus
from models.user import User
from models.clip import Clip
from api.logic import Logic
class Api(Blueprint):
def __init__(self, logger):
super().__init__('api', __name__, url_prefix='/api')
self.add_u... | [
"api.logic.Logic.load_twitch_user",
"flask.g.db_session.add",
"flask.g.db_session.query",
"flask.g.db_session.commit",
"flask.abort",
"api.logic.Logic.load_twitch_clip",
"flask.jsonify"
] | [((788, 813), 'flask.jsonify', 'jsonify', (["{'asdf': 'qwer'}"], {}), "({'asdf': 'qwer'})\n", (795, 813), False, 'from flask import Blueprint, jsonify, make_response, request, g, abort\n'), ((2410, 2424), 'flask.jsonify', 'jsonify', (['clips'], {}), '(clips)\n', (2417, 2424), False, 'from flask import Blueprint, jsonif... |
import numpy as np
import scipy.spatial
import skimage.draw
import torch
from torchvision import io
import face_alignment
import matplotlib.pyplot as plt
def interpolate_from_landmarks(image, landmarks, vertex_indices=None, weights=None, mask=None):
H, W = image.shape[-2:]
step = 4
rect = landmarks.new_... | [
"torch.stack",
"face_alignment.FaceAlignment",
"torchvision.io.read_image",
"matplotlib.pyplot.margins",
"matplotlib.pyplot.plot",
"torch.from_numpy",
"torch.no_grad",
"matplotlib.pyplot.figure",
"torch.arange",
"numpy.random.seed",
"pdb.set_trace",
"matplotlib.pyplot.scatter",
"numpy.full",... | [((376, 411), 'torch.cat', 'torch.cat', (['[landmarks, rect]'], {'dim': '(0)'}), '([landmarks, rect], dim=0)\n', (385, 411), False, 'import torch\n'), ((1949, 1994), 'torch.gather', 'torch.gather', (['vertices'], {'dim': '(1)', 'index': 'expanded'}), '(vertices, dim=1, index=expanded)\n', (1961, 1994), False, 'import t... |
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class PatreonManagerConfig(AppConfig):
name = 'patreonmanager'
verbose_name = _("Patreon Manager")
| [
"django.utils.translation.gettext_lazy"
] | [((177, 197), 'django.utils.translation.gettext_lazy', '_', (['"""Patreon Manager"""'], {}), "('Patreon Manager')\n", (178, 197), True, 'from django.utils.translation import gettext_lazy as _\n')] |
from yaml import load, dump, FullLoader
import sys, os
class QuietLoaders:
def resource_path(self, relative):
if hasattr(sys, "_MEIPASS"):
return os.path.join(sys._MEIPASS, relative)
return os.path.join(relative)
def __init__(self):
self.settings_path = self.resource_path(os.path.join('data', 'config/sett... | [
"os.path.join",
"yaml.load",
"yaml.dump"
] | [((200, 222), 'os.path.join', 'os.path.join', (['relative'], {}), '(relative)\n', (212, 222), False, 'import sys, os\n'), ((154, 190), 'os.path.join', 'os.path.join', (['sys._MEIPASS', 'relative'], {}), '(sys._MEIPASS, relative)\n', (166, 190), False, 'import sys, os\n'), ((287, 331), 'os.path.join', 'os.path.join', ([... |
from bagPy import *
from math import isclose
import shutil, pathlib
import bagMetadataSamples, testUtils
import sys
# define constants used in multiple tests
datapath = str(pathlib.Path(__file__).parent.absolute()) + "/../examples/sample-data"
chunkSize = 100
compressionLevel = 6
print("Testing VRNode")
... | [
"testUtils.RandomFileGuard",
"math.isclose",
"pathlib.Path"
] | [((363, 396), 'testUtils.RandomFileGuard', 'testUtils.RandomFileGuard', (['"""name"""'], {}), "('name')\n", (388, 396), False, 'import bagMetadataSamples, testUtils\n'), ((1555, 1608), 'math.isclose', 'isclose', (['kExpectedMinHypStr', 'minHypStr'], {'abs_tol': '(1e-05)'}), '(kExpectedMinHypStr, minHypStr, abs_tol=1e-0... |
# !/usr/bin/python
# -*- coding: utf-8 -*-
# import cProfile
import argparse
import hmac
import itertools
import logging
import os
import string
import sys
import time
from hashlib import sha1
from multiprocessing import Process, Pipe
logging.basicConfig(format='%(asctime)s %(levelname)s: %(message)s', level=logging... | [
"logging.basicConfig",
"hmac.new",
"logging.debug",
"argparse.ArgumentParser",
"multiprocessing.Process",
"itertools.product",
"os.chdir",
"os.path.dirname",
"sys.exit",
"os.path.abspath",
"multiprocessing.Pipe",
"time.time",
"logging.error"
] | [((238, 332), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s %(levelname)s: %(message)s"""', 'level': 'logging.DEBUG'}), "(format='%(asctime)s %(levelname)s: %(message)s', level=\n logging.DEBUG)\n", (257, 332), False, 'import logging\n'), ((339, 364), 'os.path.abspath', 'os.path.abspa... |
import tensorflow as tf
from .fflayer import ffLayer
class Network:
"""
Build a physics informed neural network (PINN) model for the
Kuramoto-Sivashinsky equation.
"""
@classmethod
def build(cls, num_inputs=2, layers=None, activation=tf.nn.tanh,
sig_t=[1], sig_x=[1], num_outputs=... | [
"tensorflow.keras.layers.Input",
"tensorflow.multiply",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.models.Model",
"tensorflow.keras.models.Sequential"
] | [((1497, 1551), 'tensorflow.keras.layers.Input', 'tf.keras.layers.Input', ([], {'shape': '(num_inputs,)', 'name': '"""t_x"""'}), "(shape=(num_inputs,), name='t_x')\n", (1518, 1551), True, 'import tensorflow as tf\n'), ((1949, 1977), 'tensorflow.keras.models.Sequential', 'tf.keras.models.Sequential', ([], {}), '()\n', (... |
#!/usr/bin/python3
import time; # 引入time模块
ticks = time.time()
print ("当前时间戳为:", ticks)
localtime = time.localtime(time.time())
print ("本地时间为 :", localtime)
localtime = time.asctime( time.localtime(time.time()) )
print ("本地时间为 :", localtime)
# 格式化成Sat Mar 28 22:24:24 2016形式
time_str_asc = "%a %b %d %H:%M:%S %Y"
p... | [
"time.strptime",
"time.localtime",
"time.time"
] | [((54, 65), 'time.time', 'time.time', ([], {}), '()\n', (63, 65), False, 'import time\n'), ((119, 130), 'time.time', 'time.time', ([], {}), '()\n', (128, 130), False, 'import time\n'), ((203, 214), 'time.time', 'time.time', ([], {}), '()\n', (212, 214), False, 'import time\n'), ((354, 370), 'time.localtime', 'time.loca... |
import sys
sys.path.append("../..")
from DashApp import app
# this package Imports
from flask import request, render_template
import requests
headers = {
'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36',
'accept': 'application/json',
... | [
"flask.render_template",
"DashApp.app.route",
"sys.path.append",
"requests.get"
] | [((11, 35), 'sys.path.append', 'sys.path.append', (['"""../.."""'], {}), "('../..')\n", (26, 35), False, 'import sys\n'), ((482, 513), 'DashApp.app.route', 'app.route', (['"""/communityOverview"""'], {}), "('/communityOverview')\n", (491, 513), False, 'from DashApp import app\n'), ((779, 807), 'DashApp.app.route', 'app... |
from typing import List, Optional, Set, TYPE_CHECKING
import logging
import re
import subprocess as sp
import pandas as pd
if TYPE_CHECKING:
from filter_classified_reads.target_classified_reads import \
TargetClassifiedReads # noqa
def prefix_spaces(s: str) -> int:
"""Count number of prefix spaces ... | [
"subprocess.Popen",
"logging.info"
] | [((1305, 1356), 'logging.info', 'logging.info', (['f"""Total viral reads={n_target_total}"""'], {}), "(f'Total viral reads={n_target_total}')\n", (1317, 1356), False, 'import logging\n'), ((1361, 1453), 'logging.info', 'logging.info', (['f"""Centrifuge found n={n_target_uq_c} target reads not found with Kraken2"""'], {... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.views.generic import TemplateView
from django.conf.urls.i18n import i18n_patterns
admin.au... | [
"django.conf.urls.include",
"django.conf.urls.static.static",
"django.conf.urls.url",
"django.contrib.admin.autodiscover"
] | [((312, 332), 'django.contrib.admin.autodiscover', 'admin.autodiscover', ([], {}), '()\n', (330, 332), False, 'from django.contrib import admin\n'), ((458, 519), 'django.conf.urls.static.static', 'static', (['settings.MEDIA_URL'], {'document_root': 'settings.MEDIA_ROOT'}), '(settings.MEDIA_URL, document_root=settings.M... |
#!/usr/bin/pyton3
# -*- coding: utf-8 -*-
import sys,time,NetOLED,math,os
from PIL import Image,ImageDraw,ImageFont
from random import randrange
usage = """%s [options] host"""
if len(sys.argv) < 2:
print(usage % sys.argv[0])
exit(1)
for i in range(1,len(sys.argv)):
print(sys.argv[i])
msgothic = '/c/wi... | [
"os.path.exists",
"random.randrange",
"PIL.Image.new",
"time.sleep",
"PIL.ImageDraw.Draw",
"NetOLED.NetOLED"
] | [((441, 468), 'NetOLED.NetOLED', 'NetOLED.NetOLED', (['host', 'port'], {}), '(host, port)\n', (456, 468), False, 'import sys, time, NetOLED, math, os\n'), ((474, 496), 'PIL.Image.new', 'Image.new', (['"""1"""', '(w, h)'], {}), "('1', (w, h))\n", (483, 496), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((501... |
import sys
from typing import *
from progressbar.bar import ProgressBar
from progressbar.widgets import WidgetBase
class FatalError(Exception):
def __init__(self, exit_status: int = 1) -> None:
super().__init__()
self.exit_status = exit_status
def error(message: str) -> None:
print("ERROR: " + message, file ... | [
"progressbar.widgets.BouncingBar",
"progressbar.widgets.Percentage",
"progressbar.widgets.Counter",
"progressbar.widgets.AnimatedMarker",
"progressbar.widgets.Timer",
"progressbar.widgets.SimpleProgress",
"progressbar.widgets.Bar"
] | [((680, 720), 'progressbar.widgets.Percentage', 'widgets.Percentage', ([], {}), '(**pbar.widget_kwargs)\n', (698, 720), True, 'import progressbar.widgets as widgets\n'), ((730, 834), 'progressbar.widgets.SimpleProgress', 'widgets.SimpleProgress', ([], {'format': '"""({value:,} of {max_value:,})"""', 'new_style': '(True... |
"""Participants on Gratipay give payments and take payouts.
"""
from __future__ import print_function, unicode_literals
from datetime import timedelta
from decimal import Decimal
import pickle
from time import sleep
import uuid
from aspen.utils import utcnow
import balanced
import braintree
from dependency_injection ... | [
"braintree.Customer.create",
"pickle.dumps",
"gratipay.exceptions.UsernameIsRestricted",
"gratipay.utils.i18n.parse_accept_lang",
"time.sleep",
"gratipay.utils.encode_for_querystring",
"gratipay.exceptions.UsernameContainsInvalidCharacters",
"gratipay.utils.i18n.match_lang",
"pickle.loads",
"datet... | [((1714, 1733), 'datetime.timedelta', 'timedelta', ([], {'hours': '(24)'}), '(hours=24)\n', (1723, 1733), False, 'from datetime import timedelta\n'), ((6812, 6849), 'gratipay.utils.pricing.suggested_payment', 'pricing.suggested_payment', (['self.usage'], {}), '(self.usage)\n', (6837, 6849), False, 'from gratipay.utils ... |
# from mymodule import find_index,test
# import sys
import random as r
#stand library modules
import math
import datetime
import calendar
import os
print(os.__file__)
print(os.getcwd())
today=datetime.date.today()
print(today)
# #if you want to add module in another lcoation just add tha locaiton to sys.path
# # sys.p... | [
"datetime.date.today",
"random.choice",
"os.getcwd"
] | [((193, 214), 'datetime.date.today', 'datetime.date.today', ([], {}), '()\n', (212, 214), False, 'import datetime\n'), ((520, 537), 'random.choice', 'r.choice', (['courses'], {}), '(courses)\n', (528, 537), True, 'import random as r\n'), ((174, 185), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (183, 185), False, 'impor... |
import json
from io import TextIOWrapper
from django.core.management.base import BaseCommand, CommandError
class _BaseCommand(BaseCommand):
##################################################################
# Style objects reference from django.core.management.color.Style:
#
# self.styl... | [
"json.dumps"
] | [((2483, 2522), 'json.dumps', 'json.dumps', (['content'], {'indent': 'json_indent'}), '(content, indent=json_indent)\n', (2493, 2522), False, 'import json\n'), ((2679, 2718), 'json.dumps', 'json.dumps', (['content'], {'indent': 'json_indent'}), '(content, indent=json_indent)\n', (2689, 2718), False, 'import json\n')] |
from bs4 import BeautifulSoup
import collections
import pandas as pd
import uuid
from utils import *
if __name__ == "__main__":
url = 'https://www.basketball-reference.com/leagues/NBA_2020_totals.html'
candidates = ["<NAME>", "<NAME>", "<NAME>", "<NAME>",
"<NAME>", "<NAME>", "<NAME>", "<NAME>... | [
"bs4.BeautifulSoup",
"collections.defaultdict",
"uuid.uuid4"
] | [((967, 1010), 'bs4.BeautifulSoup', 'BeautifulSoup', (['html'], {'features': '"""html.parser"""'}), "(html, features='html.parser')\n", (980, 1010), False, 'from bs4 import BeautifulSoup\n'), ((1326, 1354), 'collections.defaultdict', 'collections.defaultdict', (['int'], {}), '(int)\n', (1349, 1354), False, 'import coll... |
from solr_admin.models.restricted_condition import RestrictedCondition
from solr_admin.models.restricted_word import RestrictedWord
from solr_admin.models.restricted_word_condition import RestrictedWordCondition
from solr_admin.models.virtual_word_condition import VirtualWordCondition
from solr_admin.services.create_re... | [
"solr_admin.services.create_records.create_records"
] | [((609, 637), 'solr_admin.services.create_records.create_records', 'create_records', (['row', 'session'], {}), '(row, session)\n', (623, 637), False, 'from solr_admin.services.create_records import create_records\n')] |
from __future__ import absolute_import, division, print_function
import codecs
try:
from collections import OrderedDict
except ImportError:
from ordereddict import OrderedDict
import copy
import os
import os.path as path
import sys
import toml
import nfldb
import nflfan.provider as provider
import nflfan.sco... | [
"nflfan.score.ScoreSchema",
"os.getenv",
"os.access",
"os.path.join",
"nflfan.provider.League",
"os.mkdir",
"copy.deepcopy",
"codecs.open",
"ordereddict.OrderedDict"
] | [((345, 373), 'os.getenv', 'os.getenv', (['"""XDG_CONFIG_HOME"""'], {}), "('XDG_CONFIG_HOME')\n", (354, 373), False, 'import os\n'), ((444, 461), 'os.getenv', 'os.getenv', (['"""HOME"""'], {}), "('HOME')\n", (453, 461), False, 'import os\n'), ((580, 610), 'os.path.join', 'path.join', (['_xdg_home', '"""nflfan"""'], {})... |
# -*- coding: utf-8 -*-
from __future__ import print_function
import json
import os
import subprocess
import unittest
import collections
import tempfile
import six
class AppRunner(object):
def __init__(self):
self.results = []
self.exit_code = None
def run(self, query, config_file = None):
... | [
"json.loads",
"subprocess.Popen",
"os.path.join",
"os.path.dirname",
"os.unlink",
"tempfile.mkstemp"
] | [((682, 781), 'subprocess.Popen', 'subprocess.Popen', (['cmd'], {'stdin': 'None', 'stdout': 'subprocess.PIPE', 'stderr': 'None', 'universal_newlines': '(True)'}), '(cmd, stdin=None, stdout=subprocess.PIPE, stderr=None,\n universal_newlines=True)\n', (698, 781), False, 'import subprocess\n'), ((3997, 4015), 'tempfile... |
import gffutils
import pandas.util.testing as pdt
import pandas as pd
import pytest
@pytest.fixture
def database():
return '/Users/rhythmicstar/projects/exon_evolution//gencode.v19.' \
'annotation.outrigger.nmdtest.gtf.db'
@pytest.fixture
def exon_ids():
return ('exon:chr10:101510126-101510153:+'... | [
"pandas.Series",
"nmd.NMDExons",
"pandas.util.testing.assert_dict_equal",
"pandas.util.testing.assert_equal",
"gffutils.FeatureDB",
"pytest.fixture",
"pandas.util.testing.assert_series_equal"
] | [((1072, 1088), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (1086, 1088), False, 'import pytest\n'), ((1335, 1351), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (1349, 1351), False, 'import pytest\n'), ((1497, 1513), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (1511, 1513), False, 'import p... |
''' Mesh analysis '''
import numpy as np
from scipy import sparse
FLOAT64_EPS = np.finfo(np.float64).eps
FLOAT_TYPES = np.sctypes['float']
white = 0
red = 1
black = 2
green = 3
def sym_hemisphere(vertices,
hemisphere='z',
equator_thresh=None,
dist_thresh=None... | [
"numpy.ones",
"numpy.unique",
"numpy.where",
"numpy.asarray",
"numpy.array",
"numpy.sum",
"numpy.nonzero",
"scipy.spatial.Delaunay",
"numpy.finfo",
"numpy.all",
"numpy.arange"
] | [((82, 102), 'numpy.finfo', 'np.finfo', (['np.float64'], {}), '(np.float64)\n', (90, 102), True, 'import numpy as np\n'), ((1983, 2003), 'numpy.asarray', 'np.asarray', (['vertices'], {}), '(vertices)\n', (1993, 2003), True, 'import numpy as np\n'), ((2944, 3010), 'numpy.where', 'np.where', (['((sel_col < equator_thresh... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Commonly used utility functions."""
# mainly backports from future numpy here
from __future__ import absolute_import, division, print_function
import numpy as np
import nibabel as nib
def thresholding_abs(A, thr, smaller=True, copy=True):
"""thresholding of the adjac... | [
"numpy.mean",
"numpy.unique",
"nibabel.load",
"numpy.zeros",
"numpy.empty",
"nibabel.Nifti1Image"
] | [((3741, 3755), 'nibabel.load', 'nib.load', (['mask'], {}), '(mask)\n', (3749, 3755), True, 'import nibabel as nib\n'), ((3952, 3987), 'numpy.zeros', 'np.zeros', (['(s[0], s[1], s[2], n_tps)'], {}), '((s[0], s[1], s[2], n_tps))\n', (3960, 3987), True, 'import numpy as np\n'), ((6100, 6129), 'numpy.empty', 'np.empty', (... |
#!/usr/bin/env python
import ipaddress
from collections import defaultdict
import pandas as pd
import numpy as np
from pyspark.sql import SparkSession
from pyspark.sql import functions as F, types as T, Window
# load iCloud's private relay egress ranges
# data comes from https://mask-api.icloud.com/egress-ip-range... | [
"ipaddress.ip_address",
"pyspark.sql.SparkSession.builder.master",
"pandas.read_csv",
"pyspark.sql.functions.col",
"collections.defaultdict",
"ipaddress.ip_network",
"pyspark.sql.functions.count"
] | [((1361, 1377), 'collections.defaultdict', 'defaultdict', (['set'], {}), '(set)\n', (1372, 1377), False, 'from collections import defaultdict\n'), ((1386, 1402), 'collections.defaultdict', 'defaultdict', (['set'], {}), '(set)\n', (1397, 1402), False, 'from collections import defaultdict\n'), ((1448, 1477), 'ipaddress.i... |
"""Setuptools post install script."""
import errno
import getpass
import os
import shutil
import sys
def run(install):
"""Runs all post install hooks."""
_copy_sh_ext(install)
def _copy_sh_ext(install):
"""Copy shell extension to funky config directory."""
this_dir = os.path.dirname(os.path.realpat... | [
"os.path.realpath",
"getpass.getuser",
"shutil.copyfile",
"os.makedirs"
] | [((901, 927), 'shutil.copyfile', 'shutil.copyfile', (['src', 'dest'], {}), '(src, dest)\n', (916, 927), False, 'import shutil\n'), ((305, 331), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (321, 331), False, 'import os\n'), ((577, 594), 'getpass.getuser', 'getpass.getuser', ([], {}), '()\... |
# Standard Libraries
import ipaddress
# Third party packages
from pydantic import conint, constr, root_validator
from pydantic.typing import Optional, Union, List, Literal
# Local package
from net_models.validators import *
from net_models.fields import GENERIC_OBJECT_NAME, VRF_NAME, BASE_INTERFACE_NAME, InterfaceName
... | [
"pydantic.constr",
"pydantic.conint",
"pydantic.root_validator"
] | [((1753, 1773), 'pydantic.constr', 'constr', ([], {'max_length': '(8)'}), '(max_length=8)\n', (1759, 1773), False, 'from pydantic import conint, constr, root_validator\n'), ((1992, 2024), 'pydantic.root_validator', 'root_validator', ([], {'allow_reuse': '(True)'}), '(allow_reuse=True)\n', (2006, 2024), False, 'from pyd... |
from inspect import Parameter, _ParameterKind, signature, Signature
from typing import Any, Callable, Optional, Tuple, Union, List, Dict
from dacite import Config, from_dict
from requests import Response
from beebole.interfaces.responses import SimpleResponse
from beebole.exceptions import (
BeeboleException, Bee... | [
"beebole.exceptions.BeeboleAPIException",
"dacite.from_dict",
"beebole.exceptions.BeeboleException",
"beebole.exceptions.BeeboleRateLimited",
"inspect.signature",
"inspect.signature.parameters.values",
"inspect.Parameter",
"beebole.exceptions.BeeboleNotFound",
"beebole.utils.Sentinel"
] | [((1798, 1890), 'inspect.Parameter', 'Parameter', (['argname', '_ParameterKind.KEYWORD_ONLY'], {'default': 'default', 'annotation': 'annotation'}), '(argname, _ParameterKind.KEYWORD_ONLY, default=default, annotation\n =annotation)\n', (1807, 1890), False, 'from inspect import Parameter, _ParameterKind, signature, Si... |
import torch
import torch.nn as nn
class MultiTaskLoss(nn.Module):
def __init__(self, num_tasks):
super(MultiTaskLoss, self).__init__()
self.sigma = nn.Parameter(torch.ones(num_tasks), requires_grad=True)
def forward(self, *losses):
losses = torch.cat([loss.unsqueeze(0) for loss in los... | [
"torch.pow",
"torch.ones"
] | [((183, 204), 'torch.ones', 'torch.ones', (['num_tasks'], {}), '(num_tasks)\n', (193, 204), False, 'import torch\n'), ((348, 372), 'torch.pow', 'torch.pow', (['self.sigma', '(2)'], {}), '(self.sigma, 2)\n', (357, 372), False, 'import torch\n')] |
from lxml.builder import ElementMaker
from moai.metadata.didl import DIDL
class DareDIDL(DIDL):
"""A metadata prefix implementing the DARE DIDL metadata format
this format is registered under the name "didl"
Note that this format re-uses oai_dc and mods formats that come with
MOAI by default
"""... | [
"lxml.builder.ElementMaker"
] | [((603, 657), 'lxml.builder.ElementMaker', 'ElementMaker', ([], {'namespace': "self.ns['didl']", 'nsmap': 'self.ns'}), "(namespace=self.ns['didl'], nsmap=self.ns)\n", (615, 657), False, 'from lxml.builder import ElementMaker\n'), ((672, 710), 'lxml.builder.ElementMaker', 'ElementMaker', ([], {'namespace': "self.ns['dii... |
__author__ = 'lachesis'
import os, sys
from Bio import SeqIO
from cupcake.io.SeqReaders import LazyFastaReader
from cupcake2.io.FileIO import write_seqids_to_fasta
input = 'isoseq_flnc.fasta'
NUM_SEQS_PER_BATCH = 50000
d = LazyFastaReader(input)
lens = [(r.id, len(r.seq)) for r in SeqIO.parse(open(input), 'fasta')... | [
"cupcake2.io.FileIO.write_seqids_to_fasta",
"cupcake.io.SeqReaders.LazyFastaReader"
] | [((227, 249), 'cupcake.io.SeqReaders.LazyFastaReader', 'LazyFastaReader', (['input'], {}), '(input)\n', (242, 249), False, 'from cupcake.io.SeqReaders import LazyFastaReader\n'), ((530, 575), 'cupcake2.io.FileIO.write_seqids_to_fasta', 'write_seqids_to_fasta', (['good', '"""seed0.fasta"""', 'd'], {}), "(good, 'seed0.fa... |
import os
import functools
from mako.lookup import TemplateLookup
DIR = os.path.dirname(os.path.abspath(__file__))
templateDirs = [os.path.join(DIR, 'templates')]
templateLookup = TemplateLookup(directories=templateDirs)
def serveTemplate(path):
def deco(func):
@functools.wraps(func)
def _serve(... | [
"os.path.abspath",
"os.path.join",
"functools.wraps",
"mako.lookup.TemplateLookup"
] | [((183, 223), 'mako.lookup.TemplateLookup', 'TemplateLookup', ([], {'directories': 'templateDirs'}), '(directories=templateDirs)\n', (197, 223), False, 'from mako.lookup import TemplateLookup\n'), ((90, 115), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (105, 115), False, 'import os\n'), ((... |
import logging
from pathlib import Path
def get_logger(logger_name: str):
Path("logs/").mkdir(parents=True, exist_ok=True)
logger = logging.getLogger(logger_name)
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler('logs/' + logger_name + '.log')
fh.setLevel(logging.DEBUG)
ch = logging.Str... | [
"logging.getLogger",
"logging.StreamHandler",
"pathlib.Path",
"logging.Formatter",
"logging.FileHandler"
] | [((142, 172), 'logging.getLogger', 'logging.getLogger', (['logger_name'], {}), '(logger_name)\n', (159, 172), False, 'import logging\n'), ((217, 268), 'logging.FileHandler', 'logging.FileHandler', (["('logs/' + logger_name + '.log')"], {}), "('logs/' + logger_name + '.log')\n", (236, 268), False, 'import logging\n'), (... |
"""
Procedures for running a privacy evaluation on a generative model
"""
from sklearn.metrics import roc_curve, auc
from os import path
from numpy import concatenate, mean, ndarray
from pandas import DataFrame
from pandas.api.types import is_numeric_dtype
from multiprocessing import Pool
from synthetic_data.privacy_... | [
"warnings.filterwarnings",
"numpy.mean",
"sklearn.metrics.auc",
"pandas.api.types.is_numeric_dtype",
"sklearn.metrics.roc_curve",
"multiprocessing.Pool",
"synthetic_data.privacy_attacks.membership_inference.generate_mia_shadow_data_shufflesplit",
"numpy.concatenate",
"synthetic_data.privacy_attacks.... | [((597, 621), 'warnings.filterwarnings', 'filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (611, 621), False, 'from warnings import filterwarnings\n'), ((970, 999), 'sklearn.metrics.roc_curve', 'roc_curve', (['trueLables', 'scores'], {}), '(trueLables, scores)\n', (979, 999), False, 'from sklearn.metrics import... |
import base64
import gzip
import json
import sys
from typing import List
from pyspark.sql import DataFrame, SparkSession
from pyspark.sql.functions import (
array_contains,
array_sort,
col,
explode,
lit,
split,
collect_set,
to_json,
when,
udf,
expr,
struct,
lower,
... | [
"pyspark.sql.functions.expr",
"pyspark.sql.SparkSession.builder.getOrCreate",
"pyspark.sql.functions.explode_outer",
"sys.exc_info",
"pyspark.sql.window.Window.partitionBy",
"pyspark.sql.functions.min",
"pyspark.sql.functions.first",
"pyspark.sql.functions.regexp_replace",
"pyspark.sql.types.Integer... | [((8428, 8462), 'pyspark.sql.SparkSession.builder.getOrCreate', 'SparkSession.builder.getOrCreate', ([], {}), '()\n', (8460, 8462), False, 'from pyspark.sql import DataFrame, SparkSession\n'), ((9094, 9120), 'json.loads', 'json.loads', (['mp_chooser_txt'], {}), '(mp_chooser_txt)\n', (9104, 9120), False, 'import json\n'... |
#!/usr/bin/env python3
import time
import socket
HOST = ""
PORT = 5000
TIMEOUT = None
MAXBUF = 256
print("Create UDP Server Socket")
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.settimeout(TIMEOUT)
s.bind((HOST, PORT))
buf = bytearray(MAXBUF)
while True:
size, addr = s.recvfrom_into(buf)
print("... | [
"socket.socket"
] | [((141, 189), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_DGRAM'], {}), '(socket.AF_INET, socket.SOCK_DGRAM)\n', (154, 189), False, 'import socket\n')] |
import numpy as np
from model import generate_recommendations
user_address = '0x8c373ed467f3eabefd8633b52f4e1b2df00c9fe8'
already_rated = ['0x006bea43baa3f7a6f765f14f10a1a1b08334ef45','0x5102791ca02fc3595398400bfe0e33d7b6c82267','0x68d57c9a1c35f63e2c83ee8e49a64e9d70528d25','0xc528c28fec0a90c083328bc45f587ee215760a0f']... | [
"numpy.searchsorted",
"numpy.load",
"model.generate_recommendations"
] | [((392, 430), 'numpy.load', 'np.load', (["(model_dir + '/model/user.npy')"], {}), "(model_dir + '/model/user.npy')\n", (399, 430), True, 'import numpy as np\n'), ((442, 480), 'numpy.load', 'np.load', (["(model_dir + '/model/item.npy')"], {}), "(model_dir + '/model/item.npy')\n", (449, 480), True, 'import numpy as np\n'... |
import copy
import json
import numpy
import cepton_sdk.common.transform
from cepton_sdk.common import *
_all_builder = AllBuilder(__name__)
def _convert_keys_to_int(d, ignore_invalid=False):
d_int = {}
for key, value in d.items():
try:
key = int(key)
except:
if ignor... | [
"json.dumps",
"numpy.any",
"numpy.array",
"numpy.logical_and.reduce",
"json.load",
"numpy.full",
"numpy.logical_or.reduce"
] | [((606, 669), 'json.dumps', 'json.dumps', (['d'], {'sort_keys': '(True)', 'indent': '(2)', 'separators': "(',', ': ')"}), "(d, sort_keys=True, indent=2, separators=(',', ': '))\n", (616, 669), False, 'import json\n'), ((1361, 1382), 'json.load', 'json.load', (['input_file'], {}), '(input_file)\n', (1370, 1382), False, ... |
# Generated by Django 3.0.4 on 2020-03-25 14:09
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('InvManage', '0008_auto_20200325_1938'),
]
operations = [
migrations.AlterField(
model_name='product',
name='height',... | [
"django.db.models.FloatField"
] | [((339, 379), 'django.db.models.FloatField', 'models.FloatField', ([], {'blank': '(True)', 'null': '(True)'}), '(blank=True, null=True)\n', (356, 379), False, 'from django.db import migrations, models\n'), ((502, 542), 'django.db.models.FloatField', 'models.FloatField', ([], {'blank': '(True)', 'null': '(True)'}), '(bl... |
import unittest
from Common.Analysis.EvaluationMetrics import EvaluationMetrics, TypeML
from Common.Analysis.MergeResults import MergeResults
from Common.Config.config import get_default_config
from Models import *
from Tests.BaseTest import *
from Tests.errors import get_error, get_error_txt
FILE_DATASET = 'Datasets... | [
"unittest.main",
"Common.Config.config.get_default_config",
"Common.Analysis.MergeResults.MergeResults",
"Tests.errors.get_error"
] | [((2630, 2645), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2643, 2645), False, 'import unittest\n'), ((1024, 1054), 'Common.Config.config.get_default_config', 'get_default_config', (['m', 'io_data'], {}), '(m, io_data)\n', (1042, 1054), False, 'from Common.Config.config import get_default_config\n'), ((1512, ... |
# moderation.py
# houses all the moderation code. very useful other than the fact that 80% of bots have these commands.
import discord
from discord.ext import commands
class Moderation(commands.Cog):
def __init__(self,client):
self.client = client
@commands.command()
@commands.has_permissions(man... | [
"discord.ext.commands.has_permissions",
"discord.ext.commands.command"
] | [((268, 286), 'discord.ext.commands.command', 'commands.command', ([], {}), '()\n', (284, 286), False, 'from discord.ext import commands\n'), ((292, 338), 'discord.ext.commands.has_permissions', 'commands.has_permissions', ([], {'manage_messages': '(True)'}), '(manage_messages=True)\n', (316, 338), False, 'from discord... |
import time
import fero
import uuid
import io
import datetime
from fero import FeroError
import pandas as pd
from marshmallow import (
Schema,
fields,
validate,
validates_schema,
ValidationError,
EXCLUDE,
)
from typing import Union, List, Optional, IO
from .common import FeroObject
VALID_GOALS... | [
"marshmallow.fields.Number",
"marshmallow.ValidationError",
"marshmallow.fields.Float",
"marshmallow.fields.Nested",
"time.sleep",
"marshmallow.fields.UUID",
"marshmallow.fields.DateTime",
"marshmallow.validate.OneOf",
"fero.FeroError",
"uuid.uuid4",
"datetime.datetime.now",
"marshmallow.field... | [((613, 641), 'marshmallow.fields.String', 'fields.String', ([], {'required': '(True)'}), '(required=True)\n', (626, 641), False, 'from marshmallow import Schema, fields, validate, validates_schema, ValidationError, EXCLUDE\n'), ((665, 693), 'marshmallow.fields.String', 'fields.String', ([], {'required': '(True)'}), '(... |
import os
from evaluator.properties import (
Density,
EnthalpyOfMixing,
EnthalpyOfVaporization,
ExcessMolarVolume,
)
from nistdataselection.analysis.plotting import (
plot_estimated_vs_reference,
plot_statistic,
plot_statistic_per_environment,
)
from nistdataselection.analysis.statistics i... | [
"nistdataselection.analysis.plotting.plot_statistic",
"nistdataselection.analysis.plotting.plot_estimated_vs_reference",
"nistdataselection.analysis.plotting.plot_statistic_per_environment",
"os.makedirs"
] | [((437, 481), 'os.makedirs', 'os.makedirs', (['output_directory'], {'exist_ok': '(True)'}), '(output_directory, exist_ok=True)\n', (448, 481), False, 'import os\n'), ((966, 1040), 'nistdataselection.analysis.plotting.plot_estimated_vs_reference', 'plot_estimated_vs_reference', (['property_types', 'study_names', 'output... |
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | [
"logging.basicConfig",
"launcher.launch",
"argparse.ArgumentParser"
] | [((742, 781), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (761, 781), False, 'import logging\n'), ((793, 885), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'prog': '"""launcher"""', 'description': '"""Launch a python module or file."""'}), "(pr... |
"""
Small utility to POST /TransferRequest
Run with `python -m lta.make_transfer_request WIPAC:/data/exp/blah DESY:/data/exp/blah NERSC:/data/exp/blah`.
"""
import asyncio
from rest_tools.client import RestClient # type: ignore
from rest_tools.server import from_environment # type: ignore
import sys
EXPECTED_CONFI... | [
"asyncio.get_event_loop",
"rest_tools.client.RestClient",
"rest_tools.server.from_environment"
] | [((797, 830), 'rest_tools.server.from_environment', 'from_environment', (['EXPECTED_CONFIG'], {}), '(EXPECTED_CONFIG)\n', (813, 830), False, 'from rest_tools.server import from_environment\n'), ((840, 906), 'rest_tools.client.RestClient', 'RestClient', (["config['LTA_REST_URL']"], {'token': "config['LTA_REST_TOKEN']"})... |
from setuptools import setup, find_packages
setup(
name="Segy2Segy",
version="0.2",
packages=find_packages(exclude=["tests*"]),
scripts=['core/segy2segy.py'],
install_requires=['gdal', 'obspy'],
author="<NAME>",
author_email="<EMAIL>",
description="A command line tool for projecting an... | [
"setuptools.find_packages"
] | [((105, 138), 'setuptools.find_packages', 'find_packages', ([], {'exclude': "['tests*']"}), "(exclude=['tests*'])\n", (118, 138), False, 'from setuptools import setup, find_packages\n')] |
#!/usr/bin/python3
from sklearn import tree
#features about APPLE=0 and ORANGE=1
data=[[100,0],[130,0],[135,1],[150,1]]
output=["APPLE","APPLE","ORANGE","ORANGE"]
#decision tree algorithm call
trained_algo=tree.DecisionTreeClassifier()
#train the data
trained_data=trained_algo.fit(data,output)
#now testing phase
p... | [
"sklearn.tree.DecisionTreeClassifier"
] | [((209, 238), 'sklearn.tree.DecisionTreeClassifier', 'tree.DecisionTreeClassifier', ([], {}), '()\n', (236, 238), False, 'from sklearn import tree\n')] |
import yaml
from torch import nn, optim
from pytorch_lightning.callbacks import LearningRateMonitor, ModelCheckpoint
from pytorch_lightning.loggers import TensorBoardLogger
from monai.losses import DiceCELoss
import factorizer as ft
from factorizer import datasets
from factorizer.utils.lightning import SemanticSegmen... | [
"yaml.load"
] | [((4009, 4032), 'yaml.load', 'yaml.load', (['file', 'Loader'], {}), '(file, Loader)\n', (4018, 4032), False, 'import yaml\n')] |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2018-06-05 08:38
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('yaksh', '0015_auto_20180601_1215'),
]
operations = [
migrations.AlterField(
... | [
"django.db.models.CharField"
] | [((397, 713), 'django.db.models.CharField', 'models.CharField', ([], {'choices': "[('mcq', 'Single Correct Choice'), ('mcc', 'Multiple Correct Choices'), (\n 'code', 'Code'), ('upload', 'Assignment Upload'), ('integer',\n 'Answer in Integer'), ('string', 'Answer in String'), ('float',\n 'Answer in Float'), ('a... |
# -*- coding: utf-8 -*-
"""
:copyright: Copyright 2021 Sphinx Confluence Builder Contributors (AUTHORS)
:license: BSD-2-Clause (LICENSE)
"""
from sphinxcontrib.confluencebuilder.exceptions import ConfluenceAuthenticationFailedUrlError
from sphinxcontrib.confluencebuilder.exceptions import ConfluenceBadServerUrlError
f... | [
"sphinxcontrib.confluencebuilder.publisher.ConfluencePublisher",
"tests.lib.prepare_conf",
"tests.lib.mock_confluence_instance",
"time.time"
] | [((880, 894), 'tests.lib.prepare_conf', 'prepare_conf', ([], {}), '()\n', (892, 894), False, 'from tests.lib import prepare_conf\n'), ((1211, 1248), 'tests.lib.mock_confluence_instance', 'mock_confluence_instance', (['self.config'], {}), '(self.config)\n', (1235, 1248), False, 'from tests.lib import mock_confluence_ins... |
#!/usr/bin/env python
from __future__ import print_function
import ROOT
import sys,os,string,errno,shutil
import code
from ROOT import gROOT, gDirectory, gPad, gSystem, gRandom, gStyle
from ROOT import TH1, TH1F, TCanvas, TFile
ROOT.gROOT.SetBatch()
ROOT.gStyle.SetMarkerStyle(2)
ROOT.gStyle.SetMarkerSize(0.6)
ROOT.gS... | [
"os.listdir",
"shutil.copy2",
"ROOT.TCanvas",
"ROOT.gROOT.ProcessLine",
"os.path.join",
"os.getcwd",
"ROOT.gROOT.SetBatch",
"ROOT.gStyle.SetMarkerSize",
"ROOT.TFile",
"ROOT.gStyle.SetMarkerStyle",
"ROOT.gStyle.SetMarkerColor",
"ROOT.gStyle.SetOptStat"
] | [((230, 251), 'ROOT.gROOT.SetBatch', 'ROOT.gROOT.SetBatch', ([], {}), '()\n', (249, 251), False, 'import ROOT\n'), ((252, 281), 'ROOT.gStyle.SetMarkerStyle', 'ROOT.gStyle.SetMarkerStyle', (['(2)'], {}), '(2)\n', (278, 281), False, 'import ROOT\n'), ((282, 312), 'ROOT.gStyle.SetMarkerSize', 'ROOT.gStyle.SetMarkerSize', ... |
import numpy as np
import sys
from contextlib import closing
from io import StringIO
from gym import Env, spaces, utils
from gym.utils import seeding
UP = 0
RIGHT = 1
DOWN = 2
LEFT = 3
def categorical_sample(prob_n, np_random):
"""
Sample from categorical distribution
Each row specifies class probabilitie... | [
"numpy.prod",
"numpy.ravel_multi_index",
"numpy.asarray",
"gym.spaces.Discrete",
"numpy.array",
"numpy.zeros",
"gym.utils.EzPickle.__init__",
"numpy.unravel_index",
"contextlib.closing",
"numpy.cumsum",
"io.StringIO",
"gym.utils.seeding.np_random"
] | [((343, 361), 'numpy.asarray', 'np.asarray', (['prob_n'], {}), '(prob_n)\n', (353, 361), True, 'import numpy as np\n'), ((377, 394), 'numpy.cumsum', 'np.cumsum', (['prob_n'], {}), '(prob_n)\n', (386, 394), True, 'import numpy as np\n'), ((1119, 1143), 'gym.spaces.Discrete', 'spaces.Discrete', (['self.nA'], {}), '(self.... |
# Copyright 2019 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | [
"compiler.front_end.test_util.dict_file_reader",
"compiler.util.error.note",
"compiler.front_end.symbol_resolver.resolve_symbols",
"compiler.front_end.symbol_resolver.resolve_field_references",
"unittest.main",
"compiler.util.error.filter_errors",
"compiler.util.error.error"
] | [((32764, 32779), 'unittest.main', 'unittest.main', ([], {}), '()\n', (32777, 32779), False, 'import unittest\n'), ((16732, 16767), 'compiler.front_end.symbol_resolver.resolve_symbols', 'symbol_resolver.resolve_symbols', (['ir'], {}), '(ir)\n', (16763, 16767), False, 'from compiler.front_end import symbol_resolver\n'),... |
"""Tests for the objectrocket.acls module."""
import responses
from objectrocket.acls import Acl
####################################
# Tests for Acls public interface. #
####################################
# Tests for all. #
@responses.activate
def test_all_makes_expected_api_request(client):
instance_name = '... | [
"objectrocket.acls.Acl",
"responses.add"
] | [((426, 536), 'responses.add', 'responses.add', (['responses.GET', 'expected_url'], {'status': '(200)', 'json': "{'data': []}", 'content_type': '"""application/json"""'}), "(responses.GET, expected_url, status=200, json={'data': []},\n content_type='application/json')\n", (439, 536), False, 'import responses\n'), ((... |
#!/usr/bin/python3
"""Given the far corners of each hut, calculates the ideal AFK position.
Finds the "center" position between four huts - the point that minimizes
the distance to the furthest corner - and gives you the distance. It also
displays a diagram showing the AFKable area around that point.
Most quad-hut co... | [
"math.sqrt",
"sys.exit"
] | [((756, 808), 'math.sqrt', 'math.sqrt', (['((ax - bx) ** 2 + (az - bz) ** 2 + 19 ** 2)'], {}), '((ax - bx) ** 2 + (az - bz) ** 2 + 19 ** 2)\n', (765, 808), False, 'import math\n'), ((1849, 1859), 'sys.exit', 'sys.exit', ([], {}), '()\n', (1857, 1859), False, 'import sys\n')] |
'''Provides a class for representing a hand pose and a hand volume.'''
# python
from time import time
from copy import copy
# scipy
from matplotlib import pyplot
from numpy.linalg import inv, norm
from numpy.random import rand, randn
from numpy import arange, arccos, arctan, arctan2, array, ascontiguousarray, ceil, co... | [
"matplotlib.pyplot.imshow",
"numpy.eye",
"numpy.cross",
"numpy.ones",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.title",
"numpy.maximum",
"numpy.round",
"matplotlib.pyplot.show"
] | [((3231, 3237), 'numpy.eye', 'eye', (['(4)'], {}), '(4)\n', (3234, 3237), False, 'from numpy import arange, arccos, arctan, arctan2, array, ascontiguousarray, ceil, concatenate, cross, dot, eye, linspace, maximum, meshgrid, ones, pi, reshape, round, sqrt, stack, zeros\n'), ((3271, 3292), 'numpy.cross', 'cross', (['appr... |
"""
Write 'py.test tests.py' in the terminal to test by using the 'pytest' package.
For this, change the path in Windows by 'cd pyglobe3d\core\icosalogic\'.
"""
from pyglobe3d.core.icosalogic.mesh import Mesh
from pyglobe3d.core.icosalogic.node import Node
from pyglobe3d.core.icosalogic.node_attrs import NodeIndex, Nod... | [
"pyglobe3d.core.icosalogic.node_attrs.NodeLocation",
"pyglobe3d.core.icosalogic.triangle_attrs.TriangleIndex",
"pyglobe3d.core.icosalogic.triangle_attrs.TriangleLocation",
"pyglobe3d.core.icosalogic.node_attrs.NodeIndex",
"pyglobe3d.core.icosalogic.mesh.Mesh"
] | [((6409, 6426), 'pyglobe3d.core.icosalogic.mesh.Mesh', 'Mesh', ([], {'partition': '(4)'}), '(partition=4)\n', (6413, 6426), False, 'from pyglobe3d.core.icosalogic.mesh import Mesh\n'), ((1745, 1836), 'pyglobe3d.core.icosalogic.node_attrs.NodeLocation', 'NodeLocation', ([], {'grid': 'mesh.GRID', 'layer': 'nd1.layer', 'p... |
from setuptools import setup, find_packages
from os.path import join, dirname
import torrentgamers
attrs = {
'name': torrentgamers.__name__,
'version': torrentgamers.__version__,
'author': torrentgamers.__author__,
'author_email': torrentgamers.__email__,
'url': torrentgamers.__url__,
'long_de... | [
"os.path.dirname",
"setuptools.find_packages",
"setuptools.setup"
] | [((485, 499), 'setuptools.setup', 'setup', ([], {}), '(**attrs)\n', (490, 499), False, 'from setuptools import setup, find_packages\n'), ((399, 414), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (412, 414), False, 'from setuptools import setup, find_packages\n'), ((342, 359), 'os.path.dirname', 'dirna... |
import torch
from torch import nn
from torch.nn import functional as F
def masked_normalization(logits, mask):
scores = F.softmax(logits, dim=-1)
# apply the mask - zero out masked timesteps
masked_scores = scores * mask.float()
# re-normalize the masked scores
normed_scores = masked_scores.div(... | [
"torch.nn.ReLU",
"torch.nn.Dropout",
"torch.nn.Tanh",
"torch.nn.Sequential",
"torch.nn.Linear",
"torch.nn.functional.softmax",
"torch.arange"
] | [((126, 151), 'torch.nn.functional.softmax', 'F.softmax', (['logits'], {'dim': '(-1)'}), '(logits, dim=-1)\n', (135, 151), True, 'from torch.nn import functional as F\n'), ((1659, 1682), 'torch.nn.Sequential', 'nn.Sequential', (['*modules'], {}), '(*modules)\n', (1672, 1682), False, 'from torch import nn\n'), ((1133, 1... |
from .utils.suite_writer import Suite
from contextlib import contextmanager
import pytest
# pylint: disable=redefined-outer-name
def test_expect_failure_not_met(suite, test):
test.expect_failure()
with _raises_assertion('Test did not fail as expected'):
suite.run()
def test_expect_error_not_met(su... | [
"pytest.raises"
] | [((500, 529), 'pytest.raises', 'pytest.raises', (['AssertionError'], {}), '(AssertionError)\n', (513, 529), False, 'import pytest\n')] |
import os
import sys
from os import path
current_dir = path.dirname(path.abspath(__file__))
while path.split(current_dir)[-1] != r'Heron':
current_dir = path.dirname(current_dir)
sys.path.insert(0, path.dirname(current_dir))
from Heron import general_utils as gu
Exec = os.path.abspath(__file__)
#... | [
"Heron.general_utils.register_exit_signals",
"Heron.general_utils.start_the_transform_communications_process",
"os.path.split",
"os.path.dirname",
"os.path.abspath"
] | [((288, 313), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (303, 313), False, 'import os\n'), ((75, 97), 'os.path.abspath', 'path.abspath', (['__file__'], {}), '(__file__)\n', (87, 97), False, 'from os import path\n'), ((166, 191), 'os.path.dirname', 'path.dirname', (['current_dir'], {}), '... |
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... | [
"numpy.random.randint"
] | [((4361, 4392), 'numpy.random.randint', 'np.random.randint', (['min_v', 'max_v'], {}), '(min_v, max_v)\n', (4378, 4392), True, 'import numpy as np\n')] |
"""
This file contains the Pre-Generate Hooks for Cookiecutter.
They are executed AFTER the user entered their project config,
but BEFORE the project is actually generated. More details:
https://cookiecutter.readthedocs.io/en/1.7.2/advanced/hooks.html
In this script we execute environment checks and run input validati... | [
"distutils.version.StrictVersion",
"re.match",
"platform.python_version",
"sys.exit"
] | [((689, 711), 'distutils.version.StrictVersion', 'StrictVersion', (['"""3.6.0"""'], {}), "('3.6.0')\n", (702, 711), False, 'from distutils.version import StrictVersion\n'), ((867, 878), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (875, 878), False, 'import sys\n'), ((930, 969), 'distutils.version.StrictVersion', 'S... |
#!/usr/bin/python3
import argparse
import os
import subprocess
import tarfile
import tempfile
from pathlib import Path
from typing import List
parser = argparse.ArgumentParser(
description='Run k-core decomposition on hypergraphs in a TAR file and report decompositions with interesting cuts.')
parser.add_argument... | [
"tempfile.TemporaryDirectory",
"tarfile.open",
"argparse.ArgumentParser",
"pathlib.Path",
"subprocess.Popen",
"os.path.join",
"os.getcwd",
"os.chdir"
] | [((154, 305), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Run k-core decomposition on hypergraphs in a TAR file and report decompositions with interesting cuts."""'}), "(description=\n 'Run k-core decomposition on hypergraphs in a TAR file and report decompositions with interesting... |
#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
# Copyright (C) 2020-2021 <NAME> <<EMAIL>>
#
# Exports a static HTML view of your shotwell photo/video library.
import html
import os
from collections import Counter
import urllib.parse
import humanize
import common
from media_writer_common import CommonWrit... | [
"os.makedirs",
"humanize.naturalsize",
"os.path.join",
"collections.Counter",
"os.path.dirname",
"common.cleanup_event_title",
"os.path.isdir",
"common.add_date_to_stats",
"media_writer_common.CommonWriter.__init__",
"humanize.intcomma",
"html.escape"
] | [((674, 806), 'media_writer_common.CommonWriter.__init__', 'CommonWriter.__init__', (['self', 'all_media', 'main_title', 'max_media_per_page', 'years_prior_are_approximate', 'extra_header', 'version_label'], {}), '(self, all_media, main_title, max_media_per_page,\n years_prior_are_approximate, extra_header, version_... |