code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
from django.contrib.contenttypes.fields import GenericRelation
from django.conf import settings
from django.db import models
from .custom_field import CustomField
from .model_mixins import SoftDeleteModel
class Organisation(SoftDeleteModel):
name = models.CharField(max_length=255)
owner = models.ForeignKey(s... | [
"django.contrib.contenttypes.fields.GenericRelation",
"django.db.models.ManyToManyField",
"django.db.models.CharField",
"django.db.models.ForeignKey"
] | [((256, 288), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(255)'}), '(max_length=255)\n', (272, 288), False, 'from django.db import models\n'), ((301, 370), 'django.db.models.ForeignKey', 'models.ForeignKey', (['settings.AUTH_USER_MODEL'], {'on_delete': 'models.CASCADE'}), '(settings.AUTH_USE... |
#!/usr/bin/env python3
#-*- coding:utf-8 -*-
"""HMagnet Object"""
import json
class HMagnet:
"""
name
cadref
MAGfile(s)
status: Dead/Alive
index
"""
def __init__(self, name: str, cadref: str, MAGfile: list, status: str, index: int):
"""defaut constructor"""
self.name ... | [
"json.dumps"
] | [((3111, 3197), 'json.dumps', 'json.dumps', (['self'], {'default': 'deserialize.serialize_instance', 'sort_keys': '(True)', 'indent': '(4)'}), '(self, default=deserialize.serialize_instance, sort_keys=True,\n indent=4)\n', (3121, 3197), False, 'import json\n')] |
# Copyright 2020 DeepMind Technologies Limited.
#
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agre... | [
"dataclasses.dataclass"
] | [((742, 776), 'dataclasses.dataclass', 'dataclasses.dataclass', ([], {'frozen': '(True)'}), '(frozen=True)\n', (763, 776), False, 'import dataclasses\n'), ((866, 900), 'dataclasses.dataclass', 'dataclasses.dataclass', ([], {'frozen': '(True)'}), '(frozen=True)\n', (887, 900), False, 'import dataclasses\n'), ((1118, 115... |
# Generated by Django 4.0.2 on 2022-02-04 00:04
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Genre',
fields=[
... | [
"django.db.models.TextField",
"django.db.models.IntegerField",
"django.db.models.ForeignKey",
"django.db.models.BigAutoField",
"django.db.models.DecimalField",
"django.db.models.CharField"
] | [((334, 430), 'django.db.models.BigAutoField', 'models.BigAutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (353, 430), False, 'from django.db import migrations, m... |
import argparse
from builder import builder
def main():
parser = argparse.ArgumentParser()
parser.add_argument("filename", help="File to compile")
parser.add_argument("-O", "--optimize", help="Run optimization on program",
action="store_true")
parser.add_argument("-o", "--ou... | [
"builder.builder",
"argparse.ArgumentParser"
] | [((74, 99), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (97, 99), False, 'import argparse\n'), ((797, 806), 'builder.builder', 'builder', ([], {}), '()\n', (804, 806), False, 'from builder import builder\n')] |
from manimlib.animation.creation import Write
from manimlib.animation.fading import FadeIn
from manimlib.constants import *
from manimlib.mobject.svg.tex_mobject import TexText
from manimlib.scene.scene import Scene
from manimlib.utils.rate_functions import linear
class OpeningQuote(Scene):
CONFIG = {
"qu... | [
"manimlib.animation.fading.FadeIn",
"manimlib.animation.creation.Write",
"manimlib.mobject.svg.tex_mobject.TexText"
] | [((2214, 2259), 'manimlib.mobject.svg.tex_mobject.TexText', 'TexText', (["(self.text_size + ' --' + self.author)"], {}), "(self.text_size + ' --' + self.author)\n", (2221, 2259), False, 'from manimlib.mobject.svg.tex_mobject import TexText\n'), ((817, 858), 'manimlib.animation.fading.FadeIn', 'FadeIn', (['self.quote'],... |
import psycopg2
import smtplib
import ssl
import json
from datetime import datetime, timedelta
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from tabulate import tabulate
def mail4u():
conn = psycopg2.connect(host = "", port = "", dbname = "")
cursor = conn.cursor()
#... | [
"psycopg2.connect",
"datetime.datetime.today",
"datetime.timedelta"
] | [((235, 280), 'psycopg2.connect', 'psycopg2.connect', ([], {'host': '""""""', 'port': '""""""', 'dbname': '""""""'}), "(host='', port='', dbname='')\n", (251, 280), False, 'import psycopg2\n'), ((416, 433), 'datetime.timedelta', 'timedelta', ([], {'days': '(7)'}), '(days=7)\n', (425, 433), False, 'from datetime import ... |
from django.core.management.base import BaseCommand
import io
import os
import csv
import requests
from ...models import Organisation, Page, Attachment, Download, History, Snippet
from django.utils.dateparse import parse_datetime
from django.core.exceptions import ObjectDoesNotExist
url = 'https://raw.githubusercon... | [
"io.StringIO",
"django.utils.dateparse.parse_datetime",
"os.path.splitext",
"requests.get"
] | [((510, 538), 'requests.get', 'requests.get', ([], {'url': '(url % name)'}), '(url=url % name)\n', (522, 538), False, 'import requests\n'), ((595, 617), 'io.StringIO', 'io.StringIO', (['resp.text'], {}), '(resp.text)\n', (606, 617), False, 'import io\n'), ((1272, 1305), 'os.path.splitext', 'os.path.splitext', (["row['f... |
import sbws.util.config as con
from configparser import ConfigParser
class PseudoSection:
def __init__(self, key, value, mini=None, maxi=None):
self.key = key
self.value = value
self.mini = mini
self.maxi = maxi
def getfloat(self, key):
assert key == self.key, 'But in ... | [
"sbws.util.config._validate_nickname",
"sbws.util.config._validate_float",
"configparser.ConfigParser",
"sbws.util.config._validate_fingerprint",
"sbws.util.config._validate_boolean",
"sbws.util.config._validate_url",
"sbws.util.config._validate_int"
] | [((847, 879), 'sbws.util.config._validate_fingerprint', 'con._validate_fingerprint', (['d', '""""""'], {}), "(d, '')\n", (872, 879), True, 'import sbws.util.config as con\n'), ((1050, 1082), 'sbws.util.config._validate_fingerprint', 'con._validate_fingerprint', (['d', '""""""'], {}), "(d, '')\n", (1075, 1082), True, 'i... |
import math
import random
def calculate_vectors(pos_queue):
if (len(pos_queue) == 1):
return (0, 0)
for num in range(len(pos_queue) - 1, 0, -1):
dx = pos_queue[num][0] - pos_queue[num - 1][0]
dy = pos_queue[num][1] - pos_queue[num - 1][1]
# pdb.set_trace()
angle = math... | [
"random.uniform",
"math.cos",
"math.atan2",
"math.hypot",
"random.random",
"math.sin",
"random.randint"
] | [((920, 936), 'math.hypot', 'math.hypot', (['x', 'y'], {}), '(x, y)\n', (930, 936), False, 'import math\n'), ((1702, 1720), 'math.hypot', 'math.hypot', (['dx', 'dy'], {}), '(dx, dy)\n', (1712, 1720), False, 'import math\n'), ((540, 558), 'math.atan2', 'math.atan2', (['dy', 'dx'], {}), '(dy, dx)\n', (550, 558), False, '... |
"""
Base class for GeoRSS services.
Fetches GeoRSS feed from URL to be defined by sub-class.
"""
import codecs
import logging
import re
from datetime import datetime
from typing import Optional
import requests
from georss_client.consts import ATTR_ATTRIBUTION, CUSTOM_ATTRIBUTE
from georss_client.geo_rss_distance_hel... | [
"logging.getLogger",
"requests.Session",
"georss_client.geo_rss_distance_helper.GeoRssDistanceHelper.distance_to_geometry",
"requests.Request",
"georss_client.geo_rss_distance_helper.GeoRssDistanceHelper.extract_coordinates",
"re.search"
] | [((471, 498), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (488, 498), False, 'import logging\n'), ((8808, 8893), 'georss_client.geo_rss_distance_helper.GeoRssDistanceHelper.distance_to_geometry', 'GeoRssDistanceHelper.distance_to_geometry', (['self._home_coordinates', 'self.geometry'],... |
# Copyright (c) 2015 <NAME>
#
# See the file license.txt for copying permission.
from datetime import datetime
from hbmqtt.mqtt.packet import PUBLISH
from hbmqtt.codecs import int_to_bytes_str
import os
import ssl
import sys
import json
import random
import asyncio
import traceback
import threading
import importlib
im... | [
"hbmqtt.version.get_version",
"traceback.format_exc",
"json.loads",
"random.choice",
"collections.deque",
"importlib.import_module",
"ssl.SSLContext",
"json.dumps",
"datetime.datetime.now",
"os.path.dirname",
"hbmqtt.codecs.int_to_bytes_str",
"urllib.request.urlopen"
] | [((6823, 6830), 'collections.deque', 'deque', ([], {}), '()\n', (6828, 6830), False, 'from collections import deque\n'), ((10655, 10669), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (10667, 10669), False, 'from datetime import datetime\n'), ((12555, 12562), 'collections.deque', 'deque', ([], {}), '()\n',... |
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
import time
import os
import subprocess
from subprocess import PIPE
from get... | [
"getDriver.initDriverWithGUI",
"testHome.testHome",
"time.sleep",
"testRoomEntry.testRoomEntry",
"getDriver.initServer",
"testRoomEntry.sendChat"
] | [((477, 489), 'getDriver.initServer', 'initServer', ([], {}), '()\n', (487, 489), False, 'from getDriver import initServer, initDriverHeadless, initDriverWithGUI\n'), ((517, 536), 'getDriver.initDriverWithGUI', 'initDriverWithGUI', ([], {}), '()\n', (534, 536), False, 'from getDriver import initServer, initDriverHeadle... |
"""
Implementation of pairwise ranking using scikit-learn LinearSVC
Reference: "Large Margin Rank Boundaries for Ordinal Regression", <NAME>,
<NAME>, <NAME>.
"""
import itertools
import numpy as np
def transform_pairwise(X, y):
"""Transforms data into pairs with balanced labels for ranking
Transforms a n... | [
"numpy.ones",
"numpy.asarray",
"numpy.sign"
] | [((1221, 1234), 'numpy.asarray', 'np.asarray', (['y'], {}), '(y)\n', (1231, 1234), True, 'import numpy as np\n'), ((1753, 1770), 'numpy.asarray', 'np.asarray', (['X_new'], {}), '(X_new)\n', (1763, 1770), True, 'import numpy as np\n'), ((1573, 1599), 'numpy.sign', 'np.sign', (['(y[i, 0] - y[j, 0])'], {}), '(y[i, 0] - y[... |
from jsonls.core import get_keylists, get_keystrings
def test_get_simple_keylists():
data = {"status": "success", "message": {"affenpinscher": []}}
expect = [
(),
('message',),
('message', 'affenpinscher','*'),
('status',)
]
result = sorted(get_keylists(data))
asser... | [
"jsonls.core.get_keylists",
"jsonls.core.get_keystrings"
] | [((291, 309), 'jsonls.core.get_keylists', 'get_keylists', (['data'], {}), '(data)\n', (303, 309), False, 'from jsonls.core import get_keylists, get_keystrings\n'), ((1132, 1150), 'jsonls.core.get_keylists', 'get_keylists', (['data'], {}), '(data)\n', (1144, 1150), False, 'from jsonls.core import get_keylists, get_keyst... |
## @ingroup Plots
# Mission_Plots.py
#
# Created: Mar 2020, <NAME>
# Apr 2020, <NAME>
# Sep 2020, <NAME>
# Apr 2021, <NAME>
# ----------------------------------------------------------------------
# Imports
# ----------------------------------------------------------------------
from ... | [
"matplotlib.pyplot.grid",
"numpy.sqrt",
"numpy.array",
"matplotlib.ticker.ScalarFormatter",
"numpy.linalg.norm",
"numpy.sin",
"plotly.graph_objects.Surface",
"numpy.atleast_2d",
"numpy.zeros_like",
"numpy.max",
"numpy.linspace",
"numpy.empty",
"numpy.concatenate",
"numpy.min",
"matplotli... | [((1230, 1255), 'matplotlib.pyplot.figure', 'plt.figure', (['save_filename'], {}), '(save_filename)\n', (1240, 1255), True, 'import matplotlib.pyplot as plt\n'), ((2293, 2311), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (2309, 2311), True, 'import matplotlib.pyplot as plt\n'), ((3052, 3077)... |
import mmh3
import BitVector
import redis
import math
import time
class BloomFilter():
#内置100个随机种子
SEEDS = [543, 460, 171, 876, 796, 607, 650, 81, 837, 545, 591, 946, 846, 521, 913, 636, 878, 735, 414, 372,
344, 324, 223, 180, 327, 891, 798, 933, 493, 293, 836, 10, 6, 544, 924, 849, 438, 41, 862,... | [
"math.ceil",
"BitVector.BitVector",
"math.log1p",
"redis.ConnectionPool",
"math.log2",
"redis.StrictRedis",
"time.time",
"mmh3.hash"
] | [((2493, 2548), 'redis.ConnectionPool', 'redis.ConnectionPool', ([], {'host': '"""127.0.0.1"""', 'port': '(6379)', 'db': '(0)'}), "(host='127.0.0.1', port=6379, db=0)\n", (2513, 2548), False, 'import redis\n'), ((2556, 2595), 'redis.StrictRedis', 'redis.StrictRedis', ([], {'connection_pool': 'pool'}), '(connection_pool... |
import sys
import cv2
import os
import numpy as np
import math
import json
import random
from PIL import Image
import psutil
from threading import Thread
import time
from concurrent.futures import ThreadPoolExecutor
def getSubImageAndCopy(pixelValue, pixel_img_map, i, u, copy_to, target_res) -> None:
# print("Sta... | [
"PIL.Image.open",
"math.floor",
"concurrent.futures.ThreadPoolExecutor",
"PIL.Image.new",
"psutil.Process",
"os.getpid",
"cv2.imread"
] | [((1313, 1341), 'cv2.imread', 'cv2.imread', (['processed_pic', '(0)'], {}), '(processed_pic, 0)\n', (1323, 1341), False, 'import cv2\n'), ((1798, 1831), 'concurrent.futures.ThreadPoolExecutor', 'ThreadPoolExecutor', ([], {'max_workers': '(5)'}), '(max_workers=5)\n', (1816, 1831), False, 'from concurrent.futures import ... |
import json
from shutil import copyfile
import sys
import os.path as path
print()
if len(sys.argv) < 2:
print("inform locale key (python updateString.py <locale>)")
else:
locale = sys.argv[1]
if not path.isfile('strings.{}.json'.format(locale)):
print("'strings.{}.json' not found.\nCreate that fi... | [
"json.load",
"shutil.copyfile",
"json.dump"
] | [((2652, 2710), 'json.dump', 'json.dump', (['writing', 'loc_file'], {'ensure_ascii': '(False)', 'indent': '(2)'}), '(writing, loc_file, ensure_ascii=False, indent=2)\n', (2661, 2710), False, 'import json\n'), ((2720, 2765), 'shutil.copyfile', 'copyfile', (['"""strings.json"""', '"""last-strings.json"""'], {}), "('strin... |
# Copyright 2016-2021 Swiss National Supercomputing Centre (CSCS/ETH Zurich)
# ReFrame Project Developers. See the top-level LICENSE file for details.
#
# SPDX-License-Identifier: BSD-3-Clause
import reframe as rfm
import reframe.utility.osext as osext
import reframe.utility.sanity as sn
from reframe.utility import fi... | [
"reframe.utility.find_modules",
"reframe.utility.sanity.assert_false",
"reframe.utility.sanity.assert_found"
] | [((817, 906), 'reframe.utility.find_modules', 'find_modules', (['"""HDF5"""'], {'environ_mapping': "{'.*-gompi-.*': 'foss', '.*-iimpi-.*': 'intel'}"}), "('HDF5', environ_mapping={'.*-gompi-.*': 'foss', '.*-iimpi-.*':\n 'intel'})\n", (829, 906), False, 'from reframe.utility import find_modules, functools\n'), ((1462,... |
from pathlib import Path
# set home dir for default
HOME_DIR = str(Path.home())
DEFAULT_MODEL_DIR = os.path.join(HOME_DIR,'arabicnlp_models')
| [
"pathlib.Path.home"
] | [((68, 79), 'pathlib.Path.home', 'Path.home', ([], {}), '()\n', (77, 79), False, 'from pathlib import Path\n')] |
# -*- Python -*-
# This file is licensed under a pytorch-style license
# See frontends/pytorch/LICENSE for license information.
import typing
import torch
import torch_mlir
# RUN: %PYTHON %s | FileCheck %s
mb = torch_mlir.ModuleBuilder()
class TestModule(torch.nn.Module):
def __init__(self):
super().__... | [
"torch.jit.script",
"torch_mlir.ClassAnnotator",
"torch_mlir.ModuleBuilder"
] | [((215, 241), 'torch_mlir.ModuleBuilder', 'torch_mlir.ModuleBuilder', ([], {}), '()\n', (239, 241), False, 'import torch_mlir\n'), ((419, 448), 'torch.jit.script', 'torch.jit.script', (['test_module'], {}), '(test_module)\n', (435, 448), False, 'import torch\n'), ((462, 489), 'torch_mlir.ClassAnnotator', 'torch_mlir.Cl... |
import logging
import os
import requests
import random
sb_url = os.environ.get('sb_url')
rootLogger = logging.getLogger(__name__)
'''
A1. I’m so glad you asked. I love to talk, and I especially love to talk with you.
Do you know that you have received well wishes from the community through the Silver Bow pledge campa... | [
"logging.getLogger",
"random.choice",
"os.environ.get",
"requests.get"
] | [((64, 88), 'os.environ.get', 'os.environ.get', (['"""sb_url"""'], {}), "('sb_url')\n", (78, 88), False, 'import os\n'), ((102, 129), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (119, 129), False, 'import logging\n'), ((3696, 3727), 'requests.get', 'requests.get', (['sb_url'], {'timeou... |
# -*- encoding: utf-8 -*-
"""
License: MIT
Copyright (c) 2021 - present DaruWheel.com
"""
from django.db import models
from django.conf import settings
from django.db.models import Sum
from datetime import timedelta
from random import randint
from django.utils import timezone
try:
from account.models import *
ex... | [
"django.contrib.auth.get_user_model",
"django.db.models.OneToOneField",
"django.db.models.FloatField",
"random.randint",
"django.db.models.Sum",
"django.db.models.IntegerField",
"django.db.models.ForeignKey",
"random.randrange",
"django.db.models.BooleanField",
"django.utils.timezone.now",
"djan... | [((441, 457), 'django.contrib.auth.get_user_model', 'get_user_model', ([], {}), '()\n', (455, 457), False, 'from django.contrib.auth import get_user_model\n'), ((512, 563), 'django.db.models.FloatField', 'models.FloatField', ([], {'default': '(0)', 'blank': '(True)', 'null': '(True)'}), '(default=0, blank=True, null=Tr... |
from fabric.colors import green as _green, yellow as _yellow, red as _red
from settings import cloud_connections, DEFAULT_PROVIDER
from ghost_log import log
from ghost_tools import get_aws_connection_data
from libs.blue_green import get_blue_green_from_app
from libs.ec2 import create_ec2_instance
COMMAND_DESCRIPTION... | [
"fabric.colors.green",
"libs.blue_green.get_blue_green_from_app",
"libs.ec2.create_ec2_instance",
"fabric.colors.red"
] | [((1257, 1291), 'libs.blue_green.get_blue_green_from_app', 'get_blue_green_from_app', (['self._app'], {}), '(self._app)\n', (1280, 1291), False, 'from libs.blue_green import get_blue_green_from_app\n'), ((1691, 1824), 'libs.ec2.create_ec2_instance', 'create_ec2_instance', (['self._cloud_connection', 'self._app', 'self.... |
import torch
import numpy as np
# check if CUDA is available
train_on_gpu = torch.cuda.is_available()
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
if not train_on_gpu:
print('CUDA is not available. Training on CPU ...')
else:
print('CUDA is available! Training on GPU ...')
... | [
"torch.nn.Tanh",
"torch.nn.Softmax",
"torch.utils.data.random_split",
"torch.nn.Sequential",
"torch.nn.DataParallel",
"numpy.sum",
"torchvision.datasets.CIFAR10",
"torch.cuda.is_available",
"torch.nn.NLLLoss",
"numpy.zeros",
"torchvision.transforms.Normalize",
"torch.utils.data.DataLoader",
... | [((81, 106), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (104, 106), False, 'import torch\n'), ((567, 662), 'torchvision.datasets.CIFAR10', 'torchvision.datasets.CIFAR10', ([], {'root': '"""./data"""', 'train': '(True)', 'download': '(True)', 'transform': 'transform'}), "(root='./data', trai... |
import argparse
import json
import os
import pandas as pd
import random
import sys
from evaluation.decomposition import Decomposition, get_decomposition_from_tokens
from model.rule_based.rule_based_model import RuleBasedModel
from model.rule_based.copy_model import CopyModel
from model.seq2seq.seq2seq_model import Se... | [
"os.path.exists",
"random.sample",
"argparse.ArgumentParser",
"pandas.read_csv",
"pandas.set_option",
"annotation_pipeline.utils.app_store_generation.valid_annotation_tokens",
"utils.preprocess_examples.fix_references",
"model.rule_based.copy_model.CopyModel",
"evaluation.decomposition.Decomposition... | [((616, 637), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (631, 637), False, 'import sys\n'), ((724, 760), 'pandas.set_option', 'pd.set_option', (['"""display.width"""', '(1000)'], {}), "('display.width', 1000)\n", (737, 760), True, 'import pandas as pd\n'), ((761, 803), 'pandas.set_option', '... |
# Copyright The IETF Trust 2021, All Rights Reserved
# -*- coding: utf-8 -*-
"""Tests of models in the Meeting application"""
from ietf.meeting.factories import MeetingFactory
from ietf.stats.factories import MeetingRegistrationFactory
from ietf.utils.test_utils import TestCase
class MeetingTests(TestCase):
def t... | [
"ietf.stats.factories.MeetingRegistrationFactory.create_batch",
"ietf.meeting.factories.MeetingFactory",
"ietf.stats.factories.MeetingRegistrationFactory"
] | [((430, 474), 'ietf.meeting.factories.MeetingFactory', 'MeetingFactory', ([], {'type_id': '"""ietf"""', 'number': '"""109"""'}), "(type_id='ietf', number='109')\n", (444, 474), False, 'from ietf.meeting.factories import MeetingFactory\n'), ((483, 555), 'ietf.stats.factories.MeetingRegistrationFactory.create_batch', 'Me... |
###############################################################################
''''''
###############################################################################
from functools import cached_property
from collections import OrderedDict
from collections.abc import Mapping
from .channel import DataChannel
class Da... | [
"collections.OrderedDict"
] | [((903, 974), 'collections.OrderedDict', 'OrderedDict', ([], {'x': 'self.x', 'y': 'self.y', 'z': 'self.z', 'c': 'self.c', 's': 'self.s', 'l': 'self.l'}), '(x=self.x, y=self.y, z=self.z, c=self.c, s=self.s, l=self.l)\n', (914, 974), False, 'from collections import OrderedDict\n')] |
#!/usr/bin/env python3 -u
import SDGpython as SDG
import argparse
from collections import Counter
import os
def print_step_banner(s):
print('\n'+'*'*(len(s)+4))
print(f'* {s} *')
print('*'*(len(s)+4)+"\n")
parser = argparse.ArgumentParser()
parser.add_argument("-o", "--output_prefix", help="prefix for out... | [
"SDGpython.WorkSpace",
"SDGpython.GraphMaker",
"argparse.ArgumentParser",
"os.replace"
] | [((229, 254), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (252, 254), False, 'import argparse\n'), ((928, 943), 'SDGpython.WorkSpace', 'SDG.WorkSpace', ([], {}), '()\n', (941, 943), True, 'import SDGpython as SDG\n'), ((1104, 1170), 'os.replace', 'os.replace', (['"""small_K.freqs"""', 'f"""{... |
from django.contrib import admin
from .models import Person,report,management,Person_without_Aadhar
admin.site.register(Person)
admin.site.register(report)
admin.site.register(management)
admin.site.register(Person_without_Aadhar)
# Register your models here.
| [
"django.contrib.admin.site.register"
] | [((101, 128), 'django.contrib.admin.site.register', 'admin.site.register', (['Person'], {}), '(Person)\n', (120, 128), False, 'from django.contrib import admin\n'), ((129, 156), 'django.contrib.admin.site.register', 'admin.site.register', (['report'], {}), '(report)\n', (148, 156), False, 'from django.contrib import ad... |
import json
from shared import get_session_for_account, send_notification
from policyuniverse.policy import Policy
def audit(resource, remediate=False):
is_compliant = True
if resource["type"] != "sqs":
raise Exception(
"Mismatched type. Expected {} but received {}".format(
... | [
"shared.get_session_for_account",
"json.loads",
"policyuniverse.policy.Policy",
"shared.send_notification"
] | [((438, 509), 'shared.get_session_for_account', 'get_session_for_account', (["resource['account']", "resource['region']", '"""sqs"""'], {}), "(resource['account'], resource['region'], 'sqs')\n", (461, 509), False, 'from shared import get_session_for_account, send_notification\n'), ((890, 915), 'json.loads', 'json.loads... |
import os
def norm_path(*args):
"""
Returns normalized for current os, absolute path, joined by arguments.
:param args: path components
:return: joined, normalized, absolute path.
"""
return os.path.abspath(os.path.normpath(os.path.join(*args)))
def file_path(file_name, path):
for p in p... | [
"os.path.isfile",
"os.path.join",
"os.walk"
] | [((626, 647), 'os.walk', 'os.walk', (['prefix', 'path'], {}), '(prefix, path)\n', (633, 647), False, 'import os\n'), ((380, 405), 'os.path.isfile', 'os.path.isfile', (['file_path'], {}), '(file_path)\n', (394, 405), False, 'import os\n'), ((250, 269), 'os.path.join', 'os.path.join', (['*args'], {}), '(*args)\n', (262, ... |
import sys
from typing import Optional
from termcolor import colored
from ..stopwatch import Stopwatch
from . import Caller, format_elapsed_time, inspect_caller
# pylint: disable=invalid-name
class stopwatch:
def __init__(self, message: Optional[str] = None):
self._message = message
self._caller... | [
"termcolor.colored"
] | [((719, 822), 'termcolor.colored', 'colored', (['f"""[{caller.module}:{caller.function}:{caller.line_number}]"""'], {'color': '"""blue"""', 'attrs': "['bold']"}), "(f'[{caller.module}:{caller.function}:{caller.line_number}]', color=\n 'blue', attrs=['bold'])\n", (726, 822), False, 'from termcolor import colored\n')] |
import sympy
from cached_property import cached_property
from devito import Dimension
from devito.types import SparseTimeFunction
from devito.logger import error
import numpy as np
__all__ = ['PointSource', 'Receiver', 'Shot', 'RickerSource', 'GaborSource', 'TimeAxis']
class TimeAxis(object):
"""
Data obj... | [
"numpy.ceil",
"sympy.Function.__new__",
"devito.logger.error",
"numpy.exp",
"numpy.linspace",
"numpy.cos",
"devito.types.SparseTimeFunction.__new__"
] | [((2466, 2510), 'numpy.linspace', 'np.linspace', (['self.start', 'self.stop', 'self.num'], {}), '(self.start, self.stop, self.num)\n', (2477, 2510), True, 'import numpy as np\n'), ((4445, 4521), 'devito.types.SparseTimeFunction.__new__', 'SparseTimeFunction.__new__', (['cls'], {'dimensions': '[grid.time_dim, p_dim]'}),... |
from datetime import datetime
def create_results_file_name(dataset, algorithm_name, drift_labels_known, proxy_evaluation, image_data):
"""
Parameters
----------
dataset: String with name of the dataset
algorithm_name: String with name of the algorithm (used for folder name + description in file n... | [
"datetime.datetime.today"
] | [((621, 637), 'datetime.datetime.today', 'datetime.today', ([], {}), '()\n', (635, 637), False, 'from datetime import datetime\n')] |
import os
import shutil
from pathlib import Path
from tempfile import gettempdir
import pytest
from dsgrid.tests.common import (
TEST_DATASET_DIRECTORY,
TEST_PROJECT_REPO,
)
@pytest.fixture
def make_test_project_dir():
tmpdir = _make_project_dir(TEST_PROJECT_REPO)
yield tmpdir / "dsgrid_project"
... | [
"os.path.exists",
"pathlib.Path",
"shutil.copytree",
"tempfile.gettempdir",
"os.mkdir",
"shutil.rmtree"
] | [((321, 342), 'shutil.rmtree', 'shutil.rmtree', (['tmpdir'], {}), '(tmpdir)\n', (334, 342), False, 'import shutil\n'), ((440, 462), 'os.path.exists', 'os.path.exists', (['tmpdir'], {}), '(tmpdir)\n', (454, 462), False, 'import os\n'), ((498, 514), 'os.mkdir', 'os.mkdir', (['tmpdir'], {}), '(tmpdir)\n', (506, 514), Fals... |
from openapi_schema_generator import OpenApiSchemaGenerator
from compare_objects import compare_objects
import json
import yaml
# **************** Globals ***************** #
base_path = "test/Examples"
def get_expected_and_gen(file_name, file_type='json'):
src_path = f"{base_path}/src/{file_name}.{file_type}"
... | [
"json.load",
"yaml.load",
"openapi_schema_generator.OpenApiSchemaGenerator",
"compare_objects.compare_objects"
] | [((402, 434), 'openapi_schema_generator.OpenApiSchemaGenerator', 'OpenApiSchemaGenerator', (['src_path'], {}), '(src_path)\n', (424, 434), False, 'from openapi_schema_generator import OpenApiSchemaGenerator\n'), ((1540, 1580), 'compare_objects.compare_objects', 'compare_objects', (['data', 'generated_schemas'], {}), '(... |
import numpy as np
#I'm dumb, so I'm reducing the problem to 2D so I can see what's happening
##Make fake data
# an N x 5 array containing a regular mesh representing the stimulus params
stim_params=np.mgrid[10:25,20:22].reshape(2,-1).T
# an N x 3 array representing the output values for each simulation run
stimnum=... | [
"numpy.lexsort",
"numpy.unique",
"numpy.arange",
"numpy.random.permutation"
] | [((429, 472), 'numpy.random.permutation', 'np.random.permutation', (['stim_params.shape[0]'], {}), '(stim_params.shape[0])\n', (450, 472), True, 'import numpy as np\n'), ((1200, 1234), 'numpy.lexsort', 'np.lexsort', (['stim_params[:, ::-1].T'], {}), '(stim_params[:, ::-1].T)\n', (1210, 1234), True, 'import numpy as np\... |
"""Utility functions used in various views."""
import datetime
from .database import db
from .models import AppUse
from flask import current_app, request, session, render_template, make_response
from .twitter import TwitterClient
from .recaptcha import RecaptchaClient
from pytz import UTC
import re
twitter_username_re... | [
"flask.render_template",
"datetime.datetime.fromtimestamp",
"flask.session.get",
"datetime.datetime.utcnow",
"re.compile"
] | [((323, 357), 're.compile', 're.compile', (['"""^[a-zA-Z0-9_]{1,15}$"""'], {}), "('^[a-zA-Z0-9_]{1,15}$')\n", (333, 357), False, 'import re\n'), ((2916, 2943), 'flask.session.get', 'session.get', (['"""last_app_use"""'], {}), "('last_app_use')\n", (2927, 2943), False, 'from flask import current_app, request, session, r... |
import os
import socket
import logging
from channel.connector import Connector
class Server(Connector):
"""UNIX-socket server used to communicate with clients."""
def __init__(self):
Connector.__init__(self)
def delete_existing_socket(self):
"""Deletes the existing UNIX-socket if it exist... | [
"os.path.exists",
"logging.debug",
"channel.connector.Connector.__init__",
"logging.error",
"os.remove"
] | [((201, 225), 'channel.connector.Connector.__init__', 'Connector.__init__', (['self'], {}), '(self)\n', (219, 225), False, 'from channel.connector import Connector\n'), ((337, 362), 'os.path.exists', 'os.path.exists', (['self.path'], {}), '(self.path)\n', (351, 362), False, 'import os\n'), ((986, 1006), 'os.remove', 'o... |
from base58 import b58decode_check
import hashlib
from ecdsa import SECP256k1, VerifyingKey, util
class TxOutputScript():
def __init__(self, address, confirmed_balance, recipient, fee, value, change_address):
assert address != change_address, 'An address cannot send change to itself'
self.confirm... | [
"hashlib.sha256",
"base58.b58decode_check",
"ecdsa.util.sigdecode_der",
"ecdsa.VerifyingKey.from_pem",
"ecdsa.util.sigencode_der_canonize"
] | [((4024, 4055), 'ecdsa.VerifyingKey.from_pem', 'VerifyingKey.from_pem', (['self.pem'], {}), '(self.pem)\n', (4045, 4055), False, 'from ecdsa import SECP256k1, VerifyingKey, util\n'), ((5317, 5363), 'ecdsa.util.sigdecode_der', 'util.sigdecode_der', (['signature', 'SECP256k1.order'], {}), '(signature, SECP256k1.order)\n'... |
import pytest
from unittest.mock import MagicMock
@pytest.fixture(scope="function")
def canifier(ctre):
return ctre.CANifier(1)
@pytest.fixture(scope="function")
def cdata(canifier, hal_data):
return hal_data["CAN"][1]
def test_canifier_init(ctre, hal_data):
assert 1 not in hal_data["CAN"]
ctre.CA... | [
"pytest.fixture",
"pytest.mark.xfail"
] | [((53, 85), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""'}), "(scope='function')\n", (67, 85), False, 'import pytest\n'), ((137, 169), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""'}), "(scope='function')\n", (151, 169), False, 'import pytest\n'), ((957, 997), 'pytest.mark.xfa... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^list/$', views.targets_listing, name='crits-targets-views-targets_listing'),
url(r'^list/(?P<option>\S+)/$', views.targets_listing, name='crits-targets-views-targets_listing'),
url(r'^divisions/list/$', views.divisions_listing, na... | [
"django.conf.urls.url"
] | [((75, 161), 'django.conf.urls.url', 'url', (['"""^list/$"""', 'views.targets_listing'], {'name': '"""crits-targets-views-targets_listing"""'}), "('^list/$', views.targets_listing, name=\n 'crits-targets-views-targets_listing')\n", (78, 161), False, 'from django.conf.urls import url\n'), ((163, 266), 'django.conf.ur... |
import numpy as np
from math import pi
from numpy import linalg as LA
def project_point(vector, point):
"""Given a line vector and a point, projects the point
on the line, resulting to a point that is closest to
the given point.
Args:
vector: A 2D array of points in the form [[x1, y1], [x2, ... | [
"numpy.power",
"numpy.subtract",
"numpy.dot",
"numpy.arctan2",
"numpy.linalg.norm",
"numpy.mod"
] | [((533, 555), 'numpy.subtract', 'np.subtract', (['point', 'p0'], {}), '(point, p0)\n', (544, 555), True, 'import numpy as np\n'), ((565, 584), 'numpy.subtract', 'np.subtract', (['p1', 'p0'], {}), '(p1, p0)\n', (576, 584), True, 'import numpy as np\n'), ((1417, 1436), 'numpy.subtract', 'np.subtract', (['p1', 'p0'], {}),... |
import math
from functional.pipeline import Sequence
def dot_product(xs: Sequence, ys: Sequence) -> float:
return xs \
.zip(ys) \
.map(lambda t: t[0] * t[1]) \
.sum()
def euclidean_distance(xs: Sequence, ys: Sequence) -> float:
s = xs \
.zip(ys) \
.map(lambda t: (t[0... | [
"math.sqrt"
] | [((375, 387), 'math.sqrt', 'math.sqrt', (['s'], {}), '(s)\n', (384, 387), False, 'import math\n'), ((752, 768), 'math.sqrt', 'math.sqrt', (['(s / n)'], {}), '(s / n)\n', (761, 768), False, 'import math\n')] |
import numpy as np
"""
Q:
Write a binomial tree program to calculate the put prices of Bermuda options.
For such options, early exercise is allowed only on specific dates.
Inputs:
S (stock price)
X (strike price)
r (continuously compounded annual interest rate in percentage)
s (annual volatility in perce... | [
"numpy.exp",
"numpy.sqrt"
] | [((932, 950), 'numpy.exp', 'np.exp', (['(r * deltaT)'], {}), '(r * deltaT)\n', (938, 950), True, 'import numpy as np\n'), ((967, 982), 'numpy.sqrt', 'np.sqrt', (['deltaT'], {}), '(deltaT)\n', (974, 982), True, 'import numpy as np\n')] |
# Generated by Django 3.0.6 on 2020-06-13 12:41
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('exams', '0013_auto_20200612_1959'),
]
operations = [
migrations.AddField(
model_name='examuserrelations',
name='user... | [
"django.db.models.CharField"
] | [((347, 416), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'default': 'None', 'max_length': '(600)', 'null': '(True)'}), '(blank=True, default=None, max_length=600, null=True)\n', (363, 416), False, 'from django.db import migrations, models\n')] |
# ======================================================================
# Reactor Reboot
# Advent of Code 2021 Day 22 -- <NAME> -- https://adventofcode.com
#
# Python implementation by Dr. <NAME> III
# ======================================================================
# =========================================... | [
"re.compile"
] | [((972, 1079), 're.compile', 're.compile', (['"""(o[nf]+) x=(-?[0-9]+)..(-?[0-9]+),y=(-?[0-9]+)..(-?[0-9]+),z=(-?[0-9]+)..(-?[0-9]+)"""'], {}), "(\n '(o[nf]+) x=(-?[0-9]+)..(-?[0-9]+),y=(-?[0-9]+)..(-?[0-9]+),z=(-?[0-9]+)..(-?[0-9]+)'\n )\n", (982, 1079), False, 'import re\n')] |
import usocket as socket
def get_file(url, file):
_, _, host, path = url.split('/', 3)
if ':' in host:
host, port = host.split(':', 1)
else:
port = 80
addr = socket.getaddrinfo(host, int(port))[0][-1]
s = socket.socket()
s.connect(addr)
s.send(bytes('GET /%s HTT... | [
"usocket.socket"
] | [((253, 268), 'usocket.socket', 'socket.socket', ([], {}), '()\n', (266, 268), True, 'import usocket as socket\n'), ((911, 926), 'usocket.socket', 'socket.socket', ([], {}), '()\n', (924, 926), True, 'import usocket as socket\n')] |
# Copyright 2015-2018 Capital One Services, 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 or agreed ... | [
"dateutil.tz.gettz",
"c7n.testing.mock_datetime_now",
"azure_common.arm_template"
] | [((1675, 1710), 'azure_common.arm_template', 'arm_template', (['"""appserviceplan.json"""'], {}), "('appserviceplan.json')\n", (1687, 1710), False, 'from azure_common import BaseTest, arm_template\n'), ((2178, 2213), 'azure_common.arm_template', 'arm_template', (['"""appserviceplan.json"""'], {}), "('appserviceplan.jso... |
import pytest
import vcr
from pigskin.pigskin import pigskin
@pytest.fixture(scope='class')
def gp():
with vcr.use_cassette('backends/europe/gp.yaml'):
return pigskin()
@pytest.mark.incremental
class TestEuropeVideo(object):
"""These don't require authentication to Game Pass."""
@vcr.use_casset... | [
"pytest.fixture",
"vcr.use_cassette",
"pigskin.pigskin.pigskin"
] | [((65, 94), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""class"""'}), "(scope='class')\n", (79, 94), False, 'import pytest\n'), ((306, 369), 'vcr.use_cassette', 'vcr.use_cassette', (['"""backends/europe/video__get_diva_config.yaml"""'], {}), "('backends/europe/video__get_diva_config.yaml')\n", (322, 369), Fal... |
import jellyfish
import time
from difflib import SequenceMatcher
def getStringSimilarity(s1, s2):
return jellyfish.jaro_winkler(s1, s2)
def getStringsimilarity_difflib(s1,s2):
return SequenceMatcher(None, s1, s2).ratio()
def getInputData(path):
fin = open(path, "r", encoding="utf8")
data = []
... | [
"jellyfish.jaro_winkler",
"difflib.SequenceMatcher",
"time.time"
] | [((110, 140), 'jellyfish.jaro_winkler', 'jellyfish.jaro_winkler', (['s1', 's2'], {}), '(s1, s2)\n', (132, 140), False, 'import jellyfish\n'), ((1418, 1429), 'time.time', 'time.time', ([], {}), '()\n', (1427, 1429), False, 'import time\n'), ((193, 222), 'difflib.SequenceMatcher', 'SequenceMatcher', (['None', 's1', 's2']... |
import os
import uuid
from django.db.models import FilePathField
from django.core.files.storage import FileSystemStorage
class ReadOnlyFileSystemStorage(FileSystemStorage):
@classmethod
def create_store(cls, location):
return cls(location=location)
def save(self, name, content, max_length=None)... | [
"os.path.exists",
"uuid.uuid4"
] | [((658, 676), 'os.path.exists', 'os.path.exists', (['fn'], {}), '(fn)\n', (672, 676), False, 'import os\n'), ((605, 617), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (615, 617), False, 'import uuid\n')] |
"""Unit tests for env_loader.py"""
# Standard library imports
import os
# from unittest import TestCase, mock
import unittest
from unittest.mock import patch, mock_open
# Local application imports
from context import EnvLoader
class TestEnvLoader(unittest.TestCase):
def setUp(self):
self.__env_loader =... | [
"unittest.main",
"unittest.mock.mock_open",
"unittest.mock.patch.dict",
"context.EnvLoader"
] | [((547, 609), 'unittest.mock.patch.dict', 'patch.dict', (['os.environ', "{'ABK_TEST_ENV_VAR': '[fake_api_key]'}"], {}), "(os.environ, {'ABK_TEST_ENV_VAR': '[fake_api_key]'})\n", (557, 609), False, 'from unittest.mock import patch, mock_open\n'), ((954, 1002), 'unittest.mock.patch.dict', 'patch.dict', (['os.environ', "{... |
"""
MAILER APP
This module describes the data layout for the mailer app.
Classes:
OutboundEmail
Functions:
n/a
Created on 22 Oct 2013
@author: michael
"""
from django.db import models
from django.conf import settings
from django.contrib.sites.models import Site
from redactor.fields import RedactorTextFie... | [
"django.db.models.TextField",
"django.db.models.ForeignKey",
"redactor.fields.RedactorTextField",
"django.db.models.DateTimeField",
"django.db.models.CharField"
] | [((425, 527), 'django.db.models.ForeignKey', 'models.ForeignKey', (['settings.AUTH_USER_MODEL'], {'related_name': '"""outbound_emails"""', 'blank': '(True)', 'null': '(True)'}), "(settings.AUTH_USER_MODEL, related_name='outbound_emails',\n blank=True, null=True)\n", (442, 527), False, 'from django.db import models\n... |
from os import path
import sys
from pstats import Stats
import cProfile
import json
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
from src import genetic_algorithm_solver
def perf_test():
puzzle = json.loads(open('../puzzles/qr.json').read())
solver = genetic_algorithm_solver.GeneticAl... | [
"os.path.abspath",
"pstats.Stats",
"cProfile.Profile",
"src.genetic_algorithm_solver.GeneticAlgorithmSolver"
] | [((402, 420), 'cProfile.Profile', 'cProfile.Profile', ([], {}), '()\n', (418, 420), False, 'import cProfile\n'), ((458, 473), 'pstats.Stats', 'Stats', (['profiler'], {}), '(profiler)\n', (463, 473), False, 'from pstats import Stats\n'), ((286, 345), 'src.genetic_algorithm_solver.GeneticAlgorithmSolver', 'genetic_algori... |
import itertools
from collections import defaultdict
import numpy as np
from scipy import stats
def max_accuracy(y_true, y_pred):
names_true, names_pred, max_result = list(set(y_true)), list(set(y_pred)), 0
for perm in itertools.permutations(names_pred):
acc = np.average([1. if names_true.index(ti) =... | [
"numpy.tile",
"numpy.diagonal",
"numpy.reshape",
"numpy.repeat",
"scipy.stats.rankdata",
"numpy.power",
"itertools.combinations",
"numpy.array",
"numpy.sum",
"collections.defaultdict",
"itertools.permutations"
] | [((230, 264), 'itertools.permutations', 'itertools.permutations', (['names_pred'], {}), '(names_pred)\n', (252, 264), False, 'import itertools\n'), ((2183, 2212), 'scipy.stats.rankdata', 'stats.rankdata', (['(-measure1_ari)'], {}), '(-measure1_ari)\n', (2197, 2212), False, 'from scipy import stats\n'), ((2233, 2262), '... |
# Read & Edit PDFs
import PyPDF2
import os
print("This module will use the PyPDF2 & os modules")
os.chdir('c:\\users\\drew\\downloads\\auto')
pdfFile = open('meetingminutes2.pdf', 'rb')
print("pdf's need to be in read binary file type. THat's why we'll put pdfFile = open('meetingminutes2.pdf', 'rb')")
... | [
"os.chdir",
"PyPDF2.PdfFileReader",
"PyPDF2.PdfFileWriter"
] | [((107, 151), 'os.chdir', 'os.chdir', (['"""c:\\\\users\\\\drew\\\\downloads\\\\auto"""'], {}), "('c:\\\\users\\\\drew\\\\downloads\\\\auto')\n", (115, 151), False, 'import os\n'), ((329, 358), 'PyPDF2.PdfFileReader', 'PyPDF2.PdfFileReader', (['pdfFile'], {}), '(pdfFile)\n', (349, 358), False, 'import PyPDF2\n'), ((629... |
from numba import cuda
from math import sqrt
from .common import normalize, dot, vector_difference
@cuda.jit(device=True)
def intersect_ray_sphere(ray_origin: tuple, ray_dir: tuple, sphere_origin: tuple, sphere_radius: float) -> float:
""" This function takes the ray and sphere data and computes whether there is ... | [
"math.sqrt",
"numba.cuda.jit"
] | [((102, 123), 'numba.cuda.jit', 'cuda.jit', ([], {'device': '(True)'}), '(device=True)\n', (110, 123), False, 'from numba import cuda\n'), ((1225, 1246), 'numba.cuda.jit', 'cuda.jit', ([], {'device': '(True)'}), '(device=True)\n', (1233, 1246), False, 'from numba import cuda\n'), ((982, 1000), 'math.sqrt', 'sqrt', (['d... |
import datetime
import functools
import hashlib
from json.decoder import JSONDecodeError
import os
import pprint
from flask import current_app, request, has_request_context, json
import pytz
import six
import typing
from cape_of_good_place_names.config import config
def _deserialize(data, klass):
"""Deserialize... | [
"flask.current_app.logger.debug",
"pytz.timezone",
"os.path.exists",
"dateutil.parser.parse",
"os.listdir",
"flask.request.environ.get",
"os.path.split",
"os.path.normpath",
"datetime.datetime.now",
"flask.has_request_context",
"flask.current_app.logger.info",
"flask.current_app.logger.warning... | [((3895, 3917), 'functools.lru_cache', 'functools.lru_cache', (['(1)'], {}), '(1)\n', (3914, 3917), False, 'import functools\n'), ((6687, 6709), 'functools.lru_cache', 'functools.lru_cache', (['(1)'], {}), '(1)\n', (6706, 6709), False, 'import functools\n'), ((7060, 7082), 'functools.lru_cache', 'functools.lru_cache', ... |
"""Logger configuration."""
import logging
from pathlib import Path
import pkg_resources
__all__ = ["configure_logger"]
logger = logging.getLogger(__name__)
def configure_logger(workdir: Path, package_name: str = "swan"):
"""Set the logging infrasctucture."""
file_log = workdir / 'swan_output.log'
log... | [
"logging.getLogger",
"logging.basicConfig",
"logging.StreamHandler",
"pkg_resources.resource_filename",
"pkg_resources.get_distribution"
] | [((133, 160), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (150, 160), False, 'import logging\n'), ((317, 437), 'logging.basicConfig', 'logging.basicConfig', ([], {'filename': 'file_log', 'level': 'logging.INFO', 'format': '"""%(asctime)s %(message)s"""', 'datefmt': '"""[%I:%M:%S]"""'}... |
from app import db
from datetime import datetime
class Article(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(128))
content = db.Column(db.String(2048))
category_id = db.Column(db.Integer, db.ForeignKey('category.id'))
image = db.Column(db.String(128)) # filena... | [
"app.db.String",
"app.db.Column",
"app.db.ForeignKey",
"app.db.relationship"
] | [((84, 123), 'app.db.Column', 'db.Column', (['db.Integer'], {'primary_key': '(True)'}), '(db.Integer, primary_key=True)\n', (93, 123), False, 'from app import db\n'), ((354, 413), 'app.db.Column', 'db.Column', (['db.DateTime'], {'index': '(True)', 'default': 'datetime.utcnow'}), '(db.DateTime, index=True, default=datet... |
import os
import numpy as np
import pytest
import tensorflow as tf
from bentoml.tensorflow import TensorflowModel
from tests._internal.frameworks.tensorflow_utils import (
KerasSequentialModel,
NativeModel,
NativeRaggedModel,
)
native_data = [[1, 2, 3, 4, 5]]
native_tensor = tf.constant(np.asfarray(nativ... | [
"tensorflow.ragged.constant",
"bentoml.tensorflow.TensorflowModel",
"bentoml.tensorflow.TensorflowModel.load",
"os.path.join",
"numpy.asfarray",
"tests._internal.frameworks.tensorflow_utils.KerasSequentialModel",
"tests._internal.frameworks.tensorflow_utils.NativeModel",
"tests._internal.frameworks.te... | [((392, 441), 'tensorflow.ragged.constant', 'tf.ragged.constant', (['ragged_data'], {'dtype': 'tf.float64'}), '(ragged_data, dtype=tf.float64)\n', (410, 441), True, 'import tensorflow as tf\n'), ((303, 327), 'numpy.asfarray', 'np.asfarray', (['native_data'], {}), '(native_data)\n', (314, 327), True, 'import numpy as np... |
# coding: utf8
"""
Setup script for otsurrogate
============================
This script allows to install otsurrogate within the python environment.
Usage
-----
::
python setup.py install
"""
from setuptools import (setup, find_packages, Command)
# Check some import before starting build process.
try:
imp... | [
"setuptools.find_packages",
"pip.main"
] | [((1063, 1093), 'setuptools.find_packages', 'find_packages', ([], {'exclude': "['doc']"}), "(exclude=['doc'])\n", (1076, 1093), False, 'from setuptools import setup, find_packages, Command\n'), ((382, 412), 'pip.main', 'pip.main', (["['install', 'scipy']"], {}), "(['install', 'scipy'])\n", (390, 412), False, 'import pi... |
from copy import copy
from typing import List, Optional
from didcomm.common.types import DID_URL, DID
from didcomm.did_doc.did_doc import DIDDoc, VerificationMethod, DIDCommService
from didcomm.did_doc.did_resolver import DIDResolver
from didcomm.secrets.secrets_resolver import SecretsResolver, Secret
class TestDIDD... | [
"copy.copy"
] | [((669, 693), 'copy.copy', 'copy', (['key_agreement_kids'], {}), '(key_agreement_kids)\n', (673, 693), False, 'from copy import copy\n'), ((730, 755), 'copy.copy', 'copy', (['authentication_kids'], {}), '(authentication_kids)\n', (734, 755), False, 'from copy import copy\n'), ((793, 819), 'copy.copy', 'copy', (['verifi... |
#!/usr/bin/env python3
import argparse
import logging
from bio_embeddings.utilities.pipeline import parse_config_file_and_execute_run
def main():
"""
Pipeline commandline entry point
"""
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
# Jax likes to print ... | [
"logging.basicConfig",
"bio_embeddings.utilities.pipeline.parse_config_file_and_execute_run",
"argparse.ArgumentParser",
"logging.captureWarnings"
] | [((207, 299), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO', 'format': '"""%(asctime)s %(levelname)s %(message)s"""'}), "(level=logging.INFO, format=\n '%(asctime)s %(levelname)s %(message)s')\n", (226, 299), False, 'import logging\n'), ((333, 362), 'logging.captureWarnings', 'logging.c... |
#import open3d
import os, sys
import cv2
import numpy as np
import argparse
imgs_path = 'result/kitti_tracking/0019/'
target_size = (1920, 1080)
target_fps = 8.0
# 输出文件名
target_video = 'out.mp4'
# 是否保存 resize 的中间图像
saveResizeFlag = False
img_types = ('.bmp', '.dib', '.png', '.jpg', '.jpeg', '.pbm', '.pgm', '.ppm', '.t... | [
"numpy.copy",
"os.path.exists",
"os.listdir",
"numpy.fromfile",
"numpy.ones",
"cv2.imwrite",
"cv2.VideoWriter",
"numpy.zeros",
"os.mkdir",
"cv2.VideoWriter_fourcc",
"cv2.cvtColor"
] | [((490, 546), 'numpy.ones', 'np.ones', (['(img.shape[0], img.shape[1], 3)'], {'dtype': 'np.uint8'}), '((img.shape[0], img.shape[1], 3), dtype=np.uint8)\n', (497, 546), True, 'import numpy as np\n'), ((790, 824), 'numpy.zeros', 'np.zeros', (['hlsImg.shape', 'np.float32'], {}), '(hlsImg.shape, np.float32)\n', (798, 824),... |
'''
Function:
load the train data.
Author:
Charles
微信公众号:
Charles的皮卡丘
'''
import os
import glob
import torch
import random
import numpy as np
import pandas as pd
from PIL import Image
from torch.utils.data import Dataset
from skimage.transform import resize
'''load data'''
class ImageFolder(Dataset):
def __init__... | [
"PIL.Image.open",
"random.shuffle",
"os.path.join",
"torch.from_numpy",
"pandas.read_excel",
"pandas.DataFrame",
"numpy.transpose",
"skimage.transform.resize"
] | [((843, 865), 'pandas.read_excel', 'pd.read_excel', (['labpath'], {}), '(labpath)\n', (856, 865), True, 'import pandas as pd\n'), ((1135, 1160), 'pandas.DataFrame', 'pd.DataFrame', (['self.labels'], {}), '(self.labels)\n', (1147, 1160), True, 'import pandas as pd\n'), ((1321, 1370), 'skimage.transform.resize', 'resize'... |
import argparse
import random
import json
from typing import List, Dict
import torch
from torch.utils.data import Dataset
from transformers import AutoTokenizer, Trainer, TrainingArguments, logging
from transformers import AutoModelForCausalLM
from tqdm import tqdm
from util.io import read_jsonl
from util.dl import s... | [
"util.io.read_jsonl",
"random.shuffle",
"transformers.TrainingArguments",
"argparse.ArgumentParser",
"torch.LongTensor",
"tqdm.tqdm",
"util.dl.fix_tokenizer",
"util.dl.set_random_seed",
"transformers.logging.set_verbosity_info",
"transformers.AutoModelForCausalLM.from_pretrained",
"transformers.... | [((2077, 2098), 'util.dl.set_random_seed', 'set_random_seed', (['seed'], {}), '(seed)\n', (2092, 2098), False, 'from util.dl import set_random_seed, fix_tokenizer\n'), ((2103, 2131), 'transformers.logging.set_verbosity_info', 'logging.set_verbosity_info', ([], {}), '()\n', (2129, 2131), False, 'from transformers import... |
"""Solr Tests"""
import os
import pytest
from hamcrest import contains_string, assert_that
# pylint: disable=redefined-outer-name
@pytest.fixture()
def get_ansible_vars(host):
"""Define get_ansible_vars"""
java_role = "file=../../../java/vars/main.yml name=java_role"
common_vars = "file=../../../common/var... | [
"hamcrest.contains_string",
"os.environ.get",
"pytest.mark.parametrize",
"hamcrest.assert_that",
"pytest.fixture"
] | [((132, 148), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (146, 148), False, 'import pytest\n'), ((1216, 1243), 'os.environ.get', 'os.environ.get', (['"""TEST_HOST"""'], {}), "('TEST_HOST')\n", (1230, 1243), False, 'import os\n'), ((1445, 1496), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""svc"... |
import os
import tensorflow as tf
from functools import partial
from random import shuffle
def _get_shard_dataset(record_path, split='train'):
pattern = os.path.join(record_path, split + "*")
files = tf.data.Dataset.list_files(pattern)
return files
def _decode_jpeg(image_buffer, size, scope=None):
w... | [
"tensorflow.data.experimental.map_and_batch",
"os.listdir",
"tensorflow.image.convert_image_dtype",
"random.shuffle",
"tensorflow.image.resize",
"tensorflow.io.parse_single_example",
"tensorflow.data.Options",
"os.path.join",
"tensorflow.data.Dataset.list_files",
"tensorflow.io.FixedLenFeature",
... | [((159, 197), 'os.path.join', 'os.path.join', (['record_path', "(split + '*')"], {}), "(record_path, split + '*')\n", (171, 197), False, 'import os\n'), ((210, 245), 'tensorflow.data.Dataset.list_files', 'tf.data.Dataset.list_files', (['pattern'], {}), '(pattern)\n', (236, 245), True, 'import tensorflow as tf\n'), ((95... |
# Generated by Django 1.11.8 on 2018-01-09 11:52
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('warehouse', '0013_auto_incrementing_batch_id'),
]
operations = [
migrations.AddField(
model_name='batch',
name='dag... | [
"django.db.models.CharField"
] | [((346, 397), 'django.db.models.CharField', 'models.CharField', ([], {'default': '"""no_slug"""', 'max_length': '(100)'}), "(default='no_slug', max_length=100)\n", (362, 397), False, 'from django.db import migrations, models\n')] |
# Author: <NAME>, <NAME>, 2008
# Clustering of position weight matrices based on
# "A Novel Bayesian DNA Motif Comparison Method for Clustering and Retrieval"
# Habib et al, 2008
# PLOS Computational Biology, Volume 4, Issue 2
import math
import numpy
import copy
import os,sys
SENSE = 0
ANTISENSE = 1
CUTOFF = {0.2... | [
"numpy.log",
"numpy.ones",
"math.log"
] | [((919, 933), 'numpy.log', 'numpy.log', (['E_p'], {}), '(E_p)\n', (928, 933), False, 'import numpy\n'), ((3223, 3243), 'numpy.ones', 'numpy.ones', (['A1.shape'], {}), '(A1.shape)\n', (3233, 3243), False, 'import numpy\n'), ((707, 730), 'math.log', 'math.log', (['(bp + 1e-07)', '(2)'], {}), '(bp + 1e-07, 2)\n', (715, 73... |
import glm
class Geometry():
@staticmethod
def index_from_coords(coord_list, level=0):
return sum(glm.i16vec3(coord_list) * glm.i16vec3(1,2,4) / 2**level)
@staticmethod
def coord_gen(num):
for i in range(8):
yield glm.vec3(num) % glm.vec3(2, 4, 8) // glm.vec3(1, 2, 4)
... | [
"glm.vec3",
"glm.i16vec3"
] | [((887, 905), 'glm.i16vec3', 'glm.i16vec3', (['coord'], {}), '(coord)\n', (898, 905), False, 'import glm\n'), ((908, 926), 'glm.i16vec3', 'glm.i16vec3', (['value'], {}), '(value)\n', (919, 926), False, 'import glm\n'), ((116, 139), 'glm.i16vec3', 'glm.i16vec3', (['coord_list'], {}), '(coord_list)\n', (127, 139), False,... |
from django.db import models
from djmoney.models.fields import MoneyField
import urllib, os
from urllib.parse import urlparse
# Create your models here.
class Game(models.Model):
'''
Stores game information such as name, description, release date, image etc...
'''
name = models.CharField(max_length=40... | [
"urllib.parse.urlparse",
"django.db.models.ForeignKey",
"os.path.join",
"django.db.models.BooleanField",
"djmoney.models.fields.MoneyField",
"django.db.models.ImageField",
"django.db.models.DateTimeField",
"django.db.models.URLField",
"django.db.models.CharField"
] | [((290, 321), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(40)'}), '(max_length=40)\n', (306, 321), False, 'from django.db import models\n'), ((341, 363), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {}), '()\n', (361, 363), False, 'from django.db import models\n'), ((382, 4... |
from django.core.management.base import BaseCommand
from django_q.models import Schedule
class Command(BaseCommand):
help = "Setups up all background tasks"
def handle(self, *args, **options):
Schedule.objects.get_or_create(
func='news.tasks.get_news',
schedule_type='D',
... | [
"django_q.models.Schedule.objects.get_or_create"
] | [((212, 306), 'django_q.models.Schedule.objects.get_or_create', 'Schedule.objects.get_or_create', ([], {'func': '"""news.tasks.get_news"""', 'schedule_type': '"""D"""', 'repeats': '(-1)'}), "(func='news.tasks.get_news', schedule_type=\n 'D', repeats=-1)\n", (242, 306), False, 'from django_q.models import Schedule\n'... |
# -*- coding: utf-8 -*-
from operator import attrgetter
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType
from pyangbind.lib.yangtypes import RestrictedClassType
from pyangbind.lib.yangtypes import TypedListType
from pyangbind.lib.yangtypes import YANGBool
from pyangbind.lib.yangtypes import YANGListTy... | [
"pyangbind.lib.yangtypes.YANGDynClass",
"__builtin__.property",
"collections.OrderedDict"
] | [((19765, 19821), '__builtin__.property', '__builtin__.property', (['_get_endpoint_id', '_set_endpoint_id'], {}), '(_get_endpoint_id, _set_endpoint_id)\n', (19785, 19821), False, 'import __builtin__\n'), ((19835, 19881), '__builtin__.property', '__builtin__.property', (['_get_config', '_set_config'], {}), '(_get_config... |
#! /usr/bin/env python3
"""
RobotPrint3D:
Control your robot remotely using the Mitsubishi R3 protocol.
Translate G-Code to Mitsubishi commands.
Usage:
main.py (-V | --validate) IN_FILE CONFIG_FILE [-o OUTPUT_FILE] [--quiet | --verbose]
main.py --gi --ip=<ip> --port=<port> --vid=<vid> --pid=<pid> [--f=<file>] ... | [
"logging.basicConfig",
"src.cli_commands.interactive_gcode.interactive_gcode",
"src.cli_commands.interactive_gcode_printer_only.interactive_gcode_printer_only",
"src.cli_commands.interactive_gcode_robot_only.interactive_gcode_robot_only",
"schema.Use",
"src.cli_commands.demo.demo_mode",
"src.cli_command... | [((2733, 2812), 'docopt.docopt', 'docopt', (['__doc__'], {'argv': 'argv', 'help': '(True)', 'version': '__version__', 'options_first': '(False)'}), '(__doc__, argv=argv, help=True, version=__version__, options_first=False)\n', (2739, 2812), False, 'from docopt import docopt\n'), ((3072, 3208), 'logging.basicConfig', 'l... |
import logging
from io import BytesIO
import uvicorn
from fastapi import Body, Depends, FastAPI, File, Request, UploadFile
from sqlalchemy.orm import Session
from .database import SessionLocal, UserIn, add_user, delete_user, get_user, get_users
from .yolo_minimal.detect import detect_init, detect, parse_name
app = ... | [
"logging.getLogger",
"fastapi.FastAPI",
"uvicorn.run",
"fastapi.Body",
"fastapi.File",
"fastapi.Depends"
] | [((320, 350), 'fastapi.FastAPI', 'FastAPI', ([], {'openapi_prefix': '"""/api"""'}), "(openapi_prefix='/api')\n", (327, 350), False, 'from fastapi import Body, Depends, FastAPI, File, Request, UploadFile\n'), ((360, 379), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (377, 379), False, 'import logging\n'),... |
'''
Created on Feb 8, 2017
@author: julien
'''
from inspect import isfunction, isclass
from random import Random
import numpy
rand = Random()
class ParameterConstraint(object):
levels = ['row', 'block', 'layer']
def __init__(self, namespace_id, name, value, **kwargs):
self.namespace_id = namesp... | [
"random.Random",
"inspect.isclass",
"inspect.isfunction",
"numpy.random.normal"
] | [((138, 146), 'random.Random', 'Random', ([], {}), '()\n', (144, 146), False, 'from random import Random\n'), ((1069, 1085), 'inspect.isclass', 'isclass', (['element'], {}), '(element)\n', (1076, 1085), False, 'from inspect import isfunction, isclass\n'), ((1089, 1108), 'inspect.isfunction', 'isfunction', (['element'],... |
from flask import Blueprint, session, render_template
from jinja2 import Template
from myapp.models import db, Person
blue = Blueprint("day02",__name__)
@blue.route('/set')
def set_session():
session['name'] = 'tom'
return "OK"
@blue.route('/get')
def get_session():
res = session.get('name',... | [
"flask.render_template",
"flask.session.get",
"myapp.models.Person.query.all",
"os.path.join",
"os.path.dirname",
"myapp.models.db.session.commit",
"myapp.models.db.create_all",
"myapp.models.db.drop_all",
"flask.Blueprint",
"myapp.models.db.session.add_all"
] | [((130, 158), 'flask.Blueprint', 'Blueprint', (['"""day02"""', '__name__'], {}), "('day02', __name__)\n", (139, 158), False, 'from flask import Blueprint, session, render_template\n'), ((301, 326), 'flask.session.get', 'session.get', (['"""name"""', '"""游客"""'], {}), "('name', '游客')\n", (312, 326), False, 'from flask i... |
import asyncio
import datetime
import io
import textwrap
import TagScriptEngine
import discord
from discord.ext import commands
import TagScriptEngine as tagscript
from pydantic import BaseModel
import utility.metrics
from utility.min import get_permissions
from core.abc import KarenMixin, KarenMetaClass
from adapte... | [
"TagScriptEngine.EmbedBlock",
"discord.ext.commands.MissingPermissions",
"TagScriptEngine.AnyBlock",
"textwrap.shorten",
"TagScriptEngine.MathBlock",
"io.BytesIO",
"TagScriptEngine.ReplaceBlock",
"discord.ext.commands.group",
"TagScriptEngine.StrfBlock",
"TagScriptEngine.MemberAdapter",
"discord... | [((7549, 7572), 'discord.ext.commands.Cog.listener', 'commands.Cog.listener', ([], {}), '()\n', (7570, 7572), False, 'from discord.ext import commands\n'), ((9195, 9213), 'discord.ext.commands.command', 'commands.command', ([], {}), '()\n', (9211, 9213), False, 'from discord.ext import commands\n'), ((9219, 9269), 'dis... |
import argparse
import pickle
import json
import nltk
def get_rare_words(counts, percent):
all_words = sorted([word for word in counts], key=lambda word: counts[word])
rare_words = all_words[:int(percent / 100 * len(all_words))]
stop_words = nltk.corpus.stopwords.words('english')
return set(rare_wor... | [
"pickle.dump",
"nltk.corpus.stopwords.words",
"argparse.ArgumentParser"
] | [((257, 295), 'nltk.corpus.stopwords.words', 'nltk.corpus.stopwords.words', (['"""english"""'], {}), "('english')\n", (284, 295), False, 'import nltk\n'), ((724, 749), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (747, 749), False, 'import argparse\n'), ((651, 677), 'pickle.dump', 'pickle.dum... |
from setuptools import find_packages, setup
from valohai_cli import __version__
setup(
name='valohai-cli',
version=__version__,
entry_points={'console_scripts': ['vh=valohai_cli.cli:cli']},
author='Valohai',
author_email='<EMAIL>',
license='MIT',
install_requires=[
'click>=7.0',
... | [
"setuptools.find_packages"
] | [((535, 575), 'setuptools.find_packages', 'find_packages', ([], {'include': "('valohai_cli*',)"}), "(include=('valohai_cli*',))\n", (548, 575), False, 'from setuptools import find_packages, setup\n')] |
# Generated by Django 2.1.1 on 2018-09-21 14:17
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Class',
fields=[
('id', models.AutoField(au... | [
"django.db.models.AutoField",
"django.db.models.CharField",
"django.db.models.BooleanField",
"django.db.models.IntegerField"
] | [((301, 394), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (317, 394), False, 'from django.db import migrations, models\... |
from django.urls import path
from .views import *
urlpatterns = [
path('', listarClientes, name="listar.cliente"),
path('cliente/novo/', armazenarCliente, name="novo.cliente"),
path('cliente/up/<int:id>', atualizarCliente, name="update.cliente"),
path('cliente/del/<int:id>', deletarCliente, name="delet... | [
"django.urls.path"
] | [((71, 118), 'django.urls.path', 'path', (['""""""', 'listarClientes'], {'name': '"""listar.cliente"""'}), "('', listarClientes, name='listar.cliente')\n", (75, 118), False, 'from django.urls import path\n'), ((124, 184), 'django.urls.path', 'path', (['"""cliente/novo/"""', 'armazenarCliente'], {'name': '"""novo.client... |
from django.contrib.auth import login, logout
from django.contrib.auth.views import LoginView, PasswordResetView
from django.shortcuts import redirect
from django.urls import reverse_lazy
from django.views import View
from django.views.generic import CreateView
from explorebg.explore_auth.forms import SignUpForm, Sign... | [
"django.shortcuts.redirect",
"django.contrib.auth.login",
"django.contrib.auth.logout",
"django.urls.reverse_lazy"
] | [((447, 467), 'django.urls.reverse_lazy', 'reverse_lazy', (['"""home"""'], {}), "('home')\n", (459, 467), False, 'from django.urls import reverse_lazy\n'), ((735, 755), 'django.urls.reverse_lazy', 'reverse_lazy', (['"""home"""'], {}), "('home')\n", (747, 755), False, 'from django.urls import reverse_lazy\n'), ((551, 58... |
from pocketsphinx import LiveSpeech
for phrase in LiveSpeech(): print(phrase) | [
"pocketsphinx.LiveSpeech"
] | [((50, 62), 'pocketsphinx.LiveSpeech', 'LiveSpeech', ([], {}), '()\n', (60, 62), False, 'from pocketsphinx import LiveSpeech\n')] |
"""ops.py"""
import math
import torch.nn.functional as F
def reconstruction_loss(x_recon, x, distribution):
r"""Calculate reconstruction loss for the general auto-encoder frameworks.
Args:
x_recon (Tensor): reconstructed images. arbitrary shape.
x (Tensor): target images. same shape with x_... | [
"torch.nn.functional.mse_loss",
"torch.nn.functional.binary_cross_entropy_with_logits",
"torch.nn.functional.sigmoid",
"math.log"
] | [((666, 684), 'torch.nn.functional.sigmoid', 'F.sigmoid', (['x_recon'], {}), '(x_recon)\n', (675, 684), True, 'import torch.nn.functional as F\n'), ((2830, 2859), 'math.log', 'math.log', (['(2 * math.pi * z_var)'], {}), '(2 * math.pi * z_var)\n', (2838, 2859), False, 'import math\n'), ((537, 603), 'torch.nn.functional.... |
#
#
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyri... | [
"itertools.chain",
"operator.attrgetter",
"ganeti.cmdlib.common.ShareAll",
"ganeti.cmdlib.common.CheckInstancesNodeGroups",
"ganeti.compat.partial",
"ganeti.cmdlib.instance_utils.NICListToTuple",
"ganeti.cmdlib.common.AnnotateDiskParams",
"ganeti.qlang.MakeSimpleFilter",
"ganeti.cmdlib.common.CheckI... | [((2094, 2104), 'ganeti.cmdlib.common.ShareAll', 'ShareAll', ([], {}), '()\n', (2102, 2104), False, 'from ganeti.cmdlib.common import ShareAll, GetWantedInstances, CheckInstanceNodeGroups, CheckInstancesNodeGroups, AnnotateDiskParams\n'), ((12526, 12571), 'ganeti.cmdlib.common.AnnotateDiskParams', 'AnnotateDiskParams',... |
# """
# The code will split the training set into k-fold for cross-validation
# """
# import os
# import numpy as np
# from sklearn.model_selection import StratifiedKFold
# root = './data/2018/MICCAI_BraTS_2018_Data_Training'
# valid_data_dir = './data/2018/MICCAI_BraTS_2018_Data_Validation'
# def wri... | [
"os.listdir",
"os.path.join",
"sklearn.model_selection.StratifiedKFold",
"numpy.array",
"sys.exit"
] | [((1652, 1670), 'os.listdir', 'os.listdir', (['backup'], {}), '(backup)\n', (1662, 1670), False, 'import os\n'), ((2857, 2917), 'sklearn.model_selection.StratifiedKFold', 'StratifiedKFold', ([], {'n_splits': '(5)', 'shuffle': '(True)', 'random_state': '(2018)'}), '(n_splits=5, shuffle=True, random_state=2018)\n', (2872... |
import cv2
import os
import sys
import unittest
if __name__ == '__main__':
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import leapvision.solmotiondetector
class PersonTrackerTest(unittest.TestCase):
def setUp(self):
self.video_path = os.path.join(
os.path.dirname(__file... | [
"unittest.main",
"os.path.dirname",
"cv2.VideoCapture"
] | [((1555, 1570), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1568, 1570), False, 'import unittest\n'), ((376, 409), 'cv2.VideoCapture', 'cv2.VideoCapture', (['self.video_path'], {}), '(self.video_path)\n', (392, 409), False, 'import cv2\n'), ((765, 798), 'cv2.VideoCapture', 'cv2.VideoCapture', (['self.video_pat... |
from datetime import datetime, date
from django.urls import reverse
from django.contrib.gis.geos import Point
from rest_framework.test import APITestCase
from rest_framework import status
from robber import expect
import pytz
from data.factories import PoliceUnitFactory, OfficerFactory, OfficerHistoryFactory, Office... | [
"datetime.datetime",
"django.urls.reverse",
"trr.factories.ActionResponseFactory",
"trr.factories.TRRFactory",
"django.contrib.gis.geos.Point",
"data.factories.PoliceUnitFactory",
"datetime.date",
"email_service.factories.EmailTemplateFactory",
"data.factories.OfficerHistoryFactory",
"robber.expec... | [((664, 722), 'data.factories.PoliceUnitFactory', 'PoliceUnitFactory', ([], {'unit_name': '"""001"""', 'description': '"""Unit 001"""'}), "(unit_name='001', description='Unit 001')\n", (681, 722), False, 'from data.factories import PoliceUnitFactory, OfficerFactory, OfficerHistoryFactory, OfficerAllegationFactory\n'), ... |
# -*- coding: utf-8 -*-
# !/usr/bin/env
# !/Library/Frameworks/Python.framework/Versions/3.8/bin/python3
# Draw radar charts from numerical serie
# Libraries
import matplotlib.pyplot as plt
# import sys
# print sys.executable
import pandas as pd
import numpy as np
from math import pi
# Tecnologie 4.0
def createspide... | [
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.clf",
"matplotlib.pyplot.yticks",
"pandas.DataFrame",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.subplot"
] | [((1106, 1440), 'pandas.DataFrame', 'pd.DataFrame', (["{'group': ['A', 'B', 'C', 'D'], 'Realtà Aumentata': [real_aug, 75, 30, 4],\n 'Integrazione Oriz/Vert': [int_vert, 50, 23, 24], 'Simulazione': [simul,\n 75, 9, 34], 'IoT': [iot, 15, 32, 14], 'Cloud': [cloud, 90, 33, 14],\n 'Cybersecurity': [cyber_sec, 30, 9... |
'''
Description:
Given the root node of a binary search tree, return the sum of values of all nodes with a value in the range [low, high].
Example 1:
Input: root = [10,5,15,3,7,null,18], low = 7, high = 15
Output: 32
Example 2:
Input: root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10
Output: 23
Co... | [
"unittest.main"
] | [((2631, 2646), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2644, 2646), False, 'import unittest\n')] |
# Copyright (c) 2012-2018, University of Strathclyde
# Authors: <NAME>
# License: BSD-3-Clause
"""
This is an examplar script to produce a plot of the cycle-averaged magnitude
and phase of the fields
"""
import sys
import numpy as np
from numpy import pi
from numpy import arange
import matplotlib.pyplot as plt
impor... | [
"matplotlib.pyplot.ylabel",
"puffdata.fdata",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"retrieve.getPow",
"matplotlib.pyplot.subplot",
"numpy.arange"
] | [((548, 562), 'puffdata.fdata', 'fdata', (['h5fname'], {}), '(h5fname)\n', (553, 562), False, 'from puffdata import fdata\n'), ((901, 948), 'retrieve.getPow', 'getPow', (['h5fname', 'cfr', 'dfr'], {'irtype': 'gav', 'qScale': '(0)'}), '(h5fname, cfr, dfr, irtype=gav, qScale=0)\n', (907, 948), False, 'from retrieve impor... |
# coding: utf-8
from django.contrib import admin
from django.utils.safestring import SafeString as _S
from django.utils.html import format_html
from ordered_model.admin import OrderedModelAdmin
from ordered_model.admin import OrderedTabularInline
from mptt.admin import MPTTModelAdmin
from mptt.forms import TreeNodeChoi... | [
"django.contrib.admin.register"
] | [((688, 720), 'django.contrib.admin.register', 'admin.register', (['models.MediaFile'], {}), '(models.MediaFile)\n', (702, 720), False, 'from django.contrib import admin\n'), ((1134, 1166), 'django.contrib.admin.register', 'admin.register', (['models.ImageMeta'], {}), '(models.ImageMeta)\n', (1148, 1166), False, 'from ... |
"""
Examples of using scalaps to analyze a sample of Reddit posts.
Derived from a Scala tutorial for working with the same data:
https://towardsdatascience.com/interactively-exploring-reddit-posts-using-basic-scala-in-your-browsers-f394843069de
"""
import urllib.request
from collections import namedtuple
from scalap... | [
"collections.namedtuple"
] | [((529, 590), 'collections.namedtuple', 'namedtuple', (['"""Post"""', "['subreddit', 'author', 'title', 'score']"], {}), "('Post', ['subreddit', 'author', 'title', 'score'])\n", (539, 590), False, 'from collections import namedtuple\n')] |
# -*- coding:utf-8 -*-
"""
发送邮件
"""
import email
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
class MailSender(object):
def __init__(self, host, username, password, to_emails, subject, content):
""" 初始化
@param host 邮件服务端host
... | [
"smtplib.SMTP",
"email.mime.multipart.MIMEMultipart",
"email.mime.text.MIMEText",
"email.utils.formatdate"
] | [((746, 770), 'email.mime.multipart.MIMEMultipart', 'MIMEMultipart', (['"""related"""'], {}), "('related')\n", (759, 770), False, 'from email.mime.multipart import MIMEMultipart\n'), ((928, 952), 'email.utils.formatdate', 'email.utils.formatdate', ([], {}), '()\n', (950, 952), False, 'import email\n'), ((1052, 1080), '... |