code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import os
import platform
import sys
import unittest
import re
from checkov.common.models.consts import ckv_check_id_pattern
current_dir = os.path.dirname(os.path.realpath(__file__))
class TestCheckovPlatformOnlyPolicies(unittest.TestCase):
def test_no_ckv_ids_api_key(self):
checks_list_path = os.path.... | [
"unittest.main",
"os.path.realpath",
"re.match",
"platform.system",
"os.path.join"
] | [((157, 183), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (173, 183), False, 'import os\n'), ((1105, 1120), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1118, 1120), False, 'import unittest\n'), ((312, 370), 'os.path.join', 'os.path.join', (['current_dir', '""".."""', '"""checkov... |
"""Module providing functions to plot data collected during sleep studies."""
import datetime
from typing import Dict, Iterable, List, Optional, Sequence, Tuple, Union
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import matplotlib.ticker as mticks
import pandas as pd
import seaborn as sns
from fau... | [
"pandas.DataFrame",
"matplotlib.dates.DateFormatter",
"matplotlib.ticker.AutoMinorLocator",
"pandas.to_datetime",
"pandas.Timedelta",
"matplotlib.dates.date2num",
"matplotlib.pyplot.subplots"
] | [((6972, 7025), 'pandas.to_datetime', 'pd.to_datetime', (["sleep_endpoints['bed_interval_start']"], {}), "(sleep_endpoints['bed_interval_start'])\n", (6986, 7025), True, 'import pandas as pd\n'), ((7040, 7091), 'pandas.to_datetime', 'pd.to_datetime', (["sleep_endpoints['bed_interval_end']"], {}), "(sleep_endpoints['bed... |
import numpy as np
import argparse
import glob
import amrex_plot_tools as amrex
if __name__ == "__main__":
import pylab as plt
rkey, ikey = amrex.get_particle_keys()
t = []
fee = []
fexR = []
fexI = []
fxx = []
pupt = []
files = sorted(glob.glob("plt[0-9][0-9][0-9][0-9][0-9]"))
... | [
"pylab.grid",
"pylab.savefig",
"numpy.array",
"amrex_plot_tools.get_particle_keys",
"glob.glob",
"pylab.gcf",
"pylab.gca",
"amrex_plot_tools.read_particle_data",
"pylab.legend",
"pylab.plot",
"numpy.sqrt"
] | [((150, 175), 'amrex_plot_tools.get_particle_keys', 'amrex.get_particle_keys', ([], {}), '()\n', (173, 175), True, 'import amrex_plot_tools as amrex\n'), ((762, 775), 'numpy.array', 'np.array', (['fee'], {}), '(fee)\n', (770, 775), True, 'import numpy as np\n'), ((787, 801), 'numpy.array', 'np.array', (['fexR'], {}), '... |
import os
input_file = os.path.join(os.getcwd(), "day1/input.txt")
nb_valid_passwords = 0
def is_valid_password(min_occurences, max_occurrences, special_letter, password):
nb_occurences = 0
for letter in password:
if letter == special_letter:
nb_occurences += 1
return min_occure... | [
"os.getcwd"
] | [((37, 48), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (46, 48), False, 'import os\n')] |
import chess
import time
import copy
import sys
sys.path.append("..")
from parallel import search, startWorkers, stopWorkers
def main():
startWorkers() # Init multiprocessing
start = time.time()
maxPlies = 6 # zero for unlimited moves
defaultDepth = 3
if len(sys.argv) > 1:
defaul... | [
"sys.path.append",
"chess.Move.from_uci",
"copy.copy",
"parallel.search",
"time.time",
"chess.Board",
"parallel.stopWorkers",
"parallel.startWorkers"
] | [((49, 70), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (64, 70), False, 'import sys\n'), ((152, 166), 'parallel.startWorkers', 'startWorkers', ([], {}), '()\n', (164, 166), False, 'from parallel import search, startWorkers, stopWorkers\n'), ((202, 213), 'time.time', 'time.time', ([], {}), '()... |
import os
import config
from discord.ext import commands
bot = commands.Bot(command_prefix = '$')
bot.remove_command('help')
@bot.event
async def on_ready():
print('-'*34)
print('Logged in as: ', bot.user.name)
print('Client ID: ', bot.user.id)
print('Local time: ', config.SERVER_TIME)
print... | [
"os.listdir",
"discord.ext.commands.Bot"
] | [((64, 96), 'discord.ext.commands.Bot', 'commands.Bot', ([], {'command_prefix': '"""$"""'}), "(command_prefix='$')\n", (76, 96), False, 'from discord.ext import commands\n'), ((567, 586), 'os.listdir', 'os.listdir', (['"""./ocr"""'], {}), "('./ocr')\n", (577, 586), False, 'import os\n')] |
import random
population_size = 100
number_of_bins = 5
number_of_items = 10
item_limit_size = 35
max_weight = 50
items = [20, 27, 2, 14, 26, 15, 17, 13, 5, 4]
# items = [random.randrange(1, item_limit_size) for _ in range(number_of_items)]
print("bins:", number_of_bins, "|_| " * number_of_bins)
print("bin capacity:",... | [
"random.shuffle"
] | [((1083, 1108), 'random.shuffle', 'random.shuffle', (['bin_items'], {}), '(bin_items)\n', (1097, 1108), False, 'import random\n'), ((1113, 1133), 'random.shuffle', 'random.shuffle', (['bins'], {}), '(bins)\n', (1127, 1133), False, 'import random\n')] |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function
# Standard library imports
import collections
import os
import random
import sys
import tempfile
from string import Template
# Local imports
from . import paths
from .compat import numeric_types, platform, supported_platforms, string_types... | [
"tempfile.gettempdir",
"os.path.exists",
"string.Template",
"os.environ.keys",
"collections.namedtuple",
"random.getrandbits"
] | [((402, 445), 'collections.namedtuple', 'collections.namedtuple', (['"""Item"""', '"""key value"""'], {}), "('Item', 'key value')\n", (424, 445), False, 'import collections\n'), ((451, 495), 'collections.namedtuple', 'collections.namedtuple', (['"""Op"""', '"""key value op"""'], {}), "('Op', 'key value op')\n", (473, 4... |
# Generated by Django 2.0 on 2019-06-25 16:03
import ckeditor.fields
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Club',
... | [
"django.db.models.TextField",
"django.db.models.ForeignKey",
"django.db.models.CharField",
"django.db.models.AutoField",
"django.db.models.ImageField",
"django.db.models.DateField"
] | [((2565, 2689), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'default': 'None', 'on_delete': 'django.db.models.deletion.CASCADE', 'to': '"""clubs.Notification"""', 'verbose_name': '"""推送"""'}), "(default=None, on_delete=django.db.models.deletion.CASCADE,\n to='clubs.Notification', verbose_name='推送')\n",... |
#!/usr/bin/python
import struct
import sys
buffsize = 512
offset = 0
#/bin/sh
sc = b'\xeb\x14\x5f\x48\x31\xc0\x88\x47\x07\x50\x57\x48\x8d\x34\x24\xb0\x3b\x48\x31\xd2\x0f\x05\xe8\xe7\xff\xff\xff\x2f\x62\x69\x6e\x2f\x73\x68'
nopsled1 = b'\x90'*(buffsize-len(sc)-8)
nopsled2 = b'\x90'*8
rbp = b'\x90'*8
rip = struct.pac... | [
"sys.stdout.buffer.write",
"struct.pack"
] | [((310, 344), 'struct.pack', 'struct.pack', (['"""<Q"""', '(140737488349528)'], {}), "('<Q', 140737488349528)\n", (321, 344), False, 'import struct\n'), ((345, 406), 'sys.stdout.buffer.write', 'sys.stdout.buffer.write', (['(nopsled1 + sc + nopsled2 + rbp + rip)'], {}), '(nopsled1 + sc + nopsled2 + rbp + rip)\n', (368, ... |
import matplotlib.pyplot as plt
from matplotlib.cm import ScalarMappable
from matplotlib.colors import Normalize
import numpy as np
def hill_slopes(rule, transactions):
"""Visualize rule as hill slopes.
**Reference:** <NAME>. et al. (2020). Visualization of Numerical Association Rules by Hill Slopes.
In:... | [
"numpy.concatenate",
"numpy.empty",
"numpy.zeros",
"numpy.argsort",
"numpy.reshape",
"numpy.linspace",
"numpy.column_stack",
"numpy.interp",
"matplotlib.pyplot.subplots",
"numpy.all",
"numpy.sqrt"
] | [((893, 915), 'numpy.empty', 'np.empty', (['num_features'], {}), '(num_features)\n', (901, 915), True, 'import numpy as np\n'), ((1499, 1521), 'numpy.empty', 'np.empty', (['num_features'], {}), '(num_features)\n', (1507, 1521), True, 'import numpy as np\n'), ((2088, 2127), 'numpy.sqrt', 'np.sqrt', (['(support ** 2 + co... |
import asyncio
import os
from fastapi import FastAPI
from api.schemas import db
DB_RETRIES = int(os.getenv("DB_RETRIES", 3))
app = FastAPI(title="Dodobox", root_path="/api")
@app.on_event("startup")
async def startup():
exception = None
for retries in range(DB_RETRIES):
try:
await db.c... | [
"asyncio.sleep",
"api.schemas.db.disconnect",
"api.schemas.db.connect",
"os.getenv",
"fastapi.FastAPI"
] | [((135, 177), 'fastapi.FastAPI', 'FastAPI', ([], {'title': '"""Dodobox"""', 'root_path': '"""/api"""'}), "(title='Dodobox', root_path='/api')\n", (142, 177), False, 'from fastapi import FastAPI\n'), ((100, 126), 'os.getenv', 'os.getenv', (['"""DB_RETRIES"""', '(3)'], {}), "('DB_RETRIES', 3)\n", (109, 126), False, 'impo... |
from __future__ import annotations
from dataclasses import dataclass
import xml.etree.ElementTree as ET
from .relaton_bib import to_ds_instance
@dataclass
class DocumentStatus:
@dataclass
class Stage:
value: str
abbreviation: str = None
def to_xml(self, parent):
if self... | [
"xml.etree.ElementTree.Element",
"xml.etree.ElementTree.SubElement"
] | [((831, 847), 'xml.etree.ElementTree.Element', 'ET.Element', (['name'], {}), '(name)\n', (841, 847), True, 'import xml.etree.ElementTree as ET\n'), ((885, 912), 'xml.etree.ElementTree.SubElement', 'ET.SubElement', (['parent', 'name'], {}), '(parent, name)\n', (898, 912), True, 'import xml.etree.ElementTree as ET\n'), (... |
#!/usr/bin/python
import RPi.GPIO as GPIO
import subprocess
THE_PIN = 5
ON_STATE = 0
OFF_STATE = 1
print("Starting " + __file__)
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(THE_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
previousState = GPIO.input(THE_PIN)
loop = True
while loop:
GPIO.wait_for_edge... | [
"RPi.GPIO.setmode",
"RPi.GPIO.cleanup",
"RPi.GPIO.setup",
"RPi.GPIO.wait_for_edge",
"RPi.GPIO.input",
"RPi.GPIO.setwarnings"
] | [((132, 155), 'RPi.GPIO.setwarnings', 'GPIO.setwarnings', (['(False)'], {}), '(False)\n', (148, 155), True, 'import RPi.GPIO as GPIO\n'), ((156, 180), 'RPi.GPIO.setmode', 'GPIO.setmode', (['GPIO.BOARD'], {}), '(GPIO.BOARD)\n', (168, 180), True, 'import RPi.GPIO as GPIO\n'), ((181, 235), 'RPi.GPIO.setup', 'GPIO.setup', ... |
# Copyright 2015 IBM Corp.
#
# 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 a... | [
"nova_powervm.virt.powervm.media.ConfigDrivePowerVM._mac_to_link_local",
"mock.patch",
"pypowervm.wrappers.storage.VG.wrap",
"pypowervm.tests.test_fixtures.AdapterFx",
"pypowervm.tests.test_utils.pvmhttp.load_pvm_resp",
"nova_powervm.virt.powervm.media.ConfigDrivePowerVM",
"pypowervm.tests.test_fixtures... | [((2158, 2245), 'mock.patch', 'mock.patch', (['"""nova_powervm.virt.powervm.media.ConfigDrivePowerVM._validate_vopt_vg"""'], {}), "(\n 'nova_powervm.virt.powervm.media.ConfigDrivePowerVM._validate_vopt_vg')\n", (2168, 2245), False, 'import mock\n'), ((2265, 2318), 'mock.patch', 'mock.patch', (['"""nova.api.metadata.... |
from typing import Union
import re
from io import StringIO
from pathlib import Path
from sh import Command, ErrorReturnCode, TimeoutException
from firepy.vm import Vm
from firepy.exceptions import err_from_returncode
from firepy.tap import Tap
from firepy.utils.logging_utils import logger
from firepy.utils.network_util... | [
"io.StringIO",
"firepy.exceptions.err_from_returncode",
"firepy.tap.Tap.create",
"firepy.vm.Vm",
"firepy.utils.network_utils.network_tap_name",
"sh.Command",
"pathlib.Path",
"firepy.utils.logging_utils.logger.info",
"re.compile"
] | [((370, 422), 're.compile', 're.compile', (['""".*? \\\\[[\\\\w -:]+\\\\] (.*)"""', 're.MULTILINE'], {}), "('.*? \\\\[[\\\\w -:]+\\\\] (.*)', re.MULTILINE)\n", (380, 422), False, 'import re\n'), ((441, 465), 'sh.Command', 'Command', (['"""./firecracker"""'], {}), "('./firecracker')\n", (448, 465), False, 'from sh impor... |
# %%
import qtt.simulation.virtual_dot_array
import tempfile
from qtt.instrument_drivers.virtual_gates import VirtualGates
from qtt.measurements.storage import save_state, load_state
from unittest import TestCase
# %%
class TestStorage(TestCase):
def test_storage(self, verbose=0):
station = qtt.simulatio... | [
"qtt.measurements.storage.load_state",
"qtt.measurements.storage.save_state",
"qtt.instrument_drivers.virtual_gates.VirtualGates",
"tempfile.mkstemp"
] | [((426, 552), 'qtt.instrument_drivers.virtual_gates.VirtualGates', 'VirtualGates', (['"""virtual_gates_load_save_state"""', 'station.gates', "{'vP1': {'P1': 1, 'P2': 0.1}, 'vP2': {'P1': 0.2, 'P2': 1.0}}"], {}), "('virtual_gates_load_save_state', station.gates, {'vP1': {'P1':\n 1, 'P2': 0.1}, 'vP2': {'P1': 0.2, 'P2':... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import sys, os, time
import threading
try:
import queue
except ImportError:
import Queue as queue
import subprocess
import string
import signal
import datetime
import lib.info as info
from lib.info import bcolors
conf = info.readCon... | [
"threading.Thread.__init__",
"lib.info.readConfig",
"Queue.Queue",
"os.path.dirname",
"time.time",
"lib.info.connect",
"time.sleep",
"subprocess.call",
"lib.info.disconnect",
"signal.signal",
"datetime.datetime.now",
"sys.exit"
] | [((308, 325), 'lib.info.readConfig', 'info.readConfig', ([], {}), '()\n', (323, 325), True, 'import lib.info as info\n'), ((332, 346), 'lib.info.connect', 'info.connect', ([], {}), '()\n', (344, 346), True, 'import lib.info as info\n'), ((360, 371), 'time.time', 'time.time', ([], {}), '()\n', (369, 371), False, 'import... |
# -*- coding: utf-8 -*-
# @Time : 2020/12/12
# @Author : <NAME>
# @GitHub : https://github.com/lartpang
from functools import wraps
import numpy as np
import torch
def reduce_score(score: torch.Tensor, mean_on_loss: bool = True):
if mean_on_loss:
loss = (1 - score).mean()
else:
loss = 1... | [
"numpy.cos",
"functools.wraps"
] | [((835, 846), 'functools.wraps', 'wraps', (['func'], {}), '(func)\n', (840, 846), False, 'from functools import wraps\n'), ((2511, 2547), 'numpy.cos', 'np.cos', (['(curr_iter / num_iter * np.pi)'], {}), '(curr_iter / num_iter * np.pi)\n', (2517, 2547), True, 'import numpy as np\n')] |
import collections
class Solution:
def assignBikes(self, workers: List[List[int]], bikes: List[List[int]]) -> List[int]:
distance = collections.defaultdict(list)
for i, w in enumerate(workers):
for j, b in enumerate(bikes):
distance[abs(w[0] - b[0]) + abs(w[1] - b[1])].ap... | [
"collections.defaultdict"
] | [((144, 173), 'collections.defaultdict', 'collections.defaultdict', (['list'], {}), '(list)\n', (167, 173), False, 'import collections\n')] |
import pygame
class Game():
def __init__(self):
pygame.init()
self.gameDisplay = pygame.display.set_mode((800,600))
pygame.display.set_caption('Minesweeper!')
def run(self):
crashed = False
while not crashed:
for event in pygame.event.get():
... | [
"pygame.event.get",
"pygame.display.set_mode",
"pygame.init",
"pygame.display.flip",
"pygame.display.set_caption"
] | [((61, 74), 'pygame.init', 'pygame.init', ([], {}), '()\n', (72, 74), False, 'import pygame\n'), ((103, 138), 'pygame.display.set_mode', 'pygame.display.set_mode', (['(800, 600)'], {}), '((800, 600))\n', (126, 138), False, 'import pygame\n'), ((146, 188), 'pygame.display.set_caption', 'pygame.display.set_caption', (['"... |
# import unittest
from pandas import DataFrame
from pandas.tools.describe import value_range
import numpy as np
def test_value_range():
df = DataFrame(np.random.randn(5, 5))
df.ix[0, 2] = -5
df.ix[2, 0] = 5
res = value_range(df)
assert(res['Minimum'] == -5)
assert(res['Maximum'] == 5)
... | [
"numpy.random.randn",
"pandas.tools.describe.value_range"
] | [((234, 249), 'pandas.tools.describe.value_range', 'value_range', (['df'], {}), '(df)\n', (245, 249), False, 'from pandas.tools.describe import value_range\n'), ((159, 180), 'numpy.random.randn', 'np.random.randn', (['(5)', '(5)'], {}), '(5, 5)\n', (174, 180), True, 'import numpy as np\n')] |
# sum of elements in given range
import math
arr=list(map(int,input().split()))
m=int(input("query size: "))
query=[]
for i in range(m):
l,r=map(int,input().split())
query.append([l,r])
dic=dict()
n=len(arr)
rootn=math.sqrt(n)
blocksize=n//rootn
blocksize=int(blocksize)
while len(arr)%blocksize!=0:
arr.ap... | [
"math.sqrt"
] | [((224, 236), 'math.sqrt', 'math.sqrt', (['n'], {}), '(n)\n', (233, 236), False, 'import math\n')] |
#!/usr/bin/env python3
import argparse
import re
import logging
from cutecare.poller import CuteCarePoller
from cutecare.backends.gatttool import GatttoolBackend
from cutecare.backends.bluepy import BluepyBackend
def validate_device_mac(mac, pat=re.compile(r"C4:7C:8D:[0-9A-F]{2}:[0-9A-F]{2}:[0-9A-F]{2}")):
if ... | [
"cutecare.poller.CuteCarePoller",
"argparse.ArgumentParser",
"logging.basicConfig",
"re.compile"
] | [((474, 499), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (497, 499), False, 'import argparse\n'), ((1017, 1050), 'cutecare.poller.CuteCarePoller', 'CuteCarePoller', (['args.mac', 'backend'], {}), '(args.mac, backend)\n', (1031, 1050), False, 'from cutecare.poller import CuteCarePoller\n'), ... |
from abc import ABCMeta, abstractmethod
from six import with_metaclass
_alg_registry = {}
class Algorithm(object):
_name = None
@classmethod
def name(cls):
return cls._name
@classmethod
def register(cls):
_alg_registry[cls._name] = cls
@staticmethod
def resolve(name):
... | [
"six.with_metaclass"
] | [((385, 419), 'six.with_metaclass', 'with_metaclass', (['ABCMeta', 'Algorithm'], {}), '(ABCMeta, Algorithm)\n', (399, 419), False, 'from six import with_metaclass\n')] |
# Training to a set of multiple objects (e.g. ShapeNet or DTU)
# tensorboard logs available in logs/<expname>
import imp
import sys
import os
from unittest.mock import patch
sys.path.insert(
0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
)
sys.path.insert(
0, os.path.abspath(os.path.join(os... | [
"torch.empty",
"numpy.random.randint",
"util.get_cuda",
"util.decompose_to_subpatches",
"torch.no_grad",
"util.gen_rays",
"data.get_split_dataset",
"random.randint",
"os.path.dirname",
"render.NeRFRenderer.from_conf",
"os.path.exists",
"torch.load",
"util.args.parse_args",
"model.loss.item... | [((3595, 3670), 'util.args.parse_args', 'util.args.parse_args', (['extra_args'], {'training': '(True)', 'default_ray_batch_size': '(128)'}), '(extra_args, training=True, default_ray_batch_size=128)\n', (3615, 3670), False, 'import util\n'), ((3680, 3709), 'util.get_cuda', 'util.get_cuda', (['args.gpu_id[0]'], {}), '(ar... |
"""
Nox testing for Insights Core
=============================
To use this file install nox:
$ pip install --user --upgrade nox
Then you can run all nox tests:
$ nox
To run selected tests use `nox --list` to show the test names and then you can run
an individual test with:
$ nox -s test-2.7
See the ... | [
"nox.session"
] | [((557, 613), 'nox.session', 'nox.session', ([], {'python': "['2.7', '3.6', '3.8', '3.9', '3.10']"}), "(python=['2.7', '3.6', '3.8', '3.9', '3.10'])\n", (568, 613), False, 'import nox\n'), ((699, 726), 'nox.session', 'nox.session', ([], {'python': "['3.8']"}), "(python=['3.8'])\n", (710, 726), False, 'import nox\n'), (... |
"""The example:
- creates waveform file from two i_data and q_data vectors
- sends the file to the SGT100A instrument
- activates the waveform
You have the option of auto-scaling the samples to the full range with the parameter 'auto_scale'
"""
import numpy as np
from RsSgt import *
RsSgt.assert_minimum_version('... | [
"numpy.sin",
"numpy.arange",
"numpy.cos"
] | [((803, 847), 'numpy.arange', 'np.arange', (['(0)', '(50 / wave_freq)', '(1 / clock_freq)'], {}), '(0, 50 / wave_freq, 1 / clock_freq)\n', (812, 847), True, 'import numpy as np\n'), ((891, 934), 'numpy.cos', 'np.cos', (['(2 * np.pi * wave_freq * time_vector)'], {}), '(2 * np.pi * wave_freq * time_vector)\n', (897, 934)... |
import webapp2
import handler
from loginout import Login, Logout, TokenSignup, TokenWelcome
config = {
'jinja_env' : handler.setup_jinja('assignment-4'),
'url_login_success' : '/assignment-4/welcome',
'url_logout' : '/assignment-4/logout',
'url_logout_redirect' : '/assignment-4/signup'
}
app = we... | [
"handler.setup_jinja",
"webapp2.WSGIApplication"
] | [((318, 525), 'webapp2.WSGIApplication', 'webapp2.WSGIApplication', (["[('/assignment-4/signup', TokenSignup), ('/assignment-4/welcome',\n TokenWelcome), ('/assignment-4/login', Login), ('/assignment-4/logout',\n Logout)]"], {'config': 'config', 'debug': '(True)'}), "([('/assignment-4/signup', TokenSignup), (\n ... |
# Copyright (c) 2020, salesforce.com, inc.
# All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
# For full license text, see the LICENSE file in the repo root
# or https://opensource.org/licenses/BSD-3-Clause
import random
import numpy as np
from ai_economist.foundation.base.registrar import Registry
cla... | [
"numpy.minimum",
"ai_economist.foundation.base.registrar.Registry",
"numpy.ones",
"random.choice",
"numpy.random.randint",
"numpy.array",
"numpy.random.rand",
"numpy.concatenate"
] | [((18196, 18215), 'ai_economist.foundation.base.registrar.Registry', 'Registry', (['BaseAgent'], {}), '(BaseAgent)\n', (18204, 18215), False, 'from ai_economist.foundation.base.registrar import Registry\n'), ((13972, 14005), 'random.choice', 'random.choice', (['self._action_names'], {}), '(self._action_names)\n', (1398... |
import datetime
import random
import serial
import math
L = 18 * math.pow(10, -6)
C = 33 * math.pow(10, -12)
fref = 40000000
# ser = serial.Serial(serialString, 115200, timeout=1)
def calculateCapacitance(freq):
f = (fref * freq) / math.pow(2, 28)
csen = (1 / (L * math.pow(2 * math.pi * f, 2))) - C
ret... | [
"serial.Serial",
"random.random",
"math.pow"
] | [((67, 83), 'math.pow', 'math.pow', (['(10)', '(-6)'], {}), '(10, -6)\n', (75, 83), False, 'import math\n'), ((93, 110), 'math.pow', 'math.pow', (['(10)', '(-12)'], {}), '(10, -12)\n', (101, 110), False, 'import math\n'), ((372, 387), 'serial.Serial', 'serial.Serial', ([], {}), '()\n', (385, 387), False, 'import serial... |
from modeldata import from_downloaded as modeldata_from_downloaded
import log
from utilities import get_ncfiles_in_dir,get_variable_name,get_variable_name_reverse
from utilities import convert_time_to_datetime,get_n_months,get_l_time_range,add_month_to_timestamp
from netCDF4 import Dataset
from datetime import datetime... | [
"netCDF4.Dataset",
"utilities.get_variable_name",
"utilities.get_variable_name_reverse",
"utilities.add_month_to_timestamp",
"utilities.get_ncfiles_in_dir",
"utilities.convert_time_to_datetime",
"utilities.get_l_time_range",
"os.path.exists",
"datetime.datetime",
"modeldata.from_downloaded",
"lo... | [((653, 682), 'utilities.get_ncfiles_in_dir', 'get_ncfiles_in_dir', (['input_dir'], {}), '(input_dir)\n', (671, 682), False, 'from utilities import get_ncfiles_in_dir, get_variable_name, get_variable_name_reverse\n'), ((1438, 1457), 'netCDF4.Dataset', 'Dataset', (['input_path'], {}), '(input_path)\n', (1445, 1457), Fal... |
import math
from pandas import DataFrame
import numpy as np
from __init__fuzzy import *
def experiment(sliding_number=3, hidden_node=15):
dat_nn = np.asarray(scaler.fit_transform(dat))
X_train_size = int(len(dat_nn)*0.7)
sliding = np.array(list(SlidingWindow(dat_nn, sliding_number)))
X_train_nn = sl... | [
"numpy.array",
"numpy.savez",
"numpy.arange"
] | [((948, 1055), 'numpy.savez', 'np.savez', (["('model_saved/BPNN_%s_%s' % (sliding_number, score_mape))"], {'y_pred': 'y_pred', 'y_true': 'y_actual_test'}), "('model_saved/BPNN_%s_%s' % (sliding_number, score_mape), y_pred=\n y_pred, y_true=y_actual_test)\n", (956, 1055), True, 'import numpy as np\n'), ((1176, 1189),... |
# -*- encoding:utf-8 -*-
from __future__ import print_function
import os, codecs, re
import random
import numpy as np
from datetime import datetime
from collections import defaultdict, Counter
from nltk.stem.porter import PorterStemmer
import reader
from utils import AGENT_FIRST_THRESHOLD, AGENT_SECOND_THRES... | [
"numpy.random.seed",
"codecs.open",
"re.split",
"random.sample",
"nltk.stem.porter.PorterStemmer",
"numpy.zeros",
"collections.defaultdict",
"datetime.datetime.strptime",
"numpy.random.random",
"random.seed",
"collections.Counter",
"os.path.join",
"re.sub"
] | [((414, 458), 'os.path.join', 'os.path.join', (['BASE_DIR', '"""chat_sequences.txt"""'], {}), "(BASE_DIR, 'chat_sequences.txt')\n", (426, 458), False, 'import os, codecs, re\n'), ((483, 523), 'os.path.join', 'os.path.join', (['BASE_DIR', '"""utt_length.txt"""'], {}), "(BASE_DIR, 'utt_length.txt')\n", (495, 523), False,... |
# -*- coding: utf-8 -*-
from sqlalchemy import Column, ForeignKey
from sqlalchemy import String, Integer
from sqlalchemy.orm import relationship
from app.model import Base
class DrawStatisticsMenual(Base):
__tablename__ = 'draw_statistics_menual'
holo_twitter_draw_id = Column(Integer, ForeignKey('holo_twit... | [
"sqlalchemy.String",
"sqlalchemy.orm.relationship",
"sqlalchemy.ForeignKey",
"sqlalchemy.Column"
] | [((377, 442), 'sqlalchemy.orm.relationship', 'relationship', (['"""HoloTwitterDraw"""'], {'backref': '"""draw_statistics_menual"""'}), "('HoloTwitterDraw', backref='draw_statistics_menual')\n", (389, 442), False, 'from sqlalchemy.orm import relationship\n'), ((586, 657), 'sqlalchemy.orm.relationship', 'relationship', (... |
#!/usr/bin/env python
"""Write to daily rotating log files.
One message is written per minute so the rotation can be seen.
"""
import time
import logging
from themelog import init_log
logger = logging.getLogger()
init_log(rotating_logfile='test.log')
pause = 60
while True:
logger.info('Sleeping for {pause} seconds'.f... | [
"time.sleep",
"logging.getLogger",
"themelog.init_log"
] | [((194, 213), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (211, 213), False, 'import logging\n'), ((214, 251), 'themelog.init_log', 'init_log', ([], {'rotating_logfile': '"""test.log"""'}), "(rotating_logfile='test.log')\n", (222, 251), False, 'from themelog import init_log\n'), ((341, 358), 'time.sleep... |
import re
from string import punctuation
from nltk.tokenize import casual_tokenize
from nltk.tokenize.casual import URLS
def clean_tweet(tweet):
tweet = re.sub(r"https?://\S+", "", tweet)
# tweet = re.sub(URLS, "", tweet)
toks = casual_tokenize(tweet, preserve_case=False, reduce_len=True, strip_handles=T... | [
"re.sub",
"nltk.tokenize.casual_tokenize"
] | [((160, 194), 're.sub', 're.sub', (['"""https?://\\\\S+"""', '""""""', 'tweet'], {}), "('https?://\\\\S+', '', tweet)\n", (166, 194), False, 'import re\n'), ((244, 329), 'nltk.tokenize.casual_tokenize', 'casual_tokenize', (['tweet'], {'preserve_case': '(False)', 'reduce_len': '(True)', 'strip_handles': '(True)'}), '(tw... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2018-01-31 19:59
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('schools', '0007_schools_subcounty'),
]
operations = [
migrations.AlterField(
... | [
"django.db.models.BigIntegerField"
] | [((402, 450), 'django.db.models.BigIntegerField', 'models.BigIntegerField', ([], {'default': '(199)', 'unique': '(True)'}), '(default=199, unique=True)\n', (424, 450), False, 'from django.db import migrations, models\n')] |
from typing import Optional
from pydantic import BaseModel
import uuid
class CardModel(BaseModel):
is_normal: Optional[bool] = True
number: Optional[int] = -1
color: Optional[str] = ""
is_draw_2: Optional[bool] = False
is_draw_4: Optional[bool] = False
is_wild: Optional[bool] = False
is_s... | [
"uuid.uuid4"
] | [((473, 485), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (483, 485), False, 'import uuid\n')] |
"""Network transactions are considered open as long as the confirmation threshold has not been reached.
Because backends do not actively report the progress of confirmation status, we poll the backend for all network transactions (deposits, broadcasts) until the confirmation threshold has been reached. For example, *b... | [
"logging.getLogger"
] | [((1146, 1173), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1163, 1173), False, 'import logging\n')] |
from sys import exit
from typing import List
from eisp.param._param import _param
from eisp.utils import concretemethod
class help(_param):
'''
todo: docs
'''
@concretemethod
def _parse(self, params: List[str]) -> None:
'''
todo: docs
'''
exit('Work in progress')
| [
"sys.exit"
] | [((269, 293), 'sys.exit', 'exit', (['"""Work in progress"""'], {}), "('Work in progress')\n", (273, 293), False, 'from sys import exit\n')] |
from obscurepy.handlers import *
import importlib
import inspect
import os
import sys
import yaml
def load_handlers(log, verbose):
"""Dynamically loads handler classes
Returns:
The first handler in the chain of handlers
"""
handlers = create_handlers(log, verbose)
return connect_handlers... | [
"yaml.load",
"os.getcwd",
"inspect.isclass",
"os.listdir",
"inspect.getmembers"
] | [((1940, 1981), 'inspect.getmembers', 'inspect.getmembers', (['sys.modules[__name__]'], {}), '(sys.modules[__name__])\n', (1958, 1981), False, 'import inspect\n'), ((1994, 2014), 'inspect.isclass', 'inspect.isclass', (['obj'], {}), '(obj)\n', (2009, 2014), False, 'import inspect\n'), ((630, 641), 'os.getcwd', 'os.getcw... |
from __future__ import absolute_import, division, print_function
import os
def run():
import libtbx.load_env
src_dir = libtbx.env.under_dist(
module_name="scitbx", path="lbfgs", test=os.path.isdir)
import fable.read
all_fprocs = fable.read.process(
file_names=[os.path.join(src_dir, f) for f in ["sdriv... | [
"os.path.isdir",
"os.path.join",
"os.makedirs"
] | [((1433, 1454), 'os.path.isdir', 'os.path.isdir', (['result'], {}), '(result)\n', (1446, 1454), False, 'import os\n'), ((1463, 1482), 'os.makedirs', 'os.makedirs', (['result'], {}), '(result)\n', (1474, 1482), False, 'import os\n'), ((1496, 1517), 'os.path.isdir', 'os.path.isdir', (['result'], {}), '(result)\n', (1509,... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from ceasiompy.utils.moduleinterfaces import CPACSInOut, CEASIOM_XPATH
# ===== RCE integration =====
RCE = {
"name": "CPACS2SUMO",
"description": "Convert CPACS .xml file into SUMO .smx file",
"exec": "pwd\npython cpacs2sumo.py",
"author": "<NAME>",
... | [
"ceasiompy.utils.moduleinterfaces.CPACSInOut"
] | [((398, 410), 'ceasiompy.utils.moduleinterfaces.CPACSInOut', 'CPACSInOut', ([], {}), '()\n', (408, 410), False, 'from ceasiompy.utils.moduleinterfaces import CPACSInOut, CEASIOM_XPATH\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# adaptado de https://wiki.python.org/moin/TcpCommunication
import sys
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 5005
BUFFER_SIZE = 20
MESSAGE = "<NAME>!"
if len(sys.argv) >= 2:
TCP_IP = sys.argv[1]
if len(sys.argv) >= 3:
MESSAGE = sys.argv[2]
print ("[CLI... | [
"socket.socket"
] | [((343, 392), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (356, 392), False, 'import socket\n')] |
#!/usr/bin/python
# Copyright (C) 2010-2012 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | [
"random.shuffle",
"random.choice",
"json.dumps"
] | [((1293, 1323), 'random.shuffle', 'random.shuffle', (['square_indices'], {}), '(square_indices)\n', (1307, 1323), False, 'import random\n'), ((1565, 1590), 'random.choice', 'random.choice', (['HEX_DIGITS'], {}), '(HEX_DIGITS)\n', (1578, 1590), False, 'import random\n'), ((2116, 2138), 'json.dumps', 'json.dumps', (['col... |
"""
Script to get all the tiles from available scenes, aoi and date range for Planetscope or Skysat
Author: @developmentseed
Run:
python3 get_planet_tiles.py --geojson=supersites.geojson \
--api_key=xxxxx \
--collections=PSScene3Band \
--start_date=2020,1,1 \
--end_... | [
"json.load",
"argparse.ArgumentParser",
"numpy.asarray",
"planet.api.filters.geom_filter",
"planet.api.filters.date_range",
"planet.api.filters.range_filter",
"requests.auth.HTTPBasicAuth",
"planet.api.filters.build_search_request",
"mercantile.tile",
"planet.api.ClientV1"
] | [((666, 680), 'planet.api.ClientV1', 'api.ClientV1', ([], {}), '()\n', (678, 680), False, 'from planet import api\n'), ((2330, 2381), 'planet.api.filters.build_search_request', 'api.filters.build_search_request', (['query', 'item_types'], {}), '(query, item_types)\n', (2362, 2381), False, 'from planet import api\n'), (... |
# Generated by Django 3.1.3 on 2020-11-29 08:43
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='account',
name='is_admin',
... | [
"django.db.migrations.RemoveField",
"django.db.migrations.AlterModelTable",
"django.db.models.CharField",
"django.db.models.EmailField"
] | [((225, 286), 'django.db.migrations.RemoveField', 'migrations.RemoveField', ([], {'model_name': '"""account"""', 'name': '"""is_admin"""'}), "(model_name='account', name='is_admin')\n", (247, 286), False, 'from django.db import migrations, models\n'), ((1272, 1333), 'django.db.migrations.AlterModelTable', 'migrations.A... |
"""
Copyright 2016 adpoliak
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 writing,... | [
"os.listdir",
"os.open",
"os.path.abspath",
"os.path.basename",
"os.getcwd",
"curses.noecho",
"os.path.isdir",
"os.dup",
"curses.wrapper",
"curses.color_pair",
"curses.nl",
"os.close",
"os.path.join",
"curses.init_pair"
] | [((3560, 3571), 'curses.nl', 'curses.nl', ([], {}), '()\n', (3569, 3571), False, 'import curses\n'), ((3576, 3591), 'curses.noecho', 'curses.noecho', ([], {}), '()\n', (3589, 3591), False, 'import curses\n'), ((6436, 6445), 'os.dup', 'os.dup', (['(0)'], {}), '(0)\n', (6442, 6445), False, 'import os\n'), ((6465, 6474), ... |
import numpy as np
# transfer functions
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# derivative of sigmoid
def dsigmoid(y):
return np.multiply(y, (1.0 - y))
def tanh(x):
return np.tanh(x)
# derivative for tanh sigmoid
def dtanh(y):
return 1 - np.multiply(y, y)
| [
"numpy.exp",
"numpy.multiply",
"numpy.tanh"
] | [((144, 167), 'numpy.multiply', 'np.multiply', (['y', '(1.0 - y)'], {}), '(y, 1.0 - y)\n', (155, 167), True, 'import numpy as np\n'), ((196, 206), 'numpy.tanh', 'np.tanh', (['x'], {}), '(x)\n', (203, 206), True, 'import numpy as np\n'), ((268, 285), 'numpy.multiply', 'np.multiply', (['y', 'y'], {}), '(y, y)\n', (279, 2... |
#!/usr/local/bin/python3
# solver2021.py : 2021 Sliding tile puzzle solver
#
# Code by: <NAME> (hatha), <NAME> (aagond)
#
# Based on skeleton code by D. Crandall & B551 Staff, September 2021
#
#References used are as follows:
#1. https://www.quora.com/How-do-I-create-a-nested-list-from-a-flat-one-in-Python to creat... | [
"queue.PriorityQueue",
"copy.deepcopy",
"numpy.array"
] | [((2976, 2996), 'copy.deepcopy', 'copy.deepcopy', (['board'], {}), '(board)\n', (2989, 2996), False, 'import copy\n'), ((3220, 3240), 'copy.deepcopy', 'copy.deepcopy', (['board'], {}), '(board)\n', (3233, 3240), False, 'import copy\n'), ((3738, 3758), 'copy.deepcopy', 'copy.deepcopy', (['board'], {}), '(board)\n', (375... |
import asyncio
import pytest
from rampante.worker import worker
@pytest.mark.asyncio
async def test_worker():
queue = asyncio.PriorityQueue(maxsize=10)
check = None
async def add_2_numbers(topic, data, app):
nonlocal check
check = "TaskDone"
await asyncio.sleep(2)
return... | [
"rampante.worker.worker",
"asyncio.PriorityQueue",
"asyncio.sleep"
] | [((126, 159), 'asyncio.PriorityQueue', 'asyncio.PriorityQueue', ([], {'maxsize': '(10)'}), '(maxsize=10)\n', (147, 159), False, 'import asyncio\n'), ((368, 381), 'rampante.worker.worker', 'worker', (['queue'], {}), '(queue)\n', (374, 381), False, 'from rampante.worker import worker\n'), ((289, 305), 'asyncio.sleep', 'a... |
"""Interpolation numba functions."""
from numba import guvectorize
from numba.core.types import float64, int16, int32, uint8
from ._helper import lazycompile
from .ws2d import ws2d
@lazycompile(
guvectorize(
[(int16[:], float64[:], int32[:], uint8[:], int16[:])],
"(n),(m),(m),(l) -> (l)",
... | [
"numba.guvectorize"
] | [((202, 314), 'numba.guvectorize', 'guvectorize', (['[(int16[:], float64[:], int32[:], uint8[:], int16[:])]', '"""(n),(m),(m),(l) -> (l)"""'], {'nopython': '(True)'}), "([(int16[:], float64[:], int32[:], uint8[:], int16[:])],\n '(n),(m),(m),(l) -> (l)', nopython=True)\n", (213, 314), False, 'from numba import guvect... |
#
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# These materials are licensed under the Amazon Software License in connection with the Alexa Gadgets Program.
# The Agreement is available at https://aws.amazon.com/asl/.
# See the Agreement for the specific terms and conditions of the Agreem... | [
"subprocess.run",
"agt.base_adapter.BaseAdapter.__init__",
"gi.repository.GObject.MainLoop",
"dbus.UInt32",
"uuid.uuid4",
"dbus.service.Object.__init__",
"bluetooth.BluetoothSocket",
"threading.Condition",
"select.select",
"dbus.SystemBus",
"dbus.Interface",
"dbus.mainloop.glib.DBusGMainLoop",... | [((1423, 1510), 'subprocess.run', 'subprocess.run', (["(['/usr/bin/sudo', '/bin/hciconfig'] + args)"], {'stdout': 'subprocess.PIPE'}), "(['/usr/bin/sudo', '/bin/hciconfig'] + args, stdout=\n subprocess.PIPE)\n", (1437, 1510), False, 'import subprocess\n'), ((1539, 1628), 'subprocess.run', 'subprocess.run', (["(['/us... |
import os
import FnAssetAPI
import hiero.core
__all__ = [
'restoreAssetAPISessionSettings',
'saveManagerSessionSettings',
'saveAssetAPISettings'
]
def restoreAssetAPISessionSettings(session):
# See if we have anything stored in the application prefs
appSettings = hiero.core.ApplicationSettings()
if '... | [
"FnAssetAPI.logging.info",
"FnAssetAPI.logging.debug",
"FnAssetAPI.logging.error"
] | [((1891, 1967), 'FnAssetAPI.logging.info', 'FnAssetAPI.logging.info', (["('Setting default Asset Manager to: %s' % identifier)"], {}), "('Setting default Asset Manager to: %s' % identifier)\n", (1914, 1967), False, 'import FnAssetAPI\n'), ((2199, 2316), 'FnAssetAPI.logging.info', 'FnAssetAPI.logging.info', (['("Setting... |
def merge_sort(array):
"""
>>> from random import shuffle
>>> array = [-2, 3, -10, 11, 99, 100000, 100, -200]
>>> shuffle(array)
>>> merge_sort(array)
[-200, -10, -2, 3, 11, 99, 100, 100000]
>>> shuffle(array)
>>> merge_sort(array)
[-200, -10, -2, 3, 11, 99, 100, 100000]
>>> shuf... | [
"doctest.testmod"
] | [((1927, 1944), 'doctest.testmod', 'doctest.testmod', ([], {}), '()\n', (1942, 1944), False, 'import doctest\n')] |
from pathlib import Path
import pytest
from ploomber.env.env import _get_name, Env
def test_path_returns_Path_objects(cleanup_env):
env = Env.start({'path': {'a': '/tmp/path/file.txt',
'b': '/another/path/file.csv'}})
assert isinstance(env.path.a, Path)
assert isinstance(env... | [
"ploomber.env.env.Env.start",
"pytest.raises",
"ploomber.env.env._get_name"
] | [((145, 224), 'ploomber.env.env.Env.start', 'Env.start', (["{'path': {'a': '/tmp/path/file.txt', 'b': '/another/path/file.csv'}}"], {}), "({'path': {'a': '/tmp/path/file.txt', 'b': '/another/path/file.csv'}})\n", (154, 224), False, 'from ploomber.env.env import _get_name, Env\n'), ((391, 430), 'ploomber.env.env.Env.sta... |
from collections import namedtuple
from datetime import datetime as dt, timedelta
import unittest
from random import randint
from bot.cogs.gsuite import GSuite
from bot.constants import Color
class DiscordGuildStub:
def __init__(self, roles_members_map):
self.roles_membeers_map = roles_members... | [
"unittest.main",
"random.randint",
"datetime.datetime.now",
"datetime.datetime",
"datetime.timedelta",
"collections.namedtuple",
"bot.cogs.gsuite.GSuite"
] | [((732, 790), 'collections.namedtuple', 'namedtuple', (['"""DiscordAuthorMock"""', '"""display_name avatar_url"""'], {}), "('DiscordAuthorMock', 'display_name avatar_url')\n", (742, 790), False, 'from collections import namedtuple\n'), ((11473, 11488), 'unittest.main', 'unittest.main', ([], {}), '()\n', (11486, 11488),... |
from dataclasses import dataclass
from meru.serialization import decode_object, encode_object
from meru.types import MeruObject
@dataclass
class MeruObjectToTest(MeruObject):
field: str
encoded_object = b'{"field": "value", "object_type": "MeruObjectToTest"}'
def test_encode_custom_object():
obj = MeruOb... | [
"meru.serialization.decode_object",
"meru.serialization.encode_object"
] | [((350, 368), 'meru.serialization.encode_object', 'encode_object', (['obj'], {}), '(obj)\n', (363, 368), False, 'from meru.serialization import decode_object, encode_object\n'), ((458, 487), 'meru.serialization.decode_object', 'decode_object', (['encoded_object'], {}), '(encoded_object)\n', (471, 487), False, 'from mer... |
#!/usr/bin/env python3
from dqn.snake_world import Environment, Actions
from dqn.agent import DQNAgent
def train_snake():
# todo: put all these parameters using a configuration file
numberOfCells = 10 # in each axis
startingPosition = (4, 5) # head
foodPosition = (3, 6)
max_steps_allowed = 1000
... | [
"dqn.snake_world.Environment",
"dqn.agent.DQNAgent"
] | [((330, 356), 'dqn.snake_world.Environment', 'Environment', (['numberOfCells'], {}), '(numberOfCells)\n', (341, 356), False, 'from dqn.snake_world import Environment, Actions\n'), ((476, 592), 'dqn.agent.DQNAgent', 'DQNAgent', ([], {'state_size': 'state_size', 'action_size': 'action_size', 'batch_size': '(32)', 'memory... |
import getopt
import sys
# Store input and output file names
infile = ''
outfile = ''
searchExp = ''
replaceExp = ''
# Read command line args
myopts, args = getopt.getopt(sys.argv[1:], "i:o:s:r:")
###############################
# o == option
# a == argument passed to the o
###############################
for o, a i... | [
"getopt.getopt"
] | [((159, 198), 'getopt.getopt', 'getopt.getopt', (['sys.argv[1:]', '"""i:o:s:r:"""'], {}), "(sys.argv[1:], 'i:o:s:r:')\n", (172, 198), False, 'import getopt\n')] |
import maya.cmds as cmds
import maya.mel as mel
def createTechPasses():
'''
Creates tech passes for rendering
zdepth, xyz, normals, gi, spec, reflection, lighting, uv, top/down
TODO : topdown not working well due to strange creation methods
'''
# first we make the sampler node as we will use... | [
"maya.cmds.shadingNode",
"maya.cmds.rename",
"maya.mel.eval",
"maya.cmds.listConnections",
"maya.cmds.connectAttr",
"maya.cmds.ls",
"maya.cmds.objExists",
"maya.cmds.setAttr"
] | [((5105, 5137), 'maya.cmds.ls', 'cmds.ls', ([], {'mat': '(True)', 'showType': '(True)'}), '(mat=True, showType=True)\n', (5112, 5137), True, 'import maya.cmds as cmds\n'), ((385, 416), 'maya.cmds.objExists', 'cmds.objExists', (['samplerNodeName'], {}), '(samplerNodeName)\n', (399, 416), True, 'import maya.cmds as cmds\... |
import json
import os
import shutil
import warnings
from glob import glob
from pybdv.metadata import get_data_path, get_bdv_format
from ..xml_utils import copy_xml_with_newpath
def _load_datasets(path):
try:
with open(path) as f:
datasets = json.load(f)
except (FileNotFoundError, ValueErr... | [
"json.dump",
"json.load",
"os.makedirs",
"os.unlink",
"pybdv.metadata.get_data_path",
"os.path.realpath",
"os.path.exists",
"os.path.islink",
"os.path.relpath",
"os.path.splitext",
"shutil.copyfile",
"warnings.warn",
"os.symlink",
"os.path.split",
"os.path.join",
"os.listdir",
"pybdv... | [((452, 487), 'os.path.join', 'os.path.join', (['root', '"""datasets.json"""'], {}), "(root, 'datasets.json')\n", (464, 487), False, 'import os\n'), ((634, 669), 'os.path.join', 'os.path.join', (['root', '"""datasets.json"""'], {}), "(root, 'datasets.json')\n", (646, 669), False, 'import os\n'), ((1154, 1189), 'os.path... |
#!/usr/bin/env python3
import LinearResponseVariationalBayes as vb
import LinearResponseVariationalBayes.SparseObjectives as obj_lib
import LinearResponseVariationalBayes.OptimizationUtils as opt_lib
import autograd.numpy as np
import numpy.testing as np_test
import unittest
class QuadraticModel(object):
def __in... | [
"unittest.main",
"LinearResponseVariationalBayes.OptimizationUtils.minimize_objective_trust_ncg",
"LinearResponseVariationalBayes.OptimizationUtils.get_sym_matrix_inv_sqrt",
"LinearResponseVariationalBayes.OptimizationUtils.repeatedly_optimize",
"LinearResponseVariationalBayes.SparseObjectives.Objective",
... | [((5354, 5369), 'unittest.main', 'unittest.main', ([], {}), '()\n', (5367, 5369), False, 'import unittest\n'), ((381, 414), 'LinearResponseVariationalBayes.VectorParam', 'vb.VectorParam', (['"""theta"""'], {'size': 'dim'}), "('theta', size=dim)\n", (395, 414), True, 'import LinearResponseVariationalBayes as vb\n'), ((4... |
import os
import requests
with open('raw.csv') as f:
lis=[line.split(',') for line in f]
for i, person in enumerate(lis):
person[0] = person[0].replace(' ', '_')
person[1] = person[1].strip('\n')
print("Will create dir {0}, and store image from {1}".format(person[0], person[1]))
... | [
"os.path.exists",
"os.makedirs",
"requests.get"
] | [((329, 363), 'os.path.exists', 'os.path.exists', (["('raw/' + person[0])"], {}), "('raw/' + person[0])\n", (343, 363), False, 'import os\n'), ((375, 406), 'os.makedirs', 'os.makedirs', (["('raw/' + person[0])"], {}), "('raw/' + person[0])\n", (386, 406), False, 'import os\n'), ((523, 559), 'requests.get', 'requests.ge... |
from MyAIGuide.data import GoogleFitDataTCX, DATA_DIR, get_google_fit_steps, collect_activities_from_dir, get_google_fit_activities
import pandas as pd
import numpy as np
TEST_PARTICIPANT = DATA_DIR / 'Participant2Anonymized'
TCX_FILE = "2018-11-05T16_46_19-05_00_PT17M6S_Marche à pied.tcx"
TCX_DIR = DATA_DIR / "Parti... | [
"pandas.DataFrame",
"MyAIGuide.data.GoogleFitDataTCX",
"pandas.date_range",
"numpy.zeros",
"MyAIGuide.data.get_google_fit_steps",
"MyAIGuide.data.collect_activities_from_dir",
"MyAIGuide.data.get_google_fit_activities"
] | [((412, 464), 'pandas.date_range', 'pd.date_range', (['"""2015-11-19"""'], {'periods': '(1550)', 'freq': '"""1D"""'}), "('2015-11-19', periods=1550, freq='1D')\n", (425, 464), True, 'import pandas as pd\n'), ((904, 933), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'd', 'index': 'i'}), '(data=d, index=i)\n', (916,... |
import unittest
import qt
import slicer
import EditorLib
from EditorLib.EditUtil import EditUtil
class ThresholdThreading(unittest.TestCase):
def setUp(self):
pass
def delayDisplay(self,message,msec=1000):
"""This utility method displays a small dialog and waits.
This does two things: 1) it lets the ... | [
"EditorLib.PaintEffectOptions",
"slicer.mrmlScene.AddNode",
"slicer.vtkMRMLCropVolumeParametersNode",
"slicer.app.layoutManager",
"qt.QDialog",
"qt.QVBoxLayout",
"slicer.util.selectModule",
"EditorLib.EditUtil.EditUtil.setLabel",
"slicer.app.applicationLogic",
"EditorLib.PaintEffectTool",
"slice... | [((607, 619), 'qt.QDialog', 'qt.QDialog', ([], {}), '()\n', (617, 619), False, 'import qt\n'), ((642, 658), 'qt.QVBoxLayout', 'qt.QVBoxLayout', ([], {}), '()\n', (656, 658), False, 'import qt\n'), ((717, 746), 'qt.QLabel', 'qt.QLabel', (['message', 'self.info'], {}), '(message, self.info)\n', (726, 746), False, 'import... |
#!/usr/bin/env python3
import numpy as np
from functools import partial
class TailBoost:
def __init__(self, urm):
self.weights = list()
self.urm = urm
self.__create_weights()
self.update_scores = partial(np.vectorize(lambda weight, score: score * weight), self.weights)
def _... | [
"numpy.array",
"numpy.log",
"numpy.vectorize"
] | [((726, 748), 'numpy.array', 'np.array', (['self.weights'], {}), '(self.weights)\n', (734, 748), True, 'import numpy as np\n'), ((244, 294), 'numpy.vectorize', 'np.vectorize', (['(lambda weight, score: score * weight)'], {}), '(lambda weight, score: score * weight)\n', (256, 294), True, 'import numpy as np\n'), ((678, ... |
#
# This file is subject to the terms and conditions defined in the
# file 'LICENSE', which is part of this source code package.
#
# import json
import logging
from datetime import datetime
import rdr_service.config as config
from rdr_service.dao.bigquery_sync_dao import BigQuerySyncDao
from rdr_service.dao.bq_partic... | [
"rdr_service.cloud_utils.gcp_cloud_tasks.GCPCloudTask",
"rdr_service.resource.generators.participant.rebuild_participant_summary_resource",
"rdr_service.dao.bigquery_sync_dao.BigQuerySyncDao",
"rdr_service.resource.generators.RetentionEligibleMetricGenerator",
"rdr_service.resource.generators.ParticipantSum... | [((1353, 1393), 'rdr_service.resource.generators.ParticipantSummaryGenerator', 'generators.ParticipantSummaryGenerator', ([], {}), '()\n', (1391, 1393), False, 'from rdr_service.resource import generators\n'), ((1410, 1441), 'rdr_service.dao.bq_participant_summary_dao.BQParticipantSummaryGenerator', 'BQParticipantSumma... |
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, scale
from sklearn.metrics import auc, roc_auc_score, mean_absolute_percentage_error
from sklearn.base import BaseEstimator, TransformerMixin, is_outlier_detector
x_train = 1
y_train = 1
train_test_split(x_train, y_... | [
"sklearn.model_selection.train_test_split",
"sklearn.preprocessing.StandardScaler"
] | [((292, 357), 'sklearn.model_selection.train_test_split', 'train_test_split', (['x_train', 'y_train'], {'test_size': '(0.2)', 'random_state': '(0)'}), '(x_train, y_train, test_size=0.2, random_state=0)\n', (308, 357), False, 'from sklearn.model_selection import train_test_split\n'), ((368, 384), 'sklearn.preprocessing.... |
import numpy as np
import matplotlib.pyplot as plt
from signals.fourier import fourier
from signals.analysis import ClimbingAgent
def test_fourier():
fs = 100
length = 100.0
n = fs * length
x = np.linspace(0., length, n)
y = np.sin(10. * 2. * np.pi * x)
y += 0.75 * np.sin(20. * 2. * np.pi * ... | [
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"signals.analysis.ClimbingAgent",
"numpy.sin",
"signals.fourier.fourier",
"numpy.linspace"
] | [((214, 241), 'numpy.linspace', 'np.linspace', (['(0.0)', 'length', 'n'], {}), '(0.0, length, n)\n', (225, 241), True, 'import numpy as np\n'), ((249, 279), 'numpy.sin', 'np.sin', (['(10.0 * 2.0 * np.pi * x)'], {}), '(10.0 * 2.0 * np.pi * x)\n', (255, 279), True, 'import numpy as np\n'), ((425, 439), 'signals.fourier.f... |
# %%
import numpy as np
from mpl_toolkits.axes_grid.parasite_axes import SubplotHost
import matplotlib.ticker as ticker
import matplotlib.pyplot as plt
import csv
import os
import pandas as pd
# read into dataframes with headers
import_path = os.getcwd() + '\\ana1\\analysis.csv'
model_data = pd.read_csv(import_path, h... | [
"pandas.DataFrame",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"pandas.read_csv",
"os.getcwd",
"matplotlib.animation.FuncAnimation",
"matplotlib.pyplot.rc",
"pandas.DataFrame.from_records",
"glob.glob",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.savefig"
] | [((294, 345), 'pandas.read_csv', 'pd.read_csv', (['import_path'], {'header': 'None', 'skiprows': '[0]'}), '(import_path, header=None, skiprows=[0])\n', (305, 345), True, 'import pandas as pd\n'), ((390, 444), 'pandas.DataFrame', 'pd.DataFrame', (['model_data.T.values[1:]'], {'columns': 'headers'}), '(model_data.T.value... |
'''An example file that imports some of the installed modules.
Run with: `poetry run python testenv.py`
'''
import platform
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
if __name__ == "__main__":
# If the modules can't be imported, the following print won't happen
print("Successfully... | [
"platform.python_version"
] | [((361, 386), 'platform.python_version', 'platform.python_version', ([], {}), '()\n', (384, 386), False, 'import platform\n')] |
import glob
import os
import re
import subprocess
from conans import CMake, ConanFile, model, tools
class POCO(ConanFile):
name = "POCO"
version = "1.9.0"
license = "The Boost Software License 1.0, https://pocoproject.org/license.html"
url = "https://pocoproject.org"
settings = {"os": ["Windows", "Linux"], "com... | [
"os.remove",
"glob.glob",
"os.path.join",
"conans.tools.untargz",
"os.path.dirname",
"conans.CMake",
"conans.tools.unzip",
"conans.tools.sha256sum",
"os.path.basename",
"os.rename",
"re.match",
"conans.tools.download",
"conans.tools.chdir",
"os.rmdir",
"os.listdir",
"re.compile",
"os... | [((2661, 2682), 'os.path.basename', 'os.path.basename', (['url'], {}), '(url)\n', (2677, 2682), False, 'import os\n'), ((2732, 2785), 'conans.tools.download', 'tools.download', (['url', 'filename'], {'retry': '(3)', 'retry_wait': '(10)'}), '(url, filename, retry=3, retry_wait=10)\n', (2746, 2785), False, 'from conans i... |
import numpy as np
'''
Label any new implementation of von-Zeipel cylinders in another spacetime
by prefixing VZC, followed by the id of the spacetime.
'''
class VZCBase():
def __init__(self, l, r0, r_range=(2, 18),
num=10000, verbose=True):
self.r_in, self.r_out = r_range
self.nu... | [
"numpy.linspace"
] | [((345, 408), 'numpy.linspace', 'np.linspace', (['self.r_in', 'self.r_out'], {'num': 'self.num', 'endpoint': '(True)'}), '(self.r_in, self.r_out, num=self.num, endpoint=True)\n', (356, 408), True, 'import numpy as np\n')] |
# python3.7
# encoding: utf-8
"""
@author: Chenjin.Qian
@email: <EMAIL>
@file: operate.py
@time: 2020-06-30 16:29
"""
class DatabaseOperate(object):
def __init__(self, current_conn):
self.conn = current_conn
self.cursor = self.conn.create_cursor()
def check_connection(self):
fla... | [
"pandas.DataFrame"
] | [((1347, 1383), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {'columns': 'col_name'}), '(data, columns=col_name)\n', (1359, 1383), True, 'import pandas as pd\n')] |
import uuid
from crownstone_core.packets.behaviour.BehaviourTypes import BehaviourType
from crownstone_core.packets.behaviour.SwitchBehaviour import SwitchBehaviour
from crownstone_core.packets.behaviour.TwilightBehaviour import TwilightBehaviour
from crownstone_core.packets.behaviour.ExtendedSwitchBehaviour import Ex... | [
"uuid.uuid4",
"crownstone_core.packets.behaviour.ExtendedSwitchBehaviour.ExtendedSwitchBehaviour",
"crownstone_core.packets.behaviour.BehaviourTypes.BehaviourType",
"crownstone_core.packets.behaviour.SwitchBehaviour.SwitchBehaviour",
"crownstone_core.packets.behaviour.TwilightBehaviour.TwilightBehaviour"
] | [((726, 738), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (736, 738), False, 'import uuid\n'), ((938, 954), 'crownstone_core.packets.behaviour.BehaviourTypes.BehaviourType', 'BehaviourType', (['(0)'], {}), '(0)\n', (951, 954), False, 'from crownstone_core.packets.behaviour.BehaviourTypes import BehaviourType\n'), ((1... |
# Created By: <NAME>
# Created On: 2010-02-11
# Copyright 2013 Hardcoded Software (http://www.hardcoded.net)
#
# This software is licensed under the "BSD" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.hardcoded.net/licenses/bsd_... | [
"hscommon.gui.table.GUITable.__init__",
"operator.attrgetter",
"hscommon.gui.table.Row.__init__",
"hscommon.gui.column.Columns"
] | [((557, 582), 'hscommon.gui.table.Row.__init__', 'Row.__init__', (['self', 'table'], {}), '(self, table)\n', (569, 582), False, 'from hscommon.gui.table import GUITable, Row\n'), ((2641, 2664), 'hscommon.gui.table.GUITable.__init__', 'GUITable.__init__', (['self'], {}), '(self)\n', (2658, 2664), False, 'from hscommon.g... |
from django.contrib import admin
from Player.models import Player
admin.site.register(Player) | [
"django.contrib.admin.site.register"
] | [((67, 94), 'django.contrib.admin.site.register', 'admin.site.register', (['Player'], {}), '(Player)\n', (86, 94), False, 'from django.contrib import admin\n')] |
# Copyright (c) 2016-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | [
"unittest.main",
"caffe2.python.core.CreateOperator",
"hypothesis.strategies.text",
"numpy.array"
] | [((4080, 4095), 'unittest.main', 'unittest.main', ([], {}), '()\n', (4093, 4095), False, 'import unittest\n'), ((1833, 1910), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""StringPrefix"""', "['strings']", "['stripped']"], {'length': 'length'}), "('StringPrefix', ['strings'], ['stripped'], length=len... |
import logging
from typing import Any, Dict, List, Optional, Union
from eth_typing.evm import ChecksumAddress
from hexbytes.main import HexBytes
from moonstreamdb.db import yield_db_session_ctx
from moonstreamdb.models import (
Base,
EthereumLabel,
EthereumTransaction,
PolygonLabel,
PolygonTransact... | [
"moonworm.cu_watch.MockState",
"moonworm.crawler.moonstream_ethereum_state_provider.MoonstreamEthereumStateProvider",
"logging.getLogger",
"logging.basicConfig"
] | [((965, 1004), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (984, 1004), False, 'import logging\n'), ((1014, 1041), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1031, 1041), False, 'import logging\n'), ((1305, 1316), 'moonworm... |
# -*- coding: utf-8 -*-
"""
Copyright () 2018
All rights reserved
FILE: DBSCAN.py
AUTHOR: tianyuningmou
DATE CREATED: @Time : 2018/3/6 上午10:47
DESCRIPTION: .
VERSION: : #1
CHANGED By: : tianyuningmou
CHANGE: :
MODIFIED: : @Time : 2018/3/6 上午10:47
"""
"""
密度聚类的思想:通过计算样本点的密度大小来实现一个簇/类别的形成,样本点密度越大,越容易形成一个类,... | [
"matplotlib.pyplot.title",
"sklearn.datasets.samples_generator.make_moons",
"matplotlib.pyplot.show",
"matplotlib.pyplot.scatter",
"sklearn.cluster.KMeans",
"time.time",
"sklearn.datasets.samples_generator.make_circles",
"sklearn.cluster.DBSCAN"
] | [((1347, 1385), 'sklearn.datasets.samples_generator.make_moons', 'make_moons', ([], {'n_samples': '(1000)', 'noise': '(0.15)'}), '(n_samples=1000, noise=0.15)\n', (1357, 1385), False, 'from sklearn.datasets.samples_generator import make_moons\n'), ((1386, 1425), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x[:, 0]', ... |
from unittest.mock import patch
import logging
import pytest
from tests import (
test_mod,
test_game,
test_engine,
test_file,
test_addon,
test_media,
test_article,
test_group,
test_team,
test_job,
test_member,
test_platform,
test_software,
test_hardware,
test... | [
"logging.FileHandler",
"moddb.get_page",
"pytest.fixture",
"moddb.search",
"unittest.mock.patch",
"logging.Formatter",
"logging.getLogger"
] | [((401, 427), 'logging.getLogger', 'logging.getLogger', (['"""moddb"""'], {}), "('moddb')\n", (418, 427), False, 'import logging\n'), ((469, 538), 'logging.FileHandler', 'logging.FileHandler', ([], {'filename': '"""moddb.log"""', 'encoding': '"""utf-8"""', 'mode': '"""w"""'}), "(filename='moddb.log', encoding='utf-8', ... |
#loading libraries
import sys, os, optparse, time,logging
import numpy as np
import pylab as pl
from ConfigParser import SafeConfigParser
#loading classes
sys.path.append('./classes')
sys.path.append('./library')
import parameters,emission,transmission,output,fitting,atmosphere,data,preselector
from parameters import... | [
"sys.path.append",
"emission",
"optparse.OptionParser",
"output",
"logging.warning",
"os.path.isdir",
"data",
"fitting",
"cluster.cluster",
"parameters",
"os.path.join",
"atmosphere",
"transmission"
] | [((156, 184), 'sys.path.append', 'sys.path.append', (['"""./classes"""'], {}), "('./classes')\n", (171, 184), False, 'import sys, os, optparse, time, logging\n'), ((185, 213), 'sys.path.append', 'sys.path.append', (['"""./library"""'], {}), "('./library')\n", (200, 213), False, 'import sys, os, optparse, time, logging\... |
"""
2019.11.28新增
添加车次窗口。
并改为用TabWidget实现。
"""
from PyQt5 import QtWidgets,QtGui,QtCore
from PyQt5.QtCore import Qt
from .AddRealTrain import AddRealTrain
from .AddVirtualTrain import AddVirtualTrain
from ..data import *
class AddTrainWidget(QtWidgets.QTabWidget):
Applied = QtCore.pyqtSignal(CircuitNode)
Cancel... | [
"PyQt5.QtCore.pyqtSignal"
] | [((279, 309), 'PyQt5.QtCore.pyqtSignal', 'QtCore.pyqtSignal', (['CircuitNode'], {}), '(CircuitNode)\n', (296, 309), False, 'from PyQt5 import QtWidgets, QtGui, QtCore\n'), ((325, 344), 'PyQt5.QtCore.pyqtSignal', 'QtCore.pyqtSignal', ([], {}), '()\n', (342, 344), False, 'from PyQt5 import QtWidgets, QtGui, QtCore\n')] |
import functools
import random
import typing as tp
import gin
register = functools.partial(gin.register, module="gacl.callbacks")
class Callback:
def on_start(self):
pass
def on_completed(self, result):
pass
def on_exception(self, exception: Exception):
pass
def on_interru... | [
"gin.config.config_str",
"functools.partial",
"random.seed",
"gin.config.operative_config_str"
] | [((75, 131), 'functools.partial', 'functools.partial', (['gin.register'], {'module': '"""gacl.callbacks"""'}), "(gin.register, module='gacl.callbacks')\n", (92, 131), False, 'import functools\n'), ((2800, 2822), 'random.seed', 'random.seed', (['self.seed'], {}), '(self.seed)\n', (2811, 2822), False, 'import random\n'),... |
import datetime
from django.utils import timezone
from django.test import TestCase
from django.core.urlresolvers import reverse
from polls.models import Question
def create_question(question_text, days):
"""
Creates a question with the given `question_text` published the given
number of `days` offset to... | [
"django.core.urlresolvers.reverse",
"django.utils.timezone.now",
"polls.models.Question.objects.create",
"datetime.timedelta",
"polls.models.Question"
] | [((508, 575), 'polls.models.Question.objects.create', 'Question.objects.create', ([], {'question_text': 'question_text', 'pub_date': 'time'}), '(question_text=question_text, pub_date=time)\n', (531, 575), False, 'from polls.models import Question\n'), ((450, 464), 'django.utils.timezone.now', 'timezone.now', ([], {}), ... |
# -*- coding: utf-8 -*-
"""
@brief test tree node (time=1s)
"""
import sys
import os
import unittest
from pyquickhelper.loghelper import fLOG
from pyquickhelper.texthelper.templating import apply_template, CustomTemplateException
class TestTemplating(unittest.TestCase):
def test_mako(self):
fLOG(... | [
"unittest.main",
"pyquickhelper.loghelper.fLOG"
] | [((4604, 4619), 'unittest.main', 'unittest.main', ([], {}), '()\n', (4617, 4619), False, 'import unittest\n'), ((315, 387), 'pyquickhelper.loghelper.fLOG', 'fLOG', (['__file__', 'self._testMethodName'], {'OutputPrint': "(__name__ == '__main__')"}), "(__file__, self._testMethodName, OutputPrint=__name__ == '__main__')\n... |
import numpy as np
from . import compute_max_angle
def gensk97(N):
# See http://dx.doi.org/10.1016/j.jsb.2006.06.002 and references therein
N = int(N)
h = -1.0 + (2.0/(N-1))*np.arange(0,N)
theta = np.arccos(h)
phi_base = np.zeros_like(theta)
phi_base[1:(N-1)] = ((3.6/np.sqrt(N))/np.sqrt(1 - h[1... | [
"numpy.zeros_like",
"numpy.sum",
"numpy.ceil",
"numpy.cumsum",
"numpy.sin",
"numpy.array",
"numpy.arange",
"numpy.cos",
"numpy.arccos",
"numpy.sqrt"
] | [((214, 226), 'numpy.arccos', 'np.arccos', (['h'], {}), '(h)\n', (223, 226), True, 'import numpy as np\n'), ((242, 262), 'numpy.zeros_like', 'np.zeros_like', (['theta'], {}), '(theta)\n', (255, 262), True, 'import numpy as np\n'), ((343, 362), 'numpy.cumsum', 'np.cumsum', (['phi_base'], {}), '(phi_base)\n', (352, 362),... |
from moonfire_tokenomics.data_types import Allocation, AllocationRecord, Blockchain, Category, CommonType, Sector, Token
badger = Token(
name="BADGER",
project="Badger DAO",
sector=Sector.DEFI,
blockchain=[Blockchain.ETH, Blockchain.FTM, Blockchain.ONE, Blockchain.GC],
category=[Category.GOV],
... | [
"moonfire_tokenomics.data_types.AllocationRecord"
] | [((430, 508), 'moonfire_tokenomics.data_types.AllocationRecord', 'AllocationRecord', ([], {'type': '"""Gitcoin"""', 'common_type': 'CommonType.ECOSYSTEM', 'share': '(0.02)'}), "(type='Gitcoin', common_type=CommonType.ECOSYSTEM, share=0.02)\n", (446, 508), False, 'from moonfire_tokenomics.data_types import Allocation, A... |
from io import BytesIO
import pytest
from freezegun import freeze_time
from pyhanko.pdf_utils.incremental_writer import IncrementalPdfFileWriter
from pyhanko.pdf_utils.reader import PdfFileReader
from pyhanko.sign import signers
from pyhanko.sign.diff_analysis import ModificationLevel
from pyhanko.sign.signers.pdf_si... | [
"io.BytesIO",
"pyhanko.pdf_utils.reader.PdfFileReader",
"pyhanko_tests.signing_commons.live_testing_vc",
"pyhanko.sign.signers.PdfSignatureMetadata",
"pyhanko_tests.signing_commons.val_trusted",
"pyhanko.sign.signers.pdf_signer.DSSContentSettings",
"pytest.mark.parametrize",
"freezegun.freeze_time"
] | [((919, 986), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""password"""', "[b'<PASSWORD>', b'<PASSWORD>']"], {}), "('password', [b'<PASSWORD>', b'<PASSWORD>'])\n", (942, 986), False, 'import pytest\n'), ((988, 1013), 'freezegun.freeze_time', 'freeze_time', (['"""2020-11-01"""'], {}), "('2020-11-01')\n", (... |
# ============================================================================
#
# Copyright (C) 2007-2016 Conceptive Engineering bvba.
# www.conceptive.be / <EMAIL>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
... | [
"os.path.dirname",
"six.text_type",
"camelot.core.utils.ugettext",
"camelot.view.action_runner.hide_progress_dialog",
"camelot.core.exception.CancelRequest",
"os.path.join"
] | [((3055, 3086), 'six.text_type', 'six.text_type', (['file_name_filter'], {}), '(file_name_filter)\n', (3068, 3086), False, 'import six\n'), ((3137, 3146), 'camelot.core.utils.ugettext', '_', (['"""Open"""'], {}), "('Open')\n", (3138, 3146), True, 'from camelot.core.utils import ugettext as _\n'), ((3321, 3347), 'os.pat... |
from typing import NamedTuple
from odd_models.models import MetadataExtension
_METADATA_SCHEMA_URL_PREFIX: str = (
"https://raw.githubusercontent.com/Max3kkk/odd-tarantool-adapter/dev/metadata_schema.json"
"#/definitions/Tarantool"
)
data_set_metadata_schema_url: str = f"{_METADATA_SCHEMA_URL_PREFIX}DataSetEx... | [
"odd_models.models.MetadataExtension"
] | [((950, 1017), 'odd_models.models.MetadataExtension', 'MetadataExtension', ([], {'schema_url': 'schema_url', 'metadata': 'metadata_wo_none'}), '(schema_url=schema_url, metadata=metadata_wo_none)\n', (967, 1017), False, 'from odd_models.models import MetadataExtension\n')] |
import statistics
from typing import Optional
import typer
import droprates
def exp_vs_lem(drop_threshold: Optional[int] = None) -> None:
explores = droprates.compile_drops(explore=True)
lemonade = droprates.compile_drops(lemonade=True)
for location in sorted(explores.locations.keys() | lemonade.locatio... | [
"droprates.compile_drops",
"statistics.mean",
"typer.run"
] | [((157, 194), 'droprates.compile_drops', 'droprates.compile_drops', ([], {'explore': '(True)'}), '(explore=True)\n', (180, 194), False, 'import droprates\n'), ((210, 248), 'droprates.compile_drops', 'droprates.compile_drops', ([], {'lemonade': '(True)'}), '(lemonade=True)\n', (233, 248), False, 'import droprates\n'), (... |
import re, os
def __next_index__(base,ext,previous):
s = r'^{0}[0-9]+{1}$'.format(re.escape(base),re.escape(ext))
rec = re.compile(s)
index = [p[len(base):] for p in previous if rec.match(p)]
if ext : index = [ p[:-len(ext)] for p in index]
index = [ int(p) for p in index]
counter = max(index)+... | [
"os.listdir",
"re.escape",
"re.compile"
] | [((129, 142), 're.compile', 're.compile', (['s'], {}), '(s)\n', (139, 142), False, 'import re, os\n'), ((830, 845), 'os.listdir', 'os.listdir', (['"""."""'], {}), "('.')\n", (840, 845), False, 'import re, os\n'), ((87, 102), 're.escape', 're.escape', (['base'], {}), '(base)\n', (96, 102), False, 'import re, os\n'), ((1... |
# Python Script to initialize a Peripheral Architecture:
# Developed by <NAME> as part of the Piranhas Toolkit
# Questions & bugs: <EMAIL>
import numpy as np
from piranhas import *
import math
# Run Intialization Parameters:
param = param_init_all()
scale = param.scale
fovea = param.fovea
e0_in_deg = param.e0_in_deg... | [
"numpy.empty",
"numpy.floor",
"numpy.zeros",
"numpy.mod",
"numpy.shape",
"numpy.where",
"numpy.mean",
"numpy.linalg.norm",
"numpy.squeeze",
"numpy.round"
] | [((1329, 1365), 'numpy.shape', 'np.shape', (['peripheral_filters.regions'], {}), '(peripheral_filters.regions)\n', (1337, 1365), True, 'import numpy as np\n'), ((1492, 1556), 'numpy.empty', 'np.empty', (['(N_theta * N_e, peri_height, peri_width)'], {'dtype': 'object'}), '((N_theta * N_e, peri_height, peri_width), dtype... |
#!/usr/bin/python
import os
import sys
import numpy
import datetime
import re
# Probability of correctness
fq_prob_list = [0.725,
0.9134,
0.936204542,
0.949544344,
0.959009084,
0.966350507,
0.972348887,
0.97... | [
"numpy.copy",
"numpy.searchsorted",
"re.findall",
"numpy.array",
"numpy.math.log10",
"datetime.datetime.now",
"sys.exit"
] | [((4481, 4504), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (4502, 4504), False, 'import datetime\n'), ((3719, 3730), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (3727, 3730), False, 'import sys\n'), ((13758, 13817), 'numpy.searchsorted', 'numpy.searchsorted', (['crt_pt_sorted_array', '[star... |
import os
import json
import argparse
import sys
import numpy as np
from logger import Logger
from pathlib import Path
from joblib import Parallel, delayed
from modeling.model import KuramotoSystem, plot_interaction
from plotting.animate import Animator
from plotting.plot_solution import PlotSetup
CONFIG_NAME = 'co... | [
"json.dump",
"json.load",
"argparse.ArgumentParser",
"json.loads",
"subprocess.check_output",
"plotting.animate.Animator",
"json.dumps",
"modeling.model.KuramotoSystem",
"pathlib.Path",
"numpy.linspace",
"joblib.Parallel",
"plotting.plot_solution.PlotSetup",
"joblib.delayed",
"modeling.mod... | [((788, 873), 'modeling.model.KuramotoSystem', 'KuramotoSystem', (['(nodes_side, nodes_side)', "config['system']", 'gain'], {'boundary': 'torus'}), "((nodes_side, nodes_side), config['system'], gain, boundary=torus\n )\n", (802, 873), False, 'from modeling.model import KuramotoSystem, plot_interaction\n'), ((940, 97... |
#!/usr/bin/env python
"""
# *****************************************************************
# (C) Copyright IBM Corp. 2021. 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... | [
"open_ce.build_tree.construct_build_tree",
"os.path.join",
"os.makedirs",
"open_ce.graph.export_image"
] | [((1346, 1372), 'open_ce.build_tree.construct_build_tree', 'construct_build_tree', (['args'], {}), '(args)\n', (1366, 1372), False, 'from open_ce.build_tree import construct_build_tree\n'), ((1377, 1423), 'os.makedirs', 'os.makedirs', (['args.output_folder'], {'exist_ok': '(True)'}), '(args.output_folder, exist_ok=True... |
import cv2
import sys
import glob
cascPath = "haarcascade_frontalface_alt.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
# The files are in PGM format, and can conveniently be viewed on UNIX (TM) systems using the 'xv' program. The size of each image is 92x112 pixels, with 256 grey levels per pixel. The images ar... | [
"cv2.waitKey",
"cv2.cvtColor",
"cv2.imread",
"glob.glob",
"cv2.CascadeClassifier",
"cv2.destroyAllWindows"
] | [((94, 125), 'cv2.CascadeClassifier', 'cv2.CascadeClassifier', (['cascPath'], {}), '(cascPath)\n', (115, 125), False, 'import cv2\n'), ((655, 681), 'glob.glob', 'glob.glob', (['"""data/s*/*.pgm"""'], {}), "('data/s*/*.pgm')\n", (664, 681), False, 'import glob\n'), ((2803, 2817), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], ... |