text stringlengths 38 1.54M |
|---|
from nullroute.core import Core
import uuid
from .entry_util import *
from .string import *
class FilterSyntaxError(Exception):
pass
class Filter():
def __call__(self, entry):
return bool(self.test(entry))
@staticmethod
def parse(text):
token = ""
tokens = []
depth = ... |
from typing import Optional, Dict
import xml.etree.ElementTree as ET
class EphemeralLaunchFile(object):
"""
Provides temporary launch files that can be used to pass launch-time
parameters to ROS. Specifically, ephemeral launch files are used to provide
launch-time parameters to ROSLaunchParent since t... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AlipayCommerceEducateFacepayApplyModel(object):
def __init__(self):
self._ext_info = None
self._face_open_id = None
self._face_uid = None
self._scene = None
... |
from pwn import *
context.arch = 'amd64'
###Utils
def new(sz,data):
r.sendlineafter('> ','1')
r.sendlineafter('size: ',str(sz))
r.sendafter('content: ',data)
def prnt(idx):
r.sendlineafter('> ','2')
r.sendlineafter('index: ',str(idx))
return r.recvline()[:-1]
def rmv(idx):
r.sendlineafte... |
print('HELLO\nWELCOME TO OUR SOFTWARE')
username = (input('ENTER YOUR USERNAME: '))
#password = int(input('ENTER YOUR PASSWORD: '))
access='DIVINE'
try:
if username== access :
password = int(input('ENTER YOUR PASSWORD: '))
if password == 1234 :
print('YOU ARE WELCOME', username)
e... |
from __future__ import unicode_literals
from django.apps import AppConfig
class AnappConfig(AppConfig):
name = 'anapp'
|
import unittest
from bs4 import BeautifulSoup
from nanorcc.parse import parse_tag, parse_rcc_file, get_rcc_data
from collections import OrderedDict
import pandas as pd
class TestParseTag(unittest.TestCase):
"""test the parse_tag function using example.RCC"""
def setUp(self):
with open('tes... |
import time
import numpy as np
from algorithms.memetic.memetic_algorithm import MemeticAlgorithm
from algorithms.genetic.nsga_ii import NSGAII
from problems.problem import Problem
class NSMA(NSGAII, MemeticAlgorithm):
"""
Class for the NSMA Algorithm
The main functions are:
- Initialize a NSMA ... |
# Script of derivate computation
import numpy as np
import matplotlib.pyplot as plt
def dfdx_1(f,x,h):
return (f(x + h) - f(x))/h
def dfdx_2(f,x,h):
return (f(x) - f(x-h))/h
def dfdx_3(f,x,h):
return (f(x + h) - f(x - h))/(2*h)
def dfdx_4(f,x,h):
return (-f(x + 2*h) + 8*f(x + h) - 8*f(x - h) + f(x -... |
import argparse
import logging
import os
import koco
import pandas as pd
import torch
import torch.nn.functional as F
from omegaconf import OmegaConf
from transformers import BertForSequenceClassification
from utils import get_device_and_ngpus, makedirs, read_lines
logger = logging.getLogger(__name__)
device, n_gpus... |
from django.http.response import JsonResponse
from django.shortcuts import render
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.parsers import JSONParser
from products.models import Product
from products.serializers import ProductSerializer
# Create your views h... |
import json
defaultconfig={'station':'B08','apikey':'kfgpmgvfgacx98de9q3xazww','walktime':'6','loop':'False','simulate':'True'}
#I've hardcoded my default configuration for the program, for resetting purposes or in case the config.json file is deleted
class myMetro:
"""
Class for personal metro data. Most of... |
def read_lines(file_name):
lines = open(file_name).readlines()
lines = filter(lambda l: l != "\n", lines)
lines = list(map(lambda l: l[:-1].lower(), lines))
lines.reverse()
return lines
def read_def(lines, title=None):
t, count = lines.pop().split(":")
if(title is None):
return t, ... |
"""
Given a string (with words and spaces), split it into substrings that have at most k characters each.
Each substring must contain whole words only. Assume that k > the shortest word in the sentence.
Example:
s = "I pet my cats and dogs"
k = 5
expected output: ['I pet', 'my', 'cats', 'and', 'dogs']
Example 2:
s =... |
# We can efficiently solve for multiple potentials with one command
# Under the hood, using the batch functionality is more efficient
# than solving for one potential at a time because executing in batch
# doesn't require transitioning back in forth between the python
# and the C backend between jobs.
import schrod
im... |
import urllib.request
import time
success = False
for i in range(6 * 3):
try:
url = 'https://raw.githubusercontent.com/wkcn/SYSULAB/master/script.py'
req = urllib.request.Request(url)
f = urllib.request.urlopen(req)
s = f.read()
success = True
break
except urll... |
N=int(input())
Sum=0
numerator=2
dinominator=1
for i in range(N):
Sum+=numerator/dinominator
temp=numerator+dinominator
dinominator=numerator
numerator=temp
print('{:.2f}'.format(Sum)) |
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.http import *
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.decorators import login_required
from django.contrib.auth.decorators import login_required
from djan... |
# Generated by Django 3.0 on 2021-01-16 10:31
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("grades", "0026_remove_grad... |
from __future__ import print_function, absolute_import, division
from builtins import map
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file e... |
## -*- coding: utf-8 -*- ####################################################
from django.conf import settings
from django.utils.translation import ugettext
from image_editor.filters.basic import ImageEditToolBasic
#CROP_RATIO
class ImageCropTool(ImageEditToolBasic):
class Media:
js = ('jcrop/js/jquery.... |
from django.contrib import admin
from doors.keymaster.models import *
class KeymasterAdmin(admin.ModelAdmin):
def force_sync(self, request, queryset):
for km in queryset:
km.force_sync()
self.message_user(request, "Sync will be forced on next contact from the gatekeeper")
list_dis... |
'''
泰波那契序列 Tn 定义如下:
T0 = 0, T1 = 1, T2 = 1, 且在 n >= 0 的条件下 Tn+3 = Tn + Tn+1 + Tn+2
给你整数 n,请返回第 n 个泰波那契数 Tn 的值。
示例 1:
输入:n = 4
输出:4
解释:
T_3 = 0 + 1 + 1 = 2
T_4 = 1 + 1 + 2 = 4
示例 2:
输入:n = 25
输出:1389537
提示:
0 <= n <= 37
答案保证是一个 32 位整数,即 answer <= 2^31 - 1。
'''
from leetcode.tools.tim... |
import discord
import time
import datetime
import asyncio
import random
from discord.ext import commands
from random import randint
class Games():
def __init__(self, bot):
self.bot = bot
@commands.command()
async def choose(self, *choices : str):
"""Chooses Between Multiple... |
# Minci
# time elapsed: 37 min
# submitted 2 times
class Solution:
def calculate(self, s: str) -> int:
# re-organize spaces
s = s.replace(' ', '')
for op in "+-*/":
s = s.replace(op, str(' ' + op + ' '))
# separate the list by space
s = s.split(' ')
#... |
import logging
from celery.utils.log import get_task_logger
from lms.lmstests.sandbox.config.celery import app
from lms.lmstests.sandbox.linters import base
_logger: logging.Logger = get_task_logger(__name__)
_logger.setLevel(logging.INFO)
@app.task
def run_linters_in_sandbox(solution_file_id: str, code: str, fil... |
import tensorflow as tf
from tensorflow.keras.layers import Input, Conv2D, Flatten, Dropout, Dense, BatchNormalization, MaxPooling2D
from keras.models import Model
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from sklearn.metrics import confusion_matrix
(x_train, y_train), (x_test, y_test) ... |
from numpy import *
from numpy.linalg import *
bac = array([[2, 1, 4],[1, 2, 0],[2, 3, 2]])
vet = array(eval(input("Vetor: ")))
vet = vet.T
qtd = dot(inv(bac),vet)
print("estafilococo: ", round(qtd[0], 1))
print("salmonela: ", round(qtd[1], 1))
print("coli: ", round(qtd[2], 1))
if(qtd[0] == min(qtd)):
print("e... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
import unittest
# 4L de jacky
# le compteur kilométrique de la 4L de jacky est tout neuf
# quand le compteur affiche 222222 on retourne True
# quand le compteur affiche 444444 on retourne True
# quand le compteur affiche 738922 on retourne False
# quand le compteur affiche 051968 on retourne True
from Odometer import... |
from bert.preprocess import PAD_INDEX
from sklearn.metrics import f1_score, balanced_accuracy_score
import numpy as np
def mlm_accuracy(predictions, targets):
mlm_predictions, nsp_predictions = predictions
mlm_targets, is_nexts = targets
relevent_indexes = np.where(mlm_targets != PAD_INDEX)
relevent... |
# Importing the required libraries
import hashlib, json, sys
"""
def HashFunc(msg=""):
if type(msg) != str:
msg = json.dumps(msg,sort_keys=True)
if sys.version_info.major == 2:
return unicode(hashlib.sha256(msg).hexdigest(),'utf-8')
else:
return hashlib.sha256(str... |
from random import randint
from time import sleep
dados = []
megasena = []
print('=='*20)
print('{:^40}'.format('MEGA-SENA'))
print('=='*20)
n = int(input('Quantos jogos você quer que eu sorteie? '))
print(f'-=-=-=-=-= SORTEANDO {n} JOGOS -=-=-=-=-')
for c in range (1, n+1):
for d in range(0, 6):
... |
import os
import pickle
import numpy as np
from sklearn.model_selection import train_test_split
"""This script implements the functions for reading data.
"""
def loadpickle(path):
with open(path, 'rb') as file:
data = pickle.load(file,encoding='bytes')
return data
def load_data(data_dir):
"""Load ... |
#! /usr/bin/env python
# coding = utf-8
import time, pickle, json
d = {'a': 'b'}
c = {'d': 'e'}
p1 = pickle.dumps(d)
p2 = pickle.dumps(c)
j1 = json.dumps(d)
j2 = json.dumps(c)
def write2txt():
with open('time.txt', 'w') as f:
f.write(j1)
f.write('\n')
f.write(j2)
def readftxt():
with... |
def readAPIC(filename, artist, album, filetype):
fp = open(filename, 'rb')
if filetype == '.m4a':
covr = b'covr'
elif filetype == '.mp3':
covr = b'ID3'
else:
return False
imagetype = '.png'
start = b'\x89\x50\x4E\x47\x0D\x0A\x1A\x0A' # 默认为png,因为png的文件头长,误匹配到的概率低
end ... |
import subprocess
class PowerShellInterface:
def __init__(self):
pass
def runCommand(self, cmd):
result = subprocess.run(["powershell", "-Command", cmd], capture_output=True)
return result
def printTestCommandOutput(self):
testCommand = "Write-Host Hello World!"
res... |
import subprocess
import re
from json import JSONEncoder, JSONDecoder
IFACE_STATUS_REGEX = re.compile(r"^[0-9]+:\s([a-zA-Z0-9]+):\s<([A-Za-z,-_]+)>.+state\s((DOWN|UP)).*")
class IFaceError(Exception):
pass
def check_interface_up(interface_name):
check_cmd = ['ip', 'link', 'show', interface_name]
proc =... |
# -*- coding: utf-8 -*-
'''
@Author: Wengang.Zheng
@Email: zwg0606@gmail.com
@Filename: 接雨水.py
@Time: 2021-01-17-14:53:55
@Des:
核心思路:i位置的蓄水量由左右两边的最高柱子高度决定
water[i] = min(
# 左边最高的柱子
max(height[0..i]),
# 右边最高的柱子
max(height[i..end])
) - height[i]
'''
def violent_trap(heights):
"""
@brief 接雨水暴力解法: O(n^2),... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/8/16 17:52
# @Author : Geda
import requests
import re
import urllib
import os
import sys
reload(sys)
sys.setdefaultencoding('utf8')
def get_response(url):
response = requests.get(url).text
return response
def get_content(html):
... |
# -*-coding = utf-8-*-
# __author:"NGLS Chuang"
# @time:2019/12/4 15:39
import os
import sys
# 导入路径
from ChooseCourseSystem.core import data
from ChooseCourseSystem.core import education
# BASE_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# sys.path.append(BASE_PATH)
# print(BASE_PATH)
# 创建学校
d... |
def printinfo():
print("---" * 10)
print(" python就是简洁")
print("---" * 10)
def add2(a, b):
c = a + b
print(c)
def add2num(a, b):
return a + b
# 返回多个值
def divide(a, b):
shang = a // b
yu = a % b
return shang, yu
printinfo()
add2(11, 21)
result = add2... |
from aws_cdk import core as cdk
from aws_cdk import aws_dynamodb as _ddb
import os
class GlobalArgs:
"""
Helper to define global statics
"""
OWNER = "MystiqueAutomation"
ENVIRONMENT = "production"
REPO_NAME = "glue-elastic-views-on-s3"
SOURCE_INFO = f"https://github.com/miztiik/{REPO_NAM... |
# -*- coding: utf-8 -*-
import urllib2
from urllib import urlencode
url = 'http://apis.baidu.com/turing/turing/turing'
req = urllib2.Request(url)
req.add_header('apikey', '1b7f52ccc223f79eb67ab1cc25af0ab7')
urlParam = {
'key': '879a6cb3afb84dbf4fc84a1df2ab7319',
'info': '你好',
'userid': '张三'
}
urlParam = url... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
print("hi")
process.stdout.readline()
sys.stdout.flush()
sys.stdout.write("\n")
sys.stdout.write("running bigQuery ETL...")
import ETLbiqQueryData
ETLbiqQueryData.main()
sys.stdout.flush()
sys.stdout.write("Done!")
sys.stdout.write("\n")
sys.stdout.write("clean... |
{
"id": "mgm4456372.3",
"metadata": {
"mgm4456372.3.metadata.json": {
"format": "json",
"provider": "metagenomics.anl.gov"
}
},
"providers": {
"metagenomics.anl.gov": {
"files": {
"100.preprocess.info": {
... |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from fake_useragent import UserAgent
import MySQLdb
from multiprocessing.dummy import Pool as ThreadPool
# from multiprocessing import Pool
import time
# sql='c... |
#!/bin/python3
import math
import os
import random
import re
import sys
def getWays(n, c):
mem = [0] * (n+1)
mem[0] = 1
for coin in c:
for i in range(coin, n+1):
mem[i] += mem[i-coin]
return mem[n]
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_... |
import os
from conans import ConanFile, tools
class SmlConan(ConanFile):
name = "SML"
version = "latest"
license = "Boost"
url = "https://github.com/paulbendixen/sml.git"
description = "[Boost].SML: C++14 State Machine Library"
#no_copy_source = True
# No settings/options are necessary, t... |
import string
from collections import Counter
import matplotlib.pyplot as plt
from nltk.corpus import stopwords
from nltk.sentiment.vader import SentimentIntensityAnalyzer
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import word_tokenize
text = open('read.txt', encoding='utf-8').read()
lower_c... |
from datetime import datetime
import pandas as pd
print('\nSistema de cadastro de anúncios.\n')
anuncio = []
# Função para cadastrar
def cadastro():
nome = input('Digite o nome do anúncio: ')
cliente = input('Digite o nome do cliente: ')
# Data inicial
dataInicio = datetime.strptime(input(f'Digite a d... |
from django import forms
from .models import UserAccount
class UserAccountForm(forms.ModelForm):
class Meta:
model = UserAccount
fields = ('default_first_name', 'default_last_name', 'default_phone_number',
'default_street_address1', 'default_street_address2',
'd... |
from rest_framework import serializers
from teams.serializer import TeamSerializer
from .models import Match
class MatchSerializer(serializers.ModelSerializer):
away_team = TeamSerializer(many=False)
home_team = TeamSerializer(many=False)
phase = serializers.CharField(source='get_phase_display')
wi... |
import os
import pdb
import glob
import json
import dask
import logging
import datetime
import argparse
import subprocess
import numpy as np
import pandas as pd
import xarray as xa
import random as rand
from adcirc_utils import *
from time import perf_counter, sleep
from array import array
from contextlib import contex... |
class myTest:
import pry
def __init__(self, val):
self.interface = "test" + val
def dodo(self):
print(self.interface)
self.pry() |
import os
import numpy as np
dataset_folder = '/home/priya/code/data_volume/timecycle'
outlist = os.path.join(dataset_folder, 'davis/DAVIS/vallist.txt')
imgfolder = os.path.join(dataset_folder, 'davis/DAVIS/JPEGImages/480p/')
lblfolder = os.path.join(dataset_folder, 'davis/DAVIS/Annotations/480p/')
jpglist = []
f1 =... |
import os, sys
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
PROJECT_NAME = os.path.basename(PROJECT_ROOT)
sys.path.insert(0, PROJECT_ROOT)
sys.path.insert(0, os.path.abspath(os.path.join(PROJECT_ROOT, os.pardir)))
venv_path = os.path.abspath(os.path.join(PROJECT_ROOT, "../../../"))
activate_this = os.pa... |
from cryptography.hazmat import backends
from cryptography.hazmat.primitives.asymmetric import dsa
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.asymmetric import rsa
from Crypto.PublicKey import DSA
from Crypto.PublicKey import RSA
# Correct
dsa.generate_private_key(key... |
import schedule
import time
import days2 as d
import stopRunning2 as stp
schedule.every().friday.at("00:00").do(d.mondayToWednesdayAndWeekendPrayer)
schedule.every().sunday.at("00:00").do(d.mondayToWednesdayAndWeekendPrayer)
schedule.every().monday.at("00:00").do(d.mondayToWednesdayAndWeekendPrayer)
schedule.every().... |
import numpy as np
from sklearn.cluster import KMeans
import pickle as pkl
print ('data preparing ...')
# read the src
datapath = '../../data/'
data = np.genfromtxt(datapath + 'Sepsis_imp.csv', dtype=float, delimiter=',', skip_header=1)
# remove intervention, but include ventilation, sedation, RRT
interventions = np.... |
for _ in range(int(input())):
n = int(input())
arr = list(map(int, input().split()))
max_ans = 0
check_ans = 0
tot_ind = 0
min_val = 0
for i in arr:
tot_ind += 1
if min_val == 0:
min_val = i
else:
if i < min_val:
... |
# WORK IN PROGRESS
class Flatten(nn.Module):
def flatten(x):
N = x.shape[0] # read in N, C, H, W
return x.view(N, -1) # "flatten" the C * H * W values into a single vector per image
hidden_layer_size = 4000
learning_rate = 1e-2
input_dim = 20
num_channels = 3
model = nn.Sequential(
Flatten(),
nn.Linear(inp... |
import bugzilla
import configuration
import logging
URL = configuration.get_config(parameter_type='bugzilla-creds', parameter_name='bugzilla_url')
bzapi = bugzilla.Bugzilla(URL)
default_product = configuration.get_config(parameter_type='default-params', parameter_name='default_product')
default_component = configurati... |
"""
Runs the test dataset over the data, and stores the predictions
The arguments are loaded from a .yaml file, which is the input argument of this script
(Instructions to run: `python test_model.py <path to .yaml file>`)
"""
import os
import sys
import time
import logging
import pickle
import yaml
import numpy as n... |
# -*- coding: utf-8 -*-
"""
Execution utilities.
"""
import multiprocessing
import concurrent.futures as cf
import subprocess
import logging
import gc
from math import floor
import os
import psutil
import getpass
import shlex
from warnings import warn
from rex.utilities.loggers import LOGGERS, log_mem
from rex.utiliti... |
from flask import Flask, render_template, request, redirect
from flask import Blueprint
from repositories import task_repository, user_repository
from models.task import Task
tasks_blueprint = Blueprint("tasks", __name__)
@tasks_blueprint.route('/tasks')
def tasks():
# Get all the tasks
tasks = task_repositor... |
import MySQLdb
import re
"""
Connects to the MySQL database. Various functions to retrieve and update data.
Each function a forms new connection with the server, for ease of access
in project development.
Functions:
add_to_blacklist(word) - Inserts word into blacklist, if word already exists
... |
import pandas as pd
import numpy as np
from PIL import Image
#Оставляем у числа только 3 знака после запятой
def toFixed(numObj, digits=3):
return f"{numObj:.{digits}f}2"
#Все бинарные изображения почему-то имеют значения не 1 и 0, а 255 и 0. Эта функция исправляет проблему.
def foo(item):
if (item == 255)... |
from flask_restful import Resource, reqparse
from backend.main_api import main_api
from backend.models import Asset, AssetSchema, User, Branch, AssetCostCenterSchema, AssetCostCenter, CostCenter
from backend.db import save_to_db, delete_from_db
from flask_jwt_extended import jwt_required
from backend.api.utils import c... |
#!/usr/bin/env python
# 你想创建一个字典,并且在迭代或序列化这个字典的时候能够控制元素的顺序。
from collections import OrderedDict
# 一个 OrderedDict 的大小是一个普通字典的两倍,因为它内部维护着另外一个链表。
# 所以如果你要构建一个需要大量 OrderedDict 实例的数据结构的时候(比如读取100,000行CSV数据到一个 OrderedDict 列表中去)
# 那么你就得仔细权衡一下是否使用 OrderedDict 带来的好处要大过额外内存消耗的影响。
d = OrderedDict()
d['foo'] = 1
d['bar'] = 2
d[... |
# functions
def print_separator():
print('--------')
print('here')
# intructions
print("Hello World")
# variables
name = 'Wes'
age = 31
total = 99.78
found = False
print(name)
print(age)
print(total)
print(age + 13)
print_separator()
# if statements
user_age = 79
if(user_age ... |
import requests
url = 'http://httpbin.org/post'
data = {
'name': '孔维一',
'age': 21
}
resp = requests.post(url, data=data)
print(type(resp))
print(resp)
print(resp.text)
print(resp.json())
|
import datetime as dt
import matplotlib.pyplot as plt
from matplotlib import style
import pandas as pd
import pandas_datareader.data as data
import os
import ta
ticker = input(str("Enter ticker: "))
def get_stock_prices():
data_source = 'yahoo'
start = dt.datetime(2018, 1 ,1)
end = dt.datetime.today()
... |
################ modules for HSPICE sim ######################
##############################################################
######### varmap definition ####################
##############################################################
### This class is to make combinations of given variables ####
### ... |
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Balance:
def isBalance(self, root):
# write code here
(_, isB) = self.isBalanceIter(root)
return isB
# (height, isBalance)
def is... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from .pointnet import PointNetfeat
from .pointnet2 import PointNet2feat as PointNet2
class TPointNet2(nn.Module):
'''
TPointNet++
Extracts an initial z0 feature based on the given sequence and regresses TNOCS points.
'''
def __init... |
import argparse
import cv2 as cv
import os
import numpy as np
import random
import sys
class Person():
def __init__(self, id, label, data):
self.id = id
self.label = label
self.data = data
def get_image_data(file_name):
img = cv.imread(file_name, cv.IMREAD_GRAYSCALE)
# Muda o t... |
import concurrent.futures
from tqdm import tqdm
import requests
from z3 import *
import math
import json
import time
# M = 3
# N = 13
# t = [3, 3, 4, 3, 4, 3, 3, 3, 4, 3, 3, 4, 4]
# c = [[0, 2, 3, 4, 8, 10], [0, 1, 3, 5, 6, 7, 8], [1, 2, 3, 7, 9, 11, 12]]
# S = [[2, 4, 8], [4, 10], [], [7, 9], [], [11, 12], [8, 12], []... |
# -*- coding:utf-8 -*-
try:
from io import StringIO
except ImportError:
from StringIO import StringIO
from lxml import etree
OPTIONS = [
(('-p', '--path'), {'help': 'xml contains xpath criteria will be extracted', 'type': str}),
(('-b', '--body'), {'help': 'xpath element to extract when matching is... |
# -*- coding: utf-8 -*-
"""
Author: Jef De Smet | jef.desmet@kuleuven.be
edited: Pieter Spaepen
Date: February 2020
Class of elements.
"""
"""
An element has at least
elementNr elementNr used as identifier of this element, must be chosen unique
firstNode the starting node
s... |
from django.contrib import admin
from micameo.order.models import (Order, Occasion, Cameo)
# Register your models here.
@admin.register(Occasion)
class Occasion(admin.ModelAdmin):
list_display = ["occasion_name"]
search_fields = ["occasion_name"]
@admin.register(Order)
class Order(admin.ModelAdmin):
lis... |
import os
from datetime import datetime
from flask import Flask, Response, jsonify, request
from prometheus_flask_exporter import PrometheusMetrics
from prometheus_client import make_wsgi_app
from werkzeug.middleware.dispatcher import DispatcherMiddleware
from werkzeug.serving import run_simple
from books import boot... |
import json
import logging
from pathlib import Path
import firebase_admin.firestore
from google.api_core.exceptions import AlreadyExists, NotFound
from google.cloud.firestore_v1 import Client
from telegram import Message
from giru.config import settings
cert_file_path = Path(settings.FIREBASE_ACCOUNT_KEY_FILE_PATH).... |
from collections import Iterable
def flatten(items, ignore_type=(str,bytes)):
'''
对嵌套的序列进行扁平化操作
:param items: 可迭代对象
:param ignore_type: 最小元素类型
:return: 单个元素
'''
for x in items:
if isinstance(x,Iterable) and not isinstance(x,ignore_type):
yield from flatten(x)
els... |
from flask import request
from app.api.responses import Responses
parties = []
class PoliticalParty:
"""this initializes political party class methods"""
def __init__(self, name, hqAddress, logoUrl):
self.party_id = len(parties) + 1
self.name = name
self.hqAddress = hqAddress
... |
class Config(object):
def __init__(self, path):
@property
def pages(self):
return self
class Page(object):
def __init__(self, plugin, name, config):
self._name = name
self._config = config
self._plugin = plugin
def widget(self):
|
from django.conf.urls import patterns, url
from fans.views import get_fans, fans_report, group_up
urlpatterns = patterns(".views",
url('^get_fans/', get_fans),
url('^report/', fans_report),
url('^group_up/', group_up),
)
|
# i=input()
# print(f"hello {i}")
def square(x):
return x*x
def mian():
for i in range(10):
print("{} squared is {}".format(i,square(i)))
if __name__=="__main()__":
mian()
print(square(10))
|
####################
# Ydna Hash Killer #
# V: 1.1.1 #
####################
import itertools
import hashlib
import os
import hashlib,binascii
composicao = True
tamanho = True
continuar = True
continuar2 = True
continuargeral = True
chrs = ""
criptografia = ""
codehash = ""
quadro = """
... |
# this code is on the lowest level .Hadn't added any error handling. Need to improve this in future
# See this link and add other methods https://github.com/eclipse/paho.mqtt.python#single
import paho.mqtt.client as paho
import time
import paho.mqtt.publish as publish
def my_mqtt_publish(topic, payload):
try:
... |
import pandas as pd
import numpy as np
import sketches
import matplotlib.pyplot as plt
import torch
from tqdm import tqdm
from pathlib import Path
import itertools
from multiprocessing import Pool
from functools import partial
import multiprocessing
def get_f_error(true, pred):
return np.sum(true * abs(pred - true... |
import os
import subprocess
import time
import urllib.request
from shutil import copyfile
def main():
cwd = os.getcwd()
copyfile(cwd + "/modlunky2.exe", cwd + "/modlunky2.exe.bak") # Creates temp backup
try:
os.remove(cwd + "/modlunky2.exe") # deletes current version
print("Download la... |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""Crypto related wrapper functions."""
import logging
import pyswitcheo.crypto_utils as cutils
from neocore.Cryptography.Crypto import Crypto
from pyswitcheo.datatypes.fixed8 import Fixed8
from pyswitcheo.datatypes.transaction_types import (
TransactionInput,
Tra... |
__version__ = '0.0.1'
__author__ = 'czh'
from .main import TPTool
from .main import normalThread
from .webDriverPool import ChromeDriverHelper
from .threadGuiHelper import threadGuiHelper
|
#coding=utf-8
'''
Created on 2013年9月22日
@author: hongkangzy
'''
from distutils.core import setup
import py2exe
setup(
options = {
"py2exe": {
"dll_excludes": ["MSVCP90.dll"],
}
},windows=[{"script": "main.py"}])
|
#!/usr/bin/python3
# -*- coding:utf-8 -*-
# Author: Hongying_Lee
# @Time: 2020/5/4
# @Name: findTheDifference
def findTheDifference(s,t):
dict_s = {}
for i in s:
if i not in dict_s:
dict_s[i] = 1
else:
dict_s[i] += 1
dict_t = {}
for j in t:
if j not in ... |
from model.amortization_schedule import AmortizationSchedule
from model.monthly_details import MonthlyDetails
class Calculator:
"""Mortgage calculation class. Calculates the monthly payment, interest, etc"""
def __init__(self):
self.last_value = 0
@staticmethod
def convert_rate_to_monthl... |
#Calculates pi using the Gregory-Leibniz series.
from math import *
from random import *
iterations = 10000
divisor=1.0
switch=False
pie=4/divisor
for x in range(0,iterations):
divisor+=2
if switch:
pie+=4/divisor
switch=False
else:
pie-=4/divisor
switch=True
print (pie)
print
print (pi)
p... |
from flask import Flask, jsonify, request
import pymongo
from flask_cors import CORS
from os import environ
from bson.json_util import dumps
import json
app = Flask(__name__)
client = pymongo.MongoClient("mongodb+srv://root:0NqePorN2WDm7xYc@cluster0.fvp4p.mongodb.net/iot?retryWrites=true&w=majority&ssl=true&ssl_cert_... |
from tornado.web import RequestHandler, asynchronous
from tornado.gen import coroutine
from tornado.concurrent import run_on_executor
from concurrent.futures import ThreadPoolExecutor
from tornado.httpclient import AsyncHTTPClient
import requests
import json
import os
from base.ansible_api import ANSRunner
import loggi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.