text stringlengths 38 1.54M |
|---|
#! /usr/bin/env python3
''' Description on Numbers '''
import sys
import time
from fractions import Fraction
import math
import decimal
from decimal import Decimal
import cmath
# Compelx Numbers
# Costructors
# - complex(x, y)
# x -> real part and y -> imaginary part
# literals: x + yj or x + yJ
# Here, x and y are... |
import datetime
dt = datetime.datetime.now(datetime.timezone.utc)
print(dt) # 結果:2019-11-18 07:54:15.640504+00:00
print(dt.year) # 結果:2019
print(dt.month) # 結果:11
print(dt.day) # 結果:18
print(dt.hour) # 結果:7
print(dt.minute) # 結果:54
print(dt.second) # 結果:15
print(dt.microsecond) # 結果:640504
print(dt.tzinfo) # 結果:UTC
d... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
__doc__ = '''\
Данные об инфекционных осложнениях
'''
def upgrade(conn):
global config
c = conn.cursor()
c.execute('SET SQL_SAFE_UPDATES=0;')
sql = u'''
SELECT id FROM LayoutAttribute WHERE code = '... |
from __future__ import print_function
from __future__ import unicode_literals
import unittest
import numpy
import sklearn.dummy
import sklearn.linear_model
import sklearn.metrics
import sklearn.pipeline
import sklearn.ensemble
from .. import sk
from .. import feature_selection
class HelperTests(unittest.TestCase):... |
import matplotlib as mpl
mpl.use('TkAgg') # change the image rendering backend
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn import svm
digits = datasets.load_digits()
print('digits.data ', digits.data)
print('digits.target ', digits.target)
# apparently setting gamma and data values yiel... |
import math
try:
height = float(input('Enter ur Height(Centemeter) :'))
weight = float(input('Enter ur Weight(Kilogram) :'))
except:
print('invaild input value!!! Please input integer value')
exit()
if height <= 0 or weight <= 0:
print('input of value can\'t lower then zero!!!')
exit()
BMI = w... |
#coding=utf-8
import MySQLdb
import urllib2
import time, threading
import json
import requests
vid = 0
lock = threading.Lock()
conn= MySQLdb.connect(
host='localhost',
port = 3306,
user='root',
passwd='dzl123..',
db ='bilibili',
)
cur = conn.cursor()
def doit():
glob... |
class Solution:
nums = [2, 7, 11, 15]
target = 18
def twoSum(nums, target):
copy = target
l = len(nums)
answer = []
for i in range(0, l):
copy = target - nums[i]
for j in range(0,l):
if(j == i):
continue
... |
from fib import fib
from hypothesis import given
from hypothesis.strategies import integers
@given(integers(min_value=2, max_value=10000))
def test_fib_should_be_sum_of_previous_two(n):
assert fib(n) == fib(n-1) + fib(n-2)
|
###
# BFS
# Time Complexit: O(m^2n^2)
# Space Complexity: O(mn)
###
class Solution(object):
def shortestDistance(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
if not grid or not grid[0]:
return 0
m = len(grid)
n = len(grid[0])
... |
# -*- coding: utf-8 -*-
"""
contains functions relevant to monochromator calibration
note df funct. should work for any hdf5 file
@author: khart
"""
import numpy as np
import h5py
import pandas as pd
def create_mono_df(data_path, name):
"""
this script converts monochromator data to a pandas df
requires f... |
__author__ = 'samyvilar'
import sys
from inspect import isclass
from types import NoneType
from itertools import izip, chain, ifilter, imap, product, repeat, starmap, ifilterfalse, permutations
from front_end.loader.locations import LocationNotSet, loc
from utils import get_attribute_func
current_module = sys.module... |
# Generated by Django 3.0.6 on 2020-05-07 00:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main_app', '0007_auto_20200505_2117'),
]
operations = [
migrations.AddField(
model_name='song',
name='agree',
... |
from django.contrib import admin
from .models import User_System, System, Host
# Register your models here.
admin.site.register(User_System)
admin.site.register(System)
admin.site.register(Host)
|
from abc import ABC
from typing import Optional
from BribeNet.helpers.bribeNetException import BribeNetException
class BriberyGraphNotSetException(BribeNetException):
pass
class BriberyGraphAlreadySetException(BribeNetException):
pass
class BriberNotRegisteredOnGraphException(BribeNetException):
pass... |
from pycocotools.coco import COCO
import pickle
from feature_extractor import FeatureExtractor
import json
import numpy as np
import time
import os
from threading import Thread
dataDir='/data/ouyangzhihao/dataset/MSCOCO'
dataType='train2014'
annFile='{}/annotations/instances_{}.json'.format(dataDir,dataType)
# initia... |
"""
Massage field map into the correct format
"""
import math
def cylindrical_to_cartesian(r, phi, axis):
x = r*math.cos(phi)
z = r*math.sin(phi)
y = axis
return (x, y, z)
def cylindrical_to_cartesian_alt(phi, br, bphi, baxis):
bx = br*math.cos(phi)-bphi*math.sin(phi)
bz = br*math.sin(phi)+bp... |
from pico2d import *
import game_framework
class Block:
def __init__(self):
self.image = load_image('brick180x40.png')
self.x, self.y = 1000, 150
self.speed = 150
def update(self):
if self.x > 1500 or self.x < 90:
self.speed *= -1
self.x += self.speed * gam... |
{
"id": "mgm4443721.3",
"metadata": {
"mgm4443721.3.metadata.json": {
"format": "json",
"provider": "metagenomics.anl.gov"
}
},
"providers": {
"metagenomics.anl.gov": {
"files": {
"100.preprocess.info": {
... |
#
# Copyright 2019 The FATE Authors. 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/LICENSE-2.0
#
# Unless required by appli... |
#!/usr/bin/python2
import time,commands
def sum(x,y):
print x+y
###### now adding two numbers
if __name__ == '__main__' :
a=int(raw_input("type first number : "))
b=int(raw_input("type second number : "))
sum(a,b)
else :
print "not in mood"
|
import os
import torch
from torch import nn
from leaf_pytorch.frontend import Leaf
def get_frontend(opt):
front_end_config = opt['frontend']
audio_config = opt['audio_config']
pretrained = front_end_config.get("pretrained", "")
if os.path.isfile(pretrained):
pretrained_flag = True
ck... |
import os
from logdna import LogDNAHandler
from .base import *
DEBUG = True
ALLOWED_HOSTS = [
'127.0.0.1',
'localhost',
'sc-pri1b.michiru.sh',
'sc-alt0a.michiru.sh'
]
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
)
}
CACHES = {
'defau... |
#!/usr/bin/env python
# encoding: utf-8
import httplib
import json
file = open('hindi-eng.txt', 'r')
char_map = {}
for line in file:
'''for part in line.split(','):
part = unicode(part,encoding='utf-8')
print part
'''
part = line.split(',')
char_map[part[2].rstrip('\n').lower()] = unic... |
class Node:
def __init__(self, val):
self.next = None
self.data = val
class linked_list:
def __init__(self):
self.head = None
def add_node(self, val):
new_node = Node(val)
new_node.next = self.head
self.head = new_node
def p... |
#
import numpy as np
from int_tabulated import *
def GetTotNDVI(NDVI, Time, Start_End, bpy, DaysPerBand):
#NDVI---1D numpy array
FILL=-1.0
nSize=NDVI.shape
sSize=Start_End['SOST'].shape
if nSize[0] == sSize[0]:
ny=sSize[sSize[0]]
else:
ny = 1
ny = 1
#DaysPerBand=... |
class drawable:
def __init__(self,name,anID):
self.name = name
self.data = []
self.type = "line"
self.id = anID
def addData(self,x,y):
self.data.append((x,y))
def setType(self,t):
self.type = t
def groupInfo(self):
ret = """groups.add({
id:... |
import time
import serial
import sys,tty,termios
# XBee setting
serdev = '/dev/ttyUSB0'
s = serial.Serial(serdev, 9600, timeout=3)
print('Start parking')
# Setting d1 and d2
s.write("/parking/run 5.0 3.0 west\n".encode())
s.close() |
#Write a program that reads a file and writes out a new file with the lines in reversed order (i.e. the first line in the old file becomes the last one in the new file.)
"""
f1 = open("reverse.txt","w")
#open the input file and get the contents into a variable data
myfile=open("friends.txt","r")
data = myfile.read()... |
import unittest
from src.song import Song
class TestSong(unittest.TestCase):
def setUp(self):
self.song = Song("Lady GaGa", "Poker Face")
def test_guest_has_artist(self):
self.assertEqual("Lady GaGa", self.song.artist)
def test_guest_has_title(self):
self.assertEqual(... |
import numpy as np
# 标准化
# 将数据转化到较小的范围内,剔除数据量级对结果的影响
# 可以加速计算,提高效率
# 常用的标准化方式:
# (1)离差标准化
# 对原始数据进行线性变换,将数据变换到[0,1]内部
# 公式:new_x = (x - min) / (max - min)
def min_max_scalar(data):
"""
离差标准化来标准化数据
:param data: 需要标准化的数据
:return: 标准化之后的数据
"""
data = (data - data.min()) / (data.max() - data.min(... |
#!/usr/bin/env python
#coding:utf-8
class Integer(object):
def __init__(self,name):
self.name=name
def __get__(self, instance, cls):
if instance is None:
return self
else:
return instance.__dict__[self.name]
def __set__(self,instance,value):
if not ... |
import sympy as sp
from scipy.misc import derivative
x=sp.Symbol('x')
print(sp.diff(3*x**2 +1,x))
def f(x):
return 3*x**2 +1
print(derivative(f,2))
#in derivatives we have to give a function not equation
#derivatives for numerical derivations
#for equation derivations use sympy run the code for better understanding... |
import topside.plumbing.plumbing_utils as utils
def test_teq_to_FC():
reasonable_max_teq = 1000
absurdly_large_teq = 100000000
assert utils.teq_to_FC(0) == utils.FC_MAX
assert utils.teq_to_FC(utils.CLOSED) == 0
for i in range(utils.TEQ_MIN, reasonable_max_teq, 5):
assert utils.teq_to_FC(i... |
#!/usr/local/bin/python
#coding=UTF-8
from urllib import urlopen
import re
p = re.compile('<h3><a .*?><a .*? href="(.*?)">(.*?)</a>')
website = 'https://www.python.org/community/jobs'
p2 = re.compile('<a href="http://(.*?)">(.*?)</a>')
website2 = 'http://www.karottc.com/'
p3 = re.compile('<h3 id=(.*?)>(.*?)')
webs... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# MicroHOPE IDE program, a wxpython text widget with File I/O, Compile and Upload , undo and redo , deivice selection
# Author : Arun Jayan
# email id: arunjayan32@gmail.com , arun.jayan.j@ieee.org
# Licence : GPL version 3
# version : microHOPE 4.0.1
"""
###########... |
import math
import traceback
from compiler.compiler import Compiler
class MIPSVM:
MAX_INST = 128
def __init__(self, program=None):
self._indput = {}
self._output = {f'o': 0 for k in range(1)}
self._registers = {f'r{k}': 0 for k in range(15)}
self._pc = 0
... |
"""
Check that the lowering of non-trivial DotExpr expression in Lkt works as
expected.
"""
from langkit.dsl import ASTNode
from langkit.expressions import Self, langkit_property
from utils import build_and_run
class FooNode(ASTNode):
@langkit_property()
def identity():
return Self
class Example(... |
import os
import psycopg2
DATABASE_URL='postgres://postgres:postgres@localhost:5432/postgres'
def main():
cursor = psycopg2.connect(DATABASE_URL)
print(cursor)
if __name__ == '__main__':
main()
|
#This will work on inkscape files with absolute path coordinates. To set a file to use absolute, go to File->Inkscape #Preferences->svg output and uncheck 'allow relative coordinates'. To make sure your current svg starts to use these, #select all and move by a pixel and it'll update as appropriate.
from xml.dom imp... |
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'targets': [
{
# GN version: //components/safe_json
'target_name': 'safe_json',
#'type': '<(component)',
'type': 'static_libr... |
import json
with open("data.json") as f:
data = json.load(f)
words = data["words"]
words.reverse()
def match_pattern(word, guess, answer):
"""
- is grey
* is yellow
+ is green
"""
required = [g for g, a in zip(guess, answer) if a == "*"]
if not all(letter in word for letter in requir... |
import cv2
from pdf2image import convert_from_path
import imutils
import numpy as np
import pytesseract
from pytesseract import Output
VanBan = 'VB mau/282QĐ 2019.PDF'
# Chuyển pdf sang ảnh
def Chuyen_PDF_img(VanBan):
pages = None
try:
pages = convert_from_path(VanBan)
except:
print("không... |
"""Default input parameters."""
filename = None
out_dir = None
retinex = False
intensity_balance = False
simplest_color_balance = False
simplex_color_balance = False
# retinex defaults
scales = [15, 80, 250]
scales_nifti = [1, 3, 10]
# intensity balance defaults
int_bal_perc = [1., 99.] # intensity balance percent... |
# Crie um programa que leia um nome completo de uam pessoa e mostre:
# 1 - O nome com todas as letras maiúsculas
# 2 - O nome com todas minúsculas
# 3 - Quantas letras (sem considerar espaços)
# 4 - Quantas letras tem o primeiro nome
nome = input("Nome:").strip()
nomes = nome.split()
# nome em maiúsculas
print(nome.u... |
#Hackerrank Counting Valleys Problem
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the countingValleys function below.
def countingValleys(n, s):
s = list(s)
u = 0
d = 0
counter = 0
i = 0
while i < n:
if s[i]=='U':
u+=1
... |
import argparse
import danfosslink2mqtt.config as config
import danfosslink2mqtt.logic as logic
from .configparser import ConfigParser
def parse_config():
parser = argparse.ArgumentParser("DanfossLink2MQTT")
parser.add_argument("--config", action = "store", default = "/config.yaml")
args = parser.parse... |
def gridlandMetro(n, m, k, track):
available = n * m
visited = {}
track.sort()
for row, start, end in track:
if row not in visited:
visited[row] = [[start, end]]
else:
counter = 0
for i in range(len(visited[row])):
curstart, curend = vi... |
# -*- python -*-
#xlc++-libs-ppc450d installation file, KSL supercomputing team
from ksl.process.install.installer import *
from copy import copy
base = installer()
variants = []
base.name='xlcpp_libs'
base.version='9.0'
base.release='1'
base.license="commercial"
base.vendor="IBM"
base.url="http://publib.boulder.ibm.... |
import math
from lm.drawable import lm_drawable_container
from pyglet.gl import *
from lm.type import lm_type_mat
from lm import lm_glb
from lm import lm_consts
class CObj(lm_drawable_container.CDrawable):
def __init__(self, frame_tags, key_frame_tags, label_dict, max_depth, inst_id, depth, parent=None):
super(CO... |
# Generated by Django 2.2.17 on 2021-01-20 19:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("geofr", "0028_auto_20200616_1117"),
]
operations = [
migrations.AddField(
model_name="perimeter",
name="is_visible_... |
import json
import numpy as np
import keras
from tensorflow.keras.preprocessing import sequence
from sklearn import metrics
from tensorflow.keras import Input, Model
from tensorflow.keras.layers import Embedding, Dense, Conv1D, GlobalMaxPooling1D, Concatenate, Dropout
from tensorflow.keras.models import load_model
fil... |
from __future__ import division
import math
import string
doc2 = "The sky is blue."
doc3 = "The sun and sky are bright."
docSplit = doc2.split()
docSplit2 = doc3.split()
ignoredWords = ["is", "the", "and", "a", "to", "was", "are"]
#Remove punctuation from list of strings, and remove words that should be ignored
de... |
def func2(func):
def dec():
print('enter')
func()
print('exit')
return dec
@func2
def func3():
print(3)
func3()
|
import unittest
from tdasm import Runtime
from renmas3.base import BasicShader, Integer, Float, Vec3, Vec2, Vec4
from renmas3.base import Vector2, Vector3, Vector4, Struct
from renmas3.base import register_user_type, create_user_type
from renmas3.base import RGBSpectrum, SampledSpectrum, Spectrum
from renmas3.base imp... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumb... |
#Escreva um programa que converta uma temperatura digitando em graus Celsius e converta para graus Fahrenheit.
gc = float(input('Me diga a temperatura em c° que vc quer converter:C°'))
gf = (gc*9/5)+32
print('Analizando os dados {}C° valem {}°F'.format(gc,gf)) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from flask import Blueprint
click_search_bp = Blueprint("click_search", __name__, url_prefix="/click_search")
from click_search.views import *
|
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 15 15:10:04 2021
@author: KieraLynn
"""
"""
Params:
1、时间范围 两年期间8个Quaters
2、输入的原始数据
3、时间敏感参数δ(time-sensitive parameter)
4、1-项非频繁项的剪枝阈值
计数的支持度:
thresh1=0.2189781 * 记录数量
thresh2=0.0729927 * 记录数量
时间频繁的支持度:0.25
5、挖掘的阈值ε
"""
import itertools
from clean_data i... |
from django import forms
from django.core.exceptions import NON_FIELD_ERRORS
from django.forms import ModelForm
class ConnectForm(forms.Form):
email_signup = forms.EmailField(
required = True,
label = 'Sign Up. Stay Connected:',
initial='Your Email',
widget=forms.TextInput(attrs={'cla... |
#!/usr/bin/env python
"""
Help module to parse a simple XML buffer and store it as a read-only (mostly)
dictionary-type object (MyXml). This dictionary can hold other dictionaries,
nodes-lists, or leaf nodes. Access to the nodes is by using attributes.
>>> xml = parse("<Foo><Bar>Val</Bar></Foo>")
>>> xml.Foo.... |
class Solution:
def checkOnesSegment(self, s: str) -> bool:
if(len(s)==1):
return True
zero_exist = False
for x in s:
if(x =='0'):
zero_exist = True
if(zero_exist and x == '1'):
return False
... |
from timemachines.skaters.sk.skinclusion import using_sktime
from timemachines.skaters.pmd.pmdinclusion import using_pmd
if using_sktime and using_pmd:
from timemachines.skaters.sk.skwrappers import sk_autoarima_iskater
from timemachines.skatertools.utilities.conventions import Y_TYPE, A_TYPE, R_TYPE, E_TYPE, ... |
"""Generates random numbers from Monte Carlo simulation"""
import numpy as np
from scipy import stats
def normal(num_simulations, mu, sig):
"""Perform Monte Carlo simulation to generate rv following normal distribution
Args:
num_simulations: number of simulations
mu: mean of RV following norm... |
# coding=utf-8
import urllib
# https://www.1688.com/robots.txt
# print dir(urllib) # 帮助
# output
# ['ContentTooShortError', 'FancyURLopener', 'MAXFTPCACHE', 'URLopener',
# '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__',
# '__version__', '_asciire', '_ftperrors', '_have_ssl', '_hexdig', '... |
import graphviz
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier, export_text, export_graphviz
# 데이터 load
iris = load_iris()
x = iris.data
y = iris.target
features = iris.feature_names
# 의사결정나무(알고리즘) 객체 생성
decision_tree = DecisionTreeClassifier()
decision_tree.fit(x, y)
# decisi... |
# -*- coding: utf-8 -*-
import numpy as np
from OpenGL.GL import *
class IBO(object):
def __init__(self, sizes, instances, offsets, base_instance, first_index=None, dynamic=False):
if not isinstance(first_index, np.ndarray):
indices = np.vstack((sizes, instances, offsets, base_instance)).T.as... |
from ROOT import *
import sys
sys.path.append('/home/tkimmel/Research/codeplot/functions/')
from plottingfunctions import *
#f = TFile("/home/tkimmel/Research/root/allmfreconKstree.root","READ")
f = TFile("/home/tkimmel/Research/root/kssignalmfrecon.root","READ")
t = f.Get("kstree")
ksmass = RooRealVar("ksmass","ksm... |
from dmia.classifiers import BinaryBoostingClassifier
import matplotlib.pyplot as plt
from sklearn.datasets import make_classification
from dmia.utils import plot_surface
import numpy as np
def main():
X, y = make_classification(n_samples=500, n_features=2,
n_informative=2, n_redund... |
#!/usr/bin/env python
def sequence_gen(num):
while num != 1:
num = num // 2 if not num % 2 else 3 * num + 1
yield num
def find_longest():
for n in range(1, 1000000):
yield n, sum(1 for i in sequence_gen(n))
def main():
longest = max(find_longest(), key=lambda i: i[1])
print... |
def prime_list(n):
# 에라토스테네스의 체 초기화: n개 요소에 True 설정(소수로 간주)
sieve = [True] * n
# n의 최대 약수가 sqrt(n) 이하이므로 i=sqrt(n)까지 검사
m = int(n ** 0.5)
for i in range(2, m + 1):
if sieve[i] == True: # i가 소수인 경우
for j in range(i+i, n, i): # i이후 i의 배수들을 False 판정
sieve[... |
#-------------------------------开发者信息----------------------------------
#开发人:王园园
#日期:2020.5.25
#开发软件:pycharm
#项目:招聘信息文本分类(pytorch):只对模型进行了pytorch改写
#注:如果有看这个代码的同学,希望能帮我指正错误
#--------------------------------------------导入包-----------------------------------------------
from collections import OrderedDict
from msilib im... |
from django.db import models
class Customer(models.Model):
name = models.CharField(max_length=50, default=None)
user = models.ForeignKey('accounts.User', blank=True, null=True, on_delete=models.CASCADE)
active = models.BooleanField(default=False, blank=True, null=True)
weekly_pickup = models.CharField... |
import shapefile
w = shapefile.Writer('soal7')
w.shapeType
w.field('Nama Bidang', 'C')
w.field('Koordinat', 'C')
#nama Record
w.record('polygon', '(1.3)(5.3)(1.2)(5.2)')
#Array sebuah polygon
w.poly([[
[1,3],
[5,3],
[1,2],
[5,2]
]])
w.close() |
from flask import Flask, request
from mongoRepository import MongoRepository
from mongosanitizer.sanitizer import sanitize
app = Flask(__name__)
@app.route("/sendPatientData", methods = ['POST'])
def loadData():
incomingData = request.get_json()
sanitize(incomingData)
mongo_connector = MongoRepository()... |
# Couples Army Damage Skin
def init():
success = sm.addDamageSkin(2433804)
if success:
sm.chat("The Couples Army Damage Skin has been added to your account's damage skin collection.")
# sm.consumeItem(2433804) |
class Tree:
def __init__(self,x):
self.val = x
self.left = None
self.right = None
Stree = Tree(4)
Stree.left = Tree(2)
Stree.right = Tree(7)
Stree.left.left = Tree(1)
Stree.left.right = Tree(3)
Stree.right.left = Tree(6)
Stree.right.right = Tree(9)
"""
Input: -->
4
/ \
2 ... |
#!/bin/env python
# -*- coding: utf-8 -*-
## mesh_plotter ##
from common_drawer import common_drawer
from od_exceptions import od_exception, od_exception_parameter_error
from cairo_rectangle import cairo_rectangle, copy_cairo_rectangle
from font_store import font_store
from common_methods import format_number, map_to_... |
from test_lit import *
from test_const_expr import *
from test_struct_def import *
from test_type_def import * |
```
Given a string s, find the length of the longest substring without repeating characters.
Example 1:
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: s = "pwwkew"... |
import re
import os
from setuptools import setup
VERSION = re.search("__version__ = '([^']+)'", open(
os.path.join(os.path.dirname(__file__), 'pynuts', '__init__.py')
).read().strip()).group(1)
setup(
name="Pynuts",
author="Kozea",
version=VERSION,
url="http://www.pynuts.org/",
license="BSD",
... |
A = int(input('enter A: '))
B = int(input('enter B: '))
result = 0
for i in range(B):
result = result + A
print(A, '*', B, '=', result)
|
#-*- coding: utf-8 -*-
db.define_table('categorias',
Field('nombre'),
format="%(nombre)s"
)
db.define_table('productos',
Field('nombre'),
Field('presentacion'),
Field('categoria', db.categorias),
Field('marca'),
... |
import random
## Initialize the variables
k = 3 ### Number of moves to keep track of
A = [] ### Array of my moves
B = [] ### Array of AI's moves
def lexicon(i):
if i==0:
return "Rock"
elif i ==1:
return "Paper"
elif i==2:
return "Scissors"
else:
return -1
## Play the first three rounds to gain data
def... |
import itertools
import fractions
import numpy as np
import scipy.linalg
import utils
import echelon
from polynomial import Polynomial, Term, evaluate_monomial, gbasis, matrix_form, GrevlexOrdering, LexOrdering,\
as_term, as_polynomial, as_monomial, product
class SolutionSet(object):
def __init__(self, solut... |
import numpy as np
from semeval import SemEval
from algebra import cosine, normalize
from dataset import DataSet
import operator
#------------------------------------------------------------------
def eval_SemEval(Pair_Embeddings,flag):
"""
Evaluate SemEval2012 Task 2
"""
counter=0
S = SemEval("../semeval")
tot... |
from django.db import models
from django.contrib.auth.models import User
from multiselectfield import MultiSelectField
from datetime import timedelta
class ExerciseType(models.Model):
TYPES = (
('Bicep-Curls', 'Bicep Curls'),
('Squats', 'Squats'),
('Jumping-Jacks', 'Jumping Jacks'),
('Bench-Press'... |
from django.urls import path
from .views import *
app_name = 'chef'
urlpatterns =[
path('',orderView,name='orderView'),
path('getOrders/',getOrders,name='getOrders'),
path('cookControl/',cookControl,name='cookControl'),
] |
class Solution:
def getFolderNames(self, names: List[str]) -> List[str]:
out = set()
outl = list()
counter = collections.defaultdict(lambda: 1)
for n in names:
if n not in out:
out.add(n)
outl.append(n)
continue
... |
import requests
import os
import sys
import json
from pprint import pprint
def postPerson(hostName):
url = 'http://' + hostName + ':7001/rdf-rest-api/webresources/persons'
print ("Post to =" + url)
print ('--------------------------------------------------------------------')
os.environ['no_proxy']... |
import pickle
import json
import math
#将句子变为"BOSxxxxxEOS"这种形式
def reform(sentence):
#如果是以“。”结束的则将“。”删掉
if sentence.endswith("。"):
sentence=sentence[:-1]
#添加起始符BOS和终止符EOS
sentence_modify1=sentence.replace("。", "EOSBOS")
sentence_modify2="BOS"+sentence_modify1+"EOS"
return sentence_mo... |
from django.conf import settings
DEFAULT_EXHIBIT_CANVAS = getattr(settings, "DEFAULT_EXHIBIT_CANVAS", "three-column")
DEFAULT_EXHIBIT_THEME = getattr(settings, "DEFAULT_EXHIBIT_THEME", "smoothness") |
import math
def g(n):
return(1.0/(1+math.exp(-n)))
def gprime(n):
return(g(n)*(1-g(n)))
def calc_output(x1, weights):
"""
calculates the output of the given neural
network using the input and two weights.
"""
n1 = weights[0]*x1
x2 = g(n1)
n2 = weights[1]*x2
x3 = g(n2)
... |
import FWCore.ParameterSet.Config as cms
#------------------------------------------------------------
# This is a test of overlaps which use only Geant4 tool.
# To start it names of Physical volumes should be provides.
# It is possible to check overlap check parameters.
# Static build of Geant4 may be used
#-------... |
#!/usr/bin/env python
import rospy
from sensor_msgs.msg import Image
from std_msgs.msg import Int32, Duration, Header
import numpy as np
from ros_numpy import numpify, msgify
import scipy.misc
import scipy.ndimage.morphology
import time
from copy import deepcopy
from rospyext import *
import os
class ColorThreshol... |
#!/usr/bin/python
#
# Freeze the rpm versions found in the files:
#
# centos-6.packages1
# centos-6.packages2
# centos-6-new.packages
#
# New files are created with the name
#
# <name>.frozen
#
# Do a diff, move and copy over
#
import os
import sys
import yum
import re
import shutil
from yum.sqlitesack im... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Post',
fields=[
('id', models.AutoField(verbose... |
from hangman import *
import os
HANGMAN = Hangman()
def main():
playing = True
while playing:
# clean the cmd
HANGMAN.refresh_cmd()
# interface
HANGMAN.life_indicator()
HANGMAN.used_letters_indicator()
HANGMAN.current_word()
# user input
lette... |
DEBUG=True
import matplotlib.pyplot as plt
import datetime
from matplotlib.finance import date2num
import numpy
from matplotlib import style
import bs4 as bs
import requests
import pickle
import os
import datetime as dt
import pandas as pd
import pandas_datareader.data as web
style.use('ggplot')
def sp_500():
pag... |
from rest_framework import serializers
from rest_framework.serializers import ModelSerializer,HyperlinkedIdentityField
from . models import employees,uploadem,uploadphone,receiverequest,Posts,Likes,Shares
class employeesSerializer(serializers.ModelSerializer):
# emp_id = serializers.Field()
class Meta:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.