content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
import datetime
import sqlalchemy
# noinspection PyPackageRequirements
from models.model_base import ModelBase
class Roll(ModelBase):
__tablename__ = 'rolls'
id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True, autoincrement=True)
created = sqlalchemy.Column(sqlalchemy.DateTime, default=datetim... | python |
import json
import os
class Const:
def __init__(self, logger = None):
self.init_const()
self.logger = logger
controllerAddr = "NOT SET"
controllerPort = "NOT SET"
BASE_PATH = "/home/mmeinen/polybox/code/DC-MONDRIAN" #TODO: needs to be set whenever run somewhere else... (not elegant but ... | python |
donations = [
{
'price': 1,
'thanks': True,
'col_size': 12,
},
{
'price': 5,
'thanks': True,
'link': True,
'col_size': 12,
},
{
'price': 10,
'thanks': True,
'link': True,
'status': 'SUPPORTER',
'col_size... | python |
def merge_the_tools(string, n):
out = [list(string)[k:k+n] for k in range(0,len(list(string)),n)]
for x in out:
print(''.join(sorted(set(x), key=x.index)))
| python |
# Write the pseudo code for a program that reads a target csv file and adds the correct typing to its contents.
# After that it should transpose the resulting csv file
| python |
# Author: Simon Liedtke <liedtke.simon@googlemail.com>
#
# This module was developed with funding provided by
# the Google Summer of Code (2013).
"""
Overview
^^^^^^^^
The database package exports the following classes and exceptions:
:classes:
- Database
:exceptions:
- EntryAlreadyAddedError
... | python |
import numpy as np
import torch
import matplotlib.pyplot as plt
from collections import OrderedDict
def linear_size(output):
output_size = np.array(output.size())
h, w = output_size[2], output_size[3]
size = int(h * w)
return size
def count_parameters(model):
return sum(p.numel() for p in model.... | python |
"""treelstm.py - TreeLSTM RNN models
Written by Riddhiman Dasgupta (https://github.com/dasguptar/treelstm.pytorch)
Rewritten in 2018 by Long-Huei Chen <longhuei@g.ecc.u-tokyo.ac.jp>
To the extent possible under law, the author(s) have dedicated all copyright
and related and neighboring rights to this software to the ... | python |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# File : losses.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 10/04/2018
#
# This file is part of NSCL-PyTorch.
# Distributed under terms of the MIT license.
import torch
import torch.nn as nn
import torch.nn.functional as F
import jactorch
__a... | python |
from typing import List
class Solution1:
def rotate(self, matrix: List[List[int]]) -> None:
n = len(matrix)
for i in range(n//2):
for j in range(n-n//2):
matrix[i][j], matrix[~j][i], matrix[~i][~j], matrix[j][~i] = \
matrix[~j][i], matrix[~i][~j], ma... | python |
# -*- coding: utf-8 -*-
from .darts import *
from .priors import *
from .posterior import *
from .plotting import *
from .utils import *
from .plot_system_evolution import *
__version__ = "1.1.0"
# try:
# __DART_BOARD_SETUP__
# except NameError:
# __DART_BOARD_SETUP__ = False
#
# if not __DART_BOARD_SETUP__... | python |
# Input: a comma-separated list of integers, representing a program and its data
TEST = "1,9,10,3,2,3,11,0,99,30,40,50"
with open('day02.txt', 'r') as infile:
PUZZLE = infile.read()
def part1(data):
"""Return the value at position 0 after running the program.
Put 12 and 2 in positions 1 and 2 before run... | python |
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 29 18:28:55 2019
@author: yoelr
"""
from . import Facility
from ..decorators import cost
from thermosteam import Stream
import numpy as np
from ... import HeatUtility
# from copy import copy
__all__ = ('CoolingTower',) #'CoolingTowerWithPowerDemand')
@cost('Flow rate', ... | python |
# Evalúa qué puntos del grid del CRU corresponden a
# la Cuenca del Valle de México.
import os
import pandas as pd
import numpy as np
import geoviews as gv
import geopandas as gpd
gv.extension("matplotlib")
gv.output(size = 150)
fdir_d = os.getcwd() + "/data/Cuencas/Regiones_Hidrologicas_Adminis... | python |
# -*- coding: utf-8 -*-
# Copyright (c) 2019-2021 Ramon van der Winkel.
# All rights reserved.
# Licensed under BSD-3-Clause-Clear. See LICENSE file for details.
# importeer individuele competitie historie
from django.core.management.base import BaseCommand
from HistComp.models import HistCompetitie, HistCompetit... | python |
#!/usr/bin/env python2
# Copyright (c) 2017, ESET
# 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 cond... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : Joe Gao (jeusgao@163.com)
import os
import numpy as np
from fastapi import FastAPI
from predictor import main
from storages import DIC_ZODB, milvusDB
app = FastAPI()
collection_cosine = 'dependency'
partition_tags_cosine = '202103'
collection_words = 'word... | python |
# -*- coding: utf-8 -*-
import json
from flask.ext.script import Manager
from app import app
import config
app.config.from_object(config.DevelopmentConfig)
manager = Manager(app)
@manager.command
def index_data():
print("Indexing...")
'''try:
app.elasticsearch.indices.create(index='big-one', ignor... | python |
# GOMC Example for the Gibbs Ensemble (GEMC) using MoSDeF [1, 2, 5-10, 13-17]
# Note: In this specific example, we will be using the GEMC_NVT ensemble.
# Import the required packages and specify the force field (FF) being used.
# Note: For GOMC, the residue names are treated as molecules, so the residue names must... | python |
class Solution:
def largestValues(self, root):
maxes = []
if not root:
return maxes
stack = [(root, 0)]
while stack:
node, level = stack.pop()
if level >= len(maxes):
# first time reaching this level]
# append dire... | python |
import math
import pickle
import torch
from torch import distributed as dist
from torch.utils.data.sampler import Sampler
from torch.nn import SyncBatchNorm
import numpy as np
def get_rank():
if not dist.is_available():
return 0
if not dist.is_initialized():
return 0
re... | python |
"""
Contains special test cases that fall outside the scope of remaining test files.
"""
import textwrap
from unittest.mock import patch
from flake8_type_checking.checker import ImportVisitor
from flake8_type_checking.codes import TC001, TC002
from tests import REPO_ROOT, _get_error, mod
class TestFoundBugs:
def... | python |
from .resources import BaseResource, BaseWithSubclasses
class SwitchConnection:
def __init__(self, resource, connection_alias):
self.resource = resource
self._connection_alias = connection_alias
def __enter__(self):
if issubclass(self.resource, BaseWithSubclasses):
modifie... | python |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Connector to generate connect, engine and session object
based on parameters defined in config.yaml
"""
__author__ = 'Laurent.Chen'
__date__ = '2019/7/15'
__version__ = '1.0.0'
import os
import yaml
from sqlalchemy import create_engine
from sqlalchemy... | python |
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from app1.models import MyUser
# Register your models here.
admin.site.register(MyUser, UserAdmin) | python |
class Solution:
def countPairs(self, nums: List[int], k: int) -> int:
result=0
for i in range(len(nums)-1):
for j in range(i+1, len(nums)):
if nums[i]==nums[j] and (i*j)%k==0:
result+=1
return result | python |
from django.conf.urls import url
from ..views.admin import SubmissionRejudgeAPI, ClassSubmissionListAPI
urlpatterns = [
url(r"^submission/rejudge?$", SubmissionRejudgeAPI.as_view(), name="submission_rejudge_api"),
url(r"^class_submission/?$", ClassSubmissionListAPI.as_view(), name="class_submission_api"),
]
| python |
# -*- coding: utf-8 -*-
"""Core settings and configuration."""
# Part of Clockwork MUD Server (https://github.com/whutch/cwmud)
# :copyright: (c) 2008 - 2017 Will Hutcheson
# :license: MIT (https://github.com/whutch/cwmud/blob/master/LICENSE.txt)
from os import getcwd
from os.path import join
DEBUG = False
TESTING =... | python |
from FSMConfig import FSMConfig
class GraphicsMouseManager:
def __init__(self):
self.leftDown = False
self.middleDown = False
self.rightDown = False
self.gcLocal = FSMConfig()
self.prevDragX = None
self.prevDragY = None
self.draggedObject = ... | python |
#!/usr/bin/env python3.8
# Copyright 2021 The Fuchsia 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 argparse
import json
import os
import sys
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
... | python |
# Angus Dempster, Francois Petitjean, Geoff Webb
#
# @article{dempster_etal_2020,
# author = {Dempster, Angus and Petitjean, Fran\c{c}ois and Webb, Geoffrey I},
# title = {ROCKET: Exceptionally fast and accurate time classification using random convolutional kernels},
# year = {2020},
# journal = {Data Mi... | python |
from django.contrib import admin
from django.urls import path
from . import views
app_name = 'sbadmin'
urlpatterns = [
path('table/', views.TableView.as_view(), name='table'),
path('chart/', views.ChartView.as_view(), name='chart'),
path('', views.IndexView.as_view(), name='index'),
path('home/', view... | python |
# -*- coding: utf-8 -*-
# import bibliotek
import os
import datetime
# zmienna-licznik przeskanowanych folderow i separator
czysazdjecia = countope = 0
lines_seen = set()
# aktualna data i godzina
czasstart = datetime.datetime.now()
print("~~~~~~START~~~~~~\t" + str(czasstart).split(".")[0])
# usunac jesli stosujem... | python |
import os
import sys
import requests
import ConnectWindow, ConnectedWindow, Driver
from PySide2 import QtCore
from PySide2.QtUiTools import QUiLoader
from PySide2.QtWidgets import QApplication, QLineEdit, QPushButton, QTabWidget, QWidget
class LoginWindow(QtCore.QObject):
def __init__(self, ui_file, driver_window,... | python |
__author__ = 'joon'
import sys
sys.path.insert(0, 'ResearchTools')
from util.construct_filenames import create_token
from util.construct_controls import subcontrol
from util.ios import mkdir_if_missing, save_to_cache, load_from_cache
from util.maths import Jsoftmax, proj_lp, proj_lf, compute_percentiles
from util.dic... | python |
"""Backend for rendering multi-frame images using PIL.
These are internal APIs and subject to change at any time.
"""
try:
import PIL
except (ImportError):
PIL = None
from .shared import Backend, BackendError, check_output
class PILMultiframeBackend(Backend):
"""Backend for rendering multi-frame images... | python |
import jwt.exceptions
import pytest
from okay.jwt import main, decode
__author__ = "Cesar Alvernaz"
__copyright__ = "Cesar Alvernaz"
__license__ = "MIT"
from fixtures.jwt_fixtures import VALID_TOKEN, SECRET, \
EXPECTED_TOKEN_PAYLOAD, INVALID_SECRET, VALID_RS256_TOKEN, \
EXPECTED_TOKEN_RS256_PAYLOAD
def test... | python |
import os,re, sys
from byo.track import Track, load_track
from byo.io.genome_accessor import GenomeCache, RemoteCache
from byo.io.annotation import AnnotationAccessor
#from byo.io.lazytables import NamedTupleImporter as Importer
import byo.config
import logging
class LazyTranscriptLoader(object):
def __init__(sel... | python |
# -*- coding: utf-8 -*-
# @Time : 2018/5/28 22:03
# @Author : ddvv
# @Site : http://ddvv.life
# @File : xiaomistorespider.py
# @Software: PyCharm
"""
第三方依赖库: Crypto
功能:
1. 获取小米商店应用评论
消息说明:
1. "AppSpider-0010-001" : 应用评论
"""
import scrapy
from appspider.commonapis import *
CONST_INFO = {
'app_na... | python |
#!/usr/bin/python
# Simple tcp fuzz against a target
import socket
from sys import exit,argv
if len(argv) < 2:
print "Performs a simple fuzz against a target"
print "Usage: %s <Target IP Address/hostname> <Target Port>" % str(argv[0])
exit(1)
#Create an arry of buffers, from 10 to 2000, with increments of 20.
buf... | python |
#!/usr/bin/python
import sys
import re
threshold = float(sys.argv[1])
tp = 0
fp = 0
fn = 0
typePr = {}
for line in sys.stdin:
if re.search(r'^\d', line):
fields = line.rstrip('\n').split(' ')
gold = fields[1]
(predicted, conf) = fields[2].split(':')
print "%s\t%s\t%s" % (gold, p... | python |
import datetime as dt
import re
from collections import namedtuple
from pathlib import Path
import pytest
import ravenpy
from ravenpy.config.commands import (
BasinStateVariablesCommand,
EvaluationPeriod,
GriddedForcingCommand,
HRUStateVariableTableCommand,
)
from ravenpy.config.rvs import OST, RVC, R... | python |
# -*- coding: utf-8 -*-
# Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and Contributors
# See license.txt
from __future__ import unicode_literals
import frappe
import unittest
from frappe.utils import nowdate, get_last_day, add_days
from erpnext.assets.doctype.asset.test_asset import create_asset_data
from erpnex... | python |
import logging
import os
from ...utils import import_export_content
from ...utils import paths
from ...utils import transfer
from kolibri.core.tasks.management.commands.base import AsyncCommand
logger = logging.getLogger(__name__)
class Command(AsyncCommand):
def add_arguments(self, parser):
node_ids_h... | python |
import os
import mimetypes
import json
from plantcv.plantcv import fatal_error
# Process results. Parse individual image output files.
###########################################
def process_results(job_dir, json_file):
"""Get results from individual files. Parse the results and recompile for SQLite.
Args:
... | python |
import logging
import traceback
import urllib
import datetime
import mimetypes
import os
import sys
import zlib
import gzip
import StringIO
import json
from pylons import request, response, session, tmpl_context as c
from pylons import app_globals
from pypesvds.lib.base import BaseController, render
from pypesvds.lib... | python |
# Generated by Django 2.0.2 on 2018-05-16 11:02
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('project', '0019_auto_20180516_1034'),
]
operations = [
migrations.AlterFie... | python |
from typing import Tuple, Iterable
from rlp.utils import str_to_bytes
from state.util import utils
from storage.kv_store import KeyValueStorage
# log = get_logger('db')
databases = {}
class KeyValueStorageInMemory(KeyValueStorage):
def __init__(self):
self._dict = {}
def get(self, key):
i... | python |
#!/usr/bin/env python
# coding: utf-8
## define the convolutional neural network architecture
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
# can use the below import should you choose to initialize the weights of your Net
import torch.nn.init as I
class Net(... | python |
from .CTCModel import *
| python |
'''
Module containing all the requisite classes to perform test steps.
Adding new actions
-------------------
Creating new simple actions in the code is designed to be fairly straightforward, and only
requires three steps:
1. Add an entry for the action on the ``enums`` module
2. Create a function to perform the act... | python |
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... | python |
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 :
... | python |
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... | python |
'''
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... | python |
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... | python |
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)-... | python |
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... | python |
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,
# ... | python |
#!/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... | python |
# -*- 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,... | python |
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... | python |
# 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... | python |
# /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... | python |
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"]... | python |
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__)
... | python |
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... | python |
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... | python |
# 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','... | python |
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... | python |
# 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... | python |
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"),
]
| python |
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... | python |
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... | python |
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... | python |
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... | python |
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]
| python |
# 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... | python |
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... | python |
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.... | python |
#!/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... | python |
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... | python |
#!/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 |
"""
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,
... | python |
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... | python |
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)
| python |
#!/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... | python |
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... | python |
#!/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... | python |
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_... | python |
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... | python |
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... | python |
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('/')... | python |
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... | python |
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... | python |
#! /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, ... | python |
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 {} ({}, {}, {}... | python |
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"),
] | python |
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... | python |
# 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.... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.