content stringlengths 5 1.05M |
|---|
import pygame
FLOOR_IMG = pygame.image.load("./asset/image/floor.png").convert_alpha()
class Floor:
def __init__(self, app, position):
self.app = app
self.image = FLOOR_IMG
self.rect = self.image.get_rect(topleft=position)
|
from pathlib import Path
import os
import webutils
import shutil
import json
import difflib
###
# Emojis are generally stored in (emoji:filename) and (emoji:url) pairs
###
class EmojiCache:
_emoji_pngs = []
_init = False
_fresh = False
_guilds = None
# JSON Constants
_EMOJIFILES = 'emoji_... |
from django.db import models
from iioy.core.fields import SlugField
from iioy.core.models import BaseTmdbModel
class Movie(BaseTmdbModel):
title = models.TextField()
original_title = models.TextField()
slug = SlugField(slug_field='title')
tagline = models.TextField(null=True)
budget = models.Big... |
# coding=utf-8
# Copyright (c) 2020, NVIDIA CORPORATION. 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 re... |
#!/usr/bin/env python
# time_frames.py
# A helper script to quickly and efficiently time animated gifs from sources with erratic key frame rates.
# Layer names must contain original frame numbers (e.g. shot0001.png, frame0001.png, etc.).
# Simply delete duplicate frames (but leave the last one) and run the script to g... |
from konlpy.tag import Kkma
kkma = Kkma()
malist = kkma.pos("아버지 가방에 들어가신다.")
print(malist) |
import sys
import os
import json
# py2/3 imports fix
from .gmapi import GraymetaClient
from .cli import CLI
from .constants import *
COMMAND="gm"
def usageAndDie():
print("gm is a tool for querying a graymeta.com installation over https")
print("https://github.com/simonski/gm-api-python")
print("")
p... |
# -*- coding: utf-8 -*-
import multiprocessing
def is_divisible(n):
if n % 3 == 0 or n % 5 == 0:
return True
else:
return False
# def sum_divisibles(ns):
# return sum(filter(is_divisible, ns))
def sum_divisibles(ns):
"""return paras.
no good
"""
print 'group'
return ... |
# Copyright (C) 2018 Garth N. Wells
#
# SPDX-License-Identifier: MIT
"""This module contains a collection of functions related to
geographical data.
"""
from .utils import sorted_by_key # noqa
from haversine import haversine, Unit
'''import plotly.express as px'''
def stations_by_distance(stations, p): #1B
d... |
from pyramid.response import Response
import os
HERE = os.path.dirname(__file__)
def list_(request):
imported_text = open(os.path.join(HERE, 'templates/home.html')).read()
return Response(imported_text)
def my_view2(request):
imported_text = open(os.path.join(HERE, 'templates/sample2.html')).read()
... |
"""
Copyright, the CVXPY 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 applicable law or agreed to in writing, software
... |
import sys
import keras
import tensorflow as tf
from keras import backend
from keras import backend as K
from keras.models import Sequential
from keras.layers import Input, Conv3D, MaxPooling3D, Conv3DTranspose, BatchNormalization, GlobalAvgPool3D, GlobalMaxPooling3D
from keras.layers import concatenate, Reshape, Activ... |
#! /usr/bin/env python3
# script to append all the csv data files into 1
import csv
import os
import sys
import numpy as np
import pandas as pd
from sklearn.utils import shuffle
fileNames = []
dataPath = 'CleanedTrafficData' # use your path
for f in os.listdir(dataPath):
# print(f)
if f.endswith('_TrafficFor... |
import albow
from albow.dialogs import Dialog
from config import config
import pygame
from albow.translate import _, buildTemplate
import sys
import os
import logging
import traceback
import directories
old_lang = None
old_fprop = None
class OptionsPanel(Dialog):
anchor = 'wh'
def __init__(self, mcedit):
... |
from .parser import *
from .containers import *
|
#
# Copyright 2016 The BigDL 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 applicable law or agreed to in ... |
from napalm_base import get_network_driver
from pprint import pprint
from json import dumps
junos_driver = get_network_driver('junos')
device = junos_driver(hostname='172.30.179.107', username='pytraining', password='Poclab123', optional_args={'port': 830})
device.open()
print('-'*60)
pprint(device.get_interfaces())
... |
import os
import nester
import pickle
""" A test program to test exception"""
man = []
other = []
try:
data=open('/home/lgt/Program/pythonlearn/excep/sketch.txt')
for each_line in data:
try:
if not each_line.find(':')== -1:
(role,line_spoken) = each_line.split(':',1)
... |
from django.core.management.base import BaseCommand
from core.datatools.fail_repeat import FailRepeater
class Command(BaseCommand):
def handle(self, *args, **options):
try:
repeater = FailRepeater()
repeater.run()
except KeyboardInterrupt:
pass
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
__author__ = "pmeier82"
class DjSpikevalFrankeAppConfig(AppConfig):
label = "djspikeval_franke"
name = "djspikeval_franke"
verbose_name = _("Django Sp... |
import io
import os
import re
from setuptools import find_packages
from setuptools import setup
this_directory = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(this_directory, "README.md"), encoding="utf-8") as f:
long_description = f.read()
with open("requirements.txt", "r") as file:
requ... |
import fixtures
from oslo.config import cfg
from bricks.common import config
CONF = cfg.CONF
CONF.import_opt('use_ipv6', 'bricks.netconf')
CONF.import_opt('host', 'bricks.common.service')
class ConfFixture(fixtures.Fixture):
"""Fixture to manage global conf settings."""
def __init__(self, conf):
se... |
"""
Author: Joseph Min (kmin@caltech.edu)
This script validates the given csv file for correct formatting.
"""
|
# Generated by Django 3.0.5 on 2022-02-17 07:23
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('crawling', '0029_auto_20220216_1408'),
]
operations = [
migrations.AlterField(
model_name='fina... |
from __future__ import print_function
import os
import unittest
from dropbox import create_session
from fs.test import FSTestCases
import fs.subfs
from dropboxfs.dropboxfs import DropboxFS
def join(a, b):
return a + b
TEST_PATH = 'dropboxfs'
class TestDropboxFS(FSTestCases, unittest.TestCase):
def make_... |
# uncompyle6 version 3.2.4
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:30:26) [MSC v.1500 64 bit (AMD64)]
# Embedded file name: lib.coginvasion.minigame.CogGuardGlobals
from panda3d.core import *
GuardDialog = {'arrest': [
'Get your hands over your hea... |
from TestHelperSuperClass import testHelperSuperClass
class local_helpers(testHelperSuperClass):
pass
class test_kong_test_delete_service(local_helpers):
def test_noArgs(self):
cmdToExecute = "./scripts/kong_delete_service"
expectedOutput = ""
expectedOutput += "Start of ./scripts/kong_delete_servic... |
#Today it is all about control flow
print("Welcome to the rollercoaster!")
height = int(input("What is your height in cm? "))
if height > 120:
print("You can ride the rollercoaster!")
else:
print("Sorry, you can't ride the rollercoaster!") |
# coding: utf-8
"""
Functions for working with pitch data
This file depends on the praat script get_pitch_and_intensity.praat
(which depends on praat) to extract pitch and intensity values from
audio data. Once the data is extracted, there are functions for
data normalization and calculating various measures from the... |
"""
A collection of utility functions:
.. autosummary::
start_delayed
"""
from typing import Generator
from simpy.core import Environment, SimTime
from simpy.events import Event, Process, ProcessGenerator
def start_delayed(
env: Environment, generator: ProcessGenerator, delay: SimTime
) -> Process:
"""R... |
import numpy as np
import matplotlib.pyplot as plt
"""initialize the input vestor X and output vector Y"""
def get_data():
temp_x = []
temp_y = []
for i in range(1, 51):
x_i = i
temp_x.append(x_i)
temp_point = np.random.uniform(-1, 1, 1)
y_i = float(i + temp_point)
... |
# 导入 socket、sys 模块
import socket
import sys
import string
import numpy as np
import matplotlib.pyplot as plt
#bolin Zhao. bolin.zhao@ff.com
# 创建 socket 对象
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 获取本地主机名
#host = socket.gethostname()
host = '10.75.81.226'
# 设置端口好
port = 27015
# 连接服务,指定主机和端口
s.conn... |
import json
import os
import yaml
import argparse
import make
from collections import OrderedDict
from datetime import datetime
from shutil import copy as copy_file
'''
12/4/18
Suppressing writing term ref's in make.py
Preserving pre-existing term ref's in modify,
but suppressing functionality to add new term ref's in... |
from .manager import GeneralMomentAccountant, PrivacyManager # noqa: F401
|
import logging
from collections import defaultdict
from typing import Dict, List, Tuple, Union
import numpy
from openforcefield.topology import Molecule
from openforcefield.typing.engines.smirnoff import ForceField, ParameterHandler
from simtk import unit
from simtk.openmm import copy, openmm
from inspector.library.f... |
# --------------
# Importing header files
import numpy as np
import pandas as pd
from scipy.stats import mode
import warnings
warnings.filterwarnings('ignore')
#Reading file
bank_data = pd.read_csv(path)
#Code starts here
bank=pd.DataFrame(bank_data)
categorical_var=bank.select_dtypes(include='o... |
class Binary:
@classmethod
def decToBin(cls, dec):
if(dec == -128):
return '10000000'
b = ''
sign = '0'
if(dec < 0):
sign = '1'
dec = abs(dec)
for i in range(7):
b = str(dec % 2) + b
dec = dec // 2
b = s... |
#
# Copyright 2019 The FATE 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... |
# checking in dict
print("This script will check if monument is present in dictionary")
print("It will add if not present and exit if monument is found.")
dictionary = {
"Taj": "Agra",
"Qutub-Minar": "Delhi",
"Sun-Temple": "Puri"
}
print(f"This is the dictionary: {dictionary}")
name = inp... |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from tkdet.layers import Conv2d
from tkdet.layers import SEModule
from tkdet.layers import make_divisible
from .base import Backbone
from .build import BACKBONE_REGISTRY
__all__ = ["GhostNet", "ghostnet_1_0"]
class GhostModule(nn.Module... |
# 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... |
#import io
#import re
from __future__ import print_function
from setuptools import setup
import os, sys
import shutil
NAME = "odoo_downloader"
def get_version():
"""Get version and version_info without importing the entire module."""
print("NAME:", NAME)
path = os.path.join(os.path.dirname(_... |
import csv
# シンプルに配列を書き込む
with open('outFile.csv', mode='w', encoding='utf-8') as wf:
outdata = [
['Id', 'Name', 'Cost'],
['01', '白き鋼鉄のX', '3818'],
['02', 'Ori and the Blind Forest Definitive Edition', '1900']
]
writer = csv.writer(wf)
writer.writerows(outdata)
# 読み取り
with open... |
# Copyright © 2021, Oracle and/or its affiliates. All rights reserved.
from oci.core.models import DrgRouteDistributionStatement, DrgRouteRule, VirtualCircuitBandwidthShape
# extend VirtualCircuitBandwidthShape to add provider id
class ExtendedVirtualCircuitBandwidthShape(VirtualCircuitBandwidthShape):
_fastconn... |
from sanic import Sanic
from wadsworth.applications.redirect import attach_redirect_app
from wadsworth.blueprints.info.view import bp as info_view
from wadsworth.blueprints.view import bp
def create_app():
app = Sanic("MainApp")
app.config.SERVER_NAME = "localhost:8443"
app.blueprint(bp)
app.blueprin... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from copy import deepcopy, copy
import cython
TEMPORAL_IDX: cython.int = 0
ENC_IDX: cython.int = 1
@cython.cclass
class SDR(object):
# declare these class instance attributes with cython
#
encoding = cython.declare(dict, visibility='public')
encoders... |
# Generated by Django 3.1.3 on 2020-11-17 19:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('attendance', '0014_auto_20201117_1453'),
]
operations = [
migrations.AlterField(
model_name='case',
name='attorney',... |
#!coding:utf8
#author:yqq
#date:2020/5/8 0008 15:15
#description: 测试用例
import json
import string
import time
import unittest
import requests
from ed25519 import SigningKey
from src.api.handlers.handler_base import sign_msg, verify_sig
class TestWalletAPI(unittest.TestCase):
@classmethod
d... |
import pytest
import os
import itertools
from unittest.mock import patch, MagicMock, call
from test_utils.test_utils import AsyncContextManagerMock, coroutine_of
from boto3.dynamodb.conditions import Key
from decimal import Decimal
TEST_ENV = {
"REGION": "eu-west-wood",
"STAGE": "door",
"APP_NAME": "me-onc... |
from extra import strToBool
class Machine(object):
"""
Provides the implementation of a Machine in a Plant.
"""
def __init__(self, name, quantity = 1, canUnhook = False,
precedence = False, breaks = []):
"""
name is the unique Machine name.
precedence is whether the quantity should be dealt with as capaci... |
from ode4jax._src.ODEBase.algorithms import (
Euler,
Midpoint,
Heun,
RK4,
RK12,
RK23,
RK4Fehlberg,
RK45,
)
|
get_all_user_in_pay = "SELECT * FROM tbl_user;"
get_all_user_in_dms = "SELECT * FROM student;"
find_user_by_uuid_in_pay = "SELECT * FROM tbl_user WHERE 'user_uuid' = %s"
insert_user = "INSERT INTO tbl_user(user_number, coin, user_name, user_uuid) VALUE (%s, %s, %s, %s)"
insert_teacher = "INSERT INTO tbl_teacher(id,... |
#Standard library modules
import glob
import sys
import os
import logging
from fnmatch import fnmatch
import configparser
#Third Party imports
from music21 import *
import numpy as np
import torch
from sklearn import preprocessing
import pandas as pd
#Local Modules
from .midi_class_mapping import MidiClassMapping
fr... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" typing.py
"""
import datetime
import json
import os
import random
CHAR_COUNT = 6
TRIAL_COUNT = 5
CHARSET = (
' !"#$%&'
+ "'"
+ "()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
)
HISTORY_FILE = os.path.dirname(os.... |
# coding=utf-8
# This file is part of Rubber and thus covered by the GPL
# (c) Emmanuel Beffara, 2002--2006
# Modified by Olivier Verdier <olivier.verdier@gmail.com>
# LICENSE
# Copyright © 2010–2013, Olivier Verdier
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modifi... |
"""DNA, by Al Sweigart al@inventwithpython.com
A simple animation of a DNA double-helix. Press Ctrl-C to stop.
Thanks to matoken for inspiration: https://asciinema.org/a/155441"""
__version__ = 1
import random, sys, time
# Setup the constants:
# These are the individual rows of the DNA animation:
ROWS = [
' ... |
# -*- coding: utf-8 -*-
'''
Plot Information Data
=====================
'''
from __future__ import annotations
__all__ = ('PlotInfo',)
from builder.utils import assertion
class PlotInfo(object):
''' Plot Info Data class.
'''
def __init__(self, title: str, *args):
self._title = assertion.is_str... |
from .stream import DerivedStream
class Augmentstream(DerivedStream):
def __init__(self, aug_dimensions, field, affect_flags=(DATAFLAG_TRAIN,)):
DerivedStream.__init__(self, [field])
self.field = self.inputs[0]
self.affect_flags = affect_flags
self.aug_dimensions = range(aug_dimen... |
#
# Copyright (c) 2019 by Delphix. All rights reserved.
#
# -*- coding: utf-8 -*-
"""UpgradeOperations for the Virtualization Platform
There are 5 different objects that we can upgrade. All migration ids must be
unique. To upgrade a specific schema, the plugin author would use that specific
decorator specifying the m... |
#32 - Top Scores.py
# You rank players in the game from highest to lowest score. So far you're using an algorithm that sorts in O(n\lg{n})O(nlgn) time, but players are complaining that their rankings aren't updated fast enough. You need a faster sorting algorithm.
# Write a function that takes:
# a list of unsorted_... |
# Under MIT License, see LICENSE.txt
from PyQt5.QtGui import QPixmap
from PyQt5.QtGui import QPainter
from PyQt5.QtGui import QImage
from PyQt5.QtGui import QColor
from PyQt5.QtGui import QTransform
from PyQt5.QtCore import QThread
from PyQt5.QtCore import QRect
from Controller.DrawingObject.BaseDrawingObject import ... |
load(
"@io_bazel_rules_dotnet//dotnet/private:common.bzl",
"paths",
)
def _vs2017_ref_net_impl(ctx):
prefix = "vs"
for vs_type in ["Community", "Professional", "Enterprise"]:
vs_ref_path = paths.join("C:/Program Files (x86)/Microsoft Visual Studio/2017",
vs_type, "Common7/IDE/Refer... |
# A class for performing hidden markov models
import copy
import numpy as np
class HMM():
def __init__(self, transmission_prob, emission_prob, obs=None):
'''
Note that this implementation assumes that n, m, and T are small
enough not to require underflow mitigation.
Required Inpu... |
#! /usr/bin/python
# -*- coding: utf-8 -*-
__author__ = "Osman Baskaya"
"""
"""
import sys
import os
import task3_utils
from fastsubs_utils import read_sub_vectors
sub_file = sys.argv[1]
test_f = sys.stdin
if len(sys.argv) == 3:
test_f = sys.argv[2]
sentences = task3_utils.get_sentences(test_f)
wordset = task3... |
import jane
jane.janefunc()
|
import os, sys
import tempfile
from Bio import SeqIO
import shutil
import networkx as nx
import argparse
import textwrap
import ast
from .isvalid import *
from .set_default_args import set_default_args
from .prokka import process_prokka_input
from .cdhit import check_cdhit_version
from .cdhit import run_cdhit
from .ge... |
letters = ["a", "b", "c"]
print(letters.index("a"))
if "d" in letters:
print(letters.index("d"))
if "c" in letters:
print(letters.index("c"))
print(letters.count("a"))
print(letters.count("d"))
|
"""Features control."""
from grow.common import base_config
class Features(object):
"""Control features."""
def __call__(self, feature):
"""Ability to call the instance to shortcut to test enabled features."""
return self.is_enabled(feature)
def __init__(self, enabled=None, disabled=None... |
from functools import wraps
from warnings import warn
def add_warning(func, oldname):
@wraps(func)
def _wrapped(*args, **kwds):
warn('Deprecated function %s being called' % oldname)
return func(*args, **kwds)
return _wrapped
def test(a=2, b=4):
print(a + b)
old_test = add_warning(test... |
#
# @lc app=leetcode id=236 lang=python
#
# [236] Lowest Common Ancestor of a Binary Tree
#
# https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/description/
#
# algorithms
# Medium (43.56%)
# Total Accepted: 434K
# Total Submissions: 986.2K
# Testcase Example: '[3,5,1,6,2,0,8,null,null,7,4]\n5\n... |
from abc import ABC, abstractmethod
import torch
class Algorithm(ABC):
"""Base class for all algorithms"""
@classmethod
@abstractmethod
def create_factory(cls):
"""Returns a function to create new Algo instances"""
raise NotImplementedError
@property
@abstractmethod
def g... |
import unittest
from mock import patch
from pathlib import Path
from PyQt5.QtCore import QSettings
from PyQt5.QtWidgets import QFileDialog
from .gui_test import GUITest
from inselect.gui.user_template_choice import user_template_choice
from inselect.tests.utils import temp_directory_with_files
TESTDATA = Path(__fi... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
__all__ = [
'make_server_socket',
'make_ssl_context',
]
import socket
import ssl
from g1.asyncs.bases import adapters
def make_server_socket(
address,
*,
family=socket.AF_INET,
backlog=128,
reuse_address=False,
reuse_port=False,
ssl_context=None,
):
sock = socket.socket(famil... |
# coding: utf-8
"""
ExaVault API
See our API reference documentation at https://www.exavault.com/developer/api-docs/ # noqa: E501
OpenAPI spec version: 2.0
Contact: support@exavault.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
i... |
import logging
import os
import tempfile
from typing import Any, Dict
from allennlp.training.trainer import EpochCallback, GradientDescentTrainer
import mlflow
from xallennlp.utils import flatten_dict_for_mlflow_log, str_to_timedelta
logger = logging.getLogger(__name__)
@EpochCallback.register("mlflow_metrics")
cl... |
from httpx.client import Dispatcher
from httpx import Request, Response
from httpx.config import CertTypes, TimeoutTypes, VerifyTypes
from httpx.status_codes import codes
from tests import get_fixture_abspath
class MockDispatch(Dispatcher):
"""Network dispatcher for httpx that returns the given fixture file cont... |
from scipy.cluster.hierarchy import linkage, dendrogram
from scipy.spatial.distance import pdist, squareform
from scipy.misc import toimage
import numpy as np
from glymur import Jp2k
import StringIO
def hide_this(xxx):
qstrings = '''FGIJJJKFLLGLGPKMFMMILMHMMKIKIKMJKLLKLMHIIDKNHLIKKOLJLNELNLLFKKKKIM8FKLNJJ?KLJIKIKL... |
#!/usr/bin/env python
# encoding: utf-8
"""
Loupe.py
Created by Rui Carmo on 2007-01-11.
Published under the MIT license.
"""
import yaki.Engine, yaki.Store
from yaki.Utils import *
from BeautifulSoup import *
import re, urlparse
template = """
<div id="loupe%(serial)d" style="width:%(width)spx; height:%(height)spx;... |
from datetime import datetime
from typing import Optional
from fastapi import APIRouter
from sqlmodel import Field, SQLModel
router = APIRouter()
class Right(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Province(SQLModel, table=True):
id: Optional[in... |
#!/usr/bin/env python3
import os
import sys
import time
import json
import re
import hashlib
import subprocess
import yaml
import git
from termcolor import colored
class WebAppUpdateChecker():
def __init__(self, rootdir):
self._apps = []
self._testdir = os.path.join(rootdir, "test")
self._... |
from project_example.settings import * # pylint: disable=W0614,W0401
DEBUG = False
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
ROOT_URLCONF = 'project_example.conf.test.urls'
INSTALLED_APPS += (
'django.contrib.admin'... |
# -*- coding: utf-8 -*-
"""Test the data module."""
from adnipy import data
def test_image_id_from_filename():
"""Test extracting image id from filename."""
correct = 123456789
filename = "_I123456789.nii"
image_id = data.image_id_from_filename(filename)
assert correct == image_id
|
# importing anything from analysis segfaults java with netlogo on a mac
# for now no clue why
#
from . import pairs_plotting
from .b_and_w_plotting import set_fig_to_bw
from .cart import setup_cart, CART
from .feature_scoring import (get_ex_feature_scores, get_feature_scores_all,
get_rf_f... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module computes the neutral and ionized populations of H in the
upper atmosphere.
"""
from __future__ import (division, print_function, absolute_import,
unicode_literals)
import numpy as np
import astropy.units as u
import astropy.constant... |
# Standard Library
import os
import re
import sys
# Functions for outputting message to stderr
def warning_message(message, newLine=True):
'''Output a warning message to stderr.'''
sys.stderr.write('WARNING: ' + message)
if newLine:
sys.stderr.write('\n')
def information_message(message, newLi... |
from abc import ABCMeta, abstractmethod # Only Python 2.6 and above
"""
Defining an abstract class which the controller
modules will implement, forcing them to override
all the abstract methods
"""
class ControllerModule(object):
__metaclass__ = ABCMeta
def __init__(self):
self.pendingCBT = {}
... |
"""This pkg aims to implement serveral filtering methods for (un)directed
graphs.
Edge filtering methods allows to extract the backbone of a graph or sampling the
most important edges. You can use edge filtering methods as a preprocessing step
aiming to improve the performance/results of graph algorithms or to turn a ... |
# V0
class Solution:
# @param s, a string
# @return an integer
def numDecodings(self, s):
if s=="" or s[0]=='0': return 0
dp=[1,1]
for i in range(2,len(s)+1):
if 10 <=int(s[i-2:i]) <=26 and s[i-1]!='0':
dp.append(dp[i-1]+dp[i-2])
elif int(s[i-2... |
#Number Guessing Game Objectives:
# Include an ASCII art logo.
# Allow the player to submit a guess for a number between 1 and 100.
# Check user's guess against actual answer. Print "Too high." or "Too low." depending on the user's answer.
# If they got the answer correct, show the actual answer to the player.
# Trac... |
class StopAt:
""" Represents the Stop At CLI parameter """
def check(self, context):
""" Return if this CLI should be used """
return context.config.stopAt is not None
def build(self, context):
""" Return the string parameters to add to the command string """
... |
from Gaudi.Configuration import *
from Configurables import k4DataSvc, TestE4H2L, EDM4hep2LcioTool, Lcio2EDM4hepTool
algList = []
END_TAG = "END_TAG"
evtsvc = k4DataSvc('EventDataSvc')
# EDM4hep2lcio Tool
edmConvTool = EDM4hep2LcioTool("EDM4hep2lcio")
edmConvTool.Parameters = [
"E4H_CaloHitCollection", "LCIO_C... |
import numpy as np
from flask import Flask, request, jsonify, render_template
import pickle
app = Flask(__name__)
model = pickle.load(open('ipl_predictor.pkl', 'rb'))
@app.route('/')
def home():
return render_template('index.html')
@app.route('/predict', methods=['POST'])
def predict():
'''
For renderi... |
abc=1,2,3,4 #by default it is taken as tuple
print(type(abc))
print(abc)
tupl1=('a','xyz',10.90)
print(tupl1)
tup=()
print(tup)
mtup=(1,)
print(mtup)
mtup1=(1,2,3,4,"abc")
mtup2=mtup1 # copying of tuples
print(mtup2)
print(mtup2[0]) #print the first element
print(mtup2[-1]) #print the last element
print(mtu... |
from pprint import pformat
import logging
import os
def configure_root_logger():
"""
i prefer to use this instead of logging.basicConfig because this is more flexiable
e.g. in term of controlling encoding of the log file
"""
module_name=None # root
log_level = logging.DEBUG # default of... |
# Lesson3: List is mutable
# source: code/list_is_mutable.py
original_list = list(range(1, 6))
print(original_list)
new_list = original_list
new_list[2] = 128
print(original_list)
print(new_list) |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import sys
sys.path.append('..')
import numpy as np
from tk.TKGame import TKGame
from tk.keras.NNet import NNetWrapper as NNet
from tk.test.testTKLogick import generate_encoded_state
class TestNNet(unittest.TestCase): #TODO: rename to testTKLogick
def ... |
# Generated by Django 4.0.3 on 2022-03-22 15:09
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('bank_account', '0005_bankaccount_created_at'),
]
operations = [
migrations.AddField(
model_name... |
from scrapli.driver import GenericDriver
from scrapli.driver.core import IOSXEDriver
from scrapli.response import Response
from nornir_scrapli.exceptions import NornirScrapliNoConfigModeGenericDriver
def test_send_configs(nornir, monkeypatch):
from nornir_scrapli.tasks import send_configs
def mock_open(cls)... |
import numpy as np
import pdb
def trim(w, wvs):
if w not in wvs:
if w[:-1] in wvs: return w[:-1]
elif w.replace('-','') in wvs: return w.replace('-','')
elif w[:-4] + 'lize' in wvs: return w[:-4] + 'lize'
return w
def file_len(fname):
with open(fname) as f:
for i, l in enum... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.