content stringlengths 5 1.05M |
|---|
import os
from flask import request, render_template, redirect, session, Blueprint, flash, jsonify, abort, send_from_directory
from werkzeug.utils import secure_filename
import indieweb_utils
from bs4 import BeautifulSoup
import requests
from config import ENDPOINT_URL, TWITTER_BEARER_TOKEN, UPLOAD_FOLDER, MEDIA_ENDP... |
"""Docstring for varnet.py
Normalized U-Net implemetnation for unrolled block network.
"""
import math
from typing import List, Tuple
import fastmri
import torch
import torch.nn as nn
import torch.nn.functional as F
from fastmri.data import transforms
from unet import MHUnet
from att_unet import AttUnet
class Nor... |
import pygame
import numpy as np
from time import sleep
class GameOfLife:
def __init__(self):
pygame.init()
self.size = 800
self.divisions = 100
self.length = self.size // self.divisions
self.screen = pygame.display.set_mode((self.size, self.size))
self.fps = 120
... |
import numpy as np
import torch
import torchvision
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from sklearn.manifold import TSNE
import os
from .model import resnet
from PIL import ImageFilter
import random
def adjust_learning_rate(args, optimizer, epoch, lr):
# if args.cosine:
# eta_min = l... |
x = int(input())
if x % 2 == 0:
y = x + 1
print(y)
y = y + 2
print(y)
y = y + 2
print(y)
y = y + 2
print(y)
else:
y = x
print(y)
y = y + 2
print(y)
y = y + 2
print(y)
y = y + 2
print(y)
|
from datetime import datetime
from django.utils import timezone
from django.shortcuts import render, get_object_or_404
from django.db.models import Q
from django.contrib.auth.models import User, Group
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.http... |
# https://leetcode.com/problems/palindrome-number/
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0:
return False
p, res = x, 0
while p:
res = res * 10 + p % 10
p = int(p/10)
return res == x |
import numpy as np
import multiprocessing
import xgboost as xgb # requires xgboost package, installed e.g. via 'pip install xgboost'
class XGBoost:
def __init__(self, train_loader, val_loader, x_shape, dim_out, args):
self.args = args
self.dim_out = dim_out
if args.regression:
... |
import os
import time
# 请求用户输入要循环开关闭的网卡名称
eth_name = input('请输入要循环启用关闭的网卡名称:')
# 记录循环次数
i = 1
while True:
# 关闭指定网卡
os.popen('ifconfig ' + eth_name + ' down')
print(eth_name + '网卡关闭了')
# 休眠5S
time.sleep(5)
# 开启指定网卡
os.popen('ifconfig ' + eth_name + ' up')
print(eth_name + '网卡开启了')
# ... |
import wx
class Example(wx.Frame):
def __init__(self, parent, title):
super(Example, self).__init__(parent, title=title,
size=(400, 200))
self.Move((800, 250))
#self.Centre()
def main():
app = wx.App()
ex = Example(None, title='M2I & MQL - Moving Wind')
... |
"""
This file defines common tags to use in templates
"""
from django import template
from django.contrib import messages
from django.template.defaultfilters import safe
register = template.Library()
@register.filter(name="make_spaces")
def make_spaces(in_string: str) -> str:
"""
This filter takes a... |
import json
from google.protobuf import json_format
from services.doubler.doubler_pb2 import Number
def build_request_from_dict(d, request):
json_str = json.dumps(d)
return json_format.Parse(json_str, request)
def build_request_from_file(filename, request):
with open(filename) as f:
json_str = ... |
from .convLSTM import StConvLSTM
from .GRU import StGRU
from .additive import StAdditive
from .LSTM import StLSTM
|
#!/usr/bin/env python
"""
Example of a telnet application that displays a dialog window.
"""
from __future__ import unicode_literals
from prompt_toolkit.contrib.telnet.server import TelnetServer
from prompt_toolkit.shortcuts.dialogs import yes_no_dialog
from prompt_toolkit.eventloop import From, get_event_loop
import... |
from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
def contruindo_relatorio(service, creds, SAMPLE_SPREADSHEET_ID, lista):
# Quantidade Ped... |
'''
Created on Jan 6, 2016
@author: T0157129
'''
import logging
import logging.config
from Items.PotionObject import PotionObject
class MyCharacter:
'''
This class represents a basic character.
Attributes:
int HP : represents the Health Points of the character.
If HP==0 the chara... |
# Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""
ans = []
for intv in sorted(intervals,... |
from __future__ import division
import os,time,cv2
import scipy.io as sio
import tensorflow as tf
import tensorflow.contrib.slim as slim
import numpy as np
from numpy import *
import scipy.linalg
from copy import copy, deepcopy
def lrelu(x):
return tf.maximum(x*0.2,x)
def identity_initializer():
def _initiali... |
import tweepy
from tweepy.parsers import JSONParser
# This class creates an instance of the Twitter API
class API(object):
# Initiates the API
def __init__(self):
# Keys for Twitter API (maybe reading it from a .txt)
self.consumer_key = 'EfbgNEMgmXNSweNDcWmoaSwm0'
self.consumer_secret ... |
# coding=utf-8
import threading, time, re, os, sys, json, random
try:
import requests
except ImportError:
print '---------------------------------------------------'
print '[*] pip install requests'
print ' [-] you need to install requests Module'
sys.exit()
'''
\ \ / /__ _ ... |
"""
methods for processing mapping results in SAM/BAM format
def parse_deltas(sam_file, ...):
parse a sam/bam file into dicts of coverage changes by position
def deltas_to_cov(cov_deltas, x_max=None, nan_for_zero=True):
convert coverage deltas into coverage array
class SAMFlag(IntFlag):
class for dec... |
"""
Module for requesting to URL and get page's html code from there,
download media files, check that the request if correct, page in RNC exists.
"""
__all__ = (
'get_htmls', 'is_request_correct', 'download_docs'
)
import asyncio
import logging
import time
from typing import List, Optional, Tuple, Union
import ... |
"""
Python Interchangeable Virtual Instrument Library
Copyright (c) 2013-2014 Alex Forencich
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... |
from maskcnn import training_aux_wrapper
from sys import argv
def main():
dataset, image_subset, neuron_subset, seed, arch_name, opt_name = argv[1:]
training_aux_wrapper.train_one_wrapper(dataset, image_subset, neuron_subset, int(seed), arch_name, opt_name)
if __name__ == '__main__':
main()
|
import numpy
import unittest
import sycomore
from sycomore.units import *
class TestBloch(unittest.TestCase):
def test_pulse(self):
M = sycomore.bloch.pulse(47*deg, 23*deg)
numpy.testing.assert_almost_equal(
M,
[[ 0.95145043, 0.11437562, 0.28576266, 0. ],
... |
from django.urls import include, path
from rest_framework.routers import DefaultRouter
from project.tweets.views import TweetsViewset
router = DefaultRouter()
router.register(r"tweets", TweetsViewset, basename="tweets")
urlpatterns = [
path("", include(router.urls)),
]
|
import random
import names
import csv
from django.template.defaultfilters import slugify
from orcamentos.crm.models import Customer, Person, PhonePerson
from orcamentos.utils.lists import COMPANY_LIST
from orcamentos.utils.gen_random_values import (
gen_cpf,
gen_digits,
gen_phone,
gen_rg,
)
from orcamen... |
from urllib.request import urlopen
def get_page_3(url):
pagina = urlopen(url)
codigoHtml = pagina.read().decode('utf')
pagina.close()
return codigoHtml
def get_next_target(website):
start_link= website.find('<a href')
if (start_link) != -1:
start_quote= website.find('"',start_link... |
/home/runner/.cache/pip/pool/cf/51/25/b749cb02a5396340ce9fda7fffc4272d66af9443a947242291d6202aba |
def proc():
str = input()
fp = open('./dict/person.dic', mode='rt', encoding='utf-8')
while True:
line = fp.readline()
if not line:
break
if str in line:
return
fp.close()
fp = open('./dict/person.dic', mode='at', encoding='utf-8')
fp.write('\n%s/... |
import numpy as np
import libs.state_node as STTREE
class HillClimbing:
def __init__(self, initialPuzzle, answerPuzzle, k):
self.totalExpansions = 0
self.k = k
self.answerPuzzle = answerPuzzle.puzzle
self.frontier = []
self.frontier.append(
(
ST... |
# Generated by Django 3.1.13 on 2021-09-28 03:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('property', '0010_auto_20210928_0430'),
]
operations = [
migrations.AlterField(
model_name='property',
name='propert... |
from supermarket import Supermarket
from Markov import Get_Entry
entry = Get_Entry()
lidl = Supermarket(name='LIDL', entry = entry)
while lidl.is_open():
# increase the time of the supermarket by one minute
# generate new customers at their initial location
# repeat from step 1
lidl.add_new_cust... |
"""
Timeseries plots with error bands
=================================
_thumb: .5, .45
"""
import seaborn as sns
sns.set(style="darkgrid")
# Load an example dataset with long-form data
fmri = sns.load_dataset("fmri")
# Plot the responses for different events and regions
sns.lineplot(x="timepoint", y="signal",
... |
from typing import Literal, Any, List, Dict
from flask_sqlalchemy import SQLAlchemy
from base64 import b32encode
from flask import session
from globals import *
import xml.etree.ElementTree as ET
import sqlite3
import secrets
import random
import error
import re
import os
db = SQLAlchemy(app)
Role = Literal['s', 'u'... |
import bitwise as bw
class TestStackPointer:
def test_StackPointer(self):
up = bw.wire.Wire()
down = bw.wire.Wire()
clock = bw.wire.Wire()
output_bus = bw.wire.Bus16()
a = bw.processor.StackPointer(up, down, clock, output_bus)
clock.value = 0
clock.value =... |
from django.db import models
class Suggestion(models.Model):
name = models.CharField(max_length=100, unique=True)
class ImageTag(models.Model):
game = models.CharField(max_length=100)
image = models.CharField(max_length=50)
tag = models.CharField(max_length=200)
class Favorite(models.Model):
u... |
"""
byceps.blueprints.site.core.views
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from __future__ import annotations
from typing import Optional
from flask import g, url_for
from .... import config
from ....services.party im... |
from .qtscraper import *
from ._version import __version__
def setup(app):
from .qtgallery import setup
return setup(app)
|
# -*- coding: utf-8 -*-
# Copyright 2012 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 require... |
from keras.models import Sequential
from keras.layers import Dense, Flatten, Dropout
from keras.layers.convolutional import Conv2D, MaxPooling2D
class VGG19(Sequential):
def __init__(self):
super().__init__()
self.add(Conv2D(64, (3, 3), strides=(1, 1), input_shape=(224, 224, 3), padding='same', a... |
import sys
import time
import numpy as np
import pandas as pd
import datetime as dt
import multiprocessing as mp
class MultiProcessingFunctions:
""" This static functions in this class enable multi-processing"""
def __init__(self):
pass
@staticmethod
def lin_parts(num_atoms, num_threads):
""" This function... |
#!/usr/bin/python3
# ============================================================================
# Airbnb Configuration module, for use in web scraping and analytics
# ============================================================================
import logging
import os
import configparser
import sys
from bnb_kanpora.m... |
import _hgdb
class DebugSymbolTableException(Exception):
def __init__(self, what):
super().__init__(what)
# wrapper class
class DebugSymbolTable:
def __init__(self, filename):
self.db = _hgdb.init_debug_db(filename)
def store_variable(self, id_: int, value: str, is_rtl: bool = True):
... |
#This program takes a csv file of financial data as input and produces
#a statistical report stored to a csv file and printed to the terminal.
#The input file must contain a series of months with corresponding profits
#and losses. The output report includes the total number of months analyzed,
#the net total amount of ... |
import numpy as np
import tensorflow as tf
import time
# Load TFLite model and allocate tensors.
interpreter = tf.lite.Interpreter(model_path="output/model.tflite")
interpreter.allocate_tensors()
# Get input and output tensors.
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_de... |
#!/usr/bin/env python2
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import datetime
import optparse
import os
import re
import sys
import urlparse
import gclient_utils
import subprocess2
USAGE = ... |
# -*- coding: utf-8 -*-
"""
MagicTelecomAPILib.Models.Account
This file was automatically generated by APIMATIC v2.0 on 06/22/2016
"""
from MagicTelecomAPILib.APIHelper import APIHelper
class Account(object):
"""Implementation of the 'Account' model.
TODO: type model description here.
... |
# Linear regression on iris dataset
import numpy as np
import matplotlib.pyplot as plt
import os
figdir = os.path.join(os.environ["PYPROBML"], "figures")
def save_fig(fname): plt.savefig(os.path.join(figdir, fname))
import seaborn as sns
from sklearn.linear_model import LinearRegression
from sklearn import datasets... |
from clases.dia_mañana import *
from clases.yinyang import *
from clases.alternativa import *
if __name__ == "__main__":
print("¿Qué ejercicio quieres ver?:", "\n","1)Dia del mañana", "\n","2)Inmortal", "\n","3)Alternativa herencia multiple")
n =int(input("Número del ejercicio: "))
if n == 1:
des... |
# -*- coding: utf-8 -*-
################################################################################
## Form generated from reading UI file 'expstatus.ui'
##
## Created by: Qt User Interface Compiler version 5.15.0
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
################... |
first = list(input())
sec = list(input())
te = first + sec
te.sort()
third = list(input())
third.sort()
if te==third:
print("YES")
else:
print("NO")
s,i=sorted,input;print('YNEOS'[s(i()+i())!=s(i())::2])
|
# -*- coding: utf-8 -*-
from ..components import *
from ..container import *
from ..elements import *
__all__ = ['regression_report']
def regression_report(truth, predict, label=None, per_target=True,
target_names=None, title=None):
"""Regression report.
This method will compose a sta... |
# encoding: utf-8
# Copyright 2011 California Institute of Technology. ALL RIGHTS
# RESERVED. U.S. Government Sponsorship acknowledged.
def nullUpgradeStep(setupTool):
'''A null step for when a profile upgrade requires no custom activity.'''
|
#range_test function definition goes here
def range_test(num):
if num < 1 or num > 500:
return False
else:
return True
num = int(input("Enter a number: "))
if range_test(num):
print( "{:d} is in range.".format(num))
else:
print("The number you entered is outside the range!") |
# Python - 3.6.0
def is_sator_square(tablet):
n = len(tablet)
for r in range(n):
for c in range(n):
if not (tablet[r][c] == tablet[-(r + 1)][-(c + 1)] == tablet[c][r] == tablet[-(c + 1)][-(r + 1)]):
return False
return True
|
from platform import system, release
from sys import version_info
from configparser import ConfigParser
from pyrfc import Connection, get_nwrfclib_version
config = ConfigParser()
config.read('pyrfc.cfg')
params = config._sections['test']
conn = Connection(**params)
print(('Platform:', system(), release()))
print(('P... |
import platform, sys
if platform.system() == 'Windows': # pragma: no cover
WIN = True
else:
WIN = False
# True if we are running on Python 2.
PY2 = sys.version_info[0] == 2
if not PY2: # pragma: no cover
from urllib.parse import quote, unquote
string_type = str
unicode_text = str
byte_st... |
"""Tests for flake8.plugins.manager.PluginManager."""
import mock
from flake8.plugins import manager
def create_entry_point_mock(name):
"""Create a mocked EntryPoint."""
ep = mock.Mock(spec=['name'])
ep.name = name
return ep
@mock.patch('entrypoints.get_group_all')
def test_calls_entrypoints_on_ins... |
PyV8 = "PyV8"
Node = "Node"
JavaScriptCore = "JavaScriptCore"
SpiderMonkey = "SpiderMonkey"
JScript = "JScript"
PhantomJS = "PhantomJS"
SlimerJS = "SlimerJS"
Nashorn = "Nashorn"
Deno = "Deno"
|
from flask.sessions import SessionInterface, SessionMixin
from flask.json.tag import TaggedJSONSerializer
from werkzeug.datastructures import CallbackDict
from itsdangerous import BadSignature, want_bytes
from CTFd.cache import cache
from CTFd.utils import text_type
from CTFd.utils.security.signing import sign, unsign
... |
import math
n = int(input("Enter the number till where the series ius to be printed = "))
for i in range(1,n+1):
k = math.pow(i,3)
j = k + 2*i
print(j)
|
#Write a function that prompts user to input his/her full name.
#After user enter's his/her full name, split it and store it in variables first_name and last_name.
count=0
k=0
name=str(input("Enter your full name: "))
s=name.split(" ")
print("The first name is:",s[0])
if len(s)==3:
print("The middle name is:",s[... |
from typing import Tuple, Optional
from abc import ABC, abstractmethod
from mercury.msg.smart_grid import ElectricityOffer
from xdevs.models import Atomic, Port, PHASE_PASSIVE, INFINITY
from mercury.utils.history_buffer import EventHistoryBuffer
class EnergyProvider(Atomic, ABC):
def __init__(self, **kwargs):
... |
from abc import abstractmethod
from dataclasses import dataclass
from typing import List, Any, Callable, Dict, Tuple, NamedTuple, Union
from data_splitting import split_splits, LearnCurveJob, EvalJob
from seq_tag_util import calc_seqtag_f1_scores, Sequences
from util.worker_pool import GenericTask
@dataclass
class ... |
from SeeThru_Feeds.Model.Attribution import Attribution
from SeeThru_Feeds.Model.Properties.Properties import *
from SeeThru_Feeds.Model.Properties.PropertyManager import PropertyManager
class ComponentBase(PropertyManager, Attribution):
def component_execute(self):
"""
This function should be ove... |
'''
Copyright 2021 Kyle Kowalczyk
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
... |
# Copyright (c) 2019, MD2K Center of Excellence
# - Nasir Ali <nasir.ali08@gmail.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above cop... |
import pytesseract
import jiwer
from PIL import Image
from os import listdir
from os.path import join, isfile
TEST_PATH = '/train/tesstrain/data/storysquad-ground-truth'
extractions = []
ground_truths = []
count = 0
for file_name in listdir(TEST_PATH):
file_path = join(TEST_PATH, file_name)
if... |
from typing import (
IO,
Any,
Iterable,
Sequence,
Tuple,
)
from eth_utils import (
ValidationError,
to_tuple,
)
from eth_utils.toolz import (
sliding_window,
)
from ssz.exceptions import (
DeserializationError,
SerializationError,
)
from ssz.sedes.base import (
CompositeSed... |
import pytest
from lendingblock.const import Side, OrderType, Ccy
@pytest.fixture
async def wallets_org_id(lb, org_id):
for ccy in Ccy.BTC.name, Ccy.ETH.name, Ccy.LND.name:
await lb.execute(
f'organizations/{org_id}/wallets',
'POST',
json={
'address': f... |
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import absolute_import
import numpy as np
import tensorflow as tf
import scipy
import cPickle
import os
import glob
import random
import imageio
import scipy.misc as misc
log_device_placement = True
allow_soft_placement = True
gpu_option... |
from flask_wtf import FlaskForm
from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError
from wtforms import TextField, TextAreaField, SubmitField, validators, ValidationError,StringField, PasswordField, SubmitField, BooleanField
class LoginForm(FlaskForm):
email = StringField('Email', ... |
#
# Copyright (c) 2020 Carsten Igel.
#
# This file is part of puckdb
# (see https://github.com/carstencodes/puckdb).
#
# License: 3-clause BSD, see https://opensource.org/licenses/BSD-3-Clause
#
import unittest
import tempfile
import os
import time
import puckdb
class BasicTest(unittest.TestCase):
def test_no_c... |
#!/usr/bin/env python
"""
Inherits the stuff from tests.csvk – i.e. csvkit.tests.utils
"""
from tests.csvk import *
from tests.csvk import CSVKitTestCase as BaseCsvkitTestCase
import unittest
from unittest.mock import patch
from unittest import skip as skiptest
from unittest import TestCase
import warnings
from io ... |
from src.gui.alert import alert
def show_statistics(app):
"""Creates an alert that displays all statistics of the user
Args:
app (rumps.App): The App object of the main app
"""
message_string = "\n".join(f"{k} {str(i)}" for k, i in app.statistics.values())
alert(
title="Statistics... |
#!/usr/bin/env ipython
import numpy as np
import ipdb
import matplotlib.pyplot as plt
import seaborn as sns
import derived_results
import results_utils
from results_utils import ExperimentIdentifier
plt.style.use('ggplot')
def run_checks(cfg_name, model, diffinit, data_privacy='all', convergence_point=None):
f... |
from room import Room
from player import Player
from item import Item
import sys
import os
# Declare all the rooms
room = {
'outside': Room("Outside Cave Entrance", "North of you, the cave mount beckons"),
'foyer': Room("Foyer", """Dim light filters in from the south. Dusty
passages run north and east."""... |
from .employee import *
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from scipy.stats import geom
import matplotlib.pyplot as plt
import numpy as np
def testGeom():# {{{
"""
Geometric Distribution (discrete)
Notes
-----
伯努利事件进行k次, 第一次成功的概率
为什么是几何分布呢, 为什么不叫几毛分布?
与几何数列有关 (乘积倍数)
p: 成功的概率
q: 失败的概率(1-p)
... |
import base64
import json
import os
import twitter
import boto3
from time import sleep
from src.sam_quest import handle_game_state
# Constants
AWS_REGION = 'AWS_REGION'
total_processed = 0
# Environment Variables
aws_region = os.environ.get(AWS_REGION, 'us-west-2')
dynamodb_table_name = os.environ.get('TABLE_NAME'... |
import math
import re
from termcolor import colored
from sympy import Interval
import locale
locale.setlocale(locale.LC_ALL, '')
def round_sig(number, precision=4):
""" Round number with given number of significant numbers - precision
Args:
number (number): number to round
precision (int): nu... |
import copy
import json
import unittest
from typing import Any, Dict
import avro.schema # type: ignore
from wicker import schema
from wicker.core.errors import WickerSchemaException
from wicker.schema import dataloading, dataparsing, serialization
from wicker.schema.schema import PRIMARY_KEYS_TAG
from wicker.testing... |
from oslo_config import cfg
from oslo_log import log as logging
from nca47.common.i18n import _
from nca47.common.i18n import _LI
from nca47.common.exception_zdns import ZdnsErrMessage
from nca47.common.exception import NonExistDevices
from nca47.api.controllers.v1 import tools
import requests
import json
CONF = cfg.C... |
from flask import Flask, render_template, make_response, abort, jsonify, request, url_for
import os
import matplotlib.pyplot as plt
from io import BytesIO
from utils import *
import json
app = Flask(__name__, template_folder="tp4/templates", static_folder="tp4/static")
app_dir = os.getcwd()
db_ensembl = "tp4/data/ens... |
# -*- coding: utf-8 -*-
# @Author: JanKinCai
# @Date: 2019-12-26 23:15:03
# @Last Modified by: JanKinCai
# @Last Modified time: 2019-12-28 00:02:51
from interact import interacts
config = {
"ipv4": {
"type": "string",
"regex": r"^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$",
"default": "192.168.1... |
# -*- coding: utf-8 -*-
# Copyright (C) 2018 Intel Corporation
#
# SPDX-License-Identifier: Apache-2.0
"""
CLI logger
"""
import logging
import sys
import os
import io
VERBOSE = any(arg.startswith("-v") for arg in sys.argv)
XML_REPORTING = any(arg.startswith("-x") for arg in sys.argv)
class StreamHandler(logging.St... |
#
# WSGI entry point for RD
#
from rdr_service.main import app as application
if __name__ == "__main__":
application.run()
|
import logging
from spaceone.core.base import CoreObject
from spaceone.core.transaction import Transaction
_LOGGER = logging.getLogger(__name__)
class BaseConnector(CoreObject):
def __init__(self, transaction: Transaction = None, config: dict = None, **kwargs):
super().__init__(transaction=transaction)
... |
import string
from api.create_sync_video_job import UAICensorCreateSyncVideoJobApi
from api.create_async_video_job import UAICensorCreateAsyncVideoJobApi
from operation.utils import parse_unrequired_args
from operation.base_datastream_operation import UAICensorBaseDatastreamOperation
class UAICensorCreateVideoJobOp... |
# -*- coding: utf-8 -*-
from dart_fss import api, auth, corp, errors, filings, fs, utils, xbrl
from dart_fss.auth import set_api_key, get_api_key
from dart_fss.corp import get_corp_list
from dart_fss.filings import search
from dart_fss.fs import extract
from dart_fss.xbrl import get_xbrl_from_file
__all__ = [
'api... |
from random import randint as rand
Map = {0:42, 1:43, 2:45}
n = rand(0, rand(0, int(input())))
with open("in", "w+") as f:
f.write(chr(rand(48, 57)))
i, operators = 0, 0
while i < n:
if i == operators:
f.write(chr(rand(48, 57)))
i += 1
continue
op = rand(0, 1)
if op:
f.write(chr(Map[rand(0, 2)]))
... |
#!/usr/bin/env python
# Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo
# Copyright (C) 2008-2020 German Aerospace Center (DLR) and others.
# This program and the accompanying materials are made available under the
# terms of the Eclipse Public License 2.0 which is available at
# https://www.ec... |
# Imports
from utils import labeled_loader, suncet_fine_tune, config
import tensorflow as tf
import time
# Constants
STEPS_PER_EPOCH = int(config.SUPPORT_SAMPLES // config.SUPPORT_BS)
TOTAL_STEPS = config.FINETUNING_EPOCHS * STEPS_PER_EPOCH
# Prepare Dataset object for the support samples
# Note - no augmentation
sup... |
"""
The MIT License (MIT)
Copyright (c) 2016 Jake Lussier (Stanford University)
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... |
'''
Faça um programa que leia um número inteiro e mostre na tela o suscessor e seu antecessor.
'''
print('===== Exercício 05 =====')
n1 = int(input('Digite um número: '))
print(f'O antecessor de {n1} é {n1-1} e o sucessor é {n1+1}')
|
"""
1265, print immutable linked list reverse
Difficulty: medium
You are given an immutable linked list, print out all values of each node in reverse with the help of the following interface:
ImmutableListNode: An interface of immutable linked list, you are given the head of the list.
You need to use the following f... |
"""
Module providing AES256 symmetric encryption services
If run as a Python command-line script, module will interactively prompt
for a password, then print out the corresponding encoded db_config.ini
password parameters suitable for cut/pasting into API .ini config files.
Copyright (C) 2016 ERT Inc.
"""
import getp... |
#!/usr/bin/env python
#
# Copyright 2007 Google 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 o... |
import psycopg2
# printStackTrace prints as follows for postgres connection error
# --------------------------------------------------------------------------------
# Error connecting postgres database:
# --------------------------------------------------------------------------------
# Traceback (most recent call las... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.