content stringlengths 5 1.05M |
|---|
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import Volunteer
# Register your models here.
admin.site.register(Volunteer, UserAdmin) |
import paddle
if paddle.version.major == '2':
PP_v2 = True
from paddle.nn import functional as F
else:
PP_v2 = False
import numpy as np
from paddle import fluid
from paddle.fluid import dygraph
def kp2gaussian(kp, spatial_size, kp_variance: np.ndarray) -> np.ndarray:
"""
Transform a keypoint into ... |
"""
stanCode Breakout Project
Adapted from Eric Roberts's Breakout by
Sonja Johnson-Yu, Kylie Jue, Nick Bowman,
and Jerry Liao
YOUR DESCRIPTION HERE
"""
from campy.graphics.gwindow import GWindow
from campy.graphics.gobjects import GOval, GRect, GLabel
from campy.gui.events.mouse import onmouseclicked, onmousemoved
f... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 24 11:38:01 2017
@author: sajid
"""
import numpy as np
from numpy.fft import fftfreq
import numpy.fft as fft
from pyfftw.interfaces.numpy_fft import fftshift, fft2, ifft2
import numexpr as ne
'''
Propogation using the Transfer function method. Note that fftfreq has been... |
# -*- coding: utf-8 -*-
# Lumina User Guide documentation build configuration file.
# All configuration values have a default; values that are commented out
# serve to show the default.
import os
import six
import string
import sys
import time
# If extensions (or modules to document with autodoc) are in another direc... |
from setuptools import setup, find_packages
setup(
name='code.kottenator.com',
version='0.0.3',
description='A place to host my code experiments',
url='https://github.com/kottenator/code.kottenator.com',
author='Rostyslav Bryzgunov',
author_email='kottenator@gmail.com',
license='MIT',
p... |
# Copyright 2020 Google Inc. 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 required by applicable law or agree... |
class Connect():
def __init__(self, v1, v2):
self.v1 = v1
self.v2 = v2
def getHeight(self):
return (self.v1.getHeight() + self.v2.getHeight()) / 2.0
#if any connects had the same position, they would have to be referencing
#the same vertexes in this program
... |
from triphecta import vcf
def run(options):
vcf.sample_names_tsv_from_vcf_file_of_filenames(
options.file_of_vcf_filenames, options.out_tsv, threads=options.threads
)
|
expected_output = {"lines_match_regexp": 32102}
|
"""
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: strs = ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no ... |
from tkinter import *
import tkinter as tk
import requests
import pint
HEIGHT = 500
WIDTH = 500
def test_function(entry):
print("This is the entry:", entry)
def format_response(weather):
try:
name = weather['name']
desc = weather['weather'][0]['description']
temp = weather['main']['temp']
... |
import json
with open("Curso Udemy 2022/Nova_organizacao/aula_89_criando-lendo-escrevendo-apagando/first_js.json","r") as file:
json_file = file.read()
print(json_file)
with open("Curso Udemy 2022/Nova_organizacao/aula_89_criando-lendo-escrevendo-apagando/second_js.json","w+") as file:
file.write(j... |
''' 65-Unzip a zip archive '''
import zipfile
# Requires a zip archive called 'test.zip'
# in current directory.
un_zip = zipfile.ZipFile('test.zip')
# Will unzip contents of test.zip
# in same directory as .zip file.
un_zip.extractall()
# This will print out files found in the archive.
print (un_zip.namelist())
|
import numpy as np
import cv2
import torch
import os
import sys
import random
import torch.nn as nn
import torch.utils.data as tdata
import glob
from matplotlib import pyplot as plt
sys.path.append(".")
from visualizer_dataloader import thermaldataset
def visualize(data_sample):
data = data_sample['data']
label = ... |
#!/usr/bin/env python3
import numpy as np
import itertools as it
import copy
import sys
import subprocess
import socket
north = 0
east = 1
south = 2
west = 3
ne = 4
se = 5
so = 6
no = 7
valeurs = {
'A': 1,
'B': 3,
'C': 3,
'D': 2,
'E': 1,
'F': 4,
'G': 2,
'H': 4,
'I': 1,
'J': 6,
'K': 5,
'L': 1,... |
import pygame
from isomyr import physics
from isomyr.config import Keys
from isomyr.event import (
notify, PlayerDropItemEvent, PlayerPickUpItemEvent, PlayerUsingItemEvent)
from isomyr.gui.view import View
from isomyr.skin import ExaminableSkin
class Responder(object):
"""
This is used by the Engine obje... |
#!/usr/bin/env python3
# 有一个函数func1 能返回0和1 两个数值,返回0和1的概率都是1/2 怎么利用这个函数得到另一个函数func2
# 使func2也能返回0和1 且返回0的概率为1/4 返回1 的概率为3/4
# random.random() 返回0,1 之间的随机数
import random
# 返回0, 1 的概率都为1/2
def func1():
return int(round(random.random()))
# 返回0 1 的概率为1/4, 3/4
def func2():
a1 = func1()
a2 = func1()
t... |
import sys
import random
import time
from . import oph
#fitness will take a set s and a set of weights and return a tuple containing the fitness and the best path
def fitness( chrom, s, start_point, end_point, tmax ):
augs = []
for i in range( len( s ) ):
augs.append( ( s[ i ][0],
... |
from collections import deque
bullets_price = int(input())
barrel_size = int(input())
bullets = [int(x) for x in input().split()]
locks = deque([int(x) for x in input().split()])
intelligence = int(input())
counter = 0
bullets_used = 0
while bullets:
counter += 1
if counter % (barrel_size + 1) == 0:
... |
# flake8: noqa
import json
# ENS Default Registrar
registrar_abi = json.loads('[{"inputs":[{"internalType":"contract ENS","name":"_ens","type":"address"},{"internalType":"bytes32","name":"_baseNode","type":"bytes32"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"i... |
'''
Replace a sequence in a fasta file with new sequence
'''
import argparse
import sys
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
'-f', '--fasta_fn',
help='target fasta file'
)
parser.add_argument(
'-s', '--seq_name',
help='name of the seq... |
import FWCore.ParameterSet.Config as cms
from Validation.HcalDigis.HcalDigisParam_cfi import *
hltHCALdigisAnalyzer = hcaldigisAnalyzer.clone()
hltHCALdigisAnalyzer.dirName = cms.untracked.string("HLT/HCAL/Digis/Simulation")
hltHCALdigisAnalyzer.digiTag = cms.InputTag("hcalDigis")
hltHCALdigisAnalyzer.QIE1... |
from typing import Protocol, runtime_checkable
@runtime_checkable
class DataReaderBase(Protocol):
def ListOfLabels(self):
...
def ImageName(self) -> str:
...
def ImagePath(self) -> str:
...
def ReadLabelSource(self, source) -> None:
...
|
# Copyright (c) 2017 Huawei, 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 a... |
import nltk
import string
import pandas as pd
import numpy as np
def _clean_string(text):
'''Remove punctuation and stopwords, and put into lower case.
Args:
text (str): text to be cleaned--text will have stopwords and
punctuation removed, and will be put into lower case.
Returns:
... |
from kingfisher_scrapy.base_spiders import IndexSpider, PeriodicSpider
from kingfisher_scrapy.util import components, handle_http_error, parameters
class EcuadorSERCOPAPI(PeriodicSpider, IndexSpider):
"""
Domain
Servicio Nacional de Contratación Pública (SERCOP)
Spider arguments
from_date
... |
import copy
world = [list(input()) for _ in range(10)]
# 移動は4方向
move = [(0, 1), (1, 0), (0, -1), (-1, 0)]
# 繋がっている島1つを"x"で塗りつぶす
def dfs(x, y):
world2[x][y] = "x"
for dx, dy in move:
nx = x + dx
ny = y + dy
if 0 <= nx and nx < 10 and 0 <= ny and ny < 10 and world2[nx][ny] == "o":
... |
#!/usr/bin/python
# coding=utf-8
"""
第 0017 题: 将 第 0014 题中的 student.xls 文件中的内容写到 student.xml 文件中,如
下所示:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<students>
<!--
学生信息表
"id" : [名字, 数学, 语文, 英文]
-->
{
"1" : ["张三", 150, 120, 100],
"2" : ["李四", 90, 99, 95],
"3" : ["王五", 60, 66, 68]
}
</students>
<... |
import numpy as np
import os
import torch
from threading import Thread
from fairseq.data import data_utils, FairseqDataset, FairseqIterableDataset
class DictIterDataset(FairseqIterableDataset):
def __init__(self, defn, sizes=None):
self.defn = defn
for v in self.defn.values():
if not isinstance(v, (F... |
from keras.layers import Activation, Convolution2D, Dense, Dropout, Flatten, MaxPooling2D
from keras.models import Sequential
import numpy as np
import matplotlib.pyplot as plt
import itertools
from tabulate import tabulate
def create_model(input_size, n_categories):
"""
Create a simple baseline CNN
Ar... |
import unittest
from hamcrest import greater_than, assert_that
from behavioral.observer.observable import TempObservable, HumidObservable
from behavioral.observer.observer import TempObserver, HumidObserver
class TestClient(unittest.TestCase):
def test(self):
temp_sensor = TempObservable()
humid_... |
import argparse
import sys
import h5py
import numpy
from PyQt5.QtCore import QObject
from PyQt5.QtWidgets import (
QApplication,
QGraphicsView,
QHeaderView,
QLabel,
QListWidget,
QTableWidget,
QTabWidget,
)
from mlxtk.tools.diagonalize import diagonalize_1b_operator
from mlxtk.ui import loa... |
#################################################################################
# The Institute for the Design of Advanced Energy Systems Integrated Platform
# Framework (IDAES IP) was produced under the DOE Institute for the
# Design of Advanced Energy Systems (IDAES), and is copyright (c) 2018-2021
# by the softwar... |
from random import randint
numero_aleatorio = randint(1, 101)
contador = 0
while True:
contador += 1
numero_secreto = input("Adivinhe o numero secreto de 1 a 100: ")
if numero_secreto == "sair":
print("Sair")
break
numero_secreto = int(numero_secreto)
if numero_secreto > numero_ale... |
# source: https://github.com/dido1998/Recurrent-Independent-Mechanisms
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
import numpy as np
import torch.multiprocessing as mp
import random
class blocked_grad(torch.autograd.Function):
@staticmethod
def forward(ctx, x, mask):
... |
"""
@ jetou
@ perceptron Duality
@ date 2017 11 01
"""
import numpy as np
class perceptron:
def __init__(self, feature, label, gama=1):
self.feature = feature.transpose()
self.label = label.transpose()
self.__feature = feature
self.row = self.feature.shape[0]
s... |
import xbmc,xbmcaddon,xbmcgui,xbmcplugin,urllib,urllib2,re,os,sys
def TVShows(url):
stringlist=''
link=open_url(url)
try:
np=re.compile("<link rel='next' href='(.+?)'").findall(link)[0]
stringlist=stringlist+'<np>'+np+'<np>'
except: pass
shows=re.compile('<article class="film1">(.+?... |
# This file is part of h5py, a Python interface to the HDF5 library.
#
# http://www.h5py.org
#
# Copyright 2008-2013 Andrew Collette and contributors
#
# License: Standard 3-clause BSD; see "license.txt" for full license terms
# and contributor agreement.
from __future__ import absolute_import
try:
fro... |
a = 4+3j
print hasattr(a, 'imag')
print getattr(a, 'real')
def b(): pass
setattr(b, 'foo', -1)
print b.foo
|
#-*-coding:utf8;-*-
#qpy:console
import math
nada = '\033[m'
title = '\033[01;34m'
amarelo = '\033[33m'
rosa = '\033[35m'
caule = ("""
⣿⣿⣿⣿⠿⢋⣩⣤⣴⣶⣶⣦⣙⣉⣉⣉⣉⣙⡛⢋⣥⣶⣶⣶⣶⣶⣬⡙⢿⣿
⣿⣿⠟⣡⣶⣿⢟⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣦⠙
⣿⢋⣼⣿⠟⣱⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣟⢿⣿⣿⣿⣿⣧
⠃⣾⣯⣿⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣯⣿⣿⡈⢿⣿⣿⣿⣿
⢰⣶⣼⣿⣷⣿⣽⠿⣽⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡌⣿⣷⡀⠛⢿⣿⣿
⢃⣺⣿⣿⣿⢿⠏⢀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿... |
# -*- coding: utf-8 -*-
# <sure - utility belt for automated testing in python>
# Copyright (C) <2012> Gabriel Falcão <gabriel@nacaolivre.org>
# Copyright (C) <2012> Lincoln Clarete <lincoln@comum.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Pub... |
"""
Системный администратор вспомнил, что давно не делал архива пользовательских файлов. Однако, объем диска,
куда он может поместить архив, может быть меньше чем суммарный объем архивируемых файлов.
Известно, какой объем занимают файлы каждого пользователя.
Напишите программу, которая по заданной информации о пользова... |
import FileHandeling as fh;
import os;
CounterFilePath = "Users/nischaya/Documents/python-codes/files/counter.txt";
FilePath = "Users/nischaya/Documents/python-codes/files/Employee.txt";
def createEmployee(empFName, empLName, empSalary, empEmailId):
string = empFName+"|"+empLName+"|"+empSalary+"|"+empEmailId+"\n... |
RANGE = 30.0
L = 100.0
nS = 100
nD = 20
Vmax = 2.0
global DRONES
global SURVIVORS
global missions
global output_file
DRONES= []
SURVIVORS= []
missions= []
output_file= open('out.txt', 'w')
|
# Generated by Django 2.1.7 on 2019-03-28 17:39
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0002_auto_20190328_1715'),
]
operations = [
migrations.AddField(
model_name='user',
... |
"""
The maps that model the different processes in the QKD return for input that is diagonal in Bell-basis a diagonal output.
To reduce calculations I determined in the scipt "How many numbers for state" the effect of the maps on the diagonal elements
"""
import numpy as np
import functools
"""These are some helper fu... |
import os
from ceph_salt.salt_utils import PillarManager
from . import SaltMockTestCase
class PillarManagerTest(SaltMockTestCase):
def tearDown(self):
super(PillarManagerTest, self).tearDown()
PillarManager.reload()
def test_pillar_set(self):
PillarManager.set('ceph-salt:test:enabled... |
# My initial solution. 14 / 30 test cases passed.
class Solution(object):
def duplicateZeros(self, arr):
"""
:type arr: List[int]
:rtype: None Do not return anything, modify arr in-place instead.
"""
zeros = []
for i in range(len(arr)):
if arr[i] == 0:
... |
import tensorflow as tf
import numpy as np
import math
from data import input_data
from data import tag_data
input_num=100
data_len=2
output_num=1
test=[]
for i in range(100):
test.append([1,100])
def structure(input_val,hidden1_unit,hidden2_unit):
with tf.name_scope('hidden1'):
w=tf.Variable(tf.truncated_norma... |
from . import verb
from .. import entities
import textwrap
class Who(verb.Verb):
"""Show a list of connected players"""
command = _('who')
verbtype = verb.VERSATILE
def process(self, message):
out_message = self.get_player_list()
self.session.send_to_client(out_message)
self.f... |
from terraingrid import TerrainGrid
import matplotlib.pyplot as plt
import scipy.signal as sig
import scipy.ndimage as ndi
import cv2 as cv
import numpy as np
import numpy.ma as ma
def gradient_x(imggray):
##Sobel operator kernels.
kernel_x = np.array([[-1, 0, 1],[-2, 0, 2],[-1, 0, 1]])
return sig.convolve... |
from __future__ import print_function, division
import numpy
import matplotlib.pyplot as plt
import h5py
from numpy import exp, pi, arctan
import sys
def gauss(x, A, mu, sig):
xT = x.reshape((1,-1))
AT = A.reshape((-1,1))
muT = mu.reshape((-1,1))
sigT = sig.reshape((-1,1))
return AT * exp(-0.5 * ((muT - xT)/sigT)... |
#######################################
# Some words about this file
# created by
# Martin Gottwald, martin.gottwald@tum.de
# edited by
# Sven Gronauer, sven.gronauer@tum.de
#######################################
import tensorflow as tf
from tensorflow.python.keras import datasets
import numpy as np
from tensorbox.c... |
X = int(input())
Y = int(input())
crescente = []
if X < Y:
for number in range(X+1, Y):
if number % 5 == 2 or number % 5 == 3:
crescente.append(number)
elif X > Y:
for number in range(Y+1, X):
if number % 5 == 2 or number % 5 == 3:
crescente.append(number)
crescente.sort(... |
import torch
import torch.nn.functional as F
from torch.autograd import Variable
from torch.nn.utils import clip_grad_norm_
import numpy as np
from utils.utils import ensure_shared_grads
from params import params
def preprocess(obs, gpu_id):
state = np.concatenate([obs[0], obs[1], obs[2], obs[3]]) / 255.
sta... |
from pylab import *
import os
import matplotlib.patches as patches
import matplotlib.transforms as transforms
def makefig(medVAR, avrVAR, stdVAR, nVAR, tnorm,
SUBTITLE, YLIMS, YLAB, fname_fig):
fig = figure(1, figsize=(13, 6))
ax = fig.add_subplot(111)
ax.plot(tnorm, avrVAR, 'o-', color=... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import flask
from amberalertcn import httplib
import hashlib
import datetime
import calendar
ACCEPTED_CONTENT_ENCODING = "utf-8"
def generate_baidu_auth_uri(base_uri, params, baidu_ak, baidu_sk):
"""A helper function to generate URI with Baidu's SN"""
safe = "/:=&... |
"""
spotify-runners python package configuration.
"""
from setuptools import setup
setup(
name="spotifyrunners",
version="0.1.0",
packages=["spotifyrunners"],
include_package_data=True,
install_requires=[
"Flask==1.1.1",
"Flask-Testing==0.7.1",
"html5validator==0.3.1",
... |
#!/usr/bin/env python3
from PyQt5 import QtWidgets
import sys
"""
QGridLayout: Allows easy grid-shape layout management.
Buttons and other similar elements in the GUI are dynamically re-sized w.r.t. window dimensions.
"""
def create_window():
# Define window:
obj = QtWidgets.QApplication(s... |
from ipywidgets import *
print(IntSlider()) |
# Copyright (C) 2001-2005 Nominum, Inc.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose with or without fee is hereby granted,
# provided that the above copyright notice and this permission notice
# appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND ... |
# Copyright 2019 Nokia
#
# 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, softwa... |
#!/usr/bin/env python
from road import Road
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
''' Main script to run the traffic jam simulation. '''
n_cars = 70
n_timesteps = 100
# starting_space = 100
starting_velocity = 2
def simple_run(n_timesteps):
''' Run the simulation for a given num... |
"""
Provide implementation of account.
"""
import json
import os
import requests
import eospy.keys
from eospy.cleos import Cleos
APPLICATION_JSON_HEADERS = {
'accept': "application/json",
'content-type': "application/json"
}
MASTER_WALLET_PRIVATE_KEY = os.environ.get('MASTER_WALLET_PRIVATE_KEY')
MASTER_ACCOU... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import codecs
import DataBaseManager
import GetData
from pandas.tools.plotting import andrews_curves
import seaborn as sns
Head = ['AQI', '范围', '质量等级', 'PM2.5', 'PM10', 'SO2', 'CO', 'NO2', 'O3']
CityListO = codecs.open("CityList.info", "r... |
#
# PySNMP MIB module ZHNPWMIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZHNPWMIB
# Produced by pysmi-0.3.4 at Wed May 1 15:46:45 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:1... |
import requests
# from pymongo import MongoClient
import re
import json
def download_video(video_links):
root = './video/'
for link in video_links:
file_name = link.split('/')[-1]
file_name = re.sub(r'\?.*', '', file_name)
print("download process: %s" % file_name)
r... |
import base64
import json
import random
import re
import time
import requests
from Crypto.Cipher import PKCS1_v1_5
from Crypto.PublicKey import RSA
from callback_ import get_callback, get_callback_p
from gid import get_gid
from part_params import get_params, get_dv, get_fs, get_traceid
def login(user... |
from ns.ethernet.frame import EthernetFrame
from ns.mac import BROADCAST_MAC_ADDRESS
class Node:
def __init__(self, mac_addr, broadcast_domain):
self._mac_addr = mac_addr
self.broadcast_domain = broadcast_domain
self._connected_nodes = { mac_addr: self }
self._connected_routers = {}
self._connect... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
For cleaning & sorting entries in a YAML file
"""
from utils.yaml_organizer import YamlWrapper
from utils.logger import Log
log = Log('filter-cleaner')
log.debug('Initializing script')
# Read in the YAML file
# Debug
# When True: points to the example yaml file in ... |
import datetime
from django.contrib.gis.geos import LineString, Point
from django.db.models import Count
from django.http import JsonResponse
from django.shortcuts import redirect, render
from django.urls import reverse
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_... |
import smart_imports
smart_imports.all()
class Invoice(django_models.Model):
XSOLLA_ID_MAX_LENGTH = 255
XSOLLA_V1_MAX_LENGTH = 255
XSOLLA_V2_MAX_LENGTH = 200
XSOLLA_V3_MAX_LENGTH = 100
COMMENT_MAX_LENGTH = 255
REQUEST_URL_LENGTH = 1024
created_at = django_models.DateTimeField(auto_now_... |
from __future__ import (division)
from pomegranate import *
from nose.tools import with_setup
from nose.tools import assert_almost_equal
from nose.tools import assert_equal
from nose.tools import assert_not_equal
from nose.tools import assert_less_equal
from nose.tools import assert_raises
import pickle
import random
... |
# Copyright 2020 LMNT, Inc. 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 required by applicable law or ag... |
""" Rule for building CMake from sources. """
load("//foreign_cc:defs.bzl", "configure_make")
def cmake_tool(name, srcs, **kwargs):
tags = ["manual"] + kwargs.pop("tags", [])
configure_make(
name = "_build_{}".format(name),
configure_command = "bootstrap",
configure_options = ["--", "... |
from typing import Dict
from src.python.review.inspectors.issue import IssueType
# C convention related checks
# R refactoring related checks
# W warnings for stylistic issues, or minor programming issues
# E errors, for probable bugs in the code
CODE_TO_ISSUE_TYPE: Dict[str, IssueType] = {
'W0101': IssueType.ER... |
##
## base.py: Includes utility functions
## Author: Aditya Patange
##
from requests import get
from requests.exceptions import RequestException
from contextlib import closing
from bs4 import BeautifulSoup
import re
import string
import json
tagNames = {
## BSE
'BseCurrent': 'Bse_Prc_tick',
'BseUploadTime': 'b... |
import uuid
import pytest
import requests_mock as rm_module
from loguru import logger
from pytest_mock import MockerFixture
from ct8_refresh.constants import SIGNIN_URL
from ct8_refresh.ct8 import CT8
logger.remove()
@pytest.fixture
def ct8_account():
return CT8(username='john', password='password123')
# def... |
# -*- coding:utf-8 -*-
from simple_ml.svm import *
from simple_ml.classify_data import *
from simple_ml.data_handle import train_test_split
def iris_example():
"""
线性可分情况
:return:
"""
x, y = get_iris()
x = x[(y == 0) | (y == 1)]
y = y[(y == 0) | (y == 1)]
x_train, y_train, x_test, y_... |
import io
import logging
from typing import TYPE_CHECKING, BinaryIO, List, Union
import lxml.etree as et
from PIL import Image
from ..render.backends.svg.utils import svg_size_to_pixels
from ..render.image import create_image_data, get_image_steps
from ..render.ora import convert_ora_to_svg
from ..shapes import arrow... |
# -*- coding: utf-8 -*-
from .default import * # noqa
BKDATA_URL = f"{os.getenv('BK_PAAS_HOST', '')}/t/bk_dataweb"
|
import os
from flask import (Flask, flash, render_template,
redirect, request, session, url_for)
from flask_pymongo import PyMongo
from bson.objectid import ObjectId
from werkzeug.security import generate_password_hash, check_password_hash
if os.path.exists("env.py"):
import env
app = Flask(__... |
from .. import deprecated
if deprecated.allowed(): # pragma: no cover
from . reshape import crop, resize
from . load_image import show_image, showImage, loadImage
from . gif import (
animated_gif_to_colorlists, convert_mode, image_to_colorlist)
|
#!/usr/bin/env python
import datetime
import numpy as np
import cv2
import rospy
import dynamic_reconfigure.client
from fractions import Fraction
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
from ansel.srv import Ansel, AnselResponse
class ansel:
def __init__(self):
self... |
from flask import Flask
import ghhops_server as hs
import rhino3dm
# register hops app as middleware
app = Flask(__name__)
hops = hs.Hops(app)
@hops.component(
"/pointat",
name="PointAt",
description="Get point along curve",
inputs=[
hs.HopsCurve("Curve", "C", "Curve to evaluate"),
hs.... |
from sitepipes import config
from sitepipes.datasets.meta import MetaDataset
from abc import abstractmethod
import logging
import os
class Dataset(metaclass=MetaDataset):
""" A parent class for all data that flows between components """
name = None
_schema = []
_df_history = []
def __init__(s... |
# Convenience test module to run all of the XML-related tests in the
# standard library.
import sys
import test.test_support
test.test_support.verbose = 0
def runtest(name):
__import__(name)
module = sys.modules[name]
if hasattr(module, "test_main"):
module.test_main()
runtest("test.test_minidom... |
'''<yasir_ahmad>
Write a program to input n numbers of integer in a list and print the maximum even numberr present in it , if no even number is present, then
print('No even numbers is present !')
'''
l=[]
for i in range(int(input('Enter no. of entries: '))):
l.append(int(input()))
evn_number=-1 #-1 is de... |
import os
from PIL import Image
from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub import PubNub
pnconfig = PNConfiguration()
pnconfig.publish_key = os.environ["PUBNUB_PUBKEY"]
pnconfig.subscribe_key = os.environ["PUBNUB_SUBKEY"]
pnconfig.uuid = "serverUUID-PUB"
pubnub = PubNub(pnconfig)
with ope... |
"""
Migration script to add an inheritable column to the following tables:
library_info_association, library_folder_info_association.
Also, in case of sqlite check if the previous migration script deleted the
request table and if so, restore the table.
"""
import datetime
import logging
from sqlalchemy import Boolean... |
from main import name_n
def test_function_name_n():
# тест 1 - подается одноэлементный список
n_list = ['Sarah']
list_out = name_n(n_list, 2) # ('Sarah', 'Sarah')
if list_out == ['Sarah', 'Sarah']:
print('Test 1 is OK')
else:
print('Test 1 is failed')
#тест 2 - если на вход ... |
import mysql.connector
import datetime
from flame.utils import import_conofiguration as icnf
config = icnf(config_file='flame/setting.ini')
mysql_info = {'DB_HOST': config['DB_HOST'], 'DB_NAME': config['DB_NAME'],
'DB_USER': config['DB_USER'], 'DB_PASSWORD': config['DB_PASSWORD']
,'CHARSET': c... |
from cpt.packager import ConanMultiPackager
if __name__ == "__main__":
builder = ConanMultiPackager()
if not builder.skip_check_credentials:
builder.remotes_manager.add_remotes_to_conan()
builder.auth_manager.login(builder.remotes_manager.upload_remote_name)
name, version, user, channe... |
import typing
import pandas as pd
import operator as op
from collections import Counter
from functools import reduce
from typing import Dict, Iterable, List, Tuple, NamedTuple
from itertools import product
from vivarium_public_health.metrics import (MortalityObserver as MortalityObserver_,
... |
# simple inquiry example
import bluetooth
nearby_devices = bluetooth.discover_devices(lookup_names=True)
print("found %d devices" % len(nearby_devices))
for addr, name in nearby_devices:
print(" %s - %s" % (addr, name)) |
# -*- coding: UTF-8 -*-
# Copyright 2014-2018 Rumma & Ko Ltd
# License: BSD (see file COPYING for details)
SETUP_INFO = dict(
name='lino-cosi',
# version='0.0.4',
version='18.8.0',
install_requires=['lino-xl','django-iban', 'lxml'],
tests_require=['beautifulsoup4',],
test_suite='tests',
des... |
name = input("nama : ")
address = input("alamat : ")
age = input("umur : ")
email = input("email : ")
line1 = "Name: " + name + ", Address: " + address
line2 = "Age: " + age + ", Email: " + email
print(line1)
print(line2) |
# Author : Antoine Broyelle
# Licence : MIT
# inspired by : KTH - DD2432 : Artificial Neural Networks and Other Learning Systems
# https://www.kth.se/student/kurser/kurs/DD2432?l=en
import numpy as np
from kmeans import Kmeans
from pcn import PCN
from utils.distances import euclidianDist
class RBF:
'''Radial Basi... |
import numpy as np
import scipy as sp
import os
from PIL import Image, ImageOps
from scipy import ndimage
def random_image(folders, show=False):
"""
display a random image inside a list of directories.
"""
folder = np.random.choice(folders)
image_file = os.path.join(folder,np.random.choice(os.listdir(folder)))
i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.