code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import time
import random
import sys
sys.path.insert(0, '../message')
from messages.base import BaseMessage
from messages.response import ResponseMessage
class State(object):
def set_server(self, server):
self._server = server
def on_message(self, message):
"""
AppendEntries: 0, Re... | [
"random.randrange",
"sys.path.insert",
"time.time",
"messages.response.ResponseMessage"
] | [((38, 70), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""../message"""'], {}), "(0, '../message')\n", (53, 70), False, 'import sys\n'), ((1561, 1572), 'time.time', 'time.time', ([], {}), '()\n', (1570, 1572), False, 'import time\n'), ((2326, 2448), 'messages.response.ResponseMessage', 'ResponseMessage', (['self._... |
# -*- coding: utf-8 -*-
# @Time : 2019-05-21 19:55
# @Author : LeeHW
# @File : Prepare_data.py
# @Software: PyCharm
from glob import glob
from flags import *
import os
from scipy import misc
import numpy as np
import datetime
import imageio
from multiprocessing.dummy import Pool as ThreadPool
import argparse
pa... | [
"scipy.misc.imrotate",
"os.makedirs",
"argparse.ArgumentParser",
"scipy.misc.imsave",
"os.path.join",
"datetime.datetime.now",
"os.path.isdir",
"scipy.misc.imresize",
"imageio.imread",
"numpy.mod",
"multiprocessing.dummy.Pool"
] | [((327, 352), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (350, 352), False, 'import argparse\n'), ((754, 777), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (775, 777), False, 'import datetime\n'), ((862, 909), 'os.path.join', 'os.path.join', (['args.save_dir', 'args.m... |
#!/usr/bin/python
# API Gateway Ansible Modules
#
# Modules in this project allow management of the AWS API Gateway service.
#
# Authors:
# - <NAME> <github: bjfelton>
# - <NAME> <github: mestudd>
#
# apigw_api_key
# Manage creation, update, and removal of API Gateway ApiKey resources
#
# MIT License
#
# Copyrig... | [
"ansible.module_utils.ec2.camel_dict_to_snake_dict",
"ansible.module_utils.ec2.AWSRetry.exponential_backoff",
"ansible.module_utils.aws.core.AnsibleAWSModule"
] | [((5355, 5385), 'ansible.module_utils.ec2.AWSRetry.exponential_backoff', 'AWSRetry.exponential_backoff', ([], {}), '()\n', (5383, 5385), False, 'from ansible.module_utils.ec2 import AWSRetry, camel_dict_to_snake_dict\n'), ((5773, 5803), 'ansible.module_utils.ec2.AWSRetry.exponential_backoff', 'AWSRetry.exponential_back... |
from django.conf.urls import include, url
from django.urls import path
from django.views.generic import TemplateView
from django.views.generic.base import RedirectView
from portal import views as portal_views
app_name = 'portal'
from .views import HomeView, ResultView, result, scatter, algo_result
urlpatterns = [
... | [
"django.conf.urls.url"
] | [((381, 419), 'django.conf.urls.url', 'url', (['"""^result/"""', 'result'], {'name': '"""result"""'}), "('^result/', result, name='result')\n", (384, 419), False, 'from django.conf.urls import include, url\n'), ((431, 472), 'django.conf.urls.url', 'url', (['"""^scatter/"""', 'scatter'], {'name': '"""scatter"""'}), "('^... |
# Refer: https://codeforces.com/contest/1538/problem/C
from bisect import bisect_left
def solve2(arr, n, a, b):
arr.sort()
left = [0] * len(arr)
right = [0] * len(arr)
i, j = 0, len(arr) - 1
while i - j <= 0:
if arr[i] + arr[j] >= a:
left[j] = i
j -= 1
el... | [
"bisect.bisect_left"
] | [((866, 897), 'bisect.bisect_left', 'bisect_left', (['arr', 'val', '(i + 1)', 'n'], {}), '(arr, val, i + 1, n)\n', (877, 897), False, 'from bisect import bisect_left\n')] |
# This file is part of the Data Cleaning Library (openclean).
#
# Copyright (C) 2018-2021 New York University.
#
# openclean is released under the Revised BSD License. See file LICENSE for
# full license details.
"""Class that implements the DataframeMapper abstract class to perform groupby
operations on a pandas data... | [
"pandas.DataFrame",
"collections.defaultdict"
] | [((2827, 2840), 'collections.defaultdict', 'defaultdict', ([], {}), '()\n', (2838, 2840), False, 'from collections import defaultdict\n'), ((2909, 2922), 'collections.defaultdict', 'defaultdict', ([], {}), '()\n', (2920, 2922), False, 'from collections import defaultdict\n'), ((3534, 3554), 'pandas.DataFrame', 'pd.Data... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 10 22:09:56 2019
@author:
<NAME>
MIT Kavli Institute for Astrophysics and Space Research,
Massachusetts Institute of Technology,
77 Massachusetts Avenue,
Cambridge, MA 02109,
USA
Email: <EMAIL>
Web: www.mnguenther.com
"""
from __future__ import p... | [
"seaborn.set",
"seaborn.set_palette",
"seaborn.set_context",
"allesfitter.allesclass",
"seaborn.set_style",
"matplotlib.pyplot.tight_layout",
"copy.deepcopy",
"matplotlib.pyplot.subplots"
] | [((561, 673), 'seaborn.set', 'sns.set', ([], {'context': '"""paper"""', 'style': '"""ticks"""', 'palette': '"""deep"""', 'font': '"""sans-serif"""', 'font_scale': '(1.5)', 'color_codes': '(True)'}), "(context='paper', style='ticks', palette='deep', font='sans-serif',\n font_scale=1.5, color_codes=True)\n", (568, 673... |
import asyncio
import pickle
import logging
import socket
from functools import wraps
from utils import random_id
logger = logging.getLogger(__name__)
def rpc(func):
"""
A decorator used to indicate an RPC.
All @rpc methods if explicitly called via a request message must have
node.identifier as th... | [
"logging.getLogger",
"pickle.dumps",
"utils.random_id",
"functools.wraps",
"pickle.loads",
"asyncio.get_event_loop",
"asyncio.Future"
] | [((126, 153), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (143, 153), False, 'import logging\n'), ((575, 586), 'functools.wraps', 'wraps', (['func'], {}), '(func)\n', (580, 586), False, 'from functools import wraps\n'), ((1510, 1528), 'pickle.loads', 'pickle.loads', (['data'], {}), '(d... |
import json
import pylab as pl
import random
import numpy as np
import cv2
import anno_func
datadir = "/home/richardchen123/Documents/data/YOLOv4/data"
filedir = datadir + "/annotations.json"
ids = open(datadir + "/test/ids.txt").read().splitlines()
annos = json.loads(open(filedir).read())
imgid = random.sample(ids... | [
"anno_func.draw_all",
"random.sample",
"pylab.figure",
"anno_func.load_img",
"pylab.imshow"
] | [((352, 393), 'anno_func.load_img', 'anno_func.load_img', (['annos', 'datadir', 'imgid'], {}), '(annos, datadir, imgid)\n', (370, 393), False, 'import anno_func\n'), ((409, 459), 'anno_func.draw_all', 'anno_func.draw_all', (['annos', 'datadir', 'imgid', 'imgdata'], {}), '(annos, datadir, imgid, imgdata)\n', (427, 459),... |
import math
print(math.factorial(5)) # 120 = 5*4*3*2*1
| [
"math.factorial"
] | [((18, 35), 'math.factorial', 'math.factorial', (['(5)'], {}), '(5)\n', (32, 35), False, 'import math\n')] |
"""
@brief test log(time=2s)
"""
import sys
import os
import unittest
from pyquickhelper.loghelper import fLOG
from pyquickhelper.pycode import ExtTestCase
from pyquickhelper.jenkinshelper.yaml_helper import enumerate_processed_yml
class TestYamlCondition(ExtTestCase):
def test_jenkins_job_verif(self):
... | [
"os.path.join",
"os.path.dirname",
"pyquickhelper.jenkinshelper.yaml_helper.enumerate_processed_yml",
"pyquickhelper.loghelper.fLOG",
"unittest.main"
] | [((1628, 1643), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1641, 1643), False, 'import unittest\n'), ((326, 398), 'pyquickhelper.loghelper.fLOG', 'fLOG', (['__file__', 'self._testMethodName'], {'OutputPrint': "(__name__ == '__main__')"}), "(__file__, self._testMethodName, OutputPrint=__name__ == '__main__')\n... |
# Copyright 2015 The TensorFlow Authors. 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-2.0
#
# Unless required by applica... | [
"tensorflow.transpose",
"tensorflow.FixedLengthRecordReader",
"six.moves.xrange",
"tensorflow.train.shuffle_batch",
"numpy.arange",
"tensorflow.summary.image",
"tensorflow.gfile.Exists",
"tensorflow.decode_raw",
"tensorflow.random_crop",
"numpy.concatenate",
"numpy.frombuffer",
"tensorflow.tra... | [((3084, 3173), 'tensorflow.FixedLengthRecordReader', 'tf.FixedLengthRecordReader', ([], {'record_bytes': 'record_bytes', 'header_bytes': '(0)', 'footer_bytes': '(0)'}), '(record_bytes=record_bytes, header_bytes=0,\n footer_bytes=0)\n', (3110, 3173), True, 'import tensorflow as tf\n'), ((3399, 3433), 'tensorflow.dec... |
from abc import abstractmethod
from typing import Any, Dict, Optional, Sequence, Tuple
import gym
import numpy as np
from gym import spaces
from gym.utils import seeding
from gym_simplifiedtetris.envs._simplified_tetris_engine import _SimplifiedTetrisEngine
class _SimplifiedTetrisBaseEnv(gym.Env):
"""
All c... | [
"gym_simplifiedtetris.envs._simplified_tetris_engine._SimplifiedTetrisEngine",
"gym.spaces.Discrete",
"numpy.any",
"numpy.append",
"numpy.array",
"gym.utils.seeding.np_random"
] | [((736, 771), 'gym.spaces.Discrete', 'spaces.Discrete', (['self._num_actions_'], {}), '(self._num_actions_)\n', (751, 771), False, 'from gym import spaces\n'), ((1989, 2122), 'gym_simplifiedtetris.envs._simplified_tetris_engine._SimplifiedTetrisEngine', '_SimplifiedTetrisEngine', ([], {'grid_dims': 'grid_dims', 'piece_... |
"quantify shape and depth diversity of FHIR data"
# conda create -n py39 python=3.9
# conda activate py39
# pip install rich, numpy
# python fhir.py
from dataclasses import dataclass
from itertools import chain
from typing import Dict, List, Optional, Tuple
import json
import os
from plotly.subplots import make_subpl... | [
"plotly.graph_objects.Bar",
"os.listdir",
"plotly.subplots.make_subplots",
"os.path.join",
"dataclasses.dataclass",
"numpy.array",
"rich.print",
"itertools.chain.from_iterable",
"json.load"
] | [((4384, 4406), 'dataclasses.dataclass', 'dataclass', ([], {'frozen': '(True)'}), '(frozen=True)\n', (4393, 4406), False, 'from dataclasses import dataclass\n'), ((5640, 5662), 'dataclasses.dataclass', 'dataclass', ([], {'frozen': '(True)'}), '(frozen=True)\n', (5649, 5662), False, 'from dataclasses import dataclass\n'... |
"""
This file is part of the TheLMA (THe Laboratory Management Application) project.
See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information.
Experiment metadata table.
"""
from datetime import datetime
from sqlalchemy import Column
from sqlalchemy import DateTime
from sqlalchemy import ForeignKey... | [
"sqlalchemy.String",
"sqlalchemy.ForeignKey",
"sqlalchemy.Column",
"sqlalchemy.DateTime"
] | [((640, 699), 'sqlalchemy.Column', 'Column', (['"""experiment_metadata_id"""', 'Integer'], {'primary_key': '(True)'}), "('experiment_metadata_id', Integer, primary_key=True)\n", (646, 699), False, 'from sqlalchemy import Column\n'), ((717, 769), 'sqlalchemy.Column', 'Column', (['"""label"""', 'String'], {'nullable': '(... |
# Copyright 2017-2019 typed_python 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... | [
"typed_python.Module",
"typed_python.OneOf",
"typed_python.TupleOf"
] | [((779, 790), 'typed_python.Module', 'Module', (['"""M"""'], {}), "('M')\n", (785, 790), False, 'from typed_python import Module, TupleOf, Class, Member, OneOf\n'), ((882, 894), 'typed_python.TupleOf', 'TupleOf', (['m.Y'], {}), '(m.Y)\n', (889, 894), False, 'from typed_python import Module, TupleOf, Class, Member, OneO... |
# Copyright 2018 Google 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 writing,... | [
"utils.TextUtils.removequotes",
"urllib.parse.quote",
"io.BytesIO",
"time.sleep",
"api_handlers.APIRequest",
"utils.TextUtils.removecommas",
"googleapiclient.discovery.build",
"utils.TextUtils.removenewlines",
"googleapiclient.http.MediaIoBaseDownload",
"copy.deepcopy",
"oauth2utils.OAuth2Authen... | [((1632, 1660), 'copy.deepcopy', 'copy.deepcopy', (['body_template'], {}), '(body_template)\n', (1645, 1660), False, 'import copy\n'), ((3309, 3343), 'oauth2utils.OAuth2Authentication', 'OAuth2Authentication', (['self._scopes'], {}), '(self._scopes)\n', (3329, 3343), False, 'from oauth2utils import OAuth2Authentication... |
import unittest
from typing import List
import torch
from torch import nn
import Utility.Torch.Models.Supertransformer.EnsembleTools.SuperEnsemble
from Utility.Torch.Models.Supertransformer.Layers import EnsembleTools as Ensemble
class test_Submodel(unittest.TestCase):
"""
Tester for the submodel unit of t... | [
"Utility.Torch.Models.Supertransformer.Layers.EnsembleTools.SubModel",
"Utility.Torch.Models.Supertransformer.Layers.EnsembleTools.MemSeed",
"torch.jit.script",
"torch.randn"
] | [((689, 709), 'torch.randn', 'torch.randn', (['[4, 10]'], {}), '([4, 10])\n', (700, 709), False, 'import torch\n'), ((727, 747), 'torch.randn', 'torch.randn', (['[2, 20]'], {}), '([2, 20])\n', (738, 747), False, 'import torch\n'), ((898, 927), 'Utility.Torch.Models.Supertransformer.Layers.EnsembleTools.SubModel', 'Ense... |
"""
Create a new languoid directory for a languoid specified by name and level.
"""
import pathlib
from clldutils.clilib import ParserError
from pyglottolog.languoids import Glottocode, Languoid
from pyglottolog.cli_util import get_languoid
def register(parser):
parser.add_argument(
'parent',
he... | [
"clldutils.clilib.ParserError",
"pyglottolog.languoids.Glottocode.pattern.match",
"pyglottolog.cli_util.get_languoid",
"pathlib.Path"
] | [((796, 833), 'pyglottolog.languoids.Glottocode.pattern.match', 'Glottocode.pattern.match', (['args.parent'], {}), '(args.parent)\n', (820, 833), False, 'from pyglottolog.languoids import Glottocode, Languoid\n'), ((925, 950), 'pathlib.Path', 'pathlib.Path', (['args.parent'], {}), '(args.parent)\n', (937, 950), False, ... |
import random
from typing import Generic, TypeVar
State = TypeVar('State')
Action = TypeVar('Action')
class Monte_Carlo_Tree(Generic[State]):
class Node(Generic[State, Action]):
def __init__(self, state: State, action: Action=None, parent=None):
self.score = 0
self.state = state
... | [
"typing.TypeVar"
] | [((59, 75), 'typing.TypeVar', 'TypeVar', (['"""State"""'], {}), "('State')\n", (66, 75), False, 'from typing import Generic, TypeVar\n'), ((85, 102), 'typing.TypeVar', 'TypeVar', (['"""Action"""'], {}), "('Action')\n", (92, 102), False, 'from typing import Generic, TypeVar\n')] |
## PSYC493 - Directed Studies
## Jack 'jryzkns' Zhou 2018
## code used for calculating a range of
## tolerable values of approximate the sine ratio with the identity
from matplotlib.pyplot import plot, show, xlabel, ylabel, title, axis
from math import sin, pi, log
from numpy import arange
def diff(x):
retu... | [
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"math.log",
"matplotlib.pyplot.title",
"math.sin",
"numpy.arange",
"matplotlib.pyplot.show"
] | [((397, 423), 'numpy.arange', 'arange', (['(0.01)', '(pi / 2)', '(0.01)'], {}), '(0.01, pi / 2, 0.01)\n', (403, 423), False, 'from numpy import arange\n'), ((599, 609), 'matplotlib.pyplot.plot', 'plot', (['x', 'y'], {}), '(x, y)\n', (603, 609), False, 'from matplotlib.pyplot import plot, show, xlabel, ylabel, title, ax... |
# Copyright (c) 2020 Software AG,
# Darmstadt, Germany and/or Software AG USA Inc., Reston, VA, USA,
# and/or its subsidiaries and/or its affiliates and/or their licensors.
# Use, reproduction, transfer, publication or disclosure is prohibited except
# as specifically provided for in your License Agreement with Softwar... | [
"c8y_api.model._util._DateUtil.ensure_timestring",
"c8y_api.model._parser.ComplexObjectParser",
"c8y_api.model._util._DateUtil.to_datetime",
"c8y_api.model._base._DictWrapper",
"c8y_api.model._util._DateUtil.now"
] | [((2636, 2701), 'c8y_api.model._parser.ComplexObjectParser', 'ComplexObjectParser', (["{'type': 'type', 'time': 'time'}", "['source']"], {}), "({'type': 'type', 'time': 'time'}, ['source'])\n", (2655, 2701), False, 'from c8y_api.model._parser import ComplexObjectParser\n'), ((4215, 4248), 'c8y_api.model._util._DateUtil... |
""" SBML model downloader
:Author: <NAME> <<EMAIL>>
:Date: 2020-11-23
:Copyright: 2020, UConn Health
:License: MIT
"""
import os
from report_generation.config import Config
import urllib
from bs4 import BeautifulSoup
import requests
from logzero import logger
#TODO: Consider a better scenario to determine the models... | [
"logzero.logger.error",
"os.path.join",
"requests.get",
"bs4.BeautifulSoup",
"logzero.logger.info"
] | [((2432, 2466), 'bs4.BeautifulSoup', 'BeautifulSoup', (['get_content', '"""lxml"""'], {}), "(get_content, 'lxml')\n", (2445, 2466), False, 'from bs4 import BeautifulSoup\n'), ((4066, 4100), 'bs4.BeautifulSoup', 'BeautifulSoup', (['req_content', '"""lxml"""'], {}), "(req_content, 'lxml')\n", (4079, 4100), False, 'from b... |
#import sys, os
#from importlib import import_module
from fast_calc import rbp
def run(a,b):
return rbp(a, b)
def fcn2( a ):
a.id = a.id2
return a
| [
"fast_calc.rbp"
] | [((107, 116), 'fast_calc.rbp', 'rbp', (['a', 'b'], {}), '(a, b)\n', (110, 116), False, 'from fast_calc import rbp\n')] |
"""
Calibration and image printing utility functions
"""
import matplotlib.pyplot as plt
import torchvision
import numpy as np
__all__ = ['make_image', 'show_batch', 'write_calibration']
def write_calibration(
avg_confs_in_bins,
acc_in_bin_list,
prop_bin,
min_bin,
max_bin,
min_pred=0,
wr... | [
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.tight_layout",
"torchvision.utils.make_grid",
"numpy.transpose",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show"
] | [((470, 484), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (482, 484), True, 'import matplotlib.pyplot as plt\n'), ((1811, 1841), 'numpy.transpose', 'np.transpose', (['npimg', '(1, 2, 0)'], {}), '(npimg, (1, 2, 0))\n', (1823, 1841), True, 'import numpy as np\n'), ((2023, 2041), 'matplotlib.pyplot.ims... |
import pytest
from paukenator.prompts.challenges import Choice
@pytest.fixture
def correct_choice():
return Choice("1", "Love", True)
@pytest.fixture
def wrong_choice():
return Choice("2", "Hate", False)
def test_correct_choice(correct_choice):
assert "1", correct_choice.name
assert "Love", corre... | [
"paukenator.prompts.challenges.Choice"
] | [((115, 140), 'paukenator.prompts.challenges.Choice', 'Choice', (['"""1"""', '"""Love"""', '(True)'], {}), "('1', 'Love', True)\n", (121, 140), False, 'from paukenator.prompts.challenges import Choice\n'), ((190, 216), 'paukenator.prompts.challenges.Choice', 'Choice', (['"""2"""', '"""Hate"""', '(False)'], {}), "('2', ... |
# -*- coding: utf-8 -*-
"""
class Horizon for accessing horizon
Created on Fri July 20 2017
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
__author__ = "yuhao"
import pandas as pd
class Horizon(object):
"""
Horizon using excel file as input
... | [
"pandas.read_csv"
] | [((587, 619), 'pandas.read_csv', 'pd.read_csv', (['data_file'], {'sep': '"""\t"""'}), "(data_file, sep='\\t')\n", (598, 619), True, 'import pandas as pd\n')] |
import tensorflow as tf
from keras import backend as K
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Conv3D, MaxPooling3D, UpSampling3D, concatenate, Activation
from tensorflow.keras.optimizers import Adam
K.set_image_data_format("channels_last")
# Set the image shape to have the channel... | [
"keras.backend.set_image_data_format",
"tensorflow.keras.layers.Conv3D",
"tensorflow.keras.layers.MaxPooling3D",
"tensorflow.keras.layers.concatenate",
"tensorflow.keras.optimizers.Adam",
"tensorflow.keras.layers.UpSampling3D",
"tensorflow.keras.Input",
"tensorflow.keras.models.Model",
"tensorflow.k... | [((238, 278), 'keras.backend.set_image_data_format', 'K.set_image_data_format', (['"""channels_last"""'], {}), "('channels_last')\n", (261, 278), True, 'from keras import backend as K\n'), ((503, 542), 'tensorflow.keras.Input', 'tf.keras.Input', ([], {'shape': '(16, 160, 160, 4)'}), '(shape=(16, 160, 160, 4))\n', (517,... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
# -*- coding: utf-8 -*-
"""
fiberassign.targets
=====================
Functions for loading the target list
"""
from __future__ import absolute_import, division, print_function
import numpy as np
import fitsio
# FIXME: If / when SV bit names diverge ... | [
"numpy.isscalar",
"desitarget.targets.main_cmx_or_sv",
"desitarget.targetmask.desi_mask.names",
"scipy.spatial.KDTree",
"fitsio.FITS",
"numpy.asarray",
"numpy.flatnonzero",
"desitarget.sv3.sv3_targetmask.desi_mask.names",
"desitarget.cmx.cmx_targetmask.cmx_mask.names",
"numpy.array",
"numpy.zero... | [((19268, 19292), 'numpy.isscalar', 'np.isscalar', (['desi_target'], {}), '(desi_target)\n', (19279, 19292), True, 'import numpy as np\n'), ((22804, 22824), 'desitarget.targets.main_cmx_or_sv', 'main_cmx_or_sv', (['data'], {}), '(data)\n', (22818, 22824), False, 'from desitarget.targets import main_cmx_or_sv\n'), ((252... |
# coding=utf-8
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class Department(models.Model):
'''
用户部门表
'''
department_name = models.CharField(max_length=100, verbose_name='部门名称')
department_remar... | [
"django.db.models.DateTimeField",
"django.db.models.TextField",
"django.db.models.CharField",
"django.db.models.ForeignKey"
] | [((246, 299), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(100)', 'verbose_name': '"""部门名称"""'}), "(max_length=100, verbose_name='部门名称')\n", (262, 299), False, 'from django.db import models\n'), ((324, 397), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(64)', 'null':... |
from datasets.ImageNetSynsets import ImageNetSynsets
class ImageNet:
def __init__(self):
self.usedLabels = ImageNetSynsets.getUsedLabels()
def getLabelForLogit(self, logitId):
return self.usedLabels[logitId]
| [
"datasets.ImageNetSynsets.ImageNetSynsets.getUsedLabels"
] | [((121, 152), 'datasets.ImageNetSynsets.ImageNetSynsets.getUsedLabels', 'ImageNetSynsets.getUsedLabels', ([], {}), '()\n', (150, 152), False, 'from datasets.ImageNetSynsets import ImageNetSynsets\n')] |
"""
View this repository on github: https://github.com/Jothin-kumar/Geometry-app
MIT License
Copyright (c) 2021 <NAME>
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, includ... | [
"global_variables.get_value",
"sys.path.append",
"global_variables.set_value"
] | [((1312, 1337), 'sys.path.append', 'sys.path.append', (['"""../../"""'], {}), "('../../')\n", (1327, 1337), False, 'import sys\n'), ((1434, 1509), 'global_variables.set_value', 'global_variables.set_value', (['"""intersecting_lines_and_intersection_point"""', '{}'], {}), "('intersecting_lines_and_intersection_point', {... |
#!/usr/bin/python3.7+
# -*- coding:utf-8 -*-
"""
@auth:
@date: 2020-9-13
@desc: ...
"""
import os
from pydantic import Field
from yzcore.default_settings import DefaultSetting, get_configer
# yaml格式解析器
# conf = get_configer('yaml', import_path=os.path.dirname(__file__))
# ini格式解析器
conf = get_configer('ini', import_p... | [
"os.path.dirname",
"pydantic.Field"
] | [((588, 613), 'pydantic.Field', 'Field', (['None'], {'env': '"""DB_URI"""'}), "(None, env='DB_URI')\n", (593, 613), False, 'from pydantic import Field\n'), ((324, 349), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (339, 349), False, 'import os\n'), ((650, 675), 'os.path.dirname', 'os.path.d... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Plan'
db.create_table(u'membership_plan', (
(... | [
"south.db.db.send_create_signal",
"south.db.db.delete_table"
] | [((664, 710), 'south.db.db.send_create_signal', 'db.send_create_signal', (['u"""membership"""', "['Plan']"], {}), "(u'membership', ['Plan'])\n", (685, 710), False, 'from south.db import db\n'), ((1615, 1666), 'south.db.db.send_create_signal', 'db.send_create_signal', (['u"""membership"""', "['PlanPrice']"], {}), "(u'me... |
bl_info = {
"name": "Export SMF",
"description": "Export to SMF 10 (SnidrsModelFormat)",
"author": "<NAME>",
"version": (0, 8, 0),
"blender": (2, 80, 0),
"location": "File > Export",
"warning": "", # used for warning icon and text in addons panel
"wiki_url": "https://github.com/blender-t... | [
"bpy.props.IntProperty",
"bpy.props.BoolProperty",
"bpy.props.StringProperty",
"bpy.utils.unregister_class",
"bpy.types.TOPBAR_MT_file_export.remove",
"bpy.props.FloatProperty",
"bpy.props.EnumProperty",
"bpy.types.TOPBAR_MT_file_import.remove",
"bpy.types.TOPBAR_MT_file_import.append",
"bpy.types... | [((1024, 1087), 'bpy.props.StringProperty', 'StringProperty', ([], {'default': '"""*.smf"""', 'options': "{'HIDDEN'}", 'maxlen': '(255)'}), "(default='*.smf', options={'HIDDEN'}, maxlen=255)\n", (1038, 1087), False, 'from bpy.props import StringProperty, BoolProperty, EnumProperty, FloatProperty, IntProperty\n'), ((155... |
# /usr/bin/env python
import os
import fire
import webbrowser
from nexinfosys.bin.cli_script import set_log_level_from_cli_param, prepare_base_state, print_issues
from enbios.common.helper import list_to_dataframe, generate_workbook
from enbios.input.data_preparation.lci_to_nis import SpoldToNIS
from enbios.input.dat... | [
"nexinfosys.bin.cli_script.set_log_level_from_cli_param",
"fire.Fire",
"webbrowser.open",
"nexinfosys.bin.cli_script.prepare_base_state",
"enbios.input.data_preparation.recipe_to_nis.convert_recipe_to_nis",
"os.path.split",
"enbios.processing.main.Enviro",
"platform.system",
"enbios.common.helper.li... | [((3421, 3447), 'os.path.split', 'os.path.split', (['output_file'], {}), '(output_file)\n', (3434, 3447), False, 'import os\n'), ((3482, 3522), 'nexinfosys.bin.cli_script.prepare_base_state', 'prepare_base_state', (['nis_file', '(False)', 'dir'], {}), '(nis_file, False, dir)\n', (3500, 3522), False, 'from nexinfosys.bi... |
# coding: utf-8
# # Extract NECOFS data using NetCDF4-Python and analyze/visualize with Pandas
# In[1]:
# Plot forecast water levels from NECOFS model from list of lon,lat locations
# (uses the nearest point, no interpolation)
import netCDF4
import datetime as dt
import pandas as pd
import numpy as np
import matplo... | [
"datetime.datetime",
"numpy.sqrt",
"matplotlib.pyplot.ylabel",
"datetime.datetime.utcnow",
"netCDF4.date2index",
"netCDF4.num2date",
"netCDF4.Dataset",
"pandas.DataFrame",
"datetime.timedelta"
] | [((3103, 3156), 'netCDF4.date2index', 'netCDF4.date2index', (['start', 'time_var'], {'select': '"""nearest"""'}), "(start, time_var, select='nearest')\n", (3121, 3156), False, 'import netCDF4\n'), ((3163, 3215), 'netCDF4.date2index', 'netCDF4.date2index', (['stop', 'time_var'], {'select': '"""nearest"""'}), "(stop, tim... |
import findspark
findspark.init()
import time
from pyspark.sql import SparkSession
from pyspark.streaming import StreamingContext
from pyspark.sql.types import StructType, StructField, StringType
from pyspark.sql import Row,SQLContext
from pyspark.sql.functions import explode, split
import sys
import requests
def ... | [
"pyspark.sql.Row",
"pyspark.sql.SQLContext",
"pyspark.sql.types.StructType",
"pyspark.sql.functions.split",
"findspark.init",
"sys.exc_info",
"pyspark.sql.SparkSession.builder.appName",
"pyspark.sql.types.StringType"
] | [((17, 33), 'findspark.init', 'findspark.init', ([], {}), '()\n', (31, 33), False, 'import findspark\n'), ((847, 880), 'pyspark.sql.types.StructType', 'StructType', (['columns_struct_fields'], {}), '(columns_struct_fields)\n', (857, 880), False, 'from pyspark.sql.types import StructType, StructField, StringType\n'), ((... |
from pymongo import ReturnDocument
from telegram import ReplyKeyboardMarkup
from telegram import ReplyKeyboardRemove
from telegram import Update
from telegram.ext import CallbackContext
from telegram.ext import ConversationHandler
from thx_bot.commands import CHOOSING_REWARDS
from thx_bot.commands import TYPING_REWARD... | [
"telegram.ReplyKeyboardRemove",
"thx_bot.services.thx_api_client.get_asset_pool_info",
"thx_bot.models.channels.Channel.collection.find_one",
"thx_bot.services.thx_api_client.get_pool_rewards",
"thx_bot.models.channels.Channel.collection.find_one_and_update",
"telegram.ReplyKeyboardMarkup"
] | [((884, 943), 'telegram.ReplyKeyboardMarkup', 'ReplyKeyboardMarkup', (['REPLY_KEYBOARD'], {'one_time_keyboard': '(True)'}), '(REPLY_KEYBOARD, one_time_keyboard=True)\n', (903, 943), False, 'from telegram import ReplyKeyboardMarkup\n'), ((2418, 2604), 'thx_bot.models.channels.Channel.collection.find_one_and_update', 'Ch... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `klimaatbestendige_netwerken` package."""
import unittest
import logging
from pathlib import Path
from klimaatbestendige_netwerken import pyFIS
logging.basicConfig(level=logging.DEBUG)
class test_pyFIS(unittest.TestCase):
"""Tests for `klimaatbestend... | [
"logging.basicConfig",
"klimaatbestendige_netwerken.pyFIS.pyFIS",
"unittest.main",
"pathlib.Path"
] | [((208, 248), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.DEBUG'}), '(level=logging.DEBUG)\n', (227, 248), False, 'import logging\n'), ((390, 410), 'pathlib.Path', 'Path', (['"""export_pyFIS"""'], {}), "('export_pyFIS')\n", (394, 410), False, 'from pathlib import Path\n'), ((3470, 3485), 'unit... |
from django.dispatch import Signal
"""
When an xform is received, either from posting or when finished playing.
"""
xform_received = Signal(providing_args=["form"])
"""
When a form is finished playing (via the SMS apis)
"""
sms_form_complete = Signal(providing_args=["session_id", "form"])
| [
"django.dispatch.Signal"
] | [((134, 165), 'django.dispatch.Signal', 'Signal', ([], {'providing_args': "['form']"}), "(providing_args=['form'])\n", (140, 165), False, 'from django.dispatch import Signal\n'), ((246, 291), 'django.dispatch.Signal', 'Signal', ([], {'providing_args': "['session_id', 'form']"}), "(providing_args=['session_id', 'form'])... |
import cv2
import numpy as np
def diff_density(image1, image2, x=0, y=0, w=-1, h=-1):
#Gives how diff image1 is from image2 in a ROI (x,y,width,height)
if(image1 is None or image2 is None):
print("Input not compatible", image1, image2)
exit()
roi1 = image1[y:y+h, x:x+w]
roi2 = image2[y:y+h, x:x+w]
diff_array =... | [
"cv2.absdiff"
] | [((321, 344), 'cv2.absdiff', 'cv2.absdiff', (['roi1', 'roi2'], {}), '(roi1, roi2)\n', (332, 344), False, 'import cv2\n')] |
#!/usr/bin/python
import os, sys, signal, datetime, calendar, json, appdirs
PROGRESS_BAR_LENGTH = 50
USER_DATA_DIR = appdirs.user_data_dir("eventoftheday", "tedski999")
API_URL = "https://en.wikipedia.org/api/rest_v1/feed/onthisday/all"
EVENT_CATEGORIES = {
"births" : "Birthday wishes to {0}",
"deaths" : "Res... | [
"signal.signal",
"random.choice",
"os.makedirs",
"datetime.datetime.strptime",
"os.path.join",
"appdirs.user_data_dir",
"requests.get",
"time.sleep",
"os.path.isfile",
"datetime.datetime.now",
"os.path.isdir",
"json.load",
"json.dump"
] | [((119, 170), 'appdirs.user_data_dir', 'appdirs.user_data_dir', (['"""eventoftheday"""', '"""tedski999"""'], {}), "('eventoftheday', 'tedski999')\n", (140, 170), False, 'import os, sys, signal, datetime, calendar, json, appdirs\n'), ((2072, 2120), 'signal.signal', 'signal.signal', (['signal.SIGINT', 'int_signal_handler... |
import os
import git
import collections
from operator import itemgetter
from .helpers import is_python, get_filenames_from_path
from .parse import get_nodes_from_filenames, get_node_name, get_words_from_names, is_function_node, is_name_node
from .analysis import is_verb
from .output import to_fuzzy, to_csv, to_json, t... | [
"os.path.exists",
"git.Git",
"os.path.join",
"collections.Counter",
"operator.itemgetter"
] | [((2260, 2281), 'collections.Counter', 'collections.Counter', ([], {}), '()\n', (2279, 2281), False, 'import collections\n'), ((1369, 1410), 'os.path.join', 'os.path.join', (['projects_path', 'project_name'], {}), '(projects_path, project_name)\n', (1381, 1410), False, 'import os\n'), ((1544, 1584), 'os.path.join', 'os... |
#!/usr/bin/env python3
# Simple script to take the JSON output from AWS Transcribe and
# print it as a formatted text file
#
# Expects JSON to be fed on stdin
import collections
import json
import sys
def format_secs(secs):
mins, secs = divmod(secs, 60)
return "[%02d:%02d]" % (mins, secs)
data = json.load(s... | [
"json.load",
"collections.defaultdict"
] | [((309, 329), 'json.load', 'json.load', (['sys.stdin'], {}), '(sys.stdin)\n', (318, 329), False, 'import json\n'), ((348, 391), 'collections.defaultdict', 'collections.defaultdict', (["(lambda : 'unknown')"], {}), "(lambda : 'unknown')\n", (371, 391), False, 'import collections\n')] |
# Copyright 2017 FUJITSU LIMITED
#
# 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 writ... | [
"oslo_config.cfg.OptGroup",
"oslo_config.cfg.StrOpt",
"oslo_config.cfg.IntOpt"
] | [((1225, 1282), 'oslo_config.cfg.OptGroup', 'cfg.OptGroup', ([], {'name': '"""log_publisher"""', 'title': '"""log_publisher"""'}), "(name='log_publisher', title='log_publisher')\n", (1237, 1282), False, 'from oslo_config import cfg\n'), ((702, 885), 'oslo_config.cfg.IntOpt', 'cfg.IntOpt', (['"""max_message_size"""'], {... |
"""
Simple ICP localisation demo
Compute position of each scan using ICP
with respect to the previous one
author: <NAME>
"""
import readDatasets as datasets
import matplotlib.pyplot as plt
import icp
import numpy as np
import copy
# Reading data
#scanList = datasets.read_fr079(0)
scanList = datasets.read_u2is(0)
... | [
"matplotlib.pyplot.savefig",
"numpy.random.rand",
"icp.icp",
"readDatasets.read_u2is",
"readDatasets.transform_scan",
"copy.deepcopy",
"matplotlib.pyplot.pause",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show"
] | [((298, 319), 'readDatasets.read_u2is', 'datasets.read_u2is', (['(0)'], {}), '(0)\n', (316, 319), True, 'import readDatasets as datasets\n'), ((365, 388), 'copy.deepcopy', 'copy.deepcopy', (['scanList'], {}), '(scanList)\n', (378, 388), False, 'import copy\n'), ((506, 554), 'matplotlib.pyplot.subplots', 'plt.subplots',... |
"""
Using libroadrunner evaluate the initial values of an SBML model.
Prints out a JSON description of all the given models parameter
initial values.
"""
import argparse
import json
import roadrunner
import os
import sys
def process_arguments():
parser = argparse.ArgumentParser(description="Simulate an SBML mode... | [
"argparse.ArgumentParser",
"json.dumps",
"os.path.isfile",
"roadrunner.RoadRunner",
"sys.exit"
] | [((262, 341), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Simulate an SBML model using roadrunner."""'}), "(description='Simulate an SBML model using roadrunner.')\n", (285, 341), False, 'import argparse\n'), ((812, 845), 'roadrunner.RoadRunner', 'roadrunner.RoadRunner', (['sbml_model... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'LenoxWong'
from scrapy.http import HtmlResponse
class PhantomJSDownloaderMiddleware(object):
@classmethod
def process_request(cls, request, spider):
if spider.name == 'DB':
__pt_driver__ = spider.__pt_driver__
__pt... | [
"scrapy.http.HtmlResponse"
] | [((411, 482), 'scrapy.http.HtmlResponse', 'HtmlResponse', (['request.url'], {'body': 'body', 'encoding': '"""utf-8"""', 'request': 'request'}), "(request.url, body=body, encoding='utf-8', request=request)\n", (423, 482), False, 'from scrapy.http import HtmlResponse\n')] |
from typing import Tuple, List
import numpy as np
from math import ceil
def create_node(coordinates:Tuple[int, float, float]) -> dict:
"""
Dado o valor do indice e das coordenadas no formtato (indice, x, y),
cria um dicionario com o valores das cidades. Em primeira instancia,
a capacidade de uma cida... | [
"numpy.zeros"
] | [((2773, 2814), 'numpy.zeros', 'np.zeros', (['(clients, clients)'], {'dtype': 'float'}), '((clients, clients), dtype=float)\n', (2781, 2814), True, 'import numpy as np\n')] |
"""Defines metrics used to evaluate uncertainty."""
import numpy as np
from scipy.stats import norm
from utils.util import to_one_hot
def gaussian_nll(y, mu, var):
"""Calculates the negative log likelihood of Gaussian distribution.
Args:
y: numpy array, shape [batch_size], the true labels.
... | [
"numpy.sqrt",
"numpy.log",
"numpy.equal",
"utils.util.to_one_hot",
"numpy.arange",
"numpy.mean",
"numpy.histogram",
"numpy.where",
"numpy.max",
"numpy.linspace",
"numpy.ma.masked_array",
"numpy.abs",
"numpy.digitize",
"numpy.argmax",
"numpy.argpartition",
"numpy.absolute",
"numpy.sum... | [((2492, 2527), 'numpy.zeros_like', 'np.zeros_like', (['expected_conf_levels'], {}), '(expected_conf_levels)\n', (2505, 2527), True, 'import numpy as np\n'), ((2898, 2915), 'numpy.mean', 'np.mean', (['pred_var'], {}), '(pred_var)\n', (2905, 2915), True, 'import numpy as np\n'), ((3406, 3435), 'numpy.zeros', 'np.zeros',... |
#!/usr/bin/env python
import argparse
import logging
import os
import os.path
from lxml import html, etree
import json
import sys
class CreateSummary:
def __init__(self, languages):
self.languages = languages
def process(self):
# delete previous summaries if any
summary_file = os.path... | [
"logging.getLogger",
"logging.basicConfig",
"lxml.html.parse",
"argparse.ArgumentParser",
"json.dumps",
"os.path.join",
"os.walk"
] | [((3533, 3591), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Create Summary Page"""'}), "(description='Create Summary Page')\n", (3556, 3591), False, 'import argparse\n'), ((4295, 4334), 'logging.getLogger', 'logging.getLogger', (['"""LANGUAGE_PROCESSOR"""'], {}), "('LANGUAGE_PROCESSOR... |
import urllib.request
import urllib.parse
import frappe
def sendSMS(numbers, message):
sendSMSTextLocal()
def sendSMSTextLocal(self):
"""
resp = sendSMS('apikey', '918123456789',
'<NAME>', 'This is your message')
print (resp)
"""
testlocal_settings = frappe.get_single("Textlo... | [
"frappe.get_single"
] | [((295, 333), 'frappe.get_single', 'frappe.get_single', (['"""Textlocal Setting"""'], {}), "('Textlocal Setting')\n", (312, 333), False, 'import frappe\n')] |
"""
$ wget http://www.fit.vutbr.cz/~imikolov/rnnlm/simple-examples.tgz
$ tar xvf simple-examples.tgz
To run:
$ python3 inverse_draw.py --data_path=simple-examples/data/
"""
import time
import numpy as np
import tensorflow as tf
from controller import RNN_Controller
from heads import ReadHead
from encoder import LS... | [
"tensorflow.device",
"tensorflow.train.SummaryWriter",
"decoder.NTM_Decoder",
"vae.NTM_VAE",
"tensorflow.get_variable",
"tensorflow.nn.embedding_lookup",
"tensorflow.initialize_all_variables",
"reader.ptb_iterator",
"tensorflow.placeholder",
"encoder.LSTM_Encoder",
"tensorflow.Session",
"reade... | [((853, 897), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[BATCH, NUM_STEPS]'], {}), '(tf.int32, [BATCH, NUM_STEPS])\n', (867, 897), True, 'import tensorflow as tf\n'), ((1870, 1906), 'reader.ptb_raw_data', 'reader.ptb_raw_data', (['FLAGS.data_path'], {}), '(FLAGS.data_path)\n', (1889, 1906), False, 'imp... |
from setuptools import setup, find_packages
description = (
'Sphinx extension for kanji and hangul character support in LaTeX'
)
with open('README.rst', 'r', encoding='utf8') as f:
long_description = f.read()
requires = ['Sphinx>=0.6']
keywords = [
'sphinx',
'sphinxcontrib',
'cjk',
'chinese... | [
"setuptools.find_packages"
] | [((1063, 1078), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (1076, 1078), False, 'from setuptools import setup, find_packages\n')] |
import unittest
import numpy as np
import torch
import torch.nn as nn
import torch.optim
import sys
sys.path.append('../')
from FrEIA.modules import *
from FrEIA.framework import *
class ActNormTest(unittest.TestCase):
def __init__(self, *args):
super().__init__(*args)
self.batch_size = 256
... | [
"torch.manual_seed",
"torch.rand_like",
"torch.randn_like",
"torch.zeros",
"unittest.main",
"torch.allclose",
"sys.path.append",
"torch.randn",
"torch.ones"
] | [((102, 124), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (117, 124), False, 'import sys\n'), ((6310, 6325), 'unittest.main', 'unittest.main', ([], {}), '()\n', (6323, 6325), False, 'import unittest\n'), ((404, 424), 'torch.manual_seed', 'torch.manual_seed', (['(0)'], {}), '(0)\n', (421, 424... |
import sys,csv,os
from PyQt5 import QtCore, QtGui, QtWidgets
from gui import Ui_MainWindow
import glob
import os.path
import cv2
roi_list = []
if os.path.exists("roi.csv"):
with open('roi.csv','r')as f:
data = csv.reader(f)
for row in data:
roi_list.append(row)
def clear_roi():
del roi_list[:]
main_var = ''... | [
"PyQt5.QtWidgets.QFileDialog.getExistingDirectory",
"os.path.exists",
"PyQt5.QtWidgets.QMainWindow.__init__",
"PyQt5.QtGui.QPainter",
"PyQt5.QtGui.QPen",
"PyQt5.QtWidgets.QFileDialog.getOpenFileNames",
"csv.writer",
"PyQt5.QtGui.QColor",
"os.path.isfile",
"PyQt5.QtCore.QRect",
"PyQt5.QtWidgets.Q... | [((147, 172), 'os.path.exists', 'os.path.exists', (['"""roi.csv"""'], {}), "('roi.csv')\n", (161, 172), False, 'import sys, csv, os\n'), ((8204, 8236), 'PyQt5.QtWidgets.QApplication', 'QtWidgets.QApplication', (['sys.argv'], {}), '(sys.argv)\n', (8226, 8236), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((21... |
from pyspark.sql import SparkSession
from pyspark.sql.types import StructType, StructField, StringType, IntegerType
import os
import sys
import subprocess
import pyspark.sql.functions as func
from pyspark.sql.types import StringType, ArrayType
import re
# from pyspark.sql.functions import col,lit
class Tools(): ... | [
"os.path.exists",
"os.makedirs",
"subprocess.check_call",
"os.system",
"sys.path.append"
] | [((762, 838), 'subprocess.check_call', 'subprocess.check_call', (["[sys.executable, '-m', 'pip', 'install', 'spark-nlp']"], {}), "([sys.executable, '-m', 'pip', 'install', 'spark-nlp'])\n", (783, 838), False, 'import subprocess\n'), ((912, 985), 'subprocess.check_call', 'subprocess.check_call', (["[sys.executable, '-m'... |
import os
import errno
import inspect
here = os.path.dirname(os.path.abspath(inspect.stack()[0][1]))
source_root = os.path.join('..', 'src')
generation_root = os.path.join('..', 'gen')
distribution_root = os.path.join('..', 'dst')
source_path = os.path.abspath(os.path.join(here, source_root))
generation_path = os.pa... | [
"inspect.stack",
"os.path.join",
"os.makedirs"
] | [((117, 142), 'os.path.join', 'os.path.join', (['""".."""', '"""src"""'], {}), "('..', 'src')\n", (129, 142), False, 'import os\n'), ((161, 186), 'os.path.join', 'os.path.join', (['""".."""', '"""gen"""'], {}), "('..', 'gen')\n", (173, 186), False, 'import os\n'), ((207, 232), 'os.path.join', 'os.path.join', (['"""..""... |
from distutils.core import setup
setup(
name = 'fspathtree',
packages = ['fspathtree'],
version = '0.5',
license='MIT',
description = 'A small utility for wrapping trees (nested dict/list) that allows filesystem-like path access, including walking up with "../".',
author = '<NAME>',
author_email = '<EMAIL... | [
"distutils.core.setup"
] | [((33, 599), 'distutils.core.setup', 'setup', ([], {'name': '"""fspathtree"""', 'packages': "['fspathtree']", 'version': '"""0.5"""', 'license': '"""MIT"""', 'description': '"""A small utility for wrapping trees (nested dict/list) that allows filesystem-like path access, including walking up with "../"."""', 'author': ... |
from tokenizers import Tokenizer
import os
import unittest
from .utils import data_dir, albert_base
import json
from huggingface_hub import HfApi, hf_hub_url, cached_download
import tqdm
class TestSerialization:
def test_full_serialization_albert(self, albert_base):
# Check we can read this file.
... | [
"huggingface_hub.HfApi",
"os.getenv",
"tokenizers.Tokenizer.from_file",
"tqdm.tqdm",
"huggingface_hub.hf_hub_url",
"json.load",
"unittest.skip"
] | [((452, 484), 'tokenizers.Tokenizer.from_file', 'Tokenizer.from_file', (['albert_base'], {}), '(albert_base)\n', (471, 484), False, 'from tokenizers import Tokenizer\n'), ((578, 590), 'json.load', 'json.load', (['f'], {}), '(f)\n', (587, 590), False, 'import json\n'), ((1104, 1125), 'os.getenv', 'os.getenv', (['"""RUN_... |
"""
A query's results can be stored in the :attr:`cache` attribute of the
:class:`~postgres.Postgres` object to avoid burdening the database with
redundant requests. The caching is enabled by the `max_age` argument of the
`one` and `all` methods. For example, this call fetches a row from the `foo`
table and caches it f... | [
"collections.OrderedDict",
"threading.RLock",
"time.perf_counter"
] | [((1840, 1847), 'threading.RLock', 'RLock', ([], {}), '()\n', (1845, 1847), False, 'from threading import RLock\n'), ((1868, 1874), 'time.perf_counter', 'time', ([], {}), '()\n', (1872, 1874), True, 'from time import perf_counter as time\n'), ((2549, 2562), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (2... |
import sys
sys.path.append("../")
import duet
from duet import pandas as pd
from duet import numpy as np
from duet import L2
from duet import LInf
from duet import DuetWrapper
adult = pd.read_csv('../data_long/adult_with_pii.csv')
age_counts = adult['Age'].value_counts().to_dict()
alpha = 10
def range_query(s, a, b):... | [
"duet.numpy.exp",
"duet.list",
"duet.numpy.abs",
"duet.numpy.linalg.norm",
"duet.list2",
"duet.mode_switch",
"duet.pandas.read_csv",
"duet.numpy.random.uniform",
"duet.unwrap",
"duet.RenyiFilter",
"sys.path.append",
"duet.RenyiOdometer",
"duet.numpy.where3"
] | [((11, 33), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (26, 33), False, 'import sys\n'), ((185, 231), 'duet.pandas.read_csv', 'pd.read_csv', (['"""../data_long/adult_with_pii.csv"""'], {}), "('../data_long/adult_with_pii.csv')\n", (196, 231), True, 'from duet import pandas as pd\n'), ((1630... |
import os
import pygame
from PIL import Image
import time
import animations
import game_var
# Variables
pygame.display.set_caption('Turtle Simulator')
pygame.display.set_icon(game_var.logo64x)
################################################################
# ... | [
"pygame.init",
"pygame.time.delay",
"pygame.event.get",
"pygame.display.set_icon",
"time.sleep",
"game_var.game_state.split",
"pygame.display.set_caption",
"animations.startup_sequence",
"animations.home_screen",
"pygame.display.update"
] | [((119, 165), 'pygame.display.set_caption', 'pygame.display.set_caption', (['"""Turtle Simulator"""'], {}), "('Turtle Simulator')\n", (145, 165), False, 'import pygame\n'), ((167, 208), 'pygame.display.set_icon', 'pygame.display.set_icon', (['game_var.logo64x'], {}), '(game_var.logo64x)\n', (190, 208), False, 'import p... |
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.keys import Keys
import time
from PIL import Image
import os
import pytesseract
#url of the login page
url = 'https:... | [
"os.remove",
"selenium.webdriver.Firefox",
"time.sleep",
"PIL.Image.open"
] | [((727, 774), 'selenium.webdriver.Firefox', 'webdriver.Firefox', ([], {'executable_path': 'pathToDriver'}), '(executable_path=pathToDriver)\n', (744, 774), False, 'from selenium import webdriver\n'), ((1218, 1231), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (1228, 1231), False, 'import time\n'), ((1355, 1368),... |
import abc
import numpy as np
class Waveform(abc.ABC):
_waveform = None
@property
@abc.abstractmethod
def waveform(self) -> np.ndarray:
raise NotImplementedError
def __len__(self):
return len(self.waveform)
def shift(self, shift=0):
"""
:param shift: shift ... | [
"numpy.zeros"
] | [((1324, 1340), 'numpy.zeros', 'np.zeros', (['length'], {}), '(length)\n', (1332, 1340), True, 'import numpy as np\n'), ((541, 556), 'numpy.zeros', 'np.zeros', (['shift'], {}), '(shift)\n', (549, 556), True, 'import numpy as np\n'), ((658, 673), 'numpy.zeros', 'np.zeros', (['shift'], {}), '(shift)\n', (666, 673), True,... |
#!/usr/bin/env python3
# MIT License
#
# Copyright (c) 2021 ominocutherium
#
# 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 righ... | [
"subprocess.run",
"json.dumps"
] | [((1940, 2184), 'json.dumps', 'json.dumps', (["{'game_files_changed': self.game_files_changed, 'assets_changed': self.\n assets_changed, 'website_changed': self.website_changed, 'docs_changed':\n self.docs_changed, 'automation_code_changed': self.automation_code_changed}"], {}), "({'game_files_changed': self.game... |
import torch
import torch.nn as nn
#from torch.autograd import Function
def lovasz_grad(gt_sorted):
"""
Computes gradient of the Lovasz extension w.r.t sorted errors
See Alg. 1 in paper
"""
p = len(gt_sorted)
gts = gt_sorted.sum()
intersection = gts - gt_sorted.float().cumsum(0)
union... | [
"torch.sort",
"torch.stack",
"torch.autograd.Variable"
] | [((1806, 1825), 'torch.stack', 'torch.stack', (['losses'], {}), '(losses)\n', (1817, 1825), False, 'import torch\n'), ((1592, 1630), 'torch.sort', 'torch.sort', (['loss_c', '(0)'], {'descending': '(True)'}), '(loss_c, 0, descending=True)\n', (1602, 1630), False, 'import torch\n'), ((1501, 1534), 'torch.autograd.Variabl... |
from copy import deepcopy
from django import template
from django.urls import reverse
register = template.Library()
@register.simple_tag(takes_context=True)
def pagination_url(context, page_number):
'''
Returns a URL for the given page number, assuming that
1) you are trying to paginate for the current... | [
"django.urls.reverse",
"django.template.Library",
"copy.deepcopy"
] | [((99, 117), 'django.template.Library', 'template.Library', ([], {}), '()\n', (115, 117), False, 'from django import template\n'), ((834, 865), 'copy.deepcopy', 'deepcopy', (['resolver_match.kwargs'], {}), '(resolver_match.kwargs)\n', (842, 865), False, 'from copy import deepcopy\n'), ((1013, 1084), 'django.urls.revers... |
"""
Collection of Data Science helper functions
"""
import pandas as pd
import numpy as np
from sklearn.metrics import confusion_matrix
from sklearn.utils.multiclass import unique_labels
import seaborn as sns
def confusion_plot(y_true, y_pred, cmap='viridis'):
"""
Plots a confusion matrix using the Seaborn ... | [
"numpy.ones",
"seaborn.heatmap",
"numpy.zeros",
"sklearn.utils.multiclass.unique_labels",
"sklearn.metrics.confusion_matrix"
] | [((349, 369), 'sklearn.utils.multiclass.unique_labels', 'unique_labels', (['y_val'], {}), '(y_val)\n', (362, 369), False, 'from sklearn.utils.multiclass import unique_labels\n'), ((629, 679), 'seaborn.heatmap', 'sns.heatmap', (['table'], {'annot': '(True)', 'fmt': '"""d"""', 'cmap': 'cmap'}), "(table, annot=True, fmt='... |
from html.parser import HTMLParser
from collections import OrderedDict
import unittest
from firexkit.firexkit_common import get_link
class SimpleHtmlParser(HTMLParser):
def __init__(self, html_str):
super(SimpleHtmlParser, self).__init__()
self.start_tag, self.start_tag_attrs, self.data = None, ... | [
"firexkit.firexkit_common.get_link",
"collections.OrderedDict"
] | [((463, 481), 'collections.OrderedDict', 'OrderedDict', (['attrs'], {}), '(attrs)\n', (474, 481), False, 'from collections import OrderedDict\n'), ((715, 739), 'firexkit.firexkit_common.get_link', 'get_link', (['url'], {'text': 'text'}), '(url, text=text)\n', (723, 739), False, 'from firexkit.firexkit_common import get... |
import streamlit as st
import statsmodels.api as s_api
import matplotlib.pyplot as plt
class lin_mod: #perform linear regression using sklearn and stamodels
def __init__(self,x,y):
self.x=x
self.y=y
def model_imp(self):
x=s_api.add_constant(self.x)
y=self.y
mod=s_api.OLS(... | [
"statsmodels.api.qqplot",
"streamlit.pyplot",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.figure",
"statsmodels.api.add_constant",
"statsmodels.api.OLS",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.title"
] | [((491, 519), 'statsmodels.api.qqplot', 's_api.qqplot', (['res'], {'line': '"""45"""'}), "(res, line='45')\n", (503, 519), True, 'import statsmodels.api as s_api\n'), ((523, 537), 'streamlit.pyplot', 'st.pyplot', (['fig'], {}), '(fig)\n', (532, 537), True, 'import streamlit as st\n'), ((588, 614), 'matplotlib.pyplot.fi... |
import os
import re
import shutil
import subprocess
from sqlalchemy.orm import Session
from app import crud
from app.importers.base import BaseImporter
from app.models.job import Job, JobStatus
from app.schemas import ManifestInput
def clone_repository(url: str, path: str) -> None:
# Due to the use of core.syml... | [
"app.crud.job.get",
"app.crud.job.update_total_items",
"app.crud.job.update_status",
"subprocess.run",
"os.scandir",
"os.path.join",
"os.path.normpath",
"app.schemas.ManifestInput",
"app.crud.manifest.update_or_create",
"app.crud.job.update_imported_items",
"os.walk",
"re.search"
] | [((373, 477), 'subprocess.run', 'subprocess.run', (["['git', 'clone', '-c', 'core.symlinks=false', '--depth', '1', url, path]"], {'check': '(True)'}), "(['git', 'clone', '-c', 'core.symlinks=false', '--depth', '1',\n url, path], check=True)\n", (387, 477), False, 'import subprocess\n'), ((678, 712), 'app.crud.job.ge... |
# Generated by Django 3.1.1 on 2020-09-04 02:30
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('wagtailcore', '0052_pagelogentry'),
]
operations = [
migrations.CreateMo... | [
"django.db.models.OneToOneField",
"django.db.models.AutoField",
"django.db.models.CharField",
"django.db.models.BooleanField"
] | [((404, 497), '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", (420, 497), False, 'from django.db import migrations, models\... |
from SWIMMRS.src.TweetClassifier import Tokenizer, FeatureExtraction
from SWIMMRS.src.scraper.Datascraper import DataScraper
from SWIMMRS.src.scraper.OauthConnectionClient import OauthClient
userTweets_url = 'https://api.twitter.com/1.1/statuses/user_timeline.json?user_id=2597834149&count=20'
def main():
oauth_ob... | [
"SWIMMRS.src.scraper.OauthConnectionClient.OauthClient",
"SWIMMRS.src.scraper.Datascraper.DataScraper",
"SWIMMRS.src.TweetClassifier.Tokenizer.preprocess",
"SWIMMRS.src.TweetClassifier.FeatureExtraction.getfeatureVector"
] | [((324, 337), 'SWIMMRS.src.scraper.OauthConnectionClient.OauthClient', 'OauthClient', ([], {}), '()\n', (335, 337), False, 'from SWIMMRS.src.scraper.OauthConnectionClient import OauthClient\n'), ((404, 429), 'SWIMMRS.src.scraper.Datascraper.DataScraper', 'DataScraper', (['oauth_client'], {}), '(oauth_client)\n', (415, ... |
#!/usr/bin/env python3
from tkinter import Button
from tkinter import Entry
from tkinter import Label
from tkinter import OptionMenu
from tkinter import StringVar
from tkinter import Tk
from genius_scrape import enums
from genius_scrape import genius_scrape
class GeniusScrapeGui:
def __init__(self):
""... | [
"tkinter.Entry",
"genius_scrape.genius_scrape.get_genius_lyrics_from_parts",
"genius_scrape.genius_scrape.write_lyrics",
"tkinter.Button",
"tkinter.StringVar",
"tkinter.Tk",
"tkinter.Label",
"tkinter.OptionMenu",
"genius_scrape.genius_scrape.get_genius_album"
] | [((398, 402), 'tkinter.Tk', 'Tk', ([], {}), '()\n', (400, 402), False, 'from tkinter import Tk\n'), ((532, 575), 'tkinter.Label', 'Label', (['self.window'], {'text': '"""Artist"""', 'width': '(10)'}), "(self.window, text='Artist', width=10)\n", (537, 575), False, 'from tkinter import Label\n'), ((653, 681), 'tkinter.En... |
# Copyright 2020 The Flax 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 or agreed to in wri... | [
"jax.random.PRNGKey",
"absl.testing.absltest.main",
"flax.core.init"
] | [((1056, 1071), 'absl.testing.absltest.main', 'absltest.main', ([], {}), '()\n', (1069, 1071), False, 'from absl.testing import absltest\n'), ((994, 1001), 'flax.core.init', 'init', (['f'], {}), '(f)\n', (998, 1001), False, 'from flax.core import Scope, init, apply\n'), ((1002, 1019), 'jax.random.PRNGKey', 'random.PRNG... |
import pytz
from datetime import datetime
from django.test import override_settings
from django.test import SimpleTestCase
from django.utils import timezone
from .. import exceptions
from .. import fields
class TextFieldTest(SimpleTestCase):
def test_to_json(self):
value = fields.TextField().to_json('Text... | [
"datetime.datetime",
"django.test.override_settings",
"django.utils.timezone.override",
"pytz.timezone"
] | [((3554, 3598), 'django.test.override_settings', 'override_settings', ([], {'TIME_ZONE': '"""Europe/Athens"""'}), "(TIME_ZONE='Europe/Athens')\n", (3571, 3598), False, 'from django.test import override_settings\n'), ((3941, 3985), 'django.test.override_settings', 'override_settings', ([], {'TIME_ZONE': '"""Europe/Athen... |
from typing import TYPE_CHECKING, Any, Dict, Type
from avilla.core.elements import Audio, Image, Notice, NoticeAll, Text, Video
from avilla.core.message import Element
from avilla.core.selectors import entity as entity_selector
from avilla.core.selectors import resource as resource_selector
from avilla.core.utilles im... | [
"avilla.core.utilles.Registrar",
"avilla.onebot.elements.Poke",
"avilla.onebot.elements.Forward",
"avilla.onebot.elements.Image",
"avilla.core.elements.Notice",
"avilla.onebot.elements.FlashImage",
"avilla.onebot.elements.Json",
"avilla.core.elements.Video",
"avilla.onebot.elements.XML",
"avilla.o... | [((690, 701), 'avilla.core.utilles.Registrar', 'Registrar', ([], {}), '()\n', (699, 701), False, 'from avilla.core.utilles import Registrar\n'), ((1871, 1897), 'avilla.core.elements.Text', 'Text', (["data['data']['text']"], {}), "(data['data']['text'])\n", (1875, 1897), False, 'from avilla.core.elements import Audio, I... |
# coding: utf-8
"""
Cherwell REST API
Unofficial Python Cherwell REST API library. # noqa: E501
The version of the OpenAPI document: 9.3.2
Contact: See AUTHORS.
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import re # noqa: F401
# python 2 and pyth... | [
"pycherwell.exceptions.ApiValueError",
"pycherwell.api_client.ApiClient",
"six.iteritems",
"pycherwell.exceptions.ApiTypeError"
] | [((4504, 4545), 'six.iteritems', 'six.iteritems', (["local_var_params['kwargs']"], {}), "(local_var_params['kwargs'])\n", (4517, 4545), False, 'import six\n'), ((9517, 9558), 'six.iteritems', 'six.iteritems', (["local_var_params['kwargs']"], {}), "(local_var_params['kwargs'])\n", (9530, 9558), False, 'import six\n'), (... |
# Copyright 2021 Huawei Technologies Co., Ltd.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-2.0
#
# Unless required by ap... | [
"sys.exit",
"importlib.import_module",
"shlex.split",
"types.ModuleType",
"setuptools.find_packages",
"os.path.join",
"os.chmod",
"os.path.dirname",
"sys.stderr.write",
"platform.system",
"shutil.rmtree",
"platform.machine",
"os.walk"
] | [((1193, 1229), 'importlib.import_module', 'import_module', (['"""importlib.machinery"""'], {}), "('importlib.machinery')\n", (1206, 1229), False, 'from importlib import import_module\n'), ((1376, 1405), 'types.ModuleType', 'types.ModuleType', (['module_name'], {}), '(module_name)\n', (1392, 1405), False, 'import types... |
import os
import typing
import aioredis
import pydantic
from fastapi import FastAPI, Depends
from fastapi.logger import logger
from fastapi_plugins import RedisSettings, depends_redis, redis_plugin
import uvicorn
app = FastAPI()
KEY = "fastapi_cache_snippet"
redis_master = os.getenv('DATASTORE') if os.getenv('DATASTO... | [
"fastapi.FastAPI",
"uvicorn.run",
"os.getenv",
"fastapi_plugins.redis_plugin.init",
"fastapi_plugins.redis_plugin.init_app",
"fastapi.logger.logger.info",
"fastapi_plugins.redis_plugin.terminate",
"fastapi.Depends"
] | [((221, 230), 'fastapi.FastAPI', 'FastAPI', ([], {}), '()\n', (228, 230), False, 'from fastapi import FastAPI, Depends\n'), ((302, 324), 'os.getenv', 'os.getenv', (['"""DATASTORE"""'], {}), "('DATASTORE')\n", (311, 324), False, 'import os\n'), ((276, 298), 'os.getenv', 'os.getenv', (['"""DATASTORE"""'], {}), "('DATASTO... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from unittest import TestCase
from pygithub3.resources.issues import Label
class TestLabel(TestCase):
def test_is_valid_color(self):
valid_colors = ['BADa55', 'FF42FF', '45DFCA']
for color in valid_colors:
self.assertTrue(Label.is_valid... | [
"pygithub3.resources.issues.Label.is_valid_color"
] | [((306, 333), 'pygithub3.resources.issues.Label.is_valid_color', 'Label.is_valid_color', (['color'], {}), '(color)\n', (326, 333), False, 'from pygithub3.resources.issues import Label\n'), ((455, 482), 'pygithub3.resources.issues.Label.is_valid_color', 'Label.is_valid_color', (['color'], {}), '(color)\n', (475, 482), F... |
# -*- coding: UTF-8 -*-
import re
import locale
import json
from flask_jwt_extended import ( create_access_token )
from .dates import token_expires
LANGUAGE_CODES = [ "en", "ja", "vi" ]
def to_locale(language, to_lower=False):
p = language.find('-')
if p >= 0:
if to_lower:
return language[... | [
"re.compile"
] | [((729, 1053), 're.compile', 're.compile', (['"""\n ([A-Za-z]{1,8}(?:-[A-Za-z]{1,8})*|\\\\*) # "en", "en-au", "x-y-z", "*"\n (?:\\\\s*;\\\\s*q=(0(?:\\\\.\\\\d{,3})?|1(?:.0{,3})?))? # Optional "q=1.00", "q=0.8"\n (?:\\\\s*,\\\\s*|$) # Multiple ac... |
from pathlib import Path
from ..convertApi.pdfToTxt import *
from ..pdfToHtml.pdfToHtml import *
from .getFeatures import *
from .getHtmlFeatures import *
input_folder = Path('/Resume-Reader/resumes_in_pdf')
output_folder = Path('/Resume-Reader/output_csv')
features = ['Name', 'Phone Numbers', 'Emails', 'LinkedIn Pr... | [
"pathlib.Path"
] | [((172, 209), 'pathlib.Path', 'Path', (['"""/Resume-Reader/resumes_in_pdf"""'], {}), "('/Resume-Reader/resumes_in_pdf')\n", (176, 209), False, 'from pathlib import Path\n'), ((226, 259), 'pathlib.Path', 'Path', (['"""/Resume-Reader/output_csv"""'], {}), "('/Resume-Reader/output_csv')\n", (230, 259), False, 'from pathli... |
# -*- coding: utf-8 -*-
from tymer import t, skip
setup_tymer = """
import tldextract, posixpath, urlparse
from urltools.urltools import assemble, parse, extract, encode, split, split_netloc
from urltools.urltools import normalize, normalize_path, normalize_query, unquote
from urltools.urltools import _get_public_s... | [
"tymer.t"
] | [((399, 429), 'tymer.t', 't', (['"""_get_public_suffix_list()"""'], {}), "('_get_public_suffix_list()')\n", (400, 429), False, 'from tymer import t, skip\n'), ((465, 526), 'tymer.t', 't', (['"""normalize("http://WwW.exAmple.com./a/b/..////c?x=1#abc")"""'], {}), '(\'normalize("http://WwW.exAmple.com./a/b/..////c?x=1#abc... |
# Generated by Django 2.2.2 on 2019-09-28 14:13
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('optools', '0004_auto_20190928_1339'),
]
operations = [
migrations.AlterModelOptions(
name='section',
options={'ordering': ('... | [
"django.db.migrations.AlterModelOptions"
] | [((227, 356), 'django.db.migrations.AlterModelOptions', 'migrations.AlterModelOptions', ([], {'name': '"""section"""', 'options': "{'ordering': ('witness', 'number'), 'verbose_name_plural': 'Sections'}"}), "(name='section', options={'ordering': (\n 'witness', 'number'), 'verbose_name_plural': 'Sections'})\n", (255, ... |
# https://pythonprogramminglanguage.com/text-to-speech/
#
from gtts import gTTS
import os
def say(s,l='en'):
tts = gTTS(text=s, lang=l)
tts.save("good.mp3")
os.system("afplay good.mp3")
#say("Good morning!",'en') | [
"os.system",
"gtts.gTTS"
] | [((122, 142), 'gtts.gTTS', 'gTTS', ([], {'text': 's', 'lang': 'l'}), '(text=s, lang=l)\n', (126, 142), False, 'from gtts import gTTS\n'), ((172, 200), 'os.system', 'os.system', (['"""afplay good.mp3"""'], {}), "('afplay good.mp3')\n", (181, 200), False, 'import os\n')] |
import math
from typing import List, Tuple, Dict, Union, Set
import numpy as np
from scipy.sparse import csr_matrix
from sklearn.cluster import AgglomerativeClustering
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import Fu... | [
"sklearn.cluster.AgglomerativeClustering",
"sklearn.feature_extraction.text.CountVectorizer",
"math.sqrt",
"sklearn.feature_extraction.text.TfidfVectorizer",
"gtcacs.text_compression.GenerativeTextCompressionNN",
"sklearn.preprocessing.FunctionTransformer"
] | [((4287, 4932), 'gtcacs.text_compression.GenerativeTextCompressionNN', 'GenerativeTextCompressionNN', ([], {'num_epoches': 'self.num_epoches', 'batch_size': 'self.batch_size', 'gen_learning_rate': 'self.gen_learning_rate', 'discr_learning_rate': 'self.discr_learning_rate', 'gen_input_random_noise_size': 'self.random_se... |
'''
TODO:
Median trimmer
'''
import numpy as np
def mad(arr,axis=None):
mid = np.median(arr,axis=axis)
return np.median(abs(arr-mid),axis=axis)
def bin_median(x,y,nbin):
binsize = (x.max()-x.min()) / (2*nbin)
bin_centers = np.linspace(x.min()+binsize,x.max()-binsize,nbin)
binned = np.empty(... | [
"numpy.randint",
"numpy.mean",
"numpy.median",
"os.listdir",
"numpy.polyfit",
"numpy.delete",
"matplotlib.pyplot.plot",
"os.chdir",
"numpy.sum",
"numpy.zeros",
"numpy.empty",
"numpy.polyval",
"numpy.isnan",
"numpy.std",
"astropy.io.fits.open",
"numpy.arange",
"matplotlib.pyplot.show"... | [((84, 109), 'numpy.median', 'np.median', (['arr'], {'axis': 'axis'}), '(arr, axis=axis)\n', (93, 109), True, 'import numpy as np\n'), ((311, 325), 'numpy.empty', 'np.empty', (['nbin'], {}), '(nbin)\n', (319, 325), True, 'import numpy as np\n'), ((338, 352), 'numpy.empty', 'np.empty', (['nbin'], {}), '(nbin)\n', (346, ... |
from collections import defaultdict
from itertools import permutations
def parse_line(line):
a, _, gl, n, *_, b = line.split()
return a, b[:-1], gl, int(n)
def create_relations(data):
relations = defaultdict(lambda: defaultdict(int))
for a, b, gl, n in data:
relations[a][b] = n if gl == 'gain... | [
"itertools.permutations",
"collections.defaultdict"
] | [((231, 247), 'collections.defaultdict', 'defaultdict', (['int'], {}), '(int)\n', (242, 247), False, 'from collections import defaultdict\n'), ((494, 514), 'itertools.permutations', 'permutations', (['people'], {}), '(people)\n', (506, 514), False, 'from itertools import permutations\n')] |
import numpy as np
from matplotlib import pyplot as plt
class SMForward:
'''
Object for performing soil-moisture phase contribution simulations based on sensitivity of soil dielectric properties to soil moisture
'''
mvs: np.array = None
de_real = None
de_imag = None
def __init__(self,... | [
"numpy.radians",
"numpy.sqrt",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.plot",
"numpy.zeros",
"numpy.cos",
"numpy.sin",
"numpy.nan_to_num",
"matplotlib.pyplot.show"
] | [((955, 1006), 'matplotlib.pyplot.plot', 'plt.plot', (['self.mvs', 'self.de_real'], {'label': '"""Real Part"""'}), "(self.mvs, self.de_real, label='Real Part')\n", (963, 1006), True, 'from matplotlib import pyplot as plt\n'), ((1015, 1071), 'matplotlib.pyplot.plot', 'plt.plot', (['self.mvs', 'self.de_imag'], {'label': ... |
#!/usr/bin/env python
#coding: utf-8
from kafka import KafkaConsumer
kafka_host = "10.10.17.117"
kafka_port = 9092
server_str = '{kafka_host}:{kafka_port}'.format(kafka_host = kafka_host, kafka_port = kafka_port)
consumer = KafkaConsumer("test", group_id = "test-group", bootstrap_servers = [server_str])
for messa... | [
"kafka.KafkaConsumer"
] | [((229, 305), 'kafka.KafkaConsumer', 'KafkaConsumer', (['"""test"""'], {'group_id': '"""test-group"""', 'bootstrap_servers': '[server_str]'}), "('test', group_id='test-group', bootstrap_servers=[server_str])\n", (242, 305), False, 'from kafka import KafkaConsumer\n')] |
import numpy as np
from layers import (
FullyConnectedLayer, ReLULayer,
ConvolutionalLayer, MaxPoolingLayer, Flattener,
softmax_with_cross_entropy, l2_regularization, softmax
)
class ConvNet:
"""
Implements a very simple conv net
Input -> Conv[3x3] -> Relu -> Maxpool[4x4] ->
Conv[3x3... | [
"layers.FullyConnectedLayer",
"layers.ReLULayer",
"layers.ConvolutionalLayer",
"numpy.argmax",
"layers.softmax_with_cross_entropy",
"layers.softmax",
"layers.Flattener",
"layers.MaxPoolingLayer"
] | [((2511, 2545), 'layers.softmax_with_cross_entropy', 'softmax_with_cross_entropy', (['out', 'y'], {}), '(out, y)\n', (2537, 2545), False, 'from layers import FullyConnectedLayer, ReLULayer, ConvolutionalLayer, MaxPoolingLayer, Flattener, softmax_with_cross_entropy, l2_regularization, softmax\n'), ((2804, 2816), 'layers... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('teme', '0003_material_name'),
]
operations = [
migrations.RemoveField(
model_name='material',
name='... | [
"django.db.migrations.DeleteModel",
"django.db.migrations.RemoveField",
"django.db.models.ForeignKey"
] | [((243, 303), 'django.db.migrations.RemoveField', 'migrations.RemoveField', ([], {'model_name': '"""material"""', 'name': '"""course"""'}), "(model_name='material', name='course')\n", (265, 303), False, 'from django.db import models, migrations\n'), ((348, 406), 'django.db.migrations.RemoveField', 'migrations.RemoveFie... |
# -*- coding: utf-8 -*-
"""
Summarization by mT5 model
"""
from transformers import T5Tokenizer, MT5ForConditionalGeneration
from typing import List
class mT5Summarizer:
def __init__(
self,
model_size: str = "small",
num_beams: int = 4,
no_repeat_ngram_size: int = 2... | [
"transformers.MT5ForConditionalGeneration.from_pretrained",
"transformers.T5Tokenizer.from_pretrained"
] | [((708, 779), 'transformers.MT5ForConditionalGeneration.from_pretrained', 'MT5ForConditionalGeneration.from_pretrained', (['f"""google/mt5-{model_size}"""'], {}), "(f'google/mt5-{model_size}')\n", (751, 779), False, 'from transformers import T5Tokenizer, MT5ForConditionalGeneration\n'), ((827, 882), 'transformers.T5Tok... |
from unittest import TestCase, skip
from lxml import etree
from packtools.sps.models.article_ids import (
ArticleIds,
)
def _get_xmltree(xml=None):
xml = xml or ''
s = (
"<article>"
"<front>"
" <article-meta>"
f"{xml}"
" </article-meta>"
"</front>"
... | [
"lxml.etree.fromstring"
] | [((356, 375), 'lxml.etree.fromstring', 'etree.fromstring', (['s'], {}), '(s)\n', (372, 375), False, 'from lxml import etree\n')] |
from typing import List
from unittest import mock
from uuid import UUID
import pytest
from sqlalchemy.orm.exc import NoResultFound
from orchestrator.db import ResourceTypeTable, SubscriptionTable, WorkflowTable, db, transactional
from orchestrator.targets import Target
def test_transactional():
def insert_wf(st... | [
"orchestrator.db.ResourceTypeTable.query.filter",
"uuid.UUID",
"unittest.mock.call.debug",
"orchestrator.db.SubscriptionTable.query.search",
"orchestrator.db.transactional",
"unittest.mock.MagicMock",
"unittest.mock.call.warning",
"orchestrator.db.db.database_scope",
"orchestrator.db.db.session.comm... | [((730, 746), 'unittest.mock.MagicMock', 'mock.MagicMock', ([], {}), '()\n', (744, 746), False, 'from unittest import mock\n'), ((1720, 1736), 'unittest.mock.MagicMock', 'mock.MagicMock', ([], {}), '()\n', (1734, 1736), False, 'from unittest import mock\n'), ((3173, 3189), 'unittest.mock.MagicMock', 'mock.MagicMock', (... |
import pytest
from unittest.mock import Mock
from domain.exceptions import InputDataError
from infrastructure.message_client import MessageClient
from application_layer.json_processor import JsonProcessor
from infrastructure.processed_data_repository import ProcessedDataRepository
@pytest.fixture
def json_processor():... | [
"infrastructure.message_client.MessageClient.send_email.assert_called_once_with",
"unittest.mock.Mock",
"infrastructure.message_client.MessageClient.send_post.assert_called_once_with",
"infrastructure.message_client.MessageClient.send_sms.assert_called_once_with",
"infrastructure.processed_data_repository.P... | [((338, 363), 'infrastructure.processed_data_repository.ProcessedDataRepository', 'ProcessedDataRepository', ([], {}), '()\n', (361, 363), False, 'from infrastructure.processed_data_repository import ProcessedDataRepository\n'), ((883, 889), 'unittest.mock.Mock', 'Mock', ([], {}), '()\n', (887, 889), False, 'from unitt... |
# start, prepare data, data ready, finish, FMP
FP_DATA = {
'Chart.JS': [
[32.4, 45.1, 297.6, 1042.4, 1054.8],
[33.6, 43.4, 285.1, 1041.6, 1064.5],
[30.9, 40.9, 292.7, 1036.2, 1056.8],
],
'TimeChart': [
[29.9, 57.2, 255.2, 288.3, 853.2],
[36.2, 43.9, 236.9, 271.5, 837.... | [
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.barh",
"numpy.array",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.title",
"matplotlib.pyplot.legend"
] | [((897, 926), 'matplotlib.pyplot.title', 'plt.title', (['"""First Paint Time"""'], {}), "('First Paint Time')\n", (906, 926), True, 'import matplotlib.pyplot as plt\n'), ((927, 943), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""ms"""'], {}), "('ms')\n", (937, 943), True, 'import matplotlib.pyplot as plt\n'), ((944, ... |