code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
from argparse import ArgumentParser
from pathlib import Path
import torch
from nemo.datasets import classification_dataloaders, detection_dataloaders
from nemo.utils import ensure_reproducibility
DATASET_TYPES = [
"classification",
"detection",
]
class RunningAverage:
def __init__(self, num_channels=3)... | [
"nemo.datasets.detection_dataloaders",
"argparse.ArgumentParser",
"torch.mean",
"torch.stack",
"nemo.utils.ensure_reproducibility",
"torch.sum",
"torch.no_grad",
"nemo.datasets.classification_dataloaders",
"torch.std",
"torch.zeros",
"torch.flatten"
] | [((1159, 1190), 'nemo.utils.ensure_reproducibility', 'ensure_reproducibility', ([], {'seed': '(42)'}), '(seed=42)\n', (1181, 1190), False, 'from nemo.utils import ensure_reproducibility\n'), ((2246, 2262), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (2260, 2262), False, 'from argparse import Argument... |
# Illustration of DYNAMIC PROGRAMING
# Calculate the fibonacci sequence
# Hyp : n > 2 (don't handle fib(0))
import time
def fib_recursion(n):
if n == 1 or n == 2 :
return 1
else:
return fib_recursion(n-1) + fib_recursion(n-2)
def memoize(f):
memo = {}
def helper(x):
if x no... | [
"time.time"
] | [((1002, 1013), 'time.time', 'time.time', ([], {}), '()\n', (1011, 1013), False, 'import time\n'), ((1124, 1135), 'time.time', 'time.time', ([], {}), '()\n', (1133, 1135), False, 'import time\n'), ((1256, 1267), 'time.time', 'time.time', ([], {}), '()\n', (1265, 1267), False, 'import time\n'), ((1374, 1385), 'time.time... |
# Generated by Django 3.0 on 2020-03-25 20:27
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('content', '0018_auto_20200323_1458'),
('cloud_storage', '0004_auto_20200323_1458'),
]
operations = [
... | [
"django.db.models.ForeignKey"
] | [((424, 660), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'help_text': '"""The Artist the file is shared with"""', 'limit_choices_to': "{'platform': 'Revibe'}", 'on_delete': 'django.db.models.deletion.CASCADE', 'related_name': '"""file_shares"""', 'to': '"""content.Artist"""', 'verbose_name': '"""artist""... |
import sys
try:
from configparser import ConfigParser, NoOptionError
except ImportError:
from ConfigParser import ConfigParser, NoOptionError
from collections import namedtuple
from os.path import abspath, join, dirname
import sqlparse
BackendConfig = namedtuple('BackendConfig', 'name kwargs')
conf = None
HE... | [
"psycopg2.connect",
"sqlparse.split",
"collections.namedtuple",
"sqlite3.connect",
"os.path.join",
"ConfigParser.ConfigParser",
"os.path.dirname",
"dbschema.open",
"sys.stderr.write",
"MySQLdb.connect"
] | [((263, 305), 'collections.namedtuple', 'namedtuple', (['"""BackendConfig"""', '"""name kwargs"""'], {}), "('BackendConfig', 'name kwargs')\n", (273, 305), False, 'from collections import namedtuple\n'), ((333, 350), 'os.path.dirname', 'dirname', (['__file__'], {}), '(__file__)\n', (340, 350), False, 'from os.path impo... |
import os
import unittest
from tempfile import mkstemp
from clips import Environment, Symbol, CLIPSError, TemplateSlotDefaultType
DEFTEMPLATE = """(deftemplate MAIN::template-fact
(slot int (type INTEGER) (allowed-values 0 1 2 3 4 5 6 7 8 9))
(slot float (type FLOAT))
(slot str (type STRING))
(slot symbo... | [
"clips.Symbol",
"os.close",
"clips.Environment",
"tempfile.mkstemp",
"os.remove"
] | [((841, 850), 'tempfile.mkstemp', 'mkstemp', ([], {}), '()\n', (848, 850), False, 'from tempfile import mkstemp\n'), ((859, 873), 'os.close', 'os.close', (['fobj'], {}), '(fobj)\n', (867, 873), False, 'import os\n'), ((932, 952), 'os.remove', 'os.remove', (['self.name'], {}), '(self.name)\n', (941, 952), False, 'import... |
# Copyright 2018-2019 QuantumBlack Visual Analytics Limited
#
# 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
#
# THE SOFTWARE IS PROVIDED "AS IS"... | [
"decimal.Decimal",
"kedro.io.JSONLocalDataSet",
"kedro.io.core.Version",
"pytest.mark.parametrize",
"pytest.raises",
"pytest.fixture",
"pytest.warns"
] | [((2005, 2039), 'pytest.fixture', 'pytest.fixture', ([], {'params': '[[1, 2, 3]]'}), '(params=[[1, 2, 3]])\n', (2019, 2039), False, 'import pytest\n'), ((1760, 1800), 'kedro.io.JSONLocalDataSet', 'JSONLocalDataSet', ([], {'filepath': 'filepath_json'}), '(filepath=filepath_json)\n', (1776, 1800), False, 'from kedro.io i... |
"""Performs vector and matrix operations.
2020, <NAME> <<EMAIL>>
"""
import numpy as np
from mathstuff import root_finding
from typing import Callable, Tuple
def legendre_polynomial(x: float, n: int) -> float:
"""Evaluate n-order Legendre polynomial.
Args:
x: Abscissa to evaluate.
n: Poly... | [
"numpy.linspace",
"mathstuff.root_finding.hybrid_secant_bisection"
] | [((1020, 1049), 'numpy.linspace', 'np.linspace', (['(-1)', '(1)', '(k * n + 1)'], {}), '(-1, 1, k * n + 1)\n', (1031, 1049), True, 'import numpy as np\n'), ((1822, 1939), 'mathstuff.root_finding.hybrid_secant_bisection', 'root_finding.hybrid_secant_bisection', ([], {'x_left': 'bound[0]', 'x_right': 'bound[1]', 'func': ... |
# Copyright (C) 2021 <NAME>
# MIT License
# Generate an abstract syntax tree via a recusive descent parser
from src.error import ErrorHandler, ParseError
from src.tokenizer import Token, TokenType
from src.node import Binary, Unary, Variable, Literal, Grouping, Assignment
from src.node import Logical
from src.node i... | [
"src.node.Block",
"src.node.Branch",
"src.tokenizer.Token",
"src.node.Binary",
"src.node.VariableDeclaration",
"src.node.Loop",
"src.node.Logical",
"src.node.Assignment",
"src.error.ErrorHandler"
] | [((641, 655), 'src.error.ErrorHandler', 'ErrorHandler', ([], {}), '()\n', (653, 655), False, 'from src.error import ErrorHandler, ParseError\n'), ((1046, 1065), 'src.error.ErrorHandler', 'ErrorHandler', (['limit'], {}), '(limit)\n', (1058, 1065), False, 'from src.error import ErrorHandler, ParseError\n'), ((3613, 3651)... |
from functools import wraps
from logging import getLogger
from typing import Dict, Union
import requests
from ethereum.utils import (check_checksum, checksum_encode, ecrecover_to_pub,
privtoaddr, sha3)
from hexbytes import HexBytes
from web3 import HTTPProvider, Web3
from web3.middleware im... | [
"logging.getLogger",
"ethereum.utils.privtoaddr",
"requests.post",
"ethereum.utils.check_checksum",
"web3.HTTPProvider",
"ethereum.utils.checksum_encode",
"ethereum.utils.sha3",
"functools.wraps",
"hexbytes.HexBytes",
"ethereum.utils.ecrecover_to_pub"
] | [((484, 503), 'logging.getLogger', 'getLogger', (['__name__'], {}), '(__name__)\n', (493, 503), False, 'from logging import getLogger\n'), ((1410, 1421), 'functools.wraps', 'wraps', (['func'], {}), '(func)\n', (1415, 1421), False, 'from functools import wraps\n'), ((3446, 3501), 'requests.post', 'requests.post', ([], {... |
from flask import abort, redirect, render_template, request
from shortlinks import app
from shortlinks.links import add_link, get_link, get_most_popular_links
from shortlinks.validators import LinkForm
@app.route('/')
def index():
return render_template('index.html', links=get_most_popular_links())
@app.route('/... | [
"flask.render_template",
"shortlinks.app.errorhandler",
"shortlinks.validators.LinkForm",
"shortlinks.links.get_link",
"shortlinks.app.logger.debug",
"flask.redirect",
"shortlinks.links.add_link",
"flask.abort",
"shortlinks.app.template_filter",
"shortlinks.links.get_most_popular_links",
"shortl... | [((205, 219), 'shortlinks.app.route', 'app.route', (['"""/"""'], {}), "('/')\n", (214, 219), False, 'from shortlinks import app\n'), ((308, 330), 'shortlinks.app.route', 'app.route', (['"""/<int:id>"""'], {}), "('/<int:id>')\n", (317, 330), False, 'from shortlinks import app\n'), ((513, 552), 'shortlinks.app.route', 'a... |
import os
from datetime import timedelta
from flask import url_for
class Config(object):
DATABASE = {
'name': 'vlaskola',
'engine': 'peewee.PostgresqlDatabase',
'user': 'postgres'
}
SECRET_KEY = os.environ.get("SECRET_KEY")
SECURITY_REGISTERABLE = True
SECURITY_SEND_REGIS... | [
"os.environ.get"
] | [((234, 262), 'os.environ.get', 'os.environ.get', (['"""SECRET_KEY"""'], {}), "('SECRET_KEY')\n", (248, 262), False, 'import os\n'), ((367, 407), 'os.environ.get', 'os.environ.get', (['"""SECURITY_PASSWORD_SALT"""'], {}), "('SECURITY_PASSWORD_SALT')\n", (381, 407), False, 'import os\n')] |
# ,"geometry".*\},"properties -> ,"properties
import re
import json
import string
from shapely.geometry import shape
from shapely.strtree import STRtree
# def remove_geometry(string):
# return re.sub(r',"geometry".*\},"properties', ',"properties', string)[:-2]
# def generatePolygon(coordinates):
# coordinates... | [
"shapely.geometry.shape",
"json.loads",
"json.dumps",
"shapely.strtree.STRtree"
] | [((531, 547), 'json.loads', 'json.loads', (['"""{}"""'], {}), "('{}')\n", (541, 547), False, 'import json\n'), ((1970, 1987), 'shapely.strtree.STRtree', 'STRtree', (['polygons'], {}), '(polygons)\n', (1977, 1987), False, 'from shapely.strtree import STRtree\n'), ((636, 671), 'json.loads', 'json.loads', (['"""{"adjacent... |
import pytest
def test_ec2user_user_group(host):
"""Check if the ec2-user user created in a ec2-user group and its UID and GUID values is 1000"""
assert host.user("ec2-user").exists
assert host.group("ec2-user").exists
assert host.user("ec2-user").uid == 1000
assert host.user("ec2-user").gid == 10... | [
"pytest.mark.dependency"
] | [((1803, 1827), 'pytest.mark.dependency', 'pytest.mark.dependency', ([], {}), '()\n', (1825, 1827), False, 'import pytest\n'), ((2043, 2099), 'pytest.mark.dependency', 'pytest.mark.dependency', ([], {'depends': "['test_get_machine_ids']"}), "(depends=['test_get_machine_ids'])\n", (2065, 2099), False, 'import pytest\n')... |
from django.test import TestCase
from django.core.urlresolvers import reverse
from django.contrib.auth.models import Group
from django.contrib.auth.models import User
import json
class StoriesTestCase(TestCase):
fixtures = ['test_fixtures']
def setUp(self):
user = User.objects.create_user(username='... | [
"json.loads",
"django.contrib.auth.models.Group",
"django.contrib.auth.models.User.objects.create_user",
"django.core.urlresolvers.reverse"
] | [((285, 349), 'django.contrib.auth.models.User.objects.create_user', 'User.objects.create_user', ([], {'username': '"""test"""', 'password': '"""<PASSWORD>"""'}), "(username='test', password='<PASSWORD>')\n", (309, 349), False, 'from django.contrib.auth.models import User\n'), ((372, 406), 'django.contrib.auth.models.G... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
from wbia_cnn import utils
from wbia_cnn import ingest_helpers
from wbia_cnn import ingest_wbia
from wbia_cnn.dataset import DataSet
from os.path import join, basename, splitext
import utool as ut
print, rrr, profile = ut.inject2(... | [
"utool.dict_str",
"utool.grab_zipped_url",
"wbia_cnn.dataset.DataSet.from_alias_key",
"utool.doctest_funcs",
"numpy.array",
"wbia_cnn.dataset.DataSet.new_training_set",
"multiprocessing.freeze_support",
"wbia_cnn.utils.convert_cv2_images_to_theano_images",
"wbia_cnn.ingest_helpers.extract_liberty_st... | [((309, 329), 'utool.inject2', 'ut.inject2', (['__name__'], {}), '(__name__)\n', (319, 329), True, 'import utool as ut\n'), ((350, 404), 'utool.get_argflag', 'ut.get_argflag', (["('--nocache-cnn', '--nocache-dataset')"], {}), "(('--nocache-cnn', '--nocache-dataset'))\n", (364, 404), True, 'import utool as ut\n'), ((761... |
import argparse
from pythainlp import cli
from pythainlp.tag import pos_tag
class SubAppBase:
def __init__(self, name, argv):
parser = argparse.ArgumentParser(name)
parser.add_argument(
"--text",
type=str,
help="input text",
)
parser.add_argume... | [
"pythainlp.cli.exit_if_empty",
"argparse.ArgumentParser",
"pythainlp.cli.make_usage"
] | [((150, 179), 'argparse.ArgumentParser', 'argparse.ArgumentParser', (['name'], {}), '(name)\n', (173, 179), False, 'import argparse\n'), ((1697, 1736), 'pythainlp.cli.exit_if_empty', 'cli.exit_if_empty', (['args.command', 'parser'], {}), '(args.command, parser)\n', (1714, 1736), False, 'from pythainlp import cli\n'), (... |
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#
# Author: <NAME>
# <EMAIL>
#
# File Created: Wednesday, 10th January 2018 11:38:17 pm
# Last Modified: Sunday, 4th March 2018 6:26:29 pm
# Modified By: <NAME> (<EMAIL>)
#
# Give the best to the world
# Copyright - 2018 Ardz.Co
# +++++++++++++++++++... | [
"django.db.models.DateField",
"django.contrib.contenttypes.models.ContentType.objects.get_for_model",
"django.db.models.TextField",
"django.db.models.ForeignKey",
"django.db.models.IntegerField",
"django.db.models.ManyToManyField",
"django.db.models.FileField",
"django.db.models.BooleanField",
"djan... | [((964, 1061), 'django.db.models.PositiveIntegerField', 'models.PositiveIntegerField', ([], {'choices': 'GENDER_CHOICES', 'default': '(3)', 'verbose_name': '"""Nama Tampilan"""'}), "(choices=GENDER_CHOICES, default=3, verbose_name\n ='Nama Tampilan')\n", (991, 1061), False, 'from django.db import models\n'), ((1070,... |
"""Server control"""
import os
import signal
from lockfile.pidlockfile import PIDLockFile
from wsgiserver import WSGIServer
from .api import API
from .configuration import DEFAULT_CFG_PATH, _IN_USER_DIR, _try_dir, load_configuration
from .database import init_db
def _pid_dir():
return _try_dir("/tmp/too-simple"... | [
"lockfile.pidlockfile.PIDLockFile",
"os.kill",
"wsgiserver.WSGIServer"
] | [((909, 937), 'os.kill', 'os.kill', (['pid', 'signal.SIGTERM'], {}), '(pid, signal.SIGTERM)\n', (916, 937), False, 'import os\n'), ((1082, 1103), 'lockfile.pidlockfile.PIDLockFile', 'PIDLockFile', (['PID_FILE'], {}), '(PID_FILE)\n', (1093, 1103), False, 'from lockfile.pidlockfile import PIDLockFile\n'), ((1355, 1402), ... |
import sys
sys.path.append('..')
import glob
from typing import NoReturn
from multiprocessing import cpu_count
from sklearn.model_selection import train_test_split
from src.utilities.tfrecords_save import multi_create_tfrecords_in_shards
def main(
num_files_to_create: int = 96,
num_workeers: int = cpu_count(... | [
"sklearn.model_selection.train_test_split",
"multiprocessing.cpu_count",
"src.utilities.tfrecords_save.multi_create_tfrecords_in_shards",
"sys.path.append",
"glob.glob"
] | [((11, 32), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (26, 32), False, 'import sys\n'), ((530, 558), 'glob.glob', 'glob.glob', (['f"""/data/spec/*/*"""'], {}), "(f'/data/spec/*/*')\n", (539, 558), False, 'import glob\n'), ((608, 693), 'sklearn.model_selection.train_test_split', 'train_test_s... |
from pypsrp.client import Client
import os
import zipfile
from util import util
import tempfile
from pypsrp.powershell import PowerShell, RunspacePool
from pypsrp.wsman import WSMan
from pypsrp.shell import WinRS
from pypsrp.shell import Process
from pypsrp.shell import SignalCode
def winRsGetWinstallFolder():
sc... | [
"zipfile.ZipFile",
"pypsrp.shell.Process",
"util.util.cleanup",
"os.path.join",
"os.path.dirname",
"os.rmdir",
"pypsrp.client.Client",
"pypsrp.wsman.WSMan",
"pypsrp.powershell.RunspacePool",
"tempfile.mkdtemp",
"os.unlink",
"pypsrp.powershell.PowerShell",
"os.walk",
"pypsrp.shell.WinRS"
] | [((331, 356), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (346, 356), False, 'import os\n'), ((375, 411), 'os.path.join', 'os.path.join', (['script_dir', '"""winstall"""'], {}), "(script_dir, 'winstall')\n", (387, 411), False, 'import os\n'), ((2068, 2081), 'os.walk', 'os.walk', (['path'],... |
from openrec import ModelTrainer
from openrec.utils import Dataset
from openrec.recommenders import YouTubeRec
from openrec.utils.evaluators import AUC, Recall
from openrec.utils.samplers import YouTubeSampler, YouTubeEvaluationSampler
import numpy as np
train_data = np.load('dataset/lastfm/lastfm_train.npy')
test_dat... | [
"openrec.utils.samplers.YouTubeEvaluationSampler",
"openrec.utils.evaluators.Recall",
"openrec.utils.evaluators.AUC",
"openrec.utils.samplers.YouTubeSampler",
"openrec.utils.Dataset",
"numpy.load",
"openrec.ModelTrainer",
"openrec.recommenders.YouTubeRec"
] | [((269, 311), 'numpy.load', 'np.load', (['"""dataset/lastfm/lastfm_train.npy"""'], {}), "('dataset/lastfm/lastfm_train.npy')\n", (276, 311), True, 'import numpy as np\n'), ((324, 365), 'numpy.load', 'np.load', (['"""dataset/lastfm/lastfm_test.npy"""'], {}), "('dataset/lastfm/lastfm_test.npy')\n", (331, 365), True, 'imp... |
import functools
import inspect
import numpy as np
import pandas as pd
from collections import namedtuple
from .base import StreamEnd
def _either_type(f):
"""Utility decorator to allow for either no-arg decorator or arg decorator
Args:
f (callable): Callable to decorate
"""
... | [
"collections.namedtuple",
"inspect.ismethod",
"inspect.signature",
"functools.wraps",
"inspect.getargspec",
"inspect.isgeneratorfunction"
] | [((325, 343), 'functools.wraps', 'functools.wraps', (['f'], {}), '(f)\n', (340, 343), False, 'import functools\n'), ((3450, 3487), 'inspect.isgeneratorfunction', 'inspect.isgeneratorfunction', (['callable'], {}), '(callable)\n', (3477, 3487), False, 'import inspect\n'), ((3607, 3634), 'inspect.signature', 'inspect.sign... |
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('', include('frontend.urls')), # home page react
path('', include('leads.urls')), # leads page api
path('', include('accounts.urls')), # accounts page api
]
| [
"django.urls.include"
] | [((101, 125), 'django.urls.include', 'include', (['"""frontend.urls"""'], {}), "('frontend.urls')\n", (108, 125), False, 'from django.urls import path, include\n'), ((159, 180), 'django.urls.include', 'include', (['"""leads.urls"""'], {}), "('leads.urls')\n", (166, 180), False, 'from django.urls import path, include\n'... |
import logging
import pandas as pd
from cellpy.utils.batch_tools.batch_core import BaseAnalyzer
from cellpy.utils.ocv_rlx import select_ocv_points
from cellpy.exceptions import UnderDefined
class ICAAnalyzer(BaseAnalyzer):
def __init__(self):
super().__init__()
class EISAnalyzer(BaseAnalyzer):
def... | [
"logging.debug",
"logging.warning",
"cellpy.utils.ocv_rlx.select_ocv_points",
"cellpy.exceptions.UnderDefined",
"logging.info"
] | [((3216, 3266), 'logging.debug', 'logging.debug', (['f"""start engine::{engine.__name__}]"""'], {}), "(f'start engine::{engine.__name__}]')\n", (3229, 3266), False, 'import logging\n'), ((3401, 3432), 'logging.debug', 'logging.debug', (['"""::engine ended"""'], {}), "('::engine ended')\n", (3414, 3432), False, 'import ... |
from setuptools import setup
setup(
name='dictlisttools',
version='1.0.0',
packages=['dictlisttools', 'dictlisttools.tests'],
test_suite='dictlisttools.tests',
url='https://github.com/anthonyblanchflower/dictlisttools',
author='<NAME>',
author_email='<EMAIL>',
description='Functions for... | [
"setuptools.setup"
] | [((30, 343), 'setuptools.setup', 'setup', ([], {'name': '"""dictlisttools"""', 'version': '"""1.0.0"""', 'packages': "['dictlisttools', 'dictlisttools.tests']", 'test_suite': '"""dictlisttools.tests"""', 'url': '"""https://github.com/anthonyblanchflower/dictlisttools"""', 'author': '"""<NAME>"""', 'author_email': '"""<... |
import numpy as np
import mxnet as mx
from mxnet import gluon
import gluoncv as gcv
from .nets import *
from .dataset import *
__all__ = ['get_data_loader', 'get_network', 'imagenet_batch_fn',
'default_batch_fn', 'default_val_fn', 'default_train_fn']
def get_data_loader(dataset, input_size, batch_size, num... | [
"mxnet.autograd.record",
"mxnet.gluon.utils.split_and_load",
"mxnet.autograd.pause",
"mxnet.gluon.data.DataLoader",
"numpy.random.shuffle"
] | [((2204, 2273), 'mxnet.gluon.utils.split_and_load', 'gluon.utils.split_and_load', (['batch.data[0]'], {'ctx_list': 'ctx', 'batch_axis': '(0)'}), '(batch.data[0], ctx_list=ctx, batch_axis=0)\n', (2230, 2273), False, 'from mxnet import gluon\n'), ((2286, 2356), 'mxnet.gluon.utils.split_and_load', 'gluon.utils.split_and_l... |
import datetime, calendar
from dateutil.relativedelta import relativedelta
from freezegun import freeze_time
from doajtest.helpers import DoajTestCase
from portality.scripts.prune_marvel import generate_delete_pattern
class TestPruneMarvel(DoajTestCase):
@classmethod
def setUpClass(cls):
cls.runs = ... | [
"dateutil.relativedelta.relativedelta",
"portality.scripts.prune_marvel.generate_delete_pattern",
"calendar.monthrange",
"datetime.date",
"freezegun.freeze_time"
] | [((929, 945), 'freezegun.freeze_time', 'freeze_time', (['run'], {}), '(run)\n', (940, 945), False, 'from freezegun import freeze_time\n'), ((1159, 1184), 'portality.scripts.prune_marvel.generate_delete_pattern', 'generate_delete_pattern', ([], {}), '()\n', (1182, 1184), False, 'from portality.scripts.prune_marvel impor... |
# Copyright 2016-2018 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
#
# or in the "license" f... | [
"contextlib2.redirect_stdout",
"mock.patch",
"subprocess.CalledProcessError",
"io.StringIO",
"mock.mock_open"
] | [((1524, 1561), 'mock.patch', 'mock.patch', (['"""subprocess.check_output"""'], {}), "('subprocess.check_output')\n", (1534, 1561), False, 'import mock\n'), ((1867, 1904), 'mock.patch', 'mock.patch', (['"""subprocess.check_output"""'], {}), "('subprocess.check_output')\n", (1877, 1904), False, 'import mock\n'), ((2814,... |
'''
'''
#
# Adapted from MATLAB code written by <NAME> (see Nishimoto, et al., 2011).
# <NAME> (Jan, 2016)
#
# Updates:
# <NAME> (Apr, 2020)
#
import itertools
from PIL import Image
import numpy as np
from moten.utils import (DotDict,
iterator_func,
log_compress,
... | [
"numpy.product",
"numpy.abs",
"numpy.ceil",
"itertools.product",
"numpy.asarray",
"numpy.floor",
"numpy.exp",
"numpy.zeros",
"numpy.linspace",
"scipy.stats.zscore",
"numpy.cos",
"numpy.sin",
"numpy.meshgrid",
"numpy.zeros_like",
"numpy.arange"
] | [((1666, 1708), 'numpy.zeros', 'np.zeros', (['(nimages, nfilters)'], {'dtype': 'dtype'}), '((nimages, nfilters), dtype=dtype)\n', (1674, 1708), True, 'import numpy as np\n'), ((1729, 1771), 'numpy.zeros', 'np.zeros', (['(nimages, nfilters)'], {'dtype': 'dtype'}), '((nimages, nfilters), dtype=dtype)\n', (1737, 1771), Tr... |
from fractions import Fraction
f1=Fraction(1,2)
f2=f1
print(f1,f2)
print(f1 is f2)
print(f1.numerator ,f1.denominator)
f1.numerator = 3
f3=Fraction(1,3)
f1+=f3
print(f1,f2)
print(f1 is f2) | [
"fractions.Fraction"
] | [((35, 49), 'fractions.Fraction', 'Fraction', (['(1)', '(2)'], {}), '(1, 2)\n', (43, 49), False, 'from fractions import Fraction\n'), ((140, 154), 'fractions.Fraction', 'Fraction', (['(1)', '(3)'], {}), '(1, 3)\n', (148, 154), False, 'from fractions import Fraction\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Data loader for the PyTorch framework.
"""
from tqdm import tqdm
import os, re
import torch
import torch.utils.data as data
from utils import select
class MNIST_bis(data.Dataset):
def __init__(self, dataset, size, digits_to_keep, stratified_sampling=True):
... | [
"utils.select"
] | [((370, 428), 'utils.select', 'select', (['dataset', 'size', 'digits_to_keep', 'stratified_sampling'], {}), '(dataset, size, digits_to_keep, stratified_sampling)\n', (376, 428), False, 'from utils import select\n')] |
from gripper import GripperInfo
from grasp import *
from klampt.model import ik
from klampt.math import vectorops,so3,se3
from klampt.model import contact
from klampt import io
import copy
import json
import os
def _object_name(obj):
if isinstance(obj,str):
return obj
elif hasattr(obj,'name'):
... | [
"os.path.exists",
"known_grippers.GripperInfo.get",
"os.listdir",
"klampt.WorldModel",
"klampt.math.se3.identity",
"klampt.vis.run",
"os.path.join",
"klampt.vis.addText",
"known_grippers.GripperInfo.register",
"os.path.dirname",
"known_grippers.GripperInfo.all_grippers.keys",
"json.load",
"k... | [((6991, 7015), 'known_grippers.GripperInfo.get', 'GripperInfo.get', (['gripper'], {}), '(gripper)\n', (7006, 7015), False, 'from known_grippers import GripperInfo\n'), ((7664, 7676), 'klampt.WorldModel', 'WorldModel', ([], {}), '()\n', (7674, 7676), False, 'from klampt import WorldModel\n'), ((11333, 11342), 'klampt.v... |
#! /usr/bin/env python
#! coding:utf-8
from elasticsearch import Elasticsearch
# connection
es = Elasticsearch(["connection"])
# search record
def search_record():
body = {
"query": {
"match_all": {}
}
}
res = es.search(index="test", body=body)
print(res)
| [
"elasticsearch.Elasticsearch"
] | [((100, 129), 'elasticsearch.Elasticsearch', 'Elasticsearch', (["['connection']"], {}), "(['connection'])\n", (113, 129), False, 'from elasticsearch import Elasticsearch\n')] |
from django import template
from django.db.models import Model
from django.http import Http404
from django.urls import reverse, resolve
from formfactory import models
register = template.Library()
@register.tag()
def render_form(parser, token):
"""{% render_form <form_slug> %}"""
tokens = token.split_conten... | [
"formfactory.models.Form.objects.get",
"django.template.TemplateSyntaxError",
"django.template.Variable",
"django.template.Library",
"django.urls.resolve",
"django.http.Http404"
] | [((180, 198), 'django.template.Library', 'template.Library', ([], {}), '()\n', (196, 198), False, 'from django import template\n'), ((364, 434), 'django.template.TemplateSyntaxError', 'template.TemplateSyntaxError', (['"""{% render_form <form_slug>/<object> %}"""'], {}), "('{% render_form <form_slug>/<object> %}')\n", ... |
from __future__ import division
from past.utils import old_div
from bpz_tools import *
def function(z, m, nt):
nz = len(z)
p_i = ones((nz, nt)) * 1.
fq = 1.
fs = 1.
p_i[1:, 1:nt] = 0.
ns = sum(p_i[0, 1:nt])
nq = sum(p_i[:, 0])
#Normalize relative fractions
p_i[:, 0] *= (old_div(fq,... | [
"past.utils.old_div"
] | [((309, 324), 'past.utils.old_div', 'old_div', (['fq', 'nq'], {}), '(fq, nq)\n', (316, 324), False, 'from past.utils import old_div\n'), ((347, 362), 'past.utils.old_div', 'old_div', (['fs', 'ns'], {}), '(fs, ns)\n', (354, 362), False, 'from past.utils import old_div\n'), ((413, 442), 'past.utils.old_div', 'old_div', (... |
# -*- coding: utf-8 -*-
# @Time : 2018/1/7 上午11:47
# @Author : Mazy
# @File : html_outputer.py
# @Software: PyCharm
from xlwt import Workbook, Worksheet
import xlsxwriter
class HtmlOutputer(object):
# 使用 xlwt 将数据存到 Excel
def save_to_excel(self, results, tag_name, file_name):
book = Workbook(e... | [
"xlwt.Workbook",
"xlsxwriter.Workbook"
] | [((310, 336), 'xlwt.Workbook', 'Workbook', ([], {'encoding': '"""utf-8"""'}), "(encoding='utf-8')\n", (318, 336), False, 'from xlwt import Workbook, Worksheet\n'), ((905, 965), 'xlsxwriter.Workbook', 'xlsxwriter.Workbook', (["('/Users/bai/Desktop/%s.xls' % file_name)"], {}), "('/Users/bai/Desktop/%s.xls' % file_name)\n... |
import time
import copy
import gobject
from phony.base.log import ClassLogger
from RPi import GPIO
from types import MethodType
class Inputs(ClassLogger):
_layout = {}
_inputs_by_channel = {}
_rising_callback_by_channel_name = {}
_falling_callback_by_channel_name = {}
_pulse_callback_by_channel_name = {}
... | [
"phony.base.log.ClassLogger.__init__",
"RPi.GPIO.add_event_detect",
"gobject.threads_init",
"RPi.GPIO.setup",
"RPi.GPIO.output",
"RPi.GPIO.setwarnings",
"time.sleep",
"RPi.GPIO.remove_event_detect",
"RPi.GPIO.input",
"copy.deepcopy",
"RPi.GPIO.setmode"
] | [((354, 380), 'phony.base.log.ClassLogger.__init__', 'ClassLogger.__init__', (['self'], {}), '(self)\n', (374, 380), False, 'from phony.base.log import ClassLogger\n'), ((482, 504), 'gobject.threads_init', 'gobject.threads_init', ([], {}), '()\n', (502, 504), False, 'import gobject\n'), ((510, 532), 'RPi.GPIO.setmode',... |
import sys
print('Command "git commit" is diabled. Use "git gud commit" instead.')
sys.exit(1)
| [
"sys.exit"
] | [((84, 95), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (92, 95), False, 'import sys\n')] |
import os
import csv
import random
import numpy
import xml.etree.ElementTree as ET
def parse_tsv(base_dir, destination_file, nomenclature='relation', test=None):
"""
:param base_dir:
:param destination_file:
:param nomenclature:
:param test
:return:
"""
count_wrong = 0
line_saves... | [
"csv.writer",
"os.listdir",
"xml.etree.ElementTree.fromstring"
] | [((364, 384), 'os.listdir', 'os.listdir', (['base_dir'], {}), '(base_dir)\n', (374, 384), False, 'import os\n'), ((2648, 2687), 'csv.writer', 'csv.writer', (['output_file'], {'delimiter': '"""\t"""'}), "(output_file, delimiter='\\t')\n", (2658, 2687), False, 'import csv\n'), ((721, 743), 'xml.etree.ElementTree.fromstri... |
# coding=utf-8
"""
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); y... | [
"dubbo_client.DubboClient",
"dubbo_client.ApplicationConfig",
"dubbo_client.ZookeeperRegistry"
] | [((984, 1013), 'dubbo_client.ApplicationConfig', 'ApplicationConfig', (['"""provider"""'], {}), "('provider')\n", (1001, 1013), False, 'from dubbo_client import ApplicationConfig\n'), ((1284, 1327), 'dubbo_client.ZookeeperRegistry', 'ZookeeperRegistry', (['"""127.0.0.1:2181"""', 'config'], {}), "('127.0.0.1:2181', conf... |
import numpy as np
from core.game import Game
from core.utils import arr_to_str
class AtariWrapper(Game):
def __init__(self, env, discount: float, cvt_string=True):
"""Atari Wrapper
Parameters
----------
env: Any
another env wrapper
discount: float
d... | [
"core.utils.arr_to_str"
] | [((834, 857), 'core.utils.arr_to_str', 'arr_to_str', (['observation'], {}), '(observation)\n', (844, 857), False, 'from core.utils import arr_to_str\n'), ((1091, 1114), 'core.utils.arr_to_str', 'arr_to_str', (['observation'], {}), '(observation)\n', (1101, 1114), False, 'from core.utils import arr_to_str\n')] |
import asyncio
import pytest
from tloen.domain import Application, AudioEffect
@pytest.mark.asyncio
async def test_gain(dc_index_synthdef_factory):
application = Application(channel_count=1)
context = await application.add_context()
track = await context.add_track()
await track.add_device(AudioEffec... | [
"tloen.domain.Application",
"asyncio.sleep"
] | [((170, 198), 'tloen.domain.Application', 'Application', ([], {'channel_count': '(1)'}), '(channel_count=1)\n', (181, 198), False, 'from tloen.domain import Application, AudioEffect\n'), ((398, 416), 'asyncio.sleep', 'asyncio.sleep', (['(0.1)'], {}), '(0.1)\n', (411, 416), False, 'import asyncio\n'), ((864, 882), 'asyn... |
from copy import deepcopy
from pymaclab.dsge.translators import pml_to_dynarepp
from pymaclab.dsge.translators import dynarepp_to_pml
from pymaclab.dsge.translators import pml_to_pml
from pymaclab.dsge.parsers._dsgeparser import ff_chron_str, bb_chron_str
class Translators(object):
def __init__(self,other=None):
... | [
"pymaclab.dsge.parsers._dsgeparser.ff_chron_str",
"pymaclab.dsge.translators.pml_to_pml.translate",
"pymaclab.dsge.parsers._dsgeparser.bb_chron_str",
"pymaclab.dsge.translators.pml_to_dynarepp.translate",
"pymaclab.dsge.translators.dynarepp_to_pml.translate",
"copy.deepcopy"
] | [((353, 386), 'copy.deepcopy', 'deepcopy', (['other.template_paramdic'], {}), '(other.template_paramdic)\n', (361, 386), False, 'from copy import deepcopy\n'), ((1194, 1226), 'copy.deepcopy', 'deepcopy', (['self.template_paramdic'], {}), '(self.template_paramdic)\n', (1202, 1226), False, 'from copy import deepcopy\n'),... |
# Copyright 2018 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | [
"collections.namedtuple",
"numpy.sign"
] | [((782, 909), 'collections.namedtuple', 'collections.namedtuple', (['"""ObservableSpec"""', "['enabled', 'update_interval', 'buffer_size', 'delay', 'aggregator',\n 'corruptor']"], {}), "('ObservableSpec', ['enabled', 'update_interval',\n 'buffer_size', 'delay', 'aggregator', 'corruptor'])\n", (804, 909), False, '... |
"""Example test."""
from replace_me import main
def test(capsys):
"""Example test."""
main()
stdout, stderr = capsys.readouterr()
assert 'Hello World!\n' == stdout
assert not stderr
| [
"replace_me.main"
] | [((97, 103), 'replace_me.main', 'main', ([], {}), '()\n', (101, 103), False, 'from replace_me import main\n')] |
import sqlite3
import operator
import subprocess
import os
import csv
import apsw
import time
import threading
DB_NAME = "example.db"
# A class to store flight information.
class Flight:
def __init__(self, fid = -1, dayOfMonth=0, carrierId=0, flightNum=0, originCity="", destCity="", time=0, capacity=0, price=0):
... | [
"subprocess.run",
"apsw.Connection",
"csv.reader",
"os.remove"
] | [((2079, 2130), 'apsw.Connection', 'apsw.Connection', (['self.db_name'], {'statementcachesize': '(0)'}), '(self.db_name, statementcachesize=0)\n', (2094, 2130), False, 'import apsw\n'), ((2222, 2273), 'apsw.Connection', 'apsw.Connection', (['self.db_name'], {'statementcachesize': '(0)'}), '(self.db_name, statementcache... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Esse script é responsável por juntar todos os
arquivos .csv de uma estação do INMET para um
único arquivo .csv. Também é realizado a formatação
dos dados. A base de dados pode ser encontra aqui:
https://portal.inmet.gov.br/dadoshistoricos
autho... | [
"os.listdir",
"pandas.read_csv",
"pandas.DataFrame",
"pandas.concat",
"pandas.to_datetime"
] | [((670, 979), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['pressao_atm_(mB)', 'radiacao_global_(Kj/m2)', 'temp_ar_bulbo_seco_(C)',\n 'temp_ponto_de_orvalho_(C)', 'temp_max_(C)', 'temp_min_(C)',\n 'umidade_rlv_ar_(%)', 'vento_direcao_horaria_(gr)',\n 'vento_velocidade_horaria_(m/s)', 'precipitacao_to... |
from django.urls import path
from blog.views import BlogListView, BlogWithTypeView, BlogWithDate, BlogDetailView
urlpatterns = [
path('', BlogListView.as_view(), name='blog_list'),
path('<int:pk>/', BlogDetailView.as_view(), name='blog_detail'),
path('type/<int:blog_type_pk>/', BlogWithTypeView.as_view(),... | [
"blog.views.BlogWithTypeView.as_view",
"blog.views.BlogDetailView.as_view",
"blog.views.BlogListView.as_view",
"blog.views.BlogWithDate.as_view"
] | [((144, 166), 'blog.views.BlogListView.as_view', 'BlogListView.as_view', ([], {}), '()\n', (164, 166), False, 'from blog.views import BlogListView, BlogWithTypeView, BlogWithDate, BlogDetailView\n'), ((209, 233), 'blog.views.BlogDetailView.as_view', 'BlogDetailView.as_view', ([], {}), '()\n', (231, 233), False, 'from b... |
import unittest
from unittest import mock
from apiserver.search import parse_query
from apiserver.search import join
from apiserver.search.union import name_similarity
from .utils import DataTestCase
class TestSearch(unittest.TestCase):
def test_simple(self):
"""Test the query generation for a simple se... | [
"apiserver.search.union.name_similarity",
"unittest.mock.Mock",
"apiserver.search.join.get_temporal_join_search_results",
"apiserver.search.parse_query"
] | [((373, 434), 'apiserver.search.parse_query', 'parse_query', (["{'keywords': ['green', 'taxi'], 'source': 'gov'}"], {}), "({'keywords': ['green', 'taxi'], 'source': 'gov'})\n", (384, 434), False, 'from apiserver.search import parse_query\n'), ((2357, 2426), 'apiserver.search.parse_query', 'parse_query', (["{'keywords':... |
#!/usr/bin/python3 -S
# -*- coding: utf-8 -*-
"""
`Unit tests for cargo.expressions.Subquery`
--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--
2016 <NAME> © The MIT License (MIT)
http://github.com/jaredlunde
"""
import unittest
from vital.security import randkey
from cargo imp... | [
"unittest.main",
"vital.security.randkey"
] | [((447, 468), 'vital.security.randkey', 'randkey', (['(24)', 'keyspace'], {}), '(24, keyspace)\n', (454, 468), False, 'from vital.security import randkey\n'), ((481, 502), 'vital.security.randkey', 'randkey', (['(24)', 'keyspace'], {}), '(24, keyspace)\n', (488, 502), False, 'from vital.security import randkey\n'), ((2... |
from django.db import models
class Page(models.Model):
title = models.CharField(max_length=120)
text = models.TextField(blank=True, null=True)
img_url = models.URLField()
img_alt = models.CharField(max_length=120)
external_url = models.URLField()
external_text = models.CharField(max_length=50)... | [
"django.db.models.TextField",
"django.db.models.DateTimeField",
"django.db.models.BooleanField",
"django.db.models.URLField",
"django.db.models.CharField"
] | [((69, 101), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(120)'}), '(max_length=120)\n', (85, 101), False, 'from django.db import models\n'), ((113, 152), 'django.db.models.TextField', 'models.TextField', ([], {'blank': '(True)', 'null': '(True)'}), '(blank=True, null=True)\n', (129, 152), Fa... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 12 09:45:01 2020
@author: antonio
"""
import pandas as pd
import argparse
import warnings
###### 0. Load valid codes lists: ######
def read_gs(gs_path):
gs_data = pd.read_csv(gs_path, sep="\t", names=['clinical_case', 'code'],
... | [
"pandas.Series",
"warnings.warn",
"argparse.ArgumentParser",
"pandas.read_csv"
] | [((240, 357), 'pandas.read_csv', 'pd.read_csv', (['gs_path'], {'sep': '"""\t"""', 'names': "['clinical_case', 'code']", 'dtype': "{'clinical_case': object, 'code': object}"}), "(gs_path, sep='\\t', names=['clinical_case', 'code'], dtype={\n 'clinical_case': object, 'code': object})\n", (251, 357), True, 'import pand... |
"""
Unit tests for scCODA
"""
import unittest
import numpy as np
import scanpy as sc
import tensorflow as tf
import pandas as pd
import os
import sys
sys.path.insert(0, os.path.abspath('.'))
sys.path.insert(0, os.path.abspath('..'))
from sccoda.util import cell_composition_data as dat
from sccoda.util import comp_ana... | [
"numpy.mean",
"numpy.abs",
"sccoda.util.data_generation.b_w_from_abs_change",
"tensorflow.random.set_seed",
"scanpy.datasets.pbmc3k_processed",
"sccoda.util.data_generation.counts_from_first",
"sccoda.util.cell_composition_data.from_pandas",
"unittest.main",
"pandas.set_option",
"numpy.array",
"... | [((376, 417), 'pandas.set_option', 'pd.set_option', (['"""display.max_columns"""', '(500)'], {}), "('display.max_columns', 500)\n", (389, 417), True, 'import pandas as pd\n'), ((418, 456), 'pandas.set_option', 'pd.set_option', (['"""display.max_rows"""', '(500)'], {}), "('display.max_rows', 500)\n", (431, 456), True, '... |
# -*- coding: utf-8 -*-
import typing
import collections
import inspect
import functools
__author__ = """<NAME>"""
__email__ = '<EMAIL>'
__version__ = '0.1.4'
__all__ = (
'aiter',
'arange',
'transform_factory',
'alist',
'atuple',
'aset',
'adict',
'amap',
'anext',
'afilter',
... | [
"inspect.isawaitable",
"inspect.iscoroutinefunction",
"functools.wraps",
"inspect.isasyncgenfunction",
"functools.partial"
] | [((4220, 4268), 'functools.partial', 'functools.partial', (['transform_factory'], {'_type': 'list'}), '(transform_factory, _type=list)\n', (4237, 4268), False, 'import functools\n'), ((4638, 4687), 'functools.partial', 'functools.partial', (['transform_factory'], {'_type': 'tuple'}), '(transform_factory, _type=tuple)\n... |
import discord
from discord.ext import commands, tasks
from itertools import cycle
status = cycle(["Managing the server", "Writing some music", "Making memes"])
class Admin(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_ready(self):
... | [
"discord.ext.commands.Cog.listener",
"itertools.cycle",
"discord.ext.commands.command"
] | [((93, 161), 'itertools.cycle', 'cycle', (["['Managing the server', 'Writing some music', 'Making memes']"], {}), "(['Managing the server', 'Writing some music', 'Making memes'])\n", (98, 161), False, 'from itertools import cycle\n'), ((258, 281), 'discord.ext.commands.Cog.listener', 'commands.Cog.listener', ([], {}), ... |
# -*— coding: utf-8 -*-
import numpy as np
import operator
'''
函数说明:knn算法,分类器
parameters:
inX - 用于分类的数据(测试集)
dataset - 用于训练的数据(训练集)
labels - 分类标签
k - knn算法参数, 选择距离最小的k个点
returns:
sortedClassCount[0][0] - 分类结果
'''
def classfy0(inX, dataSet, labels, k):
# numpy函数shape[0... | [
"numpy.array",
"numpy.tile",
"operator.itemgetter"
] | [((1286, 1335), 'numpy.array', 'np.array', (['[[1, 101], [5, 89], [108, 5], [115, 8]]'], {}), '([[1, 101], [5, 89], [108, 5], [115, 8]])\n', (1294, 1335), True, 'import numpy as np\n'), ((439, 469), 'numpy.tile', 'np.tile', (['inX', '(dataSetSize, 1)'], {}), '(inX, (dataSetSize, 1))\n', (446, 469), True, 'import numpy ... |
# coding: utf-8
# In[1]:
import sklearn
import numpy as np
from glob import glob
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.linear_model import... | [
"numpy.sqrt",
"keras.utils.vis_utils.plot_model",
"numpy.array",
"keras.layers.Dense",
"keras.preprocessing.sequence.pad_sequences",
"keras.layers.merge.concatenate",
"gensim.models.Word2Vec.load",
"keras.layers.convolutional.Conv1D",
"keras.layers.LSTM",
"keras.models.Model",
"numpy.concatenate... | [((4615, 4683), 'gensim.models.Word2Vec.load', 'Word2Vec.load', (['"""C:/Users/admin-karim/Desktop/BengWord2Vec/posts.bin"""'], {}), "('C:/Users/admin-karim/Desktop/BengWord2Vec/posts.bin')\n", (4628, 4683), False, 'from gensim.models import Word2Vec\n'), ((4804, 4846), 'numpy.zeros', 'np.zeros', (['(vocabulary_size, E... |
import datetime as dt
import hydra
import logging
import numpy as np
import os
import time
import torch
import torch.distributed as dist
from hydra.utils import instantiate
from ignite.contrib.handlers import ProgressBar
from ignite.engine import Engine, Events
from ignite.handlers import Checkpoint, TerminateOnNan
fr... | [
"utils.train.resume_from_checkpoint",
"apex.parallel.distributed.DistributedDataParallel",
"apex.amp.scale_loss",
"logging.debug",
"torch.distributed.destroy_process_group",
"torch.nn.utils.clip_grad_norm_",
"ignite.engine.Engine",
"torch.cuda.synchronize",
"apex.amp.initialize",
"torch.cuda.is_av... | [((11371, 11417), 'hydra.main', 'hydra.main', ([], {'config_path': '"""../config/train.yaml"""'}), "(config_path='../config/train.yaml')\n", (11381, 11417), False, 'import hydra\n'), ((1068, 1079), 'time.time', 'time.time', ([], {}), '()\n', (1077, 1079), False, 'import time\n'), ((1491, 1502), 'time.time', 'time.time'... |
"""
evaluation.py
-------------
This module provides classes and functions for evaluating a model.
By: <NAME>, Ph.D., 2018
"""
# Compatibility imports
from __future__ import absolute_import, division, print_function
# 3rd party imports
import numpy as np
import itertools
import matplotlib.pylab as plt
from sklearn.me... | [
"matplotlib.pylab.xticks",
"matplotlib.pylab.ylabel",
"matplotlib.pylab.figure",
"matplotlib.pylab.tight_layout",
"matplotlib.pylab.xlabel",
"matplotlib.pylab.imshow",
"matplotlib.pylab.show",
"matplotlib.pylab.yticks",
"matplotlib.colors.LinearSegmentedColormap.from_list",
"numpy.round",
"sklea... | [((568, 600), 'sklearn.metrics.confusion_matrix', 'confusion_matrix', (['y_true', 'y_pred'], {}), '(y_true, y_pred)\n', (584, 600), False, 'from sklearn.metrics import confusion_matrix\n'), ((713, 798), 'matplotlib.colors.LinearSegmentedColormap.from_list', 'LinearSegmentedColormap.from_list', (['"""laussen_labs_green"... |
from flask import current_app as app, render_template, request, redirect, jsonify, render_template_string
from CTFd.utils.decorators import admins_only
from CTFd.models import db, Teams, Solves, Awards, Challenges, Fails, Flags, Tags, Files, Tracking, Pages, Configs, Hints, Unlocks
from CTFd.plugins.flags import get_fl... | [
"flask.render_template",
"CTFd.models.Flags.query.filter_by",
"CTFd.admin.admin.route",
"CTFd.plugins.challenges.get_chal_class",
"os.path.join",
"CTFd.models.Challenges.query.with_entities",
"CTFd.models.Challenges.query.filter_by",
"os.path.basename",
"CTFd.models.Solves.query.filter_by",
"CTFd.... | [((506, 538), 'CTFd.admin.admin.route', 'admin.route', (['"""/admin/challenges"""'], {}), "('/admin/challenges')\n", (517, 538), False, 'from CTFd.admin import admin\n'), ((707, 758), 'CTFd.admin.admin.route', 'admin.route', (['"""/admin/challenges/<int:challenge_id>"""'], {}), "('/admin/challenges/<int:challenge_id>')... |
"""
Tests find_lcs_optimized function
"""
import timeit
import unittest
from lab_2.main import find_lcs_length, find_lcs_length_optimized
class FindLcsOptimizedTest(unittest.TestCase):
"""
Checks for find_lcs_optimized function
"""
def test_find_lcs_length_optimized_works_faster(self):
"""
... | [
"timeit.default_timer",
"lab_2.main.find_lcs_length",
"lab_2.main.find_lcs_length_optimized"
] | [((617, 639), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (637, 639), False, 'import timeit\n'), ((648, 718), 'lab_2.main.find_lcs_length', 'find_lcs_length', (['sentence_first', 'sentence_second', 'plagiarism_threshold'], {}), '(sentence_first, sentence_second, plagiarism_threshold)\n', (663, 718... |
import base64
import datetime
import os
from collections import defaultdict, namedtuple
import jinja2
from model import Book, Cover, book_to_cover, load_books
BookWithCover = namedtuple(
'Book',
list(Book._fields) + ['cover']
)
def render_from_template(template_filename, books_with_cover_by_year, pages_... | [
"os.path.exists",
"model.book_to_cover",
"os.path.splitext",
"os.path.join",
"os.path.split",
"datetime.datetime.now",
"collections.defaultdict",
"os.mkdir",
"jinja2.FileSystemLoader",
"model.load_books"
] | [((352, 384), 'os.path.split', 'os.path.split', (['template_filename'], {}), '(template_filename)\n', (365, 384), False, 'import os\n'), ((395, 418), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (416, 418), False, 'import datetime\n'), ((691, 717), 'os.path.splitext', 'os.path.splitext', (['filen... |
"""Initialize the util subpackage of the pydvkbiology package.
This sub-package is used with data downloaded from UCSC.
"""
from pkg_resources import get_distribution, DistributionNotFound
__project__ = 'pydvkbiology'
__version__ = None # required for initial installation
try:
__version__ = get_distribution('pydv... | [
"pkg_resources.get_distribution"
] | [((298, 330), 'pkg_resources.get_distribution', 'get_distribution', (['"""pydvkbiology"""'], {}), "('pydvkbiology')\n", (314, 330), False, 'from pkg_resources import get_distribution, DistributionNotFound\n')] |
#!/usr/bin/env python
'''
Filename: test_equally_space.py
Description: unit tests to test equally_space_old.py
'''
__author__ = '<NAME>'
__email__ = '<EMAIL>'
__status__ = 'prototype'
# standard imports
import unittest
from equally_space import *
import matplotlib.pyplot as plt
import numpy as np
class TestEqually... | [
"numpy.arange",
"numpy.random.random",
"matplotlib.pyplot.plot",
"numpy.linspace",
"unittest.main",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.show"
] | [((3034, 3049), 'unittest.main', 'unittest.main', ([], {}), '()\n', (3047, 3049), False, 'import unittest\n'), ((2061, 2088), 'numpy.linspace', 'np.linspace', (['(0)', 'tot_dist', 'N'], {}), '(0, tot_dist, N)\n', (2072, 2088), True, 'import numpy as np\n'), ((2123, 2180), 'matplotlib.pyplot.plot', 'plt.plot', (['test_p... |
"""
Download URL: http://www.cs.cornell.edu/~cristian/data/cornell_movie_dialogs_corpus.zip
"""
import os
import codecs
import csv
from torch.datasets import NLPDataset
from utils.utils import maybe_download, maybe_unzip
class Corpus(NLPDataset):
working_dir = os.path.join("datasets", "cornell_movie_... | [
"os.path.exists",
"os.makedirs",
"utils.utils.maybe_unzip",
"csv.writer",
"os.path.join",
"utils.utils.maybe_download",
"codecs.decode"
] | [((280, 336), 'os.path.join', 'os.path.join', (['"""datasets"""', '"""cornell_movie_dialogs_corpus"""'], {}), "('datasets', 'cornell_movie_dialogs_corpus')\n", (292, 336), False, 'import os\n'), ((357, 421), 'os.path.join', 'os.path.join', (['working_dir', '"""raw"""', '"""cornell movie-dialogs corpus"""'], {}), "(work... |
import sys
sys.setrecursionlimit(1500)
def bubble_sort(arr: list) -> list:
n = len(arr)
for i in range(0, n - 1):
for j in range(0, n - i - 1):
if (arr[j] > arr[j + 1]):
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr
def selection_sort(arr: list) -> list:
n = l... | [
"sys.setrecursionlimit"
] | [((11, 38), 'sys.setrecursionlimit', 'sys.setrecursionlimit', (['(1500)'], {}), '(1500)\n', (32, 38), False, 'import sys\n')] |
# Generated by Django 2.1.5 on 2019-08-20 05:08
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('base', '0084_auto_20190728_0424'),
]
operations = [
migrations.CreateModel(
name='ProjectTodoIt... | [
"django.db.models.FloatField",
"django.db.models.AutoField",
"django.db.models.CharField",
"django.db.models.ForeignKey"
] | [((374, 467), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (390, 467), False, 'from django.db import migrations, models\... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# This file is part of libmodulemd
# Copyright (C) 2020 <NAME>
#
# Fedora-License-Identifier: MIT
# SPDX-2.0-License-Identifier: MIT
# SPDX-3.0-License-Identifier: MIT
#
# This program is free software.
# For more information on the license, see COPYING.
# For more informa... | [
"time.sleep"
] | [((1007, 1020), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (1017, 1020), False, 'import time\n')] |
import copy
import json
from django.contrib import admin
from django.core.serializers.json import DjangoJSONEncoder
from django.db.models import CharField, F, Sum, Value
from django.db.models.functions import (Concat, ExtractDay, ExtractMonth,
ExtractQuarter, ExtractYear, TruncD... | [
"django.utils.translation.gettext_lazy",
"investments.contrib.tags.models.Tag.objects.filter",
"django.db.models.functions.ExtractQuarter",
"django.urls.reverse",
"copy.copy",
"django.db.models.Sum",
"investments.utils.admin.get_all_years",
"django.shortcuts.render",
"django.db.models.functions.Trun... | [((16797, 16828), 'django.contrib.admin.register', 'admin.register', (['DividendPayment'], {}), '(DividendPayment)\n', (16811, 16828), False, 'from django.contrib import admin\n'), ((18167, 18198), 'django.contrib.admin.register', 'admin.register', (['InterestPayment'], {}), '(InterestPayment)\n', (18181, 18198), False... |
"""Module for interfacing with power factory."""
import os
import itertools
import numpy as np
import pandas as pd
import powerfactory as pf
from sinfactory.line import Line
from sinfactory.generator import Generator
from sinfactory.load import Load
from sinfactory.area import Area
from sinfactory.bus import Bus
from ... | [
"sinfactory.pfresults.PFResults",
"sinfactory.eigenresults.EigenValueResults",
"sinfactory.area.Area",
"numpy.sqrt",
"pandas.read_csv",
"powerfactory.GetApplication",
"sinfactory.load.Load",
"numpy.column_stack",
"numpy.count_nonzero",
"numpy.array",
"sinfactory.line.Line",
"pandas.DataFrame",... | [((628, 647), 'powerfactory.GetApplication', 'pf.GetApplication', ([], {}), '()\n', (645, 647), True, 'import powerfactory as pf\n'), ((8173, 8244), 'pandas.read_csv', 'pd.read_csv', (['filepath'], {'sep': '""","""', 'decimal': '"""."""', 'header': '[0, 1]', 'index_col': '(0)'}), "(filepath, sep=',', decimal='.', heade... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# import ipgetter
from PyQt5.QtWidgets import QApplication, QSystemTrayIcon, QMenu, QMainWindow
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import QAbstractNativeEventFilter, QAbstractEventDispatcher
import cpf
import signal
from pyqtkeybind import keybinder
from requ... | [
"signal.signal",
"PyQt5.QtWidgets.QMainWindow",
"PyQt5.QtWidgets.QMenu",
"PyQt5.QtGui.QIcon",
"requests.get",
"PyQt5.QtCore.QAbstractEventDispatcher.instance",
"PyQt5.QtWidgets.QApplication.clipboard",
"cpf.gerar_cpf",
"PyQt5.QtWidgets.QApplication",
"pyqtkeybind.keybinder.init"
] | [((822, 846), 'PyQt5.QtWidgets.QApplication.clipboard', 'QApplication.clipboard', ([], {}), '()\n', (844, 846), False, 'from PyQt5.QtWidgets import QApplication, QSystemTrayIcon, QMenu, QMainWindow\n'), ((1004, 1028), 'PyQt5.QtWidgets.QApplication.clipboard', 'QApplication.clipboard', ([], {}), '()\n', (1026, 1028), Fa... |
from flask import url_for
from mast import mail
from flask_mail import Message
def send_reset_email(user):
token = user.get_reset_token()
msg = Message('Password Reset Request',
sender='<EMAIL>',
recipients=[user.email])
msg.body = f'''To reset your password, visit the... | [
"flask_mail.Message",
"mast.mail.send",
"flask.url_for"
] | [((154, 230), 'flask_mail.Message', 'Message', (['"""Password Reset Request"""'], {'sender': '"""<EMAIL>"""', 'recipients': '[user.email]'}), "('Password Reset Request', sender='<EMAIL>', recipients=[user.email])\n", (161, 230), False, 'from flask_mail import Message\n'), ((508, 522), 'mast.mail.send', 'mail.send', (['... |
"""
Tests routes that are not in a module.
"""
import flask
import http.client
from ruddock.testing.fixtures import client
def test_home(client):
"""Tests the / route."""
response = client.get(flask.url_for('home'))
assert response.status_code == http.client.OK
def test_contact(client):
"""Tests the /contac... | [
"flask.url_for"
] | [((200, 221), 'flask.url_for', 'flask.url_for', (['"""home"""'], {}), "('home')\n", (213, 221), False, 'import flask\n'), ((356, 385), 'flask.url_for', 'flask.url_for', (['"""show_contact"""'], {}), "('show_contact')\n", (369, 385), False, 'import flask\n')] |
import re
from django.utils import timezone
from main.internals.db_helper import DBHelper
from main.internals.job import Job
class ControlHelper:
def __init__(self, job_data, action, job_new_data=None):
"""Constructor for the ControlHelper.
:param job_data: dict: contains the data... | [
"main.internals.db_helper.DBHelper.edit_job",
"re.compile",
"main.internals.db_helper.DBHelper.stop_process",
"django.utils.timezone.now",
"main.internals.job.Job",
"main.internals.db_helper.DBHelper.get_job_by_id",
"main.internals.db_helper.DBHelper.delete_entry",
"main.internals.db_helper.DBHelper.c... | [((3591, 3625), 'main.internals.db_helper.DBHelper.delete_entry', 'DBHelper.delete_entry', (['self.job.id'], {}), '(self.job.id)\n', (3612, 3625), False, 'from main.internals.db_helper import DBHelper\n'), ((5929, 6061), 'main.internals.db_helper.DBHelper.edit_job', 'DBHelper.edit_job', (['self.job.id', "self.job_new_d... |
# coding: utf-8
"""
Jamf Pro API
## Overview This is a sample Jamf Pro server which allows for usage without any authentication. The Jamf Pro environment which supports the Try it Out functionality does not run the current beta version of Jamf Pro, thus any newly added endpoints will result in an error and sh... | [
"jamf.api_client.ApiClient",
"six.iteritems",
"jamf.exceptions.ApiTypeError",
"jamf.exceptions.ApiValueError"
] | [((6642, 6683), 'six.iteritems', 'six.iteritems', (["local_var_params['kwargs']"], {}), "(local_var_params['kwargs'])\n", (6655, 6683), False, 'import six\n'), ((12703, 12744), 'six.iteritems', 'six.iteritems', (["local_var_params['kwargs']"], {}), "(local_var_params['kwargs'])\n", (12716, 12744), False, 'import six\n'... |
import heapq
class Dijkstra:
def __init__(self, rote_map, start_point, goal_point=None):
self.rote_map = rote_map
self.start_point = start_point
self.goal_point = goal_point
def execute(self):
num_of_city = 3 * 10 ** 5 + 10
dist = [float("inf") for _ in range(num_of_c... | [
"heapq.heappop",
"heapq.heappush",
"collections.defaultdict"
] | [((1585, 1602), 'collections.defaultdict', 'defaultdict', (['dict'], {}), '(dict)\n', (1596, 1602), False, 'from collections import defaultdict\n'), ((448, 493), 'heapq.heappush', 'heapq.heappush', (['heap_q', '(0, self.start_point)'], {}), '(heap_q, (0, self.start_point))\n', (462, 493), False, 'import heapq\n'), ((65... |
import os
import nibabel as nib
def list_scans(path = None):
return [os.path.join(path,scan) for scan in os.listdir(path) if scan.endswith(".nii")]
def normalize_HU(range, ct_type):
min_, max_ = range
for scan_id in list_scans(ct_type):
print(f"NORMALIZING {scan_id}")
scan_nii ... | [
"os.listdir",
"nibabel.save",
"nibabel.load",
"os.path.join",
"nibabel.Nifti1Image",
"os.system"
] | [((74, 98), 'os.path.join', 'os.path.join', (['path', 'scan'], {}), '(path, scan)\n', (86, 98), False, 'import os\n'), ((333, 350), 'nibabel.load', 'nib.load', (['scan_id'], {}), '(scan_id)\n', (341, 350), True, 'import nibabel as nib\n'), ((550, 601), 'nibabel.Nifti1Image', 'nib.Nifti1Image', (['scan_array'], {'affine... |
import re
import string
# 01234 + '-'|'.'|',' + 56789
NUM = re.compile(r"^\d*[-\./,]*\d+$")
PUNCT = set(string.punctuation)
PUNCT.add("--")
AFFIX = set(["n't", "'s", "'d", "'t"])
def process_lemma_line(line):
"""preprocess
:return lemma:
:return lemma_pos:
:return pos_tags:
"""
info = line.s... | [
"re.compile"
] | [((61, 94), 're.compile', 're.compile', (['"""^\\\\d*[-\\\\./,]*\\\\d+$"""'], {}), "('^\\\\d*[-\\\\./,]*\\\\d+$')\n", (71, 94), False, 'import re\n')] |
#!/usr/bin/env python
from __future__ import division
"""@package etddf
ROS interface script for delta tiering filter
Filter operates in ENU
"""
from etddf.delta_tier import DeltaTier
import rospy
import threading
from minau.msg import ControlStatus
from etddf.msg import Measurement, MeasurementPackage, NetworkEsti... | [
"rospy.logerr",
"geometry_msgs.msg.Vector3",
"rospy.init_node",
"numpy.array",
"copy.deepcopy",
"numpy.sin",
"etddf.delta_tier.DeltaTier",
"etddf.msg.PositionVelocity",
"nav_msgs.msg.Odometry",
"threading.Lock",
"rospy.Service",
"geometry_msgs.msg.Quaternion",
"rospy.spin",
"numpy.concaten... | [((448, 482), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'suppress': '(True)'}), '(suppress=True)\n', (467, 482), True, 'import numpy as np\n'), ((17586, 17613), 'rospy.get_param', 'rospy.get_param', (['"""~my_name"""'], {}), "('~my_name')\n", (17601, 17613), False, 'import rospy\n'), ((17629, 17663), 'rosp... |
#!/usr/bin/python
from utils import jsonclass
from dataclasses import dataclass
from typing import List
@jsonclass('JsonClass.json')
@dataclass
class Cleanup:
name: str
age: int
array: List[int]
if __name__ == '__main__':
# c1 = Cleanup(name='John', age=25, array=[12, 20])
# c1.save()
c2 = C... | [
"utils.jsonclass"
] | [((107, 134), 'utils.jsonclass', 'jsonclass', (['"""JsonClass.json"""'], {}), "('JsonClass.json')\n", (116, 134), False, 'from utils import jsonclass\n')] |
#!/usr/bin/env python
##############################################################################
# Copyright (c) 2017 Huawei Technologies Co.,Ltd and others.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompani... | [
"math.ceil",
"utils.infra_setup.runner.yardstick.yardstick_image_prepare",
"utils.infra_setup.runner.docker_env.docker_exec_cmd",
"os.path.splitext",
"time.sleep",
"uuid.uuid4",
"datetime.datetime.now",
"os.path.basename",
"json.load",
"utils.infra_setup.runner.yardstick.yardstick_command_parser",... | [((1959, 1985), 'os.path.basename', 'os.path.basename', (['__file__'], {}), '(__file__)\n', (1975, 1985), False, 'import os\n'), ((2010, 2036), 'os.path.splitext', 'os.path.splitext', (['testfile'], {}), '(testfile)\n', (2026, 2036), False, 'import os\n'), ((2125, 2138), 'Queue.Queue', 'Queue.Queue', ([], {}), '()\n', ... |
import numpy as np
from xwavecal.utils.correlate import correlate2d
def test_correlate2d():
arr = np.ones((5, 5))
arr[1:4, 1:4] = 2
sig = correlate2d(arr, 2 * np.ones((3, 3)), max_lag=1)
assert sig[2, 2] == np.max(sig) | [
"numpy.ones",
"numpy.max"
] | [((105, 120), 'numpy.ones', 'np.ones', (['(5, 5)'], {}), '((5, 5))\n', (112, 120), True, 'import numpy as np\n'), ((226, 237), 'numpy.max', 'np.max', (['sig'], {}), '(sig)\n', (232, 237), True, 'import numpy as np\n'), ((174, 189), 'numpy.ones', 'np.ones', (['(3, 3)'], {}), '((3, 3))\n', (181, 189), True, 'import numpy... |
from functools import wraps
import click
from pyfiglet import Figlet
def load_logo(f):
@wraps(f)
def wrapped(*args, **kwargs):
fig = Figlet(font='slant')
click.echo(click.style(fig.renderText("SAMIAM"), fg='green'))
r = f(*args, **kwargs)
return r
return wrapped | [
"pyfiglet.Figlet",
"functools.wraps"
] | [((95, 103), 'functools.wraps', 'wraps', (['f'], {}), '(f)\n', (100, 103), False, 'from functools import wraps\n'), ((152, 172), 'pyfiglet.Figlet', 'Figlet', ([], {'font': '"""slant"""'}), "(font='slant')\n", (158, 172), False, 'from pyfiglet import Figlet\n')] |
import glob
from pathlib import Path
from subprocess import check_output
PW_STORE_PATH = str(Path.home() / ".password-store")
def get_gpg_id(rel_p, mapped_gpg_ids):
# print(f'looking for gpg-id in {rel_p}')
if rel_p not in mapped_gpg_ids:
if len(rel_p) > 2:
return get_gpg_id(str(Path(rel... | [
"subprocess.check_output",
"pathlib.Path.home",
"glob.glob",
"pathlib.Path"
] | [((523, 579), 'glob.glob', 'glob.glob', (['f"""{PW_STORE_PATH}/**/.gpg-id"""'], {'recursive': '(True)'}), "(f'{PW_STORE_PATH}/**/.gpg-id', recursive=True)\n", (532, 579), False, 'import glob\n'), ((948, 1002), 'glob.glob', 'glob.glob', (['f"""{PW_STORE_PATH}/**/*.gpg"""'], {'recursive': '(True)'}), "(f'{PW_STORE_PATH}/... |
import os
from pathlib import Path
from appdirs import user_data_dir
class EnvManager:
"""Stashes environment variables in a file and
retrieves them in (a different process) with get_environ
with failover to os.environ
"""
app_env_dir = Path(user_data_dir("NEBULO"))
app_env = app_env_dir / ... | [
"appdirs.user_data_dir",
"os.remove"
] | [((267, 290), 'appdirs.user_data_dir', 'user_data_dir', (['"""NEBULO"""'], {}), "('NEBULO')\n", (280, 290), False, 'from appdirs import user_data_dir\n'), ((416, 439), 'os.remove', 'os.remove', (['self.app_env'], {}), '(self.app_env)\n', (425, 439), False, 'import os\n'), ((917, 940), 'os.remove', 'os.remove', (['self.... |
"""
Machine learning layer class definition module
"""
import numpy as np
import tensorflow as tf
rng = np.random.RandomState(1000)
class Dense(object):
"""
Dense layer class
"""
def __init__(self):
self.W = 0
self.b = 0
self.name_W = 'hoge'
self.name_b = 'hoge'
... | [
"numpy.random.RandomState"
] | [((106, 133), 'numpy.random.RandomState', 'np.random.RandomState', (['(1000)'], {}), '(1000)\n', (127, 133), True, 'import numpy as np\n')] |
"""Custom utilities for interacting with the Materials Project.
Mostly for getting and manipulating structures. With all of the function definitions and docstrings,
these are more verbose """
import fnmatch
import os
from pymatgen.ext.matproj import MPRester, Structure
from pymatgen.io.vasp.inputs import Incar, Posc... | [
"pymatgen.io.vasp.inputs.Incar.from_file",
"fireworks.LaunchPad.from_file",
"numpy.array",
"fireworks.LaunchPad.auto_load",
"os.walk",
"os.path.exists",
"re.split",
"pymatgen.io.vasp.outputs.Outcar",
"atomate.vasp.database.VaspCalcDb.from_db_file",
"dfttk.ftasks.ModifyKpoints",
"pymatgen.io.vasp... | [((5504, 5518), 'os.walk', 'os.walk', (['start'], {}), '(start)\n', (5511, 5518), False, 'import os\n'), ((24194, 24299), 'atomate.utils.utils.get_fws_and_tasks', 'get_fws_and_tasks', (['original_wf'], {'fw_name_constraint': 'fw_name_constraint', 'task_name_constraint': '"""RunVasp"""'}), "(original_wf, fw_name_constra... |
import re
import click
from matrix_connection import matrix_client
from tabulate import tabulate
@click.command()
@click.argument('pattern', required=False, type=str)
def list_rooms(pattern):
"""List room ids and keys."""
rooms = matrix_client().get_rooms()
data = [(rid, room.display_name)
f... | [
"tabulate.tabulate",
"click.argument",
"click.command",
"matrix_connection.matrix_client"
] | [((102, 117), 'click.command', 'click.command', ([], {}), '()\n', (115, 117), False, 'import click\n'), ((119, 170), 'click.argument', 'click.argument', (['"""pattern"""'], {'required': '(False)', 'type': 'str'}), "('pattern', required=False, type=str)\n", (133, 170), False, 'import click\n'), ((483, 534), 'tabulate.ta... |
import datetime
import json
import os
import random
import colorama
import discord
import requests
from dotenv import load_dotenv
colorama.init()
load_dotenv()
client = discord.Client()
TOKEN = os.environ.get("TOKEN")
# list of games which will be the playing status of the bot
lista_giochi_bot ... | [
"discord.Game",
"os.environ.get",
"discord.File",
"requests.get",
"dotenv.load_dotenv",
"datetime.datetime.now",
"random.choices",
"discord.Client",
"random.randint",
"colorama.init"
] | [((142, 157), 'colorama.init', 'colorama.init', ([], {}), '()\n', (155, 157), False, 'import colorama\n'), ((161, 174), 'dotenv.load_dotenv', 'load_dotenv', ([], {}), '()\n', (172, 174), False, 'from dotenv import load_dotenv\n'), ((187, 203), 'discord.Client', 'discord.Client', ([], {}), '()\n', (201, 203), False, 'im... |
import imageProcess
import numpy
from skimage.measure import label, regionprops
def areaFilter(bImg):
labelImg = label(bImg)
numLabel = labelImg.max()
props = regionprops(labelImg)
bImg[:] = False
areaList = []
for i in range(numLabel):
areaList.append(props[i].area)
areaList =... | [
"numpy.logical_or",
"skimage.measure.label",
"skimage.measure.regionprops"
] | [((118, 129), 'skimage.measure.label', 'label', (['bImg'], {}), '(bImg)\n', (123, 129), False, 'from skimage.measure import label, regionprops\n'), ((172, 193), 'skimage.measure.regionprops', 'regionprops', (['labelImg'], {}), '(labelImg)\n', (183, 193), False, 'from skimage.measure import label, regionprops\n'), ((549... |
#! /usr/bin/env python
# coding: utf-8
"""
This is Ros node for pwm control rc car
"""
import RPi.GPIO as GPIO
import pigpio
import time
import numpy as np
import math
import tf
from enum import Enum
import rospy
from geometry_msgs.msg import Twist, TwistStamped, PoseStamped
from ackermann_msgs.msg import AckermannDr... | [
"numpy.clip",
"rospy.init_node",
"time.sleep",
"math.cos",
"numpy.array",
"rospy.Rate",
"rc_car_msgs.msg.CarPwmContol",
"math.atan",
"RPi.GPIO.cleanup",
"geometry_msgs.msg.TwistStamped",
"rospy.Service",
"dynamic_reconfigure.server.Server",
"numpy.dot",
"pigpio.pi",
"rospy.Subscriber",
... | [((1335, 1340), 'PID.PID', 'PID', ([], {}), '()\n', (1338, 1340), False, 'from PID import PID\n'), ((1893, 1904), 'pigpio.pi', 'pigpio.pi', ([], {}), '()\n', (1902, 1904), False, 'import pigpio\n'), ((2139, 2153), 'geometry_msgs.msg.TwistStamped', 'TwistStamped', ([], {}), '()\n', (2151, 2153), False, 'from geometry_ms... |
import matplotlib
# no X11 server ... must be run first
# https://github.com/matplotlib/matplotlib/issues/3466/
matplotlib.use('Agg')
import matplotlib.pylab as plt
# import ccrs for map projections
import cartopy.crs as ccrs
from netCDF4 import Dataset
import os
DATADIR = os.path.join(os.path.abspath(os.path.dirname... | [
"matplotlib.pylab.figure",
"matplotlib.use",
"netCDF4.Dataset",
"os.path.join",
"cartopy.crs.PlateCarree",
"matplotlib.pylab.colorbar",
"os.path.dirname",
"matplotlib.pylab.contourf",
"matplotlib.pylab.close"
] | [((112, 133), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (126, 133), False, 'import matplotlib\n'), ((362, 401), 'os.path.join', 'os.path.join', (['DATADIR', '"""air.mon.ltm.nc"""'], {}), "(DATADIR, 'air.mon.ltm.nc')\n", (374, 401), False, 'import os\n'), ((658, 675), 'netCDF4.Dataset', 'Data... |
from setuptools import setup
# TODO use versioneer
setup(
name='sslib',
version="0.9.0",
packages=['sslib'],
include_package_data=False,
install_requires=['nlzss11']
)
| [
"setuptools.setup"
] | [((53, 171), 'setuptools.setup', 'setup', ([], {'name': '"""sslib"""', 'version': '"""0.9.0"""', 'packages': "['sslib']", 'include_package_data': '(False)', 'install_requires': "['nlzss11']"}), "(name='sslib', version='0.9.0', packages=['sslib'],\n include_package_data=False, install_requires=['nlzss11'])\n", (58, 1... |
"""mplcyberpunk - A new Python package"""
__version__ = '0.1.0'
__author__ = '<NAME> <<EMAIL>>'
__all__ = []
import matplotlib as mpl
import pkg_resources
from .core import add_glow_effects, make_lines_glow, add_underglow
# register the included stylesheet in the mpl style library
data_path = pkg_resources.resourc... | [
"matplotlib.style.core.update_nested_dict",
"matplotlib.style.core.read_style_directory",
"pkg_resources.resource_filename"
] | [((299, 355), 'pkg_resources.resource_filename', 'pkg_resources.resource_filename', (['"""mplcyberpunk"""', '"""data/"""'], {}), "('mplcyberpunk', 'data/')\n", (330, 355), False, 'import pkg_resources\n'), ((380, 426), 'matplotlib.style.core.read_style_directory', 'mpl.style.core.read_style_directory', (['data_path'], ... |
#! /usr/bin/env python3
# slurm-reporter reads the database table export (tsv) of the slurm_jobs table
# and groups all jobs by the full hour and
#
# export slurm data: echo "select * from mycluster_job_table;" | mysql slurm_acct_db > mycluster_job_table.tsv
#
# slurm-reporter dirkpetersen / Apr 2020
#
import sys, o... | [
"logging.getLogger",
"os.path.exists",
"logging.StreamHandler",
"pandas.read_csv",
"argparse.ArgumentParser",
"logging.Formatter",
"pandas.to_datetime",
"os.path.basename",
"socket.gethostname",
"logging.handlers.SysLogHandler"
] | [((793, 813), 'socket.gethostname', 'socket.gethostname', ([], {}), '()\n', (811, 813), False, 'import sys, os, argparse, socket, pandas\n'), ((1084, 1137), 'pandas.read_csv', 'pandas.read_csv', (['args.tsvfile'], {'sep': '"""\t"""', 'low_memory': '(0)'}), "(args.tsvfile, sep='\\t', low_memory=0)\n", (1099, 1137), Fals... |
"""module of classes holding models, pretrained or otherwise. The
SVMModel and LogisticModel classes do not admit any hyperparameter
changes, so any change requires using the basic MnistModel class.
"""
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
fr... | [
"sklearn.svm.SVC",
"sklearn.linear_model.LogisticRegression",
"sklearn.metrics.accuracy_score",
"typing.TypeVar"
] | [((383, 399), 'typing.TypeVar', 'TypeVar', (['"""Model"""'], {}), "('Model')\n", (390, 399), False, 'from typing import TypeVar\n'), ((1809, 1839), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['y_test', 'y_pred'], {}), '(y_test, y_pred)\n', (1823, 1839), False, 'from sklearn.metrics import accuracy_score\n'), ... |
from django.db import models
from django.contrib.auth.models import AbstractUser, AbstractBaseUser
from django.db.models.signals import post_save
from django.core.validators import RegexValidator
# Create your models here.
class Companies(models.Model):
company_name = models.CharField (max_length=50, unique=True)
... | [
"django.core.validators.RegexValidator",
"django.db.models.ImageField",
"django.db.models.CharField",
"django.db.models.ForeignKey"
] | [((273, 317), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(50)', 'unique': '(True)'}), '(max_length=50, unique=True)\n', (289, 317), False, 'from django.db import models\n'), ((420, 514), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Companies'], {'on_delete': 'models.CASCADE', 'blan... |
import os
import unittest
from scrapy.http import TextResponse, Request
from pdl_scraper.spiders.pdfurl_spider import PdfUrlSpider
class TestPdfUrlSpider(unittest.TestCase):
def setUp(self):
self.spider = PdfUrlSpider()
def test_find_pdfurl(self):
codigos = (
'00001',
... | [
"scrapy.http.TextResponse",
"scrapy.http.Request",
"os.path.join",
"os.path.realpath",
"pdl_scraper.spiders.pdfurl_spider.PdfUrlSpider"
] | [((2813, 2829), 'scrapy.http.Request', 'Request', ([], {'url': 'url'}), '(url=url)\n', (2820, 2829), False, 'from scrapy.http import TextResponse, Request\n'), ((3117, 3174), 'scrapy.http.TextResponse', 'TextResponse', ([], {'url': 'url', 'request': 'request', 'body': 'file_content'}), '(url=url, request=request, body=... |
from django.test import TestCase
from accounts.models import CustomUser
from analyser.models import SentenceAnalysis, SubmissionAnalysis, CommentAnalysis, TagMeAnalysis, TagMeSentenceAnalysis
from analyser.tasks import one_time_schedules, polarity_analysis_submission_task, polarity_analysis_comment_task, tagme_analysis... | [
"analyser.tasks.polarity_analysis_submission_task",
"analyser.tasks.polarity_analysis_comment_task",
"django_q.models.Schedule.objects.get",
"analyser.tasks.one_time_schedules",
"analyser.tasks.tagme_analysis_sentences_task"
] | [((701, 721), 'analyser.tasks.one_time_schedules', 'one_time_schedules', ([], {}), '()\n', (719, 721), False, 'from analyser.tasks import one_time_schedules, polarity_analysis_submission_task, polarity_analysis_comment_task, tagme_analysis_sentences_task\n'), ((742, 801), 'django_q.models.Schedule.objects.get', 'Schedu... |
"""
================================================================================
Utilities for handling data types and transformations
================================================================================
**<NAME>**
4/18/2018
"""
#########################################################################... | [
"pyUSID.dtype_utils.flatten_complex_to_real",
"numpy.random.rand",
"pyUSID.dtype_utils.is_complex_dtype",
"pyUSID.dtype_utils.contains_integers",
"os.remove",
"pyUSID.dtype_utils.stack_real_to_complex",
"os.path.exists",
"numpy.random.random",
"subprocess.call",
"warnings.warn",
"pyUSID.dtype_ut... | [((5144, 5233), 'numpy.dtype', 'np.dtype', (["{'names': ['r', 'g', 'b'], 'formats': [np.float32, np.uint16, np.float64]}"], {}), "({'names': ['r', 'g', 'b'], 'formats': [np.float32, np.uint16, np.\n float64]})\n", (5152, 5233), True, 'import numpy as np\n'), ((5759, 5813), 'pyUSID.dtype_utils.get_compound_sub_dtypes... |