code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import copy
import numpy as np
from nltk import WordNetLemmatizer
from intermediate_representation import lf
from spider.example import Example
# Take care, this imports are necessary due to the dynamic "eval()" command further down
from intermediate_representation.semQL import Sup, Sel, Order, Root, Filter, A, N, C,... | [
"copy.copy",
"nltk.WordNetLemmatizer",
"copy.deepcopy"
] | [((355, 374), 'nltk.WordNetLemmatizer', 'WordNetLemmatizer', ([], {}), '()\n', (372, 374), False, 'from nltk import WordNetLemmatizer\n'), ((3720, 3738), 'copy.deepcopy', 'copy.deepcopy', (['sql'], {}), '(sql)\n', (3733, 3738), False, 'import copy\n'), ((4189, 4207), 'copy.deepcopy', 'copy.deepcopy', (['sql'], {}), '(s... |
import multiprocessing
bind = "0.0.0.0:8000"
workers = multiprocessing.cpu_count() * 2 + 1
threads = workers*3
# accesslog = '/tmp/accesslog.txt'
# access_log_format = 'Neon (Outbreak News Today) %(h)s %(u)s %(t)s %(m)s Resopnse: %(s)s "%(q)s"'
| [
"multiprocessing.cpu_count"
] | [((56, 83), 'multiprocessing.cpu_count', 'multiprocessing.cpu_count', ([], {}), '()\n', (81, 83), False, 'import multiprocessing\n')] |
import copy
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Function
# ********************* quantizers(量化器,量化) *********************
# 取整(ste)
class Round(Function):
@staticmethod
def forward(self, input):
sign = torch.sign(input)
outp... | [
"torch.nn.functional.linear",
"torch.nn.functional.conv2d",
"torch.abs",
"math.sqrt",
"torch.sign",
"torch.transpose",
"torch.nn.functional.conv_transpose2d",
"torch.div",
"copy.deepcopy",
"torch.ones"
] | [((290, 307), 'torch.sign', 'torch.sign', (['input'], {}), '(input)\n', (300, 307), False, 'import torch\n'), ((9030, 9135), 'torch.nn.functional.conv2d', 'F.conv2d', (['quant_input', 'quant_weight', 'self.bias', 'self.stride', 'self.padding', 'self.dilation', 'self.groups'], {}), '(quant_input, quant_weight, self.bias... |
import os
import boto3
from python.fedml.utils import logging
from python.fedml.utils.logging import logger
BUCKET_NAME = "fedmls3"
# aws_access_key_id、aws_secret_access_key、region
CN_S3_AKI = ''
CN_S3_SAK = ''
CN_REGION_NAME = 'us-east-1'
# s3 client
s3 = boto3.client('s3', region_name=CN_REGION_NAME,
... | [
"os.path.getsize",
"boto3.client",
"python.fedml.utils.logging.error",
"python.fedml.utils.logging.info"
] | [((260, 372), 'boto3.client', 'boto3.client', (['"""s3"""'], {'region_name': 'CN_REGION_NAME', 'aws_access_key_id': 'CN_S3_AKI', 'aws_secret_access_key': 'CN_S3_SAK'}), "('s3', region_name=CN_REGION_NAME, aws_access_key_id=CN_S3_AKI,\n aws_secret_access_key=CN_S3_SAK)\n", (272, 372), False, 'import boto3\n'), ((824,... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
from PyQt5 import QtGui
from PyQt5 import QtCore
from PyQt5 import QtWidgets
import requests
from dataBase import signal_DB
import threading
from Crypto.Hash import MD5
if __name__ == '__main__':
from basedialog import BaseDialog
else:
from .basedialog import ... | [
"PyQt5.QtWidgets.QLineEdit",
"requests.post",
"PyQt5.QtCore.pyqtSlot",
"PyQt5.QtWidgets.QGridLayout",
"PyQt5.QtWidgets.QLabel",
"dataBase.signal_DB.login_sin.emit",
"PyQt5.QtGui.QApplication",
"PyQt5.QtWidgets.QPushButton",
"dataBase.signal_DB.login_sin.connect"
] | [((3142, 3163), 'PyQt5.QtCore.pyqtSlot', 'QtCore.pyqtSlot', (['dict'], {}), '(dict)\n', (3157, 3163), False, 'from PyQt5 import QtCore\n'), ((4872, 4900), 'PyQt5.QtGui.QApplication', 'QtGui.QApplication', (['sys.argv'], {}), '(sys.argv)\n', (4890, 4900), False, 'from PyQt5 import QtGui\n'), ((520, 544), 'PyQt5.QtWidget... |
from django.urls import include, path
from . import views
urlpatterns = [
path('confirm-email/<str:key>/', views.UserConfirmEmailView.as_view(), name='confirm_email'),
path('social/signup/', views.SocialUserSignupView.as_view(), name='socialaccount_signup'),
path('', include('allauth.urls')),
]
| [
"django.urls.include"
] | [((283, 306), 'django.urls.include', 'include', (['"""allauth.urls"""'], {}), "('allauth.urls')\n", (290, 306), False, 'from django.urls import include, path\n')] |
from __future__ import print_function
from cepbp.common.input_testing import TestInputs
from cepbp.common.logs import Logs
from cepbp.common.custom_error_handler import CustomError
from cepbp.areas import Areas
from cepbp.perimeters import Perimeters
import configparser
import logging
import sys
import numpy as np
cl... | [
"cepbp.common.input_testing.TestInputs.__init__",
"cepbp.common.logs.Logs",
"cepbp.common.custom_error_handler.CustomError",
"numpy.isinf"
] | [((1278, 1303), 'cepbp.common.input_testing.TestInputs.__init__', 'TestInputs.__init__', (['self'], {}), '(self)\n', (1297, 1303), False, 'from cepbp.common.input_testing import TestInputs\n'), ((1476, 1482), 'cepbp.common.logs.Logs', 'Logs', ([], {}), '()\n', (1480, 1482), False, 'from cepbp.common.logs import Logs\n'... |
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import numpy.testing as npt
import pytest
import freud
matplotlib.use("agg")
class TestGaussianDensity:
def test_random_point_with_cell_list(self):
fftpack = pytest.importorskip("scipy.fftpack")
fft = fftpack.fft
fftshi... | [
"numpy.prod",
"numpy.random.rand",
"freud.data.make_random_system",
"matplotlib.use",
"numpy.conj",
"numpy.max",
"freud.box.Box.cube",
"matplotlib.pyplot.close",
"numpy.sum",
"pytest.importorskip",
"pytest.raises",
"numpy.array",
"freud.density.GaussianDensity"
] | [((126, 147), 'matplotlib.use', 'matplotlib.use', (['"""agg"""'], {}), "('agg')\n", (140, 147), False, 'import matplotlib\n'), ((243, 279), 'pytest.importorskip', 'pytest.importorskip', (['"""scipy.fftpack"""'], {}), "('scipy.fftpack')\n", (262, 279), False, 'import pytest\n'), ((483, 545), 'freud.data.make_random_syst... |
import sys
import pdb
import argparse
import pickle
import torch
import plotly.graph_objs as go
sys.path.append("../src")
def main(argv):
parser = argparse.ArgumentParser()
parser.add_argument("estNumber", help="Estimation number", type=int)
parser.add_argument("nSamples", help="Number of samples to plot"... | [
"argparse.ArgumentParser",
"pickle.load",
"pdb.set_trace",
"plotly.graph_objs.Figure",
"sys.path.append",
"torch.arange"
] | [((97, 122), 'sys.path.append', 'sys.path.append', (['"""../src"""'], {}), "('../src')\n", (112, 122), False, 'import sys\n'), ((153, 178), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (176, 178), False, 'import argparse\n'), ((1853, 1940), 'torch.arange', 'torch.arange', ([], {'start': 'star... |
from PIL import Image
import os
def resizeImages(browserName):
try:
path = 'build/reports/geb/'+browserName
for filename in os.listdir(path):
if filename.endswith('.png'):
im = Image.open(path+"/"+filename)
size =im.size # get the size of the input image
ratio = 0.4 # reduced... | [
"os.listdir",
"PIL.Image.open"
] | [((135, 151), 'os.listdir', 'os.listdir', (['path'], {}), '(path)\n', (145, 151), False, 'import os\n'), ((796, 812), 'os.listdir', 'os.listdir', (['path'], {}), '(path)\n', (806, 812), False, 'import os\n'), ((202, 235), 'PIL.Image.open', 'Image.open', (["(path + '/' + filename)"], {}), "(path + '/' + filename)\n", (2... |
import numpy as np
import os
os.chdir('C:/Users/DELL/Desktop/Luis/Pset2')
import matplotlib.pyplot as plt
import K_S_Labor_Q3 as ks
ks1 = ks.K_S(N_k = 50)
V_Mat, gk_Mat, gn_Mat, pos_k_Mat, pos_n_Mat = ks1.Start_VFI()
f, (ax1, ax2) = plt.subplots(1,2)
f.set_figheight(5)
f.set_figwidth(10)
ax1.plot(ks1.grid... | [
"os.chdir",
"matplotlib.pyplot.subplots",
"K_S_Labor_Q3.K_S"
] | [((31, 75), 'os.chdir', 'os.chdir', (['"""C:/Users/DELL/Desktop/Luis/Pset2"""'], {}), "('C:/Users/DELL/Desktop/Luis/Pset2')\n", (39, 75), False, 'import os\n'), ((145, 159), 'K_S_Labor_Q3.K_S', 'ks.K_S', ([], {'N_k': '(50)'}), '(N_k=50)\n', (151, 159), True, 'import K_S_Labor_Q3 as ks\n'), ((244, 262), 'matplotlib.pypl... |
import numpy as np
import os
import warnings
from Input import Input
class InputFromData(Input):
"""
Used to draw random samples from a data file.
"""
def __init__(self, input_filename, delimiter=" ", skip_header=0,
shuffle_data=True):
"""
:param input_filename: path ... | [
"numpy.copy",
"os.path.isfile",
"numpy.isnan",
"warnings.warn",
"numpy.genfromtxt",
"numpy.random.shuffle"
] | [((975, 1050), 'numpy.genfromtxt', 'np.genfromtxt', (['input_filename'], {'delimiter': 'delimiter', 'skip_header': 'skip_header'}), '(input_filename, delimiter=delimiter, skip_header=skip_header)\n', (988, 1050), True, 'import numpy as np\n'), ((2896, 2911), 'numpy.copy', 'np.copy', (['sample'], {}), '(sample)\n', (290... |
'''
Created on Nov 29, 2020
@author: manik
'''
import numpy as np
import src.person_properties_util as idx
class Movement():
"""
Class providing abstraction into each movement of the population
"""
def update_persons(self, persons: np.ndarray, size: int,
speed: float = 0.1,
... | [
"numpy.random.random",
"numpy.clip",
"numpy.random.normal"
] | [((1288, 1318), 'numpy.random.random', 'np.random.random', ([], {'size': '(size,)'}), '(size=(size,))\n', (1304, 1318), True, 'import numpy as np\n'), ((1643, 1689), 'numpy.random.normal', 'np.random.normal', ([], {'loc': '(0)', 'scale': '(1 / 3)', 'size': 'shp'}), '(loc=0, scale=1 / 3, size=shp)\n', (1659, 1689), True... |
"""
This file contains tests for the update_health_rating view function.
It uses the mock library to mock out some of the messaging that happens
with Twitter, instead of interacting it Twitter it uses mock or fake data.
"""
import json
import mock
from django.test import TestCase
from django.test.client import Client... | [
"twython.TwythonError",
"mock.patch",
"json.loads",
"django.test.client.Client",
"django.test.client.RequestFactory"
] | [((1316, 1391), 'mock.patch', 'mock.patch', (['"""tweethealth.views._get_twitter_data"""', 'fake_twitter_zero_health'], {}), "('tweethealth.views._get_twitter_data', fake_twitter_zero_health)\n", (1326, 1391), False, 'import mock\n'), ((1873, 1959), 'mock.patch', 'mock.patch', (['"""tweethealth.views._get_twitter_data"... |
import treelib
# 来自[What is the most efficient way to get all nodes in a certain depth · Issue \#147 · caesar0301/treelib](https://github.com/caesar0301/treelib/issues/147)
# 只是主要代码的样例
def level_traverse():
crush_tree = treelib.Tree()
for i in range(crush_tree.depth(), -1, -1):
print(list(crush_tre... | [
"treelib.Tree"
] | [((229, 243), 'treelib.Tree', 'treelib.Tree', ([], {}), '()\n', (241, 243), False, 'import treelib\n')] |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import logging
BATCH_NORM_DECAY = 0.9
BATCH_NORM_EPSILON = 1e-5
def batch_norm_relu(inputs, is_training, relu=True, init_zero=False,
data_format='channels_last'):
... | [
"tensorflow.device",
"tensorflow.nn.relu",
"tensorflow.truncated_normal_initializer",
"tensorflow.ones_initializer",
"tensorflow.constant_initializer",
"tensorflow.layers.batch_normalization",
"tensorflow.zeros_initializer",
"tensorflow.identity",
"logging.info"
] | [((609, 824), 'tensorflow.layers.batch_normalization', 'tf.layers.batch_normalization', ([], {'inputs': 'inputs', 'axis': 'axis', 'momentum': 'BATCH_NORM_DECAY', 'epsilon': 'BATCH_NORM_EPSILON', 'center': '(True)', 'scale': '(True)', 'training': 'is_training', 'fused': '(True)', 'gamma_initializer': 'gamma_initializer'... |
#!/usr/bin/python
import time, sys
import RPi.GPIO as GPIO
redPin = 12 #Set to appropriate GPIO
greenPin = 19 #Should be set in the
bluePin = 6 #GPIO.BOARD format
def turnOn(pin):
GPIO.setmode(GPIO.BCM)
GPIO.setup(pin, GPIO.OUT)
GPIO.output(pin, GPIO.HIGH)
def turnOff(pin):
GPIO.setmode(GPIO.... | [
"RPi.GPIO.setup",
"RPi.GPIO.cleanup",
"RPi.GPIO.output",
"RPi.GPIO.setmode"
] | [((190, 212), 'RPi.GPIO.setmode', 'GPIO.setmode', (['GPIO.BCM'], {}), '(GPIO.BCM)\n', (202, 212), True, 'import RPi.GPIO as GPIO\n'), ((217, 242), 'RPi.GPIO.setup', 'GPIO.setup', (['pin', 'GPIO.OUT'], {}), '(pin, GPIO.OUT)\n', (227, 242), True, 'import RPi.GPIO as GPIO\n'), ((247, 274), 'RPi.GPIO.output', 'GPIO.output'... |
import numpy as np
import sympy as sp
from devitoboundary.symbolics.symbols import a, n, n_max
def standard_stencil(deriv, space_order, offset=0., as_float=True):
"""
Generate a stencil expression with standard weightings. Offset can be
applied to this stencil to evaluate at non-node positions.
Param... | [
"sympy.Sum",
"sympy.symbols",
"numpy.array",
"sympy.finite_diff_weights",
"sympy.diff"
] | [((1516, 1536), 'sympy.symbols', 'sp.symbols', (['"""x_poly"""'], {}), "('x_poly')\n", (1526, 1536), True, 'import sympy as sp\n'), ((1554, 1595), 'sympy.Sum', 'sp.Sum', (['(a[n] * x_poly ** n)', '(n, 0, n_max)'], {}), '(a[n] * x_poly ** n, (n, 0, n_max))\n', (1560, 1595), True, 'import sympy as sp\n'), ((1026, 1065), ... |
"""
Contains utility funcion to work with falcon POST data requests.
"""
import json
import falcon
def req_to_dict(req):
"""Exctract POST request params as a json."""
try:
raw_json = req.stream.read()
except Exception as ex:
raise falcon.HTTPError(falcon.HTTP_400, 'Error', ex.message)
... | [
"falcon.HTTPError",
"json.loads"
] | [((351, 389), 'json.loads', 'json.loads', (['raw_json'], {'encoding': '"""utf-8"""'}), "(raw_json, encoding='utf-8')\n", (361, 389), False, 'import json\n'), ((264, 318), 'falcon.HTTPError', 'falcon.HTTPError', (['falcon.HTTP_400', '"""Error"""', 'ex.message'], {}), "(falcon.HTTP_400, 'Error', ex.message)\n", (280, 318... |
"""
Management of a Member's Profiles
"""
# stdlib
from datetime import datetime
# libs
from cloudcix_rest.exceptions import Http400, Http404
from cloudcix_rest.views import APIView
from django.conf import settings
from rest_framework import status
from rest_framework.request import Request
from rest_framework.respons... | [
"membership.models.Profile.objects.get",
"membership.serializers.ProfileSerializer",
"membership.controllers.ProfileUpdateController",
"membership.controllers.ProfileListController",
"membership.permissions.profile.Permissions.delete",
"membership.permissions.profile.Permissions.update",
"membership.per... | [((2671, 2721), 'rest_framework.response.Response', 'Response', (["{'content': data, '_metadata': metadata}"], {}), "({'content': data, '_metadata': metadata})\n", (2679, 2721), False, 'from rest_framework.response import Response\n'), ((4024, 4083), 'rest_framework.response.Response', 'Response', (["{'content': data}"... |
# -*- encoding: utf-8 -*-
'''
The model module.
'''
# General imports
import ntpath
import copy
# Custom imports
import sample.model.utils as utils
from sample.model.canvas_model import CanvasModel
from sample.model.parser import Parser
from sample.model.algorithms import FreeComet, OpenComet
from sample.model.a... | [
"ntpath.basename",
"sample.model.algorithms.OpenComet",
"sample.model.canvas_model.CanvasModel",
"sample.model.parser.Parser.write",
"copy.deepcopy",
"sample.model.comet.Comet",
"sample.model.parser.Parser.read",
"sample.model.algorithm_settings.AlgorithmSettings"
] | [((1302, 1321), 'sample.model.algorithm_settings.AlgorithmSettings', 'AlgorithmSettings', ([], {}), '()\n', (1319, 1321), False, 'from sample.model.algorithm_settings import AlgorithmSettings\n'), ((1372, 1385), 'sample.model.canvas_model.CanvasModel', 'CanvasModel', ([], {}), '()\n', (1383, 1385), False, 'from sample.... |
"""
生成密钥
"""
from random import randint
from protocol.utils.read_config import get_config
from protocol.utils import long_to_bytes
import hashlib
def is_prime(num, test_count):
"""判断是否为质数(试test_count以内的数来判断)"""
if num == 1:
return False
if test_count >= num:
test_count = num - 1
for x i... | [
"protocol.utils.long_to_bytes",
"random.randint",
"protocol.utils.read_config.get_config"
] | [((652, 664), 'protocol.utils.read_config.get_config', 'get_config', ([], {}), '()\n', (662, 664), False, 'from protocol.utils.read_config import get_config\n'), ((355, 374), 'random.randint', 'randint', (['(1)', '(num - 1)'], {}), '(1, num - 1)\n', (362, 374), False, 'from random import randint\n'), ((567, 596), 'rand... |
#!/usr/bin/env python
# coding=utf-8
'''
@Author: wjm
@Date: 2019-10-13 23:07:03
@LastEditTime: 2020-07-13 16:45:30
@Description: file content
'''
import os, torch, time
from utils.utils import draw_curve_and_save, save_config
from data.dataset import data
from data.data import get_data
from torch.utils.data import Da... | [
"os.path.exists",
"torch.load",
"time.time",
"os.makedirs"
] | [((901, 927), 'os.path.exists', 'os.path.exists', (['model_path'], {}), '(model_path)\n', (915, 927), False, 'import os, torch, time\n'), ((539, 550), 'time.time', 'time.time', ([], {}), '()\n', (548, 550), False, 'import os, torch, time\n'), ((764, 799), 'os.path.exists', 'os.path.exists', (['self.checkpoint_dir'], {}... |
from django.db import models
from django.core.exceptions import ValidationError
from django.utils.text import slugify
from django.utils.translation import gettext_lazy as _
import os
from ecommerce.utils import BaseModel
from accounts.models import User
from store.managers import CategoryManager, TagManager
class St... | [
"django.db.models.EmailField",
"django.utils.text.slugify",
"django.db.models.TextField",
"os.getenv",
"django.db.models.ForeignKey",
"django.db.models.ManyToManyField",
"django.core.exceptions.ValidationError",
"accounts.models.User.objects.values_list",
"django.db.models.SlugField",
"store.manag... | [((348, 393), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(255)', 'blank': '(False)'}), '(max_length=255, blank=False)\n', (364, 393), False, 'from django.db import models\n'), ((406, 455), 'django.db.models.ForeignKey', 'models.ForeignKey', (['User'], {'on_delete': 'models.CASCADE'}), '(User... |
# -*- coding: utf-8 -*-
import re
from django import VERSION
from django.utils import six
from django.utils.safestring import mark_safe
def add_meta_class(field):
if VERSION < (1, 8):
from django.db.models import SubfieldBase
return six.add_metaclass(SubfieldBase)(field)
return field
def w... | [
"django.utils.six.add_metaclass",
"django.utils.safestring.mark_safe",
"re.compile"
] | [((497, 516), 'django.utils.safestring.mark_safe', 'mark_safe', (['rendered'], {}), '(rendered)\n', (506, 516), False, 'from django.utils.safestring import mark_safe\n'), ((257, 288), 'django.utils.six.add_metaclass', 'six.add_metaclass', (['SubfieldBase'], {}), '(SubfieldBase)\n', (274, 288), False, 'from django.utils... |
# Generated by Django 2.0.4 on 2018-04-22 13:58
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='CouncilMember',
fields=[
... | [
"django.db.models.EmailField",
"django.db.models.DateField",
"django.db.models.IntegerField",
"django.db.models.ForeignKey",
"django.db.models.AutoField",
"django.db.models.DecimalField",
"django.db.models.CharField"
] | [((2833, 2951), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'on_delete': 'django.db.models.deletion.CASCADE', 'related_name': '"""council_member"""', 'to': '"""core.District"""'}), "(on_delete=django.db.models.deletion.CASCADE, related_name\n ='council_member', to='core.District')\n", (2850, 2951), Fal... |
from quantity_field import ureg
# Set up some celestial units
ureg.define('solar_mass = 1988500000000000000000000000000 * kg = M☉')
ureg.define('solar_luminosity = 382800000000000000000000000 * watt = L☉')
ureg.define('solar_radius = 695700 * km = R☉')
ureg.define('solar_surface_temperature = 5772 * K = T☉')
ureg.def... | [
"quantity_field.ureg.define"
] | [((64, 133), 'quantity_field.ureg.define', 'ureg.define', (['"""solar_mass = 1988500000000000000000000000000 * kg = M☉"""'], {}), "('solar_mass = 1988500000000000000000000000000 * kg = M☉')\n", (75, 133), False, 'from quantity_field import ureg\n'), ((134, 207), 'quantity_field.ureg.define', 'ureg.define', (['"""solar_... |
# -*- coding: utf-8 -*-
__author__ = 'lundberg'
from django.db import IntegrityError, transaction
from django.core.exceptions import ObjectDoesNotExist
from django.utils.text import slugify
from django.conf import settings
from .models import NordunetUniqueId, UniqueIdGenerator
def unique_id_map(slug):
"""
:... | [
"django.db.IntegrityError",
"django.conf.settings.BRAND.title",
"django.db.transaction.atomic"
] | [((2456, 2522), 'django.db.IntegrityError', 'IntegrityError', (["('ID: %s already in the db and in use.' % unique_id)"], {}), "('ID: %s already in the db and in use.' % unique_id)\n", (2470, 2522), False, 'from django.db import IntegrityError, transaction\n'), ((881, 903), 'django.conf.settings.BRAND.title', 'settings.... |
import json
import pytest
import simdjson
def with_buffer(content):
import numpy
parser = simdjson.Parser()
doc = parser.parse(content)
assert len(numpy.frombuffer(doc.as_buffer(of_type='d'))) == 10001
def without_buffer(content):
import numpy
parser = simdjson.Parser()
doc = parser.... | [
"pytest.mark.parametrize",
"json.loads",
"orjson.loads",
"simdjson.Parser"
] | [((636, 731), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""loader"""', '[with_buffer, without_buffer, with_builtin, with_orjson]'], {}), "('loader', [with_buffer, without_buffer,\n with_builtin, with_orjson])\n", (659, 731), False, 'import pytest\n'), ((103, 120), 'simdjson.Parser', 'simdjson.Parser',... |
from sequana.rnadiff import RNADiffResults, RNADiffAnalysis, RNADesign
from . import test_dir
import pytest
def test_design():
d = RNADesign(f"{test_dir}/data/rnadiff/design.csv")
assert d.comparisons == [('Complemented_csrA', 'Mut_csrA'), ('Complemented_csrA', 'WT'), ('Mut_csrA', 'WT')]
assert d.conditi... | [
"pytest.mark.xfail",
"sequana.rnadiff.RNADesign",
"sequana.rnadiff.RNADiffAnalysis"
] | [((592, 651), 'pytest.mark.xfail', 'pytest.mark.xfail', ([], {'reason': '"""too slow or service may be down"""'}), "(reason='too slow or service may be down')\n", (609, 651), False, 'import pytest\n'), ((136, 184), 'sequana.rnadiff.RNADesign', 'RNADesign', (['f"""{test_dir}/data/rnadiff/design.csv"""'], {}), "(f'{test_... |
# Copyright (c) 2020.
import datetime
from csv import writer
from api_connectors import firebase_connector
from models.traffic_estimation_model import Estimacion
from serializators.traffic_estimation_serializator import TrafficEstimation
def export_traffic_estimation(ts: TrafficEstimation):
update... | [
"datetime.datetime",
"api_connectors.firebase_connector.post_estimacion_trafico",
"datetime.datetime.strptime",
"models.traffic_estimation_model.Estimacion",
"csv.writer"
] | [((3048, 3116), 'api_connectors.firebase_connector.post_estimacion_trafico', 'firebase_connector.post_estimacion_trafico', (['estimation_array', 'update'], {}), '(estimation_array, update)\n', (3090, 3116), False, 'from api_connectors import firebase_connector\n'), ((4144, 4201), 'datetime.datetime.strptime', 'datetime... |
import re
from ..exo_classes.exo_classes import BuiltInFunction, Number
from ..exo_classes.exo_context import Context
from ..exo_utils.exo_interpreter import Interpreter, SymbolTable
from ..exo_utils.exo_lexer import Lexer
from ..exo_utils.exo_parser import Parser
global_symbol_table = SymbolTable()
global_symbol_tab... | [
"re.sub"
] | [((824, 849), 're.sub', 're.sub', (['regexpr', '""""""', 'text'], {}), "(regexpr, '', text)\n", (830, 849), False, 'import re\n')] |
import nose
from melano.diff import (json_diff, list_diff)
def test_diff_json_simple_equal():
errors = json_diff(x=dict(x=1, y=2, z=3), y=dict(x=1, y=2, z=3))
nose.tools.assert_equal(len(errors), 0)
def test_diff_json_simple_not_equal():
errors = json_diff(x=dict(a=1, b=1, c=3), y=dict(a=1, b=2, c=3))
... | [
"melano.diff.json_diff",
"nose.tools.assert_equal",
"melano.diff.list_diff"
] | [((367, 421), 'nose.tools.assert_equal', 'nose.tools.assert_equal', (["errors[0]['type']", '"""MISMATCH"""'], {}), "(errors[0]['type'], 'MISMATCH')\n", (390, 421), False, 'import nose\n'), ((426, 474), 'nose.tools.assert_equal', 'nose.tools.assert_equal', (["errors[0]['field']", '"""b"""'], {}), "(errors[0]['field'], '... |
import socket
import sys
TEMPLATE_404 = 'templates/404.html'
if __name__ == '__main__':
if len(sys.argv) < 2:
sys.stderr.write('Usage: python server.py <port>\n')
exit(-1)
port = int(sys.argv[1])
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '0.0.0.0'
try:
... | [
"sys.stderr.write",
"socket.socket"
] | [((232, 281), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (245, 281), False, 'import socket\n'), ((465, 524), 'sys.stderr.write', 'sys.stderr.write', (["('Server is Up and Running on %d\\n' % port)"], {}), "('Server is Up and Running on %d\... |
#!/usr/bin/env python
# coding: utf-8
# In[11]:
import pandas as pd
import numpy as np
import glob,os
from glob import iglob
#import scanpy as sc
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import RocCurveDisplay
from sklearn.datasets import load_wine
from skl... | [
"pandas.read_csv",
"matplotlib.pyplot.ylabel",
"sklearn.model_selection.StratifiedKFold",
"numpy.mean",
"numpy.delete",
"matplotlib.pyplot.xlabel",
"pandas.DataFrame",
"sklearn.model_selection.cross_val_score",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.gca",
"... | [((1084, 1152), 'pandas.read_csv', 'pd.read_csv', (['"""./combined_gene_for_machine_learning.csv"""'], {'index_col': '(1)'}), "('./combined_gene_for_machine_learning.csv', index_col=1)\n", (1095, 1152), True, 'import pandas as pd\n'), ((1161, 1204), 'numpy.append', 'np.append', (['features.index.values', '"""patient"""... |
"""
Operator to fit features to target columns using sklearn's linear regression
"""
import numpy as np
from sklearn.linear_model import LinearRegression, LogisticRegression
from tasrif.processing_pipeline import ProcessingOperator
class LinearFitOperator(ProcessingOperator):
"""
Operator to fit features to... | [
"sklearn.linear_model.LinearRegression",
"sklearn.linear_model.LogisticRegression"
] | [((2752, 2789), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {}), '(**self.model_kwargs)\n', (2768, 2789), False, 'from sklearn.linear_model import LinearRegression, LogisticRegression\n'), ((2829, 2868), 'sklearn.linear_model.LogisticRegression', 'LogisticRegression', ([], {}), '(**self.model_kwar... |
from django.shortcuts import render
from core.models import Evento
# Create your views here.
def lista_eventos(request):
evento = Evento.objects.all()
dados = {'evento' : evento}
return render(request,'agenda.html', dados) | [
"django.shortcuts.render",
"core.models.Evento.objects.all"
] | [((136, 156), 'core.models.Evento.objects.all', 'Evento.objects.all', ([], {}), '()\n', (154, 156), False, 'from core.models import Evento\n'), ((200, 237), 'django.shortcuts.render', 'render', (['request', '"""agenda.html"""', 'dados'], {}), "(request, 'agenda.html', dados)\n", (206, 237), False, 'from django.shortcut... |
# Generated by Django 3.1 on 2020-09-09 08:54
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('portfolio', '0009_auto_20200909_2053'),
]
operations = [
migrations.RenameField(
model_name='project',
old_name='featured',
... | [
"django.db.migrations.RenameField"
] | [((227, 314), 'django.db.migrations.RenameField', 'migrations.RenameField', ([], {'model_name': '"""project"""', 'old_name': '"""featured"""', 'new_name': '"""show"""'}), "(model_name='project', old_name='featured', new_name=\n 'show')\n", (249, 314), False, 'from django.db import migrations\n')] |
import json
import os
import requests
from beeswax_api.models.SegmentUpload import SegmentUpload
from beeswax_api.Exceptions import LoginException, SegmentUploadException
class Session(requests.Session):
_url_ = ""
def url(self, path):
return self._url_ + path
def login(self, _url, auth_data):
... | [
"beeswax_api.Exceptions.LoginException",
"json.dumps",
"beeswax_api.models.SegmentUpload.SegmentUpload.from_file",
"beeswax_api.Exceptions.SegmentUploadException",
"os.path.basename"
] | [((643, 673), 'beeswax_api.models.SegmentUpload.SegmentUpload.from_file', 'SegmentUpload.from_file', (['sfile'], {}), '(sfile)\n', (666, 673), False, 'from beeswax_api.models.SegmentUpload import SegmentUpload\n'), ((1065, 1088), 'os.path.basename', 'os.path.basename', (['sfile'], {}), '(sfile)\n', (1081, 1088), False,... |
import collections
import edera.helpers
from edera.monitoring import MonitoringSnapshot
from edera.monitoring.snapshot import MonitoringSnapshotCore
from edera.monitoring.snapshot import TaskLogUpdate
from edera.monitoring.snapshot import TaskPayload
from edera.monitoring.snapshot import TaskState
from edera.monitori... | [
"edera.monitoring.snapshot.TaskPayload",
"edera.monitoring.snapshot.TaskStatusUpdate",
"edera.monitoring.snapshot.TaskState",
"edera.monitoring.snapshot.TaskLogUpdate",
"edera.monitoring.snapshot.MonitoringSnapshotCore",
"edera.monitoring.MonitoringSnapshot.void",
"edera.monitoring.snapshot.WorkflowUpda... | [((468, 482), 'edera.monitoring.snapshot.TaskState', 'TaskState', (['"""T"""'], {}), "('T')\n", (477, 482), False, 'from edera.monitoring.snapshot import TaskState\n'), ((1018, 1032), 'edera.monitoring.snapshot.TaskState', 'TaskState', (['"""T"""'], {}), "('T')\n", (1027, 1032), False, 'from edera.monitoring.snapshot i... |
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.core import util
from telemetry.value import histogram
from telemetry.value import histogram_util
from measurements import startup
from metri... | [
"telemetry.value.histogram.HistogramValue",
"telemetry.value.histogram_util.GetHistogram",
"telemetry.value.histogram_util.CustomizeBrowserOptions",
"metrics.cpu.CpuMetric",
"telemetry.value.histogram_util.GetHistogramCount"
] | [((1141, 1188), 'telemetry.value.histogram_util.CustomizeBrowserOptions', 'histogram_util.CustomizeBrowserOptions', (['options'], {}), '(options)\n', (1179, 1188), False, 'from telemetry.value import histogram_util\n'), ((2005, 2027), 'metrics.cpu.CpuMetric', 'cpu.CpuMetric', (['browser'], {}), '(browser)\n', (2018, 20... |
import os
import cv2
import torch
import numpy as np
import torchvision
from tqdm import tqdm
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
class Args:
checkpoints_dir = '/path/to/checkpoints/dir'
# FOR BDD
dataroot = '/path/to/data/BDD100k/'
segmentation_network_name = '... | [
"torchvision.models.segmentation.deeplabv3_resnet101",
"os.path.exists",
"numpy.where",
"tqdm.tqdm",
"os.path.join",
"torch.cuda.is_available",
"os.mkdir",
"torch.utils.data.DataLoader"
] | [((1929, 2029), 'torchvision.models.segmentation.deeplabv3_resnet101', 'torchvision.models.segmentation.deeplabv3_resnet101', ([], {'pretrained': '(False)', 'num_classes': 'opt.n_classes'}), '(pretrained=False,\n num_classes=opt.n_classes)\n', (1980, 2029), False, 'import torchvision\n'), ((2527, 2547), 'tqdm.tqdm',... |
import matplotlib.pyplot as plt
import time as time
from test import *
from ann import *
from data import *
np.random.seed(499)
print('Simple method Tests\n')
test_affine_forward()
test_affine_backward()
test_relu_forward()
test_relu_backward()
test_L2_loss()
test_ANN_predict()
# Initial parameters
node_num = 30
in... | [
"matplotlib.pyplot.title",
"time.time",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.show"
] | [((590, 601), 'time.time', 'time.time', ([], {}), '()\n', (599, 601), True, 'import time as time\n'), ((5061, 5072), 'time.time', 'time.time', ([], {}), '()\n', (5070, 5072), True, 'import time as time\n'), ((710, 721), 'time.time', 'time.time', ([], {}), '()\n', (719, 721), True, 'import time as time\n'), ((4901, 4912... |
#!/usr/bin/env python
import csv
import rospy
import math
import tf
import numpy as np
import time
from tf import TransformListener
from geometry_msgs.msg import PoseStamped
class Swarm():
def __init__(self):
rospy.init_node('demo', anonymous=True)
self.worldFrame = rospy.get_param("~worldFrame", "... | [
"tf.transformations.euler_from_quaternion",
"rospy.is_shutdown",
"rospy.init_node",
"rospy.get_param",
"rospy.Time.now",
"rospy.Time",
"geometry_msgs.msg.PoseStamped",
"tf.TransformListener",
"tf.transformations.quaternion_from_euler",
"rospy.Duration",
"rospy.sleep",
"rospy.Publisher",
"csv... | [((222, 261), 'rospy.init_node', 'rospy.init_node', (['"""demo"""'], {'anonymous': '(True)'}), "('demo', anonymous=True)\n", (237, 261), False, 'import rospy\n'), ((288, 328), 'rospy.get_param', 'rospy.get_param', (['"""~worldFrame"""', '"""/world"""'], {}), "('~worldFrame', '/world')\n", (303, 328), False, 'import ros... |
# -*- coding: utf-8 -*-
import scrapy
import time
import pandas as pd
from scrapy import Selector
from scrapy_selenium import SeleniumRequest
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
class Libpr... | [
"scrapy.Selector",
"scrapy_selenium.SeleniumRequest",
"selenium.webdriver.support.ui.WebDriverWait",
"time.sleep",
"pandas.read_excel",
"selenium.webdriver.support.expected_conditions.visibility_of_element_located"
] | [((378, 497), 'pandas.read_excel', 'pd.read_excel', (['"""D:/Web-Scrapping/UpWork_Projects/andy_upwork/lightinthebox/links_new.xlsx"""'], {'sheet_name': '"""urls"""'}), "(\n 'D:/Web-Scrapping/UpWork_Projects/andy_upwork/lightinthebox/links_new.xlsx'\n , sheet_name='urls')\n", (391, 497), True, 'import pandas as p... |
from django.conf import settings
from django.http import HttpResponseRedirect
DEFAULT_REDIRECT_URL = getattr(settings, 'DEFAULT_REDIRECT_URL', 'http://www.cut.com:8000')
def wildcard_redirect(request, path=None):
new_url = DEFAULT_REDIRECT_URL
if path is not None and path != '':
new_url = DEFAULT_RED... | [
"django.http.HttpResponseRedirect"
] | [((354, 383), 'django.http.HttpResponseRedirect', 'HttpResponseRedirect', (['new_url'], {}), '(new_url)\n', (374, 383), False, 'from django.http import HttpResponseRedirect\n')] |
from numpy.core.fromnumeric import take
from gi.repository import Gtk, GLib, Gio
from matplotlib.backends.backend_gtk3agg import (
FigureCanvasGTK3Agg as FigureCanvas)
from matplotlib.figure import Figure
import numpy as np
import time
import threading
import serial
# from pyfirmata import Arduino, util
from steppe... | [
"gi.repository.Gtk.FileFilter",
"stepper.StepperMotor",
"sys.platform.startswith",
"time.sleep",
"numpy.array",
"numpy.sin",
"gi.repository.Gtk.Button.new_with_label",
"numpy.arange",
"gi.repository.GLib.idle_add",
"gi.repository.Gtk.Paned.new",
"gi.repository.Gtk.Label.new",
"glob.glob",
"g... | [((375, 407), 'gi.require_version', 'gi.require_version', (['"""Gtk"""', '"""3.0"""'], {}), "('Gtk', '3.0')\n", (393, 407), False, 'import gi\n'), ((750, 791), 'gi.repository.Gtk.Paned.new', 'Gtk.Paned.new', (['Gtk.Orientation.HORIZONTAL'], {}), '(Gtk.Orientation.HORIZONTAL)\n', (763, 791), False, 'from gi.repository i... |
"""
SetupTrac2Mite:
plugin to enable the environment for Trac2mite.
This plugin must be initialized prior to using Trac2mite
Modified version of plugin SetupTracHoursPlugin
"""
from trac.core import *
from trac.db import Table, Column, Index, DatabaseManager
from trac.env import IEnvironmentSetupParticipant
from tra... | [
"trac.db.Column",
"trac.db.Table"
] | [((2245, 2277), 'trac.db.Table', 'Table', (['"""mite_bindings"""'], {'key': '"""id"""'}), "('mite_bindings', key='id')\n", (2250, 2277), False, 'from trac.db import Table, Column, Index, DatabaseManager\n'), ((2529, 2558), 'trac.db.Table', 'Table', (['"""mite_rsrcs"""'], {'key': '"""id"""'}), "('mite_rsrcs', key='id')\... |
import unittest
import uuid
import py3crdt
from py3crdt.orset import ORSet
class TestORSet(unittest.TestCase):
def setUp(self):
# Create a ORSet
self.orset1 = ORSet(uuid.uuid4())
# Create another ORSet
self.orset2 = ORSet(uuid.uuid4())
# Add elements to orset1
sel... | [
"unittest.main",
"uuid.uuid4"
] | [((6264, 6279), 'unittest.main', 'unittest.main', ([], {}), '()\n', (6277, 6279), False, 'import unittest\n'), ((187, 199), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (197, 199), False, 'import uuid\n'), ((261, 273), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (271, 273), False, 'import uuid\n'), ((338, 350), 'uui... |
from bluetooth_shower_head import bluetoothManager_head
from bluetooth_scale import bluetoothManager_scale
from influx_poster import database_post
import signal
import sys
import time
if __name__ == '__main__':
runtime = 480
try:
database_post("indicator", 1.0, "startstop").start()
print("instatiati... | [
"bluetooth_shower_head.bluetoothManager_head",
"bluetooth_scale.bluetoothManager_scale",
"influx_poster.database_post",
"time.sleep"
] | [((360, 383), 'bluetooth_shower_head.bluetoothManager_head', 'bluetoothManager_head', ([], {}), '()\n', (381, 383), False, 'from bluetooth_shower_head import bluetoothManager_head\n'), ((412, 436), 'bluetooth_scale.bluetoothManager_scale', 'bluetoothManager_scale', ([], {}), '()\n', (434, 436), False, 'from bluetooth_s... |
from transformers import LayoutLMForSequenceClassification, AdamW
import torch
from utils.dataloader import create_data
import os, json
def train(data_path, model_path, epochs, device=None):
if device is None:
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
(
tr... | [
"utils.dataloader.create_data",
"argparse.ArgumentParser",
"os.path.join",
"torch.cuda.is_available",
"json.dump"
] | [((490, 512), 'utils.dataloader.create_data', 'create_data', (['data_path'], {}), '(data_path)\n', (501, 512), False, 'from utils.dataloader import create_data\n'), ((4073, 4134), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Process some integers."""'}), "(description='Process some int... |
import os
from datetime import datetime
import discord
import yaml
# TODO: help RUTULIA
# self = discord.self()
from commands import Command
from connection import Connect
from player import Player
from settings import Settings
from utils import Error
""""
Settings for creating youtube stream
"""
ytdl_format_option... | [
"discord.opus.load_opus",
"connection.Connect",
"player.Player",
"discord.Game",
"commands.Command",
"yaml.load",
"os.path.isfile",
"datetime.datetime.now",
"settings.Settings",
"discord.opus.is_loaded",
"discord.Color.red"
] | [((2646, 2676), 'os.path.isfile', 'os.path.isfile', (['self.TokenFile'], {}), '(self.TokenFile)\n', (2660, 2676), False, 'import os\n'), ((3845, 3874), 'settings.Settings', 'Settings', (['self.SettingsFolder'], {}), '(self.SettingsFolder)\n', (3853, 3874), False, 'from settings import Settings\n'), ((3891, 3903), 'play... |
#!/usr/bin/env python3
from __future__ import print_function
import os
import sys
import urllib
import time
from ev3dev2.motor import LargeMotor, MediumMotor, OUTPUT_A, OUTPUT_B, OUTPUT_C, OUTPUT_D, SpeedPercent, MoveTank
from ev3dev2.display import Display
from ev3dev2.sensor import INPUT_1, INPUT_2, INPUT_3, INPUT_... | [
"ev3dev2.motor.MediumMotor",
"ev3dev2.sensor.lego.TouchSensor",
"ev3dev2.sensor.lego.UltrasonicSensor",
"ev3dev2.led.Leds",
"urllib.parse.urlparse",
"http.server.SimpleHTTPRequestHandler.do_GET",
"ev3dev2.display.Display",
"ev3dev2.button.Button",
"ev3dev2.motor.MoveTank",
"urllib.parse.parse_qs",... | [((7780, 7814), 'http.server.HTTPServer', 'HTTPServer', (["('', port)", 'Ev3Handler'], {}), "(('', port), Ev3Handler)\n", (7790, 7814), False, 'from http.server import HTTPServer, SimpleHTTPRequestHandler\n'), ((6907, 6944), 'http.server.SimpleHTTPRequestHandler.do_GET', 'SimpleHTTPRequestHandler.do_GET', (['self'], {}... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division
from __future__ import print_function
import os
import io
import time
import numpy as np
import scipy.io as sio
from scipy import sparse as sp
from scipy import spatial
import cPickle as pkl
import networkx as nx
import rando... | [
"networkx.from_dict_of_lists",
"scipy.spatial.distance.cosine",
"cPickle.dump",
"scipy.sparse.vstack",
"numpy.sort",
"scipy.sparse.triu",
"numpy.floor",
"numpy.array",
"numpy.zeros",
"numpy.vstack",
"scipy.sparse.isspmatrix_coo",
"cPickle.load"
] | [((1112, 1135), 'numpy.sort', 'np.sort', (['degrees_sorted'], {}), '(degrees_sorted)\n', (1119, 1135), True, 'import numpy as np\n'), ((2524, 2535), 'numpy.zeros', 'np.zeros', (['l'], {}), '(l)\n', (2532, 2535), True, 'import numpy as np\n'), ((2567, 2596), 'numpy.array', 'np.array', (['mask'], {'dtype': 'np.bool'}), '... |
import unittest
import sys
import os.path
from os.path import exists, join
import json
import functools
import inspect
from utils_for_tests import SimpleCase, WS_DIR
try:
import tensorflow
TF_INSTALLED=True
if tensorflow.__version__.startswith('2.'):
TF_VERSION=2
else:
TF_VERSION=1
exc... | [
"pandas.read_csv",
"tensorflow.feature_column.indicator_column",
"numpy.array",
"tensorflow.keras.layers.Dense",
"unittest.main",
"tensorflow.cast",
"os.path.exists",
"tensorflow.keras.layers.DenseFeatures",
"inspect.isgenerator",
"tensorflow.stack",
"dataworkspaces.kits.tensorflow.CheckpointCon... | [((224, 263), 'tensorflow.__version__.startswith', 'tensorflow.__version__.startswith', (['"""2."""'], {}), "('2.')\n", (257, 263), False, 'import tensorflow\n'), ((1370, 1437), 'unittest.skipUnless', 'unittest.skipUnless', (['TF_INSTALLED', '"""SKIP: Tensorflow not available"""'], {}), "(TF_INSTALLED, 'SKIP: Tensorflo... |
import folium
import random
import pandas
import json
BaseMap = folium.Map(location=[40.76,-111.89],zoom_start=6, tiles="MapBox Bright")
PointSource = pandas.read_csv("Volcanoes_USA.txt")
LAT = list(PointSource["LAT"])
LON = list(PointSource["LON"])
VOLC_Names = list(PointSource["NAME"])
ELEV = list(PointSource["ELEV... | [
"json.loads",
"pandas.read_csv",
"folium.LayerControl",
"folium.Map",
"folium.FeatureGroup",
"folium.CircleMarker"
] | [((65, 139), 'folium.Map', 'folium.Map', ([], {'location': '[40.76, -111.89]', 'zoom_start': '(6)', 'tiles': '"""MapBox Bright"""'}), "(location=[40.76, -111.89], zoom_start=6, tiles='MapBox Bright')\n", (75, 139), False, 'import folium\n'), ((153, 189), 'pandas.read_csv', 'pandas.read_csv', (['"""Volcanoes_USA.txt"""'... |
from connection import api_client
username = 'something'
password = '<PASSWORD>'
carrier_id = '12356'
tnas_connection = api_client.TNASConnection(api_client.TNAS_TEST)
tnas_connection.login(username=username, password=password, carrier_id=carrier_id)
| [
"connection.api_client.TNASConnection"
] | [((122, 169), 'connection.api_client.TNASConnection', 'api_client.TNASConnection', (['api_client.TNAS_TEST'], {}), '(api_client.TNAS_TEST)\n', (147, 169), False, 'from connection import api_client\n')] |
import lingeling
p = lingeling.lglinit()
lingeling.lgladd(p, 1)
lingeling.lgladd(p, -1)
lingeling.lgladd(p, 0)
lingeling.lglassume(p, -1)
assert lingeling.lglsat(p) == lingeling.LGL_SATISFIABLE
print("Done.")
| [
"lingeling.lglsat",
"lingeling.lglinit",
"lingeling.lgladd",
"lingeling.lglassume"
] | [((22, 41), 'lingeling.lglinit', 'lingeling.lglinit', ([], {}), '()\n', (39, 41), False, 'import lingeling\n'), ((42, 64), 'lingeling.lgladd', 'lingeling.lgladd', (['p', '(1)'], {}), '(p, 1)\n', (58, 64), False, 'import lingeling\n'), ((65, 88), 'lingeling.lgladd', 'lingeling.lgladd', (['p', '(-1)'], {}), '(p, -1)\n', ... |
""" This file allows the user to monitor pages for changes"""
from datetime import datetime, timedelta
from threading import Thread, Event, Lock
from random import normalvariate
# from subprocess import run
import logging
import requests
# import page_comparators
class PageWatcher (Thread):
""" Watches a single p... | [
"random.normalvariate",
"threading.Lock",
"requests.get",
"threading.Event",
"datetime.datetime.now",
"logging.info"
] | [((1046, 1053), 'threading.Event', 'Event', ([], {}), '()\n', (1051, 1053), False, 'from threading import Thread, Event, Lock\n'), ((4726, 4740), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (4738, 4740), False, 'from datetime import datetime, timedelta\n'), ((5150, 5156), 'threading.Lock', 'Lock', ([], {... |
import gensim
from gensim.utils import simple_preprocess
from gensim.parsing.preprocessing import STOPWORDS
from nltk.stem import WordNetLemmatizer, SnowballStemmer
from nltk.stem.porter import *
import numpy as np
np.random.seed(400)
import nltk
nltk.download('wordnet')
import pandas as pd
data = pd.read_csv('abcnew... | [
"gensim.corpora.Dictionary",
"nltk.download",
"pandas.read_csv",
"gensim.models.LdaMulticore",
"numpy.random.seed",
"numpy.load",
"gensim.models.TfidfModel"
] | [((215, 234), 'numpy.random.seed', 'np.random.seed', (['(400)'], {}), '(400)\n', (229, 234), True, 'import numpy as np\n'), ((247, 271), 'nltk.download', 'nltk.download', (['"""wordnet"""'], {}), "('wordnet')\n", (260, 271), False, 'import nltk\n'), ((301, 360), 'pandas.read_csv', 'pd.read_csv', (['"""abcnews-date-text... |
import os
import io
import boto3
import mimetypes
s3_client = boto3.client(
"s3",
endpoint_url="https://ams3.digitaloceanspace.com",
aws_access_key_id=os.getenv("DO_SPACE_ACCESS"),
aws_secret_access_key=os.environ("DO_SPACE_SECRET"),
region_name="ams3",
)
def upload_video(local_path, path, bucket... | [
"mimetypes.guess_type",
"os.environ",
"os.getenv"
] | [((164, 192), 'os.getenv', 'os.getenv', (['"""DO_SPACE_ACCESS"""'], {}), "('DO_SPACE_ACCESS')\n", (173, 192), False, 'import os\n'), ((220, 249), 'os.environ', 'os.environ', (['"""DO_SPACE_SECRET"""'], {}), "('DO_SPACE_SECRET')\n", (230, 249), False, 'import os\n'), ((460, 492), 'mimetypes.guess_type', 'mimetypes.guess... |
#!/usr/bin/env python3
#####################################
#
# Filename : test_Superimposer.py
#
# Projectname : diSTruct
#
# Author : <NAME>
#
# Creation Date : Fri 18 May 2018 06:28:53 PM CEST
#
# Last Modified : Fri 29 Mar 2019 04:12:22 PM CET
#
#####################################
import numpy as np
from pytes... | [
"pytest.approx",
"distruct.tools.pdb.get_contacts",
"Bio.PDB.PDBParser",
"distruct.Superimposer",
"numpy.array",
"Bio.SeqIO.parse",
"Bio.PDB.Superimposer"
] | [((554, 663), 'numpy.array', 'np.array', (['[[51.65, -1.9, 50.07], [50.4, -1.23, 50.65], [50.68, -0.04, 51.54], [50.22,\n -0.02, 52.85]]', '"""f"""'], {}), "([[51.65, -1.9, 50.07], [50.4, -1.23, 50.65], [50.68, -0.04, 51.54],\n [50.22, -0.02, 52.85]], 'f')\n", (562, 663), True, 'import numpy as np\n'), ((698, 807... |
import argparse
import logging
import os
import numpy as np
import torch.cuda
import torch.nn as nn
from torch.utils.data import DataLoader
from torch.autograd import Variable
import torch.backends.cudnn as cudnn
cudnn.benchmark = True
from utils.iam_loader import IAMLoader
from config import *
from m... | [
"logging.basicConfig",
"logging.getLogger",
"utils.iam_loader.IAMLoader",
"torch.nn.functional.ctc_loss",
"argparse.ArgumentParser",
"numpy.concatenate",
"torch.utils.data.DataLoader",
"torch.nn.functional.log_softmax",
"utils.auxilary_functions.affine_transformation",
"valid_deforms.uncertainty_r... | [((519, 658), '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=logging.I... |
# -*- coding:utf-8 -*-
'''
Created on 2016.05.10
@author: davidpower
'''
import os, sys
import maya.cmds as cmds
import maya.mel as mel
import mGeneral; reload(mGeneral)
from .. import mLogger; reload(mLogger)
exc = os.path.basename(sys.executable)
logger = mLogger.MLog('moGC.mMaya.sInfo',
False if exc == 'mayapy... | [
"os.path.exists",
"maya.cmds.playbackOptions",
"os.makedirs",
"maya.cmds.workspace",
"maya.mel.eval",
"maya.cmds.currentUnit",
"os.path.dirname",
"os.path.basename",
"mGeneral.sceneName"
] | [((217, 249), 'os.path.basename', 'os.path.basename', (['sys.executable'], {}), '(sys.executable)\n', (233, 249), False, 'import os, sys\n'), ((489, 514), 'maya.cmds.workspace', 'cmds.workspace', ([], {'q': '(1)', 'rd': '(1)'}), '(q=1, rd=1)\n', (503, 514), True, 'import maya.cmds as cmds\n'), ((625, 657), 'mGeneral.sc... |
import requests
import json
from datetime import datetime
import pysnowball.token as token
def fetch(url, host="stock.xueqiu.com"):
HEADERS = {'Host': host,
'Accept': 'application/json',
'Cookie': token.get_token(),
'User-Agent': 'Xueqiu iPhone 11.8',
'... | [
"json.loads",
"requests.post",
"requests.packages.urllib3.disable_warnings",
"requests.get",
"pysnowball.token.get_token",
"datetime.datetime.today"
] | [((483, 517), 'requests.get', 'requests.get', (['url'], {'headers': 'HEADERS'}), '(url, headers=HEADERS)\n', (495, 517), False, 'import requests\n'), ((700, 728), 'json.loads', 'json.loads', (['response.content'], {}), '(response.content)\n', (710, 728), False, 'import json\n'), ((1090, 1124), 'requests.get', 'requests... |
""" Defines a client class for working with a BitBucket namespace. """
from bitbucket.repositories import BitBucketRepositoriesClient
class BitBucketNamespaceClient(object):
""" Client class representing a single namespace in bitbucket. """
def __init__(self, dispatcher, access_token, access_token_secret, namespa... | [
"bitbucket.repositories.BitBucketRepositoriesClient"
] | [((677, 791), 'bitbucket.repositories.BitBucketRepositoriesClient', 'BitBucketRepositoriesClient', (['self._dispatcher', 'self._access_token', 'self._access_token_secret', 'self._namespace'], {}), '(self._dispatcher, self._access_token, self.\n _access_token_secret, self._namespace)\n', (704, 791), False, 'from bitb... |
from django.apps import apps
from django.conf import settings
from casepro.pods.base import PodPlugin
def load_pod(index, config):
"""
Given the index of the pod, and the config dictionary for the pod, this
returns the instance of that pod.
"""
config = config.copy()
pod_type = apps.get_app_c... | [
"django.apps.apps.get_app_configs"
] | [((598, 620), 'django.apps.apps.get_app_configs', 'apps.get_app_configs', ([], {}), '()\n', (618, 620), False, 'from django.apps import apps\n')] |
from sklearn.metrics import recall_score, roc_curve, auc
def specificity(y_true, y_pred):
return recall_score(y_true, y_pred, pos_label=0)
def sensitivity(y_true, y_pred):
return recall_score(y_true, y_pred, pos_label=1)
def balanced_accuracy(y_true, y_pred):
spec = specificity(y_true, y_pred)
sens... | [
"sklearn.metrics.recall_score",
"sklearn.metrics.auc",
"sklearn.metrics.roc_curve"
] | [((102, 143), 'sklearn.metrics.recall_score', 'recall_score', (['y_true', 'y_pred'], {'pos_label': '(0)'}), '(y_true, y_pred, pos_label=0)\n', (114, 143), False, 'from sklearn.metrics import recall_score, roc_curve, auc\n'), ((190, 231), 'sklearn.metrics.recall_score', 'recall_score', (['y_true', 'y_pred'], {'pos_label... |
# %%
import pandas as pd
# %% Display a data frame
df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]},
index=pd.Index(['x0', 'x1'], name='x'))
df
# %% Pandas plot {"tags": ["parameters"]}
df.plot(kind='bar')
| [
"pandas.Index"
] | [((122, 154), 'pandas.Index', 'pd.Index', (["['x0', 'x1']"], {'name': '"""x"""'}), "(['x0', 'x1'], name='x')\n", (130, 154), True, 'import pandas as pd\n')] |
#!/usr/bin/python3
## this file is part of cheap_pie, a python tool for chip validation
## author: <NAME>
## email: <EMAIL>
import untangle # for parsing xml
from ast import literal_eval
import string as str
from collections import namedtuple
import sys
import os.path
sys.path.append( os.path.join(os.path.dirname(__... | [
"cheap_pie_core.cp_register.cp_register",
"cheap_pie_core.cbitfield.cp_bitfield",
"ast.literal_eval",
"parsers.name_subs.name_subs",
"untangle.parse"
] | [((955, 976), 'untangle.parse', 'untangle.parse', (['fname'], {}), '(fname)\n', (969, 976), False, 'import untangle\n'), ((1393, 1420), 'ast.literal_eval', 'literal_eval', (['base_addr_str'], {}), '(base_addr_str)\n', (1405, 1420), False, 'from ast import literal_eval\n'), ((1963, 1981), 'parsers.name_subs.name_subs', ... |
# -*- coding: utf-8 -*-
"""
Entry point that calls the main source code
handler.lambda_handler calls .lib/ami_lookup.py
TO DO: None
"""
import logging
def lambda_handler(event, context):
"""Entry Point"""
enable_logging(event)
execute_main(event, context)
def enable_logging(event):
"Enables Loggi... | [
"logging.getLogger",
"lib.ami_lookup.main"
] | [((364, 383), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (381, 383), False, 'import logging\n'), ((564, 584), 'lib.ami_lookup.main', 'main', (['event', 'context'], {}), '(event, context)\n', (568, 584), False, 'from lib.ami_lookup import main\n')] |
#! /usr/bin/env python
from __future__ import print_function
import argparse
class Path(object):
def _parse_path(self, pathlist):
"""parse a list of manhattan directions into a list of points.
each coordinate that the path goes through are added to the list.
"""
loc = [0, 0]
... | [
"argparse.ArgumentParser"
] | [((4628, 4653), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (4651, 4653), False, 'import argparse\n')] |
from rest_framework import serializers
from rest_framework.validators import UniqueTogetherValidator
from rest_framework_json_api.relations import (
ResourceRelatedField,
SerializerMethodResourceRelatedField, SerializerMethodHyperlinkedRelatedField
)
from bluebottle.activities.utils import (
BaseActivitySe... | [
"rest_framework.serializers.SerializerMethodField",
"rest_framework_json_api.relations.SerializerMethodResourceRelatedField",
"bluebottle.utils.utils.reverse_signed",
"bluebottle.deeds.models.Deed.objects.all",
"rest_framework_json_api.relations.SerializerMethodHyperlinkedRelatedField",
"bluebottle.utils.... | [((836, 893), 'bluebottle.utils.serializers.ResourcePermissionField', 'ResourcePermissionField', (['"""deed-detail"""'], {'view_args': "('pk',)"}), "('deed-detail', view_args=('pk',))\n", (859, 893), False, 'from bluebottle.utils.serializers import ResourcePermissionField\n'), ((906, 941), 'rest_framework.serializers.S... |
from pygame import Vector2, mouse
from .movement import Movement
class MouseMovement(Movement):
def __init__(self, sprite, thrust=60, within=1, button=1, auto=False):
Movement.__init__(self, sprite, thrust)
self.mouse_position = Vector2(0, 0)
self.within = within
self.button = butt... | [
"pygame.mouse.get_pressed",
"pygame.Vector2",
"pygame.mouse.get_pos"
] | [((251, 264), 'pygame.Vector2', 'Vector2', (['(0)', '(0)'], {}), '(0, 0)\n', (258, 264), False, 'from pygame import Vector2, mouse\n'), ((421, 444), 'pygame.Vector2', 'Vector2', (['mouse_position'], {}), '(mouse_position)\n', (428, 444), False, 'from pygame import Vector2, mouse\n'), ((565, 584), 'pygame.mouse.get_pres... |
#!/usr/bin/env python
import functools
import math
import numpy
import hypothesis
import hypothesis.extra.numpy
from hypothesis.strategies import complex_numbers, floats
import libnu.array
from test import eq
arrays = functools.partial(
hypothesis.extra.numpy.arrays,
shape=10,
unique=True,
)
numpy.ones... | [
"numpy.mean",
"numpy.ones",
"test.eq",
"hypothesis.strategies.floats",
"math.log",
"numpy.zeros",
"functools.partial",
"hypothesis.strategies.complex_numbers",
"numpy.sin",
"math.exp"
] | [((223, 294), 'functools.partial', 'functools.partial', (['hypothesis.extra.numpy.arrays'], {'shape': '(10)', 'unique': '(True)'}), '(hypothesis.extra.numpy.arrays, shape=10, unique=True)\n', (240, 294), False, 'import functools\n'), ((323, 373), 'functools.partial', 'functools.partial', (['numpy.ones'], {'dtype': 'num... |
""" Test for fitting wavefronts
"""
from PyQt5.QtWidgets import QApplication
import poptics.gui as gui
def main():
app = QApplication([])
w = gui.WaveFrontViewer()
w.show()
app.exec_()
main()
| [
"poptics.gui.WaveFrontViewer",
"PyQt5.QtWidgets.QApplication"
] | [((136, 152), 'PyQt5.QtWidgets.QApplication', 'QApplication', (['[]'], {}), '([])\n', (148, 152), False, 'from PyQt5.QtWidgets import QApplication\n'), ((161, 182), 'poptics.gui.WaveFrontViewer', 'gui.WaveFrontViewer', ([], {}), '()\n', (180, 182), True, 'import poptics.gui as gui\n')] |
''' Spline2.py: wrapper for B. Thijsse et al.'s hyper-spline routines.
Yet another spline interpolation routine. The problem: given a set of
experimental data with noise, find the spline with the optimal number of
knots.
Solution:
They use the usual kind of routines to determine least-squares
splines from ... | [
"numpy.array",
"numpy.shape",
"numpy.asarray"
] | [((4296, 4310), 'numpy.asarray', 'num.asarray', (['x'], {}), '(x)\n', (4307, 4310), True, 'import numpy as num\n'), ((4338, 4352), 'numpy.asarray', 'num.asarray', (['y'], {}), '(y)\n', (4349, 4352), True, 'import numpy as num\n'), ((6280, 6292), 'numpy.shape', 'num.shape', (['x'], {}), '(x)\n', (6289, 6292), True, 'imp... |
import sys
sys.path.append('.') # NOQA
from src.datasets.preprocess import normalize
def main(root_path=None, arr_type='nii.gz', modality='mri'):
# save normalized npz arrays in root_path/normalized/
normalize(root_path, arr_type, modality)
if __name__ == '__main__':
from fire import Fire
Fire(main... | [
"src.datasets.preprocess.normalize",
"sys.path.append",
"fire.Fire"
] | [((11, 31), 'sys.path.append', 'sys.path.append', (['"""."""'], {}), "('.')\n", (26, 31), False, 'import sys\n'), ((211, 251), 'src.datasets.preprocess.normalize', 'normalize', (['root_path', 'arr_type', 'modality'], {}), '(root_path, arr_type, modality)\n', (220, 251), False, 'from src.datasets.preprocess import norma... |
# Copyright (c) 2021, NVIDIA CORPORATION. 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 appli... | [
"warprnnt_numba.rnnt_loss.utils.cuda_utils.gpu_rnnt_kernel.logp",
"numba.cuda.atomic.add",
"numba.cuda.jit",
"warprnnt_numba.rnnt_loss.utils.rnnt_helper.log_sum_exp"
] | [((1399, 1433), 'numba.cuda.jit', 'cuda.jit', ([], {'device': '(True)', 'inline': '(True)'}), '(device=True, inline=True)\n', (1407, 1433), False, 'from numba import cuda\n'), ((2526, 2536), 'numba.cuda.jit', 'cuda.jit', ([], {}), '()\n', (2534, 2536), False, 'from numba import cuda\n'), ((7941, 7951), 'numba.cuda.jit'... |
from django.db import models, migrations
import datetime
from django.utils.timezone import utc
MAGIC_DATETIME = datetime.datetime(2015, 8, 17, 9, 32, 48, 54124, tzinfo=utc)
class Migration(migrations.Migration):
dependencies = [
('content', '0004_site_settings_meta'),
]
operations = [
... | [
"datetime.datetime",
"django.db.models.DateTimeField"
] | [((114, 174), 'datetime.datetime', 'datetime.datetime', (['(2015)', '(8)', '(17)', '(9)', '(32)', '(48)', '(54124)'], {'tzinfo': 'utc'}), '(2015, 8, 17, 9, 32, 48, 54124, tzinfo=utc)\n', (131, 174), False, 'import datetime\n'), ((425, 488), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'default': 'MAG... |
from PyQt5 import QtCore, QtGui, QtWidgets
import qdarkstyle
from threading import Thread
from collections import deque
from datetime import datetime
import time
import sys
import cv2, torch
from PIL import Image as im
from utils.augmentations import letterbox
import imutils
import numpy as np
model = torch.hub.load('... | [
"cv2.rectangle",
"qdarkstyle.load_stylesheet_pyqt",
"PyQt5.QtGui.QPixmap.fromImage",
"PyQt5.QtWidgets.QStyleFactory.create",
"PyQt5.QtGui.QImage",
"PyQt5.QtWidgets.QApplication.processEvents",
"PyQt5.QtWidgets.QApplication",
"sys.exit",
"collections.deque",
"utils.augmentations.letterbox",
"PyQt... | [((304, 393), 'torch.hub.load', 'torch.hub.load', (['"""./models"""', '"""custom"""'], {'path': '"""helmet_head_person_s.pt"""', 'source': '"""local"""'}), "('./models', 'custom', path='helmet_head_person_s.pt', source\n ='local')\n", (318, 393), False, 'import cv2, torch\n'), ((6755, 6766), 'sys.exit', 'sys.exit', ... |
"""
Copyright (C) 2012 <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, merge, publish, distribute, sublice... | [
"numpy.dot",
"numpy.zeros"
] | [((4026, 4051), 'numpy.zeros', 'np.zeros', (['self.numNeurons'], {}), '(self.numNeurons)\n', (4034, 4051), True, 'import numpy as np\n'), ((5043, 5068), 'numpy.zeros', 'np.zeros', (['self.numNeurons'], {}), '(self.numNeurons)\n', (5051, 5068), True, 'import numpy as np\n'), ((5183, 5213), 'numpy.dot', 'np.dot', (['w', ... |
#!/usr/bin/python
import random
import tree
nums = [random.randint(0,10) for x in range(0,10)]
print("Input tree data:")
print(nums)
bst = Tree(nums)
print("Initial BST:")
print(bst)
print("Min value:")
print(bst.findMin())
nums = [random.randint(0,10) for x in range(0,10)]
print("Adding values:")
print(nums)
f... | [
"random.randint"
] | [((54, 75), 'random.randint', 'random.randint', (['(0)', '(10)'], {}), '(0, 10)\n', (68, 75), False, 'import random\n'), ((239, 260), 'random.randint', 'random.randint', (['(0)', '(10)'], {}), '(0, 10)\n', (253, 260), False, 'import random\n')] |
"""
Tests of entry
"""
import pytest
from graphql_jwt.testcases import JSONWebTokenTestCase
from django.test import TestCase
from graphene.test import Client
from alohomora.schema import schema
from django.contrib.auth import get_user_model
from accounts.models import Entry, Block, Apartment
from django.utils import t... | [
"django.contrib.auth.get_user_model",
"accounts.models.Apartment.objects.create",
"accounts.models.Entry.objects.get",
"accounts.models.Block.objects.get",
"django.utils.timezone.now",
"pytest.mark.usefixtures",
"graphene.test.Client"
] | [((330, 366), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""test_data"""'], {}), "('test_data')\n", (353, 366), False, 'import pytest\n'), ((535, 549), 'django.utils.timezone.now', 'timezone.now', ([], {}), '()\n', (547, 549), False, 'from django.utils import timezone\n'), ((633, 647), 'graphene.test.Clie... |
#!/usr/bin/env python
# encoding: utf-8
import unittest
from hebrew_tokenizer import tokenize
def compare(test_name, sentences, tokenization_ground_truth, print_results=False, with_whitespaces=False):
for n, (s, s_ground_truth) in enumerate(zip(sentences, tokenization_ground_truth)):
s_tokens = [(t, grp) ... | [
"hebrew_tokenizer.tokenize"
] | [((340, 386), 'hebrew_tokenizer.tokenize', 'tokenize', (['s'], {'with_whitespaces': 'with_whitespaces'}), '(s, with_whitespaces=with_whitespaces)\n', (348, 386), False, 'from hebrew_tokenizer import tokenize\n')] |
# coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from tapi_server.models.base_model_ import Model
from tapi_server.models.tapi_photonic_media_frequency_constraint import TapiPhotonicMediaFrequencyConstraint # noqa: F... | [
"tapi_server.util.deserialize_model"
] | [((2101, 2134), 'tapi_server.util.deserialize_model', 'util.deserialize_model', (['dikt', 'cls'], {}), '(dikt, cls)\n', (2123, 2134), False, 'from tapi_server import util\n')] |
""" Computes the American option price using the deep optimal stopping (DOS).
It is the implementation of the deep optimal stopping (DOS) introduced in
(deep optimal stopping, Becker, Cheridito and Jentzen, 2020).
"""
import numpy as np
import torch
import torch.optim as optim
import torch.utils.data as tdata
from o... | [
"torch.manual_seed",
"numpy.flip",
"torch.nn.init.xavier_uniform_",
"torch.mean",
"torch.from_numpy",
"numpy.zeros",
"optimal_stopping.algorithms.utils.neural_networks.NetworkDOS",
"torch.set_grad_enabled"
] | [((529, 550), 'torch.manual_seed', 'torch.manual_seed', (['(42)'], {}), '(42)\n', (546, 550), False, 'import torch\n'), ((592, 631), 'torch.nn.init.xavier_uniform_', 'torch.nn.init.xavier_uniform_', (['m.weight'], {}), '(m.weight)\n', (621, 631), False, 'import torch\n'), ((1496, 1525), 'numpy.flip', 'np.flip', (['stoc... |
from django.test import TestCase
from hotels.models import Hotel
class CheckPages(TestCase):
def test_hotels_page_status_code(self):
response = self.client.get('/hotels/')
self.assertEqual(response.status_code, 200)
def test_hotels_search_page_status_code(self):
response = self.clien... | [
"hotels.models.Hotel.objects.create"
] | [((551, 648), 'hotels.models.Hotel.objects.create', 'Hotel.objects.create', ([], {'name': '"""Baccarat"""', 'country': '"""United States"""', 'town': '"""NY"""', 'beds': '"""3"""', 'rank': '"""9"""'}), "(name='Baccarat', country='United States', town='NY',\n beds='3', rank='9')\n", (571, 648), False, 'from hotels.mo... |
#!/usr/bin/env python3
# coding: utf-8
# SPDX-License-Identifier: Apache-2.0
# Copyright 2020 AntiCompositeNumber
# 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/l... | [
"json.loads",
"pywikibot.Site",
"string.Template",
"collections.deque",
"argparse.ArgumentParser",
"datetime.datetime.utcnow",
"acnutils.check_runpage",
"toolforge.connect",
"acnutils.Throttle",
"acnutils.getInitLogger",
"pywikibot.Page",
"acnutils.retry",
"datetime.timedelta",
"acnutils.g... | [((900, 946), 'acnutils.getInitLogger', 'utils.getInitLogger', (['"""nolicense"""'], {'level': '"""INFO"""'}), "('nolicense', level='INFO')\n", (919, 946), True, 'import acnutils as utils\n'), ((955, 991), 'pywikibot.Site', 'pywikibot.Site', (['"""commons"""', '"""commons"""'], {}), "('commons', 'commons')\n", (969, 99... |
"""
Handles sounds for Some Platformer Game
Created by sheepy0125
30/10/2021
"""
#############
### Setup ###
#############
# Import
from pygame_setup import pygame
from utils import Logger, ROOT_PATH
from time import time
# Variables
SOUND_PATH = ROOT_PATH / "assets" / "sfx"
#######################
### Sound datacla... | [
"pygame_setup.pygame.mixer.Channel",
"utils.Logger.fatal",
"utils.Logger.log_error",
"pygame_setup.pygame.mixer.init",
"pygame_setup.pygame.mixer.Sound"
] | [((832, 904), 'pygame_setup.pygame.mixer.init', 'pygame.mixer.init', ([], {'frequency': '(44100)', 'size': '(-16)', 'channels': '(2)', 'buffer': '(2 ** 12)'}), '(frequency=44100, size=-16, channels=2, buffer=2 ** 12)\n', (849, 904), False, 'from pygame_setup import pygame\n'), ((919, 942), 'pygame_setup.pygame.mixer.Ch... |
import sqlite3
conn = sqlite3.connect('northwind_small.sqlite3')
curs = conn.cursor()
# Question 1
q1 = curs.execute("""
SELECT ProductName, UnitPrice FROM Product
ORDER BY UnitPrice DESC
LIMIT 10;
""").fetchall()
print("The ten most expensive items (per unite price) in the database are: ", q1)
# Question 2
q2 = cur... | [
"sqlite3.connect"
] | [((22, 64), 'sqlite3.connect', 'sqlite3.connect', (['"""northwind_small.sqlite3"""'], {}), "('northwind_small.sqlite3')\n", (37, 64), False, 'import sqlite3\n')] |
import numpy as np
from typing import Sequence
import pyrado
from pyrado.utils.data_types import EnvSpec
from pyrado.tasks.base import Task
from pyrado.tasks.utils import never_succeeded
from pyrado.tasks.reward_functions import RewFcn
class EndlessFlippingTask(Task):
"""
Task class for flipping an object ar... | [
"pyrado.tasks.utils.never_succeeded",
"numpy.array",
"numpy.fmod",
"numpy.min",
"pyrado.TypeErr"
] | [((2969, 3069), 'numpy.array', 'np.array', (['[[self._last_angle + self.des_angle_delta], [self._last_angle - self.\n des_angle_delta]]'], {}), '([[self._last_angle + self.des_angle_delta], [self._last_angle -\n self.des_angle_delta]])\n', (2977, 3069), True, 'import numpy as np\n'), ((3166, 3195), 'numpy.fmod', ... |
from enum import Enum
from typing import List, Tuple
import editdistance
from hunspell import Hunspell
class Spelling(Enum):
"""
the status of a token that has been processed by the spell checker.
a token can be
- correct: no change required
- fixed: the token was misspelled and a correction was ... | [
"editdistance.eval"
] | [((856, 891), 'editdistance.eval', 'editdistance.eval', (['word', 'suggestion'], {}), '(word, suggestion)\n', (873, 891), False, 'import editdistance\n')] |
from flask import Blueprint, render_template, request, url_for, redirect
from app.common.service import get_one, delete_one
from app.models import TodoList, TodoItem
from app.todo_list.forms import TodoForm
from app import db
todoList = Blueprint('todoList', __name__, template_folder='templates')
@todoList.route('/'... | [
"flask.render_template",
"app.db.session.commit",
"app.todo_list.forms.TodoForm",
"flask.url_for",
"app.common.service.delete_one",
"app.db.session.add",
"app.common.service.get_one",
"flask.Blueprint",
"app.models.TodoItem"
] | [((238, 298), 'flask.Blueprint', 'Blueprint', (['"""todoList"""', '__name__'], {'template_folder': '"""templates"""'}), "('todoList', __name__, template_folder='templates')\n", (247, 298), False, 'from flask import Blueprint, render_template, request, url_for, redirect\n'), ((492, 514), 'app.todo_list.forms.TodoForm', ... |
# coding: utf-8
from __future__ import annotations
from datetime import date, datetime # noqa: F401
import re # noqa: F401
from typing import Any, Dict, List, Optional, Union, Literal # noqa: F401
from pydantic import AnyUrl, BaseModel, EmailStr, validator, Field, Extra # noqa: F401
from aries_cloudcontroller.m... | [
"re.match",
"pydantic.validator"
] | [((2169, 2194), 'pydantic.validator', 'validator', (['"""mediation_id"""'], {}), "('mediation_id')\n", (2178, 2194), False, 'from pydantic import AnyUrl, BaseModel, EmailStr, validator, Field, Extra\n'), ((2427, 2451), 're.match', 're.match', (['pattern', 'value'], {}), '(pattern, value)\n', (2435, 2451), False, 'impor... |
import logging
import azure.functions as func
import re
import os
import itertools
from msrest.authentication import CognitiveServicesCredentials
from azure.ai.textanalytics import TextAnalyticsClient
from azure.core.credentials import AzureKeyCredential
import json
from difflib import SequenceMatcher
key1 = os.enviro... | [
"azure.functions.HttpResponse",
"difflib.SequenceMatcher",
"json.dumps",
"azure.core.credentials.AzureKeyCredential",
"re.sub",
"azure.ai.textanalytics.TextAnalyticsClient",
"logging.info"
] | [((658, 682), 'azure.core.credentials.AzureKeyCredential', 'AzureKeyCredential', (['key1'], {}), '(key1)\n', (676, 682), False, 'from azure.core.credentials import AzureKeyCredential\n'), ((711, 769), 'azure.ai.textanalytics.TextAnalyticsClient', 'TextAnalyticsClient', ([], {'endpoint': 'ep', 'credential': 'ta_credenti... |
from scraper.artist import ArtistPage
from scraper.song import Song
page = ArtistPage('https://spiewnik.wywrota.pl/kombii')
for song in page.scrape():
print(song) | [
"scraper.artist.ArtistPage"
] | [((76, 124), 'scraper.artist.ArtistPage', 'ArtistPage', (['"""https://spiewnik.wywrota.pl/kombii"""'], {}), "('https://spiewnik.wywrota.pl/kombii')\n", (86, 124), False, 'from scraper.artist import ArtistPage\n')] |
import pytest
import asyncio
from textwrap import dedent
from genesis.exceptions import AuthenticationError
from genesis import Client
from environment import Freeswitch, Callback, EVENTS
@pytest.mark.asyncio
async def test_connect_without_freeswitch():
with pytest.raises(ConnectionRefusedError):
async ... | [
"environment.Freeswitch",
"genesis.Client",
"pytest.raises",
"asyncio.sleep",
"environment.Callback"
] | [((2341, 2351), 'environment.Callback', 'Callback', ([], {}), '()\n', (2349, 2351), False, 'from environment import Freeswitch, Callback, EVENTS\n'), ((2827, 2837), 'environment.Callback', 'Callback', ([], {}), '()\n', (2835, 2837), False, 'from environment import Freeswitch, Callback, EVENTS\n'), ((3323, 3333), 'envir... |
import os
import functools
from slugify import slugify
from dateutil.parser import parse as parse_datetime
from settings import POSTS_DIR
class BlogPost(object):
title = ''
subtitle = ''
tags = []
datetime = None
content = ''
@property
def slug_tags(self):
return [slugify(t) for... | [
"functools.lru_cache",
"os.listdir",
"os.path.join",
"slugify.slugify"
] | [((3372, 3405), 'functools.lru_cache', 'functools.lru_cache', ([], {'maxsize': 'None'}), '(maxsize=None)\n', (3391, 3405), False, 'import functools\n'), ((3481, 3502), 'os.listdir', 'os.listdir', (['posts_dir'], {}), '(posts_dir)\n', (3491, 3502), False, 'import os\n'), ((4144, 4156), 'slugify.slugify', 'slugify', (['t... |
from benchmark import Benchmark, benchmark
import astropy.units as u
import pytest
@benchmark(
{
"log.final.venus.TMan": {"value": 2679.27122, "unit": u.K},
"log.final.venus.TCore": {"value": 6365.71258, "unit": u.K},
"log.final.venus.RIC": {"value": 0.0, "unit": u.km},
"log.final.... | [
"benchmark.benchmark"
] | [((86, 416), 'benchmark.benchmark', 'benchmark', (["{'log.final.venus.TMan': {'value': 2679.27122, 'unit': u.K},\n 'log.final.venus.TCore': {'value': 6365.71258, 'unit': u.K},\n 'log.final.venus.RIC': {'value': 0.0, 'unit': u.km},\n 'log.final.venus.RadPowerTotal': {'value': 31.49126, 'unit': u.TW},\n 'log.... |