content stringlengths 5 1.05M |
|---|
from django.db.models.query_utils import Q
from django_filters.rest_framework import (
BooleanFilter,
FilterSet,
MultipleChoiceFilter,
)
from app.career.enums import JobPostType
from app.career.models.job_post import JobPost
from app.common.filters import NumberInFilter
from app.util.utils import yesterday... |
"""
Copyright IBM Corp. 2018.
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, sof... |
# -*- coding: utf-8 -*-
#* Copyright (c) 2020 Intel Corporation
import os,sys,copy,json
import subprocess
import datetime
import time
os.system('sudo -E apt-get install iasl')
if os.path.exists('iasl_build'):
os.system('rm -rf iasl_build')
os.system('mkdir -p iasl_build')
cmd = "cd iasl_build" + "&&" +"wget https:/... |
from torch.optim.lr_scheduler import _LRScheduler
import math
class CosineAnnealingLR(_LRScheduler):
def __init__(self, optimizer, T_max=1, T_up=0, eta_min=0, last_epoch=-1):
self.T_max = T_max
self.T_up = T_up
self.eta_min = eta_min
super().__init__(optimizer, last_epoc... |
from django.template import Library
import inspect
register = Library()
@register.filter
def inspect_doc(model,field):
try:
func = getattr(model,field,None)
return func.__doc__
except:
return ""
@register.filter
def inspect_source(model,field):
try:
func = getattr(mode... |
from . import routes
@routes.route('/validateUpload/hello')
def hello():
return 'Hello Validate Order'
|
"""
Test that we can backtrace correctly from Non ABI functions on the stack
"""
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class EHFrameBasedUnwind(TestBase):
mydir = TestBase.compute_mydir(__file__)
@skipUnlessPlatform(['... |
import os
from hashlib import sha1
import librosa
from sound_check_app import constants
def get_file_hash(filepath, block_size=2 ** 20):
s = sha1()
with open(filepath, "rb") as f:
while True:
buf = f.read(block_size)
if not buf:
break
s.update(buf)... |
import os
import random
import cv2
import numpy as np
import torchvision.datasets as datasets
from PIL import Image
from torch.utils.data.dataset import Dataset
def rand(a=0, b=1):
return np.random.rand()*(b-a) + a
class FacenetDataset(Dataset):
def __init__(self, input_shape, dataset_path, ... |
# Copyright 2018 DeepMind Technologies Limited. 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 ... |
from .mixins import SoftDeleteManagerMixin, SoftDeleteQuerySetMixin
from django.db import models
class SoftDeleteQuerySet(SoftDeleteQuerySetMixin, models.QuerySet):
pass
class SoftDeleteManager(SoftDeleteManagerMixin, models.Manager):
queryset_class = SoftDeleteQuerySet
|
# Coded By: Tom Sumner
# Date: 07-04-2022
# Github: Tom-Sumner / https://github.com/Tom-Sumner
# Discord: TSumner#5215
# License: MIT
# Note: If you use this code, you MUST credit me in your project.
import nextcord, os, sys, colorama, time, asyncio, json
from colorama import init, Fore, Back, Style
from termcolor i... |
import re
import os
import glob
import json
import pickle
import argparse
import subprocess
from tqdm import tqdm
from multiprocessing import Pool, cpu_count
from data.github.preprocessing.src.code_tokenizer import tokenize_java, tokenize_python
def count_file_lines(file_path):
"""
Counts the number of lines... |
import sys
import numpy as np
import tensorflow as tf
from six.moves import cPickle
import pickle
import argparse
import time
import os
from rnn_model3 import RNN_Model
import data_helpers
import word2vec
def predict_epoch(model, session, data):
x, y, mask_x = data
feed_dict={}
feed_dict[model.input_da... |
import os
import sys
import logging
from cliff.app import App
from cliff.commandmanager import CommandManager
class XAM(App):
log = logging.getLogger(__name__)
#CONSOLE_MESSAGE_FORMAT = App.LOG_FILE_MESSAGE_FORMAT
def __init__(self):
super(XAM, self).__init__(
description='XBMC Addo... |
import logging
import os
import sys
import zipfile
from urllib.request import urlopen, urlretrieve
from selenium.webdriver import Chrome as _Chrome
from selenium.webdriver import ChromeOptions as _ChromeOptions
logger = logging.getLogger(__name__)
TARGET_VERSION = 83
__IS_PATCHED__ = 0
class Chrome:
def __new... |
import time
import numpy as np
from ares.inference.Priors import GaussianPrior, UniformPrior,\
ParallelepipedPrior, ExponentialPrior, BetaPrior, GammaPrior,\
TruncatedGaussianPrior, LinkedPrior, SequentialPrior, GriddedPrior
import matplotlib.pyplot as pl
import matplotlib.cm as cm
def_cm = cm.bone
t00 = time... |
from cgi import test
from django.test import TestCase
from os import walk
import cv2
from .helper.poly_solver import solve_polynomial_helper
from .helper.linear_solver import solve_2d, solve_3d
from .helper.poly_detector import get_poly_eqn
from .helper.linear_detector import get_lin_equation
from .test.polynomial_te... |
class netlist_element():
def __init__(self,typeof):
self.typeof = typeof
self.parent = False
def __str__(self):
return(self.typeof)
class subcircuit(netlist_element):
def __init__(self, name, nets, instances):
self.name = name;
self.labels = {}
self.power_net... |
import logging
import sys
import re
import plugins
from version import __version__
from commands import command
logger = logging.getLogger(__name__)
try:
import resource
except ImportError:
logger.warning("resource is unavailable on your system")
def _initialise(bot): pass # prevents commands from being ... |
#!/usr/bin/env python3
# Copyright © 2012-13 Qtrac Ltd. All rights reserved.
# This program or module is free software: you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any ... |
# 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, software
# distributed under the ... |
import sys
from os.path import join, dirname, abspath
sys.path.append(join(abspath(dirname(__file__)), "../src"))
import pytest
from sum import sumd
@pytest.mark.parametrize("a", [1])
@pytest.mark.parametrize("b", [4, 5])
def test_sum(a, b):
print(a, b)
assert sum(a, b) == (a+b)
|
"""empty message
Revision ID: 46d875667f0e
Revises: f407610aefd9
Create Date: 2021-04-09 10:02:43.623829
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '46d875667f0e'
down_revision = 'f407610aefd9'
branch_labels = None
depends_on = None
def upgrade():
# ... |
from distutils.core import setup
setup(
name='torcurl',
version='0.1',
packages=['torcurl'],
url='https://github.com/AsiganTheSunk/torcurl/',
license='',
author='asigan',
author_email='asiganthesunk@gmail.com',
description='python project to unite tor and pycurl',
download_url = 'hh... |
# coding=utf-8
#
# created by kpe on 28.Mar.2019 at 12:33
#
from __future__ import absolute_import, division, print_function
import tensorflow as tf
import params_flow as pf
from tensorflow import keras
from tensorflow.keras import backend as K
import bert
class PositionEmbeddingLayer(bert.Layer):
class Param... |
"""
Setup for buche
"""
from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name... |
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Event'
db.create_table('events_event', (
('id', self.gf('django.db.models.fiel... |
import cv2
import numpy
cap=cv2.VideoCapture(0)
while cap.isOpened():
ret,frame=cap.read()
frame=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
cv2.imshow('webcam',frame)
c=cv2.waitKey(1)
if c==27:
break
cap.release()
cv2.destroyAllWindows()
|
import cmath
import math
a = input("Escribe el valor del rendimiento: \n")
A = float(a)
while A < 0:
print("¡Ha escrito un número negativo! Inténtelo de nuevo")
a = input("Escribe el valor del rendimiento: \n")
A = float(a)
b = input("Escribe el valor del precio por litro : \n")
B = float(b)
while... |
'''
https://leetcode-cn.com/problems/burst-balloons/
312. 戳气球
'''
from typing import List
class Solution:
def maxCoins(self, nums: List[int]) -> int:
'''
考虑最后戳哪个气球 p
f[l, r] = max{f[l, p-1] + f[p+1, r] + nums[p]*nums[l-1]*nums[r+1]}
以区间长度作为 dp “阶段” , 区间端点作为dp “状态”
计算n长度问题,先计算... |
from django.conf.urls import url, patterns
urlpatterns = patterns('corehq.apps.mobile_auth.views',
url('^keys/$', 'fetch_key_records', name='key_server_url'),
) |
import os
import sys
import pytest
from dvc.exceptions import GitHookAlreadyExistsError
from dvc.utils import file_md5
from dvc.main import main
from dvc.stage import Stage
@pytest.mark.skipif(
sys.platform == "win32", reason="Git hooks aren't supported on Windows"
)
class TestInstall(object):
def _hook(se... |
import unittest
from anchore_engine.services.policy_engine.engine.policy.params import JsonSchemaValidator, BooleanStringValidator, TypeValidator, CommaDelimitedNumberListValidator, EnumValidator, \
DelimitedEnumStringValidator, IntegerValidator, NameVersionListValidator, PipeDelimitedStringListValidator, CommaDel... |
from gi.repository import Gtk
from gi.repository import Gdk
import ns.core
import ns.network
import ns.internet
import ns.olsr
from visualizer.base import InformationWindow
## ShowOlsrRoutingTable class
class ShowOlsrRoutingTable(InformationWindow):
## @var win
# window
## @var visualizer
# visuali... |
# #######################################################################
#
# Task : RunCommand Interaction
#
# #######################################################################
"""
Creates the autoIT stub code to be passed into the master compile
Takes a supplied text file for the Sheepl to type
the mas... |
import argparse
import itertools
import os.path
import time
import uuid
import torch
import torch.optim.lr_scheduler
import numpy as np
import math
import evaluate
import trees
import vocabulary
import makehp
import Zparser
from dep_reader import CoNLLXReader
import dep_eval
import utils
import json
tokens = Zparser
... |
# https://leetcode.com/problems/find-pivot-index/
class Solution:
# TC : O(N)
# SC : O(1)
# Runtime: 226 ms, faster than 39.17% of Python3 online submissions for Find Pivot Index.
# Memory Usage: 15.4 MB, less than 11.76% of Python3 online submissions for Find Pivot Index.
def pivotIndex(... |
from django.conf.urls import include
from . import views
from django.conf import settings
from django.conf.urls.static import static
from django.urls import path
urlpatterns=[
path('',views.index,name='Index'),
path('create/profile',views.create_profile, name='create-profile'),
path('new/project',views.new... |
from pyspark.sql.dataframe import DataFrame
from pyspark.sql.functions import lit
from splink.vertically_concat import vertically_concatenate_datasets
from splink.lower_id_on_lhs import lower_id_to_left_hand_side
from splink.blocking import _get_columns_to_retain_blocking, sql_gen_comparison_columns
from splink.setting... |
!pip install kaggle
import os
def get_size(path = os.getcwd()):
print("Calculating Size: ",path)
total_size = 0
#if path is directory--
if os.path.isdir(path):
print("Path type : Directory/Folder")
for dirpath, dirnames, filenames in os.walk(path):
for f in filenames:
... |
import re
with open("emoji-test.txt") as f:
for line in f:
if line[0] == "#":
continue
line = re.split(";|#", line.strip(), maxsplit=2)
line = [p.strip() for p in line]
if not line[0]:
continue
codepoints, status, description = line
if status != "fully-qualified":
continue
emoji = ''.join([chr... |
import tensorflow as tf
from caloGraphNN import *
from ops.ties import *
def dgcnn_model(feat):
feat = high_dim_dense(feat, 64) # global transform to 3D
feat = edge_conv_layer(feat, 10, [64, 64, 64])
feat_g = layer_global_exchange(feat)
feat = tf.layers.dense(tf.concat([feat, feat_g], axis=-1),
... |
import time
import json
from os import path
from getpass import getuser
from platform import node
VERSION = (16, 6, 4)
APPNAME = 'tsdesktop'
buildinfo = {
'TIME': None,
}
binfoFile = path.join(path.dirname(__file__), 'buildinfo.json')
def writeBuildInfo():
global buildinfo
buildinfo['TIME'] = time.time()... |
# https://stackoverflow.com/questions/19561727/what-is-the-difference-between-the
# -widgets-of-tkinter-and-tkinter-ttk-in-python
from __future__ import print_function
import matplotlib
import numpy as np
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure i... |
from __future__ import absolute_import
import os
import logging
from collections import OrderedDict
import torch
import torch.nn as nn
import models.networks as networks
from .base_model import BaseModel
from . import losses
logger = logging.getLogger('base')
class PBRModel(BaseModel):
def __init__(self, opt):... |
from office365.runtime.queries.service_operation_query import ServiceOperationQuery
from office365.runtime.paths.resource_path import ResourcePath
from office365.sharepoint.base_entity import BaseEntity
from office365.sharepoint.directory.user import User
class DirectorySession(BaseEntity):
def __init__(self, con... |
# *~* CatABMS Command *~* #
#start-of-config
trigger = "справка;помощь;команды;help;котопай;меню"
description = "Справка: список команд бота"
triggermode = "is"
timeout = "10"
author_pseudo = "Cat Weird"
author_contacts = "t.me/catweir1"
#end-of-config
commandslist = []
adminlist = []
for a in commands:
if "Админи... |
################################################################################
# _ ____ ___ #
# / \ / ___|_ _| #
# / _ \| | | | ... |
import os
import cv2
import numpy as np
from picamera import PiCamera
import tensorflow as tf
import argparse
import sys
import qrcode
import RPi.GPIO as GPIO
sys.path.append('..')
from utils import label_map_util
from utils import visualization_utils as vis_util
import time
import random, pygame, sys
from pygame.l... |
from .db_tool import DB_tools
from random import choices
gacha_main = {
"kazuma":[
"https://media.discordapp.net/attachments/885771035243347978/886429821809344563/1001100.png",
"https://media.discordapp.net/attachments/885771035243347978/886429812061773834/1003100.png",
"https://media.disco... |
# kalman_qstrader_strategy.py
from __future__ import print_function
import sys
from math import floor
import math
import numpy as np
from collections import deque
from qstrader.price_parser import PriceParser
from qstrader.event import (SignalEvent, EventType)
from qstrader.strategy.base import AbstractStrategy
from... |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
import jso... |
pinNumber = 1234
print("What's PIN?")
userNumber = int(input("> "))
counter = 0
accessGranted = True
while (userNumber != pinNumber):
counter += 1
if counter >= 3:
accessGranted = False
break
print("Wrong try again")
userNumber = int(input("> "))
if accessGranted:
print("WELC... |
from typing import Type, TypeVar, MutableMapping, Any, Iterable, Generator
from datapipelines import DataSource, PipelineContext, Query, NotFoundError, validate_query
from .common import KernelSource, APINotFoundError
from ...data import Platform, Tier, Division
from ...dto.league import (
LeagueEntriesDto,
Le... |
#!/usr/bin/python
# Generate Heat Map from DRAM accesses
import sys
import os
base = sys.argv[1]
step = int(sys.argv[2]) # Number of cycles to jump
VAULTS = int(os.environ['N_INIT_PORT'])
BANKS = int(os.environ['DRAM_BANKS_PER_VAULT'])
maxtime = 15000000 # This is the hard limit
print ("Dir:" + base)
banks = []
f... |
from aws_cdk import (core as cdk,
aws_ec2 as ec2,
)
from aws_cdk.aws_ec2 import SubnetConfiguration, SubnetType
# For consistency with other languages, `cdk` is the preferred import name for
# the CDK's core module. The following line also imports it as `core` for use
# with ... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from pinpoint.plugins.PinpointCommonPlugin import PinpointCommonPlugin
@PinpointCommonPlugin('', __name__)
def in_lambda(b):
return b * b
@PinpointCommonPlugin('', __name__)
def return_lambda(a):
return lambda: in_lambda(a)
|
#! /usr/bin/env python
"""
This program finds authors and reviewers for git logs.
The result is pushed into a database to be parsed into numbers.
Example commit:
commit af3290f5e790dcd1be3ac209be1805626f4ebac8 (HEAD -> master, origin/master)
Author: Amit Kapila <akapila@postgresql.org>
Date: Thu Dec 12 11:51:30 20... |
"""
Script to set up a custom genome for bcbio-nextgen
"""
import argparse
from argparse import ArgumentParser
import os
from cloudbio.biodata import genomes
from cloudbio import fabutils
from bcbio.utils import safe_makedir
from bcbio.distributed.transaction import file_transaction
from fabric.api import *
import sub... |
#Find duplicate number in array of integers bounding 1 and n being n the lenght of the array
#Most optimal solution:
#Time: O(n)
#Space: O(1)
def firstDuplicateValue(array):
for i in range(len(array)):
absValueIndex = abs(array[i])-1
if array[absValueIndex]<0:
return abs(array[i])
e... |
import dataset_converters.formats as formats
import dataset_converters.converters as converters
def convert(input_folder, output_folder, input_format, output_format, copy_fn):
FORMAT = formats.gen_conversion_format(input_format, output_format)
converter = None
for i in range(len(converters.converters))... |
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 6 15:27:04 2016
@author: alex
"""
from AlexRobotics.planning import RandomTree as RPRT
from AlexRobotics.dynamic import Hybrid_Manipulator as HM
from AlexRobotics.control import RminComputedTorque as RminCTC
import numpy as np
import matplotlib
import m... |
a = input("Digite o nome de uma fruta para adicionar na lista: ")
b = input("Digite o nome de uma fruta para adicionar na lista: ")
c = input("Digite o nome de uma fruta para adicionar na lista: ")
d = input("Digite o nome de uma fruta para adicionar na lista: ")
e = input("Digite o nome de uma fruta para adicionar na ... |
import codecs
import sys
import binaryninja.interaction
from binaryninja.flowgraph import FlowGraph, FlowGraphNode
from binaryninja.function import DisassemblyTextLine, InstructionTextToken
from binaryninja.enums import InstructionTextTokenType, BranchType
if sys.version_info[0] == 3:
decode_as = "ascii"
else:
... |
"""
TODO
"""
import os
import pwd
import json
import yaml as YAML
import logging
import jsonschema
class RegularUserException(Exception):
pass
class Config:
__shared_state = dict()
_config = dict()
def __init__(self):
self.__dict__ = self.__shared_state
if not self._config:
... |
#!/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 writing, software... |
lista_lista = list()
dados_pessoais = list()
lista_pesados = list()
lista_leves = list()
pessoa = peso_maior = peso_menor = 0
while True:
dados_pessoais.append(str(input('Qual é o teu nome? ')))
dados_pessoais.append(float(input('Qual o seu peso? ')))
question = str(input('Deseja continuar? [S/N] ').str... |
import os
import torch
import subprocess
def dist_init(args):
if 'RANK' in os.environ and 'WORLD_SIZE' in os.environ:
args.rank = int(os.environ["RANK"])
args.world_size = int(os.environ['WORLD_SIZE'])
args.gpu = int(os.environ['LOCAL_RANK'])
args.dist_url = 'env://'
os.env... |
# Author: Ivan Nikolchev
# See the LICENSE file for legal information regarding use of this file.
"""AESGCM with CTR from m2crypto"""
from tlslite.utils.cryptomath import m2cryptoLoaded
from tlslite.utils.aesgcm import AESGCM
from tlslite.utils import openssl_aes
from tlslite.utils.rijndael import Rijndael
if m2cryp... |
from copy import deepcopy
import torch
import os
from torch.distributions.normal import Normal
from rlil.environments import Action
from rlil.initializer import (
get_device, get_writer, get_replay_buffer, use_apex)
from rlil.memory import ExperienceReplayBuffer
from rlil.nn import weighted_mse_loss
from rlil.utils... |
#! /usr/bin/env python3
import click
import sys
from json import loads, dumps
import pandas as pd
from numpy.linalg import tensorinv
from numpy import matmul
def jloads(fname):
return loads(open(fname).read())
def normalizeTbl(ags, tbl):
iags = tensorinv(ags)
taxaAGS = matmul(iags, tbl)
normal = t... |
import torch
import torch.nn as nn
import torch.nn.functional as F
def concat_elu(x):
"""Concatenated ReLU (http://arxiv.org/abs/1603.05201), but with ELU."""
return F.elu(torch.cat((x, -x), dim=1))
def safe_log(x):
return torch.log(x.clamp(min=1e-22))
def squeeze(x):
##-> provide the squeezing code ... |
import networkx
import numpy
import scipy
from .base_plotable_model import BasePlotableModel
class SEIRSNetworkModel(BasePlotableModel):
"""
A class to simulate the SEIRS Stochastic Network Model
======================================================
Params:
G Network adjace... |
# coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..compat import compat_str
from ..utils import (
int_or_none,
qualities,
remove_end,
strip_or_none,
try_get,
unified_timestamp,
url_basename,
)
class AllocineIE(InfoExtractor):
_VALID_URL = ... |
#!/usr/bin/env python
# WordNet-based data augmentation
#
# Copyright (C) 2020
# Author: Joseph Sefara
# URL: <https://github.com/dsfsi/textaugment/>
# For license information, see LICENSE
import numpy as np
import nltk
from itertools import chain
from nltk.corpus import wordnet
class Wordnet:
"""
A set of ... |
from __future__ import annotations
from typing import TYPE_CHECKING, Dict
if TYPE_CHECKING:
from hyades.device.device import Device
from hyades.connection.base_wrapper import base_wrapper
from hyades.connection.fabric import ConnectionFabric
from netmiko import ConnectHandler
@ConnectionFabric.register()
class sc... |
import os
FIREBASE_DATABASE_URL = os.environ.get("FIREBASE_DATABASE_URL", "")
FIREBASE_API_KEY = os.environ.get("FIREBASE_API_KEY", "")
FIREBASE_AUTH_DOMAIN = os.environ.get("FIREBASE_AUTH_DOMAIN", "")
FIREBASE_STORAGE_BUCKET = os.environ.get("FIREBASE_STORAGE_BUCKET", "")
FIREBASE_ADMIN_CREDENTIALS = os.environ.g... |
"""
LightsheetCorrection
====================
Module to remove lightsheet artifacts in images.
Adapted from https://github.com/ChristophKirst/ClearMap2
Kirst, et al. "Mapping the Fine-Scale Organization and Plasticity of the Brain Vasculature."
Cell 180.4 (2020): 780-795.
https://doi.org/10.1016/j.cell.2020.01.028
... |
import os
import typing as tp
from motor.motor_asyncio import AsyncIOMotorClient, AsyncIOMotorCollection, AsyncIOMotorDatabase
from pydantic import BaseModel, parse_obj_as
from .routers.service.models import (
AchievementEvent,
AchievementTemplate,
Reward,
RewardEvent,
Subject,
)
from .routers.use... |
#!/usr/bin/python2.4
#
# Copyright 2008 Google 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 o... |
from app import actioner, model
def create_delta(*,
current_sink: model.SinkSpec = None,
target_sink: model.SinkSpec = None,
current_source: model.SourceSpec = None,
target_source: model.SourceSpec = None,
current_stream: model.Strea... |
#!/usr/bin/env python
# $id$
"""
Make gsw_saar_data.c from the current gsw_data_v3_0.nc. This is a developer
utility and not a part of the public distribution, but its end-product is.
Note that it generates gsw_saar_data.c but will not overwrite it if it exists.
General concept: we don't want end-users of this distri... |
from concurrent.futures import ThreadPoolExecutor
import time
from PySide2.QtCore import QCoreApplication
thread_pool=None
def init_thread_pool():
global thread_pool
thread_pool=ThreadPoolExecutor()
def deinit_thread_pool():
global thread_pool
thread_pool.shutdown()
def submit_task(function,*args,*... |
import logging
import pandas as pd
import pytest
import helpers.hdbg as hdbg
import helpers.hunit_test as hunitest
# TODO(Dan): return to code after CmTask43 is fixed.
import im_v2.ccxt.data.extract.exchange_class as imvcdeexcl
_LOG = logging.getLogger(__name__)
@pytest.mark.skip()
class Test_CcxtExchange(hunites... |
# compile using: python3 setup.py sdist bdist_wheel
import turbosensei.load
import turbosensei.preprocess
import turbosensei.regress
import turbosensei.results
import turbosensei.utils
import turbosensei.buttons |
"""
Testing signals before/after saving and deleting.
"""
from django.db import models
from django.dispatch import dispatcher
class Person(models.Model):
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
def __unicode__(self):
return u"%s %s" % (self.first_n... |
import unittest
from int_ops_addition_only import multiply, subtract, divide
class Test_Case_Int_Ops_Addition_Only(unittest.TestCase):
def test_multiply(self):
self.assertEqual(multiply(5,10), 50)
def test_divide(self):
self.assertEqual(divide(3,1), 3)
def test_subtract(self):
self.... |
#
# Misc functions related to Pillow/pictures
#
import PIL.ImageDraw
from . import log
CENTER = object()
def resizeImageToFitInside(image, size):
'''Resize a PIL image object to fit inside a box of size size'''
f = list(float(size[i]) / image.size[i] for i in range(2))
if max(f) < 1:
# too large... |
inputmin = 387638
inputmax = 919123
# rules : 1) six digits (and are within min and max
# 2) 2 adjacent digits are the same
# 3) left to right, the numbers never decrease
# this first one might be possible to do without programming?
# 456789 is the only one that violates rule 2
# 388 888 is the sta... |
import pandas as pd
import numpy as np
from math import log, exp
from random import uniform
class UtilityModel:
def __init__(self,name,churn_rate,behavior_model):
'''
This class calculates the churn probability for a customer based on their event counts. Its called a "Utility
Model" to m... |
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'test_db.sqlite'
}
}
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contri... |
import os
import json
from decimal import Decimal
from django.conf import settings
from exchange.adapters import BaseAdapter
import requests
from collections import namedtuple
CurrencyTuple = namedtuple('CurrencyTuple', (
'code', 'name'))
class MetsyncAdapter(BaseAdapter):
"""
This Adapter uses Metglobal... |
'''Exercício Python 014: Escreva um programa que converta uma temperatura digitando
em graus Celsius e converta para graus Fahrenheit.'''
msg = f'{"Conversor de Temperatura":^30}'
print('*'*len(msg))
print(msg)
print('*'*len(msg))
temp_Celsius = float(input('\nInforme a temperatura em ºC: '))
temp_Fahrenheit = (tem... |
# Copyright (c) 2015 Ansible, Inc.
# All Rights Reserved.
# Python
import os
from backports.tempfile import TemporaryDirectory
from django.conf import settings
import pytest
import mock
# AWX
from awx.main.models import * # noqa
from awx.api.versioning import reverse
@pytest.mark.django_db
def test_organization_li... |
# DRUNKWATER TEMPLATE(add description and prototypes)
# Question Title and Description on leetcode.com
# Function Declaration and Function Prototypes on leetcode.com
#730. Count Different Palindromic Subsequences
#Given a string S, find the number of different non-empty palindromic subsequences in S, and return that nu... |
def check(num):
if (num > 0):
return print("É positivo")
elif (num == 0):
return print("É zero")
else:
return print("É negativo")
val = int(input("Insira o número a ser consultado: "))
print(check(val))
def isEven(num):
if (num % 2 == 0):
return print("É par")
... |
"""
This class implements the Python Prediction's way of dealing with
categorical data preprocessing. There are three steps involved here:
- An optional regrouping of the different categories based on category size
and significance of the category w.r.t. the target
- Missing value replacement with the additional cat... |
"""
Created on Aug 31, 2014
@author: sfurman
"""
import serial.tools.list_ports
# Find devices on the device list.
def com_port_devices():
# Search for ports using a regular expression. Port name, description and hardware ID.
# [('COM3', 'USB Serial Port (COM3)', 'FTDIBUS\\COMPORT&VID_0403&PID_6001')]
... |
#!/usr/bin/env python
# # -*- coding: utf-8 -*-
__version__ = '1.0.0'
class pycaesarcrypt(object):
alphabet = 'abcdefghijklmnopqrstuvwxyz'
def caesar(self, string, shift):
result = ''
for char in string:
if char.isalpha():
index = (self.alphabet.find(char.lower())... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.