text stringlengths 38 1.54M |
|---|
#!/usr/bin/python3
# Collect information about a crash and create a report in the directory
# specified by apport.fileutils.report_dir.
# See https://wiki.ubuntu.com/Apport for details.
#
# Copyright (c) 2006 - 2016 Canonical Ltd.
# Author: Martin Pitt <martin.pitt@ubuntu.com>
#
# This program is free software; you ca... |
# Generated by Django 2.1.15 on 2021-05-30 18:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0004_remove_category_parent'),
]
operations = [
migrations.AlterField(
model_name='traitchoicesability',
na... |
"""
RegionDistances computers
-------------------------
Functions to compute in a different ways the distances between collections of
elements (or regions).
"""
import numpy as np
import networkx as nx
from scipy.sparse import coo_matrix
from scipy.spatial.distance import cdist
from pySpatialTools.Discretization im... |
# Generated by Django 3.1 on 2020-08-12 11:01
import django.core.serializers.json
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("payment", "0018_auto_20200810_1415"),
]
operations = [
migrations.AddField(
model_name="paymen... |
import struct
#import numpy
def pack_list(data_list,file_format):
if file_format[1] in ("F","f"):
return struct.pack('f' * len(datalist),*datalist)
elif file_format[1] in ("I","i"):
return struct.pack('h' * len(datalist),*datalist)
elif file_format[1] in ("D","d"):
return s... |
from django.contrib import admin
from django.urls import path,include
from django.views.generic.base import TemplateView
from django.conf import settings
from django.conf.urls.static import static
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/', include('accounts.urls',nam... |
from util.path import ALL_EQU
def select(x):
with open(ALL_EQU, "r", encoding="utf-8") as f:
data = f.readlines()
n = 0
id_list = []
for i in data:
id_ = i.split(" ")[0]
eq = i.split(" ")[1]
if x in eq:
print(id_)
... |
import logging
import log
logger = logging.getLogger('test2')
# logger.setLevel(logging.DEBUG)
logger.info('Enter: Test 2')
print(" - Enter: Test 2")
filename = "demo2.txt"
compere = "1234567"
try:
f = open(filename, "r")
a = f.read()
except IOError:
logger.critical('unable to open(' + filename + ')')
... |
#Unit Testing
import unittest
from regex import shunt
from regex import match
#Unittest is a library of python
class Testing(unittest.TestCase):
#This function tests the function 'shunt()' which is defined in regex.py
#and takes a infix regular expression and convert to a postfix one
def testShunt(se... |
from django.urls import path
from . import views
from saving.views import AssociationCreateView , AssociationListView , AssociationDetailViewSlug , AssociationDetailViewID , AssociationUpdateView , AssociationDeleteView
urlpatterns = [
# ...
path('association/add/' , AssociationCreateView.... |
# (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org)
# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
############################################################
## Functions
############################################################
def loadapp(uri... |
from datetime import datetime
from datetime import timedelta
class Customer:
def __init__(self,first_name,last_name,email,phone_number,twitter_handle):
self.first_name=first_name
self.last_name=last_name
self.email=email
self.phone_number=phone_number
self.twitter_handle=twi... |
from modules import interlingua_endocytosis
from modules import gui
path = gui()
if path['content']:
interlingua_endocytosis(path['const'], path['add'], path['save'])
|
#create 100 files with random 1 million queries
import random
try:
file=open("AnjanaQueries.txt","r")
lines=file.readlines()
file.close()
except IOError :
print "The filename doesnt exist.Please check"
for i in range(1,101):
if i<10:
filename="real_random_1m_00"+str(i)+".txt"
... |
# https://leetcode.com/problems/check-array-formation-through-concatenation
class Solution:
def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool:
n = len(arr)
mapping = {sub_piece[0]: sub_piece for sub_piece in pieces}
i = 0
while i < n:
# find key
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 18 10:33:05 2018
@author: jesse
"""
import numpy as np
import pandas as pd
from datetime import datetime, timedelta
import timeit
import new_emissions
from utilities import utilities as util
from classes.E_new import E_new
from classes import GC_c... |
# For storing objects/data to disk, here are the native options:
# See also: https://docs.python.org/3/library/persistence.html
# 1) pickle - works, but no indexing; each call dumps data as another "record"
# Retrieving data requires reading everything back in - no "random"
# access possible
# ... |
import streamlit as st
import numpy as np
st.header("ADAC Escape Room: Challenge 3")
import tensorflow.keras
from PIL import Image, ImageOps
import numpy as np
import os
import pandas as pd
# def save_uploaded_file(file):
# # with open(os.path.join("tempDir", file.name), "wb") as f:
# with open(os.path.join("mo... |
import json
import base64
from enum import Enum
import numpy as np
class MessageType(Enum):
"""
Message Type
Message Types that the service can work with.
"""
REGISTER = "REGISTER"
NEW_SESSION = "NEW_SESSION"
NEW_WEIGHTS = "NEW_WEIGHTS"
class Message:
"""
Message
Base cla... |
#!/usr/bin/env python
# coding: utf-8
# In[4]:
import pandas as pd
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
from scipy.stats import norm
import numpy as np
names=['0', '1', '2', '3', '4','5','6','7','8','9','10']
dataset = pd.read_csv("magic04.data",header=0, names=names) #读取csv数据
# print(... |
# Generated by Django 3.1.6 on 2021-06-28 09:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0008_auto_20210626_2013'),
]
operations = [
migrations.AlterField(
model_name='client',
name='contact',
... |
'''
This model recommends the top rated book titles
and runs a pearson correlation book recommendation
system as a starter model.
'''
# Import packages and modules
from src.utilities import *
import pandas as pd
import numpy as np
# Read CSVs
ratings_df = csv('https://markg110.s3-us-west-1.amazonaws.com/data/BX-Book... |
lista = [1,4,5,789,65,34,9,76]
lista_strings = ["Elaine", "Helena", "Anderson"]
print(lista)
print(lista_strings)
#Ordenar a mesma lista
lista.sort()
print(lista)
#Ordena de forma reversa
print(lista_strings)
lista_strings.sort(reverse = True)
print(lista_strings)
#Função sorted exige nova lista para armazenar retor... |
#!/usr/bin/env python3
"""
Orignal configure_vds.py script written by Sean Howard
hows@netapp.com
https://github.com/seanhowardnetapp/pyNSXdeploy/
This script will only work right if run immediately after NDE on a 6 cable setup. The idea is to break up the single
big vswitch into 3 separate ones each with 2 cables.... |
from dataclasses import dataclass
from domain.product.exceptions import InvalidProductException
@dataclass(frozen=True)
class Image:
name: str = None
url: str = None
def __post_init__(self):
if not self.name:
raise InvalidProductException("Product image name is required.")
if... |
# https://helloacm.com/teaching-kids-programming-compute-minimum-absolute-difference-of-two-numbers-in-an-array/
# https://leetcode.com/problems/minimum-absolute-difference/
# EASY, SORTING
class Solution:
def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:
n = len(arr)
arr.sort()
... |
from flask import request, render_template, redirect
from user_app.models.users import User
from user_app import app
@app.route("/")
def main():
return render_template("index.html")
@app.route("/submit", methods=['POST'])
def add_user():
data = {
'first_name' : request.form['first_name'],
'las... |
# -*- coding: utf-8 -*-
from async_pyb import coroutine, sleep, GetRunningLoop, Sleep
class Lights:
# Lights encapsulated a WS2812, and provides a "lattice" model of
# the pixels and a default rendering of them to the leds. This
# lattice model has a default treatment in the rendering, which
# subclas... |
import collections, sys, string, re
from collections import OrderedDict
import string
# Initialization of setups for building the graph
class de_bruijn_vertex:
def __init__(self, unique_kmer_seq, full_seq):
self.outedges = []
self.inedges = []
self.unique_kmer = unique_kmer_seq
sel... |
from typing import List
n: int = int(input())
R: List[int] = []
for _ in range(n):
R.append(int(input()))
maxv: int = R[1] - R[0]
minv: int = R.pop(0)
for r in R:
maxv = max(maxv, r - minv)
minv = min(minv, r)
print(maxv)
|
from scipy import genfromtxt,linspace
from pylab import *
import sys
from glob import glob
datZM = genfromtxt('ZM-kerr.dat')
rhZM = datZM[:,0]
MZM = datZM[:,1]
wZM = datZM[:,-1]
plot(wZM,MZM,'b--',ms=2.5)
V=0
extremalLine = lambda w: sqrt((1.0 - 4.0*V*V + sqrt(1.0+8.0*V*V))/w)/(2.0*sqrt(2.0*w))
ws = linspace(0.64,1,10... |
"""
Exercício Python 082: Crie um programa que vai ler vários números e colocar em uma lista. Depois disso, crie duas listas
extras que vão conter apenas os valores pares e os valores ímpares digitados, respectivamente. Ao final, mostre o
conteúdo das três listas geradas.
"""
def tratar_entrada():
while True:
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-03-11 05:30
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('posts', '0004_post_image'),
]
operations = [
migrations.DeleteModel(
name=... |
#########
# Copyright (c) 2014 GigaSpaces Technologies Ltd. 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... |
import heapq
def solution(jobs):
heap = []
time, start, end = 0, 0, len(jobs)
jobs.sort(reverse=True) # 도착시간 빠른 것이 오른쪽으로, 같으면 수행시간 짧은 것
arrive, long = jobs.pop()
heapq.heappush(heap, (long, arrive))
start = heap[0][1] # 처음 작업의 시작시간
while heap:
cur = heapq.heappop(heap)
... |
import pymysql
db = pymysql.connect(host='localhost',port=3306,user='root',password='951027',db='spiders')
cursor = db.cursor()
data = {
'id':'20120002',
'name':'bob',
'age':22
}
table = 'students'
keys = ','.join(data.keys())
values = ','.join(['%s'] * len(data))
sql = 'insert into {table}({keys}) values(... |
def parse_input_data():
adjacency_list = {}
cycle_length = 0
input_data = input().split(" -> ")
first_vertex = int(input_data[0])
adjacency_list[first_vertex] = [int(x) for x in input_data[1].split(',')]
cycle_length += len(adjacency_list[first_vertex])
try:
while True:
i... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AlipaySecurityRiskBackgroundQueryModel(object):
def __init__(self):
self._params = None
self._partner_name = None
@property
def params(self):
return self._params
... |
#进入testerhome,访问MTSC2020置顶帖,点击目录,点击议题征集范围
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
class Testlianxi():
def setup_method(self):
self.driver = webdriver.Ch... |
def char_freq_table(file_name):
char_table = {}
with open(file_name) as f:
lines = f.readlines()
for line in lines:
line = line.strip()
for char in line:
char_table[char] = char_table.get(char, 0) + 1
for key, value in sorted(char_table.iteritems(), ke... |
'''
DOCSTRING: THIS PROGRAM GENERATES THE FIBONACCI SEQUENCE
'''
#GENERATOR TO CREATE A FIBONACCI SEQUENCE
def gen_fibon(a,b,num):
'''
DOCSTRING: THIS IS A GENERATOR TO GENERATE FIBONACCI SEQUENCE
'''
'''
first_number = 1
second_number = 1
for _ in range(num):
yield f... |
import pygame
import math
import config
import sprites
import audio
import framework.ai as ai
import framework.animations as animations
from framework.ship import Ship
from framework.board import Board
from framework.button import Button
from screens.screen import Screen
from screens.win_screen import WinScreen
from s... |
from free.settings import pool
from video.models import Feedback
from free.settings import logger
import time
def add_play_volume(video_type, video_id):
"""增加某个视频的播放量
用户每点击一次播放按钮,
便向redis数据库更新某个视频的播放量。
Args:
video_type 视频类型
'm':movie / 't':tvseries / 'v':variety / 'a':anime
video_id 视频ID
"""
try:
r = ... |
import hashlib
from django.conf import settings
from django.core.mail import send_mail
from rest_framework import status, viewsets
from rest_framework.decorators import action, api_view
from rest_framework.pagination import PageNumberPagination
from rest_framework.permissions import IsAuthenticated
from rest_framework... |
import app
from utils import get_url
"""
Check if any tracks in the db do not have urls, and query them from the YouTube API
"""
# Connecting to the database file
conn = app.create_connection()
cursor = conn.cursor()
tracks = app.select_all_tracks(conn)
for track in tracks:
if track[9] is "":
_id = get_u... |
from emoji import emojize
from random import choice
from telegram import ReplyKeyboardMarkup, KeyboardButton
import settings
def get_user_emoji(user_data):
if 'smile' not in user_data:
user_data['smile'] = emojize(choice(settings.USER_EMOJI), use_aliases=True)
return user_data['smile']
def get_keyboa... |
#
# simple_adapter/__init__.py - a very simple example service adapter...
#
# Copyright (c) 2017 SingularityNET
#
# Distributed under the MIT software license, see LICENSE file.
#
import logging
from typing import List
from sn_agent.job.job_descriptor import JobDescriptor
from sn_agent.service_adapter import ServiceA... |
from tkinter import *
from tkinter import ttk
import pandas as pd
import csv, sys, os, shutil
import tkinter.messagebox
global id
def load():
try:
selected_item = database.focus() ## get selected item
print(selected_item)
# print(selected_item[])
idval.set(database.item(selected_i... |
# -*- coding: UTF-8 -*-
from django.conf.urls import url
from views import login, logout, users, groups
__author__ = "axu"
urlpatterns = [
# /management/login/
url(r"^login/", login, name="login"),
# /management/logout/
url(r"^logout/", logout, name="logout"),
# /management/users/
url(r"^users... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-09-25 16:24
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sampleapp', '0010_auto_20170925_2152'),
]
operations = [
migrations.AlterFi... |
import uuid as uuid
from datetime import datetime
from typing import List
from django.db import models
from pydantic import BaseModel
class BaseSchema(BaseModel):
# The fields from `models.BaseModelMixin`
uuid: uuid.UUID
created_at: datetime
updated_at: datetime
@classmethod
def from_orms(c... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'smartblue.ui'
#
# Created by: PyQt5 UI code generator 5.14.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_SmartBlueForm(object):
def setupUi(self, SmartBlueForm):
... |
'''
Find all the prime divisors of a number, n
'''
def prime_divisors(n):
orig_n = n
divs = []
i = 2
while i*i <= orig_n:
if n % i == 0:
while n % i == 0:
n /= i
divs.append(i)
i += 1
return divs
if __name__ == '__main__':
assert prime_divisors(18) == [2,3]
assert prime_divisors(2*2*3*3*5*7*7*7*... |
from torchvision import models
import torch.nn as nn
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=dilation, groups=groups, bias=False, dilation=dilation)... |
#!/usr/bin/env python3
import os
import time
import re
from slackclient import SlackClient
from sqlitedict import SqliteDict
from dateutil.relativedelta import relativedelta
import datetime
from websocket import WebSocketConnectionClosedException
# instantiate Slack client
slack_client = SlackClient(os.environ.get('... |
import os
import argparse
import numpy as np
from scipy.io import wavfile as wav
from scipy import signal
import time
EMOTIONS = ['happy', 'neutral', 'angry', 'sad', 'disgust']
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='')
parser.add_argument('--color', type=bool)
args = pa... |
import unittest
from memory.Memory import *
from memory.continuousAssignment.ContinuousAssignment import *
from memory.continuousAssignment.CAPolicies import *
from process.PCB import *
class TestContinuousAssignment(unittest.TestCase):
# Arrange
def setUp(self):
self.pcb1 = PCB(0, 4, BlockHolder(N... |
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Buyer(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="buyer")
numbervalue = models.IntegerField(default=0, null="False")
stringvalue = models.CharField(max_leng... |
# my answer - It is more and less the same as the book answer,
# but mine used str, while the book version used list.
def str_compression_kp(s):
pre_c = ""
counter = 1
result = ""
for character in s:
if pre_c != character:
result += str(counter)
counter = 1
re... |
import dendropy
import sys
import os
def make_control_file(rep_folder, end_folder):
print("[TYPE] NUCLEOTIDE 1")
num_reps = len([i for i in os.listdir(rep_folder) if os.path.isdir(".")])
model_submodel(num_reps)
trees(rep_folder, num_reps)
partitions(num_reps)
evolutions(num_reps, end_folder)
... |
import numpy as np
import sys
ori_dat = np.loadtxt("graphene")
fal_dat = np.zeros((0,4))
lat_vec = [12.29750, 12.78000, 15.00000]
lat_vecs = np.array([[12.29750, 0.00000, 0.00000], [0.00000, 12.78000, 0.00000], [0.00000, 0.00000, 15.00000]])
lat_vecs[0,:] = lat_vecs[0,:] * int(sys.argv[1])
lat_vecs[1,:] = lat_vecs[... |
import json, requests, csv, pandas
def get_data(schedule):
num_games = 0
x = True
z = 0
while x is True:
try:
game = schedule['scoreboard'][0]['games'][num_games]
num_games = num_games + 1
except:
break
for z in range(0, num_games):
date ... |
# -*- coding=utf-8 -*-
from __future__ import absolute_import, print_function
import os
import shutil
import pytest
import vistir
import requirementslib.utils
def check_for_mercurial():
c = vistir.misc.run(["hg, --help"], return_object=True, block=True, nospin=True,
combine_stderr=False... |
# problem : https://leetcode.com/problems/combinations/
# Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
# For example,
# If n = 4 and k = 2, a solution is:
# Solution
# ========
# One of python's inbuilt function makes this problem much easier to solve (ie)
# itertools has... |
import collections
from .simple_wires import solve_simple_wires
from .complicated_wires import solve_complicated_wires
from .symbols import solve_symbols
from .button import solve_button
from .simon_says import solve_simon_says
from .memory import solve_memory
from .password import solve_password
solvers = collectio... |
from dbus_next import PropertyAccess, introspection as intr
from dbus_next.service import method, signal, dbus_property, ServiceInterface
class ExampleInterface(ServiceInterface):
def __init__(self):
super().__init__('test.interface')
self._some_prop = 55
self._another_prop = 101
s... |
'''
给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
示例:
输入: [-2,1,-3, 4,-1,2,1,-5, 4],
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
进阶:
如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解。
'''
class Solution:
def maxSubArray(self, nums) -> int:
if len(nums) == 0: return 0
if len(nums) == 1: return nums[0]
... |
"""
Methods for get clean lines from file
"""
def get_lines_from_file(file_name):
lines = [clean_comment_and_white_spaces(line) for line in open(file_name)]
return delete_empty_lines(lines)
def clean_comment_and_white_spaces(line):
return line.partition('#')[0].replace("\t", "").replace(" ", "").strip()
def d... |
from cosmosis.datablock import option_section, names
import numpy as np
import os
dirname = os.path.split(__file__)[0]
default_data_dir = os.path.join(dirname, "data")
def setup(options):
data_dir = options.get_string(option_section, "data_dir", default_data_dir)
replace_pp = options.get_bool(option_section, ... |
# -*- coding: utf-8 -*-
# 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 law ... |
"""
I adapted some code found at
@ inspired by: https://www.youtube.com/watch?v=Kc1Q_ayAeQk
"""
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import Adherent
def create_adherent(sender, instance, created, **kwargs):
... |
from datetime import datetime, date, time
from google.appengine.ext import ndb
import json
ENTITY_KEY = 'key'
class JsonEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, ndb.Key):
return self.get_value_for_key(o)
elif isinstance(o, ndb.Model):
d = o.to_dict()
if o.key:
... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'UI_zeno_rec.ui'
#
# Created: Tue Sep 16 14:22:45 2014
# by: PyQt4 UI code generator 4.10.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except At... |
import os
#imput
pi=float(os.sys.argv[1])
radio=float(os.sys.argv[2])
#processing
area_circunferencia=(pi*radio)
#output
if(area_circunferencia<=24):
print("esta pequeño")
if(area_circunferencia>30 and area_circunferencia<60):
print("esta mediano")
if(area_circunferencia>65):
print("es grande")
|
from pygments.lexer import RegexLexer, bygroups, include
from pygments.token import Comment, Generic, Keyword, Name, Operator, Punctuation, Text
from sphinx.highlighting import lexers
class PEGLexer(RegexLexer):
"""Pygments Lexer for PEG grammar (.gram) files
This lexer strips the following elements from th... |
import corr
import iadc
import time
import struct
import pylab
SNAPHOST = 'rpi3-2'
BOFFILE = 'extadc_snap_spec_2017-03-07_1741.bof'
print 'Connecting to', SNAPHOST
r = corr.katcp_wrapper.FpgaClient(SNAPHOST)
time.sleep(0.05)
print 'Programming with', BOFFILE
r.progdev(BOFFILE)
adc = iadc.Iadc(r)
# set up for dual-... |
import os
from curio import Kernel
from . import server, abstract
from .http import HTTP, Stream
from .router import Router
AbstractApp = abstract.AbstractApp
h2_server = server.h2_server
def default_get(app):
"""
This function is the default handler for GET request whose :path is registered in the... |
# -*- coding: utf-8 -*-
# encoding: utf-8
"""
__init__.py
Created by Olivier Hardy on 2012-04-17.
Copyright (c) 2012 Olivier Hardy. All rights reserved.
"""
import tornado.web
from tornado import gen
from base import BaseHandler
class ActiveHandler:
active_menu_item = 'dashboard'
class IndexHandler(ActiveHandl... |
from .common import Element, build_request, element, etree
def pieces(data):
root = Element('Pieces')
root.append(element('Weight', data['weight']))
root.append(element('Width', data['width']))
root.append(element('Height', data['height']))
root.append(element('Depth', data['depth']))
return r... |
from flask import Flask, render_template, request, abort, redirect, url_for
app = Flask(__name__)
@app.route('/api/<action>', methods=['GET'])
def apiget(action):
if action == "wishlist":
return render_template("wishlist.html", wishlist=wishlist_dictionary)
elif action == "product":
return re... |
#!/bin/python
from flask import Flask, request
app = Flask(__name__)
@app.route('/')
def hello_world():
return '!!Hola, clase de CDK!!'
@app.route('/saludo/<persona>')
def saludoDinamico(persona):
return 'Hola %s, bienvenido!!!' % persona
@app.route('/cuadrado/<float:num>')
def calculaCuadrado(num):
re... |
import os
import time
import sys
from collect_urls import get_urls
from downloader import download_imgs
# which species of animals do we want?
# we want maximum 5 classes..
bird_species = ['peacock',
'house sparrow',
'european goldfinch',
'emu',
... |
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 06 00:25:19 2021
"""
print(__doc__)
import numpy as np # linear algebra
import pandas as pd #
import matplotlib.pyplot as plt
import seaborn as sns
import time
import xgboost
from timeit import timeit
from sklearn.metrics import accuracy_score
from skl... |
import random
import time
from pprint import pprint
import json
from scripts.m_util import execute_sql_for_dict
OCCUPANCY_SQL= """INSERT INTO occupancy(timestamp, occupancy, cam_label, cubical_label, occupant_coordinates) VALUES (%s, %s, %s, %s, %s)"""
OCCUPANCY_CACHE_SQL = "INSERT INTO occupancy_cache(timestamp, occ... |
# Generated by Django 1.11.20 on 2019-05-06 13:15
from django.db import migrations
from django.db.backends.base.schema import BaseDatabaseSchemaEditor
from django.db.migrations.state import StateApps
def upgrade_create_stream_policy(apps: StateApps, schema_editor: BaseDatabaseSchemaEditor) -> None:
Realm = apps.... |
import sounddevice as sd
import matplotlib.pyplot as plt
import numpy as np
import math
fs = 2**12 # sample rate
tp = 4 # sampling duration
N = fs*tp # number of samples
def fft(f):
Ni = len(f)
Mi = int(Ni / 2)
if Mi <= 2:
return [f[0] + f[1] + f[2] + f[3],
f[0] - 1j*f[1] - f[2] + 1... |
inval = input().split(';')
print(0)
initx = 0
inity = 0
for i in inval:
if i[0] == 'A':
initx -= int(i[1:])
if i[0] == 'D':
initx += int(i[1:])
if i[0] == 'W':
inity += int(i[1:])
if i[0] == 'S':
inity -= int(i[1:])
else:
continue
print(str(initx) + ',' ... |
# -*- coding:utf-8 -*-
import math
class Solution:
# ans = n / 5 + n / 25 + n / 125 + ...
def trailingZeroes(self, n: int) -> int:
ans = 0
while n > 0:
ans += n // 5
n = n // 5
return ans
if __name__ == '__main__':
n = 25
ans = Solution().trailingZero... |
from django.db import connection
from django.template import Template, Context
from django.conf import settings
#
# Log all SQL statements direct to the console (when running in DEBUG)
# Intended for use with the django development server.
#
class SQLLogToConsoleMiddleware:
def process_response(self, request, res... |
from gnuradio import gr as _gr
from gnuradio import uhd as _uhd
import thread as _thread
import time as _time
import numpy as _n
class _data_buffer(_gr.sync_block):
"""
A simple GNU Radio data buffer.
"""
def __init__(self, size=1000, channels=2):
"""
Thread-s... |
# needed modules
import os
import json
from zipfile import ZipFile
from biopandas.pdb import PandasPdb
from rdkit import Chem
import pandas as pd
# needed input
'''
path_to_pdb_file = '../../data/pdb_files_edited/P0A6I3/1SQ5_ADP.pdb'
complex_id = '1SQ5_ADP'
path_to_reference = '../../data/optimized_ligands/P0A6I3/1SQ... |
# Authors : Zavala Jose, Tates Alberto
#
import pandas as pd
import numpy as np
import os
import re
import mne
import matplotlib.pyplot as plt
from sklearn.decomposition import FastICA, PCA
from sklearn.preprocessing import StandardScaler
from mne.decoding import UnsupervisedSpatialFilter
from mne import create_info
fr... |
"""
该模块主要模拟spider的运动并进行仿真
"""
from spider_object import *
class MoveScript(object):
def __init__(self, state: dict, next_state: dict):
"""
:param state: 目前所在状态,字典。字典含{position:[,] , forward: ,state ,height} 用于表述当前位置与下一时刻方向与状态
注:0为暂停态,1为1,3,5固定,2为2,4,6固定不变
:param next_state: 目标状态,字典... |
string = raw_input()
found = False
sum = 0
letters = [0 for x in range(0, 26)]
for letter in string:
letters[ord(letter) - 97] += 1
for x in range(0, 26):
sum = sum + (letters[x]%2)
if sum >= 2:
print("NO")
else:
print("YES")
|
#!/usr/bin/env python
# Syscall Tracer Tool
# authors: Michael Jantz
import sys
import os
import optparse
import tempfile
import subprocess as sp
import signal
from pykusp import taskalias
from datastreams import dski
from datastreams import dsui
from datastreams.postprocess import pipeline
class traceme():
def __i... |
from django.http import HttpResponse
from channels.handler import AsgiHandler
from channels import Group
from channels.sessions import channel_session, enforce_ordering
import os
import string
import json
from django.core import serializers
from jukebox.models import JukeboxUser, Video
from django.forms.models import m... |
class CalculadoraDeImpostos():
def calcular(self, valor, imposto):
valor_a_pagar = imposto.calcula(valor)
return valor_a_pagar
def main():
from strategy_pattern.strategy import ICMS, ISS, PIS
receita_produto = 50000
receita_servico = 80000
calculadora = CalculadoraDeImpostos()
... |
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 4 01:32:08 2020
@author: Cristian Camilo Arango Fernández
"""
# Programa para calcular el valor del pasaje de un avión
# dependiendo de la cantidad de los km del recorrido
print("Cálculo del valor del tiquete de avión")
# ENTRADA DE DATOS POR CONSOLA.
km=float(input("I... |
from django.contrib import admin
from .models import Choice, Poll, Answer
class ChoiceInline(admin.TabularInline):
model = Choice
extra = 3
class PollAdmin(admin.ModelAdmin):
inlines = [ChoiceInline]
list_display = 'question', 'active'
list_filter = 'active',
search_fields = 'question',
... |
from django.conf.urls import patterns, include, url
from rest_framework_mongoengine import routers
from amspApp.BpmnModeler.views import BpmnModelerView
router = routers.SimpleRouter()
router.register(r'bpmns', BpmnModelerView.BpmnViewSet,base_name='bpmns')
urlpatterns = patterns(
'',
# ... URLs
url(r'^... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.