text
stringlengths
8
6.05M
# coding: utf-8 # Copyright 2013 The Font Bakery Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless re...
#리스트에서 특정 숫자의 위치 찾기 #입력 : 리스트 a, 찾는 값 x #출력 : 찾으면 그 값의 위치, 찾지 못하면 -1 def search_list(a,x): n = len(a) for i in range(0,n): if x == a[i]: return i,a[i] return -1 v=[18,97,5,46,84,21,5948,491,545] print(search_list(v,21)) print(search_list(v,10)) print(search_list(v,18))
# -*- coding: utf-8 -*- from django.contrib import admin from image_cropping import ImageCroppingMixin from base.admin import BaseArticleAdmin, BaseArticleSectionInline from press import models from snippets.admin.admin import ModelTranlsationFieldsetsMixin class NewsSectionInline(BaseArticleSectionInline): """...
''' @Description: In User Settings Edit @Author: suzhan @Date: 2019-07-14 15:09:08 @LastEditTime: 2019-07-22 16:50:12 @LastEditors: Please set LastEditors ''' from model_fasttext.basic_model import Model import tensorflow as tf from multiply import ComplexMultiply import numpy as np class Fasttext(Model): def _get_em...
import logging def get_logger(current_frame, name): try: logger_name = current_frame.f_back.f_globals['__name__'] logger_obj = logging.getLogger(logger_name) except: logger_obj = logging.getLogger(name) return logger_obj
# -*- coding: utf-8 -*- __author__ = 'yuvv' import sys import pygame from pygame.locals import * SCREEN_SIZE = (480, 390) # STAGE = 1 MAP_LIST = [] BALL_LIST = [] MAP_SIZE = (13, 16) PIC_SIZE = (30, 30) MAN_POS = [SCREEN_SIZE[0] // 2, SCREEN_SIZE[1] // 2] def update_rect(position, direction): ...
import math from numpy import random import time from collections.abc import Iterable import csv def fitness(sequence, evaluator): result = evaluator.run(sequence) res = result[0][0] return res def softmax(lst): result = [] lst = list(map(math.exp, lst)) sigma = sum(lst) for value in lst: ...
""" Advent of Code 2019 Day 4 """ def check_adjacent_digits_present(password): password = "".join(password) results = dict() digits = [str(i) for i in range(0, 10)] for digit in digits: chklist = [str(digit * x) for x in range(2, 7)] for chk in chklist: if ...
#!/usr/bin/env python import os import sys import time import xml.etree.ElementTree as et import urllib2 import httplib import psutil HOST = os.environ.get('HOST', "127.0.0.1") PORT = os.environ.get('PORT', "8053") BINDSTATS_URL = "http://%s:%s" % (HOST, PORT) PROCESS_NAME = "named" Path_base = "bind/statistics" Path...
import threading import time number = 100 arr = [11,22] def thread1(): global number time.sleep(1) number += 1 arr.append(33) print("thread1:number++ is %d-%s" % (number,arr)) def thread2(): arr.append(44) print("thread2:number is %d-%s" % (number,arr)) if __name__ == "__main__": ...
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ rList...
from sound_utils import * entries = GetEntryV1_1() print len(entries)
# Copyright 2019 Google LLC # # 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, ...
# reference: https://github.com/stan-dev/stan/releases/download/v2.14.0/stan-reference-2.14.0.pdf # the stan functions are from reference 2.8.0. Functions from 2.14.0 are very different and they are updated in functions.py # type high -> type hidden -> types # type hidden -> type high distribution_type = { "binary" :...
#!/usr/bin/env python # encoding: utf-8 from abc import abstractmethod, ABCMeta import datetime import random import time import unittest class PRNG: """ Represents default PRNG (currently, wrapper class for random module). """ def __init__(self): """ Constructs PRNG instance """ # Default se...
import numpy as np import glob from . import radxfer as rxf from . import convolve2aeri as c2a import sys from . import panel_file sys.path.append('../') from . import apodizer from . import tape7_reader as t7r import subprocess from scipy import convolve """ Object for Reading in LBLRTM data and doing performing ...
# Structure this script entirely on your own. # See Chapter 8: Strings Exercise 5 for the task. # Please do provide function calls that test/demonstrate your # function. def rotate_word(word,shiftint): word1='' numa=ord('a') numz=ord('z') for s in word: if shiftint>0 and ord(s)+shiftint>numz: ...
#!/usr/bin/env python # SPDX-License-Identifier: GPL-2.0 # Copyright Thomas Gleixner <tglx@linutronix.de> from argparse import ArgumentParser from ply import lex, yacc import locale import traceback import sys import git import re import os class ParserException(Exception): def __init__(self, tok, txt): s...
# Copyright 2017 AT&T Intellectual Property. All other rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required...
#!/usr/bin/python3 """This module creates a class Amenity that inherits from BaseModel""" from models.base_model import BaseModel class Amenity(BaseModel): """ This is a Amenity class with the public class attributes: - name: string - empty string """ name = ''
from __future__ import print_function from __future__ import division import string import datetime import numpy as np from sklearn.metrics import confusion_matrix from sklearn import metrics from sklearn.preprocessing import OneHotEncoder from keras.models import Model from keras.optimizers import SGD from keras.lay...
__author__ = 'Kostya'
import numpy as np import pandas as pd from dataset_loader import DatasetLoader from keras.models import load_model dataset = DatasetLoader() x = dataset.load_test_data('./fgd_prediction/dataset/test.csv') x /= 255 model = load_model('./fgd_prediction/model.h5') pred = model.predict(x) index = 0 for result in pred:...
# Determine if a list is monotonically increasing. def IsAscending(A): i = 1 maxN = A[0] while i < len(A) and A[i] > maxN: maxN = A[i] i += 1 return i - len(A) == 0 A = list(map(int, input().split())) IsAscending(A) if IsAscending(A) is True: print('YES') elif IsAscending(A) is Fa...
#!/usr/bin/env python # Funtion: # Filename: # 自定义异常,与系统定义异常不同名 class AlexException(Exception): def __init__(self, msg): self.message = msg def __str__(self): # 基类已经写了,可以不定义该函数 return self.message # return 'dfjdkj' try : raise AlexException('数据库连不上') except AlexException ...
import aiohttp from aiohttp import web from jinja2 import Environment, FileSystemLoader import json from .filegetter import DebufFileGetter from .. import messagesToHtml from ..utils import templates_list, js from pathlib import Path selfdir = Path(__file__).parent module = selfdir.parent loader = FileSystemLoader(...
import random from hand import rock from hand import paper from hand import scissors game_images = [rock, paper, scissors] user_input = input("What do you choose ? Type 0 for Rock, 1 for Paper or 2 for Scissors. ") user_choice = int(user_input) if user_choice > 2 or user_choice < 0: print("I could'nt understand, p...
#multiplication table def mul_table(n) : for i in range(1,9) : print("%d * %d = %d" % (n,i,n*i)) n = input("Give me the Number ") mul_table(n)
from pulp import LpMaximize, LpProblem, LpVariable, LpInteger, lpSum def score_team(t, opt): return { 'team_form': sum(float(p['form']) for p in t), 'team_price_change': sum(float(p['price_change']) for p in t), 'num_games': sum(float(p['next_gameweek']) for p in t), 'team_KPI': su...
#!/usr/bin/env python ''' Detects a word and changes it to "****" ''' def censor(text, word): words = text.split() # Split the text into a list of words for i in range(len(words)): # Loop through words if words[i] == word: words[i] = "*" * len(word) return " ".join(words) tex...
import tensorflow as tf # 1、sigmoid x = tf.linspace(-10., 10., 10) # startNum浮点数, endNum浮点数, Number of elements print(x) with tf.GradientTape() as tape: tape.watch(x) y = tf.sigmoid(x) print(y) grads = tape.gradient(y, [x]) print(grads) ''' x: [-10. -7.7777777 -5.5555553 -3.333333 -1.1111107 1....
from .stage import PipelineStage import matplotlib matplotlib.use("agg") matplotlib.rcParams['text.usetex'] = False import matplotlib.pyplot as plt from chainconsumer import ChainConsumer latex_names = { "cosmological_parameters--omega_b" : r"\Omega_b", "cosmological_parameters--omega_m" : r"\Omega_m...
#!/usr/bin/python prots='../list/ZINC_protein_index.tsv' #list of unique proteins with protein index blast='../list/ZINC_blast_result.dat' #list of BLAST results for ZINC proteins idx2prot={} prot2idx={} with open(prots,"r") as protline: next(protline) for line in protline: line=line.strip().split("\t"...
# learning scheme part2 # tensor and torch.autograd """ tensor可以记住他们自己来自什么运算,以及,其起源的父张量,并且提供相对于输入的导数链,因此无需手动对模型求导 不管如何嵌套,只要给出前向传播表达式,pytorch都会自动提供该表达式相对于其参数的梯度 在定义tensor的时候,required_grad=True,表示,pytorch需要追踪在params上进行运算而产生的所有tensor,换句话说,任何以params为祖先的Tensor都可以访问从params到该tensor所调用的函数链,如果这些函数是可微的,如果这些函数是可微的(大多数pytorch的ten...
from xml.etree import ElementTree from xml.etree.ElementTree import SubElement import adsk.core import adsk.fusion import traceback def write_xml_param_state(root, new_state, design): # Create a new State in the xml tree state = SubElement(root, 'state', name=new_state) user_params = design.userPar...
# coding: utf-8 # ## Task 1 # # ### 1. Write a program which will find all such numbers which are divisible by 7 but are not a multipleof 5, between 2000 and 3200 (both included). The numbers obtained should be printed in a comma-separated sequence on a single line. # In[72]: b=[] for x in range(2000,3201): i...
from Login.NewContract import * from register.RegisterPage import * from Login.logger import * class TestNewContract(unittest.TestCase, Page): '''新建合同''' def setUp(self): self.driver = webdriver.Chrome() self.driver.implicitly_wait(10) test_name = self._testMethodName + '>>>>>>>>>>>>>...
import cPickle as pickle import numpy as np import os, glob """ Store symmetry operations in .pickle format, with keys denoting the point group operation. For each point group, the symmetry operations contain both the rotation and translational operations; the final column corresponds to the translational element, and...
# -*- coding: utf-8 -*- #Bézout等式 #對兩正整數a與b,求出使得s*a+t*b=(a,b)的整數s和t def bezoutEquation(a=1, b=1): if a < b: c = a; a = b; b = c #交換a與b的次序,使得a≥b q = extendedEucrideanDivision(a,b) #廣義歐幾里德除法,求不完全商數組q s = coefficient_s(q) #求係數s t = coefficient_t(q) #求係數t ret...
# Problem Statement : Accept number from user and check whether number is even or # odd. def EvenOdd(iNo): if(iNo%2==0): return True else: return False def main(): iNo = int(input("Enter a number :\n")) iRet = EvenOdd(iNo) if(iRet==True): print("{} is Even".format(iNo)) ...
from random import random, sample, choice from math import floor from tqdm import tqdm from numpy import array, dot, mean from numpy.linalg import pinv from sys import exit #SST: the total error in a model, it is the sum of all deviations squared. #SSR: a measure of the explained variation in SST #COD: stands for ‘coe...
def step_class(page, step): return page.pyquery(f'[data-step="{step}"]').attr('class')
#!/usr/bin/env python import rospy import math import json import time from utilities import PORT_RENFREW_LATLON, MAUI_LATLON from std_msgs.msg import Float64 import local_pathfinding.msg as msg from geopy.distance import distance # Constants for this class PUBLISH_PERIOD_SECONDS = 10.0 # Can keep high to simulate r...
import sys def splitInput(lines): stack_data = [] moves = [] parsing_stack = True for line in lines: if not line: parsing_stack = False continue if parsing_stack: stack_data.append(line) else: moves.append(line) stack_coun...
# --- # jupyter: # jupytext: # formats: ipynb,py:light # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.3.1 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # WRC2020_View # # Visu...
from pyspark.sql import SparkSession def check_log_file(): sparkSession = SparkSession.builder.appName("example-pyspark-read-and-write").getOrCreate() df_load = sparkSession.read.parquet('hdfs://192.168.23.200:9000/data/Parquet/AdnLog/*') df_load.show() return None if __name__ == '__main__': check_log_file() ...
import numpy as np import sys import unittest sys.path.append('..') from src import minimize class testMinimize(unittest.TestCase): def test_minimize(self): n, p = 20, 4 A = np.random.rand(n, n) A = (A + A.T)/2 def f1(y): return np.sum(np.diag(np.dot(np.dot(y.T, A),...
import os # Zamienia linie w pliku na liste krotek w postaci # [((lewy_kraniec pierwszego przedzialu,prawy pierwszego przedzialu),(lewy_kraniec drugiego przedzialu,prawy_kraniec drugiego przedzialu),(litera))] def zamien(plik): przedzialy = [] for linia in plik: a = linia.split('|')[0] b = linia...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue May 12 20:16:12 2020 @author: altsai """ import os import sys import shutil import re import numpy as np import pandas as pd #file_AA_idx='AA_idx.list' file_AA_idx='AAA_idx.txt' #file_AA='AA.list' file_author='export-ads_A00.txt' file_author='export-cus...
#!/usr/bin/env python # echo_client.py import socket host = socket.gethostname() port = 12345 # The same port as used by the server s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) print('Sending Hello, world') s.sendall('Hello, world'.encode()) data = s.recv(1024) s.close() print('Receiv...
from .core import ez from .profiles import Profile
import regex as re import csv import time from googleSearch import search_it import numpy as np from os.path import dirname, abspath ,join d = dirname(dirname(abspath(__file__))) #set files directory path import sys # insert at position 1 in the path, as 0 is the path of this file. sys.path.insert(1, d) import Log ...
# -*- coding: utf-8 -*- """Module contains method that will be replaced by the plugin. :author: Pawel Chomicki """ import os import re def pytest_runtest_logstart(self, nodeid, location): """Signal the start of running a single test item. Hook has to be disabled because additional information may break out...
""" Helper functions for my KENDA scripts """ import sys from datetime import datetime, timedelta from subprocess import check_output from git import Repo from cosmo_utils.pywgrib import getfobj_ens, getfobj from cosmo_utils.helpers import yyyymmddhhmmss_strtotime, ddhhmmss_strtotime, \ yymmddhhmm from cosmo_utils...
# -*- coding: utf-8 -*- # !/usr/bin/env python from __future__ import absolute_import from __future__ import print_function import os import re import numpy as np import pandas as pd import jieba as jb import json import word exclude_re = re.compile(u"[,,【】<>{};??'\"]") filepath = os.path.split(os.path.realpath(__fi...
# -*- coding: utf-8 -*- """ Created on Thu Dec 10 16:08:50 2020 @author: ashwi """ from pyntcloud import PyntCloud import numpy as np import open3d as o3d from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt bin_pcd = np.fromfile('Mention ther path/.bin', dtype=np.float32) # Reshape ...
def findTheDifference(self, s, t): """ :type s: str :type t: str :rtype: str """ for char in set(t): if t.count(char) > s.count(char): return char
# Regular -- Parse tree node strategy for printing regular lists import sys from Special import Special from Tree import * class Regular(Special): # TODO: Add fields and modify the constructor as needed. def __init__(self): pass def print(self, t, n, p): # TODO: Implement this...
#通用装饰器(无参):可以给需要的函数套上一层外衣 def w1(func): def func_in(*args,**kwargs): return func(*args,**kwargs) return func_in @w1 def fun1(a,b): print("%s-----%s"%(a,b)) # @w1 # def fun1(*args,**kwargs): # print("%s-----%s"%(str(args),str(kwargs))) fun1(44,55) #通用装饰器(有参):可以给需要的函数套上一层外衣 def w2(pre_arg): ...
import unittest from pracownik import Pracownik class testPracownik(unittest): pracownik = Pracownik("Jan", "Kowalski", "Nauczyciel stażysta", 2000) def test_zwykly_awans(self): self.pracownik.zwykly_awans() self.assertEqual(self.pracownik.pensja, 2000*1.2) def test_degradacja_kierownicza(s...
#!/usr/bin/env python """Upload a FreeSurfer directory structure as RDF to a SPARQL triplestore """ # standard library from datetime import datetime as dt import hashlib import os import pwd from socket import getfqdn import uuid from utils import (prov, foaf, dcterms, fs, nidm, niiri, obo, nif, crypto, ...
import json import logging from aws import helper from aws.helper import DeveloperMode logger = logging.getLogger() logger.setLevel(logging.INFO) @DeveloperMode(True) def lambda_handler(event, context): input_json = json.loads(event["body"]) if not "refresh_token" in input_json: return helper.buil...
# Modified tissot function to take custom globe and draw multiple spots at once # Also, adds spots to given axis and returns matplotlib paths def tissot(rads_km=None, lons=None, lats=None, n_samples=80, globe=None, ax=None, draw=False, **kwargs): import numpy as np import cartopy.crs as ccrs import cartopy....
# interp_runge.py from numpy import * from pylab import plot, show, xlabel, ylabel, title, subplot from poly import newtonCoeffs,evalPoly def runge(x): return 1.0/(1.0+25.0*x*x) numnodes = input("Number of evenly spaced nodes: ") x = linspace(-1.,1.,numnodes,endpoint=True) y = runge(x) c = newtonCoeffs(x,y) xx = l...
""" 为 fast-rcnn生成训练数据 """ import numpy as np from config import Config from utils.bbox_overlaps import bbox_overlaps from utils.bbox_transform import bbox_transform config = Config() def proposal_target_layer(rpn_rois, gt_boxes, classes_num): rois, labels, bbox_targets, bbox_inside_weights, bbox_outside_weights ...
#!/home/epicardi/bin/python27/bin/python # Copyright (c) 2013-2014 Ernesto Picardi <ernesto.picardi@uniba.it> # # 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 ...
f = float(input("Enter a Decimal number: ")) x = float(input("Enter a Decimal number: ")) y = float(input("Enter a Decimal number: ")) print("Sum is: " + str(f + x + y)) print( 16 - 2 * 5 // 3 + 1) print(2 ** 2 ** 3 * 3)
from networkz.algorithms.link_analysis.pagerank_alg import * from networkz.algorithms.link_analysis.hits_alg import *
import time import numpy as np from gatheringData import create_splitted_file def automate(sleep=500,start=0,end=1000,interval=100): new_start=start if new_start+interval <= end: new_end=new_start+interval else: new_end=end for i in range(0,(end-start)//interval): crea...
#!/usr/bin/python class Node: def __init__(self,data=None,nextNode=None): self.data = data self.nextNode = nextNode class LinkedList: def __init__(self): self.head = None self.tail = None def insert_at_head(self,i): n = Node() n.data = i n.nextNo...
import logging import time import sys import lib.hwinfo.gpu as gpu from lib.utils import * logger = logging.getLogger(__name__) __lastLoadedModel = '' def loadModel(modelName, limit_memory_percentage = 85): logger.debug('enter loadModel') def checkUsageGpuMemory(): gpuUsage = gpu.gpuUsage() if...
#========================================================================= # pisa_lui_test.py #========================================================================= import pytest import random import pisa_encoding from pymtl import Bits, sext, zext from PisaSim import PisaSim from pisa_inst_test_utils import *...
import random import re def load_word(): ''' A function that reads a text file of words and randomly selects one to use as the secret word from the list. Returns: string: The secret word to be used in the spaceman guessing game ''' with open('../data/words.txt', 'r') as f: ...
# encoding: utf-8 import os, sys, io import shutil import tempfile import datetime import defs class StaticDirectory(object): def __init__(self, name, dirpath): self.name = name self.path = dirpath class File(object): def __init__(self, name): self.name = name f, sel...
print("CSYK"[input()%2::2])
# Generated by Django 2.2.5 on 2019-12-11 15:47 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('tem', '0001_initial'), ] operations = [ migrations.RenameField( model_name='copomapp', ...
#!/usr/bin/env python from __future__ import ( unicode_literals, absolute_import, print_function, division, ) str = type('') import io import os import time import datetime as dt import locale from collections import namedtuple, deque from pprint import pprint import pg8000 from chameleon import ...
# Wrapper function to run developed Random Spanning Tree Approximation algorithm parallelly on interactive cluster, for the purpose of multiple parameters and datasets. # The script uses Python thread and queue package. # Implement worker class and queuing system. # The framework looks at each parameter combinatio...
''' Created on 2012-3-13 @author: 301645 ''' import os import shutil from common.pyruncmd import pyruncmd class pywincmds(object): ''' 封装一些经常使用的windows命令 ''' py_cmd = pyruncmd() @staticmethod def call_cmd(py_curcmd): pywincmds.py_cmd.command_str = py_curcmd pywincmds...
# -*- coding: utf-8 -*- """Utility functions.""" #------------------------------------------------------------------------------ # Imports #------------------------------------------------------------------------------ import sys import os.path as op from inspect import getargspec from ..ext.six import string_type...
from bs4 import BeautifulSoup import requests import pandas as pd import json from requests.compat import urljoin from datetime import datetime import re def game_data(): print(str(datetime.now().time())[:8]) all_items = [] pg_ids = [] pg_links = [] for pg in range(1, 21): p...
import network, machine, ssd1306, test, oled_ssd1306, time, menu_framework import uasyncio as asyncio loop = asyncio.get_event_loop() board_station = network.WLAN(network.STA_IF) board_AP = network.WLAN(network.AP_IF) def reboot(): machine.reset() async def ipcfg(): # allows easy setting of AP c...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('subscriptions', '0002_subscriber_name'), ] operations = [ migrations.AddField( model_name='subscriber', ...
# coding: utf-8 import requests import re import os import base64 def decode(s): return str(base64.b64decode(s),'utf-8') UN = decode(os.getenv('UN')) UP = decode(os.getenv('UP')) HOST = decode('d3d3LnYyZXguY29t') def main(): headers = { 'User-Agent': 'Mozilla/5.0 (X11; Linux i686) AppleWebKi...
import sqlite3 def isLoginSuccess(user_id, password): conn = sqlite3.connect('Database.db3') cursor = conn.cursor() cursor.execute("select * from User where user_id = '" + user_id + "' and password = '" + password + "'") result = cursor.fetchall() cursor.close() conn.close() if len(result...
from django.conf import settings from django.contrib.auth.decorators import login_required from django.shortcuts import render @login_required(login_url=settings.LOGIN) def index(request): return render(request, 'users/dashboard.html')
from two_stream_rgb_flow.model.AU_rcnn.utils.resize_bbox import resize_bbox from two_stream_rgb_flow.model.AU_rcnn.utils.random_flip import random_flip from two_stream_rgb_flow.model.AU_rcnn.utils.flip_bbox import flip_bbox
import random a = [] def getN(num1,num2): def sameout(num1): num = random.randint(1,num1) if num in a: sameout(num1) else: a.append(num) for i in range(num2): sameout(num1) return a getN(num1,num2) a.sort() print a
import tensorflow as tf import os import logging from tensorflow.python.keras.backend import flatten from utils.all_utils import get_timestamp def get_VGG_16_model(input_shape,model_path): model=tf.keras.applications.vgg16.VGG16( input_shape=input_shape, weights="imagenet", include_top=False ) ...
# encoding:utf-8 __author__ = 'hanzhao' import sys import requests import urllib import urllib2 import json import re # http://www.zhtimer.cn:2014/scramble/.json?=333*1 SCRAMBLE_URL = 'http://www.zhtimer.cn:2014/scramble/.json?=' def run(msg): print '[info] 魔方小工具模块载入中。。' if '<br/>' in msg: #为群聊消息时...
l1 = [1 ,4 ,5, 6, 9] index = [0, 2, 0, 4, 2, 4, 4, 0, 1, 3, 3] l2 = [] for i in index: l2.append(str(l1[i])) tel = ''.join(l2) print('WeChat And Tel:' + tel)
import os, sys, re; import string; def mkChanges(scheme, lttr, nodes): #print(nodes[1]); for node in nodes[1]: print('---',node, scheme[node], scheme[node][0]); scheme[node][0].remove(lttr); del scheme[lttr]; print('***\n\n',scheme,'***\n\n'); return; step1 = []; step2 = []; a...
import bigbenclock import customreply from internal import const as C host = '127.0.0.1' port = 9876 super_user = 10000 scheduler_opt = { 'apscheduler.timezone': 'Asia/Shanghai' } bot_commands = { # keyword: [callback_func, cooldown in secs, grp/priv, enabled groups, regex, msg, at_sender] r'.*有人.+[吗嘛][...
import redis import msgpack class UserCache(object): _instance = None SEEN_USERS_SET_KEY = 'seen_users' @classmethod def get_instance(cls): if cls._instance is None: # TODO set passwords, logical db and such cls._instance = redis.StrictRedis() return cls._insta...
# Copyright 2018 Nicholas Li # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
# -*- coding: utf-8 -*- import nysol._nysolshell_core as n_core from nysol.mcmd.nysollib.core import NysolMOD_CORE from nysol.mcmd.nysollib import nysolutil as nutil class Nysol_Mcat(NysolMOD_CORE): _kwd,_inkwd,_outkwd = n_core.getparalist("mcat",3) def __init__(self,*args, **kw_args) : super(Nysol_Mcat,self)._...
from os import path from datetime import timedelta from .general import get_run_date_times def extract_water_levels(run_path, channel_cell_map, flood_plain_map): HYCHAN_OUT_PATH = path.join(run_path, 'output', 'HYCHAN.OUT') TIMDEP_OUT_PATH = path.join(run_path, 'output', 'TIMDEP.OUT') base_dt, run_dt = g...
#!/usr/bin/python # -*- coding: utf-8 -*- # @author: Anna def jijiji(is_cheap, buy_amount, good_price): all_price = good_price * buy_amount if is_cheap: print '老妈在小本子记了买菜花销%d元 ' % (all_price) def talktalktalk(is_cheap, buy_amount, good_price): if is_cheap: print '老妈回到家里,跟老爸说:"今天菜很便宜, 我买了%d斤"。' % (buy_amou...
import velocity import sys import atexit import uuid import datetime DB_NAME = r'vscDatabase' DB_USER = 'script' DB_PASS = 'script' # if workstation DB_PATH = r'/Velocity/Databases/vscDatabase' # if grid DB_IP = '127.0.0.1' DB_PORT = 57000 # requires "sixCBCT, AdaptiveMonitoring" data already imported PATIENT_ID = '...
from .tok import Token class LexicalTable: def __init__(self): self.tokenslist: Token = [] def __len__(self): return len(self.tokenslist) def __getitem__(self, item): return self.tokenslist[item] def append(self, new: Token): self.tokenslist.append(new) def __st...