text
stringlengths
38
1.54M
from artext import __version__ from artext import config from artext import utils from artext.artext import Artext def main(): parser = utils.arg_parser() parser.add_argument('-v', '--version', action='version', version=('artext %s' % __version__)) args = parser.parse_args() c...
from pyspark.sql.functions import when def gender_column_to_0_1_2(observation_df): observation_df = observation_df.withColumn( 'member_gender', when(observation_df.member_gender == "Male", 0). when(observation_df.member_gender == "Female", 1). when(observation_df.member_gender == "...
# -*- coding: utf-8 -*- import requests import json from gushiwen_master.settings import PROXY_SHADOWSOCKS_ONLY, SHADOWSOCKS_SCHEME, SHADOWSOCKS_SERVER, SHADOWSOCKS_PORT def get_http_proxies(): proxies = [] if PROXY_SHADOWSOCKS_ONLY: proxies.append(SHADOWSOCKS_SCHEME+'://'+SHADOWSOCKS_SERVER+':'+str(S...
#! /usr/bin/python import numpy as np def isAtom(line): if line[0:6] == "ATOM " or line[0:6] == "HETATM": return True else: return False def isPAtom(line): polar_atoms = ["N", "O", "S"] if isAtom(line) and atmn(line).strip()[0] in polar_atoms: return True ...
class Solution: def isSymmetric_v20220206(self, root: TreeNode) -> bool: def dfs(p, q): if not p and not q: return True if not p or not q or p.val != q.val: return False return dfs(p.left, q.right) and dfs(p.right, q.left) if not root: return True return d...
import matplotlib.pyplot as plt labels = ['Frogs','Hogs','Dogs','Logs'] sizes = [15,30,45,10] explode = [0,0,0.1,0] fig1,ax1 = plt.subplots() ax1.pie(sizes,explode=explode,labels=labels,autopct='%1.1f%%',shadow=True,startangle=30) ax1.axis('equal') plt.show()
#!/usr/bin/python3 import argparse import bcrypt import json import os import yaml import re def make_hash(password): return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("ascii") def main(): parser = argparse.ArgumentParser( description="Process the admin data file for use by the server...
import math def fib(n, start1=1, start2=2): yield start1 a, b = start1, start2 while b < n: yield b a, b = b, a + b def is_prime(n, prime_list=None): if prime_list is None: pass def primes(n): numbers = {p: None for p in range(2, n+1)} for p in range(2, n+1): ...
''' # プロジェクトファイルに含まれている複数レイヤーを指定範囲でクリッピングして別名のGeoPackageで保存する ''' import os import subprocess from qgis.core import * # VisualStudio ソリューション検索パスで # %QGIS_INSTALL%/apps/qgis-ltr/python/plugins/processingを追加すること from processing.algs.gdal.GdalUtils import GdalUtils # 環境変数を設定 # https://gis.stackexchange.com...
# -*- coding: utf-8 -*- import os try: import urlparse except ImportError: import urllib.parse as urlparse try: from django import VERSION as DJANGO_VERSION except ImportError: DJANGO_VERSION = None # Register database schemes in URLs. urlparse.uses_netloc.append('postgres') urlparse.uses_netloc.ap...
#coding:utf-8 import fn_db import fn_ref def get_bookins_join(bookinsid): query = fn_db.db.query(""" SELECT a.*, b.* FROM LIM_BOOKINS a LEFT JOIN LIM_BOOKCLS b ON a.bookclsid = b.bookclsid WHERE a.bookinsid = $bookinsid """, vars = locals()) for item in query:...
import os import sys from os.path import dirname, abspath sys.path.append(dirname(dirname(abspath(__file__)))) import gym import time from agents.actor_critic_agents.A2C import A2C from agents.DQN_agents.Dueling_DDQN import Dueling_DDQN from agents.actor_critic_agents.SAC_Discrete import SAC_Discrete from agents.acto...
# (c) Copyright 2014 Hewlett-Packard Development Company, L.P. # # 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...
import logging import os import re import requests import time import tempfile import zipfile from copy import copy from itertools import product from bs4 import BeautifulSoup class USPhoneNumberSupplier: def __init__(self, cache, user_agent_instance, proxy_instance, colors, mask): self.user_agent_instan...
# Console tool for running missions at own computer. # # Author: CheckiO <igor@checkio.org> # Last Change: # URL: https://github.com/CheckiO/checkio-console """ :py:mod:`checkio_console.cli` - Command line interface for CheckiO ============================================================================== """ import ...
__author__ = 'karthikb' def solution(): solution_set = [] for i in range(1000,100000): summation = 0 value = i #print value while value>=1: r = (value%10) summation+= r**5 value = value //10 if summation > i: conti...
hex_colours = {"AliceBlue": '#f0f8ff', "Beige": '#f5f5dc', "Brown": '#a52a2a', 'Black': '#000000', 'Coral': '#ff7f50'} hex_colour = input('Please input either AliceBlue, Beige, Brown, Black or Coral: ') hex_colour = hex_colour.capitalize() while hex_colour != "": if hex_colour in hex_colours: print(hex_colo...
# _*_ coding:utf-8 _*_ # somthing can be improve # 1. Memory limit manager # 2. Parallel computation from __future__ import division import sys import os import pysam import argparse class AlignRecords(object): """Tiny version of pysam.AlignedSegment""" qname="" rname="" start=1 end=1 strand=1 ...
# reading the fasta file import io fasta = open('computing-gc-content/rosalind_gc.txt',"r").read().splitlines() # print(fasta) # storing the name best seq best_seq_name = None best_seq = None best_gc_score = 0 def calc_gc_score(seq): counts = 0 seq_length = len(seq) for i in seq: if i in "GC": ...
from os import listdir from os.path import isfile, join from os import system import sys import math stopwords = [] spamwords = [] genuinewords =[] testwords =[] spamdict = {} genuinedict = {} testdict={} pgbr = True def processspam(files): spampath = "./spam" for i in range (0, len(files)): k=files[i] with...
def sortVector(nums): nums.sort() print(nums) vector = [1,5,2,4,8,2] sortVector(vector) # exec("""\ndef sortVector(nums):\n nums.sort()\n print(nums)\n\nvector = [1,5,2,4,8,2]\nsortVector(vector)\n""")
#2. [1, 'a',3.6000000000000001, 2, 'b', '1', 1.3999999999999999, '2'] sort this list starting with all the numbers sorted and then the characters sorted. The code should be in one line. def sort(a): a = [str(i) for i in a] a.sort() a = [int(i) if i.isdigit() else i for i in a ] return a a...
import struct import gzip from enum import Enum from srmap.actor import Actor from srmap.property import Property from srmap.tilemap import Tilemap, Name, Size class Theme(Enum): PROTOTYPE = 'StageVR' METRO = 'StageMetro' SS_ROYALE = 'StageShip' MANSION = 'StageMansion' PLAZA = 'StageCity' FAC...
# Database settings DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': INSTANCE_NAME, 'USER': DATABASE_USER, 'PASSWORD': DATABASE_PASSWORD, 'HOST': DATABASE_HOST, 'PORT': DATABASE_PORT, } }
#DO NOT MODIFY THE CODE IN THIS FILE #File: Proj03.py from Proj03Runner import Runner import turtle import random window = turtle.Screen() turtle.setup(300,300) rand = random.randrange(0,2) #get a random number #set object's colors based on the random number if(rand%2==0): #rand is even color01...
from django.urls import path from account import views from jwt_token.views import CustomizedTokenObtainPairView, CustomizedTokenRefreshView urlpatterns = [ # path('register/', views.registration_view), # path('login/', views.login_view), path('verify_session/', views.verify_session_view), # path('logo...
for case in range(1, int(input())+1): tmp = [] for i in input(): if i == '+': tmp.append(1) else: tmp.append(-1) toggle = 1 count = 0 for i in tmp[::-1]: if i * toggle == -1: toggle *= -1 count += 1 print("Case #"+str(case...
import datetime def date(): now = datetime.datetime.now() datex = now.strftime("%d/%m/%Y") return datex def time(): now = datetime.datetime.now() timex = now.strftime("%H:%M:%S") return timex
#-------------------------------------------------------------- # Script: Calculates the amount of time a procedure takes # Version: 1.0 #-------------------------------------------------------------- import time def timeExecution(code): start = time.clock() result = eval(code) runtime = time.clock() - st...
import re text = r''' <meta content="always" name="referrer"> <script> var url = ''; url += 'http://mp.weixin.qq.com/s?src=11&timestamp=1553504704&ver=1506&signature=ZQCxwQwyZdl9l5G2Ue9mL90DZjQLH8JsaU5BWMOSZi1VpX0Dkjv82EqQyuvEARuNJ41aHbzrww22mn-eHfCRdhFPr7-I54y6Z8fuB3kpk5XO43oWrNsD60ZK8P7WorVr&new=1'...
from django.apps import AppConfig class AppQuestionanswerConfig(AppConfig): name = 'App_QuestionAnswer'
# Programmed By Christopher Philip Orrell 18/10/2018. # This script compares different sorting algorithms. from random import randint from timeit import repeat newarray = [99,21,45,22,0.1,22,36,889,25,44,66,33,55,44,88,77,55,22,11,44,555,66,88,44,1,11,88,33,556,32,21,18,94,63,72,46,64,852,53,456,765,256,125,115...
# Generated by Django 3.1.6 on 2021-03-23 13:19 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('accounts', '0013_auto_20210323_1317'), ] operations = [ migrations.AlterField( model_name='orde...
# Create a while loop that will repetitively ask for a number. # If the number entered is 9999 stop the loop. while True: answer = int(input('Enter a number, 9999 to end: ')) if answer == 9999: break else: print('Your number was: ', answer)
from django.contrib.auth.mixins import ( LoginRequiredMixin, UserPassesTestMixin ) from django.views.generic import ( ListView, DetailView, TemplateView ) from django.views.generic.edit import ( UpdateView, DeleteView, CreateView ) from taggit.models impor...
import pandas as pd import os import string def dfconcat(sdir, fname): dflist = [] for f in os.listdir(sdir): path = sdir + os.path.sep + f if os.path.isdir(path): path = path + os.path.sep + fname # print(path) if os.path.exists(path): ...
# encoding=UTF-8 #!flask/bin/python from cassandra.cluster import Cluster from cassandra.policies import DCAwareRoundRobinPolicy from cassandra.auth import PlainTextAuthProvider from cassandra.query import BatchStatement, SimpleStatement import pandas as pd from pyspark.sql.types import StructType class CassandraType...
from sqgturb import SQG, rfft2, irfft2 import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation import os, sys from netCDF4 import Dataset # run SQG turbulence simulation, plotting results to screen and/or saving to # netcdf file. filename = sys.argv[1] ncin = Dataset(filename) save...
# -*- coding: utf-8 -*- ### # (C) Copyright (2012-2016) Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the 'Software'), to deal # in the Software without restriction, including without limi...
import tensorflow as tf # https://www.tensorflow.org/tutorials/seq2seq # http://suriyadeepan.github.io/2016-06-28-easy-seq2seq/ # PAD: padding(Filler) # GO: prefix of decoder input # EOS: suffix of decoder output # UNK: Unknown; word not in vocabulary # Q : [ PAD, PAD, PAD, PAD, PAD, PAD, “?”, “you”, “are”, “How” ] #...
from csv import DictReader from math import sqrt, fabs, exp, log import numpy as np D = 2 ** 20 # Neural Network withi a single hidden layer online learner class NN(object): """Neural Network with a single ReLU hidden layer online learner. Parameters: ---------- n (int): number of input units h (i...
# coding: utf-8 # In[3]: import pandas as pd import numpy as np from sqlalchemy import * import datetime DATABASE_ENDPOINT = "aqueduct30v05.cgpnumwmfcqc.eu-central-1.rds.amazonaws.com" DATABASE_NAME = "database01" TABLE_NAME = "y2018m05d29_rh_total_demand_postgis_30spfaf06_v01_v01" F = open("/.password","r") pass...
"""This will draw the plant loop for any file copy of s_plantloop.py figure out how to remove the nodes keep the nodes, but draw them differently""" import pydot import sys sys.path.append('../EPlusInputcode') from EPlusCode.EPlusInterfaceFunctions import readidf import loops def firstisnode(edge): if type(edge...
#!/usr/bin/env python # -*- coding:utf-8 -*- __author__ = 'MFC' __time__ = '18/7/15 18:06' """ Python与量化投资从基础到实战 P35 """ # break in for loop for i in range(5, 9): print(i) print("hello") if i > 6: print("i > 6") break
i, t = [int(i) for i in input().split()] prices = [4.0, 4.5, 5.0, 2.0, 1.5] print("Total: R$ {0:.2f}".format(prices[i-1]*t))
from fuzzer import Fuzzer, FuzzerBenchmark, FuzzerInstance, TargetProgram import os import subprocess import shutil from random import randint import screenutils class AngoraFuzzer(Fuzzer): def __init__(self, install_dir): super().__init__() self.install_dir = install_dir self.cc = os.pat...
import numpy as np import pandas as pd import matplotlib.pyplot as plt # Question: Is there a correlation between the relationships between the victim and the perpetrator? dataArr = pd.read_csv("../data/database.csv") # remove these columns dataArr = (dataArr.drop(['Record ID', 'Agency Code','Agency Name','Agency Ty...
c = input('string:') b = "" for ch in range(len(c)): if(c[ch] != "a" and c[ch] != "A"): b = b + c[ch] print(b)
#!/usr/bin/env python # -*- coding: utf-8 -*- # @author Zhang zhiming (zhangzhiming@) # date import re import json import sys reload(sys) sys.setdefaultencoding( "utf-8" ) import ConfigParser import logging import time import math import random import os import numpy as np class TF_v1(): def __init__(self): ...
# Copyright 2018ff. Stephan Druskat # # 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 agree...
# challenge: # - handle the case when the current pointer go outbound. class Solution(object): def spiralOrder(self, matrix): if not matrix: return [] directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] direction_ptr = 0 col_len, row_len = len(matrix), len(matrix[0]) ...
import logging import pandas as pd from flask_restful import Resource, abort, fields, marshal_with, reqparse SPONSORS = pd.DataFrame([ { 'id': 1, 'name': 'Sponsor A', 'interactions': 0 }, { 'id': 2, 'nam...
import matplotlib.pyplot as plt import requests from pandas import Series import constants import get_tweets def go_through_category(category_name, category): values = {} print(category_name) for trait in category: values[trait.get("name")] = trait.get("percentile") print("{} - {}".format(...
from django.contrib.auth.models import User, Group from core.models import Notification, ApiKey, Character import eveapi from core.tasks import Task def postNotification(target, text, cssClass="info"): n = Notification(content = text, cssClass=cssClass) n.save() if type(target) is User: n.targetUsers.add(target)...
def insertion_sort(array, compare_fn): """ :param array: array of numbers or comparable objects :param compare_fn: function that compares two objects - a1 and a2, a1 < a2 returns -1, a1 == a2 returns 0 and a1 > a2 returns 1 :return: sorted copy of array """ result = [x fo...
# Python es un lenguaje de programación que es multiparadigma, dentro de estos, # hay uno que es el Orientado a Objetos (OOB) # La Orientación a Objetos tiene Objetos, Clases y Herencia. Esto es lo que vamos a analizar en esta sección # Los objetos en Python son un tipo de dato que contiene propiedades y metodos. #...
import day23 import unittest class TestDay23a(unittest.TestCase): def test_input(self): self.assertEqual(3969, day23.calc_a(input)) class TestDay23b(unittest.TestCase): def test_case(self): self.assertEqual(917, day23.calc_b()) input = """set b 65 set c b jnz a 2 jnz 1 5 mul b 100 sub b -1...
import numpy as np import sys from dtreeutil import * x_train, y_train = getData('../decision_tree/decision_tree/train.csv') x_val, y_val = getData('../decision_tree/decision_tree/val.csv') x_test, y_test = getData('../decision_tree/decision_tree/test.csv') tree = DecisionTree() start = time.time() tree.growTree(x_tr...
import numpy as np from astropy.io import fits import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec import matplotlib.ticker as ticker from matplotlib.ticker import ScalarFormatter from matplotlib.ticker import FuncFormatter import os import sys import fnmatch plt.style.use('fancy') iprofile=np.load...
# -*-coding:Utf-8 -* # Copyright (c) 2010-2017 DAVY Guillaume # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # ...
import os import webbrowser def beautify_data_html(data): beautiful_string = "" counter = 1 for item in data: beautiful_string += """ <tr> <td>id: {id}</td> <td>{cdatetime}</td> <td>{address}</td> <td>{district}</td> <td>{beat}...
from src.models.cow import Cow from src.models.pig import Pig class AnimalFactory: """ Factory to create a new animal ... Attributes ---------- type: str The animal type to know what kind of animal creates (default: "cow"). Methods ------- get_animal(name) Return a...
import scipy.stats as s import numpy as np import matplotlib.pyplot as pl # Hypothesis Testing: Proportions ##################################### class ProportionTest: # Simulation of proportionality estimation def __init__(self): self.rv = s.binom(1000,...
from rest_framework.viewsets import ViewSet from avaliacoes.models import Avaliacao from .serializers import AvaliacaoSerializer class AvaliacaoViewSet(ViewSet): queryset = Avaliacao.objects.all() serializer_class = AvaliacaoSerializer
# -*- coding: utf-8 -*- from telegram import ReplyKeyboardMarkup, ReplyKeyboardRemove, Update from telegram.ext import ( Updater, CommandHandler, MessageHandler, Filters, ConversationHandler, CallbackContext, ) updater = Updater(token = '1706319949:AAH1LW5TWSImNumuNSOCf8IUFpibhx5FXcI...
class Rectangle: def __init__(self): self.width = 0 self.height = 0 # 当试图给特性name赋值时被自动调用 # 涉及的特性不是size时该方法也会被调用, # 为了避免死循环(该方法再次被调用),使用__dict__进行赋值 def __setattr__(self, name, value): if name == "size": self.width, self.height = value else: s...
for multiplicand in range(1, 10): for multiplier in range(1, multiplicand + 1): print('%d x %d=%d' % (multiplicand, multiplier, multiplicand*multiplier), end='\t') print()
import requests from lxml import etree import io import os from datetime import datetime from urllib import quote LICENSE = "https://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License" def link(text, href, tail): a = etree.Element("a", href=href) a.text = text a.ta...
import os import re from setuptools import (setup, find_packages) class InstallError(Exception): """reactome fipy installation error.""" pass def version(package): """ :return: the package version as listed in the package `__init.py__` `__version__` variable. """ # The version string...
def power(base, root): #base case if root == 0: return 1 return base * power(base, root -1) #main function print("Enter base : ") base = input() print("enter root:") root = input() txt = "{} root {} is" print(txt.format(base, root), pow(int(base),int(root)))
import argparse import os parser = argparse.ArgumentParser() # Environment parser.add_argument("--device", type=str, default='cuda:0') parser.add_argument("--multiple_device_id", type=tuple, default=(0,1)) parser.add_argument("--num_works", type=int, default=8) parser.add_argument('--save', metavar='SAVE', default=''...
import csv def savetoCSV(newsitems, filename): fields = ['node','relation_nodes'] with open(filename, 'w') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=fields) writer.writeheader() writer.writerows(newsitems) with open('relation2.csv') as f: relations = [{k: str(v) for ...
from rest_framework import serializers from employee.models import Employee class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ('id', 'email', 'firstname', 'lastname', 'password', 'address', 'dob', 'company', 'mobile', 'city')
from heapq import heappush, heappop def solution(food_times, k): if sum(food_times) <= k: return -1 q = [] for i in range(len(food_times)): heappush(q, (food_times[i], i + 1)) times, previous, length = 0, 0, len(q) while times + ((q[0][0] - previous) * length) <= k : now ...
from enum import Enum class GameSubTypeEnum(Enum): TexasHoldem = 0 OmahaHoldem = 1 Pineapple = 2 CrazyPineapple = 3 LazyPineapple = 4 ThreeCardsHoldem = 5 IrishPoker = 6 SpanishPoker = 7 ManilaPoker = 8 FiveCardsStud = 9 SevenCardsStud = 10 FiveCardsDraw = 11 @clas...
import unicodecsv class UnicodeCsvWriter(object): def _write(self, iterable, output_file): writer = unicodecsv.writer(output_file, encoding='utf-8') for row in iterable: writer.writerow(row) def write(self, iterable, filename='output.csv', mode='a'): with open(filename, mo...
from util import * def user_update(u_i, v, bias, profile, epochs=30, learn_rate=0.0015, reg_fact=0.06): profile = np.reshape(profile, (1, -1)) - bias u_i = np.reshape(u_i, (1, -1)) delta_matrix = np.dot(- 2 * learn_rate * np.eye(v.shape[1]), np.dot(v.T, v)) + (1 - (2 * learn_rate * reg_fact))*np.eye(v.sha...
from typing import List from bisect import bisect_left from collections import deque class Solution: def findClosestElements(self, A: List[int], k: int, x: int) -> List[int]: n = len(A) lo = 0 hi = n - k while lo < hi: mid = (lo + hi) // 2 if abs(...
# Generated by Django 2.0.6 on 2020-05-18 09:55 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('home', '0004_auto_20200515_2232'), ] operations = [ migrations.AlterField( model_name='middlena...
### # Copyright 2015-2019, Institute for Systems Biology # # 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 la...
from ast_node import AstNode class PrintTags(AstNode): def __init__(self): pass def get_value(self): return None def execute(self, tag_context): tag_context.print_tags() return None
import enum import weakref from collections import defaultdict class AttributeType(enum.Enum): email = "email" phone = "phone" street = "street" class PersonAttribute: def __init__(self, person, value): self._person = weakref.ref(person) self.value = value @property def per...
import time from selenium import webdriver driver=webdriver.Ie(executable_path= '../Exercise/drivers/IEDriverServer.exe') driver.maximize_window() time.sleep(2) driver.get('https://opensource-demo.orangehrmlive.com/') print(driver.title) print(driver.current_url) a1=driver.find_element_by_id('txtUsername') a1.send_keys...
#Embedded file name: eve/client/script/ui/services/corporation\corp_util.py VIEW_ROLES = 0 VIEW_GRANTABLE_ROLES = 1 VIEW_TITLES = 2 GROUP_GENERAL_ROLES = 0 GROUP_DIVISIONAL_ACCOUNTING_ROLES = 1 GROUP_DIVISIONAL_HANGAR_ROLES_AT_HQ = 2 GROUP_DIVISIONAL_CONTAINER_ROLES_AT_HQ = 3 GROUP_DIVISIONAL_HANGAR_ROLES_AT_BASE = 4 G...
import os import sys import re from optparse import OptionParser from Album import * class Itemizer: OPTIONS = [ ("-d", "destination", "destination directory", "DIR", "./"), ("-i", "index", "item index", "INT"), ("-f", "file_path", "input file", "PATH"), ("-s", "silent", "suppress m...
import sqlite3 import pygame import sys class Prologo: def __init__(self): conexion = sqlite3.connect('escapeRoom.db') cursor = conexion.cursor() # generamos un objeto de conexion, (crud,ddl,dml...) cursor.execute("SELECT nombre_jugador FROM JUGADORES order by id_jugador DESC limit 1")...
import json import boto3 class Publish(object): def abr(self, event_type, **kwargs): return self.__generic('abr', event_type, **kwargs) def agency(self, agency, event_type, **kwargs): return self.__generic('agency', event_type, agency=agency, **kwargs) def application(self, application,...
import re DOMAIN_NAME = "svyaznoy.ru" SIP_HOST = "82.144.65.34" SIP_PORT = 5060 RUNS_COUNT = 1 # seconds CALL_DURATION = 8 INTERVAL = 0.1 WAIT_TIME = 200 AUTH_HEADER_REGEX = 'Digest\s+nonce="(.*?)",' \ '\s+opaque="(.*?)",\s+algorithm=md5,' \ '\s+realm="(.*?)", qop="auth"' AUTH_H...
from flask import Flask, render_template, session app = Flask(__name__) app.secret_key = 'thisisnotacookie' @app.route('/') def counting(): if 'counter' not in session: session['counter'] = 0 for counter in session: session['counter'] += 1 return render_template("index.html", counter = session['counter']) ap...
import os import pickle import numpy as np import time import librosa from speakerfeatures import extract_features import warnings warnings.filterwarnings("ignore") #path to training data source = "dataset\\test\\" model_path = "speaker_models\\" test_file = "test_path.txt" file_paths = open(test_file, 'r') num_correc...
import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt class LOGGER: def __init__(self, log_file_path, file_id, log_mode=0, n_epoch=30): self.log_file_path = log_file_path self.file_id = file_id self.log_mode = log_mode self.log_buf = [] ...
#!/usr/bin/env python # # Convert an efs-*.log file from the tracker program to # three SVM training files, one for each output axis. # Usage: # ./split-efs-log.py <log file> <x file> <y file> <z file> # # --Micah # import sys logFile, xFile, yFile, zFile = sys.argv[1:] xf = open(xFile, "w") yf = open(yFile, "w") ...
#!/usr/bin/python var1 = 'Hello World' var2 = "Python Programming" print "var[0]:",var1[0] print "var2[1:5]:",var2[1:5] var1 = "Hello World" print "update a string",var1[:6]+'python' print "update a string",'python'+var1[5:] print r"hello\n" print "hello\n"
__author__ = 'kasi' import matplotlib.pyplot as plt from collections import OrderedDict # calculates the frequency of words based on their length and plots a graph of the words. class WordFrequencyCounter(object): characters_to_remove = ',.?!' def __init__(self, top_posts): self.top_posts = top_post...
#!/usr/bin/python3 from __future__ import print_function import contextlib import sys import logging from irods.configuration import IrodsConfig import irods.log def get_current_schema_version(irods_config=None, cursor=None): if irods_config is None: irods_config = IrodsConfig() return irods_config....
# coding: utf8 db = DAL('mysql://srikant:homeauto@localhost/ha_db') dropdown = ('jpg', 'pdf', 'png', 'doc') possible_extensions = ('jpg', 'pdf', 'png', 'doc') db.define_table('converter', Field('convert_from', requires = IS_IN_SET(dropdown), default = dropdown[0]), Field('convert_to',...
from typing import List, Any from random import random from math import log from collections import defaultdict cnt_pos_docs = 0 cnt_neg_docs = 0 def count_labels(labels: List): return { unique_label: sum(1 for label in labels if label == unique_label) for unique_label in set(labels) } def p...
#!/usr/bin/env python """Parse GTFS files. General Transit Feed Specification Reference: https://developers.google.com/transit/gtfs/reference Author: Panu Ranta, panu.ranta@iki.fi, https://14142.net/kartalla/about.html """ import csv import logging import os import polyline def get_routes(input_dir): """Pars...
import copy import re from printoption import PrintOption from unit import Unit class Battalion(object): def __init__(self, unit_config): self.unit_config = unit_config self.units = [] for c in self.unit_config["units"]: self.units.append(Unit(c, "unit")) def __str__(self)...
import json import requests # https://blog.51cto.com/183530300/2124750 TOKEN = "925265552:AAFjArE5ptRx9t7zp34YBiLq77_-4p7l0fc" def send_message(method, params=None): url = "https://api.telegram.org/bot{token}/{method}".format(token=TOKEN, method=method) print(url, params) rst = requests.get(url, params...