content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 3 13:10:12 2021
@author: divyam
"""
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
import copy
def get_coordinates(line_image, params):
try:
slope, intercept = params
except:
slope, intercept = 0,0
if... |
"""
Subservice Total Time
Keeps a running total timer in the format HH:MM:SS
To use:
timer = subsvc_total_time.ModuleSubservice(self,2,1) # display col 2, row 1
timer_task = uasyncio.create_task(timer.run())
...
timer_task.cancel()
Parms:
- service - t... |
import os
import pygame
import time
import random
import math
def setup(screen, etc):
pass
def draw(screen, etc):
etc.color_picker_bg(etc.knob5)
for i in range(0, 25) :
seg(screen, etc, i)
def seg(screen, etc, i) :
xr = etc.xres
yr = etc.yres
x = int(etc.knob2*xr) + (etc.audio_in... |
# Tetris game
# (c) 2018 Tingda Wang
import pygame, sys, random, time
from pygame.locals import *
# Game Object Constants
FPS = 30
WIN_W = 640 # in pixels
WIN_H = 480 # in pixels
SQ_SIZE = 20
BOARD_W = 10 # in squares
BOARD_H = 20 # in squares
NIL = '.' # nothin'
# board margins within window
SIDE_MARGINS = int((WIN... |
from django.urls import include, path
from rest_framework import routers
from web.api.views import (
CityCouncilAgendaView,
CityCouncilAttendanceListView,
GazetteView,
HealthCheckView,
)
router = routers.DefaultRouter()
router.register("", HealthCheckView, basename="root")
router.register("gazettes", G... |
"""ADS1220 example (print configuration register settings)."""
from machine import Pin, SPI # type: ignore
from ads1220 import ADC
cs = 15 # Chip select pin
drdy = 27 # Data ready pin
spi = SPI(1,
baudrate=10000000, # 10 MHz (try lower speed to troubleshoot)
sck=Pin(14),
mosi=Pin(13),... |
import simple_parsing
from dataclasses import dataclass
# create a parser,
parser = simple_parsing.ArgumentParser()
@dataclass
class MyModelHyperParameters():
"""Hyperparameters of MyModel"""
# Batch size (per-GPU)
batch_size: int = 32
# Learning rate of the Adam optimizer.
learning_rate: float =... |
# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*-
# ex: set sts=4 ts=4 sw=4 noet:
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the datalad package for the
# copyright and license terms.
#
# ## ### ##... |
from flask import Blueprint, redirect, url_for, jsonify, render_template
from framework.api.oauth import mastodon
from .group.common import user_groups
site = Blueprint("site", __name__)
@site.route("/")
def index():
if not mastodon.authorized:
return render_template("login.html")
print(mastodon.a... |
#
# PySNMP MIB module HUAWEI-VO-AAA-CLIENT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HUAWEI-VO-AAA-CLIENT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:49:24 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.... |
class Solution:
def twoSum(self, nums: 'List[int]', target: 'int') -> 'List[int]':
for fir_num in range(0,len(nums)):
for sec_num in range(fir_num+1,len(nums)):
test = nums[fir_num] + nums[sec_num]
if test == target:
return fir_num,sec_num
|
# Copyright 2015 Hewlett-Packard Development Company, L.P.
#
# Author: Endre Karlson <endre.karlson@hpe.com>
#
# 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/lic... |
import click
import logging
import pandas as pd
from IVF_extremes.IVF_func import *
import os
resources_dir = os.path.join(os.path.dirname(__file__), 'resources')
@click.command()
@click.option('--coc', required=True, type=int, help='number of cocs')
@click.option('--mii', required=True, type=int, help='number of ma... |
"""
Helper functions.
"""
import logging
from base64 import b64decode
import gzip
from typing import Iterable
import io
import json
import os
LOGGER_NAME = "quilt-lambda"
MANIFEST_PREFIX_V1 = ".quilt/packages/"
POINTER_PREFIX_V1 = ".quilt/named_packages/"
def separated_env_to_iter(
env_var: str,
*,
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# script version: 1.0.1
import requests
import re
import sys
import json
import configparser
# from retrying import retry
from time import sleep
def GetWlanParams():
msft_url = "http://www.msftconnecttest.com/redirect"
global header
header = {
'User-... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.8 on 2018-02-04 23:01
from __future__ import unicode_literals
from django.db import migrations
def move_rows(apps, schema_editor):
ToolUser = apps.get_model('tools', 'ToolUser')
ToolFollower = apps.get_model('tools', 'ToolFollower')
for follower in Tool... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import json
from flask import Flask
from flask import request
from flask import redirect
from flask import jsonify
from server.federation import pre_processing
from server.federation import alignment
from server.federation import train
from client.federation import iAo
import ... |
import os
from torch.utils.cpp_extension import load
_src_path = os.path.dirname(os.path.abspath(__file__))
_backend = load(name='_multi_shape_pvcnn_backend',
extra_cflags=['-O3', '-std=c++17'],
sources=[os.path.join(_src_path,'src', f) for f in [
'knn_dir/knn.cpp',... |
# -*- coding: utf-8 -*-
"""
overholt.manage.products
~~~~~~~~~~~~~~~~~~~~~~~~
product management commands
"""
|
from flask.cli import AppGroup
from click import argument, option
from redash import models
import json
manager = AppGroup(help="Dashboard management commands.")
#Click prevents us from simply calling a command from another command, hence this function.
def create_dashboard_logic(old_publisher, publisher, dashboard_i... |
from app.filters.BaseFilter import BaseFilter
class CleanSourceMapFilter(BaseFilter):
def __init__(self):
super().__init__()
self.enforce = True
self.input_extensions = ["js"]
def apply(self, file_contents, filename):
contents = file_contents.decode("utf8")
# find the... |
import datetime
from django import forms
from django.core.exceptions import ValidationError
from django.core.validators import validate_comma_separated_integer_list
from django.forms import Form
from django.forms.fields import (
BooleanField, CharField, ChoiceField, DateField, MultiValueField)
from django.forms.wi... |
""" This is the algos package.
This package is responsible for all price prediction algorithms.
"""
from enum import Enum
class Algos(Enum):
""" Granularity Enum class. Currently only support DAILY.
"""
EULER = 'euler'
|
# -*- coding: utf-8 -*-
"""
Script to Convert .tdms to .xlsx
Created on Wed Nov 25 16:09:49 2020
@author: crtjur
"""
#---------------------------------------------------
#----------------------imports----------------------
#---------------------------------------------------
import os
import numpy as np
import pandas... |
'''
You are given a string. You need to print the lexicographically sorted power-set of the string.
Note: The string s contains lowercase letter of alphabet.
'''
def find_sets(s, l, char, sets):
if l == len(s):
print(sets, char)
sets.append(char)
else:
find_sets(s, l+1, char+s[l], se... |
from django.core import management
from django.utils.translation import ugettext_lazy as _
from ...utils import PassthroughStorageProcessor
class Command(management.BaseCommand):
help = 'Process model files over a storage pipeline.'
def add_arguments(self, parser):
parser.add_argument(
... |
#!/usr/bin/python
import argparse
import json
import sys
import urllib2
parser = argparse.ArgumentParser(description='Checks that no other issues are present.')
parser.add_argument('url', help='URL of remote endpoint to check.')
args = parser.parse_args()
response = urllib2.urlopen(args.url) # nosec
data = json.lo... |
from tensorflow_tts.models.fastspeech2 import FastSpeech2
from tensorflow_tts.models.mb_melgan import MBMelGANGenerator
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Adapted from https://github.com/priba/nmp_qc
"""
utils.py: Functions to process dataset graphs.
Usage:
"""
from __future__ import print_function
import rdkit
import torch
from joblib import Parallel, delayed
import multiprocessing
import networkx as nx
import nu... |
from __future__ import annotations
from types import LambdaType
from typing import Dict, List
import requests
from requests import Response
from Core.ConfigHandler import ConfigHandler
from Log.Log import Log
from VersionControlProvider.Flexio.FlexioRessource import FlexioRessource
class Range:
total: int = 0
... |
import datetime
from typing import Protocol, Type, Union
import pytz
from pydantic import datetime_parse
tz_tokyo = pytz.timezone("Asia/Tokyo")
min_date_aware = tz_tokyo.localize(
datetime.datetime(1901, 12, 15)
) # 古すぎる日付は適切に扱うことが非常に難しため、問題が生じない日付のみ許容する。
min_date_naive = datetime.datetime(
1901, 12, 15
) #... |
# -*- coding: utf-8 -*-
from untils import until, Event
from Addon import Addon, middelware, addon_init
from Template import str_back
from addons.smile.emo import emo
import re
NotWork = 0
Start = 1
@addon_init(['!СМАЙЛЫ', '!ТЕКСТ В СМАЙЛЫ', '!СМАЙЛ'], '😅', True, 2)
class Smile(Addon):
__slots__... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import re
from typing import List, Optional, Sequence, Tuple
from pytext.common.constants import VocabMeta
from pytext.config import ConfigBase
from pytext.data.featurizer import Featurizer, InputRecord, OutputRecord
class... |
from PyQt5.QtCore import pyqtSignal
from easydict import EasyDict as edict
from pymodaq.daq_utils.daq_utils import ThreadCommand, getLineInfo
from pymodaq.daq_viewer.utility_classes import DAQ_Viewer_base
from collections import OrderedDict
import numpy as np
from pymodaq.daq_viewer.utility_classes import comon_paramet... |
import unittest
import pandas as pd
from lob_data_utils.overview import Overview
class Test(unittest.TestCase):
def test_is_in_results_for_one_key_value(self):
overview = Overview('1', 2)
df = pd.DataFrame()
df['a'] = [1]
self.assertTrue(overview.is_in_results(df, {'a': 1}))
... |
# Copyright 2020 The PyMC Developers
#
# 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 ag... |
# for plotting visualization for model and other data statistics
import matplotlib.pyplot as plt
def mean_square_error(model_history):
#plot to visualize performance (training & validation loss) of all models trained at each epoch, helps identify overfitting
plt.plot(model_history.history['loss'])
plt.plot(mo... |
from plex.core.idict import idict
from plex.interfaces.core.base import Interface
class PlaylistsInterface(Interface):
path = 'playlists'
def all(self, type=15, sort=None, playlist_type=None, smart=None):
response = self.http.get('all', query=[
('type', type),
('sort', sort),
... |
def escriu_capçalera(nom_fitxer):
with open(nom_fitxer, mode='w') as imatge:
imatge.write('P1\n')
imatge.write('3 3')
if __name__=='__main__':
nom_fitxer=input()
escriu_capçalera(nom_fitxer)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import discord
from discord.ext import commands
import requests
import os
token = os.getenv('token')
class D2():
""" Division2 class which get user information. """
def __init__(self, bot):
self.bot = bot
def get_user_id(self, uplay_name):
... |
import curses
class ScreenSettings:
verbose = 1
blank_character = ' '
class MConsole:
def __init__(self, stdscr):
self._y_max, self._x_max = stdscr.getmaxyx()
self._screen = []
self._windows = []
for y in range(self._y_max):
self._screen.append([])
... |
import testing
import utilities
import manager
import criterion
import interpolator
import algorithm
import genericSolvers
|
import copy
from abc import ABC
from typing import Generic, TypeVar, Union, Sequence, Callable, Optional, \
Dict, Any, Iterable, List, Set
from avalanche.benchmarks.scenarios.generic_definitions import \
TExperience, ScenarioStream, TScenarioStream, Experience, TScenario, \
TrainSet, TestSet
from avalanche... |
from telegram.ext import Updater,CommandHandler,MessageHandler,Filters,CallbackQueryHandler,InlineQueryHandler
from telegram import InlineKeyboardButton, InlineKeyboardMarkup,InlineQueryResultArticle,InputTextMessageContent,ParseMode
import telegram,logging,time,re
from PyDictionary import PyDictionary
import nltk
impo... |
# setup.py
import os
from setuptools import setup, find_packages
def read_file(fname):
"Read a local file"
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='mkdocs-img2fig-plugin',
version='0.9.3',
description='A MkDocs plugin that converts markdown encoded images in... |
import dataclasses
@dataclasses.dataclass
class BaseExport:
name: str
index: int
class FuncExport(BaseExport):
pass
class TypeExport(BaseExport):
pass
class MemExport(BaseExport):
pass
class GlobalExport(BaseExport):
pass
|
# Copyright © 2021 Arm Ltd and Contributors. All rights reserved.
# SPDX-License-Identifier: MIT
"""Automatic speech recognition with PyArmNN demo for processing audio clips to text."""
import sys
import os
import numpy as np
script_dir = os.path.dirname(__file__)
sys.path.insert(1, os.path.join(script_dir, '..', 'c... |
"""
1038. Binary Search Tree to Greater Sum Tree
Difficulty: Medium
Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST.
As a reminder, a binary search tree is a tree... |
from os.path import join
import pip
import setuptools
def v1_ge_v2(module, version):
"""return `module.__version__ >= version`"""
def v2li(v):
"""`v2li('20.0') == [20, 0]`"""
return list(map(int, v.split('.')))
version = v2li(version)
module = v2li(module)
# add semver zeros if, ... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import numpy as np
import math
from typing import Dict, List, Optional
import collections
import torch
import torch.nn as nn
from fairseq impor... |
"""Ukosnik - Manage Discord slash commands."""
__version__ = "0.1.3"
|
from django.urls import path, include
urlpatterns = [
path(r'oembed/', include('mylinks.oembed.urls')),
path(r'api/', include('mylinks.api.urls')),
]
|
# static version of the probabilistic approach for the loop reshape formation
# There are two sections of this program, first section generates two formations,
# one for initial setup formation, one for target formation; second section
# illustrates the dynamics of the preferability distribution of all nodes.
# comman... |
"""Cramped plot."""
from __future__ import annotations
import json
import os
import pathlib
import click
import matplotlib.pyplot as plt
import numpy as np
from tdub.art import canvas_from_counts, draw_atlas_label, legend_last_to_first
from tdub.rex import meta_text, region_plot_raw_material
helps = ["-h", "--help... |
from .helpers import *
from . import instance as i_model
def get_by_name(nmod_name):
data = sysrepocfg_fetch(NEMEA_SR_PREFIX)
if data is None:
raise NotFoundException("No configuration data found.")
mods = data['{}:supervisor'.format(NEMEA_SR_PREFIX)]['available-module']
for mod in mods:
... |
#$Id$
class User:
"""This class is used to create object for Users."""
def __init__(self):
"""Initialize parameters for Users object."""
self.user_id = ''
self.is_current_user = None
self.user_name = ''
self.email = ''
self.user_role = ''
self.status = ''... |
"""Base class for linear Machine Learning Regression models."""
import logging
import os
import matplotlib.pyplot as plt
import numpy as np
from esmvaltool.diag_scripts import mlr
from esmvaltool.diag_scripts.mlr.models import MLRModel
logger = logging.getLogger(os.path.basename(__file__))
class LinearModel(MLRMo... |
# Run this program with:
# python3 hello.py
# Calls the "print" function, passing a text string to it
# The function sends the text (and a newline) to stdout
print("Hello world!")
|
import math
import numpy as np
def pwm2thrust_dji_set(pwm, voltage):
pwm_mean = 1525
pwm_std = 231.1462
voltage_mean = 11.7894
voltage_std = 0.33
p00 = 2.939
p10 = 2.422
p01 = 0.1464
p20 = 0.3989
p11 = 0.1119
x = (pwm - pwm_mean) / pwm_std
y = (voltage - voltage_mean) / vol... |
from django.test import TestCase
class BaseTestCase(TestCase):
def test_response(self):
response = self.client.get('/')
self.assertEqual(response.status_code, 200)
from django.contrib.auth.models import User
user = User.objects.create(username='testuser')
user.set_passwo... |
import torch
import numpy as np
import itertools
import time
from model.module.dependency import Dependency
from model.module.constituency import Constituency, InternalParseNode
from model.module.vocab import Vocabulary
from model.chart_parser import ChartParser
DEP_PATH = "../samples/dep_train.txt"
CON_PATH = "../... |
import pbr.version
version_info = pbr.version.VersionInfo('meteos-ui')
|
import os
import shutil
import numpy as np
from osgeo import gdal, osr
# Set this variable to your osgeopy-data directory so that the following
# examples will work without editing. We'll use the os.path.join() function
# to combine this directory and the filenames to make a complete path. Of
# course, you can type t... |
#
# PySNMP MIB module SNARLSNMP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SNARLSNMP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:08:04 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... |
# -*- coding: utf-8 -*-
# (c) 2020-2021 Martin Wendt and contributors; see https://github.com/mar10/stressor
# Licensed under the MIT license: https://www.opensource.org/licenses/mit-license.php
"""
https://w3c.github.io/web-performance/specs/HAR/Overview.html
"""
import json
import logging
import os
import re
from col... |
# Generated by Django 3.0.8 on 2020-08-27 05:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("azure_part_detections", "0001_initial")]
operations = [
migrations.AddField(
model_name="partdetection",
name="maxImage",
... |
from os import getcwd, path
from dotenv import load_dotenv
# try to parse .env file to use development
load_dotenv(dotenv_path=path.join(getcwd(), '.env'), verbose=True)
def get_fixtures_directory():
"""
:rtype: str
"""
return path.join(
path.abspath(path.dirname(__file__)),
'fixture... |
# #coding: utf-8
# import torch
# from torch.autograd import Variable
# import utils
# import dataset
# import os
# from PIL import Image
# import keys
# import models.crnn as crnn
#
# #os.environ["CUDA_VISIBLE_DEVICES"] ="1"
# model_path = './expr_cmp1/netCRNN_69_2713.pth'
# img_path = './data/0000002_1.jpg'
#
# alpha... |
import subprocess
import re
import json
p = subprocess.Popen(
# "where chkdsk.exe",
"curl https://api.ratesapi.io/api/2021-04-01",
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
retval = p.wait()
print(retval)
if p and p.stdout:
r = re.compile(r'\{"(.*)"\}')
response_text = p.stdout.read()... |
from jira import JIRA
import config
def close_issue(issue, status):
jira_server = {'server': config.jira_server}
jira = JIRA(options=jira_server, basic_auth=(config.jira_user, config.jira_pass))
jira.transition_issue(issue, status)
close_issue('ZBX-2', '41') # ZBX-2: Project key, 41: transition id for c... |
import operator
import logging
from mist.api import config
from mist.api.exceptions import RuleNotFoundError
from mist.api.helpers import get_resource_model
from mist.api.notifications.helpers import _log_alert
from mist.api.rules.tasks import run_action_by_id
from mist.api.rules.models import Rule
from mist.api.r... |
from catcmd.config import CONFIG
# from catcmd.src.cli_interface import CLI |
import json
import os
class SettingsLoader:
def __init__(self, file, landir, lankey):
with open(file, "r") as f:
self.settings = json.loads(f.read())
with open(os.path.join(landir, self.settings[lankey]["lan"] + ".lan")) as f:
self.landir = json.loads(f.read())
def get... |
from discord.ext import commands
import random
import string
import os
import src.generate.wordcount as wordcount_gen
import discord
import json
IMAGE_CHANNEL_ID = 577523623355613235
LINHS_ID = 81231616772411392
class MessageStats(commands.Cog, name="Server Statistics"):
def __init__(self, bot):
self.bo... |
# Copyright (c) 2021, TNO
# 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 and the followi... |
import os
import re
from flask_apscheduler import APScheduler
from prometheus_client.core import REGISTRY, GaugeMetricFamily
from prometheus_client.parser import text_string_to_metric_families
from prometheus_client import start_http_server
from server import app
class CustomCollector(object):
def collect(self)... |
# -*- coding: utf-8 -*-
"""Arsenal test code."""
import numpy as np
from numpy import testing
from sklearn.metrics import accuracy_score
from sktime.classification.kernel_based import Arsenal
from sktime.datasets import load_basic_motions, load_unit_test
def test_arsenal_on_unit_test_data():
"""Test of Arsenal o... |
#!/usr/bin/env python3
# encoding: utf-8
import fileinput
def fix_sums():
"""fixes a checksums file in this format:
\d4e9b804eb556f8140b17921 *C:\\TV\\My Show.mkv
\885083f72a4211a6f95eb380 *C:\\Movies\\My Adventure.mkv
and replaces it with something more sensible:
d4e9b804eb556f8140b17921 My Show.mkv
885083f7... |
from django.apps import AppConfig
class CitizenConfig(AppConfig):
name = 'citizen'
|
from django.conf.urls import patterns, url
urlpatterns = patterns(
'wtl.wtlib.views',
url(r'^$', 'home', name='home'),
url(r'^libraries/$', 'libraries_list',
{'language_slug': None, 'tag': None}, name='wtlib_libraries_list'),
url(r'^libraries/(?P<language_slug>[\w\d-]+)/$', 'libraries_list',... |
#!/usr/bin/env python
import sys
from toggl import api, exceptions, utils, __version__
entry = api.TimeEntry.objects.get(sys.argv[1])
entry.continue_and_save()
|
# -*- coding:utf-8 -*-
import json
import time
import urllib
import urllib2
from datetime import datetime
from flask import Blueprint, request, jsonify, g, current_app
from sqlalchemy import or_
from lib.upload import upload_local
from sharper.flaskapp.helper import json_error
from sharper.lib.qbox import upload_web
... |
from airflow.providers.microsoft.mssql.hooks.mssql import MsSqlHook
from airflow.operators.python import PythonOperator
from typing import Optional, List, Callable, Dict
from airflow.utils.operator_helpers import determine_kwargs
class Redcap2DbOperator(PythonOperator):
def __init__(
self,
... |
from .base import Base
class Apt(Base):
@staticmethod
def is_valid(installed_binaries):
if "apt-get" in installed_binaries:
return True
return False
def __str__(self):
return "System is Debian-Ubuntu like"
|
# Copyright 2013 Rackspace, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... |
from . import core_model
import tensorflow as tf
import tensorflow_addons as tfa
from tensorflow.keras import losses
from tensorflow.keras.layers import Activation # , Dropout
from tensorflow.keras.layers import (LSTM, BatchNormalization, Bidirectional,
Conv1D, Dense, Dropout,
... |
# import boto3
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
import joblib
import numpy as np
import pandas as pd
from time import process_time_ns, time
import re
import io
import argparse
from time_limit import set_time_limit
parser = argparse.Argum... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
# compile python file to pyc file
#
# @Author : Jasonwbw@yahoo.com
import sys
des = '<input file name>' + \
'\n\taverage word counting'
def check_params(argv):
if len(argv) < 1:
print 'leak params, please use like:', des
return False
return Tr... |
import os
import shutil
import common
import easygui
from utils import meas_check
from openpyxl import load_workbook
from openpyxl.styles import Border, Side, PatternFill
# ************** Global Variables ******************** #
shared_drive_dir = r'\\wilmnas4\Local Programs\FDWatch_TestData\Data_Testsetup\DVT1_Test_Re... |
# Using a combination of black square tiles and oblong tiles chosen
# from: red tiles measuring two units, green tiles measuring three
# units, and blue tiles measuring four units, it is possible to tile
# a row measuring five units in length in exactly fifteen different
# ways.
# K K K K K R R K K K K R R K... |
class InvalidNumberError(Exception):
"""
Raised when an invalid number (in the range 32776..65535 inclusive)
is encountered.
"""
pass
class EmptyStackError(Exception):
"""Raised when attempting to pop an element from an empty stack."""
pass
|
from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import CustomUser, Profile
class UserRegisterForm(UserCreationForm):
class Meta:
model = CustomUser
fields = ['username', 'email']
class UserChangeForm(UserChangeForm):
class Meta:
... |
'''
Test create/restore snapshot functions with vm migration.
@author: Youyk
'''
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.test_lib as test_lib
import zstackwoodpecker.test_state as test_state
import zstackwoodpecker.zstack_test.zstack_test_snapshot as zstack_sp_header
import z... |
from .flutter_clean_command import FlutterCleanCommand
from .flutter_run_command import FlutterRunCommand
from .flutter_stop_app_command import FlutterStopAppCommand
from .flutter_select_device_command import FlutterSelectDeviceCommand
from .flutter_hot_reload_command import FlutterHotReloadCommand
from .flutter_hot_re... |
#
# koji hub plugin unit tests
#
import unittest
import os
import imp
from flexmock import flexmock
import koji
class TestHubPlugin(unittest.TestCase):
def setUp(self):
"""Loads the plugin to self.plugin"""
root = os.getenv("GITHUB_WORKSPACE", os.getcwd())
haystack = os.path.join(root,... |
import os
from flask import Flask, request, jsonify
from pymongo import MongoClient
def create_app():
app = Flask(__name__)
client = MongoClient(
os.environ.get('MONGODB_URI') \
or 'mongodb://localhost:27017/expensior'
)
db = client.get_database()
piles = db.piles_collection
... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import numpy as np
from nolitsa import d2, utils
from numpy.testing import assert_allclose, run_module_suite
def test_c2():
# Test d2.c2()
# Particle moving uniformly in 5d: y(t) = a + b*t
a = np.random.random(5)
... |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class FixupCNN(nn.Module):
"""
A larger version of the IMPALA CNN with Fixup init.
See Fixup: https://arxiv.org/abs/1901.09321.
Parameters
----------
input_shape : tuple
Shape input tensors.
Attributes... |
"""
DAY 17 : Minimize the maximum difference of adjacent elements after at most K insertions.
https://www.geeksforgeeks.org/minimize-the-maximum-difference-of-adjacent-elements-after-at-most-k-insertions/
QUESTION : Given an array A[] consisting 0s, 1s and 2s. The task is to write a function that
sorts the given... |
# pylint: disable=missing-graphene-docstring
import graphene
from .util import non_null_list
class GrapheneTableConstraints(graphene.ObjectType):
other = non_null_list(graphene.String)
class Meta:
name = "TableConstraints"
class GrapheneTableColumnConstraints(graphene.ObjectType):
nullable = g... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.