content stringlengths 5 1.05M |
|---|
execfile('<%= @tmp_dir %>/common.py')
# weblogic node params
WLHOME = '<%= @weblogic_home_dir %>'
JAVA_HOME = '<%= @java_home_dir %>'
WEBLOGIC_VERSION = '<%= @version %>'
# domain params
DOMAIN_PATH = '<%= @domain_dir %>'
DOMAIN = '<%= @domain_name %>'
APP_PATH = '<%= @app_d... |
import random
import sys
min = 1
max = 1000
if len(sys.argv) > 1 :
max = int(sys.argv[1])
number = random.randint(min, max)
print('I have selected a number between %d and %d' % (min, max))
print('Please try to guess my number.')
guess_count = 0
while True :
guess = input('Your guess: ')
try :
... |
import os
import unittest
from monty.json import MontyDecoder
from monty.serialization import loadfn
from robocrys.util import load_condensed_structure_json
class RobocrysTest(unittest.TestCase):
"""Base test class providing access to common test data. """
_module_dir = os.path.dirname(os.path.abspath(__fil... |
'''
Created on Jan. 24, 2018
@author Andrew Habib
'''
from statistics import mean
from collections import Counter
import os
from Util import load_parsed_ep, load_parsed_inf, load_parsed_sb, load_json_list, get_list_of_uniq_jsons
def display_min_max_avg_warnings_per_bug_total():
print("\nMin, Max, Avg (warni... |
from graphene_sqlalchemy import SQLAlchemyObjectType
import graphene
from ..database import db_session
from ..models import ModelFridge
from ..lib.utils import input_to_dictionary
from importlib import import_module
from flask_jwt_extended import jwt_required
class FridgeAttributes:
ingredient_id = graphene.List... |
while True:
try:
pilha = input()
correct = 1
par = 0
i = 0
while i < len(pilha) and correct:
if pilha[i] == '(':
par += 1
#print('1', i, par)
if pilha[i] == ')':
if par == 0:
correct = 0
#print('2', i, par)
else:
par -= 1
#print('3', i, par)
if i == len(pilha)-... |
import os
import logging
import argparse
from tqdm import tqdm
import torch
PAD_token = 1
SOS_token = 3
EOS_token = 2
UNK_token = 0
MODE = 'en'
data_version = 'init' # processed
if torch.cuda.is_available():
USE_CUDA = True
else:
USE_CUDA = False
MAX_LENGTH = 10
parser = argparse.ArgumentParser(descripti... |
DIMINISHING_BRIGHTNESS = 0.8
def run(led_wire, string_length, running_time, sleep_time, num_pulses, time_between_pulse, colour, staggered):
pass
## TODO
# start_time = time.time()
# if colour == "random":
# colour_list = [red, dim_orange, dim_yellow, dim_light_green,
# ... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/l... |
# -*- coding: utf-8 -*-
import copy
import os
import unittest
from mlcomp.utils import TemporaryDirectory
from mlcomp.report import (ReportSaver, ReportObject, Resource,
default_report_types, Report)
from .helper import to_config
class MyReportObject(ReportObject):
def __init__(self,... |
from operator import attrgetter
from ubuntui.utils import Padding
from ubuntui.widgets.hr import HR
from urwid import Columns, Text
from conjureup.app_config import app
from conjureup.ui.views.base import NEXT_SCREEN, BaseView
from conjureup.ui.widgets.selectors import CheckList
class AddonsView(BaseView):
titl... |
# Copyright (C) 2019 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Utils for manipulation with directories and files."""
import csv
import os
import time
from collections import defaultdict
from lib import constants
def wait_file_downloaded(
path_to_csv,
timeo... |
# /usr/bin/env python3.5
# -*- mode: python -*-
# =============================================================================
# @@-COPYRIGHT-START-@@
#
# Copyright (c) 2017-2020, Qualcomm Innovation Center, Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modifica... |
import os
import boto3
from boto3.dynamodb.conditions import Key
dynamodb = boto3.resource('dynamodb')
def put_atcoder_info(line_message_info):
TABLE = dynamodb.Table(os.environ["ATCODER_INFO_TABLE"])
for atcoder_id in line_message_info:
accepted_count = line_message_info[atcoder_id]["accepted_count"]... |
import struct
from logger import Logger
class ClRequestBase:
def __init__(self, payload):
self.message_id = struct.unpack("<B", payload[0:1])[0]
self.message_unique_id = struct.unpack("<H", payload[1:3])[0]
self.payload = payload
Logger.log("processing: " + type(self).__name__)
... |
from torch import nn
from torch.nn import functional as F
class QNet(nn.Module):
def __init__(self, input_channel=4, num_actions=18):
"""
Create a MLP Q network as described in DQN paper
"""
super(QNet, self).__init__()
self.conv1 = nn.Conv2d(input_channel, 32, kernel_size=8, stride=4)
self.conv2 = nn.Co... |
from typing import List, Callable
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import FunctionTransformer
from nlpretext.social.preprocess import (
remove_html_tags, remove_mentions, remove_emoji, remove_hashtag)
from nlpretext.basic.preprocess import normalize_whitespace, remove_eol_character... |
# produce list of genes in GRCm38
import pandas as pd
import json
# open refgene
refGeneFilename = '../gtex/gtex_mouse/refGene_mouse.txt'
refGene = pd.read_csv(refGeneFilename, sep="\t")
refGene.columns=['','name','chrom','strand','txStart','txEnd','cdsStart','cdsEnd','exonCount','exonStarts','exonEnds','id','name2','... |
import numpy as np
def run_env(
env,
episode_count=100,
n_samples_per_omega=100,
policy=None,
grid=False,
omega_min=0,
omega_max=10,
bins=100,
total_n_samples=500,
):
"""
Simple runner, takes an environment, run a random policy and records everything
"""
if not grid... |
# http header
API_URL = 'https://www.okex.com'
CONTENT_TYPE = 'Content-Type'
OK_ACCESS_KEY = 'OK-ACCESS-KEY'
OK_ACCESS_SIGN = 'OK-ACCESS-SIGN'
OK_ACCESS_TIMESTAMP = 'OK-ACCESS-TIMESTAMP'
OK_ACCESS_PASSPHRASE = 'OK-ACCESS-PASSPHRASE'
ACEEPT = 'Accept'
COOKIE = 'Cookie'
LOCALE = 'Locale='
APPLICATION_JSON = 'applica... |
from django.conf.urls import url
from .views import classify
from .views import delete_conversation
app_name = "classification"
urlpatterns = [
url(r"^classify/$", classify, name="classify"),
url(r"^delete/$", delete_conversation, name="delete"),
]
|
from django.urls import path
from user.views import CreateUserView
from user.views import CreateTokenView
from user.views import ManageUserView
app_name = 'user'
urlpatterns = [
path(
'create/',
CreateUserView.as_view(),
name='create',
),
path(
'token/',
CreateToke... |
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.template import loader
from django.core.mail import send_mail
class ContactForm(forms.Form):
subject = forms.CharField(label=_('Subject'), max_length=100)
message = forms.CharField(label=_('Message'), widget=forms.Text... |
from flask import Flask
from flask_cors import CORS
from .config import config
app = Flask(__name__)
app.secret_key = config['app']['secret_key']
dburi = 'postgresql://{username}:{password}@{host}:{port}/{database}'.format(**config['db'])
app.config.update(
{
'SQLALCHEMY_DATABASE_URI': dburi,
'S... |
import tkinter as tk
import math
showString=''
def output(string):
global showString
showString=str(showString)+str(string)
displayLabel['text']=showString
def calculate():
global showString
showString=str(eval(showString))
displayLabel['text']=showString
def pi():
global showString
s... |
class Solution:
def findSmallestSetOfVertices(self, n, edges):
ind = [0] * n
for e in edges:
ind[e[1]] += 1
return [i for i, d in enumerate(ind) if d == 0]
|
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'IPDB'
db.create_table('switch_ipdb', (
('id', self.gf('django.db.models.fields... |
import numpy as np, pandas as pd, os
from .. import *
from ..utils.utils_traj import unwrap_traj_and_center
from ..measure.compute_msd_simple import msd_fft
#simple routine for computation of individual mean squared displacements
# Programmer: Tim Tyree
# 7.20.2021
def compute_individual_mean_squared_displacement(df,df... |
import pickle
import requests
import streamlit as st
from requests.auth import HTTPBasicAuth
import os
import json
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())
API_URL = "https://ml-api-phn4j6lmdq-uc.a.run.app"
BASIC_AUTH_USERNAME = os.getenv("BASIC_AUTH_USERNAME")
BASIC_AUTH_PASSWORD = os.... |
#!/usr/bin/env python
"""
test functions for datacubes with raster labels
...
"""
import os
import shutil
import numpy as np
import rasterio
import json
from pathlib import Path
from icecube.bin.config import CubeConfig
from icecube.bin.labels_cube.labels_cube_generator import LabelsDatacubeGenerator
from icecube.bin... |
import petsc4py
import sys
petsc4py.init(sys.argv)
from petsc4py import PETSc
import numpy as np
class LSCnew(object):
def __init__(self, W,A,L,Bd,dBt):
self.W = W
self.A = A
self.L = L
self.Bd = Bd
self.dBt = dBt
self.u_is = PETSc.IS().createGeneral(range(W.sub(0... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import datetime, timedelta
from flask import Blueprint, jsonify, redirect, render_template, request, url_for
from gator import app, db
from gator.models import Media, News
import time
# create blueprint
core = Blueprint("core", __name__, template_folder="t... |
"""
Python 3.9.10 (tags/v3.9.10:f2f3f53, Jan 17 2022, 15:14:21) [MSC v.1929 64 bit (AMD64)] on win32
Данный модуль отвечает за детекцию движения
"""
import cv2 # Импортируем модуль OpenCV
import time
import os
def corrector(name_file: str, chk_video_det, xy_coord: list, frame_zoom: int, size_detect: int,
... |
class Const(object):
'''
Bibliography:
[1] VideoRay Example Code [Online]
Available: https://github.com/videoray/Thruster/blob/master/thruster.py
'''
# VRCSR protocol defines
sync_request = 0x5ff5
sync_response = 0x0ff0
protocol_vrcsr_header_size = 6
protocol_vrcsr_x... |
src_l = [2, 2, 2, 7, 23, 1, 44, 44, 3, 2, 10, 7, 4, 11]
res_for_check = [23, 1, 3, 10, 4, 11]
res = [el for el in range(len(src_l)) if src_l.count(el) == 1]
print(res == res_for_check)
|
#!/usr/bin/env python
# coding: utf-8
# In[27]:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import math
from scipy.optimize import curve_fit
from Funcoes_Bib import splitPlusMinus
df = pd.read_excel ('C:\Users\observer\Desktop\Ensaios_e_Caracterizacoes\Planilhas\Ganho_EM\HSS10MHz\Propagad... |
import sklearn.svm
from autotabular.pipeline.components.regression.liblinear_svr import LibLinear_SVR
from .test_base import BaseRegressionComponentTest
class SupportVectorComponentTest(BaseRegressionComponentTest):
__test__ = True
res = dict()
res['default_boston'] = 0.6768297818275556
res['default... |
#!/usr/bin/env python
import requests
__author__ = "Likhit Jain and Yashita P Jain"
__copyright__ = "Copyright 2019, Kaleyra"
__license__ = "MIT"
__version__ = "1.0"
__email__ = "support@kaleyra.com"
__status__ = "Production"
class Klient:
"""
"""
def __init__(self, url):
"""
Initiali... |
import argparse
from pathlib import Path
import lpips
import torch as th
import wandb
from PIL import Image
import torchvision.transforms as tvt
from tqdm.auto import tqdm
from cgd import losses
from cgd import clip_util
from cgd import script_util
# Define necessary functions
def clip_guided_diffusion(
image_... |
from scipy.interpolate import interp1d
from math import cos, pi
import _rrtm_radiation_fortran
from numpy import ndarray
INPUTS = [
# 'do_sw', # 0 Shortwave switch (integer) 1 1 / 0 => do / do not compute SW
# 'do_lw', # 0 Longwave switch (integer) 1 1... |
from typing import List
class Solution:
def findUnsortedSubarray(self, nums: List[int]) -> int:
N = len(nums)
min_num = max_num = float('inf')
for i in range(1, N):
if nums[i] < nums[i-1]:
min_num = min(nums[i:])
break
for i in reverse... |
from unittest import main
from tests.base import BaseTestCase
class AppTestCase(BaseTestCase):
"""This class represents the test cases to see if the app is up"""
# App runs ----------------------------------------
def test_app_is_running(self):
# make request
res = self.client().get('/')... |
amount = int(input())
count = 0
if int(amount/100):
count+=int(amount/100)
amount -= int(amount/100)*100
if int(amount/20):
count+=int(amount/20)
amount -= int(amount/20)*20
if int(amount/10):
count+=int(amount/10)
amount -= int(amount/10)*10
if int(amount/5):
count+=int(amount/5)
amoun... |
from db import db
class BookModel(db.Model):
__tablename__ = 'books'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(80))
author = db.Column(db.String(80))
isbn = db.Column(db.String(40))
release_date = db.Column(db.String(10))
price = db.Column(db.Float(precision... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Archerx
# @time: 2019/4/15 上午 11:10
from xadmin import views
import xadmin
from . import models
from django.contrib.auth.forms import (UserCreationForm, UserChangeForm)
# from xadmin import PermissionModelMultipleChoiceField
# from xadmin import Fieldset, Main, ... |
from flask import ( g, redirect, url_for )
from tmc.db import get_db
# Insert relation tool_x_technique
def insert_tool_x_techn(table, tool_id, technique_id):
try:
author_id = g.user['id']
except (NameError, TypeError) as error:
author_id = 1
g.db = get_db()
query='INSERT INTO {} ({}, {}, {}... |
from django.urls import path
from . import views
TYPE = "stream"
urlpatterns = [
path('', views.view_gallery_stream, name=f'gallery-{TYPE}'),
path('edit/<int:pk>/', views.video_stream_edit, name=f"{TYPE}-update"),
path('remove/<int:pk>/', views.removeStream, name=f"{TYPE}-delete"),
] |
import pandas as pd
import re
from django.core.management import BaseCommand
from django.conf import settings
from Styling.models import Garments, ImageURLs, Images, ProductCategories
class SanitizeData:
def __init__(self):
self.csv_path = settings.GARMENTS_DATA_URL + '\garment_items.jl'
self.ga... |
# coding: utf-8
# Import libraries
import pandas as pd
from pandas import ExcelWriter
import pickle
import xlsxwriter
def extract_regulatory_genes():
"""
The EXTRACT_REGULATORY_GENES operation extracts from the set of Transcription Factors associated to a gene, the list of its candidate regulatory genes, i.e.... |
import math
import random
def print_n_whitespaces(n: int):
print(" " * n, end="")
def print_n_newlines(n: int):
for _ in range(n):
print()
def subroutine_1610():
B = 3 / A * random.random()
if B < 0.37:
C = 0.5
elif B < 0.5:
C = 0.4
elif B < 0.63:
C = 0.3
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Created by Chouayakh Mahdi
25/06/2010
The package contains functions to analyse all sentence of a utterance
Functions: ... |
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
#
# @param head ListNode类
# @param k int整型
# @return ListNode类
#
class Solution:
def reverseKGroup(self , head , k ):
def reverse(a,b):
pre = None
cur = a
while cur != b... |
from .bignet import BigHouseModel
from .goal import BigGoalHouseModel, AuxiliaryBigGoalHouseModel |
from modules import util
from modules.util import Failed
logger = util.logger
builders = ["stevenlu_popular"]
base_url = "https://s3.amazonaws.com/popular-movies/movies.json"
class StevenLu:
def __init__(self, config):
self.config = config
def get_stevenlu_ids(self, method):
if method == "st... |
# used as reference version, for comparison/correctness
import numpy as np
from timecheck import inittime, timecheck
from neoncl.util import math_helper
def calcU(W):
Ci = W.shape[0]
kH = W.shape[1]
kW = W.shape[2]
Co = W.shape[3]
G = np.array([[1/4,0,0],
[-1/6,-1/6,-1/6],
[-1/6,... |
from nose.tools import eq_
from amo.tests import app_factory
class DynamicBoolFieldsTestMixin():
def setUp(self):
"""
Create an instance of the DynamicBoolFields model and call super
on the inheriting setUp.
(e.g. RatingDescriptors.objects.create(addon=self.app))
"""
... |
import sys, json, os
BOARD_ID='Os1ByyJc'
def read_auth_info():
script_path = os.path.dirname(os.path.realpath(__file__))
auth_file = script_path + "/trello-auth.json"
if not os.path.exists(auth_file):
sys.stderr.write("Cannot access Trello: Missing {}\n".format(auth_file))
sys.exit(1)
with open(auth_f... |
import os
'''
user = os.environ['POSTGRES_USER']
password = os.environ['POSTGRES_PASSWORD']
host = os.environ['POSTGRES_HOST']
database = os.environ['POSTGRES_DB']
port = os.environ['POSTGRES_PORT']
'''
user = 'test'
password = 'password'
host = 'localhost'
database = 'example'
port = '5432'
DATABASE_CONNECTION_URI =... |
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import collections
from collections import OrderedDict
from datetime import timedelta
from itertools import chain
import datetime
from django.urls import reverse
from django.template.loader import render_to_st... |
from collections import namedtuple
import contextlib
import meshcat
import meshcat.geometry as meshcat_geom
import meshcat.transformations as meshcat_tf
import matplotlib.pyplot as plt
import logging
import numpy as np
import networkx as nx
import os
import yaml
import torch
import pydrake
from pydrake.common.cpp_para... |
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class TestModel(models.Model):
field1 = models.CharField(max_length=255)
field2 = models.IntegerField()
def __str__(self):
return '%s%d' % (self.field1, self.field2)
@python_2... |
# -*- coding: utf-8 -*-
import torch.nn as nn
import torchvision
def densenet(n_classes, pretrained=False, n_layers=121, **kwargs):
'''
Creates a DenseNet based on the parameters
Arguments:
n_layers: The number of hidden layers
n_classes: The number of classes/labels
pretrained: Bo... |
#hwIo.py
#A part of NonVisual Desktop Access (NVDA)
#This file is covered by the GNU General Public License.
#See the file COPYING for more details.
#Copyright (C) 2015-2018 NV Access Limited, Babbage B.V.
"""Raw input/output for braille displays via serial and HID.
See the L{Serial} and L{Hid} classes.
Braille displa... |
from finta import TA
import scipy as sp
from scipy.signal import argrelextrema
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
import yfinance as yf
from collections import defaultdict
class Loss(object):
def __init__(self,method, sup, res):
self.method = method
self.sup = sup
sel... |
# This file is Copyright (c) 2010 by the GPSD project
# BSD terms apply: see the file COPYING in the distribution root for details.
#
# Creates build/lib.linux-${arch}-${pyvers}/gpspacket.so,
# where ${arch} is an architecture and ${pyvers} is a Python version.
from distutils.core import setup, Extension
import os
im... |
"""
The :class:`Signature` object and associated functionality. This
provides a way to represent rich callable objects and type check
calls.
"""
from collections import defaultdict
from .error_code import ErrorCode
from .stacked_scopes import (
AndConstraint,
Composite,
Constraint,
ConstraintType,
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2015-2016 Telefónica Investigación y Desarrollo, S.A.U
#
# This file is part of FIWARE project.
#
# 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 t... |
import math, statistics, random, time, sys
import numpy as np
import pandas as pd
import ray
import time
import holoviews as hv
from holoviews import opts
from holoviews.streams import Counter, Tap
from bokeh_util import square_circle_plot, two_lines_plot, means_stddevs_plot
hv.extension('bokeh')
from bokeh.layouts i... |
# coding: utf-8
"""
OrderCloud
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: 1.0
Contact: ordercloud@four51.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
Licensed under the Apache License, Ve... |
import calendar
import datetime as dt
import time
DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%S.000Z'
DATE_FORMAT = '%Y-%m-%dT00:00:00.000Z'
DPLUS_FORMAT = '%Y-%m-%dT00:01:00.000Z'
def valid_rfcformat(potential):
try:
dt.datetime.strptime(potential, DATETIME_FORMAT)
return True
except:
return F... |
"""Test the cli module."""
|
import asyncio, re, json
from smsgateway.sources.sms import command_list
from smsgateway.config import *
from smsgateway.sources.utils import *
from smsgateway import sink_sms
from telethon import TelegramClient, utils
from telethon.tl.types import Chat, User, Channel, \
PeerUser, PeerChat, PeerChannel, \
Me... |
from environs import Env
from lektor.pluginsystem import Plugin
__version__ = "18.6.12.3"
DEFAULT_PREFIX = "LEKTOR_"
class LektorEnv:
def __init__(self, config=None):
self.env = Env()
if not config:
self.prefix = DEFAULT_PREFIX
else:
self.prefix = config.get("env... |
import sys
from PyQt5.QtWidgets import *
from PyQt5.QAxContainer import *
from PyQt5.QtCore import *
import logging.handlers
import time
from pandas import DataFrame
is_64bits = sys.maxsize > 2**32
if is_64bits:
print('64bit 환경입니다.')
else:
print('32bit 환경입니다.')
formatter = logging.Formatter('[%(levelname)s|%(... |
#!/usr/bin/env python
# Copyright 2021 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 ... |
""" Copyright (c) 2017-2020 ABBYY Production 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 wr... |
from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
# Set default settings for celery
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'stratahq.settings')
app = Celery('strathq')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()
@ap... |
from flask import session
import csv, pymssql, datetime
import threading
table_lock = threading.Lock()
def create_csv_rep(orgid, filename):
table_lock.acquire()
host = "197.189.232.50"
username = "FE-User"
password = "Fourier.01"
database = "PGAluminium"
conn = pymssql.connect(host... |
from granule_ingester.processors.EmptyTileFilter import EmptyTileFilter
from granule_ingester.processors.GenerateTileId import GenerateTileId
from granule_ingester.processors.TileProcessor import TileProcessor
from granule_ingester.processors.TileSummarizingProcessor import TileSummarizingProcessor
from granule_ingeste... |
import sys
input = sys.stdin.readline
# import accumulate takes too much memory
def accumulate(A):
n = len(A)
P = [0] * (n + 1)
for k in range(1, n + 1):
P[k] = P[k - 1] + A[k - 1]
return P
count = 0
length = 0
lower_bound = 0
cups, fill = map(int, input().split())
cuplist = [0] * (cups + 2)... |
import PyPDF2
pdf1File = open('meetingminutes.pdf', 'rb')
pdf2File = open('meetingminutes2.pdf', 'rb')
pdf1Reader = PyPDF2.PdfFileReader(pdf1File)
pdf2Reader = PyPDF2.PdfFileReader(pdf2File)
pdfWriter = PyPDF2.PdfFileWriter()
for pageNum in range(pdf1Reader.numPages):
pageObj = pdf1Reader.getPage(pageNum)
p... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on Nov 7, 2015
Don't blink...
@author: Juan_Insuasti
'''
import sys
import datetime
import os.path
import json
class Logger:
def __init__(self, logName="Log", file="log.txt", enabled=True, printConsole=True, saveFile=False, saveCloud=False):
self.... |
from setuptools import setup
# Load in babel support, if available.
try:
from babel.messages import frontend as babel
cmdclass = {"compile_catalog": babel.compile_catalog,
"extract_messages": babel.extract_messages,
"init_catalog": babel.init_catalog,
"update_cat... |
from typing import Union
from notion.models.annotations import Annotations
class RichText():
"""
https://developers.notion.com/reference/rich-text
"""
TYPES = ["text", "mention", "equation"]
def __init__(self, plain_text: str = None, href: str = None, annotations: Union[dict, Annotations] = Non... |
"""
Handles running extensions inside a sandbox, which runs outside the primary
Petronia memory space with OS specific constraints.
"""
from .module_loader import create_sandbox_module_loader
|
# -*- coding: utf-8 -*-
# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is
# holder of all proprietary rights on this computer program.
# You can only use this computer program if you have closed
# a license agreement with MPG or you get the right to use the computer
# program from someone who is... |
from fastai.conv_learner import *
from fastai.dataset import *
from tensorboard_cb_old import *
import cv2
import pandas as pd
import numpy as np
import os
from sklearn.model_selection import train_test_split
from sklearn.metrics import f1_score
import scipy.optimize as opt
import torch
import torch.nn as nn
import t... |
"""Reverse-engineered client for the LG SmartThinQ API.
"""
from .core import * # noqa
from .client import * # noqa
from .ac import * # noqa
from .dishwasher import * # noqa
from .dryer import * # noqa
from .refrigerator import * # noqa
from .washer import * # noqa
__version__ = '1.3.0'
|
# dic = {'key': 'value', 'key2': 'value2'}
import json
#
# ret = json.dumps(dic) # 序列化
# print(dic, type(dic))
# print(ret, type(ret))
#
# res = json.loads(ret) # 反序列化
# print(res, type(res))
# 问题1
# dic = {1: 'value', 2: 'value2'}
# ret = json.dumps(dic) # 序列化
# print(dic, type(dic))
# print(ret, type(ret))
#
# r... |
__author__ = 'xubinggui'
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
def print_score(self):
print(self.score)
bart = Student('Bart Simpson', 59)
bart.print_score() |
import unittest
from app.models import Pitch, User
from flask_login import current_user
from app import db
class TestPitch(unittest.TestCase):
def setUp(self):
self.user_joe = User(
username='jack', password='password', email='xyz@gmail.com')
self.new_pitch = Pitch(title="Test", pitch... |
# -*- coding: utf-8 -*-
from abc import ABCMeta, abstractmethod
from .unique_identifiable import CloudioUniqueIdentifiable
class CloudioObjectContainer(CloudioUniqueIdentifiable):
"""Interface to be implemented by all classes that can hold cloud.iO objects."""
__metaclass__ = ABCMeta
@abstractmethod
... |
import os, sys; sys.path.append(os.path.join("..", "..", ".."))
from pattern.en import parse, Text
# The easiest way to analyze the output of the parser is to create a Text.
# A Text is a "parse tree" of linked Python objects.
# A Text is essentially a list of Sentence objects.
# Each Sentence is a list of Word objec... |
import re
from enum import Enum
from operator import attrgetter
from re import RegexFlag
from typing import List, Union, Match, Dict, Optional
from annotation.models.models import Citation
from annotation.models.models_enums import CitationSource
from library.log_utils import report_message
from ontology.models import... |
import pprint
from flask import Flask
from flask import request
app = Flask(__name__)
@app.route('/', methods=['POST'])
def hello_world():
content = request.get_json(silent=True)
pprint.pprint(content)
return content
|
#! /usr/bin/env python
from __future__ import print_function
import tensorflow as tf
import os, collections, sys, subprocess, io
from abc import abstractmethod
import numpy as np
def flattern(A):
'''
Flatten a list containing a combination of strings and lists.
Copied from https://stackoverflow.com/questions/1786... |
# -*- coding: utf-8 -*-
""" RandOm Convolutional KErnel Transform (ROCKET)
"""
__author__ = ["Matthew Middlehurst", "Oleksii Kachaiev"]
__all__ = ["ROCKETClassifier"]
import numpy as np
from joblib import delayed, Parallel
from sklearn.base import clone
from sklearn.ensemble._base import _set_random_states
from sklea... |
# Generated by Django 2.2.1 on 2019-05-29 20:37
import json
from django.db import migrations
def normalize_webhook_values(apps, schema_editor):
Channel = apps.get_model("api", "Channel")
for ch in Channel.objects.filter(kind="webhook").only("value"):
# The old format of url_down, url_up, post_data s... |
from easyidp.io.tests import test
import easyidp.io.metashape
import easyidp.io.pix4d
import easyidp.io.pcd |
#!/usr/bin/python
# (C) 2005 British Broadcasting Corporation and Kamaelia Contributors(1)
# All Rights Reserved.
#
# You may only modify and redistribute this under the terms of any of the
# following licenses(2): Mozilla Public License, V1.1, GNU General
# Public License, V2.0, GNU Lesser General Public Licens... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.