content
stringlengths
0
894k
type
stringclasses
2 values
#!/usr/bin/env python3 import copy import requests import shutil from typing import Sequence import yaml import logging logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger("gen_meta") from .common import * LINGUIST_COMMIT = "10c20c7286a4b56c17253e8aab044debfe9f0dbe" ROSETTA_CODE_DATA_COMMIT = "aac6...
python
''' 剑指 Offer 20. 表示数值的字符串 请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。 数值(按顺序)可以分成以下几个部分: 若干空格 一个 小数 或者 整数 (可选)一个 'e' 或 'E' ,后面跟着一个 整数 若干空格 小数(按顺序)可以分成以下几个部分: (可选)一个符号字符('+' 或 '-') 下述格式之一: 至少一位数字,后面跟着一个点 '.' 至少一位数字,后面跟着一个点 '.' ,后面再跟着至少一位数字 一个点 '.' ,后面跟着至少一位数字 整数(按顺序)可以分成以下几个部分: (可选)一个符号字符('+' 或 '-') 至少一位数字 部分数值列举如下: ["+100", "...
python
from typing import Tuple, Optional from .template import Processor class Cutadapt(Processor): fq1: str fq2: Optional[str] adapter: str trimmed_fq1: str trimmed_fq2: Optional[str] def main(self, fq1: str, fq2: Optional[str], adapter: str) -> Tuple[str, O...
python
import redis import json class Construct_Applications(object): def __init__(self,bc,cd): # bc is build configuration class cd is construct data structures bc.add_header_node("APPLICATION_SUPPORT") bc.end_header_node("APPLICATION_SUPPORT")
python
__author__ = 'Geir Istad' from tinydb import TinyDB, where class CanStorage: __data_base = TinyDB __current_sequence_table = TinyDB.table __current_sequence = None __max_sequence = None __ready_to_store = False def __init__(self, a_file_path): """ Opens (or creates) a data ba...
python
"""Container access request backend for Openstack Swift.""" __name__ = "swift_sharing_request" __version__ = "0.4.9" __author__ = "CSC Developers" __license__ = "MIT License"
python
# coding=utf-8 # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) from textwrap import...
python
from django.template import loader, Context from django.db.models import Q from blog.views import Entry def search(request): query = request.GET['q'] t = loader.get_template('result.html') results = Entry.objects.filter(Q(title__icontains=query) | Q(body__icontains=query))#.order_by('created') c = Cont...
python
# -*- coding: utf-8 -*- import itertools import pandas as pd from .. import models class BattleMetricsService(object): def __init__(self): self._battle = models.Battle() self.summary = pd.DataFrame() def read_html(self, file_path): log = models.BattleLog.from_html(file_path=file_p...
python
import json from .Reducer import Reducer class EAVReducer(Reducer): def setTimestamp(self, timestamp): self.set("timestamp", timestamp) def setEntity(self, entity): self.set("entity", entity) def getEntity(self): return self.get("entity") def setAttribute(self, attribute):...
python
# # This file is part of pyasn1-alt-modules software. # # Copyright (c) 2019-2022, Vigil Security, LLC # License: http://vigilsec.com/pyasn1-alt-modules-license.txt # import sys import unittest from pyasn1.codec.der.decoder import decode as der_decoder from pyasn1.codec.der.encoder import encode as der_encoder from p...
python
from typing import Dict, Tuple, Optional, Any from datetime import datetime import base64 import urllib3 import requests from cryptography.hazmat.primitives.ciphers.aead import AESGCM from CommonServerPython import * # Disable insecure warnings urllib3.disable_warnings() INTEGRATION_CONTEXT_NAME = 'MSGraphGroups' NO_...
python
# -*- coding: utf-8 -*- """Top-level package for ProtoBuf Schematics.""" __author__ = """Almog Cohen""" __version__ = '0.4.1'
python
from config import UPLOAD_FOLDER, COMCORHD_FOLDER, JULGAMENTO_FOLDER, REPOSITORIES, VALIDATE_UD, VALIDATE_LANG, GOOGLE_LOGIN, VALIDAR_UD from flask import render_template, request import pandas as pd import os, estrutura_ud, estrutura_dados, confusao, re, time, datetime, validar_UD import models, pickle from app import...
python
''' Author: Siyun WANG ''' import matplotlib.pyplot as plt import seaborn as sns import datetime import pandas as pd import numpy as np from statsmodels.tsa.seasonal import seasonal_decompose from ExploreData import ExploreData class BasicStatisticPlots(object): ''' Make basic statistic plots for data visuali...
python
def fun (r): return ((2 + ((r - 1) * 2) ) // 2 ) * r for _ in range(int(input())): l,r = [int(x) for x in input().split()] n = fun(r) n -= fun(l - 1) print(n)
python
# # Copyright (c) 2017 Nutanix Inc. All rights reserved. # # # pylint: disable=pointless-statement import unittest import uuid import mock from curie.curie_error_pb2 import CurieError from curie.curie_server_state_pb2 import CurieSettings from curie.discovery_util import DiscoveryUtil from curie.exception import Curi...
python
import numpy as np import numbers from manimlib.constants import * from manimlib.mobject.functions import ParametricFunction from manimlib.mobject.geometry import Arrow from manimlib.mobject.geometry import Line from manimlib.mobject.number_line import NumberLine from manimlib.mobject.svg.tex_mobject import TexMobject...
python
import os import unittest import numpy as np import pygsti import pygsti.construction as pc from pygsti.serialization import json from pygsti.modelpacks.legacy import std1Q_XY from pygsti.modelpacks.legacy import std2Q_XYCNOT as std from pygsti.objects import Label as L from ..testutils import BaseTestCase, compare_f...
python
""" Compare two version numbers version1 and version2. If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0. You may assume that the version strings are non-empty and contain only digits and the . character. The . character does not represent a decimal point and is used to separate num...
python
from core.views import BaseView, LoginRequiredMixin from ..models import PokerMember, PokerRoom class SettingsView(LoginRequiredMixin, BaseView): template_name = 'settings.html' def get(self, request, token): """Handle GET request.""" if not self.member: return self.redirect('po...
python
import bpy import struct import squish from bStream import * import time def compress_block(image, imageData, tile_x, tile_y, block_x, block_y): rgba = [0 for x in range(64)] mask = 0 for y in range(4): if(tile_y + block_y + y < len(imageData)): for x in range(4): i...
python
import datafellows def test_main(): assert datafellows # use your library here
python
import numpy as np import matplotlib.pyplot as plt from pypospack.eamtools import create_r from pypospack.potential.pair_general_lj import func_cutoff_mishin2004 r = create_r(6.,5000) rc = 5.168 hc = 0.332 xrc = (r-rc)/hc psirc = (xrc**4)/(1+xrc**4) rc_ind = np.ones(r.size) rc_ind[r > rc] = 0 psirc = psirc * rc_ind ...
python
from tir import Webapp import unittest from datetime import datetime class MATA940(unittest.TestCase): @classmethod def setUpClass(inst): inst.oHelper = Webapp() DateSystem = datetime.today() inst.oHelper.Setup('SIGAFIS', DateSystem.strftime( '%d/%m/%Y'), 'T1', 'X FIS16', '...
python
# -*- coding: utf-8 -*- """ .. invisible: _ _ _____ _ _____ _____ | | | | ___| | | ___/ ___| | | | | |__ | | | |__ \ `--. | | | | __|| | | __| `--. \ \ \_/ / |___| |___| |___/\__/ / \___/\____/\_____|____/\____/ Created on Mar 20, 2013 All-to-all perceptron layers: simple (:...
python
import json import logging import unittest from dataclasses import asdict, dataclass from datetime import datetime, timedelta from typing import Any, Dict, Mapping, Optional from uuid import UUID, uuid4 import bson from bson import ObjectId from falcon.testing import Result from eduid_userdb.testing import normalised...
python
# flake8: noqa from .serializers import ViewSetSerializer from .views import ( ViewSetCreateView, ViewSetDeleteView, ViewSetDetailView, ViewSetIndexView, ViewSetListView, ViewSetUpdateView ) from .viewsets import ModelViewSet, ViewSet __version__ = '0.1.6' default_app_config = 'viewsets.apps.ViewsetsConfig'
python
import uuid import boto3 from botocore.exceptions import ClientError from busy_beaver.config import ( DIGITALOCEAN_SPACES_BASE_URL, DIGITALOCEAN_SPACES_BUCKET_NAME, DIGITALOCEAN_SPACES_ENDPOINT_URL, DIGITALOCEAN_SPACES_REGION_NAME, LOGOS_FOLDER, ) class S3Client: def __init__(self, client_ke...
python
import scrapy import json from bs4 import BeautifulSoup import re import datetime import logging logging.basicConfig(filename='Error.log', level=logging.CRITICAL, format='%(asctime)s:%(levelname)s:%(name)s:%(message)s', datefmt='%d/%m/%Y %I:%M:%S %p') from PHASE_1.API_SourceCode.keyterms.key_terms import g...
python
from __future__ import print_function import json import os import yagmail import phonenumbers class MailToSMS: """MailToSMS This module implements a basic api for sending text messages via email using yagmail. Arguments: number {string|int}: The destination phone number (ex. 5551234567) ...
python
from google.cloud import storage bucket_name = "ml_model_store" storage_client = storage.Client() storage_client.create_bucket(bucket_name) for bucket in storage_client.list_buckets(): print(bucket.name)
python
from Domo.Modules import * from Domo.API import ApiManager, ApiResponse, ApiCodes from System.Collections.Generic import Dictionary from System.Drawing import Point, Color, Size, Brush, SolidBrush from System.Threading import Thread, ThreadStart from System.Windows.Forms import ( Application, Form, DialogResult...
python
# Stimulation server extended from VisionEgg.PyroApps.EPhysServer from distutils.version import LooseVersion as V import os import ast import Pyro import pickle import logging import pygame import VisionEgg import VisionEgg.PyroApps.EPhysServer as server from StimControl.LightStim.Core import DefaultScreen from StimCo...
python
import torch from torch.autograd import Function, Variable from torch.nn import Module from torch.nn.parameter import Parameter import operator def jacobian(f, x, eps): if x.ndimension() == 2: assert x.size(0) == 1 x = x.squeeze() e = Variable(torch.eye(len(x)).type_as(get_data_maybe(x))) ...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (C) 2021 Antmicro # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either ...
python
from django.conf import settings from django.contrib.auth import get_user_model from django.core.mail import send_mail class Permissions: """This is the base class for all custom permissions. To create a new permission set, subclass this class.""" def __init__(self, model_name, app_label): self.model_name =...
python
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui_send_payout_dlg.ui' # # Created by: PyQt5 UI code generator 5.9.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_SendPayoutDlg(object): def setupUi(self, SendPayoutDlg): ...
python
""" ========================================================================== TorusRouterFL.py ========================================================================== FL route unit that implements dimension order routing. Author : Yanghui Ou Date : June 30, 2019 """ from pymtl3 import * from .directions import ...
python
import json from common.methods import set_progress from resourcehandlers.aws.models import AWSHandler from botocore.client import ClientError RESOURCE_IDENTIFIER = 'db_identifier' def boto_instance_to_dict(boto_instance): """ Create a pared-down representation of an RDS instance from the full boto dicti...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # # @Author: Brian Cherinka, José Sánchez-Gallego, and Brett Andrews # @Date: 2018-07-20 # @Filename: test_quantities.py # @License: BSD 3-clause (http://www.opensource.org/licenses/BSD-3-Clause) # # @Last modified by: andrews # @Last modified time: 2018-10-19 14:10:15 ...
python
from .orientationDictionary import OrientationDictionary from copy import deepcopy class RiverDecorator: def updateCells( self, matrix, WATER_SPRITE_INDEX, waterSpot, GROUND_SPRITE_INDEX, waterSprites ): orientationDictionary = OrientationDictionary(waterSprites) spriteDict = orientat...
python
from telethon import TelegramClient, events, Button import requests import os from pynpm import NPMPackage from nodejs.bindings import node_run import requests import cryptg import asyncio import shutil import subprocess d = os.environ.get("d") APP_ID = int(os.environ.get("APP_ID", 0)) API_HASH = os.environ.get("API_H...
python
# Definition for singly-linked list. class ListNode(object): def __init__(self, val=0, next=None): self.val = val self.next = next def swapPairs(head): """ :type head: ListNode :rtype: ListNode """ dummy = ListNode(-1) prev, current = dummy, head; dummy.next = h...
python
import pandas as pd import numpy as np import tensorflow as tf import torch from torch.nn import BCEWithLogitsLoss, BCELoss from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler from keras.preprocessing.sequence import pad_sequences from sklearn.model_selection import train_test_split...
python
# -*- coding: utf-8 -*- """Class for dependency error exception .. module:: lib.exceptions.dependencyerror :platform: Unix :synopsis: Class for dependency error exception .. moduleauthor:: Petr Czaderna <pc@hydratk.org> """ class DependencyError(Exception): """Class DependencyError """ def __init...
python
# # PySNMP MIB module Zhone (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Zhone # Produced by pysmi-0.3.4 at Mon Apr 29 18:11:18 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # ...
python
from sqlalchemy import create_engine, Table, MetaData from sqlalchemy.sql import select, delete, update, and_ import collections from config import * import datetime class Dao(): con = None def get_db_engine(self): engine = create_engine( 'postgresql+psycopg2://%s:%s@%s:%s/%s' % ( ...
python
from nonebot import on_command from nonebot.adapters.cqhttp import Event import requests from nonebot.adapters.cqhttp import Bot from nonebot.rule import to_me weather = on_command("星座运势",rule=to_me(), priority=5) @weather.handle() async def handle_first_receive(bot: Bot, event: Event, state: dict): arg...
python
# Here we use the last column of Table 4 of "Planck 2015 Results: XIII. Cosmological Parameters" _cosmo_params = \ { 'omega_m_0': 0.3089, 'omega_b_0': round(0.0223/0.6774**2, 5), 'omega_l_0': 1. - 0.3089, 'hubble_0': 0.6774, 'helium_by_number': 0.0813, 'helium_by_mass': 0.2453, 'cmb_temp_0': 2.7255, 'sigma_8': 0.8159, ...
python
import pandas as pd from pandas.io.formats.format import CategoricalFormatter from config import ROOT_PATH_ABS, SSourceConfig as SSC from config import RESULT_FOLDER_ABS class Encoder(object): def __init__(self, df:pd.DataFrame) -> None: super().__init__() self.df = df self.sta...
python
import subprocess, logging logger = logging.getLogger(__name__) def turn_on_light(device): if device.enabled: if not device.status: cmd = '/usr/local/bin/wemo switch "' + device.name + '" on' proc = subprocess.Popen([cmd], stdout=(subprocess.PIPE), shell=True) out, err...
python
from django_assets import env def layout_workers(request): workers = [] for name, bundle in env.get_env()._named_bundles.iteritems(): if name.startswith('worker_'): name = name.split('_', 1)[1].rsplit('_', 1)[0] workers.append((name, bundle.urls()[0])) return { 'lay...
python
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under th...
python
# ------------------------------------------------------------------------------ # CodeHawk Binary Analyzer # Author: Henny Sipma # ------------------------------------------------------------------------------ # The MIT License (MIT) # # Copyright (c) 2016-2020 Kestrel Technology LLC # Copyright (c) 2020 Henny Si...
python
# Generated by Django 4.0 on 2022-01-02 13:31 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('leads', '0005_auto_20220102_1420'), ] operations = [ migrations.AlterField( model_name='agent', ...
python
#!/usr/bin/env python import sys import netsnmp if __name__ == '__main__': ip = '127.0.0.1' snmp = netsnmp.SNMPSession(ip, 'RJKJ') if snmp.is_alive(): snmp.close() print 'test import netsnmp ok'
python
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project # root for license information. from redact.types.file_bundle import FileBundle from redact.types.file_bundle import FileType class TestFileBundle: def test_from_names(self) -> None: ...
python
""" Copyright (C) 2017-2018 University of Massachusetts Amherst. This file is part of "learned-string-alignments" http://github.com/iesl/learned-string-alignments 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...
python
#!/usr/bin/env python3.9 # Modules import os import sprint import colorama import platform from os.path import isfile, expanduser # Credit message colorama.init() # Fix windows colors print(sprint.colored(f"Sprint v{sprint.__version__} by iiPython", "yellow")) print(sprint.colored(f"Python version {platform.pytho...
python
"""Test categoricalCNNPolicy in PyTorch.""" import cloudpickle import pytest import torch from garage.envs import GymEnv from garage.torch import TransposeImage from garage.torch.policies import CategoricalCNNPolicy from tests.fixtures.envs.dummy import DummyDictEnv, DummyDiscretePixelEnv class TestCategoricalCNNPo...
python
# coding=utf-8 import numpy as np import torch.nn.functional as F from datautil.util import random_pairs_of_minibatches from alg.algs.ERM import ERM class Mixup(ERM): def __init__(self, args): super(Mixup, self).__init__(args) self.args = args def update(self, minibatches, opt, sch): ...
python
from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(800, 600) MainWindow.setUnifiedTitleAndToolBarOnMac(False) self.centralwidget = QtWidgets.QWidget(MainWindow) self.c...
python
from __future__ import absolute_import import argparse from detect_secrets.core.usage import ParserBuilder import detect_secrets_server from .add import AddOptions from .install import InstallOptions from .list import ListOptions from .scan import ScanOptions class ServerParserBuilder(ParserBuilder): """Argume...
python
from espnet_model_zoo.downloader import ModelDownloader import sys model_name = sys.argv[1] d = ModelDownloader() model_path = d.download(sys.argv[1]) print(model_path)
python
larg = float(input('Qual a largura da parede?')) alt = float(input('Qual a altura da parede?')) print('Você vai precisar de {:.0f} litros de tinta'.format((larg*alt)/2))
python
# Difficulty Level: Beginner # Question: Calculate the sum of the values of keys a and b . # d = {"a": 1, "b": 2, "c": 3} # Expected output: # 3 # Program d = {"a": 1, "b": 2, "c": 3} print(d["a"] + d["b"]) # Output # shubhamvaishnav:python-bootcamp$ python3 17_dictionary_items_sum_up.py # 3
python
# 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 pulumi import pulumi.runtime class Association(pulumi.CustomResource): """ Associates an SSM Document to an instance or...
python
from django.db.models.query import Q from django.utils import timezone from rest_framework import serializers from ..accounts.serializers import UserSerializer from .models import Amenity, Booking class AmenityRelatedField(serializers.RelatedField): def to_native(self, value): return { 'id...
python
import os from unittest import TestCase from checkov.cloudformation.cfn_utils import create_definitions from checkov.cloudformation.graph_builder.graph_components.block_types import BlockType from checkov.cloudformation.graph_builder.graph_to_definitions import convert_graph_vertices_to_definitions from checkov.cloudf...
python
# Copyright 2020 Huawei Technologies Co., Ltd # # 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...
python
from ..classes import ml_util def test_objective_function(): new_objective = ml_util.ObjectiveFunction() new_objective.load_data(path="Use Cases/VPS Popcorn Production/Docker/src/data/vpsFeatures.csv") new_objective.fit_model() prediction = new_objective.get_objective(4000) assert prediction == 0....
python
AddressType = int SelectorType = int
python
from manimlib.imports import * from my_manim_projects.my_utils.my_3D_mobject import * from my_manim_projects.my_utils.my_text import * class Sum_of_cubes(ThreeDScene): CONFIG = { 'camera_init': { 'phi': 52.5 * DEGREES, 'gamma': 0, 'theta': -45 * DEGREES, }, ...
python
# import unittest # from unittest.mock import patch # import http.client
python
from app import app import dataquery import json @app.route("/ajaxreq/get_capital_account_info<any:args>",methods=['GET']) def ajaxrep_get_capital_account_info(args): #cai=dataquery.get_capital_account_info(); return "abc"; #return json.dumps(cai);
python
import socket import sys import hlt PORT_ = 2000 class Game(hlt.Game): def __init__(self, *args, **kwargs): self._buf = [] self._connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._connection.connect(("localhost", PORT_)) super().__init__(*args, **kwargs) def...
python
from typing import Iterable, List import sparql_queries from movie import Movie from joblib import Parallel, delayed from env import env class Recommandation(): def __init__(self, uri, func, id, text) -> None: self.data = getattr(sparql_queries, func)(uri) self.data = [Movie(dataReco=mov) for mov ...
python
import unittest from blazeweb.globals import settings from blazeweb.config import QuickSettings, EnabledSettings from blazeweb.hierarchy import listapps from nose.tools import eq_ from minimal2.application import make_wsgi as make_wsgi_min2 from blazewebtestapp.applications import make_wsgi class Base(QuickSettings)...
python
#!/usr/bin/env python """ DESCRIPTION: This is an extremely simple Python application that demonstrates how to use Elbrys SDN Developer Lab (dev.elbrys.com) to control endpoint user sessions access to the network. This application will connect to one of the switches that you have connected in the SDN Devel...
python
"""Unit tests for flux calibration/zeropoints Authors ------- - Bryan Hilbert Use --- Ensure you have pytest installed. Then, simply run pytest in any parent directory of mirage/tests/: >>> pytest """ from astropy.table import Table import numpy as np import os import pkg_resources from mirage.utils ...
python
def clean_string(s): if len(s) == 0: return s q = [] for idx in range(len(s)): if s[idx] != "#": q.append(s[idx]) elif len(q) != 0: q.pop() return "".join(q)
python
import os high_scores = { "small_1" : "0", "small_2" : "0", "small_3" : "0", "medium_1" : "0", "medium_2" : "0", "medium_3" : "0", ...
python
from typing import List import torch from torch.utils.data.dataset import Dataset def noise(outlier_classes: List[int], generated_noise: torch.Tensor, norm: torch.Tensor, nom_class: int, train_set: Dataset, gt: bool = False) -> Dataset: """ Creates a dataset based on the nominal classes of a given ...
python
import logging import logging.handlers import os def create_logger(name): """Create generic logger for all nodes""" # Create logger and let it capture all messages logger = logging.getLogger(name) logger.setLevel(logging.DEBUG) # Output formatting formatter = logging.Formatter("[ %(asctime)s...
python
from __future__ import absolute_import, division, print_function import os import numpy as np import pytest from ciso import zslice data_path = os.path.join(os.path.dirname(__file__), "data") @pytest.fixture def data(): p = np.linspace(-100, 0, 30)[:, None, None] * np.ones((50, 70)) x, y = np.mgrid[0:20:5...
python
# -*- coding: utf-8 -*- import pytest from olympia.users.models import UserProfile from olympia.users.templatetags.jinja_helpers import user_link, users_list pytestmark = pytest.mark.django_db def test_user_link(): u = UserProfile(username='jconnor', display_name='John Connor', pk=1) assert user_link(u) ==...
python
from __future__ import division import os import pickle import numpy as np import blt_net.cascademv2.utils.benchmark_utils as benchmark_utils import ntpath import cv2 from blt_net.cascademv2.utils.general_utils import create_logger import sys import tensorflow as tf os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" os.en...
python
''' Extra operators used by MetaFunctions ''' from operator import add, sub, truediv, mul def concat(*args): "concat(1, 2, 3) -> (1, 2, 3)" return args
python
# Generated by Django 2.2.2 on 2019-09-27 00:54 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("dcodex", "0003_auto_20190920_1333"), ] operations = [ migrations.AlterModelOptions( name="manuscript", options={"ordering": ...
python
import pytest # stdlib import json import os import unittest from stackstate_checks.base.errors import CheckException from stackstate_checks.splunk.client import TokenExpiredException from stackstate_checks.splunk_health.splunk_health import SplunkHealth, Instance from stackstate_checks.base.stubs import health, aggr...
python
import yaml import os import json import logging import time def read_yaml(path_to_yaml: str) -> dict: with open(path_to_yaml) as yaml_file: content = yaml.safe_load(yaml_file) logging.info(f"yaml file: {path_to_yaml} loaded successfully") return content
python
from math import sqrt import numpy as np # tools used in production # --------------------------------------------------------------------------------------------- def combine_mean_std(l_n, l_mean, l_std): """ Ref: https://www.statstodo.com/index.php and Altman DG, Machin D, Bryant TN and Gardner MJ. (2...
python
# -*- coding: utf-8 -*- from helper import IcebergUnitTestCase class ClientAddresses(IcebergUnitTestCase): def test_create(self): """ Create an address for the user """ self.login() self.create_user_address() def test_read(self): """ Try to fetch the a...
python
"""Create organisation table Revision ID: ba9997532100 Revises: Create Date: 2021-11-08 14:36:59.635469 """ import sqlalchemy as sa # revision identifiers, used by Alembic. from app.db.utils import UtcNow from alembic import op revision = "ba9997532100" down_revision = None branch_labels = None depends_on = None ...
python
# trivial example = 30/50 = 3/5 # non-trivial example = 49/98 = 4/8 # There are 4 non-trivial types of these fractions < 1 and both numerator and # denominator contain two digits find the the product of the four in its # lowest common terms, what is the denominator? import timeit import itertools from functool...
python
from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('assignments/', views.AssignmentListView.as_view(), name='assignments'), path('assignment/<int:pk>', views.AssignmentDetailView.as_view(), name='assignment-detail'), path('units/', views.UnitListView.as_view(), ...
python
from stormed.method.codegen.tx import *
python
from litex.build.generic_platform import * from litex.build.xilinx import XilinxPlatform, XC3SProg _io = [ #OSC ("clk_50", 0, Pins("T7"), IOStandard("LVCMOS33")), # RESET ("resetn", 0, Pins("C3"), IOStandard("LVCMOS33"), Misc("PULLDOWN")), #UNUSED PIN # EVERLOOP CONTROL ("everloop_ctl", 0,...
python
"""Infer properties of TensorFlow nodes. """ from lucid.misc.graph_analysis.overlay_graph import OverlayNode, OverlayGraph import tensorflow as tf def as_tensor(t): if isinstance(t, OverlayNode): return t.tf_node elif isinstance(t, tf.Operation): return t.outputs[0] elif isinstance(t, tf.Tensor): re...
python