content stringlengths 5 1.05M |
|---|
def ficha(n='<desconhecido>', g=0):
return f'O jogador {n} fez {g} gol(s) no campeonato.'
print('\033[30m-'*35)
nome = str(input('Nome do Jogador: ')).capitalize().strip()
gol = input('Número de Gols: ').strip()
if gol == '' and nome == '':
print(ficha())
elif nome == '' and gol.isnumeric():
print(ficha(g... |
from __future__ import unicode_literals
from django.contrib.auth import get_user_model
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from django.shortcuts import render, redirect
from django.template.loader import get_template
from django.urls import reverse
from django.utils impo... |
import numpy as np
def flipLabels(Y, perc):
"""Flips randomly selected labels of a binary classification problem with labels +1,-1
Arguments:
Y: array of labels
perc: percentage of labels to be flipped
Returns:
Y: array with flipped labels
"""
if perc < 1 or perc > 100:
print... |
class AbstractLstmModelBuilder(object):
"""The model combines all the components
and provides interfaces for users to train the
model and generate sequences with the model.
"""
def _build_generating_model(self,
tensors):
"""Unroll and compile tensors in self.... |
from scoring_engine.engine.basic_check import BasicCheck
class MSSQLCheck(BasicCheck):
required_properties = ['database', 'command']
CMD = "/opt/mssql-tools/bin/sqlcmd -S {0},{1} -U {2} -P {3} -d {4} -Q {5}"
def command_format(self, properties):
account = self.get_random_account()
return ... |
'''
Extract tables from HTML/XBRL files in an input directory,
and put the resulting files in an output directory -
one table per file.
'''
import os
import re
import glob
import html
from bs4 import BeautifulSoup
from utils.environ import data_dir, extracted_tables_dir
from utils.html import replace_html_tags
TABLES_... |
GRID = ['XXXXXXXXX',
'X X',
'X X X X X',
'X X',
'XXXXXXXXX']
GRID_SQ_SIZE = 64
HALF_GRID_SQ_SIZE = 64 // 2
SPEED = 2
# Convert pixel coordinates to grid coordinates
def get_grid_pos(x, y):
return x // GRID_SQ_SIZE, y // GRID_SQ_SIZE
|
from decisionai_plugin.common.plugin_service import PluginService
from decisionai_plugin.common.util.constant import STATUS_SUCCESS, STATUS_FAIL
from decisionai_plugin.common.util.timeutil import get_time_offset, str_to_dt, dt_to_str
from telemetry import log
import copy
class DemoService(PluginService):
def __ini... |
import pytest
@pytest.mark.django_db
def test_challenge_set_fixture(ChallengeSet):
assert ChallengeSet.challenge.is_admin(ChallengeSet.creator)
assert not ChallengeSet.challenge.is_participant(ChallengeSet.creator)
assert ChallengeSet.challenge.is_admin(ChallengeSet.admin)
assert not ChallengeSet.chal... |
# -*- coding: utf-8 -*-
from flair.parser.modules.dropout import SharedDropout
import torch.nn as nn
class MLP(nn.Module):
def __init__(self, n_in, n_hidden, dropout=0, identity = False):
super(MLP, self).__init__()
self.linear = nn.Linear(n_in, n_hidden)
self.identity = identity
... |
# Generated by Django 3.0.4 on 2020-03-24 12:28
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('customer', '0003_auto_20200313_0738'),
('eadmin', '0009_salesreport'),
]
operations = [
migrations.... |
# -*- encoding: utf-8 -*-
import pytest
from bs4 import BeautifulSoup as BSoup
from slack_emoji_uploader import beautiful_soup_helper
@pytest.mark.parametrize('html, name, expected', [
# A single <input/> tag with a value
('<input name="alexander" value="armstrong" />', 'alexander', 'armstrong'),
# A si... |
'''
http://code.djangoproject.com/ticket/7198
'''
|
import maml_rl.envs
import gym
import torch
import numpy as np
# from tqdm import trange
import yaml
from maml_rl.baseline import LinearFeatureBaseline
from maml_rl.samplers import MultiTaskSampler
from maml_rl.utils.helpers import get_policy_for_env, get_input_size
from maml_rl.utils.reinforcement_learning import get... |
# -*- coding: utf-8 -*-
#
# Copyright 2017-2021 AVSystem <avsystem@avsystem.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 ... |
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="lightning-talk-pipelines",
version="0.0.8",
author="Rory Murdock",
author_email="rory@itmatic.com.au",
description="A sample package for testing",
long_description=long_description,
... |
'''
Tests for the OligoAssembly design class.
'''
from nose.tools import assert_equal
from coral import design, DNA
def test_oligo_assembly():
'''
Tests output of OligoAssembly class.
'''
# Expected outputs
olig1 = 'ATGCGTAAAGGAGAAGAACTTTTCACTGGAGTTGTCCCAATTCTTGTTGAATTAGATGGTG' + \
... |
__product__ = None
__copyright__ = None
__version__ = None
__date__ = None
try:
import bhamon_orchestra_master.__metadata__
__product__ = bhamon_orchestra_master.__metadata__.__product__
__copyright__ = bhamon_orchestra_master.__metadata__.__copyright__
__version__ = bhamon_orchestra_master.__metadata__.__versio... |
import sys
import datetime
import asyncio
import traceback
from aiohttp_json_rpc import JsonRpcClient
class WorkerClient(JsonRpcClient):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.add_methods(
("", self.start_job),
)
self.current_job =... |
import re
import json
from sqlalchemy.orm import Session
from .. import schemas, models
from fastapi import HTTPException, status
from sqlalchemy.sql import text
from sqlalchemy import desc
# from fastapi_pagination import Page, pagination_params, page_size
# Show All Incomes ##.order_by(desc('date'))
def get_all(db:... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Problem 24
# Lexicographic permutations
from itertools import permutations
import numpy as np
a = [int(''.join(k)) for k in
list(permutations([str(i) for i in np.arange(10)], 10))]
a.sort()
print(a[999999])
# 2783915460
# 3.190 s
|
from django.utils import simplejson as json
from jsonate.json_encoder import JsonateEncoder
def jsonate(obj, *args, **kwargs):
kwargs['cls'] = JsonateEncoder
return json.dumps(obj, *args, **kwargs) |
# Generated by Django 3.2.5 on 2021-07-28 07:48
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('LabNet', '0013_ip_ip_to_interger_ip'),
]
operations = [
migrations.RemoveField(
model_name='ip',
name='comment',
... |
# -*- coding: utf-8 -*-
# The LLVM Compiler Infrastructure
#
# This file is distributed under the University of Illinois Open Source
# License. See LICENSE.TXT for details.
""" This module is a collection of methods commonly used in this project. """
import collections
import functools
import json
i... |
from typing import (
get_args,
Type,
ClassVar,
TypeVar,
)
T = TypeVar("T")
def add_on(data_class: Type) -> Type:
class AddOn(data_class):
size: ClassVar[int] = sum(
get_args(field_type)[0].size
for field_type in data_class.__annotations__.values()
)
... |
import requests
from API.library.support.data import tr
def get_token(user_name, password):
body = {
'userName': user_name,
'password': password
}
url = tr
token = requests.post(
url,
json=body
)
return 'Bearer ' + token.text
|
###############################################################################
# PyDial: Multi-domain Statistical Spoken Dialogue System Software
###############################################################################
#
# Copyright 2015 - 2017
# Cambridge University Engineering Department Dialogue Systems Grou... |
import grpc
import account_pb2
import account_pb2_grpc
with grpc.insecure_channel('0.0.0.0:8000') as channel:
# ------- ----
# 1 2
# 1. Docker を使っているときは localhost ではなく 0.0.0.0 にする
# 2. ポート番号
stub = account_pb2_grpc.UserControllerStub(channel)
fo... |
class Condor(object):
def __init__(self, slottable):
self.slottable = slottable
def host_score(self, pnode, vnode_capacity):
vnode_cpu = vnode_capacity.get_by_type("CPU")
vnode_memory = vnode_capacity.get_by_type("Memory")
vnode_net_in = vnode_capacity.get_by_type("Net-in")
... |
def return_json_temprate(MODALITY: str) -> dict:
"""テンプレート辞書を返す
Args:
MODALITY (str): MODALITY
Returns:
[dict]: temprate
"""
header = {
'PRIMARY KEY':' ',
'Identified Modality':"",
"SOPInstanceUID":" ",
"StudyID":" ",
"ManufacturerModelName":... |
import math
def newton(function,function1,startingInt): #function is the f(x) and function1 is the f'(x)
x_n=startingInt
while True:
x_n1=x_n-function(x_n)/function1(x_n)
if abs(x_n-x_n1)<0.00001:
return x_n1
x_n=x_n1
def f(x):
return math.pow(x,3)-2*x-5
def f1(x):
retur... |
#!/usr/bin/env python
import sys
from matplotlib import pyplot as plt
import TraceView
import TraceModel
import scipy
import argparse
import glob
import os.path
__version__="01.00.00"
__author__ ="Robert Shelansky"
DEFAULT_LENGTH =2246
DEFAULT_THRESHOLD=4
DEFAULT_SMOOTH =10
parser = argparse.ArgumentParser(descr... |
# Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Module for testing constant regex expressions."""
import re
from lib.constants import regex
def test_url_to_widget_info_regex():
"""Test regex for parsing the source object name, source object id,
... |
from distutils.version import StrictVersion
VERSION = StrictVersion('1.1.14')
|
"""
Git commands module
Module for interacting with Git command line interface
author: Ryan Long <ryan.long@noaa.gov>
"""
import os
import subprocess
import logging
logger = logging.getLogger(__name__)
def _command_safe(cmd, cwd=os.getcwd()) -> subprocess.CompletedProcess:
"""_command_safe ensures commands ar... |
# This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
# * Rearrange models' order
# * Make sure each model has one field with primary_key=True
# * Make sure each ForeignKey has `on_delete` set to the desired behavior.
# * Remove `managed = False` lines if ... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : data_pack.py
@Time : 2022/03/08 22:18:18
@Author : felix
@Version : 1.0
@Contact : laijia2008@126.com
@License : (C)Copyright 2021-2025, felix&lai
@Desc : 用于数据封包解包
'''
# here put the import lib
import struct
from tool_define import *
... |
from typing import List
from .attributed_lines import *
from .attributed_lines_widget import *
from .attributed_text_widget import *
from .config import *
from .cursor_rendering import *
from .cursor_tree_widget import *
from .element import *
from .element_supply import *
from .exceptions import *
from .markup import... |
#!/usr/bin/env python
# Copyright 2017 The Forseti Security 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
#
#... |
#!/usr/bin/python
'''
Generates splunk configurations from manifest files under the security_content repo.
'''
import glob
import yaml
import argparse
from os import path
import sys
import datetime
from jinja2 import Environment, FileSystemLoader
import re
from attackcti import attack_client
import csv
import shutil
... |
###############################
#
# Created by Patrik Valkovic
# 4/3/2021
#
###############################
import torch as t
import numpy as np
import time
REPEATS = 1000
PARENTS = 10000
TO_PICK = 1
CHILDREN = 5000
# init
t.set_num_threads(4)
d = t.device('cuda:0')
t.rand(1,device=d)
print("=== CPU ===")
# randint... |
class Graph:
def __init__(self, art_installations, weighted_connect):
self.installations = art_installations
self.adjacency_mtx = weighted_connect
self.artwork_to_index = {}
for i, artwork in enumerate(self.installations):
self.artwork_to_index[artwork] = i
... |
#!/usr/bin/env python
from flattery.cext import *
|
# -*- coding: utf-8 -*-
import os
import sys
import numpy as np
from keras.layers import (
Activation, TimeDistributed, Dense, RepeatVector, Embedding
)
from keras.layers.recurrent import LSTM
from keras.models import Sequential
from keras.preprocessing.sequence import pad_sequences
from preporcessi... |
import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
import zipfile
import tarfile
import tempfile
import shutil
import unittest
import getfile
class DownloadTest(unittest.TestCase):
def create_sample_text_file(self):
"""Create a basic text file for use ... |
import json
from django.template.loader import render_to_string
from django.utils.safestring import mark_safe
from wagtail.admin.edit_handlers import FieldPanel
from .models import TaxonomyTerms
class TaxonomyPanel(FieldPanel):
object_template = "wagtailadmin/edit_handlers/taxonomy_panel.html"
field_templa... |
import os
from django.db import models
# from django.core.exceptions import ValidationError
#
# def validate_only_one_instance(obj):
# model = obj.__class__
# if (model.objects.count() > 0 and
# obj.id != model.objects.get().id):
# raise ValidationError("Can only create 1 %s instance. Delete... |
"""
Provide access to clipboard from rc.conf
USE: eval fm.get_clipboard([<p/b/s>])
SEE: http://kendriu.com/how-to-use-pipes-in-python-subprocesspopen-objects
"""
import os
from subprocess import PIPE, CalledProcessError, run
import ranger.api
from ranger.ext.shell_escape import shell_quote
old_hook_init = ranger.api... |
from deap import gp
import operator
import math
import random
def logabs(x):
return math.log(math.fabs(x)) if x != 0 else 0
def safediv(x, y):
return x/y if y != 0 else 1
def safesqrt(x):
return math.sqrt(abs(x))
def inverse(x):
return 1/x if x != 0 else 1
def sqr(x):
return x**2
def cub... |
from covid_model_seiir_pipeline.pipeline.regression.task.beta_regression import (
beta_regression,
)
from covid_model_seiir_pipeline.pipeline.regression.task.hospital_correction_factors import (
hospital_correction_factors,
)
|
num = cont = soma = 0
while True:
num = int(input('Digite um numero (999 para parar: '))
if num !=999:
soma = soma + num
cont +=1
else:
break
print(f'A soma dos {cont} valores foi {soma}')
print("FIM") |
import numpy as np
from matplotlib import pylab as plt
from tqdm import tqdm
def K(x):
left = 1 / np.sqrt(2 * np.pi)
right = x * x / 2
return left * np.exp(- right)
def hat_f(x, D, h):
N = D.shape[0]
k = [K((x - w) / h) for w in D]
return sum(k) / (N * h)
def hat_f_k(x, D, k):
_ = np.fa... |
# -*- coding: utf-8 -*-
"""
Balanced Error Rate error functions
"""
__author__ = """Giovanni Colavizza"""
import numpy as np
def BER(yn, ynhat):
"""
Implementation of Balanced Error Rate
:param yn: ground truth
:param ynhat: predicted values
:return: error score
"""
y = list()
for z ... |
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import json
import scrapy
from scrapy.exporters import JsonItemExporter
from scrapy.exporters import CsvItemExporter
class Fund... |
def evaluate(pos_df):
"""
position.csv
------------
X,Y,BLOCK,TABLE,PARTICIPANT,GENRE_CODE
0,0,C,27,2,Red
1,0,C,26,1,Red
2,0,C,25,37,Red
"""
# 評価値
value = 0
# block_dict[block][genre_code] = value
block_dict = {}
for _index, row in pos_df.iterrows():
# x = row["X"]
... |
class Node:
def __init__(self,data):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.head = None
def isempty(self):
if self.head == None:
return True
else:
return False
def push(self,data):
... |
# Copyright 2015 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 required by applicable law or ... |
""" An example message family definition.
"""
from typing import Dict, Any
from message import Message
from router import Router
from serializer import JSONSerializer as Serializer
class MESSAGE_TYPES:
SEND_MESSAGE = 'urn:ssi:message:sovrin.org/testing/1.0/send_message_command'
def is_valid_send_message(msg: Mes... |
import sys
def sum_triangular_numbers(n):
if n <= 0:
return 0
else:
t = [int((i + 1) * (i + 2) / 2) for i in range(n)]
return sum(t)
if __name__ == "__main__":
if len(sys.argv) == 2:
print(sum_triangular_numbers(n=int(sys.argv[1])))
else:
sys.exit(1)
|
#!/usr/bin/env python3
import re
from collections import defaultdict, deque
class Compy:
def __init__(self, mem):
self.memory = list(mem)
self.reg = defaultdict(int)
self.pc = 0
self.n_mulls = 0
def get_value(self, value):
if type(value) == int:
return valu... |
#!/usr/bin/env python
# Copyright 2015-2016 Yelp 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 ... |
# criando um Cliente para conexão com o servidor Python
import socket
host = '127.0.0.1' # mesmo local do servidor
porta = 8800 # mesma porta do servidor
soquete = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
envio = (host,porta)
soquete.connect(envio)
print('Digite: S e pressione ENTER para encerra... |
from typing import List
import fastapi
from models.instrument import Instrument
router = fastapi.APIRouter()
@router.get('/instruments')
def get_instruments() -> List[Instrument]:
pass
@router.get('/instrument/{beamline}')
def read_beamline(beamline: str):
# TODO: Validate beamline string is valid
retu... |
# -*- coding: utf-8 -*-
# This file is part of the Ingram Micro Cloud Blue Connect connect-cli.
# Copyright (c) 2019-2021 Ingram Micro. All Rights Reserved.
ITEMS_COLS_HEADERS = {
'A': 'ID',
'B': 'MPN',
'C': 'Action',
'D': 'Name',
'E': 'Description',
'F': 'Type',
'G': 'Precision',
'H':... |
from typing import List, Optional
import crud
import models
import schemas
from core.database import get_db
from core.logger import get_logger
from exceptions.core import APIException
from exceptions.error_messages import ErrorMessage
from fastapi import APIRouter, Depends
from schemas.core import FilterQuer... |
from __future__ import unicode_literals
from moto.core import BaseBackend, BaseModel
from moto.compat import OrderedDict
from.exceptions import DatabaseAlreadyExistsException, TableAlreadyExistsException
class GlueBackend(BaseBackend):
def __init__(self):
self.databases = OrderedDict()
def create_d... |
import torch.nn as nn
from collections import OrderedDict
class VGGFace(nn.Module):
def __init__(self):
super(VGGFace, self).__init__()
self.features = nn.ModuleDict(OrderedDict(
{
# === Block 1 ===
'conv_1_1': nn.Conv2d(in_channels=3, out_channels=64, ... |
from .detecttrend import detecttrend
from .vizplot import *
from .maxtrend import getmaxtrend
from . import version
__version__ = version.__version__ |
import flask
from flask import Flask
from flask.globals import request
from flask.json import JSONEncoder
from statscontroller import StatsController
import hero
from flask.helpers import url_for
class CustomEncoder(JSONEncoder):
def default(self, obj):
encoded = {}
for attr in dir(obj):
... |
# Importing Libraries:
import pandas as pd
import numpy as np
import pickle
# for displaying all feature from dataset:
pd.pandas.set_option('display.max_columns', None)
# Reading Dataset:
dataset = pd.read_csv("Liver_data.csv")
# Filling NaN Values of "Albumin_and_Globulin_Ratio" feature with Median:
dataset['Albumi... |
# -*- coding: utf-8 -*-
from typing import List, Any
class TokenizedDataPage:
"""
Data transfer object that is used to pass results of paginated queries.
It contains items of retrieved page and optional total number of items.
Most often this object type is used to send responses to paginated queries... |
from .RC4 import * |
from .errors import *
from .plot import *
from .util import *
from . import exec
|
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 CERN.
#
# CDS-ILS is free software; you can redistribute it and/or modify it under
# the terms of the MIT License; see LICENSE file for more details.
"""CDS-ILS migrator module."""
from cds_dojson.overdo import OverdoBase
serial_marc21 = OverdoBase(entry_point_models="cd... |
import os
import json
import torch
import pickle
import numpy as np
import torch.nn.functional as F
from torch.utils.data import DataLoader
import torcheras
from dataset import QANetDataset
from constants import device
from qanet.qanet import QANet
from utils import convert_tokens, evaluate
def variable_data(sample... |
import re
from copy import copy
from unidecode import unidecode
from django.db import models
from datagrowth.datatypes import DocumentBase
PRIVATE_PROPERTIES = ["pipeline", "from_youtube", "lowest_educational_level"]
class DocumentManager(models.Manager):
def build_from_seed(self, seed, collection=None, metad... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-24 03:34
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('transactions', '0003_auto_20161117_0224'),
]
operations = [
migrations.Alte... |
""" graph conversions
"""
import autoparse.pattern as app
import autoparse.find as apf
from automol.util import dict_
from automol.convert.inchi import standard_form
from automol.convert.inchi import object_to_hardcoded_inchi_by_key
from automol.convert import _molfile
from automol.convert import _rdkit
from automol.co... |
# SPDX-License-Identifier: MIT
from bobber import __version__
from setuptools import setup
with open('README.md', 'r') as f:
long_description = f.read()
setup(
name='nvidia-bobber',
version=__version__,
description='Containerized testing of system components that impact AI workload performance',
l... |
import re
from abc import ABC, abstractmethod
from typing import Dict, Any
from pydantic import ConstrainedStr
from ulid import ULID as _ULID, base32
from .abstract import JsonSerializable, Restoreable, Generatable, T
class PrimitiveBase(JsonSerializable, Restoreable, Generatable, ABC):
@classmethod
@abstra... |
from ossConfig import ossConfig
import Oss
access_key = 'XXXXXXXXX'
secret_key = 'XXXXXXXXXXXXXXXXXXX'
endpoint_url = 'http://XXXXXXXXXXXXXXXXX.com'
config = ossConfig(access_key, secret_key, endpoint_url)
bucket_name = 'test1'
object_name = 'mytestput'
URL = Oss.PresignedURLs(config, bucket_name, object_name)
print... |
#!/usr/bin/python
import ConfigParser
from shutil import copyfile
import sys
import os.path
if not os.path.exists("MobaXterm.ini") or not os.path.exists("WinSCP.ini"):
print "MobaXterm.ini and/or WinSCP.ini are missing. Please place them in the same directory as the script"
sys.exit()
moba_parser = Confi... |
import os
import unittest
from os import path
import numpy as np
from numpy.testing import assert_allclose
from hazma.decay import charged_pion, muon, neutral_pion
class TestDecay(unittest.TestCase):
def setUp(self):
self.base_dir = path.dirname(__file__)
def load_data(self, data_dir):
"""L... |
# Generated by Django 3.2.6 on 2021-08-20 12:24
from django.db import migrations, models
import gnd.fields
class Migration(migrations.Migration):
dependencies = [
('example', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Person',
fields=[
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2018-07-19 11:13
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('orgManager', '0003_auto_20180719_1431'),
]
operations = [
migrations.AddFie... |
# Copyright 2020 Open Climate Tech Contributors
#
# 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 agr... |
# BOJ 17779
"""
선거구를 선정하는 방법
가장 윗 점인 x, y를 선정 (1 <= x <= N, 1 <= y <= N)
d1, d2를 이용하여 구획 쪼개기 (d1, d2는 브루트포스를 이용하여 모두 선정하기, d1, d2 >= 1)
x, y 정하기 1 <= x < x + d1 + d2 <= N
1. x, y의 위치를 정하기
"""
import sys
si = sys.stdin.readline
dy = [-1, 1, 0, 0]
dx = [0, 0, -1, 1]
def label_5(y, x, d1, d2):
i = 0
while i <= ... |
import math
import pandas as pd
import teller as tr
import numpy as np
from sklearn import datasets
from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_breast_cancer, load_wine, load_iris, make_classification
... |
from skidl import *
# Create input & output voltages and ground reference.
vin, vout, gnd = Net("VI"), Net("VO"), Net("GND")
# Create two resistors.
r1, r2 = 2 * Part("Device", "R", TEMPLATE, footprint="Resistors_SMD:R_0805")
r1.value = "1K" # Set upper resistor value.
r2.value = "500" # Set lower resistor value.
... |
'''
Created on Dec 16, 2018
@author: gsnyder
Add tags to a project
'''
from blackduck.HubRestApi import HubInstance
import argparse
parser = argparse.ArgumentParser("Add tags to a project")
parser.add_argument("project_name")
parser.add_argument("tag")
args = parser.parse_args()
hub = HubInstance()
project_list ... |
"""Collection of Ivy loss functions."""
# local
import ivy
from typing import Optional, Union
from ivy.func_wrapper import to_native_arrays_and_back
# Extra #
# ------#
@to_native_arrays_and_back
def cross_entropy(
true: Union[ivy.Array, ivy.NativeArray],
pred: Union[ivy.Array, ivy.NativeArray],
axis: O... |
#!/usr/bin/python
"""
(C) Copyright 2020-2022 Intel Corporation.
SPDX-License-Identifier: BSD-2-Clause-Patent
"""
import time
import random
import threading
import copy
from osa_utils import OSAUtils
from daos_utils import DaosCommand
from dmg_utils import check_system_query_status
from exception_utils import Comm... |
# Copyright International Business Machines Corp, 2020
#
# 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 ... |
from terial import models
from terial.database import session_scope
from terial.materials import loader
def main():
with session_scope() as sess:
materials = (sess.query(models.Material)
.filter_by(type=models.MaterialType.MDL)
.all())
for material in mat... |
import os
import sys
from os3.fs.directory import DirList
from os3.fs.entry import get_path
from os3.fs.utils import get_node
from os3.utils.decorators import withrepr
@withrepr(lambda x: DirList().print_format())
def ls(path='', depth=None, **kwargs):
return DirList(path).ls(depth, **kwargs)
ls.filter = DirList... |
#This program will calculate a persons BMI using figures provided
#The inputs are the person's height in centimetres and weight in kilograms.
#The output is their weight divided by their height in metres squared.
weight = float(input("Enter your weight in KG; "))
height = float(input("Enter your height in meters;... |
import bz2
import os
import pickle
from faker.providers import BaseProvider
with bz2.open(os.path.join(os.path.dirname(__file__), "substances.bz2"), "rb") as f:
SUBSTANCES = pickle.load(f)
class SubstanceFaker(BaseProvider):
substances = SUBSTANCES
def sid(self):
return f"DTXSID{self.random_int... |
"""
Input/output functions for the word_graphs API, including
functions for storing and retrieving word graphs and subgraphs.
Functions:
get_integer, get_word_graph_filename, get_word_subgraph_filename,
store_word_graph, retrieve_word_graph, retrieve_word_graph_statistics,
store_word_subgraphs, retrieve... |
def solution(N):
return len(max(format(N,'b').strip('0').split('1')))
if __name__ =="__main__":
X= solution(20)
print (X)
|
"""
Quantiphyse - Base class for logging
Copyright (c) 2013-2020 University of Oxford
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 require... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.