text stringlengths 38 1.54M |
|---|
"""Exceptions module."""
class NotASuite(Exception):
"""Exception class for When it's not a Suite errors."""
pass
class NumberOutsideOfRange(Exception):
"""Exception class for When Number is out of range errors."""
pass
class NotADeck(Exception):
"""Exception class for When invalide deck type r... |
from datetime import timedelta
from django.db import models
from django.db.models import F, ExpressionWrapper, OuterRef, Max, Subquery
from django.utils import timezone
from duckevents.models import FeedEntry
from background_task import background
def _clone_feed_entry(entry):
"""
"Clones" <entry> by removi... |
from nltk import pos_tag, ne_chunk
from nltk.tree import Tree
from utils import tokenize
def nltk_ner(text):
tokenized_sents = tokenize(text)
orgs = []
for (index, tokenized_sent) in enumerate(tokenized_sents):
_orgs = extract_orgs(tokenized_sent)
orgs.extend([(index, org) for org in _orgs... |
#!/usr/bin/env python
# encoding: utf-8
'''
icgc_mutation_zscores.py
Created by Joan Smith
on 2017-6-18
Calculate zscores for each ICGC mutation file
Copyright (c) 2018. All rights reserved.
'''
import argparse
import sys
import os
import glob
import pandas as pd
import numpy as np
sys.path.append('../common/')
im... |
from edgetpu.basic import edgetpu_utils
version = edgetpu_utils.GetRuntimeVersion()
print(version)
all_edgetpu_paths = edgetpu_utils.ListEdgeTpuPaths(edgetpu_utils.EDGE_TPU_STATE_NONE)
print('Available EdgeTPU Device(s):')
print(''.join(all_edgetpu_paths))
|
import os
import socket
from cStringIO import StringIO
from fabric.api import run, env, task, sudo, put, parallel, local, runs_once, hide
env.hosts = [
'ipd1.tic.hefr.ch',
'ipd2.tic.hefr.ch',
'ipd3.tic.hefr.ch',
'ipd4.tic.hefr.ch',
]
env.user = 'ipd'
@task
def ping():
run('hostname')
run('... |
#Build Mood Vector for each
import pickle, time
from buildEmotionDatabase import getEmotionsVector
UrlDict = pickle.load(open("faceUrls.pkl", "rb"))
#testUrlDict = {"01/2016" : UrlDict["01/2016"],
#"02/2016" : UrlDict["02/2016"],
#"03/2016" : UrlDict["03/2016"]}
moodDict = {}
count = ... |
# 1052. Grumpy Bookstore Owner
class Solution:
def maxSatisfied(self, C: List[int], G: List[int], X: int) -> int:
hi = cur = sum(C[:X]) + sum(C[i] for i in range(X, len(C)) if G[i] == 0)
for i in range(X, len(C)):
if G[i] == 1:
cur += C[i]
if G[i-X] =... |
str1 = input("Enter a string: ")
str2 = input("Enter another: ")
if not str1 == str2:
print(str1 + str2)
else:
print("Two strings are identical.")
|
"""Support for GitHub Actions."""
from typing import cast, Any, Dict
import time
import jwt
from gidgethub.abc import GitHubAPI
def get_jwt(*, app_id: str, private_key: str) -> str:
"""Construct the JWT (JSON Web Token), used for GitHub App authentication."""
time_int = int(time.time())
payload = {"iat"... |
def find_matching_strings(list):
lower_list = map(lambda x: x.lower, list)
words_dict = {}
true_word_count = {}
occurrences = {}
for word in list:
if word.lower() not in words_dict:
words_dict[word.lower()] = 1
true_word_count[word] = 1
occurrences[word.lo... |
#!/usr/bin/env python
from __future__ import print_function, division
import numpy as np
import h5py
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import astropy.units as u
from astropy.coordinates import SkyCoord
from glob import glob
import os
def load_data(fnames):
# Load in all the d... |
# -*- coding:utf-8 -*-
import random
"""
t={
"F1":(1,f1)#数量,函数
}"""
def random_func(random_dict):
assemble=[]
for key in random_dict:
assemble+=[key for i in range(random_dict[key][0])]
focus=random.choice(assemble)
return random_dict[focus][1]
#
class RandomFunc():
def __init__(self,ra... |
a = [1, 4, 7, 3, 11, 9, 2, 6, 4, 7]
def find_element(a, p, q, k):
element = None
j = p
povit = a[q]
for i in range(p, q+1):
if a[i] < povit:
tmp = a[i]
a[i] = a[j]
a[j] = tmp
j += 1
tmp = a[j]
a[j] = a[q]
a[q] = tmp
print(a)
... |
# Advent of code day 5
# Open data
advent_input = open('input_5.txt')
advent_data = advent_input.readlines()
advent_data = [x.rstrip() for x in advent_data]
# Create class seat
class Seat:
def __init__(self, str):
start_row = 0
end_row = 127
start_column = 0
end_column = 7
... |
import os
import os.path
import sys
def rename_files(indir, outdir):
files = os.listdir(indir)
print(len(files))
for index, oldname in enumerate(files):
newname = '{0:06}_1.jpg'.format(index)
oldpath = indir + '/' + oldname
newpath = outdir + '/' + newname
#cmd = 'mv {0} {1}'.format(oldpath, newpath)
... |
import socket
import sys
import threading
import time
import errno
from queue import Queue
HEADER_LENGTH=10
all_connections = []
all_address = []
HOST = "localhost"
PORT = 5054
queue = Queue()
username=input("Username:")
username=username+"-helper"
client_socket=socket.socket()
client_socket.connect((HOST,PORT))
clie... |
# -*- coding: utf-8 -*-
from odoo import models, fields, api
from odoo.exceptions import UserError
from datetime import datetime
import logging
class ControlExt(models.Model):
_inherit = 'account.move'
icbp = fields.Float('I.C.B.P.', digits=(12,2), compute="_get_icbp")
def _get_icbp(self):
# rai... |
'''
1644번
소수의 연속합
'''
import sys
from collections import deque
input=sys.stdin.readline
n=int(input())
prime=deque()
p=[i%2 for i in range(n+2)]
p[1]=0; p[2]=1
for i in range(3, n+1, 2):
if p[i]==1:
for j in range(i+i, n+1, i):
p[j]=0
for i in range(2, n+1):
if p[i]: prime.append(i)
l=0... |
# fungsi open
# parameter 1 = nama filenya
# parameter 2 = mode
# mode mode :
# r = read = membaca file
# w = write = menulis ke sebuah file , jika file sudah ada isinya , maka isi tersebut akan di tiban
# a = append = menambahkan data ke dalam file
# r+ = user bisa baca dan bisa nulis
user = open("user.tx... |
## https://docs.djangoproject.com/en/1.11/topics/db/managers/
## https://docs.djangoproject.com/en/dev/howto/custom-management-commands/#howto-custom-management-commands
## https://medium.com/@bencleary/django-scheduled-tasks-queues-part-1-62d6b6dc24f8
## https://medium.com/@bencleary/django-scheduled-tasks-queues-part... |
#!/usr/bin/env python3
"""
Convert a LBANN model to an ONNX model.
Run "./lbann2onnx.py --help" for more details.
"""
import argparse
import re
import onnx
import os
import lbann.onnx.l2o
def parseInputShape(s):
name, shape = re.compile("^([^=]+)=([0-9,]+)$").search(s).groups()
return (name, list(map(int, s... |
from DateTime import DateTime
import transaction
portal = app.recensio
broken = portal.portal_catalog.search(
{
"review_state": "published",
"effective": {"query": DateTime("1000/01/02 1:00:00 GMT+0"), "range": "max"},
}
)
for i, brain in enumerate(broken):
obj = brain.getObject()
ef... |
import re
import itertools
def isPrime(n):
if n == 2:
return 0
if n == 3:
return 0
if n % 2 == 0:
return 2
if n % 3 == 0:
return 3
i = 5
w = 2
while i * i <= n:
if n % i == 0:
return i
i += w
w = 6 - w
return 0
def gen... |
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 02 23:06:02 2018
@author: Lucas
"""
import random
def AM(x1, x2):
ret = []
for i in range(len(x1)):
ret.append((x1[i] + x2[i]) / 2.0)
return ret
class Monomial:
MIN_POWER = -5
MAX_POWER = 5
def __init__(self, n, a=None, c=1):
... |
from django.db import models
from datetime import datetime
class Roll(models.Model):
producer = models.CharField(max_length=20)
number = models.IntegerField()
batch = models.IntegerField(null=True)
size = models.CharField(max_length=20)
coating = models.CharField(max_length=20)
hardness = model... |
from collections import Counter
def error_corrected_message(signal_text):
transmissions = signal_text.splitlines()
return ''.join(Counter(repeated_character).most_common()[0][0]
for repeated_character in zip(*transmissions))
def hidden_message(signal_text):
transmissions = signal_tex... |
import os
import uuid
from dotenv import load_dotenv
from flask import Flask, flash, redirect, url_for, send_from_directory, render_template
from flask_bootstrap import Bootstrap
from flask_wtf import FlaskForm
from flask_wtf.file import FileRequired, FileAllowed
from werkzeug.utils import secure_filename
from wtforms... |
from alpaca import Alpaca
from utils import load_test, split_df, TimeSeriesResampler,confusion_matrix
import time
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
from sklearn.pipeline import Pipeline
import numpy as np
import pandas as pd
if __name__ == '__main__':
X, y = l... |
# coding: utf-8
# In[2]:
import torch
import os
import numpy as np
os.environ["CUDA_VISIBLE_DEVICES"]= "0"
os.environ['CUDA_LAUNCH_BLOCKING'] = "1"
import torch.backends.cudnn as cudnn
cudnn.benchmark = True
import modelio
import feature_handler
import masked_softmax
# In[ ]:
def prepare_training_data_vocab(tr... |
from selenium import webdriver
from scrap import scrap
import settings
if __name__ == "__main__":
# ドライバー設定
driver = webdriver.Chrome(r"chromedriver.exe", options=settings.chrome_options)
#ログイン
scrap.log_in_amazon(driver)
# 注文履歴へ
scrap.go_to_order_history(driver)
#
|
class emp:
sal=10
name="anonymous"
def __init__(self,name,sal): #create constuctor
self.name=name
self.sal=sal
def disp(self):
print(self.name," salary:",self.sal)
emp1=emp("yopp",123)
emp1.name="yoss"
emp1.disp()
emp2=emp("kaka",34)
emp2.disp()
print(h... |
# -*- coding: utf-8 -*-
from main import DOORPI
logger = DOORPI.register_module(__name__, return_new_logger = True)
import time
import datetime
from resources.event_handler.classes import SingleAction
class TimeTickDestroyAction(SingleAction): pass
class TimeTicker:
last_time_tick = 0
last_realtime_event = 0... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 24 00:22:57 2019
@author: kevin
"""
import cv2
import numpy as np
import PyQt5 import QtCore, QtGui, QtWidgets
from Epc660 import *
class ImageThread(QThread, camera):
signal = pyqtSignal('PyQt_PyObject')
def __init__(self, camera):
... |
##eta keno kaj korlo na???
import re
class Solution:
def mostCommonWord(self, paragraph, banned):
banned=set(banned)
words = re.findall(r'\w+', paragraph.lower())
print(words)
for i in words:
if i in banned:
words.remove(i)
dic = collections.Counte... |
# -*- coding: utf-8 -*-
import base64
from datetime import date, datetime
from dateutil.relativedelta import relativedelta
from odoo import api, fields, models, _
from odoo.addons.hr_payroll.models.browsable_object import BrowsableObject, InputLine, WorkedDays, Payslips
from odoo.exceptions import UserError, Validati... |
import os
from .default import *
SITE_URL = 'http://127.0.0.1:8000'
SPOTIFY_CLIENT_ID = os.getenv('SPOTIFY_CLIENT_ID')
SPOTIFY_CLIENT_SECRET = os.getenv('SPOTIFY_CLIENT_SECRET')
SPOTIFY_REDIRECT_URL = '{}/spotify_authorize_callback/'.format(SITE_URL)
|
import ast
import logging
from State import *
from Property import *
from SymbolicVariable import *
from Z3Solver import *
from BinarySolver import *
class Tree:
"""The Computation Tree, which walks down the Python Abstract Syntax Tree (AST)
Parameters
----------
code : string
A string of pyt... |
import argparse
import tensorflow as tf
from tensorflow.keras.callbacks import Callback
import ray
import ray.train as train
from ray.data import Dataset
from ray.data.dataset_pipeline import DatasetPipeline
from ray.train import Trainer
class TrainReportCallback(Callback):
def on_epoch_end(self, epoch, logs=No... |
import sys
def day_name(num):
""" Get day from int """
if num == 0:
return "Sunday"
elif num == 1:
return "Monday"
elif num == 2:
return "Tuesday"
elif num == 3:
return "Wednesday"
elif num == 4:
return "Thursday"
elif num == 5:
return "Friday... |
# encoding: utf-8
import time ,os,time,datetime,random
random.seed(time)
# index select max(aid) from idbase;
index = 1
def Shuffer_1(start, end,fielname):
global index
glist=[i for i in range(start, end+1)];
random.shuffle(glist)
with open(fielname, 'w') as f:
for use in glist:
... |
import requests
from requests_oauthlib import OAuth1
import json
from urllib.parse import urlparse
import pprint
params = {
'app_key':'2mM1ISxurDZiulWBJdqa9WDcO',
'app_secret':'YtGkV6HuPukSI8OZHsHXLaOQzRPfvm4uwuRZYdsh5pRru79f9e',
'oauth_token':'334499616-T6vgrPbGZEc8yWPF3PZlQ9qNWg3cqbHWRwMulZxJ',
... |
"""
app
"""
from flask import Flask, make_response, request
from flask_cors import CORS
from json import loads, dumps
from os import remove
from database_controller import DatabaseController
app = Flask(__name__)
CORS(app, resources={"/*": {"origins": "*"}})
def reset_database():
"""
resets basic database
... |
# -*- coding: utf-8 -*-
# @Time : 2019/3/25 15:54
# @Author : 昨夜
# @Email : 903165495@qq.com
from sqlalchemy import Column, String, Integer
from app.models.base import Base
class DurationPage(Base):
__tablename__ = 'duration_page'
id = Column(Integer, primary_key=True, comment='id')
duration_id = C... |
tupla = (100, "Hola", [1, 2, 3], -50)
for dato in tupla:
print(dato)
# Funciones de tuplas
print("La cantidad de datos que tiene esta posicion (Solo si son listas) en la tupla es :",len(tupla[1]))
print("El índice del valor 100 es :", tupla.index(100))
print("El índice del valor 'Hola' es :", tupla.index("Hola")... |
import random
def rollDice():
roll = random.randint(1,100)
return roll
# Now, just to test our dice, let's roll the dice 100 times.
x = 0
while x < 100:
result = rollDice()
print result
x+=1
|
from django.urls import path
from . import views
urlpatterns = [
path('', views.favorites, name='favorites'),
path('add_favorites/<int:asset_id>/', views.add_favorites, name='add_favorites'),
path('remove_favorites/<int:asset_id>/<int:favorites_item_id>/', views.remove_favorites, name='remove_favorites'),
... |
"""
This module contains the view for a user login/session creation
"""
from flask_restful import reqparse, Resource
from api import db
from api.models.account import Account
from flask import current_app
from passlib.hash import pbkdf2_sha256
import datetime
import jwt
class Login(Resource):
def post(self):
... |
"""Expected test results"""
TEST_1 = """[\
{\
"category": "Local Eats", \
"venues": [{"name": "Dagu Rice Noodle (Winnipeg)", "address": "102-1855 Pembina \
Hwy, Winnipeg, MB R3T 2G6"}, {"name": "Smitty's Family Restaurant (St. James)", "address": \
"1017 St James St, Winnipeg, MB R3H 0K6"}, {"name": "Food Trip Kitchen"... |
#Brief intro about selenium
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
# Special keys can be sent using Keys
#step1: create object of webdriver
driver = webdriver.Firefox()
print(driver)
#step2: get the web
driver.get("http://www.python.org")
print(driver.title)
assert "Python" ... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import os
import sys
import logging
import requests
import datetime
from datetime import timedelta
from jira import JIRA
import base64
import smtplib
from email.mime.text import MIMEText
reload(sys)
sys.setdefaultencoding("utf8")
###################### tools ##########... |
#!/usr/bin/python
import pymongo
import StockLib
from datetime import datetime, timedelta
client = pymongo.MongoClient('mongodb://mongodb_host:27017/')
db = client['stock']
stockLib = StockLib.StockLib()
startDate = '2014-01-01'
endDate = '2020-01-01'
'''
Each day, get top earnings estimates increased top 20 indus... |
import sys
import cv2 as cv
from PyQt5 import uic, QtWidgets, QtCore
from PyQt5.QtWidgets import QLabel, QApplication, QMainWindow, QFileDialog, QAction, QMessageBox
from PyQt5.QtGui import QPixmap, QImage, QIcon
from ip import ImageProcessing as IP
class Ui_MainWindow(QtWidgets.QMainWindow):
def __i... |
# Aa Aa - Aa a Aa Aa a AaN
N
'''N
Aa a a a a a a a aN
'''N
N
# Aa Aa a Aa Aa aN
a a a aN
a a('a.a', a='a-0') a a_a:N
a_a = a(a(a_a))N
a_a_a = a_a[0]N
a_a = a_a[0:]N
N
a('Aa a:')N
a(a_a_a)N
a('Aa a a')N
a(a_a[0])N
N
# Aa a Aa, AaAa, AaAa a Aa a a a a aN
# Aa a a a a a a a (Aa, a, Aa, '')N
# Aa a a a a a a a ... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# 时间复杂度O(n),空间复杂度O(1)
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
i, p = 0, head
while p:
i += 1
p = p.next
if i < 2:
... |
import numpy as np
import torch.nn as nn
from web_processor import WebProcessor
from rel_predictor import RelPredictor
from link_evaluation import LinkEvaluation
from link_evaluation import CNN
class Web:
def __init__(self, query, W2V):
self.processor = WebProcessor(query, model=W2V)
se... |
# Turn
from AI import*
from player_class import*
from AI_foreign_affairs import*
from copy import deepcopy
from Scenarios.historical.Scenario import*
from Scenarios.BalanceScenario.Scenario import*
def AI_turn(players, player, market, relations, provinces):
if len(player.provinces.keys()) < 1:
ret... |
import operator
import pathlib
from dataclasses import dataclass
from typing import Dict
def main():
instructions = instruction_parser(pathlib.Path('puzzle_input.txt').read_text())
acc = process(instructions)
print(acc)
@dataclass
class Operation:
instruction: str
arg: int
op: operator
... |
from turtle import Turtle, Screen
tim = Turtle()
screen = Screen()
angle = 0
def move_forwards():
tim.forward(10)
def move_backwards():
tim.backward(10)
def turn_anticlockwise():
global angle
angle += 5
tim.setheading(angle)
# tim.setheading(tim.heading + 5)
def turn_clockwise():
gl... |
def find_uniq(arr):
n = None
duplicate = None
test = arr[0]
for i in range(1,3):
if arr[i] == test:
duplicate = arr[i]
break
else:
duplicate = arr[i]
s = set(arr)
for i in s:
if i != duplicate:
n = i
r... |
# O(m+n) time where m and n are the number of characters in the letter and magazine respectively
# O(L) space where L is the number of distinct letters appearing in the letter
def is_letter_constructible_from_magazine(letter_text, magazine_text):
return (not collections.Counter(letter_text) - collections.Counter(ma... |
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
import uuid
from werkzeug.security import generate_password_hash, check_password_hash
import jwt
import datetime
from functools import wraps
from flask_s... |
# -*- coding: utf-8 -*-
#
# Copyright 2020 Nitrokey Developers
#
# Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
# http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
# http://opensource.org/licenses/MIT>, at your option. This file may not be
# copied, modified, or distribute... |
from collections import deque
import collections
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def findClosestLeaf(self, root: TreeNode, k: int) -> int:
graph = collections.... |
# 给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。
#
# 最高位数字存放在数组的首位, 数组中每个元素只存储一个数字。
#
# 你可以假设除了整数 0 之外,这个整数不会以零开头。
#
# 示例 1:
#
# 输入: [1,2,3]
# 输出: [1,2,4]
# 解释: 输入数组表示数字 123。
# 示例 2:
#
# 输入: [4,3,2,1]
# 输出: [4,3,2,2]
# 解释: 输入数组表示数字 4321。
class Solution(object):
def plusOne(self, digits):
"""
:type digits: List... |
from django.db import models
from AdmSchedule.models import Schedule
class Config(models.Model):
id = models.AutoField(db_column='ID', primary_key=True) # Field name made lowercase.
effectivedate = models.DateField(db_column='EffectiveDate') # Field name made lowercase.
capacitypercentage = models.Decima... |
import pprint
import sys
import os
# idea 引入自定义模块编译不通过,有红色的下划线,但是运行正常
# 解决办法:右键工程->open module settings->sdks->classpath->添加引入模块所在的路径
import searchTool
pprint.pprint(sys.path) # 打印摸快搜索路径
# pprint.pprint(os.environ) # 打印系统环境变量
# pprint.pprint(searchTool.find_files("E:\\java\\ideaWorkspace\\pythonTest\\tmp","简书"))
dect... |
import sys
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
import scipy as sp
from scipy import ndimage
class BasicImageProcessing():
def __init__(self, _filename, _width, _height):
self.filename = _filename
self.width = _width
self.height = _height
self.img ... |
#!/usr/bin/env python3
import sys,os
Code_path = os.path.dirname(os.path.abspath(__file__))
Project_path = os.path.dirname(Code_path)
serverside = os.path.join(Code_path, "server")
datafile = os.path.join(os.getcwd(), "profile.dat")
#-----------------------------------------------------------------... |
'''
Prepare images for display/processing. We want to scale everything down so we
dont take up a ton of space on the disk. It is not necessary to run this module unless
the raw images are changed.
'''
import cv2
import os
from glob import glob
def process(filename):
img = cv2.imread(filename)
img = cv2.resize(img,... |
"""
Tests for adapters.py
"""
import json
from django.contrib.auth.models import User
from django.test import TestCase
from main.adapters import adapt_model_to_frontend
from main.models import Chromosome
from main.models import Project
from main.models import ReferenceGenome
from main.models import Variant
from main... |
import sqlite3
from employee import Employee
conn = sqlite3.connect(':memory:')
c = conn.cursor()
c.execute("""CREATE TABLE employees(
first text,
last text,
pay integer
)""")
def insert_emp(emp):
with conn:
c.execute("INSERT INTO employees VALUES(:first, :last, :pay)", {'... |
# -*- coding: utf-8 -*-
import sys
import biblioteca
def menu():
print ("Conversor de Medidas")
print (" ")
print ("Digite a opção desejada: ")
print (" ")
print ("1 Conversão de pes para jardas\n")
print ("2 Conversão de polegadas para centimetros\n")
print ("3 Conversão de jardas para met... |
from certification_script.tests import base
from certification_script.fuel_rest_api import with_timeout
class OSTFTests(base.BaseTests):
def run_test(self, test_name):
data = {'testset': test_name,
'tests': [],
'metadata': {'cluster_id': self.cluster_id}}
return s... |
import json
class GetDelivery:
def __init__(self, deliveryID, merchantOrderID, quote, sender, recipient,
cashOnDelivery, schedule, status, courier, timeline, trackingURL, advanceInfo):
self.deliveryID = deliveryID
self.merchantOrderID = merchantOrderID
self.quote = quote
self.s... |
# -*- coding: utf-8 -*-
import os
import sys
from os import path
from xmldiff import main
sys.path.append(path.join(path.dirname(__file__), '..', 'ccelib'))
from ccelib.v1_00 import leiauteCCe as cce
def test_in_out_leiauteCCe():
path = 'tests/cce/v1_00/leiauteCCe'
for filename in os.listdir(path):
i... |
# -*- coding: utf-8 -*-
import logging
import numpy as np
from network import NetworkFunction
from hobotrl.tf_dependent.distribution import NNDistribution, DiscreteDistribution, NormalDistribution
from core import Policy
class GreedyPolicy(Policy):
def __init__(self, q_function):
"""
:param q_fun... |
import copy
import sys
import matplotlib.pyplot as plt
import numpy as np
import re
from glob import glob
import cv2
np.set_printoptions(threshold=sys.maxsize)
def read_pgm(filename, byteorder='>'):
with open(filename, 'rb') as f:
buffer = f.read()
try:
header, width, height, m... |
#some colors definitions
black = 0, 0, 0
yellow = 255, 255, 0
green = 0,255,0
blue = 0,0,150
red = 255,0,0
dimred = 125,0,0
white = 255,255,255
gray = 125,125,125
|
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:light
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.3'
# jupytext_version: 1.0.1
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
import pandas as pd
... |
# Generated by Django 3.1.2 on 2020-10-03 23:47
import django.contrib.gis.db.models.fields
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('api', '0001_initial'),
]
operations = [
migr... |
from helpers import swap_in_array, timeit
def insert_sort(unsorted):
'''Sorts a given list inplace using Insertion Sort Algo.
Algorithm: Consider that the array is divided in to 2 subarrays, Left
and Right. Array on Left is sorted while the Right is unsorted. In order
to sort the array we pick an eleme... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2018-07-12 21:07:54
# @Author : flying
import package_test
#导入包的本质->就是解释包下面的__init__文件
#>>>from package
#想要执行包下面的文件,更改__init__.py文件
package_test.test1.test()
|
import solidBoundaryPoint
#x, y, z are the solid body points.
#x1, y1, z1 are the FFD points
def computeTUVData(SolidBoundaryPointArray, FFDPointArray, FFDXMax, FFDXMin, FFDYMax, FFDYMin, FFDZMax, FFDZMin):
for i in range(len(SolidBoundaryPointArray)):
element = SolidBoundaryPointArray[i]
t = (e... |
import random
import numpy as np
import matplotlib.pyplot as plt
def number_of_population():
"""
:return: pocet populacie, ktora sa vygeneruje
"""
return 100
def gems():
"""
:return: pozicie v jednorozmenom poli, kde su ukyte poklady
"""
return [11, 16, 27, 29, 39]
def load_map():
... |
"""
The VORONOI program only accepts meshes in a select few formats.
See [1] for a list of supported filetypes.
This script is intended to generate an AVS-UCD mesh for use in VORONOI,
from a collection of nodes and connectivity.
[1]: http://lagrit.lanl.gov/docs/commands/READ.html
"""
import argparse
import numpy a... |
import datetime
from datetime import date, timedelta
import pandas
import json
import os
import way2sms
import sys
sys.path.append(os.environ.get('TRADING_SOFTWARE')+'/src/1_input_marketdatafetcher/dataparsers/')
import google_history_data_parser as ghdp
import nse_option_data_parser as nodp
###########################... |
n = int(input())
ans = 0 ;
three = [3,6,9,12] # 결론은 최소 공배수 15 전까지는 3의 몫이 최저해
# 15 이상부터 5로 나눠 떨어지면 몫이 최저값
# 그렇지 않으면 나머지가 3으로 떨어졌을때가 최저값
# 이것도 아니라면 5개 짜리 봉지를 먼저 만들어 보고 (5로 빼주고 계속해서 재귀호출)
# 12 이하까지 만들어졌을때 3,6,9,12 중 하나가 만들어지면
# 3으로 나눈값 + 5를 뺀 횟수 (재귀 호출 횟수)=최저값
# 그외는 만들 수 없는 값.
def solution(n):
global ans
... |
from purchase import purchase,discountAmount,createInvoice
from readfiles import readInventory
from updateinventory import updateStock
import datetime
print("Hello!!! This is an electronic store.We sell different kinds of mobile phones,laptops and Harddisks.Please Proceed if you wish to buy.")
def main():
person_n... |
import numpy as np
def print_reproducibility_check(self, reproducible_success, reproducible_result, cochrain_critical_value):
print('--------------------------------------------------------------')
mean, var = self.points_mean_var()
df_numerator = self.count_of_parallel_experiments - 1
df_denominator ... |
from bson.code import Code
from database import db
def run(args):
mapper = Code("""
function() {
var cells = {}
this.grid.cells.forEach(function(cell) {
cells[cell.x + "-" + cell.y] = {
"x": cell.x,
"y": cell.y,
"block": cell.block,
... |
from lib2d import res, quadtree, vec, context, bbox
from lib2d.utils import *
import euclid, physicsbody
import pygame, itertools
class PlatformerMixin(object):
"""
Mixin class that contains methods to translate world coordinates to screen
or surface coordinates.
"""
# accessing the bbox by ind... |
from state import *
from accel import *
from indicators import *
from search import *
from bluepy.sensortag import *
import bluepy.btle as btle
import time, os
NUM_TAGS = 3
USB_PREFIX = '/media/'
LOCAL_PREFIX = '/home/pi/local-data/'
DEFAULT_SPIN_TIME = 1 #sec
if __name__ == '__main__':
# Turn off these debugg... |
# Generated by Django 3.0.2 on 2021-06-06 21:11
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('assesment', '0001_initial'),
('user', '0005_userprofile_status'),
]
operations = [
migrations.Alter... |
import abc
class HttpRequest:
def request(self):
raise NotImplementedError
class HttpGet(HttpRequest):
# This class will try to execute the method request to receive a NotImplementedError
...
class File(abc.ABC):
@abc.abstractmethod
def parse_content(self):
return 'parsed con... |
import telnetlib
import time
import re
import random
import traceback
import tenacity
from baremetal.common import exceptions
import logging
from baremetal.common import locking as sw_lock, exceptions, utils, jsonobject, http
from baremetal.conductor import models
from oslo_config import cfg
from tooz import coordina... |
#Instituto Tecnologico de Costa Rica
#Escuela de Ing. en Computacion
#Tarea 2 - Requerimientos de Software
#Autores: * Jeison Esquivel Samudio (2013018688)
# * David Valverde Garro (2016034774)
# Comentarios: Adjunto esta una version mejorada del diagrama de actividad
# que incorpora las ideas de los diagr... |
#!/usr/bin/env ambari-python-wrap
"""
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... |
import os
import requests
import discord
from dotenv import load_dotenv
from discord.ext import commands
def filename(url, iden):
file = ''
for char in url:
if char not in './:':
file += char
file += iden
return file
usersitelist = {}
with open("sites.txt") as file:
for line i... |
#!/usr/bin/env python
import sys
import rospy
import rospkg
import cv2 as cv
import numpy as np
import constants as CONST
from sensor_msgs.msg import CompressedImage
img = None
hsv = None
wait = False
click = False
number = None
is_mask = False
sub_sampling = 0.5
camera_position = None
image_width, image_height = No... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.