text stringlengths 38 1.54M |
|---|
# -*- coding: utf-8 -*-
"""
This code creates a database with a list of publications data from Google
Scholar.
The data acquired from GS is Title, Citations, Links and Rank.
It is useful for finding relevant papers by sorting by the number of citations
This example will look for the top 100 papers related to the keywo... |
#!/usr/bin/env python3
import json
from bson.objectid import ObjectId
import time
from db import db
from logger import Logger
l = Logger('backup.log', log_f=True)
trace = l.trace
log = l.getlog()
def main():
with open('weather.json') as wet:
for rec in wet:
weather = json.loads(rec... |
import urllib
import urllib.request
import urllib.parse
# ajax post
url = 'http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=pid'
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36'}
# get
url_get = 'http://www.kfc.com.cn/kfccda... |
import numpy as np
import os.path as osp
import os
import sys
from util import *
import torch
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
import torch.optim as optim
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
input_fi... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 5 10:38:22 2017
@author: cyril
"""
import numpy as np
def load_data(data_path, data_name):
data = np.load(data_path + data_name)
return data
def gen_batch(raw_data, batch_size, shuffle=True):
'''
during each iter, randomly sel... |
# coding: utf-8
#
# Copyright 2016 The MyCleanIndia 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
#
# Unles... |
"""Testing the modules from script1."""
from unittest import TestCase
from my_python_learning_scripts.script1 import parse_file, get_numbers
class TestScript1(TestCase):
"""Class holds the test functions for get_numbers method."""
def test_get_numbers(self):
"""Function should receive a list and retu... |
# Queue implementation using Linked List - preferred implementation
# To use a class of another file in current file, import it
from doubly_linked_list import DoublyLinkedList
class Queue:
def __init__(self):
self.queue_list = DoublyLinkedList() # create an empty queue object
# this object will ... |
from pydub import AudioSegment,playback
AudioSegment.converter='ffmpeg\\ffmpeg.exe'
songlist=['1.mp3','2.mp3']
class mediaplayer:
def __init__(self):
self.songlist = ['1.mp3', '2.mp3']
def play(self,index):
sound=AudioSegment.from_mp3(self.songlist[index])
playback.play(sound)
def mi... |
import os
import sys
import codecs
import requests
from itertools import groupby
from wikibench.dataset import *
class ERDConvert(object):
def __init__(self, goldenfile):
self.golden = self.read_file(goldenfile)
def get_wid(self, mid):
return requests.get(
'http://wikisense.mkapp.... |
# Copyright 2018 D-Wave Systems Inc.
#
# 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... |
#!/usr/bin/env python3
import sys
import os
import subprocess
from subprocess import call as _call
from glob import glob
import shutil
if sys.version_info.major == 3:
from pathlib import Path
def prntfail(*args, **kwargs):
print(args)
print(kwargs)
exit(1)
# TODO: more robust check for dry run
# Wrap functio... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'main.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, ... |
from XYZUtil4.customclass.Signal import Signal
from .Singleton import singleton
@singleton
class Signals:
pump_ena = Signal(int, bool) # bot_id, ena
channel_switch = Signal(int, int, bool) # bot_id, chem_id, is_open
cur_level = Signal(int, int, int) # bot_id, chem_id, level
cur_flow = Signal(int,... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def countNodes(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:... |
'''
keys:
Solutions:
Similar:
T:
S:
'''
from typing import List
# https://leetcode.com/problems/least-number-of-unique-integers-after-k-removals/discuss/686335/JavaPython-3-Greedy-Alg.%3A-3-methods-from-O(nlogn)-to-O(n)-w-brief-explanation-and-analysis.
class Solution:
# T: O(nlogn), S: O(n)
def findLeastNu... |
from time import sleep
from multiprocessing.dummy import Pool as ThreadPool, Event
event = Event()
def click():
# event.clear() # 设置标准为假(默认是False)
print("用户在修改网页表单")
sleep(2)
print("点击了修改案例")
event.set() # 设置标准为真
def update():
print(f"事件状态:{event.is_set()}")
event.wait() # 等待到标志为真
... |
from __future__ import print_function
import numpy as np
import pandas as pd
class Utils:
@staticmethod
def read_data(path, cols_names):
df = pd.read_csv(path, sep='\t', header=None, names=cols_names)
return df
@staticmethod
def to_one_hot(labels, n_classes):
labels = np.eye... |
from robot_bases import MJCFBasedRobot, URDFBasedRobot
import numpy as np
import pybullet_data
import os
import gym
from robot_bases import BodyPart
class Hand(URDFBasedRobot):
used_objects = []
object_poses = {}
num_joints = 24
num_touch_sensors = 10
class ObsSpaces:
JOINT_PO... |
#
#
# Test misc utils
#
#
import unittest
from abstractgame import AbstractGame
from connectgame import ConnectGame
from utils import softmax, random_simulation, uct_factory
class TestUtils(unittest.TestCase):
# Can softmax
def test_board_creation_new(self):
m = softmax([1,1])
... |
import json
from time import sleep
import random
from selenium.common.exceptions import NoSuchElementException
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from se... |
from glob import glob
from xml.dom.minidom import parse
from os.path import basename
def getParseCommandPairMappingsForTrain():
'''
Returns a dictionary mapping from filename to list of parse-command pairs
'''
fileMappings = {}
recipeNumber = 0
for filename in glob("parsed_annotated_recipes/*.xml"):
... |
#!/usr/bin/env python
# coding=utf-8
"""
Site: http://www.beebeeto.com/
Framework: https://github.com/n0tr00t/Beebeeto-framework
"""
import requests
from baseframe import BaseFrame
class MyPoc(BaseFrame):
poc_info = {
# poc相关信息
'poc': {
'id': 'poc-2015-0097',
... |
import os
os.chdir('C:\\ENEA_CAS_WORK\\Catania_RAFAEL\\postprocessing')
os.getcwd()
import numpy as np
import pandas as pd
import geopandas as gpd
from geopandas import GeoDataFrame
from shapely.geometry import Point
import folium
import osmnx as ox
import networkx as nx
import math
import momepy
from ... |
# -*- coding: utf-8 -*-
'''
Created on 2015年5月20日
@author: zqh
'''
import freetime.util.log as ftlog
from hall.servers.common.base_checker import BaseMsgPackChecker
from poker.protocol import runcmd
from poker.protocol.decorator import markCmdActionHandler, markCmdActionMethod
@markCmdActionHandler
class ComplainTc... |
import pytest
from fireo.fields import TextField, NumberField
from fireo.models import Model
from fireo.models.errors import AbstractNotInstantiate, NonAbstractModel
class User(Model):
name = TextField()
class Meta:
abstract = True
def test_abstract_not_instantiate():
with pytest.raises(Abstrac... |
import logging
from logging.handlers import SMTPHandler, RotatingFileHandler
import os
from flask import Flask, request, current_app
from config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
from flask_mail import Mail
from flask_bootstrap i... |
def is_leap(year):
leap = False
if year%400 ==0 :
leap = True
elif year%100 !=0 and year%4 ==0:
leap = True
# Write your logic here
return leap
# print(is_leap(2000)) //checkpoint
# best solution
# def is_leap(year):
# return year % 4 == 0 and (year % 400 == 0 or year % 100 !=... |
__author__ = 'anirudha'
import csv
import numpy as np
import matplotlib.animation as animation
import matplotlib.pyplot as plt
def init():
return line,
def update(num):
#newData = np.array([[1 + num, 2 + num / 2, 3, 4 - num / 4, 5 + num],[7, 4, 9 + num / 3, 2, 3]])
newData = np.vstack((range(num),data[:nu... |
#!/usr/bin/env python3
input()
from itertools import*
print(sum(len([*l]) // 3 for k, l in groupby(input()) if k == "X")) |
import sys
nl = sys.stdin.read().split()[1:]
for case,n in enumerate(nl):
n = int(n)
digits = [False]*10
i = 1
while True:
nk = n * i
i = i + 1
for d in str(nk):
digits[int(d)] = True
if sum(digits) == 10:
print("Case #{}: {}".format(case+1,nk))
... |
#!/usr/bin/python3
def divisible_by_2(my_list=[]):
if my_list is None:
return None
nueva = my_list.copy()
for count in range(len(my_list)):
if my_list[count] % 2 == 0:
nueva[count] = True
else:
nueva[count] = False
return nueva
|
# Generated by Django 2.2.5 on 2021-10-03 06:46
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('guardians_of_children', '0004_auto_20211003_0642'),
]
operations = [
migrations.RenameField(
model_name='videos',
old_name='... |
import cv2
import numpy as np
import matplotlib.pyplot as plt
cmap = plt.cm.viridis
def rgb2gray(rgb):
return np.dot(rgb[...,:3], [0.299, 0.587, 0.114])
def convert_2d_to_3d(u, v, z, K):#将2d图像转到3d空间中
v0 = K[1][2]
u0 = K[0][2]
fy = K[1][1]
fx = K[0][0]
x = (u-u0)*z/fx
y = (v-v0)*z/fy
r... |
"""
A :class:`~QtWidgets.QWidget` for controlling a Thorlabs_ translation stage.
.. _Thorlabs: https://www.thorlabs.com/navigation.cfm?guide_id=2060
"""
import os
import time
from msl.qt import QtWidgets, QtCore, QtGui
from msl.qt import prompt
from msl.qt.io import get_icon
from msl.qt.equipment.thorlabs import show... |
# -*- coding:utf-8 -*-
import hashlib
from datetime import datetime
from flask import current_app
from flask_login import UserMixin, AnonymousUserMixin
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from werkzeug.security import generate_password_hash, check_password_hash
from . import db
from... |
from flask import Flask, request
from flask_cors import CORS
from lib import config, log
from werkzeug.exceptions import HTTPException
from routes.roku import roku_template
from flask_swagger_ui import get_swaggerui_blueprint
from roku import Roku
try:
c = config.Configuration('config.ini')
except Exception as e:
... |
#!/usr/bin/env python
import numpy as np
import time
import rospy
from geometry_msgs.msg import Twist
from std_msgs.msg import String
import sys, select, os
if os.name == 'nt':
import msvcrt
else:
import tty, termios
e = """
Communications Failed
"""
def getKey(): #you can ignore this function. It's for s... |
from rest_framework.request import Request
from django.contrib.auth.models import AnonymousUser
from django.utils.functional import SimpleLazyObject
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from django.contrib.auth.middleware import get_user
from django.utils.deprecation import Middlewar... |
# -*- coding: utf-8 -*-
import cv2
import numpy as np
from config import VideoConfig
from utils import crop_by_roi
path = '/home/cys/Codes/DolphinDetection'
blur_ksize = 5
canny_lth = 75
canny_hth = 125
kernel_size = np.ones((3, 3), np.uint8)
def adaptive_thresh(frame, cfg=None):
# img = img[370:1080, 0:1980]
... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def widthOfBinaryTree(self, root: TreeNode) -> int:
# print(root)
L = [root]
lmax ... |
import sys
sys.stdin = open("input.txt")
T = int(input())
money = [50000,10000,5000,1000,500,100,50,10]
for tc in range(1, T+1):
inp = int(input())
count_arr = [0] * len(money)
for i in range(len(money)) :
count_arr[i], inp = divmod(inp, money[i])
print("#{}".format(tc))
print(*cou... |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from scipy import interpolate
from random import random
import math
def read_data_3d():
loaded = np.load('DIRO_skeletons.npz')
data = loaded['data']
normal_data = data[:, 0, :, :]
normal_d... |
from sys import stdin
class Particle:
def __init__(self, id, position, velocity, acceleration):
self.id = id
self.position = position
self.velocity = velocity
self.acceleration = acceleration
def update(self):
self.velocity = [self.velocity[i] + self.acceleration[i] for i in range(3)]
self.position = [s... |
"""
最初始的版本,留作纪念
"""
import json
from dataclasses import dataclass, is_dataclass
import typing
def ex_dataclass(*args, **kwargs):
"""
desc:
dataclass增强版,支持原生功能及以下扩展能力;
1、支持class类型正反递归解析;
2、支持列表正反解析;
3、支持列表简易嵌套正反解析,如:{a: [[1, 2, 3]]}
4、支持typing.Type类型注解的多态... |
from bs4 import BeautifulSoup
import requests
url = "https://www.theguardian.com/crosswords/cryptic/27558"
r = requests.get(url)
soup = BeautifulSoup(r.content, "html.parser")
grid = list(soup.find(class_ = "crossword__grid"))
def make_grid(grid, l=15):
return [['#' if grid[i+(l*j)] is "#" else " " for i in r... |
def approachlefthand():
#i01.startedGesture()
i01.setHandSpeed("right", 31.0, 31.0, 31.0, 31.0, 31.0, 22.0)
i01.setArmSpeed("left", 100.0, 100.0, 100.0, 100.0)
i01.setArmSpeed("right", 6.0, 6.0, 6.0, 6.0)
i01.setHeadSpeed(22.0, 22.0)
i01.setTorsoSpeed(31.0, 13.0, 100.0)
i01.moveHead(20,84)
i01.moveArm("... |
for i in range(1,11):
num_apart=int(input()) #아파트숫자
high_list=list(map(int,input().split()))#아파트높이
my_sum = 0
for j in range(num_apart):
if high_list[j] > 0 :
side = [high_list[j-2],high_list[j-1],high_list[j+1],high_list[j+2]]
m = 255
for k in side :
... |
import requests
import json
url = "https://www.bing.com/covid/data"
response = requests.get(url)
resp = response.json()
with open("results2.json",'w') as f:
json.dump(resp,f)
with open("results2.json",'r') as f:
ditc = json.load(f)
total = int(ditc['totalConfirmed'])
deaths = int(ditc['totalDeaths'])
reco... |
def iif(condition, true_part, false_part):
return (condition and [true_part] or [false_part])[0] |
from django.db import models
import uuid
class RetrivedData(models.Model):
name = models.CharField(verbose_name='Customer Name',max_length=120,null=True,blank=True)
due_amount = models.IntegerField(verbose_name='Due Amount',null=True,blank=True)
template_id = models.IntegerField(verbose_name='Template ID',null=Tru... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-08-16 15:12
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('prodsys', '0034_auto_20170807_1406'),
]
operations = [
migrations.AddIndex(
... |
#-*- coding:utf-8 -*-
"""
ECC Utils
This submodule comprises of ECC utilities, and common exploit scripts.
The tool also features ECC Analyser.
"""
|
INPUT_FILE = "B-large.in"
OUTPUT_FILE = "B-large.out"
res = []
def write_output():
out_file = open(OUTPUT_FILE, "w")
for i,line in enumerate(res):
out_file.write("Case #%d: %s\n" % (i+1, line))
out_file.close()
def count_plusminus(stack):
curr = stack[0]
if len(stack) == 1:
... |
import pandas as pd
import pickle, os
try:
DATA_PATH = open("data_location.txt", "r").read().strip()
except:
DATA_PATH = "."
def get_images_code_for_react_skinless():
fnums_list = pickle.load(open("%s/data/basics/fnums_list.p"%DATA_PATH,"rb"))
fnum_to_url_dict = pickle.load(open("%s/data/basics/fnum_... |
# Generated by Django 3.2.1 on 2021-05-16 01:29
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('CovidVaccine', '0003_auto_20210515_1557'),
]
operations = [
migrations.CreateModel(
name='AuthGroup',
... |
#=========================================================#
# [+] Script : Encoder / Decoder Base64 #
# [+] Auteur : oOScuByOo #
# [+] Site : xxxxxxxxxxxxxxxxxxx #
# [+] Twitter : xxxxxxxx #
#===================... |
# -*- coding: utf-8 -*-
"""
Created on 13 January, 2018 @ 11:08 AM
@author: Bryant Chhun
email: bchhun@gmail.com
Project: Insight_AI_BayLabs
License:
"""
import vtk
from vtk import vtkPolyDataReader
from vtk.util import numpy_support as ns
def load_vtk(filename):
# vtk files are polydata types.
# we use p... |
import requests
import re
import os
import pyfiglet
from pyfiglet import fonts
from colorama import Fore, Back, Style
from colorama import init
import time
import urllib3
from datetime import datetime
init()
# Console colors
W = '\033[0m' # white (normal)
R = '\033[31m' # red
G = '\033[32m' # gr... |
# -*- coding: utf-8 -*-
from django.db import models
from django.utils import timezone
import time,hashlib
# Create your models here.
from django.utils.timezone import now, timedelta
class Test(models.Model):#测试数据表
Char字段 = models.CharField(verbose_name="Char字段", max_length=32) # Char字段
选择 = (('xz1', '选择1'... |
# http://www.cyberforum.ru/turbo-pascal/thread1294897.html
import matplotlib.pyplot as plt
import random
g=0.0
Integral=0.0
fx=0.0
fx1=0.0
xi=[]
yi=[]
random.seed(0)
a=-2 # реальный интервал от -2 до 2..
b=2 # в задаче зачем-то от -3 до 3
N=1000000
k=b-a # Переменной"k"присвоим значение длины промежутка интегрир... |
# -*- coding:utf-8 -*-
from typing import List
class Solution:
# O(nlogn)
# def getLeastNumbers(self, arr: List[int], k: int) -> List[int]:
# arr_sort = sorted(arr)
# return arr_sort[:k]
# heapq O(nlogk)
def getLeastNumbers(self, arr: List[int], k: int) -> List[int]:
import he... |
import csv
import io
from dateutil.parser import parse
from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import User
from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from rest_framework import status
from rest_framework.response ... |
from django.db import models
class CuadradoMedio(models.Model):
semilla = models.FloatField()
iteraciones = models.IntegerField()
ri = models.FloatField()
def set_ri(self, ri):
self.ri = ri
def get_ri(self):
return self.ri
class Aditivo(models.Model):
semil... |
import pandas as pd
import os
import csv
import platform
import numpy as np
def read_csv_to_dataframe(csv_path, dtype=''):
dateparse = lambda x: pd.datetime.strptime(x, '%Y-%m-%d')
if (dtype is ''):
df = pd.read_csv(csv_path)
else:
df = pd.read_csv(csv_path, dtype=dtype, parse_dat... |
n = int(input())
if n%2:
print(n//2, n//2+1)
elif n//2%2:
print(n//2-2, n//2+2)
else:
print(n//2-1, n//2+1)
|
from torch.nn.modules.module import Module
from ..functions.add import MyAddFunction
class MyAddModule(Module):
def forward(self, input1, input2):
return MyAddFunction()(input1, input2)
|
class Egg:
def __init__(self, x=5):
self.x = x
def __cmp__(self, other):
if self.x < other.x:
return -1
elif self.x > other.x:
return 1
else:
return 0
e1 = Egg(4)
e2 = Egg(5)
print e1 == e2
print e1 > e2
print e1 < e2
|
#!/usr/bin/python3
# Homework 4 Unit Tests
import unittest
import random
import multiprocessing
import time
import sys
from hw4 import sequentialSearchRec
from hw4 import binarySearchRec
from HashTable import HashTable
# Make a decorator that skips tests when the required functionality hasn't been implemented y... |
#! ./python27.tar.gz/python27/bin/python27
#-*- coding:utf-8 -*-
import sys
import re
import cPickle as pickle
import random
old_recalltag_count = pickle.load(open("recalltag_count.pkl","rb"));recalltag_count={}
recalltag2code = pickle.load(open("/home/hdp-reader-tag/shechanglue/sources/recalltag2code.pkl","rb"))
newt... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2019-02-28 02:35
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('wildlifecompliance', '0123_auto_20190227_1511'),
]
operations = [
migrations.Remove... |
N = int(input())
arr = []
for i in range(N) :
a = list(map(int,input().split()))
arr.append([a[1], a[0]] )
arr.sort()
for i in range(N):
print(arr[i][1],arr[i][0]) |
# -*- 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 'MTabla'
db.create_table(u'tramiteDoc_mtabla', (
... |
"""
Leap year
Write a program that reads a year from the user and tells whether a given year is a leap year or not.
A leap year (also known as an intercalary year or bissextile year) is a calendar year that contains an additional day
(or, in the case of a lunisolar calendar, a month) added to keep the calendar year sy... |
import tensorflow as tf
from tensorflow.keras import layers, models
from adversarial.defences import AdvClassifier
class AdvGAN(models.Model):
def __init__(self):
super(AdvGAN, self).__init__()
self.genereator = PerturbationGenerator()
self.adv_clf = AdvClassifier()
def call(self, ... |
import boto3
import sys
my_region = sys.argv[1]
ec2client = boto3.client('ec2', region_name=my_region)
cloudwatch = boto3.client('cloudwatch', region_name=my_region)
account = boto3.client('sts').get_caller_identity().get('Account')
sns_topic_arn = "arn:aws:sns:" + my_region + ":" + account + ":notification_for_insta... |
""" Summarize the column names in a collection of tabular files. """
from hed.tools.analysis.column_name_summary import ColumnNameSummary
from hed.tools.remodeling.operations.base_op import BaseOp
from hed.tools.remodeling.operations.base_summary import BaseSummary
class SummarizeColumnNamesOp(BaseOp):
... |
#! /usr/bin/env python
from itty import *
import urllib2
import json
"""
Network Fingerprint
Author: Clint Mann
Illustrates the following concept:
- This is a simple Spark bot that monitors a Spark Room for user input.
It is one component in the Network Fingerprint App
"""
__author__ = "Clint Mann"
__license__ = ... |
# -*- coding: utf-8 -*-
import pymongo
import pandas as pd
from PIL import Image
import io
import numpy as np
import matplotlib.pyplot as plt
def get_coll(name_db):
client = pymongo.MongoClient('127.0.0.1', 27017)
db = client.DataDb_detection
if name_db=="Detection":
user = db.Detection... |
from django.contrib import admin
from .models import DevTool, Idea
admin.site.register(DevTool)
admin.site.register(Idea) |
from flask import Flask, session, render_template, request, redirect, url_for, escape
import pymysql.cursors
import bcrypt
import re
app = Flask(__name__)
db = pymysql.connect(host="localhost", user="budget-sheets", passwd="sheets-budget", db="budget-sheets", cursorclass=pymysql.cursors.DictCursor)
cursor = db.cursor(... |
from sandbox_api import sandbox_api_key, sandbox_secret_key, sandbox_passphrase
#from real_api import real_api_key, real_secret_key, real_passphrase
import sys
sys.path.append('/Users/Joseph/Documents/Ethereum/trade')
from authenticated_client import GDAXRequestAuth
# Sandbox api base
API_BASE = 'https://api-public.s... |
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
def obj_over_configs(x_config_names,y_kub,y_nsga,obj_name,title):
x_idx = np.arange(len(x_config_names))
width = 0.3
plt.bar(x_idx-width/2,y_kub,width=width,label="Kubernetes")
plt.bar(x_idx+width/2,y_nsga,width=width,label="N... |
from pacbot.game.blinky import Blinky
from pacbot.game.clyde import Clyde
from pacbot.game.inky import Inky
from pacbot.game.maze import Maze
from pacbot.game.pinky import Pinky
from pacbot.game.player import Player
from pacbot.game.renderer import Renderer
import pygame
class Game:
def __init__(self, scene):
... |
import datetime
from django.contrib.auth.models import User
from django.db import models
# Create your models here.
from django.urls import reverse
from GestionLab.models import Laboratorio, Maquina
from Convocatorias.models import Convocatoria
# def maqdelLab(lab):
# return Maquina.local(lab)
class Reservaci... |
# !/usr/bin/env python
# encoding: utf-8
"""
SEED Platform (TM), Copyright (c) Alliance for Sustainable Energy, LLC, and other contributors.
See also https://github.com/seed-platform/seed/main/LICENSE.md
"""
import base64
import json
from django.urls import reverse_lazy
from seed.landing.models import SEEDUser as Use... |
from flask import Flask, request, jsonify, Response
from flask_pymongo import PyMongo
from bson import json_util
from bson.objectid import ObjectId
app = Flask(__name__)
app.config['MONGO_URI']='mongodb://localhost:27017/pythonmongodb'
#Le pasamos la configuracion a PyMongo
mongo = PyMongo(app)
#POST
@app.route('/cu... |
#!/usr/bin/python
import gtk
import myanmar.converter as converter
clipboard = gtk.clipboard_get()
clipboard.set_text(converter.convert(clipboard.wait_for_text(), "zawgyi", "unicode"))
clipboard.store()
|
import time
# Welcome the user
name = input("what is your name ")
print("Welcome to my word game " + name + "!")
time.sleep(1)
print("Start Guessing...")
time.sleep(0.5)
#Set the secret word
word = "onomatopoeia"
# Create a variable with an empty Value
guesses = ''
# Determine the number of turns
turns = 12
#Cr... |
from sys import argv
from os.path import exists
script,from_file,to_file=argv
print "Copying from %s to %s" %(from_file,to_file)
in_file= open(from_file)
indata=in_file.read()
print "The input file is %d bytes long" %len(indata)
print "Does the output file exist? %r" %exists(to_file)
print "Ready , hit RETURN to cont... |
# -*- coding: utf-8 -*-
# filename:pics
import csv
import numpy
import matplotlib.pyplot as plt
price,size = numpy.loadtxt("house.csv",delimiter='|',usecols=(1,2),unpack=True)
plt.figure()
plt.subplot(211)
plt.title("price")
plt.title("/10000RMB")
plt.hist(price,bins=30)
plt.subplot(212)
plt.title("area")
plt.figur... |
import argparse
import json
import logging
import sys
import time
from subprocess import call
import requests
log = logging.getLogger(__name__)
def configure_logging():
root = log
root.setLevel(logging.DEBUG)
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.DEBUG)
formatter ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 19 11:54:19 2020
@author: zhengsc
"""
import numpy as np
import matplotlib.pyplot as plt
# 二分类的信息熵
# p可以传递数值,也可以传递向量。因此使用np.log
def entropy(p):
return -p * np.log(p) - (1-p) * np.log(1-p)
# linspace生成向量x,从0到1均匀取值,绘制出x在不同值时对应的信息熵
x = np.lins... |
import ROOT
from xAH_config import xAH_config
import sys, os
sys.path.insert(0, os.environ['ROOTCOREBIN']+"/user_scripts/XhhCommon/")
from XhhResolved_config_VHqqbb import *
from XhhBoosted_config_VHqqbb import *
from XhhLepTop_config import *
c = xAH_config()
#
# Basic Setup
#
trig... |
#!/usr/bin/env python
# pip install virtualenv
# virtualenv exceltrans
# \exceltrans\Scripts\activate
# python -m pip install --upgrade pip
# pip install xlsxwriter
# pip install openpyxl
# pip install pandas
# Openpyxl <https://doitnow-man.tistory.com/159>
# Pandas <https://www.delftstack.com/ko/howto/python-pandas/... |
# coding:utf-8
import codecs
from collections import defaultdict
class Vertex(object):
def __init__(self, value):
self.value = value
def __eq__(self, other):
return self.value == other.value
def __str__(self):
return str(self.value)
def __hash__(self):
#vital part, this will make the vertex be the on... |
# -*- coding: utf-8 -*-
import datetime
from ..models import User
from ..constants import Code
class AuthManager(object):
@classmethod
def authenticate(cls, username, password):
try:
user = User.objects.get(username=username)
except:
# TODO 日志
return
... |
import cv2
objectName = "Kalem Ucu"
frameWidth = 280
frameHeight = 360
color = (255,0,0)
cap = cv2.VideoCapture(0)
cap.set(3,frameWidth)
cap.set(4,frameHeight)
def empty(a):pass
# trackbar
cv2.namedWindow("Sonuc")
cv2.resizeWindow("Sonuc", frameWidth, frameHeight + 100)
cv2.createTrackbar("Scale","Sonuc",400,1000,e... |
# -*- coding: utf-8 -*-
from square.api_helper import APIHelper
from square.http.api_response import ApiResponse
from square.api.base_api import BaseApi
from square.http.auth.o_auth_2 import OAuth2
class RefundsApi(BaseApi):
"""A Controller to access Endpoints in the square API."""
def __init__(self, confi... |
from django.db import models
from eventex.subscriptions.validators import validate_cpf
from django.shortcuts import resolve_url as r
class Subscription(models.Model):
name = models.CharField(max_length=100, verbose_name='nome')
cpf = models.CharField(max_length=11, verbose_name='CPF',
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.