code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
#!/usr/bin/python3
import json
import sys
from pprint import pprint
import requests
from config import database
import MySQLdb
try:
db = MySQLdb.connect(database["host"],
database["user"],
database["passwd"],
database["db"])
cur = ... | [
"MySQLdb.connect",
"requests.get",
"sys.exit"
] | [((146, 237), 'MySQLdb.connect', 'MySQLdb.connect', (["database['host']", "database['user']", "database['passwd']", "database['db']"], {}), "(database['host'], database['user'], database['passwd'],\n database['db'])\n", (161, 237), False, 'import MySQLdb\n'), ((635, 706), 'requests.get', 'requests.get', (['"""https:... |
import numpy as np
def compute_intensity(pos, pos_list, radius):
return (norm(np.array(pos_list) - np.array(pos), axis=1) < radius).sum()
def compute_colours(all_pos):
colours = [compute_intensity(pos, all_pos, 1e-4) for pos in all_pos]
colours /= max(colours)
return colours
| [
"numpy.array"
] | [((84, 102), 'numpy.array', 'np.array', (['pos_list'], {}), '(pos_list)\n', (92, 102), True, 'import numpy as np\n'), ((105, 118), 'numpy.array', 'np.array', (['pos'], {}), '(pos)\n', (113, 118), True, 'import numpy as np\n')] |
#prints hello world letter by letter on windows system
import os,time
def slowhello():
s = 'Hello World!'
for i in range(len(s)):
os.system('cls')
print (s[:i+1])
time.sleep(0.5)
slowhello()
| [
"os.system",
"time.sleep"
] | [((135, 151), 'os.system', 'os.system', (['"""cls"""'], {}), "('cls')\n", (144, 151), False, 'import os, time\n'), ((172, 187), 'time.sleep', 'time.sleep', (['(0.5)'], {}), '(0.5)\n', (182, 187), False, 'import os, time\n')] |
"""Parser Configuration Reader"""
import typing
from json import JSONDecodeError
from pathlib import Path
from nltk.corpus import stopwords
from ..constants import (
BUILTIN, DEFAULT_IDEAL_LENGTH, DEFAULT_IDIOM, DEFAULT_LANGUAGE,
DEFAULT_NLTK_STOPS, DEFAULT_USER_STOPS)
from ..io import load_json
from ..repr_a... | [
"nltk.corpus.stopwords.words",
"pathlib.Path"
] | [((723, 733), 'pathlib.Path', 'Path', (['root'], {}), '(root)\n', (727, 733), False, 'from pathlib import Path\n'), ((2870, 2880), 'pathlib.Path', 'Path', (['root'], {}), '(root)\n', (2874, 2880), False, 'from pathlib import Path\n'), ((1255, 1280), 'nltk.corpus.stopwords.words', 'stopwords.words', (['language'], {}), ... |
"""
This is module implementing fixed point numbers for python. For a motivation, description and some
examples, we refer to the docstring of the FixedPoint class.
"""
from __future__ import annotations
import numbers
from secrets import randbelow
from typing import Optional, Tuple, Union
# Add numpy support, if ava... | [
"secrets.randbelow"
] | [((29141, 29197), 'secrets.randbelow', 'randbelow', (['(cal_upper_bound.value - cal_lower_bound.value)'], {}), '(cal_upper_bound.value - cal_lower_bound.value)\n', (29150, 29197), False, 'from secrets import randbelow\n'), ((29282, 29294), 'secrets.randbelow', 'randbelow', (['(2)'], {}), '(2)\n', (29291, 29294), False,... |
from Point import Point
class Rectangle:
def __init__(self, p, w, h):
self.CornerPoint = p
self.width = w
self.height = h
def __str__(self):
return f"Rectangle {self.width} by {self.height}, at {self.CornerPoint}."
def transpose(self):
self.width, self.height = s... | [
"Point.Point"
] | [((1448, 1459), 'Point.Point', 'Point', (['(3)', '(4)'], {}), '(3, 4)\n', (1453, 1459), False, 'from Point import Point\n'), ((1605, 1616), 'Point.Point', 'Point', (['(0)', '(0)'], {}), '(0, 0)\n', (1610, 1616), False, 'from Point import Point\n'), ((1898, 1909), 'Point.Point', 'Point', (['(0)', '(0)'], {}), '(0, 0)\n'... |
# flake8: noqa
from construct import *
from xbox.sg.utils.struct import XStruct
from xbox.sg.utils.adapters import XSwitch, XEnum, PrefixedBytes
from xbox.nano.enum import ControlPayloadType, ControllerEvent
"""
ControlProtocol Streamer Messages
"""
session_init = XStruct(
'unk3' / GreedyBytes
)
session_create... | [
"xbox.sg.utils.adapters.XEnum",
"xbox.sg.utils.struct.XStruct",
"xbox.sg.utils.adapters.XSwitch",
"xbox.sg.utils.adapters.PrefixedBytes"
] | [((268, 297), 'xbox.sg.utils.struct.XStruct', 'XStruct', (["('unk3' / GreedyBytes)"], {}), "('unk3' / GreedyBytes)\n", (275, 297), False, 'from xbox.sg.utils.struct import XStruct\n'), ((567, 692), 'xbox.sg.utils.struct.XStruct', 'XStruct', (["('unk3' / Float32l)", "('unk4' / Float32l)", "('unk5' / Float32l)", "('unk6'... |
import cProfile
import compas
from compas.datastructures import Mesh, mesh_transform
from compas.geometry import Frame, Point, Transformation, Vector
print('compas.__version__ : ', compas.__version__)
f1 = Frame([2, 2, 2], [0.12, 0.58, 0.81], [-0.80, 0.53, -0.26])
f2 = Frame([1, 1, 1], [0.68, 0.68, 0.27], [-0.67, 0.... | [
"compas.geometry.Frame",
"compas.datastructures.mesh_transform",
"cProfile.run",
"compas.get_bunny",
"compas.geometry.Transformation.from_frame_to_frame"
] | [((209, 266), 'compas.geometry.Frame', 'Frame', (['[2, 2, 2]', '[0.12, 0.58, 0.81]', '[-0.8, 0.53, -0.26]'], {}), '([2, 2, 2], [0.12, 0.58, 0.81], [-0.8, 0.53, -0.26])\n', (214, 266), False, 'from compas.geometry import Frame, Point, Transformation, Vector\n'), ((273, 331), 'compas.geometry.Frame', 'Frame', (['[1, 1, 1... |
#!/usr/bin/python3
# find_conserved_blocks_v*.py
###########################
# Overview:
# Script analyses DNA multi sequence alignment data and searches for areas
# (blocks) which are conserved (i.e. identical or very similar). Required
# input is any valid FASTA file with multiple sequences.
# User can adjus... | [
"Bio.AlignIO.read",
"os.path.realpath",
"os.path.basename",
"Bio.Align.MultipleSeqAlignment",
"time.time"
] | [((859, 870), 'time.time', 'time.time', ([], {}), '()\n', (868, 870), False, 'import time\n'), ((1559, 1626), 'Bio.AlignIO.read', 'AlignIO.read', (['inputFilePath', 'inputFileType'], {'alphabet': 'alphabetFormat'}), '(inputFilePath, inputFileType, alphabet=alphabetFormat)\n', (1571, 1626), False, 'from Bio import Align... |
__author__ = "<NAME>"
__email__ = "<EMAIL>"
""" Baseline parallel BFS implementation.
Algorithm 1 Parallel BFS algorithm: High-level overview [1] was implemented.
Reference:
[1] https://www.researchgate.net/publication/220782745_Scalable_Graph_Exploration_on_Multicore_Processors
"""
import n... | [
"multiprocessing.cpu_count",
"src.load_graph.gen_balanced_tree",
"functools.partial",
"multiprocessing.Pool",
"numpy.concatenate",
"time.time"
] | [((1822, 1833), 'time.time', 'time.time', ([], {}), '()\n', (1831, 1833), False, 'import time\n'), ((1844, 1882), 'src.load_graph.gen_balanced_tree', 'gen_balanced_tree', (['(3)', '(4)'], {'directed': '(True)'}), '(3, 4, directed=True)\n', (1861, 1882), False, 'from src.load_graph import get_graph, gen_balanced_tree\n'... |
from django.conf.urls import url
from . import views
urlpatterns = [
# generic profile endpoint
url(r'^profile/(?P<username>\w+)/', views.profile, name='profile-api'),
# current user profile
url(r'^profile/', views.profile, name='profile-api'),
]
| [
"django.conf.urls.url"
] | [((106, 176), 'django.conf.urls.url', 'url', (['"""^profile/(?P<username>\\\\w+)/"""', 'views.profile'], {'name': '"""profile-api"""'}), "('^profile/(?P<username>\\\\w+)/', views.profile, name='profile-api')\n", (109, 176), False, 'from django.conf.urls import url\n'), ((209, 260), 'django.conf.urls.url', 'url', (['"""... |
from torch.utils.data import Dataset
import torch
import os
import pandas as pd
from PIL import Image
class Dataset(Dataset):
def __init__(self, csv_file, image_dir, mask_dir, img_col='image',
mask_col='mask', transform=None, batch_size=32):
"""
Args:
csv_file (P... | [
"torch.is_tensor",
"PIL.Image.open",
"os.path.join",
"pandas.read_csv"
] | [((1195, 1215), 'torch.is_tensor', 'torch.is_tensor', (['idx'], {}), '(idx)\n', (1210, 1215), False, 'import torch\n'), ((1338, 1376), 'os.path.join', 'os.path.join', (['self.image_dir', 'filename'], {}), '(self.image_dir, filename)\n', (1350, 1376), False, 'import os\n'), ((1525, 1562), 'os.path.join', 'os.path.join',... |
#!/usr/bin/python3
# count_mkdir.py
# Author: Guochao
# Created on 17-01-2022
# Print timing of mkdir
from bcc import BPF
program = r"""
#include <uapi/linux/ptrace.h>
BPF_HASH(count);
int do_trace(struct pt_regs *ctx) {
u64 c1 = 1, *cnt, delta, key = 1;
cnt = count.lookup(&key);
if (cnt != NULL)... | [
"bcc.BPF"
] | [((440, 457), 'bcc.BPF', 'BPF', ([], {'text': 'program'}), '(text=program)\n', (443, 457), False, 'from bcc import BPF\n')] |
import numpy as np
import numpy.testing as npt
import pytest
from openscm_units import unit_registry as ur
from test_model_base import TwoLayerVariantTester
from openscm_twolayermodel import ImpulseResponseModel, TwoLayerModel
from openscm_twolayermodel.base import _calculate_geoffroy_helper_parameters
from openscm_tw... | [
"numpy.testing.assert_equal",
"openscm_units.unit_registry",
"numpy.testing.assert_allclose",
"openscm_twolayermodel.base._calculate_geoffroy_helper_parameters",
"numpy.exp",
"numpy.array",
"openscm_twolayermodel.TwoLayerModel",
"numpy.isnan",
"pytest.raises"
] | [((1204, 1221), 'numpy.isnan', 'np.isnan', (['res.erf'], {}), '(res.erf)\n', (1212, 1221), True, 'import numpy as np\n'), ((1237, 1261), 'numpy.isnan', 'np.isnan', (['res._temp1_mag'], {}), '(res._temp1_mag)\n', (1245, 1261), True, 'import numpy as np\n'), ((1277, 1301), 'numpy.isnan', 'np.isnan', (['res._temp2_mag'], ... |
import pandas as pd
from util import StockAnalysis, AllStocks
import talib
import os
import numpy as np
class FilterEma:
def __init__(self, barCount, showtCount=None, longCount=None):
self.sa = StockAnalysis()
self.jsonData = self.sa.GetJson
self.trendLength = int(os.getenv('FILTER_TREND_LE... | [
"talib.EMA",
"os.getenv",
"util.StockAnalysis",
"util.AllStocks.GetDailyStockData",
"numpy.isnan",
"util.AllStocks.Run"
] | [((207, 222), 'util.StockAnalysis', 'StockAnalysis', ([], {}), '()\n', (220, 222), False, 'from util import StockAnalysis, AllStocks\n'), ((2150, 2185), 'util.AllStocks.GetDailyStockData', 'AllStocks.GetDailyStockData', (['symbol'], {}), '(symbol)\n', (2177, 2185), False, 'from util import StockAnalysis, AllStocks\n'),... |
import os
import sys
import inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(os.path.dirname(currentdir))
os.sys.path.insert(0,parentdir)
import os
sys.path.append(os.getcwd()+'/ReinforcementLearning')
import MyGym
import gym
import argparse
impo... | [
"argparse.ArgumentParser",
"inspect.currentframe",
"os.sys.path.insert",
"os.getcwd",
"time.sleep",
"os.path.dirname",
"time.time",
"gym.make"
] | [((180, 212), 'os.sys.path.insert', 'os.sys.path.insert', (['(0)', 'parentdir'], {}), '(0, parentdir)\n', (198, 212), False, 'import os\n'), ((151, 178), 'os.path.dirname', 'os.path.dirname', (['currentdir'], {}), '(currentdir)\n', (166, 178), False, 'import os\n'), ((918, 929), 'time.time', 'time.time', ([], {}), '()\... |
from src.trainer import train_by_config, test_by_config
import os
# train_by_config(os.path.join('settings', 'training_settings_7.ini'))
#
test_by_config(os.path.join('test_settings', 'test_settings.ini'))
| [
"os.path.join"
] | [((160, 210), 'os.path.join', 'os.path.join', (['"""test_settings"""', '"""test_settings.ini"""'], {}), "('test_settings', 'test_settings.ini')\n", (172, 210), False, 'import os\n')] |
from collections import deque
from itertools import islice
def test_1():
list = ['a', 'b', 'c']
d = deque(list)
assert 'a' == d[0] and 'b' == d[1] and 'c' == d[2], 'queue error'
def test_2():
data = islice(['a', 'b', 'c'],None)
d = deque(data)
assert 'a' == d[0] and 'b' == d[1] and 'c' == d[... | [
"itertools.islice",
"collections.deque"
] | [((110, 121), 'collections.deque', 'deque', (['list'], {}), '(list)\n', (115, 121), False, 'from collections import deque\n'), ((219, 248), 'itertools.islice', 'islice', (["['a', 'b', 'c']", 'None'], {}), "(['a', 'b', 'c'], None)\n", (225, 248), False, 'from itertools import islice\n'), ((256, 267), 'collections.deque'... |
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# %matplotlib inline
from IPython import get_ipython
get_ipython().run_line_magic('matplotlib', 'inline')
sns.set()
def gl_confmatrix_2_confmatrix(sf,number_label=3):
Nlabels=max(len(sf['target_label'].unique()),len(sf['predicted_label'].... | [
"IPython.get_ipython",
"seaborn.set",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"seaborn.heatmap",
"matplotlib.pyplot.figure",
"numpy.zeros",
"matplotlib.pyplot.title",
"matplotlib.pyplot.subplots"
] | [((182, 191), 'seaborn.set', 'sns.set', ([], {}), '()\n', (189, 191), True, 'import seaborn as sns\n'), ((342, 396), 'numpy.zeros', 'np.zeros', (['[number_label, number_label]'], {'dtype': 'np.float'}), '([number_label, number_label], dtype=np.float)\n', (350, 396), True, 'import numpy as np\n'), ((595, 643), 'matplotl... |
"""empty message
Revision ID: 2d70b2b7f421
Revises: <PASSWORD>
Create Date: 2017-01-07 15:40:46.326596
"""
# revision identifiers, used by Alembic.
revision = '2d70b2b7f421'
down_revision = '<PASSWORD>'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - plea... | [
"sqlalchemy.INTEGER",
"alembic.op.drop_column"
] | [((339, 378), 'alembic.op.drop_column', 'op.drop_column', (['"""company"""', '"""com_number"""'], {}), "('company', 'com_number')\n", (353, 378), False, 'from alembic import op\n'), ((383, 422), 'alembic.op.drop_column', 'op.drop_column', (['"""company"""', '"""tax_number"""'], {}), "('company', 'tax_number')\n", (397,... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2014 Intel 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/lice... | [
"sqlalchemy.engine.reflection.Inspector.from_engine"
] | [((1291, 1339), 'sqlalchemy.engine.reflection.Inspector.from_engine', 'reflection.Inspector.from_engine', (['migrate_engine'], {}), '(migrate_engine)\n', (1323, 1339), False, 'from sqlalchemy.engine import reflection\n')] |
import argparse
parser = argparse.ArgumentParser(description='This script takes a dihedral trajectory and detects change points using SIMPLE (simultaneous Penalized Likelihood Estimation, see Fan et al. P. Natl. Acad. Sci, 2015, 112, 7454-7459). Two parameters alpha and lambda are controlling the extent of simultaneous... | [
"numpy.loadtxt",
"SIMPLEchangepoint.ComputeChanges",
"argparse.ArgumentParser"
] | [((25, 487), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""This script takes a dihedral trajectory and detects change points using SIMPLE (simultaneous Penalized Likelihood Estimation, see Fan et al. P. Natl. Acad. Sci, 2015, 112, 7454-7459). Two parameters alpha and lambda are controll... |
import unittest
from context import html2md
from assertions import assertEq
class DefinitioListTests(unittest.TestCase):
def test_basic(self):
in_html = u'''
<dl>
<dt>Apple</dt>
<dd>Pomaceous fruit of plants of the genus Malus in
the family Rosaceae.</dd>
<dt>Orange</dt>
<dd>The fruit of an evergreen tr... | [
"unittest.main",
"context.html2md.html2md",
"unittest.TestLoader"
] | [((2109, 2124), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2122, 2124), False, 'import unittest\n'), ((565, 604), 'context.html2md.html2md', 'html2md.html2md', (['in_html'], {'def_list': '(True)'}), '(in_html, def_list=True)\n', (580, 604), False, 'from context import html2md\n'), ((1115, 1154), 'context.html... |
import gym
from gym.spaces.box import Box
class TransposeImagesIfRequired(gym.ObservationWrapper):
"""
When environment observations are images, this wrapper transposes
the axis. It is useful when the images have shape (W,H,C), as they can be
transposed "on the fly" to (C,W,H) for PyTorch convolutions... | [
"gym.spaces.box.Box"
] | [((902, 1097), 'gym.spaces.box.Box', 'Box', (['self.observation_space.low[0, 0, 0]', 'self.observation_space.high[0, 0, 0]', '[obs_shape[self.op[0]], obs_shape[self.op[1]], obs_shape[self.op[2]]]'], {'dtype': 'self.observation_space.dtype'}), '(self.observation_space.low[0, 0, 0], self.observation_space.high[0, 0, \n ... |
# File: guess.py
# Author: <NAME>
# Date: 11/21/2019
'''A guessing game.
This is the classic game where someone thinks of a secret number and someone
else tries to guess it. In this case, the computer thinks of the number and we
(the user) have to guess what it is.
'''
# LEARN: Python has a standard module for deali... | [
"random.randint"
] | [((632, 658), 'random.randint', 'random.randint', (['(1)', 'HIGHEST'], {}), '(1, HIGHEST)\n', (646, 658), False, 'import random\n')] |
# Copyright (c) 2021 ComputerAlgorithmsGroupAtKyotoU
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, mer... | [
"digraphillion.DiGraphSet.graphs",
"digraphillion.DiGraphSet.directed_st_paths",
"digraphillion.DiGraphSet.rooted_forests",
"digraphillion.DiGraphSet.rooted_trees",
"graphillion.GraphSet.set_universe",
"digraphillion.DiGraphSet.directed_cycles",
"unittest.main",
"digraphillion.DiGraphSet.directed_hami... | [((11825, 11840), 'unittest.main', 'unittest.main', ([], {}), '()\n', (11838, 11840), False, 'import unittest\n'), ((1650, 1662), 'digraphillion.DiGraphSet', 'DiGraphSet', ([], {}), '()\n', (1660, 1662), False, 'from digraphillion import DiGraphSet\n'), ((1745, 1784), 'digraphillion.DiGraphSet.set_universe', 'DiGraphSe... |
from pathlib import Path
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
with open(Path('tmp.txt'), 'r') as f:
lines_read = f.readlines()
lines = list()
for line in lines_read:
lines.append(line.split())
labels = list()
naive_time = list()
kapra_time = list()
for index, line in enumerat... | [
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.subplots",
"pathlib.Path"
] | [((595, 609), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (607, 609), True, 'import matplotlib.pyplot as plt\n'), ((1459, 1482), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""stat.png"""'], {}), "('stat.png')\n", (1470, 1482), True, 'import matplotlib.pyplot as plt\n'), ((105, 120), 'pathlib.Pat... |
from datetime import date
from datetime import datetime
from datetime import timedelta
from datetime import timezone
class CommonDate(object):
DEFAULT_ZONE = timezone(offset=timedelta(hours=8))
@staticmethod
def today(tz=DEFAULT_ZONE):
return date.today()
@staticmethod
def today_time(tz=... | [
"datetime.datetime.fromtimestamp",
"datetime.timedelta",
"datetime.datetime.now",
"datetime.datetime.timestamp",
"datetime.date.today"
] | [((266, 278), 'datetime.date.today', 'date.today', ([], {}), '()\n', (276, 278), False, 'from datetime import date\n'), ((2239, 2253), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (2251, 2253), False, 'from datetime import datetime\n'), ((180, 198), 'datetime.timedelta', 'timedelta', ([], {'hours': '(8)'}... |
#!/usr/bin/env python
# encoding: utf-8
"""
@author:nikan
@file: project.py
@time: 2018/5/14 下午4:20
"""
import datetime
from sqlalchemy import text
from sqlalchemy.dialects import mysql
from PyScraper.server.extensions import db
class Project(db.Model):
__tablename__ = "project"
project_id = db.Column(d... | [
"PyScraper.server.extensions.db.Column",
"PyScraper.server.extensions.db.String",
"sqlalchemy.text"
] | [((309, 380), 'PyScraper.server.extensions.db.Column', 'db.Column', (['db.Integer'], {'autoincrement': '(True)', 'primary_key': '(True)', 'doc': '"""自增id"""'}), "(db.Integer, autoincrement=True, primary_key=True, doc='自增id')\n", (318, 380), False, 'from PyScraper.server.extensions import db\n'), ((468, 501), 'PyScraper... |
import os
from bottle import Bottle, static_file, run
HERE = os.path.abspath(os.path.dirname(__file__))
STATIC = os.path.join(HERE, 'static')
app = Bottle()
@app.route('/')
@app.route('/<filename:path>')
def serve(filename='index.html'):
return static_file(filename, root=STATIC)
if __name__ == '__main__':
... | [
"bottle.static_file",
"bottle.Bottle",
"os.path.join",
"os.path.dirname",
"bottle.run"
] | [((114, 142), 'os.path.join', 'os.path.join', (['HERE', '"""static"""'], {}), "(HERE, 'static')\n", (126, 142), False, 'import os\n'), ((150, 158), 'bottle.Bottle', 'Bottle', ([], {}), '()\n', (156, 158), False, 'from bottle import Bottle, static_file, run\n'), ((78, 103), 'os.path.dirname', 'os.path.dirname', (['__fil... |
import unittest
from model.game import Game
class GameTest(unittest.TestCase):
def setUp(self):
self.game = Game()
def test_next_player(self):
first_player = self.game.next_player
self.game.turn(0, 0)
second_player = self.game.next_player
self.game.turn(1, 0)
... | [
"model.game.Game"
] | [((122, 128), 'model.game.Game', 'Game', ([], {}), '()\n', (126, 128), False, 'from model.game import Game\n')] |
# -*-coding:utf-8 -*-
import pymongo
from pyramid.config import Configurator
from pyramid.events import subscriber
from pyramid.events import NewRequest
from pyramid.request import Request
from pyramid.authentication import AuthTktAuthenticationPolicy
from pyramid.authorization import ACLAuthorizationPolicy
from wf_b... | [
"pyramid.security.unauthenticated_userid",
"pyramid.threadlocal.get_current_registry",
"pyramid.authentication.AuthTktAuthenticationPolicy",
"pyramid_beaker.session_factory_from_settings",
"pyramid.config.Configurator",
"pyramid.authorization.ACLAuthorizationPolicy",
"wf_blog.model.User.get_user",
"wf... | [((1157, 1228), 'pyramid.authentication.AuthTktAuthenticationPolicy', 'AuthTktAuthenticationPolicy', (["settings['security']"], {'callback': 'groupfinder'}), "(settings['security'], callback=groupfinder)\n", (1184, 1228), False, 'from pyramid.authentication import AuthTktAuthenticationPolicy\n'), ((1248, 1272), 'pyrami... |
# #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
MIT License
Copyright (c) 2019 magnusoy
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including with... | [
"communication.SerialCommunication"
] | [((1305, 1355), 'communication.SerialCommunication', 'SerialCommunication', ([], {'port': '"""COM10"""', 'baudrate': '(115200)'}), "(port='COM10', baudrate=115200)\n", (1324, 1355), False, 'from communication import SerialCommunication\n')] |
# -*- coding: utf-8 -*-
# Review Heatmap Add-on for Anki
#
# Copyright (C) 2016-2018 <NAME>. <https//glutanimate.com/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3... | [
"aqt.mw.col.db.scalar",
"anki.utils.ids2str",
"datetime.datetime.fromtimestamp"
] | [((6205, 6250), 'datetime.datetime.fromtimestamp', 'datetime.datetime.fromtimestamp', (['self.col.crt'], {}), '(self.col.crt)\n', (6236, 6250), False, 'import datetime\n'), ((7189, 7210), 'aqt.mw.col.db.scalar', 'mw.col.db.scalar', (['cmd'], {}), '(cmd)\n', (7205, 7210), False, 'from aqt import mw\n'), ((9756, 9769), '... |
import os
import pandas as pd
import numpy as np
from collections import Counter, defaultdict
def train_from_file(dir_path, leap_limit=15):
file_list = os.listdir(dir_path)
pig_format = [
"id",
"onset",
"offset",
"pitch",
"onsetvel",
"offsetvel",
"hand"... | [
"pandas.Series",
"numpy.tile",
"os.listdir",
"numpy.triu_indices",
"pandas.read_csv",
"numpy.log",
"numpy.argmax",
"pandas.DataFrame.from_dict",
"collections.Counter",
"numpy.zeros",
"numpy.apply_along_axis",
"collections.defaultdict",
"pandas.DataFrame",
"numpy.tril_indices",
"numpy.ama... | [((158, 178), 'os.listdir', 'os.listdir', (['dir_path'], {}), '(dir_path)\n', (168, 178), False, 'import os\n'), ((367, 376), 'collections.Counter', 'Counter', ([], {}), '()\n', (374, 376), False, 'from collections import Counter, defaultdict\n'), ((406, 415), 'collections.Counter', 'Counter', ([], {}), '()\n', (413, 4... |
import cocos
import pyglet
from world import Terrain
TERRAIN_TEXTURES = {Terrain.GRASS: 'grass.png', Terrain.DIRT: 'dirt.png',
Terrain.WATER: 'water.png', Terrain.MOUNTAIN: 'mountain.png'}
CELL_SIZE = 32
DEFAULT_CHARACTER = pyglet.resource.image('res/img/dummy.png')
class WorldMap(cocos.tiles.Re... | [
"pyglet.resource.image",
"cocos.tiles.TileSet",
"cocos.tiles.RectCell",
"pyglet.graphics.Batch",
"cocos.sprite.Sprite",
"pyglet.sprite.Sprite",
"pyglet.graphics.draw"
] | [((246, 288), 'pyglet.resource.image', 'pyglet.resource.image', (['"""res/img/dummy.png"""'], {}), "('res/img/dummy.png')\n", (267, 288), False, 'import pyglet\n'), ((623, 651), 'cocos.tiles.TileSet', 'cocos.tiles.TileSet', (['(0)', 'None'], {}), '(0, None)\n', (642, 651), False, 'import cocos\n'), ((2231, 2254), 'pygl... |
import pymongo
import numpy as np
from tqdm import tqdm
from datetime import datetime, timedelta
def mongo_query(**kwargs):
"""Create a MongoDB query based on a set of conditions."""
query = {}
if 'start_date' in kwargs:
if not ('CreationDate' in query):
query['CreationDate'] = {}
... | [
"datetime.datetime",
"tqdm.tqdm",
"numpy.array_split",
"pymongo.MongoClient",
"datetime.timedelta"
] | [((1136, 1162), 'datetime.datetime', 'datetime', (['year', 'month', 'day'], {}), '(year, month, day)\n', (1144, 1162), False, 'from datetime import datetime, timedelta\n'), ((822, 848), 'datetime.datetime', 'datetime', (['start_year', '(1)', '(1)'], {}), '(start_year, 1, 1)\n', (830, 848), False, 'from datetime import ... |
import sys
import os
import subprocess
import text
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
from distutils.util import convert_path
def _find_packages(where='.', exclude=()):
"""Return a list all Python packages found within director... | [
"os.listdir",
"fnmatch.fnmatchcase",
"distutils.util.convert_path",
"setuptools.find_packages",
"os.path.join",
"os.path.isdir",
"subprocess.call",
"sys.exit"
] | [((1748, 1788), 'subprocess.call', 'subprocess.call', (['PUBLISH_CMD'], {'shell': '(True)'}), '(PUBLISH_CMD, shell=True)\n', (1763, 1788), False, 'import subprocess\n'), ((1793, 1809), 'sys.exit', 'sys.exit', (['status'], {}), '(status)\n', (1801, 1809), False, 'import sys\n'), ((1994, 2039), 'subprocess.call', 'subpro... |
from __future__ import absolute_import, unicode_literals
import warnings
from unittest import TestCase
from immutable import Immutable, ImmutableFactory
warnings.filterwarnings("ignore")
class TestImmutableObjectFactory(TestCase):
def test_create_empty(self):
# unlike a namedtuple, you don't even nee... | [
"immutable.ImmutableFactory",
"immutable.ImmutableFactory.create",
"immutable.Immutable",
"warnings.filterwarnings"
] | [((156, 189), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (179, 189), False, 'import warnings\n'), ((363, 388), 'immutable.ImmutableFactory.create', 'ImmutableFactory.create', ([], {}), '()\n', (386, 388), False, 'from immutable import Immutable, ImmutableFactory\n'), (... |
# Generated by Django 2.2.6 on 2019-10-15 19:17
import uuid
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("children", "0001_initial")]
operations = [
migrations.RenameField(model_name="child", old_name="uuid", new_name="id"),
migrations.Rem... | [
"django.db.migrations.RemoveField",
"django.db.migrations.RenameField",
"django.db.models.UUIDField"
] | [((222, 296), 'django.db.migrations.RenameField', 'migrations.RenameField', ([], {'model_name': '"""child"""', 'old_name': '"""uuid"""', 'new_name': '"""id"""'}), "(model_name='child', old_name='uuid', new_name='id')\n", (244, 296), False, 'from django.db import migrations, models\n'), ((306, 384), 'django.db.migration... |
#!/usr/bin/env python3
# Foundations of Python Network Programming, Third Edition
# https://github.com/brandon-rhodes/fopnp/blob/m/py3/chapter17/recursedl.py
from ftplib import FTP, error_perm
def walk_dir(ftp, dirpath):
original_dir = ftp.pwd()
try:
ftp.cwd(dirpath)
except error_perm:
ret... | [
"ftplib.FTP"
] | [((571, 592), 'ftplib.FTP', 'FTP', (['"""ftp.kernel.org"""'], {}), "('ftp.kernel.org')\n", (574, 592), False, 'from ftplib import FTP, error_perm\n')] |
from allauth.socialaccount import providers
from django import template
register = template.Library()
@register.simple_tag
def get_user_social_providers(user):
user_providers = set()
for account in user.socialaccount_set.all():
user_providers.add(account.get_provider())
return list(user_providers... | [
"django.template.Library",
"allauth.socialaccount.providers.registry.get_list"
] | [((84, 102), 'django.template.Library', 'template.Library', ([], {}), '()\n', (100, 102), False, 'from django import template\n'), ((548, 577), 'allauth.socialaccount.providers.registry.get_list', 'providers.registry.get_list', ([], {}), '()\n', (575, 577), False, 'from allauth.socialaccount import providers\n')] |
from uninas.utils.args import Argument
from uninas.register import Register
from uninas.methods.abstract import AbstractBiOptimizationMethod
from uninas.methods.strategies.manager import StrategyManager
from uninas.methods.strategies.differentiable import DifferentiableStrategy
@Register.method(search=True)
class Asa... | [
"uninas.methods.strategies.differentiable.DifferentiableStrategy",
"uninas.register.Register.method",
"uninas.utils.args.Argument",
"uninas.methods.strategies.manager.StrategyManager"
] | [((282, 310), 'uninas.register.Register.method', 'Register.method', ([], {'search': '(True)'}), '(search=True)\n', (297, 310), False, 'from uninas.register import Register\n'), ((1323, 1388), 'uninas.methods.strategies.differentiable.DifferentiableStrategy', 'DifferentiableStrategy', (['self.max_epochs'], {'tau': 'tau_... |
from flask import Blueprint, render_template, request
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from .models import User
from .basilica_service import connection as basilica_c... | [
"sklearn.datasets.load_iris",
"flask.render_template",
"sklearn.ensemble.RandomForestClassifier",
"sklearn.linear_model.LogisticRegression",
"flask.Blueprint",
"sklearn.metrics.accuracy_score"
] | [((346, 381), 'flask.Blueprint', 'Blueprint', (['"""stats_routes"""', '__name__'], {}), "('stats_routes', __name__)\n", (355, 381), False, 'from flask import Blueprint, render_template, request\n'), ((491, 517), 'sklearn.datasets.load_iris', 'load_iris', ([], {'return_X_y': '(True)'}), '(return_X_y=True)\n', (500, 517)... |
import pandas as pd
dataset = pd.read_csv('iris.csv')
dataset.boxplot(column = 'sepal_width',by = 'species')
import matplotlib.pyplot as plt
hours_slices = [8,16]
activities = ['work','sleep']
colors = ['g','r']
plt.pie(hours_slices,labels=activities,colors=colors,startangle=90,autopct='%.1f%%')
plt.show()
... | [
"matplotlib.pyplot.pie",
"pandas.read_csv",
"matplotlib.pyplot.show"
] | [((30, 53), 'pandas.read_csv', 'pd.read_csv', (['"""iris.csv"""'], {}), "('iris.csv')\n", (41, 53), True, 'import pandas as pd\n'), ((215, 307), 'matplotlib.pyplot.pie', 'plt.pie', (['hours_slices'], {'labels': 'activities', 'colors': 'colors', 'startangle': '(90)', 'autopct': '"""%.1f%%"""'}), "(hours_slices, labels=a... |
# -*- coding: utf-8 -*-
'''
Copyright (c) 2021 <NAME>.
This file is part of HermesBot.
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 requir... | [
"discord.ext.commands.command"
] | [((1050, 1147), 'discord.ext.commands.command', 'commands.command', ([], {'name': '"""connect"""', 'aliases': "['join']", 'help': '"""- Call bot to your voice channel."""'}), "(name='connect', aliases=['join'], help=\n '- Call bot to your voice channel.')\n", (1066, 1147), False, 'from discord.ext import commands\n'... |
from PIL import Image
my_image = Image.open("assets/images/splashscreen_background.png")
width, height = my_image.size
print(height)
| [
"PIL.Image.open"
] | [((35, 90), 'PIL.Image.open', 'Image.open', (['"""assets/images/splashscreen_background.png"""'], {}), "('assets/images/splashscreen_background.png')\n", (45, 90), False, 'from PIL import Image\n')] |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Interpreter version: python 2.7
#
# Imports =====================================================================
import xmltodict
from odictliteral import odict
from kwargs_obj import KwargsObj
from tools import both_set_and_different
# Functions & classes ========... | [
"tools.both_set_and_different",
"xmltodict.parse",
"xmltodict.unparse"
] | [((4150, 4170), 'xmltodict.parse', 'xmltodict.parse', (['xml'], {}), '(xml)\n', (4165, 4170), False, 'import xmltodict\n'), ((3091, 3127), 'xmltodict.unparse', 'xmltodict.unparse', (['root'], {'pretty': '(True)'}), '(root, pretty=True)\n', (3108, 3127), False, 'import xmltodict\n'), ((1821, 1870), 'tools.both_set_and_d... |
"""Test for Simple Content Chunkifyer"""
import unittest
from PiCN.Layers.ChunkLayer.Chunkifyer import SimpleContentChunkifyer
from PiCN.Packets import Content, Name
class test_SimpleContentChunkifyer(unittest.TestCase):
def setUp(self):
self.chunkifyer = SimpleContentChunkifyer()
def tearDown(sel... | [
"PiCN.Packets.Content",
"PiCN.Packets.Name",
"PiCN.Layers.ChunkLayer.Chunkifyer.SimpleContentChunkifyer"
] | [((273, 298), 'PiCN.Layers.ChunkLayer.Chunkifyer.SimpleContentChunkifyer', 'SimpleContentChunkifyer', ([], {}), '()\n', (296, 298), False, 'from PiCN.Layers.ChunkLayer.Chunkifyer import SimpleContentChunkifyer\n'), ((454, 472), 'PiCN.Packets.Name', 'Name', (['"""/test/data"""'], {}), "('/test/data')\n", (458, 472), Fal... |
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from pyspawn._graph.relationship import Relationship
from dataclasses import dataclass
from typing import Set
@dataclass(frozen=False)
class Table:
"""Table class"""
schema: str
table_name: str
def __post_init__(self):
self.relationship... | [
"dataclasses.dataclass"
] | [((169, 192), 'dataclasses.dataclass', 'dataclass', ([], {'frozen': '(False)'}), '(frozen=False)\n', (178, 192), False, 'from dataclasses import dataclass\n')] |
# pylint: disable=fixme, line-too-long, import-error, no-name-in-module
#
# Copyright (c) 2020 Synopsys, Inc.
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownersh... | [
"os.path.exists",
"getopt.getopt",
"re.split",
"pip.download.PipSession",
"pip.__version__.split",
"pkg_resources.Requirement.parse",
"sys.exit"
] | [((1524, 1550), 'pip.__version__.split', 'pip.__version__.split', (['"""."""'], {}), "('.')\n", (1545, 1550), False, 'import pip\n'), ((2058, 2121), 'getopt.getopt', 'getopt', (['sys.argv[1:]', '"""p:r:"""', "['projectname=', 'requirements=']"], {}), "(sys.argv[1:], 'p:r:', ['projectname=', 'requirements='])\n", (2064,... |
import json
import logging
import hashlib
from actingweb import on_aw
from armyknife_src import webexrequest
from armyknife_src import webexbothandler
from armyknife_src import webexmessagehandler
from armyknife_src import fargate
PROP_HIDE = [
"email",
"oauthId"
]
PROP_PROTECT = PROP_HIDE + [
"service_st... | [
"hashlib.sha256",
"armyknife_src.webexrequest.WebexTeamsRequest",
"logging.debug",
"json.dumps",
"logging.warning",
"armyknife_src.fargate.in_fargate",
"armyknife_src.fargate.fargate_disabled",
"armyknife_src.webexbothandler.WebexTeamsBotHandler",
"logging.info",
"armyknife_src.webexmessagehandler... | [((2988, 3110), 'armyknife_src.webexrequest.WebexTeamsRequest', 'webexrequest.WebexTeamsRequest', ([], {'body': 'self.webobj.request.body', 'auth': 'self.auth', 'myself': 'self.myself', 'config': 'self.config'}), '(body=self.webobj.request.body, auth=self.\n auth, myself=self.myself, config=self.config)\n', (3018, 3... |
import os, sys
import warnings
__thisdir__ = os.path.dirname(os.path.realpath(__file__))
# Testing the import of the numpy package
def test_import_numpy():
try:
import numpy as np
except ImportError as e:
assert(1 == 0), "Numpy could not be imported:\n %s" %e
sys.path.pop(0)
# Testing the ... | [
"os.path.realpath",
"sys.path.pop",
"sys.path.insert"
] | [((61, 87), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (77, 87), False, 'import os, sys\n'), ((289, 304), 'sys.path.pop', 'sys.path.pop', (['(0)'], {}), '(0)\n', (301, 304), False, 'import os, sys\n'), ((506, 521), 'sys.path.pop', 'sys.path.pop', (['(0)'], {}), '(0)\n', (518, 521), Fals... |
# coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from xcube_hub.models.base_model_ import Model
from xcube_hub import util
class CubegenConfigCodeConfigFileSet(Model):
"""NOTE: This class is auto generated by Op... | [
"xcube_hub.util.deserialize_model"
] | [((1173, 1206), 'xcube_hub.util.deserialize_model', 'util.deserialize_model', (['dikt', 'cls'], {}), '(dikt, cls)\n', (1195, 1206), False, 'from xcube_hub import util\n')] |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-09-29 22:13
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hostmanager', '0001_initial'),
]
operations = [
migrations.AlterField(
... | [
"django.db.models.CharField"
] | [((390, 562), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'help_text': '"""Will be automatically populated if the domain is registered."""', 'max_length': '(255)', 'null': '(True)', 'verbose_name': '"""IP Address"""'}), "(blank=True, help_text=\n 'Will be automatically po... |
# Generated by Django 3.2.4 on 2021-06-28 14:12
import django.db.models.deletion # noqa
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("contenttypes", "0002_remove_content_type_name"),
("wagtailsearch", "0004_querydailyhits_verbose_name_plural... | [
"django.db.migrations.AlterUniqueTogether",
"django.db.models.FloatField",
"django.db.models.ForeignKey",
"django.db.models.AutoField",
"django.db.models.CharField"
] | [((1365, 1468), 'django.db.migrations.AlterUniqueTogether', 'migrations.AlterUniqueTogether', ([], {'name': '"""indexentry"""', 'unique_together': "{('content_type', 'object_id')}"}), "(name='indexentry', unique_together={(\n 'content_type', 'object_id')})\n", (1395, 1468), False, 'from django.db import migrations, ... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
import torch.nn.functional as F
from torch import nn
from maskrcnn_benchmark.modeling import registry
from maskrcnn_benchmark.modeling.rbox_coder import RBoxCoder
from maskrcnn_benchmark.layers import Mish
from .loss import make_rpn_l... | [
"torch.nn.GroupNorm",
"torch.nn.ReLU",
"torch.nn.init.constant_",
"ipdb.set_trace",
"torch.nn.Sequential",
"torch.nn.Conv2d",
"maskrcnn_benchmark.modeling.registry.RPN_HEADS.register",
"maskrcnn_benchmark.layers.Mish",
"maskrcnn_benchmark.modeling.rbox_coder.RBoxCoder",
"torch.no_grad",
"torch.n... | [((1413, 1462), 'maskrcnn_benchmark.modeling.registry.RPN_HEADS.register', 'registry.RPN_HEADS.register', (['"""SingleConvARPNHead"""'], {}), "('SingleConvARPNHead')\n", (1440, 1462), False, 'from maskrcnn_benchmark.modeling import registry\n'), ((3123, 3174), 'maskrcnn_benchmark.modeling.registry.RPN_HEADS.register', ... |
import matplotlib.pyplot as plt
import numpy as np
plt.style.use('seaborn-darkgrid')
x = range(8)
y = np.linspace(1.1, 5.0, 8)
ylabel = map(lambda num: bin(num)[2:], x)
xlabel = map(lambda num: "{0:.2f}".format(num), y)
plt.step(x, y)
plt.yticks(y, ylabel)
plt.xticks(x, xlabel, rotation=45)
plt.ylabel("Binary Output... | [
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.style.use",
"numpy.linspace",
"matplotlib.pyplot.yticks",
"matplotlib.pyplot.step"
] | [((51, 84), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""seaborn-darkgrid"""'], {}), "('seaborn-darkgrid')\n", (64, 84), True, 'import matplotlib.pyplot as plt\n'), ((103, 127), 'numpy.linspace', 'np.linspace', (['(1.1)', '(5.0)', '(8)'], {}), '(1.1, 5.0, 8)\n', (114, 127), True, 'import numpy as np\n'), ((223... |
"""The Tesla Wall Charger Director integration."""
import asyncio
from twcdirector.listener import TWCListener
from twcdirector.device import TWCPeripheral
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.const import (EVENT_HOMEASSISTANT_STOP)
from... | [
"logging.getLogger",
"twcdirector.listener.TWCListener",
"asyncio.Queue"
] | [((475, 502), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (492, 502), False, 'import logging\n'), ((1244, 1275), 'twcdirector.listener.TWCListener', 'TWCListener', ([], {}), '(**listener_options)\n', (1255, 1275), False, 'from twcdirector.listener import TWCListener\n'), ((1788, 1803),... |
import pygame
from pygame.locals import QUIT, KEYDOWN, K_q, K_ESCAPE, K_BACKQUOTE, MOUSEBUTTONDOWN
from resources.resourcemgr import ResourceMgr
from scenes.game_scene import GameScene
def main():
pygame.init()
SCREEN_SIZE = (1280, 800)
surface = pygame.display.set_mode(SCREEN_SIZE, 0, 32)
clock = py... | [
"pygame.init",
"pygame.event.get",
"pygame.display.set_mode",
"resources.resourcemgr.ResourceMgr",
"pygame.mouse.get_pos",
"pygame.time.Clock",
"pygame.display.update"
] | [((204, 217), 'pygame.init', 'pygame.init', ([], {}), '()\n', (215, 217), False, 'import pygame\n'), ((262, 305), 'pygame.display.set_mode', 'pygame.display.set_mode', (['SCREEN_SIZE', '(0)', '(32)'], {}), '(SCREEN_SIZE, 0, 32)\n', (285, 305), False, 'import pygame\n'), ((318, 337), 'pygame.time.Clock', 'pygame.time.Cl... |
from src.modelo.cancion import Cancion
from src.modelo.interprete import Interprete
from src.modelo.album import Album, Medio
from src.modelo.declarative_base import Session, engine, Base
from src.logica.coleccion import Coleccion
def anadir_album (titulo , anio , descripcion , medio) :
# Crea la BD
Base.metada... | [
"src.modelo.cancion.Cancion",
"src.modelo.declarative_base.Base.metadata.create_all",
"src.modelo.interprete.Interprete",
"src.modelo.album.Album",
"src.logica.coleccion.Coleccion",
"src.modelo.declarative_base.Session"
] | [((309, 341), 'src.modelo.declarative_base.Base.metadata.create_all', 'Base.metadata.create_all', (['engine'], {}), '(engine)\n', (333, 341), False, 'from src.modelo.declarative_base import Session, engine, Base\n'), ((379, 388), 'src.modelo.declarative_base.Session', 'Session', ([], {}), '()\n', (386, 388), False, 'fr... |
from __future__ import absolute_import, division, print_function, unicode_literals
import json
from postgres.orm import Model
from psycopg2 import IntegrityError
from urlparse import urlsplit, urlunsplit
import xml.etree.ElementTree as ET
import xmltodict
from aspen import Response
from gratipay.exceptions import Pro... | [
"gratipay.security.user.User.from_username",
"urlparse.urlunsplit",
"xml.etree.ElementTree.tostring",
"json.dumps",
"gratipay.utils.username.safely_reserve_a_username",
"aspen.Response",
"urlparse.urlsplit"
] | [((2783, 2807), 'json.dumps', 'json.dumps', (['i.extra_info'], {}), '(i.extra_info)\n', (2793, 2807), False, 'import json\n'), ((5186, 5231), 'gratipay.security.user.User.from_username', 'User.from_username', (['self.participant.username'], {}), '(self.participant.username)\n', (5204, 5231), False, 'from gratipay.secur... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class Conv2d(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, NL='relu', same_padding=False, bn=False, dilation=1):
super(Conv2d, self).__init__()
padding = int((kernel_size - 1) // 2) if same_padding... | [
"torch.nn.BatchNorm2d",
"torch.nn.ReLU",
"torch.nn.init.constant_",
"torch.nn.Conv2d",
"torch.nn.PReLU",
"torch.nn.init.normal_",
"torch.nn.MaxPool2d",
"torch.nn.functional.interpolate",
"torch.cat"
] | [((3008, 3034), 'torch.cat', 'torch.cat', (['(x1, x2, x3)', '(1)'], {}), '((x1, x2, x3), 1)\n', (3017, 3034), False, 'import torch\n'), ((399, 496), 'torch.nn.Conv2d', 'nn.Conv2d', (['in_channels', 'out_channels', 'kernel_size', 'stride'], {'padding': 'padding', 'dilation': 'dilation'}), '(in_channels, out_channels, ke... |
from .piece import Piece
from typing import Optional
from colorama import init
from termcolor import colored
init()
class Field:
def __init__(self, piece: Optional[Piece] = None) -> None:
self._piece = piece
def get_piece(self) -> Optional[Piece]:
return self._piece
def put_piece(self,... | [
"colorama.init"
] | [((111, 117), 'colorama.init', 'init', ([], {}), '()\n', (115, 117), False, 'from colorama import init\n')] |
from time import sleep
import emoji
print('AGUARDE A CONTAGEM PARA OS FOGOS')
for c in range(10, 0, -1):
print(c)
sleep(1)
print(emoji.emojize("Detonação dos fogos :sunny: ", use_aliases=True))
print('FIM') | [
"emoji.emojize",
"time.sleep"
] | [((123, 131), 'time.sleep', 'sleep', (['(1)'], {}), '(1)\n', (128, 131), False, 'from time import sleep\n'), ((138, 201), 'emoji.emojize', 'emoji.emojize', (['"""Detonação dos fogos :sunny: """'], {'use_aliases': '(True)'}), "('Detonação dos fogos :sunny: ', use_aliases=True)\n", (151, 201), False, 'import emoji\n')] |
#funcsboot.py
from placerg.funcs import *
from placerg.funcsrg import *
from placerg.funcsall import *
from placerg.objects import *
from scipy.optimize import curve_fit
def bootfunc(a, env):
rate=[]
coeff=[]
eigspec=[]
var=[]
psil=[]
actmom=[]
autocorr=[]
tau=[]
... | [
"scipy.optimize.curve_fit"
] | [((960, 1006), 'scipy.optimize.curve_fit', 'curve_fit', (['linfunc', 'plott[0][:4]', 'plott[1][:4]'], {}), '(linfunc, plott[0][:4], plott[1][:4])\n', (969, 1006), False, 'from scipy.optimize import curve_fit\n'), ((1180, 1205), 'scipy.optimize.curve_fit', 'curve_fit', (['probfunc', 'x', 'y'], {}), '(probfunc, x, y)\n',... |
# -*- coding: UTF-8 -*-
# 该算法比较慢
import operator
# 牌型枚举
class ComeType:
PASS, SINGLE, PAIR, TRIPLE, TRIPLE_ONE, TRIPLE_TWO, FOURTH_TWO_ONES, FOURTH_TWO_PAIRS, STRAIGHT, EVEN_PAIR, BOMB = \
range(11)
# 3-14 分别代表 3-10, J, Q, K, A
# 16, 18, 19 分别代表 2, little_joker, big_joker
# 将 2 与其他牌分开是为了方便计算顺子
# 定义 HAN... | [
"operator.eq",
"time.clock"
] | [((7683, 7695), 'time.clock', 'time.clock', ([], {}), '()\n', (7693, 7695), False, 'import time\n'), ((7783, 7795), 'time.clock', 'time.clock', ([], {}), '()\n', (7793, 7795), False, 'import time\n'), ((9557, 9569), 'time.clock', 'time.clock', ([], {}), '()\n', (9567, 9569), False, 'import time\n'), ((8588, 8600), 'tim... |
# -*- coding: utf-8 -*-
def main():
from math import ceil
import sys
input = sys.stdin.readline
a, b = map(int, input().split())
ans = 1
for i in range(1, b):
z = ceil(a / i)
if i * (z + 1) <= b:
ans = max(ans, i)
print(ans)
if __name__ == "__main__":
... | [
"math.ceil"
] | [((200, 211), 'math.ceil', 'ceil', (['(a / i)'], {}), '(a / i)\n', (204, 211), False, 'from math import ceil\n')] |
"""
This script generates number list text files
Number list contains stem of filenames
Number list specifies the files used for a certain data split
Prefix:
- training: 0 (training/)
- validation: 1 (training/)
- testing: 2 (testing/)
- domain adaptation training labell... | [
"glob.glob"
] | [((866, 906), 'glob.glob', 'glob.glob', (["(path + '/' + prefix + '*.txt')"], {}), "(path + '/' + prefix + '*.txt')\n", (875, 906), False, 'import glob\n')] |
# author: Bartlomiej "furas" Burek (https://blog.furas.pl)
# date: 2022.03.07
# [javascript - export gpx file with python? - Stack Overflow](https://stackoverflow.com/questions/71375579/export-gpx-file-with-python/71375874#71375874)
import requests
start_lon = -0.0898 # can be also as text
start_lat = 51.514739 #... | [
"requests.get"
] | [((790, 823), 'requests.get', 'requests.get', (['url'], {'params': 'payload'}), '(url, params=payload)\n', (802, 823), False, 'import requests\n')] |
import pulumi
from pulumi_aws import ec2, get_availability_zones
stack_name = pulumi.get_stack()
project_name = pulumi.get_project()
config = pulumi.Config('vpc')
vpc = ec2.Vpc(resource_name=f"eks-{project_name}-{stack_name}",
cidr_block="10.100.0.0/16",
enable_dns_support=True,
... | [
"pulumi.export",
"pulumi_aws.ec2.Subnet",
"pulumi.log.warn",
"pulumi_aws.ec2.RouteTableRouteArgs",
"pulumi_aws.ec2.Vpc",
"pulumi_aws.ec2.SecurityGroupIngressArgs",
"pulumi_aws.ec2.InternetGateway",
"pulumi.Config",
"pulumi_aws.ec2.RouteTableAssociation",
"pulumi.get_project",
"pulumi.get_stack",... | [((80, 98), 'pulumi.get_stack', 'pulumi.get_stack', ([], {}), '()\n', (96, 98), False, 'import pulumi\n'), ((114, 134), 'pulumi.get_project', 'pulumi.get_project', ([], {}), '()\n', (132, 134), False, 'import pulumi\n'), ((145, 165), 'pulumi.Config', 'pulumi.Config', (['"""vpc"""'], {}), "('vpc')\n", (158, 165), False,... |
# coding=utf-8
from flask import Flask
from mailshake import ToConsoleMailer, SMTPMailer
from sqlalchemy_wrapper import SQLAlchemy
import settings
app = Flask(__name__)
app.config.from_object(settings)
db = SQLAlchemy(settings.SQLALCHEMY_URI, app)
if settings.DEBUG:
mailer = ToConsoleMailer()
else:
mailer ... | [
"mailshake.ToConsoleMailer",
"sqlalchemy_wrapper.SQLAlchemy",
"mailshake.SMTPMailer",
"flask.Flask"
] | [((156, 171), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (161, 171), False, 'from flask import Flask\n'), ((211, 251), 'sqlalchemy_wrapper.SQLAlchemy', 'SQLAlchemy', (['settings.SQLALCHEMY_URI', 'app'], {}), '(settings.SQLALCHEMY_URI, app)\n', (221, 251), False, 'from sqlalchemy_wrapper import SQLAlche... |
import numpy as np
import os
from scipy.interpolate import interp1d
import matplotlib.pyplot as plt
import starterlite
grf = starterlite.simulation.GaussianRandomField()
grf_input = np.load(os.getenv('STARTERLITE')+'/output/grf/grf_samples_x180y1z30_N1.npz', allow_pickle=True)
f_in = grf_input['grf']
f_in = f_in.sq... | [
"matplotlib.pyplot.loglog",
"os.getenv",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.figure",
"starterlite.simulation.GaussianRandomField",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.show"
] | [((127, 171), 'starterlite.simulation.GaussianRandomField', 'starterlite.simulation.GaussianRandomField', ([], {}), '()\n', (169, 171), False, 'import starterlite\n'), ((601, 627), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(6, 3)'}), '(figsize=(6, 3))\n', (611, 627), True, 'import matplotlib.pyplot as... |
import RPi.GPIO as GPIO
import sys
import os
from datetime import datetime
from time import sleep
import socket
try:
from mfrc522 import SimpleMFRC522
from getmac import get_mac_address
import hashlib
except:
os.system("pip3 install mfrc522")
os.system("pip3 install getmac")
os.system("pip3 ins... | [
"RPi.GPIO.cleanup",
"os.get_terminal_size",
"socket.socket",
"RPi.GPIO.setwarnings",
"time.sleep",
"mfrc522.SimpleMFRC522",
"os.path.isfile",
"datetime.datetime.now",
"os.system",
"getmac.get_mac_address",
"sys.stdout.write"
] | [((437, 460), 'RPi.GPIO.setwarnings', 'GPIO.setwarnings', (['(False)'], {}), '(False)\n', (453, 460), True, 'import RPi.GPIO as GPIO\n'), ((470, 485), 'mfrc522.SimpleMFRC522', 'SimpleMFRC522', ([], {}), '()\n', (483, 485), False, 'from mfrc522 import SimpleMFRC522\n'), ((486, 518), 'os.system', 'os.system', (['"""sette... |
import json
import os
import uuid
def main(event, context):
return_object = {
"success": True,
"response_id": str(uuid.uuid4()),
"querystring": event.get("queryStringParameters"),
"environment_variables": os.environ['GREETING']
}
return {
"statusCode": 200,
"... | [
"json.dumps",
"uuid.uuid4"
] | [((483, 508), 'json.dumps', 'json.dumps', (['return_object'], {}), '(return_object)\n', (493, 508), False, 'import json\n'), ((135, 147), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (145, 147), False, 'import uuid\n')] |
# -*- coding: utf-8 -*-
import plotly.graph_objects as go
import pandas as pd
import dash
import dash_core_components as dcc
import dash_html_components as html
def plot_ohlc(co_df: pd.DataFrame, title: str = ""):
colors = {
'background': '#11001A', # onyx
'text': '#7FDBFF'
}
hovertext... | [
"plotly.graph_objects.Layout",
"dash_html_components.H1",
"plotly.graph_objects.Candlestick",
"dash.Dash",
"dash_html_components.Div",
"dash_core_components.Graph"
] | [((2638, 2649), 'dash.Dash', 'dash.Dash', ([], {}), '()\n', (2647, 2649), False, 'import dash\n'), ((691, 927), 'plotly.graph_objects.Candlestick', 'go.Candlestick', ([], {'x': "co_df['Date']", 'open': "co_df['AdjOpen']", 'high': "co_df['AdjHigh']", 'low': "co_df['AdjLow']", 'close': "co_df['AdjClose']", 'text': 'hover... |
import unittest
import sme
class TestMembrane(unittest.TestCase):
def test_membrane(self):
m = sme.open_example_model()
self.assertEqual(len(m.membranes), 2)
self.assertRaises(sme.InvalidArgument, lambda: m.membranes["X"])
mem = m.membranes["Outside <-> Cell"]
self.assertEq... | [
"sme.open_sbml_file",
"sme.open_example_model"
] | [((109, 133), 'sme.open_example_model', 'sme.open_example_model', ([], {}), '()\n', (131, 133), False, 'import sme\n'), ((1050, 1079), 'sme.open_sbml_file', 'sme.open_sbml_file', (['"""tmp.xml"""'], {}), "('tmp.xml')\n", (1068, 1079), False, 'import sme\n')] |
from flask import Flask, request, Response
import json
import pymongo
from flask_cors import CORS
from bson.json_util import dumps, loads
import os
from azure.storage.blob import BlockBlobService, PublicAccess
from celery import Celery
import subprocess
import uuid
app = Flask(__name__)
CORS(app)
db_cli... | [
"flask_cors.CORS",
"flask.Flask",
"celery.Celery",
"uuid.uuid4",
"flask.request.get_json",
"flask.Response",
"pymongo.MongoClient",
"flask.request.files.items",
"os.system",
"azure.storage.blob.BlockBlobService",
"bson.json_util.dumps"
] | [((284, 299), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (289, 299), False, 'from flask import Flask, request, Response\n'), ((301, 310), 'flask_cors.CORS', 'CORS', (['app'], {}), '(app)\n', (305, 310), False, 'from flask_cors import CORS\n'), ((415, 511), 'azure.storage.blob.BlockBlobService', 'BlockB... |
import enum
import time
from collections import namedtuple
from dataclasses import dataclass, field
from typing import List, Dict, Any, Union, Tuple, Sequence, Callable, Optional
import gym
import numpy as np
from malib.utils.notations import deprecated
""" Rename and definition of basic data types which are corresp... | [
"collections.namedtuple",
"time.time",
"dataclasses.field"
] | [((1090, 1163), 'collections.namedtuple', 'namedtuple', (['"""StandardTransition"""', '"""obs, new_obs, actions, rewards, dones"""'], {}), "('StandardTransition', 'obs, new_obs, actions, rewards, dones')\n", (1100, 1163), False, 'from collections import namedtuple\n'), ((4197, 4208), 'time.time', 'time.time', ([], {}),... |
# pylint: disable=protected-access
# This code is part of Ansible, but is an independent component.
# This particular file snippet, and this file snippet only, is licensed under the Apache License 2.0.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# still belong to the author of the ... | [
"ansible_collections.ctera.ctera.plugins.modules.ctera_portal_syslog.CteraPortalSyslog",
"unittest.mock.MagicMock",
"munch.Munch",
"tests.ut.mocks.ctera_portal_base_mock.mock_bases"
] | [((1640, 1718), 'tests.ut.mocks.ctera_portal_base_mock.mock_bases', 'ctera_portal_base_mock.mock_bases', (['self', 'ctera_portal_syslog.CteraPortalSyslog'], {}), '(self, ctera_portal_syslog.CteraPortalSyslog)\n', (1673, 1718), True, 'import tests.ut.mocks.ctera_portal_base_mock as ctera_portal_base_mock\n'), ((1783, 18... |
import math
from typing import Union, Dict
import numpy as np
import torch
import torchvision.transforms as transforms
from torchvision.transforms import InterpolationMode
import utility as utils
import utility.color as color
class Resolution:
def __init__(self, width, height):
self.width = width
... | [
"torchvision.transforms.ToPILImage",
"math.sqrt",
"torch.sqrt",
"torch.cuda.is_available",
"torch.sum",
"torchvision.transforms.Resize",
"torchvision.transforms.ToTensor",
"torch.FloatTensor"
] | [((3479, 3515), 'torch.sqrt', 'torch.sqrt', (["(total['R'] / total_pixel)"], {}), "(total['R'] / total_pixel)\n", (3489, 3515), False, 'import torch\n'), ((3542, 3578), 'torch.sqrt', 'torch.sqrt', (["(total['G'] / total_pixel)"], {}), "(total['G'] / total_pixel)\n", (3552, 3578), False, 'import torch\n'), ((3606, 3642)... |
from pandas import read_sql_query
from sqlite3 import connect
from pickle import load, dump
from time import time
from gensim.utils import simple_preprocess
from gensim.models import Phrases
from gensim.models.phrases import Phraser
from gensim.parsing.preprocessing import STOPWORDS
from gensim.corpora import Dictiona... | [
"pandas.read_sql_query",
"gensim.models.AuthorTopicModel",
"gensim.models.AuthorTopicModel.load",
"gensim.corpora.Dictionary.load",
"pickle.dump",
"sqlite3.connect",
"gensim.corpora.Dictionary",
"nltk.SnowballStemmer",
"pickle.load",
"nltk.WordNetLemmatizer",
"gensim.utils.simple_preprocess",
... | [((451, 469), 'numpy.random.seed', 'np.random.seed', (['(59)'], {}), '(59)\n', (465, 469), True, 'import numpy as np\n'), ((873, 879), 'time.time', 'time', ([], {}), '()\n', (877, 879), False, 'from time import time\n'), ((2337, 2343), 'time.time', 'time', ([], {}), '()\n', (2341, 2343), False, 'from time import time\n... |
from sklearn.neighbors import KNeighborsClassifier
from skmultiflow.lazy import KNNClassifier
from skmultiflow.meta import LearnPPNSEClassifier
from cacp import all_datasets, run_experiment, ClassificationDataset
from cacp_examples.classifiers import CLASSIFIERS
from cacp_examples.example_custom_classifiers.xgboost im... | [
"skmultiflow.lazy.KNNClassifier",
"cacp.all_datasets",
"sklearn.neighbors.KNeighborsClassifier",
"skmultiflow.meta.LearnPPNSEClassifier",
"cacp.run_experiment",
"cacp_examples.example_custom_classifiers.xgboost.XGBoost",
"cacp.ClassificationDataset"
] | [((745, 759), 'cacp.all_datasets', 'all_datasets', ([], {}), '()\n', (757, 759), False, 'from cacp import all_datasets, run_experiment, ClassificationDataset\n'), ((1641, 1746), 'cacp.run_experiment', 'run_experiment', (['experimental_datasets', 'experimental_classifiers'], {'results_directory': '"""./example_result"""... |
import os,sys
from os import walk
path='C:\\Users\\PUJITHA\\AppData\\Local\\Programs\\Python\\Python36\\Timestamps'
dirs=os.listdir(path)
print("list of all the contetnts in the TimeStamps Library ")
print(dirs)
# Adding the directory contents in list data structure
f = []
for (filenames) in walk(path):
... | [
"os.listdir",
"os.walk"
] | [((126, 142), 'os.listdir', 'os.listdir', (['path'], {}), '(path)\n', (136, 142), False, 'import os, sys\n'), ((305, 315), 'os.walk', 'walk', (['path'], {}), '(path)\n', (309, 315), False, 'from os import walk\n')] |
import csv
import datetime
import re
import json
import unicodedata
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators i... | [
"form_builder.forms.FieldFormSet",
"form_builder.models.Field.objects.filter",
"django.http.HttpResponse",
"form_builder.forms.FieldForm",
"django.shortcuts.get_object_or_404",
"django.template.RequestContext",
"csv.writer",
"django.core.urlresolvers.reverse",
"json.dumps",
"form_builder.forms.For... | [((1078, 1115), 'django.contrib.messages.add_message', 'messages.add_message', (['*args'], {}), '(*args, **kwargs)\n', (1098, 1115), False, 'from django.contrib import messages\n'), ((2269, 2295), 'form_builder.forms.FormForm', 'FormForm', (['(req.POST or None)'], {}), '(req.POST or None)\n', (2277, 2295), False, 'from... |
import asyncio
from aiohttp import ClientSession
from ssl_context_builder.builder.builder import SslContextBuilder
from ssl_context_builder.http_impl.requests_wrapper.secure_session import RequestsSecureSession
def create_strong_crypto_ctx():
builder = SslContextBuilder()
ssl_ctx = builder.use_tls_1_2_and_a... | [
"aiohttp.ClientSession",
"ssl_context_builder.http_impl.requests_wrapper.secure_session.RequestsSecureSession",
"ssl_context_builder.builder.builder.SslContextBuilder"
] | [((261, 280), 'ssl_context_builder.builder.builder.SslContextBuilder', 'SslContextBuilder', ([], {}), '()\n', (278, 280), False, 'from ssl_context_builder.builder.builder import SslContextBuilder\n'), ((552, 571), 'ssl_context_builder.builder.builder.SslContextBuilder', 'SslContextBuilder', ([], {}), '()\n', (569, 571)... |
import sys
import random
import pygame
# Define Window Size
SCREEN_WIDTH, SCREEN_HEIGHT = 800, 600
# Define Frames Per Second
FRAMES_PER_SEC = 25
# Function: Draw a text to the screen
def blit_text(screen_object, font, msg_text, color_tuple, center_tuple, antialiased=True):
# Define a message in Main Menu with Co... | [
"sys.exit",
"pygame.init",
"pygame.quit",
"pygame.event.get",
"random.randrange",
"pygame.display.set_mode",
"pygame.key.get_pressed",
"pygame.time.Clock",
"pygame.display.update",
"pygame.font.SysFont"
] | [((2517, 2530), 'pygame.init', 'pygame.init', ([], {}), '()\n', (2528, 2530), False, 'import pygame\n'), ((2583, 2619), 'pygame.font.SysFont', 'pygame.font.SysFont', (['"""comicsans"""', '(40)'], {}), "('comicsans', 40)\n", (2602, 2619), False, 'import pygame\n'), ((2686, 2740), 'pygame.display.set_mode', 'pygame.displ... |
# -*- coding: utf8 -*-
import os
import sys
import logging
from logging.handlers import RotatingFileHandler
__all__ = (
'get_logger',
)
LOG_PATH = "/var/log/imap2gotify.log"
__LOG__ = None
def get_logger(path=LOG_PATH):
global __LOG__
if __LOG__ is not None:
return __LOG__... | [
"logging.getLogger",
"logging.Formatter",
"logging.StreamHandler",
"logging.handlers.RotatingFileHandler"
] | [((394, 426), 'logging.getLogger', 'logging.getLogger', (['"""imap2gotify"""'], {}), "('imap2gotify')\n", (411, 426), False, 'import logging\n'), ((475, 550), 'logging.Formatter', 'logging.Formatter', (['"""%(asctime)s | %(name)s | %(levelname)10s | %(message)s"""'], {}), "('%(asctime)s | %(name)s | %(levelname)10s | %... |
# -*- encoding: utf-8 -*-
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from django.shortcuts import redirect
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.core.paginator import Paginator... | [
"django.shortcuts.render",
"django.http.HttpResponse",
"django.contrib.messages.error",
"django.core.urlresolvers.reverse",
"django.contrib.messages.success",
"django.core.paginator.Paginator"
] | [((513, 533), 'django.core.paginator.Paginator', 'Paginator', (['photos', '(1)'], {}), '(photos, 1)\n', (522, 533), False, 'from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\n'), ((736, 843), 'django.shortcuts.render', 'render', (['request', '"""index.html"""', "{'title': u'ostatnie zdjęcia', 'ph... |
# -*- coding: utf-8 -*-
"""
@date: 2020/7/14 下午8:34
@file: anno_processor.py
@author: zj
@description:
"""
import os
import glob
from parseanno.anno import build_anno
from parseanno.utils.logger import setup_logger
class AnnoProcessor(object):
"""
对标注数据进行处理,创建指定格式的训练数据
"""
def __init__(self, cfg)... | [
"parseanno.anno.build_anno",
"parseanno.utils.logger.setup_logger"
] | [((344, 376), 'parseanno.anno.build_anno', 'build_anno', (['cfg.ANNO.PARSER', 'cfg'], {}), '(cfg.ANNO.PARSER, cfg)\n', (354, 376), False, 'from parseanno.anno import build_anno\n'), ((400, 433), 'parseanno.anno.build_anno', 'build_anno', (['cfg.ANNO.CREATOR', 'cfg'], {}), '(cfg.ANNO.CREATOR, cfg)\n', (410, 433), False,... |
import arrow
from datetime import timedelta
def identify_missing_sources(oh_member):
missing_sources = {"oura": True, "fitbit": True}
# Check data already in Open Humans.
for i in oh_member.list_files():
if i["source"] == "direct-sharing-184" and i["basename"] == "oura-data.json":
mis... | [
"datetime.timedelta",
"arrow.now"
] | [((995, 1006), 'arrow.now', 'arrow.now', ([], {}), '()\n', (1004, 1006), False, 'import arrow\n'), ((1009, 1027), 'datetime.timedelta', 'timedelta', ([], {'hours': '(1)'}), '(hours=1)\n', (1018, 1027), False, 'from datetime import timedelta\n')] |
import asyncio
from bleak import BleakScanner
def detection_callback(*args):
print(args)
async def run():
scanner = BleakScanner()
scanner.register_detection_callback(detection_callback)
await scanner.start()
await asyncio.sleep(2.0)
await scanner.stop()
devices = await scanner.get_discove... | [
"bleak.BleakScanner",
"asyncio.get_event_loop",
"asyncio.sleep"
] | [((382, 406), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (404, 406), False, 'import asyncio\n'), ((126, 140), 'bleak.BleakScanner', 'BleakScanner', ([], {}), '()\n', (138, 140), False, 'from bleak import BleakScanner\n'), ((237, 255), 'asyncio.sleep', 'asyncio.sleep', (['(2.0)'], {}), '(2.0)\... |
# Created byMartin.cz
# Copyright (c) <NAME>. All rights reserved.
from pero.properties import *
from pero import Label, LabelBox
from . graphics import InGraphics
class Labels(InGraphics):
"""
Labels container provides a simple tool to draw all given labels at once in
the order defined by their 'z_in... | [
"pero.LabelBox"
] | [((1973, 1983), 'pero.LabelBox', 'LabelBox', ([], {}), '()\n', (1981, 1983), False, 'from pero import Label, LabelBox\n')] |
import pyjion
import timeit
from statistics import fmean
def test_floats(n=10000):
for y in range(n):
x = 0.1
z = y * y + x - y
x *= z
def test_ints(n=10000):
for y in range(n):
x = 2
z = y * y + x - y
x *= z
if __name__ == "__main__":
tests = (test_floa... | [
"pyjion.set_optimization_level",
"timeit.repeat",
"statistics.fmean",
"pyjion.enable",
"pyjion.disable"
] | [((383, 425), 'timeit.repeat', 'timeit.repeat', (['test'], {'repeat': '(5)', 'number': '(1000)'}), '(test, repeat=5, number=1000)\n', (396, 425), False, 'import timeit\n'), ((585, 600), 'pyjion.enable', 'pyjion.enable', ([], {}), '()\n', (598, 600), False, 'import pyjion\n'), ((609, 641), 'pyjion.set_optimization_level... |
# import the required packages
import warnings
import sys
from scipy.optimize import OptimizeWarning
from PyQt5 import QtCore, QtWidgets
from ._tools import Fitter, value_to_string
from ._widgets import PlotWidget, ModelWidget, ReportWidget
from ._settings import settings
from ._version import __version__ as CFGversio... | [
"PyQt5.QtWidgets.QWidget",
"PyQt5.QtWidgets.QApplication.instance",
"PyQt5.QtWidgets.QMessageBox",
"warnings.catch_warnings",
"PyQt5.QtWidgets.QHBoxLayout",
"PyQt5.QtWidgets.QApplication.quit",
"PyQt5.QtWidgets.QSplitter",
"warnings.simplefilter",
"sys.exc_info",
"PyQt5.QtWidgets.QGroupBox",
"Py... | [((915, 944), 'PyQt5.QtWidgets.QApplication.quit', 'QtWidgets.QApplication.quit', ([], {}), '()\n', (942, 944), False, 'from PyQt5 import QtCore, QtWidgets\n'), ((1133, 1152), 'PyQt5.QtWidgets.QWidget', 'QtWidgets.QWidget', ([], {}), '()\n', (1150, 1152), False, 'from PyQt5 import QtCore, QtWidgets\n'), ((1506, 1552), ... |
import http.server
import socketserver
import socket
#set the process name to "chaos_server" so we can easily kill it with "pkill chaos_server"
def set_proc_name(newname):
from ctypes import cdll, byref, create_string_buffer
libc = cdll.LoadLibrary('libc.so.6')
buff = create_string_buffer(len(newname)+1)
... | [
"ctypes.byref",
"ctypes.cdll.LoadLibrary"
] | [((241, 270), 'ctypes.cdll.LoadLibrary', 'cdll.LoadLibrary', (['"""libc.so.6"""'], {}), "('libc.so.6')\n", (257, 270), False, 'from ctypes import cdll, byref, create_string_buffer\n'), ((379, 390), 'ctypes.byref', 'byref', (['buff'], {}), '(buff)\n', (384, 390), False, 'from ctypes import cdll, byref, create_string_buf... |
import board
import adafruit_ahtx0
from datetime import datetime
html_dir = "/var/www/html/temp"
data_fname = "temperature.csv"
html_fname = "index.html"
sensor = adafruit_ahtx0.AHTx0(board.I2C())
temp = sensor.temperature
hum = sensor.relative_humidity
now = datetime.now()
# open data file
history = []
with open... | [
"datetime.datetime.strptime",
"datetime.datetime.now",
"board.I2C"
] | [((264, 278), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (276, 278), False, 'from datetime import datetime\n'), ((186, 197), 'board.I2C', 'board.I2C', ([], {}), '()\n', (195, 197), False, 'import board\n'), ((417, 463), 'datetime.datetime.strptime', 'datetime.strptime', (['fields[0]', '"""%d/%m/%y %H:%M... |
import os
import pickle
import json
from typing import List
def subdirs(folder: str, join: bool = True, prefix: str = None, suffix: str = None, sort: bool = True) -> List[str]:
if join:
l = os.path.join
else:
l = lambda x, y: y
res = [l(folder, i) for i in os.listdir(folder) if os.path.isd... | [
"os.listdir",
"pickle.dump",
"os.makedirs",
"pickle.load",
"os.path.join",
"json.load",
"json.dump"
] | [((1154, 1191), 'os.makedirs', 'os.makedirs', (['directory'], {'exist_ok': '(True)'}), '(directory, exist_ok=True)\n', (1165, 1191), False, 'import os\n'), ((1742, 1771), 'os.path.join', 'os.path.join', (['path', 'os.pardir'], {}), '(path, os.pardir)\n', (1754, 1771), False, 'import os\n'), ((1284, 1298), 'pickle.load'... |
import torch
from torch.autograd import Variable
batch_size = 100
row_lenth = 10
col_length = 10
if __name__ == '__main__':
a = Variable(torch.randn((batch_size, row_lenth, col_length)))
b = Variable(torch.randn((batch_size, row_lenth, col_length)))
c = Variable(torch.randn((batch_size, row_lenth, col_length)))
s... | [
"torch.zeros",
"torch.randn"
] | [((140, 188), 'torch.randn', 'torch.randn', (['(batch_size, row_lenth, col_length)'], {}), '((batch_size, row_lenth, col_length))\n', (151, 188), False, 'import torch\n'), ((204, 252), 'torch.randn', 'torch.randn', (['(batch_size, row_lenth, col_length)'], {}), '((batch_size, row_lenth, col_length))\n', (215, 252), Fal... |
from django.test import TestCase
from django.contrib.auth import get_user_model
from unittest.mock import patch
from core import models
class ModelTests(TestCase):
"""Test the core models"""
def test_create_user_with_email(self):
"""Create User with email"""
email = "<EMAIL>"
passwor... | [
"django.contrib.auth.get_user_model"
] | [((353, 369), 'django.contrib.auth.get_user_model', 'get_user_model', ([], {}), '()\n', (367, 369), False, 'from django.contrib.auth import get_user_model\n'), ((669, 685), 'django.contrib.auth.get_user_model', 'get_user_model', ([], {}), '()\n', (683, 685), False, 'from django.contrib.auth import get_user_model\n'), (... |