text stringlengths 38 1.54M |
|---|
#!/usr/bin/python3
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""
res = []
for i in sorted(intervals, key=lambda x: x.start):
if res and i.start <= res[-1].end:
res[-1].e... |
import time
from itertools import permutations as perm
def sol1(lim):
pent_nums_set = set([(3*i*i-i)//2 for i in range(lim)])
hexa_nums_set = set([2*n*n-n for n in range(lim)])
for i in range(286, lim):
tri = (i*i+i)//2
if tri in pent_nums_set and tri in hexa_nums_set:
print('next tri pent hex num... |
# Generated by Django 2.2.7 on 2020-01-14 12:04
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('Public_Data_Acquisition_Unit', '0012_auto_20200101_1047'),
]
operations = [
migrations... |
#!/usr/bin/python
# coding:utf-8
from numpy import *
import mysql.connector
import Similarity
config = {'host': 'localhost',
'user':'root',
'password':'',
'port':'3306',
'database':'movielens',
'charset':'utf8',
'buffered': True,
}
try:
conn = my... |
import numpy as np
import pandas as pd
from mxnet import ndarray as nd
from mxnet import autograd as ag
from mxnet import gluon
import matplotlib as mpl
mpl.rcParams['figure.dpi'] = 120
import matplotlib.pyplot as plt
# import os
# print(os.path.abspath('.'))
# 读入数据
train = pd.read_csv("all/train.csv")
test = pd.rea... |
# Generated by Django 3.0.2 on 2020-03-19 09:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('apis', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='orderpost',
name='order_status',
... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
import os
import imageio
from ..composition import SeekableSource
class ImageFileSource(SeekableSource):
"""
"""
def __init__(self, filename_func, nb_images=None, **kwargs):
self.parallel_possible = ... |
/*
Nome: Van
ID: 2693
Resposta: Accepted
Linguagem: Python 3 (Python 3.4.3) [+1s]
Tempo: 0.028s
Tamanho: 287 Bytes
Submissao: 24/10/17 08:11:55
*/
# -*- coding: utf-8 -*-
while 1:
try:
Q = int(input())
except:
break
schedule = []
for i in range(Q):
student, region, cost = inpu... |
import Products.PloneGetPaid.browser.portlets.cart
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from getpaid.googlecheckout.browser.button import checkout_button_url
from Products.CMFCore.utils import getToolByName
class Renderer(Products.PloneGetPaid.browser.portlets.cart.Renderer):
re... |
def max_value(list):
max_num = 0
for i in list:
if i > max_num:
max_num = i
return max_num
def sum_of_list(list):
sum_of_list = 0
count = 0
for nota in notas:
sum_of_list += nota
count += 1
return sum_of_list / count
# Main
notas = [9,7,7,10,3,9,6,6,2]
... |
def create_sieve(size):
l=[1]*(size+1)
l[0]=0
for i in range(2,size+1):
if l[i]==1:
j=2
while(i*j<=size):
l[i*j]=0
j+=1
return l
size=input('Enter the sieve size: ')
sieve=create_sieve(size)
|
from django.shortcuts import render, get_object_or_404
# used for pagnation
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
#used for my customized created models
from .models import Category, Product
from cart.forms import CartAddProductForm
from .forms import SearchForm
#used for normalizing... |
from django.db import models
from reversion import revisions as reversion
from geoposition.fields import GeopositionField
SITE_TYPES = [
('TR', 'Training Site'),
('IN', 'Inland Site'),
('OF', 'Offshore Site'),
]
@reversion.register()
class Site(models.Model):
name=models.CharField(max_length=128)
... |
import re
import os
import shutil
import yaml
from steam_buddy.config import SHORTCUT_DIR
from PIL import Image, ImageFont, ImageDraw
def sanitize(string):
if isinstance(string, str):
return string.replace('\n', '_').replace('\r', '_').replace('/', '_').replace('\\', '_').replace('\0', '_').replace('"', '... |
#ImportModules
import ShareYourSystem as SYS
#Definition an Tree instance
MyViewer=SYS.ViewerClass().view()
MyViewer.MeteoredConcurrentDDPClientVariable.stop()
#Definition the AttestedStr
SYS._attest(
[
'MyViewer is '+SYS._str(
MyViewer,
**{
'RepresentingBaseKeyStrsListBool':False,
'RepresentingAlinea... |
import random
import re
import time
book = [] # database, name < 31, phone < 16, address < 31
n = 0 # кол-во имен в справочнике
# reg.ex. for check numbers: digit + it can be plus in the beginning
p = re.compile('\+?\d+$')
# for check name: letters and one space in the middle
o = re.compile('[a-zA-zа-яА-я]+\s*[a-zA-zа... |
# -*- coding: utf-8 -*-
import pandas as pd
import sys
import os
reload(sys)
sys.setdefaultencoding('utf8')
import numpy as np
# import jieba
import codecs
import re
import shutil
from keras.preprocessing.image import ImageDataGenerator, img_to_array, load_img
import random
datagen = ImageDataGenerator(
rotati... |
#!/usr/bin/env python
#
# Copyright (c) 2010-2017, David Dittrich <dave.dittrich@gmail.com>
# 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.or... |
#
# Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... |
class Solution:
# @param board, a 9x9 2D array
# @return a boolean
def isValidSudoku(self, board):
row = [set([]) for i in range(9)]
col = [set([]) for i in range(9)]
grid = [set([]) for i in range(9)]
for r in range(9):
for c in range(9):
if boa... |
import os
import ray
import time
import pytest
from ray._private.test_utils import (
run_string_as_driver_nonblocking,
run_string_as_driver,
)
from ray.tests.conftest import * # noqa
from ray import workflow
from unittest.mock import patch
driver_script = """
import time
import ray
from ray import workflow
... |
from .operations import *
def calculate_expression(expression):
x, operator, y = expression.split()
x = float(x)
y = int(y)
if operator == '+':
result = add(x, y)
elif operator == '-':
result = subtract(x, y)
elif operator == '*':
result = multiply(x, y)
elif operat... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import statistics as stat
import scipy.stats as scs
import seaborn as sns
# 1
print('-----1-----')
elements = (1, 2, 3, 4, 5, 6)
probabilities = (1/6, 1/6, 1/6, 1/6, 1/6, 1/6)
data = scs.rv_discrete(values=(elements, probabilities))
print('Mean: ',... |
import torch
import numpy as np
import parameters as pt
from torch.utils.data import Dataset
from numpy.random import normal, randint, permutation
from glob import glob
from skimage import img_as_float
from skimage.io import imread, imsave
from skimage.color import rgb2gray
from skimage.filters import prewitt
from os i... |
#coding:utf-8
'''
折半查找法双排序列表的中位数
'''
def half_find(l1, d):
if len(l1) == 0: return
if len(l1) == 1:
if l1[0] == d:
return d
else:
return
if d < l1[0]: return
if d > l1[-1]: return
mid = len(l1) / 2
if l1[mid] == d:
return d
if l1[mid] < d... |
import numpy as np
import pandas as pd
import pytorch_lightning as pl
from sklearn.metrics import top_k_accuracy_score
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.optim import Adam
from torch.optim.lr_scheduler import CosineAnnealingWarmRestarts, ReduceLROnPlateau
from torch.nn.utils.... |
# -*- coding: utf-8 -*-
import datetime
import calendar
def date_finder(year, month):
def allsaturdays(year):
d = datetime.date(year, 1, 4)
d += datetime.timedelta(days = 5 - d.weekday())
while d.year == year:
yield d
d += datetime.timedelta(days = 7)
##var... |
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
#reverse return url as string. The view takes care of the redirect part
from django.urls import reverse
# Create your models here.
class Post(models.Model):
title=models.CharField(max_length=100) #Title of... |
import FWCore.ParameterSet.Config as cms
process = cms.Process("ecalReconstructedPi0")
process.load('Configuration.StandardSequences.Services_cff')
process.load('Configuration.StandardSequences.MagneticField_38T_cff')
process.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_cff')
process.load('Heav... |
from .config import cfg
from .utils import get_tvm_module_N_params
import tvm
from tvm import relay, auto_scheduler
from tvm.relay import data_dep_optimization as ddo
from argparse import ArgumentParser
def run_tuning_cpu(tasks, task_weights, json_file, trials=1000, use_sparse=False):
print("Begin tuning...")
... |
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------
# MapTask Manager
# ---------------------------------------------------------------------
# Copyright (C) 2007-2017 The NOC Project
# See LICENSE for details
# ----------------------------------------------------------------... |
import keyboard
def myString():
print("The Program must have interface as below:")
mystring = input()
print("Please enter string:", mystring )
print("The old string", mystring)
new = mystring[::-1]
print ("The reversed string:", new)
print("Press enter to continue another rever... |
# Generated by Django 2.2.9 on 2020-08-06 08:27
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('posts', '0002_auto_20200715_1221'),
]
operations = [
migrati... |
'''
Generate PDB information for each biounit file
'''
import os
from Bio.PDB import PDBParser
from Bio.PDB import DSSP
BIODIR = "../../ligandNet/2013_biounits_noligand"
BIODIR = "../pdb_nogz" # this is for the whole PDB
#BIODIR = "2013_biounits_noligand"
OUTDIR = "out_all_pdb"
#DSSPDIR= "./dssp-2.0.4-linux-amd... |
# encoding:utf-8
from rest_framework import pagination
from django.conf import settings
import os
import csv
def export_model(export_fields, destination_fields, model, name):
try:
os.mkdir(os.path.join(settings.MEDIA_URL, 'csv'))
os.mkdir(os.path.join(settings.MEDIA_URL + 'csv', 'to_export'))
... |
#Write a program to accept string & a charter or another string and without using count method, count the occurances of second string into first string.
#!/usr/bin/python
def countOccurances(string,char):
count=0
for letter in string:
if(letter==char):
count=count+1
print(count )
def main():
string = input("E... |
def print_parentheses(P):
stack = list()
for p in P:
if stack and stack[-1] == '(' and p == ')':
stack.pop()
print(' ' * len(stack) + p)
else:
stack.append(p)
print(' ' * (len(stack) - 1) + p)
print_parentheses('(()((())()))') |
import datetime
from datetime import timedelta
import pandas as pd
import sqlite3
from tkinter import messagebox
from tkinter import *
pd.set_option('display.max_columns', 500)
conn = sqlite3.connect(
'C:\\Users\\chenqi\\polybox\\Qian\\1 Doctoral Research\\16.02-AMF\\P6 GUI development\\data\\Aturm.... |
#!/usr/bin/env python
from optparse import OptionParser
import string
import math
def run(opts, args):
with open(opts.inf, 'r') as inf, open(opts.outf, 'w') as outf:
first = True
for line in inf:
tokens = line.split()
if first == True:
first = False
... |
import tensorflow as tf
import time
import os
import matplotlib.pyplot as plt
from datetime import datetime
class Pix2Pix:
def __init__(self, mode, train_dataset=False, test_dataset=False, LAMBDA=100, epochs=25, checkpoint_dir='',
restore_check=False, test_samples='', for_tflite=False):
se... |
from math import pow as p
x = int(input("Enter the value for x: "))
answer = 3 * p(x, 5) + 2 * p(x, 4) - 5 * p(x, 3) - p(x, 2) + 7 * x - 6
print(f"The answer is {answer:.0f}")
|
#!/usr/bin/env python
# Create a new FE analysis job from a template
# J.Cugnoni, CAELinux.com, 2005-2013
from Tkinter import *
from tkCommonDialog import *
from tkMessageBox import *
from tkFileDialog import *
import os
import os.path
import sys
astk_bin_path="/opt/aster113/bin/astk"
templateASTK="""
etude,fich,3,FR... |
def int_from_bytes(bytes_, byteorder):
if byteorder == 'little':
little_ordered = iter(bytes_)
elif byteorder == 'big':
little_ordered = reversed(iter(bytes_))
n = sum(ord(v) << i*8 for i,v in enumerate(little_ordered))
return n
def int_to_bytes(n, length, order):
indexes = xrange(l... |
# %%R
import pandas as pd
import numpy
import sys,os
# import ExponentialSmoothing as es
from statsmodels.tsa.holtwinters import ExponentialSmoothing, SimpleExpSmoothing, Holt
import scipy.stats as st
import rpy2
import rpy2.robjects as r
import rpy2.robjects.numpy2ri
from sklearn.metrics import mean_squared_error
from... |
def leapyearcheck(n):
if (n%4)==0:
if (n%100)==0:
if (n%400)==0:
print ('是闰年')
else:
print ('不是闰年')
else:
print ('是闰年')
else:
print ('不是闰年')
|
#WTForm Stuff
CSRF_ENABLED = True
SECRET_KEY = 'a-different-secret-key' #Sample, change this when deploying code.
#Database config.
import os
basedir = os.path.abspath(os.path.dirname(__file__))
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'app.db')
SQLALCHEMY_MIGRATE_REPO = os.path.join(basedir, 'db... |
import argparse
import sys
import pyjq
import json
import subprocess,time
from mysolatcli import SolatAPI
from yaspin import yaspin
from argparse import ArgumentParser
from tabulate import tabulate
api = None
sp = yaspin(text="Fetching Data..", color="green")
def init_api():
global api
api = SolatAPI()
def f... |
from telethon import events
from telethon.tl.custom.message import Message
from res import algo
from res.pkg import *
@client.on(events.NewMessage(incoming=True, func=post_photo_filter))
async def posts_handler(event):
post = event.message
from_channel = await event.get_sender()
reference = ... |
"""
Author: Lori White
Purpose: Showing how to use the python debugger.
"""
# import json
name = input("What's your name? ")
print("Hello " + name + ".")
age = input("How old are you? ")
print(name + " is " + str(age) + " years old.")
|
import os
import pandas as pd
import numpy as np
from data_helper import label_encoding, label_transform
from data_helper import setup_pandas
from data_helper import calculate_and_add_correctness_ratio
from data_helper import train_val_test_split
from data_helper import get_one_user_data
from data_helper import pri... |
from django.db import models
class Obd(models.Model):
OrgID=models.CharField(max_length=70, blank=False, default='')
SiteID=models.CharField(max_length=70, blank=False, default='')
VOB_ID=models.CharField(max_length=70, blank=False, default='')
OBD_TAG_ID=models.CharField(max_length=70, blank=False, d... |
ec2_address = "ec2-18-236-160-205.us-west-2.compute.amazonaws.com"
user = "ec2-user"
key_file = "/Documents/License/jjsham_msds694.pem"
git_repo_owner = "MSDS698"
git_repo_name = "googlemap_week1"
git_user_id = "jacquessham"
orig_coord = '37.7909,-122.3925'
dest_coord = '37.7765,-122.4506'
output_file_name = 'output.tx... |
import csv
import sklearn
import nltk
from nltk.corpus import stopwords
import re
import time
start_time = time.time()
inputFile = open("reviews.csv")
reader = csv.reader(inputFile, delimiter='|')
next(reader)
# get all the stopWords and put them into set
stopWords = set(stopwords.words('english'))
# skip first lin... |
# coding: utf-8
from celery import task
from scoop.location.util.weather import get_open_weather
@task(expires=30, rate_limit='10/m')
def weather_prefetch(city):
""" Précharger les informations météo pour une ville """
get_open_weather(city)
|
# -*- coding: UTF-8 -*-
'''
Created on 2017年5月5日
@author: superhy
'''
from interface.embedding import word2Vec
from K_core import basic_Seq2Seq
def loadQuesAnsVocabData(trainFilePath, gensimW2VModelPath):
# load file data
fr_train = open(trainFilePath, 'r')
trainLines = fr_train.readlines()
fr_train.... |
import json
# 如果以前存储了名字, 就加载
# 如果以前没存储名字, 就提示用户输入并存储
filename = 'username.json'
try:
with open("json/" + filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
username = input("请问您叫什么名字")
with open("json/" + filename) as f_obj:
json.dump(username, f_obj)
print(... |
cost = int(input("Enter the bill total: "))
tip1 = cost * .15
tip2 = cost * .2
print("15% tip is $" + str(tip1) + " and 20% tip is $" + str(tip2) + ".")
|
import os
# 设置应用的运行模式, 是否开启调试模式
DEBUG = True
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
# 数据库配置
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:123456@127.0.0.1:3306/test_gov'
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
from django.contrib.auth.models import User
from faker import Factory as FakerFactory
import factory
from collectors.user.models import Friendship
faker = FakerFactory.create('en')
class UserFactory(factory.DjangoModelFactory):
email = factory.LazyAttribute(lambda n: faker.email())
password = factory.PostGe... |
import datetime
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema
from polls.models import Polls, Question
from polls.serializers import PollsListSerializers, QuestionSeria... |
from django.db import models
class Company(models.Model):
name = models.CharField(max_length=256)
phone = models.CharField(max_length=256)
inn = models.CharField(max_length=256)
class Adress(models.Model):
name = models.CharField(max_length=256)
building_type = models.CharField(max_length=256)
... |
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
from weibo import APIClient
import webbrowser
APP_KEY = '2401928872'
APP_SECRET = 'a2c6813e42cdcc1f9b762e4eeaf496dc'
CALLBACK_URL = 'https://api.weibo.com/oauth2/default.html'
# 利用官方微博SDK
client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK_URL... |
from django.shortcuts import get_object_or_404, render, redirect, reverse
from django.urls.base import reverse_lazy
from django.http import HttpResponse
from django.views.generic.base import View
from .models import Ad, Comment
from .forms import CreateForm, CommentForm
from .owner import OwnerCreateView, OwnerListView... |
from PhysicsTools.SelectorUtils.centralIDRegistry import central_id_registry
import FWCore.ParameterSet.Config as cms
# Common functions and classes for ID definition are imported here:
from RecoEgamma.PhotonIdentification.Identification.cutBasedPhotonID_tools \
import ( WorkingPoint_V3,
IsolationCut... |
loop = 1
while loop == 1:
score = float(input("Input Score:"))
if score < 0 or score > 100:
print("Invalid score. Must be between 1 and 100")
elif score > 100:
print("Invalid score. Must be between 1 and 100")
elif score > 50 and score < 90:
print("Pass")
loop = 0
... |
#rotated array
a = [9,3,4,5,6,7,8]
def find(l,r):
if a[l] < a[r]:
return a[l]
if l == r-1 or l==r:
return min(a[l],a[r])
m = (l+r)/2
if a[m] > a[l]:
return find(m,r)
else:
return find(l,m)
print a
print find(0,len(a)-1)
|
import os.path as osp
from tempfile import mkdtemp
from datetime import datetime
from typing import Iterable, Tuple
import numpy as np
# from sklearn.metrics import confusion_matrix
import tensorflow as tf
from tqdm import tqdm
from ..names import (
X_PLACE,
Y_PLACE,
SAMPLE_WEIGHT_PLACE,
LR_PLACE,
... |
import requests
import os
url=""
root="D://pics//"
path=root+url.split("/")[-1]
try:
kv={"user-agent":"Mozilla/5.0"}
if not os.path.exists(root):
os.mkdir(root)
if not os.path.exists(path):
r=requests.get(url,headers=kv)
r.raise_for_status()
with open(path,'wb') as f:
f.write(r.content)
f.close()
... |
# -*- coding: utf-8 -*-
from docxtpl import DocxTemplate
from time import time
from zip import *
from enum import Enum
from Generator.settings import BASE_DIR
import shutil
WORK_DIR = 'documents'
TEMPLATES_DIR = 'docs/docx_templates'
class Document(Enum):
CLAIM = 'claim'
FORM = 'form'
MEMO = 'memo'
R... |
from copy import deepcopy as copy
from utils import *
def grid_rotate(grid):
w = len(grid[0]) #new grid height
h = len(grid) #new grid width
result = []
for c in range(w): #build a new row for each column in original
newrow = []
for r in range(h):
newrow.append(grid[h-r-1][c... |
#!/usr/bin/python3
# *- coding: utf-8 -*-
'''
nom: andy limmois, johann hospice
command: py limmois_hospice.py <n> <k> <l> <d>
'''
import argparse
'''
Outils
'''
def buildParser():
parser = argparse.ArgumentParser(
description='Generate a deck of dobble card game')
parser.add_argument(
'n',
type=int,
hel... |
import securitycenter
from getpass import getpass
import markdown
import re
html_head = '''
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body{-webkit... |
from numpy import *
n = int(input("insira o numero:"))
i = 0
v = zeros(n,dtype =int)
if(n==2):
v = arange(n)
elif(n > 2):
while(i < size(n)):
v[n] = v[i] - i
i = i + 1
print(v[i]) |
from django.conf.urls import url
from . import views
app_name = 'communications'
urlpatterns = [
url(r'^(?P<uuid>[\w-]+)/$', views.comm_detail, name="comm_detail"),
url(r'^(?P<uuid>[\w-]+)/edit/$', views.comm_cru, name="comm_update"),
url(r'^(?P<uuid>[\w-]+)/delete/$', views.CommDelete.as_view(), name="comm_delete... |
#
# File: run_RSA.py
# Author: Alexander Craig
# Project: An Analysis of the Security of RSA & Elliptic Curve Cryptography
# Supervisor: Maximilien Gadouleau
# Version: 2.2
# Date: 06/04/19
#
# Functionality: utilises other programs to generate and subsequently break RSA
# keys us... |
a = ["Bayam", "Kangkung", "Wortel", "Selada"]
print("""
MENU :
A. Tambah data Sayur
B. Hapus data Sayur
C. Tampilkan data Sayur""")
masukan = input("Pilihan Anda:")
while masukan != 'C' :
if masukan == 'A' :
input_sayur = input("Masukkan nama sayur yang akan ditambahkan :... |
"""
script for generating the testvector file for use in ALU_tb.v
Format will be:
{inM[WIDTH], instruction[WIDTH], reset}_{outM[WIDTH], writeM, addressM[WIDTH], pc[WIDTH]}
NOTE that clk and reset should be set internally in the testbench
Algorithm:
- Follow the alu approach of blasting this with random numbers and ... |
import os
lista = os.listdir('C:\\Users\\Matheus\\Desktop\\psp')
print(lista)
print('Data criação e alteração em segundos')
for x in lista:
listaC = os.path.getctime('C:\\Users\\Matheus\\Desktop\\psp\\' + x)
listaA = os.path.getmtime('C:\\Users\\Matheus\\Desktop\\psp\\' + x)
print(listaC)
print(lista... |
from fractions import Fraction
s = float(input('Decimal Radius? '))
s = Fraction(round(s/(1/64),0)*(1/64))
print(s)
l = input('Press Enter to close this script')
|
def twoStrings(s1, s2):
s1 = set(list(s1))
s2 = set(list(s2))
if s1.intersection(s2):
return "YES"
return "NO"
if __name__ == '__main__':
print(twoStrings("hello", "world"))
print(twoStrings("hi", "world"))
|
''' all routing for accounts app '''
from django.urls import path
from . import views
app_name = 'accounts'
urlpatterns = [
path('', views.index, name='index'),
path('<int:account_id>/', views.accountlist, name='accountlist'),
path('<int:account_id>/newpass/', views.pass_change, name='pass_change'),
]
|
scelta=0
n_task=0
task=[]
from sys import argv
fp= argv[1]
txt= open(fp)
for strng in txt.read().splitlines():
task.append(strng)
n_task+=1
while scelta!=4:
print("Task Manager")
print("1. Insert a new task (a string of text)")
print("2. Remove a task (by typing a substring of its content)")
pri... |
# -*- mode: python -*-
from kivy_deps import sdl2, glew, gstreamer
block_cipher = None
a = Analysis(['game_inspector.py'],
pathex=[''],
binaries=[],
datas=[('no_screenshot.png', '.'), ('fps_inspector_sdk\\python\\fps_inspector_sdk\\lib', 'fps_inspector_sdk\\lib'), ('screen_recor... |
import pytest
from institutionevolution.individual import Individual as Ind
from institutionevolution.deme import Deme as Dem
from institutionevolution.population import Population as Pop
import gc
class TestTechnology(object):
def test_deme_technology_is_right_format(self):
self.pop = Pop(fit_fun='technology', in... |
#-*- coding: utf-8 -*-
from django.conf.urls.defaults import *
from basiccrud.views import *
urlpatterns = patterns('usuario',
## - Cadastro e listagem de usuarios
url(r'^listagem/$', 'views.usuario_list', name='usuario.listagem'),
url(r'^cadastro/$', 'views.usuario', ... |
import pymongo
import datetime
class MongoDB:
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["app_v0"]
# 获取用户账号
def getAccount(self, type="lixinren"):
account = self.db["account"]
result = account.find({"type": type})
json = {}
for x in result:
... |
import matplotlib.pyplot as plt
import numpy as np
from sklearn.cluster import KMeans
np.random.seed(13579)
X = np.r_[np.random.randn(50, 2) + [2, 2],
np.random.randn(50, 2) + [0, -2],
np.random.randn(50, 2) + [-2, 2]]
print(type(X), X.shape)
print(X[:5, ])
print(X[50:55, ])
print(X[100:105])
Ks =... |
import sys
def main():
with open("A-large.in","r") as f:
T = int(f.readline())
ll = []
for line in f:
ll.append(int(line.strip()))
#print T
#print ll
compare = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for i in xrange(T):
N = ll[i]
digit_list = []
if N == 0:
sys.stdout.write("Case... |
import pandas as pd
import numpy as np
import json
from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
from preprocess.utils import clean_text, lemmatize, important
drug = pd.read_csv('./data/nhi_drug.csv', encoding = 'big5')
drug['Ingredient'] = drug['Ingredient'].apply(lambda x : lemmatize(x))
... |
import os, re, sys
import numpy as np
from scipy.ndimage import generate_binary_structure, iterate_structure
from scipy.ndimage.morphology import binary_dilation, binary_erosion
from scipy.interpolate import RectBivariateSpline
from lsst.ts.wep.cwfs.Tool import padArray, extractArray, ZernikeAnnularGrad, ZernikeAnnul... |
# -*- coding: utf-8 -*-
from odoo import models, fields, api
class TodoTask(models.Model):
_name = 'todo.task'
_inherit = ['todo.task','mail.thread']
user_id = fields.Many2one('res.users', 'Responsible')
date_deadline = fields.Date('Deadline') |
#!/usr/bin/env python
import roslib; roslib.load_manifest('leica_ros_sph')
import rospy
import sys
import time
import math
import GeoCom_mod
from geometry_msgs.msg import PointStamped
from optparse import OptionParser
from operator import neg
# Handling options
usage = "usage: rosrun leica_interface %prog [options]"... |
import os
import cv2
import torch
import time
import random
import warnings
import torchvision as tv
import albumentations as albu
import numpy as np
from config import configs
from PIL import ImageFile
from glob import glob
from utils.reader import SegDataset
from utils.losses import *
from utils.o... |
# Write a list comprehension that results in a list of every letter in the word smog-tether capitalized.
str_to_parse = "smog-tether"
print ([x.upper() for x in str_to_parse if x.isalnum()]) |
# -*- coding: utf-8 -*-
from mbp.models import portal_user
from Library.mailhelper import sendMail,sendMail_Nosync
import requests
def sendsmscode(user_code=None,code=None):
"""
给user_code的手机号发送验证码code
:param user_code:
:param code:
"""
xx = portal_user.query.filter(portal_user.user_code =... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-07-20 10:17
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dictionary', '0007_auto_20170707_1349'),
]
operations = [
migrations.RenameMo... |
from app.main.util.response import response_object
from app.main import db
from app.main.model.special_skills_model import SpecialSkillsModel
def get_all_company():
return SpecialSkillsModel.query.all()
def get_a_skills_by_name(name, is_main_skill):
print(name)
print(is_main_skill)
if name == None or... |
list1 = ["TITLE 1: FOOD",
"1.a) ANIMAL FOOD",
"1. Fish",
"(Tariff number 30). Kippers in boxes",
"(Tariff number 31). Pickled herring",
"2. Meat",
"(Tariff number 45). Cow",
"1.b) VEGETABLE FOOD",
]
list2 = ["TITLE 1: FOOD",
"1.a) ANIMAL... |
# -*- coding: utf-8 -*-
"""
Clamor
~~~~~~
The Python Discord API Framework.
:copyright: (c) 2019 Valentin B.
:license: MIT, see LICENSE for more details.
"""
from .meta import *
from .rest import *
import logging
fmt = '[%(levelname)s] %(asctime)s - %(name)s:%(lineno)d - %(message)s'
logging.basicConfig(format=fm... |
n, k = input(), int(input())
lenn = len(n)
dp = [[[i] * (k + 1) for i in range(2)] for j in range(lenn + 1)]
print(dp)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.