code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
from projectCode import db
db.create_all()
| [
"projectCode.db.create_all"
] | [((27, 42), 'projectCode.db.create_all', 'db.create_all', ([], {}), '()\n', (40, 42), False, 'from projectCode import db\n')] |
import numpy as np
import scipy.special
def powder_isotropic(omega, pas):
"""
Frequency domain calculation over an isotropic powder for CSA tensor.
The expressions are evaluated using complete elliptic integrals of the first kind.
Parameters
----------
omega : array
frequency
pas... | [
"numpy.convolve",
"numpy.sqrt",
"numpy.log",
"numpy.zeros_like",
"numpy.arange"
] | [((592, 612), 'numpy.zeros_like', 'np.zeros_like', (['omega'], {}), '(omega)\n', (605, 612), True, 'import numpy as np\n'), ((3408, 3443), 'numpy.convolve', 'np.convolve', (['y', 'kernel'], {'mode': '"""same"""'}), "(y, kernel, mode='same')\n", (3419, 3443), True, 'import numpy as np\n'), ((837, 889), 'numpy.sqrt', 'np... |
from funcs import invert
assert invert("F' R U2 R' U2 R' F2 R U R U' R' F'") == "F L' U2 L U2 L F2 L' U' L' U L F", "with spaces"
assert invert("F'RU2R'U2R'F2RURU'R'F'") == "F L' U2 L U2 L F2 L' U' L' U L F", "without spaces"
assert invert("F 'RU 2R'U 2 R'F 2R UR U'R'F'") == "F L' U2 L U2 L F2 L' U' L' U L F", "mixe... | [
"funcs.invert",
"funcs.clean"
] | [((33, 77), 'funcs.invert', 'invert', (['"""F\' R U2 R\' U2 R\' F2 R U R U\' R\' F\'"""'], {}), '("F\' R U2 R\' U2 R\' F2 R U R U\' R\' F\'")\n', (39, 77), False, 'from funcs import invert\n'), ((139, 171), 'funcs.invert', 'invert', (['"""F\'RU2R\'U2R\'F2RURU\'R\'F\'"""'], {}), '("F\'RU2R\'U2R\'F2RURU\'R\'F\'")\n', (14... |
#!/usr/bin/python
#-*- coding: utf-8 -*-
import turtle
import math
import tkinter
class Viewer:
def __init__(self):
self.l_vessel = 50 # Metade do comprimento da embarcacao
#first we initialize the turtle settings
turtle.speed(0)
turtle.mode('logo')
turtle.setworldcoordinat... | [
"turtle.begin_fill",
"turtle.mode",
"turtle.pendown",
"turtle.register_shape",
"turtle.penup",
"turtle.setworldcoordinates",
"turtle.degrees",
"math.cos",
"turtle.speed",
"turtle.setpos",
"turtle.fillcolor",
"turtle.mainloop",
"turtle.end_fill",
"math.sin",
"turtle.setup",
"turtle.Turt... | [((244, 259), 'turtle.speed', 'turtle.speed', (['(0)'], {}), '(0)\n', (256, 259), False, 'import turtle\n'), ((268, 287), 'turtle.mode', 'turtle.mode', (['"""logo"""'], {}), "('logo')\n", (279, 287), False, 'import turtle\n'), ((296, 342), 'turtle.setworldcoordinates', 'turtle.setworldcoordinates', (['(0)', '(-500)', '... |
"""
Модуль предоставляет API сервиса конвертации валют
"""
from decimal import Decimal
from converter import converter
from converter import error
async def convert(currency_from, currency_to, amount):
"""
Конвертация валюты
Params:
currency_from - валюта из которой необходимо прео... | [
"converter.converter.save_course",
"converter.error.ServiceError",
"decimal.Decimal",
"converter.converter.convert_currency"
] | [((551, 566), 'decimal.Decimal', 'Decimal', (['amount'], {}), '(amount)\n', (558, 566), False, 'from decimal import Decimal\n'), ((600, 662), 'converter.converter.convert_currency', 'converter.convert_currency', (['amount', 'currency_from', 'currency_to'], {}), '(amount, currency_from, currency_to)\n', (626, 662), Fals... |
#
# radarbeam.py
#
# module for calculating geometry parameters and magnetic aspect
# angle of radar targets monitored by any radar
#
# use aspect_elaz or aspect_txty to calculate aspect angles of targets
# specified by (el,az) or (tx,ty) angles
#
# Created by <NAME> on 11/29/08 as jrobeam.py
# Copyright (c) 2008 EC... | [
"numpy.sqrt",
"numpy.cross",
"numpy.sin",
"pyigrf.igrf.igrf_B",
"numpy.array",
"numpy.dot",
"numpy.arctan2",
"numpy.cos",
"numpy.finfo",
"numpy.arctan"
] | [((1506, 1534), 'numpy.sqrt', 'np.sqrt', (['(x ** 2.0 + y ** 2.0)'], {}), '(x ** 2.0 + y ** 2.0)\n', (1513, 1534), True, 'import numpy as np\n'), ((1535, 1551), 'numpy.arctan2', 'np.arctan2', (['y', 'x'], {}), '(y, x)\n', (1545, 1551), True, 'import numpy as np\n'), ((1559, 1575), 'numpy.arctan2', 'np.arctan2', (['z', ... |
'''
Created on Jul 18, 2013
@author: noah
'''
import math
import main as m
def pi(args):
return math.pi
def sqrt_(args):
return math.sqrt(m.eval_(args[0]))
def sq(args):
return m.eval_(args[0])**2 ... | [
"main.eval_"
] | [((207, 223), 'main.eval_', 'm.eval_', (['args[0]'], {}), '(args[0])\n', (214, 223), True, 'import main as m\n'), ((299, 315), 'main.eval_', 'm.eval_', (['args[0]'], {}), '(args[0])\n', (306, 315), True, 'import main as m\n'), ((353, 369), 'main.eval_', 'm.eval_', (['args[0]'], {}), '(args[0])\n', (360, 369), True, 'im... |
from django_filters import rest_framework as filters
from rest_framework import viewsets
from rest_framework.response import Response
from utils.pagination import CustomPageNumberPagination
from categories.models import Category
from categories.serializers import CategoryListSerializer, CategoryDetailSerializer
clas... | [
"rest_framework.response.Response",
"categories.models.Category.objects.all",
"categories.serializers.CategoryDetailSerializer"
] | [((495, 517), 'categories.models.Category.objects.all', 'Category.objects.all', ([], {}), '()\n', (515, 517), False, 'from categories.models import Category\n'), ((758, 822), 'categories.serializers.CategoryDetailSerializer', 'CategoryDetailSerializer', (['instance'], {'context': "{'request': request}"}), "(instance, c... |
#!/usr/bin/env python3
'''
Class to take care of building btpkgs
'''
#import asyncio
import click
import logging
# TODO(cooper): Make relative imports work
#from . import btpkg
import btpkg
class BuildCli():
@click.command()
@click.option(
'-y',
'--yes',
help='Auto confirm ...'... | [
"click.option",
"click.command"
] | [((223, 238), 'click.command', 'click.command', ([], {}), '()\n', (236, 238), False, 'import click\n'), ((244, 310), 'click.option', 'click.option', (['"""-y"""', '"""--yes"""'], {'help': '"""Auto confirm ..."""', 'is_flag': '(True)'}), "('-y', '--yes', help='Auto confirm ...', is_flag=True)\n", (256, 310), False, 'imp... |
import pytest
from spacy_lemmatizer.models import Text, LemmaText
@pytest.fixture
def test_text():
return Text(content='One morning, when <NAME> woke from troubled dreams')
@pytest.fixture()
def test_lemma_text():
lemmas = ['morning', 'gregor', 'samsa', 'wake', 'troubled', 'dream']
return LemmaText(le... | [
"pytest.fixture",
"spacy_lemmatizer.models.Text",
"spacy_lemmatizer.models.LemmaText"
] | [((183, 199), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (197, 199), False, 'import pytest\n'), ((113, 179), 'spacy_lemmatizer.models.Text', 'Text', ([], {'content': '"""One morning, when <NAME> woke from troubled dreams"""'}), "(content='One morning, when <NAME> woke from troubled dreams')\n", (117, 179), F... |
from cms.app_base import CMSApp
from cms.apphook_pool import apphook_pool
from django.utils.translation import ugettext_lazy as _
from cms_genome_browser.menu import BrowsersMenu
class BrowserApp(CMSApp):
name = _("Genome Browser App")
urls = ["cms_genome_browser.urls"]
app_name = "cms_genome_browser"
... | [
"cms.apphook_pool.apphook_pool.register",
"django.utils.translation.ugettext_lazy"
] | [((345, 378), 'cms.apphook_pool.apphook_pool.register', 'apphook_pool.register', (['BrowserApp'], {}), '(BrowserApp)\n', (366, 378), False, 'from cms.apphook_pool import apphook_pool\n'), ((218, 241), 'django.utils.translation.ugettext_lazy', '_', (['"""Genome Browser App"""'], {}), "('Genome Browser App')\n", (219, 24... |
#!/usr/bin/env python
import logging
import numpy as np
import pandas as pd
from library import Imputation as iptt
SAMPLING = np.array([2, 4, 4, 4, 5, 5, 7, 9])
BENIGN = np.array([4., 28., 1., 1., 3.])
MALIGNANT = np.array([5., 60., 2., 4., 3.])
BENIGN_COUNT = np.array([1., 1., 1., 1., 1.])
MALIGNANT_COUNT = np.... | [
"numpy.array",
"logging.warning",
"pandas.read_csv",
"library.Imputation"
] | [((131, 165), 'numpy.array', 'np.array', (['[2, 4, 4, 4, 5, 5, 7, 9]'], {}), '([2, 4, 4, 4, 5, 5, 7, 9])\n', (139, 165), True, 'import numpy as np\n'), ((176, 212), 'numpy.array', 'np.array', (['[4.0, 28.0, 1.0, 1.0, 3.0]'], {}), '([4.0, 28.0, 1.0, 1.0, 3.0])\n', (184, 212), True, 'import numpy as np\n'), ((220, 256), ... |
import unittest
import random
import os
import shutil
import uuid
from main import qsort, external_merge_sort, phase1_sorting
from constants import PAGE_SIZE
random.seed(0)
DATA_FOLDER = "./data"
def split_nums(nums, k):
i = 0
strs = []
while i < len(nums):
strs.append(' '.join(map(str, nums[i:i ... | [
"main.phase1_sorting",
"main.external_merge_sort",
"os.path.join",
"random.seed",
"uuid.uuid4",
"os.mkdir",
"shutil.rmtree",
"unittest.main",
"random.randint"
] | [((159, 173), 'random.seed', 'random.seed', (['(0)'], {}), '(0)\n', (170, 173), False, 'import random\n'), ((657, 698), 'shutil.rmtree', 'shutil.rmtree', (['folder'], {'ignore_errors': '(True)'}), '(folder, ignore_errors=True)\n', (670, 698), False, 'import shutil\n'), ((703, 719), 'os.mkdir', 'os.mkdir', (['folder'], ... |
import click
@click.group()
@click.pass_context
def flavor(ctx):
ctx.obj.cloud_resource_name = "flavor"
ctx.obj.headers = [
'name',
'vcpu_count',
'memory_gb',
'slug',
'zones',
]
@click.option('--filter-json')
@flavor.command("list")
@click.pass_obj
def cmd_list(clou... | [
"click.group",
"click.option"
] | [((15, 28), 'click.group', 'click.group', ([], {}), '()\n', (26, 28), False, 'import click\n'), ((233, 262), 'click.option', 'click.option', (['"""--filter-json"""'], {}), "('--filter-json')\n", (245, 262), False, 'import click\n')] |
""" Posterior predictions
1. Load data
2. Run simulations
- First experiment:
- With perseveration (3 cycles)
- Without perseveration (3 cycles)
- With perseveration (1 cycle) to plot single-trial updates and predictions
- Follow-up experiment:
- With perseveration (3 cycles)
... | [
"pandas.read_pickle",
"al_simulation.simulation_loop",
"numpy.random.seed"
] | [((544, 563), 'numpy.random.seed', 'np.random.seed', (['(123)'], {}), '(123)\n', (558, 563), True, 'import numpy as np\n'), ((645, 687), 'pandas.read_pickle', 'pd.read_pickle', (['"""al_data/data_prepr_1.pkl"""'], {}), "('al_data/data_prepr_1.pkl')\n", (659, 687), True, 'import pandas as pd\n'), ((727, 769), 'pandas.re... |
"""
Linux Kernel 4.8+ libgpiod
"""
import threading
from datetime import datetime, timedelta
from typing import TYPE_CHECKING, Any, Callable, Dict, Optional
from ...types import ConfigType, PinType
from . import GenericGPIO, InterruptEdge, InterruptSupport, PinDirection, PinPUD
if TYPE_CHECKING:
# pylint: disable... | [
"threading.Event",
"datetime.datetime.now",
"gpiod.chip",
"datetime.timedelta"
] | [((875, 906), 'gpiod.chip', 'gpiod.chip', (["self.config['chip']"], {}), "(self.config['chip'])\n", (885, 906), False, 'import gpiod\n'), ((1052, 1069), 'threading.Event', 'threading.Event', ([], {}), '()\n', (1067, 1069), False, 'import threading\n'), ((4703, 4737), 'datetime.timedelta', 'timedelta', ([], {'millisecon... |
# Generated by Django 3.1.5 on 2021-01-27 01:04
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Ingredient',
fields=[
... | [
"django.db.models.AutoField",
"django.db.models.ManyToManyField",
"django.db.models.CharField",
"django.db.models.ForeignKey"
] | [((1943, 2021), 'django.db.models.ManyToManyField', 'models.ManyToManyField', ([], {'through': '"""menu.RecipeIngredients"""', 'to': '"""menu.Ingredient"""'}), "(through='menu.RecipeIngredients', to='menu.Ingredient')\n", (1965, 2021), False, 'from django.db import migrations, models\n'), ((339, 432), 'django.db.models... |
#
# Copyright 2020 The Feast Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... | [
"pandas.DataFrame.from_records",
"feast.loaders.file.export_source_to_staging_location",
"boto3.client",
"urllib.parse.urlparse",
"pandavro.to_avro",
"fastavro.reader",
"tempfile.mktemp",
"pandas.testing.assert_frame_equal",
"pandas.DataFrame",
"tempfile.TemporaryFile",
"unittest.mock.patch"
] | [((1072, 1189), 'pandas.DataFrame', 'pd.DataFrame', (["{'driver': [1001, 1002, 1003], 'transaction': [1001, 1002, 1003],\n 'driver_id': [1001, 1002, 1003]}"], {}), "({'driver': [1001, 1002, 1003], 'transaction': [1001, 1002, \n 1003], 'driver_id': [1001, 1002, 1003]})\n", (1084, 1189), True, 'import pandas as pd\... |
#!/usr/bin/python
######################################################################
# Generate static HTML for non dynamic pages
######################################################################
# <NAME> - 01/02/2014
import jinja2
import os
import codecs
import distutils.core
def createFile(path, filename,... | [
"jinja2.Environment",
"os.makedirs",
"os.path.isdir",
"jinja2.FileSystemLoader",
"codecs.open"
] | [((454, 503), 'codecs.open', 'codecs.open', (['filename'], {'encoding': '"""utf-8"""', 'mode': '"""w"""'}), "(filename, encoding='utf-8', mode='w')\n", (465, 503), False, 'import codecs\n'), ((635, 674), 'jinja2.FileSystemLoader', 'jinja2.FileSystemLoader', ([], {'searchpath': '"""/"""'}), "(searchpath='/')\n", (658, 6... |
# coding : utf-8
'''
Copyright 2019 <NAME>.
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 w... | [
"HTTPyS.Server.Server"
] | [((995, 1141), 'HTTPyS.Server.Server', 'Server.Server', ([], {'IPAddress': '"""localhost"""', 'portNumber': '(8000)', 'certificateFilePath': '"""./SSLFiles/certificate.pem"""', 'keyFilePath': '"""./SSLFiles/privkey.pem"""'}), "(IPAddress='localhost', portNumber=8000, certificateFilePath=\n './SSLFiles/certificate.pe... |
import configparser
import os
class Configuration():
def __init__(self):
user_config_dir = os.path.join(
os.path.expanduser("~"), '.config', 'sprint-printer'
)
self._user_config = os.path.join(
user_config_dir, 'default.ini'
)
self._config = configp... | [
"configparser.ConfigParser",
"os.makedirs",
"os.path.join",
"os.path.isfile",
"os.path.expanduser"
] | [((223, 267), 'os.path.join', 'os.path.join', (['user_config_dir', '"""default.ini"""'], {}), "(user_config_dir, 'default.ini')\n", (235, 267), False, 'import os\n'), ((313, 340), 'configparser.ConfigParser', 'configparser.ConfigParser', ([], {}), '()\n', (338, 340), False, 'import configparser\n'), ((132, 155), 'os.pa... |
import setuptools
#
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="hargrave",
# version="0.0.1",
# author="<NAME>",
# author_email="<EMAIL>",
# description="A wrapper around flaport/FDTD for PCB simulations.",
# long_description=long_description,
... | [
"setuptools.setup"
] | [((89, 275), 'setuptools.setup', 'setuptools.setup', ([], {'name': '"""hargrave"""', 'packages': "['hargrave_base', 'hargrave_drivers', 'hargrave_language_bindings',\n 'hargrave_modules', 'hargrave_standards']", 'python_requires': '""">=3.6"""'}), "(name='hargrave', packages=['hargrave_base',\n 'hargrave_drivers'... |
#!/usr/bin/env python
from distutils.core import setup
setup(name='pattern',
version='0.1~alpha0',
author='<NAME>',
author_email='<EMAIL>',
description='Parsing strings according to python formats',
url='http://github.com/integralws/pattern',
license='MIT License',
packages=['pattern'],
) | [
"distutils.core.setup"
] | [((57, 302), 'distutils.core.setup', 'setup', ([], {'name': '"""pattern"""', 'version': '"""0.1~alpha0"""', 'author': '"""<NAME>"""', 'author_email': '"""<EMAIL>"""', 'description': '"""Parsing strings according to python formats"""', 'url': '"""http://github.com/integralws/pattern"""', 'license': '"""MIT License"""', ... |
# coding: utf-8
#
# Project: X-ray image reader
# https://github.com/silx-kit/fabio
#
# Copyright (C) 2016 Univeristy Köln, Germany
#
# Principal author: <NAME> (<EMAIL>)
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated docum... | [
"logging.getLogger",
"numpy.float",
"datetime.datetime.strptime",
"xml.dom.minidom.parseString",
"numpy.polynomial.polynomial.polyval",
"numpy.dtype",
"numpy.fromstring",
"numpy.arange"
] | [((1579, 1606), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1596, 1606), False, 'import logging\n'), ((5062, 5114), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (['str_date', '"""%d%b%Y%H%M%S"""'], {}), "(str_date, '%d%b%Y%H%M%S')\n", (5088, 5114), False, 'import dateti... |
#!/usr/bin/env python
# Cartopy implementation of TEC plotting in polar coordinates
# author: @mrinalghosh
import matplotlib.pyplot as plt
import matplotlib.path as mpath
import numpy as np
import cartopy.feature as cfeature
import cartopy.crs as ccrs
import h5py
from argparse import ArgumentParser
from datetime impo... | [
"numpy.nanmean",
"numpy.sin",
"cartopy.crs.NorthPolarStereo",
"matplotlib.path.Path",
"numpy.reshape",
"argparse.ArgumentParser",
"os.path.split",
"matplotlib.pyplot.close",
"numpy.linspace",
"cartopy.crs.Mercator",
"cartopy.crs.NearsidePerspective",
"matplotlib.pyplot.gcf",
"os.path.splitex... | [((874, 889), 'matplotlib.pyplot.colormaps', 'plt.colormaps', ([], {}), '()\n', (887, 889), True, 'import matplotlib.pyplot as plt\n'), ((1095, 1115), 'h5py.File', 'h5py.File', (['root', '"""r"""'], {}), "(root, 'r')\n", (1104, 1115), False, 'import h5py\n'), ((11042, 11058), 'argparse.ArgumentParser', 'ArgumentParser'... |
#!/usr/bin/env python
"""Make big QUOCKA cubes"""
from IPython import embed
import schwimmbad
import sys
from glob import glob
from tqdm import tqdm
import matplotlib.pyplot as plt
from radio_beam import Beam, Beams
from radio_beam.utils import BeamError
from astropy import units as u
from astropy.io import fits
from ... | [
"matplotlib.pyplot.ylabel",
"radio_beam.Beam.from_fits_header",
"numpy.isfinite",
"sys.exit",
"astropy.io.fits.open",
"schwimmbad.choose_pool",
"argparse.ArgumentParser",
"radio_beam.Beams",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.diff",
"numpy.vstack",
"numpy.concatenat... | [((515, 571), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""'], {'category': 'AstropyWarning'}), "('ignore', category=AstropyWarning)\n", (536, 571), False, 'import warnings\n'), ((1153, 1200), 'numpy.round', 'np.round', (['(a + 0.5 * 10 ** -precision)', 'precision'], {}), '(a + 0.5 * 10 ** -precisio... |
import sys, os
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, os.path.join(CURRENT_DIR, "..", ".."))
import constants
import requests
HTTP_ERROR_CODE_START = 400
HTTP_ERROR_MESSAGE_FORMAT= "Site '%s' returned error '%d'"
REQUEST_ERROR_FORMAT = "Requesting connection to '%s' errored!"
HYP... | [
"sys.platform.startswith",
"os.path.join",
"requests.get",
"os.path.realpath",
"os.system"
] | [((434, 488), 'sys.platform.startswith', 'sys.platform.startswith', (['constants.MAC_OS_X_IDENTIFIER'], {}), '(constants.MAC_OS_X_IDENTIFIER)\n', (457, 488), False, 'import sys, os\n'), ((45, 71), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (61, 71), False, 'import sys, os\n'), ((92, 129... |
from job_snapshotting.google_cloud_storage import GoogleCloudStorage
from job_snapshotting.internal_model import SnapshotSchema
class Snapshot:
def __init__(self, name, job_run_timestamp, bucket_id):
self._snapshot_schema = SnapshotSchema()
self._storage = GoogleCloudStorage(bucket_id, self._snaps... | [
"job_snapshotting.google_cloud_storage.GoogleCloudStorage",
"job_snapshotting.internal_model.SnapshotSchema"
] | [((238, 254), 'job_snapshotting.internal_model.SnapshotSchema', 'SnapshotSchema', ([], {}), '()\n', (252, 254), False, 'from job_snapshotting.internal_model import SnapshotSchema\n'), ((279, 331), 'job_snapshotting.google_cloud_storage.GoogleCloudStorage', 'GoogleCloudStorage', (['bucket_id', 'self._snapshot_schema'], ... |
from django.shortcuts import render_to_response, get_object_or_404
from django.http import Http404, HttpResponseRedirect, HttpResponse, HttpResponseRedirect
from django.template import RequestContext#,Template
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from dja... | [
"django.shortcuts.get_object_or_404",
"django.template.RequestContext"
] | [((520, 562), 'django.shortcuts.get_object_or_404', 'get_object_or_404', (['User'], {'username': 'username'}), '(User, username=username)\n', (537, 562), False, 'from django.shortcuts import render_to_response, get_object_or_404\n'), ((884, 901), 'django.template.RequestContext', 'RequestContext', (['r'], {}), '(r)\n',... |
from flask_login import current_user
from flask_wtf import FlaskForm
from flask_wtf.file import FileAllowed, FileField, FileRequired
import pytz
from wtforms import ValidationError
from wtforms.fields import IntegerField, SelectField, StringField
from wtforms.validators import DataRequired, NumberRange
from wtforms_com... | [
"busy_beaver.common.datetime_utilities.add_gmt_offset_to_timezone",
"pytz.timezone",
"wtforms.validators.NumberRange",
"flask_wtf.file.FileAllowed",
"wtforms.validators.DataRequired",
"busy_beaver.models.UpcomingEventsGroup.meetup_urlname.ilike",
"flask_wtf.file.FileRequired",
"busy_beaver.clients.mee... | [((653, 690), 'busy_beaver.common.datetime_utilities.add_gmt_offset_to_timezone', 'add_gmt_offset_to_timezone', (['TIMEZONES'], {}), '(TIMEZONES)\n', (679, 690), False, 'from busy_beaver.common.datetime_utilities import add_gmt_offset_to_timezone\n'), ((972, 1000), 'wtforms.fields.SelectField', 'SelectField', ([], {'la... |
# -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxtpro.base.exchange import Exchange
import ccxt.async_support as ccxt
from ccxtpro.base.cache import ArrayCache, ArrayCacheByTimesta... | [
"ccxt.base.errors.ArgumentsRequired",
"ccxtpro.base.cache.ArrayCacheByTimestamp",
"ccxtpro.base.cache.ArrayCache"
] | [((13588, 13711), 'ccxt.base.errors.ArgumentsRequired', 'ArgumentsRequired', (['(self.id +\n " watchBalance requires a type parameter(one of \'spot\', \'margin\', \'futures\', \'swap\')"\n )'], {}), '(self.id +\n " watchBalance requires a type parameter(one of \'spot\', \'margin\', \'futures\', \'swap\')"\n ... |
from random import randint
from pynput.keyboard import Key, Listener
output = 'kld' + str(randint(0, 10000)) + '.txt'
with open(output, 'w') as f:
f.close()
def on_press(key):
with open(output, 'a') as f:
f.write('{0} pressed\n'.format(key))
f.close()
def on_release(key):
... | [
"pynput.keyboard.Listener",
"random.randint"
] | [((476, 526), 'pynput.keyboard.Listener', 'Listener', ([], {'on_press': 'on_press', 'on_release': 'on_release'}), '(on_press=on_press, on_release=on_release)\n', (484, 526), False, 'from pynput.keyboard import Key, Listener\n'), ((96, 113), 'random.randint', 'randint', (['(0)', '(10000)'], {}), '(0, 10000)\n', (103, 11... |
import psycopg2
def hello_world(request):
"""
Responds to any HTTP request.
Args:
request (flask.Request): HTTP request object.
Returns:
The response text or any set of values that can be turned into a
Response object using
`make_response <http://flask.pocoo.org/docs/1.... | [
"psycopg2.connect",
"psycopg2.errorcodes.lookup"
] | [((684, 817), 'psycopg2.connect', 'psycopg2.connect', ([], {'host': '"""/cloudsql/hackwa-membership:us-west1:myinstance"""', 'dbname': '"""postgres"""', 'user': '"""postgres"""', 'password': '"""password"""'}), "(host='/cloudsql/hackwa-membership:us-west1:myinstance',\n dbname='postgres', user='postgres', password='... |
'''Wrapper for RESTful api https://sm.ms/api'''
import requests
class Api:
'''Wrapper for RESTful api https://sm.ms/api'''
params = {'format': 'json', 'ssl': True}
prefix = 'https://sm.ms/api'
@classmethod
def delete(cls, delete_url):
'''delete an image from remote server'''
retu... | [
"requests.get"
] | [((323, 347), 'requests.get', 'requests.get', (['delete_url'], {}), '(delete_url)\n', (335, 347), False, 'import requests\n')] |
from datetime import datetime as dt
import pickle
from uuid import uuid4
import io
import binascii
filename = 'my-database.data'
with open(filename, 'rb') as f:
data = pickle.load(f)
print(data)
record = [{
'id': str(uuid4()),
'name': data[0].get('name'),
'email': data[0].get('email... | [
"pickle.dump",
"pickle.load",
"uuid.uuid4"
] | [((173, 187), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (184, 187), False, 'import pickle\n'), ((521, 543), 'pickle.dump', 'pickle.dump', (['record', 'f'], {}), '(record, f)\n', (532, 543), False, 'import pickle\n'), ((238, 245), 'uuid.uuid4', 'uuid4', ([], {}), '()\n', (243, 245), False, 'from uuid import uu... |
# coding:utf-8
import tensorflow as tf
from tensorflow.python.keras.api._v2.keras.initializers import Initializer
class EmbeddingInit(Initializer):
def __init__(self, embeddings):
self.embeddings = embeddings
def __call__(self, shape, dtype):
if not self.embeddings.shape == shape:
... | [
"tensorflow.convert_to_tensor"
] | [((385, 435), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['self.embeddings'], {'dtype': 'dtype'}), '(self.embeddings, dtype=dtype)\n', (405, 435), True, 'import tensorflow as tf\n')] |
from argparse import ArgumentParser
from collections import defaultdict
import numpy as np
import torch
import h5py
from tqdm import tqdm
from pytorch_pretrained_bert import BertTokenizer
LAYER_NUM = 12
FEATURE_DIM = 768
def match_tokenized_to_untokenized(tokenized_sent, untokenized_sent):
'''Aligns tokenized an... | [
"numpy.mean",
"pytorch_pretrained_bert.BertTokenizer.from_pretrained",
"numpy.savez",
"argparse.ArgumentParser",
"h5py.File",
"numpy.zeros",
"collections.defaultdict"
] | [((915, 932), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (926, 932), False, 'from collections import defaultdict\n'), ((1561, 1577), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (1575, 1577), False, 'from argparse import ArgumentParser\n'), ((1747, 1808), 'pytorch_pretrained... |
import random
from tensorboardX import SummaryWriter
class GridSearch():
GRID_LIST_SUFFIX = '_grid'
GRID_PARAM_SEPARATOR = ' '
GRID_VALUE_SEPARATOR = '-'
def __init__(self, solution, randomSearch = True):
self.solution = solution
self.solution.__grid_search__ = self
self.random... | [
"random.randint",
"tensorboardX.SummaryWriter"
] | [((570, 585), 'tensorboardX.SummaryWriter', 'SummaryWriter', ([], {}), '()\n', (583, 585), False, 'from tensorboardX import SummaryWriter\n'), ((2066, 2103), 'random.randint', 'random.randint', (['(0)', '(attr_list_size - 1)'], {}), '(0, attr_list_size - 1)\n', (2080, 2103), False, 'import random\n')] |
from typing import List
import os
import sys
import shutil
import subprocess
def is_non_system_dylib(dylib_path: str) -> bool:
return not dylib_path.startswith('/usr/lib') and not dylib_path.startswith('/System/Library')
def get_child_dylib_abs_path(parent_dylib_dir: str, child_dylib: str) -> str:
if child... | [
"os.makedirs",
"shutil.copy2",
"subprocess.run",
"os.path.join",
"os.path.split",
"os.path.dirname",
"os.path.basename",
"shutil.rmtree",
"os.path.abspath"
] | [((882, 973), 'subprocess.run', 'subprocess.run', (["['otool', '-L', exec_or_dylib_path]"], {'stdout': 'subprocess.PIPE', 'check': '(True)'}), "(['otool', '-L', exec_or_dylib_path], stdout=subprocess.PIPE,\n check=True)\n", (896, 973), False, 'import subprocess\n'), ((1328, 1440), 'subprocess.run', 'subprocess.run',... |
import os
import unittest
import datetime
import discord
import bot
class BotTest(unittest.TestCase):
def setUp(self):
self.name = "BotIFPS"
def test_environ(self):
self.assertIn('DISCORD_TOKEN', os.environ)
def test_login(self):
client = discord.Client()
@client.event... | [
"unittest.main",
"datetime.datetime.now",
"discord.Client",
"bot.validate_fpl"
] | [((1312, 1327), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1325, 1327), False, 'import unittest\n'), ((281, 297), 'discord.Client', 'discord.Client', ([], {}), '()\n', (295, 297), False, 'import discord\n'), ((538, 561), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (559, 561), False, 'i... |
# https://adventofcode.com/2021/day/17
import math
test = "target area: x=20..30, y=-10..-5"
run = "target area: x=153..199, y=-114..-75"
# y axis
# vertical acceleration constant -1 per step
# at y=0, speed going up is the same as speed going down, but different sign
# therefore, max speed up is distance from y=0 ... | [
"math.sqrt"
] | [((1663, 1686), 'math.sqrt', 'math.sqrt', (['(1 + 8 * xmin)'], {}), '(1 + 8 * xmin)\n', (1672, 1686), False, 'import math\n')] |
import csv
from govhack_app import db
from govhack_app.location.models import Postcode, Demand, Lga
def example_data():
for csv_file in [{'age': '0-4', 'file': 'data/input1.csv'},
{'age': '5-9', 'file': 'data/input2.csv'},
{'age': '10-14', 'file': 'data/input3.csv'}]:
... | [
"govhack_app.location.models.Postcode",
"govhack_app.location.models.Demand",
"govhack_app.db.session.commit",
"govhack_app.location.models.Postcode.query.filter_by",
"csv.reader",
"govhack_app.db.session.add"
] | [((380, 393), 'csv.reader', 'csv.reader', (['f'], {}), '(f)\n', (390, 393), False, 'import csv\n'), ((2432, 2929), 'govhack_app.location.models.Demand', 'Demand', ([], {'postcode_id': 'pcode.id', 'total_childcare_facilities': 'total_childcare_facilities', 'government_funded_places': 'government_funded_places', 'seifa':... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'E:\py_code\StepScanMeter\measurement\QT\ui_setupTimescale.ui'
#
# Created by: PyQt5 UI code generator 5.6
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Ui_SetupTimeScale(object... | [
"PyQt5.QtWidgets.QWidget",
"PyQt5.QtGui.QFont",
"PyQt5.QtWidgets.QDoubleSpinBox",
"PyQt5.QtCore.QMetaObject.connectSlotsByName",
"PyQt5.QtWidgets.QGridLayout",
"PyQt5.QtWidgets.QLabel",
"PyQt5.QtWidgets.QApplication",
"PyQt5.QtWidgets.QSizePolicy",
"PyQt5.QtWidgets.QDockWidget",
"PyQt5.QtWidgets.Q... | [((9525, 9557), 'PyQt5.QtWidgets.QApplication', 'QtWidgets.QApplication', (['sys.argv'], {}), '(sys.argv)\n', (9547, 9557), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((9582, 9605), 'PyQt5.QtWidgets.QDockWidget', 'QtWidgets.QDockWidget', ([], {}), '()\n', (9603, 9605), False, 'from PyQt5 import QtCore, QtG... |
import torch
from ebonite.core.analyzer.dataset import DatasetAnalyzer
from ebonite.runtime.openapi.spec import type_to_schema
def test_torch__single_tensor(first_tensor):
# this import ensures that this dataset type is registered in `DatasetAnalyzer`
from ebonite.ext.torch.dataset import TorchTensorDatasetT... | [
"ebonite.runtime.openapi.spec.type_to_schema",
"torch.equal",
"ebonite.core.analyzer.dataset.DatasetAnalyzer.analyze"
] | [((343, 380), 'ebonite.core.analyzer.dataset.DatasetAnalyzer.analyze', 'DatasetAnalyzer.analyze', (['first_tensor'], {}), '(first_tensor)\n', (366, 380), False, 'from ebonite.core.analyzer.dataset import DatasetAnalyzer\n'), ((819, 858), 'torch.equal', 'torch.equal', (['first_tensor', 'tensor_deser'], {}), '(first_tens... |
import numpy as np
from optlang import Constraint
from scipy import stats
from ..util.constraints import *
from ..util.linalg_fun import *
from ..util.thermo_constants import *
def generate_n_sphere_sample(n_variables):
"""Generates unit n-sphere sample. Works by picking random sample from normal distribution an... | [
"numpy.random.normal",
"scipy.stats.genextreme.fit",
"numpy.insert",
"numpy.sqrt",
"scipy.stats.genextreme.interval",
"numpy.any",
"numpy.square",
"numpy.diag",
"numpy.zeros",
"numpy.nonzero",
"scipy.stats.chi2.isf"
] | [((608, 660), 'numpy.random.normal', 'np.random.normal', ([], {'loc': '(0)', 'scale': '(1.0)', 'size': 'n_variables'}), '(loc=0, scale=1.0, size=n_variables)\n', (624, 660), True, 'import numpy as np\n'), ((8997, 9027), 'scipy.stats.genextreme.fit', 'stats.genextreme.fit', (['data_set'], {}), '(data_set)\n', (9017, 902... |
import cv2 as cv
#Reading images
# img = cv.imread('photos/1.jpg') #reading data
# cv.imshow('img', img) #diplaying data
# cap=cv.VideoCapture(0) # camera capture
#reading videos
cap = cv.VideoCapture('videos/v1.mp4')
while True:
isTrue, frame =cap.read()
cv.imshow('video',frame)
if cv.wait... | [
"cv2.waitKey",
"cv2.destroyAllWindows",
"cv2.VideoCapture",
"cv2.imshow"
] | [((190, 222), 'cv2.VideoCapture', 'cv.VideoCapture', (['"""videos/v1.mp4"""'], {}), "('videos/v1.mp4')\n", (205, 222), True, 'import cv2 as cv\n'), ((381, 403), 'cv2.destroyAllWindows', 'cv.destroyAllWindows', ([], {}), '()\n', (401, 403), True, 'import cv2 as cv\n'), ((276, 301), 'cv2.imshow', 'cv.imshow', (['"""video... |
#!/usr/bin/env python
# Note : Handle all other corner cases which are not handled here
import sys
import os
from functools import reduce
# Write a python program to read contents of a file (filename as argument)
# and store number of occurrences of each word in a dictionary.
dict = {}
wordLen = []
if(len(sys.argv... | [
"functools.reduce",
"os.path.exists",
"sys.exit"
] | [((1462, 1497), 'functools.reduce', 'reduce', (['(lambda x, y: x + y)', 'wordLen'], {}), '(lambda x, y: x + y, wordLen)\n', (1468, 1497), False, 'from functools import reduce\n'), ((359, 369), 'sys.exit', 'sys.exit', ([], {}), '()\n', (367, 369), False, 'import sys\n'), ((378, 405), 'os.path.exists', 'os.path.exists', ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import os
import xarray as xr
from ooi_data_explorations.common import inputs, m2m_collect, m2m_request, get_deployment_dates, \
get_vocabulary, dt64_epoch, update_dataset, ENCODINGS
from ooi_data_explorations.uncabled.process_phsen import ATTRS, qua... | [
"ooi_data_explorations.common.get_vocabulary",
"ooi_data_explorations.common.get_deployment_dates",
"numpy.reshape",
"ooi_data_explorations.common.inputs",
"ooi_data_explorations.uncabled.process_phsen.ATTRS.items",
"ooi_data_explorations.common.dt64_epoch",
"ooi_data_explorations.common.m2m_collect",
... | [((3068, 3088), 'numpy.atleast_3d', 'np.atleast_3d', (['light'], {}), '(light)\n', (3081, 3088), True, 'import numpy as np\n'), ((3101, 3133), 'numpy.reshape', 'np.reshape', (['light', '(nrec, 23, 4)'], {}), '(light, (nrec, 23, 4))\n', (3111, 3133), True, 'import numpy as np\n'), ((3593, 3613), 'numpy.atleast_3d', 'np.... |
# ------------------------------------------------------------------
# Capsules_mnist
# By <NAME>
# This file is adapted from tensorflow official tutorial of mnist.
# ------------------------------------------------------------------
from __future__ import absolute_import
from __future__ import division
from __future__... | [
"tensorflow.reset_default_graph",
"CapsNet.CapsNet",
"argparse.ArgumentParser",
"tensorflow.sign",
"tensorflow.Session",
"tensorflow.train.get_checkpoint_state",
"tensorflow.examples.tutorials.mnist.input_data.read_data_sets",
"tensorflow.gradients",
"tensorflow.global_variables_initializer",
"ten... | [((594, 607), 'CapsNet.CapsNet', 'CapsNet', (['None'], {}), '(None)\n', (601, 607), False, 'from CapsNet import CapsNet\n'), ((779, 834), 'tensorflow.examples.tutorials.mnist.input_data.read_data_sets', 'input_data.read_data_sets', (['FLAGS.data_dir'], {'one_hot': '(True)'}), '(FLAGS.data_dir, one_hot=True)\n', (804, 8... |
#
# Copyright (c) 2015-2016 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
from nfv_vim import database
from nfv_vim.tables._table import Table
_system_table = None
class SystemTable(Table):
"""
System Table
"""
def __init__(self):
super(SystemTable, self).__init__()
... | [
"nfv_vim.database.database_system_add",
"nfv_vim.database.database_system_delete",
"nfv_vim.database.database_system_get_list"
] | [((770, 805), 'nfv_vim.database.database_system_get_list', 'database.database_system_get_list', ([], {}), '()\n', (803, 805), False, 'from nfv_vim import database\n'), ((362, 397), 'nfv_vim.database.database_system_add', 'database.database_system_add', (['value'], {}), '(value)\n', (390, 397), False, 'from nfv_vim impo... |
import six
import json
from prompt_toolkit.application import get_app
from prompt_toolkit.filters import to_filter
from prompt_toolkit.mouse_events import MouseEventType
from prompt_toolkit.key_binding.key_bindings import KeyBindings
from prompt_toolkit.layout.containers import Window
from prompt_toolkit.layout.contro... | [
"prompt_toolkit.layout.containers.Window",
"json.loads",
"prompt_toolkit.key_binding.key_bindings.KeyBindings",
"prompt_toolkit.filters.to_filter",
"json.dumps",
"prompt_toolkit.application.get_app",
"freud.model.db.fetch_one"
] | [((786, 814), 'freud.model.db.fetch_one', 'db.fetch_one', ([], {'name': 'self.name'}), '(name=self.name)\n', (798, 814), False, 'from freud.model import db\n'), ((1606, 1622), 'prompt_toolkit.filters.to_filter', 'to_filter', (['(False)'], {}), '(False)\n', (1615, 1622), False, 'from prompt_toolkit.filters import to_fil... |
"""
Report module
"""
import os
import os.path
import sys
from .models import Models
from .query import Query
class Report(object):
"""
Methods to build reports from a series of queries
"""
@staticmethod
def write(output, line):
"""
Writes line to output file.
Args:
... | [
"os.path.splitext"
] | [((3175, 3197), 'os.path.splitext', 'os.path.splitext', (['task'], {}), '(task)\n', (3191, 3197), False, 'import os\n')] |
# -*- coding: utf-8 -*-
import binascii
class pretty_bytes(bytes):
"""提供自定义格式
>>> pb = pretty_bytes('\xe8\x87\xaa\xe5\xae\x9a\xe4\xb9\x89')
>>> '{0:hex}'.format(pb)
'e887aae5ae9ae4b989'
>>> '{0:HEX}'.format(pb)
'E887AAE5AE9AE4B989'
>>> '{0:hex+}'.format(pb)
'e8 87 aa e5 ae 9a e4 b9 89'... | [
"binascii.hexlify",
"doctest.testmod"
] | [((963, 980), 'doctest.testmod', 'doctest.testmod', ([], {}), '()\n', (978, 980), False, 'import doctest\n'), ((552, 574), 'binascii.hexlify', 'binascii.hexlify', (['self'], {}), '(self)\n', (568, 574), False, 'import binascii\n')] |
import tensorflow as tf
from experiment.mapping.model.transform_both import FixSpaceModel
from experiment.utils.variables import weight_variable, bias_variable
class FixSpaceSeparateTransformationModel(FixSpaceModel):
def __init__(self, config, config_global, logger):
super(FixSpaceSeparateTransformation... | [
"experiment.utils.variables.bias_variable",
"tensorflow.nn.xw_plus_b",
"experiment.utils.variables.weight_variable"
] | [((462, 531), 'experiment.utils.variables.weight_variable', 'weight_variable', (['"""W1_src"""', '[data.embedding_size, data.embedding_size]'], {}), "('W1_src', [data.embedding_size, data.embedding_size])\n", (477, 531), False, 'from experiment.utils.variables import weight_variable, bias_variable\n'), ((549, 595), 'ex... |
import wx
import sys
import threading
import traceback
import inspect
import weakref
class Signal(object):
def __init__(self, owner=None):
self.__lock = threading.Lock()
self.__handlers = []
if isinstance(owner, wx.Window):
owner.Bind(wx.EVT_WINDOW_DESTROY, lambda evt: self.dest... | [
"traceback.format_exc",
"inspect.ismethod",
"threading.Lock",
"wx.CallAfter",
"inspect.isfunction",
"weakref.ref"
] | [((166, 182), 'threading.Lock', 'threading.Lock', ([], {}), '()\n', (180, 182), False, 'import threading\n'), ((536, 582), 'wx.CallAfter', 'wx.CallAfter', (['self.__dosignal', '*args'], {}), '(self.__dosignal, *args, **kwargs)\n', (548, 582), False, 'import wx\n'), ((1736, 1758), 'inspect.ismethod', 'inspect.ismethod',... |
#!/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
# "... | [
"textwrap.dedent",
"ai_flow.AIFlowMaster",
"os.path.exists",
"airflow.logging_config.configure_logging"
] | [((998, 1558), 'textwrap.dedent', 'textwrap.dedent', (['f""" # Config of master server\n\n # endpoint of master\n master_ip: localhost\n master_port: 50051\n # uri of database backend in master\n db_uri: sqlite:///{root_dir_path}/aiflow.db\n # type of database backend in... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 21 11:03:20 2018
@author: Ryan
"""
import pandas as pd
from UDFs import createreplacexlsx
seasonteams = pd.read_csv(
'/Users/Ryan/Google Drive/ncaa-basketball-data/seasonteams.csv')
inclcolumns = ['Season',
'TmName',
... | [
"UDFs.createreplacexlsx",
"pandas.read_csv"
] | [((178, 254), 'pandas.read_csv', 'pd.read_csv', (['"""/Users/Ryan/Google Drive/ncaa-basketball-data/seasonteams.csv"""'], {}), "('/Users/Ryan/Google Drive/ncaa-basketball-data/seasonteams.csv')\n", (189, 254), True, 'import pandas as pd\n'), ((1776, 1881), 'UDFs.createreplacexlsx', 'createreplacexlsx', (['"""/Users/Rya... |
# type:ignore
from photo.models import Image
from django.http.response import Http404, HttpResponse
from django.shortcuts import render, redirect
from django.conf import settings
from . import views
from django.conf.urls.static import static
from django.http import HttpResponse
import datetime as dt
from .models import... | [
"django.shortcuts.render",
"photo.models.Image.objects.all",
"datetime.datetime.strptime",
"django.shortcuts.redirect",
"photo.models.Image.search_by_category",
"django.http.response.Http404",
"datetime.date.today",
"photo.models.Image.objects.get"
] | [((654, 673), 'photo.models.Image.objects.all', 'Image.objects.all', ([], {}), '()\n', (671, 673), False, 'from photo.models import Image\n'), ((731, 787), 'django.shortcuts.render', 'render', (['request', '"""all-Photos/today-photos.html"""', 'context'], {}), "(request, 'all-Photos/today-photos.html', context)\n", (73... |
import json
import logging
import traceback
from urllib.request import urlopen, Request
from uniswap.uniswap import UniswapV2Client
import os
from web3 import Web3
import time
from datetime import datetime
import math
logger = logging.getLogger(__name__)
ACC = 'xxx'
PRIVATE_KEY = 'xxx'
API = 'xxx'
NETWORK = 'https:/... | [
"logging.getLogger",
"math.floor",
"urllib.request.Request",
"uniswap.uniswap.UniswapV2Client",
"time.sleep",
"web3.Web3",
"datetime.datetime.now",
"traceback.print_exc",
"datetime.datetime.timestamp",
"web3.Web3.toHex",
"web3.Web3.toChecksumAddress",
"urllib.request.urlopen",
"web3.Web3.HTT... | [((229, 256), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (246, 256), False, 'import logging\n'), ((768, 859), 'urllib.request.Request', 'Request', (['"""https://ethgasstation.info/api/ethgasAPI.json"""'], {'headers': 'headers', 'method': '"""GET"""'}), "('https://ethgasstation.info/ap... |
"""Some query helpers.
Authors
-------
<NAME>
"""
import os
from astropy.table import Table
from astroquery.gaia import Gaia, TapPlus
import pandas as pd
def get_gaiadr_data(analysis_dataset_name, data_dir, source_id_array=None, gaia_data_release='dr3int5',
overwrite_query=False, gaia_table... | [
"pandas.read_parquet",
"astropy.table.Table",
"os.path.join",
"os.path.isfile",
"astroquery.gaia.TapPlus"
] | [((2474, 2502), 'pandas.read_parquet', 'pd.read_parquet', (['output_file'], {}), '(output_file)\n', (2489, 2502), True, 'import pandas as pd\n'), ((862, 889), 'os.path.isfile', 'os.path.isfile', (['output_file'], {}), '(output_file)\n', (876, 889), False, 'import os\n'), ((973, 1029), 'astroquery.gaia.TapPlus', 'TapPlu... |
#!/usr/bin/env python3
"""Interface slurmd."""
import copy
import json
import logging
from ops.framework import (
EventBase, EventSource, Object, ObjectEvents, StoredState
)
logger = logging.getLogger()
class SlurmdAvailableEvent(EventBase):
"""Emmited when slurmd is available."""
class SlurmdBrokenEvent... | [
"logging.getLogger",
"json.loads",
"ops.framework.StoredState",
"ops.framework.EventSource",
"copy.deepcopy"
] | [((190, 209), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (207, 209), False, 'import logging\n'), ((585, 618), 'ops.framework.EventSource', 'EventSource', (['SlurmdAvailableEvent'], {}), '(SlurmdAvailableEvent)\n', (596, 618), False, 'from ops.framework import EventBase, EventSource, Object, ObjectEvent... |
# -*- coding: utf-8 -*-
#!/usr/bin/env python
__author__ = """Prof. <NAME>, Ph.D. <<EMAIL>>"""
import os
os.system('clear')
print('.-------------------------------.')
print('| |#')
print('| By.: Prof. <NAME> |#')
print('| |#')
print('| ... | [
"matplotlib.pyplot.imshow",
"numpy.average",
"numpy.append",
"numpy.array",
"numpy.zeros",
"numpy.linspace",
"random.choices",
"numpy.exp",
"os.system",
"random.random",
"matplotlib.pyplot.show"
] | [((108, 126), 'os.system', 'os.system', (['"""clear"""'], {}), "('clear')\n", (117, 126), False, 'import os\n'), ((961, 977), 'numpy.zeros', 'np.zeros', (['(N, N)'], {}), '((N, N))\n', (969, 977), True, 'import numpy as np\n'), ((982, 998), 'numpy.zeros', 'np.zeros', (['(N, N)'], {}), '((N, N))\n', (990, 998), True, 'i... |
"""
This module implements methods for generating random connections between nodes in a graph.
in a neo4j database.
Method generate() will create all the necessary connections for the graph:
dataset <-> dataset collection
system <-> system collection
dataset read <-> system input
dataset write <-> syst... | [
"itertools.islice",
"random.choice",
"random.shuffle"
] | [((4845, 4875), 'random.shuffle', 'random.shuffle', (['element_values'], {}), '(element_values)\n', (4859, 4875), False, 'import random\n'), ((4884, 4918), 'random.shuffle', 'random.shuffle', (['elements_per_group'], {}), '(elements_per_group)\n', (4898, 4918), False, 'import random\n'), ((7282, 7313), 'random.choice',... |
# -*- coding: utf-8 -*-
# Imports
import numpy as np
import torch
import gpytorch
from gpytorch.priors import GammaPrior
from copy import deepcopy
# Disctionary of distributions for randomm initialization
def build_dist_dict(noise_prior, outputscale_prior, lengthscale_prior):
"""
Build a dictionary of dist... | [
"torch.manual_seed",
"gpytorch.mlls.ExactMarginalLogLikelihood",
"gpytorch.priors.GammaPrior",
"copy.deepcopy",
"numpy.argmin"
] | [((1249, 1269), 'copy.deepcopy', 'deepcopy', (['dictionary'], {}), '(dictionary)\n', (1257, 1269), False, 'from copy import deepcopy\n'), ((2266, 2325), 'gpytorch.mlls.ExactMarginalLogLikelihood', 'gpytorch.mlls.ExactMarginalLogLikelihood', (['likelihood', 'model'], {}), '(likelihood, model)\n', (2306, 2325), False, 'i... |
# xml.py
# ------------------------------------------------------------------------------------------------ #
def indent(elem, level=0):
i = "\n" + level*" "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
if not elem.tail or not elem.tail.strip():
... | [
"xml.etree.ElementTree.parse",
"ast.literal_eval",
"xml.etree.ElementTree.Element",
"xml.etree.ElementTree.ElementTree",
"xml.etree.ElementTree.SubElement"
] | [((5947, 6000), 'ast.literal_eval', 'literal_eval', (["xmlWellObject.attrib['hopedForPresent']"], {}), "(xmlWellObject.attrib['hopedForPresent'])\n", (5959, 6000), False, 'from ast import literal_eval\n'), ((9116, 9134), 'xml.etree.ElementTree.parse', 'ET.parse', (['fileName'], {}), '(fileName)\n', (9124, 9134), True, ... |
import os
import pickle
from sklearn.externals import joblib
with open('song_theme_pca_model_pickle.pkl', 'rb') as f:
theme_pca = pickle.load(f, encoding='latin1')
print(theme_pca)
joblib.dump(theme_pca, os.path.join('song_theme_pca_model_python3.pkl'))
| [
"os.path.join",
"pickle.load"
] | [((136, 169), 'pickle.load', 'pickle.load', (['f'], {'encoding': '"""latin1"""'}), "(f, encoding='latin1')\n", (147, 169), False, 'import pickle\n'), ((212, 260), 'os.path.join', 'os.path.join', (['"""song_theme_pca_model_python3.pkl"""'], {}), "('song_theme_pca_model_python3.pkl')\n", (224, 260), False, 'import os\n')... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 1 23:04:56 2020
@author: dhruv
"""
from os import listdir
from xml.etree import ElementTree
from numpy import zeros
from numpy import asarray
from mrcnn.utils import Dataset
from mrcnn.config import Config
from mrcnn.model import MaskRCNN
from os import listdir
from xml... | [
"mrcnn.model.MaskRCNN",
"numpy.asarray",
"os.listdir",
"xml.etree.ElementTree.parse"
] | [((4429, 4485), 'mrcnn.model.MaskRCNN', 'MaskRCNN', ([], {'mode': '"""training"""', 'model_dir': '"""./"""', 'config': 'config'}), "(mode='training', model_dir='./', config=config)\n", (4437, 4485), False, 'from mrcnn.model import MaskRCNN\n'), ((1005, 1024), 'os.listdir', 'listdir', (['images_dir'], {}), '(images_dir)... |
import unittest
from common_utils import VerboseTestCase
import subprocess
class TestLinearReorder(VerboseTestCase):
def test_linear_reorder(self):
with subprocess.Popen('DNNL_VERBOSE=1 python -u linear_reorder.py', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) as p:
segmentation... | [
"unittest.main",
"subprocess.Popen"
] | [((2120, 2135), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2133, 2135), False, 'import unittest\n'), ((165, 293), 'subprocess.Popen', 'subprocess.Popen', (['"""DNNL_VERBOSE=1 python -u linear_reorder.py"""'], {'shell': '(True)', 'stdout': 'subprocess.PIPE', 'stderr': 'subprocess.STDOUT'}), "('DNNL_VERBOSE=1 p... |
import webhoseio
from utils import get_company_name, path, send_log_email
def get_webhose_titles(stock, APIkey):
file = open(path + "Stock_data" + '\\' + stock + '\\' + "News" + '\\' + "news_data.txt", "a+")
webhoseio.config(token=APIkey)
query_params = {
"q": "\"" + stock + " Stock\"" + "OR" +... | [
"webhoseio.config",
"utils.get_company_name",
"webhoseio.query"
] | [((221, 251), 'webhoseio.config', 'webhoseio.config', ([], {'token': 'APIkey'}), '(token=APIkey)\n', (237, 251), False, 'import webhoseio\n'), ((465, 514), 'webhoseio.query', 'webhoseio.query', (['"""filterWebContent"""', 'query_params'], {}), "('filterWebContent', query_params)\n", (480, 514), False, 'import webhoseio... |
"""Contains main storage class and related functions."""
import copy
import logging
import uuid
import os
import sys
import glob
import pickle
import datetime
from .data import Data
SAVE_PATH = os.path.join(os.path.expanduser("~/.cosmoscope"), "sessions")
class StoreRegistry(type):
"""
When added to a clas... | [
"os.path.exists",
"pickle.dump",
"datetime.datetime.utcnow",
"os.path.join",
"logging.warning",
"pickle.load",
"uuid.uuid4",
"os.mkdir",
"copy.deepcopy",
"logging.info",
"logging.error",
"os.path.expanduser"
] | [((210, 245), 'os.path.expanduser', 'os.path.expanduser', (['"""~/.cosmoscope"""'], {}), "('~/.cosmoscope')\n", (228, 245), False, 'import os\n'), ((2059, 2084), 'os.path.exists', 'os.path.exists', (['open_path'], {}), '(open_path)\n', (2073, 2084), False, 'import os\n'), ((3477, 3564), 'logging.info', 'logging.info', ... |
import pytest
from box import Box
from mock import Mock
from pyrabbit2.http import HTTPError, NetworkError
from bartender.pyrabbit import PyrabbitClient
@pytest.fixture
def pyrabbit_client():
return Mock()
@pytest.fixture
def client(pyrabbit_client):
the_client = PyrabbitClient(
host="localhost", p... | [
"mock.Mock",
"pyrabbit2.http.HTTPError",
"box.Box",
"pytest.raises",
"pytest.fixture",
"bartender.pyrabbit.PyrabbitClient"
] | [((437, 465), 'pytest.fixture', 'pytest.fixture', ([], {'autouse': '(True)'}), '(autouse=True)\n', (451, 465), False, 'import pytest\n'), ((206, 212), 'mock.Mock', 'Mock', ([], {}), '()\n', (210, 212), False, 'from mock import Mock\n'), ((277, 355), 'bartender.pyrabbit.PyrabbitClient', 'PyrabbitClient', ([], {'host': '... |
import aoc
import numpy as np
coorddata, folddata = aoc.get_data(13)
coordlist = []
for e in coorddata:
coordlist.append(np.array(e.split(",")).astype(int))
coords = np.array(coordlist)
size = (np.max(coords[:, 1]) + 1, np.max(coords[:, 0]) + 1)
print(f"{size}")
board = np.zeros(shape=size, dtype=np.uint8)
for... | [
"aoc.get_data",
"numpy.max",
"numpy.count_nonzero",
"numpy.array",
"numpy.zeros",
"numpy.set_printoptions"
] | [((53, 69), 'aoc.get_data', 'aoc.get_data', (['(13)'], {}), '(13)\n', (65, 69), False, 'import aoc\n'), ((172, 191), 'numpy.array', 'np.array', (['coordlist'], {}), '(coordlist)\n', (180, 191), True, 'import numpy as np\n'), ((279, 315), 'numpy.zeros', 'np.zeros', ([], {'shape': 'size', 'dtype': 'np.uint8'}), '(shape=s... |
"""
Command line interface for viper
"""
import click
from .docs import docs as docs_internal
from .cdslib import add_library, include_cdslib
@click.group()
def virt():
"""
Cadence virtuoso command-line utilities
"""
pass
@virt.command()
def docs():
docs_internal()
@virt.group()
def cdslib():
... | [
"click.group",
"click.argument",
"click.option"
] | [((145, 158), 'click.group', 'click.group', ([], {}), '()\n', (156, 158), False, 'import click\n'), ((378, 404), 'click.argument', 'click.argument', (['"""cds_path"""'], {}), "('cds_path')\n", (392, 404), False, 'import click\n'), ((406, 436), 'click.argument', 'click.argument', (['"""library_name"""'], {}), "('library... |
import os
import sys
import discord
from dotenv import load_dotenv
env_files = [f for f in os.listdir() if f.endswith(".env")]
if env_files:
load_dotenv(env_files[0])
# Relative path to the terminal
sys.path.append("..")
# https://discord.com/developers/applications/
DISCORD_BOT_TOKEN = os.getenv("GT_DISCORD_BO... | [
"os.listdir",
"os.getenv",
"dotenv.load_dotenv",
"os.path.dirname",
"discord.Color.from_rgb",
"sys.path.append"
] | [((206, 227), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (221, 227), False, 'import sys\n'), ((507, 542), 'discord.Color.from_rgb', 'discord.Color.from_rgb', (['(0)', '(206)', '(154)'], {}), '(0, 206, 154)\n', (529, 542), False, 'import discord\n'), ((147, 172), 'dotenv.load_dotenv', 'load_do... |
import os
import sys
import numpy as np
from pycocotools import mask as maskUtils
import imgaug
import skimage
from matplotlib import pyplot as plt
import cv2
import time
from pycocotools.cocoeval import COCOeval
from pycocotools.coco import COCO
ROOT_DIR = os.path.abspath("../")
# Import Mask RCNN
sys.path.append(... | [
"mrcnn.model.MaskRCNN",
"imgaug.augmenters.PiecewiseAffine",
"pycocotools.cocoeval.COCOeval",
"angiodataset.AngioDataset",
"tensorflow.config.experimental.list_logical_devices",
"numpy.array",
"imgaug.augmenters.Fliplr",
"sys.path.append",
"os.walk",
"argparse.ArgumentParser",
"imgaug.augmenters... | [((261, 283), 'os.path.abspath', 'os.path.abspath', (['"""../"""'], {}), "('../')\n", (276, 283), False, 'import os\n'), ((304, 329), 'sys.path.append', 'sys.path.append', (['ROOT_DIR'], {}), '(ROOT_DIR)\n', (319, 329), False, 'import sys\n'), ((366, 409), 'os.path.join', 'os.path.join', (['ROOT_DIR', '"""mask_rcnn_coc... |
from datetime import datetime, timezone
from tests.books import AbstractTestBook, Book
class CreateBooksSuite(AbstractTestBook):
def setUp(self):
self._ISBN = '978-0618968633'
def tearDown(self):
key = self._client.key(self._kind, self._ISBN)
self._client.delete(key)
def testCreate(self):
expec... | [
"datetime.datetime",
"tests.books.Book"
] | [((559, 565), 'tests.books.Book', 'Book', ([], {}), '()\n', (563, 565), False, 'from tests.books import AbstractTestBook, Book\n'), ((1155, 1161), 'tests.books.Book', 'Book', ([], {}), '()\n', (1159, 1161), False, 'from tests.books import AbstractTestBook, Book\n'), ((491, 533), 'datetime.datetime', 'datetime', (['(200... |
from sys import argv, stdin, stdout
# BIO -> BIOES
# B O -> S O
# B B -> S B|S
# I O -> E O
def tag_name(full):
if full == 'O':
return full
else:
return full[2:]
def from_iobes():
def get_new(true, prev_true, equal_types):
if true == 'S' and equal_types:
return 'B'
elif true == 'S' and ... | [
"sys.stdin.readlines"
] | [((546, 563), 'sys.stdin.readlines', 'stdin.readlines', ([], {}), '()\n', (561, 563), False, 'from sys import argv, stdin, stdout\n'), ((1374, 1391), 'sys.stdin.readlines', 'stdin.readlines', ([], {}), '()\n', (1389, 1391), False, 'from sys import argv, stdin, stdout\n')] |
from flask import Flask, Response, request, make_response, jsonify, g, render_template
from news_filter import filter_news
import ModelTrain
app = Flask(__name__)
@app.route('/')
def index():
response = make_response(jsonify({'Hello':'world'}))
return response
@app.route('/classification', methods=['GET'])
... | [
"flask.request.args.get",
"werkzeug.contrib.fixers.ProxyFix",
"flask.Flask",
"ModelTrain.train",
"news_filter.filter_news",
"flask.jsonify"
] | [((149, 164), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (154, 164), False, 'from flask import Flask, Response, request, make_response, jsonify, g, render_template\n'), ((353, 377), 'flask.request.args.get', 'request.args.get', (['"""text"""'], {}), "('text')\n", (369, 377), False, 'from flask import F... |
'''
Author: <NAME>
Email: <EMAIL>
Date created: 2020/1/6
Python Version: 3.6
'''
"""
Code to extract physical measurements from given period
"""
import configparser
import logging
import sys
import click
import ast
import os
sys.path.append('.')
from src.data.utils import read_global_pars, extract_f... | [
"logging.getLogger",
"logging.basicConfig",
"configparser.ConfigParser",
"src.data.utils.extract_from_raw_data",
"src.data.utils.read_global_pars",
"ast.literal_eval",
"click.Path",
"click.command",
"sys.path.append"
] | [((245, 265), 'sys.path.append', 'sys.path.append', (['"""."""'], {}), "('.')\n", (260, 265), False, 'import sys\n'), ((336, 351), 'click.command', 'click.command', ([], {}), '()\n', (349, 351), False, 'import click\n'), ((528, 555), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (545, 55... |
# Inspired by, and based on, <NAME>'s Multi-Namespace work in
# https://github.com/jupyterhub/kubespawner/pull/218
import time
from kubernetes import watch
from kubespawner.reflector import NamespacedResourceReflector
from traitlets import Bool
# This is kubernetes client implementation specific, but we need to know
#... | [
"time.monotonic",
"kubernetes.watch.Watch",
"time.sleep",
"traitlets.Bool"
] | [((515, 737), 'traitlets.Bool', 'Bool', (['(False)'], {'help': '"""\n If True, our calls to API `list_method_name` will omit a `namespace`\n argument. Necessary for non-namespaced methods such as\n `list_pod_for_all_namespaces`\n """'}), '(False, help=\n """\n If True, our calls t... |
#crop and resize the image
from PIL import Image
import os
#for image read and save
from skimage import io
from skimage.transform import resize
import time
#scriptDir = os.path.dirname(__file__)
#imagePath = os.path.join(scriptDir, '/home/tirth/Diabetic Retinopathy/TirthSampleTest/126_right.jpeg')
start_time_first = ... | [
"PIL.Image.open",
"skimage.io.imread",
"skimage.io.imsave",
"skimage.transform.resize",
"time.time"
] | [((320, 331), 'time.time', 'time.time', ([], {}), '()\n', (329, 331), False, 'import time\n'), ((424, 445), 'PIL.Image.open', 'Image.open', (['imagePath'], {}), '(imagePath)\n', (434, 445), False, 'from PIL import Image\n'), ((453, 473), 'skimage.io.imread', 'io.imread', (['imagePath'], {}), '(imagePath)\n', (462, 473)... |
#!/usr/local/bin/python3
import csv
import json
# opening the file csv to clean
csvDataFile = open('mbti_1.csv', 'r')
jsonDataFile = open('formatted_data.json', 'w')
fieldNames = ("Type", "Post")
reader = csv.DictReader(csvDataFile, fieldNames)
for row in reader:
json.dump(row, jsonDataFile)
jsonDat... | [
"csv.DictReader",
"json.dump"
] | [((207, 246), 'csv.DictReader', 'csv.DictReader', (['csvDataFile', 'fieldNames'], {}), '(csvDataFile, fieldNames)\n', (221, 246), False, 'import csv\n'), ((276, 304), 'json.dump', 'json.dump', (['row', 'jsonDataFile'], {}), '(row, jsonDataFile)\n', (285, 304), False, 'import json\n')] |
import numpy as np
import SimpleITK as sitk
from napari_imsmicrolink.data.image_transform import ImageTransform
def test_ImageTransform_add_points():
test_pts = np.array([[50.75, 100.0], [20.0, 10.0], [10.0, 50.0], [60.0, 20.0]])
itfm = ImageTransform()
itfm.output_spacing = (1, 1)
itfm.add_points(t... | [
"SimpleITK.AffineTransform",
"napari_imsmicrolink.data.image_transform.ImageTransform.apply_transform_to_pts",
"numpy.array",
"napari_imsmicrolink.data.image_transform.ImageTransform",
"numpy.testing.assert_array_equal"
] | [((168, 236), 'numpy.array', 'np.array', (['[[50.75, 100.0], [20.0, 10.0], [10.0, 50.0], [60.0, 20.0]]'], {}), '([[50.75, 100.0], [20.0, 10.0], [10.0, 50.0], [60.0, 20.0]])\n', (176, 236), True, 'import numpy as np\n'), ((249, 265), 'napari_imsmicrolink.data.image_transform.ImageTransform', 'ImageTransform', ([], {}), ... |
import dateutil.parser
import freezegun
from behaving import environment as benv
PERSONAS = {}
def before_all(context):
benv.before_all(context)
def after_all(context):
benv.after_all(context)
def before_feature(context, feature):
benv.before_feature(context, feature)
def after_feature(context, fea... | [
"behaving.environment.before_feature",
"behaving.environment.after_feature",
"behaving.environment.after_scenario",
"freezegun.freeze_time",
"behaving.environment.after_all",
"behaving.environment.before_scenario",
"behaving.environment.before_all"
] | [((127, 151), 'behaving.environment.before_all', 'benv.before_all', (['context'], {}), '(context)\n', (142, 151), True, 'from behaving import environment as benv\n'), ((182, 205), 'behaving.environment.after_all', 'benv.after_all', (['context'], {}), '(context)\n', (196, 205), True, 'from behaving import environment as... |
#!/usr/bin/env python
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django import forms
from django.forms.widgets import Input
class TinyColorPickerWidget(Input):
input_type = 'text'
template_name = 'tinycolorpicker/widget.html'
def __init__(self, attrs=None, imag... | [
"django.core.exceptions.ImproperlyConfigured",
"django.forms.Media"
] | [((1374, 1410), 'django.forms.Media', 'forms.Media', ([], {'css': "{'all': css}", 'js': 'js'}), "(css={'all': css}, js=js)\n", (1385, 1410), False, 'from django import forms\n'), ((1226, 1315), 'django.core.exceptions.ImproperlyConfigured', 'ImproperlyConfigured', (['"""TINYCOLORPICKER_VARIANT must be one of \'vanilla\... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=256)
| [
"django.db.models.CharField"
] | [((267, 299), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(256)'}), '(max_length=256)\n', (283, 299), False, 'from django.db import models\n')] |
from picraft import World, Block, Vector, X, Y, Z, vector_range, line
world = World()
world.checkpoint.save()
world.events.track_players = world.players
p = world.player.tile_pos
GAME_AREA = vector_range(p - Vector(30, 2, 25), p + Vector(25, 20, 25) + 1)
DRAWING_AREA = vector_range(p - Vector(25, 1, 25), p + Vector(2... | [
"picraft.vector_range",
"picraft.World",
"picraft.Vector",
"picraft.Block",
"picraft.line"
] | [((79, 86), 'picraft.World', 'World', ([], {}), '()\n', (84, 86), False, 'from picraft import World, Block, Vector, X, Y, Z, vector_range, line\n'), ((351, 410), 'picraft.vector_range', 'vector_range', (['(DRAWING_AREA.start + Y)', '(DRAWING_AREA.stop + Y)'], {}), '(DRAWING_AREA.start + Y, DRAWING_AREA.stop + Y)\n', (3... |
#!/usr/bin/python
from __future__ import division
from __future__ import print_function
"""
This file serves as an example of how to
a) select a problem to be solved
b) select a network type
c) train the network to minimize recovery MSE
"""
import numpy as np
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # BE ... | [
"numpy.log10",
"tools.problems.bernoulli_gaussian_trial",
"tools.networks.build_LAMP",
"tensorflow.Session",
"tensorflow.nn.l2_loss",
"tensorflow.global_variables_initializer",
"numpy.random.seed",
"tensorflow.reduce_mean",
"tensorflow.set_random_seed"
] | [((397, 414), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (411, 414), True, 'import numpy as np\n'), ((462, 483), 'tensorflow.set_random_seed', 'tf.set_random_seed', (['(1)'], {}), '(1)\n', (480, 483), True, 'import tensorflow as tf\n'), ((754, 832), 'tools.problems.bernoulli_gaussian_trial', 'proble... |
import itertools
import pytest
from alphago.games import NoughtsAndCrosses, UltimateNoughtsAndCrosses
from alphago.games.noughts_and_crosses import (GameState, Action, UltimateAction,
UltimateGameState)
class TestBasic3x3NoughtsAndCrosses:
terminal_state = GameStat... | [
"alphago.games.UltimateNoughtsAndCrosses",
"alphago.games.noughts_and_crosses.GameState",
"alphago.games.noughts_and_crosses.Action",
"pytest.mark.skip",
"alphago.games.noughts_and_crosses.UltimateGameState",
"alphago.games.NoughtsAndCrosses",
"pytest.raises",
"alphago.games.noughts_and_crosses.Ultima... | [((3559, 3621), 'pytest.mark.skip', 'pytest.mark.skip', ([], {'reason': '"""Mid migration to using a bit board."""'}), "(reason='Mid migration to using a bit board.')\n", (3575, 3621), False, 'import pytest\n'), ((312, 333), 'alphago.games.noughts_and_crosses.GameState', 'GameState', (['(468)', '(43)', '(2)'], {}), '(4... |
try:
from functools import lru_cache
except ImportError:
from backports.functools_lru_cache import lru_cache
from .utils import ConversionFunction
from .channels import channels_register, Channel
class ptype(object): # noqa: N801
"""The *pixel-type* of a given image: A representation of its spectral bas... | [
"backports.functools_lru_cache.lru_cache"
] | [((4522, 4543), 'backports.functools_lru_cache.lru_cache', 'lru_cache', ([], {'maxsize': '(10)'}), '(maxsize=10)\n', (4531, 4543), False, 'from backports.functools_lru_cache import lru_cache\n')] |
# -*- coding: utf-8 -*- #
# Copyright 2021 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... | [
"os.path.exists",
"os.path.getsize",
"googlecloudsdk.command_lib.storage.resources.resource_reference.UnknownResource",
"math.ceil",
"googlecloudsdk.core.util.files.BinaryFileWriter",
"googlecloudsdk.core.util.scaled_integer.ParseInteger",
"googlecloudsdk.command_lib.storage.storage_url.CloudUrl"
] | [((3803, 3903), 'googlecloudsdk.command_lib.storage.storage_url.CloudUrl', 'storage_url.CloudUrl', (['destination_url.scheme', 'destination_url.bucket_name', 'component_object_name'], {}), '(destination_url.scheme, destination_url.bucket_name,\n component_object_name)\n', (3823, 3903), False, 'from googlecloudsdk.co... |
from django.conf import settings
from corehq.preindex import ExtraPreindexPlugin
ExtraPreindexPlugin.register('fixtures', __file__, settings.NEW_FIXTURES_DB)
| [
"corehq.preindex.ExtraPreindexPlugin.register"
] | [((83, 159), 'corehq.preindex.ExtraPreindexPlugin.register', 'ExtraPreindexPlugin.register', (['"""fixtures"""', '__file__', 'settings.NEW_FIXTURES_DB'], {}), "('fixtures', __file__, settings.NEW_FIXTURES_DB)\n", (111, 159), False, 'from corehq.preindex import ExtraPreindexPlugin\n')] |
#!/usr/bin/env python3
import sys
import numpy as np
from config import Config
from base import Connect4Base
from random_agent import RandomAgent
from simple_agent import SimpleAgent
from one_step_lookahead_agent import OneStepLookaheadAgent
from n_steps_lookahead_agent import NStepsLookaheadAgent
from cnn_agent impor... | [
"n_steps_lookahead_agent.NStepsLookaheadAgent",
"config.Config",
"numpy.full",
"network_128x4_64_64.Network1"
] | [((1325, 1340), 'config.Config', 'Config', (['(6)', '(7)', '(4)'], {}), '(6, 7, 4)\n', (1331, 1340), False, 'from config import Config\n'), ((1728, 1759), 'n_steps_lookahead_agent.NStepsLookaheadAgent', 'NStepsLookaheadAgent', (['config', '(3)'], {}), '(config, 3)\n', (1748, 1759), False, 'from n_steps_lookahead_agent ... |
#! /g/kreshuk/pape/Work/software/conda/miniconda3/envs/cluster-new/bin/python
import os
import json
from concurrent import futures
import numpy as np
import luigi
import z5py
import skeletor.io
from cluster_tools.skeletons import SkeletonWorkflow
def check_scale(scale):
path = '/g/kreshuk/data/FIB25/data.n5'
... | [
"luigi.build",
"os.makedirs",
"cluster_tools.skeletons.SkeletonWorkflow",
"concurrent.futures.ThreadPoolExecutor",
"os.path.join",
"cluster_tools.skeletons.SkeletonWorkflow.get_config",
"z5py.File",
"numpy.array",
"numpy.zeros",
"json.dump"
] | [((388, 403), 'z5py.File', 'z5py.File', (['path'], {}), '(path)\n', (397, 403), False, 'import z5py\n'), ((734, 772), 'os.makedirs', 'os.makedirs', (['config_dir'], {'exist_ok': '(True)'}), '(config_dir, exist_ok=True)\n', (745, 772), False, 'import os\n'), ((787, 816), 'cluster_tools.skeletons.SkeletonWorkflow.get_con... |
"""
This config file allows pytest to pass arguments into tests
Author: <NAME>, <EMAIL>
"""
from pytest import fixture
def pytest_addoption(parser):
parser.addoption(
"--config_path",
action="store"
)
@fixture()
def config_path(request):
return request.config.getoption("--config_path")... | [
"pytest.fixture"
] | [((232, 241), 'pytest.fixture', 'fixture', ([], {}), '()\n', (239, 241), False, 'from pytest import fixture\n')] |
from minos.common.testing import (
MockedDatabaseClient,
)
from minos.networks import (
BrokerPublisherQueueDatabaseOperationFactory,
)
from ..collections import (
MockedBrokerQueueDatabaseOperationFactory,
)
class MockedBrokerPublisherQueueDatabaseOperationFactory(
BrokerPublisherQueueDatabaseOperat... | [
"minos.common.testing.MockedDatabaseClient.set_factory"
] | [((410, 544), 'minos.common.testing.MockedDatabaseClient.set_factory', 'MockedDatabaseClient.set_factory', (['BrokerPublisherQueueDatabaseOperationFactory', 'MockedBrokerPublisherQueueDatabaseOperationFactory'], {}), '(BrokerPublisherQueueDatabaseOperationFactory,\n MockedBrokerPublisherQueueDatabaseOperationFactory... |
#!/bin/python
# Python 2.7
import os
stage = (os.getenv("STAGE") or "development").upper()
output = "We're running in %s" % stage
if stage.startswith("PROD"):
output = "DANGER!!! - " + output
print(output)
| [
"os.getenv"
] | [((48, 66), 'os.getenv', 'os.getenv', (['"""STAGE"""'], {}), "('STAGE')\n", (57, 66), False, 'import os\n')] |
from itertools import islice
def fib():
prev, curr = 0, 1
while True:
yield curr
prev, curr = curr, prev + curr
f = fib()
print(list(islice(f, 0, 10)))
| [
"itertools.islice"
] | [((168, 184), 'itertools.islice', 'islice', (['f', '(0)', '(10)'], {}), '(f, 0, 10)\n', (174, 184), False, 'from itertools import islice\n')] |
import concurrent
import pytest
from channels.testing import WebsocketCommunicator
from django.contrib.auth import get_user_model
from backend.dialogs.models import DialogMessage
from backend.socket_chat.tests.utils import round_to_minutes
User = get_user_model()
pytestmark = [pytest.mark.asyncio, pytest.mark.djang... | [
"django.contrib.auth.get_user_model",
"pytest.mark.django_db",
"backend.socket_chat.tests.utils.round_to_minutes",
"pytest.raises"
] | [((251, 267), 'django.contrib.auth.get_user_model', 'get_user_model', ([], {}), '()\n', (265, 267), False, 'from django.contrib.auth import get_user_model\n'), ((303, 342), 'pytest.mark.django_db', 'pytest.mark.django_db', ([], {'transaction': '(True)'}), '(transaction=True)\n', (324, 342), False, 'import pytest\n'), (... |
import functools
from .common import InfoExtractor
from ..utils import (
OnDemandPagedList,
traverse_obj,
unified_strdate,
)
class GronkhIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?gronkh\.tv/(?:watch/)?stream/(?P<id>\d+)'
_TESTS = [{
'url': 'https://gronkh.tv/stream/536',
... | [
"functools.partial"
] | [((3454, 3489), 'functools.partial', 'functools.partial', (['self._fetch_page'], {}), '(self._fetch_page)\n', (3471, 3489), False, 'import functools\n')] |