text stringlengths 8 6.05M |
|---|
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten
from tensorflow.keras.optimizers import Adam
# 케라스에서 MNIST데이터 셋을 다운로드
fashion_mnist = tf.keras.datasets.fashion_mnist
# 데이터 셋을 트레이닝 셋과 테스트 셋으로 ... |
from django.db import models
class ModelWithBasicField(models.Model):
name = models.CharField(max_length=32)
class Meta:
app_label = 'testapp'
def __unicode__(self):
return u'%s' % self.pk
class ModelWithParentModel(ModelWithBasicField):
foo = models.BooleanField(default=False)
... |
"""
i18n regions resource implementation.
"""
from typing import Optional, Union
from pyyoutube.resources.base_resource import Resource
from pyyoutube.models import I18nRegionListResponse
from pyyoutube.utils.params_checker import enf_parts
class I18nRegionsResource(Resource):
"""An i18nRegion resource iden... |
#!/usr/bin/env python
import sys
import simplep2p as s
peer_count = s.get_peer_count()
if peer_count == 0:
print "FAIL: no peers"
sys.exit(1)
response_count = s.send_message_to_peers("hello_there")
if response_count == peer_count:
print "PASS"
else:
print "FAIL"
sys.exit(1)
|
import unittest
from employee import Employee
<<<<<<< HEAD
from unittest.mock import patch # we can use patch as a decorator or as a context manager
# patch allows us to mock an object during a test and then that object is automatically restored after the test is run.
=======
from unittest.mock import patch # can be ... |
import argparse
import copy
import json
import os
import platform
import socket
import time
import traceback
from queue import Queue
from base64 import b64encode, b64decode
import requests
class OperationLoop:
def __init__(self, server, es_host='http://127.0.0.1:9200', index_pattern='*',
result... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 15 12:11:43 2020
@author: adeela
"""
'''
## Given data of intervals, find overlaping intervals
## x1, 9:30
## x1, 10:00
## x2, 11:00
## x2, 12:00
## y1, 11:30
## y1, 01:00
In this data x2 and y1
x1(9:30, 10:00), x2(11:00, 12:00),
y1(11:30, 01:0... |
import os
def isValidPath(filePath):
if os.path.exists(filePath):
pass
elif os.access(os.path.dirname(filePath), os.W_OK):
pass
else:
return False
return True |
import autodisc as ad
def get_system_parameters():
system_parameters = ad.systems.Lenia.default_system_parameters()
system_parameters.size_y = 256
system_parameters.size_x = 256
return system_parameters
def get_explorer_config():
explorer_config = ad.explorers.OnlineLearningGoalExplorer.defaul... |
# coding:utf-8
# 除非显示说明,否则np.array()会尝试为新建的数组推断出一个较为合适的数据类型。
# 数据类型保存在一个特殊的dtype()对象中
# 1. 一个列表的转换
import numpy as np
import matplotlib.pyplot as plt
data = [1, 2, 3, 4, 5, 6]
arr1 = np.array(data)
print(arr1)
# shape: 表示维度大小的数组; dtype:用于说明数组数据类型的对象
print("arr1.shape:{0},\narr1.dtype:{1}".format(arr1.shape, arr1.dtype... |
import xmltodict
with open('sample.xml', 'r', encoding='utf-8') as fp:
root = xmltodict.parse(fp.read(), dict_constructor=dict)
sample = root['root']
sample['items']['item'][0]['amount'] = 200
if not sample['items']['item'][0]['owner']:
sample['items']['item'][0]['owner'] = 'alice'
sampl... |
import cx_Oracle
import threading
from urllib import urlopen
#subclass of threading.Thread
class AsyncBlobInsert(threading.Thread):
def __init__(self, cur, input):
threading.Thread.__init__(self)
self.cur = cur
self.input = input
def run(self):
blobdoc = self.input.read()
self.cur.execute("INSE... |
#!/usr/bin/python3
#
# Python script that regenerates the README.md from the embedded template. Uses
# ./generate_table.awk to regenerate the ASCII tables from the various *.txt
# files.
from subprocess import check_output
nano_results = check_output(
"./generate_table.awk < nano.txt", shell=True, text=True)
micr... |
import pdb
import scipy
import numpy
import pygame
from pygame import display
from pygame.draw import *
from pygame import Color
import math
def barGraph(data):
"""
drawing contains (x, y, width, height)
"""
def f(surface, rectangle):
x0, y0, W, H = rectangle
try:
l = l... |
#I pledge my Honor I have abided by the Stevens Honor System. Elaine Kooiker
#Problem One; The Body Mass Index (BMI) is calculated as a person’s weight (in pounds) times 720,
#divided by the square of the person’s height (in inches).
#A BMI in the range of 19 to 25 (inclusive) is considered healthy.
#Write a program ... |
populationGrowthA = 80000
populationGrowthB = 200000
countYearPopulationGrowthA = 0
countYearPopulationGrowthB = 0
analysisPeriod = 100
#countYearPopulationGrowthA < analysisPeriod
while(populationGrowthB >= populationGrowthA):
populationGrowthA = populationGrowthA + (populationGrowthA * 0.3)
populationGrowth... |
from django.contrib import admin
from projects.models import Dependency, Project
class ProjectDependencyInline(admin.TabularInline):
model = Project.dependencies.through
class ProjectAdmin(admin.ModelAdmin):
inlines = [ProjectDependencyInline]
admin.site.register(Dependency)
admin.site.register(Project, P... |
from apps.settings.base import *
DEBUG = False
|
import logging
from flask import request
from flask_restx import Resource, marshal
from main.util.decorator import admin_token_required, token_required
from ..util.dto import UserDto, fail_response
from ..service.user_service import UserService
from ..worker.tasks import add as task_add
LOG = logging.getLogger("app")... |
def sec_lar(a, b, c):
if a==b and b==c:
return -1
elif (a==b and b>c) or (a>c and b==c) or (a>c and c>b) or (b>c and c>a):
return c
elif (b==c and c>a) or (b>a and a==c) or (b>a and a>c) or (c>a and a>b):
return a
elif (a==c and a>b) or (c>b and a==b) or (c>b and b>a):
re... |
#!/usr/bin/env python
import socket
remoteServer = raw_input("Enter a remote host to scan: ")
if socket.has_ipv6:
print "Has IPv6"
if not socket.has_ipv6:
print "Does Not Have IPv6"
|
#I pledge my honor I have abided by the Stevens Honor System - Tyson Werner
weight = float(input("What is your weight in pounds: "))
height = float(input("What is your height in inches: "))
BMI = (weight * 720)/(height*height)
if BMI < 19:
print("below healthy BMI range")
elif 19 <= BMI <=25:
print("within he... |
from abc import ABCMeta, abstractmethod
class AbstractInfrastructureManager(object):
__metaclass__ = ABCMeta
def __init__(self):
"""TODO"""
self.client = docker.from_env()
self.overlay_opt_dict = {}
@abstractmethod
def init_nfvi(self):
"""
:return:
"""... |
code1, units1, price1 = input().split()
code2, units2, price2 = input().split()
value1 = int(units1)*float(price1)
value2 = int(units2)*float(price2)
print('VALOR A PAGAR: R$ {:.2f}'.format(value1+value2)) |
import numpy as np
from rdkit import Chem, DataStructs
from rdkit.Chem import AllChem
from rdkit.Chem.Crippen import MolLogP
from rdkit.Chem.rdMolDescriptors import CalcTPSA
def read_data(filename):
f = open(filename + '.smiles', 'r')
contents = f.readlines()
smiles = []
labels = []
for i in conte... |
#!/usr/bin/python
import os
import sys
import shutil
import tarfile
import StringIO
import unittest
from mic import chroot
TEST_CHROOT_LOC = os.path.join(os.getcwd(), 'chroot_fixtures')
TEST_CHROOT_TAR = os.path.join(TEST_CHROOT_LOC, 'minchroot.tar.gz')
TEST_CHROOT_DIR = os.path.join(TEST_CHROOT_LOC, 'minchroot')
de... |
# inspired by https://graph-tool.skewed.de/performance
# pgp.xml from:
# Richters O, Peixoto TP (2011) Trust Transitivity in Social Networks. PLoS ONE 6(4): e18384.
# doi 10.1371/journal.pone.0018384
import benchutil
import os
benchutil.add_external_path("networkx-1.11")
benchutil.add_external_path("decorator-4.0.10/s... |
import requests
import json
url = "http://www.kuaidi.com/index-ajaxselectcourierinfo-1109966897738-ems-UUCAO1608710624586.html"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"
}
s = requests.session()
r = s.get(url, hea... |
from datetime import date
AnoAtual = date.today().year
MaiorIdade = 0
MenorIdade = 0
for c in range(1,8):
pessoa = int(input('Digite o ano que a {}ª pessoa nasceu:'.format(c)))
if AnoAtual - pessoa >= 18:
MaiorIdade += 1
else:
MenorIdade += 1
print('Ao todo tivemos {} pessoas maiores de ida... |
from heapq import heapify, heappush, heappop
from itertools import count
from codes import codes
def huffman(seq, frq):
num = count()
trees = list(zip(frq, num, seq))
heapify(trees)
while len(trees) > 1:
fa, _, a = heappop(trees)
fb, _, b = heappop(trees)
n = next(num)
... |
import caffe
import numpy as np
import argparse, pprint
from multiprocessing import Pool
import scipy.misc as scm
from os import path as osp
import my_pycaffe_io as mpio
import my_pycaffe as mp
from easydict import EasyDict as edict
import time
import glog
import pdb
try:
import cv2
except:
print('OPEN CV not found, ... |
#-coding:utf8-
#https://www.zhihu.com/question/25949022
# 检验正态分布等,ks h0 假设为正态分布
import numpy as np
from scipy.stats import kstest
x = np.linspace(-15, 15, 3)
print kstest(x, 'norm')
#最终返回的结果,第二个值 p-value=0.76584491300591395,比指定的显著水平(假设为5%)大,则我们不能拒绝假设:x服从正态分布。
#p<0.05 则可以拒绝
# 疑问?第一个d值怎么看,什么用
|
# this file also contains 2 function that belongs to other project ( the writing to txt files )
import xml.etree.ElementTree as ET
from Product import Product
class MakeData():
def __init__(self):
self.data_shufersal = []
self.data_market = []
self.data_ramilevi = []
self.file = ope... |
__author__ = "Narwhale"
# class Dog(object):
#
# def __init__(self,name):
# self.name = name
#
# def eat(self):
# print('%s is eating ....'%self.name)
#
# d = Dog('xiaohei') #实例化对象
# choice = input('>>>>:').strip() #strip()去除左右空格
#
# if hasattr(d,choice): ... |
### 3-1. multi-class classification ###
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from scipy import io
import matplotlib.cm as cm
import random
import scipy.misc
## 1.1. Dataset ##
all_data = io.loadmat("d:/data/ex03/ex3data1.mat")
x_data = all_data['X']
y_data = a... |
"""
"""
__all__ = [ "base", "simulator" ]
|
import numpy as np
from sklearn import svm
from sklearn.metrics import classification_report
import csv
import talib as ta
import math
import pymysql
import operator
from functools import reduce
def train_test_split(array,ratio=0.8):
train=array[0:int(ratio*len(array))]
test=array[int(ratio*len(array))... |
# This is a program to test the importing of modules
def greetings():
print ("Hello world!") |
import re
from collections import defaultdict
import pandas as pd
from scipy import stats
import numpy as np
from rdflib import Namespace, Literal
from brickschema.namespaces import BRICK, A, OWL
# from brickschema.inference import BrickInferenceSession
from brickschema.inference import OWLRLAllegroInferenceSession
fro... |
import os
from easydict import EasyDict as edict
cfg = edict()
cfg.PATH = edict()
cfg.PATH.DATA = ['/home/liuhaiyang/dataset/CUB_200_2011/images.txt',
'/home/liuhaiyang/dataset/CUB_200_2011/train_test_split.txt',
'/home/liuhaiyang/dataset/CUB_200_2011/images/']
cfg.PATH.LABEL = '/home/liuhaiyang/datase... |
import unittest
from katas.kyu_6.drunk_friend import decode
class DrunkFriendTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(decode('yvvi'), 'beer')
def test_equals_2(self):
self.assertEqual(decode('Blf zoivzwb szw 10 yvvih'),
'You already had 10... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import stats
from ast import literal_eval
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from sklearn.metrics.pairwise import linear_kernel, cosine_similarity
from nltk.stem.snowball imp... |
age=50
name="John"
print name
print name[0:2]
list = []
list.append(1)
print(list[1])
for x in list:
print(x)
if (x == 1):
print(x)
def my_function():
print(5)
my_function()
class MyClass:
variable = "John"
def function(self):
print("wesh wesh")
myObject = MyClass()
myObject.variable |
from controller import *
import os,re,time,random,math
class EpuckFunctions (DifferentialWheels):
max_wheel_speed = 1000
num_dist_sensors = 8
encoder_resolution = 159.23 # for wheel encoders
tempo = 0.5 # Upper velocity bound = Fraction of the robot's maximum velocity = 1000 = 1 wheel revolution/sec ... |
d = 2
st = 1
backwards = False
while st < 6:
if backwards == False:
print(" " * d + "*" * st + " " * d)
d -= 1
st += 2
if st == 5:
backwards = True
if backwards == True:
print(" " * d + "*" * st + " " * d)
d += 1
st -= 2
if st == ... |
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... |
from bottle import Bottle, route, run, response, hook, request, static_file
import paste
import bottle
import dbserver
import obtenerDatos
import impactarExtracto
from json import dumps
default = Bottle()
bottle.BaseRequest.MEMFILE_MAX = (1024 * 1024) * 3 #maximo 3mb
@default.hook('after_request')
def enable_cors(... |
# -*- coding: utf-8 -*-
import numpy as np
def sampler(counts, prior_alpha, repl = 10000):
"""
Executes a Monte Carlo simulation to estimate the distribution
of class probabilities based on the dirichlet-multinomial conjugate
model with non-missing count data.
- counts is a 2-dim array of count... |
# Generated by Django 2.2.4 on 2019-10-31 06:55
from django.db import migrations
import django.db.models.deletion
import smart_selects.db_fields
class Migration(migrations.Migration):
dependencies = [
('billings', '0007_auto_20191022_0832'),
]
operations = [
migrations.AlterField(
... |
#DRONE LAUNCHER
#Import modules
from flask import Flask, render_template, request, jsonify
from roboclaw import Roboclaw
import time
import socket
#Open serial port
#Linux comport name
rc = Roboclaw("/dev/ttyACM0",115200)
#Windows comport name
#rc = Roboclaw("COM8",115200)
rc.Open()
#Declare variables
host=(([i... |
from sim.api import *
from sim.basics import *
'''
Create your distance vector router in this file.
'''
class DVRouter (Entity):
def __init__(self):
# neighbor_list <neighbor, (port , distance)>
self.neighbor_list = {}
# distance_Vector - <(src, des), distance>
self.distance_Vector ... |
from flask import Blueprint
from flask import jsonify
from shutil import copyfile, move
from google.cloud import storage
from google.cloud import bigquery
import dataflow_pipeline.ucc.ucc_mensajes_beam as ucc_mensajes_beam
import dataflow_pipeline.ucc.ucc_agentev_beam as ucc_agentev_beam
import dataflow_pipeline.ucc.uc... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 20 20:38:15 2019
@author: imad
"""
import numpy as np
class AdalineSGD(object):
"""
A simple adaptive linear neuron with gradient descent classifier
Paratmeters
-----------
eta : float
Learning rate (between 0.... |
import json
import twitter
def oauth_login():
# XXX: Go to http://twitter.com/apps/new to create an app and get values
# for these credentials that you'll need to provide in place of these
# empty string values that are defined as placeholders.
# See https://dev.twitter.com/docs/auth/oauth for more inf... |
#File: speeding.py
#Author: Joel Okpara
#Date: 2/22/2016
#Section: 04
#E-mail: joelo1@umbc.edu
#Description: This program calculates the fine for driving over
# the speed limit.
def main():
speedLimit = int(input("What was the speed limit?"))
userSpeed = float(input("At how many miles per hour wer... |
from common.run_method import RunMethod
import allure
@allure.step("极数据/权限部门查询")
def geekData_areaRelation_get(params=None, header=None, return_json=True, **kwargs):
'''
:param: url地址后面的参数
:body: 请求体
:return_json: 是否返回json格式的响应(默认是)
:header: 请求的header
:host: 请求的环境
:return: 默认json格式的响应, re... |
__author__ = 'Vlad Iulian Schnakovszki'
# Using this because: http://stackoverflow.com/questions/1272138/baseexception-message-deprecated-in-python-2-6
class MyException(Exception):
def _get_message(self):
return self._message
def _set_message(self, message):
self._message = message
message... |
import os
import win32com.client as win32
from tkinter import *
from tkinter import filedialog
from tkinter import messagebox
import openpyxl
class SampleApp(Tk):
def __init__(self):
Tk.__init__(self)
self._frame = None
self.switch_frame(main_Page)
def switch_frame(self, frame_class):
... |
import numpy as np
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal
fs = 2e6 //sample frequency
rb = 1e3 //bit rate
fc = 0.5e6 //carrier frequency
t_sim = 1e-2 //simlation time
src_bits = 1-2*np.random.randint(0,2,t_sim*rb)
class mod_iq:
def __i... |
from django.contrib.auth.models import User
from django.db import models
from django.conf import settings
class Story(models.Model):
place = models.CharField(max_length=150)
people_involved = models.TextField(blank=True)
images = models.ManyToManyField('StoryImage', blank=True)
date_posted ... |
# Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
# This file contains a set of utilities for parsing minidumps.
import ctypes
import mmap
import os
import... |
def d_separated(G, x, y, z): ...
def minimal_d_separator(G, u, v): ...
def is_minimal_d_separator(G, u, v, z): ...
|
number = int(input('Enter number : '))
integer = number
number1 = 1
number2 = 1
count = 0
if integer <= 0:
print("Please enter positive integer")
elif integer == 1:
print("Fibonacci sequence",integer,":")
print(number1)
else:
print("Fibonacci sequence",integer,":")
while count < integer:
pri... |
# -*- coding: utf-8 -*-
import pymysql.cursors
connection = pymysql.connect(host=#'hostname',
user=#'username',
password=#'password',
db=#'dbname',
charset=#'utf8',
cursorclass=py... |
# coding: utf-8
# # Problem 6: Hash Tables
# You've used Python's `dict` data type extensively now. Recall that it maps keys to values. But how is it implemented under-the-hood? One way is via a classic computer science technique known as a **hash table**.
#
# For our purposes, a hash table has two parts:
#
# 1. A... |
import time
while(True):
f = open("data.txt","r")
a = f.readline()
f.close()
print a
|
import string
from abc import ABC, abstractmethod
import os
import pyaes
from io import BytesIO, StringIO
class Cipher(ABC):
def __init__(self) -> None:
super().__init__()
@abstractmethod
def generate_key(self):
pass
@abstractmethod
def encrypt(self, key, message):
pas... |
#! /usr/local/bin/python
# ! -*- encoding:utf-8 -*-
from pathlib import Path
import pandas as pd
import numpy as np
import random
import os
import argparse
proj_path = Path(__file__).parent.resolve().parent.resolve().parent.resolve()
data_path = proj_path / 'data' / 'PPP'
def read_csv(data_file, dataset):
cci_la... |
from flask import jsonify, make_response, abort
def get_paginated_list(model, schema, url, start, limit):
"""
start - It is the position from which we want the data to be returned.
schema - It is the marsmallow schema to serialize models data
limit - It is the max number of items to return from that po... |
from django.shortcuts import render
from django.http import HttpResponse
from django.core.mail import EmailMessage
from django.conf import settings
from django.template.loader import render_to_string
# Create your views here.
from .models import Post
def home(request):
posts = Post.objects.filter(active=True, fea... |
import json
none = "d3043820717d74d9a17694c176d39733"
# region EMR
class EMR:
def __init__(
self,
name=none,
description=none,
region=none,
strategy=none,
compute=none,
scaling=none):
"""
:type name: str
:type decription: str
:type region: str
:type strategy: Strategy
:tpye compute: Compu... |
#!/usr/bin/env python
# Dirty bit: if this memory has been Written to (and thus, it must write to disk upon eviction)
# Referenced bit: if this memory has been read or written to (if it's been referenced at all)
# Four algorithms: Optimal, Clock (w/ circular queue enhancement of second chance algo.),
# NotRecentl... |
import unittest
from app.code.bank.account import Account
from app.code.bank.bank import Bank
class BankTest(unittest.TestCase):
def test_bank_init_empty(self):
bank = Bank()
self.assertEqual({}, bank.accounts)
self.assertEqual(len(bank.accounts), 0)
def test_add_account(self):
... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from pants.testutil.pants_integration_test import run_pants, setup_tmpdir
PLUGIN = """
import logging
from pants.engine.goal import GoalSubsystem, Goal
from pants.engine.rules import col... |
import io
from typing import Dict, Union, List
from parseridge.utils.logger import LoggerMixin
ID, FORM, LEMMA, UPOS, XPOS, FEATS, HEAD, DEPREL, DEPS, MISC = range(10)
class CoNLLEvaluationScript(LoggerMixin):
"""
Based on v. 1.0 of the CoNLL 2017 UD Parsing evaluation script by
the Institute of Formal ... |
import argparse
def run(var1, var2):
"""
Change made to this file...
"""
var3 = f"{var1}:{var2}"
print(var3)
return var3
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Input sample argparse args")
parser.add_argument('--V1', type=int, help='Enter val for var... |
import os
import json
import csv
with open("social.csv","a",newline="") as f:
csv_write = csv.writer(f, dialect='excel')
title = ["uid",">5person","social times"]
csv_write.writerow(title)
for file in os.listdir("./response/Social"):
dirt = "./response/Social/" + file
with open(dirt,"r... |
import datetime
from datetime import date
import requests
from flask import Flask
from flask import request
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def home():
stu_id = request.args.get('id', '')
today = date.today()
full_html = ""
for i in range(7):
d1 = today.strfti... |
#!/usr/bin/python
# soapclient.py - SOAP client class, part of BlackStratus.
"""
Provider level access to SOAP service.
"""
import webservice.soapclient
import logging;
logger = logging.getLogger("Notification")
class CaseClient(webservice.soapclient.TrSoapClient):
def __init__(self, wsdl_url, username... |
from urllib import request, parse, error
import json
import socket
import re
import time
socket.setdefaulttimeout(5)
class ZabbixApi(object):
def __init__(self, url, username, password):
self.__url = url
self.__username = username
self.__password = password
self.__rpc_version = "2... |
import random
from django.apps import apps
from django.conf import settings
from django.contrib.auth import get_user_model
from django.db import models
from django.db.models.fields import NOT_PROVIDED
from faker import Factory as FakerFactory
from .compat import get_model_fields, string_types
from .exceptions import... |
import math
import random
random.seed(28492)
class Synapse:
def __init__(self, weight):
self.weight=random.random()
self.value=0
def output():
self.out = weight*value
class Neuron(Synapse):
def __init__(self, value):
self.value = 0
self.connect_to ... |
import requests
print(requests.get("http://localhost:5000/test/Shagaev").text) |
# Copyright 2014 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompa... |
T = int(input())
for _ in range(T):
n = int(input())
a = list(map(int, input().split()))
A = []
for i in range(0,n*2,2):
A.append([a[i],a[i+1]])
A = sorted(A, key = lambda i: i[0])
for i in range(n-1):
if A[i][1] >= A[i+1][0]:
A[i][1] = max(A[i][1],A[i+1][1])
... |
'''
# Целевая функция
def W():
Ограничения:
2*x1 + 5*x2 + 2*x3 <= 12
7*x1 + x2 + 2*x3 <= 18
x1, x2, x3 >= 0
return 3*x1 + 4*x2 + 6*x3 -> max
'''
'''
1) Приводим к каноническому виду: Вводим добавочные неотрицательные переменные,
если <= то со знаком +, если >=, то со знаком -
2*x1 + 5*x2 + 2*x3... |
# IntelHex library version information
version_info = (2, 1)
version_str = '.'.join([str(i) for i in version_info])
|
#!/usr/bin/env python
"""
pyjld.phidgets.erl_manager.cmd
"""
__author__ = "Jean-Lou Dupont"
__email = "python (at) jldupont.com"
__fileid = "$Id$"
__all__ = ['PhidgetsErlManagerCmd',]
from pyjld.system.command.base import BaseCmd, BaseCmdException
import pyjld.system.daemon as daemon
from erl_manager_daemon ... |
class Node:
def __init__(self,data):
self.data = data
self.reference = None
node1 = Node(10)
print(node1)
|
from urllib import parse
urls1 = ['province=上海&city=上海市&district=南汇区&all=Y&page=0&_=1509106871111',
'province=上海&city=上海市&district=卢湾区&all=Y&page=0&_=1509106871111',
'province=上海&city=上海市&district=嘉定区&all=Y&page=0&_=1509106871111',
'province=上海&city=上海市&district=奉贤区&all=Y&page=0&_=1509106871111',
'province=上海&city=上海市&... |
import django.dispatch
create_message = django.dispatch.Signal(providing_args=["room", "user", "content", "msg_type"]) |
# import socket programming library
#import socket
from socket import *
import os
import sys
# import thread module
from _thread import *
import threading
import json
from datetime import datetime,date,timedelta
import random
blockingdic = {}
blockdic = {}
blocktime = 0
loginuser = []
tempidlist = []
# thread func... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 27 17:25:38 2018
@author: bdus
try to preprocess data
"""
import os
import sys
import numpy as np
import matplotlib.pyplot as plt
import random
import scipy.io as sio
from sklearn import preprocessing
from sklearn import datasets, svm, metric... |
__author__ = 'sb5518'
"""
This Module contains the grades_by_year_graph_generator(grades_dictionary, graph_name) function which
purpose is to generate the graphs required in question 5. It creates a graph of lines for the total amount of grades by
year. The required input is a dictionary of dictionaries in the form {... |
from django.contrib import admin
from story.models import *
admin.site.register(Story)
admin.site.register(StoryImage)
admin.site.register(TestImage) |
import os
import numpy as np
import torch
import torch.utils.data.dataset as Dataset
from skimage.transform import resize
import SimpleITK as sitk
import random
import scipy.io as sio
from scipy import ndimage,misc
# from batchgenerators.transforms import MirrorTransform, SpatialTransform
from aug_tool import Crop, Mir... |
from unittest import result
from django.http import response
from django.test import TestCase
from django.urls import reverse
from alimentos.models import Food
import pytest
class TestAlimentos(TestCase):
def setUp(self):
food = Food.objects.create(name='Banana', brand='Seu Ze', section='Frutas', content... |
a = int(input('Digite um ano: '))
if a % 4==0 and a % 100 != 0 or a % 400 == 0:
print(' O ano {} É BISSEXTO'.format(a))
else:
print('O ano {} NÃO É BISSEXTO'.format(a)) |
import glob
import pickle
import numpy as np
import pandas as pd
import tensorflow.keras.models as models
from flight_delay_prediction.constant import CONTINUOUS_INPUTS, CATEGORICAL_INPUTS
from flight_delay_prediction.errors import UnknownCategoryError
from flight_delay_prediction.utils import cached_classproperty
... |
import json
import time
import os, sys
import requests
'''
Given a .json database of anime, picks the corresponding Anilist page and
adds a new a new key with charachters (that were picked up via the
Anilist.co API).
'''
def update_database(database='anime-offline-database.json'):
'''
Searches in the entire ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.