content
stringlengths
5
1.05M
#!/usr/bin/env python import sys # read file line by line with open(sys.argv[1],"r") as file: for line in file: print(type(line))
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse from dump_env import dump def _create_parser(): parser = argparse.ArgumentParser() parser.add_argument('-t', '--template', default='', type=str, help='Adds template path') parser.add_argument('-p', '--prefix', default=...
import random from src.hw3.col import o from copy import deepcopy """ all : Seems like a Sample. bin : Seems like a Col. """ class FFT(): def __init__(self, all, conf, branch,branches,stop = None, level=0): self.my = conf stop = stop or 2*len(all.rows)**self.my.bins tmp ...
from django import template from django.conf import settings from django.core.cache import cache from django.db.models import Count from django.template import Variable from django.utils.safestring import mark_safe from mptt.utils import get_cached_trees from ..models import ( Post, Category ) register = template...
import pytesseract from PIL import Image from io import BytesIO def data_to_text(data: bytes, args: dict) -> str: img = Image.open(BytesIO(data)) configs = format_url_params(args) return pytesseract.image_to_string(img, config=configs['config'], lang=configs['lang'] ) def format_url_params(args) -> dict...
from django.apps import AppConfig class UsageStatsAppConfig(AppConfig): name = 'topobank.usage_stats' def ready(self): from .utils import register_metrics register_metrics()
from fastapi import FastAPI from .routers import operators, users, redirect app = FastAPI() app.include_router( operators.router, prefix="/api/operators", tags=["operators"], responses={404: {"description": "Not found"}}, ) app.include_router( users.router, prefix="/api/users", tags=["u...
import nose, random import .rp_with_graphs as rp import functools def make_votes_from_cand_stren(candidates, strengths, num_votes, noise=3): votes = [] nc = len(candidates) for _ in range(num_votes): vote = {} for candidate in candidates: vote[candidate] = max(min(strengths[candidate] + \ random.ra...
import docker client = docker.from_env() for container in client.containers.list(): print(container.id) for image in client.images.list(): print(image)
""" https://archive.ics.uci.edu/ml/datasets/Heart+Disease 1. #3 (age) 2. #4 (sex) 3. #9 (cp) 4. #10 (trestbps) 5. #12 (chol) 6. #16 (fbs) 7. #19 (restecg) 8. #32 (thalach) 9. #38 (exang) 10. #40 (oldpeak) 11. #41 (slope) 12. #44 (ca) 13. #51 (thal) 14. #58 (num) (the predicted attribute) ex: ['62', '0', '1', '140', '...
import pandas as pd import pytest from botocore.stub import ANY from envparse import env from faker import Faker from seller_stats.category_list_updates import CategoryListUpdates fake = Faker() Faker.seed(0) def make_categories(len_1, len_2, diff_count): lists = [[], []] # заполняем первый лист (старые ка...
# Copyright 2018 Iguazio # # 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...
from boa3.boa3 import Boa3 from boa3.exception import CompilerError, CompilerWarning from boa3.model.builtin.builtin import Builtin from boa3.neo.vm.opcode.Opcode import Opcode from boa3.neo.vm.type.Integer import Integer from boa3.neo.vm.type.String import String from boa3_test.tests.boa_test import BoaTest from boa3_...
import io import os import sys from configparser import ConfigParser import click from beets import config from beets.util import confit from summertunes.cli.run_mpv import run_mpv from summertunes.cli.run_serve import run_serve from summertunes.config_defaults import CONFIG_DEFAULTS import beetsplug.web config.re...
from __future__ import absolute_import, unicode_literals from celery import shared_task # from rest_framework import status # from rest_framework.response import Response import sys import os sys.path.append('..') from process_pdf import read __all__ = ['process_info'] @shared_task def log(data): print(data) ...
frase = input("Escreva uma frase: ") fraseNova = "" for chr in frase: if chr != " ": fraseNova += chr.upper() print(fraseNova) #https://pt.stackoverflow.com/q/340130/101
import tkinter as tk from tkinter import ttk from thonny import get_workbench, ui_utils import traceback from thonny.ui_utils import ems_to_pixels, CommonDialog class ConfigurationDialog(CommonDialog): last_shown_tab_index = 0 def __init__(self, master, page_records): super().__init__(master) ...
# links.py ''' The elements of genealogy are those things which get their own database table, for the most part, and are endowed with unique ID numbers. The element category names are listed in the constant `ELEMENTS`. The most key elements such as persons, places, events, notes, images and others ...
from .config import ADDRESS, PORT from .service import Service import click @click.command('mui-server') @click.option('--port', '-p', type=int, default=PORT, help=f'Set service port number. Defaults to {PORT}.') @click.option('--address', '-a', type=str, default=ADDRESS, ...
import pandas as pd import numpy as np import config import os import joblib from sklearn import metrics from sklearn import preprocessing from xgboost import XGBClassifier from lightgbm import LGBMClassifier from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier, GradientBoostingClassifier import ti...
# Copyright 2021 The LUCI Authors. All rights reserved. # Use of this source code is governed under the Apache License, Version 2.0 # that can be found in the LICENSE file. from recipe_engine import post_process PYTHON_VERSION_COMPATIBILITY = "PY2+3" DEPS = [ 'assertions', ] def RunSteps(api): api.assertions...
"""Artifact TQL Filter""" # standard library from enum import Enum # first-party from tcex.api.tc.v3.api_endpoints import ApiEndpoints from tcex.api.tc.v3.filter_abc import FilterABC from tcex.api.tc.v3.tql.tql import Tql from tcex.api.tc.v3.tql.tql_operator import TqlOperator from tcex.api.tc.v3.tql.tql_type import T...
symbols = [' ', 'O', 'X'] EMPTY = 0 J1 = 1 J2 = 2 NB_CELLS=9 class grid: cells = [] def __init__(self): self.cells = [] for i in range(NB_CELLS): self.cells.append(EMPTY) def play(self, player, cellNum): assert(0<= cellNum and cellNum < NB_CELLS) assert(self....
z = 0 i = 0 while i <10: print(i) z += i i += 1 if i == 5: print("Total I :", z) break
import os, shutil os.system("cd "+ os.path.join("..", "front") +" && yarn build") try: shutil.rmtree("dist") except: pass shutil.copytree(os.path.join("..", "front", "build"), "dist")
import FWCore.ParameterSet.Config as cms pfClustersFromCombinedCaloHF = cms.EDProducer("L1TPFCaloProducer", debug = cms.untracked.int32(0), ecalCandidates = cms.VInputTag(), ecalClusterer = cms.PSet( energyShareAlgo = cms.string('fractions'), energyWeightedPosition = cms.bool(True), ...
import random import string from typing import Any, Dict, Set def custom_name_generate(prohibited_names: Set[str], dict_names: Dict[str, Any]) -> str: for _ in range(1000): rand_name = "custom_" + "".join(random.choice(string.ascii_letters + string.digits) for _ in range(10)) # nosec if rand_name...
from aws_cdk import ( Stack, aws_iam as iam, ) from constructs import Construct class RoleArnStack(Stack): def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None: super().__init__(scope, construct_id, **kwargs) # CDK will automatically fill out the rest of the ARN with ...
from setuptools import * with open('requirements.txt', 'r') as F: requirements = F.readlines() setup(name='ignoramus', version='0.1', description='A command line tool for generating .gitignore files.', url='https://github.com/cornjuliox/ignoramus', author='Enrico Jr Tuvera', author_email='enricojr.tuvera@gmail....
import cv2 import numpy as np from imutils import contours # Load image, grayscale, blur, Otsu's threshold image = cv2.imread('1.png') original = image.copy() gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(gray, (3,3), 0) thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_...
# http://stackoverflow.com/a/12465861/5288758 from builtins import range import sys from PyQt4 import QtGui from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar import matplotlib.pyplot as plt import ...
# coding:utf8 import torch from torch import nn from collections import namedtuple import torch.nn.functional as F BeamCandidate = namedtuple('BeamCandidate', ['state', 'log_prob_sum', 'log_prob_seq', 'last_word_id', 'word_id_seq']) class Decoder(nn.Module): def __init__(self, idx2wor...
# Generated by Django 3.2.5 on 2021-11-26 12:15 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import taggit.managers class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER...
# Question 6 # Festival budget for 2000 is announced INR 10000/- and every year it will increase by 10%. write a recursive function to calculate total festival expense till 2020. def fes(year,budget): if year == 2020: return budget else: year +=1 return fes(year,budget + 10) print(...
# Copyright 2013-2021 The Salish Sea MEOPAR contributors # and The University of British Columbia # 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...
# coding: utf-8 from enum import Enum from six import string_types, iteritems from bitmovin_api_sdk.common.poscheck import poscheck_model import pprint import six class LiveEncoding(object): @poscheck_model def __init__(self, stream_key=None, encoder_ip=None, ...
# -*- encoding=utf-8 -*- # Copyright 2016 David Cary; licensed under the Apache License, Version 2.0 """RCV related classes and functions for exceptions and errors """ import sys import traceback class _RcvError(Exception): """A base class for Exceptions related to RCV This class is not intended for direct use...
from collections import deque class Solution: def reorderList(self, head: Optional[ListNode]) -> None: if not (head or head.next) : return None arr = [] def helper(node): while node : arr.append(node) node = node.next ...
import numpy as np from numpy.testing import assert_equal import hypothesis from hypothesis import given from hypothesis import strategies as st from hypothesis.extra import numpy as hynp @given(hynp.arrays(np.int64, 10), st.integers(), st.integers(), ) def test_clip_scalar_ints(arr, amin, amax): ...
# test_constants.py # Copyright 2012 Roger Marsh # Licence: See LICENCE (BSD licence) """constants tests""" import unittest from .. import constants class Constants(unittest.TestCase): def test_001_constants_001(self): self.assertEqual( sorted( k for k in dir...
from bspider.config.default_settings import EXCHANGE_NAME from bspider.core import BaseMonitor, Project from bspider.utils.sign import Sign from .async_downloader import AsyncDownloader class DownloaderMonitor(BaseMonitor): exchange = EXCHANGE_NAME[1] def get_work_obj(self, project: Project, sign: Sign): ...
Version = '$Header$'; from Components.Sources.Source import Source from Components.Sources.ServiceList import ServiceList from Components.config import config from Tools.Directories import resolveFilename, SCOPE_CONFIG, SCOPE_HDD from enigma import eServiceReference from re import sub from time import strftime, local...
import os from flask import Flask from flask_smorest import Api from .characters.rest import blp_characters from .comments.rest import blp_comments from .db import db from .episodes.rest import blueprint_episodes class Config: API_TITLE = "Rick and Morty API" API_VERSION = "v1" OPENAPI_VERSION = "3.0.2" ...
# -*- coding: utf-8 -*- """ flask.app ~~~~~~~~~ App for flask-snippets :copyright: (c) 2013 by fsp. :license: BSD. """ from flask import Flask app = Flask(__name__) app.debug = True app.secret_key = 'flask-snippets-fsp' if __name__ == "__main__": app.run()
import os import shutil import pytest import sys pytest_plugins = "pytester" @pytest.fixture def exes(testdir, request): """ Returns a fixture that can be used to obtain the executables found in the same directory as the test requesting it. The executables are copied first to testdir's tmpdir locatio...
from django.db import models from django.contrib.postgres import fields as postgres_fields class Diary(models.Model): id = models.PositiveIntegerField(primary_key=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) version = models.BigInteg...
import os import subprocess import sys from pathlib import Path from Download import FileDownload, YesNoQuestion from io import BytesIO from urllib.request import urlopen from zipfile import ZipFile # Get vulkan sdk from environment variables # if it exists we don't need to install vulkan VK_SDK = os.environ.get('VU...
# -*- coding: utf-8 -*- import logging if __name__ == '__main__': logging.basicConfig() _log = logging.getLogger(__name__) import unittest import A import B class Trac43_1 (unittest.TestCase): def testCode (self): x = A.a2('a2m-value', 'legal') self.assertEqual('a2m-value', x.a2member) ...
import queue from unittest import TestCase from aworker.task import Worker from aworker.queue.memory import MemoryQueue from aworker.serializers import PickleSerializer from aworker.exceptions import DuplicateTaskError def x2(x): return x * 2 async def async_x2(x): return x * 2 class WorkerTestCase(TestCa...
import sys import os import argparse import onnx import json import mxnet as mx from onnx import helper from onnx import TensorProto from onnx import numpy_helper import onnxruntime import cv2 print('mxnet version:', mx.__version__) print('onnx version:', onnx.__version__) assert mx.__version__ >= '1.8', 'mxnet versi...
hex='hhhh' token='aaaa-bbbb-ccccccccccc-ddddddd-eeee' base_url = 'http://cdn.mydomain.com' platform = 'small' # small|large|flash|adn lambda_region = 'us-east-1' sourcebucket = 'mybucket' sdb_region = 'us-east-1' sdb_domain = 'purge-edgecast' sdb_item='bucket-map'
# Generated by Django 3.0.7 on 2020-06-05 04:12 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('files', '0001_initial'), ] operations = [ migrations.AddField( model_name='file', name='fileobject', fie...
def score(word): up = word.upper() count = 0 for letter in up: if letter == 'A' or letter == 'E' or letter == 'I' or letter == 'O' or letter == 'U' or \ letter == 'L' or letter == 'N' or letter == 'R' or letter == 'S' or letter == 'T': count += 1 elif letter == 'D' or ...
from .db import db from werkzeug.security import generate_password_hash, check_password_hash from flask_login import UserMixin class User(db.Model, UserMixin): __tablename__ = 'users' id = db.Column(db.Integer, primary_key = True) first_name = db.Column(db.String(40), nullable = True) last_name = db.Column(db...
import torch import logging def calculate_accuracy_prototypes(y_pred, y_train, plabels): with torch.no_grad(): idx = torch.argmin(y_pred, axis=1) return torch.true_divide(torch.sum(y_train == plabels[idx]), len(y_pred)) * 100 def predict_label(y_pred,plabels): with torch.no_grad(): ret...
## find the key in rowwise and column wise sorted matrix..!!!! ## Initialize our asume mid element to topmost right corner.. def search_matrix(mat,key,n,m): i = 0 j = m-1 while(i>=0 and i<n and j>= 0 and j<m): if (arr[i][j] == key): return i,j elif(arr[i][j]>key): j-...
import pyqrcode # .PNG source = "www.github.com/diablo/" url = pyqrcode.create(source) url.png('qrcode.png', scale = 8) url.show() # .SVG # source = "www.github.com/CorvoDev/" # url = pyqrcode.create(source) # url.svg('qrcode.svg', scale = 8) # url.show()
import pytest, sys from pytest_in_60_minutes import mathFunc from pytest_in_60_minutes.mathFunc import StudentDB ################################################ # Test the "add" function ################################################ # skip only when python version is older than version 3.3 @pytest.mark.skipif(...
"""Lens serializers.""" # Rest framework from rest_framework import serializers # Models from apps.products.models import Lens from apps.products.models.features import Feature # Serializers from .features import FeatureModelSerializer class LensModelSerializer(serializers.ModelSerializer): """Lens model serial...
# %% [markdown] # # Pre-sail checklist - Ocean protocol component status # With simulated Kubernetes endpoints deployed, this script will make a simple # HTTP request to each, and report the status returned. # # %% # Standard imports import requests import os import logging from pathlib import Path from mantaray_utili...
from django.urls import path from musica import views app_name='musica' urlpatterns = [ path('<int:id>/<slug:slug_da_musica>',views.index,name='musicadetail') ]
import sys sys.path.append("..") sys.path.append("../main") from main import utils import unittest import random import numpy as np class Cepstrum_pitch_estim_test(unittest.TestCase): """ Unit test to test if the speaker is a man in the audio """ def test_01(self): pitch_men = uti...
#!/usr/bin/env # -*- coding: utf-8 -*- """ Copyright 2017-2018 Jagoba Pérez-Gómez 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 ...
import torch import numpy as np import torch.nn as nn from vae_network import * import torch.nn.functional as F from scipy.special import softmax class NAS(): def __init__(self, input_dim, c_dim, size, layer_upper_bound = 5, neuron_upper_bound = 1000, neuron_lower_bound = 50, latent...
import os import sys ENDPOINTS_PROJECT_DIR = os.path.join(os.path.dirname(__file__), 'endpoints-proto-datastore') sys.path.append(ENDPOINTS_PROJECT_DIR)
# encoding: UTF-8 from datetime import datetime from pymongo import Connection from pymongo.errors import * from eventEngine import * # 常量定义 OFFSET_OPEN = '0' # 开仓 OFFSET_CLOSE = '1' # 平仓 DIRECTION_BUY = '0' # 买入 DIRECTION_SELL = '1' # 卖出 PRICETYPE_LIMIT = '2' ...
# -*- coding:utf-8 -*- import argparse import random from random import randint import os import numpy as np import shutil def clc(dir): ls = os.listdir(dir) for i in ls: c_path = os.path.join(dir, i) os.remove(c_path) parser = argparse.ArgumentParser(description='Get the data info') parser.ad...
# %% import pandas as pd from tensorflow.keras.layers import DenseFeatures from tftabular.models import TabNetRegressor from tftabular.utils import df_to_dataset, get_feature # %% names = ['Sex', 'Length', 'Diameter', 'Height', 'While weight', 'Shucked weight', 'Viscera weight', 'Shell weight', 'Rings'] data = pd.read...
import unittest from request_parsers import keystroke class KeystrokeTest(unittest.TestCase): # Intentionally violating style conventions sot hat we can parallel the # self.assertEqual method. # pylint: disable=no-self-use # pylint: disable=invalid-name def assertKeystrokesEqual(self, expected, ...
#!/usr/bin/python3 # You can follow this installation instructions to get your RPi set up: # https://gist.github.com/ageitgey/1ac8dbe8572f3f533df6269dab35df65 import os import cv2 import time import threading import requests import json import settings import sys import time import argparse RECOGNITION_HOST = setti...
from .locations import LocationModelSerializer, ImageModelSerializer, RatingModelSerializer LocationModelSerializer, ImageModelSerializer, RatingModelSerializer
import re listofspecies = open("Bacteria_Species_extremo37.txt").readlines() do_print = False with open("Bac16s.faa") as f: for line in f: if do_print: print (do_print + line.strip()) do_print = False continue for x in listofspecies: names = x.split("...
# # PySNMP MIB module Nortel-Magellan-Passport-BgpMIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-Magellan-Passport-BgpMIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:17:03 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Pytho...
import pathlib import setuptools def read(*args: str) -> str: file_path = pathlib.Path(__file__).parent.joinpath(*args) return file_path.read_text("utf-8") setuptools.setup( name="labels", version="0.3.0.dev0", author="Raphael Pierzina", author_email="raphael@hackebrot.de", maintainer="R...
import re from django.contrib.auth import ( authenticate, login as auth_login, logout as auth_logout, ) from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from django.core.paginator import Paginator from django.db import transaction from django.http import...
from datetime import datetime from django import forms from django.forms import fields, widgets from .models import Cliente, Pedido, DESCR_COBERTURA, DESCR_RECHEIO, DESCR_MASSA, DESCR_TAMANHO, TipoMassa from django.utils.translation import ugettext_lazy as _ class PedidoForm(forms.ModelForm): # class Fault(models.Model...
import glob import logging import os import subprocess from plugins import BaseAssessment from yapsy.IPlugin import IPlugin import asmtypes class QuastAssessment(BaseAssessment, IPlugin): new_version = True def run(self): contigsets = self.data.contigsets for i,c, in enumerate(contigsets): ...
'''OpenGL extension EXT.vertex_attrib_64bit This module customises the behaviour of the OpenGL.raw.GL.EXT.vertex_attrib_64bit to provide a more Python-friendly API Overview (from the spec) This extension provides OpenGL shading language support for vertex shader inputs with 64-bit floating-point compon...
#!/usr/bin/python # @lint-avoid-python-3-compatibility-imports # # biolatency Summarize block device I/O latency as a histogram. # For Linux, uses BCC, eBPF. # # USAGE: biolatency [-h] [-T] [-Q] [-m] [-D] [interval] [count] # # Copyright (c) 2015 Brendan Gregg. # Licensed under the Apache License, Version 2.0 ...
#!/usr/bin/python import getopt import sys import pandas as pd import numpy as np import os import subprocess from osgeo import gdal import geopandas as gpd from shapely.geometry import Point import rasterio import multiprocessing as mp ''' Converts a large HDF or CSV file of pixel values to raster Arguments: in_csv...
#!/usr/bin/env python import sys from datetime import datetime sys.path.append("../") # noqa from aiohttp import web import jinja2 import aiohttp_jinja2 import aiohttp_session from aiohttp_tools import jsonify, redirect, get_client_ip, get_argument from aiohttp_tools import flash from aiohttp_tools.static_url impor...
from tests.common import EWSTest t = EWSTest() t.setUpClass() t.wipe_test_account()
# The MIT License (MIT) # Copyright (c) 2020. Ian Buttimer # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy,...
# -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incor...
#!/usr/bin/python # -*- coding:utf-8 -*- import numpy as np import tensorflow as tf from utils.common import * class Vocabulary(object): """ Token vocabulary. """ PAD = "<PAD>" BOS = "<BOS>" EOS = "<EOS>" UNK = "<UNK>" RESERV_TOKEN = [PAD, BOS, EOS, UNK] def __init__(self, vocab...
import traceback from datetime import datetime import json from flask import ( Blueprint, Response, current_app, request, render_template, abort ) from sqlalchemy import desc from ..models import ConversationHistory bp = Blueprint("conversation_history", __name__, template_folder="../templates") @bp.app_temp...
#Loss functions def gradient_penalty(samples, output, weights): gradients = K.gradients(output, samples)[0] gradients_sqr = K.square(gradients) gradient_penalty = K.sum(gradients_sqr, axis=np.arange(1, len(gradients_sqr.shape))) # (weight / 2) * ||grad||^2 # Penalize t...
import numpy as np def sigmoid(x): """ Calculate sigmoid """ return 1 / (1 + np.exp(-x)) x = np.array([0.5, 0.1, -0.2]) target = 0.6 learnrate = 0.5 weights_input_hidden = np.array([[0.5, -0.6], [0.1, -0.2], [0.1, 0.7]]) weights_hid...
# -*- coding: utf-8 -*- """ database decorators module. """ import pyrin.database.services as database_services def session_factory(*args, **kwargs): """ decorator to register a database session factory. :param object args: session factory class constructor arguments. :param object kwargs: session f...
import cv2 import numpy as np from keras import backend as K from losses import ActivationMaximization from optimizer import Optimizer from regularizers import TotalVariation, LPNorm from utils import utils def _get_num_filters(layer): """ Returns: Total number of filters within this layer """ # For ...
# @date 2021-05-16 # @author Frederic Scherma, All rights reserved without prejudices. # @license Copyright (c) 2021 Dream Overflow # History tools import json from tools.tool import Tool from config import utils from terminal.terminal import Terminal from watcher.service import WatcherService import logging logge...
import os import json import requests import jenkinsapi from jenkinsapi.jenkins import Jenkins from jenkinsapi.constants import STATUS_SUCCESS payload_str = os.environ['payload'] payload_str = payload_str.decode('utf-8','ignore') #parse to json obj payload = json.loads(payload_str) #pr = payload['pull_request'] url = ...
#!/usr/bin/env python3 import sys sum_ = 0 for line in sys.stdin: for output in line.split(" | ")[1].split(): sum_ += len(output) in (2, 3, 4, 7) print(sum_)
import cairo import math import random import sys import os sys.path.append(os.path.abspath('..')) from lib import palettes # Final image dimensions # Threadless wall art recommended: 12000 x 8400px JPG # Blanket recommended: 12500 x 9375px JPG IMG_HEIGHT = 2160 IMG_WIDTH = 3840 #IMG_HEIGHT = 6300 # 4200 #IMG_WIDTH ...
# Copyright (c) 2019 Alibaba 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...
from app import db from gr.dao.BaseDao import BaseDao from gr.model.usuario.Usuario import Usuario class UsuarioDao(BaseDao): def get_by_username(self, username): return self.model.query.filter(self.model.username == username).first() def get_by_empresa(self, empresaId): return self.model.quer...
# https://github.com/jrob93/grav_cloud/blob/master/python_stuff/py_func.py ''' Useful functions! Notes: - Units, generally units are SI (meters, seconds...) and angles are in radians, unless otherwise stated ''' import numpy as numpy #Imports Python mathematical functions library import math #import scipy #from scip...
import requests import hashlib import random import os import json import getpass import io import argparse import traceback import datetime import typing as T SERVER_URL = "54.85.95.128" SERVER_PORT = 5000 VERSION = "0.1" class MPResponse: def __init__(self, ok: bool, message: str, payload: T.Optional[T.Any]):...
from collections import Counter import algebra def majority_vote(labels): """assumes that labels are ordered from nearest to farthest""" vote_counts = Counter(labels) winner, winner_count = vote_counts.most_common(1)[0] num_winners = len([count for count in vote_counts.values() ...
from flaskr.blog import blog blog.blog_bp.add_url_rule('/', view_func=blog.home, methods=('GET',)) blog.blog_bp.add_url_rule('/contact/', view_func=blog.contact, methods=('GET', 'POST',)) blog.blog_bp.add_url_rule('/search/', view_func=blog.search_post, methods=('GET',)) blog.blog_bp.add_url_rule('/author/', view_func...