code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import unittest
from hiveengine.tokens import Tokens
class Testcases(unittest.TestCase):
def test_tokens(self):
tokens = Tokens()
self.assertTrue(tok... | [
"hiveengine.tokens.Tokens"
] | [((284, 292), 'hiveengine.tokens.Tokens', 'Tokens', ([], {}), '()\n', (290, 292), False, 'from hiveengine.tokens import Tokens\n')] |
"""Loss layers for keypoints that can be inserted to modules"""
import torch
import torch.nn as nn
__all__ = ['WeightedMSELoss', 'HMFocalLoss']
def _sigmoid(x):
y = torch.clamp(x.sigmoid_(), min=1e-4, max=1-1e-4)
return y
class WeightedMSELoss(nn.Module):
"""Weighted MSE loss layer"""
def __init__(se... | [
"torch.log",
"torch.pow"
] | [((877, 905), 'torch.pow', 'torch.pow', (['(1 - gt)', 'self.beta'], {}), '(1 - gt, self.beta)\n', (886, 905), False, 'import torch\n'), ((926, 941), 'torch.log', 'torch.log', (['pred'], {}), '(pred)\n', (935, 941), False, 'import torch\n'), ((944, 975), 'torch.pow', 'torch.pow', (['(1 - pred)', 'self.alpha'], {}), '(1 ... |
import unittest
from github_network import GithubNetwork
class Test_GithubNetwork(unittest.TestCase):
def setUp(self):
pass
if __name__ == '__main__':
unittest.main()
| [
"unittest.main"
] | [((172, 187), 'unittest.main', 'unittest.main', ([], {}), '()\n', (185, 187), False, 'import unittest\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from .policies import *
from .objects import *
class BaseAgent(Object):
'''
QTable: Q Table
state: state of agent
last_state: last state
init_state: init. state
'''
env = None
n_steps = 0
total_reward = 0
def next_state(self, act... | [
"pandas.DataFrame",
"pickle.load",
"pickle.dump",
"pathlib.Path"
] | [((8003, 8064), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "('state', 'action', 'reward', 'state+')"}), "(columns=('state', 'action', 'reward', 'state+'))\n", (8015, 8064), True, 'import pandas as pd\n'), ((1624, 1651), 'pathlib.Path', 'pathlib.Path', (['f"""{name}.pkl"""'], {}), "(f'{name}.pkl')\n", (1636, 1... |
from py_compile import _get_default_invalidation_mode
import threading, queue, random
from requests_futures.sessions import FuturesSession
import discum
class banclass:
def __init__(self, user, guild, channel):
self.user = user
self.guild = guild
self.channel = channel
d... | [
"requests_futures.sessions.FuturesSession",
"discum.Client",
"threading.Thread",
"queue.Queue",
"random.randint"
] | [((455, 486), 'discum.Client', 'discum.Client', ([], {'token': 'user_token'}), '(token=user_token)\n', (468, 486), False, 'import discum\n'), ((1861, 1874), 'queue.Queue', 'queue.Queue', ([], {}), '()\n', (1872, 1874), False, 'import threading, queue, random\n'), ((2398, 2414), 'requests_futures.sessions.FuturesSession... |
# requirements.txt:
# pyro 1.6.0
# torch 1.8.0
import pyro
from pyro.distributions import Normal,Gamma,InverseGamma,Bernoulli,Poisson
import matplotlib.pyplot as plt
# import pyro.poutine as poutine
pyro.set_rng_seed(101)
def normal_density_estimation(obs, N):
assert obs is None or N==obs.shape[0]
loc = pyro.... | [
"matplotlib.pyplot.show",
"pyro.distributions.Gamma",
"pyro.set_rng_seed",
"pyro.distributions.Normal",
"pyro.plate"
] | [((200, 222), 'pyro.set_rng_seed', 'pyro.set_rng_seed', (['(101)'], {}), '(101)\n', (217, 222), False, 'import pyro\n'), ((678, 688), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (686, 688), True, 'import matplotlib.pyplot as plt\n'), ((334, 346), 'pyro.distributions.Normal', 'Normal', (['(0)', '(1)'], {}), ... |
from orders.forms import OrderUpdateForm
from django.urls import path
from orders import views
app_name = 'orders'
urlpatterns = [
path('place/<int:sid>/<int:oid>', views.CreateOrder.as_view(), name='place'),
path('recommend/<str:plid>',
views.Recommend.recommendation_algo, name='recommend'),
path(... | [
"orders.views.CreateOrder.as_view",
"orders.views.MyOrders.as_view",
"django.urls.path",
"orders.views.OrderInvoice.as_view",
"orders.views.OrderDetails.as_view"
] | [((217, 305), 'django.urls.path', 'path', (['"""recommend/<str:plid>"""', 'views.Recommend.recommendation_algo'], {'name': '"""recommend"""'}), "('recommend/<str:plid>', views.Recommend.recommendation_algo, name=\n 'recommend')\n", (221, 305), False, 'from django.urls import path\n'), ((522, 590), 'django.urls.path'... |
#!/usr/bin/env python
import numpy as np
import tensorflow as tf
train_X = np.linspace(-1, 1, 100)
train_Y = 2 * train_X + np.random.randn(*train_X.shape) * 0.33 + 10
X = tf.placeholder("float")
Y = tf.placeholder("float")
w = tf.Variable(0.0, name="weight")
b = tf.Variable(0.0, name="bias")
cost_op = tf.square(Y -... | [
"tensorflow.initialize_all_variables",
"tensorflow.Variable",
"tensorflow.placeholder",
"tensorflow.Session",
"tensorflow.train.GradientDescentOptimizer",
"numpy.linspace",
"numpy.random.randn",
"tensorflow.mul"
] | [((77, 100), 'numpy.linspace', 'np.linspace', (['(-1)', '(1)', '(100)'], {}), '(-1, 1, 100)\n', (88, 100), True, 'import numpy as np\n'), ((174, 197), 'tensorflow.placeholder', 'tf.placeholder', (['"""float"""'], {}), "('float')\n", (188, 197), True, 'import tensorflow as tf\n'), ((202, 225), 'tensorflow.placeholder', ... |
"""Meteo-France generic test utils."""
import pytest
from tests.async_mock import patch
@pytest.fixture(autouse=True)
def patch_requests():
"""Stub out services that makes requests."""
patch_client = patch("homeassistant.components.meteo_france.meteofranceClient")
patch_weather_alert = patch(
"ho... | [
"pytest.fixture",
"tests.async_mock.patch"
] | [((92, 120), 'pytest.fixture', 'pytest.fixture', ([], {'autouse': '(True)'}), '(autouse=True)\n', (106, 120), False, 'import pytest\n'), ((211, 275), 'tests.async_mock.patch', 'patch', (['"""homeassistant.components.meteo_france.meteofranceClient"""'], {}), "('homeassistant.components.meteo_france.meteofranceClient')\n... |
import json
from enum import Enum
from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer
from channels.layers import get_channel_layer
class MessageType(Enum):
ERROR = (0,)
WARNING = (1,)
INFO = (2,)
SUCCESS = 3
def log(message, log_var, log_level):
chan... | [
"json.dumps",
"asgiref.sync.async_to_sync",
"channels.layers.get_channel_layer"
] | [((332, 351), 'channels.layers.get_channel_layer', 'get_channel_layer', ([], {}), '()\n', (349, 351), False, 'from channels.layers import get_channel_layer\n'), ((356, 395), 'asgiref.sync.async_to_sync', 'async_to_sync', (['channel_layer.group_send'], {}), '(channel_layer.group_send)\n', (369, 395), False, 'from asgire... |
from serif.theory.enumerated_type import MentionType
from serif.theory.mention import Mention
from serif.theory.parse import Parse
from serif.theory.serif_sequence_theory import SerifSequenceTheory
from serif.xmlio import _SimpleAttribute, _ReferenceAttribute, _ChildTheoryElementList
class MentionSet(SerifSequenceThe... | [
"serif.theory.mention.Mention",
"serif.xmlio._SimpleAttribute",
"serif.xmlio._ChildTheoryElementList",
"serif.xmlio._ReferenceAttribute"
] | [((343, 366), 'serif.xmlio._SimpleAttribute', '_SimpleAttribute', (['float'], {}), '(float)\n', (359, 366), False, 'from serif.xmlio import _SimpleAttribute, _ReferenceAttribute, _ChildTheoryElementList\n'), ((384, 407), 'serif.xmlio._SimpleAttribute', '_SimpleAttribute', (['float'], {}), '(float)\n', (400, 407), False... |
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from django.views.generic import RedirectView
urlpatterns = [
url(r'^$', RedirectView.as_view(url='http://127.0.0.1:8000/login/')),
url(r'^admin/', admin.site.u... | [
"django.conf.urls.static.static",
"django.conf.urls.include",
"django.conf.urls.url",
"django.views.generic.RedirectView.as_view"
] | [((292, 323), 'django.conf.urls.url', 'url', (['"""^admin/"""', 'admin.site.urls'], {}), "('^admin/', admin.site.urls)\n", (295, 323), False, 'from django.conf.urls import url, include\n'), ((593, 656), 'django.conf.urls.static.static', 'static', (['settings.STATIC_URL'], {'document_root': 'settings.STATIC_ROOT'}), '(s... |
#!/usr/bin/env python3
import argparse
import sys
from ._const import AnsiBGColor, AnsiFGColor, AnsiStyle
from ._truecolor import tcolor
def parse_option() -> argparse.Namespace:
parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("string", help="strin... | [
"argparse.ArgumentParser"
] | [((196, 273), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'formatter_class': 'argparse.RawDescriptionHelpFormatter'}), '(formatter_class=argparse.RawDescriptionHelpFormatter)\n', (219, 273), False, 'import argparse\n')] |
# Copyright (c) OpenMMLab. All rights reserved.
import copy
import pytest
import torch
from mmcv import Config
from numpy.testing import assert_almost_equal
from mmpose.datasets import DATASETS
def test_NVGesture_dataset():
dataset = 'NVGestureDataset'
dataset_info = Config.fromfile(
'configs/_base... | [
"mmpose.datasets.DATASETS.get",
"numpy.testing.assert_almost_equal",
"torch.tensor",
"pytest.raises",
"copy.deepcopy",
"mmcv.Config.fromfile",
"torch.zeros"
] | [((380, 401), 'mmpose.datasets.DATASETS.get', 'DATASETS.get', (['dataset'], {}), '(dataset)\n', (392, 401), False, 'from mmpose.datasets import DATASETS\n'), ((582, 605), 'copy.deepcopy', 'copy.deepcopy', (['data_cfg'], {}), '(data_cfg)\n', (595, 605), False, 'import copy\n'), ((1662, 1703), 'numpy.testing.assert_almos... |
import base64
import gws
import gws.common.auth.method
import gws.common.auth.error
import gws.types as t
# @TODO support WWW-Authenticate at some point
class Config(t.WithType):
"""HTTP-basic authorization options"""
secure: bool = True #: use only with SSL
class Object(gws.common.auth.method.Object):... | [
"gws.as_bytes",
"gws.common.auth.error.LoginNotFound"
] | [((884, 921), 'gws.common.auth.error.LoginNotFound', 'gws.common.auth.error.LoginNotFound', ([], {}), '()\n', (919, 921), False, 'import gws\n'), ((1207, 1225), 'gws.as_bytes', 'gws.as_bytes', (['h[1]'], {}), '(h[1])\n', (1219, 1225), False, 'import gws\n')] |
# Generated by Django 3.1.5 on 2021-01-11 12:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pictures', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='image',
name='image',
fiel... | [
"django.db.models.ImageField"
] | [((322, 375), 'django.db.models.ImageField', 'models.ImageField', ([], {'default': '"""jpg"""', 'upload_to': '"""images/"""'}), "(default='jpg', upload_to='images/')\n", (339, 375), False, 'from django.db import migrations, models\n')] |
import operator
import threading
import functools
import itertools
import contextlib
import collections
import numpy as np
from ..autoray import (
get_lib_fn,
infer_backend,
get_dtype_name,
register_function,
astype,
)
_EMPTY_DICT = {}
class LazyArray:
"""A lazy array representing a shaped... | [
"itertools.chain",
"networkx.draw_networkx_nodes",
"matplotlib.colors.to_rgb",
"numpy.arange",
"networkx.DiGraph",
"functools.wraps",
"numpy.max",
"matplotlib.pyplot.close",
"threading.get_ident",
"opt_einsum.parser.parse_einsum_input",
"functools.reduce",
"numpy.log2",
"matplotlib.pyplot.sh... | [((20196, 20365), 'collections.defaultdict', 'collections.defaultdict', (['(lambda : materialize_identity)', '{LazyArray: materialize_larray, tuple: materialize_tuple, list:\n materialize_list, dict: materialize_dict}'], {}), '(lambda : materialize_identity, {LazyArray:\n materialize_larray, tuple: materialize_tu... |
#-*- coding:utf-8 -*-
import urllib.request
import ssl
from lxml import etree
url = 'https://movie.douban.com/top250'
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_1)
def fetch_page(url):
response = urllib.request.urlopen(url, context=context)
return response
def parse(url):
response = fetch_page(url)
... | [
"ssl.SSLContext",
"lxml.etree.HTML"
] | [((129, 165), 'ssl.SSLContext', 'ssl.SSLContext', (['ssl.PROTOCOL_TLSv1_1'], {}), '(ssl.PROTOCOL_TLSv1_1)\n', (143, 165), False, 'import ssl\n'), ((354, 370), 'lxml.etree.HTML', 'etree.HTML', (['page'], {}), '(page)\n', (364, 370), False, 'from lxml import etree\n'), ((869, 885), 'lxml.etree.HTML', 'etree.HTML', (['pag... |
import re
def is_url(possible_url):
regex = re.compile(r'[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)')
if re.search(regex, possible_url):
return True
else:
return False
def message_to_upper(message):
words = message.split()
rage_message = ''
for ... | [
"re.search",
"re.compile"
] | [((50, 150), 're.compile', 're.compile', (['"""[-a-zA-Z0-9@:%._\\\\+~#=]{2,256}\\\\.[a-z]{2,6}\\\\b([-a-zA-Z0-9@:%_\\\\+.~#?&//=]*)"""'], {}), "(\n '[-a-zA-Z0-9@:%._\\\\+~#=]{2,256}\\\\.[a-z]{2,6}\\\\b([-a-zA-Z0-9@:%_\\\\+.~#?&//=]*)'\n )\n", (60, 150), False, 'import re\n'), ((145, 175), 're.search', 're.search'... |
# Generated by Django 3.2.5 on 2021-09-20 13:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('payment', '0005_subscription'),
]
operations = [
migrations.AddField(
model_name='subscription',
name='customer_id',... | [
"django.db.models.CharField"
] | [((339, 410), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(200)', 'null': '(True)', 'verbose_name': '"""Customer ID"""'}), "(max_length=200, null=True, verbose_name='Customer ID')\n", (355, 410), False, 'from django.db import migrations, models\n')] |
"""
Copy of the find command. Missing lots of args
"""
import argparse
import os
import glob
import sys
def main():
"""
Main find functionality
"""
parser = argparse.ArgumentParser()
parser.add_argument('dir', type=str, default='/usr/local', nargs='?',
help='Path to director... | [
"os.path.exists",
"glob.glob",
"argparse.ArgumentParser",
"sys.exit"
] | [((174, 199), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (197, 199), False, 'import argparse\n'), ((601, 625), 'os.path.exists', 'os.path.exists', (['args.dir'], {}), '(args.dir)\n', (615, 625), False, 'import os\n'), ((669, 705), 'glob.glob', 'glob.glob', (['f"""{args.dir}/{args.name}"""']... |
import time
S = ")()())"
S1 = "()(()"
S2 = "(()()()"
S3 = "()()"
def solution(s):
if len(s) <= 1:
return 0
left = 0
right = 0
max_length = 0
for i in range(len(s)):
if s[i] == ')':
right += 1
else:
left += 1
if left == right:
max... | [
"time.time"
] | [((738, 749), 'time.time', 'time.time', ([], {}), '()\n', (747, 749), False, 'import time\n'), ((783, 794), 'time.time', 'time.time', ([], {}), '()\n', (792, 794), False, 'import time\n')] |
# Copyright (C) 2007-2010 by <NAME>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distrib... | [
"logging.getLogger",
"logging.NullHandler",
"socket.getfqdn",
"time.sleep",
"os.utime",
"datetime.datetime.now",
"random.random",
"os.unlink",
"os.getpid",
"os.stat",
"datetime.timedelta",
"random.randint",
"os.link"
] | [((2694, 2724), 'datetime.timedelta', 'datetime.timedelta', ([], {'seconds': '(15)'}), '(seconds=15)\n', (2712, 2724), False, 'import datetime\n'), ((2775, 2805), 'datetime.timedelta', 'datetime.timedelta', ([], {'seconds': '(10)'}), '(seconds=10)\n', (2793, 2805), False, 'import datetime\n'), ((3038, 3069), 'logging.g... |
"""This module contains classes of graphoelements.
These graphoelements can be generated by the package "detect".
"""
from copy import deepcopy
class Graphoelement:
"""Class containing all the events of one type in one dataset.
Attributes
----------
chan_name : ndarray (dtype='U')
list of c... | [
"copy.deepcopy"
] | [((685, 699), 'copy.deepcopy', 'deepcopy', (['self'], {}), '(self)\n', (693, 699), False, 'from copy import deepcopy\n')] |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from datetime import date
from dateutil import rrule
from decimal import Decimal as D
import mock
from django.test import TestCase
from ralph_sc... | [
"ralph_scrooge.models.ServiceEnvironment.objects.all",
"dateutil.rrule.rrule",
"ralph_scrooge.plugins.cost.pricing_service.PricingServicePlugin._get_service_extra_cost",
"ralph_scrooge.models.TeamCost",
"ralph_scrooge.tests.utils.factory.UsageTypeFactory",
"ralph_scrooge.plugins.cost.pricing_service.Prici... | [((914, 932), 'datetime.date', 'date', (['(2013)', '(10)', '(10)'], {}), '(2013, 10, 10)\n', (918, 932), False, 'from datetime import date\n'), ((954, 971), 'datetime.date', 'date', (['(2013)', '(10)', '(1)'], {}), '(2013, 10, 1)\n', (958, 971), False, 'from datetime import date\n'), ((991, 1009), 'datetime.date', 'dat... |
import cv2 as cv
import numpy as np
img = cv.imread('/home/praveen/Desktop/Python/Deep Learning/Open CV/Resources/Photos/cats.jpg')
cv.imshow('cats',img)
blank=np.zeros(img.shape,dtype='uint8')
cv.imshow('blank',blank)
gray=cv.cvtColor(img,cv.COLOR_BGR2GRAY)
cv.imshow('gray',gray)
blur = cv.GaussianBlur(gray,(5,5),... | [
"cv2.drawContours",
"cv2.threshold",
"cv2.Canny",
"cv2.imshow",
"numpy.zeros",
"cv2.waitKey",
"cv2.cvtColor",
"cv2.findContours",
"cv2.GaussianBlur",
"cv2.imread"
] | [((43, 142), 'cv2.imread', 'cv.imread', (['"""/home/praveen/Desktop/Python/Deep Learning/Open CV/Resources/Photos/cats.jpg"""'], {}), "(\n '/home/praveen/Desktop/Python/Deep Learning/Open CV/Resources/Photos/cats.jpg'\n )\n", (52, 142), True, 'import cv2 as cv\n'), ((133, 155), 'cv2.imshow', 'cv.imshow', (['"""ca... |
from gpiozero import TrafficLights, Button
from time import sleep
tl1 = TrafficLights(13, 19, 26)
tl2 = TrafficLights(21, 20, 16)
tl3 = TrafficLights(10, 9, 11)
tl4 = TrafficLights(7, 8, 25)
cross1 = TrafficLights(2, 3, 4)
cross2 = TrafficLights(18, 15, 14)
btn = Button(5)
def pressed():
print("Don't push the but... | [
"time.sleep",
"gpiozero.Button",
"gpiozero.TrafficLights"
] | [((73, 98), 'gpiozero.TrafficLights', 'TrafficLights', (['(13)', '(19)', '(26)'], {}), '(13, 19, 26)\n', (86, 98), False, 'from gpiozero import TrafficLights, Button\n'), ((105, 130), 'gpiozero.TrafficLights', 'TrafficLights', (['(21)', '(20)', '(16)'], {}), '(21, 20, 16)\n', (118, 130), False, 'from gpiozero import Tr... |
# 11/11/18
# Copy files from a CSV named files_map.csv to indicated paths and names.
import os
import shutil
import errno
import csv
import sys
if not os.path.isfile('file_map.csv'):
print('Please create a file named file_map.csv in the current directory.')
sys.exit()
with open('file_map.csv', 'r') as f:
... | [
"shutil.copy2",
"os.path.isfile",
"os.path.dirname",
"sys.exit",
"csv.reader"
] | [((153, 183), 'os.path.isfile', 'os.path.isfile', (['"""file_map.csv"""'], {}), "('file_map.csv')\n", (167, 183), False, 'import os\n'), ((268, 278), 'sys.exit', 'sys.exit', ([], {}), '()\n', (276, 278), False, 'import sys\n'), ((327, 370), 'csv.reader', 'csv.reader', (['f'], {'delimiter': '""","""', 'quotechar': '"""\... |
import os
import re
from pathlib import Path
from typing import Dict, List, Tuple, Match, Optional, Set
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from matplotlib.axes import Axes
from matplotlib.figure import Figure
from artificial_bias_experiments.evaluation.confidence_comparison.df_u... | [
"artificial_bias_experiments.evaluation.confidence_comparison.df_utils.get_df_diffs_between_true_conf_and_confidence_estimators_melted",
"re.compile",
"kbc_pul.data_structures.rule_wrapper.RuleWrapper.get_columns_header_without_amie",
"artificial_bias_experiments.evaluation.confidence_comparison.df_utils.Colu... | [((1668, 1694), 'seaborn.set', 'sns.set', ([], {'style': '"""whitegrid"""'}), "(style='whitegrid')\n", (1675, 1694), True, 'import seaborn as sns\n'), ((1720, 1782), 're.compile', 're.compile', (['"""s_prop([0-1]\\\\.?[0-9]*)_ns_prop([0-1]\\\\.?[0-9]*)"""'], {}), "('s_prop([0-1]\\\\.?[0-9]*)_ns_prop([0-1]\\\\.?[0-9]*)'... |
from setuptools import find_packages, setup
from disturbia.version import VERSION
with open("README.md", encoding="utf-8") as readme_file:
long_description = readme_file.read()
setup(
name="disturbia",
author="<NAME>",
description="Library for set of simple methods regarding distribution.",
long... | [
"setuptools.find_packages"
] | [((634, 677), 'setuptools.find_packages', 'find_packages', ([], {'exclude': "['tests.*', 'tests']"}), "(exclude=['tests.*', 'tests'])\n", (647, 677), False, 'from setuptools import find_packages, setup\n')] |
# -*- coding: utf-8 -*-
# Author: <NAME> <<EMAIL>>
#
# This program 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 your option) any later version.
#
# This program is... | [
"PyQt5.QtWidgets.QDialog.__init__",
"PyQt5.QtCore.pyqtSignal",
"logging.getLogger",
"logging.basicConfig"
] | [((1181, 1196), 'PyQt5.QtCore.pyqtSignal', 'pyqtSignal', (['str'], {}), '(str)\n', (1191, 1196), False, 'from PyQt5.QtCore import pyqtSignal\n'), ((1243, 1273), 'PyQt5.QtWidgets.QDialog.__init__', 'QDialog.__init__', (['self', 'parent'], {}), '(self, parent)\n', (1259, 1273), False, 'from PyQt5.QtWidgets import QDialog... |
# ---
# jupyter:
# jupytext:
# cell_markers: region,endregion
# formats: ipynb,py:light
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.4'
# jupytext_version: 1.1.1
# kernelspec:
# display_name: Python 3
# language: python
# name: pyt... | [
"sklearn.preprocessing.LabelEncoder",
"pandas.read_csv",
"sklearn.neighbors.KNeighborsClassifier",
"matplotlib.pyplot.annotate",
"numpy.array",
"nltk.corpus.stopwords.words",
"sklearn.feature_extraction.text.CountVectorizer",
"gensim.models.Word2Vec.load",
"IPython.display.Image",
"numpy.asarray",... | [((1526, 1660), 'pandas.read_csv', 'pd.read_csv', (['"""../twitter_data/train2017.tsv"""'], {'sep': '"""\t+"""', 'escapechar': '"""\\\\"""', 'engine': '"""python"""', 'names': "['ID_1', 'ID_2', 'Label', 'Text']"}), "('../twitter_data/train2017.tsv', sep='\\t+', escapechar='\\\\',\n engine='python', names=['ID_1', 'I... |
#!/usr/bin/env python
import sys
import rospy
import rosbag
from scipy.interpolate import interp1d
import matplotlib
import matplotlib.pylab as plt
matplotlib.rcParams['mathtext.fontset'] = 'custom'
matplotlib.rcParams['mathtext.rm'] = 'Bitstream Vera Sans'
matplotlib.rcParams['mathtext.it'] = 'Bitstream Vera Sans:i... | [
"matplotlib.pylab.figure",
"matplotlib.pylab.title",
"matplotlib.pylab.xlabel",
"scipy.interpolate.interp1d",
"rosbag.Bag",
"matplotlib.pylab.show",
"matplotlib.pylab.plot",
"matplotlib.pylab.close",
"matplotlib.pylab.ylabel"
] | [((2790, 2815), 'rosbag.Bag', 'rosbag.Bag', (['bag_path', '"""r"""'], {}), "(bag_path, 'r')\n", (2800, 2815), False, 'import rosbag\n'), ((3789, 3826), 'scipy.interpolate.interp1d', 'interp1d', (['battery.ts', 'battery.voltage'], {}), '(battery.ts, battery.voltage)\n', (3797, 3826), False, 'from scipy.interpolate impor... |
import numpy as np
import scipy.fftpack as fftpack
import audio_dspy as adsp
def tf2minphase(h, normalize=True):
"""Converts a transfer function to minimum phase
Parameters
----------
h : ndarray
Numpy array containing the original transfer function
Returns
-------
h_min : ndarra... | [
"numpy.mean",
"numpy.abs",
"audio_dspy.normalize",
"numpy.fft.fft",
"numpy.log",
"numpy.exp",
"numpy.linspace",
"numpy.fft.ifft"
] | [((964, 977), 'numpy.fft.fft', 'np.fft.fft', (['h'], {}), '(h)\n', (974, 977), True, 'import numpy as np\n'), ((986, 1014), 'numpy.linspace', 'np.linspace', (['(0)', '(2 * np.pi)', 'N'], {}), '(0, 2 * np.pi, N)\n', (997, 1014), True, 'import numpy as np\n'), ((1033, 1060), 'numpy.exp', 'np.exp', (['(-1.0j * (N / 2) * w... |
import tensorflow as tf
a = tf.constant(120, name="a")
b = tf.constant(130, name="b")
c = tf.constant(140, name="c")
v = tf.Variable(0, name="v" )
calc_op = a + b + c
assign_op = tf.assign(v, calc_op)
session = tf.Session()
session.run(assign_op)
o = session.run(v)
print(o)
| [
"tensorflow.assign",
"tensorflow.Session",
"tensorflow.constant",
"tensorflow.Variable"
] | [((28, 54), 'tensorflow.constant', 'tf.constant', (['(120)'], {'name': '"""a"""'}), "(120, name='a')\n", (39, 54), True, 'import tensorflow as tf\n'), ((59, 85), 'tensorflow.constant', 'tf.constant', (['(130)'], {'name': '"""b"""'}), "(130, name='b')\n", (70, 85), True, 'import tensorflow as tf\n'), ((90, 116), 'tensor... |
import os
import sys
from random import randrange
from azure.servicebus import ServiceBusClient
from azure.servicebus import Message
from azure.servicebus.common.constants import ReceiveSettleMode
def get_live_servicebus_config():
config = {}
config['hostname'] = os.environ['SERVICE_BUS_HOSTNAME']
config[... | [
"azure.servicebus.ServiceBusClient"
] | [((550, 724), 'azure.servicebus.ServiceBusClient', 'ServiceBusClient', ([], {'service_namespace': "sb_config['hostname']", 'shared_access_key_name': "sb_config['key_name']", 'shared_access_key_value': "sb_config['access_key']", 'debug': '(False)'}), "(service_namespace=sb_config['hostname'],\n shared_access_key_name... |
import time
from io import BytesIO
from multiprocessing import Process,Pipe
import threading
class mp4frag(threading.Thread):
'''
Creates a stream transform for piping a fmp4 (fragmented mp4) from ffmpeg.
Can be used to generate a fmp4 m3u8 HLS playlist and compatible file fragments.
Can also be used for storing p... | [
"threading.Thread.__init__",
"multiprocessing.Pipe",
"time.time",
"time.sleep"
] | [((1732, 1763), 'threading.Thread.__init__', 'threading.Thread.__init__', (['self'], {}), '(self)\n', (1757, 1763), False, 'import threading\n'), ((2855, 2872), 'multiprocessing.Pipe', 'Pipe', ([], {'duplex': '(True)'}), '(duplex=True)\n', (2859, 2872), False, 'from multiprocessing import Process, Pipe\n'), ((3265, 328... |
"""Load config from disk."""
def obtain_config(logging):
"""Import YAML based configs."""
import yaml
import sys
try:
with open('data/config.yaml', 'r') as myconfig:
config = yaml.load(myconfig.read(), Loader=yaml.FullLoader)
except FileNotFoundError:
from utils.create_... | [
"utils.create_config.create_config",
"sys.exit"
] | [((429, 444), 'utils.create_config.create_config', 'create_config', ([], {}), '()\n', (442, 444), False, 'from utils.create_config import TEMPLATE, create_config\n'), ((453, 464), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (461, 464), False, 'import sys\n'), ((592, 603), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
API for proxy
"""
from core import exceptions
from core.web import WebHandler
from service.proxy.proxy import proxy_srv
from service.proxy.serializers import ProxySerializer
from utils import log as logger
from utils.routes import route
from utils.tools import subdic... | [
"core.exceptions.ValidationError",
"service.proxy.serializers.ProxySerializer",
"utils.tools.subdict",
"service.proxy.proxy.proxy_srv.query",
"service.proxy.proxy.proxy_srv.new_proxy",
"service.proxy.proxy.proxy_srv.keys_by_dict",
"core.exceptions.NotFound",
"utils.log.exception",
"utils.routes.rout... | [((420, 441), 'utils.routes.route', 'route', (['"""/api/proxy/$"""'], {}), "('/api/proxy/$')\n", (425, 441), False, 'from utils.routes import route\n'), ((2285, 2313), 'utils.routes.route', 'route', (['"""/api/proxy/report/$"""'], {}), "('/api/proxy/report/$')\n", (2290, 2313), False, 'from utils.routes import route\n'... |
from flask_restx import Resource, Namespace # https://flask-restx.readthedocs.io/en/latest/quickstart.html
from core.mcq_generator import McqGenerator
import os
import copy
from db import DRVideoNotFound
from db.factory import create_repository
from settings import REPOSITORY_NAME, REPOSITORY_SETTINGS
# DB
repository... | [
"flask_restx.Namespace",
"db.factory.create_repository",
"core.mcq_generator.McqGenerator"
] | [((323, 378), 'db.factory.create_repository', 'create_repository', (['REPOSITORY_NAME', 'REPOSITORY_SETTINGS'], {}), '(REPOSITORY_NAME, REPOSITORY_SETTINGS)\n', (340, 378), False, 'from db.factory import create_repository\n'), ((397, 472), 'flask_restx.Namespace', 'Namespace', (['"""mcq_generator"""'], {'description': ... |
from infobip.clients import send_multiple_textual_sms_advanced
from infobip.api.model.sms.mt.send.textual.SMSAdvancedTextualRequest import SMSAdvancedTextualRequest
from infobip.api.model.sms.mt.send.SMSData import SMSData
from infobip.api.model.sms.mt.send.IsFlash import IsFlash
from infobip.api.model.sms.Destinat... | [
"infobip.api.model.sms.mt.send.IsFlash.IsFlash",
"infobip.api.model.sms.mt.send.textual.SMSAdvancedTextualRequest.SMSAdvancedTextualRequest",
"infobip.clients.send_multiple_textual_sms_advanced",
"infobip.api.model.sms.Destination.Destination",
"infobip.api.model.sms.mt.send.SMSData.SMSData"
] | [((400, 449), 'infobip.clients.send_multiple_textual_sms_advanced', 'send_multiple_textual_sms_advanced', (['configuration'], {}), '(configuration)\n', (434, 449), False, 'from infobip.clients import send_multiple_textual_sms_advanced\n'), ((460, 473), 'infobip.api.model.sms.Destination.Destination', 'Destination', ([]... |
import os
import argparse
import json
import logging
import traceback
from flask import Flask, redirect, request, jsonify, render_template
from pymongo import MongoClient
from telegram import Bot
dir_path = os.path.dirname(os.path.realpath(__file__))
# Logging
logger = logging.getLogger()
logger.setLevel(logging.INF... | [
"logging.getLogger",
"flask.render_template",
"argparse.ArgumentParser",
"flask.Flask",
"logging.Formatter",
"os.urandom",
"telegram.Bot",
"os.path.realpath",
"json.load",
"pymongo.MongoClient",
"traceback.print_exc"
] | [((273, 292), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (290, 292), False, 'import logging\n'), ((336, 398), 'logging.Formatter', 'logging.Formatter', (['"""%(asctime)s - %(levelname)s - %(message)s"""'], {}), "('%(asctime)s - %(levelname)s - %(message)s')\n", (353, 398), False, 'import logging\n'), (... |
import pytest
from radix import Bin, Num
def test_2s_compl():
n1 = Bin(-13)
assert n1.twos_compl() == '10011'
n2 = Bin(19)
assert n2.twos_compl() == '010011'
n3 = Bin(-10.75)
assert n3.twos_compl() == '10101.01'
def test_1s_compl():
n1 = Bin(-25)
assert n1.ones_compl() == '10011... | [
"radix.Bin.from_Num",
"radix.Bin",
"pytest.raises",
"radix.Num"
] | [((75, 83), 'radix.Bin', 'Bin', (['(-13)'], {}), '(-13)\n', (78, 83), False, 'from radix import Bin, Num\n'), ((132, 139), 'radix.Bin', 'Bin', (['(19)'], {}), '(19)\n', (135, 139), False, 'from radix import Bin, Num\n'), ((189, 200), 'radix.Bin', 'Bin', (['(-10.75)'], {}), '(-10.75)\n', (192, 200), False, 'from radix i... |
#!/usr/bin/env python3
import argparse
import json
import os
from pathlib import Path
FILENAME = "latest.json"
def main():
parser = argparse.ArgumentParser()
parser.add_argument("source", help="Path to directory of JSONs")
parser.add_argument("destination", help="Path to destination JSON")
args = par... | [
"os.listdir",
"argparse.ArgumentParser",
"pathlib.Path",
"json.load",
"json.dump"
] | [((139, 164), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (162, 164), False, 'import argparse\n'), ((352, 369), 'pathlib.Path', 'Path', (['args.source'], {}), '(args.source)\n', (356, 369), False, 'from pathlib import Path\n'), ((414, 433), 'os.listdir', 'os.listdir', (['dirname'], {}), '(di... |
import sys
sys.path.append("..")
from .Mesure import *
from Ordonnancement import *
import numpy as np
from scipy import stats
class EvalIRModel:
"""Evaluation d'un modèle d'appariement avec une mesure d'evaluation.
-----------------------------------------------------
Parameters:
- model : modè... | [
"numpy.square",
"numpy.array",
"numpy.sum",
"scipy.stats.ttest_ind",
"sys.path.append"
] | [((11, 32), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (26, 32), False, 'import sys\n'), ((2481, 2514), 'scipy.stats.ttest_ind', 'stats.ttest_ind', (['scores1', 'scores2'], {}), '(scores1, scores2)\n', (2496, 2514), False, 'from scipy import stats\n'), ((1952, 1967), 'numpy.array', 'np.array'... |
from api.dataset.models import DataSchema, Dataset
def verify_settings(model, p_key, settings):
details = eval(model).get(p_key)
for key, setting in settings.items():
print(getattr(details, key), setting)
setting = setting if setting else None
assert getattr(details, key) == setting
... | [
"api.dataset.models.Dataset",
"api.dataset.models.DataSchema",
"api.dataset.models.DataSchema.create_table"
] | [((417, 503), 'api.dataset.models.DataSchema.create_table', 'DataSchema.create_table', ([], {'read_capacity_units': '(1)', 'write_capacity_units': '(1)', 'wait': '(True)'}), '(read_capacity_units=1, write_capacity_units=1, wait\n =True)\n', (440, 503), False, 'from api.dataset.models import DataSchema, Dataset\n'), ... |
import functools
def my_map(fun, seq):
def apply_function_and_aggregate_as_list(accumulator, current_elt):
accumulator.append(fun(current_elt))
return accumulator
return functools.reduce(apply_function_and_aggregate_as_list, seq, [])
print("Puissances de 2 des nombres entre 1 à 9 avec my_ma... | [
"functools.reduce"
] | [((197, 260), 'functools.reduce', 'functools.reduce', (['apply_function_and_aggregate_as_list', 'seq', '[]'], {}), '(apply_function_and_aggregate_as_list, seq, [])\n', (213, 260), False, 'import functools\n')] |
import json
import torch
from torch.nn import functional as F
from torch.utils.data import DataLoader
from tqdm import tqdm
from helpers.text import devectorize
from helpers.training import load_checkpoint
from models.translate import prior_model_from_checkpoint
from modules.data.collates import Seq2SeqCollate
from m... | [
"modules.data.datasets.TranslationDataset",
"modules.data.collates.Seq2SeqCollate",
"models.translate.prior_model_from_checkpoint",
"torch.softmax",
"modules.data.datasets.SequenceDataset",
"torch.nn.functional.cross_entropy",
"torch.no_grad",
"helpers.training.load_checkpoint",
"helpers.text.devect... | [((2212, 2234), 'helpers.training.load_checkpoint', 'load_checkpoint', (['lm_cp'], {}), '(lm_cp)\n', (2227, 2234), False, 'from helpers.training import load_checkpoint\n'), ((2240, 2274), 'models.translate.prior_model_from_checkpoint', 'prior_model_from_checkpoint', (['lm_cp'], {}), '(lm_cp)\n', (2267, 2274), False, 'f... |
import requests
import json
from pprint import pprint
import sqlite3
from typing import Sequence, Union, Optional
import datetime
from datetime import datetime
from ..api import ApiConfig
ENDPOINT_BASE = 'https://data.jmnel.com/api/v1/'
ENDPOINT_AUTH = ENDPOINT_BASE + 'topk/authenticate?api={}'
ENDPOINT_EXPORT = ENDP... | [
"json.loads",
"requests.Session",
"datetime.datetime.strptime",
"json.dumps",
"datetime.datetime.strftime",
"pprint.pprint"
] | [((1387, 1405), 'requests.Session', 'requests.Session', ([], {}), '()\n', (1403, 1405), False, 'import requests\n'), ((2563, 2591), 'json.loads', 'json.loads', (['response.content'], {}), '(response.content)\n', (2573, 2591), False, 'import json\n'), ((2048, 2077), 'datetime.datetime.strftime', 'datetime.strftime', (['... |
from torchtext import data
from torch.utils.data import DataLoader
from graph import MTInferBatcher, get_mt_dataset, MTDataset, DocumentMTDataset
from modules import make_translate_infer_model
from utils import tensor_to_sequence, average_model
import torch as th
import argparse
import yaml
max_length = 1024
def run... | [
"graph.get_mt_dataset",
"torchtext.data.Field",
"argparse.ArgumentParser",
"utils.tensor_to_sequence",
"yaml.load",
"graph.DocumentMTDataset",
"graph.MTDataset",
"modules.make_translate_infer_model",
"torch.utils.data.DataLoader",
"torch.no_grad",
"torch.device"
] | [((3360, 3551), 'modules.make_translate_infer_model', 'make_translate_infer_model', (['vocab_sizes', 'dim_model', 'dim_ff', 'num_heads', 'n_layers', 'm_layers'], {'dropouti': 'dropouti', 'dropouth': 'dropouth', 'dropouta': 'dropouta', 'dropoutc': 'dropoutc', 'rel_pos': 'rel_pos'}), '(vocab_sizes, dim_model, dim_ff, num... |
#!/usr/bin/env python3
import requests
from SPARQLWrapper import SPARQLWrapper, JSON
endpoint = "https://query.wikidata.org/bigdata/namespace/wdq/sparqlba"
sparql = SPARQLWrapper(endpoint)
sparql.setQuery("""
SELECT DISTINCT ?floss ?label ?repo WHERE {
{
?floss p:P31/ps:P31/wdt:P279* wd:Q506883.
} Union {
... | [
"requests.get",
"SPARQLWrapper.SPARQLWrapper"
] | [((169, 192), 'SPARQLWrapper.SPARQLWrapper', 'SPARQLWrapper', (['endpoint'], {}), '(endpoint)\n', (182, 192), False, 'from SPARQLWrapper import SPARQLWrapper, JSON\n'), ((1367, 1388), 'requests.get', 'requests.get', (['license'], {}), '(license)\n', (1379, 1388), False, 'import requests\n')] |
import numpy as np
from scipy.spatial.distance import squareform
from random import randint
# there are more efficient algorithms for this
# https://people.csail.mit.edu/virgi/6.890/papers/APBP.pdf
def max_min(A, B):
'''max-min product of two square matrices
params:
A, B: NxN numpy arrays '''
asse... | [
"numpy.abs",
"scipy.spatial.distance.squareform",
"numpy.minimum",
"numpy.random.choice",
"numpy.max",
"numpy.diag",
"numpy.linalg.norm",
"numpy.all",
"random.randint"
] | [((1327, 1340), 'numpy.max', 'np.max', (['dists'], {}), '(dists)\n', (1333, 1340), True, 'import numpy as np\n'), ((360, 400), 'numpy.minimum', 'np.minimum', (['A[:, :, None]', 'B[None, :, :]'], {}), '(A[:, :, None], B[None, :, :])\n', (370, 400), True, 'import numpy as np\n'), ((1158, 1187), 'random.randint', 'randint... |
import functools
import FreeCAD
from PyFlow.Packages.AnimationFreeCAD.Class.FenetreErreur import FenetreErreur
from PyFlow.Packages.AnimationFreeCAD.Class.Mouvement import *
from PyFlow.Core import NodeBase
from PyFlow.Core.Common import *
from PySide import QtCore
class TranslationDecelere(NodeBase):
def __init... | [
"functools.partial",
"PySide.QtCore.QTimer",
"PyFlow.Packages.AnimationFreeCAD.Class.FenetreErreur.FenetreErreur"
] | [((1512, 1527), 'PySide.QtCore.QTimer', 'QtCore.QTimer', ([], {}), '()\n', (1525, 1527), False, 'from PySide import QtCore\n'), ((1584, 1629), 'functools.partial', 'functools.partial', (['self.mouvementDeceleration'], {}), '(self.mouvementDeceleration)\n', (1601, 1629), False, 'import functools\n'), ((918, 1013), 'PyFl... |
#!/usr/bin/env python3
'''
# tgf-cli.py
# interactive search of player_game_finder
# shows defense vs. position (team totals)
'''
import logging
import click
from nfl.tgf import TeamGameFinder
@click.command()
@click.option('-y', '--seas', default=None, type=click.IntRange(2010, 2021),
help='NFL ... | [
"logging.getLogger",
"click.Choice",
"click.IntRange",
"click.option",
"logging.Formatter",
"logging.FileHandler",
"nfl.tgf.TeamGameFinder",
"click.command",
"click.FloatRange"
] | [((200, 215), 'click.command', 'click.command', ([], {}), '()\n', (213, 215), False, 'import click\n'), ((459, 528), 'click.option', 'click.option', (['"""-o"""', '"""--opp"""'], {'type': 'str', 'default': 'None', 'help': '"""Team code"""'}), "('-o', '--opp', type=str, default=None, help='Team code')\n", (471, 528), Fa... |
import torch
import torchvision.models as models
import os,sys
import numpy as np
from matplotlib import pyplot as plt
from tqdm import tqdm
pwd = os.path.abspath('.')
MP3D_build_path = os.path.join(pwd, 'MP3D_Sim', 'build')
DASA_path = os.path.join(pwd, 'DASA')
sys.path.append(MP3D_build_path)
os.chdir(DA... | [
"numpy.radians",
"MatterSim.Simulator",
"torch.load",
"tqdm.tqdm",
"os.path.join",
"torch.stack",
"torch.cuda.set_device",
"os.chdir",
"numpy.array",
"numpy.max",
"torchvision.models.resnet152",
"numpy.min",
"os.path.abspath",
"torch.no_grad",
"numpy.load",
"sys.path.append"
] | [((156, 176), 'os.path.abspath', 'os.path.abspath', (['"""."""'], {}), "('.')\n", (171, 176), False, 'import os, sys\n'), ((196, 234), 'os.path.join', 'os.path.join', (['pwd', '"""MP3D_Sim"""', '"""build"""'], {}), "(pwd, 'MP3D_Sim', 'build')\n", (208, 234), False, 'import os, sys\n'), ((248, 273), 'os.path.join', 'os.... |
import myffmpeg.ffprobe as probe
import myffmpeg.convert as convert
from pytest import approx
def test_duration():
fnin = 'myvid.mp4'
fnout = 'myvid480.mp4'
orig_meta = probe.ffprobe(fnin)
orig_duration = float(orig_meta['streams'][0]['duration'])
convert(fnin, fnout, 480)
meta_480 = probe.f... | [
"pytest.approx",
"myffmpeg.convert",
"myffmpeg.ffprobe.ffprobe"
] | [((183, 202), 'myffmpeg.ffprobe.ffprobe', 'probe.ffprobe', (['fnin'], {}), '(fnin)\n', (196, 202), True, 'import myffmpeg.ffprobe as probe\n'), ((271, 296), 'myffmpeg.convert', 'convert', (['fnin', 'fnout', '(480)'], {}), '(fnin, fnout, 480)\n', (278, 296), True, 'import myffmpeg.convert as convert\n'), ((313, 333), 'm... |
from game import *
import ai
import pygame
if __name__ == '__main__':
# If this module had been imported, __name__ would be 'flappybird'.
# It was executed (e.g. by double-clicking the file), so call main.
# Do these now to save time
display_surface = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGH... | [
"pygame.display.set_mode",
"pygame.quit",
"ai.AI"
] | [((275, 323), 'pygame.display.set_mode', 'pygame.display.set_mode', (['(WIN_WIDTH, WIN_HEIGHT)'], {}), '((WIN_WIDTH, WIN_HEIGHT))\n', (298, 323), False, 'import pygame\n'), ((373, 391), 'ai.AI', 'ai.AI', ([], {'silent': '(True)'}), '(silent=True)\n', (378, 391), False, 'import ai\n'), ((507, 520), 'pygame.quit', 'pygam... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-BASE 蓝鲸基础平台 is licensed under the MIT License.
License for BK-BASE 蓝鲸基础平台:
------------------------------------------... | [
"django.utils.translation.ugettext_lazy"
] | [((1699, 1719), 'django.utils.translation.ugettext_lazy', '_', (['"""请求参数必须包含{param}"""'], {}), "('请求参数必须包含{param}')\n", (1700, 1719), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((1737, 1752), 'django.utils.translation.ugettext_lazy', '_', (['"""查看相关参数是否存在"""'], {}), "('查看相关参数是否存在')\n", (1738, ... |
#!/usr/bin/python3
import pyaudio
import os
import numpy as np
from scipy.interpolate import UnivariateSpline
from scipy.signal import butter, lfilter, filtfilt, resample
from scipy.optimize import curve_fit
import scipy as sp
import time
import pygame
from pygame.locals import *
from pygame import gfxdraw
from pygame ... | [
"numpy.log10",
"numpy.sqrt",
"pygame.init",
"SC18IS602B.SC18IS602B",
"numpy.column_stack",
"time.sleep",
"pygame.event.Event",
"pygame.time.set_timer",
"pygame.font.Font",
"RPi.GPIO.setmode",
"numpy.arange",
"numpy.mean",
"pygame.display.set_mode",
"os.putenv",
"numpy.fft.fft",
"pygame... | [((8367, 8384), 'pyaudio.PyAudio', 'pyaudio.PyAudio', ([], {}), '()\n', (8382, 8384), False, 'import pyaudio\n'), ((8581, 8616), 'MCP230XX.MCP230XX', 'MCP230XX', (['"""MCP23008"""'], {'i2cAddress': '(32)'}), "('MCP23008', i2cAddress=32)\n", (8589, 8616), False, 'from MCP230XX import MCP230XX\n'), ((8625, 8647), 'LTC138... |
# Generated by Django 3.2.6 on 2021-10-28 19:56
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('store', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='product',
name='avg_rate',
... | [
"django.db.models.DecimalField"
] | [((326, 403), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'blank': '(True)', 'decimal_places': '(1)', 'default': 'None', 'max_digits': '(1)'}), '(blank=True, decimal_places=1, default=None, max_digits=1)\n', (345, 403), False, 'from django.db import migrations, models\n')] |
# -*- coding: utf-8 -*-
# Copyright (C) 2010-2014 Mag. <NAME> All rights reserved
# Glasauergasse 32, A--1130 Wien, Austria. <EMAIL>
# ****************************************************************************
# This module is part of the package GTW.OMP.SWP.
#
# This module is licensed under the terms of the BSD 3-C... | [
"_GTW.GTW.OMP.SWP._Export"
] | [((1572, 1596), '_GTW.GTW.OMP.SWP._Export', 'GTW.OMP.SWP._Export', (['"""*"""'], {}), "('*')\n", (1591, 1596), False, 'from _GTW import GTW\n')] |
from imgaug import augmenters as iaa
import matplotlib.pyplot as plt
from itertools import cycle
from scipy import interp
import tensorflow as tf
import itertools
import numpy as np
import json
import argparse
import warnings
import os
from synth.utils import datagenerate
from sklearn.metrics import roc_curve, auc, a... | [
"matplotlib.pyplot.ylabel",
"sklearn.metrics.classification_report",
"sklearn.metrics.auc",
"sklearn.metrics.roc_curve",
"tensorflow.cast",
"synth.utils.datagenerate",
"matplotlib.pyplot.imshow",
"os.path.exists",
"scipy.interp",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"matplotli... | [((623, 637), 'synth.utils.datagenerate', 'datagenerate', ([], {}), '()\n', (635, 637), False, 'from synth.utils import datagenerate\n'), ((651, 676), 'tensorflow.cast', 'tf.cast', (['images', 'tf.uint8'], {}), '(images, tf.uint8)\n', (658, 676), True, 'import tensorflow as tf\n'), ((943, 982), 'os.path.join', 'os.path... |
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from pathlib import Path
from template_data.models import TemplateData
from template_data.management.commands.add_data import DataMixin
import json
class Command(DataMixin, BaseCommand):
"""Install the theme"""
... | [
"json.load",
"traceback.print_exc"
] | [((646, 659), 'json.load', 'json.load', (['fp'], {}), '(fp)\n', (655, 659), False, 'import json\n'), ((1063, 1084), 'traceback.print_exc', 'traceback.print_exc', ([], {}), '()\n', (1082, 1084), False, 'import traceback\n')] |
from concurrent import futures
from functools import partial
from itertools import product
import os
import numpy as np
from pyx import color, deco, graph, path, text
def mandelbrot_iteration(niter, *args):
nx, ny, c = args[0]
z = np.zeros_like(c)
for n in range(niter):
z = z**2+c
return nx, ny... | [
"numpy.abs",
"pyx.graph.axis.lin",
"pyx.text.set",
"pyx.text.preamble",
"pyx.graph.data.points",
"pyx.color.grey",
"pyx.path.rect",
"pyx.graph.style.density",
"functools.partial",
"concurrent.futures.ProcessPoolExecutor",
"os.getpid",
"pyx.color.transparency",
"numpy.zeros_like"
] | [((691, 733), 'concurrent.futures.ProcessPoolExecutor', 'futures.ProcessPoolExecutor', ([], {'max_workers': '(4)'}), '(max_workers=4)\n', (718, 733), False, 'from concurrent import futures\n'), ((1224, 1250), 'pyx.text.set', 'text.set', (['text.LatexRunner'], {}), '(text.LatexRunner)\n', (1232, 1250), False, 'from pyx ... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^(?P<id>\d{10})/'
r'(?P<accion>\d+)/$',
views.accion, name='accion'
),
]
| [
"django.conf.urls.url"
] | [((74, 145), 'django.conf.urls.url', 'url', (['"""^(?P<id>\\\\d{10})/(?P<accion>\\\\d+)/$"""', 'views.accion'], {'name': '"""accion"""'}), "('^(?P<id>\\\\d{10})/(?P<accion>\\\\d+)/$', views.accion, name='accion')\n", (77, 145), False, 'from django.conf.urls import url\n')] |
# -*- coding: utf-8 -*-
"""
"""
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
dtype = torch.float
class RNN(nn.Module):
def __init__(self, input_size, hidden_size, num_layers, device=torch.device("cpu")):
super(RNN, self).__init__()... | [
"torch.nn.ReLU",
"torch.nn.Dropout",
"torch.nn.Softmax",
"torch.nn.LeakyReLU",
"torch.nn.LSTM",
"torch.transpose",
"torch.nn.Linear",
"torch.squeeze",
"torch.bmm",
"torch.randn",
"torch.cat",
"torch.device"
] | [((262, 281), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (274, 281), False, 'import torch\n'), ((722, 743), 'torch.nn.Dropout', 'nn.Dropout', ([], {'p': 'dropout'}), '(p=dropout)\n', (732, 743), True, 'import torch.nn as nn\n'), ((1659, 1687), 'torch.bmm', 'torch.bmm', (['out', 'hidden_state'], {... |
import os
import unittest
import jwt
from dataservice.app import app
from flask_webtest import TestApp as _TestApp
_HERE = os.path.dirname(__file__)
with open(os.path.join(_HERE, 'privkey.pem')) as f:
_KEY = f.read()
def create_token(data):
return jwt.encode(data, _KEY, algorithm='RS512')
_TOKEN = {'iss':... | [
"flask_webtest.TestApp",
"os.path.dirname",
"os.path.join",
"jwt.encode"
] | [((125, 150), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (140, 150), False, 'import os\n'), ((260, 301), 'jwt.encode', 'jwt.encode', (['data', '_KEY'], {'algorithm': '"""RS512"""'}), "(data, _KEY, algorithm='RS512')\n", (270, 301), False, 'import jwt\n'), ((161, 195), 'os.path.join', 'os.... |
from MLlib.models import Agglomerative_clustering
import numpy as np
X = np.genfromtxt('datasets/agglomerative_clustering.txt')
model = Agglomerative_clustering()
model.work(X, 4)
model.plot(X)
| [
"numpy.genfromtxt",
"MLlib.models.Agglomerative_clustering"
] | [((74, 128), 'numpy.genfromtxt', 'np.genfromtxt', (['"""datasets/agglomerative_clustering.txt"""'], {}), "('datasets/agglomerative_clustering.txt')\n", (87, 128), True, 'import numpy as np\n'), ((139, 165), 'MLlib.models.Agglomerative_clustering', 'Agglomerative_clustering', ([], {}), '()\n', (163, 165), False, 'from M... |
import sys
import argparse
import math
import cv2
import pdb
import os
from os import listdir
from os.path import isfile, join
def pngImgDirs(x_args):
#pdb.set_trace()
in_path = os.path.abspath(x_args.indir)
out_path = os.path.abspath(x_args.outdir)
if(x_args.opt == 'test'):
eval_... | [
"os.listdir",
"argparse.ArgumentParser",
"os.makedirs",
"os.path.join",
"cv2.cvtColor",
"os.path.abspath",
"os.stat",
"cv2.imread"
] | [((193, 222), 'os.path.abspath', 'os.path.abspath', (['x_args.indir'], {}), '(x_args.indir)\n', (208, 222), False, 'import os\n'), ((241, 271), 'os.path.abspath', 'os.path.abspath', (['x_args.outdir'], {}), '(x_args.outdir)\n', (256, 271), False, 'import os\n'), ((384, 410), 'os.path.join', 'join', (['out_path', 'x_arg... |
from __future__ import annotations
import copy
import dataclasses
import functools
import getpass
import json
import logging
import logging.handlers
import os
import platform
import queue as queue_module
import socket
import sys
import typing
import warnings
from .utils import get_fully_qualified_domain_name
# The s... | [
"logging.getLogger",
"dataclasses.dataclass",
"os.environ.get",
"platform.uname",
"queue.Queue",
"logging.getLevelName",
"functools.partial",
"getpass.getuser",
"copy.copy",
"sys.modules.items"
] | [((344, 377), 'logging.getLogger', 'logging.getLogger', (['"""pcds-logging"""'], {}), "('pcds-logging')\n", (361, 377), False, 'import logging\n'), ((576, 629), 'os.environ.get', 'os.environ.get', (['"""PCDS_LOG_HOST"""', '"""ctl-logsrv01.pcdsn"""'], {}), "('PCDS_LOG_HOST', 'ctl-logsrv01.pcdsn')\n", (590, 629), False, ... |
# convert the downscaled data archive
def run( x ):
''' simple wrapper to open and return a 2-D array from a geotiff '''
import rasterio
return rasterio.open(x).read(1)
def sort_files( files, split_on='_', elem_month=-2, elem_year=-1 ):
'''
sort a list of files properly using the month and year parsed
from the... | [
"os.path.exists",
"time.ctime",
"argparse.ArgumentParser",
"os.makedirs",
"rasterio.open",
"os.path.join",
"numpy.swapaxes",
"affine.Affine.translation",
"multiprocessing.Pool",
"pyproj.Proj",
"numpy.min",
"pandas.DataFrame",
"time.time",
"numpy.arange",
"numpy.vectorize"
] | [((1410, 1469), 'pandas.DataFrame', 'pd.DataFrame', (["{'fn': files, 'month': months, 'year': years}"], {}), "({'fn': files, 'month': months, 'year': years})\n", (1422, 1469), True, 'import pandas as pd\n'), ((2349, 2391), 'pandas.DataFrame', 'pd.DataFrame', (["{'fn': files, 'year': years}"], {}), "({'fn': files, 'year... |
__author__ = 'Reem'
# This file contains the main functions that deal with caching the diff
# at different levels of details
# detail (as detail), middle (as count), overview (as ratios)
from diff_finder import Table, DiffFinder, Diff, Levels, Ratios
import caleydo_server.dataset as dataset
import timeit
import json
... | [
"hashlib.md5",
"ujson.dumps",
"timeit.default_timer",
"os.path.isfile",
"diff_finder.Ratios",
"caleydo_server.dataset.get",
"json.load",
"diff_finder.DiffFinder",
"json.dump"
] | [((536, 561), 'os.path.isfile', 'os.path.isfile', (['file_name'], {}), '(file_name)\n', (550, 561), False, 'import os\n'), ((3597, 3613), 'caleydo_server.dataset.get', 'dataset.get', (['id1'], {}), '(id1)\n', (3608, 3613), True, 'import caleydo_server.dataset as dataset\n'), ((3624, 3640), 'caleydo_server.dataset.get',... |
import configparser
import spotipy
from spotipy.oauth2 import SpotifyOAuth
class Spotify:
SCOPE = "playlist-read-private playlist-modify-private user-library-modify user-library-read"
def __init__(self):
config = configparser.ConfigParser()
config.read("config.ini")
self.client = sp... | [
"configparser.ConfigParser",
"spotipy.oauth2.SpotifyOAuth"
] | [((233, 260), 'configparser.ConfigParser', 'configparser.ConfigParser', ([], {}), '()\n', (258, 260), False, 'import configparser\n'), ((347, 524), 'spotipy.oauth2.SpotifyOAuth', 'SpotifyOAuth', ([], {'client_id': "config['spotify']['clientId']", 'client_secret': "config['spotify']['clientSecret']", 'redirect_uri': "co... |
import unittest
import libraries.morflessLibs as libs
# import test values and expected outputs
# main includes sidebar data
import unit.read_schematic_test_io.read_schematic_1_test_io as tv1
import unit.read_schematic_test_io.read_schematic_2_test_io as tv2
import unit.read_schematic_test_io.read_schematic_3_test_io ... | [
"libraries.morflessLibs.read_schematic.pcom_process_inserts",
"libraries.morflessLibs.read_schematic.pcom_determine_placement",
"libraries.morflessLibs.read_schematic.polimorf_determine_schematic_reference",
"libraries.morflessLibs.read_schematic.pcom_get_schematic_tags",
"libraries.morflessLibs.read_schema... | [((8522, 8537), 'unittest.main', 'unittest.main', ([], {}), '()\n', (8535, 8537), False, 'import unittest\n'), ((690, 764), 'libraries.morflessLibs.string_processes.pcom_build_dictionary', 'libs.string_processes.pcom_build_dictionary', (['libs.globals.DEFAULT_SETTINGS'], {}), '(libs.globals.DEFAULT_SETTINGS)\n', (733, ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for AuthService."""
import pytest
from webodm import NonFieldErrors, LOCAL_HOST
from webodm.services import AuthService
@pytest.fixture
def authservice():
return AuthService(LOCAL_HOST)
class MockResponse:
def __init__(self, json_data, status_code):
... | [
"webodm.services.AuthService",
"pytest.raises"
] | [((225, 248), 'webodm.services.AuthService', 'AuthService', (['LOCAL_HOST'], {}), '(LOCAL_HOST)\n', (236, 248), False, 'from webodm.services import AuthService\n'), ((1250, 1279), 'pytest.raises', 'pytest.raises', (['NonFieldErrors'], {}), '(NonFieldErrors)\n', (1263, 1279), False, 'import pytest\n')] |
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the License);
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, sof... | [
"yamlformat.validator.base_lib.GetTreeLocation",
"absl.testing.absltest.main",
"yamlformat.validator.base_lib.ComponentType.FromString"
] | [((2964, 2979), 'absl.testing.absltest.main', 'absltest.main', ([], {}), '()\n', (2977, 2979), False, 'from absl.testing import absltest\n'), ((1948, 1982), 'yamlformat.validator.base_lib.GetTreeLocation', 'base_lib.GetTreeLocation', (['testpath'], {}), '(testpath)\n', (1972, 1982), False, 'from yamlformat.validator im... |
import numpy as np
class Node():
def __init__(self, params=[]):
self.in_nodes = params
self.value = 0
def forward(self):
return NotImplementedError
def backward(self):
return NotImplementedError
class Input_Node(Node):
def __init__(self, value ... | [
"numpy.array",
"numpy.sum"
] | [((631, 676), 'numpy.array', 'np.array', (['[x.value for x in self.in_nodes[0]]'], {}), '([x.value for x in self.in_nodes[0]])\n', (639, 676), True, 'import numpy as np\n'), ((695, 740), 'numpy.array', 'np.array', (['[w.value for w in self.in_nodes[1]]'], {}), '([w.value for w in self.in_nodes[1]])\n', (703, 740), True... |
import pickle
def get_users():
users_file = open("users_file", "rb")
try:
users = pickle.load(users_file)
except:
import pdb;pdb.set_trace()
username_table = {u.username: u for u in users}
return username_table
class User:
def __init__(self, user_id, username, password):
... | [
"pickle.load",
"pdb.set_trace"
] | [((100, 123), 'pickle.load', 'pickle.load', (['users_file'], {}), '(users_file)\n', (111, 123), False, 'import pickle\n'), ((155, 170), 'pdb.set_trace', 'pdb.set_trace', ([], {}), '()\n', (168, 170), False, 'import pdb\n')] |
from time import perf_counter_ns as ns
def solution(s):
d = {n: str(i) for i, n in enumerate('zero one two three four '
'five six seven eight nine'.split())}
for k, v in d.items():
s = s.replace(k, v)
return int(s)
if __name__ == '__main__':
ITERATION... | [
"time.perf_counter_ns"
] | [((859, 863), 'time.perf_counter_ns', 'ns', ([], {}), '()\n', (861, 863), True, 'from time import perf_counter_ns as ns\n'), ((914, 918), 'time.perf_counter_ns', 'ns', ([], {}), '()\n', (916, 918), True, 'from time import perf_counter_ns as ns\n')] |
# ****************************************************************
# AULA: Visão Computacional
# Prof: <NAME>, DSc.
# ****************************************************************
# Importando a biblioteca OpenCV
import cv2
import numpy as np
# Imagem
aquivo = "./imagens/raposa.jpg"
# Carregando a imagem
imagem =... | [
"cv2.waitKey",
"cv2.imread",
"cv2.cvtColor",
"cv2.imshow"
] | [((321, 339), 'cv2.imread', 'cv2.imread', (['aquivo'], {}), '(aquivo)\n', (331, 339), False, 'import cv2\n'), ((380, 420), 'cv2.cvtColor', 'cv2.cvtColor', (['imagem', 'cv2.COLOR_BGR2GRAY'], {}), '(imagem, cv2.COLOR_BGR2GRAY)\n', (392, 420), False, 'import cv2\n'), ((421, 459), 'cv2.imshow', 'cv2.imshow', (['"""Imagem b... |
# -*- encoding: utf-8 -*-
"""
Provide a class for orchestrating the rush of some yielding callable.
"""
from __future__ import absolute_import
import sys
from collections import defaultdict
from datetime import timedelta
from threading import Condition, Event, Thread
from time import time
__all__ = ['Rusher', 'rush',... | [
"datetime.timedelta",
"threading.Event",
"collections.defaultdict",
"threading.Thread",
"threading.Condition",
"time.time"
] | [((956, 967), 'threading.Condition', 'Condition', ([], {}), '()\n', (965, 967), False, 'from threading import Condition, Event, Thread\n'), ((1076, 1083), 'threading.Event', 'Event', ([], {}), '()\n', (1081, 1083), False, 'from threading import Condition, Event, Thread\n'), ((2546, 2552), 'time.time', 'time', ([], {}),... |
""" state, observation and action spaces """
from collections import namedtuple, OrderedDict
from io import BytesIO
from itertools import product
from os.path import join
import pkg_resources
import numpy as np
import pandas as pd
import energypy as ep
from energypy.common.spaces import DiscreteSpace, ContinuousSpac... | [
"collections.namedtuple",
"itertools.product",
"io.BytesIO",
"os.path.join",
"numpy.max",
"numpy.array",
"numpy.random.randint",
"numpy.min"
] | [((358, 422), 'collections.namedtuple', 'namedtuple', (['"""primitive"""', "['name', 'low', 'high', 'type', 'data']"], {}), "('primitive', ['name', 'low', 'high', 'type', 'data'])\n", (368, 422), False, 'from collections import namedtuple, OrderedDict\n'), ((3128, 3142), 'numpy.array', 'np.array', (['data'], {}), '(dat... |
# import XML libraries
import xml.etree.ElementTree as ET
import xml.dom.minidom as minidom
import HTMLParser
# Function to create an XML structure
def make_problem_XML(
problem_title='Missing title',
problem_text=False,
label_text='Enter your answer below.',
description_text=False,
answers=[{'corr... | [
"xml.etree.ElementTree.Element",
"xml.etree.ElementTree.SubElement",
"HTMLParser.HTMLParser",
"xml.etree.ElementTree.ElementTree"
] | [((2703, 2724), 'xml.etree.ElementTree.Element', 'ET.Element', (['"""problem"""'], {}), "('problem')\n", (2713, 2724), True, 'import xml.etree.ElementTree as ET\n'), ((2795, 2822), 'xml.etree.ElementTree.ElementTree', 'ET.ElementTree', (['problem_tag'], {}), '(problem_tag)\n', (2809, 2822), True, 'import xml.etree.Elem... |
import os
os.system("pip3 install GitPython")
os.system("pip3 install PyYAML")
os.system("pip3 install nltk")
os.system("python3 -m nltk.downloader stopwords")
os.system("python3 -m nltk.downloader wordnet")
os.system("pip3 install psycopg2-binary")
| [
"os.system"
] | [((10, 45), 'os.system', 'os.system', (['"""pip3 install GitPython"""'], {}), "('pip3 install GitPython')\n", (19, 45), False, 'import os\n'), ((46, 78), 'os.system', 'os.system', (['"""pip3 install PyYAML"""'], {}), "('pip3 install PyYAML')\n", (55, 78), False, 'import os\n'), ((79, 109), 'os.system', 'os.system', (['... |
import pynini
import tqdm
class Alphabet:
"""
Represents mapping between phonemes in IPA
and representations in text files
"""
def __init__(self):
self.symbols
class Vocabulary:
"""
Get ...
"""
class Allophony:
"""
Multiplies the vocabulary by ta... | [
"pynini.pdt_shortestpath",
"pynini.compose",
"tqdm.tqdm",
"pynini.Fst"
] | [((884, 896), 'pynini.Fst', 'pynini.Fst', ([], {}), '()\n', (894, 896), False, 'import pynini\n'), ((1079, 1100), 'tqdm.tqdm', 'tqdm.tqdm', (['transcript'], {}), '(transcript)\n', (1088, 1100), False, 'import tqdm\n'), ((1632, 1679), 'pynini.compose', 'pynini.compose', (['acoustic_fst', 'self.language_fst'], {}), '(aco... |
# Generated by Django 3.0.8 on 2020-12-04 17:53
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('auctions', '0006_auto_20201203_1859'),
]
operations = [
migrations.AlterFi... | [
"django.db.models.ForeignKey"
] | [((415, 540), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'blank': '(True)', 'on_delete': 'django.db.models.deletion.CASCADE', 'related_name': '"""watched"""', 'to': '"""auctions.Auction"""'}), "(blank=True, on_delete=django.db.models.deletion.CASCADE,\n related_name='watched', to='auctions.Auction')\n... |
# --*-- coding: utf-8 --*--
import os
import datetime
import sys
WORK_PATH = os.getcwd()
LOG_PATH = os.path.join(WORK_PATH, 'Logs')
class Logger(object):
def __init__(self, file_name):
if not os.path.exists(LOG_PATH):
os.makedirs(LOG_PATH)
date = datetime.datetime.now()
self.file_path = os.path.join(LOG_P... | [
"os.path.exists",
"os.makedirs",
"os.path.join",
"os.getcwd",
"datetime.datetime.now"
] | [((79, 90), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (88, 90), False, 'import os\n'), ((102, 133), 'os.path.join', 'os.path.join', (['WORK_PATH', '"""Logs"""'], {}), "(WORK_PATH, 'Logs')\n", (114, 133), False, 'import os\n'), ((259, 282), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (280, 282)... |
#!/usr/bin/env python3
#
# Copyright (c) 2021 @marbocub <<EMAIL>>
# Released under the MIT license
#
import os, pathlib, hashlib, time, sys, re
from typing import Callable, List, Tuple
import dotenv
from database import FileBase, File, Dir, DatabaseInterface, DatabasePostgreSQL
#-------------------------... | [
"os.path.exists",
"hashlib.sha256",
"database.DatabasePostgreSQL",
"os.listdir",
"pathlib.Path",
"os.path.join",
"os.environ.get",
"os.getcwd",
"dotenv.load_dotenv",
"os.chdir",
"sys.exit",
"os.stat",
"time.time"
] | [((5965, 5976), 'time.time', 'time.time', ([], {}), '()\n', (5974, 5976), False, 'import os, pathlib, hashlib, time, sys, re\n'), ((6111, 6131), 'dotenv.load_dotenv', 'dotenv.load_dotenv', ([], {}), '()\n', (6129, 6131), False, 'import dotenv\n'), ((6382, 6415), 'database.DatabasePostgreSQL', 'DatabasePostgreSQL', ([],... |
import serial
import MySQLdb
device = '/dev/ttyACM0'
#ser = serial.Serial('/dev/ttyACM1', 9600)
arduino = serial.Serial(device, 9600)
data = arduino.readline()
print('Encoded Serial Databyte'+ data)
temp = data.decode('UTF-8')
print(temp)
#Make DB connection
dbConn = MySQLdb.connect("localhost", "root", "password... | [
"MySQLdb.connect",
"serial.Serial"
] | [((109, 136), 'serial.Serial', 'serial.Serial', (['device', '(9600)'], {}), '(device, 9600)\n', (122, 136), False, 'import serial\n'), ((274, 336), 'MySQLdb.connect', 'MySQLdb.connect', (['"""localhost"""', '"""root"""', '"""password"""', '"""<PASSWORD>"""'], {}), "('localhost', 'root', 'password', '<PASSWORD>')\n", (2... |
# ============LICENSE_START==========================================
# org.onap.vvp/engagementmgr
# ===================================================================
# Copyright © 2017 AT&T Intellectual Property. All rights reserved.
# ===================================================================
#
# Unless ot... | [
"datetime.datetime",
"django.db.models.EmailField",
"django.db.models.DateField",
"django.db.models.TextField",
"django.db.models.ForeignKey",
"django.db.models.IntegerField",
"django.db.models.ManyToManyField",
"django.db.models.BooleanField",
"django.db.models.AutoField",
"django.db.models.Binar... | [((19455, 19550), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'on_delete': 'django.db.models.deletion.PROTECT', 'to': '"""engagementmanager.VFC"""'}), "(on_delete=django.db.models.deletion.PROTECT, to=\n 'engagementmanager.VFC')\n", (19472, 19550), False, 'from django.db import migrations, models\n'), ... |
import unittest
import pickle
import sys
import tempfile
from pathlib import Path
class TestUnpickleDeletedModule(unittest.TestCase):
def test_loading_pickle_with_no_module(self):
"""Create a module that uses Numba, import a function from it.
Then delete the module and pickle the function. The fun... | [
"tempfile.TemporaryDirectory",
"pathlib.Path",
"pickle.dumps",
"pickle.loads",
"sys.path.append"
] | [((1548, 1566), 'pickle.dumps', 'pickle.dumps', (['inc1'], {}), '(inc1)\n', (1560, 1566), False, 'import pickle\n'), ((1579, 1596), 'pickle.loads', 'pickle.loads', (['pkl'], {}), '(pkl)\n', (1591, 1596), False, 'import pickle\n'), ((998, 1027), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()... |
from selenium import webdriver
driver = webdriver.Chrome(executable_path='/home/denoh/Programs/Webdriver/chromedriver')
driver.implicitly_wait(0.5)
driver.get("https://www.tutorialspoint.com/index.htm")
# identify element
# l= driver.find_elements_by_css_selector("body > div:nth-child(2) > div > h4")
l = driver.find_e... | [
"selenium.webdriver.Chrome"
] | [((41, 120), 'selenium.webdriver.Chrome', 'webdriver.Chrome', ([], {'executable_path': '"""/home/denoh/Programs/Webdriver/chromedriver"""'}), "(executable_path='/home/denoh/Programs/Webdriver/chromedriver')\n", (57, 120), False, 'from selenium import webdriver\n')] |
"""
Pylibui test suite.
"""
from pylibui.controls import Combobox
from tests.utils import WindowTestCase
class ComboboxTest(WindowTestCase):
def setUp(self):
super().setUp()
self.combobox = Combobox()
def test_set_selected(self):
"""Tests the set_selected method of the combobox."""... | [
"pylibui.controls.Combobox"
] | [((215, 225), 'pylibui.controls.Combobox', 'Combobox', ([], {}), '()\n', (223, 225), False, 'from pylibui.controls import Combobox\n')] |
import datetime
import random
import threading
import consul
from loadbalance.consulconfig import ConsulConfig, ConsulDiscoverConfig, AppConfig
from tool.networktool import *
service_cache = {}
def reload_service_cache():
if service_cache is not None and len(service_cache)>0:
for key in service_cache.ke... | [
"random.uniform",
"threading.Timer",
"loadbalance.consulconfig.ConsulConfig.load_config",
"consul.Consul",
"datetime.datetime.now",
"loadbalance.consulconfig.AppConfig.load_config",
"consul.Check.http",
"loadbalance.consulconfig.ConsulDiscoverConfig.load_config"
] | [((475, 509), 'loadbalance.consulconfig.ConsulDiscoverConfig.load_config', 'ConsulDiscoverConfig.load_config', ([], {}), '()\n', (507, 509), False, 'from loadbalance.consulconfig import ConsulConfig, ConsulDiscoverConfig, AppConfig\n'), ((531, 554), 'loadbalance.consulconfig.AppConfig.load_config', 'AppConfig.load_conf... |
from util import db
from util import getFilteredQuery
from flask import jsonify
from flask_restful import Resource
from flask_restful import reqparse
from urllib.parse import unquote
_weaponsCollection = db.weapons
class WeaponsListApi(Resource):
def get(self):
return jsonify(getFilteredQue... | [
"util.getFilteredQuery",
"flask_restful.reqparse.RequestParser",
"urllib.parse.unquote"
] | [((1221, 1245), 'flask_restful.reqparse.RequestParser', 'reqparse.RequestParser', ([], {}), '()\n', (1243, 1245), False, 'from flask_restful import reqparse\n'), ((306, 346), 'util.getFilteredQuery', 'getFilteredQuery', (['_weaponsCollection', '{}'], {}), '(_weaponsCollection, {})\n', (322, 346), False, 'from util impo... |
import numpy as np, matplotlib.pyplot as plt, seaborn as sns
from rdkit import Chem
from dataclasses import dataclass
from utils.exp import BaseArgs, BaseExpLog
from utils.data import remove_processed_data
import torch
from torch_geometric.data import DataLoader
from data.data_processors.ts_gen_processor import TSGenDa... | [
"rdkit.Chem.Get3DDistanceMatrix",
"data.data_processors.ts_gen_processor.TSGenDataset",
"matplotlib.pyplot.savefig",
"seaborn.color_palette",
"torch_geometric.data.DataLoader",
"seaborn.distplot",
"numpy.floor",
"utils.data.remove_processed_data",
"rdkit.Chem.SDMolSupplier",
"numpy.concatenate",
... | [((1568, 1608), 'data.data_processors.ts_gen_processor.TSGenDataset', 'TSGenDataset', (['args.root_dir', 'args.n_rxns'], {}), '(args.root_dir, args.n_rxns)\n', (1580, 1608), False, 'from data.data_processors.ts_gen_processor import TSGenDataset\n'), ((1840, 1962), 'torch_geometric.data.DataLoader', 'DataLoader', (['dat... |
import requests
class UnauthenticatedError(Exception):
pass
class InvalidTokenError(Exception):
pass
class InvalidResponseError(Exception):
pass
class NetworkManager:
def __init__(self, endpoint):
self.endpoint = endpoint
self.token = ""
def register_device(self, hardware_id... | [
"requests.get"
] | [((480, 558), 'requests.get', 'requests.get', (["(self.endpoint + '/api/register')"], {'params': 'payload', 'headers': 'headers'}), "(self.endpoint + '/api/register', params=payload, headers=headers)\n", (492, 558), False, 'import requests\n')] |
#!/usr/bin/env python
"""Script used to generate a cuboid dataset with cubes and rectangles under
various shapes, rotations, translations following the general format of
ShapeNet.
"""
import argparse
import random
import os
from string import ascii_letters, digits
import sys
import numpy as np
from progress.bar import... | [
"os.path.exists",
"os.listdir",
"pyquaternion.Quaternion.random",
"numpy.random.rand",
"argparse.ArgumentParser",
"os.makedirs",
"numpy.random.random",
"random.choice",
"os.path.join",
"learnable_primitives.mesh.MeshFromOBJ",
"shapes.Shape.from_shapes",
"numpy.array",
"numpy.linspace",
"sh... | [((615, 642), 'shapes.Cuboid', 'Cuboid', (['(-r)', 'r', '(-r)', 'r', '(-r)', 'r'], {}), '(-r, r, -r, r, -r, r)\n', (621, 642), False, 'from shapes import Shape, Cuboid, Ellipsoid\n'), ((703, 720), 'numpy.array', 'np.array', (['minimum'], {}), '(minimum)\n', (711, 720), True, 'import numpy as np\n'), ((735, 752), 'numpy... |
import os
# If server, need to use osmesa for pyopengl/pyrender
if os.cpu_count() > 20:
os.environ['PYOPENGL_PLATFORM'] = 'osmesa'
# https://github.com/marian42/mesh_to_sdf/issues/13
# https://pyrender.readthedocs.io/en/latest/install/index.html?highlight=ssh#getting-pyrender-working-with-osmesa
else:
os.environ[... | [
"numpy.random.get_state",
"torch.optim.lr_scheduler.MultiStepLR",
"yaml.load",
"src.dataset_grasp.TrainDataset",
"torch.from_numpy",
"torch.nn.MSELoss",
"src.pointnet_encoder.PointNetEncoder",
"numpy.array",
"torch.get_rng_state",
"os.cpu_count",
"logging.info",
"multiprocessing.set_start_meth... | [((67, 81), 'os.cpu_count', 'os.cpu_count', ([], {}), '()\n', (79, 81), False, 'import os\n'), ((17202, 17219), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (17213, 17219), False, 'import random\n'), ((17221, 17241), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (17235, 17241), True, '... |
from urllib.parse import quote_plus
from flask import url_for
from sopy import db
from sopy.ext.models import IDModel
from sopy.se_data.models import ChatMessage
class Transcript(IDModel):
title = db.Column(db.String, nullable=False)
ts = db.Column(db.DateTime, nullable=False)
body = db.Column(db.String, ... | [
"sopy.db.Column",
"sopy.db.ForeignKey",
"sopy.db.relationship",
"flask.url_for"
] | [((203, 239), 'sopy.db.Column', 'db.Column', (['db.String'], {'nullable': '(False)'}), '(db.String, nullable=False)\n', (212, 239), False, 'from sopy import db\n'), ((249, 287), 'sopy.db.Column', 'db.Column', (['db.DateTime'], {'nullable': '(False)'}), '(db.DateTime, nullable=False)\n', (258, 287), False, 'from sopy im... |