code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
"""
The ``cpp_pimpl`` test project.
"""
from testing.hierarchies import clike, directory, file, namespace
def default_class_hierarchy_dict():
"""Return the default class hierarchy dictionary."""
return {
namespace("pimpl"): {
clike("class", "Planet"): {},
clike("class", "Earth... | [
"testing.hierarchies.directory",
"testing.hierarchies.namespace",
"testing.hierarchies.file",
"testing.hierarchies.clike"
] | [((223, 241), 'testing.hierarchies.namespace', 'namespace', (['"""pimpl"""'], {}), "('pimpl')\n", (232, 241), False, 'from testing.hierarchies import clike, directory, file, namespace\n'), ((831, 851), 'testing.hierarchies.directory', 'directory', (['"""include"""'], {}), "('include')\n", (840, 851), False, 'from testi... |
"""
The implementation of some losses based on Tensorflow.
@Author: <NAME>
@Author: <NAME>
@Github: https://github.com/luyanger1799
@Project: https://github.com/luyanger1799/amazing-semantic-segmentation
"""
import tensorflow as tf
import numpy as np
backend = tf.keras.backend
def mix_loss(labels, logits):
retur... | [
"tensorflow.reduce_sum",
"tensorflow.constant",
"tensorflow.nn.softmax",
"tensorflow.reshape",
"tensorflow.reduce_mean",
"tensorflow.cast",
"tensorflow.log"
] | [((703, 730), 'tensorflow.cast', 'tf.cast', (['labels', 'tf.float32'], {}), '(labels, tf.float32)\n', (710, 730), True, 'import tensorflow as tf\n'), ((746, 773), 'tensorflow.reshape', 'tf.reshape', (['logits', '(-1, 4)'], {}), '(logits, (-1, 4))\n', (756, 773), True, 'import tensorflow as tf\n'), ((807, 831), 'tensorf... |
from direct.directnotify import DirectNotifyGlobal
from toontown.toonbase import ToontownBattleGlobals
from toontown.suit import SuitDNA
BattleExperienceAINotify = DirectNotifyGlobal.directNotify.newCategory('BattleExprienceAI')
def getSkillGained(toonSkillPtsGained, toonId, track):
exp = 0
expList = toonSkill... | [
"toontown.suit.SuitDNA.suitDepts.index",
"direct.directnotify.DirectNotifyGlobal.directNotify.newCategory",
"toontown.toonbase.ToontownBattleGlobals.encodeUber",
"toontown.suit.SuitDNA.suitHeadTypes.index"
] | [((164, 228), 'direct.directnotify.DirectNotifyGlobal.directNotify.newCategory', 'DirectNotifyGlobal.directNotify.newCategory', (['"""BattleExprienceAI"""'], {}), "('BattleExprienceAI')\n", (207, 228), False, 'from direct.directnotify import DirectNotifyGlobal\n'), ((2715, 2760), 'toontown.suit.SuitDNA.suitDepts.index'... |
import torch
import torch.optim as optim
import sys
import os
import argparse
import tokenization
from torch.optim import lr_scheduler
from loss import registry as loss_f
from loader import registry as loader
from model import registry as Producer
from evaluate import overall
#hyper-parameters
parser = argparse.Argum... | [
"torch.optim.lr_scheduler.ExponentialLR",
"argparse.ArgumentParser",
"evaluate.overall",
"sys.exit",
"tokenization.FullTokenizer"
] | [((306, 396), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""contrastive learning framework for word vector"""'}), "(description=\n 'contrastive learning framework for word vector')\n", (329, 396), False, 'import argparse\n'), ((2527, 2616), 'tokenization.FullTokenizer', 'tokenization... |
import os, sys
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
import tensorflow as tf
import cv2
import numpy as np
sys.path.insert(1, os.path.join(sys.path[0], '/mywork/tensorflow-tuts/sd19reader'))
from batches2patches_tensorflow import GetFuncToPatches, GetFuncOverlapAdd
from myutils import describe
from vizutils import ... | [
"numpy.prod",
"tensorflow.InteractiveSession",
"tensorflow.initialize_all_variables",
"cv2.imread",
"tensorflow.placeholder",
"batches2patches_tensorflow.GetFuncOverlapAdd",
"os.path.join",
"cv2.imshow",
"os.path.realpath",
"cv2.waitKey",
"cv2.getTrackbarPos",
"numpy.expand_dims",
"batches2p... | [((469, 512), 'os.path.join', 'os.path.join', (['path2file', '"""Lenna_noise1.png"""'], {}), "(path2file, 'Lenna_noise1.png')\n", (481, 512), False, 'import os, sys\n'), ((631, 679), 'numpy.pad', 'np.pad', (['testim', '[(1, 1), (1, 1), (0, 0)]', '"""edge"""'], {}), "(testim, [(1, 1), (1, 1), (0, 0)], 'edge')\n", (637, ... |
import torch
import torch.nn as nn
from .base_module import BaseModule
class BottleneckResidual(BaseModule):
def __init__(self,in_feature,out_featue,hidden_feature=None,stride=1,**kwargs):
super(BottleneckResidual,self).__init__(in_feature,out_featue,stride,**kwargs)
if hidden_feature is None:
... | [
"torch.nn.Conv2d"
] | [((387, 441), 'torch.nn.Conv2d', 'nn.Conv2d', (['in_feature', 'hidden_feature', '(1)', '(1)'], {'padding': '(0)'}), '(in_feature, hidden_feature, 1, 1, padding=0)\n', (396, 441), True, 'import torch.nn as nn\n'), ((459, 522), 'torch.nn.Conv2d', 'nn.Conv2d', (['hidden_feature', 'hidden_feature', '(3)', 'stride'], {'padd... |
import unittest
from project.card.magic_card import MagicCard
class TestMagicCard(unittest.TestCase):
def test_set_attr(self):
tc = MagicCard('card')
self.assertEqual(tc.name, 'card')
self.assertEqual(tc.damage_points, 5)
self.assertEqual(tc.health_points, 80)
self.assertE... | [
"project.card.magic_card.MagicCard"
] | [((147, 164), 'project.card.magic_card.MagicCard', 'MagicCard', (['"""card"""'], {}), "('card')\n", (156, 164), False, 'from project.card.magic_card import MagicCard\n'), ((650, 667), 'project.card.magic_card.MagicCard', 'MagicCard', (['"""test"""'], {}), "('test')\n", (659, 667), False, 'from project.card.magic_card i... |
# -*- coding: utf-8 -*-
import unittest
from pydruid.db.api import rows_from_chunks
class RowsFromChunksTestSuite(unittest.TestCase):
def test_rows_from_chunks_empty(self):
chunks = []
expected = []
result = list(rows_from_chunks(chunks))
self.assertEquals(result, expected)
... | [
"unittest.main",
"pydruid.db.api.rows_from_chunks"
] | [((1681, 1696), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1694, 1696), False, 'import unittest\n'), ((246, 270), 'pydruid.db.api.rows_from_chunks', 'rows_from_chunks', (['chunks'], {}), '(chunks)\n', (262, 270), False, 'from pydruid.db.api import rows_from_chunks\n'), ((592, 616), 'pydruid.db.api.rows_from_c... |
#!/usr/bin/env python
import rospy
import cv2
import numpy as np
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
import time
import os
'''
CAMERA NODE RUNNING AT 10HZ
RECORD ALL IMAGES
'''
# Node to obtain call camera data. Separate I/O pipeline
rospy.loginfo('Init Cameras...')
cam_fro... | [
"cv2.imwrite",
"rospy.is_shutdown",
"rospy.init_node",
"cv2.imshow",
"cv_bridge.CvBridge",
"cv2.waitKey",
"rospy.Rate",
"cv2.VideoCapture",
"os.mkdir",
"cv2.destroyAllWindows",
"rospy.Publisher",
"time.time",
"rospy.loginfo"
] | [((280, 312), 'rospy.loginfo', 'rospy.loginfo', (['"""Init Cameras..."""'], {}), "('Init Cameras...')\n", (293, 312), False, 'import rospy\n'), ((325, 344), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(1)'], {}), '(1)\n', (341, 344), False, 'import cv2\n'), ((570, 584), 'os.mkdir', 'os.mkdir', (['path'], {}), '(path)\n'... |
import os
import psycopg2
from psycopg2 import pool
from dotenv import load_dotenv
load_dotenv()
class Connection:
"""
initialize constructor
creates database connection
"""
def __init__(self):
try:
self.pool = psycopg2.pool.SimpleConnectionPool(1, 20, user = os.getenv... | [
"os.getenv",
"dotenv.load_dotenv"
] | [((84, 97), 'dotenv.load_dotenv', 'load_dotenv', ([], {}), '()\n', (95, 97), False, 'from dotenv import load_dotenv\n'), ((311, 331), 'os.getenv', 'os.getenv', (['"""DB_USER"""'], {}), "('DB_USER')\n", (320, 331), False, 'import os\n'), ((378, 401), 'os.getenv', 'os.getenv', (['"""<PASSWORD>"""'], {}), "('<PASSWORD>')\... |
from datastructures import structures
import datastructures
from interpreter import interpret
from os import listdir, makedirs
from os.path import isfile, join, dirname
import pathlib
import sys
testFiles = [f[:-3] for f in listdir("../tests") if isfile(join("../tests", f)) and f.endswith(".in")]
def get_class( name )... | [
"os.listdir",
"pathlib.Path",
"os.path.join",
"os.path.dirname",
"interpreter.interpret"
] | [((224, 243), 'os.listdir', 'listdir', (['"""../tests"""'], {}), "('../tests')\n", (231, 243), False, 'from os import listdir, makedirs\n'), ((1050, 1103), 'interpreter.interpret', 'interpret', (['test', 'instance', 'benches', 'benchmarkinterval'], {}), '(test, instance, benches, benchmarkinterval)\n', (1059, 1103), Fa... |
# -*- coding: utf-8 -*-
#
# Buggy documentation build configuration file
import sys
import os
needs_sphinx = '1.7'
sys.path.append(os.path.abspath('extensions'))
extensions = ['sphinx.ext.imgmath']
templates_path = ['_templates']
source_suffix = '.rst'
source_encoding = 'utf-8-sig'
# The master toctree document
ma... | [
"os.path.abspath",
"os.environ.get",
"sphinx_rtd_theme.get_html_theme_path"
] | [((134, 163), 'os.path.abspath', 'os.path.abspath', (['"""extensions"""'], {}), "('extensions')\n", (149, 163), False, 'import os\n'), ((668, 703), 'os.environ.get', 'os.environ.get', (['"""READTHEDOCS"""', 'None'], {}), "('READTHEDOCS', None)\n", (682, 703), False, 'import os\n'), ((791, 829), 'sphinx_rtd_theme.get_ht... |
'''File containing the display methods'''
from cv2 import cv2
def display(window_name, image):
'''Calculates scale and fits into display'''
screen_res = 960, 540
scale_width = screen_res[0] / image.shape[1]
scale_height = screen_res[1] / image.shape[0]
scale = min(scale_width, scale_height)
... | [
"cv2.cv2.resizeWindow",
"cv2.cv2.waitKey",
"cv2.cv2.destroyAllWindows",
"cv2.cv2.namedWindow",
"cv2.cv2.imshow"
] | [((459, 506), 'cv2.cv2.namedWindow', 'cv2.namedWindow', (['window_name', 'cv2.WINDOW_NORMAL'], {}), '(window_name, cv2.WINDOW_NORMAL)\n', (474, 506), False, 'from cv2 import cv2\n'), ((511, 569), 'cv2.cv2.resizeWindow', 'cv2.resizeWindow', (['window_name', 'window_width', 'window_height'], {}), '(window_name, window_wi... |
from django.views.decorators.http import require_http_methods
from graphene_django.views import GraphQLView
@require_http_methods(['POST'])
def graphql_view(request):
from graph_wrap.tastypie import schema
schema = schema()
view = GraphQLView.as_view(schema=schema)
return view(request)
| [
"graphene_django.views.GraphQLView.as_view",
"django.views.decorators.http.require_http_methods",
"graph_wrap.tastypie.schema"
] | [((111, 141), 'django.views.decorators.http.require_http_methods', 'require_http_methods', (["['POST']"], {}), "(['POST'])\n", (131, 141), False, 'from django.views.decorators.http import require_http_methods\n'), ((225, 233), 'graph_wrap.tastypie.schema', 'schema', ([], {}), '()\n', (231, 233), False, 'from graph_wrap... |
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions ... | [
"weakref.WeakKeyDictionary",
"pyglet.clock.tick",
"pyglet.clock.get_sleep_time",
"pyglet.app.xlib.XlibEventLoop"
] | [((2900, 2927), 'weakref.WeakKeyDictionary', 'weakref.WeakKeyDictionary', ([], {}), '()\n', (2925, 2927), False, 'import weakref\n'), ((6709, 6725), 'pyglet.clock.tick', 'clock.tick', (['(True)'], {}), '(True)\n', (6719, 6725), False, 'from pyglet import clock\n'), ((6972, 6998), 'pyglet.clock.get_sleep_time', 'clock.g... |
# adapted from Machine Learning Mastery by <NAME>
# https://machinelearningmastery.com/
from random import randrange, seed
def zero_rule_regressor(train, test):
output_values = [row[-1] for row in train]
prediction = sum(output_values) / float(len(output_values))
predicted = [prediction for i in r... | [
"random.seed"
] | [((379, 386), 'random.seed', 'seed', (['(1)'], {}), '(1)\n', (383, 386), False, 'from random import randrange, seed\n')] |
# Copyright 2017 The TensorFlow Authors modified by <NAME>. 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 ... | [
"tensorflow.shape",
"numpy.random.rand",
"numpy.ones",
"numpy.arange",
"kerod.utils.ops.item_assignment",
"numpy.testing.assert_allclose",
"kerod.utils.ops.indices_to_dense_vector",
"numpy.random.randint",
"tensorflow.constant",
"numpy.zeros",
"numpy.testing.assert_array_equal",
"numpy.random.... | [((854, 877), 'numpy.random.randint', 'np.random.randint', (['size'], {}), '(size)\n', (871, 877), True, 'import numpy as np\n'), ((974, 1006), 'numpy.zeros', 'np.zeros', (['size'], {'dtype': 'np.float32'}), '(size, dtype=np.float32)\n', (982, 1006), True, 'import numpy as np\n'), ((1069, 1094), 'tensorflow.constant', ... |
"""
ckwg +31
Copyright 2017 by Kitware, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the ... | [
"kwiver.vital.types.Image"
] | [((4976, 5098), 'kwiver.vital.types.Image', 'Image', (['img_data', 'img_width', 'img_height', 'img_depth', 'img_w_step', 'img_h_step', 'img_d_step', 'img_pix_type', 'img_pix_num_bytes'], {}), '(img_data, img_width, img_height, img_depth, img_w_step, img_h_step,\n img_d_step, img_pix_type, img_pix_num_bytes)\n', (498... |
# coding=utf-8
import numpy as np
import torch
from torch.utils.data import Dataset
from allennlp.data import Vocabulary
from updown.config import Config
from updown.data.readers import CocoCaptionsReader
from updown.utils.constraints import ConstraintFilter, FiniteStateMachineBuilder
from collections import Counte... | [
"torch.LongTensor",
"tqdm.tqdm",
"nltk.tokenize.word_tokenize",
"torch.tensor",
"collections.defaultdict",
"json.load"
] | [((2264, 2281), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (2275, 2281), False, 'from collections import Counter, defaultdict\n'), ((2364, 2398), 'tqdm.tqdm', 'tqdm', (["captions_json['annotations']"], {}), "(captions_json['annotations'])\n", (2368, 2398), False, 'from tqdm import tqdm\n'), (... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
from odoo import api, fields, models
_logger = logging.getLogger(__name__)
class SaleConfiguration(models.TransientModel):
_inherit = 'sale.config.settings'
company_id = fields.Many2one('res.c... | [
"logging.getLogger",
"odoo.fields.Many2one",
"odoo.api.onchange",
"odoo.fields.Text",
"odoo.fields.Selection",
"odoo.fields.Boolean"
] | [((164, 191), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (181, 191), False, 'import logging\n'), ((298, 412), 'odoo.fields.Many2one', 'fields.Many2one', (['"""res.company"""'], {'string': '"""Company"""', 'required': '(True)', 'default': '(lambda self: self.env.user.company_id)'}), "(... |
from django.core.management.base import BaseCommand, CommandError
from shortener.models import LitresinURL
class Command(BaseCommand):
help = 'Refrehes all LitresinURL shortcodes'
def add_arguments(self, parser):
parser.add_argument('--items', type=int)
def handle(self, *args, **options):
... | [
"shortener.models.LitresinURL.objects.refresh_shortcodes"
] | [((330, 392), 'shortener.models.LitresinURL.objects.refresh_shortcodes', 'LitresinURL.objects.refresh_shortcodes', ([], {'items': "options['items']"}), "(items=options['items'])\n", (368, 392), False, 'from shortener.models import LitresinURL\n')] |
# -*- coding: utf-8 -*-
import os
import sublime
import sublime_plugin
class CopyPythonPathCommand(sublime_plugin.TextCommand):
def run(self, edit):
python_path_items = []
head, tail = os.path.split(self.view.file_name())
module = tail.rsplit('.', 1)[0]
if module != '__init__':... | [
"sublime.set_clipboard",
"sublime.status_message",
"os.path.join",
"os.path.split"
] | [((388, 407), 'os.path.split', 'os.path.split', (['head'], {}), '(head)\n', (401, 407), False, 'import os\n'), ((1712, 1746), 'sublime.set_clipboard', 'sublime.set_clipboard', (['python_path'], {}), '(python_path)\n', (1733, 1746), False, 'import sublime\n'), ((1756, 1820), 'sublime.status_message', 'sublime.status_mes... |
import time
import logging
import requests
from concurrent.futures import ThreadPoolExecutor
from ..order.orderpackage import BaseOrderPackage, OrderPackageType, BaseOrder
from ..events.events import OrderEvent
logger = logging.getLogger(__name__)
MAX_SESSION_AGE = 200 # seconds since last request
BET_ID_START = 10... | [
"logging.getLogger",
"concurrent.futures.ThreadPoolExecutor",
"time.time",
"requests.Session"
] | [((222, 249), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (239, 249), False, 'import logging\n'), ((560, 609), 'concurrent.futures.ThreadPoolExecutor', 'ThreadPoolExecutor', ([], {'max_workers': 'self._max_workers'}), '(max_workers=self._max_workers)\n', (578, 609), False, 'from concur... |
"""
Copyright (c) Microsoft Corporation.
Licensed under the MIT license.
convert image npz to LMDB
"""
import argparse
import glob
import io
import json
import multiprocessing as mp
import os
from os.path import basename, exists
from cytoolz import curry
import numpy as np
from tqdm import tqdm
import lmdb
import ms... | [
"os.path.exists",
"numpy.savez",
"msgpack_numpy.patch",
"argparse.ArgumentParser",
"os.makedirs",
"json.dump",
"io.BytesIO",
"glob.glob",
"lmdb.open",
"os.path.basename",
"multiprocessing.Pool",
"numpy.savez_compressed",
"numpy.load",
"msgpack.dumps"
] | [((347, 368), 'msgpack_numpy.patch', 'msgpack_numpy.patch', ([], {}), '()\n', (366, 368), False, 'import msgpack_numpy\n'), ((1315, 1330), 'os.path.basename', 'basename', (['fname'], {}), '(fname)\n', (1323, 1330), False, 'from os.path import basename, exists\n'), ((1659, 1697), 'msgpack.dumps', 'msgpack.dumps', (['dum... |
import numpy as np
import theano.tensor as tt
from . import Hypers, ones
from ...libs.tensors import tt_to_num
class Metric(Hypers):
def __call__(self, x1, x2):
return tt.abs_(x1 - x2)
def gram(self, x1, x2):
#try:
return (self(x1[:, self.dims].dimshuffle([0, 'x', 1]), x2[:, self.dims... | [
"numpy.abs",
"theano.tensor.diag",
"numpy.ones",
"theano.tensor.sum",
"theano.tensor.minimum",
"theano.tensor.abs_",
"numpy.zeros",
"theano.tensor.eq",
"numpy.float32",
"theano.tensor.dot"
] | [((182, 198), 'theano.tensor.abs_', 'tt.abs_', (['(x1 - x2)'], {}), '(x1 - x2)\n', (189, 198), True, 'import theano.tensor as tt\n'), ((539, 558), 'numpy.ones', 'np.ones', (['self.shape'], {}), '(self.shape)\n', (546, 558), True, 'import numpy as np\n'), ((1976, 2004), 'theano.tensor.sum', 'tt.sum', (['(0.5 * (x1 - x2)... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import os
def inputfile(path):
if not path.endswith(".csv"):
raise argparse.ArgumentTypeError("argument "
"filename must be of type *.csv")
return path
def check_range(arg):
try:
value... | [
"os.access",
"os.path.isdir",
"argparse.ArgumentError",
"argparse.ArgumentTypeError"
] | [((144, 213), 'argparse.ArgumentTypeError', 'argparse.ArgumentTypeError', (['"""argument filename must be of type *.csv"""'], {}), "('argument filename must be of type *.csv')\n", (170, 213), False, 'import argparse\n'), ((529, 564), 'argparse.ArgumentTypeError', 'argparse.ArgumentTypeError', (['message'], {}), '(messa... |
from fpack import (
primelist_till_x,
delete_from_left,
delete_from_right,
divide_primecheck,
)
from time import time
x = int(input("Check till where: \n"))
t = time()
l = [i for i in primelist_till_x(x) if len(str(i)) > 1]
primes = [i for i in primelist_till_x(x)]
main = set()
for i in l:
almi = ... | [
"fpack.primelist_till_x",
"time.time",
"fpack.divide_primecheck"
] | [((178, 184), 'time.time', 'time', ([], {}), '()\n', (182, 184), False, 'from time import time\n'), ((201, 220), 'fpack.primelist_till_x', 'primelist_till_x', (['x'], {}), '(x)\n', (217, 220), False, 'from fpack import primelist_till_x, delete_from_left, delete_from_right, divide_primecheck\n'), ((262, 281), 'fpack.pri... |
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 30 10:12:34 2018
@author: kite
"""
"""
完成策略的回测,绘制以沪深300为基准的收益曲线,计算年化收益、最大回撤、夏普比率
主要的方法包括:
ma10_factor:
is_k_up_break_ma10:当日K线是否上穿10日均线
is_k_down_break_ma10:当日K线是否下穿10日均线
compare_close_2_ma_10:工具方法,某日收盘价和当日对应的10日均线的关系
backtest:回测主... | [
"pandas.Series",
"pickle.dump",
"matplotlib.pyplot.show",
"stock_pool_strategy.find_out_stocks",
"pandas.DatetimeIndex",
"matplotlib.pyplot.style.use",
"stock_util.get_trading_dates",
"factor.ma10_factor.is_k_down_break_ma10",
"stock_util.dynamic_max_drawdown",
"factor.ma10_factor.is_k_up_break_ma... | [((886, 909), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""ggplot"""'], {}), "('ggplot')\n", (899, 909), True, 'import matplotlib.pyplot as plt\n'), ((2365, 2376), 'pandas.Series', 'pd.Series', ([], {}), '()\n', (2374, 2376), True, 'import pandas as pd\n'), ((3283, 3337), 'pandas.DataFrame', 'pd.DataFrame', ([... |
import torch
import torch.nn as nn
import numpy as np
import random
from torch import optim
from rl_network import *
class Agent:
"""
학습 에이전트
네트워크 모델을 받고, 학습을 수행함
"""
def __init__(self, num_states, num_actions, network_type, learning_rate, use_rnn=False,
gamma=0.99, capa... | [
"random.sample",
"torch.max",
"numpy.zeros",
"torch.sum",
"torch.no_grad",
"torch.zeros"
] | [((5858, 5901), 'random.sample', 'random.sample', (['self.memory', 'self.batch_size'], {}), '(self.memory, self.batch_size)\n', (5871, 5901), False, 'import random\n'), ((6310, 6360), 'numpy.zeros', 'np.zeros', ([], {'shape': '(*reward_shape, 1)', 'dtype': 'np.float'}), '(shape=(*reward_shape, 1), dtype=np.float)\n', (... |
import json
import os
import fasteners
from collections import OrderedDict, namedtuple
from conans.errors import ConanException, NoRemoteAvailable
from conans.model.ref import ConanFileReference, PackageReference
from conans.util.files import load, save
from conans.util.config_parser import get_bool_from_text_value
f... | [
"conans.model.ref.PackageReference.loads",
"collections.OrderedDict",
"collections.namedtuple",
"json.loads",
"fasteners.InterProcessLock",
"json.dumps",
"conans.util.config_parser.get_bool_from_text_value",
"os.unlink",
"conans.util.files.save",
"conans.errors.NoRemoteAvailable",
"conans.errors... | [((374, 440), 'collections.OrderedDict', 'OrderedDict', (["{'conan-center': ('https://conan.bintray.com', True)}"], {}), "({'conan-center': ('https://conan.bintray.com', True)})\n", (385, 440), False, 'from collections import OrderedDict, namedtuple\n'), ((451, 494), 'collections.namedtuple', 'namedtuple', (['"""Remote... |
from cowrie.core.plugins import BasePlugin
from cowrie.plugins.ssh.utils import get_command_name_from_path
class DeletingTracksDetectorPlugin(BasePlugin):
risky_directories = [
'/var/log',
'bash_history'
]
def get_input(self, event):
return event
def process_event(self, event... | [
"cowrie.plugins.ssh.utils.get_command_name_from_path"
] | [((482, 516), 'cowrie.plugins.ssh.utils.get_command_name_from_path', 'get_command_name_from_path', (['_input'], {}), '(_input)\n', (508, 516), False, 'from cowrie.plugins.ssh.utils import get_command_name_from_path\n')] |
import logging
from copy import deepcopy
from loqusdb.exceptions import CaseError
from ped_parser import FamilyParser
LOG = logging.getLogger(__name__)
def get_case(family_lines, family_type="ped", vcf_path=None):
"""Return ped_parser case from a family file
Create a dictionary with case data. If no family... | [
"logging.getLogger",
"loqusdb.exceptions.CaseError",
"ped_parser.FamilyParser",
"copy.deepcopy"
] | [((126, 153), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (143, 153), False, 'import logging\n'), ((661, 700), 'ped_parser.FamilyParser', 'FamilyParser', (['family_lines', 'family_type'], {}), '(family_lines, family_type)\n', (673, 700), False, 'from ped_parser import FamilyParser\n'),... |
from models import MongoModel, ObjectId, Field
class ItemModel(MongoModel):
name: str = Field(..., title="Name of the item")
description: str = Field(..., title="Description of the item")
class Config:
allow_population_by_field_name = True
arbitrary_types_allowed = True
json_en... | [
"models.Field"
] | [((93, 129), 'models.Field', 'Field', (['...'], {'title': '"""Name of the item"""'}), "(..., title='Name of the item')\n", (98, 129), False, 'from models import MongoModel, ObjectId, Field\n'), ((153, 196), 'models.Field', 'Field', (['...'], {'title': '"""Description of the item"""'}), "(..., title='Description of the ... |
print("hello world!")
from browser import document, window, alert
env = window.env
def PrintNiceMessage(message):
window.swal(message, "", "success")
######################
# Start Learning Here
######################
env.step(0)
env.step(0)
env.step(0)
env.step(0)
#######################
## En... | [
"browser.window.swal"
] | [((124, 159), 'browser.window.swal', 'window.swal', (['message', '""""""', '"""success"""'], {}), "(message, '', 'success')\n", (135, 159), False, 'from browser import document, window, alert\n')] |
import sys
import os
import importlib
import logging
from neovim.api import Nvim
from neovim import attach, setup_logging
def getLogger(name):
def get_loglevel():
# logging setup
level = logging.INFO
if 'NVIM_PYTHON_LOG_LEVEL' in os.environ:
ll = getattr(logging,
... | [
"logging.getLogger",
"neovim.attach",
"importlib.import_module",
"imp.load_source",
"imp.reload",
"importlib.reload",
"cm_core.CoreHandler",
"sys.path.append"
] | [((729, 756), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (746, 756), False, 'import logging\n'), ((5159, 5203), 'neovim.attach', 'attach', (['"""tcp"""'], {'address': 'serveraddr', 'port': 'port'}), "('tcp', address=serveraddr, port=port)\n", (5165, 5203), False, 'from neovim import a... |
# Copyright: Copyright (c) 2020., <NAME>
# Author: <NAME> <adam at jakab dot pro>
# License: See LICENSE.txt
import math
from abc import ABC
from abc import abstractmethod
from random import randint
from beets.library import Item
from confuse import Subview
from beetsplug.goingrunning import common
pickers = {
... | [
"random.randint",
"beetsplug.goingrunning.common.get_training_attribute",
"beetsplug.goingrunning.common.get_class_instance",
"beetsplug.goingrunning.common.say",
"beetsplug.goingrunning.common.get_min_max_sum_avg_for_items"
] | [((788, 844), 'beetsplug.goingrunning.common.get_training_attribute', 'common.get_training_attribute', (['training', '"""pick_strategy"""'], {}), "(training, 'pick_strategy')\n", (817, 844), False, 'from beetsplug.goingrunning import common\n'), ((983, 1053), 'beetsplug.goingrunning.common.get_class_instance', 'common.... |
''' Check and manipulate filenames within the Naming Convention '''
from collections import OrderedDict
import re
## Logging
import logging
logger=logging.getLogger()
MOLI_NAMING_REGEX=r'''
([A-Z]+[0-9]*) # SHOW code, group 0
_(RL[0-9]{2}|EP[0-9]{2}) # ReeL or EPisode number, group 1
_([0-9]+[A-Z]?) # se... | [
"logging.getLogger",
"logging.basicConfig",
"collections.OrderedDict",
"re.compile",
"re.search"
] | [((149, 168), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (166, 168), False, 'import logging\n'), ((787, 810), 're.compile', 're.compile', (['"""[a-z]{,6}"""'], {}), "('[a-z]{,6}')\n", (797, 810), False, 'import re\n'), ((825, 852), 're.compile', 're.compile', (['"""[a-zA-Z]{,10}"""'], {}), "('[a-zA-Z]{... |
from __future__ import division
import math
# TODO @saved_file saves the conditional probabilities for this bayes net
# @lables is 1*n array
# @features is 'n' * 'number of features', each element is a single 'feature' list that contains arbitrary numbe of values a feature can take on
# so features is a 3-d array
#... | [
"math.log"
] | [((4382, 4410), 'math.log', 'math.log', (['self.priors[label]'], {}), '(self.priors[label])\n', (4390, 4410), False, 'import math\n'), ((4639, 4697), 'math.log', 'math.log', (['self.posteriors[label][feature_idx][feature_val]'], {}), '(self.posteriors[label][feature_idx][feature_val])\n', (4647, 4697), False, 'import m... |
from rest_framework.mixins import (
CreateModelMixin,
DestroyModelMixin,
ListModelMixin
)
from rest_framework.viewsets import GenericViewSet
from pydis_site.apps.api.models.bot.offensive_message import OffensiveMessage
from pydis_site.apps.api.serializers import OffensiveMessageSerializer
class Offensive... | [
"pydis_site.apps.api.models.bot.offensive_message.OffensiveMessage.objects.all"
] | [((1587, 1617), 'pydis_site.apps.api.models.bot.offensive_message.OffensiveMessage.objects.all', 'OffensiveMessage.objects.all', ([], {}), '()\n', (1615, 1617), False, 'from pydis_site.apps.api.models.bot.offensive_message import OffensiveMessage\n')] |
import sys
import argparse
import numpy as np
from dataclasses import dataclass
from mchap.application import baseclass
from mchap.application.baseclass import SampleAssemblyError, SAMPLE_ASSEMBLY_ERROR
from mchap.application.arguments import (
CALL_MCMC_PARSER_ARGUMENTS,
collect_call_mcmc_program_arguments,
)... | [
"mchap.io.qual_of_prob",
"mchap.application.baseclass.SAMPLE_ASSEMBLY_ERROR.format",
"numpy.unique",
"argparse.ArgumentParser",
"mchap.jitutils.natural_log_to_log10",
"sys.exit",
"mchap.application.baseclass.SampleAssemblyError",
"mchap.calling.exact.genotype_likelihoods",
"mchap.calling.classes.Cal... | [((836, 885), 'argparse.ArgumentParser', 'argparse.ArgumentParser', (['"""MCMC haplotype calling"""'], {}), "('MCMC haplotype calling')\n", (859, 885), False, 'import argparse\n'), ((1149, 1190), 'mchap.application.arguments.collect_call_mcmc_program_arguments', 'collect_call_mcmc_program_arguments', (['args'], {}), '(... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from subprocess import Popen, PIPE
emojis="""⛑🏻 Helmet With White Cross, Type-1-2
💏🏻 Kiss, Type-1-2
💑🏻 Couple With Heart, Type-1-2
⛷🏻 Skier, Type-1-2
😀 Grinning Face
😁 Beaming Face With Smiling Eyes
😂 Face With Tears of Joy
🤣 Rolling on the Floor Laughing
😃 Grinni... | [
"subprocess.Popen"
] | [((40473, 40595), 'subprocess.Popen', 'Popen', ([], {'args': "['rofi', '-dmenu', '-i', '-multi-select', '-p', ' 😀 ', '-kb-custom-1',\n 'Alt+c']", 'stdin': 'PIPE', 'stdout': 'PIPE'}), "(args=['rofi', '-dmenu', '-i', '-multi-select', '-p', ' 😀 ',\n '-kb-custom-1', 'Alt+c'], stdin=PIPE, stdout=PIPE)\n", (40478... |
#
# This file is part of pyasn1-modules software.
#
# Copyright (c) 2005-2020, <NAME> <<EMAIL>>
# License: http://snmplabs.com/pyasn1/license.html
#
import sys
import unittest
from pyasn1.codec.der.decoder import decode as der_decoder
from pyasn1.codec.der.encoder import encode as der_encoder
from pyasn1_modules impo... | [
"pyasn1_modules.rfc2315.ContentInfo",
"pyasn1.codec.der.decoder.decode",
"pyasn1.codec.der.encoder.encode",
"unittest.TextTestRunner",
"unittest.TestLoader",
"pyasn1_modules.pem.readBase64fromText"
] | [((546, 567), 'pyasn1_modules.rfc2315.ContentInfo', 'rfc2315.ContentInfo', ([], {}), '()\n', (565, 567), False, 'from pyasn1_modules import pem, rfc2315\n'), ((618, 665), 'pyasn1_modules.pem.readBase64fromText', 'pem.readBase64fromText', (['self.pem_text_unordered'], {}), '(self.pem_text_unordered)\n', (640, 665), Fals... |
from service import app
def test_all_prooducts():
request, response = app.test_client.get('/')
assert response.status == 200
response_body = json.loads(response.body)
assert len(response_body) == 4
def test_single_product():
request, response = app.test_client.get('/0')
assert response.statu... | [
"service.app.test_client.get"
] | [((76, 100), 'service.app.test_client.get', 'app.test_client.get', (['"""/"""'], {}), "('/')\n", (95, 100), False, 'from service import app\n'), ((269, 294), 'service.app.test_client.get', 'app.test_client.get', (['"""/0"""'], {}), "('/0')\n", (288, 294), False, 'from service import app\n'), ((588, 614), 'service.app.t... |
#
# Autogenerated by Thrift Compiler (0.11.0)
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
#
# options string: py:new_style,no_utf8strings
#
from thrift.Thrift import TType, TMessageType, TFrozenDict, TException, TApplicationException
from thrift.protocol.TProtocol import TProtocolException
fr... | [
"thrift.TRecursive.fix_spec"
] | [((1727, 1748), 'thrift.TRecursive.fix_spec', 'fix_spec', (['all_structs'], {}), '(all_structs)\n', (1735, 1748), False, 'from thrift.TRecursive import fix_spec\n')] |
import pandas as pd
import os
import click
import numpy as np
opj = os.path.join
@click.command()
@click.option('--datadir', type=str, default='./data/lorenz/bias_experiment')
def main(datadir):
df = pd.read_pickle(opj(datadir, 'results.pkl'))
print(df)
print('\\toprule')
print('$\\sigma_w$ & $\\si... | [
"click.option",
"numpy.abs",
"click.command"
] | [((85, 100), 'click.command', 'click.command', ([], {}), '()\n', (98, 100), False, 'import click\n'), ((102, 178), 'click.option', 'click.option', (['"""--datadir"""'], {'type': 'str', 'default': '"""./data/lorenz/bias_experiment"""'}), "('--datadir', type=str, default='./data/lorenz/bias_experiment')\n", (114, 178), F... |
#!/usr/bin/env python
# projectS and projectC were written by <NAME>.
import time
start = time.time()
import argparse
import cv2
import os
import dlib
import numpy as np
np.set_printoptions(precision=2)
import openface
from matplotlib import cm
fileDir = os.path.dirname(os.path.realpath(__file__))
modelDir = os.p... | [
"openface.TorchNeuralNet",
"cv2.rectangle",
"numpy.sqrt",
"matplotlib.cm.Set1",
"cv2.imshow",
"numpy.array",
"cv2.destroyAllWindows",
"numpy.sin",
"numpy.multiply",
"argparse.ArgumentParser",
"cv2.line",
"cv2.addWeighted",
"numpy.linspace",
"cv2.waitKey",
"dlib.correlation_tracker",
"c... | [((92, 103), 'time.time', 'time.time', ([], {}), '()\n', (101, 103), False, 'import time\n'), ((174, 206), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'precision': '(2)'}), '(precision=2)\n', (193, 206), True, 'import numpy as np\n'), ((316, 353), 'os.path.join', 'os.path.join', (['fileDir', '""".."""', '"""... |
import pandas as pd
import numpy as np
from sklearn import model_selection
from sklearn import preprocessing
if __name__ == "__main__":
df = pd.read_csv("data.csv")
df["kfold"] = -1
d = {"downdog": 0, "goddess": 1, "plank": 2, "tree": 3, "warrior2": 4}
df["y"] = df["y"].map(d)
df = df.sa... | [
"sklearn.model_selection.StratifiedKFold",
"pandas.read_csv"
] | [((150, 173), 'pandas.read_csv', 'pd.read_csv', (['"""data.csv"""'], {}), "('data.csv')\n", (161, 173), True, 'import pandas as pd\n'), ((387, 430), 'sklearn.model_selection.StratifiedKFold', 'model_selection.StratifiedKFold', ([], {'n_splits': '(5)'}), '(n_splits=5)\n', (418, 430), False, 'from sklearn import model_se... |
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
with open('README.rst') as f:
readme = f.read()
setup(
name='nepcal_applet',
version='0.0.3',
description='Nepali calendar applet',
long_description=readme,
author='<NAME>',
author_email='<EMAIL>',
url='https://githu... | [
"setuptools.find_packages"
] | [((563, 603), 'setuptools.find_packages', 'find_packages', ([], {'exclude': "('tests', 'docs')"}), "(exclude=('tests', 'docs'))\n", (576, 603), False, 'from setuptools import setup, find_packages\n')] |
from rest_framework import serializers
from authentication.models import User, UserManager
from django.contrib.auth import authenticate
class RegistrationSerializer(serializers.ModelSerializer):
password = serializers.CharField(
max_length=128,
min_length=8,
write_only=True
)
token... | [
"django.contrib.auth.authenticate",
"rest_framework.serializers.EmailField",
"rest_framework.serializers.ValidationError",
"authentication.models.User.objects.create_user",
"rest_framework.serializers.CharField"
] | [((211, 279), 'rest_framework.serializers.CharField', 'serializers.CharField', ([], {'max_length': '(128)', 'min_length': '(8)', 'write_only': '(True)'}), '(max_length=128, min_length=8, write_only=True)\n', (232, 279), False, 'from rest_framework import serializers\n'), ((323, 376), 'rest_framework.serializers.CharFie... |
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
from builtins import str
from builtins import range
from past.utils import old_div
from builtins import object
import os
import re
import json
import copy
from glm.Qtpy.Qt import QtGui, QtCore, QtWidgets, Qt
fr... | [
"glm.Qtpy.Qt.QtGui.QPainter",
"builtins.str",
"past.utils.old_div",
"glm.Qtpy.Qt.QtCore.Signal",
"builtins.range",
"glm.Qtpy.Qt.QtGui.QFont",
"copy.deepcopy",
"glm.Qtpy.Qt.QtCore.QRectF",
"glm.Qtpy.Qt.QtGui.QPixmap",
"os.path.exists",
"glm.Qtpy.Qt.QtWidgets.QGraphicsLineItem",
"glm.Qtpy.Qt.QtC... | [((1662, 1717), 'glm.Qtpy.Qt.QtCore.Signal', 'QtCore.Signal', (['signalObject', 'signalObject', 'signalObject'], {}), '(signalObject, signalObject, signalObject)\n', (1675, 1717), False, 'from glm.Qtpy.Qt import QtGui, QtCore, QtWidgets, Qt\n'), ((1855, 1896), 'glm.Qtpy.Qt.QtCore.Signal', 'QtCore.Signal', (['signalObje... |
import os
import sys
from pkg_resources import Requirement, resource_listdir, resource_filename
FIRST = 0
def message_to_screen(message, banner=False, bannerdashes=57):
if not banner:
sys.stderr.write(message + '\n')
else:
sys.stderr.write('{dashes}\n{message}\n{dashes}\n'.format(
... | [
"os.path.abspath",
"sys.stderr.write",
"os.path.exists",
"pkg_resources.Requirement.parse"
] | [((199, 231), 'sys.stderr.write', 'sys.stderr.write', (["(message + '\\n')"], {}), "(message + '\\n')\n", (215, 231), False, 'import sys\n'), ((486, 511), 'pkg_resources.Requirement.parse', 'Requirement.parse', (['"""swag"""'], {}), "('swag')\n", (503, 511), False, 'from pkg_resources import Requirement, resource_listd... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.db.models.deletion
import jsonfield.fields
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0001_initial'),
]
operations = [
migrations.CreateM... | [
"django.db.models.ForeignKey",
"django.db.models.BooleanField",
"django.db.models.AutoField",
"django.db.models.PositiveIntegerField",
"django.db.models.CharField"
] | [((403, 496), 'django.db.models.AutoField', 'models.AutoField', ([], {'serialize': '(False)', 'auto_created': '(True)', 'verbose_name': '"""ID"""', 'primary_key': '(True)'}), "(serialize=False, auto_created=True, verbose_name='ID',\n primary_key=True)\n", (419, 496), False, 'from django.db import models, migrations\... |
import json
import logging
import os
import trio
from trio_websocket import (
ConnectionClosed, WebSocketConnection, WebSocketRequest, serve_websocket,
)
from . import errors
from .controller import route_message
from .services.auth import ResultType, check_token
from .user import User, registry
from .utils impor... | [
"logging.getLogger",
"json.loads",
"os.getenv",
"json.dumps",
"logging.warning",
"trio.open_nursery",
"trio_websocket.serve_websocket"
] | [((458, 485), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (475, 485), False, 'import logging\n'), ((356, 389), 'os.getenv', 'os.getenv', (['"""WS_MAX_CLIENTS"""', '"""16"""'], {}), "('WS_MAX_CLIENTS', '16')\n", (365, 389), False, 'import os\n'), ((628, 685), 'logging.warning', 'logging... |
# The dataset code has been adapted from:
# https://pytorch.org/tutorials/intermediate/torchvision_tutorial.html
# from https://github.com/pytorch/tutorials
# which has been distributed under the following license:
################################################################################
# BSD 3-Clause License
#... | [
"torch.squeeze",
"torch.as_tensor",
"PIL.Image.open",
"numpy.unique",
"matplotlib.pyplot.show",
"avalanche.benchmarks.datasets.default_dataset_location",
"numpy.where",
"torchvision.transforms.ToPILImage",
"pathlib.Path",
"torch.utils.data.dataloader.DataLoader",
"numpy.max",
"numpy.array",
... | [((3270, 3291), 'PIL.Image.open', 'Image.open', (['mask_path'], {}), '(mask_path)\n', (3280, 3291), False, 'from PIL import Image\n'), ((7804, 7840), 'torch.utils.data.dataloader.DataLoader', 'DataLoader', (['train_data'], {'batch_size': '(1)'}), '(train_data, batch_size=1)\n', (7814, 7840), False, 'from torch.utils.da... |
from kf_d3m_primitives.ts_classification.lstm_fcn.lstm_fcn_pipeline import LstmFcnPipeline
def _test_serialize(dataset):
pipeline = LstmFcnPipeline(epochs=1)
pipeline.write_pipeline()
pipeline.fit_serialize(dataset)
pipeline.deserialize_score(dataset)
pipeline.delete_pipeline()
pipeline.de... | [
"kf_d3m_primitives.ts_classification.lstm_fcn.lstm_fcn_pipeline.LstmFcnPipeline"
] | [((142, 167), 'kf_d3m_primitives.ts_classification.lstm_fcn.lstm_fcn_pipeline.LstmFcnPipeline', 'LstmFcnPipeline', ([], {'epochs': '(1)'}), '(epochs=1)\n', (157, 167), False, 'from kf_d3m_primitives.ts_classification.lstm_fcn.lstm_fcn_pipeline import LstmFcnPipeline\n')] |
import json
from datetime import datetime
from base64 import b64encode
from sqlalchemy.ext.declarative import DeclarativeMeta
def to_camel_case(s: str) -> str:
return ''.join(map(str.capitalize, s.split('_')))
class BaseEncoder(json.JSONEncoder):
def default(self, obj):
if type(obj) == datetime:
... | [
"base64.b64encode",
"json.dumps"
] | [((829, 868), 'json.dumps', 'json.dumps', (['data'], {'cls': 'SQLAlchemyEncoder'}), '(data, cls=SQLAlchemyEncoder)\n', (839, 868), False, 'import json\n'), ((404, 418), 'base64.b64encode', 'b64encode', (['obj'], {}), '(obj)\n', (413, 418), False, 'from base64 import b64encode\n')] |
#!/usr/bin/env python3
import hashlib, os, getpass
data = getpass.getpass(">>> ")
out = hashlib.new('md5', data.encode('utf-8'))
print(out.hexdigest())
input("Press enter to exit...")
| [
"getpass.getpass"
] | [((59, 82), 'getpass.getpass', 'getpass.getpass', (['""">>> """'], {}), "('>>> ')\n", (74, 82), False, 'import hashlib, os, getpass\n')] |
#
# Copyright (c) 2016-2021 Deephaven Data Labs and Patent Pending
#
# add JDK to path (otherwise jnius gives DLL load error)
import os
os.environ['PATH'] = os.environ['PATH'] + ";C:\\Program Files\\Java\jdk1.8.0_72\\jre\\bin\\server"
os.environ['PATH'] = os.environ['PATH'] + ";C:\\Program Files\\Java\jdk1.8.0_60\\jre... | [
"jpyutil.init_jvm",
"jpy.get_type"
] | [((378, 396), 'jpyutil.init_jvm', 'jpyutil.init_jvm', ([], {}), '()\n', (394, 396), False, 'import jpyutil\n'), ((495, 526), 'jpy.get_type', 'jpy.get_type', (['"""java.util.Stack"""'], {}), "('java.util.Stack')\n", (507, 526), False, 'import jpy\n')] |
import sys
import functools
import signal
import select
import socket
import numpy as np
import pickle
import matplotlib.pyplot as plt
import time
import datetime
from multiprocessing import Process, Queue
sys.path.append('../dhmsw/')
import interface
import telemetry_iface_ag
import struct
PLOT = True
headerStruct = ... | [
"struct.calcsize",
"telemetry_iface_ag.Framesource_Telemetry",
"multiprocessing.Process",
"telemetry_iface_ag.Session_Telemetry",
"sys.path.append",
"telemetry_iface_ag.Hologram_Telemetry",
"telemetry_iface_ag.Heartbeat_Telemetry",
"telemetry_iface_ag.Datalogger_Telemetry",
"numpy.frombuffer",
"te... | [((206, 234), 'sys.path.append', 'sys.path.append', (['"""../dhmsw/"""'], {}), "('../dhmsw/')\n", (221, 234), False, 'import sys\n'), ((320, 340), 'struct.Struct', 'struct.Struct', (['"""III"""'], {}), "('III')\n", (333, 340), False, 'import struct\n'), ((7944, 7977), 'socket.gethostbyname', 'socket.gethostbyname', (['... |
from germanium.decorators import login
from germanium.test_cases.rest import RESTTestCase
from germanium.tools import assert_in
from germanium.tools.http import assert_http_unauthorized, assert_http_forbidden, assert_http_not_found
from .test_case import HelperTestCase, AsSuperuserTestCase
__all__ =(
'HttpExcept... | [
"germanium.tools.http.assert_http_unauthorized",
"germanium.decorators.login",
"germanium.tools.http.assert_http_not_found",
"germanium.tools.http.assert_http_forbidden",
"germanium.tools.assert_in"
] | [((913, 938), 'germanium.decorators.login', 'login', ([], {'is_superuser': '(False)'}), '(is_superuser=False)\n', (918, 938), False, 'from germanium.decorators import login\n'), ((1245, 1270), 'germanium.decorators.login', 'login', ([], {'is_superuser': '(False)'}), '(is_superuser=False)\n', (1250, 1270), False, 'from ... |
from __future__ import division # Omit for Python 3.x
import matplotlib.pyplot as plt
from lucastree import LucasTree
fig, ax = plt.subplots()
tree = LucasTree(gamma=2, beta=0.95, alpha=0.90, sigma=0.1)
grid, price_vals = tree.grid, tree.compute_lt_price()
ax.plot(grid, price_vals, lw=2, alpha=0.7, label=r'$p^*(y)$... | [
"lucastree.LucasTree",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show"
] | [((131, 145), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (143, 145), True, 'import matplotlib.pyplot as plt\n'), ((154, 205), 'lucastree.LucasTree', 'LucasTree', ([], {'gamma': '(2)', 'beta': '(0.95)', 'alpha': '(0.9)', 'sigma': '(0.1)'}), '(gamma=2, beta=0.95, alpha=0.9, sigma=0.1)\n', (163, 205),... |
import unittest
import shutil
import os
from poor_trader.screening import indicator
from poor_trader import market, config
from poor_trader.screening.entity import Direction
from poor_trader.screening.indicator import DefaultIndicatorFactory, IndicatorRunnerFactory, DefaultIndicatorRunnerFactory
TEMP_INDICATORS_PATH ... | [
"os.path.exists",
"poor_trader.screening.indicator.DefaultIndicatorFactory",
"poor_trader.screening.indicator.MACross",
"poor_trader.screening.indicator.DonchianChannel",
"poor_trader.screening.indicator.DefaultIndicatorRunnerFactory",
"poor_trader.screening.indicator.SMA",
"poor_trader.screening.indica... | [((4976, 4991), 'unittest.main', 'unittest.main', ([], {}), '()\n', (4989, 4991), False, 'import unittest\n'), ((611, 667), 'poor_trader.market.csv_to_market', 'market.csv_to_market', (['"""TestMarket"""', 'HISTORICAL_DATA_PATH'], {}), "('TestMarket', HISTORICAL_DATA_PATH)\n", (631, 667), False, 'from poor_trader impor... |
import functools
import time
def memoize(func):
"""
Naive memoization decorator
If the need is speed, use functools.lru_cache instead as lru_cache is ~2x faster.
"""
cache = {}
@functools.wraps(func)
def memo_wrapper(*args, **kwargs):
nonlocal cache
# Create unique identif... | [
"functools.partial",
"time.perf_counter",
"functools.wraps"
] | [((205, 226), 'functools.wraps', 'functools.wraps', (['func'], {}), '(func)\n', (220, 226), False, 'import functools\n'), ((1038, 1059), 'functools.wraps', 'functools.wraps', (['func'], {}), '(func)\n', (1053, 1059), False, 'import functools\n'), ((982, 1031), 'functools.partial', 'functools.partial', (['recursive_time... |
from flask import Flask, url_for, redirect, Blueprint,render_template,session
from werkzeug.security import generate_password_hash
from prol import db
from prol.user.forms import RegisterForm, LoginForm
from prol.user.models import User
user_app = Blueprint('User',__name__)
@user_app.route('/register', methods=('GE... | [
"flask.render_template",
"prol.user.forms.LoginForm",
"prol.db.session.commit",
"prol.user.models.User.query.filter_by",
"flask.url_for",
"werkzeug.security.generate_password_hash",
"flask.session.pop",
"prol.user.forms.RegisterForm",
"flask.Blueprint",
"prol.user.models.User",
"prol.db.session.... | [((251, 278), 'flask.Blueprint', 'Blueprint', (['"""User"""', '__name__'], {}), "('User', __name__)\n", (260, 278), False, 'from flask import Flask, url_for, redirect, Blueprint, render_template, session\n'), ((356, 370), 'prol.user.forms.RegisterForm', 'RegisterForm', ([], {}), '()\n', (368, 370), False, 'from prol.us... |
# Module that contains the calibration functions of the nodes.
import time
def test_calibration_True():
'''
Dummy calibration function for test cases. Always returns True.
'''
return True
def test_calibration_True_delayed(delay=.5):
'''
Dummy calibration function for test cases. Always retur... | [
"time.sleep"
] | [((341, 358), 'time.sleep', 'time.sleep', (['delay'], {}), '(delay)\n', (351, 358), False, 'import time\n')] |
from numba import typeof
from numba.core import types
from numba.np.ufunc.ufuncbuilder import GUFuncBuilder
from numba.np.ufunc.sigparse import parse_signature
from numba.np.numpy_support import ufunc_find_matching_loop
class GUFunc(object):
"""
Dynamic generalized universal function (GUFunc)
intended to ... | [
"numba.core.types.none",
"numba.core.types.Array",
"numba.typeof",
"numba.np.ufunc.ufuncbuilder.GUFuncBuilder",
"numba.np.ufunc.sigparse.parse_signature",
"numba.np.numpy_support.ufunc_find_matching_loop"
] | [((878, 943), 'numba.np.ufunc.ufuncbuilder.GUFuncBuilder', 'GUFuncBuilder', (['py_func', 'signature', 'identity', 'cache', 'targetoptions'], {}), '(py_func, signature, identity, cache, targetoptions)\n', (891, 943), False, 'from numba.np.ufunc.ufuncbuilder import GUFuncBuilder\n'), ((2472, 2518), 'numba.np.ufunc.sigpar... |
from flask import Blueprint
from api.remoclient import NatureRemoClient
tv_controller = Blueprint('tv_controller', __name__, url_prefix='/tv/api')
@tv_controller.route('/send/<appliance_id>/<button_name>', methods=['POST'])
def send_tv(appliance_id,button_name):
nclient = NatureRemoClient()
result = nclient.... | [
"api.remoclient.NatureRemoClient",
"flask.Blueprint"
] | [((89, 147), 'flask.Blueprint', 'Blueprint', (['"""tv_controller"""', '__name__'], {'url_prefix': '"""/tv/api"""'}), "('tv_controller', __name__, url_prefix='/tv/api')\n", (98, 147), False, 'from flask import Blueprint\n'), ((280, 298), 'api.remoclient.NatureRemoClient', 'NatureRemoClient', ([], {}), '()\n', (296, 298)... |
# coding: utf-8
import numpy as np
from typing import List, Union
from collections import OrderedDict
from datetime import datetime
from .objects import Direction, BI, FakeBI, Signal
from .enum import Freq
from .utils.ta import MACD, SMA, KDJ
from .cobra.utils import kdj_gold_cross
from . import analyze
def check_th... | [
"numpy.array",
"collections.OrderedDict"
] | [((23899, 23912), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (23910, 23912), False, 'from collections import OrderedDict\n'), ((24475, 24488), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (24486, 24488), False, 'from collections import OrderedDict\n'), ((25203, 25216), 'collections.Order... |
"""
Requires python 2.7 and torch==0.3.1 and pycaffe (CPU is sufficient).
"""
from collections import OrderedDict
import caffe
import torch
import torch.nn as nn
from torch.autograd import Variable
from torchvision import models
from resnet_caffe import ResNetCaffe, convert_batchnorm, load_resnet50
from utils import ... | [
"resnet_caffe.ResNetCaffe",
"resnet_caffe.load_resnet50",
"collections.OrderedDict",
"torch.abs",
"utils.replace_module",
"argparse.ArgumentParser",
"torch.nn.Sequential",
"torch.load",
"resnet_caffe.convert_batchnorm",
"torch.nn.Linear",
"sys.exit",
"traceback.print_exc",
"torch.randn"
] | [((2093, 2125), 'torch.load', 'torch.load', (['orig_checkpoint_path'], {}), '(orig_checkpoint_path)\n', (2103, 2125), False, 'import torch\n'), ((2220, 2282), 'resnet_caffe.ResNetCaffe', 'ResNetCaffe', (['models.resnet.Bottleneck', 'bottleneck_depths', '(1000)'], {}), '(models.resnet.Bottleneck, bottleneck_depths, 1000... |
import functools
import glob
import gzip
import os
import sys
import warnings
import zipfile
from itertools import product
from django.apps import apps
from django.conf import settings
from django.core import serializers
from django.core.exceptions import ImproperlyConfigured
from django.core.management.b... | [
"django.core.management.color.no_style",
"itertools.product",
"django.db.transaction.get_autocommit",
"os.path.normpath",
"os.path.isdir",
"django.db.router.allow_migrate_model",
"warnings.warn",
"os.path.isabs",
"django.core.serializers.deserialize",
"glob.escape",
"django.apps.apps.get_app_con... | [((9398, 9431), 'functools.lru_cache', 'functools.lru_cache', ([], {'maxsize': 'None'}), '(maxsize=None)\n', (9417, 9431), False, 'import functools\n'), ((2366, 2413), 'django.core.management.utils.parse_apps_and_model_labels', 'parse_apps_and_model_labels', (["options['exclude']"], {}), "(options['exclude'])\n", (2393... |
# This module contains the code to create maps
import numpy as np
from itertools import combinations
import matplotlib.pyplot as plt
import itertools
# For plotting
import seaborn as sns
import logging
import statistics
import time
def manhattan(coords_ind1, coords_ind2):
return abs(coords_ind1[0] - coords_ind... | [
"logging.getLogger",
"seaborn.cubehelix_palette",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.ylabel",
"numpy.digitize",
"matplotlib.pyplot.xlabel",
"seaborn.heatmap",
"numpy.linspace",
"numpy.zeros",
"matplotlib.pyplot.yticks",
"numpy.concatenate",
"numpy.transpose",
"matplotlib.pyplot.s... | [((792, 856), 'logging.getLogger', 'logging.getLogger', (['"""illumination_map.IlluminationAxisDefinition"""'], {}), "('illumination_map.IlluminationAxisDefinition')\n", (809, 856), False, 'import logging\n'), ((1227, 1271), 'numpy.linspace', 'np.linspace', (['min_value', 'max_value', 'num_cells'], {}), '(min_value, ma... |
from os import path
from setuptools import setup, find_packages
with open(path.join(path.abspath(path.dirname(__file__)), "README.rst"), encoding="utf-8") as handle:
readme = handle.read()
setup(
name="tdigest-cffi",
version="0.1.2",
description="A data structure for accurate on-line accumulation of r... | [
"os.path.dirname",
"setuptools.find_packages"
] | [((509, 541), 'setuptools.find_packages', 'find_packages', ([], {'exclude': "['tests']"}), "(exclude=['tests'])\n", (522, 541), False, 'from setuptools import setup, find_packages\n'), ((98, 120), 'os.path.dirname', 'path.dirname', (['__file__'], {}), '(__file__)\n', (110, 120), False, 'from os import path\n')] |
# -*- coding: utf-8 -*-
#
# This file is part of urlwatch (https://thp.io/2008/urlwatch/).
# Copyright (c) 2008-2018 <NAME> <<EMAIL>>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redis... | [
"logging.getLogger",
"os.path.exists",
"json.loads",
"re.search",
"lxml.etree.HTMLParser",
"imp.load_source",
"json.dumps",
"io.StringIO",
"hashlib.sha1",
"os.path.expanduser",
"lxml.etree.tostring"
] | [((1751, 1778), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1768, 1778), False, 'import logging\n'), ((4607, 4653), 'os.path.expanduser', 'os.path.expanduser', (['"""~/.urlwatch/lib/hooks.py"""'], {}), "('~/.urlwatch/lib/hooks.py')\n", (4625, 4653), False, 'import os\n'), ((4766, 4795... |
import re
import json
import time
import string
import logging
import argparse
import multiprocessing as mp
manager = mp.Manager()
q_to_store = manager.Queue()
from tqdm import tqdm
from spiral import ronin
keywords = json.load(open("keywords.json"))
def identifier_split(line):
split_data = []
for tok in l... | [
"re.split",
"spiral.ronin.split",
"argparse.ArgumentParser",
"multiprocessing.cpu_count",
"time.time",
"multiprocessing.Manager",
"logging.info"
] | [((120, 132), 'multiprocessing.Manager', 'mp.Manager', ([], {}), '()\n', (130, 132), True, 'import multiprocessing as mp\n'), ((1348, 1373), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1371, 1373), False, 'import argparse\n'), ((557, 593), 're.split', 're.split', (['"""([a-zA-Z0-9]+|\\\\W+)... |
"""Message types."""
from functools import lru_cache
from typing import Union, Optional, Type
from typing_extensions import get_args
from . import message_definitions as defs
from ..constants import MessageId
MessageDefinition = Union[
defs.HeartbeatRequest,
defs.HeartbeatResponse,
defs.DeviceInfoRequest... | [
"functools.lru_cache",
"typing_extensions.get_args"
] | [((1118, 1141), 'functools.lru_cache', 'lru_cache', ([], {'maxsize': 'None'}), '(maxsize=None)\n', (1127, 1141), False, 'from functools import lru_cache\n'), ((1436, 1463), 'typing_extensions.get_args', 'get_args', (['MessageDefinition'], {}), '(MessageDefinition)\n', (1444, 1463), False, 'from typing_extensions import... |
'''
This file implements an example for using the MAX22190PMB in SPI Mode 1.
It displays the input read and wire break readout in the terminal.
For further details on MAX22190PMB refer to the data sheet.
Created on 25.02.2021
@author: JH
'''
from pyb import Pin
from PyTrinamicMicro.platforms.motionpy2.modules.max.ma... | [
"logging.getLogger",
"PyTrinamicMicro.platforms.motionpy2.modules.max.max22190.MAX22190",
"time.sleep"
] | [((380, 407), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (397, 407), False, 'import logging\n'), ((868, 991), 'PyTrinamicMicro.platforms.motionpy2.modules.max.max22190.MAX22190', 'MAX22190', (["connector['pin_cs']", "connector['spi']", "connector['fault_pin']", "connector['ready_pin']... |
# Copyright 2020 The Netket Authors. - All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... | [
"netket.legacy.sampler.MetropolisLocal",
"netket.legacy.optim.GradientDescent",
"netket.legacy.operator.Ising",
"netket.legacy.graph.Hypercube",
"netket.legacy.nn.models.RBM",
"netket.legacy.variational_states.ClassicalVariationalState",
"netket.legacy.Vmc",
"netket.legacy.hilbert.Spin"
] | [((663, 710), 'netket.legacy.graph.Hypercube', 'nk.graph.Hypercube', ([], {'length': 'L', 'n_dim': '(1)', 'pbc': '(True)'}), '(length=L, n_dim=1, pbc=True)\n', (681, 710), True, 'from netket import legacy as nk\n'), ((755, 792), 'netket.legacy.hilbert.Spin', 'nk.hilbert.Spin', ([], {'s': '(1 / 2)', 'N': 'g.n_nodes'}), ... |
# Licensed under the MIT license.
'''utilities'''
import os
import shutil
def to_int(array):
'''convert array to ints'''
return [int(a) for a in array]
def create_temp():
'''create temp folder'''
temp = get_temp()
if not os.path.isdir(temp):
os.mkdir(temp)
def get_temp():
'''temp ... | [
"os.path.dirname",
"os.path.isdir",
"os.mkdir"
] | [((509, 534), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (524, 534), False, 'import os\n'), ((246, 265), 'os.path.isdir', 'os.path.isdir', (['temp'], {}), '(temp)\n', (259, 265), False, 'import os\n'), ((275, 289), 'os.mkdir', 'os.mkdir', (['temp'], {}), '(temp)\n', (283, 289), False, 'im... |
# ============LICENSE_START=======================================================
# Copyright (c) 2017-2021 AT&T Intellectual Property. All rights reserved.
# Copyright (c) 2019 Pantheon.tech. All rights reserved.
# Copyright (c) 2021 Fujitsu Ltd.
# =====================================================================... | [
"miss_htbt_service.mod.trapd_http_session.init_session_obj"
] | [((1267, 1304), 'miss_htbt_service.mod.trapd_http_session.init_session_obj', 'trapd_http_session.init_session_obj', ([], {}), '()\n', (1302, 1304), False, 'from miss_htbt_service.mod import trapd_http_session\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import RPi.GPIO as GPIO
import time
pd = 17 #DATA IN
pc = 18 #CLK IN
CmdMode = 0x0000 # Work on 8-bit mode
ON = 0x00ff # 8-bit 1 data
OFF = 0x0000 # 8-bit 0 data
def isBitSet(x, n):
return (x & n**2) != 0
def sendData(d):
clk = True
GPIO... | [
"RPi.GPIO.output",
"RPi.GPIO.setup",
"RPi.GPIO.setwarnings",
"time.sleep",
"RPi.GPIO.setmode"
] | [((316, 334), 'RPi.GPIO.output', 'GPIO.output', (['pc', '(0)'], {}), '(pc, 0)\n', (327, 334), True, 'import RPi.GPIO as GPIO\n'), ((335, 353), 'time.sleep', 'time.sleep', (['(0.0005)'], {}), '(0.0005)\n', (345, 353), False, 'import time\n'), ((470, 488), 'RPi.GPIO.output', 'GPIO.output', (['pc', '(0)'], {}), '(pc, 0)\n... |
import glob
def chaves_valores(path): # mostra tudo entro de dados
text = open(path, 'r').read()
dic_text = eval(text)
print("mostrando valores e chaves")
guias = dic_text['guias']
for s in guias:
for pagen in s:
for key in s[pagen]['dados']:
print(f"key: {key... | [
"glob.glob"
] | [((838, 858), 'glob.glob', 'glob.glob', (['"""./*json"""'], {}), "('./*json')\n", (847, 858), False, 'import glob\n')] |
from abc import ABC, abstractmethod
from collections import OrderedDict
import torch
class Reparameterizer(ABC):
"""
Base class for reparameterization transforms, generalizing [1] to handle
multiple distributions and auxiliary variables.
The interface specifies two methods to be used by inference al... | [
"torch.zeros_like",
"collections.OrderedDict",
"torch.ones_like"
] | [((2173, 2203), 'collections.OrderedDict', 'OrderedDict', (["[('trivial', fn)]"], {}), "([('trivial', fn)])\n", (2184, 2203), False, 'from collections import OrderedDict\n'), ((2518, 2542), 'torch.zeros_like', 'torch.zeros_like', (['fn.loc'], {}), '(fn.loc)\n', (2534, 2542), False, 'import torch\n'), ((2559, 2584), 'to... |
from django.db import models
from django.utils import timezone
from user.models import Member
# Create your models here.
class Organization(models.Model):
Organization_name = models.CharField(max_length=20, unique=True)
def __str__(self):
return self.Organization_name
class Folder(models.Model):
... | [
"django.db.models.IntegerField",
"django.db.models.ForeignKey",
"django.db.models.ManyToManyField",
"django.db.models.DateTimeField",
"django.db.models.CharField"
] | [((180, 224), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(20)', 'unique': '(True)'}), '(max_length=20, unique=True)\n', (196, 224), False, 'from django.db import models\n'), ((332, 364), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(128)'}), '(max_length=128)\n', (3... |
import heapq
class Solution:
"""
@param k: an integer
@param W: an integer
@param Profits: an array
@param Capital: an array
@return: final maximized capital
"""
def findMaximizedCapital(self, k, W, Profits, Capital):
# Write your code here
cappq = [(cap, i) for i, cap in... | [
"heapq.heappush",
"heapq.heappop",
"heapq.heapify"
] | [((349, 369), 'heapq.heapify', 'heapq.heapify', (['cappq'], {}), '(cappq)\n', (362, 369), False, 'import heapq\n'), ((494, 514), 'heapq.heappop', 'heapq.heappop', (['cappq'], {}), '(cappq)\n', (507, 514), False, 'import heapq\n'), ((531, 572), 'heapq.heappush', 'heapq.heappush', (['profitpq', '(-Profits[index])'], {}),... |
'''
The logic behind the sensitivity calculation is the following:
1) read the effective area from a file
2) interpolate the effective area
3) calculate the sensitivity integral spectral exclusion zone
from inverting LiMa formula numerically and find where a signal would give
5 sigma, then make plots:
3.1... | [
"gamma_limits_sensitivity.get_sens_phasespace_figure",
"helper_functions_for_tests.get_effective_area_list",
"gamma_limits_sensitivity.get_sens_spectrum_figure"
] | [((853, 878), 'helper_functions_for_tests.get_effective_area_list', 'get_effective_area_list', ([], {}), '()\n', (876, 878), False, 'from helper_functions_for_tests import get_effective_area_list\n'), ((1362, 1387), 'helper_functions_for_tests.get_effective_area_list', 'get_effective_area_list', ([], {}), '()\n', (1385... |
import os
import warnings
from typing import Optional, Tuple, Union, List
import joblib
import numpy as np
from ConfigSpace import Configuration
from sklearn import clone
from sklearn.base import is_classifier
from sklearn.model_selection import check_cv
from sklearn.model_selection._validation import _fit_and_predict... | [
"dswizard.util.util.model_file",
"dswizard.util.util.score",
"numpy.reshape",
"sklearn.base.is_classifier",
"os.path.join",
"sklearn.model_selection._validation._fit_and_predict",
"sklearn.utils.indexable",
"sklearn.utils.validation._num_samples",
"numpy.concatenate",
"sklearn.clone",
"joblib.du... | [((819, 874), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'category': 'UserWarning'}), "('ignore', category=UserWarning)\n", (842, 874), False, 'import warnings\n'), ((1661, 1676), 'sklearn.clone', 'clone', (['pipeline'], {}), '(pipeline)\n', (1666, 1676), False, 'from sklearn import clone... |
import time
class TokenContainer:
tokens = {}
def __init__(self, access_token=None, refresh_token=None):
self.tokens["access"] = access_token
self.tokens["refresh"] = refresh_token
def set(self, access_or_refresh, token):
self.tokens[access_or_refresh] = token
def get(self,... | [
"time.time"
] | [((1059, 1070), 'time.time', 'time.time', ([], {}), '()\n', (1068, 1070), False, 'import time\n'), ((1444, 1455), 'time.time', 'time.time', ([], {}), '()\n', (1453, 1455), False, 'import time\n')] |
"""
Module realize VLImage - structure for storing image in special format.
"""
from enum import Enum
from pathlib import Path
from typing import Optional, Union
import requests
from FaceEngine import FormatType, Image as CoreImage # pylint: disable=E0611,E0401
import numpy as np
from PIL.Image import Image as PilImag... | [
"PIL.Image.fromarray",
"pathlib.Path",
"FaceEngine.Image",
"requests.get",
"numpy.array"
] | [((6990, 7001), 'FaceEngine.Image', 'CoreImage', ([], {}), '()\n', (6999, 7001), True, 'from FaceEngine import FormatType, Image as CoreImage\n'), ((11343, 11373), 'PIL.Image.fromarray', 'pilImage.fromarray', (['imageArray'], {}), '(imageArray)\n', (11361, 11373), True, 'from PIL import Image as pilImage\n'), ((6039, 6... |
"""
MatchTemplate
=============
The **MatchTemplate** module uses `normalized cross-correlation`_ to
match a template to a single-channel two-or-three dimensional image or
multi-channel two-dimensional image. The output of the module is an
image where each pixel corresponds to the `Pearson product-moment
correlation c... | [
"cellprofiler_core.setting.text.Pathname",
"cellprofiler_core.setting.text.ImageName",
"imageio.imread",
"cellprofiler_core.image.Image",
"cellprofiler_core.setting.subscriber.ImageSubscriber"
] | [((1550, 1615), 'cellprofiler_core.setting.subscriber.ImageSubscriber', 'ImageSubscriber', (['"""Image"""'], {'doc': '"""Select the image you want to use."""'}), "('Image', doc='Select the image you want to use.')\n", (1565, 1615), False, 'from cellprofiler_core.setting.subscriber import ImageSubscriber\n'), ((1668, 17... |
from __future__ import with_statement
from __future__ import absolute_import
import sys
if sys.version_info[0] < 3:
input = raw_input
import argparse
from NDATools.Download import Download
from NDATools.Configuration import *
import NDATools
import logging
def parse_args():
parser = argparse.ArgumentParser(
... | [
"NDATools.Download.Download",
"NDATools.Utils.logging.getLogger",
"argparse.ArgumentParser"
] | [((295, 731), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""This application allows you to enter a list of aws S3 paths and will download the files to your drive in your home folder. Alternatively, you may enter a packageID, an NDA data structure file or a text file with s3 links, and t... |
import os
import shutil
import pathlib
import stat
def mkdir_p(path, exist_ok=True):
"""
Creates the directory and paths leading up to it like unix mkdir -p .
Defaults to exist_ok so if it exists were not throwing fatal errors
https://docs.python.org/3.7/library/os.html#os.makedirs
"""
if not ... | [
"os.path.exists",
"shutil.chown",
"os.makedirs",
"pathlib.Path",
"os.access",
"os.path.join",
"os.symlink",
"os.chmod",
"os.stat",
"os.walk"
] | [((1880, 1893), 'os.walk', 'os.walk', (['path'], {}), '(path)\n', (1887, 1893), False, 'import os\n'), ((3216, 3229), 'os.walk', 'os.walk', (['path'], {}), '(path)\n', (3223, 3229), False, 'import os\n'), ((320, 340), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (334, 340), False, 'import os\n'), ((3... |
# modify from PointGroup
# Written by <NAME>
import os
import os.path as osp
import logging
from typing import Optional
from operator import itemgetter
from copy import deepcopy
import gorilla
import torch
import numpy as np
import open3d as o3d
COLORSEMANTIC = np.array([
[171, 198, 230], # rgb(171, 198, 230)
... | [
"gorilla.derive_logger",
"numpy.where",
"torch.load",
"os.path.join",
"os.path.isfile",
"open3d.io.read_triangle_mesh",
"numpy.array",
"open3d.io.write_point_cloud",
"numpy.zeros",
"open3d.geometry.PointCloud",
"copy.deepcopy",
"operator.itemgetter",
"numpy.loadtxt",
"numpy.load",
"numpy... | [((264, 617), 'numpy.array', 'np.array', (['[[171, 198, 230], [143, 223, 142], [0, 120, 177], [255, 188, 126], [189, \n 189, 57], [144, 86, 76], [255, 152, 153], [222, 40, 47], [197, 176, 212\n ], [150, 103, 185], [200, 156, 149], [0, 190, 206], [252, 183, 210], [\n 219, 219, 146], [255, 127, 43], [234, 119, 1... |
import os
import logging
import numpy as np
import pandas as pd
logger = logging.getLogger(__name__)
from supervised.utils.config import LOG_LEVEL
from supervised.utils.common import learner_name_to_fold_repeat
from supervised.utils.metric import Metric
logger.setLevel(LOG_LEVEL)
import matplotlib.pyplot as plt
impo... | [
"logging.getLogger",
"pandas.isnull",
"supervised.utils.common.learner_name_to_fold_repeat",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"os.path.join",
"matplotlib.pyplot.close",
"matplotlib.pyplot.fi... | [((74, 101), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (91, 101), False, 'import logging\n'), ((370, 401), 'matplotlib.colors.TABLEAU_COLORS.values', 'mcolors.TABLEAU_COLORS.values', ([], {}), '()\n', (399, 401), True, 'import matplotlib.colors as mcolors\n'), ((1560, 1587), 'matplot... |
import tensorflow as tf
from openea.models.trans.transe import TransE
from openea.modules.base.initializers import init_embeddings
from openea.modules.base.losses import get_loss_func
from openea.modules.base.optimizers import generate_optimizer
class TransR(TransE):
def __init__(self):
super().__init__... | [
"tensorflow.nn.embedding_lookup",
"openea.modules.base.losses.get_loss_func",
"openea.modules.base.optimizers.generate_optimizer",
"tensorflow.variable_scope",
"tensorflow.nn.l2_normalize",
"tensorflow.placeholder",
"openea.modules.base.initializers.init_embeddings",
"tensorflow.name_scope",
"tensor... | [((370, 416), 'tensorflow.variable_scope', 'tf.variable_scope', (["('relational' + 'embeddings')"], {}), "('relational' + 'embeddings')\n", (387, 416), True, 'import tensorflow as tf\n'), ((448, 561), 'openea.modules.base.initializers.init_embeddings', 'init_embeddings', (['[self.kgs.entities_num, self.args.dim]', '"""... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Clear the class names in case MappedClasses are declared in another example
from ming.odm import Mapper
Mapper._mapper_by_classname.clear()
from ming import create_datastore
from ming.odm import ThreadLocalODMSession
session = ThreadLocalODMSession(bind=create_datastore(... | [
"ming.odm.Mapper.compile_all",
"ming.odm.Mapper._mapper_by_classname.clear",
"ming.odm.RelationProperty",
"ming.odm.ForeignIdProperty",
"ming.schema.String",
"ming.odm.FieldProperty",
"ming.create_datastore"
] | [((152, 187), 'ming.odm.Mapper._mapper_by_classname.clear', 'Mapper._mapper_by_classname.clear', ([], {}), '()\n', (185, 187), False, 'from ming.odm import Mapper\n'), ((1752, 1772), 'ming.odm.Mapper.compile_all', 'Mapper.compile_all', ([], {}), '()\n', (1770, 1772), False, 'from ming.odm import Mapper\n'), ((586, 616)... |
import gym
import random
from collections import namedtuple, defaultdict
from typing import List, Tuple
import policy
import trainer
import episode
import epsilongreedy
class MonteCarloPolicyUpdater(policy.PolicyUpdater):
policy : policy.Policy
def __init__(self, policy : policy.Policy):
self.policy... | [
"trainer.run_trajectory",
"epsilongreedy.EpsilonGreedyPolicy",
"trainer.run",
"gym.make"
] | [((797, 822), 'gym.make', 'gym.make', (['"""FrozenLake-v1"""'], {}), "('FrozenLake-v1')\n", (805, 822), False, 'import gym\n'), ((930, 981), 'epsilongreedy.EpsilonGreedyPolicy', 'epsilongreedy.EpsilonGreedyPolicy', (['env.action_space'], {}), '(env.action_space)\n', (963, 981), False, 'import epsilongreedy\n'), ((1032,... |
# -*- coding: utf-8 -*-
import logging
from core.helpers.log_format import format_dict
from core.models.base_product import BaseProduct
class ProductCollection(object):
"""
Коллекция продуктов (простой список) в объектном виде.
умеет добавлять продукты по имени из указанного фида
"""
def __init... | [
"core.core.Core.get_instance"
] | [((728, 747), 'core.core.Core.get_instance', 'Core.get_instance', ([], {}), '()\n', (745, 747), False, 'from core.core import Core\n')] |
# ------------------------------------------------------------------------------
# Modified from https://github.com/microsoft/human-pose-estimation.pytorch
# ------------------------------------------------------------------------------
import torch.nn as nn
from ..resnet import _resnet, Bottleneck
class Upsampling(... | [
"torch.nn.BatchNorm2d",
"torch.nn.ReLU",
"torch.nn.init.constant_",
"torch.nn.Conv2d",
"torch.nn.ConvTranspose2d",
"torch.nn.init.normal_"
] | [((2862, 2965), 'torch.nn.Conv2d', 'nn.Conv2d', ([], {'in_channels': 'feature_dim', 'out_channels': 'num_keypoints', 'kernel_size': '(1)', 'stride': '(1)', 'padding': '(0)'}), '(in_channels=feature_dim, out_channels=num_keypoints, kernel_size=\n 1, stride=1, padding=0)\n', (2871, 2965), True, 'import torch.nn as nn\... |
import os
import random
import libvirt
from lxml import etree
from twisted.python import log
import util
import domains
def handler(ctxt, err):
global errno
errno = err
libvirt.registerErrorHandler(handler, 'pllm')
# taken from virtinst/_util.py (python-virtinst), GPLv2+
def fetch_all_guests(conn):
"... | [
"lxml.etree.Element",
"domains.LibvirtDomain",
"random.randint",
"twisted.python.log.msg",
"os.path.join",
"util.get_host_macs",
"util.destroy_libvirt_domain",
"lxml.etree.fromstring",
"libvirt.open",
"libvirt.registerErrorHandler",
"lxml.etree.tostring"
] | [((182, 227), 'libvirt.registerErrorHandler', 'libvirt.registerErrorHandler', (['handler', '"""pllm"""'], {}), "(handler, 'pllm')\n", (210, 227), False, 'import libvirt\n'), ((1370, 1391), 'lxml.etree.fromstring', 'etree.fromstring', (['xml'], {}), '(xml)\n', (1386, 1391), False, 'from lxml import etree\n'), ((1544, 15... |
from bisect import bisect_right
from utils.misc import source_import
import torch
class WarmupMultiStepLR(torch.optim.lr_scheduler._LRScheduler):
def __init__(
self,
optimizer,
milestones,
gamma=0.1,
warmup_factor=1.0 / 3,
warmup_epochs=5,
warmup_method="line... | [
"torch.optim.Adam",
"torch.optim.SGD",
"models.model.DotProduct_Classifier",
"utils.misc.source_import",
"bisect.bisect_right",
"torch.cuda.is_available",
"models.model.BBN_ResNet_Cifar",
"models.model.ResNet",
"loss.BalancedCE.create_loss"
] | [((6514, 6538), 'loss.BalancedCE.create_loss', 'create_loss', ([], {}), '(**loss_args)\n', (6525, 6538), False, 'from loss.BalancedCE import create_loss\n'), ((1813, 1838), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (1836, 1838), False, 'import torch\n'), ((5655, 5680), 'torch.cuda.is_avail... |