text
string
size
int64
token_count
int64
import pytest import datetime from django.test import TestCase from django.utils import timezone from gamer_registration_system.con.models import Convention, Event, EventSchedule # Create your tests here. class EventScheduleModelTests(TestCase): new_con = Convention(convention_name='Test Future Con') new_eve...
1,648
509
# -*- coding: utf-8 -*- # @Time: 2020/7/3 10:21 # @Author: GraceKoo # @File: interview_33.py # @Desc: https://leetcode-cn.com/problems/chou-shu-lcof/ class Solution: def nthUglyNumber(self, n: int) -> int: if n <= 0: return 0 dp, a, b, c = [1] * n, 0, 0, 0 for i in range(1, n):...
661
298
# Solution for the SafeCracker 50 Puzzle from Creative Crafthouse # By: Eric Pollinger # 9/11/2016 # # Function to handle the addition of a given slice def add(slice): if row1Outer[(index1 + slice) % 16] != -1: valRow1 = row1Outer[(index1 + slice) % 16] else: valRow1 = row0Inner[slice] ...
2,599
1,133
#!/usr/bin/env python # -*- coding: utf-8 -*- import chainer from chainer import cuda from chainer import configuration class Mul(chainer.function.Function): def __init__(self): return def forward(self, inputs): x1, x2 = inputs xp = cuda.get_array_module(x1) # Get numpy(x=n) or c...
978
365
#!/usr/bin/env python # Copyright 2012 Google Inc. All Rights Reserved. """Tests for grr.client.lib.osx.objc. These tests don't have OS X dependencies and will run on linux. """ import ctypes import mox from grr.client.osx import objc from grr.lib import flags from grr.lib import test_lib class ObjcTest(test_li...
1,673
634
import pytest from demo.jwt import IdentityMaker, JwtIdentityPolicy, JwtAuthPolicy from security_interface.api import Security SECRET = "SECRET" identity_maker = IdentityMaker(expired_after=1, secret=SECRET) jwt_identity = JwtIdentityPolicy(secret=SECRET) jwt_auth = JwtAuthPolicy() security = Security(jwt_identity...
731
243
#!/usr/bin/env python import rospy import tf from jsk_recognition_msgs.msg import BoundingBox class BoundingBoxToTf(object): def __init__(self): self.tf_frame = rospy.get_param('~tf_frame', 'bounding_box') self.broadcaster = tf.TransformBroadcaster() self.sub = rospy.Subscriber('~inpu...
867
297
from .pymkup import * __version__ = '0.1'
42
19
# test __getattr__ on module # ensure that does_not_exist doesn't exist to start with this = __import__(__name__) try: this.does_not_exist assert False except AttributeError: pass # define __getattr__ def __getattr__(attr): if attr == 'does_not_exist': return False raise AttributeError # ...
539
164
from defs_utils import * import pdf2image import os def transforma_pdf_em_img_por_materia(materia, pdf_path=None): searched = materia if pdf_path: list_files = list_dir(complete_name(searched, pre=pdf_path), True) else: list_files = list_dir(complete_name(searched), True) volta = os.ge...
1,094
367
#Cristian Chitiva #cychitivav@unal.edu.co #12/Sept/2018 myList = ['Hi', 5, 6 , 3.4, "i"] #Create the list myList.append([4, 5]) #Add sublist [4, 5] to myList myList.insert(2,"f") #Add "f" in the position 2 print(myList) myList = [1, 3, 4, 5, 23, 4, 3, 222, 454, 6445, 6, 4654, 455] myList.sort() #So...
826
388
import sys, traceback from bs4 import BeautifulSoup import rethinkdb as r import requests import time import geocoder import datetime from dateutil.parser import parse as dtparse from pytz import timezone r.connect( "localhost", 28015).repl() la = timezone('America/Los_Angeles') table = r.db("revealseattle").table("dis...
7,955
2,513
import os import pathlib import pytest from unasyncer.unasync import unasync_path @pytest.fixture def expected_unasynced_code(sources: pathlib.Path) -> str: with open(sources / "right_sync.py") as right_sync_file: return right_sync_file.read() def test_create_right_sync_structure_for_dir(sources: path...
2,654
929
import random def shuffle_shoe(n_decks=8): cards = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K'] deck = cards * 4 shoe = deck * n_decks random.shuffle(shoe) return shoe def deal_game(shoe): # initialize a list to store cards for player and banker player = [] banker = [] # defi...
4,281
1,536
import pytest from sage_utils.amqp.clients import RpcAmqpClient from sage_utils.amqp.extension import AmqpExtension from sage_utils.constants import VALIDATION_ERROR from sage_utils.wrappers import Response from tests.fixtures import Application, FakeConfig, FakeRegisterMicroserviceWorker REQUEST_QUEUE = FakeRegiste...
3,561
1,157
""" File: largest_digit.py Name: ---------------------------------- This file recursively prints the biggest digit in 5 different integers, 12345, 281, 6, -111, -9453 If your implementation is correct, you should see 5, 8, 6, 1, 9 on Console. """ def main(): print(find_largest_digit(12345)) # 5 print(find_larg...
986
463
#!/usr/bin/env python3 # Test whether a connection is disconnected if it sets the will flag but does # not provide a will payload. from mosq_test_helper import * def do_test(proto_ver): rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("will-no-payload", keepalive=keepalive, will_topic="will/t...
1,196
442
# Copyright (c) 2017, Carnegie Mellon University. All rights reserved. # # Use of the K-NRM package is subject to the terms of the software license set # forth in the LICENSE file included with this software, and also available at # https://github.com/AdeDZY/K-NRM/blob/master/LICENSE from setuptools import setup from ...
563
180
""" This module is not meant to be imported directly. Its purpose is to patch the TohuBaseGenerator class so that its special methods __add__, __mul__ etc. support other generators as arguments. """ from operator import add, mul, gt, ge, lt, le, eq from .base import TohuBaseGenerator from .primitive_generators import...
2,674
846
#Imports import config import telebot from db_manager import SQL import os #Globals restaurants = {"12345":"abc"} current_restaurant_id = "" current_restaurant_key = "" couriers = {"12345":"abc"} current_courier_id = "" current_courier_key = "" current_courier_altitude = 0 current_courier_longitude = 0 #DB + BOT CO...
12,486
4,646
#!/usr/bin/env python3 from math import hypot from sys import argv from typing import List, Dict, Tuple def main(fn, maxD): with open(fn) as file: positions: List[str] = file.readlines() uLocations: Dict[int, Dict[str, Tuple[int, int]]] = {} for position in positions: positionSplit = posi...
1,205
386
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2017-09-10 20:53 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ("bdiadmin", "0013_auto_20170319_1415"), ("stock", "0...
2,155
571
# -*- coding: UTF-8 -*- """ Source processing routines """ from __future__ import absolute_import from __future__ import unicode_literals import warnings from collections import OrderedDict from astropy.cosmology import default_cosmology import numpy as np import os import pysynphot as S import astropy.table as at fro...
5,271
1,634
from random import randint class Objects: def __init__(self): self._type=' ' self._arr=[] def creating_objects(self): times=randint(10,20) for i in range(times): temp=[] temp.append(randint(1,4))#1=slant 2=horizontal 3=vertical 4=powerup temp.a...
415
138
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import cv2 import numpy as np from matplotlib import pyplot as plt import os import math def gaussian(x, mu, sig): return ((1/(sig*math.sqrt(2*math.pi)))*np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))) x=list(range(0, 256)) g1=gaussian(x,np.array([239.82])...
2,264
934
sample = ["abc", "xyz", "aba", "1221"] def stringCounter(items): amount = 0 for i in items: if len(i) >= 2 and i[0] == i[-1]: amount += 1 return amount print("The amount of string that meet the criteria is:",stringCounter(sample))
264
89
#!/usr/bin/python # -*- coding: utf-8 -*- __author__ = "Robin 'r0w' Weiland" __date__ = "2020-03-02" __version__ = "0.1.2" """Library for creating system tray applications based on Moses Palmér's 'pystray' library See README for insntructions""" __all__ = ('TrayApp',) from typing import Union, Tuple from pystray im...
3,937
1,246
"""Domain class for the compiler service.""" from typing import NamedTuple, Optional, BinaryIO, Dict import io from datetime import datetime from .util import ResponseStream from enum import Enum class Format(Enum): """Compilation formats supported by this service.""" PDF = "pdf" DVI = "dvi" PS = "p...
5,210
1,509
#! /usr/bin/python # -*- coding: UTF-8 -*- import sys import re import string import commands import warnings errors = 0 def warn(msg, error=None): global errors errors += 1 if error is None: warnings.warn("-- "+str(errors)+" --\n "+msg, RuntimeWarning, 2) else: warnings.warn("-- "+str...
40,912
12,760
# Copyright 2015 Tzanetos Balitsaris # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
2,618
766
import pandas as pd import numpy as np import pickle from sklearn.metrics.pairwise import linear_kernel from sklearn.feature_extraction.text import TfidfVectorizer import csv from kivy.app import App from kivy.uix.gridlayout import GridLayout from kivy.uix.label import Label from kivy.uix.textinput import TextInput ...
1,566
514
#!/usr/bin/env python import rospy import roslaunch if __name__ == "__main__": rospy.sleep(6.5) uuid = roslaunch.rlutil.get_or_generate_uuid(None, False) roslaunch.configure_logging(uuid) launch = roslaunch.parent.ROSLaunchParent(uuid,["/home/ntestar/catkin_ws/src/yoyoman01_robot/yoyoman01_traject/launch/set...
369
149
from django import template register = template.Library() @register.inclusion_tag('quiz/correct_answer.html', takes_context=True) def correct_answer_for_all(context, question): """ processes the correct answer based on a given question object if the answer is incorrect, informs the user """ answe...
744
213
# -*- coding: utf-8 -*- """ Created on Mon Jun 29 14:14:45 2020 @author: Nikki """ import numpy as np import cv2 import transform as tform import sys import math import scipy.spatial import markers ###--------------------------------------------------------------------------- # Allows video to be initialized usin...
12,867
4,468
"""Select2 support for DAL.""" # default_app_config = 'dal_select2.apps.DefaultApp'
85
31
from django.urls import path from . import views urlpatterns = [ #Assets Section path('all', views.AssetsView.all_assets, name='AssetsList'), path('lookup', views.AssetsView.lookup, name='Lookup_Asset'), path('add', views.AssetsView.add_asset, name='Add_Asset'), path('<str:asset_id>/statement', vie...
714
221
"""empty message Revision ID: 597e346723ee Revises: 56b57f01c4b4 Create Date: 2015-03-25 16:36:11.552342 """ # revision identifiers, used by Alembic. revision = '597e346723ee' down_revision = '56b57f01c4b4' from alembic import op import sqlalchemy as sa from sqlalchemy.sql import column, table from sqlalchemy impor...
1,493
512
# ####### # Copyright (c) 2014-2020 Cloudify Platform Ltd. All rights reserved # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
4,813
1,358
#!/usr/bin/env python """Generic network class for supervised regression Created on: March 25, 2017 Author: Mohak Bhardwaj""" from collections import defaultdict from planning_python.heuristic_functions.heuristic_function import EuclideanHeuristicNoAng, ManhattanHeuristicNoAng, DubinsHeuristic import numpy as np impor...
8,974
2,975
import os NOT_SET: object = object() DEFAULT_INI_PATH: str = os.environ.get( "NETSUITE_CONFIG", os.path.expanduser("~/.config/netsuite.ini"), ) DEFAULT_INI_SECTION: str = "netsuite"
187
72
import os import re import sys from .conda import conda, conda_env_load, conda_cmd_channels, ei_touch from .utils import comment_find, git, pushd, sh from configparser import ConfigParser from glob import glob from ruamel.yaml import YAML DMFILE_RE = re.compile(r'^(?P<name>[A-z\-_l]+)(?:[=<>\!]+)?(?P<version>[A-z0-9....
7,996
2,479
# mp4.py # --------------- # Licensing Information: You are free to use or extend this projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to the University of Illinois at Urbana-Champaign # # Created Fa...
5,762
1,724
# Uri Online Judge 1079 N = int(input()) for i in range(0,N): Numbers = input() num1 = float(Numbers.split()[0]) num2 = float(Numbers.split()[1]) num3 = float(Numbers.split()[2]) print(((2*num1+3*num2+5*num3)/10).__round__(1))
251
109
from ex2.sigmoid import sigmoid def sigmoidGradient(z): """computes the gradient of the sigmoid function evaluated at z. This should work regardless if z is a matrix or a vector. In particular, if z is a vector or matrix, you should return the gradient for each element.""" # =====================...
633
170
#!/usr/bin/env python """ Test the Inspector """ import os.path, sys sys.path.append(os.path.dirname(__file__)) import unittest import inspector ######################################################## # # Inspector test # ######################################################## def func2(*args, **kwargs): ""...
2,363
731
"""Util functions for accessing data via DynamoDB.""" import boto3 from boto3.dynamodb.conditions import Key class UnknownInviteCodeError(Exception): """An error when an unknown invite code is entered.""" pass def get_invitee(invite_code: str): """Get a dictionary of the stored information for this inv...
4,418
1,318
# Auto generated configuration file # using: # Revision: 1.19 # Source: /local/reps/CMSSW/CMSSW/Configuration/Applications/python/ConfigBuilder.py,v # with command line options: Configuration/GenProduction/python/HIG-RunIIFall17wmLHEGS-05498-fragment.py --python_filename HIG-RunIIFall17wmLHEGS-05498_1_cfg.py --event...
10,199
4,148
import pywikibot from pywikibot import pagegenerators from urllib.request import urlopen import urllib.parse import regex as re #use this rather than "re" to avoid the "look-behind requires fixed-width pattern" error site = pywikibot.Site('zh','wikipedia') cat = pywikibot.Category(site,'Category:連結格式不正確的條目') page_to_w...
4,251
2,259
#! /usr/bin/env python # -*- coding: utf-8 -*- """ The main varnam module. """ from .library import InternalVarnamLibrary from .utils import * from .varnam_defs import * from warnings import warn import ctypes as C class Varnam: """ Varnam class which encapsulates all InternalVarnamLibrary calls. """...
5,306
1,483
from . import * class BICClassifier(Classifier): # These prefixes came from from http://editeur.dyndns.org/bic_categories LEVEL_1_PREFIXES = { Art_Design: 'A', Biography_Memoir: 'B', Foreign_Language_Study: 'C', Literary_Criticism: 'D', Reference_Study_Aids: 'G', ...
3,755
1,338
# -*- coding: utf-8 -*- from __future__ import (print_function, unicode_literals, absolute_import, division) from pusher.config import Config from pusher.request import Request from pusher.sync import SynchronousBackend from pusher.util import GET, POST, text, validate_channel import collectio...
4,490
1,278
""" To run this module directly """ # pylint: disable=no-else-return import argparse import os try: from . import prefetch_from_file except ImportError: import prefetch_from_file try: from . import prefetch_from_url except ImportError: import prefetch_from_url def validate_filepath_or_url(filepath_o...
1,986
620
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 # # 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 ...
2,577
822
import numpy as np from src import const #TODO: should be imported from aguirregabiria_simple.py def period_profit(p: np.ndarray, lambdas: np.ndarray, betas_transition=const.betas_transition): """ Correct expected period return profit. See ReadMe for derivation """ constant_part = (p-const.c) * np.e *...
1,219
569
# code adapted from http://my.safaribooksonline.com/book/-/9781449308100/2dot-ec2-recipes/id2529379 def launch_instance(aws_access_key_id=None, aws_secret_access_key=None, ami='ami-a29943cb', instance_type='t1.micro', key_name='rdhyee_publi...
6,187
1,661
import mock from pyramid.request import Request from .support import DummyRequest, unittest from kinto.core import authentication from kinto.core.authorization import RouteFactory, AuthorizationPolicy from kinto.core.storage import exceptions as storage_exceptions class RouteFactoryTest(unittest.TestCase): def...
10,998
3,251
import copy #from enum import IntFlag from time import sleep # I tried to use enum here, but I was having a problem with packages in the image, so I gave up as I just want to get it done class FieldValue: Empty = 0 Wall = 1 Player = 2 Box = 4 Goal = 8 class SenseHATColour: Red = (204, 4, 4) ...
6,663
2,116
from __future__ import print_function from sklearn.feature_extraction.text import TfidfVectorizer from common.util import ReviewUtil import numpy as np import ntpath import pandas as pd import os from common.base_task import BaseTask class ReviewDedupTask(BaseTask): def __init__(self, inputdir, threshold=0.9, sit...
4,082
1,306
# coding: utf-8 """ NiFi Rest Api The Rest Api provides programmatic access to command and control a NiFi instance in real time. Start and stop processors, monitor queues, query provenance data, and more. Each endpoint below includes a description, ...
59,325
13,822
#!/usr/bin/env python """ Usage: python vtk_reindent_code.py [--test] <file1> [<file2> ...] This script takes old-style "Whitesmiths" indented VTK source files as input, and re-indents the braces according to the new VTK style. Only the brace indentation is modified. If called with the --test option, then it ...
16,811
4,959
from simplesensor.communication_modules.azure_iot_hub.azureIotHubModule import AzureIotHubModule as CommunicationModule
119
33
from util.List import * print( dir() ) lst = list(range(9999)) hd,*tl = lst print( hd ) print( tl ) del hd,tl Lst = toList(lst) try: print( hd,tl ) except NameError as e: with Lst as (hd,tl): print( hd ) print( tl ) print( type(hd),type(tl) ) print( Lst.hd is hd ) print(...
591
265
import os.path from scipy.optimize import fsolve import math import numpy as np from matplotlib import pyplot as plt import pandas as pd import utils_Florian as utils def equations(p, t_peak, t_half): x, y = p return (0.5 * (math.exp(-x * t_peak) - math.exp(-y * t_peak)) - (math.exp(-x * t_half) - math.exp...
1,809
760
from otree.api import Currency as c, currency_range from . import pages from ._builtin import Bot from .models import Constants class PlayerBot(Bot): def play_round(self): if self.round_number <= self.participant.vars['last_round']: yield pages.Decision, {"decision_high": 1, "decision_low": 1}...
1,334
409
import requests async def req_top_topic(): url = "https://www.zhihu.com/api/v4/search/top_search" user_agent = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.8) Gecko Fedora/1.9.0.8-1.fc10 Kazehakase/0.5.6" headers = { "User-Agent": user_agent } try: resp = requests.get(url=url, ...
511
201
import re import string import numpy as np from tqdm import tqdm from typing import List from docqa.triviaqa.read_data import TriviaQaQuestion from docqa.triviaqa.trivia_qa_eval import normalize_answer, f1_score from docqa.utils import flatten_iterable, split """ Tools for turning the aliases and answer strings from...
11,219
3,238
"""Schemas for grocy.""" import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.const import (CONF_HOST, CONF_ENTITY_ID, CONF_USERNAME, CONF_PASSWORD) from .const import (DOMAIN, CONF_APIKEY, CONF_AMOUNT, CONF_SHOPPING_LIST_ID, CONF_B...
2,171
834
entity_id = data.get('entity_id') command = data.get('command') params = str(data.get('params')) parsedParams = [] for z in params.replace(' ', '').replace('],[', '|').replace('[', '').replace(']', '').split('|'): rect = [] for c in z.split(','): rect.append(int(c)) parsedParams.append(rect) if co...
548
184
# Generated by Django 3.2.9 on 2021-11-13 14:43 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('base', '0005_authquery_password'), ] operations = [ migrations.AddField( model_name='profile', name='h...
417
151
def rank_filter(func): def func_filter(local_rank=-1, *args, **kwargs): if local_rank < 1: return func(*args, **kwargs) else: pass return func_filter
199
63
import math def checkio(data): x1=int(data[1]) y1=int(data[3]) x2 = int(data[7]) y2 = int(data[9]) x3 = int(data[13]) y3 = int(data[15]) A = x2 - x1 B = y2 - y1 C = x3 - x1 D = y3 - y1 E = A * (x1 + x2) + B * (y1 + y2) F = C * (x1 + x3) + D * (y1 + y3) G = 2 * (A ...
897
461
import configparser import enum ini = 'settings.ini' class Database(enum.Enum): SQLITE = 1 POSTGRES = 2 def get_db() -> Database: return Database[get_entry('Database', 'db')] def get_database_url() -> str: return get_entry('Database', 'database_url') def get_init_username() -> str: return g...
903
288
import pytest from lispyc import nodes from lispyc.exceptions import SpecialFormSyntaxError, TypeSyntaxError from lispyc.nodes import ComposedForm, Constant from lispyc.nodes import FunctionParameter as Param from lispyc.nodes import Program, Variable, types from lispyc.parser import parse VALID = [ ("(lambda () ...
3,070
981
from django.conf.urls import url from rest_framework_jwt.views import ( obtain_jwt_token, refresh_jwt_token, verify_jwt_token ) urlpatterns = [ url(r'^obtain-token', obtain_jwt_token), url(r'^token-refresh/', refresh_jwt_token), url(r'^api-token-verify/', verify_jwt_token) ]
306
123
import nifty.tools as nt import numpy as np import z5py from elf.label_multiset import deserialize_multiset from tqdm import trange def check_serialization(mset1, mset2): if len(mset1) != len(mset2): print("Serialization sizes disagree:", len(mset1), len(mset2)) return False if not np.array_...
5,289
1,940
import sys from itertools import product n, *abc = map(int, sys.stdin.readline().split()) *l, = map(int, sys.stdin.read().split()) def main(): cand = [] for p in product([0, 1, 2, 3], repeat=n): group = [[] for _ in range(4)] for i in range(n): group[p[i]].append(l[i]) ...
729
275
import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import DataLoader from torchvision.transforms import ToTensor from torchvision.datasets import MNIST from vis_util import visual_mnist ##### settings x_dim = 28 * 28 # size of mnist digit z_dim = 100 # random noise h_dim = 128 ...
2,882
1,104
from django.shortcuts import render, redirect, reverse from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage from django.db.models import Q from django.views.generic import View from .models import OrgInfo, CityInfo, TeacherInfo from operations.models import UserLove # Create your views here. clas...
6,296
2,155
from keras.callbacks import TensorBoard,EarlyStopping,TerminateOnNaN,ReduceLROnPlateau,ModelCheckpoint import os import sys import tensorflow as tf import keras.backend.tensorflow_backend as KTF file_abspath = os.path.abspath(sys.argv[0]) # exe所在文件地址 location = os.path.dirname(file_abspath) # exe所在文件夹目录地址 tbCallB...
1,021
399
from copy import deepcopy from bmds.bmds3.constants import ContinuousModelIds, DichotomousModelIds from bmds.bmds3.types.priors import PriorClass from bmds_server.analysis.executor import AnalysisSession class TestAnalysisSession: def test_default_dichotomous(self, bmds3_complete_dichotomous): # assure ...
8,545
2,723
tot=coe=rat=sap=0 for i in range(int(input())): n,s=input().split() n=int(n) tot+=n if s=='C':coe+=n elif s=='R':rat+=n elif s=='S':sap+=n print(f"Total: {tot} cobaias\nTotal de coelhos: {coe}\nTotal de ratos: {rat}\nTotal de sapos: {sap}") p=(coe/tot)*100 print("Percentual de coelhos: %.2f"%p,e...
483
232
from sys import path path.append('..') from armoryengine import * TheBDM.setBlocking(True) TheBDM.setOnlineMode(True) if not os.path.exists('testmultiblock'): os.mkdir('testmultiblock') fout = [] fout.append([0, 101, 'testmultiblock/blk00000.dat']) fout.append([0, 102, 'testmultiblock/blk00000_test1.dat']) #...
1,722
750
# Generated by Django 3.1.1 on 2020-12-26 20:50 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('dashboard', '0033_auto_20201226_2148'), ] operations = [ migrations.RenameField( model_name='sleepnight', old_name='data', ...
369
138
"""Fear and Greed Index Class""" __docformat__ = "numpy" from matplotlib import pyplot as plt from fear_greed_index import scrape_cnn from fear_greed_index.FearAndGreedIndicator import FearAndGreedIndicator class CNNFearAndGreedIndex: """CNN Fear and Greed Index Attributes ---------- junk_bond_deman...
7,050
2,145
#!/usr/bin/dev python # coding=utf-8 #让爬虫等待几秒 from pyDEV import BsDI, ToolDI from bs4 import BeautifulSoup; import os import urllib; #创建入口url url_web = "http://48et.com/pic/12/" html_pag = ''; for i in range(1,1001): if i > 1 : html_pag='p_'+str(i)+'.html' url_web = url_web+html_pag html = BsDI.ge...
1,632
767
#! /usr/bin/env python # The MIT License (MIT) # # Copyright (c) 2015, EPFL Reconfigurable Robotics Laboratory, # Philip Moseley, philip.moseley@gmail.com # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (th...
3,553
1,306
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Changing field 'Party.primaries_date' db.alter_column('party_party', 'primaries_date', self.gf('django.db...
6,331
1,955
[ ## this file was manually modified by jt { 'functor' : { 'description' : [ "The function always returns a value of the same type than the entry.", "Take care that for integers the value returned can differ by one unit", "from \c ceil((a+b)/2.0) o...
2,767
946
from __future__ import print_function from conductor.conductor import MetadataClient, WorkflowClient class Workflow(object): def __init__(self, name, description=None): self.tasks = {} self.inputs = {} self.outputs = {} self.connections = {} self.name = name if de...
6,165
1,963
'''super basic web server to start/stop and monitor virtual environments''' import sys import os import logging import web import time import argparse from webpyutils import api from webpyutils import APIServer from vswitch import VirtualSwitch #get project path from current file or venv it setup locally PROJECT_PATH ...
4,049
1,221
from con_esxi_host import * from math import pow, ceil class vmware: def get_vm_info(self): si = connect_to_host() #global virtual inv = si.RetrieveContent() dc1 = inv.rootFolder.childEntity[0] vmList = dc1.vmFolder.childEntity virtual = [] for vm in...
2,441
765
import numpy as np import cv2 import matplotlib.pyplot as plt from pathlib import Path import glob2 as glob import os import sys savedir = "./output/" def AddWatermarkFolder(str_foldername, str_watermarkname, alpha1=1.0, alpha2=0.2): path = str_foldername + '/*.png*' for iter, path_name in enumerate(glob.glob...
2,155
827
# -*- coding: utf-8 -*- """ idfy_rest_client.models.person_person_information This file was automatically generated for Idfy by APIMATIC v2.0 ( https://apimatic.io ) """ from idfy_rest_client.api_helper import APIHelper class PersonPersonInformation(object): """Implementation of the 'Person.P...
4,980
1,328
import logging import subprocess # create logger logger = logging.getLogger('simple_example') logger.setLevel(logging.DEBUG) # create console handler and set level to INFO console_logger = logging.StreamHandler() console_logger.setLevel(logging.INFO) # create formatter formatter = logging.Formatter('%(asctime)s - %(...
1,018
332
from django.http import HttpResponse from django.shortcuts import render from django.views.decorators.cache import cache_page from django.views.decorators.gzip import gzip_page from django.views.generic import DetailView from about.models import AboutItem from blog.models import Article from home.models import Home f...
2,214
655
import numpy as np from pandas import read_csv import pandas as pd from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt from config import * from lib.preprocess.read_data import DataReader from lib.scaler.preprocessing_data.data_normalizer import DataNormalizer class DataPreprocessor:...
4,366
1,452
# This Python file uses the following encoding: utf-8 """autogenerated by genpy from px_comm/CameraInfo.msg. Do not edit.""" import codecs import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct import geometry_msgs.msg import std_msgs.msg class CameraInfo(genpy.Message): _md5...
16,292
5,318
from itertools import chain from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.shortcuts import render from wagtail.core.models import Page from wagtail.search.models import Query from about.models import AboutPage, AboutSubPage, CaseStudyPage, HistoryPage, PeoplePage from contact.mode...
3,567
1,005
# pylint: disable=arguments-differ,unused-argument,line-too-long """R2Plus1D, implemented in Gluon. https://arxiv.org/abs/1711.11248. Code partially borrowed from https://github.com/pytorch/vision/blob/master/torchvision/models/video/resnet.py.""" __all__ = ['R2Plus1D', 'r2plus1d_resnet18_kinetics400', 'r2...
24,607
7,465
#!/usr/bin/env python3 import retrieve_author_ppn as autppn import retrieve_references as refs import zot_helpers as pyzot from itertools import islice researchers = autppn.constructOutput('test.csv') autppn.writeCsv('out.csv', researchers) for researcher in researchers: ppn = researcher['ppn'] creator_name...
1,079
344