text
stringlengths
38
1.54M
from binascii import hexlify, unhexlify from io import BytesIO from .. import hashes, compact, ec, bip32, script from ..networks import NETWORKS from .errors import DescriptorError from .base import DescriptorBase from .miniscript import Miniscript from .arguments import Key class Descriptor(DescriptorBase): def ...
from django.db.models.functions import Coalesce, Lower from products.models import Product class Manager: __query = None __products = None __products_output = [] def __call__(self, query): self.__initialize(query) self.__obtain_products() self.__format_product_output() ...
from tree import TreeNode # Test inputs lst = ['apple', 'ape', 'array', 'argon', 'advanced', 'Barry', 'Bee', 'Bat', 'Ball'] class Trie: def implementation(self, lst): self.tree = TreeNode(len(lst)) head_node = self.tree letters_in_tree = [] for word in lst: word = wo...
import cv2 from PIL import Image import numpy as np def pil2cv(image): ''' PIL型 -> OpenCV型 ''' new_image = np.array(image, dtype=np.uint8) if new_image.ndim == 2: # モノクロ pass elif new_image.shape[2] == 3: # カラー new_image = cv2.cvtColor(new_image, cv2.COLOR_RGB2BGR) elif new_image....
import numpy as np import math from data_loader import loader import argparse import time def Merge_sort(A,p,r): if p < r: q = int(math.floor((p+r)/2)) Merge_sort(A,p,q) Merge_sort(A,q+1,r) Merge(A,p,q,r) def Merge(A,p,q,r): n1 = q-p+1 n2 = r-q L = A[p:p+n1].copy() ...
# Copyright 2016 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 or at # https://developers.google.com/open-source/licenses/bsd """Unittests for the projectexport servlet.""" from __future__ import print_function from __fut...
# -*- coding: cp1252 -*- """ Description: Challenge CAMELYON16. Script for pixel classification. Authors: Vaïa Machairas, Etienne Decencière, Peter Naylor, Thomas Walter. Creation date: 2016-02-24 """ from optparse import OptionParser import sys import timeit import pdb import os from getpass import getuser imp...
''' Created on 18 Feb 2016 @author: Maxim Scheremetjew ''' import mysql.connector from mysql.connector import errorcode class MySQLDBConnection: """Context manager class for oracle DB connection""" def __init__(self, **config): self.config = config def __enter__(self): try: ...
import requests import random from bs4 import BeautifulSoup from selenium import webdriver from fake_useragent import UserAgent options = webdriver.ChromeOptions() options.add_argument('headless') # change useragent useragent = UserAgent() options.add_argument(f'user-agent={useragent.random}') url = 'ht...
import pygame from sprites.Ball import Ball from sprites.Brick import Brick from sprites.Paddle import Paddle from threads.RankInput import RankInput from threads.Webcam import Webcam try: from cv2 import cv2 except ImportError: pass import numpy import sqlite3 import random import time # Adjustments SCREEN...
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-11-24 16:08 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('mainApp', '0037_auto_20171124_1823'), ('mainApp', '0034_review'), ] operations = [ ...
#!/sw/bin/python3 """Tool for marking newick-format-tree branches.""" import argparse import sys import re __author__ = "Bogdan Kirilenko, 2018." def eprint(msg, end="\n"): """Like print but for stderr.""" sys.stderr.write(msg + end) def die(msg, rc=1): """Write msg to stderr and abort program.""" ...
import sys import pandas as pd import numpy as np import multiprocessing as mp import time import datetime as dt import adv_finance.sampling as sampling from adv_finance.multiprocess import process_jobs_, process_jobs # from adv_finance.sampling import get_ind_matrix, get_avg_uniqueness def get_rnd_t1(num_obs, num_b...
""" """ import time start_time = time.time() distict_powers = [] for a in range(2,101): for b in range(2,101): cache = a**b if cache not in distict_powers: distict_powers.append(cache) print len(distict_powers) print("--- %s ms ---" %int(round((time.time() - start_time)*1000)))
from .defaults import update_with_defaults from .log_prob import get_log_prob import matplotlib import matplotlib.pyplot as plt from matplotlib import colors from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable from starry_process import StarryProcess from starry_process.latitude import beta2gauss, gaus...
""" Copyright (c) 2016 Keitaro AB 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 https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software dis...
#imports from flask import Flask, request, session, redirect, url_for, abort, render_template, flash from models import Blog, User from werkzeug.security import generate_password_hash, check_password_hash from google.appengine.ext import db import cgi #configuration DEBUG = True app = Flask(__name__) app.secret_ke...
''' InEfficient Implementation of Python Decorator Hacker Rank problem : https://www.hackerrank.com/challenges/standardize-mobile-number-using-decorators/problem ''' def wrapper(f): def fun(l): # complete the function number = '' length = 0 num_list = [] for number in l: ...
import os import json import xmlrpclib import SentimentAnalyzer as sentiment from xml.dom.minidom import parseString allComponents = [] allComponents.append('name') allComponents.append('firstname') allComponents.append('surname') allComponents.append('email') allComponents.append('address') allComponents.append('phon...
# -*- coding: utf-8 -*- # Define your item pipelines here from scrapy.exceptions import DropItem class FilterWordsPipeline(object): """A pipeline for filtering out items which contain certain words in their description""" words_to_filter = ['company', 'Date'] def process_item(self, item, spider...
#!/usr/bin/env python #Written by PJ import string import flask from flask import request, flash, jsonify, Flask, redirect, current_app import requests import json from functools import wraps from flask.ext.restful import Resource, Api # import relevance import pandas as pd import numpy as np import re import math fr...
@pytest.fixture def ff_pair(): ff0 = Forcefield.load_from_file(DEFAULT_FF) ff1 = Forcefield.load_from_file(DEFAULT_FF) # Modify the charge parameters for ff1 ff1.q_handle.params += 1.0 return ff0, ff1 def test_get_solvent_phase_system_parameter_changes(ff_pair): ff0, ff1 = ff_pair mol = f...
# import time #Insertion Sort import random import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt plt.style.use('ggplot') # start_time=time.time() tim=[] bst=[] wrt=[] avg=[] for n in range(10,101,10): tim.append(n) avgarr=[random.randint(1,100) for i in range(n)] bstarr=sorted(avgarr) wrta...
# coding=utf- import logging import pika from pymongo import MongoClient import time import datetime from settings import REQUESTS_QUEUE, MONGO_COLLECTION, MONGO_DB def callback(ch, method, properties, body): mongodb = MongoClient('mongodb', 27017) db = mongodb[MONGO_DB] collection = db[MONGO_COLLECTION...
import os import config from base import * class RapidXML(Base): def __init__(self): self.name = "rapidxml" self.version = "1.13" self.compilers = [config.COMPILER_MAC_GCC, config.COMPILER_MAC_CLANG, config.COMPILER_UNIX_GCC] self.arch = [config.ARCH_M32, config.ARCH_M64] ...
class Solution: def stringMatching(self, words: List[str]) -> List[str]: words.sort(key=len) res = [] lps = [self._compute_lps(w) for w in words[:-1]] for i in range(len(words)): for j in range(i + 1, len(words)): if self._kmp(words[i], words[j], lps[i]): ...
from flask import Flask, render_template, flash, request, redirect, url_for from flask_cors import CORS from flask_wtf import FlaskForm from flask_bootstrap import Bootstrap from flask_wtf.recaptcha import RecaptchaField, Recaptcha from flask_wtf.csrf import CSRFProtect from wtforms import TextField, TextAreaField, Str...
import os import math import csv import datetime from dateutil import rrule import numpy as np import pandas as pd from numpy import random from scipy.fftpack import fft, ifft from federated import t_product # 读取txt文件中的数据,处理成三元组列表形式[src,des,sec] def TxtFileLoad(filepath): DataLoad = [] max_id = -1 max_T =...
# coding=utf-8 # # This file is part of Hypothesis, which may be found at # https://github.com/HypothesisWorks/hypothesis/ # # Most of this work is copyright (C) 2013-2019 David R. MacIver # (david@drmaciver.com), but it contains contributions by others. See # CONTRIBUTING.rst for a full list of people who may hold cop...
from django import template from django.utils.safestring import mark_safe register = template.Library() #register的名字是固定的,不可改变 # simple_tag可以多个参数,filter最多有2个参数 # 但是{% if %}后面只能是filter @register.simple_tag def my_add100_tag(value): return value + 100 @register.filter def my_add100_filter(value1, value2): re...
import argparse import socket HOST = '127.0.0.1' # The server's hostname or IP address PORT = 1993 # The port used by the server def main(key , value, wait=True): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((HOST, PORT)) input = 'STORE '+key+'='+value s....
from django.db import models from django.utils.translation import ugettext as _ from mptt.models import MPTTModel, TreeForeignKey from django.utils.safestring import mark_safe from core.abstract import ( ActiveModel, DescriptionModel, GeoModel, HookModel, NameModel, SeoModel, SlugModel, ...
import os from time import sleep from textwrap import wrap from room import Room from player import Player # from minimap.minimap import MiniMap # Importing from subdirectories from item import Item from item import Treasure from item import LightSource # Declare Global Items items = { 'dandelions': Item('dande...
import speech_recognition as sp recog = sp.Recognizer() with sp.Microphone() as source: audioData = recog.listen(source) # 使用 listen() 方法將聲源存起來 try: question = recog.recognize_google(audioData, language = 'zh-tw') print(question) except: print("聽不懂...")
# Tweepy 3.10.0 import os from dotenv import load_dotenv import tweepy as tw import pandas as pd import matplotlib.pyplot as plt import numpy as np import streamlit as st from textblob import TextBlob import nltk from nltk.sentiment.vader import SentimentIntensityAnalyzer import re # Authentication load_dote...
#!/usr/bin/env python import os from fabric.api import ( task, local, ) from datetime import datetime from new7day import settings DATABASES = settings.DATABASES['default'] @task def manage(cmd): local( 'python manage.py {cmd}'.format(cmd=cmd) ) @task def migrate(): ''' 数据库迁移 '...
import os from lib.conf.config import settings #导入配置路径(实现自定义配置+默认配置的整合) class Nic(object): """获取主机网卡信息""" def __init__(self): pass #执行构造方法之前,可以加点其他操作,可有可无 #类似预留的钩子 @classmethod def initial(cls): return cls() def process(self,command_func,debug): # if debug: ...
#정수형 int 실수형 float x =2 y=4 p=10 q=3 A = x*y #A=8? A=8.0? 당연히 8이다 C = y/x D= x ** y ** x #x의 y의 x승 이다 D=256? D=65536 print(C) #나누기는 소수점이 나와서 2.0 임 나눗셈은 정수에 대해 닫혀있지 않음 print("D=",D) print('17을 3으로 나누면 몫이', 17//3 ,'이고','나머지가', 17%3,"이다") def wow(x,y): a = int(x // y) b = int(x % y) ...
from django.db import models from django.utils.text import slugify from django.shortcuts import reverse from django.db.models import Q from user_account.models import UserAccount class Profile(models.Model): user = models.ForeignKey(UserAccount, on_delete=models.CASCADE, ...
from django.contrib import admin from df_goods.models import TypeInfo, GoodsInfo, Comment class TypeInfoAdmin(admin.ModelAdmin): list_display = ['id', 'ttitle'] class GoodsInfoAdmin(admin.ModelAdmin): list_per_page = 15 list_display = ['id', 'gtitle', 'gprice', 'gunit', 'gkucun', 'gcontent', 'gtype'] ...
print(2 + 2) print(50 - 5 * 6) print((50 - 5 * 6)/4) print(8/5) print(5 ** 2) #5 squared width = 20 height = 5 * 9 print(width * height)
import os Import('env') env = env.Clone() env.Append(LIBPATH = ['#../build/log']) env.Append(LIBS = ['kulog', 'rt']) env.Program('simple_log', Glob('simple_log.cpp'))
from flask import Flask, render_template from bs4 import BeautifulSoup import requests base_url = "https://ngojobsinafrica.com/?post_type=noo_job&s=&location[]=ethiopia&category[]=information-technology" source = requests.get(base_url).text soup = BeautifulSoup(source, 'lxml') all_information_technology_jobs = soup.f...
# -*- coding: utf-8 -*- """ Created on Fri Sep 09 11:28:29 2016 @author: utente Pattern Analysis 2016 """ import pandas as pd import numpy as np from functions_for_PA2016 import * import matplotlib.pyplot as plt import statsmodels.api data = pd.read_excel("C:/Users/utente/Documents/PUN/Anno 2016_08....
import json import pymysql class OptionMysql(object): def __init__(self, options): host = options['HOST'] user = options['USERNAME'] password = options['PASSWORD'] database = options['DATABASE'] port = options['PORT'] charset = 'utf8' # 连接数据库 self.co...
# -*- coding: utf-8 -*- # Martínez García Mariana Yasmin print (34*3)-(1/2)*(9.81)*(3**2)#1/2 calcula la división entera print (34*3)-(1/2.0)*(9.81)*(3**2)#1.0/2 o 1/2.0 división flotante print (34*1)-(1/2.0)*(9.81)*(1*2) print (34*1.5)-(1/2.0)*(9.81)*(1.5**2) print (34*5)-(1/2.0)*(9.81)*(5**2) v0 = 34 g = 9.81 t = 5 y...
import scrapy import json from scrapy.http import Request class movieSpider( scrapy.Spider ) : name = "movit" movie_name = "the_martian" allowed_domains = [ "www.rottentomatoes.com" ] #http://www.rottentomatoes.com/m/the_martian/reviews/ start_urls = [ "http://www.rottentomatoes.com/m/the_martian/reviews/" ] ...
from django.conf.urls import url from finder import views urlpatterns = [ url(r'^inter-region/$', views.inter_region_lookup_view, name='inter_region_lookup_view'), url(r'^single-type/$', views.SingleTypeLookupView.as_view(), name='single_type_lookup_view'), ]
import json import array as arr import sys import glob import errno from time import sleep import os #import keyboard nameofsong = '' path = '/Users/alejandrasandoval/Desktop/usb/' def getsong(songnum,count): with open(json_arr[songnum]) as data_file: data = json.load(data_file) for p in data['trac...
# Generated by Django 2.2.1 on 2019-05-28 08:34 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app', '0004_auto_20190528_1720'), ] operations = [ migrations.AlterField( model_name='board', name='created_date', ...
import random import generate_private_public from elsig_hash import egGen import RSA Bob_id = 0 Alice_key = tuple() Alice_id = 0 bob_n = 0 bob_e = 0 signed_m = "" def key_id_Generation(): global Alice_id Alice_id = random.randint(1000001, 10000000) # to be from other ranges generated in cert (to be uniqu...
# -*- coding:utf-8 -*- import operator import string import operator import itertools import snowballstemmer from textblob import TextBlob, Word LOWER_MAP = {"tr": {ord("I"): u"ı"}} STEMMERS = { "en": snowballstemmer.stemmer("english"), "tr": snowballstemmer.stemmer("turkish"), } def noun_phrases(text): ...
# -*- coding: utf-8 -*- """ Created on Mon May 3 15:43:36 2021 @author: Nikita """ """ First solution i've written was very similar to this; the major difference was that it used slices and sum(slice), leading to a complexity of O(n^3) likely. Essentially, for array_size in range (2,size): for start_index in ...
import sys sys.path.append(".") import argparse from model.utils import str2bool, str2list LOGGING_PATH = './logging' parser = argparse.ArgumentParser(description="Model Options") parser.add_argument( "--run-identifier", "-id", dest="run_id", type=str, required=True, help="Add an identifier th...
#!python import os import numpy as np import pandas as pd import general_functions as gf import argparse import pdb parser = argparse.ArgumentParser() parser.add_argument('--trait', type=str, help='trait', default=None) args = parser.parse_args() OUT_DIR = os.environ['OUT_DIR'] ## load trait condsigs condsig = pd.read...
import time class LightControl: def __init__(self, channel, pin): self.channel = channel def on(self): return True def off(self): return True def flash(self, time, count): # if(not self.notPi) for i in range(count): self.on() time.sl...
from __future__ import absolute_import, division, print_function from __future__ import unicode_literals import sys import os from random import randint import datetime import time from multiprocessing import Pool, TimeoutError from collections import defaultdict from scipy.stats import chisquare from mmgroup impo...
from django import forms from .models import Vote class VoteForm(forms.ModelForm): BOOLEAN_CHOICES = (('1', 'Ja'), ('0', 'Nej')) positive = forms.ChoiceField(choices=BOOLEAN_CHOICES, widget=forms.RadioSelect) class Meta: model = Vote fields = ['positive']
from django.test import TestCase # Create your tests here. from .views import get_location_from_zip, search_location_in_sheet, get_response_for_help from data.gsheets import get_gsheet class ViewsTestCase(TestCase): def setUp(self): self.gsheet = get_gsheet() def test_get_location_from_zip_invali...
from google.cloud import storage as gcs import csv from numpy import genfromtxt import requests import tensorflow as tf #get the bucket and blob containing the .csv data file client=gcs.Client() try: bucket=client.get_bucket('parquery-sandbox') except google.cloud.exceptions.NotFound: print('Sorry, that...
#/usr/bin/env python from ctypes import * ############################################################################### AT_NULL = 0 # End of vector AT_IGNORE = 1 # Entry should be ignored AT_EXECFD = 2 # File descriptor of program AT_PHDR = 3 # Program headers for program ...
from itertools import chain, combinations # A class to encapsulate a Functional Dependency, and some helper functions class FD: def __init__(self, lhs, rhs): self.lhs = frozenset(list(lhs)) self.rhs = frozenset(list(rhs)) def __str__(self): return ''.join(self.lhs) + " -> " + ''.join(self.rhs) def __eq__(self...
import random import string import tkinter as tk from tkinter import ttk import pyperclip def parameter_password(): entry.delete(0, 'end') # стирает сгенерированный пароль из окна ввода length = var_1.get() # длина пароля count = count_checkmarks() password = generator_pass(length, count) retur...
import FWCore.ParameterSet.Config as cms from PhysicsTools.NanoAOD.nano_eras_cff import * from PhysicsTools.NanoAOD.common_cff import * from PhysicsTools.NanoAOD.simpleCandidateFlatTableProducer_cfi import simpleCandidateFlatTableProducer import PhysicsTools.PatAlgos.producersLayer1.muonProducer_cfi # this below is ...
""" Machine Learning(기계 학습) -> Deep Learning(심층 학습) training data set(학습 세트) / test data set(검증 세트) 신경망 층을 지나갈 때 사용되는 가중치(weight) 행렬, 편항(bias) 행렬을 찾는 게 목적 오차를 최소화하는 가중치 행렬을 찾아야 한다 손실(loss) 함수 / 비용(cost) 함수의 값을 최소화하는 가중치 행렬 찾기 손실 함수: - 평균 제곱 오차(MSE: Mean Squared Error) - 교차 엔트로피(Cross-Entropy) """ import numpy a...
integer=int(input("enter an integer?\n")) decimal=float(input("enter a float?\n")) string=str(input("enter a string?\n")) string2=eval(input("enter any type?\n")) print("krishanth likes "+string);
from .. import init_blueprint, schedule_daily bp = init_blueprint(__name__) from . import routes, handlers from .jobs import update_users_data schedule_daily(update_users_data)
################################################################ # Reads in World Bank tariff data ################################################################ from pulp import * import math import json import numpy as np import re from sys import exit import matplotlib.cm as cm import matplotlib.pyplot as plt tr...
from IPython.utils.tokenutil import line_at_cursor from ipykernel.ipkernel import IPythonKernel from jupytervvp.vvpsession import VvpSession, SessionException from jupytervvp.flinksql import complete_sql from IPython.core.magic_arguments import parse_argstring from jupytervvp import VvpMagics import json def _do_fli...
import sys import ctypes import re import collections import io import json def printf(fmt, *args, **kwargs): print(fmt.format(*args, **kwargs), end='') def printf_line(fmt, *args, **kwargs): print(fmt.format(*args, **kwargs)) def printf_error(fmt, *args, **kwargs): print("error:", fmt.format(*args, **k...
import pygame class Paddle(pygame.sprite.Sprite): surface: pygame.Surface velocity: pygame.Vector2 paddle_width: int paddle_height: int rect: pygame.Rect oldrect: pygame.Rect def __init__(self, surface: pygame.Surface, x: int, y: int) -> None: super().__init__() ...
from os import close from tkinter import * from tkinter import ttk from tkinter import filedialog import BeW import sys class Root(Tk): def __init__(self): super(Root, self).__init__() self.title("Test") self.minsize(800,600) self.labelFrame = ttk.LabelFrame(self,text = "abrir") ...
''' Created on 15-Apr-2017 @author: rmaduri ''' import matplotlib, sys matplotlib.use('TkAgg') from numpy import arange, sin, pi from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg from matplotlib.figure import Figure from tkinter import * master = Tk() master.title("Hello World!"...
#encoding:utf-8 __authors__ = ['"Wei Keke" <keke.wei@cs2c.com.cn>'] __version__ = "V0.1" ''' # ChangeLog: #--------------------------------------------------------------------------------- # Version Date Desc Author #-----------------------------------------------------...
import requests from bs4 import BeautifulSoup import csv url = 'https://www.bilibili.com/ranking' # 发起网络请求 response = requests.get(url) html_text = response.text print(html_text) soup = BeautifulSoup(html_text, 'html.parser') # 用来保存视频信息的对象 class Vidoe: def __init__(self, rank, title, score, visit, up, up_id, u...
# 生成种群 import random from NSGA2.Filtpop import filtpop # 约束条件过滤 from NSGA2.Decodechrom import binary2decimal def genepop(pop_size, genes_num, gene_length): """ 生成二进制种群基因集合 :param pop_size: :param gene_lenth: :return: """ pop = [] while len(pop) < pop_size: n = pop_size - len(p...
import os import json from flask import Flask, request, url_for, redirect from twilio.util import TwilioCapability import twilio.twiml from twilio.rest import TwilioRestClient # Account Sid and Auth Token can be found in your account dashboard ACCOUNT_SID = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' AUTH_TOKEN = 'YYYYYYYYYYYY...
from collections import OrderedDict import copy import numpy import torch """ `state_dict` or `nested_dict`? When `torch.nn.Module` loads from state_dict, the keys in state_dict contains prefix and parameter/buffer name. The prefix determines the specific module to load the parameter/buffer. Meanwhile th...
import flask cv = flask.Flask(__name__) @cv.route('/name') def name(): return '<h1>Goldie Perlmann</h1>' @cv.route('/pic') def pic(): return 'picture' @cv.route('/hobbies') def hobbies(): return '<p></p>' @cv.route('/skills') def skills(): return '<p></p>' if __name__ == "__main__": cv.run()
# APPROACH 1 : OPTIMAL SOLUTION # Time Complexity : O(n*m), n: number of rows of the matrix, m: number of columns of the matrix # Space Complexity : O(1), not considering the space of the matrix (else, O(n*m) - result holds all the elements of the matrix) # Did this code successfully run on Leetcode : Yes # Any problem...
import requests from bs4 import BeautifulSoup class C1maps: def __init__(self): self.mprint = 0 self.dos = 0 self.s = '' def getRusData(self): vgm_url = 'https://1maps.ru/statistika-koronavirusa-v-rossii-i-mire-na-19-maya-2020-na-segodnyashnij-den/' html_text = requests...
class ContactInfo: def __init__(self, name, phone,email): self.name= name self.email= email self.phone =phone def print_info(self): print('{0}:{1}:{2}'.format(self.name,self.phone,self.email)) if __name__ == '__main__': sanghyun = ContactInfo('박상현','seenlab@gmail....
import random class ListGenerator: @staticmethod def listselect(data): return random.choice(data) @staticmethod def listseed(seed, data): random.seed(seed) return ListGenerator.listselect(data) @staticmethod def listselected(numbers, data): newlist = [] ...
#!/usr/bin/env python3 """ :mod:`strain` -- title ======================================== .. module strain :platform: Unix, Windows, Mac, Linux :synopsis: doc .. moduleauthor:: Qi Zhang <qz2280@columbia.edu> """ class EulerianStrain: def __init__(self, v0: float, v: float): self.v0 = v0 se...
import nuke import nukeSearcher toolbar = nuke.menu('Nodes') c = toolbar.addMenu('PP Tools', 'pptool.png') c.addCommand('Nuke API Searcher', lambda: nukeSearcher.nukeSearcher(), '', icon='pptool.png')
from django.shortcuts import render from django.http import HttpResponse from django.views.decorators.http import require_GET from .models import Grade @require_GET def get_all_grades_by_category_and_kind_id(request, category_id, kind_id): grades = Grade.objects.filter(kind__category_id=category_id, kind_id=kind...
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # @Author : SUN FEIFEI from selenium.webdriver.common.by import By from app.honor.teacher.home.vanclass.object_page.home_page import ThomePage from app.honor.teacher.home.vanclass.object_page.vanclass_paper_page import VanclassPaperPage from app.honor.teacher.home.vanclas...
from django.shortcuts import render,redirect,get_object_or_404 from django.contrib import messages from django.core.paginator import EmptyPage,Paginator from .models import * from .forms import * def List(request): items=Report.objects.all() print(items) paginator=Paginator(items,10) page=request.GET.ge...
""" A PySpark script that converts raster images to COGss. Edit the settings at the top to tune how many concurrent images to process per machine. Edit get_input_and_output_paths to return the input rasters mapped to their desired COG locations. Edit gdal_cog_commands to modify any GDAL settings to make the COGs you wa...
# -*- coding : utf-8 -*- from __future__ import absolute_import import requests from celery_app import app from celery.utils.log import get_task_logger from env import SERVER_WEBHOOK_URL from pprint import pprint logger = get_task_logger(__name__) @app.task def trigger_webhook(data): r = requests.post(SERVER_WE...
""" Contains methods for performing validation of learning models """ import time from sklearn.model_selection import StratifiedKFold from src.common import LABELS, FOLDS_COUNT from src.common import SENTENCES from src.data import dataset from src.features.word_embeddings.word2vec_embedding import Word2VecEmbedding fr...
class SmoothProp(Optimizer): def __init__(self, lr=1e-4, beta=0.9, l2=1e-5, epsilon=1e-6, *args, **kwargs): super(SmoothProp, self).__init__(**kwargs) self.__dict__.update(locals()) self.iterations = K.variable(0.0) self.lr = K.variable(lr) self.l2 = l2 self.beta = K....
#!/usr/bin/python ################################################################################ from test import * from diamond.collector import Collector from nagios import NagiosStatsCollector ################################################################################ class TestNagiosStatsCollector(Collec...
# -*- conding utf-8 -*- # 作者:彭静 # 开发时间:上午 11:35 # 开发工具:PyCharm # 列表中的元素的类型可以不相同,支持数字,字符串,也可包含列表 # nameList = []#定义一个空的列表 nameList = ['小张','小王','小李'] # testList = [1,'测试'] # # print(type(nameList[0]),nameList[0]) # print(type(testList[0])) length = len(nameList) # print(len(nameList))#获得列表长度 # for name in nameList: #...
class Node(object): pass def loop_size(node): nodes = [] tail_node = None while(not node in nodes): nodes.append(node) node = node.next return len(nodes) - nodes.index(node) node1 = Node() node1.next = node1 print loop_size(node1) # 1 node1 = Node() node2 = Node() node1.nex...
# -*- coding: utf-8 -*- """ Custom Sizer for Cryptocurrencies, allowing for fractional orders. """ from common import * import backtrader as bt from decimal import Decimal, ROUND_DOWN class CryptoSizer(bt.Sizer): """ Custom Crypto Sizer. """ params = ( ('stake', 0.1), ) def _g...
from flask import Flask ### Creates a WSGI application # WSGI is a standard protocol we follow while communication between our web server # and web application takes place app = Flask(__name__) # Initializing the Flask object will tell the Flask app to follow the # WSGI protocol while communicating with the serv...
#!/usr/bin/python3 import os, sys sys.path.append(os.getcwd()) from Utilities import python_helpers import fractions def main(): # this solution is a little bit verbose in the number of variables and # conditionals, but I've tried to be clear about how I arrive at the solution, # rather than to write a t...
import argparse import numpy as np from PIL import Image from scipy import fftpack import cv2 import os import collections from dahuffman import HuffmanCodec import ast def largest_N_value_DCT(img_dct, num_of_coefficients): rows_1, cols_1, no_of_blocks = img_dct.shape[0], img_dct.shape[1], img_dct.shape[2]...
__author__ = 'vladimir' from re import match from pymorphy2 import MorphAnalyzer all = 0 nonnum = 0 all_postings = 0 alpha_postings = 0 no_stops_postings = 0 low_reg = dict() lemmatized = dict() with open("Dictionary") as f: for line in f.readlines(): all += 1 word = line.split(" ")[0] cnt...