text stringlengths 8 6.05M |
|---|
#!/usr/bin/python3
import string
class Node():
def __init__(self, value, dataCount = None, fileName = None):
self.data = value
self.dataFileName = fileName
self.next = None
self.dataCount = dataCount
#Function points current node to another node
def addNode(self, node2):
... |
#!/usr/bin/env python
#import modules
try:
#delays
import time
#threads
import threading
except RuntimeError:
print "Error importing modules\n"
print "Try using 'sudo' to run this script\n"
#------------------------------------------------------------------------------
def readBuff():
try: GPIO.wait_for_edge... |
try:
from tuneup.ndimraces import sigopt_versus_shgo_deap
except ImportError:
pass
from tuneup.ndimraces import open_source_race
|
import os
import unittest
import __main__
class PrhTests(unittest.TestCase):
def create_local_ref(self, name):
path_prefix = __main__.get_repo_git_dir() + "/refs/heads/"
self.create_dirs_and_file(name, path_prefix)
def create_remote_ref(self, name):
path_prefix = __main__.get_repo_gi... |
#This program flashes an led connected to GIPO Pin 17 on the Raspberry PI
import gpiozero #Importing LED functions from GIPO in Pyhton
import time #Import Sleep function
ledBlue = gpiozero.LED(17) #Assign control of the pin to the variable, note this is referencing GIPO 17 not the pin#
w... |
import numpy as np
from scipy.ndimage import zoom
from imu.io import mkdir, segToRgb
from imageio import imsave
def createMipImages(getInputImage, getOutputName, zran, level_ran=range(3), resize_order=1, do_seg=False):
# need helper function to get image slice from 3D volume or image namges
# getInputImage(z):... |
from flask import Flask
from flask_restful import Api, Resource, reqparse
import pickle
import numpy as np
from PIL import Image
from io import BytesIO
import base64
# variables Flask
app = Flask(__name__)
api = Api(app)
# se carga el modelo de Logistic Regression del Notebook #3
pkl_filename = "ModeloLR... |
# Generated by Django 2.1 on 2018-08-09 01:21
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('exchanges', '0002_auto_20180809_0049'),
]
operations = [
migrations.RenameField(
model_name='exchange',
old_name='icon',
... |
class Solution:
# @param A, a list of integer
# @return an integer
def singleNumber(self, A):
result = 0
for a in A:
result ^= a
return result
s = Solution()
print s.singleNumber([1,2,3,4,5,6,5,4,3,2,1,2,2,6,4]) |
from django import template
from ghostwriter.shepherd.models import AuxServerAddress
register = template.Library()
@register.simple_tag
def get_primary_address(value):
"""Gets the primary IP address for this server."""
primary_address = value.ip_address
aux_addresses = AuxServerAddress.objects.filter(sta... |
from collections import OrderedDict
import threading
import time
import unittest
from smqtk.utils.read_write_lock import \
ContextualReadWriteLock
def wait_for_value(f, timeout):
"""
Wait a specified timeout period of time (seconds) for the given
function to execute successfully.
`f` usually wr... |
#!/usr/bin/python
import optparse
import os
import re
import sys
import shutil
base_path = '/storage/tvseries/'
down_path = '/home/todsah/download'
patterns_epi = [
'(?P<series>.*)[sS](?P<season>\d+?)[eE](?P<episode>\d+)',
'(?P<series>.*)(?P<season>\d\d)(?P<episode>\d\d)',
'(?P<series>.*)(?P<season>\d)(?P<episode... |
# this file is to handle the file transactions
# it is the main application level in the server
# our goal is to make the server as light weight as possible
import time
import trans
import meta_puller
import config
import random
import pickle
import os
import time
# the "transaction" is implemented as foll... |
from conans import ConanFile, CMake, tools
import os
from conans import ConanFile, CMake, tools, AutoToolsBuildEnvironment, RunEnvironment, python_requires
from conans.errors import ConanInvalidConfiguration, ConanException
from conans.tools import os_info
import os, re, stat, fnmatch, platform, glob, traceback, shuti... |
import chainer
from onnx_chainer.functions.opset_version import support
from onnx_chainer import onnx_helper
@support((1, 6, 7))
def convert_Dropout(func, opset_version, input_names, output_names, context):
if opset_version == 1:
return onnx_helper.make_node(
'Dropout', input_names, output_na... |
from newspaper import Article
import fact_check
#url = "https://politics.theonion.com/trump-insists-he-never-thought-about-firing-mueller-fe-1822461545" # later to be replaced by active tab's url
#url = "http://uspoliticalpost.com/economic_terrorism_exposed/"
#url = "http://empirenews.net/trump-begins-waging-battle-ag... |
# -*- coding:utf-8 -*-
'''
硬币找零问题:
我们有 3 种不同的硬币,1 元、3 元、5 元,我们要支付9元,最少需要几个硬币
'''
import numpy as np
'''
money = [1,3,5]
total = 9
states = np.zeros((total, total+1))
# states[次数][金额]
for i in money:
states[0][i] = 1
for i in range(1,total):
for j in range(total+1):
if states[i-1][j]:
if j + 1 <= total:
... |
#!/bin/python3
import sys
from collections import *
def migratoryBirds(n, ar):
c = Counter(ar).most_common(1)
return (c[0][0])
n = int(input().strip())
ar = list(map(int, input().strip().split(' ')))
result = migratoryBirds(n, ar)
print(result)
|
import unittest
from katas.kyu_7.speed_control import gps
class GPSTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(gps(
15, [0.0, 0.19, 0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0, 2.25]), 74)
def test_equals_2(self):
self.assertEqual(gps(
15, [0.0, 0.15... |
>>> from tdd1 import *
>>> f(2,3)
5
>>> f(-1,1)
0
>>> fact(5)
120
>>> fact(1)
1
#from my-rb import *
|
import logging
import numpy as np
from copy import deepcopy
from scipy import sparse
"""
@desc: Adds a generator which produces random spikes and
connects it to the excitatory reservoir neurons
"""
def addNoiseGenerator(self):
# Create spike generator
sg = self.nxNet.createSpikeGenProcess(numPorts=self... |
from .boxplot import boxplot
from .distribution import distribution
from .pca import pca
from .permutation_test import permutation_test
from .roc import roc_boot, roc_cv, roc
from .scatter import scatter
from .scatterCI import scatterCI
from .scatter_ellipse import scatter_ellipse
__all__ = ["boxplot", "distribution",... |
#!/usr/bin/env python
#
# Copyright 2017 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 la... |
import time
for i in range(1,100):
f = open('Sources\\' + str(i) + '.txt')
print(f.readline())
time.sleep(1)
|
"""
설탕배달
https://www.acmicpc.net/problem/2839
"""
n = int(input())
cnt = 0
while n>0:
if n % 5==0:
cnt += n/5
n = 0
else:
cnt += 1
n -= 3
if n == 0:
print(int(cnt))
else:
print("-1")
|
#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
def check(lhs, rhs, at):
if lhs >= rhs:
print('+ Convex at {}'.format(at))
else:
print('- Concave at {}'.format(at))
def f(x):
return -x*x*x
def f_2(x):
return -x*x*x + 2*x*x + 5
def test_set(x, y, p):
... |
import time
import random
from pylo import Datatype
from pylo import MicroscopeInterface
from pylo import MeasurementVariable
class DummyMicroscope(MicroscopeInterface):
"""This class represents a dummy microscope.
Attributes
----------
record_time : int or None
The record time in seconds or ... |
#!/usr/bin/python
import sys
import os
def convert(password):
password = password.strip('\'')
if password.startswith("$SHA$") is False:
print("Invalid Token: Does not begin with $SHA$")
exit(1)
password = password[5:]
salthash = password.split('$')
if len(salthash... |
from .symex import SymexFrontend, TestInfo
from .fuzz import FuzzerFrontend, FuzzFrontendError
|
from tkinter import *
import time
import pymysql as p
class MainFrame():
def __init__(self ,master ,number):
#Create frame
self.cos = self
self.master = master
self.master.iconbitmap("C:/Users/bkwia/Desktop/python/bankGUI/data/bank.ico")
self.master.title("BANK")
sel... |
from django.db import models
# Create your models here.
class Data_sets(models.Model):
train_data = models.FileField(upload_to='files')
|
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'dkdrive_2.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
... |
#!/usr/bin/python3
# -*- encoding: utf-8 -*-
# PKGBUILDer v2.1.5.12
# An AUR helper (and library) in Python 3.
# Copyright © 2011-2012, Kwpolska.
# See /LICENSE for licensing information.
# Names convention: pkg = a package object, pkgname = a package name.
"""
pkgbuilder.pbds
~~~~~~~~~~~~~~~
PKGBUILDer D... |
"""
Student: Karina Jonina - 10543032
Module: B8IT110
Module Name: HDIP PROJECT
Task: Time Series Forecasting of Cryptocurrency
File: This file is for functions to run the
"""
# Downloading necessary files
import numpy as np
import pandas as pd
import yfinance as yf
import p... |
__author__ = "Narwhale"
class ListNode:
def __init__(self,elem):
self.elem = elem
self.next = None
class Solution(object):
def __init__(self,node=None):
self.__head = node
def is_empty(self):
return self.__head == None
def append(self,item):
node = ListNode(i... |
#pypharm by Danny Limoges, PharmD
# A construct for managing data for: fill claims, fills, prescriptions, drug data, insurance data and more.
# The goal is to develop easy-to-use interfaces for pharmacy-related APIs |
"""empty message
Revision ID: 5d4aee209354
Revises: 99cd2a081a3c
Create Date: 2018-11-16 15:15:44.885014
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '5d4aee209354'
down_revision = '99cd2a081a3c'
branch_labels = None
depends_on = None
def upgrade():
# #... |
# -*- coding: utf-8 -*-
a=int(input())
i=1
sum=0
while i <= a:
if (i % 5 == 0):
sum=sum+i
i=i+1
print(sum)
|
from selenium.webdriver.common.by import By
# for maintainability we can seperate web objects by page name
class FormPageLocators(object):
FormUrl = 'https://www.seleniumeasy.com/test/basic-first-form-demo.html'
NumberField1 = (By.XPATH, '//*[@id="sum1"]')
NumberField2 = (By.XPATH, '//*[@id="sum2"]')
... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import logging
from dataclasses import dataclass
import ijson.backends.python as ijson
from pants.backend.go.util_rules import go_mod
from pants.backe... |
import cv2
import matplotlib.pyplot as plt
img = cv2.imread('bird.png')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# Lower/Upper thresholds for edge detection. If between, it is kept if adjacent to high. L1 absolute, L2 squared
L1 = cv2.Canny(img, 150, 200, L2gradient=False)
L2 = cv2.Canny(img, 150, 200, L2gradien... |
from django.apps import AppConfig
class GtinConfig(AppConfig):
name = 'gtin'
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ==================================================
# @Time : 2019-06-20 14:40
# @Author : ryuchen
# @File : celery_app.py
# @Desc :
# ==================================================
from celery.bin import worker
from apps.jobs.celery import app
from lib.base.Applicati... |
from pyTFM.data_analysis import *
# reading the Wildtype data set. Use your own output text file here
# your file maybe called out0.txt or similiar
file_WT = r"/home/user/Software/example_data_for_pyTFM/clickpoints_tutorial/WT/out.txt"
# reading the parameters and the results, sorted for frames and object ids
paramet... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class PairNet(nn.Module):
def __init__(self, dim_in, dim_out):
super(PairNet, self).__init__()
self.fc1 = nn.Linear(dim_in, 512)
self.fc2 = nn.Linear(512, 256)
self.fc3 = nn.Linear(256, dim_out)
def forward(sel... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
text = raw_input()
print text
|
__author__ = 'AmmiNi'
import unittest
import SMSSender
import EmailSender
class NotificationTest(unittest.TestCase):
def test_one_sms(self):
sms_client = SMSSender.SMSSender("test sms", '')
raised = False
try:
sms_client.send_message("+6594681497", "Test message")
... |
# Generated by Django 2.2.6 on 2020-01-12 18:37
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('work', '0084_auto_20200110_1124'),
]
operations = [
migrations.RenameField(
model_name='historicalsurveyqty',
old_name='appr... |
"""
ZIP UTILS
Herramientas para el uso de archivos ZIP
Autor: Pablo Pizarro R. @ ppizarror.com
Licencia:
The MIT License (MIT)
Copyright 2017 Pablo Pizarro R.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Softwar... |
## Initial conditions cuts
from __future__ import print_function, division
import hdf5_to_dict as io
import sys
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from pylab import *
COMPARE = False
dump_dir = sys.argv[1]
init_file = io.get_dumps_list(dump_dir)[0]
hdr, geom,... |
from __future__ import division
import caffe
from caffe import tools
import test
from util import Timer
import numpy as np
import os
save_format, snapshot_prefix = test.prepare()
weights = '/home/jonlong/x/caffe/models/VGG/VGG16_full_conv.caffemodel'
caffe.set_device(6)
solver = caffe.SGDSolver('solver.prototxt')
so... |
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
classifier = Sequential()
classifier.add(Conv2D(32, (3, 3), input_shape = (64, 64, 3), activation = 'relu'))
# Step 2 - Pooling
classifi... |
import argparse
from FileHandler import File
from ExitHandler import Exit
class Handler:
def __init__(self):
self.parser = argparse.ArgumentParser
self.parser.add_argument('-c', '--config', action='store', help='Configuration File to use.')
self.parser.add_argument('--ftp', action='store_tr... |
from math import *
import numpy as np
import matplotlib.pyplot as plt
from qiskit import *
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute
from qiskit.circuit import Parameter
from qiskit.tools.visualization import plot_histogram
from qiskit import Aer, IBMQ
from qiskit.providers.ibmq i... |
from sklearn.metrics import confusion_matrix
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
def name_species(predict, error):
class_result = []
if error < 0.1:
error = 0.1
for i in range(len(predict)):
if (1-abs(predict[i][0])) <= error and (0-abs(predict[i][1])... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import os.path
import platform
import subprocess
from pathlib import Path
from textwrap import dedent
import pytest
from pants.backend.go import targe... |
#!/usr/bin/python
VERSION = 0.1
#---------------------------------
# BAGEL-calc_foldchange: given a matrix of read counts, normalize, filter for low reads, and calculate fold change
# (c) Traver Hart, 10/2015.
# modified 9/2015
# Free to modify and redistribute with attribtution
#---------------------------------
... |
def define_parinject_model(vocab_size, max_length):
# feature extractor model
inputs1 = Input(shape=(4096,))
fe1 = Dropout(0.5)(inputs1)
fe2 = Dense(256, activation='relu')(fe1)
fe3 = fe2
for i in range(33):
fe3=concatenate([fe3,fe2],axis=1)
fe4 = Reshape((34,256))(fe3)
# sequen... |
import numpy as np
import open3d as o3d
import math
from math import cos, sin, pi
from sklearn.linear_model import LinearRegression
from matplotlib import pyplot as plt
import lineSegmentation as seg
# import sortline as sl
############################## Macro ###############################
# pi = 3.141592653589793... |
import random
import time
print ('Vamos jogar pedra papel tesoura? ')
r2 = str (input ('Digite pedra ou papel ou tesoura: (digite em minusculo SEM ESPACOS) '))
r = ['pedra', 'papel','tesoura']
r1 = random.choice(r,)
print ('JO')
time.sleep(1)
print ('KEN')
time.sleep(1)
print('PO')
if r2 == 'pedra' and r1 == 'tes... |
# Create a set called my_fav_numbers with your favorites numbers.
# Add two new numbers to it.
# Remove the last one.
# Create a set called friend_fav_numbers with your friend’s favorites numbers.
# Concatenate my_fav_numbers and friend_fav_numbers to our_fav_numbers.
#task1
# my_fav_numbers = set([9, 3])
# my_fav_num... |
# Copyright (c) 2017-2023 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Logging utilities used in `dazl`.
This is an internal API and not meant to be used directly outside of dazl; symbols declared in this
file may change at any time.
"""
from ... |
import unittest
import os
import json
from utils.text import Text
TEST_PATH = os.path.dirname(os.path.realpath(__file__))
TEST_FILES_PATH = os.path.join(TEST_PATH, '../test_source')
TMP_PATH = os.path.join(TEST_PATH, '../tmp_test')
class TextTestCase(unittest.TestCase):
def setUp(self):
self.test_interve... |
from common import *
#from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import juggle_axes
from mpl_toolkits.axes_grid1 import make_axes_locatable
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
from matplotlib import colors
from matplotlib.ticker import MaxNLocator
tri_corr = Tru... |
#!/usr/bin/env python
import os
import sys
import time
import pyrax
pyrax.set_setting("identity_type", "rackspace")
creds_file = os.path.expanduser("~/.rackspace_cloud_credentials")
pyrax.set_credential_file(creds_file)
# Prints out all your current servers and their statuses
# Note: lists for DFW and ord
print "Her... |
# -*- python -*-
from math import trunc
def rSigma( n ):
# Case: if type( n ) is float
n = trunc( n )
if n <= 0:
return( 0 )
elif n == 1:
return( 1 )
else:
return( n + rSigma( n - 1 ) )
# Testing
print "rSigma( 5 )", " =", rSigma( 5 ), "## Expect =", 15
print "rSigma(... |
#!/usr/bin/env python
"""
npy_asyncio.py
----------------
TODO: integrate with external runloop/REPL,
eg receiving an array whilst in a live ipython session
* https://ipython.readthedocs.io/en/stable/interactive/autoawait.html
https://docs.python.org/3/library/asyncio-stream.html
Async marks a function that may be... |
#http://live.amasupercross.com/xml/sx/RaceResults.json?
import urllib2
import twitter
import time
import pandas as pd
import itertools
import random
import config
import json
import re
from xml.etree import cElementTree as ET
import os
import sys
import helpers
top_x_dict = {0 : 10, 10 : 5, 15 : 3}
positions_to_twee... |
# Copyright (c) 2018 Amdocs
#
# 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... |
from taiga.requestmaker import RequestMaker
from taiga.models import UserStoryStatus, UserStoryStatuses
import unittest
from mock import patch
class TestPriorities(unittest.TestCase):
@patch('taiga.models.base.ListResource._new_resource')
def test_create_user_story_status(self, mock_new_resource):
rm... |
import os
import json
import requests
import subprocess
from urllib.parse import urlparse
from datetime import datetime
import boto3
from .azul_agent import AzulAgent
from .data_store_agent import DataStoreAgent
from .ingest_agents import IngestUIAgent, IngestApiAgent
from .analysis_agent import AnalysisAgent
from .m... |
import argparse
import random
import string
import os
parser = argparse.ArgumentParser(
prog='keygen',
description='Key generator')
parser.add_argument('-q', type=int)
args = parser.parse_args()
def gen_key():
key = ''
alphabet = string.ascii_uppercase + '0123456789'
for block in range(5):
... |
# Simulation 1
import os
import sys
sys.path.insert(1, os.path.join(sys.path[0], '..'))
import agent
def f12(x1, x2):
if (x1, x2) == (0, 0): return 3
elif (x1, x2) == (0, 1): return 2
elif (x1, x2) == (1, 0): return 4
elif (x1, x2) == (1, 1): return 1
else: raise ValueError
def f21(x2, x1):
... |
# -*- coding: utf-8 -*-
from architect.inventory.client import BaseClient
from celery.utils.log import get_logger
logger = get_logger(__name__)
class ArchitectClient(BaseClient):
def __init__(self, **kwargs):
super(ArchitectClient, self).__init__(**kwargs)
def check_status(self):
return Fa... |
import os
import sys
import time
import scipy
import matplotlib
import pybedtools
import subprocess
def gfffeature_to_interval(feature):
return pybedtools.create_interval_from_list(feature.tostring().split('\t'))
def chunker(f, n):
"""
Utility function to split iterable `f` into `n` chunks
"""
f... |
import numpy as np
import matplotlib.pyplot as plt
def drawPlan(plans, stu, time_len, bins, stat_time=10, note=''):
for name, groups in plans.items():
for i in range(groups):
group_arr = np.random.normal(time_len / groups * (i + 1) - time_len / groups / 3,
... |
# This program do the following
# - opens a list of devices to telne
# - save the list of devices in a list
# - asks for user and password
# - then loops entering to devices and sendsa command
# - the output is shown and stored in a file
import getpass
import telnetlib
import time
with open ("device-list.list", "r") ... |
import base64
from bbbingo import db
class User(db.Document):
username = db.StringField(unique=True)
email = db.StringField()
password = db.StringField()
cards = db.ListField(db.ReferenceField('Card'))
plays = db.ListField(db.ReferenceField('Play'))
class Card(db.Document):
slug = db.String... |
logparser = r'(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2},\d{3})\s+' \
r'(DEBUG|ERROR|INFO)\s+\[(\w+):(\w+):?(\w+)?\]\s+(.+)$'
|
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.urls import reverse
from django.utils.text import slugify
import uuid, os
from django.contrib.gis.geos import Point
from geopy.geocoders import Nominatim
from django.contrib.gis.db.models import PointField
geolocator = Nominat... |
global namephone
global flag
import numpy
namephone=numpy.array([[' ']*6]*10)
namephone[0][0]='Tossapon'
namephone[1][0]='Poowanai'
namephone[2][0]='Norasath'
namephone[0][1]='0811323545'
namephone[1][1]='0835411234'
namephone[1][2]='0823354121'
namephone[2][1]='0850550354'
flag=0
def createuser():
... |
# -*- coding: utf-8 -*-
"""
Created on Sun May 17 14:51:48 2015
@author: Martin Nguyen
"""
from NodeClass import node
from numpy import random
#list of TreatmentTree
# [[IOPreduction],CurrentMedicationType,SideEffect,MedicationCombination]
TreatmentTree = node ([ [511,1381] ,1, [10,109] , [1,0,0,0,0] ],
... |
import time
class BubbleSort:
def bubble_sort(vetor, tempo):
elementos = len(vetor.lista) - 1
vetor.ordenado = False
ordenado = False
j = 0
while not ordenado:
ordenado = True
for i in range(elementos):
if vetor.lista[i] > vetor.lista... |
class Color:
def __init__(self, id, name, rgba):
self.id = id
self.name = name
self.rgba = rgba
# https://minecraft.gamepedia.com/Map_item_format#Map_colors
COLOR_NONE = Color(0, "NONE", (0, 0, 0, 0))
COLOR_GRASS = Color(1, "GRASS", (127, 178, 56, 255))
COLOR_SAND = Color(2, "SAND", (247, 2... |
import json
from urllib import request, parse
import codecs
from tv_trivia import settings
from tv_trivia.models import Show
def get_show_by_id(title_query, year=''):
qry_dict = {'t': title_query, 'apikey': settings.OMDB_API_KEY}
if year:
qry_dict.update({'y': year})
r = request.urlopen("http://w... |
"""
A script to convert Bus Monitor Log files to CSV files easily importable to Excel.
Note: only parameters are exported, and read/write appear are different entries at different times.
"""
import sys
import os.path
import re
import collections
__commentLinePattern__ = re.compile(r'^\*[\s]*[\w:\s\.=]*$')
__aliasLine... |
# -*- coding: utf-8 -*-
"""
99: program finished
1 : adds num in two positions and store the result in third position.
2 : multiplies num in two positions and store the result in third position.
3 : takes an input to store in a specific pos
4 : outputs the value in the specific pos
5 : jump_if_true
6 : jump if false
7 ... |
#!/usr/bin/env python
import traceback
import sys
from regression import scenario
try:
scenario.run()
except Exception, ex:
print "Error in scenario"
tb = tb2 = sys.exc_info()[2]
tb_len = 1
while tb2.tb_next:
tb_len += 1
tb2 = tb2.tb_next
traceback.print_tb(tb, tb_len - 1, sys... |
# 渾沌加密外掛程式(免key的版本
# by sklonely
# import自動修復 程式碼片段Stste
lestModName = ""
while 1:
try:
import sys
import os
sys.path.append(sys.path[0] + '/mods/') # 將自己mods的路徑加入倒python lib裡面
# 要import的東西放這下面
from flask import Flask, jsonify, request
from flask_cors import CORS
... |
import sys
from keras.preprocessing.image import img_to_array
from keras.preprocessing.image import load_img
from keras.models import load_model
from numpy import vstack, expand_dims
from loadingdata import load_dataset
from matplotlib import pyplot
from keras_contrib.layers.normalization.instancenormalization import I... |
'''
Created on Nov 15, 2015
@author: TranBui
'''
from Tkinter import Frame,BOTH,Tk
import datetime
from ChartingCanvas import ChartingCanvas
from StockReader import StockReader
from MatplotCharting import MatplotCharting
class MainFrame(Frame):
'''
presents our human interface in an TkInter image window
Th... |
#!/usr/bin/env python
from setuptools import setup, find_packages
with open('VERSION') as version_file:
version = version_file.read().strip()
with open('README.rst') as readme_file:
readme = readme_file.read()
install_requires = [
'boto3>=1.4.0',
]
setup(
name='marquee',
version=version,
des... |
from flask import Flask,render_template,request
app = Flask(__name__)
@app.route('/')
def hello():
return render_template("form.html")
@app.route('/form',methods=["post"])
def fb():
enroll = request.form["enrollment"]
name = request.form["name"]
mail = request.form["mail"]
print(enroll , name, mail)
return rend... |
from dagster import pipeline, execute_pipeline
from zitarice.solids.caloriest_cereals import sort_by_calories
from zitarice.solids.configuring_download_csv import download_csv
@pipeline
def configurable_pipeline():
sort_by_calories(download_csv())
if __name__ == '__main__':
run_config = {
"solids": ... |
"""
Week 4, Day 2: Interval List Intersections
Given two lists of closed intervals, each list of intervals is pairwise disjoint and in sorted order.
Return the intersection of these two interval lists.
(Formally, a closed interval [a, b] (with a <= b) denotes the set of real numbers x with a <= x <= b. The
intersec... |
# Generated by Django 2.2.4 on 2019-09-24 20:28
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('recipes', '0015_auto_20190924_1558'),
]
operations = [
migrations.RenameMo... |
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import os
import urllib.request
URL = 'https://www.google.co.kr/imghp?hl=ko'
keyword = 'akakubi'
totalCount = 3
driver = webdriver.Chrome('H:\chromedriver.exe')
driver.get(url=URL)
driver.implicitly_wait(3... |
import itertools
import time
import numpy
import pytest
from helpers import *
from tigger.helpers import product
from tigger.fft import FFT
import tigger.cluda.dtypes as dtypes
from tigger.transformations import scale_param
def pytest_generate_tests(metafunc):
perf_log_shapes = [
(4,), (10,), (13,), #... |
"""Module container for functions that are zone-neutral."""
from re import finditer
import numpy as np
import pandas as pd
import re
import os
def file_to_df(file_in):
"""Read .csv file into dataframe."""
working_df = pd.read_csv(file_in, sep=',', encoding='iso-8859-1')
working_df = working_df.drop(['Unn... |
# 给定两个二进制字符串,返回他们的和(用二进制表示)。
#
# 输入为非空字符串且只包含数字 1 和 0。
#
# 示例 1:
#
# 输入: a = "11", b = "1"
# 输出: "100"
#
# 示例 2:
#
# 输入: a = "1010", b = "1011"
# 输出: "10101"
# Related Topics 数学 字符串
# leetcode submit region begin(Prohibit modification and deletion)
class Solution:
def addRestNum(self, c: str, tmp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.