code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import os
import keyboard
import time
from time import sleep
from picamera import PiCamera
# import RPi.GPIO as GPIO
# camera = PiCamera()
# def setup_mortor():
def p3():
cut_num = 50
dir_name = "./P3"
if os.path.isdir(dir_name) == False:
os.mkdir(dir_name)
pill = input("Enter the number of ... | [
"keyboard.read_key",
"os.path.isdir",
"os.mkdir",
"picamera.PiCamera"
] | [((989, 999), 'picamera.PiCamera', 'PiCamera', ([], {}), '()\n', (997, 999), False, 'from picamera import PiCamera\n'), ((220, 243), 'os.path.isdir', 'os.path.isdir', (['dir_name'], {}), '(dir_name)\n', (233, 243), False, 'import os\n'), ((262, 280), 'os.mkdir', 'os.mkdir', (['dir_name'], {}), '(dir_name)\n', (270, 280... |
from __future__ import print_function
import click
from click.testing import CliRunner
from kcleaner import cli
runner = CliRunner()
| [
"click.testing.CliRunner"
] | [((123, 134), 'click.testing.CliRunner', 'CliRunner', ([], {}), '()\n', (132, 134), False, 'from click.testing import CliRunner\n')] |
from crypt import mksalt
from datetime import datetime, timedelta
from typing import List, Optional
from arrow.arrow import Arrow
from fastapi.encoders import jsonable_encoder
import sqlalchemy
from sqlalchemy import or_
from sqlalchemy.orm import Session
from sqlalchemy.sql.functions import func
from app import crud... | [
"crypt.mksalt",
"sqlalchemy.sql.functions.func.now",
"app.logger.logger.info",
"app.crud.user.is_superuser",
"datetime.datetime.now",
"app.models.domain.Domain.salt.is_",
"app.models.domain.Domain.delete_at.is_",
"arrow.arrow.Arrow.now",
"datetime.timedelta",
"fastapi.encoders.jsonable_encoder"
] | [((794, 818), 'fastapi.encoders.jsonable_encoder', 'jsonable_encoder', (['obj_in'], {}), '(obj_in)\n', (810, 818), False, 'from fastapi.encoders import jsonable_encoder\n'), ((2895, 2940), 'app.logger.logger.info', 'logger.info', (['"""Updated salt for %d domains"""', 'i'], {}), "('Updated salt for %d domains', i)\n", ... |
import pygame
from gameplay import Gameplay
pygame.init()
gameplay = Gameplay()
loop = True
while loop:
for e in pygame.event.get():
if e.type == pygame.QUIT:
loop = False
pygame.display.set_caption("Connect Four By MrGio7")
gameplay.gameplay()
gameplay.score_check()
... | [
"gameplay.Gameplay",
"pygame.init",
"pygame.event.get",
"pygame.display.set_caption",
"pygame.display.update"
] | [((45, 58), 'pygame.init', 'pygame.init', ([], {}), '()\n', (56, 58), False, 'import pygame\n'), ((71, 81), 'gameplay.Gameplay', 'Gameplay', ([], {}), '()\n', (79, 81), False, 'from gameplay import Gameplay\n'), ((120, 138), 'pygame.event.get', 'pygame.event.get', ([], {}), '()\n', (136, 138), False, 'import pygame\n')... |
import sys
import os
pattern = sys.argv[1]
print(pattern)
def get_result_line(i, pattern):
filename = pattern.format(i)
if os.path.exists(filename):
lines = open(filename, 'r').readlines()[-3:]
return str(i) + "\t" + '\t'.join([line.split(':')[1].strip() for line in lines])
return None
re... | [
"os.path.exists"
] | [((133, 157), 'os.path.exists', 'os.path.exists', (['filename'], {}), '(filename)\n', (147, 157), False, 'import os\n')] |
"""
Visualization script that takes logs and plots the fitness of generations in
a given simulation
"""
import time
import seaborn
import json
import pandas as pd
import numpy as np
import scipy.signal as signal
import matplotlib.pyplot as plt
seaborn.set()
def graph(log_location):
df = pd.read_csv(log_locatio... | [
"seaborn.set",
"json.loads",
"pandas.read_csv",
"matplotlib.pyplot.ylabel",
"argparse.ArgumentParser",
"scipy.signal.filtfilt",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"scipy.signal.butter",
"matplotlib.pyplot.show"
] | [((247, 260), 'seaborn.set', 'seaborn.set', ([], {}), '()\n', (258, 260), False, 'import seaborn\n'), ((297, 335), 'pandas.read_csv', 'pd.read_csv', (['log_location'], {'header': 'None'}), '(log_location, header=None)\n', (308, 335), True, 'import pandas as pd\n'), ((381, 403), 'scipy.signal.butter', 'signal.butter', (... |
#!/usr/bin/python3
# -*- coding: utf8 -*-
# Copyright (c) 2020 Baidu, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE... | [
"QCompute.QProtobuf.PBRotationGate.Value",
"QCompute.QProtobuf.PBMeasure.Type.Value",
"QCompute.QProtobuf.PBFixedGate.Value",
"QCompute.QProtobuf.PBCompositeGate.Value",
"QCompute.QProtobuf.PBCircuitLine",
"QCompute.QPlatform.Error.ArgumentError"
] | [((2521, 2536), 'QCompute.QProtobuf.PBCircuitLine', 'PBCircuitLine', ([], {}), '()\n', (2534, 2536), False, 'from QCompute.QProtobuf import PBProgram, PBCircuitLine, PBFixedGate, PBRotationGate, PBCompositeGate, PBMeasure\n'), ((5339, 5354), 'QCompute.QProtobuf.PBCircuitLine', 'PBCircuitLine', ([], {}), '()\n', (5352, ... |
# -*- coding: utf-8 -*-
import os
from qiniu import Auth, http, urlsafe_base64_encode
access_key = os.getenv('QINIU_ACCESS_KEY')
secret_key = os.getenv('QINIU_SECRET_KEY')
q = Auth(access_key, secret_key)
bucket_name = 'tmp-1811282'
region = 'z0'
url = 'http://rs.qiniu.com/mkbucketv2/' + urlsafe_base64_encode(buck... | [
"qiniu.Auth",
"qiniu.http._post_with_auth",
"os.getenv",
"qiniu.urlsafe_base64_encode"
] | [((102, 131), 'os.getenv', 'os.getenv', (['"""QINIU_ACCESS_KEY"""'], {}), "('QINIU_ACCESS_KEY')\n", (111, 131), False, 'import os\n'), ((145, 174), 'os.getenv', 'os.getenv', (['"""QINIU_SECRET_KEY"""'], {}), "('QINIU_SECRET_KEY')\n", (154, 174), False, 'import os\n'), ((180, 208), 'qiniu.Auth', 'Auth', (['access_key', ... |
from typing import Any, Dict
from os.path import join
import os
from analyzer.src.statistics import Tests
from analyzer.src.experiments import Experiment
from analyzer.src.utils import get_analyzer_res_path, load_json_file, to_camel_case
from analyzer.src.features import Features
from analyzer.src.metrics import Metri... | [
"analyzer.src.experiments.Experiment.as_list",
"analyzer.src.utils.get_analyzer_res_path",
"os.makedirs",
"os.path.join",
"analyzer.src.features.Features.as_list",
"analyzer.src.statistics.Tests.as_list",
"analyzer.src.metrics.Metric.as_list",
"analyzer.src.utils.to_camel_case",
"analyzer.scripts.co... | [((3441, 3464), 'analyzer.scripts.correction.bonferroni_correction', 'bonferroni_correction', ([], {}), '()\n', (3462, 3464), False, 'from analyzer.scripts.correction import bonferroni_correction\n'), ((625, 645), 'analyzer.src.experiments.Experiment.as_list', 'Experiment.as_list', ([], {}), '()\n', (643, 645), False, ... |
#
# 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 ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | [
"airflow.utils.timezone.utcnow",
"airflow.providers.microsoft.azure.operators.adx.AzureDataExplorerQueryOperator",
"unittest.mock.patch.object",
"airflow.models.DAG",
"airflow.utils.timezone.datetime"
] | [((1169, 1189), 'airflow.utils.timezone.datetime', 'datetime', (['(2019)', '(1)', '(1)'], {}), '(2019, 1, 1)\n', (1177, 1189), False, 'from airflow.utils.timezone import datetime\n'), ((2591, 2643), 'unittest.mock.patch.object', 'mock.patch.object', (['AzureDataExplorerHook', '"""get_conn"""'], {}), "(AzureDataExplorer... |
#coding:utf-8
#
# id: bugs.core_6314
# title: Assigning RDB$DB_KEY to MBCS CHAR/VARCHAR does not enforce the target limit
# decription:
# In order to prevent receiving non-ascii characters in output we try to get only octet_length of this.
# Confirmed bug on 3.0.6.3... | [
"pytest.mark.version",
"firebird.qa.db_factory",
"firebird.qa.isql_act"
] | [((719, 764), 'firebird.qa.db_factory', 'db_factory', ([], {'sql_dialect': '(3)', 'init': 'init_script_1'}), '(sql_dialect=3, init=init_script_1)\n', (729, 764), False, 'from firebird.qa import db_factory, isql_act, Action\n'), ((957, 1019), 'firebird.qa.isql_act', 'isql_act', (['"""db_1"""', 'test_script_1'], {'substi... |
from django.contrib import admin
from django.contrib.staticfiles import views
try:
from django.urls import re_path, include
except ImportError:
from django.conf.urls import url as re_path, include
admin.autodiscover()
urlpatterns = [
re_path(r'^admin/', admin.site.urls),
re_path(r'^package_monitor/', ... | [
"django.conf.urls.include",
"django.conf.urls.url",
"django.contrib.admin.autodiscover"
] | [((206, 226), 'django.contrib.admin.autodiscover', 'admin.autodiscover', ([], {}), '()\n', (224, 226), False, 'from django.contrib import admin\n'), ((248, 283), 'django.conf.urls.url', 're_path', (['"""^admin/"""', 'admin.site.urls'], {}), "('^admin/', admin.site.urls)\n", (255, 283), True, 'from django.conf.urls impo... |
import pandas as pd
import os
def prepare_legends(mean_models, models, interpretability_name):
bars = []
y_pos = []
index_bars = 0
for nb, i in enumerate(mean_models):
if nb % len(models) == int(len(models)/2):
bars.append(interpretability_name[index_bars])
index_bars +=... | [
"pandas.DataFrame",
"os.path.dirname"
] | [((2922, 2962), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': 'columns_name_file1'}), '(columns=columns_name_file1)\n', (2934, 2962), True, 'import pandas as pd\n'), ((3001, 3041), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': 'columns_name_file2'}), '(columns=columns_name_file2)\n', (3013, 3041), True, '... |
import h5py
import os
import re
class H5Explorer(object):
def __init__(self, h5_obj):
self.__filename = h5_obj.file.filename
self.__file = h5_obj
self.__working_dir = h5_obj.name
self.__dir_queue = list()
@staticmethod
def from_file(filename, mode="r"):
filename = ... | [
"os.path.normpath",
"os.path.expanduser",
"h5py.File"
] | [((320, 348), 'os.path.expanduser', 'os.path.expanduser', (['filename'], {}), '(filename)\n', (338, 348), False, 'import os\n'), ((367, 392), 'h5py.File', 'h5py.File', (['filename', 'mode'], {}), '(filename, mode)\n', (376, 392), False, 'import h5py\n'), ((681, 703), 'os.path.normpath', 'os.path.normpath', (['path'], {... |
########################################################################################################################
"""
Inspired by http://usingpython.com/programs/ 'Crafting Challenge' Game
Created by SimplyNate
Coding Module - Python Lab
Craft the items indicated in the Quests panel to win the game.
Hunger tick... | [
"base64.b64decode",
"tkinter.ttk.Progressbar",
"tkinter.ttk.Style"
] | [((5242, 5253), 'tkinter.ttk.Style', 'ttk.Style', ([], {}), '()\n', (5251, 5253), False, 'from tkinter import ttk\n'), ((8814, 8890), 'tkinter.ttk.Progressbar', 'ttk.Progressbar', (['master'], {'orient': '"""horizontal"""', 'length': '(200)', 'mode': '"""determinate"""'}), "(master, orient='horizontal', length=200, mod... |
import sys
import binascii
filename = sys.argv[1]
output = sys.argv[2]
with open(filename, 'rb') as file:
content = file.read()
hexData = binascii.hexlify(content)
hexList = list(''.join(map(chr, hexData)))
caCertLen = 0
hexOutput = ' '
x = len(hexList)
for i in range(0, (x-1), 2):
first = hexList[i]
... | [
"binascii.hexlify"
] | [((145, 170), 'binascii.hexlify', 'binascii.hexlify', (['content'], {}), '(content)\n', (161, 170), False, 'import binascii\n')] |
# -*- coding: utf-8 -*-
"""Markdown Subscript Extension
Extends the Python-Markdown library to support subscript text.
Given the text:
The molecular composition of water is H~2~O.
Will output:
<p>The molecular composition of water is H<sub>2</sub>O.</p>
:website: https://github.com/jambonrose/markdown_subscr... | [
"markdown.inlinepatterns.SimpleTagPattern"
] | [((1103, 1140), 'markdown.inlinepatterns.SimpleTagPattern', 'SimpleTagPattern', (['SUBSCRIPT_RE', '"""sub"""'], {}), "(SUBSCRIPT_RE, 'sub')\n", (1119, 1140), False, 'from markdown.inlinepatterns import SimpleTagPattern\n')] |
# -*- coding: utf-8 -*-
from django.test import TestCase
import json
from plogical.CyberCPLogFileWriter import CyberCPLogFileWriter as logging
import requests
import time
from plogical.processUtilities import ProcessUtilities
import urllib3
urllib3.disable_warnings()
# Create your tests here.
class TestWebsiteManagem... | [
"os.path.exists",
"json.loads",
"requests.Session",
"json.dumps",
"plogical.CyberCPLogFileWriter.CyberCPLogFileWriter.writeToFile",
"requests.get",
"time.sleep",
"plogical.processUtilities.ProcessUtilities.decideDistro",
"urllib3.disable_warnings",
"plogical.processUtilities.ProcessUtilities.norma... | [((241, 267), 'urllib3.disable_warnings', 'urllib3.disable_warnings', ([], {}), '()\n', (265, 267), False, 'import urllib3\n'), ((352, 370), 'requests.Session', 'requests.Session', ([], {}), '()\n', (368, 370), False, 'import requests\n'), ((435, 451), 'json.dumps', 'json.dumps', (['data'], {}), '(data)\n', (445, 451),... |
# -*- coding: utf-8 -*-
from django.http import Http404, HttpResponse
from django.template import loader, Context
from django.db.models import Q
from django.contrib.auth.decorators import login_required
from symposion.speakers.models import Speaker
from symposion.teams.models import Membership
from symposion.sponsors... | [
"django.http.HttpResponse",
"symposion.teams.models.Membership.objects.filter",
"symposion.sponsorship.models.Sponsor.objects.exclude",
"django.template.Context",
"django.db.models.Q",
"django.template.loader.get_template",
"django.http.Http404"
] | [((2212, 2245), 'django.http.HttpResponse', 'HttpResponse', ([], {'mimetype': '"""text/csv"""'}), "(mimetype='text/csv')\n", (2224, 2245), False, 'from django.http import Http404, HttpResponse\n'), ((442, 451), 'django.http.Http404', 'Http404', ([], {}), '()\n', (449, 451), False, 'from django.http import Http404, Http... |
# https://github.com/Womsxd/YuanShen_User_Info
import os
import re
import sys
import json
import time
import string
import random
import hashlib
import requests
from settings import *
def md5(text):
md5 = hashlib.md5()
md5.update(text.encode())
return md5.hexdigest()
# Github-@lulu666lulu https://github... | [
"json.loads",
"hashlib.md5",
"time.sleep",
"os.remove",
"sys.exit",
"re.sub",
"time.time",
"random.randint",
"re.search"
] | [((212, 225), 'hashlib.md5', 'hashlib.md5', ([], {}), '()\n', (223, 225), False, 'import hashlib\n'), ((4115, 4135), 'json.loads', 'json.loads', (['JsonText'], {}), '(JsonText)\n', (4125, 4135), False, 'import json\n'), ((10770, 10798), 'random.randint', 'random.randint', (['(1)', 'maxSecond'], {}), '(1, maxSecond)\n',... |
import numpy as np
# projection mask of NYUv2
PMASK = np.zeros([480, 640], dtype=np.float64)
PMASK[44:471, 40:601] = 1.0
# sorted names
METRIC_NAMES = [
'RMSE',
'Mean RMSE',
'Mean Log10',
'Abs Rel Diff',
'Squa Rel Diff',
'delta < 1.25',
'delta < 1.25^2',
'delta < 1.25^3',
]
def get_m... | [
"numpy.mean",
"numpy.abs",
"numpy.log10",
"numpy.sqrt",
"numpy.float64",
"numpy.square",
"numpy.sum",
"numpy.zeros",
"numpy.stack",
"numpy.maximum"
] | [((55, 93), 'numpy.zeros', 'np.zeros', (['[480, 640]'], {'dtype': 'np.float64'}), '([480, 640], dtype=np.float64)\n', (63, 93), True, 'import numpy as np\n'), ((1437, 1463), 'numpy.sum', 'np.sum', (['masks'], {'axis': '(1, 2)'}), '(masks, axis=(1, 2))\n', (1443, 1463), True, 'import numpy as np\n'), ((1576, 1588), 'num... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import unittest
from numpy.testing import assert_almost_equal
from theanolm.commands.score import _merge_subwords
class TestScore(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_merge_subwords(self):
# w... | [
"unittest.main",
"numpy.testing.assert_almost_equal",
"theanolm.commands.score._merge_subwords"
] | [((2833, 2848), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2846, 2848), False, 'import unittest\n'), ((482, 531), 'theanolm.commands.score._merge_subwords', '_merge_subwords', (['subwords', 'subword_logprobs', 'None'], {}), '(subwords, subword_logprobs, None)\n', (497, 531), False, 'from theanolm.commands.sco... |
import time
from math import ceil
from selenium import webdriver
from selenium.common.exceptions import NoAlertPresentException, TimeoutException
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.su... | [
"math.ceil",
"lztools.web.ElementVisibilityTimeout",
"selenium.webdriver.support.wait.WebDriverWait",
"lztools.web.HTMLElement",
"selenium.webdriver.support.expected_conditions.alert_is_present",
"lztools.web.LocatorCollection",
"time.sleep",
"selenium.webdriver.support.expected_conditions.staleness_o... | [((503, 522), 'lztools.web.LocatorCollection', 'LocatorCollection', ([], {}), '()\n', (520, 522), False, 'from lztools.web import Driver, LocatorCollection, ElementVisibilityTimeout, HTMLElementList, HTMLElement\n'), ((542, 570), 'lztools.web.Locator', 'Locator', (['"""body"""', 'By.TAG_NAME'], {}), "('body', By.TAG_NA... |
import math
import copy
import numpy as np
import torch.nn as nn
import torch
import torch.nn.functional as F
from torch.nn import CrossEntropyLoss
from transformers import RobertaTokenizer, RobertaModel, BertModel, BertForMaskedLM, BertConfig, RobertaForMaskedLM
MAX_LENGTH = 512
class CrossEntropy(nn.Module):
... | [
"transformers.BertForMaskedLM.from_pretrained",
"torch.nn.Dropout",
"torch.nn.Tanh",
"torch.nn.MSELoss",
"torch.sum",
"torch.nn.functional.softmax",
"torch.nn.GRU",
"torch.mean",
"torch.nn.LSTM",
"torch.zeros_like",
"torch.nn.utils.rnn.pad_packed_sequence",
"transformers.RobertaForMaskedLM.fro... | [((618, 639), 'torch.nn.LogSoftmax', 'nn.LogSoftmax', ([], {'dim': '(-1)'}), '(dim=-1)\n', (631, 639), True, 'import torch.nn as nn\n'), ((748, 760), 'torch.nn.MSELoss', 'nn.MSELoss', ([], {}), '()\n', (758, 760), True, 'import torch.nn as nn\n'), ((2610, 2636), 'torch.nn.functional.softmax', 'F.softmax', (['p_logit'],... |
# Generated by Django 3.0 on 2019-12-25 08:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('graduated_site', '0045_auto_20191222_1917'),
]
operations = [
migrations.AddField(
model_name='user_internship_post',
... | [
"django.db.models.CharField"
] | [((364, 573), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'choices': "[(None, 'Lütfen Staj Dönemini Seçiniz'), ('YAZ', 'YAZ'), ('BAHAR', 'BAHAR'),\n ('KIŞ', 'KIŞ'), ('GÜZ', 'GÜZ')]", 'max_length': '(25)', 'null': '(True)', 'verbose_name': '"""Staj Dönemi"""'}), "(blank=True, choices=[(... |
"""
Copyright 2016 <NAME> <<EMAIL>>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Red... | [
"xml.etree.ElementTree.tostring"
] | [((3491, 3558), 'xml.etree.ElementTree.tostring', 'ElementTree.tostring', (['self.__root'], {'encoding': '"""unicode"""', 'method': '"""xml"""'}), "(self.__root, encoding='unicode', method='xml')\n", (3511, 3558), False, 'from xml.etree import ElementTree\n'), ((3851, 3910), 'xml.etree.ElementTree.tostring', 'ElementTr... |
# Copyright 2020 Softwerks LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | [
"logging.getLogger",
"joust.redis.get_connection"
] | [((778, 805), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (795, 805), False, 'import logging\n'), ((1738, 1760), 'joust.redis.get_connection', 'redis.get_connection', ([], {}), '()\n', (1758, 1760), False, 'from joust import redis\n')] |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-11-02 09:53
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Auctio... | [
"django.db.models.FloatField",
"django.db.models.TextField",
"django.db.models.BooleanField",
"django.db.models.AutoField",
"django.db.models.PositiveIntegerField",
"django.db.models.DateTimeField",
"django.db.models.CharField"
] | [((368, 461), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (384, 461), False, 'from django.db import migrations, models\... |
import torch
import torch.nn as nn
from loss_functions import AngularPenaltySMLoss
class Stem_layer(nn.Module):
def __init__(self, in_ch, out_ch, kernel_size, drop_rate, pool_size):
super().__init__()
dilation = 1
self.conv = nn.Conv1d(
in_ch,
out_ch,
ke... | [
"torch.nn.MaxPool1d",
"torch.nn.Sigmoid",
"torch.nn.ReLU",
"torch.nn.Dropout",
"torch.mul",
"torch.nn.Tanh",
"torch.nn.Sequential",
"torch.mean",
"torch.nn.BatchNorm1d",
"torch.nn.Upsample",
"torch.nn.Linear",
"torch.nn.Conv1d"
] | [((517, 539), 'torch.nn.BatchNorm1d', 'nn.BatchNorm1d', (['out_ch'], {}), '(out_ch)\n', (531, 539), True, 'import torch.nn as nn\n'), ((560, 569), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (567, 569), True, 'import torch.nn as nn\n'), ((593, 638), 'torch.nn.MaxPool1d', 'nn.MaxPool1d', ([], {'kernel_size': 'pool_siz... |
# LCD via i2c driver for MicroPython (on ESP8266)
# Copyright (c) 2016 Dries007
# License: MIT
#
# Only tested with PCF8574T and a 16*2 LCD
import time
_BIT0 = const(1 << 0)
_BIT1 = const(1 << 1)
_BIT2 = const(1 << 2)
_BIT3 = const(1 << 3)
_BIT4 = const(1 << 4)
_BIT5 = const(1 << 5)
_BIT6 = const(1 << 6)
_BIT7 = cons... | [
"time.sleep"
] | [((1184, 1200), 'time.sleep', 'time.sleep', (['(0.01)'], {}), '(0.01)\n', (1194, 1200), False, 'import time\n'), ((1265, 1281), 'time.sleep', 'time.sleep', (['(0.01)'], {}), '(0.01)\n', (1275, 1281), False, 'import time\n'), ((2060, 2078), 'time.sleep', 'time.sleep', (['(0.0001)'], {}), '(0.0001)\n', (2070, 2078), Fals... |
from __future__ import unicode_literals
from django.contrib import admin
from subscription.models import Subscription
class SubscriptionAdmin(admin.ModelAdmin):
list_display = ["brand", "user"]
search_fields = ["user"]
admin.site.register(Subscription, SubscriptionAdmin)
| [
"django.contrib.admin.site.register"
] | [((234, 286), 'django.contrib.admin.site.register', 'admin.site.register', (['Subscription', 'SubscriptionAdmin'], {}), '(Subscription, SubscriptionAdmin)\n', (253, 286), False, 'from django.contrib import admin\n')] |
# seno cosseno e tangente
from math import radians, sin, cos, tan
an = float(input('Digite o ângulo que você deseja: '))
seno = sin(radians(an))
cosseno = cos(radians(an))
tangente = tan(radians(an))
print('O ângulo de {} tem o SENO de {:.2f}, COSSENO de {:.2f} e TANGENTE de {:.2f}'.format(an, seno, cosseno, tangente))... | [
"math.radians"
] | [((132, 143), 'math.radians', 'radians', (['an'], {}), '(an)\n', (139, 143), False, 'from math import radians, sin, cos, tan\n'), ((159, 170), 'math.radians', 'radians', (['an'], {}), '(an)\n', (166, 170), False, 'from math import radians, sin, cos, tan\n'), ((187, 198), 'math.radians', 'radians', (['an'], {}), '(an)\n... |
import unittest
from api.color import color, color_o
class test_color(unittest.TestCase):
def assertAlmostEqual(self, a, b):
if isinstance(a, color):
unittest.TestCase.assertAlmostEqual(self, a.r, b.r)
unittest.TestCase.assertAlmostEqual(self, a.g, b.g)
unittest.TestCas... | [
"api.color.color",
"unittest.TestCase.assertAlmostEqual"
] | [((530, 547), 'api.color.color', 'color', (['(1)', '(2)', '(3)', '(4)'], {}), '(1, 2, 3, 4)\n', (535, 547), False, 'from api.color import color, color_o\n'), ((557, 574), 'api.color.color', 'color', (['(1)', '(2)', '(3)', '(4)'], {}), '(1, 2, 3, 4)\n', (562, 574), False, 'from api.color import color, color_o\n'), ((584... |
from kubespawner.reflector import NamespacedResourceReflector
from kubespawner.spawner import PodReflector, EventReflector
from kubernetes import watch
from urllib3.exceptions import ReadTimeoutError
from functools import partial
import json
import threading
import time
class MultiNamespaceReflector(NamespacedResourc... | [
"threading.Thread",
"time.monotonic",
"time.sleep",
"kubernetes.watch.Watch"
] | [((7502, 7549), 'threading.Thread', 'threading.Thread', ([], {'target': 'self._watch_and_update'}), '(target=self._watch_and_update)\n', (7518, 7549), False, 'import threading\n'), ((2978, 2994), 'time.monotonic', 'time.monotonic', ([], {}), '()\n', (2992, 2994), False, 'import time\n'), ((3011, 3024), 'kubernetes.watc... |
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from scrapy.selector import HtmlXPathSelector
from ..items import NewsItem
from datetime import datetime
import pandas as pd
import re
class YenisafakSpider(CrawlSpider):
name = "yenisafak"
allowed_domains = ["yenisaf... | [
"re.sub",
"scrapy.linkextractors.LinkExtractor",
"scrapy.selector.HtmlXPathSelector"
] | [((821, 848), 'scrapy.selector.HtmlXPathSelector', 'HtmlXPathSelector', (['response'], {}), '(response)\n', (838, 848), False, 'from scrapy.selector import HtmlXPathSelector\n'), ((1954, 1984), 're.sub', 're.sub', (['"""\n"""', '""" """', 'new_content'], {}), "('\\n', ' ', new_content)\n", (1960, 1984), False, 'import ... |
import pytest
from testfixtures import LogCapture
@pytest.fixture(autouse=True)
def log_capture():
with LogCapture() as capture:
yield capture
| [
"pytest.fixture",
"testfixtures.LogCapture"
] | [((53, 81), 'pytest.fixture', 'pytest.fixture', ([], {'autouse': '(True)'}), '(autouse=True)\n', (67, 81), False, 'import pytest\n'), ((110, 122), 'testfixtures.LogCapture', 'LogCapture', ([], {}), '()\n', (120, 122), False, 'from testfixtures import LogCapture\n')] |
# Generated by Django 2.2.6 on 2020-02-02 23:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('account', '0037_auto_20200131_1640'),
]
operations = [
migrations.AddField(
model_name='address',
name='pinyin',
... | [
"django.db.models.TextField"
] | [((335, 403), 'django.db.models.TextField', 'models.TextField', ([], {'blank': '(True)', 'max_length': '(1024)', 'verbose_name': '"""pinyin"""'}), "(blank=True, max_length=1024, verbose_name='pinyin')\n", (351, 403), False, 'from django.db import migrations, models\n')] |
#!/usr/bin/python
# $Id:$
import ctypes
import pyglet
from pyglet.window.win32 import _user32
from pyglet.window.win32.constants import *
from pyglet.window.win32.types import *
WCHAR = ctypes.c_wchar
BCHAR = ctypes.c_wchar
class MONITORINFOEX(ctypes.Structure):
_fields_ = (
('cbSize', DW... | [
"ctypes.byref",
"pyglet.app.run",
"pyglet.window.get_platform",
"pyglet.window.Window",
"ctypes.sizeof"
] | [((3969, 3991), 'pyglet.window.Window', 'pyglet.window.Window', ([], {}), '()\n', (3989, 3991), False, 'import pyglet\n'), ((4025, 4041), 'pyglet.app.run', 'pyglet.app.run', ([], {}), '()\n', (4039, 4041), False, 'import pyglet\n'), ((2308, 2336), 'ctypes.sizeof', 'ctypes.sizeof', (['MONITORINFOEX'], {}), '(MONITORINFO... |
import random
import string
import logging
from crawlino import generator_plugin, CrawlinoValueError
log = logging.getLogger("crawlino-plugin")
@generator_plugin
def generator_random(*args, **kwargs):
"""
Input parameters:
arg[0]: generated type: string, number
arg[1]: generated value len
arg[2... | [
"logging.getLogger",
"random.choice",
"crawlino.CrawlinoValueError"
] | [((109, 145), 'logging.getLogger', 'logging.getLogger', (['"""crawlino-plugin"""'], {}), "('crawlino-plugin')\n", (126, 145), False, 'import logging\n'), ((540, 607), 'crawlino.CrawlinoValueError', 'CrawlinoValueError', (['f"""Total generated values must be bigger than 0"""'], {}), "(f'Total generated values must be bi... |
"""
Twin-delayed DDPG
"""
import numpy as np
import tensorflow as tf
from utils.logx import EpochLogger
from utils.tf_utils import set_tf_allow_growth
set_tf_allow_growth()
import gym
import time
from tqdm.auto import tqdm
def hard_update(target: tf.keras.Model, source: tf.keras.Model):
target.set_weights(sour... | [
"tensorflow.shape",
"tensorflow.tanh",
"tensorflow.reduce_sum",
"tensorflow.GradientTape",
"tensorflow.keras.layers.Dense",
"tensorflow.reduce_mean",
"gym.make",
"tensorflow.reduce_min",
"numpy.isscalar",
"argparse.ArgumentParser",
"tensorflow.keras.Sequential",
"tensorflow.concat",
"numpy.r... | [((154, 175), 'utils.tf_utils.set_tf_allow_growth', 'set_tf_allow_growth', ([], {}), '()\n', (173, 175), False, 'from utils.tf_utils import set_tf_allow_growth\n'), ((926, 967), 'tensorflow.where', 'tf.where', (['cond', 'squared_loss', 'linear_loss'], {}), '(cond, squared_loss, linear_loss)\n', (934, 967), True, 'impor... |
# author: <NAME>
#
# Program to preprocess Twitter text data and create 'blob files' that contain
# only the text.
#
# STD LIB
import re
import os
import csv
import sys
import time
import string
import pathlib
# EXTERNAL LIB
# PROJECT LIB
from extern import *
# CONSTANTS
TIME_FORMAT = '%H:%M:%S'
def cleanse(target... | [
"csv.writer",
"os.path.isdir",
"os.mkdir",
"re.sub",
"csv.reader"
] | [((436, 459), 'os.path.isdir', 'os.path.isdir', (['DATA_DIR'], {}), '(DATA_DIR)\n', (449, 459), False, 'import os\n'), ((469, 487), 'os.mkdir', 'os.mkdir', (['DATA_DIR'], {}), '(DATA_DIR)\n', (477, 487), False, 'import os\n'), ((688, 708), 'csv.reader', 'csv.reader', (['src_file'], {}), '(src_file)\n', (698, 708), Fals... |
from netCDF4 import Dataset
from numpy import *
import os
import sys
from scipy.interpolate import NearestNDInterpolator, RegularGridInterpolator
sose_path = os.path.join(os.environ['projdir'],'data','preprocessing','external','sose')
sys.path.append(sose_path)
from mds import *
import scipy.io as sio
run = 'waom2'
#... | [
"scipy.interpolate.RegularGridInterpolator",
"scipy.io.loadmat",
"netCDF4.Dataset",
"os.path.join",
"scipy.interpolate.NearestNDInterpolator",
"sys.path.append"
] | [((159, 244), 'os.path.join', 'os.path.join', (["os.environ['projdir']", '"""data"""', '"""preprocessing"""', '"""external"""', '"""sose"""'], {}), "(os.environ['projdir'], 'data', 'preprocessing', 'external', 'sose'\n )\n", (171, 244), False, 'import os\n'), ((236, 262), 'sys.path.append', 'sys.path.append', (['sos... |
#
# Copyright (C) 2019 Authlete, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | [
"authlete.django.web.response_utility.ResponseUtility.okJson"
] | [((2493, 2520), 'authlete.django.web.response_utility.ResponseUtility.okJson', 'ResponseUtility.okJson', (['jsn'], {}), '(jsn)\n', (2515, 2520), False, 'from authlete.django.web.response_utility import ResponseUtility\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Author : Joshua
@Time : 2020/6/30 6:09 下午
@File : get_spot_check_data_from_kafka.py
@Desc : 从kafka队列获取谛听标注数据
"""
import kafka_handler
import time
# kafka.
kafka_user = "recommend_online"
kafka_password = "<PASSWORD>=="
kakfa_servers = "moli-kafka.prd.<EMAI... | [
"time.localtime",
"kafka_handler.Consumer"
] | [((434, 529), 'kafka_handler.Consumer', 'kafka_handler.Consumer', (['kakfa_servers', 'kafka_user', 'kafka_password', 'kafka_topic', 'kafka_group'], {}), '(kakfa_servers, kafka_user, kafka_password,\n kafka_topic, kafka_group)\n', (456, 529), False, 'import kafka_handler\n'), ((628, 644), 'time.localtime', 'time.loca... |
"""
Module allows the grabbing of dose rate factors for the calculation of radiotoxicity. There are four dose rates provided:
1. external from air (mrem/h per Ci/m^3)
Table includes: nuclide, air dose rate factor, ratio to inhalation dose (All EPA values)
2. external from 15 cm of soil (mrem/h per Ci/m^2)
T... | [
"os.path.exists",
"pyne.nucname.id",
"tables.open_file",
"numpy.array",
"os.path.dirname",
"numpy.dtype",
"csv.reader"
] | [((2144, 2162), 'pyne.nucname.id', 'nucname.id', (['row[0]'], {}), '(row[0])\n', (2154, 2162), False, 'from pyne import nucname\n'), ((5826, 6020), 'numpy.dtype', 'np.dtype', (["[('nuc', int), ('ext_air_dose', float), ('ratio', float), ('ext_soil_dose',\n float), ('ingest_dose', float), ('fluid_frac', float), ('inha... |
"""Provide common pytest fixtures for kraken tests."""
from unittest.mock import patch
import pytest
@pytest.fixture(autouse=True)
def mock_call_rate_limit_sleep():
"""Patch the call rate limit sleep time."""
with patch("homeassistant.components.kraken.CALL_RATE_LIMIT_SLEEP", new=0):
yield
| [
"pytest.fixture",
"unittest.mock.patch"
] | [((105, 133), 'pytest.fixture', 'pytest.fixture', ([], {'autouse': '(True)'}), '(autouse=True)\n', (119, 133), False, 'import pytest\n'), ((225, 294), 'unittest.mock.patch', 'patch', (['"""homeassistant.components.kraken.CALL_RATE_LIMIT_SLEEP"""'], {'new': '(0)'}), "('homeassistant.components.kraken.CALL_RATE_LIMIT_SLE... |
from otp.chat.WhiteList import WhiteList
from toontown.toonbase import TTLocalizer
from toontown.chat import WhiteListData
class TTWhiteList(WhiteList):
notify = directNotify.newCategory('TTWhiteList')
def __init__(self):
WhiteList.__init__(self, WhiteListData.WHITELIST)
self.defaultWord = T... | [
"otp.chat.WhiteList.WhiteList.__init__"
] | [((241, 290), 'otp.chat.WhiteList.WhiteList.__init__', 'WhiteList.__init__', (['self', 'WhiteListData.WHITELIST'], {}), '(self, WhiteListData.WHITELIST)\n', (259, 290), False, 'from otp.chat.WhiteList import WhiteList\n')] |
from ichubOpenApi import const
from ichubOpenApi.request.requestBase import requestBase
from ichubOpenApi.request.models import Method
import json
class Client:
def __init__(self, host=None, v='1.0.0', app_id='', sign_type='', key='', public_key='', private_key=''):
self.request = requestBase(host=host, v... | [
"json.dumps",
"ichubOpenApi.request.requestBase.requestBase"
] | [((296, 420), 'ichubOpenApi.request.requestBase.requestBase', 'requestBase', ([], {'host': 'host', 'v': 'v', 'app_id': 'app_id', 'sign_type': 'sign_type', 'key': 'key', 'public_key': 'public_key', 'private_key': 'private_key'}), '(host=host, v=v, app_id=app_id, sign_type=sign_type, key=key,\n public_key=public_key, ... |
"""Parent class for tab panes."""
# --- import --------------------------------------------------------------------------------------
import logging
import WrightTools as wt
from .input_table import InputTable
from .label import Label
from .pane_widget import PaneWidget
from .push_button import PushButton
# ---... | [
"logging.getLogger",
"logging.Handler.__init__",
"WrightTools.kit.TimeStamp"
] | [((423, 450), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (440, 450), False, 'import logging\n'), ((806, 836), 'logging.Handler.__init__', 'logging.Handler.__init__', (['self'], {}), '(self)\n', (830, 836), False, 'import logging\n'), ((1866, 1901), 'WrightTools.kit.TimeStamp', 'wt.kit... |
import requests
import asyncio
from fastapi import Depends
from ..models.movie import MovieIns, UpdatedMovie
from ..models.actor import Actor
from ..crud.movies import add_movie,fetch_incomplete_movies,update_movie
from .connection import get_database,connect_to_mongo
apiKey = "<KEY>"
def get_top_250_movies(apikey):
... | [
"requests.get"
] | [((330, 396), 'requests.get', 'requests.get', (['f"""https://imdb-api.com/fr/API/Top250Movies/{apikey}"""'], {}), "(f'https://imdb-api.com/fr/API/Top250Movies/{apikey}')\n", (342, 396), False, 'import requests\n'), ((578, 596), 'requests.get', 'requests.get', (['link'], {}), '(link)\n', (590, 596), False, 'import reque... |
"""
Restore database.
"""
from __future__ import (absolute_import, division,
print_function, unicode_literals)
import os
import sys
import warnings
from optparse import make_option
from django.conf import settings
from django.core.management.base import CommandError
from django.utils import si... | [
"django.db.connection.close",
"optparse.make_option",
"django.core.management.base.CommandError",
"sys.exit",
"warnings.warn",
"os.path.basename",
"django.conf.settings.DATABASES.keys"
] | [((5094, 5132), 'warnings.warn', 'warnings.warn', (['msg', 'DeprecationWarning'], {}), '(msg, DeprecationWarning)\n', (5107, 5132), False, 'import warnings\n'), ((759, 818), 'optparse.make_option', 'make_option', (['"""-d"""', '"""--database"""'], {'help': '"""Database to restore"""'}), "('-d', '--database', help='Data... |
import random
m=1
n=6
roll_again="yes"
while roll_again=="yes" or roll_again=="y":
print("Rolling the dice....")
print("the values are..")
print(random.randint(m,n))
print(random.randint(m,n))
print(random.randint(m,n))
break
roll_again = input("enter yes or y to continue...Roll the dices again?")
pri... | [
"random.randint"
] | [((323, 343), 'random.randint', 'random.randint', (['m', 'n'], {}), '(m, n)\n', (337, 343), False, 'import random\n'), ((351, 371), 'random.randint', 'random.randint', (['m', 'n'], {}), '(m, n)\n', (365, 371), False, 'import random\n'), ((379, 399), 'random.randint', 'random.randint', (['m', 'n'], {}), '(m, n)\n', (393... |
'''OpenGL extension ARB.invalidate_subdata
This module customises the behaviour of the
OpenGL.raw.GL.ARB.invalidate_subdata to provide a more
Python-friendly API
Overview (from the spec)
This extension adds a mechanism for an application to tell the GL that
the previous contents of a subregion of an im... | [
"OpenGL.wrapper.wrapper",
"OpenGL.extensions.hasGLExtension"
] | [((2713, 2755), 'OpenGL.extensions.hasGLExtension', 'extensions.hasGLExtension', (['_EXTENSION_NAME'], {}), '(_EXTENSION_NAME)\n', (2738, 2755), False, 'from OpenGL import extensions\n'), ((2870, 2910), 'OpenGL.wrapper.wrapper', 'wrapper.wrapper', (['glInvalidateFramebuffer'], {}), '(glInvalidateFramebuffer)\n', (2885,... |
#!/usr/bin/env python3
#python script to quickly plot geographical grids
# Author <NAME> (http://wobbly.earth)
# initial version 5 December 2017
# License: see file LICENSE (MIT)
#part of speedplot
import sys
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
from optparse import OptionParser
from netCDF4 imp... | [
"matplotlib.pyplot.contourf",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.gcf",
"netCDF4.Dataset",
"matplotlib.pyplot.colorbar",
"cartopy.crs.PlateCarree",
"optparse.OptionParser",
"matplotlib.pyplot.sca",
"matplotlib.pyplot.axes",
"sys.exit",
"matplotlib.pyplot.title",
"re.findall",
"ma... | [((561, 580), 'optparse.OptionParser', 'OptionParser', (['usage'], {}), '(usage)\n', (573, 580), False, 'from optparse import OptionParser\n'), ((4247, 4284), 'cartopy.crs.PlateCarree', 'ccrs.PlateCarree', ([], {'central_longitude': '(0)'}), '(central_longitude=0)\n', (4263, 4284), True, 'import cartopy.crs as ccrs\n')... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.9 on 2018-02-05 07:28
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
import django.utils.timezone
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('book', '0... | [
"datetime.datetime",
"django.db.models.TextField",
"django.db.models.CharField"
] | [((478, 529), 'django.db.models.TextField', 'models.TextField', ([], {'default': 'django.utils.timezone.now'}), '(default=django.utils.timezone.now)\n', (494, 529), False, 'from django.db import migrations, models\n'), ((690, 721), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(50)'}), '(max_le... |
# This file is part of faro.
#
# Developed for the LSST Data Management System.
# This product includes software developed by the LSST Project
# (https://www.lsst.org).
# See the COPYRIGHT file at the top-level directory of this distribution
# for details of code ownership.
#
# This program is free software: you can re... | [
"lsst.verify.Measurement",
"lsst.pipe.base.Struct"
] | [((1630, 1671), 'lsst.verify.Measurement', 'Measurement', (['"""starFrac"""', '(frac * u.percent)'], {}), "('starFrac', frac * u.percent)\n", (1641, 1671), False, 'from lsst.verify import Measurement\n'), ((1687, 1711), 'lsst.pipe.base.Struct', 'Struct', ([], {'measurement': 'meas'}), '(measurement=meas)\n', (1693, 171... |
import pickle
import numpy as np
import tensorflow as tf
import librosa
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from mpl_toolkits.axes_grid1 import make_axes_locatable
import os
import json
import glob
from Input import Input
import Models.UnetAudioSeparator
import Models.UnetSpectrogramSep... | [
"numpy.log10",
"matplotlib.pyplot.vlines",
"librosa.resample",
"numpy.array",
"numpy.nanmean",
"librosa.load",
"numpy.mean",
"tensorflow.Session",
"numpy.max",
"musdb.DB",
"mpl_toolkits.axes_grid1.make_axes_locatable",
"numpy.min",
"numpy.tile",
"numpy.nanstd",
"museval.eval_mus_track",
... | [((760, 786), 'numpy.inner', 'np.inner', (['estimate', 'target'], {}), '(estimate, target)\n', (768, 786), True, 'import numpy as np\n'), ((3555, 3666), 'Input.Input.get_multitrack_placeholders', 'Input.get_multitrack_placeholders', (['sep_output_shape', "model_config['num_sources']", 'sep_input_shape', '"""input"""'],... |
import json
import logging
import multiprocessing.pool
from typing import Optional
from cda_client import ApiClient, Configuration
from cda_client.api.query_api import QueryApi
from cda_client.model.query import Query
from cdapython.constantVariables import table_version, default_table,project_name
from cdapython.Resul... | [
"json.loads",
"cdapython.functions.Unquoted",
"cdapython.Result.get_query_result",
"cda_client.Configuration",
"cda_client.api.meta_api.MetaApi",
"cda_client.api.query_api.QueryApi",
"cda_client.model.query.Query",
"cdapython.functions.col",
"cdapython.functions.Quoted"
] | [((6930, 6943), 'cdapython.functions.Unquoted', 'Unquoted', (['val'], {}), '(val)\n', (6938, 6943), False, 'from cdapython.functions import Quoted, Unquoted, col\n'), ((840, 847), 'cda_client.model.query.Query', 'Query', ([], {}), '()\n', (845, 847), False, 'from cda_client.model.query import Query\n'), ((2636, 2704), ... |
import pandas as pd
import collections
data = "https://bites-data.s3.us-east-2.amazonaws.com/summer.csv"
def athletes_most_medals(data=data):
# read data
pd_data = pd.read_csv(data, index_col=0)
# ==> one way
# male_most_medals = dict(pd_data[pd_data["Gender"] == "Men"]["Athlete"].value_counts()... | [
"collections.Counter",
"medals.data.replace",
"medals.athletes_most_medals",
"pandas.read_csv"
] | [((175, 205), 'pandas.read_csv', 'pd.read_csv', (['data'], {'index_col': '(0)'}), '(data, index_col=0)\n', (186, 205), True, 'import pandas as pd\n'), ((930, 952), 'medals.athletes_most_medals', 'athletes_most_medals', ([], {}), '()\n', (950, 952), False, 'from medals import data, athletes_most_medals\n'), ((1145, 1187... |
import unittest
import datetime
import sys
sys.path.append(".")
from python_play.date_utility import random_datetime
from python_play.date_utility import random_date_string_inferring_format
from python_play.date_utility import date_format_parse
from python_play.date_utility import random_date_string
class TestDateUti... | [
"python_play.date_utility.random_date_string_inferring_format",
"python_play.date_utility.date_format_parse",
"datetime.datetime.strptime",
"python_play.date_utility.random_datetime",
"python_play.date_utility.random_date_string",
"unittest.main",
"sys.path.append"
] | [((43, 63), 'sys.path.append', 'sys.path.append', (['"""."""'], {}), "('.')\n", (58, 63), False, 'import sys\n'), ((4207, 4222), 'unittest.main', 'unittest.main', ([], {}), '()\n', (4220, 4222), False, 'import unittest\n'), ((524, 586), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (['start_date_string', ... |
import numpy as np
from pymoo.experimental.deriv import DerivationBasedAlgorithm
from pymoo.algorithms.base.line import LineSearchProblem
from pymoo.algorithms.soo.univariate.exp import ExponentialSearch
from pymoo.algorithms.soo.univariate.golden import GoldenSectionSearch
from pymoo.core.population import Population... | [
"pymoo.algorithms.soo.univariate.golden.GoldenSectionSearch",
"numpy.zeros",
"pymoo.core.population.Population.merge",
"numpy.linalg.norm",
"pymoo.algorithms.soo.univariate.exp.ExponentialSearch",
"pymoo.algorithms.base.line.LineSearchProblem"
] | [((840, 926), 'pymoo.algorithms.base.line.LineSearchProblem', 'LineSearchProblem', (['self.problem', 'sol', 'direction'], {'strict_bounds': 'self.strict_bounds'}), '(self.problem, sol, direction, strict_bounds=self.\n strict_bounds)\n', (857, 926), False, 'from pymoo.algorithms.base.line import LineSearchProblem\n')... |
from mutation import *
from evolocity_graph import *
import evolocity as evo
np.random.seed(1)
random.seed(1)
def parse_args():
import argparse
parser = argparse.ArgumentParser(description='Flu NP sequence analysis')
parser.add_argument('model_name', type=str,
help='Type of languag... | [
"evolocity.tl.velocity_embedding",
"evolocity.pl.velocity_embedding_stream",
"pickle.dump",
"argparse.ArgumentParser",
"evolocity.tools.velocity_graph.VelocityGraph",
"evolocity.pl.velocity_embedding_grid",
"pickle.load",
"evolocity.tl.onehot_msa",
"evolocity.pl.residue_scores",
"evolocity.set_fig... | [((163, 226), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Flu NP sequence analysis"""'}), "(description='Flu NP sequence analysis')\n", (186, 226), False, 'import argparse\n'), ((10377, 10415), 'evolocity.tools.velocity_graph.VelocityGraph', 'VelocityGraph', (['adata', "adata.obs['seq... |
# =============================================================================
# PROJECT CHRONO - http://projectchrono.org
#
# Copyright (c) 2022 projectchrono.org
# All rights reserved.
#
# Use of this source code is governed by a BSD-style license that can be found
# in the LICENSE file at the top level of the distr... | [
"pychrono.core.ChBoxShape",
"pychrono.core.ChVectorD",
"pychrono.irrlicht.ChVisualSystemIrrlicht",
"pychrono.core.ChBody",
"pychrono.core.GetChronoDataFile",
"pychrono.core.ChLinkRevolute",
"pychrono.core.ChSystemNSC"
] | [((1039, 1059), 'pychrono.core.ChSystemNSC', 'chrono.ChSystemNSC', ([], {}), '()\n', (1057, 1059), True, 'import pychrono.core as chrono\n'), ((1099, 1114), 'pychrono.core.ChBody', 'chrono.ChBody', ([], {}), '()\n', (1112, 1114), True, 'import pychrono.core as chrono\n'), ((1213, 1232), 'pychrono.core.ChBoxShape', 'chr... |
import GatherDataSetScripts.Video as VideoClass
import json
from dateutil import parser
def get_videos_ids(client, channel_id, data_set_location, published_after_string):
publish_after = parser.parse(published_after_string).date()
channel_parameters = {
'part': 'contentDetails',
'id': channel_... | [
"dateutil.parser.parse",
"GatherDataSetScripts.Video.Video",
"json.dump"
] | [((1704, 1761), 'json.dump', 'json.dump', (['[video.__dict__ for video in videos]', 'out_file'], {}), '([video.__dict__ for video in videos], out_file)\n', (1713, 1761), False, 'import json\n'), ((193, 229), 'dateutil.parser.parse', 'parser.parse', (['published_after_string'], {}), '(published_after_string)\n', (205, 2... |
import argparse
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../'))
import torch
from volksdep.converters import torch2onnx
from vedaseg.runners import InferenceRunner
from vedaseg.utils import Config
def parse_args():
parser = argparse.ArgumentParser(description='Convert to... | [
"argparse.ArgumentParser",
"os.path.dirname",
"vedaseg.runners.InferenceRunner",
"vedaseg.utils.Config.fromfile",
"volksdep.converters.torch2onnx",
"os.path.abspath",
"torch.randn"
] | [((273, 334), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Convert to Onnx model."""'}), "(description='Convert to Onnx model.')\n", (296, 334), False, 'import argparse\n'), ((1404, 1432), 'vedaseg.utils.Config.fromfile', 'Config.fromfile', (['args.config'], {}), '(args.config)\n', (14... |
import numpy as np
import tensorflow as tf
if int(tf.__version__[0]) > 1:
from tensorflow.keras.utils import Sequence
else:
from tensorflow.python.keras.utils import Sequence
class DefaultGenerator(Sequence):
"""
Create the default generator class using Keras sequence as the parent
"""
def _... | [
"numpy.shape",
"numpy.transpose",
"numpy.random.shuffle"
] | [((2251, 2288), 'numpy.transpose', 'np.transpose', (['batch_y'], {'axes': '(0, 2, 1)'}), '(batch_y, axes=(0, 2, 1))\n', (2263, 2288), True, 'import numpy as np\n'), ((2478, 2509), 'numpy.random.shuffle', 'np.random.shuffle', (['self.indices'], {}), '(self.indices)\n', (2495, 2509), True, 'import numpy as np\n'), ((937,... |
"""
authorizer module for invoking lambda function to do authentication
"""
import json
import boto3
SECRET_NAME = "grouch/apiKey"
def lambda_handler(event, context):
"""
lambda function for authenticating users
:param event: lambda event that contains the authorization token
:param context: lambda ... | [
"json.loads",
"boto3.session.Session"
] | [((1091, 1114), 'boto3.session.Session', 'boto3.session.Session', ([], {}), '()\n', (1112, 1114), False, 'import boto3\n'), ((1246, 1295), 'json.loads', 'json.loads', (["secret_value_response['SecretString']"], {}), "(secret_value_response['SecretString'])\n", (1256, 1295), False, 'import json\n')] |
#!/usr/bin/python
from egat.loggers.simple_text_logger import SimpleTextLogger
from egat.loggers.html_logger import HTMLLogger
from egat.auto_threaded_test_runner import AutoThreadedTestRunner
from egat.user_threaded_test_runner import UserThreadedTestRunner
from egat.parse import ArgumentParser
import sys
def run():
... | [
"egat.loggers.simple_text_logger.SimpleTextLogger",
"egat.loggers.html_logger.HTMLLogger",
"egat.parse.ArgumentParser",
"egat.auto_threaded_test_runner.AutoThreadedTestRunner",
"egat.user_threaded_test_runner.UserThreadedTestRunner",
"sys.exit"
] | [((418, 434), 'egat.parse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (432, 434), False, 'from egat.parse import ArgumentParser\n'), ((1180, 1199), 'sys.exit', 'sys.exit', (['exit_code'], {}), '(exit_code)\n', (1188, 1199), False, 'import sys\n'), ((748, 800), 'egat.loggers.html_logger.HTMLLogger', 'HTMLLogger... |
import os
import os.path as osp
import cv2
import numpy as np
import pickle
import argparse
import sys
sys.path.append(osp.join(sys.path[0], '..', '..')) # relative to current one
# print(sys.path)
import utils.utils as ut
from tqdm import tqdm
'''
history:
210924: update the part to global 24 index with visibility ... | [
"numpy.savez",
"os.listdir",
"os.makedirs",
"argparse.ArgumentParser",
"tqdm.tqdm",
"os.path.join",
"pickle.load",
"numpy.array",
"numpy.zeros",
"os.path.isdir",
"numpy.einsum",
"cv2.Rodrigues"
] | [((119, 152), 'os.path.join', 'osp.join', (['sys.path[0]', '""".."""', '""".."""'], {}), "(sys.path[0], '..', '..')\n", (127, 152), True, 'import os.path as osp\n'), ((907, 958), 'os.path.join', 'os.path.join', (['dataset_path', '"""sequenceFiles"""', '"""test"""'], {}), "(dataset_path, 'sequenceFiles', 'test')\n", (91... |
import ast
import pathlib
import pprint
from flake8_rst_docstrings import Plugin
s = pathlib.Path("tests/test_ast.py").read_text()
pprint.pprint(list(Plugin(ast.parse(s)).run()))
| [
"ast.parse",
"pathlib.Path"
] | [((87, 120), 'pathlib.Path', 'pathlib.Path', (['"""tests/test_ast.py"""'], {}), "('tests/test_ast.py')\n", (99, 120), False, 'import pathlib\n'), ((160, 172), 'ast.parse', 'ast.parse', (['s'], {}), '(s)\n', (169, 172), False, 'import ast\n')] |
#!/usr/bin/env python
"""Tests for InputRescaling layer"""
import pytest
import torch
import numpy
from econ_layers.layers import RescaleOutputsByInput
def test_input_rescaling():
x = torch.cartesian_prod(
torch.linspace(
0.0,
10.0,
steps=20,
),
torch... | [
"econ_layers.layers.RescaleOutputsByInput",
"torch.isclose",
"torch.linspace"
] | [((424, 448), 'econ_layers.layers.RescaleOutputsByInput', 'RescaleOutputsByInput', (['(0)'], {}), '(0)\n', (445, 448), False, 'from econ_layers.layers import RescaleOutputsByInput\n'), ((469, 493), 'econ_layers.layers.RescaleOutputsByInput', 'RescaleOutputsByInput', (['(1)'], {}), '(1)\n', (490, 493), False, 'from econ... |
import unittest
import mud
class TestTimeSlice(unittest.TestCase):
def test_raw_events(self):
events = [
mud.Event(mud.Note('C4', 1), mud.Time(0)),
mud.Event(mud.Note('G5', 1), mud.Time(0)),
mud.Event(mud.Rest( 1), mud.Time(1)),
mud.Event(mud.Note('C4', ... | [
"mud.Span",
"mud.TimeSlice",
"mud.Time",
"mud.Rest",
"mud.Note"
] | [((418, 454), 'mud.Span', 'mud.Span', (['events'], {'length': '(4)', 'offset': '(4)'}), '(events, length=4, offset=4)\n', (426, 454), False, 'import mud\n'), ((1713, 1749), 'mud.Span', 'mud.Span', (['events'], {'length': '(4)', 'offset': '(4)'}), '(events, length=4, offset=4)\n', (1721, 1749), False, 'import mud\n'), (... |
import os
from gensim.models import KeyedVectors
# Load pretrained model (since intermediate data is not included, the model cannot be refined with additional data)
vector_file = os.getenv("VECTOR_FILE",
"https://s3.amazonaws.com/dl4j-distribution/GoogleNews-vectors-negative300.bin.gz")
binary ... | [
"gensim.models.KeyedVectors.load_word2vec_format",
"os.getenv"
] | [((180, 297), 'os.getenv', 'os.getenv', (['"""VECTOR_FILE"""', '"""https://s3.amazonaws.com/dl4j-distribution/GoogleNews-vectors-negative300.bin.gz"""'], {}), "('VECTOR_FILE',\n 'https://s3.amazonaws.com/dl4j-distribution/GoogleNews-vectors-negative300.bin.gz'\n )\n", (189, 297), False, 'import os\n'), ((433, 494... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-10-27 01:09
from __future__ import unicode_literals
from django.db import migrations
def create_entity(apps, schema_editor):
Entity = apps.get_model('waypoints', 'Entity')
WaypointGroup = apps.get_model('waypoints', 'WaypointGroup')
db_alias = s... | [
"django.db.migrations.RunPython"
] | [((1117, 1167), 'django.db.migrations.RunPython', 'migrations.RunPython', (['create_entity', 'remove_entity'], {}), '(create_entity, remove_entity)\n', (1137, 1167), False, 'from django.db import migrations\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
r''' Copyright 2018, SigDev
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 requ... | [
"sys.getsizeof",
"six.iteritems"
] | [((1180, 1194), 'sys.getsizeof', 'getsizeof', (['obj'], {}), '(obj)\n', (1189, 1194), False, 'from sys import getsizeof\n'), ((3095, 3111), 'six.iteritems', 'iteritems', (['cache'], {}), '(cache)\n', (3104, 3111), False, 'from six import iteritems\n'), ((1706, 1720), 'six.iteritems', 'iteritems', (['obj'], {}), '(obj)\... |
import os
from pyspark_tooling.emr import EMR
from pyspark_tooling.timestamp import format_timestamp, utcnow
class IntegrationTest:
def __init__(self):
self.bucket = os.environ["INTEGRATION_TEST_BUCKET"]
self.folder = f"landing_timestamp={format_timestamp(utcnow())}"
self.s3_path = f"s3://... | [
"pyspark_tooling.emr.EMR.from_defaults",
"pyspark_tooling.timestamp.utcnow"
] | [((616, 785), 'pyspark_tooling.emr.EMR.from_defaults', 'EMR.from_defaults', ([], {'cluster_name': '"""integration_test_cluster"""', 'code_path': 'f"""{s3_path}/main.py"""', 'log_uri': 'f"""{s3_path}/logs"""', 'minimum_memory_in_gb': '(32)', 'minimum_vcpu': '(12)'}), "(cluster_name='integration_test_cluster', code_path=... |
# -*- coding: utf-8 -*-
from mock import patch
from datetime import datetime
from collections import defaultdict
from concurrent.futures import Future, ThreadPoolExecutor
from connect.api import ConnectApi
from connect.client import ConnectClient
from connect.event import Event
from connect import exceptions, response... | [
"datetime.datetime",
"connect.event.Event",
"mock.patch",
"connect.responses.PushBatchResponse",
"collections.defaultdict",
"connect.client.ConnectClient"
] | [((538, 567), 'datetime.datetime', 'datetime', (['(2015)', '(8)', '(27)', '(10)', '(17)'], {}), '(2015, 8, 27, 10, 17)\n', (546, 567), False, 'from datetime import datetime\n'), ((1907, 1952), 'mock.patch', 'patch', (['"""connect.client.ConnectApi.post_event"""'], {}), "('connect.client.ConnectApi.post_event')\n", (191... |
import pytest
from chainloader.units import is_type, to_type
@pytest.mark.unittest
class TestUnitsCommon:
def test_is_type(self):
is_int = is_type(int)
assert is_int(1) == 1
assert is_int(2) == 2
with pytest.raises(TypeError):
_ = is_int(1.0)
with pytest.raises... | [
"chainloader.units.is_type",
"chainloader.units.to_type",
"pytest.raises"
] | [((154, 166), 'chainloader.units.is_type', 'is_type', (['int'], {}), '(int)\n', (161, 166), False, 'from chainloader.units import is_type, to_type\n'), ((415, 427), 'chainloader.units.to_type', 'to_type', (['int'], {}), '(int)\n', (422, 427), False, 'from chainloader.units import is_type, to_type\n'), ((240, 264), 'pyt... |
"""test calculation of coordinates and shortest paths"""
import os
import pytest
from casymda.blocks.tilemap.coordinates_holder import CoordinatesHolder, delete_cached
CSV_FILE = "6x6_ABC.csv"
directory = os.path.dirname(__file__)
csv_path = os.path.join(directory, CSV_FILE)
SCALE = 1
@pytest.fixture(scope="modul... | [
"os.path.join",
"casymda.blocks.tilemap.coordinates_holder.CoordinatesHolder",
"os.path.dirname",
"pytest.fixture",
"casymda.blocks.tilemap.coordinates_holder.delete_cached"
] | [((208, 233), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (223, 233), False, 'import os\n'), ((245, 278), 'os.path.join', 'os.path.join', (['directory', 'CSV_FILE'], {}), '(directory, CSV_FILE)\n', (257, 278), False, 'import os\n'), ((293, 337), 'pytest.fixture', 'pytest.fixture', ([], {'s... |
import numpy as np
import networkx as nx
from itertools import combinations
from random import randrange, uniform
from numpy.linalg import inv
import scipy.sparse as sp
import pickle as pk
import os
def get_sparse_eigen_decomposition(graph, K):
adj = nx.adjacency_matrix(graph, nodelist=sorted(graph.nodes()), weig... | [
"os.path.exists",
"random.uniform",
"networkx.barabasi_albert_graph",
"numpy.linalg.eig",
"pickle.load",
"networkx.Graph",
"numpy.argsort",
"numpy.zeros",
"networkx.draw_shell",
"numpy.linalg.svd",
"numpy.matrix",
"networkx.erdos_renyi_graph"
] | [((527, 545), 'numpy.linalg.eig', 'np.linalg.eig', (['adj'], {}), '(adj)\n', (540, 545), True, 'import numpy as np\n'), ((663, 690), 'numpy.zeros', 'np.zeros', (['(adj.shape[0], K)'], {}), '((adj.shape[0], K))\n', (671, 690), True, 'import numpy as np\n'), ((818, 838), 'numpy.matrix', 'np.matrix', (['V_ksparse'], {}), ... |
# connect to registration table
# search targets to push
# 1. get all the jobs with "job_success"
# 2. check if job files are indeed there
# 3. get level of theory from job files
# 4. check if results table has this job with
# same level of theory
# launch cantherm job,
# push results to results table
# main da... | [
"os.path.exists",
"os.path.join",
"time.time"
] | [((4123, 4197), 'os.path.join', 'os.path.join', (["config['QuantumMechanicJob']['scratch_data_path']", '"""success"""'], {}), "(config['QuantumMechanicJob']['scratch_data_path'], 'success')\n", (4135, 4197), False, 'import os\n'), ((1154, 1196), 'os.path.join', 'os.path.join', (['success_data_path', 'spec_name'], {}), ... |
import time
import asyncio
from spade.agent import Agent
from spade.behaviour import CyclicBehaviour
class DummyAgent(Agent):
"""Test example SPADE Agent."""
class MyBehav(CyclicBehaviour):
async def on_start(self):
print("Starting behaviour . . .")
self.counter = 0
as... | [
"time.sleep",
"asyncio.sleep"
] | [((848, 861), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (858, 861), False, 'import time\n'), ((441, 457), 'asyncio.sleep', 'asyncio.sleep', (['(1)'], {}), '(1)\n', (454, 457), False, 'import asyncio\n')] |
# Generated by Django 2.2.13 on 2021-02-01 11:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('project', '0036_auto_20210201_1120'),
]
operations = [
migrations.AlterField(
model_name='project',
name='pi',
... | [
"django.db.models.CharField"
] | [((334, 460), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(256)', 'verbose_name': '"""(obsolete) Principal Investigator\'s name, position and email"""'}), '(blank=True, max_length=256, verbose_name=\n "(obsolete) Principal Investigator\'s name, position and email")\n', (... |
# Resource object code (Python 3)
# Created by: object code
# Created by: The Resource Compiler for Qt version 5.15.2
# WARNING! All changes made in this file will be lost!
from PySide2 import QtCore
qt_resource_data = b"\
\x00\x00\x0c\x0d\
\x89\
PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\
\x00\x00@\x00\x... | [
"PySide2.QtCore.qUnregisterResourceData",
"PySide2.QtCore.qRegisterResourceData"
] | [((10698, 10789), 'PySide2.QtCore.qRegisterResourceData', 'QtCore.qRegisterResourceData', (['(3)', 'qt_resource_struct', 'qt_resource_name', 'qt_resource_data'], {}), '(3, qt_resource_struct, qt_resource_name,\n qt_resource_data)\n', (10726, 10789), False, 'from PySide2 import QtCore\n'), ((10822, 10915), 'PySide2.Q... |
import logging
class Logger:
config = {
'level': 'DEBUG',
'stdout': True
}
def __init__(self, name='logger', config=config):
self.logger = logging.getLogger(name)
level = logging.getLevelName(config.get('level', 'DEBUG'))
self.logger.setLevel(level)
defau... | [
"logging.getLogger",
"logging.Formatter",
"logging.StreamHandler",
"logging.FileHandler"
] | [((178, 201), 'logging.getLogger', 'logging.getLogger', (['name'], {}), '(name)\n', (195, 201), False, 'import logging\n'), ((335, 443), 'logging.Formatter', 'logging.Formatter', (['"""%(asctime)s - %(name)s - %(levelname)-8s %(message)s"""'], {'datefmt': '"""%d-%m-%Y %H:%M:%S"""'}), "('%(asctime)s - %(name)s - %(lev... |
# MIT License
#
# Copyright (c) 2020-2021 <NAME> AG
#
# 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, merg... | [
"datalayerprovider.data_container.DataContainer",
"datalayerprovider.providerNodeCfgUint16.ProviderNodeCfgUint16",
"datalayer.variant.Variant",
"datalayer.provider_node.ProviderNodeCallbacks",
"datalayer.provider_node.ProviderNode"
] | [((1928, 1951), 'datalayerprovider.providerNodeCfgUint16.ProviderNodeCfgUint16', 'ProviderNodeCfgUint16', ([], {}), '()\n', (1949, 1951), False, 'from datalayerprovider.providerNodeCfgUint16 import ProviderNodeCfgUint16\n'), ((2088, 2111), 'datalayerprovider.providerNodeCfgUint16.ProviderNodeCfgUint16', 'ProviderNodeCf... |
from typing import cast, Iterable, List
import numpy as np
import tensorflow as tf
import warpctc_tensorflow as warpctc
from typeguard import check_argument_types
from neuralmonkey.dataset import Dataset
from neuralmonkey.decorators import tensor
from neuralmonkey.model.feedable import FeedDict
from neuralmonkey.mode... | [
"tensorflow.nn.conv2d",
"tensorflow.get_variable",
"tensorflow.transpose",
"tensorflow.nn.ctc_greedy_decoder",
"tensorflow.nn.ctc_beam_search_decoder",
"tensorflow.reduce_sum",
"tensorflow.placeholder",
"neuralmonkey.model.model_part.ModelPart.__init__",
"tensorflow.concat",
"typeguard.check_argum... | [((1428, 1450), 'typeguard.check_argument_types', 'check_argument_types', ([], {}), '()\n', (1448, 1450), False, 'from typeguard import check_argument_types\n'), ((1459, 1548), 'neuralmonkey.model.model_part.ModelPart.__init__', 'ModelPart.__init__', (['self', 'name', 'reuse', 'save_checkpoint', 'load_checkpoint', 'ini... |
from __future__ import print_function
from six.moves import xrange
from ortools.constraint_solver import pywrapcp
from ortools.constraint_solver import routing_enums_pb2
import urllib.request
import json
from geopy.distance import vincenty
test_20 = {
"points": [[10.773687, 106.703263], [10.731158, 106.716759], [... | [
"ortools.constraint_solver.pywrapcp.RoutingModel.DefaultSearchParameters",
"json.loads",
"ortools.constraint_solver.pywrapcp.RoutingModel",
"json.dumps",
"geopy.distance.vincenty"
] | [((923, 939), 'json.dumps', 'json.dumps', (['body'], {}), '(body)\n', (933, 939), False, 'import json\n'), ((1056, 1078), 'geopy.distance.vincenty', 'vincenty', (['pos_1', 'pos_2'], {}), '(pos_1, pos_2)\n', (1064, 1078), False, 'from geopy.distance import vincenty\n'), ((3869, 3919), 'ortools.constraint_solver.pywrapcp... |
"""
RSA encryption algorithm
a method for encrypting a number that uses seperate encryption and decryption keys
this file only implements the key generation algorithm
there are three important numbers in RSA called n, e, and d
e is called the encryption exponent
d is called the decryption exponent
n is called the modu... | [
"random.randrange"
] | [((959, 997), 'random.randrange', 'random.randrange', (['(2 ** (k - 1))', '(2 ** k)'], {}), '(2 ** (k - 1), 2 ** k)\n', (975, 997), False, 'import random\n')] |
#!/usr/bin/env python3
# Copyright (C) 2020 <NAME>
#
# Licensed under the MIT License. See LICENSE.txt for additional details.
import numpy as np
import matplotlib as mpl
mpl.use("pgf")
import matplotlib.pylab as plt
import grfstyl as gfx
mpl.rcParams.update( gfx.rc_custom_preamble( use_grid=False, columns=1 ) )
fi... | [
"grfstyl.label_axes",
"matplotlib.pylab.figure",
"matplotlib.use",
"grfstyl.aspect_ratio",
"grfstyl.page_size.max_elements",
"grfstyl.rc_custom_preamble"
] | [((174, 188), 'matplotlib.use', 'mpl.use', (['"""pgf"""'], {}), "('pgf')\n", (181, 188), True, 'import matplotlib as mpl\n'), ((324, 336), 'matplotlib.pylab.figure', 'plt.figure', ([], {}), '()\n', (334, 336), True, 'import matplotlib.pylab as plt\n'), ((905, 1041), 'grfstyl.label_axes', 'gfx.label_axes', (['ax', '"""$... |
from collections import defaultdict
strings = ('puppy', 'kitten', 'puppy', 'puppy',
'weasel', 'puppy', 'kitten', 'puppy')
counts = defaultdict(int) # 使用lambda来定义简单的函数
for s in strings:
counts[s] += 1
print(counts) | [
"collections.defaultdict"
] | [((143, 159), 'collections.defaultdict', 'defaultdict', (['int'], {}), '(int)\n', (154, 159), False, 'from collections import defaultdict\n')] |
import os
import torch
import numbers
import torchvision.transforms as transforms
import torchvision.transforms.functional as F
from torch.utils.data import Subset, TensorDataset
import numpy as np
def get_dataset(args, config):
if config.data.random_flip is False:
tran_transform = test_transform = trans... | [
"numpy.mean",
"torch.log",
"torch.rand_like",
"numpy.std",
"torch.sigmoid",
"torchvision.transforms.RandomHorizontalFlip",
"torch.from_numpy",
"numpy.max",
"torch.randn_like",
"numpy.min",
"torchvision.transforms.Resize",
"torchvision.transforms.ToTensor",
"numpy.load",
"torch.clamp",
"t... | [((826, 851), 'numpy.load', 'np.load', (['args.train_fname'], {}), '(args.train_fname)\n', (833, 851), True, 'import numpy as np\n'), ((917, 970), 'numpy.mean', 'np.mean', (['train_samples'], {'axis': '(0, 2, 3)', 'keepdims': '(True)'}), '(train_samples, axis=(0, 2, 3), keepdims=True)\n', (924, 970), True, 'import nump... |
import networkzero as nw0
address = nw0.advertise("myservice3", 1234)
print("Service is at address", address) | [
"networkzero.advertise"
] | [((37, 70), 'networkzero.advertise', 'nw0.advertise', (['"""myservice3"""', '(1234)'], {}), "('myservice3', 1234)\n", (50, 70), True, 'import networkzero as nw0\n')] |
import os
LOCAL_PATH = os.path.dirname(os.path.realpath(__file__))
TEMPLATE_DIR = os.path.join(LOCAL_PATH, 'templates')
API_HOST_URL = 'https://espa.cr.usgs.gov'
API_VERSION = 'v0'
HEADERS = {'Content-Type': 'application/json'}
LANDSAT_TILE_REGEX = "(L)(C|O|T|E)(7|8|5|4)(\d{3})(\d{3})(\d{7})(\w{3})(\d{2})"
LANDSAT_SH... | [
"os.path.realpath",
"os.path.join"
] | [((83, 120), 'os.path.join', 'os.path.join', (['LOCAL_PATH', '"""templates"""'], {}), "(LOCAL_PATH, 'templates')\n", (95, 120), False, 'import os\n'), ((40, 66), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (56, 66), False, 'import os\n')] |
from numpy import arange
from hex_to_decimal import hex_to_decimal
from decimal_to_hex import decimal_to_hex
from binary_to_decimal import binary_to_decimal
from decimal_to_binary import decimal_to_binary
from octal_to_decimal import octal_to_decimal
from decimal_to_octal import decimal_to_octal
from binary_to_hex imp... | [
"octal_to_decimal.octal_to_decimal",
"binary_to_decimal.binary_to_decimal",
"decimal_to_octal.decimal_to_octal",
"decimal_to_hex.decimal_to_hex",
"binary_to_octal.binary_to_octal",
"hex_to_decimal.hex_to_decimal",
"decimal_to_binary.decimal_to_binary",
"unittest.main",
"random.random",
"binary_to_... | [((2160, 2166), 'unittest.main', 'main', ([], {}), '()\n', (2164, 2166), False, 'from unittest import main, TestCase\n'), ((532, 553), 'numpy.arange', 'arange', (['(0)', '(100)', '(0.001)'], {}), '(0, 100, 0.001)\n', (538, 553), False, 'from numpy import arange\n'), ((779, 800), 'numpy.arange', 'arange', (['(0)', '(100... |
import os
import shutil
from vilya.libs.permdir import get_repo_root
from vilya.models.project import CodeDoubanProject
from tests.base import TestCase
class TestBasic(TestCase):
def test_create_git_repo(self):
git_path = os.path.join(get_repo_root(), 'abc.git')
CodeDoubanProject.create_git_repo... | [
"os.path.exists",
"vilya.models.project.CodeDoubanProject.create_git_repo",
"vilya.libs.permdir.get_repo_root",
"os.path.join",
"shutil.rmtree"
] | [((287, 330), 'vilya.models.project.CodeDoubanProject.create_git_repo', 'CodeDoubanProject.create_git_repo', (['git_path'], {}), '(git_path)\n', (320, 330), False, 'from vilya.models.project import CodeDoubanProject\n'), ((346, 370), 'os.path.exists', 'os.path.exists', (['git_path'], {}), '(git_path)\n', (360, 370), Fa... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Reads a class definitions file and an n-gram counts file, and corrects the
# class expansion probabilities according to the unigram counts of the words.
import argparse
import sys
from filetypes import TextFileType
from wordclasses import WordClasses, WordsToClasses
f... | [
"filetypes.TextFileType",
"ngramcounts.NGramCounts",
"wordclasses.WordClasses",
"argparse.ArgumentParser"
] | [((365, 390), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (388, 390), False, 'import argparse\n'), ((602, 615), 'wordclasses.WordClasses', 'WordClasses', ([], {}), '()\n', (613, 615), False, 'from wordclasses import WordClasses, WordsToClasses\n'), ((658, 671), 'ngramcounts.NGramCounts', 'NG... |
# -*- coding: utf-8 -*-
"""
@author: <NAME>
"""
import os
import sys
import shutil
from subprocess import call
from warnings import warn
from setuptools import setup
setup(name='CIRCLET',
version='1.0',
package_dir={'': 'src'},
packages=['CIRCLET'],
package_data={
# And include any *.msg file... | [
"setuptools.setup"
] | [((180, 410), 'setuptools.setup', 'setup', ([], {'name': '"""CIRCLET"""', 'version': '"""1.0"""', 'package_dir': "{'': 'src'}", 'packages': "['CIRCLET']", 'package_data': "{'CIRCLET': ['DATA/*', '*.txt', 'DATA/RNA-seq/*', 'DATA/Hi-Cmaps/*',\n 'DATA/Nagano et al/*']}", 'include_package_data': '(True)'}), "(name='CIRC... |
#!/usr/bin/env python
# This program runs as a daemon, collects switch/router interface counter data, and sends
# the metrics to Graphite. It also serves a simple HTTP service that organizes links for
# the interfaces it monitors, as to create a dashboard of graphs without needing to browse
# and click through t... | [
"socket.socket",
"threading.Timer",
"netsnmp.Session",
"cherrypy.config.update",
"netsnmp.Varbind",
"time.time"
] | [((1863, 1969), 'cherrypy.config.update', 'cherrypy.config.update', (["{'server.socket_host': WEB_SERVER_HOST, 'server.socket_port': WEB_SERVER_PORT}"], {}), "({'server.socket_host': WEB_SERVER_HOST,\n 'server.socket_port': WEB_SERVER_PORT})\n", (1885, 1969), False, 'import cherrypy\n'), ((3671, 3686), 'socket.socke... |
from lib import db
from lib import part
import pretty_errors
import xlwings
from argparse import ArgumentParser
XML_PARTS_XLS = r"\\HSSFILESERV1\HSSshared\HSSI Lean\Job Plans\Pre-Nesting Tools\XML PRENESTING\XML-Parts.xls"
pretty_errors.configure(
line_number_first = True,
display_link = True,
)
... | [
"argparse.ArgumentParser",
"lib.db.DbConnection",
"pretty_errors.configure",
"lib.part.Part",
"lib.part.xml_format",
"xlwings.Book"
] | [((228, 294), 'pretty_errors.configure', 'pretty_errors.configure', ([], {'line_number_first': '(True)', 'display_link': '(True)'}), '(line_number_first=True, display_link=True)\n', (251, 294), False, 'import pretty_errors\n'), ((345, 361), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (359, 361), Fals... |