content stringlengths 5 1.05M |
|---|
# python3
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... |
'''
One-off script to look at embedding results for a set of script
'''
import argparse, os, pickle, random, sys, time
import numpy as np
import torch
import scipy.io
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import NearestNeighbors
sys.path.append("..")
from DL.utils import *
from DL.ne... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 4.0.1-9346c8cc45 (http://hl7.org/fhir/StructureDefinition/Subscription) on 2020-02-03.
# 2020, SMART Health IT.
import sys
from dataclasses import dataclass, field
from typing import ClassVar, Optional, List
from .backboneelement import BackboneEl... |
#!/bin/false
# Copyright (c) 2022 Vít Labuda. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
# following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice, this list of conditions an... |
import shutil
from tempfile import mkdtemp, mktemp
import os
from zipfile import ZipFile
from AnkiTools.excel import AnkiExcelSync
class AnkiFormatEditor:
def __init__(self):
self.tempdir = mkdtemp()
def convert(self, in_file, out_file=None, out_format=None):
in_file_type = os.path.splitext(... |
"""
ObjectiveGenerator constructs 3 types of optimization objectives
- Risk-only (Volatility, Variance, Skewness, Kurtosis, Higher Normalized Moments, Market Neutral)
- Risk Reward (Expected Return, Efficient Frontier, Sharpe, Sortino, Beta, Treynor, Jenson's Alpha)
- Numerical (Inverse Volatility, Variance... |
from typing import Dict, Any
import json
import logging
import os
import boto3
from utils.parse_user_id import parse_user_id
from aws_xray_sdk.core import patch_all
patch_all()
logger = logging.getLogger()
logger.setLevel(logging.INFO)
dynamodb = boto3.resource('dynamodb')
def put_handler(event: Dict[str, Any], co... |
# -*- coding: utf-8 -*-
"""
**views.jobs**
================
This module contains the jobs function that handles requests for the jobs
endpoint of the mycroft service.
"""
from simplejson.decoder import JSONDecodeError
from staticconf import read_string
from pyramid.view import view_config
from mycroft.logic.job_acti... |
import math
def do_naive_bayes_prediction(x, observed_class_distribution: dict, splitters: dict):
"""Perform Naive Bayes prediction
Parameters
----------
x
The feature values.
observed_class_distribution
Observed class distribution.
splitters
Attribute (features) obs... |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.7.0-rc1
# kernelspec:
# display_name: Python [conda env:b36]
# language: python
# name: conda-env-b36-py
# ---
# %% [markdown]
# # import... |
"""
Exemplary workflow using the py-fmas library code.
.. codeauthor:: Oliver Melchert <melchert@iqo.uni-hannover.de>
"""
import fmas
import numpy as np
glob = fmas.data_io.read_h5("in_file.h5")
grid = fmas.grid.Grid(
t_max=glob.t_max, t_num=glob.t_num, z_max=glob.z_max, z_num=glob.z_num
)
model = fmas.models.F... |
# -*- coding: utf-8 -*-
from rest_framework import viewsets, mixins, decorators, response
from apps.contact import models
from . import serializers
class ContactViewSetMixin:
def get_queryset(self):
qs = super().get_queryset()
type = self.request.query_params.get('type', None)
if type:
... |
from typing import Generator, List, Dict
import pandas as pd
from gym import Space
import pytest
from tensortrade import TradingContext
from tensortrade.exchanges import Exchange
from tensortrade.trades import Trade
@pytest.mark.xskip(reason="GAN exchange is not complete. ")
def test_create_gan_exchnage():
"""... |
print('=' * 5, 'EX_003', '=' * 5)
nome = input('Digite seu nome: ')
print('Bem vindo, {}!'.format(nome))
|
import os
from pydantic import BaseSettings
class Settings(BaseSettings):
class Config:
env_file = ".env"
app_name: str = "FastAPI Demo"
admin_email: str = "sirayhancs@gmail.com"
secret_key: str = os.getenv("SECRET_KEY")
hash_algo: str = os.getenv("HASH_ALGO", "HS256")
access_tok... |
import sys, time
def readanswers():
try:
answers = {}
f = open('answers.txt')
try:
for line in f.readlines():
line = line.strip()
if line:
problem, answer = line.split(':')
answers[int(problem.str... |
# -*- coding: utf-8 -*-
from collections import defaultdict
from contextlib import suppress
from timeit import default_timer
from threading import Event, Thread, Lock
import os
import time
import sys
try:
from dask.callbacks import Callback
except ImportError as e:
opt_import_err = e
Callback = object
else... |
import yfinance as yf
import datetime as dt
import pandas as pd
from pandas_datareader import data as pdr
yf.pdr_override() # <== that's all it takes :-)
start =dt.datetime(1980,12,1)
now = dt.datetime.now()
stock=""
stock = input("Enter the stock symbol : ")
while stock != "quit":
df = pdr.get_data_yahoo(stock, s... |
import pickle
import scipy.stats as st
from sklearn.model_selection import RandomizedSearchCV
from sklearn.metrics import auc
from sklearn.model_selection import StratifiedKFold
import xgboost as xgb
from sklearn.model_selection import KFold
from sklearn.metrics import matthews_corrcoef,make_scorer
def train_xgb(X,
... |
'''
Beginning with just a plot
Let's get started on the Gapminder app. Your job is to make the ColumnDataSource object, prepare the plot, and add circles for Life expectancy vs Fertility. You'll also set x and y ranges for the axes.
As in the previous chapter, the DataCamp environment executes the bokeh serve command... |
# Copyright (c) 2021, TU Wien, Department of Geodesy and Geoinformation
# 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 copyright notice,... |
"""
Post Class
for lap_joint script
Post:
.id int Post identifier
.brep Brep Brep representing Post
.profile Curve Curve defining end profile of post
.axis Line Line between centers of end faces
.origin Point start of axis Line
.ori... |
# import socket programming library
import socket
import sys
from packet_parser import Parser
# import thread module
from _thread import *
import threading
parser = Parser()
print_lock = threading.Lock()
stateOfApllication = True
# thread function
def threaded(c):
while True:
# data received from... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2018 University of Groningen
#
# 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
#
# U... |
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
profile_photo = models.ImageField(upload_to = 'images/',blank=True)
bio = models.TextField(max_length = 50,null = True)
user = models.OneToOneField(User,on_delete=models.CASCADE)
def __str__(self):
... |
import datetime
import pytest
from django.core.management import call_command
from dashboard.testing import BuilderTestCase
from apps.flowers.builder import direct_wholesale_04
from apps.dailytrans.models import DailyTran
from apps.flowers.models import Flower
from apps.configs.models import Source
from django.db.model... |
import panscore
def load(filename:str)->panscore.Score:
#打开文件,返回panscore.Score对象
#由于编码不确定,先用二进制打开文件
with open(filename,'rb') as f:
file=f.read()
#读取编码
if(b"Charset=UTF-8" in file):
encoding="utf-8"
else:
encoding="shift-JIS"
#分块
blocks=[]
block=... |
# Alphabeticak order
# TODO add method and class definition modules
from .bayesianEstimator import BayesianEstimator
from .errorEstimator import ErrorEstimator
from .estimationAssembler import EstimationAssembler
from .hierarchyOptimiser import HierarchyOptimiser
from .modelEstimator import ModelEstimator
from .m... |
import cioppy
import geopandas as gp
import os
import pandas as pd
from py_snap_helpers import *
from shapely.geometry import box
from snappy import jpy
from snappy import ProductIO
import gdal
import osr
import ogr
from shapely.geometry import box
import json
import sys
sys.path.append('/opt/OTB/lib/python')
sys.path... |
from django.contrib import admin
from .models import Entry
def publish_selected(modeladmin, request, queryset):
queryset.update(is_published=True)
publish_selected.short_description = "Publish the selected posts"
@admin.register(Entry)
class EntryAdmin(admin.ModelAdmin):
list_display = ("pub_date", "titl... |
# Generated by Django 3.0.12 on 2021-03-01 11:06
from django.db import migrations, models
import django.utils.timezone
import model_utils.fields
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Blog',
... |
__all__ = ["Brain", "Entity","STT", "TTS"]
|
# import statements
import cv2
import os
import sqlite3
from tkinter import *
'''
Function to assure whether the folder to store the training images are here.
'''
def assure_folder_exists(folder):
directory = os.path.dirname(folder)
if not os.path.exists(directory):
os.makedirs(directory)
# Variables... |
from MDSplus import Device, Event, VECTOR, Uint8Array
import subprocess
import numpy as np
import time
import traceback
import os
MC = __import__('MARTE2_COMPONENT', globals())
class MARTE2_SUPERVISOR(Device):
"""National Instrument 6683 device. Generation of clock and triggers and recording of events """
p... |
import io
import logging
from random import sample
from typing import List
import matplotlib.pyplot as plt
from django.contrib import messages
from django.contrib.auth import authenticate, logout, login, update_session_auth_hash
from django.contrib.auth.decorators import login_required, permission_required
from django... |
# License: BSD 3 clause
import tick.base
from .hawkes_kernels import (HawkesKernel0, HawkesKernelExp,
HawkesKernelPowerLaw, HawkesKernelSumExp,
HawkesKernelTimeFunc)
from .simu_hawkes import SimuHawkes
from .simu_hawkes_exp_kernels import SimuHawkesExpKernels
... |
import re
from typing import Dict, List, Optional, Union
from ufal.udpipe import InputFormat
from ufal.udpipe import Model
from ufal.udpipe import OutputFormat, ProcessingError, Sentence
from .utils import get_path
def _default_model_meta(lang: str, name: str) -> Dict:
return {
"author": "Milan Straka &... |
import os
def attempt_already_made(function_name, dirname, new_args):
MAKE_ATTEMPT = False
# Construct filename from function and dirname.
filename = dirname + function_name + '_args.sobj'
special_comparisons = {'construct_all_odes' : construct_all_odes_cmp}
try:
old_args = load(... |
somaIdade = 0
homemVelho = [0, 'nome']
mulher = 0
for p in range(1, 5):
print('=' * 10, f'{p}ª Pessoa', '=' * 10)
nome = str(input('Informe seu nome: ')).strip()
idade = int(input('Informe sua idade: '))
sexo = str(input('Qual o seu sexo?\nSexo [M/F]: ')).strip().upper()
somaIdade += idade
if ... |
from __future__ import division
from expr_utils import *
PATH = "" # Data path
if __name__ == "__main__":
# Command-line args:
# fname: 'ORL' or 'PEMS'
# rep: trial number
fname, rep = sys.argv[1:]
rep = int(rep)
# ORL data (400 * 10304)
# PEMS-SF data (440 * 138672)
A = np.load... |
mainpage="""/**
\mainpage {0}
This is the mainpage description for the "{0}" project as found in
mainpage.dox.
*/
"""
|
# Generated by Django 3.1.1 on 2020-09-21 18:36
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('products', '0003_product_image'),
('categories', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='cate... |
# -*- coding: utf-8 -*-
################################################################################
## Form generated from reading UI file 'FormloginObXcwY.ui'
##
## Created by: Qt User Interface Compiler version 5.14.2
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
##########... |
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from workflows.models import State
from workflows.models import StateInheritanceBlock
from workflows.models import StatePermissionRelation
from workflows.models import StateObjectRelation
from workflows.models import TransitionObje... |
import RPi.GPIO as GPIO
import time
leds = [20,21,4,17,27]
GPIO.setmode(GPIO.BCM)
for led in leds:
GPIO.setup(led,GPIO.OUT)
GPIO.output(led,GPIO.LOW)
i=0
while i <30:
for led in leds:
GPIO.output(led,GPIO.HIGH)
time.sleep(0.5)
GPIO.output(led,GPIO.LOW)
i+=1 # i = i + 1
GPIO... |
salario = float(input('Informe seu salário: '))
if salario > 1250:
ajuste = 0.10 * salario
ajuste += salario
print('O seu salário de R${:.2f} sofreu aumento de 10%. Reajuste salárial: R${:.2f}'.format(salario, ajuste))
else:
ajuste = 0.15 * salario
ajuste += salario
print('O seu salário de R${:.2f... |
"""
aggregators
This file maintains methods for path aggregation
- Rakshit Agrawal, 2018
"""
import numpy as np
import tensorflow as tf
kl = tf.keras.layers
class Aggregators(object):
def __init__(self,
node_count,
path_lengths,
additional_embeddings=None,
... |
import os
import wx
from pprint import pprint
# from ..Views.StatsPanel.PlayersPanel import NCAABPlayerStatsPanel, NBAPlayerStatsPanel
from ..Views.TeamPanels.StatsPanel import NCAABStatsPanel, NBAStatsPanel, MLBStatsPanel
from ..Views.GamePanels.GameLinePanel import GameLinePanel
from .GamePanels.TitlePanel import Ti... |
import glob
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import cv2
import os.path as path
def calibrate_pts(input_path):
objpoints = [] # Objects in real world space
imgpoints = [] # Objects in 2-D space
nx, ny = 9, 6
objp = np.zeros((nx * ny, 3), np.float32)
... |
from rest_framework import serializers
from wq.db.rest.serializers import ModelSerializer
from wq.db.patterns import serializers as patterns
from vera.models import Site
from .models import Parameter, Report
from vera.results.serializers import ResultSerializer as VeraResultSerializer
from vera.series.serializers impor... |
"""
Copyright 2022 IBM Corporation All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
"""
# pylint: disable=global-statement,global-variable-not-assigned,invalid-name
from flask import Flask, Response, jsonify, request
app = Flask(__name__)
DEFAULT_ROOT_CONFIGS = {
"start_search": {"status_code": 200},
... |
# file: mean_deviation.py
# vim:fileencoding=utf-8:fdm=marker:ft=python
#
# Copyright © 2018 R.F. Smith <rsmith@xs4all.nl>.
# SPDX-License-Identifier: MIT
# Created: 2018-04-21T19:07:27+0200
# Last modified: 2019-07-13T10:16:34+0200
"""
Calculate the mean deviation of samples.
See http://www.leeds.ac.uk/educol/documen... |
from tkinter import ttk
class Treeview(ttk.Treeview):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.heading("#0", text="Versions")
@property
def selected_item(self):
return self.item(self.selection())
def clean(self):
children = sel... |
from Board import Board
from Ship import Ship
from SimulationResult import SimulationResult
from SimulationStatistics import SimulationStatistics
import functionalComponents
import random, copy
#Represents a game of battleship. Using a board of set ships, the engine will attempt to compute positions of the ships in ... |
import abc
import pdb
from time import time
import helpers.vcommon as CM
from helpers.miscs import Miscs, MP
import settings
import data.prog
import data.symstates
import infer.inv
DBG = pdb.set_trace
mlog = CM.getLogger(__name__, settings.LOGGER_LEVEL)
class _Infer(metaclass=abc.ABCMeta):
"""
Base class ... |
"""
:CRAPS又称花旗骰,是美国拉斯维加斯非常受欢迎的一种的桌上赌博游戏。
Craps赌 博游戏
玩家摇 两颗色子 如果第一次摇出7点或11点 玩家胜
如果摇 出2点 3点 12点 庄家胜 其他情况游戏继续
玩家再次要色子 如果摇出7点 庄家胜
如果摇 出第一次摇的点数 玩家胜
否则 游戏继续 玩家继续摇色子
玩家进入游戏时 有1000元的赌 注 全部输 光游戏 结束
"""
from random import randint
money = 1000
while money > 0:
print('你的总资产为:', money)
needs_go_on = False
while True:
... |
# Generated by Django 3.0.5 on 2020-05-12 10:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('project_core', '0118_calls_need_to_be_part_of_a_funding_instrument'),
('grant_management', '0029_signed_by_multiple_people'),
]
operations =... |
# Copyright 2018 Twitter, Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
""" This module contains the main program for Caladrius and will set up all
resources and start the API server """
import os
import sys
import logging
import argparse
from typing import Dict, ... |
from PySide2.QtCore import QUrl, QDir
from PySide2.QtWebEngineWidgets import QWebEngineView
import sys
from HandSimServer import *
sys.path.append('./handsim')
def create_hand_sim_widget(parent=None):
sim_in_new_thread()
view = QWebEngineView(parent)
view.setUrl(QUrl.fromLocalFile(QDir.currentPath() + "/... |
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect, get_object_or_404
from django.views.decorators.http import require_POST
from django.views.decorators.csrf import csrf_protect
from bookstore.models import Book
from .cart import Cart
from .forms import CartAddProduc... |
from django.contrib import admin
from .models import Post, Comment, LikeModel, Follow
# Register your models here.
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
list_display = ('user', 'picture', 'context')
@admin.register(Comment)
class CommentAdmin(admin.ModelAdmin):
list_display = ('post', 'us... |
from json import dump, load
import click
from giveaway.core.typing import UserName
from giveaway.core.usernames import (
filter_usernames,
prepare_username,
process_usernames,
)
from giveaway.core.winner import (
choose_winners,
find_winners,
verify_winner,
hash_username,
get_date_from... |
import torch
import shutil
import numpy as np
import matplotlib
matplotlib.use('pdf')
import matplotlib.pyplot as plt
# import cv2
from skimage.transform import resize
import torchvision.transforms as transforms
from sklearn.metrics import precision_score, recall_score, f1_score, roc_auc_score
class AverageMeter(obje... |
from termcolor import cprint, colored
from random import randint
from time import sleep
cprint('Printo para jogar Pedra Papel Tesoura com o computador?', 'yellow')
a = colored('-=-' * 20, 'cyan')
print(a)
p1 = str(input(colored('Pedra, Papel... Tesoura! (escreve o que queres jogar) ', 'magenta',))).strip().lower()
prin... |
from augustine_text.sample_text import words
# 75K words of procedurally generated text
# This is about the length of novel.
text = words(75000)
text_length = len(text)
print(text[:100])
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# hello-world.py
# MIT License
# Copyright (c) <2021> <stephen.stengel@cwu.edu>
# This is a test program using glade and gtk through pygobject
#TODO: Figure out why it goes transparent every two color flashes.
# I've found that both gnome-terminal and byobu terminal ... |
from datetime import datetime, timedelta
from jinja2 import Template as JinjaTemplate
from typing import Any, Callable, Dict, Tuple, Union
from homeassistant.core import Event, HomeAssistant, callback
from homeassistant.exceptions import TemplateError
from homeassistant.helpers.event import TrackTemplate, TrackTemplat... |
#! /usr/bin/env python
from __future__ import print_function
import sys
from Bio import SeqIO
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(description='convert embl to genbank.')
parser.add_argument('infile', nargs='?', type=argparse.FileType('rU'), default=sys.stdin)
par... |
import os
from typing import Tuple
import cyvcf2
from django.conf import settings
from django.contrib.auth.models import User
from django.test import TestCase
from snpdb.models import ImportSource, Sequence, md5sum_str
from upload.models import UploadedFile, UploadPipeline, UploadedVCF, UploadStep, UploadedFileTypes
... |
#!/usr/bin/python3
from telnetlib import Telnet
from re import findall
from time import sleep, time
from os import environ
from influxdb import InfluxDBClient
ROUTER = environ["ROUTER_IP_ADDRESS"]
USER = environ["ROUTER_LOGIN_USER"]
PASSWORD = environ["ROUTER_LOGIN_PASSWORD"]
PROMPT = environ["ROUTER_PROMPT"]
DB_NAME... |
"""
==================
Errorbar Subsample
==================
Demo for the errorevery keyword to show data full accuracy data plots with
few errorbars.
"""
import numpy as np
import matplotlib.pyplot as plt
# example data
x = np.arange(0.1, 4, 0.1)
y1 = np.exp(-1.0 * x)
y2 = np.exp(-0.5 * x)
# example variable error... |
import math
import numpy as np
from typing import Any, List
from util import common_values
from util.game_state import GameState
from util.physics_object import PhysicsObject
from util.player_data import PlayerData
class CustomObs:
POS_STD = 2300
ANG_STD = math.pi
def __init__(self, cars):
super... |
import os
import unittest
import doto
d0 = doto.connect_d0()
class TestConfig(unittest.TestCase):
def test_get_all_droplets(self):
self.assertEqual(d0.get_all_droplets(status_check=True),200)
self.assertEqual(d0.get_sizes(status_check=True),200)
self.assertEqual(d0.get_images(status_chec... |
from collections import OrderedDict
from ..util import create_element
from .common import EWSAccountService, create_folder_ids_element
class EmptyFolder(EWSAccountService):
"""
MSDN: https://docs.microsoft.com/en-us/exchange/client-developer/web-service-reference/emptyfolder
"""
SERVICE_NAME = 'Empty... |
import re
from nonebot.typing import T_State
from nonebot.permission import SUPERUSER
from nonebot.adapters.onebot.v11 import Bot, MessageEvent, GroupMessageEvent
from nonebot_plugin_guild_patch import GuildMessageEvent
from nonebot.adapters.onebot.v11.permission import GROUP_OWNER, GROUP_ADMIN
from .data_source impo... |
import torch
import dsntnn
def gaze_loss(targets, masks, targets_start_from, masks_start_from, coords, heatmaps, probabilities, slice_ind,
interpolate_coordinates):
gaze_targets = targets[targets_start_from:targets_start_from + 16*interpolate_coordinates, :].transpose(1, 0).reshape(-1, 8*interpolate... |
# Django modules.
from django.urls import reverse
from django.test import TestCase, Client
# !Triplinker modules:
# Another apps modules.
from accounts.models.TLAccount_frequest import TLAccount
from trip_places.models import Place
# Current app modules.
from .models import Journey, Participant
class TestJourneysV... |
from dataclasses import dataclass, field
@dataclass
class DeliveryFailure():
pass
@dataclass
class SendFailure():
pass
def send(to=None, cc=None, bcc=None, from_address="no-reply", from_name=None, subject=None, text=None, html=None,
attachments=None, inline_attachments=None):
"""Send an email... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 7 06:34:16 2021
@author: ayman
"""
import torch
import torch.nn.functional as F
import numpy as np
class A3CGruAgent:
"""
Actor critic agent that returns action It applies softmax by default.
"""
def __init__(self, model, env, f... |
from flask import Blueprint
bp = Blueprint("profiler", __name__)
from wlanpi_webui.profiler import profiler
|
def kth_element(arr, M, K):
"""
Given an array arr[] of size N and two integers M and K, the task is to find the array element at the Kth index after performing
following M operations on the given array.
In a single operation, a new array is formed whose elements have the Bitwise XOR values of the adj... |
#예제 확장...
str28 = "900123-1234567"
print(str28[7:8])
print("홍길동은 "+str28[0:2]+"년 "+str28[2:4]+"월 "+str28[4:6]+"일 생이다")
myCitizenCode = input("주민번호를 입력하세요: ")
print("\n당신은 "+myCitizenCode[0:2]+"년 "+myCitizenCode[2:4]+"월 "+myCitizenCode[4:6]+"일 생이다")
|
import json
import uuid
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
class VaultTest(APITestCase):
def test_generate_uuid(self):
"""
Tests that a new UUID is generated and returns previously
created generated UUIDs.
... |
from pythonds.basic.deque import Deque
def palchecker(a_string):
chardeque = Deque()
for ch in a_string:
chardeque.addRear(ch)
stillEqual = True
while chardeque.size() > 1 and stillEqual:
first = chardeque.removeFront()
last = chardeque.removeRear()
if first != last:... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""The command line interface for calling pyRVT.
See :doc:`usage` for more details.
"""
import argparse
from . import __version__
from .tools import operation_psa2fa, operation_fa2psa
from .motions import DEFAULT_CALC
parser = argparse.ArgumentParser(
prog='pyrvt',
... |
from tenacity import retry, stop_after_delay
@retry(stop=stop_after_delay(10))
def stop_after_delay_test():
print('retry')
raise Exception
stop_after_delay_test()
"""
retry
retry
~~~~~
10秒後に止まる
"""
|
# -*- coding: utf-8 -*-
from django import forms
from djspace.core.models import BIRTH_YEAR_CHOICES
from djspace.core.models import DISABILITY_CHOICES
from djspace.core.models import REG_TYPE
from djspace.core.models import GenericChoice
from djspace.core.models import UserProfile
from djtools.fields import BINARY_CHO... |
"""Chapter 1: Question 8.
Check if string 1 is a rotation of string 2.
"""
def is_rotation_slicing(s1, s2):
"""Uses slicing."""
if not s1:
return False
n = len(s1)
if n != len(s2):
return False
for i in range(n):
if s1[i:n] + s1[0:i] == s2:
return True
r... |
# -*- coding: utf-8 -*-
from __future__ import division
import numpy as np
__all__ = ['cabbeling', # TODO
'isopycnal_slope_ratio', # TODO
'isopycnal_vs_ntp_CT_ratio', # TODO
'ntp_pt_vs_CT_ratio', # TODO
'thermobaric'] # TODO
def cabbeling():
pass
def isopycnal... |
f = open("flash_data.h", "w")
print("const uint32_t flash_data[] = {", file=f)
for i in range(256):
print(" %d," % i, file=f)
print("};", file=f)
|
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available.
Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in co... |
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 29 13:37:49 2016
@author: alex
"""
|
# encoding: utf-8
from bs4 import BeautifulSoup
from okscraper.base import BaseScraper
from okscraper.sources import UrlSource, ScraperSource
from okscraper.storages import ListStorage, DictStorage
from lobbyists.models import LobbyistHistory, Lobbyist, LobbyistData, LobbyistRepresent, LobbyistRepresentData
from perso... |
from ownership import server
from ownership.models import Owners
import unittest
import json
import mock
import uuid
#Set up test models
test_owner1 = Owners()
test_owner1.lrid = 'a8098c1a-f86e-11da-bd1a-00112444be1e'
test_owner1.owner_index = 1
test_owner2 = Owners()
test_owner2.lrid = 'd7cd9904-2f84-11e4-b2e1-0800... |
import torch
import torch.nn as nn
class ARModelBase(nn.Module):
def __init__(self, encoder, decoder, discriminator, lambda_auto=1.0, lambda_adv=1.0, lambda_cross=1.0):
super().__init__()
self.bos_ix = encoder.src_embedder.get_bos_ix()
self.eos_ix = encoder.src_embedder.get_eos_ix()
... |
import numpy as np
from numpy import array
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_context("poster")
sns.set(rc={'figure.figsize': (8, 6.)})
sns.set_style("whitegrid")
def target(training, test, valid):
plt.figure()
plt.title('Target function performance training vs validation data')
... |
print('DIVISÃO EM PYTHON\n')
try:
a = int(input('Numerador: '))
b = int(input('Denominador: '))
r = a / b
except (ValueError, TypeError) as erro1:
print(f'Ocorreu um erro com os valores que introduziu.')
except ZeroDivisionError as erro2:
print('Não é possível dividir por 0.')
except KeyboardInterr... |
import turtle as t
import random
#---------------------------------------#
# SCREEN SETUP #
#---------------------------------------#
width = 10
height = 5
t.setup(width*100+20,height*100+20)
screen = t.Screen()
screen.title("Captain Planet")
screen.screensize(width*100,height*100)
right = 1... |
'''
Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.
Note:
Given target value is a floating point.
You are guaranteed to have only one unique value in the BST that is closest to the target.
Example:
Input: root = [4,2,5,1,3], target = 3.714286... |
from header import *
from .utils import *
from .util_func import *
class BERTDualInferenceContextDataset(Dataset):
def __init__(self, vocab, path, **args):
self.args = args
self.vocab = vocab
self.vocab.add_tokens(['[EOS]'])
self.pad = self.vocab.convert_tokens_to_ids('[PAD]')
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.