text stringlengths 38 1.54M |
|---|
# -*- coding: utf-8 -*-
import pandas as pd
from flask import Flask, render_template, request
import sys
app = Flask(__name__) # create an app instance
data = pd.read_csv("https://raw.githubusercontent.com/joe608939/test/master/hklit_test.csv")
author_data = pd.read_csv('https://raw.githubus... |
import threading
import time
#You need to have a function, threads execute a function
def sleeper(n,name):
print("Hi i am{}. Going to sleep for 5 seconds \n".format(name))
time.sleep(n)
print('{} has woken up from sleep \n '.format(name))
threads_list = [] #holds out threads after we initialize them
start = tim... |
# uncompyle6 version 3.3.5
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.7.3 (default, Apr 24 2019, 15:29:51) [MSC v.1915 64 bit (AMD64)]
# Embedded file name: c:\Jenkins\live\output\win_64_static\Release\python-bundle\MIDI Remote Scripts\Push2\auto_filter.py
# Compiled at: 2019-04-23 16:19:13
from __future... |
"""
You shouldn't need to modify this file, but if you are making submodules (nested folders + files) you
will need to include a __init__.py file that has relative import statements.
Example
-------
If you have a submodule folder called /foo, with a module inside called bar.py you will need to include
a __init... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
class AlipayCommerceEcShopCreateResponse(AlipayResponse):
def __init__(self):
super(AlipayCommerceEcShopCreateResponse, self).__init__()
self._ec_shop_id = None
@prope... |
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... |
import torchvision
import torchvision.datasets as dset
import torchvision.transforms as transforms
from torch.utils.data import DataLoader,Dataset
import matplotlib.pyplot as plt
import torchvision.utils
import numpy as np
import random
from PIL import Image
import torch
from torch.autograd import Variable
import PIL.... |
countries = {
'0': '🇷🇺 Россия',
'1': '🇺🇦 Украина',
'2': '🇰🇿 Казахстан',
'51': '🇧🇾 Беларусь',
'3': '🇨🇳 Китай',
'15': '🇵🇱 Польша',
'29': '🇷🇸 Сербия',
'34': '🇪🇪 Эстония',
'32': '🇷🇴 Румыния',
'43': '🇩🇪 Германия',
'44': '🇱🇹 Литва',
... |
# O(nm) time | O(nm) space
def number_of_ways(n, m):
def compute_ways_to_xy(x, y):
if x == y == 0:
return 1
if number_of_ways[x][y] == 0:
ways_top = 0 if x == 0 else compute_ways_to_xy(x-1, y)
ways_left = 0 if y == 0 else compute_ways_to_xy(x, y-1)
... |
#! /usr/bin/env python
import rospy
import actionlib
from geometry_msgs.msg import Twist, Vector3, PoseStamped
# Uses Test.action from actionlib as action messages
from actionlib.msg import TestFeedback, TestResult, TestAction
cnt = 0
posX_0 = 0
posY_0 = 0
posX = 0
posY = 0
movingUp = True
def stopDrone() :
prin... |
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 05 07:21:42 2015
@author: jeppley
"""
import pandas as pd
import os as os
from sklearn import preprocessing
from sklearn.preprocessing import Imputer
from sklearn import ensemble
import numpy
from sklearn.feature_selection import RFECV
from sklearn.cross_validation impor... |
import pybullet as p
import pybullet_data
import time
import math
import numpy as np
import time
from scipy.spatial.transform import Rotation as R
import scipy.stats
import typing as T
import collections
from sim_objects import Arm, Bottle
SimResults = collections.namedtuple(
'SimResults', ['is_fallen', 'is_colli... |
import math
import matplotlib.pyplot as plt
import numpy as np
def makeODE(delta):
ode = lambda sigma, theta: delta * math.exp(theta) - theta
return ode
def makeInverseODE(delta):
ode = lambda theta, sigma: 1/(delta * math.exp(theta) - theta)
return ode
def rk4(f, initX, initY, h, stop, t... |
import random
op = ["+", "-", "*", "/", "p", "%", "!", "s", "r"]
a = input("the first number =\n")
def factorial(a):
a = int(a)
r = a
for i in range(1, a):
r = r * i
return(r)
try:
a = float(a)
except:
while type(a) == str:
a = input("please insert the first number in numb... |
bills = [500, 200, 100, 50, 20, 10, 5, 2, 1]
def find_adequate_bill(num):
for i in range(9):
if num > bills[i]:
return i
return 8
def pay_with_bills_greedy(num):
change = [0, 0, 0, 0, 0, 0, 0, 0, 0]
while num > 0:
bill = int(find_adequate_bill(num))
change[bill] +... |
import math
listofprimes=[0]*26
smalllistofprimes=[0]*26
smalllistofnos=[0]*10
listofalphabets=[None]*62
for i in range(26):
listofalphabets[i] = chr(65+i)
j=0
for i in range(26,52,1):
listofalphabets[i] = chr(97+j)
j=j+1
j=0
for i in range(52,62,1):
listofalphabets[i] = chr(48+j)
j=... |
#!/usr/bin/env python3
import numpy as np
result = []
for n in [16, 32, 48, 64, 96]:
row = [n]
for m in [3, 4, 5]:
name = "%02d_%02d" % (m, n)
for i in range(m*m*m):
tmp = []
with open("test004/%s/log%06d.txt" % (name, i)) as fh:
for line in fh:
... |
# from rest_framework.decorators import api_view
# from rest_framework.generics import GenericAPIView, ListAPIView, CreateAPIView, RetrieveAPIView, UpdateAPIView, DestroyAPIView, ListCreateAPIView, RetrieveUpdateAPIView, RetrieveDestroyAPIView , RetrieveUpdateDestroyAPIView
# from rest_framework.mixins import ListModel... |
# Generated by Django 3.0.7 on 2020-07-09 12:55
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('app', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Pet',
fields=... |
vowels = ['a', 'e', 'i', 'o', 'u']
word = "iliketotravel"
vowel_dict = dict()
for letter in word:
if letter in vowels:
# if letter not in vowel_dict:
# vowel_dict[letter] = 1
# else:
# vowel_dict[letter] += 1
vowel_dict.setdefault(letter,0)
vowel_d... |
import requests,execjs,re
headers ={
"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3",
"Accept-Encoding":"gzip, deflate, br",
"Accept-Language":"zh-CN,zh;q=0.9",
"Cache-Control":"no-cache",
"Connection":"keep-alive",
"Host":"www.guazi.com... |
from sqlalchemy import create_engine
from sqlalchemy.ext.automap import automap_base
import datetime
import time
from datetime import timedelta
engine = create_engine('sqlite:///database.db', echo=True)
# engine = create_engine('postgresql://postgres:1sebaQuinta@localhost:5432/Gym', echo=True)
Base = automap_base()
B... |
# Functions for calibration of results
from __future__ import division, print_function
import sklearn.metrics as metrics
import numpy as np
import pickle
import keras
from sklearn.preprocessing import OneHotEncoder
from sklearn.metrics import log_loss
import sklearn.metrics as metrics
from scipy.stats import percentile... |
import pickle
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import itertools
import os
results = None
# matplotlib.rcParams.update({'font.size': 12})
color_list = plt.cm.tab10(np.linspace(0, 1, 10))
colors = {'lstm': color_list[0], 'pf_e2e': color_list[1... |
""" All functions necessary to create and return views """
from datetime import datetime
from math import floor, ceil
from statistics import mean
import json
import requests
from django.core.cache import cache
def get_start_and_end_date(site_id, api_key):
""" Returns the start and the end date of the data in Sola... |
file = open("infoDB.txt", 'w')
boolean = True
detail_list = ["Name : ", "Family : ", "Age : ", "Gender : ", "BirthDate : ", "Nationality : ", "National ID : "]
input_list = []
info_list = []
while boolean:
for i in range(len(detail_list)):
info = detail_list[i] + input(detail_list[i])
file... |
no1=int(input("Enter number to show number is prime or not"))
flag=0
print(isprime(11))
for i in range (2,no1):
if(i%no1!=0):
flag=1
if (flag==1):
print("not Prime number")
else:
print(" Prime Number")
|
TYPE = "schema:PostalAddress"
class PostalAddress:
def __init__(self,er_event):
self._type = TYPE
#... |
from model import DrivetrainModel
from model.motors import _775pro
from optimizer import Optimizer
if __name__ == "__main__":
model = DrivetrainModel(_775pro(8), gear_ratio=26, robot_mass=68, wheel_diameter=6 * 0.0254,
motor_voltage_limit=12, motor_current_limit=30, max_dist=6)
op... |
def main():
diagSum = 1
increment = 2
lastNumber = 1
while increment < 1001:
for i in range(4):
lastNumber += increment
diagSum += lastNumber
increment += 2
print(diagSum)
main()
|
from django import forms
# from django.contrib.auth.models import User
from . models import SignupUser
from django.core.validators import validate_email
class userform(forms.Form):
name = forms.CharField(widget=forms.TextInput(attrs={'class': 'input--style-3 cw', 'placeholder': 'Name'}), required=True, max_length=... |
"""
Created on Fri Jan 13 2017 09:00:00
@author: Peter Harris, NPL\MM
@author: Sam Hunt, NPL\ENV
"""
'''___Python Modules____'''
from copy import deepcopy
from numpy import array, append, zeros
from numpy import sum as npsum
'''___Harmonisation Modules___'''
from harm_data_reader import HarmData
fro... |
#!/bin/python3
import sys
import os
import os.path as osp
from PIL import Image
from torchvision import transforms
import argparse
import logging
from plan2scene.config_manager import ConfigManager
from plan2scene.texture_gen.custom_transforms.random_crop import RandomResizedCropAndDropAlpha
if __name__ == "__main__"... |
import sys
import time
import argparse
from PIL import Image
# from naoqi import ALProxy
# from naoqi import ALBroker
from naoqi import ALModule
from nao_class import NaoWrapper
IP = "10.125.200.124"
data = "nao_data.csv"
# create nao object
my_nao = NaoWrapper(IP, data)
# deactivate fall manager
my_nao.FallManage... |
class Plane():
#constructor
def __init__(self,n='',nr=0,arc='',nrs=0,dest='',lps=[]):
self.__name=n
self.__number=nr
self.__airline_company=arc
self.__number_seats=nrs
self.__destination=dest
self.__list_passengers=lps[:]
#... |
# Generated by Django 2.1.3 on 2018-12-11 12:40
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('blog', '0003_post_thumbnail'),
]
operations = [
migrations.AlterModelOptions(
name='post',
options={'permissions': (('view_o... |
from datetime import datetime
from typing import Optional
from uuid import UUID, uuid4
import sqlalchemy as sa
import sqlalchemy.dialects.postgresql as pg
from oasst_shared.utils import utcnow
from sqlalchemy import false
from sqlmodel import Field, SQLModel
from .payload_column_type import PayloadContainer, payload_... |
# Test Name Description
# A_BX_UART_AT&K_0005 To check if hardware flow control working
#
# Requirement
# 1 Euler module
#
# Author: ptnlam
#
# Jira ticket:
#-----------------------------------------------------------------------------------------------... |
import puzzle as game
from copy import deepcopy,copy
from direction import Direction,Coordinate
from board import print_board
from main import clear
from time import sleep
class Node:
def __init__(self,board : list, parent = None):
self.state = board
self.parent = parent
self.g_value = 0
... |
from django.views.generic import ListView, DetailView
from .models import Order
from django.http import Http404
from django.contrib.auth.mixins import LoginRequiredMixin
# Create your views here.
class OrderListView(LoginRequiredMixin, ListView):
def get_queryset(self):
return Order.objects.by_request(se... |
import logging
from cycler import cycler
from matplotlib.colors import LogNorm, rgb2hex
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
import numpy as np
from itertools import chain
logger = logging.getLogger('pyrain')
STANDARD = {'outline': {'file': 'resources/arena_outline.png',
... |
def reverse(arr):
left, right = 0, 4
while(left < right):
swap(arr,left,right)
left += 1
right -= 1
return arr
def swap(arr, left, right):
temp = arr[left]
arr[left] = arr[right]
arr[right] = temp
arr = [1,2,3,4,5]
print(reverse(arr)) |
from setuptools import setup, find_packages
setup(
name="cryptpad_auto",
version="0.0.1",
author="Liam Cripwell",
description="A tool to automate CryptPad form generation from data.",
packages=find_packages(),
include_package_data=True,
)
|
import numpy as np
import sys
import unittest
sys.path.append('..')
from src import minimize
class testMinimize(unittest.TestCase):
def test_minimize(self):
n, p = 20, 4
A = np.random.rand(n, n)
A = (A + A.T)/2
def f1(y):
return np.sum(np.diag(np.dot(np.dot(y.T, A),... |
import functools
import pytest
def check_depends(depends):
try:
for dep in depends:
dep()
except Exception as e:
return dep
else:
return True
def pytest_depend(depends):
def pytest_depend_decorator(func):
stat = check_depends(depends)
if stat is True... |
import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QLabel, QGridLayout, QWidget, QRadioButton, QButtonGroup
from PyQt5.QtCore import QSize
class Questionnaire(QWidget):
def __init__(self, parent):
super(Questionnaire, self).__init__(parent)
self.layout = QGridLa... |
'''
Created on Mar 30, 2020
@author: zen
'''
#if __name__ == '__main__':
RMB = [200, 100, 20, 10, 5, 1]
NUM = 6
X = 628
count = 0
for i in range(NUM):
use = X // RMB[i]
count += use
X = X - RMB[i] * use
print('需要面额为{} 的 {} 张'.format(RMB[i],use))
print('剩余需要支付金额{}'.format(X))
print(count) |
import jsonlines
import argparse
from tqdm import tqdm
parser = argparse.ArgumentParser()
parser.add_argument("--corpus", type=str, default="data/corpus.jsonl")
parser.add_argument("--claims", type=str, required=True)
parser.add_argument("--retrieval", type=str, required=True)
parser.add_argument("--t5_input_ids", ty... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 14 12:59:36 2020
@author: Tushar Saxena
"""
#Find sum of numbers from different arrays closest to given sum
import time
a = [-1, 3,8, 2, 9, 5]
b = [4, 1, 2, 10, 5, 20]
c = 24 #given sum
summ = 0
diff = c
start = time.time()
x = 0
y = 0
for i in a:... |
from PySide6.QtWidgets import QApplication, QMainWindow
from PySide6.QtUiTools import QUiLoader
from qt_material import apply_stylesheet
extra = {
# Button colors
'danger': '#dc3545',
'warning': '#ffc107',
'success': '#17a2b8',
# Font
'font_family': 'monoespace',
'font_size': '14px',
... |
# include this gypi to include all the golden master slides.
{
'sources': [
'../gm/aaclip.cpp',
'../gm/aarectmodes.cpp',
'../gm/arithmode.cpp',
'../gm/bigmatrix.cpp',
'../gm/bitmapcopy.cpp',
'../gm/bitmapmatrix.cpp',
'../gm/bitmapfilters.cpp',
'../gm/bitmapscroll.cpp',
'../gm/blurs... |
# -*- coding: utf-8 -*-
class Dog(): # скобки пусты т.к. класс создается с нуля
# Dog это экземпляр класса
'''Простая модель собаки'''
# метод __init__ автоматически выполняется при создании каждого нового экземпляра на базе класса Dog
# метод __init__ с тремя параметрами self, name, age
# self ссылка на экзем... |
import pygame
class Enemy(pygame.sprite.Sprite):
def __init__(self, x, y, image, speed, bg_size, music):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image).convert_alpha()
self.rect = self.image.get_rect()
if self.rect.w > x:
self.rect.left, self.... |
class Assistant:
"""Class for simple calls for the UI
Attributes:
assistant_inst (AssistantV2): AssistantV2 object that will call the API
assistant_id (str): The user's assistant ID used for calling
session_id (str): The session ID created with the AssistantV2 object
intent (s... |
#写模式
fo =open("foo.txt","w")
fo.write("joinx test python io stream")
fo.close()
#读模式
fo=open("foo.txt","r+")
str=fo.readline(20)
print(str)
fo.close()
fo=open("foo.txt","r+")
str=fo.readline(3)
print("读取的字符",str)
posistion=fo.tell()
print("当前的文件读取的位置",posistion)
#将文件位置重新定位到文件开头
posistion=fo.seek(0,0)
str=fo.read(30)
p... |
from aiogram.types import Message
from aiogram.dispatcher.filters.builtin import CommandStart
from utils.utils import get_sticker_hello
from loader import dp
@dp.message_handler(CommandStart())
async def send_welcome(message: Message):
sticker = get_sticker_hello()
await message.answer_sticker(sticker)
a... |
from cotton.scm import SCM
from fabric import api as fab
from fabric.api import env
class Git(SCM):
def git(self, *commands):
commands = ' '.join(['git'] + list(commands))
fab.run(commands)
def checkout(self, repository, checkout_to, ref=None):
self.git('clone', repository, checkout... |
from contextlib import contextmanager
import logging
import os
from typing import NamedTuple
from flask import current_app, g
import psycopg2
from psycopg2.pool import ThreadedConnectionPool
from psycopg2.extras import RealDictCursor
pool = None
def setup():
global pool
DATABASE_URL = os.environ['DATABASE_URL']... |
class Puissance4:
'''Une partie de Puissance 4'''
SYMBOLES = ('.', '@', 'X', 'O', '+')
_JOUEURS_MIN = 2
_JOUEURS_MAX = 4
def __init__(self, largeur=7, hauteur=6, nb_joueurs=2):
'''Initialise une partie avec une grille vide.'''
if largeur < 7 or hauteur < 6:
... |
from MyMainPackage import some_main_script
from mymodule import my_func
from MyMainPackage.SubPackage import mysubscript
some_main_script.report_main()
mysubscript.sub_report()
my_func() |
import json
import time
from urllib import request as r
class GroupRequest():
def __init__(self, token, params, url):
self.token = token
self.params = params
self.base_url = url
self.headers = {"Content-Type": "application/json", "accept": "application/json"}
self.task = "... |
import unittest
from src.tools.lotto.euromillions import euromillions_analysis
class EuromillionsAnalysisTestCase(unittest.TestCase):
twenty_draws = [['1379', '08-Dec-2020', '1', '4', '21', '24', '46', '2', '12'],
['1378', '04-Dec-2020', '14', '20', '27', '34', '38', '1', '11'],
... |
import os
import json
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# try get custom settings
try:
with open(os.path.join(BASE_DIR, "sigec", "mysettings.json"), encoding='utf-8') as f:
USER_SETTINGS = json.loa... |
import os, re, argparse
import torch.optim as optim
import numpy as np
import pandas as pd
from gensim.models import Word2Vec
from tqdm import tqdm
from sklearn.utils import compute_class_weight
from DeepLineDP_model import *
from my_util import *
torch.manual_seed(0)
arg = argparse.ArgumentParser()
arg.add_ar... |
import uuid
import datetime
from managment.tasks import Tasks
from managment.instances_repository import InstancesRepository
class Instances(object):
def __init__(self):
self.instances_repository = InstancesRepository()
def get_all_instances(self):
return self.instances_repository.get_all_inst... |
import re
from pandas import concat
from .helpers.utils import collect_codes_and_names
from . import bcb, ipea
def get_series(*codes, start=None, end=None, **kwargs):
"""
Get multiple series from both BCB or IPEA.
Parameters
----------
codes : dict, str, int
Dictionary like {"name1": cod... |
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Usuario(User):
observacion = models.CharField(max_length=20, default="no especificado",null=False)
telefono = models.IntegerField(max_length=15,default=00,null=False)
domicilio = models.CharField(max... |
import os
import time
import torch
import torch.nn.functional
from torch import nn, Tensor
import torchvision.models as models
import math
class Model(nn.Module):
def __init__(self):
super().__init__()
# TODO: CODE BEGIN
self.resnet18 = models.resnet18(pretrained=True)
self.fc ... |
from klampt import *
from klampt import vectorops,so3,se3
from klampt import resource
import math
#import matrixops
DO_VISUALIZATION = 1
if DO_VISUALIZATION:
from klampt import vis
from klampt.model import coordinates
def point_fit_rotation_3d(apts,bpts):
"""Computes a 3x3 rotation matrix that rotates the... |
"""
bioBakery Workflows: tasks.dadatwo module
A collection of tasks for DADA2 workflow with 16s amplicon sequences
Copyright (c) 2017 Harvard School of Public Health
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to de... |
__author__ = "Silei Xiong"
import xml.etree.ElementTree as ET
import string
# from collections import namedtuple
# from urllib.request import urlopen
# from xml.etree.cElementTree import parse
import csv
def read_data(model):
with open('Icon_size_data_base.csv') as f:
f_csv = csv.reader(f, delimiter=',')
... |
def count_letters(frase):
dic_mio = {}
for let in frase:
if let in dic_mio:
dic_mio[let] += 1
else:
dic_mio[let] = 1
return dic_mio
|
#!/bin/python2.7
import sys
import subprocess
#TODO: Adding source folder
if len(sys.argv) != 3:
print("Srsly, you need 2 arguments or it won't work.")
print("Usage: python2.7 snekbackup.py [regex] [destination folder] ")
else:
subprocess.call("find / -type f -name " + '"' + sys.argv[1] + '"' + " -exec cp... |
# -*- coding: utf-8 -*-
# Copyright (C) 2010-2013 Mag. Christian Tanzer All rights reserved
# Glasauergasse 32, A--1130 Wien, Austria. tanzer@swing.co.at
# ****************************************************************************
# This module is part of the package GTW.OMP.Auth.
#
# This module is licensed under th... |
#! /usr/bin/env python3
import os
import sys
from functools import reduce
from itertools import combinations
from time import process_time
def main():
with open(os.path.join(sys.path[0], 'input.txt')) as f:
ids = [l.strip() for l in f.readlines()]
p1 = reduce(
lambda x, y: x * y,
[su... |
from random import randint
from data.dataloaders.bar_dataset import *
from data.dataloaders.bar_dataset_helpers import *
from MeasureVAE.measure_vae import MeasureVAE
from MeasureVAE.vae_trainer import VAETrainer
from sklearn.manifold import TSNE
from sklearn.decomposition import PCA
from sklearn.metrics import mutual_... |
#!/usr/bin/python3
from sys import argv
savejson = __import__('7-save_to_json_file').save_to_json_file
loadjson = __import__('8-load_from_json_file').load_from_json_file
filename = "add_item.json"
try:
newlist = loadjson(filename)
except FileNotFoundError:
newlist = []
for i, arg in enumerate(argv):
if i... |
"""ResourceSpec classes for elbv2 resources."""
from altimeter.aws.resource.resource_spec import AWSResourceSpec
class ELBV2ResourceSpec(AWSResourceSpec):
"""Abstract base for ResourceSpec classes for elbv2 resources."""
service_name = "elbv2"
|
"""
Program to find the most optimal path to the center of a tumor to perform laparoscopy
Milestones:
1) Available dataset: https://wiki.cancerimagingarchive.net/display/Public/SPIE-AAPM-NCI+PROSTATEx+Challenges#7a2690e0c25948c69ddda9cc3b3905ec
Tumor locations are available
2) Find CNN trained with abdomenal MRIs
... |
from datetime import datetime
import pytest
from fdk_fulltext_search.ingest import create_index, init_info_doc, update_index_info
def mock_update_by_query_result(m_query_success):
if m_query_success:
return {"total": 1}
else:
return {"total": 0}
@pytest.fixture
def init_info_mock(mocker):
... |
from django.conf import global_settings
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
},
}
DEBUG = True
SECRET_KEY = 'secret'
ROOT_URLCONF = "testproject.urls"
INSTALLED_APPS = ["log_request_id"]
MIDDLEWARE = [
'log_request_id.middleware.Request... |
import argparse
import csv
import datetime
import logging
import multiprocessing
import os
import subprocess
import sys
import urllib
import torch
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DATA = os.path.join(ROOT, "data")
# https://www.bart.gov/about/reports/ridership
SOURCE_DIR = "http://6... |
#oggpnosn
#hkhr
import webapp2
from lib import BaseHandler, NGO, Project
import random
from google.appengine.api import mail
class CredibilityCheckHandler(BaseHandler):
def get(self):
parameter = {}
ngoQuery = NGO.query(NGO.credibility == False)
ngoList = ngoQuery.fetch(10)
parameter["ngoList"] = ngoList ... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'User'
db.create_table('disk_user', (
('id', s... |
# ['red', 'yellow', 'blue'].
# f(1) = 1
# f(n) = f(n - 1) + n
# term value colour
# 1 1 'red'
# 2 3 'blue'
# 3 6 'blue'
# 4 10 'red'
# 5 15 'blue'
# 6 21 'blue'
# 7 28 'red'
# (3, 3, 'blue') == [6, 15, 21]
# (100, 4, 'red') == [136, 190, 253,... |
# -*- coding: utf-8 -*-
# Date: 2020/3/17 14:21
"""
some command args
"""
__author__ = 'tianyu'
from argparse import ArgumentParser
import sys
class Parser(ArgumentParser):
def __init__(self, args_name='network'):
self.work_name = args_name
super(Parser, self).__init__(description=f"PyTorch impl... |
def hammingWeight(n):
# 第一种方法
# py3中库函数
# return bin(n).count("1")
# 第二种方法
# 直观统计二进制中每一位是否包含1
return sum(1 for i in range(32) if n & (1<<i))
print(hammingWeight(0b00000000000000000000000000001011)) |
import sys, getopt, datetime, codecs
import got3
import pandas as pd
from datetime import datetime
from datetime import timedelta
from time import sleep
def getTweets(Name="", Term="", Start="", End="", maxDayTweets=5000):
tweetCriteria = got3.manager.TweetCriteria()
twList = []
delta = datetime.strptime... |
# make sure that prints will be supported
import argparse, sys
import random
import time
sys.path.append("..")
print(sys.path)
from blossompy import Blossom
from time import sleep
import simpleaudio as sa #used for playing audio files to facilitate exercise
# seed time for better randomness
random.seed(time.time())
ma... |
from __future__ import absolute_import, unicode_literals
from c8.utils import get_col_name
import json
__all__ = [
'StandardFabric',
'AsyncFabric',
'BatchFabric',
'TransactionFabric'
]
from datetime import datetime
from c8.api import APIWrapper
from c8.c8ql import C8QL
from c8 import constants
from ... |
# Should use a balanced tree to ensure O(log(n)) insert and rank.
class BinarySearchTree(object):
def __init__(self):
self.root = None
def insert(self, x):
y = self.root
z = None
while y is not None:
y.size += 1
z = y
if x.key < y.k... |
import smbus
import os
import sys
import time
import io
from datetime import datetime, timedelta
import statistics
#Third Party Modules
import pi_servo_hat # Pan/Tilt mast controller
import picamera
tf_width = 299 #Width required for Tensorflow
tf_height = 299 #Height required for Tensorflow
tf_bw = True #Whet... |
# Stacker model (Lasso + Ridge + XGB + KNN) using Linear Regression
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import cross_val_score
from sklearn.ensemble import RandomForestRegressor
# Function... |
import imutils
import threading
import os
import glob
import numpy as np
import cv2
import csv
import time
import sys
from color_markers import *
sys.stdout = open('temp_log', 'w')
width = 5
img = np.zeros((500,500),dtype=np.uint8)
img_with_circles = np.zeros((500,500),dtype=np.uint8)
img_thick = np.zeros((500,500),... |
import numpy as np
import pandas as pd
import random
import os
import argparse
import sys
import time
from datetime import date
###################################################
###################### ARGS #######################
###################################################
def str2bool(v):
if isinstance... |
def log_make_dir(dirname):
if not(os.path.isdir(dirname)):
os.mkdir(dirname)
def _reg_loss(x,w):
return np.mean(K.eval(AE_reg_loss(K.constant(x), K.constant(w))))
def log_update_loglik_recons_reg():
loglik.append(Kalman_tools.log_likelihood(w_all,A,b,H,v_all,C,d,Q,R,mu_0,Sig_0))
p... |
"""Model store which provides pretrained models."""
from __future__ import print_function
import os
import zipfile
from ..utils.download import download, check_sha1
__all__ = ['get_model_file', 'get_resnet_file']
# _model_sha1 = {name: checksum for checksum, name in [
# ('25c4b50959ef024fcc050213a06b614899f94b3... |
# -*- coding: utf-8 -*-
import KBEngine
import random
import SCDefine
import time
import d_avatar_inittab
from KBEDebug import *
from interfaces.GameObject import GameObject
class Avatar(KBEngine.Proxy,GameObject):
"""docstring for Avatar"""
def __init__(self):
KBEngine.Proxy.__init__(self)
G... |
# https://leetcode.com/problems/angle-between-hands-of-a-clock/
class Solution:
def angleClock(self, hour: int, minutes: int) -> float:
hour = hour % 12
hour_angle = 360 * hour / 12 + 360 / 12 * minutes / 60
min_angle = 360 * minutes / 60
angle = abs(hour_angle - min_angle)
... |
# Thanks to https://github.com/PavelOstyakov/toxic
import sys
import numpy as np
import pandas as pd
import nltk
import tqdm
sentence_length = 256
def tokenize_sentences(sentences, word_to_token):
tokenized_sentences = []
for sentence in tqdm.tqdm(sentences):
if hasattr(sentence, "decode"):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.