text stringlengths 38 1.54M |
|---|
import tensorflow as tf
from tensorflow.python.framework import graph_util
from preprocessing import *
import pickle
import json
def predict(rnn_graph,texts,vocab_to_int):
# textcnn 预测
x = rnn_graph.get_tensor_by_name('prefix/Inputs/batch_ph:0')
seq_length= rnn_graph.get_tensor_by_name('prefix/Inputs... |
# Exercise 1
# Basic scatter plot, log scale
plt.scatter(gdp_cap, life_exp)
plt.xscale('log')
# Strings
xlab = 'GDP per Capita [in USD]'
ylab = 'Life Expectancy [in years]'
title = 'World Development in 2007'
# Add axis labels
plt.xlabel(xlab)
plt.ylabel(ylab)
# Add title
plt.title(title)
# After customizing, disp... |
# -*- coding: utf-8 -*-
'''
Created on 2012/04/11
@author: 0000131307
'''
"""
numpyの紹介 → pylabの中にnumpy moduleが入っているので、numpyのreferenceに参照が入っている:
-numpy resource:
http://www.geocities.jp/showa_yojyo/note/python-numpy.html#array (Japanese)
http://www.ike-dyn.ritsumei.ac.jp/~uchida/sc... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class HbGoodsTradeRule(object):
def __init__(self):
self._max_buy_frequency = None
self._max_buy_quantity = None
self._min_buy_quantity = None
self._one_max_quantity = N... |
#!/usr/bin/python3.5
# ^^ note the python directive on the first line
# COMP 9414 agent initiation file
# requires the host is running before the agent
# designed for python 3.6
# typical initiation would be (file in working directory, port = 31415)
# python3 agent.py -p 31415
# created by Leo Hoare
# with sli... |
#!/bin/python
# Do fitting for M samples of K columns from correlation data files (???.txt)
# For residues in RESIDS, and calculate appropriate R1,R2,R2/R1 for each sample
# using fit3.sh script, and based on samples in COLUMNS file (see below)
#
# If GENERATE_COL is 1, also generates a COLUMNS file that holds the col... |
import jinja2
import os
from .compiler import generate
import glob
import re
_lib_js = {}
def lib(minified=False):
global _lib_js
key = "minified" if minified else "normal"
if key not in _lib_js:
runtime = os.path.join(os.path.dirname(__file__),"lib/jinja2.runtime.min.js" if minified else "lib/jin... |
# Generated by Django 2.1.5 on 2019-02-19 08:41
from django.db import migrations, models
import modules.core.models
class Migration(migrations.Migration):
dependencies = [
('core', '0002_auto_20190217_1233'),
]
operations = [
migrations.AlterField(
model_name='commoninfo',
... |
import os
import re
MAX_LEN_NAME = 50
def cut_scheme(url):
return re.sub('http[s]?://', '', url)
def make_kebab_case(name):
name = re.sub('\\W|_', '-', name)
if len(name) > MAX_LEN_NAME:
return name[:MAX_LEN_NAME]
return name
def make_file_name(url):
without_scheme = cut_scheme(url)
... |
import pymongo
from pymongo import MongoClient
from operator import attrgetter
client = MongoClient()
db = client.social_net
answer = db.tweets.find()
def GetAllUniqueUsers():
print(len(db.tweets.distinct("user")))
def GetMostLinkingUsers():
pipeline = [
{'$match':{'text':{'$regex':"@\w+"}}},
... |
import requests,re,ast,json
class quizlet_words(object):
def __init__(self,id):
self.id = id
self.link = "https://quizlet.com/%s/flashcards" % id
self.wd = []
if self.isValid():
self.wd = self.__reqData()
@classmethod
def initFromLink(cls,link):
... |
class Solution:
def isPalindrome(self, s: str) -> bool:
if len(s) < 2:
return True
value = 'abcdefghijklmnopqrstuvwxyz0123456789'
value_list = list(value)
s_list = list(s.lower())
pure_s = []
for i in range(len(s_list)):
if s_list[i] in value_l... |
#!/usr/bin/python
#
# Determine if this tool can run a test based on a test spec.
#
import datetime
import sys
import pscheduler
logger = pscheduler.Log(prefix='tool-bwctliperf3', quiet=True)
json = pscheduler.json_load(exit_on_error=True)
logger.debug("can-run for %s" % json)
try:
if json['type'] != 'throug... |
def longestValidParentheses(self, s):
dp, ans = [0]*(len(s)+1), 0
for i in range(2, len(s)+1):
if s[i-1]==')':
if i-dp[i-1]-2>=0 and s[i-dp[i-1]-2]=='(': dp[i] = dp[i-1] + 2
dp[i] += dp[i-dp[i]]
ans = max(ans, dp[i])
return ans
###
let ... |
def fabonacci(nth):
#nth=nth term of the number
if nth<0:
print("Enter a positive number.")
elif nth==1:
return 0
elif nth==2:
return 1
else:
return fabonacci(nth-1)+fabonacci(nth-2)
print(fabonacci(10))
|
# 1.7 Flip it!
def flip_vertical_axis(matrix):
rows = len(matrix)
columns = len(matrix[0])
odd = False
if columns % 2 != 0:
odd = True
for row in range(0, rows):
middle = None
new_row = []
middle_found = False
for column in range((columns // 2), columns):... |
import tensorflow as tf
from utility.tf_utils import assert_rank
from core.module import Ensemble
from nn.func import rnn
from algo.ppo.nn import Encoder, Actor, Value
class PPO(Ensemble):
def __init__(self, config, env, **kwargs):
super().__init__(
model_fn=create_components,
co... |
from DataManipulation import UseFirebase, XMLManipulate
def check_article_connection(): #Make sure there are articles, and can be connected
""" function to ensure DB connection and format """
assert len(UseFirebase.get_articles()) > 0 #There are articles in the DB that I manually seeded to check the connection... |
from entities import RateCategoryEntity, RoundEntity, TrackEntity, RateEntity, PairEntity
from models import RateCategory, Round, Track, Rate, Pair
def rate_category_orm_to_entity(rate_category_orm: RateCategory) -> RateCategoryEntity:
return RateCategoryEntity(
id=rate_category_orm.id,
name=rate_... |
import argparse
import crossref_commons.retrieval
import json
import os
import requests
from bs4 import BeautifulSoup
from datetime import datetime
def current_timestamp():
'''
Returns current timestamp for logging purposes
'''
return datetime.now().strftime('%Y-%m-%d %H:%M:%S')
def repec_page(ba... |
from pandas import DataFrame
import blocks
import load_data
import numpy as np
from numpy.testing import assert_array_equal
def test_purity():
ids = range(10)
labels = [1, 1, 1, -1, -1, -1, 1, 1, -1, -1]
blocks_ = [1, 1, 1, 2, 2, 3, 3, 4, 4, 4]
df = DataFrame({'ids': ids, 'label': labels, 'block'... |
# -*- coding: utf-8 -*-
data = u"""Apache Software License
Version 1.1
Copyright (c) 2000 The Apache Software Foundation. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source c... |
import re
from .ncbi_ranks import _TAXONOMIC_RANKS
from htstk.utils import log
_taxa_levels = [
'root',
'kingdom',
'phylum',
'class',
'order',
'family',
'genus',
'species'
]
class NCBITaxonomyInMem():
def __init__(self, path_nodes, path_names):
self.ranks = _TAXONOMIC_RANK... |
import torch
import numpy as np
def test_tensors():
# Initializing a Tensor
def initialize_a_tensor():
data = [[1, 2],[3, 4]]
# Directly from data
x_data = torch.tensor(data)
# From a NumPy array
np_array = np.array(data)
x_np = torch.from_numpy(np_array)
# From another tensor
... |
#!C:\Python38\Python
import tkinter as tk
import random
import keyboard
import time
from PIL import Image, ImageTk
def goLeft():
global x_snake,y_snake,direction
if keyboard.is_pressed('left'):
print("left pressed")
x_snake-=50
direction='left'
elif direction=='left':
x_... |
from .._distutils.command import install_lib as orig
class install_lib(orig.install_lib):
def run(self) -> None: ...
def get_exclusions(self): ...
def copy_tree(
self, infile, outfile, preserve_mode: int = 1, preserve_times: int = 1, preserve_symlinks: int = 0, level: int = 1
): ...
def get... |
import numpy as np
b = np.arange(9).reshape(3,3)
b = b * 1.0
var_1 = var_2 = var_3 = 99.
for i in range(3):
tmp = ('var_'+str(i+1))
b[2, i] = locals()[tmp]
c = np.zeros(shape=(100, 100), dtype=np.float32)
print(c)
print(c[:,0])
# result
#[[ 0. 1. 2.]
# [ 3. 4. 5.]
# [99. 99. 99.]] |
# This file is part of AltCanvas.
#
# http://code.google.com/p/altcanvas
#
# AltCanvas is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.... |
from google.cloud import datastore
import cirq
from flask import Flask
import time
import sys
import datetime
import os
from networkx import Graph
from itertools import combinations
from cirq.contrib.routing import route_circuit
def get_error_qubits(project_id, processor_id, threshold):
# query for the latest ca... |
from pyspark.sql import *
from pyspark.sql.functions import *
from pyspark.sql.functions import min
from pyspark.sql import SparkSession
from pyspark import SparkContext
from pyspark.sql.functions import lit
'''
Script functionality:
In order to filter and reduce even more the size of the datasets we dropped the
colum... |
# http://rosalind.info/problems/fib/
def fib(n, k):
if n <= 1:
return n
return fib(n - 1, k) + k * fib(n - 2, k)
with open('datasets/rosalind_fib.txt') as f:
n, k = f.readline().split()
res = fib(int(n), int(k))
print(res)
|
import functions
class Node:
def __init__(self, char, pos):
self.char = char
self.i = pos[0]
self.j = pos[1]
self.isWall = self.char == "x" or self.char == "|" or self.char == "-"
self.isStart = self.char == "H"
self.isGoal = self.char == "T"
self.isTorch = ... |
# -*- coding: utf-8 -*-
# Bibliotecas para manuseio dos dados
import pandas as pd
import numpy as np
# datasheet
dataset = pd.read_csv("2020_before_iqa.csv", encoding='utf8',
delimiter=',', engine='python')
print(dataset.info())
dataset['IQA'] = (dataset['Oxigenio dissolvido'].astype('float32'... |
"""
Необходимо написать скрипт, обрабатывающий лог файл Nginx и выводящий список IP адресов, с которых производились запросы. Адреса из общей подсети \24 необходимо группировать при выводе (например, 10.40.0.4 и 10.40.0.231 относятся к одной подсети).
Версия Python: 3.5
"""
import ipaddress
MASK = 24
f = open("acce... |
# Generated by Django 3.1.7 on 2021-03-22 02:00
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('cartoons', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='cartoon',
... |
'''
Created on May 26, 2017
@author: deckyal
'''
import tensorflow as tf
from tensorflow.contrib import rnn
import numpy as np
#Impor MNIST data
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot = True)
#Parameters
learning_rate = 0.001
training... |
import sys
from genStubs import *
stub = Stubs( "flashSectionStm32", sys.argv[1], sys.argv[2] )
### Include Headers
stub.include( "flashSectionStm32.h" )
### Used Namespaces
stub.newline()
stub.externC()
stub.stubFunction( ("flashSectionErr_t", "FLASH_SECTION_ERR_NONE"), "flashSectionInit", "flashSectionType_t", "S... |
from ctypes import *
_libraries = {}
_libraries['librtlsdr.so'] = CDLL('librtlsdr.so')
STRING = c_char_p
int8_t = c_int8
int16_t = c_int16
int32_t = c_int32
int64_t = c_int64
uint8_t = c_uint8
uint16_t = c_uint16
uint32_t = c_uint32
uint64_t = c_uint64
int_least8_t = c_byte
int_least16_t = c_short
int_least32_t = c_... |
from config import nyanpasu_id
from funcs.rep import user_make
def chat_stats(app, chat_id, chat, service, sleep, msg_id, nyanpasu_stats):
cc = '✅' if int(chat.cond) else '❌'
ct = '✅' if int(chat.ttsm) else '❌'
cn = '✅' if int(chat.nsfw) else '❌'
cg = '✅' if int(chat.greetc) else '❌'
if str... |
import numpy as np
import math
import random
class ExperienceReplay():
def __init__(self, capacity):
self.capacity=capacity
self.memory=[]
self.position=0
def push(self, state,
action, new_state,
reward, done):
transition=(st... |
import numpy as np
import forward_propagation as fp
def test_accuracy(X_test, Y_test, m_test, w, b):
A = fp.forward_propagation(w, b, X_test)
sum = 0
for i in range(m_test):
if (A[0][i] > 0.5 and Y_test[0][i] == 1) or (A[0][i] < 0.5 and Y_test[0][i] == 0):
sum += 1
... |
import web
import random
render = web.template.render('templates/', cache=False, globals={})
render._keywords['globals']['render'] = render
def data(n):
d = []
for i in xrange(n):
d.append(random.uniform(2,50))
return d
|
def vowels():
print "Ei Ei Oh"
def oldman():
print "Old McDonald Had a Fahm"
def hehad(s):
print "And on that farm he had a:", s
def animal(f):
print " There's a",f,f,"here"
def verse(s,f):
oldman(),vowels(),hehad(s),vowels(),animal(f),vowels()
oldman()
vowels()
hehad("dog")
vowels()
animal("woof")
vowels()
verse(... |
f= open("./ExData/maxK", 'r')
n, k = map(int, f.readline().split())
lst = list(map(int, f.readline().split()))
print(n)
print(k)
print(lst)
lst.sort(reverse=True)
print(lst)
result =[]
for i in range(0,n):
for j in range(1,n):
for x in range(2,n):
result.append(lst[i] + lst[j] + lst[x])
... |
import unittest
from oslo.config import cfg
from dnh import consumer as dnh_consumer
from dnh.handler import nsd4
class DnhTestCase(unittest.TestCase):
def setUp(self):
cfg.CONF.set_override('handlers', ['nsd4'],
group=dnh_consumer.CFG_GRP)
cfg.CONF.set_override('ser... |
#!/usr/bin/python
import tweepy
import os
import picamera
import time
auth = tweepy.OAuthHandler('X', 'X')
auth.set_access_token('X', 'X')
twitter_api = tweepy.API(auth)
camera = picamera.PiCamera()
camera.capture('test1.jpg')
time.sleep(1)
photo = '/home/pi/test1.jpg'
status = 'This is a test using the Raspberry... |
from django.urls import path
from Bigflow.ServiceManagement import views
from django.conf.urls import url, include
urlpatterns = [
url(r'^ServiceManagement/(?P<template_name>[\w-]+)/$', views.Service_Management_Template, name='Service_Management_Template'),
# path('AMC_Maker_Summary/' ,views.amc_Maker_Summary,... |
import torch
import numpy as np
class RNN(torch.nn.Module):
def __init__(self, input_vector, hidden_vector):
super().__init__()
self.weights_x = torch.nn.Parameter(torch.randn((input_vector, hidden_vector)))
self.weights_h = torch.nn.Parameter(torch.randn((hidden_vector, hidden_vector)))
self.biases... |
import re
import csv
import sys
import random
from datetime import datetime, timedelta
class HourConverter():
def dateConverter(self, date):
hour = date.split(":")[0]
minute = date.split(":")[1]
minute = minute.split(" ")[0]
day = date.split(" ")[2]
month = se... |
#!/usr/bin/python
import os, sys, random
def roll_dice():
digits=""
for i in range(0,5):
digits += str(random.choice(range(1,7)))
return digits
def loading_diceware_list():
dwl={}
dir_path=os.path.dirname(os.path.realpath(__file__))
try:
with open(dir_path+os.sep+"dicepass.lst")... |
import os , json
import sqlite3
__author__ = 'aleksandrsl'
def update_address_mapping():
app_root_path = os.getcwd()
addr_path = os.path.join(app_root_path, "configs", "address_mapping.json")
jobj = json.load(file(addr_path))
counter = 1
for item in jobj :
if not("id" in item):
... |
from multiprocessing import Process,Pipe
from random import randint
#YOLO
def random_int():
lst = [randint(0, 20), randint(0, 20),randint(0, 20),randint(0, 20)]
return lst
while True:
def f(child_conn):
msg = random_int()
child_conn.send(msg)
child_conn.close() |
import Pyro4
class ChatBox(object):
def __init__(self):
self.users = [] # registered users [user --> (nick, client callback)]
self.nicks = [] # all registered nicks on this server
def getNicks(self):
return self.nicks
def join(self, nick, callback):
if not nick:
raise ValueError('Invalid nickname')
i... |
#!flask/bin/python
# -*- coding: utf-8 -*-
from flask import Flask, jsonify
import requests
from lxml import html
import json
import http.client, urllib.parse
import datetime, time
from flask import send_file
from flask_cors import CORS
from multiprocessing import Queue
from flask import request
from flask_... |
import numpy as np
import pandas as pd
from datetime import datetime
import time
while True:
url_dict = {
'GTX1050ti' : 'http://www.nowinstock.net/computers/videocards/nvidia/gtx1050ti/'
,'GTX1060' : 'http://www.nowinstock.net/computers/videocards/nvidia/gtx1060/'
,'GTX1070' : 'http://ww... |
from sys import stdin
def parse_program(line):
head, tail = line.split('<->')
id = int(head)
connections = [int(s) for s in tail.split(',')]
return id, connections
def main():
programs = dict(parse_program(line) for line in stdin)
groups = {}
stack = []
group_count = 0
for id in... |
f = open ('text.txt', 'w')
str_list = input('Введите текст: \n')
while str_list:
f.writelines(str_list)
str_list = input('Введите текст: \n')
if not str_list:
break
f.close()
with open ('text.txt') as f:
for line in f:
print(line)
f.close() |
import urllib
from bs4 import BeautifulSoup
from uritools import urijoin
import re
from sqlite3 import dbapi2 as sqlite
# words to ignore
ignorewords=set(['the','of','to','and','a','in','is','it'])
class crawler:
# initialize the crawler with the dbname
def __init__(self, dbname):
self.con = sqlite.c... |
x=int(input("Enter 1st Number="))
y=int(input("Enter 2nd Number="))
z=x+y
print(z)
'''(The String as Input)
ch=input("enter the char")[0:2]
print(ch)
'''
'''(The String as Input)
ch=input("enter the char")
print(ch[5])
'''
'''("Sol of expressions")
result=eval(input("Enter the expression"))
print(result... |
# Link: https://leetcode.com/problems/climbing-stairs/
# It takes 'n' steps to reach the top of a staircase. You can either climb 1 or 2 steps. How many distinct ways can you climb to the top?
class Solution:
def climbStairs(self, n: int) -> int:
ans = [0, 1, 2]
if n == 1:
retu... |
"""
4. Write a script that receives a directory as argument and creates a JSON file with data about all the files in that
directory. For each file, the following information will be displayed: file_name, md5_file, sha256_file, size_file
(in bytes), time when the file was created (human-readable) and the absolute path t... |
import numpy as np
import matplotlib.pyplot as plt
import torch
from tiered_algorithm import state_to_actions
from variables import Actions
device = torch.device("cpu")
def set_device(_device):
global device
device = _device
class maze_game:
def __init__(self, maze_list, max_steps=100, max_rounds=100, ... |
from extra.makeTree import *
import queue
def levelOrder(head):
cur_node = head.root
help_queue = queue.Queue()
help_queue.put(cur_node)
while not help_queue.empty():
cur_node = help_queue.get()
print(cur_node.elem)
if cur_node.lChild is not None:
... |
from sqlalchemy import Column, Integer, String
from flask_apispec import use_kwargs, marshal_with
from marshmallow import Schema, fields
from webargs.flaskparser import use_args
from hc_flask.api import FlaskApi
from hc_flask.database import SqlAlchemyBase
class ScreenResolution(SqlAlchemyBase, FlaskApi):
"""Def... |
import os
from collections import defaultdict
import re
import pprint as pp
import configparser
def create_ticker_name_dict():
'''
create a dictionary that matches korean ticker's naming
:return: tickers['ticker'] = name
'''
cnt = 0
limit = 20 # the limited number of tickers
tickers = defa... |
##########################################################
from math import atan2,cos,sin,pi
#面向对象中的设计模式-实现复数和分数的运算
#首先定义一个数的抽象类
class Number():
def __add__(self, another):
return self.add(another)
def __mul__(self, another):
return self.mul(another)
#############
#这是后期实现
#############
def add... |
import csv
import cv2
import dataset_creator as DC
import feature_extractor as FE
import glob
import numpy as np
import os
import read_files as RF
import time
import platform
from scipy import stats
from commonfunctions import *
start_time = time.time()
#############################################################... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# CGI处理模块
import cgi,cgitb
# 创建FieldStorage的实例化
form = cgi.FieldStorage()
if form.getvalue('google'):
google_flag = "是"
else:
google_flag = "否"
if form.getvalue("baidu"):
baidu_flag = "是"
else:
baidu_flag = "否"
print "Content-type:text/html"
print
print "... |
# Generated by Django 3.2 on 2021-04-24 17:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('bookings', '0011_rename_at_theater_seats_present_in_theater'),
]
operations = [
migrations.RemoveField(
model_name='seats',
... |
a = [2,6,7,9,12]
b = [99,56,3,5,87]
c = a+b
c.sort()#ordena sequencialmente
print(c)
print()
print(a*2)#Ele vai esquever os elementos de A Duas vezes
print()
print(2 in a) # ver se tem o numero na lista ou a string(nomes)
print()
print(15 in a) |
def splitter(data,n):
l = zip(data.Hr_Length.tolist(),data.Cluster.tolist())
numresult = [[] for i in range(n)]
idxresult = [[] for i in range(n)]
sums = {i:0 for i in range(n)}
c = 0
for e,g in l:
for i in sums:
if c == sums[i]:
numresult[i].append(e)
... |
from flask import Flask, request,jsonify, render_template
import json
import sqlite3
app = Flask(__name__)
#an in memory students storage(using a list)
#students = []
#instead of a list,we need to create a connection to database where we store students
def db_connection():
conn = None
try:
conn = sqlite3.connect... |
def calculator_base_message(message):
operators = ['+', '-', '*', '/']
message = message[2:-2]
if len(message) != 0:
if ' ' not in message:
if message[-1] == '=':
for i in range(len(operators)):
if operators[i] in message:
opera... |
# -*- coding: utf-8 -*-
import Spider
if __name__ == "__main__":
obj = Spider.SpiderMain()
obj.getAllCityInfo()
obj.con_cursor.close()
obj.connection.commit()
obj.connection.close() |
from random import random
from time import perf_counter
DARTS = 10000*10000
hits = 0.0
start = perf_counter()
for i in range(DARTS):
x, y = random(), random()
dist = pow(x**2+y**2, 0.5)
if dist < 1.0:
hits += 1
pi = 4*hits/DARTS
print('圆周率是:{:.6f}'.format(pi))
print('运行时间:{:.3f}'.format(perf_counter()-start))
|
# def init(shared_arr_):
# global shared_arr
# shared_arr = shared_arr_ # must be inhereted, not passed as an argument
from multiprocessing import sharedctypes
from multiprocess import Pool
import ctypes
global_vars = {}
class A(object):
def __init__(self, size):
self.size = size
# self.... |
""" Wrapper for pyevolove library to support multiprocessing
and more convenient usage.
"""
import copy_reg
import types
import time
from multiprocessing import Pool
from gaengine import GAInstance
from funclib import *
def _pickle_method(method):
func_name = method.im_func.__name__
obj = method.im_self
... |
import ConfigParser
import os
from scipy import misc
import matplotlib.pyplot as plt
import skimage.transform as sk_transform
from abhishek import *
config = ConfigParser.RawConfigParser(allow_no_value=True)
with open('/media/adv/Shared/PROJECTS/CSE515_MWDB/Code/variables.cfg') as config_file:
config.readfp(conf... |
import os
import networkx as nx # https://networkx.org/
import re
def create_graph(raw_bag: str) -> nx.MultiDiGraph:
graph = nx.MultiDiGraph()
lines = raw_bag.splitlines()
for line in lines:
if "contain no other bag" in line:
continue
definition_bag, raw_containing_bags = li... |
import math
import random
import puzzleRandomizer
from datetime import datetime
from copy import deepcopy
import itertools
import numpy as np
# ------------------------------------------------------------ #
# ------------------ SET PUZZLE SIZE HERE -------------------- #
algorithm = 1 # use dictionary (0), ... |
from django.db import models
from django.utils.translation import ugettext as _
class Config(models.Model):
key = models.CharField(_('Key'), max_length=100, unique=True)
value = models.BooleanField(_('Value'), default=False)
message = models.TextField(_('Message'))
def __unicode__(self):
return ... |
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
# class Solution:
# def nextLargerNodes(self, head: ListNode):
# nums = []
# node = head
# while node != None :
# nums.append(node.val)
# node = node.next
# stac... |
import pandas as pd
import numpy as np
def hard_voting(target):
N, B = target.shape[0], target.shape[1]
result = np.zeros_like(target[0])
for i in range(B):
result[i] = np.bincount(target[:, i]).argmax()
return result
files_list = [
'./ensamble/deeplabv3_resnet101 StepLR.csv',
'./e... |
from tkinter import *
root = Tk()
root.title("Пример меню на Python")
root.geometry("400x300")
main_menu = Menu()
file_menu = Menu(font=("Comic sans", 10, "bold"), tearoff=0, activebackground="red")
file_menu.add_command(label="New file")
file_menu.add_command(label="Save")
file_menu.add_command(label="Save as ")
file_... |
# Generated by Django 3.1.2 on 2020-11-06 13:08
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('myapp', '0006_auto_20201106_1506'),
]
operations = [
migrations.AlterField(
model_name='order',
name='... |
#!/bin/python3
import numpy as np
import pickle
from lnm.kneser_ney import kneser_ney
from lnm.witten_bell import witten_bell
from sklearn.model_selection import train_test_split
corpus = pickle.load(open('resources/sentences.pkl','rb'))
X, y = train_test_split(corpus, test_size=0.2)
X_cor = ''
kn_df = []
wb_df = []
... |
# myiterator.py
# 此示例示意用迭代器来遍历列表
L = [2, 3, 5, 7]
it = iter(L) # 让L提供迭代器
while True:
try:
x = next(it)
print(x)
except StopIteration:
break
print("---------------")
L = [2, 3, 5, 7]
for x in L:
print(x)
print("程序结束")
|
import sys, os
from math import sin,pi
from random import choice
from Utils.observer import *
from Utils.signal import *
from Utils.wav_audio import save_wav
from tkinter import Tk,Canvas, messagebox
from tkinter import filedialog
# TODO: removed unused imports
class Signal(Subject):
"""Signal class"""
def __... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index),
url(r'^validate$', views.validate),
url(r'^dashboard$', views.dashboard),
url(r'^create$', views.create),
url(r'^additem$', views.additem),
url(r'^wishes/(?P<id>\d+)$', views.wishes),
url(r'^log... |
from django.contrib import admin
from esign.models import SigEnvelope, SignRequest, Recipient
admin.site.register(SigEnvelope)
admin.site.register(SignRequest)
admin.site.register(Recipient)
|
# O(nlogn) Time | O(1) Space, where n is length of coins
def nonConstructibleChange(coins):
# Write your code here.
canConstructUpto = 0
coins.sort()
for coin in coins:
if coin > canConstructUpto + 1:
break
else:
canConstructUpto += coin
return canConstructUpto + 1
# O(n*n^n) Time | O(n) Space, ... |
import re
# a = re.compile('fChain->SetBranchAddress("^[\w\s\S&]$"^[\w\s\S&,]$);')
a = re.compile('SetBranchAddress')
num = 10
count = 0
for i in open("branch_need_toSet.Cpp","r").readlines():
if count<num:
if 'SetBranchAddress' in i:
new_text = a.sub(r'hhh',i)
print new_text
... |
# -*- coding: utf-8 -*-
import os
class Configuration(object):
APPLICATION_DIR = os.path.dirname(os.path.realpath(__file__))
DEBUG = True
## dialect+driver://username:password@host:port/database
## postgresql://postgres:secretpassword@localhost:5432/blog_db
SQLALCHEMY_DATABASE_URI = 'sqlite:///%s/s... |
# -*- coding: utf-8 -*-
import socket
import time
def egcd(a, b):
(x, lastx) = (0, 1)
(y, lasty) = (1, 0)
while b != 0:
q = a // b
(a, b) = (b, a % b)
(x, lastx) = (lastx - q * x, x)
(y, lasty) = (lasty - q * y, y)
return (lastx, lasty, a)
def modinv(a, m):
(inv, q, gcd_val) = egcd(a, m)
... |
from Model import *
from DataType import *
from TemplateFile import *
class MyModel(Model):
def __init__(self):
Model.__init__(self, 'Model')
self.setupDataTypes()
self.setupDatabases()
self.setupPythonModules()
def setupDataTypes(self):
self.createDataType('Integer')
... |
'''
Created on 2020-09-21 11:55:42
Last modified on 2020-09-22 07:57:56
@author: L. F. Pereira (lfpereira@fe.up.pt))
Main goal
---------
Show how the supercompressible example can be coded in a non object-oriented
strategy.
'''
# imports
# abaqus
from caeModules import * # allow noGui
from abaqus import mdb, backw... |
#!/usr/bin/python3
"""Outsiders"""
import os
PROJECT_DIR = os.path.dirname(os.path.dirname(
os.path.dirname(os.path.abspath(__file__))))
DATASETS_DIR = PROJECT_DIR + '/datasets/'
MEDIA_DIR = PROJECT_DIR + '/media/'
def prepare_query(query):
"""Strip all except words"""
return ''.join(e for e in query if e... |
# Problem Set 2, hangman.py
# Name: Haley Bates-Tarasewicz
# Collaborators: William Kalb
# Time spent: 2:00
# Hangman Game
# -----------------------------------Provided Code
import random
import string
WORDLIST_FILENAME = "words.txt"
def load_words():
print "Loading word list from file..."
# inFile: file
... |
# -*- coding:utf8 -*-
'''
Created on 2018年6月1日
@author: chenzf
'''
import requests
import re
from requests.exceptions import RequestException
from multiprocessing import Pool
from bs4 import BeautifulSoup
from urllib.parse import urljoin
import json
import os,sys
parentdir = os.path.dirname(os.path.dirname(os.path.d... |
## Predicitng Models
from keras.models import load_model
from keras.preprocessing import image
from keras.applications.vgg16 import preprocess_input
import numpy as np
model = load_model('model_vgg19.h5')
img = image.load_img('val/PNEUMONIA/person1946_bacteria_4874.jpeg', target_size=(224, 224))
x = image.img_to_arra... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.