content stringlengths 5 1.05M |
|---|
"""
Skeletonizer: Python Cell Morphology Analysis and Construction Toolkit
KAUST, BESE, Neuro-Inspired Computing Project
(c) 2014-2015. All rights reserved.
"""
"""
Amiramesh module.
"""
import re
import sys
import logging
#
# Node class
#
class Node(object):
"""Graph node point class in 3D spac... |
import xml.etree.ElementTree as ET
from lxml import objectify
from xml.dom import minidom
import sys
import re
# Take h files and create xml files
# fixup the XML such that it accounts for padding
# fixup the XML such that enums and vals are included from other headers
debug=0
tree = ET.parse(sys.argv[1])
print("XML ... |
import opengm
import numpy
np = numpy
#---------------------------------------------------------------
# MinSum with SelfFusion
#---------------------------------------------------------------
numpy.random.seed(42)
#gm=opengm.loadGm("/home/tbeier/datasets/image-seg/3096.bmp.h5","gm")
#gm=opengm.loadGm("/home/tbeier/d... |
import numpy as np
import urllib2 as ulib
import csv
import psycopg2
import sys
import time
import json
'''
to do:
SUPERTARGET
BRENDA
DsigDB
'''
sys.path.append('../../utility')
from map_id_util import mapUniprotToKEGG,mapKEGGToCAS,mapPCToCAS,baseURL
sys.path.append('../../config')
from database_config import databas... |
from data_resource.generator.api_manager.v1_0_0.resource_handler import ResourceHandler
import pytest
from data_resource.shared_utils.api_exceptions import ApiError
from data_resource.db.base import db_session
@pytest.mark.requiresdb
def test_query_works_with_correct_data(valid_people_orm):
resource_handler = Res... |
import tkinter as tk
from PIL import Image, ImageTk
from tkinter import *
w = OptionMenu(master, variable, "one", "two", "three")
w.config(bg = "GREEN") # Set background color to green
# Set this to what you want, I'm assuming "green"...
w["menu"].config(bg="GREEN")
w.pack() |
class Solution:
def maxSumMinProduct(self, nums: List[int]) -> int:
ans = 0
stack = []
prefix = [0] + list(accumulate(nums))
for i in range(len(nums) + 1):
while stack and (i == len(nums) or nums[stack[-1]] > nums[i]):
minVal = nums[stack.pop()]
sum = prefix[i] - prefix[stack[-1... |
from azure.storage.blob import BlobService
import datetime
import string
from verify_oauth import verify_oauth
accountName = 'jesse15'
accountKey = ''
blob_service = BlobService(accountName, accountKey)
uploaded = False
def uploadBlob(username, file, filename, token, secret):
global uploaded
returnList = []
... |
import os
from flask_sqlalchemy import SQLAlchemy
app = None
db:SQLAlchemy = None
|
# Generated by Django 3.0.5 on 2020-07-11 05:18
from django.db import migrations, models
import django.utils.timezone
import taggit.managers
class Migration(migrations.Migration):
dependencies = [
('taggit', '0003_taggeditem_add_unique_index'),
('listelement', '0004_auto_20200630_0029'),
]
... |
__author__ = 'stev1090'
|
system.exec_command("bspc wm -h off; bspc node older -f; bspc wm -h on", getOutput=False) |
from picar_4wd.utils import mapping
class Servo():
PERIOD = 4095
PRESCALER = 10
MAX_PW = 2500
MIN_PW = 500
FREQ = 50
ARR = 4095
CPU_CLOCK = 72000000
def __init__(self, pin, offset=0):
self.pin = pin
self.offset = offset
self.pin.period(self.PERIOD)
presca... |
import xbmc,xbmcaddon,xbmcgui,xbmcplugin,urllib,urllib2,os,re,sys,datetime,shutil
SiteName='Space Telescope 0.0.1'
addon_id = 'plugin.video.spacetelescope'
baseurl = 'http://www.spacetelescope.org/videos/'
videobase = 'http://www.spacetelescope.org'
fanart = xbmc.translatePath(os.path.join('special://home/addons/' + ... |
# This code is part of the project "Krill"
# Copyright (c) 2020 Hongzheng Chen
def get_prop_class(job_prop,pb_name):
prop_name, type_name, initial_val = job_prop
class_name = "{}".format(prop_name)
if type_name == "uint":
type_name = "uintE"
elif type_name == "int":
type_name = "intE"
... |
from django.shortcuts import render
from django.http import JsonResponse, HttpResponse
from .models import *
import random
from django.db.models import Q
# Load Table Page
def ldsp(request):
return render(request, 'ldsp/index.html')
# Load Table Data
def ldspData(request):
# Get the data from request
se... |
from statistics import mean
from signal_processing_algorithms.energy_statistics import energy_statistics
def jump_detection(time_series, relative_threshold = 0.05):
jump_points = []
idx=1
last_point = time_series[0]
for current_point in time_series[1:]:
relative_change = abs((current_point/... |
# Leet spek generator. Leet é uma forma de se escrever o alfabeto latino usando outros símbolos em lugar das letras' como
# números por exemplo. A própria palavra leet admite muitas variações' como l33t ou 1337. O uso do leet reflete uma
# subcultura relacionada ao mundo dos jogos de computador e internet' sendo muito ... |
class Calendar(dict):
fields = [
'id',
'name',
'type',
'uid',
'url',
'updated',
'enabled',
'defaultCategory',
'external',
]
def __init__(self, **kwargs):
for field in kwargs.keys():
if field not in Calendar.fields:
... |
import hashlib
import os
import socket
import time
from django.core.cache import get_cache
from django.core.files.base import ContentFile
from django.utils import simplejson
from django.utils.encoding import smart_str
from django.utils.functional import SimpleLazyObject
from django.utils.importlib import import_module... |
"""
Created on Thu Sep 17 01:23:14 2020
@author: anish.gupta
"""
from flask import Flask, request, jsonify
import numpy as np
import pickle
import pandas as pd
import flasgger
from flasgger import Swagger
# from clean import preprocess
from fastai.text import load_learner, DatasetType
from flasgger import APISpec,... |
#!/usr/bin/python
#-*- coding: utf-8 -*-
# >.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.
# Licensed under the Apache License, Version 2.0 (the "License")
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# --- File Name: spatial_biased_networks.py
# --- Creation Date: 20-01-2020
# --- Last Mod... |
from flask import Flask, render_template, request, redirect, session, jsonify
from datetime import datetime
import csv
import json
app = Flask(__name__)
app.config['SECRET_KEY'] = "some_random"
app.config['SESSION_TYPE'] = 'filesystem'
app.config['SESSION_PERMANENT'] = False
# Dictionary containing all foods
co2_dic... |
'''
Log generation simulation with different durations and rates.
'''
import os
import time
import random
from time import sleep
from datetime import datetime
import logging
log_format = '%(asctime)s %(levelname)s %(message)s'
logging.basicConfig(format=log_format, level=logging.INFO)
class LogGenerator:
'''
... |
"""Remote client command for creating image from container."""
import sys
import podman
from pypodman.lib import AbstractActionBase, BooleanAction, ChangeAction
class Commit(AbstractActionBase):
"""Class for creating image from container."""
@classmethod
def subparser(cls, parent):
"""Add Commit... |
# Copyright 2021 The gRPC Authors
#
# 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 writ... |
import random
import string
from fake_gen.base import Factory
class RandomLengthStringFactory(Factory):
"""
Generates random strings between 2 lengths
:param min_chars: minimum amount of characters
:param max_chars: maximum amount of characters
:param prefix: string that must be present before th... |
from unittest import mock
from tests.util.test_util import perform_test_ca_sign, find_test_ca_sign_url
from xrdsst.controllers.auto import AutoController
from xrdsst.controllers.base import BaseController
from xrdsst.controllers.cert import CertController
from xrdsst.controllers.status import StatusController
from xrd... |
# encoding: utf-8
from opendatatools.common import RestAgent
from bs4 import BeautifulSoup
import json
import pandas as pd
import datetime
index_map={
'SSEC' : '上证综合指数',
'SZSC1' : '深证成份指数(价格)',
'FTXIN9' : '富时中国A50指数',
'DJSH' : '道琼斯上海指数',
'HSI' : '香港恒生指数 (CFD)',
... |
#!/usr/bin/env python3
# Copyright (c) 2014-2016 The MagnaChain Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Base class for RPC testing."""
from collections import deque
from enum import Enum
import logging
i... |
import torch
from torch_geometric.datasets import Planetoid
import torch.nn.functional as F
from torch_geometric.nn import GATConv
device = torch.device('cuda:2')
class Net(torch.nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = GATConv(1433, 8, heads=8, dropout=0.6)
... |
import glob
import logging
import math
import os
import pickle
import re
from itertools import product
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from sklearn.model_selection import ShuffleSplit, learning_curve
from .classifiers import custom_dict
from .utils imp... |
from . import features
from . import models
from . import preprocess
from . import utils
from . import visualizations
|
from databases import Database, DatabaseURL
import os
from .config import load_config, Config
from .generators.empty import EmptyGenerator
from .generators.initial import InitialGenerator
from .tables import (
db_create_migrations_table_if_not_exists,
db_load_migrations_table,
db_apply_migration,
db_una... |
import numpy as np
from taurex.model.simplemodel import SimpleForwardModel
import pycuda.autoinit
from pycuda.compiler import SourceModule
import pycuda.driver as drv
from pycuda.gpuarray import GPUArray, to_gpu, zeros
from functools import lru_cache
import math
from ..utils.emission import cuda_blackbody
import pycuda... |
"""OWASP Dependency Check dependencies collector."""
from xml.etree.ElementTree import Element # nosec, Element is not available from defusedxml, but only used as type
from collector_utilities.functions import parse_source_response_xml_with_namespace, sha1_hash
from collector_utilities.type import Namespaces
from mo... |
import pytest
from libpythonpro.spam.enviador_de_email import Enviador, EmailInvalido
def test_criar_enviador_de_email():
enviador = Enviador()
assert enviador is not None
@pytest.mark.parametrize(
'remetente',
['contato@smkbarbosa.eti.br', 'foo@bar.com.br']
)
def test_remetente(remetente):
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache License, Ve... |
from . import isotropic_cov_funs
import numpy as np
__all__ = ['nsmatern','nsmatern_diag','default_h']
def default_h(x):
return np.ones(x.shape[:-1])
def nsmatern(C,x,y,diff_degree,amp=1.,scale=1.,h=default_h,cmin=0,cmax=-1,symm=False):
"""
A covariance function. Remember, broadcasting for covariance ... |
import os.path
import pandas as pd
from datetime import date
from distutils import dir_util
import requests
from pandas.io.json import json_normalize
from resources import constants
from utils import data_utils, api_utils
import time
import json
"""
This script currently updates the committed and paid funding for ap... |
"""
Quantiphyse - Processes for basic loading/saving of data
Copyright (c) 2013-2020 University of Oxford
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... |
from __future__ import print_function, absolute_import, division
import os
import numpy as np
from tqdm import tqdm
import cv2
import argparse
import torch
import torch.nn as nn
import torch.optim
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
from model.mesh_graph_hg import ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import argparse
from functools import reduce
def arguments():
# Handle command line arguments
parser = argparse.ArgumentParser(description='Adventofcode.')
parser.add_argument('-f', '--file', required=True)
args = parser.parse_args()
return args
class ... |
from graph.graph import Graph
def gain(K, Z, vModify, g, list):
""" calcoliamo il guadagno tra il set X-Z e Z.
Args:
K (set): insieme dove è stato rimosso v
Z (set): insieme dove è stato aggiunto v
vModify (vertex): nodo che aggiungiamo/togliamo per valutarne il guadagno
g (gr... |
def queda(lista):
for i in range(1, len(lista)):
if lista[i]<lista[i-1]:
return i+1
return 0
n = int(input())
r = list(map(int, input().split()))
print(queda(r)) |
# mosromgr: Python library for managing MOS running orders
# Copyright 2021 BBC
# SPDX-License-Identifier: Apache-2.0
from mosromgr.cli import main
import pytest
def test_args_incorrect():
with pytest.raises(SystemExit):
main(['--nonexistentarg'])
def test_help(capsys):
with pytest.raises(SystemExit... |
import argparse
import textwrap
from wordle import Wordle
class ArgumentDefaultsHelpFormatter(argparse.RawTextHelpFormatter):
def _get_help_string(self, action):
return textwrap.dedent(action.help)
def start():
parser = argparse.ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter)
parse... |
from typing import List
class Solution:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
res = []
flag = True
for interval in intervals:
# 1. 没有交集的情况
if interval[1] < newInterval[0]:
res.append(interval)
... |
import os
env = os.environ
#: The Celery broker URL used by webhook.
celery_broker = env.get("CELERY_BROKER", "redis://localhost:6379")
#: The Celery backend used by webhook.
celery_backend = env.get("CELERY_BACKEND", "redis://localhost:6379")
#: The secret used for encoding GitHub commit message.
webhook_secret =... |
"""Custom errors, error handler functions and function to register error
handlers with a Connexion app instance."""
import logging
from connexion import App, ProblemException
from connexion.exceptions import (
ExtraParameterProblem,
Forbidden,
Unauthorized
)
from flask import Response
from json import dum... |
import argparse
import os
import sys
from dotenv import load_dotenv
from sendgrid.helpers.mail import Mail
from requests.exceptions import RequestException
from bude_hezky.content import content_builder
from bude_hezky.sender import email_sender
from bude_hezky.weather import weather_forecast
CITY_OPTION_KEY = 'mest... |
import json
import os
import tensorflow as tf
import numpy as np
import datetime as dt
from collections import defaultdict
import gaussian_variables as gv
def start_run():
pid = os.getpid()
run_id = "%s_%s" % (dt.datetime.now().strftime('%Y%m%d_%H%M%S'), pid)
np.random.seed(0)
tf.set_random_seed(0)
... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
"""
File name: screenshot.py
Author: Fredrik Forsberg
Date created: 2020-11-11
Date last modified: 2020-11-11
Python Version: 3.8
"""
import numpy as np
import cv2
from PIL import ImageGrab
###
def pil_screenshot(all_screens=True):
"""
Ret... |
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from django.contrib.auth.models import Group,Permission
from meiduo_admin.serializers.groups import GroupSerializer
from meiduo_admin.serializers.permission import Permission... |
from __future__ import print_function, absolute_import, division
import sys
import click
CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
import ec2hosts
def main():
try:
cli(obj={})
except Exception as e:
import traceback
click.echo(traceback.format_exc(), err=True)
... |
import random
# Helper functions ----------------------------------------------------------------------------------------------------------------------------------
def make_node_barrier(node):
"""Turns a node into a hard barrier."""
node.make_barrier()
node.is_hard_barrier = True
return node
def no... |
from loguru import logger
from mass_spec_utils.data_import.mzmine import load_picked_boxes, map_boxes_to_scans
from mass_spec_utils.data_import.mzml import MZMLFile
from vimms.Roi import make_roi
def picked_peaks_evaluation(mzml_file, picked_peaks_file):
boxes = load_picked_boxes(picked_peaks_file)
mz_file =... |
from django.contrib import admin
from .models import UserProfile,Teacher,Timetable,Klass,Pupil,Cabinet,Subject, Grade
admin.site.register(UserProfile)
admin.site.register(Teacher)
admin.site.register(Timetable)
admin.site.register(Klass)
admin.site.register(Pupil)
admin.site.register(Cabinet)
admin.site.regis... |
import json
import pandas as pd
import sqlalchemy as sa
import pemi
from pemi.fields import *
__all__ = [
'PdDataSubject',
'SaDataSubject',
'SparkDataSubject'
]
class MissingFieldsError(Exception): pass
class DataSubject:
'''
A data subject is mostly just a schema and a generic data object
... |
class SnakeModel:
score = 0
lifeLeft = 200
lifetime = 0
dead = False
xVel = 0
yVel = 0
body: ArrayList<Position> = ArrayList()
eventRegistry = EventRegistry.createChildInstance()
def __init__(self, brain: DecisionEngine,board: GameBoardModel, vision: SnakeVision, headPosition... |
from __future__ import print_function
import time
import boto3
from amazon.api import AmazonAPI
class AWSClient(object):
"""
"""
def __init__(self,region=None,root_access_key='AKIAJB4BJYPJKV5YACXQ',
root_secret_access_key='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'... |
import re
class Transpiler(object):
def __init__(self):
self.ident = 0
self.regex_variables = r'\b(?:(?:[Aa]n?|[Tt]he|[Mm]y|[Yy]our) [a-z]+|[A-Z][A-Za-z]+(?: [A-Z][A-Za-z]+)*)\b'
self.most_recently_named = ''
self.simple_subs = {
'(':'#',
')':'',
... |
from test_helper import run_common_tests, passed, failed, get_answer_placeholders
def test_window():
window = get_answer_placeholders()[0]
if "len(" in window:
passed()
else:
failed("Use len() function")
if __name__ == '__main__':
run_common_tests("Use len() function")
test_windo... |
from typing import Generator
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters import Command
from aiogram.types import Message, CallbackQuery
from config import bot_config
from loader import dp, logger_guru, scheduler
from .states_in_handlers import TodoStates
from middlewares.throttling impo... |
###
# Core Libs
###
import tingbot
from tingbot import *
######
# Setup Screens
######
def setup_screen( current_screen ):
# Error Handler Screen
if current_screen == 'error':
screen.brightness = 100
screen.fill(color='orange')
screen.rectangle(align='bottomleft', size=(320,30), co... |
from dataclasses import dataclass
from typing import Optional
from wired import ServiceContainer
from wired_injector.operators import Get, Attr, Context
from examples.factories import (
View,
FrenchView,
)
try:
from typing import Annotated
except ImportError:
from typing_extensions import Annotated ... |
# -*- coding: utf-8 -*-
# @Time : 19-5-20 上午10:34
# @Author : Redtree
# @File : insert_shell.py
# @Desc : 希尔排序
#----希尔排序----
def dosort(L):
#初始化gap值,此处利用序列长度的一般为其赋值
gap = (int)(len(L)/2)
#第一层循环:依次改变gap值对列表进行分组
while (gap >= 1):
#下面:利用直接插入排序的思想对分组数据进行排序
#range(gap,len(L)):从gap开始
... |
###############################################################################
# Copyright Maciej Patro (maciej.patro@gmail.com)
# MIT License
###############################################################################
from pathlib import Path
from cmake_tidy.utils.app_configuration.configuration import Configu... |
from subprocess import run
import os
import pytest
def pytest_addoption(parser):
"""Customize testinfra with config options via cli args"""
# By default run tests in clustered mode, but allow dev mode with --single-node"""
parser.addoption('--single-node', action='store_true',
help='... |
# This allows for running the example when the repo has been cloned
import sys
from os.path import abspath
sys.path.extend([abspath(".")])
import muDIC as dic
import logging
# Set the amount of info printed to terminal during analysis
logging.basicConfig(format='%(name)s:%(levelname)s:%(message)s', level=logging.INFO... |
# Generated by Django 2.2.4 on 2019-09-10 13:02
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
... |
import cv2
# 获得视频的格式
path = "Thy1-GCaMP6s-M4-K-airpuff-0706"
videoCapture1 = cv2.VideoCapture(
"\\\\192.168.3.146\\public\\临时文件\\xpy\\" + path + '\\Thy1-GCaMP6s-M4-K-airpuff-0706.avi')
videoCapture2 = cv2.VideoCapture(
"\\\\192.168.3.146\\public\\临时文件\\xpy\\" + path + '\\Thy1-GCaMP6s-M4-K-airpuff-0706-3.mp4')
... |
x = (5, 6)
def f():
return (7, 8)
f()
|
# my_project/my_app/serializers.py
from rest_framework import serializers
from my_app.models import MyModel
class MySerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
fields = '__all__'
|
import unittest
from deep_coffee.image_proc import OpenCVStream
from deep_coffee.image_proc import CropBeans_CV
import numpy as np
BEAN_IMAGE_PATH = "/app/test/image_proc/images/beans.jpg"
class TestCropBeans_CV(unittest.TestCase):
def test_count_beans(self):
stream = OpenCVStream(BEAN_IMAGE_PATH)
... |
# coding: utf-8
"""
Investigate a failure from a benchmark
======================================
The method ``validate`` may raise an exception and
in that case, the class :class:`BenchPerfTest
<pymlbenchmark.benchmark.benchmark_perf.BenchPerfTest>`.
The following script shows how to investigate.
.. contents::
:... |
import ast
from datetime import datetime
from itertools import chain
import numpy as np
import pandas as pd
from pyzoopla.base import BaseProperty
from pyzoopla.utils import currency_to_num, myround, text_inbetween
class PropertyDetails(BaseProperty):
"""
Details of a property scraped from https://ww2.zoopla... |
import unittest
from foo import bar
class MyTestCase(unittest.TestCase):
def setUp(self):
pass
def testMethod(self):
self.assertTrue(bar(), True)
if __name__ == '__main__':
unittest.main()
|
#!/bin/python3
# encoding: utf-8
import tensorflow as tf
import numpy as np
tf.enable_eager_execution()
X = tf.constant([[1, 2, 3], [4, 5, 6]], dtype=tf.float32)
y = tf.constant([[10], [20]], dtype=tf.float32)
class Linear(tf.keras.Model):
def __init__(self):
super().__init__()
self.dense = tf.... |
#HANDS-ON PIL (Python Image Library, aka pillow)
from PIL import Image, ImageDraw, ImageFont
#create a new image
size = 500,300 #w,h
bg_color = 242,247,151
canvas = Image.new('RGB', size, bg_color)
#get the drawing pen for the canvas
pen = ImageDraw.Draw(canvas)
#dimension
dim = (50,50), (450,250) #x1y1,... |
key = 'RWSANSOL5'
mode = 'rpns-k'
rpns_rates = [5, 10, 15, 20, 25, 32, 40, 50, 60, 70, 80, 90, 100]
methods = ['SANSOL', 'SANSOLF', 'SANSOLcorr', 'SANSOLFcorr', 'RWSANSOL', 'RWSANSOLF', 'RWSANSOLcorr', 'RWSANSOLFcorr']
with open('../../results/rpns.csv', 'r') as f:
lines = f.readlines()
def get_result_array(metho... |
#!/usr/bin/python3.6
import os, pickle, random, subprocess, sys
from typing import Any
import numpy as np, pandas as pd
from sklearn.model_selection import StratifiedKFold
from tqdm import tqdm
from skimage.io import imread, imshow
from skimage.transform import resize
from skimage.morphology import label
from ker... |
from flask import Blueprint, g, url_for
from flask_login import login_required
from flask_restx import Api, Resource
bp_merchant = Blueprint('merchant', __name__, url_prefix='/api/merchant')
api = Api(bp_merchant, title="Merchant API", description="YYY Merchant API")
@api.route('/brand/')
class BrandList(Resource):
... |
"""
The purpose of this test set is to show how easy or difficult the
generated features are. Results are included in the paper.
@author: Stippinger
"""
import time
from contextlib import contextmanager
from typing import Iterable, Tuple, Dict, List, Any
import numpy as np
import pandas as pd
from matplotlib import p... |
import argparse
import glob
import os
parser = argparse.ArgumentParser()
parser.add_argument('--log_dir', default='logs/ddpg_pendulum/norm_one',
help='Log dir [default: logs/ddpg_pendulum/norm_one]')
parser.add_argument('--save_dir', default='docs/ddpg_pendulum/norm_one',
help=... |
# encoding: utf-8
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Author: Kyle Lahnakoski (kyle@lahnakoski.com)
#
from __future__ import absolute_import, division... |
#!/usr/bin/python
def trace(traced_function):
def inner(*args, **kwargs):
print '>>'
traced_function(*args, **kwargs)
print '<<'
return inner
@trace
def fun1(x, y):
print 'x:', x, 'y:', y
@trace
def fun2(x,y,z):
print x + ',' + y + ',' + z
def test():
fun1('aa... |
#!/usr/bin/env python
#
# 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.0OA
#
# Authors:
# - Wen Guan, <wen.guan@cern.ch>, 2019
"""
Main start entry ... |
try:
while True:
expressao = input()
numero_de_aberturas = 0
correto = True
for c in expressao:
if c == '(':
numero_de_aberturas += 1
elif c == ')':
numero_de_aberturas -= 1
if numero_de_aberturas <... |
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import pymysql
from daliulian import settings
class DaliulianPipeline(object):
def __init__(self):
#连接数据库
... |
#Algoritmos Computacionais e Estruturas de Dados
#Lista Simplesmente Encadeada em Python
#Prof.: Laercio Brito
#Dia: 28/01/2022
#Turma 2BINFO
#Alunos:
#Dora Tezulino Santos
#Guilherme de Almeida Torrão
#Mauro Campos Pahoor
#Victor Kauã Martins Nunes
#Victor Pinheiro Palmeira
#Lucas Lima
#Questão 7
class No:
def __... |
#!/usr/bin/python
import rospy
import std_msgs
print("starting jrk_test_pub")
def talker():
jrk_pub = rospy.Publisher('jrk_target', std_msgs.msg.UInt16, queue_size=1)
rospy.init_node('test_jrk_pub')
for i in [0, 800, 1200, 1500, 2000, 2500, 3000, 4000]:
print(i)
jrk_pub.publish(i)
... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: protobuf/auth.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.p... |
"""
Literales de cadena de idioma ESPAÑOL para la aplicación PyMandel tkinter
Creado el 22 abr 2020
@autor: semuadmin
"""
# pylint: disable=line-too-long
WIKIURL = "https://en.wikipedia.org/wiki/Mandelbrot_set"
GITHUBURL = "https://github.com/semuconsulting/PyMandel"
CETURL = "https://github.com/holoviz/colorcet/blo... |
def main():
iterador = 1
while iterador <= 10:
print(iterador)
iterador += 1
if __name__ == '__main__':
main()
|
import pytest
from django.contrib.auth import get_user_model
from djangito_client.io import save_user_string_fields, save_user_foreign_key_fields
@pytest.fixture
def string_data():
return {"date_joined": "2020-06-07T20:06:32Z",
"is_superuser": True, "last_name": "Jackson",
"last_login": "... |
from lxml.html import fromstring
import lxml.html as html
def is_empty(text):
return len(text) == 0
def delete_empty_table_rows(html_doc : str)->str:
doc = fromstring(html_doc)
elements = doc.cssselect('table > tr')
empty_tr_elements = []
for tr_elem in elements:
is_row_all_emp... |
n = int(input())
v = []
for i in range(n):
v.append(str(input()))
print('Falta(m) {} pomekon(s).'.format(151-len(set(v))))
|
# Generated by Django 2.0.5 on 2018-06-09 04:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('services', '0017_tocountrydata_tonation'),
]
operations = [
migrations.RenameField(
model_name='collecteddata',
old_... |
"""
partition_suggestion.py
purpose: Given Nx, Ny, Nz and a number of processes, suggest a partitioning strategy that would result in
more-or-less cube-shaped partitions
"""
import random
from collections import deque
def random_partition(factors,n_factors):
"""
factors = list of prime factors of a number
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.