code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
from enum import Enum, unique
@unique
class Weekday(Enum):
Sun = 0
Mon = 1
Tue = 2
Web = 3
Thu = 4
Fri = 5
Sat = 6
day1 = Weekday.Mon
print('day1 =', day1)
print('Weekday.Tue =', Weekday.Tue)
print('Weekday[\'Tue\'] =', Weekday['Tue'])
print(... | [
"enum.Enum"
] | [((605, 708), 'enum.Enum', 'Enum', (['"""Month"""', "('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct',\n 'Nov', 'Dec')"], {}), "('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug',\n 'Sep', 'Oct', 'Nov', 'Dec'))\n", (609, 708), False, 'from enum import Enum, unique\n')] |
#! /usr/bin/env python3
import json
import mimetypes
import os
import re
import shutil
import string
import sys
import tarfile
import urllib.parse
import urllib.request
from collections import defaultdict, namedtuple
from http.server import BaseHTTPRequestHandler, HTTPServer
from bs4 import BeautifulSoup # pip3 in... | [
"os.path.exists",
"collections.namedtuple",
"shutil.copyfileobj",
"os.rename",
"json.dumps",
"os.path.join",
"re.match",
"os.path.dirname",
"collections.defaultdict",
"tarfile.extractfile",
"re.findall"
] | [((351, 379), 'collections.namedtuple', 'namedtuple', (['"""Symbol"""', '"""name"""'], {}), "('Symbol', 'name')\n", (361, 379), False, 'from collections import defaultdict, namedtuple\n'), ((405, 430), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (420, 430), False, 'import os\n'), ((601, 63... |
import os, sys, matplotlib
import faulthandler; faulthandler.enable()
mpl_v = 'MPL-8'
daptype = 'SPX-MILESHC-MILESHC'
os.environ['STELLARMASS_PCA_RESULTSDIR'] = '/Users/admin/sas/mangawork/manga/mangapca/zachpace/CSPs_CKC14_MaNGA_20190215-1/v2_5_3/2.3.0/results'
manga_results_basedir = os.environ['STELLARMASS_PCA_RESU... | [
"matplotlib.use",
"os.path.join",
"faulthandler.enable"
] | [((48, 69), 'faulthandler.enable', 'faulthandler.enable', ([], {}), '()\n', (67, 69), False, 'import faulthandler\n'), ((526, 589), 'os.path.join', 'os.path.join', (["os.environ['STELLARMASS_PCA_RESULTSDIR']", '"""mocks"""'], {}), "(os.environ['STELLARMASS_PCA_RESULTSDIR'], 'mocks')\n", (538, 589), False, 'import os, s... |
import random
r1 = random.randint(1, 40)
print("Generate a random number without a seed between a range of two numbers - Integer:", r1)
r2 = random.uniform(1, 40)
print("Generate a random number without a seed between a range of two numbers - Decimal:", r2)
| [
"random.uniform",
"random.randint"
] | [((20, 41), 'random.randint', 'random.randint', (['(1)', '(40)'], {}), '(1, 40)\n', (34, 41), False, 'import random\n'), ((144, 165), 'random.uniform', 'random.uniform', (['(1)', '(40)'], {}), '(1, 40)\n', (158, 165), False, 'import random\n')] |
#!/usr/bin/python
#use to parse ms-sql-info nmap xml
#https://nmap.org/nsedoc/scripts/ms-sql-info.html
#nmap -Pn -n -p135,445,1433 --script ms-sql-info <host> -oX results-ms-sql-info.xml
#nmap -Pn -n -p135,445,1433 --script ms-sql-info -iL <hosts_file> -oX results-ms-sql-info.xml
# python3 mssql-info-parser.py... | [
"xml.etree.ElementTree.Element",
"xml.etree.ElementTree.parse",
"collections.defaultdict",
"sys.exit"
] | [((980, 1002), 'xml.etree.ElementTree.parse', 'ET.parse', (['masssql_file'], {}), '(masssql_file)\n', (988, 1002), True, 'import xml.etree.ElementTree as ET\n'), ((821, 831), 'sys.exit', 'sys.exit', ([], {}), '()\n', (829, 831), False, 'import sys\n'), ((874, 884), 'sys.exit', 'sys.exit', ([], {}), '()\n', (882, 884), ... |
from kivy.app import App
from controller.game import Game
from controller.actor import Local, AI
class GameApp(App):
def build(self):
game = Game()
game.actors = [
Local(game=game, name='player1'),
AI(game=game, name='player2'),
]
view = game.actors[0].vi... | [
"controller.actor.Local",
"controller.game.Game",
"controller.actor.AI"
] | [((158, 164), 'controller.game.Game', 'Game', ([], {}), '()\n', (162, 164), False, 'from controller.game import Game\n'), ((201, 233), 'controller.actor.Local', 'Local', ([], {'game': 'game', 'name': '"""player1"""'}), "(game=game, name='player1')\n", (206, 233), False, 'from controller.actor import Local, AI\n'), ((24... |
from carp_api.routing import router
from . import endpoints # NOQA
# to use pong we need to disable common routes as they are using conflicting
# urls
router.enable(endpoints=[
endpoints.UberPong,
])
| [
"carp_api.routing.router.enable"
] | [((155, 200), 'carp_api.routing.router.enable', 'router.enable', ([], {'endpoints': '[endpoints.UberPong]'}), '(endpoints=[endpoints.UberPong])\n', (168, 200), False, 'from carp_api.routing import router\n')] |
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
An example of reading a line at a time from standard input
without blocking the reactor.
"""
from os import linesep
from twisted.internet import stdio
from twisted.protocols import basic
class Echo(basic.LineReceiver):
delimiter = lin... | [
"os.linesep.encode",
"twisted.internet.reactor.run"
] | [((317, 340), 'os.linesep.encode', 'linesep.encode', (['"""ascii"""'], {}), "('ascii')\n", (331, 340), False, 'from os import linesep\n'), ((612, 625), 'twisted.internet.reactor.run', 'reactor.run', ([], {}), '()\n', (623, 625), False, 'from twisted.internet import reactor\n')] |
import networkx as nx
class Hierarchy:
def __init__(self, tree, column):
self.tree = tree
self.column = column
def _leaves_below(self, node):
leaves = sum(([vv for vv in v if self.tree.out_degree(vv) == 0]
for k, v in nx.dfs_successors(self.tree, node).items()),
... | [
"networkx.dfs_successors"
] | [((275, 309), 'networkx.dfs_successors', 'nx.dfs_successors', (['self.tree', 'node'], {}), '(self.tree, node)\n', (292, 309), True, 'import networkx as nx\n')] |
# coding = utf-8
from inherit_abstract.abstractcollection import AbstractCollection
class AbstractDict(AbstractCollection):
"""
Common data and method implementations for dictionaries.
"""
def __init__(self, source_collection):
"""
Will copy items to the collection from source_collect... | [
"inherit_abstract.abstractcollection.AbstractCollection.__init__"
] | [((361, 394), 'inherit_abstract.abstractcollection.AbstractCollection.__init__', 'AbstractCollection.__init__', (['self'], {}), '(self)\n', (388, 394), False, 'from inherit_abstract.abstractcollection import AbstractCollection\n')] |
import logging
from functools import partial
from django import forms
from django.db import models
from django.utils.translation import ugettext_lazy as _
from simple_history.admin import SimpleHistoryAdmin
from simple_history.models import HistoricalRecords
from simple_history.utils import update_change_reason
log =... | [
"logging.getLogger",
"django.utils.translation.ugettext_lazy",
"functools.partial",
"simple_history.utils.update_change_reason"
] | [((321, 348), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (338, 348), False, 'import logging\n'), ((1575, 1637), 'functools.partial', 'partial', (['HistoricalRecords'], {'bases': '[ExtraFieldsHistoricalModel]'}), '(HistoricalRecords, bases=[ExtraFieldsHistoricalModel])\n', (1582, 1637)... |
#!/usr/bin/env python
import numpy
import storm_analysis
import storm_analysis.simulator.pupil_math as pupilMath
def test_pupil_math_1():
"""
Test GeometryC, intensity, no scaling.
"""
geo = pupilMath.Geometry(20, 0.1, 0.6, 1.5, 1.4)
geo_c = pupilMath.GeometryC(20, 0.1, 0.6, 1.5, 1.4)
pf = ... | [
"numpy.allclose",
"storm_analysis.simulator.pupil_math.GeometryVectorial",
"storm_analysis.simulator.pupil_math.GeometryC",
"numpy.linspace",
"storm_analysis.simulator.pupil_math.GeometryCVectorial",
"storm_analysis.simulator.pupil_math.Geometry"
] | [((211, 253), 'storm_analysis.simulator.pupil_math.Geometry', 'pupilMath.Geometry', (['(20)', '(0.1)', '(0.6)', '(1.5)', '(1.4)'], {}), '(20, 0.1, 0.6, 1.5, 1.4)\n', (229, 253), True, 'import storm_analysis.simulator.pupil_math as pupilMath\n'), ((266, 309), 'storm_analysis.simulator.pupil_math.GeometryC', 'pupilMath.G... |
import numpy as np
import gdal
from ..utils.indexing import _LocIndexer, _iLocIndexer
from libpyhat.transform.continuum import continuum_correction
from libpyhat.transform.continuum import polynomial, linear, regression
class HCube(object):
"""
A Mixin class for use with the io_gdal.GeoDataset class
to o... | [
"numpy.copy",
"libpyhat.transform.continuum.continuum_correction",
"numpy.array",
"numpy.stack",
"gdal.Info",
"numpy.round"
] | [((2841, 2853), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (2849, 2853), True, 'import numpy as np\n'), ((3684, 3867), 'libpyhat.transform.continuum.continuum_correction', 'continuum_correction', (['self.data', 'self.wavelengths'], {'nodes': 'nodes', 'correction_nodes': 'correction_nodes', 'correction': 'correc... |
import orderedset
def find_cycle(nodes, successors):
path = orderedset.orderedset()
visited = set()
def visit(node):
# If the node is already in the current path, we have found a cycle.
if not path.add(node):
return (path, node)
# If we have otherwise already visit... | [
"orderedset.orderedset"
] | [((65, 88), 'orderedset.orderedset', 'orderedset.orderedset', ([], {}), '()\n', (86, 88), False, 'import orderedset\n')] |
# -*- coding: utf-8 -*- #
# Copyright 2021 Google LLC. 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 requir... | [
"six.text_type"
] | [((2740, 2768), 'six.text_type', 'six.text_type', (['duration_mins'], {}), '(duration_mins)\n', (2753, 2768), False, 'import six\n')] |
#!/usr/bin/env python3
"""
Tests of ktrain text classification flows
"""
import sys
import os
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID";
os.environ["CUDA_VISIBLE_DEVICES"]="0"
sys.path.insert(0,'../..')
from unittest import TestCase, main, skip
import ktrain
def synthetic_multilabel():
import numpy as np
... | [
"sys.path.insert",
"keras.layers.GlobalAveragePooling1D",
"keras.models.Sequential",
"ktrain.get_learner",
"numpy.array",
"keras.layers.Dense",
"unittest.main",
"keras.layers.Embedding"
] | [((179, 206), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""../.."""'], {}), "(0, '../..')\n", (194, 206), False, 'import sys\n'), ((1700, 1711), 'numpy.array', 'np.array', (['X'], {}), '(X)\n', (1708, 1711), True, 'import numpy as np\n'), ((1720, 1731), 'numpy.array', 'np.array', (['Y'], {}), '(Y)\n', (1728, 1731... |
"""
Keras implementation of Pix2Pix from <NAME>'s tutorial.
https://machinelearningmastery.com/how-to-develop-a-pix2pix-gan-for-image-to-image-translation/
"""
from keras.initializers import RandomNormal
from keras.layers import Activation, BatchNormalization, Concatenate, Conv2D, Conv2DTranspose, Dropout, LeakyReLU
f... | [
"keras.optimizers.Adam",
"keras.layers.Conv2D",
"keras.layers.LeakyReLU",
"keras.layers.Concatenate",
"keras.models.Model",
"keras.models.Input",
"keras.layers.Activation",
"keras.layers.Conv2DTranspose",
"keras.layers.BatchNormalization",
"keras.layers.Dropout",
"keras.initializers.RandomNormal... | [((473, 498), 'keras.initializers.RandomNormal', 'RandomNormal', ([], {'stddev': '(0.02)'}), '(stddev=0.02)\n', (485, 498), False, 'from keras.initializers import RandomNormal\n'), ((521, 545), 'keras.models.Input', 'Input', ([], {'shape': 'image_shape'}), '(shape=image_shape)\n', (526, 545), False, 'from keras.models ... |
import lx, lxifc, lxu.command, tagger
CMD_NAME = tagger.CMD_PTAG_QUICK_SELECT_POPUP
class CommandClass(tagger.CommanderClass):
#_commander_default_values = []
def commander_arguments(self):
return [
{
'name': tagger.TAGTYPE,
'label': tagger.LAB... | [
"lx.eval",
"tagger.convert_to_iPOLYTAG",
"tagger.scene.all_tags_by_type",
"tagger.build_arg_string",
"tagger.convert_to_tagType_label",
"lx.bless",
"tagger.Notifier"
] | [((1966, 1998), 'lx.bless', 'lx.bless', (['CommandClass', 'CMD_NAME'], {}), '(CommandClass, CMD_NAME)\n', (1974, 1998), False, 'import lx, lxifc, lxu.command, tagger\n'), ((1148, 1215), 'tagger.build_arg_string', 'tagger.build_arg_string', (['{tagger.TAGTYPE: tagType, tagger.TAG: tag}'], {}), '({tagger.TAGTYPE: tagType... |
import tensorflow as tf
from tensorflow.keras.applications import MobileNetV2
from tensorflow.keras.layers import Dense, GlobalAveragePooling2D, Add,\
GlobalMaxPooling2D
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import Adam
def MobileNetV2_avg_max(input_shape, num_classes):
bas... | [
"tensorflow.keras.optimizers.Adam",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.models.Model",
"tensorflow.keras.applications.MobileNetV2",
"tensorflow.keras.layers.GlobalAveragePooling2D"
] | [((330, 405), 'tensorflow.keras.applications.MobileNetV2', 'MobileNetV2', ([], {'weights': '"""imagenet"""', 'include_top': '(False)', 'input_shape': 'input_shape'}), "(weights='imagenet', include_top=False, input_shape=input_shape)\n", (341, 405), False, 'from tensorflow.keras.applications import MobileNetV2\n'), ((10... |
import json
import pytest
from asynctest import TestCase as AsyncTestCase, mock as async_mock
from copy import deepcopy
from pathlib import Path
from shutil import rmtree
import base58
from ....config.injection_context import InjectionContext
from ....storage.base import BaseStorage
from ....storage.basic import Ba... | [
"asynctest.mock.MagicMock",
"asynctest.mock.patch.object",
"copy.deepcopy",
"shutil.rmtree"
] | [((2332, 2369), 'shutil.rmtree', 'rmtree', (['TAILS_DIR'], {'ignore_errors': '(True)'}), '(TAILS_DIR, ignore_errors=True)\n', (2338, 2369), False, 'from shutil import rmtree\n'), ((3748, 3769), 'copy.deepcopy', 'deepcopy', (['REV_REG_DEF'], {}), '(REV_REG_DEF)\n', (3756, 3769), False, 'from copy import deepcopy\n'), ((... |
#!/usr/bin/env python
import os
import sys
from optparse import OptionParser
def parse_args():
parser = OptionParser()
parser.add_option('-s', '--settings', help='Define settings.')
parser.add_option('-t', '--unittest', help='Define which test to run. Default all.')
options, args = parser.parse_args(... | [
"django.setup",
"optparse.OptionParser",
"django.test.utils.get_runner",
"sys.exit"
] | [((111, 125), 'optparse.OptionParser', 'OptionParser', ([], {}), '()\n', (123, 125), False, 'from optparse import OptionParser\n'), ((848, 868), 'django.test.utils.get_runner', 'get_runner', (['settings'], {}), '(settings)\n', (858, 868), False, 'from django.test.utils import get_runner\n'), ((931, 959), 'django.test.u... |
import os
def Usage():
print("Commands : ") #输出帮助信息
print("+----------------------------------------------------+")
print("|Num|Command | Describe |")
print("+----------------------------------------------------+")
print("|0. | help | ... | [
"os.path.join",
"os.walk"
] | [((1580, 1599), 'os.walk', 'os.walk', (['"""Scripts/"""'], {}), "('Scripts/')\n", (1587, 1599), False, 'import os\n'), ((1632, 1656), 'os.path.join', 'os.path.join', (['root', 'file'], {}), '(root, file)\n', (1644, 1656), False, 'import os\n')] |
import smbus
class AtlasOEM(object):
DEFAULT_BUS = 1
def __init__(self, address, name = "", bus=None):
self._address = address
self.bus = smbus.SMBus(bus or self.DEFAULT_BUS)
self._name = name
def read_byte(self, reg):
return self.bus.read_byte_data(self._addre... | [
"smbus.SMBus"
] | [((168, 204), 'smbus.SMBus', 'smbus.SMBus', (['(bus or self.DEFAULT_BUS)'], {}), '(bus or self.DEFAULT_BUS)\n', (179, 204), False, 'import smbus\n')] |
import threading
import os
import obd
from random import random
from pathlib import Path
conn = obd.OBD()
connect = obd.Async(fast=False)
speed=""
fueli=""
tem =""
def get_temp(t):
if not t.is_null():
tem=str(t.value)
if t.is_null():
tem=str(0)
def get_fuel(f):
if n... | [
"obd.OBD",
"obd.Async"
] | [((109, 118), 'obd.OBD', 'obd.OBD', ([], {}), '()\n', (116, 118), False, 'import obd\n'), ((129, 150), 'obd.Async', 'obd.Async', ([], {'fast': '(False)'}), '(fast=False)\n', (138, 150), False, 'import obd\n')] |
from django.contrib import admin
from django import forms
from . import models
class PizzaFlavorAdminForm(forms.ModelForm):
class Meta:
model = models.PizzaFlavor
fields = "__all__"
class PizzaFlavorAdmin(admin.ModelAdmin):
form = PizzaFlavorAdminForm
list_display = [
"id",
... | [
"django.contrib.admin.site.register"
] | [((1808, 1865), 'django.contrib.admin.site.register', 'admin.site.register', (['models.PizzaFlavor', 'PizzaFlavorAdmin'], {}), '(models.PizzaFlavor, PizzaFlavorAdmin)\n', (1827, 1865), False, 'from django.contrib import admin\n'), ((1866, 1925), 'django.contrib.admin.site.register', 'admin.site.register', (['models.Ord... |
#!/usr/bin/env python2.7
#
# This file is part of peakAnalysis, http://github.com/alexjgriffith/peaks/,
# and is Copyright (C) University of Ottawa, 2014. It is Licensed under
# the three-clause BSD License; see doc/LICENSE.txt.
# Contact: <EMAIL>
#
# Created : AUG262014
# File : buildPeaksClass
# Author : <NAME>... | [
"peakClass.peakCapHandler",
"buildPeaksClass.buildPeaks",
"argparse.ArgumentParser",
"sys.stdout.write"
] | [((615, 767), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'prog': '"""TAG"""', 'description': '"""Combine and tag input files."""', 'epilog': '"""File Format: <bed file location><catagory><value>..."""'}), "(prog='TAG', description=\n 'Combine and tag input files.', epilog=\n 'File Format: <bed fi... |
# -*- coding: utf-8 -*-
"""
.. module:: skimpy
:platform: Unix, Windows
:synopsis: Simple Kinetic Models in Python
.. moduleauthor:: SKiMPy team
[---------]
Copyright 2017 Laboratory of Computational Systems Biotechnology (LCSB),
Ecole Polytechnique Federale de Lausanne (EPFL), Switzerland
Licensed under the ... | [
"skimpy.analysis.ode.utils.make_flux_fun",
"skimpy.io.generate_from_pytfa.FromPyTFA",
"pytfa.io.import_matlab_model",
"numpy.log",
"skimpy.sampling.simple_parameter_sampler.SimpleParameterSampler.Parameters",
"pytfa.io.load_thermoDB",
"skimpy.sampling.simple_parameter_sampler.SimpleParameterSampler",
... | [((1890, 1948), 'pytfa.io.import_matlab_model', 'import_matlab_model', (['"""../../models/toy_model.mat"""', '"""model"""'], {}), "('../../models/toy_model.mat', 'model')\n", (1909, 1948), False, 'from pytfa.io import import_matlab_model, load_thermoDB\n'), ((2080, 2128), 'pytfa.io.load_thermoDB', 'load_thermoDB', (['"... |
from opswat import MetaDefenderApi
if __name__ == "__main__":
md = MetaDefenderApi(ip="10.26.50.15", port=8008)
#dir = "files"
dir = "C:\\Users\\10694\\dev"
results = md.scan_directory(dir)
print(results) | [
"opswat.MetaDefenderApi"
] | [((74, 118), 'opswat.MetaDefenderApi', 'MetaDefenderApi', ([], {'ip': '"""10.26.50.15"""', 'port': '(8008)'}), "(ip='10.26.50.15', port=8008)\n", (89, 118), False, 'from opswat import MetaDefenderApi\n')] |
import os
import pytest
@pytest.fixture(scope="module")
def some_context():
return [1,2,3,4,5]
def get_scripts():
with open(config_file) as f:
scripts = [line.strip('\n') for line in f.readlines()]
return scripts
config_file = os.environ["RECIPY_TEST_CASES_CONFIG"]
def case_name(value):
retu... | [
"pytest.fixture",
"pytest.fail"
] | [((26, 56), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (40, 56), False, 'import pytest\n'), ((511, 550), 'pytest.fail', 'pytest.fail', (['script', '""" failed its test"""'], {}), "(script, ' failed its test')\n", (522, 550), False, 'import pytest\n')] |
import builtins
from larval_gonad.mock import MockSnake
from larval_gonad.config import read_config
builtins.snakemake = MockSnake(
input="../../output/paper_submission/fig1_data_avg_tpm_per_chrom.feather",
params=dict(colors=read_config("../../config/colors.yaml")),
)
| [
"larval_gonad.config.read_config"
] | [((236, 275), 'larval_gonad.config.read_config', 'read_config', (['"""../../config/colors.yaml"""'], {}), "('../../config/colors.yaml')\n", (247, 275), False, 'from larval_gonad.config import read_config\n')] |
from wsgiserver import WSGIServer
import sys
class Server(WSGIServer):
def error_log(self, msg="", level=20, traceback=False):
# Override this in subclasses as desired
import logging
lgr = logging.getLogger('theonionbox')
e = sys.exc_info()[1]
if e.args[1].find('UNKNOWN_CA... | [
"logging.getLogger",
"sys.exc_info"
] | [((220, 252), 'logging.getLogger', 'logging.getLogger', (['"""theonionbox"""'], {}), "('theonionbox')\n", (237, 252), False, 'import logging\n'), ((265, 279), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (277, 279), False, 'import sys\n')] |
# Generated by Django 2.1 on 2018-08-16 20:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('fpl', '0016_auto_20180816_2020'),
]
operations = [
migrations.AlterField(
model_name='classicleague',
name='fpl_league... | [
"django.db.models.IntegerField"
] | [((344, 365), 'django.db.models.IntegerField', 'models.IntegerField', ([], {}), '()\n', (363, 365), False, 'from django.db import migrations, models\n'), ((504, 525), 'django.db.models.IntegerField', 'models.IntegerField', ([], {}), '()\n', (523, 525), False, 'from django.db import migrations, models\n')] |
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from rest_framework import status
from rest_framework.request import Request
from rest_framework.test import APIClient, APIRequestFactory
from user import models, serializers
FAMILY_DATA_URL = reverse('user... | [
"django.contrib.auth.get_user_model",
"user.serializers.BiodataSerializer",
"user.models.FamilyData.objects.create",
"user.models.FamilyData.objects.all",
"rest_framework.test.APIClient",
"user.serializers.FamilyDataSerializer",
"user.models.FamilyData.objects.get",
"django.urls.reverse",
"user.mode... | [((307, 338), 'django.urls.reverse', 'reverse', (['"""user:familydata-list"""'], {}), "('user:familydata-list')\n", (314, 338), False, 'from django.urls import reverse\n'), ((376, 395), 'rest_framework.test.APIRequestFactory', 'APIRequestFactory', ([], {}), '()\n', (393, 395), False, 'from rest_framework.test import AP... |
#!/usr/bin/env python
import datetime
import json
import pathlib
import re
import sys
from typing import List, Optional
from vaccine_feed_ingest_schema import location as schema
from vaccine_feed_ingest.utils.log import getLogger
logger = getLogger(__file__)
RUNNER_ID = "az_pinal_ph_vaccinelocations_gov"
def _g... | [
"json.loads",
"pathlib.Path",
"datetime.datetime.utcnow",
"vaccine_feed_ingest.utils.log.getLogger",
"vaccine_feed_ingest_schema.location.Vaccine",
"vaccine_feed_ingest_schema.location.Contact",
"vaccine_feed_ingest_schema.location.Organization",
"re.sub",
"json.dump",
"re.search"
] | [((243, 262), 'vaccine_feed_ingest.utils.log.getLogger', 'getLogger', (['__file__'], {}), '(__file__)\n', (252, 262), False, 'from vaccine_feed_ingest.utils.log import getLogger\n'), ((4761, 4786), 'pathlib.Path', 'pathlib.Path', (['sys.argv[2]'], {}), '(sys.argv[2])\n', (4773, 4786), False, 'import pathlib\n'), ((4846... |
from sqlalchemy import Boolean, Column, Integer, String
from app.models.base import Base
class OJ(Base):
__tablename__ = 'oj'
fields = ['id', 'name', 'status', 'need_password']
id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(String(100), unique=True)
url = Column(String... | [
"sqlalchemy.String",
"sqlalchemy.Column"
] | [((199, 252), 'sqlalchemy.Column', 'Column', (['Integer'], {'primary_key': '(True)', 'autoincrement': '(True)'}), '(Integer, primary_key=True, autoincrement=True)\n', (205, 252), False, 'from sqlalchemy import Boolean, Column, Integer, String\n'), ((341, 372), 'sqlalchemy.Column', 'Column', (['Integer'], {'nullable': '... |
"""
Usage Instructions:
10-shot sinusoid:
python main.py --datasource=sinusoid --logdir=logs/sine/ --metatrain_iterations=70000 --norm=None --update_batch_size=10
10-shot sinusoid baselines:
python main.py --datasource=sinusoid --logdir=logs/sine/ --pretrain_iterations=70000 --metatrain_iterati... | [
"numpy.sqrt",
"matplotlib.pyplot.fill_between",
"numpy.array",
"numpy.nanmean",
"numpy.sin",
"numpy.mean",
"tensorflow.slice",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.close",
"numpy.linspace",
"numpy.random.seed",
"tensorflow.summary.merge_all",
"tensorflow.python.platform.flags.DEFINE_... | [((2210, 2299), 'tensorflow.python.platform.flags.DEFINE_string', 'flags.DEFINE_string', (['"""datasource"""', '"""sinusoid"""', '"""sinusoid or omniglot or miniimagenet"""'], {}), "('datasource', 'sinusoid',\n 'sinusoid or omniglot or miniimagenet')\n", (2229, 2299), False, 'from tensorflow.python.platform import f... |
from typing import Callable, AsyncGenerator, Generator
import asyncio
import httpx
import pytest
from asgi_lifespan import LifespanManager
from fastapi import FastAPI
from fastapi.testclient import TestClient
TestClientGenerator = Callable[[FastAPI], AsyncGenerator[httpx.AsyncClient, None]]
@pytest.fixture(scope="s... | [
"fastapi.testclient.TestClient",
"httpx.AsyncClient",
"pytest.fixture",
"asyncio.set_event_loop",
"asyncio.get_event_loop",
"asgi_lifespan.LifespanManager"
] | [((297, 328), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (311, 328), False, 'import pytest\n'), ((358, 382), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (380, 382), False, 'import asyncio\n'), ((1549, 1601), 'httpx.AsyncClient', 'httpx.AsyncCli... |
import numpy as np
import torch
from scipy.stats import norm
from codes.worker import ByzantineWorker
from codes.aggregator import DecentralizedAggregator
class DecentralizedByzantineWorker(ByzantineWorker):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# The target of at... | [
"torch.mean",
"torch.stack",
"scipy.stats.norm.ppf",
"numpy.floor",
"torch.std"
] | [((4811, 4833), 'torch.stack', 'torch.stack', (['models', '(1)'], {}), '(models, 1)\n', (4822, 4833), False, 'import torch\n'), ((4847, 4876), 'torch.mean', 'torch.mean', (['stacked_models', '(1)'], {}), '(stacked_models, 1)\n', (4857, 4876), False, 'import torch\n'), ((4891, 4919), 'torch.std', 'torch.std', (['stacked... |
#!/usr/bin/env python
#coding: utf8
"""Zipper
A class that can zip and unzip files.
"""
__author__ = "<NAME>"
__license__ = "GPLv3+"
import os
import zipfile
try:
import zlib
has_zlib = True
except:
has_zlib = False
class Zipper(object):
"""This is the main class.
Can zip and unzi... | [
"os.makedirs",
"os.path.join",
"zipfile.ZipFile"
] | [((812, 839), 'zipfile.ZipFile', 'zipfile.ZipFile', (['name', 'mode'], {}), '(name, mode)\n', (827, 839), False, 'import zipfile\n'), ((1025, 1055), 'zipfile.ZipFile', 'zipfile.ZipFile', (['file_to_unzip'], {}), '(file_to_unzip)\n', (1040, 1055), False, 'import zipfile\n'), ((1157, 1177), 'os.makedirs', 'os.makedirs', ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Author: <NAME> <<EMAIL>>
# PGP: https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x00bebdd0437ad513a4a0e13d93435cab4ca92fb9
# Date: 05.11.2021
import argparse
import os
# Unicode placeholders and their replacements
uc_table = {
b"LRE": chr(0x202a)... | [
"os.path.exists",
"argparse.ArgumentParser"
] | [((3599, 3701), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Generate malicious code using bidi-attack (CVE-2021-42574)"""'}), "(description=\n 'Generate malicious code using bidi-attack (CVE-2021-42574)')\n", (3622, 3701), False, 'import argparse\n'), ((5267, 5289), 'os.path.exists... |
"""
Unit tests for the plugin_support module
This is just a hack to invoke it..not a unit test
Copyright 2022 <NAME>
SPDX-License-Identifier: Apache-2.0
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 Licens... | [
"os.path.dirname",
"rvc2mqtt.plugin_support.PluginSupport"
] | [((970, 995), 'rvc2mqtt.plugin_support.PluginSupport', 'PluginSupport', (['p_path', '{}'], {}), '(p_path, {})\n', (983, 995), False, 'from rvc2mqtt.plugin_support import PluginSupport\n'), ((877, 902), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (892, 902), False, 'import os\n')] |
from data_types.user import User
class PullRequestReview:
"""
GitHub Pull Request Review
https://developer.github.com/v3/pulls/reviews/
Attributes:
id: Review id
body: Review body text
html_url: Public URL for issue on github.com
state: approved|commented|changes_requ... | [
"data_types.user.User"
] | [((689, 707), 'data_types.user.User', 'User', (["data['user']"], {}), "(data['user'])\n", (693, 707), False, 'from data_types.user import User\n')] |
"""Utilities for tests"""
import copy
import re
BAD_ID = "line %s: id '%s' doesn't match '%s'"
BAD_SEQLEN = "line %s: %s is not the same length as the first read (%s)"
BAD_BASES = "line %s: %s is not in allowed set of bases %s"
BAD_PLUS = "line %s: expected '+', got %s"
BAD_QUALS = "line %s: %s is not the same lengt... | [
"copy.deepcopy",
"re.compile"
] | [((1426, 1498), 're.compile', 're.compile', (['"""^@(.+)_(\\\\d+)_(\\\\d+)_e(\\\\d+)_e(\\\\d+)_([a-f0-9]+)\\\\/([12])$"""'], {}), "('^@(.+)_(\\\\d+)_(\\\\d+)_e(\\\\d+)_e(\\\\d+)_([a-f0-9]+)\\\\/([12])$')\n", (1436, 1498), False, 'import re\n'), ((5412, 5435), 'copy.deepcopy', 'copy.deepcopy', (['original'], {}), '(orig... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import datetime
import pathlib
import gpxpy
import pandas as pd
import statistics
import seaborn
import matplotlib.pyplot as plt
from activity import Activity, create_activity, parse_activities_csv
def select_activity(activities, iso_date=None):
"""Given a l... | [
"pandas.DataFrame",
"datetime.datetime.now",
"pandas.Grouper",
"datetime.datetime.fromisoformat"
] | [((1653, 1676), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (1674, 1676), False, 'import datetime\n'), ((2460, 2619), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': "{'name': ride_names, 'date': ride_dates, 'moving_time': ride_moving_times,\n 'distance': ride_distances, 'elevation': ride_e... |
from flask import Blueprint
bp_album = Blueprint('album', __name__)
from . import views
| [
"flask.Blueprint"
] | [((40, 68), 'flask.Blueprint', 'Blueprint', (['"""album"""', '__name__'], {}), "('album', __name__)\n", (49, 68), False, 'from flask import Blueprint\n')] |
import json
from base64 import b64encode, b64decode
from flask import abort, request, redirect
from simplecrypt import encrypt, decrypt
from secrets import ENCRYPTION_SECRET
def route_apis(app):
@app.route('/api/encrypt', methods=['GET', 'POST'])
def encrypt_layout():
if request.method == "POST":
... | [
"simplecrypt.decrypt",
"json.loads",
"base64.b64encode",
"json.dumps",
"flask.redirect",
"flask.abort"
] | [((805, 818), 'flask.redirect', 'redirect', (['"""/"""'], {}), "('/')\n", (813, 818), False, 'from flask import abort, request, redirect\n'), ((1417, 1430), 'flask.redirect', 'redirect', (['"""/"""'], {}), "('/')\n", (1425, 1430), False, 'from flask import abort, request, redirect\n'), ((358, 382), 'json.loads', 'json.... |
import re
_ARGS = r"\[[^]]+\]"
_IDENTITIFER = r"[a-zA-Z_][_0-9a-zA-Z]*"
_MODULE_PATH = r"[\.a-zA-Z_][\._0-9a-zA-Z]*"
def _REMEMBER(x, name):
return "(?P<{0}>{1})".format(name, x)
def _OPTIONAL(*x):
return "(?:{0})?".format(''.join(x))
FILTER_STRING_RE = ''.join((
'^',
_REMEMBER(_MODULE_PATH, "modu... | [
"re.compile"
] | [((725, 753), 're.compile', 're.compile', (['FILTER_STRING_RE'], {}), '(FILTER_STRING_RE)\n', (735, 753), False, 'import re\n')] |
import time
import Ordem
class ContaTempo():
def compara(self, tamanho_da_lista):
'''Compara o tempo exercido para ordenar uma lista com o tamanho passado'''
l = Ordem.Lista()
lista1 = l.crialista(tamanho_da_lista)
lista2 = lista1[:]
o = Ordem.Ordenacao()
antes = time.time... | [
"Ordem.Ordenacao",
"Ordem.Lista",
"time.time"
] | [((178, 191), 'Ordem.Lista', 'Ordem.Lista', ([], {}), '()\n', (189, 191), False, 'import Ordem\n'), ((279, 296), 'Ordem.Ordenacao', 'Ordem.Ordenacao', ([], {}), '()\n', (294, 296), False, 'import Ordem\n'), ((311, 322), 'time.time', 'time.time', ([], {}), '()\n', (320, 322), False, 'import time\n'), ((409, 420), 'time.... |
#T# the following code shows how to draw the slope of the perpendicular line to a given line
#T# to draw the slope of the perpendicular line to a given line, the pyplot module of the matplotlib package is used
import matplotlib.pyplot as plt
#T# to transform the markers of a plot, import the MarkerStyle constructor
f... | [
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show"
] | [((406, 424), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {}), '(1, 1)\n', (418, 424), True, 'import matplotlib.pyplot as plt\n'), ((1471, 1481), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1479, 1481), True, 'import matplotlib.pyplot as plt\n')] |
"""Test the mulled BioContainers image name generation."""
import pytest
from nf_core.modules import MulledImageNameGenerator
@pytest.mark.parametrize(
"specs, expected",
[
(["foo==0.1.2", "bar==1.1"], [("foo", "0.1.2"), ("bar", "1.1")]),
(["foo=0.1.2", "bar=1.1"], [("foo", "0.1.2"), ("bar",... | [
"nf_core.modules.MulledImageNameGenerator.generate_image_name",
"pytest.mark.parametrize",
"pytest.raises",
"nf_core.modules.MulledImageNameGenerator.parse_targets"
] | [((131, 314), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""specs, expected"""', "[(['foo==0.1.2', 'bar==1.1'], [('foo', '0.1.2'), ('bar', '1.1')]), ([\n 'foo=0.1.2', 'bar=1.1'], [('foo', '0.1.2'), ('bar', '1.1')])]"], {}), "('specs, expected', [(['foo==0.1.2', 'bar==1.1'], [(\n 'foo', '0.1.2'), ('b... |
import astropy.units as u
from astropy.coordinates import Angle, SkyCoord
from astropy import wcs
from regions import CircleSkyRegion
import numpy as np
from scipy.stats import expon
def estimate_exposure_time(timestamps):
'''
Takes numpy datetime64[ns] timestamps and returns an estimates of the exposure time... | [
"numpy.unique",
"astropy.coordinates.Angle",
"numpy.diff",
"numpy.array",
"numpy.ma.masked_array",
"scipy.stats.expon.ppf",
"astropy.wcs.WCS",
"astropy.units.quantity_input"
] | [((780, 834), 'astropy.units.quantity_input', 'u.quantity_input', ([], {'ra': 'u.hourangle', 'dec': 'u.deg', 'fov': 'u.deg'}), '(ra=u.hourangle, dec=u.deg, fov=u.deg)\n', (796, 834), True, 'import astropy.units as u\n'), ((1966, 2032), 'astropy.units.quantity_input', 'u.quantity_input', ([], {'event_ra': 'u.hourangle',... |
import numpy as np
a = np.zeros((10,6))
a[1,4:6] = [2,3]
b = a[1,4]
print(b)
check = np.array([2,3])
for i in range(a.shape[0]):
t = int(a[i,4])
idx = int(a[i,5])
if t == 2 and idx == 4:
a = np.delete(a,i,0)
break
else:
continue
print(a.shape)
| [
"numpy.array",
"numpy.zeros",
"numpy.delete"
] | [((24, 41), 'numpy.zeros', 'np.zeros', (['(10, 6)'], {}), '((10, 6))\n', (32, 41), True, 'import numpy as np\n'), ((88, 104), 'numpy.array', 'np.array', (['[2, 3]'], {}), '([2, 3])\n', (96, 104), True, 'import numpy as np\n'), ((216, 234), 'numpy.delete', 'np.delete', (['a', 'i', '(0)'], {}), '(a, i, 0)\n', (225, 234),... |
# coding: utf-8
import csv # ファイル出力用
import bs4, requests # スクレイピング(html取得・処理)
import re #正規表現
from pathlib import Path
# 指定エンコードのgetメソッド
def get_enc(mode):
enc_dic = dict(r='utf-8', w='sjis', p='cp932')
return enc_dic[mode]
# インラインのfor文リストで除外文字以外を繋ぐ
def remove_str(target, str_list):
return ''.join([... | [
"pathlib.Path",
"csv.writer",
"re.match",
"requests.get",
"bs4.BeautifulSoup"
] | [((513, 530), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (525, 530), False, 'import bs4, requests\n'), ((542, 569), 'bs4.BeautifulSoup', 'bs4.BeautifulSoup', (['res.text'], {}), '(res.text)\n', (559, 569), False, 'import bs4, requests\n'), ((799, 817), 'pathlib.Path', 'Path', (['sub_dir_path'], {}), '(su... |
# Generated by Django 2.1.4 on 2019-05-29 11:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('daiquiri_metadata', '0024_django2'),
]
operations = [
migrations.AddField(
model_name='schema',
name='published',
... | [
"django.db.models.DateField"
] | [((336, 401), 'django.db.models.DateField', 'models.DateField', ([], {'blank': '(True)', 'null': '(True)', 'verbose_name': '"""Published"""'}), "(blank=True, null=True, verbose_name='Published')\n", (352, 401), False, 'from django.db import migrations, models\n'), ((522, 585), 'django.db.models.DateField', 'models.Date... |
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#Created by: <NAME>
#BE department, University of Pennsylvania
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
import numpy as np
import nibabel as nib
import os
from tqdm import tqdm
from functools import partial
i... | [
"nibabel.load",
"numpy.array",
"numpy.gradient",
"os.path.exists",
"numpy.mean",
"os.listdir",
"numpy.asarray",
"numpy.eye",
"numpy.std",
"numpy.transpose",
"numpy.median",
"data_utils.surface_distance.compute_robust_hausdorff",
"numpy.unique",
"os.makedirs",
"tqdm.tqdm",
"os.path.join... | [((588, 609), 'numpy.zeros_like', 'np.zeros_like', (['labels'], {}), '(labels)\n', (601, 609), True, 'import numpy as np\n'), ((631, 668), 'numpy.unique', 'np.unique', (['labels'], {'return_counts': '(True)'}), '(labels, return_counts=True)\n', (640, 668), True, 'import numpy as np\n'), ((687, 704), 'numpy.median', 'np... |
from django.contrib.auth import get_user_model
from django.test import TestCase
from posts.models import Group, Post
User = get_user_model()
class PostModelTest(TestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.user = User.objects.create_user(username='auth')
cls.... | [
"django.contrib.auth.get_user_model",
"posts.models.Group.objects.create",
"posts.models.Post.objects.create"
] | [((126, 142), 'django.contrib.auth.get_user_model', 'get_user_model', ([], {}), '()\n', (140, 142), False, 'from django.contrib.auth import get_user_model\n'), ((327, 393), 'posts.models.Post.objects.create', 'Post.objects.create', ([], {'author': 'cls.user', 'text': '"""Тестовый текст больше"""'}), "(author=cls.user, ... |
import logging
import uuid
from assistant.orders.models import LineItem
from .models import Stock
from .exceptions import InsufficientStock
logger = logging.getLogger(__name__)
def process_simple_stock_allocation(**data):
stocks = Stock.objects.filter(product_variant=data.get("variant"))
line_items = data.... | [
"logging.getLogger",
"assistant.orders.models.LineItem.objects.filter"
] | [((152, 179), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (169, 179), False, 'import logging\n'), ((1160, 1203), 'assistant.orders.models.LineItem.objects.filter', 'LineItem.objects.filter', ([], {'variant__guid': 'guid'}), '(variant__guid=guid)\n', (1183, 1203), False, 'from assistant... |
import tempfile
import unittest
from pathlib import Path
from typing import Iterable
import numpy as np
from tests.fixtures.algorithms import SupervisedDeviatingFromMean
from timeeval import (
TimeEval,
Algorithm,
Datasets,
TrainingType,
InputDimensionality,
Status,
Metric,
ResourceCon... | [
"tempfile.TemporaryDirectory",
"timeeval.utils.hash_dict.hash_dict",
"numpy.testing.assert_array_almost_equal",
"pathlib.Path",
"timeeval.TimeEval",
"timeeval.datasets.Dataset",
"tests.fixtures.algorithms.SupervisedDeviatingFromMean",
"timeeval.DatasetManager",
"timeeval.ResourceConstraints",
"tim... | [((615, 653), 'timeeval.DatasetManager', 'DatasetManager', (['"""./tests/example_data"""'], {}), "('./tests/example_data')\n", (629, 653), False, 'from timeeval import TimeEval, Algorithm, Datasets, TrainingType, InputDimensionality, Status, Metric, ResourceConstraints, DatasetManager\n'), ((1207, 1236), 'timeeval.Data... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 兼容python2和python3
from __future__ import print_function
from __future__ import unicode_literals
from concurrent.futures import TimeoutError
from subprocess import Popen
from os import path, system, mknod
import json
import time
import timeout_decorator
import sys
from getopt... | [
"os.path.exists",
"getopt.getopt",
"timeout_decorator.timeout",
"json.load",
"os.system",
"os.mknod",
"time.time",
"json.dump"
] | [((1791, 1835), 'os.system', 'system', (['"""sudo kill -SIGHUP $(pidof dockerd)"""'], {}), "('sudo kill -SIGHUP $(pidof dockerd)')\n", (1797, 1835), False, 'from os import path, system, mknod\n'), ((1896, 1967), 'timeout_decorator.timeout', 'timeout_decorator.timeout', (['self.timeout'], {'timeout_exception': 'TimeoutE... |
"""SQLAlchemy models and utility functions for Sprint."""
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Record(db.Model):
id = db.Column(db.Integer, primary_key=True)
datetime = db.Column(db.String(25))
value = db.Column(db.Float, nullable=False)
def __repr__(self):
return... | [
"flask_sqlalchemy.SQLAlchemy"
] | [((105, 117), 'flask_sqlalchemy.SQLAlchemy', 'SQLAlchemy', ([], {}), '()\n', (115, 117), False, 'from flask_sqlalchemy import SQLAlchemy\n')] |
#!/usr/bin/env python3
import os
import sys
import argparse
import logging
from io import IOBase
from sys import stdout
from select import select
from threading import Thread
from time import sleep
from io import StringIO
import shutil
from datetime import datetime
import numpy as np
logging.basicConfig(filename=d... | [
"logging.getLogger",
"logging.StreamHandler",
"configparser.ConfigParser",
"sys.stdout.decode",
"time.sleep",
"sys.exit",
"os.read",
"os.path.exists",
"argparse.ArgumentParser",
"shutil.copy2",
"subprocess.Popen",
"io.StringIO",
"os.path.expanduser",
"subprocess.check_output",
"select.se... | [((604, 635), 'logging.getLogger', 'logging.getLogger', (['"""matplotlib"""'], {}), "('matplotlib')\n", (621, 635), False, 'import logging\n'), ((683, 710), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (700, 710), False, 'import logging\n'), ((774, 807), 'logging.StreamHandler', 'loggin... |
from django.contrib import admin
from .models.customer import Customer
from .models.purchase import Purchase
from .models.purchase import PurchaseItem
@admin.register(Customer)
class CustomerAdmin(admin.ModelAdmin):
pass
@admin.register(Purchase)
class PurchaseAdmin(admin.ModelAdmin):
pass
@admin.registe... | [
"django.contrib.admin.register"
] | [((155, 179), 'django.contrib.admin.register', 'admin.register', (['Customer'], {}), '(Customer)\n', (169, 179), False, 'from django.contrib import admin\n'), ((231, 255), 'django.contrib.admin.register', 'admin.register', (['Purchase'], {}), '(Purchase)\n', (245, 255), False, 'from django.contrib import admin\n'), ((3... |
import os
import tqdm
import argparse
import subprocess
from shutil import copyfile
def dump_files(src_dir, out_dir, data):
with open(f"{out_dir}/wav.scp", "w") as file:
for key in sorted(data):
file.write(f"{key} {data[key]}\n")
copyfile(f"data/{src_dir}/utt2spk", f"{out_dir}/utt2spk")
... | [
"os.path.exists",
"argparse.ArgumentParser",
"os.makedirs",
"subprocess.Popen",
"shutil.copyfile"
] | [((260, 317), 'shutil.copyfile', 'copyfile', (['f"""data/{src_dir}/utt2spk"""', 'f"""{out_dir}/utt2spk"""'], {}), "(f'data/{src_dir}/utt2spk', f'{out_dir}/utt2spk')\n", (268, 317), False, 'from shutil import copyfile\n'), ((322, 379), 'shutil.copyfile', 'copyfile', (['f"""data/{src_dir}/spk2utt"""', 'f"""{out_dir}/spk2... |
from opendatatools.common import RestAgent, md5
from progressbar import ProgressBar
import json
import pandas as pd
import io
import hashlib
import time
index_map = {
'Barclay_Hedge_Fund_Index' : 'ghsndx',
'Convertible_Arbitrage_Index' : 'ghsca',
'Distressed_Securities_Index' : 'ghsds',
'Emerg... | [
"json.loads",
"opendatatools.common.RestAgent.__init__",
"io.BytesIO",
"time.sleep",
"pandas.DataFrame",
"hashlib.sha1",
"pandas.concat",
"progressbar.ProgressBar"
] | [((1042, 1066), 'opendatatools.common.RestAgent.__init__', 'RestAgent.__init__', (['self'], {}), '(self)\n', (1060, 1066), False, 'from opendatatools.common import RestAgent, md5\n'), ((1529, 1549), 'json.loads', 'json.loads', (['response'], {}), '(response)\n', (1539, 1549), False, 'import json\n'), ((2512, 2532), 'js... |
#==========================================================================================
# A very clumsy attemp to read and write data stored in csv files
# because I have tried hard to write cutomized data file in .npz and .pt but both gave trouble
# so I gave up and now use the old good csv--->but everything is a ... | [
"pandas.read_csv",
"csv.writer",
"numpy.asarray",
"numpy.array",
"csv.reader"
] | [((2653, 2686), 'pandas.read_csv', 'pd.read_csv', (['csvPath'], {'header': 'None'}), '(csvPath, header=None)\n', (2664, 2686), True, 'import pandas as pd\n'), ((2708, 2738), 'numpy.asarray', 'np.asarray', (['dataset.iloc[:, 0]'], {}), '(dataset.iloc[:, 0])\n', (2718, 2738), True, 'import numpy as np\n'), ((2762, 2792),... |
import os
import numpy as np
# import jax.numpy as jnp
from sklearn.decomposition import TruncatedSVD
def Temporal_basis_POD(K, SAVE_T_POD=False, FOLDER_OUT='./',n_Modes=10):
"""
This method computes the POD basis. For some theoretical insights, you can find
the theoretical background of the proper orth... | [
"os.makedirs",
"numpy.savez",
"numpy.sqrt",
"sklearn.decomposition.TruncatedSVD"
] | [((1438, 1459), 'sklearn.decomposition.TruncatedSVD', 'TruncatedSVD', (['n_Modes'], {}), '(n_Modes)\n', (1450, 1459), False, 'from sklearn.decomposition import TruncatedSVD\n'), ((1561, 1578), 'numpy.sqrt', 'np.sqrt', (['Lambda_P'], {}), '(Lambda_P)\n', (1568, 1578), True, 'import numpy as np\n'), ((1611, 1659), 'os.ma... |
import networkx as nx
import matplotlib.pyplot as plt
from nxviz import GeoPlot
G = nx.read_gpickle("divvy.pkl")
print(list(G.nodes(data=True))[0])
G_new = G.copy()
for n1, n2, d in G.edges(data=True):
if d["count"] < 200:
G_new.remove_edge(n1, n2)
g = GeoPlot(
G_new,
node_lat="latitude",
nod... | [
"networkx.read_gpickle",
"nxviz.GeoPlot",
"matplotlib.pyplot.show"
] | [((86, 114), 'networkx.read_gpickle', 'nx.read_gpickle', (['"""divvy.pkl"""'], {}), "('divvy.pkl')\n", (101, 114), True, 'import networkx as nx\n'), ((268, 372), 'nxviz.GeoPlot', 'GeoPlot', (['G_new'], {'node_lat': '"""latitude"""', 'node_lon': '"""longitude"""', 'node_color': '"""dpcapacity"""', 'node_size': '(0.005)'... |
# -*- coding: utf-8 -*-
import re
import fnmatch
import itertools
import six
from .util import matcher
class TaskContainer(list):
"""Contains tasks. Tasks can be accessed by task_no or by name"""
def __init__(self, *args, **kwargs):
self.by_name = dict()
return super(TaskContainer, self).__... | [
"re.search",
"fnmatch.translate",
"itertools.tee"
] | [((911, 934), 'itertools.tee', 'itertools.tee', (['iterable'], {}), '(iterable)\n', (924, 934), False, 'import itertools\n'), ((518, 540), 'fnmatch.translate', 'fnmatch.translate', (['key'], {}), '(key)\n', (535, 540), False, 'import fnmatch\n'), ((726, 748), 're.search', 're.search', (['q', 'val.name'], {}), '(q, val.... |
from core.framework.module import BaseModule
import ast
import time
import difflib
class Module(BaseModule):
meta = {
'name': 'Jailbreak Detection',
'author': '@LanciniMarco (@MWRLabs)',
'description': 'Verify that the app cannot be run on a jailbroken device. Currently detects i... | [
"ast.literal_eval",
"time.sleep",
"difflib.unified_diff"
] | [((1877, 1911), 'ast.literal_eval', 'ast.literal_eval', (['file_list_str[0]'], {}), '(file_list_str[0])\n', (1893, 1911), False, 'import ast\n'), ((2975, 3002), 'time.sleep', 'time.sleep', (['self.WATCH_TIME'], {}), '(self.WATCH_TIME)\n', (2985, 3002), False, 'import time\n'), ((3789, 3836), 'difflib.unified_diff', 'di... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# By: <NAME> (Tedezed)
# Source: https://github.com/Tedezed
# Mail: <EMAIL>
from sys import argv
from copy import deepcopy
from chronos import *
from module_control import *
debug = True
def argument_to_dic(list):
dic = {}
for z in list:
dic[z[0]] = z[1]
... | [
"copy.deepcopy"
] | [((381, 395), 'copy.deepcopy', 'deepcopy', (['argv'], {}), '(argv)\n', (389, 395), False, 'from copy import deepcopy\n')] |
import numpy as np
import pandas as pd
import torch
import src.configuration as C
import src.dataset as dataset
import src.models as models
import src.utils as utils
from pathlib import Path
from fastprogress import progress_bar
if __name__ == "__main__":
args = utils.get_sed_parser().parse_args()
config =... | [
"src.utils.get_sed_parser",
"src.configuration.get_metadata",
"src.models.get_model_for_inference",
"pathlib.Path",
"fastprogress.progress_bar",
"src.configuration.get_device",
"src.configuration.get_split",
"pandas.read_csv",
"src.configuration.get_sed_inference_loader",
"torch.cuda.is_available"... | [((321, 351), 'src.utils.load_config', 'utils.load_config', (['args.config'], {}), '(args.config)\n', (338, 351), True, 'import src.utils as utils\n'), ((409, 442), 'pathlib.Path', 'Path', (["global_params['output_dir']"], {}), "(global_params['output_dir'])\n", (413, 442), False, 'from pathlib import Path\n'), ((498, ... |
import requests
import json
from bs4 import BeautifulSoup
BASE_URL = 'https://cobalt.qas.im/documentation/%s/filter'
def scrape(api_endpoint):
"""Scrape filter keys from the Cobalt documentation of api_endpoint."""
host = BASE_URL % api_endpoint
resp = requests.get(host)
soup = BeautifulSoup(resp.t... | [
"bs4.BeautifulSoup",
"requests.get"
] | [((270, 288), 'requests.get', 'requests.get', (['host'], {}), '(host)\n', (282, 288), False, 'import requests\n'), ((300, 339), 'bs4.BeautifulSoup', 'BeautifulSoup', (['resp.text', '"""html.parser"""'], {}), "(resp.text, 'html.parser')\n", (313, 339), False, 'from bs4 import BeautifulSoup\n')] |
from flask import Blueprint, render_template, request, redirect, url_for, Response
from flask.views import MethodView
from flask.ext.login import login_required, current_user
from lablog import config
from lablog.models.client import SocialAccount, FacebookPage, PageCategory
from flask_oauth import OAuth
import logging... | [
"flask.render_template",
"flask.ext.login.current_user.social_accounts.append",
"flask.request.args.get",
"urlparse.parse_qs",
"flask.ext.login.current_user.social_account",
"flask.ext.login.current_user.facebook_pages.append",
"json.dumps",
"flask.url_for",
"logging.exception",
"flask_oauth.OAuth... | [((382, 389), 'flask_oauth.OAuth', 'OAuth', ([], {}), '()\n', (387, 389), False, 'from flask_oauth import OAuth\n'), ((402, 500), 'flask.Blueprint', 'Blueprint', (['"""facebook"""', '__name__'], {'template_folder': 'config.TEMPLATES', 'url_prefix': '"""/auth/facebook"""'}), "('facebook', __name__, template_folder=confi... |
import cv2
'''
gets a video file and dumps each frame as a jpg picture in an output dir
'''
# Opens the Video file
cap = cv2.VideoCapture('./Subt_2.mp4')
i = 0
while(cap.isOpened()):
ret, frame = cap.read()
if i%(round(25*0.3)) == 0:
print(i)
if ret == False:
break... | [
"cv2.destroyAllWindows",
"cv2.VideoCapture"
] | [((131, 163), 'cv2.VideoCapture', 'cv2.VideoCapture', (['"""./Subt_2.mp4"""'], {}), "('./Subt_2.mp4')\n", (147, 163), False, 'import cv2\n'), ((411, 434), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (432, 434), False, 'import cv2\n')] |
import normalize
norm = normalize.normalize("heightdata.png", 6, 6)
class TestNormArray:
"""test_norm_array references requirement 3.0 because it shows 2x2 block area of (0,0),
(0,1), (1,0), (1,1), this area will for sure be a 2x2 block area"""
# \brief Ref : Req 3.0 One pixel in topographic image sha... | [
"normalize.process_image",
"normalize.normalize"
] | [((25, 68), 'normalize.normalize', 'normalize.normalize', (['"""heightdata.png"""', '(6)', '(6)'], {}), "('heightdata.png', 6, 6)\n", (44, 68), False, 'import normalize\n'), ((1710, 1759), 'normalize.process_image', 'normalize.process_image', (['"""heightdata.jpg"""', '(10)', '(10)'], {}), "('heightdata.jpg', 10, 10)\n... |
# imports
import json
import argparse
import torch
from torch import nn
from torch import optim
from torch.optim import lr_scheduler
import torch.nn.functional as F
from torchvision import models
from collections import OrderedDict
from data_utils import load_data
from model_utils import define_model, train_model
# pa... | [
"model_utils.define_model",
"data_utils.load_data",
"argparse.ArgumentParser",
"model_utils.train_model",
"torch.optim.lr_scheduler.StepLR",
"torch.nn.NLLLoss",
"torch.save",
"json.load",
"torch.device"
] | [((383, 484), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Parser command line arguments for Flower Image Classifier"""'}), "(description=\n 'Parser command line arguments for Flower Image Classifier')\n", (406, 484), False, 'import argparse\n'), ((1306, 1330), 'data_utils.load_data... |
from django.contrib import admin
from .models import Patient,Ipd,Rooms,TreatmentAdviced,TreatmentGiven,Discharge,Procedure,Investigation,DailyRound,Opd
admin.site.register(Opd)# Register your models here.
admin.site.register(Patient)
admin.site.register(Ipd)
admin.site.register(Rooms)
admin.site.register(TreatmentAdv... | [
"django.contrib.admin.site.register"
] | [((153, 177), 'django.contrib.admin.site.register', 'admin.site.register', (['Opd'], {}), '(Opd)\n', (172, 177), False, 'from django.contrib import admin\n'), ((207, 235), 'django.contrib.admin.site.register', 'admin.site.register', (['Patient'], {}), '(Patient)\n', (226, 235), False, 'from django.contrib import admin\... |
"""
Copyright (c) 2015 <NAME>
license http://opensource.org/licenses/MIT
lib/ui/handlers.py
Handlers for find menu
"""
from functools import partial
import sys
import traceback
import pynance as pn
from ..dbtools import find_job
from ..dbwrapper import job
from ..spreads.dgb_finder import DgbFinder
from ..stockopt... | [
"sys.stdout.flush",
"traceback.print_exc",
"functools.partial",
"pynance.opt.get"
] | [((2252, 2270), 'pynance.opt.get', 'pn.opt.get', (['equity'], {}), '(equity)\n', (2262, 2270), True, 'import pynance as pn\n'), ((1051, 1095), 'functools.partial', 'partial', (['find_job', '"""find"""', "{'spread': 'dgb'}"], {}), "(find_job, 'find', {'spread': 'dgb'})\n", (1058, 1095), False, 'from functools import par... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
__author__ = 'andyguo'
from functools import wraps
class DayuDatabaseStatusNotConnect(object):
pass
class DayuDatabaseStatusConnected(object):
pass
def validate_status(status):
def outter_wrapper(func):
@wraps(func)
def wrapper(self, *a... | [
"functools.wraps"
] | [((280, 291), 'functools.wraps', 'wraps', (['func'], {}), '(func)\n', (285, 291), False, 'from functools import wraps\n')] |
from dataclasses import dataclass, field
from typing import Optional
from pytest import raises
from apischema import ValidationError, deserialize
from apischema.metadata import required
@dataclass
class Foo:
bar: Optional[int] = field(default=None, metadata=required)
with raises(ValidationError) as err:
d... | [
"apischema.deserialize",
"pytest.raises",
"dataclasses.field"
] | [((237, 275), 'dataclasses.field', 'field', ([], {'default': 'None', 'metadata': 'required'}), '(default=None, metadata=required)\n', (242, 275), False, 'from dataclasses import dataclass, field\n'), ((283, 306), 'pytest.raises', 'raises', (['ValidationError'], {}), '(ValidationError)\n', (289, 306), False, 'from pytes... |
from django.test import TestCase
# from django.db.utils import IntegrityError
from core.models import User
class CaseInsensitiveUserNameManagerTest(TestCase):
@classmethod
def setUpTestData(cls):
cls.user1 = User.objects.create_user(username="user1",
pass... | [
"core.models.User.objects.create_user",
"core.models.User.objects.get_by_natural_key"
] | [((228, 315), 'core.models.User.objects.create_user', 'User.objects.create_user', ([], {'username': '"""user1"""', 'password': '"""<PASSWORD>"""', 'email': '"""<EMAIL>"""'}), "(username='user1', password='<PASSWORD>', email=\n '<EMAIL>')\n", (252, 315), False, 'from core.models import User\n'), ((456, 496), 'core.mo... |
import torch
import torch.nn as nn
from torch.nn import init
from torchvision import models
from torch.autograd import Variable
from resnet import resnet50, resnet18
import torch.nn.functional as F
import math
from attention import IWPA, AVG, MAX, GEM
class Normalize(nn.Module):
def __init__(self, power=2):
... | [
"attention.AVG",
"torch.nn.Dropout",
"torch.nn.functional.adaptive_avg_pool2d",
"attention.IWPA",
"torch.nn.LeakyReLU",
"torch.nn.Sequential",
"torch.mean",
"torch.nn.init.kaiming_normal_",
"torch.nn.init.zeros_",
"torch.nn.functional.adaptive_max_pool2d",
"resnet.resnet50",
"torch.nn.BatchNor... | [((739, 794), 'torch.nn.init.kaiming_normal_', 'init.kaiming_normal_', (['m.weight.data'], {'a': '(0)', 'mode': '"""fan_in"""'}), "(m.weight.data, a=0, mode='fan_in')\n", (759, 794), False, 'from torch.nn import init\n'), ((1178, 1215), 'torch.nn.init.normal_', 'init.normal_', (['m.weight.data', '(0)', '(0.001)'], {}),... |
import os
import numpy as np
from ._population import Population
from pychemia import pcm_log
from pychemia.utils.mathematics import spherical_to_cartesian, cartesian_to_spherical, rotate_towards_axis, \
angle_between_vectors
from pychemia.code.vasp import read_incar, read_poscar, VaspJob, VaspOutput
from pychemia.... | [
"pychemia.code.vasp.VaspJob",
"numpy.ones",
"pychemia.code.vasp.read_poscar",
"pychemia.utils.mathematics.angle_between_vectors",
"pychemia.code.vasp.read_incar",
"pychemia.utils.mathematics.spherical_to_cartesian",
"pychemia.crystal.KPoints.optimized_grid",
"numpy.random.rand",
"os.path.isfile",
... | [((785, 826), 'pychemia.code.vasp.read_incar', 'read_incar', (["(source_dir + os.sep + 'INCAR')"], {}), "(source_dir + os.sep + 'INCAR')\n", (795, 826), False, 'from pychemia.code.vasp import read_incar, read_poscar, VaspJob, VaspOutput\n'), ((928, 971), 'pychemia.code.vasp.read_poscar', 'read_poscar', (["(source_dir +... |
# Generated by Django 2.2.7 on 2020-02-02 19:42
import datetime
from django.db import migrations, models
import django.db.models.deletion
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('Ecommerce', '0009_review_date'),
]
operations = [
mig... | [
"datetime.datetime",
"django.db.models.AutoField",
"django.db.models.ForeignKey"
] | [((445, 506), 'datetime.datetime', 'datetime.datetime', (['(2020)', '(2)', '(2)', '(19)', '(42)', '(47)', '(841789)'], {'tzinfo': 'utc'}), '(2020, 2, 2, 19, 42, 47, 841789, tzinfo=utc)\n', (462, 506), False, 'import datetime\n'), ((621, 714), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(Tru... |
# -*- coding: utf-8 -*-
"""Generator reserve plots.
This module creates plots of reserve provision and shortage at the generation
and region level.
@author: <NAME>
"""
import logging
import numpy as np
import pandas as pd
import datetime as dt
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib... | [
"logging.getLogger",
"marmot.plottingmodules.plotutils.plot_library.create_stackplot",
"matplotlib.pyplot.ylabel",
"numpy.array",
"marmot.plottingmodules.plotutils.plot_data_helper.PlotDataHelper.get_sub_hour_interval_count",
"datetime.timedelta",
"marmot.plottingmodules.plotutils.plot_exceptions.Missin... | [((1826, 1870), 'logging.getLogger', 'logging.getLogger', (["('marmot_plot.' + __name__)"], {}), "('marmot_plot.' + __name__)\n", (1843, 1870), False, 'import logging\n'), ((1901, 1951), 'marmot.config.mconfig.parser', 'mconfig.parser', (['"""axes_options"""', '"""y_axes_decimalpt"""'], {}), "('axes_options', 'y_axes_d... |
# -*- coding:utf-8 -*-
from yepes.apps import apps
AbstractConnection = apps.get_class('emails.abstract_models', 'AbstractConnection')
AbstractDelivery = apps.get_class('emails.abstract_models', 'AbstractDelivery')
AbstractMessage = apps.get_class('emails.abstract_models', 'AbstractMessage')
class Connection(Abstra... | [
"yepes.apps.apps.get_class"
] | [((74, 136), 'yepes.apps.apps.get_class', 'apps.get_class', (['"""emails.abstract_models"""', '"""AbstractConnection"""'], {}), "('emails.abstract_models', 'AbstractConnection')\n", (88, 136), False, 'from yepes.apps import apps\n'), ((156, 216), 'yepes.apps.apps.get_class', 'apps.get_class', (['"""emails.abstract_mode... |
"""
Top level function calls for pentomino solver
"""
from tree_find_pents import build_pent_tree
from rect_find_x import solve_case
def fill_rectangles_with_pentominos(io_obj=print, low=3, high=7):
"""
Loop through rectangle sizes and solve for each. build_pent_tree
is called to initialize the tree. Io... | [
"tree_find_pents.build_pent_tree"
] | [((484, 501), 'tree_find_pents.build_pent_tree', 'build_pent_tree', ([], {}), '()\n', (499, 501), False, 'from tree_find_pents import build_pent_tree\n')] |
# --------------------------------------------------------------------------- #
# Title: Wifi/Ethernet communication server script
# Author: <NAME>
# Date: 04/07/2018 (DD/MM/YYYY)
# Description: This function opens up a port for wifi/ethernet communication
# and listens to the channel, if it receives a string, it crop... | [
"time.sleep",
"socket.socket"
] | [((700, 749), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (713, 749), False, 'import socket\n'), ((1803, 1820), 'time.sleep', 'time.sleep', (['(0.005)'], {}), '(0.005)\n', (1813, 1820), False, 'import time\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# ade:
# Asynchronous Differential Evolution.
#
# Copyright (C) 2018-20 by <NAME>,
# http://edsuom.com/ade
#
# See edsuom.com for API documentation as well as information about
# Ed's background and other projects, software and otherwise.
#
# Licensed under the Apache Li... | [
"ade.specs.DictStacker",
"ade.test.testbase.fileInModuleDir",
"ade.specs.Specs",
"ade.specs.SpecsLoader"
] | [((1198, 1222), 'ade.specs.DictStacker', 'specs.DictStacker', (['"""foo"""'], {}), "('foo')\n", (1215, 1222), False, 'from ade import specs\n'), ((2208, 2221), 'ade.specs.Specs', 'specs.Specs', ([], {}), '()\n', (2219, 2221), False, 'from ade import specs\n'), ((3924, 3956), 'ade.test.testbase.fileInModuleDir', 'tb.fil... |
import numpy as np
import pandas as p
from datetime import datetime, timedelta
class PreprocessData():
def __init__(self, file_name):
self.file_name = file_name
#get only used feature parameters
def get_features(self, file_name):
data = p.read_csv(file_name, skiprows=7, sep=';', header=Non... | [
"pandas.read_csv",
"datetime.datetime.strptime",
"numpy.append",
"datetime.timedelta",
"pandas.concat"
] | [((267, 322), 'pandas.read_csv', 'p.read_csv', (['file_name'], {'skiprows': '(7)', 'sep': '""";"""', 'header': 'None'}), "(file_name, skiprows=7, sep=';', header=None)\n", (277, 322), True, 'import pandas as p\n'), ((1485, 1564), 'pandas.concat', 'p.concat', (['[data_date, data_time, wind_direction, cloud_rate, temp_da... |
"""
OBJECT RECOGNITION USING A SPIKING NEURAL NETWORK.
* The main code script to run the model.
@author: atenagm1375
"""
# %% IMPORT MODULES
import torch
from utils.data import CaltechDatasetLoader, CaltechDataset
from utils.model import DeepCSNN
from tqdm import tqdm
# %% ENVIRONMENT CONSTANTS
PATH = "../101_... | [
"utils.data.CaltechDataset",
"utils.data.CaltechDatasetLoader",
"torch.utils.data.DataLoader"
] | [((505, 552), 'utils.data.CaltechDatasetLoader', 'CaltechDatasetLoader', (['PATH', 'CLASSES', 'image_size'], {}), '(PATH, CLASSES, image_size)\n', (525, 552), False, 'from utils.data import CaltechDatasetLoader, CaltechDataset\n'), ((603, 637), 'utils.data.CaltechDataset', 'CaltechDataset', (['data'], {}), '(data, **Do... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Datasets
==================
Classes for dataset handling
Dataset - Base class
^^^^^^^^^^^^^^^^^^^^
This is the base class, and all the specialized datasets are inherited from it. One should never use base class itself.
Usage examples:
.. code-block:: python
:lin... | [
"logging.getLogger",
"tarfile.open",
"zipfile.ZipFile",
"numpy.array",
"itertools.izip",
"sys.exit",
"socket.setdefaulttimeout",
"os.walk",
"os.remove",
"os.listdir",
"numpy.diff",
"os.path.split",
"os.path.isdir",
"csv.reader",
"os.path.relpath",
"numpy.abs",
"collections.OrderedDic... | [((7552, 7611), 'os.path.join', 'os.path.join', (['self.local_path', 'self.evaluation_setup_folder'], {}), '(self.local_path, self.evaluation_setup_folder)\n', (7564, 7611), False, 'import os\n'), ((8138, 8193), 'os.path.join', 'os.path.join', (['self.local_path', 'self.error_meta_filename'], {}), '(self.local_path, se... |
import logging
import collections
import json
import time
import string
import random
logger = logging.getLogger(__name__)
from schematics.types import BaseType
from schematics.exceptions import ValidationError
from nymms.utils import parse_time
import arrow
class TimestampType(BaseType):
def to_native(self, ... | [
"logging.getLogger",
"collections.OrderedDict",
"collections.namedtuple",
"nymms.utils.parse_time",
"json.loads",
"random.choice",
"random.randrange",
"json.dumps",
"arrow.get",
"time.time"
] | [((96, 123), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (113, 123), False, 'import logging\n'), ((1302, 1357), 'collections.namedtuple', 'collections.namedtuple', (['"""StateObject"""', "['name', 'code']"], {}), "('StateObject', ['name', 'code'])\n", (1324, 1357), False, 'import colle... |
from datetime import datetime
import decimal
import json
import os
import random
import uuid
import boto3
from botocore.exceptions import ClientError
# Helper class to convert a DynamoDB item to JSON.
class DecimalEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, decimal.Decimal):
... | [
"json.loads",
"boto3.client",
"json.dumps",
"os.environ.get",
"uuid.uuid4",
"datetime.datetime.now",
"boto3.resource",
"random.randint"
] | [((514, 540), 'boto3.resource', 'boto3.resource', (['"""dynamodb"""'], {}), "('dynamodb')\n", (528, 540), False, 'import boto3\n'), ((558, 587), 'boto3.client', 'boto3.client', (['"""stepfunctions"""'], {}), "('stepfunctions')\n", (570, 587), False, 'import boto3\n'), ((594, 613), 'boto3.client', 'boto3.client', (['"""... |
from .socket import Socket
from socket import timeout as sockTimeout
from ... import Logger, DummyLog
import threading
import sys
import warnings
_QUEUEDSOCKET_IDENTIFIER_ = '<agutil.io.queuedsocket:1.0.0>'
class QueuedSocket(Socket):
def __init__(
self,
address,
port,
logmethod=D... | [
"threading.Event",
"socket.timeout",
"warnings.warn",
"threading.Thread",
"threading.Condition"
] | [((365, 481), 'warnings.warn', 'warnings.warn', (['"""QueuedSocket is now deprecated and will be removed in a future release"""', 'DeprecationWarning'], {}), "(\n 'QueuedSocket is now deprecated and will be removed in a future release',\n DeprecationWarning)\n", (378, 481), False, 'import warnings\n'), ((728, 749... |
#!/usr/bin/env python3
from astropy.modeling.models import Const1D, Const2D, Gaussian1D, Gaussian2D
from astropy.modeling.fitting import LevMarLSQFitter
from astropy.modeling import Fittable2DModel, Parameter
import sys
import logging
import argparse
import warnings
from datetime import datetime
from glob import glob
... | [
"numpy.ptp",
"sep.kron_radius",
"logging.StreamHandler",
"astropy.table.Table",
"numpy.array",
"sep.Background",
"numpy.isfinite",
"astropy.io.fits.open",
"astropy.modeling.models.Const2D",
"numpy.mean",
"argparse.ArgumentParser",
"numpy.ma.count",
"astropy.modeling.Parameter",
"astropy.wc... | [((658, 683), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (681, 683), False, 'import argparse\n'), ((4104, 4137), 'logging.Logger', 'logging.Logger', (['"""LMI Add Catalog"""'], {}), "('LMI Add Catalog')\n", (4118, 4137), False, 'import logging\n'), ((4923, 4972), 'warnings.simplefilter', 'w... |
from __future__ import absolute_import, unicode_literals
from django.urls import include, re_path
from wagtail.admin import urls as wagtailadmin_urls
from wagtail.core import urls as wagtail_urls
from wagtail_transfer import urls as wagtailtransfer_urls
urlpatterns = [
re_path(r'^admin/', include(wagtailadmin_u... | [
"django.urls.include"
] | [((298, 324), 'django.urls.include', 'include', (['wagtailadmin_urls'], {}), '(wagtailadmin_urls)\n', (305, 324), False, 'from django.urls import include, re_path\n'), ((362, 391), 'django.urls.include', 'include', (['wagtailtransfer_urls'], {}), '(wagtailtransfer_urls)\n', (369, 391), False, 'from django.urls import i... |
# Generated by Django 3.2.5 on 2021-07-30 15:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0011_auto_20210729_2147'),
]
operations = [
migrations.AddField(
model_name='curation',
name='needs_verifica... | [
"django.db.models.BooleanField"
] | [((345, 413), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(True)', 'verbose_name': '"""Needs Verification"""'}), "(default=True, verbose_name='Needs Verification')\n", (364, 413), False, 'from django.db import migrations, models\n'), ((557, 625), 'django.db.models.BooleanField', 'models.Bo... |
import tensorflow as tf
def touch(fname: str, times=None, create_dirs: bool = False):
import os
if create_dirs:
base_dir = os.path.dirname(fname)
if not os.path.exists(base_dir):
os.makedirs(base_dir)
with open(fname, 'a'):
os.utime(fname, times)
def touch_dir(base_di... | [
"datetime.datetime.utcfromtimestamp",
"tensorflow.reduce_min",
"os.path.exists",
"tensorflow.image.convert_image_dtype",
"tensorflow.shape",
"tensorflow.transpose",
"tensorflow.Variable",
"os.makedirs",
"tensorflow.logical_not",
"os.utime",
"tensorflow.reduce_max",
"os.path.dirname",
"tensor... | [((481, 509), 'datetime.datetime.utcfromtimestamp', 'datetime.utcfromtimestamp', (['(0)'], {}), '(0)\n', (506, 509), False, 'from datetime import datetime\n'), ((615, 644), 'tensorflow.constant', 'tf.constant', (['(0.1)'], {'shape': 'shape'}), '(0.1, shape=shape)\n', (626, 644), True, 'import tensorflow as tf\n'), ((65... |
# Some of the implementation inspired by:
# REF: https://github.com/fchen365/epca
import time
from abc import abstractmethod
import numpy as np
from factor_analyzer import Rotator
from sklearn.base import BaseEstimator
from sklearn.preprocessing import StandardScaler
from sklearn.utils import check_array
from graspo... | [
"factor_analyzer.Rotator",
"numpy.abs",
"numpy.sqrt",
"graspologic.embed.selectSVD",
"numpy.argsort",
"sklearn.preprocessing.StandardScaler",
"numpy.linalg.norm",
"time.time"
] | [((654, 709), 'graspologic.embed.selectSVD', 'selectSVD', (['X'], {'n_components': 'X.shape[1]', 'algorithm': '"""full"""'}), "(X, n_components=X.shape[1], algorithm='full')\n", (663, 709), False, 'from graspologic.embed import selectSVD\n'), ((817, 872), 'graspologic.embed.selectSVD', 'selectSVD', (['X'], {'n_componen... |