text stringlengths 38 1.54M |
|---|
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy import Column, Boolean, VARCHAR, Integer, String, DateTime, ForeignKey, UniqueConstraint, PrimaryKeyConstraint
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.dialects.sqlite import TEXT
engine = create... |
#finds all "lucky tickets" in range between two inputted numbers
#"lucky" are tickets which sum of first three digits equals to sum of three last
import sys
if len(sys.argv) != 3 : #if number of arguments does not equal 3
print "error1"
exit() #exit
a1 = int(sys.argv[1])
a2 = int(sys.argv[2])
new_string = "" #v... |
#Arrays/Lists
import rhinoscriptsyntax as rs
#because of the coercePt command all of the lists/strings below will be able to creat points
# [ ] brackets define lists
# ( ) perenthesis define touples
arrPt1 = [1,3,9]
arrPt2 = [4,5,6]
arrPt3 = [-1,-2,-3]
arrPt4 = [7,8,9]
rs.AddPoint(arrPt1)
rs.AddPoint (arrPt2)
rs.AddP... |
# Generated by Django 3.2.5 on 2021-07-17 16:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('notes_app', '0003_alter_note_title'),
]
operations = [
migrations.AlterField(
model_name='note',
name='title',
... |
import pdb;
def x_traverse(x_forward, y_forward, result, depth, start_idx, start_jdx, matrix):
if len(result) == len(matrix) * len(matrix):
return result
if x_forward:
for jdx in range(0, len(matrix) - depth):
result.append(matrix[start_idx][start_jdx + jdx])
start_idx += 1... |
"""
root
/ \
a | a
/ \ | / \
b c | c b
/ \ | / \
d e | e d return true
root
/ \
a | a
/ \ | / \
b c | c c
/ \ | / \
d e | e d return false
struct Node {
int dat... |
from game import *
from math import sin, cos, tan, pi
W, H = CANVAS_WIDTH, CANVAS_HEIGHT
PINCH_MIN, PINCH_MAX, PINCH_SPEED = -50, 50, 2.5
init_state = {
"pos": (0,0),
"pinch": 0
}
colourmod = lambda x, y, t, st: (
rangebounce(0,255,x),
rangebounce(0,255,y),
rangebounce(0,255,x*y)
) if st["pinch"] >= 0 el... |
import os
import numpy as np
from fparam import *
from default_functions_proc import *
class offset_class:
def __init__(self): # {{{
self.vx = None
self.vy = None
self.snr = None
# }}}
def load(self,filename,par_file=None,snr_file=None,init=False): # {{{
if par_file is No... |
#!/usr/bin/python
# python-deps - find the dependencies of a given python script.
import os, sys
from modulefinder import ModuleFinder
# pylint: disable=wildcard-import
from distutils.sysconfig import *
sitedir = get_python_lib()
libdir = get_config_var('LIBDEST')
# A couple helper functions...
def moduledir(pyfile)... |
#!/usr/bin/env python
import numpy as np
from collections import deque
N, M = map(int, input().split())
G = [[] for _ in range(N)]
for _ in range(M):
a, b = map(int, input().split())
a -= 1
b -= 1
G[a].append(b)
G[b].append(a)
def dfs(graph, v):
used = {v}
res = set()
q = deque([v])
... |
from matplotlib.pyplot import*
import numpy as np
import matplotlib.pyplot as plt
def f(x):
return x**2 - 85*x + 400
def falsi( a , b , f , kmax ):
i = 0
dif = 10000000
x = 1
while( i < kmax and dif > 0.0000001 ):
ant = x
x = ( (f(b) * a - f(a) * b) / ( f(b) - f(a)))
if( f(a) * ... |
from server.models import User, Location
from server import app, db, twilio_client
from datetime import datetime, timedelta
import json
from server.constants import *
from server.sms.msg_templates import *
#TODO: Option for neighboring counties
def filter_users_to_alert(users):
final = []
for user in users:
... |
"""Initialization module."""
from .celery import CELERY_APP as celery_app
__all__ = ['celery_app']
|
_base_ = './mask-rcnn_s50_fpn_syncbn-backbone+head_ms-1x_coco.py'
model = dict(
backbone=dict(
stem_channels=128,
depth=101,
init_cfg=dict(type='Pretrained',
checkpoint='open-mmlab://resnest101')))
|
import subprocess
from eth_utils import (
to_text,
)
def get_version_from_git() -> str:
version = subprocess.check_output(["git", "describe"]).strip()
return to_text(version)
|
"""
Operations on containers
Interacts directly with Docker and Docker-Compose. In the future it will be possible to integrate also Docker Swarm.
:author: Blackandred <riotkit .. riseup.net>
"""
import os
import re
import subprocess
from time import time
from contextlib import contextmanager
from typing import Optio... |
# -*- coding: utf-8 -*-
"""
The Django URLs for the server.
"""
from django.conf.urls.defaults import patterns
from slumber.server.http import view_handler
from slumber.server.meta import applications
_urls = {'^$': 'slumber.server.views.get_applications'}
for app in applications():
_urls['^(%s)/$' % app.pa... |
#!/usr/bin/python3
def flip(stack, count):
hsh ={"+": "-", "-": "+"}
for i in range(count):
stack[i] = hsh[stack[i]]
def pack(stack):
new_stack = [stack[0]]
old = stack[0]
for i in stack[1:]:
if old != i:
new_stack.append(i)
old = i
return new_stack
def pa... |
# -*- coding: utf-8 -*-
# 关键参数
DATA_DIR = '../data/'
TRAIN_DATA_DIR = '../traindata/'
PCON = 'BB' # 合约简称
PERIOD = '1MINUTE' # 合约数据时间格式
# 回测相关参数
CAPITAL = 1000000 # 初始资金总数
RISK = 0.01 # 承担风险指数
CLEVEL = 0 # 机器学习预测置信比
OPCYCLE = 4 # 操作周期 = OPCYCLE * 数据最小时间单位
# ... |
#!/usr/bin/env python
"""
This filename contains a health monitoring plugin which is still
being developed and is still in the alpha testing stage.
----------------------------------------------------------------
check-disk
DESCRIPTION
Check Disk Usage by filesystem, by analysing the output from the "df -x tm... |
from ._affine_transform import affine_transform
from ._AffineTransform3D import AffineTransform3D
from ._apply_vector_field import apply_vector_field
from ._deskew_y import deskew_y
from ._deskew_x import deskew_x
from ._rigid_transform import rigid_transform
from ._rotate import rotate
from ._scale import scale
from .... |
from sklearn import *
from clean_train import *
import time, re, amueller_mlp
from sklearn.metrics import *
import numpy as np
def logRange(limit, n=10,start_at_one=[]):
"""
returns an array of logaritmicly spaced integers untill limit of size n
starts at 0 unless if start_at_one = True
"""
if start_at_one: n=n+... |
import random
HangMan = ['''
________
|/ |
|
|
|
|
|
|___''', '''
________
|/ |
| (_)
|
|
|
|
|___''', '''
________
|/ |
| (_)
| |
| |
|
|
|___''', '''
________
|/ |
| (_)
| \|
| |
|
|
|___''', '''
_______... |
"""A module that defines constants of expression's variable names.
"""
from typing_extensions import Final
DOCUMENT: Final[str] = 'document'
DISPLAY_OBJECT: Final[str] = 'do'
PARENT: Final[str] = 'parent'
GRAPHICS: Final[str] = 'g'
POINT2D: Final[str] = 'p2d'
RECTANGLE: Final[str] = 'rect'
CIRCLE: Final[st... |
import os
def renomear_arquivos():
#Obter o nome dos arquivos de uma pasta
lista_arquivos = os.listdir("/home/victorshgo/Desktop/Python Projects/rename-files/images-for-example")
#Qual o diretorio atual
pasta_atual = os.getcwd()
print("A pasta atual e: " + pasta_atual)
#Entrando no diretorio co... |
#MergeRankSummaries.py
#
# Description: Merges rank summaries and attaches values as
# an attribute table to the patch raster
#
# Inputs: <Patch raster> <Geometry CSV> <Connectivity CSV>
# Outputs: <Patch composite>
#
# June 2012, John.Fay@duke.edu
#
import sys, os, arcpy
import arcpy.sa as sa
arcpy.CheckOutExtensio... |
"""Markdown extension to render content similar to the source.
This will render Markdown such that the spacing and alignment in the source
text and the rendered content looks roughly the same. It's meant to help ensure
that what's typed is very close to what's viewed when rendered.
"""
import re
from collections impo... |
import datetime
import json
import logging
import os
import threading
import time
from abc import ABC, abstractmethod
import pika
from tools.mongo_dao import MongoDB
class StopCondition(ABC):
def __init__(self, stop_condition_parameters: dict, experiment_description: dict, experiment_id: str):
self.even... |
with open('D:/python_udemy/pycharm/src/files', mode='a+') as my_file:
print(my_file.read())
print('---------------------')
my_file.seek(0)
print(my_file.read())
|
import argparse
import random
from crowd_dataset import CrowdDataset
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
import cv2
import numpy as np
import os
import random, string
import math
import pickle
from collections import OrderedDict
import torch
from torch import nn as nn, optim as ... |
"""
Test attrs that previously caused bugs.
"""
import pdir
from pdir._internal_utils import category_match
from pdir.attr_category import AttrCategory
def test_dataframe():
from pandas import DataFrame
result = pdir(DataFrame)
for attr in result.pattrs:
if attr.name in ('columns', 'index'):
... |
# 第一次
import requests
url = 'https://wordpress-edu-3autumn.localprod.forc.work/wp-login.php'
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36'
}
data = {
'log': 'spiderman', #写入账户
'pwd': 'crawler334566', #写入密码
'wp-submit': '登... |
import numpy as np
from largescale.src.support.geometry import gen_coordinates
def make_gabor(size=(0,0), orientation=0, scale=0, period=0, phase=0, peak=1.0):
if isinstance(scale, tuple):
xscale = scale[1]
yscale = scale[0]
else:
xscale = scale
yscale = scale
[coorx, coory] = gen_coordinates(siz... |
# coding:utf-8
import sys
import redis
import time
import sqlite3
import re
import collections
import logging
logging.basicConfig(filename ='redis.log',level=logging.DEBUG,format='%(asctime)s %(filename)s[line:%(lineno)d] %(message)s',datefmt='%m/%d/%Y %H:%M:%S %p')
logging.info('beginning!')
key_set = set()
key_li... |
def gcd(n,m):
if n==0:
return m
else:
return(n, m%n)
def iterative_gcd(n1,n2):
min = n1 if n1<n2 else n2
largest_factor=1
for i in range(1,min+1):
if n1%i==0 and n2%i==0:
largest_factor = i
return(largest_factor)
def main():
for num1 in range(1,... |
# coding=utf-8
__author__ = 'F.Marouane'
import sys
from PyQt4.QtGui import *
from PyQt4 import QtCore
from DPricer.presentation.PyuicFiles.Echeancier import Ui_Dialog
class EcheancierDialog(QDialog, Ui_Dialog):
def __init__(self):
super(Ui_Dialog, self).__init__()
QDialog.__init__(self)
... |
CLASSES = [
'Brick 1x1',
'Brick 1x2',
'Brick 1x3',
'Brick 1x4',
'Brick 2x2',
'Brick 2x2 L',
'Brick 2x2 Slope',
'Brick 2x3',
'Brick 2x4',
'Plate 1x1',
'Plate 1x1 Round',
'Plate 1x1 Slope',
'Plate 1x2',
'Plate 1x2 Grill',
'Plate 1x3',
'Plate 1x4',
'Plate... |
#Find possible odds
n, m = [int(i) for i in input().split()]
if n%2 != 0:
n += 1
for i in range(n,m):
if (i%2)!=0:
print(i)
|
'''
@author: xilh
@since: 20200126
'''
print("== 无序列表修改 ==")
set1 = {'a', 'b', 'c'}
print("set1 : ", set1)
set1.add(1)
print("set1 add : ", set1)
set2 = {'computer', 'calulator'}
set1.update(set2)
print("set1 update: ", set1)
|
#ThreadLocal
"""
在多线程环境下,每个线程都有自己的数据。一个线程使用自己的局部变量比使用全局变量好,因为局部变量只有线程自己能看见,不会影响其他线程,而全局变量的修改必须加锁。
但是局部变量也有问题,就是在函数调用的时候,传递起来很麻烦:
"""
class Student(object):
pass
def process_student(name):
std = Student(name)
# std是局部变量,但是每个函数都要用它,因此必须传进去:
do_task_1(std)
do_task_2(std)
def do_subtask_1(std):
... |
#!/usr/bin/env python
# Copyright (c) 2020-2021 VMware, Inc. All Rights Reserved.
# SPDX-License-Identifier: BSD-2 License
# The full license information can be found in LICENSE.txt
# in the root directory of this project.
import logging
import os
import sqlite3
import unittest
import uuid
from lydian.apps.rules impo... |
#!/usr/bin/env python
# ----------------------------------------------------------------------------
# Copyright (c) 2017--, Evguenia Kopylova
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# --------------------------------... |
import datetime
from peewee import CharField, DateTimeField, ForeignKeyField
from model_base import *
from model_table import *
class ColumnModel(PostgresqlModel):
class Meta:
db_table = 'columns'
table = ForeignKeyField(TableModel, related_name='columns')
name = CharField()
created_date = Da... |
"""
PointNet分类
"""
import torch.nn as nn
import torch.utils.data
import torch.nn.functional as F
from torch.autograd import Variable
from pointnet1_utils import PointNetEncoder, feature_transform_regularizer, TN3d, TNkd
class PointNetCls(nn.Module):
"""
pointnet 分类网络结构
"""
def __init__(self, k=40, ch... |
import hashlib, binascii, os
from functools import wraps
from flask import session, redirect
def hash_password(password):
"""Hash a password for storing."""
"""https://www.vitoshacademy.com/hashing-passwords-in-python/"""
salt = hashlib.sha256(os.urandom(60)).hexdigest().encode('ascii')
pwdhash = hash... |
#!/usr/bin/python
#coding=utf-8
import psycopg2
import time
from datetime import datetime
conn = psycopg2.connect(database="cyy_insurdb", user="cyyuser",password="kkz9c7H2", host="10.10.1.210")
print "connect success"
def log(file,context): #log记录函数
current_time=datetime.now()
f = open(file,"wb+")
f... |
## PARA REMOVER UM ITEM DA LISTA DE ACORDO COM A POSICÇÃO
del lanche [3]
# OU
lanche.pop(3)
# PARA REMOVER SOMENTE O ULTIMO ELEMENTO
lanche.pop()
#PARA REMOVER UM ITEM DA LISTA DE ACORDO COM O NOME DELE
lanche.remove('pizza')
## PARA ORDERNAR VALORES
valores.sort()#ordena em ordem crescente
valores.sort(reverse=True... |
import datetime
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Sum,F,FloatField
from work_data.views import JSONQueryView
from stats.helpers import day_of_year,week_of_year,filter_keys
MONTHS = ['January','Febuary','March','April','May','June','July','August','September','October','... |
from peacemakr.exception.peacemakr import PeacemakrError
class ServerError(PeacemakrError):
pass
|
from ..users.models import Users
from django.shortcuts import render
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework import status
from django.conf import settings
from django.contrib import auth
from rest_framework.views import APIView
from rest_fram... |
#!/usr/bin/env python
import json
import os
from os.path import join
import argparse
def write_doc_and_decl(op, layout, type_sig, type_map, operator, out_as_operand, compound_assignment):
signature = list(enumerate(zip(layout, type_sig)))
out_cpp_type = type_map[type_sig[0]]['cpp']
doc = "/** %s\n" % (op... |
#! -*-encoding=utf-8-*-
import pandas as pd
import hypertools as hyp
from hypertools.tools import cluster
data = pd.read_csv('F:\\mushrooms.csv')
#print data.head()
'''
Now let’s plot the high-dimensional data in a low dimensional space by passing it to HyperTools.
To handle text columns, HyperTools will first convert... |
from Class_object.Concluding_task_1 import Student
from Class_object.Concluding_task_2 import Course
user_num=int(input("Enter a number of the course: "))
user_name_course=input("Enter a name of the course: ")
user_num_subject=int(input("Enter the number of subjects: "))
user_capacity=int(input("Enter a max number of ... |
from django.shortcuts import render
from annoying.decorators import render_to
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_protect
from .poll_api import Api
# Create your views here.
@csrf_protect
def api(request, method_name):
poll_api = Api()
poll_api.method = method_n... |
import os
import sys
import struct
import zlib
import time
"""
#define IMAGE_MAGIC 0xAEAE
struct image_header
{
uint16_t magic;
uint8_t encrypt_algo;
uint8_t resv[1];
uint8_t version[VERSION_SZ];
uint32_t crc32;
uint32_t size;
//uint8_t padding[4060];
};
"""
def insert(original... |
import os
import cv2
import json
import sys
import tensorflow as tf
# Wagon segmentation with the help of Tensorflow
class App:
def __init__(self):
# Config
self.debug = False
# Global variables
self.tf_files_dir = './tf_files'
self.frames_dir = os.path.abspat... |
from task2.data_util import *
from task2.config import Config
from task2.NER_model import NERModel
from task2.utils import *
if __name__ == "__main__":
config = Config()
train_dataset = Dataset(config=config, name="train")
validate_dataset = Dataset(config=config, name="valid")
test_dataset = Dataset(... |
import pprint as pp
import json, math, re, csv, itertools, os
from datetime import datetime
import numpy as np
# COUNTING UNIQUE TUEKERS
exit()
path_to_batch_results = "./batch_results"
batch_files = os.listdir(path_to_batch_results)
dict_turkers = {}
for bf_name in batch_files:
print bf_name
with open(path_to_... |
import torch
import torchvision
from torchvision import transforms
from PIL import Image
from torch.utils.data import Dataset, DataLoader
import os
import json
import tqdm
import random
class_id_list = list()
for classdir in os.listdir(os.path.join("../image_exp/Classification/Data", "Train")):
class_id_list.appen... |
import numpy as np
import cv2
##import keras
##from keras.models import load_model
##model = load_model('savedmodel.h5')
image=cv2.imread('photo1.jpg')
##print(image)
##cv2.imshow('image',image)
##cv2.waitKey()
##cv2.destroyAllWindows()
grayimage=cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) #convert to grayscale to mat... |
import numpy as np
import tensorflow as tf
class BiLSTM:
def __init__(self, hparams, scope):
self.scope = scope
self.hidden_nums = int(hparams['global']['hidden_size'])
def __call__(self, hs, seq_len):
with tf.variable_scope('LSTM_Variables_%s' % self.scope, reuse=tf.AUTO_REUSE):
... |
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this... |
import numpy as np
from tools import Indicators
class MovingAverage:
def __init__(self):
pass
def ma_cross_strategy(self, open_prices,
fast_h=6, slow_h=13, family="sma",
start_balance=1000, fee=0.1):
if family == "sma":
ma_fast = Indicators().sma(open_prices, fast_h)
ma_fast = ma_fast[slow_h-fast... |
def get_max_value(data_list, capacity):
data_list = sorted(data_list, key=lambda x: x[1] / x[0], reverse=True)
total_value = 0
details = list()
for data in data_list:
if capacity - data[0] >= 0:
capacity -= data[0]
total_value += data[1]
details.append([data[... |
#!/usr/bin/env micropython
from ev3dev2.motor import LargeMotor, MoveSteering, MoveTank, OUTPUT_C, OUTPUT_B
from ev3dev2.sensor import INPUT_1, INPUT_4
from ev3dev2.sensor.lego import ColorSensor
from time import sleep
motor = LargeMotor(OUTPUT_C)
tank_pair = MoveTank(OUTPUT_C, OUTPUT_B, motor_class=LargeMotor)
steer_p... |
import numpy as np
import pandas as pd
from models import model_dt
ext_params = {}
def set_params(max_round, p_value):
global ext_params
ext_params = {
'max_round': max_round,
'p_value': p_value,
}
print('Extraction params:', ext_params)
def fit(x, y, t, **kwargs):
kwargs.updat... |
import sqlite3
import csv
class SqliteReader():
def __init__ (self, dbName):
self.conn = sqlite3.connect(dbName)
self.league = ["England Premier League","Germany 1. Bundesliga", "Switzerland Super League", "Netherlands Eredivisie", "France Ligue 1", "Scotland Premier League", "Portugal Liga ZON Sag... |
from __future__ import print_function
class Node:
def __init__(self, item):
self.item = item
self.min = item
def __str__(self):
return str(self.item)
# unbounded stack
class Stack:
def __init__(self):
self.nodes = []
self.top = -1
def push(self, node):
... |
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
import tensorflow as tf
train = pd.read_csv('./train.csv')
test = pd.read_csv('./test.csv')
del train['Name']
del train['Ticket']
del train['Fare']
del train['Embarked']
train = train.fillna(value=0.0)
for i in range(train.s... |
from HNL.Tools.ROC import ROC
from HNL.Tools.mergeFiles import merge
import os
import glob
from HNL.Tools.helpers import makePathTimeStamped
#
# Argument parser and logging
#
import argparse
argParser = argparse.ArgumentParser(description = "Argument parser")
argParser.add_argument('bkgr', action='store', def... |
import unittest
def monge_min(A):
'''
:param A: list[list[num]] a monge list
:return: list[num] min value of every row
'''
# todo: write the next
i = 0
while i < len(A) // 2:
pass
class TestSolution(unittest.TestCase):
def test_case(self):
examples = (
((... |
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import argparse
import torch.utils.data.sampler as sampler
from create_dataset import *
from utils import *
parser = argparse.ArgumentParser(description='Multi-task: Cross')
parser.add_argument('--weight', default='equal', type=str, hel... |
#!/usr/bin/env python
# encoding: utf-8
from __future__ import absolute_import
import time
from celery.utils.log import get_task_logger
from artproject.celery import app
from art.utils.send_mail import send_email, pack_html
@app.task
def add(x, y):
return x+y
@app.task
def tsend_email():
url = "http://www.b... |
from django.shortcuts import render
from initialise.models import User, Bandit
import random
def get_game(order, game_id):
real_game_id = ((order / pow(10, game_id - 1)) % 10)
game = Bandit.objects.get(id=real_game_id)
return game.p, game.reward
# Create your views here.
def playgame(request):
items = request.p... |
lis = input("Enter a input: ")
for i in lis:
if len(i) >= 3:
print "True"
break
elif len(i) <= 2:
print "False"
"""
if len(lis) >= 2:
print "True"
elif len(lis) <= 2:
print "False"
else:
pass
"""
|
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
#请求URL并把结果用UTF-8编码
response = urlopen('https://en.wikipedia.org/wiki/Main_Page').read().decode('utf-8')
#使用BeautifulSoup去解析
soup = BeautifulSoup(response, 'html.parser')
#获取所有以/wiki/开头的a标签的href属性... |
#!/usr/bin/env python3
import sys
import unittest
#Add your test here
tests = [
'unittests.test_simple_mangling',
'unittests.test_kooc_file',
'unittests.test_import',
'unittests.test_class',
# 'unittests.test_module',
'unittests.test_kooccall',
]
# 'unittests.test_newtest',
def main():
... |
import numpy as np
import matplotlib.pyplot as plt
from uncertainties import ufloat
from scipy.optimize import curve_fit
from scipy.stats import sem
import importlib
exec(open('python/u_hall_iqconst_pos.py').read())
exec(open('python/u_hall_iqconst_neg.py').read())
plt.tight_layout()
plt.savefig("build... |
#
# Copyright 2019-2020 Lukas Schmelzeisen
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
# -*- coding:utf-8 -*-
"""
Boston Housing Example.
"""
# Copyright 2017 Authors NJU PASA BigData Laboratory.
# Authors: Qiu Hu <huqiu00#163.com>
# License: Apache-2.0
from __future__ import print_function
from keras.datasets import boston_housing
from forestlayer.estimators.estimator_configs import ExtraRandomForestC... |
"""Distance functions."""
import numpy as np
from scipy import linalg as la
from typing import List, Callable, Union
import logging
from .scale import standard_deviation, span
from .base import Distance, to_distance
from ..storage import save_dict_to_json
logger = logging.getLogger("ABC.Distance")
class PNormDist... |
# Uses python3
import sys
"""
def optimal_sequence(n):
sequence = []
while n >= 1:
sequence.append(n)
if n % 3 == 0:
n = n // 3
elif n % 2 == 0:
n = n // 2
else:
n = n - 1
return reversed(sequence)
"""
"""
9 8 7 6 5 4 3 2 1
0 x x x x x ... |
import re
partyDict = {
'Latvijas Krievu savienība': 'LKS',
'Jaunā konservatīvā partija': 'JKP',
'Rīcības partija': 'Ricib',
'Nacionālā apvienība Visu Latvijai!-Tēvzemei un Brīvībai/LNNK': 'NA',
'PROGRESĪVIE': 'Progr',
'Latvijas centriskā partija': 'Centr',
'LSDSP/KDS/GKL':'LSDSP',
... |
from math import *
def sieve(n):
L = [True] * (n + 1)
L[0] = False
L[1] = False
prime = 2
k = prime
while prime < int(floor(sqrt(n))) + 1:
while k <= n - prime:
k += prime
L[k] = False
prime += 1
while L[prime] == False:
prime += 1
k = prime
return L
def compute_quadratic(a, b, n):
return (n ... |
# TF-IDF é uma medida estatística que indica a importância de uma palavra TF - IDF = TF*IDF
# TF = Numero de vezes que uma palavra ocorre no documento / Número total de palavras no documento
import math
DicWords = []
DicWord = {}
DicWordAllDocument = {}
def includeWordsOfDocuments(Document):
Words = []
for ... |
# coding: utf-8
# In[1]:
import sys
with open(sys.argv[1]) as f:
m = f.read()
dictionary = m.split()
sentences = []
with open(sys.argv[2]) as d:
sentences = d.readlines()
punct = ["「", "」", "。", "、", "!", "?", "“", "\n"]
for i in range(len(sentences)):
for elem in punct:
sentences[i] = s... |
#======================== puzzle.builder.fromMask ========================
#
# @brief Create digital puzzles from a puzzle partition mask and a
# source iamge with a similar aspect ratio.
#
# The mask is white or "true" where the puzzle piece regions are and is
# black or "false" where the boundaries are. ... |
#!/usr/bin/env python3
import sys
from orthrus.serialdevice import SerialDevice
import _thread
from orthrus.util.logger import DataLogger
from orthrus.util.argparser import ArgParser
from orthrus.ui.plotter import DataPlotter
def print_tof(distance):
outstring = "Distance from transmitter: {}m"
print(outstri... |
import shutil
from collections import namedtuple
from ansible.parsing.dataloader import DataLoader
from ansible.vars.manager import VariableManager
from ansible.inventory.manager import InventoryManager
from ansible.playbook.play import Play
from ansible.executor.task_queue_manager import TaskQueueManager
import ansibl... |
# coding: utf-8
from snowballing.models import *
from snowballing import dbindex
dbindex.last_citation_file = dbindex.this_file(__file__)
from ..work.y2016 import michaelides2016a
from ..work.y2016 import correndo2016a
from ..work.y2017 import correndo2017a
from ..work.y2018 import moreau2018a
from ..work.y2018 import... |
import os, sys
#import intan module
sys.path.insert(0, '/Intan/')
print(os.getcwd())
from load_intan_rhd_format import read_data
#Read .rhd file and returns numpy array of amplitude data
#Adapted from Esther's Concentrate RAW code
def rhd_to_numpy(file_name):
rhd_dic = read_data(file_name) #read rhd file
rhd_array... |
from keystone import *
CODE = (
" jmp esp;"
)
# Initialize engine in 32bit
ks = Ks(KS_ARCH_X86, KS_MODE_32)
encoding, count = ks.asm(CODE)
egghunter = ""
for dec in encoding:
egghunter += "\\x{0:02x}".format(int(dec)).rstrip("\n")
print("egghunter = (\"" + egghunter + "\")") |
species(
label = 'C#CC([CH2])C(=C)[CH]C(26577)',
structure = SMILES('C#CC([CH2])C([CH2])=CC'),
E0 = (478.231,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([3010,987.5,1337.5,450,1655,2750,2800,2850,1350,1500,750,1050,1375,1000,2175,525,1380,1390,370,380,2900,435,350,440,435,1725,3000,3033... |
###
# Time Complexity: O(n)
# Space Complexity: O(1)
###
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseKGroup(self, head, k):
"""
:type head: ListNode
:type k: i... |
#!/usr/bin/python3
import argparse
import json
import urllib.request
# Set up argparser, add one argument option, parse it, and assign it to arguments
argparser = argparse.ArgumentParser()
argparser.add_argument("-u","--url", action="store", dest="url", help="URL to JSON data")
arguments = argparser.parse_args()
# U... |
'''
Name: Sung Joon Park
ID: 01514170
'''
def referenceSpectra(spectra):
#dividing and converting spectra into a dictionary about symbolic name and reference spectrum
'''
>>> spectra = ['H 486.135,434.0472,656.279,410.1734', 'He 501.56783,667.8151,587.5621,471.31457,492.19313,504.7738,447.14802,438.79296,40... |
import tkinter as tk
from tkinter import *
from tkinter import Menu
mw = tk.Tk()
mw.option_add("*Button.Background", "black")
mw.option_add("*Button.Foreground", "red")
mw.title('Screen Timer Program')
mw.geometry("500x500") #Selects the size of the window
mw.resizable(0, 0) #Doesn't allow resizing
menu = Menu(mw)
mw... |
import networks
import tensorflow as tf
import time
import os
import sys
base = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(base,'../../'))
from basemodels.GanLosses import GanLoss
from basemodels.GanOptimizers import Adam
import matplotlib.pyplot as plt
plt.switch_backend('agg')
import ... |
# Parallels Arrays
fire_station = ["ALPHA", "BETA", "THETA","CENTER", "RAILWAY", "HARBOR", "SUBURB"]
personnel = [12, 13, 23, 44, 23, 11, 43]
# Cloning the fire stations
fire_duty = fire_station
# Finding the understaffed station
p
# Main Loop
i = 0
loop = 0
# 1 year = 52 weeks
while i < 52:
# Mayor's input
... |
from __future__ import annotations
from . edge import Edge
from typing import List, Mapping, Any, Collection, Set, Dict
from . algorithm_ordering import AlgorithmOrdering
""" Module that contains the definition of a vertex in the context of a
directed graph """
class Vertex():
""" Class to represent details abou... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.