content stringlengths 5 1.05M |
|---|
import logging
import io
import os
import os.path
import platform
import sys
from collections import deque, OrderedDict
from datetime import datetime, timezone, timedelta
from itertools import islice
from operator import attrgetter
from ..logger import create_logger
logger = create_logger()
from .time import to_local... |
''' Program to connect with database and update the employee record of entered empno. '''
from utils import clear_screen
from sqlTor import SqlTor
from q18_dbSearch import get_employee
from q17_dbRecord import input_employee_details
def update_employee(cursor):
''' Update an employee '''
emp = get_employee... |
#!/usr/bin/env python
"""
A script that imports and verifies metadata and then dumps it in a basic
dictionary format.
"""
import sys
from saml2.mdstore import MetaDataExtern
from saml2.mdstore import MetaDataFile
MDIMPORT = {
"swamid": {
"url": "https://kalmar2.org/simplesaml/module.php/aggregator/?id=... |
import random
import torch as t
from py.data.XYDataset import XYDataset
from py.util.Config import dtype, device
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
import numpy as np
en_stops = set(stopwords.words('english'))
# TODO: move into more reusable class
class Embedding():
def __in... |
from typing import Tuple
import numpy as np
from numpy import ndarray
from skfem.element import DiscreteField
from skfem.quadrature import get_quadrature
from .basis import Basis
class FacetBasis(Basis):
"""Basis functions evaluated at quadrature points on the element boundaries.
Initialized and used simil... |
import validators as _v
from rest_framework import serializers
from .models import Check
from autotasks.models import AutomatedTask
from scripts.serializers import ScriptSerializer, ScriptCheckSerializer
class AssignedTaskField(serializers.ModelSerializer):
class Meta:
model = AutomatedTask
... |
#! /usr/bin/env python
# This script is to read from a Active Directory Server
# to get sAMAccountName and objectGUID to transform them
# to SQL statements for a specific user table
import ldap
import getpass
import uuid
LDAPURL = "ldaps://ldapserver"
DOMAIN = "example.com"
# ask for login credentials
USER = raw_input... |
from talon.api import lib
from talon.voice import Context, ContextGroup, talon
from talon.engine import engine
from talon import app
def set_enabled(enable):
if enable:
talon.enable()
app.icon_color(0, 0.7, 0, 1)
else:
talon.disable()
app.icon_color(1, 0, 0, 1)
lib.menu_chec... |
#!/usr/bin/env python
u"""
convert_calendar_decimal.py
Written by Tyler Sutterley (07/2020)
Converts from calendar date into decimal years
Converts year, month (day, hour, minute, second)
into decimal years taking into account leap years
CALLING SEQUENCE:
t_date = convert_calendar_decimal(year, month)
t_d... |
# Bep Marketplace ELE
# Copyright (c) 2016-2021 Kolibri Solutions
# License: See LICENSE file or https://github.com/KolibriSolutions/BepMarketplace/blob/master/LICENSE
#
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('presentations', '0001_initial'),
]
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 23 14:48:36 2020
@author: arest
"""
import argparse,sys
import numpy as np
from jwst_SNR import jwst_SNRclass
if __name__ == '__main__':
parser = argparse.ArgumentParser(usage="create exposure time table for a given set of filters, mags, and t... |
# http://www.codewars.com/kata/55192f4ecd82ff826900089e/
def divide(weight):
return weight > 2 and weight % 2 == 0
|
import numpy as np
from kb_learning.envs import ObjectEnv
from kb_learning.tools import rot_matrix, compute_robust_mean_swarm_position
from gym import spaces
class ObjectAbsoluteEnv(ObjectEnv):
_observe_objects = True
def __init__(self,
num_kilobots=None,
object_shape='qua... |
"""
__author__: Abhishek Thakur
"""
import datetime
import pytorch_lightning as pl
import segmentation_models_pytorch as smp
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torch.nn.modules import BCEWithLogitsLoss
from tqdm import tqdm
from wtfml.engine.image.embedder.utils im... |
print("First Number:")
first_number = int(input())
print("Second Number:")
second_number = int(input())
sum = first_number + second_number
print("Sum: " + str(sum)) |
class BookStorage:
def __init__(self, data=[]):
self.data = data
def add(self, book):
self.data.append(book)
return True
def searchById(self, id):
return self.data[id]
def giveAll(self):
return self.data |
import attr
import copy
import six
def interpretBoolean(s):
"""
Interpret string as a boolean value.
"0" and "False" are interpreted as False. All other strings result in
True. Technically, only "0" and "1" values should be seen in UCI files.
However, because of some string conversions in Pyth... |
class PurplexError(Exception):
pass
class TokenMatchesEmptyStringError(PurplexError):
'''Raised when TokenDef regex matches the empty string.'''
def __init__(self, regexp):
message = 'token {!r} matched the empty string'.format(regexp)
super(TokenMatchesEmptyStringError, self).__init__(me... |
# Generated by Django 2.0.3 on 2018-06-22 19:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("main", "0010_remove_line_replicate")]
operations = [
migrations.AlterField(
model_name="protocol",
name="categorization",
... |
from datetime import datetime, timedelta
from django.db.models import Count
from django.db.models.functions import TruncDate, TruncYear
from django.shortcuts import render
from account.models import User
from dispatcher.manage import ping
from dispatcher.models import Server
from problem.models import Problem
from su... |
import struct
import snap7
from snap7 import util
class DTbool:
def __init__(self, readBuffer,boolIndex):
self.readBuffer=readBuffer
self.boolIndex=boolIndex
def readValue (self,offset):
result=snap7.util.get_bool(self.readBuffer,offset,self.boolIndex)
return result
|
import serial
import time
import fnmatch
import sys
def _auto_detect_serial_unix(preferred_list=['*']):
import glob
glist = glob.glob('/dev/ttyUSB*') + glob.glob('/dev/ttyACM*')
ret = []
for d in glist:
for preferred in preferred_list:
if fnmatch.fnmatch(d, preferred):
... |
#####################################################################
# #
# /batch_compiler.py #
# #
# Copyright 2013, Monash University ... |
from JumpscaleCore.servers.tests.base_test import BaseTest
from Jumpscale import j
from smtplib import SMTP
from imbox import Imbox
from imapclient import IMAPClient
class TestSMTPIMAP(BaseTest):
def test001_check_smtp_save_message_in_bcdb(self):
"""
SMTP server should connect to 'main' bcdb insta... |
'''Common implementation for routing clear triggers'''
# python
from functools import partial
# genie libs
from genie.libs.sdk.libs.utils.mapping import Mapping
from genie.libs.sdk.triggers.clear.clear import TriggerClear, verify_clear_callable
from genie.libs.sdk.libs.utils.triggeractions import CompareUptime
# Ign... |
import unittest, pytest, os
from declarativeunittest import raises
ontravis = 'TRAVIS' in os.environ
from construct import *
from construct.lib import *
class TestThis(unittest.TestCase):
def test_this(self):
assert repr(this) == "this"
this_example = Struct(
# straight-forward usag... |
# -*- coding: utf-8 -*-
import cv2
import numpy as np
from PIL import Image
import re
from thumbor.filters import BaseFilter, filter_method
from thumbor_extras.filters import rainbow
class Filter(BaseFilter):
@filter_method(
BaseFilter.PositiveNonZeroNumber,
BaseFilter.DecimalNumber,
BaseFi... |
import os
import argparse
from trainer import SemanticSeg
import pandas as pd
import random
from PIL import Image
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from rcnn.config import INIT_TRAINER, SETUP_TRAINER, CURRENT_FOLD, PATH_LIST, FOLD_NUM, ROI_NAME,TEST_PATH
fro... |
from django.conf import settings
from django.urls import path, re_path, reverse_lazy
from django.conf.urls.static import static
from django.conf.urls import url, include
from django.contrib import admin
from django.views.generic.base import RedirectView
from graphene_django.views import GraphQLView
from rest_framewor... |
"""
AWS Example
"""
import fire
import pkg
if __name__ == '__main__':
fire.Fire(pkg.aws.Handler)
|
"""
@author: Min Du (midu@paloaltonetworks.com)
Copyright (c) 2021 Palo Alto Networks
"""
import time
import logging
from utils import misc
from utils import const
from worker import combo_selection
if __name__ == '__main__':
misc.init_logger(const.get_data_preparation_logs_filename())
logger = logging.getL... |
# -*- coding: utf-8 -*-
"""
> 007 @ Facebook
~~~~~~~~~~~~~~~~
Given the mapping a = 1, b = 2, ... z = 26, and an encoded message, count the
number of ways it can be decoded.
For example, the message '111' would give 3, since it could be
decoded as 'aaa', 'ka', and 'ak'.
__
You can... |
# -*- coding: utf-8 -*-
"""Wrapper to run ML from the command line.
:copyright: Copyright (c) 2020 RadiaSoft LLC. All Rights Reserved.
:license: http://www.apache.org/licenses/LICENSE-2.0.html
"""
from __future__ import absolute_import, division, print_function
from pykern.pkcollections import PKDict
from pykern.pkde... |
# Generated by Django 2.0.2 on 2018-02-19 12:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('website', '0006_video_contest_vote'),
]
operations = [
migrations.AlterField(
model_name='profile',
name='voted_vide... |
import pandas as pd
import numpy as np
from collections import namedtuple
from typing import Tuple, List, Iterator, Any
from .. import spec as S
from ..dsl import Node, AtomNode, ParamNode, ApplyNode
from ..visitor import GenericVisitor
from .interpreter import Interpreter
from .post_order import PostOrderInterpreter... |
"""
Extra exception types that may be thrown in CoralNet methods.
These can be useful if:
- When catching exceptions that you've thrown, you don't want
to catch any exceptions that you didn't anticipate. For example, perhaps
you were going to throw and catch a ValueError in some case, but you're
worried that you'll a... |
import LanguageModel
import argparse
import torch
import sys
import time
import resource
torch.no_grad()
parser = argparse.ArgumentParser()
parser.add_argument('--checkpoint', default='models/test.json')
args = parser.parse_args()
model = LanguageModel.LanguageModel()
model.load_json(args.checkpoint)
model.eval()
e... |
from __future__ import unicode_literals
from django.shortcuts import render, HttpResponse
def index(request):
response = "Hello, I am your first request!"
return render(request, "Amniotic_App/index.html")
|
# -*- coding: utf-8 -*-
from essentia.streaming import *
import essentia.standard as es
import essentia
import librosa
import librosa.display
import numpy as np
def melspectrogram(audio, sampleRate=44100, frameSize=2048, hopSize=1024,
window='blackmanharris62', zeroPadding=0, center=True,
... |
import torch.nn as nn
from torch.autograd import Variable
from torch.nn.utils import weight_norm
class RNN(nn.Module):
"""
Base RNN class
"""
def __init__(self, input_size, hidden_size, nlayers, embed_dim,
rnn_type, pad_idx, use_cuda, dropout, bidirect):
super().__init__()
... |
import nltk
from nltk.translate import AlignedSent
from nltk.translate.ibm2 import (
IBMModel2,
Model2Counts
)
from tqdm import tqdm
class IBMModel2WithProgressbar(IBMModel2):
def __init__(
self,
sentence_aligned_corpus,
iterations,
probability_tables=None
... |
"""Fixtures for Forecast.Solar integration tests."""
import datetime
from typing import Generator
from unittest.mock import MagicMock, patch
import pytest
from homeassistant.components.forecast_solar.const import (
CONF_AZIMUTH,
CONF_DAMPING,
CONF_DECLINATION,
CONF_MODULES_POWER,
DOMAIN,
)
from h... |
import unittest
from jsonasobj2 import JsonObj, loads
from linkml import METAMODEL_CONTEXT_URI, META_BASE_URI
from linkml_runtime.utils.context_utils import merge_contexts
json_1 = '{ "ex": "http://example.org/test/", "ex2": "http://example.org/test2/" }'
json_2 = '{ "foo": 17, "@context": { "ex": "http://example.or... |
# Copyright (c) 2015 Intel 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... |
# coding=utf-8
# Copyright 2020 The Google Research Authors.
#
# 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 applicab... |
import os
import time
import torch
import logging
import argparse
from utils.train import train
from utils.hparams import HParam
from utils.writer import MyWriter
from utils.graph_reader import read_graph
from dataset.dataloader import create_dataloader
if __name__ == '__main__':
parser = argparse.ArgumentParser... |
import os
import re
import logging
from collections import OrderedDict
import xml.etree.ElementTree as ET
import penman
from penman.models.noop import NoOpModel
logger = logging.getLogger(__name__)
# Cache for Penman graphs so they only need to be loaded once
pgraph_cache = {}
def load_amrs_cached(amr_fpath):
... |
import requests
import turtle
### Implementation details
# Global mutable state. Forgive me.
state = {
'connected_to_bot': False,
'window': None,
'turtle': None,
'distance_traveled': 0,
}
# These measurements are in "steps", which are basically pixels.
WCB_WIDTH = 500
WCB_HEIGHT = 360
SUGGESTED_REIN... |
import adv.adv_test
import ieyasu
from slot.a import *
def module():
return Ieyasu
class Ieyasu(ieyasu.Ieyasu):
comment = ''
def prerun(this):
super().prerun()
from adv.adv_test import sim_duration
if this.condition('always poisoned'):
this.afflics.poison.resist=0
... |
#functions to handle request to microsoft store
class msft():
#color terminal output
Red = '\033[91m'
Green = '\033[92m'
Yellow = '\033[93m'
Endc = '\033[0m'
#button html classes
X_class_text = '_-_-node_modules--xbox-web-partner-core-build-pages-BundleBuilder-Components-BundleBuilderHead... |
from enum import Enum, auto
from parse.node import NodeType, NodeFunctionExpression
from interpreter.typing.basic_type import BasicType
from interpreter.function import Function
from interpreter.basic_value import BasicValue
class VariableType(Enum):
Auto = 'auto'
Int = 'int'
String = 'str'
... |
#!/usr/bin/env python3
import multiprocessing
import numpy as np
import os
import re
import subprocess
import sys
class colors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.24 on 2020-07-06 18:23
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('emgapi', '0026_auto_20200612_1102'),
]
operations... |
# Copyright (c) 2017 Dell Inc. or its subsidiaries.
# 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/licenses/LICENSE-2.0
#
# ... |
import sys
import numpy as np
import unittest
from numba.core.compiler import compile_isolated, Flags
from numba import jit, njit
from numba.core import types
from numba.tests.support import TestCase, MemoryLeakMixin
from numba.core.datamodel.testing import test_factory
enable_pyobj_flags = Flags()
enable_pyobj_flag... |
from .modules.common import *
import numpy as np
import os
class Group(object):
def __init__(self,npart,index):
self.index = index
self.npart_total = npart
def readpstar(catdir,snapnum,groupIndex,**kwargs):
"""Read and return info from P-Star catalogues.
Parameters
----------
catd... |
from .dataset import EnvironmentDataset, NodeTypeDataset
from .preprocessing import collate, collate_sdc, collate_sdc_test, get_node_timestep_data, get_timesteps_data, restore, get_relative_robot_traj
|
#We will take categorical data and turn it into features
#VectorizationL converting arbitray data into well behaved vectors
#Categorical Features
#housing price data
data = [
{'price': 850000, 'rooms': 4, 'neighborhood': 'Queen Anne'},
{'price': 700000, 'rooms': 3, 'neighborhood': 'Fremont'},
{'price': 650... |
""" Advent of Code, 2015: Day 12, a """
import json
with open(__file__[:-5] + "_input") as f:
inputs = [line.strip() for line in f]
def find_numbers(data):
""" Recursively find numbers in JSON data except dicts with "red" value """
if isinstance(data, int):
return [data]
numbers = []
if ... |
"""
Test Epilog script.
"""
from unittest import mock
import pytest
from lm_agent.workload_managers.slurm.slurmctld_epilog import epilog
@pytest.mark.asyncio
@mock.patch("lm_agent.workload_managers.slurm.slurmctld_epilog.get_job_context")
@mock.patch("lm_agent.workload_managers.slurm.slurmctld_epilog.update_report"... |
# function delay(n) {
# n = n || 2000;
# return new Promise(done => {
# setTimeout(() => {
# done();
# }, n);
# });
# }
# var sections = document.querySelectorAll('.report-section')
# for (var index = 0; index < sections.length; index++) {
# sections[index].querySelector('.wbic-ic-overflow').... |
"""
Copyright StrangeAI authors @2019
assume you have to directly which you want
convert A to B, just put all faces of A person to A,
faces of B person to B
"""
import torch
from torch.utils.data import Dataset
import glob
import os
from alfred.dl.torch.common import device
import cv2
from PIL import Image
from torch... |
from flask import Flask, g, render_template, url_for, abort
from flask import make_response, request
from jinja2 import FileSystemLoader
from sqlalchemy.sql.expression import func
import itertools
import pickle
from trajectory import config as TRJ
from trajectory.utils.prereqs import get_prereq_graph
from trajectory.u... |
from Katna.video import Video
from Katna.image import Image
from .version import __version__
|
from datetime import datetime
import csv
import re
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup
from jumia.database import DatabaseSessio... |
# Generated by Django 3.0.7 on 2020-07-22 11:44
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('contr_clienti', '0009_remove_contract_document'),
]
operations = [
migrations.AddField(
model_n... |
# Advent of Code 2021 - Day 2 Part 1
# 2 Dec 2021 Brian Green
#
# Problem:
# Calculate the horizontal position and depth you would have after following the planned course.
# What do you get if you multiply your final horizontal position by your final depth?
#
import os
filename = "data" + os.sep + "brian_aoc202102.d... |
"""
Segment level tests.
"""
from fontTools.misc import bezierTools as ftBezierTools
import defcon
from .tools import (
roundPoint,
unwrapPoint,
calculateAngle,
calculateAngleOffset,
calculateLineLineIntersection,
calculateLineCurveIntersection,
calculateLineLength,
calculateLineThrough... |
from __future__ import annotations
import datetime
import enum
from typing import Any, Dict, List, Literal, NewType, Optional, TYPE_CHECKING, Union
from pydantic import (
Extra,
Field,
PrivateAttr,
StrictBool,
ValidationError,
root_validator,
validator,
)
from server import logger
from ta... |
#!/usr/bin/env python
'''
CUDA-accelerated Computer Vision functions
'''
# Python 2/3 compatibility
from __future__ import print_function
import numpy as np
import cv2 as cv
import os
from tests_common import NewOpenCVTests, unittest
class cuda_test(NewOpenCVTests):
def setUp(self):
super(cuda_test, se... |
# coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from openapi_server.models.base_model_ import Model
from openapi_server import util
class ExpertiseLevels(Model):
"""NOTE: This class is auto generated by OpenAPI... |
from spaceone.api.cost_analysis.v1 import job_pb2, job_pb2_grpc
from spaceone.core.pygrpc import BaseAPI
class Job(BaseAPI, job_pb2_grpc.JobServicer):
pb2 = job_pb2
pb2_grpc = job_pb2_grpc
def cancel(self, request, context):
params, metadata = self.parse_request(request, context)
with s... |
from utils.solution_base import SolutionBase
class Solution(SolutionBase):
def solve(self, part_num: int):
self.test_runner(part_num)
func = getattr(self, f"part{part_num}")
result = func(self.data)
return result
def test_runner(self, part_num):
test_inputs = self.get... |
import sys
from lexer import CalcLexer
from parser import CalcParser
def repl(lexer, parser):
print('Custom language v0.0.1')
print('Type "exit" to quit the REPL')
linecount = 0
while True:
try:
text = input(f'λ({linecount}) ⇒ ')
except EOFError:
break
... |
# encoding: utf8
#
# spyne - Copyright (C) Spyne contributors.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version... |
# Copyright 2013, Michael H. Goldwasser
#
# Developed for use with the book:
#
# Data Structures and Algorithms in Python
# Michael T. Goodrich, Roberto Tamassia, and Michael H. Goldwasser
# John Wiley & Sons, 2013
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of... |
'''
AAA lllllll lllllll iiii
A:::A l:::::l l:::::l i::::i
A:::::A l:::::l l:::::l iiii
A:::::::A l:::::l l:::::l
... |
# Generated by Django 3.2.7 on 2021-11-14 13:01
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('school_management', '0007_student_otherschool'),
]
operations = [
migrations.RemoveField(
model_name='student',
name='others... |
from creds import *
import tweepy
import markovify
import os
import argparse
# Execute in script directory
abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname)
def generate_tweet(test_mode=False):
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(... |
#!/usr/bin/env python3
import os, re, sys
class Validator( object ):
def __init__( self, vmap = dict(), **opt ):
self._validator_map = vmap
if __name__ == "__main__":
pass |
import os
from setuptools import setup, find_packages
from setuptools.command.install import install
from setuptools.command.develop import develop
import pathlib
NAME = 'git-scan'
DESCRIPTION = "Scan local or remote git repositories for history divergent from origin"
URL = 'https://github.com/johnaparker/git-scan'
EM... |
import sys
import inspect
import pytest
from botorum.servicecatalog.models.portfolio import Portfolio
from botorum.servicecatalog.models.tagoption import TagOption
@pytest.fixture(scope="module")
def tagoption_config():
return {
'Key': 'test-portfolio-tagoption',
'Value': 'arbitrary'
}
@pyt... |
#!/usr/bin/env python3
# coding: utf-8
#
# Project: Azimuthal integration
# https://github.com/silx-kit/pyFAI
#
# Copyright (C) 2015-2020 European Synchrotron Radiation Facility, Grenoble, France
#
# Principal author: Jérôme Kieffer (Jerome.Kieffer@ESRF.eu)
#
# Permission is hereby granted, f... |
"""
The :mod:`sklearn.model_selection._validation` module includes classes and
functions to validate the model.
"""
#
# Authors of sklearn.model_selection._validation:
# Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Gael Varoquaux <gael.varoquaux@normalesup.org>
# Olivier Grisel <olivier.g... |
"""Test suite for the notion_paperpile_ package."""
|
from collections import OrderedDict
from toml import TomlEncoder
from toml import TomlDecoder
class TomlOrderedDecoder(TomlDecoder):
def __init__(self):
super(self.__class__, self).__init__(_dict=OrderedDict)
class TomlOrderedEncoder(TomlEncoder):
def __init__(self):
super(self.__class__, ... |
# 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 logging
import pprint
import sys
from typing import Any, List
import torch
from omegaconf import DictConfig, OmegaConf
from vissl.confi... |
from datetime import datetime
def greetingTime():
current_hour = datetime.now().hour
if current_hour < 12:
return "Buenos días"
elif 12 <= current_hour < 18:
return "Buenas tardes"
else:
return "Buenas noches" |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2019-08-18 06:59
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('account', '0011_auto_20190818_0653'),
]
operations =... |
import os
import shutil
import tempfile
import unittest
from lobster.core import Dataset
from lobster import fs, se, util
class TestDataset(unittest.TestCase):
@classmethod
def setUpClass(cls):
path = os.path.expandvars(
os.environ.get('LOBSTER_STORAGE', '/hadoop/store/user/') +
... |
# -*- coding: utf-8 -*-
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import numpy as np
### Hyperparameters ###
IMG_X = 28
IMG_Y = 28
INPUT_DIM = IMG_X * IMG_Y
OUTPUT_DIM = 10
LR = 0.1
MAX_LOOP = 20000
BATCH_SIZE = 100
### Hyperparameters ###
# load data
mnist =... |
import demes
import numpy as np
import matplotlib
from demesdraw import utils
def size_history(
graph: demes.Graph,
ax: matplotlib.axes.Axes = None,
colours: utils.ColourOrColourMapping = None,
log_time: bool = False,
log_size: bool = False,
title: str = None,
inf_ratio: float = 0.1,
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'chengzhi'
from tqsdk import TqApi, TargetPosTask
'''
如果当前价格大于10秒K线的MA15则开多仓
如果小于则平仓
'''
api = TqApi()
# 获得 m1909 10秒K线的引用
klines = api.get_kline_serial("DCE.m1909", 10)
# 创建 m1909 的目标持仓 task,该 task 负责调整 m1909 的仓位到指定的目标仓位
target_pos = TargetPosTask(api, "DCE... |
import glob
import json
import anyconfig
import scalpl
from datetime import datetime
from .logger_setup import logger
# Class: ConfigManager
# Function: To store and load settings for BoxBot 2.0
# :
# : - Register a setting to the bot's config model
# : - Retrieve a value from the bot's con... |
class ThemeConfig:
def __init__(self, colors, extras, base_text_states):
self._light_scheme=f"""[ColorEffects:Disabled]
Color={extras['LightSurface1']}
ColorAmount=0.55
ColorEffect=3
ContrastAmount=0.65
ContrastEffect=0
IntensityAmount=0.1
IntensityEffect=0
[ColorEffects:Inactive]
ChangeSelectionC... |
def maior(a, b):
return (a + b + abs(a - b))/2
inp = list(map(int, input().split()))
a, b, c = inp
print('%d eh o maior' % (maior(a, maior(b, c))))
|
##
# Copyright (c) 2016, Microsoft Corporation
# 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... |
"""
Import data from dataset, and preprocess it.
To use take advantage of the preprocess in this file, simply import this file to
your python code and call `train_table, valid_table = dataset.preprocess()` to get
all images in one table with their labels and metadata.
Once you have the training and validation table, ... |
import asyncio
from playwright.async_api import async_playwright
from urllib.parse import urlparse
from pathlib import Path
'''
popup
page.onDialog(dialog -> {
assertEquals("alert", dialog.type());
assertEquals("", dialog.defaultValue());
assertEquals("yo", dialog.message());
dialog.accept();
});
page... |
LEFT = complex(0, 1)
RIGHT = complex(0, -1)
def read_infect_map(filename):
with open(filename) as f:
infect_map = dict()
for i, line in enumerate(f):
for j, c in enumerate(line):
if c == '#':
infect_map[complex(i, j)] = 'I'
return infect_map
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.