text stringlengths 8 6.05M |
|---|
# Generated by Django 2.1.9 on 2019-08-05 05:41
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('whiskydatabase', '0017_auto_20190621_1451'),
]
operations = [
migrations.AlterField(
model_name='comment',
name='rat... |
"""
Queue based upon array
用数组实现的队列
Author: Wenru
"""
from typing import Optional
class ArrayQueue:
def __init__(self, capacity: int):
self._items = []
self._capacity = capacity
self._head = 0
self._tail = 0
def enqueue(self, item: str) -> bool:
if se... |
def solution(s):
# 각 케이스별로 나눌 수 있게 문자열에 불필요한 문자 제거
a = s.replace('{{', '')
c = a.replace('}}', '')
d = c.replace(',', ' ')
e = d.split('} {')
# 중복 값이 없다는 조건은 set을 활용하라는 의미로 받아드림
# str 값이 담긴 e 리스트를 int형 set으로 변환 (- 연산을 위해서 set 변환)
SetList = [set(map(int, i.split())) for i in e]
SetLi... |
# -*- coding: iso-8859-1 -*-
import eiscp
import logging
from kalliope.core.NeuronModule import NeuronModule, MissingParameterException
logging.basicConfig()
logger = logging.getLogger("kalliope")
class Onkyo(NeuronModule):
def __init__(self, **kwargs):
super(Onkyo, self).__init__(**kwargs)
# the args... |
from html.parser import HTMLParser
import requests
import sys
from colorama import init, Fore, Back, Style
class parse_html(HTMLParser):
def __init__(self):
self.final_brow = "---Dracux Browser--- "
self.print_data = False
HTMLParser.__init__(self)
def handle_starttag(self, t... |
from .day02 import part1, part2 |
from matplotlib.animation import FuncAnimation
from scipy.ndimage import convolve
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import perl
import sys
def interpolation(noise, screen_size, res_size):
tr = np.sqrt(res_size).astype('int64')
data = noise[:res_size].reshape(tr, tr)
... |
s1 = 'Spicy Jalape\u00f1o'
s2 = 'Spicy Jalapen\u0303o'
print s1.decode("utf-8")
print s1
print s2
print s1 == s2
print len(s1)
print len(s2)
import unicodedata
t1 = unicodedata.normalize('NFC', s1)
t2 = unicodedata.normalize('NFC', s2)
print t1 == t2
t3 = unicodedata.normalize('NFD', s1)
t4 = unicodedata.normali... |
import math
import unittest
import katas.kyu_7.radians_to_degrees
class RadiansToDegreesTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(math.degrees(math.pi), '180deg')
def test_equals_2(self):
self.assertEqual(math.radians(180), '3.14rad')
|
import random
random.seed()
class Tournament(object):
""" The crossover function requires two parents to be selected from the population pool. The Tournament class is used to do this.
Two individuals are selected from the population pool and a random number in [0, 1] is chosen. If this number is less than the... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os, sys, time
from datetime import date
from optparse import OptionParser, Option
# Complete hack.
Option.ALWAYS_TYPED_ACTIONS += ('callback',)
CONFIG = '/etc/bind/named.conf.slave'
#CONFIG = './named.conf.slave'
NOW = date.today()
DOMAINS_FOLDER = '/etc/bind/slave... |
#!/usr/bin/env python3
"""
Analysis class to read a ROOT TTree of MC track information
and do jet-finding, and save response histograms.
Author: James Mulligan (james.mulligan@berkeley.edu)
"""
from __future__ import print_function
# General
import os
import sys
import argparse
import time
# Data analysis ... |
# Copyright (c) 2021 kamyu. All rights reserved.
#
# Google Code Jam 2021 Round 2 - Problem D. Retiling
# https://codingcompetitions.withgoogle.com/codejam/round/0000000000435915/00000000007dc2de
#
# Time: O((R * C)^3)
# Space: O((R * C)^2)
#
# Template translated from:
# https://github.com/kth-competitive-programmin... |
from django.shortcuts import render
from django.http import HttpResponse
from website import forms
from website.models import Customer, Order, Product
from django.contrib.auth.models import User
def index(request):
context = dict()
if ("userID" in request.session) and (request.session["userID"] != "anon"):
... |
#
# cogs/info/core.py
#
# mawabot - Maware's selfbot
# Copyright (c) 2017 Ma-wa-re, Ammon Smith
#
# mawabot is available free of charge under the terms of the MIT
# License. You are free to redistribute and/or modify it under those
# terms. It is distributed in the hopes that it will be useful, but
# WITHOUT ANY WARRAN... |
import json
def openfile(l):#import data
a=open(l, 'r')
b=json.loads(open(l).read())[0]
x=b["universe_name"]
y=b['rewards']
z=b['portals']
return x,y,z
class Universe(object):
def __init__(self,name=str(),rewards=(),portals=()):
self.name=name
self.rewards=reward... |
t = int(input())
while t > 0:
n = int(input())
s = str(input())
if s[0] == '2' and s[-1] == '0' and s[-2] == '2' and s[-3] == '0':
print("YES")
elif s[0] == '2' and s[1] == '0' and s[2] == '2' and s[-1] == '0':
print("YES")
elif s[0] == '2' and s[1] == '0' and s[2] == '2' and... |
values = {1:1, 2:5, 3:8, 4:9, 5:10, 6:17, 7:17, 8:20, 9:24, 10:30}
previous_values = []
def rod_cut(rod_length):
current_max = 0
previous_values.append(0)
for length in range(1, rod_length + 1):
for possible_cut in values:
if possible_cut <= length:
current_max = max(current_max, values[possible_cut] +
... |
#
# @lc app=leetcode.cn id=34 lang=python3
#
# [34] 在排序数组中查找元素的第一个和最后一个位置
#
# @lc code=start
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
left, right = self.binarySearchLeft(nums, target), self.binarySearchRight(nums, target)
return [left, right] if le... |
import ha_engine.ha_infra as common
import habase_helper as helper
LOG = common.ha_logging(__name__)
class BaseMonitor(object):
def __init__(self, input_args):
self.ha_report = []
self.input_args = {}
if input_args:
self.set_input_arguments(input_args)
def set_input_argum... |
"""
insertion sort implementaion
"""
def insertion_sort(x):
if len(x) < 2:
return
for i in range(1, len(x)):
for j in range(i, 0, -1):
if x[j] < x[j - 1]:
x[j], x[j - 1] = x[j - 1], x[j]
|
from .aws import AutoScaling
from .formatter import FormatReport
from .sender import SendReport
def stateless_ha(asg):
return 'StatelessHa' in asg['Tags']
def not_enough_subnets(asg):
return len(asg['VPCZoneIdentifier'].split(',')) < 2
def enough_subnets(asg):
return len(asg['VPCZoneIdentifier'].split... |
import binascii
import enum
import io
ENDIAN = "little"
class Action(enum.IntEnum):
SourceRead = 0
TargetRead = 1
SourceCopy = 2
TargetCopy = 3
def convert_uint(b: bytes):
return int.from_bytes(b, ENDIAN, signed=False)
def read_number_io(b: io.BytesIO) -> int:
data, shift = 0, 1
# th... |
import random
import math
Menu = True
gameStart = False
instructionStart = False
aboutStart = False
global selection
""" This is the "about" page; essentially a credits page """
def About():
leaveAbout = False
while leaveAbout == False:
print('u uglee')
leaveAbout = input('type anything to leave l... |
import setuptools
from setuptools import setup, find_packages
from setuptools.command.install import install
import os
from os.path import isfile, isdir, join, dirname
class CustomInstallCommand(install):
"""Customized setuptools install command."""
def run(self):
from setuptools.command.install import... |
# set去重
# 对每个元素n 判断数组中是否有n + k 或 n - k
class Solution:
def findPairs(self, nums: List[int], k: int) -> int:
visited, res = set(), set()
for num in nums:
if num - k in visited:
res.add(num - k)
if num + k in visited:
res.add(num)
vi... |
import json
import os
import secrets
from functools import lru_cache
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DATA_DIR = os.path.join(BASE_DIR, 'data')
TEMPLATES = os.listdir(os.path.join(BASE_DIR, 'html'))
@lru_cache(maxsize=10)
def autodiscover():
"""
Autodiscover files in the HTML folder of... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from pylib.timer import *
from pylib.utils import *
|
class Student:
def __init__(self, name): #constructor
self.name = name
self.subscores = []
def average(self):
return sum(self.subscores)/len(self.subscores)
stu_1 = Student("Lehan")
stu_1.subscores.extend([45,55,79])
print(f"{stu_1.average():.2f}")
|
import os
import pymongo
from tqdm import tqdm
from collections import OrderedDict
from src.tokenizer import Tokenizer
from src.indexer import read_directory
from src.parser import parse
import config
import pprint
import json
Index = dict()
Header = dict()
pp = pprint.PrettyPrinter()
def build_index():
global ... |
from typing import Any
from tqdm.auto import tqdm
from parseridge.parser.training.callbacks.base_callback import Callback
class ProgressBarCallback(Callback):
"""
Shows a progress bar during training.
"""
def __init__(self, moving_average: int = 64):
self._pbar = None
self.template ... |
class Queue(object):
def __init__(self):
self.queue = []
def isEmpty(self):
return self.queue == []
def enqueue(self, data):
return self.queue.insert(0, data)
def dequeue(self, data):
return self.queue.append(data)
def size(slef):
return len(self.queue)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import base64
import codecs
import errno
import logging
import os
import platform
import sys
from liveproxy import __version__ as liveproxy_version
from requests import __version__ as requests_version
from streamlink import __version__ as streamlink_version
from .argparse... |
#Enter 2 numbers, to show result with and without decimal places.
a = int(raw_input())
b = int(raw_input())
print (a/b)
print float (a)/b
#Examples of operators.
#Source https://www.programiz.com/python-programming/operators
x = 15
y = 4
# Output: x + y = 19
print('x + y =',x+y)
# Output: x - y = 11
print('x - y ... |
import numpy as np
import scipy.io
from numpy import genfromtxt
import os
import cv2
from sklearn import metrics
########################################### Vertebra segmentation results
IMG_SIZE_X = 128
IMG_SIZE_Y = 256
# function to generate datasets with segmentation maps of entire spinal column
def create_roi_dat... |
#-*- coding: UTF-8 -*-
# import scrapy
#
#
# class QuotesSpider(scrapy.Spider):
# name = "bookLink_test"
#
# def start_requests(self):
# urls = [
# 'https://book.douban.com/tag/?view=type&icn=index-sorttags-hot#%E6%96%87%E5%AD%A6',
# ]
# for url in urls:
# yield... |
#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# 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 o... |
import numpy
import pandas as pd
import keras
from keras.models import Sequential
from keras.layers import Dense,Activation,Conv2D,MaxPool2D,Flatten,Dropout
from keras.utils import np_utils
from keras.models import load_model
import numpy as np
import os
import requests
from flask import Flask
app = Flask(__name__)... |
from typing import Dict, List
from Controller.Utilities.GameStateInterface import GameStateSecondary
class GameState(GameStateSecondary):
def __init__(self, game_dict: [str, str or int] = {}):
self.game_dict = game_dict
self.game_dict_expected_keys = ["turnInfo", "timers", "gameObjects", "players"... |
# import numpy as np
# import scipy.optimize
# import matplotlib.pyplot as plt
# def sigmoid(x):
# g = 1. / (1 + np.e ** (-1 * x))
# g = np.reshape(g, [len(g),])
# return g
# def costFunction(theta, x, y):
# h = sigmoid(x.dot(theta))
# m = len(y)
# J = 1. / m * -1 * (np.transpose(y).dot(np.log... |
#!/bin/python
# delete-dssstore.py
#
# A simple python script to delete .DS_Store files
#
# 3zbumban
# 2019
import os
import sys
import argparse
import time
from hurry.filesize import size
CWD = os.getcwd()
to_delete = ".DS_Store"
argumetnparser = argparse.ArgumentParser(description="Usage: delete-dsstore.py -p/--... |
import numpy as np
import tensorflow as tf
from app.ds.graph.preprocessed_graph import Graph
from app.model.params import SparseModelParams
from app.utils.constant import TRAIN, LABELS, FEATURES, SUPPORTS, MASK, VALIDATION, TEST, DROPOUT, GCN, \
FF, GCN_POLY
class DataPipeline():
'''Class for managing the da... |
from enum import Enum
# Enumerator to store color value
class Color(Enum):
RED = 1
BLUE = 2
YELLOW = 3
GREEN = 4
# Greater than and less than compare the Color Enumerator value
def __gt__(self, other):
if other == None:
return False
return self.value > other.value
... |
import datetime
import ftplib
from prettytable import PrettyTable
class ExtraccionFtp:
def __init__(self,host,usuario,clave):
self.host = host
self.usuario = usuario
self.clave = clave
self.ftp = ftplib.FTP(self.host)
def login(self):
try:
self.ftp.log... |
#!/usr/bin/python
def divisors(n):
count = 0
for j in range(int(n / 2), 0, -1):
if n % j == 0:
count += j
if count > n:
return True
return count > n
sum = 0
arr = []
for i in range(2, 28124):
if divisors(i):
arr.append(i)
d = {}
for i in range(... |
from albus import fields
def step_0001(m):
m.create(
'Author', [
('name', fields.StringField()),
('initials', fields.StringField(size=fields.TINY)),
('rank', fields.IntegerField()),
('birthdate', fields.DateTimeField()),
]
)
m.create(
... |
# Generated by Django 3.1.7 on 2021-03-07 04:03
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('api', '0015_auto_20210307_0134'),
]
operations = [
migrations.RemoveField(
model_name='post',
... |
from class_Student import Student
# Instantiate class with 5 students
student0 = Student("Alan", 29, 4.0)
student1 = Student("Benji", 27, 2.0)
student2 = Student("Dave", 29, 3.4)
student3 = Student("Dave", 29, 3.4)
student4 = Student("Edgar", 23, 3.1)
# Create test array of 5 students
student_array = [student0, stude... |
/Users/daniel/anaconda/lib/python3.6/__future__.py |
import cherrypy, os, urllib, pickle
from n6_searching_images import imagesearch
from n6_searching_images.vocabulary import Vocabulary
import random
class SearchDemo(object):
def __init__(self):
# load list of images
with open('ukbench_imlist.pkl', 'rb') as f:
self.imlist = pickle.load... |
# 27.Merge the Tools!
# 28.itertools.product()
# > import itertools
# > 순열: permutations(list, 선택 개수), 조합: combinations(list, 선택 개수)
# > 여러 리스트 간의 곱집합(데카르트의 곱): product(list, list, ....), *list 넣으면 리스트 안의 문자열 하나하나에 대해서도 모든 경우의 수를 구함
# > product(list, repeat=2) == product(list, list) repeat 사용이 가능한데, repeat은 인자에 대한 반복임... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param A : head node of linked list
# @return an integer
def lPalin(self, A):
if not A.next:
return 1
vals = [A.val]
c... |
import subprocess, os
images = os.listdir('./img')
#qss = os.listdir('./qss')
f = open('resource.qrc', 'w+')
f.write(u'<!DOCTYPE RCC>\n<RCC version="1.0">\n<qresource>\n')
for item in images:
f.write(u'<file alias="img/'+ item +'">img/'+ item +'</file>\n')
#f.write(u'<file alias="icons/'+ item +'">icons/'+ item ... |
import unittest
from katas.beta.lightswitches import lightswitch
class LightswitchTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(lightswitch(3), 1)
def test_equals_2(self):
self.assertEqual(lightswitch(4), 2)
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2019-11-09 06:31
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateM... |
import forca
import adivinhacao
print(14*"*")
print("Bem vindo a minha biblioteca de jogos!")
print(14*"*")
print("""----Escolha o jogo----
(1) Forca (2) Advinhação""")
escolha_jogo = int(input("Escolha: "))
if (escolha_jogo == 1):
forca.jogar()
elif(escolha_jogo == 2):
adivinhacao.jogar() |
import datetime
import time
from sawtooth_sdk.processor.handler import TransactionHandler
from sawtooth_sdk.processor.exceptions import InvalidTransaction
SYNC_TOLERANCE = 60 * 5
def is_active(object):
return max(object.infos, key=lambda obj: obj.timestamp).active
def validate_timestamp(timestamp):
"""Val... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import textwrap
import pytest
from pants.backend.go import target_type_rules
from pants.backend.go.goals.test import GoTestFieldSet, GoTestRequest
fro... |
# This file is part of beets.
# Copyright 2016, Adrian Sampson.
#
# 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 limitation the rights to use, copy, ... |
# Generated by Django 2.1.3 on 2018-11-21 06:56
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0010_auto_20181121_1209'),
]
operations = [
migrations.AddField(
model_name='teacher',
name='educations'... |
import PySimpleGUI as sg, sys
import pandas as pd
df = pd.read_csv(r"C:\Users\avivy\PycharmProjects\pythonProject\pysimplegui\test_for_main.csv", header=None)
first_col = df.iloc[:, 0].values
a = "\n".join(first_col)
print (a)
form = sg.FlexForm("Dynamic Combo")
col = [[sg.Checkbox(f'{i}', enable_events=True, font=... |
from unittest import TestCase
import phi
from phi import math
from phi.field import CenteredGrid
from phi.geom import Box
from phiml.math import channel, tensor
from phiml.backend import Backend
def simulate_hit(pos, height, vel, angle, gravity=1.):
vel_x, vel_y = math.cos(angle) * vel, math.sin(angle) * vel
... |
#load_image.py
#Shorthand to load image from assets directory
import os, sys, pygame
def load_image(name):
fullname = os.path.join('assets', name)
try:
image = pygame.image.load(fullname)
except pygame.error, message:
print 'Cannot load image:', name
raise SystemExit, message
... |
import sympy
def error(f, err_vars=None):
from sympy import Symbol, latex
s = 0
latex_names = dict()
if err_vars == None:
err_vars = f.free_symbols
for v in err_vars:
err = Symbol('latex_std_' + v.name)
s += f.diff(v)**2 * err**2
latex_names[err] = '\\sigma_{' + la... |
#!/usr/bin/env python
import rospy
from std_msgs.msg import Int8
if __name__ == "__main__":
rospy.init_node("led7seg_talker")
pub = rospy.Publisher("led7seg", Int8, queue_size=10)
i = 0
rate = rospy.Rate(1)
while not rospy.is_shutdown():
rospy.loginfo("echo "+str(i))
pub.publish(i)
i += 1
if i > 9:
i ... |
# created by Ryan Spies
# 3/3/2015
# Python 2.7
# Description: parse through a individual CONAGUA csv files to cardfile
# Features: dms to dd conversion
# Plot features: datelocator for axis, subplots, tick label modifications
import os
import sys
import datetime as dt
from datetime import datetime
from da... |
# Copyright (C) 2019 Verizon. 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 required by applicable law ... |
from avatar import *
class Bike(Avatar):
def __init__(self):
self.name = "bike"
def action(self):
pass
|
import pandas as pd
import numpy as np
"""
Function which convert the label of subconcepts into core concepts labels
"""
def convert_sub_concepts_to_core(ontology, abstract_concepts_file):
# open files
concepts = pd.read_csv(abstract_concepts_file, sep=",", header=0).values
# create dictionnary of... |
import requests
import time
from datetime import datetime
import json, io, os
def writefileheaders(filename, json_data):
with io.open(filename, 'w', encoding='utf-8') as f:
for bolt in range(len(data["bolts"])):
f.write(unicode("boltId, emitted, executeLatency(s), processLatency(s), "))
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, sys , argparse
import glob
import numpy as np
import pydicom
from shutil import copyfile, rmtree, move
def get_arguments():
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description="",
epilo... |
# Generated by Django 2.2.3 on 2020-01-15 09:49
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("robbit", "0006_auto_20190718_1221")]
operations = [
migrations.AlterField(
model_name="tile", name="x", field=models.BigIntegerField(db_index... |
def zebulansNightmare(arg):
return ''.join([x.capitalize() if c != 0 else x for c,x in enumerate(arg.split('_'))])
'''
Zebulan has worked hard to write all his python code in strict compliance to PEP8
rules. In this kata, you are a mischevious hacker that has set out to sabatoge all his good code.
Your job is to ... |
from PyQt5 import QtCore,QtWidgets
from PyQt5.QtWidgets import QApplication, QWidget
import sys
import requests
from lxml import etree
import re
from concurrent.futures import ThreadPoolExecutor
import threading
import csv
import os
Tlock = threading.Lock()
class Ui_Form(object):
def setupUi(self, For... |
from common.run_method import RunMethod
import allure
@allure.step("极运营/系统设置/基础参数设置/线索来源/查询")
def dict_studentSource_query_post(params=None, body=None, header=None, return_json=True, **kwargs):
'''
:param: url地址后面的参数
:body: 请求体
:return_json: 是否返回json格式的响应(默认是)
:header: 请求的header
:host: 请求的环境
... |
import numpy as np # importing the libraries
import os
from gwpy.table import EventTable
from gwpy.segments import DataQualityDict
from trigfind import find_trigger_files
from gwpy.segments import DataQualityFlag
from gwpy.time import tconvert
import datetime
from gwpy.time import to_gps
from gwpy.time import from_gps
... |
#!/usr/bin/env python3
#Suin Kim
#CS265-005
#Assignment 2
import sys
import os
import stat
import re
#checks arguments provided
def checkArg():
if (len(sys.argv) == 1): #if no argument provided, use current directory
return os.getcwd()
elif (len(sys.argv) == 2):
if (os.path.isdir(sys.argv[1])): #if valid dire... |
#!/usr/bin/env python2
import json
import re
import sqlite3
import os
import pprint
pp = pprint.PrettyPrinter(indent=4)
conn = sqlite3.connect('picasadb.sqlite')
cur = conn.cursor()
# Make some fresh tables using executescript()
cur.executescript('''
DROP TABLE IF EXISTS Albums;
DROP TABLE IF EXISTS Contacts;
DROP T... |
# Generated by Django 2.1 on 2018-09-24 06:31
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('mainapp', '0012_auto_20180924_0625'),
]
operations = [
migrations.RemoveField(
model_name='category',
name='image',
),... |
import os, glob
import numpy as np
from ..algorithms.utils import get_file_manager
from ..algorithms.clustered_writes import *
from ..exp_utils import create_empty_dir
def test_get_entity_sizes():
# in C order
bytes_per_voxel = 1
R = (10,9,10)
cs = (5,3,2)
partition = (2,3,5)
bs, brs, bss = g... |
#!/usr/bin/python
import sys
if __name__ == "__main__":
#full_msg = sys.stdin.read()
f = open("parseout.txt",'w')
f.write("SUCCESS")
f.close()
|
import os, sys
WORKING_DIR = getattr(sys, '_MEIPASS', os.getcwd())
APPLICATION_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), "js_app")
NODE_MODULES = os.path.join(APPLICATION_DIR, "node_modules")
PACKAGE_JSON = os.path.join(APPLICATION_DIR, "package.json")
ELECTRON_DIR = os.path.join(WORKING_DIR, "e... |
import os
import threading
import time
import dash_bootstrap_components as dbc
from dash import Dash, html
from rubicon_ml import __version__ as rubicon_ml_version
_next_available_port = 8050
class VizBase:
"""The base class for all `rubicon_ml` visualizations.
`VizBase` can not be directly instantatied. ... |
"""
This takes an array of numbers and finds the max product of 3 numbers.
"""
def maxProductFinder(l):
sortL = sorted(l)
product = 0
print(sortL)
product += max(sortL)
print(product)
print(sortL[0] * sortL[1])
print(sortL)
if (sortL[0] * sortL[1]) > sortL[len(sortL)- 2] * sortL[(len(... |
from ffmpy import FFmpeg
import io
from fileModule import FileManager
from subprocess import PIPE, call
call(["chmod", "+x", "ffmpeg"])
def main(args):
inId = args["videoID"]
inconf = ""
outconf = "-f mpegts -vf scale=320:-1"
fm = FileManager()
data = fm.loadFile(inId)
datared = data.read()
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import codecs
import sys
import numpy as np
import re
import math
import preproc
from sklearn.preprocessing import LabelEncoder
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction import DictVectorizer
from sklearn.lin... |
import threading
from msg import *
def ProcessMessages():
while True:
m = Message.SendMessage(M_BROKER, M_GETDATA)
if m.Header.Type == M_DATA:
print(m.Data)
else:
time.sleep(1)
def Client():
Message.SendMessage(M_BROKER, M_INIT)
t = threading.Thread(target=ProcessMessages)
t.start()
while True:
M... |
"""
Python Version 3.8
Singapore Institute of Technology (SIT)
Information and Communications Technology (Information Security), BEng (Hons)
ICT-2203 Network Security Assignment 1
Author: @ Tan Zhao Yea / 1802992
Academic Year: 2020/2021
Lecturer: Woo Wing Keong
Submission Date: 25th October 2020
This script holds ... |
for i in range(1,3000):
for j in range(1,11):
if i%j != 0:
break
else:
continue
num = 2520
i = 2
while i < 21:
if num%i == 0:
i += 1
else:
num += 1
i = 2
print(num) |
# Write a Python program to find common items from two lists
def commoninList (list1,list2):
commonEle = []
if len(list1)<len(list2):
for i in range(len(list1)):
if list1[i] in list2:
commonEle.append(list1[i])
else:
print('Nothing in common')
... |
from setuptools import setup
setup(
name='geomap6',
version='6.2.0',
packages=['ml_project', 'ml_project.src', 'ml_project.src.model', 'ml_project.src.model.utils'],
url='',
license='MIT',
author='asokolov',
author_email='aesokolov1975@gmail.com',
description='Geo tools'
)
|
"""
- contains data for a single author
"""
class author( object ):
"""docstring for `uPub_data`."""
def __init__(self, line):
import hashlib
"""assigns values to the object.
INPUT: MD file containing all data; path to image
"""
self.fname = None
self.lname = None
self.contribution = None
self.affi... |
class PokerHand:
"""
models a poker hand
"""
def __init__(self, hand_list=None):
if hand_list is None:
hand_list = []
self.__hand = hand_list
def get_hand(self):
"""
getter method for hand(list of cards)
:return: hand
"""
return... |
import os
from nltk import sent_tokenize
from nltk import word_tokenize
class SentenceIterator(object):
def __init__(self, dirname):
self.dirname = dirname
def __iter__(self):
for fname in os.listdir(self.dirname):
for sent in sent_tokenize(open(os.path.join(self.dirname, fname),'r... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from base.segbase import SegBaseModel
class PSPNet(SegBaseModel):
def __init__(self, nclass, backbone='resnet50', pretrained_base=True, **kwargs):
super(PSPNet, self).__init__(nclass, backbone, pretrained_base=pretrained_base, **kwargs)
... |
# -*- coding: utf-8 -*-
import scrapy
from scrapy.http import Request
class Pic169bbSpider(scrapy.Spider):
name = "pic_169bb"
allowed_domains = ["169bb.com","169ku.com"]
start_urls = ['http://169bb.com/']
def parse(self, response):
url_data = response.xpath("/html/body/div[@class='header']/di... |
#!/usr/bin/env python
import time, unittest, os, sys
from selenium import webdriver
from main.activity.desktop_v3.activity_login import *
from main.activity.desktop_v3.activity_talk_product import *
from main.page.desktop_v3.shop.pe_shop import *
from main.page.desktop_v3.product.pe_product import *
from main.page.des... |
#!/usr/bin/env python
#-*-coding:utf-8-*-
# @File:lr_model.py
# @Author: Michael.liu
# @Date:2020/6/17 14:51
# @Desc: this code is ....
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.externals import joblib
clas... |
#!/usr/bin/python -tt
#
# Marko Saukko <marko.saukko@cybercom.com>
#
# Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
#
# This copyrighted material is made available to anyone wishing to use, modify,
# copy, or redistribute it subject to the terms and conditions of the GNU
# General Public License v.... |
# coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from pants.util.cont... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.