code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
from bokeh.models.sources import ColumnDataSource
from bokeh.transform import cumsum
from functools import partial
from typing import List, Type
from jira_analysis.chart.base import Axis, IChart, Chart
from jira_analysis.defect_rate.issue import Issue
from .plot.donut import DefectRateDonut
def generate_defect_chart... | [
"functools.partial",
"jira_analysis.chart.base.Axis"
] | [((447, 484), 'jira_analysis.chart.base.Axis', 'Axis', ([], {'label': '""""""', 'values': 'None', 'size': '(600)'}), "(label='', values=None, size=600)\n", (451, 484), False, 'from jira_analysis.chart.base import Axis, IChart, Chart\n'), ((496, 533), 'jira_analysis.chart.base.Axis', 'Axis', ([], {'label': '""""""', 'va... |
import datetime
from typing import Any, Dict, List, Type, TypeVar, Union
import attr
from dateutil.parser import isoparse
from ..models.email_model_object import EmailModelObject
from ..models.email_model_sev_client import EmailModelSevClient
from ..types import UNSET, Unset
T = TypeVar("T", bound="EmailModel")
@a... | [
"attr.s",
"attr.ib",
"dateutil.parser.isoparse",
"typing.TypeVar"
] | [((283, 315), 'typing.TypeVar', 'TypeVar', (['"""T"""'], {'bound': '"""EmailModel"""'}), "('T', bound='EmailModel')\n", (290, 315), False, 'from typing import Any, Dict, List, Type, TypeVar, Union\n'), ((319, 344), 'attr.s', 'attr.s', ([], {'auto_attribs': '(True)'}), '(auto_attribs=True)\n', (325, 344), False, 'import... |
import numpy as np
import torch
def swav_loss_func(preds, assignments, temperature):
losses = []
for v1 in range(len(preds)):
for v2 in np.delete(np.arange(len(preds)), v1):
a = assignments[v1]
p = preds[v2] / temperature
loss = -torch.mean(torch.sum(a * torch.log_s... | [
"torch.log_softmax"
] | [((309, 336), 'torch.log_softmax', 'torch.log_softmax', (['p'], {'dim': '(1)'}), '(p, dim=1)\n', (326, 336), False, 'import torch\n')] |
import soundfile as sf
import torch
import torch.nn.functional as F
from fairseq.data import Dictionary
from bol.utils.helper_functions import move_to_cuda
def get_feature(filepath):
def postprocess(feats, sample_rate):
if feats.dim == 2:
feats = feats.mean(-1)
assert feats.dim() == ... | [
"torch.nn.functional.layer_norm",
"fairseq.data.Dictionary.load",
"bol.utils.helper_functions.move_to_cuda",
"torch.from_numpy",
"torch.no_grad",
"soundfile.read"
] | [((464, 481), 'soundfile.read', 'sf.read', (['filepath'], {}), '(filepath)\n', (471, 481), True, 'import soundfile as sf\n'), ((1350, 1376), 'fairseq.data.Dictionary.load', 'Dictionary.load', (['dict_path'], {}), '(dict_path)\n', (1365, 1376), False, 'from fairseq.data import Dictionary\n'), ((1766, 1786), 'bol.utils.h... |
import tkinter as tk
from gameworld03 import World
if __name__ == "__main__":
root = tk.Tk()
root.title("Hello, Pong!")
world = World(root)
world.mainloop() | [
"gameworld03.World",
"tkinter.Tk"
] | [((90, 97), 'tkinter.Tk', 'tk.Tk', ([], {}), '()\n', (95, 97), True, 'import tkinter as tk\n'), ((141, 152), 'gameworld03.World', 'World', (['root'], {}), '(root)\n', (146, 152), False, 'from gameworld03 import World\n')] |
import requests
import os
import sys
import inspect
def start():
print("""
░██╗░░░░░░░██╗███████╗██████╗░██╗███╗░░██╗░██████╗██████╗░███████╗░█████╗░████████╗
░██║░░██╗░░██║██╔════╝██╔══██╗██║████╗░██║██╔════╝██╔══██╗██╔════╝██╔══██╗╚══██╔══╝
░╚██╗████╗██╔╝█████╗░░██████╦╝██║██╔██╗██║╚█████╗░██████╔╝█████╗░░█... | [
"requests.post",
"requests.get"
] | [((837, 858), 'requests.get', 'requests.get', (['website'], {}), '(website)\n', (849, 858), False, 'import requests\n'), ((1045, 1066), 'requests.get', 'requests.get', (['website'], {}), '(website)\n', (1057, 1066), False, 'import requests\n'), ((1305, 1326), 'requests.get', 'requests.get', (['website'], {}), '(website... |
from random import choice
from flask import Flask, redirect
app = Flask(__name__)
words = {
"1": "One Direction",
"2": "Dr Who",
"3": "Cup of herbal tea",
"4": "Knock at the door",
"5": "Johnny's Alive",
"6": "Little Mix",
"7": "<NAME>",
"8": "Golden Gate",
"9": "Selfie Time",
... | [
"flask.redirect",
"random.choice",
"flask.Flask"
] | [((67, 82), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (72, 82), False, 'from flask import Flask, redirect\n'), ((6600, 6632), 'flask.redirect', 'redirect', (['"""/increment"""'], {'code': '(302)'}), "('/increment', code=302)\n", (6608, 6632), False, 'from flask import Flask, redirect\n'), ((2814, 2841... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import os
from eatb.utils.datetime import ts_date
from config.configuration import config_path_work
from functools import wraps
import logging
def requires_parameters(*required_params):
"""
Decorator function to check if required parameters are avai... | [
"logging.getLogger",
"os.path.exists",
"json.loads",
"os.makedirs",
"logging.Formatter",
"os.path.join",
"functools.wraps",
"logging.shutdown",
"logging.FileHandler",
"logging.LoggerAdapter"
] | [((1213, 1251), 'os.path.join', 'os.path.join', (['ip_dir', '"""processing.log"""'], {}), "(ip_dir, 'processing.log')\n", (1225, 1251), False, 'import os\n'), ((1329, 1381), 'logging.getLogger', 'logging.getLogger', (["('%s_%s' % (ip_dir, func.__name__))"], {}), "('%s_%s' % (ip_dir, func.__name__))\n", (1346, 1381), Fa... |
from math import gcd
import torch
import torch.nn as nn
import torch.nn.functional as F
from model import common
def make_model(args, parent=False):
return RFDN(args)
def generate_masks(num):
masks = []
for i in range(num):
now = list(range(2 ** num))
length = 2 ** (num - i)
fo... | [
"torch.index_select",
"torch.nn.PixelShuffle",
"torch.nn.Sequential",
"math.gcd",
"torch.nn.Conv2d",
"torch.tensor",
"model.common.MeanShift",
"argparse.Namespace",
"torch.nn.Identity",
"torch.zeros",
"torch.cat"
] | [((575, 594), 'torch.tensor', 'torch.tensor', (['masks'], {}), '(masks)\n', (587, 594), False, 'import torch\n'), ((6623, 6643), 'argparse.Namespace', 'argparse.Namespace', ([], {}), '()\n', (6641, 6643), False, 'import argparse\n'), ((2105, 2135), 'torch.nn.Sequential', 'nn.Sequential', (['*self.conv_acts'], {}), '(*s... |
from datetime import datetime as dt
import torch
import torch.nn as nn
"""
Inspired by https://medium.com/dair-ai/a-simple-neural-network-from-scratch-with-pytorch-and-google-colab-c7f3830618e0
"""
class NeuralNet(nn.Module):
GPU_AVAIL = torch.cuda.is_available()
DEVICE = torch.device("cuda:0" if torch.cuda... | [
"torch.full",
"torch.mean",
"torch.cuda.device_count",
"torch.exp",
"torch.t",
"torch.tensor",
"datetime.datetime.now",
"torch.cuda.is_available",
"torch.matmul",
"torch.empty",
"torch.randn",
"torch.ones"
] | [((4998, 5041), 'torch.tensor', 'torch.tensor', (['x_all[:-1]'], {'dtype': 'torch.float'}), '(x_all[:-1], dtype=torch.float)\n', (5010, 5041), False, 'import torch\n'), ((5048, 5091), 'torch.tensor', 'torch.tensor', (['y_all[:-1]'], {'dtype': 'torch.float'}), '(y_all[:-1], dtype=torch.float)\n', (5060, 5091), False, 'i... |
import os
import numpy as np
import pandas as pd
from scipy import sparse as sp
from typing import Callable, List, Tuple, Dict
from os.path import join
from . import utils, process_dat
from . import SETTINGS_POLIMI as SETTINGS
os.environ['NUMEXPR_MAX_THREADS'] = str(SETTINGS.hyp['cores'])
pd.options.mode.chained_ass... | [
"pandas.read_csv",
"numpy.hstack",
"numpy.array",
"numpy.arange",
"numpy.random.binomial",
"numpy.repeat",
"numpy.random.poisson",
"numpy.where",
"numpy.sort",
"numpy.random.seed",
"pandas.DataFrame",
"numpy.maximum",
"numpy.random.permutation",
"numpy.ceil",
"numpy.ones",
"tensorflow.... | [((2162, 2208), 'tensorflow.keras.backend.set_floatx', 'tensorflow.keras.backend.set_floatx', (['"""float64"""'], {}), "('float64')\n", (2197, 2208), False, 'import tensorflow\n'), ((2233, 2295), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'category': 'DeprecationWarning'}), "('ignore', ca... |
"""
This module contains definitions of lume-model variables for use with lume tools.
The variables are divided into input and outputs, each with different minimal requirements.
Initiating any variable without the minimum requirements will result in an error.
Two types of variables are currently defined: Scalar and Im... | [
"logging.getLogger",
"pydantic.Field",
"typing.TypeVar"
] | [((653, 680), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (670, 680), False, 'import logging\n'), ((3970, 3986), 'typing.TypeVar', 'TypeVar', (['"""Value"""'], {}), "('Value')\n", (3977, 3986), False, 'from typing import Any, List, Union, Optional, Generic, TypeVar\n'), ((4306, 4316), ... |
from xml.etree import ElementTree as Etree
from xml.dom import minidom
from elavonvtpv.enum import RequestType
from elavonvtpv.Response import Response
import datetime
import hashlib
import requests
class Request:
def __init__(self, secret, request_type, merchant_id, order_id, currency=None, amount=None, card=Non... | [
"xml.etree.ElementTree.Element",
"datetime.datetime.now",
"xml.etree.ElementTree.ElementTree",
"xml.etree.ElementTree.SubElement",
"elavonvtpv.Response.Response"
] | [((4511, 4535), 'xml.etree.ElementTree.Element', 'Etree.Element', (['"""request"""'], {}), "('request')\n", (4524, 4535), True, 'from xml.etree import ElementTree as Etree\n'), ((4650, 4689), 'xml.etree.ElementTree.SubElement', 'Etree.SubElement', (['request', '"""merchantid"""'], {}), "(request, 'merchantid')\n", (466... |
from . import DATA_DIR
import pandas as pd
import xarray as xr
import numpy as np
from pathlib import Path
import csv
REMIND_ELEC_MARKETS = (DATA_DIR / "remind_electricity_markets.csv")
REMIND_ELEC_EFFICIENCIES = (DATA_DIR / "remind_electricity_efficiencies.csv")
REMIND_ELEC_EMISSIONS = (DATA_DIR / "remind_electricity... | [
"csv.reader",
"numpy.arange",
"pandas.read_csv",
"pathlib.Path"
] | [((4893, 5000), 'pandas.read_csv', 'pd.read_csv', (['filepath'], {'skiprows': '(4)', 'names': "['year', 'region', 'GAINS', 'pollutant', 'scenario', 'factor']"}), "(filepath, skiprows=4, names=['year', 'region', 'GAINS',\n 'pollutant', 'scenario', 'factor'])\n", (4904, 5000), True, 'import pandas as pd\n'), ((3419, 3... |
"""baseline
Revision ID: 398d6252cdce
Revises:
Create Date: 2020-03-12 10:10:15.689958
"""
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = '398d6252cdce'
down_revision = None
branch_labels = None
depends_on = None
def upgrade... | [
"sqlalchemy.dialects.mysql.TIMESTAMP",
"alembic.op.drop_table",
"sqlalchemy.dialects.mysql.VARCHAR",
"sqlalchemy.PrimaryKeyConstraint",
"sqlalchemy.Integer",
"sqlalchemy.JSON"
] | [((2114, 2143), 'alembic.op.drop_table', 'op.drop_table', (['"""verification"""'], {}), "('verification')\n", (2127, 2143), False, 'from alembic import op\n'), ((2148, 2183), 'alembic.op.drop_table', 'op.drop_table', (['"""jumio_verification"""'], {}), "('jumio_verification')\n", (2161, 2183), False, 'from alembic impo... |
import pickle
import torch
import numpy as np
from attention import make_model
SRC_STOI = None
TARGET_ITOS = None
TRG_EOS_TOKEN = None
TRG_SOS_TOKEN = None
def load_metadata(meta_path):
global SRC_STOI, TARGET_ITOS, TRG_EOS_TOKEN, TRG_SOS_TOKEN
with open(meta_path, 'rb') as f:
metadata = pickle.lo... | [
"torch.ones_like",
"numpy.where",
"torch.LongTensor",
"torch.max",
"pickle.load",
"numpy.array",
"torch.no_grad",
"torch.ones"
] | [((1476, 1492), 'numpy.array', 'np.array', (['output'], {}), '(output)\n', (1484, 1492), True, 'import numpy as np\n'), ((2095, 2122), 'torch.LongTensor', 'torch.LongTensor', (['src_index'], {}), '(src_index)\n', (2111, 2122), False, 'import torch\n'), ((2212, 2241), 'torch.LongTensor', 'torch.LongTensor', (['src_lengt... |
from datetime import datetime
from getopt import GetoptError, getopt
from socket import AF_INET, SOCK_STREAM, socket as Socket
from sys import stderr
from typing import List, NoReturn
from ..io import DVRIPClient
from ..message import EPOCH
from . import EX_USAGE, guard, prog_connect
def usage() -> NoReturn:
print('... | [
"datetime.datetime.now",
"getopt.getopt",
"socket.socket",
"dateparser.parse"
] | [((659, 673), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (671, 673), False, 'from datetime import datetime\n'), ((564, 584), 'getopt.getopt', 'getopt', (['args', '"""s:e:"""'], {}), "(args, 's:e:')\n", (570, 584), False, 'from getopt import GetoptError, getopt\n'), ((956, 984), 'socket.socket', 'Socket'... |
"""Create the docker image for running twentyquestions.
See ``python dockerize.py --help`` for more information.
"""
import logging
import subprocess
import click
from backend import settings
logger = logging.getLogger(__name__)
@click.command(
context_settings={
'help_option_names': ['-h', '--help'... | [
"logging.getLogger",
"subprocess.run",
"click.command"
] | [((207, 234), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (224, 234), False, 'import logging\n'), ((238, 309), 'click.command', 'click.command', ([], {'context_settings': "{'help_option_names': ['-h', '--help']}"}), "(context_settings={'help_option_names': ['-h', '--help']})\n", (251, ... |
from django.core.urlresolvers import reverse
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.contrib import messages
from django.db.models import Q
from django.http import HttpResponseRedirect, Http404
from django.views.generic import FormView, RedirectView, TemplateView
from django.u... | [
"logging.getLogger",
"json.loads",
"django.utils.translation.ugettext_lazy",
"django.core.urlresolvers.reverse",
"django.utils.timezone.now",
"allauth.account.forms.LoginForm",
"django.db.models.Q",
"allauth.account.forms.SignupForm",
"django.http.Http404"
] | [((1096, 1123), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1113, 1123), False, 'import logging\n'), ((1460, 1483), 'django.core.urlresolvers.reverse', 'reverse', (['"""registration"""'], {}), "('registration')\n", (1467, 1483), False, 'from django.core.urlresolvers import reverse\n')... |
'''
Python script of the fitting process in the notebook run_simulation.ipynb.
This is made so that this can be run on command line as a bash script.
'''
import os
from fancy import Data, Model, Analysis
import argparse
# paths to important files
path_to_this_file = os.path.abspath(os.path.dirname(__file__))
stan_pa... | [
"os.path.exists",
"fancy.Analysis",
"argparse.ArgumentParser",
"fancy.Data",
"os.path.join",
"os.path.dirname",
"fancy.Model",
"os.mkdir"
] | [((325, 364), 'os.path.join', 'os.path.join', (['path_to_this_file', '"""stan"""'], {}), "(path_to_this_file, 'stan')\n", (337, 364), False, 'import os\n'), ((379, 435), 'os.path.join', 'os.path.join', (['path_to_this_file', '"""data"""', '"""sourcedata.h5"""'], {}), "(path_to_this_file, 'data', 'sourcedata.h5')\n", (3... |
#/***********************************************************************
# * Licensed Materials - Property of IBM
# *
# * IBM SPSS Products: Statistics Common
# *
# * (C) Copyright IBM Corp. 1989, 2020
# *
# * US Government Users Restricted Rights - Use, duplication or disclosure
# * restricted by GSA ADP Schedule Co... | [
"re.escape",
"spss.StartProcedure",
"os.path.sep.join",
"spssaux._smartquote",
"textwrap.wrap",
"spssdata.Spssdata",
"os.remove",
"re.split",
"extension.Template",
"webbrowser.get",
"spssaux.VariableDict",
"spss.CellText.String",
"spss.ActiveDataset",
"extension.helper",
"random.uniform"... | [((4566, 4586), 'spss.ActiveDataset', 'spss.ActiveDataset', ([], {}), '()\n', (4584, 4586), False, 'import spss, spssaux, spssdata\n'), ((5055, 5098), 'spss.Submit', 'spss.Submit', (["('DATASET ACTIVATE %s' % dsname)"], {}), "('DATASET ACTIVATE %s' % dsname)\n", (5066, 5098), False, 'import spss, spssaux, spssdata\n'),... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class GCNConv(nn.Module):
"""
Simple GCN layer, similar to https://arxiv.org/abs/1609.02907
"""
def __init__(self, in_features, out_features, activation=None, dropout=False):
super(GCNConv, self).__init__()
self.in_fea... | [
"torch.nn.ModuleList",
"torch.nn.LayerNorm",
"torch.nn.functional.dropout",
"torch.nn.init.xavier_normal_",
"torch.spmm",
"torch.nn.Linear",
"torch.nn.init.calculate_gain"
] | [((403, 439), 'torch.nn.Linear', 'nn.Linear', (['in_features', 'out_features'], {}), '(in_features, out_features)\n', (412, 439), True, 'import torch.nn as nn\n'), ((745, 798), 'torch.nn.init.xavier_normal_', 'nn.init.xavier_normal_', (['self.linear.weight'], {'gain': 'gain'}), '(self.linear.weight, gain=gain)\n', (767... |
import pandas as pd
import networkx as nx
import collections
from operator import itemgetter
def clean_game_titles(t_names, g_names):
t_names_inverse = collections.defaultdict(list)
for k,v in t_names.items():
t_names_inverse[v].append(k)
to_merge = {}
for k,v in t_names_inverse.items():
if len(v) > 1... | [
"networkx.nodes",
"networkx.Graph",
"networkx.contracted_nodes",
"collections.defaultdict",
"networkx.set_node_attributes",
"operator.itemgetter"
] | [((155, 184), 'collections.defaultdict', 'collections.defaultdict', (['list'], {}), '(list)\n', (178, 184), False, 'import collections\n'), ((1539, 1611), 'networkx.set_node_attributes', 'nx.set_node_attributes', (['G'], {'name': '"""total_weight"""', 'values': 'total_weight_dict'}), "(G, name='total_weight', values=to... |
'''
Start by reading and running the following code
to see what it does.
1. Then rewrite this code so that it uses a for loop.
Challenge yourself to make the rewrite as short as
possible.
2. Modify your code to draw a square instead of a triangle.
3. Modify your code to draw a pentagon. (You should Google
what angles ... | [
"turtle.done",
"turtle.Turtle"
] | [((640, 655), 'turtle.Turtle', 'turtle.Turtle', ([], {}), '()\n', (653, 655), False, 'import turtle\n'), ((866, 879), 'turtle.done', 'turtle.done', ([], {}), '()\n', (877, 879), False, 'import turtle\n')] |
from django.test import TestCase
from django.contrib.auth import get_user_model
class ModelTests(TestCase):
def test_create_user_succesful(self):
"""test thst creating a new ussful"""
email = "<EMAIL>"
password = "<PASSWORD>"
user = get_user_model().objects.create_user(
... | [
"django.contrib.auth.get_user_model"
] | [((272, 288), 'django.contrib.auth.get_user_model', 'get_user_model', ([], {}), '()\n', (286, 288), False, 'from django.contrib.auth import get_user_model\n'), ((612, 628), 'django.contrib.auth.get_user_model', 'get_user_model', ([], {}), '()\n', (626, 628), False, 'from django.contrib.auth import get_user_model\n'), (... |
import torch.utils.data as data
import os
import numpy as np
import cv2
#/mnt/lustre/share/dingmingyu/new_list_lane.txt
class MyDataset(data.Dataset):
def __init__(self, file, dir_path, new_width, new_height, label_width, label_height):
imgs = []
fw = open(file, 'r')
lines = fw.readlines()
... | [
"numpy.unique",
"os.path.join",
"numpy.zeros",
"cv2.resize",
"cv2.imread"
] | [((725, 758), 'os.path.join', 'os.path.join', (['self.dir_path', 'path'], {}), '(self.dir_path, path)\n', (737, 758), False, 'import os\n'), ((849, 891), 'cv2.resize', 'cv2.resize', (['img', '(self.width, self.height)'], {}), '(img, (self.width, self.height))\n', (859, 891), False, 'import cv2\n'), ((973, 994), 'cv2.im... |
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="workdown",
version="0.0.4",
author="<NAME>",
author_email="<EMAIL>",
description="Write Markdown and have it published and hosted on Cloudflare Workers",
long_description=long_descript... | [
"setuptools.find_packages"
] | [((438, 464), 'setuptools.find_packages', 'setuptools.find_packages', ([], {}), '()\n', (462, 464), False, 'import setuptools\n')] |
from django.conf import settings
from django.shortcuts import redirect, render
from transport.models import *
from transport.forms import *
from django.contrib.auth.decorators import login_required
import requests,json
from django.template.loader import render_to_string, get_template
from django.core.mail import Email... | [
"django.shortcuts.render",
"json.loads",
"requests.auth.HTTPBasicAuth",
"django.http.HttpResponse",
"django.template.loader.get_template",
"requests.get",
"django_daraja.mpesa.core.MpesaClient",
"django.shortcuts.redirect",
"django.contrib.auth.decorators.login_required",
"django.core.mail.EmailMe... | [((679, 719), 'django.contrib.auth.decorators.login_required', 'login_required', ([], {'login_url': '"""client_login"""'}), "(login_url='client_login')\n", (693, 719), False, 'from django.contrib.auth.decorators import login_required\n'), ((2547, 2587), 'django.contrib.auth.decorators.login_required', 'login_required',... |
import numpy as np
import os
import torch
import math
class Params(object):
def __init__(self):
self.exp_id = '0207/exp1'
self.root_params()
self.network_params()
self.train_params()
self.load_params()
self.reconstruct_params()
def change_node_num(self, node_n... | [
"torch.cuda.is_available",
"os.path.join",
"torch.FloatTensor",
"torch.device"
] | [((1069, 1119), 'os.path.join', 'os.path.join', (['self.root_file', '"""debug"""', 'self.exp_id'], {}), "(self.root_file, 'debug', self.exp_id)\n", (1081, 1119), False, 'import os\n'), ((1147, 1213), 'os.path.join', 'os.path.join', (['self.root_file', '"""experiment/train/log/"""', 'self.exp_id'], {}), "(self.root_file... |
#from setuptools import setup, find_packages
#from os import getcwd, path
import os
import sys
import json
import config
#currentDir = getcwd()
'''
# Get Readme text
with open(path.join(currentDir, 'README.md'), encoding='utf-8') as fR:
readme = fR.read()
'''
# Run setup
'''
setup(
# Project's name
name... | [
"config.Config",
"os.path.isfile",
"os.path.isdir",
"os.mkdir",
"sys.exit",
"json.dump"
] | [((2860, 2875), 'config.Config', 'config.Config', ([], {}), '()\n', (2873, 2875), False, 'import config\n'), ((2906, 2956), 'os.path.isdir', 'os.path.isdir', (['f"""/{configurations.BACKUP_FOLDER}/"""'], {}), "(f'/{configurations.BACKUP_FOLDER}/')\n", (2919, 2956), False, 'import os\n'), ((2971, 3006), 'sys.exit', 'sys... |
import unittest
from django.apps import apps
from tethys_config.apps import TethysPortalConfig
class TethysConfigAppsTest(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_TethysPortalConfig(self):
app_config = apps.get_app_config('tethys_config')
... | [
"django.apps.apps.get_app_config"
] | [((279, 315), 'django.apps.apps.get_app_config', 'apps.get_app_config', (['"""tethys_config"""'], {}), "('tethys_config')\n", (298, 315), False, 'from django.apps import apps\n')] |
import pygame
import math
from pygame import mixer
import os
pygame.init()
WIDTH, HEIGHT = 800, 600
#create the screen
screen = pygame.display.set_mode((WIDTH , HEIGHT))
# Title and Icon
pygame.display.set_caption("Space Fighter")
icon = pygame.image.load(os.path.join('assets', 'icon.png'))
pygame.di... | [
"pygame.init",
"pygame.event.get",
"math.pow",
"pygame.display.set_mode",
"pygame.display.set_icon",
"os.path.join",
"pygame.display.set_caption",
"pygame.display.update",
"pygame.mixer.music.play"
] | [((67, 80), 'pygame.init', 'pygame.init', ([], {}), '()\n', (78, 80), False, 'import pygame\n'), ((141, 181), 'pygame.display.set_mode', 'pygame.display.set_mode', (['(WIDTH, HEIGHT)'], {}), '((WIDTH, HEIGHT))\n', (164, 181), False, 'import pygame\n'), ((204, 247), 'pygame.display.set_caption', 'pygame.display.set_capt... |
import reframe as rfm
import reframe.utility.sanity as sn
@rfm.simple_test
class np_max_test(rfm.RunOnlyRegressionTest):
omp_threads = parameter([12])
# mpi_rks = parameter([1, 2])
np_per_c = parameter([
1.8e6,
2.0e6, 2.2e6, 2.4e6, 2.6e6, 2.8e6,
3.0e6, 3.2e6, 3.4e6, 3.6e6, 3.8e6,
... | [
"reframe.utility.sanity.extractsingle",
"reframe.utility.sanity.evaluate",
"reframe.utility.sanity.extractall",
"reframe.utility.sanity.assert_found"
] | [((1922, 1957), 'reframe.utility.sanity.assert_found', 'sn.assert_found', (['regex', 'self.stdout'], {}), '(regex, self.stdout)\n', (1937, 1957), True, 'import reframe.utility.sanity as sn\n'), ((2096, 2140), 'reframe.utility.sanity.extractsingle', 'sn.extractsingle', (['regex', 'self.stdout', '(1)', 'int'], {}), '(reg... |
from kerashistoryplot.data import (get_metrics,
_get_batch_metric_vs_epoch,
get_metric_vs_epoch)
HISTORY = {
'batches': [
{
'batch': [0, 1],
'size': [300, 200],
'loss': [0.4, 0.3],
'mean_ab... | [
"kerashistoryplot.data.get_metrics",
"kerashistoryplot.data.get_metric_vs_epoch",
"kerashistoryplot.data._get_batch_metric_vs_epoch"
] | [((839, 859), 'kerashistoryplot.data.get_metrics', 'get_metrics', (['HISTORY'], {}), '(HISTORY)\n', (850, 859), False, 'from kerashistoryplot.data import get_metrics, _get_batch_metric_vs_epoch, get_metric_vs_epoch\n'), ((1017, 1058), 'kerashistoryplot.data.get_metric_vs_epoch', 'get_metric_vs_epoch', (['HISTORY'], {'m... |
import tensorflow as tf
from tensorflow.keras.layers import Dense, LayerNormalization, Reshape, Permute, Dropout, GlobalAveragePooling1D, Embedding
from tensorflow.keras.activations import softmax, linear
import tensorflow.keras.backend as K
import numpy as np
def gelu(x):
return 0.5*x*(1+tf.tanh(np.sqrt(2/np.pi)*... | [
"tensorflow.shape",
"numpy.sqrt",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.backend.shape",
"tensorflow.keras.layers.Reshape",
"tensorflow.pow",
"tensorflow.keras.layers.Permute",
"tensorflow.image.extract_patches",
"tensorflow.keras.activations.softmax",
"tensorflow.concat",
"tensorflo... | [((6093, 6124), 'tensorflow.keras.Input', 'tf.keras.Input', ([], {'shape': 'input_dim'}), '(shape=input_dim)\n', (6107, 6124), True, 'import tensorflow as tf\n'), ((810, 828), 'tensorflow.keras.layers.Permute', 'Permute', (['(2, 1, 3)'], {}), '((2, 1, 3))\n', (817, 828), False, 'from tensorflow.keras.layers import Dens... |
from time import sleep
from threading import Thread
import socket
import datetime as datetime
from tkinter import *
#global varaibles
global run
global message
global gui
run=True
class client():
def __init__(self):
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.count = 0
... | [
"threading.Thread",
"datetime.time",
"datetime.datetime.now",
"socket.socket"
] | [((240, 289), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (253, 289), False, 'import socket\n'), ((2935, 3000), 'threading.Thread', 'Thread', ([], {'name': '"""client-receive"""', 'target': 'client.receive', 'daemon': '(True)'}), "(name='cl... |
import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
import logging
import datetime
import time
class Semaphore:
def __init__(self, filename='semaphore.txt'):
self.filename = filename
with open(self.filename, 'w') as f:
... | [
"dash_core_components.Interval",
"dash_core_components.RadioItems",
"dash_html_components.Button",
"dash.dependencies.Output",
"time.sleep",
"dash.dependencies.Input",
"datetime.datetime.now",
"dash_html_components.Div",
"dash.Dash"
] | [((847, 858), 'dash.Dash', 'dash.Dash', ([], {}), '()\n', (856, 858), False, 'import dash\n'), ((768, 781), 'time.sleep', 'time.sleep', (['(7)'], {}), '(7)\n', (778, 781), False, 'import time\n'), ((816, 839), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (837, 839), False, 'import datetime\n'), (... |
import pycountry
from irco import logging
_cache = {}
log = logging.get_logger()
NAMES = {c.name.lower(): c for c in pycountry.countries.objects}
SUBDIVISIONS = {s.name.lower(): s for s in pycountry.subdivisions.objects}
PREFIXES = set([
'Republic of',
])
REPLACEMENTS = {
'South Korea': 'Korea, Republic of... | [
"pycountry.countries.get",
"irco.logging.get_logger"
] | [((62, 82), 'irco.logging.get_logger', 'logging.get_logger', ([], {}), '()\n', (80, 82), False, 'from irco import logging\n'), ((1283, 1326), 'pycountry.countries.get', 'pycountry.countries.get', ([], {'name': 'country_token'}), '(name=country_token)\n', (1306, 1326), False, 'import pycountry\n')] |
from django.urls import include, path
from rest_framework.routers import DefaultRouter
from rooms import views
# Create a router and register our viewsets with it.
router = DefaultRouter()
router.register(r"room", views.RoomViewSet, basename="room")
# The API URLs are now determined automatically by the router.
urlp... | [
"rest_framework.routers.DefaultRouter",
"django.urls.include"
] | [((175, 190), 'rest_framework.routers.DefaultRouter', 'DefaultRouter', ([], {}), '()\n', (188, 190), False, 'from rest_framework.routers import DefaultRouter\n'), ((345, 365), 'django.urls.include', 'include', (['router.urls'], {}), '(router.urls)\n', (352, 365), False, 'from django.urls import include, path\n')] |
#!/usr/bin/env python
"""
Copyright 2018 Johns Hopkins University (Author: <NAME>)
Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""
"""
Evals PDDA LLR
"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
from six.moves import xrange
import sys
... | [
"hyperion.hyp_defs.config_logger",
"logging.debug",
"argparse.ArgumentParser",
"hyperion.helpers.TrialDataReader.filter_args",
"hyperion.helpers.TrialDataReader",
"logging.info",
"hyperion.hyp_defs.set_float_cpu",
"hyperion.transforms.TransformList.load",
"hyperion.keras.vae.TiedVAE_qY.load",
"hyp... | [((1083, 1107), 'hyperion.hyp_defs.set_float_cpu', 'set_float_cpu', (['"""float32"""'], {}), "('float32')\n", (1096, 1107), False, 'from hyperion.hyp_defs import set_float_cpu, float_cpu, config_logger\n'), ((1246, 1271), 'hyperion.helpers.TrialDataReader.filter_args', 'TDR.filter_args', ([], {}), '(**kwargs)\n', (1261... |
import re
import typing
import logging
import argparse
from opensearchpy import OpenSearch
from datetime import datetime
_version = "0.0.1"
_project_name = "opensearch-index-rotate"
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(f"{_project_name}-{_version}")
def build_filter_function(
unit... | [
"logging.basicConfig",
"logging.getLogger",
"argparse.ArgumentParser",
"re.compile",
"opensearchpy.OpenSearch",
"datetime.datetime.now",
"re.search"
] | [((185, 224), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (204, 224), False, 'import logging\n'), ((234, 282), 'logging.getLogger', 'logging.getLogger', (['f"""{_project_name}-{_version}"""'], {}), "(f'{_project_name}-{_version}')\n", (251, 282), False, 'impo... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
RealSense PCD Viewer with Open3D.
Copyright (c) 2021 <NAME>
This software is released under the MIT License.
See the LICENSE file in the project root for more information.
"""
import argparse
import json
import os
import numpy as np
import open3d as... | [
"argparse.ArgumentParser",
"open3d.visualization.VisualizerWithKeyCallback",
"open3d.t.io.RealSenseSensor",
"os.path.isfile",
"open3d.t.io.RealSenseSensor.list_devices",
"open3d.t.io.RealSenseSensorConfig",
"open3d.geometry.RGBDImage.create_from_color_and_depth",
"open3d.geometry.PointCloud",
"open3... | [((3164, 3230), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""RealSene PointCloud Viewer."""'}), "(description='RealSene PointCloud Viewer.')\n", (3187, 3230), False, 'import argparse\n'), ((3513, 3552), 'open3d.t.io.RealSenseSensor.list_devices', 'o3d.t.io.RealSenseSensor.list_devices'... |
# <NAME>
# /Module for Binary Classification
from classification import ClassificationModel
import pandas as pd
import logging
import sklearn
# import fire
eval_df = pd.read_csv('/Volumes/Loopdisk/Bi_Transformer/data/dev.csv', sep='\t')
eval_df = eval_df[['0', '1']]
eval_df['0'] = eval_df['0'].astype(str)
model =... | [
"pandas.read_csv",
"classification.ClassificationModel"
] | [((170, 240), 'pandas.read_csv', 'pd.read_csv', (['"""/Volumes/Loopdisk/Bi_Transformer/data/dev.csv"""'], {'sep': '"""\t"""'}), "('/Volumes/Loopdisk/Bi_Transformer/data/dev.csv', sep='\\t')\n", (181, 240), True, 'import pandas as pd\n'), ((321, 375), 'classification.ClassificationModel', 'ClassificationModel', (['"""be... |
"""
sphinx_c_autodoc is a package which provide c source file parsing for sphinx.
It is composed of multiple directives and settings:
.. rst:directive:: .. c:module:: filename
A directive to document a c file. This is similar to :rst:dir:`py:module`
except it's for the C domain. This can be used for both c... | [
"sphinx.util.docstrings.prepare_docstring",
"docutils.statemachine.StringList",
"sphinx.ext.autodoc.directive.DocumenterBridge",
"itertools.groupby",
"re.compile",
"docutils.statemachine.ViewList",
"sphinx_c_autodoc.loader.load",
"os.path.isfile",
"sphinx.util.logging.getLogger",
"docutils.nodes.s... | [((1762, 1789), 'sphinx.util.logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1779, 1789), False, 'from sphinx.util import logging\n'), ((1723, 1750), 'dataclasses.field', 'field', ([], {'default_factory': 'dict'}), '(default_factory=dict)\n', (1728, 1750), False, 'from dataclasses import d... |
# coding: utf-8
# Copyright 2016 Vauxoo (https://www.vauxoo.com) <<EMAIL>>
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
import re
from odoo import models, api, fields, _
class AccountJournal(models.Model):
_inherit = 'account.journal'
@api.model
def _prepare_liquidity_account(self, na... | [
"odoo.api.onchange",
"re.search",
"odoo.fields.Selection"
] | [((1719, 1739), 'odoo.api.onchange', 'api.onchange', (['"""code"""'], {}), "('code')\n", (1731, 1739), False, 'from odoo import models, api, fields, _\n'), ((2030, 2183), 'odoo.fields.Selection', 'fields.Selection', (["[('D', 'Debitable Account'), ('A', 'Creditable Account')]"], {'help': '"""Used in Mexican report of e... |
# (C) Copyright 1996-2018 ECMWF.
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
# In applying this licence, ECMWF does not waive the privileges and immunities
# granted to it by virtue of its status as an intergov... | [
"datetime.datetime",
"os.path.exists",
"csv.DictReader",
"kronos_modeller.jobs.IngestedJob",
"datetime.datetime.strptime",
"kronos_modeller.jobs.ModelJob",
"os.path.isfile",
"kronos_modeller.kronos_exceptions.ConfigurationError"
] | [((7413, 7466), 'csv.DictReader', 'csv.DictReader', (['csvfile'], {'delimiter': '""";"""', 'quotechar': '"""\\""""'}), '(csvfile, delimiter=\';\', quotechar=\'"\')\n', (7427, 7466), False, 'import csv\n'), ((11169, 11222), 'csv.DictReader', 'csv.DictReader', (['csvfile'], {'delimiter': '""","""', 'quotechar': '"""\\"""... |
import numpy as np
import multiprocessing
import sys
have_cext = False
try:
from .. import _cext
have_cext = True
except ImportError:
pass
except:
print("the C extension is installed...but failed to load!")
pass
try:
import xgboost
except ImportError:
pass
except:
print("xgboost is ins... | [
"numpy.zeros",
"xgboost.DMatrix",
"catboost.Pool",
"multiprocessing.Pool"
] | [((6770, 6826), 'numpy.zeros', 'np.zeros', (['(self._current_X.shape[1] + 1, self.n_outputs)'], {}), '((self._current_X.shape[1] + 1, self.n_outputs))\n', (6778, 6826), True, 'import numpy as np\n'), ((5023, 5065), 'numpy.zeros', 'np.zeros', (['(X.shape[0] + 1, self.n_outputs)'], {}), '((X.shape[0] + 1, self.n_outputs)... |
import os
import shutil
from argparse import ArgumentParser
from tmd.bilayer.dgrid import get_prefixes
from tmd.bilayer.bilayer_util import global_config
def _main():
parser = ArgumentParser("wfc cleanup")
parser.add_argument("--subdir", type=str, default=None,
help="Subdirectory under work_base wh... | [
"tmd.bilayer.dgrid.get_prefixes",
"argparse.ArgumentParser",
"os.path.expandvars",
"os.path.join",
"shutil.rmtree",
"tmd.bilayer.bilayer_util.global_config"
] | [((181, 210), 'argparse.ArgumentParser', 'ArgumentParser', (['"""wfc cleanup"""'], {}), "('wfc cleanup')\n", (195, 210), False, 'from argparse import ArgumentParser\n'), ((699, 714), 'tmd.bilayer.bilayer_util.global_config', 'global_config', ([], {}), '()\n', (712, 714), False, 'from tmd.bilayer.bilayer_util import glo... |
from helpers import as_list
lines = as_list('2016/day6/input.txt')
# lines = as_list('2016/day6/example-input.txt')
length = len(lines[0])
positions = {
}
for line in lines:
for i, c in enumerate(line):
v = positions.setdefault(i, dict()).setdefault(c, 0)
positions[i][c] = v + 1
most_common = ... | [
"helpers.as_list"
] | [((37, 67), 'helpers.as_list', 'as_list', (['"""2016/day6/input.txt"""'], {}), "('2016/day6/input.txt')\n", (44, 67), False, 'from helpers import as_list\n')] |
import os
import time
max_brightness = 26666
stream = os.popen("cat /sys/class/backlight/intel_backlight/brightness")
output = int(stream.read())
print(f"{int(output/max_brightness * 100)}%")
| [
"os.popen"
] | [((55, 118), 'os.popen', 'os.popen', (['"""cat /sys/class/backlight/intel_backlight/brightness"""'], {}), "('cat /sys/class/backlight/intel_backlight/brightness')\n", (63, 118), False, 'import os\n')] |
"""The spalloc command-line tool and Python library determine their default
configuration options from a spalloc configuration file if present.
.. note::
Use of spalloc's configuration files is entirely optional as all
configuration options may be presented as arguments to commands/methods at
runtime.
By... | [
"appdirs.site_config_dir",
"appdirs.user_config_dir",
"six.moves.configparser.ConfigParser",
"six.iteritems"
] | [((3103, 3133), 'appdirs.site_config_dir', 'appdirs.site_config_dir', (['_name'], {}), '(_name)\n', (3126, 3133), False, 'import appdirs\n'), ((3153, 3183), 'appdirs.user_config_dir', 'appdirs.user_config_dir', (['_name'], {}), '(_name)\n', (3176, 3183), False, 'import appdirs\n'), ((3751, 3765), 'six.moves.configparse... |
from overrides import overrides
from allennlp.data import Instance
from allennlp.common.util import JsonDict
from allennlp.predictors.predictor import Predictor
@Predictor.register('nfh_classification')
class NfhDetectorPredictor(Predictor):
""""Predictor wrapper for the NfhDetector"""
@overrides
def _js... | [
"allennlp.predictors.predictor.Predictor.register"
] | [((165, 205), 'allennlp.predictors.predictor.Predictor.register', 'Predictor.register', (['"""nfh_classification"""'], {}), "('nfh_classification')\n", (183, 205), False, 'from allennlp.predictors.predictor import Predictor\n')] |
import numpy as np
from unityagents import UnityEnvironment
"""UnityEnv is a wrapper around UnityEnvironment
The main purpose for this Env is to establish a common interface which most environments expose
"""
class UnityEnv:
def __init__(self,
env_path,
train_mode = True... | [
"numpy.clip",
"numpy.prod",
"unityagents.UnityEnvironment",
"numpy.array"
] | [((1294, 1330), 'unityagents.UnityEnvironment', 'UnityEnvironment', ([], {'file_name': 'env_path'}), '(file_name=env_path)\n', (1310, 1330), False, 'from unityagents import UnityEnvironment\n'), ((1649, 1672), 'numpy.clip', 'np.clip', (['actions', '(-1)', '(1)'], {}), '(actions, -1, 1)\n', (1656, 1672), True, 'import n... |
# -----------------------------------------------------------------------------
# System Imports
# -----------------------------------------------------------------------------
from operator import itemgetter
# -----------------------------------------------------------------------------
# Public Imports
# ----------... | [
"operator.itemgetter",
"netcad.topology.TopologyDesignService"
] | [((1338, 1404), 'netcad.topology.TopologyDesignService', 'TopologyDesignService', ([], {'topology_name': 'design.name', 'devices': 'all_devs'}), '(topology_name=design.name, devices=all_devs)\n', (1359, 1404), False, 'from netcad.topology import TopologyDesignService\n'), ((1592, 1626), 'operator.itemgetter', 'itemgett... |
import torch
from torch import nn
import pdb, os
from shapely.geometry import *
from maskrcnn_benchmark.structures.boxlist_ops import cat_boxlist
import time
import matplotlib.pyplot as plt
import numpy as np
from scipy.signal import argrelextrema
import random
import string
all_types = [[1,2,3,4],[1,2,4,3],[1,3,2,4... | [
"torch.nn.functional.grid_sample",
"numpy.ceil",
"torch.ones_like",
"cv2.resize",
"torch.full",
"maskrcnn_benchmark.structures.ke.textKES",
"torch.stack",
"torch.from_numpy",
"maskrcnn_benchmark.structures.bounding_box.BoxList",
"numpy.exp",
"numpy.zeros",
"torch.linspace",
"numpy.maximum",
... | [((3298, 3319), 'numpy.maximum', 'np.maximum', (['widths', '(1)'], {}), '(widths, 1)\n', (3308, 3319), True, 'import numpy as np\n'), ((3334, 3356), 'numpy.maximum', 'np.maximum', (['heights', '(1)'], {}), '(heights, 1)\n', (3344, 3356), True, 'import numpy as np\n'), ((3375, 3390), 'numpy.ceil', 'np.ceil', (['widths']... |
import streamlit as st
import numpy as np
import matplotlib.pyplot as plt
perc_heads = st.number_input(label='Chance of Coins Landing on Heads', min_value=0.0, max_value=1.0, value=.5)
graph_title = st.text_input(label='Graph Title')
binom_dist = np.random.binomial(1, perc_heads, 1000)
list_of_means =... | [
"matplotlib.pyplot.hist",
"streamlit.pyplot",
"streamlit.number_input",
"numpy.random.choice",
"matplotlib.pyplot.title",
"streamlit.text_input",
"matplotlib.pyplot.subplots",
"numpy.random.binomial"
] | [((98, 200), 'streamlit.number_input', 'st.number_input', ([], {'label': '"""Chance of Coins Landing on Heads"""', 'min_value': '(0.0)', 'max_value': '(1.0)', 'value': '(0.5)'}), "(label='Chance of Coins Landing on Heads', min_value=0.0,\n max_value=1.0, value=0.5)\n", (113, 200), True, 'import streamlit as st\n'), ... |
import sys
import emailprotectionslib.dmarc as dmarc
from MaltegoTransform import *
mt = MaltegoTransform()
mt.parseArguments(sys.argv)
domain = mt.getValue()
mt = MaltegoTransform()
try:
dmarc_record = dmarc.DmarcRecord.from_domain(domain)
#print spf_record
mt.addEntity("maltego.Phrase","DMARC Record: "... | [
"emailprotectionslib.dmarc.DmarcRecord.from_domain"
] | [((210, 247), 'emailprotectionslib.dmarc.DmarcRecord.from_domain', 'dmarc.DmarcRecord.from_domain', (['domain'], {}), '(domain)\n', (239, 247), True, 'import emailprotectionslib.dmarc as dmarc\n')] |
# -*- coding: utf-8 -*-
"""
idfy_rest_client.models.update_signer_request_wrapper
This file was automatically generated for Idfy by APIMATIC v2.0 ( https://apimatic.io )
"""
from idfy_rest_client.api_helper import APIHelper
import idfy_rest_client.models.redirect_settings
import idfy_rest_client.mode... | [
"idfy_rest_client.api_helper.APIHelper.RFC3339DateTime"
] | [((3204, 3247), 'idfy_rest_client.api_helper.APIHelper.RFC3339DateTime', 'APIHelper.RFC3339DateTime', (['sign_url_expires'], {}), '(sign_url_expires)\n', (3229, 3247), False, 'from idfy_rest_client.api_helper import APIHelper\n')] |
import os
def obtenNombreArchivos(ruta):
archivos = list()
with os.scandir(ruta) as ficheros:
for fichero in ficheros:
archivos.append(fichero.name)
return archivos
def concatenaRegistros(ruta,nombreArchivo):
registroConcatenado = list()
with open(ruta,'r') as lecturaArchivo:
for registr... | [
"os.scandir"
] | [((73, 89), 'os.scandir', 'os.scandir', (['ruta'], {}), '(ruta)\n', (83, 89), False, 'import os\n')] |
import os
import requests
import time
import json
import io
import numpy as np
import pandas as pd
import paavo_queries as paavo_queries
from sklearn.linear_model import LinearRegression
import statsmodels.api as sm
## NOTE: Table 9_koko access is forbidden from the API for some reasons.
# url to the API... | [
"os.path.exists",
"json.loads",
"requests.post",
"os.makedirs",
"pandas.read_csv",
"numpy.where",
"os.path.join",
"io.BytesIO",
"time.sleep",
"numpy.array",
"statsmodels.api.add_constant",
"numpy.isnan",
"pandas.DataFrame",
"statsmodels.api.OLS",
"sklearn.linear_model.LinearRegression"
] | [((758, 823), 'requests.post', 'requests.post', (['url'], {'json': 'query', 'stream': '(True)', 'allow_redirects': '(True)'}), '(url, json=query, stream=True, allow_redirects=True)\n', (771, 823), False, 'import requests\n'), ((947, 993), 'os.path.join', 'os.path.join', (['destination_directory', 'file_name'], {}), '(d... |
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import OrdinalEncoder, StandardScaler, OneHotEncoder
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split, GridSearc... | [
"sklearn.preprocessing.OneHotEncoder",
"sklearn.preprocessing.StandardScaler",
"numpy.array",
"pandas.to_numeric",
"sklearn.impute.SimpleImputer",
"pandas.DataFrame"
] | [((373, 431), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {'copy': '(False)', 'with_mean': '(False)', 'with_std': '(True)'}), '(copy=False, with_mean=False, with_std=True)\n', (387, 431), False, 'from sklearn.preprocessing import OrdinalEncoder, StandardScaler, OneHotEncoder\n'), ((2839, 2879), 'pand... |
# For SSH
import Exscript
# For Color Font
from colorama import init as colorama_init
from colorama import Fore
colorama_init(autoreset=True)
username = "user1"
password = "<PASSWORD>"
ip4 = "192.168.33.3"
# SSHセッションの確立
session = Exscript.protocols.SSH2()
session.connect(ip4)
# ルータにログイン
account = Exscript.Account(n... | [
"Exscript.Account",
"Exscript.protocols.SSH2",
"colorama.init"
] | [((113, 142), 'colorama.init', 'colorama_init', ([], {'autoreset': '(True)'}), '(autoreset=True)\n', (126, 142), True, 'from colorama import init as colorama_init\n'), ((233, 258), 'Exscript.protocols.SSH2', 'Exscript.protocols.SSH2', ([], {}), '()\n', (256, 258), False, 'import Exscript\n'), ((302, 352), 'Exscript.Acc... |
import time
from tasks.capp import app
from others.affine_applications import MoveApps
@app.task(name="sdc.move11", bind=True)
def task_1(self, x):
time.sleep(1)
return MoveApps(":move", x).foo()
@app.task(name="sdc.move12", bind=True)
def task_2(self, x):
return MoveApps(":move", x + 1).foo()
| [
"tasks.capp.app.task",
"others.affine_applications.MoveApps",
"time.sleep"
] | [((91, 129), 'tasks.capp.app.task', 'app.task', ([], {'name': '"""sdc.move11"""', 'bind': '(True)'}), "(name='sdc.move11', bind=True)\n", (99, 129), False, 'from tasks.capp import app\n'), ((210, 248), 'tasks.capp.app.task', 'app.task', ([], {'name': '"""sdc.move12"""', 'bind': '(True)'}), "(name='sdc.move12', bind=Tru... |
from django.db import models
from django.contrib.auth.models import User
from PIL import Image
# Create your models here.
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='profile_pics/')
contacts=models.CharF... | [
"django.db.models.ImageField",
"django.db.models.OneToOneField",
"django.db.models.CharField"
] | [((162, 214), 'django.db.models.OneToOneField', 'models.OneToOneField', (['User'], {'on_delete': 'models.CASCADE'}), '(User, on_delete=models.CASCADE)\n', (182, 214), False, 'from django.db import models\n'), ((227, 294), 'django.db.models.ImageField', 'models.ImageField', ([], {'default': '"""default.jpg"""', 'upload_... |
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 16 11:40:09 2017
@author: florentin
"""
import serial
from os import getcwd
## paramètres du port série
#port = input("Quel numéro de port COM voulez-vous écouter?\n")
#vitesse = int(input("Quelle vitesse en baud?\n"))
#caracFin = input("Quel(s) caractère(s) de fin de c... | [
"serial.Serial"
] | [((561, 597), 'serial.Serial', 'serial.Serial', (["('COM' + port)", 'vitesse'], {}), "('COM' + port, vitesse)\n", (574, 597), False, 'import serial\n')] |
import logging
from django import template
from django.db.models import Q
from django.utils import timezone
from django.utils.safestring import SafeString
from cms.contexts.utils import handle_faulty_templates
from cms.publications.models import Category, Publication, PublicationContext
logger = logging.getLogger(_... | [
"logging.getLogger",
"django.utils.safestring.SafeString",
"cms.publications.models.Publication.objects.filter",
"cms.publications.models.PublicationContext.objects.filter",
"django.utils.timezone.localtime",
"cms.publications.models.Category.objects.exclude",
"cms.contexts.utils.handle_faulty_templates... | [((301, 328), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (318, 328), False, 'import logging\n'), ((340, 358), 'django.template.Library', 'template.Library', ([], {}), '()\n', (356, 358), False, 'from django import template\n'), ((552, 572), 'django.utils.timezone.localtime', 'timezone... |
# -*- mode: python; encoding: utf-8 -*-
#
# Copyright 2012 <NAME>, Opera Software ASA
#
# 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
#
# Unl... | [
"diff.File",
"gitutils.Commit.fromId",
"diff.Chunk",
"diff.Changeset.fromId"
] | [((2874, 3008), 'diff.File', 'diff.File', (['file_id', 'file_path', 'file_old_sha1', 'file_new_sha1', 'repository'], {'old_mode': 'file_old_mode', 'new_mode': 'file_new_mode', 'chunks': '[]'}), '(file_id, file_path, file_old_sha1, file_new_sha1, repository,\n old_mode=file_old_mode, new_mode=file_new_mode, chunks=[]... |
#!/usr/bin/env python3
from powerdnsadmin import create_app
app = create_app()
| [
"powerdnsadmin.create_app"
] | [((68, 80), 'powerdnsadmin.create_app', 'create_app', ([], {}), '()\n', (78, 80), False, 'from powerdnsadmin import create_app\n')] |
#!/usr/bin/python3
# ==================================================
"""
File: RMedian - Unittest - Phase 1
Author: <NAME>
"""
# ==================================================
# Import
import math
import random
import pytest
# ==================================================
# Phase 1
def phase1(X, k, d):... | [
"math.ceil",
"random.shuffle",
"math.floor",
"math.log2",
"math.log",
"random.randint"
] | [((359, 376), 'random.shuffle', 'random.shuffle', (['X'], {}), '(X)\n', (373, 376), False, 'import random\n'), ((1405, 1436), 'random.randint', 'random.randint', (['(2 ** 9)', '(2 ** 15)'], {}), '(2 ** 9, 2 ** 15)\n', (1419, 1436), False, 'import random\n'), ((906, 932), 'math.floor', 'math.floor', (['(k / 2 - lst[0])'... |
from typing import Dict, Iterable, List, Optional, Union
from functools import partial
import torch
import torch.nn as nn
from torch.nn import functional as F
import pytorch_lightning as pl
class BaseException(Exception):
def __init__(
self,
parameter,
types: List):
me... | [
"torch.no_grad"
] | [((2414, 2429), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (2427, 2429), False, 'import torch\n'), ((2968, 2983), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (2981, 2983), False, 'import torch\n')] |
import tkinter as tk
class ScrolledFrame(tk.Frame):
def __init__(self, parent, vertical=True, horizontal=False):
super().__init__(parent)
# canvas for inner frame
self._canvas = tk.Canvas(self)
self._canvas.grid(row=0, column=0, sticky='news') # changed
# create right scr... | [
"tkinter.Canvas",
"tkinter.Scrollbar",
"tkinter.Frame"
] | [((209, 224), 'tkinter.Canvas', 'tk.Canvas', (['self'], {}), '(self)\n', (218, 224), True, 'import tkinter as tk\n'), ((380, 445), 'tkinter.Scrollbar', 'tk.Scrollbar', (['self'], {'orient': '"""vertical"""', 'command': 'self._canvas.yview'}), "(self, orient='vertical', command=self._canvas.yview)\n", (392, 445), True, ... |
import logging
import goaway.globalvars as globalvars
logger = logging.getLogger(__name__)
DATA_STORE_HANDLE_KIND_ATTR = "__store"
NAME_ATTR = "__name"
class ObjectHandle(object):
"""
Represents a shared object in a datstore.
Instances of this class are returned by object handle constructors.
Applic... | [
"logging.getLogger"
] | [((65, 92), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (82, 92), False, 'import logging\n')] |
import os
import mimetypes
import chardet
UTF8 = ('utf-8', 'ascii')
WANTED_CHARSET = UTF8
FILE_PATH = '.'
THRESHOLD = 0.6
# Chardet cannot recognize ISO-8859-1 charset.
RECOGNIZE_8859_2_AS_8859_1 = True
LOG_FILE_CONVERTED = '/dcclog/converted'
LOG_FILE_UNCONVERTED = '/dcclog/unconverted'
LOG_FILE_CAN_NOT_DETECT = '/... | [
"os.path.samefile",
"os.path.join",
"os.path.split",
"chardet.detect",
"os.mkdir",
"mimetypes.guess_type",
"os.walk",
"os.remove"
] | [((1473, 1491), 'os.walk', 'os.walk', (['FILE_PATH'], {}), '(FILE_PATH)\n', (1480, 1491), False, 'import os\n'), ((741, 772), 'os.mkdir', 'os.mkdir', (["(FILE_PATH + '/dcclog')"], {}), "(FILE_PATH + '/dcclog')\n", (749, 772), False, 'import os\n'), ((1220, 1256), 'os.path.samefile', 'os.path.samefile', (['dirpath', 'FI... |
import os
import sys
import unittest
from test.support import run_unittest, import_module
# Skip tests if we don't have threading.
import_module('threading')
# Skip tests if we don't have concurrent.futures.
import_module('concurrent.futures')
def suite():
tests = unittest.TestSuite()
loader = unittest.TestL... | [
"os.path.dirname",
"unittest.TestSuite",
"unittest.TestLoader",
"test.support.import_module"
] | [((132, 158), 'test.support.import_module', 'import_module', (['"""threading"""'], {}), "('threading')\n", (145, 158), False, 'from test.support import run_unittest, import_module\n'), ((209, 244), 'test.support.import_module', 'import_module', (['"""concurrent.futures"""'], {}), "('concurrent.futures')\n", (222, 244),... |
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.models import User
from django.shortcuts import render, redirect
from django.contrib.auth import login as auth_login
from django.contrib.auth import logout as auth_logout
# Create your views here.
from django.views.generic import View
... | [
"django.shortcuts.render",
"django.contrib.auth.login",
"django.shortcuts.redirect",
"django.contrib.auth.models.User.objects.get",
"django.contrib.auth.models.User.objects.create_user",
"django.contrib.auth.logout"
] | [((389, 442), 'django.shortcuts.render', 'render', (['request', '"""signup.html"""', "{'user_exist': False}"], {}), "(request, 'signup.html', {'user_exist': False})\n", (395, 442), False, 'from django.shortcuts import render, redirect\n'), ((803, 833), 'django.contrib.auth.login', 'auth_login', (['request'], {'user': '... |
import pandas as pd
from xml.etree import ElementTree as etree
from pprint import pprint
from yattag import *
import pdb
#------------------------------------------------------------------------------------------------------------------------
# -*- coding: utf-8 -*-
#----------------------------------------------------... | [
"pandas.DataFrame",
"pandas.isnull",
"pandas.concat",
"pdb.set_trace"
] | [((4682, 4726), 'pandas.DataFrame', 'pd.DataFrame', (['(e.attrib for e in lineElements)'], {}), '(e.attrib for e in lineElements)\n', (4694, 4726), True, 'import pandas as pd\n'), ((5390, 5442), 'pandas.DataFrame', 'pd.DataFrame', (["{'START': startTimes, 'END': endTimes}"], {}), "({'START': startTimes, 'END': endTimes... |
from dl_plus.cli import main
main()
| [
"dl_plus.cli.main"
] | [((31, 37), 'dl_plus.cli.main', 'main', ([], {}), '()\n', (35, 37), False, 'from dl_plus.cli import main\n')] |
import torch
import numpy as np
from torch.utils.data import Dataset
import torchvision.transforms.functional as TF
import torchvision.transforms as transforms
import random
import glob
import os
from PIL import Image
'''
require fix the random seeds
'''
# PotsdamDataset
rgb_means = [0.3366, 0.3599, 0.3333]
rgb_stds =... | [
"torchvision.transforms.functional.to_tensor",
"PIL.Image.open",
"os.path.join",
"torchvision.transforms.functional.hflip",
"numpy.array",
"torchvision.transforms.functional.rotate",
"torchvision.transforms.functional.vflip",
"torch.tensor",
"random.random",
"torchvision.transforms.functional.norm... | [((2291, 2310), 'torchvision.transforms.functional.to_tensor', 'TF.to_tensor', (['image'], {}), '(image)\n', (2303, 2310), True, 'import torchvision.transforms.functional as TF\n'), ((2327, 2376), 'torchvision.transforms.functional.normalize', 'TF.normalize', (['image'], {'mean': 'rgb_means', 'std': 'rgb_stds'}), '(ima... |
import ipaddress
from collections import defaultdict
from autonetkit.design.utils import filters
from autonetkit.design.utils.general import group_by
from autonetkit.network_model.types import LAYER3_DEVICES
def assign_loopbacks(topology):
"""
@param topology:
"""
layer3_nodes = [n for n in topology... | [
"ipaddress.IPv4Network",
"autonetkit.design.utils.filters.broadcast_domains",
"collections.defaultdict",
"autonetkit.design.utils.general.group_by"
] | [((399, 437), 'ipaddress.IPv4Network', 'ipaddress.IPv4Network', (['"""172.16.0.0/16"""'], {}), "('172.16.0.0/16')\n", (420, 437), False, 'import ipaddress\n'), ((516, 545), 'autonetkit.design.utils.general.group_by', 'group_by', (['layer3_nodes', '"""asn"""'], {}), "(layer3_nodes, 'asn')\n", (524, 545), False, 'from au... |
#******************************************************************************
# (C) 2018, <NAME>, Austria *
# *
# The Space Python Library is free software; you can redistribute it and/or *
# modif... | [
"UTIL.SYS.LOG_WARNING",
"socket.socket",
"UTIL.SYS.Error",
"UTIL.SYS.LOG_INFO",
"sys.exit",
"UTIL.SYS.LOG_ERROR"
] | [((1427, 1442), 'socket.socket', 'socket.socket', ([], {}), '()\n', (1440, 1442), False, 'import socket, sys\n'), ((26027, 26039), 'sys.exit', 'sys.exit', (['(-1)'], {}), '(-1)\n', (26035, 26039), False, 'import socket, sys\n'), ((2181, 2240), 'UTIL.SYS.LOG_ERROR', 'LOG_ERROR', (["('TMreceiver.recvError: ' + errorMessa... |
"""
Run Intervals. Takes 3 values from user, counts down intervals.
wanted: Data class that holds state
"""
from datetime import timedelta
import time
import toga
from toga.style import Pack
from toga.style.pack import COLUMN, ROW
class RunIntervals(toga.App):
"""
__init__ values in __init__.py:
runsNu... | [
"toga.style.Pack",
"toga.MainWindow",
"time.sleep",
"datetime.timedelta",
"time.time"
] | [((3510, 3549), 'toga.MainWindow', 'toga.MainWindow', ([], {'title': 'self.formal_name'}), '(title=self.formal_name)\n', (3525, 3549), False, 'import toga\n'), ((4719, 4746), 'datetime.timedelta', 'timedelta', ([], {'seconds': '"""toWait"""'}), "(seconds='toWait')\n", (4728, 4746), False, 'from datetime import timedelt... |
# Advent of Code
# Day 1 Problem 1
import pandas as pd
nums = pd.read_csv('adventofcode2020_day1.csv')
numlist = nums.values.tolist()
flatList = [item for elem in numlist for item in elem]
for i in range(len(flatList)):
testnum = int(flatList[i])
neednum = 2020 - testnum
if neednum in flatList:
... | [
"pandas.read_csv"
] | [((65, 105), 'pandas.read_csv', 'pd.read_csv', (['"""adventofcode2020_day1.csv"""'], {}), "('adventofcode2020_day1.csv')\n", (76, 105), True, 'import pandas as pd\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
from bms_state_machine import BMSChargeStateMachine, BMSChargeModel, BMSChargeController
# 48V 16S LiFePO4 Battery
# Absorption: 58V (56.4 for longer life)
# Float: 54.4V
# Restart bulk voltage: Float-0.8 (max of 54V)
# Inverter Cut-off: 42.8V-48V (depending ... | [
"bms_state_machine.BMSChargeController",
"time.sleep"
] | [((376, 521), 'bms_state_machine.BMSChargeController', 'BMSChargeController', ([], {'charge_bulk_current': '(160)', 'charge_absorb_voltage': '(58.4)', 'charge_float_voltage': '(54.4)', 'time_min_absorb': '(0.5)', 'rebulk_voltage': '(53.6)'}), '(charge_bulk_current=160, charge_absorb_voltage=58.4,\n charge_float_volt... |
# -*- coding: utf-8 -*-
import pytest
from numpy import pi
from os.path import join
from pyleecan.Classes.LamSlotWind import LamSlotWind
from pyleecan.Classes.SlotW11 import SlotW11
from pyleecan.Classes.WindingDW1L import WindingDW1L
from pyleecan.Classes.CondType12 import CondType12
from pyleecan.Functions.load impo... | [
"pytest.fixture",
"pytest.approx",
"os.path.join"
] | [((373, 403), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (387, 403), False, 'import pytest\n'), ((438, 479), 'os.path.join', 'join', (['DATA_DIR', '"""Machine"""', '"""IPMSM_A.json"""'], {}), "(DATA_DIR, 'Machine', 'IPMSM_A.json')\n", (442, 479), False, 'from os.path impo... |
import numpy as np
def random_policy(env):
counter = 0
total_rewards = 0
reward = None
rewardTracker = []
while reward != 1:
env.render()
state, reward, done, info = env.step(env.action_space.sample())
total_rewards += reward
if done:
rewardTracker.appen... | [
"numpy.zeros",
"numpy.random.randn",
"numpy.random.rand",
"numpy.max"
] | [((999, 1054), 'numpy.zeros', 'np.zeros', (['[env.observation_space.n, env.action_space.n]'], {}), '([env.observation_space.n, env.action_space.n])\n', (1007, 1054), True, 'import numpy as np\n'), ((600, 616), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (614, 616), True, 'import numpy as np\n'), ((720, 749... |
"""
:copyright: (c) 2019 Pinn Technologies, Inc.
:license: MIT
"""
def test_import():
import pinn
def test_configuration_error():
import pinn
try:
pinn.User.create()
except pinn.errors.ConfigurationError:
pass
def test_authentication_error():
import pinn
pinn.secret_key = '... | [
"pinn.User.create"
] | [((171, 189), 'pinn.User.create', 'pinn.User.create', ([], {}), '()\n', (187, 189), False, 'import pinn\n'), ((342, 360), 'pinn.User.create', 'pinn.User.create', ([], {}), '()\n', (358, 360), False, 'import pinn\n')] |
"""Sliding windows for connectivity functions."""
from frites.io import set_log_level, logger
import numpy as np
def define_windows(times, windows=None, slwin_len=None, slwin_start=None,
slwin_stop=None, slwin_step=None, verbose=None):
"""Define temporal windows.
This function can be used... | [
"frites.io.set_log_level",
"frites.io.logger.info",
"numpy.atleast_2d",
"numpy.abs",
"matplotlib.patches.Rectangle",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.plot",
"matplotlib.collections.PatchCollection",
"numpy.array",
"matplotlib.pyplot.title",
"matplotlib.pyplot.xlim",
"numpy.zeros_lik... | [((1791, 1813), 'frites.io.set_log_level', 'set_log_level', (['verbose'], {}), '(verbose)\n', (1804, 1813), False, 'from frites.io import set_log_level, logger\n'), ((1859, 1899), 'frites.io.logger.info', 'logger.info', (['"""Defining temporal windows"""'], {}), "('Defining temporal windows')\n", (1870, 1899), False, '... |
import torch
from torch import nn
from torch.autograd import Variable
from torch.distributions import Categorical
from torch.nn import functional as F
def classify(logits):
if len(logits.shape) == 1:
logits = logits.view(1, -1)
distribution = Categorical(F.softmax(logits, dim=1))
atn = distributio... | [
"torch.nn.ReLU",
"torch.nn.LSTM",
"torch.nn.Conv2d",
"torch.nn.Linear",
"torch.nn.functional.softmax",
"torch.cat"
] | [((273, 297), 'torch.nn.functional.softmax', 'F.softmax', (['logits'], {'dim': '(1)'}), '(logits, dim=1)\n', (282, 297), True, 'from torch.nn import functional as F\n'), ((492, 511), 'torch.nn.Linear', 'nn.Linear', (['h', 'nattn'], {}), '(h, nattn)\n', (501, 511), False, 'from torch import nn\n'), ((1409, 1440), 'torch... |
from taskplus.core.actions import ListTaskStatusesRequest
def test_list_user_roles_request_without_parameters():
request = ListTaskStatusesRequest()
assert request.filters is None
assert request.is_valid() is True
def test_list_user_roles_request_with_empty_filters():
request = ListTaskStatusesRequ... | [
"taskplus.core.actions.ListTaskStatusesRequest"
] | [((129, 154), 'taskplus.core.actions.ListTaskStatusesRequest', 'ListTaskStatusesRequest', ([], {}), '()\n', (152, 154), False, 'from taskplus.core.actions import ListTaskStatusesRequest\n'), ((300, 335), 'taskplus.core.actions.ListTaskStatusesRequest', 'ListTaskStatusesRequest', ([], {'filters': '{}'}), '(filters={})\n... |
#!/usr/bin/env python3
import os
import re
import sys
def main():
if len(sys.argv) != 2:
print("Usage: %s input-file" % sys.argv[0])
sys.exit(1)
macro_pattern = re.compile("#define\s+(\w+)\s+([a-zA-Z0-9_\-]+)\s*(.*)")
consts_pattern = re.compile("\s*([A-Z_0-9]+)\s*=\s*([0-9\-\.xXa-fA-F]+... | [
"sys.exit",
"re.compile"
] | [((189, 250), 're.compile', 're.compile', (['"""#define\\\\s+(\\\\w+)\\\\s+([a-zA-Z0-9_\\\\-]+)\\\\s*(.*)"""'], {}), "('#define\\\\s+(\\\\w+)\\\\s+([a-zA-Z0-9_\\\\-]+)\\\\s*(.*)')\n", (199, 250), False, 'import re\n'), ((267, 332), 're.compile', 're.compile', (['"""\\\\s*([A-Z_0-9]+)\\\\s*=\\\\s*([0-9\\\\-\\\\.xXa-fA-F... |
import xlwt
class DRIVER:
# An Interface
def parse(self, s):
return None # Return an tuple
class TABLE:
def __init__(self, sentence, driver):
self.comment, self.table_name, self.columns, self.engine, self.charset = driver.parse(sentence)
def output(self, xls):
bold_title = x... | [
"xlwt.easyxf"
] | [((319, 407), 'xlwt.easyxf', 'xlwt.easyxf', (['"""font: name Times New Roman, bold on; align:horiz center, vert center"""'], {}), "(\n 'font: name Times New Roman, bold on; align:horiz center, vert center')\n", (330, 407), False, 'import xlwt\n'), ((426, 500), 'xlwt.easyxf', 'xlwt.easyxf', (['"""font: name Times New... |
from django.core.files.uploadedfile import SimpleUploadedFile
from easy_tenants import tenant_context_disabled
from easy_tenants.storage import TenantFileSystemStorage
def test_default_storage(tenant_ctx, settings):
tenant_id = str(tenant_ctx.id)
s = TenantFileSystemStorage()
file = SimpleUploadedFile("t... | [
"easy_tenants.storage.TenantFileSystemStorage",
"django.core.files.uploadedfile.SimpleUploadedFile",
"easy_tenants.tenant_context_disabled"
] | [((262, 287), 'easy_tenants.storage.TenantFileSystemStorage', 'TenantFileSystemStorage', ([], {}), '()\n', (285, 287), False, 'from easy_tenants.storage import TenantFileSystemStorage\n'), ((299, 345), 'django.core.files.uploadedfile.SimpleUploadedFile', 'SimpleUploadedFile', (['"""test.txt"""', "b'any content'"], {}),... |
# FIXME this class is not done yet
import logging
import platform
import subprocess
LOGGER = logging.getLogger("scope-admin")
class ScopeExternalService:
def __init__(self, tag, paramsDict):
self._tag = tag
self._name = paramsDict["name"]
self._description = paramsDict["description"]
... | [
"logging.getLogger",
"platform.system",
"subprocess.call"
] | [((95, 127), 'logging.getLogger', 'logging.getLogger', (['"""scope-admin"""'], {}), "('scope-admin')\n", (112, 127), False, 'import logging\n'), ((1348, 1372), 'subprocess.call', 'subprocess.call', (['command'], {}), '(command)\n', (1363, 1372), False, 'import subprocess\n'), ((1178, 1195), 'platform.system', 'platform... |
# ===================================
# Import the libraries
# ===================================
import numpy as np
from matplotlib import pylab as plt
import imaging
import utility
import os,sys
# ===================================
# Which stages to run
# ===================================
do_add_noise = False
d... | [
"numpy.fromfile",
"imaging.bad_pixel_correction",
"imaging.chromatic_aberration_correction",
"imaging.tone_mapping",
"imaging.sharpening",
"imaging.distortion_correction",
"imaging.memory_color_enhancement",
"imaging.lens_shading_correction",
"imaging.bayer_denoising",
"numpy.empty",
"imaging.Im... | [((827, 855), 'os.system', 'os.system', (['"""rm images/*.png"""'], {}), "('rm images/*.png')\n", (836, 855), False, 'import os, sys\n'), ((1654, 1722), 'numpy.fromfile', 'np.fromfile', (["('images/' + image_name + '.raw')"], {'dtype': '"""uint16"""', 'sep': '""""""'}), "('images/' + image_name + '.raw', dtype='uint16'... |
import redis
import time
import json
redis_host = 'localhost'
redis_port = '6379'
channel = "hello-channel"
publisher = redis.Redis(host=redis_host, port=redis_port)
count = 0
while True:
count += 1
message = {
'text': 'Hello World',
'count': count
}
publisher.publish(channel, json.du... | [
"json.dumps",
"time.sleep",
"redis.Redis"
] | [((123, 168), 'redis.Redis', 'redis.Redis', ([], {'host': 'redis_host', 'port': 'redis_port'}), '(host=redis_host, port=redis_port)\n', (134, 168), False, 'import redis\n'), ((401, 414), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (411, 414), False, 'import time\n'), ((313, 332), 'json.dumps', 'json.dumps', (['... |
import logging
from bson.objectid import ObjectId
from django import forms
from django.conf import settings
from django.contrib import messages
from django.contrib.admin.views.decorators import staff_member_required
from django.shortcuts import render, redirect, get_object_or_404
from django.utils.translation import u... | [
"logging.getLogger",
"django.shortcuts.render",
"django.utils.translation.ugettext_lazy",
"models.PhoneData.objects.order_by",
"models.InstalledApp.objects.get_top_apps",
"django.forms.CharField",
"pycountry.countries.get",
"bson.objectid.ObjectId",
"django.shortcuts.get_object_or_404",
"models.Ph... | [((423, 450), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (440, 450), False, 'import logging\n'), ((855, 920), 'django.shortcuts.render', 'render', (['request', 'tmpl', "{'cards': info, 'cl': cl}"], {'content_type': 'ct'}), "(request, tmpl, {'cards': info, 'cl': cl}, content_type=ct)\n... |
import argparse
parser = argparse.ArgumentParser(description="Generate path to config file given input")
parser.add_argument('vars', nargs='+')
args = parser.parse_args()
# The last item of vars contains the random seed
result = '-'.join(args.vars[:-1])
print(result)
| [
"argparse.ArgumentParser"
] | [((26, 105), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Generate path to config file given input"""'}), "(description='Generate path to config file given input')\n", (49, 105), False, 'import argparse\n')] |
from setuptools import setup
setup(name='my_project',
version='0.1.0',
packages=['my_project'],
entry_points={
'console_scripts': [
'my_project = my_project.__main__:main'
]
},
)
| [
"setuptools.setup"
] | [((32, 184), 'setuptools.setup', 'setup', ([], {'name': '"""my_project"""', 'version': '"""0.1.0"""', 'packages': "['my_project']", 'entry_points': "{'console_scripts': ['my_project = my_project.__main__:main']}"}), "(name='my_project', version='0.1.0', packages=['my_project'],\n entry_points={'console_scripts': ['m... |
import os
import sys
import imp
import argparse
import time
import math
import numpy as np
from utils import utils
from utils.imageprocessing import preprocess
from utils.dataset import Dataset
from network import Network
from evaluation.lfw import LFWTest
def main(args):
paths = [
r'F:\data\face-recog... | [
"numpy.mean",
"utils.utils.pair_MLS_score",
"argparse.ArgumentParser",
"numpy.log",
"numpy.max",
"network.Network",
"utils.utils.pair_cosin_score",
"numpy.concatenate",
"numpy.min",
"utils.imageprocessing.preprocess"
] | [((1241, 1250), 'network.Network', 'Network', ([], {}), '()\n', (1248, 1250), False, 'from network import Network\n'), ((1388, 1428), 'utils.imageprocessing.preprocess', 'preprocess', (['paths', 'network.config', '(False)'], {}), '(paths, network.config, False)\n', (1398, 1428), False, 'from utils.imageprocessing impor... |
from django.conf.urls import url
from personal.models import Book
from . import views
from django.contrib.auth.views import login
from django.views.generic import ListView, DetailView
urlpatterns = [
url(r'^$', views.index , name='index'),
url(r'^login/$', login, {'template_name': 'personal/login.html'}),
... | [
"personal.models.Book.objects.all",
"django.views.generic.DetailView.as_view",
"django.conf.urls.url"
] | [((207, 243), 'django.conf.urls.url', 'url', (['"""^$"""', 'views.index'], {'name': '"""index"""'}), "('^$', views.index, name='index')\n", (210, 243), False, 'from django.conf.urls import url\n'), ((251, 315), 'django.conf.urls.url', 'url', (['"""^login/$"""', 'login', "{'template_name': 'personal/login.html'}"], {}),... |