content
stringlengths
5
1.05M
lista = list() def l(): print(30*'-') l() print('s para sair em nome') while 1: nome = str(input('nome: ').lower()) if nome =='s': break nota1 = float(input('nota 1: ')) nota2 = float(input('nota 2: ')) media = (nota1 + nota2) / 2 lista.append([nome, [nota1, nota2], media]) l() print(f'{"No...
# -*- coding: utf-8 -*- """ .. module: byroapi.cli :synopsis: CLI interface .. moduleauthor:: "Josef Nevrly <[email protected]>" """ import sys import pkg_resources import asyncio import logging import click from onacol import ConfigManager, ConfigValidationError import yaml try: from yaml import CLoader ...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import _init_paths import os import torch import torch.utils.data from opts import opts from model.model import create_model, load_model, save_model from model.data_parallel import DataParallel from logger imp...
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # 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...
import re import secrets import string import unicodedata from flask import request import boto3 from .errors import ITSInvalidImageFileError from .settings import MIME_TYPES, NAMESPACES def get_redirect_location(namespace, query, filename): config = NAMESPACES[namespace] redirect_url = "{url}?{query_param}...
from mamba import description, before, context, it, after from doublex import Spy from doublex_expects import have_been_called_with from expects import expect, have_keys, be_a, have_len, be_above_or_equal from os import getpid from infcommon import logger from infrabbitmq import factory from infrabbitmq.rabbitmq impo...
import numpy as np import numpy.random as npr import collections from itertools import product from scipy.stats import multivariate_normal def split_train_test_multiple( datas, datas2, chunk=5000, train_frac=0.7, val_frac=0.15, seed=0, verbose=True ): """ Split elements of lists (data and datas2) in chunk...
""" Parse method tests for pyubx2.UBXMessage Created on 3 Oct 2020 *** NB: must be saved in UTF-8 format *** @author: semuadmin """ # pylint: disable=line-too-long, invalid-name, missing-docstring, no-member import unittest from pyubx2 import UBXMessage, UBXReader, VALCKSUM, VALNONE, SET class Pa...
from utils import get_embeddings import os import torch import pickle import argparse def create_database(in_path, out_path): images_list = os.listdir(in_path) embeddings_set = torch.rand(len(images_list), 1, 512) id_to_name = {} for i, image in enumerate(images_list): embeddings, name = get_e...
#This scripts demonstartes developing program with Tkinter library #Source: https://www.udemy.com/the-python-mega-course/learn/v4/t/lecture/4775342?start=0 from tkinter import * window = Tk() #Everything goes between this line and window.mainloop() b1=Button(window, text="Execute") #b1.pack() b1.grid(row=1,...
# -*- coding: utf-8 -*- """ Python Slack Bot docker parser class for use with the HB Bot """ import os import re DOCKER_SUPPORTED = ["image", "container", "help"] SUBCOMMAND_SUPPORTED = ["ls",] def docker_usage_message(): return ("I'm sorry. I don't understand your docker command." "I understand docker [%...
import pandas as pd import glob import csv import os import seaborn as sns import matplotlib.pyplot as plt from builtins import any class CrystalBall: def __init__(self, list_of_csvs:list, csvname_to_colnames_list:dict, csvname_to_IDs:dict, csvname_to_nonIDs:dict, all_IDs:list, all_nonIDs:list, csvname_to_one...
import unittest from flask import session from flask.globals import request from flask_login import current_user from app import create_app from app.models import User, db # data for register / login FULL_NAME = 'Gibran Abdillah' USERNAME = 'hadehbang' PASSWORD = 'cumansegini' EMAIL = '[email protected]' clas...
from .engine import TemplateEngine, Template from .nodes import UrlNode, TextNode, StaticNode from .ast import replace_on_tree class EngineExtension: def before_compile(self, engine: TemplateEngine, template: Template): pass class ViboraNodes(EngineExtension): def __init__(self, app): supe...
from phone.phone_interface import PhoneInterface from util import constants def read_input(input_file, phone: PhoneInterface) -> str: input_text = '' output_text = [] use_phone = { constants.PRESS_BUTTON_CALL: phone.press_button_call(), constants.PRESS_BUTTON_DISMISS: phone.press_button_...
#!/usr/bin/python # encoding: utf-8 """ @author: Ian @contact:[email protected] @file: flask_wrapper.py @time: 2019/3/8 18:20 """ from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'hello123' if __name__ == '__main__': app.run()
""" Credited to https://stackoverflow.com/a/41318195, https://apple.stackexchange.com/a/115373 """ import os import subprocess CMD = """ on run argv display notification (item 2 of argv) with title (item 1 of argv) end run """ async def notify(title, text='Restocked!! Go and check', sound='Funk'): subprocess....
#!/usr/bin/env python # _*_ coding: utf-8 _*_ import os import argparse def main(): parser = argparse.ArgumentParser() parser.add_argument("-d", "--directory", help="directory of relax running", type=str, default="matflow-running") args = parser.parse_args() # making traj: initial an...
from abc import ABC, abstractmethod class AbstractClassExample(ABC): @abstractmethod def do_something(self): print("wilson: from super {}".format(type(self).__name__)) print("Some implementation!") class AnotherSubclass(AbstractClassExample): def do_something(self): print("wils...
# $Id:# import FWCore.ParameterSet.Config as cms process = cms.Process('FILEFI') # import of standard configurations process.load('Configuration/StandardSequences/Services_cff') process.load('FWCore/MessageService/MessageLogger_cfi') process.load('Configuration.StandardSequences.GeometryDB_cff') process.load('Config...
from numpy import arange from scipy.interpolate import interp1d class MakeWaveformSeries(object): """docstring for MakeWaveformSeries""" def __init__(self, freqs, hptilde, hctilde, df=None): """ assuming uniformly spaced! """ self.f_min = freqs[0] self.f_max = freqs[-1] ...
import importlib import inspect import pkgutil from typing import Any, Iterator import returns def _classes_in_module(module: Any) -> Iterator[type]: yield from ( klass for _, klass in inspect.getmembers(module, inspect.isclass) if klass.__module__.startswith(module.__name__) # noqa: WPS...
# -*- coding: utf-8 -* # Author: Jianghan LI # File: li.py # Create Date: 2017-02-03 10:09-10:11 class Solution(object): def findPeakElement2(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) == 1: return 0 for i in range(len(nums) - 1): if nums[i] ...
import queue import threading import numba import numpy as np from ..utils import log_sum_exp @numba.jit(nogil=True) def _ctc_loss_np(logits, targets, blank_idx=0): """ http://www.cs.toronto.edu/~graves/icml_2006.pdf :param logits: numpy array, sequence_len * num_labels :param targets: numpy array,...
import argparse import os parser=argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--log_file', type=str, default='', help='path to log file') parser.add_argument('--n', type=int, default=4800, help='how many in one iteration') args=parser.parse_args() log_file=args...
def degrees_converter(celsius): """ Converts degrees to farenheit """ return celsius * 9/5 + 32
# --- # jupyter: # jupytext: # formats: ipynb,py:percent # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.13.0 # kernelspec: # display_name: CAMELS # language: python # name: camels # --- # %% import sys # %% s...
""" This is basically Xingyi's code adapted for LVIS. We only work with GT annotations. This script does not parse predictions. """ ################################################################################ ## Import. ## #################...
def encDec(messageDigest, hashDigest): n = 0 xorMess = "" for i in messageDigest: if n == 7: n = 0 rawBinMess = int(i, 2) ^ int(hashDigest[n], 2) if rawBinMess <= 31 or rawBinMess == 127: xorMess += " " + hex(rawBinMess) + " " else:...
#coding: utf-8 from youey.util.webcolors import * from youey.util.prop import * class Color(list): def __init__(self, *args, alpha=None): value = False if len(args) == 0: value = [0, 0, 0, 1] elif len(args) == 1: arg = args[0] if type(arg) is Color: value = arg.copy() e...
#the urls should really go here.....but i can't do that atm the moment because i don't know how :/ from flask.ext.classy import FlaskView, route from flask import request, current_app, redirect @route("/test") def testSomething(): return "hello world"
from appJar import gui import sqlite3 ''' CREATE TABLE USUARIO(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, EMAIL TEXT NOT NULL, TYPE TEXT NOT NULL, DEPARTMENT TEXT NOT NULL, PROGRAM TEXT NOT NULL, CAMPUS TEXT NOT NULL, PERIODICITY TEXT NOT NULL); CREATE TABLE RSS(ID INT PRIMARY KEY NOT NULL, NAME TEXT NO...
from is_core.auth.permissions import BasePermission class RelatedCoreAllowed(BasePermission): """ Grant permission if core permission with the name grants access """ name = None def __init__(self, name=None): super().__init__() if name: self.name = name def has_p...
from .alpha_spheres import get_alpha_spheres_set from . import clustering as clustering
import pytest from feeds.external_api.groups import ( get_user_groups, get_group_names, validate_group_id ) from feeds.exceptions import GroupsError def test_validate_group_id_valid(mock_valid_group): g = "a_group" mock_valid_group(g) assert validate_group_id(g) def test_validate_group_id_inva...
from setuptools import setup setup(name='local_factorySim', version='0.2dev0', packages=['factorySim',], install_requires=['gym', 'pycairo', 'pandas', 'fabulous', 'Polygon3',] )
from django.contrib import admin from django.contrib.admin import ModelAdmin from main.models import Contest, Problem, Submission class ContestAdmin(ModelAdmin): list_display = ("ccode", "title", "can_view", "can_submit") class ProblemAdmin(ModelAdmin): list_display = ("pcode", "title", "contest") class Submission...
print(f'\033[33m{"—"*30:^30}\033[m') print(f'\033[36m{"EXERCÍCIO Nº 2":^30}\033[m') print(f'\033[33m{"—"*30:^30}\033[m') print("Confirme sua data de nascimento") dia = input("Dia: ") mes = input("Mês: ") ano = input("Ano: ") print(f"Você nasceu no dia {dia} de {mes} de {ano}. Correto?")
import random import sys import uuid import datetime from confluent_kafka import Producer from faker import Faker fake = Faker('en_US') if __name__ == '__main__': if len(sys.argv) != 4: sys.stderr.write('Usage: %s <bootstrap-brokers> <topic> <num msgs>\n' % sys.argv[0]) sys.exit(1) broke...
""" Given an array arr of 4 digits, find the latest 24-hour time that can be made using each digit exactly once. 24-hour times are formatted as "HH:MM", where HH is between 00 and 23, and MM is between 00 and 59. The earliest 24-hour time is 00:00, and the latest is 23:59. Return the latest 24-hour time in "HH:MM" for...
from django.core.management import BaseCommand from django.utils.timezone import now from django_freeradius.models import RadiusBatch class Command(BaseCommand): help = "Deactivating users added in batches which have expired" def handle(self, *args, **options): radbatches = RadiusBatch.objects.filte...
# Author # Pedro Silva import configparser import argparse import nexmo import pandas class Notify(object): """ Notify contacts Allows for pushing sms information to a set of contatct people. It is capable of populating the list of clients by parsing the contents of an excel file ...
# process media objects returned by Twitter's APIs
#! python2 #coding:utf8 from abc import ABCMeta, abstractmethod import time import sys import os from Rule.Rules import * from File.Files import * from PktsParser import * class IReplay: __metaclass__ = ABCMeta @abstractmethod def initFilter(cls): pass @abstractmethod def startReplay(cls): pass @abst...
import pathlib import time import watchdog.events import watchdog.observers from GlobusTransfer import GlobusTransfer from .log import logger class Handler(watchdog.events.PatternMatchingEventHandler): def __init__(self, args): # Set the patterns for PatternMatchingEventHandler watchdog.events....
# from tracemalloc import start from flair.data import Sentence from flair.models import SequenceTagger from flair.models.sequence_tagger_model import MultiTagger from flair.data import Token from tqdm import tqdm import base as be import mspacy as msp class Flair: """Base class for Flair, reads in the basic para...
# MIT License # # Copyright (C) IBM Corporation 2019 # # 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, modify, merge...
import re from typing import Any, Mapping, Sequence import pytest from snuba_sdk.aliased_expression import AliasedExpression from snuba_sdk.column import Column from snuba_sdk.conditions import Condition, InvalidConditionError, Op from snuba_sdk.entity import Entity from snuba_sdk.expressions import InvalidExpression...
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available. Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. BK-BASE 蓝鲸基础平台 is licensed under the MIT License. License for BK-BASE 蓝鲸基础平台: ---------------------------------------------...
"""empty message Revision ID: 1c3f88dbccc3 Revises: 2e7b377cbc7b Create Date: 2020-07-30 18:51:01.816284 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = '1c3f88dbccc3' down_revision = 'ab06a94e5d4c' branch_labels = None...
import datetime from dataclasses import dataclass from typing import Optional from aspen.database.models import PublicRepositoryType @dataclass class AccessionWorkflowDirective: """This is a way to encapsulate the accession workflows hanging off of an entity.""" repository_type: PublicRepositoryType st...
# Given string S and a dictionary of words words, find the number of words[i] that is a subsequence of S. # # Example : # Input: # S = "abcde" # words = ["a", "bb", "acd", "ace"] # Output: 3 # Explanation: There are three words in words that are a subsequence of S: "a", "acd", "ace". # Note: # # All words in words and ...
import requests from bs4 import BeautifulSoup website_url = "https://www.azlyrics.com" artist = "Bon Iver" artist = ''.join(artist.lower().split(' ')) artist_url = "%s/%s/%s.html" % (website_url, artist[0], artist) artist_html = requests.get(artist_url) artist_soup = BeautifulSoup(artist_html.content, "html.parser") ...
from django.shortcuts import render, redirect from apps.inicio.models import DatosPersonales, OrdenRiego, Noticia, Parcela, AuthUser, Reparto, AuthUser, Caudal, Destajo from apps.inicio.models import * from apps.inicio.forms import PersonaForm from apps.usuario.forms import OrdenRForm, AuthUserForm from django.http imp...
from PyObjCTools.TestSupport import * from PyObjCTest.protected import * class TestProtected (TestCase): def testProtectedNotInDir(self): d = dir(PyObjCTest_Protected) self.assertIn('publicMethod', d) self.assertNotIn('_protectedMethod', d) def testProtectedCallable(self): o =...
# -*- coding: utf-8 -*- import netCDF4 import mds.constants # import mds.date_time import mds.ordered_set import mds.math import mds.netcdf.convention class Dataset(object): """ Constructs an instance based on a *name* and an optional default *favor_convention_class* filter_out_nd_coordinates ...
from cloudburst.client.client import CloudburstConnection import time def dag_start(cloudburst, key, size): return 1 def dag_sleep(cloudburst, up_res): import time import uuid time.sleep(1) uid = str(uuid.uuid4()) return str({uid:1}) def dag_end(cloudburst, *values): return len(values) cl...
""" Autor: Daniel de Souza Baulé (16200639) Disciplina: INE5452 - Topicos Especiais em Algoritmos II Atividade: Segundo simulado - Questoes extra-URI Escalonador de Processos """ from src.EscalonadorDeProcessos.MaxHeap import MaxHeap from src.EscalonadorDeProcessos.Processo import Processo from pprint import pp #...
from .conversion import convert as geojson
"""macros/delete.py - Deleting character macros.""" from .. import common from ..vchar import errors __HELP_URL = "https://www.inconnu-bot.com/#/macros?id=deletion" async def delete(ctx, macro_name: str, character=None): """Delete the given macro.""" try: tip = f"`/macro delete` `macro:{macro_name}`...
# Basics """ Summary: Dictionary are a list of Key and Value {Key: Value} You can create a key connected to its own definition e.g. {"Bug": "An error in a program that prevents the program from running as expected"} You can also create more keys, separating each key /w a comma. { "Bug": "An error i...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def pathSum(self, root, sum): """ :type root: TreeNode :type sum: int :rtype: List[List[i...
# -*- coding: utf-8 -*- """Parsers for tables.""" import copy import textwrap from typing import List, Optional, Union import tabulate from ..constants.tables import KEY_MAP_ADAPTER, KEY_MAP_CNX, KEY_MAP_SCHEMA, TABLE_FMT from ..tools import json_dump, listify def tablize( value: List[dict], err: Optional[s...
''' Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. A subarray is a contiguous part of an array. Example 1: Input: nums = [-2,1,-3,4,-1,2,1,-5,4] Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6. Example 2: Input: nu...
# check python version, this script requires python3 import sys if sys.version_info[0] < 3: print('ERROR: This script requires Python 3') sys.exit(1) import os import subprocess from argparse import ArgumentParser # ################################ # # Main Program # # #############...
# The MIT License (MIT) # # Copyright (c) 2017-2018 Niklas Rosenstein # # 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, ...
''' based on the code in the thread https://forum.omz-software.com/topic/1686/3d-in-pythonista by omz ''' from objc_util import * import sceneKit as scn import ui import math @on_main_thread def demo(): main_view = ui.View() w, h = ui.get_screen_size() main_view.frame = (0,0,w,h) main_view.name = 'particles de...
# Generated by Django 2.0 on 2019-09-07 12:06 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Teams', fields=[ ('teamname', models.CharFiel...
from cms.models import Page, Title from django.contrib import admin from django.contrib.admin.options import csrf_protect_m from django.core.exceptions import PermissionDenied from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect class ExtensionAdmin(admin.ModelAdmin): change_f...
# See LICENSE for licensing information. # # Copyright (c) 2016-2021 Regents of the University of California and The Board # of Regents for the Oklahoma Agricultural and Mechanical College # (acting for and on behalf of Oklahoma State University) # All rights reserved. # """ This is a DRC/LVS/PEX interface file for kla...
# Copyright 2018 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
# NOTE: This code is expected to run in a virtual Python environment. from abc import ABC, abstractmethod import os import unittest import logging import vtk, qt, ctk, slicer from slicer.ScriptedLoadableModule import * from slicer.util import VTKObservationMixin import pydicom import numpy as np import csv import sys ...
from typing import ( Dict, Union, Tuple, Callable, List, Optional, Any, Generator ) import tensorflow as tf import numpy as np import pandas as pd from ml_hadoop_experiment.tensorflow.numpy_to_sparse_tensors import \ create_sparse_np_stacked add_to_list_type = Callable[ [pd.D...
import unittest from datanator_query_python.query import query_kegg_organism_code from datanator_query_python.config import config class TestKOC(unittest.TestCase): @classmethod def setUpClass(cls): db = 'datanator' conf = config.TestConfig() username = conf.USERNAME password ...
from flask import Flask, render_template, request, make_response import os import random import boto3 import configparser config = configparser.ConfigParser() config.read('config.ini') IAMAccessKey = config['DEFAULT']["IAMAccessKey"] IAMSecretKey = config['DEFAULT']["IAMSecretKey"] s3_region = config['DEFAULT']["s3_r...
# coding: utf-8 # Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. import unittest from oci_cli.util import pymd5 class TestPyMd5(unittest.TestCase): def test_hexdigest(self): hash = pymd5.md5(b"Hello World").hexdigest() self.assertEquals(hash, 'b10a8db164e0754105b7a9...
# # Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; version 2 of the License. # # This program is distributed in the hope...
fname = input('Enter file: ') try: fhandle = open(fname, 'r') except: print('No such file.') quit() days = dict() for line in fhandle: if not line.startswith('From'): continue words = line.split() if len(words) < 3: continue day = words[2] days[day] = days.get(day, 0) + 1 print(days)
c = get_config() # Allow all IP addresses to use the service and run it on port 80. c.NotebookApp.ip = '0.0.0.0' c.NotebookApp.port = 80 # Don't load the browser on startup. c.NotebookApp.open_browser = False
#!/usr/bin/python import rospy import numpy as np from sam_msgs.msg import ThrusterRPMs from geometry_msgs.msg import TwistStamped from uavcan_ros_bridge.msg import ESCStatus from sbg_driver.msg import SbgEkfEuler from nav_msgs.msg import Odometry import message_filters from sensor_msgs.msg import Imu import tf class...
import download, linkload, getproxy from bs4 import BeautifulSoup import time import csv import re import os def get_books_as_sort(): url = 'https://www.23wxw.cc' seed_url = 'https://www.23wxw.cc/xiaoshuodaquan/' page = download.localPage(seed_url) if page is None: print 'Local file is None, just download.' p...
# Generated by Django 3.2 on 2022-04-05 11:22 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("post", "0003_category"), ] operations = [ migrations.AlterModelOptions( name="category", options={"verbose_name_plural": "cate...
from django.shortcuts import render from django.http import HttpResponse import random, sys # Create your views here. def index(request): return maze(request) def maze(request, width=12, height=12, seed = None): seed, maze = generate_maze(width, height, seed=seed) return render(request, 'labyapp/index.html', conte...
from cloudmesh_job.cm_jobdb import JobDB class CommandJob(object): @classmethod def start(cls): db = JobDB() db.start() Console.ok("job server start") @classmethod def stop(cls): db = JobDB() db.stop() Console.ok("job server stop")
''' Provides the common utility operations for plotting images ''' import os import shutil import uuid import matplotlib.pyplot as plt import numpy as np import tensorflow as tf import imageio def cleanup(path): if not os.path.isdir(path): raise TypeError('Path provided to cleanup can only be a directory...
import operator points = {'A1':(2,10), 'A2':(2, 5), 'A3':(8, 4), 'A4':(5, 8), 'A5':(7, 5), 'A6':(6, 4), 'A7':(1, 2), 'A8':(4, 9)} centroid_1 = points['A1'] centroid_2 = points['A4'] centroid_3 = points['A7'] def distance(p1, p2): return abs(p...
from unittest.mock import patch from django.contrib.auth import get_user_model from rest_framework.reverse import reverse from rest_framework.test import APIClient from core.models import (Asset, AssetModelNumber, AllocationHistory, AssetMake, ...
import fcntl import logging import queue import os import ipcqueue.posixmq from django.conf import settings from . import Monitoring logger = logging.getLogger(__name__) class PrometheusMultiprocessMonitoring(Monitoring): def __init__(self): super().__init__() monitoring_setting = getattr(sett...
from direct.interval.IntervalGlobal import Sequence, Func, Wait, LerpColorScaleInterval, Parallel from direct.distributed import DistributedObject from direct.directnotify import DirectNotifyGlobal from direct.task.Task import Task from direct.showbase import PythonUtil from toontown.distributed import DelayDelete from...
#Conditional Statements #Boolean logic # > # < # >= # <= # == # != #AND ''' True and True = True True and False = False False and True = False False and False = False ''' #OR ''' True or True = True True or False = True False or True = True False or False = False ''' #NOT ''' not True = False not False = True ''' #if...
import re import sys import os from datetime import * ADJ_FF_TIME = -5 malicious_labels = [] preprocessing_lines = [] process_parent = {} def order_events(): global preprocessing_lines preprocessing_lines.sort() for i in range(0, len(preprocessing_lines)): node = preprocessing_lines[i] if "a" in node[:node.fi...
# This program calculates gross pay. def main(): try: # Get the number of hours worked. hours = int(input('How many hours did you work? ')) # Get the hourly pay rate. pay_rate = float(input('Enter your hourly pay rate: ')) # Calculate the gross pay. gross_pay = hou...
# ***** BEGIN LICENSE BLOCK ***** # Version: MPL 1.1/GPL 2.0/LGPL 2.1 # # The contents of this file are subject to the Mozilla Public License Version # 1.1 (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.mozilla.org/MPL/ # # Softwa...
import logging from serial import Serial from influxdb import InfluxDBClient from influxdb.client import InfluxDBClientError import paho.mqtt.client as mqtt import time from settings import * ser = Serial(SERIAL_PORT, 460800, timeout=5, xonxoff=True) influx_client = InfluxDBClient(INFLUX_HOST, 8086, INFLUX_USER, ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ QiCore Python Module """ from __future__ import absolute_import from __future__ import unicode_literals from __future__ import print_function import os import sys def register(): """ Register QiCore Python Module """ # Get the Absolute Path if the Package ...
#Global parameters module N = 1024 K = 16 Q = 12289 POLY_BYTES = 1792 NEWHOPE_SEEDBYTES = 32 NEWHOPE_RECBYTES = 256 NEWHOPE_SENDABYTES = POLY_BYTES + NEWHOPE_SEEDBYTES NEWHOPE_SENDBBYTES = POLY_BYTES + NEWHOPE_RECBYTES
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'table_example.ui' # # Created: Tue Aug 08 17:25:48 2017 # by: PyQt4 UI code generator 4.10 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except At...
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from collections import Counter import time class TimingCtx: def __init__(self, init=None, init_ns=None, first_tic=None): self.t...
import pytest from steputils.express import pyparser, ast primary = pyparser.primary.copy().addParseAction(ast.Primary.action) bound_spec = pyparser.bound_spec.copy().addParseAction(ast.BoundSpec.action) def test_bound_spec(): r = bound_spec.parseString('[3:3]')[0] assert len(r) == 2 bound_1 = r[0] b...
import sys sys.path.append('.') # stdlib import os import shutil from glob import glob from tqdm.auto import tqdm import re import time import argparse # numlib import pandas as pd from global_config import Config from utils.file import Logger from utils.metrics import map_2cls from utils.common import increment_pat...