text stringlengths 8 6.05M |
|---|
import json
import numpy as np
import re
import argparse
key_name_update_dict = {'object':'annotations', 'bounding_box': 'bbox',
'class': 'category_name',
}
cname_cid_dict = {}
set_of_objects = set()
object_types = ['barrel', 'tableround', 'chair', 'crate',
... |
import json
import warnings
import numpy as np
import pytest
from smalldataviewer.ext import h5py, NoSuchModule, z5py, imageio
from tests.constants import INTERNAL_PATH
def hdf5_file(path, array):
if isinstance(h5py, NoSuchModule):
pytest.skip("h5py not installed")
with h5py.File(path, "w") as f:
... |
# importer la binliothèque
import tkinter as tk
import pandas as pd
import numpy as np
import pyttsx3
import os
import shutil
import time
from tkinter import filedialog, messagebox, ttk
from tkinter.constants import ACTIVE
from datetime import date
from openpyxl import load_workbook
##################... |
import requests
from bs4 import BeautifulSoup
import json
import pandas as pd
from sklearn import preprocessing
def process_rec(rec):
t1slash=rec[0].index('/')
t2slash=rec[1].index('/')
try:
print(rec)
int(rec[0][-1])
except:
print(rec)
dd = {
'line': rec[0][1]
,'t1score': rec[0][-1]
,'t2score': rec... |
from tkinter import *
from tkinter.ttk import *
from tkinter import *
from tkinter.ttk import *
# Command interface
class Command():
def comd(self):pass
#derived button class with an abstract comd method
class DButton(Button, Command):
def __init__(self, master, **kwargs):
super().__init__(master, c... |
import django_filters
from subreddit.models import Subreddit
from django_filters import CharFilter
class SubredditFilter(django_filters.FilterSet):
title = CharFilter(field_name='title', lookup_expr='startswith')
class Meta:
model = Subreddit
fields = ['title']
|
# Generated by Django 2.2.9 on 2020-02-27 08:36
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('dmarc', '0002_auto_20180124_2311'),
]
operations = [
migrations.AlterModelOptions(
name='report',
options={},
),
... |
#1
def numberlist():
ui = input("Enter a list of numbers. Please put a space between each number ")
List = list(int(num) for num in ui.strip().split())
for i in range(len(List)):
List[i] = List[i] ** 2
print(List)
numberlist()
#2
def numberlist2():
print("\n")
ui2 = input("Enter a list ... |
# -*- coding: utf-8 -*-
from app.tests import WebTestCase
class ModelTestCase(WebTestCase):
""" Parent of all models test classes """
pass
|
def ghostbusters(building):
return building.replace(' ', '') if ' ' in building else "You just wanted my autograph didn't you?"
|
#!/usr/bin/python
# -*- coding: UTF-8 -*-
""""
версия 1.0.1
общие утилиты
"""
import os
import logging
import numpy as np
import torch
import functools
import operator
import tqdm
from utils.data_structures import Config, PredictResultDescription
log = logging.getLogger(__name__)
def batch_predict_area_class(model,... |
from django.shortcuts import render
from rest_framework import viewsets
from .serializers import UserSerializer
from .models.site_application import *
class UserView(viewsets.ModelViewSet):
serializer_class = UserSerializer
queryset = RecordedUser.objects.all()
# Create your views here.
|
import numpy as np
import cv2
image=cv2.imread("./../si.jpg",1)
imageinfo = image.shape
height = imageinfo[0]
width = imageinfo[1]
matSrc = np.float32([[0,0],[0,height-1],[width-1,0]])
matDst = np.float32([[100,50],[300,height+100],[width+300,300]])
matAffine = cv2.getAffineTransform(matSrc,matDst)
print(matAffine)
ds... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Filename: step03_run_preliminary_regression_with_count_year_control
# @Date: 2020/3/12
# @Author: Mark Wang
# @Email: wangyouan@gamil.com
"""
python -m ConstructRegressionFile.Stata.step03_run_preliminary_regression_with_count_year_control
"""
import os
from Constant... |
from _typeshed import Incomplete
from collections.abc import Generator
from networkx.algorithms.flow import edmonds_karp
default_flow_func = edmonds_karp
def all_node_cuts(
G, k: Incomplete | None = None, flow_func: Incomplete | None = None
) -> Generator[Incomplete, None, None]: ...
|
import pymongo
from tqdm import tqdm
import copy
import os
from utils import *
if __name__ == '__main__':
config = Config()
data = getData(config.db, config.data_dir+'/data0.pkl', restore=True, save=True)
data = delRepetition(dataset=data, save_dir=config.data_dir+'/data1_unique.pkl', restore=True, save=T... |
"""clangparser - use clang to get preprocess a source code."""
import logging
import os
import collections
from clang.cindex import Index, TranslationUnit
from clang.cindex import TypeKind
from ctypeslib.codegen import cursorhandler
from ctypeslib.codegen import typedesc
from ctypeslib.codegen import typehandler
fro... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import redirect
from .models import Post
from django.contrib.auth.models import User
from django.utils import timezone
from django.shortcuts import render, get_object_or_404
from .forms import PostForm
import re
import string
import c... |
from typing import Set
from argsolverdd.common.atom import Atom
from argsolverdd.common.misc import NameDict
class Rule:
def __init__(self, name: str, premises: Set[Atom], conclusions: Atom, strict: bool):
self.name = name
self.premises = premises
self.conclusions = conclusions
se... |
# This file is part of beets.
# Copyright 2016, Bruno Cauet.
#
# 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, mod... |
import streamlit as st
import pandas as pd
import torch
import pytorch_model_summary as pms
from utils import CompTwo
from st_utils import load_model_v2, load_model_v3, load_model_v4, load_model_v5
st.set_page_config(layout="wide")
@st.cache()
def get_bias(model, class_ref):
bias = model.anime_bias.weight.sque... |
import re
def validate_name(string):
USER_RE = re.compile(r"^[a-zA-Z0-9_-]{3,20}$")
if USER_RE.match(string):
return True
return False
def validate_password(string):
USER_RE = re.compile(r"^.{3,20}$")
if USER_RE.match(string):
return True
return False
def validate_email(string... |
# coding: utf-8
"""Base classes for content scraping / visiting."""
from __future__ import print_function, unicode_literals
from parsimonious.nodes import NodeVisitor
from .data import Data
from .issues import ISSUES
class Recorder(object):
"""Records information in HTML or parsed HTML."""
def initialize_t... |
from ..extensions import marshmallow
from .answer import AnswerSchema
from marshmallow import fields
class UserAnswerSchema(marshmallow.Schema):
id = fields.Str()
answers = fields.Nested(AnswerSchema, many=True, exclude=[u'updated' , u'user']) |
"""
Base class of all configurators, must be extended.
"""
class UConfiguratorBase(object):
def getParams(self):
"""
Dictionary with known variables, need to be overridden.
"""
pass
def run(self, options, config, section, params):
"""
Needs to be o... |
"""
La idea es crear un script que tenga una funcion que me de Rc'\D' y R0'/D'
dandole como entrada beta, para toda i posible. Luego, dar un intervalo para
Rc/Ro y para R0/D y de la salida que me dio ver cuales valores de i dan un R0
y Rc que caigan en el intervalo, y guardar esos valores de i en un archivo, y
graf... |
# Copyright (C) 2014-2016 Cuckoo Foundation.
# This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org
# See the file 'docs/LICENSE' for copying permission.
# Originally contributed by Check Point Software Technologies, Ltd.
import ConfigParser
class Config:
def __init__(self, cfg):
"""@param c... |
import logging.config
from django.utils.log import DEFAULT_LOGGING
LOGGING_CONFIG = None
DEFAULT_LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'console': {
'format': '%(asctime)s %(name)-12s %(funcName)s %(levelname)-8s %(message)s',
},
'd... |
# Stream limited number of tweets, filter them (language,location, etc) #
# Passes filtered tweets to sentiment.py #
import setup
import csv
import json
import tweepy
from tweepy import StreamListener
class Streamer(StreamListener):
def __init__(self):
super().__init__()
self.counter = 0
... |
# name: Breann Nielsen
# date: 12/4/2020
# description: text-based adventure game
# Global imports
import random
import sys
import time
def print1by1(text, delay=0.0001):
for c in text:
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(delay)
print
def displayIntro():
... |
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
#
# Find the sum of all the multiples of 3 or 5 below 1000.
def findmultiplessum (lower, upper):
sumval=0
for i in range (lower, upper):
if i%3==0 or i%5==0:
sumval+=i
return(sum... |
# -*- mode: python -*-
block_cipher = None
# windows cmd:
# pyinstaller --clean -y musclex_win32.spec 2>&1 | findstr "..*" | findstr /v "api-ms-win"
a = Analysis(['musclex\\main.py'],
pathex=['.'],
binaries=[],
datas=[('musclex\\tests\\testImages', 'testImages'),('musclex\\test... |
# -*- coding: utf-8 -*-
"""
##############################################################################
The calculation of 3D RDF descriptors. You can get 180 molecular
decriptors. You can freely use and distribute it. If you hava
any problem, you could contact with us timely!
Authors: Dongsheng Cao and Yizeng... |
questions = {
"strong": "Do ye like yer drinks strong?",
"salty": "Do ye like it with a salty tang?",
"bitter": "Are ye a lubber who likes it bitter?",
"sweet": "Would ye like a bit of sweetness with yer poison?",
"fruity": "Are ye one for a fruity finish?",
}
ingredients = {
"strong": ["glug o... |
import logging
logger = logging.getLogger(__name__)
# noinspection PyUnresolvedReferences
import logging
logger = logging.getLogger(__name__)
from django.core.urlresolvers import reverse
from django.shortcuts import get_object_or_404
from django.http import HttpResponse
from django.views.generic import (
ListView... |
import julia
import timeit
from functools import partial
julia_large = partial(julia.julia_set,2048,1536)
print(timeit.timeit(julia_large,number=1)) |
from backbone import ResNet2015
from backbone import RegNet2020
from backbone import effnet
NET_LUT = {
'resnet': ResNet2015.ResNet,
'regnet': RegNet2020.RegNet,
'resnext': RegNet2020.AnyNet,
'effnet': effnet.EffNet,
}
def load_regnet_weight(model,pretrain_path,sub_name)... |
'''
Copyright (c) 2020 Aria-K-Alethia@github.com
Description:
train and exp code
Licence:
MIT
THE USER OF THIS CODE AGREES TO ASSUME ALL LIABILITY FOR THE USE OF THIS CODE.
Any use of this code should display all the info above.
'''
from __future__ import print_function
import argpa... |
import unittest
from katas.kyu_8.did_she_say_hello import validate_hello
class ValidateHelloTestCase(unittest.TestCase):
def test_true(self):
self.assertTrue(validate_hello('hello'))
def test_true_2(self):
self.assertTrue(validate_hello('ciao bella!'))
def test_true_3(self):
sel... |
import pytest
from ethereum.tools.tester import TransactionFailed
from plasma_core.constants import NULL_ADDRESS, NULL_ADDRESS_HEX, MIN_EXIT_PERIOD, NULL_SIGNATURE
from plasma_core.transaction import Transaction
from plasma_core.utils.transactions import decode_utxo_id
def test_challenge_standard_exit_valid_spend_sho... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2017-02-07 22:31
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('medecin', '0002_patient_affectation'),
]
operations = [
migrations.AlterFie... |
#!/usr/bin/env python
#
# Copyright (c) 2019 Opticks Team. All Rights Reserved.
#
# This file is part of Opticks
# (see https://bitbucket.org/simoncblyth/opticks).
#
# 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... |
def isBinary(n):
num = str(n)
res = True
for pos, bit in enumerate(num):
if bit != '0' and bit != '1':
res = False
return res
def toDecimal(num):
pot = len(num) - 1
soma = 0
for pos in range(0, len(num)):
soma += (int(num[pos]) * (2 ** pot))
pot -= 1
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# raiz_quadrada_recursiva.py
#
# Copyright 2015 Cristian <cristian@cristian>
#
"""
4. Calcular a raiz quadrada de um número n com tolerância máxima t. (pesquise a definição de raiz
quadrada)
"""
def raiz(n, t):
if abs(n**2 - t) <= 0.0001:
return n
else:
a0 =... |
# Generated by Django 3.2.5 on 2021-07-27 22:32
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Customer',
fields=[
... |
"""Implementation of the server-side open-tracing interceptor."""
import sys
import logging
import re
import grpcext
import opentracing
def _add_peer_tags(peer_str, tags):
ipv4_re = r"ipv4:(?P<address>.+):(?P<port>\d+)"
match = re.match(ipv4_re, peer_str)
if match:
tags['peer.ipv4'] = match.group('address... |
import requests
import json
from .api_results import *
class BaseFacade(object):
baseURL = ""
@classmethod
def make_get_call(cls, url, result_type):
response = requests.get(cls.baseURL + url)
# print(response.json())
json_str = json.dumps(response.json(), default=lambda o: o.__... |
from ..FeatureExtractor import ContextFeatureExtractor
class closest_in_light(ContextFeatureExtractor):
"""distance_in_arcmin_to_nearest_galaxy"""
active = True
extname = 'closest_in_light' #extractor's name
light_cutoff = 4.0 ## dont report anything farther away than this
... |
import ConfigParser
import io
# default config as string
def_config = """
[seed]
iseed = 1234
wseed = 4321
pseed = 4321
[netsyn]
NMAMREE = 0.1
NMAMREI = 0.1
mGLURR = 7.5
GB2R = 7.5
rdmsec = 1
nmfracca = 0.13
[chan]
ihginc = 2.0
iark2fctr = 1.0
iark4 = 0.008
erevh = -30.0
h_lambda = 325.0
h_gbar = 0.0025
fs_h_gbar = 0.... |
"""Read and combine zone logs into single dataframe."""
import pandas as pd
import numpy as np
import os
class file_operations(object):
"""
Read in zone character confidence and content files and join them as a single
file in a Pandas dataframe. Perform simple math to develop confidence data about
pa... |
# Generated by Django 3.2.5 on 2021-07-24 06:02
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... |
from select_factor import get_factors
from mylib import get_data
from mylib import get_data_fromDB #从数据库中获取数据
from mylib import train_test_split
from label_generator import generate_label
from mltool import method
from sklearn.metrics import classification_report
import numpy as np
def train(high,low,dope... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/7/23 8:04 PM
# @Author : ZhangHao
# @File : config.py
# @Desc : 通用配置
import os
import feature_generator.base_generator
import feature_generator.card_qualification_data
# 原始训练数据总目录
origin_data = "data/origin_data"
# 处理原始数据 生成特征的类
data_feature_generator... |
#!/usr/bin/python
##############
## Make Plots
##############
########################
# Libraries and Includes
########################
# Python System Modules
import os,sys,glob
import logging
import array
# Python Paths
# Python Math Modules
import array
from math import sqrt,fabs,sin,pow
# ROOT Modules
from R... |
def alex_mistakes(number_of_katas, time_limit):
req_time = 5
sets = 0
remaining = time_limit - number_of_katas * 6
while remaining>=req_time:
remaining-=req_time
req_time*=2
sets+=1
return sets
'''
Alex is transitioning from website design to coding and wants to sharpen hi... |
"""
Created by Alex Wang on 2018-04
LBP常用使用方法
(1)首先将检测窗口划分为16×16的小区域(cell);
(2)对于每个cell中的一个像素,将相邻的8个像素的灰度值与其进行比较,若周围像素值大于中心像素值,则该像素点的位置被标记为1,否则为0。这样,3*3邻域内的8个点经比较可产生8位二进制数,即得到该窗口中心像素点的LBP值;
(3)然后计算每个cell的直方图,即每个数字(假定是十进制数LBP值)出现的频率;然后对该直方图进行归一化处理。
(4)最后将得到的每个cell的统计直方图进行连接成为一个特征向量,也就是整幅图的LBP纹理特征向量;
(5)然后便可利用SVM或者其他机器学... |
from flask import Flask, request, send_file
from google_api import Vision
from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub import PubNub
import os
from PIL import Image, ImageDraw
def publish_callback(result, status):
print(result, status)
# Handle PNPublishResult and PNStatus
app = Flask(... |
from typing import List, Dict
from fractions import Fraction
power_mod = {0: 1.0, 1: 1.25, 2: 1.4, 3: 1.5, 4: 1.6, 5: 1.7, 6: 1.8}
def calc_attack(attack_stat: int, gear: int, sync_grid_additions: int):
atk = attack_stat + gear + sync_grid_additions
return atk
def cal_defence(
base_move_dmg: int,
e... |
import datetime
from flask import request, jsonify
from init import create_app
from models import Player, Country, Club, db
from views import player_json, club_json, country_json
app = create_app()
@app.route('/players', methods=['GET'])
def get_players():
players = Player.query.all()
all_players = []
fo... |
import sys
import os
# Make sure we're using the right python. Assume we're running out of the venv.
INTERP = os.path.join(os.getcwd(), 'bin', 'python')
if sys.executable != INTERP:
os.execl(INTERP, INTERP, *sys.argv)
sys.path.append(os.getcwd())
import configparser
import importlib
config = configparser.Con... |
import argparse
import os.path
import logging
import sys
import django
from django.core.management import load_command_class, find_commands, \
BaseCommand, CommandError
from django.apps import apps
logger = logging.getLogger("backathon.main")
def setup():
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "back... |
from __future__ import unicode_literals
from django.shortcuts import render, HttpResponse, redirect
from django.core.urlresolvers import reverse
from .models import User, Message, Comment
from .forms import Register, Message_Form, Comment_Form
from django.contrib import messages
import bcrypt
# Rendering pages below.
... |
#!/usr/bin/env python
"""
pyjld.phidgets.bonjour.bus
"""
__author__ = "Jean-Lou Dupont"
__email = "python (at) jldupont.com"
__fileid = "$Id: bus.py 69 2009-04-17 18:49:17Z jeanlou.dupont $"
__all__ = ['busSignals',]
import dbus, dbus.service
class busSignals(dbus.service.Object):
"""
Dbus signa... |
import paramiko
from termcolor import colored
import time
def sshConnection(user, password):
host = "172.16.0.10"
port = 22
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host, port, user, password)
|
#!/usr/bin/env python
import requests
import re
import urllib.parse as urlparse
import subprocess
import colorama
from colorama import Fore, Back, Style
colorama.init(autoreset=True)
try:
unknown = input(Fore.WHITE + "\n Enter the Website (target url): ")
target_url = "https://" + unknown
target_links = [... |
import models
from Crypto.Cipher import AES
def uid_check(uid):
if models.User.select().where(models.User.username == uid).exists():
uid = models.User.get(models.User.username == uid).uid
elif models.User.select().where(models.User.uid == uid).exists():
pass
else:
raise models.Does... |
import pygame,sys
from pygame.locals import *
pygame.init()
new_surface = pygame.display.set_mode((600,600))
imgSurface = pygame.image.load(Knot_Class.jpg)
new_surface.blit(imgSurface,(0,0))
|
import numpy
#TOIMII
def isInTriangle(x,y,x1,y1,x2,y2,x3,y3):
sqx1 = x1*x1
sqx2 = x2*x2
sqx3 = x3*x3
sqy1 = y1*y1
sqy2 = y2*y2
sqy3 = y3*y3
#if 1.41*1.41 > (x*x+y*y):
#time.sleep(10)
return 1.41*1.41 > (x*x+y*y)
#TESTAA
def ray_hits_triangle(screenpoint,triangle):
tri = triangle
I = screenp... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 7 20:19:15 2018
@author: user
資料加總
"""
with open("read.txt","r",encoding="utf-8") as fd:
data=fd.read()
d_sp=data.split(" ")
d_li=list(map(eval,d_sp))
print(sum(d_li) ) |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import time
import os
import sys
import urllib
import urllib2
import logging
DOWNLOAD_LIST_FNAME = 'download_list'
DOWNLOAD_TAG_FNAME = 'finish'
def generate_job(file_path):
"""
Arguments:
- `file_path`:
"""
with open(DOWNLOAD_LIST_FNAME, 'w') as f:... |
from mongoengine import *
from threads import Thread
class Board(Document):
"""
A Board object represents a list of topics.
"""
name = StringField()
board_id = StringField()
description = StringField()
topics = ListField(ReferenceField(Thread, dbref=False)) |
import logging
from datetime import datetime, timedelta
import time
from canvas import Canvas
# #############################################################################
# Class: Clock
# Draws the date and/or time on a canvases, and then those canvases to the
# Matrix (matrixobject).
# positioninmatrix is the pos... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
#Q: [b, n, d_k]
#K: [k, d_k]
#V: [k, d_v]
#TODO / care: a@b and a.bmm(b) come out the same right?
def scaled_dotproduct_attention(Q,K,V, apply_mask=False):
assert Q.size(-1)==K.size(-1) and K.size(-2)==V.size(-2)
batch_size, ... |
from appconfig import systemd
def test_enable(app, testdir, mocker):
files = mocker.Mock(upload_template=mocker.Mock())
mocker.patch('appconfig.systemd.files', files)
mocker.patch('appconfig.systemd.sudo')
systemd.enable(app, testdir / 'systemd')
assert files.upload_template.call_count == 3
|
#!/usr/bin/python
import feedparser
import zlib
f = open('http://www.torrentday.com/torrents/rss?download;7;u=428237;tp=887f3b1d10049f24d6fddf65d2139b22', 'rb')
decompressed_data=zlib.decompress(f.read(), 16+zlib.MAX_WBITS)
print decompressed_data
#feed = feedparser.parse( decompressed_data )
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Script to parse Windows Jump List files:
* .automaticDestinations-ms
* .customDestinations-ms
"""
import argparse
import logging
import sys
import pyolecf
from dtformats import file_system
from dtformats import jump_list
from dtformats import output_writers
try:
fr... |
for num in range (1500,20001):
if num % 7 == 0:
print (num)
elif num % 5 == 0:
print (num) |
# Framework using SQLite.
import sqlite3
active = 'A'
inactive = 'I'
status = 'Status'
connection = sqlite3.connect('Ram.db')
generalTable = connection.execute('select * from general_configurations')
menuConfigurations = []
def getGeneralConfigurationValue(configurationkey):
return generalConfigurations[configurati... |
from nameko.rpc import rpc
from model_provider import Agent
class ChitChat(object):
name = 'chitchat'
a = Agent()
@rpc
def predict(self, phrase=None, session=0):
with self.a['graph'].as_default():
answer = self.a['agent'].send(msg=phrase, agent_id=session)
print("Ses... |
# coding=utf-8
from var_dump import var_dump as vd
import const
from pprint import pprint as pp
import reader # CSV Files
import os.path
class Converter:
'''
Conver specific files into format Select into ...
'''
def __init__(self, file_name, file_reader, file_writer):
self.file_name = fi... |
boardList = [[[4], [2], [], [], [], [3], [8], [], []],
[[], [], [3], [4], [], [], [2], [7], []],
[[], [8], [], [], [2], [5], [9], [3], [4]],
[[5], [], [1], [], [4], [], [], [], []],
[[], [], [], [5], [], [7], [], [], []],
[[], [], [], [], [6], [], [1], [], [3]],
[[3], [1]... |
import random
# noinspection PyUnresolvedReferences
from six.moves import range
def partition_string(s, segments):
"""
Partition a string into a number of segments. If the given number of
segments does not divide evenly into the string's length, extra characters
are added to the leading segments in o... |
# -*- coding: utf-8 -*-
import re
import sys
import os
import pickle
import numpy as np
from collections import Counter
from os import listdir
from os.path import isfile, join
##################################################################################################################
def hasNumbers(inputString):... |
#!/usr/bin/env python
#-*-coding:utf-8-*-
# @File:User_CF.py
# @Author: Michael.liu
# @Date:2020/6/19 13:37
# @Desc: this code is ....
import argparse
from pyspark.sql import SparkSession
from pyspark import SparkConf, SparkContext
import pyspark.sql.types as T
def UserCF():
print("...begin...")
if __name__ == ... |
# -*- coding: utf8 -*-
#!env python
import subprocess
import os
import codecs
import re
import datetime
import time
now = str(int(time.mktime(datetime.datetime.now().timetuple())))
#压缩html
targets = ['index', 'top', 'cat', 'search','subject']
for target in targets:
file = os.path.abspath(tar... |
from selenium.webdriver.common.by import By
class HomePage:
def __init__(self, driver):
self.driver = driver
Search = (By.XPATH, "//*[@type='search']")
AddToCart = (By.XPATH, "//button[text()='ADD TO CART']")
Cart_Icon = (By.XPATH, "//*[@class='cart-icon']/img")
Proceed_ToCheckOut = (By.... |
from kivy.lang import Builder
from kivy.properties import ObjectProperty
from kivymd.app import MDApp
from kivymd.uix.boxlayout import MDBoxLayout
KV = '''
<ContentNavigationDrawer>:
ScrollView:
MDList:
OneLineListItem:
text: "Список учеников"
on_press:
... |
import _plotly_utils.basevalidators
class BoxsValidator(_plotly_utils.basevalidators.CompoundArrayValidator):
def __init__(
self, plotly_name='box', parent_name='layout.template.data', **kwargs
):
super(BoxsValidator, self).__init__(
plotly_name=plotly_name,
parent_nam... |
# import time
# import os
# import automationhat
# import Adafruit_DHT
# from balena import Balena
# import json
# import paho.mqtt.client as mqtt
#
# class PlantSaver:
#
# def __init__(self):
#
# self.client = mqtt.Client("1")
#
# # Variables
# self.dht_sensor = ... |
# encoding=utf8
# \xc3\x93 -> O ; \xc2\xa0 -> "" ; \xc3\x91 -> Ñ
# from procesos.bancolombia_castigada import ejecutar_query
from google.cloud import bigquery
def makeTrans(listaHeader):
standarizedHeaders = []
my_query = ''' SELECT *
FROM `contento-bi.MetLife.base_campos_matriculados_bd_... |
"""empty message
Revision ID: b5a45440b11d
Revises: 44ac09b089b6
Create Date: 2020-03-24 11:52:57.802979
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = 'b5a45440b11d'
down_revision = '44ac09b089b6'
branch_labels = None
depe... |
# Generated by Django 2.2.5 on 2019-10-03 19:32
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0003_user_is_staff'),
]
operations = [
migrations.RemoveField(
model_name='user',
name='is... |
# Astrocrash 1
# Get asteroids moving on the screen
import random, math
from livewires import games, color
games.init(screen_width = 640, screen_height = 480, fps = 50)
class Wrapper(games.Sprite):
"""A sprite that wraps around the screen"""
def update(self):
"""Wrap sprite around screen."""
... |
from UnitTesting.page_objects.base_page_object import base_page_object
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
import random
class sign_up(base_page_object):
def __init__(self, w... |
x=int(input("x= "))
y=int(input("y= "))
if ((x>0)and(y>0)or(x<0)and(y>0)or(x<0)and(y<0)or(x>0)and(y<0)):
print(3)
elif((x>0)and(y==0)or(x<0)and(y==0)):
print(1)
elif((x==0)and(y>0)or(x==0)and(y<0)):
print(2)
else:
print(0) |
import sys, os, argparse
from Midi import MidiEvents
from Sender import Sender
MILLI_SEC = 0.001
MICRO_SEC = 0.000001
# ループ間隔のデフォルト値[sec]
DEFAULT_INTERVAL = 2.0 * MILLI_SEC
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--file', help = 'MIDI file path (*.mid)', required = True... |
from tkinter import ttk ,messagebox
import os , json , tkinter as tk
def insert_into_list_box():
course_name = string_course.get()
if course_name and course_name not in listbox.get(0,'end'):
listbox.insert(tk.END, course_name)
e_course.delete(0, 'end')
else:
messagebox.showinfo("Add... |
import argparse,collections,copy,datetime,os,pandas,shutil,sys,time
import Wrangler
# Based on NetworkWrangler\scripts\build_network.py
#
# Builds 3 futures networks. Use with net_spec_horizon.py
#
import build_network_mtc
###############################################################################
if __name__... |
# -*- coding: utf-8 -*-
# @Author: zjx
# @Date : 2018/3/20
class ValidationError(ValueError):
pass
|
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 6 19:36:00 2018
@author: PPAGACZ
"""
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 6 18:15:24 2018
@author: PPAGACZ
"""
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 6 13:01:27 2018
@author: PPAGACZ
"""
import pytest
from FitARMAFilter import *
from unittest imp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.