code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
# -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
"""
import pytest
import os
import tarfile
from pathlib import Path
import nibabel as nib
import numpy as np
from ....tests.resource import setup as setuptestresources
from .... | [
"nipype.interfaces.ants.ApplyTransforms",
"numpy.abs",
"tarfile.open",
"numpy.isclose",
"nibabel.load",
"pathlib.Path",
"templateflow.api.get",
"nipype.interfaces.ants.ResampleImageBySpacing",
"pytest.mark.parametrize",
"nipype.interfaces.fsl.MultipleRegressDesign",
"pytest.fixture",
"pytest.m... | [((683, 713), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (697, 713), False, 'import pytest\n'), ((1566, 1596), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (1580, 1596), False, 'import pytest\n'), ((1996, 2026), 'pytest.fixtur... |
from prev_ob_models.utils import RunInClassDirectory, IsolatedCell
class MC(IsolatedCell):
def __init__(self):
with RunInClassDirectory(MC):
from neuron import h,gui
h.xopen("mitral.hoc")
h.xopen("memb.hoc")
h.celsius = 23
self.h = ... | [
"neuron.h.cvode_active",
"neuron.h.xopen",
"prev_ob_models.utils.RunInClassDirectory"
] | [((133, 156), 'prev_ob_models.utils.RunInClassDirectory', 'RunInClassDirectory', (['MC'], {}), '(MC)\n', (152, 156), False, 'from prev_ob_models.utils import RunInClassDirectory, IsolatedCell\n'), ((211, 232), 'neuron.h.xopen', 'h.xopen', (['"""mitral.hoc"""'], {}), "('mitral.hoc')\n", (218, 232), False, 'from neuron i... |
from __future__ import annotations
import mmap
import threading
from enum import Enum
from itertools import product
from pathlib import Path
from typing import (
TYPE_CHECKING,
Optional,
Sequence,
Set,
Sized,
SupportsInt,
Union,
cast,
overload,
)
import numpy as np
from ._util imp... | [
"numpy.prod",
"numpy.hstack",
"pathlib.Path",
"numpy.ravel_multi_index",
"dask.array.map_blocks",
"threading.RLock",
"itertools.product",
"resource_backed_dask_array.ResourceBackedDaskArray.from_array",
"xarray.DataArray",
"numpy.dtype",
"typing.cast",
"numpy.arange"
] | [((1978, 1995), 'threading.RLock', 'threading.RLock', ([], {}), '()\n', (1993, 1995), False, 'import threading\n'), ((3150, 3167), 'threading.RLock', 'threading.RLock', ([], {}), '()\n', (3165, 3167), False, 'import threading\n'), ((6028, 6061), 'typing.cast', 'cast', (['Attributes', 'self.attributes'], {}), '(Attribut... |
# Copyright 2015-2016 Mirantis, Inc
#
# 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... | [
"argparse.FileType",
"argparse.ArgumentParser"
] | [((745, 922), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'prog': 'config.PROJECT_NAME', 'formatter_class': 'argparse.RawTextHelpFormatter', 'description': 'config.PROJECT_DESCRIPTION', 'epilog': 'config.RUN_DESCRIPTION'}), '(prog=config.PROJECT_NAME, formatter_class=argparse.\n RawTextHelpFormatter,... |
import tensorflow as tf
from dataset.create_kitti_tfrecords import get_dataset
from dataset import input_generator
import model_options
import scipy.misc as smi
import numpy as np
import cv2
slim = tf.contrib.slim
prefetch_queue = slim.prefetch_queue
# with tf.Graph().as_default():
# dataset = get_dataset(m... | [
"tensorflow.InteractiveSession",
"tensorflow.equal",
"dataset.create_kitti_tfrecords.get_dataset",
"tensorflow.train.Coordinator",
"cv2.destroyWindow",
"dataset.input_generator.get",
"tensorflow.train.start_queue_runners",
"tensorflow.constant",
"cv2.waitKey"
] | [((860, 883), 'tensorflow.InteractiveSession', 'tf.InteractiveSession', ([], {}), '()\n', (881, 883), True, 'import tensorflow as tf\n'), ((995, 1016), 'tensorflow.constant', 'tf.constant', (['"""campus"""'], {}), "('campus')\n", (1006, 1016), True, 'import tensorflow as tf\n'), ((1026, 1048), 'tensorflow.constant', 't... |
#!/usr/bin/env python3
from cache_tools import CachedBaseHttpSession
# TODO: Schema checking
class LunaSource:
def __init__(self, api_url: str, api_key: str):
self._session = CachedBaseHttpSession("LUNA", api_url)
self._session.headers.update({
"Authorization": api_key
})
... | [
"cache_tools.CachedBaseHttpSession"
] | [((191, 229), 'cache_tools.CachedBaseHttpSession', 'CachedBaseHttpSession', (['"""LUNA"""', 'api_url'], {}), "('LUNA', api_url)\n", (212, 229), False, 'from cache_tools import CachedBaseHttpSession\n')] |
import math
class UintN:
def __init__(self, number, n):
self.n = n
assert 0 <= number and number < 2 ** self.n
self.number = number
def bits(self):
number = self.number
bits = [None] * self.n
for i in range(self.n):
bits[self.n-1-i] = bool(number % ... | [
"math.floor"
] | [((348, 370), 'math.floor', 'math.floor', (['(number / 2)'], {}), '(number / 2)\n', (358, 370), False, 'import math\n')] |
import asyncio
import logging
import re
import socket
from dataclasses import dataclass, field
from typing import Any, Dict, Optional, Union, Coroutine, Callable
import aiohttp
from aiven.monitor import Check, CheckResult
logger = logging.getLogger(__name__)
@dataclass
class HTTPCheckResult(CheckResult):
stat... | [
"logging.getLogger",
"re.compile",
"aiohttp.TraceConfig",
"aiohttp.ClientTimeout",
"asyncio.sleep",
"aiohttp.TCPConnector",
"asyncio.get_event_loop",
"dataclasses.field"
] | [((235, 262), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (252, 262), False, 'import logging\n'), ((955, 976), 'aiohttp.TraceConfig', 'aiohttp.TraceConfig', ([], {}), '()\n', (974, 976), False, 'import aiohttp\n'), ((340, 359), 'dataclasses.field', 'field', ([], {'default': 'None'}), '... |
import pytest
import inspect
import starstar
def test_divide():
def b(a=None, b=None, c=None):
return 'b', a, b, c
def c(d=None, e=None, f=None, c=None):
return 'c', d, e, f, c
kw = dict(a='a', e='e')
assert starstar.divide(kw, b, c) == [{'a': 'a'}, {'e': 'e'}]
kw = dict(a='a',... | [
"starstar.filtered",
"starstar.unmatched_kw",
"inspect.signature",
"starstar.wraps",
"inspect.cleandoc",
"starstar.traceto",
"starstar.get_args",
"pytest.raises",
"starstar.nestdoc",
"starstar.filter_kw",
"starstar.divide",
"starstar.signature",
"docstring_parser.parse",
"starstar.kw2id",
... | [((1639, 1659), 'inspect.signature', 'inspect.signature', (['b'], {}), '(b)\n', (1656, 1659), False, 'import inspect\n'), ((1672, 1693), 'starstar.signature', 'starstar.signature', (['b'], {}), '(b)\n', (1690, 1693), False, 'import starstar\n'), ((2105, 2127), 'starstar.traceto', 'starstar.traceto', (['b', 'c'], {}), '... |
import pandas as pd
#https://archive.ics.uci.edu/ml/machine-learning-databases/mushroom/agaricus-lepiota.names
#
# TODO: Load up the mushroom dataset into dataframe 'X'
# Verify you did it properly.
# Indices shouldn't be doubled.
# Header information is on the dataset's website at the UCI ML Repo
# Check NA Encod... | [
"pandas.isnull",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"sklearn.tree.DecisionTreeClassifier",
"sklearn.tree.export_graphviz",
"pandas.get_dummies"
] | [((353, 411), 'pandas.read_csv', 'pd.read_csv', (['"""Datasets/agaricus-lepiota.data"""'], {'header': 'None'}), "('Datasets/agaricus-lepiota.data', header=None)\n", (364, 411), True, 'import pandas as pd\n'), ((1686, 1703), 'pandas.get_dummies', 'pd.get_dummies', (['X'], {}), '(X)\n', (1700, 1703), True, 'import pandas... |
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | [
"logging.getLogger",
"ray.tune.suggest.bayesopt.BayesOptSearch",
"tensorflow.unstack",
"itertools.chain",
"cifar10.Cifar10DataSet",
"tensorflow.logging.set_verbosity",
"tensorflow.estimator.EstimatorSpec",
"tensorflow.gradients",
"tensorflow.group",
"numpy.array",
"six.moves.xrange",
"tensorfl... | [((1608, 1650), 'tensorflow.logging.set_verbosity', 'tf.logging.set_verbosity', (['tf.logging.ERROR'], {}), '(tf.logging.ERROR)\n', (1632, 1650), True, 'import tensorflow as tf\n'), ((1891, 1916), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1914, 1916), False, 'import argparse\n'), ((16042,... |
"""add org_name
Revision ID: 0647beeadb7d
Revises: <PASSWORD>
Create Date: 2022-05-12 19:35:03.484368
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "0647beeadb7d"
down_revision = "<PASSWORD>"
branch_labels = None
depends_on = None
def upgrade():
op.add_... | [
"sqlalchemy.text",
"alembic.op.drop_column",
"sqlalchemy.String",
"alembic.op.drop_index",
"alembic.op.create_index"
] | [((417, 487), 'alembic.op.drop_index', 'op.drop_index', (['"""projects_name_owner_cluster_uq"""'], {'table_name': '"""projects"""'}), "('projects_name_owner_cluster_uq', table_name='projects')\n", (430, 487), False, 'from alembic import op\n'), ((703, 827), 'alembic.op.create_index', 'op.create_index', (['"""projects_n... |
import unittest
from fastNLP import Vocabulary
from fastNLP.embeddings import BertEmbedding, BertWordPieceEncoder
import torch
import os
from fastNLP import DataSet
@unittest.skipIf('TRAVIS' in os.environ, "Skip in travis")
class TestDownload(unittest.TestCase):
def test_download(self):
# import os
... | [
"torch.LongTensor",
"unittest.skipIf",
"fastNLP.embeddings.BertEmbedding",
"fastNLP.embeddings.BertWordPieceEncoder",
"fastNLP.Vocabulary"
] | [((168, 225), 'unittest.skipIf', 'unittest.skipIf', (["('TRAVIS' in os.environ)", '"""Skip in travis"""'], {}), "('TRAVIS' in os.environ, 'Skip in travis')\n", (183, 225), False, 'import unittest\n'), ((400, 444), 'fastNLP.embeddings.BertEmbedding', 'BertEmbedding', (['vocab'], {'model_dir_or_name': '"""en"""'}), "(voc... |
import torch
import cv2 as cv
import numpy as np
from sklearn.neighbors import NearestNeighbors
from .model_utils import spread_feature
def optimize_image_mask(image_mask, sp_image, nK=4, th=1e-2):
mask_pts = image_mask.reshape(-1)
xyz_pts = sp_image.reshape(-1, 3)
xyz_pts = xyz_pts[mask_pts > 0.5, :]
... | [
"cv2.Laplacian",
"numpy.ones",
"torch.from_numpy",
"cv2.morphologyEx",
"numpy.zeros",
"numpy.sum",
"sklearn.neighbors.NearestNeighbors",
"cv2.resize",
"cv2.getStructuringElement"
] | [((1330, 1503), 'cv2.resize', 'cv.resize', (['image_learned_uv'], {'dsize': '(image_resize_factor * image_learned_uv.shape[0], image_resize_factor *\n image_learned_uv.shape[1])', 'interpolation': 'cv.INTER_LINEAR'}), '(image_learned_uv, dsize=(image_resize_factor * image_learned_uv.\n shape[0], image_resize_fact... |
from contextlib import closing
from .helper import create_journal_group_name_lookup, load_delimited_data, save_delimited_data
from mysql.connector import connect
from .settings import get_config
SELECT_JOURNAL_DATA_BY_ID = 'SELECT nlmid, medline_ta from journals WHERE id = %(id)s'
SELECT_ARTICLE_DATA_BY_ID = 'SELECT ... | [
"mysql.connector.connect"
] | [((591, 611), 'mysql.connector.connect', 'connect', ([], {}), '(**db_config)\n', (598, 611), False, 'from mysql.connector import connect\n')] |
# -*- coding: utf-8 -*-
from django.contrib import admin
from django.contrib.contenttypes.admin import GenericTabularInline
from django.utils.html import format_html, escape, mark_safe
from mptt.admin import DraggableMPTTAdmin
from .models import Comment, RootHeader
from attachment.admin import AttachmentInline, Attac... | [
"django.utils.html.format_html",
"django.contrib.admin.site.register",
"django.utils.html.escape",
"django.utils.html.mark_safe"
] | [((3706, 3748), 'django.contrib.admin.site.register', 'admin.site.register', (['Comment', 'CommentAdmin'], {}), '(Comment, CommentAdmin)\n', (3725, 3748), False, 'from django.contrib import admin\n'), ((3749, 3797), 'django.contrib.admin.site.register', 'admin.site.register', (['RootHeader', 'RootHeaderAdmin'], {}), '(... |
import giphypop
import requests
from os import path, makedirs
from PIL import Image, ImagePalette
import io
import argparse
import json
import time
from Utils import init_dirs
limit = 100
giphy = giphypop.Giphy(api_key='')
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--src', typ... | [
"argparse.ArgumentParser",
"os.makedirs",
"PIL.Image.new",
"os.path.join",
"Utils.init_dirs",
"os.path.splitext",
"io.BytesIO",
"os.path.isfile",
"requests.get",
"os.path.isdir",
"json.load",
"giphypop.Giphy",
"time.time",
"json.dump"
] | [((198, 224), 'giphypop.Giphy', 'giphypop.Giphy', ([], {'api_key': '""""""'}), "(api_key='')\n", (212, 224), False, 'import giphypop\n'), ((2024, 2035), 'Utils.init_dirs', 'init_dirs', ([], {}), '()\n', (2033, 2035), False, 'from Utils import init_dirs\n'), ((2260, 2301), 'os.path.join', 'path.join', (['logdir', "('%s-... |
import logging
import os
import numpy as np
import torch
if torch.cuda.is_available():
torch.backends.cudnn.enabled = True
torch.backends.cudnn.benchmark = True
torch.backends.cudnn.deterministic = True
device = torch.device('cuda')
else:
device = torch.device('cpu')
def _patch_noise_extend_to_i... | [
"numpy.clip",
"logging.getLogger",
"os.path.exists",
"logging.StreamHandler",
"numpy.sqrt",
"os.makedirs",
"logging.Formatter",
"torch.load",
"numpy.zeros",
"torch.cuda.is_available",
"logging.FileHandler",
"numpy.random.randint",
"torch.save",
"numpy.int",
"torch.zeros",
"torch.device... | [((62, 87), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (85, 87), False, 'import torch\n'), ((230, 250), 'torch.device', 'torch.device', (['"""cuda"""'], {}), "('cuda')\n", (242, 250), False, 'import torch\n'), ((270, 289), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (2... |
import pandas as pd
from sklearn.datasets import load_boston
boston_housing = load_boston()
columns_names = boston_housing.feature_names
y = boston_housing.target
X = boston_housing.data
# Splitting features and target datasets into: train and test
from sklearn.model_selection import train_test_split
X_train, X_test,... | [
"sklearn.model_selection.train_test_split",
"sklearn.datasets.load_boston",
"sklearn.linear_model.LinearRegression",
"pandas.DataFrame"
] | [((79, 92), 'sklearn.datasets.load_boston', 'load_boston', ([], {}), '()\n', (90, 92), False, 'from sklearn.datasets import load_boston\n'), ((339, 377), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': '(0.35)'}), '(X, y, test_size=0.35)\n', (355, 377), False, 'from sklearn.mo... |
from . import builder, config, exceptions, generator, logging
import click
import os
import sys
__all__ = []
LOG = logging.getLogger(__name__)
@click.group()
@click.option('-v', '--verbose', is_flag=True)
def promenade(*, verbose):
if _debug():
verbose = True
logging.setup(verbose=verbose)
@promen... | [
"click.group",
"click.option",
"click.File",
"os.environ.get",
"click.Path",
"sys.exit"
] | [((148, 161), 'click.group', 'click.group', ([], {}), '()\n', (159, 161), False, 'import click\n'), ((163, 208), 'click.option', 'click.option', (['"""-v"""', '"""--verbose"""'], {'is_flag': '(True)'}), "('-v', '--verbose', is_flag=True)\n", (175, 208), False, 'import click\n'), ((613, 691), 'click.option', 'click.opti... |
#!/usr/bin/env python
import PySimpleGUI as sg
from os import system
from time import sleep
from threading import Thread
# Read Saved Theme
with open("theme.txt") as theme:
theme = theme.read()
# Variables
timer_goal = 5
timer = 0
start_loops = True
clicks = 0
running = True
final = 0
cps = 0
round_finished =... | [
"PySimpleGUI.Menu",
"PySimpleGUI.Column",
"PySimpleGUI.Text",
"time.sleep",
"PySimpleGUI.Button",
"PySimpleGUI.theme",
"threading.Thread",
"os.system",
"PySimpleGUI.Window"
] | [((407, 422), 'PySimpleGUI.theme', 'sg.theme', (['theme'], {}), '(theme)\n', (415, 422), True, 'import PySimpleGUI as sg\n'), ((2600, 2700), 'PySimpleGUI.Window', 'sg.Window', (['"""G-CPS"""', 'layout'], {'size': '(1000, 375)', 'finalize': '(True)', 'grab_anywhere': '(True)', 'icon': '"""ico.ico"""'}), "('G-CPS', layou... |
import pylab
import matplotlib as mpl
import numpy as np
import matplotlib.colors as colors
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
from colormap import cmap_builder, test_cmap # for _build_colormap()
# --------------------------------------... | [
"matplotlib.pyplot.imshow",
"colormap.cmap_builder",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.colorbar",
"matplotlib.pyplot.clf",
"matplotlib.pyplot.axis",
"numpy.linspace",
"matplotlib.pyplot.title",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show"
] | [((769, 808), 'colormap.cmap_builder', 'cmap_builder', (['"""blue"""', '"""orange"""', '"""green"""'], {}), "('blue', 'orange', 'green')\n", (781, 808), False, 'from colormap import cmap_builder, test_cmap\n'), ((1019, 1040), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'ncols': '(2)'}), '(ncols=2)\n', (1031, 10... |
from django.contrib import admin
from django import forms
from import_export import fields,resources
from import_export.admin import ImportExportModelAdmin,ImportExportActionModelAdmin
from import_export.widgets import ForeignKeyWidget
from .models import Customer
class CustomerResource(resources.ModelResource):
... | [
"django.contrib.admin.site.register"
] | [((834, 878), 'django.contrib.admin.site.register', 'admin.site.register', (['Customer', 'CustomerAdmin'], {}), '(Customer, CustomerAdmin)\n', (853, 878), False, 'from django.contrib import admin\n')] |
import os
import sys
import argparse
import logging
import datetime as dt
from fishnet_generator import fishnet_func
from hru_parameters import hru_parameters
from dem_parameters import dem_parameters
from dem_2_streams import flow_parameters
from crt_fill_parameters import crt_fill_parameters
from stream_parameters i... | [
"prism_800m_normals.prism_800m_parameters",
"crt_fill_parameters.crt_fill_parameters",
"dem_2_streams.flow_parameters",
"prms_template_fill.prms_template_fill",
"argparse.Namespace",
"fishnet_generator.fishnet_func",
"logging.info",
"veg_parameters.veg_parameters",
"stream_parameters.stream_paramete... | [((733, 866), 'argparse.Namespace', 'argparse.Namespace', ([], {'ini': '"""C:\\\\Users\\\\CNA372\\\\gsflow-arcpy-master\\\\uyws_multibasin\\\\uyws_parameters.ini"""', 'overwrite': 'overwrite'}), "(ini=\n 'C:\\\\Users\\\\CNA372\\\\gsflow-arcpy-master\\\\uyws_multibasin\\\\uyws_parameters.ini'\n , overwrite=overwri... |
from absl import app, flags, logging
from absl.flags import FLAGS
import tensorflow as tf
import numpy as np
import cv2
from tensorflow.keras.callbacks import (
ReduceLROnPlateau,
EarlyStopping,
ModelCheckpoint,
TensorBoard
)
from yolov3_tf2.models import (
YoloV3, YoloV3Tiny, YoloLoss... | [
"yolov3_tf2.dataset.load_fake_dataset",
"yolov3_tf2.models.YoloLoss",
"tensorflow.reduce_sum",
"yolov3_tf2.utils.freeze_all",
"tensorflow.GradientTape",
"tensorflow.keras.callbacks.EarlyStopping",
"yolov3_tf2.dataset.load_tfrecord_dataset",
"yolov3_tf2.models.YoloV3",
"tensorflow.keras.callbacks.Red... | [((876, 927), 'tensorflow.config.experimental.list_physical_devices', 'tf.config.experimental.list_physical_devices', (['"""GPU"""'], {}), "('GPU')\n", (920, 927), True, 'import tensorflow as tf\n'), ((4067, 4115), 'tensorflow.keras.optimizers.Adam', 'tf.keras.optimizers.Adam', ([], {'lr': 'FLAGS.learning_rate'}), '(lr... |
import argparse
import json
import subprocess
import sys
from eks import AwsCluster
from shell import run_out, run_in
from utils import reduce_subnets, get_current_region
DEFAULT_CIDR_BLOCK = "192.168.0.0/16"
def create_cluster(data):
run_in("eksctl", "create", "cluster", "-f", "-", **data)
def generate_clust... | [
"shell.run_out",
"argparse.ArgumentParser",
"subprocess.check_call",
"json.dump",
"utils.get_current_region",
"shell.run_in",
"utils.reduce_subnets",
"eks.AwsCluster"
] | [((243, 299), 'shell.run_in', 'run_in', (['"""eksctl"""', '"""create"""', '"""cluster"""', '"""-f"""', '"""-"""'], {}), "('eksctl', 'create', 'cluster', '-f', '-', **data)\n", (249, 299), False, 'from shell import run_out, run_in\n'), ((1762, 1969), 'shell.run_out', 'run_out', (['"""aws"""', '"""ec2"""', '"""describe-s... |
import os
from kavik.settings import BASE_DIR
DEBUG = True
TEMPLATE_DEBUG = DEBUG
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []
SECRET_KEY = ''
DATABASES = {
'default': {
'ENGINE':... | [
"os.path.join"
] | [((367, 403), 'os.path.join', 'os.path.join', (['BASE_DIR', '"""db.sqlite3"""'], {}), "(BASE_DIR, 'db.sqlite3')\n", (379, 403), False, 'import os\n')] |
import random as _random
import unittest as _unittest
import numpy as _np
import torch as _torch
import torchutils as _tu
class _TestUtils(_unittest.TestCase):
def test_set_random_seed(self):
# Set new seed and verify.
seed = _random.randint(1, 1000)
_tu.set_random_seed(seed)
np... | [
"numpy.random.get_state",
"torch.initial_seed",
"torch.cuda.is_available",
"torch.cuda.initial_seed",
"unittest.main",
"random.randint",
"torchutils.set_random_seed"
] | [((676, 692), 'unittest.main', '_unittest.main', ([], {}), '()\n', (690, 692), True, 'import unittest as _unittest\n'), ((251, 275), 'random.randint', '_random.randint', (['(1)', '(1000)'], {}), '(1, 1000)\n', (266, 275), True, 'import random as _random\n'), ((284, 309), 'torchutils.set_random_seed', '_tu.set_random_se... |
from os import getcwd
from os.path import join
from sys import exit
from docker_tests.test_utils import CurrentTest, test_command
if __name__ == '__main__':
# install expac-git
test_command("git clone https://aur.archlinux.org/expac-git.git")
test_command("makepkg -si --needed --noconfirm", dir_to_execute... | [
"docker_tests.test_utils.test_command",
"os.getcwd",
"sys.exit"
] | [((187, 252), 'docker_tests.test_utils.test_command', 'test_command', (['"""git clone https://aur.archlinux.org/expac-git.git"""'], {}), "('git clone https://aur.archlinux.org/expac-git.git')\n", (199, 252), False, 'from docker_tests.test_utils import CurrentTest, test_command\n'), ((354, 387), 'docker_tests.test_utils... |
from __future__ import print_function
from __future__ import absolute_import
import tensorflow as tf
def encoder_decoder_input_placeholder(encoder_input_range, decoder_input_range):
encoder_inputs = []
decoder_inputs = []
for i in xrange(encoder_input_range):
encoder_inputs.append(tf.placeholder(tf.int32, shape... | [
"tensorflow.get_variable",
"tensorflow.transpose",
"tensorflow.Variable",
"tensorflow.nn.seq2seq.embedding_attention_seq2seq",
"tensorflow.reshape",
"tensorflow.nn.sampled_softmax_loss",
"tensorflow.cast"
] | [((1926, 1957), 'tensorflow.Variable', 'tf.Variable', (['(0)'], {'trainable': '(False)'}), '(0, trainable=False)\n', (1937, 1957), True, 'import tensorflow as tf\n'), ((1066, 1118), 'tensorflow.get_variable', 'tf.get_variable', (['"""proj_w"""', '[size, target_vocab_size]'], {}), "('proj_w', [size, target_vocab_size])\... |
OntCversion = '2.0.0'
from ontology.interop.Ontology.Contract import Migrate
# from ontology.interop.Ontology.Contract import Destroy
from ontology.interop.System.Runtime import Notify
from ontology.interop.System.Storage import Put, GetContext, Get
KEY = "KEY"
NAME = "SecondName"
def Main(operation, args):
# if ... | [
"ontology.interop.System.Storage.GetContext",
"ontology.interop.Ontology.Contract.Migrate",
"ontology.interop.System.Runtime.Notify"
] | [((964, 1036), 'ontology.interop.Ontology.Contract.Migrate', 'Migrate', (['code', '(True)', '"""name"""', '"""version"""', '"""author"""', '"""email"""', '"""description"""'], {}), "(code, True, 'name', 'version', 'author', 'email', 'description')\n", (971, 1036), False, 'from ontology.interop.Ontology.Contract import ... |
from bot import botToken
import unittest
def test_bot():
assert str(botToken(token_file='test_bot.token').getToken(
)) == '1111111111:TeStTaPiToKeN', 'Loading token from file is wrong'
| [
"bot.botToken"
] | [((74, 111), 'bot.botToken', 'botToken', ([], {'token_file': '"""test_bot.token"""'}), "(token_file='test_bot.token')\n", (82, 111), False, 'from bot import botToken\n')] |
from torchfes.opt.utils.generalize import generalize
from typing import Dict
import torch
from torch import Tensor, nn
from .. import properties as p
from .utils import (
Lagrangian, set_directional_hessian, set_directional_gradient)
from ..utils import detach
# Line search Newtons method is below
# gp := g(x + a ... | [
"torchfes.opt.utils.generalize.generalize",
"torch.ones"
] | [((1927, 1982), 'torch.ones', 'torch.ones', (['[n_bch]'], {'dtype': 'gsd.dtype', 'device': 'gsd.device'}), '([n_bch], dtype=gsd.dtype, device=gsd.device)\n', (1937, 1982), False, 'import torch\n'), ((2809, 2824), 'torchfes.opt.utils.generalize.generalize', 'generalize', (['mol'], {}), '(mol)\n', (2819, 2824), False, 'f... |
import json
import boto3
import logging
from datetime import datetime
from dateutil import tz
logger = logging.getLogger()
logger.setLevel(logging.INFO)
from_zone = tz.gettz('UTC')
to_zone = tz.gettz('Asia/Jerusalem')
starts_in = {'SINGLE': 5,
"DOUBLE": 2,
"LONG": 0
}
client = boto3.client('iot-data', regio... | [
"logging.getLogger",
"boto3.client",
"datetime.datetime.utcnow",
"dateutil.tz.gettz",
"json.dumps"
] | [((104, 123), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (121, 123), False, 'import logging\n'), ((167, 182), 'dateutil.tz.gettz', 'tz.gettz', (['"""UTC"""'], {}), "('UTC')\n", (175, 182), False, 'from dateutil import tz\n'), ((193, 219), 'dateutil.tz.gettz', 'tz.gettz', (['"""Asia/Jerusalem"""'], {}),... |
from typing import Generator
import pytest
from fastapi.testclient import TestClient
from app.main import app
@pytest.fixture(scope="module")
def test_data():
sample_data = {"user_handle": 1}
return sample_data
@pytest.fixture()
def client() -> Generator:
with TestClient(app) as _client:
yield... | [
"pytest.fixture",
"fastapi.testclient.TestClient"
] | [((115, 145), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (129, 145), False, 'import pytest\n'), ((226, 242), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (240, 242), False, 'import pytest\n'), ((279, 294), 'fastapi.testclient.TestClient', 'TestClient', (['app'], ... |
# GTA_Hunter pipeline to first blast a query against GTA database to search for GTA homologs and then classifying them using SVM approach
# Author: Evolutionary Computational Genomics Lab
# Last modified: 6/20/2019
###############
### IMPORTS ###
###############
import os
# import sys
from Bio.Blast.Applications i... | [
"bin.Feature.Feature",
"os.listdir",
"argparse.ArgumentParser",
"bin.filter_extract_fasta_ch.extract_fasta",
"bin.Weight.Weight.load",
"os.path.join",
"bin.Loader.Loader.load",
"Bio.SeqIO.parse",
"Bio.Blast.Applications.NcbiblastpCommandline",
"bin.Weight.Weight",
"time.time",
"bin.SVM.SVM"
] | [((3259, 3345), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Gene Classification Using\n SVM."""'}), '(description=\n """Gene Classification Using\n SVM.""")\n', (3282, 3345), False, 'import argparse\n'), ((7822, 7840), 'os.listdir', 'os.listdir', (['folder'], {}), '(f... |
"""
This module contains the tests to check peleffy's solvent.
"""
import tempfile
from peleffy.utils import get_data_file_path, temporary_cd
from peleffy.topology import Molecule, Topology
from peleffy.forcefield import OPLS2005ForceField, OpenForceField
from peleffy.solvent import OPLSOBC, OBC2
class TestSolvent(... | [
"peleffy.utils.temporary_cd",
"tempfile.TemporaryDirectory",
"peleffy.forcefield.OPLS2005ForceField",
"peleffy.utils.get_data_file_path",
"peleffy.topology.Molecule",
"json.load",
"peleffy.solvent.OPLSOBC",
"peleffy.topology.Topology",
"peleffy.forcefield.OpenForceField",
"peleffy.solvent.OBC2"
] | [((680, 728), 'peleffy.utils.get_data_file_path', 'get_data_file_path', (['"""tests/ligandParams_MAL.txt"""'], {}), "('tests/ligandParams_MAL.txt')\n", (698, 728), False, 'from peleffy.utils import get_data_file_path, temporary_cd\n'), ((937, 988), 'peleffy.forcefield.OpenForceField', 'OpenForceField', (['"""openff_unc... |
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm
from solo12_collisions_utils import followBoundary
# Load the collision map from file
col_map_file = './npy_data/collision_map_centered_res100.npy'
col_map = np.load(col_map_file, allow_pickle=True)
traj1 = np.array(followBoundary(col_map))
tr... | [
"matplotlib.pyplot.xticks",
"sklearn.svm.NuSVC",
"solo12_collisions_utils.followBoundary",
"numpy.array",
"matplotlib.pyplot.contour",
"numpy.linspace",
"matplotlib.pyplot.yticks",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.axis",
"numpy.load",
"matplotlib.pyplot.show"
] | [((235, 275), 'numpy.load', 'np.load', (['col_map_file'], {'allow_pickle': '(True)'}), '(col_map_file, allow_pickle=True)\n', (242, 275), True, 'import numpy as np\n'), ((1417, 1428), 'numpy.array', 'np.array', (['X'], {}), '(X)\n', (1425, 1428), True, 'import numpy as np\n'), ((1497, 1514), 'sklearn.svm.NuSVC', 'svm.N... |
"""Tests for usgsm2m module."""
import os
import pytest
from usgsm2m.usgsm2m import USGSM2M
from usgsm2m.errors import USGSM2MError
@pytest.fixture(scope="module")
def ee():
return USGSM2M(
os.getenv("USGSM2M_USERNAME"), os.getenv("USGSM2M_PASSWORD")
)
def test_ee_login(ee):
assert ee.logged_i... | [
"pytest.fixture",
"pytest.raises",
"os.getenv",
"usgsm2m.errors.USGSM2MError"
] | [((137, 167), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (151, 167), False, 'import pytest\n'), ((206, 235), 'os.getenv', 'os.getenv', (['"""USGSM2M_USERNAME"""'], {}), "('USGSM2M_USERNAME')\n", (215, 235), False, 'import os\n'), ((237, 266), 'os.getenv', 'os.getenv', (['... |
import os
import numpy as np
from data_prepare import *
from Network_structure import *
from loss_function import *
from train_method import *
def save_eeg(saved_model, result_location, foldername, save_train, save_vali, save_test,
noiseEEG_train, EEG_train, noiseEEG_val, EEG_val, noiseEEG_test,... | [
"os.makedirs",
"os.path.exists",
"numpy.save"
] | [((814, 946), 'numpy.save', 'np.save', (["(result_location + '/' + foldername + '/' + train_num + '/' + 'nn_output' +\n '/' + 'noiseinput_train.npy')", 'noiseEEG_train'], {}), "(result_location + '/' + foldername + '/' + train_num + '/' +\n 'nn_output' + '/' + 'noiseinput_train.npy', noiseEEG_train)\n", (821, 946... |
########
# Copyright (c) 2016 GigaSpaces Technologies Ltd. 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... | [
"pynsxv.library.nsx_dlr.dlr_create",
"cloudify_nsx.library.nsx_common.possibly_assign_vm_creation_props",
"cloudify_nsx.library.nsx_esg_dlr.update_common_edges",
"cloudify_nsx.library.nsx_common.attempt_with_rerun",
"cloudify_nsx.library.nsx_common.nsx_login",
"cloudify.exceptions.NonRecoverableError",
... | [((1647, 1717), 'cloudify_nsx.library.nsx_common.get_properties_and_validate', 'common.get_properties_and_validate', (['"""router"""', 'kwargs', 'validation_rules'], {}), "('router', kwargs, validation_rules)\n", (1681, 1717), True, 'import cloudify_nsx.library.nsx_common as common\n'), ((1737, 1789), 'cloudify.ctx.log... |
from asyncio import Future
from prompt_toolkit.layout.containers import HSplit
from prompt_toolkit.layout.dimension import D
from prompt_toolkit.widgets import Button, Dialog, Label
from constants import DIALOG_WIDTH
from custom_types.ui_types import PopUpDialog
from utils import display_path
class ConfirmDialog(Po... | [
"prompt_toolkit.widgets.Button",
"utils.display_path",
"asyncio.Future",
"prompt_toolkit.layout.dimension.D"
] | [((444, 452), 'asyncio.Future', 'Future', ([], {}), '()\n', (450, 452), False, 'from asyncio import Future\n'), ((701, 737), 'prompt_toolkit.widgets.Button', 'Button', ([], {'text': '"""Yes"""', 'handler': 'set_done'}), "(text='Yes', handler=set_done)\n", (707, 737), False, 'from prompt_toolkit.widgets import Button, D... |
import torch
import ignite.distributed as idist
from tests.ignite.distributed.utils import (
_sanity_check,
_test_distrib__get_max_length,
_test_distrib_all_gather,
_test_distrib_all_reduce,
_test_distrib_barrier,
_test_distrib_broadcast,
_test_sync,
)
def test_no_distrib(capsys):
as... | [
"ignite.distributed.get_rank",
"ignite.distributed.show_config",
"ignite.distributed.device",
"tests.ignite.distributed.utils._sanity_check",
"tests.ignite.distributed.utils._test_distrib_broadcast",
"tests.ignite.distributed.utils._test_distrib__get_max_length",
"torch.cuda.device_count",
"tests.igni... | [((356, 381), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (379, 381), False, 'import torch\n'), ((703, 718), 'tests.ignite.distributed.utils._sanity_check', '_sanity_check', ([], {}), '()\n', (716, 718), False, 'from tests.ignite.distributed.utils import _sanity_check, _test_distrib__get_max... |
import os
import tempfile
import time
import cv2
import numpy as np
from PIL import Image
def calcVanishingPoint(lines):
points = lines[:, :2]
normals = lines[:, 2:4] - lines[:, :2]
normals /= np.maximum(np.linalg.norm(normals, axis=-1, keepdims=True), 1e-4)
normals = np.stack([normals[:, 1], -normal... | [
"numpy.clip",
"numpy.ceil",
"numpy.linalg.solve",
"numpy.ones",
"numpy.random.choice",
"numpy.logical_not",
"numpy.argmax",
"numpy.stack",
"numpy.deg2rad",
"numpy.zeros",
"numpy.array",
"numpy.random.randint",
"numpy.linalg.lstsq",
"numpy.linalg.norm",
"numpy.dot",
"numpy.expand_dims",... | [((288, 337), 'numpy.stack', 'np.stack', (['[normals[:, 1], -normals[:, 0]]'], {'axis': '(1)'}), '([normals[:, 1], -normals[:, 0]], axis=1)\n', (296, 337), True, 'import numpy as np\n'), ((2329, 2350), 'numpy.stack', 'np.stack', (['VPs'], {'axis': '(0)'}), '(VPs, axis=0)\n', (2337, 2350), True, 'import numpy as np\n'),... |
import os
from github import Github
g = Github(os.environ['GITHUB_TOKEN'])
stargazers = set()
contributors = set()
subscribers = set()
for repo in g.get_organization('orbitdb').get_repos():
for gazer in repo.get_stargazers():
stargazers.add(gazer)
for contributor in repo.get_contributors():
... | [
"github.Github"
] | [((41, 75), 'github.Github', 'Github', (["os.environ['GITHUB_TOKEN']"], {}), "(os.environ['GITHUB_TOKEN'])\n", (47, 75), False, 'from github import Github\n')] |
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')
class Template:
template_name = ""
context = None
def __init__(self, template_name="", context=None, *args, **kwargs):
self.template_name = template_name
self.context = context
def get_template... | [
"os.path.abspath",
"os.path.exists",
"os.path.join"
] | [((80, 115), 'os.path.join', 'os.path.join', (['BASE_DIR', '"""templates"""'], {}), "(BASE_DIR, 'templates')\n", (92, 115), False, 'import os\n'), ((38, 63), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (53, 63), False, 'import os\n'), ((346, 392), 'os.path.join', 'os.path.join', (['TEMPLAT... |
from __future__ import print_function
import argparse
from collections import OrderedDict
import json
import os
import logging
from keras.callbacks import EarlyStopping
from sklearn.preprocessing import normalize
from sklearn.metrics import roc_curve, auc, roc_auc_score, precision_score, recall_score, f1_score, accurac... | [
"logging.debug",
"pandas.read_csv",
"common.get_next_model_id",
"common.save_model",
"sklearn.metrics.precision_score",
"sklearn.metrics.recall_score",
"keras.optimizers.SGD",
"common.ensure_dir",
"sklearn.metrics.r2_score",
"argparse.ArgumentParser",
"numpy.where",
"json.dumps",
"numpy.asar... | [((1981, 1998), 'numpy.load', 'np.load', (['filename'], {}), '(filename)\n', (1988, 1998), True, 'import numpy as np\n'), ((2010, 2103), 'scipy.sparse.csr_matrix', 'csr_matrix', (["(loader['data'], loader['indices'], loader['indptr'])"], {'shape': "loader['shape']"}), "((loader['data'], loader['indices'], loader['indpt... |
"""empty message
Revision ID: <KEY>
Revises: 5b9e2fef18f6
Create Date: 2021-10-21 14:12:46.696355
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.sql import column, table
from sqlalchemy.sql.sqltypes import Boolean, String
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision ... | [
"sqlalchemy.sql.column",
"alembic.op.bulk_insert",
"alembic.op.execute"
] | [((735, 1080), 'alembic.op.bulk_insert', 'op.bulk_insert', (['requeststatus_table', "[{'name': 'On Hold', 'description': 'On Hold', 'isactive': True}, {'name':\n 'Deduplication', 'description': 'Deduplication', 'isactive': True}, {\n 'name': 'Harms Assessment', 'description': 'Harms Assessment',\n 'isactive': ... |
#!/usr/bin/python -B
# 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
# "Lic... | [
"traceback.print_exc",
"os.path.split"
] | [((2983, 3002), 'os.path.split', 'os.path.split', (['p[0]'], {}), '(p[0])\n', (2996, 3002), False, 'import os\n'), ((5090, 5111), 'traceback.print_exc', 'traceback.print_exc', ([], {}), '()\n', (5109, 5111), False, 'import traceback\n'), ((2593, 2615), 'os.path.split', 'os.path.split', (['save_as'], {}), '(save_as)\n',... |
'''
phone_communication_backup_coalescer
Copyright 2016, <NAME>
Licensed under MIT.
'''
import logging
import sys
import cli
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s:%(message)s')
def main():
cli.run(sys.argv[1:])
if __name__ == "__main__":
main()
| [
"logging.basicConfig",
"cli.run"
] | [((128, 220), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO', 'format': '"""%(asctime)s %(levelname)s:%(message)s"""'}), "(level=logging.INFO, format=\n '%(asctime)s %(levelname)s:%(message)s')\n", (147, 220), False, 'import logging\n'), ((234, 255), 'cli.run', 'cli.run', (['sys.argv[1:]... |
"""
*****************************************************************
Licensed Materials - Property of IBM
(C) Copyright IBM Corp. 2020. All Rights Reserved.
US Government Users Restricted Rights - Use, duplication or
disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
************************************... | [
"os.path.isabs",
"os.path.dirname",
"sys.exit",
"os.path.abspath",
"os.path.expanduser"
] | [((587, 598), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (595, 598), False, 'import sys\n'), ((1780, 1798), 'os.path.abspath', 'os.path.abspath', (['e'], {}), '(e)\n', (1795, 1798), False, 'import os\n'), ((2568, 2600), 'os.path.expanduser', 'os.path.expanduser', (['imported_env'], {}), '(imported_env)\n', (2586, ... |
import logging
import struct
from macholib.MachO import MachO
from macholib.mach_o import *
from .base_executable import *
from .section import *
INJECTION_SEGMENT_NAME = 'INJECT'
INJECTION_SECTION_NAME = 'inject'
class MachOExecutable(BaseExecutable):
def __init__(self, file_path):
super(MachOExecutabl... | [
"macholib.MachO.MachO",
"struct.unpack",
"logging.warning"
] | [((372, 386), 'macholib.MachO.MachO', 'MachO', (['self.fp'], {}), '(self.fp)\n', (377, 386), False, 'from macholib.MachO import MachO\n'), ((3897, 3993), 'struct.unpack', 'struct.unpack', (["(self.pack_endianness + 'I' * dysymtab_command.nindirectsyms)", 'indirect_symbols'], {}), "(self.pack_endianness + 'I' * dysymtab... |
# Somefun, <NAME>
# <EMAIL>
# EEE/CPE Dept. FUTA
# (c) 2018
#
# Number Theory Computing
# Recursive Patterns in Powers
# Integer Powers of any real number
# param n: base number, n
# param r: exponent number, r
# return: power, the result of the operation
import time
import sys
sys.setrecursionlimit(1500)
class SPR... | [
"sys.setrecursionlimit",
"time.clock"
] | [((281, 308), 'sys.setrecursionlimit', 'sys.setrecursionlimit', (['(1500)'], {}), '(1500)\n', (302, 308), False, 'import sys\n'), ((2831, 2843), 'time.clock', 'time.clock', ([], {}), '()\n', (2841, 2843), False, 'import time\n'), ((2906, 2918), 'time.clock', 'time.clock', ([], {}), '()\n', (2916, 2918), False, 'import ... |
from django.contrib import admin
from .models import UserDetail
# Register your models here.
admin.site.register(UserDetail) | [
"django.contrib.admin.site.register"
] | [((94, 125), 'django.contrib.admin.site.register', 'admin.site.register', (['UserDetail'], {}), '(UserDetail)\n', (113, 125), False, 'from django.contrib import admin\n')] |
from django.conf.urls import url
from organizers import views
urlpatterns = [
url(r'^review/$', views.ReviewApplicationView.as_view(), name='review'),
url(r'^ranking/$', views.RankingView.as_view(), name='ranking'),
url(r'^(?P<id>[\w-]+)$', views.ApplicationDetailView.as_view(), name="app_detail"),
ur... | [
"organizers.views.ApplicationDetailView.as_view",
"django.conf.urls.url",
"organizers.views.ApplicationsExportView.as_view",
"organizers.views.RankingView.as_view",
"organizers.views.InviteListView.as_view",
"organizers.views.ReviewApplicationView.as_view",
"organizers.views.WaitlistListView.as_view",
... | [((815, 877), 'django.conf.urls.url', 'url', (['"""^recalculate/votes/$"""', 'views.recalc'], {'name': '"""recalc_votes"""'}), "('^recalculate/votes/$', views.recalc, name='recalc_votes')\n", (818, 877), False, 'from django.conf.urls import url\n'), ((102, 139), 'organizers.views.ReviewApplicationView.as_view', 'views.... |
import urllib.request
import os
import json
from html.parser import HTMLParser
class MLStripper(HTMLParser):
def __init__(self):
super().__init__()
self.reset()
self.fed = []
def handle_data(self, d):
self.fed.append(d)
def get_data(self):
return ''.join... | [
"json.dump"
] | [((1984, 2005), 'json.dump', 'json.dump', (['result', 'fh'], {}), '(result, fh)\n', (1993, 2005), False, 'import json\n')] |
#!/usr/bin/env python3
# Platform-independent `mkdir`
import argparse
import pathlib
import sys
def main():
parser = argparse.ArgumentParser(description='Platform-independent `mkdir`')
parser.add_argument('-p', '--parents', action='store_true', required=False, help='no error if existing, make parent director... | [
"argparse.ArgumentParser",
"pathlib.Path"
] | [((124, 191), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Platform-independent `mkdir`"""'}), "(description='Platform-independent `mkdir`')\n", (147, 191), False, 'import argparse\n'), ((452, 467), 'pathlib.Path', 'pathlib.Path', (['p'], {}), '(p)\n', (464, 467), False, 'import pathli... |
from __future__ import unicode_literals # isort:skip
from future import standard_library # isort:skip
standard_library.install_aliases() # noqa: E402
from collections import defaultdict
import csv
from datetime import datetime
from io import StringIO
from time import strftime
from flask import (
Blueprint,
... | [
"flask.render_template",
"flask.request.args.get",
"datetime.datetime.utcnow",
"flask_user.roles_required",
"csv.writer",
"time.strftime",
"future.standard_library.install_aliases",
"collections.defaultdict",
"flask_babel.gettext",
"io.StringIO",
"flask.Blueprint"
] | [((106, 140), 'future.standard_library.install_aliases', 'standard_library.install_aliases', ([], {}), '()\n', (138, 140), False, 'from future import standard_library\n'), ((933, 965), 'flask.Blueprint', 'Blueprint', (['"""reporting"""', '__name__'], {}), "('reporting', __name__)\n", (942, 965), False, 'from flask impo... |
import json
import pytest
from apisports.response import AbstractResponse, ErrorResponse, HttpErrorResponse, Headers
from helpers import MockResponse, assert_response_ok, assert_response_error
def test_invalidjson():
response = AbstractResponse.create(None, MockResponse("-"))
assert_response_error(response)... | [
"helpers.MockResponse",
"apisports.response.AbstractResponse.create",
"json.dumps",
"pytest.mark.parametrize",
"helpers.assert_response_error",
"helpers.assert_response_ok"
] | [((1044, 1090), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""data"""', '[False, None]'], {}), "('data', [False, None])\n", (1067, 1090), False, 'import pytest\n'), ((1648, 1707), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""text"""', '[\'\', \'{"response": "ok"}\']'], {}), '(\'text\', [\'\... |
"""
-- For Development Purposes --
Serves all all api challenges and training materials
Look out for auth clashes and multiple cookies
"""
import uvicorn
from fastapi import FastAPI
from rest_introduction_app.api.api import api_router
app = FastAPI(
title='Testing HTTP responses',
description="Application to ... | [
"fastapi.FastAPI"
] | [((243, 426), 'fastapi.FastAPI', 'FastAPI', ([], {'title': '"""Testing HTTP responses"""', 'description': '"""Application to show different HTTP responses for learning testing purpose"""', 'version': '"""0.1"""', 'docs_url': '"""/"""', 'redoc_url': 'None'}), "(title='Testing HTTP responses', description=\n 'Applicat... |
import tensorflow as tf
from tensorflow.contrib import slim
import numpy as np
import os
import time
from utils import kde
from ops import *
tf.reset_default_graph()
os.environ['CUDA_VISIBLE_DEVICES'] = '6'
# Parameters
learning_rate = 1e-3
reg_param = 10.
batch_size = 128
x_dim = 2
z_dim = 2
sigma = 0.7
mu = 2
met... | [
"os.path.exists",
"tensorflow.reset_default_graph",
"tensorflow.random_normal",
"os.makedirs",
"tensorflow.Session",
"time.strftime",
"os.path.join",
"tensorflow.global_variables_initializer",
"numpy.random.randn",
"tensorflow.summary.scalar",
"tensorflow.summary.FileWriter",
"tensorflow.make_... | [((144, 168), 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), '()\n', (166, 168), True, 'import tensorflow as tf\n'), ((1302, 1357), 'tensorflow.make_template', 'tf.make_template', (['"""generator"""', 'generator4Gaussian_func1'], {}), "('generator', generator4Gaussian_func1)\n", (1318, 1357), Tru... |
from unittest.case import skip
from bs4.element import NavigableString, PageElement, Tag, TemplateString
from pp.models import BadUrlException, GitHubCode, GithubCodeElement, GithubCodeLine
from django.test import TestCase
# Create your tests here.
class GithubCodeTestCase(TestCase):
def test_about_bad_url_on_con... | [
"pp.models.GithubCodeLine",
"bs4.element.Tag",
"unittest.case.skip",
"pp.models.GitHubCode",
"pp.models.GithubCodeElement",
"bs4.element.NavigableString"
] | [((430, 478), 'unittest.case.skip', 'skip', (['"""skip this test other than local machine."""'], {}), "('skip this test other than local machine.')\n", (434, 478), False, 'from unittest.case import skip\n'), ((701, 763), 'pp.models.GitHubCode', 'GitHubCode', (['"""https://github.com/not_requesable_source#L11-L22"""'], ... |
import os
class Config:
NEWS_API_BASE_URL = 'https://newsapi.org/v2/{}?{}&apiKey={}'
SECRET_KEY = os.environ.get("SECRET_KEY")
NEWS_API_KEY = os.environ.get('NEWS_API_KEY')
class DevConfig(Config):
DEBUG = True
class ProdConfig(Config):
DEBUG = False
configuration = {
'develop': DevConfig,... | [
"os.environ.get"
] | [((107, 135), 'os.environ.get', 'os.environ.get', (['"""SECRET_KEY"""'], {}), "('SECRET_KEY')\n", (121, 135), False, 'import os\n'), ((155, 185), 'os.environ.get', 'os.environ.get', (['"""NEWS_API_KEY"""'], {}), "('NEWS_API_KEY')\n", (169, 185), False, 'import os\n')] |
# Copyright 2022 Huawei Technologies Co., Ltd
#
# 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... | [
"mindspore.ops.Cummax",
"mindspore.context.set_context",
"pytest.mark.parametrize",
"numpy.array",
"mindspore.ops.operations._inner_ops.Cummin",
"mindspore.Tensor"
] | [((2017, 2113), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""data_type"""', '[np.uint8, np.int8, np.int32, np.float16, np.float32]'], {}), "('data_type', [np.uint8, np.int8, np.int32, np.\n float16, np.float32])\n", (2040, 2113), False, 'import pytest\n'), ((3272, 3389), 'pytest.mark.parametrize', 'py... |
import torch
from torch.distributions import Normal
def theta(mod, priors, y=None):
# Sample posterior model parameters
idx = [range(mod.N[i]) for i in range(mod.I)]
params = mod.sample_params(idx)
# Detach model parameters
mu0 = -params['delta0'].cumsum(0).detach()
mu1 = params['delta1'].cums... | [
"torch.tensor"
] | [((947, 980), 'torch.tensor', 'torch.tensor', (["priors['noisy_var']"], {}), "(priors['noisy_var'])\n", (959, 980), False, 'import torch\n')] |
'''Faça um program que mostre uma contagem regressiva para os estouros de fogos de artificil.
indo de 10 ate 0 com pausa de 1 segundo entre eles.'''
from time import sleep
for c in range(10, -1, -1):
print(c)
sleep(1)
print('\033[1;36;40mFELIZ ANO NOVO MEUS QUERIDOS!\033[m') | [
"time.sleep"
] | [((218, 226), 'time.sleep', 'sleep', (['(1)'], {}), '(1)\n', (223, 226), False, 'from time import sleep\n')] |
import random
a1 = input ('Nome do primeiro aluno: ')
a2 = input ('nome do segundo aluno: ')
a3 = input (' nome do terceiro aluno: ')
a4 = input (' nome do quarto aluno: ')
lista = [a1, a2, a3, a4]
print ('Alunos: \n {} \n {} \n {} \n {} \n' .format(a1,a2,a3,a4))
escolhido = random.choice (lista)
print (' O aluno sor... | [
"random.choice",
"random.shuffle"
] | [((278, 298), 'random.choice', 'random.choice', (['lista'], {}), '(lista)\n', (291, 298), False, 'import random\n'), ((355, 376), 'random.shuffle', 'random.shuffle', (['lista'], {}), '(lista)\n', (369, 376), False, 'import random\n')] |
#!/usr/bin/env python3
import re
import os
import shutil
import argparse
from pprint import pprint
parser = argparse.ArgumentParser()
parser.add_argument("ssid", help = "network SSID.")
parser.add_argument("--psk", help = "network password, if not provided, script will attempt using saved credentials.")
args = parser.... | [
"argparse.ArgumentParser",
"re.compile",
"os.path.join",
"os.path.realpath",
"shutil.copyfile",
"os.system"
] | [((109, 134), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (132, 134), False, 'import argparse\n'), ((587, 638), 'os.path.join', 'os.path.join', (['script_dir', '"""wpa_supplicant.conf.tmp"""'], {}), "(script_dir, 'wpa_supplicant.conf.tmp')\n", (599, 638), False, 'import os\n'), ((653, 700), ... |
from rest_framework.decorators import api_view
from rest_framework.response import Response
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from homework.models import Presentation
from homework.serializers import PresentationSerializer
from homework.services.presentation_services import (
... | [
"homework.models.Presentation.objects.get",
"homework.models.Presentation.objects.all",
"homework.services.presentation_services.upload_image_",
"homework.services.presentation_services.update_presentation_",
"rest_framework.response.Response",
"homework.serializers.PresentationSerializer",
"homework.se... | [((389, 406), 'rest_framework.decorators.api_view', 'api_view', (["['GET']"], {}), "(['GET'])\n", (397, 406), False, 'from rest_framework.decorators import api_view\n'), ((1021, 1039), 'rest_framework.decorators.api_view', 'api_view', (["['POST']"], {}), "(['POST'])\n", (1029, 1039), False, 'from rest_framework.decorat... |
from nltk.corpus import stopwords
stop_words = set(stopwords.words("indonesian"))
print(stop_words)
| [
"nltk.corpus.stopwords.words"
] | [((52, 81), 'nltk.corpus.stopwords.words', 'stopwords.words', (['"""indonesian"""'], {}), "('indonesian')\n", (67, 81), False, 'from nltk.corpus import stopwords\n')] |
#!/usr/bin/python
try:
from gpxpy import gpx
except ImportError:
print("gpxpy not found - please run: pip install gpxpy")
sys.exit()
class GpxUtil:
def coords_2_sequences(self, coords):
""" Takes an array of arrays of coordinates (lon,lat) and returns a gpx object with sequences."""
gp... | [
"gpxpy.gpx.GPXTrack",
"gpxpy.gpx.GPXTrackPoint",
"gpxpy.gpx.GPXTrackSegment",
"gpxpy.gpx.GPX"
] | [((329, 338), 'gpxpy.gpx.GPX', 'gpx.GPX', ([], {}), '()\n', (336, 338), False, 'from gpxpy import gpx\n'), ((401, 415), 'gpxpy.gpx.GPXTrack', 'gpx.GPXTrack', ([], {}), '()\n', (413, 415), False, 'from gpxpy import gpx\n'), ((520, 541), 'gpxpy.gpx.GPXTrackSegment', 'gpx.GPXTrackSegment', ([], {}), '()\n', (539, 541), Fa... |
import os
os.system("nohup python src/Tulsi.py >> nohup.out 2>&1 &")
| [
"os.system"
] | [((11, 70), 'os.system', 'os.system', (['"""nohup python src/Tulsi.py >> nohup.out 2>&1 &"""'], {}), "('nohup python src/Tulsi.py >> nohup.out 2>&1 &')\n", (20, 70), False, 'import os\n')] |
import unittest
from kafka_influxdb.encoder import heapster_json_encoder
class TestHeapsterJsonEncoder(unittest.TestCase):
def setUp(self):
self.encoder = heapster_json_encoder.Encoder()
def testEncoder(self):
msg = b'{ "MetricsName":"memory/major_page_faults","MetricsValue":{"value":56}, "... | [
"kafka_influxdb.encoder.heapster_json_encoder.Encoder"
] | [((171, 202), 'kafka_influxdb.encoder.heapster_json_encoder.Encoder', 'heapster_json_encoder.Encoder', ([], {}), '()\n', (200, 202), False, 'from kafka_influxdb.encoder import heapster_json_encoder\n')] |
# -*- coding: utf-8 -*-
# Copyright (C) 2010-2013 Mag. <NAME> All rights reserved
# Glasauergasse 32, A--1130 Wien, Austria. <EMAIL>
# ****************************************************************************
# This module is part of the package GTW.OMP.Auth.
#
# This module is licensed under the terms of the BSD 3-... | [
"_GTW.GTW.OMP.Auth._Export"
] | [((1610, 1635), '_GTW.GTW.OMP.Auth._Export', 'GTW.OMP.Auth._Export', (['"""*"""'], {}), "('*')\n", (1630, 1635), False, 'from _GTW import GTW\n')] |
from mtga.set_data import all_mtga_cards
from mtga.models.card import Card
from getpass import getuser
import json
from prettytable import PrettyTable
debug = False
class CardOwned:
card = Card()
owned = 0
filePath = "C:/Users/" + getuser() + "/AppData/LocalLow/Wizards Of The Coast/MTGA/output_log.txt"
file... | [
"prettytable.PrettyTable",
"json.loads",
"mtga.models.card.Card",
"mtga.set_data.all_mtga_cards.find_one",
"getpass.getuser"
] | [((3339, 3352), 'prettytable.PrettyTable', 'PrettyTable', ([], {}), '()\n', (3350, 3352), False, 'from prettytable import PrettyTable\n'), ((3711, 3724), 'prettytable.PrettyTable', 'PrettyTable', ([], {}), '()\n', (3722, 3724), False, 'from prettytable import PrettyTable\n'), ((195, 201), 'mtga.models.card.Card', 'Card... |
#!/usr/bin/python3
import pygame
from pygame import Color
from enum import Enum
from random import randint
import re
import sys
size = width, height = [1024, 640]
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Hanoch")
clock = pygame.time.Clock()
class Colors(Enum):
WHITE = (255,255,255)
... | [
"pygame.display.set_caption",
"pygame.quit",
"re.compile",
"pygame.event.get",
"pygame.display.set_mode",
"pygame.display.flip",
"pygame.display.get_surface",
"pygame.time.Clock",
"pygame.display.update",
"random.randint"
] | [((174, 203), 'pygame.display.set_mode', 'pygame.display.set_mode', (['size'], {}), '(size)\n', (197, 203), False, 'import pygame\n'), ((204, 240), 'pygame.display.set_caption', 'pygame.display.set_caption', (['"""Hanoch"""'], {}), "('Hanoch')\n", (230, 240), False, 'import pygame\n'), ((250, 269), 'pygame.time.Clock',... |
# Copyright 2020 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" file ac... | [
"neptune_python_utils.endpoints.Endpoints",
"boto3.client",
"requests.utils.urlparse"
] | [((1841, 1886), 'boto3.client', 'boto3.client', (['"""glue"""'], {'region_name': 'self.region'}), "('glue', region_name=self.region)\n", (1853, 1886), False, 'import boto3\n'), ((2235, 2271), 'requests.utils.urlparse', 'requests.utils.urlparse', (['neptune_uri'], {}), '(neptune_uri)\n', (2258, 2271), False, 'import req... |
import os
import io
import sys
import numpy as np
from array import array
import cv2
from PIL import Image, ImageDraw
import streamlit as st
from image_processing import *
from azure_api import *
MAGE_EMOJI_URL = "https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/240/twitter/259/mage_1f9d9.png"
# Set... | [
"streamlit.image",
"PIL.Image.open",
"streamlit.file_uploader",
"os.environ.get",
"streamlit.set_page_config",
"streamlit.title"
] | [((345, 417), 'streamlit.set_page_config', 'st.set_page_config', ([], {'page_title': '"""OCR Generator"""', 'page_icon': 'MAGE_EMOJI_URL'}), "(page_title='OCR Generator', page_icon=MAGE_EMOJI_URL)\n", (363, 417), True, 'import streamlit as st\n'), ((426, 465), 'streamlit.title', 'st.title', (['"""A web app for OCR on i... |
import datetime
from bitmovin import Bitmovin, Encoding, S3Output, H264CodecConfiguration, AACCodecConfiguration, H264Profile, \
StreamInput, SelectionMode, Stream, EncodingOutput, ACLEntry, ACLPermission, MuxingStream, \
S3Input, FairPlayDRM, TSMuxing, HlsManifest, AudioMedia, VariantStream
from bitmovin.error... | [
"bitmovin.HlsManifest",
"bitmovin.VariantStream",
"bitmovin.H264CodecConfiguration",
"bitmovin.Bitmovin",
"bitmovin.FairPlayDRM",
"bitmovin.AACCodecConfiguration",
"bitmovin.MuxingStream",
"bitmovin.AudioMedia",
"bitmovin.S3Input",
"datetime.datetime.now",
"bitmovin.Stream",
"bitmovin.ACLEntry... | [((1054, 1079), 'bitmovin.Bitmovin', 'Bitmovin', ([], {'api_key': 'API_KEY'}), '(api_key=API_KEY)\n', (1062, 1079), False, 'from bitmovin import Bitmovin, Encoding, S3Output, H264CodecConfiguration, AACCodecConfiguration, H264Profile, StreamInput, SelectionMode, Stream, EncodingOutput, ACLEntry, ACLPermission, MuxingSt... |
#!/usr/bin/env python3
# Based on pcgod's mumble-ping script found at http://0xy.org/mumble-ping.py.
import socket
import sys
import time
import datetime
from struct import pack, unpack
if len(sys.argv) < 3:
print("Usage: %s <host> <port>" % sys.argv[0])
sys.exit()
host = sys.argv[1]
port = int(sys.argv[2])
... | [
"socket.socket",
"datetime.datetime.now",
"struct.unpack",
"sys.exit",
"time.time"
] | [((325, 373), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_DGRAM'], {}), '(socket.AF_INET, socket.SOCK_DGRAM)\n', (338, 373), False, 'import socket\n'), ((637, 662), 'struct.unpack', 'unpack', (['""">bbbbQiii"""', 'data'], {}), "('>bbbbQiii', data)\n", (643, 662), False, 'from struct import pack, ... |
import random
import numpy as np
from mesa import Agent
# [STRATEGY_CHEATERS, STRATEGY_FAIR, STRATEGY_GENEROUS, STRATEGY_MARTYRS, STRATEGY_PRUDENT]
SMART_VAMPIRE_STRATEGIES_PROB = [0.25, 0.25, 0.125, 0.25, 0.125]
class Vampire(Agent):
def __init__(self, id, model, root_id):
super().__init__(id, model)
... | [
"random.choice",
"numpy.ones",
"numpy.random.choice",
"numpy.sum",
"numpy.random.randint",
"random.random"
] | [((2752, 2829), 'numpy.random.choice', 'np.random.choice', (['self.STRATEGIES'], {'p': 'self.model.smart_vampire_strategies_prob'}), '(self.STRATEGIES, p=self.model.smart_vampire_strategies_prob)\n', (2768, 2829), True, 'import numpy as np\n'), ((720, 735), 'random.random', 'random.random', ([], {}), '()\n', (733, 735)... |
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from django.shortcuts import render
from .models import Pag1juegos,Aventura,Lucha,Rol,MundoAbierto
from django.http import HttpResponse
# Create your views here.
def home(request):
Juegos = Pag1juegos.objects.all()
d... | [
"django.shortcuts.render"
] | [((370, 409), 'django.shortcuts.render', 'render', (['request', '"""core/home.html"""', 'data'], {}), "(request, 'core/home.html', data)\n", (376, 409), False, 'from django.shortcuts import render\n'), ((531, 576), 'django.shortcuts.render', 'render', (['request', '"""core/Adventures.html"""', 'data'], {}), "(request, ... |
from numpy import random
x = random.multinomial(n=6, pvals=[1 / 6, 1 / 6, 1 / 6, 1 / 6, 1 / 6, 1 / 6])
print(x)
| [
"numpy.random.multinomial"
] | [((30, 103), 'numpy.random.multinomial', 'random.multinomial', ([], {'n': '(6)', 'pvals': '[1 / 6, 1 / 6, 1 / 6, 1 / 6, 1 / 6, 1 / 6]'}), '(n=6, pvals=[1 / 6, 1 / 6, 1 / 6, 1 / 6, 1 / 6, 1 / 6])\n', (48, 103), False, 'from numpy import random\n')] |
import click
from marinetrafficapi import constants
from marinetrafficapi.bind import bind_request
from marinetrafficapi.vessels_positions.\
PS01_vessel_historical_track.models import VesselHistoricalPosition
from marinetrafficapi.vessels_positions.\
PS01_vessel_historical_track.query_params import PS01QueryP... | [
"click.style"
] | [((1446, 1484), 'click.style', 'click.style', (['"""API CALL PS01"""'], {'fg': '"""red"""'}), "('API CALL PS01', fg='red')\n", (1457, 1484), False, 'import click\n'), ((2379, 2417), 'click.style', 'click.style', (['"""API CALL PS02"""'], {'fg': '"""red"""'}), "('API CALL PS02', fg='red')\n", (2390, 2417), False, 'impor... |
#!/usr/bin/env python3
import sys
import os
import types
import subprocess
import json
import yaml
import shutil
def run_dialog(parameters):
dialog_cmd = ["dialog"] + parameters
dialog_env = os.environ.copy()
# By default dialog returns 255 on ESC. It gets mixed up with error code -1
# converted to un... | [
"sys.exit",
"os.listdir",
"subprocess.Popen",
"subprocess.CalledProcessError",
"subprocess.run",
"json.dumps",
"os.path.isdir",
"os.path.expanduser",
"subprocess.check_output",
"subprocess.check_call",
"types.SimpleNamespace",
"shutil.which",
"os.path.isfile",
"os.path.dirname",
"os.path... | [((2081, 2156), 'os.path.expanduser', 'os.path.expanduser', (['"""~/.cache/cheretbe/ansible-playbooks/run_role_cfg.json"""'], {}), "('~/.cache/cheretbe/ansible-playbooks/run_role_cfg.json')\n", (2099, 2156), False, 'import os\n'), ((2160, 2192), 'os.path.isfile', 'os.path.isfile', (['config_file_name'], {}), '(config_f... |
#getLog(mt) : Returns the natural log of the matrix.
import numpy as np
from .isPSDMd import isPSD
__all__ = ['getLog']
def getLog(M, eps=1e-15):
r"""Takes as input a matrix M and returns the natural log of M.
Parameters
----------
M : numpy.ndarray
2-d array representing a... | [
"numpy.log",
"numpy.any"
] | [((1135, 1152), 'numpy.any', 'np.any', (['(val < eps)'], {}), '(val < eps)\n', (1141, 1152), True, 'import numpy as np\n'), ((1211, 1222), 'numpy.log', 'np.log', (['val'], {}), '(val)\n', (1217, 1222), True, 'import numpy as np\n')] |
# Copyright 2020 Xilinx Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | [
"os.path.join",
"cv2.resize",
"numpy.asarray",
"cv2.imread"
] | [((1452, 1508), 'cv2.resize', 'cv2.resize', (['image', 'size'], {'interpolation': 'cv2.INTER_NEAREST'}), '(image, size, interpolation=cv2.INTER_NEAREST)\n', (1462, 1508), False, 'import cv2\n'), ((1551, 1568), 'numpy.asarray', 'np.asarray', (['image'], {}), '(image)\n', (1561, 1568), True, 'import numpy as np\n'), ((22... |
import os
class Config(object):
"""
Parent configuration class
"""
DEBUG = False
CSRF_ENABLED = True
SECRET = os.getenv('SECRET')
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL')
class DevelopmentConfig(Config):
"""
Configuration for Dev
"""
DEBUG = True
SQLALCHEMY... | [
"os.getenv"
] | [((136, 155), 'os.getenv', 'os.getenv', (['"""SECRET"""'], {}), "('SECRET')\n", (145, 155), False, 'import os\n'), ((186, 211), 'os.getenv', 'os.getenv', (['"""DATABASE_URL"""'], {}), "('DATABASE_URL')\n", (195, 211), False, 'import os\n')] |
# -*- coding: utf-8 -*-
"""
TSDB DAO
"""
# This code is a part of coolisf library: https://github.com/letuananh/intsem.fx
# :copyright: (c) 2014 <NAME> <<EMAIL>>
# :license: MIT, see LICENSE for more details.
import os
import os.path
import logging
from delphin import itsdb
from coolisf.model import Document, Sent... | [
"logging.getLogger",
"coolisf.model.Document",
"delphin.itsdb.ItsdbProfile",
"os.path.realpath",
"os.path.basename",
"coolisf.model.Sentence"
] | [((499, 526), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (516, 526), False, 'import logging\n'), ((552, 578), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (568, 578), False, 'import os\n'), ((846, 870), 'delphin.itsdb.ItsdbProfile', 'itsdb.ItsdbProfile',... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Advent of Code 2021, day seventeen."""
import re
from typing import Optional
MAX_ITER = 250
INPUT_FILE = 'data/day_17.txt'
INPUT_RE = re.compile(r'target area:\sx=(\d+)\.\.(\d+),\s'
r'y=(-?\d+)\.\.(-?\d+)')
def simulate(x: int, y: int,
... | [
"re.compile"
] | [((186, 263), 're.compile', 're.compile', (['"""target area:\\\\sx=(\\\\d+)\\\\.\\\\.(\\\\d+),\\\\sy=(-?\\\\d+)\\\\.\\\\.(-?\\\\d+)"""'], {}), "('target area:\\\\sx=(\\\\d+)\\\\.\\\\.(\\\\d+),\\\\sy=(-?\\\\d+)\\\\.\\\\.(-?\\\\d+)')\n", (196, 263), False, 'import re\n')] |
import numpy as np
import torch
class AverageMeter(object):
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, num):
self.val = val
self.sum += val * num
self.count +... | [
"torch.sin",
"torch.cos",
"torch.sqrt",
"torch.acos"
] | [((566, 602), 'torch.sqrt', 'torch.sqrt', (['(x ** 2 + y ** 2 + z ** 2)'], {}), '(x ** 2 + y ** 2 + z ** 2)\n', (576, 602), False, 'import torch\n'), ((439, 462), 'torch.sin', 'torch.sin', (['angles[:, 1]'], {}), '(angles[:, 1])\n', (448, 462), False, 'import torch\n'), ((472, 495), 'torch.sin', 'torch.sin', (['angles[... |
# -*- coding: utf-8 -*-
# Resource object code
#
# Created by: The Resource Compiler for PyQt5 (Qt v5.9.6)
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore
qt_resource_data = b"\
\x00\x00\x08\x75\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\
\x00\x00\x80\x0... | [
"PyQt5.QtCore.qVersion",
"PyQt5.QtCore.qUnregisterResourceData",
"PyQt5.QtCore.qRegisterResourceData"
] | [((266074, 266175), 'PyQt5.QtCore.qRegisterResourceData', 'QtCore.qRegisterResourceData', (['rcc_version', 'qt_resource_struct', 'qt_resource_name', 'qt_resource_data'], {}), '(rcc_version, qt_resource_struct,\n qt_resource_name, qt_resource_data)\n', (266102, 266175), False, 'from PyQt5 import QtCore\n'), ((266202,... |
from xls2xml import TSVReader
def test_get_valid_conf_keys():
tsv_reader = TSVReader('data/example_samples.tsv', 'data/T2D_xls2xml_v1.conf', 'Sample')
assert set(tsv_reader.get_valid_conf_keys()) == {'Sample'}
tsv_reader = TSVReader('data/example_samples.tsv', 'data/T2D_xls2xml_v1.conf', 'Analysis')
as... | [
"xls2xml.TSVReader"
] | [((80, 155), 'xls2xml.TSVReader', 'TSVReader', (['"""data/example_samples.tsv"""', '"""data/T2D_xls2xml_v1.conf"""', '"""Sample"""'], {}), "('data/example_samples.tsv', 'data/T2D_xls2xml_v1.conf', 'Sample')\n", (89, 155), False, 'from xls2xml import TSVReader\n'), ((236, 313), 'xls2xml.TSVReader', 'TSVReader', (['"""da... |
from django.views.generic import TemplateView
if settings.DEBUG:
# enable local preview of error pages
urlpatterns += patterns('',
(r'^403/$', TemplateView.as_view(template_name="403.html")),
(r'^404/$', TemplateView.as_view(template_name="404.html")),
(r'^500/$', TemplateView.as_view... | [
"django.views.generic.TemplateView.as_view"
] | [((162, 208), 'django.views.generic.TemplateView.as_view', 'TemplateView.as_view', ([], {'template_name': '"""403.html"""'}), "(template_name='403.html')\n", (182, 208), False, 'from django.views.generic import TemplateView\n'), ((231, 277), 'django.views.generic.TemplateView.as_view', 'TemplateView.as_view', ([], {'te... |
# SCRAMBLE - Adit
import cv2
import numpy as np
from emb import *
def decryption2(p,key):
img = cv2.imread(p, cv2.IMREAD_GRAYSCALE)
i2 = np.zeros((258, 258), dtype="int")
i3 = np.zeros((258, 258), dtype="int")
i4 = np.zeros((258, 258), dtype="int")
i5 = np.zeros((258, 258), dtype="int")
key2=ke... | [
"numpy.roll",
"cv2.imwrite",
"numpy.zeros",
"cv2.imread"
] | [((101, 136), 'cv2.imread', 'cv2.imread', (['p', 'cv2.IMREAD_GRAYSCALE'], {}), '(p, cv2.IMREAD_GRAYSCALE)\n', (111, 136), False, 'import cv2\n'), ((146, 179), 'numpy.zeros', 'np.zeros', (['(258, 258)'], {'dtype': '"""int"""'}), "((258, 258), dtype='int')\n", (154, 179), True, 'import numpy as np\n'), ((189, 222), 'nump... |
import turtle
#now create a graphics window.
t = turtle.Pen()
for j in range(1):
for i in range(5):
t.forward(100)
t.left(72)
stopper = raw_input("Hit <enter> to quit.")
#now remove the graphics window before exiting
turtle.bye()
| [
"turtle.Pen",
"turtle.bye"
] | [((52, 64), 'turtle.Pen', 'turtle.Pen', ([], {}), '()\n', (62, 64), False, 'import turtle\n'), ((241, 253), 'turtle.bye', 'turtle.bye', ([], {}), '()\n', (251, 253), False, 'import turtle\n')] |
from pygtfs import Schedule
from pygtfs import append_feed, delete_feed, overwrite_feed, list_feeds
class GTFSSmallSetup(object):
def __init__(self):
self.schedule = Schedule(":memory:")
append_feed(self.schedule, "test/data/atx_small" )
# class GTFSATXSetup(object):
# def __init__(... | [
"pygtfs.append_feed",
"pygtfs.Schedule"
] | [((184, 204), 'pygtfs.Schedule', 'Schedule', (['""":memory:"""'], {}), "(':memory:')\n", (192, 204), False, 'from pygtfs import Schedule\n'), ((214, 263), 'pygtfs.append_feed', 'append_feed', (['self.schedule', '"""test/data/atx_small"""'], {}), "(self.schedule, 'test/data/atx_small')\n", (225, 263), False, 'from pygtf... |
"""
test_question.py
サンプルテストケース
"""
import pytest
import run as myApp
from datetime import datetime, timedelta
from models import Question
@pytest.fixture
def api():
return myApp.api
class TestQuestionModel:
def test_was_published_recently_with_future_question(self, api):
"""
未来の質問に対してwas_... | [
"models.Question",
"datetime.datetime.now",
"datetime.timedelta"
] | [((507, 549), 'models.Question', 'Question', (['"""future_question"""'], {'pub_date': 'time'}), "('future_question', pub_date=time)\n", (515, 549), False, 'from models import Question\n'), ((1102, 1136), 'models.Question', 'Question', (['"""old_question"""', 'time_old'], {}), "('old_question', time_old)\n", (1110, 1136... |
"""
Demo Program - Progress Meter using a Text Element
This program was written by @jason990420
This is a clever use of a Text Element to create the same look
and feel of a progress bar in PySimpleGUI using only a Text Element.
Copyright 2020 PySimpleGUI.org
"""
from tkinter.constants import BOTTOM... | [
"PySimpleGUI.theme",
"PySimpleGUI.Text",
"PySimpleGUI.Window"
] | [((394, 412), 'PySimpleGUI.theme', 'sg.theme', (['"""Reddit"""'], {}), "('Reddit')\n", (402, 412), True, 'import PySimpleGUI as sg\n'), ((742, 911), 'PySimpleGUI.Window', 'sg.Window', (['"""Title"""', 'layout'], {'size': '(500, 70)', 'finalize': '(True)', 'element_justification': '"""center"""', 'background_color': '""... |
import json
from pathlib import Path
import pandas as pd
import requests
from tqdm import tqdm
ROOT = Path(__file__)
TOPSTORIES_NAME = "hn_topstories"
TOPSTORIES_ZIP = ROOT.parent / f"{TOPSTORIES_NAME}.zip"
TOPSTORIES_JSONL = TOPSTORIES_ZIP / f"{TOPSTORIES_NAME}.jsonl"
def save_topstories_as_zip():
hn_topstori... | [
"pandas.read_pickle",
"json.loads",
"pandas.json_normalize",
"pathlib.Path",
"tqdm.tqdm",
"requests.get",
"pandas.read_json"
] | [((104, 118), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (108, 118), False, 'from pathlib import Path\n'), ((548, 579), 'requests.get', 'requests.get', (['hn_topstories_url'], {}), '(hn_topstories_url)\n', (560, 579), False, 'import requests\n'), ((599, 631), 'json.loads', 'json.loads', (['topstory_res... |