text stringlengths 38 1.54M |
|---|
#!/usr/bin/env python3
import click
import json
import os
import yaml
from drain import drain
def regex_from_yaml(f):
if not f:
return []
rs = yaml.load(f)
return [ r['regex'] for r in rs ]
def common_start(ctx, args):
pass
def common_end(ctx):
if ctx.obj['tree_file']:
ctx.o... |
from pathlib import Path
from os import listdir
from PIL import Image
import pytesseract
from pytesseract import image_to_string
def main():
"""
Testing image_to_string
"""
source = Path(r'sourceimg').absolute()
img_paths = [(source / img) for img in listdir(source)]
for img in img_paths:
... |
## Grant Gasser
## Leetcode 187 Repeated DNA Sequences
## 9/11/19
def findRepeatedDnaSequences(s):
"""
Finds 10-letter sequences that appear >= 2 times
Args:
s (string): string of chars 'A', 'T', 'C', 'G'
Returns:
two_or_more (list): list of the 10-letter subsequences
"""
# e... |
from django.test import TestCase
from django.template.loader import render_to_string
from django.core.urlresolvers import resolve
from django.http import HttpRequest
from lists.models import Item,List
from lists.views import home_page
import re
class HomePageTest(TestCase):
@staticmethod
def remo... |
# -*- coding: utf-8 -*-from kivy.uix.slider import Slider
from kivy.uix.textinput import TextInput
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.stacklayout import StackLayout
from kivy.uix.button import Button
from kivy.uix.togglebutton import ToggleButton
from kiv... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('malware_toolkit', '0015_feature_functions'),
]
operations = [
migrations.RemoveField(
model_name='feature_functi... |
n=int(input())
fib=[0,1]
if n<2:
print(fib[n])
else:
for i in range(2,n+1):
fib.append(fib[i - 1] + fib[i - 2])
print(fib[n])
|
# -*- coding: utf-8 -*-
# Copyright (c) 2015, Nicolas VERDIER (contact@n1nj4.eu)
# Pupy is under the BSD 3-Clause license. see the LICENSE file at the root of the project for the detailed licence terms
""" abstraction layer over rpyc streams to handle different transports and integrate obfsproxy pluggable transports ""... |
"""
n! means n × (n − 1) × ... × 3 × 2 × 1
For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
Find the sum of the digits in the number 100!
"""
import math
temp = str(format(math.factorial(100))) #removes scientific notation
sum = 0
for... |
#!/usr/bin/env python
# coding: utf-8
import pandas
import psycopg2
from configparser import ConfigParser
import numpy
path = 'C:/Users/tonyr/Desktop/Self Education/Production Files/apple_health_export/'
import os
prodfiles = 'C:/Users/tonyr/desktop/Self Education/Production Files/'
os.chdir(prodfiles)
class data_a... |
import pygame
width = 640
height = 480
radius = 100
stroke = 1
pygame.init()
window = pygame.display.set_mode((width,height))
window.fill(pygame.Color(255,255,255))
while True:
pygame.draw.circle(window,
pygame.Color(255,0,0),
(width/2, height/2),
rad... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-10-15 15:19
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('workshop', '0001_initial'),
]
operations = [
... |
# 0 ~ 9 : ball or goal
# . : plane field
# # : object
# Returns: String[]
# column = x, row = y
import random
class RollingBalls:
def restorePattern(self, start, target):
## initial process
#
W = len(start[0])
H = len(start)
start = list(start)
target = list(target)
# make outrange wall
start.appen... |
import pprint
def run(world):
pp = pprint.PrettyPrinter(indent=4)
for dev in world:
print "===================="
print str(dev)
pp.pprint(world[dev])
|
import dataset
import matplotlib.pyplot as plt
import numpy as np
xs,ys = dataset.get_beans(100)
w = 0.1
plt.title("Siz-Toxicity Functon",fontsize=12)
plt.xlabel("Size")
plt.ylabel("Toxicity")
yPre = w * xs
plt.scatter(xs,ys)
plt.plot(xs,yPre)
print("修正前图像")
plt.show()
es = (ys-yPre)**2
sum_e = np.sum(es)
sum_e =... |
# -*- coding: utf-8 -*-
"""
Appication script for Advance Algorithmic trading
Created on Wed Nov 7 09:14:12 2018
@author: akira
This scripts simulates some bernouillis experiences and adjust it with the bayesian statistics
before printing as a char;
it does not require any parameter
"""
import numpy as np
from s... |
from django.shortcuts import render
from .models import Timesheet
def index(request):
latest_entry = Timesheet.objects.all()
context = {'latest_entry': latest_entry}
return render(request, 'timecardApp/index.html', context)
|
#链接:https://www.zhihu.com/question/60868436/answer/307219795
###对scrPath中250文件进行随机抽取175个,到datPath中
###
###
import random
import os
import shutil
def random_copyfile(srcPath,dstPath,lastpath,numfiles):
name_list=list(os.path.join(srcPath,name) for name in os.listdir(srcPath))
random_name_list=list(ran... |
color =input("Choose a color: ")
plural_noun =input("Choose a plural noun: ")
celebrity =input("Choose a celebrity: ")
print("Rose are " + color)
print(plural_noun + " are blue")
print("I love " + celebrity)
|
import torch
from torch.utils.data import Dataset
from torch import nn, optim
from torchsummary import summary
import torch.nn.functional as F
import data.flic_dataset as flic_dataset
import models.DeepNet as deepnet
import models.simplenet as simplenet
import models.residualNet as resnet
def evaluate(mode... |
import cProfile, pstats, random
import numpy as np
import Main.NumpyNN as NN
SIZE = [2, 3, 1]
ITER = 1
def func(array): return [array[0] ^ array[1]]
def getinp(x):
return np.array([random.choice([0, 1]) for _ in range(x)])
def test(size, iters, func):
nn = NN.NeuralNet(size)
tests = []
... |
# coding=utf-8
from pytest_bdd import (
scenario
)
@scenario('../features/dynamodb_recovery-pending_replication_count.feature',
'pending_replication_count - green')
def test_alarm_green():
pass
|
# author azure
# 1,老男孩好声音选秀大赛评委在打分的时候呢,
# 可以进行输入. 假设, 老男孩有10个评委.
# 让10个评委进行打分, 要求, 分
# 数必须大于5分, 小于10分
# # 1
# count = 1
# while count <=10:
# fen = int(input("请第%s号评委打分:" % count))
# if fen <=5 or fen >10:
# print("你打的分")
# continue
# else:
# print("第%s评委打的是:%s "%(count,fen))
# ... |
import string
import random
total= string.ascii_letters + string.digits + string.punctuation
length=random.randint(8,13)
password="".join(random.sample(total,length))
print(password) |
import pandas as pd
import pickle
class Preprocessor():
def prepare_dataset(self, df):
return df[:3000]
def prepare_test_dataset(self, df):
idx = [124, 162, 174, 184, 185, 292, 460, 464, 521, 527, 574, 588, 625, 705, 763, 842, 854, 901, 902, 1006, 1043, 1050, 1102, 1274, 1326, 1381, 1396, 1404, 1409, 1619,... |
from datetime import datetime
def printClock():
now = datetime.now()
clock = "%02d:%02d" % (now.hour,now.minute)
print clock
return clock
|
from gql import gql, Client
from gql.transport.requests import RequestsHTTPTransport
sample_transport=RequestsHTTPTransport(
url='http://acad-overflow.herokuapp.com/v1/graphql',
use_json=True,
headers={
"Content-type": "application/json",
},
verify=False
)
client = Client(
retries=3,
... |
import roll
import char
import cli
class Attacks:
def __init__(self, templates=None):
self.templates = templates if templates else []
def add_template(self, template, character):
template = template.strip()
if not template:
return "Usage: attack <roll>"
try:
... |
# ROS Client Library for Python
import rclpy
# Handles the creation of nodes
from rclpy.node import Node
# Handles string messages
from std_msgs.msg import String
from userInterfaceManager import createUI
def msg_to_val(msg):
return msg.data;
# title, command
buttonsDict = {
"CT11": ("echo 'command send ... |
from autobahn.twisted.websocket import WebSocketClientFactory, \
WebSocketClientProtocol, connectWS
from twisted.python import log
from twisted.internet import reactor
#from pprint import pprint
import sys
import json
class CoinbaseExchangeClientProtocol(WebSocketClientProtocol):
def onOpen(self):
... |
from sgfmill import sgf
import argparse
import sys
from sgfmill import ascii_boards
from sgfmill import sgf_moves
import numpy as np
import os
import pickle
## Data format
# {
# "b":[][],
# "w":[][],
# "e":[][],
# "b_w_level":(),
# "isBlack": bool,
# "next":()
# }
def ConvertSgfToTrainingData(filename, all_da... |
from functools import update_wrapper
from weakref import WeakValueDictionary, WeakKeyDictionary
import torch
import torch.nn.functional as F
import pyro.distributions as dist
from pyro.poutine.messenger import Messenger
from pyro.poutine.runtime import effectful
__all__ = [
"LocalReparameterizationMessenger",
... |
import pandas as pd
import numpy as np
from selenium import webdriver
from time import sleep
username = []
skincond = []
recommend = []
datereview = []
review = []
rating = []
produk = []
merk = []
kategori = []
price = []
home = 'https://femaledaily.com/category/skincare'
path = 'chromedriver.exe'... |
# ライブラリの読み込み
import os.path as osp
import dotenv
from utils.init_dotenv import input_env_vals
def main():
# .env ファイル → 環境変数 (読み込む)
dotenv_path = osp.join(osp.dirname(__file__), '.env')
if not osp.isfile(dotenv_path):
# .env ファイルがないので、初期設定する。
input_env_vals(dotenv_path)
dotenv.load_dot... |
import sys
import re
inputfile1 = sys.argv[2]
table =[]
try:
file1=open(inputfile1, 'r')
data=[]
line=0
for line in file1:
for ch in line:
if ch!="\n":
data.append(int(ch))
except IOError:
sys.exit("\nError.\nFile name invalid.\n")
#represents ... |
import logging
import pytest
from page_request.pagerequest import ApiMethod
from data import canshu2
from mysql import mysqlDB
import allure
from common import get_path
path=get_path.get_login()
logging.basicConfig(level=logging.DEBUG)
casedate1=canshu2.ExcelData2().openexl(path,'Sheet5')
# casedate1[0][3]=array[... |
import h5py, cv2
import csv, time, os.path
import matplotlib.pyplot as plt
import numpy as np
from six.moves import cPickle
from sklearn import model_selection as ms
# function to process a single image
def processImage(prefix, size, gtReader, proc_type=None, is_lisa=False, class_match=None):
images = []
label... |
import math
t = int(raw_input())
for i in range(t):
n = int(raw_input())
result = 0
for j in range(1, (n / 2) + 1):
if n % j == 0:
result += j
print result |
# Author: Mathieu Blondel
# License: BSD
import numpy as np
from sklearn.base import ClassifierMixin
from sklearn.preprocessing import LabelBinarizer
from .base import BaseClassifier
from .dataset_fast import get_dataset
from .dual_cd_fast import _dual_cd
class LinearSVC(BaseClassifier, ClassifierMixin):
def ... |
import utils
from config import *
states = ['md','fl', 'co', 'mi', 'la', 'ga', 'or', 'il', 'wa', 'tx']
cities = {'md':'baltimore','fl':'miami','co':'denver','mi':'detroit','la':'new orleans','ga':'atlanta','or':'portland','il':'chicago','wa':'seattle','tx':'houston'}
distances = []
for state in states:
# ... |
import board
import displayio
import digitalio
from adafruit_st7735r import ST7735R
from adafruit_rgb_display import color565
import adafruit_rgb_display.st7735 as st7735
tft_cs = board.A2 #digitalio.DigitalInOut(board.A2)
tft_dc = board.A3 #digitalio.DigitalInOut(board.A3)
tft_rc = board.A4 #digitalio.DigitalInOut(bo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import random
import getopt
import sys
def gen_rand_nums(count, filename):
rand_seed = os.urandom(32)
random.seed(rand_seed)
with open(filename, "wb") as f:
for i in range(0, count):
tmp = str(random.randint(0, 13 * count)) + " "
f.write... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 19 14:59:35 2020
@author: evaferreira
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from imblearn.over_sampling import SMOTE
import warnings
warnings.filterwarnings("ignore")
df_list = [None]*15
df_test = [None]*15
for... |
import sys
import re
from pyspark import SparkContext
if __name__ == "__main__":
if len(sys.argv) < 4:
print >> sys.stderr, "spark-submit MainPy2.py [HDFS file]\n" \
+ "[searcher] [number to get] [Medium (Video, Book, etc.] [Genre (as gen:'War')] [Rating (as rat:4 for over 4 stars) or ... |
import socket
from fastapi import FastAPI
from redis import Redis
app = FastAPI()
redis = Redis(host="redis", port=6379)
@app.get("/")
def root():
visits = redis.incr("visits")
return socket.gethostname(), visits
|
from sklearn.decomposition import SparsePCA as sp
import numpy as np
import cv2
from matplotlib import pyplot as plt
from numpy import *
# from imtools import *
import os
from PIL import Image
import glob
#-----Pre-processing the images from the dataset
def get_image(filename):
img = cv2.imread(filename) #Read i... |
import sys
import serial
import threading
import time
s_task_interval = 1
def initUart(com='COM0', baudrate=19200):
ser = serial.Serial()
ser.port = com
ser.baudrate=baudrate
return ser
def uart_sent(ser,string):
if not ser.isOpen():
ser.open()
ser.write(string)
def uart_receive(ser,... |
import random
from typing import List
class Solution:
# quick select
# should we add insertion sort for short lists?
def findKthLargest(self, nums: List[int], k: int) -> int:
def partition(nums, l, r, pivot_idx):
pivot = nums[pivot_idx]
nums[r], nums[pivot_idx] = nums[pivot_i... |
import socket
# field computer
local_ip = "172.16.1.76"
local_port = 25565
buf_size = 1024
server_msg = "hellorobot!"
bytes_to_send = str.encode(server_msg)
udp_socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
udp_socket.bind((local_ip, local_port))
print(f"UDP server up and listening at {local... |
# -*- coding: utf-8 -*-
from Acquisition import aq_inner
from plone import api
from plone.app.content.browser.foldercontents import (FolderContentsTable
, FolderContentsBrowserView
, FolderContentsView)
class P... |
# EDA Back Pain
'''Ref: https://towardsdatascience.com/an-exploratory-data-analysis-on-lower-back-pain-6283d0b0123
https://www.kaggle.com/nasirislamsujan/exploratory-data-analysis-lower-back-pain?scriptVersionId=5589885'''
import numpy as np
import pandas as pd
import matplotlib.pyplot as plot
import seaborn ... |
"""
881. Boats to Save People
Medium
The i-th person has weight people[i], and each boat can carry a maximum weight of limit.
Each boat carries at most 2 people at the same time, provided the sum of the weight of those people is at most limit.
Return the minimum number of boats to carry every given person. (It is g... |
import os
from PyQt5 import QtWidgets, QtCore, QtGui
class ControlWidget(QtWidgets.QWidget):
run_state = QtCore.pyqtSignal(str, int, bool)
def __init__(self, axes):
super().__init__()
self.axes = axes
self.init_ui()
def init_ui(self):
layout = QtWidgets.QGridLayout()
... |
#!/usr/bin/python3
""" Test module for storing Square class test cases. """
import unittest
from models.base import Base
from models.square import Square
from unittest.mock import patch
from io import StringIO
from time import sleep
import os
print_on = 0 # <-- Set to 1 to activate printing of the tests.
class Test... |
# [ ] for x = 6, use range(x) to print the numbers 1 through 6
x = 7
m = 1
for num in (range(1, x+1)):
m = m*num
print(m)
|
import pandas as pd
import numpy as np
from datetime import datetime, date
def age_calc(born):
""""takes in the date of a customer and calulates the age"""
born = born.date()
today = date.today()
return today.year - born.year - ((today.month,
today.day) < (born.... |
# imports
import os
import io
import re
# import tokenize
# import json
# import numpy as np
import pandas as pd
import stringdist
def create_filenames_df(data_path, out_path, save_csv=False, given_class_company=None):
# create a pandas dataframe with the filenames in our dataset
df_files_dict = {
'r... |
# 숫자 8개를 입력받아 리스트에 넣음
data = list(map(int, input().split()))
# 1로 시작하는 경우
if data[0] == 1:
# 오름차순으로 정렬되어 있다면
if data == sorted(data):
print('ascending')
# 정렬되어 있지 않다면
else:
print('mixed')
# 8로 시작하는 경우
elif data[0] == 8:
# 내림차순으로 정렬되어 있다면
if data == sorted(data, reverse=True):
... |
import json
import logging
import paho.mqtt.client as mqtt
import re
LOG = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG)
class OpenstackMqtt(object):
def __init__(self, connection='firehose.openstack.org'):
self.client = mqtt.Client()
self.connection = connection
s... |
# @author Nayara Souza
# UFCG - Universidade Federal de Campina Grande
# AA - Basico
nk = input().split()
id = input().split()
n = int(nk[0])
k = int(nk[1])
for i in range(n):
if (i >= k):
break
k -= i
print(id[k-1]) |
class Solution:
def combinationSum4(self, nums: List[int], target: int) -> int:
nums.sort()
dp = [0 for i in range(target+1)]
dp[0]=1
for i in range(1, target+1):
for num in nums:
if num>i:
break
dp[i] += dp[i-num]
... |
import requests, json, logging
#API at https://hadoop.apache.org/docs/r2.6.0/hadoop-yarn/hadoop-yarn-site/WebServicesIntro.html
class YarnRestApi():
def __init__(self, hostname, port=8088):
self.hostname = hostname
self.port = port
#Returns dictionary of parsed JSON data
def getRequest(self, path, pa... |
import streamlit as st
from datetime import datetime
import database as db
import pandas as pd
# function to verify department id
def verify_department_id(department_id):
verify = False
conn, c = db.connection()
with conn:
c.execute(
"""
SELECT id
FROM department... |
from flask import Flask
from flask_wtf import FlaskForm
from flask import flash, url_for, redirect, render_template, request, escape
from wtforms import Form, BooleanField, StringField, PasswordField, validators
from flask_wtf.csrf import CSRFProtect
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Should be moved to stir_tools
import os
import commands
import sys
import shutil
from utils import apple
from utils import spm_tools as spm
class Phantom_Preparation(object):
def __init__(self, spm_run, act_map, att_map, scanner, scanner_target_size, pet_image=Fals... |
import django_filters
from django_filters import DateFilter, CharFilter
from .models import *
class ContentFilter(django_filters.FilterSet):
# start_date = DateFilter(field_name='updated', lookup_expr='gte')
# end_date = DateFilter(field_name='updated', lookup_expr='lte')
note = CharFilter(field_n... |
#Cal Hasie
#11/5/12
#Lab 9- 9.8
#This program will capitalize the beginning of the users sentences.
def main():
#Takes in the users sentences.
user = input("Please enter the sentences you wish: ")
#Splits apart each sentence
sentence_list = user.split('.')
#Prints the list of sentences
prin... |
import zipfile
import os
import argparse
from oauth2client import file, client, tools
from httplib2 import Http
from googleapiclient.discovery import build
import io
import httplib2
from pathlib import Path
import re
import webbrowser
# ================================================
# Create a temporary zip file
# ... |
# -*- coding: utf-8 -*-
# Copyright (C) 2004-2013 Mag. Christian Tanzer. All rights reserved
# Glasauergasse 32, A--1130 Wien, Austria. tanzer@swing.co.at
# ****************************************************************************
#
# This module is licensed under the terms of the BSD 3-Clause License
# <http://www.... |
import math
def main():
N = int(input())
TA = [
list(map(int, input().split()))
for _ in range(N)
]
# ans = f(N, TA)
ans = editorial(N, TA)
print(ans)
def test_ceil_mod():
"""https://stackoverflow.com/questions/14822184/is-there-a-ceiling-equivalent-of-operator-in-python... |
from argparse import ArgumentParser, SUPPRESS
from invisibleroads_macros.disk import link_path
from invisibleroads_macros.iterable import sort_dictionary
from invisibleroads_macros.text import unicode_safely
from six.moves import getcwd
from sys import argv
from . import ToolScript, corral_arguments, run_script
from .... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/10/31 9:37 AM
# @Author : Ganodermaking
from openpyxl import load_workbook
class Excel:
def __init__(self, filename, sheet_name):
self.filename = filename
self.wb = load_workbook(self.filename)
self.ws = self.wb[sheet_name]
... |
from commitizen import factory, out
from commitizen.config import BaseConfig
class Example:
"""Show an example so people understands the rules."""
def __init__(self, config: BaseConfig, *args):
self.config: BaseConfig = config
self.cz = factory.commiter_factory(self.config)
def __call__(... |
'''
Created on Nov 10, 2015
@author: Jonathan
'''
def emailsLargest(courses):
sizes = {}
for course in sorted(courses):
name = course.split(":")[0]
if name not in sizes:
sizes[name] = 0
else:
sizes[name] += 1
largest = max(sorted(sizes), key = sizes.get)
... |
# -*- code: utf-8 -*-
class UninitializedConfiguration(Exception):
pass
class MongoDBException(Exception):
pass
|
from typing import List
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
i = 0
while i < len(s) // 2:
s[i], s[len(s) - i - 1] = s[len(s) - i - 1], s[i]
i += 1
sol = Solution()... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import json
import codecs
import sys
import pandas as pd
import numpy as np
import requests
from tqdm import tqdm
import random
import csv
from html_processor import normalize_text
def select_random_tagged_works(n=75):
random.se... |
#!/usr/bin/python3
import multiprocessing
import multiprocessing.connection
import re
import subprocess
import sys
import time
# launch an agent in it's own process
def launch_agent(id, v):
p = subprocess.run(["./bin/sudoku_agent", str(id), v])
# launch 81 agents in parallel
def launch_agents(starting_values):
... |
import os
import requests
import operator
import re
import json
from datetime import datetime, timedelta
from flask import Flask, render_template, request, jsonify
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
CORS(app)
app.config.from_object(os.environ['APP_SETTINGS'])
app.c... |
class cat:
def __init__(self):
print("cat被创建了")
def eat(self):
print("小猫爱吃鱼")
c = cat() # 实例化对象的时候,init方法自动调用
c.eat() # 必须明确的通过代码调用普通方法 |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'DetailsView.ui'
#
# Created: Wed Apr 25 11:24:59 2018
# by: pyside-uic 0.2.15 running on PySide 1.2.4
#
# WARNING! All changes made in this file will be lost!
from PySide import QtCore, QtGui
class Ui_DetailsView(object):
def setu... |
Given an integer array nums, return the number of range sums that lie in [lower, upper] inclusive.
Range sum S(i, j) is defined as the sum of the elements in nums between indices i and j (i ≤ j), inclusive.
Note:
A naive algorithm of O(n2) is trivial. You MUST do better than that.
Example:
Given nums = [-2, 5, -1], l... |
import graphene
from schema.event import CreateEvent, UpdateEvent, DeleteEvent
class Mutation(graphene.ObjectType):
create_event = CreateEvent.Field()
update_event = UpdateEvent.Field()
delete_event = DeleteEvent.Field()
|
# -*- coding: utf-8 -*-
# snapshottest: v1 - https://goo.gl/zC4yUc
from __future__ import unicode_literals
from snapshottest import GenericRepr, Snapshot
snapshots = Snapshot()
snapshots['TestCase01CreateTransitionAPITestCase::test_case status'] = 200
snapshots['TestCase01CreateTransitionAPITestCase::test_case bod... |
#! /usr/bin/env python
# coding=utf-8
#================================================================
# Copyright (C) 2018 * Ltd. All rights reserved.
#
# Editor : VIM
# File name : test.py
# Author : YunYang1994
# Created date: 2018-12-20 11:58:21
# Description :
#
#==========================... |
# -*- coding: utf-8 -*-
from Classes import Job
def locate_min(sum_list):
min_indexes = []
smallest = min(sum_list)
for index, element in enumerate(sum_list):
if smallest == element: # check if this element is the minimum_value
min_indexes.append(index) # add the index to the list if... |
import sys
from subprocess import run
from path import getcwd
def get_dependencies(file_name):
out = []
output = run(
[
"ldd",
file_name,
],
capture_output=True,
)
# raw ldd output
dependencies = output.stdout.decode().split("\n")
# only last colu... |
class Solution(object):
def backspaceCompare(self, S, T):
"""
:type S: str
:type T: str
:rtype: bool
"""
m, n = len(S), len(T)
ptr1, ptr2 = m - 1, n - 1
cnt1, cnt2 = 0, 0
while True:
while ptr1 >= 0 and (S[ptr1] == '#' or cnt1):
... |
from socket import gethostbyname, gethostname, socket, AF_INET, SOCK_STREAM
from time import ctime, time
from HiLens.utils import set_temperature_and_humidity, get_command
HOST = ''
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST, PORT)
def start_listen():
print("start listen !!!!!!!!!!!!!!!!!!!!!!")
myname = getho... |
import datetime
import sqlalchemy
from flask_login import UserMixin
from sqlalchemy import orm
from werkzeug.security import generate_password_hash, check_password_hash
from sqlalchemy_serializer import SerializerMixin
from data.db_session import SqlAlchemyBase
class Direction(SqlAlchemyBase, UserMixin, SerializerMi... |
# Chat server
import socket, select
# Function to broadcast chat messages to all connected clients
def broadcast_data(sender, message):
byte_message = bytes(message, 'UTF-8')
# print("broadcasting", len(connection_list))
# Do not send the message to master socket
# and the client who has send us the ... |
from ._CBUS import *
from ._Kylin import *
from ._PosCalib import *
from ._Sonar import *
from ._VirtualRC import *
from ._ZGyro import *
|
# 3.4
guests = ['John', 'Sam', 'Tim']
print(f"{guests[0]}, you are invited for dinner")
print(f"{guests[1]}, you are invited for dinner")
print(f"{guests[2]}, you are invited for dinner")
#3.5
guests = ['John', 'Sam', 'Tim']
print(f"{guests[0]} can't make it")
guests[0] = "Michael"
print(f"{guests[0]}, you are invited... |
Import("*")
import glob, os, SCons
import platform as p
CCFLAGS=['-Wall','-fPIC']
LINKFLAGS=[]
CPPDEFINES=[]
OPTIMIZE=['-O3', '-fno-strict-aliasing']
buildtype = ARGUMENTS.get('type', 'default')
if buildtype == "debug":
CCFLAGS.append('-g')
LINKFLAGS.append('-g')
CCFLAGS.append('-DDEBUG=1')
elif ... |
from peewee import *
from model.account import Account
from model.base_entity import BaseEntity
class Folder(BaseEntity):
name = TextField()
parent = ForeignKeyField('self', null=True, related_name='folders')
account = ForeignKeyField(Account, related_name="folders")
with_emails = BooleanField(defaul... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Author :AmosWu
# Date :2019/1/26
# Features : Print all daffodils number on the screen
for i in range(100,1000):
a = i%10
b = int(i/100)
c = (int(i/10))%10
if i == a**3+b**3+c**3:
print('%d'%i) |
"""
Example 3-1
===========
Finding Factorial with Recusion
Author: Adnan Umer <u.adnan@outlook.com>
"""
def fact(n):
"""
Finds Factorial of given number using recusion
"""
if n <= 1: # factorial of 1 is 1
return 1
else:
# factorial of n = n x [factorial of n -1]
return n ... |
import pytest
from hls2dash.lib import MPDRepresentation
def test_segment_duration_precision():
obj = MPDRepresentation.Segment(4.64, False)
obj.setTimescale(48000)
assert obj.asXML() == ' <S d="222720" />\n'
obj2 = MPDRepresentation.Segment(4.63999375, False)
obj2.setTimescale(48000)
... |
#!/usr/bin/env python3
'''
Author: Alexander Roth
Date: 2016-03-13
'''
import sys
def main(args):
in_file = args[1]
line_generator = read_file(in_file)
try:
while True:
line = next(line_generator)
first_set, second_set = gen_sets(line)
result = check_sets(f... |
from hx3dtoolkit.config import config
import shutil
import os
class RemoveDirectoryCommand:
def __init__(self, directory, **options):
self.directory = directory
self.options = options
def execute(self):
if os.path.exists(self.directory):
if config.debug_mode:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.