content
stringlengths
5
1.05M
#!/usr/bin/env python3 # This is a slightly modified version of timm's training script """ ImageNet Training Script This is intended to be a lean and easily modifiable ImageNet training script that reproduces ImageNet training results with some of the latest networks and training techniques. It favours canonical PyTor...
""" Prepare training and testing datasets as CSV dictionaries Created on 11/26/2018 @author: RH """ import os import pandas as pd import sklearn.utils as sku import numpy as np # get all full paths of images def image_ids_in(root_dir, ignore=['.DS_Store','dict.csv', 'all.csv']): ids = [] for id in os.listdi...
import sys import os import re from operator import attrgetter class LibrarySource(object): """Holds info on all the library source code""" class SourceFile(object): """Info for an individual source file""" class SectionFinder(object): """Match a section within a source file""" ...
"""Extract subject-question-answer triples from 20 Questions game HITs. See ``python extractquestions.py --help`` for more information. """ import collections import json import logging import click from scripts import _utils logger = logging.getLogger(__name__) # main function @click.command( context_sett...
import re PATH_TO_STOPWORDS = 'alfred/resources/stopwords.txt' def sterilize(text): """Sterilize input `text`. Remove proceeding and preeceding spaces, and replace spans of multiple spaces with a single space. Args: text (str): text to sterilize. Returns: sterilized message `text`. ...
import torch import torch.nn as nn class ExpWarpLoss(nn.Module): def __init__(self, yaw_warp, pitch_warp): super().__init__() assert yaw_warp * pitch_warp == 0 assert yaw_warp + pitch_warp > 0 self._Pwarp = pitch_warp > 0 print(f'[{self.__class__.__name__}] PitchWarp:{self....
import curve, defaults, glyphs, pathdata, plot, svg, trans # Only bring into the namespace the functions and classes that the user will need # This distinguishes user interface from internal functions # (Though the user can still access them, it intentionally requires more typing) # Internal class members are preceede...
""" # Definition for a Node. class Node: def __init__(self, val, left, right, next): self.val = val self.left = left self.right = right self.next = next """ class Solution: def connect(self, root: 'Node') -> 'Node': def add_children(queue, node): if node.left ...
from abc import ABCMeta, abstractmethod, abstractproperty import os import sqlite3 import time from .. import db class Task(metaclass=ABCMeta): @abstractproperty def name(self): """Name for the task""" pass @abstractmethod def should_run(self): """Check whether the f...
# -*- coding: iso-8859-15 -*- """ Grundmodul der Entwicklungsumgebung """ from optparse import OptionParser import sys import os import re import shutil endSkeletor = False options = None args = None def readTemplateFile(tmpname): fpath = sys.argv[0] fpath = os.path.split(fpath)[0] f = open(fpath+'/{0}...
# -*- coding: utf-8 -*- """ Created with IntelliJ IDEA. Description: User: jinhuichen Date: 3/20/2018 11:12 AM Description: """ from fetchman.pipeline.console_pipeline import ConsolePipeline from fetchman.pipeline.pic_pipeline import PicPipeline from fetchman.pipeline.test_pipeline import TestPipeline POSTGRES...
""" Base Class for HTTP Client we use to interact with APIs """ import json import requests import requests.packages.urllib3 # pylint: disable=E0401 import logging from random import choice from string import ascii_uppercase requests.packages.urllib3.disable_warnings() # pylint: disable=E1101 line_separator = '\n' ...
import os import zipfile import pandas as pd from ..datasets import core BASE_URL = "https://ti.arc.nasa.gov/" def load_turbofan_engine(): """ Load Turbofan Engine Degradation Simulation Dataset from https://ti.arc.nasa.gov/tech/dash/groups/pcoe/prognostic-data-repository/ :return: """ s...
from datetime import datetime from django.test import SimpleTestCase from data_schema.models import FieldSchemaType from data_schema.convert_value import convert_value class ConvertValueExceptionTest(SimpleTestCase): def test_get_value_exception(self): """ Tests that when we fail to parse a valu...
# -*- coding: utf-8 -*- """Dummy test case that invokes all of the C++ unit tests.""" import testify as T import moe.build.GPP as C_GP class CppUnitTestWrapperTest(T.TestCase): """Calls a C++ function that runs all C++ unit tests. TODO(GH-115): Remove/fix this once C++ gets a proper unit testing framework....
from .ichart import iChart
from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.http import HttpResponse from django.shortcuts import get_object_or_404, redirect, render from django.views.generic import DetailView, ListView from dfirtra...
""" Models for configuration of the feature flags controlling persistent grades. """ from config_models.models import ConfigurationModel from django.conf import settings from django.db.models import BooleanField, IntegerField, TextField from opaque_keys.edx.django.models import CourseKeyField from openedx.core.lib....
from collections import OrderedDict from .states import DefaultState from lewis.devices import StateMachineDevice class SampleHolderMaterials(object): ALUMINIUM = 0 GLASSY_CARBON = 1 GRAPHITE = 2 QUARTZ = 3 SINGLE_CRYSTAL_SAPPHIRE = 4 STEEL = 5 VANADIUM = 6 class SimulatedIndfurn(StateMa...
__author__ = 'Meemaw' vhodnaTabela = [] indeks = 0 with open("odpri.txt") as file: for line in file: indeks+=1 line = line.split() vhodnaTabela.append(map(int,line)) vhodnaTabela.append([0]*(indeks+1)) for i in range(indeks-1,-1,-1): for x in range(len(vhodnaTabela[i])): ...
import pandas as pd # df = pd.read_csv('Data/main_dataset.csv') df = pd.read_csv('Data/personality_questions_answers.csv') # personality_features = ['Openness', 'Conscientiousness', 'Extraversion', 'Agreeableness', 'Emotional range'] personality_features = ['openness', 'conscientiousness', 'extraversion', 'agreeable...
from common import * # NOQA from cattle import ApiError RESOURCE_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'resources/certs') def test_create_cert_basic(client): cert = _read_cert("san_domain_com.crt") key = _read_cert("san_domain_com.key") cert1 = clie...
{%extends 'setup.py.jj2'%} {%block platform_block%} {%endblock%} {%block morefiles%} 'CONTRIBUTORS.rst',{%endblock%}
from graphene_django import DjangoObjectType import graphene from dashboard.models import Course from dashboard.graphql.objects import CourseType from dashboard.rules import is_admin_or_enrolled_in_course, is_admin from graphql import GraphQLError import logging logger = logging.getLogger(__name__) class Query(graph...
"""Tests for avro2py/avro_types.py""" import avro2py.avro_types as avro_types def test_parsing_permits_metadata_attributes(): """ https://avro.apache.org/docs/1.10.2/spec.html#schemas states: "Attributes not defined in this document are permitted as metadata, but must not affect the format of seriali...
import pydub,os,PIL,ffmpeg,shutil,time,textwrap from pathlib import Path from gtts import gTTS from PIL import Image, ImageDraw, ImageFont from pydub import AudioSegment from moviepy.editor import * import snatch try: shutil.rmtree("out") except: pass os.mkdir("out") def insert_newlines(string, every=100): ...
from models.mobilenet import * def get_mobilenet(config): """ Get mobile based on config.py """ model = None if config.backbone == 'mobilenetv2': model = mobilenet_v2() return model
from os.path import dirname, abspath from imdbmovie.utilities.settings.site_config import SiteConfig site_config = SiteConfig(config_file='development.yaml').get_config() # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = dirname(dirname(abspath(__file__))) # JWT Authentication Confi...
PROJECT_ROOT = ".." import os import sys sys.path.insert(0, os.path.abspath(PROJECT_ROOT)) project = "mulberry" copyright = "2020, Hunter Damron" author = "Hunter Damron" with open(os.path.join(PROJECT_ROOT, "VERSION"), "r") as fh: release = fh.read().strip() version = ".".join(release.split(".")[:2]) # Get...
from math import fabs a = float(input("Enter a number: ")) b = float(input("Enter another number: ")) D = fabs(a - b) if D <= 0.001: print("Close.") else: print("Not Close.")
from django.forms import ModelForm from .models import * from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms class KundeForm(ModelForm): """ Eine Klasse zur Repräsentation einer Kundenform ... Classes ...
import contextlib import logging import os import subprocess import time import torch import torch.distributed as dist import seq2seq.data.config as config from seq2seq.inference.beam_search import SequenceGenerator from seq2seq.utils import AverageMeter from seq2seq.utils import barrier from seq2seq.utils import get...
''' You are given a positive integer. Your function should calculate the product of the digits excluding any zeroes. For example: The number given is 123405. The result will be 1*2*3*4*5=120 (don't forget to exclude zeroes). Input: A positive integer. Output: The product of the digits as an integer. Example: check...
from ClickablePopup import * from MarginPopup import * from otp.otpbase import OTPLocalizer import NametagGlobals class WhisperPopup(ClickablePopup, MarginPopup): WTNormal = 0 WTQuickTalker = 1 WTSystem = 2 WTBattleSOS = 3 WTEmote = 4 WTToontownBoardingGroup = 5 WTMagicWord = 6 WTGlobal...
import sys from math import sqrt EPS = 1e-9 class sp: def __init__(self): x, y = 0, 0 x_l, x_r = 0.0, 0.0 if __name__ == '__main__': for line in sys.stdin: n, l, w = map(int, line.strip('\n').split()) sprinkler = [sp() for _ in range(n)] for i in range(n): sprinkler[i].x, sprinkler[i]....
from updater_test import DBManager import numpy as np df = DBManager('final_datasets/all_rirs_final.csv', reg_time=True, time=True, step='second') df.first_policy() df = DBManager('final_datasets/all_standard_policy.csv', reg_time=True, time=True, step='second') df.apply_afrinic_policy() df = DBManager('final_data...
# coding=utf-8 # Copyright 2022 The ML Fairness Gym 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 obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'e:\git\softmech\nanoindentation\nano.ui' # # Created by: PyQt5 UI code generator 5.12.3 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self...
from django.shortcuts import render, render_to_response from blog.models import Author, Book # Create your views here. def show_author(request): authors = Author.objects.all() return render_to_response('show_author.html', {'authors': authors}) def show_book(request): books = Book.objects.all() return...
import numpy as np from scipy.optimize import linear_sum_assignment from scipy.stats import kendalltau import torch is_cuda = torch.cuda.is_available() device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') def sinkhorn_unrolled(c, a, b, num_sink, lambd_sink): """ An implementation of a Sinkhorn layer...
from .ReportDaily import * # Find all forks in organizations that have a parent in an organization. # Organizational repositories should have only one source of truth on # the entire instance. # # c.f. https://medium.com/@larsxschneider/talk-dont-fork-743a1253b8d5 class ReportForksToOrgs(ReportDaily): def name(self):...
#! /usr/bin/env python3 import os import time codes = { 'power': '16658433', 'mode_plus': '16658437', 'mode_minus': '16658443', 'speed_plus': '16658441', 'speed_minus': '16658439', 'demo': '16658440', 'color_plus': '16658442', 'color_minus': '16658445', 'bright_plus': '16658444', ...
# Number of Recent Calls: https://leetcode.com/problems/number-of-recent-calls/ # You have a RecentCounter class which counts the number of recent requests within a certain time frame. # Implement the RecentCounter class: # RecentCounter() Initializes the counter with zero recent requests. # int ping(int t) ...
""" Author: Andreas Finkler Created: 23.12.2020 Statistics for qualifying times. """ from operator import attrgetter import numpy as np from granturismo_stats.entities.ranking import Leaderboard class QualifyingTimes: """ Statistics of the qualifying results for a given race. """ def __init__(self,...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ nwid.widget ~~~~~~~~~~~ This module contains nwid widget objects and data structures. """ from __future__ import absolute_import from .base import BaseWidget
#required !pip install googleads -q import pandas as pd import numpy as np from google.ads.googleads.client import GoogleAdsClient from google.ads.googleads.errors import GoogleAdsException from google.protobuf.json_format import MessageToDict import _locale """ MANDATORY INPUT: start_date, end_date as string ...
import json def text_file_to_list(filename): with open(filename, 'r') as file: return file.read().splitlines() def list_to_text_file(filename, string_list): with open(filename, 'w') as text_file: for line in string_list: text_file.write(f'{line}\n') def json_to_dict(filename): ...
# Copyright (C) Mesosphere, Inc. See LICENSE file for details. """Implement handler for the /uiconfig endpoint. In a DC/OS cluster it is exposed via /dcos-metadata/ui-config.json. It is there so that the UI can display a special message to visitors of the login page ("you will be the superuser!") before the first re...
""" This is the main program for making the ATM forcing file. Testing on my mac: need to use this day to find stored files: run make_forcing_main.py -g cas6 -t v3 -d 2017.04.20 Note: we set rain to zero because its units are uncertain and we don't currently use it in the simulations. 2021.09.16: I finally added a p...
from django import forms from overrides.widgets import CustomStylePagedown class EditProfileForm(forms.Form): about = forms.CharField(label='About', max_length=1000, required=False, widget=CustomStylePagedown(),) view_adult...
import torch import torch.nn as nn from torch_geometric.data import InMemoryDataset import numpy as np import pandas as pd import pickle import csv import os from torch_geometric.data import Data from torch_geometric.data import DataLoader from sklearn.metrics import roc_auc_score from torch_geometric.nn import Grap...
import unittest import sys sys.path.append('../lib') sys.path.append('helpers') import matrixUtils import vTableServer import pTableServer class vTest(unittest.TestCase): def test_V_write_read(self): fileName = "temp.txt" matrixUtils.write_V_table(vTableServer.get_table(5), fileName) self.assertEqual(ma...
from clang.cindex import Index, File def test_file(): index = Index.create() tu = index.parse('t.c', unsaved_files = [('t.c', "")]) file = File.from_name(tu, "t.c") assert str(file) == "t.c" assert file.name == "t.c" assert repr(file) == "<File: t.c>"
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. (http://www.facebook.com) import unittest import weakref from unittest.mock import MagicMock, Mock class WeakRefTests(unittest.TestCase): def test_ref_dunder_callback_readonly(self): class C: pass def callback(*...
from typing import List class Solution: def tribonacci(self, n: int) -> int: self.tribonacci_list: List = [0, 1, 1, 2] for i in range(4, n+1): self.tribonacci_list.append(sum(self.tribonacci_list[-3:])) return self.tribonacci_list[n]
# encoding: utf-8 # Copyright 2015 California Institute of Technology. ALL RIGHTS # RESERVED. U.S. Government Sponsorship acknowledged. # # set-rdf-sources - configure RDF URLs app = globals().get('app', None) # ``app`` comes from ``instance run`` magic. portalID = 'edrn' from AccessControl.SecurityManagement import...
from .asset import * from .channel import * from .message import * from .server import * from .user import *
#!/usr/bin/env python3 """ Copyright (C) 2018 Rene Rivera. Use, modification and distribution are subject to the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) """ from bls.build_tools import BuildB2 if __name__ == "__main__"...
# Copyright 2010 Hakan Kjellerstrand [email protected] # # Licensed under the Apache License, Version 2.0 (the 'License'); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
""" Some instructions on writing CLI tests: 1. Look at test_ray_start for a simple output test example. 2. To get a valid regex, start with copy-pasting your output from a captured version (no formatting). Then escape ALL regex characters (parenthesis, brackets, dots, etc.). THEN add ".+" to all the places where ...
# -*- coding: utf-8 -*- from __future__ import absolute_import from ...spec.attr import AttributeGroup class ReferenceAttributeGroup(AttributeGroup): __attributes__ = { 'ref_obj': dict(), 'normalized_ref': dict(), } class PathItemAttributeGroup(AttributeGroup): __attributes__ = { ...
import torch.nn as nn import torch import torchvision import torch.nn.functional as F class EnsembleModel(nn.Module): def __init__(self,num_classes,layer): super(EnsembleModel,self).__init__() # model A: resnet50 if layer==50: self.modelA=torchvision.models.resnet50(pretrained=...
import numpy as np import torch from torch.distributions import Normal class Actor(torch.nn.Module): def __init__(self, input_size, hidden_size, output_size): super(Actor, self).__init__() # defining fully-connected layers self.fc_1 = torch.nn.Linear(input_size, hidden_size) self....
import os, logging, sys, subprocess, argparse, time import xml.etree.ElementTree as xmlparse from nc_config import * from exe_cmd import * from topo import * from fail_recovery import * ########################################### ## get parameters ########################################### class Parameters: def ...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import...
# coding=utf-8 # Copyright 2020 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 ...
n = int(input()) wait_time = list(map(int, input().split())) wait_time.sort(reverse=True) sum = 0 for i, t in enumerate(wait_time): sum += (i + 1) * t print(sum)
def tenbase(s, alpha, w, h): l = [] while s != "": l.append(s[:(w+1) * h - 1]) s = s[(w+1) * h:] l = l[::-1] x = 0 for i in range(len(l) - 1, -1, -1): x += alpha.index(l[i]) * 20**i return x def maybase(x, alpha): l = [] if x == 0: l....
print('===== DESAFIO 006 =====') x = int(input('Digite um numero: ')) print(f'Esse é seu dobro {x*2}\n Seu triplo {x*3}\n Sua Raiz Quadrada {x**(1/2)}')
from random import randint from enums import * from stix_generator import * from util import Util as u def make_cybox_object_list(objects): """ Makes an object list out of cybox objects to put in a cybox container """ cybox_objects = {} for i in range(len(objects)): cybox_objects[str...
import glob import os import shutil import time import random def sleep_time(): time.sleep(2) def git_automation(repository_name,local_file_path,script_name,git_script_path): print('E:\\Github\\'+repository_name) os.chdir(r'E:\\Github\\'+repository_name) sleep_time() os.system('git checkout mai...
''' problem-- Given a time in 12-hour AM/PM format, convert it to military (24-hour) time. Note: Midnight is 12:00:00AM on a 12-hour clock, and 00:00:00 on a 24-hour clock. Noon is 12:00:00PM on a 12-hour clock, and 12:00:00 on a 24-hour clock. Function Description-- Complete the timeConversion function in the editor...
import unittest from pyval import evaluate class TestEvaluate(unittest.TestCase): def test_evaluate(self): self.assertEqual(evaluate("(2 + 3) * 5"), 25) self.assertEqual(evaluate("2 + 3 * 5"), 17) self.assertEqual(evaluate("(4 - 6) * ((4 - 2) * 2)"), -8) self.assertEqual(evaluate("(...
""" __init__.py """ __author__ = 'Gavin M. Roy' __email__ = '[email protected]' __since__ = '2012-06-05' __version__ = '0.3.2' import api import apps import cli import crashes import crashlog
""" Pipeline pressure containment according to DNVGL-ST-F101 (2017-12) refs: Notes: to run: python DnvStF101_pressure_containment.py """ from pdover2t.dnvstf101 import * from pdover2t.pipe import pipe_Do_Di_WT # Gas Export (0-0.3 km) location class II, 60°C max. Temp. 340-370m depth D_i = 0.6172 # (m) pipe inter...
import qutip as qt import numpy as np import scipy from scipy import constants from scipy.linalg import expm, sinm, cosm import matplotlib.pyplot as plt pi = np.pi e = constants.e h = constants.h hbar = constants.hbar ep0 = constants.epsilon_0 mu0 = constants.mu_0 Phi0 = h/(2*e) kb = constants.Boltzmann def to_dBm(...
r"""Reference. http://cocodataset.org/#detection-eval https://arxiv.org/pdf/1502.05082.pdf https://github.com/rafaelpadilla/Object-Detection-Metrics/issues/22 """ import collections from .base import EvaluationMetric from .records import Records class AverageRecallBBox2D(EvaluationMetric): """2D Bounding Box Av...
# # Working with the OS # import os from os import path import datetime from datetime import date, time, timedelta import time def main(): # Print the name of the OS print(os.name) # Check for if an item exists and what is its type print("Item exists: " + str(path.exists("textfile.txt"))) print("...
from rest_framework import serializers from base.models import Task, Subtask, Category, Attachment from django.contrib.auth.models import User from taggit.serializers import (TagListSerializerField, TaggitSerializer) from taggit.models import Tag, TaggedItem from base.reports import Repo...
#Fatiamento #frase = 'Curso em Vídeo Python' #print(frase[9::3]) # Análise frase = "Fabio Rodrigues Dias" print(len(frase)) print(frase.count("o")) print(frase.count("o", 0, 20)) print(frase.lower().find("Dias")) print(frase.count("abio")) print("Dias"in frase) print('\n') #Transformação print(frase.replace("Pyth...
""" Database event signals """ from asgiref.sync import async_to_sync from channels.layers import get_channel_layer from django.db.models.signals import post_delete, post_save from django.dispatch import receiver from apps.chat.models import Room from apps.chat.serializers import RoomHeavySerializer @receiver(post...
from PyQt5 import QtCore, QtWidgets from PyQt5.QtWidgets import QMainWindow import math class BuyCityWindow(QMainWindow): """ This window is used for proposing price for city buyout. """ def __init__(self, parent, grandparent): super(BuyCityWindow, self).__init__() self.resize(440, 28...
import random import generate_histogram #module to select one word based on commonness(frequency) in the given histogram def weighted_random_word(histogram_dict): ''' Takes a histogram and returns a random weighted word ''' # Raise an exception if we are given an empty histogram if len(histogram_dict) == 0...
# # @lc app=leetcode id=283 lang=python3 # # [283] Move Zeroes # from typing import List class Solution: def moveZeroes(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ index = 0 for i, n in enumerate(nums): if n != 0...
from easydict import EasyDict cartpole_dqn_config = dict( env=dict( collector_env_num=8, collector_episode_num=2, evaluator_env_num=5, evaluator_episode_num=1, stop_value=195, ), policy=dict( cuda=False, model=dict( obs_shape=4, ...
""" Main script for semantic experiments Author: Vivien Sainte Fare Garnot (github/VSainteuf) License: MIT """ import argparse import json import os import pickle as pkl import pprint import time import numpy as np import torch import torch.nn as nn import torch.utils.data as data import torchnet as tnt from src impo...
# generate figs for processing import predusion.immaker as immaker from predusion.color_deg import Degree_color import numpy as np import os n_image, n_image_w = 4, 4 imshape = (128, 160) l, a, b, r = 80, 22, 14, 70 n_deg = 30 deg_color = Degree_color(center_l=l, center_a=a, center_b=b, radius=r) center = 10 width ...
from __future__ import print_function import tensorflow as tf try: tf.contrib.eager.enable_eager_execution() except ValueError: print('value error!') else: print(tf.executing_eagerly()) graph = tf.Graph() with graph.as_default(): c = tf.constant('hello world!') with tf.Session(graph=graph) as sess...
#coding:utf-8 N = int(raw_input()) s = list(raw_input()) K = int(raw_input()) % 26 for i, char in enumerate(s): if char >= 'A' and char <= 'Z': num = ord(char) + K if num > 90: num -= 26 elif char >= 'a' and char <= 'z': num = ord(char) + K if num > 122: ...
import os import unittest from os.path import join as pjoin from e2xgrader.models import TaskModel from ..test_utils.test_utils import create_temp_course, add_question_to_task class TestTaskModel(unittest.TestCase): def setUp(self): tmp_dir, coursedir = create_temp_course() self.tmp_dir = tmp_di...
DEFAULT = False called = DEFAULT def reset_app(): global called called = DEFAULT def generate_sampledata(options): global called assert called == DEFAULT called = True
#!/usr/bin/python # # flg - FOX lexer generator. # # usage: # flg [ -l,--language=<outputlanguage> ] [ -n,--name=<name> ] # [ -o,--outputfile=<filename> ] [ -v,--showtables ] <inputfile>|- # # options: # -l,--language=<outputlanguage> # What language to output the lexer in. Currently, only "python" # ...
from .base import ByteableList from .stroke import Stroke class Layer(ByteableList): __slots__ = "name" @classmethod def child_type(cls): return Stroke def __init__(self, name=None): self.name = name super().__init__() def __str__(self): return f"Layer: nobjs={le...
from indy_node.server.request_handlers.domain_req_handlers.attribute_handler import AttributeHandler from plenum.server.request_handlers.handler_interfaces.read_request_handler import ReadRequestHandler from indy_common.constants import ATTRIB, GET_ATTR from indy_node.server.request_handlers.utils import validate_attri...
# -*- coding: utf-8 -*- """ Created on Tue Oct 1 23:22:03 2019 @author: SERELPA1 """ # Feature Scaling from sklearn.preprocessing import StandardScaler def feature_scaling(ds_train): sc = StandardScaler() ds_train_scaled = sc.fit_transform(ds_train) sc_predict = StandardScaler() sc_predict.fit_tra...
from django import forms from django.utils.translation import ugettext as _ from dal import autocomplete from dal import forward from ..models import Country class CountryForm(forms.ModelForm): """ Custom Country Form. """ class Meta: model = Country fields = ('__all__') widg...
import astra import numpy as np import os import pickle from tqdm import tqdm from time import time from astropy.io import fits from astropy.table import Table from astra.utils import (log, timer) from astra.tasks import BaseTask from astra.tasks.io import LocalTargetTask from astra.tasks.io.sdss5 import ApStarFile fr...
# -*- coding: utf-8 -*- # Copyright 2017-2019 ControlScan, Inc. # # This file is part of Cyphon Engine. # # Cyphon Engine 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, version 3 of the License. # # Cyphon En...
# -*- coding: utf-8 -*- # snapshottest: v1 - https://goo.gl/zC4yUc from __future__ import unicode_literals from snapshottest import Snapshot snapshots = Snapshot() snapshots['test_login_shortcut 1'] = { 'data': { 'node': { 'id': 'TG9naW5TaG9ydGN1dDoxMA==', 'name': 'foo' }...
import logging from .paths import DetectionPaths class DetectionLogs(): # Set Logging configs LOG_FORMAT = "%(levelname)s %(asctime)s - - %(message)s" logging.basicConfig(filename=DetectionPaths.LOG_PATH, level=logging.DEBUG, format=LOG_FORMAT) logger...