index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
200
1a7e83fe9528b177246d6374ddaf2a76a0046e83
# coding:utf-8 import jieba import os import sys import math reload(sys) sys.setdefaultencoding('utf-8') from sklearn import feature_extraction from sklearn.feature_extraction.text import TfidfTransformer from sklearn.feature_extraction.text import CountVectorizer #import csv #import pandas #import numpy sente...
201
7e7e96fb9377e4dc59a46a46951f5057ecae419a
# -*- coding: utf-8 -*- import random import gym import numpy as np from collections import deque from keras.models import Sequential from keras.layers import Dense from keras.optimizers import Adam from simulation_utils import box, simulation from kinematics import pose3D a = np.log(2)/25 apdataX = np.random.random(...
202
b6183daa943cc63fd2959e3e54fc1e6af5d761de
# -*- coding: utf-8 -*- import math #COMECE SEU CÓDIGO AQUI f = float(input('Digite o valor de f: ')) L = float(input('Digite o valor de L: ')) Q = float(input('Digite o valor de Q: ')) DeltaH = float(input('Digite o valor de DeltaH: ')) v = float(input('Digite o valor de v: ')) g = 9.81 e = 0.000002 #PROCESSAMENTO D =...
203
1490fecd6e983c0e3093a45d77d6fb8afdb54718
# ****************************************************************************** # main.py # # Date Name Description # ======== ========= ======================================================== # 6/5/19 Paudel Initial version, # ***********************************************************************...
204
e5d7cc65041d65f915d4882b4fdad5bebf79a067
from collections import defaultdict from typing import Union, Iterable, Sized import numpy as np from cached_property import cached_property from keras.utils import to_categorical from keras.preprocessing.sequence import pad_sequences from keras.preprocessing.text import Tokenizer, text_to_word_sequence class Source...
205
e221553f866de8b3e175197a40982506bf8c1ef9
import torch import torch.nn.functional as F import csv class Net(torch.nn.Module): def __init__(self, n_feature, n_hidden, n_output): super(Net, self).__init__() self.hidden = torch.nn.Linear(n_feature, n_hidden) self.predict = torch.nn.Linear(n_hidden, n_output) def forward(self, x...
206
39dda191ab2137b5f5538660f17e39b0a1358bf4
import numpy as np import cv2 import colorsys from matplotlib import pyplot as plt img = cv2.imread('coins.jpg') b,g,r = cv2.split(img) rgb_img = cv2.merge([r,g,b]) gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) # Blurring image grayBlur = cv2.medianBlur(gray, 3) # Binary threshold ret, thresh = cv2.threshold(grayBl...
207
0e6e84a31b626639e2aa149fd1ef89f3ef251cd7
# -*- coding: utf-8 -*- ################################## # @program synda # @description climate models data transfer program # @copyright Copyright "(c)2009 Centre National de la Recherche Scientifique CNRS. # All Rights Reserved" # @license CeCILL (https://raw.g...
208
c0d71d970b2632dbf182a5ee8bad27d3e41578f6
#!/Library/Frameworks/Python.framework/Versions/3.7/bin/python3 import sys def sumInput(text): f = open(text, 'r') sum = 0 count = 1 for line in f: count += 1 line = line.strip() if (line[0] == '+'): sum += int(line[1:]) else: sum -= int(line[1:...
209
f14d46bedd5f6e0081a982251ad45e95860ef310
class HashTable: def __init__(self): self.dados = [] def hash(self, chave): return int(chave) def __put(self, int, chave, valor): self.dados.append({chave: valor}) """ backup = dados dados = novo_array(t * 2) for elemento in backup: hash = hash(elemento.chave) __put(...
210
21a41356fcedb36223498db0fe783e4a9e8e1ba6
# help from https://stackoverflow.com/questions/19007383/compare-two-different-files-line-by-line-in-python with open('Book1.txt', 'r') as file1: with open('20k.txt', 'r') as file2: same = set(file1).intersection(file2) same.discard('\n') with open('notin20kforBook1.txt', 'w') as file_out: for line i...
211
de7b5e44c5c213e4ab70b0f8c0c402edaf4926e0
from django.conf.urls import url from .import views app_name='user' # user子路由 urlpatterns = [ # user首页 url(r'^$',views.index,name='index'), # 用户登录 url('login/', views.login, name='login'), # 用户注册 url('regist/', views.regist, name='regist'), # 根据id判断用户是否存在 url(r'^getuser\w*/(?P<id>\...
212
cc7f1f38efcd4d757c1d11e2bd53695fca44e15a
'For learning OWL and owlready2' 'From "https://qiita.com/sci-koke/items/a650c09bf77331f5537f"' 'From "https://owlready2.readthedocs.io/en/latest/class.html"' '* Owlready2 * Warning: optimized Cython parser module "owlready2_optimized" is not available, defaulting to slower Python implementation' '↑ This wartning mean...
213
a2e2528f560f6117d4ceeb9cd20d3f6f6b2a30a7
# -*- coding: utf-8 -*- def testeum(): a = 10 print(id(a)) def testedois(): a = 10 print(id(a))
214
e09af436f2fb37d16427aa0b1416d6f2d59ad6c4
#!/usr/bin/env python3 import argparse import os import sys,shutil from shutil import make_archive import pathlib from phpManager import execute,execute_outputfile from datetime import date,datetime import re import pymysql import tarfile def append_log(log,message): f = open(log, "a+") today = datetime.now()...
215
46adb1834f6013ca0f13a64f280182a805d76278
#!/usr/bin/python3 # encoding: utf-8 import sys import argparse import logging from pathlib import Path module = sys.modules['__main__'].__file__ __author__ = 'FFX' __version__ = '1.0' log = logging.getLogger(module) def parse_command_line(argv): """Parse command line argument. See -h option :param argv: ...
216
c63e5a2178e82ec6e0e1e91a81145afb735bf7bf
__author__ = 'lei' import unittest from ch3.node import TreeNode as t import ch3.searchRange as sr class MyTestCase(unittest.TestCase): def test_1(self): a = t(2) b=t(1) a.left = b self.assertEqual(sr.searchRange(a,0,4), [1,2]) def test_2(self): a = t(20) b = ...
217
b77da75b01e96ff89f873f4c5764a62cf68cd576
from rest_framework import serializers from .models import * __all__ = ( 'CatalogCoinListSerializer', 'CatalogCoinSerializer', 'SeriesListSerializer', 'CoinListSerializer', 'CoinSerializer', 'CountriesListSerializer', ) class CountriesListSerializer(serializers.ModelSerializer): class Meta: mode...
218
1f0695f0e9745912d8ee3a87e6c9b1272e9ebbae
""" Writes day of the week and time to a file. Script written for crontab tutorial. Author: Jessica Yung 2016 """ import time filename = "record_time.txt" # Records time in format Sun 10:00:00 current_time = time.strftime('%a %H:%M:%S') # Append output to file. 'a' is append mode. with open(filename, 'a') as hand...
219
142a2ba3ec2f6b35f4339ed9fffe7357c1a85fa0
import requests import time import urllib import argparse from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.common.keys import Keys from fake_useragent import UserAgent from multiprocessing import Pool from lxml.html import fromstring import os, sys #text = 'chowchowbaby' #url='https...
220
2a19c2d6e51e9c123236c58f82de1a39e5db40f4
import numpy as np # Copyright 2011 University of Bonn # Author: Hannes Schulz def cnan(x): """ check for not-a-number in parameter x """ if np.isnan(x).sum()>0: import pdb pdb.set_trace() def get_curve_3D(eig, alpha=0.25,g23=0.5,g12=0.5): # renumerated according to sato et al: l3 is smallest...
221
550f5ad4fef77d5795db0393ae0701f679143e72
#!/usr/bin/env python # @HEADER # ************************************************************************ # # TriBITS: Tribal Build, Integrate, and Test System # Copyright 2013 Sandia Corporation # # Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, # the U.S. Govern...
222
4fa9d16f979acf3edce05a209e1c6636e50fc315
from jox_api import label_image,Mysql,Utils from jox_config import api_base_url import json class Menu(): def __init__(self): self.mysqlClass = Mysql.MySQL() self.timeClass = Utils.Time() def get_menu(self,type,openid): try: if type == 'mine': self.sql = "SEL...
223
e5e012e40a71dee9f4dbd9913590aef125b758df
from classes.Board import Board class Visualiser: coordinate_map = ("a", "b", "c", "d", "e", "f", "g", "h") __dimensions = 8 def __init__(self): self.map = [] self.__build_map() def __build_map(self): """ Creates the array of the battlefield. Should never be used for ...
224
c4e4e54ac93c2acdbd3a1cd22b200341a6e45688
import pyaudio import numpy as np from collections import OrderedDict import utils class MasterPlayer(object): def __init__(self, volume=1., samplesPerSecond=44100): self.p = pyaudio.PyAudio() self.volume = volume self.samplesPerSecond = samplesPerSecond self.individual_callbacks =...
225
27e9e63338d422b5fca6f7a67fa3d255602a3358
from abstract_class_V import V import torch import torch.nn as nn class V_test_abstract(V): def __init__(self): super(V_test_abstract, self).__init__() def V_setup(self,y,X,nu): self.explicit_gradient = False self.need_higherorderderiv = True self.dim = X.shape[1] self...
226
ec4348c61cd1c9130543bb20f9ca199399e1caff
class Solution(object): def restoreIpAddresses(self, s): """ :type s: str :rtype: List[str] """ def helper(sb, string, level): if len(string) == 0: if level == 4: ans.append(sb[:-1]) return if level ...
227
d0a3f332e04627eb275168972bd92cd1ea9b9447
from board.ttt import TTT from mctsai.mcts import MCTS import unittest # skip = [0, 1] skip = [0] class TestTTT(unittest.TestCase): def test_mcts(self): if 0 in skip: print("Skipping ai self-play") return ttt = TTT() for i in range(1000): mcts = MCTS(tt...
228
e95bda8be2294c295d89f1c035bc209128fa29c8
def merge_the_tools(string, k): # your code goes here num_sub_strings = len(string)/k #print num_sub_strings for idx in range(num_sub_strings): print "".join(set(list(string[idx * k : (idx + 1) * k])))
229
f85a703b47d981397ed6048e941030a3fbee7b6d
# -*- coding: utf-8 -*- # Generated by Django 1.9.8 on 2018-04-27 08:05 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('talk', '0023_auto_20180207_1121'), ] operations = [ migrations.AddField( ...
230
23375760c0943ca177b7009031d9d17a91165c5c
#!/usr/bin/env python #--coding: utf8-- import time if __name__ == '__main__': date = time.strftime('%m-%d') if date == '03-08': print '女神节' elif date == '02-14': print '情人节' else: print '发红包' print '这是一个测试题'
231
f8d815bcdc74452b66a1b3b33bf0fbe976e728c8
# This is a sample Python script. # Press Shift+F10 to execute it or replace it with your code. # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings. import tensorflow as tf from tensorflow.keras import datasets, layers, models import matplotlib.pyplot as plt import numpy ...
232
ef85f94282bfd7c9491c4e28bab61aaab5c792a5
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'src/ui_LibraryTab.ui' # # Created: Tue Jun 9 21:46:41 2015 # by: PyQt5 UI code generator 5.4 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Tab(object): def setupUi(se...
233
8c8bbbc682889c8d79c893f27def76ad70e8bf8d
DATABASE_NAME = "user_db"
234
9d904225afd4f4d0cf338ae16f031f8ab41639ad
# -*- coding=utf-8 -*- from mako.template import Template from xblock.fragment import Fragment from .lookup import TemplateLookup # xblock_ifmo.lookup from .utils import deep_update class FragmentMakoChain(Fragment): """ Класс, позволяющий последовательно оборачивать экземпляры Fragment друг в друга. ...
235
8cc0393082448bb8f61068b5c96e89ef3aee77ed
#coding: utf-8 import logging from threading import Thread from ldap import SCOPE_BASE from seafevents.ldap_syncer.ldap_conn import LdapConn from seafevents.ldap_syncer.utils import bytes2str, add_group_uuid_pair from seaserv import get_group_dn_pairs logger = logging.getLogger(__name__) def migrate_dn_pairs(set...
236
21af630bf383ee1bdd0f644283f0ddadde71620a
#!/bin/usr/python2.7.x import os, re, urllib2 def main(): ip = raw_input(" Target IP : ") check(ip) def check(ip): try: print "Loading Check File Uploader...." print 58*"-" page = 1 while page <= 21: bing = "http://www.bing.com/search?q=ip%3A" + \ ip + "+upload&count=50&first=" + str(...
237
eb853e430b996a81dc2ef20c320979a3e04d956a
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- import hashlib import re from datetime import datetime import gevent import requests import scrapy from gevent.pool import Pool from lxml import etree from scrapy.http import HtmlResponse from sqlalchemy import create_engine, func from sqlalchemy.orm import sessionmaker ...
238
bc4684d255a46427f708d8ce8bda2e12fb8c8ffe
# -*- coding: utf-8 -*- from route4me import Route4Me API_KEY = "11111111111111111111111111111111" def main(): r4m = Route4Me(API_KEY) route = r4m.route response = route.get_routes(limit=1, offset=0) if isinstance(response, dict) and 'errors' in response.keys(): print('. '.join(response['err...
239
d015a1b27a3a9e7f5e6614da752137064000b905
#!/usr/bin/env python3 """Transfer learning with xception""" import tensorflow.keras as K from GPyOpt.methods import BayesianOptimization import pickle import os import numpy as np class my_model(): """A model bassed on xception""" def make_model(self, param): """makes the model""" self.lr = ...
240
ef6f55bf27982f53441215da6822cfcdc80706a5
# -*- coding: utf-8 -*- __author__ = 'Yun' __project__ = 'DjangoBookTest2' # from django.template import Template, Context # from django.template.loader import get_template # from django.http import HttpResponse from django.shortcuts import render_to_response import datetime def current_datetime(request): # now ...
241
e8226ab6be5c21335d843cba720e66646a2dee4e
import os import requests import sqlite3 from models import analytics, jcanalytics def populate(): url = 'https://api.clicky.com/api/stats/4?site_id=100716069&sitekey=93c104e29de28bd9&type=visitors-list' date = '&date=last-30-days' limit = '&limit=all' output = '&output=json' total = url+date+limi...
242
e616d14827beaa08ab08219421cbf7990cf163fd
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.InsureAdmitDTO import InsureAdmitDTO class AlipayInsSceneEcommerceInsureCheckModel(object): def __init__(self): self._insure_admit_dto_list = None self._partn...
243
c4ca4b5c77c3c912b44a4853be30298ec845c4fd
#str owog="Delger" # len()- urt # lower()- jijigruuleh # upper()- tomruulah # capitalize()- ehnii useg tomruulah # replace()- temdegt solih print(owog.find("e")) print(owog.count("e")) print(owog[2:10]) a=21 b=21 if a>b: print("a too ih") elif a==b: print("tentsuu") else: print("b to...
244
050e2207ac7331444d39305869c4b25bcbc53907
import pandas as pd from sklearn.preprocessing import MinMaxScaler #loading data from CSV training_data_df = pd.read_csv("sales_data_training.csv") test_data_df = pd.read_csv("sales_data_test.csv") #scaler scaler = MinMaxScaler(feature_range=(0,1)) #scale both inputs and outputs scaled_training = scaler.fit_transfor...
245
df64d769ffba8cddac34282a526122e3c941249d
#!/usr/bin/env python import os import tempfile import shutil import math import sys import subprocess from irank.config import IrankOptionParser, IrankApp from irank import db as irank_db STATUS = 0 def main(): p = IrankOptionParser('%prog -d DEST playlist_name [playlist_name ...]') p.add_option('-d', '--dest', he...
246
21b295e28a7e4443ea116df1b22ff5074dca955a
n =int(input("nhap gia tri")) for i in range(1,n+1): print(i)
247
93737e4c409d0efb1ae2263cb60d4b03d9aad0d8
import os import shutil import argparse ap = argparse.ArgumentParser() ap.add_argument('-D','--dir', required=False, help='Directory to sort') args = vars(ap.parse_args()) if args['dir'] == None: DIR = os.getcwd() elif os.path.exists(args['dir']): DIR = args['dir'] for file in os.listdir(DIR): if not os....
248
b5611c668a40e1735c92d6d00867885023ad713f
target=[] with open('IntegerArray.txt','r') as f: target=f.readlines() for x in range(len(target)): target[x]=int(target[x]) def f(A): if len(A)==1: return 0 else: rightStart=len(A)//2 leftArray=A[0:rightStart] righArray=A[rightStart:] B,b=count_and_sort(leftArray) C,c=count_and_sort(righA...
249
09f032301fa9389f6b07687e0ee13844e0b4ddf3
from artichoke import DefaultManager, Config from artichoke.helpers import read, prompt from fabric.api import env, task, run import os chars = ''.join(chr(c) if chr(c).isupper() or chr(c).islower() else '_' for c in range(256)) class MagicDefaultManager(DefaultManager): def __init__(self, env): self.en...
250
68b967ecf18d576758cf05e889919944cfc34dcd
""" generalised behaviour for actors and vacancies """ from mesa import Agent from random import shuffle import numpy as np class Entity(Agent): """ superclass for vacancy and actor agents not intended to be used on its own, but to inherit its methods to multiple other agents """ def __init__(sel...
251
46babde9c26a944c9d29121b6bbf89a32f242a81
import simple_draw as sd import random # sd.resolution = (1400, 900) # Prepare data for the sun function def sun_prepare(xpoint, ypoint, radius, color, angle): delta_list = [] radius_list = [] for delta in range(0, 360, angle): delta_list.append(delta) radius_list.append(random.randint(ra...
252
e736991f364ba9ff709348e4b1f612b1e9673281
from flask import * app=Flask(__name__) from app import views from app import admin_views from app import usr_reg from app import cookie from app import db_connect
253
07215403750be53994ae36727b6f790202b88697
# Inspiration: [Fake Album Covers](https://fakealbumcovers.com/) from IPython.display import Image as IPythonImage from PIL import Image from PIL import ImageFont from PIL import ImageDraw import requests from xml.etree import ElementTree as ET def display_cover(top,bottom ): name='album_art_raw.png' alb...
254
18d3f58048b7e5d792eb2494ecc62bb158ac7407
from flask import Flask from flask import render_template from flask import make_response import json from lib import powerswitch app = Flask(__name__) @app.route('/') def hello_world(): return render_template('index.html') @app.route('/on/') def on(): state = powerswitch.on() return json.dumps(state) ...
255
869284fa531a93c1b9812ed90a560d0bb2f87e97
# fonction pour voir quel est le plus grand entre l'energie limite et l'enerve potentiel def ep (m,h,el,g=9.8): E=m*h*g if E<el: print ("le plus grand est : el") else: print ("le plus grand est : E") ep(3,4,5) #fontion fibonaci 0 1 1 2 3 5 8 13 def fibonaci(n): for i in range(0,n,): ...
256
d126efa91b964a3a374d546bb860b39ae26dfa22
"""A tiny example binary for the native Python rules of Bazel.""" import unittest from bazel_tutorial.examples.py.lib import GetNumber from bazel_tutorial.examples.py.fibonacci.fib import Fib class TestGetNumber(unittest.TestCase): def test_ok(self): self.assertEqual(GetNumber(), 42) def test_fib(self): ...
257
e582787a912f479830ed99575b2c6adb8088b4e5
from flask import Flask, request from flask import jsonify from preprocessing import QueryProcessor from flask_cors import CORS app = Flask(__name__) CORS(app) qp = QueryProcessor() @app.route('/search_general', methods=['POST']) def query(): message = None searchQuery = request.json['searchQuery'] resul...
258
cf0cf028d5f67e8deca8ebd3ad76d9c1e3563002
#!/usr/bin/python2 import sys import argparse """ This program generates an extract table having the following format: <S1> <S2> <S3> ... <Sn> ||| <T1> <T2> <T3> ... <Tk> ||| 0-0 Each line is a mapping from a source sentence to target sentence with special delimiter characters. You can give the output of this s...
259
f8bf7e2d8f06bbd00f04047153833c07bf483fd3
from django.apps import AppConfig class PyrpgConfig(AppConfig): name = 'PyRPG'
260
48677d73f6489ce789884a9dff5d50c23f47d8b3
__author__ = 'simon.hughes' from sklearn.feature_extraction import DictVectorizer from WindowFeatures import compute_middle_index from collections import Counter class WindowFeatureExtractor(object): """ A simple wrapper class that takes a number of window based feature extractor functions and applies the...
261
65aa85675393efa1a0d8e5bab4b1dbf388018c58
indelCost = 1 swapCost = 13 subCost = 12 noOp = 0 def alignStrings(x,y): nx = len(x) ny = len(y) S = matrix(nx+1, ny+1) #?? for i in range (nx+1) for j in range (ny+1) if i == 0: #if the string is empty S[i][j] = j #this will put all the letters from j in i elif j == 0: #if the second string ...
262
47c1ad4bd1ceffa38eef467ea8eb59dbd2fc2ebb
from packet import Packet from packetConstructor import PacketConstructor import threading import time class PacketSender: """ Packet represents a simulated UDP packet. """ # The next seq num for sent packets seq_num = 0 # The next seq num for acks that we're waiting for next_seq_num = 0 ...
263
24cdbbadc8ff1c7ad5d42eeb518cb6c2b34724a2
from openfermion import QubitOperator, FermionOperator from openfermion.transforms import jordan_wigner from src.utils import QasmUtils, MatrixUtils from src.ansatz_elements import AnsatzElement, DoubleExchange import itertools import numpy class EfficientDoubleExchange(AnsatzElement): def __init__(self, qubit_...
264
2843845848747c723d670cd3a5fcb7127153ac7e
from flask import Flask from sim.toggle import ToggleSensor from sim.sensor import Sensor app = Flask(__name__) sensors = [ ToggleSensor(id="s-01", description="lampadina"), ToggleSensor(id="s-02", description="lampadina"), ToggleSensor(id="s-03", description="allarme atomico"), ToggleSensor(id="s-04...
265
f5bd41f4aaff616a332d80ec44c364ffc91c58f0
# %load q03_skewness_log/build.py from scipy.stats import skew import pandas as pd import numpy as np data = pd.read_csv('data/train.csv') # Write code here: def skewness_log(df): df['SalePrice_New'] = np.log(df['SalePrice']) df['GrLivArea_New'] = np.log(df['GrLivArea']) skewed_slPri = skew(df['SalePrice...
266
d65f858c3ad06226b83d2627f6d38e03eae5b36c
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Phase transition module """ import utils import datetime import itertools import numpy as np import recovery as rec import sampling as smp import graphs_signals as gs import pathos.multiprocessing as mp from tqdm import tqdm ## MAIN FUNCTIONS ## def grid_evalua...
267
f97a892e6e0aa258ad917c4a73a66e89b0dc3253
# coding: utf-8 # In[1]: import sys sys.path.extend(['detection', 'train']) # from detection folder from MtcnnDetector import MtcnnDetector from detector import Detector from fcn_detector import FcnDetector # from train folder from model_factory import P_Net, R_Net, O_Net import config as config from preprocess.uti...
268
f19d8aa2104240cc93a0146f1b14c635e7cd3a41
#! /usr/bin/env python import ldac from numpy import * import shearprofile as sp import sys import os, subprocess import pylab if len(sys.argv) != 6: sys.stderr.write("wrong number of arguments!\n") sys.exit(1) catfile= sys.argv[1] clusterz=float(sys.argv[2]) center= map(float,sys.argv[3].split(',')) pixsc...
269
0e58834120c34b5152026bde6d089be19244e21a
import os from MdApi import MdApi class Adapter(MdApi): def __init__(self): super(Adapter, self).__init__() def connect(self): self.createFtdcMdApi(os.getcwd()) self.registerFront('tcp://180.168.146.187:10010') def onFrontConnected(self): print 'front succ...
270
df40b0628d6a180a98cd385145ee7c65ecb78256
import os import tensorflow as tf import torch from tqdm import tqdm from glob import glob import numpy as np from collections.abc import Iterable from utils.hparams import HParam #from utils.audio import Audio #import librosa #python encoder_inference.py --in_dir training_libri_mel/train/ --gpu_str 5 #python tfrecord...
271
ed7b29a4d7f3a48884434373418c3528f2f397ac
#!/usr/bin/python3 import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # or any {'0', '1', '2' os.environ['KERAS_BACKEND'] = 'tensorflow' import numpy as np import sys from util import load_model from keras.preprocessing.text import hashing_trick from keras.preprocessing.sequence import pad_sequences from southpar...
272
b6d8a918659f733919fe3bb4be9037e36ad32386
import queue import sys import logging from superai.common import InitLog logger = logging.getLogger(__name__) # 2维到1维 def hwToidx(x: int, y: int, weight: int): return y * weight + x # 1维到2维 def idxTohw(idx, weight: int): return [idx % weight, idx // weight] # 10x10 cell idx 到 [x,y] def idxToXY(idx, cel...
273
7930bb813bd546747c7c65b661900939f5ba93f1
user_input = input() #abv>1>1>2>2asdasd exploded_str = user_input for n in range(len(user_input)): explosion_strength = 0 if user_input[n] == ">": explosion_strength += int(user_input[n+1]) if user_input[n+explosion_strength] != ">": exploded_str = user_input[:n] + user_input[n+ex...
274
c6cf085330f47ffb139c5acc91d91e9758f5396a
from page_objects import PageObject, PageElement class MainPage(PageObject): level_menu_opened = False level_menu_created = False css_input = PageElement(css='input.input-strobe') level_text_span = PageElement(css='span.level-text') instruction_h2 = PageElement(css='h2.order') enter_button = P...
275
c2ddf31bce4a5f3ae2b0d5455bbc9942f92bff40
import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' from keras.models import load_model from utils import resize_to_fit, clear_chunks, stack_windows from imutils import paths import numpy as np import imutils import cv2 as cv2 import pickle from tqdm import tqdm c1_correct = 0 c2_correct = 0 c3_correct = 0 c4_correct ...
276
75e6554ea3c327c87a2a65710a7f1d55e9933bb0
# Author: BeiYu # Github: https://github.com/beiyuouo # Date : 2021/2/21 21:57 # Description: __author__ = "BeiYu" from utils.init_env import set_seed from utils.options import * import os import logging import torch from torch import nn from torch import optim from torch.optim.lr_scheduler import MultiStepLR from ...
277
58f3b8c5470c765c81f27d39d9c28751a8c2b719
"""Ex026 Faça um programa que leia uma frase pelo teclado e mostre: Quantas vezes aparece a letra "A". Em que posição ela aparece a primeira vez. Em que posição ela aparece pela última vez.""" frase = str(input('Digite uma frase: ')).strip().lower() n_a = frase.count('a') f_a = frase.find('a')+1 l_a= frase.rfind('a')-1...
278
d83f2d9bb25a46bc7344b420ce65bf729165e6b9
from django.apps import AppConfig class FosAppConfig(AppConfig): name = 'fos_app'
279
d2b05c5653ca6c6b7219f6c0393e81c9425b5977
""" HLS: Check if Twin Granule Exists """ from typing import Dict import os import re import boto3 from botocore.errorfactory import ClientError from datetime import date s3 = boto3.client("s3") bucket = os.getenv("SENTINEL_INPUT_BUCKET", None) print(bucket) if bucket is None: raise Exception("No Input Bucket set"...
280
c73a199d1c1c1867f3d53ceebf614bc9b65c0d5e
from django.contrib import admin from ticket.models import Ticket, UserTicket, AuxiliaryTicket @admin.register(Ticket) class TicketAdmin(admin.ModelAdmin): pass @admin.register(AuxiliaryTicket) class AuxiliaryTicketAdmin(admin.ModelAdmin): pass @admin.register(UserTicket) class UserTicketAdmin(admin.Mode...
281
e564e0d05c3c0e60f356422722803df510d9dd0b
import numpy as np import pandas as pd from sklearn.metrics import confusion_matrix from sklearn.metrics import classification_report from sklearn.metrics import precision_score, recall_score, f1_score from scipy.optimize import fsolve import numba from numba import njit,jit # @jit(parallel = True) def conventional_tes...
282
9bc13c608c079cbf23ed04f29edd1fd836214cde
from rest_framework import viewsets, mixins from .models import Comment, Post from .serializer import CommentSerializer, PostSerializer, AllCommentSerializer class PostViewSet(viewsets.ModelViewSet): serializer_class = PostSerializer queryset = Post.objects.all() class CommentViewSet(viewsets.GenericViewSet...
283
b11e2837d3ba9c14770b8039186a2175adc41ea1
from .server import CanvasServer try: from .jupyter import JupyterCanvas, create_jupyter_canvas HAS_JUPYTER = True except: HAS_JUPYTER = False JupyterCanvas = None # type: ignore def http_server( file: str = None, host: str = "localhost", port: int = 5050 ) -> CanvasServer: """Creates a new...
284
2da7892722afde5a6f87e3bd6d5763c895ac96c9
import json import os import ipdb from tqdm import tqdm import argparse from os import listdir from os.path import isfile, join import pickle import joblib from collections import Counter from shutil import copyfile import networkx as nx import spacy import nltk import numpy as np nltk.download('stopwords') nltk_stopw...
285
e38ae7f91deed1be00e60b7516210ea1feefe23e
import sys import os from configparser import ConfigParser import logging from mod_argparse import setup_cli from checkers.IndexFile import DocumentIndex, ProgressNoteIndex from checkers import source_files from utilities import write_to_file, strip # , write_to_db_isok # import pandas as pd logger = logging.getLogger...
286
069338b188f3cf16357b2502cbb3130b69918bd9
from .cli import cli if __name__ == "__main__": exit(cli.main(prog_name="htmap"))
287
b52269237d66ea50c453395b9536f25f1310bf2e
#!/usr/bin/env python2.7 # -*- coding: utf-8 -*- import re from blessings import Terminal from validate_email import validate_email import requests import sys _site_ = sys.argv[1] _saida_ = sys.argv[2] _file_ = open(_saida_, "w") t = Terminal() r = requests.get(_site_, headers={'User-Agent': 'Mozilla/5.0 (Windows NT 6....
288
8c539dbbb762717393b9a71ddca8eb3872890854
import re import os import pandas as pd instruments_file = os.path.abspath("instruments.csv") input_names_file = os.path.abspath("names.txt") output_names_file = os.path.abspath("names.csv") inst_name_file = os.path.abspath("name_instrument.csv") reg_ex = '; |, |\\*|\n' name_header = ["first_name", "last_name"] def ...
289
0db0daf9bea254cffaec1280cd13b2d70368cd94
import numpy.random as rnd import numpy as np B=100000 N1=50 N2=50 p1mle=0.3 p2mle=0.4 taumle=p2mle-p1mle estimate=[] for i in range(B): p1=0.0 for j in range(N1): if(rnd.uniform(0,1)<p1mle): p1+=1 p1/=N1 p2=0.0 for j in range(N2): if(rnd.uniform(0,1)<p2mle): p2+=1 p2/=N2 estimate.append(p2-p...
290
a90b7e44cc54d4f96a13e5e6e2d15b632d3c4983
import random import string import steembase import struct import steem from time import sleep from time import time from steem.transactionbuilder import TransactionBuilder from steembase import operations from steembase.transactions import SignedTransaction from resultthread import MyThread from charm.toolbox.pairingg...
291
ee80169afd4741854eff8619822a857bbf757575
''' Created on 27 Mar 2015 @author: Jon ''' import matplotlib.pyplot as plt from numerical_functions import Timer import numerical_functions.numba_funcs.indexing as indexing import numpy as np import unittest class Test(unittest.TestCase): def test_take(self): x = np.linspace( 0, 100 ) ...
292
ce6dba2f682b091249f3bbf362bead4b95fee1f4
""" .. currentmodule:: jotting .. automodule:: jotting.book :members: .. automodule:: jotting.to :members: .. automodule:: jotting.read :members: .. automodule:: jotting.style :members: """ from .book import book from . import style, to, read, dist
293
99c839eddcbe985c81e709878d03c59e3be3c909
#coding=utf-8 ######################################### # dbscan: # 用法说明:读取文件 # 生成路径文件及簇文件,输出分类准确率 ######################################### from matplotlib.pyplot import * import matplotlib.pyplot as plt from collections import defaultdict import random from math import * import numpy import datetime ...
294
bf8bbeb408cb75af314ef9f3907456036e731c0b
def solution(S): # write your code in Python 3.6 # Definitions log_sep = ',' num_sep = '-' time_sep = ':' # Initialization from collections import defaultdict # defaultdict initialize missing key to default value -> 0 bill = defaultdict(int) total = defaultdict(int) calls = S...
295
35ae9c86594b50bbe4a67d2cc6b20efc6f6fdc64
#配置我们文件所在目录的搜寻环境 import os,sys #第一步先拿到当前文件的路径 file_path = os.path.abspath(__file__) #第二步 根据这个路径去拿到这个文件所在目录的路径 dir_path = os.path.dirname(file_path) #第三步:讲这个目录的路径添加到我们的搜寻环境当中 sys.path.append(dir_path) #第四步,动态设置我们的setting文件 os.environ.setdefault("DJANGO_SETTINGS_MODULE", "gulishop.settings") #第五步,让设置好的环境初始化生效 ...
296
d34159536e860719094a36cfc30ffb5fcae72a9a
#API End Points by Mitul import urllib.error, urllib.request, urllib.parse import json target = 'http://py4e-data.dr-chuck.net/json?' local = input('Enter location: ') url = target + urllib.parse.urlencode({'address': local, 'key' : 42}) print('Retriving', url) data = urllib.request.urlopen(url).read() print('Retrive...
297
c382b298cce8d7045d6ce8a84f90b3800dba7717
# Generated by Django 3.0.7 on 2020-06-15 15:26 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('products', '0003_auto_20200615_1225'), ] operations = [ migrations.AlterField( model_name='product', name='harmoniza...
298
3372d98ff91d90558a87293d4032820b1662d60b
from django.conf.urls import patterns, url from riskDashboard2 import views urlpatterns = patterns('', #url(r'getdata', views.vulnData, name='getdata'), url(r'appmanagement', views.appmanagement, name='appmanagement'), url(r'^.*', views.index, name='index'), )
299
0465e33d65c2ce47ebffeec38db6908826bf4934
people = 20 cats = 30 dogs = 15 if people < cats: print("Too many cats") elif people > cats: print("Not many cats") else: print("we cannnot decide")