content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
from rubicon_ml.client import Base
class Parameter(Base):
"""A client parameter.
A `parameter` is an input to an `experiment` (model run)
that depends on the type of model being used. It affects
the model's predictions.
For example, if you were using a random forest classifier,
'n_estimators... | python |
# Mirror data from source MSN's to destination MSN on same Mark6 unit
# Jan 29, 2017 Lindy Blackburn
import argparse
import subprocess
import stat
import os
parser = argparse.ArgumentParser(description="mount drives and create commands to copy data from source MSN(s) to destination MSN.")
parser.add_argument('source'... | python |
# Generated by Django 2.2.10 on 2020-04-26 14:55
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('pacientes', '0013_consulta_turno'),
]
operations = [
migrations.CreateModel(
... | python |
"""Option handling polyfill for Flake8 2.x and 3.x."""
import optparse
import os
def register(parser, *args, **kwargs):
r"""Register an option for the Option Parser provided by Flake8.
:param parser:
The option parser being used by Flake8 to handle command-line options.
:param \*args:
Pos... | python |
# -*- coding: utf-8 -*-
"""
Created on 2018/8/1
@author: xing yan
"""
from random import shuffle, sample, randint, choice
administrative_div_code = ['110101', '110102', '110105', '110106', '110107', '110108', '110109', '110111', '110112', '110113', '110114', '110115', '110116', '110117', '110118', '110119']
surname ... | python |
#! /usr/bin/env python
#S.rodney
# 2011.05.04
"""
Extrapolate the Hsiao SED down to 300 angstroms
to allow the W filter to reach out to z=2.5 smoothly
in the k-correction tables
"""
import os
from numpy import *
from pylab import *
sndataroot = os.environ['SNDATA_ROOT']
MINWAVE = 300 # min wavelength for extrap... | python |
# coding=utf8
# Copyright 2018 JDCLOUD.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/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... | python |
# === Start Python 2/3 compatibility
from __future__ import absolute_import, division, print_function, unicode_literals
from future.builtins import * # noqa pylint: disable=W0401, W0614
from future.builtins.disabled import * # noqa pylint: disable=W0401, W0614
# == End Python 2/3 compatibility
import mmap
import os... | python |
__version__ = "1.5.0"
default_app_config = "oauth2_provider.apps.DOTConfig"
| python |
import os, requests, json, redis
from flask import Flask
from openarticlegauge import config, licenses
from flask.ext.login import LoginManager, current_user
login_manager = LoginManager()
def create_app():
app = Flask(__name__)
configure_app(app)
if app.config['INITIALISE_INDEX']: initialise_index(app)
... | python |
#!/usr/bin/env python3
import logging
import sys
import tempfile
import threading
import time
import unittest
import warnings
from os.path import dirname, realpath
sys.path.append(dirname(dirname(dirname(realpath(__file__)))))
from logger.utils import formats # noqa: E402
from logger.readers.text_file_reader import ... | python |
# This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from __future__ import unicode_literals
from flask import session
from indico.core.db import db
def ge... | python |
import math
import time
import copy
import random
import numpy as np
import eugene as eu
import pdb
#Parent Sensor
class VABSensor( object ):
def __init__(self, dynamic_range):
self._init_value = None
self._range = dynamic_range
def get_range(self):
return self._range
################... | python |
#!/usr/bin/env python3
# _*_ coding: utf-8 _*_
"""Numbering formats for converted XML lists.
:author: Shay Hill
:created: 6/26/2019
I don't want to add non-ascii text to a potentially ascii-only file, so all bullets
are '--' and Roman numerals stop at 3999.
Doesn't capture formatting like 1.1.1 or b) or (ii). Only t... | python |
import info
class subinfo(info.infoclass):
def setTargets(self):
self.versionInfo.setDefaultValues(gitUrl = "https://invent.kde.org/utilities/ktrip.git")
self.description = "Public transport assistant"
def setDependencies(self):
self.buildDependencies["virtual/base"] = None
se... | python |
def Predict(X_user) :
# Libs
import pandas as pd
import numpy as np
from sklearn.preprocessing import OneHotEncoder
from sklearn.compose import ColumnTransformer
from catboost import CatBoostClassifier
X_user = np.array(X_user).reshape(1,-1)
print(X_user)
# Reading the dat... | python |
#!/usr/bin/env python3
def test_prime(test_value):
if test_value == 2:
return 1
for x in range(2, test_value):
if test_value % x == 0:
return 0
return 1
def main():
test_value = 179424673
if test_prime(test_value):
print(test_value, "is prime.")
else:
... | python |
from .color import *
from .display import *
from .patterns import *
| python |
from api import views
from django.contrib import admin
from django.urls import include, path
from rest_framework.routers import DefaultRouter
from rest_framework.schemas import get_schema_view
from rest_framework.documentation import include_docs_urls
router = DefaultRouter()
router.register(r'match', views.MatchView... | python |
# Generated by Django 2.1.5 on 2019-01-19 20:13
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('access', '0015_auto_20170416_2044'),
]
operations = [
migrations.AddField(
model_name='smtpserver',
name='password_f... | python |
from earthnet_models_pytorch.setting.en21_data import EarthNet2021DataModule
from earthnet_models_pytorch.setting.en22_data import EarthNet2022DataModule
from earthnet_models_pytorch.setting.en21x_data import EarthNet2021XDataModule,EarthNet2021XpxDataModule
from earthnet_models_pytorch.setting.en21_std_metric import... | python |
#!/usr/bin/env python3
"""
This example shows how to generate basic plots and manipulate them with FEA
In this case, we'll generate a 4D model and ruse FEA to find all possible
2D and 3D reduced models.
We'll then solve for the solution spaces by breaking up each solution and
finding the maximum and minimum values in... | python |
#!/usr/bin/env python3
# Intro & methodology:
#
# 自从几个月前大号被百度永封了就没怎么来hhy,来了也不发贴回贴。今天听说
# 有人统计了五选周期每人的直播次数,就来看了一下,发现受统计方法所限,原
# 贴数据问题很大(例:路人最爱的那位大人分明直播了两次——虽然都是外务要求;
# 但原贴说那位大人直播了零次,以致收了很多酸菜,本人心痛不已),所以本人
# 决定小号出山,拿出箱底的数据拨乱反正一下,也顺便提供一点细节。
#
# 还是老样子,本人先介绍数据来源、统计方法,指出局限性;然后提供数据,但
# 不多加主观发挥,由读者自行理解。
#
# 本人数据来源是每整十分钟爬一次口袋的当... | python |
import multiprocessing
import os
import random
import time
import pytest
import requests
from finetuner.toydata import generate_fashion
from finetuner import __default_tag_key__
from jina.helper import random_port
os.environ['JINA_LOG_LEVEL'] = 'DEBUG'
all_test_losses = ['SiameseLoss', 'TripletLoss']
def _run(fram... | python |
from .Layer import *
class Slice(Layer):
def __init__(self, model, *args, **kwargs):
Layer.__init__(self, model, *args, **kwargs)
self.axis = kwargs.get("axis", 1)
if "slice_point" in kwargs:
self.slice_points = [kwargs["slice_point"]]
else:
self.slice_points... | python |
class NaturalNumbers:
def __init__(self):
pass
def get_first_n_for(self, n): # Ejemplo
"""
Obtener los primeros n naturales en una lista con for
"""
first_n = [] # Se declara una lista donde almacenaremos los numeros
for i in range(n): # Se itera sobre range que ... | python |
"""
MIT License
Copyright (c) 2021 Defxult#8269
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, ... | python |
# Generated by Django 2.2.10 on 2020-04-06 06:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('items', '0002_item_whereabouts'),
]
operations = [
migrations.AddField(
model_name='item',
name='sale_type',
... | python |
# Copyright 2021 IBM Corporation
#
# 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 wri... | python |
import os
import shutil
import unittest
from xbrr.tdnet.client.document_client import DocumentClient
from xbrr.edinet.reader.reader import Reader
from xbrr.tdnet.reader.doc import Doc
import pandas as pd
class TestReader(unittest.TestCase):
@classmethod
def setUpClass(cls):
_dir = os.path.join(os.path... | python |
from noise import pnoise2
from time import sleep
from threading import Thread
import os
import color
import platform
import socket
try: from pynput import keyboard
except ImportError: keyboard = None
# unused ports: 26490-26999
port = 26969
address = "192.168.50.172"
s = socket.socket(socket.AF_INET, socket.SOCK_STRE... | python |
expected_output = {
"vrf": {
"User": {
"iid": 4100,
"number_of_entries": 2186,
"eid": {
"0.0.0.0/0": {
"uptime": "1w6d",
"expire": "never",
"via": [
"static-send-map-reques... | python |
import random
from environment import TicTacToe, X, O
class Agent:
def __init__(self, plays=X, episodes=10_000):
"""
Initialise the agent with all the possible board states in a look up table.
Winning states have a value of 1, losing states have -1. All else are 0
"""
... | python |
import random
import uuid
LOGGED_IN_DATA = {
'host': 'https://app.valohai.com/',
'user': {'id': 'x'},
'token': 'x',
}
PROJECT_DATA = {
'id': '000',
'name': 'nyan',
'description': 'nyan',
'owner': 1,
'ctime': '2016-12-16T12:25:52.718310Z',
'mtime': '2017-01-20T14:35:02.196871Z',
... | python |
#!/usr/bin/env python
from distutils.core import setup
LONG_DESCRIPTION = \
'''Convert DNA structural variants in VCF files into BED format'''
setup(
name='svdistil',
version='0.1.0.0',
author='Bernie Pope',
author_email='bjpope@unimelb.edu.au',
packages=['svdistil'],
package_dir={'svdistil'... | python |
import h5py
import numpy as np
import pandas as pd
import lightgbm as lgb
class HDFSequence(lgb.Sequence):
def __init__(self, hdf_dataset, batch_size):
"""
Construct a sequence object from HDF5 with required interface.
Parameters
----------
hdf_dataset : h5py.Dataset
... | python |
import json
from src.main import ReadFile
if __name__ == '__main__':
path_to_annotell_annotation = 'annotell_1.json'
with open(path_to_annotell_annotation, 'r') as content:
json_body = json.load(content)
result = ReadFile().convert(json_body)
print(result) | python |
import httpretty
import pytest
from h_matchers import Any
@pytest.fixture
def pyramid_settings():
return {
"client_embed_url": "http://hypothes.is/embed.js",
"nginx_server": "http://via.hypothes.is",
"via_html_url": "https://viahtml.hypothes.is/proxy",
"checkmate_url": "http://loca... | python |
#! /usr/bin/env python
from metadata_file import MetadataFile
import json
class FalseJSONMetadataFile(MetadataFile):
"""A metadata file type for files that claim to be JSON files but aren't """
category_name = 'FALSE_JSON';
def collect_metadata(self):
print('not parsing json from %s' % self.path)... | python |
"""
# FRACTION TO RECURRING DECIMAL
Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.
If the fractional part is repeating, enclose the repeating part in parentheses.
If multiple answers are possible, return any of them.
It is guaranteed that the leng... | python |
from youtube_search import YoutubeSearch as YS
from config import TOKEN
from aiogram import Bot,types,Dispatcher,utils
from aiogram.utils import executor
from aiogram.types import InputTextMessageContent,InlineQueryResultArticle, ReplyKeyboardMarkup,KeyboardButton
import hashlib
async def on_startup(_):
... | python |
# do imports
import matplotlib.pyplot as plt
import logomaker as logomaker
# load ARS enrichment matrix
ars_df = logomaker.get_example_matrix('ars_enrichment_matrix',
print_description=False)
# load wild-type ARS1 sequence
with logomaker.open_example_datafile('ars_wt_sequence.txt... | python |
"""Portfolio Helper"""
__docformat__ = "numpy"
from datetime import datetime
from dateutil.relativedelta import relativedelta
import yfinance as yf
import pandas as pd
# pylint: disable=too-many-return-statements
BENCHMARK_LIST = {
"SPDR S&P 500 ETF Trust (SPY)": "SPY",
"iShares Core S&P 500 ETF (IVV)": "IVV... | python |
import json
from testtools.matchers import raises, Not
import falcon.testing as testing
import falcon
class FaultyResource:
def on_get(self, req, resp):
status = req.get_header('X-Error-Status')
title = req.get_header('X-Error-Title')
description = req.get_header('X-Error-Description')
... | python |
from django import forms
from .models import AVAILABLE_SLOTS_LEVELS, Spell, Spellbook
class SpellbookForm(forms.ModelForm):
class Meta:
model = Spellbook
fields = ['name']
class SpellbookSlotsForm(forms.Form):
spellbook_pk = forms.IntegerField(label="spellbook")
slot_level_field_names =... | python |
# terrascript/provider/vcd.py
# Automatically generated by tools/makecode.py (24-Sep-2021 15:30:19 UTC)
#
# For imports without namespace, e.g.
#
# >>> import terrascript.provider.vcd
#
# instead of
#
# >>> import terrascript.provider.vmware.vcd
#
# This is only available for 'official' and 'partner' providers.
fr... | python |
import re
import jsonschema
import json
import copy
from anchore_engine.services.policy_engine.engine.policy.exceptions import (
RequiredParameterNotSetError,
ValidationError,
ParameterValidationError,
)
from anchore_engine.subsys import logger
class InputValidator(object):
__validator_description__ ... | python |
from django.http import HttpResponse
from django.db.models import Q
from apiApp.models import Profile, Comment, Tag, User, Group, Post
from apiApp.serializers import ProfileSerializer, CommentSerializer, UserSerializer, TagSerializer, GroupSerializer, PostSerializer
from apiApp.permissions import IsOwnerOrReadOnly
... | python |
from bson.objectid import ObjectId
from app.models.domain.training_data_set import TrainingDataSet
from tests.stubs.models.domain.feature_extraction_data import get_feature_extraction_data_stub_5_1, get_feature_extraction_data_stub_4_2
def get_training_data_set_stub():
return TrainingDataSet(
last_modifi... | python |
"""Slack platform for notify component."""
import asyncio
import logging
import os
from urllib.parse import urlparse
from aiohttp import BasicAuth, FormData
from aiohttp.client_exceptions import ClientError
from slack import WebClient
from slack.errors import SlackApiError
import voluptuous as vol
from homeassistant.... | python |
from main import notion
from commands.run_daily_reset import run_daily_reset
from commands.run_update_duration import run_update_duration
if notion.UPDATE_DURATION:
print("UPDATE_DURATION : ", run_update_duration())
if notion.DAILY_RESET:
print("DAILY_REST : ", run_daily_reset())
| python |
{% extends "_common/main.py" %}
{% set typeStep = "Delete" %}
| python |
#! /usr/bin/python2
#
# Copyright (c) 2017 Intel Corporation
#
# SPDX-License-Identifier: Apache-2.0
#
#
# Configuration file for ttbd (place in ~/.ttbd/) or run ttbd with
# `--config-file PATH/TO/THISFILE`
#
import ttbl.tt_qemu
def nw_default_targets_zephyr_add(letter, bsps = [ 'x86', 'arm', 'nios2',
... | python |
from collections import Counter
anzZweier, anzDreier = 0,0
with open('AdventOfCode_02_1_Input.txt') as f:
for zeile in f:
zweierGefunden, dreierGefunden = False, False
counter = Counter(zeile)
for key,value in counter.items():
if value == 3 and not dreierGefunden:
anzDreier += 1
dr... | python |
import pandas as pd
import numpy as np
from scipy.sparse import data
from sklearn.experimental import enable_iterative_imputer
from sklearn.impute import SimpleImputer
from sklearn.impute import IterativeImputer
from sklearn.impute import KNNImputer
class BasicImputation():
""" This class supports basic imputati... | python |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | python |
# https://leetcode.com/problems/pascals-triangle/description/
class Solution(object):
def generate(self, numRows):
if numRows == 0:
return []
elif numRows == 1:
return [[1]]
elif numRows == 2:
return [[1], [1, 1]]
res = [[1], [1, 1]]
... | python |
from math import ceil
def to_bytes(n):
binary = '{:b}'.format(n)
width = int(ceil(len(binary) / 8.0) * 8)
padded = binary.zfill(width)
return [padded[a:a + 8] for a in xrange(0, width, 8)]
| python |
#!python3
import numpy as np
from magLabUtilities.datafileutilities.timeDomain import importFromXlsx
from magLabUtilities.signalutilities.signals import SignalThread, Signal, SignalBundle
from magLabUtilities.signalutilities.hysteresis import XExpQA, HysteresisSignalBundle
from magLabUtilities.uiutilities.plotti... | python |
#!/usr/bin/env python
#
# 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 ... | python |
# place `import` statement at top of the program
import string
# don't modify this code or the variable may not be available
input_string = input()
# use capwords() here
print(string.capwords(input_string))
| python |
#!/usr/bin/env python
# Select sequences by give seqIDs
import sys
import os
import myfunc
usage="""
usage: selectfastaseq.py -f fastaseqfile
[ ID [ID ... ] ] [-l FILE]
[ [-mine FLOAT ] [-maxe FLOAT] ]
Description: select fasta sequences by seqID from the giv... | python |
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 29 00:56:43 2017
@author: roshi
"""
import pandas as pd
import matplotlib.pyplot as plt
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
from app import app
data = pd.read_csv('./data/youth_to... | python |
import numpy as np
import matplotlib.pyplot as plt
from infinity import inf
from scipy.spatial import ConvexHull
from scipy.spatial.distance import euclidean
from shapely.geometry import LineString, Point
from sklearn.model_selection import KFold
from .metrics import MetaMetrics
from . import util
class Meta:
d... | python |
"""Parameter layer in TensorFlow."""
import tensorflow as tf
from tensorflow.python.ops.gen_array_ops import broadcast_to
def parameter(input_var,
length,
initializer=tf.zeros_initializer(),
dtype=tf.float32,
trainable=True,
name='parameter'):
... | python |
import gym
import torch as th
from stable_baselines3.common.torch_layers import BaseFeaturesExtractor
from torch import nn
class CNNFeatureExtractor(BaseFeaturesExtractor):
def __init__(self, observation_space: gym.spaces.Box, features_dim: int = 128, **kwargs):
super().__init__(observation_space, feature... | python |
#!/usr/bin/env python
# coding: utf-8
import numpy as np
from wopsego import Optimization, ValidOptimumNotFoundError
# Objective
def G24(point):
"""
Function G24
1 global optimum y_opt = -5.5080 at x_opt =(2.3295, 3.1785)
"""
p = np.atleast_2d(point)
return -p[:, 0] - p[:, 1]
# Constraints <... | python |
document = ["Whip-Off World Championships - Gallery","ROWDY DH COURSE PREVIEW! 2019 iXS European Downhill Cup #5, Spicak","IXS Launch the Trigger FF, The Lightest Full Face Out There.","Watch: Breck Epic Day 2","Cam Zink Slams Hard on a 110 Foot Backflip Attempt.","Pivot’s All-New Mach 4 SL","Meet The Riders And Their ... | python |
"""Test the Aurora ABB PowerOne Solar PV sensors."""
from datetime import timedelta
from unittest.mock import patch
from aurorapy.client import AuroraError
from homeassistant.components.aurora_abb_powerone.const import (
ATTR_DEVICE_NAME,
ATTR_FIRMWARE,
ATTR_MODEL,
ATTR_SERIAL_NUMBER,
DEFAULT_INTE... | python |
from typing import Generic, List, Optional, TypeVar
from py_moysklad.entities.context import Context
from py_moysklad.entities.meta_entity import MetaEntity
T = TypeVar("T", bound=MetaEntity)
class ListEntity(MetaEntity, Generic[T]):
context: Optional[Context]
rows: Optional[List[T]]
| python |
from .script import test
def main():
test()
| python |
def rosenbrock_list(**kwargs):
num_fns = kwargs['functions']
# if num_fns > 1:
# least_sq_flag = true
# else:
# least_sq_flag = false
x = kwargs['cv']
ASV = kwargs['asv']
# get analysis components
#an_comps = kwargs['analysis_components']
#print an_comps
f0 = ... | python |
from django.test import TestCase
from ..factories import UrlFactory
from ..helpers import BASE62IdConverter
from ..models import Url
class TestUrlManager(TestCase):
def setUp(self):
self.url_objs = [UrlFactory() for i in range(100)]
def test_get_by_shortcut(self):
received_url_obj = [
... | python |
from Pluto.Libraries.Libraries.GLM import *
| python |
""" BOVI(n)E getsecuritygroup endpoint """
import json
import boto3
from botocore.exceptions import ClientError
from lib import rolesession
def get_instance_info(session, account, sg_id):
""" Get EC2 instance info for a specific security group.
:param session: AWS boto3 session
:param account: AWS accou... | python |
from typing import Dict
def count_duplicates(sample_dict: Dict) -> int:
"""takes a single dictionary as an argument and returns the number of values that appear two or more times
>>> sample_dict = {'red': 1, 'green': 1, 'blue': 2, 'purple': 2, 'black': 3, 'magenta': 4}
>>> count_duplicates(sample_dict)
... | python |
#!/usr/bin/env python
# ----------------------------------------------------------------------------
# Copyright (c) 2013--, scikit-bio development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# ---------------------... | python |
# This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
"""This module contains function declarations for several functions of libc
(based on ctyp... | python |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: mars/serialize/protos/chunk.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import ... | python |
def subset(arr, ind, sub, ans):
if ind == len(arr):
return ans
for i in range(ind, len(arr)):
temp = sub.copy()
temp.append(arr[i])
ans.append(temp)
subset(arr, i + 1, temp, ans)
return ans
arr = [1, 2, 3]
ans = []
ans = subset(arr, 0, [], ans)
for i in range(len(ans)):
print(ans[i])
| python |
import numpy as np
import os
from scipy.io import loadmat
from sklearn.datasets import load_svmlight_file
def gisette2npz():
data_path = "./dataset/GISETTE"
train_data = np.loadtxt(os.path.join(data_path, "GISETTE/gisette_train.data"))
train_labels = np.loadtxt(os.path.join(data_path, "GISETTE/gisette_tr... | python |
""" Web application main script. """
import os
from typing import Any, Dict, List
import cfbd
import streamlit as st
import college_football_rankings as cfr
import ui
import ui.rankings
import ui.schedule
from college_football_rankings import iterative
FIRST_YEAR: int = 1869
LAST_YEAR: int = 2020
RANKINGS_LEN = 25
... | python |
import app.api.point
import app.api.track
import app.api.tracker
import app.api.user
| python |
from functools import wraps
from flask import session, flash, redirect, url_for
from app.log import get_logger
logger = get_logger(__name__)
# Login required decorator
def login_required(f):
@wraps(f)
def wrap(*args, **kwargs):
if "logged_in" in session:
return f(*args, **kwargs)
... | python |
#!/usr/bin/env python
"""
Functions for building tutorial docs from
Libre Office .fodt files using PanDoc
Required formats are:
html
pdf
(eBook)
pdf will need to be generated by Sphinx
via LaTeX intermediate
""" | python |
num1 = int(input('Primeiro valor: '))
num2 = int(input('Segundo valor: '))
num3 = int(input('Treceiro valor: '))
# verificando qual é o menor
menor = num1
if num2 < num1 and num2 < num3:
menor = num2
if num3 < num1 and num3 < num2:
menor = num3
# verificando qual é o maior
maior = num1
if num2 > num1 and num2 >... | python |
from collections import defaultdict
from dataclasses import dataclass
from typing import List
import torch
import torch.nn as nn
from luafun.model.actor_critic import ActorCritic
class TrainEngine:
def __init__(self, train, model, args):
self.engine = LocalTrainEngine(*args)
@property
def weigh... | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2019-01-09 09:04
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('submission', '0008_submission_sender'),
]
operations = [
migrations.AlterF... | python |
from .core import Event, EventType
class JoyAxisMotion(Event):
__slots__ = ('axis', 'value', )
type = EventType.JOY_AXIS_MOTION
def __init__(self, source, axis, value):
super().__init__(source)
self.axis = axis
self.value = value
def __repr__(self):
return f'<{self._... | python |
import numpy as np
import pytest
from psydac.core.bsplines import make_knots
from psydac.fem.basic import FemField
from psydac.fem.splines import SplineSpace
from psydac.fem.tensor import TensorFemSpace
from psydac.fem.vector import ProductFemSpace
from psydac.f... | python |
from pyrules.dictobj import DictObject
class RuleContext(DictObject):
"""
Rule context to store values and attributes (or any object)
The rule context is used to pass in attribute values that
for the rules to consider. A rule does not have access to
any other data except provided in this rule... | python |
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import numpy as np
import tensorflow as tf
from ladder_network import tensor_utils
from ladder_network.wrappers import Registry
initializers = Registry('Initialization')
@initializers.register('glorot_un... | python |
import netns
import pdb
fin = open("host.config", "r")
_ = fin.readline()
host_mnet_pid = int(fin.readline().split()[0])
with netns.NetNS(nspid=host_mnet_pid):
from scapy.all import *
class sync_header(Packet):
name = "sync_header"
fields_desc = [\
BitField("msg_type", 0, 8),\
... | python |
import unittest
from cellular_automata_population_python import Model
class TestModel(unittest.TestCase):
def setUp(self):
"""Set up a model"""
self.model = Model.Model()
self.model.run()
def test_model(self):
"""Test that the model is not null"""
self.assertIsNotNone... | python |
from functools import cached_property
from typing import Tuple
from prompt_toolkit.completion import Completer
from .argument_base import ArgumentBase
from ..errors import FrozenAccessError
from ..utils import abbreviated
class FrozenArgument(ArgumentBase):
"""An encapsulation of an argument which can no longer... | python |
##################################################################################
#
# By Cascade Tuholske on 2019.12.31
# Updated 2020.02.23
#
# Modified from 7_make_pdays.py now in oldcode dir
#
# NOTE: Fully rewriten on 2021.02.01 see 'oldcode' for prior version / CPT
#
# These are the functions needed ... | python |
#!/usr/bin/env python3
import os, logging
from argparse import ArgumentParser
from mg996r import MG996R
start_degree = 360
state_file = '.servo-state'
if __name__ == '__main__':
# set logging level
logging.basicConfig(level=logging.DEBUG)
# parse arguments
parser = ArgumentParser()
parser.add_arg... | python |
import threading
import random
from time import sleep
from math import sqrt,cos,sin,pi
from functools import partial
from Tkinter import *
import tkMessageBox as messagebox
from ttk import *
import tkFont
from PIL import Image, ImageTk
import numpy as np
import networkx as nx
from event import myEvent
from Object im... | python |
# -*- coding: utf-8 -*-
"""
@author:XuMing(xuming624@qq.com)
@description: evaluate with mscc data set
The function create_mscc_dataset is Copyright 2016 Oren Melamud
Modifications copyright (C) 2018 Tatsuya Aoki
This code is based on https://github.com/orenmel/context2vec/blob/master/context2vec/eval/mscc_text_token... | python |
# Source
# ======
# https://www.hackerrank.com/contests/projecteuler/challenges/euler011
#
# Problem
# =======
# In the 20x20 grid (see Source for grid), four numbers along a diagonal
# line have been marked in bold.
#
# The product of these numbers is 26 x 63 x 78 x 14 = 1788696.
#
# What is the greatest product of f... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.