content stringlengths 5 1.05M |
|---|
import tensorflow as tf
from model import ops
from model.ops import up_sample, upsample_ps
def _block(x, labels, out_channels, num_classes, name, conv=ops.snconv2d, kernel=(3, 3), strides=(1, 1),
dilations=(1, 1), act=tf.nn.leaky_relu, pooling='avg', padding='SAME'):
"""Builds the residual blocks used ... |
# def merge(arr, l, m, r):
# print("==m:")
# n1 = m - l + 1
# n2 = r - m
#
# # 创建临时数组
# L = [0] * (n1)
# R = [0] * (n2)
#
# # 拷贝数据到临时数组 arrays L[] 和 R[]
# for i in range(0, n1):
# L[i] = arr[l + i]
#
# for j in range(0, n2):
# R[j] = arr[m + 1 + j]
#
# # 归并临... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2017-10-12 21:18
from __future__ import unicode_literals
from django.db import migrations
def delete_hayward_clean_slate_clinic(apps, schema_editor):
Address = apps.get_model('user_accounts', 'Address')
Address.objects.filter(name='Hayward Clean Slate W... |
'''
@Date: 2019-11-09 23:22:07
@Author: ywyz
@LastModifiedBy: ywyz
@Github: https://github.com/ywyz
@LastEditors: ywyz
@LastEditTime: 2019-11-09 23:51:19
'''
import turtle
turtle.pensize(10)
# 正方形
turtle.goto(400, 0)
turtle.goto(400, -400)
turtle.goto(0, -400)
turtle.goto(0, 0)
turtle.pensize(1)
x = 0
y = 0
# 行
for n ... |
import pytest
# TODO: put some of this code into a pre-function
PHOTOS_DB = "./tests/Test-10.14.6.photoslibrary/database/photos.db"
PHOTOS_DB_PATH = "/Test-10.14.6.photoslibrary/database/photos.db"
PHOTOS_LIBRARY_PATH = "/Test-10.14.6.photoslibrary"
ALBUMS = ["Pumpkin Farm", "AlbumInFolder", "Test Album", "Test Alb... |
import unittest
from pyjsg.jsglib import JSGString, JSGPattern
class Issue9TestCase(unittest.TestCase):
def test_issue_9(self):
self.assertTrue(isinstance("abc", JSGString))
self.assertTrue(isinstance("", JSGString))
self.assertFalse(isinstance(None, JSGString))
self.assertFalse(... |
# n = flowerbed.length
# time = O(n)
# space = O(1)
# done time = 20m
class Solution:
def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
not_planted_num = 1
for flower in flowerbed:
if flower != 0:
not_planted_num = 0
else:
not... |
import os
import io
import csv
import ast
import sys
import math
import struct
from enum import Enum
from exceptions import CSVError, SchemaError
csv.field_size_limit(sys.maxsize) # Don't limit the size of user input fields.
class Type(Enum):
UNKNOWN = 0
BOOL = 1
DOUBLE = 2
FLOAT = 2 # alias to... |
import datetime
import re
from warnings import warn
def sparql_escape_string(obj):
if not isinstance(obj, str):
warn("You are escaping something that isn't a string with \
the 'sparql_escape_string'-method. Implicit casting will occurr.")
obj = str(obj)
return '"""' + re.sub(r'[\\\'"]',... |
#
# PyDB
# A simple way to store persistent data in Python.
# Version 2.0
# (c) 2018 Matthew Gallant
# Licensed under the MIT license
#
import os
def set(key, data):
if not os.path.exists(".pydb/"):
os.makedirs(".pydb/")
dataStore = open(".pydb/" + key + ".data", "w+")
dataStore.write(str(data))
... |
import boto3
import os
from datetime import datetime
from time import sleep
import sys
import subprocess
import json
import gzip
import urllib
BINARY_PATH=sys.argv[1]
#endpoint_url = "http://localhost:8000/"
### CHOOSE REGION ####
#EC2_REGION = 'us-east-1'
###CHOOSE NAMESPACE PARMETERS HERE###
my_NameSpace = 'Accel... |
"""
Fibonacci version 1.5.10.20
Copyright (c) 2020 Shahibur Rahaman
Licensed under MIT
"""
def words(term):
for i in range(term):
i += 1
word = ""
if i == 1:
word += "th"
elif i == 2:
word += "nd"
elif i == 3:
word += "rd"
else:
word += "th"
return word
def fib(term):
a = 0
b = 1
for _ ... |
import pandas as pd
import webbrowser
class Song:
def __init__(self,track_name: str = None,artist_name: str = None,track_id: str = None,genre: str = None,popularity: float = None,valence: float = None,danceability: float = None,energy: float = None,loudness: float = None):
self.genre = genre
self.... |
#On the name of ALLAH and may the blessing and peace of Allah
#be upon the Messenger of Allah Mohamed Salla Allahu Aliahi Wassalam.
#Author : Fouad Teniou
#Date : 06/07/10
#version :2.6
"""
maclaurin_series_two is a function to compute 1/1+x^2 using maclaurin series
and the interval of convergence is -1 < x < 1
1/1+... |
import io
import os
import zipfile
import tarfile
import gzip
import shutil
from functools import partial
import torch.utils.data
from .utils import RandomShuffler
from .example import Example
from ..utils import download_from_url, unicode_csv_reader
class Dataset(torch.utils.data.Dataset):
"""Defines a dataset... |
import random
print('=--Student name picker--=')
print('How many students do you want to register?')
nStudents = int(input('Number of students: '))
students = []
index = 0
while index < nStudents:
studentName = input('Enter the name of student number {} '.format(index + 1))
students.append(studentName)
i... |
# The following source code was originally obtained from:
# https://github.com/keras-team/keras/blob/r2.6/keras/layers/core.py#L388-L430
# https://github.com/keras-team/keras/blob/r2.6/keras/layers/preprocessing/image_preprocessing.py#L314-L361
# =========================================================================... |
# Funções para votação
def voto (ano):
from datetime import date
ano_atual = date.today().year
idade = ano_atual - ano
if idade < 16:
print("Voto NEGADO!")
elif idade >= 16 and idade < 18:
print("Voto OPCIONAL!")
else:
print("Voto OBRIGATORIO!")
voto(int(input("Em que ano... |
import json as simplejson
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.views.generic import TemplateView
from django.template.loader import render_to_string
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
f... |
""" Module containing Galaxy workflow scheduling plugins. Galaxy's interface
for workflow scheduling is highly experimental and the interface required for
scheduling plugins will almost certainly change.
"""
from abc import ABCMeta
from abc import abstractmethod
class WorkflowSchedulingPlugin( object ):
""" A plu... |
from collections import defaultdict
import threading
import queue
class Program(threading.Thread):
def __init__(self, raw_cmds, idd):
super().__init__()
self.idd = idd
self.rcv_q = queue.Queue()
self.send_q = None
self.commands = [line.strip().split(' ') for line in raw_cmd... |
from fairness.algorithms.Ben.utils import *
from fairness.algorithms.Ben.errorfunctions import *
from fairness.algorithms.Ben import svm
import numpy
from fairness.algorithms.Ben import lr
from fairness.algorithms.Ben import boosting
from fairness.algorithms.Ben.weaklearners.decisionstump import buildDecisionStump
imp... |
from .types import DocumentMapping, DocumentSet
from collections import defaultdict
from matplotlib.colors import to_hex
import seaborn as sns
import json
import numpy as np
import networkx as nx
import pyvis
import textwrap
def calculate_layout(g, iterations=1000, gravity=1):
try:
from fa2 import ForceAt... |
from django.contrib import admin
from quotes_v1.models import Languages, Quotes
admin.site.register(Languages)
admin.site.register(Quotes)
|
def addition(x, y):
""" Adds x and y. Solution for day 2.
"""
return x + y
def subtraction(x, y):
""" Subtracts x with y. Solution for day 2.
"""
return x - y
def divison(x, y):
""" Divide x with y. Solution for day 2.
"""
return x / y
def multiplication(x, y):
""" M... |
import re
import sys
import urllib.request
def parse_uptime(uptime):
space_pattern = re.compile('\\s+')
def extract_number(x):
return int(space_pattern.split(x[0])[0])
result = 0
days = re.compile('[0-9]+\\s+jour').findall(uptime)
if days:
result += extract_number(days) * 24 * 60... |
#!/usr/bin/env python3
from abc import ABC, abstractmethod
from typing import Optional, Tuple
import torch
from matplotlib.axis import Axis
from torch import nn
class BasicCurve(ABC, nn.Module):
def __init__(
self,
begin: torch.Tensor,
end: torch.Tensor,
num_nodes: int = 5,
... |
# coding: utf-8
# /*##########################################################################
# Copyright (C) 2016 European Synchrotron Radiation Facility
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# i... |
"""Django CAS 1.0/2.0 authentication backend"""
from django.conf import settings
__all__ = []
_DEFAULTS = {
'CAS_ADMIN_PREFIX': None,
'CAS_EXTRA_LOGIN_PARAMS': None,
'CAS_IGNORE_REFERER': False,
'CAS_LOGOUT_COMPLETELY': True,
'CAS_REDIRECT_URL': '/',
'CAS_RETRY_LOGIN': False,
'CAS_SERVER_... |
from django import forms
class RegistroForm(forms.Form):
nombre = forms.CharField(max_length=100)
apaterno = forms.CharField(max_length=100)
amaterno = forms.CharField(max_length=100)
telefono = forms.CharField(max_length=100)
escuela = forms.CharField(max_length=100)
correo = forms.CharField(max_length=100)
pa... |
from django.core import exceptions as django_exceptions
from django.core.exceptions import PermissionDenied
from django.http import Http404
from django.test import TestCase
from misago.core import exceptionhandler
from misago.core.exceptions import Banned
from misago.users.models import Ban
INVALID_EXCEPTIONS = [
... |
# A collection of grabbers capable of filling a shared frame
# with captured image and timestamp
# __all__ = ['factory', ] |
from os.path import join, dirname
from setuptools import setup
from setuptools.extension import Extension
from Cython.Build import cythonize
import numpy as np
path = dirname(__file__)
src_dir = join(dirname(path), "..", "src")
defs = [("NPY_NO_DEPRECATED_API", 0)]
inc_path = np.get_include()
# If we need random/lib... |
'''
extract the speech from the whole dataset, and save each file under the same folder as the
'''
from utils import get_all_transcript_paths, safe_read
from extract_speech import extract_speech_string
from tqdm import tqdm
if __name__ == '__main__':
for path in tqdm(list(get_all_transcript_paths())):
tra... |
# -*- coding: utf-8 -*-
"""Database module, including the SQLAlchemy database object and DB-related utilities."""
# flake8: noqa # flake8 has real problems linting this file on Python 2
from pprint import pformat
from sqlalchemy import desc, or_
from sqlalchemy.sql.sqltypes import Date, DateTime
from werkzeug impor... |
from flask_login import UserMixin
from . import db
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(100), unique=True)
password = db.Column(db.String(100))
name = db.Column(db.String(1000))
# Foreign key relationship to meals
meals = db.r... |
##########################
# Custom Libraries #
import mapcontroller as mapctrl
##########################
# Built-in Libraries #
from queue import heappop,heappush
from enum import IntEnum
from pysat.solvers import Glucose4
import numpy as np
def h_n(start_pos:tuple,des_pos:tuple):
return abs(start_pos[... |
from dolfin import *
from xii import OuterNormal, EmbeddedMesh
import numpy as np
mesh = UnitSquareMesh(10, 10)
f = MeshFunction('size_t', mesh, 1, 0)
CompiledSubDomain('near(x[1], 0)').mark(f, 1)
CompiledSubDomain('near(x[1], 1)').mark(f, 1)
bmesh = EmbeddedMesh(f, 1)
n = OuterNormal(bmesh, [0.5, 0.5])
# Top?
for ... |
"""
Page definitions for the experiment.
March 2021, Markus Konrad <markus.konrad@wzb.eu>
"""
from otree.api import Currency as c, currency_range
from ._builtin import Page, WaitPage
from .models import Constants, FruitOffer, Purchase
from django.forms import modelformset_factory, ModelForm, IntegerField, HiddenInpu... |
#!/usr/bin/python
# Uses poogie to dump quest information from a pcap file. Only works with MHGen.
#
# ./get-quests.py <pcap file>
#
# Most of this will get moved into poogie itself at some point.
from poogie.poogie import MHGenPoogie
import sys
from datetime import timedelta
from mh_data.mhg_quests import mhg_quest... |
"""
Hilbert Space based regression
==================================
"""
from numpy import sqrt, array, ndarray, delete, concatenate, power
from numpy.linalg import det
from scipy import integrate
from scipy.stats import t
try:
from sklearn.base import BaseEstimator, RegressorMixin
except ModuleNotFoundError:
... |
# Copyright (c) 2015 Midokura SARL, All Rights Reserved.
#
# @author: Antonio Sagliocco <antonio@midokura.com>, Midokura
import logging
from injector import inject
from midonet_sandbox.wrappers.docker_wrapper import Docker
from midonet_sandbox.exceptions import ContainerNotFound
from midonet_sandbox.utils import exce... |
from contextlib import contextmanager
from tensorflow.keras.utils import get_custom_objects
def memory_as_readable_str(num_bits: int) -> str:
"""Generate a human-readable string for the memory size.
1 KiB = 1024 B; we use the binary prefix (KiB) [1,2] instead of the decimal prefix
(KB) to avoid any conf... |
import numpy as np
import argparse
parser = argparse.ArgumentParser(
description='Nearest neighbours of an entity of FB15k'
)
parser.add_argument('--ent', metavar='',)
args = parser.parse_args()
distmult_nn_idx = np.load('results/NN/distmult_nn_idxs.npy')
distmult_nn_val = np.load('results/NN/distmult_nn_vals.np... |
from . import db
from flask_login import UserMixin
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(100), unique=True)
password = db.Column(db.String(100))
name = db.Column(db.String(1000))
highscore = db.Column(db.Integer, default = 0) |
"""Generate snippets of markdown for various types of supporters.
These are meant to be inserted into our docs.
"""
from pathlib import Path
from yaml import safe_load
# Code to generate the HTML grid
template_binderhub = """
```{{grid-item-card}}
:text-align: center
:class-header: bg-light
:class-body: sd-p-4 sd-m-au... |
from concurrent import futures
import time
import grpc
import classification_pb2
import classification_pb2_grpc
import sys
import subprocess
from classification import Vgg16Classifier
_ONE_DAY_IN_SECONDS = 60 * 60 * 24
model = Vgg16Classifier()
class Classification(classification_pb2_grpc.ClassificationServicer):
... |
#!/usr/bin/env python3
#
# Copyright (c) 2018-2020 The MicroBitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Download or build previous releases.
# Needs curl and tar to download a release, or the build d... |
import socket
import sys
class TcpClient():
def __init__(self):
self.sock = None
def connect(self, address, port):
server_address = (address, port)
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect(server_address)
def disconnect(self):
... |
import logging
from scipy.stats import scoreatpercentile, percentileofscore
import numpy as np
class ModellingError(Exception): pass
class Base(object):
"""Base model inherited by all real models"""
def __init__(self, training_data):
self.fit(training_data)
self.training_residuals = self.res... |
from enum import Enum
class TIPO_DATO(Enum) :
CREATE_TABLE = 1
class Simbolo() :
'Esta clase representa un simbolo dentro de nuestra tabla de simbolos'
def __init__(self, val, tipo, valor, ambito) :
self.val = val
self.tipo = tipo
self.valor = valor
self.ambito = ambito
c... |
import os, sys, inspect
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import numpy as np
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0, parentdir)
nf = 8
nf0 = 16
nf1 = 24
nf2 = 32
nf3 = 40
nf... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2019 The FATE 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/lic... |
# =============================================================================
# Copyright 2020 NVIDIA. All Rights Reserved.
# Copyright 2019 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 obt... |
from forex_python.converter import CurrencyRates, CurrencyCodes
def validate(to,frm,amount):
to_answer = check_valid_currency_type(to)
from_answer = check_valid_currency_type(frm)
amount_answer = check_valid_amount(amount)
return{"To":to_answer, "From":from_answer, "Amount":amount_answer}
def check_v... |
# This file is part of the P3IV Simulator (https://github.com/fzi-forschungszentrum-informatik/P3IV),
# copyright by FZI Forschungszentrum Informatik, licensed under the BSD-3 license (see LICENSE file in main directory)
import abc
import numpy as np
import itertools
import random
from p3iv_types.timestamp import Time... |
/usr/local/python3/lib/python3.7/base64.py |
# An array A consisting of N different integers is given. The array contains integers in the range [1..(N + 1)], which means that exactly one element is missing.
#
# Your goal is to find that missing element.
#
# Write a function:
#
# def solution(A)
#
# that, given an array A, returns the value of the missing element.... |
import logging
from logs.setup_logs import init_logs
from readers.file_reader import FileReader
logger = init_logs(__name__)
UP = '('
DOWN = ')'
floor_modifier = {
UP: 1,
DOWN: -1
}
def navigate_stairs(direction):
if direction in floor_modifier:
return floor_modifier[direction]
logging.erro... |
#! /usr/bin/env python
#
# This script compares RFMIP results from RTE+RRTMGP against a benchmark
#
import os
import sys
import numpy as np
import xarray as xr
import argparse
import urllib.request
#
# Comparing reference and test results
#
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="C... |
import json
from django.db import models
from django.contrib.auth.models import User
from django.contrib.postgres.fields import JSONField
from oauth2client.contrib.django_util.models import CredentialsField
from core.helpers import parse_sheet_url
class CredentialsModel(models.Model):
id = models.OneToOneField(Us... |
import pytest
from game_engine import models
from game_engine.lib.pasur import STATUS
pytestmark = pytest.mark.django_db
@pytest.fixture('function')
def match():
match = models.Match()
match.save()
return match
@pytest.fixture('function')
def game(match):
game = models.Game(match=match)
game.s... |
import logging
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.http import Request, HtmlResponse
from scrapy.utils.response import get_base_url
from scrapy.utils.url import urljoin_rfc
from scrapy.xlib.pydispatch import dispatcher
from scrapy import signals
from product... |
import numpy as np
import pandas as pd
from sagemaker_sklearn_extension.feature_extraction.text import MultiColumnTfidfVectorizer
from sklearn.compose import ColumnTransformer, make_column_selector
from sklearn.decomposition import TruncatedSVD
from sklearn.impute import SimpleImputer
from sklearn.linear_model import R... |
import tensorflow as tf
from argo.core.network.AbstractModule import AbstractModule
from argo.core.utils.argo_utils import create_panels_lists
class MSE(AbstractModule):
def __init__(self, name="MSE"): # drop_one_logit=0,
super().__init__(name = name)
#self._drop_one_logit = drop_one_logit
... |
from porc import Client
import random
client = Client("92598997-88c0-40cf-8cd7-767fe67470c8")
client.ping().raise_for_status()
def bubbleSort(l,s,n):
for i in range(0,n):
if l[i]>l[i+1]:
temp = l[i]
l[i] = l[i+1]
l[i+1] = temp
temp = s[i]
s[i]... |
#!/usr/bin/env python
from collections import defaultdict
from collections import OrderedDict
import copy
from intervaltree import IntervalTree
from ragoo_utilities.PAFReader import PAFReader
from ragoo_utilities.ReadCoverage import ReadCoverage
from ragoo_utilities.ContigAlignment import ContigAlignment
from ragoo_uti... |
# -*- coding: utf-8 -*-
import os
import setuptools
setuptools.setup(
name='done-sns-sns',
version='0.0.1',
description='Simple command to notify users when process is done_sns',
author='Shayne Miel',
author_email='miel.shayne@gmail.com',
url='https://github.com/FragLegs/done_sns-sns',
pac... |
import pytest
import pandas as pd
from gzreduction.schemas.schema import Schema, Question, Answer
@pytest.fixture()
def question_a():
question_a = Question(
name='question-12',
raw_name='T12'
)
question_a.set_answers([
Answer(
name='answer-0',
raw_name='a-... |
import argparse
import os
import timeit
import datetime
import pickle
from contrastive_losses import *
import torch.backends.cudnn as cudnn
from torch.utils import data, model_zoo
import torch.nn as nn
from utils.loss import CrossEntropy2d
from utils.loss import CrossEntropyLoss2dPixelWiseWeighted
import math
from uti... |
# --------------------------------------------------------
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
"""Train a Fast R-CNN network."""
import numpy as np
import os
import t... |
from problink.priors import *
from problink.xidmod import *
from problink.match import *
from problink.read_data import *
from problink.misc import * |
# Generated by Django 2.1.1 on 2020-01-28 19:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Training', '0004_auto_20200128_1919'),
]
operations = [
migrations.AddField(
model_name='trainingcourse',
name='shor... |
import numpy as _np
import scipy.fftpack as _scf
import scipy.signal as _scs
import warnings as _warning
import multiprocessing as _mp
import ctypes as _ctypes
__all__ = ['xcorr', 'acorr']
def xcorr(signal1, signal2, **kwargs):
"""
Calculate phase cross correlation (pcc)
between signal1 and signal2
... |
import upsert
import hashlib
class MergeFunction:
@classmethod
@upsert.memoize
def lookup(cls, controller, selector_keys, setter_keys):
return cls(controller, selector_keys, setter_keys)
@classmethod
def name(cls, controller, selector_keys, setter_keys):
uniq = '_'.join([controller... |
"""
Created on 10/2/2020
@author: Jingchao Yang
auto model training and cross region testing with predefined input/prediction combination
"""
import sys
sys.path.append(r"../multistep_lstm")
import matplotlib.pyplot as plt
import pandas as pd
import time
import math
from sklearn.metrics import mean_squared_error
from... |
# -*- coding: utf-8 -*-
class CibopathException(Exception):
"""Super class for all of Cibopath's exceptions."""
class CookiecutterContextError(CibopathException):
"""Raised when a cookiecutter.json cannot be decoded."""
class GetRequestError(CibopathException):
"""Raised when the status code of a resp... |
import argparse
import json
import os
import sys
from getpass import getpass
from .utils import error, file_type, info, output, serialize
from .vault import Tables, Vault
def parser_add_basics(parser):
parser.add_argument(
"-v",
"--verbose",
default=False,
action="store_true",
... |
# write hello world to the command line
print('hello world')
x = 1
print(x) # write the value of x to the command line
'''
This is a multi-line comment
second line
third line
'''
print('After triple single quote multi-line comment')
"""
This is also a multi-line comment
second line
third line
"""
print('After tripl... |
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.db import transaction
from application.models import Customer, User, Author
class CustomerSignUp(UserCreationForm):
first_name= forms.CharField(label='First Name' ,error_messages={'required': 'Please enter your first name'... |
import string
import random
import requests, os, sys, tempfile, subprocess, base64, time
import GetAddress
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
def CallUber_Run():
# initial parameter
email_list = "xyz@gmail.com"
... |
def setup():
raise "KABOOM"
def test_foo():
assert(1==1)
|
import os
import psutil
import time
import gc
import numpy as np
import pandas as pd
import lightgbm
# memory status
process = psutil.Process(os.getpid())
memused = process.memory_info().rss
print('Total memory in use before reading data: {:.02f} GB '
''.format(memused / (2 ** 30)))
# read data
df_train = pd.re... |
moves=((1, 2), (1, -2), (-1, 2), (-1, -2), (2, 1), (2, -1), (-2, 1), (-2, -1))
def knights_tour(start, size):
temp=helper(start[0], start[1], size, size**2, set())
return [tuple(i) for i in [start]+temp]
def helper(y, x, size, total, memo):
temp=[]
memo.add((y, x))
for i,j in moves:
new_y, n... |
# Copyright (c) 2021 kraptor
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
import coloredlogs
import logging
def configure(log_format: str):
coloredlogs.install(fmt=log_format, level="DEBUG")
log = logging.getLogger(__name__)
for logger, level in {
"... |
#!/usr/bin/env python
# Copyright 2017 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 require... |
import requests
def get_json(user_name):
"""
Function sent request to Twitter Api and get .json object with information about current twitter user.
"""
base_url = "https://api.twitter.com/1.1/friends/list.json"
bearer_token = "AAAAAAAAAAAAAAAAAAAAAKkSNAEAAAAADGjajQeyVyQTi28qCAff1Mrl520%3DGzjvYM2Y... |
#função de calcular area
def area(l,c):
a = l * c
print(f'Sua area é {a:.2f}')
area(float(input('Comprimento')),float(input('Largura')))
|
# Copyright 2021, 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... |
a,b,c = input().split(" ")
a = float(a)
b = float(b)
c = float(c)
arr = [a,b,c]
arr.sort()
a = float(arr[2])
b = float(arr[1])
c = float(arr[0])
if a<(b+c) and a > 0 and b >0 and c >0:
if a**2 == (b**2 + c**2):
print("TRIANGULO RETANGULO")
if a**2 > (b**2 + c**2):
print("TRIANGULO OBTUSANGULO")... |
"""Common fixes used for multiple datasets."""
import iris
from .fix import Fix
from .shared import add_plev_from_altitude, fix_bounds
class ClFixHybridHeightCoord(Fix):
"""Fixes for ``cl`` regarding hybrid sigma height coordinates."""
def fix_metadata(self, cubes):
"""Fix hybrid sigma height coordi... |
def correct_bracketing(brackets: str):
"""brackets is a string of "(" and ")".
return True if every opening bracket has a corresponding closing bracket.
>>> correct_bracketing("(")
False
>>> correct_bracketing("()")
True
>>> correct_bracketing("(()())")
True
>>> correct_bracketing("... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
from typing import Any
import urllib.request
import recommonmark
from recommonmark.parser import CommonMarkParser
from recommonmark.parser import CommonMarkParser
from recommonmark.parser import CommonMarkParser
from recommonmark.transform import AutoS... |
# file: driver_utils.py
# author: Joram Wessels
# date: 11-12-2017
# dependencies: numpy
# description
# usage
#
from sys import stderr
from numpy import sign
# as stated by Torcs documentation
MAX_WHEEL_ROTATION = 21
# confusing polarities
STR_R, STR_L = -1, 1
ANG_R, ANG_L = 1, -1
DFC_R, DFC_L... |
"""
NSLS2V3 BSR Line
-----------------
"""
# :author: Lingyun Yang <lyyang@bnl.gov>
from lattice import *
|
import sys
import difflib
import pytest
import py
from xdist.slavemanage import NodeManager
queue = py.builtin._tryimport('queue', 'Queue')
class EachScheduling:
def __init__(self, numnodes, log=None):
self.numnodes = numnodes
self.node2collection = {}
self.node2pending = {}
if... |
# -*- coding: utf-8 -*-
#
# Copyright 2012-2015 Spotify AB
#
# 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... |
a,b=map(int,input().split())
print(4-(a+b>2)-(2<b>9-a)-(7<b>14-a)) |
"""
Downloads data files from ATF's site, saves them in fetched/YYYY-MM.txt
"""
from sys import argv, path as syspath
from pathlib import Path
syspath.append(str(Path(__file__).resolve().parents[1]))
from data_settings import DATA_DIRS
import requests
FETCHED_DATA_DIR = DATA_DIRS['fetched']
DATA_URLS = {
'2013-0... |
from django.contrib import admin
from .models import *
# Register your models here.
admin.site.register(Location)
admin.site.register(Hall)
admin.site.register(DanceStyle)
admin.site.register(Workshop)
admin.site.register(User)
admin.site.register(QueryForParticipance)
admin.site.register(QueryForTuition)
admin.site.re... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.