code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
__author__ = '<NAME>'
import settings
import datetime
import pygal
import webbrowser
from peewee import *
from clients.steamapi import SteamApiClient
from collections import defaultdict, OrderedDict
from datetime import date
from dateutil.relativedelta import relativedelta
db = SqliteDatabase(settings.sqlite_database... | [
"dateutil.relativedelta.relativedelta",
"pygal.HorizontalBar",
"webbrowser.open_new",
"clients.steamapi.SteamApiClient",
"collections.defaultdict",
"datetime.date.today"
] | [((2421, 2513), 'pygal.HorizontalBar', 'pygal.HorizontalBar', ([], {'title': '"""Playtime in minutes over the last 2 weeks by date captured"""'}), "(title=\n 'Playtime in minutes over the last 2 weeks by date captured')\n", (2440, 2513), False, 'import pygal\n'), ((2575, 2592), 'collections.defaultdict', 'defaultdic... |
import shelve
import os
import re
from resource_api.interfaces import Resource as BaseResource, Link as BaseLink, AbstractUriPolicy
from resource_api.schema import StringField, DateTimeField, IntegerField
from resource_api.service import Service
from resource_api.errors import ValidationError
RE_SHA1 = re.compile("^... | [
"resource_api.schema.StringField",
"re.compile",
"resource_api.errors.ValidationError",
"os.urandom",
"resource_api.schema.DateTimeField",
"shelve.open",
"resource_api.schema.IntegerField"
] | [((307, 335), 're.compile', 're.compile', (['"""^[a-f0-9]{40}$"""'], {}), "('^[a-f0-9]{40}$')\n", (317, 335), False, 'import re\n'), ((817, 857), 'shelve.open', 'shelve.open', (['SHELVE_PATH'], {'writeback': '(True)'}), '(SHELVE_PATH, writeback=True)\n', (828, 857), False, 'import shelve\n'), ((4044, 4161), 'resource_a... |
import os
import json
from string import Template
from functools import total_ordering
import argparse
from os import path
def generate(sitedir, siteBaseUrl, codeBaseUrl, logoPath):
versions = loadVersions(sitedir)
print(versions.asList())
generateVersions(sitedir, versions)
generateIndex(sitedir, siteBaseUrl, ver... | [
"string.Template",
"argparse.ArgumentParser",
"os.makedirs",
"os.scandir",
"os.path.dirname",
"json.dump"
] | [((778, 797), 'os.scandir', 'os.scandir', (['sitedir'], {}), '(sitedir)\n', (788, 797), False, 'import os\n'), ((2459, 2506), 'os.makedirs', 'os.makedirs', (["(sitedir + '/badges')"], {'exist_ok': '(True)'}), "(sitedir + '/badges', exist_ok=True)\n", (2470, 2506), False, 'import os\n'), ((2658, 2780), 'string.Template'... |
#!/usr/bin/env python3
import argparse
import matplotlib.pyplot as plt
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
import torch.optim as optim
from torch.utils.tensorboard import SummaryWriter
import numpy as np
from torchdiffeq import... | [
"torch.nn.functional.mse_loss",
"matplotlib.pyplot.Circle",
"os.makedirs",
"argparse.ArgumentParser",
"torch.load",
"os.path.join",
"random.seed",
"torch.set_default_dtype",
"train.BouncingBall",
"matplotlib.pyplot.subplots",
"torch.utils.data.DataLoader",
"torch.no_grad",
"matplotlib.cm.get... | [((886, 914), 'random.seed', 'random.seed', (['(1234)'], {'version': '(2)'}), '(1234, version=2)\n', (897, 914), False, 'import random\n'), ((916, 954), 'torch.set_default_dtype', 'torch.set_default_dtype', (['torch.float64'], {}), '(torch.float64)\n', (939, 954), False, 'import torch\n'), ((1257, 1277), 'torch.load', ... |
import fileinput
import re
import math
match_str = r'^target area: x=(-?[0-9]+)\.\.(-?[0-9]+), y=(-?[0-9]+)\.\.(-?[0-9]+)$'
def reaches_range(vx, vy, x_dests, y_dests):
x,y = 0,0
y_dest_min = min(y_dests)
x_dest_max = max(x_dests)
while y >= y_dest_min and x <= x_dest_max:
x += vx
... | [
"fileinput.input"
] | [((509, 526), 'fileinput.input', 'fileinput.input', ([], {}), '()\n', (524, 526), False, 'import fileinput\n')] |
import torch as th
import torch.linalg as linalg
from tqdm.notebook import tqdm
import matplotlib.pyplot as plt
import time
global device
device = th.device("cuda:0" if th.cuda.is_available() else "cpu")
global zero
class tuner:
def __init__(self):
self.lanbda = None
self.n_iter = None
s... | [
"torch.abs",
"torch.randperm",
"torch.mean",
"torch.eye",
"torch.sign",
"torch.tensor",
"torch.Generator",
"torch.cuda.is_available",
"torch.sum",
"torch.matmul",
"torch.clone",
"tqdm.notebook.tqdm",
"torch.var",
"torch.zeros",
"torch.argmax"
] | [((177, 199), 'torch.cuda.is_available', 'th.cuda.is_available', ([], {}), '()\n', (197, 199), True, 'import torch as th\n'), ((599, 630), 'torch.zeros', 'th.zeros', (['(1)'], {'device': 'self.device'}), '(1, device=self.device)\n', (607, 630), True, 'import torch as th\n'), ((3268, 3317), 'torch.randperm', 'th.randper... |
import iso8601
from typing import List
from ro_py.captcha import UnsolvedCaptcha
from ro_py.bases.baseuser import PartialUser
from ro_py.utilities.pages import Pages, SortOrder
from ro_py.utilities.url import url
endpoint = url("groups")
class WallPost:
"""
Represents a Roblox wall post.
"""
def __in... | [
"ro_py.utilities.url.url",
"iso8601.parse_date",
"ro_py.utilities.pages.Pages",
"ro_py.bases.baseuser.PartialUser",
"ro_py.captcha.UnsolvedCaptcha"
] | [((225, 238), 'ro_py.utilities.url.url', 'url', (['"""groups"""'], {}), "('groups')\n", (228, 238), False, 'from ro_py.utilities.url import url\n'), ((537, 577), 'iso8601.parse_date', 'iso8601.parse_date', (["wall_data['created']"], {}), "(wall_data['created'])\n", (555, 577), False, 'import iso8601\n'), ((601, 641), '... |
# Copyright 2022 The TensorFlow Authors. 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 applica... | [
"official.vision.beta.modeling.decoders.factory.build_decoder",
"official.vision.beta.modeling.backbones.factory.build_backbone",
"official.vision.beta.projects.yolo.modeling.yolo_model.Yolo",
"official.vision.beta.projects.yolo.modeling.heads.yolo_head.YoloHead"
] | [((2751, 3123), 'official.vision.beta.projects.yolo.modeling.heads.yolo_head.YoloHead', 'yolo_head.YoloHead', ([], {'min_level': 'min_level', 'max_level': 'max_level', 'classes': 'model_config.num_classes', 'boxes_per_level': 'model_config.anchor_boxes.anchors_per_scale', 'norm_momentum': 'model_config.norm_activation.... |
import platform
import os
import shutil
sys = platform.system()
def link(origin, link_path):
if sys == "Windows":
shutil.copy(origin, link_path)
else:
os.link(origin, link_path)
| [
"platform.system",
"os.link",
"shutil.copy"
] | [((47, 64), 'platform.system', 'platform.system', ([], {}), '()\n', (62, 64), False, 'import platform\n'), ((128, 158), 'shutil.copy', 'shutil.copy', (['origin', 'link_path'], {}), '(origin, link_path)\n', (139, 158), False, 'import shutil\n'), ((177, 203), 'os.link', 'os.link', (['origin', 'link_path'], {}), '(origin,... |
import unittest
def mytestrunner(tc):
alltests = unittest.TestSuite([unittest.TestLoader().loadTestsFromTestCase(s) for s in tc])
unittest.TextTestRunner(verbosity=2).run(alltests)
| [
"unittest.TextTestRunner",
"unittest.TestLoader"
] | [((139, 175), 'unittest.TextTestRunner', 'unittest.TextTestRunner', ([], {'verbosity': '(2)'}), '(verbosity=2)\n', (162, 175), False, 'import unittest\n'), ((74, 95), 'unittest.TestLoader', 'unittest.TestLoader', ([], {}), '()\n', (93, 95), False, 'import unittest\n')] |
# Imports
from __future__ import print_function
import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Ridge, Lasso, SGDRegressor, ElasticNet, LinearRegression
from sklearn.multioutput import MultiOutputRegressor
from sklearn.metrics import mean_squared_error
import matplot... | [
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.collections.LineCollection",
"sklearn.metrics.mean_squared_error",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.errorbar",
"numpy.concatenate",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.legend",... | [((1539, 1574), 'numpy.concatenate', 'np.concatenate', (['masses_pred'], {'axis': '(0)'}), '(masses_pred, axis=0)\n', (1553, 1574), True, 'import numpy as np\n'), ((1576, 1615), 'numpy.concatenate', 'np.concatenate', (['amplitudes_pred'], {'axis': '(0)'}), '(amplitudes_pred, axis=0)\n', (1590, 1615), True, 'import nump... |
# faça um programa que leia o ano de nascimento de um jovem e informe de acordo sua idade
# se ele ainda vai se alsitar ao serviço militar obrigatorio
# se é a hora de se alistar
# ou se já passou o tempo do alistamento
# caso ele ainda não tenha 18 anos avisar quanto tempo falta para ele se alistar
from datetime impor... | [
"datetime.date.today"
] | [((474, 486), 'datetime.date.today', 'date.today', ([], {}), '()\n', (484, 486), False, 'from datetime import date\n'), ((617, 629), 'datetime.date.today', 'date.today', ([], {}), '()\n', (627, 629), False, 'from datetime import date\n'), ((761, 773), 'datetime.date.today', 'date.today', ([], {}), '()\n', (771, 773), F... |
import os
import sys
import errno
import logging
import pytest
import __main__ as main
scriptdir = os.path.dirname(os.path.realpath(__file__))
os.chdir(scriptdir)
logdir = scriptdir + '/logs'
try:
os.mkdir(logdir)
except (OSError, FileExistsError) as e:
if e.errno != errno.EEXIST:
print(e.errno, err... | [
"logging.basicConfig",
"logging.getLogger",
"os.chdir",
"os.path.realpath",
"os.mkdir",
"os.path.basename"
] | [((146, 165), 'os.chdir', 'os.chdir', (['scriptdir'], {}), '(scriptdir)\n', (154, 165), False, 'import os\n'), ((467, 607), 'logging.basicConfig', 'logging.basicConfig', ([], {'filename': '_logname', 'level': 'logging.DEBUG', 'filemode': '"""w"""', 'format': '"""%(asctime)s - %(levelname)s - %(name)s - %(message)s"""'}... |
import pytest
from waterbutler.providers.figshare.metadata import (FigshareFileMetadata,
FigshareFolderMetadata,
FigshareFileRevisionMetadata)
from tests.providers.figshare.fixtures import (project_article_type_1... | [
"waterbutler.providers.figshare.metadata.FigshareFileRevisionMetadata",
"waterbutler.providers.figshare.metadata.FigshareFolderMetadata",
"waterbutler.providers.figshare.metadata.FigshareFileMetadata"
] | [((599, 653), 'waterbutler.providers.figshare.metadata.FigshareFileMetadata', 'FigshareFileMetadata', (['base_meta', "base_meta['files'][0]"], {}), "(base_meta, base_meta['files'][0])\n", (619, 653), False, 'from waterbutler.providers.figshare.metadata import FigshareFileMetadata, FigshareFolderMetadata, FigshareFileRe... |
#! /usr/bin/python
from __future__ import with_statement
# ignobleepub.pyw, version 3.5
# modified by shani and adapted it for android
__license__ = 'GPL v3'
import sys
import os
class IGNOBLEError(Exception):
pass
def _load_crypto_libcrypto():
from ctypes import CDLL, POINTER, c_void_p, c_char_p, c_int... | [
"ctypes.POINTER",
"ctypes.cdll.LoadLibrary",
"ctypes.create_string_buffer"
] | [((464, 503), 'ctypes.cdll.LoadLibrary', 'ctypes.cdll.LoadLibrary', (['"""libcrypto.so"""'], {}), "('libcrypto.so')\n", (487, 503), False, 'import ctypes\n'), ((540, 557), 'ctypes.POINTER', 'POINTER', (['c_char_p'], {}), '(c_char_p)\n', (547, 557), False, 'from ctypes import CDLL, POINTER, c_void_p, c_char_p, c_int, c_... |
#!/pxrpythonsubst
#
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
... | [
"pxr.Tf.Type.FindByName",
"pxr.Sdf.Path",
"pxr.Sdf.ValueTypeName",
"pxr.UsdQt._bindings._VariantSetsProxy",
"pxr.Usd.Stage.Open",
"pxr.UsdQt._bindings._PrimProxy",
"pxr.UsdQt._bindings._MetadataProxy",
"unittest.main",
"pxr.Usd.TimeCode.Default",
"pxr.Vt.TokenArray"
] | [((9990, 10016), 'unittest.main', 'unittest.main', ([], {'verbosity': '(2)'}), '(verbosity=2)\n', (10003, 10016), False, 'import unittest\n'), ((1890, 1923), 'pxr.UsdQt._bindings._VariantSetsProxy', '_VariantSetsProxy', (['[prim1, prim2]'], {}), '([prim1, prim2])\n', (1907, 1923), False, 'from pxr.UsdQt._bindings impor... |
# Copyright 2020 StrongDM 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 to in writi... | [
"grpc.method_handlers_generic_handler",
"grpc.experimental.unary_unary",
"grpc.unary_unary_rpc_method_handler"
] | [((5870, 5939), 'grpc.method_handlers_generic_handler', 'grpc.method_handlers_generic_handler', (['"""v1.Roles"""', 'rpc_method_handlers'], {}), "('v1.Roles', rpc_method_handlers)\n", (5906, 5939), False, 'import grpc\n'), ((4474, 4667), 'grpc.unary_unary_rpc_method_handler', 'grpc.unary_unary_rpc_method_handler', (['s... |
import time
import math
import datetime
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter, date2num
import numpy as np
import subprocess as sp
import time
import sys
import os
from itertools import groupby
from sklearn.neighbors import KernelDensity
from ... | [
"matplotlib.pyplot.hist",
"math.floor",
"matplotlib.pyplot.ylabel",
"numpy.arange",
"os.listdir",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"sklearn.neighbors.KernelDensity",
"matplotlib.pyplot.close",
"numpy.linspace",
"subprocess.call",
"matplotlib.pyplot.ylim",
"subprocess.che... | [((58, 79), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (72, 79), False, 'import matplotlib\n'), ((369, 425), 'subprocess.check_output', 'sp.check_output', (["['date', '--date', '-1 day', '+%Y%m%d']"], {}), "(['date', '--date', '-1 day', '+%Y%m%d'])\n", (384, 425), True, 'import subprocess as ... |
# -*- coding: utf-8 -*-
"""
Sphinx configuration file for clik-wtforms.
:author: <NAME> <<EMAIL>>
:copyright: Copyright (c) <NAME> and contributors, 2017-2019.
:license: BSD
"""
import os
import sys
root_path = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))
src_path = os.path.join(root_path, 'src')
sys.... | [
"os.path.dirname",
"sys.path.insert",
"os.path.join"
] | [((285, 315), 'os.path.join', 'os.path.join', (['root_path', '"""src"""'], {}), "(root_path, 'src')\n", (297, 315), False, 'import os\n'), ((316, 344), 'sys.path.insert', 'sys.path.insert', (['(0)', 'src_path'], {}), '(0, src_path)\n', (331, 344), False, 'import sys\n'), ((2542, 2577), 'os.path.join', 'os.path.join', (... |
"""
Request Entity Module
"""
# Django
from django.contrib.auth.models import User
# local Django
from app.models import Namespace
from app.models import Endpoint
from app.models import Request
from app.models import Request_Meta
from app.modules.util.helpers import Helpers
class Request_Entity():
GET = "get"
... | [
"app.models.Endpoint.objects.get",
"app.models.Request.objects.get",
"app.models.Namespace.objects.get",
"app.models.Request.objects.filter"
] | [((1319, 1345), 'app.models.Request.objects.get', 'Request.objects.get', ([], {'pk': 'id'}), '(pk=id)\n', (1338, 1345), False, 'from app.models import Request\n'), ((2544, 2578), 'app.models.Request.objects.get', 'Request.objects.get', ([], {'pk': 'request_id'}), '(pk=request_id)\n', (2563, 2578), False, 'from app.mode... |
'''
Copyright 2022 Airbus SAS
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
dis... | [
"sos_trades_core.tools.rw.load_dump_dm_data.DirectLoadDump",
"pathlib.Path",
"sos_trades_core.sos_processes.test.test_disc1_data_connector_dremio.usecase.Study",
"time.sleep",
"sos_trades_core.tools.tree.serializer.DataSerializer",
"os.remove",
"os.path.dirname",
"sos_trades_core.execution_engine.exec... | [((3207, 3233), 'sos_trades_core.execution_engine.execution_engine.ExecutionEngine', 'ExecutionEngine', (['self.name'], {}), '(self.name)\n', (3222, 3233), False, 'from sos_trades_core.execution_engine.execution_engine import ExecutionEngine\n'), ((3541, 3556), 'sos_trades_core.execution_engine.data_connector.mock_conn... |
"""authentik OAuth2 Token Introspection Views"""
from dataclasses import dataclass, field
from django.http import HttpRequest, HttpResponse
from django.views import View
from structlog.stdlib import get_logger
from authentik.providers.oauth2.errors import TokenIntrospectionError
from authentik.providers.oauth2.models... | [
"authentik.providers.oauth2.utils.TokenResponse",
"structlog.stdlib.get_logger",
"authentik.providers.oauth2.models.RefreshToken.objects.get",
"authentik.providers.oauth2.errors.TokenIntrospectionError",
"dataclasses.field",
"authentik.providers.oauth2.utils.authenticate_provider"
] | [((458, 470), 'structlog.stdlib.get_logger', 'get_logger', ([], {}), '()\n', (468, 470), False, 'from structlog.stdlib import get_logger\n'), ((640, 657), 'dataclasses.field', 'field', ([], {'init': '(False)'}), '(init=False)\n', (645, 657), False, 'from dataclasses import dataclass, field\n'), ((1614, 1644), 'authenti... |
"""This module implements the DoWhileLoopPass class."""
from __future__ import annotations
import logging
from typing import Any
from typing import Sequence
from bqskit.compiler.basepass import BasePass
from bqskit.ir.circuit import Circuit
from bqskit.passes.control.predicate import PassPredicate
from bqskit.utils.t... | [
"logging.getLogger",
"bqskit.utils.typing.is_sequence"
] | [((356, 383), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (373, 383), False, 'import logging\n'), ((1430, 1452), 'bqskit.utils.typing.is_sequence', 'is_sequence', (['loop_body'], {}), '(loop_body)\n', (1441, 1452), False, 'from bqskit.utils.typing import is_sequence\n'), ((1922, 1944),... |
import json
import requests
class GooglePatentsAPI():
def __init__(self):
self.__baseQueryUrl = 'https://patents.google.com/xhr/query'
self.resultQuery = ''
self.page = 0
def setQuery(self, query):
proccessedQuery = self.__proccessQuery(query)
self.resultQuery = f'q={... | [
"json.loads",
"requests.get"
] | [((1013, 1061), 'requests.get', 'requests.get', (['self.__baseQueryUrl'], {'params': 'params'}), '(self.__baseQueryUrl, params=params)\n', (1025, 1061), False, 'import requests\n'), ((1085, 1110), 'json.loads', 'json.loads', (['response.text'], {}), '(response.text)\n', (1095, 1110), False, 'import json\n')] |
from flask import Flask
import logging
import os
from logging.handlers import RotatingFileHandler, SMTPHandler
from config import Config
app = Flask(__name__)
app.config.from_object(Config)
if not os.path.exists('logs'):
os.mkdir('logs')
# Normal logging setup
file_handler = RotatingFileHandler('logs/pyted.log',... | [
"os.path.exists",
"setup.dbCheck",
"flask.Flask",
"logging.Formatter",
"logging.handlers.RotatingFileHandler",
"os.mkdir"
] | [((144, 159), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (149, 159), False, 'from flask import Flask\n'), ((283, 352), 'logging.handlers.RotatingFileHandler', 'RotatingFileHandler', (['"""logs/pyted.log"""'], {'maxBytes': '(10240)', 'backupCount': '(10)'}), "('logs/pyted.log', maxBytes=10240, backupCou... |
'''
@Author: JoeyforJoy
@Date: 2022-03-25 19:39:52
@LastEditTime: 2022-04-06 21:34:28
@LastEditors: JoeyforJoy
@Description: Transfer rosbag to synchronized image1 and image2.
@Example: python bag2sync_img2.py ${bag_file} ${img1_topic} ${img2_topic}
'''
import os
from os import system
import argparse
def parse_... | [
"os.system",
"os.path.exists",
"argparse.ArgumentParser"
] | [((341, 406), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Transfer rosbag to images."""'}), "(description='Transfer rosbag to images.')\n", (364, 406), False, 'import argparse\n'), ((1444, 1462), 'os.system', 'system', (['"""roscore&"""'], {}), "('roscore&')\n", (1450, 1462), False, '... |
import time
import pytest
from py_ecc import (
bn128,
optimized_bn128,
bls12_381,
optimized_bls12_381,
)
from py_ecc.fields import (
bls12_381_FQ,
bls12_381_FQ2,
bls12_381_FQ12,
bn128_FQ,
bn128_FQ2,
bn128_FQ12,
optimized_bls12_381_FQ,
optimized_bls12_381_FQ2,
optim... | [
"pytest.fixture",
"pytest.skip",
"pytest.raises"
] | [((490, 569), 'pytest.fixture', 'pytest.fixture', ([], {'params': '[bn128, optimized_bn128, bls12_381, optimized_bls12_381]'}), '(params=[bn128, optimized_bn128, bls12_381, optimized_bls12_381])\n', (504, 569), False, 'import pytest\n'), ((6113, 6126), 'pytest.skip', 'pytest.skip', ([], {}), '()\n', (6124, 6126), False... |
# Generated by Django 4.0.3 on 2022-03-22 15:23
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('bank_account', '0006_transaction_recipient_bank_account'),
]
operations = [
migrations.AddField(
model_name='transaction',
... | [
"django.db.models.BooleanField"
] | [((360, 393), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(True)'}), '(default=True)\n', (379, 393), False, 'from django.db import migrations, models\n')] |
"""Task generation for split resmoke tasks."""
from typing import Any, Dict, List, NamedTuple, Optional, Set
import inject
import structlog
from shrub.v2 import FunctionCall, Task, TaskDependency
from buildscripts.ciconfig.evergreen import EvergreenProjectConfig
from buildscripts.resmokelib.multiversionconstants impo... | [
"structlog.getLogger",
"shrub.v2.FunctionCall",
"buildscripts.task_generation.task_types.models.resmoke_task_model.ResmokeTask",
"inject.autoparams",
"buildscripts.timeouts.timeout.TimeoutEstimate.no_timeouts",
"shrub.v2.TaskDependency",
"buildscripts.task_generation.task_types.multiversion_decorator.Mu... | [((954, 983), 'structlog.getLogger', 'structlog.getLogger', (['__name__'], {}), '(__name__)\n', (973, 983), False, 'import structlog\n'), ((2609, 2628), 'inject.autoparams', 'inject.autoparams', ([], {}), '()\n', (2626, 2628), False, 'import inject\n'), ((3108, 3138), 'buildscripts.task_generation.task_types.multiversi... |
import pandas as pd
import numpy as np
# turn off pink warning boxes
import warnings
warnings.filterwarnings("ignore")
import sklearn
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
#-----------------------------------------------------------------------------
# A... | [
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"pandas.cut",
"pandas.DataFrame",
"sklearn.preprocessing.MinMaxScaler",
"warnings.filterwarnings",
"pandas.to_datetime"
] | [((86, 119), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (109, 119), False, 'import warnings\n'), ((524, 557), 'pandas.read_csv', 'pd.read_csv', (['"""med_center_air.csv"""'], {}), "('med_center_air.csv')\n", (535, 557), True, 'import pandas as pd\n'), ((878, 906), 'pan... |
import unittest
from vodem.api import net_select
class TestNetSelect(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.valid_response = {
'net_select': 'WCDMA_preferred',
}
def test_call(self):
resp = net_select()
self.assertEqual(self.valid_response,... | [
"vodem.api.net_select"
] | [((262, 274), 'vodem.api.net_select', 'net_select', ([], {}), '()\n', (272, 274), False, 'from vodem.api import net_select\n')] |
#!/usr/bin/env python3
from setuptools import setup
with open("README.md", "r") as fh:
long_description = fh.read()
setup(name='jitsi-monitor',
version='0.1',
description='Monitor public Jitsi Meet instances',
long_description=long_description,
long_description_content_type='text/markdo... | [
"setuptools.setup"
] | [((125, 907), 'setuptools.setup', 'setup', ([], {'name': '"""jitsi-monitor"""', 'version': '"""0.1"""', 'description': '"""Monitor public Jitsi Meet instances"""', 'long_description': 'long_description', 'long_description_content_type': '"""text/markdown"""', 'author': '"""<NAME>"""', 'url': '"""https://guardianproject... |
import json
import sys
import numpy
import copy
#extractors = {0: {"precision": 0.5, "recall": 0.5}}
#sources = {0: {"KBT": 0.5, "triples": [[0,0,0], [0,1,None]]}}
#Correct triples have a value of 0, incorrect triples have a value of 1 through 25
#format = {0: {0: [], 1: [], 2: []} }
def generateTriples(quantity):
... | [
"numpy.cbrt",
"numpy.random.default_rng",
"json.dump",
"copy.deepcopy"
] | [((516, 541), 'copy.deepcopy', 'copy.deepcopy', (['allTriples'], {}), '(allTriples)\n', (529, 541), False, 'import copy\n'), ((2898, 2939), 'json.dump', 'json.dump', (['triples', 'triplesFile'], {'indent': '(2)'}), '(triples, triplesFile, indent=2)\n', (2907, 2939), False, 'import json\n'), ((2950, 2991), 'json.dump', ... |
import time
from nubia import command, argument
import pandas as pd
from suzieq.cli.sqcmds.command import SqCommand
from suzieq.sqobjects.interfaces import IfObj
from suzieq.utils import humanize_timestamp
@command("interface", help="Act on Interface data")
class InterfaceCmd(SqCommand):
"""Device interface info... | [
"nubia.argument",
"nubia.command",
"time.time",
"pandas.DataFrame"
] | [((210, 260), 'nubia.command', 'command', (['"""interface"""'], {'help': '"""Act on Interface data"""'}), "('interface', help='Act on Interface data')\n", (217, 260), False, 'from nubia import command, argument\n'), ((1006, 1021), 'nubia.command', 'command', (['"""show"""'], {}), "('show')\n", (1013, 1021), False, 'fro... |
# File containing functions used to plot visualizations
from orbital_mechanics import *
import plotly.graph_objects as go
import streamlit as st
import altair as alt
from poliastro.earth.plotting import GroundtrackPlotter
from poliastro.earth import EarthSatellite
from poliastro.twobody import Orbit
from poliastro.bodi... | [
"streamlit.cache",
"altair.Chart",
"altair.Axis",
"plotly.graph_objects.Scattergeo",
"poliastro.earth.EarthSatellite",
"altair.selection_interval",
"poliastro.util.time_range",
"poliastro.twobody.Orbit.from_classical",
"poliastro.earth.plotting.GroundtrackPlotter",
"altair.Scale"
] | [((1302, 1330), 'streamlit.cache', 'st.cache', ([], {'show_spinner': '(False)'}), '(show_spinner=False)\n', (1310, 1330), True, 'import streamlit as st\n'), ((1475, 1495), 'poliastro.earth.plotting.GroundtrackPlotter', 'GroundtrackPlotter', ([], {}), '()\n', (1493, 1495), False, 'from poliastro.earth.plotting import Gr... |
from pytest_bdd import when, given, then
from jinja2 import Environment, FileSystemLoader
from ebu_tt_live.documents import EBUTT1Document, EBUTT3Document, \
EBUTT3DocumentSequence, EBUTTDDocument
from ebu_tt_live.bindings.converters.ebutt1_ebutt3 import EBUTT1EBUTT3Converter
from ebu_tt_live.documents.converters i... | [
"ebu_tt_live.bindings.converters.timedelta_converter.FixedOffsetSMPTEtoTimedeltaConverter",
"ebu_tt_live.node.denester.DenesterNode",
"pytest_bdd.when",
"pytest_bdd.given",
"ebu_tt_live.bindings._ebuttdt.LimitedClockTimingType",
"pytest.fixture",
"pytest_bdd.then",
"ebu_tt_live.documents.EBUTT3Documen... | [((823, 901), 'ebu_tt_live.node.denester.DenesterNode', 'DenesterNode', ([], {'node_id': '"""denester_node"""', 'sequence_identifier': '"""denestedSequenceT"""'}), "(node_id='denester_node', sequence_identifier='denestedSequenceT')\n", (835, 901), False, 'from ebu_tt_live.node.denester import DenesterNode\n'), ((919, 9... |
# coding: utf-8
import logging
from django.db.models.query import F
from blog.models import Blog
from tasks import app
logger = logging.getLogger(__name__)
@app.task(name="ops.update_art_like")
def update_art_like(pk):
"""
記事の「いいね!」数の更新
"""
Blog.objects.filter(pk=pk).update(like=F("like") + 1)
... | [
"logging.getLogger",
"tasks.app.task",
"blog.models.Blog.objects.filter",
"django.db.models.query.F"
] | [((131, 158), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (148, 158), False, 'import logging\n'), ((162, 198), 'tasks.app.task', 'app.task', ([], {'name': '"""ops.update_art_like"""'}), "(name='ops.update_art_like')\n", (170, 198), False, 'from tasks import app\n'), ((262, 288), 'blog.... |
from django import conf, http, shortcuts, views as dj_views
from django.contrib import messages
from django.contrib.auth import models as auth_models, views as auth_views
from django.core import mail, signing
from . import forms as acc_forms, signer
class UserSigninView(auth_views.LoginView):
template_name = 'ac... | [
"django.shortcuts.render",
"django.core.mail.send_mail",
"django.shortcuts.redirect",
"django.shortcuts.reverse",
"django.contrib.messages.success",
"django.contrib.auth.models.User.objects.get"
] | [((1673, 1732), 'django.shortcuts.render', 'shortcuts.render', (['request', 'self.template_name', 'context_data'], {}), '(request, self.template_name, context_data)\n', (1689, 1732), False, 'from django import conf, http, shortcuts, views as dj_views\n'), ((3519, 3578), 'django.shortcuts.render', 'shortcuts.render', ([... |
# -*- coding: utf-8 -*-
################################################################################
## Form generated from reading UI file 'rules.ui'
##
## Created by: Qt User Interface Compiler version 5.14.2
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
####################... | [
"PySide2.QtCore.QMetaObject.connectSlotsByName",
"PySide2.QtCore.QRect",
"PySide2.QtCore.QCoreApplication.translate"
] | [((1485, 1528), 'PySide2.QtCore.QMetaObject.connectSlotsByName', 'QMetaObject.connectSlotsByName', (['RulesWindow'], {}), '(RulesWindow)\n', (1515, 1528), False, 'from PySide2.QtCore import QCoreApplication, QDate, QDateTime, QMetaObject, QObject, QPoint, QRect, QSize, QTime, QUrl, Qt\n'), ((1188, 1211), 'PySide2.QtCor... |
from datetime import datetime, timedelta
import os
from airflow import DAG
from airflow.operators.dummy_operator import DummyOperator
from airflow.operators import (StageToRedshiftOperator, LoadFactOperator,
LoadDimensionOperator, DataQualityOperator)
from helpers import SqlQueries
# AWS... | [
"airflow.operators.LoadFactOperator",
"datetime.datetime",
"airflow.operators.StageToRedshiftOperator",
"airflow.operators.dummy_operator.DummyOperator",
"airflow.operators.LoadDimensionOperator",
"airflow.DAG",
"datetime.timedelta",
"airflow.operators.DataQualityOperator"
] | [((629, 816), 'airflow.DAG', 'DAG', (['"""udac_example_dag"""'], {'catchup': '(False)', 'default_args': 'default_args', 'description': '"""Load and transform data in Redshift with Airflow"""', 'schedule_interval': '"""0 * * * *"""', 'max_active_runs': '(1)'}), "('udac_example_dag', catchup=False, default_args=default_a... |
import ast
import json
import jsonpickle
from channels.generic.websocket import WebsocketConsumer
from django.apps import apps
from django.conf import settings
from django.template.loader import render_to_string
from django.utils import translation
from . import checksum
from . import crypto
class TemplateGetter(We... | [
"json.loads",
"jsonpickle.loads",
"django.apps.apps.get_model",
"json.dumps",
"django.utils.translation.activate",
"ast.literal_eval",
"django.template.loader.render_to_string"
] | [((467, 494), 'jsonpickle.loads', 'jsonpickle.loads', (['text_data'], {}), '(text_data)\n', (483, 494), False, 'import jsonpickle\n'), ((4604, 4639), 'django.utils.translation.activate', 'translation.activate', (['language_code'], {}), '(language_code)\n', (4624, 4639), False, 'from django.utils import translation\n'),... |
from __future__ import absolute_import
# from celery import shared_task
# from celery.decorators import task
from information.task_module.rescue_crawler import RescueCrawler
from information.task_module.dart_crawler import DartUpdate
from information.models import Rescue, Dart
import os
import time
from datetim... | [
"information.models.Rescue.objects.bulk_create",
"information.task_module.dart_crawler.DartUpdate",
"information.task_module.rescue_crawler.RescueCrawler",
"information.models.Dart",
"os.getcwd",
"information.models.Rescue",
"datetime.datetime.today",
"time.time",
"information.models.Dart.objects.bu... | [((1405, 1444), 'information.models.Rescue.objects.bulk_create', 'Rescue.objects.bulk_create', (['rescue_list'], {}), '(rescue_list)\n', (1431, 1444), False, 'from information.models import Rescue, Dart\n'), ((2403, 2438), 'information.models.Dart.objects.bulk_create', 'Dart.objects.bulk_create', (['dart_list'], {}), '... |
#!/usr/bin/env python
import argparse
import glob
import subprocess
from pathlib import Path
import yaml
def flatten(d, path):
"""
Flatten a dictionary into ('some/path/to/key', value)
>>> flatten({'a': {'b': 2}, 'q': 3}, [])
[('a.b', 2), ('q', 3)]
"""
if isinstance(d, dict):
for k,... | [
"subprocess.check_output",
"argparse.ArgumentParser",
"pathlib.Path",
"pathlib.Path.cwd",
"glob.glob"
] | [((4579, 4680), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Diff yaml configuration files between two points in time."""'}), "(description=\n 'Diff yaml configuration files between two points in time.')\n", (4602, 4680), False, 'import argparse\n'), ((3172, 3265), 'subprocess.check... |
import unittest
from api.images import Images
class TestImages(unittest.TestCase):
def test_images(self):
self.assertEqual(Images.THUMBNAIL_FOLDER, ['images', 'thumbnails'])
self.assertEqual(Images.POSTER_FOLDER, ['images', 'posters'])
def test_thumbnails(self):
import sys
im... | [
"api.images.Images.thumbnail",
"os.path.exists",
"api.images.Images.poster",
"os.path.join",
"models.media.Movie",
"models.containers.MediaLibrary",
"os.sep.join",
"os.path.dirname",
"models.media.Episode",
"unittest.main",
"models.meta.Meta",
"os.remove"
] | [((4741, 4756), 'unittest.main', 'unittest.main', ([], {}), '()\n', (4754, 4756), False, 'import unittest\n'), ((437, 486), 'models.media.Episode', 'Episode', (['"""foobar"""'], {'episode_number': '(1)', 'played': '(False)'}), "('foobar', episode_number=1, played=False)\n", (444, 486), False, 'from models.media import ... |
from enum import IntEnum
from typing import TypeAlias
import msgpack
import toml
import ujson
import yaml
__all__ = [
'Data',
'SchemeType',
'Scheme',
'JSON',
'YAML',
'TOML',
'MsgPack',
]
Data: TypeAlias = int | float | bool | str | None
Data: TypeAlias = Data | list[Data] | dict[str, Data... | [
"yaml.safe_dump",
"ujson.dumps",
"toml.dumps",
"yaml.safe_load",
"toml.loads",
"ujson.loads",
"msgpack.loads",
"msgpack.dumps"
] | [((1139, 1156), 'ujson.loads', 'ujson.loads', (['data'], {}), '(data)\n', (1150, 1156), False, 'import ujson\n'), ((1392, 1412), 'yaml.safe_load', 'yaml.safe_load', (['buff'], {}), '(buff)\n', (1406, 1412), False, 'import yaml\n'), ((1487, 1525), 'yaml.safe_dump', 'yaml.safe_dump', (['data'], {'encoding': '"""utf-8"""'... |
# Add this project to the path
import os; import sys; currDir = os.path.dirname(os.path.realpath("__file__"))
rootDir = os.path.abspath(os.path.join(currDir, '..')); sys.path.insert(1, rootDir)
# Warnings
import warnings
warnings.filterwarnings("ignore")
# My modules
from features.build_features import *
# Public mo... | [
"sklearn.model_selection.GridSearchCV",
"sys.path.insert",
"pandas.read_csv",
"sklearn.metrics.precision_recall_curve",
"os.path.join",
"lightgbm.LGBMClassifier",
"sklearn.metrics.precision_score",
"os.path.realpath",
"sklearn.metrics.recall_score",
"numpy.random.seed",
"warnings.simplefilter",
... | [((166, 193), 'sys.path.insert', 'sys.path.insert', (['(1)', 'rootDir'], {}), '(1, rootDir)\n', (181, 193), False, 'import sys\n'), ((222, 255), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (245, 255), False, 'import warnings\n'), ((897, 905), 'numpy.random.seed', 'seed'... |
# httpServerLogParser.py
#
# Copyright (c) 2016, <NAME>
#
"""
Parser for HTTP server log output, of the form:
192.168.127.12 - - [20/Jan/2003:08:55:36 -0800]
"GET /path/to/page.html HTTP/1.0" 200 4649 "http://www.somedomain.com/020602/page.html"
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"
127.0.0.1 - <EMAIL> ... | [
"mo_parsing.helpers.delimited_list",
"mo_parsing.helpers.dblQuotedString.set_token_name"
] | [((1134, 1176), 'mo_parsing.helpers.delimited_list', 'delimited_list', (['integer', '"""."""'], {'combine': '(True)'}), "(integer, '.', combine=True)\n", (1148, 1176), False, 'from mo_parsing.helpers import delimited_list, dblQuotedString, remove_quotes\n'), ((2257, 2300), 'mo_parsing.helpers.dblQuotedString.set_token_... |
# stdlib
from collections import namedtuple
# Datadog
from checks import AgentCheck
# 3p
import requests
class PowerDNSRecursorCheck(AgentCheck):
# See https://doc.powerdns.com/md/recursor/stats/ for metrics explanation
GAUGE_METRICS = [
'cache-entries',
'concurrent-queries',
]
RATE_... | [
"collections.namedtuple",
"requests.get"
] | [((1673, 1722), 'collections.namedtuple', 'namedtuple', (['"""Config"""', "['host', 'port', 'api_key']"], {}), "('Config', ['host', 'port', 'api_key'])\n", (1683, 1722), False, 'from collections import namedtuple\n'), ((2143, 2177), 'requests.get', 'requests.get', (['url'], {'headers': 'headers'}), '(url, headers=heade... |
# -*- coding: utf-8 -*-
import sys
sys.path.append('../common')
from gen import go, GenerateIndex, Theme
# Все темы в порядке их следования в курсе
for fn in [
Theme('Динамическое программирование', 'Понедельник - 7'),
("Info6.1.0.htm", 3, 4, 0, 4),
Theme('Деревья', 'Вторник - 6'),
("segments_tree.h... | [
"gen.Theme",
"gen.go",
"sys.path.append",
"gen.GenerateIndex"
] | [((36, 64), 'sys.path.append', 'sys.path.append', (['"""../common"""'], {}), "('../common')\n", (51, 64), False, 'import sys\n'), ((747, 805), 'gen.GenerateIndex', 'GenerateIndex', (['"""Сессия 5 - лето: учебно-тематический план"""'], {}), "('Сессия 5 - лето: учебно-тематический план')\n", (760, 805), False, 'from gen ... |
# Copyright (c) 2013 OpenStack Foundation.
# Copyright 2015 Rackspace
#
# 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 ... | [
"neutron.tests.unit.api.test_extensions.setup_extensions_middleware",
"neutron.manager.NeutronManager.get_service_plugins",
"neutron.api.extensions.PluginAwareExtensionManager.get_instance",
"mock.patch",
"datetime.datetime.utcnow",
"neutron.api.v2.attributes.RESOURCE_ATTRIBUTE_MAP.update",
"neutron.db.... | [((4395, 4443), 'six.iteritems', 'six.iteritems', (['attributes.RESOURCE_ATTRIBUTE_MAP'], {}), '(attributes.RESOURCE_ATTRIBUTE_MAP)\n', (4408, 4443), False, 'import six\n'), ((4957, 5010), 'neutron.api.extensions.PluginAwareExtensionManager.get_instance', 'extensions.PluginAwareExtensionManager.get_instance', ([], {}),... |
import ev3dev.ev3 as ev3
from constant import constants
from planet import Direction
import time
class Equipment:
motorA = ev3.LargeMotor("outA") # Erste Motor
motorB = ev3.LargeMotor("outB") # Zweite Motor
colorSensor = ev3.ColorSensor("in1")
touchSensor = ev3.TouchSensor("in3")
usSensor = ev3.... | [
"ev3dev.ev3.ColorSensor",
"ev3dev.ev3.TouchSensor",
"time.sleep",
"ev3dev.ev3.UltrasonicSensor",
"ev3dev.ev3.LargeMotor"
] | [((129, 151), 'ev3dev.ev3.LargeMotor', 'ev3.LargeMotor', (['"""outA"""'], {}), "('outA')\n", (143, 151), True, 'import ev3dev.ev3 as ev3\n'), ((180, 202), 'ev3dev.ev3.LargeMotor', 'ev3.LargeMotor', (['"""outB"""'], {}), "('outB')\n", (194, 202), True, 'import ev3dev.ev3 as ev3\n'), ((237, 259), 'ev3dev.ev3.ColorSensor'... |
import unittest
from parameterized import parameterized
from poc.util.fplutil import Utils
from poc.fplsourcetransformer import FPLSourceTransformer
from tatsu.exceptions import FailedToken
from tatsu.exceptions import FailedParse
from tatsu.exceptions import FailedPattern
import os
"""
Tests of FPL related (parser) e... | [
"poc.fplsourcetransformer.FPLSourceTransformer",
"parameterized.parameterized.expand",
"os.path.join",
"poc.util.fplutil.Utils",
"os.path.isfile",
"os.path.dirname",
"os.path.abspath"
] | [((1179, 1251), 'parameterized.parameterized.expand', 'parameterized.expand', (["['test_syntax_type_var_declarations_in_signature']"], {}), "(['test_syntax_type_var_declarations_in_signature'])\n", (1199, 1251), False, 'from parameterized import parameterized\n'), ((1434, 3914), 'parameterized.parameterized.expand', 'p... |
import re
import itertools
regex = r"<x=(-*\d+),\sy=(-*\d+),\sz=(-*\d+)>"
p = re.compile(regex)
def moon(p_x, p_y, p_z, v_x, v_y, v_z):
return {"pos": {"x": p_x, "y": p_y, "z": p_z}, "vel": {"x": v_x, "y": v_y, "z": v_z}}
a = []
for line in open('day12-2019.txt').read().split('\n'):
x, y, z = p.match(line)... | [
"re.compile"
] | [((79, 96), 're.compile', 're.compile', (['regex'], {}), '(regex)\n', (89, 96), False, 'import re\n')] |
__author__ = '<NAME> (<EMAIL>)'
import json
import time
import resource
import sys
resource.setrlimit(resource.RLIMIT_STACK, (2**29, -1))
sys.setrecursionlimit(10**6)
from oauth2client.tools import argparser
from googleapiclient.errors import HttpError
from youtube_discussion_collector.auth_new import get_authentica... | [
"oauth2client.tools.argparser.add_argument",
"sys.setrecursionlimit",
"youtube_discussion_collector.auth_new.get_authenticated_service",
"youtube_discussion_collector.collect.get_video_metadata",
"youtube_discussion_collector.collect.enrich_all_comment_threads",
"youtube_discussion_collector.collect.get_a... | [((84, 140), 'resource.setrlimit', 'resource.setrlimit', (['resource.RLIMIT_STACK', '(2 ** 29, -1)'], {}), '(resource.RLIMIT_STACK, (2 ** 29, -1))\n', (102, 140), False, 'import resource\n'), ((139, 169), 'sys.setrecursionlimit', 'sys.setrecursionlimit', (['(10 ** 6)'], {}), '(10 ** 6)\n', (160, 169), False, 'import sy... |
"""
The backup interface for the kinetics dataset for a easier way to prepare the dataset
The data structure is:
├── data
│ ├── ${DATASET}
│ │ ├── ${DATASET}_train_list_videos.txt
│ │ ├── ${DATASET}_val_list_videos.txt
│ │ ├── annotations
│ │ ├── videos_train
│ │ ├── videos_val
│ │ │ ├── ab... | [
"os.listdir",
"os.path.join",
"mmaction.tools.data.kinetics.download.main",
"plato.config.Config",
"re.findall",
"logging.info"
] | [((1603, 1655), 'os.path.join', 'os.path.join', (['base_data_path', 'kinetics_anno_dir_name'], {}), '(base_data_path, kinetics_anno_dir_name)\n', (1615, 1655), False, 'import os\n'), ((2079, 2142), 'os.path.join', 'os.path.join', (['self.data_anno_dir_path', 'extracted_anno_file_name'], {}), '(self.data_anno_dir_path, ... |
import datetime
import importlib
import re
from typing import Optional, List
from telegram import Message, Chat, Update, Bot, User
from telegram import ParseMode, InlineKeyboardMarkup, InlineKeyboardButton, ReplyKeyboardMarkup, KeyboardButton
from telegram.error import Unauthorized, BadRequest, TimedOut, NetworkError,... | [
"haruka.modules.connection.connected",
"telegram.ext.CallbackQueryHandler",
"datetime.timedelta",
"haruka.updater.idle",
"datetime.datetime",
"haruka.dispatcher.bot.getChat",
"haruka.updater.start_webhook",
"haruka.LOGGER.info",
"telegram.ext.CommandHandler",
"haruka.dispatcher.add_handler",
"im... | [((1841, 1897), 'importlib.import_module', 'importlib.import_module', (["('haruka.modules.' + module_name)"], {}), "('haruka.modules.' + module_name)\n", (1864, 1897), False, 'import importlib\n'), ((3436, 3550), 'haruka.dispatcher.bot.send_message', 'dispatcher.bot.send_message', ([], {'chat_id': 'chat_id', 'text': 't... |
# coding: utf-8
# # Broadcasting a spectrum - Two spectral Components model
# In[ ]:
from astropy.io import fits
import numpy as np
import scipy as sp
from scipy.interpolate import interp1d
from scipy.stats import chisquare
from PyAstronomy.pyasl import dopplerShift
import matplotlib.pyplot as plt
get_ipython().ma... | [
"matplotlib.pyplot.contourf",
"numpy.arange",
"scipy.stats.chisquare",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.colorbar",
"numpy.asarray",
"scipy.interpolate.interp1d",
"matplotlib.pyplot.close",
"numpy.array",
"astropy.io.fits.getdata",
"numpy.linspace",
"matplotlib.pyplot.figure",
"nu... | [((2235, 2253), 'astropy.io.fits.getdata', 'fits.getdata', (['host'], {}), '(host)\n', (2247, 2253), False, 'from astropy.io import fits\n'), ((2258, 2276), 'astropy.io.fits.getdata', 'fits.getdata', (['comp'], {}), '(comp)\n', (2270, 2276), False, 'from astropy.io import fits\n'), ((2508, 2523), 'numpy.array', 'np.arr... |
import json
import typing
from discord_bot_eternal_dice import handler
from discord_bot_eternal_dice.model.discord_response import ResponseType
from tests.integration.utilities import create_context, make_discord_event
def test_integration_roll_numbers():
# No subcommand or options
response = call_command(co... | [
"tests.integration.utilities.create_context",
"json.loads",
"tests.integration.utilities.make_discord_event"
] | [((1754, 1782), 'json.loads', 'json.loads', (["response['body']"], {}), "(response['body'])\n", (1764, 1782), False, 'import json\n'), ((1545, 1620), 'tests.integration.utilities.make_discord_event', 'make_discord_event', ([], {'command': 'command', 'subcommand': 'subcommand', 'options': 'options'}), '(command=command,... |
# -*- coding: utf-8 -*-
import collections
import json
from TM1py.Objects.Annotation import Annotation
from TM1py.Services.ObjectService import ObjectService
class AnnotationService(ObjectService):
""" Service to handle Object Updates for TM1 CellAnnotations
"""
def __init__(self, rest):
su... | [
"TM1py.Objects.Annotation.Annotation.from_json",
"collections.OrderedDict",
"json.dumps"
] | [((1107, 1132), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (1130, 1132), False, 'import collections\n'), ((2627, 2662), 'TM1py.Objects.Annotation.Annotation.from_json', 'Annotation.from_json', (['response.text'], {}), '(response.text)\n', (2647, 2662), False, 'from TM1py.Objects.Annotation ... |
import unittest
import run as lmpkit
# just some notes on prboom+ compat levels so I can't botch this
#
# test_01 - 3 - Doom Ultimate - Doom 1 - E1L1
# test_02 - 3 - Doom Ultimate - Doom 1 - E1L1
# test_03 - 3 - Doom Ultimate - Doom 1 - E1L1
# test_04 - 17 - PRBoom 6 - Doom 1 - E1L1
# te... | [
"unittest.main",
"run.createDemoLumpFromFile"
] | [((1782, 1797), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1795, 1797), False, 'import unittest\n'), ((583, 638), 'run.createDemoLumpFromFile', 'lmpkit.createDemoLumpFromFile', (['"""test_files/test_01.lmp"""'], {}), "('test_files/test_01.lmp')\n", (612, 638), True, 'import run as lmpkit\n'), ((679, 734), 'ru... |
#!/usr/bin/env python3
"""
This script creates a data file for the 'trips' database table
by processing the CSV file from Capital Bikeshare (CaBi). The
resulting output is suitable for the PostgreSQL COPY command,
which can then be used to populate the database table.
COPY trips (duration, start_time, stop_time,
st... | [
"logging.basicConfig",
"psycopg2.connect",
"logging.debug",
"csv.writer",
"sys.exit"
] | [((466, 544), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.DEBUG', 'format': '"""%(levelname)s - %(message)s"""'}), "(level=logging.DEBUG, format='%(levelname)s - %(message)s')\n", (485, 544), False, 'import logging\n'), ((994, 1030), 'csv.writer', 'csv.writer', (['dataFile'], {'delimiter': '""... |
# Generated by Django 3.2.7 on 2021-09-05 11:15
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('photos', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='location',
... | [
"django.db.migrations.AlterModelOptions",
"django.db.models.CharField",
"django.db.models.ForeignKey"
] | [((256, 379), 'django.db.migrations.AlterModelOptions', 'migrations.AlterModelOptions', ([], {'name': '"""location"""', 'options': "{'verbose_name': 'Location', 'verbose_name_plural': 'Locations'}"}), "(name='location', options={'verbose_name':\n 'Location', 'verbose_name_plural': 'Locations'})\n", (284, 379), False... |
import math
import random
populationNum = 50000
chromoLen = 21 * 2 # 2D X in f1, therefore the chromosome len will be 21*2, 1-21: x1, 22-42: x2
maxX = 100
minX = -100
crossRate=0.7
mutationRate=0.01
def f1(x1, x2):
return x1 * x1 + x2 * x2
def f3(x1,x2):
return x1*x1-10*math.cos(2*math.pi*x1)+10+\
... | [
"math.cos",
"random.random",
"math.pow",
"random.randint"
] | [((2496, 2511), 'random.random', 'random.random', ([], {}), '()\n', (2509, 2511), False, 'import random\n'), ((2690, 2705), 'random.random', 'random.random', ([], {}), '()\n', (2703, 2705), False, 'import random\n'), ((3217, 3232), 'random.random', 'random.random', ([], {}), '()\n', (3230, 3232), False, 'import random\... |
#objective
#read ExportSessionProto and dump as numpy data
#copy the whole structure inside d0ExportSessionProto
import FeatureExport_pb2 as pb
import numpy as np
import math
import glob
import os
import pickle
f=open(r'02Kinect+IMU\comb\mixAbnormal\AL_COMB_ab1_2018-09-27_10-03-34.ExportSessionProto','rb')
reader=pb.... | [
"FeatureExport_pb2.ExportSessionProto"
] | [((317, 340), 'FeatureExport_pb2.ExportSessionProto', 'pb.ExportSessionProto', ([], {}), '()\n', (338, 340), True, 'import FeatureExport_pb2 as pb\n')] |
"""
MOST OF THIS CODE IS NOT USED
ITS COPY/PASTED AND LEFT HERE FOR CONVENIENCE
"""
import os
import sys
# in case our module isn't installed (running from this folder)
thisPath=os.path.abspath('../../../')
print(thisPath)
if not thisPath in sys.path:
sys.path.append(thisPath)
import swhlab
import matplotlib.pyp... | [
"matplotlib.pyplot.grid",
"numpy.convolve",
"matplotlib.pyplot.ylabel",
"sys.path.append",
"matplotlib.pyplot.margins",
"numpy.arange",
"os.listdir",
"numpy.where",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.diff",
"matplotlib.pyplot.axhline",
"matplotlib.pyplot.close",
"... | [((180, 208), 'os.path.abspath', 'os.path.abspath', (['"""../../../"""'], {}), "('../../../')\n", (195, 208), False, 'import os\n'), ((258, 283), 'sys.path.append', 'sys.path.append', (['thisPath'], {}), '(thisPath)\n', (273, 283), False, 'import sys\n'), ((797, 823), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'fi... |
from __future__ import print_function
from rasahub import RasahubPlugin
from flask import Flask, render_template, session, request, redirect, url_for, abort, jsonify
from authlib.client import OAuth2Session
import json
import sys
is_py2 = sys.version[0] == '2'
if is_py2:
import thread as thread
else:
import ... | [
"flask.request.args.get",
"flask.Flask",
"json.dump",
"json.dumps",
"time.strftime",
"flask.url_for",
"flask.redirect",
"oauth2client.client.step1_get_authorize_url",
"oauth2client.client.OAuth2WebServerFlow",
"json.load",
"time.localtime",
"apiclient.discovery.build",
"time.gmtime",
"_thr... | [((656, 671), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (661, 671), False, 'from flask import Flask, render_template, session, request, redirect, url_for, abort, jsonify\n'), ((2944, 2992), 'apiclient.discovery.build', 'build', (['"""calendar"""', '"""v3"""'], {'credentials': 'credentials'}), "('calen... |
import asyncio
import pytest
from aiohttp.test_utils import AioHTTPTestCase, unittest_run_loop
from aiohttp import web
from asynctest import mock as async_mock
from ....core.in_memory import InMemoryProfile
from ....utils.stats import Collector
from ...wire_format import JsonWireFormat
from ..base import OutboundTr... | [
"aiohttp.web.Application",
"aiohttp.web.HTTPOk",
"asynctest.mock.MagicMock",
"aiohttp.web.post",
"pytest.raises",
"asynctest.mock.CoroutineMock"
] | [((740, 752), 'aiohttp.web.HTTPOk', 'web.HTTPOk', ([], {}), '()\n', (750, 752), False, 'from aiohttp import web\n'), ((893, 910), 'aiohttp.web.Application', 'web.Application', ([], {}), '()\n', (908, 910), False, 'from aiohttp import web\n'), ((4544, 4581), 'pytest.raises', 'pytest.raises', (['OutboundTransportError'],... |
from collections import defaultdict, deque
import heapq
#Graph class, it has a set of nodes, a defaultdict of edges, and a dictionary of distances
#This is a bidirectional graph so each relation goes both ways.
class Graph:
def __init__(self):
self.nodes = set()
self.edges = defaultdict(list)
... | [
"collections.deque",
"collections.defaultdict"
] | [((2131, 2138), 'collections.deque', 'deque', ([], {}), '()\n', (2136, 2138), False, 'from collections import defaultdict, deque\n'), ((297, 314), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (308, 314), False, 'from collections import defaultdict, deque\n')] |
import unittest
from unittest import mock
from django.contrib.auth.models import User, Group
from tethys_compute.job_manager import JobManager, JOB_TYPES
from tethys_compute.models.tethys_job import TethysJob
from tethys_compute.models.condor.condor_scheduler import CondorScheduler
from tethys_apps.models import Tethy... | [
"tethys_compute.models.tethys_job.TethysJob",
"unittest.mock.patch.dict",
"unittest.mock.MagicMock",
"tethys_compute.job_manager.JobManager",
"tethys_apps.models.TethysApp",
"tethys_compute.models.condor.condor_scheduler.CondorScheduler",
"unittest.mock.patch",
"django.contrib.auth.models.User.objects... | [((2591, 2641), 'unittest.mock.patch', 'mock.patch', (['"""tethys_compute.job_manager.CondorJob"""'], {}), "('tethys_compute.job_manager.CondorJob')\n", (2601, 2641), False, 'from unittest import mock\n'), ((3992, 4042), 'unittest.mock.patch', 'mock.patch', (['"""tethys_compute.job_manager.TethysJob"""'], {}), "('tethy... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 2 16:15:32 2021
@author: furqanafzal
"""
#%%modules
import os
path='/Users/furqanafzal/Documents/furqan/MountSinai/Research/Code/trakr'
os.chdir(path)
import numpy as np
import matplotlib.pylab as plt
import modules
import importlib
importlib.reloa... | [
"pickle.dump",
"modules.cross_val_metrics_naiveB",
"modules.add_noise",
"os.chdir",
"numpy.linspace",
"importlib.reload",
"numpy.load"
] | [((208, 222), 'os.chdir', 'os.chdir', (['path'], {}), '(path)\n', (216, 222), False, 'import os\n'), ((305, 330), 'importlib.reload', 'importlib.reload', (['modules'], {}), '(modules)\n', (321, 330), False, 'import importlib\n'), ((661, 675), 'os.chdir', 'os.chdir', (['path'], {}), '(path)\n', (669, 675), False, 'impor... |
import matplotlib
from matplotlib import pyplot as plt
import tensorflow as tf
# tf.enable_eager_execution()
import tensorflow_probability as tfp
import numpy as np
def session_options(enable_gpu_ram_resizing=True):
"""Convenience function which sets common `tf.Session` options."""
config = tf.ConfigProto()
... | [
"tensorflow.InteractiveSession",
"tensorflow.reset_default_graph",
"tensorflow.get_variable",
"tensorflow.Session",
"tensorflow.global_variables_initializer",
"tensorflow_probability.mcmc.make_simple_step_size_update_policy",
"tensorflow.ConfigProto"
] | [((1105, 1195), 'tensorflow.get_variable', 'tf.get_variable', ([], {'name': '"""step_size"""', 'initializer': '(1.0)', 'use_resource': '(True)', 'trainable': '(False)'}), "(name='step_size', initializer=1.0, use_resource=True,\n trainable=False)\n", (1120, 1195), True, 'import tensorflow as tf\n'), ((1711, 1744), 't... |
# -*- coding: utf-8 -*-
# (c) Copyright IBM Corp. 2010, 2020. All Rights Reserved.
# pragma pylint: disable=unused-argument, no-self-use
""" Test AWS GuardDuty poller. """
from __future__ import print_function
import pytest
from mock import patch, MagicMock
from resilient_circuits.util import get_function_definition
f... | [
"mock.patch"
] | [((1157, 1283), 'mock.patch', 'patch', (['"""fn_aws_guardduty.components.func_aws_guardduty_poller.ResilientComponent.rest_client"""'], {'side_effect': 'MagicMock'}), "(\n 'fn_aws_guardduty.components.func_aws_guardduty_poller.ResilientComponent.rest_client'\n , side_effect=MagicMock)\n", (1162, 1283), False, 'fr... |
# Generated by Django 3.1.8 on 2021-05-02 11:09
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
("cms", "0022_auto_20180620_1551"),
]
operations = [
migrations.CreateModel(
... | [
"django.db.models.OneToOneField",
"django.db.models.CharField",
"django.db.models.BooleanField"
] | [((445, 670), 'django.db.models.OneToOneField', 'models.OneToOneField', ([], {'auto_created': '(True)', 'on_delete': 'django.db.models.deletion.CASCADE', 'parent_link': '(True)', 'primary_key': '(True)', 'related_name': '"""cms_automations_automationhookplugin"""', 'serialize': '(False)', 'to': '"""cms.cmsplugin"""'}),... |
import threading
import os
from selenium import webdriver
from selenium.webdriver import ChromeOptions
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from datetime import datetime
from playsound import ... | [
"selenium.webdriver.ChromeOptions",
"selenium.webdriver.support.ui.WebDriverWait",
"selenium.webdriver.Chrome",
"playsound.playsound",
"time.sleep",
"os.chdir",
"datetime.datetime.now",
"threading.Thread",
"os.system",
"random.randint",
"selenium.webdriver.support.expected_conditions.element_to_... | [((7898, 7935), 'threading.Thread', 'threading.Thread', ([], {'target': 'os_mitmproxy'}), '(target=os_mitmproxy)\n', (7914, 7935), False, 'import threading\n'), ((7949, 7986), 'threading.Thread', 'threading.Thread', ([], {'target': 'main_program'}), '(target=main_program)\n', (7965, 7986), False, 'import threading\n'),... |
from lenstronomy.LensModel.lens_model import LensModel
from lenstronomy.LightModel.light_model import LightModel
from lenstronomy.PointSource.point_source import PointSource
class ModelAPI(object):
"""
This class manages the model choices. The role is to return instances of the lenstronomy LightModel, LensMod... | [
"lenstronomy.PointSource.point_source.PointSource",
"lenstronomy.LightModel.light_model.LightModel",
"lenstronomy.LensModel.lens_model.LensModel"
] | [((1989, 2151), 'lenstronomy.LensModel.lens_model.LensModel', 'LensModel', ([], {'lens_model_list': 'lens_model_list', 'z_source': 'z_source', 'z_lens': 'z_lens', 'lens_redshift_list': 'lens_redshift_list', 'multi_plane': 'multi_plane', 'cosmo': 'cosmo'}), '(lens_model_list=lens_model_list, z_source=z_source, z_lens=z_... |
"""A utility class to summarize all results in a directory.
"""
__author__ = '<NAME>'
from dataclasses import dataclass, field
from pathlib import Path
import logging
import pandas as pd
from zensols.util.time import time
from zensols.deeplearn import DatasetSplitType
from . import (
ModelResult, DatasetResult, M... | [
"logging.getLogger",
"zensols.util.time.time",
"dataclasses.field",
"pandas.DataFrame"
] | [((400, 427), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (417, 427), False, 'import logging\n'), ((995, 1002), 'dataclasses.field', 'field', ([], {}), '()\n', (1000, 1002), False, 'from dataclasses import dataclass, field\n'), ((1162, 1181), 'dataclasses.field', 'field', ([], {'defaul... |
import wx
from ogreyEntity import *
from FoldPanelBar import *
from ogreyScriptEditor import *
import ogre.renderer.OGRE as ogre
class ogreyLevelAttributesPanel(wx.Panel):
def __init__(self, parent, window, resourceInformation, middle):
wx.Panel.__init__(self, parent, -1, style = wx.FULL_REPAINT_ON_RESIZE... | [
"wx.Button",
"wx.Colour",
"wx.BitmapButton",
"wx.CheckBox",
"wx.TextCtrl",
"wx.Slider",
"wx.StaticText",
"wx.ColourDialog",
"wx.TextAttr",
"wx.Panel",
"wx.Panel.__init__"
] | [((251, 319), 'wx.Panel.__init__', 'wx.Panel.__init__', (['self', 'parent', '(-1)'], {'style': 'wx.FULL_REPAINT_ON_RESIZE'}), '(self, parent, -1, style=wx.FULL_REPAINT_ON_RESIZE)\n', (268, 319), False, 'import wx\n'), ((2740, 2790), 'wx.Panel', 'wx.Panel', (['pan', '(-1)'], {'style': 'wx.FULL_REPAINT_ON_RESIZE'}), '(pa... |
from wbdbgbus import DebugBus
import time
from tqdm import tqdm
DBG_PORT = "/dev/tty.usbserial-120001"
DBG_BAUD = 115200
MOSI = 0x00
CLK = 0x08
DC = 0x0C
RST = 0x10
CS = 0x14
GPIO_BASE = 0x8100_0000
SPI_CFG_REG = 0x8000_3000
SPI_REG = 0x8000_3004
DRAW = True
with DebugBus(DBG_PORT, DBG_BAUD, fifo_size=1... | [
"wbdbgbus.DebugBus",
"time.sleep"
] | [((280, 332), 'wbdbgbus.DebugBus', 'DebugBus', (['DBG_PORT', 'DBG_BAUD'], {'fifo_size': '(1)', 'timeout': '(0)'}), '(DBG_PORT, DBG_BAUD, fifo_size=1, timeout=0)\n', (288, 332), False, 'from wbdbgbus import DebugBus\n'), ((753, 768), 'time.sleep', 'time.sleep', (['(0.1)'], {}), '(0.1)\n', (763, 768), False, 'import time... |
import math
import os
import random
import time
from pathlib import Path
import json
from mt import DATASETS_PATH, DATASET_EVAL_NAME, DATASET_SUMMARY_NAME
from mt import helpers, utils
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
def get_metrics(datapath, sr... | [
"seaborn.set",
"mt.utils.get_dataset_ids",
"pathlib.Path",
"os.path.join",
"seaborn.lineplot",
"json.load",
"matplotlib.pyplot.tight_layout",
"pandas.DataFrame",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.show"
] | [((280, 289), 'seaborn.set', 'sns.set', ([], {}), '()\n', (287, 289), True, 'import seaborn as sns\n'), ((2222, 2240), 'pandas.DataFrame', 'pd.DataFrame', (['rows'], {}), '(rows)\n', (2234, 2240), True, 'import pandas as pd\n'), ((2249, 2317), 'seaborn.lineplot', 'sns.lineplot', ([], {'data': 'df_new', 'x': '"""vocab_s... |
from tkinter import N
import os
import numpy as np
from .main import DataLoader
from .timeseriesDLs import GridDataGenPyTorch
class TimeSeriesDataLoader(DataLoader):
def __init__(
self,
path: str,
file_ext: str,
recursive: bool,
iw_params: dict,
ow_params=None,
... | [
"os.listdir",
"numpy.arange"
] | [((512, 528), 'os.listdir', 'os.listdir', (['path'], {}), '(path)\n', (522, 528), False, 'import os\n'), ((1580, 1602), 'numpy.arange', 'np.arange', (['window_size'], {}), '(window_size)\n', (1589, 1602), True, 'import numpy as np\n'), ((1639, 1717), 'numpy.arange', 'np.arange', (['((n_rows - window_size - leave_last -... |
import sys
import eval_model as E
import model as M
"""
Script to retrain the model
Args:
Train dataset name ('nih', 'chexpert' or 'mimic')
"""
DATASET_NAMES = ('nih', 'chexpert', 'mimic')
if len(sys.argv) != 2:
raise Exception('One argument expected (dataset name)')
DATASET_NAME = sys.argv[1]
if DATASET_NAM... | [
"model.train_cnn"
] | [((545, 633), 'model.train_cnn', 'M.train_cnn', (['PATH_TO_IMAGES', 'LEARNING_RATE', 'WEIGHT_DECAY'], {'DATASET_NAME': 'DATASET_NAME'}), '(PATH_TO_IMAGES, LEARNING_RATE, WEIGHT_DECAY, DATASET_NAME=\n DATASET_NAME)\n', (556, 633), True, 'import model as M\n')] |
##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
## ICA model for TE data
## %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#%% import required packages
import numpy as np
from sklearn.preprocessing import StandardScaler
from ... | [
"numpy.hstack",
"matplotlib.pyplot.ylabel",
"numpy.column_stack",
"numpy.argsort",
"numpy.cumsum",
"numpy.linalg.norm",
"sklearn.decomposition.FastICA",
"sklearn.decomposition.PCA",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.axhline",
"numpy.dot",
"numpy.argmax"... | [((669, 692), 'numpy.hstack', 'np.hstack', (['(xmeas, xmv)'], {}), '((xmeas, xmv))\n', (678, 692), True, 'import numpy as np\n'), ((730, 746), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (744, 746), False, 'from sklearn.preprocessing import StandardScaler\n'), ((1137, 1166), 'numpy.cumsu... |
import numpy as np
import cv2
import matplotlib.image as mpimg
from skimage.feature import hog
def bin_spatial(img, size=(32, 32)):
color1 = cv2.resize(img[:,:,0], size).ravel()
color2 = cv2.resize(img[:,:,1], size).ravel()
color3 = cv2.resize(img[:,:,2], size).ravel()
return np.hstack((color1, color... | [
"numpy.copy",
"numpy.histogram",
"cv2.resize",
"numpy.hstack",
"matplotlib.image.imread",
"numpy.concatenate",
"cv2.cvtColor",
"numpy.ravel",
"skimage.feature.hog"
] | [((296, 331), 'numpy.hstack', 'np.hstack', (['(color1, color2, color3)'], {}), '((color1, color2, color3))\n', (305, 331), True, 'import numpy as np\n'), ((490, 546), 'numpy.histogram', 'np.histogram', (['img[:, :, 0]'], {'bins': 'nbins', 'range': 'bins_range'}), '(img[:, :, 0], bins=nbins, range=bins_range)\n', (502, ... |
import unittest
import sys
from pathlib import Path
TEST_DIR = str(Path(__file__).parent.resolve())
BASE_DIR = str(Path(__file__).parent.parent.resolve())
sys.path.append(BASE_DIR)
# Run tests without using GPU
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
from core.sensible_span_extractor import SensibleSpanEx... | [
"pathlib.Path",
"core.sensible_span_extractor.SensibleSpanExtractor",
"core.sensible_span_extractor.SubsequenceExtractor",
"unittest.main",
"sys.path.append"
] | [((155, 180), 'sys.path.append', 'sys.path.append', (['BASE_DIR'], {}), '(BASE_DIR)\n', (170, 180), False, 'import sys\n'), ((1506, 1521), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1519, 1521), False, 'import unittest\n'), ((442, 465), 'core.sensible_span_extractor.SensibleSpanExtractor', 'SensibleSpanExtrac... |
import cv2
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
from PIL import Image
from numpy.random import random
from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split
from keras.models import Sequential
from keras.layers import Dense, Flatten... | [
"keras.layers.Conv2D",
"pandas.read_csv",
"matplotlib.pyplot.ylabel",
"numpy.array",
"keras.layers.Dense",
"keras.layers.Cropping2D",
"numpy.random.random",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.close",
"matplotlib.pyplot.savefig",
"keras.layers.Flatten",
"... | [((2615, 2650), 'numpy.array', 'np.array', (['augmented_images'], {'ndmin': '(4)'}), '(augmented_images, ndmin=4)\n', (2623, 2650), True, 'import numpy as np\n'), ((2654, 2686), 'numpy.array', 'np.array', (['augmented_measurements'], {}), '(augmented_measurements)\n', (2662, 2686), True, 'import numpy as np\n'), ((3618... |
def coding_problem_16(length):
"""
You run a sneaker website and want to record the last N order ids in a log. Implement a data structure to
accomplish this, with the following API:
record(order_id): adds the order_id to the log
get_last(i): gets the ith last element from the log. i is guar... | [
"doctest.testmod"
] | [((8068, 8097), 'doctest.testmod', 'doctest.testmod', ([], {'verbose': '(True)'}), '(verbose=True)\n', (8083, 8097), False, 'import doctest\n')] |
import os
import time
import os.path
import logging
from piecrust.chefutil import format_timed
logger = logging.getLogger(__name__)
STATE_UNKNOWN = 0
STATE_DIRTY = 1
STATE_CLEAN = 2
FORCE_BUILD = object()
class ProcessingTreeError(Exception):
pass
class ProcessorNotFoundError(ProcessingTreeError):
pas... | [
"logging.getLogger",
"os.makedirs",
"os.path.join",
"time.perf_counter",
"os.path.split",
"os.path.isfile",
"os.path.dirname",
"os.path.isdir",
"os.path.getmtime",
"piecrust.chefutil.format_timed"
] | [((106, 133), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (123, 133), False, 'import logging\n'), ((5166, 5192), 'os.path.dirname', 'os.path.dirname', (['node.path'], {}), '(node.path)\n', (5181, 5192), False, 'import os\n'), ((5211, 5250), 'os.path.join', 'os.path.join', (['base_out_d... |
"""
This module contains functions that operate on Argo filenames.
These filenames follow specific conventions that can be hard
to remember. This is built-in to the interactive module. The
``path`` argument for all functions in this module can be a string
file path, an iterable of file paths, a ``pandas.Series`` or
a `... | [
"warnings.simplefilter",
"warnings.catch_warnings",
"pandas.DataFrame",
"re.compile"
] | [((781, 840), 're.compile', 're.compile', (['"""(B|S)?(R|D)([0-9]+)_([0-9]+)(D)?(_aux)?\\\\.nc$"""'], {}), "('(B|S)?(R|D)([0-9]+)_([0-9]+)(D)?(_aux)?\\\\.nc$')\n", (791, 840), False, 'import re\n'), ((975, 1005), 're.compile', 're.compile', (['"""[0-9]{3,4}D\\\\.nc"""'], {}), "('[0-9]{3,4}D\\\\.nc')\n", (985, 1005), Fa... |
import re, time
############ Functions ############
# Set player list from text file
def get_players():
file_name = input("Your .txt file name: ")
if ".txt" in file_name:
pass
else:
file_name+=".txt"
params = []
min_avg_min = int(input("Minimum average minutes to include: "))
... | [
"re.split"
] | [((575, 597), 're.split', 're.split', (['"""\\\\t+"""', 'unit'], {}), "('\\\\t+', unit)\n", (583, 597), False, 'import re, time\n')] |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('fluent_contents', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='YandexMapItem',
fi... | [
"django.db.models.PositiveIntegerField",
"django.db.models.OneToOneField",
"django.db.models.CharField"
] | [((363, 493), 'django.db.models.OneToOneField', 'models.OneToOneField', ([], {'parent_link': '(True)', 'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'to': '"""fluent_contents.ContentItem"""'}), "(parent_link=True, auto_created=True, primary_key=True,\n serialize=False, to='fluent_content... |
# -*- coding: utf-8 -*-
#
# Copyright 2018-2020 - Swiss Data Science Center (SDSC)
# A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and
# Eidgenössische Technische Hochschule Zürich (ETHZ).
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in c... | [
"renku.core.models.workflow.parameters.MappedIOStream",
"attr.s",
"renku.core.models.calamus.fields.Id",
"renku.core.models.workflow.parameters.CommandOutput.generate_id",
"pathlib.Path",
"renku.core.models.calamus.fields.String",
"os.path.join",
"os.environ.get",
"uuid.uuid4",
"bisect.bisect",
... | [((5295, 5312), 'attr.s', 'attr.s', ([], {'cmp': '(False)'}), '(cmp=False)\n', (5301, 5312), False, 'import attr\n'), ((13428, 13445), 'attr.s', 'attr.s', ([], {'cmp': '(False)'}), '(cmp=False)\n', (13434, 13445), False, 'import attr\n'), ((2159, 2213), 'renku.core.models.workflow.parameters.CommandArgument.generate_id... |
from django.urls import path, include
from rest_framework import routers
from . import views
router = routers.SimpleRouter()
router.register('signup',views.UserAccountsViewSet)
urlpatterns = [
path('',include(router.urls)),
path('login/',views.UserLoginApiView.as_view()),
] | [
"rest_framework.routers.SimpleRouter",
"django.urls.include"
] | [((105, 127), 'rest_framework.routers.SimpleRouter', 'routers.SimpleRouter', ([], {}), '()\n', (125, 127), False, 'from rest_framework import routers\n'), ((210, 230), 'django.urls.include', 'include', (['router.urls'], {}), '(router.urls)\n', (217, 230), False, 'from django.urls import path, include\n')] |
import torch
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def flat_grad(grads):
grad_flatten = []
for grad in grads:
grad_flatten.append(grad.view(-1))
grad_flatten = torch.cat(grad_flatten)
return grad_flatten
def flat_hessian(hessians):
hessians_flatten = []
... | [
"torch.cuda.is_available",
"torch.log",
"torch.cat",
"torch.dot"
] | [((214, 237), 'torch.cat', 'torch.cat', (['grad_flatten'], {}), '(grad_flatten)\n', (223, 237), False, 'import torch\n'), ((2045, 2060), 'torch.dot', 'torch.dot', (['r', 'r'], {}), '(r, r)\n', (2054, 2060), False, 'import torch\n'), ((46, 71), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (69,... |
from __future__ import absolute_import, print_function
from torch.autograd import Variable
from ImageFolder_new import *
from utils import *
from sklearn.metrics.pairwise import euclidean_distances
import torchvision.transforms as transforms
import torch.nn as nn
class Generator(nn.Module):
def __init__(self):
... | [
"torchvision.transforms.CenterCrop",
"torch.nn.ReLU",
"torch.nn.LeakyReLU",
"torch.nn.Sequential",
"torchvision.transforms.RandomHorizontalFlip",
"torchvision.transforms.RandomCrop",
"torch.nn.Linear",
"torchvision.transforms.Normalize",
"torchvision.transforms.Resize",
"torchvision.transforms.ToT... | [((627, 650), 'torch.nn.Sequential', 'nn.Sequential', (['*modules'], {}), '(*modules)\n', (640, 650), True, 'import torch.nn as nn\n'), ((853, 872), 'torch.nn.Linear', 'nn.Linear', (['(512)', '(128)'], {}), '(512, 128)\n', (862, 872), True, 'import torch.nn as nn\n'), ((892, 909), 'torch.nn.Linear', 'nn.Linear', (['(12... |
import sys
from bs4 import BeautifulSoup
import numpy as np
from matplotlib import pyplot as plt
import cv2
import os
folder_name = sys.argv[1]
file_name = sys.argv[2]
original_img = cv2.imread(os.path.join("../../Images/"+str(folder_name),file_name))
original_prediction = cv2.imread(os.path.join('../../Images/origi... | [
"cv2.addWeighted",
"cv2.resize",
"os.path.join"
] | [((364, 464), 'cv2.resize', 'cv2.resize', (['original_img', '(original_prediction.shape[:-1][1], original_prediction.shape[:-1][0])'], {}), '(original_img, (original_prediction.shape[:-1][1],\n original_prediction.shape[:-1][0]))\n', (374, 464), False, 'import cv2\n'), ((474, 537), 'cv2.addWeighted', 'cv2.addWeighte... |
# Example using PIO to wait for a pin change and raise an IRQ.
#
# Demonstrates:
# - PIO wrapping
# - PIO wait instruction, waiting on an input pin
# - PIO irq instruction, in blocking mode with relative IRQ number
# - setting the in_base pin for a StateMachine
# - setting an irq handler for a StateMachine
# ... | [
"rp2.StateMachine",
"rp2.asm_pio",
"time.ticks_ms",
"machine.Pin"
] | [((448, 461), 'rp2.asm_pio', 'rp2.asm_pio', ([], {}), '()\n', (459, 461), False, 'import rp2\n'), ((770, 798), 'machine.Pin', 'Pin', (['(16)', 'Pin.IN', 'Pin.PULL_UP'], {}), '(16, Pin.IN, Pin.PULL_UP)\n', (773, 798), False, 'from machine import Pin\n'), ((805, 853), 'rp2.StateMachine', 'rp2.StateMachine', (['(0)', 'wai... |
from celery import Celery
'''
' 配置文件
'''
cel = Celery('celery_demo', # 名称
broker='redis://localhost:6379/1', # 中间件
backend='redis://localhost:6379/2', # 结果存储
# 包含以下两个任务文件,去相应的py文件中找任务,对多个任务做分类
include=['tasks_demo.task1',
'tasks_demo.task2']
... | [
"celery.Celery"
] | [((48, 199), 'celery.Celery', 'Celery', (['"""celery_demo"""'], {'broker': '"""redis://localhost:6379/1"""', 'backend': '"""redis://localhost:6379/2"""', 'include': "['tasks_demo.task1', 'tasks_demo.task2']"}), "('celery_demo', broker='redis://localhost:6379/1', backend=\n 'redis://localhost:6379/2', include=['tasks... |
#!/usr/bin/python3
"""
similarity_mapper2
"""
import sys
import pandas as pd
import numpy as np
big_data = pd.read_csv('ratings.csv')
all_films = np.unique(big_data.movieId)
for line in sys.stdin:
film, film_statistics = line.strip().split('\t', 1)
for f in all_films:
if int(film) < f:
... | [
"numpy.unique",
"pandas.read_csv"
] | [((111, 137), 'pandas.read_csv', 'pd.read_csv', (['"""ratings.csv"""'], {}), "('ratings.csv')\n", (122, 137), True, 'import pandas as pd\n'), ((150, 177), 'numpy.unique', 'np.unique', (['big_data.movieId'], {}), '(big_data.movieId)\n', (159, 177), True, 'import numpy as np\n')] |
from moduls import *
from oredictnames import *
from Inventorys import *
import Item
import crafting as cb
import config
from Inventorys import *
from Inventorys.Inventory import Slot, handler as invhandler, InventoryHandler
import EventHandler
import entity
class player:
def __init__(self, window):
... | [
"EventHandler.eventhandler.on_event",
"Inventorys.Inventory.Slot",
"crafting.craftinghandler.updateOutput_player",
"Inventorys.Inventory.handler.show",
"entity.PlayerModel",
"crafting.craftinghandler.removeOutput_player"
] | [((871, 889), 'Inventorys.Inventory.handler.show', 'invhandler.show', (['(0)'], {}), '(0)\n', (886, 889), True, 'from Inventorys.Inventory import Slot, handler as invhandler, InventoryHandler\n'), ((1160, 1200), 'entity.PlayerModel', 'entity.PlayerModel', (['self.window.position'], {}), '(self.window.position)\n', (117... |
#-*- encoding: UTF-8 -*-
from __future__ import print_function
from setuptools import setup
import re
import os
import sys
long_description = (
"pyDict is command tool for query online dictionaries, "
"like Bing, Collins dictionaries; "
"iDict will have a word learning function"
"which is underdevelop... | [
"os.path.join",
"os.walk",
"re.search"
] | [((503, 558), 're.search', 're.search', (['"""__version__ = [\'"]([^\'"]+)[\'"]"""', 'init_py'], {}), '(\'__version__ = [\\\'"]([^\\\'"]+)[\\\'"]\', init_py)\n', (512, 558), False, 'import re\n'), ((717, 733), 'os.walk', 'os.walk', (['package'], {}), '(package)\n', (724, 733), False, 'import os\n'), ((447, 483), 'os.pa... |