text stringlengths 38 1.54M |
|---|
from TestHelperSuperClass import testHelperSuperClass
import passwordmanpro_cli
from unittest.mock import patch
import samplePayloadsAndEnvs
class test_AppObj(testHelperSuperClass):
@patch('passwordmanpro_cli.AppObjClass._callGet')
def test_getSinglePassword(self, getResoursesResponse):
getResoursesResponse.si... |
import pytest
from hickory.every_launchd import *
def test_seconds_interval_to_seconds():
intervals = ["10", "10s", "10sec", "10secs", "10seconds"]
seconds = [interval_to_seconds(i) for i in intervals]
assert all([s == 10 for s in seconds])
def test_minutes_interval_to_seconds():
intervals = ["30m"... |
#-*- coding:utf-8 -*-
import xlrd
import json
import codecs
from datetime import datetime
from xlrd import xldate_as_tuple
def get_9th_daibiao():
file_path = '../data/9th_daibiao.xls'
sheetno = 0
suggest_unit_col = 0
name_col = 3
sex_col = 4
nation_col = 5
birthDay_col = 6
political... |
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
return HttpResponse("<h2>Porumbeii sunt agenti lui Mussolini</h2>") |
from typing import *
import hydra
import torch
import random
import numpy as np
from pytorch_lightning import Trainer
from loguru import logger
from model import Classifier
@hydra.main(config_path="config.yaml")
def train(config):
logger.info(config)
np.random.seed(42)
random.seed(42)
if torch.cuda... |
from django.db import models
import datetime
from multiselectfield import MultiSelectField
from django.contrib.auth.models import User
# Create your models here.
from SanteLib import config
class Address(models.Model):
street = models.CharField(max_length=200)
city = models.CharField(max_length=30)
stat... |
import os, time
from bs4 import BeautifulSoup
import urllib
from selenium import webdriver
SCHEME = "https"
DOMAIN = "carbon.now.sh"
def carbon(code, lang="auto"):
config = {
"pv": "10px",
"ph": "10px",
"t": "vscode",
"wa": "false",
"l": lang,
"code": code
}
... |
import networkx as nx
import csv
import helper as hp
import sys
from lib import structural_holes2 as sx
from lib import structural_holes as sx1
import sys,getopt
import time
def main(argv):
#Standardvalues
partitionfile = "data/partitions/final_partitions_p100_200_0.2.csv"
project = "584"
to_pajek = False
... |
# Lecture 5 if Statements
# import this
# a = [1, 2, 3]
# b = [1, 2, 3]
# print(id([1, 2, 3]))
# print(id(a))
# print(id(b))
# print(a == b)
# print (a is b)
#x = None
#print(id(x))
#print(id(None))
#print(x == None)
#print(x is None)
#y = []
#print(y == None)
#print(y is None)
#print(not '0')
#print( 0 or -1 )
... |
"""
This file contains some constants that represent directions like up or left.
The constants themselves are numbers.
"""
LEFT = 0
RIGHT = 1
UP = 2
DOWN = 3
|
## @file
## @brief Assembler lexer.
import os
import sys
sys.path.insert(1, os.path.join(sys.path[0], '../../external/ply/'))
import ply.lex as lex
import Util
## @brief Reserved word types.
## @details Holds every accepted instruction and the corresponding type.
## @TODO Optimize this for easier localization.
rese... |
# -*- coding: utf-8 -*-
# Author: Konstantinos
from collections import OrderedDict
import numpy as np
import scipy as sp
import itertools as it
import scipy.sparse as sps
import matplotlib.pyplot as plt
import multiprocessing
import abc
import time
class Node:
dictionary = {'x':0, 'y':1, 'z':2, 'rx':3, 'ry':4,... |
class Card(object):
def __init__(self, contents=None):
self.contents = contents
self.hand = None
if contents is not None:
self.name = contents.name
def can_play(self):
side = self.hand.board.playerTurn
availMana = self.hand.board.manaCurrent[side]
co... |
from flask import Blueprint, jsonify, request
import sqlalchemy
from db import db
from helpers import status_response, row_dictify
from models.user import User
blueprint = Blueprint("user", __name__)
prefix = "/user"
@blueprint.route("/")
def get_all_user():
user_list = User.query.all()
return jsonify([row... |
from django.db import models
from home.models import clasemodelo
from inv.models import Producto
# Create your models here.
class ComprasEnc(clasemodelo):
fecha_compra=models.DateField(null=True, blank=True)
observacion=models.TextField(blank=True,null=True)
no_factura=models.CharField(max_length=100)
f... |
'''Question3 ) Write a program for array rotation?'''
n = int(input("Enter the number of elements required: "))
array = []
for i in range(0, n):
element = input("Enter the element: ")
array.append(element)
print("Before rotation :" , "\narray = ", array)
steps = int(input("Enter a positive number for left ... |
import turtle as t
t.pensize(5)
for i in range(0, 1440):
t.forward(1)
t.left(0.25)
t.done()
|
"""api URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based ... |
import torch
import torch.nn as nn
from models.multi_headed_attn import MultiHeadedAttention
from models.psition_ffn import PositionwiseFeedForward
from models.embedding import Embeds
class DecoderLayer(nn.Module):
def __init__(self, config):
super().__init__()
self.self_attn = MultiHeadedAttentio... |
from django.shortcuts import render
from django.http import JsonResponse
def index(request):
data = {
'key1': 'data1'
}
return JsonResponse(data)
|
from django.contrib import admin
from .models import Post,Userdetails
admin.site.register(Post)
admin.site.register(Userdetails) |
from compile.util.python_compiler import python_runner
from compile.util.java_compiler import java_runner
commands = {
'python': {
2: 'python',
3: 'python3'
},
'java': {
8: 'javac'
}
}
extensions = {
'python': '.py',
'java': '.java'
}
def get_command(language, version... |
import json
import os
import requests
from nose.tools import *
import sys
import unittest
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
path_dir = os.path.join(ROOT_DIR, "utils")
sys.path.append(path_dir)
from main_functions import *
class TestDashboard(unittest.TestCase):
def test_ge... |
# Numa eleição existem três candidatos. Faça um programa que peça o número total de eleitores. Peça para cada
# eleitor votar e ao final mostrar o número de votos de cada candidato.
eleitores = int(input('Numero de eleitores: '))
count_1 = 0
count_2 = 0
count_3 = 0
for x in range(1, eleitores + 1):
votos = int(in... |
import urllib.request, json
def main():
with urllib.request.urlopen("https://demo1684309.mockable.io/names") as url:
data = json.loads(url.read().decode())
print(data)
names_in_alphabetical_order = arrange(data)
print('---Names is---')
print(names_in_alphabetical_order)
... |
from django.db import models
from geofr.constants import REGIONS_WITH_CODES, DEPARTMENTS_WITH_CODES
class RegionField(models.CharField):
"Model fields to store a single french region." ""
def __init__(self, *args, **kwargs):
kwargs["max_length"] = kwargs.get("max_length", 2)
kwargs["choices... |
#Uses python3
import sys
def lcs2(s, t):
dp_result = [[x for x in range(len(s) + 1)] for y in range(len(t) + 1)]
for y in range(len(t) + 1):
dp_result[y][0] = y
for i in range(1, len(s)+1):
for j in range(1, len(t)+1):
insert_op = dp_result[j-1][i] + 1
delete_op = ... |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import os
import sys
import time
gits_filename = "gits.txt"
backup_dir = ""
gits = []
def process_one_git(one_git):
print(one_git)
os.system(f'git clone {one_git}')
def get_date():
now = time.localtime()
now_time = time.strftime("%Y%m%d_%H%M%S", now)
return n... |
#!/usr/bin/env python
"""Stacker module for creating an ECS Service."""
from troposphere import (
And, Equals, If, Join, Not, Output, Ref, autoscaling, ec2, iam, AWSHelperFn, Base64, ecs
)
from troposphere.autoscaling import MetricsCollection
from troposphere.policies import (
UpdatePolicy, AutoScalingRolling... |
import requests
def handle_request(request):
try:
request.raise_for_status()
return request
except requests.exceptions.HTTPError as e:
print(f"HTTP error: {e}")
except requests.exceptions.ConnectionError as e:
print(f"Connection error: {e}")
except requests.exceptions.T... |
import rosbag
import argparse
import os
import glob
import re
import numpy as np
from cv_bridge import CvBridge
from sensor_msgs.point_cloud2 import read_points, create_cloud_xyz32
from sensor_msgs.msg import CameraInfo
from src.segmentation import PointCloudSegmentation
from src.detections import MaskRCNNDetections
fr... |
# -*- coding: utf8 -*-
from django import forms
from datetime import timedelta, date, datetime
from django.conf import settings
from inventory.models import Item, Box, Request, InventoryItem, Network
from django.contrib.auth.models import User
def load_dates_initial():
return date.today() - timedelta(days=30), da... |
from subprocess import call
import sys
from os import listdir
from os.path import isfile, join
# Schedule multiple optical flow error tests
# Version numbers for each version to run
#vers_to_run = [1]
vers_to_run = [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 36, 37]
for index in range(0,len(vers... |
from bdpair_reg import bdpair_reg
from Gau_one import Gau_one
import pandas as pd
import scipy as sp
class tune_table(object):
def __init__(self, pandasfiledataframe):
self.pfdf = pandasfiledataframe
self.FittingAll = pd.DataFrame(columns = ['aij_int', 'bij_int'])
#
def gettable(self, ifsav... |
from __future__ import absolute_import
# Tests for ThriftField.
# Some parts based on http://www.djangosnippets.org/snippets/1044/
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership... |
# coding=utf-8
import os
import pytest
import rospy
def get_output_file(argv):
for arg in argv:
if arg.startswith('--gtest_output'):
return arg.split('=xml:')[1]
raise RuntimeError('No output file has been passed')
def get_add_args(argv):
# don't include the --gtest, as that is the ... |
from django.contrib.auth.mixins import UserPassesTestMixin
from django.views.generic import TemplateView, CreateView, UpdateView, DeleteView, DetailView
from django.urls import reverse
from matirbank.filters import MatirBankFilter
from matirbank.forms import MatirBankForm
from matirbank.models import MatirBank
from pe... |
import struct
import numpy as np
import sys
from sklearn.decomposition import PCA
class Constants:
path_images = 'train-images.idx3-ubyte'
path_labels = 'train-labels.idx1-ubyte'
class PreprocessData:
@classmethod
def get_images(cls, path):
with open(path, 'rb') as f:
# loading h... |
from enum import Enum
from pydantic import BaseModel
class ImmutableModel(BaseModel):
class Config:
allow_mutation = False
class DrivingMode(str, Enum):
ECO = "ECO"
COMFORT = "COMFORT"
SPORT = "SPORT"
class AggressiveMode(Enum):
Mode1 = 1
Mode2 = 1.2
Mode3 = 1.3
class Engine... |
# for i in range(1,20):
# print ("i is now {0}".format(i))
#
# number = "123,456,789,0000"
# for i in range(0, len(number)):
# print (number[i])
number = "123,456,789,0000"
cleanedNumber = ''
for i in range(0, len(number)):
if number[i] in "0123456789":
cleanedNumber = cleanedNumber + number[i]
ne... |
from sklearn import tree
#Impeative programming in python
a = [10,20]
len(a)
type(a)
print(type(a))
#OOP programming in python
dt = tree.DecisionTreeClassifier()
#Traditional functional programming
age = [1,2,3,4,]
i = 0
for e in age:
age[i] = e + 10
i = i + 1
print(age)
#Convert above traditional functio... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from PIL import Image
import os
import sys
import glob
path = '/Users/tusharnema/Desktop/opencv/google-images-deep-learning/images/taylor'
dirs = os.listdir(path)
save = '/Users/tusharnema/Desktop/opencv/google-images-deep-learning/images/new-taylor'
import glob
imagePaths ... |
import sys
from component import *
def daily():
"""this function should be called only once daily"""
pass
def hourly():
"""this function should be called hourly"""
# changes add's the watch items into playlist
WatchToPlaylist().init()
"""check if the function that needs to be called has been pas... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator, FormatStrFormatter
from datetime import datetime
def mask_data(df, n, _seed ,ignore=[]):
df = df.copy()
vals = df.values
# Create a list of features names without the ignored-features
... |
import os
import sys
def link_duplicates():
with open("hashes.txt", 'r', encoding='utf_8', errors='replace') as hashfile:
hashmap = []
for f in hashfile:
filename = "".join(f.rsplit(" - ", 1)[0:-1])
hash_value = f.rsplit(" - ", 1)[-1]
hashmap.append((filename, ha... |
# ! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "Miller"
# Datetime: 2019/10/29 14:31
import socket
sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sk.connect(("127.0.0.1", 8000))
while True:
sk.send(input(">>>").encode())
data = sk.recv(1024)
print(data.decode())
|
#!/usr/bin/env python
# --------------------------------------------------------
# cuts for the telescope planes
# created on March 30th 2022 by M. Reichmann (remichae@phys.ethz.ch)
# --------------------------------------------------------
from numpy import all
from mod.dut_cuts import DUTCut
class TelCut(DUTC... |
import imtools
from PIL import Image, ImageDraw
from numpy import *
from numpy.ma import floor
from pylab import *
import os
import pickle
def example_pca(save=False):
imlist = imtools.get_imlist('fonts')
im = array(Image.open(imlist[0])) # open one image to get size
m,n = im.shape[0:2] # get the size o... |
import pickle
from matplotlib import pyplot as plt
from Utils.general import count_zeros_in_gradient
path_to_files_gs_15 = './Results/gradients/grad_gs_25/gradients_100.pkl'
path_to_files_gs_67 = './Results/gradients/grad_gs_67/gradients_100.pkl'
path_to_files_igr_50 = './Results/gradients/grad_igr_50/gradients_100.pk... |
from pathlib import Path
from CommonHelper import GVar
from CommonHelper.Common import GetFileName, GetTrainedModelFolder, LoadFileToDict, GetPredictESNFolder
from CommonHelper.GVar import tblFunctionList, tblModel
from keras.models import load_model
from LogHelper.ReadFile import LogFileToTraceList
from LogHelper.Sa... |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 24 10:48:07 2015
@author: Administrator
"""
import pyaudio
import wave
import threading
import queue
import numpy as np
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"
data =[]
p = pyaudio.PyAudio()... |
from typing import List, Dict, Tuple
from collections import defaultdict, namedtuple
Edge = namedtuple("Edge", ["start", "end"]) # represents an edge
def form_de_bruijn_graph(kmers: List[str]):
graph = defaultdict(list) # map kmer string to node object
prefix_to_node = defaultdict(list)
for kmer in kmers:
graph... |
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import xlrd
# Bitcoin market report from 2018
loan_data = "BTC.xls"
# reading in of .xls data
loan_book = xlrd.open_workbook(loan_data, encoding_override="uft-8")
loan_sheet = loan_book.sheet_by_index(0)
data = np.asarray([[loan_sheet.row_val... |
from time import sleep
import os
import csv
import usb.core
import numpy as np
import time
# Helper Functions
def translate(value, leftMin, leftMax, rightMin, rightMax):
""" This helper function scales a value from one range of values to another. It is used in our python spring implementation.
Much... |
from TeachersGUI import *
from tkinter import messagebox
from Query import *
class Teachers:
def __init__(self, master, main_window):
self.master = master
self.main_window = main_window
self.grade_list = []
self.subject_list = []
self.teachers = TeachersGUI(self.master)
... |
#!/usr/bin/python3
"""test"""
import unittest
from models.base import Base
class TestBase(unittest.TestCase):
"""test"""
def test1(self):
"""test 1"""
b = Base(48)
self.assertEqual(b.id, 48)
def test2(self):
"""test 2"""
b = Base()
self.assertEqual(b.id, 1)... |
"""
141. Linked List Cycle
src: https://leetcode.com/problems/linked-list-cycle/
Given head, the head of a linked list, determine if the linked list has a cycle in it.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, ... |
# -*- coding:UTF-8 -*-
def countBirths() :
ret = []
for y in range(1880 , 2018) :
count = 0
fileName = 'names/yob%d.txt'%y
with open(fileName , 'r') as f :
data = f.readlines()
for d in data :
if d[-1] == '\n' : # d 의 마지막요소가 개행문자인 경우
... |
import pytest
from appium import webdriver
class TestElementLocation():
def setup(self):
desired_caps = {}
desired_caps['platformName'] = 'Android'
# desired_caps['platformVersion'] = '6.0'
desired_caps['deviceName'] = '127.0.0.1:21503'
desired_caps['appPackage'] = 'com.xueq... |
from django.urls import path
from . import views
app_name='diary'
urlpatterns = [
path('', views.IndexView.as_view(), name="index"),
path('inquiry/', views.InquiryView.as_view(), name='inquiry'),
path('diary-list/', views.DiaryListView.as_view(), name="diary_list"),
path('diary-detail/<int:pk>/', vie... |
# 下面介绍两种文本向量化
# 方法一:
def tfidf(corpus):
# 词频矩阵:矩阵元素a[i][j] 表示j词在i类文本下的词频
vectorizer = CountVectorizer()
# 统计每个词语的tf-idf权值
transformer = TfidfTransformer()
freq_word_matrix = vectorizer.fit_transform(corpus)
#获取词袋模型中的所有词语
word = vectorizer.get_feature_names()
tfidf = transformer.fit_tra... |
import webapp2
import jinja2
import os
import urllib
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape=True)
class Handler(webapp2.RequestHandler):
def write(self, *a, **kw):
self.response.write(*a,... |
# Solution 1
# O(n) time / O(n) space
def findSuccessor(tree, node):
inOrderTraversalOrder = getInOrderTraversalOrder(tree)
for idx, currentNode in enumerate(inOrderTraversalOrder):
if currentNode != node:
continue
if idx == len(inOrderTraversalOrder) - 1:
return None
... |
#coding=utf-8
__author__ = 'hqx'
import time
#登陆操作
def login(run,phone,code):
try:
run.input_phone(phone)
run.input_code(code)
run.click_privacy()
run.click_login()
run.mes_person()
run.saveScreenshot('login')
time.sleep(1)
except Exception as e:
print(e)
#登出操作
def logout(run):
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import cv2
import numpy as np
import os
os.chdir(os.path.dirname(os.path.abspath(__file__)))
img = cv2.imread('photo1.jpg')
result3 = img.copy()
# img = cv2.GaussianBlur(img,(3,3),0) # 高斯滤波,用来降噪
# gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) # 灰度化,边缘检测要求输入灰度图... |
"""urlshortener URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Clas... |
import requests
from settings import valid_email, valid_password, name, animal_type, age
class PetFriends:
def __init__(self):
self.base_url="http://petfriends1.herokuapp.com/"
def get_api_key(self, email, password):
headers={
'email': valid_email,
'password': valid_pas... |
import math
l = int(input("Jumlah mahasiswa laki-laki : "))
p = int(input("Jumlah mahasiswa perempuan : "))
JUmlahL = "*"*math.ceil(l/10)
jumlahP = "*"*math.ceil(p/10)
print("Laki-laki : " + JUmlahL + "("+str(l)+")")
print("Perempuan : " + jumlahP + "("+str(p)+")") |
import math
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
def score_(y, pred):
print('RMSE : ', math.sqrt(mean_squared_error(y, pred)))
print('MAE : ', mean_absolute_error(y, pred))
print('R2 : ', r2_score(y, pred) * 100) |
class Price:
def __init__(self, name: str, symbol: str, price: float, last_updated: str):
self.name = name
self.price = price
self.symbol = symbol
self.last_updated = last_updated
def to_dict(self) -> dict:
return {
'name': self.name,
'symbol': s... |
from __future__ import annotations
import pkgutil
import tomllib
from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence
from importlib.metadata import entry_points
from importlib.resources import files
from typing import TypeVar, Generic, Final
__all__ = ['PluginT', 'Plugin']
#: The plugin type... |
ammo= 17
fear= 3
dealoffer= 0
sulfurmines= 0
tradeoffer= 0
vault= 0
vaultprotect= 0
farms= 0
coalmines= 0
metalmines= 0
walls= 0
quarrytot= 0
metalmineproduce= 0
sulfurmineproduce= 0
oildrillproduce= 0
turnrotate= 1
coalmineproduce= 0
coal= 0
oil= 24
metalore= -1
raidedtimes= 0
quarry= 0
sentpeople= 6
day= 0
camplog= 1... |
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request,'home/index.html')
def contacto(request):
contacto = "Gerardo Medina"
list_directions = ['Cerro del Perote #136 Colinas del Cimatario', 'Casa2']
administradores = [
{'nombre':"Luis", 'apellidos... |
import pandas as pd
import numpy as np
from .data_reader import read, get_data, merge
"""Gets data from data_reader.py and cleans it"""
directory_path = "/Users/jasonterry/Documents/Scripts/Misc/My_stuff/" \
"Kaggle/astro"
metadata_columns = ["object_id", "ra", "decl", "gal_l", "gal_b" "ddf",
... |
from flask import Flask, jsonify
app = Flask(__name__)
@app.route("/api")
def index():
return jsonify({
"message": "api"
})
|
import util
def part1(timestamp, buses):
buses = list(filter(lambda bus: bus != "x", buses))
deltas = {}
for bus in buses:
time = 0
while time < timestamp:
time += bus
deltas[bus] = time - timestamp
bus = min(deltas, key=deltas.get)
return bus * deltas[bus]
... |
from AdditionalFunctions import *
class Unit(object):
def __init__(self,name, id, parentId, employees, children):
self.Name = name
self.Id = id
self.ParentId = parentId
self.Children = children
self.Employees = employees
def AddChild(self, unit):
self.Children.a... |
'''
This script handling the training process.
'''
import os
import argparse
import math
import time
from tqdm import tqdm
import torch
import torch.nn.functional as F
import torch.optim as optim
import torch.utils.data
import transformer.Constants as Constants
import dataset
import vocab
from transformer.Models impo... |
#! /usr/bin/env python
"""Hyperinterval mapping
Repeated hyperinterval finding.
(c) 2011 Jouke Witteveen
"""
import hint
hint.cli_args()
fh = open( '2dboxes', 'w' )
judgement = [ [], [] ]
try:
for hinterval, complexity, keep in hint.hints():
print( "Found:", hinterval, "KEPT" if keep else "DISCARDED" )
x... |
from math import radians, sin, cos, atan, atan2, sqrt
from simplemapplot import make_us_state_map
from time import sleep
#######################
# Name:readStateCenterFile(stateCenterDict)
# Input:
# Output:
# Purpose: reads in the file of state centers as described in the handout
#
def readStateCenterFile(stateCenter... |
import socket
import numpy as np
from select import select
import threading
import time
def clamp(x,min,max):
"Clamps the value x between `min` and `max` "
if x < min:
return min
elif x > max:
return max
else:
return x
def check_server(ip='191.30.80.131', port=23, timeout=3):... |
#!/home/moozg/venvs/kasatest/bin/python
#coding: utf-8
#!/home/moozg/venvs/kasa33/bin/python
from __future__ import division, absolute_import, print_function, unicode_literals
import unittest, os
# misc
from kasaya.conf import set_value, settings
from kasaya.core.lib import comm
from gevent import socket
import gevent,... |
import os
from data_generator.common import *
corpus_dir = os.path.join(data_path, "enwiki")
train_path = os.path.join(corpus_dir, "enwiki_train.txt")
eval_path = os.path.join(corpus_dir, "enwiki_eval.txt")
from data_generator.mask_lm.chunk_lm import DataLoader
class EnwikiLoader(DataLoader):
def __init__(self, ... |
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
import scipy.optimize as opt
file = open("../result/result.txt", "w")
def standard(x):
return 2 + 2 * x
def standard_with_error(x):
return [stats.norm.rvs(0, 1) + i for i in standard(x)]
def mnk_parameter(x, y):
beta_1 = (np.... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.post_list_view.as_view(),name="blog-home"),
path('user/<str:username>', views.user_post_list_view.as_view(),name="user-posts"),
path("about/",views.about,name="blog-about"),
path('post/<int:pk>',views.post_detail_view.as... |
from Extract_Character import *
from Character_Recognizer import *
from digit_recognizer_ import *
import Check_Stolen_Plates
class Get_Plate_Characters:
def __init__(self):
self.cr = Character_Recognizer()
self.nr = Number_Recognizer()
self.Ec = Extract_Characters()
def GetPl... |
from PythonFiles.Screens.screen_inventory import InventoryScreen
from PythonFiles.Screens.screen_game_over import GameOverScreen
from kivy.uix.screenmanager import ScreenManager, NoTransition
from PythonFiles.Screens.screen_crafting import CraftingScreen
from PythonFiles.Screens.screen_shelter import ShelterScreen
from... |
from openpyxl import Workbook
from openpyxl.styles import PatternFill, Alignment, Border, Side, Font
def excel单元格填入(sheet, value, color="FF8C69"):
sheet.value = value
sheet.fill = PatternFill("solid", fgColor=color) # 颜色代码:http://www.114la.com/other/rgb.htm
# 设置数据垂直居中和水平居中
sheet.alignment = Alignment(... |
from setuptools import setup, find_packages
# read the contents of your README file
from os import path
THISDIRECTORY = path.abspath(path.dirname(__file__))
with open(path.join(THISDIRECTORY, "README.md")) as f:
LONGDESC = f.read()
setup(
name="tehran-stocks",
version="0.8.2.2",
description="Data D... |
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import ListView, DetailView, CreateView
from django.views.generic.edit import DeleteView, UpdateView
from.models import models
from .models import Vehicle
from django.urls import reverse_lazy
class VehicleListView(LoginRequiredMixin,L... |
from we7dm.util.commonDM import systemInit
systemInit()
import we7dm.config
import we7dm.recsys.configs
from we7dm.databases.offline import DmDatabase
from we7dm.recsys import ui
from we7dm.recsys.ui import filtering
from we7dm.recsys.predictors.pop import PopPredictor
from we7dm.recsys import similarity
from we7dm im... |
def div(a, b):
print("before")
print(a/b)
print("after")
div(1, 0)
# before
# Traceback (most recent call last):
# File "examples/exceptions/divide_by_zero.py", line 8, in <module>
# div(1, 0)
# File "examples/exceptions/divide_by_zero.py", line 5, in div
# print(a/b)
# ZeroDivisionError: inte... |
fpath = 'input.txt'
contents = open(fpath, 'r').read().split(' ')
contents = list(map(int, contents))
global mdsum
mdsum = 0
def dig(chlist):
global mdsum
while chlist[0] > 0:
chlist[:] = chlist[0:2] + dig(chlist[2:])
chlist[0] -= 1
while chlist[1] > 0:
mdsum += chlist.pop(2)
chlist[1] -= 1
chlist[:] =... |
def postopek(vsebina_datoteke, vnos):
seznam = list(map(int, vsebina_datoteke.split(",")))
for _ in range(40000000):
seznam.append(0)
output = 0
i = 0
baza = 0
while seznam[i] != 99:
if seznam[i] == 1:
a = seznam[seznam[i+1]]
b = seznam[seznam[i+2]]
... |
### Taking a string and changing a letter in the string
def mutate_string(string, position, character):
### Convert string to a list
l = list(string)
### At the given position, change to the given character
l[position] = character
### Join the list back into a string
string = ''.join(l)
### ... |
import re
class Item:
def scrap(self,soup_item,cat):
img_div = soup_item.find('div', {'class': 'listagem-img'})
img_a = img_div.find('a')
img_el = img_div.find('img')
fab = soup_item.find('li',{'class': 'imagem-fabricante'})
fab = fab.find('img')
cash_price = self.price_handle(soup_item,'... |
from mingus.containers import Note
class Tuning:
def __init__(self, notes = None):
self.notes = notes
def __iter__(self):
for note in self.notes:
yield note
Standard = Tuning((Note('E', 4), Note('B', 3), Note('G', 3), Note('D', 3), Note('A', 2), Note('E', 2)))
|
# Doc Handler.py
import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.httpclient
import tornado.gen
import tornado.options
from tornado.escape import json_decode,json_encode
import json, hashlib, pickle, sys, os
from assignment2.IndexerHandler import IndexerHandler
from assignment2.invent... |
import random
import numpy as np
from game_state import GameState
__author__ = 'Anthony Rouneau'
class AlphaBeta(object):
"""
Simple implementation of a cutoff alpha-beta
Assert that the player using this Alpha Beta is the "MAX" player.
"""
def __init__(self, eval_fct, _max_depth=6):
"... |
#
# these files are created by
# Aryaman Godara
#
#
# Any changes for better is accepted, cause these are made in the initial phase of my coding
# It is a bot for sending messages to your whatsapp contacts..
# con:-
# it is not able to find a contact if you haven't recently... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.