code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
#coding:utf-8
'''
author : linkin
e-mail : <EMAIL>
date : 2018-11-15
'''
import amipy
from amipy.BaseClass import Hub
from amipy.middlewares import MiddleWareManager
from amipy.util.load import load_py
from amipy.log import getLogger
class SpiderHub(Hub):
def __new__(cls, *args, **kwargs):
i... | [
"amipy.log.getLogger",
"amipy.util.load.load_py"
] | [((773, 792), 'amipy.log.getLogger', 'getLogger', (['__name__'], {}), '(__name__)\n', (782, 792), False, 'from amipy.log import getLogger\n'), ((932, 947), 'amipy.util.load.load_py', 'load_py', (['_queue'], {}), '(_queue)\n', (939, 947), False, 'from amipy.util.load import load_py\n')] |
import numpy as np
def ratios(pops1, pops2):
totals1 = np.array(pops1[0]) + np.array(pops1[1])
totals2 = np.array(pops2[0]) + np.array(pops2[1])
change_ratio = np.delete(totals2, 0) / np.delete(totals1, -1)
change_ratio = np.delete(change_ratio, -1)
baby_ratio = totals2[0] / np.sum(np.array(pops1... | [
"numpy.delete",
"numpy.array",
"numpy.sum"
] | [((241, 268), 'numpy.delete', 'np.delete', (['change_ratio', '(-1)'], {}), '(change_ratio, -1)\n', (250, 268), True, 'import numpy as np\n'), ((61, 79), 'numpy.array', 'np.array', (['pops1[0]'], {}), '(pops1[0])\n', (69, 79), True, 'import numpy as np\n'), ((82, 100), 'numpy.array', 'np.array', (['pops1[1]'], {}), '(po... |
#!/usr/bin/python
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
import sys
import re
import os
import shutil
import subprocess
import zipfile
"""
Copy Speci... | [
"os.path.exists",
"os.listdir",
"zipfile.ZipFile",
"subprocess.run",
"os.path.join",
"os.mkdir",
"shutil.copy",
"sys.exit",
"re.search"
] | [((707, 728), 'os.listdir', 'os.listdir', (['directory'], {}), '(directory)\n', (717, 728), False, 'import os\n'), ((1541, 1588), 'subprocess.run', 'subprocess.run', (["(['zip', '-j', zip_path] + paths)"], {}), "(['zip', '-j', zip_path] + paths)\n", (1555, 1588), False, 'import subprocess\n'), ((789, 820), 're.search',... |
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
setup(
name="giraffe",
version="0.1",
package_dir={"giraffe" : ""},
packages=["giraffe"],
cmdclass = {'build_ext': build_ext},
ext_modules = [
Exten... | [
"distutils.extension.Extension"
] | [((315, 356), 'distutils.extension.Extension', 'Extension', (['"""graph"""', "['giraffe/graph.pyx']"], {}), "('graph', ['giraffe/graph.pyx'])\n", (324, 356), False, 'from distutils.extension import Extension\n'), ((379, 432), 'distutils.extension.Extension', 'Extension', (['"""graph_mixin"""', "['giraffe/graph_mixin.py... |
import click
from modules.processor import build_report, print_report
@click.group(invoke_without_command=True)
@click.option('--files', '-f', required=True, type=str, prompt="Provide the path to data files")
@click.pass_context
def cli_root(ctx, files):
ctx.meta['files'] = files
@cli_root.command()
@click.argu... | [
"click.Choice",
"click.argument",
"modules.processor.build_report",
"click.group",
"click.option",
"modules.processor.print_report"
] | [((73, 113), 'click.group', 'click.group', ([], {'invoke_without_command': '(True)'}), '(invoke_without_command=True)\n', (84, 113), False, 'import click\n'), ((115, 215), 'click.option', 'click.option', (['"""--files"""', '"""-f"""'], {'required': '(True)', 'type': 'str', 'prompt': '"""Provide the path to data files""... |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
# Set fontsize larger for latex plots
matplotlib.rcParams.update({'font.size': 20})
# Generate data from file
x, y = np.genfromtxt("bin/python_Aufgabe2.txt", unpack=True)
m, n = x[-1], y[-1]
# Plotting
plt.figure(figsize=(12,7))
plt.grid()
plt.xla... | [
"matplotlib.pyplot.grid",
"matplotlib.pyplot.savefig",
"matplotlib.rcParams.update",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.tight_layout",
"numpy.genfromtxt",
"matplotlib.pyplot.legend"
] | [((108, 153), 'matplotlib.rcParams.update', 'matplotlib.rcParams.update', (["{'font.size': 20}"], {}), "({'font.size': 20})\n", (134, 153), False, 'import matplotlib\n'), ((188, 241), 'numpy.genfromtxt', 'np.genfromtxt', (['"""bin/python_Aufgabe2.txt"""'], {'unpack': '(True)'}), "('bin/python_Aufgabe2.txt', unpack=True... |
#!/usr/bin/env python3
# This script assumes that the non-numerical column headers
# in train and predi files are identical.
# Thus the sm header(s) in the train file must be numeric (day/month/year).
import sys
import numpy as np
import pandas as pd
from sklearn.decomposition import PCA #TruncatedSVD as SVD
from skl... | [
"pandas.read_csv",
"sklearn.pipeline.Pipeline",
"sklearn.decomposition.PCA",
"sklearn.preprocessing.StandardScaler",
"pandas.DataFrame",
"pandas.concat"
] | [((694, 741), 'pandas.DataFrame', 'pd.DataFrame', (['data_matrix'], {'columns': 'data.columns'}), '(data_matrix, columns=data.columns)\n', (706, 741), True, 'import pandas as pd\n'), ((849, 865), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (863, 865), False, 'from sklearn.preprocessing i... |
# Copyright (C) 2015 <NAME>
#
# This program is released under the "MIT License".
# Please see the file COPYING in this distribution for
# license terms.
import datetime
from flask import Blueprint, request, jsonify
from webargs import Arg
from webargs.flaskparser import use_args
import geoalchemy2.functions as func... | [
"app.db.session.commit",
"app.models.Locations.tstamp.desc",
"app.models.Active.tstamp.desc",
"webargs.Arg",
"app.models.Active",
"geoalchemy2.functions.ST_X",
"geoalchemy2.functions.ST_Y",
"app.models.Active.query.filter_by",
"app.db.session.add",
"webargs.flaskparser.use_args",
"app.models.Loc... | [((400, 445), 'flask.Blueprint', 'Blueprint', (['"""api"""', '__name__'], {'url_prefix': '"""/api"""'}), "('api', __name__, url_prefix='/api')\n", (409, 445), False, 'from flask import Blueprint, request, jsonify\n'), ((866, 892), 'webargs.flaskparser.use_args', 'use_args', (['active_post_args'], {}), '(active_post_arg... |
'''
Created on April 15, 2018
@author: <NAME>
'''
import numpy as np
import warnings
from scipy.stats import gamma, lognorm
from sklearn.linear_model import ElasticNet
from spn.structure.leaves.conditional.Conditional import Conditional_Gaussian, Conditional_Poisson, \
Conditional_Bernoulli
import statsmodels.api... | [
"statsmodels.api.families.Poisson",
"numpy.savez",
"sklearn.linear_model.ElasticNet",
"numpy.ones",
"statsmodels.api.families.Gaussian",
"tensorflow_probability.glm.Poisson",
"tensorflow.Session",
"statsmodels.api.families.Binomial",
"os.path.dirname",
"tensorflow.constant",
"numpy.isnan",
"st... | [((364, 381), 'os.path.dirname', 'dirname', (['__file__'], {}), '(__file__)\n', (371, 381), False, 'from os.path import dirname\n'), ((939, 1013), 'sklearn.linear_model.ElasticNet', 'ElasticNet', ([], {'random_state': '(0)', 'alpha': '(0.01)', 'max_iter': '(2000)', 'fit_intercept': '(False)'}), '(random_state=0, alpha=... |
# Copyright (c) 2019 Science and Technology Facilities Council
# All rights reserved.
# Modifications made as part of the fparser project are distributed
# under the following license:
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following condi... | [
"pytest.raises",
"fparser.two.Fortran2003.Control_Edit_Desc"
] | [((4275, 4302), 'fparser.two.Fortran2003.Control_Edit_Desc', 'Control_Edit_Desc', (['my_input'], {}), '(my_input)\n', (4292, 4302), False, 'from fparser.two.Fortran2003 import Control_Edit_Desc\n'), ((4768, 4795), 'fparser.two.Fortran2003.Control_Edit_Desc', 'Control_Edit_Desc', (['my_input'], {}), '(my_input)\n', (478... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division
from __future__ import print_function
from NumPyNet.activations import Activations
from NumPyNet.utils import _check_activation
from NumPyNet.utils import check_is_fitted
import numpy as np
from NumPyNet.layers.base import BaseLayer
__aut... | [
"PIL.Image.open",
"numpy.ones",
"NumPyNet.utils._check_activation",
"NumPyNet.utils.check_is_fitted",
"os.path.dirname",
"numpy.zeros",
"NumPyNet.activations.Hardtan",
"numpy.expand_dims",
"pylab.subplots",
"pylab.show"
] | [((4263, 4284), 'NumPyNet.activations.Hardtan', 'activations.Hardtan', ([], {}), '()\n', (4282, 4284), False, 'from NumPyNet import activations\n'), ((4751, 4779), 'numpy.expand_dims', 'np.expand_dims', (['inpt'], {'axis': '(0)'}), '(inpt, axis=0)\n', (4765, 4779), True, 'import numpy as np\n'), ((4971, 5009), 'numpy.o... |
from oled import TrackerOled
from color_tracker import ColorTracker
import cv2
from threading import Thread
tracker_oled = TrackerOled()
color_tracker = ColorTracker()
def write_fps():
tracker_oled.writeTextCenter("FPS: {:.2f}".format(color_tracker.fps.fps()))
tracker_oled.writeTextCenter("READY")
while True:
... | [
"color_tracker.ColorTracker",
"oled.TrackerOled",
"cv2.waitKey"
] | [((124, 137), 'oled.TrackerOled', 'TrackerOled', ([], {}), '()\n', (135, 137), False, 'from oled import TrackerOled\n'), ((154, 168), 'color_tracker.ColorTracker', 'ColorTracker', ([], {}), '()\n', (166, 168), False, 'from color_tracker import ColorTracker\n'), ((871, 885), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), ... |
"""
This script shows the usage of scikit-learns linear regression functionality.
"""
# %% [markdown]
# # Linear Regression using Scikit-Learn #
# %% [markdown]
# ## Ice Cream Dataset ##
# | Temperature C° | Ice Cream Sales |
# |:--------------:|:---------------:|
# | 15 | 34 |
# | 24 ... | [
"sklearn.model_selection.train_test_split",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.style.use",
"sklearn.metrics.mean_squared_error",
"numpy.array",
"matplotlib.pyplot.scatter",
"sklearn.linear_model.LinearRegression",
"matplotlib.pyplot.show"
] | [((1100, 1247), 'numpy.array', 'np.array', (['[[15, 34], [24, 587], [34, 1200], [31, 1080], [29, 989], [26, 734], [17, 80\n ], [11, 1], [23, 523], [25, 651], [0, 0], [2, 0], [12, 5]]'], {}), '([[15, 34], [24, 587], [34, 1200], [31, 1080], [29, 989], [26, 734],\n [17, 80], [11, 1], [23, 523], [25, 651], [0, 0], [2... |
# create this file
# rerouting all requests that have ‘api’ in the url to the <code>apps.core.urls
from django.conf.urls import url
from django.urls import path
from rest_framework import routers
from base.src import views
from base.src.views import InitViewSet
#from base.src.views import UploadFileForm
#upload stuf... | [
"django.urls.path",
"rest_framework.routers.DefaultRouter",
"base.src.views.InitViewSet.as_view"
] | [((408, 431), 'rest_framework.routers.DefaultRouter', 'routers.DefaultRouter', ([], {}), '()\n', (429, 431), False, 'from rest_framework import routers\n'), ((653, 716), 'django.urls.path', 'path', (['"""pawsc/upload"""', 'views.simple_upload'], {'name': '"""simple_upload"""'}), "('pawsc/upload', views.simple_upload, n... |
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
'''test_Rainbow_pen
'''
import sys, os
import numpy as np
from matplotlib import pyplot as plt
from PIL import Image
FN_OUT = 'rainbow_pen_320x240.png'
def mk_col(w, h, x, y):
a = 255
i = int(7 * y / h)
if i == 0: c, u, v = (192, 0, 0), (32, 0, 0), (0, 32, 0) # R... | [
"PIL.Image.fromarray",
"numpy.array",
"matplotlib.pyplot.figure",
"numpy.ndarray",
"matplotlib.pyplot.show"
] | [((1087, 1106), 'numpy.array', 'np.array', (['(r, g, b)'], {}), '((r, g, b))\n', (1095, 1106), True, 'import numpy as np\n'), ((1475, 1509), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(6, 4)', 'dpi': '(96)'}), '(figsize=(6, 4), dpi=96)\n', (1485, 1509), True, 'from matplotlib import pyplot as plt\n'), ... |
# k3d.py
#
# Copyright 2020 <NAME>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in ... | [
"dateutil.parser.parse",
"logging.debug",
"logging.warning",
"ssl._create_unverified_context",
"os.environ.copy",
"webbrowser.open",
"time.sleep",
"logging.error",
"logging.info",
"gi.repository.GObject.type_register"
] | [((1906, 1946), 'logging.debug', 'logging.debug', (['f"""k3d found at {k3d_exe}"""'], {}), "(f'k3d found at {k3d_exe}')\n", (1919, 1946), False, 'import logging\n'), ((14769, 14802), 'gi.repository.GObject.type_register', 'GObject.type_register', (['K3dCluster'], {}), '(K3dCluster)\n', (14790, 14802), False, 'from gi.r... |
import os
from utility import write_to_output, print_board, color_is_black, board_to_list, print_results
from board import Board
import time
from algorithm import minimax, minimax_alpha_beta, minimax_alpha_beta_final, minimax_alpha_beta_rand
from math import sqrt, floor
start = time.time()
# parse input file
with ope... | [
"utility.board_to_list",
"math.floor",
"utility.print_results",
"utility.color_is_black",
"board.Board",
"time.time"
] | [((281, 292), 'time.time', 'time.time', ([], {}), '()\n', (290, 292), False, 'import time\n'), ((770, 791), 'utility.color_is_black', 'color_is_black', (['color'], {}), '(color)\n', (784, 791), False, 'from utility import write_to_output, print_board, color_is_black, board_to_list, print_results\n'), ((800, 811), 'time... |
from __future__ import print_function
from os import getenv
from datetime import datetime
def vprint(*a, **k):
if not getenv('VERBOSE'):
return
print(datetime.now(), ' ', end='')
print(*a, **k)
| [
"datetime.datetime.now",
"os.getenv"
] | [((124, 141), 'os.getenv', 'getenv', (['"""VERBOSE"""'], {}), "('VERBOSE')\n", (130, 141), False, 'from os import getenv\n'), ((168, 182), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (180, 182), False, 'from datetime import datetime\n')] |
from talon import Context, Module
ctx = Context()
mod = Module()
mod.tag("code_data_null", desc="Tag for enabling commands relating to null")
@mod.action_class
class Actions:
def code_insert_null():
"""Inserts null"""
def code_insert_is_null():
"""Inserts check for null"""
def code_ins... | [
"talon.Module",
"talon.Context"
] | [((41, 50), 'talon.Context', 'Context', ([], {}), '()\n', (48, 50), False, 'from talon import Context, Module\n'), ((57, 65), 'talon.Module', 'Module', ([], {}), '()\n', (63, 65), False, 'from talon import Context, Module\n')] |
from numpy import array as np_array, zeros as np_zeros, sum as np_sum, empty as np_empty, \
amax as np_amax, interp as np_interp, ones as np_ones, tile as np_tile, isnan as np_isnan
import yaml
from seir_model import SEIR_matrix
from common import Window, get_datetime, timesteps_between_dates, get_datetime_arra... | [
"yaml.full_load",
"common.timesteps_over_timedelta_weeks",
"common.get_datetime",
"numpy.ones",
"common.get_datetime_array",
"common.timesteps_between_dates",
"numpy.sum",
"numpy.zeros",
"numpy.empty",
"numpy.interp",
"sys.exit",
"seir_model.SEIR_matrix",
"numpy.amax"
] | [((1888, 1920), 'numpy.sum', 'np_sum', (['proportion_total'], {'axis': '(0)'}), '(proportion_total, axis=0)\n', (1894, 1920), True, 'from numpy import array as np_array, zeros as np_zeros, sum as np_sum, empty as np_empty, amax as np_amax, interp as np_interp, ones as np_ones, tile as np_tile, isnan as np_isnan\n'), ((... |
from body.tests.login_test_case import LoginTestCase
from body.tests.model_helpers import create_ledger_entry, create_medicine
from freezegun import freeze_time
from django.utils.timezone import make_aware, datetime
@freeze_time(make_aware(datetime(2022, 3, 1)))
class MedicineTests(LoginTestCase):
def test_ledger... | [
"body.tests.model_helpers.create_medicine",
"body.tests.model_helpers.create_ledger_entry",
"django.utils.timezone.datetime"
] | [((480, 506), 'body.tests.model_helpers.create_medicine', 'create_medicine', (['self.user'], {}), '(self.user)\n', (495, 506), False, 'from body.tests.model_helpers import create_ledger_entry, create_medicine\n'), ((515, 547), 'body.tests.model_helpers.create_ledger_entry', 'create_ledger_entry', (['medicine', '(4)'], ... |
"""This module contains functions to generate strategies from annotations."""
from __future__ import annotations
import collections
import inspect
import sys
from itertools import chain
from itertools import combinations
from typing import Any
from typing import Callable
from typing import Iterable
from typing import ... | [
"bqskit.utils.test.strategies.unitaries",
"inspect.signature",
"hypothesis.strategies.sets",
"bqskit.utils.test.strategies.unitary_likes",
"hypothesis.strategies.lists",
"hypothesis.strategies.booleans",
"bqskit.utils.test.strategies.circuit_points",
"hypothesis.given",
"hypothesis.strategies.dictio... | [((7359, 7377), 'hypothesis.strategies.one_of', 'one_of', (['strategies'], {}), '(strategies)\n', (7365, 7377), False, 'from hypothesis.strategies import one_of\n'), ((16054, 16072), 'hypothesis.strategies.one_of', 'one_of', (['strategies'], {}), '(strategies)\n', (16060, 16072), False, 'from hypothesis.strategies impo... |
# Copyright 2019-2021 Swiss National Supercomputing Centre (CSCS/ETH Zurich)
# HPCTools Project Developers. See the top-level LICENSE file for details.
#
# SPDX-License-Identifier: BSD-3-Clause
import os
import sys
import reframe as rfm
import reframe.utility.sanity as sn
sys.path.append(os.path.abspath(os.path.join(o... | [
"os.path.dirname",
"reframe.utility.sanity.assert_found",
"sphexa.sanity_mpip.mpip_perf_patterns",
"reframe.run_before"
] | [((2513, 2542), 'reframe.run_before', 'rfm.run_before', (['"""performance"""'], {}), "('performance')\n", (2527, 2542), True, 'import reframe as rfm\n'), ((3076, 3105), 'reframe.run_before', 'rfm.run_before', (['"""performance"""'], {}), "('performance')\n", (3090, 3105), True, 'import reframe as rfm\n'), ((319, 344), ... |
import torch
from torch.nn import Module, Parameter
from torch.autograd import Function
class Forward_Warp_Python:
@staticmethod
def forward(im0, flow, interpolation_mode):
im1 = torch.zeros_like(im0)
B = im0.shape[0]
H = im0.shape[2]
W = im0.shape[3]
if interpolation_m... | [
"torch.floor",
"torch.round",
"torch.sum",
"torch.zeros_like",
"torch.empty",
"torch.zeros"
] | [((197, 218), 'torch.zeros_like', 'torch.zeros_like', (['im0'], {}), '(im0)\n', (213, 218), False, 'import torch\n'), ((2000, 2029), 'torch.zeros_like', 'torch.zeros_like', (['grad_output'], {}), '(grad_output)\n', (2016, 2029), False, 'import torch\n'), ((2050, 2075), 'torch.empty', 'torch.empty', (['[B, H, W, 2]'], {... |
import itertools
import Partitioning
class Algorithm( object ):
def __init__( self, linv, variant, init, repart, contwith, before, after, updates ):
self.linv = linv
self.variant = variant
if init:
#assert( len(init) == 1 )
self.init = init[0]
else:
... | [
"Partitioning.repartition_shape"
] | [((7650, 7697), 'Partitioning.repartition_shape', 'Partitioning.repartition_shape', (['op', 'repart_size'], {}), '(op, repart_size)\n', (7680, 7697), False, 'import Partitioning\n')] |
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
import matplotlib.gridspec as gs
import sys
data = np.loadtxt('NbSe2.freq.gp')
symmetryfile = 'plotband.out'
lbd = np.loadtxt("lambda.dat")
lbd_val = np.where(lbd<1 , lbd, 1)
def Symmetries(fstring):
f = open(fstring, 'r')
x = np.... | [
"numpy.tile",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.ylabel",
"numpy.where",
"matplotlib.pyplot.colorbar",
"matplotlib.pyplot.figure",
"numpy.zeros",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.ylim",
"numpy.loadtxt",
"matplotlib.pyplot.axvline",
"mat... | [((133, 160), 'numpy.loadtxt', 'np.loadtxt', (['"""NbSe2.freq.gp"""'], {}), "('NbSe2.freq.gp')\n", (143, 160), True, 'import numpy as np\n'), ((197, 221), 'numpy.loadtxt', 'np.loadtxt', (['"""lambda.dat"""'], {}), "('lambda.dat')\n", (207, 221), True, 'import numpy as np\n'), ((232, 257), 'numpy.where', 'np.where', (['... |
"""Python library to connect deCONZ and Home Assistant to work together."""
import logging
from .light import DeconzLightBase
_LOGGER = logging.getLogger(__name__)
class DeconzGroup(DeconzLightBase):
"""deCONZ light group representation.
Dresden Elektroniks documentation of light groups in deCONZ
http... | [
"logging.getLogger"
] | [((139, 166), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (156, 166), False, 'import logging\n')] |
"""
Regression tests for the REINFORCE agent on OpenAI gym environments
"""
import pytest
import numpy as np
import shutil
from yarlp.utils.env_utils import NormalizedGymEnv
from yarlp.agent.ddqn_agent import DDQNAgent
env = NormalizedGymEnv(
'PongNoFrameskip-v4',
is_atari=True
)
def test_ddqn():
a... | [
"yarlp.agent.ddqn_agent.DDQNAgent.load",
"yarlp.utils.env_utils.NormalizedGymEnv",
"numpy.array",
"shutil.rmtree",
"yarlp.agent.ddqn_agent.DDQNAgent"
] | [((232, 285), 'yarlp.utils.env_utils.NormalizedGymEnv', 'NormalizedGymEnv', (['"""PongNoFrameskip-v4"""'], {'is_atari': '(True)'}), "('PongNoFrameskip-v4', is_atari=True)\n", (248, 285), False, 'from yarlp.utils.env_utils import NormalizedGymEnv\n'), ((327, 418), 'yarlp.agent.ddqn_agent.DDQNAgent', 'DDQNAgent', (['env'... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('arbeitsplan', '0008_auto_20141208_1906'),
]
operations = [
migrations.AddField(
model_name='mitglied',
... | [
"django.db.models.IntegerField"
] | [((361, 510), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'default': '(10)', 'help_text': "b'Wieviele Stunden pro Jahr muss dieses Mitglied arbeiten?'", 'verbose_name': "b'Arbeitslast (h/Jahr)'"}), "(default=10, help_text=\n b'Wieviele Stunden pro Jahr muss dieses Mitglied arbeiten?',\n verbose_... |
import collections
import logging
import json
import os
import luigi
import gokart
import tqdm
import torch
import sentencepiece as spm
import sacrebleu
import MeCab
from fairseq.models.transformer import TransformerModel
from fairseq.data import LanguagePairDataset
from context_nmt.pipelines.conversation_dataset_mer... | [
"logging.getLogger",
"luigi.FloatParameter",
"context_nmt.pipelines.conversation_dataset_merger.MergeMultipleDataset",
"fairseq.models.transformer.TransformerModel.from_pretrained",
"luigi.IntParameter",
"luigi.DictParameter",
"sentencepiece.SentencePieceProcessor",
"fairseq.data.LanguagePairDataset",... | [((389, 425), 'logging.getLogger', 'logging.getLogger', (['"""luigi-interface"""'], {}), "('luigi-interface')\n", (406, 425), False, 'import logging\n'), ((531, 548), 'luigi.Parameter', 'luigi.Parameter', ([], {}), '()\n', (546, 548), False, 'import luigi\n'), ((569, 590), 'luigi.ListParameter', 'luigi.ListParameter', ... |
import os
from copy import deepcopy
with open(os.path.join(os.path.dirname(__file__), "input.txt"), "r") as file:
lines = [l.strip() for l in file.readlines()]
p1 = list(reversed([int(i) for i in lines[1:26]]))
p2 = list(reversed([int(i) for i in lines[28:]]))
def part1(player1, player2):
while playe... | [
"os.path.dirname",
"copy.deepcopy"
] | [((60, 85), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (75, 85), False, 'import os\n'), ((1968, 1980), 'copy.deepcopy', 'deepcopy', (['p1'], {}), '(p1)\n', (1976, 1980), False, 'from copy import deepcopy\n'), ((1982, 1994), 'copy.deepcopy', 'deepcopy', (['p2'], {}), '(p2)\n', (1990, 1994)... |
import shutil
from contextlib import contextmanager
from tempfile import NamedTemporaryFile
from s3fs import S3FileSystem
class S3Downloader:
def __init__(self, tmp_dir=None, chunk_size=16 * 1024, **kwargs):
self.tmp_dir = tmp_dir
self.chunk_size = chunk_size
self.fs = S3FileSystem(**kwa... | [
"tempfile.NamedTemporaryFile",
"shutil.copyfileobj",
"s3fs.S3FileSystem"
] | [((302, 324), 's3fs.S3FileSystem', 'S3FileSystem', ([], {}), '(**kwargs)\n', (314, 324), False, 'from s3fs import S3FileSystem\n'), ((424, 460), 'tempfile.NamedTemporaryFile', 'NamedTemporaryFile', ([], {'dir': 'self.tmp_dir'}), '(dir=self.tmp_dir)\n', (442, 460), False, 'from tempfile import NamedTemporaryFile\n'), ((... |
# Copyright (c) 2021, MITRE Engenuity. Approved for public release.
# See LICENSE for complete terms.
import argparse
import json
import pathlib
import numpy
import requests
from src.create_mappings import get_sheets, get_sheet_by_name
def get_argparse():
desc = "ATT&CK to VERIS Mappings Validator"
argpars... | [
"argparse.ArgumentParser",
"pathlib.Path",
"requests.get",
"src.create_mappings.get_sheets",
"json.load",
"src.create_mappings.get_sheet_by_name"
] | [((325, 366), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': 'desc'}), '(description=desc)\n', (348, 366), False, 'import argparse\n'), ((4285, 4336), 'src.create_mappings.get_sheet_by_name', 'get_sheet_by_name', (['spreadsheet_location', '"""Metadata"""'], {}), "(spreadsheet_location, 'Meta... |
# This file contains the list of API's for operations on ZTP
# @author : <NAME> (<EMAIL>)
from spytest import st
import apis.system.basic as basic_obj
import utilities.utils as utils_obj
import apis.system.switch_configuration as switch_conf_obj
import apis.system.interface as intf_obj
import apis.routing.ip as ip_obj
... | [
"spytest.st.debug",
"apis.system.basic.service_operations_by_systemctl",
"spytest.st.wait_system_reboot",
"spytest.st.config",
"spytest.st.reboot",
"apis.system.reboot.config_reload",
"spytest.st.wait_system_status",
"spytest.st.report_fail",
"spytest.st.wait",
"apis.system.basic.make_dir",
"api... | [((634, 672), 'spytest.st.get_ui_type', 'st.get_ui_type', (['dut'], {'cli_type': 'cli_type'}), '(dut, cli_type=cli_type)\n', (648, 672), False, 'from spytest import st\n'), ((969, 1026), 'spytest.st.show', 'st.show', (['dut', 'command'], {'expect_reboot': '(False)', 'type': 'cli_type'}), '(dut, command, expect_reboot=F... |
from kivy.app import runTouchApp
from kivy.properties import StringProperty
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.lang import Builder
from kivyx.uix.drawer import KXDrawer
class Numpad(GridLayout):
def on_kv_post(self, *ar... | [
"kivy.uix.button.Button",
"kivy.lang.Builder.load_string",
"kivy.properties.StringProperty",
"kivy.app.runTouchApp"
] | [((779, 3023), 'kivy.lang.Builder.load_string', 'Builder.load_string', (['"""\n<Numpad>:\n cols: 4\n rows: 4\n spacing: 10\n padding: 10\n size_hint: None, None\n size: self.minimum_size\n\n<Separator@Widget>:\n size: 1, 1\n canvas:\n Color:\n rgb: 1, 0, 1\n Rectangle:\n... |
# -*- coding: utf-8 -*-
"""
A Probabiltics Context Free Grammer (PCFG) Parser using Python.
This code implemented a weighted graph search
@author: <NAME>
"""
import codecs
from collections import defaultdict
import math
f_grammer=".\\test\\08-grammar.txt"
nonterm=[]
preterm=defaultdict(list)
grammer_f... | [
"codecs.open",
"collections.defaultdict",
"math.log"
] | [((290, 307), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (301, 307), False, 'from collections import defaultdict\n'), ((324, 360), 'codecs.open', 'codecs.open', (['f_grammer', '"""r"""', '"""utf-8"""'], {}), "(f_grammer, 'r', 'utf-8')\n", (335, 360), False, 'import codecs\n'), ((773, 806), 'c... |
#!/usr/bin/env python
#
# test tool for PostgreSQL Commitfest website
#
# written by: <NAME> <<EMAIL>>
#
import re
import os
import sys
import logging
import tempfile
import atexit
import shutil
import time
import subprocess
from subprocess import Popen
import socket
import sqlite3
import datetime
from time import gmt... | [
"logging.basicConfig",
"config.Config",
"atexit.register"
] | [((459, 535), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO', 'format': '"""%(levelname)s: %(message)s"""'}), "(level=logging.INFO, format='%(levelname)s: %(message)s')\n", (478, 535), False, 'import logging\n'), ((782, 811), 'atexit.register', 'atexit.register', (['exit_handler'], {}), '(e... |
import random
from fake_useragent import UserAgent
agent_list = '''Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50
Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50
Mozilla/5.0 (com... | [
"random.randint",
"fake_useragent.UserAgent"
] | [((591, 620), 'random.randint', 'random.randint', (['(0)', '(length - 1)'], {}), '(0, length - 1)\n', (605, 620), False, 'import random\n'), ((656, 678), 'fake_useragent.UserAgent', 'UserAgent', ([], {'cache': '(False)'}), '(cache=False)\n', (665, 678), False, 'from fake_useragent import UserAgent\n')] |
# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
import seaborn as sns
import numpy as np
import tensorflow as tf
tf.enable_eager_execution()
import tensorflow_probability as tfp
from tensorflow_proba... | [
"seaborn.distplot",
"matplotlib.use",
"odin.visual.plot_save",
"tensorflow.reduce_sum",
"tensorflow.enable_eager_execution",
"matplotlib.pyplot.figure",
"tensorflow.sqrt",
"numpy.concatenate",
"matplotlib.pyplot.title"
] | [((107, 128), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (121, 128), False, 'import matplotlib\n'), ((233, 260), 'tensorflow.enable_eager_execution', 'tf.enable_eager_execution', ([], {}), '()\n', (258, 260), True, 'import tensorflow as tf\n'), ((1194, 1206), 'matplotlib.pyplot.figure', 'plt.... |
#
# This source file is part of the EdgeDB open source project.
#
# Copyright 2016-present MagicStack Inc. and the EdgeDB 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... | [
"logging.getLogger",
"edb.common.devmode.enable_dev_mode",
"edb.edgeql.parser.preload",
"sys.exit",
"getpass.getuser",
"edb.server.bootstrap.bootstrap",
"pathlib.Path",
"click.option",
"asyncio.new_event_loop",
"os.path.isdir",
"os.path.expanduser",
"edb.common.devmode.is_in_dev_mode",
"temp... | [((1096, 1127), 'logging.getLogger', 'logging.getLogger', (['"""edb.server"""'], {}), "('edb.server')\n", (1113, 1127), False, 'import logging\n'), ((1217, 1228), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (1225, 1228), False, 'import sys\n'), ((1669, 1695), 'pathlib.Path', 'pathlib.Path', (['runstate_dir'], {}), ... |
# -*- coding: utf-8 -*-
from TopCmds import *
import quality_check
import data_management as dat
Qualitytest = quality_check.Qualitytest
left_boundary=float(dat.get_globalParameter("left_boundary"))
right_boundary=float(dat.get_globalParameter("right_boundary"))
def Check_180turn(leftboundary,rightboundary):... | [
"data_management.get_globalParameter",
"quality_check.conditional_decorator"
] | [((785, 891), 'quality_check.conditional_decorator', 'quality_check.conditional_decorator', (['quality_check.Quality', 'quality_check.Quality_lifted', 'Qualitytest'], {}), '(quality_check.Quality, quality_check.\n Quality_lifted, Qualitytest)\n', (820, 891), False, 'import quality_check\n'), ((1519, 1625), 'quality_... |
import PegandoVariavel as v
print(v.get_Pessoas())
print()
for d in v.get_Pessoas():
print(d) | [
"PegandoVariavel.get_Pessoas"
] | [((71, 86), 'PegandoVariavel.get_Pessoas', 'v.get_Pessoas', ([], {}), '()\n', (84, 86), True, 'import PegandoVariavel as v\n'), ((36, 51), 'PegandoVariavel.get_Pessoas', 'v.get_Pessoas', ([], {}), '()\n', (49, 51), True, 'import PegandoVariavel as v\n')] |
import abc
from collections import OrderedDict
from .constants import RESULT_KEY_MAP
class ResultMessageBase(abc.ABC):
"""
Result message base class.
"""
@abc.abstractmethod
def get_content(self, custom_data=None):
"""
Get message content.
Args:
custom_data ... | [
"collections.OrderedDict"
] | [((878, 891), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (889, 891), False, 'from collections import OrderedDict\n')] |
# coding: utf-8
from nltk.corpus import wordnet as wn
all_synsets = set()
for word in wn.words():
for synset in wn.synsets(word):
all_synsets.add(synset)
with open("wordnet_synset_definition.txt", "wb+") as fp:
for synset in all_synsets:
print >> fp, "%s\t%s" % (
synset.name()... | [
"nltk.corpus.wordnet.synsets",
"nltk.corpus.wordnet.words"
] | [((88, 98), 'nltk.corpus.wordnet.words', 'wn.words', ([], {}), '()\n', (96, 98), True, 'from nltk.corpus import wordnet as wn\n'), ((118, 134), 'nltk.corpus.wordnet.synsets', 'wn.synsets', (['word'], {}), '(word)\n', (128, 134), True, 'from nltk.corpus import wordnet as wn\n')] |
"""Main module."""
from sqlalchemy import create_engine
import pandas as pd
import collections
import logging
import re
from pprint import pprint
from typing import Sequence
from opentelemetry.metrics import Counter, Metric
from opentelemetry.sdk.metrics.export import (
MetricRecord,
MetricsExporter,
Metr... | [
"logging.getLogger",
"sqlalchemy.create_engine"
] | [((349, 376), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (366, 376), False, 'import logging\n'), ((899, 949), 'sqlalchemy.create_engine', 'create_engine', (['eng_str'], {'pool_recycle': '(60)', 'echo': '(True)'}), '(eng_str, pool_recycle=60, echo=True)\n', (912, 949), False, 'from sql... |
# Copyright (c) 2017 UFCG-LSD.
#
# 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,... | [
"broker.utils.logger.Log",
"broker.utils.framework.authorizer.get_authorization",
"broker.exceptions.BadRequestException",
"broker.exceptions.UnauthorizedException",
"broker.plugins.base.PLUGINS.get_plugin"
] | [((832, 864), 'broker.utils.logger.Log', 'Log', (['"""APIv10"""', '"""logs/APIv10.log"""'], {}), "('APIv10', 'logs/APIv10.log')\n", (835, 864), False, 'from broker.utils.logger import Log\n'), ((2269, 2340), 'broker.utils.framework.authorizer.get_authorization', 'authorizer.get_authorization', (['api.authorization_url'... |
try:
import tensorflow
except ModuleNotFoundError:
pkg_name = 'tensorflow'
import os
import sys
import subprocess
from cellacdc import myutils
cancel = myutils.install_package_msg(pkg_name)
if cancel:
raise ModuleNotFoundError(
f'User aborted {pkg_name} installation'
... | [
"numpy.__version__.split",
"subprocess.check_call",
"cellacdc.myutils.install_package_msg"
] | [((180, 217), 'cellacdc.myutils.install_package_msg', 'myutils.install_package_msg', (['pkg_name'], {}), '(pkg_name)\n', (207, 217), False, 'from cellacdc import myutils\n'), ((334, 411), 'subprocess.check_call', 'subprocess.check_call', (["[sys.executable, '-m', 'pip', 'install', 'tensorflow']"], {}), "([sys.executabl... |
import aioredis
import trafaret as t
import yaml
from aiohttp import web
CONFIG_TRAFARET = t.Dict(
{
t.Key('redis'): t.Dict(
{
'port': t.Int(),
'host': t.String(),
'db': t.Int(),
'minsize': t.Int(),
'maxsize': t.In... | [
"aioredis.create_redis_pool",
"trafaret.String",
"yaml.load",
"trafaret.Key",
"aiohttp.web.HTTPBadRequest",
"trafaret.Int"
] | [((115, 129), 'trafaret.Key', 't.Key', (['"""redis"""'], {}), "('redis')\n", (120, 129), True, 'import trafaret as t\n'), ((388, 395), 'trafaret.Int', 't.Int', ([], {}), '()\n', (393, 395), True, 'import trafaret as t\n'), ((479, 491), 'yaml.load', 'yaml.load', (['f'], {}), '(f)\n', (488, 491), False, 'import yaml\n'),... |
### tensorflow==2.3.1
import tensorflow as tf
# Float16 Quantization - Input/Output=float32
height = 384
width = 384
converter = tf.lite.TFLiteConverter.from_saved_model('saved_model')
converter.optimizations = [tf.lite.Optimize.DEFAULT]
converter.target_spec.supported_types = [tf.float16]
tflite_model = converter.c... | [
"tensorflow.lite.TFLiteConverter.from_saved_model"
] | [((132, 187), 'tensorflow.lite.TFLiteConverter.from_saved_model', 'tf.lite.TFLiteConverter.from_saved_model', (['"""saved_model"""'], {}), "('saved_model')\n", (172, 187), True, 'import tensorflow as tf\n')] |
import os
from experiments.file_naming.single_target_classifier_indicator import SingleTargetClassifierIndicator
from project_info import project_dir
def get_single_target_tree_rule_dir() -> str:
mcars_dir: str = os.path.join(project_dir,
'models',
... | [
"os.path.exists",
"os.path.join",
"os.makedirs"
] | [((220, 283), 'os.path.join', 'os.path.join', (['project_dir', '"""models"""', '"""single_target_tree_rules"""'], {}), "(project_dir, 'models', 'single_target_tree_rules')\n", (232, 283), False, 'import os\n'), ((1657, 1713), 'os.path.join', 'os.path.join', (['rules_dir', 'f"""{relative_file_name}.json.gz"""'], {}), "(... |
from database import Base
from sqlalchemy import Column, Integer, String, Boolean, ForeignKey, DateTime, Float
from sqlalchemy.types import DateTime
from flask import Flask, request, jsonify, make_response
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = ... | [
"flask_sqlalchemy.SQLAlchemy",
"sqlalchemy.String",
"sqlalchemy.Column",
"flask.Flask"
] | [((257, 272), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (262, 272), False, 'from flask import Flask, request, jsonify, make_response\n'), ((332, 347), 'flask_sqlalchemy.SQLAlchemy', 'SQLAlchemy', (['app'], {}), '(app)\n', (342, 347), False, 'from flask_sqlalchemy import SQLAlchemy\n'), ((411, 444), 's... |
#####################################
##### Class to Query Census API #####
#####################################
import requests
import json
import pandas as pd
import datascience as ds
from .utils import *
class CensusQuery:
"""Object to query US Census API"""
_url_endings = {
"acs5": "acs/acs5",
"acs1": "ac... | [
"pandas.DataFrame",
"json.loads",
"datascience.Table.from_df",
"requests.get"
] | [((2941, 2966), 'requests.get', 'requests.get', (['url', 'params'], {}), '(url, params)\n', (2953, 2966), False, 'import requests\n'), ((3099, 3135), 'pandas.DataFrame', 'pd.DataFrame', (['text[1:]'], {'columns': 'cols'}), '(text[1:], columns=cols)\n', (3111, 3135), True, 'import pandas as pd\n'), ((2984, 3009), 'json.... |
import os, sys, re, json, random, importlib
import numpy as np
import pandas as pd
from collections import OrderedDict
from tqdm import tqdm
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
import logomaker as lm
from venn import venn
from venn import generate_petal_labels, draw_venn
from scipy.s... | [
"pandas.read_csv",
"numpy.log",
"numpy.array",
"seaborn.scatterplot",
"scipy.stats.pearsonr",
"seaborn.regplot",
"os.listdir",
"numpy.where",
"scipy.cluster.hierarchy.linkage",
"matplotlib.pyplot.scatter",
"logomaker.alignment_to_matrix",
"pandas.DataFrame",
"collections.OrderedDict",
"mat... | [((412, 445), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (435, 445), False, 'import warnings\n'), ((3833, 3870), 'pandas.read_csv', 'pd.read_csv', (['df_filename'], {'index_col': '(0)'}), '(df_filename, index_col=0)\n', (3844, 3870), True, 'import pandas as pd\n'), ((9... |
from flask_script import Manager, Server
from flask_migrate import Migrate, MigrateCommand
from app import create_app, db
from app.models import User, Article, Category, Comment, Quote
app = create_app('development')
manager = Manager(app)
migrate= Migrate(app, db)
manager.add_command('db', MigrateCommand)
manager... | [
"flask_script.Manager",
"flask_migrate.Migrate",
"app.create_app"
] | [((193, 218), 'app.create_app', 'create_app', (['"""development"""'], {}), "('development')\n", (203, 218), False, 'from app import create_app, db\n'), ((230, 242), 'flask_script.Manager', 'Manager', (['app'], {}), '(app)\n', (237, 242), False, 'from flask_script import Manager, Server\n'), ((252, 268), 'flask_migrate.... |
from django.urls import path
from . import views
urlpatterns = [
path("", views.home, name="home"),
path("faq/", views.faq, name="faq"),
path("plagiarism_policy/", views.plagiarism_policy,
name="plagiarism_policy"),
path("privacy_policy/", views.privacy_policy, name="privacy_policy"),
path... | [
"django.urls.path"
] | [((70, 103), 'django.urls.path', 'path', (['""""""', 'views.home'], {'name': '"""home"""'}), "('', views.home, name='home')\n", (74, 103), False, 'from django.urls import path\n'), ((109, 144), 'django.urls.path', 'path', (['"""faq/"""', 'views.faq'], {'name': '"""faq"""'}), "('faq/', views.faq, name='faq')\n", (113, 1... |
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# ... | [
"heat.engine.plugin_manager.PluginManager",
"stevedore.extension.ExtensionManager",
"heat.engine.clients.initialise",
"heat.engine.environment.Environment",
"heat.engine.environment.read_global_environment",
"heat.engine.plugin_manager.PluginMapping"
] | [((1307, 1376), 'stevedore.extension.ExtensionManager', 'extension.ExtensionManager', ([], {'namespace': 'namespace', 'invoke_on_load': '(False)'}), '(namespace=namespace, invoke_on_load=False)\n', (1333, 1376), False, 'from stevedore import extension\n'), ((1669, 1689), 'heat.engine.clients.initialise', 'clients.initi... |
import os
from datetime import datetime
directory = "../runs"
current = os.path.join(directory, ".current")
class Run:
def __init__(self, runName):
run = os.path.join(directory, runName)
self.model = os.path.join(run, "model.h5")
self.log = os.path.join(run, "log.csv")
self.accurac... | [
"os.path.isfile",
"datetime.datetime.now",
"os.path.join",
"os.mkdir"
] | [((73, 108), 'os.path.join', 'os.path.join', (['directory', '""".current"""'], {}), "(directory, '.current')\n", (85, 108), False, 'import os\n'), ((550, 582), 'os.path.join', 'os.path.join', (['directory', 'runName'], {}), '(directory, runName)\n', (562, 582), False, 'import os\n'), ((587, 603), 'os.mkdir', 'os.mkdir'... |
from utils import *
import torch
import sys
import numpy as np
import time
import torchvision
from torch.autograd import Variable
import torchvision.transforms as transforms
import torchvision.datasets as datasets
def validate_pgd(val_loader, model, criterion, K, step, configs, logger, save_image=False, HE=False):
... | [
"torchvision.transforms.CenterCrop",
"torchvision.transforms.ToTensor",
"torch.max",
"torch.min",
"numpy.array",
"torch.autograd.grad",
"torchvision.transforms.Resize",
"torch.no_grad",
"sys.stdout.flush",
"torch.autograd.Variable",
"time.time"
] | [((873, 884), 'time.time', 'time.time', ([], {}), '()\n', (882, 884), False, 'import time\n'), ((4940, 4951), 'time.time', 'time.time', ([], {}), '()\n', (4949, 4951), False, 'import time\n'), ((7509, 7520), 'time.time', 'time.time', ([], {}), '()\n', (7518, 7520), False, 'import time\n'), ((377, 405), 'numpy.array', '... |
import numpy as np
from numexpr_kernel import numexpr_kernel
from numba_kernel import numba_kernel
N = 10000
x = np.random.rand(N)
y = np.random.rand(N)
z = np.random.rand(N)
tau = np.random.rand(N)
r1 = numexpr_kernel(x, y, z, tau)
r1 = numexpr_kernel(x, y, z, tau)
r2 = np.zeros(N, dtype=float)
numba_kernel(x, y, z,... | [
"numexpr_kernel.numexpr_kernel",
"numpy.zeros",
"numba_kernel.numba_kernel",
"numpy.random.rand"
] | [((114, 131), 'numpy.random.rand', 'np.random.rand', (['N'], {}), '(N)\n', (128, 131), True, 'import numpy as np\n'), ((136, 153), 'numpy.random.rand', 'np.random.rand', (['N'], {}), '(N)\n', (150, 153), True, 'import numpy as np\n'), ((158, 175), 'numpy.random.rand', 'np.random.rand', (['N'], {}), '(N)\n', (172, 175),... |
"""
This module give the classification results for test data using SVM with RBF
kernel.
Email: <EMAIL>
Dtd: 2 - August - 2020
Parameters
----------
classification_type : string
DESCRIPTION - classification_type == "binary_class" loads binary classification artificial data.
classification_type == "... | [
"sklearn.metrics.f1_score",
"sklearn.metrics.confusion_matrix",
"os.makedirs",
"numpy.unique",
"sklearn.metrics.classification_report",
"os.getcwd",
"load_data_synthetic.get_data",
"numpy.max",
"sklearn.metrics.accuracy_score",
"numpy.save",
"sklearn.svm.SVC"
] | [((1369, 1380), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (1378, 1380), False, 'import os\n'), ((1867, 1896), 'load_data_synthetic.get_data', 'get_data', (['classification_type'], {}), '(classification_type)\n', (1875, 1896), False, 'from load_data_synthetic import get_data\n'), ((2376, 2412), 'sklearn.svm.SVC', 'svm... |
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from conditional import db
from conditional.models import models, old_models as zoo
import flask_migrate
# pylint: skip-file
old_engine = None
zoo_session = None
# Takes in param of SqlAlchemy Database Connection String
def... | [
"conditional.models.models.HousingEvalsSubmission",
"conditional.models.models.FreshmanEvalData",
"conditional.models.models.MemberSeminarAttendance",
"conditional.db.session.flush",
"conditional.models.old_models.Base.metadata.create_all",
"conditional.models.models.SpringEval",
"conditional.models.mod... | [((785, 834), 'sqlalchemy.create_engine', 'create_engine', (['database_url'], {'convert_unicode': '(True)'}), '(database_url, convert_unicode=True)\n', (798, 834), False, 'from sqlalchemy import create_engine\n'), ((1030, 1075), 'conditional.models.old_models.Base.metadata.create_all', 'zoo.Base.metadata.create_all', (... |
# Pro-Football-Reference.com
# TEAMS
import re, os
import uuid
import json
from datetime import datetime, date, time
from bs4 import BeautifulSoup
import bs4
from Constants import *
from PathUtils import *
from PluginSupport import *
from Serialization import *
from StringUtils import *
import ProFoo... | [
"ProFootballReferenceFranchiseScraper.GetFranchises",
"uuid.uuid4"
] | [((741, 774), 'ProFootballReferenceFranchiseScraper.GetFranchises', 'FranschiseScraper.GetFranchises', ([], {}), '()\n', (772, 774), True, 'import ProFootballReferenceFranchiseScraper as FranschiseScraper\n'), ((2277, 2289), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (2287, 2289), False, 'import uuid\n')] |
import torch
import numpy as np
import time
import datetime
import random
from Kfold import KFold
from split_data import DataManager
from transformers import BertTokenizer
from transformers import BertTokenizer
from torch.utils.data import TensorDataset, random_split
from torch.utils.data import DataLoader, RandomSamp... | [
"torch.cuda.is_available",
"datetime.timedelta",
"numpy.random.seed",
"torch.utils.data.SequentialSampler",
"numpy.argmax",
"torch.utils.data.TensorDataset",
"transformers.BertForSequenceClassification.from_pretrained",
"time.time",
"torch.cat",
"torch.device",
"torch.cuda.manual_seed_all",
"t... | [((638, 708), 'transformers.BertTokenizer.from_pretrained', 'BertTokenizer.from_pretrained', (['"""bert-base-uncased"""'], {'do_lower_case': '(True)'}), "('bert-base-uncased', do_lower_case=True)\n", (667, 708), False, 'from transformers import BertTokenizer\n'), ((1706, 1733), 'torch.cat', 'torch.cat', (['input_ids'],... |
#!/usr/bin/env python
# pylint: disable=invalid-name
""" Web-based proxy to a Kerberos KDC for Webathena. """
import base64
import json
import os
import select
import socket
import dns.resolver
from pyasn1.codec.der import decoder as der_decoder
from pyasn1.codec.der import encoder as der_encoder
from pyasn1.error im... | [
"select.select",
"socket.socket",
"os.urandom",
"base64.b64encode",
"json.dumps",
"base64.b64decode",
"werkzeug.routing.Rule",
"werkzeug.serving.run_simple",
"pyasn1.codec.der.encoder.encode",
"werkzeug.wrappers.Request"
] | [((884, 921), 'select.select', 'select.select', (['socks', '[]', '[]', 'timeout'], {}), '(socks, [], [], timeout)\n', (897, 921), False, 'import select\n'), ((7853, 7916), 'werkzeug.serving.run_simple', 'run_simple', (['ip', 'port', 'app'], {'use_debugger': '(True)', 'use_reloader': '(True)'}), '(ip, port, app, use_deb... |
# -*- coding: utf8 -*-
#
# DB migration 001 by 2017-11-03
#
# New statistics for subvolume - root diff in blocks / bytes
#
__author__ = 'sergey'
__NUMBER__ = 20171103001
def run(manager):
"""
:param manager: Database manager
:type manager: dedupsqlfs.db.sqlite.manager.DbManager|dedupsqlfs.db.mysql.manage... | [
"traceback.format_exc"
] | [((1639, 1661), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (1659, 1661), False, 'import traceback\n')] |
import pytest
@pytest.mark.parametrize("cli_options", [
('-k', 'notestdeselect',),
])
def test_autoexecute_yml_keywords_skipped(testdir, cli_options):
yml_file = testdir.makefile(".yml", """
---
markers:
- marker1
- marker2
---
- provider: python
type: assert
expression: "1"
""")
assert yml_fi... | [
"pytest.mark.parametrize"
] | [((17, 83), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""cli_options"""', "[('-k', 'notestdeselect')]"], {}), "('cli_options', [('-k', 'notestdeselect')])\n", (40, 83), False, 'import pytest\n')] |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import ipdb
import time
# Clustering penalties
class ClusterLoss(torch.nn.Module):
"""
Cluster loss comes from the SuBiC paper and consists of two losses. First is the Mean Entropy
Loss which makes the output to be clos... | [
"torch.cuda.LongTensor",
"torch.nn.functional.softmax",
"torch.nn.CrossEntropyLoss",
"torch.mean",
"torch.nn.functional.normalize",
"torch.sum",
"torch.nn.functional.log_softmax",
"torch.zeros"
] | [((981, 1014), 'torch.zeros', 'torch.zeros', (['[logits.shape[0], 1]'], {}), '([logits.shape[0], 1])\n', (992, 1014), False, 'import torch\n'), ((1116, 1132), 'torch.mean', 'torch.mean', (['sum1'], {}), '(sum1)\n', (1126, 1132), False, 'import torch\n'), ((1274, 1299), 'torch.mean', 'torch.mean', (['logits'], {'dim': '... |
import solana_rpc as rpc
def get_apr_from_rewards(rewards_data):
result = []
if rewards_data is not None:
if 'epochRewards' in rewards_data:
epoch_rewards = rewards_data['epochRewards']
for reward in epoch_rewards:
result.append({
'percent_c... | [
"solana_rpc.load_stake_account_rewards"
] | [((902, 960), 'solana_rpc.load_stake_account_rewards', 'rpc.load_stake_account_rewards', (["validator['stake_account']"], {}), "(validator['stake_account'])\n", (932, 960), True, 'import solana_rpc as rpc\n')] |
import re
class Solution:
def helper(self, expression: str) -> List[str]:
s = re.search("\{([^}{]+)\}", expression)
if not s: return {expression}
g = s.group(1)
result = set()
for c in g.split(','):
result |= self.helper(expression.replace('{' + g + '}', c, ... | [
"re.search"
] | [((92, 131), 're.search', 're.search', (['"""\\\\{([^}{]+)\\\\}"""', 'expression'], {}), "('\\\\{([^}{]+)\\\\}', expression)\n", (101, 131), False, 'import re\n')] |
from tensorflow.keras.callbacks import Callback
from poem_generator.word_generator import generate_poem
class PoemCallback(Callback):
def __init__(self, poems, seed_length, dictionary, single=True):
super(PoemCallback, self).__init__()
self.poems = poems
self.dictionary = dictionary
... | [
"poem_generator.word_generator.generate_poem"
] | [((610, 720), 'poem_generator.word_generator.generate_poem', 'generate_poem', (['self.model', 'self.reverse_dictionary', 'self.dictionary', 'self.seed_length'], {'single': 'self.single'}), '(self.model, self.reverse_dictionary, self.dictionary, self.\n seed_length, single=self.single)\n', (623, 720), False, 'from po... |
# encoding: utf-8
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Author: <NAME> (<EMAIL>)
#
from __future__ import absolute_import, division, unicode_literals
fr... | [
"mo_math.floor",
"zlib.decompressobj",
"mo_logs.Log.error",
"zipfile.ZipFile",
"io.BytesIO",
"struct.pack",
"gzip.GzipFile",
"zlib.crc32",
"tempfile.TemporaryFile",
"zlib.compressobj",
"time.time",
"mo_logs.Log.note"
] | [((7801, 7840), 'zlib.decompressobj', 'zlib.decompressobj', (['(16 + zlib.MAX_WBITS)'], {}), '(16 + zlib.MAX_WBITS)\n', (7819, 7840), False, 'import zlib\n'), ((9371, 9386), 'zlib.crc32', 'zlib.crc32', (["b''"], {}), "(b'')\n", (9381, 9386), False, 'import zlib\n'), ((9419, 9493), 'zlib.compressobj', 'zlib.compressobj'... |
from unittest.mock import patch
from dependent import parameter_dependent
@patch('math.sqrt')
def test_negative(mock_sqrt):
assert parameter_dependent(-1) == 0
mock_sqrt.assert_not_called()
@patch('math.sqrt')
def test_zero(mock_sqrt):
mock_sqrt.return_value = 0
assert parameter_dependent(0) == 0
... | [
"dependent.parameter_dependent",
"unittest.mock.patch"
] | [((77, 95), 'unittest.mock.patch', 'patch', (['"""math.sqrt"""'], {}), "('math.sqrt')\n", (82, 95), False, 'from unittest.mock import patch\n'), ((203, 221), 'unittest.mock.patch', 'patch', (['"""math.sqrt"""'], {}), "('math.sqrt')\n", (208, 221), False, 'from unittest.mock import patch\n'), ((362, 380), 'unittest.mock... |
"""Tests a package installation on a user OS."""
import pathlib
import subprocess
import unittest
class TestPlErrPackage(unittest.TestCase):
def test_plerr_error_getter(self):
# Given: a command to get a description of a pylint error by an
# error code.
command = ['python3', '-m', 'plerr',... | [
"subprocess.Popen",
"pathlib.Path"
] | [((383, 456), 'subprocess.Popen', 'subprocess.Popen', (['command'], {'stdout': 'subprocess.PIPE', 'stderr': 'subprocess.PIPE'}), '(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n', (399, 456), False, 'import subprocess\n'), ((1214, 1287), 'subprocess.Popen', 'subprocess.Popen', (['command'], {'stdout': 'subp... |
import os
_lab_components = """from api2db.ingest import *
CACHE=True # Caches API data so that only a single API call is made if True
def import_target():
return None
def pre_process():
return None
def data_features():
return None
def post_process():
return None
if __name__ == "__main__":
... | [
"os.path.isdir",
"os.path.join",
"os.makedirs",
"os.getcwd"
] | [((2460, 2471), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (2469, 2471), False, 'import os\n'), ((2498, 2525), 'os.path.isdir', 'os.path.isdir', (['lab_dir_path'], {}), '(lab_dir_path)\n', (2511, 2525), False, 'import os\n'), ((2535, 2560), 'os.makedirs', 'os.makedirs', (['lab_dir_path'], {}), '(lab_dir_path)\n', (254... |
#-*- coding: utf-8 -*-
"""Forms for the django-shop app."""
from django import forms
from django.conf import settings
from django.forms.models import modelformset_factory
from django.utils.translation import ugettext_lazy as _
from shop.backends_pool import backends_pool
from shop.models.cartmodel import CartItem
from... | [
"django.utils.translation.ugettext_lazy",
"shop.backends_pool.backends_pool.get_shipping_backends_list",
"shop.backends_pool.backends_pool.get_payment_backends_list",
"shop.util.loader.load_class",
"django.forms.IntegerField"
] | [((419, 461), 'shop.backends_pool.backends_pool.get_shipping_backends_list', 'backends_pool.get_shipping_backends_list', ([], {}), '()\n', (459, 461), False, 'from shop.backends_pool import backends_pool\n'), ((640, 681), 'shop.backends_pool.backends_pool.get_payment_backends_list', 'backends_pool.get_payment_backends_... |
from src.access import UserRemoveAccess
from generate_access_data import generate_access_data
def test_remove_user_access():
sessions = generate_access_data()
user = sessions['user'].users.get('user')
useraccess = UserRemoveAccess(sessions['user'], user)
manageraccess = UserRemoveAccess(sessions['mana... | [
"generate_access_data.generate_access_data",
"src.access.UserRemoveAccess"
] | [((142, 164), 'generate_access_data.generate_access_data', 'generate_access_data', ([], {}), '()\n', (162, 164), False, 'from generate_access_data import generate_access_data\n'), ((228, 268), 'src.access.UserRemoveAccess', 'UserRemoveAccess', (["sessions['user']", 'user'], {}), "(sessions['user'], user)\n", (244, 268)... |
import re
import unicodedata
# Remove empty brackets (that could happen if the contents have been removed already
# e.g. for citation ( [3] [4] ) -> ( ) -> nothing
def remove_brackets_without_words(text: str) -> str:
fixed = re.sub(r"\([\W\s]*\)", " ", text)
fixed = re.sub(r"\[[\W\s]*\]", " ", fixed)
... | [
"re.sub",
"unicodedata.category"
] | [((238, 274), 're.sub', 're.sub', (['"""\\\\([\\\\W\\\\s]*\\\\)"""', '""" """', 'text'], {}), "('\\\\([\\\\W\\\\s]*\\\\)', ' ', text)\n", (244, 274), False, 'import re\n'), ((285, 322), 're.sub', 're.sub', (['"""\\\\[[\\\\W\\\\s]*\\\\]"""', '""" """', 'fixed'], {}), "('\\\\[[\\\\W\\\\s]*\\\\]', ' ', fixed)\n", (291, 32... |
#!/usr/bin/env python3
#
# Import built in packages
#
import logging
import platform
import os
import time
import socket
import subprocess
import signal
import psutil
from .util import setup_logger
from .util import PylinxException
import re
# Import 3th party modules:
# - wexpect/pexpect to launch... | [
"logging.getLogger",
"os.kill",
"socket.socket",
"re.compile",
"subprocess.Popen",
"pexpect.spawn",
"psutil.Process",
"os.path.join",
"time.sleep",
"os.path.realpath",
"platform.system",
"re.findall"
] | [((668, 695), 'logging.getLogger', 'logging.getLogger', (['"""pylinx"""'], {}), "('pylinx')\n", (685, 695), False, 'import logging\n'), ((357, 374), 'platform.system', 'platform.system', ([], {}), '()\n', (372, 374), False, 'import platform\n'), ((566, 592), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '... |
from behave import *
import requests
from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token
use_step_matcher("re")
@given("that I am a registered host of privilege walk events and exists events on my username")
def step_impl(context):
context.username = "12thMan"
conte... | [
"requests.post",
"requests.get",
"django.contrib.auth.models.User.objects.filter",
"django.contrib.auth.models.User.objects.create_user",
"rest_framework.authtoken.models.Token.objects.get_or_create"
] | [((450, 525), 'django.contrib.auth.models.User.objects.create_user', 'User.objects.create_user', (['context.username', 'context.email', 'context.password'], {}), '(context.username, context.email, context.password)\n', (474, 525), False, 'from django.contrib.auth.models import User\n'), ((672, 711), 'django.contrib.aut... |
"""soft_encoder.py: Encoding sentence with LSTM.
It encodes sentence with Bi-LSTM.
After encoding, it uses all tokens for sentence, and extract some parts for trigger.
Written in 2020 by <NAME>.
"""
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
import torch.nn as nn
import torch
from ..uti... | [
"torch.nn.Dropout",
"torch.nn.LSTM",
"torch.stack",
"torch.tensor",
"torch.nn.utils.rnn.pack_padded_sequence",
"torch.nn.utils.rnn.pad_packed_sequence",
"torch.FloatTensor",
"torch.cat"
] | [((2808, 2869), 'torch.nn.utils.rnn.pack_padded_sequence', 'pack_padded_sequence', (['sorted_seq_tensor', 'sorted_seq_len', '(True)'], {}), '(sorted_seq_tensor, sorted_seq_len, True)\n', (2828, 2869), False, 'from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence\n'), ((2940, 2985), 'torch.nn.utils.rn... |
"""Forms for ox_herd commands.
"""
from wtforms import StringField
from ox_herd.core.plugins import base
class BackupForm(base.GenericOxForm):
"""Use this form to enter parameters for a new backup job.
"""
bucket_name = StringField(
'bucket_name', [], description=(
'Name of AWS bucke... | [
"wtforms.StringField"
] | [((236, 325), 'wtforms.StringField', 'StringField', (['"""bucket_name"""', '[]'], {'description': '"""Name of AWS bucket to put backup into."""'}), "('bucket_name', [], description=\n 'Name of AWS bucket to put backup into.')\n", (247, 325), False, 'from wtforms import StringField\n'), ((364, 471), 'wtforms.StringFi... |
import numpy as np
import operator
# TODO: Make Mutation Operator.
class TerminationCriteria:
@staticmethod
def _convergence_check(convergence_ratio, population_fitness):
if abs((np.max(population_fitness) - np.mean(population_fitness)) / np.mean(
population_fitness)) <= convergence_... | [
"numpy.random.choice",
"numpy.array",
"numpy.mean",
"numpy.max"
] | [((674, 700), 'numpy.max', 'np.max', (['population_fitness'], {}), '(population_fitness)\n', (680, 700), True, 'import numpy as np\n'), ((3339, 3371), 'numpy.random.choice', 'np.random.choice', (['contestants', 'm'], {}), '(contestants, m)\n', (3355, 3371), True, 'import numpy as np\n'), ((3744, 3762), 'numpy.array', '... |
from distutils.core import setup
setup(
name = 'niu',
packages = ['niu'],
version = '0.2',
description = 'A grouping and pairing library',
author = '<NAME>',
author_email = '<EMAIL>',
url = 'https://github.com/gabeabrams/niu',
download_url = 'https://github.com/gabeabrams/niu/archive/0.1.tar.gz',
key... | [
"distutils.core.setup"
] | [((34, 394), 'distutils.core.setup', 'setup', ([], {'name': '"""niu"""', 'packages': "['niu']", 'version': '"""0.2"""', 'description': '"""A grouping and pairing library"""', 'author': '"""<NAME>"""', 'author_email': '"""<EMAIL>"""', 'url': '"""https://github.com/gabeabrams/niu"""', 'download_url': '"""https://github.c... |
import logging
from datetime import timedelta
from flask import Flask, render_template, redirect, request, url_for, flash
from flask_login import LoginManager, login_user, logout_user, current_user
from preston.crest import Preston as CREST
from preston.xmlapi import Preston as XMLAPI
from auth.shared import db, evea... | [
"flask.render_template",
"flask_login.LoginManager",
"auth.models.User",
"flask.flash",
"preston.crest.Preston",
"flask.Flask",
"auth.shared.db.session.add",
"logging.Formatter",
"flask_login.login_user",
"flask_login.logout_user",
"auth.models.User.query.filter_by",
"flask.url_for",
"loggin... | [((481, 496), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (486, 496), False, 'from flask import Flask, render_template, redirect, request, url_for, flash\n'), ((530, 548), 'datetime.timedelta', 'timedelta', ([], {'days': '(14)'}), '(days=14)\n', (539, 548), False, 'from datetime import timedelta\n'), ((... |
import MiniNero
import ed25519
import binascii
import PaperWallet
import cherrypy
import os
import time
import bitmonerod
import SimpleXMR2
import SimpleServer
message = "send0d000114545737471em2WCg9QKxRxbo6S3xKF2K4UDvdu6hMc"
message = "send0d0114545747771em2WCg9QKxRxbo6S3xKF2K4UDvdu6hMc"
sec = raw_input("sec?")
print... | [
"SimpleServer.Signature"
] | [((321, 357), 'SimpleServer.Signature', 'SimpleServer.Signature', (['message', 'sec'], {}), '(message, sec)\n', (343, 357), False, 'import SimpleServer\n')] |
from vedacore.misc import registry, build_from_cfg
def build_loss(cfg):
loss = build_from_cfg(cfg, registry, 'loss')
return loss
| [
"vedacore.misc.build_from_cfg"
] | [((85, 122), 'vedacore.misc.build_from_cfg', 'build_from_cfg', (['cfg', 'registry', '"""loss"""'], {}), "(cfg, registry, 'loss')\n", (99, 122), False, 'from vedacore.misc import registry, build_from_cfg\n')] |
# -*- coding: UTF-8 -*-
"""
Created by <NAME> <<EMAIL>> on 19/06/2016.
"""
import os
from datetime import datetime
from django.core.management.base import BaseCommand, CommandError
from django_rest_scaffold.settings import DJANGO_REST_SCAFFOLD_SETTINGS as SETTINGS
class Command(BaseCommand):
help = 'Creates ... | [
"os.path.exists",
"os.path.join",
"datetime.datetime.now",
"django.core.management.base.CommandError"
] | [((1556, 1608), 'os.path.join', 'os.path.join', (["SETTINGS['APPS_FOLDER']", 'resource_name'], {}), "(SETTINGS['APPS_FOLDER'], resource_name)\n", (1568, 1608), False, 'import os\n'), ((1932, 1972), 'os.path.join', 'os.path.join', (['resource_path', '"""models.py"""'], {}), "(resource_path, 'models.py')\n", (1944, 1972)... |
#
# derl: CLI Utility for searching for dead URLs <https://github.com/tpiekarski/derl>
# ---
# Copyright 2020 <NAME> <<EMAIL>>
#
from time import perf_counter
from derl.model.stats import Stats
class Singleton(type):
_instances = {}
def __call__(cls: "Singleton", *args: tuple, **kwargs: dict) -> "Tracker":... | [
"derl.model.stats.Stats",
"time.perf_counter"
] | [((570, 577), 'derl.model.stats.Stats', 'Stats', ([], {}), '()\n', (575, 577), False, 'from derl.model.stats import Stats\n'), ((1075, 1082), 'derl.model.stats.Stats', 'Stats', ([], {}), '()\n', (1080, 1082), False, 'from derl.model.stats import Stats\n'), ((694, 708), 'time.perf_counter', 'perf_counter', ([], {}), '()... |
import random
import copy
rr = random.Random ( 22 )
def readNameList(fn):
f = open(fn,"r")
if f == None:
print ( f"Invalid file {fn} - failed to open" )
return None
dt = f.readlines()
f.close()
for i in range (len(dt)):
s = dt[i].rstrip()
dt[i] = s
return dt
... | [
"random.Random",
"copy.deepcopy"
] | [((32, 49), 'random.Random', 'random.Random', (['(22)'], {}), '(22)\n', (45, 49), False, 'import random\n'), ((500, 522), 'copy.deepcopy', 'copy.deepcopy', (['letters'], {}), '(letters)\n', (513, 522), False, 'import copy\n')] |
import numpy as np
import torch
import anndata
from celligner2.othermodels.trvae.trvae import trVAE
from celligner2.trainers.trvae.unsupervised import trVAETrainer
def trvae_operate(
network: trVAE,
data: anndata,
condition_key: str = None,
size_factor_key: str = None,
n_epoch... | [
"celligner2.trainers.trvae.unsupervised.trVAETrainer",
"torch.from_numpy",
"celligner2.othermodels.trvae.trvae.trVAE",
"torch.cat"
] | [((2141, 2387), 'celligner2.othermodels.trvae.trvae.trVAE', 'trVAE', (['network.input_dim'], {'conditions': 'conditions', 'hidden_layer_sizes': 'network.hidden_layer_sizes', 'latent_dim': 'network.latent_dim', 'dr_rate': 'new_dr', 'use_mmd': 'network.use_mmd', 'mmd_boundary': 'network.mmd_boundary', 'recon_loss': 'netw... |
import datetime
import remi
import core.globals
connected_clients = {} # Dict with key=session id of App Instance and value=ws_client.client_address of App Instance
connected_clients['number'] = 0 # Special Dict Field for amount of active connections
client_route_url_to... | [
"datetime.datetime.now",
"remi.server.clients.items"
] | [((778, 805), 'remi.server.clients.items', 'remi.server.clients.items', ([], {}), '()\n', (803, 805), False, 'import remi\n'), ((1498, 1521), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (1519, 1521), False, 'import datetime\n'), ((1898, 1921), 'datetime.datetime.now', 'datetime.datetime.now', ([... |
import time
from os import system
from django.http import HttpResponse
from django.template import Context, loader
from django.views.decorators.csrf import csrf_exempt # Pour des formulaires POST libres
from jla_utils.utils import Fichier
from .models import ElementDialogue
class Tunnel:
def __init__(self, long... | [
"django.http.HttpResponse",
"time.sleep",
"django.template.Context",
"os.system",
"time.localtime",
"django.template.loader.get_template",
"jla_utils.utils.Fichier"
] | [((1154, 1179), 'jla_utils.utils.Fichier', 'Fichier', (['nomFichTunnel', '(0)'], {}), '(nomFichTunnel, 0)\n', (1161, 1179), False, 'from jla_utils.utils import Fichier\n'), ((3284, 3341), 'django.template.loader.get_template', 'loader.get_template', (['"""cestmoilechef/petite_merdasse.html"""'], {}), "('cestmoilechef/p... |
#!/usr/bin/env python
from unittest import TestCase
from boutiques.bosh import bosh
from boutiques.bids import validate_bids
from boutiques import __file__ as bofile
from jsonschema.exceptions import ValidationError
from boutiques.validator import DescriptorValidationError
import os.path as op
import simplejson as jso... | [
"boutiques.bosh.bosh",
"os.path.split"
] | [((493, 522), 'boutiques.bosh.bosh', 'bosh', (["['validate', fil, '-b']"], {}), "(['validate', fil, '-b'])\n", (497, 522), False, 'from boutiques.bosh import bosh\n'), ((413, 429), 'os.path.split', 'op.split', (['bofile'], {}), '(bofile)\n', (421, 429), True, 'import os.path as op\n'), ((577, 593), 'os.path.split', 'op... |
from __future__ import print_function
import pathlib
from builtins import object, str
from typing import Dict
from empire.server.common import helpers
from empire.server.common.module_models import PydanticModule
from empire.server.utils import data_util
from empire.server.utils.module_util import handle_error_messag... | [
"builtins.str"
] | [((1685, 1709), 'builtins.str', 'str', (['sql_instance_source'], {}), '(sql_instance_source)\n', (1688, 1709), False, 'from builtins import object, str\n')] |
from collections import defaultdict
from itertools import permutations
import networkx as nx
def air_duct_spelunking(inp, part1=True):
max_y = len(inp)
max_x = max(len(line) for line in inp)
grid = defaultdict(lambda: '#')
numbers = defaultdict(lambda: '')
route_list = defaultdict(lambda: 0)
... | [
"networkx.shortest_path_length",
"collections.defaultdict",
"networkx.Graph"
] | [((213, 238), 'collections.defaultdict', 'defaultdict', (["(lambda : '#')"], {}), "(lambda : '#')\n", (224, 238), False, 'from collections import defaultdict\n'), ((252, 276), 'collections.defaultdict', 'defaultdict', (["(lambda : '')"], {}), "(lambda : '')\n", (263, 276), False, 'from collections import defaultdict\n'... |
import unittest2
from openerp.osv.orm import except_orm
import openerp.tests.common as common
from openerp.tools import mute_logger
class TestServerActionsBase(common.TransactionCase):
def setUp(self):
super(TestServerActionsBase, self).setUp()
cr, uid = self.cr, self.uid
# Models
... | [
"openerp.workflow.clear_cache",
"openerp.tools.mute_logger",
"unittest2.main"
] | [((18225, 18289), 'openerp.tools.mute_logger', 'mute_logger', (['"""openerp.addons.base.ir.ir_model"""', '"""openerp.models"""'], {}), "('openerp.addons.base.ir.ir_model', 'openerp.models')\n", (18236, 18289), False, 'from openerp.tools import mute_logger\n'), ((20104, 20120), 'unittest2.main', 'unittest2.main', ([], {... |
# -*- coding: utf-8 -*-
"""
Created on 2021-03-11 18:53:58
---------
@summary:
抓糗事百科的案例
---------
@author: Administrator
"""
import feapder
class Spider(feapder.AirSpider):
def start_requests(self):
for page_num in range(1, 2):
url = "https://www.qiushibaike.com/8hr/page/{}/".format(page_... | [
"feapder.Request"
] | [((343, 363), 'feapder.Request', 'feapder.Request', (['url'], {}), '(url)\n', (358, 363), False, 'import feapder\n'), ((796, 857), 'feapder.Request', 'feapder.Request', (['url'], {'callback': 'self.parse_detail', 'title': 'title'}), '(url, callback=self.parse_detail, title=title)\n', (811, 857), False, 'import feapder\... |
"""Fixtures for tests."""
import json
import boto3
from moto import mock_dynamodb2
import pytest
from fixtures import LambdaContextMock
import payloads
@pytest.fixture
def event():
"""Return parsed event."""
with open('tests/payloads/success.json') as json_data:
return json.load(json_data)
@pytest... | [
"boto3.client",
"moto.mock_dynamodb2",
"json.load",
"fixtures.LambdaContextMock",
"pytest.fixture"
] | [((1052, 1080), 'pytest.fixture', 'pytest.fixture', ([], {'autouse': '(True)'}), '(autouse=True)\n', (1066, 1080), False, 'import pytest\n'), ((1207, 1235), 'pytest.fixture', 'pytest.fixture', ([], {'autouse': '(True)'}), '(autouse=True)\n', (1221, 1235), False, 'import pytest\n'), ((393, 412), 'fixtures.LambdaContextM... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
# <NAME> (<EMAIL>)
import py_trees as pt
import py_trees_ros as ptr
import time
import numpy as np
import rospy
import tf
import actionlib
# from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal
from smarc_msgs.msg import GotoWaypointAction, Got... | [
"std_srvs.srv.SetBool",
"numpy.radians",
"rospy.logerr",
"rospy.logwarn",
"imc_ros_bridge.msg.EstimatedState",
"numpy.argsort",
"py_trees.behaviour.Behaviour.__init__",
"numpy.array",
"rospy.logwarn_throttle",
"tf.TransformListener",
"imc_ros_bridge.msg.PlanDBState",
"imc_ros_bridge.msg.PlanDB... | [((1112, 1138), 'py_trees.blackboard.Blackboard', 'pt.blackboard.Blackboard', ([], {}), '()\n', (1136, 1138), True, 'import py_trees as pt\n'), ((1238, 1245), 'std_msgs.msg.Empty', 'Empty', ([], {}), '()\n', (1243, 1245), False, 'from std_msgs.msg import Float64, Header, Bool, Empty\n'), ((1297, 1345), 'rospy.Publisher... |
from __future__ import annotations
import logging
import os
import os.path
from ..util import gcs
logger = logging.getLogger(os.path.basename(__file__))
class Image:
def __init__(self, url) -> None:
self.url = url
def __str__(self) -> str:
return self.url
def delete(self):
gcs... | [
"os.path.basename"
] | [((128, 154), 'os.path.basename', 'os.path.basename', (['__file__'], {}), '(__file__)\n', (144, 154), False, 'import os\n')] |