code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import Deck
class Blackjack(object):
def __init__(self):
self.start()
def start(self):
deck = Deck.Deck(1)
deck.display_decks()
Blackjack().start() | [
"Deck.Deck"
] | [((122, 134), 'Deck.Deck', 'Deck.Deck', (['(1)'], {}), '(1)\n', (131, 134), False, 'import Deck\n')] |
import sqlalchemy.orm
import xml.etree.ElementTree
from ietf.sql.rfc import (Abstract, Author, FileFormat, IsAlso, Keyword,
ObsoletedBy, Obsoletes, Rfc, SeeAlso, Stream,
UpdatedBy, Updates,)
import ietf.xml.parse as parse
def _add_keyword(session: sqlalchemy.orm.ses... | [
"ietf.xml.parse.find_obsoleted_by",
"ietf.xml.parse.find_see_also",
"ietf.xml.parse.find_obsoletes",
"ietf.xml.parse.find_current_status",
"ietf.sql.rfc.Stream",
"ietf.sql.rfc.FileFormat",
"ietf.sql.rfc.Rfc",
"ietf.sql.rfc.IsAlso",
"ietf.sql.rfc.Author",
"ietf.xml.parse.find_format",
"ietf.xml.p... | [((843, 875), 'ietf.xml.parse.findall', 'parse.findall', (['root', '"""rfc-entry"""'], {}), "(root, 'rfc-entry')\n", (856, 875), True, 'import ietf.xml.parse as parse\n'), ((590, 603), 'ietf.sql.rfc.Keyword', 'Keyword', (['word'], {}), '(word)\n', (597, 603), False, 'from ietf.sql.rfc import Abstract, Author, FileForma... |
import re
import pickle
with open('words2num_dict.pickle', 'rb') as handle:
words2num = pickle.load(handle)
num2words = {v: k for k, v in words2num.items()}
freq_raw = []
with open('output.txt') as f:
for i in range(31):
f.readline()
for line in f:
line = re.sub('\[\w+\]', '',... | [
"pickle.dump",
"pickle.load",
"re.sub"
] | [((97, 116), 'pickle.load', 'pickle.load', (['handle'], {}), '(handle)\n', (108, 116), False, 'import pickle\n'), ((1190, 1222), 'pickle.dump', 'pickle.dump', (['words_tuple', 'handle'], {}), '(words_tuple, handle)\n', (1201, 1222), False, 'import pickle\n'), ((299, 329), 're.sub', 're.sub', (['"""\\\\[\\\\w+\\\\]"""',... |
import os
from pathlib import Path
import numpy as np
import pandas as pd
import spacy
from spacy.compat import pickle
import lz4.frame
from tqdm import tqdm
from tensorflow.keras.callbacks import ModelCheckpoint, TensorBoard, EarlyStopping
from ehr_classification.tokenizer import get_features, get_custom_tokenizer
fro... | [
"ehr_classification.classifier_model.compile_lstm",
"tensorflow.keras.callbacks.TensorBoard",
"plac.call",
"tensorflow.keras.callbacks.ModelCheckpoint",
"ehr_classification.tokenizer.get_custom_tokenizer",
"pathlib.Path",
"tensorflow.keras.callbacks.EarlyStopping",
"pandas.read_parquet",
"numpy.arra... | [((1076, 1110), 'ehr_classification.tokenizer.get_custom_tokenizer', 'get_custom_tokenizer', (['word_vectors'], {}), '(word_vectors)\n', (1096, 1110), False, 'from ehr_classification.tokenizer import get_features, get_custom_tokenizer\n'), ((1163, 1288), 'ehr_classification.classifier_model.compile_lstm', 'compile_lstm... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-04-10 23:25
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('stardate', '0009_auto_20170301_0155'),
]
operations = [
migrations.RemoveField(
... | [
"django.db.migrations.RemoveField"
] | [((293, 354), 'django.db.migrations.RemoveField', 'migrations.RemoveField', ([], {'model_name': '"""blog"""', 'name': '"""social_auth"""'}), "(model_name='blog', name='social_auth')\n", (315, 354), False, 'from django.db import migrations\n')] |
# Generated by Django 3.1 on 2020-08-17 21:14
from django.db import migrations, models
import profile.models
class Migration(migrations.Migration):
dependencies = [
('profile', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='profile',
name='pho... | [
"django.db.models.ImageField"
] | [((343, 421), 'django.db.models.ImageField', 'models.ImageField', ([], {'blank': '(True)', 'null': '(True)', 'upload_to': 'profile.models.upload_path'}), '(blank=True, null=True, upload_to=profile.models.upload_path)\n', (360, 421), False, 'from django.db import migrations, models\n')] |
""" Tests File"""
import requests
from website import API_KEY
def test_api_key_is_not_null():
""" Get API_KEY value and compare """
assert API_KEY != None
def test_request_api_key():
""" Test a request with api_key value """
assert requests.get(f'https://api.themoviedb.org/3/movie/76341?api_key={API_K... | [
"requests.get"
] | [((250, 325), 'requests.get', 'requests.get', (['f"""https://api.themoviedb.org/3/movie/76341?api_key={API_KEY}"""'], {}), "(f'https://api.themoviedb.org/3/movie/76341?api_key={API_KEY}')\n", (262, 325), False, 'import requests\n')] |
# Generated by Django 3.1.3 on 2020-11-26 02:30
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('users', '0006_auto_20201126_0321'),
]
operations = [
migrations.AddField(
... | [
"datetime.datetime"
] | [((413, 473), 'datetime.datetime', 'datetime.datetime', (['(2020)', '(11)', '(26)', '(2)', '(30)', '(10)', '(7725)'], {'tzinfo': 'utc'}), '(2020, 11, 26, 2, 30, 10, 7725, tzinfo=utc)\n', (430, 473), False, 'import datetime\n')] |
from django import forms
from projects.models import *
from django.views.decorators.csrf import csrf_exempt
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.shortcuts import render
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestC... | [
"json.load",
"django.forms.TextInput",
"django.core.paginator.Paginator",
"urllib2.urlopen",
"django.forms.Textarea",
"django.template.RequestContext"
] | [((798, 824), 'django.core.paginator.Paginator', 'Paginator', (['prject_list', '(10)'], {}), '(prject_list, 10)\n', (807, 824), False, 'from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\n'), ((1473, 1532), 'urllib2.urlopen', 'urllib2.urlopen', (['"""https://api.github.com/users/moztn/repos"""'], ... |
import os
import sys
import hashlib
import requests
def md5_str(szText):
return str(hashlib.md5(szText).hexdigest())
def MD5(szText):
m = hashlib.md5()
m.update(szText)
return m.digest()
def md5_file(filePath):
with open(filePath, 'rb') as fh:
m = hashlib.md5()
whi... | [
"hashlib.md5"
] | [((157, 170), 'hashlib.md5', 'hashlib.md5', ([], {}), '()\n', (168, 170), False, 'import hashlib\n'), ((294, 307), 'hashlib.md5', 'hashlib.md5', ([], {}), '()\n', (305, 307), False, 'import hashlib\n'), ((95, 114), 'hashlib.md5', 'hashlib.md5', (['szText'], {}), '(szText)\n', (106, 114), False, 'import hashlib\n')] |
import math
import warnings
from collections import OrderedDict
from enum import Enum
import efel
import matplotlib.pyplot as plt
import numpy as np
from lib.Model import Model
from lib.NrnModel import NrnModel
class Level(Enum):
HIGH = 0.5
MID = 5.0
LOW = 10.0
VLOW = 50.0
EFEL_NAME_MAP = {
... | [
"matplotlib.pyplot.show",
"warnings.filterwarnings",
"efel.setDoubleSetting",
"efel.setIntSetting",
"efel.getFeatureValues",
"numpy.mean",
"math.isclose",
"numpy.random.rand",
"matplotlib.pyplot.subplots"
] | [((5889, 5903), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (5901, 5903), True, 'import matplotlib.pyplot as plt\n'), ((6657, 6667), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6665, 6667), True, 'import matplotlib.pyplot as plt\n'), ((2056, 2121), 'efel.setDoubleSetting', 'efel.setDoub... |
# Implementatin of our blockchain
# <NAME>
# Object Oriented blockchain
# The container + chain where our blocks live
# Bring in some needed libraries
from datetime import datetime
import hashlib
import json
from urllib.parse import urlparse
import requests
from timeit import default_timer as timer
class Blockchain... | [
"timeit.default_timer",
"json.dumps",
"hashlib.sha256",
"requests.get",
"datetime.datetime.now",
"urllib.parse.urlparse"
] | [((1980, 1987), 'timeit.default_timer', 'timer', ([], {}), '()\n', (1985, 1987), True, 'from timeit import default_timer as timer\n'), ((2487, 2494), 'timeit.default_timer', 'timer', ([], {}), '()\n', (2492, 2494), True, 'from timeit import default_timer as timer\n'), ((4322, 4345), 'urllib.parse.urlparse', 'urlparse',... |
"""
Get singer songs by qq music.
Refer: https://github.com/yangjianxin1/QQMusicSpider
``` bash
cd crawler/qq_music
python crawler.py initdb
python crawler.py crawler -s {singer_mid}
```
"""
import sqlite3
import sys
import time
import click
import requests
from requests.adapters import ... | [
"sys.path.append",
"requests.adapters.HTTPAdapter",
"requests.Session",
"click.option",
"click.echo",
"time.time",
"sqlite3.connect",
"click.group"
] | [((333, 358), 'sys.path.append', 'sys.path.append', (['"""../../"""'], {}), "('../../')\n", (348, 358), False, 'import sys\n'), ((384, 402), 'requests.Session', 'requests.Session', ([], {}), '()\n', (400, 402), False, 'import requests\n'), ((414, 440), 'requests.adapters.HTTPAdapter', 'HTTPAdapter', ([], {'max_retries'... |
from bs4 import BeautifulSoup as Soup
import re
string = '<p>Please click <a href="http://www.dr-chuck.com">here</a></p>'
match = re.findall('https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+', string)
html = Soup(string, 'html.parser')
bsm= [a['href'] for a in html.find_all('a')]
match2 = re.findall('"(http.*.*)"',string... | [
"bs4.BeautifulSoup",
"re.findall"
] | [((131, 194), 're.findall', 're.findall', (['"""https?://(?:[-\\\\w.]|(?:%[\\\\da-fA-F]{2}))+"""', 'string'], {}), "('https?://(?:[-\\\\w.]|(?:%[\\\\da-fA-F]{2}))+', string)\n", (141, 194), False, 'import re\n'), ((201, 228), 'bs4.BeautifulSoup', 'Soup', (['string', '"""html.parser"""'], {}), "(string, 'html.parser')\n... |
import subprocess
import sys
def start():
# 0x78 == 01111000 == x, eXit
return subprocess.call((sys.executable, "main.py")) == 0x78
if __name__ == "__main__":
print("Executing Bot initialisation.")
while True:
# Start the bot
print("Starting Bot;")
code = start()
if n... | [
"subprocess.call"
] | [((89, 133), 'subprocess.call', 'subprocess.call', (["(sys.executable, 'main.py')"], {}), "((sys.executable, 'main.py'))\n", (104, 133), False, 'import subprocess\n')] |
from tkinter import *
from tkinter import ttk
from View.Datepicker import Datepicker
from Controller.Controller import Controller
from tkinter.filedialog import askopenfilename
"""
Autor: <NAME> (418002863)
Email: <EMAIL>
"""
class GUI(ttk.Frame):
fields_current_query = dict()
def __init__(self, master):
... | [
"tkinter.ttk.Label",
"tkinter.ttk.Entry",
"tkinter.ttk.Labelframe",
"tkinter.ttk.Scrollbar",
"View.Datepicker.Datepicker",
"tkinter.filedialog.askopenfilename",
"tkinter.ttk.Frame",
"Controller.Controller.Controller",
"tkinter.ttk.Treeview",
"tkinter.ttk.Button",
"tkinter.ttk.Checkbutton",
"tk... | [((341, 353), 'Controller.Controller.Controller', 'Controller', ([], {}), '()\n', (351, 353), False, 'from Controller.Controller import Controller\n'), ((656, 686), 'tkinter.ttk.Notebook', 'ttk.Notebook', (['self'], {'padding': '(10)'}), '(self, padding=10)\n', (668, 686), False, 'from tkinter import ttk\n'), ((807, 83... |
#!/usr/bin/python3
"""
Given four lists A, B, C, D of integer values, compute how many tuples (i, j,
k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero.
To make problem a bit easier, all A, B, C, D have same length of N where
0 ≤ N ≤ 500. All integers are in the range of -2^28 to 2^28 - 1 and the result
is gu... | [
"collections.defaultdict"
] | [((1100, 1116), 'collections.defaultdict', 'defaultdict', (['int'], {}), '(int)\n', (1111, 1116), False, 'from collections import defaultdict\n'), ((1130, 1146), 'collections.defaultdict', 'defaultdict', (['int'], {}), '(int)\n', (1141, 1146), False, 'from collections import defaultdict\n')] |
from django.shortcuts import render
from moviesapp.models import Movies
from moviesapp.forms import MoviesForm
def index(request):
return render(request, 'moviesapp/index.html')
def moviesList(request):
moviesList=Movies.objects.all()
movies_dict={'movies':moviesList}
return render(request, 'moviesapp... | [
"django.shortcuts.render",
"moviesapp.forms.MoviesForm",
"moviesapp.models.Movies.objects.all"
] | [((143, 182), 'django.shortcuts.render', 'render', (['request', '"""moviesapp/index.html"""'], {}), "(request, 'moviesapp/index.html')\n", (149, 182), False, 'from django.shortcuts import render\n'), ((224, 244), 'moviesapp.models.Movies.objects.all', 'Movies.objects.all', ([], {}), '()\n', (242, 244), False, 'from mov... |
import streamlit as st
from help import health_analysis
from load_chatmodel import load
from data import main_data
from get_medical import get_links
import torch
from tensorflow.keras.preprocessing.sequence import pad_sequences
encoder_net, decoder_net = load()
data = main_data()
max, vocab_enc, vocab_dec =... | [
"streamlit.markdown",
"data.main_data",
"streamlit.text_input",
"get_medical.get_links",
"torch.LongTensor",
"help.health_analysis",
"streamlit.write",
"streamlit.title",
"tensorflow.keras.preprocessing.sequence.pad_sequences",
"load_chatmodel.load",
"torch.no_grad"
] | [((265, 271), 'load_chatmodel.load', 'load', ([], {}), '()\n', (269, 271), False, 'from load_chatmodel import load\n'), ((280, 291), 'data.main_data', 'main_data', ([], {}), '()\n', (289, 291), False, 'from data import main_data\n'), ((387, 404), 'streamlit.title', 'st.title', (['"""Animo"""'], {}), "('Animo')\n", (395... |
import uuid
import unittest
import influxgraph
from influxdb import InfluxDBClient
class InfluxGraphLogFileTestCase(unittest.TestCase):
def setUp(self):
self.db_name = 'fakey'
self.client = InfluxDBClient(database=self.db_name)
self.client.create_database(self.db_name)
_logger = in... | [
"unittest.main",
"uuid.uuid4",
"influxdb.InfluxDBClient",
"influxgraph.InfluxDBFinder"
] | [((1704, 1719), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1717, 1719), False, 'import unittest\n'), ((212, 249), 'influxdb.InfluxDBClient', 'InfluxDBClient', ([], {'database': 'self.db_name'}), '(database=self.db_name)\n', (226, 249), False, 'from influxdb import InfluxDBClient\n'), ((987, 1021), 'influxgrap... |
import discord
from discord.ext import commands
import datetime as dt
import utilities.db as DB
import utilities.facility as Facility
from bot import MichaelBot
class CustomCommand(commands.Cog, name = "Custom Commands", command_attrs = {"cooldown_after_parsing": True}):
"""Commands that support adding custom c... | [
"discord.ext.commands.Cog.listener",
"utilities.db.CustomCommand.get_commands",
"discord.ext.commands.cooldown",
"utilities.db.CustomCommand.get_command",
"discord.ext.commands.bot_has_permissions",
"datetime.datetime.utcnow",
"discord.ext.commands.has_guild_permissions",
"discord.ext.commands.group",... | [((623, 658), 'discord.ext.commands.Cog.listener', 'commands.Cog.listener', (['"""on_message"""'], {}), "('on_message')\n", (644, 658), False, 'from discord.ext import commands\n'), ((3312, 3386), 'discord.ext.commands.group', 'commands.group', ([], {'aliases': "['ccmd', 'customcmd']", 'invoke_without_command': '(True)... |
import datetime
import os
import sqlalchemy.orm as sa_orm
from app import factories
from app.etl import transformers
from app.util.json import load_json_file
def test_make_response_from_nested_schema(session: sa_orm.Session, data_dir):
schema = load_json_file(os.path.join(data_dir, 'nested_schema.json'))
fo... | [
"app.factories.FormFactory",
"app.factories.UserFactory",
"datetime.datetime.strptime",
"app.factories.make_response",
"app.etl.transformers.get_node_path_map_cache",
"os.path.join"
] | [((325, 361), 'app.factories.FormFactory', 'factories.FormFactory', ([], {'schema': 'schema'}), '(schema=schema)\n', (346, 361), False, 'from app import factories\n'), ((374, 397), 'app.factories.UserFactory', 'factories.UserFactory', ([], {}), '()\n', (395, 397), False, 'from app import factories\n'), ((478, 523), 'ap... |
from glob import glob
import os, random
class userAgents(object):
def __init__(self):
files_ = glob(f'{os.path.dirname(os.path.realpath(__file__))}/assets/*.txt')
self.uas,self.Chrome,self.Edge,self.Firefox,self.Opera,self.Safari = [],[],[],[],[],[]
for file_ in files_:
with open(file_,'r') as f:
record... | [
"os.path.realpath",
"random.choice"
] | [((754, 780), 'random.choice', 'random.choice', (['self.Chrome'], {}), '(self.Chrome)\n', (767, 780), False, 'import os, random\n'), ((816, 840), 'random.choice', 'random.choice', (['self.Edge'], {}), '(self.Edge)\n', (829, 840), False, 'import os, random\n'), ((879, 906), 'random.choice', 'random.choice', (['self.Fire... |
import uuid
from django.contrib.auth import get_user_model
from django.db import models
from django.utils.translation import gettext_lazy as _
from investments.models import TimestampedModel
UserModel = get_user_model()
class Tag(TimestampedModel):
uuid = models.UUIDField(default=uuid.uuid4, primary_key=True)
... | [
"django.db.models.ForeignKey",
"django.db.models.UUIDField",
"django.contrib.auth.get_user_model",
"django.utils.translation.gettext_lazy"
] | [((206, 222), 'django.contrib.auth.get_user_model', 'get_user_model', ([], {}), '()\n', (220, 222), False, 'from django.contrib.auth import get_user_model\n'), ((265, 319), 'django.db.models.UUIDField', 'models.UUIDField', ([], {'default': 'uuid.uuid4', 'primary_key': '(True)'}), '(default=uuid.uuid4, primary_key=True)... |
from mltoolkit.mldp.utils.constants.vocabulary import PAD, START, END, UNK
from mltoolkit.mldp import PyTorchPipeline
from mltoolkit.mldp.steps.readers import CsvReader
from mltoolkit.mldp.steps.transformers.nlp import TokenProcessor, VocabMapper, \
SeqLenComputer, Padder, SeqWrapper
from mltoolkit.mldp.steps.gener... | [
"mltoolkit.mldp.steps.readers.CsvReader",
"mltoolkit.mldp.steps.transformers.nlp.VocabMapper",
"mltoolkit.mldp.steps.transformers.nlp.Padder",
"mltoolkit.mldp.PyTorchPipeline",
"fewsum.data_pipelines.steps.GoldSummRevIndxsCreator",
"mltoolkit.mldp.steps.transformers.field.FieldRenamer",
"fewsum.data_pip... | [((1107, 1218), 'mltoolkit.mldp.steps.readers.CsvReader', 'CsvReader', ([], {'sep': '"""\t"""', 'encoding': '"""utf-8"""', 'engine': '"""python"""', 'chunk_size': 'None', 'use_lists': '(True)', 'quating': 'QUOTE_NONE'}), "(sep='\\t', encoding='utf-8', engine='python', chunk_size=None,\n use_lists=True, quating=QUOTE... |
import themis.monitoring.emr_monitoring
import themis.scaling.emr_scaling
from themis.util import aws_common
from themis import config
from themis.model.aws_model import *
class EmrCluster(Scalable, Monitorable):
def __init__(self, id=None):
super(EmrCluster, self).__init__(id)
self.type = None
... | [
"themis.config.get_config"
] | [((652, 671), 'themis.config.get_config', 'config.get_config', ([], {}), '()\n', (669, 671), False, 'from themis import config\n')] |
import sys
import os
import logging
from flask import Flask
HOME_SERVER_DIR = os.path.dirname(os.path.abspath(__file__))
#the absolute path of this script
app_path = os.path.dirname(os.path.realpath(__file__))
#config for the project
from homeserver.server_config import load_config, setup_logging
config = load_... | [
"os.path.abspath",
"homeserver.server_config.setup_logging",
"os.path.realpath",
"flask.Flask",
"os.path.join"
] | [((399, 435), 'homeserver.server_config.setup_logging', 'setup_logging', (['config', 'logging.DEBUG'], {}), '(config, logging.DEBUG)\n', (412, 435), False, 'from homeserver.server_config import load_config, setup_logging\n'), ((98, 123), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (113, 12... |
#!/usr/bin/env python3.7
import unittest
import numpy
import os
import librosa
import soundfile
import sys
from tempfile import TemporaryDirectory
def main():
dest = "tests/test_1_note_Csharp3.wav"
tone = librosa.tone(138.59, sr=22050, length=44100)
soundfile.write(dest, tone, 22050)
print("Created {... | [
"librosa.tone",
"numpy.zeros",
"soundfile.write"
] | [((216, 260), 'librosa.tone', 'librosa.tone', (['(138.59)'], {'sr': '(22050)', 'length': '(44100)'}), '(138.59, sr=22050, length=44100)\n', (228, 260), False, 'import librosa\n'), ((265, 299), 'soundfile.write', 'soundfile.write', (['dest', 'tone', '(22050)'], {}), '(dest, tone, 22050)\n', (280, 299), False, 'import so... |
# Copyright 2020. ThingsBoard
# #
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# #
# http://www.apache.org/licenses/LICENSE-2.0
# #
# Unless required by ... | [
"logging.info",
"logging.exception",
"logging.basicConfig"
] | [((816, 972), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.DEBUG', 'format': '"""%(asctime)s - %(levelname)s - %(module)s - %(lineno)d - %(message)s"""', 'datefmt': '"""%Y-%m-%d %H:%M:%S"""'}), "(level=logging.DEBUG, format=\n '%(asctime)s - %(levelname)s - %(module)s - %(lineno)d - %(messag... |
#!/usr/bin/env python2
"""
grammar_gen.py - Use pgen2 to generate tables from Oil's grammar.
"""
from __future__ import print_function
import os
import sys
from _devbuild.gen.id_kind_asdl import Id, Kind
from _devbuild.gen.syntax_asdl import source
from core import alloc
from core import meta
from core.util import l... | [
"frontend.reader.StringLineReader",
"frontend.lexer.LineLexer",
"pgen2.pgen.MakeGrammar",
"core.meta.ID_SPEC.LexerPairs",
"core.util.log",
"parser.st2tuple",
"tools.find.parse.TokenDef",
"pprint.pprint",
"os.path.join",
"parser.expr",
"oil_lang.expr_parse.ParseTreePrinter",
"_devbuild.gen.synt... | [((2440, 2480), 'frontend.reader.StringLineReader', 'reader.StringLineReader', (['code_str', 'arena'], {}), '(code_str, arena)\n', (2463, 2480), False, 'from frontend import lexer, match, reader\n'), ((2496, 2537), 'frontend.lexer.LineLexer', 'lexer.LineLexer', (['match.MATCHER', '""""""', 'arena'], {}), "(match.MATCHE... |
#!/usr/bin/env python3
# TODO: how will commands handle incorrectly cased names? will need to be able to do that, preferably without losing original case in messages.
# TODO: initial 'all clear'? here, or in main?
# TODO: save 'seen' persistently upon changes?
# TODO: commands, reporting/unique players (later)... | [
"bisect.insort",
"datetime.datetime.now"
] | [((8892, 8915), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (8913, 8915), False, 'import datetime\n'), ((9824, 9847), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (9845, 9847), False, 'import datetime\n'), ((7605, 7672), 'bisect.insort', 'bisect.insort', (['prioritized_war... |
# Copyright(C) 2020 Horus View and Explore B.V.
import psycopg2
from horus_db import Frames, Recordings, Frame, Recording
# This example shows how to iterate over all the recordings
def get_connection():
return psycopg2.connect(
"dbname=HorusWebMoviePlayer user=postgres password=<PASSWORD>")
connection... | [
"psycopg2.connect",
"horus_db.Recording",
"horus_db.Recordings"
] | [((353, 375), 'horus_db.Recordings', 'Recordings', (['connection'], {}), '(connection)\n', (363, 375), False, 'from horus_db import Frames, Recordings, Frame, Recording\n'), ((416, 433), 'horus_db.Recording', 'Recording', (['cursor'], {}), '(cursor)\n', (425, 433), False, 'from horus_db import Frames, Recordings, Frame... |
'''
###############################################################################
# twist_controller.py #
# --------------------------------------------------------------------------- #
# ... | [
"yaw_controller.YawController",
"velocity_controller.VelocityController"
] | [((3209, 3358), 'yaw_controller.YawController', 'YawController', ([], {'wheel_base': 'wheel_base', 'steer_ratio': 'steer_ratio', 'min_speed': 'min_speed', 'max_lat_accel': 'max_lat_accel', 'max_steer_angle': 'max_steer_angle'}), '(wheel_base=wheel_base, steer_ratio=steer_ratio, min_speed=\n min_speed, max_lat_accel=... |
from typing import List, Set, Optional, Tuple
from random import randrange, shuffle, random
from RatInterface import Rat, MazeInfo
from SimpleRats import AlwaysLeftRat, RandomRat
from Localizer import Localizer, NonLocalLocalizer, OneDimensionalLocalizer, TwoDimensionalOneStepLocalizer
from graphviz import Graph
... | [
"Localizer.TwoDimensionalOneStepLocalizer",
"Localizer.OneDimensionalLocalizer",
"SimpleRats.RandomRat",
"random.shuffle",
"Localizer.NonLocalLocalizer",
"SimpleRats.AlwaysLeftRat",
"random.random",
"graphviz.Graph"
] | [((8627, 8634), 'graphviz.Graph', 'Graph', ([], {}), '()\n', (8632, 8634), False, 'from graphviz import Graph\n'), ((13970, 13985), 'SimpleRats.AlwaysLeftRat', 'AlwaysLeftRat', ([], {}), '()\n', (13983, 13985), False, 'from SimpleRats import AlwaysLeftRat, RandomRat\n'), ((14237, 14252), 'SimpleRats.AlwaysLeftRat', 'Al... |
import os
#from tensorflow.keras.applications.vgg16 import VGG16
from tensorflow.keras.applications.inception_v3 import InceptionV3
from tensorflow.keras.preprocessing.image import ImageDataGenerator
#from tensorflow.keras.models import Sequential
#from tensorflow.keras.layers import Activation, Dropout, Flatten, Dense... | [
"os.mkdir",
"tensorflow.keras.preprocessing.image.ImageDataGenerator",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.applications.inception_v3.InceptionV3",
"tensorflow.keras.optimizers.SGD",
"os.path.exists",
"tensorflow.keras.models.Model",
"tensorflow.keras.layers.Input",
"tensorflow.keras.l... | [((1356, 1382), 'os.path.exists', 'os.path.exists', (['result_dir'], {}), '(result_dir)\n', (1370, 1382), False, 'import os\n'), ((1388, 1408), 'os.mkdir', 'os.mkdir', (['result_dir'], {}), '(result_dir)\n', (1396, 1408), False, 'import os\n'), ((1947, 1990), 'tensorflow.keras.layers.Input', 'Input', ([], {'shape': '(I... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: pyatv/protocols/mrp/protobuf/AudioFadeResponseMessage.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google... | [
"google.protobuf.symbol_database.Default",
"pyatv.protocols.mrp.protobuf.ProtocolMessage_pb2.ProtocolMessage.RegisterExtension",
"google.protobuf.descriptor_pool.Default",
"google.protobuf.reflection.GeneratedProtocolMessageType"
] | [((522, 548), 'google.protobuf.symbol_database.Default', '_symbol_database.Default', ([], {}), '()\n', (546, 548), True, 'from google.protobuf import symbol_database as _symbol_database\n'), ((1315, 1531), 'google.protobuf.reflection.GeneratedProtocolMessageType', '_reflection.GeneratedProtocolMessageType', (['"""Audio... |
#!/usr/bin/env python3
#
# Copyright 2018-2020 Internet Corporation for Assigned Names and Numbers.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, you can obtain one at https://mozilla.org/MPL/2.0/.
#
# Developed by S... | [
"psycopg2.connect"
] | [((888, 1003), 'psycopg2.connect', 'psycopg2.connect', ([], {'host': "pgcfg['host']", 'dbname': "pgcfg['database']", 'user': "pgcfg['user']", 'password': "pgcfg['password']"}), "(host=pgcfg['host'], dbname=pgcfg['database'], user=pgcfg[\n 'user'], password=pgcfg['password'])\n", (904, 1003), False, 'import psycopg2\... |
from gksdudaovld import KoEngMapper as Mapper
from SimpleTester import SimpleTester
tester = SimpleTester("./test_en2ko.txt", Mapper.conv_en2ko)
print(tester.start().log)
# tester = SimpleTester("./test_ko2en.txt", Mapper.conv_ko2en)
# print(tester.start().log) | [
"SimpleTester.SimpleTester"
] | [((94, 145), 'SimpleTester.SimpleTester', 'SimpleTester', (['"""./test_en2ko.txt"""', 'Mapper.conv_en2ko'], {}), "('./test_en2ko.txt', Mapper.conv_en2ko)\n", (106, 145), False, 'from SimpleTester import SimpleTester\n')] |
"""Test the Nanoleaf config flow."""
from unittest.mock import patch
from pynanoleaf import InvalidToken, NotAuthorizingNewTokens, Unavailable
from homeassistant import config_entries
from homeassistant.components.nanoleaf.const import DOMAIN
from homeassistant.const import CONF_HOST, CONF_TOKEN
from homeassistant.co... | [
"unittest.mock.patch",
"pynanoleaf.Unavailable",
"pynanoleaf.NotAuthorizingNewTokens",
"pynanoleaf.InvalidToken"
] | [((1584, 1680), 'unittest.mock.patch', 'patch', (['"""homeassistant.components.nanoleaf.config_flow.Nanoleaf.authorize"""'], {'return_value': 'None'}), "('homeassistant.components.nanoleaf.config_flow.Nanoleaf.authorize',\n return_value=None)\n", (1589, 1680), False, 'from unittest.mock import patch\n'), ((2596, 269... |
import urllib
from bs4 import BeautifulSoup
from urllib import request
page = urllib.request.urlopen('https://www.python.org')
st = page.read()
soup = BeautifulSoup(st, 'html.parser')
print("Text in the first a tag:")
li = soup.find_all("li")
for i in li:
a = i.find('a')
print(a.attrs['href'])
| [
"bs4.BeautifulSoup",
"urllib.request.urlopen"
] | [((80, 128), 'urllib.request.urlopen', 'urllib.request.urlopen', (['"""https://www.python.org"""'], {}), "('https://www.python.org')\n", (102, 128), False, 'import urllib\n'), ((153, 185), 'bs4.BeautifulSoup', 'BeautifulSoup', (['st', '"""html.parser"""'], {}), "(st, 'html.parser')\n", (166, 185), False, 'from bs4 impo... |
#!/usr/bin/env python3
import os
import sys
import unittest
from ietf.cmd.mirror import assemble_rsync
class TestAssembleRsync(unittest.TestCase):
boilerplate = ['rsync', '-az', '--delete-during']
rsync_no_path = (('charter', boilerplate +
['ietf.org::everything-ftp/ietf/']),
... | [
"unittest.main",
"ietf.cmd.mirror.assemble_rsync"
] | [((2361, 2376), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2374, 2376), False, 'import unittest\n'), ((1657, 1699), 'ietf.cmd.mirror.assemble_rsync', 'assemble_rsync', (['doc_type', 'test_path', '(False)'], {}), '(doc_type, test_path, False)\n', (1671, 1699), False, 'from ietf.cmd.mirror import assemble_rsync... |
# Subscribers are created with ZMQ.SUB socket types.
# A zmq subscriber can connect to many publishers.
import sys
import zmq
import base64
import simplejson as json
port = "5563"
if len(sys.argv) > 1:
port = sys.argv[1]
int(port)
# Socket to talk to server
context = zmq.Context()
socket = context.socket(zmq... | [
"zmq.Context"
] | [((279, 292), 'zmq.Context', 'zmq.Context', ([], {}), '()\n', (290, 292), False, 'import zmq\n')] |
import numpy as np
import itertools
from scintillations.stream import modulate as apply_turbulence
from scintillations.stream import transverse_speed
from streaming.stream import Stream, BlockStream
from streaming.signal import *
import streaming.signal
import logging
from acoustics.signal import impulse_response_real... | [
"numpy.log2",
"acoustics.signal.impulse_response_real_even"
] | [((2442, 2478), 'acoustics.signal.impulse_response_real_even', 'impulse_response_real_even', (['s', 'ntaps'], {}), '(s, ntaps)\n', (2468, 2478), False, 'from acoustics.signal import impulse_response_real_even\n'), ((4702, 4712), 'numpy.log2', 'np.log2', (['x'], {}), '(x)\n', (4709, 4712), True, 'import numpy as np\n')] |
import subprocess
import sys
import time
from pathlib import Path
import click
from .database import Job, db
from .lint import lint
from .pdf_reader import pdf_workers
from .utils import add_files
dir = Path(__file__).resolve().parent.parent
@click.group(invoke_without_command=True)
@click.pass_context
def cli(ctx... | [
"sys.stdout.write",
"click.option",
"click.echo",
"time.sleep",
"time.time",
"pathlib.Path",
"sys.stdout.flush",
"click.Path",
"click.group"
] | [((248, 288), 'click.group', 'click.group', ([], {'invoke_without_command': '(True)'}), '(invoke_without_command=True)\n', (259, 288), False, 'import click\n'), ((435, 502), 'click.option', 'click.option', (['"""-c"""', '"""--count"""'], {'default': '(3)', 'help': '"""Number of workers."""'}), "('-c', '--count', defaul... |
from setuptools import setup, find_packages
import sys
import os.path
# Must be one line or PyPI will cut it off
DESC = ("A colormap tool")
LONG_DESC = open("README.rst").read()
setup(
name="viscm",
version="0.10.0",
description=DESC,
long_description=LONG_DESC,
author="<NAME>, <NAME>, <NAME>",
... | [
"setuptools.find_packages"
] | [((700, 715), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (713, 715), False, 'from setuptools import setup, find_packages\n')] |
from unittest.mock import Mock
import pytest
from directory_header_footer import context_processors
from directory_constants.constants import urls as default_urls
@pytest.fixture
def sso_user():
return Mock(
id=1,
email='<EMAIL>'
)
@pytest.fixture
def request_logged_in(rf, sso_user):
re... | [
"directory_header_footer.context_processors.header_footer_context_processor",
"directory_header_footer.context_processors.sso_processor",
"unittest.mock.Mock",
"directory_header_footer.context_processors.urls_processor"
] | [((209, 236), 'unittest.mock.Mock', 'Mock', ([], {'id': '(1)', 'email': '"""<EMAIL>"""'}), "(id=1, email='<EMAIL>')\n", (213, 236), False, 'from unittest.mock import Mock\n'), ((569, 620), 'directory_header_footer.context_processors.sso_processor', 'context_processors.sso_processor', (['request_logged_in'], {}), '(requ... |
"""
A toy example of playing against random bot on Mocsár
Using env "mocsar" and 'human_mode'. It implies using random agent.
"""
import rlcard3
# Make environment and enable human mode
env = rlcard3.make(env_id='mocsar', config={'human_mode': True})
# Reset environment
state = env.reset()
while not env.is_over():
... | [
"rlcard3.make"
] | [((194, 252), 'rlcard3.make', 'rlcard3.make', ([], {'env_id': '"""mocsar"""', 'config': "{'human_mode': True}"}), "(env_id='mocsar', config={'human_mode': True})\n", (206, 252), False, 'import rlcard3\n')] |
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 14 13:04:49 2017
@author: acer
"""
from skpy import Skype
from getpass import getpass
Skype("pandey.divyanshu34", getpass(), ".tokens-pandey.divyanshu34")
sk = Skype(connect=False)
print(sk.contacts) | [
"getpass.getpass",
"skpy.Skype"
] | [((208, 228), 'skpy.Skype', 'Skype', ([], {'connect': '(False)'}), '(connect=False)\n', (213, 228), False, 'from skpy import Skype\n'), ((162, 171), 'getpass.getpass', 'getpass', ([], {}), '()\n', (169, 171), False, 'from getpass import getpass\n')] |
"""
爬虫的用途:12306抢票,短信轰炸,数据获取
分类:通用爬虫:是搜索引擎抓取系统的重要部分,主要是把互联网上的页面下载到本地作为一个镜像备份
聚焦爬虫:对特定需求进行数据获取,会对页面的内容进行筛选,保证只抓取和需求相关的网页信息
Http:端口号80
Https: 端口号443
使用第三方的requests进行请求:支持python2和3,在urllib中2和3的语法有些不一样
"""
import requests
kw = {'wd': '长城'}
# headers伪装成一个浏览器进行的请求
# 不加这个的话,网页会识别出请求来自一个python而不是... | [
"requests.get"
] | [((484, 552), 'requests.get', 'requests.get', (['"""https://www.baidu.com/s?"""'], {'params': 'kw', 'headers': 'headers'}), "('https://www.baidu.com/s?', params=kw, headers=headers)\n", (496, 552), False, 'import requests\n')] |
import markovify
# with open("esenin.txt", 'r', encoding='utf-8') as f0, \
# open("kish.txt", 'r', encoding='utf-8') as f1, \
# open("kino.txt", 'r', encoding='utf-8') as f2, \
# open("kukr.txt", 'r', encoding='utf-8') as f3, \
# open("dataset.txt", 'a', encoding='utf-8') as f:
# f.write(f0.read())
# ... | [
"markovify.Text"
] | [((489, 509), 'markovify.Text', 'markovify.Text', (['text'], {}), '(text)\n', (503, 509), False, 'import markovify\n')] |
"""halfway URL Configuration"""
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.urls import path, include
urlpatterns = [
path('admin', admin.site.urls),
path('users/login', auth_views.L... | [
"django.contrib.auth.views.LogoutView.as_view",
"django.contrib.auth.views.LoginView.as_view",
"django.urls.path",
"django.urls.include",
"django.conf.urls.static.static"
] | [((488, 549), 'django.conf.urls.static.static', 'static', (['settings.MEDIA_URL'], {'document_root': 'settings.MEDIA_ROOT'}), '(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n', (494, 549), False, 'from django.conf.urls.static import static\n'), ((252, 282), 'django.urls.path', 'path', (['"""admin"""', 'admin.... |
from django.shortcuts import render
from cms.models import Pages
from django.http import HttpResponse
from django.http import HttpResponseNotFound
from django.core.exceptions import ObjectDoesNotExist
# Create your views here.
def slash(self):
response = ''
for Page in Pages.objects.all():
redirection... | [
"django.http.HttpResponseNotFound",
"cms.models.Pages.objects.all",
"django.http.HttpResponse"
] | [((280, 299), 'cms.models.Pages.objects.all', 'Pages.objects.all', ([], {}), '()\n', (297, 299), False, 'from cms.models import Pages\n'), ((452, 474), 'django.http.HttpResponse', 'HttpResponse', (['response'], {}), '(response)\n', (464, 474), False, 'from django.http import HttpResponse\n'), ((716, 749), 'django.http.... |
from __future__ import print_function
import torch
''' Env
pip install -U torch torchvision
pip install -U cython
pip install -U 'git+https://github.com/facebookresearch/fvcore.git' 'git+https://github.com/cocodataset/cocoapi.git#subdirectory=PythonAPI'
git clone https://github.com/facebookresearch/detectron2 detectr... | [
"detectron2.engine.DefaultPredictor",
"detectron2.utils.logger.setup_logger",
"cv2.imread",
"detectron2.config.get_cfg",
"detectron2.data.MetadataCatalog.get"
] | [((459, 473), 'detectron2.utils.logger.setup_logger', 'setup_logger', ([], {}), '()\n', (471, 473), False, 'from detectron2.utils.logger import setup_logger\n'), ((779, 804), 'cv2.imread', 'cv2.imread', (['"""./input.jpg"""'], {}), "('./input.jpg')\n", (789, 804), False, 'import cv2\n'), ((812, 821), 'detectron2.config... |
# Generated by Django 3.1.7 on 2021-04-06 12:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('catalog', '0004_auto_20210405_1042'),
]
operations = [
migrations.AlterField(
model_name='book',
name='title',
... | [
"django.db.models.CharField"
] | [((333, 365), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(300)'}), '(max_length=300)\n', (349, 365), False, 'from django.db import migrations, models\n')] |
from keckdrpframework.core.framework import Framework
from keckdrpframework.config.framework_config import ConfigClass
from keckdrpframework.models.arguments import Arguments
from keckdrpframework.utils.drpf_logger import getLogger
import subprocess
import time
import argparse
import sys
import traceback
impor... | [
"traceback.print_exc",
"argparse.ArgumentParser",
"keckdrpframework.core.framework.Framework",
"pkg_resources.resource_filename",
"datetime.datetime.utcnow",
"pathlib.Path",
"keckdrpframework.config.framework_config.ConfigClass",
"sys.exit",
"keckdrpframework.utils.drpf_logger.getLogger"
] | [((730, 800), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'prog': 'f"""{in_args[0]}"""', 'description': 'description'}), "(prog=f'{in_args[0]}', description=description)\n", (753, 800), False, 'import argparse\n'), ((2612, 2671), 'pkg_resources.resource_filename', 'pkg_resources.resource_filename', (['p... |
# -*- coding: utf-8 -*-
import explainaboard.error_analysis as ea
import numpy
import os
def get_aspect_value(sample_list, dict_aspect_func):
dict_span2aspect_val = {}
dict_span2aspect_val_pred = {}
for aspect, fun in dict_aspect_func.items():
dict_span2aspect_val[aspect] = {}
dict_span2a... | [
"explainaboard.error_analysis.compute_confidence_interval_acc",
"explainaboard.error_analysis.select_bucketing_func",
"os.path.dirname",
"explainaboard.error_analysis.print_dict",
"explainaboard.error_analysis.beautify_interval",
"explainaboard.error_analysis.sort_dict",
"explainaboard.error_analysis.fo... | [((3461, 3494), 'explainaboard.error_analysis.accuracy', 'ea.accuracy', (['true_list', 'pred_list'], {}), '(true_list, pred_list)\n', (3472, 3494), True, 'import explainaboard.error_analysis as ea\n'), ((11223, 11251), 'explainaboard.error_analysis.sort_dict', 'ea.sort_dict', (['dict_bucket2f1'], {}), '(dict_bucket2f1)... |
import numpy as np
from libs.chromosome.chromosome_modifier import ChromosomeModifier
from libs.chromosome.mutation_types import MutationTypes
class MutationService:
def __init__(self, algorithm_configuration):
self.__algorithm_configuration = algorithm_configuration
self.__chromosome_modifier =... | [
"libs.chromosome.chromosome_modifier.ChromosomeModifier"
] | [((321, 478), 'libs.chromosome.chromosome_modifier.ChromosomeModifier', 'ChromosomeModifier', (['algorithm_configuration.chromosome_config', 'algorithm_configuration.left_range_number', 'algorithm_configuration.right_range_number'], {}), '(algorithm_configuration.chromosome_config,\n algorithm_configuration.left_ran... |
import contextlib
import os
import pathlib
import shutil
import subprocess
import sys
import pytest
from cookiecutter.main import cookiecutter
_template_dir = pathlib.Path(__file__).parent.parent
_base_cookiecutter_args = {
"project_name": "my-python-package",
"package_name": "my_python_package",
"friendl... | [
"os.getcwd",
"pytest.fixture",
"pathlib.Path",
"shutil.copytree",
"os.chdir"
] | [((680, 711), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (694, 711), False, 'import pytest\n'), ((1227, 1243), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (1241, 1243), False, 'import pytest\n'), ((1442, 1458), 'pytest.fixture', 'pytest.fixture', ([], {}), '()... |
import pandas as pd
import numpy as np
import re
import math
import sys
def top_extract(s):
top = []
for i in range (1,len(s)+1):
if s[i-1].lower() == 'top':
top.append(s[i])
return top
def base_extract(s):
base = []
for i in range (1,len(s)+1):
if s[i-1].lower() == '... | [
"pandas.DataFrame",
"pandas.isna",
"re.split",
"pandas.read_csv"
] | [((1603, 1654), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['perfume_name', 'note_name']"}), "(columns=['perfume_name', 'note_name'])\n", (1615, 1654), True, 'import pandas as pd\n'), ((2329, 2375), 'pandas.DataFrame', 'pd.DataFrame', (['note_list'], {'columns': "['note_name']"}), "(note_list, columns=['note... |
######################################
# tooltip.py
# @author: <NAME>
# 6/24/2015
######################################
from Tkinter import Toplevel, TclError, Label, LEFT, SOLID
class ToolTip(object):
"""
Displays text in a label below a passed widget
:param widget: The widget tooltip will be ... | [
"Tkinter.Label",
"Tkinter.Toplevel"
] | [((1267, 1288), 'Tkinter.Toplevel', 'Toplevel', (['self.widget'], {}), '(self.widget)\n', (1275, 1288), False, 'from Tkinter import Toplevel, TclError, Label, LEFT, SOLID\n'), ((1606, 1732), 'Tkinter.Label', 'Label', (['tw'], {'text': 'self.text', 'justify': 'LEFT', 'background': '"""#ffffe0"""', 'relief': 'SOLID', 'bo... |
from pathlib import Path
def get_project_path():
return Path(__file__).parent
def get_data_path():
project_path = get_project_path()
parent_dir = project_path.parent
return parent_dir / 'data'
def get_results_path():
project_path = get_project_path()
parent_dir = project_path.parent
re... | [
"pathlib.Path"
] | [((62, 76), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (66, 76), False, 'from pathlib import Path\n')] |
#!/usr/bin/env python
#Copyright (c) 2014, <NAME> <<EMAIL>>
#All rights reserved.
#
#Redistribution and use in source and binary forms, with or without
#modification, are permitted provided that the following conditions are met:
#
#* Redistributions of source code must retain the above copyright notice, this
# list of... | [
"os.mkdir",
"subprocess.Popen",
"os.remove",
"optparse.OptionParser",
"converter.Img_conv",
"numpy.ones",
"os.kill",
"threading.Event",
"glob.glob",
"cola.ComponentLabeling",
"threading.Semaphore",
"re.compile"
] | [((21936, 21950), 'optparse.OptionParser', 'OptionParser', ([], {}), '()\n', (21948, 21950), False, 'from optparse import OptionParser\n'), ((2045, 2080), 'glob.glob', 'glob.glob', (["(ccl_c_dir + '/img/*.pbm')"], {}), "(ccl_c_dir + '/img/*.pbm')\n", (2054, 2080), False, 'import glob\n'), ((2130, 2152), 're.compile', '... |
import re
import pytest
from pathlib import Path
from utilities import subprocess_runner, remove_ansible_warnings
TEST_CASES = [
"../class6/collateral/roles_test/test_pb1.yml",
"../class6/collateral/roles_test/test_pb2.yml",
"../class6/collateral/roles_test/test_pb3.yml",
"../class6/collateral/roles_te... | [
"utilities.remove_ansible_warnings",
"pathlib.Path",
"utilities.subprocess_runner",
"pytest.mark.parametrize",
"re.search"
] | [((948, 996), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""test_case"""', 'TEST_CASES'], {}), "('test_case', TEST_CASES)\n", (971, 996), False, 'import pytest\n'), ((1354, 1427), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""exercise"""', "['exercise1a.yml', 'exercise1b.yml']"], {}), "('exe... |
from decimal import Decimal
from django.conf import settings
from shop.models import Product
from coupons.models import Coupon
class Cart(object):
def __init__(self, request):
"""
Initialize the cart
:param request:
"""
self.session = request.session
cart = self.s... | [
"shop.models.Product.objects.filter",
"coupons.models.Coupon.objects.get",
"decimal.Decimal"
] | [((2370, 2412), 'shop.models.Product.objects.filter', 'Product.objects.filter', ([], {'id__in': 'product_ids'}), '(id__in=product_ids)\n', (2392, 2412), False, 'from shop.models import Product\n'), ((3788, 3800), 'decimal.Decimal', 'Decimal', (['"""0"""'], {}), "('0')\n", (3795, 3800), False, 'from decimal import Decim... |
# Generated by Django 2.2.6 on 2020-08-20 14:01
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('core', '0042_conference_treasurer'),
]
operations = [
migrations.AddField(
model_name='conference',... | [
"django.db.models.DateField",
"django.db.models.CharField"
] | [((377, 428), 'django.db.models.DateField', 'models.DateField', ([], {'default': 'django.utils.timezone.now'}), '(default=django.utils.timezone.now)\n', (393, 428), False, 'from django.db import migrations, models\n'), ((597, 648), 'django.db.models.DateField', 'models.DateField', ([], {'default': 'django.utils.timezon... |
from django.utils.translation import gettext as _
NA = 99
RATE_CHOICES = (
(0, _('0. Need more info')),
(1, _('1. Poor')),
(2, _('2. Not so good')),
(3, _('3. Is o.k.')),
(4, _('4. Good')),
(5, _('5. Excellent')),
(NA, _('n/a - choose not to answer')),
)
RATE_CHOICES_DICT = dict(RATE_CHOI... | [
"django.utils.translation.gettext"
] | [((672, 699), 'django.utils.translation.gettext', '_', (['"""Visible only to staff."""'], {}), "('Visible only to staff.')\n", (673, 699), True, 'from django.utils.translation import gettext as _\n'), ((715, 757), 'django.utils.translation.gettext', '_', (['"""Visible to other reviewers and staff."""'], {}), "('Visible... |
"""
Simple audio clustering
1. Get the embeddings - at an interval of 0.5s each
2. Get the VAD - variable interval
3. Get embeddings for a VAD interval -> Take average of the embeddings
4. Get the ground truth for embedding for each speaker - marked 0.5s interval
5. L2 Normalize the embeddings before taking a distance ... | [
"pandas.DataFrame",
"yaml.load",
"json.load",
"argparse.ArgumentParser",
"os.makedirs",
"yaml.dump",
"os.path.exists",
"isat_diarization.gen_embeddings",
"utils.print_list",
"pickle.load",
"numpy.linalg.norm",
"numpy.dot",
"os.path.join"
] | [((1913, 1946), 'numpy.linalg.norm', 'np.linalg.norm', (['embeddings'], {'ord': '(2)'}), '(embeddings, ord=2)\n', (1927, 1946), True, 'import numpy as np\n'), ((6918, 6932), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (6930, 6932), True, 'import pandas as pd\n'), ((7031, 7078), 'os.path.join', 'os.path.join',... |
# Generated by Django 2.2.10 on 2020-11-04 21:03
from django.db import migrations, models
import versatileimagefield.fields
class Migration(migrations.Migration):
dependencies = [("page", "0001_initial")]
operations = [
migrations.AddField(
model_name="page", name="in_menu", field=model... | [
"django.db.models.BooleanField"
] | [((315, 349), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)'}), '(default=False)\n', (334, 349), False, 'from django.db import migrations, models\n')] |
import numpy as np
from distributions.distribution import Distribution
class NonParametric(Distribution):
"""
Provides functions for a non-parametric forecast distribution.
"""
@staticmethod
def pdf(x, pdf_x, x_eval):
pass
@staticmethod
def cdf(x, cdf_x, x_eval):
"""
... | [
"numpy.trapz",
"numpy.maximum",
"numpy.searchsorted",
"numpy.array",
"numpy.arange"
] | [((522, 548), 'numpy.searchsorted', 'np.searchsorted', (['x_eval', 'x'], {}), '(x_eval, x)\n', (537, 548), True, 'import numpy as np\n'), ((619, 654), 'numpy.maximum', 'np.maximum', (['(0)', '(insertion_points - 1)'], {}), '(0, insertion_points - 1)\n', (629, 654), True, 'import numpy as np\n'), ((1061, 1135), 'numpy.t... |
# from collections import ChainMap
# food_types = {'Vegetables': 15, 'Dairy': 20, 'Meat': 3, 'Cereals': 9, 'Fruits': 11, 'Fish': 7}
# countries = {'USA': 25, 'Australia': 15, 'Canada': 15, 'France': 6, 'India': 4}
# discount = {'gold': 20, 'regular': 10}
# chain = ChainMap(food_types, countries)
# food_types['Sweets'... | [
"datetime.datetime.strptime"
] | [((917, 960), 'datetime.datetime.strptime', 'datetime.strptime', (['datetime_obj', '"""%Y-%m-%d"""'], {}), "(datetime_obj, '%Y-%m-%d')\n", (934, 960), False, 'from datetime import datetime\n'), ((1231, 1263), 'datetime.datetime.strptime', 'datetime.strptime', (['s', '"""%d %B %Y"""'], {}), "(s, '%d %B %Y')\n", (1248, 1... |
from functools import wraps
from unittest.mock import patch
from auth import get_user_token_string
def mock_decorator(f):
"""Fake decorator for mocking other decorators."""
@wraps(f)
def decorated_function(*args, **kwargs):
return f(*args, **kwargs)
return decorated_function
def mock_auth... | [
"unittest.mock.patch",
"functools.wraps"
] | [((485, 574), 'unittest.mock.patch', 'patch', (['"""boxwise_flask.auth_helper.get_auth_string_from_header"""', 'get_user_token_string'], {}), "('boxwise_flask.auth_helper.get_auth_string_from_header',\n get_user_token_string)\n", (490, 574), False, 'from unittest.mock import patch\n'), ((599, 663), 'unittest.mock.pa... |
import numpy as np
from math import log, sqrt, ceil
import random
import string
from copy import copy
import pyximport
from tabulate import tabulate
pyximport.install()
from ..util import math_functions
import matplotlib.pyplot as plt
import textwrap
from textwrap import dedent
from multiprocessing import Pool
from ... | [
"matplotlib.pyplot.show",
"numpy.sum",
"numpy.vectorize",
"numpy.copy",
"numpy.multiply",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.plot",
"math.sqrt",
"copy.copy",
"random.choice",
"numpy.logical_and",
"textwrap.TextWrapper",
"numpy.array",
"tabulate.tabulate",
"numpy.arange",
"... | [((149, 168), 'pyximport.install', 'pyximport.install', ([], {}), '()\n', (166, 168), False, 'import pyximport\n'), ((10474, 10486), 'copy.copy', 'copy', (['ranges'], {}), '(ranges)\n', (10478, 10486), False, 'from copy import copy\n'), ((10860, 10872), 'copy.copy', 'copy', (['ranges'], {}), '(ranges)\n', (10864, 10872... |
#! /usr/bin/env python3
import argparse
from pathlib import Path
import json
import sys
from scriptutil import calc
C0_OFF = "Task: C0, Corunner: OFF"
C0_ON = "Task: C0, Corunner: ON"
C1_OFF = "Task: C1, Corunner: OFF"
C1_ON = "Task: C1, Corunner: ON"
def getopts(argv):
parser = argparse.ArgumentParser()
pa... | [
"scriptutil.calc",
"json.load",
"argparse.ArgumentParser"
] | [((288, 313), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (311, 313), False, 'import argparse\n'), ((1213, 1248), 'scriptutil.calc', 'calc', (['values[C0_OFF]', 'values[C0_ON]'], {}), '(values[C0_OFF], values[C0_ON])\n', (1217, 1248), False, 'from scriptutil import calc\n'), ((1262, 1297), '... |
"""
Multivariate Version of exchange prediciton.
"""
import os
os.system("clear")
import sys
sys.path.append("./core/containers/")
sys.path.append("./core/models/")
sys.path.append("./core/tools/")
import datetime
import keras
import pandas as pd
import numpy as np
import matplotlib
# TODO: add auto-detect
# for mac O... | [
"sys.path.append",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.close",
"matplotlib.pyplot.legend",
"os.system",
"multivariate_container.MultivariateContainer",
"matplotlib.use",
"bokeh_visualize.advanced_visualize",
"multivariate_lstm.MultivariateLSTM",
"datetime.datet... | [((63, 81), 'os.system', 'os.system', (['"""clear"""'], {}), "('clear')\n", (72, 81), False, 'import os\n'), ((93, 130), 'sys.path.append', 'sys.path.append', (['"""./core/containers/"""'], {}), "('./core/containers/')\n", (108, 130), False, 'import sys\n'), ((131, 164), 'sys.path.append', 'sys.path.append', (['"""./co... |
import numpy as np
a = np.array([
[1, 2, 3],
[4, 5, 6]
])
print("print(a)")
print(a)
print()
print("print(a.T)")
print(a.T)
print()
print("print(a.dot(2))")
print(a.dot(2))
print()
print("print(a.dot(np.array([2, 2, 2])))")
print(a.dot(np.array([2, 2, 2])))
print()
| [
"numpy.array"
] | [((24, 56), 'numpy.array', 'np.array', (['[[1, 2, 3], [4, 5, 6]]'], {}), '([[1, 2, 3], [4, 5, 6]])\n', (32, 56), True, 'import numpy as np\n'), ((250, 269), 'numpy.array', 'np.array', (['[2, 2, 2]'], {}), '([2, 2, 2])\n', (258, 269), True, 'import numpy as np\n')] |
"""
Sample Python 3.5 application that has plugin support.
It dynamically loads plugins from the 'plugins' directory.
Two types of plugins are supported: commands and hooks.
A command is executed if it matches a cmdline argument.
A hook is executed before and after each command...
Example usage:
main.py print upp... | [
"app.processor.process_commands",
"app.args.get_args",
"logging.debug",
"logging.basicConfig"
] | [((497, 537), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.DEBUG'}), '(level=logging.DEBUG)\n', (516, 537), False, 'import logging\n'), ((542, 567), 'logging.debug', 'logging.debug', (['"""Starting"""'], {}), "('Starting')\n", (555, 567), False, 'import logging\n'), ((579, 593), 'app.args.get_a... |
import random
import numpy
import torch
from backobs.integration import extend as backobs_extend
from backobs.integration import (
extend_with_access_unreduced_loss as backobs_extend_with_access_unreduced_loss,
)
def set_deepobs_seed(seed=0):
"""Set all seeds used by DeepOBS."""
random.seed(seed)
nu... | [
"numpy.random.seed",
"torch.manual_seed",
"numpy.logical_not",
"numpy.isclose",
"random.seed",
"backobs.integration.extend_with_access_unreduced_loss",
"torch.allclose",
"backobs.integration.extend"
] | [((296, 313), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (307, 313), False, 'import random\n'), ((318, 341), 'numpy.random.seed', 'numpy.random.seed', (['seed'], {}), '(seed)\n', (335, 341), False, 'import numpy\n'), ((346, 369), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (363,... |
import copy
import numpy as np
import os
import torch
import pickle
from detectron2.data import MetadataCatalog
from detectron2.data import detection_utils as utils
from detectron2.structures import (
BitMasks,
Boxes,
BoxMode,
Instances,
PolygonMasks,
polygons_to_bitmask,
)
import pycocotools.ma... | [
"pycocotools.mask.decode",
"pickle.load",
"detectron2.structures.Instances",
"os.path.join",
"detectron2.structures.polygons_to_bitmask",
"detectron2.structures.PolygonMasks",
"os.path.exists",
"torchvision.transforms.Compose",
"copy.deepcopy",
"numpy.asarray",
"detectron2.structures.Boxes",
"... | [((1016, 1033), 'numpy.asarray', 'np.asarray', (['image'], {}), '(image)\n', (1026, 1033), True, 'import numpy as np\n'), ((2086, 2107), 'detectron2.structures.Instances', 'Instances', (['image_size'], {}), '(image_size)\n', (2095, 2107), False, 'from detectron2.structures import BitMasks, Boxes, BoxMode, Instances, Po... |
# -*- coding: utf-8 -*-
"""
Python-Future Documentation Extensions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Support for automatically documenting filters and tests.
Based on the Jinja2 documentation extensions.
:copyright: Copyright 2008 by <NAME>.
:license: BSD.
"""
import collections
import o... | [
"docutils.nodes.section"
] | [((767, 782), 'docutils.nodes.section', 'nodes.section', ([], {}), '()\n', (780, 782), False, 'from docutils import nodes\n')] |
from time import time
class CallController:
def __init__(self, max_call_interval):
self._max_call_interval = max_call_interval
self._last_call = time()
def __call__(self, function):
def wrapped(*args, **kwargs):
now = time()
if now - self._last_call > self._m... | [
"time.time"
] | [((168, 174), 'time.time', 'time', ([], {}), '()\n', (172, 174), False, 'from time import time\n'), ((266, 272), 'time.time', 'time', ([], {}), '()\n', (270, 272), False, 'from time import time\n')] |
import re
import urllib.parse
from typing import Union
_scheme_regex = re.compile(r"^(?:https?)?$", flags=re.IGNORECASE | re.ASCII)
_netloc_regex = re.compile(r"^(?:www\.)?mangaupdates\.com$", flags=re.IGNORECASE | re.ASCII)
_query_regex = re.compile(r"id=(\d+)(?:&|$)", flags=re.IGNORECASE | re.ASCII)
def get_id_fr... | [
"re.compile"
] | [((73, 132), 're.compile', 're.compile', (['"""^(?:https?)?$"""'], {'flags': '(re.IGNORECASE | re.ASCII)'}), "('^(?:https?)?$', flags=re.IGNORECASE | re.ASCII)\n", (83, 132), False, 'import re\n'), ((150, 227), 're.compile', 're.compile', (['"""^(?:www\\\\.)?mangaupdates\\\\.com$"""'], {'flags': '(re.IGNORECASE | re.AS... |
import pytest
from flag_engine.features.schemas import (
FeatureStateSchema,
MultivariateFeatureOptionSchema,
MultivariateFeatureStateValueSchema,
)
from flag_engine.utils.exceptions import InvalidPercentageAllocation
def test_can_load_multivariate_feature_option_dict_without_id_field():
Multivariate... | [
"pytest.raises",
"flag_engine.features.schemas.MultivariateFeatureOptionSchema",
"flag_engine.features.schemas.FeatureStateSchema",
"flag_engine.features.schemas.MultivariateFeatureStateValueSchema"
] | [((1003, 1045), 'pytest.raises', 'pytest.raises', (['InvalidPercentageAllocation'], {}), '(InvalidPercentageAllocation)\n', (1016, 1045), False, 'import pytest\n'), ((308, 341), 'flag_engine.features.schemas.MultivariateFeatureOptionSchema', 'MultivariateFeatureOptionSchema', ([], {}), '()\n', (339, 341), False, 'from ... |
import torch
from torch import nn, Tensor
from torch.nn import functional as F
from abc import abstractmethod
from typing import List, Callable, Union, Any, TypeVar, Tuple
from .util import reparameterize
class BaseVAE(nn.Module):
def __init__(self,
name: str,
latent_dim: int) ->... | [
"torch.nn.functional.mse_loss",
"torch.abs",
"torch.randn"
] | [((1428, 1469), 'torch.randn', 'torch.randn', (['num_samples', 'self.latent_dim'], {}), '(num_samples, self.latent_dim)\n', (1439, 1469), False, 'import torch\n'), ((2306, 2331), 'torch.nn.functional.mse_loss', 'F.mse_loss', (['recons', 'input'], {}), '(recons, input)\n', (2316, 2331), True, 'from torch.nn import funct... |
import socket
host = "192.168.0.103"
port_windows = 7899
while True:
try:
socket_windows = socket.socket()
socket_windows.connect((host, port_windows))
temp = socket_windows.recv(1024).decode()
if temp:
print(temp)
continue
except Exception:
con... | [
"socket.socket"
] | [((105, 120), 'socket.socket', 'socket.socket', ([], {}), '()\n', (118, 120), False, 'import socket\n')] |
from datetime import datetime, timedelta, timezone
import discord
import humanize
from apscheduler.jobstores.base import ConflictingIdError
from data.model import Case
from data.services import guild_service, user_service
from discord import app_commands
from discord.ext import commands
from discord.utils import escap... | [
"data.services.guild_service.get_guild",
"utils.mod.prepare_liftwarn_log",
"discord.utils.escape_markdown",
"data.services.guild_service.inc_caseid",
"utils.mod.submit_public_log",
"discord.utils.escape_mentions",
"utils.mod.notify_user",
"discord.app_commands.describe",
"data.services.user_service.... | [((1002, 1014), 'utils.framework.mod_and_up', 'mod_and_up', ([], {}), '()\n', (1012, 1014), False, 'from utils.framework import mod_and_up, ModsAndAboveMemberOrUser, Duration, ModsAndAboveMember, UserOnly\n'), ((1020, 1053), 'discord.app_commands.guilds', 'app_commands.guilds', (['cfg.guild_id'], {}), '(cfg.guild_id)\n... |
'''
------------------------------------------------------------------------
MOMENTUM.PY
------------------------------------------------------------------------
If extreme, overtraded or wix issue long, or short signals, trigger the
executor
'''
'''
---------------------------------------------------------------... | [
"pandas.DataFrame",
"ccat.bucket.Bucket",
"ccat.wix.Wix",
"pandas.merge",
"ccat.extreme.Extreme",
"ccat.config.now",
"ccat.overtraded.Overtraded"
] | [((4125, 4134), 'ccat.config.now', 'cnf.now', ([], {}), '()\n', (4132, 4134), True, 'from ccat import config as cnf\n'), ((4422, 4483), 'ccat.bucket.Bucket', 'bucket.Bucket', ([], {'market_id': 'market_id', 'timeframe_id': 'timeframe_id'}), '(market_id=market_id, timeframe_id=timeframe_id)\n', (4435, 4483), False, 'fro... |
from datetime import datetime
from multiprocessing import Array
from queue import Empty, Full
# except AttributeError:
# from multiprocessing import Queue
import numpy as np
# try:
from arrayqueues.portable_queue import PortableQueue # as Queue
class ArrayView:
def __init__(self, array, max_bytes, dtype, el_sh... | [
"multiprocessing.Array",
"arrayqueues.portable_queue.PortableQueue",
"numpy.floor",
"numpy.product",
"datetime.datetime.now"
] | [((1929, 1954), 'multiprocessing.Array', 'Array', (['"""c"""', 'self.maxbytes'], {}), "('c', self.maxbytes)\n", (1934, 1954), False, 'from multiprocessing import Array\n'), ((2001, 2016), 'arrayqueues.portable_queue.PortableQueue', 'PortableQueue', ([], {}), '()\n', (2014, 2016), False, 'from arrayqueues.portable_queue... |
# ------------------------------
# 460. LFU Cache
#
# Description:
# Design and implement a data structure for Least Frequently Used (LFU) cache. It should support the following operations: get and put.
# get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.... | [
"collections.OrderedDict"
] | [((1685, 1698), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (1696, 1698), False, 'from collections import OrderedDict\n'), ((2322, 2335), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (2333, 2335), False, 'from collections import OrderedDict\n')] |
import sys
from calendar import monthrange
from contextlib import contextmanager
from csv import DictReader, DictWriter
from datetime import date, datetime, timedelta, MINYEAR
from enum import Enum
from gzip import GzipFile
from importlib.resources import open_binary as open_binary_package
from io import TextIOWrapper
... | [
"weather.configuration.get_logger",
"urllib.parse.urljoin",
"weather.configuration.get_setting",
"re.compile",
"urllib.parse.urlencode",
"importlib.resources.open_binary",
"typing.NamedTuple",
"pathlib.Path",
"datetime.timedelta",
"io.TextIOWrapper",
"gzip.GzipFile",
"calendar.monthrange",
"... | [((658, 678), 'weather.configuration.get_logger', 'get_logger', (['__name__'], {}), '(__name__)\n', (668, 678), False, 'from weather.configuration import get_setting, get_logger\n'), ((2038, 2083), 'typing.NamedTuple', 'NamedTuple', (['"""_DateRange"""'], {'low': 'date', 'high': 'date'}), "('_DateRange', low=date, high... |
# jsb/plugs/core/user.py
#
#
""" users related commands. """
## jsb imports
from jsb.utils.generic import getwho
from jsb.utils.exception import handle_exception
from jsb.utils.name import stripname
from jsb.lib.users import users
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
## basic imp... | [
"logging.warn",
"jsb.lib.commands.cmnds.add",
"jsb.utils.generic.getwho",
"jsb.lib.examples.examples.add",
"jsb.utils.name.stripname"
] | [((501, 567), 'jsb.lib.commands.cmnds.add', 'cmnds.add', (['"""user-whoami"""', 'handle_whoami', "['OPER', 'USER', 'GUEST']"], {}), "('user-whoami', handle_whoami, ['OPER', 'USER', 'GUEST'])\n", (510, 567), False, 'from jsb.lib.commands import cmnds\n'), ((568, 631), 'jsb.lib.examples.examples.add', 'examples.add', (['... |
# -*- coding: utf-8 -*-
"""
Names database models
A structure for holding a (user-provided) name for an Individual.
--------------------
"""
import uuid
from app.extensions import db, HoustonModel, Timestamp
import logging
import app.extensions.logging as AuditLog
log = logging.getLogger(__name__) # pylint: disable... | [
"app.extensions.db.String",
"app.extensions.db.ForeignKey",
"app.extensions.db.relationship",
"app.extensions.db.session.add",
"app.extensions.db.backref",
"app.extensions.db.session.begin",
"app.extensions.db.UniqueConstraint",
"app.extensions.db.Column",
"app.extensions.logging.delete_object",
"... | [((274, 301), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (291, 301), False, 'import logging\n'), ((632, 695), 'app.extensions.db.relationship', 'db.relationship', (['"""Name"""'], {'back_populates': '"""preferring_user_joins"""'}), "('Name', back_populates='preferring_user_joins')\n",... |
from __future__ import division
from math import radians as rad, cos, sin
from PIL import Image, ImageDraw
from random import randint
width,height = 1280,1280
def randColour(s=0,e=255):
return (randint(s,e),randint(s,e),randint(s,e))
def drange(start, stop, step):
r = start
while r < stop:
yield ... | [
"PIL.Image.new",
"random.randint",
"math.radians",
"math.sin",
"PIL.Image.open",
"math.cos"
] | [((200, 213), 'random.randint', 'randint', (['s', 'e'], {}), '(s, e)\n', (207, 213), False, 'from random import randint\n'), ((213, 226), 'random.randint', 'randint', (['s', 'e'], {}), '(s, e)\n', (220, 226), False, 'from random import randint\n'), ((226, 239), 'random.randint', 'randint', (['s', 'e'], {}), '(s, e)\n',... |
"""
Tests for typehinting.py
"""
# -----------------------------------------------------------------------------
# IMPORTS
# -----------------------------------------------------------------------------
import pytest
from hsr4hci.typehinting import (
BaseLinearModel,
BaseLinearModelCV,
RegressorModel,
)
... | [
"hsr4hci.typehinting.BaseLinearModel",
"pytest.raises",
"hsr4hci.typehinting.RegressorModel",
"hsr4hci.typehinting.BaseLinearModelCV"
] | [((606, 630), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (619, 630), False, 'import pytest\n'), ((654, 670), 'hsr4hci.typehinting.RegressorModel', 'RegressorModel', ([], {}), '()\n', (668, 670), False, 'from hsr4hci.typehinting import BaseLinearModel, BaseLinearModelCV, RegressorModel\n'), ... |
'''
전략 : 하루의 주가를 놓고 보면 오른 경우가 42%, 내린 경우가 46%, 나머지 12%는 변동이 없다. 증명
알고리즘 : PyportfolioOpt 라이브러리 이용한 최적화
(max sharp, risk, return, fund remaining)
'''
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import FinanceDataReader as fdr
import datetime
from pykrx import stock
import requests
from pypfop... | [
"pandas.DataFrame",
"pypfopt.risk_models.sample_cov",
"pykrx.stock.get_market_fundamental_by_ticker",
"datetime.datetime.today",
"pypfopt.efficient_frontier.EfficientFrontier",
"pypfopt.discrete_allocation.get_latest_prices",
"numpy.array",
"pypfopt.expected_returns.mean_historical_return",
"pypfopt... | [((2378, 2398), 'numpy.array', 'np.array', (['symbol_udz'], {}), '(symbol_udz)\n', (2386, 2398), True, 'import numpy as np\n'), ((2454, 2468), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (2466, 2468), True, 'import pandas as pd\n'), ((2596, 2646), 'pypfopt.expected_returns.mean_historical_return', 'expected_r... |
#!/usr/bin/python
from __future__ import (absolute_import, division, print_function)
# Copyright 2019 Fortinet, Inc.
#
# 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 Lic... | [
"json.loads",
"ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios.check_legacy_fortiosapi",
"ansible.module_utils.connection.Connection",
"ansible.module_utils.basic.AnsibleModule",
"ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios.FortiOSHandler"
] | [((9973, 9998), 'ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios.check_legacy_fortiosapi', 'check_legacy_fortiosapi', ([], {}), '()\n', (9996, 9998), False, 'from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import check_legacy_fortiosapi\n'), ((10012, 10074), 'ans... |
import time
import logging
import os
import adb
from .. import app_test
from ..dummy_driver import TouchAction
logger = logging.getLogger(__name__)
IMG_TO_MV = 'IMG_1555.jpg'
ANDROID_PIC_DIR = '/sdcard/Pictures'
ANDROID_DL_DIR = '/sdcard/Download'
class App(app_test.AppTest):
def __init__(self, **kwargs):
... | [
"os.path.dirname",
"time.sleep",
"adb.shell",
"os.path.join",
"os.listdir",
"logging.getLogger"
] | [((122, 149), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (139, 149), False, 'import logging\n'), ((959, 983), 'os.listdir', 'os.listdir', (['self.res_dir'], {}), '(self.res_dir)\n', (969, 983), False, 'import os\n'), ((1070, 1138), 'adb.shell', 'adb.shell', (["['mv', ANDROID_PIC_DIR +... |
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 2.0.11
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info
if version_info >= (2,6,0):
def swig_import_helper():
from os.path impo... | [
"os.path.dirname",
"imp.load_module"
] | [((655, 718), 'imp.load_module', 'imp.load_module', (['"""_CameraMindVision"""', 'fp', 'pathname', 'description'], {}), "('_CameraMindVision', fp, pathname, description)\n", (670, 718), False, 'import imp\n'), ((459, 476), 'os.path.dirname', 'dirname', (['__file__'], {}), '(__file__)\n', (466, 476), False, 'from os.pat... |
#!/usr/bin/env python3
import libvirt
##
## vstb_launch.py
## EU INPUT
##
## Created by <NAME> on 28/10/2017
## Copyright (c) 2017 <NAME>. All rights reserved.
##
class VSTB(object):
'''
This class define, start, and then destroy and undefine the vSTB VMs
'''
def __init__(self, base_path, domain... | [
"libvirt.open"
] | [((379, 409), 'libvirt.open', 'libvirt.open', (['"""qemu:///system"""'], {}), "('qemu:///system')\n", (391, 409), False, 'import libvirt\n')] |
# pylint: disable=invalid-name,protected-access
from copy import deepcopy
from unittest import TestCase
import codecs
import gzip
import logging
import os
import shutil
from keras import backend as K
import numpy
from numpy.testing import assert_allclose
from deep_qa.common.checks import log_keras_version_info
from d... | [
"copy.deepcopy",
"gzip.open",
"os.makedirs",
"logging.basicConfig",
"codecs.open",
"numpy.testing.assert_allclose",
"numpy.zeros",
"deep_qa.common.params.Params",
"deep_qa.common.checks.log_keras_version_info",
"shutil.rmtree",
"shutil.copyfileobj",
"keras.backend.clear_session"
] | [((1030, 1143), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s - %(levelname)s - %(name)s - %(message)s"""', 'level': 'logging.DEBUG'}), "(format=\n '%(asctime)s - %(levelname)s - %(name)s - %(message)s', level=logging.DEBUG\n )\n", (1049, 1143), False, 'import logging\n'), ((1170, ... |
# Copyright (c) 2015 <NAME>
# See the file LICENSE for copying permission.
# This object is intended to run from script bassist.py
import logging
import logging.config
import argparse
import ConfigParser
from ..parser import host as parser_host
from ..flavor import directory as flavor_directory
class Script(object):
... | [
"argparse.ArgumentParser",
"logging.basicConfig",
"logging.config.dictConfig",
"logging.config.fileConfig",
"logging.getLogger"
] | [((911, 938), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (928, 938), False, 'import logging\n'), ((1201, 1254), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': 'self.description'}), '(description=self.description)\n', (1224, 1254), False, 'import argparse\n'... |