code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import torch
import torch.nn.functional as F
import numpy as np
import torch.nn
def dice_loss(input,target):
'''
make the soft dice loss
:param input: input
:param target: mask label
:return:
'''
input=torch.sigmoid(input)
smooth=1.0#for soft
flat_input=input.view(-1)
... | [
"torch.nn.functional.softmax",
"torch.sigmoid",
"torch.FloatTensor",
"torch.nn.functional.sigmoid",
"torch.pow",
"torch.gather",
"torch.clamp",
"torch.cat"
] | [((241, 261), 'torch.sigmoid', 'torch.sigmoid', (['input'], {}), '(input)\n', (254, 261), False, 'import torch\n'), ((1008, 1024), 'torch.nn.functional.sigmoid', 'F.sigmoid', (['input'], {}), '(input)\n', (1017, 1024), True, 'import torch.nn.functional as F\n'), ((1069, 1099), 'torch.cat', 'torch.cat', (['(1 - prob, pr... |
from StringIO import StringIO
from django.core.paginator import Paginator
from django.core.handlers.wsgi import WSGIRequest
from django.template import Template, Context
from django.http import HttpRequest as DjangoHttpRequest
from django.test import SimpleTestCase
from pagination.templatetags.pagination_tags import... | [
"StringIO.StringIO",
"django.template.Template",
"pagination.middleware.PaginationMiddleware"
] | [((2917, 2993), 'django.template.Template', 'Template', (['"""{% load pagination_tags %}{% autopaginate var 2 %}{% paginate %}"""'], {}), "('{% load pagination_tags %}{% autopaginate var 2 %}{% paginate %}')\n", (2925, 2993), False, 'from django.template import Template, Context\n'), ((3189, 3263), 'django.template.Tem... |
"""
This class is for the Enemy object. This class allows us to keep track of
an Enemy's id as well as it's health. An Enemy can lose its health.
The health of an Enemy can be as high as 1000 or as low as 0.
"""
import pygame
import math
import os
import random
class Enemy:
def __init__(self, id): # Constructor to... | [
"pygame.transform.flip",
"math.sqrt"
] | [((2123, 2165), 'math.sqrt', 'math.sqrt', (['(change[0] ** 2 + change[1] ** 2)'], {}), '(change[0] ** 2 + change[1] ** 2)\n', (2132, 2165), False, 'import math\n'), ((2468, 2517), 'pygame.transform.flip', 'pygame.transform.flip', (['self.image[i]', '(True)', '(False)'], {}), '(self.image[i], True, False)\n', (2489, 251... |
from django.test import TestCase
from django.test import Client
class Exercise4TestCase(TestCase):
def test_template_content(self):
"""Test that the index view returns the set names from the paramaters, or defaults to 'world'"""
c = Client()
response = c.get('/')
self.assertEqual(r... | [
"django.test.Client"
] | [((255, 263), 'django.test.Client', 'Client', ([], {}), '()\n', (261, 263), False, 'from django.test import Client\n')] |
"""
Credibility estimation example
"""
import pprint
from lunavl.sdk.faceengine.engine import VLFaceEngine
from lunavl.sdk.faceengine.setting_provider import DetectorType
from lunavl.sdk.image_utils.image import VLImage
from resources import EXAMPLE_1
def estimateCredibility():
"""
Estimate credibility of a ... | [
"lunavl.sdk.faceengine.engine.VLFaceEngine",
"lunavl.sdk.image_utils.image.VLImage.load"
] | [((347, 379), 'lunavl.sdk.image_utils.image.VLImage.load', 'VLImage.load', ([], {'filename': 'EXAMPLE_1'}), '(filename=EXAMPLE_1)\n', (359, 379), False, 'from lunavl.sdk.image_utils.image import VLImage\n'), ((397, 411), 'lunavl.sdk.faceengine.engine.VLFaceEngine', 'VLFaceEngine', ([], {}), '()\n', (409, 411), False, '... |
import connexion
import six
from tapi_server.models.inline_object1 import InlineObject1 # noqa: E501
from tapi_server.models.inline_object12 import InlineObject12 # noqa: E501
from tapi_server.models.inline_object13 import InlineObject13 # noqa: E501
from tapi_server.models.inline_object14 import InlineObject14 # ... | [
"tapi_server.database.connectivity_service",
"tapi_server.database.connection_end_point",
"tapi_server.database.connectivity_service_list",
"connexion.request.get_json",
"tapi_server.database.connection"
] | [((16687, 16715), 'connexion.request.get_json', 'connexion.request.get_json', ([], {}), '()\n', (16713, 16715), False, 'import connexion\n'), ((19291, 19319), 'connexion.request.get_json', 'connexion.request.get_json', ([], {}), '()\n', (19317, 19319), False, 'import connexion\n'), ((20099, 20127), 'connexion.request.g... |
import numpy as np
import scipy.stats as stats
from tbainfo import tbarequests
from sim_team import SimTeam
from match_score import Match, TeamScore, AllianceScore
import globals
CARGO_PT = 3
PANEL_PT = 2
AUTO1 = 3
AUTO2 = 6
CLIMB1 = 3
CLIMB2 = 6
CLIMB3 = 12
# returns a normal distribution truncated at the specified... | [
"numpy.mean",
"sim_team.SimTeam",
"globals.init",
"numpy.std",
"numpy.min",
"numpy.max",
"match_score.Match",
"scipy.stats.truncnorm",
"tbainfo.tbarequests",
"match_score.AllianceScore"
] | [((399, 472), 'scipy.stats.truncnorm', 'stats.truncnorm', (['((low - mean) / sd)', '((upp - mean) / sd)'], {'loc': 'mean', 'scale': 'sd'}), '((low - mean) / sd, (upp - mean) / sd, loc=mean, scale=sd)\n', (414, 472), True, 'import scipy.stats as stats\n'), ((3230, 3244), 'globals.init', 'globals.init', ([], {}), '()\n',... |
from pathlib import Path
import fpdf
from test.conftest import assert_pdf_equal
HERE = Path(__file__).resolve().parent
TEXT_SIZE, SPACING = 36, 1.15
LINE_HEIGHT = TEXT_SIZE * SPACING
TABLE_DATA = (
("First name", "Last name", "Age", "City"),
("Jules", "Smith", "34", "San Juan"),
("Mary", "Ramos", "45",... | [
"fpdf.FPDF",
"test.conftest.assert_pdf_equal",
"pathlib.Path"
] | [((501, 538), 'fpdf.FPDF', 'fpdf.FPDF', ([], {'format': '"""letter"""', 'unit': '"""pt"""'}), "(format='letter', unit='pt')\n", (510, 538), False, 'import fpdf\n'), ((2801, 2897), 'test.conftest.assert_pdf_equal', 'assert_pdf_equal', (['doc', "(HERE / 'ln_positioning_and_page_breaking_for_multicell.pdf')", 'tmp_path'],... |
#!/usr/bin/env python3
""" This script splits punctuations, digits and currency symbols
from the word.
Eg. "They have come!" he said reverently, gripping his
" They have come ! " he said reverently , gripping his
Eg. trans_to_tokenized_words.py <input-file> <output-file>
"""
import unicodedata
im... | [
"snor.SnorIter",
"sys.exit"
] | [((458, 469), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (466, 469), False, 'import sys\n'), ((1065, 1077), 'snor.SnorIter', 'SnorIter', (['fh'], {}), '(fh)\n', (1073, 1077), False, 'from snor import SnorIter\n')] |
# pylint: disable=no-self-use,invalid-name
import random
from os.path import join
import numpy
from deep_qa.data.dataset_readers.squad_sentence_selection_reader import SquadSentenceSelectionReader
from deep_qa.testing.test_case import DeepQaTestCase
from overrides import overrides
class TestSquadSentenceSelectionRea... | [
"deep_qa.data.dataset_readers.squad_sentence_selection_reader.SquadSentenceSelectionReader",
"os.path.join",
"numpy.random.seed",
"random.seed"
] | [((3453, 3470), 'random.seed', 'random.seed', (['(1337)'], {}), '(1337)\n', (3464, 3470), False, 'import random\n'), ((3479, 3502), 'numpy.random.seed', 'numpy.random.seed', (['(1337)'], {}), '(1337)\n', (3496, 3502), False, 'import numpy\n'), ((3586, 3603), 'random.seed', 'random.seed', (['(1337)'], {}), '(1337)\n', (... |
# Generated by Django 3.2.3 on 2021-06-27 17:28
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('wood', '0004_alter_woodmodel_surface'),
]
operations = [
migrations.RemoveField(
model_name='woodmodel',
name='surface',
... | [
"django.db.migrations.RemoveField"
] | [((229, 291), 'django.db.migrations.RemoveField', 'migrations.RemoveField', ([], {'model_name': '"""woodmodel"""', 'name': '"""surface"""'}), "(model_name='woodmodel', name='surface')\n", (251, 291), False, 'from django.db import migrations\n')] |
from enum import IntEnum
import struct
from .parser import MsftBandParser
from datetime import datetime
from .filetimes import datetime_to_filetime
class NotificationTypes(IntEnum):
"""Complete list of all Notification types"""
SMS = 1
Email = 2
IncomingCall = 11
AnsweredCall = 12
MissedCall =... | [
"datetime.datetime.now",
"struct.pack"
] | [((1009, 1023), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (1021, 1023), False, 'from datetime import datetime\n'), ((668, 709), 'struct.pack', 'struct.pack', (['"""<H"""', 'self.notification_type'], {}), "('<H', self.notification_type)\n", (679, 709), False, 'import struct\n')] |
import pkg_resources
import platform
import sys
def validate_python_version():
"""
Validate python interpreter version. Only 3.3+ allowed.
"""
if pkg_resources.parse_version(platform.python_version()) < pkg_resources.parse_version('3.3.0'):
print("Sorry, Python 3.3+ is required")
sys.e... | [
"setuptools.find_packages",
"os.path.join",
"os.path.dirname",
"pkg_resources.parse_version",
"sys.exit",
"platform.python_version"
] | [((468, 490), 'os.path.dirname', 'path.dirname', (['__file__'], {}), '(__file__)\n', (480, 490), False, 'from os import path\n'), ((221, 257), 'pkg_resources.parse_version', 'pkg_resources.parse_version', (['"""3.3.0"""'], {}), "('3.3.0')\n", (248, 257), False, 'import pkg_resources\n'), ((315, 326), 'sys.exit', 'sys.e... |
# -*- coding: utf-8 -*-
#
# 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
... | [
"lacquer.parser.parse",
"lacquer.expression_parser.parse"
] | [((13588, 13614), 'lacquer.parser.parse', 'parser.parse', (['"""select 123"""'], {}), "('select 123')\n", (13600, 13614), False, 'from lacquer import parser, expression_parser\n'), ((13700, 13718), 'lacquer.parser.parse', 'parser.parse', (['expr'], {}), '(expr)\n', (13712, 13718), False, 'from lacquer import parser, ex... |
#!/usr/bin/env python3
import subprocess
from subprocess import PIPE, Popen
import wandb
from collections import defaultdict
from statistics import mean
hname = subprocess.check_output("hostname -I|grep -oP '(?<=192.168.0.1)\d*'", shell=True).decode().strip()
project = f"monitor_health{hname}"
wandb.init(project=proje... | [
"subprocess.check_output",
"wandb.log",
"collections.defaultdict",
"wandb.init"
] | [((296, 323), 'wandb.init', 'wandb.init', ([], {'project': 'project'}), '(project=project)\n', (306, 323), False, 'import wandb\n'), ((594, 611), 'collections.defaultdict', 'defaultdict', (['dict'], {}), '(dict)\n', (605, 611), False, 'from collections import defaultdict\n'), ((1036, 1051), 'wandb.log', 'wandb.log', ([... |
import speech_recognition as sr
from os import system, _exit
from playsound import playsound
from random import randrange
from threading import Thread
from time import time, localtime
from datetime import date
from utilities import *
from dictionary import *
from tts import *
from stt import *
from google_functions im... | [
"random.randrange",
"datetime.date.today",
"speech_recognition.Recognizer",
"speech_recognition.Microphone",
"os._exit",
"os.system",
"time.localtime",
"time.time",
"threading.Thread"
] | [((4088, 4103), 'random.randrange', 'randrange', (['(0)', '(2)'], {}), '(0, 2)\n', (4097, 4103), False, 'from random import randrange\n'), ((4113, 4128), 'random.randrange', 'randrange', (['(0)', '(4)'], {}), '(0, 4)\n', (4122, 4128), False, 'from random import randrange\n'), ((5703, 5714), 'time.localtime', 'localtime... |
import threading
import grpc
import client.grpc_out.chat_pb2 as chat_proto
import client.grpc_out.chat_pb2_grpc as chat_grpc
class ChatClient:
"""
Класс - клиент чата.
В gRPC довольно легко работать с сервером, но мы сделаем прослойку, чтобы было совсем просто.
"""
def __init__(self, port=5000, ... | [
"client.grpc_out.chat_pb2.Empty",
"client.grpc_out.chat_pb2_grpc.ChattingStub",
"grpc.insecure_channel",
"threading.Thread",
"client.grpc_out.chat_pb2.Message"
] | [((501, 552), 'grpc.insecure_channel', 'grpc.insecure_channel', (['f"""{self._host}:{self._port}"""'], {}), "(f'{self._host}:{self._port}')\n", (522, 552), False, 'import grpc\n'), ((630, 667), 'client.grpc_out.chat_pb2_grpc.ChattingStub', 'chat_grpc.ChattingStub', (['self._channel'], {}), '(self._channel)\n', (652, 66... |
import torch.nn as nn
def conv_relu(in_channels, out_channels, kernel_size=3, stride=1,
padding=1, bias=True):
return [
nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size,
stride=stride, padding=padding, bias=bias),
nn.ReLU(inplace=True),
]
def conv_bn_rel... | [
"torch.nn.BatchNorm2d",
"torch.nn.ReLU",
"torch.nn.Dropout",
"torch.nn.Conv2d",
"torch.nn.BatchNorm1d",
"torch.nn.Linear"
] | [((148, 256), 'torch.nn.Conv2d', 'nn.Conv2d', (['in_channels', 'out_channels'], {'kernel_size': 'kernel_size', 'stride': 'stride', 'padding': 'padding', 'bias': 'bias'}), '(in_channels, out_channels, kernel_size=kernel_size, stride=stride,\n padding=padding, bias=bias)\n', (157, 256), True, 'import torch.nn as nn\n'... |
import gym
# 生成仿真环境
env = gym.make('Taxi-v3')
# 重置仿真环境
obs = env.reset()
# 渲染环境当前状态
#env.render()
m = env.observation_space.n # size of the state space
n = env.action_space.n # size of action space
print(m,n)
print("出租车问题状态数量为{:d},动作数量为{:d}。".format(m, n))
import numpy as np
# Intialize the Q-table an... | [
"numpy.mean",
"numpy.random.rand",
"numpy.argmax",
"numpy.any",
"numpy.max",
"numpy.sum",
"numpy.zeros",
"gym.make",
"numpy.var"
] | [((30, 49), 'gym.make', 'gym.make', (['"""Taxi-v3"""'], {}), "('Taxi-v3')\n", (38, 49), False, 'import gym\n'), ((357, 373), 'numpy.zeros', 'np.zeros', (['[m, n]'], {}), '([m, n])\n', (365, 373), True, 'import numpy as np\n'), ((377, 393), 'numpy.zeros', 'np.zeros', (['[m, n]'], {}), '([m, n])\n', (385, 393), True, 'im... |
# Generated by Django 2.2.2 on 2019-08-08 15:42
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tom_education', '0002_observationalert'),
]
operations = [
migrations.AddField(
model_name='asyncprocess',
name='pro... | [
"django.db.models.CharField"
] | [((350, 405), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(100)', 'null': '(True)'}), '(blank=True, max_length=100, null=True)\n', (366, 405), False, 'from django.db import migrations, models\n')] |
"""
The `methods` script contains functions for estimating the period of a star.
"""
import lightkurve as lk
import astropy.units as u
import numpy as np
from scipy.signal import find_peaks
from scipy import interpolate
from scipy.optimize import curve_fit
from scipy.ndimage import gaussian_filter1d
import warnings
i... | [
"scipy.optimize.curve_fit",
"jazzhands.WaveletTransformer",
"numpy.flip",
"numpy.mean",
"numpy.argmax",
"numpy.max",
"scipy.interpolate.interp1d",
"numpy.sum",
"lightkurve.LightCurve",
"numpy.correlate",
"numpy.nanmax",
"scipy.signal.find_peaks",
"numpy.nanmin",
"scipy.ndimage.gaussian_fil... | [((2827, 2995), 'scipy.optimize.curve_fit', 'curve_fit', (['_gaussian_fn', 'p', 'P'], {'p0': '[max_period, 0.1 * max_period, max_power]', 'bounds': '([lolim, 0.0, 0.9 * max_power], [uplim, 0.25 * max_period, 1.1 * max_power])'}), '(_gaussian_fn, p, P, p0=[max_period, 0.1 * max_period, max_power],\n bounds=([lolim, 0... |
import torch
import torch.nn as nn
from collections import OrderedDict
from PIL import Image
import numpy as np
def act(act_type, inplace=True, neg_slope=0.2, n_prelu=1):
# helper selecting activation
# neg_slope: for leakyrelu and init of prelu
# n_prelu: for p_relu num_parameters
act_type = act_type... | [
"torch.nn.BatchNorm2d",
"torch.nn.ReLU",
"torch.nn.LeakyReLU",
"torch.nn.Sequential",
"torch.nn.ReflectionPad2d",
"torch.load",
"torch.nn.Conv2d",
"torch.nn.InstanceNorm2d",
"torch.nn.PReLU",
"numpy.transpose",
"torch.nn.ReplicationPad2d"
] | [((2255, 2278), 'torch.nn.Sequential', 'nn.Sequential', (['*modules'], {}), '(*modules)\n', (2268, 2278), True, 'import torch.nn as nn\n'), ((2919, 3050), 'torch.nn.Conv2d', 'nn.Conv2d', (['in_nc', 'out_nc'], {'kernel_size': 'kernel_size', 'stride': 'stride', 'padding': 'padding', 'dilation': 'dilation', 'bias': 'bias'... |
import pytest
pytest.importorskip('numpy')
import numpy as np
import pytest
import dask.array as da
from dask.array.utils import assert_eq
def test_linspace():
darr = da.linspace(6, 49, chunks=5)
nparr = np.linspace(6, 49)
assert_eq(darr, nparr)
darr = da.linspace(1.4, 4.9, chunks=5, num=13)
np... | [
"dask.array.linspace",
"dask.array.indices",
"pytest.mark.xfail",
"dask.array.utils.assert_eq",
"numpy.indices",
"dask.array.arange",
"numpy.linspace",
"pytest.importorskip",
"pytest.raises",
"numpy.arange"
] | [((14, 42), 'pytest.importorskip', 'pytest.importorskip', (['"""numpy"""'], {}), "('numpy')\n", (33, 42), False, 'import pytest\n'), ((2153, 2290), 'pytest.mark.xfail', 'pytest.mark.xfail', ([], {'reason': '"""Casting floats to ints is not supported since edgebehavior is not specified or guaranteed by NumPy."""'}), "(r... |
from fairseq.models.roberta import RobertaModel
from examples.roberta.wsc import wsc_utils
roberta = RobertaModel.from_pretrained('checkpoints', 'checkpoint_best.pt', 'WSC/')
roberta.cuda()
nsamples, ncorrect = 0, 0
for sentence, label in wsc_utils.jsonl_iterator('WSC/val.jsonl', eval=True):
pred = roberta.disambi... | [
"fairseq.models.roberta.RobertaModel.from_pretrained",
"examples.roberta.wsc.wsc_utils.jsonl_iterator"
] | [((102, 175), 'fairseq.models.roberta.RobertaModel.from_pretrained', 'RobertaModel.from_pretrained', (['"""checkpoints"""', '"""checkpoint_best.pt"""', '"""WSC/"""'], {}), "('checkpoints', 'checkpoint_best.pt', 'WSC/')\n", (130, 175), False, 'from fairseq.models.roberta import RobertaModel\n'), ((240, 292), 'examples.r... |
# =============== 有序数组去重
from collections import OrderedDict
from typing import List
# Method 1 ----- new list
def removeDuplicates(test_list):
res = []
for i in test_list:
if i not in res:
res.append(i)
# Method 2 ----- new list
def removeDuplicates(test_list):
res = []
[res.app... | [
"collections.OrderedDict.fromkeys"
] | [((743, 774), 'collections.OrderedDict.fromkeys', 'OrderedDict.fromkeys', (['test_list'], {}), '(test_list)\n', (763, 774), False, 'from collections import OrderedDict\n')] |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2018-05-30 13:33
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('workish', '0002_auto_20180529_1945'),
]
operations = [
migrations.RenameFiel... | [
"django.db.migrations.RenameField",
"django.db.models.CharField"
] | [((299, 388), 'django.db.migrations.RenameField', 'migrations.RenameField', ([], {'model_name': '"""employees"""', 'old_name': '"""address"""', 'new_name': '"""email"""'}), "(model_name='employees', old_name='address', new_name\n ='email')\n", (321, 388), False, 'from django.db import migrations, models\n'), ((544, ... |
"""
Projects Views | Cannlytics API
Created: 4/21/2021
Updated: 6/12/2021
API to interface with laboratory projects.
"""
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
@api_view(['GET', 'POST', 'DELETE'])
def projects(request, format=Non... | [
"rest_framework.response.Response",
"rest_framework.decorators.api_view"
] | [((252, 287), 'rest_framework.decorators.api_view', 'api_view', (["['GET', 'POST', 'DELETE']"], {}), "(['GET', 'POST', 'DELETE'])\n", (260, 287), False, 'from rest_framework.decorators import api_view\n'), ((501, 572), 'rest_framework.response.Response', 'Response', (["{'error': 'not_implemented'}"], {'content_type': '... |
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sn
import pandas as pd
import os
from scipy.stats import chi2_contingency
def chi_squared_yates(
no_Gold, no_Resections, no_No_Surgery,
no_Gold_absent_term, no_Resections_absent_term, no_No_Surgery_absent_t... | [
"matplotlib.pyplot.savefig",
"scipy.stats.chi2_contingency",
"seaborn.despine",
"matplotlib.pyplot.clf",
"os.path.join",
"seaborn.heatmap",
"matplotlib.pyplot.axis",
"numpy.array",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.yticks",
"numpy.around",
"pandas.DataFrame",
"matplotlib.pyplot.... | [((1095, 1116), 'scipy.stats.chi2_contingency', 'chi2_contingency', (['obs'], {}), '(obs)\n', (1111, 1116), False, 'from scipy.stats import chi2_contingency\n'), ((2516, 2651), 'numpy.array', 'np.array', (['[[no_Gold, no_No_Surgery + no_Resections], [no_Gold_absent_term, \n no_No_Surgery_absent_term + no_Resections_... |
import torch
import torch.nn as nn
from torch.nn import Parameter
import torch.nn.functional as F
from torch.autograd import Variable
class ST_LSTM(nn.Module):
def __init__(self, nodes, in_channel, out_channel, out = None,
forget_bias = 1.0, ln = True, first = False):
super(ST_LSTM, self)._... | [
"torch.tanh",
"torch.nn.Conv1d",
"torch.nn.BatchNorm2d",
"torch.nn.ReLU",
"torch.nn.ModuleList",
"torch.sigmoid",
"torch.nn.LayerNorm",
"torch.nn.Conv2d",
"torch.zeros",
"torch.cat"
] | [((582, 612), 'torch.nn.Conv1d', 'nn.Conv1d', (['out', 'out_channel', '(1)'], {}), '(out, out_channel, 1)\n', (591, 612), True, 'import torch.nn as nn\n'), ((636, 666), 'torch.nn.Conv1d', 'nn.Conv1d', (['out', 'out_channel', '(1)'], {}), '(out, out_channel, 1)\n', (645, 666), True, 'import torch.nn as nn\n'), ((690, 72... |
import numpy as np
from sklearn.preprocessing import PolynomialFeatures
from statsmodels.api import OLS
from predictions.utils.future import set_future_series
def polynomial_forecast(series, steps_ahead=3, freq='D', series_name='polynomial'):
"""
Function fits data into OLS.
INPUT:
:param series: p... | [
"predictions.utils.future.set_future_series",
"statsmodels.api.OLS",
"sklearn.preprocessing.PolynomialFeatures"
] | [((678, 710), 'sklearn.preprocessing.PolynomialFeatures', 'PolynomialFeatures', ([], {'degree': 'level'}), '(degree=level)\n', (696, 710), False, 'from sklearn.preprocessing import PolynomialFeatures\n'), ((1034, 1178), 'predictions.utils.future.set_future_series', 'set_future_series', ([], {'forecasted_values': 'predi... |
from urllib.parse import urljoin
import pytest
from nose.tools import eq_
from django.contrib.auth import get_user_model
from django.core.urlresolvers import reverse
from rest_framework import status
from linkanywhere.apps.base.constants import DRAFT, PUBLISHED
from linkanywhere.apps.links.models import Link
from .... | [
"django.contrib.auth.get_user_model",
"nose.tools.eq_",
"django.core.urlresolvers.reverse",
"pytest.mark.parametrize",
"linkanywhere.apps.links.models.Link.objects.count",
"linkanywhere.apps.links.models.Link.objects.get"
] | [((352, 368), 'django.contrib.auth.get_user_model', 'get_user_model', ([], {}), '()\n', (366, 368), False, 'from django.contrib.auth import get_user_model\n'), ((5301, 5425), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""publication_status, readable_publication_status"""', "[(PUBLISHED, 'published'), (DRA... |
# encoding: utf-8
import time
import hashlib
import hmac
def _sha256_hmac(key, data):
return hmac.new(str.encode(key, 'utf-8'), str.encode(data, 'utf-8'), hashlib.sha256).hexdigest()
def _do_sign(ak, sk, expiration, text):
sign_key_info = '<KEY>' % (ak, int(time.time()), expiration)
sign_key = _sha256_h... | [
"time.time"
] | [((270, 281), 'time.time', 'time.time', ([], {}), '()\n', (279, 281), False, 'import time\n')] |
from math import prod
def solve(inp):
bus_deps = [(int(x), idx) for idx, x in enumerate(inp.split(",")) if x != "x"]
# Extended Euclidean algorithm
# https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
invm = lambda a, b: 0 if a == 0 else 1 if b % a == 0 else b - invm(b % a, a) * b // a
# chinese rem... | [
"math.prod"
] | [((402, 434), 'math.prod', 'prod', (['[bs[0] for bs in bus_deps]'], {}), '([bs[0] for bs in bus_deps])\n', (406, 434), False, 'from math import prod\n')] |
from bs4 import BeautifulSoup
html = open('sample.html', 'r').read()
soup = BeautifulSoup(html, features="lxml")
for element in soup.find_all('a', href=True):
print (element['href'])
| [
"bs4.BeautifulSoup"
] | [((77, 113), 'bs4.BeautifulSoup', 'BeautifulSoup', (['html'], {'features': '"""lxml"""'}), "(html, features='lxml')\n", (90, 113), False, 'from bs4 import BeautifulSoup\n')] |
# ========== (c) <NAME> 3/8/21 ==========
import pandas as pd
import numpy as np
import scipy.stats
desired_width = 320
pd.set_option('display.max_columns', 20)
pd.set_option('display.width', desired_width)
# ==========================
# For datasets 1-3
# ==========================
df = pd.read_csv("data-vid/examp... | [
"utils.load_data",
"utils.symbol_dict_to_df",
"pandas.read_csv",
"pandas.set_option",
"utils.normalise_price",
"datetime.datetime.now",
"plotly.express.line",
"pandas.DataFrame",
"plotly.express.imshow",
"pandas.concat"
] | [((123, 163), 'pandas.set_option', 'pd.set_option', (['"""display.max_columns"""', '(20)'], {}), "('display.max_columns', 20)\n", (136, 163), True, 'import pandas as pd\n'), ((164, 209), 'pandas.set_option', 'pd.set_option', (['"""display.width"""', 'desired_width'], {}), "('display.width', desired_width)\n", (177, 209... |
# run export FLASK_ENV=development before running flask run
import datetime
import requests
from flask import Flask, redirect, render_template, request
from flask_sqlalchemy import SQLAlchemy
key = open("apikey.txt", "r").readline()
url = "https://api.openweathermap.org/data/2.5/weather?q={}&units=metric&APPID=" + ke... | [
"flask.render_template",
"flask.Flask",
"flask.request.form.get",
"flask.redirect",
"datetime.datetime.now",
"flask_sqlalchemy.SQLAlchemy"
] | [((328, 343), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (333, 343), False, 'from flask import Flask, redirect, render_template, request\n'), ((494, 509), 'flask_sqlalchemy.SQLAlchemy', 'SQLAlchemy', (['app'], {}), '(app)\n', (504, 509), False, 'from flask_sqlalchemy import SQLAlchemy\n'), ((1680, 1738... |
import re
def flag(value):
"convert value to integer bool type"
s = str(value).strip().lower()
is_true = s in "yes y true t on 1".split(' ')
return int(is_true)
def join(lst,dlm='',fmt="{0}",strip=True):
if strip:
lst = [x.strip() if hasattr(x,"strip") else x for x in lst]
return dlm.join([fmt.format(x) for x... | [
"re.split",
"re.subn"
] | [((549, 584), 're.subn', 're.subn', (['"""[$][$]"""', '"""_#D0LaR#_"""', 'fmt'], {}), "('[$][$]', '_#D0LaR#_', fmt)\n", (556, 584), False, 'import re\n'), ((591, 611), 're.subn', 're.subn', (['"""[$]"""', 'x', 'a'], {}), "('[$]', x, a)\n", (598, 611), False, 'import re\n'), ((618, 646), 're.subn', 're.subn', (['"""_#D0... |
import datetime
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import os
import shutil
import sys
import time
import pandas as pd
import pynder
import urllib.request
from pynput import keyboard
from pylab import rcParams
from config import FACEBOOK_AUTH_TOKEN, FACEBOOK_ID, RATING_THRESHOLD
# Itera... | [
"matplotlib.image.imread",
"time.sleep",
"pynder.Session",
"os.remove",
"matplotlib.pyplot.imshow",
"os.path.exists",
"pandas.read_pickle",
"matplotlib.pyplot.close",
"pandas.DataFrame",
"sys.stdout.flush",
"matplotlib.pyplot.get_current_fig_manager",
"os.path.splitext",
"shutil.copyfile",
... | [((753, 771), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (769, 771), False, 'import sys\n'), ((1124, 1153), 'matplotlib.pyplot.get_current_fig_manager', 'plt.get_current_fig_manager', ([], {}), '()\n', (1151, 1153), True, 'import matplotlib.pyplot as plt\n'), ((1805, 1824), 'matplotlib.pyplot.suptitle', ... |
from src.tac.core.wavenet_vocoder.models.wavenet import WaveNet
from warnings import warn
from src.tac.core.wavenet_vocoder.util import is_mulaw_quantize
def create_model(hparams, init=False):
if is_mulaw_quantize(hparams.input_type):
if hparams.out_channels != hparams.quantize_channels:
raise RuntimeError(
... | [
"src.tac.core.wavenet_vocoder.models.wavenet.WaveNet",
"src.tac.core.wavenet_vocoder.util.is_mulaw_quantize"
] | [((198, 235), 'src.tac.core.wavenet_vocoder.util.is_mulaw_quantize', 'is_mulaw_quantize', (['hparams.input_type'], {}), '(hparams.input_type)\n', (215, 235), False, 'from src.tac.core.wavenet_vocoder.util import is_mulaw_quantize\n'), ((411, 433), 'src.tac.core.wavenet_vocoder.models.wavenet.WaveNet', 'WaveNet', (['hpa... |
from django.urls import path
from . import views
app_name = "home"
urlpatterns = [
path("", views.IndexView.as_view(), name="index"),
path("discover/", views.DiscoverView.as_view(), name="discover"),
path("faq/", views.FAQView.as_view(), name="faq"),
path("playground/", views.PlayGroundView.as_view()... | [
"django.urls.path"
] | [((346, 434), 'django.urls.path', 'path', (['"""playground-response/"""', 'views.playground_response'], {'name': '"""playground-response"""'}), "('playground-response/', views.playground_response, name=\n 'playground-response')\n", (350, 434), False, 'from django.urls import path\n'), ((466, 580), 'django.urls.path'... |
#!/usr/bin/python
# Copyright (c) 2020, 2022 Oracle and/or its affiliates.
# This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Apache License v2.0
# See LICENSE.TXT for d... | [
"ansible.module_utils.basic.AnsibleModule",
"ansible_collections.oracle.oci.plugins.module_utils.oci_common_utils.get_common_arg_spec",
"ansible_collections.oracle.oci.plugins.module_utils.oci_resource_utils.get_custom_class"
] | [((15548, 15598), 'ansible_collections.oracle.oci.plugins.module_utils.oci_resource_utils.get_custom_class', 'get_custom_class', (['"""DrgAttachmentFactsHelperCustom"""'], {}), "('DrgAttachmentFactsHelperCustom')\n", (15564, 15598), False, 'from ansible_collections.oracle.oci.plugins.module_utils.oci_resource_utils imp... |
import requests
import json
# Cloudflare API
x_auth_email = ""
x_auth_key = ""
zone_identifier = ""
url = "https://api.cloudflare.com/client/v4/filters/validate-expr"
payload = json.dumps([{
"expression": '(http.request.uri.path contains "/clientareafake.php?incorrect=true")',
"description": "/clientareafake... | [
"json.dumps",
"requests.request"
] | [((180, 327), 'json.dumps', 'json.dumps', (['[{\'expression\':\n \'(http.request.uri.path contains "/clientareafake.php?incorrect=true")\',\n \'description\': \'/clientareafake.php\'}]'], {}), '([{\'expression\':\n \'(http.request.uri.path contains "/clientareafake.php?incorrect=true")\',\n \'description\':... |
from datetime import datetime
import peewee as pw
from envparse import env
from telegram.update import Update
env.read_envfile()
db = pw.SqliteDatabase(env("DATABASE_URL"))
def _utcnow():
return datetime.utcnow()
class BaseModel(pw.Model):
created = pw.DateTimeField(default=_utcnow)
modified = pw.Dat... | [
"peewee.CharField",
"datetime.datetime.utcnow",
"peewee.BigIntegerField",
"peewee.ForeignKeyField",
"peewee.IntegerField",
"envparse.env",
"peewee.DateTimeField",
"envparse.env.read_envfile"
] | [((112, 130), 'envparse.env.read_envfile', 'env.read_envfile', ([], {}), '()\n', (128, 130), False, 'from envparse import env\n'), ((155, 174), 'envparse.env', 'env', (['"""DATABASE_URL"""'], {}), "('DATABASE_URL')\n", (158, 174), False, 'from envparse import env\n'), ((204, 221), 'datetime.datetime.utcnow', 'datetime.... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import urllib.request as req
import urllib.parse as par
data = {}
data['cid'] = 497816
data['page'] = '2'
data['key'] = ''
data['language'] = '1'
data['gtk'] = '6'
data = par.urlencode(data).encode('ascii')
r = req.Request('http://www.dm5.com/chapterfun.ashx', data)
r.se... | [
"urllib.parse.urlencode",
"urllib.request.Request",
"urllib.request.urlopen"
] | [((260, 315), 'urllib.request.Request', 'req.Request', (['"""http://www.dm5.com/chapterfun.ashx"""', 'data'], {}), "('http://www.dm5.com/chapterfun.ashx', data)\n", (271, 315), True, 'import urllib.request as req\n'), ((593, 607), 'urllib.request.urlopen', 'req.urlopen', (['r'], {}), '(r)\n', (604, 607), True, 'import ... |
from setuptools import setup
setup(
name='padacioso',
version='0.1.1',
packages=['padacioso'],
url='https://github.com/OpenJarbas/padacioso',
license='apache-2.0',
author='jarbasai',
author_email='<EMAIL>',
install_requires=["simplematch"],
description='dead simple intent parser'
)
| [
"setuptools.setup"
] | [((30, 295), 'setuptools.setup', 'setup', ([], {'name': '"""padacioso"""', 'version': '"""0.1.1"""', 'packages': "['padacioso']", 'url': '"""https://github.com/OpenJarbas/padacioso"""', 'license': '"""apache-2.0"""', 'author': '"""jarbasai"""', 'author_email': '"""<EMAIL>"""', 'install_requires': "['simplematch']", 'de... |
# ##############################################################################
# Copyright © 2021 Univ Artois & CNRS, Exakis Nelite #
# #
# Permission is hereby granted, free of charge, to any person ... | [
"collections.defaultdict",
"autograph.core.style.TextPosition",
"autograph.core.style.TextStyle"
] | [((2259, 2276), 'collections.defaultdict', 'defaultdict', (['dict'], {}), '(dict)\n', (2270, 2276), False, 'from collections import defaultdict\n'), ((2943, 2954), 'autograph.core.style.TextStyle', 'TextStyle', ([], {}), '()\n', (2952, 2954), False, 'from autograph.core.style import TextStyle, TextPosition, PlotStyle, ... |
from pathlib import Path
from typing import Tuple
import re
from itertools import groupby
def find_suggestion_for_return(suggestions):
for s in suggestions:
if s.symbol_kind == "class-or-function":
return s
else:
return None
def annotate_line(line, suggestions):
... | [
"itertools.groupby",
"re.compile"
] | [((1836, 1859), 're.compile', 're.compile', (['"""\\\\)\\\\s*:$"""'], {}), "('\\\\)\\\\s*:$')\n", (1846, 1859), False, 'import re\n'), ((2406, 2438), 'itertools.groupby', 'groupby', (['sorted_suggestions', 'key'], {}), '(sorted_suggestions, key)\n', (2413, 2438), False, 'from itertools import groupby\n')] |
from datetime import datetime
from typing import Any, Dict, Iterable
from peewee import Check, DateTimeField, ForeignKeyField, PrimaryKeyField, TextField, fn
from playhouse.postgres_ext import BinaryJSONField
from andreas.db.model import Model
from andreas.models.server import Server
from andreas.models.user import U... | [
"peewee.Check",
"peewee.ForeignKeyField",
"peewee.TextField",
"peewee.PrimaryKeyField",
"peewee.DateTimeField"
] | [((450, 467), 'peewee.PrimaryKeyField', 'PrimaryKeyField', ([], {}), '()\n', (465, 467), False, 'from peewee import Check, DateTimeField, ForeignKeyField, PrimaryKeyField, TextField, fn\n'), ((492, 521), 'peewee.DateTimeField', 'DateTimeField', ([], {'default': 'fn.now'}), '(default=fn.now)\n', (505, 521), False, 'from... |
import torch.backends as backends
import torch.cuda as cuda
import torch.nn as nn
import torch.utils.checkpoint as torchcheckpoint
from typing import Callable, Any, Union, List
from __types import Module
# TODO: move feature maps out of VRAM
# - https://medium.com/syncedreview/how-to-train-a-very-large-and-deep-mo... | [
"torch.cuda.is_available",
"torch.utils.checkpoint.checkpoint_sequential",
"torch.cuda.empty_cache"
] | [((801, 820), 'torch.cuda.is_available', 'cuda.is_available', ([], {}), '()\n', (818, 820), True, 'import torch.cuda as cuda\n'), ((3747, 3834), 'torch.utils.checkpoint.checkpoint_sequential', 'torchcheckpoint.checkpoint_sequential', (['self.sequential', '(self.num_checkpoints + 1)', 'x'], {}), '(self.sequential, self.... |
#!/usr/bin/env python
import scapy.all as scapy
from scapy.layers import http
def sniff(interface):
scapy.sniff(iface=interface, store=False, prn=process_sniffed_packet,)
def get_login_info(packet):
if packet.haslayer(scapy.Raw):
load = packet[scapy.Raw].load
keywords = ["username", "user",... | [
"scapy.all.sniff"
] | [((107, 176), 'scapy.all.sniff', 'scapy.sniff', ([], {'iface': 'interface', 'store': '(False)', 'prn': 'process_sniffed_packet'}), '(iface=interface, store=False, prn=process_sniffed_packet)\n', (118, 176), True, 'import scapy.all as scapy\n')] |
# Code to split the dataset into train/validation/test.
import argparse
import os
import time
from collections import defaultdict
import math
import numpy as np
import csv
import hickle as hkl
import glob
from sklearn.model_selection import train_test_split
import pdb
import random
from generate_dat... | [
"sklearn.model_selection.train_test_split",
"csv.writer",
"numpy.random.seed",
"glob.glob"
] | [((360, 379), 'numpy.random.seed', 'np.random.seed', (['(123)'], {}), '(123)\n', (374, 379), True, 'import numpy as np\n'), ((426, 497), 'glob.glob', 'glob.glob', (['"""/data/INTERACTION-Dataset-DR-v1_1/processed_data/pkl/*ego*"""'], {}), "('/data/INTERACTION-Dataset-DR-v1_1/processed_data/pkl/*ego*')\n", (435, 497), F... |
# Generated by Django 3.2.4 on 2021-06-19 15:08
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('memetext', '0008_alter_controlannotation_s3_image'),
]
operations = [
migrations.AddField(
model_name='annotationbatch',
... | [
"django.db.models.TextField"
] | [((374, 414), 'django.db.models.TextField', 'models.TextField', ([], {'blank': '(True)', 'default': '""""""'}), "(blank=True, default='')\n", (390, 414), False, 'from django.db import migrations, models\n')] |
from estimator_adaptative import EstimatorAdaptative
from mpl_toolkits.mplot3d import Axes3D
from grid_search import GridSearch
import matplotlib.pyplot as plt
import matplotlib as mpl
from utils import *
import numpy as np
import os
import sys
data_path = '../../databases'
PlotsDirectory = '../plots/Week2/task2/'
if... | [
"os.path.exists",
"estimator_adaptative.EstimatorAdaptative",
"os.makedirs",
"numpy.array",
"matplotlib.pyplot.figure",
"numpy.meshgrid",
"matplotlib.pyplot.show"
] | [((325, 355), 'os.path.exists', 'os.path.exists', (['PlotsDirectory'], {}), '(PlotsDirectory)\n', (339, 355), False, 'import os\n'), ((361, 388), 'os.makedirs', 'os.makedirs', (['PlotsDirectory'], {}), '(PlotsDirectory)\n', (372, 388), False, 'import os\n'), ((449, 471), 'numpy.array', 'np.array', (['[1050, 1200]'], {}... |
# -*- coding: utf-8 -*-
# Copyright (c) 2012, <NAME>
# All rights reserved.
# This file is part of PyDSM.
# PyDSM is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at yo... | [
"numpy.abs",
"numpy.log",
"numpy.zeros",
"scipy.signal.lfilter",
"scipy.signal.zpk2tf",
"scipy.signal.tf2zpk",
"numpy.seterr"
] | [((2394, 2405), 'numpy.zeros', 'np.zeros', (['m'], {}), '(m)\n', (2402, 2405), True, 'import numpy as np\n'), ((2432, 2460), 'scipy.signal.lfilter', 'sp.signal.lfilter', (['b', 'a', 'ins'], {}), '(b, a, ins)\n', (2449, 2460), True, 'import scipy as sp\n'), ((2243, 2263), 'scipy.signal.zpk2tf', 'sp.signal.zpk2tf', (['*h... |
# Generated by Django 2.2.1 on 2019-10-24 17:25
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import simple_history.models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
... | [
"django.db.models.ForeignKey",
"django.db.models.IntegerField",
"django.db.models.BooleanField",
"django.db.models.AutoField",
"django.db.models.DateTimeField",
"django.db.migrations.swappable_dependency",
"django.db.models.CharField"
] | [((256, 313), 'django.db.migrations.swappable_dependency', 'migrations.swappable_dependency', (['settings.AUTH_USER_MODEL'], {}), '(settings.AUTH_USER_MODEL)\n', (287, 313), False, 'from django.db import migrations, models\n'), ((1722, 1790), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'm... |
# -*- coding: utf-8 -*-
import torch
import numpy as np
import torch.nn.functional as F
from nnlib.load_time_series import load_data
from nnlib.utils.general_utils import reshape_3d_rest
dtype = torch.float
device = torch.device("cpu")
# device = torch.device("conv1D_cuda:2") # Uncomment this to run on GPU
np.random.... | [
"nnlib.load_time_series.load_data",
"torch.nn.functional.conv1d",
"torch.from_numpy",
"nnlib.utils.general_utils.reshape_3d_rest",
"numpy.array",
"numpy.random.seed",
"torch.device"
] | [((217, 236), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (229, 236), False, 'import torch\n'), ((310, 329), 'numpy.random.seed', 'np.random.seed', (['(231)'], {}), '(231)\n', (324, 329), True, 'import numpy as np\n'), ((430, 448), 'nnlib.load_time_series.load_data', 'load_data', (['dataset'], {})... |
import requests
class Connection:
"""This class handles JSON RPC calls to a DERO daemon and DERO cli-wallet (running with the --rpc-server flag enabled)."""
def __init__(self,access_point_wallet="http://127.0.0.1:30309",access_point_daemon="http://127.0.0.1:30306"):
self.access_point_wallet=access_po... | [
"requests.post"
] | [((696, 775), 'requests.post', 'requests.post', (['(self.access_point_wallet + mode)'], {'headers': 'self.headers', 'json': 'data'}), '(self.access_point_wallet + mode, headers=self.headers, json=data)\n', (709, 775), False, 'import requests\n'), ((1028, 1107), 'requests.post', 'requests.post', (['(self.access_point_da... |
from .trrv1pr import TRRv1PR
from .trrv1 import TRRv1
from .trrv2 import TRRv2
from .trrv3 import TRRv3
from .trrv4 import TRRv4
from .trrv5 import TRRv5
from xbrl.xbrlerror import XBRLError
class TRRCollection:
def __init__(self):
self.registries = dict()
def addRegistry(self, registry):
se... | [
"xbrl.xbrlerror.XBRLError"
] | [((501, 608), 'xbrl.xbrlerror.XBRLError', 'XBRLError', (['"""unknownTransformationRegistry"""', "('Unsupported transformation registry: %s' % name.namespace)"], {}), "('unknownTransformationRegistry', \n 'Unsupported transformation registry: %s' % name.namespace)\n", (510, 608), False, 'from xbrl.xbrlerror import XB... |
# Generated by Django 3.1 on 2021-01-06 15:33
import django.core.validators
import django.db.models.deletion
from django.db import migrations
from django.db import models
import common.fields
class Migration(migrations.Migration):
initial = True
dependencies = [
("footnotes", "0001_initial"),
... | [
"django.db.models.OneToOneField",
"django.db.models.PositiveSmallIntegerField",
"django.db.models.TextField",
"django.db.models.ForeignKey"
] | [((6077, 6186), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'on_delete': 'django.db.models.deletion.PROTECT', 'to': '"""additional_codes.additionalcodetype"""'}), "(on_delete=django.db.models.deletion.PROTECT, to=\n 'additional_codes.additionalcodetype')\n", (6094, 6186), False, 'from django.db import ... |
import os
import cv2
import numpy as np
from PIL import Image
recognizer = cv2.face.LBPHFaceRecognizer_create()
path='dataSet'
def getImagesWithID(path):
imagepaths=[os.path.join(path,f) for f in os.listdir(path)]
faces=[]
IDs=[]
for imagepath in imagepaths:
faceImg=Image.open(imagepath).conv... | [
"os.listdir",
"PIL.Image.open",
"os.path.join",
"cv2.face.LBPHFaceRecognizer_create",
"cv2.imshow",
"os.path.split",
"numpy.array",
"cv2.destroyAllWindows",
"cv2.waitKey"
] | [((77, 113), 'cv2.face.LBPHFaceRecognizer_create', 'cv2.face.LBPHFaceRecognizer_create', ([], {}), '()\n', (111, 113), False, 'import cv2\n'), ((713, 736), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (734, 736), False, 'import cv2\n'), ((651, 664), 'numpy.array', 'np.array', (['IDs'], {}), '(IDs... |
from Footy.MatchStates import (MatchState,
Drawing,
TeamLeadByOne,
TeamExtendingLead,
TeamLosingLead,
TeamDeficitOfOne,
TeamE... | [
"Footy.MatchStates.MatchState"
] | [((402, 418), 'Footy.MatchStates.MatchState', 'MatchState', (['(0)', '(0)'], {}), '(0, 0)\n', (412, 418), False, 'from Footy.MatchStates import MatchState, Drawing, TeamLeadByOne, TeamExtendingLead, TeamLosingLead, TeamDeficitOfOne, TeamExtendingDeficit, TeamLosingDeficit\n')] |
"""
Evaluate CHAOS at a Ground Observatory
======================================
Compute a time series of the first time-derivative of the field components
(SV) given by CHAOS.
In this example the location of the ground observatory in Niemegk (Germany)
is used. Also, the spherical harmonic coefficients of the SV are... | [
"chaosmagpy.data_utils.timestamp",
"chaosmagpy.CHAOS.from_mat",
"matplotlib.pyplot.subplots",
"chaosmagpy.data_utils.mjd2000",
"matplotlib.pyplot.show"
] | [((435, 470), 'chaosmagpy.CHAOS.from_mat', 'cp.CHAOS.from_mat', (['"""CHAOS-6-x9.mat"""'], {}), "('CHAOS-6-x9.mat')\n", (452, 470), True, 'import chaosmagpy as cp\n'), ((976, 1011), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(3)'], {'figsize': '(12, 5)'}), '(1, 3, figsize=(12, 5))\n', (988, 1011), True, 'i... |
import logging
from banal import is_mapping, ensure_list
from pprint import pprint # noqa
from followthemoney import model
log = logging.getLogger(__name__)
DEFTAULT_IDENTIFIER = 'registrationNumber'
IDENTIFIERS = {
'TRADE_REGISTER': 'registrationNumber',
'AU-ABN': 'registrationNumber',
'PY-PGN': 'class... | [
"logging.getLogger",
"banal.ensure_list",
"followthemoney.model.get",
"banal.is_mapping",
"followthemoney.model.make_entity"
] | [((132, 159), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (149, 159), False, 'import logging\n'), ((913, 929), 'banal.is_mapping', 'is_mapping', (['data'], {}), '(data)\n', (923, 929), False, 'from banal import is_mapping, ensure_list\n'), ((1752, 1769), 'banal.is_mapping', 'is_mapping... |
import sys
input = sys.stdin.readline
### functions ###
# getDistance(char ch1, char ch2) returns the distance btw ch1, ch2
def getDistance(ch1,ch2):
x1, y1 = coord[ch1]
x2, y2 = coord[ch2]
return abs(x1-x2) + abs(y1-y2)
### main ###
# make "coordinate table" of alphabets
# EX. coord['q']=(0,0) , coord['m']=(2,6... | [
"sys.stdout.write"
] | [((1005, 1051), 'sys.stdout.write', 'sys.stdout.write', (["('%s %d\\n' % (word, distance))"], {}), "('%s %d\\n' % (word, distance))\n", (1021, 1051), False, 'import sys\n')] |
import os
import re
import urllib
import urlparse
import hashlib
import logging
from google.appengine.api import memcache
from google.appengine.api import urlfetch
from google.appengine.runtime import apiproxy_errors
import webapp2
# URLs that have absolute addresses
ABSOLUTE_URL_REGEX = r"(http(s?):)?//(?P<url>[^\... | [
"google.appengine.api.memcache.add",
"hashlib.sha256",
"google.appengine.api.urlfetch.fetch",
"logging.debug",
"logging.warning",
"logging.exception",
"os.path.dirname",
"urllib.urlencode",
"google.appengine.api.memcache.get",
"re.sub",
"logging.info",
"logging.error",
"urlparse.urlparse"
] | [((2631, 2662), 'urlparse.urlparse', 'urlparse.urlparse', (['accessed_url'], {}), '(accessed_url)\n', (2648, 2662), False, 'import urlparse\n'), ((2680, 2709), 'os.path.dirname', 'os.path.dirname', (['url_obj.path'], {}), '(url_obj.path)\n', (2695, 2709), False, 'import os\n'), ((3523, 3539), 'hashlib.sha256', 'hashlib... |
from sympy import symbols, Integer
from sympy.physics.quantum.dagger import Dagger
from sympy.physics.quantum.anticommutator import AntiCommutator as AComm
from sympy.physics.quantum.operator import Operator
a, b, c = symbols('abc')
A, B, C, D = symbols('ABCD', commutative=False)
def test_anticommutator():
ac ... | [
"sympy.symbols",
"sympy.physics.quantum.anticommutator.AntiCommutator",
"sympy.Integer",
"sympy.physics.quantum.dagger.Dagger"
] | [((221, 235), 'sympy.symbols', 'symbols', (['"""abc"""'], {}), "('abc')\n", (228, 235), False, 'from sympy import symbols, Integer\n'), ((249, 283), 'sympy.symbols', 'symbols', (['"""ABCD"""'], {'commutative': '(False)'}), "('ABCD', commutative=False)\n", (256, 283), False, 'from sympy import symbols, Integer\n'), ((32... |
import os
import time
from . import task
class CopyGradientsFromHPC(task.Task):
"""
Tar the waveforms on the HPC. This can easily take on hour.
"""
@property
def required_inputs(self):
return {"summed_kernel_directory"}
def check_pre_staging(self):
self._init_ssh_and_stfp_cli... | [
"os.path.exists",
"os.listdir",
"os.path.join"
] | [((366, 407), 'os.path.join', 'os.path.join', (['self.working_dir', '"""KERNELS"""'], {}), "(self.working_dir, 'KERNELS')\n", (378, 407), False, 'import os\n'), ((1395, 1434), 'os.listdir', 'os.listdir', (['self.local_kernel_directory'], {}), '(self.local_kernel_directory)\n', (1405, 1434), False, 'import os\n'), ((741... |
from django.contrib import admin
from .models import User , Advisor , Booking
# Register your models here.
admin.site.register(User)
admin.site.register(Advisor)
admin.site.register(Booking) | [
"django.contrib.admin.site.register"
] | [((107, 132), 'django.contrib.admin.site.register', 'admin.site.register', (['User'], {}), '(User)\n', (126, 132), False, 'from django.contrib import admin\n'), ((133, 161), 'django.contrib.admin.site.register', 'admin.site.register', (['Advisor'], {}), '(Advisor)\n', (152, 161), False, 'from django.contrib import admi... |
import csv
import os
from subprocess import call
# Opcodes list
opcodes_list = ['mov', 'push', 'call', 'pop', 'cmp', 'jz', 'lea', 'test', 'jmp', 'add', 'jnz', 'retn', 'xor', 'and', 'bt', 'fdivp', 'fild', 'fstcw', 'imul', 'int', 'nop', 'pushf', 'rdtsc', 'sbb', 'setb', 'setle', 'shld', 'std', '(bad)']
# Prepare feature... | [
"os.path.exists",
"os.listdir",
"csv.writer",
"os.path.join",
"os.path.isfile",
"subprocess.call"
] | [((561, 590), 'os.path.exists', 'os.path.exists', (['"""./check.csv"""'], {}), "('./check.csv')\n", (575, 590), False, 'import os\n'), ((765, 781), 'os.listdir', 'os.listdir', (['PATH'], {}), '(PATH)\n', (775, 781), False, 'import os\n'), ((826, 847), 'os.path.join', 'os.path.join', (['PATH', 'i'], {}), '(PATH, i)\n', ... |
#!/usr/bin/env python3
"""<NAME> (TGBTG)
Script to check softeare versions for fastp|fastqc|bwa|macs2|bedtools|home
Prints out a tsv with header- Name\tVersion\tBuild\tChannel
"""
import os
import sys
import subprocess
from optparse import OptionParser
def main():
usage = "USAGE: %prog -o [output tsv file]"
... | [
"subprocess.Popen",
"optparse.OptionParser",
"sys.exit"
] | [((336, 361), 'optparse.OptionParser', 'OptionParser', ([], {'usage': 'usage'}), '(usage=usage)\n', (348, 361), False, 'from optparse import OptionParser\n'), ((555, 567), 'sys.exit', 'sys.exit', (['(-1)'], {}), '(-1)\n', (563, 567), False, 'import sys\n'), ((769, 838), 'subprocess.Popen', 'subprocess.Popen', (['cmd'],... |
from wai.common.adams.imaging.locateobjects import LocatedObjects, LocatedObject
from wai.common.cli.options import TypedOption, FlagOption
from ....core.component import ProcessorComponent
from ....core.stream import ThenFunction, DoneFunction
from ....core.stream.util import RequiresNoFinalisation
from ....domain.im... | [
"wai.common.cli.options.TypedOption",
"wai.common.cli.options.FlagOption"
] | [((649, 742), 'wai.common.cli.options.TypedOption', 'TypedOption', (['"""--min-width"""'], {'type': 'int', 'help': '"""the minimum width of annotations to convert"""'}), "('--min-width', type=int, help=\n 'the minimum width of annotations to convert')\n", (660, 742), False, 'from wai.common.cli.options import TypedO... |
import xml.etree.ElementTree as ET
from bs4 import BeautifulSoup
import re
import os
import glob
from lxml import etree
import sys
from io import StringIO
import json
from rdflib import URIRef, BNode, Literal
from rdflib import Graph
g = Graph()
files = glob.glob("../../docs/data/*/files/*.xml")
prefix = ".//{http:/... | [
"xml.etree.ElementTree.parse",
"xml.etree.ElementTree.tostring",
"bs4.BeautifulSoup",
"rdflib.Graph",
"rdflib.Literal",
"xml.etree.ElementTree.register_namespace",
"rdflib.URIRef",
"glob.glob"
] | [((239, 246), 'rdflib.Graph', 'Graph', ([], {}), '()\n', (244, 246), False, 'from rdflib import Graph\n'), ((256, 298), 'glob.glob', 'glob.glob', (['"""../../docs/data/*/files/*.xml"""'], {}), "('../../docs/data/*/files/*.xml')\n", (265, 298), False, 'import glob\n'), ((672, 692), 'xml.etree.ElementTree.parse', 'ET.par... |
#!/usr/bin/env python3
# Usage: midigen.py <MIDI FILE> <OUTPUT FILE>
# Given a MIDI file, generate a corresponding function using MIDI_On, MIDI_Off, and HAL_Delay functions
# <NAME> and <NAME> 2020
from mido import MidiFile
from sys import argv
if (len(argv) < 3):
print("Usage: midigen.py <MIDI FILE> <OUTPUT FILE>... | [
"mido.MidiFile"
] | [((405, 424), 'mido.MidiFile', 'MidiFile', (['midi_file'], {}), '(midi_file)\n', (413, 424), False, 'from mido import MidiFile\n')] |
"""
Periodically start netdisco and extract naming info about the network.
"""
import threading
import os
import stat
import utils
import requests
import subprocess
import json
import time
BASE_BINARY_PATH = 'https://github.com/noise-lab/netdisco-python-wrapper/raw/master/release/device_identifier_{os}' # noqa
DO... | [
"json.loads",
"os.stat",
"utils.get_device_id",
"subprocess.Popen",
"requests.get",
"os.chmod",
"os.path.isfile",
"time.sleep",
"utils.safe_run",
"threading.Thread",
"utils.get_os",
"os.path.expanduser"
] | [((480, 494), 'utils.get_os', 'utils.get_os', ([], {}), '()\n', (492, 494), False, 'import utils\n'), ((587, 630), 'threading.Thread', 'threading.Thread', ([], {'target': 'self._start_thread'}), '(target=self._start_thread)\n', (603, 630), False, 'import threading\n'), ((1208, 1243), 'os.path.isfile', 'os.path.isfile',... |
# Generated by Django 3.2.3 on 2021-07-06 08:57
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... | [
"django.db.models.IntegerField",
"django.db.models.ForeignKey",
"django.db.models.BigAutoField",
"django.db.models.DateTimeField",
"django.db.migrations.swappable_dependency",
"django.db.models.CharField"
] | [((247, 304), 'django.db.migrations.swappable_dependency', 'migrations.swappable_dependency', (['settings.AUTH_USER_MODEL'], {}), '(settings.AUTH_USER_MODEL)\n', (278, 304), False, 'from django.db import migrations, models\n'), ((438, 534), 'django.db.models.BigAutoField', 'models.BigAutoField', ([], {'auto_created': '... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 7 14:29:19 2018
@author: Matthew
https://stackoverflow.com/questions/12014210/tkinter-app-adding-a-right-click-context-menu
"""
import tkinter # Tkinter -> tkinter in Python 3
class FancyListbox(tkinter.Listbox):
def __init__(self, parent, *args, **kwargs):
... | [
"tkinter.Menu",
"tkinter.Tk",
"tkinter.Listbox.__init__"
] | [((1080, 1092), 'tkinter.Tk', 'tkinter.Tk', ([], {}), '()\n', (1090, 1092), False, 'import tkinter\n'), ((322, 377), 'tkinter.Listbox.__init__', 'tkinter.Listbox.__init__', (['self', 'parent', '*args'], {}), '(self, parent, *args, **kwargs)\n', (346, 377), False, 'import tkinter\n'), ((405, 434), 'tkinter.Menu', 'tkint... |
# Copyright (c) 2022. Harvard University
#
# Developed by Harvard T.H. Chan School of Public Health
# (HSPH) and Research Software Engineering,
# Faculty of Arts and Sciences, Research Computing (FAS RC)
# Author: <NAME> (https://github.com/mbsabath)
#
# Licensed under the Apache License, Version 2.0 (the "Licens... | [
"unittest.main"
] | [((1358, 1373), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1371, 1373), False, 'import unittest\n')] |
# Generated by Django 3.1.13 on 2021-08-03 12:51
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('biserici', '0027_auto_20210803_1546'),
]
operations = [
migrations.RenameField(
model_name='historicalpicturainterioara',
o... | [
"django.db.migrations.RenameField"
] | [((229, 346), 'django.db.migrations.RenameField', 'migrations.RenameField', ([], {'model_name': '"""historicalpicturainterioara"""', 'old_name': '"""tehnica"""', 'new_name': '"""tehnica_pictura"""'}), "(model_name='historicalpicturainterioara', old_name=\n 'tehnica', new_name='tehnica_pictura')\n", (251, 346), False... |
# Author: Mr_Orange <<EMAIL>>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of Sick Beard.
#
# Sick Beard is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
... | [
"sickbeard.TORRENT_LABEL.lower",
"json.dumps",
"base64.b64encode",
"sickbeard.logger.log"
] | [((1172, 1244), 'json.dumps', 'json.dumps', (["{'method': 'auth.login', 'params': [self.password], 'id': 1}"], {}), "({'method': 'auth.login', 'params': [self.password], 'id': 1})\n", (1182, 1244), False, 'import json\n'), ((1647, 1737), 'json.dumps', 'json.dumps', (["{'method': 'core.add_torrent_magnet', 'params': [re... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
cleanDownload
~~~~~~~~~~~~~
Cli Entrance
:copyright: (c) 2019 by staugur.
:license: BSD 3-Clause, see LICENSE for more details.
"""
import os
from tool import rc, get_current_timestamp, timestamp_after_timestamp, try_request, Logger
logger = Logg... | [
"tool.timestamp_after_timestamp",
"tool.rc.hgetall",
"tool.rc.delete",
"os.listdir",
"argparse.ArgumentParser",
"tool.Logger",
"os.path.getctime",
"os.path.join",
"os.path.splitext",
"os.path.realpath",
"os.path.isfile",
"tool.get_current_timestamp",
"os.remove"
] | [((316, 329), 'tool.Logger', 'Logger', (['"""cli"""'], {}), "('cli')\n", (322, 329), False, 'from tool import rc, get_current_timestamp, timestamp_after_timestamp, try_request, Logger\n'), ((484, 507), 'os.listdir', 'os.listdir', (['downloadDir'], {}), '(downloadDir)\n', (494, 507), False, 'import os\n'), ((2271, 2296)... |
import torch
import torchvision.transforms as T
import numpy as np
import cv2
from PIL import Image
class DictBatch(object):
def __init__(self, data):
"""
:param data: list of Dict of Tensors.
"""
self.keys = list(data[0].keys())
values = list(zip(*[list(d.values()) for d ... | [
"torchvision.transforms.ToPILImage",
"numpy.array",
"torchvision.transforms.Resize",
"cv2.resize",
"torchvision.transforms.ToTensor",
"torchvision.transforms.Compose",
"torch.cat"
] | [((1766, 1779), 'torchvision.transforms.Compose', 'T.Compose', (['ts'], {}), '(ts)\n', (1775, 1779), True, 'import torchvision.transforms as T\n'), ((2752, 2763), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (2760, 2763), True, 'import numpy as np\n'), ((3459, 3492), 'cv2.resize', 'cv2.resize', (['image', '(new_h, ... |
import time
count=0
while count<10:
print(count)
count +=1
time.sleep(2)
print("Boom!")
| [
"time.sleep"
] | [((62, 75), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (72, 75), False, 'import time\n')] |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 15 15:19:40 2022
@author: turnerp
"""
import traceback
import numpy as np
from skimage import exposure
import cv2
import tifffile
import os
from glob2 import glob
import pandas as pd
import mat4py
import datetime
import json
import matplotlib.pyplot as plt
import hashli... | [
"glob2.glob",
"tifffile.TiffFile",
"json.loads",
"numpy.where",
"os.path.isfile",
"numpy.array",
"pandas.DataFrame",
"os.path.abspath"
] | [((5494, 5520), 'glob2.glob', 'glob', (["(path + '\\\\**\\\\*.tif')"], {}), "(path + '\\\\**\\\\*.tif')\n", (5498, 5520), False, 'from glob2 import glob\n'), ((1575, 1695), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['path', 'file_name', 'folder', 'parent_folder', 'posX', 'posY', 'posZ',\n 'laser', 'times... |
import numpy as np
import datetime
from ..nets.lstm_network import ActorCritic
import torch
import torch.optim as optim
from tqdm import trange
from tensorboardX import SummaryWriter
class Agent(object):
def __init__(self, agent_name, input_channels, network_parameters, ppo_parameters=None, n_actions=3):
... | [
"tensorboardX.SummaryWriter",
"torch.load",
"torch.min",
"numpy.random.randint",
"torch.cuda.is_available",
"torch.zeros",
"tqdm.trange",
"torch.clamp",
"torch.device"
] | [((1304, 1329), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (1327, 1329), False, 'import torch\n'), ((1352, 1395), 'torch.device', 'torch.device', (["('cuda' if use_cuda else 'cpu')"], {}), "('cuda' if use_cuda else 'cpu')\n", (1364, 1395), False, 'import torch\n'), ((3243, 3331), 'tqdm.tran... |
# Copyright 2019 Red Hat, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | [
"ansible.utils.display.Display",
"ansible.plugins.filter.ipaddr.ipaddr"
] | [((1569, 1578), 'ansible.utils.display.Display', 'Display', ([], {}), '()\n', (1576, 1578), False, 'from ansible.utils.display import Display\n'), ((4130, 4184), 'ansible.plugins.filter.ipaddr.ipaddr', 'ipaddr.ipaddr', ([], {'value': 'ip_data'}), '(value=ip_data, **kwargs_hash[ipversion])\n', (4143, 4184), False, 'from... |
# -*- coding: utf-8 -*-
import sys
from PySide2 import QtWidgets
from PySide2.QtTest import QTest
from numpy import pi
from Tests.GUI import gui_option # Set unit as [m]
from pyleecan.Classes.LamSlotMag import LamSlotMag
from pyleecan.Classes.SlotCirc import SlotCirc
from pyleecan.GUI.Dialog.DMachineSetup.SMSlot.WSl... | [
"pyleecan.Classes.LamSlotMag.LamSlotMag",
"PySide2.QtTest.QTest.keyClicks",
"pyleecan.Classes.SlotCirc.SlotCirc",
"pyleecan.GUI.Dialog.DMachineSetup.SMSlot.WSlotCirc.WSlotCirc.WSlotCirc",
"PySide2.QtWidgets.QApplication.instance",
"PySide2.QtWidgets.QApplication"
] | [((515, 545), 'pyleecan.Classes.LamSlotMag.LamSlotMag', 'LamSlotMag', ([], {'Rint': '(0.1)', 'Rext': '(0.2)'}), '(Rint=0.1, Rext=0.2)\n', (525, 545), False, 'from pyleecan.Classes.LamSlotMag import LamSlotMag\n'), ((575, 602), 'pyleecan.Classes.SlotCirc.SlotCirc', 'SlotCirc', ([], {'H0': '(0.01)', 'W0': '(0.045)'}), '(... |
"""Test that our pexer is capable of building .pex files with custom interpreters."""
import platform
import unittest
class CustomInterpreterTest(unittest.TestCase):
def testInterpreterIsPyPy(self):
"""Test that this is being run with PyPy."""
self.assertEqual('PyPy', platform.python_implementat... | [
"unittest.main",
"platform.python_implementation"
] | [((360, 375), 'unittest.main', 'unittest.main', ([], {}), '()\n', (373, 375), False, 'import unittest\n'), ((293, 325), 'platform.python_implementation', 'platform.python_implementation', ([], {}), '()\n', (323, 325), False, 'import platform\n')] |
#!/usr/bin/env python
# Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the LICENSE file in
# the root directory of this source tree.
import getpass
import json
import os
import socket
import StringIO
import sys
import tempfile
import unitt... | [
"StringIO.StringIO",
"json.loads",
"getpass.getuser",
"os.path.join",
"os.path.realpath",
"nuclide_server_manager.get_option_parser",
"tempfile.gettempdir",
"unittest.main",
"socket.gethostname",
"json.dump",
"nuclide_server_manager.NuclideServerManager"
] | [((543, 594), 'os.path.join', 'os.path.join', (['WORK_DIR', '"""nuclide_server_manager.py"""'], {}), "(WORK_DIR, 'nuclide_server_manager.py')\n", (555, 594), False, 'import os\n'), ((499, 525), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (515, 525), False, 'import os\n'), ((6657, 6672), ... |
# -*- coding: utf-8 -*-
"""Settings for python-dotenv"""
# Import standard library
from pathlib import Path
# Import from package
from dotenv import load_dotenv
env_path = Path('.') / '.env'
load_dotenv(verbose=True)
| [
"pathlib.Path",
"dotenv.load_dotenv"
] | [((195, 220), 'dotenv.load_dotenv', 'load_dotenv', ([], {'verbose': '(True)'}), '(verbose=True)\n', (206, 220), False, 'from dotenv import load_dotenv\n'), ((176, 185), 'pathlib.Path', 'Path', (['"""."""'], {}), "('.')\n", (180, 185), False, 'from pathlib import Path\n')] |
import numpy as np
from torch.utils.data import Dataset
class GraphDataset(Dataset):
def __init__(self, node_attributes, adj_matrices, labels):
super(GraphDataset, self).__init__()
num_nodes = []
for adj_matrix in adj_matrices:
num_nodes.append(adj_matrix.shape[0])
se... | [
"numpy.array",
"numpy.zeros"
] | [((531, 548), 'numpy.array', 'np.array', (['[label]'], {}), '([label])\n', (539, 548), True, 'import numpy as np\n'), ((828, 868), 'numpy.zeros', 'np.zeros', (['(self.max_size, self.max_size)'], {}), '((self.max_size, self.max_size))\n', (836, 868), True, 'import numpy as np\n'), ((1195, 1241), 'numpy.zeros', 'np.zeros... |
import csv, os
from py3dengine.utils.WavefrontOBJFormat.WavefrontOBJReader import WavefrontOBJReader
from dolphintracker.smooth_path.pool_camera import PoolCamera
from py3dengine.scenes.SceneClient import SceneClient
from py3dengine.scenes.Scene import Scene
from py3dengine.cameras.Ray import Ray, lin3d_distance
... | [
"pyforms.start_app",
"os.path.exists",
"os.makedirs",
"pyforms.controls.ControlFile",
"csv.writer",
"os.path.splitext",
"dolphintracker.smooth_path.pool_camera.PoolCamera",
"os.path.split",
"pyforms.controls.ControlText",
"py3dengine.cameras.Ray.Ray.FindClosestPointBetweenRays",
"py3dengine.util... | [((7614, 7674), 'pyforms.start_app', 'pyforms.start_app', (['SmoothPath'], {'geometry': '(100, 100, 900, 200)'}), '(SmoothPath, geometry=(100, 100, 900, 200))\n', (7631, 7674), False, 'import pyforms\n'), ((640, 665), 'pyforms.controls.ControlFile', 'ControlFile', (['"""Scene file"""'], {}), "('Scene file')\n", (651, 6... |
import socket
import os
os.environ['OPENCV_IO_MAX_IMAGE_PIXELS']=str(2**64)
import cv2
import numpy as np
import time
import warnings
from time import sleep
warnings.simplefilter("ignore", DeprecationWarning)
HOST = 'localhost'
PORT = 50505
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('So... | [
"socket.socket",
"cv2.destroyWindow",
"cv2.imshow",
"cv2.VideoCapture",
"warnings.simplefilter",
"cv2.waitKey",
"cv2.namedWindow"
] | [((165, 216), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""', 'DeprecationWarning'], {}), "('ignore', DeprecationWarning)\n", (186, 216), False, 'import warnings\n'), ((260, 309), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\... |
"""
A fake implementation of a target for the Vuforia Web Services API.
"""
import datetime
import io
import random
import statistics
import uuid
from typing import Optional, Union
from backports.zoneinfo import ZoneInfo
from PIL import Image, ImageStat
from mock_vws._constants import TargetStatuses
class Target: ... | [
"statistics.mean",
"PIL.Image.open",
"backports.zoneinfo.ZoneInfo",
"uuid.uuid4",
"datetime.datetime.now",
"PIL.ImageStat.Stat",
"datetime.timedelta",
"random.randint"
] | [((2783, 2798), 'backports.zoneinfo.ZoneInfo', 'ZoneInfo', (['"""GMT"""'], {}), "('GMT')\n", (2791, 2798), False, 'from backports.zoneinfo import ZoneInfo\n'), ((2813, 2842), 'datetime.datetime.now', 'datetime.datetime.now', ([], {'tz': 'gmt'}), '(tz=gmt)\n', (2834, 2842), False, 'import datetime\n'), ((2985, 3005), 'r... |
#!/usr/bin/env python
import argparse
import mdtraj as md
import os
from LLC_Membranes.llclib import topology
def initialize():
parser = argparse.ArgumentParser(description='Generate topology file from coordinate file.')
parser.add_argument('-g', '--gro', help='Name of coordinate file to write topology fil... | [
"LLC_Membranes.llclib.topology.fix_resnumbers",
"argparse.ArgumentParser",
"os.getcwd",
"os.path.dirname",
"LLC_Membranes.llclib.topology.Residue",
"mdtraj.load"
] | [((145, 233), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Generate topology file from coordinate file."""'}), "(description=\n 'Generate topology file from coordinate file.')\n", (168, 233), False, 'import argparse\n'), ((1950, 1962), 'mdtraj.load', 'md.load', (['gro'], {}), '(gro)... |
import json
from pymongo import MongoClient
# Load 'config.json' file
conf = json.load(
open("config.json", "r+")
)
# MongoDB Init
client = MongoClient(conf["mongodb"]["connection-string"])
db = client.MyEshop
promos = db.PromoCodes
# Create 'Promo' class
# It's main usecase is to make it easier
# to work wi... | [
"pymongo.MongoClient"
] | [((148, 197), 'pymongo.MongoClient', 'MongoClient', (["conf['mongodb']['connection-string']"], {}), "(conf['mongodb']['connection-string'])\n", (159, 197), False, 'from pymongo import MongoClient\n')] |
from netaddr import IPAddress
def test_reverse_dns_v4():
assert IPAddress('172.24.0.13').reverse_dns == '192.168.3.11.in-addr.arpa.'
def test_reverse_dns_v6():
assert IPAddress('fe80::feeb:daed').reverse_dns == ('d.e.a.d.b.e.e.f.0.0.0.0.0.0.0.0.'
'0.0.0... | [
"netaddr.IPAddress"
] | [((70, 94), 'netaddr.IPAddress', 'IPAddress', (['"""172.24.0.13"""'], {}), "('172.24.0.13')\n", (79, 94), False, 'from netaddr import IPAddress\n'), ((179, 207), 'netaddr.IPAddress', 'IPAddress', (['"""fe80::feeb:daed"""'], {}), "('fe80::feeb:daed')\n", (188, 207), False, 'from netaddr import IPAddress\n')] |
import os
import unittest
import time
from inspect import getmembers, isfunction
import src.aoc_2020_1b as aoc_2020_1b
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
class AnswerCorrect(unittest.TestCase):
methods = [member[1] for member in getmembers(aoc_2020_1b, isfunction)]
filename = os.path.joi... | [
"inspect.getmembers",
"os.path.join",
"time.process_time",
"unittest.main",
"os.path.abspath"
] | [((148, 173), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (163, 173), False, 'import os\n'), ((309, 356), 'os.path.join', 'os.path.join', (['THIS_DIR', '"""aoc_2020_1b_input.txt"""'], {}), "(THIS_DIR, 'aoc_2020_1b_input.txt')\n", (321, 356), False, 'import os\n'), ((1063, 1078), 'unittest.... |
import pytest
from datetime import datetime, timedelta
from lt_booking_scraper.utils import extract_number, validate_date, generate_headers
def test_generate_headers_accept():
header = generate_headers()
assert 'Accept' in header
def test_generate_headers_user_agent():
header = generate_headers()
a... | [
"lt_booking_scraper.utils.validate_date",
"lt_booking_scraper.utils.generate_headers",
"lt_booking_scraper.utils.extract_number",
"pytest.mark.parametrize",
"datetime.datetime.now",
"pytest.raises",
"datetime.timedelta"
] | [((352, 521), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""value, expected"""', "[('1.5 km from centre', 1.5), ('from centre 1.5 km', 1.5), (\n 'from 1.5 km centre', 1.5), ('1.5km from centre', 1.5)]"], {}), "('value, expected', [('1.5 km from centre', 1.5), (\n 'from centre 1.5 km', 1.5), ('from 1... |
import re
from lib import get_lines
def day_8():
screen = [['.' for _ in range(50)] for _ in range(6)]
rect_cmd_regex = r'rect (?P<rows>[0-9]+)x(?P<cols>[0-9]+)'
rotate_cmd_regex = r'rotate (?P<dimension>[\w]+) (x|y)=(?P<index>[0-9]+) by (?P<amount>[0-9]+)'
for command in get_lines('input8.txt'):
... | [
"lib.get_lines",
"re.match"
] | [((294, 317), 'lib.get_lines', 'get_lines', (['"""input8.txt"""'], {}), "('input8.txt')\n", (303, 317), False, 'from lib import get_lines\n'), ((340, 373), 're.match', 're.match', (['rect_cmd_regex', 'command'], {}), '(rect_cmd_regex, command)\n', (348, 373), False, 'import re\n'), ((507, 542), 're.match', 're.match', ... |
import os
from package_name_map import cli
test_data_folder = os.path.relpath(os.path.join(os.path.dirname(__file__), "data"), os.getcwd())
def test_build_db():
cli.main(["mkdb", os.path.join(test_data_folder, "example.toml")])
assert os.path.isfile("package_name_map.db")
os.remove("package_name_map.db"... | [
"os.path.join",
"os.getcwd",
"os.path.isfile",
"os.path.dirname",
"os.remove"
] | [((129, 140), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (138, 140), False, 'import os\n'), ((247, 284), 'os.path.isfile', 'os.path.isfile', (['"""package_name_map.db"""'], {}), "('package_name_map.db')\n", (261, 284), False, 'import os\n'), ((289, 321), 'os.remove', 'os.remove', (['"""package_name_map.db"""'], {}), "... |