code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
from cs1media import *
import math
def dist(c1, c2):
r1, g1, b1 = c1
r2, g2, b2 = c2
return math.sqrt((r1-r2)**2 + (g1-g2)**2 + (b1-b2)**2)
def chroma(img, key, threshold):
w, h = img.size()
for y in range(h):
for x in range(w):
p = img.get(x, y)
if dist(p, key) < threshold:
img.set... | [
"math.sqrt"
] | [((100, 159), 'math.sqrt', 'math.sqrt', (['((r1 - r2) ** 2 + (g1 - g2) ** 2 + (b1 - b2) ** 2)'], {}), '((r1 - r2) ** 2 + (g1 - g2) ** 2 + (b1 - b2) ** 2)\n', (109, 159), False, 'import math\n')] |
import numpy as np
import scipy
import scipy.io
import pylab
import numpy
import glob
import pyfits
def mklc(t, nspot=200, incl=(scipy.pi)*5./12., amp=1., tau=30.5, p=10.0):
diffrot = 0.
''' This is a simplified version of the class-based routines in
spot_model.py. It generates a light curves for dark, p... | [
"scipy.ones",
"scipy.zeros_like",
"scipy.sqrt",
"scipy.exp",
"scipy.ones_like",
"scipy.sin",
"scipy.cos",
"scipy.rand"
] | [((1870, 1892), 'scipy.zeros_like', 'scipy.zeros_like', (['time'], {}), '(time)\n', (1886, 1892), False, 'import scipy\n'), ((1906, 1928), 'scipy.zeros_like', 'scipy.zeros_like', (['time'], {}), '(time)\n', (1922, 1928), False, 'import scipy\n'), ((1943, 1965), 'scipy.zeros_like', 'scipy.zeros_like', (['time'], {}), '(... |
from collections import defaultdict
import json
import re
import time
from urllib.parse import urlparse
import uuid
import boto3
import boto3.exceptions
import botocore.exceptions
import markus
import redis.exceptions
import requests
import requests.exceptions
from sqlalchemy import select
import sqlalchemy.exc
from ... | [
"ichnaea.models.ExportConfig.get",
"ichnaea.models.DataMap.scale",
"ichnaea.models.ExportConfig.all",
"urllib.parse.urlparse",
"ichnaea.models.content.encode_datamap_grid",
"re.compile",
"ichnaea.models.DataMap.shard_id",
"ichnaea.models.Report.create",
"json.dumps",
"time.sleep",
"ichnaea.util.... | [((698, 733), 're.compile', 're.compile', (['"""\\\\s"""'], {'flags': 're.UNICODE'}), "('\\\\s', flags=re.UNICODE)\n", (708, 733), False, 'import re\n'), ((745, 765), 'markus.get_metrics', 'markus.get_metrics', ([], {}), '()\n', (763, 765), False, 'import markus\n'), ((1442, 1459), 'collections.defaultdict', 'defaultdi... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for the fseventsd record event formatter."""
from __future__ import unicode_literals
import unittest
from plaso.formatters import fseventsd
from tests.formatters import test_lib
class FseventsdFormatterTest(test_lib.EventFormatterTestCase):
"""Tests for the... | [
"unittest.main",
"plaso.formatters.fseventsd.FSEventsdEventFormatter"
] | [((959, 974), 'unittest.main', 'unittest.main', ([], {}), '()\n', (972, 974), False, 'import unittest\n'), ((449, 484), 'plaso.formatters.fseventsd.FSEventsdEventFormatter', 'fseventsd.FSEventsdEventFormatter', ([], {}), '()\n', (482, 484), False, 'from plaso.formatters import fseventsd\n'), ((657, 692), 'plaso.formatt... |
from keras.callbacks import ModelCheckpoint,Callback,LearningRateScheduler,TensorBoard
from keras.models import load_model
import random
import numpy as np
from scipy import misc
import gc
from keras.optimizers import Adam
from imageio import imread
from datetime import datetime
import os
import json
import models
from... | [
"os.listdir",
"random.shuffle",
"os.makedirs",
"keras.callbacks.ModelCheckpoint",
"argparse.ArgumentParser",
"config.Config",
"keras.callbacks.TensorBoard",
"models.modelCreator",
"datetime.datetime.now",
"utils.LrPolicy",
"utils.DataLoader"
] | [((434, 466), 'argparse.ArgumentParser', 'argparse.ArgumentParser', (['"""train"""'], {}), "('train')\n", (457, 466), False, 'import argparse\n'), ((639, 647), 'config.Config', 'Config', ([], {}), '()\n', (645, 647), False, 'from config import Config\n'), ((815, 860), 'os.makedirs', 'os.makedirs', (["(conf.logPath + '/... |
import unittest
import numpy
import chainer
from chainer import cuda
from chainer import functions
from chainer import gradient_check
from chainer import testing
from chainer.testing import attr
@testing.parameterize(*testing.product({
'shape': [(3, 4), ()],
'dtype': [numpy.float16, numpy.float32, numpy.flo... | [
"numpy.prod",
"chainer.Variable",
"chainer.testing.run_module",
"chainer.testing.product",
"chainer.functions.Flatten",
"chainer.functions.flatten",
"numpy.random.uniform",
"chainer.cuda.to_gpu"
] | [((1406, 1444), 'chainer.testing.run_module', 'testing.run_module', (['__name__', '__file__'], {}), '(__name__, __file__)\n', (1424, 1444), False, 'from chainer import testing\n'), ((678, 702), 'chainer.Variable', 'chainer.Variable', (['x_data'], {}), '(x_data)\n', (694, 702), False, 'import chainer\n'), ((715, 735), '... |
# Generated by Django 3.0.3 on 2020-03-24 09:59
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('exercises', '0018_photo_file'),
]
operations = [
migrations.CreateModel(
na... | [
"django.db.models.TextField",
"django.db.models.ForeignKey",
"django.db.models.AutoField",
"django.db.models.DateTimeField",
"django.db.models.URLField",
"django.db.models.CharField"
] | [((379, 472), '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", (395, 472), False, 'from django.db import migrations, models\... |
from dagster import check
from .house import Lakehouse
from .table import create_lakehouse_table_def
class SnowflakeLakehouse(Lakehouse):
def __init__(self):
pass
def hydrate(self, _context, _table_type, _table_metadata, table_handle, _dest_metadata):
return None
def materialize(self, c... | [
"dagster.check.opt_dict_param",
"dagster.check.opt_set_param"
] | [((562, 596), 'dagster.check.opt_dict_param', 'check.opt_dict_param', (['tags', '"""tags"""'], {}), "(tags, 'tags')\n", (582, 596), False, 'from dagster import check\n'), ((705, 774), 'dagster.check.opt_set_param', 'check.opt_set_param', (['required_resource_keys', '"""required_resource_keys"""'], {}), "(required_resou... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2018 Brno University of Technology FIT
# Author: <NAME> <<EMAIL>>
# All Rights Reserved
import os
import logging
import pickle
import multiprocessing
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
from vbdiar.features.segments... | [
"logging.getLogger",
"numpy.mean",
"pickle.dump",
"sklearn.metrics.pairwise.cosine_similarity",
"vbdiar.embeddings.embedding.extract_embeddings",
"numpy.std",
"os.path.join",
"pickle.load",
"os.path.isfile",
"numpy.array",
"os.path.dirname",
"multiprocessing.Pool",
"numpy.concatenate",
"vb... | [((488, 515), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (505, 515), False, 'import logging\n'), ((1308, 1336), 'multiprocessing.Pool', 'multiprocessing.Pool', (['n_jobs'], {}), '(n_jobs)\n', (1328, 1336), False, 'import multiprocessing\n'), ((3560, 3623), 'vbdiar.embeddings.embedding... |
import datetime
import re
from .exceptions import ObjectIsNotADate
def format_date(value, format="%d %M %Y"):
regex = re.match(r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})", value)
if regex is not None:
date = datetime.date(
int(regex.group("year")),
int(regex.group("mont... | [
"re.match"
] | [((125, 194), 're.match', 're.match', (['"""(?P<year>\\\\d{4})-(?P<month>\\\\d{2})-(?P<day>\\\\d{2})"""', 'value'], {}), "('(?P<year>\\\\d{4})-(?P<month>\\\\d{2})-(?P<day>\\\\d{2})', value)\n", (133, 194), False, 'import re\n')] |
import numpy as np
import os
import logging
from sklearn.model_selection import train_test_split
DATASET_ROOT_FOLDER = os.path.abspath('datasets')
class DataLoader:
train = None
validation = None
test = None
mode = None
partial_dataset = None
@staticmethod
def load(train_path=None, valid... | [
"numpy.reshape",
"os.path.join",
"os.path.abspath",
"numpy.loadtxt",
"numpy.random.permutation"
] | [((120, 147), 'os.path.abspath', 'os.path.abspath', (['"""datasets"""'], {}), "('datasets')\n", (135, 147), False, 'import os\n'), ((3261, 3277), 'numpy.loadtxt', 'np.loadtxt', (['path'], {}), '(path)\n', (3271, 3277), True, 'import numpy as np\n'), ((3810, 3877), 'numpy.reshape', 'np.reshape', (['images', '[images.sha... |
from os.path import join
FAAS_ROOT="/lhome/trulsas/faas-profiler"
WORKLOAD_SPECS=join(FAAS_ROOT, "specs", "workloads")
#FAAS_ROOT="/home/truls/uni/phd/faas-profiler"
WSK_PATH = "wsk"
OPENWHISK_PATH = "/lhome/trulsas/openwhisk"
#: Location of output data
DATA_DIR = join(FAAS_ROOT, "..", "profiler_results")
SYSTEM_CPU... | [
"os.path.join"
] | [((82, 119), 'os.path.join', 'join', (['FAAS_ROOT', '"""specs"""', '"""workloads"""'], {}), "(FAAS_ROOT, 'specs', 'workloads')\n", (86, 119), False, 'from os.path import join\n'), ((267, 308), 'os.path.join', 'join', (['FAAS_ROOT', '""".."""', '"""profiler_results"""'], {}), "(FAAS_ROOT, '..', 'profiler_results')\n", (... |
'''
pymmh3 was written by <NAME> and enhanced by <NAME>, and is placed in the public
domain. The authors hereby disclaim copyright to this source code.
pure python implementation of the murmur3 hash algorithm
https://code.google.com/p/smhasher/wiki/MurmurHash3
This was written for the times when you do not want to c... | [
"argparse.ArgumentParser"
] | [((13771, 13846), 'argparse.ArgumentParser', 'argparse.ArgumentParser', (['"""pymurmur3"""', '"""pymurmur [options] "string to hash\\""""'], {}), '(\'pymurmur3\', \'pymurmur [options] "string to hash"\')\n', (13794, 13846), False, 'import argparse\n')] |
import asyncio
import discord
from datetime import datetime
from operator import itemgetter
from discord.ext import commands
from Cogs import Nullify
from Cogs import DisplayName
from Cogs import UserTime
from Cogs import Message
def setup(bot):
# Add the bot... | [
"Cogs.DisplayName.name",
"Cogs.UserTime.getUserTime",
"Cogs.Nullify.clean",
"Cogs.Message.EmbedText",
"Cogs.DisplayName.memberForName",
"Cogs.DisplayName.memberForID",
"discord.Embed",
"discord.ext.commands.command"
] | [((1159, 1194), 'discord.ext.commands.command', 'commands.command', ([], {'pass_context': '(True)'}), '(pass_context=True)\n', (1175, 1194), False, 'from discord.ext import commands\n'), ((6950, 6985), 'discord.ext.commands.command', 'commands.command', ([], {'pass_context': '(True)'}), '(pass_context=True)\n', (6966, ... |
import random
import torch.utils.data.sampler
class BalancedBatchSampler(torch.utils.data.sampler.BatchSampler):
def __init__(
self,
dataset_labels,
batch_size=1,
steps=None,
n_classes=0,
n_samples=2
):
""" Create a balanced batch sampler for label based... | [
"random.sample"
] | [((1796, 1845), 'random.sample', 'random.sample', (['self.labels_subset', 'self.n_classes'], {}), '(self.labels_subset, self.n_classes)\n', (1809, 1845), False, 'import random\n'), ((2535, 2576), 'random.sample', 'random.sample', (['batch_ids', 'self.batch_size'], {}), '(batch_ids, self.batch_size)\n', (2548, 2576), Fa... |
#!/usr/bin/env python
"""
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");... | [
"re.match"
] | [((1272, 1337), 're.match', 're.match', (['"""([^/@]+)(?:/[^@])?(?:@.*)?"""', 'normalized_principal_name'], {}), "('([^/@]+)(?:/[^@])?(?:@.*)?', normalized_principal_name)\n", (1280, 1337), False, 'import re\n')] |
import pytest
from httmock import urlmatch, HTTMock
from util.config import URLSchemeAndHostname
from util.config.validator import ValidatorContext
from util.config.validators import ConfigValidationException
from util.config.validators.validate_bitbucket_trigger import BitbucketTriggerValidator
from test.fixtures i... | [
"util.config.URLSchemeAndHostname",
"httmock.HTTMock",
"util.config.validator.ValidatorContext",
"pytest.raises",
"util.config.validators.validate_bitbucket_trigger.BitbucketTriggerValidator",
"httmock.urlmatch"
] | [((753, 780), 'util.config.validators.validate_bitbucket_trigger.BitbucketTriggerValidator', 'BitbucketTriggerValidator', ([], {}), '()\n', (778, 780), False, 'from util.config.validators.validate_bitbucket_trigger import BitbucketTriggerValidator\n'), ((952, 984), 'httmock.urlmatch', 'urlmatch', ([], {'netloc': '"""bi... |
""" BigGAN: The Authorized Unofficial PyTorch release
Code by <NAME> and <NAME>
This code is an unofficial reimplementation of
"Large-Scale GAN Training for High Fidelity Natural Image Synthesis,"
by <NAME>, <NAME>, and <NAME> (arXiv 1809.11096).
Let's go.
"""
import datetime
import time
import torc... | [
"datetime.datetime.fromtimestamp",
"utils.prepare_root",
"dataset.get_data_loaders",
"utils.prepare_z_y",
"train_fns.save_and_sample",
"BigGAN.Generator",
"time.perf_counter",
"utils.update_config_roots",
"train_fns.create_train_fn",
"utils.ema",
"BigGAN.G_D",
"BigGAN.Discriminator",
"utils.... | [((1176, 1209), 'utils.update_config_roots', 'utils.update_config_roots', (['config'], {}), '(config)\n', (1201, 1209), False, 'import utils\n'), ((1249, 1279), 'utils.seed_rng', 'utils.seed_rng', (["config['seed']"], {}), "(config['seed'])\n", (1263, 1279), False, 'import utils\n'), ((1324, 1350), 'utils.prepare_root'... |
# Ce fichier contient (au moins) cinq erreurs.
# Instructions:
# - tester jusqu'ร atteindre 100% de couverture;
# - corriger les bugs;"
# - envoyer le diff ou le dรฉpรดt git par email."""
import hypothesis
from hypothesis import given, settings
from hypothesis.strategies import integers, lists
class BinHeap:
#st... | [
"hypothesis.settings",
"hypothesis.strategies.integers"
] | [((2854, 2880), 'hypothesis.settings', 'settings', ([], {'max_examples': '(100)'}), '(max_examples=100)\n', (2862, 2880), False, 'from hypothesis import given, settings\n'), ((3612, 3639), 'hypothesis.settings', 'settings', ([], {'max_examples': '(1000)'}), '(max_examples=1000)\n', (3620, 3639), False, 'from hypothesis... |
from typing import List, Tuple
from omegaconf import DictConfig
import torch
import torch.nn as nn
import torch.nn.functional as F
from rlcycle.common.abstract.loss import Loss
class DQNLoss(Loss):
"""Compute double DQN loss"""
def __init__(self, hyper_params: DictConfig, use_cuda: bool):
Loss.__in... | [
"torch.log",
"torch.mean",
"torch.linspace",
"torch.no_grad",
"rlcycle.common.abstract.loss.Loss.__init__",
"torch.clamp"
] | [((311, 354), 'rlcycle.common.abstract.loss.Loss.__init__', 'Loss.__init__', (['self', 'hyper_params', 'use_cuda'], {}), '(self, hyper_params, use_cuda)\n', (324, 354), False, 'from rlcycle.common.abstract.loss import Loss\n'), ((1206, 1249), 'rlcycle.common.abstract.loss.Loss.__init__', 'Loss.__init__', (['self', 'hyp... |
# -*- coding: utf8 -*-
# Copyright (C) PyZMQ Developers
# Distributed under the terms of the Modified BSD License.
import os
import platform
import time
import pytest
import zmq
from zmq.tests import BaseZMQTestCase, skip_pypy
class TestDraftSockets(BaseZMQTestCase):
def setUp(self):
if not zmq.DRAFT_AP... | [
"pytest.skip",
"time.sleep"
] | [((341, 377), 'pytest.skip', 'pytest.skip', (['"""draft api unavailable"""'], {}), "('draft api unavailable')\n", (352, 377), False, 'import pytest\n'), ((1258, 1273), 'time.sleep', 'time.sleep', (['(0.1)'], {}), '(0.1)\n', (1268, 1273), False, 'import time\n')] |
# -*- coding:utf-8 -*-
# Author: RubanSeven
# import cv2
import numpy as np
# from transform import get_perspective_transform, warp_perspective
from warp_mls import WarpMLS
def distort(src, segment):
img_h, img_w = src.shape[:2]
cut = img_w // segment
thresh = cut // 3
# thresh = img_h... | [
"warp_mls.WarpMLS",
"numpy.random.randint",
"numpy.arange"
] | [((934, 958), 'numpy.arange', 'np.arange', (['(1)', 'segment', '(1)'], {}), '(1, segment, 1)\n', (943, 958), True, 'import numpy as np\n'), ((1373, 1417), 'warp_mls.WarpMLS', 'WarpMLS', (['src', 'src_pts', 'dst_pts', 'img_w', 'img_h'], {}), '(src, src_pts, dst_pts, img_w, img_h)\n', (1380, 1417), False, 'from warp_mls ... |
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def addEdge(self, starting_vertex, end_vertex):
self.graph[starting_vertex].append(end_vertex)
def printAllPaths(self, starting_vertex, target_vertex):
visitedVertices = defaultdic... | [
"collections.defaultdict"
] | [((96, 113), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (107, 113), False, 'from collections import defaultdict\n'), ((310, 327), 'collections.defaultdict', 'defaultdict', (['bool'], {}), '(bool)\n', (321, 327), False, 'from collections import defaultdict\n')] |
from devito.ir import Call
from devito.passes.iet.definitions import DataManager
from devito.passes.iet.langbase import LangBB
__all__ = ['CBB', 'CDataManager']
class CBB(LangBB):
mapper = {
'aligned': lambda i:
'__attribute__((aligned(%d)))' % i,
'host-alloc': lambda i, j, k:
... | [
"devito.ir.Call"
] | [((326, 359), 'devito.ir.Call', 'Call', (['"""posix_memalign"""', '(i, j, k)'], {}), "('posix_memalign', (i, j, k))\n", (330, 359), False, 'from devito.ir import Call\n'), ((404, 422), 'devito.ir.Call', 'Call', (['"""free"""', '(i,)'], {}), "('free', (i,))\n", (408, 422), False, 'from devito.ir import Call\n')] |
# PyTorch
import torch
from torch.utils.data import IterableDataset, DataLoader
from donkeycar.utils import train_test_split
from donkeycar.parts.tub_v2 import Tub
from torchvision import transforms
from typing import List, Any
from donkeycar.pipeline.types import TubRecord, TubDataset
from donkeycar.pipeline.sequence ... | [
"donkeycar.pipeline.sequence.TubSequence",
"donkeycar.utils.train_test_split",
"torch.tensor",
"donkeycar.parts.tub_v2.Tub",
"torchvision.transforms.Normalize",
"torch.utils.data.DataLoader",
"torchvision.transforms.Resize",
"torchvision.transforms.ToTensor",
"donkeycar.pipeline.types.TubRecord",
... | [((1394, 1429), 'torchvision.transforms.Compose', 'transforms.Compose', (['transform_items'], {}), '(transform_items)\n', (1412, 1429), False, 'from torchvision import transforms\n'), ((1223, 1244), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (1242, 1244), False, 'from torchvision import... |
import os
from tornado.template import Template
__SNIPPET__ = os.path.join(os.path.dirname(os.path.abspath(__file__)), '_snippet')
def T(name, **kw):
t = Template(open(os.path.join(__SNIPPET__, name + '.html'), 'rb').read())
return t.generate(**dict([('template_file', name)] + globals().items() + kw.items()))
| [
"os.path.abspath",
"os.path.join"
] | [((92, 117), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (107, 117), False, 'import os\n'), ((172, 213), 'os.path.join', 'os.path.join', (['__SNIPPET__', "(name + '.html')"], {}), "(__SNIPPET__, name + '.html')\n", (184, 213), False, 'import os\n')] |
"""
Support for getting the disk temperature of a host.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.hddtemp/
"""
import logging
from datetime import timedelta
from telnetlib import Telnet
import voluptuous as vol
import homeassistant.helpers.... | [
"logging.getLogger",
"datetime.timedelta",
"voluptuous.Optional",
"voluptuous.All",
"telnetlib.Telnet"
] | [((577, 604), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (594, 604), False, 'import logging\n'), ((767, 787), 'datetime.timedelta', 'timedelta', ([], {'minutes': '(1)'}), '(minutes=1)\n', (776, 787), False, 'from datetime import timedelta\n'), ((836, 872), 'voluptuous.Optional', 'vol.... |
import telegram
from django.conf import settings
from django.shortcuts import redirect
from django.utils.decorators import method_decorator
from django.views.generic import View
from django.views.decorators.csrf import csrf_exempt
from braces.views import CsrfExemptMixin
from rest_framework.authentication import Bas... | [
"rest_framework.response.Response",
"django.utils.decorators.method_decorator"
] | [((580, 626), 'django.utils.decorators.method_decorator', 'method_decorator', (['csrf_exempt'], {'name': '"""dispatch"""'}), "(csrf_exempt, name='dispatch')\n", (596, 626), False, 'from django.utils.decorators import method_decorator\n'), ((1264, 1299), 'rest_framework.response.Response', 'Response', ([], {'status': 's... |
import os
from datetime import datetime
from os.path import join
import pathlib
from tqdm import tqdm
import argparse
import torch
from torch import nn, optim
from torch.autograd import Variable
import torchvision
from torchvision.transforms import Pad
from torchvision.utils import make_grid
import repackage
repackage... | [
"utils.Optimizers",
"argparse.ArgumentParser",
"repackage.up",
"imagenet.config.get_cfg_defaults",
"pathlib.Path",
"torch.load",
"os.path.join",
"imagenet.models.CGN",
"os.path.isfile",
"datetime.datetime.now",
"torch.cuda.is_available",
"torch.save",
"torch.no_grad",
"torchvision.transfor... | [((311, 325), 'repackage.up', 'repackage.up', ([], {}), '()\n', (323, 325), False, 'import repackage\n'), ((1569, 1619), 'os.path.join', 'join', (['sample_path', "(f'cls_sheet_' + ep_str + '.png')"], {}), "(sample_path, f'cls_sheet_' + ep_str + '.png')\n", (1573, 1619), False, 'from os.path import join\n'), ((3970, 401... |
import logging
from typing import Dict, List, Optional
import numpy as np
import qiskit
from qiskit.circuit import Barrier, Delay, Reset
from qiskit.circuit.library import (CRXGate, CRYGate, CRZGate, CZGate,
PhaseGate, RXGate, RYGate, RZGate, U1Gate,
... | [
"logging.getLogger",
"qiskit.circuit.quantumcircuit.QuantumCircuit",
"qiskit.circuit.Delay",
"numpy.abs",
"logging.info",
"qiskit.dagcircuit.DAGCircuit",
"qiskit.converters.circuit_to_dag.circuit_to_dag",
"numpy.mod"
] | [((785, 812), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (802, 812), False, 'import logging\n'), ((5004, 5021), 'qiskit.circuit.quantumcircuit.QuantumCircuit', 'QuantumCircuit', (['(1)'], {}), '(1)\n', (5018, 5021), False, 'from qiskit.circuit.quantumcircuit import QuantumCircuit\n'),... |
def help():
return '''
Isotropic-Anisotropic Filtering Norm Nesterov Algorithm
Solves the filtering norm minimization + quadratic term problem
Nesterov algorithm, with continuation:
argmin_x || iaFN(x) ||_1/2 subjected to ||b - Ax||_2^2 < delta
If no filter is provided, solves the L1.
Continuation is perf... | [
"IAFNNesterov.IAFNNesterov",
"fil2mat.fil2mat",
"numpy.power",
"scipy.sparse.issparse",
"numpy.array",
"numpy.matmul",
"numpy.vstack",
"numpy.transpose"
] | [((4800, 4835), 'numpy.power', 'np.power', (['(muf / mu0)', '(1 / MaxIntIter)'], {}), '(muf / mu0, 1 / MaxIntIter)\n', (4808, 4835), True, 'import numpy as np\n'), ((4856, 4894), 'numpy.power', 'np.power', (['(TolVar / 0.1)', '(1 / MaxIntIter)'], {}), '(TolVar / 0.1, 1 / MaxIntIter)\n', (4864, 4894), True, 'import nump... |
import asyncio
import discord
# Just with a function to add to the bot.
async def on_message(message):
if not message.author.bot:
await message.channel.send(f"{message.author.mention} a envoyรฉ un message!")
# A Listener already created with the function
from discordEasy.objects import Listener
async def on_messa... | [
"discordEasy.objects.Listener"
] | [((463, 483), 'discordEasy.objects.Listener', 'Listener', (['on_message'], {}), '(on_message)\n', (471, 483), False, 'from discordEasy.objects import Listener\n')] |
import os
import random
from flask import Flask, request, send_from_directory
from werkzeug.utils import secure_filename
from pianonet.core.pianoroll import Pianoroll
from pianonet.model_inspection.performance_from_pianoroll import get_performance_from_pianoroll
app = Flask(__name__)
base_path = "/app/"
# base_pat... | [
"flask.request.args.get",
"os.path.exists",
"flask.send_from_directory",
"flask.Flask",
"os.path.join",
"flask.request.form.get",
"pianonet.core.pianoroll.Pianoroll",
"werkzeug.utils.secure_filename",
"random.randint"
] | [((272, 287), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (277, 287), False, 'from flask import Flask, request, send_from_directory\n'), ((387, 434), 'os.path.join', 'os.path.join', (['base_path', '"""data"""', '"""performances"""'], {}), "(base_path, 'data', 'performances')\n", (399, 434), False, 'impo... |
import dash
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import logging
import json
import os
import pandas as pd
from datetime import datetime
from datetime import timedelta
fro... | [
"logging.getLogger",
"datetime.datetime",
"plotly.graph_objects.Bar",
"requests.post",
"plotly.subplots.make_subplots",
"urllib.parse.urlparse",
"json.dumps",
"os.environ.get",
"plotly.graph_objects.Scatter",
"dash_html_components.H1",
"pandas.DataFrame",
"datetime.timedelta",
"dash.Dash",
... | [((369, 396), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (386, 396), False, 'import logging\n'), ((552, 606), 'os.environ.get', 'os.environ.get', (['"""CF_INSTANCE_INTERNAL_IP"""', '"""127.0.0.1"""'], {}), "('CF_INSTANCE_INTERNAL_IP', '127.0.0.1')\n", (566, 606), False, 'import os\n')... |
from robot import __version__ as ROBOT_VERSION
import sys
import tempfile
import textwrap
import unittest
import shutil
import subprocess
class PabotOrderingGroupTest(unittest.TestCase):
def setUp(self):
self.tmpdir = tempfile.mkdtemp()
def tearDown(self):
shutil.rmtree(self.tmpdir)
def ... | [
"textwrap.dedent",
"tempfile.mkdtemp",
"shutil.rmtree"
] | [((232, 250), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (248, 250), False, 'import tempfile\n'), ((284, 310), 'shutil.rmtree', 'shutil.rmtree', (['self.tmpdir'], {}), '(self.tmpdir)\n', (297, 310), False, 'import shutil\n'), ((457, 482), 'textwrap.dedent', 'textwrap.dedent', (['testfile'], {}), '(testfi... |
import torch
ckp_path = './checkpoints/fashion_PATN/latest_net_netG.pth'
save_path = './checkpoints/fashion_PATN_v1.0/latest_net_netG.pth'
states_dict = torch.load(ckp_path)
states_dict_new = states_dict.copy()
for key in states_dict.keys():
if "running_var" in key or "running_mean" in key:
del states_dict_new[key]... | [
"torch.load",
"torch.save"
] | [((154, 174), 'torch.load', 'torch.load', (['ckp_path'], {}), '(ckp_path)\n', (164, 174), False, 'import torch\n'), ((322, 360), 'torch.save', 'torch.save', (['states_dict_new', 'save_path'], {}), '(states_dict_new, save_path)\n', (332, 360), False, 'import torch\n')] |
import multiprocessing
# ========== #Python3 - concurrent
from math import floor, sqrt
numbers = [
112272537195293,
112582718962171,
112272537095293,
115280098190773,
115797840077099,
1099726829285419]
# numbers = [33, 44, 55, 275]
def lowest_factor(n, _start=3):
if n % 2 == 0:
re... | [
"math.sqrt",
"multiprocessing.Pool"
] | [((749, 782), 'multiprocessing.Pool', 'multiprocessing.Pool', ([], {'processes': '(5)'}), '(processes=5)\n', (769, 782), False, 'import multiprocessing\n'), ((354, 361), 'math.sqrt', 'sqrt', (['n'], {}), '(n)\n', (358, 361), False, 'from math import floor, sqrt\n')] |
from setuptools import find_packages, setup
setup(
name='src',
packages=find_packages(),
version='0.1.0',
description='Project: Nowcasting the air pollution using online search log',
author='<NAME>(IR Lab)',
license='MIT',
)
| [
"setuptools.find_packages"
] | [((81, 96), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (94, 96), False, 'from setuptools import find_packages, setup\n')] |
import ast
from json_codegen.generators.python3_marshmallow.utils import Annotations, class_name
class ObjectGenerator(object):
@staticmethod
def _get_property_name(node_assign):
name = node_assign.targets[0]
return name.id
@staticmethod
def _nesting_class(node_assign):
for n... | [
"json_codegen.generators.python3_marshmallow.utils.class_name",
"ast.walk",
"ast.Str",
"ast.ClassDef",
"ast.arg",
"ast.Dict",
"ast.Name",
"json_codegen.generators.python3_marshmallow.utils.Annotations",
"ast.FunctionDef",
"ast.NameConstant",
"ast.Pass"
] | [((327, 348), 'ast.walk', 'ast.walk', (['node_assign'], {}), '(node_assign)\n', (335, 348), False, 'import ast\n'), ((2112, 2133), 'ast.walk', 'ast.walk', (['node_assign'], {}), '(node_assign)\n', (2120, 2133), False, 'import ast\n'), ((2511, 2532), 'ast.walk', 'ast.walk', (['node_assign'], {}), '(node_assign)\n', (251... |
import BboxToolkit as bt
import pickle
import copy
import numpy as np
path1="/home/hnu1/GGM/OBBDetection/work_dir/oriented_obb_contrast_catbalance/dets.pkl"
path2="/home/hnu1/GGM/OBBDetection/data/FaIR1M/test/annfiles/ori_annfile.pkl"#
with open(path2,'rb') as f: #/home/disk/FAIR1M_1000_split/val/annfiles/ori_... | [
"numpy.append",
"BboxToolkit.obb2poly",
"pickle.load",
"copy.deepcopy"
] | [((344, 358), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (355, 358), False, 'import pickle\n'), ((402, 416), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (413, 416), False, 'import pickle\n'), ((430, 452), 'copy.deepcopy', 'copy.deepcopy', (['obbdets'], {}), '(obbdets)\n', (443, 452), False, 'import cop... |
import taichi as ti
import utils
from apic_extension import *
@ti.data_oriented
class Initializer3D: # tmp initializer
def __init__(self, res, x0, y0, z0, x1, y1, z1):
self.res = res
self.x0 = int(res * x0)
self.y0 = int(res * y0)
self.z0 = int(res * z0)
self.x1 = int(res * ... | [
"taichi.template"
] | [((443, 456), 'taichi.template', 'ti.template', ([], {}), '()\n', (454, 456), True, 'import taichi as ti\n')] |
# (C) Copyright 2016-2017 Hewlett Packard Enterprise Development LP
# Copyright 2017 FUJITSU 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... | [
"oslo_config.cfg.PortOpt",
"oslo_config.cfg.OptGroup",
"oslo_config.cfg.StrOpt",
"oslo_config.cfg.HostAddressOpt"
] | [((1281, 1328), 'oslo_config.cfg.OptGroup', 'cfg.OptGroup', ([], {'name': '"""influxdb"""', 'title': '"""influxdb"""'}), "(name='influxdb', title='influxdb')\n", (1293, 1328), False, 'from oslo_config import cfg\n'), ((697, 790), 'oslo_config.cfg.StrOpt', 'cfg.StrOpt', (['"""database_name"""'], {'help': '"""database na... |
import json
your_json = '["foo", {"bar":["baz", null, 1.0, 2]}]'
parsed = json.loads(your_json)
print(type(your_json))
print(type(parsed))
#print(json.dumps(parsed, indent=4, sort_keys=True)) | [
"json.loads"
] | [((75, 96), 'json.loads', 'json.loads', (['your_json'], {}), '(your_json)\n', (85, 96), False, 'import json\n')] |
import matplotlib
matplotlib.use('Agg')
import numpy as np
from astropy.tests.helper import pytest
from .. import FITSFigure
def test_grid_addremove():
data = np.zeros((16, 16))
f = FITSFigure(data)
f.add_grid()
f.remove_grid()
f.add_grid()
f.close()
def test_grid_showhide():
data = np... | [
"matplotlib.use",
"numpy.zeros",
"astropy.tests.helper.pytest.raises"
] | [((18, 39), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (32, 39), False, 'import matplotlib\n'), ((167, 185), 'numpy.zeros', 'np.zeros', (['(16, 16)'], {}), '((16, 16))\n', (175, 185), True, 'import numpy as np\n'), ((318, 336), 'numpy.zeros', 'np.zeros', (['(16, 16)'], {}), '((16, 16))\n', (3... |
import os, sys
class Object:
## @name constructor
def __init__(self, V):
self.value = V
self.nest = []
def box(self, that):
if isinstance(that, Object): return that
if isinstance(that, str): return S(that)
raise TypeError(['box', type(that), that])
## @name d... | [
"os.urandom",
"os.mkdir",
"os.getcwd"
] | [((2736, 2755), 'os.mkdir', 'os.mkdir', (['self.path'], {}), '(self.path)\n', (2744, 2755), False, 'import os, sys\n'), ((4051, 4062), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (4060, 4062), False, 'import os, sys\n'), ((7598, 7612), 'os.urandom', 'os.urandom', (['(34)'], {}), '(34)\n', (7608, 7612), False, 'import o... |
from torch.optim.lr_scheduler import StepLR, ReduceLROnPlateau, OneCycleLR
def step_lr(optimizer, step_size, gamma=0.1, last_epoch=-1):
"""Create LR step scheduler.
Args:
optimizer (torch.optim): Model optimizer.
step_size (int): Frequency for changing learning rate.
gamma (float): Fa... | [
"torch.optim.lr_scheduler.OneCycleLR",
"torch.optim.lr_scheduler.ReduceLROnPlateau",
"torch.optim.lr_scheduler.StepLR"
] | [((512, 586), 'torch.optim.lr_scheduler.StepLR', 'StepLR', (['optimizer'], {'step_size': 'step_size', 'gamma': 'gamma', 'last_epoch': 'last_epoch'}), '(optimizer, step_size=step_size, gamma=gamma, last_epoch=last_epoch)\n', (518, 586), False, 'from torch.optim.lr_scheduler import StepLR, ReduceLROnPlateau, OneCycleLR\n... |
# Copyright 2019 TerraPower, LLC
#
# 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 writi... | [
"armi.reactor.grids.hexGridFromPitch",
"armi.reactor.geometry.SystemLayoutInput",
"armi.reactor.blueprints.Blueprints",
"armi.reactor.zones.Zone",
"armi.reactor.zones.createHotZones",
"armi.utils.pathTools.armiAbsDirFromName",
"armi.reactor.zones.splitZones",
"armi.settings.getMasterCs",
"copy.deepc... | [((1049, 1087), 'armi.utils.pathTools.armiAbsDirFromName', 'pathTools.armiAbsDirFromName', (['__name__'], {}), '(__name__)\n', (1077, 1087), False, 'from armi.utils import pathTools\n'), ((10873, 10888), 'unittest.main', 'unittest.main', ([], {}), '()\n', (10886, 10888), False, 'import unittest\n'), ((1164, 1187), 'arm... |
"""empty message
Revision ID: 2018_04_20_data_src_refactor
Revises: 2018_04_11_add_sandbox_topic
Create Date: 2018-04-20 13:03:32.478880
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
from sqlalchemy.dialects.postgresql import ARRAY
revision = '2018_04_20_data_src_refac... | [
"alembic.op.get_bind",
"alembic.op.create_foreign_key",
"alembic.op.drop_constraint",
"sqlalchemy.VARCHAR",
"alembic.op.drop_column",
"sqlalchemy.TEXT",
"alembic.op.execute",
"sqlalchemy.INTEGER",
"sqlalchemy.Enum",
"sqlalchemy.dialects.postgresql.ARRAY"
] | [((520, 582), 'sqlalchemy.Enum', 'sa.Enum', (['"""ADMINISTRATIVE"""', '"""SURVEY"""'], {'name': '"""type_of_data_types"""'}), "('ADMINISTRATIVE', 'SURVEY', name='type_of_data_types')\n", (527, 582), True, 'import sqlalchemy as sa\n'), ((1113, 1126), 'alembic.op.get_bind', 'op.get_bind', ([], {}), '()\n', (1124, 1126), ... |
# Copyright 2013 - Mirantis, Inc.
# Copyright 2015 - StackStorm, Inc.
# Copyright 2015 - 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:/... | [
"mistral.utils.ssh_utils._to_paramiko_private_key",
"mistral_lib.utils.iter_subclasses"
] | [((1498, 1587), 'mistral.utils.ssh_utils._to_paramiko_private_key', 'ssh_utils._to_paramiko_private_key', ([], {'private_key_filename': 'None', 'password': '"""<PASSWORD>"""'}), "(private_key_filename=None, password=\n '<PASSWORD>')\n", (1532, 1587), False, 'from mistral.utils import ssh_utils\n'), ((1099, 1123), 'm... |
import xmltodict
import json
from .models import Tunein
from .utils import _init_session
from .Exceptions import APIException
base_url = 'http://api.shoutcast.com'
tunein_url = 'http://yp.shoutcast.com/{base}?id={id}'
tuneins = [Tunein('/sbin/tunein-station.pls'), Tunein('/sbin/tunein-station.m3u'), Tunein('/sbin/tun... | [
"xmltodict.parse"
] | [((604, 637), 'xmltodict.parse', 'xmltodict.parse', (['response.content'], {}), '(response.content)\n', (619, 637), False, 'import xmltodict\n')] |
from django.core.management.base import BaseCommand, no_translations
from django.contrib.auth.models import Group
from django.conf import settings
import sys
class Command(BaseCommand):
def handle(self, *args, **options):
sys.stdout.write("\nResolving app groups")
app_list = [app_name.lower... | [
"django.contrib.auth.models.Group.objects.get_or_create",
"sys.stdout.write"
] | [((243, 288), 'sys.stdout.write', 'sys.stdout.write', (['"""\nResolving app groups"""'], {}), '("""\nResolving app groups""")\n', (259, 288), False, 'import sys\n'), ((559, 581), 'sys.stdout.write', 'sys.stdout.write', (['"""\n"""'], {}), "('\\n')\n", (575, 581), False, 'import sys\n'), ((438, 480), 'django.contrib.aut... |
"""
Provides usable args and kwargs from inspect.getcallargs.
For Python 3.3 and above, this module is unnecessary and can be achieved using
features from PEP 362:
http://www.python.org/dev/peps/pep-0362/
For example, to override a parameter of some function:
>>> import inspect
>>> def func(a, b=1, c=2,... | [
"collections.namedtuple",
"inspect.signature",
"inspect.getfullargspec",
"inspect.getargspec",
"inspect.getcallargs"
] | [((2471, 2505), 'inspect.getcallargs', 'getcallargs', (['func', '*args'], {}), '(func, *args, **kwargs)\n', (2482, 2505), False, 'from inspect import getcallargs\n'), ((2517, 2537), 'inspect.getfullargspec', 'getfullargspec', (['func'], {}), '(func)\n', (2531, 2537), False, 'from inspect import getfullargspec\n'), ((35... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-06-10 21:25
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('vendors', '0089_auto_20160602_2123'),
]
operations = [
migrations.AlterField... | [
"django.db.models.EmailField"
] | [((399, 466), 'django.db.models.EmailField', 'models.EmailField', ([], {'blank': '(True)', 'max_length': '(254)', 'verbose_name': '"""Email"""'}), "(blank=True, max_length=254, verbose_name='Email')\n", (416, 466), False, 'from django.db import migrations, models\n')] |
import pymongo
from conf import Configuracoes
class Mongo_Database:
""" Singleton com a conexao com o MongoDB """
_instancia = None
def __new__(cls, *args, **kwargs):
if not(cls._instancia):
cls._instancia = super(Mongo_Database, cls).__new__(cls, *args, **kwargs)
return cls._in... | [
"pymongo.MongoClient",
"conf.Configuracoes"
] | [((615, 650), 'pymongo.MongoClient', 'pymongo.MongoClient', (['string_conexao'], {}), '(string_conexao)\n', (634, 650), False, 'import pymongo\n'), ((440, 455), 'conf.Configuracoes', 'Configuracoes', ([], {}), '()\n', (453, 455), False, 'from conf import Configuracoes\n')] |
# Generated by Django 3.1.7 on 2021-03-27 18:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('HackBitApp', '0002_company_photo'),
]
operations = [
migrations.CreateModel(
name='Roadmap',
fields=[
... | [
"django.db.models.ImageField",
"django.db.models.AutoField",
"django.db.models.CharField"
] | [((329, 422), '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", (345, 422), False, 'from django.db import migrations, models\... |
import json
from wptserve.utils import isomorphic_decode
def main(request, response):
origin = request.GET.first(b"origin", request.headers.get(b'origin') or b'none')
if b"check" in request.GET:
token = request.GET.first(b"token")
value = request.server.stash.take(token)
if value is n... | [
"json.dumps",
"wptserve.utils.isomorphic_decode"
] | [((2260, 2279), 'json.dumps', 'json.dumps', (['headers'], {}), '(headers)\n', (2270, 2279), False, 'import json\n'), ((2049, 2077), 'wptserve.utils.isomorphic_decode', 'isomorphic_decode', (['values[0]'], {}), '(values[0])\n', (2066, 2077), False, 'from wptserve.utils import isomorphic_decode\n'), ((2022, 2045), 'wptse... |
#!/usr/bin/env python
import argparse
DELIMITER = "\t"
def merge(genotypes_filename, gq_filename, merged_filename):
with open(genotypes_filename, "r") as genotypes, open(gq_filename, "r") as gq, open(merged_filename, "w") as merged:
# Integrity check: do the files have same columns?
genotypes_... | [
"argparse.ArgumentParser"
] | [((1257, 1360), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '__doc__', 'formatter_class': 'argparse.RawDescriptionHelpFormatter'}), '(description=__doc__, formatter_class=argparse.\n RawDescriptionHelpFormatter)\n', (1280, 1360), False, 'import argparse\n')] |
import tweepy
import traceback
import time
import pymongo
from tweepy import OAuthHandler
from pymongo import MongoClient
from pymongo.cursor import CursorType
twitter_consumer_key = ""
twitter_consumer_secret = ""
twitter_access_token = ""
twitter_access_secret = ""
auth = OAuthHandler(twitter_consumer_key, twitter_... | [
"pymongo.MongoClient",
"tweepy.API",
"time.sleep",
"tweepy.OAuthHandler"
] | [((277, 336), 'tweepy.OAuthHandler', 'OAuthHandler', (['twitter_consumer_key', 'twitter_consumer_secret'], {}), '(twitter_consumer_key, twitter_consumer_secret)\n', (289, 336), False, 'from tweepy import OAuthHandler\n'), ((410, 426), 'tweepy.API', 'tweepy.API', (['auth'], {}), '(auth)\n', (420, 426), False, 'import tw... |
#!/usr/bin/env python
"""Handles Earth Engine service account configuration."""
import ee
# The service account email address authorized by your Google contact.
# Set up a service account as described in the README.
EE_ACCOUNT = '<EMAIL>'
# The private key associated with your service account in Privacy Enhanced
# E... | [
"ee.ServiceAccountCredentials"
] | [((590, 651), 'ee.ServiceAccountCredentials', 'ee.ServiceAccountCredentials', (['EE_ACCOUNT', 'EE_PRIVATE_KEY_FILE'], {}), '(EE_ACCOUNT, EE_PRIVATE_KEY_FILE)\n', (618, 651), False, 'import ee\n')] |
import os
from graphene_sqlalchemy import SQLAlchemyObjectType
from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
POSTGRES_CONNECTION_STRING = (
os.environ.get("POSTGRES_CONNECTION_STRING")
... | [
"sqlalchemy.orm.sessionmaker",
"sqlalchemy.create_engine",
"os.environ.get",
"sqlalchemy.ext.declarative.declarative_base",
"sqlalchemy.Column"
] | [((392, 455), 'sqlalchemy.create_engine', 'create_engine', (['POSTGRES_CONNECTION_STRING'], {'convert_unicode': '(True)'}), '(POSTGRES_CONNECTION_STRING, convert_unicode=True)\n', (405, 455), False, 'from sqlalchemy import Column, Integer, String, create_engine\n'), ((559, 577), 'sqlalchemy.ext.declarative.declarative_... |
# microsig
"""
Author: <NAME>
More detail about the MicroSIG can be found at:
Website:
https://gitlab.com/defocustracking/microsig-python
Publication:
Rossi M, Synthetic image generator for defocusing and astigmatic PIV/PTV, Meas. Sci. Technol., 31, 017003 (2020)
DOI:10.1088/1361-6501/ab42bb.
"""
import n... | [
"numpy.uint8",
"tkinter.filedialog.askdirectory",
"numpy.arccos",
"numpy.sqrt",
"numpy.hstack",
"numpy.array",
"sys.exit",
"numpy.sin",
"numpy.genfromtxt",
"numpy.arange",
"numpy.cross",
"numpy.sort",
"os.path.split",
"numpy.max",
"tkinter.filedialog.askopenfilenames",
"numpy.vstack",
... | [((4177, 4184), 'tkinter.Tk', 'tk.Tk', ([], {}), '()\n', (4182, 4184), True, 'import tkinter as tk\n'), ((4263, 4395), 'tkinter.filedialog.askopenfilenames', 'filedialog.askopenfilenames', ([], {'title': '"""Select settings file"""', 'parent': 'root', 'filetypes': "(('txt files', '*.txt'), ('all files', '*.*'))"}), "(t... |
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from django.contrib.auth.models import User
from django import forms
class UploadFileForm(forms.Form):
title = forms.CharField(max_length=50)
file = forms.FileField()
# If you don't do this you cannot use Bootstrap CSS
class LoginFor... | [
"django.forms.CharField",
"django.forms.PasswordInput",
"django.forms.EmailInput",
"django.forms.TextInput",
"django.forms.FileField"
] | [((192, 222), 'django.forms.CharField', 'forms.CharField', ([], {'max_length': '(50)'}), '(max_length=50)\n', (207, 222), False, 'from django import forms\n'), ((234, 251), 'django.forms.FileField', 'forms.FileField', ([], {}), '()\n', (249, 251), False, 'from django import forms\n'), ((445, 513), 'django.forms.TextInp... |
import pandas as pd
from pandas import DataFrame
df = pd.read_csv('sp500_ohlc.csv', index_col = 'Date', parse_dates=True)
df['H-L'] = df.High - df.Low
# Giving us count (rows), mean (avg), std (standard deviation for the entire
# set), minimum for the set, maximum for the set, and some %s in that range.
print( df.des... | [
"datetime.datetime",
"pandas.read_csv"
] | [((55, 120), 'pandas.read_csv', 'pd.read_csv', (['"""sp500_ohlc.csv"""'], {'index_col': '"""Date"""', 'parse_dates': '(True)'}), "('sp500_ohlc.csv', index_col='Date', parse_dates=True)\n", (66, 120), True, 'import pandas as pd\n'), ((1602, 1632), 'datetime.datetime', 'datetime.datetime', (['(2011)', '(10)', '(1)'], {})... |
import cv2
import numpy as np
import threading
def test():
while 1:
img1=cv2.imread('captured car1.jpg')
print("{}".format(img1.shape))
print("{}".format(img1))
cv2.imshow('asd',img1)
cv2.waitKey(1)
t1 = threading.Thread(target=test)
t1.start()
| [
"threading.Thread",
"cv2.waitKey",
"cv2.imread",
"cv2.imshow"
] | [((250, 279), 'threading.Thread', 'threading.Thread', ([], {'target': 'test'}), '(target=test)\n', (266, 279), False, 'import threading\n'), ((86, 117), 'cv2.imread', 'cv2.imread', (['"""captured car1.jpg"""'], {}), "('captured car1.jpg')\n", (96, 117), False, 'import cv2\n'), ((198, 221), 'cv2.imshow', 'cv2.imshow', (... |
# Copyright 2013 Cloudbase Solutions Srl
#
# Author: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
#
# 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/LICENS... | [
"ceilometer.openstack.common.log.getLogger",
"ceilometer.openstack.common.gettextutils._",
"wmi.WMI"
] | [((1068, 1095), 'ceilometer.openstack.common.log.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1085, 1095), True, 'from ceilometer.openstack.common import log as logging\n'), ((2286, 2339), 'wmi.WMI', 'wmi.WMI', ([], {'moniker': "('//%s/root/virtualization/v2' % host)"}), "(moniker='//%s/root/vi... |
# system
from io import IOBase, StringIO
import os
# 3rd party
import click
# internal
from days import DayFactory
# import logging
# logger = logging.getLogger(__name__)
# logger.setLevel(logging.DEBUG)
# ch = logging.StreamHandler()
# logger.addHandler(ch)
@click.group(invoke_without_command=True)
@click.option... | [
"os.path.exists",
"click.IntRange",
"click.group",
"os.path.join",
"days.DayFactory",
"click.Path",
"io.StringIO"
] | [((266, 306), 'click.group', 'click.group', ([], {'invoke_without_command': '(True)'}), '(invoke_without_command=True)\n', (277, 306), False, 'import click\n'), ((715, 767), 'os.path.join', 'os.path.join', (['input', 'f"""{day:02}_puzzle_{puzzle}.txt"""'], {}), "(input, f'{day:02}_puzzle_{puzzle}.txt')\n", (727, 767), ... |
from matplotlib.colors import LinearSegmentedColormap
from numpy import nan, inf
# Used to reconstruct the colormap in viscm
parameters = {'xp': [-5.4895292543686764, 14.790571669586654, 82.5546687431056, 29.15531114139253, -4.1316769886951761, -13.002076438907238],
'yp': [-35.948168839230306, -42.27337... | [
"viscm.viscm",
"numpy.linspace",
"matplotlib.colors.LinearSegmentedColormap.from_list",
"matplotlib.pyplot.show"
] | [((16621, 16673), 'matplotlib.colors.LinearSegmentedColormap.from_list', 'LinearSegmentedColormap.from_list', (['__file__', 'cm_data'], {}), '(__file__, cm_data)\n', (16654, 16673), False, 'from matplotlib.colors import LinearSegmentedColormap\n'), ((17022, 17032), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n'... |
from sqlalchemy import Integer, Text, DateTime, func, Boolean, text
from models.database_models import Base, Column
class Comment(Base):
__tablename__ = "comment"
id = Column(Integer, primary_key=True, )
user_id = Column(Integer, nullable=False, comment="่ฏ่ฎบ็จๆท็ ID")
post_id = Column(Integer, nullable... | [
"models.database_models.Column",
"sqlalchemy.func.now",
"sqlalchemy.text"
] | [((180, 213), 'models.database_models.Column', 'Column', (['Integer'], {'primary_key': '(True)'}), '(Integer, primary_key=True)\n', (186, 213), False, 'from models.database_models import Base, Column\n'), ((230, 281), 'models.database_models.Column', 'Column', (['Integer'], {'nullable': '(False)', 'comment': '"""่ฏ่ฎบ็จๆท็ ... |
from typing import Callable, Collection, Iterable, List, Union
from data.anagram import anagram_iter
from data.graph import _op_mixin, bloom_mask, bloom_node, bloom_node_reducer
Transformer = Callable[['bloom_node.BloomNode'], 'bloom_node.BloomNode']
_SPACE_MASK = bloom_mask.for_alpha(' ')
def merge_fn(
host: 'b... | [
"data.graph.bloom_mask.lengths_product",
"data.anagram.anagram_iter.from_choices",
"data.graph.bloom_mask.for_alpha",
"data.graph._op_mixin.Op",
"data.graph.bloom_node_reducer.reduce",
"data.graph.bloom_node.BloomNode"
] | [((267, 292), 'data.graph.bloom_mask.for_alpha', 'bloom_mask.for_alpha', (['""" """'], {}), "(' ')\n", (287, 292), False, 'from data.graph import _op_mixin, bloom_mask, bloom_node, bloom_node_reducer\n'), ((946, 1019), 'data.graph.bloom_node_reducer.reduce', 'bloom_node_reducer.reduce', (['host'], {'whitelist': 'whitel... |
import pathlib
import os
from setuptools import setup
# The directory containing this file
HERE = pathlib.Path(__file__).parent
# The text of the README file
README = (HERE / "README.md").read_text()
# specify requirements of your package here
REQUIREMENTS = ['biopython', 'numpy', 'pandas']
setup(name='stacksPairwi... | [
"setuptools.setup",
"pathlib.Path"
] | [((296, 843), 'setuptools.setup', 'setup', ([], {'name': '"""stacksPairwise"""', 'version': '"""0.0.0"""', 'description': '"""Calculate pairwise divergence (pairwise pi) from Stacks `samples.fa` output fle"""', 'long_description': 'README', 'long_description_content_type': '"""text/markdown"""', 'url': '"""https://gith... |
from numpy import array
from pickle import load
from pandas import read_csv
import os
from BioCAT.src.Combinatorics import multi_thread_shuffling, multi_thread_calculating_scores, make_combine, get_score, get_max_aminochain, skipper
# Importing random forest model
modelpath = os.path.dirname(os.path.abspath(__file__)... | [
"BioCAT.src.Combinatorics.multi_thread_shuffling",
"BioCAT.src.Combinatorics.multi_thread_calculating_scores",
"pandas.read_csv",
"BioCAT.src.Combinatorics.get_max_aminochain",
"BioCAT.src.Combinatorics.skipper",
"BioCAT.src.Combinatorics.make_combine",
"BioCAT.src.Combinatorics.get_score",
"os.path.a... | [((939, 1029), 'BioCAT.src.Combinatorics.multi_thread_shuffling', 'multi_thread_shuffling', (['matrix'], {'ShufflingType': '"""module"""', 'iterations': 'iterat', 'threads': 'cpu'}), "(matrix, ShufflingType='module', iterations=iterat,\n threads=cpu)\n", (961, 1029), False, 'from BioCAT.src.Combinatorics import mult... |
import signal
import requests
import time
from math import floor
shutdown = False
MAIN_TAKER = 0.0065
MAIN_MAKER = 0.002
ALT_TAKER = 0.005
ALT_MAKER = 0.0035
TAKER = (MAIN_TAKER + ALT_TAKER)*2
MAKER = MAIN_MAKER + ALT_MAKER
TAKEMAIN = MAIN_TAKER - ALT_MAKER
TAKEALT = ALT_TAKER - MAIN_MAKER
BUFFER = 0.0... | [
"signal.signal",
"requests.Session",
"time.sleep"
] | [((14446, 14490), 'signal.signal', 'signal.signal', (['signal.SIGINT', 'signal.SIG_DFL'], {}), '(signal.SIGINT, signal.SIG_DFL)\n', (14459, 14490), False, 'import signal\n'), ((14549, 14585), 'signal.signal', 'signal.signal', (['signal.SIGINT', 'sigint'], {}), '(signal.SIGINT, sigint)\n', (14562, 14585), False, 'import... |
"""
==========================================
Genrating feedthrough from single instance
==========================================
This example demostrates how to generate a feedthrough wire connection for
a given scalar or vector wires.
**Initial Design**
.. hdl-diagram:: ../../../examples/basic/_initial_design.v... | [
"spydrnet.compose",
"spydrnet_physical.load_netlist_by_name"
] | [((801, 847), 'spydrnet_physical.load_netlist_by_name', 'sdnphy.load_netlist_by_name', (['"""basic_hierarchy"""'], {}), "('basic_hierarchy')\n", (828, 847), True, 'import spydrnet_physical as sdnphy\n'), ((970, 1034), 'spydrnet.compose', 'sdn.compose', (['netlist', '"""_initial_design.v"""'], {'skip_constraints': '(Tru... |
from __future__ import annotations
from typing import Optional, Union
from tools import tools
from exceptions import workflow_exceptions
class Workflow:
"""A class to represent a workflow.
Workflow class provides set of methods to manage state of the workflow.
It allows for tool insertions, removals and... | [
"tools.tools.RootTool"
] | [((916, 936), 'tools.tools.RootTool', 'tools.RootTool', ([], {'id': '(0)'}), '(id=0)\n', (930, 936), False, 'from tools import tools\n')] |
from django.apps import apps
from django.test import override_settings
from wagtail_live.signals import live_page_update
def test_live_page_update_signal_receivers():
assert len(live_page_update.receivers) == 0
@override_settings(
WAGTAIL_LIVE_PUBLISHER="tests.testapp.publishers.DummyWebsocketPublisher"
)
... | [
"django.test.override_settings",
"django.apps.apps.get_app_config",
"wagtail_live.signals.live_page_update.disconnect"
] | [((221, 318), 'django.test.override_settings', 'override_settings', ([], {'WAGTAIL_LIVE_PUBLISHER': '"""tests.testapp.publishers.DummyWebsocketPublisher"""'}), "(WAGTAIL_LIVE_PUBLISHER=\n 'tests.testapp.publishers.DummyWebsocketPublisher')\n", (238, 318), False, 'from django.test import override_settings\n'), ((393,... |
# -*- coding: utf-8 -*-
"""
Script Name:
Author: <NAME>/Jimmy - 3D artist.
Description:
"""
# -------------------------------------------------------------------------------------------------------------
""" Import """
import os
from PySide2.QtWidgets import (QFrame, QStyle, QAbstractItemView, QSizePolicy, ... | [
"PySide2.QtGui.QColor",
"PySide2.QtCore.QDateTime.currentDateTime",
"PySide2.QtCore.QSize"
] | [((1731, 1744), 'PySide2.QtCore.QSize', 'QSize', (['(87)', '(20)'], {}), '(87, 20)\n', (1736, 1744), False, 'from PySide2.QtCore import QEvent, QSettings, QSize, Qt, QDateTime\n'), ((1775, 1796), 'PySide2.QtCore.QSize', 'QSize', (['(87 - 1)', '(20 - 1)'], {}), '(87 - 1, 20 - 1)\n', (1780, 1796), False, 'from PySide2.Qt... |
"""Contains tests for finpack/core/cli.py
"""
__copyright__ = "Copyright (C) 2021 <NAME>"
import os
import unittest
from importlib import metadata
from docopt import docopt
from finpack.core import cli
class TestCli(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.DATA_DIR = "temp"
... | [
"os.rmdir",
"os.mkdir",
"docopt.docopt"
] | [((322, 344), 'os.mkdir', 'os.mkdir', (['cls.DATA_DIR'], {}), '(cls.DATA_DIR)\n', (330, 344), False, 'import os\n'), ((399, 421), 'os.rmdir', 'os.rmdir', (['cls.DATA_DIR'], {}), '(cls.DATA_DIR)\n', (407, 421), False, 'import os\n'), ((503, 533), 'docopt.docopt', 'docopt', (['cli.__doc__'], {'argv': 'argv'}), '(cli.__do... |
"""
Author: <NAME>
"""
import numpy as np
import pandas as pd
from sklearn.neighbors import NearestNeighbors
def affinity_graph(X):
'''
This function returns a numpy array.
'''
ni, nd = X.shape
A = np.zeros((ni, ni))
for i in range(ni):
for j in range(i+1, ni):
dist = ((X[i] - X[j])**2).sum() # compute ... | [
"numpy.exp",
"numpy.zeros",
"sklearn.neighbors.NearestNeighbors"
] | [((208, 226), 'numpy.zeros', 'np.zeros', (['(ni, ni)'], {}), '((ni, ni))\n', (216, 226), True, 'import numpy as np\n'), ((606, 624), 'numpy.zeros', 'np.zeros', (['(ni, ni)'], {}), '((ni, ni))\n', (614, 624), True, 'import numpy as np\n'), ((896, 914), 'numpy.zeros', 'np.zeros', (['(ni, ni)'], {}), '((ni, ni))\n', (904,... |
import numpy as np
import pytest
from pytest import approx
from pymt.component.grid import GridMixIn
class Port:
def __init__(self, name, uses=None, provides=None):
self._name = name
self._uses = uses or []
self._provides = provides or []
def get_component_name(self):
return ... | [
"numpy.array",
"pytest.raises"
] | [((7100, 7125), 'pytest.raises', 'pytest.raises', (['IndexError'], {}), '(IndexError)\n', (7113, 7125), False, 'import pytest\n'), ((1613, 1638), 'numpy.array', 'np.array', (['[3.0, 5.0, 7.0]'], {}), '([3.0, 5.0, 7.0])\n', (1621, 1638), True, 'import numpy as np\n'), ((2214, 2258), 'numpy.array', 'np.array', (['[[0.0, ... |
"""Exercise 1
Usage:
$ CUDA_VISIBLE_DEVICES=2 python practico_1_train_petfinder.py --dataset_dir ../ --epochs 30 --dropout 0.1 0.1 --hidden_layer_sizes 200 100
To know which GPU to use, you can check it with the command
$ nvidia-smi
"""
import argparse
import os
import mlflow
import pickle
import numpy as np
impo... | [
"mlflow.set_experiment",
"mlflow.log_param",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.layers.Input",
"os.path.exists",
"argparse.ArgumentParser",
"tensorflow.data.Dataset.from_tensor_slices",
"mlflow.log_metric",
"auxiliary.log_dir_name",
"auxiliary.load_dataset",
"tensorflow.keras.mod... | [((475, 508), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (498, 508), False, 'import warnings\n'), ((654, 732), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Training a MLP on the petfinder dataset"""'}), "(description='Training a MLP on... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from pkg_resources import parse_version
from warnings import warn
from copy import deepcopy
import networkx as nx
from networkx.readwrite import json_graph
from catpy.applications.base import CatmaidClientApplication
NX_VERSION_INFO = parse_version(nx.... | [
"warnings.warn",
"pkg_resources.parse_version",
"networkx.readwrite.json_graph.node_link_graph",
"copy.deepcopy"
] | [((1205, 1218), 'copy.deepcopy', 'deepcopy', (['jso'], {}), '(jso)\n', (1213, 1218), False, 'from copy import deepcopy\n'), ((303, 332), 'pkg_resources.parse_version', 'parse_version', (['nx.__version__'], {}), '(nx.__version__)\n', (316, 332), False, 'from pkg_resources import parse_version\n'), ((1038, 1166), 'warnin... |
from typing import Optional
from watchmen_auth import PrincipalService
from watchmen_data_kernel.cache import CacheService
from watchmen_data_kernel.common import DataKernelException
from watchmen_data_kernel.external_writer import find_external_writer_create, register_external_writer_creator
from watchmen_meta.common... | [
"watchmen_data_kernel.cache.CacheService.external_writer",
"watchmen_data_kernel.external_writer.find_external_writer_create",
"watchmen_meta.common.ask_snowflake_generator",
"watchmen_meta.common.ask_meta_storage"
] | [((640, 689), 'watchmen_data_kernel.external_writer.find_external_writer_create', 'find_external_writer_create', (['external_writer.type'], {}), '(external_writer.type)\n', (667, 689), False, 'from watchmen_data_kernel.external_writer import find_external_writer_create, register_external_writer_creator\n'), ((1547, 156... |
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distrib... | [
"os.path.exists",
"pickle.dump",
"re.compile",
"enchant.Dict",
"pickle.load"
] | [((17963, 17987), 're.compile', 're.compile', (['_valid_words'], {}), '(_valid_words)\n', (17973, 17987), False, 'import re\n'), ((18213, 18231), 'enchant.Dict', 'enchant.Dict', (['lang'], {}), '(lang)\n', (18225, 18231), False, 'import enchant\n'), ((18334, 18355), 'os.path.exists', 'os.path.exists', (['cache'], {}), ... |
from pythonforandroid.toolchain import Recipe, shprint, current_directory, ArchARM
from os.path import exists, join, realpath
from os import uname
import glob
import sh
class LibX264Recipe(Recipe):
version = 'x264-snapshot-20170608-2245-stable' # using mirror url since can't use ftp
url = 'http://mirror.yand... | [
"pythonforandroid.toolchain.shprint",
"os.path.realpath",
"os.path.join",
"sh.Command"
] | [((745, 770), 'sh.Command', 'sh.Command', (['"""./configure"""'], {}), "('./configure')\n", (755, 770), False, 'import sh\n'), ((1191, 1224), 'pythonforandroid.toolchain.shprint', 'shprint', (['sh.make', '"""-j4"""'], {'_env': 'env'}), "(sh.make, '-j4', _env=env)\n", (1198, 1224), False, 'from pythonforandroid.toolchai... |
#coding=utf-8
try:
if __name__.startswith('qgb.Win'):
from .. import py
else:
import py
except Exception as ei:
raise ei
raise EnvironmentError(__name__)
if py.is2():
import _winreg as winreg
from _winreg import *
else:
import winreg
from winreg import *
def get(skey,name,root=HKEY_CURRENT_USER,returnTyp... | [
"py.is2",
"py.isint",
"py.isbyte",
"py.istr"
] | [((167, 175), 'py.is2', 'py.is2', ([], {}), '()\n', (173, 175), False, 'import py\n'), ((1014, 1028), 'py.isint', 'py.isint', (['type'], {}), '(type)\n', (1022, 1028), False, 'import py\n'), ((1035, 1050), 'py.isint', 'py.isint', (['value'], {}), '(value)\n', (1043, 1050), False, 'import py\n'), ((1063, 1077), 'py.istr... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import sys
import os
sys.path.insert(0, os.path.abspath('..'))
from clint import resources
resources.init('kennethreitz', 'clint')
lorem = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt... | [
"clint.resources.user.read",
"clint.resources.user.write",
"clint.resources.user.delete",
"os.path.abspath",
"clint.resources.init"
] | [((180, 219), 'clint.resources.init', 'resources.init', (['"""kennethreitz"""', '"""clint"""'], {}), "('kennethreitz', 'clint')\n", (194, 219), False, 'from clint import resources\n'), ((724, 764), 'clint.resources.user.write', 'resources.user.write', (['"""lorem.txt"""', 'lorem'], {}), "('lorem.txt', lorem)\n", (744, ... |
from django.conf.urls import url
from django.conf import settings
from django.conf.urls.static import static
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^image/$', views.add_image, name='upload_image'),
url(r'^profile/$', views.profile_info, name='profile'),
url(r'... | [
"django.conf.urls.static.static",
"django.conf.urls.url"
] | [((151, 187), 'django.conf.urls.url', 'url', (['"""^$"""', 'views.index'], {'name': '"""index"""'}), "('^$', views.index, name='index')\n", (154, 187), False, 'from django.conf.urls import url\n'), ((194, 247), 'django.conf.urls.url', 'url', (['"""^image/$"""', 'views.add_image'], {'name': '"""upload_image"""'}), "('^i... |
import datetime
from unittest.mock import patch
import dns.resolver
import dns.rrset
import pytest
import pytz
from django.utils import timezone
from freezegun import freeze_time
from rest_framework import status
from posthog.models import Organization, OrganizationDomain, OrganizationMembership, Team
from posthog.te... | [
"posthog.models.OrganizationDomain.objects.create",
"datetime.datetime",
"posthog.models.OrganizationDomain.objects.count",
"posthog.models.OrganizationDomain.objects.get",
"django.utils.timezone.now",
"posthog.models.OrganizationDomain.objects.filter",
"posthog.models.Team.objects.create",
"freezegun... | [((7935, 7999), 'unittest.mock.patch', 'patch', (['"""posthog.models.organization_domain.dns.resolver.resolve"""'], {}), "('posthog.models.organization_domain.dns.resolver.resolve')\n", (7940, 7999), False, 'from unittest.mock import patch\n'), ((9227, 9291), 'unittest.mock.patch', 'patch', (['"""posthog.models.organiz... |
import numpy as np
import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as plt
from os import listdir
from tensorflow.keras.callbacks import ModelCheckpoint
dataDir = "./data/trainSmallFA/"
files = listdir(dataDir)
files.sort()
totalLength = len(files)
inputs = np.empty((len(files), 3, 64, 64)... | [
"matplotlib.pyplot.imshow",
"os.listdir",
"numpy.sqrt",
"matplotlib.pyplot.colorbar",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.title",
"numpy.load",
"numpy.amax",
"matplotlib.pyplot.show"
] | [((224, 240), 'os.listdir', 'listdir', (['dataDir'], {}), '(dataDir)\n', (231, 240), False, 'from os import listdir\n'), ((833, 861), 'numpy.amax', 'np.amax', (['targets[:, 0, :, :]'], {}), '(targets[:, 0, :, :])\n', (840, 861), True, 'import numpy as np\n'), ((413, 436), 'numpy.load', 'np.load', (['(dataDir + file)'],... |
# ~~~
# This file is part of the paper:
#
# " An Online Efficient Two-Scale Reduced Basis Approach
# for the Localized Orthogonal Decomposition "
#
# https://github.com/TiKeil/Two-scale-RBLOD.git
#
# Copyright 2019-2021 all developers. All rights reserved.
# License: Licensed as BSD 2-Clause ... | [
"setuptools.setup"
] | [((450, 606), 'setuptools.setup', 'setup', ([], {'name': '"""rblod"""', 'version': '"""2021.1"""', 'description': '"""Pymor support for RBLOD"""', 'author': '"""<NAME>"""', 'author_email': '"""<EMAIL>"""', 'license': '"""MIT"""', 'packages': "['rblod']"}), "(name='rblod', version='2021.1', description='Pymor support fo... |
import os
import shutil
import numpy as np
import pandas as pd ... | [
"seaborn.set",
"numpy.power",
"numpy.geomspace",
"numpy.array",
"cosmicfish.makedirectory",
"cosmicfish.forecast"
] | [((665, 674), 'seaborn.set', 'sns.set', ([], {}), '()\n', (672, 674), True, 'import seaborn as sns\n'), ((1328, 1359), 'cosmicfish.makedirectory', 'cf.makedirectory', (['fp_resultsdir'], {}), '(fp_resultsdir)\n', (1344, 1359), True, 'import cosmicfish as cf\n'), ((3270, 3368), 'numpy.array', 'np.array', (['[0.65, 0.75,... |
import argparse
import warnings
warnings.simplefilter("ignore", UserWarning)
import files
from tensorboardX import SummaryWriter
import os
import numpy as np
import time
import torch
import torch.optim
import torch.nn as nn
import torch.utils.data
import torchvision
import torchvision.transforms as tfs
from data impo... | [
"torch.nn.CrossEntropyLoss",
"torchvision.transforms.ColorJitter",
"torchvision.transforms.functional.rotate",
"torch.cuda.is_available",
"files.save_checkpoint_all",
"numpy.arange",
"util.setup_runtime",
"tensorboardX.SummaryWriter",
"argparse.ArgumentParser",
"util.write_conv",
"torchvision.da... | [((32, 76), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""', 'UserWarning'], {}), "('ignore', UserWarning)\n", (53, 76), False, 'import warnings\n'), ((594, 662), 'torchvision.transforms.Normalize', 'tfs.Normalize', ([], {'mean': '[0.485, 0.456, 0.406]', 'std': '[0.229, 0.224, 0.225]'}), '(mean=[0.48... |
# -*- coding: utf-8 -*-
from tests import HangulizeTestCase
from hangulize.langs.vie import Vietnamese
class VietnameseTestCase(HangulizeTestCase):
""" http://korean.go.kr/09_new/dic/rule/rule_foreign_0218.jsp """
lang = Vietnamese()
def test_1st(self):
"""์ 1ํญ
nh๋ ์ด์ด์ง๋ ๋ชจ์๊ณผ ํฉ์ณ์ ํ ์์ ๋ก ์ ๋๋ค.... | [
"hangulize.langs.vie.Vietnamese"
] | [((232, 244), 'hangulize.langs.vie.Vietnamese', 'Vietnamese', ([], {}), '()\n', (242, 244), False, 'from hangulize.langs.vie import Vietnamese\n')] |
from mathlibpy.functions import *
import unittest
class SinTester(unittest.TestCase):
def setUp(self):
self.sin = Sin()
def test_call(self):
self.assertEqual(self.sin(0), 0)
def test_eq(self):
self.assertEqual(self.sin, Sin())
def test_get_derivative_call(self):
sel... | [
"unittest.main"
] | [((1038, 1053), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1051, 1053), False, 'import unittest\n')] |
import numpy as np
from something import Top
i = 0
while i < 10:
a = np.ndarray((10,4))
b = np.ones((10, Top))
i += 1
del Top
# show_store()
| [
"numpy.ndarray",
"numpy.ones"
] | [((74, 93), 'numpy.ndarray', 'np.ndarray', (['(10, 4)'], {}), '((10, 4))\n', (84, 93), True, 'import numpy as np\n'), ((101, 119), 'numpy.ones', 'np.ones', (['(10, Top)'], {}), '((10, Top))\n', (108, 119), True, 'import numpy as np\n')] |
from aiohttp_admin2.mappers import Mapper
from aiohttp_admin2.mappers import fields
class FloatMapper(Mapper):
field = fields.FloatField()
def test_correct_float_type():
"""
In this test we check success convert to float type.
"""
mapper = FloatMapper({"field": 1})
mapper.is_valid()
ass... | [
"aiohttp_admin2.mappers.fields.FloatField"
] | [((125, 144), 'aiohttp_admin2.mappers.fields.FloatField', 'fields.FloatField', ([], {}), '()\n', (142, 144), False, 'from aiohttp_admin2.mappers import fields\n')] |
#!/usr/bin/env python3
import os
from argparse import ArgumentParser, ArgumentTypeError, FileType, Namespace
from typing import Any
def DirType(string: str) -> str:
if os.path.isdir(string):
return string
raise ArgumentTypeError(
'Directory does not exist: "{}"'.format(os.path.abspath(string))... | [
"os.path.abspath",
"argparse.FileType",
"os.path.isdir"
] | [((174, 195), 'os.path.isdir', 'os.path.isdir', (['string'], {}), '(string)\n', (187, 195), False, 'import os\n'), ((296, 319), 'os.path.abspath', 'os.path.abspath', (['string'], {}), '(string)\n', (311, 319), False, 'import os\n'), ((915, 929), 'argparse.FileType', 'FileType', (['mode'], {}), '(mode)\n', (923, 929), F... |
import torch
import torch.nn as nn
from torch.nn.functional import max_pool1d
from utility.model_parameter import Configuration, ModelParameter
class CNNLayer(nn.Module):
def __init__(self, config: Configuration, vocab_size=30000, use_embeddings=True, embed_dim=-1, **kwargs):
super(CNNLayer, self).__init... | [
"torch.nn.ReLU",
"torch.nn.Dropout",
"torch.nn.Embedding",
"torch.nn.Conv2d",
"torch.cuda.is_available",
"torch.cat"
] | [((446, 471), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (469, 471), False, 'import torch\n'), ((919, 963), 'torch.nn.Embedding', 'nn.Embedding', (['vocab_size', 'self.embedding_dim'], {}), '(vocab_size, self.embedding_dim)\n', (931, 963), True, 'import torch.nn as nn\n'), ((984, 993), 'tor... |
'''
<xs:complexType name="backup">
<xs:annotation>
<xs:documentation></xs:documentation>
</xs:annotation>
<xs:sequence>
<xs:group ref="duration"/>
<xs:group ref="editorial"/>
</xs:sequence>
</xs:complexType>
'''
from musicscore.dtd.dtd import Sequence, GroupReference, Element
from musicscore.musicxml... | [
"musicscore.dtd.dtd.GroupReference",
"musicscore.dtd.dtd.Element"
] | [((972, 989), 'musicscore.dtd.dtd.Element', 'Element', (['Duration'], {}), '(Duration)\n', (979, 989), False, 'from musicscore.dtd.dtd import Sequence, GroupReference, Element\n'), ((999, 1024), 'musicscore.dtd.dtd.GroupReference', 'GroupReference', (['Editorial'], {}), '(Editorial)\n', (1013, 1024), False, 'from music... |
import torch
import numpy as np
import hashlib
from torch.autograd import Variable
import os
def deterministic_random(min_value, max_value, data):
digest = hashlib.sha256(data.encode()).digest()
raw_value = int.from_bytes(digest[:4], byteorder='little', signed=False)
return int(raw_value / (2 ** 32 - 1... | [
"numpy.mean",
"torch.mean",
"numpy.linalg.det",
"numpy.sum",
"numpy.matmul",
"numpy.linalg.svd",
"torch.autograd.Variable"
] | [((2852, 2890), 'numpy.mean', 'np.mean', (['target'], {'axis': '(1)', 'keepdims': '(True)'}), '(target, axis=1, keepdims=True)\n', (2859, 2890), True, 'import numpy as np\n'), ((2901, 2942), 'numpy.mean', 'np.mean', (['predicted'], {'axis': '(1)', 'keepdims': '(True)'}), '(predicted, axis=1, keepdims=True)\n', (2908, 2... |