text stringlengths 2 999k |
|---|
ERROR_FIRST = 1000
HASHCHK = 1000
NISAMCHK = 1001
NO = 1002
YES = 1003
CANT_CREATE_FILE = 1004
CANT_CREATE_TABLE = 1005
CANT_CREATE_DB = 1006
DB_CREATE_EXISTS = 1007
DB_DROP_EXISTS = 1008
DB_DROP_DELETE = 1009
DB_DROP_RMDIR = 1010
CANT_DELETE_FILE = 1011
CANT_FIND_SYSTEM_REC = 1012
CANT_GET_STAT = 1013
CANT_GET_WD = 1... |
#!/usr/bin/env python3
#
# Copyright (c) 2020, The OpenThread Authors.
# 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
# ... |
class controller:
def __init__(self):
# print(f'Constructor {self.getName()}')
pass
def __del__(self):
# print(f'Destructor {self.getName()}')
pass
def getName(self):
return self.__class__.__name__
|
#! /usr/bin/env python2
# basics.py - basic SQL commands tutorial
# inspired from the Postgres95 tutorial
# adapted to Python 1995 by Pascal ANDRE
print """
__________________________________________________________________
MODULE BASICS.PY : BASIC POSTGRES SQL COMMANDS TUTORIAL
This module is designed for being... |
from cobra.model.mgmt import InB, RsMgmtBD
from cobra.model.fv import RsProv, RsCons, RsProtBy
from createMo import *
DEFAULT_ENCAP = ''
DEFAULT_QOS = 'unspecified'
DEFAULT_BRIDGE_DOMAIN = ''
DEFAULT_MATCH_TYPE = 'AtleastOne'
QOS_CHOICES = ['level1', 'level2', 'level3', DEFAULT_QOS]
CONTRACT_TYPE_CHOICES = ['provid... |
# -*- coding: utf-8 -*-
"""
flaskext.session
~~~~~~~~~~~~~~~~
Adds server session support to your application.
:copyright: (c) 2014 by Shipeng Feng.
:license: BSD, see LICENSE for more details.
"""
__version__ = '0.4.5'
import os
from logging import getLogger,DEBUG
from .sessions import NullSes... |
#-----------------------------------------------------------------------#
# predict.py将单张图片预测、摄像头检测、FPS测试和目录遍历检测等功能
# 整合到了一个py文件中,通过指定mode进行模式的修改。
#-----------------------------------------------------------------------#
import time
import cv2
import numpy as np
from PIL import Image
from yolo import YOLO
if __n... |
#!h:\zsolt\python\grocerypricecompare\virtual\scripts\python.exe
# See http://cens.ioc.ee/projects/f2py2e/
from __future__ import division, print_function
import os
import sys
for mode in ["g3-numpy", "2e-numeric", "2e-numarray", "2e-numpy"]:
try:
i = sys.argv.index("--" + mode)
del sys.argv[i]
... |
# Copyright (C) 2009-2016, Quentin "mefyl" Hocquet
#
# This software is provided "as is" without warranty of any kind,
# either expressed or implied, including but not limited to the
# implied warranties of fitness for a particular purpose.
#
# See the LICENSE file for more information.
import drake
import drake.cxx
i... |
def count_alphabet(word):
alphabet_cnt_list = [0] * 26
for ch in word:
code = ord(ch)
if code >= 65 and code <= 90:
alphabet_cnt_list[code - 65] += 1
elif code >= 97 and code <= 122:
alphabet_cnt_list[code - 97] += 1
return alphabet_cnt_list
def main():
w... |
import pandas as pd
df = pd.read_csv("day2.txt", names=("dir", "val"), delim_whitespace=True)
def aim(row):
if row.dir=="down":
return row.val
elif row.dir == "up":
return -row.val
return 0
df["aim"] = df.apply(aim, axis=1).cumsum()
depth = df.apply(lambda row: row.val*row.aim if row.dir == ... |
#!/usr/bin/python
import json
import random
import re
import math
def parseLength(length):
m = re.match(r'([0-9]+)(\-([0-9]+))? (inches|feet)', length)
if m.group(3):
height = math.floor((int(m.group(1)) + int(m.group(3))) / 2)
if m.group(4) == 'feet':
height = height * 12
r... |
class Solution:
# array 二维列表
def Find(self, target, array):
# write code here
row = len(array)-1
col = 0
while row>=0 and col<len(array[0]):
if target == array[row][col]:
return True
elif target > array[row][col]:
col+=1
... |
from overtime.tests.algorithms.paths.test_optimality import * |
# buildhistory-web - model definitions
#
# Copyright (C) 2013-2015 Intel Corporation
#
# Licensed under the MIT license, see COPYING.MIT for details
from django.db import models
from datetime import datetime
from django.contrib.auth.models import User
class Build(models.Model):
name = models.CharField(max_length=... |
#!/usr/bin/env python
#
# Copyright 2011 Google Inc. 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
#
# Unless requir... |
"""
Copyright (c) 2018 Intel 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... |
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 18 10:19:28 2017
@author: water
"""
#Reading index.html and editing html to replace phrases
import urllib.request
page = urllib.request.urlopen("file:///Github/dp/internal/deadpool/index.html")
text = page.read().decode("utf8")
x = str(unique_pharmacies)
y = "$" + str(ro... |
#!/usr/bin/env python
import os
import pickle
import tensorflow as tf
import numpy as np
import tf_util
from model import fc_net
from tensorflow.python import debug as tf_debug
from global_defs import GlobalDefs
import load_policy
class GetBatch(object):
def __init__(self, obs, act, shuffle, batch_size):
... |
#Conversor de Moedas
real = float(input('Quanto dinheiro vocẽ tem na carteira? R$ '))
dolar = real / 5.39
print('Com {:.2f} reais você pode comprar US${:.2f} dolar'.format(real, dolar))
|
import time
from selenium import webdriver
from instascrape import Profile
class InstagramDriver():
def __init__(self, username, password) -> None:
self.username = username
self.password = password
self.driver = self.get_webdriver()
self.complete_login()
self._retrieve_cook... |
import os
from time import time
from settings.globalconf import PROJECT_DIR
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
#X_FRAME_OPTIONS = 'ALLOW-FROM *'
ADMINS = (
('Sergey Lentsov', 'serge.lenz@gmail.com'),
)
MANAGERS = ADMINS
# Application definition
INSTALLED_APPS = (
'django.contrib... |
# Copyright (C) 2020 GreenWaves Technologies, SAS
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# This progr... |
# -*- coding: utf-8 -*-
# Copyright 2018 ICON Foundation
#
# 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 o... |
########################################################
# Copyright 2019-2020 program was created VMware, Inc. #
# SPDX-License-Identifier: Apache-2.0 #
########################################################
import requests
from fate_arch.common import log
LOGGER = log.getLogger()
C_HTTP_TEMPLAT... |
# 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.models.all_view import AllView # noqa: F401,E501
from openapi_server.models.free_style_project ... |
import string
from flask import Blueprint, jsonify, request
from flask_cors import CORS
from extensions import db
from models import build_brain
from utils import stop_words
bp = Blueprint('bp', __name__)
CORS(bp)
def trans(data):
query = {
"query": {
"bool": {
"must_not" : {
... |
import os, sys, time, random, argparse
from .share_args import add_shared_args
def obtain_RandomSearch_args():
parser = argparse.ArgumentParser(description='Train a classification model on typical image classification datasets.', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--resum... |
__all__ = [
]
|
from collections import OrderedDict
from pynars.NARS.DataStructures import LinkType, TaskLink, TermLink
from pynars.utils.SparseLUT import SparseLUT
from pynars import Global
from ....RuleMap.add_rule import *
def add_rules__NAL5(sparse_lut: SparseLUT, structure: OrderedDict):
''''''
'''syllogystic rules'''
... |
# Copyright 2017 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
#!/usr/bin/env python3
from mcpi.minecraft import Minecraft
from mcpi import block
mc = Minecraft.create()
x, y, z = mc.player.getPos()
y = mc.getHeight(x + 10, z)
mc.setBlock(x + 10, y + 1, z, block.DIAMOND_BLOCK.id)
mc.postToChat("Destroy the Diamond Block!")
# The 'forcefield' is an area four blocks around the D... |
#!/usr/bin/env python3
import io
import logging
import multiprocessing
import os
import time
import imghdr
from pathlib import Path
from typing import Union
import cv2
import torch
import numpy as np
from loguru import logger
from lama_cleaner.model_manager import ModelManager
from lama_cleaner.schema import Config
... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
from core import settings
from modules.podcast.utils import episode_process_hook
from modules.podcast.models import EpisodeStatus
class TestEpisodeProcessHooks:
def test_call_hook__ok(self, mocked_redis):
mocked_redis.get.return_value = {"total_bytes": 1024}
episode_process_hook(
Episo... |
from enum import Enum, auto
from fastapi import Request
from fastapi.responses import JSONResponse
class ErrCode(Enum):
NO_ERROR = 0
EMAIL_DUPLICATED = auto()
NO_ITEM = auto()
ErrDict = {
ErrCode.NO_ERROR: "정상",
ErrCode.EMAIL_DUPLICATED: "동일한 이메일이 존재합니다.",
ErrCode.NO_ITEM: "해당 항목이 존재하지 않습니다. "... |
import _plotly_utils.basevalidators
class ReversescaleValidator(_plotly_utils.basevalidators.BooleanValidator):
def __init__(self, plotly_name="reversescale", parent_name="heatmapgl", **kwargs):
super(ReversescaleValidator, self).__init__(
plotly_name=plotly_name,
parent_name=paren... |
import pandas as pd
import numpy as np
def generate_noisy_dataframe(df, frac_nulls):
df_mat = df.to_numpy()
tot_values = df_mat.size
null_values = int(tot_values * frac_nulls)
# print(null_values)
arr = np.array([1] * null_values + [0] * (tot_values - null_values))
np.random.shuffle(arr)
... |
"""=========================================
Read Mapping parameter titration pipeline
=========================================
* align reads to the genome using a range of different parameters
* calculate alignment statistics
Requirements
------------
On top of the default CGAT setup, the pipeline requires ... |
import os.path
import numpy as np
import pandas
import pickle
import requests
import ast
import typing
from json import JSONDecoder
from typing import List
from primitive_interfaces.base import PrimitiveBase, CallResult
from d3m_metadata import container, hyperparams, metadata as metadata_module, params, utils
__auth... |
""" yluo - 05/01/2016 creation
Call cnn_preprocess functions to generate data files ready to used by Seg-CNN
"""
import sys
import cnn_preprocess as cp
#print("Setting scale factor to 0: ignoring all external features.")
#scale_fac=0
scale_fac=100 # will use only semantic classes
if sys.argv[1] == "trp":
print(... |
#!/usr/bin/python
# Copyright (c) 2017, 2021 Oracle and/or its affiliates.
# This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Apache License v2.0
# See LICENSE.TXT for d... |
import csv
from typing import List, Dict
from flpy_bank.objects import Record
class DataParser(object):
def parse_file(self, file: str) -> List[Record]:
raise NotImplementedError()
class CsvDataParser(DataParser):
def __init__(self,
delimiter=',',
quote='"'):
... |
from abc import abstractmethod
import torch
import torch.nn as nn
from mvt.cores.ops import ConvModule
from mvt.utils.init_util import bias_init_with_prob, normal_init
from mvt.utils.misc_util import multi_apply
from ..block_builder import HEADS, build_loss
from .base_det_head import BaseDetHead
from .dense_test_mixin... |
#@result Submitted a few seconds ago • Score: 10.00 Status: Accepted Test Case #0: 0s Test Case #1: 0s Test Case #2: 0s Test Case #3: 0s Test Case #4: 0.01s Test Case #5: 0s Test Case #6: 0s Test Case #7: 0s Test Case #8: 0s Test Case #9: 0s
# Enter your code here. Read input from STDIN. Print output to STDOUT
a = (r... |
# Gino, make me rock paper scissors!
import random
print("Welcome to Rock Paper Scissors!")
playerSelection = input("Type in rock, paper, or scissors. ")
# Gino, we are going to generate a random number in order
# to make the computers selection.
randomNumber = random.randint(1, 3)
if randomNumber == 1:
compute... |
from credmon.CredentialMonitors.AbstractCredentialMonitor import AbstractCredentialMonitor
from credmon.utils import atomic_rename
from requests_oauthlib import OAuth2Session
import os
import time
import json
import glob
import tempfile
class OAuthCredmon(AbstractCredentialMonitor):
def should_renew(self, usernam... |
"""
:code:`script_utils.py`
Utilities to support the use of command line sensitivity experiments
"""
import os
import numpy as np
import yaml
from epimodel.pymc3_models.mask_models import *
def get_target_accept_from_model_str(model_type_str):
# default
return 0.9
def get_tree_depth_from_model_str(model_t... |
#!/usr/bin/python3
# Script: 401 Op Challenge Day 45
# Author: Courtney Hans
# Date of latest revision: 12/8/20
# Purpose: Enumeration tool
# Import Libraries
import nmap, socket
# Define variables
scanner = nmap.PortScanner()
# Define functions
# nmap 'steal... |
from django.apps import AppConfig
class TextSearchVectorConfig(AppConfig):
name = 'tsvector_field'
def ready(self):
"""
This supports two use cases for using tsvector_field:
1. Configure your Django project to use tsvecotr_field's DatabaseSchemaEditor
directly by creating... |
"""user-track-collection-mat-views
Revision ID: 5bcbe23f6c70
Revises: 2ff46a8686fa
Create Date: 2021-04-12 20:01:40.395480
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "5bcbe23f6c70"
down_revision = "2ff46a8686fa"
branch_labels = None
depends_on = None
def... |
# Description: Reads a config file, stores values in a dictionary of dictionary and serves request
from ConfigParser import SafeConfigParser
class ConfigManager():
"""Reads a config file, stores in a dictionary of dictionary and serves request"""
def read(self, fileName):
"""Reads the config file fi... |
#!/usr/bin/python
# Copyright 2020 Daniele Moro <daniele.moro@polimi.it>
# Davide Sanvito <davide.sanvito@neclab.eu>
#
# 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
#
# ht... |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import unittest
import torch
from common_testing import TestCaseMixin
from pytorch3d.loss import mesh_... |
'''
data_structures.py
We can compose multiple simple types of values into more complicated structures...
like lists!
'''
# We can assign a list to a variable:
pet_names = ['Yogi', 'Boomer', 'Gunther', 'Banana']
# It's easy to loop over a list
for name in pet_names:
print(name)
# Each item in a list is at a par... |
class FastSort2():
def __init__(self, elems = []):
self._elems = elems
def FS2(self, low, high):
if low >= high:
return
i = low
pivot = self._elems[low]
for m in range(low + 1, high + 1):
if self._elems[m] < pivot:
i += ... |
import unittest
from stability_label_algorithm.modules.dataset_generator.argumentation_system_generator.random.\
random_argumentation_system_generator import RandomArgumentationSystemGenerator
from stability_label_algorithm.modules.dataset_generator.argumentation_system_generator.random.\
random_argumentation_... |
# exported from PySB model 'model'
from pysb import Model, Monomer, Parameter, Expression, Compartment, Rule, Observable, Initial, MatchOnce, Annotation, ANY, WILD
Model()
Monomer('C6A', ['C8pro'])
Monomer('BaxA', ['BaxM', 'BaxA_1', 'BaxA_2', 'SmacM'])
Monomer('Ligand', ['Receptor'])
Monomer('C6pro', ['C3A'])
Monome... |
import torch.nn as nn
import math
__all__ = ['mobilenet_v2_XBNBlock']
import extension as my
def conv_bn(inp, oup, stride):
return nn.Sequential(
nn.Conv2d(inp, oup, 3, stride, 1, bias=False),
nn.BatchNorm2d(oup),
#my.Norm(oup),
nn.ReLU6(inplace=True)
)
def conv_1x1_bn(inp,... |
# Copyright 2017 Intel 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... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2018 Carter Yagemann
#
# 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 ri... |
#! /usr/bin/env python
import os;
SCRIPT_PATH = os.path.dirname(os.path.realpath(__file__));
#GOLDEN_PATH = SCRIPT_PATH + '/../../../golden-bundle';
import sys;
# sys.path.append(SCRIPT_PATH + '/scripts')
#sys.path.append(GOLDEN_PATH + '/src')
import subprocess;
import numpy as np;
# import filesandfolders;
import fa... |
import datetime
import math
import os
import platform
import textwrap
import time
import traceback
import typing as t
from discord import Activity, ActivityType, Color, DiscordException, Embed, Game, Status
from discord import __version__ as discord_version
from discord.ext.commands import Cog, Context, group
import h... |
import logging
import sys
import glob
import os
from fvcore.common.checkpoint import Checkpointer
from naslib.defaults.trainer import Trainer
from naslib.optimizers import DARTSOptimizer, GDASOptimizer, RandomSearch
from naslib.optimizers.discrete.re.optimizer import RegularizedEvolution
from naslib.search_spaces im... |
from __future__ import print_function
from six.moves import cPickle as pickle
import numpy as np
import os
from scipy.misc import imread
import platform
import random
# 读取文件
def load_pickle(f):
version = platform.python_version_tuple() # 取python版本号
if version[0] == "2":
return pickle.load(f) # pickl... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云(BlueKing) available.
Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obt... |
from django.shortcuts import render
from django.core.exceptions import ObjectDoesNotExist
from django.db import transaction
from rest_framework.decorators import api_view, action, permission_classes
from rest_framework.generics import get_object_or_404
from rest_framework.permissions import AllowAny, IsAdminUser, IsAut... |
#!/usr/bin/env python
import sys, re, operator, string
# Auxiliary functions that can't be lambdas
#
def extract_words(obj, path_to_file):
with open(path_to_file) as f:
obj['data'] = f.read()
pattern = re.compile('[\W_]+')
data_str = ''.join(pattern.sub(' ', obj['data']).lower())
obj['data'] = ... |
# © 2020 Nokia
# Licensed under the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
# !/usr/bin/env python3
# coding: utf-8
# Author: Élie de Panafieu <elie.de_panafieu@nokia-bell-labs.com>
from fitting_text_distance.fitting_vectorization.fitting_vectorization import FittingVectorization
from fitting_t... |
"""
based on bingapi.py version 1.0 described here"
Home-page: https://svn.uswaretech.com/bingapi/
Author: Lakshman Prasad, Shabda Raaj
Author-email: lakshman@uswaretech.com
License: UNKNOWN
Modified by mdipierro to work with web2py and on Google App Engine
"""
import gluon.contrib.simplejson as simplejson
imp... |
# -*- coding: utf-8 -*-
'''
Created on 14.10.2019
@author: Katrin Ortmann
'''
import os
from corpus import Doc, Sentence, Token
############################
class Importer(object):
def __init__(self, **kwargs):
for key,val in kwargs.items():
self.__dict__[key] = val
#######################... |
"""
Lasagne implementation of SGDR on WRNs from "SGDR: Stochastic Gradient Descent with Restarts" (http://arxiv.org/abs/XXXX)
This code is based on Lasagne Recipes available at
https://github.com/Lasagne/Recipes/blob/master/papers/deep_residual_learning/Deep_Residual_Learning_CIFAR-10.py
and on WRNs implementation by F... |
import unittest
from nose.tools import assert_equal, assert_true, assert_false
from robotide.robotapi import TestCaseFile
from robotide.controller import Project
from robotide.controller.macrocontrollers import KEYWORD_NAME_FIELD
from robotide.controller.ctrlcommands import (
Undo, FindOccurrences, FindVariableOcc... |
from typing import Any, ClassVar, Dict, List, Optional, TYPE_CHECKING
from ..constants import Constants
from ..config import Config
from .irresource import IRResource
from .irhttpmapping import IRHTTPMapping
from .irtls import IRAmbassadorTLS
from .irtlscontext import IRTLSContext
from .ircors import IRCORS
from .ir... |
from . import Remesh
|
import base64
import json
import random
import string
from datetime import datetime, timedelta
from io import BytesIO
from typing import Dict
import pytest
from boto3.dynamodb.conditions import Key
from botocore import stub
from botocore.config import Config
from botocore.response import StreamingBody
from aws_lambda... |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os, sys
import time
import numpy as np
from scipy.spatial.distance import cdist
import gc
import faiss
import logging
import torch
import torch.nn.functional as F
def swig_ptr_from_FloatTensor(x):
assert x.is_contiguous()
assert x.dtype == torch.float32
... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 6 13:42:53 2019
@author: rdamseh
"""
import GraphPaper2018V1
if __name__=='__main__':
path='data/sim/data56noisy2/'
seg=sio.loadmat(path+'1.mat')['seg']
# testmodel #################
l=sio.loadmat('data/test_model.... |
#!/usr/bin/env python
import numpy as np
import rospy
from geometry_msgs.msg import PoseStamped
from std_msgs.msg import Int32, Bool
from styx_msgs.msg import Lane, Waypoint
from scipy.spatial import KDTree
import math
'''
This node will publish waypoints from the car's current position to some `x` distance ahead.
As... |
from django_tenants.migration_executors import get_executor
from django_tenants.utils import get_tenant_domain_model, get_public_schema_name, schema_exists, get_tenant_database_alias, \
has_multi_type_tenants, get_multi_type_database_field_name
from django_tenants.management.commands import SyncCommon
class Migra... |
from typing import Any
import numpy as np
import plotly.graph_objects as go
from plotly.graph_objects import Figure
from sklearn.linear_model import LinearRegression, Lasso, Ridge
from vizml._dashboard_configs import DASH_STYLE, PLOT_TEMPLATE
from vizml.data_generator import Linear1DGenerator, Linear2DGenerator
from v... |
# Tutorials > 10 Days of Statistics > Day 2: More Dice
# Calculate the probability that two dice will roll two unique values having a sum of 6.
#
# https://www.hackerrank.com/challenges/s10-mcq-2/problem
# challenge id: 21608
#
from fractions import Fraction
n = 0
for i in range(1, 7):
for j in range(1, 7):
... |
# Copyright 2017 The TensorFlow 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/licenses/LICENSE-2.0
#
# Unless required by applica... |
import mlflow
import argparse
import os
import logging
from src.utils.common import read_yaml, create_directories
STAGE = "MAIN" ## <<< change stage name
create_directories(["logs"])
with open(os.path.join("logs", 'running_logs.log'), "w") as f:
f.write("")
logging.basicConfig(
filename=os.pa... |
"""
An example module for future contributors to reference using events.
"""
from discord.ext import commands
class ExampleEventModule(commands.Cog):
"""
An example class that inherits from commands.Cog for contributors to reference.
This one uses events unlike the one in example_command_module
"""
... |
from typing import List
from constants import *
from creeps.base import RoleBase
from creeps.behaviors.military import MilitaryBase
from creeps.behaviors.refill import Refill
from jstools.screeps import *
from utilities import movement
__pragma__('noalias', 'name')
__pragma__('noalias', 'undefined')
__pragma__('noali... |
# 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.
"""
BART: Denoising Sequence-to-Sequence Pre-training for
Natural Language Generation, Translation, and Comprehension
"""
from typing import Op... |
import sys
with open('sciCaseTemplate.html') as han:
html = han.readlines()
with open('HH_sciCases_Feb20.txt') as han:
data = han.readlines()
lines = []
for i in range(len(data)):
s = data[i].split()
if len(s) == 1:
try:
ind = int(float(s[0]))
title = " ".join(data[i... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
import sys
import yaml
import json
import requests
import hashlib
import datetime
import re
def get_hash(resource_url):
""" Access the URL provided and calculate an MD5 hash of whatever is returned.
Throw an exception, if the URL is not accessible.
"""
req = requests.get(resource_url, stream=True)
... |
# -*- coding: utf-8 -*-
"""Optimus_VIRTUOSO.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1pNtJXB2ltVD3rCXHcL6Wh9nTVLXgETC9
# Optimus VIRTUOSO (ver. 1.0)
## "Music never allows falsehoods for even the deaf hear flat notes!" ---OV
***
Credit ... |
from __future__ import print_function
import os
import re
import sys
import textwrap
import click
import yaml
from dagster import PipelineDefinition, check, execute_pipeline
from dagster.cli.workspace.cli_target import (
get_external_pipeline_from_external_repo,
get_external_pipeline_from_kwargs,
get_ext... |
import logging
import pytest
import botocore.exceptions as boto3exception
import json
import uuid
from ocs_ci.framework import config
from ocs_ci.ocs.exceptions import (
NoBucketPolicyResponse,
InvalidStatusCode,
UnexpectedBehaviour,
)
from ocs_ci.framework.testlib import MCGTest, tier1, tier2, tier3, ski... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Installation driver (and development utility entry point) for ngs-chew
"""
import os
import sys
from setuptools import setup, find_packages
import versioneer
__author__ = "Manuel Holtgrewe <manuel.holtgrewe@bihealth.de>"
def parse_requirements(path):
"""Parse `... |
from .generic import *
from .model import *
from .object import *
from .field import *
|
# A JSON-based API(view) for your app.
# Most rules would look like:
#
# @jsonify.when("isinstance(obj, YourClass)")
# def jsonify_yourclass(obj):
# return [obj.val1, obj.val2]
#
# @jsonify can convert your objects to following types:
# lists, dicts, numbers and strings
from turbojson.jsonify import jsonify
|
import time
from gym import Wrapper, logger
class TimeLimit(Wrapper):
def __init__(self, env, max_episode_seconds=None, max_episode_steps=None):
super(TimeLimit, self).__init__(env)
self._max_episode_seconds = max_episode_seconds
self._max_episode_steps = max_episode_steps
self._el... |
#! /usr/bin/env python3
# coding=utf-8
import datetime
import ARLreader as Ar
gdas_file = Ar.fname_from_date(datetime.datetime.now())
print('name of input file ', gdas_file)
gdas = Ar.reader('/Users/yinzhenping/Downloads/current7days')
# print('indexinfo ', gdas.indexinfo)
# print('headerinfo ', gdas.headerinfo)
# f... |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
from google.cloud.vision_v1.proto import (
product_search_service_pb2 as google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2,
)
from google.longrunning import (
operations_pb2 as google_dot_longrunning_dot... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.