text stringlengths 38 1.54M |
|---|
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 3 16:23:18 2021
@author: alexd
"""
"""Hi, here's your problem today. This problem was recently asked by Microsoft:
Given a string, find the length of the longest substring without repeating characters."""
class Solution:
def lengthOfLongestSubstring(self, s):
#... |
"""Proxy for access to framebuffer pixels.
@author: Stephan Wenger
@date: 2012-09-18
"""
import numpy as _np
import glitter.raw as _gl
from glitter.utils import float32, format_to_length, State
class BufferProxy(object):
def __init__(self, mode, dtype=float32, format=_gl.GL_RGBA, context=None):
self._co... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2022 Baidu, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICEN... |
import configparser
import json
from _md5 import md5
from _sha256 import sha256
class EnvServerConfig:
def __init__(self):
self.cf=configparser.ConfigParser()
self.cf.read("./config.ini")
# def getDEV(self,address):
# value=self.cf.get("dev",address)
# return value
... |
from django.conf.urls import patterns, include, url
from django.conf.urls.i18n import i18n_patterns
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings
admin.autodiscover()
urlpatterns = patterns('',
url(... |
#经营性收费
##收费
客户搜索栏="//span[@id='select2-CustomerId-container']/span"
客户搜索栏输入框="//span[@class='select2-dropdown select2-dropdown--below']//input"
下拉选择客户="//ul[@id='select2-CustomerId-results']/li[1]/div"
添加临时费用="//button[@id='btnAddCost']"
标准搜索栏="//span[@id='select2-TemporaryCostChargeItem-container']"
标准搜索栏输入框="//span[@... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import copy
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
fr... |
from django.contrib import admin
from django.urls import path, include
from .api.register import UserRegister
from .api.login import UserLogin
from .api.list import ListUser
from .api.delete import UserDelete
from .api.update import UserUpdate
urlpatterns = [
path('register/' , UserRegister.as_view() , name='user r... |
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
def loss_function(style_weight,content_weight,style_image,content_image,target_image,style_layer,content_layer):
loss = 0.0
for layer in content_layer:
loss += content_weight * content_loss
def content_... |
from pyspark.sql import SparkSession
import time
from pyspark.sql.functions import split, col
class test:
spark = SparkSession.builder \
.appName("DirectKafka_Spark_Stream_Stream_Join") \
.getOrCreate()
table1_stream = (spark.readStream.format("kafka").option("startingOffsets", "latest").opt... |
#. 读取的过程 1 打开文件, 2 读取文件 3 关闭文件
# r: read
#. w: write
#. A : 可读写
==================================
File = open('文件路径', ‘r’) 'r' 只可读, ‘w’,只可写, ‘a+’ 可读写
data = file.read(). 一次性全部读出来
data = file.read(5). 读前5个字符
file.seek(n). 跳过前n个字符
data = file.readline() # only read one line a time
While data:
print(data, en... |
# Script taken from https://github.com/damienjadeduff/all-your-depths-are-belong-to-us/tree/master/scripts
# Matches RGB images with their corresponding depth images
# Modified for Windows OS
import os
import re
from decimal import *
# Returns a map of matched rgb and depth files by comparing timestamps in ... |
#Based on code by Github user SZanlongo
import random
import cv2
import numpy as np
import time
import operator
# Perform edge detection
def hough_transform(img, probabilistic, startTime, profiling):
sumTime = 0
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Convert image to grayscale
if profiling:
... |
from __future__ import division
import pygame, time, math, sys
import cffi
from random import random
from vec import Vec3, Ray, Triangle, Sphere
from mat import Material
pygame.font.init()
myfont = pygame.font.SysFont('Arial MS', 30)
pygame.init()
X = 1000
Y = 500
ffi = cffi.FFI()
screen = pygame.display.set_mode... |
def polygon(idNum,points,style):
res = "<polygon id=\"" + str(idNum) + "\" " + "points=\""
for point in points:
res += str(point[0]) + ',' + str(point[1]) + ' '
return res+ "\" style=\"" + style +"\"/>"
def dot(point,color):
return "<circle cx=\"" + str(point[0]) + "\" cy=\"" + str(point[1]) + ... |
class Solution(object):
def nthSuperUglyNumber(self, n, primes):
"""
:type n: int
:type primes: List[int]
:rtype: int
"""
res=[1]
pos=[0]*len(primes)
while len(res)<n:
minv=float("inf")
sel=0
for j in range(len(prime... |
import numpy as np
import scipy.sparse as sp
import warnings
import logging
import enum
warnings.filterwarnings("error",'Matrix is exactly singular', sp.linalg.MatrixRankWarning)
np.set_printoptions(precision=3, threshold=10000, linewidth=300)
logger = logging.getLogger(__name__)
class SolverStatus(enum.IntEnum):
... |
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
from books.views import AuthorCreateView, AuthorDetailView, BooksListView, BooksByAuthorView
urlpatterns = patterns('',
# url(r'^books/$', 'books.views.home'... |
#!/usr/bin/env python
# encoding: utf-8
"""
is_number.py
Created by Måns Magnusson on 2013-04-09.
Copyright (c) 2013 __MyCompanyName__. All rights reserved.
"""
import sys
import os
def is_number(number):
"""Returns true if the string is a number or False otherwise"""
if type(number) == type(1) or type(numbe... |
import os
from django.conf import settings
import datetime
import openpyxl
import re
import logging
import sys
import os.path
sys.path.append(
os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))
from parsing.models import *
from parsing.parsers.functions import *
def media_mist(filename, co... |
# -*- coding: utf-8 -*-
"""
Created on Mon May 11 20:45:29 2020
@author: user
"""
"""
Code Challenge
Name:
Population Counting
Filename:
Population.py
Problem Statement:
The given input has a number of rows, each with four fields from a table,
Rank,City, Population, State or union terr... |
import sys
file = open(sys.argv[1])
buffer = file.read()
buffer = buffer.split('\n')
wire1 = buffer[0].split(',')
wire2 = buffer[1].split(',')
intersections = [] #List of intersections
wirepoints = {} #Every point on the grid the first wire covers
coord = (0, 0) #Current X and Y coordinate
for lines in wire1:
i... |
from __future__ import print_function
import argparse
import torch
import torch.optim as optim
from gcommand_loader import GCommandLoader, AudioProcessor, spect_loader
import numpy as np
from model import LeNet, VGG
from train import train, test
import os
# Training settings
parser = argparse.ArgumentParser(descriptio... |
from _collections import deque
n, m = map(int, input().split())
data = [[] for _ in range(n+1)]
distance = [0 for _ in range(n+1)]
for _ in range(m):
a, b = map(int, input().split())
data[a].append(b)
distance[b] += 1
def solved():
q = deque()
for i in range(1, n+1):
if distance[i] == 0:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 9 19:23:33 2020
@author: patrickburke
"""
import os
os.chdir('/Users/patrickburke/documents/Learning-Content/Automate-Boring')
#os.path.abspath(path) will return a string of the absolute path of the argument.
#os.path.isabs(path) will return true... |
# list.py
students = [] # liste vide
print(type(students)) # <class 'list'>
fruits = ['Pomme', 'Cerise', 'Fraise']
# les listes sont facilement itérables avec la boucle for
for fruit in fruits:
print(fruit)
print("Premier fruit:", fruits[0]) # affiche Pomme |
import os
import sys
import requests
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QLineEdit, QPushButton
from PyQt5.QtCore import Qt, pyqtSignal
from PyQt5 import uic # Импортируем uic
from PyQt5.QtWidgets import QApplication, QMainWindow
APIKEY = "40d164... |
from django.conf import settings
from django.conf.urls.static import static
from django.urls import path, include
from drf_spectacular.views import (
SpectacularAPIView,
SpectacularRedocView,
SpectacularSwaggerView,
)
from api.urls import urlpatterns as api_urls
# Common urls
# ===========================... |
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
from flask import Flask, flash, render_template, request, redirect, session, url_for
from wtforms import Form, TextField, PasswordField, validators
from wtforms.fields.html5 import IntegerField, EmailField
from passlib.hash import sha256_cr... |
def odwracanie_recursive(L, left, right):
if left >= right:
return None
L[left], L[right] = L[right], L[left]
if left + 1 != right:
odwracanie_recursive(L, left + 1, right - 1)
def odwracanie_iterative(L, left, right):
if left >= right:
return None
for i in range(int((right... |
# Exercise 4
# Create a program that asks user for a number then prints out a list
#of all divisors of that number(number with no reminder)
num = int(input("Please choose a number to divide\n"))
listRange = list(range(1, num+1))
divisorList = []
for x in listRange:
if num % x == 0:
divisorLi... |
def find_pairs_with_given_difference(arr, k):
if arr == []:
return arr
# create the hashset
mapp = set(arr)
# build the solution while checking
solution = []
for el in arr:
higher = el + k
if higher in mapp:
solution.append([higher, el])
return solution
arr = [0, -1, -2, 2, 1]
k = 1... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/6/9 14:13
# @Author : Tang Na
# @Site :
# @File : confparser.py
# @Software: PyCharm Community Edition
import ConfigParser
__all__ = ['cf']
def cf():
'''
:return: 返回解析后的配置文件
'''
cf = ConfigParser.ConfigParser()
cf.read(["../... |
import copy
f = open("input.txt", "r")
maze = [int(line) for line in f]
count = 0
try:
currentIndex = 0
while True:
x = maze[currentIndex]
originIndex = copy.copy(currentIndex)
currentIndex = currentIndex + x
maze[originIndex] = x + 1
count += 1
except Index... |
"""add create_at available_time Artist Table
Revision ID: 98d650b1f984
Revises: fb96a477909e
Create Date: 2020-04-26 21:33:46.216367
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '98d650b1f984'
down_revision = 'fb96a477909e'
branch_labels = None
depends_on = ... |
import random
import time
from copy import copy, deepcopy
import math
def gameOfLife(dim, level, iter, timestep, iterType):
matrix = [ [0] * dim for i in range(dim) ] # create matrix
initState(dim, matrix, level) # create init matrix state
if iterType == 'I':
print("InstantChange:")
iterate_instantChange(dim,... |
import os
import torch.utils.data as data
from PIL import Image
import numpy as np
import random
class CubDataset(data.Dataset):
def __init__(self, image_dir, list_path, input_transform = None):
super(CubDataset, self).__init__()
self.input_transform = input_transform
name_list = []
... |
import numpy
from mpi4py import MPI
from isingMapping import mass2c
import genFit
comm = MPI.COMM_WORLD
size = comm.size
rank = comm.rank
ng = 2
n = 101
center = (n/2,n/2)
mass2lst = genFit.genMass2lst(mass2c,50,28)
mass2rank = [mass2lst[i] for i in range(len(mass2lst)) if i%size == rank]
# mpirun -n 4 python genDat... |
import math
import random
t=1
n=600851475143
s=775146
while t<=s:
if n%t==0:
print(t)
t+=1
|
#!/usr/bin/python2.7
import numpy as np#para cargar numpy
from pylab import *#cargar mtplotlib
import os#cargar herramientas de archivos
import re # use regular patterns
import sys, getopt # system commands
import string # string functions4
import math
#from scipy import linalg as scipylinalg
#from scipy import stats... |
import FWCore.ParameterSet.Config as cms
# Calo geometry service model
#ECAL conditions
from RecoLocalCalo.EcalRecProducers.getEcalConditions_orcoffint2r_cff import *
#ECAL reconstruction
from RecoLocalCalo.EcalRecProducers.ecalWeightUncalibRecHit_cfi import *
from RecoLocalCalo.EcalRecProducers.ecalRecHit_cfi import ... |
from typing import Tuple
import gdsfactory as gf
from gdsfactory import components as pc
from gdsfactory.component import Component
from gdsfactory.types import LayerSpec
@gf.cell
def litho_steps(
line_widths: Tuple[float, ...] = (1.0, 2.0, 4.0, 8.0, 16.0),
line_spacing: float = 10.0,
height: float = 100... |
#!/Users/insightshiga/.pyenv/shims/python
from pyquery import PyQuery as pq
d = pq(filename='dp.html')
d.make_links_absolute('https//gihyo.jp/dp')
for a in d('#listbook > li > a[itemprop="url"]'):
url = d(a).attr('href')
p = d(a).find('p[itemporp="name"]').eq(0)
title = p.text()
print(url, title)
|
#/*
#============================================
#; Title: Python in Action
#; File Name: thomason_calculator.py
#; Author: William Thomason
#; Date: 19 June 2019
#; Description: Calculator Python
#;===========================================
#*/
def add(param1, param2):
return param1 + param2
def subtract(p... |
from datetime import datetime, timedelta
from logging import Logger
from collections import deque
class _ObservationHistory(object):
def __init__(self, maxObservations: int):
self._maxObservations = maxObservations
self._observations = deque()
def addObservation(self, timeSpent: float, workD... |
"""
Given an array of positive numbers and a positive number 'k', find the maximum sum of any subarray of size 'k'.
Example 1:
Input: [2, 1, 5, 1, 3, 2], k=3
Output: 9
Explanation: Subarray with maximum sum is [5, 1, 3].
Example 2:
Input: [2, 3, 4, 1, 5], k=2
Output: 7
Explanation: Subarray wi... |
from django.http import HttpResponse
from django.shortcuts import render, redirect
# Create your views here.
from app_media.forms import UploadFileForm, DocumentForm, MultiFileForm
from app_media.models import File
def upload_file(request):
if request.method == "POST":
upload_file_form = UploadFileForm(r... |
import lxml.etree as et
xml="""
<groceries>
<fruit state="rotten">apple</fruit>
<fruit state="fresh">pear</fruit>
<punnet>
<fruit state="rotten">strawberry</fruit>
<fruit state="fresh">blueberry</fruit>
</punnet>
<fruit state="fresh">starfruit</fruit>
<fruit state="rotten">mango</fruit>
<fruit st... |
from django.shortcuts import render
from django.http import HttpResponse
import os
from datetime import datetime
import winsound
import pygame
def index(request):
<<<<<<< HEAD
return(render(request, 'list.html'))
=======
f = open('log', 'a')
s = ''
if request.META['QUERY_STRING'] == 'lol':
# DogSimulatorTM
... |
from authentication.models import User
from django.db import models
# Create your models here.
from django.utils import timezone
from meeting.models import Meeting
from poll.emails import send_email_remove_option
class MeetingParticipant(models.Model):
participant = models.ForeignKey(User, related_name='partici... |
import logging
import telegram
from telegram.ext import Updater
from telegram.constants import MAX_MESSAGE_LENGTH
from config.settings import TELEGRAM_TOKEN
class TelegramClient:
CHAT_ID = '@ArsenalRepostsTest' # channel name where messages will be sent
def __init__(self):
self.bot = ... |
import cv2
from PIL import Image
import os, glob
import moviepy.video.io.ImageSequenceClip
import shutil
from os import path
import numpy as np
def video2Images(pathOfVideo, folder):
vidcap = cv2.VideoCapture(pathOfVideo)
success, image = vidcap.read()
count = 0
while success:
cv2.imwrite(folder... |
import FWCore.ParameterSet.Config as cms
from RecoBTag.Combined.combinedMVA_EventSetup_cff import *
# CombinedMVA V2
from RecoBTag.Combined.combinedMVAV2BJetTags_cfi import *
from RecoBTag.Combined.negativeCombinedMVAV2BJetTags_cfi import *
from RecoBTag.Combined.positiveCombinedMVAV2BJetTags_cfi import *
from RecoBT... |
from .distance_neighbor import *
from .distance_norm import *
from .distance_norm_weighted import *
from .distance_neighbor_eff import *
from .distance_neighbor_dist import *
from .distance_crop import *
|
# -*- coding: utf-8 -*-
"""
File name: exponential_null_model.py
Author: Mario Gutiérrez-Roig
Date created: 14/07/2016
Python Version: 3.4.3
Description: This code fits an exponential function on the Population Proxy
curve. Then, performs a simulation resampling by randomly drawing dates
... |
'''Slack service
Reference:
https://www.fullstackpython.com/blog/build-first-slack-bot-python.html
'''
import time
import config
from clients import GPIOClient
from slackclient import SlackClient
# starterbot's ID as an environment variable
BOT_ID = config.get_value('bot_id')
# constants
AT_BOT = "<@" + BO... |
"""
Script for training the DNNClassifier.
"""
import tensorflow as tf
import glovedata
from glovedata import FEATURES
import sys
hidden_units = [18, 20]
batch_size = 100
train_steps = 2000
def train_input_fn(features, labels, batch_size):
"""
An input function for training the neural network.
"""
# C... |
import sqlite3
import pandas as pd
def sqlite_connection():
conn = sqlite3.connect('support_data.db')
c = conn.cursor()
return c, conn
def import_csv_to_sqlite(conn, support_csv):
support_df = pd.read_csv(support_csv)
support_df.to_sql('support', conn, if_exists='append', index=False)
def main()... |
from flask import Flask, redirect, url_for, request, render_template
app = Flask(__name__)
@app.route('/')
def homepage():
return render_template('halloween.html')
if __name__ == '__main__':
app.run(host='0.0.0.0',debug=True) |
import os.path
__author__="pborky"
__date__ ="$22.2.2010 3:22:45$"
import os
import sys
import signal
import threading
import atexit
import Queue
from logger import get_logger
log = get_logger('pywef.monitor')
class Monitor(object):
"""
Class monitoring loaded modules and additional files for modification.
... |
class Book:
def __init__(self, isbn, title='', authors=[], date_added='', url='', subjects=[], subject_places=[], subject_people=[], subject_times=[], publishers=[], publish_places=[], publish_date='', cover_url='', number_of_pages='', weight=''):
self.isbn = isbn
self.title = title
self.au... |
# author: Arun Ponnusamy
# website: https://www.arunponnusamy.com
# import necessary packages
from keras.preprocessing.image import img_to_array
from keras.models import load_model
#from keras.utils import get_file
import numpy as np
#import argparse
import cv2
#import os
#import cvlib as cv
class GenderRecognition:
... |
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
def register_form(request):
return render(request, 'users/register.html')
def register(request):
username = request.POST.get("username")
email = request.POST.get("email")
password = request.POST.get("password")... |
class Luhn(object):
def __init__(self, data):
self.data = [c for c in data if not c.isspace()]
"""
Strings of length 1 or less are not valid.
Spaces are allowed in the input, but they
should be stripped before checking.
All other non-digit characters are disallowed.
"""
def ... |
""" Roger Rues Student ID: 1000130372
Program Exercise# 4-4 Distance Traveled Assignment# 3 Uplink
Due Date: 3/23/21
Program Description:
This program will ask the user for a vehicle's speed and hours traveled.
It will then display the distance traveled for each hour. ... |
# first we import libraries
import smtplib
# set our variables/account info
sender_email_id = "<Gmail username>"
sender_password = "<Gmail Password>"
message = "<Email Message>"
recipient_email_id = "<Recipient Email Address>"
# next we create the session with definitions
session = smtplib.SMTP('smtp.gmail.com', 587)... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import influx_api
import json
import requests
import pandas as pd
import csv
import sched
import time
import os
import re
from utils import *
# 参数设置
# 一些参数设置
system_name = "business-kpi"
# current_time = "1586534400150" #代表"现在"时间
'''
"1586548560" -> ... |
"""
==========================================
Miscellaneous routines (:mod:`scipy.misc`)
==========================================
.. currentmodule:: scipy.misc
Various utilities that don't have another home.
Note that Pillow (https://python-pillow.org/) is not a dependency
of SciPy, but the image manipulation fun... |
#backup avanços finais do dia 13-14/06
#avanços no quesito tentar organizar a função do 1ºclick
#CLASSES
class colors: #Criada para não precisar escrever as tuplas RGB.
def __init__(self):
self.black=(0,0,0)
self.white=(255,255,255)
self.gray_e=(80, 80, 80) #cinza escuro
self.gray=(... |
import pandas as pd
import numpy as np
from constants import Columns
class Reader:
@staticmethod
def read_csv(file):
print(file)
return pd.read_csv(file)
class RawFileReader:
columns_to_read = [
Columns.OCINumber,
Columns.CustomerName,
Columns.CustomerCode,
... |
"""
# Oscillating String
Sam and Alex are competitive coders working together on strings. They like to create challenges for each other as practice. In one challenge, Sam asks Alex to create a function to sort a string. The terms
smaller and larger refer to the alphabetically lower or higher character. For example 'a'... |
# coding=utf-8
# author:Star
from DF.core.Server import Server
from DF.core.Client import Client
import sys
import socket
from DF.app.configuration import configuration
# get cmd operation
poten_opera = ['-h/-help', '-v/-version', 'run-main-server', 'run-slave-server']
operation = sys.argv[1]
print("###### Welcome to ... |
#! /usr/bin/env python3
import abc
import json
import pathlib
import argparse
class CamelCased(abc.ABC):
type = ''
capitalized = True
container = {}
override = dict()
rename = dict()
capitalize = set()
@classmethod
def camel_cased(cls, mashed_together: str):
""" Generates an... |
import sys
from collections import defaultdict
import ConfigParser
from deploy.screen_utils import create_screen, generate_screen_name
from deploy.constants import FULL_COMMAND
from deploy.classes.exchange_arbitrage_settings import ExchangeArbitrageSettings
from deploy.service_utils import deploy_process_in_screen
fro... |
# Copyright © 2021 CloudBlue. All rights reserved.
import pytest
from connect.reports.datamodels import (
ChoicesParameterDefinition,
ParameterDefinition,
RendererDefinition,
ReportDefinition,
RepositoryDefinition,
)
from connect.reports.validator import (
_validate_parameters,
_validate_... |
from turtle import *
from random import *
from math import *
def tree2(n, l):
pd() # 下笔
# 阴影效果
t = cos(radians(heading() + 45)) / 8 + 0.25
pencolor(t, t, t)
pensize(n / 3)
forward(l) # 画树枝
if n > 0:
b = random() * 15 + 10 # 右分支偏转角度
c = random() * 15 + 10 # 左分支偏转角度
... |
# name = 'Bob'
# def greeting(param):
# return "Hi " + param + "!"
# print(greeting(name))
# word_1 = 'Hi'
# word_2 = 'Bye'
# def combine(a, b):
# return a + (b * 2) + a
# print(combine(word_1, word_2))
# tag_type = 'i'
# word = 'Yay'
# def make_tags(a, b):
# return "<" + a + ">" + b + "</" + a + ">"
... |
import os
os.system('cls')
posiciones = int(input('Número de casillas para conformar el vector: '))
ultimo = posiciones - 2
vector = []
for recorre in range(posiciones):
numero = int(input("Ingresa un valor: "))
if recorre < (posiciones-1):
vector.append(numero)
else:
while (vector[0]+ve... |
from itertools import chain, combinations
import time
def all_subsets(ss):
return chain(*map(lambda x: combinations(ss, x), range(0, len(ss)+1)))
def Primes(a):
sieve=[True]*(a+1)
sieve[:2]=[False, False]
sqrt=int(a**.5)+1
for x in range(2, sqrt):
if sieve[x]:
sieve[2*x::x]=[Fa... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2018-02-01 21:22
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('usuarios', '0015_auto_20180123_2350'),
]
operations = [
migrations.AlterMod... |
from parser import KunaiParser
from lexer import KunaiLexer
from interpreter import KunaiExecute
import sys
file_name = sys.argv[1]
f = open(file_name)
parser = KunaiParser()
lexer = KunaiLexer()
asString = f.read()
split = asString.split(';')
# print(split)
tree = parser.parse(lexer.tokenize(asString))
ID = {}
Ku... |
import numpy as np
def wmean(x, w=None):
""" weighted mean """
if w is None:
return np.mean(x)
else:
return np.sum(x * w) / np.sum(w)
def wstd(x, w=None):
"""
Weighted standard deviation
Parameters
----------
x : array
data
w : array
weights
... |
from random import random
def generate_title_table(title, edge_character = "#", height = 11, width = 80, thickness = 2, side_thickness = 3):
mid_row = (height / 2) if height % 2 == 0 else ((height + 1) / 2)
middle_rows = [(mid_row - 1), mid_row, (mid_row + 1)]
title_length = len(title)
number_of_spac... |
# -*- coding: utf-8 -*-
"""Tests for pybaselines._banded_utils.
@author: Donald Erb
Created on Dec. 11, 2021
"""
import numpy as np
from numpy.testing import assert_allclose, assert_array_equal
import pytest
from scipy.sparse import diags, identity, spdiags
from scipy.sparse.linalg import spsolve
from pybaselines i... |
# coding=utf-8
import ast
import json
import os
import time
from math import fabs
import tweepy
from progressbar import Bar, ETA, Percentage, ProgressBar
import sys
sys.path.append('./CommuniTweet/')
import CommuniTweet.textprocessing64 as txtpro
#sys.path.append('C:/CommuniTweet/CommuniTweet')
#import textprocessi... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2020-02-29 16:00:30
# @Author : mutudeh (josephmathone@gmail.com)
# @Link : ${link}
# @Version : $Id$
import os
class Solution(object):
def wordBreak(self, s, wordDict):
if not wordDict:
return False
is_separable = [-1 for... |
from typing import Callable, List, Tuple, Optional, Union, Set, Dict
from types import ModuleType
from dataclasses import dataclass, field, replace
from contextlib import contextmanager
import functools
import itertools
import inspect
import torch
import torch.onnx
torch.set_default_dtype(torch.float32)
from ksc imp... |
import os
import sys
import logging
import webapp2
from webapp2_extras import jinja2
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.ext.webapp import template
from google.appengine.ext import blobstore
from google.appengine.ext.ndb import Key
from google.appengine.api import users
fr... |
# coding: utf-8
# Standard Libraries
import logging
from enum import Enum
# Dopplerr
from dopplerr import json
log = logging.getLogger(__name__)
class RequestStatus(Enum):
UNHANDLED = "unhandled"
PROCESSING = "processing"
SUCCESSFUL = "successful"
FAILED = "failed"
class Response(object):
de... |
#!/usr/bin/env python3
#
# etl_migrate.py:
# Migrate an input database file to an output file
# Based on etl_ipums.py
# Note coding around Pandas memory leak...
import gc
import gzip
import json
import logging
import logging.handlers
import os
import os.path
import psutil
import re
import sqlite3
import subprocess
imp... |
from __future__ import print_function
from __future__ import division
import os
import argparse
import gym
import numpy as np
import tensorflow as tf
from agent import ActorCritic
from utils import *
def main(args):
INPUT_DIM = 80 * 80
HIDDEN_UNITS = 200
ACTION_DIM = 6
MAX_EPISODES = 10000
# lo... |
'''
@package: dc
@author igor
@link: http://hierarchical-cluster-engine.com/
@copyright: Copyright © 2013-2014 IOIX Ukraine
@license: http://hierarchical-cluster-engine.com/license/
@since: 0.1
'''
import hashlib
import logging
import Constants
import shutil
import dc.EventObjects
import MySQLdb
from BaseTask impo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class DesignatedDrivingDynamicPrice(object):
def __init__(self):
self._dynamic_fee = None
self._dynamic_rate = None
self._dynamic_reason = None
self._dynamic_title = Non... |
import datetime
import os
import pickle
import pyinter
import re
import shutil
import subprocess
from Bio import SeqIO
from django.conf import settings
from genome_finish.celery_task_decorator import get_failure_report_path
from genome_finish.celery_task_decorator import set_assembly_status
from genome_finish.constan... |
#!/usr/bin/env python3
from sys import stderr, exit, argv
import re
import random
from TALinputs import TALinput
from multilanguage import Env, Lang, TALcolors
from increasing_subsequence_lib import *
# METADATA OF THIS TAL_SERVICE:
problem="increasing_subseq"
service="is_subseq_server"
args_list = [
... |
# list of the check functions, which have to output a boolean, with True if the test passes
import sys
code_path = "Data-Science-template-master/Code"
sys.path.append("{}/preprocessing".format(code_path))
sys.path.append("{}/training".format(code_path))
model_save_path = "Data-Science-template-master/Data/models"
#sys... |
import numpy as np
from random import randint
from DisjointSet import DisjointSet
def kruskal(nodes, edges):
"""
implementation of kruskal's algorithm
:param nodes: nodes for input.
:param edges: edges for input.
:return: edges of the minimum spanning tree.
"""
# edges of the minimum span... |
# coding:utf-8
# 作业:1、设计一个表示服务器的类。包含服务器的属性有:
# CPU 个数、 内存大小、磁盘空间大小、操作系统类型(Linux, Windows)
# 其中操作系统类型设置为私有变量,外部不可以更改。
# 实现一个方法,输出服务器的属性内容为以下格式:8核CPU、40G内存、150G磁盘空间、Linux
class Server():
def __init__(self, cpu_num, mem_size, disk_size, system):
self.cpu_num = cpu_num
self.mem_si... |
###############################################################################
# Univesidade Federal de Pernambuco -- UFPE (http://www.ufpe.br)
# Centro de Informatica -- CIn (http://www.cin.ufpe.br)
# Bacharelado em Sistemas de Informacao
# IF969 -- Algoritmos e Estruturas de Dados
#
# Autor: Gabriel Cavalcanti... |
from django.contrib import admin
from .models import Pizza, Order
admin.site.register(Pizza)
admin.site.register(Order)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.