code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import dotworld
import ufrnsplashworld
from src.define import *
from src.dot.entities.dotpairg import DotPairg
from src.dot.dottext import DotText
import i18n
_ = i18n.language.ugettext
class LogoSplashWorld(dotworld.DotWorld):
def __init__(self):
dotworld.DotWorld.__init__(self)
self.counter = ... | [
"dotworld.DotWorld.__init__",
"ufrnsplashworld.UfrnSplashWorld",
"src.dot.entities.dotpairg.DotPairg",
"src.dot.dottext.DotText"
] | [((264, 296), 'dotworld.DotWorld.__init__', 'dotworld.DotWorld.__init__', (['self'], {}), '(self)\n', (290, 296), False, 'import dotworld\n'), ((418, 428), 'src.dot.entities.dotpairg.DotPairg', 'DotPairg', ([], {}), '()\n', (426, 428), False, 'from src.dot.entities.dotpairg import DotPairg\n'), ((450, 553), 'src.dot.do... |
# Copyright (c) 2020 SMHI, Swedish Meteorological and Hydrological Institute
# License: MIT License (see LICENSE.txt or http://opensource.org/licenses/mit).
"""
Created on 2020-12-15 14:15
@author: johannes
"""
from pathlib import Path
from sharkstruc.readers.xlsx import PandasXlsxReader
from sharkstruc.readers.txt ... | [
"pathlib.Path"
] | [((1906, 1919), 'pathlib.Path', 'Path', (['args[0]'], {}), '(args[0])\n', (1910, 1919), False, 'from pathlib import Path\n'), ((1948, 1958), 'pathlib.Path', 'Path', (['args'], {}), '(args)\n', (1952, 1958), False, 'from pathlib import Path\n')] |
"""
Draw stuff in the game!
"""
import pyglet
import pyglet.window.key
import pyglet.gl as gl
import pymunk.pyglet_util
import whoosh.graphics.camera
from whoosh.engine.core import WhooshCore
from whoosh.components.animatedsprite import AnimatedSpriteComponent
from whoosh.components.physics import PhysicsComponent
from... | [
"pyglet.app.run",
"pyglet.clock.ClockDisplay",
"pyglet.graphics.Batch",
"pyglet.gl.glTexParameteri",
"pyglet.window.Window.__init__",
"pyglet.gl.glEnable"
] | [((604, 649), 'pyglet.window.Window.__init__', 'pyglet.window.Window.__init__', (['self'], {}), '(self, **kwargs)\n', (633, 649), False, 'import pyglet\n'), ((976, 1003), 'pyglet.clock.ClockDisplay', 'pyglet.clock.ClockDisplay', ([], {}), '()\n', (1001, 1003), False, 'import pyglet\n'), ((1026, 1049), 'pyglet.graphics.... |
#!/usr/bin/python3
"""Platform for light integration."""
import logging
# Import the device class from the component that you want to support
from datetime import timedelta
from typing import Any, List
import homeassistant.util.color as color_util
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
... | [
"logging.getLogger",
"wyzeapy.base_client.DeviceTypes",
"datetime.timedelta",
"homeassistant.util.color.rgb_hex_to_rgb_list"
] | [((768, 795), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (785, 795), False, 'import logging\n'), ((850, 871), 'datetime.timedelta', 'timedelta', ([], {'seconds': '(30)'}), '(seconds=30)\n', (859, 871), False, 'from datetime import timedelta\n'), ((1810, 1848), 'wyzeapy.base_client.Dev... |
from sklearn import datasets, svm
from sklearn.metrics import accuracy_score, precision_recall_fscore_support
from experitur import Experiment, Trial
from experitur.parameters import Grid
@Grid({"svc_kernel": ["linear", "poly", "rbf", "sigmoid"]})
@Experiment()
def classifier_svm(trial: Trial):
X, y = datasets.l... | [
"sklearn.metrics.precision_recall_fscore_support",
"experitur.Experiment",
"sklearn.datasets.load_digits",
"experitur.parameters.Grid",
"sklearn.metrics.accuracy_score"
] | [((192, 250), 'experitur.parameters.Grid', 'Grid', (["{'svc_kernel': ['linear', 'poly', 'rbf', 'sigmoid']}"], {}), "({'svc_kernel': ['linear', 'poly', 'rbf', 'sigmoid']})\n", (196, 250), False, 'from experitur.parameters import Grid\n'), ((252, 264), 'experitur.Experiment', 'Experiment', ([], {}), '()\n', (262, 264), F... |
"""
Do Not Edit this file. You may and are encouraged to look at it for reference.
"""
import unittest
import re
import gas_mileage
class TestListTrips(unittest.TestCase):
def verifyLines(self, notebook, mpg):
from gas_mileage import listTrips
trips = listTrips(notebook)
self.assertTrue(... | [
"unittest.main",
"gas_mileage.listTrips"
] | [((2417, 2432), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2430, 2432), False, 'import unittest\n'), ((276, 295), 'gas_mileage.listTrips', 'listTrips', (['notebook'], {}), '(notebook)\n', (285, 295), False, 'from gas_mileage import listTrips\n'), ((1594, 1613), 'gas_mileage.listTrips', 'listTrips', (['noteboo... |
import nhpp
import math
import numpy as np
import pandas as pd
import pytest
@pytest.mark.parametrize("test_input,expected", [
({0: 1, 2: 1, 1: 0}, ([0, 1, 2], [1, 0, 1])),
({0: 1, 3: 1, 2: 2}, ([0, 2, 3], [1, 2, 1])),
])
def test_sorting(test_input, expected):
assert nhpp.nhpp._get_sorted_pairs(test_input) == ex... | [
"numpy.histogram",
"nhpp.nhpp._get_piecewise_val",
"nhpp.get_arrivals",
"numpy.sin",
"pytest.mark.parametrize",
"numpy.sum",
"nhpp.nhpp._get_rate_slopes",
"pytest.raises",
"numpy.array",
"numpy.linspace",
"pandas.DataFrame",
"nhpp.nhpp._get_sorted_pairs"
] | [((80, 241), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""test_input,expected"""', '[({(0): 1, (2): 1, (1): 0}, ([0, 1, 2], [1, 0, 1])), ({(0): 1, (3): 1, (2):\n 2}, ([0, 2, 3], [1, 2, 1]))]'], {}), "('test_input,expected', [({(0): 1, (2): 1, (1): 0},\n ([0, 1, 2], [1, 0, 1])), ({(0): 1, (3): 1, (2... |
from django.db import models
from localflavor.in_.models import INStateField
class Customer(models.Model):
def __str__(self):
return f"{self.name} | {self.email}"
name = models.CharField(max_length=128, blank=True, null=True)
email = models.EmailField(max_length=128, db_index=True, blank=True, nu... | [
"django.db.models.EmailField",
"django.db.models.DateTimeField",
"localflavor.in_.models.INStateField",
"django.db.models.DecimalField",
"django.db.models.CharField"
] | [((189, 244), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(128)', 'blank': '(True)', 'null': '(True)'}), '(max_length=128, blank=True, null=True)\n', (205, 244), False, 'from django.db import models\n'), ((257, 346), 'django.db.models.EmailField', 'models.EmailField', ([], {'max_length': '(12... |
# -*-coding:utf-8 -*-
# Reference:**********************************************
# @Time : 2019-08-22 21:30
# @Author : <NAME>
# @File : cv2_test.py
# @User : liyihao
# @Software: PyCharm
# @Description: line regression
# Reference:**********************************************
import numpy as np
import ... | [
"numpy.random.choice",
"random.random",
"random.randint"
] | [((1482, 1523), 'numpy.random.choice', 'np.random.choice', (['num_samples', 'batch_size'], {}), '(num_samples, batch_size)\n', (1498, 1523), True, 'import numpy as np\n'), ((1840, 1861), 'random.randint', 'random.randint', (['(0)', '(10)'], {}), '(0, 10)\n', (1854, 1861), False, 'import random\n'), ((1864, 1879), 'rand... |
from dataclasses import FrozenInstanceError
import pytest
from rest_client.base.config import BaseUrlConfig
base_url = 'https://www.saleweaver.com/'
def test_create_endpoint_config():
endpoint_config = BaseUrlConfig(base_url)
assert endpoint_config.base_url == base_url
assert endpoint_config.sandbox_url... | [
"rest_client.base.config.BaseUrlConfig",
"pytest.raises"
] | [((210, 233), 'rest_client.base.config.BaseUrlConfig', 'BaseUrlConfig', (['base_url'], {}), '(base_url)\n', (223, 233), False, 'from rest_client.base.config import BaseUrlConfig\n'), ((380, 403), 'rest_client.base.config.BaseUrlConfig', 'BaseUrlConfig', (['base_url'], {}), '(base_url)\n', (393, 403), False, 'from rest_... |
import json
testData = {}
testData["sfcsho"] = {}
testData["sfcsho"]["weekday"] = []
# testData["sfcsho"]["sat"] = {}
# testData["sfcsho"]["sun"] = {}
for h in range(0,24):
for m in range(0,60):
busData = {
"hour": h,
"min": m,
"type": None,
"rotary": Fal... | [
"json.dump"
] | [((485, 523), 'json.dump', 'json.dump', (['testData', 'outfile'], {'indent': '(4)'}), '(testData, outfile, indent=4)\n', (494, 523), False, 'import json\n')] |
import mock
import os
import textwrap
from mock import Mock
from conan.tools.microsoft import MSBuild, MSBuildToolchain
from conans.model.conf import ConfDefinition
from conans.model.env_info import EnvValues
from conans.test.utils.mocks import ConanFileMock, MockSettings
from conans.tools import load
from conans impo... | [
"conan.tools.microsoft.MSBuild",
"textwrap.dedent",
"conans.test.utils.mocks.MockSettings",
"conans.test.utils.mocks.ConanFileMock",
"mock.Mock",
"conans.Settings",
"os.getcwd",
"conans.model.env_info.EnvValues",
"conan.tools.microsoft.MSBuildToolchain",
"conans.tools.load",
"conans.model.conf.C... | [((383, 399), 'conans.model.conf.ConfDefinition', 'ConfDefinition', ([], {}), '()\n', (397, 399), False, 'from conans.model.conf import ConfDefinition\n'), ((541, 661), 'conans.test.utils.mocks.MockSettings', 'MockSettings', (["{'build_type': 'Release', 'compiler': 'gcc', 'compiler.version': '7', 'os':\n 'Linux', 'a... |
import errno
import os
import pytest
from Mainframe3270.py3270 import Emulator, TerminatedError
CURDIR = os.path.dirname(os.path.realpath(__file__))
@pytest.fixture
def mock_windows(mocker):
mocker.patch("Mainframe3270.py3270.os_name", "nt")
@pytest.fixture
def mock_posix(mocker):
mocker.patch("Mainframe... | [
"os.path.realpath",
"os.path.join",
"Mainframe3270.py3270.Emulator",
"pytest.raises"
] | [((124, 150), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (140, 150), False, 'import os\n'), ((453, 463), 'Mainframe3270.py3270.Emulator', 'Emulator', ([], {}), '()\n', (461, 463), False, 'from Mainframe3270.py3270 import Emulator, TerminatedError\n'), ((646, 668), 'Mainframe3270.py3270.... |
from __future__ import unicode_literals
import cherrypy
import sideboard.server
if __name__ == '__main__':
cherrypy.engine.start()
cherrypy.engine.block()
| [
"cherrypy.engine.start",
"cherrypy.engine.block"
] | [((114, 137), 'cherrypy.engine.start', 'cherrypy.engine.start', ([], {}), '()\n', (135, 137), False, 'import cherrypy\n'), ((142, 165), 'cherrypy.engine.block', 'cherrypy.engine.block', ([], {}), '()\n', (163, 165), False, 'import cherrypy\n')] |
import classfile
import instructions
import instructions.base
import rtda
import rtda.heap
def logInstruction(frame:rtda.Frame, inst:instructions.base.Instruction):
method = frame.Method()
className = method.Class().Name()
methodName = method.Name()
pc = frame.Thread().PC()
print(f"{className}.{met... | [
"rtda.NewThread",
"instructions.base.BytecodeReader",
"instructions.NewInstruction"
] | [((409, 443), 'instructions.base.BytecodeReader', 'instructions.base.BytecodeReader', ([], {}), '()\n', (441, 443), False, 'import instructions\n'), ((1306, 1322), 'rtda.NewThread', 'rtda.NewThread', ([], {}), '()\n', (1320, 1322), False, 'import rtda\n'), ((664, 699), 'instructions.NewInstruction', 'instructions.NewIn... |
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.db.models import F
from django.utils import timezone
from django_ajax.decorators import ajax
from django.core.mail import EmailMessage
from wsgiref.util import FileWrapper
from... | [
"django.shortcuts.render",
"django.http.HttpResponse",
"django.core.mail.EmailMessage",
"wsgiref.util.FileWrapper"
] | [((451, 499), 'django.shortcuts.render', 'render', (['request', '"""main_page/index.html"""', 'context'], {}), "(request, 'main_page/index.html', context)\n", (457, 499), False, 'from django.shortcuts import render, get_object_or_404\n'), ((574, 625), 'django.shortcuts.render', 'render', (['request', '"""main_page/serv... |
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | [
"google.cloud.storage.Client",
"re.compile",
"pathlib.Path",
"google.protobuf.timestamp_pb2.Timestamp",
"datetime.datetime.now",
"re.sub",
"typing.TypeVar"
] | [((2076, 3317), 'typing.TypeVar', 'TypeVar', (['"""VertexAiServiceClient"""', 'dataset_service_client_v1beta1.DatasetServiceClient', 'endpoint_service_client_v1beta1.EndpointServiceClient', 'featurestore_online_serving_service_client_v1beta1.FeaturestoreOnlineServingServiceClient', 'featurestore_service_client_v1beta1.... |
import numpy as np
#import pickle
#A = np.loadtxt("Rock_Paper_Scissors_Raw.txt", dtype = list, comments = '#', delimiter = ',', usecols = (0,1,2,3))
#A = np.loadtxt("Rock_Paper_Scissors_Raw.txt", dtype = int, comments = '#', delimiter = ',', usecols = (2), ndmin = 1)
#B = np.loadtxt("Rock_Paper_Scissors_Raw.txt", dtyp... | [
"itertools.product",
"numpy.genfromtxt"
] | [((4403, 4522), 'numpy.genfromtxt', 'np.genfromtxt', (['"""Rock_Paper_Scissors_Raw.txt"""'], {'dtype': 'int', 'comments': '"""#"""', 'delimiter': '""","""', 'usecols': '(0, 2)', 'max_rows': '(5000)'}), "('Rock_Paper_Scissors_Raw.txt', dtype=int, comments='#',\n delimiter=',', usecols=(0, 2), max_rows=5000)\n", (4416... |
import yaml
import pandas as pd
import numpy as np
from glob import glob
import sys
# Create the datatable containing the samples, units and paths of all
# fastq files formatted correctly. This is vital for the snakemake
# pipeline, without it, the wildcards can't be created.
with open(sys.argv[1]) as f_:
config ... | [
"yaml.load",
"glob.glob"
] | [((322, 359), 'yaml.load', 'yaml.load', (['f_'], {'Loader': 'yaml.FullLoader'}), '(f_, Loader=yaml.FullLoader)\n', (331, 359), False, 'import yaml\n'), ((1744, 1778), 'glob.glob', 'glob', (['"""results/assembly/*/*.fastq"""'], {}), "('results/assembly/*/*.fastq')\n", (1748, 1778), False, 'from glob import glob\n'), ((1... |
# gbfs.py
# Parser: General Bikeshare Feed Specification
import json, re, urllib2, requests
from bsrp import bsrputil
def scrape(df, apikey):
# get the GBFS 'pointer' file that indicates paths to the key files
try:
info_req = requests.get( df['feedurl'] )
info_json = json.loads(inf... | [
"json.loads",
"requests.get"
] | [((255, 282), 'requests.get', 'requests.get', (["df['feedurl']"], {}), "(df['feedurl'])\n", (267, 282), False, 'import json, re, urllib2, requests\n'), ((306, 331), 'json.loads', 'json.loads', (['info_req.text'], {}), '(info_req.text)\n', (316, 331), False, 'import json, re, urllib2, requests\n'), ((519, 547), 'request... |
from pymongo import MongoClient
def create_indexes(config):
# Create index
mongo = MongoClient(config['MONGO_URI'])
db = getattr(mongo, config['MONGO_DBNAME'])
db.execution.create_index("id", unique=True)
db.execution.create_index("status")
db.execution.create_index("started_at")
db.execu... | [
"pymongo.MongoClient"
] | [((93, 125), 'pymongo.MongoClient', 'MongoClient', (["config['MONGO_URI']"], {}), "(config['MONGO_URI'])\n", (104, 125), False, 'from pymongo import MongoClient\n')] |
import dill
import json
import os
def load(path):
"""
Loads a saved model and returns it.
Args:
path: Name of the model or full path to model.
Example::
import backprop
backprop.save(model_object, "my_model")
model = backprop.load("my_model")
"""
# Try to loo... | [
"os.path.exists",
"os.path.isabs",
"os.path.join",
"os.getcwd",
"os.path.expanduser",
"dill.load"
] | [((355, 402), 'os.path.expanduser', 'os.path.expanduser', (['f"""~/.cache/backprop/{path}"""'], {}), "(f'~/.cache/backprop/{path}')\n", (373, 402), False, 'import os\n'), ((426, 463), 'os.path.join', 'os.path.join', (['cache_path', '"""model.bin"""'], {}), "(cache_path, 'model.bin')\n", (438, 463), False, 'import os\n'... |
from dataclasses import dataclass
from typing import List
from exceptions import GameException
from rules import Rule
class ScoreBoard:
rules: List[Rule] = []
scores: List[int] = []
def register_rules(self, rules: List[Rule]):
self.rules = rules
self.scores = [None] * len(rules)
def... | [
"exceptions.GameException"
] | [((434, 481), 'exceptions.GameException', 'GameException', (['f"""Unknown rule key {rule_index}"""'], {}), "(f'Unknown rule key {rule_index}')\n", (447, 481), False, 'from exceptions import GameException\n')] |
#!/usr/bin/env python3
# test_conv2d.py
#
# Copyright (c) 2010-2018 Wave Computing, Inc. and its applicable licensors.
# All rights reserved; provided, that any files identified as open source shall
# be governed by the specific open source license(s) applicable to such files.
#
# For any files associated with d... | [
"tensorflow.nn.conv2d",
"progressbar.Bar",
"numpy.allclose",
"tensorflow.reset_default_graph",
"numpy.isclose",
"numpy.where",
"waveflow.wavecomp_ops_module.wave_conv2d",
"tensorflow.Session",
"tensorflow.truncated_normal_initializer",
"tensorflow.global_variables_initializer",
"progressbar.Perc... | [((2939, 2963), 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), '()\n', (2961, 2963), True, 'import tensorflow as tf\n'), ((3255, 3305), 'progressbar.ProgressBar', 'pb.ProgressBar', ([], {'widgets': 'widgets', 'maxval': 'iterations'}), '(widgets=widgets, maxval=iterations)\n', (3269, 3305), True, ... |
import bisect
import json
import os
import re
import subprocess
from datetime import datetime, timedelta, timezone
from typing import List, Optional
import pytz
from .location_history import Location
from .log import log
from .timezone import gps_coords_to_utc_offset
def read_exif(root: str) -> List[dict]:
log.... | [
"json.loads",
"datetime.datetime.fromtimestamp",
"re.compile",
"datetime.datetime.strptime",
"subprocess.run",
"datetime.timedelta",
"bisect.bisect_left"
] | [((861, 928), 're.compile', 're.compile', (['"""(?P<sign>\\\\+|-)?(?P<hours>\\\\d{2}):(?P<minutes>\\\\d{2})"""'], {}), "('(?P<sign>\\\\+|-)?(?P<hours>\\\\d{2}):(?P<minutes>\\\\d{2})')\n", (871, 928), False, 'import re\n'), ((387, 473), 'subprocess.run', 'subprocess.run', (["['exiftool', '-json', '-r', root]"], {'captur... |
import os
import re
from weakref import WeakKeyDictionary
from io import StringIO
import trafaret as _trafaret
from yaml import load, dump, ScalarNode
from yaml.scanner import ScannerError
try:
from yaml import CSafeLoader as SafeLoader
except ImportError:
from yaml import SafeLoader
from .error import Config... | [
"io.StringIO",
"yaml.SafeLoader.__init__",
"re.compile"
] | [((352, 392), 're.compile', 're.compile', (['"""\\\\$(\\\\w+)|\\\\$\\\\{([^}]+)\\\\}"""'], {}), "('\\\\$(\\\\w+)|\\\\$\\\\{([^}]+)\\\\}')\n", (362, 392), False, 'import re\n'), ((5231, 5247), 'io.StringIO', 'StringIO', (['string'], {}), '(string)\n', (5239, 5247), False, 'from io import StringIO\n'), ((1980, 2013), 'ya... |
from django.db.models import Q, Count
from picasso.index.models import Tag, Listing
__author__ = 'tmehta'
def get_current_tags(request):
full_tags = Tag.objects.annotate(num_listings=Count('listings')).filter(parent_tag=None, visible=True).order_by(
'-num_listings')
all_tags = Tag.objects.annotate(nu... | [
"django.db.models.Count",
"picasso.index.models.Listing.objects.count"
] | [((506, 529), 'picasso.index.models.Listing.objects.count', 'Listing.objects.count', ([], {}), '()\n', (527, 529), False, 'from picasso.index.models import Tag, Listing\n'), ((190, 207), 'django.db.models.Count', 'Count', (['"""listings"""'], {}), "('listings')\n", (195, 207), False, 'from django.db.models import Q, Co... |
# Copyright 2015 Infoblox 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... | [
"logging.getLogger",
"infoblox_client.objects.DNSView.create",
"infoblox_client.objects.FixedAddress.create",
"infoblox_client.objects.Dhcpoption",
"infoblox_client.objects.Network.search_all",
"infoblox_client.objects.HostRecord.search_all",
"infoblox_client.objects.IPRange.create",
"infoblox_client.... | [((878, 905), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (895, 905), False, 'import logging\n'), ((1091, 1167), 'infoblox_client.objects.NetworkView.create', 'obj.NetworkView.create', (['self.connector'], {'name': 'network_view', 'extattrs': 'extattrs'}), '(self.connector, name=networ... |
# Copyright 2019 SAP SE
# 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, software
#... | [
"os.path.exists",
"datetime.datetime.fromtimestamp",
"argparse.ArgumentParser",
"os.makedirs",
"functools.reduce",
"cfg.load_config.cfg_from_file",
"networks.net_DGMa.netD",
"random.seed",
"numpy.random.seed",
"shutil.rmtree",
"networks.net_DGMa.parameters",
"time.time",
"random.randint",
... | [((785, 796), 'time.time', 'time.time', ([], {}), '()\n', (794, 796), False, 'import time\n'), ((819, 861), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""xxx"""'}), "(description='xxx')\n", (842, 861), False, 'import argparse\n'), ((1874, 1897), 'cfg.load_config.cfg_from_file', 'cfg_fro... |
# The MIT License
# Modified to work with MK1 keyboards
import hid
import mido
from msvcrt import getch
numkeys = 88 #change this to the number of keys on your keyboard
offset = -(108-numkeys+1)
pid = 0x1410 #change this to the product id of your keyboard
def init():
"""Connect to the keyboard, swi... | [
"mido.get_input_names",
"mido.open_input",
"hid.device"
] | [((438, 450), 'hid.device', 'hid.device', ([], {}), '()\n', (448, 450), False, 'import hid\n'), ((3184, 3206), 'mido.get_input_names', 'mido.get_input_names', ([], {}), '()\n', (3204, 3206), False, 'import mido\n'), ((3353, 3378), 'mido.open_input', 'mido.open_input', (['portName'], {}), '(portName)\n', (3368, 3378), F... |
#!/usr/bin/env python3
""" Run the gear: set up for and call command-line code """
import json
import os
import subprocess as sp
import sys
import shutil
import psutil
import glob
import flywheel
from utils import args
from utils.bids.download_bids import *
from utils.bids.validate_bids import *
from utils.fly.custom... | [
"os.path.exists",
"utils.args.build_command",
"flywheel.GearContext",
"subprocess.run",
"os.path.join",
"utils.args.validate",
"utils.results.zip_intermediate.zip_all_intermediate_output",
"utils.results.zip_htmls.zip_htmls",
"psutil.virtual_memory",
"utils.results.zip_intermediate.zip_intermediat... | [((3449, 3470), 'utils.results.set_zip_name.set_zip_head', 'set_zip_head', (['context'], {}), '(context)\n', (3461, 3470), False, 'from utils.results.set_zip_name import set_zip_head\n'), ((3515, 3553), 'os.path.join', 'os.path.join', (['context.work_dir', '"""bids"""'], {}), "(context.work_dir, 'bids')\n", (3527, 3553... |
import torch
from scipy.misc import imread, imsave, imresize
import matplotlib.pyplot as plt
import numpy as np
from path import Path
import argparse
from tqdm import tqdm
from models import DispResNet6
from utils import tensor2array
parser = argparse.ArgumentParser(description='Inference script for DispNet learned ... | [
"argparse.ArgumentParser",
"utils.tensor2array",
"torch.load",
"tqdm.tqdm",
"torch.from_numpy",
"path.Path",
"scipy.misc.imread",
"scipy.misc.imresize",
"models.DispResNet6",
"numpy.transpose"
] | [((246, 497), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Inference script for DispNet learned with Structure from Motion Learner inference on KITTI and CityScapes Dataset"""', 'formatter_class': 'argparse.ArgumentDefaultsHelpFormatter'}), "(descriptio... |
"""Adds the ability to Controllers to checkpoint upon receipt of a
signal, by default SIGTERM. There can be only one instance of Handler.
Your class must subclass from both Handler.Handler and
Controller.Controller, furthermore Handler must be the leftmost of the
superclasses. E.g.,
class MyController(Handler.Handler... | [
"signal.signal",
"weakref.ref",
"sys.exit"
] | [((2172, 2217), 'signal.signal', 'signal.signal', (['signal.SIGTERM', 'Handler.handle'], {}), '(signal.SIGTERM, Handler.handle)\n', (2185, 2217), False, 'import signal\n'), ((807, 824), 'weakref.ref', 'weakref.ref', (['self'], {}), '(self)\n', (818, 824), False, 'import weakref\n'), ((2116, 2127), 'sys.exit', 'sys.exit... |
from Hiven.client import Bot, events #import events
bot = Bot("Your Bot Token")
@events.event
def on_message(ctx): # this method gets called when a someone sends a message
if ctx.author.id != bot.user.id: # checks if author of message is not bot account to prevent spam
if ctx.message.content == "ping":... | [
"Hiven.client.Bot"
] | [((60, 81), 'Hiven.client.Bot', 'Bot', (['"""Your Bot Token"""'], {}), "('Your Bot Token')\n", (63, 81), False, 'from Hiven.client import Bot, events\n')] |
# Generated by Django 2.0.1 on 2018-05-27 10:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('catalog', '0010_auto_20180527_1235'),
]
operations = [
migrations.AddField(
model_name='dayinstance',
name='day_imag... | [
"django.db.models.ImageField"
] | [((342, 388), 'django.db.models.ImageField', 'models.ImageField', ([], {'default': '""""""', 'upload_to': '"""day"""'}), "(default='', upload_to='day')\n", (359, 388), False, 'from django.db import migrations, models\n')] |
import pyautogui
from PIL import Image, ImageGrab
import time
def hit(key):
pyautogui.keyDown(key)
# LIGHT
def isCollide(data):
# Check for birds
#for i in range(200, 250):
# for j in range(355, 370):
# if data[i, j] < 171:
# hit("down")
... | [
"PIL.ImageGrab.grab",
"pyautogui.keyDown",
"time.sleep"
] | [((82, 104), 'pyautogui.keyDown', 'pyautogui.keyDown', (['key'], {}), '(key)\n', (99, 104), False, 'import pyautogui\n'), ((998, 1011), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (1008, 1011), False, 'import time\n'), ((1059, 1075), 'PIL.ImageGrab.grab', 'ImageGrab.grab', ([], {}), '()\n', (1073, 1075), False,... |
""" The broker service
This REST service fields incoming registration requests from endpoints,
creates an appropriate forwarder to which the endpoint can connect up.
"""
import bottle
from bottle import post, run, request, route
import argparse
import json
import uuid
import sys
from funcx_endpoint.mock_broker.forw... | [
"argparse.ArgumentParser",
"funcx_endpoint.mock_broker.forwarder.spawn_forwarder",
"bottle.post",
"bottle.route",
"uuid.uuid4",
"json.load",
"bottle.default_app"
] | [((363, 380), 'bottle.post', 'post', (['"""/register"""'], {}), "('/register')\n", (367, 380), False, 'from bottle import post, run, request, route\n'), ((1388, 1411), 'bottle.route', 'route', (['"""/list_mappings"""'], {}), "('/list_mappings')\n", (1393, 1411), False, 'from bottle import post, run, request, route\n'),... |
from functools import wraps, partial
import trio
import asyncpg
import trio_asyncio
def _shielded(f):
@wraps(f)
async def wrapper(*args, **kwargs):
with trio.open_cancel_scope(shield=True):
return await f(*args, **kwargs)
return wrapper
def connect(*args, **kwargs):
return TrioC... | [
"trio_asyncio.aio_as_trio",
"trio.open_cancel_scope",
"functools.partial",
"functools.wraps"
] | [((109, 117), 'functools.wraps', 'wraps', (['f'], {}), '(f)\n', (114, 117), False, 'from functools import wraps, partial\n'), ((956, 997), 'functools.partial', 'partial', (['asyncpg.connect', '*args'], {}), '(asyncpg.connect, *args, **kwargs)\n', (963, 997), False, 'from functools import wraps, partial\n'), ((2754, 279... |
import pickle
from PIL import Image
import numpy as np
from dlib import cnn_face_detection_model_v1
from controller import Camera
from flockai.PyCatascopia.Metrics import *
from flockai.interfaces.flockai_ml import FlockAIClassifier
from flockai.models.probes.flockai_probe import FlockAIProbe, ProcessCpuUtilizationMet... | [
"flockai.models.devices.device_enums.Devices",
"PIL.Image.open",
"flockai.models.probes.flockai_probe.ProcessCpuTimeMetric",
"flockai.models.probes.flockai_probe.FlockAIProbe",
"flockai.models.probes.flockai_probe.ProbeAliveTimeMetric",
"flockai.models.devices.device_enums.Relative2DPosition",
"dlib.cnn... | [((1903, 1969), 'flockai.models.devices.device_enums.Devices', 'Devices', (['enableable_devices', 'non_enableable_devices', 'motor_devices'], {}), '(enableable_devices, non_enableable_devices, motor_devices)\n', (1910, 1969), False, 'from flockai.models.devices.device_enums import EnableableDevice, NonEnableableDevice,... |
from django.db import models
from servers.models import Compute
class Instance(models.Model):
compute = models.ForeignKey(Compute)
name = models.CharField(max_length=20)
uuid = models.CharField(max_length=36)
# display_name = models.CharField(max_length=50)
# display_description = models.CharField(m... | [
"django.db.models.CharField",
"django.db.models.ForeignKey"
] | [((110, 136), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Compute'], {}), '(Compute)\n', (127, 136), False, 'from django.db import models\n'), ((148, 179), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(20)'}), '(max_length=20)\n', (164, 179), False, 'from django.db import models\n')... |
from AuthTest import fetchToken, getHeader
import requests
header1 = getHeader(fetchToken("<EMAIL>", "rentify"))
header2 = getHeader(fetchToken("<EMAIL>", "rentify"))
r = requests.get("http://localhost:4200/groups", headers= header1)
# gidten = r.json()["tenant"][0]["_id"]
# r = requests.get(f"http://localhost:4200/... | [
"requests.post",
"AuthTest.fetchToken",
"requests.get"
] | [((173, 234), 'requests.get', 'requests.get', (['"""http://localhost:4200/groups"""'], {'headers': 'header1'}), "('http://localhost:4200/groups', headers=header1)\n", (185, 234), False, 'import requests\n'), ((361, 525), 'requests.post', 'requests.post', (['"""http://localhost:4200/groups"""'], {'headers': 'header2', '... |
from __future__ import print_function
from ovirtsdk.api import API
import sys
class vm_balance():
"""moves a vm from a host with to many"""
# What are the values this module will accept, used to present
# the user with options
properties_validation = 'maximum_vm_count=[0-9]*'
def _get_connection... | [
"ovirtsdk.api.API"
] | [((436, 500), 'ovirtsdk.api.API', 'API', ([], {'url': '"""http://host:port"""', 'username': '"""user@domain"""', 'password': '""""""'}), "(url='http://host:port', username='user@domain', password='')\n", (439, 500), False, 'from ovirtsdk.api import API\n')] |
# Author: karl
# Created: 2020-06-21, 9:34 a.m.
import os
import copy
import time
import logging
import numpy as np
from typing import *
from mg_general import Environment
from mg_io.general import mkdir_p, write_to_file, remove_p
from mg_general.general import get_value, run_shell_cmd
from mg_options.parallelizati... | [
"logging.getLogger",
"mg_io.general.mkdir_p",
"mg_parallelization.pbs_job_package.PBSJobPackage.load",
"mg_parallelization.pbs_job_package.PBSJobPackage.save",
"mg_general.general.run_shell_cmd",
"os.path.join",
"time.time",
"mg_general.general.get_value",
"copy.deepcopy",
"mg_io.general.write_to_... | [((421, 448), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (438, 448), False, 'import logging\n'), ((649, 676), 'copy.deepcopy', 'copy.deepcopy', (['self._kwargs'], {}), '(self._kwargs)\n', (662, 676), False, 'import copy\n'), ((1404, 1439), 'mg_general.general.get_value', 'get_value', ... |
#!/usr/bin/env python3
import os
device_class = os.getenv("ICEDEVICE")
with open("../icebox/iceboxdb.py", "w") as f:
files = [ "database_io", "database_logic", "database_ramb", "database_ramt", "database_ipcon_5k"]
for device_class in ["8k"]:
files.append("database_ramb_" + device_class)
files.app... | [
"os.getenv"
] | [((49, 71), 'os.getenv', 'os.getenv', (['"""ICEDEVICE"""'], {}), "('ICEDEVICE')\n", (58, 71), False, 'import os\n')] |
from symsynd.heuristics import get_ip_register
def test_ip_reg():
assert get_ip_register({'pc': '0x42'}, 'arm7') == int('42', 16)
assert get_ip_register({}, 'arm7') == None
assert get_ip_register({}, 'x86') == None
| [
"symsynd.heuristics.get_ip_register"
] | [((79, 118), 'symsynd.heuristics.get_ip_register', 'get_ip_register', (["{'pc': '0x42'}", '"""arm7"""'], {}), "({'pc': '0x42'}, 'arm7')\n", (94, 118), False, 'from symsynd.heuristics import get_ip_register\n'), ((147, 174), 'symsynd.heuristics.get_ip_register', 'get_ip_register', (['{}', '"""arm7"""'], {}), "({}, 'arm7... |
#!/usr/bin/env python
# coding: utf-8
"""Demo of different plot API styles: procedural test_widget and OO test_plot
"""
from __future__ import print_function
import logging
import sys
import numpy
from PyQt4 import QtGui
logging.basicConfig()
logger = logging.getLogger(__name__)
app = QtGui.QApplication([])
def ... | [
"logging.basicConfig",
"PyQt4.QtGui.QApplication",
"logging.getLogger",
"plot.PlotWidget.PlotWidget",
"plot.BackendMPL",
"numpy.arange"
] | [((225, 246), 'logging.basicConfig', 'logging.basicConfig', ([], {}), '()\n', (244, 246), False, 'import logging\n'), ((256, 283), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (273, 283), False, 'import logging\n'), ((291, 313), 'PyQt4.QtGui.QApplication', 'QtGui.QApplication', (['[]'],... |
import cv2
import numpy as np
from PIL import Image
from torch.utils.data import Dataset
# imagenet
imagenet_mean = [0.485, 0.456, 0.406]
imagenet_std = [0.229, 0.224, 0.225]
class CustomDataset(Dataset):
def __init__(self, all_img_path_list, transform, ):
self.all_img_paths = all_img_path_list
s... | [
"PIL.Image.fromarray",
"numpy.fromfile"
] | [((625, 645), 'PIL.Image.fromarray', 'Image.fromarray', (['img'], {}), '(img)\n', (640, 645), False, 'from PIL import Image\n'), ((554, 591), 'numpy.fromfile', 'np.fromfile', (['img_path'], {'dtype': 'np.uint8'}), '(img_path, dtype=np.uint8)\n', (565, 591), True, 'import numpy as np\n')] |
import warnings
import pickle
import pandas as pd
import numpy as np
import random
from math import ceil, floor
from copy import deepcopy
from functions import *
warnings.filterwarnings('ignore')
minicolumns = 10
hypercolumns = 15
sequence_length = 2
number_of_sequences = 20
desired_root = 0.9
verbose = True
# Do ... | [
"numpy.random.randint",
"warnings.filterwarnings",
"pandas.read_csv"
] | [((164, 197), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (187, 197), False, 'import warnings\n'), ((503, 527), 'numpy.random.randint', 'np.random.randint', (['(0)', '(20)'], {}), '(0, 20)\n', (520, 527), True, 'import numpy as np\n'), ((729, 785), 'pandas.read_csv', 'p... |
#
# Copyright 2021 Ocean Protocol Foundation
# SPDX-License-Identifier: Apache-2.0
#
import pytest
from ocean_lib.ocean import util
from ocean_lib.ocean.util import (
get_bfactory_address,
get_dtfactory_address,
get_ocean_token_address,
)
def test_get_web3_connection_provider(monkeypatch):
# GANACHE_... | [
"ocean_lib.ocean.util.get_bfactory_address",
"ocean_lib.ocean.util.get_dtfactory_address",
"ocean_lib.ocean.util.get_contracts_addresses",
"pytest.raises",
"ocean_lib.ocean.util.get_web3_connection_provider",
"ocean_lib.ocean.util.get_ocean_token_address"
] | [((339, 390), 'ocean_lib.ocean.util.get_web3_connection_provider', 'util.get_web3_connection_provider', (['util.GANACHE_URL'], {}), '(util.GANACHE_URL)\n', (372, 390), False, 'from ocean_lib.ocean import util\n'), ((500, 551), 'ocean_lib.ocean.util.get_web3_connection_provider', 'util.get_web3_connection_provider', (['... |
import argparse
from glob import glob
import importlib
import hashlib
import logging
import os
from typing import Optional
from pydantic import BaseModel
import re
from sqlalchemy import create_engine, text
import sqlalchemy
from sqlalchemy import exc
from sqlalchemy.exc import InternalError, OperationalError
from sqla... | [
"logging.getLogger",
"logging.StreamHandler",
"re.compile",
"time.sleep",
"sys.exit",
"os.path.exists",
"argparse.ArgumentParser",
"sqlalchemy.create_engine",
"os.path.split",
"os.mkdir",
"os.path.dirname",
"sqlalchemy.text",
"logging.Formatter",
"sqlalchemy.orm.Session",
"os.path.join",... | [((450, 478), 'logging.getLogger', 'logging.getLogger', (['"""MiGreat"""'], {}), "('MiGreat')\n", (467, 478), False, 'import logging\n'), ((514, 537), 'logging.StreamHandler', 'logging.StreamHandler', ([], {}), '()\n', (535, 537), False, 'import logging\n'), ((554, 615), 'logging.Formatter', 'logging.Formatter', (['"""... |
from traitlets.config import Configurable
from traitlets import (
Int,
List,
Unicode,
Bool,
)
class ArgModelPara(Configurable):
# Basic configs.
use_gpu = Bool(help="Whether to use gpu.", default_value=True).tag(config=True)
model_type = Unicode(help="Type of the model.", default_value="")... | [
"traitlets.List",
"traitlets.Int",
"traitlets.Unicode",
"traitlets.Bool"
] | [((181, 233), 'traitlets.Bool', 'Bool', ([], {'help': '"""Whether to use gpu."""', 'default_value': '(True)'}), "(help='Whether to use gpu.', default_value=True)\n", (185, 233), False, 'from traitlets import Int, List, Unicode, Bool\n'), ((268, 320), 'traitlets.Unicode', 'Unicode', ([], {'help': '"""Type of the model."... |
# -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""DTITK utility interfaces
DTI-TK developed by <NAME>, <EMAIL>
For additional help, visit http://dti-tk.sf.net
The high-dimensional tensor-based DTI registration algorithm
<NAME>... | [
"os.path.abspath",
"os.path.basename"
] | [((8997, 9022), 'os.path.abspath', 'os.path.abspath', (['out_file'], {}), '(out_file)\n', (9012, 9022), False, 'import os\n'), ((9176, 9213), 'os.path.basename', 'os.path.basename', (['self.inputs.in_file'], {}), '(self.inputs.in_file)\n', (9192, 9213), False, 'import os\n')] |
import gi
gi.require_version('Gtk', '3.0')
import threading
import time
import I2C_LCD_driver
import random
import table
import servidor
import puzzle1
from gi.repository import GLib, Gtk, Gdk, GObject, GdkPixbuf
class CourseManager_Gtk(Gtk.Window):
def __init__(self):
#Inicialitzem la finestra i posem... | [
"gi.repository.Gtk.Box",
"puzzle1.RfidPn532",
"gi.repository.Gtk.Image",
"gi.repository.Gtk.Grid",
"gi.repository.Gdk.RGBA",
"gi.repository.Gtk.EventBox",
"gi.repository.GdkPixbuf.Pixbuf.new_from_file_at_scale",
"time.sleep",
"gi.require_version",
"gi.repository.Gtk.Window",
"gi.repository.Gtk.L... | [((10, 42), 'gi.require_version', 'gi.require_version', (['"""Gtk"""', '"""3.0"""'], {}), "('Gtk', '3.0')\n", (28, 42), False, 'import gi\n'), ((5427, 5447), 'I2C_LCD_driver.lcd', 'I2C_LCD_driver.lcd', ([], {}), '()\n', (5445, 5447), False, 'import I2C_LCD_driver\n'), ((5476, 5486), 'gi.repository.Gtk.main', 'Gtk.main'... |
import pymysql, json
from model.sql import Connection
class FaultModel():
def create_fault(self, name):
sql = "INSERT INTO `fault` (`name`) VALUES (%s)"
values = (name)
conn = Connection()
conn.create(sql, values)
def get_fault(self):
sql = "SELECT * FROM fault ORDER ... | [
"model.sql.Connection"
] | [((206, 218), 'model.sql.Connection', 'Connection', ([], {}), '()\n', (216, 218), False, 'from model.sql import Connection\n'), ((360, 372), 'model.sql.Connection', 'Connection', ([], {}), '()\n', (370, 372), False, 'from model.sql import Connection\n')] |
'''Define the tasks and code for loading their data.
- As much as possible, following the existing task hierarchy structure.
- When inheriting, be sure to write and call load_data.
- Set all text data as an attribute, task.sentences (List[List[str]])
- Each task's val_metric should be name_metric, where metric is retu... | [
"json.loads",
"allennlp.data.fields.LabelField",
"allennlp.training.metrics.CategoricalAccuracy",
"allennlp.training.metrics.Average",
"allennlp.training.metrics.F1Measure",
"logging.warning",
"os.path.join",
"collections.Counter",
"torch.nonzero",
"itertools.count",
"allennlp.data.token_indexer... | [((3299, 3358), 'allennlp.data.fields.LabelField', 'LabelField', (['idx'], {'label_namespace': '"""idxs"""', 'skip_indexing': '(True)'}), "(idx, label_namespace='idxs', skip_indexing=True)\n", (3309, 3358), False, 'from allennlp.data.fields import TextField, LabelField, SpanField, ListField, MetadataField\n'), ((3405, ... |
import os
import re
from collections import Counter
from polyglotdb.exceptions import (DelimiterError, ILGError, ILGLinesMismatchError,
ILGWordMismatchError)
from polyglotdb.structure import Hierarchy
from ..helper import guess_type, ilg_text_to_lines
from ..discoursedata import Di... | [
"polyglotdb.exceptions.ILGLinesMismatchError",
"polyglotdb.exceptions.ILGWordMismatchError",
"polyglotdb.structure.Hierarchy",
"os.path.split"
] | [((964, 989), 'polyglotdb.structure.Hierarchy', 'Hierarchy', (["{'word': None}"], {}), "({'word': None})\n", (973, 989), False, 'from polyglotdb.structure import Hierarchy\n'), ((1620, 1648), 'polyglotdb.exceptions.ILGLinesMismatchError', 'ILGLinesMismatchError', (['lines'], {}), '(lines)\n', (1641, 1648), False, 'from... |
import requests
from rest_framework.settings import api_settings
from django import forms
from django.conf import settings
from django.urls import NoReverseMatch, reverse
import olympia.core.logger
from olympia import amo
from olympia.shelves.models import Shelf
log = olympia.core.logger.getLogger('z.admin.shelves... | [
"django.forms.ValidationError",
"requests.get",
"django.urls.reverse"
] | [((1755, 1810), 'django.urls.reverse', 'reverse', (['f"""{api_settings.DEFAULT_VERSION}:addon-search"""'], {}), "(f'{api_settings.DEFAULT_VERSION}:addon-search')\n", (1762, 1810), False, 'from django.urls import NoReverseMatch, reverse\n'), ((2474, 2491), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (2486,... |
#!/usr/bin/env python3
# coding: utf-8
# Copyright (c) 2019-2020 Latona. All rights reserved.
from datetime import datetime
from time import sleep
import os
from pathlib import Path
# AION func
from aion.microservice import main_decorator, Options
from aion.kanban import Kanban
from aion.mongo import BaseMongoAccess... | [
"aion.mongo.BaseMongoAccess",
"aion.microservice.main_decorator",
"os.makedirs",
"os.path.join",
"os.environ.get",
"aion.logger.lprint",
"time.sleep",
"datetime.datetime.now"
] | [((599, 644), 'os.environ.get', 'os.environ.get', (['"""AION_HOME"""', '"""/var/lib/aion/"""'], {}), "('AION_HOME', '/var/lib/aion/')\n", (613, 644), False, 'import os\n'), ((3801, 3829), 'aion.microservice.main_decorator', 'main_decorator', (['SERVICE_NAME'], {}), '(SERVICE_NAME)\n', (3815, 3829), False, 'from aion.mi... |
from collections import Counter
a = "kjalfj;ldsjafl;hdsllfdhg;lahfbl;hl;ahlf;h"
res = Counter(a)
print(res)
str = "张三 李四 美国 三国 中国"
res = str.count("国")
print(res)
| [
"collections.Counter"
] | [((90, 100), 'collections.Counter', 'Counter', (['a'], {}), '(a)\n', (97, 100), False, 'from collections import Counter\n')] |
from fish import Fish
WIDTH = 640
HEIGHT = 416
NFISHES = 15 # Anzahl der Fische
FPS = 60
fishes = []
def setup():
global bg
size(WIDTH, HEIGHT)
this.surface.setTitle(u"<NAME>, bonbonbuntes Aquarium")
bg = loadImage("background.png")
for _ in range(NFISHES):
fishes.append(Fish())
fram... | [
"fish.Fish"
] | [((304, 310), 'fish.Fish', 'Fish', ([], {}), '()\n', (308, 310), False, 'from fish import Fish\n')] |
"""Names Datasets from data.austintext.gov .
Sources:
# noqa - https://data.austintexas.gov/Health-and-Community-Services/From-Aadhav-to-Zyva-6-087-Names-of-Babies-Born-in-/rmd7-g4yz #noqa
# noqa - https://data.austintexas.gov/Health-and-Community-Services/Most-Popular-Baby-Names-2008-2017-City-Of-Austin/53bh-5yz... | [
"pandas.concat",
"pandas.read_csv",
"pathlib.Path"
] | [((504, 570), 'pandas.read_csv', 'pd.read_csv', (['"""https://data.austintexas.gov/resource/rmd7-g4yz.csv"""'], {}), "('https://data.austintexas.gov/resource/rmd7-g4yz.csv')\n", (515, 570), True, 'import pandas as pd\n'), ((799, 865), 'pandas.read_csv', 'pd.read_csv', (['"""https://data.austintexas.gov/resource/53bh-5y... |
# -*- coding: utf-8 -*-
"""
author: <NAME> (github Boyne272)
Last updated on Wed Aug 28 08:46:31 2019
"""
import sys
import time as tm
import random
import torch
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
def percent_print(i, i_max, interval=1, length=50):
"""
... | [
"torch.cuda.manual_seed_all",
"torch.manual_seed",
"PIL.Image.open",
"time.clock",
"random.seed",
"numpy.random.seed",
"sys.stdout.flush",
"matplotlib.pyplot.subplots",
"sys.stdout.write"
] | [((1336, 1352), 'PIL.Image.open', 'Image.open', (['path'], {}), '(path)\n', (1346, 1352), False, 'from PIL import Image\n'), ((1586, 1603), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (1597, 1603), False, 'import random\n'), ((1609, 1629), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n',... |
"""Unit test for Notification objects."""
import asyncio
import unittest
from unittest.mock import Mock, patch
from xknx import XKNX
from xknx.devices import Notification
from xknx.dpt import DPTArray, DPTBinary, DPTString
from xknx.exceptions import CouldNotParseTelegram
from xknx.telegram import GroupAddress, Telegr... | [
"xknx.dpt.DPTArray",
"unittest.mock.Mock",
"xknx.XKNX",
"asyncio.new_event_loop",
"xknx.dpt.DPTString",
"xknx.devices.Notification",
"xknx.telegram.GroupAddress",
"xknx.telegram.apci.GroupValueRead",
"xknx.dpt.DPTBinary",
"asyncio.set_event_loop",
"unittest.mock.patch"
] | [((552, 576), 'asyncio.new_event_loop', 'asyncio.new_event_loop', ([], {}), '()\n', (574, 576), False, 'import asyncio\n'), ((585, 618), 'asyncio.set_event_loop', 'asyncio.set_event_loop', (['self.loop'], {}), '(self.loop)\n', (607, 618), False, 'import asyncio\n'), ((843, 849), 'xknx.XKNX', 'XKNX', ([], {}), '()\n', (... |
from Setting import DefineManager
from Utils import LogManager
class CrawlDetailInfo(object):
def __init__(self, webCrawler, crawlUrl):
self.webCrawler = webCrawler
self.crawlUrl = crawlUrl
urlStatus = str(self.webCrawler.SetDriverUrl(crawlUrl))
crawlerStatus = str(self.webCrawler.G... | [
"Utils.LogManager.PrintLogMessage"
] | [((428, 524), 'Utils.LogManager.PrintLogMessage', 'LogManager.PrintLogMessage', (['"""CrawlDetailInfo"""', '"""__init__"""', 'msg', 'DefineManager.LOG_LEVEL_INFO'], {}), "('CrawlDetailInfo', '__init__', msg,\n DefineManager.LOG_LEVEL_INFO)\n", (454, 524), False, 'from Utils import LogManager\n'), ((1207, 1379), 'Uti... |
import os
import urlparse
import redis
from flask_kvsession import KVSessionExtension
from simplekv.memory.redisstore import RedisStore
from flask import Flask, request
from flask_login import LoginManager
import dmapiclient
from dmutils import init_app, init_frontend_app
from dmutils.user import User
from config i... | [
"flask.current_app.jinja_env.get_template",
"flask_login.LoginManager",
"urlparse.urljoin",
"flask.Flask",
"dmutils.init_frontend_app",
"os.environ.get",
"dmutils.init_app",
"dmapiclient.DataAPIClient",
"redis.StrictRedis",
"flask_kvsession.KVSessionExtension"
] | [((396, 423), 'dmapiclient.DataAPIClient', 'dmapiclient.DataAPIClient', ([], {}), '()\n', (421, 423), False, 'import dmapiclient\n'), ((440, 454), 'flask_login.LoginManager', 'LoginManager', ([], {}), '()\n', (452, 454), False, 'from flask_login import LoginManager\n'), ((645, 706), 'os.environ.get', 'os.environ.get', ... |
import torch
import numpy as np
import pandas as pd
import torch.nn as nn
from sklearn.neighbors import KernelDensity
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestRegressor
# Estimate the distribusion of P{A|Y}
def density_estimation(Y, A, Y_test=[]):
bandwidth = np.sq... | [
"torch.nn.ReLU",
"torch.nn.Dropout",
"torch.max",
"torch.from_numpy",
"torch.nn.MSELoss",
"numpy.arange",
"numpy.mean",
"torch.nn.Sigmoid",
"sklearn.ensemble.RandomForestRegressor",
"sklearn.neighbors.KernelDensity",
"numpy.concatenate",
"numpy.abs",
"pandas.get_dummies",
"sklearn.preproce... | [((3896, 3917), 'torch.max', 'torch.max', (['outputs', '(1)'], {}), '(outputs, 1)\n', (3905, 3917), False, 'import torch\n'), ((4057, 4075), 'torch.max', 'torch.max', (['Yhat', '(1)'], {}), '(Yhat, 1)\n', (4066, 4075), False, 'import torch\n'), ((4224, 4246), 'torch.from_numpy', 'torch.from_numpy', (['Yhat'], {}), '(Yh... |
# Generate invoices for discount codes. That is, sponsors that have ordered discount codes,
# that have now either expired or been used fully.
#
from django.core.management.base import BaseCommand
from django.utils import timezone
from django.db import transaction
from django.conf import settings
from datetime import... | [
"postgresqleu.confreg.models.DiscountCode.objects.filter",
"datetime.time",
"postgresqleu.util.time.today_global",
"django.db.models.Count",
"postgresqleu.invoices.util.InvoiceManager",
"django.db.models.F",
"datetime.timedelta",
"django.utils.timezone.now",
"postgresqleu.invoices.util.InvoiceWrappe... | [((821, 832), 'datetime.time', 'time', (['(5)', '(19)'], {}), '(5, 19)\n', (825, 832), False, 'from datetime import timedelta, time\n'), ((1207, 1250), 'django.db.models.Q', 'Q', ([], {'sponsor__isnull': '(False)', 'is_invoiced': '(False)'}), '(sponsor__isnull=False, is_invoiced=False)\n', (1208, 1250), False, 'from dj... |
#
# Copyright 2020–21, by the California Institute of Technology. ALL RIGHTS
# RESERVED. United States Government Sponsorship acknowledged. Any commercial
# use must be negotiated with the Office of Technology Transfer at the
# California Institute of Technology.
#
"""
====================
service_validator.py
===... | [
"pds_doi_service.core.util.config_parser.DOIConfigUtil.get_config"
] | [((709, 735), 'pds_doi_service.core.util.config_parser.DOIConfigUtil.get_config', 'DOIConfigUtil.get_config', ([], {}), '()\n', (733, 735), False, 'from pds_doi_service.core.util.config_parser import DOIConfigUtil\n')] |
# (C) Copyright 2017-2020 UCAR
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
import os
import re
test_string = 'Test :'
# Loop over log files
runfiles = os.listdir()
for runfile in runfiles:
# Check if t... | [
"os.listdir",
"re.search"
] | [((265, 277), 'os.listdir', 'os.listdir', ([], {}), '()\n', (275, 277), False, 'import os\n'), ((554, 582), 're.search', 're.search', (['test_string', 'line'], {}), '(test_string, line)\n', (563, 582), False, 'import re\n')] |
from typing import Optional
import cv2
from pymba import Frame
# todo add more colours
PIXEL_FORMATS_CONVERSIONS = {
'BayerRG8': cv2.COLOR_BAYER_RG2RGB,
}
def display_frame(frame: Frame, delay: Optional[int] = 1) -> None:
"""
Displays the acquired frame.
:param frame: The frame object to display.
... | [
"cv2.waitKey",
"cv2.cvtColor",
"cv2.imshow"
] | [((710, 736), 'cv2.imshow', 'cv2.imshow', (['"""Image"""', 'image'], {}), "('Image', image)\n", (720, 736), False, 'import cv2\n'), ((741, 759), 'cv2.waitKey', 'cv2.waitKey', (['delay'], {}), '(delay)\n', (752, 759), False, 'import cv2\n'), ((584, 650), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'PIXEL_FORMATS_CONVERSI... |
#!/usr/bin/env python
#
# Public Domain 2014-2017 MongoDB, Inc.
# Public Domain 2008-2014 WiredTiger, Inc.
#
# This is free and unencumbered software released into the public domain.
#
# Anyone is free to copy, modify, publish, use, compile, sell, or
# distribute this software, either in source code form or as a compil... | [
"wttest.run"
] | [((5701, 5713), 'wttest.run', 'wttest.run', ([], {}), '()\n', (5711, 5713), False, 'import wiredtiger, wttest, run\n')] |
# -*- coding: utf-8 -*-
#
# OS related library functions
#
import re
import os
import subprocess
import json
def run_command(str_array):
x = subprocess.Popen(str_array, stdout=subprocess.PIPE)
return x.stdout.read()
| [
"subprocess.Popen"
] | [((149, 200), 'subprocess.Popen', 'subprocess.Popen', (['str_array'], {'stdout': 'subprocess.PIPE'}), '(str_array, stdout=subprocess.PIPE)\n', (165, 200), False, 'import subprocess\n')] |
#Written by egbertbouman
#Forked by DrDayoX
from __future__ import print_function
import json
import re
import time
import dateparser
import requests
YOUTUBE_VIDEO_URL = 'https://www.youtube.com/watch?v={youtube_id}'
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chr... | [
"requests.Session",
"time.sleep",
"re.search"
] | [((658, 676), 'requests.Session', 'requests.Session', ([], {}), '()\n', (674, 676), False, 'import requests\n'), ((5641, 5665), 're.search', 're.search', (['pattern', 'text'], {}), '(pattern, text)\n', (5650, 5665), False, 'import re\n'), ((5528, 5545), 'time.sleep', 'time.sleep', (['sleep'], {}), '(sleep)\n', (5538, 5... |
from django.http import HttpResponseRedirect
from django.utils.safestring import mark_safe
from fluent_contents.extensions import ContentPlugin, plugin_pool
from fluent_contents.tests.testapp.models import RawHtmlTestItem, TimeoutTestItem, MediaTestItem, RedirectTestItem
@plugin_pool.register
class RawHtmlTestPlugin(... | [
"django.http.HttpResponseRedirect",
"django.utils.safestring.mark_safe"
] | [((503, 527), 'django.utils.safestring.mark_safe', 'mark_safe', (['instance.html'], {}), '(instance.html)\n', (512, 527), False, 'from django.utils.safestring import mark_safe\n'), ((756, 780), 'django.utils.safestring.mark_safe', 'mark_safe', (['instance.html'], {}), '(instance.html)\n', (765, 780), False, 'from djang... |
import matplotlib.pyplot as plt
import pandas as pd
data = pd.read_csv('all_participants.csv', sep=',', index_col =0)
for k, v in data.items():
if k != "BDI":
data.pop(k)
data.plot.hist(by='BDI', bins=2)
plt.show()
| [
"pandas.read_csv",
"matplotlib.pyplot.show"
] | [((60, 117), 'pandas.read_csv', 'pd.read_csv', (['"""all_participants.csv"""'], {'sep': '""","""', 'index_col': '(0)'}), "('all_participants.csv', sep=',', index_col=0)\n", (71, 117), True, 'import pandas as pd\n'), ((220, 230), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (228, 230), True, 'import matplotli... |
from sonosco.inputs.audio import SonoscoAudioInput
import webrtcvad
import collections
import pyaudio
import sys
import logging
class VadInput(SonoscoAudioInput):
def __init__(self):
super().__init__()
self.FORMAT = pyaudio.paInt16
self.CHANNELS = 1
self.RATE = 16000
self.... | [
"logging.basicConfig",
"logging.getLogger",
"collections.deque",
"webrtcvad.Vad",
"sys.stdout.flush",
"pyaudio.PyAudio",
"sys.stdout.write"
] | [((709, 725), 'webrtcvad.Vad', 'webrtcvad.Vad', (['(2)'], {}), '(2)\n', (722, 725), False, 'import webrtcvad\n'), ((740, 757), 'pyaudio.PyAudio', 'pyaudio.PyAudio', ([], {}), '()\n', (755, 757), False, 'import pyaudio\n'), ((1120, 1141), 'logging.basicConfig', 'logging.basicConfig', ([], {}), '()\n', (1139, 1141), Fals... |
# filename: main_mqtt_oled.py
# WEMOS D1 Mini Board GPIO Map: D8 pull_down, D4 pull_down
# D0=16, D1=5, D2=4, D3=0, D4=2, D5=14, D6=12, D7=13, D8=15
import os, gc, micropython, machine, time, json
# Broker
# https://www.hivemq.com/public-mqtt-broker/
# TOPIC: devices/???/status
GATE_PIN = micropython.const(13) # D7
G... | [
"json.dumps",
"machine.Pin",
"micropython.const",
"ssd1306.SSD1306_I2C",
"gc.collect",
"sensor_manager.PhotoGate",
"mqtt_manager.MQTT_Manager",
"time.sleep_us",
"wlan_manager.WLAN_Manager"
] | [((292, 313), 'micropython.const', 'micropython.const', (['(13)'], {}), '(13)\n', (309, 313), False, 'import os, gc, micropython, machine, time, json\n'), ((331, 351), 'micropython.const', 'micropython.const', (['(0)'], {}), '(0)\n', (348, 351), False, 'import os, gc, micropython, machine, time, json\n'), ((397, 417), ... |
from setuptools import setup
try:
long_description = open("README.rst").read()
except IOError:
long_description = ""
setup(name='DowPy',
version='0.1.5',
description='Module for downloading files over HTTP(s) efficiently',
url='http://github.com/jhnbrunelle/dowpy',
author='JohnBrunel... | [
"setuptools.setup"
] | [((129, 566), 'setuptools.setup', 'setup', ([], {'name': '"""DowPy"""', 'version': '"""0.1.5"""', 'description': '"""Module for downloading files over HTTP(s) efficiently"""', 'url': '"""http://github.com/jhnbrunelle/dowpy"""', 'author': '"""JohnBrunelle"""', 'author_email': '"""<EMAIL>"""', 'license': '"""MIT"""', 'pa... |
from haystack.query import SearchQuerySet
from search.services.suggest import SuggestBase
class SuggestInvestigator(SuggestBase):
@classmethod
def _query(cls, term):
sqs = SearchQuerySet()
raw_results = sqs.filter(investigator_name=term).order_by('-investigator_complaint_count')[:5]
... | [
"haystack.query.SearchQuerySet"
] | [((191, 207), 'haystack.query.SearchQuerySet', 'SearchQuerySet', ([], {}), '()\n', (205, 207), False, 'from haystack.query import SearchQuerySet\n')] |
import behave
@behave.given(u'There are no annotations')
def step_impl(context):
assert True
@behave.when(u'I list all annotations')
def step_impl(context):
context.annotations_list = context.item.annotations.list()
@behave.then(u'I receive a list of all annotations')
def step_impl(context):
assert le... | [
"behave.given",
"behave.then",
"behave.when"
] | [((17, 58), 'behave.given', 'behave.given', (['u"""There are no annotations"""'], {}), "(u'There are no annotations')\n", (29, 58), False, 'import behave\n'), ((102, 140), 'behave.when', 'behave.when', (['u"""I list all annotations"""'], {}), "(u'I list all annotations')\n", (113, 140), False, 'import behave\n'), ((231... |
# ------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# ------------------------------------------------------------------------------
... | [
"logging.getLogger",
"logging.StreamHandler",
"logging.Formatter",
"logging.FileHandler",
"six.iteritems"
] | [((1276, 1302), 'logging.getLogger', 'logging.getLogger', (['"""azure"""'], {}), "('azure')\n", (1293, 1302), False, 'import logging\n'), ((1343, 1371), 'logging.getLogger', 'logging.getLogger', (['"""urllib3"""'], {}), "('urllib3')\n", (1360, 1371), False, 'import logging\n'), ((5826, 5865), 'logging.Formatter', 'logg... |
import pytest
from datetime import datetime
from airflow import DAG
from airflow.models import TaskInstance
from smart_transfer.smart_transfer import SmartTransfer
import os
import psycopg2
PREOPERATOR1 = """
DROP TABLE IF EXISTS test_target;
DROP TABLE IF EXISTS test_source;
CREATE TABLE test_source (
... | [
"smart_transfer.smart_transfer.SmartTransfer.oracle_col_to_type",
"smart_transfer.smart_transfer.SmartTransfer",
"datetime.datetime.now"
] | [((2250, 2315), 'smart_transfer.smart_transfer.SmartTransfer.oracle_col_to_type', 'SmartTransfer.oracle_col_to_type', (["('', cx_Oracle.DB_TYPE_VARCHAR)"], {}), "(('', cx_Oracle.DB_TYPE_VARCHAR))\n", (2282, 2315), False, 'from smart_transfer.smart_transfer import SmartTransfer\n'), ((2371, 2434), 'smart_transfer.smart_... |
"""
Imports meetings in 'caldendar/calendar.yaml' to the Kubeflow Community Calendar
For modifications please refer to the Google Calendar Python API:
https://developers.google.com/resources/api-libraries/documentation/calendar/v3/python/latest/calendar_v3.events.html#insert
Requires the following packages: oauth2clie... | [
"logging.getLogger",
"fire.Fire",
"pathlib.Path.home",
"logging.info",
"logging.error",
"os.path.exists",
"googleapiclient.discovery.build",
"google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file",
"dateutil.parser.parse",
"json.loads",
"google.auth.transport.requests.Request",
"... | [((7713, 7863), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO', 'format': '"""%(levelname)s|%(asctime)s|%(pathname)s|%(lineno)d| %(message)s"""', 'datefmt': '"""%Y-%m-%dT%H:%M:%S"""'}), "(level=logging.INFO, format=\n '%(levelname)s|%(asctime)s|%(pathname)s|%(lineno)d| %(message)s',\n ... |
from napari_plugin_engine import napari_hook_implementation
from typing import List, Tuple, Dict, Any
from imlib.IO.cells import save_cells
from imlib.cells.cells import Cell
from .utils import convert_layer_to_cells
@napari_hook_implementation(specname="napari_get_writer")
def cellfinder_write_multiple_xml(path: s... | [
"imlib.IO.cells.save_cells",
"napari_plugin_engine.napari_hook_implementation"
] | [((222, 278), 'napari_plugin_engine.napari_hook_implementation', 'napari_hook_implementation', ([], {'specname': '"""napari_get_writer"""'}), "(specname='napari_get_writer')\n", (248, 278), False, 'from napari_plugin_engine import napari_hook_implementation\n'), ((1032, 1063), 'imlib.IO.cells.save_cells', 'save_cells',... |
"""
DJANGO_SECURE_SIGNATURE = [
{
'HEADER': 'X-Custom-Header',
'SECRET': 'secret-1',
'SALT': 'salt-1',
'DATA_GENERATOR': lambda request, *args, **kwargs: {'test': 'test'}
'MAX_AGE': timedelta(seconds=60),
},
{
'HEADER': 'X-Signed-Header',
'SECRET':... | [
"django.test.signals.setting_changed.connect"
] | [((878, 916), 'django.test.signals.setting_changed.connect', 'setting_changed.connect', (['drop_settings'], {}), '(drop_settings)\n', (901, 916), False, 'from django.test.signals import setting_changed\n')] |
"""
Tests for the entry point of pypy3-c, app_main.py.
"""
from __future__ import with_statement, print_function
import py
import sys, os, re, runpy, subprocess
import shutil
from rpython.tool.udir import udir
from contextlib import contextmanager
import textwrap
from pypy import pypydir
from pypy.conftest import PYTHO... | [
"re.escape",
"pexpect.spawn",
"os.popen4",
"sys.path.append",
"os.strerror",
"py.test.skip",
"os.unsetenv",
"textwrap.dedent",
"py.test.mark.skipif",
"py.code.Source",
"subprocess.Popen",
"os.putenv",
"os.chmod",
"pexpect.__version__.split",
"rpython.tool.udir.udir.join",
"select.selec... | [((545, 570), 'os.path.abspath', 'os.path.abspath', (['app_main'], {}), '(app_main)\n', (560, 570), False, 'import os\n'), ((46795, 46850), 'py.test.mark.skipif', 'py.test.mark.skipif', (['"""config.getoption("runappdirect")"""'], {}), '(\'config.getoption("runappdirect")\')\n', (46814, 46850), False, 'import py\n'), (... |
import unittest
from textwrap import dedent
from qspectra import utils
class Example(object):
def __init__(self, a=0, b=1, c=None, d=None):
self.a = a
self.b = b
self.c = self if c is None else c
self.d = Example(1, 2, 3, 4) if d is None else d
def __repr__(self):
ret... | [
"qspectra.utils.inspect_repr",
"textwrap.dedent"
] | [((324, 348), 'qspectra.utils.inspect_repr', 'utils.inspect_repr', (['self'], {}), '(self)\n', (342, 348), False, 'from qspectra import utils\n'), ((505, 773), 'textwrap.dedent', 'dedent', (['"""\n Example(\n a=0,\n b=1,\n c=Example(...),\n d=Exampl... |
import itertools
while True:
try:
x,y=input().split()
x,y=list(x),int(y)
try:
p=itertools.permutations(x)
for i in range(y-1): p.__next__()
print("".join(x),y,"=","".join(p.__next__()))
except:
print("".join(x),y,"=","No permutation")
... | [
"itertools.permutations"
] | [((120, 145), 'itertools.permutations', 'itertools.permutations', (['x'], {}), '(x)\n', (142, 145), False, 'import itertools\n')] |
import torch
import torch.nn as nn
import torch.nn.functional as F
from .dla_models import *
class GGCNN3(nn.Module):
def __init__(self, input_channels=1, backend='dla60up'):
super().__init__()
self.features = dlaup_func_dict[backend](16, input_channels=input_channels)
self.pos_... | [
"torch.nn.BatchNorm2d",
"torch.nn.ReLU",
"torch.nn.functional.mse_loss",
"torch.nn.Tanh",
"torch.nn.Conv2d"
] | [((1555, 1582), 'torch.nn.functional.mse_loss', 'F.mse_loss', (['pos_pred', 'y_pos'], {}), '(pos_pred, y_pos)\n', (1565, 1582), True, 'import torch.nn.functional as F\n'), ((1602, 1629), 'torch.nn.functional.mse_loss', 'F.mse_loss', (['cos_pred', 'y_cos'], {}), '(cos_pred, y_cos)\n', (1612, 1629), True, 'import torch.n... |
# External dependencies
from sanic.response import text, json
from sanic.log import logger
from sanic import response as sanic_response
import asyncio
import copy
import time
import subprocess
import socket
import time
from sanic_openapi import doc
import logging
logging.basicConfig(filename='logs.txt',level=logging.W... | [
"logging.basicConfig",
"sanic.response.json",
"sanic.log.logger.error",
"apps.utils.csv_utils.create_permission_csv",
"apps.utils.csv_utils.create_general_csv",
"sanic.log.logger.info",
"apps.utils.dict_utils.nested_append",
"apps.utils.csv_utils.delete_all_csv",
"apps.utils.mongo_utils.save_csv_to_... | [((265, 328), 'logging.basicConfig', 'logging.basicConfig', ([], {'filename': '"""logs.txt"""', 'level': 'logging.WARNING'}), "(filename='logs.txt', level=logging.WARNING)\n", (284, 328), False, 'import logging\n'), ((1506, 1541), 'sanic.log.logger.info', 'logger.info', (['"""AGREEMENT_LIST_QUERY"""'], {}), "('AGREEMEN... |
"""
Color Sensor for the MiniBot.
"""
from minibot.peripherals.TCS34725 import TCS34725 as CSensor
import logging
import math
# Abstract class representing a sensor
class ColorSensor():
"""
Color Sensor class.
"""
def __init__(self, name, pin_number):
"""
Constructor.
Args:
... | [
"minibot.peripherals.TCS34725.TCS34725",
"math.sqrt"
] | [((2359, 2436), 'math.sqrt', 'math.sqrt', (['((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2 + (p1[2] - p2[2]) ** 2)'], {}), '((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2 + (p1[2] - p2[2]) ** 2)\n', (2368, 2436), False, 'import math\n'), ((467, 476), 'minibot.peripherals.TCS34725.TCS34725', 'CSensor', ([], {}), '()\n', (4... |
from django.contrib.auth.models import Group
from django.test import TestCase
from users.models import *
from users.user_enums import UserGroupsEnum
from users.user_service import UserService
class TestService(TestCase):
fixtures = ['user_groups']
def setUp(self):
User.objects.all().delete()
def... | [
"users.user_service.UserService.check_user_permission",
"django.contrib.auth.models.Group.objects.get"
] | [((489, 543), 'django.contrib.auth.models.Group.objects.get', 'Group.objects.get', ([], {'name': 'UserGroupsEnum.MODERATOR.value'}), '(name=UserGroupsEnum.MODERATOR.value)\n', (506, 543), False, 'from django.contrib.auth.models import Group\n'), ((632, 706), 'users.user_service.UserService.check_user_permission', 'User... |
from tempfile import NamedTemporaryFile
import webbrowser
from django.conf import settings
from django.core.mail.backends.base import BaseEmailBackend
class BrowsableEmailBackend(BaseEmailBackend):
"""
An email backend that opens HTML parts of emails sent
in a local web browser, for testing during devel... | [
"webbrowser.open",
"tempfile.NamedTemporaryFile"
] | [((817, 855), 'webbrowser.open', 'webbrowser.open', (["('file://' + temp.name)"], {}), "('file://' + temp.name)\n", (832, 855), False, 'import webbrowser\n'), ((721, 753), 'tempfile.NamedTemporaryFile', 'NamedTemporaryFile', ([], {'delete': '(False)'}), '(delete=False)\n', (739, 753), False, 'from tempfile import Named... |
import os
from datetime import datetime
import json
from shutil import copy
import AppConfig as app_config
from ml_pipeline.settings import APP_ROOT
import ml_pipeline.utils.Helper as helper
import ml_pipeline.utils.Logging as logging
logger = logging.logger
def create_job(job_config_json, user_file, is_example_jo... | [
"os.makedirs",
"os.path.join",
"ml_pipeline.utils.Helper.create_job_config_object",
"datetime.datetime.now",
"shutil.copy",
"json.load",
"json.dump"
] | [((1062, 1096), 'os.path.join', 'os.path.join', (['all_jobs_fld', 'job_id'], {}), '(all_jobs_fld, job_id)\n', (1074, 1096), False, 'import os\n'), ((1101, 1136), 'os.makedirs', 'os.makedirs', (['job_fld'], {'exist_ok': '(True)'}), '(job_fld, exist_ok=True)\n', (1112, 1136), False, 'import os\n'), ((1160, 1213), 'os.pat... |
import os
import utils
import datetime
import pickle as pkl
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import transforms as T
from torch.optim import lr_scheduler
from torchvision import datasets, models, transforms
from engine import train_one_epoch, evaluate
from custom_datase... | [
"torch.optim.SGD",
"pickle.dump",
"os.makedirs",
"transforms.ToTensor",
"torch.optim.lr_scheduler.step",
"os.path.join",
"torch.optim.lr_scheduler.StepLR",
"torchvision.models.detection.faster_rcnn.FastRCNNPredictor",
"transforms.Compose",
"datetime.datetime.now",
"torchvision.models.detection.f... | [((578, 599), 'transforms.Compose', 'T.Compose', (['transforms'], {}), '(transforms)\n', (587, 599), True, 'import transforms as T\n'), ((1035, 1098), 'torchvision.models.detection.fasterrcnn_resnet50_fpn', 'models.detection.fasterrcnn_resnet50_fpn', ([], {'pretrained': 'pretrained'}), '(pretrained=pretrained)\n', (107... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2014 <NAME> <<EMAIL>>
# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html
"""
Run with:
sudo python ./setup.py install
"""
import os
import sys
import warnings
import ez_setup
from setuptools import setup, find_packages, Extensio... | [
"ez_setup.use_setuptools",
"setuptools.find_packages",
"setuptools.Extension",
"os.path.dirname",
"sys.exc_info",
"setuptools.command.build_ext.build_ext.run",
"setuptools.command.build_ext.build_ext.build_extension",
"numpy.get_include",
"warnings.warn",
"setuptools.command.build_ext.build_ext.fi... | [((552, 577), 'ez_setup.use_setuptools', 'ez_setup.use_setuptools', ([], {}), '()\n', (575, 577), False, 'import ez_setup\n'), ((3384, 3409), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (3399, 3409), False, 'import os\n'), ((3457, 3482), 'os.path.dirname', 'os.path.dirname', (['__file__'],... |
import copy
import itertools
import os
import uuid
from typing import Callable, List, Tuple
import numpy as np
import ray
from gym import Env
from gym.spaces import Box
from interact.environments.vector_env import VectorEnv
from interact.experience.episode_batch import EpisodeBatch
from interact.experience.sample_bat... | [
"numpy.clip",
"interact.experience.episode_batch.EpisodeBatch.from_episodes",
"interact.environments.vector_env.VectorEnv",
"os.urandom",
"interact.experience.sample_batch.SampleBatch",
"numpy.asarray",
"copy.copy",
"uuid.uuid4",
"itertools.chain.from_iterable",
"ray.remote"
] | [((1157, 1187), 'interact.environments.vector_env.VectorEnv', 'VectorEnv', (['([env_fn] * num_envs)'], {}), '([env_fn] * num_envs)\n', (1166, 1187), False, 'from interact.environments.vector_env import VectorEnv\n'), ((2307, 2320), 'interact.experience.sample_batch.SampleBatch', 'SampleBatch', ([], {}), '()\n', (2318, ... |
# Solved correctly
# Primality test adapted from the Brilliant.org wiki entry on primality testing, found at https://brilliant.org/wiki/prime-testing/
import random
from snippets import is_prime
def problem_35():
"How many circular primes are there below one million, where [all rotations of the digits are themsel... | [
"snippets.is_prime"
] | [((424, 437), 'snippets.is_prime', 'is_prime', (['num'], {}), '(num)\n', (432, 437), False, 'from snippets import is_prime\n')] |
""" used for packaging this for pypi """
import setuptools
with open("README.md", "r") as fh:
LONG_DESCRIPTION = fh.read()
setuptools.setup(
name="pygoodwe",
version="0.0.15",
author="<NAME>",
author_email="<EMAIL>",
description="Goodwe Python interface",
long_description=LONG_DESCRIPTION... | [
"setuptools.find_packages"
] | [((433, 459), 'setuptools.find_packages', 'setuptools.find_packages', ([], {}), '()\n', (457, 459), False, 'import setuptools\n')] |
import subprocess
import os
os.chdir('./')
ST = 'python '
stand = dict()
conf = dict()
stand = dict()
stand['ds'] = 'cifar10'
stand['bs'] = 128
stand['defense'] = 'adr_pgd'
stand['model'] = 'resnet18'
stand['epsilon'] = 0.031
stand['trades_beta'] = 1.0
stand['lccomw'] = 1.0
stand['lcsmtw'] = 1.0
stand['gbcomw'] =... | [
"os.chdir",
"subprocess.call"
] | [((31, 45), 'os.chdir', 'os.chdir', (['"""./"""'], {}), "('./')\n", (39, 45), False, 'import os\n'), ((881, 927), 'subprocess.call', 'subprocess.call', (['[ST + chST + sub]'], {'shell': '(True)'}), '([ST + chST + sub], shell=True)\n', (896, 927), False, 'import subprocess\n')] |