content
stringlengths
5
1.05M
from django.contrib.postgres.fields import ArrayField from django.db import models from apps.tags.models import SubjectTag class Course(models.Model): subject = models.ForeignKey( SubjectTag, verbose_name='Предмет', on_delete=models.CASCADE) title = models.CharField( verbose_n...
from abc import ABC, abstractmethod from gzip import open as gzip_open from astropy.io import fits from pickle import load __all__ = ['PickleSource', 'FITSSource'] class Source(ABC): def __init__(self, filename): self.infile = filename self.file_object = None @abstractmethod def __next__...
from moto.core.responses import BaseResponse from moto.ec2.utils import filters_from_querystring, add_tag_specification from xml.sax.saxutils import escape class VPNConnections(BaseResponse): def create_vpn_connection(self): type = self._get_param("Type") cgw_id = self._get_param("CustomerGatewayI...
#!/usr/bin/env python2 # Copyright (c) 2015-2017, NVIDIA CORPORATION. All rights reserved. """ Functions for creating temporary LMDBs Used in test_views """ from __future__ import print_function import argparse import os import random import re import sys import time import lmdb import numpy as np import PIL.Image ...
# coning: utf-8 import time from django.db import transaction from . import database from . import database_operation from . import models from . import haxi_simple_model_CRUD class Examine(object): @staticmethod def get_bank(limit=None, skip=None, desc='-b_id', fields=[], contions={}): fields = field...
""" Read full .ndpi slides, rough segmentation of tissue areas, random selection of centroids, extract 1001x1001 windows around centroids. The windows are saved with row_R_col_C, where R, C are the row, col centroid of the image. You can get the offset of the image from the centroid as offset = centroid - box_half_siz...
__author__ = 'Dominic Miglar <dominic.miglar@bitmovin.net>' import unittest from bitcodin.util import convert from bitcodin.test.bitcodin_test_case import BitcodinTestCase class ConvertTestCase(BitcodinTestCase): def setUp(self): super(ConvertTestCase, self).setUp() def runTest(self): camel...
from magicalimport import import_from_physical_path foo = import_from_physical_path("../a/b/c/foo.py", as_="foo2", here=__file__) print(foo.name) import foo2 # noqa: F401 print(foo2.name)
import matplotlib matplotlib.use('Agg') import pylab import sys import numpy from utils import diversity_utils, gene_diversity_utils, stats_utils from parsers import parse_midas_data import os # Load time metadata subject_sample_time_map = parse_midas_data.parse_subject_sample_time_map() # store data in these varia...
import torch from torch import nn from torch.nn import Module from torch.nn import functional as F from torchcrf import CRF from transformers import BertModel, BertPreTrainedModel # from transformers import add_start_docstrings, add_start_docstrings_to_callable from loss import FocalLoss, DSCLoss, DiceLoss, LabelSmoot...
from pylearn2.train_extensions import TrainExtension from pylearn2.utils import serial class pylearn2_save_callback(TrainExtension): def __init__(self, my_save_path=None, save_at=None, save_every=None): self.my_save_path = my_save_path self.save_at = save_at self.save_every = save_every ...
#pip install requests import requests response = requests.get('https://api.github.com') #response.status_code ''' response.content response.text response.headers response.headers['Content-Type'] response.elapsed.total_seconds() ''' '''from requests.exceptions import HTTPError for url in ['https://api.github.com', 'htt...
import asyncio from concurrency import utils import typing class ChannelClosed(Exception): def __init__(self, channel_id): super().__init__(channel_id) self.channel_id = channel_id T = typing.TypeVar("T") class _ChannelCommon(typing.Generic[T]): __slots__ = ["_channel_id", ...
#!/usr/bin/python # indexing.py n = [1, 2, 3, 4, 5, 6, 7, 8] print (n[0]) print (n[-1]) print (n[-2]) print (n[3]) print (n[5])
#!/usr/bin/env python # -*- coding: utf-8 -*- from six.moves import range import numpy as np from scipy import stats from sm2.tools.tools import not_ported # TODO: should this be public if it's just a container? class ContrastResults(object): """ Class for results of tests of linear restrictions on coeffici...
class cogit: def __init__(self): pass
#!/usr/bin/env python3 """ Displays robot fetch at a disco party. """ from mujoco_py import load_model_from_path, MjSim, MjViewer from mujoco_py.modder import TextureModder import os model = load_model_from_path("../xmls/fetch/main.xml") sim = MjSim(model) viewer = MjViewer(sim) modder = TextureModder(sim) t = 0 wh...
import xadmin from .models import Comment @xadmin.sites.register(Comment) class CommentAdmin: list_display = ('target', 'nickname', 'content', 'website', 'created_time')
#This is a smart version of the classic snake arcade game using BFS # to determine routes to take. import curses from curses import KEY_RIGHT, KEY_LEFT, KEY_UP, KEY_DOWN import random #constant variables HEAD = 0 FOOD = 0 LEFT = -1 RIGHT = 1 #bad move ERROR = -1111 #game board height HEIGHT = 20 #g...
from gitz import config def _version(): with open('gitz/config.py') as fp: line = next(i for i in fp if i.startswith('__version__')) return line.strip().split()[-1].strip("'") if __name__ == '__main__': import setuptools with open('README.rst', 'rb') as fp: desc = fp.read() ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ """ from dmpnn.data import featurize import argparse import torch import numpy import pandas import matplotlib.pyplot from tqdm.auto import tqdm from sklearn.metrics import r2_score from scipy.stats import pearsonr, kendalltau __author__ = "Damien Coupry" __copyr...
def solution(n): memo = [[0 for _ in range(n + 2)] for _ in range(n + 2)] return staircase(1, n, memo) - 1 def staircase(h, l, memo): if memo[h][l] != 0: return memo[h][l] if l == 0: return 1 if l < h: return 0 memo[h][l] = staircase(h + 1, l - h, memo) + stai...
from driver_risk_utils import general_utils """ Tests to make sure timers are passed by reference. """ timer = general_utils.Timing() def test_fn(timer): timer.update_start("Test") for i in range(1000): a = i * i timer.update_end("Test") timer.print_stats() print("Before function call") test_fn...
"""Track packages from dhl via api""" from urllib.parse import urlparse import json import logging from datetime import timedelta import requests import voluptuous as vol #from homeassistant.helpers.entity import Entity from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.components.senso...
#!/usr/bin/env python """ Script for """ import requests import pandas as pd import xmltodict #import pprint #import json if __name__ == '__main__': # working example # http://esgf-node.jpl.nasa.gov/esg-search/search?project=obs4MIPs&variable=hus&variable=ta&model!=Obs-AIRS # http://https://esgf-index1.c...
"""Flask SQLAlchemy ORM models for Social Auth""" from peewee import Model, ForeignKeyField, Proxy from social.utils import setting_name, module_member from social.storage.peewee_orm import PeeweeUserMixin, \ PeeweeAssociationMixin, \ Pe...
# Micropython driver for the TTY6955/TTY6945 # Capacitive touch key sensor IC # Copyright 2020, Thomas TEMPE # DWTFYL license. # # The two IC apparently have the same features and protocole, # and differ only by the number of pads they can drive. # Warning: these chip can drive up to 3 sliders, but can't detect when yo...
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # 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 rights # to us...
from __future__ import print_function import sqlite3 from enum import Enum from passlib.hash import pbkdf2_sha256 class Account(object): """ """ def __init__(self, username, password): self.username = username self.password = password def __str__(self): return '(username={...
import os from setuptools import find_packages, setup ROOT = os.path.abspath(os.path.dirname(__file__)) def read_version(): data = {} path = os.path.join(ROOT, "synthtiger", "_version.py") with open(path, "r", encoding="utf-8") as fp: exec(fp.read(), data) return data["__version__"] def re...
from item import Item from tile import Tile from projectile_collection import PROJECTILES from random import choice def drop(self, engine, user): self.position = user.forwards self.old_position = user.forwards if engine.place(self): user.inventory = None from pygame_objects import SOUNDS ...
#!/usr/bin/env python import rospy from std_msgs.msg import UInt16 from sensor_msgs.msg import Joy import math from operator import add def joystick_callback(data): print data global last_update global front_left_pub global front_right_pub global back_left_pub global bac...
from __future__ import absolute_import, division, print_function, unicode_literals from gratipay.testing import BrowserHarness class Tests(BrowserHarness): def test_clicking_resend_doesnt_error(self): self.make_participant('alice', claimed_time='now') self.sign_in('alice') self.visit('/~...
import re from .rest_api_context import RestAPIContext class RestSchema: def __init__(self, routes=None): self.routes = routes or {} self.build() def build(self): self._ordered_routes = list(reversed(sorted( list(self.routes.items()), key=lambda x: len(x[0]) ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging import threading import time import frida from lib.core.frida_thread import FridaThread from lib.core.types import FakeDevice from lib.utils.shell import Shell class WatchThread(threading.Thread): def __init__(self): super().__init__() ...
#!/usr/bin/env python # # Copyright (c) 2017 10X Genomics, Inc. All rights reserved. # import math import cellranger.analysis.multigenome as cr_mg_analysis import cellranger.h5_constants as h5_constants from cellranger.matrix import CountMatrix import cellranger.io as cr_io __MRO__ = """ stage RUN_MULTIGENOME_ANALYSIS...
#Code based on python DScript library (pip install dscript ) #This file mostly uses the hyperparameters and sets up the networks as done in the train.py file from dscript #MIT License #Copyright (c) 2020 Samuel Sledzieski #Permission is hereby granted, free of charge, to any person obtaining a copy #of this so...
import collections import itertools import re data = [] data = [['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'], ['a', 'f', 'g'], ['b', 'd', 'e', 'f', 'j'], ['a', 'b', 'd', 'i', 'k'], ['a', 'b', 'e', 'g'], ['g', 'b']] # print(data) data = data support = 3 # ite frequency CountItem = collections.defaultdict(int) for line...
class Solution(object): def licenseKeyFormatting(self, S, K): """ :type S: str :type K: int :rtype: str """ S = S.upper() #upper case groups = ''.join(S.split('-')) #join bias = len(groups) % K #check how many for the left devides = len(groups)...
from __future__ import absolute_import, division, print_function from iotbx import mtz from cctbx import crystal def extract_from(file_name): mtz_object = mtz.object(file_name=file_name) assert mtz_object.n_symmetry_matrices() > 0 return mtz_object.crystals()[0].crystal_symmetry() extract_from(file_name="3nd...
"""F5 Agent code for LBaaSv2.""" import eventlet eventlet.monkey_patch()
import copy import unittest from module.mining import LatticeGraph class TestLatticeGraph(unittest.TestCase): num_of_dims = 3 lattice_graph_inst = LatticeGraph(num_of_dims) clone_lattice_graph_inst = copy.deepcopy(lattice_graph_inst) def test_init_graph(self): expected_graph = ("{0: {'(0, 1, ...
"""Test interface update payload.""" from ipaddress import ip_address, ip_interface import pytest from supervisor.dbus.payloads.generate import interface_update_payload from supervisor.host.const import AuthMethod, InterfaceMethod, InterfaceType, WifiMode from supervisor.host.network import VlanConfig, WifiConfig fro...
# Copyright 2015 Ufora Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
__author__ = 'jie' from PyQt5.QtWidgets import QLabel,QLineEdit,QDockWidget,QWidget,QHBoxLayout,QVBoxLayout,QCheckBox,QDialogButtonBox,QGroupBox,QFormLayout,QMessageBox from PyQt5 import QtCore import cadnano.util as util from cadnano.oligo.removeoligocmd import RemoveOligoCommand class DockWidget(QDockWidget): ''...
import plotly.io as pio from .plotly_util import make_slider_figure, add_vertical, add_horizontal from . import hover_info from .dat_plotting import OneD, TwoD, ThreeD from ...core_util import Data1D, Data2D pio.renderers.default = 'browser'
import pytest import os from aim_trajectory_picking import JSON_IO from aim_trajectory_picking import algorithms from aim_trajectory_picking import pick_trajectories from aim_trajectory_picking import util def algorithm_testing_function(algorithm): targeted_result_list = [] directory = r'./testsets' test_...
from setuptools import setup # To use a consistent encoding from codecs import open from os import path here = path.abspath(path.dirname(__file__)) import sys sys.path.insert(0, path.join(here, 'src')) import komparse_gen # Get the long description from the README file with open(path.join(here, 'README.md'), encodin...
class TestConfiguration: def __init__(self, keyValuePairs): self.keyValuePairs = keyValuePairs def get(self, section, key, fallback): key = f'{section}|{key}' if key in self.keyValuePairs: return self.keyValuePairs[key] return fallback def getint(self, secti...
import os import numpy as np import torch import cv2 import torchreid from torchreid import metrics from torch.nn import functional as F from tqdm import tqdm def evaluate_market_local(): dataset_cfg = {'root': '/home/liyongjing/Egolee_2021/data/open_dataset', 'sources': ['market1501'], 'target...
import math import torch import logging from functools import partial from torch.nn import functional as F from tensorboardX import SummaryWriter from torch.distributions.utils import lazy_property from torch.optim.lr_scheduler import ReduceLROnPlateau from torch.distributions.categorical import Categorical as TorchCat...
from keras.datasets import mnist from autokeras import ImageClassifier from autokeras.constant import Constant from autokeras.utils import pickle_from_file from keras.utils import plot_model import time model_file_name = 'mnist.model' if __name__ == '__main__': (x_train, y_train), (x_test, y_test) = mnist.load_...
from .base import request from . import config def login_with_email(email): options = { 'method': 'POST', 'body' : { 'email' : email } } return request(options, 'v3/customers/login_with_email') def login_with_phone(phone): options = { 'method': 'POST', ...
from . import test_resized_attachments
import os import glob import numpy as np import pandas as pd import argparse parser = argparse.ArgumentParser() parser.add_argument("--frames-path", type=str, default="../UCF101FrameExtractor/UCF101_frames/") parser.add_argument("--save-path", type=str, default="./UCF101_few_shot_labels/") parser.add_argument("--categ...
#!/usr/bin/env python import sys import tensorflow as tf input_path = sys.argv[1] with tf.Session() as session: with open(input_path, "rb") as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) tf.import_graph_def(graph_def, name="") global_step = session.run("global_step:0...
# Generated by Django 2.2.23 on 2021-09-21 10:31 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('fn_portal', '0020_fn123_comment_to_comment3'), ] operations = [ migrations.AddField( model_name='fnprotocol', name=...
###################################################################### # # # Copyright 2009-2018 Lucas Heitzmann Gabrielli. # # This file is part of gdspy, distributed under the terms of the # # Boost Software License - Version ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('content', '0032_merge'), ] operations = [ migrations.DeleteModel( name='DonateInfo', ), migratio...
from django.conf.urls import url from content_notes.views import chooser, endnotes app_name = 'content_notes' urlpatterns = [ url(r'^choose/$', chooser.choose, name='choose'), url(r'^choose/(\d+)/$', chooser.chosen, name='chosen'), url(r'^$', endnotes.list, name='list'), ]
# flake8: noqa from dataclasses_json.api import (DataClassJsonMixin, LetterCase, dataclass_json) from dataclasses_json.cfg import config, global_config from dataclasses_json.undefined import CatchAll, Undefined
import queue import threading from process_exec.queued_io_channel import ReadIOChannel, IOChannelPublication, WriteIOChannel from process_exec.util.atomic_bool import AtomicBool def new_thread_safe_queue(): return queue.Queue() class ExecuteParallelRead: @staticmethod def __none_process(read_data): ...
'Generated protocol buffer code.' from google.protobuf.internal import enum_type_wrapper from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database _sym_db = ...
# -*- coding: utf-8 -*- """ libavwrapper.avconv ~~~~~~~~~~~~~~~~~~~~ Your entrypoint for every Task you want to do with AVConv :copyright: (c) 2012 by Mathias Koehler, Conrado Buhrer. :license: BSD, see LICENSE for more details. """ from subprocess import Popen, PIPE, STDOUT from itertools impor...
from .models import PhotoEntry, MedicationAmount, Medication, DrinkType, DrinkAmount, DayEntry, FoodTag, HeadacheTag from .serializers import UserSerializer, DetailDayEntrySerializer, TextEntrySerializer, DrinkEntrySerializer, SimpleDayEntrySerializer, MedicationEntrySerializer, PhotoEntrySerializer, FoodEntrySerialize...
def solution(A): value = None size = 0 for i, a in enumerate(A): if size == 0: value = a size += 1 else: if value != a: size -= 1 else: value = a size += 1 candidate_count = 0 for a in A:...
import os from setuptools import setup with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as fp: long_description = fp.read() setup( name='datauri', description="implementation of the data uri scheme defined in rfc2397", long_description=long_description, version='1.0.0', author=...
# import os # import pathlib # import string # import sys # from . import website # # # general note: I'm writing this pretty late, way after the submissions deadline. # # I would ahve created a class to hold all the handler methods and would have implemented it using the cli class. # # I have had a doubt that decorati...
#!/usr/bin/env python2.7 # encoding: utf8 import os import sys import time sys.path.append(os.path.realpath(__file__ + '/../../../lib')) sys.path.append(os.path.realpath(__file__ + '/..')) import udf from abstract_performance_test import AbstractPerformanceTest class ScalarEmitConsumeColumnsRPeformanceTest(Abstrac...
import unittest import numpy as np from convnet.layers.convolutional_layer import ConvolutionalLayerSettings, _ConvolutionalLayer, ConvolutionalLayer from convnet.layers.input_layer import InputLayerSettings, InputLayer from convnet.net import ConvNet class ConvolutionalLayerTest(unittest.TestCase): def test_fo...
safe_z = 5 low_z = -0.9 feedrate = 300 #feedrate for via hits current_drill_size = 3 #in tool list, tools with a diameter of 3 are for locator holes. output = open('output_files/locator_drills.ngc','w+') output.write('%\n') output.write('M03 S24000;\n') input_file = open('input_files/drills.drd') #Split into tool s...
""" Copyright 2020 The OneFlow 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 applicable law or agr...
import numpy as np ''' simple function to compute the menger curvature. https://en.wikipedia.org/wiki/Menger_curvature ''' def menger(xyj,xyk,xyl): ''' Compute the curvature from three (x,y) pairs. ''' #xyj=np.array(xyj) #xyk=np.array(xyk) #xyl=np.array(xyl) if np.allclose(xyj,xyk) or np.a...
import logging from dataclasses import dataclass from enum import Enum, unique from typing import Callable, Dict, Optional, Tuple import numpy as np import pandas as pd import plotly.graph_objects as go from analysis.src.python.evaluation.issues_statistics.get_raw_issues_statistics import VALUE from analysis.src.pytho...
# A class to collect alert properties import glob import os import pandas as pd class Alert: def __init__(self, row): self.ra = float(row['RA [deg]']) self.dec = float(row['Dec [deg]']) self.err90 = float(row['Error90 [arcmin]']) self.err50 = float(row['Error50 [arcmin]']...
from django.contrib import admin from .models import ScLineUsr admin.site.register(ScLineUsr)
import unittest from problem_14 import estimate_pi class Problem14TestCase(unittest.TestCase): dp = 3 # we can not do specific assertion since it is based on random generation def test_estimate_pi(self): self.assertGreaterEqual(estimate_pi(self.dp), 3.1) if __name__ == "__main__": unittest....
#!/usr/bin/env python from __future__ import print_function import os import sys import numpy as np import tensorflow as tf import importlib import time import cv2 from tqdm import tqdm import pickle from mydatasets import * from det_tools import * from eval_tools import draw_keypoints from common.tf_train_utils impo...
#!/usr/bin/env python import unittest import os import sys from os.path import basename, join, normpath, \ dirname, exists, isdir from errno import ENOENT from modipyd import utils from tests import TestCase, FILES_DIR class TestModipydUtils(TestCase): def test_sequence(self): self....
# global import os import ivy try: import git except ModuleNotFoundError: git = None import abc import time import shutil import pathlib import logging import datetime import numpy as np from datetime import datetime # local from ivy_builder.abstract.network import Network from ivy_builder.specs.trainer_spec i...
#!/usr/bin/env python # -*- coding: utf-8 -*- # vispy: gallery 200 """ Example demonstrating the Game of Life in shaders. See http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life This examples uses textures and FBO's. """ import numpy as np from vispy.gloo import gl from vispy import gloo from vispy import app # G...
from marathon.models.app import MarathonApp class AsgardApp(MarathonApp): def get_constraints_by_name(self, consraint_name): result = [] for c in self.constraints: if c.field == consraint_name: result.append(c) return result def remove_constraints_by_name(s...
from UdonPie import System from UdonPie import UnityEngine from UdonPie.Undefined import * class AnimatorTransitionInfo: def __new__(cls, arg1=None): ''' :returns: AnimatorTransitionInfo :rtype: UnityEngine.AnimatorTransitionInfo ''' pass @staticmethod def IsName(a...
SCALE_MINMAX_FEATURE_KEYS = [ "Horizontal_Distance_To_Hydrology", "Vertical_Distance_To_Hydrology", ] SCALE_01_FEATURE_KEYS = [ "Hillshade_9am", "Hillshade_Noon", "Horizontal_Distance_To_Fire_Points", ] SCALE_Z_FEATURE_KEYS = [ "Elevation", "Slope", ...
"""Package errors."""
# Copyright 2014 - Rackspace Hosting # # 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 ...
from typing import Optional import torch # type: ignore from indigo import Indigo, IndigoObject # type: ignore indigo = Indigo() indigo.setOption("ignore-stereochemistry-errors", True) indigo.setOption("ignore-bad-valence", True) def atomic_number(mol: IndigoObject) -> dict: """Get the atomic number for each...
import cv2 as cv import numpy as np from matplotlib import pyplot as plt import glob import os import sys os.chdir(sys.path[0]) print('Starting task 1...') pics = glob.glob('resources/images/*.jpg') frame_prev = cv.imread(pics[0]) gray_prev = cv.cvtColor(frame_prev, cv.COLOR_BGR2GRAY) frame_shape = np.flip(gray_pre...
import unittest import lecture1_code00 as dl from sklearn.datasets.samples_generator import make_blobs class TestDeepLearning(unittest.TestCase): def setUp(self): self.X, self.Y = make_blobs(n_samples=50, centers=2, random_state=0, cluster_std=0.60) def tearDown(self): del self.X del ...
import numpy as np from numpy import shape from scipy import fftpack class cos_basic: ''' 基础离散余弦变换类 ''' def __init__(self, matrix): self.matrix = matrix def do_cos(self): data = fftpack.dct(fftpack.dct(self.matrix, axis=0, norm='ortho'), axis=1, norm='ortho') return np.l...
import datetime import os import glob import tables import json import numpy as np from core.data import open_data_file from core.model import isensee2017_model from core.generator import data_generator, get_number_of_steps, get_number_of_patches from core.training import train_model from unet.unet_config import get_k...
print('===== DESAFIO 052 =====') num = int(input('digite um numero: ')) tot = 0 for c in range(1, num + 1): if num % c == 0: tot += 1 print('\033[33m',end='') else: print('\033[31m',end='') print(f'{c} ', end='') print(f'\n\033[mo numero {num} foi divido {tot} vez') if tot == 2: ...
# Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: urban@reciprocitylabs.com # Maintained By: urban@reciprocitylabs.com from freezegun import freeze_time from datetime import date from ggrc import ...
def leap_year(year): """ - Add code in the defined function to figure out whether or not the given year is a leap year or not. - Every year that is exactly divisible by four is a leap year, except for years that are exactly divisible by 100, but these centurial years are leap years if they are exactly...
# Generated by Django 3.0.8 on 2020-08-08 22:24 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('Main', '0002_address_order_orderitem_payment'), ] operations = [ migrations.AlterModelOptions( ...
import unittest from lesson_01_iterations.binary_gap import solution # Command to execute the test: # python -m unittest -v class TestBinaryGap(unittest.TestCase): def test_binary_gap(self): self.assertEqual(solution(1), 0) self.assertEqual(solution(2), 0) self.assertEqual(solution(147), ...
import dotenv import os import pathlib from .integration_test_utils import ( IterableApiHelpers, generate_csv_file, generate_newline_delimited_json_file, ) from iterable_data_import import ( IterableDataImport, FileFormat, UserProfile, UpdateUserProfile, CustomEvent, TrackCustomEven...
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Dotconf(AutotoolsPackage): """dot.conf configuration file parser.""" homepage = "http...
# Unit tests for R8_20.py # IMPORTS import R8_20 import unittest # main class SetsTests(unittest.TestCase): def setUp(self): self.set_a = {1, 2, 3, 4} self.set_b = {2, 4, 6, 8} self.set_c = {5, 7, 9, 2} def test_create_new_set_from_union_of_two_sets(self): self.assertEqual({1...
"""Generates Dockerfiles based on an input matrix based on Python.""" import os from ..conda import CondaBuildPack class PythonBuildPack(CondaBuildPack): """Setup Python for use with a repository.""" @property def python_version(self): if hasattr(self, '_python_version'): return self...