content stringlengths 5 1.05M |
|---|
import pickle
results_file = 'grid.pickle'
with open(results_file, 'rb') as f:
grid = pickle.load(f)
def summarize_grid(grid, val_loss_threshold):
"""
Print out the more promising hyperparameters from a search, according to
validation loss.
"""
best_val_loss = 1e9
best_params = None
it... |
import os
import re
import subprocess
import requests
ROOT_DIR_PATH = os.environ.get("ROOT_DIR", "nautilus")
def load_repo(tarball_url, dest):
resp = requests.get(tarball_url, stream=True)
resp.raise_for_status()
r, w = os.pipe()
os.makedirs(dest, exist_ok=True)
proc = subprocess.Popen(["tar", ... |
import os.path
BASE_PATH = os.path.dirname(os.path.abspath(__file__))
def joined_with_base(path):
return os.path.join(BASE_PATH, path)
def joined_with_generated(path):
return os.path.join(joined_with_base('generated/'), path)
def joined_with_data(path):
return os.path.join(joined_with_base('data/'), ... |
import tensorflow as tf
from tensorflow.contrib import slim as slim
from avb.ops import *
import math
def encoder(x, a, config, is_training=True):
z_dim = config['z_dim']
# Center x at 0
x = 2*x - 1
x = flatten_spatial(x)
net = tf.concat([x, a], axis=1)
net = slim.fully_connected(net, 300, a... |
from django.urls import path,include
from . import views
# List of all existing api urls end-points of the project
urlpatterns = [
path('',views.apiOverview,name='apiView'),
path('selectMode/',views.registerUserMode,name='userMode'),
path('openBox/<int:deliveryId>',views.boxOpenRequest,name='openBox'),... |
import os
import docker
import uuid
import tempfile
import subprocess
import pytoml as toml
from .flist import HubPublicFlist
class HubDocker:
def __init__(self, config):
self.dockerclient = docker.from_env()
self.config = config
@staticmethod
def container_boot(cn):
if cn.attrs['... |
import re
from typing import Dict, List, Tuple
from weaverbird.backends.sql_translator.metadata import ColumnMetadata, SqlQueryMetadataManager
from weaverbird.backends.sql_translator.types import SQLQuery
from weaverbird.pipeline.conditions import (
ComparisonCondition,
Condition,
ConditionComboAnd,
Co... |
"""
This python script will return the user's permission level for ANY given permission
"""
from .models import *
from django.db.models import Max
"""
Permission table
0 - No permission
1 - Read only
2 - Edit permission
3 - Create permission
4 - Admin/Delete permission
"""
def return_user_permission_level(request, gro... |
#!/usr/local/bin/python3
"""Script to generate a fixture of a box falling on a saw."""
import argparse
import json
import pathlib
import sys
import numpy
import shapely.geometry
import shapely.ops
from fixture_utils import *
def generate_fixture(args):
"""Generate a saw and block."""
fixture = generate_cus... |
# encoding: utf-8
'''
@author: xupengfei
'''
import datetime
import os
import shutil
import tempfile
from utils import ensure_list
import contextlib
import arrow
DUMP_DIRECTORY = '/tmp'
def new_tempfile(suffix='', prefix=None, dir=None):
# suffix后缀(与时间有关) prefix前缀 dir 来生成临时文件
arrow_ts = arrow.get(datetim... |
from django.contrib import admin
from myapp import models
# Register your models here.
admin.site.register(models.StudentModel)
admin.site.register(models.StudentMarkModel)
|
print(5//3)
|
#$Id$
from projects.util.ZohoHttpClient import ZohoHttpClient
from projects.api.Api import Api
from projects.parser.PortalsParser import PortalsParser
base_url = Api().base_url
zoho_http_client = ZohoHttpClient()
parser = PortalsParser()
class PortalsApi:
"""Portals Api class is used to get all portals for the l... |
import unittest
from app.models import Post, User, Comments
from app import db
class CommentModelTest(unittest.TestCase):
def setUp(self):
self.new_comment = Comments(comment_content = 'content')
db.session.add(self.new_comment)
db.session.commit()
def tearDown(self):
C... |
from arch.api.utils import log_utils
from federatedml.logistic_regression.hetero_dnn_logistic_regression.federation_client import FATEFederationClient
from federatedml.logistic_regression.hetero_logistic_regression import HeteroLRArbiter
from federatedml.util import consts
from federatedml.util.transfer_variable import... |
# For splitting one XML string into multiple ones each with only one keymap at most.
import re
oneKeymapRegExp = re.compile(r"(<\s*keyMap.*?>.*?<\s*/\s*keyMap\s*>)", flags=re.IGNORECASE | re.DOTALL)
beforeFirstKeymapRegExp = re.compile(r"^(.*?)<\s*keymap.*?>", flags=re.IGNORECASE | re.DOTALL)
allKeyMapRegExp = re.com... |
from hops import constants
class CorrelationValue(object):
"""
Represents a correlation value in a correlation matrix
"""
def __init__(self, correlation_value_json):
"""
Initialize the correlation value object from JSON payload
Args:
:correlation_value_json: JSON p... |
import argparse
from project0 import project0 as myProject
def main(url):
myPDF = myProject.fetchincidents(url)
myCSV = myProject.extractincidents(myPDF)
#Write the csv to a .csv file.
f = open("incidents.csv", "w")
f.write(myCSV)
f.close()
#Now I am ready to use this file as the paramet... |
# -*- coding: utf-8 -*-
class Calculator(object):
"""
四則演算を行う。
"""
@staticmethod
def addition(x, y):
"""
加算を行う。
:param x: 左辺
:param y: 右辺
:return: 計算結果
"""
result = x + y
return result
@staticmethod
def subtraction(x, y):
... |
import torch
import torch.nn as nn
from .modulated_conv2d import ModulatedConv2d
class MultichannelIamge(nn.Module):
def __init__(
self,
channels_in,
channels_out,
style_dim,
kernel_size=1
):
super().__init__()
self.conv = ModulatedCo... |
import warnings
import numpy as np
from asreviewcontrib.visualization.plot_base import PlotBase
class PlotInclusions(PlotBase):
def __init__(self, analyses, result_format="percentage", thick=None):
"""Class for the Inclusions plot.
Plot the number of queries that turned out to be included
... |
from .interface import MainWindow
from .backends import *
from .socket import *
from .settings import __version__
__all__ = [
'__version__',
]
|
import random
import os
import json
import time
import threading
import simple_http_client
from front_base.host_manager import HostManagerBase
class HostManager(HostManagerBase):
def __init__(self, config, logger, default_fn, fn, front):
self.config = config
self.logger = logger
self.def... |
import sys
if sys.version_info < (3,):
range = xrange
import numpy as np
import pandas as pd
import scipy.stats as ss
from .. import families as fam
from .. import output as op
from .. import tests as tst
from .. import tsm as tsm
from .. import gas as gs
from .. import data_check as dc
class EGARCH(tsm.TSM):
... |
from var_plots import plot_input
plot_input()
|
# Copyright (c) 2021 PaddlePaddle 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 appli... |
from django.test import TestCase
from ants.utils import *
from ants.decorators import *
class ScriptTest(TestCase):
def setUp(self):
pass
class DecoratorTest(TestCase):
def setUp(self):
pass
|
from abc import abstractmethod
from typing import Generator, Union
from tree import Tree
class BinaryTree(Tree):
"""A binary tree is a tree whose nodes contain a maximum of two children, the left child and the right child. The
order of the children of any node is such that the left child has precedence over ... |
import os
import glob
import pickle
from flask import Flask, request, jsonify, render_template
from langdetect import detect
from flask_cors import cross_origin, CORS
app = Flask(__name__, static_folder='static/static', template_folder='static')
app.config['CORS_HEADERS'] = 'Content-Type'
cors = CORS(app)
... |
"""
First trial with data plotting
"""
import numpy as np
import matplotlib.pyplot as plt
p = np.poly1d([666,0,1,2])
x = np.arange(-20,60,1)
print "Voici les antecedants :", x
print "Voici le polynome", p
# calcul des ordonnees
y = p(x)
print "Voici les ordonnees correspondant a l'interval -20 a 59: ", y
plt.plo... |
from django.core.urlresolvers import reverse
from django.test import TestCase, Client
from django.core.exceptions import ValidationError
from .models import Booking
from .views import updateBooking
from table.models import Table
from unittest.mock import patch, MagicMock, call
from model_mommy import mommy
from copy ... |
import logging
from django.template import RequestContext
from django.urls import reverse
from django.utils.encoding import force_text
from django.utils.translation import ugettext_lazy as _
from mayan.apps.common.generics import (
AddRemoveView, SingleObjectCreateView, SingleObjectDeleteView,
SingleObjectLis... |
'''
Load files using the file system, with automated patch application from
enabled extensions, then save the patched xml for easier viewing.
'''
from Plugins import *
from Framework import Load_Files
# Pick a location to save to.
# This will go to X4root/extracted_patched
folder = Settings.Get_X4_Folder() / 'extracte... |
from django.urls import include, path
urlpatterns = [
path("ess/", include(("api.ess.urls", "ess"), namespace="ess")),
path("pdrs/", include(("api.pdrs.urls", "pdrs"), namespace="pdrs")),
]
|
# file used to manage VMs in Amazon EC2
import boto3
import time
import paramiko
class Ec2VMManager:
def __init__(self, description, access_key, secret_key):
print "Starting VM Manager"
self.description = description
self.ec2_client = boto3.client('ec2', region_name='us-west-2')
self.ec2_r... |
import copy
from flask_restful import Api, Resource
from .utils import null_view, ismatch
class CustomApi(Api):
def __init__(self, app=None):
super(CustomApi, self).__init__(app=app)
def add_resource(self, resource, *urls, **kwargs):
if kwargs.get('demo_dict'):
resource = get_de... |
"""
@file
@brief Functions to show shortened options in :epkg:`asv` benchmarks.
"""
def expand_onnx_options(model, optim):
"""
Expands shortened options. Long names hide some part
of graphs in :epkg:`asv` benchmark. This trick converts
a string into real conversions options.
@param model ... |
from inspect import getfullargspec
def find_all_logic_combos(n: int) -> list:
"""
Takes a integer "n" and generates a list
of all possible combinations of 0 and 1 with length "n"
:param int n: length of combinations
:return: list of all possible combinations of 0 and 1 with specified length n
... |
# main imports
import numpy as np
import pandas as pd
import sys, os, argparse
# image processing
from PIL import Image
from ipfml import utils
from ipfml.processing import transform, segmentation
# modules and config imports
sys.path.insert(0, '') # trick to enable import of main folder module
import custom_config ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2020-07-27 12:54
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
... |
num1 =1
num2 =2
num3 =3
|
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the Apache 2.0 License.
# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-d... |
# 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
# d... |
#
# {c) 2017 Red Hat, Inc.
#
# This file is part of Ansible
#
# Ansible 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, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is ... |
#x=True
#y=0
#x=y<4
#print(x)
#
# x=True
# y=0
# x=y==0
# print(x)
#
#x=True
#y=0
#x=y!=9
#print(x)
#3
#x='b' in 'bed'
#print(x)
#
# x='b' in 'po'
# print(x)
#
# help()
x='b' in 'bo'
print(x) |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import pickle
def plot_evaluation(model_name,
roll=None):
"""
Creates a plot of the training/validation accuracy and loss over the training epochs.
Paramters:
model_name: (string with quotes) name of mo... |
"""
Test object marking.
"""
from unittest import TestCase
from six import (
PY2,
PY3,
)
from chromalog.mark import Mark
from .common import (
repeat_for_values,
repeat_for_integral_values,
)
class MarkTests(TestCase):
@repeat_for_values()
def test_string_rendering_of_marked(self, _, value)... |
#!/usr/bin/env python3
from mpi4py import MPI
def mesh_ep_gmshapi(name,
Lx,
Ly,
L0,
s,
lc,
tdim,
order=1,
msh_file=None,
sep=0.1,
... |
import random
# O(n) average case, O(n^2) worst case
def get_median(arr,m=None):
smaller = []
larger = []
equal = []
num = random.choice(arr)
for n in arr:
if n < num:
smaller.append(n)
elif n > num:
larger.append(n)
else:
equal.append(n)
if... |
import json
def save_records_to_file(records, filename):
with open(filename, 'w') as f:
json.dump(records, indent=4, sort_keys=True, fp=f)
def add_state_to_addresses(filename):
with open(filename, 'r') as f:
records = json.load(f)
for i in range(len(records)):
for j in ra... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 26 20:22:25 2020
@author: xianbingu
"""
def maximum(A):
#delete the following line and insert your code
#the built-in max() is not allowed to use here
pass
##---test---##
##You can comment out them when you write and test your code... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the BSD license found in the
# LICENSE file in the root directory of this source tree.
"""
Testing SsdFlatParameter and SsdTensorHandle modules.
"""
import tempfile
import numpy as np
import pytest
import torch
import fairscal... |
#
# Copyright (c) 2020, Neptune Labs Sp. z o.o.
#
# 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... |
# coding=utf8
# Copyright 2018 JDCLOUD.COM
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... |
from flask import render_template
from . import bl_leitos
|
import glob
import os
from datetime import datetime
basedir = "/home/tlhop/aplicacao_urls/urls/repo"
dataatual = datetime.today().strftime('%Y%m%d')
conjunto_urls = set()
lista_arquivos = glob.glob(basedir+"/*")
for arquivo in lista_arquivos:
fr = open(arquivo,'r')
urls = fr.readlines()
for url_data in url... |
# Copyright (c) 2018-2020, Michael P. Howard
# Copyright (c) 2021, Auburn University
# This file is part of the azplugins project, released under the Modified BSD License.
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list se... |
import nibabel as nib
import numpy as np
import glob
import pandas as pd
img_fldr = './Task04_Hippocampus/imagesTr/'
files = glob.glob(img_fldr + "*.gz")
datas = []
for filePath in files:
img = nib.load(filePath)
data = img.get_fdata()
datas.append(data.shape)
df = pd.DataFrame(datas, columns = ['Xsize'... |
import tributary.lazy as tl
import tributary.streaming as ts
import tributary as t
class TestLazyToStreaming:
def test_function(self):
def foo(*args):
for _ in range(5):
yield _
lazy_node = tl.Node(callable=foo) + 5
# 5 6 7 8 9
streaming_node = ts.Prin... |
# Generated by Django 3.2.9 on 2022-01-27 10:02
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('parasitologyTool', '0020_auto_20220127_0959'),
]
operations = [
migrations.AlterField(
model_name='photo',
name='ima... |
import os
import uuid
from typing import Dict, List, Tuple
import numpy as np
from app.config import Config
from app.utils.slide_utils import delete_keys_from_dict
from PIL import Image
from pydicom import dcmread
from pydicom.pixel_data_handlers.util import apply_color_lut
class Dicom:
@staticmetho... |
# -*- coding: utf-8 -*-
import unittest
import sys
import os.path as path
sys.path.insert(0, path.abspath(path.join(__file__ ,"../..")))
from geograpy3.place import Place
class TestPlace(unittest.TestCase):
def test_basic(self):
p = Place(city='city', region='region', country='country')
self.ass... |
from numpy.linalg import inv,cholesky
class BaseMetricLearner(object):
def __init__(self):
raise NotImplementedError('BaseMetricLearner should not be instantiated')
def metric(self):
L = self.transformer()
return L.T.dot(L)
def transformer(self):
return inv(cholesky(self.metric()))
def tran... |
icon_ico = b'\x00\x00\x01\x00\x06\x00\x00\x00\x00\x00\x01\x00 \x00pK\x00\x00f\x00\x00\x00\x80\x80\x00\x00\x01\x00 \x00(\x08\x01\x00\xd6K\x00\x00@@\x00\x00\x01\x00 \x00(B\x00\x00\xfeS\x01\x0000\x00\x00\x01\x00 \x00\xa8%\x00\x00&\x96\x01\x00 \x00\x00\x01\x00 \x00\xa8\x10\x00\x00\xce\xbb\x01\x00\x10\x10\x00\x00\x01\x00 ... |
# -*- coding: utf-8 -*-
#
# Copyright: (c) 2017, F5 Networks Inc.
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
import pytest
import sys
from nose.plugins.skip i... |
"""Module contains functions for build and preprocess dataset."""
from os import path
import numpy as np
import pandas as pd
from scipy.stats import norm
from .file import download_files, DEFAULT_DATA_DIR_NAME
def build_lagged_matrix(X, lags=3):
"""
Build a lagged variable for each ones in X.
Paramete... |
import pygame
import time
import random
pygame.init()
display_width = 900
display_height = 800
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)
gameDisplay = pygame.display.set_mode((display_width , display_height))
pygame.display.set_caption('Avoid Them')
cl... |
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Dsa
from .serializer import DsaSerializer
# Create your views here.
class DsaView(APIView):
def get(self, request, *args, **kwargs):
dsaList = Dsa.objects.all()
... |
import librosa
from specAugment import spec_augment_pytorch
def get_warped_masked_spectrogram(audio_file_path):
audio, sampling_rate = librosa.load(audio_file_... |
import json
from robot.libraries.BuiltIn import BuiltIn
from suds.plugin import DocumentPlugin
from suds.client import Client
from suds import WebFault
zoomba = BuiltIn()
class _ObjectNamespacePlugin(DocumentPlugin):
"""_ObjectNamespacePlugin
This class contains a plugin for use in fixing broken WSDL Na... |
# -*- coding: utf-8 -*-
"""
oauthlib.oauth2.rfc6749.grant_types
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
from __future__ import unicode_literals, absolute_import
import json
import logging
from oauthlib import common
from oauthlib.uri_validate import is_absolute_uri
from .base import GrantTypeBase
from .. import err... |
from dearpygui.core import *
from dearpygui.simple import *
def print_me(sender, data):
log_debug(f"Menu Item: {sender}, {data}")
show_logger()
with window("Tutorial"):
with menu_bar("Main Menu Bar"):
with menu("File"):
add_menu_item("Save", callback=print_me)
add_menu_it... |
# coding: utf-8
from normality import stringify
from collections import OrderedDict
# from tempfile import NamedTemporaryFile
from openpyxl import load_workbook
URL = "http://date.gov.md/ckan/en/dataset/11736-date-din-registrul-de-stat-al-unitatilor-de-drept-privind-intreprinderile-inregistrate-in-repu" # noqa
de... |
# https://www.codewars.com/kata/523f5d21c841566fde000009
def array_diff(a, b):
bs = set(b)
return [n for n in a if n not in bs]
|
import time
DEFAULT_FORMAT = '[{elapsed:0.8f}s] {name}({args}) -> {result}'
def clock(fmt=DEFAULT_FORMAT):
def decorate(func):
def clocked(*_args):
t0 = time.time()
_result = func(*_args)
elapsed = time.time() - t0
name = func.__name__
args = ',... |
from uplink import (
Consumer,
Path,
Query,
Body,
Header,
get,
post,
patch,
put,
delete,
returns,
json,
)
from typing import Dict, List, Optional, Union # noqa: F401
from aries_cloudcontroller.uplink_util import bool_query
from aries_cloudcontroller.model.admin_config... |
#!/usr/bin/env python3
import sys
from jnpr.junos import Device
from jnpr.junos.exception import LockError
from jnpr.junos.utils.config import Config
from jnpr_devices import srx2
def check_connected(device):
print()
if device.connected:
print("Connected to {}".format(device.hostname))
return ... |
# () , を使用した型はタプル
# 値を変えることはできない
tuple_data = (1, 'Hokkaido', 47, 'Okinawa')
print(tuple_data)
print(type(tuple_data))
# [] , を使用した型はリスト
# 値を変えることができる
list_data = [1, 'Hokkaido', 47, 'Okinawa']
print(list_data)
print(type(list_data))
list_data[0] = 0
list_data[1] = 'Aomori'
print(list_data)
# {} : , を使用した型は辞書
dict_... |
import cdms
from MA import allclose
f = cdms.open('clt.nc')
v = f('clt')
s = cdms.selectors.timeslice(0,120,12)
x = s.select(v)
print x.shape
y = v(s)
print y.shape
assert allclose(x,y)
assert allclose(x, f('clt', time=slice(0,120,12)))
x = v(s, longitude=(100,150))
print x.shape
y = x(latitude=(-40,40))
print y.shape
... |
# Generated by Django 3.0.9 on 2020-12-16 14:20
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('music_library', '0004_stand_score'),
]
operations = [
migrations.AlterField(
model_name='instrument',
name='name',
... |
import re
from os import path
import sys
from subprocess import run
import json
import requests
def collect(input_path, output_path):
wordpress_path = input_path
version_php_path = path.join(wordpress_path, "wp-includes/version.php")
with open(version_php_path, "r") as f:
content = f.read()
... |
import re
from typing import Callable
from click import version_option as click_version_option
from click.decorators import FC
from rich.console import Console
from .utils import _colorize
def version_option(
version: str = None,
prog_name: str = None,
message: str = "%(prog)s, version %(version)s",
... |
"""See :doc:`/dev/polls/index`."""
|
import random
def roll_dice():
"""give a random number from 1 to 6"""
diceroll = random.randint(1,6)
return diceroll
def player1(b1):
roll = roll_dice()
if roll == 1:
if b1.body == 0:
b1.body = 1
player1(b1)
else:
return b1
eli... |
u"""
This module provides support for managing PDF colorspaces and colors.
Color spaces in PDF are organized as two factory functions:
1. `COLOR SPACE FAMILIES` create `COLOR SPACES` based on certain parameters
2. `COLOR SPACES` create `COLORS` based on certain numerical values
minecart's approach to handling these ... |
import os
import sys
import cv2
import time
import numpy as np
import scipy.io
import argparse
import timm
import torch
import torch.nn as nn
import torch.nn.functional as F
import albumentations as A
from glob import glob
from torch.utils.data import Dataset, DataLoader
SEED = 42
N_CLASSES = 120
IMAGE_SIZE = (128, 12... |
from pandas import DataFrame
import random
def split_by_id(data, id_column, n=None, fraction=None, random_state=None, **kwargs):
"""
this method splits the data, by considering rows with the same id as one and refusing to divide them
it is useful when you want a sample of the data based on ids when the ids are repe... |
class ProducerError(Exception):
"""
Exception is thrown when producing fails.
"""
pass
class MissingProducerError(ProducerError):
"""
Exception is thrown when trying to dispatch without a producer.
"""
pass
class ConsumerError(Exception):
"""
Exception is thrown when consumin... |
import pytest
from cx_Freeze.winmsvcr import FILES, FILES_TO_DUPLICATE
def test_FILES():
expected = (
# VC 2015 and 2017
"api-ms-win-core-console-l1-1-0.dll",
"api-ms-win-core-datetime-l1-1-0.dll",
"api-ms-win-core-debug-l1-1-0.dll",
"api-ms-win-core-errorhandling-l1-1-0.dl... |
#!/bin/env python3
# coding: utf-8
import sys
for line in sys.stdin:
if not line:
continue
if len(line.strip()) == 1:
continue
text = line.encode("utf-8", "ignore")
out = text.decode("utf-8", "ignore").strip()
print(out)
|
import typing as T
from functools import lru_cache
class DataKeys:
def __init__(self, detector: str, image: str) -> None:
self.image = image
self.detector = detector
self.mask = detector + "_mask"
self.chi_2theta = detector + "_chi_2theta"
self.chi_Q = detector + "_chi_Q"
... |
# Copyright (C) Ivan Kravets <me@ikravets.com>
# See LICENSE for details.
from twisted.application.service import ServiceMaker
SmartAnthill = ServiceMaker(
"smartanthill",
"smartanthill.service",
"An intelligent micro-oriented networking system",
"smartanthill")
|
import sys
import os
def write_over(oldFile, newFile):
print("Old file is ",oldFile)
print("New file is ",newFile)
with (open(newFile, 'r',encoding = "utf-8")) as f:
data = f.read()
with (open(oldFile, 'w',encoding = "utf-8")) as g:
g.write(data)
#print("Data overwritten successf... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models # noqa
# Note: This was written when we needed to migrate the Standup db from the old schema to the new
# one. We don't need to do that anymore and this migration prevents contributors from creating fresh
# datab... |
#!/usr/bin/env python
#
# export_occupation_category_partial.py
#
# This script reads in spreadsheets to output an HTML fragment that can be
# embedded into browse.html that creates the dropdown-by-category menu for
# browsing jobs. Generally, the output of the script should be placed into the
# path views/partials/m... |
import numpy as np
import math
import collections
def periodic_particles_stay_in_box(pos_arr, length):
return pos_arr - np.floor(pos_arr / length) * length
def periodic_wrap_corner(dist_arr, length, verbose=False):
"""For a box with lower left vertex at the origin."""
if verbose:
print(dist_arr)... |
""" USER INFORMATION
Student: Josh Block
Date: 4/28/22
Version: 1.6.1 """
# create SQL connection
import mysql.connector
# ------------ VIEW DATA QUERY FUNCTIONS ------------ #
# Query the EmployeesPerRegion to show the number of employees per region [COMPLETE]
def get_employees_data(mycursor):
... |
"""
URL: https://codeforces.com/problemset/problem/702/A
Author: Safiul Kabir [safiulanik at gmail.com]
Tags: dp, greedy, implementation, *800
"""
n = int(input())
array = list(map(int, input().split()))
max_inc_subarray_count = 1
tmp_count = 1
ci = array[0]
del array[0]
for i in array:
if ci < i:
tmp_cou... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
class MDA:
"""
Supervised Mixture Discriminant Analysis Model. The Model creates a
Gaussian Mixture Model for each class in the classification problem.
Classification probabilities are then computed for each Gaussian
Mixtu... |
import os
import json
import logging
import importlib
import six
logger = logging.getLogger(__name__)
_BASE_CONFIG_NAME = "default.json"
def add_log_handler(fh):
logger.addHandler(fh)
def merge_config(a, b, name):
assert type(a) == type(b), "default and %s config file are not compatible" % name
if isin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.