text stringlengths 38 1.54M |
|---|
class Person:
def __init__(self, name = "Vasya", sex = "M", age = 13 ):
self.name = name
self.sex=sex
self.age = age
class Citizen(Person):
def __init__(self, nation = "Ukrainian", **kwargs):
self.nation = nation
#super(Citizen, self).__init__()
Person.__init... |
from dictdb.GenericDictDB import GenericDictDB
from dictdb.SqliteThreadWork import SqliteThreadWork
from dictdb.StorageDict import SharedStorage, ThreadedSharedStorage
# end-of-file |
#!/usr/bin/env python3
import re
import sys
import ipaddress
from mysql import connector
from itertools import islice
from collections import defaultdict
db = { 'host' : 'localhost',
'database' : 'bgp',
'user' : 'bgp',
'passwd' : 'bgp'
}
#bgp_file = './test5000000.bgp'
#bgp_file = './test100... |
import os
import csv
from constant_ble_read import ReadBLE
files_path = os.path.join(os.getcwd(), 'files')
while True:
try:
start = input("Iniciar teste s/n: ")
if start.upper() != "S":
break
name = input("Número do teste: ")
read_time_sec = int(input("Tempo de leitur... |
import hashlib
import json
import os
import random
from datetime import *
from django.db.models import Q
from django.http import Http404, FileResponse
from django.http import JsonResponse
from django.shortcuts import render,redirect
from app02.models import User, File, File_Users, Share
from app02.py import zip
from ... |
#!/usr/bin/python3
from commands.modules.create_connection import create_connection
from commands.mysql_server.integrate_mysql import integrate_mysql
import typer
app = typer.Typer()
@app.command()
def mysql_storage(
ip: str = typer.Option(...),
key_ssh: str = typer.Option(...),
user_ssh: st... |
# Copyright 2014 Scalyr 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 or agreed to in writing, so... |
# Generated by Django 2.2 on 2019-05-04 09:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ordering', '0003_auto_20190504_1351'),
]
operations = [
migrations.CreateModel(
name='Ingredient',
fields=[
... |
#!/usr/bin/env python
#coding: utf-8
import json
import logging_debug
from models import execute_sql
from models import select_all_result
from models import select_one_result
import logging
import hashlib
rememberme='./rememberme'
logging.basicConfig(
filename = './logs',
filemode = 'a',
for... |
# -*- coding: utf-8 -*-
focus = ['yura', 'kolia', 'vasia']
r = []
def show_magicians(focus):
for i in focus:
print(i)
def make_great (focus, r):
for n in focus:
he = n + 'Great'
r.append(he)
print(r)
f2 = ['sdf', 'sdfsdsdf']
gg = []
make_great(f2, gg)
show_magicians(f2) # список ... |
# Generated by Django 2.2.4 on 2019-11-04 08:08
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('accounts', '0012_student_lock'),
('application', '0012_auto_20191103_0407'),
]
operations = [
migra... |
from collections import namedtuple
import json
class Config(object):
def __init__(self, influx_host, influx_port, influx_username, influx_password, influx_database):
self.influx_host = influx_host
self.influx_port = influx_port
self.influx_username = influx_username
self.influx_pas... |
from flask import Flask, escape, request, jsonify
from flask_restful import Api
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
api = Api(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://tmp_hello:ceshiren.com@182.92.129.158/tmp123?charset=utf8mb4'
db = SQLAlchemy(app)
@app.route('/users')... |
# Day 16 code 1
# Convert a list of Tuples into Dictionary
list_1=[("Vijay kumar",93), ("Vikram kumar",94), ("Vivek dutta",95),
("Vivek kumar",96), ("Vivek choudhary",97)]
dict_1=dict()
for student,score in list_1:
dict_1.setdefault(student, []).append(score)
print(dict_1) |
def gcd(a,b):
for i in range(1,min(a, b)+1):
if (a % i == 0) and (b % i == 0):
x = i
return x |
from scrapy.spider import BaseSpider
class CulinaryFruitsSpider(BaseSpider):
name = 'culinary_fruits'
domain_name = 'wikipedia.org'
start_urls = ['http://en.wikipedia.org/wiki/List_of_culinary_fruits',
'http://en.wikipedia.org/wiki/List_of_edible_seeds',
'http://en.wikip... |
"""
.. module: lemur
:platform: Unix
:copyright: (c) 2015 by Netflix Inc., see AUTHORS for more
:license: Apache, see LICENSE for more details.
.. moduleauthor:: Kevin Glisson <kglisson@netflix.com>
"""
from lemur import factory
from lemur.users.views import mod as users_bp
from lemur.roles.views import... |
'''
Created on 29.10.2018
@author: Henry Fock, Lia Kirsch
'''
import csv
import os
import sys
import sqlite3
import tempfile
import getBoundingBox
# add local modules folder
# file_path = os.path.join('..', 'Python_Modules')
# sys.path.append(file_path)
from osgeo import ogr, osr
import click
import pandas as pd
imp... |
import os
import motor
from tornado.httpclient import AsyncHTTPClient
from tornado.testing import AsyncHTTPTestCase, gen_test
from tornado.web import Application, RequestHandler
class ExampleHandler(RequestHandler):
async def get(self):
document = await self.settings["database"].things.find_one({"thing":... |
from django.db import models
from datetime import datetime
from django.utils.safestring import mark_safe
from django.urls import reverse
from django.contrib.auth.models import User
from apps.data.models import Cliente, Moneda
from django.core.validators import MaxValueValidator, MinValueValidator
from decimal import De... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.13 on 2017-05-27 19:36
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('journal', '0014_auto_20170527_1932'),
]
operations = [
migrations.RenameFie... |
import os
import time
import unittest
# 创建测试套件
import HTMLTestRunner_PY3
from Autoapitest import app
from Autoapitest.script.test_tpshop_login import TpshopLogin
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
suite = unittest.TestSuite()
# 将测试用例添加到测试组件
suite.addTest(unittest.makeSuite(TpshopLogin))
# 定义测试报告的目录... |
# created by Ryan Spies
# 3/5/2015
# Python 2.7
# Description: parse through UHG .xml parameter files and create a new file with
# ordinates rounded to whole numbers (CHPS version currently leaves multiple decimals)
import os
import glob
os.chdir("../..")
maindir = os.getcwd()
###########################... |
"""
a -> b -> b
b -> a
a -> a
(b -> b) -> b
(a, b -> b)
fail
a allocated by side1
b allocated by side2
(b, a) -> normalized -> (a, b)
once type is temporary nominal type!
a = (b -> b)
a -> a = b
how fail?
subst other side's once vars with its own side's once vars,
if cannot(not principal), fail
otherwise... |
"""Helper for file handling."""
import os
def cleanup(config_dir):
"""Remove temporary stderr and stdout files as well as the daemon socket."""
stdout_path = os.path.join(config_dir, 'pueue.stdout')
stderr_path = os.path.join(config_dir, 'pueue.stderr')
if os._exists(stdout_path):
os.remove(st... |
from __future__ import print_function
import ttfw_idf
EXPECT_TIMEOUT = 20
@ttfw_idf.idf_example_test(env_tag='Example_RMT_IR_PROTOCOLS')
def test_examples_rmt_ir_protocols(env, extra_data):
dut = env.get_dut('ir_protocols_example', 'examples/peripherals/rmt/ir_protocols', app_config_name='nec')
print("Using... |
"""
ANTECEDENTES
-------------
La primera version de numeros a letras se construyó en 1993 en clipper para ayudar a mi amigo Paulino para transferir las notas de los alumnos de la Escuela de Enseñanza de Automoción del EA a la Direccion de Enseñanza que pedia las mismas, aparte de en su valor numerico, como cadena de ... |
import collections
import random
import re
from collections import Counter
from itertools import islice
import nltk
from nltk.corpus import stopwords
import numpy as np
import pandas as pd
pd.set_option('display.max_colwidth', -1)
from time import time
import re
import string
import os
import emoji
fro... |
import json
import requests
import sys
sys.path.insert(1, '../')
URI_OBTAIN_DOCUMENT_INFORMATION = 'http://librairy.linkeddata.es/solr/tbfy/select?q=id:'
URI_INFERENCES = 'https://librairy.linkeddata.es/jrc-en-model/inferences'
URI_LIST_TOPICS = 'http://librairy.linkeddata.es/jrc-en-model/topics'
URI_DOCUMENT_RANK = ... |
import os
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
import tensorflow.contrib.eager as tfe
from scipy.misc import toimage
def make_generator(images, z_vectors):
def _generator():
for image, z_vec in zip(images, z_vectors):
yield image, z_vec
return _generat... |
from multiprocessing import Process
import time
import redis
def redis_process_no_tran(key):
server_ip = "192.168.64.4"
bunny_node1_port = 6379
pool1 = redis.ConnectionPool(host=server_ip,
port=bunny_node1_port,
db=0,
... |
import re
"""
- os.path is either posixpath or ntpath
- os.name is either 'posix' or 'nt'
- os.curdir is a string representing the current directory (always '.')
- os.pardir is a string representing the parent directory (always '..')
- os.sep is the (or a most common) pathname separator ('... |
from tkinter import *
# "SELECT * FROM users WHERE personal_code = {}".format(personalcode)
def personal_info_start():
"""
Create a GUI for Personal informatie
:return: Returns a GUI Screen
"""
# Create screen for personal logon
personal_info_window = Tk()
# Screen Title
persona... |
#!/usr/bin/env /home/shbae/anaconda3/envs/work/bin/python
import glob
import sys
import os
import subprocess
# modify below three lines
# according to your directory structures
vina_path = "/home/shbae/bin/vina-1.1.2/vina"
receptors = glob.glob("./rec/xyz.pdbqt")
ligands = glob.glob("./lig/com-1234.pdbqt")
def dock... |
import unittest
import os
import sys
import shutil
from common import HTMLTestReportCN
from common.log_utils import logger
from common.email_utils import EmailUtils
current_path = os.path.dirname(__file__)
case_path = os.path.join(current_path,'testcases')
# print(case_path)
html_report_path = os.path.join(current_pat... |
import json
import pathlib
from .models import *
from django.core.exceptions import ObjectDoesNotExist
class DbLoadError(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return self.message
class PopulationConfig:
def __init__(self, cfg):
se... |
def install(vm):
vm.install('unzip')
vm.install('build-essential')
vm.script('sudo su - hduser -c "git clone https://github.com/hortonworks/hive-testbench.git"')
vm.script('sudo su - hduser -c "cd hive-testbench && ./tpch-build.sh"')
def uninstall(vm):
pass
def installed(vm):
pass
|
from __future__ import absolute_import
from django.core import mail
from sentry.models import (OrganizationAccessRequest, OrganizationMember, OrganizationMemberTeam)
from sentry.testutils import TestCase
class SendRequestEmailTest(TestCase):
def test_sends_email_to_everyone(self):
owner = self.create_us... |
#!/usr/bin/python
import os
import sys
import math
class AES(object):
keySize = dict(SIZE_128=16)
# Rijndael S-box
sbox = [0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67,
0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59,
0x47, 0xf0, 0xad, 0xd... |
import os, sys, json, time, datetime
import numpy as np
from utils import read_file, write_file, sigmoid, sigmoid_derivative
def train(X, y, alpha=1, epochs=10000, classes=[]):
print ("Training with alpha:%s" % (str(alpha)) )
print ("Input matrix: %sx%s Output matrix: %sx%s" % (len(X),len(X[0]),len(X[0]), ... |
# ******************************************
# Author : Ali Azhari
# Created On : Fri Jul 19 2019
# File : app.py
# *******************************************/
class Solution(object):
# Brute force that takes O(n**2)
def lengthOfLongestSubstring1(self, s):
"""
:type s: str
:rtype:... |
#!/usr/bin/python3
from urllib.request import urlopen
from urllib.error import HTTPError
from urllib.error import URLError
from bs4 import BeautifulSoup
try:
html = urlopen(r'http://pythonscraping.com/pages/page1.html')
# html = urlopen(r'http://lilacaromas.com.br/inicio.html')
except HTTPError as e:
print... |
def test_prompt(netmiko_conn):
assert netmiko_conn.find_prompt() == "arista1#"
def test_show_ver(netmiko_conn):
assert "4.20.10M" in netmiko_conn.send_command("show version")
|
# -*- coding: utf-8 -*-
"""Helper utilities and decorators."""
import re
from flask import flash, request
def flash_errors(form, category='warning'):
"""Flash all errors for a form."""
for field, errors in form.errors.items():
for error in errors:
flash('{0} - {1}'.format(getattr(form, fie... |
import linecache #lines are 1 indexed
import sys
import random
import re
import collections
#only call this on lines in the matrix. will err otherwise.
def convert(file_name, node_index):
"""turn line into list"""
line = linecache.getline(file_name, node_index+1)
line = line[2:line.index('\n')]
line = line.split()... |
"""
Test PySlipQt GototPosition() function.
The idea is to have a set of buttons selecting various geo positions on the OSM
tile map. When selected, the view would be moved with GotoPosition() and a
map-relative marker would be drawn at that position. At the same time, a
view-relative marker would be drawn at the ce... |
import requests
def login():
session = requests.session()
url = 'https://authapi.xincheng.com:8090/mobilelogin/index'
params = {
'userid': 'lvrihui',
'password':
'Taco53TfQ2iDfvIUrKHroIRFNBt2/SP5TYYxCzgJ4wE+dElEIvQzGn4nVO9hQOl2qGDhC5T6D3/jEZvyJ/wQKq6uBnbTECGoB\
mvTpwAW... |
from app import db
class Users(db.Model):
userid = db.Column(db.String(30), primary_key=True, nullable=False)
passwd = db.Column(db.String(30), nullable=False)
uid = db.Column(db.Integer, nullable=False, unique=True)
gid = db.Column(db.Integer, nullable=False)
homedir = db.Column(db.String(255))
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import struct
class NotMemoFileError(Exception):
pass
class MemoItemType:
""" MemoItem's type """
QA = 0
SINGLE_SELECT = 1
JUDGE = 2
class MemoItem(object):
""" parent of MenuItem. """
FMT = "<BII%ss%ss"
def __init__(self, _subj... |
from App.Model.Local import Local
from App.Model.Pessoa import Pessoa
from App.Model.Tarefa import Tarefa
from App.Model.UserAuth import UserAuth
def routes(api):
api.register(Local)
api.register(Pessoa)
api.register(Tarefa)
api.register(UserAuth)
|
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 12 01:03:39 2018
@author: ikc15
Train an Image Classifier with TensorFlow Learn to classify handwritten digits
from the mnist dataset.
Since we are using a neural network. We do not need to manually select features.
The neural network takes each raw pixel as... |
#!/usr/bin/env python
# Usage:
# ./QA.py path/to/transcripts/ path/to/output/directory
import os
import subprocess
import sys
from Bio import SeqIO
threads = 16
mgy_db = '/Nancy/data/input/RNA/ENA_gut/db/mgy.dmnd'
def get_fasta_ids(fasta):
ids = set()
for seq_record in SeqIO.parse(fasta, "fasta"):
... |
# -*- coding: utf-8 -*-
import os
if os.name == "posix":
from ._DBusSessionService import DBusService as SessionService
elif os.name == "nt":
from ._NtSessionService import NtService as SessionService
else:
SessionService = None
|
import cPickle
import gzip
import os
import sys
import time
import numpy
import collections
import random
random.seed(1)
labels=numpy.load(sys.argv[2])
counter=collections.defaultdict(list)
cnt=0
for l in labels.tolist():
counter[l].append(cnt)
cnt+=1
print counter.keys()
vals = map(len,counter.values())
print val... |
"""
Using this code you will be able to reduce the number of qubits by finding underlying Z2 symmetries of the Hamiltonian.
The paper expaining the qubit reduction technique is:
by S. Bravyi et al. "Tapering off qubits to simulate fermionic Hamiltonians"
arXiv:1701.08213
This will drastically speed up all the simulatio... |
import FWCore.ParameterSet.Config as cms
# Electron collection merger
mergedSlimmedElectronsForTauId = cms.EDProducer('PATElectronCollectionMerger',
src = cms.VInputTag('slimmedElectrons', 'slimmedElectronsHGC')
)
|
# Download zip file from EC2: scp -i "winter2017.pem" ec2-user@ec2-52-90-235-168.compute-1.amazonaws.com:pz.tar.gz .
# flags to get updated data
scrape_fighters = False
scrape_birthdays = True
###################################
import time
import requests
session = requests.Session()
#session.headers = {}
#session... |
#!/usr/bin/python
#
# Copyright 2015 Gerard kok
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
BOARD_WIDTH = 240
BOARD_HEIGHT = 95
window = {
"name" : "FinishedAchievementDialog",
"x" : SCREEN_WIDTH - (BOARD_WIDTH + 4),
"y" : SCREEN_HEIGHT - (BOARD_HEIGHT + 18),
"width" : BOARD_WIDTH,
"height" : BOARD_HEIGHT,
"children" :
(
{
"name" : "board",
"type" : "board",
"x" : 0,
"y" : 0,
... |
from flask import Blueprint, render_template, redirect,request,jsonify
from app import app
from app import sched, trigger
from app.etlMongo.pubFunction import set_log
from app.etlMongo.tabStudent import get_stu_info
from app.etlMongo.tabHomework import get_homework
from app.etlMongo.tabGame import get_game_info
from . ... |
##########################################################################
#
# Copyright (c) 2010, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistribu... |
import math
from busquedas_02 import ProblemaBusqueda, aestrella
MAPA = """
##############################
# # # #
# #### ######## # #
# o # # # #
# ### #### ###### #
# #### # #
# # # # #### #
# ###### # # ... |
# Device manager
# author: ulno
# created: 2017-04-07
#
# manage a list of installed devices and enable
# sending or reacting to mqtt
import gc
# import ussl - no decent ssl possible on micropython esp8266
# gc.collect
from umqtt.simple import MQTTClient as _MQTTClient
gc.collect()
import machine
import time
import u... |
from django.conf.urls import url, include
from django.conf import settings
from django.contrib.staticfiles.urls import static, staticfiles_urlpatterns
from django.contrib import admin
from payment.views import *
app_name='payment'
urlpatterns = [
url(r'login/$', loginK, name="login"),
url(r'logout/$',logoutK,name=... |
def digitalSum(num):
sum = 0
for x in range(0, len(str(num))):
sum = sum + int(str(num)[x])
return sum
largest = 0
for a in range(1, 100):
for b in range(1, 100):
test = digitalSum(a**b)
if test > largest:
largest = test
print(largest) |
from funlib.evaluate import rand_voi
import numpy as np
import gunpowder as gp
def evaluate_affs(pred_labels, gt_labels, return_results=False):
results = rand_voi(gt_labels.data, pred_labels.data)
results["voi_sum"] = results["voi_split"] + results["voi_merge"]
scores = {"sample": results, "average... |
#################################################################
# Course : CS-382 Network Centric Computing #
# Offering : Spring 2017 #
# University : Lahore University of Management Sciences #
# File name : client_v9.py #
# Assignment title : Programming Assignment 1 #
# ... |
import pytest
from gyomu.file_model import FileTransportInfo
from collections import namedtuple
TransportResult = namedtuple('TransportResult', ['input_base', 'input_sdir', 'input_sname', 'input_ddir', 'input_dname',
'source_full_base', 'source_full', 'source_dir', 'sou... |
#!/usr/bin/env python
import matplotlib, argparse
import numpy as np
import matplotlib.pyplot as plt
parser = argparse.ArgumentParser(description='plot with error bars for a set of powers')
parser.add_argument('pdffile', help='an output PDF file')
parser.add_argument('-x', default='power/speed', help='value for the x... |
from core.enums import CommandMessageType
from core.utils import emojize, escape_markdown
def command_menu(command):
msgs = command.message_set.all()
msgs_count = msgs.count()
first_msg = msgs.first()
answer = 'No answer'
if msgs_count == 1 and first_msg.type == CommandMessageType.TEXT:
an... |
from calendar import *
import calendar
month, day, year = map(int,input().split())
result = weekday(year,month,day)
print((calendar.day_name[result]).upper()) |
from math import sin, cos, pi
from matrix import *
from draw import *
def circx(x, t, r):
return r * cos(2 * pi * t) + x
def circy(y, t, r):
return r * sin(2 * pi * t) + y
def add_circle(matrix, x, y, z, r):
return draw_parametric(matrix, x, y, z, r, circx, circy, 0.01)
def cubicx(x, t, c):
#xc is x... |
# Generated by Django 3.1.7 on 2021-03-14 14:16
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('Musica', '0005_auto_20210314_1348'),
]
operations = [
migrations.RemoveField(
model_name='lista',
name='usuario',
),... |
class Config:
def __init__(self):
#DBCONFIG
self.DB_URL = "postgresql://postgres:bry4nchr1s@localhost/postgres" |
import logging
class GlobalRouting:
def __init__(self, floorplan, top_rtl_parser, slot_manager):
self.floorplan = floorplan
self.top_rtl_parser = top_rtl_parser
self.slot_manager = slot_manager
self.v2s = floorplan.getVertexToSlot()
self.s2e = floorplan.getSlotToEdges()
self.e_name2path = {}... |
from datetime import datetime
from django.db import models
from django.contrib import messages
from django.contrib.messages import get_messages
from .user import User
from .tag import Tag
class TaskManager(models.Manager):
def create_task(self, request):
new_task = None
tag_errors = False
... |
import FWCore.ParameterSet.Config as cms
CSCTFConfigOnline = cms.ESProducer("CSCTFConfigOnlineProd",
onlineAuthentication = cms.string('.'),
forceGeneration = cms.bool(False),
onlineDB = cms.string('oracle://CMS_OMDS_LB/CMS_TRG_R')
)
|
import statistics
temperatures = [10,14,15,10,9,5]
# temperatures_under_mean = list(filter(lambda x:x>statistics.mean(temperatures),temperatures))
# print(temperatures_under_mean)
def if_greater_then_mean (x):
if x > statistics.mean(temperatures):
return True
else:
return False
# tworzeni... |
from Chromosome import Chromosome
from DNN import DNN
from keras import backend as KerasBackend
from Paths import get_path_slash
from Paths import get_symbol_data_path
from Paths import get_symbol_data
from PreprocessCsv import PreprocessCsv
from framePrepDnn import framePrepDnn
from LoadData import load_training_an... |
from sanic import Sanic
from sanic.response import json
import sys
app = Sanic()
@app.route("/")
async def test(request):
return json({"hello": "world"})
#if __name__ == "__main__":
# app.run(host="0.0.0.0", port=8000)
#app.run()
app.run(host= '0.0.0.0', port=8000)
print ('exiting...')
sys.exit(0) |
from flask_restful import Resource
from flask_jwt_extended import jwt_required
from webargs import fields
from webargs.flaskparser import use_args
from services.meal_plan_generator import generate_meal_plan
from models.dietary_restriction import DietaryRestriction
GENDERS = ['Male', 'Female']
class MealPlanApi(Resou... |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 11 19:16:52 2020
@author: Jay
"""
import numpy as np
A = np.array([[1,0.67,0.33],[0.45,1.,0.55],[0.67,0.33,1.]])
b = np.array([2,2,2])
print(np.linalg.solve(A,b)) |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from utils import AddBias, where
class Categorical(nn.Module):
def __init__(self, num_inputs, num_outputs):
super(Categorical, self).__init__()
self.linear = nn.Linear(num_inputs, nu... |
import taichi as ti
arch = ti.vulkan if ti._lib.core.with_vulkan() else ti.cuda
ti.init(arch=arch)
n = 128
quad_size = 1.0 / n
dt = 4e-2 / n
substeps = int(1 / 60 // dt)
gravity = ti.Vector([0, -9.8, 0])
spring_Y = 3e4
dashpot_damping = 1e4
drag_damping = 1
ball_radius = 0.3
ball_center = ti.Vector.field(3, dtype=f... |
import os
import numpy as np
import rasterio.features
import shapely.ops
import shapely.wkt
import shapely.geometry
import pandas as pd
import cv2
from scipy import ndimage as ndi
from skimage.morphology import watershed
from tqdm import tqdm
from fire import Fire
def _remove_interiors(line):
if "), (" in line:
... |
import os
from typing import Optional
from unittest import mock
import pytest
from pytorch_lightning import Trainer
from pytorch_lightning.callbacks import Callback
from pytorch_lightning.plugins.training_type.rpc_sequential import RPCPlugin
from tests.helpers.boring_model import BoringModel
from tests.helpers.runif ... |
from .device import SimulatedTekafg3XXX
from ..lewis_versions import LEWIS_LATEST
framework_version = LEWIS_LATEST
__all__ = ['SimulatedTekafg3XXX']
|
def BasicCommands():
import os
os.system("tput setaf 10")
print("***************************************************************************************************************************************")
os.system("tput setaf 10")
name = "\" \t\t\t\t LINUX TERMINAL USER INTERFACE\""
os... |
N, K = map(int, input().split())
A = list(map(int, input().split()))
result = 1
L = 2
current = A[0]
visited = [0] * N
visited_loop_cnt = 1
flag = True
while L < K:
if visited[current - 1] == 3:
J = K - L
J %= visited_loop_cnt
K = L + J
elif visited[current - 1] == 2 and flag:
... |
from __future__ import print_function # Make sure this line is always at the top of the file.
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from email.mime.text import MIMEText
import base64
import pickle
import os.... |
#.find string03.py
#Diogo.c
email = "TheQueen@BuckinghamPalace.uk"
index = email.find("@")
print("The @ is at index",index)
|
from quant.project.fund_project.fund_stock_selection_ability_tianfeng.allfund_alpha_on_factor_file import *
from quant.project.fund_project.fund_stock_selection_ability_tianfeng.allstock_alpha_on_factor import *
if __name__ == '__main__':
# GetAllStockAllDateAlpha
############################################... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# größter gemeinsamer Teiler
def ggt(x, y):
if x > y:
return ggt(x-y, y)
elif x == y:
return x
else:
return ggt(y, x)
def ggt(x,y):
while x != y:
if x > y or x%y != 0:
x % y
tmp = x
x = y
... |
from PyQt5.QtWidgets import QLabel, QWidget
from PyQt5.QtCore import Qt, QMimeData, QRect
from PyQt5.QtGui import QDrag, QPixmap, QPainter, QCursor
import parametros as par
import os
#Inspirado con https://www.youtube.com/watch?v=9CJV-GGP22c
class Pinguino(QLabel):
def __init__(self, parent, color, pos_x, pos_y):... |
print("################################################################################")
print('''
INTRODUCTION\n''')
print("################################################################################")
print('''
Classes can be used in many different ways. We are going to focus on using them
for object-orient... |
import spotipy
import spotipy.util as util
class AlbumInfo:
def __init__(self, name, artist, coverUrl, genres):
self.name = name
self.artist = artist
self.coverUrl = coverUrl
self.genres = genres
class SpotifyInfo:
spotify = None
def __init__(self, usern... |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: alpc32
# Date: 2017-09-12 22:29:40
# Last Modified by: alpc32
# Last Modified time: 2017-09-12 22:29:40
import time
import math
from file_handle import FileHandle
from mtools import queue, frame_info_queue, hexstr2int, AllConfig, PI, error_frame
def get_fram... |
"""
Taken from https://github.com/martinohanlon/quickdraw_python
Paritally modified to suit the needs of our projects.
"""
from PIL import Image, ImageDraw
import numpy as np
class QuickDrawing():
"""
Represents a single Quick, Draw! drawing.
"""
def __init__(self, name, drawing_data):
... |
import re
import logging
import time
pattern = [
u"%Y-%m-%d",
u"%Y-%m-%d %H:%M",
u"%Y-%m-%d %H:%M",
u"%Y-%m-%d %H:%M:%S",
u"%Y-%m-%d %H:%M:%S",
u"%Y/%m/%d",
u"%Y/%m/%d %H:%M",
u"%Y/%m/%d %H:%M",
u"%Y/%m/%d %H:%M:%S",
u"%Y/%m/%d %H:%M:%S",
u"%Y %m/%d",
u"%Y %m/%d %H:%... |
#!/usr/bin/env python
# coding: utf-8
"""
Extraire un tableau pour un Run en transitoire :
- zfond : point le plus bas du casier (issu de la géométrie des PCS)
- zmax : niveau maximum
- hmoy : hauteur moyenne maximum, calculée comme ratio Vol/Splan
Il faut que les variables Z, Vol et Splan soient disponibles aux casie... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.