text stringlengths 8 6.05M |
|---|
import click
import os
import transaction
from decimal import Decimal
from decimal import InvalidOperation
from onegov.core.cli import abort
from onegov.core.cli import command_group
from onegov.core.cli import pass_group_context
from onegov.core.crypto import random_token
from onegov.file.utils import as_fileintent
f... |
from ex4 import largest
from ex5 import findYear
result = largest(10,50,1000)
year = findYear(25)
print(result)
print(year) |
# Though number is defined outside the def of function the variable is accessible.
# Global variable can be accessed anywhere if defined outside a function or class
'''
def getnumber( ):
print number
number=1
getnumber()
'''
# output is 2 because the fuction uses the local variable value
'''
def g... |
import pyimgur # imgur library
import urllib # url fetching default library
import time # time library to add delay like in Arduino
CLIENT_ID = "50e8d92be50757f" # imgur client ID
# retrieve the snapshot from the camera and save it as an image in the chosen directory
urllib.urlretrieve("http://192.168.0.111:81/sn... |
#!/usr/bin/python
import argparse
import sys
import random as random
from fractions import gcd
import math as math
import time as time
from memory_profiler import memory_usage
def options():
parser = argparse.ArgumentParser()
parser.add_argument('-message', type = str, help = 'The Message to Encrpyt')
arg... |
# -*- coding: utf-8 -*-
__author__ = 'Yuvv'
# todo: analyse rules and return result
# 正、反向推理
# 规则存储
# 冲突解决
# 规则匹配方法
# 解释器
from utils.engine import param_splitter, update_factor
from utils.inference import infer
import sys
# engine启动函数
def run_engine(args):
try:
r_target = args[0]
c_factors = ar... |
import pytest
from queue_with_stacks.queue_with_stacks import PseudoQueue
# from queue_with_stacks.queue_with_stacks import PseudoQueue
# from ..queue_with_stacks import PseudoQueue
# from .queue_with_stacks import PseudoQueue
# from queue_with_stacks import PseudoQueue
# from queue_with_stacks import Stack
@pytest... |
from PyQt5.QtWidgets import QWidget, QDialog, QInputDialog
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtGui import QImage, QPalette, QBrush
from PyQt5.QtCore import QSize
import os
SCREEN_SIZE = [700, 700]
class AddCustomLevel(QDialog, QWidget):
def __init__(self):
super().__init__()
self... |
"""Advent of Code Day 7 - Recursive Circus"""
import collections
import re
def base_dict(tower_data):
"""Build weight and holding dictionaries and identify the base program."""
holding = {}
weights = {}
base = []
for tower in tower_data:
program, weight, *held = re.findall(r'\w+', tower)
... |
#! /usr/bin/env python3
import os
import requests
import json
import slack
from slackbot import slackclient
# Need to clean this up to use slash command
# grab token from env var, error if not found
def extract_api_token(env_var_name):
token = os.environ.get(env_var_name)
if token:
return token
el... |
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 23 11:09:30 2021
@author: DELL
"""
import torch
from torch.nn.init import xavier_normal_
from torch import nn
class mirror_conv(nn.Module):
def __init__(self,in_channel,out_channel,kernel_size):
super(mirror_conv,self).__init__()
self.k... |
from sample_madlibs import hello, park, party, madlibs
import random
if __name__ == "__main__":
m = random.choice([hello, park, party, madlibs])
m.madlib() |
import unittest
import os
from ..BaseTestCase import BaseTestCase
from centipede.ExpressionEvaluator import ExpressionEvaluator
class SystemTest(BaseTestCase):
"""Test System expressions."""
def testTmpdir(self):
"""
Test that the tmpdir expression works properly.
"""
result = ... |
import numpy as np
# obs = [ace, sum1, otherSum, rounds, cardsLeft]
# noinspection PyRedundantParentheses
class blackJack():
numDeck = 5
rounds = 1
deck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
def __init__(self):
self.forPlayerCardCount = [0 for i in range(11)]
self.cardCount =... |
#!/usr/bin/env python
import setuptools
with open("README.md", "r", encoding='utf-8') as fh:
long_description = fh.read()
setuptools.setup(
name='TurkishStemmer',
version='1.3',
description='Turkish Stemmer',
long_description=long_description,
long_description_content_type="text/markdown",
... |
import numpy as np
def normalize(X):
X_norm = np.copy(X)
n_cols = X.shape[1]
for i in range(n_cols):
X_norm[:, i] = (X[:, i] - np.min(X[:, i])) / (np.max(X[:, i]) - np.min(X[:, i]))
return X_norm
def standardize(X):
X_std = np.copy(X)
n_cols = X.shape[1]
for i in range(n_cols):
... |
from collections.abc import Iterable, Iterator
from typing import Any, Generic
from typing_extensions import Literal
from wtforms.meta import _MultiDictLikeWithGetall
def clean_datetime_format_for_strptime(formats: Iterable[str]) -> list[str]: ...
class UnsetValue:
def __bool__(self) -> Literal[False]: ...
unse... |
from colorama import Fore, Style
import time
class Logger:
output_file = None
@staticmethod
def set_output_file(file_name):
if file_name:
Logger.output_file = open(file_name, 'w')
@staticmethod
def time_now():
return time.strftime("%H:%M:%S", time.localtime())
@s... |
import random
import gzip
import math
import heapq
import multiprocessing
from itertools import izip
from PIL import Image
import numpy as np
import cPickle as pickle
WORLD_TO_MAP_SCALE = 15.758
RAY_MOD = 20
CELLS_IN_ONE_METRE = 2
LASER_MAX_RANGE = 10
LASER_SCAN_ANGLE_INCREMENT = 10
TOTAL_PARTICLES = 4200
PARTICLES_P... |
#!/usr/bin/python
## -*- coding: utf-8 -*-
#
import json
#import db_conf
import cgi
import sys
import sqlite3
qform = cgi.FieldStorage()
inparam = qform.getvalue('inpathway')
#inparam = "Citrate_cycle_tca_cycle_KEGG" #autophagy_article"#
intype = qform.getvalue('pathwaytype')
#intype = "all"#"leukemia"#"aml"
pw_src = ... |
# Generated by Django 3.0.5 on 2020-06-18 12:32
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('csp_observer', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='CspRule',
fields=[
('... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import requests
import utils
import packages.trend.github_lang as github_lang
from re import search, escape
from bs4 import BeautifulSoup
def run(string, entities):
"""Grab the GitHub trends"""
# Number of repositories
limit = 5
# Range string
since = 'daily'
# T... |
# coding: utf-8
# In[4]:
import numpy as np
arr = np.arange(1,5)
print(arr)
# # numpy library
#
# In[8]:
import numpy as np
arr = np.arange(5)
print (arr)
# In[9]:
list = [1,2,3,4]
arr=np.array(list)
print(arr)
# In[10]:
list = [[1,2,6],[4,5,6]]
arr=np.array(list)
print(arr)
# In[11]:
np.arrange(10)... |
import select
import socket
import urwid
from packet_list_box import PacketListBox
class WireDolphin:
palette = [
('reveal focus', 'black', 'dark cyan', 'standout'),
('reveal focus1', 'black', 'black', 'standout'),
('layer_title', 'dark red', 'black'),
('layer_desc', 'white', 'bla... |
# -*- coding: utf-8 -*-
import pygame
from pygame.locals import *
from world import *
from hud import *
from math import *
class Enemy(pygame.sprite.Sprite):
def __init__(self, world, n, img, px, py, walk, orient = 0):
self.world = world
self.name = n
print n
self.image = img
self.rect = img.get_rect()
... |
import requests
class ApiClient:
"""
Base class for api clients
"""
api_path = None # populated in subclass
trailing_slash = False # override in subclass if needed
def __init__(self, host, token):
self.host = host
self.base_url = self.host + self.api_path
self.client... |
# https://python.swaroopch.com/basics.html
# and also some https://automatetheboringstuff.com
myNum = 100
if myNum > 50:
print("High")
else:
print("Low")
print("yo")
print('''This is a multi-line string. This is the first line.
This is the second line.
"What's your name?," I asked.
He said "Bond, James ... |
"""
Given an integer, write a function to determine if it is a power of two.
"""
class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
if bin(n).count('1') == 1:
return True
else:
return False
if __name__ == '__m... |
#!/usr/bin/python3
"""unit tests for Square class"""
import io
import sys
import unittest
from models.base import Base
from models.square import Square
class TestSquare_instantiation(unittest.TestCase):
"""Unittests for testing instantiation of the Square class."""
def test_is_base(self):
self.assert... |
import pytest
import pdb
from fhir_walk.model import unwrap_bundle
from fhireval.test_suite.crud import prep_server
test_id = f"{'2.2.06':10} - CRUD Observation"
test_weight = 2
example_observation_id = None
example_patient_id = None
def test_create_research_subject(host, prep_server):
global example_observat... |
import sys, getopt
import requests
from bs4 import BeautifulSoup
import time
import pandas as pd
import numpy as np
from datetime import datetime
from datetime import timedelta
if __name__ == "__main__":
from_date = ''
to_date = ''
main_category = ''
sub_category = []
try:
opts, args = getopt.getopt(sys.... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# coding=utf-8
d = {"name": '魑魅魍魉'}
d2 = {"name": "python"}
d.update(d2)
print(d)
|
#IMPORT HERE..
import os
import time
from zipfile import ZipFile
from selenium import webdriver
#DEFINE CONSTANTS HERE..
URL = 'http://localhost:8000/CollectMaterial/'
PATH = os.getcwd()
def fetch_questions(code):
chrome_options = webdriver.ChromeOptions()
prefs = {'download.default_directory' : PATH+"\Quest... |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
file = r'grupo06.csv'
data = pd.read_csv(file, skipinitialspace=True)
data2 = pd.read_csv(file, skipinitialspace=True)
data.drop_duplicates(keep='first', inplace=False)
data2.drop_duplicates(keep='first', inplace=True)
opa = data2['Performance']
de... |
import statistics, io, argparse, random
import numpy as np
from collections import Counter
def accuracy(gold_word, pred_word):
correct = 0
if gold_word == pred_word:
correct = 1
return correct * 100
def F1(gold_word, pred_word):
correct_total = 0
for m in pred_word:
if m in gold_word:
correct_tota... |
from Layer import *
import ast
import math
class Net:
layers = [];
layerOut = []; # output haye har layer
opt = "";
alpha = 0.0;
def __init__(self, opt, size, active, regul, alpha): # size , tedad neuron haye hame laye ha ( input layer ham ) hast
self.opt = opt;
self.alpha = alpha;
for i in range(0, le... |
# 1. 문제
# (핵심) 부등호 순서를 만족하는 최대 최소를 찾아야 함
# 1.1 세부조건
# - 모든 숫자는 달라야함. (한 번 씩만 사용가능)
# -- 부등호에 부분
# -- 부등호 방향 같거나 다른 경우를 나눠서 생각.
# 2. 포인트 - 해결 아이디어
# - 최대가 되려면???
# --- 숫자를 큰 수 부터 뽑아가면서 부등호를 만족할 수 있을지를 체크한다.
# ex. 2 < >
# 9 < ? 9보다 더 큰 수가 없기 때문에 8로 내려감
# 8 < 9 만족할 수 있기 때문에 다음 부등호 체크
# 9 > 7 만족하기 때문에 끝
# 3. 플로우
# 숫자 배... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# @author: Chuan
# For beginner
# 1. variable - int,num,str,bool
# 2. if
# 3. > < >= <= ==
# 4. print
def main():
who = 'chuan的老妈 '
good_price = 6 #小贩的价格
good_description = "西双版纳大白菜" #小贩的招牌
is_cheap = False #是否便宜
reasonable_price = 5 #老妈能接受的最高价格
bu... |
from __future__ import absolute_import
import sys
import re
import pandas as pd
import numpy as np
import itertools
GRO_FIELDS = {
"resid": ((0, 5), int),
"resname": ((5, 10), str),
"atom_name": ((10, 15), str),
"atomid": ((15, 20), int),
"x": ((20, 28), float),
"y": ((28, 36), float),
"z"... |
#!/usr/bin/python3
"""unit_test.py: Testing to make sure that the functions from
diagonals.py is working correctly
"""
import unittest
from diagonals import get_all_diagonals, smallest_sum_in_array, get_diagonal
class UnitTest(unittest.TestCase):
"""UnitTest"""
def test_get_diagonal(self):
"""test_ge... |
import os
import pandas as pd
from autumn.projects.covid_19.mixing_optimisation.constants import OPTI_REGIONS, PHASE_2_START_TIME
from autumn.projects.covid_19.mixing_optimisation.mixing_opti import DURATIONS, MODES
from autumn.projects.covid_19.mixing_optimisation.utils import (
get_country_population_size,
... |
from django.shortcuts import render, redirect
from .forms import ParkForm
from .models import Parks
from .filters import ParkFilter
def home(request):
parks = Parks.objects.all()
context = {'parks':parks }
return render(request, 'home.html', context)
def addPark(request):
current_user = request.user
... |
#/bin/python
# parse repo tree, collect todo's, generate todo file
# Unix tool inspiration
# grep, sed, cut, awk
import os
import os.path
import sys
import re
# single file grepping class
class Grepper:
def __init__(self):
self.matches = {}
self.is_empty = True
# pseudo grep method
def grep_file(self... |
#coding:utf-8
import datetime
import json
import traceback
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.http.request import QueryDict
from django.http.response import HttpResponse
from django.middleware.csrf import get_token
from django.shortcuts imp... |
class Solution(object):
def isIsomorphic(self, s, t):
if len(s) != len(t):
return False
word1, word2 = {}, {}
for i in range(len(s)):
ch1, ch2 = s[i], t[i]
if word1.get(ch1, 0) != word2.get(ch2, 0):
return False
word1[ch1] = i +... |
from keras.models import load_model
from PIL import Image
import os
import numpy as np
import sys
def testmodel(file_name):
print os.path.dirname(__file__)
os.chdir(os.path.curdir)
model = load_model('pic_model.h5')
if not os.path.exists(os.path.join(os.path.dirname(__file__), "Uploads", file_name)):
... |
import win32gui, win32con
def winEnumHandler( hwnd, ctx ):
if win32gui.IsWindowVisible( hwnd ):
print (hex(hwnd), win32gui.GetWindowText( hwnd ))
Minimize = win32gui.GetForegroundWindow()
win32gui.ShowWindow(hwnd, win32con.SW_MINIMIZE)
win32gui.EnumWindows( winEnumHandler, None )
|
"""
Service Announcement
Adapted from https://stackoverflow.com/questions/21089268/python-service-discovery-advertise-a-service-across-a-local-network
"""
import time
from localshit.utils import utils
from localshit.utils.utils import logging
class ServiceAnnouncement:
def __init__(self, hosts, socket_sender):
... |
import os
import numpy
from sklearn.preprocessing import scale
if __name__ == '__main__':
loadpath = 'D:/PythonProjects_Data/CMU_MOSEI/AudioPart/Step4SAME_SpectrumGeneration/'
savepath = 'D:/PythonProjects_Data/CMU_MOSEI/AudioPart/Step5SAME_Normalization/'
totalData = []
for partName in os.listdir(lo... |
#!/usr/bin/python
#Following sine curve.
from dxl_mikata import *
import time
import math
import numpy as np
#Setup the device
mikata= TMikata()
mikata.Setup()
mikata.EnableTorque()
#Move to initial pose
p_start= [0, 0, 1, -1.3, 0]
mikata.MoveTo({jname:p for jname,p in zip(mikata.JointNames(),p_start)})
time.sleep(0... |
#Pay calculator with time and a half
def overtime_pay():
try:
hrs = float(raw_input('Hours?'))
rate = float(raw_input('Rate?'))
rate_overtime = 1.5*rate
if hrs < 40:
pay = hrs*rate
elif hrs > 40:
pay = 40*rate + (hrs - 40)*rate_overtime
... |
# @Title: 柱状图中最大的矩形 (Largest Rectangle in Histogram)
# @Author: 2464512446@qq.com
# @Date: 2020-11-16 15:33:30
# @Runtime: 64 ms
# @Memory: 15.4 MB
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
res = 0
heights = [0] + heights + [0]
stack = [0]
size = le... |
import numpy as np
import matplotlib.pyplot as plt
from DynamicSystems.cart_pole import CartPole
from utils import simulate_system
parameters = {
'mass_cart': 1,
'mass_pendulum': 1,
'pendulum_length': 1,
'gravity': 9.8
}
cp = CartPole(parameters)
test_state = np.array([0, np.pi, 0, -.01])
deriv = cp.derivative... |
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
noreplist = []
ans = 0
for i in range(len(s)):
if s[i] in noreplist:
n = noreplist.index(s[i])
noreplist = noreplist[n+1... |
import copy
import math
import numpy as np
import torch
from torch.nn import Parameter, init
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Implementation of Twin Delayed Deep Deterministic Policy Gradi... |
def splitArr(arr, n, k):
for i in range(0, k):
x = arr[0]
for j in range(0, n-1):
arr[j] = arr[j + 1]
arr[n-1] = x
n=int(input('Enter the no. of elements in the list'))
arr=[]
for i in range(0,m):
c=int(input('Enter the element'))
arr.appen... |
import torch
import torch.nn as nn
from torch.nn import functional as F
import torchvision.models as models
import numpy as np
from PIL import Image
import mynet
def main():
path = '/home/zzl/zzlWorkspace/NNInference/'
module = torch.load(path+'MNIST/module/my_mnist.pkl')
'''
test_data = Image.ope... |
import os
import sys
import argparse
from colorama import Fore
from lib.core.banner import BANNER
from lib.core import utils
from lib.core import log
# globals
found = 0
def main():
vuln_classes = utils.get_vulnerability_classes()
vulns_list = [(_class.name, _class.keyname) for _class in vuln_classes]
... |
class Solution(object):
def groupAnagrams(self, strs):
groups = {}
for str_ in strs:
sorted_str_ = ''.join(sorted(str_))
try:
groups[sorted_str_].append(str_)
except KeyError:
groups[sorted_str_] = [str_]
for str_lst in grou... |
import time
import helper
import process
import smali_parser
# improvement - return variable - possible ?
def inject_code(file_path, file_metadata):
'''
Edit the methods of a .smali file.
:param file_path: path of the .smali file
:param my_tag: debug tag to use in logcat
:param file_metadata: dictiona... |
#!/usr/bin/python3.5
#coding: utf8
"""
sudo get-apt install python3
sudo apt-get install python3-pip
python3 -m pip --version
"""
print("~~~~~~~~~~~~~~ Start ~~~~~~~~~~~~~~\n")
from random import randint
from libery import get_list
from libery import firatFan
firatFan()
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ N... |
from tensorflow import keras as ke
import tensorflow.python.keras.backend as K
from tensorflow.keras.models import Model, load_model
import streamlit as st
from nltk.tokenize import word_tokenize
from tensorflow.keras.preprocessing.sequence import pad_sequences
import pickle
import re
import string
import nltk
import s... |
from lxml import etree
tree = etree.parse("nlp.txt.xml")
root = tree.getroot()
docment = root[0]
sentences = docment.find("sentences")
for sentence in sentences:
tokens = sentence.find("tokens")
for token in tokens:
word = token.find("word")
ner = token.find("NER")
if ner.text == "PERS... |
@chef_routes.route('/<int:id>/appointment', methods=['POST'])
def post_appointment(id):
form = AppointmentForm()
data = request.get_json()
y, m, d, h, minute, sec = request.json["date"].split("-")
new_date = datetime.datetime(int(y), int(m), int(d), int(h), int(minute), int(sec))
new_appointment = A... |
import torch
import numpy as np
import os
import monai
from monai.data import ArrayDataset, create_test_image_2d
from monai.inferers import sliding_window_inference
from monai.metrics import DiceMetric
from monai.transforms import Activations, AddChannel, AsDiscrete, Compose, LoadImage, RandRotate90, RandSpatialCrop, S... |
#!/usr/bin/env python
#Duncan Campbell
#February 3, 2015
#Yale University
#plot the projected correlation function of a set of mocks.
#load packages
from __future__ import print_function
import sys
import numpy as np
import h5py
from astropy.io import ascii
import matplotlib.pyplot as plt
import custom_utilities as c... |
#! python3
"""download-solid.py - Download every single XKCD comic."""
# Import essential modules.
import os
import requests
import bs4
import logging
logging.basicConfig(level = logging.DEBUG, format = '%(levelname)s, %(message)s')
logging.disable(logging.CRITICAL)
# Set basic url and create directory to save comi... |
from tensorflow.keras.layers import (GRU, Dense, Dropout, Embedding, Flatten,
Input, Multiply, Permute, RepeatVector,
Softmax)
from tensorflow.keras.models import Model
from utils import MAX_SEQUENCE_LENGTH
def make_ner_model(embedding_tensor,... |
import imghdr
from werkzeug.utils import secure_filename
from flask import Flask, request, jsonify, render_template
import pickle
import os
import pandas as pd
from keras.models import load_model
from keras.preprocessing import image
import tensorflow as tf
from PIL import Image
import numpy as np
import json
app = Fla... |
from django.conf import settings
from django.conf.urls import include
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path
from rest_framework import routers
from rest_framework_jwt.views import obtain_jwt_token
from apps.articles.views import ArticleViewSet, Article... |
"""
create a bunch of different indexes using ggindex() and compare their properties.
"""
# set start end date
ret_bsk_mat.index[0]
ret_bsk_mat.index[-1]
# corr
ret_bsk_mat.corr().round(4)
ret_bsk_mat.corr().round(4).to_csv('output/bsk/ret/corr_1.csv')
# sharpe sortino
sharpe_1 = sharpe(ret_bsk_mat, s... |
#!/usr/bin/env python
import lcddriver
from mpu6050 import mpu6050
import math
sensor = mpu6050(0x69)
lcd = lcddriver.lcd()
while True:
accel_data = sensor.get_accel_data()
pitch = math.atan2(accel_data['z'],accel_data['y'])
roll = math.atan2(accel_data['z'],accel_data['x'])
print(pitch)
print(r... |
str1 = input()
str2 = input()
if (str1 == str2):
print("-1")
else:
if (len(str1) > len(str2)):
print(len(str1))
elif (len(str2) > len(str1)):
print(len(str2))
else:
print(len(str1))
|
from django.contrib import admin
# Register your models here.
from .models import Post, Category
class PostAdmin(admin.ModelAdmin):
list_display=("Title", "Author")
search_fields=["contents"]
class CategoryAdmin(admin.ModelAdmin):
list_display=("Category_name","Description")
admin.site.register(Post, Po... |
# write a program that receives in input an integer value and
# computes and outputs '/' if the value is positive, '-' if the value is 0
# '\' otherwise
POS = '/'
NEG = '\\'
ZERO = '-'
val = int(raw_input())
if val > 0:
sOut = POS
else:
if val == 0: # if val < 0:
sOut = ZERO # sOut = NEG
else: # else:
... |
import numpy as np
import numpy.linalg as npl
import matplotlib.pyplot as plt
import util
def discrimAnalysis(x, y):
"""
Estimate the parameters in LDA/QDA and visualize the LDA/QDA models
Inputs
------
x: a N-by-2 2D array contains the height/weight data of the N samples
... |
import json
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from shopback.items.models import Product,ProductSku
def productsku_quantity_view(request):
#request.POST
content = request.REQUEST
product_id = content.get('product_id')
sku_id = content.get... |
#!/usr/bin/env python
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from power.lib import * #@UnusedWildImport
from statistics.lib import * #@UnusedWildImport
p = Power.load(verbose=True)
s = Statistic.load(verbose=True)
device_opportunistic = {}
devices = s.experiment_devices
for d in de... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import numpy as np
from ddz_type import CARDS_VALUE2CHAR, CARDS_CHAR2VALUE
def str2ary(cards_str, separator=','):
"""
把字符串的牌型转换成数组
输入中包含分隔符,就返回二维数组,不包含,则直接返回一个数组
:param cards_str:
:param separator:
:return:
"""
ary = cards_str.split(separat... |
# Generated by Django 2.2 on 2019-04-23 07:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('TestModel', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='test',
name='detail1',
fiel... |
from board import *
from mario import *
from objects import *
from getch import _getChUnix as getChar
from os import system
from time import sleep
import sys
a=board()
a.makeArray()
move = Mario()
b=Badal()
enemyList=[]
sEnemyList=[]
PtsBrk=[]
a.array=b.generateBadal(a.array)
c=Bricks()
a.array=c.generateBricks(a.a... |
class Solution:
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
i = 1
s = '1'
while i < n:
end = 0
cur = s[end]
count = 0
result = []
while end < len(s):
if s[end] == cur:
... |
import matplotlib.pyplot as plt
x=0.01
deltaX= 0.01
yProp=0 # THE PROPORTIONAL FUNCTION MUST BEGIN AT 0
yLinear=5
yQuad=0
yExpPlus=1
yExpMinus=1
yLog= -10
ySin=0
yCos=1
xList = []
yPropList = []
yLinearList = []
yQuadList = []
yExpPlusList = []
yExpMinusList = []
yLogList = []
ySinList = []
yCosList = []
for i i... |
import re
import csv
import datetime
tsv = open('3_vera.tsv', 'r')
fileContent = tsv.read()
fileContent = re.sub('\t', ',', fileContent) # convert from tab to comma
csv_file = open('3_vera.csv', 'w')
csv_file.write(fileContent)
csv_file.close()
# code below I found on the internet and matched for my code,
# but I... |
from django.db import models
# Create your models here.
class Usuario(models.Model):
nome = models.CharField(max_length=64, unique=True)
senha = models.CharField(max_length=120)
descricao = models.CharField(max_length=500)
admin = models.BooleanField(default=False)
def __str__(self):
return self.nome
|
import numpy as np
from math import log2
np.set_printoptions(precision=2)
# information gain = E_start - E
# want highest value
def entropy(values):
sum1 = 0
values = np.array(values)
for v in values:
sum1 += v * log2(v)
entropy = -sum1
print("E({}) = {}".format(values, entropy))
ret... |
nums = [0,1,4,2,0]
target = 5
map = {}
l = nums.__len__()
for i in range(0, l):
complement = target - nums[i]
if nums[i] in map.keys() and nums[i] ==complement:
#print "[%s,%s]" %(i,map[nums[i]])
ret = [map[nums[i]],i]
break
else:
if complement in map.keys():
... |
import pytest
from rif.util import rcl
@pytest.mark.skipif('not rcl.HAVE_PYROSETTA')
def test_import_pyrosetta():
import pyrosetta
import rosetta
@pytest.mark.skipif('not rcl.HAVE_PYROSETTA')
def test_pyrosetta_init():
rcl.init_check()
rcl.init_check() # second call ignored
with pytest.raises(... |
from typing import List, Callable
from hummingbot.client.config.config_helpers import get_connector_class
from hummingbot.connector.exchange.paper_trade.market_config import MarketConfig
from hummingbot.connector.exchange.paper_trade.paper_trade_exchange import PaperTradeExchange
from hummingbot.client.settings import ... |
#! /usr/bin/env python3
from joint import Joint
import sys
import time
def parse(argFile = None):
if(argFile == None):
print("No file was given to parse")
return
indexOfpos = 0
with open(argFile, 'r') as argument:
data = argument.read()
lines = data.split("\n")
curr... |
from typing import List
import re
from .base_factory import BaseFactory
INT_PATTERN = re.compile(r"[0-90123456789]+(?!float|\_|\d)")
FLOAT_PATTERN = re.compile(
r"(?<!\.|\d)[0-90123456789]+\.[0-90123456789]+(?!\.|\d)",
)
def gen_float_token_with_digit(floats: List[str], token: str = "_{}float{}_"):
output ... |
with open('../.config', 'r') as config:
vals = config.readlines()
for val in vals: print(val)
print(vals[4][0])
|
BULLET_TYPE = 1
FOOD_TYPE = 2
TRAVEL_TYPE = 3
SPORT_TYPE = 4
TYPES = (
(BULLET_TYPE, 'bullet'),
(FOOD_TYPE, 'food'),
(TRAVEL_TYPE, 'travel'),
(SPORT_TYPE, 'sport')
) |
from discord.ext import commands
import discord
import asyncio
import requests
import time
from discord import Member
from random import randint
from coinbase_commerce import Client
import os
from bit import Key
class DealCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.key = Key('5J5... |
import sys
def cascade(index, true_index, reach_list):
current_domino = reach_list[index]
if current_domino == 0:
return true_index
end = index + current_domino
if end > 0:
reach_values = reach_list[index:] + [current_domino + true_index]
else:
reach_values = reach_list[ind... |
import json
from shutil import make_archive
from distutils.dir_util import copy_tree
from os import path
from .general import create_dir, get_run_date_times
from .asci_extractor import extract_water_level_grid
def prepare_flo2d_run(run_path, model_template_path, flo2d_lib_path):
# create a directory for the mod... |
import pygame
from constants import SQUARE_SIZE, WIN, BLACK, WHITE, W_KING, B_PAWN, B_ROOK, B_KNIGHT, B_BISHOP, B_QUEEN, B_KING, W_PAWN, W_ROOK, W_KNIGHT, W_BISHOP, W_QUEEN, CONTACT
class Piece:
def __init__(self, name, row, col, colour):
self.name = name
self.row = row
self.col = ... |
class Solution(object):
def missingNumber(self, nums):
res = len(nums)
for i, item in enumerate(nums):
res ^= item
res ^= i
return res |
import logging
import asyncio
import aioamqp
from ... import config
from .driver_base import ExchangerBase
logger = logging.getLogger(__name__)
class Exchanger(ExchangerBase):
async def __aenter__(self):
logger.debug('connecting with role {}'.format(self.role))
params = config.get_amqp_conn_pa... |
import os
import json
def rarity_skeleton():
return {
"model": "main.Card_Rarity",
"pk": None,
"fields": {
"card_rarity": None
}
}
def type_skeleton():
return {
"model": "main.Card_Type",
"pk": None,
"fields": {
"card_type":... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.