content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Benjamin Vial
# License: MIT
from dolfin import *
# parameters['allow_extrapolation'] = True
mesh = UnitIntervalMesh(15)
V = FunctionSpace(mesh, "CG", 2)
u = Function(V)
# u_vec = u.vector()
# u_vec[:] = MPI.comm_world.rank + 1
#
# v_vec = Vector(MPI.comm_sel... |
"""Defines Blink cameras."""
from shutil import copyfileobj
import logging
from blinkpy import api
from blinkpy.helpers.constants import TIMEOUT_MEDIA
_LOGGER = logging.getLogger(__name__)
class BlinkCamera:
"""Class to initialize individual camera."""
def __init__(self, sync):
"""Initiailize Blink... |
#AUTOGENERATED! DO NOT EDIT! File to edit: dev/01.ML_Landscape.ipynb (unless otherwise specified).
__all__ = [] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
requests_cache.backends.base
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Contains BaseCache class which can be used as in-memory cache backend or
extended to support persistence.
"""
from datetime import datetime
import hashlib
from copy import copy
from alp.request ... |
__docformat__ = "restructuredtext"
__version__ = "0.2.7"
__doc__ = """
This<https://github.com/WinVector/wvpy> is a package of example files for teaching data science.
"""
|
import insightconnect_plugin_runtime
from .schema import Component, DeleteUrlListByIdInput, DeleteUrlListByIdOutput, Input
class DeleteUrlListById(insightconnect_plugin_runtime.Action):
def __init__(self):
super(self.__class__, self).__init__(
name="delete_url_list_by_id",
descrip... |
#
# This file is 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
# distr... |
import numpy as np
from keras import backend as K
from keras.layers import Input
from keras.layers import Lambda
from keras.layers import Dense
from keras.layers import Flatten
from keras.layers import Dropout
from keras.layers import Activation
from keras.layers import Conv1D
from keras.layers import Conv2D
from ker... |
s=input()
x="hello"
t=0
l=0
for item in range (len(s)):
if(t<=4 and s[item]==x[t]):
t=t+1
l=l+1
if(l==5):
print("YES")
else:
print("NO") |
class Errors(object):
def __init__(self, data=None, parameter=None, token=None):
self.data = data
self.parameter = parameter
self.token = token
def check_error(self):
if 'error' in self.data:
if self.data['error'] == 'Authorization required':
raise Va... |
# The MIT License (MIT)
#
# Copyright (c) 2021 Huimao Chen
#
# 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 use, copy, modif... |
from math import floor, log2
from typing import (
Any,
Collection,
Dict,
Iterator,
Optional,
Sequence,
Set,
Tuple,
Union,
)
from pystiche import ComplexObject, loss
from pystiche.misc import zip_equal
from .level import PyramidLevel
from .storage import ImageStorage
__all__ = ["Im... |
import chainercv
import copy
import numpy as np
def _copy_transform(in_data):
out = []
for elem in in_data:
if isinstance(elem, np.ndarray):
elem = elem.copy()
else:
elem = copy.copy(elem)
out.append(elem)
return tuple(out)
def copy_dataset(dataset):
... |
"""
Good morning! Here's your coding interview problem for today.
This problem was asked by Google.
Suppose we represent our file system by a string in the following manner:
The string "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext" represents:
dir
subdir1
subdir2
file.ext
The directory dir contains an em... |
#! /usr/bin/env python
"""
singleSession.py
===================
This program is used to generate the subject- and session-specific workflows for BRAINSTool processing
Usage:
singleSession.py [--rewrite-datasinks] [--wfrun PLUGIN] [--use-sentinal] [--dry-run] --workphase WORKPHASE --pe ENV --ExperimentConfig FILE SES... |
# +
from RPA.Browser.Selenium import Selenium
import time
import os
from os import replace
import pandas as pd
browser=Selenium()
url='https://heycarson.com/task-catalog-browse/task-types/development'
if not os.path.exists('Output'):
os.makedirs('Output')
path_dload=(((os.getcwd()).replace('\\','\\\\'))+'\\Ou... |
"""Config for mara Google Sheets Downloader
You need to configure oauth2 credentials for either a google service or a google user account.
"""
import typing as t
def gs_service_account_private_key_id()-> t.Optional[str]:
"""Google Service Account private_key_id used to download the Google Sheets"""
return Non... |
# Assesses the readability score of a document, line-by-line.
import argparse
import textstat
def get_scorer(choice):
scorers = {
0: textstat.flesch_reading_ease,
1: textstat.flesch_kincaid_grade,
2: textstat.dale_chall_readability_score,
3: textstat.text_standard
}
return s... |
from django.contrib import admin
from emails.models import Email
# Register your models here.
admin.site.register(Email)
|
from GenericRequest import GenericRequest
from kol.manager import PatternManager
class LoadClanAdminRequest(GenericRequest):
"Load's the clan administration page."
def __init__(self, session):
super(LoadClanAdminRequest, self).__init__(session)
self.url = session.serverURL + "clan_admin.php"
... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from keras.layers import Conv2D, Dense, Flatten
from keras.models import Sequential
# https://www.kaggle.com/crawford/deepsat-sat4
# _____________________________________________________________________________
# - Each sample image is 28... |
# -*- coding: utf-8 -*-
"""Generate the Resilient customizations required for algosec_resilient"""
from __future__ import print_function
from resilient_circuits.util import *
def codegen_reload_data():
"""Parameters to codegen used to generate the algosec_resilient package"""
reload_params = {"package": u"al... |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
class ImageMaker:
def __init__(self,img):
plt.axis('off')
plt.imshow(mpimg.imread(img))
def addPoint(self,x,y):
plt.scatter([x],[y])
def saveImage(self):
plt.savefig('/var/www/html/images/... |
from trinsicokapi.proto.okapi.metadata import MetadataResponse, MetadataRequest
from trinsicokapi.wrapper import _typed_wrap_and_call
def get_metadata() -> MetadataResponse:
response = _typed_wrap_and_call(
"okapi_metadata", MetadataRequest(), MetadataResponse
)
return response
|
#!/usr/bin/python3.5
# I don't believe in license.
# You can do whatever you want with this program.
def doWork():
while True:
host = q.get()
resolve( host )
q.task_done()
def resolve( host ):
if t_multiproc['n_current']%5000 == 0:
save(False)
sys.stdout.write( 'prog... |
import datetime as dt
import json
import multiprocessing as mul
import os
from sqlite3 import dbapi2 as sqlite
from unittest import skip, TestCase
import numpy as np
import pandas as pd
from requests.exceptions import ConnectionError
import responses
from sqlalchemy import create_engine
from sqlalchemy.orm import sess... |
#!/usr/bin/env python3
import sys
import getopt
import Mail
import subprocess
import socket
config = {
'smtp_host' : "smtp.qq.com",
'smtp_user' : "czlibit@foxmail.com",
'smtp_pass' : "dngcjckjeylmdfbi",
'from_email' : "czlibit@foxmail.com",
'to_email' : ['hefish@qq.com', "hefish@gmail.com"],
... |
import os
from argparse import ArgumentParser
def get_args():
parser = ArgumentParser(description='PyTorch/torchtext SNLI example')
parser.add_argument('--epochs', type=int, default=50)
parser.add_argument('--batch_size', type=int, default=128)
parser.add_argument('--d_embed', type=int, default=300)
... |
import bpy
from bpy.props import *
from ... data_structures import DoubleList
from ... base_types import AnimationNode
modeItems = [
("AVERAGE", "Average", "", "FORCE_TURBULENCE", 0),
("SPECTRUM", "Spectrum", "", "RNDCURVE", 1)
]
class EvaluateSoundNode(bpy.types.Node, AnimationNode):
bl_idname = "an_Eval... |
"""Mix-ins used to add defined behaviors to Tapis CLI commands
"""
import argparse
import copy
import json
import os
import sys
import validators
import docker as dockerpy
from agavepy.agave import Agave
from cliff.command import Command
from cliff.hooks import CommandHook
from cliff.app import App
from tapis_cli im... |
# ------------------------------------------------------------------------------
# Class all model definitions should descend from.
# ------------------------------------------------------------------------------
import os
import torch.nn as nn
import numpy as np
from torchsummary import summary
from mp.utils.pytorch... |
from . import tests
|
# Exercício Python 086:
# Crie um programa que declare uma matriz de dimensão 3x3 e
# preencha com valores lidos pelo teclado.
# No final, mostre a matriz na tela, com a formatação correta.
#matriz = [[2, 3, 4], [7, 5 , 4], [8, 4, 9]]
def l(ll): print(30*ll)
matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
l('=')
print('v... |
# Copyright 2017 Akretion (http://www.akretion.com).
# @author Sébastien BEAU <sebastien.beau@akretion.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import base64
import os
from urllib import parse
import requests_mock
from odoo.exceptions import AccessError
from odoo.addons.component.tests.c... |
# -*- coding: utf-8 -*-
# This module is part of GitPython and is released under
# the BSD License: http://www.opensource.org/licenses/bsd-license.php
import re
from pathlib import Path
import git
from .lib import TestBase, with_rw_directory
class TestClone(TestBase):
@with_rw_directory
def test_checkout_i... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** 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 _utilities
__... |
"""
Feature Scaling
- We discussed previously that the scale of the features is an important consideration when building machine
learning models.
Briefly:
Feature magnitude matters because:
- The regression coefficients of linear models are directly influenced by the scale of the variable.
- Varia... |
#
# Copyright (c) 2021 ISP RAS (http://www.ispras.ru)
# Ivannikov Institute for System Programming of the Russian Academy of Sciences
#
# 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
#
# h... |
from builtins import object
import os
from vnc_api_test import *
from tcutils.config.vnc_introspect_utils import *
from tcutils.config.svc_mon_introspect_utils import SvcMonInspect
from tcutils.control.cn_introspect_utils import *
from tcutils.agent.vna_introspect_utils import *
from tcutils.collector.opserver_introsp... |
import re
REGEX = r"^([a-z0-9-._]+)@([a-z0-9]+)(\.[a-z]{1,3})+$"
def valid_email(email):
match = re.match(REGEX, email)
if match:
return True
return False
def filter_email(emails):
return [email for email in emails if valid_email(email)]
|
import pytest
from src import Store
def test_invalid_constructor_argument():
with pytest.raises(Exception):
Store(None)
with pytest.raises(Exception):
Store(1)
with pytest.raises(Exception):
Store("AHAHA")
|
from setuptools import find_packages
from distutils.core import setup
from modbus_tcp_server import __version__
setup(version=__version__,
packages=find_packages(include=['modbus_tcp_server', 'modbus_tcp_server.*']),
install_requires=['satella'],
python_requires='!=2.7.*,!=3.0.*,!=3.1.*,!=3.2.*,!=3.... |
import sys
import numpy as np
import seaborn as sns
import pandas
import matplotlib
import matplotlib.pylab as plt
from matplotlib.colors import ListedColormap, LinearSegmentedColormap
file = sys.argv[1]
outbase = sys.argv[2]
with open(file) as f:
labels = f.readline().split('\t');
ncols = len(labels);
print ... |
#!/usr/bin/python
######################################################################
# import utils.database # @UnusedImport to ensure database connection
######################################################################
from __future__ import division
from sys import argv
from cronutils import run_tasks,... |
# -*- coding: utf-8 -*-
import socket
import os
import time
import cv2
import math
import serial
import matplotlib.pyplot as plt
from configparser import ConfigParser
from Modules import module_calibrate_camera, module_vision, module_calibrate_color
#Read config.ini file
config_object = ConfigParser()
config_object.re... |
from django.template import Library
register = Library()
@register.filter
def is_false(arg):
return arg is False
|
import zmq
import logging
import sys
from os import path
import pickle
import numpy as np
import time
import threading
from collections import deque
import math
try:
from attitude_config import (init, ATTITUDE_TOPIC, IMU_TOPIC, TIME_STEP)
except ImportError as e:
print(f'failed to import: {e} - exit')
sys... |
import re
from threading import Lock
from pycor import korutils, parser
from pycor import morpheme as lm
from pycor import speechmodel as sm
# Y_TAGS0 = set(['EFN','ETN','EFQ'])
# Y_TAGS1 = set(['EPT-pp','EPT-f','EPT-guess','EFN','EFI','EC-to','EC-for','EC-but'])
# Y_TAGS2 = set(['EPT-pr','ETM'])
# C_TAGS0 = set(['J... |
import re
import random
from cwbot.modules.BaseChatModule import BaseChatModule
from cwbot.util.shuntingYard import evalInfix
def parseDice(args):
""" Parse a dice expression (e.g., 3d10-1d6) and evaluate the dice
(e.g., to the string 18-2) """
m = re.search(r'(\d*)d(\d+)', args)
while m is ... |
# Configuration Blender
import bpy
bpy.context.user_preferences.edit.use_drag_immediately = True
bpy.context.user_preferences.edit.use_insertkey_xyz_to_rgb = False
bpy.context.user_preferences.inputs.select_mouse = 'LEFT'
bpy.context.user_preferences.inputs.view_zoom_method = 'DOLLY'
bpy.context.user_preferences.input... |
"""The Azure Storage Block Blob backend for Celery."""
from __future__ import absolute_import, unicode_literals
from kombu.utils import cached_property
from kombu.utils.encoding import bytes_to_str
from celery.exceptions import ImproperlyConfigured
from celery.utils.log import get_logger
from .base import KeyValueSt... |
import logging
from loguru import logger as loguru_logger
import os
import os.path as osp
import sys
from setproctitle import setproctitle
import torch
from mmcv import Config
import cv2
from pytorch_lightning import seed_everything
from pytorch_lightning.lite import LightningLite # import LightningLite
cv2.setNumTh... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ldig : Language Detector with Infinite-Gram
# This code is available under the MIT License.
# (c)2011 Nakatani Shuyo / Cybozu Labs Inc.
import os
import sys
import re
import codecs
import json
import gzip
import htmlentitydefs
import numpy
from Microblog_Trec.common i... |
import matplotlib.pyplot as plt
import numpy as np
focal_length = 100 # focal length in mm
angle_deg = 0 # angle of incidence of the incident beam in degrees
rays = 21 # number of rays
p = 2 * focal_length # parameter of the parabola equation y**2 = 2*p*z
a = 1.1 * focal_length # mirror field
inc_ang = -ang... |
import psycopg2
from app import database
from app.vendors.prepare import PreparingCursor
def get_db():
try:
connection = database.connect()
cursor = connection.cursor(cursor_factory=PreparingCursor)
return cursor, connection
except Exception as exc:
raise ValueError(f"{exc}")
... |
# xpyBuild - eXtensible Python-based Build System
#
# Copyright (c) 2013 - 2017 Software AG, Darmstadt, Germany and/or its licensors
#
# 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
#
# ... |
import frappe
from frappe.custom.doctype.custom_field.custom_field import create_custom_field
def execute():
company = frappe.get_all('Company', filters = {'country': 'India'})
if not company:
return
create_custom_field('Delivery Note', {
'fieldname': 'ewaybill',
'label': 'E-Way B... |
class Solution:
def hasAlternatingBits(self, n: int) -> bool:
t = n & 1
n >>= 1
while n:
if (n & 1) == t: return False
t = n & 1
n >>= 1
return True
|
import re
from django import template
from festival.models import Project
from filmfestival.models import Film
register = template.Library()
@register.simple_tag(takes_context=True)
def project_film_by_directors(context, **kwargs):
projects = Project.objects.filter(**kwargs)
context['films'] = Film.objects... |
from collections import defaultdict
from datetime import datetime, timezone
from itertools import chain
import logging
import pickle
from typing import Any, Collection, Dict, Iterable, List, Mapping, Optional, Tuple, Union
import aiomcache
import numpy as np
import pandas as pd
from sqlalchemy import sql
from sqlalche... |
# app seettings
EC2_ACCESS_ID = 'A***Q'
EC2_ACCESS_KEY = 'R***I'
YCSB_SIZE =0
MCROUTER_NOISE = 0
MEMCACHED_OD_SIZE = 1
MEMCACHED_SPOT_SIZE = 0
G_M_MIN = 7.5*1024
G_M_MAX = 7.5*1024
G_C_MIN = 2
G_C_MAX = 2
M_DEFAULT = 7.5*1024
C_DEFAULT = 2
G_M_MIN_2 = 7.5*1024
G_M_MAX_2 = 7.5*1024
G_C_MIN_2 = 2
G_C_MAX_2 = 2
M_... |
from django.contrib.auth.tokens import PasswordResetTokenGenerator
class PasswordGenerator(PasswordResetTokenGenerator):
def _make_hash_value(self, user , timestamp: int):
return str(user.pk)+str(timestamp) |
# $Id$
#
# Copyright (C) 2007,2008 Greg Landrum
#
# @@ All Rights Reserved @@
#
import os, sys
import io
import unittest
import pickle
from rdkit import RDConfig
from rdkit import DataStructs as ds
def feq(v1, v2, tol=1e-4):
return abs(v1 - v2) < tol
class TestCase(unittest.TestCase):
def setUp(self):
pas... |
# Copyright 2009-2011 by Eric Talevich. All rights reserved.
# Revisions copyright 2009-2013 by Peter Cock. All rights reserved.
# Revisions copyright 2013 Lenna X. Peterson. All rights reserved.
# Revisions copyright 2013 Gokcen Eraslan. All rights reserved.
# Revisions copyright 2020 Joao Rodrigues. All rights rese... |
import json
import pytest
import os
import nomad
import uuid
import responses
import tests.common as common
def test_register_job(nomad_setup):
with open("example.json") as fh:
job = json.loads(fh.read())
nomad_setup.job.register_job("example", job)
assert "example" in nomad_setup.job
#... |
import sys
from pathlib import Path
from typing import List
from pipx_release import copy_file_replace_line, python_mypy_ok
def fix_version_py(new_version: str) -> bool:
version_code_file = Path("src/pipx/version.py")
new_version_code_file = Path("src/pipx/version.py.new")
new_version_list = new_version.... |
import logging
from selenium.webdriver.common.keys import Keys
logger = logging.getLogger(__name__)
class TextBoxActionsMixin:
def set_text(self, text, skip_if_none=True, blur_and_focus=False):
"""
clear the text field and type new text
:param text: text that should be set
:para... |
# Generated by Django 3.1.7 on 2021-04-10 11:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('spell', '0007_components'),
]
operations = [
migrations.AddField(
model_name='spell',
name='components',
... |
from framework.util.db import get_db_port
def main():
port = get_db_port()
print(port)
if __name__ == "__main__":
main()
|
"""Tests of easy.py
"""
import unittest
from reversi.board import Board
from reversi.strategies import Random, Greedy, Unselfish, SlowStarter
class TestEasy(unittest.TestCase):
"""easy
"""
def test_random(self):
random = Random()
board = Board()
legal_moves = board.get_legal_mov... |
#!/usr/bin/env python
import os
from UrlConfig import UrlConfig
HOST_NAME = '0.0.0.0'
PORT_NUMBER = 443 # This is the bind port
SYSTEM_PROFILER = "/in"
SYSTEM_PROFILER_REDIRECT = "https://linkedin.com"
POSHDIR = "/opt/PoshC2_Python/"
ROOTDIR = "/opt/PoshC2_Project/"
HostnameIP = "https://192.36.15.234"
DomainFrontHea... |
__all__ = ["utils","sra","mgrast","imicrobe"]
import os, sys, argparse, warnings, shutil
import pandas as pd
from pathlib import Path
from grabseqslib.sra import process_sra, add_sra_subparser
from grabseqslib.imicrobe import process_imicrobe, add_imicrobe_subparser
from grabseqslib.mgrast import process_mgrast, add_... |
# Copyright 2018 IBM Corporation
#
# 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, ... |
#! python3
#stopwatch.py - a simple stopwatch program
import time
#display instructions
print('Press ENTER to begin. Afterwards, press ENTER to "click" the stopwatch Press CTRL-C to quit.')
input() #press enter to begin
print('Started.')
startTime = time.time() #grabs the first 'lap's' startime
lastTime = startTime
l... |
import sys
import numpy as np
import configReader
import scipy.stats as stats
import os, shutil
def initializeIndividual(n, allzero=False, sigma=0.0, bounds=(0,1)):
"""
Initialize the single-population EA. If the allzero flag is on, then
the individual is initialized at the 0^n position. If sigma is 0, then
... |
# -*- coding: utf-8 -*-
###############################################################################
# Copyright Kitware 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
#
# ... |
'''
Class regrouping all methods and attributes for an experiment.
'''
import os
import sys
import time
import subprocess
import csv
from copy import deepcopy
from datetime import datetime
from ast import literal_eval
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mplcolors
from matplotl... |
from django.contrib import admin
from fsdviz.common.utils import fill_color_widget
from .models import (
LifeStage,
Condition,
StockingMethod,
StockingEvent,
Hatchery,
YearlingEquivalent,
)
admin.site.empty_value_display = "(None)"
@admin.register(LifeStage)
class LifeStageModelAdmin(admin.... |
from ec2mc.utils import handle_ip
from ec2mc.utils.base_classes import CommandBase
from ec2mc.utils.find import find_instances
from ec2mc.validate import validate_perms
class CheckServers(CommandBase):
def main(self, cmd_args):
"""check instance status(es)
Args:
cmd_args (namedtuple):... |
#!/usr/local/bin/python3.6
# -*- coding:utf-8 -*-
# ========================================
# Description :
# 框架引导层
# 全局参数定义、配置参数定义、默认参数生成、路径参数生成
# Created : 2020.10.14
# Author : Chalk Yu
# ========================================
from __future__ import absolute_import
from types import MethodType, FunctionType... |
from pathlib import Path
from typing import Optional
import typer
from experiment_utils.utils.log_utils import (filter_runs, get_runs,
print_runs, rename_runs)
from rich import print
def show_runs(
dir_name: Optional[str] = typer.Argument(None),
rename: bool = ty... |
import vrdata
db1 = vrdata.connect('db1')
selected = db1['metadata'].find_one()
print(selected)
|
#============================================
__author__ = "Sachin Mehta"
__license__ = "MIT"
__maintainer__ = "Sachin Mehta"
#============================================
import numpy as np
def cropVolume(img, data=False):
'''
Helper function to remove the redundant black area from the 3D volume
:param i... |
from distutils.core import setup
setup(name='compiler01',
version='0.0.1',
description='Learning compiler theroy',
author='tor4z',
author_email='vwenjie@hotmail.com',
# install_requires=[],
packages=['lex']
)
|
import numpy as np
from sklearn import metrics
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, GaussianNoise
from keras.callbacks import EarlyStopping
import gc
import warnings
warnings.filterwarnings('ignore')
class SimpleUncompleteAutoencoder:
def __init__(se... |
# Run this script as a "standalone" script (terminology from the Django
# documentation) that uses the Djano ORM to get data from the database.
# This requires django.setup(), which requires the settings for this project.
# Appending the root directory to the system path also prevents errors when
# importing the models... |
from netapp.netapp_object import NetAppObject
class NdmpPasswordInfo(NetAppObject):
"""
Information about generate password
When returned as part of the output, all elements of this typedef
are reported, unless limited by a set of desired attributes
specified by the caller.
<p>
When used as... |
""" distribubot."""
from .version import version as __version__
__all__ = [
'utils',
'distribubot'
] |
import numpy as np
import matplotlib.pyplot as plt
def plot_saved_scores(causality_pipeline):
model = causality_pipeline.stages[3].model
saved_scores = model.decoder.saved
positives, negatives = [
[score for label, _pc, score in saved_scores if label == desired_label]
for desired_label in ... |
# License: BSD 3-Clause
from .functions import (
attributes_arff_from_df,
check_datasets_active,
create_dataset,
get_dataset,
get_datasets,
list_datasets,
status_update,
list_qualities,
)
from .dataset import OpenMLDataset
from .data_feature import OpenMLDataFeature
__all__ = [
"at... |
from django.apps import AppConfig
class WebsheetsConfig(AppConfig):
name = 'websheets'
|
import numpy as np
import matplotlib.pyplot as plt
import numpy.random as rn
from numpy import array as ary
from numpy import sqrt
from numpy.linalg import svd, eig, eigvals, inv, pinv
def set_offdiag(mat, triu, inplace=True):
'''sets the off-diagonal elements of a symmetric matrix when the top triangle's ... |
from itertools import takewhile
from math import sin, pi
# The takewhile function in the itertools module will yield elements from an iterable, as long as a specific criteria (the predicate) is True.
#
# As soon as the predicate is False,
# iteration is stopped - even if subsequent
# elements would have had a True pre... |
#!/usr/bin/env python
import sys
import subprocess
import os
import shutil
FNULL = open(os.devnull, "w")
def help():
print("Usage: cfgmngr [ACTION] [OPTION]")
print("Actions:")
print(" set-repo [URL] - add remote git repository to store your configs")
print(" repo - show current git repository")
... |
#!/usr/bin/env python3
# Solution to Project Euler problem 3
import math
def get_primes(limit):
return [idx for idx,b in enumerate(sieve(limit)) if b]
def sieve(limit):
is_prime = [False, True] * ((limit // 2) + (limit % 2))
is_prime[0], is_prime[1], is_prime[2] = False, False, True
i = 3
... |
import sys, unittest, glfw
sys.path.insert(0, '..')
from OpenGL.GL import *
from engine.base.shader import Shader
from engine.base.program import *
import helper
class ProgramTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.window = helper.initAndGetWindow()
@classmethod
def tear... |
o, b, l = map(float, input().split())
if o < b and o < l:
print("Otavio")
elif b < o and b < l:
print("Bruno")
elif l < o and l < b:
print("Ian")
else:
print("Empate") |
from django.http import HttpResponse, HttpResponseNotFound
from biostar.apps.posts.models import Tag
from biostar.apps.users.models import Profile
from django.shortcuts import redirect
from energyuse.eserver import views as eviews
from django.contrib import messages
def subscribe(request,topic):
context = {}
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2017, National University of Ireland and The James Hutton Insitute
# Author: Nicholas Waters
#
# This code is part of the riboSeed package, and is governed by its licence.
# Please see the LICENSE file that should have been included as part of
# this package.
... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'selector.ui'
#
# Created: Sat Jul 13 16:18:03 2019
# by: pyside-uic 0.2.15 running on PySide 1.2.2
#
# WARNING! All changes made in this file will be lost!
from PySide import QtCore, QtGui
class Ui_MainWindow(object):
def setupUi(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.