text stringlengths 8 6.05M |
|---|
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import shlex
from dataclasses import dataclass
from pathlib import Path
from typing import Tuple
from pants.core.util_rules import external_tool
from pa... |
#coding=utf-8
#created by SamLee 2020/3/6
import os
import sys
import math
from elftools.elf.elffile import ELFFile
import zipfile
import tempfile
import shutil
import struct
import entropy
from concurrent.futures import ThreadPoolExecutor
import threading
from queue import Queue
import time
import multiprocessing
imp... |
"""
@description: 执行训练
"""
"""
import
"""
from config import ConfigTrain
import utils
from os.path import join as pjoin
import pandas as pd
import numpy as np
import cv2
import torch
import time
"""
main
"""
if __name__ == '__main__':
cfg = ConfigTrain()
print('Pick device: ', cfg.DEVICE)
device = torch... |
'''
Susan Hohenberger and Brent Waters (Pairing-based)
| From: "Constructing Verifiable Random Functions with Large Input Spaces"
| Published in: ePrint
| Available from: http://eprint.iacr.org/2010/102.pdf
| Notes: applications to resetable ZK proofs, micropayment schemes, updatable ZK DBs
and verifiable tr... |
###MODULES###
import numpy as np
import pandas as pd
import os, sys
import time as t
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
from matplotlib.ticker import MaxNLocator
import pathlib
from matplotlib.colors import Normalize
from scipy import interpola... |
import numpy as np
import pytest
from napari._qt.widgets.qt_color_swatch import (
TRANSPARENT,
QColorSwatch,
QColorSwatchEdit,
)
@pytest.mark.parametrize('color', [None, [1, 1, 1, 1]])
@pytest.mark.parametrize('tooltip', [None, 'This is a test'])
def test_succesfull_create_qcolorswatchedit(qtbot, color, ... |
# -*- encoding:utf-8 -*-
# __author__=='Gan'
# Given preorder and inorder traversal of a tree, construct the binary tree.
# Note:
# You may assume that duplicates do not exist in the tree.
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left ... |
from functools import partial
from operator import itemgetter
import numpy as np
from django.core.management import BaseCommand
from web.models import NotionDocument
from web.services.bert_service.read import get_bert_client
from web.services.notion_service.read import get_notion_client
from web.services.notion_servi... |
# Copyright 2023 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import json
from unittest.mock import Mock, patch
import pytest
from generate_json_schema import (
GENERATED_JSON_SCHEMA_FILENAME,
VERSION_MAJOR_MINOR,
main,
simplify_optio... |
#!/usr/bin/env python
"""
Small hack to iterate over all Wistar bridges and enable LLDP/LACP
(see https://github.com/Juniper/wistar/issues/12)
"""
import subprocess
import re
# return all bridges that contain _br*
BR_INFO = subprocess.Popen("ifconfig | grep _br", shell=True, stdout=subprocess.PIPE).stdout.read()
# re... |
# Generated by Django 3.2.7 on 2021-10-06 17:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('lab', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='researchpaper',
name='year',
... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'Type.ui'
#
# Created by: PyQt4 UI code generator 4.12.1
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui,uic
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
... |
import numpy as np
import math
import torch
from torch.autograd import Function
class MaxDivideMin(Function):
@staticmethod
def forward(ctx, input_rep, coef, count=None, f=None, logger=None):
"""
calculate the condition number
:param ctx:
:param input_rep: (batch, dim_represen... |
# coding=utf-8
"""A serializer that extends pickle to change the default protocol"""
from __future__ import absolute_import
from .. import common
import pickle
protocol = common.select_pickle_protocol()
def dump(value, fp, sort_keys=False):
"Serialize value as pickle to a byte-mode file object"
... |
import board
import neopixel
import time
pixels = neopixel.NeoPixel(board.D18, 20)
for i in range(0):
pixels[i] = (255,69,0)
time.sleep(.1)
for x in range(20):
pixels[x] = (255,69,0)
time.sleep(.25)
|
import pygame
from pygame.locals import *
from shapes import Entity, RandEnt
# BLUE = (0, 0, 255)
# width, height = 300, 400
# screen = pygame.display.set_mode((width, height))
# background_color = (255, 255, 255)
# screen.fill(background_color)
# p = RandEnt()
# print(p.x)
# print(p.y)
# p.draw(... |
"""Protocol Port Objects Class."""
from fmcapi.api_objects.apiclasstemplate import APIClassTemplate
import logging
import warnings
class ProtocolPortObjects(APIClassTemplate):
"""The ProtocolPortObjects in the FMC."""
VALID_JSON_DATA = ["id", "name", "description", "port", "protocol", "type"]
VALID_FOR_... |
import pandas as pd
import func
import sys
track_length = 3900
filename = 'Times.csv'
df = pd.read_csv(filename)
print('Type "help" to see available commands')
user_input = input('').upper()
while True:
df.drop(df.filter(regex="Unnamed: "), axis=1, inplace=True)
if user_input == 'HELP':
df.drop(df.filt... |
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 29 15:43:39 2019
This is a copy of the DC Eigen vector code, however, I am trying to paralelize it to run moore efficiently using Numba and the solution provided through stack overflow.
@author: matthewmorriss
"""
import numpy as np
import numba as nb
#
#@nb.njit()
#def ... |
import sys
import pytest
import itertools
from models import *
from utils import assert_queries_equal, assert_query_count
from peewee import ModelQueryResultWrapper
from peewee import NaiveQueryResultWrapper
from aiopeewee.result import (AioNaiveQueryResultWrapper,
AioModelQueryResultWra... |
import json
import numpy as np
import plotly.graph_objects as go
from dash import callback_context, dcc, html
from dash.dependencies import ALL, Input, Output
from rubicon_ml.viz.base import VizBase
from rubicon_ml.viz.common import dropdown_header
from rubicon_ml.viz.common.colors import get_rubicon_colorscale, ligh... |
import numpy as np
def get_index(components, percentile=20):
stds = []
std = components.reshape(-1, 200, 4).transpose(1, 0, 2).reshape(-1, 4*200).std(axis=1)
threshold = np.percentile(std, percentile)
usable_index = np.where(std > threshold)
print("X_COLUMN:", len(usable_index[0]), threshold)
r... |
# Generated by Django 2.2.13 on 2020-07-10 07:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('product', '0009_auto_20200710_1238'),
]
operations = [
migrations.AlterField(
model_name='product',
name='discount_... |
'''
@Description: BinaryTree Library
@Date: 2020-06-04 00:02:32
@Author: Wong Symbol
@LastEditors: Wong Symbol
@LastEditTime: 2020-07-10 22:18:31
'''
class TreeNode():
def __init__(self, data=None):
self.data = data
self._left = None
self._right = None
def add2left(self,new_no... |
from common.run_method import RunMethod
import allure
@allure.step("JkyApp/登录")
def employee_login_post(params=None, body=None, header=None, return_json=True, **kwargs):
'''
:param: url地址后面的参数
:body: 请求体
:return_json: 是否返回json格式的响应(默认是)
:header: 请求的header
:host: 请求的环境
:return: 默认json格式的响应... |
# -*- python -*-
from Product import *
class Store(object):
def __init__( self, owner, location ):
self.owner = owner
self.location = location
self.products = []
def add_product( self, product ):
self.products.append( product )
return( self )
def remove_product( ... |
# 有1、2、3、4个数字,能组成多少个互不相同且无重复数字的三位数?都是多少?
count = 0
for i in range(1, 5):
for j in range(1, 5):
for k in range(1, 5):
if i != j and i != k and j != k:
count += 1
print ("%d%d%d" % (i, j, k))
print("%d 种可能" % count)
# i, j, k 分别代表个位十位百位上的数字 |
# Copyright (c) 2013 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'make_global_settings': [
['CC', '/usr/bin/clang'],
['CXX', '/usr/bin/clang++'],
],
'targets': [
{
'target_name': 'aliasing_yes',
'... |
import unittest
from katas.beta.fix_the_base_conversion_function import convert_num
class ConvertNumTestCase(unittest.TestCase):
def test_equal_1(self):
self.assertEqual(convert_num(12463, ['num']), 'Invalid base input')
def test_equal_2(self):
self.assertEqual(convert_num(122, 'bin'), '0b11... |
import pandas as pd
import pickle
vehicles = []
csv = pd.read_csv('../vehicles.csv')
for _, row in csv.iterrows():
vehicles.append(
{
'VIN': row[0],
'TrainID': row[1],
'Cabin': row[2],
'Seat': row[3],
'Transit': row[4]
}
)
pickle.dump... |
from django.conf.urls import url
from . import views
app_name = 'active_learning'
urlpatterns = [
url(r'^$', views.iframe, name='iframe'),
url(r'^article$', views.index, name='index'),
url(r'^article/(?P<article_id>[0-9]+)/$', views.detail, name='detail'),
url(r'^learn$', views.learn),
url(r'^push... |
# examples of exception handling
# a few types of common errors
# print(yana) # NameError
# print(1 + 'yana') #TypeError
# handle errors using "try...except" blocks
"""
try:
statements
...
except ExceptionName:
statements evaluated in case ExceptionName happens
"""
# an example
def ... |
import os
from os import listdir
from os.path import isfile, join
def rename_file(path):
onlyfiles = [f for f in listdir(path) if isfile(join(path, f))]
print onlyfiles
os.chdir(r'C:\Users\Administrator\Desktop\prank')
for file in onlyfiles:
print ("old name - "+file)
print ("new name ... |
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path("fb-login/", views.SignInView.as_view()),
]
|
#!/usr/bin/env python
import pygame
import mimo
from utils import utils
from utils import neopixelmatrix as graphics
from utils.NeoSprite import NeoSprite, AnimatedNeoSprite, TextNeoSprite, SpriteFromFrames
from utils import constants
from scenes.BaseScene import SceneBase
# Introduction Scene
# Available actions: ... |
class Rectangle:
def __init__(self, x, plane):
self.x = x
self.y = x
self.xy_plane = plane
self.user_input()
self.draw_shape_chosen()
self.draw_graphic_plane()
def user_input(self):
while True:
xdim = int(input("Enter x dimension: \n"))
ydim = int(input("Enter y dimension: \n"))
if xdim < 20 a... |
#! /usr/bin/python
import numpy as np
import xgboost as xgb
# label need to be 0 to num_class -1
# if col 33 is '?' let it be 1 else 0, col 34 substract 1
# data = np.loadtxt('data/201504_train.csv', delimiter=',')
# sz = data.shape
#
# train = data[:int(sz[0] * 0.7), :] # take row 1-256 as training set
# test = data... |
o = object()
print()
print(o)
print(".. 以上是 object 型態物件的字串形式")
print()
print("程式結束 ....")
print()
|
n, k, l, c, d, p, nl, np = map(int, input().split())
total_drink = k * l
total_slice = c * d
print(min([total_drink//(n*nl), total_slice//(1*n), p//(n * np)]))
|
"""
Django settings for {{ cookiecutter.project_name }} project.
"""
from os import environ
from os.path import abspath, basename, dirname, join, normpath
from pathlib import Path
from sys import path
# PATH CONFIGURATION
BASE_DIR = Path(__file__).resolve(strict=True).parent.parent.parent
# Absolute filesystem path to... |
#import modules
from keras.models import Model
from keras.layers import Input, LSTM, Dense
import os
import numpy as np
def convert_to_onehot( c ):
tensor = np.zeros(128)
tensor[ord(c)] = 1
return tensor
code_tensors = []
vocab = set()
comments_dict = {}
comments = []
file_path = 'code'
for root,dirs,f... |
#Usage: python predict-multiclass.py
#https://github.com/tatsuyah/CNN-Image-Classifier
import os
import numpy as np
from keras.preprocessing.image import ImageDataGenerator, load_img, img_to_array
from keras.models import Sequential, load_model
img_width, img_height = 150, 150
model_path = './models/model.h5'
model_w... |
import os
import sys
import winreg as reg
# Get path of current working directory and python.exe
cwd = os.getcwd()
python_exe = sys.executable
# optional hide python terminal in windows
hidden_terminal = '\\'.join(python_exe.split('\\')[:-1])+"\\pythonw.exe"
# Set the path of the context menu (right-click menu)
key... |
#!/usr/local/bin/python3
# -*- conding: utf-8 -*-
from app import create_app
# 生成app
app = create_app()
if __name__ == '__main__':
app.run('0.0.0.0', 8432, debug=True) |
import numpy as np
import tensorflow as tf
import os, sys, random, csv
def linear(x, output_size, name=None, nonlinearity=tf.nn.relu):
print("linear layer", x.get_shape()[1],"->", output_size, name)
input_size = x.get_shape().as_list()[1]
with tf.variable_scope(name or 'linear_layer', reuse=False):
W = tf.get_va... |
#!/usr/bin/env python
import moksha.ctl.core.main as main
if __name__ == '__main__':
main.main(entry_point=False)
|
import numpy as np
import matplotlib.pyplot as plt
import sys
sys.path.insert(0,"../..")
from equation6 import Shell
import argparse
import seaborn as sns
###################################
"""
The objective of this program is
#to make a figure that illustrates
how the shell shape change... |
"""
Created by Alex Wang
On 2018-11-30
"""
import traceback
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn import decomposition
from sklearn import datasets
def test_pca():
np.random.seed(5)
centers = [[1, 1], [-1, -1], [1, -1]]
iris = datasets.l... |
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
class ExtrasPage:
def __init__(s... |
from main import WKhtmlToPdf, wkhtmltopdf
import api
|
from abc import ABCMeta, abstractmethod
import logging
from random import randrange
import sys
from bitarray import bitarray
from indigox.config import (INFINITY, RUN_QBND, BASIS_LEVEL, ALLOW_HYPERVALENT,
ELECTRON_PAIRS, HYPERPENALTY, PREFILL_LOCATIONS,
COUNTERP... |
# Base Vehicle:
class Vehicle:
# Constructor
def __init__(self, owner):
self.owner = owner
def get_owner(self):
return self.owner
# Methods in which every subclass will be required to implement.
def top_speed(self):
raise NotImplementedError("Subclass is ... |
import sys
import json
import h5py
import numpy as np
def json_parameter_lists_from_chain(json_dict,n_sigma=3):
"""
Read in chain data and compute parameter stats and bounds
"""
# obtain number of parameters to estimate stats and limits for
model_type = json_dict["mcmcopts"]["model_type"]
np... |
# Generated by Django 3.2.4 on 2021-07-12 20:11
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('churrasco', '0003_alter_produto_nome'),
]
operations = [
migrations.CreateModel(
name='Informac... |
from collections import defaultdict, deque, Counter
from heapq import heapify, heappop, heappush
import math
from copy import deepcopy
from itertools import combinations, permutations, product, combinations_with_replacement
from bisect import bisect_left, bisect_right
import sys
def input():
return sys.stdin.readl... |
#test4.1.py
for i in range(1,10):
for j in range(10):
for k in range(10):
for n in range(10):
if i**4+j**4+k**4+n**4==1000*i+100*j+10*k+n:
print('{}{}{}{}'.format(i,j,k,n))
'''
s = ""
for i in range(1000, 10000):
t = str(i)
if pow(eval(t[0]),4) + pow... |
# File: hw3_part3.py
# Author: Joel Okpara
# Date: 2/21/2016
# Section: 04
# E-mail: joelo1@umbc.edu
# Description: This program guesses what character the user is thinking of
def main():
#This segment checks if the character is a woman
woman = input("Is your character a woman?(y/n)")
if woman == "y":
... |
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 21 00:14:54 2020
@author: Meng
"""
import pandas as pd #pandas处理数据
import seaborn as sb
import matplotlib.pyplot as plt
import numpy as np #numpy数学函数
from sklearn.linear_model import LinearRegression #导入线性回归
from sklearn.model_selection import KFold #导入交叉验证
... |
from django.test import TestCase
from .models import Tutorial
class TutorialTestCase(TestCase):
def setUp(self):
Tutorial.objects.create(title="this is a title")
Tutorial.objects.create(title="this is a title")
def test_check_slugs(self):
object_1 = Tutorial.objects.get(pk=1)
... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import pytest
from pants.backend.kotlin.compile import kotlinc_plugins
from pants.backend.kotlin.compile.kotlinc import rules as kotlinc_rules
from pant... |
import pprint
def raj_template_dump():
dump_array = [{
"type": "movies",
"modes": [
"top250",
"random",
"list all movies",
"my fav movies"
]
}, {
"type": "books",
"modes": [
"popular",
"random",
... |
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import string
import itertools as it
def comp_words(word1, word2):
singleton_presence = 0
letter_pairs = set((map(frozenset, zip(word1, word2))))
for lp in letter_pairs:
if len(lp) == 1:
singleton_presence = singleton_presence + 1
if ... |
# appconfig - remote control for DLCE apps
import pathlib
from . import config
__all__ = ['PKG_DIR', 'APPS_DIR', 'CONFIG_FILE', 'APPS']
PKG_DIR = pathlib.Path(__file__).parent
APPS_DIR = PKG_DIR.parent / 'apps'
CONFIG_FILE = APPS_DIR / 'apps.ini'
APPS = config.Config.from_file(CONFIG_FILE)
# TODO: consider http... |
from os import path, mkdir
import json
from datetime import datetime
from modules.logmanager import LogManager
from modules.navigationmanager import NavigationManager
from modules.datamanager import DataManager
from multiprocessing import Process
def retrieve_incremental_cases_info_from_url(urlToBeRequested, startingU... |
class ShelfNotAvailable(Exception):
""" Custom exception for signalizing a case when item not available on
product's shelf
"""
pass
|
import numpy as np
from tensorflow.keras.applications import VGG16
IMG_SIZE=128
model = VGG16(include_top=False, weights="imagenet",\
input_shape=(IMG_SIZE,IMG_SIZE,3), pooling="ave")
for layer in model.layers:
layer.trainable = False
#データの読み込み
in_npy = "gen_fig.npy"
data = np.load(f"./{in_np... |
import requests
import os
import gitlab
import sys
import configparser
gitlab_url = None
gitlab_private_token = None
gitlab_file = os.environ.get('GITLAB_CREDENTIALS', None)
if gitlab_file:
config = configparser.ConfigParser()
try:
config.read(gitlab_file)
gitlab_url = config["GITLAB"]["GITLAB... |
from utils.function.setup import *
from utils.lib.user_data import *
from main.activity.desktop_v3.activity_login import *
from main.activity.desktop_v3.activity_logout import *
from main.activity.desktop_v3.activity_user_settings import *
import unittest
class TestNotification(unittest.TestCase):
#Instance
_s... |
# -*- coding: utf-8 -*-
SPECIAL_PRICE = 40
IS_NEW = 42
RECOMMEND_PRICE = 10
BY_ORDER = "Под заказ"
EMPTY_STRING = ""
DOUBLE_DASH = "--"
|
#!/usr/bin/python3
import json
import typing
import argparse
from classes import Student, Room
from controllers import FilesController, DBController
from models import Model
def get_input_arguments():
parser = argparse.ArgumentParser(description='give 3 arguments - path to students.json, path to rooms.json, outpu... |
# coding: utf-8
import redis
import json
import hashlib
import urllib.parse
import lglass.database.base
import lglass.rpsl
@lglass.database.base.register("redis")
class RedisDatabase(lglass.database.base.Database):
""" Caching database layer which uses redis to cache the objects and search
results, but without red... |
# network = input("enter network id: ")
# subnet = list(map(int,input("enter subnet id: ").split('.')))
from prettytable import PrettyTable
def dec_to_bin(x):
return int(bin(x)[2:])
def bin_to_dec(n):
return bin(n).replace("0b", "")
x = PrettyTable()
is_cidr = input('is you network include CIDR? Y/n: ')
... |
# -*- coding: utf-8 -*-
class Solution:
def strWithout3a3b(self, A, B):
if A >= 2 * B:
result = ["aab"] * B + ["a"] * (A - 2 * B)
elif A >= B:
result = ["aab"] * (A - B) + ["ab"] * (2 * B - A)
elif B >= 2 * A:
result = ["bba"] * A + ["b"] * (B - 2 * A)
... |
print('Hello')
#создадим список и сразу выводим его
spisok2 = ['Gosha','Max','Denis']
print(spisok2)
#Добавим в список переменную
spisok2.append('Alex')
print(spisok2)
#создадим ещё один список и добавим всё его содержимое в первый
spisok1 = ['Gordon']
spisok2.extend(spisok1)
print(spisok2)
#удаляем из списка конкре... |
import argparse, logging, json, sys
from ..algorithms.utils import get_blocks_shape, get_named_volumes, numeric_to_3d_pos, get_theta
DEBUG=False
def compute_max_mem(R, B, O, nb_bytes_per_voxel):
""" Algorithm to compute the maximum amount of memory to be consumed by the keep algorithm.
"""
buffers_partiti... |
import logging
import random as rand
from enum import Enum
import numpy as np
from numpy import array as arr
from numpy import concatenate as cat
import scipy as sy
import scipy.io as sio
from scipy.misc import imread, imresize
pred = sio.loadmat('predictions.mat')
pred = pred['joints']
mlab = sio.loadmat('dataset.m... |
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
context = {'username': 'Keith Yue'}
return render(request, 'test.html', context)
def test_bootstrap(request):
return render(request, 'bootstrapSample.html')
|
#!/usr/bin/python
import os
import time
f = open("all.txt",'r+a')
f.write("hello file")
print(f.readline())
|
import os
import threading
import time
from concurrent.futures.thread import ThreadPoolExecutor
from urllib.parse import urlencode
import chardet
import redis
import requests
from soupsieve.util import string
from Cookie_pool.account_saver import RedisClient
CONN = RedisClient('account', 'pkulaw_v5')
NUM = 16
pool ... |
__author__ = 'aoboturov'
import networkx as nx
def session_transition_graph(ds):
g = nx.Graph()
url_id_idx = ds.columns.get_loc('url') + 1
referrer_idx = ds.columns.get_loc('referrer') + 1
layer_idx = ds.columns.get_loc('layer') + 1
order_price_idx = ds.columns.get_loc('order_price') + 1
fo... |
# list of question
questions_list = ['האם חדשנות טובה לכלכלה? : ',
'האם וודגווד היה בעל מפעל לכלי חרס? : ',
'האם ניהול וטכנו זה מעפן? : ']
admin_answers_list = ['yes', 'yes', 'no']
user_answers_list = []
right_answers = []
for i in range(len(questions_list)):
user_answers_list.a... |
import csv
import json
import pathlib
import pandas as pd
import os
"""
This script convert .json file to .csv using Pandas
Input: All .json files in current directory
Output: .csv converted files to current directory
"""
# list all files in the directory
json_filenames = [' ']
for i in os.listdir():
if i.endsw... |
from pymel.core.datatypes import Vector
from pymel.util import path
from functools import partial
import maya.cmds as cmds
import pymel.core as pm
class BaseDragger(object):
def __init__(self, name="pbDragger", title="Base", default_value=0,
min_value=None, max_value=None, multiplier=0.01, cursor... |
# Generated by Django 2.2 on 2019-10-19 17:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0007_auto_20191018_1809'),
]
operations = [
migrations.AddField(
model_name='pedidos',
name='finalizado',
... |
print('Converte graus Celsius para Farenheit')
celsius = float(input('Informe os graus em Celsius: '))
farenheit = (celsius * 9 / 5) + 32
print('Convertidos, são {:.1f} graus Farenheit'.format(farenheit))
|
#como saber o resto de uma divisao
print (6%2)
print (2%3)
print (4%2)
print (5%2)
print (7%3.1)
print (900%100 == 0)
num1 = float(input("Digite um numero: "))
num2 = float(input ("Digite outro numero: "))
resultado = num1 / num2
resto = num1 % num2
print (num1, "dividido por ",num2," resulta em", resultado)
print ... |
#coding:utf-8
import CRFPP
import os
tagger = CRFPP.Tagger('-m '+ os.path.join('data','address_model'))
def crf_segmenter(address_str):
tags_list = []
tagger.clear()
for word in address_str:
tagger.add(word.encode('utf-8'))
tagger.parse()
size = tagger.size()
xsize = tagger.xs... |
import datetime
from django.db import models
from django.utils import timezone
from accounts.models import Person
# Coupon Class Specifier
class Coupon(models.Model):
owner = models.ForeignKey(
Person,
on_delete=models.CASCADE,
editable=False)
title = models.CharField(max_length=100)
... |
from django.contrib import admin
from .models import Cryptocurrency
admin.site.register(Cryptocurrency)
|
# def listsum(numList):
# theSum = 0
# for i in numList:
# theSum = theSum + i
# return theSum
# print(listsum([1,3,5,6,10,2000]))
#tast1
#Write a function called display_message() that prints one sentence telling everyone what you are learning about in this chapter.
#Call the function, and make... |
from django.shortcuts import get_object_or_404,render
from django.http import HttpResponse,HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.template import Context, loader
from polls.models import *
# Create your views here.
# def index(request):
# latest_poll_list = Poll.objects.order_by... |
"""
이코테 p303
선수 강의가있다.
ex) 알고리즘 강의의 선수강의로 자료구조와 컴퓨터 기초가 있다면 자료구조, 컴퓨터 기초를 모두 들은 후 알고리즘 강의를 들을수 있다.
총 N개의 강의를 듣고자 한다.
동시에 여러 강의를 들을수 있다.
첫번째 줄에 듣고자 하는 강의의 수 N(1 <= N <= 500)이 주어진다.,
다음 N개의 줄에는 강의의 시간과 강의를 듣기 위해서 먼저 들어야하는 강의들의 번호가 자연수로 주어진다.
각 강의번호는 1부터 N까지로 구성되며 각 줄은 -1로 끝난다
5
10 -1
10 1 -1
4 1 -1
4 3 1 -1
3 3 -1
... |
def reverse(string):
stringList = string.split()
stringList.reverse()
newString = " ".join(str(x) for x in stringList)
return newString
arg = raw_input()
res = reverse(arg)
print res
|
import turtle
turtle.speed(-1)
width = 60
xRef = -4 * width
yRef = -4 * width
def draw_squre(x, y):
turtle.goto(x + xRef, y + yRef)
turtle.begin_fill()
turtle.down() # "Pen" down?
for i in range(4): # For each edge of the shape
turtle.forward(width) # Move forward 40 units
turtle... |
#!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verify that the xcode-ninja GYP_GENERATOR runs and builds correctly.
"""
import TestGyp
import os
import sys
if sys.platform == 'darw... |
from django.contrib import admin
from asignacionc.models import Alumno, AlumnoAdmin, Materia, MateriaAdmin
admin.site.register(Alumno, AlumnoAdmin)
admin.site.register(Materia, MateriaAdmin)
|
import os,sys
sys.path.append("/Users/twongjirad/working/uboone/vireviewer")
from vireviewer import getmw
import numpy as np
import pandas as pd
from channelmap import getChannelMap
from hoot import gethootdb
from pyqtgraph.Qt import QtCore, QtGui
import pyqtgraph as pg
import math
def get_pulsed_list(run):
f = op... |
# import discord
from redbot.core import commands
class Greetings(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_member_join(self, member):
channel = self.bot.get_channel(971361677348044862) # the channel ID
await channel.send(f"Welc... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 28 22:51:33 2018
@author: shooter
"""
import dash
import dash_core_components as dcc
import dash_html_components as html
token = 'pk.eyJ1Ijoicm9iaW5zdW5ueSIsImEiOiJjam50Nmh3ZW0wcW9zM3BwNmRjcjgyNjJ3In0.BL1Gs2sYSrUkEJ7soat4jg'
app = dash.Dash()... |
from io import StringIO
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import scipy.stats as stats
import numpy as np
from sklearn import preprocessing, tree
from sklearn.tree import export_graphviz
from sklearn.model_selection import train_test_split
from scipy.stats import chi2
from sklearn... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.