code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from events.models import Category, Language, City
import uuid
class UserCategory(models.Model):
user_id = models.ForeignKey(User)
category_id = models.F... | [
"django.db.models.OneToOneField",
"django.db.models.ForeignKey",
"django.dispatch.receiver",
"django.db.models.BooleanField",
"django.db.models.EmailField",
"django.db.models.DateField",
"django.db.models.UUIDField"
] | [((1600, 1632), 'django.dispatch.receiver', 'receiver', (['post_save'], {'sender': 'User'}), '(post_save, sender=User)\n', (1608, 1632), False, 'from django.dispatch import receiver\n'), ((1760, 1792), 'django.dispatch.receiver', 'receiver', (['post_save'], {'sender': 'User'}), '(post_save, sender=User)\n', (1768, 1792... |
import shutil, os, glob
src = 'train'
dst = 'SIG17/train'
if not os.path.exists('SIG17'):
os.mkdir('SIG17')
os.mkdir(dst)
elif not os.path.exists(dst):
os.mkdir(dst)
count = 1
for s in glob.glob(src + '/*'):
d = dst + '/{:03d}'.format(count)
if not os.path.exists(d):
os.mkdir(d... | [
"shutil.copyfile",
"os.mkdir",
"os.path.exists",
"glob.glob"
] | [((208, 229), 'glob.glob', 'glob.glob', (["(src + '/*')"], {}), "(src + '/*')\n", (217, 229), False, 'import shutil, os, glob\n'), ((1131, 1152), 'glob.glob', 'glob.glob', (["(src + '/*')"], {}), "(src + '/*')\n", (1140, 1152), False, 'import shutil, os, glob\n'), ((68, 91), 'os.path.exists', 'os.path.exists', (['"""SI... |
import pyautogui as pt
from time import sleep
while True:
posXY = pt.position()
print(posXY, pt.pixel(posXY[0],posXY[1]))
sleep(1)
if posXY[0] == 0:
break
# this program will tell axis of the cursor
# program will end if x-axis = 0
| [
"pyautogui.position",
"pyautogui.pixel",
"time.sleep"
] | [((75, 88), 'pyautogui.position', 'pt.position', ([], {}), '()\n', (86, 88), True, 'import pyautogui as pt\n'), ((141, 149), 'time.sleep', 'sleep', (['(1)'], {}), '(1)\n', (146, 149), False, 'from time import sleep\n'), ((107, 135), 'pyautogui.pixel', 'pt.pixel', (['posXY[0]', 'posXY[1]'], {}), '(posXY[0], posXY[1])\n'... |
'''
command for zim custom tool: python path/to/zim_to_md.py -T %T -f %f -D %D
* Markdown format: https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet
'''
import argparse
import pyperclip
from zim.formats import get_parser, StubLinker
from zim.formats.markdown import Dumper as TextDumper
class Dumper(... | [
"zim.formats.get_parser",
"zim.formats.StubLinker",
"argparse.ArgumentParser",
"pyperclip.copy"
] | [((778, 822), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '__doc__'}), '(description=__doc__)\n', (801, 822), False, 'import argparse\n'), ((1132, 1150), 'zim.formats.get_parser', 'get_parser', (['"""wiki"""'], {}), "('wiki')\n", (1142, 1150), False, 'from zim.formats import get_parser, S... |
# -*- coding: utf-8 -*-
from setuptools import find_packages
from cx_Freeze import setup, Executable
import apyml
install_requires = [
'cx_Freeze'
'pandas'
]
setup(
name='apyml',
version=apyml.__version__,
packages=find_packages(),
author=apyml.__author__,
author_email='<EMAIL>',
... | [
"cx_Freeze.Executable",
"setuptools.find_packages"
] | [((242, 257), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (255, 257), False, 'from setuptools import find_packages\n'), ((841, 861), 'cx_Freeze.Executable', 'Executable', (['"""app.py"""'], {}), "('app.py')\n", (851, 861), False, 'from cx_Freeze import setup, Executable\n')] |
import torch
import torch.nn as nn
from torch.nn import functional as F
class CustomRNN(nn.Module):
def __init__(self, input_size, output_size, hidden_size, batch_first=True, W_scale=1e-1, f_hidden=None):
super(CustomRNN, self).__init__()
self.input_size = input_size
self.output_size = out... | [
"torch.zeros",
"torch.nn.LSTM",
"torch.stack",
"torch.rand"
] | [((748, 789), 'torch.zeros', 'torch.zeros', (['x.shape[0]', 'self.hidden_size'], {}), '(x.shape[0], self.hidden_size)\n', (759, 789), False, 'import torch\n'), ((1144, 1166), 'torch.stack', 'torch.stack', (['ys'], {'dim': '(1)'}), '(ys, dim=1)\n', (1155, 1166), False, 'import torch\n'), ((1885, 1926), 'torch.zeros', 't... |
import time
from tkinter import *
from model.battle import ClientBattle
class JoinRoomWaitFrame(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.label = Label(self, font=("Helvetica", 18))
self.label.pack(side="top", pady=20)
self.players = Listbox(self)
... | [
"model.battle.ClientBattle",
"time.sleep"
] | [((797, 830), 'model.battle.ClientBattle', 'ClientBattle', (['self.master.handler'], {}), '(self.master.handler)\n', (809, 830), False, 'from model.battle import ClientBattle\n'), ((843, 856), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (853, 856), False, 'import time\n')] |
import helper_test
from configuration import Configuration
from local_services import Compress
from helper import Helper
configuration = Configuration('actioncam', path=helper_test.config_path())
helper = Helper(configuration.config)
helper.state_set_start()
debug = True
compress = Compress(configuration, helper, deb... | [
"helper.Helper",
"local_services.Compress",
"helper_test.config_path"
] | [((207, 235), 'helper.Helper', 'Helper', (['configuration.config'], {}), '(configuration.config)\n', (213, 235), False, 'from helper import Helper\n'), ((285, 323), 'local_services.Compress', 'Compress', (['configuration', 'helper', 'debug'], {}), '(configuration, helper, debug)\n', (293, 323), False, 'from local_servi... |
#
# This file is part of CasADi.
#
# CasADi -- A symbolic framework for dynamic optimization.
# Copyright (C) 2010-2014 <NAME>, <NAME>, <NAME>,
# <NAME>. All rights reserved.
# Copyright (C) 2011-2014 <NAME>
#
# CasADi is free software; you can redistribute it and/or
# ... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.subplot",
"os.path.abspath",
"numpy.meshgrid",
"matplotlib.pyplot.show",
"matplotlib.pyplot.clabel",
"numpy.linspace",
"matplotlib.pyplot.grid"
] | [((4203, 4245), 'numpy.linspace', 'numpy.linspace', (['(-pi / 4)', '(pi / 4)', 'ngrid_phi'], {}), '(-pi / 4, pi / 4, ngrid_phi)\n', (4217, 4245), False, 'import numpy\n'), ((4250, 4293), 'numpy.linspace', 'numpy.linspace', (['(-pi / 4)', '(pi / 4)', 'ngrid_beta'], {}), '(-pi / 4, pi / 4, ngrid_beta)\n', (4264, 4293), F... |
from binance_trading_bot import utilities, visual, indicator
import matplotlib.pyplot as plt
plt.style.use('classic')
from matplotlib.ticker import FormatStrFormatter
import matplotlib.patches as mpatches
import math
def volume_spread_analysis(client, market,
NUM_PRICE_STEP, TIME_FRAME_STEP... | [
"math.isnan",
"binance_trading_bot.indicator.bbands",
"binance_trading_bot.indicator.volume_profile",
"binance_trading_bot.visual.candlestick2_ohlc",
"binance_trading_bot.utilities.get_candles",
"matplotlib.pyplot.style.use",
"matplotlib.ticker.FormatStrFormatter",
"binance_trading_bot.indicator.volat... | [((93, 117), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""classic"""'], {}), "('classic')\n", (106, 117), True, 'import matplotlib.pyplot as plt\n'), ((474, 544), 'binance_trading_bot.utilities.get_candles', 'utilities.get_candles', (['client', 'market', 'TIME_FRAME', 'TIME_FRAME_DURATION'], {}), '(client, mar... |
#!/usr/bin/env python
#------------------------------------------------------------------------------
# JChipClient.py: JChip simulator program for testing JChip interface and CrossMgr.
#
# Copyright (C) <NAME>, 2012.
import os
import time
import xlwt
import socket
import random
import operator
import datetime
#-----... | [
"xlwt.Workbook",
"os.getpid",
"random.normalvariate",
"random.shuffle",
"socket.socket",
"time.sleep",
"socket.gethostname",
"random.seed",
"datetime.timedelta",
"operator.itemgetter",
"datetime.datetime.now"
] | [((742, 763), 'random.seed', 'random.seed', (['(10101010)'], {}), '(10101010)\n', (753, 763), False, 'import random\n'), ((801, 821), 'random.shuffle', 'random.shuffle', (['nums'], {}), '(nums)\n', (815, 821), False, 'import random\n'), ((4773, 4788), 'xlwt.Workbook', 'xlwt.Workbook', ([], {}), '()\n', (4786, 4788), Fa... |
from fastapi import APIRouter
from backend.auth.login import router
auth_routers = APIRouter()
auth_routers.include_router(router, tags=["Auth"])
| [
"fastapi.APIRouter"
] | [((86, 97), 'fastapi.APIRouter', 'APIRouter', ([], {}), '()\n', (95, 97), False, 'from fastapi import APIRouter\n')] |
#
# This file is part of the LibreOffice project.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# This file incorporates work covered by the following license noti... | [
"com.sun.star.beans.PropertyValue"
] | [((1805, 1820), 'com.sun.star.beans.PropertyValue', 'PropertyValue', ([], {}), '()\n', (1818, 1820), False, 'from com.sun.star.beans import PropertyValue\n')] |
from django.contrib import admin
from geartracker.models import *
class ItemAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("make", "model", "size")}
list_display = ('__unicode__', 'type', 'metric_weight', 'acquired')
list_filter = ('archived', 'category', 'type', 'make')
search_fields = ('ma... | [
"django.contrib.admin.site.register"
] | [((371, 407), 'django.contrib.admin.site.register', 'admin.site.register', (['Item', 'ItemAdmin'], {}), '(Item, ItemAdmin)\n', (390, 407), False, 'from django.contrib import admin\n'), ((546, 590), 'django.contrib.admin.site.register', 'admin.site.register', (['Category', 'CategoryAdmin'], {}), '(Category, CategoryAdmi... |
from datetime import date
from typing import Final, Generator, Sequence, cast, Iterable, Mapping, Optional, Union, List
from json import loads
from requests import Response, Session
from tenacity import retry, stop_after_attempt
from pandas import DataFrame
from ._model import (
EpiRangeLike,
AEpiDataCall,
... | [
"requests.Session",
"tenacity.stop_after_attempt",
"json.loads"
] | [((1194, 1203), 'requests.Session', 'Session', ([], {}), '()\n', (1201, 1203), False, 'from requests import Response, Session\n'), ((652, 673), 'tenacity.stop_after_attempt', 'stop_after_attempt', (['(2)'], {}), '(2)\n', (670, 673), False, 'from tenacity import retry, stop_after_attempt\n'), ((5532, 5543), 'json.loads'... |
import json
import os
from logging import getLogger
from pathlib import Path
from scplint.statement import Statement
logger = getLogger()
class SCP:
def __init__(self, scp: dict, filename: str = 'my_scp',
size_max: int = 5120, minimize: bool = False):
logger.debug('initialize scp')
... | [
"scplint.statement.Statement",
"logging.getLogger",
"json.dumps"
] | [((128, 139), 'logging.getLogger', 'getLogger', ([], {}), '()\n', (137, 139), False, 'from logging import getLogger\n'), ((951, 971), 'scplint.statement.Statement', 'Statement', (['statement'], {}), '(statement)\n', (960, 971), False, 'from scplint.statement import Statement\n'), ((3148, 3168), 'json.dumps', 'json.dump... |
import requests
import pickle
from comdirect_api.auth.auth_service import AuthService
from comdirect_api.service.account_service import AccountService
from comdirect_api.service.depot_service import DepotService
from comdirect_api.service.document_service import DocumentService
from comdirect_api.service.report_servic... | [
"comdirect_api.service.depot_service.DepotService",
"pickle.dump",
"comdirect_api.service.account_service.AccountService",
"requests.Session",
"comdirect_api.service.order_service.OrderService",
"comdirect_api.service.report_service.ReportService",
"comdirect_api.service.instrument_service.InstrumentSer... | [((1325, 1367), 'comdirect_api.service.account_service.AccountService', 'AccountService', (['self.session', 'self.api_url'], {}), '(self.session, self.api_url)\n', (1339, 1367), False, 'from comdirect_api.service.account_service import AccountService\n'), ((1397, 1437), 'comdirect_api.service.depot_service.DepotService... |
import tensorflow as tf
import numpy as np
import os
import time
import argparse
import imageio
parser = argparse.ArgumentParser()
parser.add_argument("--training", type=int, default=1, help="training or testing")
parser.add_argument("--testdir", type=str, default=None, help="specify log file dir")
parser.add_argument... | [
"os.mkdir",
"argparse.ArgumentParser",
"tensorflow.reshape",
"tensorflow.get_variable_scope",
"numpy.shape",
"tensorflow.matmul",
"tensorflow.nn.conv2d",
"tensorflow.nn.softmax",
"tensorflow.nn.softmax_cross_entropy_with_logits",
"os.path.exists",
"tensorflow.placeholder",
"tensorflow.cast",
... | [((106, 131), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (129, 131), False, 'import argparse\n'), ((2063, 2129), 'os.system', 'os.system', (["('cp %s %s/%s' % (args.runfile, test_path, args.runfile))"], {}), "('cp %s %s/%s' % (args.runfile, test_path, args.runfile))\n", (2072, 2129), False,... |
import pandas as pd
import io
import pymc3 as pm
import arviz as az
from arviz_json import get_dag, arviz_to_json
#Binomial Logistic Regression Model
#Reference: https://docs.pymc.io/notebooks/putting_workflow.html#Logit-model
#data
golf_data = """distance tries successes
2 1443 1346
3 694 577
4 455 337
5 353 208
6 27... | [
"pymc3.sample",
"io.StringIO",
"pymc3.Model",
"pymc3.Normal",
"arviz.from_pymc3",
"arviz_json.get_dag",
"pymc3.sample_prior_predictive",
"pymc3.Binomial",
"pymc3.Data",
"arviz_json.arviz_to_json",
"pymc3.math.invlogit",
"pymc3.sample_posterior_predictive"
] | [((649, 672), 'pymc3.Model', 'pm.Model', ([], {'coords': 'coords'}), '(coords=coords)\n', (657, 672), True, 'import pymc3 as pm\n'), ((1504, 1591), 'arviz.from_pymc3', 'az.from_pymc3', ([], {'trace': 'trace', 'prior': 'prior', 'posterior_predictive': 'posterior_predictive'}), '(trace=trace, prior=prior, posterior_predi... |
from datagenerationpipeline import dataGenerationPipeline
imageDirectory = "\\\\192.168.1.37\\Multimedia\\datasets\\test\\watches_categories\\1"
fileType=".jpg"
pipeline=dataGenerationPipeline(imageDirectory, fileType)
print("[INFO]: There should be 200 images in directory 1")
pipeline.rotate()
#assert there are 10... | [
"datagenerationpipeline.dataGenerationPipeline"
] | [((172, 220), 'datagenerationpipeline.dataGenerationPipeline', 'dataGenerationPipeline', (['imageDirectory', 'fileType'], {}), '(imageDirectory, fileType)\n', (194, 220), False, 'from datagenerationpipeline import dataGenerationPipeline\n')] |
from django.core.management.base import BaseCommand
from dashboard.models import User, App, APICall, Webhook, WebhookTriggerHistory
class Command(BaseCommand):
help = 'Cleans Dashboard of everything'
def handle(self, *args, **options):
string = input("THIS WILL WIPE THESE MODELS ARE YOU S... | [
"dashboard.models.APICall.objects.all",
"dashboard.models.App.objects.all",
"dashboard.models.User.objects.all",
"dashboard.models.WebhookTriggerHistory.objects.all",
"dashboard.models.Webhook.objects.all"
] | [((425, 443), 'dashboard.models.User.objects.all', 'User.objects.all', ([], {}), '()\n', (441, 443), False, 'from dashboard.models import User, App, APICall, Webhook, WebhookTriggerHistory\n'), ((466, 483), 'dashboard.models.App.objects.all', 'App.objects.all', ([], {}), '()\n', (481, 483), False, 'from dashboard.model... |
# Copyright 2019 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... | [
"importlib.util.find_spec",
"os.path.dirname",
"os.path.join",
"imp.find_module"
] | [((1862, 1904), 'os.path.join', 'os.path.join', (['base_path', '*name_split[1:-1]'], {}), '(base_path, *name_split[1:-1])\n', (1874, 1904), False, 'import os\n'), ((1824, 1852), 'os.path.dirname', 'os.path.dirname', (['spec.origin'], {}), '(spec.origin)\n', (1839, 1852), False, 'import os\n'), ((943, 975), 'os.path.dir... |
'''History for wx GUIs'''
# Author: <NAME> <<EMAIL>>
from logging import getLogger
import os
from typing import Optional, Tuple
import wx
from .help import show_help_txt
from .frame import EelbrainFrame
from .utils import Icon
from . import ID
TEST_MODE = False
class CallBackManager:
def __init__(self, keys)... | [
"os.path.basename",
"wx.FileDialog",
"wx.MessageBox",
"wx.Config",
"os.path.split",
"logging.getLogger"
] | [((1993, 2012), 'logging.getLogger', 'getLogger', (['__name__'], {}), '(__name__)\n', (2002, 2012), False, 'from logging import getLogger\n'), ((3497, 3516), 'logging.getLogger', 'getLogger', (['__name__'], {}), '(__name__)\n', (3506, 3516), False, 'from logging import getLogger\n'), ((4194, 4213), 'logging.getLogger',... |
import os
import re
import json
from typing import Sequence, GenericMeta
from datetime import datetime, date
import dateutil.parser
import inflection
from stevesie import resources
from stevesie.utils import api
DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%S.%fZ'
class RemoteResource(object):
_is_hydrated = False
... | [
"inflection.underscore",
"json.load",
"stevesie.utils.api.get",
"stevesie.utils.api.delete",
"re.search",
"os.path.expanduser",
"inflection.camelize"
] | [((2341, 2367), 'stevesie.utils.api.get', 'api.get', (['self.resource_url'], {}), '(self.resource_url)\n', (2348, 2367), False, 'from stevesie.utils import api\n'), ((2481, 2510), 'stevesie.utils.api.delete', 'api.delete', (['self.resource_url'], {}), '(self.resource_url)\n', (2491, 2510), False, 'from stevesie.utils i... |
import os
import glob
import shutil
from PIL import Image
# for file_path in glob.glob('./data/evaluation/card_evaluation/*.png'):
# file_name = os.path.basename(file_path)
# if file_name.find(',') >= 0 or file_name.find('@') >=0 or file_name.find('*') > 0 or file_name.find(':') > 0 \
# or file_nam... | [
"os.path.basename",
"shutil.move",
"glob.glob"
] | [((1081, 1105), 'glob.glob', 'glob.glob', (["(src + '*.png')"], {}), "(src + '*.png')\n", (1090, 1105), False, 'import glob\n'), ((1123, 1150), 'os.path.basename', 'os.path.basename', (['file_path'], {}), '(file_path)\n', (1139, 1150), False, 'import os\n'), ((1268, 1308), 'shutil.move', 'shutil.move', (['file_path', '... |
import time
import pandas as pd
from dash_website.utils.aws_loader import load_excel, load_parquet, load_feather
if __name__ == "__main__":
time_excel = 0
for idx_load_excel in range(10):
start_excel = time.time()
load_excel("xwas/univariate_results/linear_correlations.xlsx")
time_exce... | [
"dash_website.utils.aws_loader.load_excel",
"dash_website.utils.aws_loader.load_parquet",
"dash_website.utils.aws_loader.load_feather",
"time.time"
] | [((220, 231), 'time.time', 'time.time', ([], {}), '()\n', (229, 231), False, 'import time\n'), ((240, 302), 'dash_website.utils.aws_loader.load_excel', 'load_excel', (['"""xwas/univariate_results/linear_correlations.xlsx"""'], {}), "('xwas/univariate_results/linear_correlations.xlsx')\n", (250, 302), False, 'from dash_... |
from django.contrib.auth import get_user_model
from django.contrib.postgres.fields import JSONField
from django.db import models
from organization.models import BaseTemplate
from misc.models import Content
class ToDo(BaseTemplate):
content = models.ManyToManyField(Content)
due_on_day = models.IntegerField(de... | [
"django.db.models.CharField",
"django.db.models.IntegerField",
"django.db.models.ManyToManyField",
"django.db.models.BooleanField"
] | [((249, 280), 'django.db.models.ManyToManyField', 'models.ManyToManyField', (['Content'], {}), '(Content)\n', (271, 280), False, 'from django.db import models\n'), ((298, 328), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'default': '(0)'}), '(default=0)\n', (317, 328), False, 'from django.db import mo... |
import functools
from flask import Blueprint
from flask import flash
from flask import g
from flask import redirect
from flask import render_template
from flask import request
from flask import session
from flask import url_for
from werkzeug.security import check_password_hash
from werkzeug.security import generate_pa... | [
"flask.url_for",
"flask.Blueprint",
"functools.wraps"
] | [((371, 418), 'flask.Blueprint', 'Blueprint', (['"""auth"""', '__name__'], {'url_prefix': '"""/auth"""'}), "('auth', __name__, url_prefix='/auth')\n", (380, 418), False, 'from flask import Blueprint\n'), ((528, 549), 'functools.wraps', 'functools.wraps', (['view'], {}), '(view)\n', (543, 549), False, 'import functools\... |
from django.urls import re_path
from . import views
app_name = 'weather'
urlpatterns = [
re_path(r'^$', views.weather, name='root'),
re_path(r'^current/$', views.current, name='current'),
re_path(r'^unitchange/$', views.unit_change, name='unit-change'),
re_path(r'^generate/$', views.generate,... | [
"django.urls.re_path"
] | [((101, 142), 'django.urls.re_path', 're_path', (['"""^$"""', 'views.weather'], {'name': '"""root"""'}), "('^$', views.weather, name='root')\n", (108, 142), False, 'from django.urls import re_path\n'), ((150, 202), 'django.urls.re_path', 're_path', (['"""^current/$"""', 'views.current'], {'name': '"""current"""'}), "('... |
#!/usr/bin/python
"""Console script for cmus_scrobbler."""
import cmus_scrobbler
import argparse
import sys
def main():
"""Console script for cmus_scrobbler."""
parser = argparse.ArgumentParser()
parser.add_argument('status', nargs='*')
parser.add_argument('-c', '--config', nargs=2, help="Called with t... | [
"cmus_scrobbler.main",
"argparse.ArgumentParser"
] | [((179, 204), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (202, 204), False, 'import argparse\n'), ((444, 469), 'cmus_scrobbler.main', 'cmus_scrobbler.main', (['args'], {}), '(args)\n', (463, 469), False, 'import cmus_scrobbler\n')] |
from collections import Counter
# sort
class Solution_1:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
nums1.sort()
nums2.sort()
res = []
len1 = len(nums1)
len2 = len(nums2)
idx1 = 0
idx2 = 0
whi... | [
"collections.Counter"
] | [((1428, 1442), 'collections.Counter', 'Counter', (['nums1'], {}), '(nums1)\n', (1435, 1442), False, 'from collections import Counter\n'), ((1445, 1459), 'collections.Counter', 'Counter', (['nums2'], {}), '(nums2)\n', (1452, 1459), False, 'from collections import Counter\n')] |
import json
from unittest import TestCase
from unittest.mock import patch
from zoltpy.covid19 import validate_config_dict, validate_quantile_csv_file
class CdcIOTestCase(TestCase):
"""
"""
def test_validate_quantile_csv_file_calls_validate_config_dict(self):
validation_config = {'target_groups'... | [
"unittest.mock.patch",
"json.load",
"zoltpy.covid19.validate_config_dict",
"zoltpy.covid19.validate_quantile_csv_file"
] | [((883, 962), 'zoltpy.covid19.validate_quantile_csv_file', 'validate_quantile_csv_file', (['"""tests/quantile-predictions.csv"""', 'validation_config'], {}), "('tests/quantile-predictions.csv', validation_config)\n", (909, 962), False, 'from zoltpy.covid19 import validate_config_dict, validate_quantile_csv_file\n'), ((... |
import pytest
from gridthings import Cell
# Cells represent individual data points in a grid
# They implement a variety of mathematical dunder methods
# so that they can be compared, sorted, and manipulated
def test_cell_when_equal():
c1 = Cell(y=0, x=0, value="foo")
c2 = Cell(y=0, x=1, value="foo")
# u... | [
"pytest.raises",
"gridthings.Cell"
] | [((248, 275), 'gridthings.Cell', 'Cell', ([], {'y': '(0)', 'x': '(0)', 'value': '"""foo"""'}), "(y=0, x=0, value='foo')\n", (252, 275), False, 'from gridthings import Cell\n'), ((285, 312), 'gridthings.Cell', 'Cell', ([], {'y': '(0)', 'x': '(1)', 'value': '"""foo"""'}), "(y=0, x=1, value='foo')\n", (289, 312), False, '... |
import os
import logging
#[PATHS]
# Paths will be based on the location of this file which is ./conf by default. Adjust accordingly!
FILEPATH = os.path.abspath(os.path.dirname(__file__))
ENV_PATH = FILEPATH + "/env"
#[LOGGING]
LOG_PATH = FILEPATH + "/../logs/"
LOG_FILE = "twitterbot.log"
LOG_LEVEL = logging.DEBUG
... | [
"os.path.dirname"
] | [((162, 187), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (177, 187), False, 'import os\n')] |
#=======================================================================================================================
# an example file on how to build special test/training cubes using nh3_testcube.py
#================================================================================================================... | [
"numpy.abs",
"nh3_testcubes.generate_gradients",
"nh3_testcubes.generate_parameters",
"numpy.zeros",
"numpy.ones",
"numpy.array",
"numpy.linspace",
"numpy.column_stack",
"nh3_testcubes.make_and_write"
] | [((1611, 1661), 'nh3_testcubes.generate_parameters', 'testcubes.generate_parameters', (['nCubes', 'random_seed'], {}), '(nCubes, random_seed)\n', (1640, 1661), True, 'import nh3_testcubes as testcubes\n'), ((1681, 1730), 'nh3_testcubes.generate_gradients', 'testcubes.generate_gradients', (['nCubes', 'random_seed'], {})... |
# (C) Datadog, Inc. 2022-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
import logging
import os
import mock
import pytest
from requests import HTTPError
from datadog_checks.arangodb import ArangodbCheck
from datadog_checks.dev.http import MockResponse
from datadog_checks.de... | [
"datadog_checks.arangodb.ArangodbCheck",
"os.path.dirname",
"mock.patch",
"pytest.param",
"pytest.raises",
"datadog_checks.dev.utils.get_metadata_metrics",
"mock.MagicMock"
] | [((504, 562), 'datadog_checks.arangodb.ArangodbCheck', 'ArangodbCheck', (['"""arangodb"""', '{}', '[instance_invalid_endpoint]'], {}), "('arangodb', {}, [instance_invalid_endpoint])\n", (517, 562), False, 'from datadog_checks.arangodb import ArangodbCheck\n'), ((1706, 1747), 'datadog_checks.arangodb.ArangodbCheck', 'Ar... |
from programmingalpha.DataSet.DBLoader import MongoStackExchange
import programmingalpha
from programmingalpha.Utility.TextPreprocessing import PreprocessPostContent
import json
import logging
import argparse
import tqdm
import multiprocessing
logging.basicConfig(format = '%(asctime)s - %(levelname)s - %(name... | [
"tqdm.tqdm",
"multiprocessing.current_process",
"argparse.ArgumentParser",
"logging.basicConfig",
"json.loads",
"programmingalpha.DataSet.DBLoader.MongoStackExchange",
"json.dumps",
"programmingalpha.Utility.TextPreprocessing.PreprocessPostContent",
"multiprocessing.Pool",
"logging.getLogger"
] | [((254, 397), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s - %(levelname)s - %(name)s - %(message)s"""', 'datefmt': '"""%m/%d/%Y %H:%M:%S"""', 'level': 'logging.INFO'}), "(format=\n '%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt=\n '%m/%d/%Y %H:%M:%S', level=l... |
from Code.UI.splash_layout import Ui_MainWindow
from Code.UI.label import LabelUI
#from ui.export_ui import ExportUI
#from ui.questionnaire_ui import QuestionnaireUI
from PyQt5 import QtCore
import sys, traceback
if QtCore.QT_VERSION >= 0x50501:
def excepthook(type_, value, traceback_):
traceback.print_exc... | [
"PyQt5.QtCore.qFatal",
"Code.UI.label.LabelUI",
"traceback.print_exception"
] | [((301, 352), 'traceback.print_exception', 'traceback.print_exception', (['type_', 'value', 'traceback_'], {}), '(type_, value, traceback_)\n', (326, 352), False, 'import sys, traceback\n'), ((361, 378), 'PyQt5.QtCore.qFatal', 'QtCore.qFatal', (['""""""'], {}), "('')\n", (374, 378), False, 'from PyQt5 import QtCore\n')... |
#------------------------------------------------------------------------------
# query_one.py (Section 3.2)
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
# Copyright 2017, 2018, Oracle and/or its affiliat... | [
"cx_Oracle.connect"
] | [((506, 568), 'cx_Oracle.connect', 'cx_Oracle.connect', (['db_config.user', 'db_config.pw', 'db_config.dsn'], {}), '(db_config.user, db_config.pw, db_config.dsn)\n', (523, 568), False, 'import cx_Oracle\n')] |
"""
Copyright 2021 Objectiv B.V.
"""
from typing import List
import pytest
from bach import get_series_type_from_dtype
from bach.expression import Expression
from bach.partitioning import GroupBy
from tests.unit.bach.util import get_fake_df, FakeEngine
def test_equals(dialect):
def get_df(index_names: List[str]... | [
"tests.unit.bach.util.get_fake_df",
"bach.get_series_type_from_dtype",
"tests.unit.bach.util.FakeEngine",
"bach.expression.Expression.construct",
"bach.partitioning.GroupBy"
] | [((1270, 1335), 'tests.unit.bach.util.FakeEngine', 'FakeEngine', ([], {'dialect': 'engine.dialect', 'url': '"""sql://some_other_string"""'}), "(dialect=engine.dialect, url='sql://some_other_string')\n", (1280, 1335), False, 'from tests.unit.bach.util import get_fake_df, FakeEngine\n'), ((1352, 1387), 'bach.get_series_t... |
"""
Copyright (c) 2018 <NAME> <<EMAIL>>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribut... | [
"mpikat.core.ip_manager.ip_range_from_stream",
"json.loads",
"logging.getLogger"
] | [((1158, 1207), 'logging.getLogger', 'logging.getLogger', (['"""mpikat.apsuse_config_manager"""'], {}), "('mpikat.apsuse_config_manager')\n", (1175, 1207), False, 'import logging\n'), ((4286, 4362), 'mpikat.core.ip_manager.ip_range_from_stream', 'ip_range_from_stream', (["self._fbfuse_config['incoherent-beam-multicast-... |
#!/Users/toma/python278i/bin/python
# -*- coding: utf-8 -*-
#
import MainWindow
import os
import platform
import sys
from PyQt4.QtGui import (QApplication, QIcon)
__version__ = "1.0.0"
def main():
app = QApplication(sys.argv)
app.setOrganizationName("tomacorp")
app.setOrganizationDomain("tomacorp.com") ... | [
"MainWindow.Window",
"PyQt4.QtGui.QIcon",
"PyQt4.QtGui.QApplication"
] | [((214, 236), 'PyQt4.QtGui.QApplication', 'QApplication', (['sys.argv'], {}), '(sys.argv)\n', (226, 236), False, 'from PyQt4.QtGui import QApplication, QIcon\n'), ((368, 387), 'MainWindow.Window', 'MainWindow.Window', ([], {}), '()\n', (385, 387), False, 'import MainWindow\n'), ((341, 360), 'PyQt4.QtGui.QIcon', 'QIcon'... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Copyright (C) 2021, Ontario Institute for Cancer Research
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the L... | [
"os.mkdir",
"copy.deepcopy",
"hashlib.md5",
"os.path.abspath",
"argparse.ArgumentParser",
"os.stat",
"os.path.basename",
"os.getcwd",
"json.load",
"uuid.uuid4",
"re.match",
"datetime.date.today",
"json.dumps",
"tarfile.open",
"sys.exit"
] | [((2255, 2268), 'hashlib.md5', 'hashlib.md5', ([], {}), '()\n', (2266, 2268), False, 'import hashlib\n'), ((3951, 3972), 'os.path.basename', 'os.path.basename', (['tar'], {}), '(tar)\n', (3967, 3972), False, 'import os\n'), ((4858, 4952), 'sys.exit', 'sys.exit', (['(\'Error: unable to match ubam qc metric tar "%s" to r... |
# -*- coding: utf-8 -*-
"""Rebinning the PSF
This script rebins the given PSF and stores the rebinned PSFs in the specified directory.
"""
import os
import argparse
import rebinning_utils
def parse_args():
"""Parse command-line arguments
"""
parser = argparse.ArgumentParser()
parser.add_argument('ps... | [
"os.makedirs",
"argparse.ArgumentParser",
"rebinning_utils.load_psf_map",
"os.path.exists",
"rebinning_utils.rebin_psf"
] | [((267, 292), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (290, 292), False, 'import argparse\n'), ((874, 922), 'rebinning_utils.load_psf_map', 'rebinning_utils.load_psf_map', (['args.psf_file_path'], {}), '(args.psf_file_path)\n', (902, 922), False, 'import rebinning_utils\n'), ((1016, 1105... |
# -*- coding: utf-8 -*-
#####----------------------------------------------------------------#####
##### #####
##### 使用教程/readme: #####
##### https://cloud.tencent.com/document/product/583/47076 ###... | [
"os.mkdir",
"os.remove",
"os.path.isfile",
"patool.extract_archive",
"os.path.join",
"zipfile.is_zipfile",
"os.path.abspath",
"qcloud_cos_v5.CosConfig",
"os.path.exists",
"os.path.normpath",
"sys.setdefaultencoding",
"os.path.basename",
"os.path.expandvars",
"os.rmdir",
"os.listdir",
"... | [((683, 713), 'sys.setdefaultencoding', 'sys.setdefaultencoding', (['"""utf8"""'], {}), "('utf8')\n", (705, 713), False, 'import sys\n'), ((770, 828), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO', 'stream': 'sys.stdout'}), '(level=logging.INFO, stream=sys.stdout)\n', (789, 828), False, 'i... |
import sys
import getopt
from pyiron.base.job.wrapper import job_wrapper_function
def command_line(argv):
"""
Parse the command line arguments.
Args:
argv: Command line arguments
"""
debug = False
project_path = None
job_id = None
try:
opts, args = getopt.getopt(argv,... | [
"sys.exit",
"getopt.getopt",
"pyiron.base.job.wrapper.job_wrapper_function"
] | [((301, 377), 'getopt.getopt', 'getopt.getopt', (['argv', '"""dj:p:h"""', "['debug', 'project_path=', 'job_id=', 'help']"], {}), "(argv, 'dj:p:h', ['debug', 'project_path=', 'job_id=', 'help'])\n", (314, 377), False, 'import getopt\n'), ((907, 992), 'pyiron.base.job.wrapper.job_wrapper_function', 'job_wrapper_function'... |
"""
This script extract news information from the local web
"""
import glob
import os
import os.path
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverW... | [
"selenium.webdriver.support.expected_conditions.element_to_be_clickable",
"selenium.webdriver.Firefox",
"os.path.isfile",
"glob.glob",
"bs4.BeautifulSoup",
"selenium.webdriver.support.ui.WebDriverWait"
] | [((819, 838), 'selenium.webdriver.Firefox', 'webdriver.Firefox', ([], {}), '()\n', (836, 838), False, 'from selenium import webdriver\n'), ((959, 978), 'selenium.webdriver.Firefox', 'webdriver.Firefox', ([], {}), '()\n', (976, 978), False, 'from selenium import webdriver\n'), ((994, 1019), 'selenium.webdriver.support.u... |
from flask_sqlalchemy import SQLAlchemy
from api import app, db
from data.models import Authentication, UserLogin
from data.parser import authlogs
from predictions import update_predictions
# create tables
with app.app_context():
db.create_all()
with app.app_context():
entry = UserLogin(
username="adm... | [
"api.app.app_context",
"api.db.create_all",
"api.db.session.add",
"data.models.Authentication",
"api.db.session.commit",
"data.models.UserLogin"
] | [((212, 229), 'api.app.app_context', 'app.app_context', ([], {}), '()\n', (227, 229), False, 'from api import app, db\n'), ((235, 250), 'api.db.create_all', 'db.create_all', ([], {}), '()\n', (248, 250), False, 'from api import app, db\n'), ((257, 274), 'api.app.app_context', 'app.app_context', ([], {}), '()\n', (272, ... |
import pandas as pd
import json
import datetime
import subprocess
import localModule
#----
def atting_program(row):
ffmpeg_command_line = 'ffmpeg \
-loglevel error \
-fflags +discardcorrupt \
-i {0} \
-acodec copy \
-movflags faststart \
-vn \
-bsf:a aac_adtstoasc \
-t {1} \
-m... | [
"pandas.read_csv",
"subprocess.check_output",
"pandas.to_timedelta",
"pandas.to_datetime",
"datetime.timedelta"
] | [((1151, 1186), 'pandas.read_csv', 'pd.read_csv', (['localModule.TABLE_FILE'], {}), '(localModule.TABLE_FILE)\n', (1162, 1186), True, 'import pandas as pd\n'), ((1209, 1244), 'pandas.to_datetime', 'pd.to_datetime', (["table['start_time']"], {}), "(table['start_time'])\n", (1223, 1244), True, 'import pandas as pd\n'), (... |
import sys
sys.path.append('..')
import unittest
from graphs.Graph import Graph
class TestGraph(unittest.TestCase):
def setUp(self):
self.G = Graph(5)
self.G.add_edge(1, 2)
self.G.add_edge(1, 3)
self.G.add_edge(1, 4)
self.G.add_edge(2, 4)
self.G.add_edge(... | [
"sys.path.append",
"unittest.main",
"graphs.Graph.Graph"
] | [((11, 32), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (26, 32), False, 'import sys\n'), ((742, 757), 'unittest.main', 'unittest.main', ([], {}), '()\n', (755, 757), False, 'import unittest\n'), ((166, 174), 'graphs.Graph.Graph', 'Graph', (['(5)'], {}), '(5)\n', (171, 174), False, 'from graph... |
from threading import Thread
from typing import Union, Dict, Optional, Tuple
from datetime import datetime, timedelta, timezone
from enum import Enum, auto
from kafka import KafkaConsumer, TopicPartition
from queue import Queue, Empty, Full
from wherefore.DataSource import DataSource
from wherefore.Message import Messa... | [
"threading.Thread",
"wherefore.Message.Message",
"copy.copy",
"wherefore.DataSource.DataSource",
"kafka.TopicPartition",
"datetime.timedelta",
"enum.auto",
"datetime.datetime.now",
"queue.Queue",
"kafka.KafkaConsumer"
] | [((401, 427), 'datetime.timedelta', 'timedelta', ([], {'milliseconds': '(50)'}), '(milliseconds=50)\n', (410, 427), False, 'from datetime import datetime, timedelta, timezone\n'), ((471, 477), 'enum.auto', 'auto', ([], {}), '()\n', (475, 477), False, 'from enum import Enum, auto\n'), ((494, 500), 'enum.auto', 'auto', (... |
#!/usr/bin/env python
import os
import sys
sys.path.insert(0, os.pardir)
sys.path.insert(0, os.path.join(os.pardir, 'openmoc'))
from testing_harness import MultiSimTestHarness
import openmoc
try:
import openmc.openmoc_compatible
import openmc.mgxs
except:
print("OpenMC could not be imported, it's require... | [
"openmoc.CPUSolver",
"os.path.join",
"openmoc.TrackGenerator",
"sys.path.insert",
"openmoc.materialize.load_openmc_mgxs_lib"
] | [((45, 74), 'sys.path.insert', 'sys.path.insert', (['(0)', 'os.pardir'], {}), '(0, os.pardir)\n', (60, 74), False, 'import sys\n'), ((94, 128), 'os.path.join', 'os.path.join', (['os.pardir', '"""openmoc"""'], {}), "(os.pardir, 'openmoc')\n", (106, 128), False, 'import os\n'), ((1929, 1997), 'openmoc.materialize.load_op... |
"""Sociological poll example."""
import sys
sys.path.append('..')
from trials import Trials
if __name__ == '__main__':
test = Trials(['Poroshenko', 'Tymoshenko'])
test.update({
'Poroshenko': (48, 52),
'Tymoshenko': (12, 88)
})
estimates = test.evaluate('posterior CI')
dominance... | [
"sys.path.append",
"trials.Trials"
] | [((45, 66), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (60, 66), False, 'import sys\n'), ((134, 170), 'trials.Trials', 'Trials', (["['Poroshenko', 'Tymoshenko']"], {}), "(['Poroshenko', 'Tymoshenko'])\n", (140, 170), False, 'from trials import Trials\n')] |
import os
import sys
import PyPDF2
from io import BytesIO
from mailer import mailer
def split(pB):
print(pB)
pTS = PyPDF2.PdfFileReader(pB)
if pTS.flattenedPages is None:
pTS._flatten()
for n, pO in enumerate(pTS.flattenedPages):
sP = PyPDF2.PdfFileWriter()
sP.addPage(pO)
b = BytesIO()
... | [
"PyPDF2.PdfFileReader",
"io.BytesIO",
"PyPDF2.PdfFileWriter"
] | [((121, 145), 'PyPDF2.PdfFileReader', 'PyPDF2.PdfFileReader', (['pB'], {}), '(pB)\n', (141, 145), False, 'import PyPDF2\n'), ((257, 279), 'PyPDF2.PdfFileWriter', 'PyPDF2.PdfFileWriter', ([], {}), '()\n', (277, 279), False, 'import PyPDF2\n'), ((307, 316), 'io.BytesIO', 'BytesIO', ([], {}), '()\n', (314, 316), False, 'f... |
from matplotlib import pyplot as plt
from niaarm import Dataset, RuleList, get_rules
from niaarm.visualize import hill_slopes
dataset = Dataset('datasets/Abalone.csv')
metrics = ('support', 'confidence')
rules, _ = get_rules(dataset, 'DifferentialEvolution', metrics, max_evals=1000, seed=1234)
some_rule = rules[150]
p... | [
"niaarm.get_rules",
"niaarm.Dataset",
"niaarm.visualize.hill_slopes",
"matplotlib.pyplot.show"
] | [((137, 168), 'niaarm.Dataset', 'Dataset', (['"""datasets/Abalone.csv"""'], {}), "('datasets/Abalone.csv')\n", (144, 168), False, 'from niaarm import Dataset, RuleList, get_rules\n'), ((216, 295), 'niaarm.get_rules', 'get_rules', (['dataset', '"""DifferentialEvolution"""', 'metrics'], {'max_evals': '(1000)', 'seed': '(... |
# coding: utf-8
"""jinja2_fsloader - A Jinja2 template loader using PyFilesystem2.
"""
import sys
import fs
import fs.path
import fs.errors
import jinja2
import pkg_resources
__author__ = "<NAME> <<EMAIL>>"
__license__ = "MIT"
__version__ = pkg_resources.resource_string(__name__, "_version.txt").decode('utf-8').stri... | [
"fs.open_fs",
"jinja2.TemplateNotFound",
"pkg_resources.resource_string",
"fs.path.relpath"
] | [((1424, 1447), 'fs.open_fs', 'fs.open_fs', (['template_fs'], {}), '(template_fs)\n', (1434, 1447), False, 'import fs\n'), ((1713, 1746), 'jinja2.TemplateNotFound', 'jinja2.TemplateNotFound', (['template'], {}), '(template)\n', (1736, 1746), False, 'import jinja2\n'), ((244, 299), 'pkg_resources.resource_string', 'pkg_... |
import sys
from datetime import datetime
from . import main
from flask import render_template, request, redirect, url_for, flash
from ..models import db, Artist, Venue, Show
from .forms import ShowForm, VenueForm, ArtistForm, DeleteArtist, DeleteVenue
@main.route('/')
def index():
return render_template('pages/ho... | [
"flask.flash",
"flask.request.form.get",
"flask.url_for",
"flask.render_template",
"sys.exc_info",
"datetime.datetime.now"
] | [((295, 329), 'flask.render_template', 'render_template', (['"""pages/home.html"""'], {}), "('pages/home.html')\n", (310, 329), False, 'from flask import render_template, request, redirect, url_for, flash\n'), ((395, 409), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (407, 409), False, 'from datetime impo... |
import os
from flask import render_template, flash, redirect, url_for, request
import requests
from app.source import bp
from app.models import article as at
@bp.route('/source')
def search_source():
"""Show this view when a source is pressed and show articles."""
API_KEY = os.environ.get('API_KEY')
news_... | [
"app.models.article.Article",
"flask.request.args.get",
"app.source.bp.route",
"os.environ.get",
"requests.get",
"flask.render_template"
] | [((161, 180), 'app.source.bp.route', 'bp.route', (['"""/source"""'], {}), "('/source')\n", (169, 180), False, 'from app.source import bp\n'), ((285, 310), 'os.environ.get', 'os.environ.get', (['"""API_KEY"""'], {}), "('API_KEY')\n", (299, 310), False, 'import os\n'), ((329, 350), 'flask.request.args.get', 'request.args... |
import pytest
from .Week1Bonus_PalindromePermutation import Solution
s = Solution()
@pytest.mark.parametrize("test_input", ["code", "abc"])
def test_cannot_permute(test_input):
assert not s.canPermutePalindrome(test_input)
@pytest.mark.parametrize("test_input", ["aab", "carerac", "a", "aa"])
def test_can_permu... | [
"pytest.mark.parametrize"
] | [((88, 142), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""test_input"""', "['code', 'abc']"], {}), "('test_input', ['code', 'abc'])\n", (111, 142), False, 'import pytest\n'), ((233, 301), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""test_input"""', "['aab', 'carerac', 'a', 'aa']"], {}), "(... |
#!/usr/bin/env python
"""Calculate HOG features for an image"""
import os
import matplotlib.pyplot as plt
from hog_features import image2pixelarray
from skimage import exposure
from skimage.feature import hog
def main(filename):
"""
Orchestrate the HOG feature calculation
Parameters
----------
... | [
"os.path.abspath",
"matplotlib.pyplot.show",
"argparse.ArgumentParser",
"skimage.exposure.rescale_intensity",
"skimage.feature.hog",
"os.path.exists",
"hog_features.image2pixelarray",
"matplotlib.pyplot.subplots"
] | [((356, 382), 'hog_features.image2pixelarray', 'image2pixelarray', (['filename'], {}), '(filename)\n', (372, 382), False, 'from hog_features import image2pixelarray\n'), ((404, 500), 'skimage.feature.hog', 'hog', (['image'], {'orientations': '(8)', 'pixels_per_cell': '(16, 16)', 'cells_per_block': '(1, 1)', 'visualise'... |
import pandas as pd
import tweepy
import json
import configparser
import re, string, random
from nltk.stem.wordnet import WordNetLemmatizer
from nltk.corpus import twitter_samples, stopwords
from nltk.tag import pos_tag
from nltk import TweetTokenizer
from nltk import FreqDist, classify, NaiveBayesClassifier
def tra... | [
"pandas.DataFrame",
"tweepy.API",
"nltk.stem.wordnet.WordNetLemmatizer",
"nltk.corpus.twitter_samples.tokenized",
"random.shuffle",
"pandas.read_csv",
"nltk.classify.accuracy",
"nltk.NaiveBayesClassifier.train",
"nltk.tag.pos_tag",
"tweepy.Cursor",
"nltk.corpus.stopwords.words",
"tweepy.OAuthH... | [((645, 694), 'nltk.corpus.twitter_samples.tokenized', 'twitter_samples.tokenized', (['"""positive_tweets.json"""'], {}), "('positive_tweets.json')\n", (670, 694), False, 'from nltk.corpus import twitter_samples, stopwords\n'), ((723, 772), 'nltk.corpus.twitter_samples.tokenized', 'twitter_samples.tokenized', (['"""neg... |
from django import forms
from mimetypes import guess_type
import base64
import os
from .models import Post
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = [
"content",
"image",
"privacy",
"content_type",
"accessible_... | [
"django.forms.HiddenInput"
] | [((539, 558), 'django.forms.HiddenInput', 'forms.HiddenInput', ([], {}), '()\n', (556, 558), False, 'from django import forms\n'), ((599, 618), 'django.forms.HiddenInput', 'forms.HiddenInput', ([], {}), '()\n', (616, 618), False, 'from django import forms\n'), ((1964, 1983), 'django.forms.HiddenInput', 'forms.HiddenInp... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# File: list.py
# by <NAME>
# <EMAIL>
#
import os
from datetime import datetime as dt
def do_list(ark, opts):
total_size = sum(x.original_filesize for x in ark.metadatas)
len_size = max(len(str(total_size)), len('Length'))
if opts['-v']:
print("File:... | [
"datetime.datetime.fromtimestamp"
] | [((826, 858), 'datetime.datetime.fromtimestamp', 'dt.fromtimestamp', (['meta.timestamp'], {}), '(meta.timestamp)\n', (842, 858), True, 'from datetime import datetime as dt\n')] |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-12-11 14:21
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Grundgeruest', '0004_auto_20171211_1418'),
]
operations = [
migrations.Alte... | [
"django.db.models.SmallIntegerField"
] | [((425, 498), 'django.db.models.SmallIntegerField', 'models.SmallIntegerField', ([], {'default': '(0)', 'null': '(True)', 'verbose_name': '"""auslaufend"""'}), "(default=0, null=True, verbose_name='auslaufend')\n", (449, 498), False, 'from django.db import migrations, models\n')] |
# -*- coding: utf-8 -*-
import urllib2
import urllib
from bs4 import BeautifulSoup
import json
import cookielib
import sqlite3
import time
import os
import sys
import socket
socket.setdefaulttimeout(30)
reload(sys)
sys.setdefaultencoding('utf-8')
def get_search_page_url(keyWord):
res = 1
pageURL = ''
t... | [
"json.loads",
"cookielib.CookieJar",
"urllib2.Request",
"os.path.exists",
"urllib2.quote",
"json.dumps",
"time.sleep",
"socket.setdefaulttimeout",
"sqlite3.connect",
"sys.setdefaultencoding",
"urllib.urlencode",
"bs4.BeautifulSoup",
"sys.exit",
"urllib2.HTTPCookieProcessor",
"urllib2.url... | [((176, 204), 'socket.setdefaulttimeout', 'socket.setdefaulttimeout', (['(30)'], {}), '(30)\n', (200, 204), False, 'import socket\n'), ((218, 249), 'sys.setdefaultencoding', 'sys.setdefaultencoding', (['"""utf-8"""'], {}), "('utf-8')\n", (240, 249), False, 'import sys\n'), ((2636, 2673), 'sqlite3.connect', 'sqlite3.con... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.http import HttpResponse
from django.test import RequestFactory
from nose.tools import eq_
from gnu_terry_pratchett.decorators import clacks_overhead
@clacks_overhead
def view(request):
return HttpResponse("Death can't have him")
def test_view_decorat... | [
"nose.tools.eq_",
"django.http.HttpResponse",
"django.test.RequestFactory"
] | [((260, 296), 'django.http.HttpResponse', 'HttpResponse', (['"""Death can\'t have him"""'], {}), '("Death can\'t have him")\n', (272, 296), False, 'from django.http import HttpResponse\n'), ((399, 456), 'nose.tools.eq_', 'eq_', (["response['x-clacks-overhead']", '"""GNU Terry Pratchett"""'], {}), "(response['x-clacks-o... |
# Copyright 2021 Sony Group Corporation.
#
# 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 ... | [
"nnabla.logger.log",
"tqdm.tqdm",
"csv.reader",
"csv.writer",
"argparse.ArgumentParser",
"sklearn.manifold.TSNE",
"nnabla.utils.data_iterator.data_iterator_csv_dataset",
"numpy.array"
] | [((1028, 1065), 'nnabla.logger.log', 'logger.log', (['(99)', '"""Loading variable..."""'], {}), "(99, 'Loading variable...')\n", (1038, 1065), False, 'from nnabla import logger\n'), ((1583, 1620), 'nnabla.logger.log', 'logger.log', (['(99)', '"""Processing t-SNE..."""'], {}), "(99, 'Processing t-SNE...')\n", (1593, 162... |
from django.contrib import admin
from .models import Category , Incomes , Expense
# Register your models here.
admin.site.register(Category)
admin.site.register(Incomes)
admin.site.register(Expense)
| [
"django.contrib.admin.site.register"
] | [((113, 142), 'django.contrib.admin.site.register', 'admin.site.register', (['Category'], {}), '(Category)\n', (132, 142), False, 'from django.contrib import admin\n'), ((143, 171), 'django.contrib.admin.site.register', 'admin.site.register', (['Incomes'], {}), '(Incomes)\n', (162, 171), False, 'from django.contrib imp... |
from torch.utils.data import DataLoader, Subset
from pathlib import Path
import torch
import torch.nn as nn
import itertools as its
import pandas as pd
import numpy as np
import json
from rdkit import Chem, DataStructs
from rdkit.Chem import AllChem
import matplotlib.pyplot as plt
from NeuralGraph.dataset import MolDa... | [
"numpy.random.seed",
"pandas.read_csv",
"torch.nn.init.uniform_",
"pathlib.Path",
"numpy.mean",
"numpy.std",
"torch.load",
"itertools.product",
"numpy.random.choice",
"json.dump",
"rdkit.Chem.AllChem.GetMorganFingerprintAsBitVect",
"matplotlib.pyplot.ylim",
"numpy.corrcoef",
"numpy.asarray... | [((576, 601), 'rdkit.Chem.MolFromSmiles', 'Chem.MolFromSmiles', (['smile'], {}), '(smile)\n', (594, 601), False, 'from rdkit import Chem, DataStructs\n'), ((620, 683), 'rdkit.Chem.AllChem.GetMorganFingerprintAsBitVect', 'Chem.AllChem.GetMorganFingerprintAsBitVect', (['mol', 'radius', 'fp_len'], {}), '(mol, radius, fp_l... |
# coding: utf-8
"""
self-managed-osdu
Rest API Documentation for Self Managed OSDU # noqa: E501
OpenAPI spec version: 0.11.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
from OsduClient.configuration import Configurati... | [
"six.iteritems",
"OsduClient.configuration.Configuration"
] | [((2354, 2387), 'six.iteritems', 'six.iteritems', (['self.swagger_types'], {}), '(self.swagger_types)\n', (2367, 2387), False, 'import six\n'), ((1167, 1182), 'OsduClient.configuration.Configuration', 'Configuration', ([], {}), '()\n', (1180, 1182), False, 'from OsduClient.configuration import Configuration\n')] |
from melange import DriverManager
from melange.messaging.exchange_message_publisher import ExchangeMessagePublisher
DriverManager.instance().use_driver(driver_name='aws')
publisher = ExchangeMessagePublisher('dev-superbattle')
publisher.publish({
'amount': 20
}, 'DamageDealtToHero')
print('Gñeeee, die you fool!... | [
"melange.DriverManager.instance",
"melange.messaging.exchange_message_publisher.ExchangeMessagePublisher"
] | [((185, 228), 'melange.messaging.exchange_message_publisher.ExchangeMessagePublisher', 'ExchangeMessagePublisher', (['"""dev-superbattle"""'], {}), "('dev-superbattle')\n", (209, 228), False, 'from melange.messaging.exchange_message_publisher import ExchangeMessagePublisher\n'), ((117, 141), 'melange.DriverManager.inst... |
import argparse
import re
import subprocess
REGEX = r'\[\s*(\d+)\s*\]'
def solved_questions():
print('Getting list of solved questions.')
out = subprocess.check_output(
['leetcode', 'list', '-q', 'd'],
)
problems = []
for line in out.decode().split('\n'):
matches = re.search(REGEX,... | [
"subprocess.check_output",
"re.search",
"argparse.ArgumentParser"
] | [((154, 210), 'subprocess.check_output', 'subprocess.check_output', (["['leetcode', 'list', '-q', 'd']"], {}), "(['leetcode', 'list', '-q', 'd'])\n", (177, 210), False, 'import subprocess\n'), ((475, 543), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Get list of solved questions."""'})... |
# coding:utf-8
'''
Created on 2016/07/09
@author: ota
'''
import sys
import traceback
class SqlFormatterException(Exception):
'''
SqlFormatter用のExceptionクラス
'''
def __init__(self, tlist, ex, trace):
super(SqlFormatterException, self).__init__(ex.message if hasattr(ex, "message") else "")
... | [
"traceback.format_exc"
] | [((1359, 1381), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (1379, 1381), False, 'import traceback\n'), ((1719, 1741), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (1739, 1741), False, 'import traceback\n')] |
# File :all.py
# Author :WJ
# Function :
# Time :2021/02/18
# Version :
# Amend :
import numpy as np
import ConvexPolygon as cp
import HierarchicalClustering as hc
import ConPolyProcess as cs
import LaplacianMatrice as lm
import time
from scipy.optimize import linear_sum_assignment
im... | [
"LaplacianMatrice.corrlation",
"HierarchicalClustering.HierarchicalClustering",
"HierarchicalClustering.mergeClosePoints",
"Visualization.VisualizeMatch",
"TransformationMatrix.transformation",
"ConPolyProcess.maxPoints",
"ConPolyProcess.delete_linepoints",
"LaplacianMatrice.resort_clouds",
"Laplaci... | [((1201, 1212), 'time.time', 'time.time', ([], {}), '()\n', (1210, 1212), False, 'import time\n'), ((1310, 1371), 'numpy.loadtxt', 'np.loadtxt', (['"""..\\\\data\\\\Polyline_PCB02_500.txt"""'], {'delimiter': '""","""'}), "('..\\\\data\\\\Polyline_PCB02_500.txt', delimiter=',')\n", (1320, 1371), True, 'import numpy as n... |
import unittest
from cipher import sub_cipher
class CipherTests(unittest.TestCase):
"""
Run several error tests
"""
def test_one_to_one(self):
self.assertTrue(sub_cipher('toot', 'peep'))
def test_one_to_two_correspondence(self):
self.assertFalse(sub_cipher('lambda', 'school'))
... | [
"unittest.main",
"cipher.sub_cipher"
] | [((622, 637), 'unittest.main', 'unittest.main', ([], {}), '()\n', (635, 637), False, 'import unittest\n'), ((186, 212), 'cipher.sub_cipher', 'sub_cipher', (['"""toot"""', '"""peep"""'], {}), "('toot', 'peep')\n", (196, 212), False, 'from cipher import sub_cipher\n'), ((286, 316), 'cipher.sub_cipher', 'sub_cipher', (['"... |
import logging
from requests_extra import get
logging.basicConfig(level=logging.DEBUG)
def test_sessions_automatically_reused_for_same_scheme_and_netloc(caplog):
# we will capture the debug logs that will print sth like "Got session from cache"
caplog.set_level(logging.DEBUG)
get("https://httpbin.org/... | [
"requests_extra.get",
"logging.basicConfig"
] | [((48, 88), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.DEBUG'}), '(level=logging.DEBUG)\n', (67, 88), False, 'import logging\n'), ((295, 324), 'requests_extra.get', 'get', (['"""https://httpbin.org/ip"""'], {}), "('https://httpbin.org/ip')\n", (298, 324), False, 'from requests_extra import ge... |
"""Views related to the Activity model.
Activity:
- POST /projects/{project_id}/activities
- PATCH /projects/{project_id}/activities/{activity_id}
- DELETE /projects/{project_id}/activities/{activity_id}
- PATCH /projects/{project_id}/activities/{activity_id}/publish
Competence:
- GET /competences
- POST /co... | [
"innopoints.extensions.db.session.add",
"innopoints.extensions.db.session.rollback",
"innopoints.models.Activity.query.get_or_404",
"innopoints.schemas.ActivitySchema",
"innopoints.extensions.db.session.commit",
"innopoints.models.Competence.query.get_or_404",
"logging.getLogger",
"innopoints.models.P... | [((1067, 1094), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1084, 1094), False, 'import logging\n'), ((1098, 1166), 'innopoints.blueprints.api.route', 'api.route', (['"""/projects/<int:project_id>/activities"""'], {'methods': "['POST']"}), "('/projects/<int:project_id>/activities', me... |
from matplotlib import mlab
import matplotlib.pyplot as plt
import numpy as np
import colorednoise as cn
from automutualinformation import sequential_mutual_information as smi
from automutualinformation import fit_model
beta = 0.5 # the exponent
samples = 10000 # number of samples to generate
y = cn.powerlaw_psd_gau... | [
"colorednoise.powerlaw_psd_gaussian",
"automutualinformation.sequential_mutual_information",
"numpy.max",
"numpy.min",
"numpy.arange",
"automutualinformation.fit_model",
"numpy.digitize"
] | [((301, 340), 'colorednoise.powerlaw_psd_gaussian', 'cn.powerlaw_psd_gaussian', (['beta', 'samples'], {}), '(beta, samples)\n', (325, 340), True, 'import colorednoise as cn\n'), ((441, 473), 'numpy.digitize', 'np.digitize', (['y', 'bins'], {'right': '(True)'}), '(y, bins, right=True)\n', (452, 473), True, 'import numpy... |
import unittest
from colourise import rgb2hsl
class TestRGBtoHSL(unittest.TestCase):
def test_primary_colour_red(self):
r, g, b = 255, 0, 0
h, s, l = rgb2hsl(r, g, b)
self.assertEqual(h, 0.0)
self.assertEqual(s, 1.0)
self.assertEqual(l, 0.5)
def test_primary_colour_gre... | [
"colourise.rgb2hsl"
] | [((172, 188), 'colourise.rgb2hsl', 'rgb2hsl', (['r', 'g', 'b'], {}), '(r, g, b)\n', (179, 188), False, 'from colourise import rgb2hsl\n'), ((376, 392), 'colourise.rgb2hsl', 'rgb2hsl', (['r', 'g', 'b'], {}), '(r, g, b)\n', (383, 392), False, 'from colourise import rgb2hsl\n'), ((581, 597), 'colourise.rgb2hsl', 'rgb2hsl'... |
from util import read_puzzle_input
from year_2021.day04.giant_squid import (
get_losing_board_score,
get_winning_board_score,
)
def test_get_winning_board_score():
assert get_winning_board_score(read_puzzle_input("test_input.txt")) == 4512
def test_get_losing_board_score():
assert get_losing_board_s... | [
"util.read_puzzle_input"
] | [((209, 244), 'util.read_puzzle_input', 'read_puzzle_input', (['"""test_input.txt"""'], {}), "('test_input.txt')\n", (226, 244), False, 'from util import read_puzzle_input\n'), ((325, 360), 'util.read_puzzle_input', 'read_puzzle_input', (['"""test_input.txt"""'], {}), "('test_input.txt')\n", (342, 360), False, 'from ut... |
from secretsharing import PlaintextToHexSecretSharer
def main():
# Enter shares
shares = [input('Enter your share: ')]
while True:
numofSHares = input("Still have more?\tYes\tNo\n").upper()
if numofSHares == "Y":
shares.append(input('Enter your share: '))
elif numof... | [
"secretsharing.PlaintextToHexSecretSharer.recover_secret"
] | [((461, 510), 'secretsharing.PlaintextToHexSecretSharer.recover_secret', 'PlaintextToHexSecretSharer.recover_secret', (['shares'], {}), '(shares)\n', (502, 510), False, 'from secretsharing import PlaintextToHexSecretSharer\n')] |
from HuginAutomator import HuginAutomator
from flask import Flask
import time
import datetime
import os
CONTEXTS = ('run', 'compute')
def get_env():
return {'credentials': os.getenv('DROPBOX_TOKEN'),
'min_s': os.getenv('MIN_STITCH'),
'max_s': os.getenv('MAX_STITCH'),
'min_a':... | [
"HuginAutomator.HuginAutomator",
"flask.Flask",
"time.sleep",
"os.environ.get",
"datetime.timedelta",
"os.getenv"
] | [((1179, 1194), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (1184, 1194), False, 'from flask import Flask\n'), ((630, 724), 'HuginAutomator.HuginAutomator', 'HuginAutomator', (["env['credentials']", "env['min_s']", "env['max_s']", "env['min_a']", "env['max_a']"], {}), "(env['credentials'], env['min_s'],... |
import os
from setuptools import setup
from snakehouse import Multibuild, build, monkey_patch_parallel_compilation, find_pyx_and_c, \
find_all
from setuptools import Extension
monkey_patch_parallel_compilation()
dont_snakehouse = False
if 'DEBUG' in os.environ:
print('Debug is enabled!')
dont_snakehouse... | [
"setuptools.Extension",
"snakehouse.find_all",
"setuptools.setup",
"snakehouse.Multibuild",
"snakehouse.build",
"snakehouse.monkey_patch_parallel_compilation"
] | [((183, 218), 'snakehouse.monkey_patch_parallel_compilation', 'monkey_patch_parallel_compilation', ([], {}), '()\n', (216, 218), False, 'from snakehouse import Multibuild, build, monkey_patch_parallel_compilation, find_pyx_and_c, find_all\n'), ((1148, 1218), 'snakehouse.build', 'build', (['cython_multibuilds'], {'compi... |
#! /usr/bin/python3
import sys
import os
import time
from typing import Dict, List, Tuple
from collections import defaultdict
Position = complex
DIRECTIONS: Dict[int, Position] = {
1: -1j,
2: 1j,
3: -1,
4: 1
}
class IntCodeComputer():
def __init__(self, memory: List[int], inputs: List[int] = [... | [
"os.path.isfile",
"time.perf_counter"
] | [((7302, 7321), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (7319, 7321), False, 'import time\n'), ((7395, 7414), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (7412, 7414), False, 'import time\n'), ((7014, 7039), 'os.path.isfile', 'os.path.isfile', (['file_path'], {}), '(file_path)\n', (7... |
#!/usr/bin/env python
from __future__ import print_function
from builtins import input
import sys
import pmagpy.pmag as pmag
def spitout(line):
if '\t' in line:
dat=line.split('\t') # split the data on a space into columns
else:
dat=line.split() # split the data on a space into columns
b,la... | [
"builtins.input",
"pmagpy.pmag.b_vdm",
"sys.argv.index",
"sys.stdin.readlines",
"sys.exit"
] | [((364, 382), 'pmagpy.pmag.b_vdm', 'pmag.b_vdm', (['b', 'lat'], {}), '(b, lat)\n', (374, 382), True, 'import pmagpy.pmag as pmag\n'), ((954, 964), 'sys.exit', 'sys.exit', ([], {}), '()\n', (962, 964), False, 'import sys\n'), ((1002, 1022), 'sys.argv.index', 'sys.argv.index', (['"""-f"""'], {}), "('-f')\n", (1016, 1022)... |
#!/usr/bin/env python
#
# This test uses out of band ovs-ofctl to query the
# switches and compare to an existing state to see
# if the flows are installed correctly in the PyTapDEMon
# topology.
#
import unittest
import subprocess
def parseFlows(flows):
"""
Parse out the string representation of flows pass... | [
"unittest.main",
"subprocess.check_output"
] | [((1008, 1076), 'subprocess.check_output', 'subprocess.check_output', (["['sudo', 'ovs-ofctl', 'dump-flows', switch]"], {}), "(['sudo', 'ovs-ofctl', 'dump-flows', switch])\n", (1031, 1076), False, 'import subprocess\n'), ((1543, 1558), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1556, 1558), False, 'import uni... |
import torch
import numpy as np
# Util function for loading meshes
from pytorch3d.io import load_objs_as_meshes
from pytorch3d.transforms import euler_angles_to_matrix, matrix_to_euler_angles,Rotate
# Data structures and functions for rendering
from pytorch3d.structures import Pointclouds, Meshes
from pytorch3d.render... | [
"torch.ones",
"pytorch3d.renderer.PointLights",
"pytorch3d.transforms.Rotate",
"pytorch3d.transforms.euler_angles_to_matrix",
"pytorch3d.renderer.BlendParams",
"pytorch3d.renderer.Materials",
"pytorch3d.structures.Meshes",
"torch.zeros",
"pytorch3d.renderer.MeshRasterizer",
"torch.sum",
"pytorch... | [((910, 1035), 'pytorch3d.renderer.RasterizationSettings', 'RasterizationSettings', ([], {'image_size': 'texture_size', 'blur_radius': '(0.0)', 'faces_per_pixel': '(1)', 'bin_size': 'None', 'max_faces_per_bin': 'None'}), '(image_size=texture_size, blur_radius=0.0,\n faces_per_pixel=1, bin_size=None, max_faces_per_bi... |
import scipy.sparse
import numpy as np
from tectosaur.util.cpp import imp
fast_constraints = imp('tectosaur.fast_constraints')
for k in dir(fast_constraints):
locals()[k] = getattr(fast_constraints, k)
def build_constraint_matrix(cs, n_total_dofs):
rows, cols, vals, rhs_rows, rhs_cols, rhs_vals, rhs_in, n_un... | [
"tectosaur.util.cpp.imp"
] | [((94, 127), 'tectosaur.util.cpp.imp', 'imp', (['"""tectosaur.fast_constraints"""'], {}), "('tectosaur.fast_constraints')\n", (97, 127), False, 'from tectosaur.util.cpp import imp\n')] |
from scipy.misc import comb
def exp(p, n):
total = 0.0
for k in range(n+1):
total += comb(n, k, exact=False) * p**k * (1-p) ** (n-k)
return total
def main():
for p in [0.3, 0.75, 0.8, 1.0, 0.0, 0.5]:
for n in range(1, 20):
print('Checking n=%d, p=%f' % (n, p))
... | [
"scipy.misc.comb"
] | [((103, 126), 'scipy.misc.comb', 'comb', (['n', 'k'], {'exact': '(False)'}), '(n, k, exact=False)\n', (107, 126), False, 'from scipy.misc import comb\n')] |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... | [
"pulumi.get",
"pulumi.getter",
"pulumi.set",
"pulumi.InvokeOptions",
"pulumi.runtime.invoke"
] | [((3175, 3207), 'pulumi.getter', 'pulumi.getter', ([], {'name': '"""createTime"""'}), "(name='createTime')\n", (3188, 3207), False, 'import pulumi\n'), ((3829, 3861), 'pulumi.getter', 'pulumi.getter', ([], {'name': '"""fileShares"""'}), "(name='fileShares')\n", (3842, 3861), False, 'import pulumi\n'), ((4128, 4160), 'p... |
#!/usr/bin/env python3
# Include the directory up in the path:
import sys
sys.path.insert(0,'..')
# Import stocker:
import stocker
# Main:
if __name__== "__main__":
# Let's save in a combination of stocks and bonds for retirement. Weight the
# initial portfolio towards 100% stocks for 15 years, weighted 70% US ... | [
"stocker.Piecewise_Scenario",
"sys.path.insert",
"stocker.Monte_Carlo",
"stocker.US_Bonds",
"stocker.International_Bonds",
"stocker.show_plots",
"stocker.International_Stocks",
"stocker.Scenario",
"stocker.US_Stocks"
] | [((75, 99), 'sys.path.insert', 'sys.path.insert', (['(0)', '""".."""'], {}), "(0, '..')\n", (90, 99), False, 'import sys\n'), ((676, 842), 'stocker.Scenario', 'stocker.Scenario', ([], {'name': '"""Initial Accumulation"""', 'portfolio': 'all_stocks_portfolio', 'num_years': '(15)', 'annual_contribution': '(16000)', 'annu... |
#!/usr/bin/env python
# coding: utf-8
import logging
from pykit import rangeset
from pykit import txutil
from .accessor import KeyValue
from .accessor import Value
from .status import COMMITTED
from .status import PURGED
from .status import STATUS
logger = logging.getLogger(__name__)
class StorageHelper(object):
... | [
"pykit.txutil.cas_loop",
"pykit.rangeset.RangeSet",
"pykit.rangeset.substract",
"logging.getLogger",
"pykit.rangeset.union"
] | [((261, 288), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (278, 288), False, 'import logging\n'), ((732, 842), 'pykit.txutil.cas_loop', 'txutil.cas_loop', (['self.record.get', 'self.record.set_or_create'], {'args': '(key,)', 'conflicterror': 'self.conflicterror'}), '(self.record.get, s... |
# -*- coding: utf-8 -*-
"""
@author: jiankaiwang
@version: 0.0.1
@date: 2020/03
@desc: The script implements the data loader of the MOT challenge.
@note:
Style: pylint_2015
@reference:
"""
import os
import logging
import pandas as pd
import requests
import tqdm
import zipfile
import argparse
# In[]
MOT_ID_LABEL = ... | [
"os.mkdir",
"zipfile.ZipFile",
"argparse.ArgumentParser",
"logging.basicConfig",
"os.path.basename",
"pandas.read_csv",
"os.path.exists",
"requests.get",
"os.path.join"
] | [((2092, 2116), 'os.path.join', 'os.path.join', (['"""/"""', '"""tmp"""'], {}), "('/', 'tmp')\n", (2104, 2116), False, 'import os\n'), ((2536, 2558), 'os.path.exists', 'os.path.exists', (['target'], {}), '(target)\n', (2550, 2558), False, 'import os\n'), ((6380, 6419), 'logging.basicConfig', 'logging.basicConfig', ([],... |
import logging
import sys
import numpy as np
from tensorflow.keras import backend as K
from tensorflow.keras import layers
from tensorflow.keras.layers import (
AveragePooling2D,
BatchNormalization,
Conv2D,
MaxPooling2D,
SeparableConv2D,
)
from tensorflow.keras.models import Model
sys.setrecursion... | [
"numpy.random.seed",
"tensorflow.keras.layers.MaxPooling2D",
"tensorflow.keras.layers.Reshape",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.layers.Multiply",
"sys.setrecursionlimit",
"tensorflow.keras.layers.Flatten",
"tensorflow.keras.layers.BatchNormalization",
"tensorflow.keras.backend.exp... | [((304, 334), 'sys.setrecursionlimit', 'sys.setrecursionlimit', (['(2 ** 20)'], {}), '(2 ** 20)\n', (325, 334), False, 'import sys\n'), ((335, 358), 'numpy.random.seed', 'np.random.seed', (['(2 ** 10)'], {}), '(2 ** 10)\n', (349, 358), True, 'import numpy as np\n'), ((949, 983), 'logging.debug', 'logging.debug', (['"""... |
#!/usr/bin/python3
# max_score:392
import sys
import random
import platform
from optparse import OptionParser
if platform.system() == "Windows":
import msvcrt
import time
else:
from select import select
try:
import enquiries
choose = enquiries.choose
except: # On offre une autre option si le mod... | [
"sys.stdin.flush",
"sys.stdout.write",
"msvcrt.kbhit",
"optparse.OptionParser",
"msvcrt.getwche",
"random.choice",
"time.sleep",
"select.select",
"time.monotonic",
"sys.stdout.flush",
"platform.system",
"sys.stdin.readline"
] | [((7643, 7657), 'optparse.OptionParser', 'OptionParser', ([], {}), '()\n', (7655, 7657), False, 'from optparse import OptionParser\n'), ((114, 131), 'platform.system', 'platform.system', ([], {}), '()\n', (129, 131), False, 'import platform\n'), ((2598, 2615), 'platform.system', 'platform.system', ([], {}), '()\n', (26... |
# Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""
migrate urls to documents
Create Date: 2017-05-02 14:06:36.936410
"""
# disable Invalid constant name pylint warning for mandatory Alembic variables.
# pylint: disable=invalid-name
from ggrc.migrations... | [
"ggrc.migrations.utils.url_util.delete_reference_urls",
"ggrc.migrations.utils.url_util.migrate_urls_to_documents"
] | [((655, 710), 'ggrc.migrations.utils.url_util.migrate_urls_to_documents', 'url_util.migrate_urls_to_documents', (['HYPERLINKED_OBJECTS'], {}), '(HYPERLINKED_OBJECTS)\n', (689, 710), False, 'from ggrc.migrations.utils import url_util\n'), ((810, 863), 'ggrc.migrations.utils.url_util.delete_reference_urls', 'url_util.del... |
import tensorflow as tf
a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')
c = tf.matmul(a, b)
# Creates a session with log_device_placement set to True.
with tf.Session(config=tf.ConfigProto(log_device_placement=True)) as ses... | [
"tensorflow.matmul",
"tensorflow.constant",
"tensorflow.ConfigProto"
] | [((29, 96), 'tensorflow.constant', 'tf.constant', (['[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]'], {'shape': '[2, 3]', 'name': '"""a"""'}), "([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')\n", (40, 96), True, 'import tensorflow as tf\n'), ((101, 168), 'tensorflow.constant', 'tf.constant', (['[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]... |
import re
boxRegex = re.compile(r"(\d+)x(\d+)x(\d+)")
def day2(fileName):
totalPaper = 0
totalRibbon = 0
with open(fileName) as infile:
for line in infile:
match = boxRegex.match(line)
if match:
sides = sorted(int(side) for side in match.group(1, 2, 3))
totalPaper += 3 * sides[0] * sides[1] + 2 * s... | [
"re.compile"
] | [((22, 56), 're.compile', 're.compile', (['"""(\\\\d+)x(\\\\d+)x(\\\\d+)"""'], {}), "('(\\\\d+)x(\\\\d+)x(\\\\d+)')\n", (32, 56), False, 'import re\n')] |
# 数学运算math函数示例
import math
import log
# 设置日志输出级别
log.basicConfig(level=log.INFO)
math_log = log.getLogger("Math")
# x**y运算后的值
result = math.pow(2,3)
math_log.info(result)
# 8.0
# 取大于等于x的最小的整数值,如果x是一个整数,则返回x
result = math.ceil(4.12)
math_log.info(result)
# 5
# 把y的正负号加到x前面,可以使用0
result = math.copysign(2,-3)
math_... | [
"math.isinf",
"math.copysign",
"math.frexp",
"math.ldexp",
"math.fmod",
"math.pow",
"math.modf",
"log.basicConfig",
"math.cos",
"math.trunc",
"math.isnan",
"math.sqrt",
"math.ceil",
"math.sin",
"math.degrees",
"math.exp",
"math.fabs",
"math.tan",
"log.getLogger",
"math.floor",
... | [((51, 82), 'log.basicConfig', 'log.basicConfig', ([], {'level': 'log.INFO'}), '(level=log.INFO)\n', (66, 82), False, 'import log\n'), ((97, 118), 'log.getLogger', 'log.getLogger', (['"""Math"""'], {}), "('Math')\n", (110, 118), False, 'import log\n'), ((141, 155), 'math.pow', 'math.pow', (['(2)', '(3)'], {}), '(2, 3)\... |
import board
import neopixel
pixels = neopixel.NeoPixel(board.D6, 30, brightness=0.5, auto_write=False)
pixels.fill((255, 0, 0))
pixels.show()
| [
"neopixel.NeoPixel"
] | [((38, 103), 'neopixel.NeoPixel', 'neopixel.NeoPixel', (['board.D6', '(30)'], {'brightness': '(0.5)', 'auto_write': '(False)'}), '(board.D6, 30, brightness=0.5, auto_write=False)\n', (55, 103), False, 'import neopixel\n')] |