code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
"""
SAC state-space: 2M * 8envs (orig 12) * 5seeds * 4 methods (ours vs mlp vs diag fourier vs l2 regul.)
SAC images: 2M * 4envs * 5seeds * 2methods
SAC ablation Value vs Policy vs Both vs Baseline: 2M * 4envs * 5seeds * 2NewMethods
SAC ablation: 1M * 4envs * 3seeds * 3methods (can leave it as is)
SAC no critic: 1M * 4... | [
"math.ceil"
] | [((1132, 1178), 'math.ceil', 'math.ceil', (['(lff_params / (1024 + 1 + input_dim))'], {}), '(lff_params / (1024 + 1 + input_dim))\n', (1141, 1178), False, 'import math\n')] |
from hyperopt import hp, fmin, tpe, space_eval, Trials
def hpchoice(label, p_options):
return hp.pchoice(label, p_options)
def choice(label, options):
return hp.choice(label, options)
def randint(label, *args, **kwargs):
return hp.randint(label, *args, **kwargs)
def uniform(label, *args, **kwargs):
... | [
"hyperopt.hp.qloguniform",
"hyperopt.hp.qlognormal",
"hyperopt.fmin",
"hyperopt.hp.uniformint",
"hyperopt.hp.randint",
"hyperopt.hp.quniform",
"hyperopt.hp.lognormal",
"hyperopt.hp.uniform",
"hyperopt.hp.normal",
"hyperopt.hp.choice",
"hyperopt.hp.qnormal",
"hyperopt.hp.loguniform",
"hyperop... | [((99, 127), 'hyperopt.hp.pchoice', 'hp.pchoice', (['label', 'p_options'], {}), '(label, p_options)\n', (109, 127), False, 'from hyperopt import hp, fmin, tpe, space_eval, Trials\n'), ((169, 194), 'hyperopt.hp.choice', 'hp.choice', (['label', 'options'], {}), '(label, options)\n', (178, 194), False, 'from hyperopt impo... |
from helper import *
import json
URL = "https://www.umb.edu/academics/course_catalog/subjects/2018%20Spring"
SEM = "2018 Spring"
# Get the catalog page
text = read_URL(URL)
# Get the list of majors
cut = cut_text(text, "<h3>Undergraduate Subjects</h3>", "</ul>")
urls = get_URLs(cut)
cut = cut_text(text, "<h3>Gradua... | [
"json.dump"
] | [((726, 752), 'json.dump', 'json.dump', (['majors', 'outfile'], {}), '(majors, outfile)\n', (735, 752), False, 'import json\n')] |
from mgt.datamanagers.data_manager import Dictionary
class DictionaryGenerator(object):
@staticmethod
def create_dictionary() -> Dictionary:
"""
Creates a dictionary for a REMI-like mapping of midi events.
"""
dictionary = [{}, {}]
def append_to_dictionary(word):
... | [
"mgt.datamanagers.data_manager.Dictionary"
] | [((1688, 1728), 'mgt.datamanagers.data_manager.Dictionary', 'Dictionary', (['dictionary[0]', 'dictionary[1]'], {}), '(dictionary[0], dictionary[1])\n', (1698, 1728), False, 'from mgt.datamanagers.data_manager import Dictionary\n')] |
"""
Model for mecctable objects :
Structures, link between them and exams
"""
from django.db import models
from django.utils.translation import ugettext as _
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
class Stru... | [
"django.utils.translation.ugettext",
"django.db.models.DateField",
"django.contrib.auth.models.User.objects.get"
] | [((3547, 3574), 'django.db.models.DateField', 'models.DateField', ([], {'null': '(True)'}), '(null=True)\n', (3563, 3574), False, 'from django.db import models\n'), ((3652, 3679), 'django.db.models.DateField', 'models.DateField', ([], {'null': '(True)'}), '(null=True)\n', (3668, 3679), False, 'from django.db import mod... |
import unittest
from paco.combinators import SepBy
from paco.atomic import (Char, Regex)
class TestSepByParser(unittest.TestCase):
def setUp(self):
self.integer = Regex(r'[1-9][0-9]*')
self.comm = Char(',') << Regex(r' *')
self.rule = SepBy(self.integer, self.comm)
def test_empty(self... | [
"paco.atomic.Char",
"paco.combinators.SepBy",
"paco.atomic.Regex"
] | [((177, 197), 'paco.atomic.Regex', 'Regex', (['"""[1-9][0-9]*"""'], {}), "('[1-9][0-9]*')\n", (182, 197), False, 'from paco.atomic import Char, Regex\n'), ((265, 295), 'paco.combinators.SepBy', 'SepBy', (['self.integer', 'self.comm'], {}), '(self.integer, self.comm)\n', (270, 295), False, 'from paco.combinators import ... |
import re
'''
. 匹配任意一个字符 除了\n
[] 匹配[]中列举的字符
\d==[0-9] 匹配数字,即0-9
\D==[^0-9] 匹配非数字,即不是数字
\s 匹配空白,即 空格 tab
\S 匹配非空白
\w==[a-zA-Z0-9_] 匹配单词字符 即a-z,A-Z,0-9,_
\W==[^a-zA-Z0-9_] 匹配非单词字符
* 匹配前一个字符出现0次或者无限次,即可有可无 abc* ab abcccccc... | [
"re.compile"
] | [((753, 784), 're.compile', 're.compile', (['"""^1[345678]\\\\d{9}$"""'], {}), "('^1[345678]\\\\d{9}$')\n", (763, 784), False, 'import re\n'), ((979, 1008), 're.compile', 're.compile', (['"""(http://.+?/).*"""'], {}), "('(http://.+?/).*')\n", (989, 1008), False, 'import re\n'), ((1064, 1093), 're.compile', 're.compile'... |
import RPi.GPIO as GPIO
import time
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
BUZZER = 20 #GPIO for buzzer
GPIO.setup(BUZZER, GPIO.OUT)
# Sounds the buzzer for 1 second when invoked
def sound_buzzer():
GPIO.output(BUZZER, True)
time.sleep(1)
GPIO.output(BUZZER, False)
| [
"RPi.GPIO.setup",
"RPi.GPIO.output",
"RPi.GPIO.setwarnings",
"time.sleep",
"RPi.GPIO.setmode"
] | [((38, 61), 'RPi.GPIO.setwarnings', 'GPIO.setwarnings', (['(False)'], {}), '(False)\n', (54, 61), True, 'import RPi.GPIO as GPIO\n'), ((63, 85), 'RPi.GPIO.setmode', 'GPIO.setmode', (['GPIO.BCM'], {}), '(GPIO.BCM)\n', (75, 85), True, 'import RPi.GPIO as GPIO\n'), ((116, 144), 'RPi.GPIO.setup', 'GPIO.setup', (['BUZZER', ... |
from datetime import timedelta
from sqlalchemy import func, case, text
from app import db, app
from app.models import OckovaciMistoMetriky, OckovaniRegistrace, OckovaniLide, Populace, CrMetriky, OckovaniDistribuce, \
Vakcina
class CrMetricsEtl:
"""Class for computing metrics for whole Czech republic."""
... | [
"app.app.logger.info",
"sqlalchemy.text",
"sqlalchemy.func.sum",
"sqlalchemy.case",
"app.models.CrMetriky",
"datetime.timedelta"
] | [((1976, 2038), 'app.app.logger.info', 'app.logger.info', (['"""Computing cr metrics - population finished."""'], {}), "('Computing cr metrics - population finished.')\n", (1991, 2038), False, 'from app import db, app\n'), ((3046, 3111), 'app.app.logger.info', 'app.logger.info', (['"""Computing cr metrics - registratio... |
import sys
sys.path.append("..")
from faigen.data.sequence import Dna2VecList,regex_filter
import pandas as pd
import numpy as np
import os
from functools import partial
import configargparse
from pathlib import Path
from Bio.SeqRecord import SeqRecord
import yaml
from pathlib import Path
import os
from shutil import c... | [
"os.path.exists",
"os.makedirs",
"pathlib.Path",
"numpy.asarray",
"configargparse.get_argument_parser",
"shutil.copy",
"sys.path.append"
] | [((11, 32), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (26, 32), False, 'import sys\n'), ((872, 908), 'configargparse.get_argument_parser', 'configargparse.get_argument_parser', ([], {}), '()\n', (906, 908), False, 'import configargparse\n'), ((1762, 1827), 'pathlib.Path', 'Path', (['"""/home... |
import libtcodpy as libtcod
class Wall:
def __init__(self, x, y, char, color, length, dir):
self.x = x
self.y = y
self.char = char
self.color = color
self.length = length
self.dir = dir
def draw(self):
tempx = self.x
tempy = self.y
for in... | [
"libtcodpy.console_set_default_foreground",
"libtcodpy.console_put_char"
] | [((357, 410), 'libtcodpy.console_set_default_foreground', 'libtcod.console_set_default_foreground', (['(0)', 'self.color'], {}), '(0, self.color)\n', (395, 410), True, 'import libtcodpy as libtcod\n'), ((423, 495), 'libtcodpy.console_put_char', 'libtcod.console_put_char', (['(0)', 'tempx', 'tempy', 'self.char', 'libtco... |
import flask
from flask import request
from flask import render_template
from .web_support import *
from .cli import cli
#####################################################################
# STARING NEW FLASK SKELETON (Task 2 - flask)
#check the config
class LabelordWeb(flask.Flask):
"""
The class represent... | [
"flask.render_template"
] | [((3258, 3306), 'flask.render_template', 'flask.render_template', (['"""index.html"""'], {'repos': 'repos'}), "('index.html', repos=repos)\n", (3279, 3306), False, 'import flask\n')] |
"""A pickleable wrapper for sharing NumPy ndarrays between processes using multiprocessing shared memory."""
import numpy as np
import multiprocessing.shared_memory as shm
class SharedNDArray:
"""Creates a new SharedNDArray, a pickleable wrapper for sharing NumPy ndarrays between
processes using multiprocess... | [
"numpy.prod",
"numpy.dtype",
"numpy.ndarray",
"multiprocessing.shared_memory.SharedMemory"
] | [((1652, 1702), 'numpy.ndarray', 'np.ndarray', (['shape', 'dtype', 'self._shm.buf'], {'order': '"""C"""'}), "(shape, dtype, self._shm.buf, order='C')\n", (1662, 1702), True, 'import numpy as np\n'), ((1523, 1545), 'multiprocessing.shared_memory.SharedMemory', 'shm.SharedMemory', (['name'], {}), '(name)\n', (1539, 1545)... |
from flask_jwt_extended import JWTManager
from flask_bcrypt import Bcrypt
jwt = JWTManager()
bcrypt = Bcrypt() | [
"flask_bcrypt.Bcrypt",
"flask_jwt_extended.JWTManager"
] | [((81, 93), 'flask_jwt_extended.JWTManager', 'JWTManager', ([], {}), '()\n', (91, 93), False, 'from flask_jwt_extended import JWTManager\n'), ((103, 111), 'flask_bcrypt.Bcrypt', 'Bcrypt', ([], {}), '()\n', (109, 111), False, 'from flask_bcrypt import Bcrypt\n')] |
import torch
import argparse
import numpy as np
import sys
sys.path.insert(0, "/home/jwieting/min-risk-cl-simile/min-risk")
from fairseq.tasks.sim_utils import Example
from fairseq.tasks.sim_models import WordAveraging
from sacremoses import MosesDetokenizer
parser = argparse.ArgumentParser()
parser.add_argument('--... | [
"numpy.mean",
"sys.path.insert",
"argparse.ArgumentParser",
"sacremoses.MosesDetokenizer",
"torch.load",
"fairseq.tasks.sim_models.WordAveraging"
] | [((60, 124), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""/home/jwieting/min-risk-cl-simile/min-risk"""'], {}), "(0, '/home/jwieting/min-risk-cl-simile/min-risk')\n", (75, 124), False, 'import sys\n'), ((271, 296), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (294, 296), False, 'import ... |
from django.forms import ModelForm, forms
from django import forms
from .models import User
from django.contrib.auth.forms import UserCreationForm
class UserCreateForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ("username", "email", "<PASSWORD... | [
"django.forms.EmailField",
"django.forms.CharField",
"django.forms.ValidationError"
] | [((201, 232), 'django.forms.EmailField', 'forms.EmailField', ([], {'required': '(True)'}), '(required=True)\n', (217, 232), False, 'from django import forms\n'), ((940, 1004), 'django.forms.CharField', 'forms.CharField', ([], {'required': '(True)', 'label': '"""Kullanici Adi veya Email"""'}), "(required=True, label='Ku... |
import unittest
import sys
import os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__),
os.pardir)))
import housinginsights.tools.misc as misc_tools
class ToolsMiscTestCase(unittest.TestCase):
def test_get_unique_addresses_from_str(self):
... | [
"unittest.main",
"housinginsights.tools.misc.get_unique_addresses_from_str",
"os.path.dirname"
] | [((22258, 22273), 'unittest.main', 'unittest.main', ([], {}), '()\n', (22271, 22273), False, 'import unittest\n'), ((703, 756), 'housinginsights.tools.misc.get_unique_addresses_from_str', 'misc_tools.get_unique_addresses_from_str', (['address_str'], {}), '(address_str)\n', (743, 756), True, 'import housinginsights.tool... |
from django.shortcuts import render
import pandas as pd
from dashboard.models import Utilization, Samples, Revenue, monthlystats
from dashboard.serializers import UtilizationSerializer, SamplesSerializer, RevenueSerializer, monthlystatsSerializer
from dashboard.viewfuncs import index_context, sample_context, util_conte... | [
"dashboard.serializers.monthlystatsSerializer",
"django.shortcuts.render",
"pandas.DataFrame",
"dashboard.models.Samples.objects.all",
"dashboard.serializers.SamplesSerializer",
"dashboard.models.Utilization.objects.all",
"dashboard.viewfuncs.sample_context",
"dashboard.viewfuncs.util_context",
"das... | [((410, 431), 'dashboard.models.Samples.objects.all', 'Samples.objects.all', ([], {}), '()\n', (429, 431), False, 'from dashboard.models import Utilization, Samples, Revenue, monthlystats\n'), ((450, 471), 'dashboard.models.Revenue.objects.all', 'Revenue.objects.all', ([], {}), '()\n', (469, 471), False, 'from dashboar... |
# -*- coding: utf-8
# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose with or without fee is hereby granted,
# provided that the above c... | [
"base64.b64decode"
] | [((2436, 2492), 'base64.b64decode', 'base64.b64decode', (['"""KEYKEYKEYKEYKEYKEYKEYKEYKEYKEYKEYKEY"""'], {}), "('KEYKEYKEYKEYKEYKEYKEYKEYKEYKEYKEYKEY')\n", (2452, 2492), False, 'import base64\n'), ((2509, 2561), 'base64.b64decode', 'base64.b64decode', (['"""OTHEROTHEROTHEROTHEROTHEROTHEROT"""'], {}), "('OTHEROTHEROTHER... |
import argparse, sys, json, yaml
import pandas as pd
import asyncio
from iotsim.utils import to_iterable
from iotsim.runtime.destinations import known_destinations
from iotsim.assembler import from_config
if __name__ != '__main__':
sys.exit("This program must be run as a standalone script")
parser = argparse.A... | [
"asyncio.sleep",
"argparse.ArgumentParser",
"pandas.Timedelta",
"json.dumps",
"yaml.load",
"iotsim.assembler.from_config",
"sys.exit",
"pandas.Timestamp",
"asyncio.get_event_loop",
"iotsim.utils.to_iterable"
] | [((310, 364), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Assembly runner"""'}), "(description='Assembly runner')\n", (333, 364), False, 'import argparse, sys, json, yaml\n'), ((2686, 2728), 'iotsim.assembler.from_config', 'from_config', (['args.assembly_config_filename'], {}), '(args... |
from pyspark import SparkContext
from pyspark.sql import SQLContext
sc = SparkContext("local", appName="mysqltest")
sqlContext = SQLContext(sc)
df = sqlContext.read.format("jdbc").options(
url="jdbc:neo4j://192.168.10.74:7687?password=<PASSWORD>&"
"useUnicode=true&characterEncoding=utf-8&useJDBCCompliantT... | [
"pyspark.SparkContext",
"pyspark.sql.SQLContext"
] | [((75, 117), 'pyspark.SparkContext', 'SparkContext', (['"""local"""'], {'appName': '"""mysqltest"""'}), "('local', appName='mysqltest')\n", (87, 117), False, 'from pyspark import SparkContext\n'), ((131, 145), 'pyspark.sql.SQLContext', 'SQLContext', (['sc'], {}), '(sc)\n', (141, 145), False, 'from pyspark.sql import SQ... |
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="rp3_dcache",
version="0.3",
author="<NAME>",
author_email="<EMAIL>",
description="Cache to dope the result retrieval from reaction rules, to be used with RetroPath 3.0"... | [
"setuptools.find_packages"
] | [((473, 499), 'setuptools.find_packages', 'setuptools.find_packages', ([], {}), '()\n', (497, 499), False, 'import setuptools\n')] |
# -*- coding: UTF-8 -*-
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
from django.db import connection
class cmdbDao(object):
def getDbInstanceList(self, search_key, offset, limit):
cursor = connection.cursor()
if search_key == "" or search_key is None:
sql = "select c... | [
"django.db.connection.cursor",
"pymysql.install_as_MySQLdb"
] | [((41, 69), 'pymysql.install_as_MySQLdb', 'pymysql.install_as_MySQLdb', ([], {}), '()\n', (67, 69), False, 'import pymysql\n'), ((222, 241), 'django.db.connection.cursor', 'connection.cursor', ([], {}), '()\n', (239, 241), False, 'from django.db import connection\n')] |
import os
from blasy.blasy import PluginManager
class TestLoadingPlugin:
# TODO: recursive, category
def test_can_find_plugins_from_dir(self):
pm = PluginManager(plugin_info_ext="testplug")
test_dir = os.path.dirname(__file__)
test_data_dir = os.path.join(test_dir, "data")
... | [
"blasy.blasy.PluginManager",
"os.path.dirname",
"os.path.join"
] | [((170, 211), 'blasy.blasy.PluginManager', 'PluginManager', ([], {'plugin_info_ext': '"""testplug"""'}), "(plugin_info_ext='testplug')\n", (183, 211), False, 'from blasy.blasy import PluginManager\n'), ((232, 257), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (247, 257), False, 'import os\n... |
from flask_restplus import Namespace, Resource, fields
from ..dao import DAO, jobs_dao
from ..service.job_runner import job_runner_service
api = Namespace('job_runner', description='JobRunner related operations')
job_runner_status_model = api.model('JobRunnerStatus', {
'state': fields.String(required=True, descr... | [
"flask_restplus.fields.String",
"flask_restplus.Namespace",
"flask_restplus.fields.List"
] | [((146, 213), 'flask_restplus.Namespace', 'Namespace', (['"""job_runner"""'], {'description': '"""JobRunner related operations"""'}), "('job_runner', description='JobRunner related operations')\n", (155, 213), False, 'from flask_restplus import Namespace, Resource, fields\n'), ((286, 355), 'flask_restplus.fields.String... |
import logging
import os
from tempfile import NamedTemporaryFile
import hydra
import torch
from flask import Flask, request, jsonify
from hydra.core.config_store import ConfigStore
from deepspeech_pytorch.configs.inference_config import ServerConfig
from deepspeech_pytorch.inference import run_transcribe
from deepspe... | [
"logging.getLogger",
"deepspeech_pytorch.inference.run_transcribe",
"hydra.main",
"flask.Flask",
"flask.jsonify",
"deepspeech_pytorch.utils.load_model",
"os.path.splitext",
"logging.info",
"tempfile.NamedTemporaryFile",
"deepspeech_pytorch.utils.load_decoder",
"hydra.core.config_store.ConfigStor... | [((445, 460), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (450, 460), False, 'from flask import Flask, request, jsonify\n'), ((527, 549), 'hydra.core.config_store.ConfigStore.instance', 'ConfigStore.instance', ([], {}), '()\n', (547, 549), False, 'from hydra.core.config_store import ConfigStore\n'), ((1... |
import numpy as np
from collections import defaultdict
class Agent:
def __init__(self, nA=6, epsilon=1.,alpha=0.2, gamma=1.,episode=1):
""" Initialize agent.
Params
======
- nA: number of actions available to the agent
"""
self.nA = nA
self.Q = defaultdict(... | [
"numpy.zeros",
"numpy.argmax",
"numpy.arange",
"numpy.max"
] | [((2215, 2241), 'numpy.max', 'np.max', (['self.Q[next_state]'], {}), '(self.Q[next_state])\n', (2221, 2241), True, 'import numpy as np\n'), ((328, 345), 'numpy.zeros', 'np.zeros', (['self.nA'], {}), '(self.nA)\n', (336, 345), True, 'import numpy as np\n'), ((983, 1001), 'numpy.arange', 'np.arange', (['self.nA'], {}), '... |
# -*- coding: utf-8 -*-
import json
from TM1py.Objects.User import User
from TM1py.Services.ObjectService import ObjectService
class SecurityService(ObjectService):
""" Service to handle Security stuff
"""
def __init__(self, rest):
super().__init__(rest)
def create_user(self, user):
... | [
"TM1py.Objects.User.User.from_json",
"json.loads",
"TM1py.Objects.User.User.from_dict"
] | [((804, 828), 'TM1py.Objects.User.User.from_json', 'User.from_json', (['response'], {}), '(response)\n', (818, 828), False, 'from TM1py.Objects.User import User\n'), ((1766, 1786), 'json.loads', 'json.loads', (['response'], {}), '(response)\n', (1776, 1786), False, 'import json\n'), ((2219, 2239), 'json.loads', 'json.l... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "<NAME>"
__doc__ = r"""
Created on 16-09-2020
"""
def main():
""" """
# from draugr import TerminalPlotWriter
from draugr.drawers import SeriesScrollPlot
import psutil
# psutil.virtual_memory() # gives an object w... | [
"draugr.drawers.SeriesScrollPlot",
"psutil.cpu_percent"
] | [((649, 715), 'draugr.drawers.SeriesScrollPlot', 'SeriesScrollPlot', ([], {'window_length': '(100)', 'reverse': '(False)', 'overwrite': '(True)'}), '(window_length=100, reverse=False, overwrite=True)\n', (665, 715), False, 'from draugr.drawers import SeriesScrollPlot\n'), ((747, 767), 'psutil.cpu_percent', 'psutil.cpu_... |
"""FEMTO dataset."""
import os
from pathlib import Path
import itertools
import json
import numpy as np
import tensorflow as tf
import tensorflow_datasets as tfds
import pandas as pd
# from scipy.io import loadmat
_DESCRIPTION = """
FEMTO-ST bearing dataset used in the IEEE PHM 2012 Data Challenge for RUL (remaining... | [
"pandas.read_csv",
"tensorflow_datasets.features.Tensor",
"pathlib.Path",
"os.path.join",
"tensorflow_datasets.core.Version",
"numpy.array",
"tensorflow_datasets.download.Resource"
] | [((3092, 3118), 'tensorflow_datasets.core.Version', 'tfds.core.Version', (['"""1.0.0"""'], {}), "('1.0.0')\n", (3109, 3118), True, 'import tensorflow_datasets as tfds\n'), ((4707, 4798), 'tensorflow_datasets.download.Resource', 'tfds.download.Resource', ([], {'url': '_DATA_URLS', 'extract_method': 'tfds.download.Extrac... |
import sys
from pyramid.config import Configurator
from pyramid.i18n import get_localizer, TranslationStringFactory
from pyramid.threadlocal import get_current_request
def add_renderer_globals(event):
request = event.get('request')
if request is None:
request = get_current_request()
event['_'] ... | [
"pyramid.threadlocal.get_current_request",
"pyramid.i18n.TranslationStringFactory"
] | [((779, 819), 'pyramid.i18n.TranslationStringFactory', 'TranslationStringFactory', (['default_domain'], {}), '(default_domain)\n', (803, 819), False, 'from pyramid.i18n import get_localizer, TranslationStringFactory\n'), ((282, 303), 'pyramid.threadlocal.get_current_request', 'get_current_request', ([], {}), '()\n', (3... |
import os
def enum(icon_path, vscode_path, callback):
# function exit
if not os.path.isdir(icon_path):
print('Error: "', icon_path, '" is not a directory or does not exist.')
return
# exec callback recursively
list_dirs = os.walk(icon_path)
for root, dirs, files in list_dirs:
for d in dirs:
enum(os.pat... | [
"os.path.isdir",
"os.path.join",
"os.walk"
] | [((233, 251), 'os.walk', 'os.walk', (['icon_path'], {}), '(icon_path)\n', (240, 251), False, 'import os\n'), ((81, 105), 'os.path.isdir', 'os.path.isdir', (['icon_path'], {}), '(icon_path)\n', (94, 105), False, 'import os\n'), ((314, 335), 'os.path.join', 'os.path.join', (['root', 'd'], {}), '(root, d)\n', (326, 335), ... |
from OpenAttack import substitute
import sys, os
sys.path.insert(0, os.path.join(
os.path.dirname(os.path.abspath(__file__)),
".."
))
import OpenAttack
def get_attackers_on_chinese(dataset, clsf):
triggers = OpenAttack.attackers.UATAttacker.get_triggers(clsf, dataset, clsf.tokenizer)
attackers = ... | [
"OpenAttack.attackers.TextBuggerAttacker",
"OpenAttack.attackers.GeneticAttacker",
"OpenAttack.attackers.UATAttacker.get_triggers",
"OpenAttack.attackers.UATAttacker",
"OpenAttack.attackers.PWWSAttacker",
"OpenAttack.attackers.PSOAttacker",
"os.path.abspath",
"OpenAttack.attackers.FDAttacker"
] | [((226, 302), 'OpenAttack.attackers.UATAttacker.get_triggers', 'OpenAttack.attackers.UATAttacker.get_triggers', (['clsf', 'dataset', 'clsf.tokenizer'], {}), '(clsf, dataset, clsf.tokenizer)\n', (271, 302), False, 'import OpenAttack\n'), ((330, 403), 'OpenAttack.attackers.FDAttacker', 'OpenAttack.attackers.FDAttacker', ... |
from datetime import datetime
from notifications_utils.template import SMSMessageTemplate
from app import statsd_client
from app.celery.service_callback_tasks import send_delivery_status_to_service
from app.config import QueueNames
from app.dao import notifications_dao
from app.dao.notifications_dao import dao_update... | [
"notifications_utils.template.SMSMessageTemplate",
"datetime.datetime.utcnow",
"app.dao.notifications_dao.dao_update_notification",
"app.dao.templates_dao.dao_get_template_by_id",
"app.notifications.callbacks.create_delivery_status_callback_data",
"app.dao.service_callback_api_dao.get_service_delivery_sta... | [((2570, 2607), 'app.dao.notifications_dao.dao_update_notification', 'dao_update_notification', (['notification'], {}), '(notification)\n', (2593, 2607), False, 'from app.dao.notifications_dao import dao_update_notification\n'), ((1364, 1443), 'app.dao.templates_dao.dao_get_template_by_id', 'dao_get_template_by_id', ([... |
from django.test import TestCase
from georiviere.description.models import Morphology, Status
from georiviere.river.tests.factories import StreamFactory
class SignalRiverTest(TestCase):
def test_create_stream_generate_topologies(self):
stream = StreamFactory.create()
self.assertEqual(str(stream),... | [
"georiviere.description.models.Status.objects.get",
"georiviere.river.tests.factories.StreamFactory.create",
"georiviere.description.models.Morphology.objects.get",
"georiviere.description.models.Status.objects.values_list",
"georiviere.description.models.Morphology.objects.values_list"
] | [((260, 282), 'georiviere.river.tests.factories.StreamFactory.create', 'StreamFactory.create', ([], {}), '()\n', (280, 282), False, 'from georiviere.river.tests.factories import StreamFactory\n'), ((402, 426), 'georiviere.description.models.Morphology.objects.get', 'Morphology.objects.get', ([], {}), '()\n', (424, 426)... |
import codecs
import functools
import sys
from django import forms
from django.core import checks, exceptions, validators
from django.db import models
from django.utils.encoding import force_bytes
from six import integer_types, text_type
from six.moves import reduce
from django.utils.translation import ugettext_lazy a... | [
"django.utils.translation.ugettext_lazy",
"django.db.models.Field.deconstruct",
"django.core.validators.MaxValueValidator",
"django.db.models.Field.value_to_string",
"sys.platform.startswith",
"django.core.exceptions.ValidationError",
"django.utils.encoding.force_bytes",
"functools.partial",
"django... | [((730, 761), 'sys.platform.startswith', 'sys.platform.startswith', (['"""java"""'], {}), "('java')\n", (753, 761), False, 'import sys\n'), ((1071, 1108), 'codecs.decode', 'codecs.decode', (['hex_value', '"""hex_codec"""'], {}), "(hex_value, 'hex_codec')\n", (1084, 1108), False, 'import codecs\n'), ((1900, 1912), 'djan... |
#!/usr/bin/env python
import os
import shutil
import sys
import sleemo
from setuptools import Command, find_packages, setup
if sys.argv[-1] == "publish":
os.system("python setup.py upload")
sys.exit()
class UploadCommand(Command):
user_options = []
def initialize_options(self): pass
def final... | [
"setuptools.find_packages",
"os.path.join",
"setuptools.setup",
"os.path.dirname",
"sys.exit",
"os.system"
] | [((1576, 1598), 'setuptools.setup', 'setup', ([], {}), '(**setup_options)\n', (1581, 1598), False, 'from setuptools import Command, find_packages, setup\n'), ((161, 196), 'os.system', 'os.system', (['"""python setup.py upload"""'], {}), "('python setup.py upload')\n", (170, 196), False, 'import os\n'), ((201, 211), 'sy... |
import sys
import tempfile
from qgis.core import (
QgsApplication,
QgsProcessingFeedback,
QgsVectorLayer,
QgsRasterLayer,
QgsProject
)
from qgis.analysis import QgsNativeAlgorithms
import argparse
from pathlib import Path
parser = argparse.ArgumentParser(description="Prepare the houston d... | [
"osgeo.gdal.Open",
"qgis.analysis.QgsNativeAlgorithms",
"processing.run",
"qgis.core.QgsRasterLayer",
"argparse.ArgumentParser",
"pathlib.Path",
"processing.core.Processing.Processing.initialize",
"qgis.core.QgsApplication.processingRegistry",
"qgis.core.QgsApplication.setPrefixPath",
"qgis.core.Q... | [((262, 340), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Prepare the houston dataset for roadnet"""'}), "(description='Prepare the houston dataset for roadnet')\n", (285, 340), False, 'import argparse\n'), ((584, 626), 'qgis.core.QgsApplication.setPrefixPath', 'QgsApplication.setPref... |
import math
import cv2
import numpy as np
from PIL import Image
from skimage import exposure
from DataToCloud import dataToCloud
def calc_projection_image (ptCloud, pcloud, messyValidRGB):
ptCloudPoints = np.asarray(ptCloud.points)
validIndices = np.argwhere(
np.isfinite(ptCloudPoints[:, 0]) & np.i... | [
"math.floor",
"numpy.column_stack",
"numpy.isfinite",
"numpy.arange",
"numpy.multiply",
"cv2.threshold",
"numpy.asarray",
"numpy.max",
"numpy.unravel_index",
"numpy.concatenate",
"cv2.add",
"numpy.abs",
"cv2.warpAffine",
"skimage.exposure.rescale_intensity",
"cv2.cvtColor",
"cv2.getRot... | [((214, 240), 'numpy.asarray', 'np.asarray', (['ptCloud.points'], {}), '(ptCloud.points)\n', (224, 240), True, 'import numpy as np\n'), ((447, 466), 'numpy.arange', 'np.arange', (['(0)', 'count'], {}), '(0, count)\n', (456, 466), True, 'import numpy as np\n'), ((480, 552), 'numpy.unravel_index', 'np.unravel_index', (['... |
from . import stack
from oslo_versionedobjects import base
from oslo_versionedobjects import fields
class SubObject(fields.FieldType):
def __init__(self, obj_names, **kwargs):
self._obj_names = obj_names
super(SubObject, self).__init__(**kwargs)
def coerce(self, obj, attr, value):
t... | [
"oslo_versionedobjects.base.VersionedObject.obj_from_primitive",
"oslo_versionedobjects.fields.ObjectField",
"oslo_versionedobjects.fields.DateTimeField"
] | [((1184, 1248), 'oslo_versionedobjects.base.VersionedObject.obj_from_primitive', 'obj_base.VersionedObject.obj_from_primitive', (['value', 'obj._context'], {}), '(value, obj._context)\n', (1227, 1248), True, 'from oslo_versionedobjects import base as obj_base\n'), ((2420, 2455), 'oslo_versionedobjects.fields.DateTimeFi... |
import json
import logging
from logging.config import dictConfig
from os.path import dirname, abspath, join, realpath
import requests
from ..config import LogConfig
log_name = 'get_proxies'
base_dir = dirname(dirname(dirname(realpath(__file__))))
log_file = abspath(join(base_dir, 'Log/%s.log' % log_name))
log_config =... | [
"logging.getLogger",
"json.loads",
"logging.config.dictConfig",
"json.dumps",
"os.path.join",
"requests.get",
"os.path.realpath"
] | [((361, 383), 'logging.config.dictConfig', 'dictConfig', (['log_config'], {}), '(log_config)\n', (371, 383), False, 'from logging.config import dictConfig\n'), ((393, 420), 'logging.getLogger', 'logging.getLogger', (['log_name'], {}), '(log_name)\n', (410, 420), False, 'import logging\n'), ((267, 306), 'os.path.join', ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_emclpy
----------------------------------
Tests for `emclpy` module.
"""
import unittest
import os
import time
import emclpy
# Environments for testing.
# Set url appropriately before running tests.
testing_environment = {'dev': 'https://localhost:7799/em',
... | [
"emclpy.command_runner",
"os.path.join",
"time.sleep",
"emclpy.Emclpy",
"unittest.main"
] | [((584, 622), 'emclpy.Emclpy', 'emclpy.Emclpy', (['url', 'username', 'password'], {}), '(url, username, password)\n', (597, 622), False, 'import emclpy\n'), ((816, 854), 'emclpy.Emclpy', 'emclpy.Emclpy', (['url', 'username', 'password'], {}), '(url, username, password)\n', (829, 854), False, 'import emclpy\n'), ((1127,... |
import torch, torchvision
class CIFAR10(torchvision.datasets.CIFAR10):
def __init__(self, root, part, labeled_factors, transform):
super().__init__(root, part == 'train', transform = transform, download = True)
if len(labeled_factors) == 0:
self.has_label = False
self.nclass = []
self.class_freq = []
... | [
"torch.tensor"
] | [((589, 611), 'torch.tensor', 'torch.tensor', (['[target]'], {}), '([target])\n', (601, 611), False, 'import torch, torchvision\n'), ((391, 417), 'torch.tensor', 'torch.tensor', (['self.targets'], {}), '(self.targets)\n', (403, 417), False, 'import torch, torchvision\n')] |
import numpy as np
from scipy.interpolate import RectBivariateSpline
def TemplateCorrection(T, It1, rect, p0 = np.zeros(2)):
threshold = 0.1
x1_t, y1_t, x2_t, y2_t = rect[0], rect[1], rect[2], rect[3]
Iy, Ix = np.gradient(It1)
rows_img, cols_img = It1.shape
rows_rect, cols_rect = T.sh... | [
"scipy.interpolate.RectBivariateSpline",
"numpy.square",
"numpy.array",
"numpy.zeros",
"numpy.linspace",
"numpy.linalg.inv",
"numpy.meshgrid",
"numpy.gradient",
"numpy.arange"
] | [((115, 126), 'numpy.zeros', 'np.zeros', (['(2)'], {}), '(2)\n', (123, 126), True, 'import numpy as np\n'), ((229, 245), 'numpy.gradient', 'np.gradient', (['It1'], {}), '(It1)\n', (240, 245), True, 'import numpy as np\n'), ((401, 426), 'numpy.arange', 'np.arange', (['(0)', 'rows_img', '(1)'], {}), '(0, rows_img, 1)\n',... |
#!/usr/bin/env python
"""Analyze how important a Unicode block is for the different languages."""
# core modules
import logging
# 3rd party modules
import click
import numpy as np
# internal modules
from lidtk.data import wili
@click.command(name='analyze-unicode-block', help=__doc__)
@click.option('--start', de... | [
"click.option",
"numpy.array",
"lidtk.data.wili.load_data",
"click.command",
"logging.info"
] | [((235, 292), 'click.command', 'click.command', ([], {'name': '"""analyze-unicode-block"""', 'help': '__doc__'}), "(name='analyze-unicode-block', help=__doc__)\n", (248, 292), False, 'import click\n'), ((294, 349), 'click.option', 'click.option', (['"""--start"""'], {'default': '(123)', 'show_default': '(True)'}), "('-... |
import string
from utils import clean_word
# {'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5, 'F': 6, 'G': 7, 'H': 8, 'I': 9,
# 'J': 10, 'K': 11, 'L': 12, 'M': 13, 'N': 14, 'O': 15, 'P': 16, 'Q': 17, 'R': 18,
# 'S': 19, 'T': 20, 'U': 21, 'V': 22, 'W': 23, 'X': 24, 'Y': 25, 'Z': 26, ' ': 0}
letter_to_value = {letter: index ... | [
"utils.clean_word"
] | [((935, 951), 'utils.clean_word', 'clean_word', (['word'], {}), '(word)\n', (945, 951), False, 'from utils import clean_word\n')] |
from django.core.management.base import BaseCommand, CommandError
from dashboard.models import Bin, Dataset
class Command(BaseCommand):
"""for testing only!!"""
help = 'delete all bins'
def add_arguments(self, parser):
parser.add_argument('-ds', '--dataset', type=str, help='name of dataset')... | [
"dashboard.models.Bin.objects.all",
"dashboard.models.Dataset.objects.get"
] | [((452, 485), 'dashboard.models.Dataset.objects.get', 'Dataset.objects.get', ([], {'name': 'ds_name'}), '(name=ds_name)\n', (471, 485), False, 'from dashboard.models import Bin, Dataset\n'), ((547, 564), 'dashboard.models.Bin.objects.all', 'Bin.objects.all', ([], {}), '()\n', (562, 564), False, 'from dashboard.models i... |
"""Main module."""
import pandas as pd
import numpy as np
import re
import os
from shipflowmotionshelpers import errors
def _load_time_series(file_path:str)->pd.DataFrame:
"""Load time series from ShipFlowMotions into a pandas data frame
Parameters
----------
file_path : str
Where is the moti... | [
"pandas.Series",
"pandas.read_csv",
"shipflowmotionshelpers.errors.TimeSeriesFilePathError",
"os.path.splitext",
"os.path.split",
"numpy.deg2rad",
"pandas.DataFrame",
"re.sub",
"re.findall",
"os.path.abspath"
] | [((437, 464), 'os.path.splitext', 'os.path.splitext', (['file_path'], {}), '(file_path)\n', (453, 464), False, 'import os\n'), ((715, 735), 'numpy.deg2rad', 'np.deg2rad', (["df['V4']"], {}), "(df['V4'])\n", (725, 735), True, 'import numpy as np\n'), ((754, 774), 'numpy.deg2rad', 'np.deg2rad', (["df['A4']"], {}), "(df['... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import numpy as np
import common
def load_json(filename):
with open(filename, "r") as f:
return json.load(f)
def load_data(filename):
j = load_json(filename)
return np.array(j["h_max"]), np.array(j["L2Error"]), np.array(j["H1Error"])
d... | [
"numpy.sqrt",
"numpy.log",
"numpy.array",
"common.plotLogLogData",
"json.load"
] | [((609, 643), 'numpy.sqrt', 'np.sqrt', (['(L2err1 ** 2 + H1err1 ** 2)'], {}), '(L2err1 ** 2 + H1err1 ** 2)\n', (616, 643), True, 'import numpy as np\n'), ((651, 685), 'numpy.sqrt', 'np.sqrt', (['(L2err2 ** 2 + H1err2 ** 2)'], {}), '(L2err2 ** 2 + H1err2 ** 2)\n', (658, 685), True, 'import numpy as np\n'), ((1847, 1922)... |
from django.urls import path
from . import views
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('', views.index, name='index'),
path('section/<int:section_id>', views.detail, name='section'),
path('userinfo/<int:user_id>', views.user_info, name='userinfo'),... | [
"django.urls.path"
] | [((146, 181), 'django.urls.path', 'path', (['""""""', 'views.index'], {'name': '"""index"""'}), "('', views.index, name='index')\n", (150, 181), False, 'from django.urls import path\n'), ((187, 249), 'django.urls.path', 'path', (['"""section/<int:section_id>"""', 'views.detail'], {'name': '"""section"""'}), "('section/... |
import subprocess
def test_pipeline():
subprocess.check_call(["snakemake", "-n", "--configfile", "config.yaml"])
| [
"subprocess.check_call"
] | [((45, 118), 'subprocess.check_call', 'subprocess.check_call', (["['snakemake', '-n', '--configfile', 'config.yaml']"], {}), "(['snakemake', '-n', '--configfile', 'config.yaml'])\n", (66, 118), False, 'import subprocess\n')] |
from setuptools import setup
setup(
name='argulib',
version='0.1',
packages=['test', 'argulib'],
url='https://github.com/roman-kutlak/argulib',
license='BSD',
author='<NAME>',
author_email='<EMAIL>',
description='A simple library for formal argumentation',
install_requires=[
... | [
"setuptools.setup"
] | [((30, 308), 'setuptools.setup', 'setup', ([], {'name': '"""argulib"""', 'version': '"""0.1"""', 'packages': "['test', 'argulib']", 'url': '"""https://github.com/roman-kutlak/argulib"""', 'license': '"""BSD"""', 'author': '"""<NAME>"""', 'author_email': '"""<EMAIL>"""', 'description': '"""A simple library for formal ar... |
import logging
import tempfile
import unittest
from os import path
from Bio import SeqIO
from staramr.blast.JobHandler import JobHandler
from staramr.blast.plasmidfinder.PlasmidfinderBlastDatabase import PlasmidfinderBlastDatabase
from staramr.blast.resfinder.ResfinderBlastDatabase import ResfinderBlastDatabase
from ... | [
"logging.getLogger",
"tempfile.TemporaryDirectory",
"staramr.databases.AMRDatabasesManager.AMRDatabasesManager.create_default_manager",
"staramr.blast.JobHandler.JobHandler",
"staramr.blast.resfinder.ResfinderBlastDatabase.ResfinderBlastDatabase",
"os.path.join",
"os.path.dirname",
"staramr.detection.... | [((667, 704), 'logging.getLogger', 'logging.getLogger', (['"""AMRDetectionMLST"""'], {}), "('AMRDetectionMLST')\n", (684, 704), False, 'import logging\n'), ((1215, 1257), 'staramr.blast.resfinder.ResfinderBlastDatabase.ResfinderBlastDatabase', 'ResfinderBlastDatabase', (['self.resfinder_dir'], {}), '(self.resfinder_dir... |
import pytest
from datetime import datetime
from server import create_app, config
from server.resources import db as _db
from server.resources.models import User, Profile
from server.resources.utils import Serializer
''' Session-wide test application. '''
@pytest.yield_fixture(scope='session')
def app(request):
ap... | [
"server.resources.db.create_all",
"datetime.datetime.utcnow",
"server.resources.models.Profile",
"server.resources.db.engine.connect",
"pytest.yield_fixture",
"pytest.fixture",
"server.create_app",
"server.resources.models.User",
"server.resources.db.drop_all"
] | [((258, 295), 'pytest.yield_fixture', 'pytest.yield_fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (278, 295), False, 'import pytest\n'), ((438, 475), 'pytest.yield_fixture', 'pytest.yield_fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (458, 475), False, 'import pytest\n'), ((692... |
import twint
c = twint.Config()
c.Search = "#SouthChinaSea"
c.Since = "2021-01-01"
c.Until = "2021-06-30"
c.Verified = True
c.Index_tweets = "scs2"
c.Elasticsearch = "http://localhost:9200"
twint.run.Search(c) | [
"twint.Config",
"twint.run.Search"
] | [((18, 32), 'twint.Config', 'twint.Config', ([], {}), '()\n', (30, 32), False, 'import twint\n'), ((192, 211), 'twint.run.Search', 'twint.run.Search', (['c'], {}), '(c)\n', (208, 211), False, 'import twint\n')] |
from pkgutil import extend_path
from i3pystatus.core import Status
from i3pystatus.core.modules import Module, IntervalModule
from i3pystatus.core.settings import SettingsBase
from i3pystatus.core.util import formatp
import logging
import os
h = logging.FileHandler(".i3pystatus-" + str(os.getpid()), delay=True)
log... | [
"logging.getLogger",
"i3pystatus.core.Status",
"pkgutil.extend_path",
"i3pystatus.clock.Clock",
"os.getpid"
] | [((326, 357), 'logging.getLogger', 'logging.getLogger', (['"""i3pystatus"""'], {}), "('i3pystatus')\n", (343, 357), False, 'import logging\n'), ((426, 457), 'pkgutil.extend_path', 'extend_path', (['__path__', '__name__'], {}), '(__path__, __name__)\n', (437, 457), False, 'from pkgutil import extend_path\n'), ((621, 644... |
from django.db import models
from django.contrib.humanize.templatetags.humanize import naturaltime
from django.utils.html import escape, format_html
from config import models as config_models
from cached_property import cached_property
from utils import notify_slack
from django.dispatch import receiver
from django.db... | [
"django.db.models.FloatField",
"django.db.models.TextField",
"utils.notify_slack",
"django.db.models.ForeignKey",
"django.db.models.IntegerField",
"django.contrib.humanize.templatetags.humanize.naturaltime",
"django.db.models.ManyToManyField",
"django.utils.html.format_html",
"django.dispatch.receiv... | [((5101, 5133), 'django.dispatch.receiver', 'receiver', (['post_save'], {'sender': 'City'}), '(post_save, sender=City)\n', (5109, 5133), False, 'from django.dispatch import receiver\n'), ((5976, 6011), 'django.dispatch.receiver', 'receiver', (['post_save'], {'sender': 'Country'}), '(post_save, sender=Country)\n', (5984... |
# Generated by Django 3.2 on 2021-05-09 09:29
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Index', '0021_auto_20210509_1729'),
]
operations = [
migrations.AlterField(
model_name='indexheader',
name='header_sho... | [
"django.db.models.CharField"
] | [((355, 445), 'django.db.models.CharField', 'models.CharField', ([], {'default': '""""""', 'max_length': '(512)', 'verbose_name': '"""Header showcase descript"""'}), "(default='', max_length=512, verbose_name=\n 'Header showcase descript')\n", (371, 445), False, 'from django.db import migrations, models\n')] |
from distutils.core import setup, Extension
import os
setup (name = 'stdoutwriter',
version = '0.1',
description = 'Python wrapper for libmtester',
packages=[''],
package_dir={'':''},
package_data={'':['stdoutwriter.so']}
)
setup (name = 'adder',
version = '0.1',
... | [
"distutils.core.setup"
] | [((54, 226), 'distutils.core.setup', 'setup', ([], {'name': '"""stdoutwriter"""', 'version': '"""0.1"""', 'description': '"""Python wrapper for libmtester"""', 'packages': "['']", 'package_dir': "{'': ''}", 'package_data': "{'': ['stdoutwriter.so']}"}), "(name='stdoutwriter', version='0.1', description=\n 'Python wr... |
import boto3
from kaos_backend.constants import DOCKER_REGISTRY, REGION, CLOUD_PROVIDER
def get_login_command():
if CLOUD_PROVIDER == 'AWS':
# ecr = boto3.client('ecr', region_name=REGION)
#
# raw_auth_data = ecr.get_authorization_token()['authorizationData'][0]['authorizationToken']
... | [
"boto3.client"
] | [((750, 789), 'boto3.client', 'boto3.client', (['"""ecr"""'], {'region_name': 'REGION'}), "('ecr', region_name=REGION)\n", (762, 789), False, 'import boto3\n'), ((929, 968), 'boto3.client', 'boto3.client', (['"""ecr"""'], {'region_name': 'REGION'}), "('ecr', region_name=REGION)\n", (941, 968), False, 'import boto3\n')] |
# *****************************************************************************
# Copyright (c) 2021, Intel Corporation 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 ... | [
"numba.extending.register_model",
"numba.extending.models.OpaqueModel.__init__"
] | [((2427, 2453), 'numba.extending.register_model', 'register_model', (['SdcTypeRef'], {}), '(SdcTypeRef)\n', (2441, 2453), False, 'from numba.extending import models, register_model\n'), ((2560, 2607), 'numba.extending.models.OpaqueModel.__init__', 'models.OpaqueModel.__init__', (['self', 'dmm', 'fe_type'], {}), '(self,... |
#!/usr/bin/env python3
import sys
sys.path.append("..")
from auth import authorization_metadata
import os
import requests
endpoint = os.environ.get("VOICEKIT_ENDPOINT") or "api.tinkoff.ai:443"
api_key = os.environ["VOICEKIT_API_KEY"]
secret_key = os.environ["VOICEKIT_SECRET_KEY"]
metadata = authorization_metadata(... | [
"auth.authorization_metadata",
"sys.path.append",
"os.environ.get"
] | [((35, 56), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (50, 56), False, 'import sys\n'), ((297, 372), 'auth.authorization_metadata', 'authorization_metadata', (['api_key', 'secret_key', '"""tinkoff.cloud.tts"""'], {'type': 'dict'}), "(api_key, secret_key, 'tinkoff.cloud.tts', type=dict)\n", (... |
# -*- coding: utf-8 -*-
"""
Tellus
"""
import datetime
import json
import requests
class Tellus:
"""
Tellus
"""
api_token = ""
market_token = ""
expires_at = datetime.datetime.now()
def __init__(self, api_token):
self.api_token = api_token
def _get(self, url, payload={}): ... | [
"json.loads",
"datetime.datetime.strptime",
"json.dumps",
"requests.get",
"datetime.datetime.now",
"datetime.timedelta"
] | [((187, 210), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (208, 210), False, 'import datetime\n'), ((540, 590), 'requests.get', 'requests.get', (['url'], {'headers': 'headers', 'params': 'payload'}), '(url, headers=headers, params=payload)\n', (552, 590), False, 'import requests\n'), ((1170, 119... |
#!/usr/bin/env python3
import time
import treelights
from treelights.ledstrip import LEDStrip, Colors
from colour import Color
import animations
import itertools
import inspect
def run_animation(strip, animation, cycles=100, delay=0.03):
strip.off()
for d in itertools.islice(animation(strip), cycles):
time.sle... | [
"time.sleep",
"treelights.ledstrip.LEDStrip"
] | [((391, 410), 'treelights.ledstrip.LEDStrip', 'LEDStrip', (['LED_COUNT'], {}), '(LED_COUNT)\n', (399, 410), False, 'from treelights.ledstrip import LEDStrip, Colors\n'), ((312, 334), 'time.sleep', 'time.sleep', (['(d or delay)'], {}), '(d or delay)\n', (322, 334), False, 'import time\n')] |
import gym
import pybullet_envs
import numpy as np
from ppo.agent import Agent
if __name__ == '__main__':
env = gym.make('AntBulletEnv-v0')
learn_interval = 100
batch_size = 5000
n_epochs = 1000
learning_rate = 0.0003
observation_space = env.observation_space.shape[0]
action_space = env.... | [
"numpy.mean",
"ppo.agent.Agent",
"gym.make"
] | [((119, 146), 'gym.make', 'gym.make', (['"""AntBulletEnv-v0"""'], {}), "('AntBulletEnv-v0')\n", (127, 146), False, 'import gym\n'), ((354, 489), 'ppo.agent.Agent', 'Agent', ([], {'n_actions': 'action_space', 'batch_size': 'batch_size', 'learning_rate': 'learning_rate', 'n_epochs': 'n_epochs', 'input_dims': 'observation... |
from django.urls import path
from apps.accounts.views import LogoutView, register, login, forgot_password_view
urlpatterns = [
path('register/', register, name='registration'),
path('login/', login, name='custom-login'),
path('logout/', LogoutView.as_view(), name='custom-logout'),
path('forgot-passwor... | [
"django.urls.path",
"apps.accounts.views.LogoutView.as_view"
] | [((133, 181), 'django.urls.path', 'path', (['"""register/"""', 'register'], {'name': '"""registration"""'}), "('register/', register, name='registration')\n", (137, 181), False, 'from django.urls import path\n'), ((187, 229), 'django.urls.path', 'path', (['"""login/"""', 'login'], {'name': '"""custom-login"""'}), "('lo... |
import cherrypy
from cherrypy.process import plugins
import validators
class Plugin(plugins.SimplePlugin):
def __init__(self, bus):
plugins.SimplePlugin.__init__(self, bus)
self.validators = validators
def start(self):
self.bus.subscribe('get-validators', self.get_validators)
def... | [
"cherrypy.engine.publish",
"cherrypy.process.plugins.SimplePlugin.__init__",
"cherrypy.Tool._setup",
"cherrypy.Tool.__init__"
] | [((146, 186), 'cherrypy.process.plugins.SimplePlugin.__init__', 'plugins.SimplePlugin.__init__', (['self', 'bus'], {}), '(self, bus)\n', (175, 186), False, 'from cherrypy.process import plugins\n'), ((524, 601), 'cherrypy.Tool.__init__', 'cherrypy.Tool.__init__', (['self', '"""on_start_resource"""', 'self.set_tool'], {... |
# -*- coding: utf-8 -*-
"""Small module to load user configuration parameters."""
from __future__ import unicode_literals
import json
import sys
class Config(object):
"""Class that handles DFTimewolf's configuration parameters."""
_recipe_classes = {}
_collector_classes = {}
_processor_classes = {}
_expo... | [
"json.loads"
] | [((1950, 1966), 'json.loads', 'json.loads', (['data'], {}), '(data)\n', (1960, 1966), False, 'import json\n')] |
# -*- coding: utf-8 -*-
import clr
import os.path
project_dir = os.path.dirname(os.path.abspath(__file__))
import sys
sys.path.append(os.path.join(project_dir, "TestStack.White.0.13.3\\lib\\net40\\"))
sys.path.append(os.path.join(project_dir, "Castle.Core.3.3.0\\lib\\net40-client\\"))
clr.AddReferenceByName("TestStack... | [
"TestStack.White.Application.Launch",
"clr.AddReferenceByName"
] | [((287, 328), 'clr.AddReferenceByName', 'clr.AddReferenceByName', (['"""TestStack.White"""'], {}), "('TestStack.White')\n", (309, 328), False, 'import clr\n'), ((451, 485), 'TestStack.White.Application.Launch', 'Application.Launch', (['"""iexplore.exe"""'], {}), "('iexplore.exe')\n", (469, 485), False, 'from TestStack.... |
from kid_readout.analysis.timeseries import fftfilt, decimating_fir
import numpy as np
def test_decimating_fir():
np.random.seed(123)
x = np.random.randn(2**16) + 1j*np.random.randn(2**16)
dfir = decimating_fir.DecimatingFIR(downsample_factor=16,num_taps=1024)
gold = fftfilt.fftfilt(dfir.coefficients.r... | [
"kid_readout.analysis.timeseries.decimating_fir.FIR1D",
"numpy.allclose",
"kid_readout.analysis.timeseries.decimating_fir.DecimatingFIR",
"numpy.empty_like",
"numpy.random.seed",
"numpy.random.randn"
] | [((119, 138), 'numpy.random.seed', 'np.random.seed', (['(123)'], {}), '(123)\n', (133, 138), True, 'import numpy as np\n'), ((209, 274), 'kid_readout.analysis.timeseries.decimating_fir.DecimatingFIR', 'decimating_fir.DecimatingFIR', ([], {'downsample_factor': '(16)', 'num_taps': '(1024)'}), '(downsample_factor=16, num_... |
#coding:utf-8
# 感知器 y = f(Wn * x + b)
# 代码实现的是一个逻辑AND操作,输入最后一项一直为1,代表我们可以理解偏置项b的特征值输入一直为1
# 这样就是 y = f(Wn+1*[x,1]), Wn+1就是b
# https://www.zybuluo.com/hanbingtao/note/433855
from numpy import array, dot, random
from random import choice
def fun_1_or_0(x): return 0 if x < 0 else 1
training_data = [(array([0, 0, 1... | [
"numpy.random.random",
"numpy.array",
"numpy.dot",
"random.choice"
] | [((425, 441), 'numpy.random.random', 'random.random', (['(3)'], {}), '(3)\n', (438, 441), False, 'from numpy import array, dot, random\n'), ((575, 596), 'random.choice', 'choice', (['training_data'], {}), '(training_data)\n', (581, 596), False, 'from random import choice\n'), ((610, 629), 'numpy.dot', 'dot', (['weights... |
from django import http
def my_decorator(func):
'''自定义的装饰器:判断是否登录,如果登录,执行func ,未登录,返回json'''
# request.user表示请求的用户对象,如果是未登录用户: user 为 匿名用户,如果是登录用户: user 为 登录用户
def wrapper(request, *args, **kwargs):
if request.user.is_authenticated:
# 如果用户登录, 则进入这里,正常执行
return func(request... | [
"django.http.JsonResponse"
] | [((410, 462), 'django.http.JsonResponse', 'http.JsonResponse', (["{'code': 400, 'errmsg': '请登录后重试'}"], {}), "({'code': 400, 'errmsg': '请登录后重试'})\n", (427, 462), False, 'from django import http\n')] |
import numpy as np
import torch
import torch.nn as nn
import torchvision
import pandas as pd
import matplotlib.pyplot as plt
import torch.nn.functional as F
from sklearn import metrics
import torchvision.transforms as transforms
def get_target_label_idx(labels, targets):
return np.argwhere(np.isin(labels, target... | [
"numpy.prod",
"torch.abs",
"torch.mean",
"numpy.isin",
"torch.sum"
] | [((461, 474), 'torch.mean', 'torch.mean', (['x'], {}), '(x)\n', (471, 474), False, 'import torch\n'), ((431, 447), 'numpy.prod', 'np.prod', (['x.shape'], {}), '(x.shape)\n', (438, 447), True, 'import numpy as np\n'), ((541, 553), 'torch.abs', 'torch.abs', (['x'], {}), '(x)\n', (550, 553), False, 'import torch\n'), ((60... |
import torch
from pytorch_lightning.core.lightning import LightningModule
from torch import nn
from torch.nn import functional as F
from torchmetrics.functional import accuracy, f1
from sklearn.metrics import classification_report
class MLECG(LightningModule):
def __init__(self, config):
super().__init__(... | [
"torch.nn.MaxPool1d",
"torch.nn.CrossEntropyLoss",
"torch.nn.LSTM",
"torch.stack",
"torch.transpose",
"torch.softmax",
"torch.nn.BatchNorm1d",
"torch.nn.Linear",
"torch.nn.functional.relu",
"torch.nn.Conv1d",
"torch.cat",
"torch.argmax"
] | [((564, 598), 'torch.nn.Conv1d', 'nn.Conv1d', (['(1)', '(16)', 'self.kernel_size'], {}), '(1, 16, self.kernel_size)\n', (573, 598), False, 'from torch import nn\n'), ((621, 639), 'torch.nn.BatchNorm1d', 'nn.BatchNorm1d', (['(16)'], {}), '(16)\n', (635, 639), False, 'from torch import nn\n'), ((661, 677), 'torch.nn.MaxP... |
"""Add book_id to books table
Revision ID: c8d5cd3a7733
Revises: <KEY>
Create Date: 2021-09-06 21:17:25.939460
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "<KEY>"
down_revision = "<KEY>"
branch_labels = None
depends_on = None
def upgrade():
# ### comm... | [
"alembic.op.f",
"alembic.op.drop_column",
"sqlalchemy.Integer"
] | [((720, 754), 'alembic.op.drop_column', 'op.drop_column', (['"""books"""', '"""book_id"""'], {}), "('books', 'book_id')\n", (734, 754), False, 'from alembic import op\n'), ((470, 494), 'alembic.op.f', 'op.f', (['"""ix_books_book_id"""'], {}), "('ix_books_book_id')\n", (474, 494), False, 'from alembic import op\n'), ((6... |
from rest_framework import serializers, viewsets
from Escola.models import Aluno
from Escola.serializer import AlunoSerializer
class AlunosViewSet(viewsets.ModelViewSet):
queryset = Aluno.objects.all()
serializer_class = AlunoSerializer
| [
"Escola.models.Aluno.objects.all"
] | [((187, 206), 'Escola.models.Aluno.objects.all', 'Aluno.objects.all', ([], {}), '()\n', (204, 206), False, 'from Escola.models import Aluno\n')] |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
# snippet-start:[python.example_code.config.config_rule_imports]
from pprint import pprint
import boto3
from botocore.exceptions import ClientError
# snippet-end:[python.example_code.config.config_rule_imports]
... | [
"boto3.client",
"pprint.pprint"
] | [((1915, 1937), 'boto3.client', 'boto3.client', (['"""config"""'], {}), "('config')\n", (1927, 1937), False, 'import boto3\n'), ((1067, 1083), 'pprint.pprint', 'pprint', (['response'], {}), '(response)\n', (1073, 1083), False, 'from pprint import pprint\n'), ((1411, 1427), 'pprint.pprint', 'pprint', (['response'], {}),... |
from utils import headerParse
class BaseParser:
def __init__(self, line):
self.raw = {}
for prop in line:
self.raw[headerParse(prop)] = line[prop]
def setMod(self, modName: str, version: str):
self.modName = modName
self.version = version
@staticmethod
def getName():
raise NotImplementedError()
de... | [
"utils.headerParse"
] | [((124, 141), 'utils.headerParse', 'headerParse', (['prop'], {}), '(prop)\n', (135, 141), False, 'from utils import headerParse\n')] |
"""
===================================
Pose Coupling of Dual Cartesian DMP
===================================
A dual Cartesian DMP is learned from an artificially generated demonstration
and replayed with and without a coupling of the pose of the two end effectors.
The red line indicates the DMP without coupling te... | [
"pytransform3d.rotations.quaternion_slerp",
"numpy.eye",
"pytransform3d.rotations.plot_basis",
"movement_primitives.dmp.DualCartesianDMP",
"numpy.asarray",
"numpy.tanh",
"pytransform3d.transformations.transform_from_pq",
"numpy.array",
"numpy.zeros",
"numpy.deg2rad",
"movement_primitives.dmp.Cou... | [((858, 961), 'numpy.array', 'np.array', (['[[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, -1.2], [0.0, \n 0.0, 0.0, 1.0]]'], {}), '([[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, -1.2],\n [0.0, 0.0, 0.0, 1.0]])\n', (866, 961), True, 'import numpy as np\n'), ((1092, 1249), 'movement_pr... |
# Copyright 2013 Cloudbase Solutions SRL
# Copyright 2013 <NAME>
# 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/LIC... | [
"unittest.mock.Mock",
"unittest.mock.MagicMock",
"networking_hyperv.neutron.agent.hyperv_neutron_agent.HyperVNeutronAgent",
"networking_hyperv.neutron.agent.hyperv_neutron_agent.main",
"networking_hyperv.neutron.agent.hyperv_neutron_agent.HyperVSecurityAgent",
"ddt.data",
"unittest.mock.patch.object",
... | [((1262, 1360), 'unittest.mock.patch.object', 'mock.patch.object', (['hyperv_agent.HyperVSecurityAgent', '"""__init__"""', '(lambda *args, **kwargs: None)'], {}), "(hyperv_agent.HyperVSecurityAgent, '__init__', lambda *\n args, **kwargs: None)\n", (1279, 1360), False, 'from unittest import mock\n'), ((1515, 1577), '... |
# Generated by Django 2.1.5 on 2019-07-29 16:42
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('registration', '0009_automatic_earlydate'),
]
operations = [
migrations.AlterField(
model_name='courseevent',
name='... | [
"django.db.models.IntegerField"
] | [((351, 556), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'help_text': '"""Kč, s DPH<br/>\n <dl>\n <dt>Začátečník</dt><dd>6000</dd>\n <dt>Pokročilý</dt><dd>8500</dd>\n </dl>\n """', 'verbose_name': '"""Standardní"""'}), '(help_text=\n """Kč, s DPH<br/>\n <d... |
from flask import Flask, redirect, render_template, request, jsonify
from flask_sqlalchemy import SQLAlchemy
import pymysql
pymysql.install_as_MySQLdb()
from sqlalchemy.ext.automap import automap_base
import simplejson as json
import os
# Set up flask and db
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] ... | [
"flask.render_template",
"flask.Flask",
"sqlalchemy.ext.automap.automap_base",
"os.environ.get",
"flask_sqlalchemy.SQLAlchemy",
"simplejson.loads",
"pymysql.install_as_MySQLdb",
"flask.jsonify"
] | [((124, 152), 'pymysql.install_as_MySQLdb', 'pymysql.install_as_MySQLdb', ([], {}), '()\n', (150, 152), False, 'import pymysql\n'), ((266, 281), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (271, 281), False, 'from flask import Flask, redirect, render_template, request, jsonify\n'), ((322, 360), 'os.envi... |
import numpy as np
C_BASE_SCALES = {
"cromatic": np.arange(12),
"diatonic": (0, 2, 4, 5, 7, 9, 11),
"melodic minor": (0, 2, 3, 5, 7, 9, 11),
"harmonic minor": (0, 2, 3, 5, 7, 8, 11),
}
NOTES = ("C", "Db", "D", "Eb", "E", "F", "F#", "G", "Ab", "A", "Bb", "B")
DEGREES = ("I", "II", "III", "IV", "V", "VI"... | [
"numpy.full",
"numpy.arange"
] | [((54, 67), 'numpy.arange', 'np.arange', (['(12)'], {}), '(12)\n', (63, 67), True, 'import numpy as np\n'), ((747, 761), 'numpy.full', 'np.full', (['(11)', '(1)'], {}), '(11, 1)\n', (754, 761), True, 'import numpy as np\n')] |
from flask_mail import Message
from applications.extensions.init_mail import mail
# send_mail(subject='title', recipients=['<EMAIL>'], content='body')
def send_mail(subject, recipients, content):
try:
message = Message(subject=subject, recipients=recipients, body=content)
mail.send(message)
e... | [
"flask_mail.Message",
"applications.extensions.init_mail.mail.send"
] | [((226, 287), 'flask_mail.Message', 'Message', ([], {'subject': 'subject', 'recipients': 'recipients', 'body': 'content'}), '(subject=subject, recipients=recipients, body=content)\n', (233, 287), False, 'from flask_mail import Message\n'), ((296, 314), 'applications.extensions.init_mail.mail.send', 'mail.send', (['mess... |
from unittest import TestCase
from unittest.mock import patch, Mock
from gtfo.gtfo_filters.templatetags.random import rand_from
class Random_RandFrom(TestCase):
def test_NoArgumentsGiven_ValueErrorIsRaised(self):
self.assertRaises(ValueError, rand_from)
@patch("gtfo.gtfo_filters.templatetags.random.... | [
"gtfo.gtfo_filters.templatetags.random.rand_from",
"unittest.mock.Mock"
] | [((336, 387), 'unittest.mock.Mock', 'Mock', ([], {'side_effect': "(lambda args: {'chose_from': args})"}), "(side_effect=lambda args: {'chose_from': args})\n", (340, 387), False, 'from unittest.mock import patch, Mock\n'), ((521, 550), 'gtfo.gtfo_filters.templatetags.random.rand_from', 'rand_from', (['(1)', '(2)', '"""f... |
# See LICENSE file for full copyright and licensing details.
import time
from odoo import models, fields, api, _
from odoo.exceptions import ValidationError
class ProductTemplate(models.Model):
_inherit = "product.template"
name = fields.Char('Name', required=True)
class ProductCategory(models.Model):
... | [
"odoo._",
"odoo.fields.Selection",
"odoo.fields.Binary",
"time.strftime",
"odoo.fields.Float",
"odoo.fields.Text",
"odoo.fields.Datetime",
"odoo.fields.Many2one",
"odoo.api.onchange",
"odoo.fields.Integer",
"odoo.fields.One2many",
"odoo.api.depends",
"odoo.fields.Many2many",
"odoo.fields.C... | [((243, 277), 'odoo.fields.Char', 'fields.Char', (['"""Name"""'], {'required': '(True)'}), "('Name', required=True)\n", (254, 277), False, 'from odoo import models, fields, api, _\n'), ((369, 415), 'odoo.fields.Boolean', 'fields.Boolean', (['"""Book Category"""'], {'default': '(False)'}), "('Book Category', default=Fal... |
# -*- coding: UTF-8 -*-
"""
Tests for the functions module
"""
try:
from unittest.mock import Mock
except ImportError:
from mock import Mock
from functools import partial
from logging import getLogger
import pytest
from pydecor.decorators import Decorated
from pydecor.constants import LOG_CALL_FMT_STR
fro... | [
"logging.getLogger",
"mock.Mock",
"pytest.mark.parametrize",
"functools.partial",
"pydecor.constants.LOG_CALL_FMT_STR.format",
"pytest.raises",
"pydecor.decorators.Decorated",
"pydecor.functions.log_call"
] | [((370, 784), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""raises, catch, reraise, include_handler"""', '[(Exception, Exception, ValueError, False), (Exception, Exception,\n ValueError, True), (None, Exception, ValueError, False), (None,\n Exception, ValueError, True), (Exception, Exception, None, ... |
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm, PowerNorm, Normalize
from scipy import fftpack
def pix_intensity_hist(vals, generator, noise_vector_length, inv_transf, channel_axis, fname=None, Xterm=True, window=None, multichannel=False):
"""Plots a hist... | [
"numpy.sqrt",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.fill_between",
"numpy.argsort",
"numpy.array",
"numpy.mean",
"numpy.where",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"scipy.fftpack.fft2",
"numpy.take",
"matplotlib.pyplot.close",
"matplotlib.pyplot.axis",
"numpy.hyp... | [((860, 872), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (870, 872), True, 'import matplotlib.pyplot as plt\n'), ((1054, 1071), 'matplotlib.pyplot.yscale', 'plt.yscale', (['"""log"""'], {}), "('log')\n", (1064, 1071), True, 'import matplotlib.pyplot as plt\n'), ((1076, 1105), 'matplotlib.pyplot.legend'... |
"""Encoder, Decoder and Seq2Seq standard implementations.
"""
import math
import time
import torch
from torch import nn, optim
from tqdm import tqdm
import textformer.utils.exception as e
import textformer.utils.logging as l
logger = l.get_logger(__name__)
class Encoder(torch.nn.Module):
"""An Encoder class i... | [
"textformer.utils.logging.get_logger",
"torch.nn.CrossEntropyLoss",
"torch.set_default_tensor_type",
"torch.nn.init.uniform_",
"torch.cuda.is_available",
"textformer.utils.exception.TypeError",
"torch.no_grad",
"math.exp",
"time.time"
] | [((238, 260), 'textformer.utils.logging.get_logger', 'l.get_logger', (['__name__'], {}), '(__name__)\n', (250, 260), True, 'import textformer.utils.logging as l\n'), ((3446, 3494), 'torch.set_default_tensor_type', 'torch.set_default_tensor_type', (['torch.FloatTensor'], {}), '(torch.FloatTensor)\n', (3475, 3494), False... |
# Copyright 2018 The TensorFlow Probability Authors.
#
# 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 o... | [
"tensorflow.unique",
"tensorflow.shape",
"tensorflow.reduce_sum",
"tensorflow.reduce_mean",
"tensorflow_probability.mcmc.sample_chain",
"tensorflow.eye",
"tensorflow.executing_eagerly",
"itertools.product",
"tensorflow.linalg.norm",
"tensorflow.math.reduce_mean",
"tensorflow_probability.python.d... | [((2088, 2217), 'tensorflow_probability.mcmc.sample_chain', 'tfp.mcmc.sample_chain', ([], {'num_results': 'num_steps', 'num_burnin_steps': '(0)', 'current_state': '[state]', 'kernel': 'kernel', 'parallel_iterations': '(1)'}), '(num_results=num_steps, num_burnin_steps=0,\n current_state=[state], kernel=kernel, parall... |
# <editor-fold desc="The following 6 lines of code are required to allow Heron to be able to see the Operation without
# package installation. Do not change.">
import sys
from os import path
current_dir = path.dirname(path.abspath(__file__))
while path.split(current_dir)[-1] != r'Heron':
current_dir = pat... | [
"Heron.communication.socket_for_serialization.Socket.reconstruct_array_from_bytes_message",
"os.path.split",
"os.path.dirname",
"serial.Serial",
"os.path.abspath",
"Heron.general_utils.start_the_sink_worker_process"
] | [((226, 248), 'os.path.abspath', 'path.abspath', (['__file__'], {}), '(__file__)\n', (238, 248), False, 'from os import path\n'), ((317, 342), 'os.path.dirname', 'path.dirname', (['current_dir'], {}), '(current_dir)\n', (329, 342), False, 'from os import path\n'), ((363, 388), 'os.path.dirname', 'path.dirname', (['curr... |
# Generated by Django 2.0.7 on 2018-08-24 13:41
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import markdownx.models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USE... | [
"django.db.models.TextField",
"django.db.models.ForeignKey",
"django.db.models.AutoField",
"django.db.models.DateTimeField",
"django.db.migrations.swappable_dependency",
"django.db.models.CharField"
] | [((271, 328), 'django.db.migrations.swappable_dependency', 'migrations.swappable_dependency', (['settings.AUTH_USER_MODEL'], {}), '(settings.AUTH_USER_MODEL)\n', (302, 328), False, 'from django.db import migrations, models\n'), ((2178, 2267), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'on_delete': 'djang... |
#!/usr/bin/env python
# encoding: utf-8
try:
import socketserver
except ImportError:
import SocketServer as socketserver
from uwsgidns.utils import uwsgi_packet_to_dict
class SubscriptionHandler(socketserver.BaseRequestHandler):
"""Handle UDP subscription requests from uWSGI."""
"""
trigge... | [
"uwsgidns.utils.uwsgi_packet_to_dict"
] | [((550, 576), 'uwsgidns.utils.uwsgi_packet_to_dict', 'uwsgi_packet_to_dict', (['data'], {}), '(data)\n', (570, 576), False, 'from uwsgidns.utils import uwsgi_packet_to_dict\n')] |
"""empty message
Revision ID: 2488b2a0a217
Revises: <PASSWORD>
Create Date: 2019-04-22 16:45:30.004076
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '2488b2a0a217'
down_revision = '<PASSWORD>'
branch_labels = None
depends_on = None
def upgrade():
op.add... | [
"sqlalchemy.DateTime",
"alembic.op.drop_constraint",
"sqlalchemy.Boolean",
"alembic.op.drop_column",
"sqlalchemy.Integer",
"sqlalchemy.TEXT"
] | [((635, 688), 'alembic.op.drop_constraint', 'op.drop_constraint', (['None', '"""users"""'], {'type_': '"""foreignkey"""'}), "(None, 'users', type_='foreignkey')\n", (653, 688), False, 'from alembic import op\n'), ((693, 727), 'alembic.op.drop_column', 'op.drop_column', (['"""users"""', '"""is_free"""'], {}), "('users',... |
from spinta import commands
from spinta.components import Context
from spinta.backends.fs.components import FileSystem
@commands.bootstrap.register(Context, FileSystem)
def bootstrap(context: Context, backend: FileSystem):
pass
| [
"spinta.commands.bootstrap.register"
] | [((122, 170), 'spinta.commands.bootstrap.register', 'commands.bootstrap.register', (['Context', 'FileSystem'], {}), '(Context, FileSystem)\n', (149, 170), False, 'from spinta import commands\n')] |
#!/usr/bin/env python
# _*_coding:utf-8_*_
"""
@Time : 2020/8/23 0:11
@Author: sml2h3
@File: make_dataset
@Software: PyCharm
"""
from utils.constants import *
from utils.exception import *
from config import Config
from PIL import Image
import os
import sys
import json
import time
import random
class MakeDa... | [
"os.path.exists",
"os.listdir",
"PIL.Image.open",
"random.shuffle",
"config.Config",
"json.dumps",
"os.path.join",
"random.seed",
"os.path.split",
"os.path.abspath",
"sys.stdout.flush",
"time.time",
"os.remove"
] | [((751, 788), 'os.path.join', 'os.path.join', (['self.base_path', '"""datas"""'], {}), "(self.base_path, 'datas')\n", (763, 788), False, 'import os\n'), ((1877, 1901), 'random.seed', 'random.seed', (['random_seed'], {}), '(random_seed)\n', (1888, 1901), False, 'import random\n'), ((1910, 1941), 'random.shuffle', 'rando... |
#!/usr/bin/python2.7
import commands
import os
while True:
output = commands.getoutput('ps -aux')
if '/usr/bin/python2.7 /home/user/Workspace/silenceisgolden.py' in output:
# print "ITS ALIVE!!!"
continue
else:
os.system('/usr/bin/python2.7 /home/user/Workspace/silenceisgolden.py &')
| [
"os.system",
"commands.getoutput"
] | [((70, 99), 'commands.getoutput', 'commands.getoutput', (['"""ps -aux"""'], {}), "('ps -aux')\n", (88, 99), False, 'import commands\n'), ((230, 303), 'os.system', 'os.system', (['"""/usr/bin/python2.7 /home/user/Workspace/silenceisgolden.py &"""'], {}), "('/usr/bin/python2.7 /home/user/Workspace/silenceisgolden.py &')\... |
import Foundation
from PyObjCTools.TestSupport import TestCase, min_os_level
class TestNSTextCheckingResult(TestCase):
@min_os_level("10.6")
def testConstants(self):
self.assertEqual(Foundation.NSTextCheckingTypeOrthography, 1 << 0)
self.assertEqual(Foundation.NSTextCheckingTypeSpelling, 1 << ... | [
"PyObjCTools.TestSupport.min_os_level"
] | [((126, 146), 'PyObjCTools.TestSupport.min_os_level', 'min_os_level', (['"""10.6"""'], {}), "('10.6')\n", (138, 146), False, 'from PyObjCTools.TestSupport import TestCase, min_os_level\n'), ((1924, 1944), 'PyObjCTools.TestSupport.min_os_level', 'min_os_level', (['"""10.7"""'], {}), "('10.7')\n", (1936, 1944), False, 'f... |
# -*- coding: utf-8 -*-
from django.contrib import admin
from vvcontact.models import Email
from vvcontact.forms import EmailAdminForm
@admin.register(Email)
class EmailAdmin(admin.ModelAdmin):
form = EmailAdminForm
search_fields = ('message', 'subject')
date_hierarchy = 'created'
list_display = ('em... | [
"django.contrib.admin.register"
] | [((139, 160), 'django.contrib.admin.register', 'admin.register', (['Email'], {}), '(Email)\n', (153, 160), False, 'from django.contrib import admin\n')] |
from rest_framework.test import APITestCase
from apps.user.models import UserRole, User
class TestUserRegistration(APITestCase):
ENDPOINT = '/api/users/register'
def test_user_registration_should_success(self):
"""
this function tests the user registration with following processes:
1.... | [
"apps.user.models.User.objects.create_user"
] | [((2755, 2867), 'apps.user.models.User.objects.create_user', 'User.objects.create_user', ([], {'phone_number': '"""021231234"""', 'name': '"""홍길동"""', 'password': '"""<PASSWORD>"""', 'role': 'UserRole.CLIENT'}), "(phone_number='021231234', name='홍길동', password=\n '<PASSWORD>', role=UserRole.CLIENT)\n", (2779, 2867),... |