text stringlengths 38 1.54M |
|---|
import re
print('a\tb')
p=r'\d+'
text='35 my lucky number is 35'
match=re.match(p,text)
print(match.group(0),match.start())
# match used to find only start of the string
# --------------------------------------------------------------------
p=r'\d+'
text=' my lucky number is 35 and 35'
match=re.search(p,tex... |
def add_tip(total, tip_percent):
'''Return the total amount including tip'''
tip = tip_percent*total
return total + tip
def mean(a,b,c):
return (a+b+c)/3.
def hyp(leg1, leg2):
return (leg1**2 + leg2**2)**0.5
def perimeter(base, height):
return 2*base+2*height
#1.3.2 Function Test
print add_tip... |
import FWCore.ParameterSet.Config as cms
from IOMC.EventVertexGenerators.VtxSmearedParameters_cfi import Early10TeVX322Y100VtxSmearingParameters,VtxSmearedCommon
VtxSmeared = cms.EDProducer("BetafuncEvtVtxGenerator",
Early10TeVX322Y100VtxSmearingParameters,
VtxSmearedCommon
)
|
__author__ = 'ArkJzzz (arkjzzz@gmail.com)'
import json
import logging
import textwrap
from telegram import InlineKeyboardButton
from telegram_bot_pagination import InlineKeyboardPaginator
logger = logging.getLogger('keyboards')
start_keyboard = [
[
InlineKeyboardButton(
text='Меню магазина... |
import django_tables2 as tables
from .models import Roadmap
from issuelog.models import Issue
"""
create helper classes for django_tables2 to defined product Roadmap
tables. the Roadmap table shows product release schedule and TopIssuesTable
shows top features or bug fixes requested.
"""
class RoadmapTable(table... |
from rest_framework.views import APIView
from rest_framework.response import Response
class HelloApiView(APIView):
"""Test API View"""
def get(self, request, format=None):
"""Returns a list of API View features"""
an_apiview = [
'Uses HTTP methods as get post put delete',
'Is s... |
import requests
import json
import sqlite3 as sql
import time
app_id = '741da96a'
app_key = '5f83749620ab5b89b6a70e315e6616a9'
language = 'en'
word_id = 'destrier'
url = 'https://od-api.oxforddictionaries.com:443/api/v1/entries/' + language + '/' + word_id.lower() + '/definitions'
r = requests.get(url, headers = {'ap... |
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 25 20:56:00 2015
@author: Timber
"""
import json
from supervisedRWfunc import *
from loadData import *
import sys
from heapq import *
from matplotlib import pyplot as plt
from added_edge import *
from dumpGraphJSON import *
print "Reading data..."
# load the sanpshots o... |
from congress.etl.members import LegislatorsToDB
import os
from argparse import ArgumentParser
def main(chamber, congress, get_all):
legis = LegislatorsToDB()
if get_all:
legis.run_pipeline(
{'house': [str(i) for i in range(102, 116)],
'senate': [str(i) for i in range(80, 116... |
import asyncio
import json
import os
import pwd
import shutil
from traitlets import Float, Unicode, Instance, default
from traitlets.config import SingletonConfigurable
from ..base import ClusterManager
from ...utils import TaskPool
__all__ = ("JobQueueClusterManager", "JobQueueStatusTracker")
class JobQueueStatu... |
import streamlit as st
#import openpyxl as pxl
def textFm():
st.subheader("Login Section")
userName = st.sidebar.text_input("User Name")
password = st.sidebar.text_input("password",type='password')
'''
submissionButton = st.form_submit_button(label="Login")
if submissionButton == True:
... |
#!/usr/bin/env python
import unittest
import os
from eulcore.binfile import eudora
from testcore import main
TEST_ROOT = os.path.dirname(__file__)
def fixture(fname):
return os.path.join(TEST_ROOT, 'fixtures', fname)
class TestEudora(unittest.TestCase):
def test_members(self):
fname = fixture('In.to... |
import math
from itertools import combinations
#m number of equations
#arr is the coefficient matrix (list of lists)
#e is the error
#b is the value matrix
# 4x+y+2z=2
# 3x-y+5z=0.5
arr=[[4,3],[1,-1],[2,5]]
b=[2,0.5]
m=2
e=0.001
def Solutions(arr, b,e):
n=len(arr)#no. of variables
m=len(arr[0])... |
{
"id": "mgm4440434.3",
"metadata": {
"mgm4440434.3.metadata.json": {
"format": "json",
"provider": "metagenomics.anl.gov"
}
},
"providers": {
"metagenomics.anl.gov": {
"files": {
"100.preprocess.info": {
... |
from django.contrib.contenttypes.fields import (GenericForeignKey,
GenericRelation)
from django.contrib.contenttypes.models import ContentType
from django.db import models
from documents.models import Document
class Approval(models.Model):
"""Approval exit criteria... |
#! /usr/bin/env python2.5
from count import *
print ''
print '*** HOTSHOT output *** '
print ''
import hotshot, hotshot.stats
prof = hotshot.Profile('hotshot.prof')
prof.runcall(count1)
prof.runcall(count2)
prof.close()
stats = hotshot.stats.load('hotshot.prof')
stats.sort_stats('time', 'calls')
stats.print_stats(20... |
# An implementation of Speck32/64
# params
k = 16
alpha = 7
beta = 2
MOD = 2**k
MASK = MOD - 1
ROUNDS = 22
def rol(x, y):
assert 0 < y < k, "Can't shift by negative negative shifts"
return ((x << y) & MASK) | (x >> (k - y))
def ror(x, y):
assert 0 < y < k, "Can't shift by negative negative shifts"
return r... |
# -*- coding: UTF-8 -*-
"""
@author: WanZhiWen
@file: adaboost.py
@time: 2018-04-25 20:59
"""
import numpy as np
import matplotlib.pyplot as plt
def loadDataSet1():
# 直接返回numpy矩阵
dataMat = np.matrix([[1., 2.1],
[2., 1.1],
[1.3, 1.],
... |
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#using tensor flow helpers to get data from MNIST site
#first param is the folder where the data will be stored
#gets the digit in 'one-hot' format, kind of like binary but only one digit is 1. e.g 0 = 10000000000, 2 = 00100000000, 5 =... |
import socket
import signal
import sys
ClientSocket = socket.socket()
host = '192.168.1.10'
port = 8828 #CHANGE
print('Waiting for connection')
try:
ClientSocket.connect((host, port))
except socket.error as e:
print(str(e))
Response = ClientSocket.recv(1024)
print(Response.... |
import numpy as np
from ray.rllib.env import MultiAgentEnv
from social_dilemmas.envs.matrix_agent import MatrixAgent
class CoopMatrixEnv(MultiAgentEnv):
def __init__(self, game, cooperation_level=0.5):
self.num_agents = 3
self.agents = {}
self.game = game
self.setup_agents()
... |
from .builder import ReportFileBuilder, BuildResult
from .loader import ReportFileLoader, ReportFileLoaderError
from .reportfile import ReportFile
from .job import ReportJob, JobResult
from .const import *
|
#!/usr/bin/env python
# coding: utf-8
# In[62]:
#!pip install psycopg2
import psycopg2
import pandas as pd
import numpy as np
import random
import string
from datetime import date
def db_conn():
return psycopg2.connect("host=127.0.0.1 dbname=group18 user=postgres password=group18.ca")
# Parameters
num_of_reco... |
#!/bin/python
from functools import reduce
from collections import defaultdict
class TrieNode(object):
def __init__(self, value = None):
self.children = dict()
self.value = value
self.isTerminalNode = False
def findChild(self, value):
if value in self.children.keys():
... |
from __future__ import annotations
from typing import TYPE_CHECKING, Any, NamedTuple, Sequence
import boto3
if TYPE_CHECKING:
from mypy_boto3_ec2.type_defs import DescribeImagesResultTypeDef, FilterTypeDef
from typing_extensions import NotRequired, TypedDict
import aec.util.tags as util_tags
from aec.util.conf... |
# -*- coding: utf-8 -*-
import re
import os
from middleware.text_format import replace_special_chars_in_text
import urllib
import urllib2
import json
__author__ = "fuiste"
middleware_dir = os.path.dirname(__file__)
parse_url = "http://distill-server.herokuapp.com/parse"
# Old noun phrase extraction method.
def ext... |
#!/usr/bin/env python
# coding: utf-8
# In[26]:
"""
Support vector Machine
2. For a given dataset predict number of bikes getting shared based on different parameters
"""
# In[43]:
import numpy as np
# import matplotlib.plotly as plt
import matplotlib.pyplot as plt
from matplotlib import pyplot as plt
import... |
import ipywidgets as widgets
from traitlets import Unicode
class VaultPassword(widgets.Password):
ansible_kernel_property = Unicode('vault_password').tag(sync=True)
class SSHPassword(widgets.Password):
ansible_kernel_property = Unicode('ssh_password').tag(sync=True)
class SSHPrivateKey(widgets.Password):
... |
from zipfile import BadZipFile
import pandas as pd
import plotly.express as px
from django.conf import settings
from django.core.cache import cache
from django.db import transaction
from django.shortcuts import get_object_or_404
from rest_framework import exceptions, mixins, permissions, status, viewsets
from rest_fra... |
# In python 2.7
from __future__ import print_function
import sys
# import the Flask class from the flask module
# from flask.ext.login import LoginManager
from flask import (Flask, render_template, redirect, flash,
url_for, request, session, make_response)
# from flask_login import (login_required, l... |
from random import seed
from random import randrange
from csv import reader
from math import sqrt
#load a csv file
def load_csv(filename):
dataset = list()
with open(filename, 'r') as file:
csv_reader = reader(file)
for row in csv_reader:
if not row:
cont... |
import numpy as np
from matplotlib import cm
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
def get_color_map(label_num, cmap_name='terrain', normalzation=False):
cmap = cm.get_cmap(cmap_name, label_num)
cmap_array = np.array([cmap(i)[:3] for i in range(label_num)])
return cmap_array * 25... |
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if nums==None or len(nums)==0:
return None
return self.helper(nums,0,len(nums)-1)
def helper(self,nums,left,right):
if left>=right:
... |
class TrieNode:
def __init__(self, val):
self.children = dict()
self.val = val
self.end = False
class WordDictionary:
def __init__(self):
"""
Initialize your data structure here.
"""
self.head = TrieNode(None)
def addWord(self, word):
n... |
from data.firestore import DatabaseController
class User(DatabaseController):
def __init__(self, name: str, authenticated: bool = False):
super().__init__(data="users")
user = self.get_data(name)
self.profile = user
self.username = name
self.exists = user["exists"]
... |
import geoip2.database
reader = geoip2.database.Reader('./GeoLite2-City_20190423/GeoLite2-City.mmdb')
response = reader.city('47.145.125.28')
print(response.country.iso_code) # US
print(response.subdivisions.most_specific.name) # Hawaii
print(response.subdivisions.most_specific.iso_code) # HI
print(response.city.n... |
import os
from .base_config import BaseConfig
class DevConfig(BaseConfig):
# Env settings
FLASK_ENV = 'development'
FLASK_DEBUG = True
# Database settings
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(BaseConfig.BASE_DIR, 'devel.db')
SQLALCHEMY_MIGRATE_REPO = os.path.join(BaseConfig.B... |
from django.db import models
from django.contrib.auth import get_user_model
User = get_user_model()
class Message(models.Model):
content = models.TextField()
timestamp = models.DateTimeField(auto_now_add=True)
def get_last_10_msg(self):
'''
Fetch last new 10 message
'''
... |
import random
def rollDice():
return random.randint(1,6)
def main(n):
d1=1
d2=n/2+1
count=0
while d1!=d2:
r1=rollDice()
r2=rollDice()
if r1==6:
if d1==n:
d1=0
else:
d1+=1
elif r1==6:
if d1==0:
... |
from typing import Tuple
def get_direction(ball_angle: float) -> int:
if ball_angle >= 345 or ball_angle <= 15:
return 0
return -1 if ball_angle < 180 else 1
def getDirectionBy4(angle: float) -> int:
if angle >= 345 or angle < 15:
return 0
elif angle >= 15 and angle < 165:
re... |
import numpy as np
import pandas as pd
from sklearn.metrics import confusion_matrix, accuracy_score
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split
import seaborn as sns
import os
sns.set()
os.chdir("C:/githubrep... |
# coding:utf-8
'''
@Copyright:LintCode
@Author: ultimate010
@Problem: http://www.lintcode.com/problem/insert-node-in-a-binary-search-tree
@Language: Python
@Datetime: 16-06-11 08:39
'''
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right... |
"""
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
"""
a=[]
for s in [*open(0)]:
for x in map(int,s.split()):
a+=[x]
for x in a[::-1]:
print(x**.5) |
#!/usr/bin/env python
# encoding: utf-8
name = "Disproportionation/rules"
shortDesc = ""
longDesc = """
"""
entry(
index = 1,
label = "Root",
kinetics = ArrheniusBM(A=(211.065,'m^3/(mol*s)'), n=1.40533, w0=(576945,'J/mol'), E0=(16272,'J/mol'), Tmin=(300,'K'), Tmax=(1500,'K'), uncertainty=RateUncertainty(m... |
import argparse
import os
import time
import googleapiclient.discovery
credential_path = "./MyProject.json"
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = credential_path
def delete_instance(compute, project_id, zone, name):
return compute.instances().delete(
project=project_id,
zone=... |
from django.utils.translation import ugettext_lazy as _
CODE_TEXT_EDIT = 'EDIT'
TEXT_MSG_SUCCESS = _('Data saved correctly')
TEXT_MSG_ERROR = _('There was an error saving information')
TEXT_MSG_WARNING = _('It required to complete required fields')
STATUS_MSG_TAGS = {
'success': TEXT_MSG_SUCCESS,
'error': TEXT... |
# QUESTION:
#
# This problem was asked by Stripe.
#
# Given an array of integers, find the first missing positive integer in
# linear time and constant space. In other words, find the lowest positive
# integer that does not exist in the array. The array can contain duplicates
# and negative numbers as well.
#
# For ex... |
"""
class for storing static results of a tarjan ordering
"""
from scipy.sparse.csc import csc_matrix
from scipy.sparse.csr import csr_matrix
from scipy.sparse.linalg import inv, factorized, spsolve
from scipy.sparse import eye
from scipy.io import savemat, loadmat
import os
from collections import namedtuple, defaul... |
# -*- coding: utf-8 -*-
value = input().split()
a,b = value
x = int(a)
y = int(b)
if(x==1):
snack = float((y*4.00))
print(f'Total: R$ {snack:.2f}')
if(x==2):
snack = float((y*4.50))
print(f'Total: R$ {snack:.2f}')
if(x==3):
snack = float((y*5.00))
print(f'Total: R$ {snack:.2f}')
if(x==4):
sn... |
from PySide2 import QtWidgets, QtCore
from Elegan import Ui_MainWindow
import connection
import serial
class MyApp(Ui_MainWindow, QtWidgets.QMainWindow):
def __init__(self):
super(MyApp, self).__init__()
self.setupUi(self)
self.setWindowTitle("MyApp 3.7")
self.progressBa... |
#!/usr/bin/env python
'''
Created on 12/lug/2013
@author: davide
'''
import sys
import csv
import numpy as np
import os
from optparse import OptionParser
def_out_file = 'out_stat_overhead.csv'
def_release = 'ft_release.csv'
def_schedule = 'ft_schedule.csv'
def parse_args():
parser = OptionParser("usage: %prog [o... |
# 使用SimpleTagBased算法对Delicious2K数据进行推荐
# 原始数据集:https://grouplens.org/datasets/hetrec-2011/
# 数据格式:userID bookmarkID tagID timestamp
import random
import math
import operator
import pandas as pd
"""0.数据准备,变量定义"""
file_path = "./user_taggedbookmarks-timestamps.dat"
records = {} # 从原始数据生成user->item->tag记录... |
import array
# 1,[mutable/immutable]: item assignment, item deletion
# 2,hold arbitrary data types
if __name__ == '__main__':
# standard array: the list are mutable, and can hold arbitrary data types
print('-' * 20, " list, mutable dynmaic arrays ")
arr = ['gold', 'pogoda', 'abudo']
print(arr)
del(a... |
# # F = C * 9/5 +32
# celsius = 0
# fahrenheit = celsius * 9/5 + 32
# print(fahrenheit)
# celsius = 100
# fahrenheit = celsius * 9/5 + 32
# print(fahrenheit)
# celsius = 23
# fahrenheit = celsius * 9/5 + 32
# print(fahrenheit)
c_list = [0, 23, 100]
def celsius_to_fahrenheit(celsius):
fahrenheit = celsius * 9/... |
from django_quill.fields import QuillField
from django.db import models
class Core(models.Model):
content = QuillField() |
import tkinter as tk
from tkinter import *
from tkinter import font
from tkinter.filedialog import askopenfilename
from tkinter import ttk
import textwrap
from AppOperations import AppOperations as ao # the class build for this purpose
from CommandsGUI import CommandsGUI
from CommandsGUI import ScreenGUI
#from ... |
""" This class keeps global parameters, used
in the whole DHCP server
"""
# socket parameters
PORT = 67
BROADCAST_IP_ADDRESS = '0.0.0.0'
# DHCP message constant values
DHCP_EMPTY_BYTE = 0
NUM_CHADDR_UNUSED_BYTES = 10
NUM_BOOTP_LEGACY_BYTES = 192
# message options codes
END_OPTION_CODE = 255
DHCP_MESSAGE_TYPE = ... |
import torch
import torch.optim as optim
from torch.utils.data import DataLoader
from torchvision import transforms
import tqdm
import argparse
import time
from emotion_classification.dataset.emotion_dataset import PredictDataSet
from emotion_classification.model.model import *
classes = ['angry', 'dis... |
# DC motor cqparts model
# 2018 Simon Kirkby obeygiantrobot@gmail.com
import cadquery as cq
import cqparts
from cqparts.params import *
from cqparts.display import render_props
from cqparts.constraint import Fixed, Coincident
from cqparts.constraint import Mate
from cqparts.utils.geometry import CoordSystem
import m... |
from typing import Dict, List, NamedTuple, Tuple
import os
import h5py
import numpy as np
import pandas as pd
from PIL import Image
from ..logging import DEBUG, WARNING, log
class Spot(NamedTuple):
r"""
Data type for encoding circular capture spots, which are used in
technologies based on the Spatial Tr... |
#!/bin/python3
# Idea: keep two heap, lower is max heap, higher is min heap.
import sys
from heapq import heappush as push, heappushpop as pushpop
class Spliter:
def __init__(self):
self.upper = []
self.lower = []
def median(self):
if len(self.upper) > len(self.lower):
re... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_tg_react
------------
Tests for `tg_react` models module.
"""
import unittest
class TestTgReact(unittest.TestCase):
def test_something(self):
# TODO: Add more tests
pass
|
from django.db import models
from django.contrib.auth.models import User
class TaskModel(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
description = models.TextField(null=True, blank=True)
complete = models.BooleanField(default=False)
created =... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on Mar 6, 2013
@author: manuel
'''
from __future__ import print_function
from scipy.stats import poisson
from hmmlearn.hmm import _BaseHMM
import string , numpy as np
import sys
from time import time
from math import fabs
from help_hmm import _init, _add_pseudo... |
from scipy.io import netcdf
import numpy as np
# for skua - TODO
#import matplotlib
#matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
import matplotlib.ticker as ticker
from argparse import ArgumentParser
import os
import pdb
# names of variable to plot
Variable_... |
import math
s = int(raw_input('ENTER THE VALUE OF N: '))
n = s + 1
def cat(n):
if n == 0:
return 1
else:
return (4*n - 2)/( n + 1 ) * cat(n-1)
def print_cat(n):
c1, c2 = 1, 1
while c1 <= cat(n):
print(c1)
c1, c2 = c2, (4*n - 2)/ ( n + 1 ) * c2
print print_cat(n)
|
import sys
import os
import string
import glob
import optparse
import shlex
import time
import getopt
import shutil
import fnmatch
import cmd
import django
from os.path import join
from datetime import datetime, timedelta
from django.utils import timezone
sys.path.append(os.path.abspath('..'))
os.environ.setdef... |
import sys
import BayesDB
classifier = sys.argv[1].strip()
if classifier == 'NONE':
classifier = None
training_data = open(sys.argv[2], 'r')
db_file = sys.argv[3]
db = BayesDB.createOrLoad(db_file)
docs = 0
for line in training_data:
line = line.strip()
## assume non-trivial sanitisation done upstream
... |
from flask import Flask, request, render_template
from werkzeug.exceptions import NotFound
from cart_views import cart_app
from products_views import products_app
app = Flask(__name__)
app.register_blueprint(products_app, url_prefix='/products/')
app.register_blueprint(cart_app, url_prefix='/cart/')
@app.route('/... |
#!/usr/bin/env python3
# encoding: utf-8
import json
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--feat', type=str)
parser.add_argument('--num_frames', type=str)
parser.add_argument('--trans', type=str)
parser.add_argument('--tokens', type=str)... |
import json
import os
import pickle
import sys
import model
# Keep track of the last loaded version of each channel
MEMORY = 'pickle.db'
try:
with open(MEMORY, 'rb') as f:
memory = pickle.load(f)
except IOError:
memory = {}
def get_last_loaded(channel):
return memory.get(channel)
def set_last... |
'''
Created on 6 feb. 2021
@author: David
'''
from pyb import Pin
from micropython import schedule
class Stepper(object):
'''
Counts signals received on a pin and counts them.
Also rises an event on a concrete step.
'''
def __init__(self, pin, pullMode=None, stepLevel=1):
'''
Cons... |
#!/usr/bin/env python
# wxPython module
import wx
# Matplotlib Figure object
from matplotlib.figure import Figure
# Numpy functions for image creation
import numpy as np
# import the WxAgg FigureCanvas object, that binds Figure to
# WxAgg backend. In this case, this is also a wxPanel
from matplotlib.backends.backend... |
from django.shortcuts import render, render_to_response
from django.http.response import HttpResponseRedirect, HttpResponse
from django.template import loader
from django.template.context import RequestContext
# Create your views here.
def main(request):
return render_to_response('main.html')
def setos(reques... |
# -*- encoding: utf-8 -*-
##############################################################################
#
# Vikasa Infinity Anugrah, PT
# Copyright (c) 2011 - 2012 Vikasa Infinity Anugrah <http://www.infi-nity.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the term... |
# Generated by Django 2.2.8 on 2019-12-09 21:44
from django.conf import settings
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('inventory', '0003_artcomments_articledetails'),
]
operat... |
from dal import autocomplete
from .models import Location
from django.db.models import Q
class LocationAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
qs = Location.objects.all()
if self.q:
qs = qs.filter(Q(city__istartswith=self.q) | Q(state__istartswith=self.... |
import cv2
import numpy as np
def contours_by_mat(src_bank):
contours = cv2.Canny(src_bank,100,200)
return contours;
def tresh_contours_by_length(contours,min_length,max_length):
threshed = []
for i in contours:
if min_length <= len(contours[i]) <= max_length:
threshed.append(contours[i])
return thre... |
from . import sales_report_export
from . import sales_report_export_by_invoice
from . import stock_pick_item_report
from . import sales_report_outstock_item
from . import stock_picking_return
from . import customer_statement
from . import sales_delete_posted
|
import matplotlib.pyplot as plt
import numpy as np
import os
# Contains functions to plot/save information
def plot_perf(algs, save_dir=None, rm_mode=False):
if save_dir is not None:
try:
os.mkdir(save_dir)
except OSError:
pass
def save_or_show(name, save_dir, rm_mode)... |
"""
https://www.python-lernen.de/kommentare.htm
Hier kommt auskommentierter Bereich
der über mehrere Zeilen sich zieht
"""
# hier kommt ein Kommentar |
n=3
max_w =8
w =[3, 4, 5]
v =[30, 50, 60]
"""
n, max_w = map(int, input().split())
w = []
v = []
for i in range(n):
a, b = map(int, input().split())
w.append(a)
v.append(b)
"""
dp = [[0 for _ in range(max_w+1)] for _ in range(n+2)]
for i in range(1, n+1):
for j in range(max_w+1):
dp[i][j] =... |
import numpy as np
from scipy import ndimage as ndi
from skimage.transform import resize
from .utils import get_crop_pad_sequence
def resize_image(image, target_size):
"""Resize image to target size
Args:
image (numpy.ndarray): Image of shape (C x H x W).
target_size (tuple): Target size (H,... |
import unittest
import numpy as np
from PCAfold import preprocess
from PCAfold import reduction
from PCAfold import PCA
from PCAfold import PreProcessing
from PCAfold import KernelDensity
class TestManipulation(unittest.TestCase):
def test_center_scale_all_possible_C_and_D(self):
test_data_set = np.rand... |
def includeme(config):
config.add_static_view('static', 'static', cache_max_age=3600)
config.add_static_view('dist', '../build/dist')
config.add_static_view('build', 'build')
config.add_static_view('app1/dist', '../build/dist')
|
# PC served as a server
import socket
import ConnectWiFi
import MotorControl
import machine
import time
import jy901
from amg88xx import AMG88XX
from machine import Pin, I2C, UART
# Indicator Blue LED for successful connection
led = Pin(2, Pin.OUT)
led.on()
i2c = I2C(scl=Pin(5), sda=Pin(4))
thermal = A... |
sales = float(input("Enter sales: $"))
while sales >= 0:
if sales >= 1000:
user_bonus = (sales * 0.15)
else:
user_bonus = (sales * 0.1)
print("You're bonus is: {}".format(user_bonus))
sales = float(input("Enter sales: $")) |
from functions import *
if __name__ == '__main__':
print("_" * 80)
print("Bienvenid@ a DCCAirlines")
try:
while True:
print("_" * 80)
print("Menú principal")
print("-" * 80)
print("¿Qué acción desea realizar?")
foreach(lambda i: print(f"... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import AbstractUser
from lib.rest_framework_extend.common import gen_random_str
class User(AbstractUser):
api_secret = models.CharField(
u'Api Secret', max_length=64, null=True, bl... |
import json
json_filename = '3'
csv_filename = '7'
with open(f'irrigation_data_as_json/{json_filename}.json', 'r') as f:
datastore = json.load(f)
with open(f"data/{csv_filename}.csv", 'w') as f:
f.write('time,soil_moisture,temperature,air_humidity' + '\n')
for data in datastore['production']['data']:
... |
'''
Escreva um programa que leia valor em metros e exiba convetido em centímetros
e em milímetros
'''
metro = float (input('Coloque o valor em metros: '))
km = metro/1000
hm = metro/100
dam = metro/10
dm = metro*10
cm = metro*100
mm = metro*1000
print(f'{metro} metros medirá:\n{km}km, {hm} hm , {dam} dam\n{d... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('reviews', '0050_merge'),
]
operations = [
migrations.AlterField(
model_name='study',
name='status',
... |
for i in range(1, 10):
print("0"*(9-i), end='')
for k in range(1, i+1):
print(i, end='')
print(end='\n')
|
import imageio
import numpy as np
from sklearn.metrics import roc_curve
from sklearn.metrics import confusion_matrix
from sklearn.metrics import cohen_kappa_score
from sklearn.metrics import accuracy_score
def assess_accuracy(gt_changed, gt_unchanged, changed_map, multi_class=False):
"""
assess accuracy of c... |
from collections import defaultdict
class Solution(object):
def sparsify(self, mat):
sp_dict = defaultdict(dict)
for i in range(len(mat)):
for j in range(len(mat[0])):
if mat[i][j] != 0:
sp_dict[i][j] = mat[i][j]
return sp_dict
def multi... |
#!/usr/bin/python
import commands
import os
t2 = os.system('ps -ef')
title = commands.getoutput('pwd')
t3 = os.popen('ls')
print t3
|
#http://www.eeweb.com/project/mohd_kashif/controlling-of-stepper-motors-using-raspberry-pi17
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
#Define GPIO signals to use
Pins = 18,22,24,26
#GPIO24,GPIO25,GPIO8,GPIO7
StepPins = [17,22,23,24]
#Set all pins as output for pin in StepPins:
for pin i... |
import unittest
from codebase.practice.MaxOfThree import MaxOfThree
class MaxOfThreeUnitTest(unittest.TestCase):
def test_find_max_between_three_numbers_when_three_number_is_different(self):
self.assertEqual(29, MaxOfThree().find_max(11, 5, 29))
|
# -*- coding: utf-8 -*-
__author__ = 'Peng'
from bs4 import BeautifulSoup,Comment
import urllib2
from urllib2 import urlopen,HTTPError
import MySQLdb
import json
import datetime
import logging
import sys
import re
import time
import random
def getSinaArticle(url):
#创建请求头
headers={"User-Agent":"Mozilla/5.0 (Wi... |
import datetime
import re
import json
from datetime import timedelta
from difflib import unified_diff
from pathlib import Path
from urllib.parse import urlencode
import mock
import pytest
from bs4 import BeautifulSoup
from django.utils import timezone
from capapi.tests.helpers import check_response, is_cached
from c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.