content
stringlengths
0
894k
type
stringclasses
2 values
#!/usr/bin/env python # # Author: Qiming Sun <osirpt.sun@gmail.com> # ''' Natural atomic orbitals Ref: F. Weinhold et al., J. Chem. Phys. 83(1985), 735-746 ''' import sys from functools import reduce import numpy import scipy.linalg from pyscf import lib from pyscf.gto import mole from pyscf.lo import orth from p...
python
import requests import sys import os import re import csv from urlparse import urljoin from bs4 import BeautifulSoup import urllib from pprint import pprint class Movies(object): def __init__(self, args): self.movies = [] if len(args) == 0: print 'No Argument given' #T...
python
class CondorJob: def __init__(self, job_id): self.job_id = job_id self.state = None self.execute_machine = None self.running_time = 0 def reset_state(self): self.state = None
python
# -*- coding: utf-8 -*- import requests import re from threading import Thread import queue from threading import Semaphore from lxml import etree import json import ssl prefix = "http://www.cazy.org/" fivefamilies = ["Glycoside-Hydrolases.html","GlycosylTransferases.html","Polysaccharide-Lyases.html","Carbohydrate-Es...
python
# execute # pytest -s test_class.py def setup_module(): print("setting up MODULE 1") def teardown_module(): print("tearing down MODULE 1") class TestClass1(): def setup_method(self): print(" setting up TestClass1 INSTANCE") def teardown_method(self): print(" tearing down ...
python
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html from scrapy import signals import json import codecs from twisted.enterprise import adbapi from datetime import datetime from ...
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.0 # # Unless required by applicable law or agreed to in writing, software # distrib...
python
"""Middleware used by Reversion.""" from __future__ import unicode_literals from django.core.exceptions import ImproperlyConfigured from reversion.revisions import revision_context_manager REVISION_MIDDLEWARE_FLAG = "reversion.revision_middleware_active" class RevisionMiddleware(object): """Wraps the en...
python
from dataclasses import dataclass from enum import Enum from typing import Dict, List, Union from loguru import logger from dome9 import BaseDataclassRequest, APIUtils, Dome9Resource, Client from dome9.consts import NewGroupBehaviors from dome9.exceptions import UnsupportedCloudAccountCredentialsBasedType, Unsupporte...
python
from requests import get import json from datetime import datetime from dotenv import load_dotenv import os def get_public_ip(): ip = get('https://api.ipify.org').text # print('My public IP address is: {}'.format(ip)) key = os.environ.get("api_key") api_url = 'https://geo.ipify.org/api/v1?' url ...
python
# -*- coding: utf-8 -*- from odoo import api, fields, models, _ from odoo.exceptions import UserError from odoo.addons.wecom_api.api.wecom_abstract_api import ApiException import logging _logger = logging.getLogger(__name__) RESPONSE = {} class EmployeeBindWecom(models.TransientModel): _name = "wecom.wizard.em...
python
import copy import struct class SBox: def __init__(self): # define S-box self.S = [ 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0...
python
from OpenGL.GL import glVertex3fv, glVertex2fv class Vertex: def __init__(self, x, y, z): self._x = x self._y = y self._z = z def draw(self): if self._z is None: glVertex2fv((self._x,self._y)) else: glVertex3fv((self._x,self._y,self._z))
python
#!/usr/bin/env python import os import re from setuptools import setup, find_packages setup( name="shipwreck", version="0.0.1", description="An experiment with using blob storage as my recordings storage!", long_description=open("README.md", "r").read(), long_description_content_type="text/markdo...
python
from datetime import date, datetime from django.core.management.base import BaseCommand, CommandError from django.db import transaction from tradeaccounts.models import Positions, TradeAccount, StockPositionSnapshot from tradeaccounts.utils import calibrate_realtime_position from users.models import User class Comm...
python
# Created by MechAviv # ID :: [130030103] # Empress Road : Drill Hall
python
from src.music_utils.PlaylistHandler import create_music_playlist from src.network.OperationType import OperationType from src.network.NetworkCommunication import * all_music = create_music_playlist("All Songs") socket = None log = None def init(sock, logger): global socket socket = sock global log l...
python
# Copyright 2021 AI Redefined Inc. <dev+cogment@ai-r.com> # # 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 l...
python
# -*- coding: utf-8 -*- # Generated by Django 1.11.20 on 2021-03-22 21:25 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('activityinfo', '0173_auto_20210312_1957'), ] operations = [ migrations.Add...
python
bl_info = { "name": "keMouseAxisMove", "author": "Kjell Emanuelsson", "category": "Modeling", "version": (1, 1, 4), "blender": (2, 80, 0), } import bpy from mathutils import Vector, Matrix from bpy_extras.view3d_utils import region_2d_to_location_3d from .ke_utils import getset_transform, restore_t...
python
# setup.py import os, sys, re # get version info from module without importing it version_re = re.compile("""__version__[\s]*=[\s]*['|"](.*)['|"]""") with open('hello_world.py') as f: content = f.read() match = version_re.search(content) version = match.group(1) readme = os.path.join(os.path.dirname(__f...
python
# python module to make interfacing with the cube simpler import requests import json class Animation(object): def __init__(self): self.animation_type = "None" def to_json(self): return f'{{"animation":{self.animation_type}}}' class Blink(Animation): def __init__(self, count=1, wait=1...
python
"""Check the configuration for cspell. See `cSpell <https://github.com/streetsidesoftware/cspell/tree/master/packages/cspell>`_. """ import itertools import json import os import textwrap from configparser import ConfigParser from pathlib import Path from typing import Any, Iterable, List, Sequence, Union import yam...
python
# Date: 01/27/2021 # Author: Borneo Cyber
python
# Copyright (c) 2020 PaddlePaddle Authors. 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 app...
python
username = "YourInstagramUsername" password = "YourInstagramPassword"
python
# Copyright 2015, Pinterest, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writ...
python
from datetime import date import click @click.group() def cli(): "Utility for http://b3.com.br datasets" @cli.command() @click.option("--date", type=click.DateTime(formats=["%Y-%m-%d"])) @click.option("--chunk-size", type=int, default=10000) def download(date, chunk_size): """Downloads quotes data""" if...
python
import torch from torchvision.datasets.folder import default_loader from torch.utils import data from tqdm import tqdm import sys import numpy as np import struct class DatasetBin(data.Dataset): def __init__(self, meta_filename, bin_filename, meta_columns, transform=None, targets_transform=None, loader=default_lo...
python
import streamlit as st from pdf2docx import Converter pdf_file = 'pdf文件路径' docx_file = '输出word文件的路径' cv = Converter(pdf_file) cv.convert(docx_file, start=0, end=None) cv.close() st.file_uploader(label, type=None, accept_multiple_files=False, key=None, help=None, on_change=None, args=None, kwargs=None) st.downl...
python
import logging import textwrap from pathlib import Path from typing import Optional import click from tabulate import tabulate from bohr import api from bohr.datamodel.bohrrepo import load_bohr_repo from bohr.util.logging import verbosity logger = logging.getLogger(__name__) @click.group() def dataset(): pass ...
python
import requests import json from datetime import datetime, timedelta import logging bLoadWeatherModelFromFile = False class WeatherQueryProxy(): def __init__(self, apikey, refreshtimeoutinminutes): self.queryCache = {} self.api_key = apikey self.queryInvalidationTimeout = timede...
python
#Exercício Python 096: Faça um programa que tenha uma função chamada área(), que receba as dimensões de um terreno retangular (largura e comprimento) e mostre a área do terreno. #Funções utilizadas no programa principal def mostraLinha(): print("-" * 30) def calculoArea (x, y): area = x * y print(f"O terr...
python
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import...
python
import re try: import json except ImportError: import simplejson as json from rbtools.api.errors import APIError from rbtools.commands import (Command, CommandError, CommandExit, Option, Par...
python
''' Alena will manage directories ''' import os from pathlib import Path def cleaning_service(pathsToClean, images = False, videos = False): if images: if pathsToClean.get('original'): if Path(os.environ.get('IMAGE_ORIGINAL_LOCAL_PATH') + pathsToClean['original']).i...
python
from .custom_unet import custom_unet from .custom_vnet import custom_vnet from .vanilla_unet import vanilla_unet from .satellite_unet import satellite_unet
python
# Generated by Django 3.1.3 on 2020-12-19 15:03 from django.db import migrations, models import django.db.models.expressions class Migration(migrations.Migration): dependencies = [ ('events', '0006_auto_20201215_1622'), ] operations = [ migrations.RemoveConstraint( model_nam...
python
# Create a function named remove_middle which has three parameters named lst, start, and end. # The function should return a list where all elements in lst with an index between start and end(inclusive) have been removed. # For example, the following code should return [4, 23, 42] because elements at indices 1, 2, and ...
python
import pytest from erp import schema from erp import forms from erp.models import Accessibilite from erp.schema import get_help_text_ui, get_help_text_ui_neg @pytest.fixture def form_test(): def _factory(name, value): instance = Accessibilite(**{name: value}) form = forms.ViewAccessibiliteForm(i...
python
import logging import sys import os from tasker.master.Master import Master from dotenv import load_dotenv load_dotenv() logging.basicConfig(level=logging.INFO, handlers=[logging.StreamHandler(sys.stdout)]) def supply(): n = 1 while n <= 5: task = { "id": "test-{}".format(n), ...
python
import datetime as dt from os.path import splitext def add_ts_to_filename(filepath): filename, extension = splitext(filepath) ts = dt.datetime.today().strftime('%Y%m%dT%H%M%S') filename_with_ts = f"{filename}_{ts}{extension}" return filename_with_ts if __name__ == '__main__': print(add_ts_to_file...
python
import json class Solution: def removeElement(self, nums, val): """ :type nums: List[int] :rtype: int """ if not nums: return 0 j = len(nums) - 1 i = 0 while i < j: if nums[i] == val and nums[j] != val: nums[i...
python
from enum import IntFlag from .ProcStates import * class Process: def __init__(self, n_cores=4096, time_needed=1000, process_id = 0,state = PROC_STATE.WAITING, scheduled_start_time=0, name="CIFAR" ): self.n_cores = n_cores self.needed_time = time_needed self.process_id = ...
python
pas = float(input('Quantos Km você irá percorrer')) pas1 = pas * 0.45 pas2 = pas * 0.5 if pas > 200: print('Sua passagem saí por R${:.2f}' .format(pas1)) else: print('Sua passagem saí por R${:.2f}'.format(pas2))
python
import json from http.client import HTTPResponse from urllib.parse import urlencode from urllib.request import urlopen class MeasurementUnit: def __init__(self, name: str, temperature: str, wind_speed: str): self.name = name self.temperature = temperature self.wind_speed = wind_speed cla...
python
from os.path import abspath, dirname, join from setuptools import find_packages, setup # Fetches the content from README.md # This will be used for the "long_description" field. with open(join(dirname(abspath(__file__)), "README.md"), encoding='utf-8') as f: README_MD = f.read() setup( # The name of your proje...
python
import random import numpy as np from time import sleep def AgentModel(Observation,actions,reward): sleep(0.05) #action = random.choice(actions) Observation_size = Observation.size() action_size = len(actions) qtable = np.zeros((Observation_size, action_size)) return action
python
#---------------------------------------------------------------------- # Libraries from PyQt6.QtWidgets import QGridLayout, QDialog, QDialogButtonBox, QLabel, QSizePolicy from PyQt6.QtGui import QPixmap from PyQt6.QtCore import Qt from .QBaseApplication import QBaseApplication from .QGridWidget import QG...
python
""" plugin example for autofile template system """ from typing import Iterable, List, Optional import autofile # specify which template fields your plugin will provide FIELDS = {"{foo}": "Returns BAR", "{bar}": "Returns FOO"} @autofile.hookimpl def get_template_help() -> Iterable: """Specify help text for you...
python
""" appends JSON wine records from given data, formats and sort'em, output is JSON file, contains summary information by built-in parameters """ winedata_full = [] avg_wine_price_by_origin = [] ratings_count = [] def string_comb(raw_str): form_str = ' '.join( raw_str[1:-1].split() ).replace( ...
python
#!/usr/bin/env python3 # @generated AUTOGENERATED file. Do not Change! from dataclasses import dataclass, field as _field from ...config import custom_scalars, datetime from gql_client.runtime.variables import encode_variables from gql import gql, Client from gql.transport.exceptions import TransportQueryError from fu...
python
#!/usr/bin/env python3 # Copyright (c) 2004-present Facebook All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. from gql.transport.exceptions import TransportServerError from psym.common.constant import __version__ from .api.equipment_type impor...
python
import os import cv2 import numpy as np import argparse from SSRNET_model import SSR_net, SSR_net_general import sys import timeit from moviepy.editor import * from keras import backend as K def draw_label(image, point, label, font=cv2.FONT_HERSHEY_SIMPLEX, font_scale=1, thickness=2): size = cv2.get...
python
#!/usr/bin/env python3 import sys assert_statement = "Requires Python{mjr}.{mnr} or greater".format( mjr='3', mnr='4') assert sys.version_info >= (3, 4), assert_statement from groupby import main if __name__ == '__main__': main()
python
import importlib from contextlib import ContextDecorator from django.conf import settings ## add those to settings.py ## ## MOCKABLE_NAMES = { ## "MockableClassName": { ## "test": 'path.to.some.ServiceMockError', ## "development": 'path.to.some.ServiceMockOk', ## # "production": 'please.don...
python
import torch from torch import nn from PVANet import PVANet device = torch.device("cuda" if torch.cuda.is_available() else "cpu") class Encoder(nn.Module): def __init__(self, in_channels, out_channels,feature_size=20): super(Encoder, self).__init__() self.cnn = PVANet(in_channels, out_channels) ...
python
""" Functions in this file have all been defined in the notebooks. This file serves to allow subsequent notebooks to import functionality and reduce code duplication. """ import cv2 import numpy as np import ipyvolume as ipv def calibrate_cameras() : """ Calibrates cameras from chessboard images. Ret...
python
from urllib.request import Request, urlopen from bs4 import BeautifulSoup class WebDelegate: def __init__(self, parser_engine=BeautifulSoup): #TO-DO: default parser engine은 BeautifulSoup. 필요시 추가. self.__parser_engine=parser_engine def get_web_data(self, addr): req = Request(addr, heade...
python
from solution import Solution # MAIN TESTING PROGRAM: m = 5 n = 5 sln = Solution() result = sln.unique_paths(m,n) print('Input:') print(m) print(n) print('Output:') print(result)
python
''' Facebook Hacker Cup 2017 (Qualification Round) problem 2 : https://www.facebook.com/hackercup/problem/169401886867367/ Lazy Loader ''' import sys DEBUG = 1 TESTCASE = 'input/lazy_loading.txt' def maxTrips(a): a = sorted(a) trips = 0 while len(a) > 0: w = a.pop() k = w wh...
python
# coding=utf-8 """ Copyright 2013 LinkedIn Corp. 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 l...
python
""" Json for config file. Added supports for comments and expandable keywords. """ import copy import json import os RECURRENT_OBJECT_TYPES = (dict, list) # Identifier key to import another json file, # work as prefix, allowing "INCLUDE_KEY_1", "INCLUDE_KEY_2"... INCLUDE_KEY = '_include_json' # There may be perform...
python
# Module name: user # from package: smart_scheduler_tools # Used Modules: basic_structures_definitions, code_plus_section_list_generator, # code_plus_section_set_filter, subject_list_to_dictionary, dict_from_json # Description: Its the most fundamental class of the application, it uses all the # basic struc...
python
from preprocessor.Text_File import Text_File, Log_File class Bibtex_File(Text_File): """ Examples: >>> # Instantiation >>> my_bibtex_file = Bibtex_File('example_data//vu_25_test.bib') >>> # Invalid formatting of input directory >>> try: ... # input directory path ...
python
""" Copyright 2020 The Johns Hopkins University Applied Physics Laboratory LLC 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 Unles...
python
# -*- coding: utf-8 -*- r""" Hugging Face BERT implementation. ============== BERT model from hugging face transformers repo. """ import torch from transformers import BertModel, BertForMaskedLM from caption.models.encoders.encoder_base import Encoder from caption.tokenizers import BERTTextEncoder from test_tube i...
python
from .. import db Playlist_Songs = db.Table("play_songs", db.Column("playlist_id", db.Integer, db.ForeignKey('playlist._Playlist__id')), db.Column("song_id", db.Integer, db.ForeignKey('song._Song__id')) ...
python
import re import numpy as np def pad_sequences(sequences, maxlen=None, dtype='int32', padding='pre', truncating='pre', value=0.): """Pads sequences to the same length. # Arguments sequences: List of lists, where each element is a sequence. maxlen: Int, maximum length of all se...
python
#!/usr/bin/env python import argparse import glob import re import os import textract import pyexcel as pe import email.utils import olefile as OleFile from email.parser import Parser as EmailParser EMAIL_REGEX = re.compile(r"(?i)([a-z0-9._-]{1,}@[a-z0-9-]{1,}\.[a-z]{2,})") FLAT_FORMATS = ['txt', 'out', 'log', 'csv'...
python
# Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved. from typing import Sequence, Union, Callable, Any, Set import warnings import dace from dace import Config import dace.serialize import dace.library from dace.sdfg import SDFG, SDFGState from dace.sdfg import graph, nodes from dace.properties...
python
# # 2018-01-15 by Toomas Mölder # Some temporary logging (activity includes _tmp_ added for all steps to better understand, what steps take how long and what indexes to create # TODO: add exception handling # from AnalyzerDatabaseManager import AnalyzerDatabaseManager from models.AveragesByTimeperiodModel import Averag...
python
import os import textwrap from typing import List, Optional import colorama # type: ignore from spectacles.logger import GLOBAL_LOGGER as logger, log_sql_error, COLORS LINE_WIDTH = 80 COLOR_CODE_LENGTH = len(colorama.Fore.RED) + len(colorama.Style.RESET_ALL) def color(text: str, name: str) -> str: if os.environ...
python
# ##### BEGIN MIT LICENSE BLOCK ##### # # Copyright (c) 2015 - 2017 Pixar # # 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 u...
python
import logging import warnings from analyzer import Analyzer log = logging.getLogger(__name__) class URLParsing: def __init__(self, url_link): self.url_link = url_link self.tittle = None self.keywords = None log.info("set new url {}".format(self.url_link)) self.parsing() ...
python
""" Provides the Vault class for secure variable storage. """ import base64 import getpass import json import os import subprocess import tempfile from simple_automation.vars import Vars from simple_automation.exceptions import LogicError, MessageError from simple_automation.utils import choice_yes class Vault(Vars)...
python
from .__version__ import __title__, __description__, __url__, __version__ from .__version__ import __author__, __author_email__, __license__ from .__version__ import __copyright__ from .config import Config from .neuralnet import NeuralNetwork from .layers import activation, affine, batch_norm, convolution, dropout f...
python
try: from ulab import numpy as np except: import numpy as np dtypes = (np.uint8, np.int8, np.uint16, np.int16, np.float) print(np.ones(3)) print(np.ones((3,3))) print(np.eye(3)) print(np.eye(3, M=4)) print(np.eye(3, M=4, k=0)) print(np.eye(3, M=4, k=-1)) print(np.eye(3, M=4, k=-2)) print(np.eye(3, M=4, k=-3)...
python
from .imdb import AS, IMDb # NOQA __version__ = "1.0.22"
python
from AppKit import * from PyObjCTools.TestSupport import * class TestNSUserInterfaceValidationHelper (NSObject): def action(self): return 1 def tag(self): return 1 def validateUserInterfaceItem_(self, a): return 1 class TestNSUserInterfaceValidation (TestCase): def testProtocols(self): self.a...
python
import PyPDF2 import pytesseract from pdf2image import convert_from_path from src.plataform import data_dir_scan as dds class pdf_extract: @staticmethod def get_text_pypdf2(filename): pdf_reader = PyPDF2.PdfFileReader(pdf_extract.__path_from_filename(filename)) pdf_text = '' for i i...
python
""" Simple water flow example using ANUGA: Water flowing down a channel. It was called "steep_slope" in an old validation test. """ import sys #------------------------------------------------------------------------------ # Import necessary modules #--------------------------------------------------------------------...
python
import numpy as np def cubic_roots(a, b, c, d): """Compute the roots of the cubic polynomial :math:`ax^3 + bx^2 + cx + d`. :param a: cubic coefficient :param b: quadratic coefficient :param c: linear coefficient :param d: constant :return: list of three complex roots This functio...
python
# Copyright 2017 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 agre...
python
from django.core.paginator import Paginator from django.db.models import Q from django.shortcuts import render from django.utils import timezone from pokefriend.forms import TrainerRegisterForms, TrainerSearchForms from pokefriend.models import Trainer def index(request): register_form = TrainerRegisterForms() ...
python
class PBXList(list): pass
python
import collections import logging import random from datetime import datetime from typing import Iterable, Text, Dict, Any import attr import faust from replay_output_experiment.app import app from replay_output_experiment.page_views.models import BalanceUpdate, RequestTransfer, DATETIME_BASIC_FORMAT, \ balances...
python
# print keypad combination codes = [".;","abc","def","ghi","jkl","mno","pqrs","tu","vwx","yz"] def gkpc(keypad): if len(keypad) ==0: return [""] key = keypad[0] rok = keypad[1:] rres = gkpc(rok) mres =[] for word in rres: for char in codes[int(key)]: mres.append(cha...
python
# encoding: utf8 # filename: completion.py import logging import transformers from transformers import AutoConfig, AutoModel, AutoTokenizer, pipeline from abc import ABC, abstractmethod from functools import partial from typing import List from .corpus import Document __all__ = ('AbstractCompletor', 'make_co...
python
number_1 = float(input('Type a number: ')) number_2 = float(input('Type another one: ')) number_3 = float(input('Type the last one, please: ')) if number_1 > number_2 and number_1 > number_3: if number_2 > number_3: print(f'{number_1} + {number_2} = {number_1 + number_2}') else: print(f'{number...
python
# -*- encoding: utf-8 -*- import os import click ### set environment variable # os.environ['FLASK_CONFIGURATION'] = "default" # "testing" / "production" ### change environment var to "production" for debugging # os.environ['FLASK_CONFIGURATION'] = "production" # from app import app debug = True @click.comman...
python
import sys import unittest import testing.postgresql import psycopg2 import mock from mock import patch from eutils import Client sys.path.append("..") import crud import dblib def handler(postgresql): with open('data/srss.sql', 'r') as myfile: data = myfile.read().replace('\n', '') conn = psycopg2.c...
python
import datetime as dt def getDatefromDate(date,delta,strfmt='%Y%m%d'): if type(date)==str: date=stringToDate(date,strfmt) return (date + dt.timedelta(delta)).strftime(strfmt) def getDateFromToday(delta,strfmt='%Y%m%d'): """ Returns a string that represents a date n numbers of days from today. Parameters: ----...
python
from M2Crypto.EVP import Cipher from M2Crypto.Rand import rand_bytes class TestRule3c: def __init__(self): self.g_encrypt = 1 self.g_decrypt = 0 self.g_key1 = b"12345678123456781234567812345678" self.g_key2 = bytes("12345678123456781234567812345678", "utf8") self.g_iv = b"0...
python
"""General-purpose test script for image-to-image translation. Once you have trained your model with train.py, you can use this script to test the model. It will load a saved model from --checkpoints_dir and save the results to --results_dir. It first creates model and dataset given the option. It will hard-code some...
python
from datetime import date from time import sleep print('\033[1:31m-=-\033[m' * 10) print('\033[1m ...ALISTAMENTO MILITAR...\033[m') print('\033[1:31m-=-\033[m' * 10) ano = int(input('Em que ano você nasceu? ')) today = date.today().year dif = today - ano sleep(2) print('''\033[1m...PROCESSANDO...AGUARDE... ''...
python
import zPE.GUI.io_encap as io_encap from zPE.GUI.zComp.zStrokeParser import KEY_BINDING_RULE_MKUP, parse_key_binding as zSP_PARSE_KEY_BINDING import os, sys import pygtk pygtk.require('2.0') import gtk import copy # for deep copy import pango # for parsing the font import re ...
python
# -*- coding: utf-8 -*- import unittest import os from elfwrapper.elf_wrapper import ElfAddrObj class TestApp(unittest.TestCase): def setUp(self): pass def test_1(self): elf = ElfAddrObj(os.path.join(os.getcwd(), r"example/Test.elf")) with open(r'example\test_var.txtdatafile.txt') ...
python
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """TPS65185: Single chip PMIC for E Ink (R) Vizplex (TM) Enabled Electronic Paper Display""" __author__ = "ChISL" __copyright__ = "TBD" __credits__ = ["Texas Instruments"] __license__ = "TBD" __version__ = "0.1" __maintainer__ = "https://chisl.io" __email__ ...
python
import matplotlib matplotlib.use('Agg') import os import argparse import torch import numpy as np import pickle import sys sys.path.append('./utils') from torch import optim from torch import nn from torch import multiprocessing from torch.optim import lr_scheduler from torch.autograd import Variable from torch.utils....
python