text stringlengths 38 1.54M |
|---|
#!/usr/bin/python3
import csv
import datetime
import glob
import json
import os.path
from statistics import mean
import sys
from zoneinfo import ZoneInfo
def needs_update(srcfn, destfn):
if not os.path.exists(destfn):
return True
src_mtime = os.path.getmtime(srcfn) if srcfn is not None else os.path.ge... |
import torch.nn as nn
from models.unet.parts import DoubleConv, Down, Up
class UNet(nn.Module):
'''
Architecture based on U-Net: Convolutional Networks for Biomedical Image Segmentation
Link - https://arxiv.org/abs/1505.04597
Parameters:
num_classes (int) - Number of output classes required ... |
#!/usr/bin/python3
# coding: utf-8
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
def cliquer( bouton ) :
print( 'clic' )
print( 'Bouton> '+ str( bouton ) )
#win = Gtk.Window( title = 'Foody' )
win = Gtk.Window( title = 'Foody' )
win.set_title( 'Foody' )
print( dir( win ) )
win.connec... |
# Pascal's triangle
import sys, getopt
# input args
opts, args = getopt.getopt(sys.argv[1:], "no")
#flag -n:True -o:False
flag = True
for op ,value in opts:
if op == "-n":
flag = True
elif op == "-o":
flag = False
else:
print('unknown options')
exit()
def pascal_triangle... |
#Program Untuk Menghitung berapa kali pengisian bahan bakar di sebuah perjalanan
import math
jarakTotal=795
print('Jarak yang akan ditempuh Pak Budi adalah sejauh 795 km'+ '\n')
jarakPerLiter=12
print('Untuk 1liter mobil, mobil pak Budi bisa menempuh jarak 12 km'+'\n')
kapasitasTanki=50
print('kapasitas tanki mobil... |
# Databricks notebook source
# MAGIC %run ./_includes/setup
# COMMAND ----------
# MAGIC %run ./_includes/paths
# COMMAND ----------
# MAGIC %run ./_includes/src
# COMMAND ----------
# MAGIC %md extract
# COMMAND ----------
from glob import glob
import os
if not os.path.exists(f"/dbfs/{source_data_dir}"):
... |
class NotFoundError(Exception):
def __init__(self, resource, resource_id):
Exception.__init__(self)
self.resource = resource
self.resource_id = resource_id
class PokemonNotFoundError(NotFoundError):
def __init__(self, resource_id):
NotFoundError.__init__(self, "Pokemon", resour... |
from util.db_helper import session
from model.user import User
from flask import current_app
class UserDao(object):
def get_all(self):
return session.query(User)
def insert(self, user):
session.add(user)
session.commit()
def select_by_name(self, name):
sql = session.quer... |
import sys
from pysim.PySim import *
from basic_skills.action import *
from basic_skills.move_to import *
from basic_skills.helper_functions import *
import numpy as np
import math
'''
moves around the ball so that it faces target_loc
'''
class OrbitBall(MoveTo):
def __init__(self, game, target_loc = False, offset ... |
# Print the first hedgehog.
# Finish off the rest of the image. See the instructions to the right.
print(" .|||||||||.")
print(" |||||||||||||")
print(" /. `|||||||||||")
print(" o__,_||||||||||'")
# Wait for the user to press enter.
# Type the code below.
input('Press [Enter] to fuzz')
print("")
# Print the... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function # for python 2 and stderr
from __version__ import version
import os
import sys
import getopt
from subprocess import check_output, call
# TODO use GitPython once it is compatible with python3
# instead of calling git(3)
program_name =... |
# examples of using the helping methods
from helping_methods import scores_to_emotions
# dummy data ( we get if from the emotions API)
emotion_scores={"anger":0,"disgust":0,"fear":0,"joy":0.13447999002654,"sadness":0.022660050917593,"surprise":0.0087308825457527}
#no normalizations
emojies = scores_to_emotions(emotio... |
def isvowel(char):
all_vowels = 'a','e','i','o','u'
return char in all_vowels
print(isvowel('a'))
print(isvowel('c'))
|
from django.db import models
# Create your models here.
from django.db import models
class Tag(models.Model):
name = models.CharField(max_length=200,null=True)
def __str__(self):
return str(self.name)
class Note(models.Model):
title = models.CharField(max_length=200, null=True)
content=mo... |
#!/usr/bin/env python3
import socket
import sys
HOST = "0.0.0.0"
PORT = int(sys.argv[1])
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((HOST, PORT))
while True:
data, addr = sock.recvfrom(2048)
print("received message:", data.decode())
|
from django.contrib.auth.models import User
from main.models import Profile
class Signup:
def __init__(self, data):
self.login = data['login']
self.password = data['password']
self.password_repeat = data['passwordRepeat']
def validate(self):
if not self.login or not self.password or not self.password_repe... |
from django.test import TestCase
from django.core.urlresolvers import resolve
from lists.views import home_page
from django.http import HttpRequest
from django.template.loader import render_to_string
from django.conf import settings
if not settings.configured:
settings.configure()
from lists.models import Item
class... |
#!/usr/bin/env python3
# coding:utf-8
# Author:Lee
# 2020/4/28 19:05
"""
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
思路:
先判断一下哪个链表长,然后用交换的方法确保一定是l1更长
然后把l2的值加... |
# encoding= utf-8
def add_key(value):
value.add(11)
return value
if __name__ == '__main__':
setValue=set([1,',cd','cdw',1])
print(setValue)
print(add_key(setValue)) |
# Generated by Django 3.2.7 on 2021-09-25 00:49
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('survey_api', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='survey',
... |
""" Core definition of a Thermo Document """
from collections import defaultdict
from typing import Dict, List, Union
from datetime import datetime
from pydantic import BaseModel, Field
from pymatgen.analysis.phase_diagram import PhaseDiagram
from pymatgen.entries.computed_entries import ComputedEntry, ComputedStructu... |
#_*_ coding: utf-8 _*_
from sqlalchemy import create_engine, MetaData
from sqlalchemy import (Table, Column, String, BigInteger,
Boolean, DateTime)
from sqlalchemy.sql import func, select, exists
from sqlalchemy.exc import IntegrityError
metadata = MetaData()
items = Table('items', metadata... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
:copyright:
Lion Krischer (krischer@geophysik.uni-muenchen.de), 2013-2014
:license:
BSD 3-Clause ("BSD New" or "BSD Simplified")
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import glob
import ... |
import problem
import random
class Genetic:
def __init__(self):
self.chromosomes = 10
self.DNACount = 6
self.Maxgeneration = 30
self.currentGen = 0
self.mutationRate = .4
self.crossoverRate = .3
self.chromosomesList = []
self.fitness = []
sel... |
try:
from pathos.multiprocessing import ProcessingPool as Pool
except ImportError:
from multiprocessing import Pool
import logging
logging.getLogger(__name__).addHandler(logging.NullHandler())
logger = logging.getLogger()
# Note : Using pathos multiprocessing which leverages dill over standard
# pickle, whic... |
import cil
logo = cil.read_image('codeit_logo')
text = cil.read_image('codeit_text')
print('코드잇 로고:')
# logo를 디스플래이해 주세요
cil.utils.display(logo)
print('\n코드잇 텍스트:')
# text를 디스플래이해 주세요
cil.utils.display(text)
### 코드를 작성해 주세요 ###
# text를 색상 반전해서 inverted_text에 저장해 주세요
inverted_text = cil.processing.invert(text)
# logo... |
# -*- coding: UTF-8 -*-
import sys
import socket
import json
import yaml
import abc
from colored import fg, attr
from pymongo import MongoClient
class BaseServer(object, metaclass = abc.ABCMeta):
def __init__(self, IP: str, port: int):
with open('./config/server_config.yml') as config_file:
self._server_co... |
i = None
o = None
from collections import OrderedDict
import logging
import helpers.logger as log_system
logger_alias_map = (("root","Main launcher"),
("input.input","Input system"),
("apps.app_manager","App manager"),
("context_manager","Context manager"),... |
"""upgrade file size types
Revision ID: 90bf491700cb
Revises: e694fb270acb
Create Date: 2022-01-12 16:14:01.280566
"""
from alembic import op
from sqlalchemy import BigInteger, Integer
# revision identifiers, used by Alembic.
revision = "90bf491700cb"
down_revision = "e694fb270acb"
branch_labels = None
depends_on = ... |
import pytest
def tdd_root_health(fresh_anonymous_client):
"""
GIVEN: an initialized app fresh_anonymous_client
WHEN: the /health/ route is requested
THEN: the response.status_code is 200
THEN: the return data is 'Healthy
"""
response = fresh_anonymous_client.get('/health/')
assert res... |
cont = dict()
cont['A'] = cont['B'] = cont['C'] = '2'
cont['D'] = cont['E'] = cont['F'] = '3'
cont['G'] = cont['H'] = cont['I'] = '4'
cont['J'] = cont['K'] = cont['L'] = '5'
cont['M'] = cont['N'] = cont['O'] = '6'
cont['p'] = cont['Q'] = cont['R'] = cont['S'] = '7'
cont['T'] = cont['U'] = cont['V'] = '8'
cont... |
# from evaluation import evaluate_policy, collectEpisode
#
# __all__ = ["evaluate_policy", "collectEpisode"]
|
import json
import logging
import boto3
from .exceptions import InvalidMessageError
from .threading_utils import Interval
# -----------------------------------------------------------------------------
def _jsonify_dictionary(dictionary):
return {k: json.dumps(v) for k, v in dictionary.items()}
logger = logg... |
import datetime
import dateutil.parser
import dateutil.tz
import requests
import simplejson as json
import os
class OSClient(object):
""" Base class for querying the OpenStack API endpoints.
It uses the Keystone service catalog to discover the API endpoints.
"""
EXPIRATION_TOKEN_DELTA = datetime.time... |
# coding: utf-8
from sqlalchemy import Column, ForeignKey, Integer, Text
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
metadata = Base.metadata
class Engine(Base):
__tablename__ = 'engines'
engine = Column(Text, primary_key=True)
... |
from __future__ import print_function
from functools import wraps
import math
import sys
from time import time
# Setup cython modules
import pyximport; pyximport.install()
import cyexpdecay
rng = xrange if sys.version_info.major < 3 else range
i = 1000000
def fixlen(s, maxlen=16):
if len(s) > maxlen:
ss... |
__all__ = [
'Namespace',
'SubcommandHelpFormatter',
'UsageHelpFormatter',
'create_parser_dry_run',
'create_parser_filter_dates',
'create_parser_local',
'create_parser_logging',
'create_parser_meta',
'create_parser_yes',
'custom_path',
'merge_defaults',
'parse_args'
]
import argparse
import os
from pathlib ... |
#!/usr/local/bin/python
from optparse import OptionParser
import os, errno
options = {}
classes = []
def main():
usage = "usage: %prog [options] ops_dir data_dir impls_dir(s)"
parser = OptionParser(usage)
parser.add_option("-v", "--verbose", action="store_true", dest="verbose")
(opts, args) = parse... |
from turtle import Screen, Turtle # module and class import
import time
from snake import Snake
from food import Food
from scoreboard import Scoreboard
screen = Screen()
screen.setup(width = 600, height= 600)
screen.tracer(0)
screen.bgcolor("black")
screen.title("My Snake Game")
snake = Snake()
food = ... |
class Addition:
def add(self,num1,num2):
self.num1=num1
self.num2=num2
print("sum:",self.num1+self.num2)
a1=Addition()
a=int(input("enter num1"))
b=int(input("enter num2"))
a1.add(a,b) |
#Divide Array in Sets of K Consecutive Numbers
from collections import defaultdict
def printDict(myDict):
for i in myDict.keys():
print str(i)+" : "+str(myDict[i])
def isPossibleDivide(nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
myDict = defaultdict()
... |
import matplotlib.cm as cm
import tensorflow as tf
import keras.backend as K
import numpy as np
import numpy.ma as ma
import pylab as pl
import os
#import tensorflow.compat.v1 as tf
#tf.disable_v2_behavior()
#from tf.keras.models import model_from_json
from keras.models import model_from_json
from mpl_toolkits.axes_g... |
def function_name_two(arguement):
if arguement == 3:
print('Yes')
else:
print('No')
a = 1
b = 2
c = a + b
function_name_two(c)
|
from wtforms.validators import ValidationError
from api.constants import CurrencyNames
def amount_length_check(form, field):
currency = form.currency.data
amount_data = field.data
if currency == CurrencyNames.RUB.value:
if amount_data < 10.0 or amount_data > 1000000.0:
raise Validat... |
import datapackage
import pandas as pd
data_url = 'https://datahub.io/core/nasdaq-listings/datapackage.json'
# to load Data Package into storage
package = datapackage.Package(data_url)
# to load only tabular data
resources = package.resources
c=0
for resource in resources:
if resource.tabular:
... |
import numpy as np
from random import shuffle
from past.builtins import xrange
def softmax_loss_naive(W, X, y, reg):
"""
Softmax loss function, naive implementation (with loops)
Inputs have dimension D, there are C classes, and we operate on minibatches
of N examples.
Inputs:
- W: A numpy array of shape ... |
#!/usr/bin/env python2
'''
Simple Parallel Concurrency script to
get beautiful soup objects from response get
objects
READS: cPickle list of of url: response tuple pairs
WRITES: cPickle list of of url: cleanedtext pairs
OUT: None
'''
from bs4 import BeautifulSoup
import cPickle
import html5lib
fr... |
import unittest
from pyramid import testing
import transaction
from apex.models import AuthUser, AuthID
from piktio.models import (DBSession,
PiktioProfile,
Subject,
Predicate,
Game,
... |
#!/usr/bin/env python3
#
# Copyright (C) 2017-2018 Alpha Griffin
# @%@~LICENSE~@%@
"""Alpha Griffin Python setuptools build script.
@author lannocc
@see https://packaging.python.org/en/latest/distributing.html
@see https://github.com/pypa/sampleproject
Some of this script logic also taken from:
https:... |
# -*- coding: utf-8 -*-
from model.group import Group
import random
def test_delete_group(app):
if app.group.count() == 0:
app.group.create(Group("test"))
old_groups = app.group.get_group_list()
index = random.randrange(len(old_groups))
app.group.delete_random_group(index)
new_groups = app.... |
# _____ ______ _____
# / ____/ /\ | ____ | __ \
# | | / \ | |__ | |__) | Caer - Modern Computer Vision
# | | / /\ \ | __| | _ / Languages: Python, C, C++
# | |___ / ____ \ | |____ | | \ \ http://github.com/jasmcaus/caer
# \_____\/_/ \_ \______ |_| \_\
# Licensed ... |
# Copyright (c) 2019-2023, Manfred Moitzi
# License: MIT License
from __future__ import annotations
from typing import TYPE_CHECKING, Optional
import logging
from ezdxf.lldxf import validator
from ezdxf.lldxf.attributes import (
DXFAttr,
DXFAttributes,
DefSubclass,
RETURN_DEFAULT,
group_code_mappin... |
import os
import tensorflow as tf
import numpy as np
from tqdm import tqdm
import random
from utility import tf_utility as ut
def gather_features(data, feature_mask):
mask = np.zeros(np.shape(data)[-1], dtype= bool)
for i in range(len(mask)):
if i in feature_mask:
mask[i] = True
e... |
#!python3
# Author: Theodor Giles
# Created: 7/14/20
# Last Edited 8/3/20
# Description:
# This program manages the commands/movement/physical control of the RoboSub
#
import time
import pyfirmata
import math
board = pyfirmata.ArduinoMega('/dev/ttyACM0')
# ROBOSUB
class MovementCommander:
# initialize everythi... |
from office365.sharepoint.client_context import ClientContext
from tests import test_client_credentials, test_team_site_url
ctx = ClientContext(test_team_site_url).with_credentials(test_client_credentials)
target_list = ctx.web.lists.get_by_title("Tasks")
target_field = target_list.fields.get_by_internal_name_or_titl... |
#3.1.2.5 Loops in Python | for
# for range 1 parameter -> jumlah perulangan
for i in range(10) :
print("perulangan ke",i)
print()
# for range 2 parameter -> angka awal perulangan, angka akhir perulangan
a = 1
for i in range(3,10) :
print(i," = perulangan ke",a)
a+=1
print()
# for range 3 parameter ->... |
#! /usr/bin/env python
'''
Created on Jul 27, 2011
@author: jklo
'''
import time
import random
import argparse
import csv
import sys
class RandomDateRangeGenerator():
def __init__(self, start, end, gran="second"):
if gran == "second":
self.format = "%Y-%m-%dT%H:%M:%SZ"
elif gr... |
from .model import Model
from sklearn.metrics import accuracy_score, precision_score, recall_score, \
mean_absolute_error, mean_squared_error
from datetime import datetime
import pandas as pd
import torch
import time
from torch.utils.data import Dataset, DataLoader
import torch.nn.functional as F
class RatingsData... |
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 6 11:57:27 2019
@author: jjnun
"""
from __future__ import division
import numpy as np
from scipy.spatial.distance import cdist
from icd9 import ICD9
from pathlib import Path
import re
from embed_helpers import generate_overlapping_sets_cui
from cui_icd9_helpers import g... |
from flask import Blueprint
# Import all the view function
from app.modules.core.views import hello
# Define the blueprint name
module = Blueprint('core', __name__)
module.add_url_rule('/', view_func=hello)
|
from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
is_offer: Optional[bool] = None
@app.get("/")
def index():
return {"Hello": "World"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: Op... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-01-16 17:29
from __future__ import unicode_literals
import b24online.custom
import b24online.models
import b24online.utils
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
... |
import discord
import asyncio
import logging
import datetime
from pprint import pprint
from copy import deepcopy
import demobot.client.getkey as _getkey
import demobot.handlers
logger = logging.getLogger('discord')
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler(filename='data/discord.log', encoding='utf... |
#coding=utf-8
'''
Created on 2017��2��14��
@author: zhao
'''
import os
module_name=raw_input("enter module name")
print "attributes: ",dir(module_name)
with open(module_name):
pwd=os.getcwdu()
path_list=os.listdir(pwd)
for i in path_list:
print dir(i),i.__class__,i |
# -*- coding: utf-8 -*-
# Description:
# Created: Fengchong 2020/09/18
import json
import pandas as pd
import pymysql
from config import LocalConfig
import numpy as np
def get_DataFrame(db_name, cursor:pymysql.cursors.Cursor):
sql = "select * from " + db_name
cursor.execute(sql)
data = cursor.fetchall()
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 17-6-21 上午10:52
# @Author : sadscv
# @File : q303_RangeSumQuery.py
class NumArray(object):
def __init__(self, nums):
"""
:type nums: List[int]
"""
self.nums = nums
def sumRange(self, i, j):
"""
:type... |
from os import environ
environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
from eval_utils import setup_args
from train_utils import load_configs, build_model
import tensorflow as tf
args = setup_args()
config = load_configs(args.path)
def generate_text(model, prime):
# Evaluation step (generating text using the learned model... |
# -*- coding: utf-8 -*-
"""
Composition of two function g(x) and f(x) as g(f(x)).
g(x) should be DA vector(s). f(x) could be float(s) or DA vector(s).
"""
import tpsa
tpsa.da_init(4,2,100)
da = tpsa.base()
print("g(f(x)) with f(x) floats: ")
x=tpsa.assign(2)
x[0] = 1 + da[0] + 2*da[1]
x[1] = 0.5 + 3*d... |
#!/usr/bin/env python
import rospy
from std_msgs.msg import String
from bebop_msgs_msg import Ardrone3GPSStateNumberOfSatelliteChanged
from bebop_msgs.msg import Ardrone3PilotingStatePositionChanged
is_satellite_check = False
first_latitude = 0.0
first_longitude = 0.0
def cbSatelliteNumCheck(msg):
n = msg.number... |
import sys
import time
from datetime import datetime
import mysql.connector
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
def SendEmail(msgText):
import smtplib
import ssl
from email.mime.multipart import MIMEMult... |
# pylint: skip-file
# -*- coding: utf-8 -*-
# Learn more: https://github.com/kennethreitz/setup.py
from setuptools import setup, find_packages
with open('README.md') as f:
readme = f.read()
with open('LICENSE') as f:
license = f.read()
with open('requirements.txt') as f:
requirements = f.read()
setup(... |
import numpy
import pandas
from scipy.optimize import minimize
from scipy.stats import norm
from scipy.stats import chi2
from plotnine import *
def linear(p, obs):
B0 = p[0]
B1 = p[1]
sigma = p[2]
expected = B0 + (B1 * obs.mutation)
nll = -1 * norm(expected, sigma).logpdf(obs.ponzr1Counts).sum... |
fname = input("Enter file name: ")
fh = open(fname)
lst = list()
sp=list()
for line in fh:
x=line.rstrip()
sp=x.split()
for z in sp:
if z in lst:
continue
else:
lst.append(z)
lst.sort()
print(lst) |
import random
import numpy as np
import networkx as nx
import scipy as sp
import csv
from sklearn.metrics import roc_auc_score
# References for code
# http://docs.scipy.org/doc/scipy/reference/generated/scipy.io.loadmat.html # to read matlab file
# https://networkx.github.io/documentation/latest/reference/classes.gr... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.11 on 2018-05-06 13:48
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('apkstore', '0023_auto_20180503_2331'),
]
operations = [
migrations.AddFiel... |
"""
Optional:
This script visualizes genre and decade based statistics and saves them as .png files.
"""
import os
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use("seaborn-whitegrid")
META_DIR = "XXX\filmgenre_classification\3_metadata"
GENRE_DIR = "XXX\filmgenre_classification\3_metadata\genre_ba... |
## -*- coding: utf-8 -*-
#""" Python KNX framework
#License
#=======
# - B{PyKNyX} (U{https://github.com/knxd/pyknyx}) is Copyright:
# - © 2016-2017 Matthias Urlichs
# - PyKNyX is a fork of pKNyX
# - © 2013-2015 Frédéric Mantegazza
#This program is free software; you can redistribute it and/or modify
#it under ... |
# 1. 内置的open函数打开文件有几种模式,它们的区别是什么?
'''
r 缺省的,表示只读打开
w 只写打开
x 创建并写入一个新文件
a 写入打开,如果文件存在,则追加
b 二进制模式
t 缺省的,文本模式
+ 读写打开一个文件,给原来只读、只写方式打开提供确实的读或者写的能力
'''
# 2. 使用base64解码“bWFnZWR1LmNvbQ==”,使用base64编码”magedu.com”,分别给出它们的解码和编码结果。
import base64
s1='bWFnZWR1LmNvbQ=='
base64_decrypt = base64.b64decode(s1.encode('utf-8'))
... |
import time
from datetime import datetime
import requests
from bs4 import BeautifulSoup
import pandas as pd
import json
from pprint import pprint
import sys
train_num = input('Enter your train number: ')
url = ('https://asm.transitdocs.com/api/trainDetail.php?year=2021&month=2&day=21&train='+ str(train_num... |
import pathlib
import tempfile
import os
import ray
from ray import workflow
from ray.workflow.storage import set_global_storage
_GLOBAL_MARK_FILE = pathlib.Path(tempfile.gettempdir()) / "__workflow_test"
def unset_global_mark():
if _GLOBAL_MARK_FILE.exists():
_GLOBAL_MARK_FILE.unlink()
def set_global_... |
from ._alertController import *
from ._tokenController import *
from ._subscriptionController import *
from ._Alerter import *
|
#!/usr/bin/python
import argparse
import time
import requests
import utilLCM as lcm
def setupArgs():
parser = argparse.ArgumentParser(description='Block template shell until LCM jobs are not in RUNNING/PENDING state.',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
... |
# -*- 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
import datetime
import os
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from .... |
from unittest import TestCase
import numpy as np
import auto_diff as ad
class TestGlorot(TestCase):
def test_glorot_normal(self):
weights = ad.inits.glorot_normal(shape=(3, 5))
self.assertEqual((3, 5), weights.shape)
weights = ad.inits.glorot_normal(shape=(300, 500))
weights = wei... |
#답을 구하는 순서
def find_sdokou_answer(Data1) :
Data2 = process.make_Data2(Data1)
Data3 = process.make_Data3(Data1)
col = process.make_stdset(Data1)
row = process.make_stdset(Data2)
box = process.make_stdset(Data3)
answer, setinfo, setlocation, listlocation = process.find_answer(Data1, col, row, box)... |
from rest_framework import viewsets
from rest_framework import permissions
from .serializers import Patient_TransferSerializer
from .models import Patient_Transfer
from django.shortcuts import render, get_object_or_404
class Patient_TransferViewSet(viewsets.ModelViewSet):
queryset = Patient_Transfer.objects.all()... |
'''print('Napisz coś.')
tekst = input()
print(f'Napisałeś: {tekst}')
imie = input('Jak masz na imie? ')
print(f'Witaj {imie} !!!')
'''
r = float(input('Podaj promień koła: '))
PI = 3.14
pole = PI*r**2
print(f'Pole koła o promieniu {r} wynosi {pole:.2f}') |
import discord
import asyncio
from resources import client
async def server_status_update_task():
while True:
await client.change_presence(
status=discord.Status.online,
activity=discord.Game(name=f"Active on {str(len(client.guilds))} servers"),
)
await asyncio.sle... |
import subprocess
import time
import optparse
def writeFuses(portName, lockFuses, eFuses, hFuses, lFuses):
"""
Attempt to write the fuses of the attached Atmega device.
"""
command = [
"./avrdude",
"-c", "avrisp",
"-p", "m32u4",
"-P", portName,
"-B", "200",
"-u",
"-U", "lock:w:%#02... |
from os import path, remove
from classes import placeholder
import numpy as np
# Define the current level. Used for loading input/save output paths
CCC_LEVEL = 2
INPUT_FILE = 5
# Input/Output file path
SCRIPT_PATH = path.dirname(path.abspath(__file__))
INPUT = f"{SCRIPT_PATH}/../inputs/level{CCC_LEVEL}_{INPUT_FILE}.i... |
import sys
import logging
from pprint import pprint
from LogHandler import LogHandler
import kiwoom.code_util as code_util
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, QTableWidget, QTableView, QTableWidgetItem
from PyQt5.QAxContainer import QAxWidget
from PyQt5.QtCore import QAbstractTableModel, QVa... |
"""
CHECK PERMUTATION (CCI 1.2)
Given two strings, write a method to decide if one is a permutation of the other.
Example:
Input = "race", "acre"
Output = True
NOTE: You ought to ask the interviewer for clarification on spaces, capitalization, text type (ASCII/Unicode), etc.
"""
# V... |
from http.server import BaseHTTPRequestHandler
from io import BytesIO
from typing import Optional
class HTTPRequest(BaseHTTPRequestHandler):
def __init__(self, request_text: bytes = b"") -> None:
self.rfile: BytesIO = BytesIO(request_text)
self.raw_requestline: bytes = self.rfile.readline()
... |
from re import *
pattern='[a-zA-Z0-9]' #checking for lower and upper case alphabets from a to z and also digits between 0 to 9
source="ab Zk@9c"
matcher=finditer(pattern,source)
count=0
for match in matcher:
print(match.start())
print(match.group())
count+=1
print("")
print(count) |
# B - Around Square
# https://atcoder.jp/contests/abc077/tasks/abc077_b
print(int(int(input())**0.5)**2) |
# -*- coding: utf-8 -*-
# @Author: Qilong Pan
# @Date: 2018-07-20 10:10:57
# @Last Modified by: Qilong Pan
# @Last Modified time: 2018-08-10 09:53:24
#
from __future__ import print_function
from game import Board,Game
from mcts_alphaZero import MCTSPlayer
class Human(object):
#player is human tag
def __init__(se... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from scipy import ndimage
def abrir_imagen(ruta):
"""Funcion que abre una imagen y devuelve su matriz"""
imagen = ndimage.imread(ruta)
return imagen
def is_num(text):
buffer = text
for char in ["-", ",", "."]:
buffer = ... |
from setuptools import setup
setup(
name='youtube-downloader-cli',
version='0.1.0',
description='This tool is used to parse and download the youtube videos.',
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Console',
'Intended Audience :: Developers',
'O... |
#!usr/bin/env python
# -*- coding:utf-8 -*-
from flask import Flask,render_template,request,redirect
from pager import Pagination
from urllib.parse import urlencode
import pymysql
import os
import re
app = Flask(__name__)
# 打开数据库连接
db = pymysql.connect("localhost","root","liao1977","liao" )
# 使用cursor()方法获取操... |
#!/usr/bin/env python3
# Copyright (c) 2012, Regents of the University of California
# 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 ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.