code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
# coding: utf-8
import unittest
from data_structures.trees.trie import Trie
class TrieNodeTest(unittest.TestCase):
def setUp(self):
self.trie = Trie()
def test__len__(self):
self.assertEqual(len(self.trie), 0)
def test_insert(self):
with self.assertRaises(ValueError):
... | [
"unittest.main",
"data_structures.trees.trie.Trie"
] | [((1232, 1247), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1245, 1247), False, 'import unittest\n'), ((159, 165), 'data_structures.trees.trie.Trie', 'Trie', ([], {}), '()\n', (163, 165), False, 'from data_structures.trees.trie import Trie\n')] |
import requests
import time
from datetime import datetime
from bs4 import BeautifulSoup
BASE_URL = "https://www.amazon.com.mx"
def scrapWhishlistUrls(whishlist_url: str, hdrs: dict ):
current_session = requests.session()
current_session.headers = hdrs
urls = set()
failed_attempts_left = 10
whil... | [
"requests.session",
"time.sleep",
"requests.get",
"bs4.BeautifulSoup",
"datetime.datetime.now"
] | [((211, 229), 'requests.session', 'requests.session', ([], {}), '()\n', (227, 229), False, 'import requests\n'), ((1797, 1833), 'requests.get', 'requests.get', (['prod_url'], {'headers': 'hdrs'}), '(prod_url, headers=hdrs)\n', (1809, 1833), False, 'import requests\n'), ((1336, 1349), 'time.sleep', 'time.sleep', (['(2)'... |
"""
MIT License
Copyright (c) 2019 Chodera lab // Memorial Sloan Kettering Cancer Center,
Weill Cornell Medical College, Nicea Research, and Authors
Authors:
<NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to de... | [
"tensorflow.keras.layers.Dense",
"pandas.read_csv",
"sklearn.metrics.r2_score",
"tensorflow.reshape",
"gin.probabilistic.gn.GraphNet.batch",
"numpy.mean",
"lime.nets.for_gn.ConcatenateThenFullyConnect",
"tensorflow.one_hot",
"numpy.std",
"tensorflow.concat",
"tensorflow.keras.optimizers.Adam",
... | [((1353, 1390), 'pandas.read_csv', 'pd.read_csv', (['"""data/Lipophilicity.csv"""'], {}), "('data/Lipophilicity.csv')\n", (1364, 1390), True, 'import pandas as pd\n'), ((2069, 2130), 'gin.i_o.from_smiles.to_mols_with_attributes', 'gin.i_o.from_smiles.to_mols_with_attributes', (['x_array', 'y_array'], {}), '(x_array, y_... |
import sys
import os.path
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(sys.modules[__name__].__file__), "..")))
import matplotlib.pyplot as plt
import numpy as np
from sklearn.neighbors import KernelDensity
from tensorflow.python.keras.datasets import mnist
from data.data_handler import ProcessedNNHan... | [
"data.data_handler.ProcessedNNHandler",
"matplotlib.pyplot.show",
"sklearn.neighbors.KernelDensity",
"numpy.zeros",
"numpy.array",
"tensorflow.python.keras.datasets.mnist.load_data",
"matplotlib.pyplot.rc",
"numpy.linspace",
"matplotlib.pyplot.subplots_adjust",
"numpy.exp",
"matplotlib.pyplot.su... | [((2940, 2958), 'evaluation.create_plot.save_plot', 'save_plot', (['"""mnist"""'], {}), "('mnist')\n", (2949, 2958), False, 'from evaluation.create_plot import save_plot\n'), ((2960, 2970), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2968, 2970), True, 'import matplotlib.pyplot as plt\n'), ((431, 454), 'ma... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 30 11:30:08 2020
@author: xavier.mouy
"""
import functools
import time
def listinput(func):
"""Set input argument of function as a list if not already the case."""
@functools.wraps(func)
def wrapper_listinput(*args, **kwargs):
# print(type(**kwargs)... | [
"time.perf_counter",
"functools.wraps"
] | [((223, 244), 'functools.wraps', 'functools.wraps', (['func'], {}), '(func)\n', (238, 244), False, 'import functools\n'), ((583, 604), 'functools.wraps', 'functools.wraps', (['func'], {}), '(func)\n', (598, 604), False, 'import functools\n'), ((663, 682), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (680... |
import numpy as np
import pysam
import utils
import pdb
MIN_MAP_QUAL = 10
class Genome():
def __init__(self, fasta_filename, map_filename):
self._seq_handle = pysam.FastaFile(fasta_filename)
self._map_handles = [pysam.TabixFile(map_filename+'_%d.gz'%r)
for r in utils... | [
"pysam.FastaFile",
"pysam.TabixFile",
"numpy.zeros",
"utils.make_complement",
"numpy.array"
] | [((175, 206), 'pysam.FastaFile', 'pysam.FastaFile', (['fasta_filename'], {}), '(fasta_filename)\n', (190, 206), False, 'import pysam\n'), ((5431, 5464), 'pysam.TabixFile', 'pysam.TabixFile', (["(filename + '.gz')"], {}), "(filename + '.gz')\n", (5446, 5464), False, 'import pysam\n'), ((6353, 6375), 'numpy.array', 'np.a... |
import cv2
import numpy as np
from nnga.inference.base_predictor import BasePredictor
from nnga.utils.data_manipulation import adjust_image_shape, normalize_image
class SegmentationPredictor(BasePredictor):
"""Image predictor to NNGA models
Parameters
----------
model_dir : {str}
Path... | [
"cv2.threshold",
"nnga.utils.data_manipulation.adjust_image_shape",
"numpy.array"
] | [((1045, 1088), 'nnga.utils.data_manipulation.adjust_image_shape', 'adjust_image_shape', (['inpt', 'self._image_shape'], {}), '(inpt, self._image_shape)\n', (1063, 1088), False, 'from nnga.utils.data_manipulation import adjust_image_shape, normalize_image\n'), ((1738, 1794), 'cv2.threshold', 'cv2.threshold', (['predcit... |
import unittest
from gcloud.aio.run import RunService
class RunServiceTest(unittest.TestCase):
def setUp(self) -> None:
self.service = RunService(raw={"metadata":
{
"name": "service-name"
},
"status": {
"address": {
"url": "the-url"
}
}}
)
def te... | [
"gcloud.aio.run.RunService"
] | [((144, 245), 'gcloud.aio.run.RunService', 'RunService', ([], {'raw': "{'metadata': {'name': 'service-name'}, 'status': {'address': {'url':\n 'the-url'}}}"}), "(raw={'metadata': {'name': 'service-name'}, 'status': {'address':\n {'url': 'the-url'}}})\n", (154, 245), False, 'from gcloud.aio.run import RunService\n'... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import unittest
from classy_vision.dataset.core.random_image_datasets import (
RandomImageBinaryClassDataset,
)
fr... | [
"classy_vision.dataset.core.random_image_datasets.RandomImageBinaryClassDataset",
"classy_vision.dataset.transforms.util.build_field_transform_default_imagenet"
] | [((598, 689), 'classy_vision.dataset.core.random_image_datasets.RandomImageBinaryClassDataset', 'RandomImageBinaryClassDataset', ([], {'crop_size': '(224)', 'class_ratio': '(0.5)', 'num_samples': '(100)', 'seed': '(0)'}), '(crop_size=224, class_ratio=0.5, num_samples=\n 100, seed=0)\n', (627, 689), False, 'from clas... |
"""Traefik implementation
Custom proxy implementations can subclass :class:`Proxy`
and register in JupyterHub config:
.. sourcecode:: python
from mymodule import MyProxy
c.JupyterHub.proxy_class = MyProxy
Route Specification:
- A routespec is a URL prefix ([host]/path/), e.g.
'host.tld/path/' for host-ba... | [
"os.remove",
"json.loads",
"json.dumps",
"traitlets.Unicode",
"traitlets.Any"
] | [((921, 926), 'traitlets.Any', 'Any', ([], {}), '()\n', (924, 926), False, 'from traitlets import Any, Unicode\n'), ((971, 1032), 'traitlets.Unicode', 'Unicode', ([], {'config': '(False)', 'help': '"""The name of the key value store"""'}), "(config=False, help='The name of the key value store')\n", (978, 1032), False, ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
from scipy.interpolate import interp1d
from scipy.signal import find_peaks, peak_widths
ALLOWED_STATISTICS = ["n_spikes",
"spike_rate",
"latency_to_first_spike",
"average_AP_overshoot",
... | [
"numpy.sum",
"numpy.abs",
"matplotlib.pyplot.figure",
"scipy.signal.find_peaks",
"numpy.mean",
"matplotlib.pyplot.hlines",
"scipy.signal.peak_widths",
"numpy.max",
"matplotlib.pyplot.rcParams.update",
"matplotlib.pyplot.rc",
"matplotlib.ticker.FormatStrFormatter",
"seaborn.set",
"seaborn.set... | [((13594, 13603), 'seaborn.set', 'sns.set', ([], {}), '()\n', (13601, 13603), True, 'import seaborn as sns\n'), ((13608, 13632), 'seaborn.set_context', 'sns.set_context', (['"""paper"""'], {}), "('paper')\n", (13623, 13632), True, 'import seaborn as sns\n'), ((13637, 13690), 'seaborn.set_style', 'sns.set_style', (['"""... |
import numpy as np
lin = open("__21_d25.txt").read().splitlines(); gm = np.array([list(line) for line in lin])
def st(hN, gm):
tM = gm == hN; gS = np.roll(gm, -1, 1 if hN == ">" else 0)
tM[gS != '.'] = False; gm[tM] = '.'; tS = np.roll(tM, 1, 1 if hN == ">" else 0)
gm[tS] = hN; return len(gm[tM])
count = 1
while ... | [
"numpy.roll"
] | [((150, 188), 'numpy.roll', 'np.roll', (['gm', '(-1)', "(1 if hN == '>' else 0)"], {}), "(gm, -1, 1 if hN == '>' else 0)\n", (157, 188), True, 'import numpy as np\n'), ((232, 269), 'numpy.roll', 'np.roll', (['tM', '(1)', "(1 if hN == '>' else 0)"], {}), "(tM, 1, 1 if hN == '>' else 0)\n", (239, 269), True, 'import nump... |
import os
import requests
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def _node_exporter_svc(host):
return host.service('node_exporter')
def test_node_exporter_is_enabled(host):
assert _n... | [
"requests.get"
] | [((582, 627), 'requests.get', 'requests.get', (['"""http://127.0.0.1:9100/metrics"""'], {}), "('http://127.0.0.1:9100/metrics')\n", (594, 627), False, 'import requests\n')] |
import sys
import click
from xcube.cli.apply import apply
from xcube.cli.extract import extract
from xcube.cli.gen import gen
from xcube.cli.grid import grid
from xcube.cli.prune import prune
from xcube.cli.resample import resample
from xcube.cli.serve import serve
from xcube.cli.timeit import timeit
from xcube.cli.v... | [
"click.version_option",
"xcube.api.levels.write_levels",
"xcube.api.vars_to_dim",
"xcube.api.dump_dataset",
"click.option",
"click.ClickException",
"os.path.join",
"os.path.dirname",
"os.path.exists",
"click.command",
"click.Choice",
"click.group",
"xcube.util.cliutil.parse_cli_kwargs",
"o... | [((549, 576), 'click.command', 'click.command', ([], {'name': '"""chunk"""'}), "(name='chunk')\n", (562, 576), False, 'import click\n'), ((578, 620), 'click.argument', 'click.argument', (['"""input"""'], {'metavar': '"""<input>"""'}), "('input', metavar='<input>')\n", (592, 620), False, 'import click\n'), ((622, 666), ... |
from unittest import TestCase, TestSuite, TextTestRunner
from cryptoMath.finiteField import FieldElement
class FieldElementTest(TestCase):
def test_ne(self):
a = FieldElement(2, 31)
b = FieldElement(2, 31)
c = FieldElement(15, 31)
self.assertEqual(a, b)
self.assertTrue(a !... | [
"cryptoMath.finiteField.FieldElement",
"unittest.TextTestRunner",
"unittest.TestSuite"
] | [((1645, 1656), 'unittest.TestSuite', 'TestSuite', ([], {}), '()\n', (1654, 1656), False, 'from unittest import TestCase, TestSuite, TextTestRunner\n'), ((177, 196), 'cryptoMath.finiteField.FieldElement', 'FieldElement', (['(2)', '(31)'], {}), '(2, 31)\n', (189, 196), False, 'from cryptoMath.finiteField import FieldEle... |
"""A domain for real-world experiments."""
import time
from itertools import combinations
from pathlib import Path
from typing import Tuple, Union
from inquire.environments.gym_wrapper_environment import Environment
from inquire.interactions.feedback import Trajectory
from numba import jit
import numpy as np
import... | [
"numpy.sum",
"numpy.empty",
"numpy.random.default_rng",
"numpy.sin",
"numpy.linalg.norm",
"numpy.exp",
"numpy.append",
"numpy.linspace",
"time.perf_counter",
"itertools.combinations",
"numpy.cos",
"numpy.argwhere",
"numpy.random.uniform",
"numpy.zeros",
"numpy.where",
"numba.jit",
"n... | [((15354, 15372), 'numba.jit', 'jit', ([], {'nopython': '(True)'}), '(nopython=True)\n', (15357, 15372), False, 'from numba import jit\n'), ((15497, 15517), 'numpy.empty', 'np.empty', (['(2, count)'], {}), '((2, count))\n', (15505, 15517), True, 'import numpy as np\n'), ((1407, 1440), 'numpy.random.default_rng', 'np.ra... |
import discord
from discord.ext import commands
import pymongo
from pymongo import MongoClient
import random
from datetime import datetime
class vein6(commands.Cog, name= "custom"):
def __init__(self, Bot):
self.Bot = Bot
'''@commands.Cog.listener()
@commands.cooldown(1, 15, comman... | [
"discord.ext.commands.command",
"discord.ext.commands.has_permissions",
"random.choice",
"datetime.datetime.utcnow",
"discord.ext.commands.guild_only"
] | [((1228, 1326), 'discord.ext.commands.command', 'commands.command', ([], {'aliases': "['cc list']", 'description': 'f"""List all the available custom commands."""'}), "(aliases=['cc list'], description=\n f'List all the available custom commands.')\n", (1244, 1326), False, 'from discord.ext import commands\n'), ((13... |
import os
from typing import List
def get_files_with_type_from_folder(folder: str, file_type: str) -> List:
files = []
for file in os.listdir(folder):
if file.endswith(file_type):
files.append(folder+'/'+file)
return files
def get_entry_as_string(entry, headlines, join_string) -> st... | [
"os.listdir"
] | [((141, 159), 'os.listdir', 'os.listdir', (['folder'], {}), '(folder)\n', (151, 159), False, 'import os\n')] |
from app.worker import WorkerClass
import json
""" получение конфигурационных данных из json файла """
with open('config.json') as file:
file = json.load(file)
work = WorkerClass(file['mongo_con_str'], file['url_for_parse'])
work.parse_worker()
| [
"json.load",
"app.worker.WorkerClass"
] | [((175, 232), 'app.worker.WorkerClass', 'WorkerClass', (["file['mongo_con_str']", "file['url_for_parse']"], {}), "(file['mongo_con_str'], file['url_for_parse'])\n", (186, 232), False, 'from app.worker import WorkerClass\n'), ((151, 166), 'json.load', 'json.load', (['file'], {}), '(file)\n', (160, 166), False, 'import j... |
#!/usr/bin/env python3
# importing the required modules
import argparse as argp
import gc
from time import time
from matplotlib import pyplot as plt
from pandas import read_csv
def fps_graph_fv(csv_path, transparent_background, resolution, title, preset_frame_range, colour, back_colour,
out_folder,... | [
"argparse.ArgumentParser",
"pandas.read_csv",
"matplotlib.pyplot.yticks",
"time.time",
"gc.collect",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.subplots"
] | [((17014, 17264), 'argparse.ArgumentParser', 'argp.ArgumentParser', ([], {'description': '"""Generates image sequences from FPS/FrameTime information captured by FPS recording software (only Nvidia FrameView support right now).\nSupported files: .csv and MSI Afterburner .hml"""', 'allow_abbrev': '(False)'}), '(descript... |
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 3.0.10
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info as _swig_python_version_info
if _swig_python_version_info >= (2, 7, 0):
def swi... | [
"_Channel.CFileChannel_listen",
"_Channel.CChannel_checkType",
"_Channel.disown_CSharedMemChannel",
"_Channel.CFileChannel_isConnected",
"_Channel.charArray_frompointer",
"os.path.dirname",
"_Channel.charArray___getitem__",
"_Channel.CPipeChannel_wait",
"_Channel.CFileChannelU_write",
"_Channel.ne... | [((4484, 4517), '_Channel.charArray_frompointer', '_Channel.charArray_frompointer', (['t'], {}), '(t)\n', (4514, 4517), False, 'import _Channel\n'), ((8842, 8880), '_Channel.CChannel_create', '_Channel.CChannel_create', (['eType', 'sDesc'], {}), '(eType, sDesc)\n', (8866, 8880), False, 'import _Channel\n'), ((8974, 901... |
# Generated by Django 3.2.9 on 2022-01-04 20:23
import cloudinary.models
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_US... | [
"django.db.models.TextField",
"django.db.models.OneToOneField",
"django.db.migrations.swappable_dependency",
"django.db.models.BigAutoField",
"django.db.models.CharField",
"django.db.models.ForeignKey",
"django.db.models.EmailField",
"django.db.models.IntegerField",
"django.db.models.DateField"
] | [((272, 329), 'django.db.migrations.swappable_dependency', 'migrations.swappable_dependency', (['settings.AUTH_USER_MODEL'], {}), '(settings.AUTH_USER_MODEL)\n', (303, 329), False, 'from django.db import migrations, models\n'), ((462, 558), 'django.db.models.BigAutoField', 'models.BigAutoField', ([], {'auto_created': '... |
"""grid_world.py
A simple grid world environment. Edges of the map are treated like obstacles
Map must be a image file whose values represent free (255, white), occupied (0, black).
"""
from __future__ import print_function, absolute_import, division
import cv2
import numpy as np
from bc_exploration.mapping.costmap i... | [
"numpy.zeros_like",
"bc_exploration.utilities.util.xy_to_rc",
"numpy.concatenate",
"cv2.cvtColor",
"cv2.waitKey",
"cv2.destroyAllWindows",
"cv2.getStructuringElement",
"cv2.imread",
"numpy.max",
"numpy.random.randint",
"numpy.array",
"bc_exploration.utilities.util.compute_connected_pixels",
... | [((3156, 3196), 'numpy.random.randint', 'np.random.randint', (['valid_points.shape[0]'], {}), '(valid_points.shape[0])\n', (3173, 3196), True, 'import numpy as np\n'), ((4845, 4865), 'cv2.imread', 'cv2.imread', (['filename'], {}), '(filename)\n', (4855, 4865), False, 'import cv2\n'), ((4980, 5022), 'cv2.cvtColor', 'cv2... |
import CSDGAN.utils.constants as cs
import CSDGAN.utils.db as db
import CSDGAN.utils.utils as cu
import CSDGAN.utils.img_data_loading as cuidl
import logging
import os
import pickle as pkl
def make_image_dataset(run_id, username, title, folder, bs, x_dim=None, splits=None):
"""
Requirements of image data set... | [
"pickle.dump",
"CSDGAN.utils.img_data_loading.preprocess_imported_dataset",
"CSDGAN.utils.img_data_loading.import_dataset",
"os.path.exists",
"CSDGAN.utils.db.query_verify_live_run",
"CSDGAN.utils.utils.setup_run_logger",
"CSDGAN.utils.db.query_set_status",
"os.path.join",
"logging.getLogger"
] | [((1122, 1161), 'CSDGAN.utils.db.query_verify_live_run', 'db.query_verify_live_run', ([], {'run_id': 'run_id'}), '(run_id=run_id)\n', (1146, 1161), True, 'import CSDGAN.utils.db as db\n'), ((1167, 1239), 'CSDGAN.utils.utils.setup_run_logger', 'cu.setup_run_logger', ([], {'name': '"""dataset_func"""', 'username': 'usern... |
import pytest
from tests.mocks import MockOktaClient
import okta.models as models
from http import HTTPStatus
from okta.errors.okta_api_error import OktaAPIError
class TestEventHooksResource:
"""
Integration Tests for the Event Hooks Resource
"""
SDK_PREFIX = "python_sdk"
EVENT_TYPE = "EVENT_TYPE"... | [
"pytest.mark.vcr",
"okta.models.EventHookChannelConfigAuthScheme",
"tests.mocks.MockOktaClient",
"okta.models.EventHookChannelConfigHeader",
"okta.models.EventSubscriptions"
] | [((327, 344), 'pytest.mark.vcr', 'pytest.mark.vcr', ([], {}), '()\n', (342, 344), False, 'import pytest\n'), ((3082, 3099), 'pytest.mark.vcr', 'pytest.mark.vcr', ([], {}), '()\n', (3097, 3099), False, 'import pytest\n'), ((7952, 7969), 'pytest.mark.vcr', 'pytest.mark.vcr', ([], {}), '()\n', (7967, 7969), False, 'import... |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unl... | [
"aws_orbit.messages.MessagesContext",
"aws_orbit.plugins.PLUGINS_REGISTRIES.load_plugins",
"aws_orbit.models.context.ContextSerDe.load_context_from_ssm",
"aws_orbit.services.codebuild.generate_spec",
"aws_orbit.services.ssm.cleanup_changeset",
"aws_orbit.services.cfn.does_stack_exist",
"aws_orbit.remote... | [((890, 917), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (907, 917), False, 'import logging\n'), ((989, 1044), 'aws_orbit.messages.MessagesContext', 'MessagesContext', (['"""Destroying Docker Image"""'], {'debug': 'debug'}), "('Destroying Docker Image', debug=debug)\n", (1004, 1044), ... |
# # lets write a store class with a name and categories
# class Store:
# def __init__(self, name, categories):
# # attributes
# self.name = name # string has_a name
# self.categories = categories # has_a (has_many) composition
# def __str__(self):
# ret = f"{self.name}\n"
# ... | [
"product.Sneakers",
"os.path.abspath",
"IntroIII.category.Category",
"product.SoccerBall"
] | [((2328, 2400), 'product.SoccerBall', 'SoccerBall', (['"""VBall"""', '"""50"""', '"""leather"""', '"""Virtue Spots"""', '"""black and orange"""'], {}), "('VBall', '50', 'leather', 'Virtue Spots', 'black and orange')\n", (2338, 2400), False, 'from product import Sneakers, SoccerBall\n'), ((2514, 2600), 'product.Sneakers... |
import os
# Directories
ROOT=os.path.dirname(os.path.realpath(__file__))
REPOS=os.path.join(ROOT, "repos")
GAME_CONF=os.path.join(ROOT, "game_config.json")
SRC_CONF=os.path.join(ROOT, "sources.json")
| [
"os.path.realpath",
"os.path.join"
] | [((80, 107), 'os.path.join', 'os.path.join', (['ROOT', '"""repos"""'], {}), "(ROOT, 'repos')\n", (92, 107), False, 'import os\n'), ((119, 157), 'os.path.join', 'os.path.join', (['ROOT', '"""game_config.json"""'], {}), "(ROOT, 'game_config.json')\n", (131, 157), False, 'import os\n'), ((167, 201), 'os.path.join', 'os.pa... |
# Get elemental data from pymatgen
import json
from pymatgen import Element
atomic_numbers = {e.symbol: e.Z for e in Element}
atomic_weights = {e.symbol: e.atomic_mass for e in Element}
with open('../data/atomic_numbers.json', 'w') as f:
json.dump(atomic_numbers, f)
with open('../data/atomic_weights.json', 'w') ... | [
"json.dump"
] | [((245, 273), 'json.dump', 'json.dump', (['atomic_numbers', 'f'], {}), '(atomic_numbers, f)\n', (254, 273), False, 'import json\n'), ((330, 358), 'json.dump', 'json.dump', (['atomic_weights', 'f'], {}), '(atomic_weights, f)\n', (339, 358), False, 'import json\n')] |
import subprocess
import yaml
from m2g.utils.gen_utils import run
def make_dataconfig(input_dir, sub, ses, anat, func, acquisition='alt+z', tr=2.0):
"""Generates the data_config file needed by cpac
Arguments:
input_dir {str} -- Path of directory containing input files
sub {int} -- subject ... | [
"yaml.dump",
"subprocess.call",
"m2g.utils.gen_utils.run"
] | [((1597, 1627), 'm2g.utils.gen_utils.run', 'run', (['f"""chmod +x {cpac_script}"""'], {}), "(f'chmod +x {cpac_script}')\n", (1600, 1627), False, 'from m2g.utils.gen_utils import run\n'), ((2552, 2594), 'subprocess.call', 'subprocess.call', (['[cpac_script]'], {'shell': '(True)'}), '([cpac_script], shell=True)\n', (2567... |
# Generated by Django 2.0.5 on 2018-06-12 14:49
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('zconnect', '0011_fix_url_length'),
('zc_billing', '0002_add_bill_foreign_keys'),
('zc_timeseries', '0001_initial'),
('organizations', '0003_f... | [
"django.db.migrations.RemoveField",
"django.db.migrations.DeleteModel"
] | [((436, 505), 'django.db.migrations.RemoveField', 'migrations.RemoveField', ([], {'model_name': '"""companygroup"""', 'name': '"""distributor"""'}), "(model_name='companygroup', name='distributor')\n", (458, 505), False, 'from django.db import migrations\n'), ((550, 616), 'django.db.migrations.RemoveField', 'migrations... |
import os
import torch
import torch.nn as nn
import numpy as np
from .helpers import forward_multi_scale, forward_single_scale
class Predictor(nn.Module):
def __init__(self, multi_scale=False):
super().__init__()
self.multi_scale = multi_scale
# sample images using specified snapshot model... | [
"torch.unsqueeze",
"torch.no_grad"
] | [((397, 412), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (410, 412), False, 'import torch\n'), ((619, 642), 'torch.unsqueeze', 'torch.unsqueeze', (['img', '(0)'], {}), '(img, 0)\n', (634, 642), False, 'import torch\n')] |
from __future__ import print_function
import save_novel
import tensorflow as tf
import os
import sys
import random
import numpy as np
import re
import MeCab
from glob import glob
from keras.optimizers import RMSprop
from keras.layers import LSTM
from keras.layers import Dense
from keras.models import Sequential
from ke... | [
"sys.stdout.write",
"numpy.sum",
"numpy.log",
"tensorflow.config.experimental.get_memory_growth",
"numpy.argmax",
"numpy.random.multinomial",
"numpy.asarray",
"os.path.exists",
"tensorflow.config.experimental.set_memory_growth",
"keras.callbacks.LambdaCallback",
"MeCab.Tagger",
"numpy.exp",
... | [((375, 426), 'tensorflow.config.experimental.list_physical_devices', 'tf.config.experimental.list_physical_devices', (['"""GPU"""'], {}), "('GPU')\n", (419, 426), True, 'import tensorflow as tf\n'), ((821, 845), 'MeCab.Tagger', 'MeCab.Tagger', (['"""-Owakati"""'], {}), "('-Owakati')\n", (833, 845), False, 'import MeCa... |
# Copyright 2016 Cisco Systems, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | [
"rally.plugins.load",
"json.dumps",
"rally.api.Deployment.get",
"rally.common.db.schema_create",
"os.path.join",
"cloud99.logging_setup.LOGGER.exception",
"voluptuous.Optional",
"os.path.dirname",
"rally.cli.commands.task.TaskCommands",
"rally.api.Task.create",
"threading.Thread",
"rally.api.T... | [((3736, 3756), 'rally.plugins.load', 'load_rally_plugins', ([], {}), '()\n', (3754, 3756), True, 'from rally.plugins import load as load_rally_plugins\n'), ((5536, 5564), 'time.sleep', 'time.sleep', (['self.start_delay'], {}), '(self.start_delay)\n', (5546, 5564), False, 'import time\n'), ((5591, 5645), 'rally.api.Tas... |
# -*- coding: utf-8 -*-
"""Parser for Windows Restore Point (rp.log) files."""
import logging
import os
import construct
from plaso.events import time_events
from plaso.lib import errors
from plaso.lib import eventdata
from plaso.parsers import interface
from plaso.parsers import manager
class RestorePointInfoEven... | [
"construct.Field",
"construct.ULInt64",
"plaso.lib.errors.UnableToParseFile",
"plaso.parsers.manager.ParsersManager.RegisterParser",
"construct.ULInt32"
] | [((4855, 4915), 'plaso.parsers.manager.ParsersManager.RegisterParser', 'manager.ParsersManager.RegisterParser', (['RestorePointLogParser'], {}), '(RestorePointLogParser)\n', (4892, 4915), False, 'from plaso.parsers import manager\n'), ((1498, 1530), 'construct.ULInt32', 'construct.ULInt32', (['u"""event_type"""'], {}),... |
import en_core_web_lg
import json
import pickle
import numpy as np
import rdflib
class FoodEmbeddingSims:
def run(self, *,
spacy_savefile = '../data/out/spacy_ing_sim.pkl',
w2v_savefile = '../data/out/w2v_ing_sim.pkl',
substitution_data_file = '../data/in/foodsubs_data.json',
... | [
"pickle.dump",
"rdflib.Graph",
"json.load",
"numpy.multiply",
"numpy.sum",
"rdflib.URIRef",
"en_core_web_lg.load",
"numpy.mean",
"numpy.array",
"gensim.models.KeyedVectors.load_word2vec_format"
] | [((459, 473), 'rdflib.Graph', 'rdflib.Graph', ([], {}), '()\n', (471, 473), False, 'import rdflib\n'), ((1741, 1762), 'en_core_web_lg.load', 'en_core_web_lg.load', ([], {}), '()\n', (1760, 1762), False, 'import en_core_web_lg\n'), ((3939, 3995), 'gensim.models.KeyedVectors.load_word2vec_format', 'KeyedVectors.load_word... |
import re
import sys
import os
print('***********************************************************************')
print('Let us check on that pyarrow version...')
print('***********************************************************************')
print()
pyarrow_version = sys.modules["pyarrow"].__version__
f = re.search("... | [
"sys.modules.keys",
"re.search"
] | [((309, 345), 're.search', 're.search', (['"""0.15.+"""', 'pyarrow_version'], {}), "('0.15.+', pyarrow_version)\n", (318, 345), False, 'import re\n'), ((379, 397), 'sys.modules.keys', 'sys.modules.keys', ([], {}), '()\n', (395, 397), False, 'import sys\n')] |
import os
from numpy.testing import assert_allclose, assert_equal
from astropy.io import fits
import shutil
import numpy as np
def spectrum_answer_testing(spec, filename, answer_store, answer_dir):
testfile = os.path.join(answer_dir, filename)
if answer_store:
spec.write_h5_file(testfile, overwrite=Tr... | [
"astropy.io.fits.open",
"numpy.testing.assert_equal",
"shutil.copy",
"numpy.testing.assert_allclose",
"os.path.join",
"numpy.issubdtype"
] | [((215, 249), 'os.path.join', 'os.path.join', (['answer_dir', 'filename'], {}), '(answer_dir, filename)\n', (227, 249), False, 'import os\n'), ((699, 733), 'os.path.join', 'os.path.join', (['answer_dir', 'filename'], {}), '(answer_dir, filename)\n', (711, 733), False, 'import os\n'), ((395, 451), 'numpy.testing.assert_... |
"""
File: main2.py
Author: <NAME>
Email: <EMAIL>
Date: 2019-08-12
Description: main
"""
import sys
from PySide2.QtUiTools import QUiLoader
from PySide2.QtWidgets import QApplication
from PySide2 import QtCore
from PySide2.QtCore import QFile, QCoreApplication
from pyqt_corrector.mainwindow import MainWindow
from pyqt... | [
"PySide2.QtCore.QFile",
"PySide2.QtCore.QCoreApplication.setAttribute",
"PySide2.QtUiTools.QUiLoader",
"PySide2.QtWidgets.QApplication"
] | [((440, 503), 'PySide2.QtCore.QCoreApplication.setAttribute', 'QCoreApplication.setAttribute', (['QtCore.Qt.AA_ShareOpenGLContexts'], {}), '(QtCore.Qt.AA_ShareOpenGLContexts)\n', (469, 503), False, 'from PySide2.QtCore import QFile, QCoreApplication\n'), ((514, 530), 'PySide2.QtWidgets.QApplication', 'QApplication', ([... |
import torch
from kayddrl.utils import utils
from kayddrl.utils.logging import logger
class Engine:
def __init__(self, env, agent, config):
self.env = env
self.agent = agent
self._config = config
self._logger = logger
self.max_time_steps = env.max_steps
self.score... | [
"kayddrl.utils.utils.set_attr"
] | [((336, 410), 'kayddrl.utils.utils.set_attr', 'utils.set_attr', (['self', 'self._config', "['num_episodes', 'to_be_solved_score']"], {}), "(self, self._config, ['num_episodes', 'to_be_solved_score'])\n", (350, 410), False, 'from kayddrl.utils import utils\n')] |
from utils.data_adapters.json_adapter import JsonAdapter
from utils.data_adapters.memory_adapter import MemoryAdapter
from utils.data_adapters.mongodb_adapter import MongodbAdapter
def get_data_adapter(strategy='MemoryAdapter',
data_path='',
database_url=None,
... | [
"utils.data_adapters.json_adapter.JsonAdapter",
"utils.data_adapters.memory_adapter.MemoryAdapter",
"utils.data_adapters.mongodb_adapter.MongodbAdapter"
] | [((847, 887), 'utils.data_adapters.json_adapter.JsonAdapter', 'JsonAdapter', ([], {'data_storage_path': 'data_path'}), '(data_storage_path=data_path)\n', (858, 887), False, 'from utils.data_adapters.json_adapter import JsonAdapter\n'), ((667, 770), 'utils.data_adapters.mongodb_adapter.MongodbAdapter', 'MongodbAdapter',... |
# An example of using a tensorflow custom core estimator with contrib predictor for increased inference performance.
# Attempts to use up-to-date best practice for tensorflow development and keep dependencies to a minimum.
# Performs a regression using a deep neural network where the number of inputs and outputs can ... | [
"numpy.full",
"tensorflow.estimator.export.PredictOutput",
"tensorflow.train.get_global_step",
"tensorflow.losses.mean_squared_error",
"tensorflow.estimator.export.ServingInputReceiver",
"tensorflow.layers.dense",
"tensorflow.train.AdagradOptimizer",
"numpy.float32",
"time.clock",
"tensorflow.laye... | [((2948, 3012), 'tensorflow.contrib.predictor.from_estimator', 'tf.contrib.predictor.from_estimator', (['estimator', 'serving_input_fn'], {}), '(estimator, serving_input_fn)\n', (2983, 3012), True, 'import tensorflow as tf\n'), ((3045, 3077), 'numpy.random.rand', 'np.random.rand', (['(1)', 'FEATURES_RANK'], {}), '(1, F... |
import pytest
import os
import argparse
from shopify_scrape.extract import (
extract, extract_url, parse_args, extract_batch)
@pytest.mark.parametrize('args_str, expectation',
[
('url example.com -p 2 1'.split(),
pytest.raises(Va... | [
"shopify_scrape.extract.extract_batch",
"shopify_scrape.extract.extract",
"shopify_scrape.extract.parse_args",
"os.path.exists",
"shopify_scrape.extract.extract_url",
"pytest.raises",
"os.path.join"
] | [((1306, 1323), 'shopify_scrape.extract.extract_url', 'extract_url', (['args'], {}), '(args)\n', (1317, 1323), False, 'from shopify_scrape.extract import extract, extract_url, parse_args, extract_batch\n'), ((1427, 1482), 'shopify_scrape.extract.extract', 'extract', (['"""https://bombas.com/products.json"""', '"""produ... |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from torch.testing._internal.common_methods_invocations import op_db
from torch.testing._internal.common_device_ty... | [
"torch.testing._internal.common_utils.run_tests",
"functorch_lagging_op_db.in_functorch_lagging_op_db",
"torch.testing._internal.common_device_type.ops"
] | [((742, 783), 'torch.testing._internal.common_device_type.ops', 'ops', (['op_db'], {'allowed_dtypes': '(torch.float,)'}), '(op_db, allowed_dtypes=(torch.float,))\n', (745, 783), False, 'from torch.testing._internal.common_device_type import instantiate_device_type_tests, ops\n'), ((1306, 1317), 'torch.testing._internal... |
from covariance import Covariance
import numpy as np
from scipy.special import gamma
"""Covariance run 1: COSMOS-like with no lensing fields"""
# Generate non-fit parameters.
# .. These values should be motivated to reflect actual data
# .. Postage stamp size
Nx = 150
Ny = 150
# .. Standard galaxy size (in pixels)
a... | [
"scipy.special.gamma",
"numpy.array",
"numpy.sqrt"
] | [((891, 959), 'numpy.array', 'np.array', (['(0.5, 0.5, ns, rs, q, phi, psi111, psi112, psi122, psi222)'], {}), '((0.5, 0.5, ns, rs, q, phi, psi111, psi112, psi122, psi222))\n', (899, 959), True, 'import numpy as np\n'), ((775, 802), 'numpy.sqrt', 'np.sqrt', (['((1 + q ** 2.0) / 2)'], {}), '((1 + q ** 2.0) / 2)\n', (782... |
import abc
from collections import namedtuple
class Privilege(namedtuple('Privilege', ('name', 'description', 'categories')), metaclass=abc.ABCMeta):
def __eq__(self, other):
return isinstance(other, Privilege) and self.name == other.name
def __hash__(self):
return hash(self.name)
def _... | [
"collections.namedtuple"
] | [((64, 126), 'collections.namedtuple', 'namedtuple', (['"""Privilege"""', "('name', 'description', 'categories')"], {}), "('Privilege', ('name', 'description', 'categories'))\n", (74, 126), False, 'from collections import namedtuple\n')] |
from os import path
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
FILTERED_METHODS = [
'addCleanup',
'addTypeEquality',
'addTypeEqualityFunc',
'countTestCases',
'debug',
'defaultTestResult',
'doCleanups',
'id',
'setUp',
... | [
"os.path.dirname",
"pdoc.TemplateLookup",
"pdoc.html",
"os.path.join",
"sys.exit"
] | [((823, 854), 'os.path.join', 'path.join', (['doc_dir', '"""templates"""'], {}), "(doc_dir, 'templates')\n", (832, 854), False, 'from os import path\n'), ((877, 924), 'pdoc.TemplateLookup', 'pdoc.TemplateLookup', ([], {'directories': '[template_dir]'}), '(directories=[template_dir])\n', (896, 924), False, 'import pdoc\... |
from behaviour_cloning import *
import tensorflow as tf
import pickle
import mujoco_py
import gym
import numpy as np
def main():
observations, actions = process_expert_data("Humanoid-v2")
comp_returns= np.zeros(shape=(20,20))
comp_avg_return=[]
for i in range (20):
train_model(observations, act... | [
"numpy.zeros",
"numpy.concatenate"
] | [((211, 235), 'numpy.zeros', 'np.zeros', ([], {'shape': '(20, 20)'}), '(shape=(20, 20))\n', (219, 235), True, 'import numpy as np\n'), ((525, 582), 'numpy.concatenate', 'np.concatenate', (['(observations, eval_observations)'], {'axis': '(0)'}), '((observations, eval_observations), axis=0)\n', (539, 582), True, 'import ... |
import os
import pyglet
from utils import interface_mixin
from utils import sprite_patching
from utils import utils
arrow_left_btn_png = pyglet.resource.image(os.path.join("static", "arrow_left.png"))
arrow_left_btn_pressed_png = pyglet.resource.image(os.path.join("static", "arrow_left_pressed.png"))
arrow_right_bt... | [
"os.path.abspath",
"pyglet.graphics.glTexParameteri",
"pyglet.window.instance.remove_handlers",
"pyglet.window.instance.get_size",
"utils.utils.is_collide_2d",
"utils.sprite_patching.SpritePatched",
"pyglet.sprite.Sprite",
"os.path.join",
"pyglet.window.instance.push_handlers"
] | [((161, 201), 'os.path.join', 'os.path.join', (['"""static"""', '"""arrow_left.png"""'], {}), "('static', 'arrow_left.png')\n", (173, 201), False, 'import os\n'), ((254, 302), 'os.path.join', 'os.path.join', (['"""static"""', '"""arrow_left_pressed.png"""'], {}), "('static', 'arrow_left_pressed.png')\n", (266, 302), Fa... |
#!/usr/bin/env python3
'''
<NAME>, <EMAIL>
2020/05/23
Python code to read the sensor data from the
Silicon Labs Thunderboard Sense2
command-line input parameters:
--time [seconds]
--sensor
outputs:
CSV of all sensor data
plot of all specific sensor
v0.1 : inital version
'''
import serial
import datetime
im... | [
"serial.Serial",
"matplotlib.pyplot.show",
"argparse.ArgumentParser",
"matplotlib.pyplot.ioff",
"serial.tools.list_ports.comports",
"matplotlib.pyplot.subplots",
"time.sleep",
"datetime.datetime",
"numpy.append",
"matplotlib.pyplot.style.use",
"datetime.datetime.utcnow",
"numpy.array",
"plat... | [((509, 532), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (530, 532), False, 'import datetime\n'), ((638, 655), 'platform.system', 'platform.system', ([], {}), '()\n', (653, 655), False, 'import platform\n'), ((657, 671), 'appnope.nope', 'appnope.nope', ([], {}), '()\n', (669, 671), False, 'impo... |
#!/usr/bin/env python
# python_example.py
# Author: <NAME>
#
# This is a direct port to python of the shared library example from
# ALE provided in doc/examples/sharedLibraryInterfaceExample.cpp
import sys
from random import randrange
from ale_python_interface import ALEInterface
if len(sys.argv) < 2:
print('Usage: ... | [
"sys.platform.startswith",
"pygame.init",
"ale_python_interface.ALEInterface",
"sys.exit"
] | [((368, 382), 'ale_python_interface.ALEInterface', 'ALEInterface', ([], {}), '()\n', (380, 382), False, 'from ale_python_interface import ALEInterface\n'), ((350, 360), 'sys.exit', 'sys.exit', ([], {}), '()\n', (358, 360), False, 'import sys\n'), ((689, 702), 'pygame.init', 'pygame.init', ([], {}), '()\n', (700, 702), ... |
"""Utilities to import data into M/EEG preprocessing pipelines."""
# Authors: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
#
# License: BSD (3-clause)
import nipype.pipeline.engine as pe
from nipype.interfaces.utility import IdentityInterface, Function
import nipype.interfaces.io as nio
def create_iterator(fields, ... | [
"nipype.interfaces.io.DataGrabber",
"nipype.interfaces.utility.IdentityInterface",
"nipype.interfaces.utility.Function"
] | [((1094, 1126), 'nipype.interfaces.utility.IdentityInterface', 'IdentityInterface', ([], {'fields': 'fields'}), '(fields=fields)\n', (1111, 1126), False, 'from nipype.interfaces.utility import IdentityInterface, Function\n'), ((2686, 2741), 'nipype.interfaces.io.DataGrabber', 'nio.DataGrabber', ([], {'infields': 'infie... |
import fridge.utilities.mcnpCreatorFunctions as MCF
import numpy as np
def test_getRCC():
surfaceCard = MCF.getRCC(0.5, 10, [0.0, 0.0, 0.5555555], 1, '$ Comment')
surfaceCardKnown = '1 RCC 0.0 0.0 0.55556 0 0 10 0.5 $ Comment'
assert surfaceCard == surfaceCardKnown
def test_getRHP():
surfaceCard = M... | [
"fridge.utilities.mcnpCreatorFunctions.getCoolantWireWrapSmear",
"fridge.utilities.mcnpCreatorFunctions.getRHP",
"fridge.utilities.mcnpCreatorFunctions.getSmearedMaterial",
"fridge.utilities.mcnpCreatorFunctions.getOutsideCell",
"fridge.utilities.mcnpCreatorFunctions.getAssemblyUniverseCell",
"fridge.util... | [((110, 168), 'fridge.utilities.mcnpCreatorFunctions.getRCC', 'MCF.getRCC', (['(0.5)', '(10)', '[0.0, 0.0, 0.5555555]', '(1)', '"""$ Comment"""'], {}), "(0.5, 10, [0.0, 0.0, 0.5555555], 1, '$ Comment')\n", (120, 168), True, 'import fridge.utilities.mcnpCreatorFunctions as MCF\n'), ((319, 377), 'fridge.utilities.mcnpCre... |
import os, pickle, sys, io
from collections import Counter, defaultdict
from argparse import ArgumentParser
script_dir = os.path.dirname(os.path.realpath(__file__))
model_dir = os.path.abspath(script_dir + os.sep + ".." + os.sep + ".." + os.sep + "models")
lib = os.path.abspath(script_dir + os.sep + "..")
sys.path.ap... | [
"sys.path.append",
"seg_eval.get_scores",
"os.path.abspath",
"pickle.dump",
"argparse.ArgumentParser",
"os.path.realpath",
"collections.defaultdict",
"pickle.load",
"io.open",
"conll_reader.read_conll",
"collections.Counter"
] | [((178, 257), 'os.path.abspath', 'os.path.abspath', (["(script_dir + os.sep + '..' + os.sep + '..' + os.sep + 'models')"], {}), "(script_dir + os.sep + '..' + os.sep + '..' + os.sep + 'models')\n", (193, 257), False, 'import os, pickle, sys, io\n'), ((265, 308), 'os.path.abspath', 'os.path.abspath', (["(script_dir + os... |
from django import forms
from .models import Picture
class PicForm(forms.ModelForm):
class Meta:
model = Picture
fields = ('image', )
class CropForm(forms.Form):
"""Django form for accepting the information passed after cropping a loaded
image
"""
imgUrl = forms.CharField(max_len... | [
"django.forms.CharField",
"django.forms.DecimalField"
] | [((297, 328), 'django.forms.CharField', 'forms.CharField', ([], {'max_length': '(250)'}), '(max_length=250)\n', (312, 328), False, 'from django import forms\n'), ((409, 429), 'django.forms.DecimalField', 'forms.DecimalField', ([], {}), '()\n', (427, 429), False, 'from django import forms\n'), ((515, 535), 'django.forms... |
from django.urls import path, re_path
from . import views
app_name = 'myapp'
urlpatterns = [
path('requestmovie/', views.requestmovie, name='requestmovie'),
path('createmovie/', views.createmovie, name='createmovie'),
path('createlist/', views.createlist, name='createlist'),
path('requests/', views.re... | [
"django.urls.re_path",
"django.urls.path"
] | [((99, 161), 'django.urls.path', 'path', (['"""requestmovie/"""', 'views.requestmovie'], {'name': '"""requestmovie"""'}), "('requestmovie/', views.requestmovie, name='requestmovie')\n", (103, 161), False, 'from django.urls import path, re_path\n'), ((167, 226), 'django.urls.path', 'path', (['"""createmovie/"""', 'views... |
import datetime
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity import Entity
from .constants import *
class RingAlarmDevice(Entity):
"""Representation of a RingAlarm device entity."""
def __init__(self, ringalar... | [
"datetime.datetime.fromtimestamp"
] | [((731, 808), 'datetime.datetime.fromtimestamp', 'datetime.datetime.fromtimestamp', (['(ringalarm_device[DEVICE_LAST_UPDATE] // 1000)'], {}), '(ringalarm_device[DEVICE_LAST_UPDATE] // 1000)\n', (762, 808), False, 'import datetime\n'), ((1305, 1370), 'datetime.datetime.fromtimestamp', 'datetime.datetime.fromtimestamp', ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import unittest
from plyse.grammar import GrammarFactory
from plyse.parser import QueryParser
from plyse.query_tree import Operand, And, Operator
class QueryParserTester(unittest.TestCase):
qp = QueryParser(GrammarFactory.build_default())
def test_init_query(self):
... | [
"unittest.main",
"plyse.grammar.GrammarFactory.build_default"
] | [((2835, 2861), 'unittest.main', 'unittest.main', ([], {'verbosity': '(3)'}), '(verbosity=3)\n', (2848, 2861), False, 'import unittest\n'), ((256, 286), 'plyse.grammar.GrammarFactory.build_default', 'GrammarFactory.build_default', ([], {}), '()\n', (284, 286), False, 'from plyse.grammar import GrammarFactory\n')] |
from urllib import response
from django.shortcuts import render
import pyrebase
from django.shortcuts import redirect
import json
from django.http import JsonResponse
from dotenv import load_dotenv, find_dotenv
import os
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
load_dotenv(BASE_DIR / ... | [
"json.loads",
"django.shortcuts.redirect",
"pyrebase.initialize_app",
"django.http.JsonResponse",
"dotenv.load_dotenv",
"pathlib.Path",
"django.shortcuts.render",
"os.getenv"
] | [((297, 327), 'dotenv.load_dotenv', 'load_dotenv', (["(BASE_DIR / '.env')"], {}), "(BASE_DIR / '.env')\n", (308, 327), False, 'from dotenv import load_dotenv, find_dotenv\n'), ((773, 804), 'pyrebase.initialize_app', 'pyrebase.initialize_app', (['config'], {}), '(config)\n', (796, 804), False, 'import pyrebase\n'), ((16... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import csv
import logging.handlers
import os
import time
import multiprocessing as mp
import xmlrpc.client as xmlrpclib
import queue
import math
import multiprocessing_logging
from scriptconfig import URL, DB, UID, PSW, WORKERS
# Set up logging
logger = logging.getLogg... | [
"os.path.basename",
"multiprocessing.Manager",
"csv.DictReader",
"multiprocessing_logging.install_mp_handler",
"os.path.splitext",
"math.isclose",
"multiprocessing.Process",
"xmlrpc.client.ServerProxy"
] | [((420, 446), 'os.path.basename', 'os.path.basename', (['__file__'], {}), '(__file__)\n', (436, 446), False, 'import os\n'), ((1170, 1227), 'multiprocessing_logging.install_mp_handler', 'multiprocessing_logging.install_mp_handler', ([], {'logger': 'logger'}), '(logger=logger)\n', (1212, 1227), False, 'import multiproce... |
import numpy as np
import matplotlib.pyplot as plt
def threshold_convolved_image(convolved_image):
tci = np.copy(convolved_image)
for i in range(3):
m = np.mean(convolved_image[:, :, i])
s = np.std(convolved_image[:, :, i])
thr = m
tci[convolved_image[:, :, i] < thr, i] = 0
... | [
"matplotlib.pyplot.subplot",
"numpy.load",
"matplotlib.pyplot.show",
"numpy.sum",
"numpy.copy",
"numpy.std",
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.figure",
"numpy.mean"
] | [((883, 915), 'numpy.load', 'np.load', (['"""../data/test/ci=0.npy"""'], {}), "('../data/test/ci=0.npy')\n", (890, 915), True, 'import numpy as np\n'), ((920, 959), 'numpy.load', 'np.load', (['"""../data/kernels/kernel=0.npy"""'], {}), "('../data/kernels/kernel=0.npy')\n", (927, 959), True, 'import numpy as np\n'), ((9... |
#!/usr/bin/python3
"""
AI Daemon to play against.
"""
# Import the saig0 library
import saig0_lib as sl
import sys, time
game_name = sys.argv[1]
ai_player = sl.saig0_player ("AI Player", "ai_player.dat")
# Create players if not created yet.
if (ai_player.secret == ""):
ai_player.create_player ()
# Join the... | [
"saig0_lib.saig0_player",
"time.sleep"
] | [((164, 209), 'saig0_lib.saig0_player', 'sl.saig0_player', (['"""AI Player"""', '"""ai_player.dat"""'], {}), "('AI Player', 'ai_player.dat')\n", (179, 209), True, 'import saig0_lib as sl\n'), ((569, 593), 'time.sleep', 'time.sleep', (['wait_seconds'], {}), '(wait_seconds)\n', (579, 593), False, 'import sys, time\n')] |
# Copyright (c) 2017-2021 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
from dazl import async_network
from dazl.ledger import CreateCommand, ExerciseCommand
import pytest
from .dars import Pending
Counter = "Pending:Counter"
Account = "Pending:Acco... | [
"dazl.ledger.CreateCommand",
"dazl.async_network",
"dazl.ledger.ExerciseCommand"
] | [((550, 590), 'dazl.async_network', 'async_network', ([], {'url': 'sandbox', 'dars': 'Pending'}), '(url=sandbox, dars=Pending)\n', (563, 590), False, 'from dazl import async_network\n'), ((1277, 1318), 'dazl.ledger.ExerciseCommand', 'ExerciseCommand', (['counter_cid', '"""Increment"""'], {}), "(counter_cid, 'Increment'... |
# -*- coding: utf-8 -*-
import httplib as http
from flask import redirect
from framework.auth.decorators import must_be_logged_in
from framework.exceptions import HTTPError, PermissionsError
from osf.models import ExternalAccount
from website.oauth.utils import get_service
from website.oauth.signals import oauth_com... | [
"admin.rdm_addons.utils.validate_rdm_addons_allowed",
"flask.redirect",
"flask.request.args.to_dict",
"furl.furl",
"osf.models.ExternalAccount.load",
"framework.exceptions.HTTPError",
"requests.get",
"website.oauth.signals.oauth_complete.send",
"website.oauth.utils.get_service"
] | [((521, 562), 'osf.models.ExternalAccount.load', 'ExternalAccount.load', (['external_account_id'], {}), '(external_account_id)\n', (541, 562), False, 'from osf.models import ExternalAccount\n'), ((1472, 1497), 'website.oauth.utils.get_service', 'get_service', (['service_name'], {}), '(service_name)\n', (1483, 1497), Fa... |
import ergo
def test_nomem():
"""
Without mem, different calls to foo() should differ sometimes
"""
def foo():
return ergo.lognormal_from_interval(1, 10)
def model():
x = foo()
y = foo()
return x == y
samples = ergo.run(model, num_samples=1000)
assert sum... | [
"ergo.run",
"ergo.lognormal_from_interval"
] | [((272, 305), 'ergo.run', 'ergo.run', (['model'], {'num_samples': '(1000)'}), '(model, num_samples=1000)\n', (280, 305), False, 'import ergo\n'), ((627, 660), 'ergo.run', 'ergo.run', (['model'], {'num_samples': '(1000)'}), '(model, num_samples=1000)\n', (635, 660), False, 'import ergo\n'), ((892, 924), 'ergo.run', 'erg... |
# Generated by Django 2.1.3 on 2019-01-03 13:32
from django.conf import settings
import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
... | [
"django.db.models.NullBooleanField",
"django.db.models.ManyToManyField",
"django.db.models.CharField",
"django.db.models.ForeignKey",
"django.db.models.BooleanField",
"django.db.models.EmailField",
"django.db.models.AutoField",
"django.db.models.IntegerField",
"django.db.models.DateTimeField"
] | [((527, 620), '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", (543, 620), False, 'from django.db import migrations, models\... |
#!/usr/bin/env python
"""
Copyright 2015 Brocade Communications Systems, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicab... | [
"xml.etree.ElementTree.fromstring",
"xml.etree.ElementTree.tostring"
] | [((1742, 1761), 'xml.etree.ElementTree.tostring', 'ET.tostring', (['result'], {}), '(result)\n', (1753, 1761), True, 'import xml.etree.ElementTree as ET\n'), ((3372, 3391), 'xml.etree.ElementTree.tostring', 'ET.tostring', (['result'], {}), '(result)\n', (3383, 3391), True, 'import xml.etree.ElementTree as ET\n'), ((441... |
import yaml
import glob
import json
env_path = "../../.env.yml"
with open(env_path) as file:
yml = yaml.load(file)
path = yml["json_dir"] + "/iiif/collections/*/*.json"
files = glob.glob(path)
manifests = []
license_check = {}
checks = [
"",
"http://kotenseki.nijl.ac.jp/page/usage.html",
"http://r... | [
"json.dump",
"yaml.load",
"json.load",
"glob.glob"
] | [((184, 199), 'glob.glob', 'glob.glob', (['path'], {}), '(path)\n', (193, 199), False, 'import glob\n'), ((3004, 3102), 'json.dump', 'json.dump', (['collection', 'fw'], {'ensure_ascii': '(False)', 'indent': '(4)', 'sort_keys': '(True)', 'separators': "(',', ':')"}), "(collection, fw, ensure_ascii=False, indent=4, sort_... |
import logging
from cliff import command
from smiley import db
from smiley.report import html
class Report(command.Command):
"""Create an HTML report for a previously captured run.
"""
log = logging.getLogger(__name__)
_cwd = None
def get_parser(self, prog_name):
parser = super(Repor... | [
"smiley.db.DB",
"smiley.report.html.HTMLReport",
"logging.getLogger"
] | [((209, 236), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (226, 236), False, 'import logging\n'), ((1167, 1194), 'smiley.db.DB', 'db.DB', (['parsed_args.database'], {}), '(parsed_args.database)\n', (1172, 1194), False, 'from smiley import db\n'), ((1284, 1462), 'smiley.report.html.HTML... |
import csv
import sys
from django.core.management.base import BaseCommand
from frontend.models import OrgBookmark
class Command(BaseCommand):
def handle(self, *args, **kwargs):
fieldnames = ["org_type", "org_code", "org_name", "email_address", "created_at"]
writer = csv.DictWriter(sys.stdout, fi... | [
"frontend.models.OrgBookmark.objects.order_by",
"csv.DictWriter"
] | [((291, 340), 'csv.DictWriter', 'csv.DictWriter', (['sys.stdout'], {'fieldnames': 'fieldnames'}), '(sys.stdout, fieldnames=fieldnames)\n', (305, 340), False, 'import csv\n'), ((395, 437), 'frontend.models.OrgBookmark.objects.order_by', 'OrgBookmark.objects.order_by', (['"""created_at"""'], {}), "('created_at')\n", (423... |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
import json
import math
from frappe import _
from frappe.utils import flt, get_datetime, getdate, date_diff, cint, nowdate, get_link_to_fo... | [
"frappe.utils.get_link_to_form",
"frappe.utils.get_datetime",
"erpnext.manufacturing.doctype.bom.bom.get_bom_items_as_dict",
"frappe.has_permission",
"frappe.db.sql_list",
"frappe.utils.nowdate",
"erpnext.stock.utils.get_latest_stock_qty",
"erpnext.manufacturing.doctype.bom.bom.validate_bom_no",
"js... | [((23538, 23556), 'frappe.whitelist', 'frappe.whitelist', ([], {}), '()\n', (23554, 23556), False, 'import frappe\n'), ((23836, 23854), 'frappe.whitelist', 'frappe.whitelist', ([], {}), '()\n', (23852, 23854), False, 'import frappe\n'), ((25200, 25218), 'frappe.whitelist', 'frappe.whitelist', ([], {}), '()\n', (25216, ... |
from django.conf import settings
from django.core import mail
from django.test import TestCase
from django.test.client import Client
from django.urls import reverse
from model_mommy import mommy
from courses.models import Course
# Create your tests here.
class CouseManagerTestCase(TestCase):
def setUp(self):
... | [
"model_mommy.mommy.make",
"courses.models.Course.objects.all",
"django.test.client.Client",
"courses.models.Course.objects.search"
] | [((514, 582), 'model_mommy.mommy.make', 'mommy.make', (['"""courses.Course"""'], {'name': '"""Python com Django"""', '_quantity': '(10)'}), "('courses.Course', name='Python com Django', _quantity=10)\n", (524, 582), False, 'from model_mommy import mommy\n'), ((631, 697), 'model_mommy.mommy.make', 'mommy.make', (['"""co... |
import copy
import warnings
from keras import backend as K
from keras import activations, regularizers
from keras.engine import InputSpec
from keras.layers import Recurrent
import numpy as np
from ...data.instances.text_classification.logical_form_instance import SHIFT_OP, REDUCE2_OP, REDUCE3_OP
class TreeCompositi... | [
"keras.backend.dot",
"copy.deepcopy",
"keras.backend.concatenate",
"keras.activations.get",
"keras.regularizers.get",
"keras.backend.zeros_like",
"keras.backend.sum",
"numpy.zeros",
"keras.backend.equal",
"keras.backend.tile",
"keras.engine.InputSpec",
"warnings.warn",
"keras.backend.permute... | [((2554, 2581), 'keras.activations.get', 'activations.get', (['activation'], {}), '(activation)\n', (2569, 2581), False, 'from keras import activations, regularizers\n'), ((2614, 2647), 'keras.activations.get', 'activations.get', (['inner_activation'], {}), '(inner_activation)\n', (2629, 2647), False, 'from keras impor... |
from app.core import settings
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return settings.__dict__
| [
"fastapi.FastAPI"
] | [((66, 75), 'fastapi.FastAPI', 'FastAPI', ([], {}), '()\n', (73, 75), False, 'from fastapi import FastAPI\n')] |
# -*- coding: utf-8 -*-
from sanic import Blueprint
from .models import api
message_api = Blueprint.group(api, url_prefix='/message') | [
"sanic.Blueprint.group"
] | [((92, 135), 'sanic.Blueprint.group', 'Blueprint.group', (['api'], {'url_prefix': '"""/message"""'}), "(api, url_prefix='/message')\n", (107, 135), False, 'from sanic import Blueprint\n')] |
from django.conf import settings
from django.test import TestCase
from django.test.utils import override_settings
from ..bower import bower_adapter
import os
import shutil
try:
TEST_COMPONENTS_ROOT = os.path.join(
settings.TEST_PROJECT_ROOT, 'bower_components',
)
except AttributeError:
TEST_COMPON... | [
"shutil.rmtree",
"os.path.exists",
"os.path.join",
"django.test.utils.override_settings"
] | [((360, 421), 'django.test.utils.override_settings', 'override_settings', ([], {'BOWER_COMPONENTS_ROOT': 'TEST_COMPONENTS_ROOT'}), '(BOWER_COMPONENTS_ROOT=TEST_COMPONENTS_ROOT)\n', (377, 421), False, 'from django.test.utils import override_settings\n'), ((206, 266), 'os.path.join', 'os.path.join', (['settings.TEST_PROJ... |
# Copyright (C) 2020 GreenWaves Technologies, SAS
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# This progr... | [
"utils.node_id.NodeId"
] | [((946, 958), 'utils.node_id.NodeId', 'NodeId', (['node'], {}), '(node)\n', (952, 958), False, 'from utils.node_id import NodeId\n')] |
from setuptools import find_packages, setup
setup(name='mlpy',
version='0.1.0',
description='an educational python-based ML library',
url='https://github.com/SNUDerek/MLPy',
author='<NAME>',
author_email='<EMAIL>',
# license='MIT',
packages=find_packages(),
zip_safe=Fals... | [
"setuptools.find_packages"
] | [((284, 299), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (297, 299), False, 'from setuptools import find_packages, setup\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''checkplotserver_handlers.py - <NAME> (<EMAIL>) -
Jan 2017
These are Tornado handlers for serving checkplots and operating on them.
'''
####################
## SYSTEM IMPORTS ##
####################
import os
import os.path
import gzi... | [
"os.remove",
"base64.b64decode",
"numpy.full_like",
"json.loads",
"os.path.dirname",
"numpy.logical_not",
"os.path.exists",
"numpy.isfinite",
"json.JSONEncoder.default",
"json.dump",
"io.BytesIO",
"os.path.basename",
"numpy.min",
"tornado.escape.xhtml_escape",
"time.time",
"numpy.any",... | [((1733, 1760), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1750, 1760), False, 'import logging\n'), ((37454, 37476), 'tornado.escape.xhtml_escape', 'xhtml_escape', (['objectid'], {}), '(objectid)\n', (37466, 37476), False, 'from tornado.escape import xhtml_escape, xhtml_unescape, url... |
# --------------------------------------- IMPORT HERE ---------------------------------------
from sqlite3 import connect
import pika
from kazoo.client import KazooClient
import logging
import csv, string, collections, datetime
import docker
import os
import time
# --------------------------------------- WORKER CODE ... | [
"logging.debug",
"logging.basicConfig",
"kazoo.client.KazooClient",
"pika.ConnectionParameters",
"time.sleep",
"logging.info",
"sqlite3.connect",
"pika.BasicProperties"
] | [((366, 487), 'logging.basicConfig', 'logging.basicConfig', ([], {'filename': '"""worker.log"""', 'format': '"""%(asctime)s => %(levelname)s : %(message)s"""', 'level': 'logging.DEBUG'}), "(filename='worker.log', format=\n '%(asctime)s => %(levelname)s : %(message)s', level=logging.DEBUG)\n", (385, 487), False, 'imp... |
from common import input_list_string
def part_one(inp_lst):
x = 0
accumulator = 0
ins_done = list()
maxx = len(inp_lst)
while x < maxx:
if x in ins_done:
break
ins_done.append(x)
ins, val = inp_lst[x].split()
if ins == "nop":
x += 1
el... | [
"common.input_list_string"
] | [((1505, 1536), 'common.input_list_string', 'input_list_string', (['"""2020"""', '"""08"""'], {}), "('2020', '08')\n", (1522, 1536), False, 'from common import input_list_string\n')] |
import json
import logging
from decimal import Decimal
# Custom log level
from enum import Enum
EVENT_LOG_LEVEL = 15
METRICS_LOG_LEVEL = 14
logging.addLevelName(EVENT_LOG_LEVEL, "EVENT_LOG")
logging.addLevelName(METRICS_LOG_LEVEL, "METRIC_LOG")
def log_encoder(obj):
if isinstance(obj, Decimal):
return s... | [
"logging.addLevelName",
"json.dumps"
] | [((142, 192), 'logging.addLevelName', 'logging.addLevelName', (['EVENT_LOG_LEVEL', '"""EVENT_LOG"""'], {}), "(EVENT_LOG_LEVEL, 'EVENT_LOG')\n", (162, 192), False, 'import logging\n'), ((193, 246), 'logging.addLevelName', 'logging.addLevelName', (['METRICS_LOG_LEVEL', '"""METRIC_LOG"""'], {}), "(METRICS_LOG_LEVEL, 'METR... |
import logging
# Configure logging module. If not set, pycord will not show any logging.
logging.basicConfig(level=logging.INFO)
# Provide a logger for our own application
logger = logging.getLogger()
| [
"logging.getLogger",
"logging.basicConfig"
] | [((90, 129), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (109, 129), False, 'import logging\n'), ((183, 202), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (200, 202), False, 'import logging\n')] |
def set_vis_args(datactr):
from visualizer.OpencvVis import CVis
datactr.vis = CVis(grab_pcl_fuc=datactr.get_data,
switch_model_func=datactr.switch_model,
switch_dataset_func=datactr.switch_dataset,
switch_pcl_func=datactr.switc... | [
"visualizer.OpencvVis.CVis"
] | [((87, 262), 'visualizer.OpencvVis.CVis', 'CVis', ([], {'grab_pcl_fuc': 'datactr.get_data', 'switch_model_func': 'datactr.switch_model', 'switch_dataset_func': 'datactr.switch_dataset', 'switch_pcl_func': 'datactr.switch_pcl', '_3d': '(False)'}), '(grab_pcl_fuc=datactr.get_data, switch_model_func=datactr.switch_model,\... |
#!/usr/bin/env python3
import logging
import sys
import usb.core
class UsbDeviceMatcher:
def __init__(self, properties, handler):
self.properties = properties
self.handler = handler
def matches(self, candidate):
for prop, value in self.properties.items():
if prop not in candidate.__dict__ or candidate.__d... | [
"sys.exit",
"logging.getLogger",
"logging.basicConfig"
] | [((1919, 1959), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.DEBUG'}), '(level=logging.DEBUG)\n', (1938, 1959), False, 'import logging\n'), ((1970, 1997), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1987, 1997), False, 'import logging\n'), ((1345, 1372), 'logg... |
import truecase
fi = open("allqueries.txt", "r")
fo = open("allQueries.txt", "w")
for q in fi:
fo.write(truecase.get_true_case(q))
fo.write("\n")
fo.close()
fi.close()
| [
"truecase.get_true_case"
] | [((107, 132), 'truecase.get_true_case', 'truecase.get_true_case', (['q'], {}), '(q)\n', (129, 132), False, 'import truecase\n')] |
import re
from collections.abc import MutableMapping
from configDmanager.errors import ReinterpretationError, FormatExecutorError
from configDmanager._format import FileReader, EnvironReader
class Config(MutableMapping):
__c_regex = re.compile(r"\${(.*?)}")
__c_fe_regex = re.compile(r'\${(.*?)\[(.*?)\]}')
... | [
"configDmanager._format.EnvironReader",
"configDmanager.errors.ReinterpretationError",
"configDmanager._format.FileReader",
"re.sub",
"re.compile"
] | [((241, 265), 're.compile', 're.compile', (['"""\\\\${(.*?)}"""'], {}), "('\\\\${(.*?)}')\n", (251, 265), False, 'import re\n'), ((285, 320), 're.compile', 're.compile', (['"""\\\\${(.*?)\\\\[(.*?)\\\\]}"""'], {}), "('\\\\${(.*?)\\\\[(.*?)\\\\]}')\n", (295, 320), False, 'import re\n'), ((4719, 4772), 're.sub', 're.sub'... |
# Newton-Raphson method for orbit calculations using numpy arrays;
from numpy import linspace, abs, sqrt, sin, cos, arctan2, array, pi
def orbit(m0, e, a, inclination, ascension, n, acc=1.e-2):
m = linspace(m0, 2 * pi + m0, n)
ecc_anom = m
ecc_anom_old = 0
while acc < abs(ecc_anom - ecc_anom_old).max(... | [
"numpy.abs",
"numpy.sin",
"numpy.array",
"numpy.linspace",
"numpy.cos",
"numpy.sqrt"
] | [((204, 232), 'numpy.linspace', 'linspace', (['m0', '(2 * pi + m0)', 'n'], {}), '(m0, 2 * pi + m0, n)\n', (212, 232), False, 'from numpy import linspace, abs, sqrt, sin, cos, arctan2, array, pi\n'), ((1117, 1133), 'numpy.array', 'array', (['(x, y, z)'], {}), '((x, y, z))\n', (1122, 1133), False, 'from numpy import lins... |
import requests
from bs4 import BeautifulSoup
import pandas as pd
import lxml
def crawl(url):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/83.0.4103.116 Safari/537.36 '
}
html = requests.get(url, headers=... | [
"bs4.BeautifulSoup",
"requests.get",
"pandas.DataFrame"
] | [((345, 372), 'bs4.BeautifulSoup', 'BeautifulSoup', (['html', '"""lxml"""'], {}), "(html, 'lxml')\n", (358, 372), False, 'from bs4 import BeautifulSoup\n'), ((1808, 1825), 'pandas.DataFrame', 'pd.DataFrame', (['dic'], {}), '(dic)\n', (1820, 1825), True, 'import pandas as pd\n'), ((294, 328), 'requests.get', 'requests.g... |
# coding: utf-8
"""
This module provides a Locator class for finding template files.
"""
import os
import re
import sys
DEFAULT_EXTENSION = 'mustache'
class Locator(object):
def __init__(self, extension=None):
"""
Construct a template locator.
Arguments:
extension: the te... | [
"os.path.dirname",
"os.path.join",
"os.path.exists",
"re.sub"
] | [((1507, 1528), 'os.path.dirname', 'os.path.dirname', (['path'], {}), '(path)\n', (1522, 1528), False, 'import os\n'), ((816, 849), 'os.path.join', 'os.path.join', (['dir_path', 'file_name'], {}), '(dir_path, file_name)\n', (828, 849), False, 'import os\n'), ((865, 890), 'os.path.exists', 'os.path.exists', (['file_path... |
import datetime
from django.conf import settings
from django.utils import timezone
from account.models import SignupCode
from waitinglist.models import WaitingListEntry
User = getattr(settings, 'AUTH_USER_MODEL', 'auth.User')
def stats():
waiting_list = WaitingListEntry.objects
return {
"waiting... | [
"django.utils.timezone.now",
"account.models.SignupCode.objects.values",
"datetime.timedelta"
] | [((447, 461), 'django.utils.timezone.now', 'timezone.now', ([], {}), '()\n', (459, 461), False, 'from django.utils import timezone\n'), ((464, 490), 'datetime.timedelta', 'datetime.timedelta', ([], {'days': '(7)'}), '(days=7)\n', (482, 490), False, 'import datetime\n'), ((591, 605), 'django.utils.timezone.now', 'timezo... |
# -*- encoding: utf-8 -*-
# Copyright (c) 2020 <NAME> <<EMAIL>>
# ISC License <https://choosealicense.com/licenses/isc>
"""Contains some common necessary frame transformation helper methods.
These transformation methods are useful for optimizing face detection in frames.
Typically face detection takes much longer the... | [
"numpy.abs",
"cv2.cvtColor",
"numpy.float32",
"cv2.warpAffine",
"cv2.convertScaleAbs",
"cv2.flip",
"cv2.getRotationMatrix2D",
"cv2.resize"
] | [((4081, 4170), 'cv2.resize', 'cv2.resize', ([], {'src': 'frame', 'dsize': 'None', 'fx': 'factor', 'fy': 'factor', 'interpolation': 'interpolation'}), '(src=frame, dsize=None, fx=factor, fy=factor, interpolation=\n interpolation)\n', (4091, 4170), False, 'import cv2\n'), ((9345, 9424), 'cv2.getRotationMatrix2D', 'cv... |
#This code comes from: https://github.com/becomequantum/kryon
from PIL import Image,ImageDraw,ImageFont
import numpy as np
#This code is only about animation. 本代码只是和做演示动画相关.
VideoSize = (1280, 720)
DemoImageSize = (48, 36)
标题位置 = (60, 16)
注释1位置 = (1000, 76)
网格位置 = (32, 76)
比例 = 17
网格颜色 = (230, 230, 230)
网三位置... | [
"PIL.ImageFont.truetype",
"PIL.ImageDraw.Draw",
"PIL.Image.new",
"numpy.array"
] | [((603, 639), 'PIL.ImageFont.truetype', 'ImageFont.truetype', (['"""msyh.ttf"""', 'Size'], {}), "('msyh.ttf', Size)\n", (621, 639), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((1592, 1628), 'PIL.Image.new', 'Image.new', (['"""RGB"""', 'VideoSize', 'BgColor'], {}), "('RGB', VideoSize, BgColor)\n", (1601, 1... |
import re
class Utils():
def __init__(self, COMMA_DELIMITER):
COMMA_DELIMITER = re.compile(''',(?=(?:[^"]*"[^"]*")*[^"]*$)''')
self.COMMA_DELIMITER = COMMA_DELIMITER
| [
"re.compile"
] | [((94, 136), 're.compile', 're.compile', (['""",(?=(?:[^"]*"[^"]*")*[^"]*$)"""'], {}), '(\',(?=(?:[^"]*"[^"]*")*[^"]*$)\')\n', (104, 136), False, 'import re\n')] |
#!/usr/bin/network python
# -*- coding: utf-8 -*-
'''
.. _module_mc_network:
mc_network / network registry
============================================
If you alter this module and want to test it, do not forget
to deploy it on minion using::
salt '*' saltutil.sync_modules
Documentation of this module is availab... | [
"mc_states.api.is_valid_ip",
"ipaddr.IPAddress",
"mc_states.api.six.iteritems",
"re.match",
"salt.utils.validate.net.ipv4_addr",
"time.time",
"salt.utils.odict.OrderedDict",
"time.sleep",
"traceback.format_exc",
"whois.query",
"ipwhois.IPWhois",
"urllib2.urlopen",
"logging.getLogger"
] | [((1027, 1054), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1044, 1054), False, 'import logging\n'), ((3513, 3537), 're.match', 're.match', (['"""^(eth0)"""', 'key'], {}), "('^(eth0)', key)\n", (3521, 3537), False, 'import re\n'), ((3573, 3630), 're.match', 're.match', (['"""^(eth[123... |
"""
For migrating recipe summaries in content/contents.lr (root)
to various directories, depending on CLI arguments.
E.g. move items based on:
- Country of origin
- Author
- Meal
"""
from pathlib import Path
LEKTOR_ROOT_DIR = project_dir = (
Path(__file__).parent.resolve().parent.parent.absolute() / "recipe-webs... | [
"pathlib.Path"
] | [((249, 263), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (253, 263), False, 'from pathlib import Path\n')] |
import logging
module_logger = logging.getLogger('H-rep')
from itertools import combinations, chain
from typing import List, Iterable, Tuple, Generator
from ortools.linear_solver import pywraplp
from bidict import bidict
from collections import namedtuple, defaultdict
Var = namedtuple('Var', ('level', 'index'))
Cov... | [
"ortools.linear_solver.pywraplp.Solver.CreateSolver",
"bidict.bidict",
"collections.defaultdict",
"collections.namedtuple",
"itertools.chain",
"logging.getLogger"
] | [((32, 58), 'logging.getLogger', 'logging.getLogger', (['"""H-rep"""'], {}), "('H-rep')\n", (49, 58), False, 'import logging\n'), ((278, 315), 'collections.namedtuple', 'namedtuple', (['"""Var"""', "('level', 'index')"], {}), "('Var', ('level', 'index'))\n", (288, 315), False, 'from collections import namedtuple, defau... |
from data_explorer.db import query_mysql
class CourseInfo:
"""Data for the General tab."""
def __init__(self, lang, course_code):
self.lang = lang
self.course_code = course_code
self.course_info = None
def load(self):
"""Query course's info from table 'product_info' and format for
display in General ... | [
"data_explorer.db.query_mysql"
] | [((1091, 1142), 'data_explorer.db.query_mysql', 'query_mysql', (['query', '(self.course_code,)'], {'dict_': '(True)'}), '(query, (self.course_code,), dict_=True)\n', (1102, 1142), False, 'from data_explorer.db import query_mysql\n')] |
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import librosa
import librosa.display
import numpy as np
def summary(x):
if x.ndim == 1:
SUM = ('\n{0:>10s}: {1:>15.4f}').format('min', np.amin(x))
SUM += ('\n{0:>10s}: {1:>15.4f}').format('1st Quar', np.percentile(x, 25))
SUM += ('\n{0:>10s... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show",
"numpy.amin",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.ylim",
"numpy.median",
"numpy.std",
"matplotlib.pyplot.colorbar",
"numpy.percentile",
"numpy.amax",
"matplotlib.pyplot.figure... | [((1882, 1910), 'numpy.linspace', 'np.linspace', (['to', 'ti', 'samples'], {}), '(to, ti, samples)\n', (1893, 1910), True, 'import numpy as np\n'), ((2373, 2388), 'matplotlib.pyplot.title', 'plt.title', (['text'], {}), '(text)\n', (2382, 2388), True, 'import matplotlib.pyplot as plt\n'), ((2390, 2400), 'matplotlib.pypl... |
import torch
class BaseObserver:
def __init__(self, module_type, bit_type, calibration_mode):
self.module_type = module_type
self.bit_type = bit_type
self.calibration_mode = calibration_mode
self.max_val = None
self.min_val = None
self.eps = torch.finfo(torch.float3... | [
"torch.finfo",
"torch.tensor"
] | [((296, 322), 'torch.finfo', 'torch.finfo', (['torch.float32'], {}), '(torch.float32)\n', (307, 322), False, 'import torch\n'), ((421, 436), 'torch.tensor', 'torch.tensor', (['v'], {}), '(v)\n', (433, 436), False, 'import torch\n')] |