text stringlengths 1 927k |
|---|
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
import pytest
import jax.numpy as jnp
from jaxga.mv import MultiVector
from jaxga.signatures import positive_signature
def _jaxga_mul(a, b):
return a * b
def _mv_ones(num_elements, num_bases):
return MultiVector(
values=jnp.ones([num_bases, num_el... |
import sys
import numpy as np
rawalgo, rawimg = sys.stdin.read().strip().split('\n\n')
algo = np.array([1 if c == '#' else 0 for c in rawalgo], dtype=np.int8)
img = np.array([[1 if c == '#' else 0 for c in line] for line in rawimg.split('\n')], dtype=np.int8)
def enhance(img, algo):
img = np.pad(img, 2, 'edge')
... |
# Copyright 2015: Hewlett-Packard Development Company, L.P.
# 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-... |
import mysql.connector
import pandas as pd
mydb = mysql.connector.connect(
host="135.148.9.103",
user="admin",
password="rod@2021",
database="rod_input",
)
mycursor1 = mydb.cursor()
mycursor1.execute("TRUNCATE TABLE `data_input_test`")
mydb.commit()
print("Bien") |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
from teimedlib.textentities import TextEntities
from teimedlib.textentities_log import *
from teimedlib.ualog import Log
def do_main(path_src,path_tags):
path_err=path_src.replace(".txt","_words.ERR.log")
log_err=Log("w").open(path_err,1).log
te = T... |
# Necessary imports. Provides library functions to ease writing tests.
from lib import prebuild, testcase, SUBMITTY_TUTORIAL_DIR
import subprocess
import os
import glob
############################################################################
# COPY THE ASSIGNMENT FROM THE SAMPLE ASSIGNMENTS DIRECTORIES
SAMPLE_AS... |
from typing import Any, Type, Union, List
import torch
import torch.nn as nn
from torch import Tensor
from torch.quantization import fuse_modules
from torchvision.models.resnet import Bottleneck, BasicBlock, ResNet, model_urls
from ..._internally_replaced_utils import load_state_dict_from_url
from .utils import _repl... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 6 18:03:09 2020
@author: Jonathan A. Yepez M.
"""
#Task Description
"""
En el archivo auto.csv se encuentran los siguientes datos de diferentes automoviles:
* Cilindros
* Cilindrada
* Potencia
* Peso
* Aceleracion
* Año del coche
* Origen
... |
from django.contrib import admin
from ballots.models import Poll, Category, CategoryItem, Ballot, Vote, Answer, AnswerItem
# class ItemInline(admin.TabularInline):
# model = CategoryItem
#
#
# class CategoryAdmin(admin.ModelAdmin):
# inlines = [ItemInline,
# ]
class CategoryInline(admin.Tabul... |
"""The tests for numeric state automation."""
from datetime import timedelta
import unittest
from unittest.mock import patch
import homeassistant.components.automation as automation
from homeassistant.core import Context, callback
from homeassistant.setup import setup_component
import homeassistant.util.dt as dt_util
... |
# Generated by Django 3.2.10 on 2022-03-30 10:18
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import materials.models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0012_alte... |
# Generated manually on 2022-01-24 17:40
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('deployments', '0042_personnel_country_to'),
]
operations = [
migrations.RunSQL(
sql=[("update deployme... |
import math
import numpy
from PIL import Image
from the_ark.selenium_helpers import SeleniumHelperExceptions, ElementNotVisibleError, ElementError
from StringIO import StringIO
import time
import traceback
DEFAULT_SCROLL_PADDING = 100
SCREENSHOT_FILE_EXTENSION = "png"
DEFAULT_PIXEL_MATCH_OFFSET = 100
FIREFOX_HEAD_HEIG... |
from __future__ import division
def get_x_distribution_series(x_values, probabilites):
distr_series = {}
for i, x in enumerate(x_values):
prob_sum = 0
for prob in probabilites[i]:
prob_sum += prob
distr_series[x] = prob_sum
return distr_series
def get_x_distribution_f... |
from openprocurement.agreement.core.adapters.configurator import BaseAgreementConfigurator
class CFAgreementUAConfigurator(BaseAgreementConfigurator):
name = "CFA configurator"
model = None # TODO: |
ano = int(input('Digite o ano do seu nascimento: '))
idade = 2020-ano
if idade <= 10:
print('Mirim')
elif idade <= 15:
print('Infantil')
elif idade <= 19:
print('Junior')
elif idade <= 20:
print('Sênior')
else:
print('Master')
print(idade) |
"""Snake Game Python Tutorial
youtube video: https://www.youtube.com/watch?v=CD4qAhfFuLo
current time: 33:00
"""
import sys
import math
import random
import pygame
from pygame.locals import *
import tkinter as tk
from tkinter import messagebox
WHITE = (255,255,255)
BLACK = (0,0,0)
RED = (255,0,0)
GREEN = (0,255,0)
BLU... |
#!/usr/bin/env python
import logging
import sys
import traceback
import katcp
import readline
import codecs
import re
from optparse import OptionParser
from cmd2 import Cmd
from katcp import DeviceClient
logging.basicConfig(level=logging.INFO,
stream=sys.stderr,
format="%(asctim... |
"""opentamilweb URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Cla... |
# Generated by Django 2.2.2 on 2019-06-24 14:07
import django.contrib.gis.db.models.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('main', '0004_auto_20190624_1355'),
]
operations = [
migrations.AlterField(
model_name='photo'... |
"""Script to train the Hamiltonian Generative Network
"""
import ast
import argparse
import copy
import pprint
import os
import warnings
import yaml
import numpy as np
import torch
import tqdm
from utilities.integrator import Integrator
from utilities.training_logger import TrainingLogger
from utilities import loader... |
# Copyright (C) 2019-2020, Therapixel SA.
# All rights reserved.
# This file is subject to the terms and conditions described in the
# LICENSE file distributed in this package.
"""Test the C-Find message are correctly sent
and can provide useful results.
"""
import os
from datetime import datetime, timedelta
from path... |
import yaml
import os
import shutil
import re
import toml
from typing import List, Set, Tuple, Pattern, Match
from urllib.parse import urlparse
from pathlib import Path
CHECKOUT_DIR = "checkouts"
GIT_CLONE_CMD = "git clone {{}} ./{}/{{}}/{{}}".format(CHECKOUT_DIR)
RE_EXTRACT_TITLE: Pattern[str] = re.compile("([#\s]*)(... |
from __future__ import unicode_literals
import io
import itertools
import os
import subprocess
import time
import re
import json
from .common import AudioConversionError, PostProcessor
from ..compat import compat_str
from ..utils import (
dfxp2srt,
encodeArgument,
encodeFilename,
float_or_none,
_... |
'''
Function:
setup
Author:
Charles
微信公众号:
Charles的皮卡丘
GitHub:
https://github.com/CharlesPikachu
更新日期:
2020-02-20
'''
import DecryptLogin
from setuptools import setup, find_packages
'''readme'''
with open('README.md', 'r', encoding='utf-8') as f:
long_description = f.read()
'''setup'''
setup(
name='DecryptLo... |
# Copyright (c) 2021 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 required by appli... |
#!/usr/bin/env python
'''
Input: An array of integers.
Output: The single integer that occurs most often.
'''
from __future__ import print_function
from collections import Counter
given_array = [2,2,3,7,5,7,7,7,4,7,2,7,4,5,6,7,7,8,6,7,7,8,10,12,29,30,19,10,7,7,7,7,7,7,7,7,7]
def find_major(array):
co... |
"""Demo unanimous voting: multiparty matching without embarrassments.
Unanimous voting between parties P[0],...,P[t] is implemented by securely
evaluating the product of their votes (using 1s and 0s to encode "yes"
and "no" votes, respectively) and revealing only whether the product
equals 1 (unanimous agreement) or 0... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
@file:pip_util.py
@des:下载|安装 对应(win或any)pip版本的安装包
# pip 命令说明
# https://pip.pypa.io/en/stable/user_guide/
# pip uninstall SomePackage 卸载包
# pip search SomePackage 卸载包
# pip uninstall SomePackage 卸载包
# pip show ... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""Centralized catalog of paths."""
import os
class DatasetCatalog(object):
DATA_DIR = "datasets"
DATASETS = {
"coco_test-dev": (
"coco/test2017",
"coco/annotations/image_info_test-dev2017.json",
... |
# Copyright 2022 Paul Rogers
#
# 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, ... |
from setuptools import setup
# "import" __version__
__version__ = 'unknown'
for line in open('src/splines/__init__.py'):
if line.startswith('__version__'):
exec(line)
break
setup(
name='splines',
packages=['splines'],
package_dir={'': 'src'},
version=__version__,
author='Matthi... |
from dataclasses import dataclass
from typing import List
import click
import desert
import marshmallow
import requests
API_URL = "https://www.biobiochile.cl/lista/api/get-todo?limit={limit}"
@dataclass
class New:
post_hour: str
post_title: str
post_content: str
schema = desert.schema(New, meta={"unkn... |
import numpy as np
import xarray as xr
from .. import time as tmlib
import warnings
from os.path import getsize
from ._read_bin import bin_reader
from .base import _find_userdata, _create_dataset, _abspath
from ..rotate.rdi import _calc_beam_orientmat, _calc_orientmat
from ..rotate.base import _set_coords
from ..rotate... |
import django_filters
import netaddr
from django.core.exceptions import ValidationError
from django.db.models import Q
from netaddr.core import AddrFormatError
from dcim.models import Site, Device, Interface
from extras.filters import CustomFieldFilterSet
from tenancy.models import Tenant
from utilities.filters import... |
# 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 ... |
__author__ = 'frederico'
from tabuleiro import tabuleiro
# Type of ship | Size | Legenda
# Aircraft carrier 5 ac
# Battleship 4 b
# Submarine 3 s
# Destroyer (or Cruiser) 3 d
# Patrol boat (or destroyer) 2 pb
barcos = {'ac':... |
import torch
import random
import collections
import networkx as nx
from rdkit.Chem import AllChem
import numpy as np
from loader import graph_data_obj_to_nx_simple, nx_to_graph_data_obj_simple
from loader import MoleculeDataset
def get_filtered_fingerprint(smiles):
""" Get filtered PubChem fingerprint. The di... |
from __future__ import absolute_import
import posixpath
from rest_framework import serializers
from rest_framework.exceptions import PermissionDenied
from rest_framework.response import Response
from sentry.api.base import DocSection
from sentry.api.bases.organization import OrganizationReleasesBaseEndpoint
from sent... |
import pytest
from stone_burner.config import parse_project_config
from stone_burner.config import TFAttributes
from stone_burner.config import get_component_paths
from .utils import SAMPLE_CONFIG
def test_parse_project_config_1():
e = {
'c1': {'component_type': 'c1', 'validate': {}},
'c2': {'co... |
import os,sys,inspect
current_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parent_dir = os.path.dirname(current_dir)
sys.path.insert(0, parent_dir)
import sum
def test_sum():
assert sum.sum(3, 4) == 7 |
# -*- coding: utf-8 -*-
#
# Copyright @ 0x6c78.
#
# 16-10-20 下午1:27 0x6c78@gmail.com
#
# Distributed under terms of the MIT License
from operator import mul
from itertools import combinations
class Score(object):
def __init__(self):
"""
张峰实验室通过实验获得的每个位置错配的特异性,具体参考网页:
http://crispr.mit.edu/... |
def cast_kwargs(kwargs):
kwargs_copy = kwargs.copy()
for arg, value in kwargs_copy.items():
if isinstance(value, dict):
kwargs_copy[arg] = cast_kwargs(value)
else:
kwargs_copy[arg] = cast_string(kwargs_copy[arg])
return kwargs_copy
def cast_string(s):
if s == "T... |
from .analysis import *
from .plot import *
from .generate import *
from .utils import *
__author__ = 'Konstantinos Kavvadias'
__license__ = 'BSD-3-Clause'
__version__ = "0.1.dev11" |
# 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 may ... |
from pathlib import Path
from fhir.resources.valueset import ValueSet as _ValueSet
from oops_fhir.utils import ValueSet
from oops_fhir.r4.code_system.structure_map_group_type_mode import (
StructureMapGroupTypeMode as StructureMapGroupTypeMode_,
)
__all__ = ["StructureMapGroupTypeMode"]
_resource = _ValueSet... |
from django.contrib import admin
from .models import SensorNode
from .models import SensorData
admin.site.register(SensorNode)
admin.site.register(SensorData) |
"""
This file is part of web2py Web Framework (Copyrighted, 2007-2009).
Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>.
License: GPL v2
"""
import datetime
from storage import Storage
from html import *
import contrib.simplejson as simplejson
import contrib.rss2 as rss2
def xml_rec(value, key):
if isins... |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
# 介于二者之间
if p.val <= root.val <= q.val or q.val <= root.val <= p.val:
... |
import tensorflow as tf
from baselines.ppo2 import ppo2
from baselines.common.models import build_impala_cnn
from baselines.common.mpi_util import setup_mpi_gpus
from procgen import ProcgenEnv
from baselines.common.vec_env import (
VecExtractDictObs,
VecMonitor,
VecFrameStack,
VecNormalize
)
from baseli... |
from random import randint
from time import sleep
lista = list()
jogos = list()
print('-' * 30)
print('{:^30}'.format('JOGA NA MEGA SENA'))
print('-' * 30)
quant = int(input('Quantos jogos você quer que eu sorteie? '))
tot = 1
while tot <= quant:
cont = 0
while True:
num = randint(1, 60)
if num ... |
"""
WSGI config for ChamberOfSecret project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJAN... |
from __future__ import print_function
import os
from importlib import import_module, reload
from pathlib import Path
from _pytest.pytester import Testdir
from nbformat import read
from pytest import ExitCode
from .helper import failing_nb, passing_nb, write_nb
pytest_plugins = "pytester"
NB_VERSION = 4
def test_i... |
"""
This is the Orchestra Project Python API.
TODO(marcua): Move this file to its own pip/github project.
"""
import json
import logging
from datetime import datetime
from time import mktime
from wsgiref.handlers import format_date_time
import requests
from django.conf import settings
from httpsig.requests_auth impo... |
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import boto3
import os, logging, json
from botocore.retries import bucket
#from pkg_resources import Version
from crhelper import CfnResource
from botocore.exceptions import ClientError
# declare helper an... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 3 17:03:45 2021
@author: shangfr
"""
import joblib
import operator
from functools import reduce
from whoosh.index import open_dir
from whoosh.qparser import QueryParser
import pkg_resources
INDEX_DIR = pkg_resources.resource_filename('cnsyn', 'query')
ix = open_dir(INDE... |
# Copyright 2018 Open Source Robotics Foundation, 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
"""Support for aggregation-based AMG."""
from __future__ import absolute_import
from warnings import warn
import numpy as np
from scipy.sparse import csr_matrix, isspmatrix_csr, isspmatrix_bsr,\
SparseEfficiencyWarning
from pyamg.multilevel import multilevel_solver
from pyamg.relaxation.smoothing import change_s... |
#!/usr/bin/env python3
# Copyright (c) 2014-2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test RPCs related to blockchainstate.
Test the following RPCs:
- getblockchaininfo
- gettxouts... |
import os
import sys
import ctypes
from os import listdir, path
from os.path import isfile
from PyQt4.QtGui import *
from PyQt4.QtCore import *
# Before using arnold!
# I have to load dll manually
# Problem using dlls
s_path = "C:/solidangle/arnold/Arnold-5.2.2.0-windows/bin"
if os.access(s_path, os.F_OK):
dlls... |
"""Classify changes in Ansible code."""
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import collections
import os
import re
import time
from . import types as t
from .target import (
walk_module_targets,
walk_integration_targets,
walk_units_targets,
walk_com... |
# -*- coding:utf-8 -*-
import re
import os
import time
import json
import sys
import subprocess
import requests
import hashlib
from bs4 import BeautifulSoup
"""
info:
author:CriseLYJ
github:https://github.com/CriseLYJ/
update_time:2019-3-6
"""
class Lagou_login(object):
def __init__(self):
self.session ... |
#! /usr/bin/python3
# Define the class DVD
class DVD:
def __init__(self, title, studio, director, released):
self.__title = title
self.__studio = studio
self.__director = director
self.__released = released
def get_title(self):
return self.__title
def get_studio(se... |
from scrapy.exceptions import DropItem
class PricePipeline(object):
vat_factor = 1.15
def process_item(self, item, spider):
if item.get('price'):
if item.get('price_excludes_vat'):
item['price'] = item['price'] * self.vat_factor
return item
else:
... |
# coding: utf-8
import pprint
import re
import six
class UpdateHealthMonitorOption:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and th... |
"""empty message
Revision ID: d4c798575877
Revises: 1daa601d3ae5
Create Date: 2018-05-09 10:28:22.931442
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'd4c798575877'
down_revision = '1daa601d3ae5'
branch_labels = None
depends_on = None
def upgrade():
op... |
from django.apps import AppConfig
class ShortnsweetConfig(AppConfig):
name = 'shortnsweet' |
# -*- coding: utf-8 -*-
import sys, os
from chainer import cuda, optimizers, gradient_check, Variable
sys.path.append(os.path.split(os.getcwd())[0])
from ddqn import *
from config import config
# Override config
config.ale_actions = [4, 3, 1, 0]
config.ale_screen_size = [210, 160]
config.ale_scaled_screen_size = [84, ... |
"""
Collectors have two main functions: synthesizing (or collecting) samples and compute metric matrix (which will be passed to selectors and losses).
All methods are listed below:
+-----------------------+-------------------------------------------------------------------------------+
| method | desc... |
# coding: utf-8
#########################################################################
# 网站: <a href="http://www.crazyit.org">疯狂Java联盟</a> #
# author yeeku.H.lee kongyeeku@163.com #
# #
# version 1.0 ... |
import FWCore.ParameterSet.Config as cms
nEvtLumi = 4
nEvtRun = 2*nEvtLumi
nRuns = 64
nStreams = 4
nEvt = nRuns*nEvtRun
process = cms.Process("TESTGLOBALMODULES")
import FWCore.Framework.test.cmsExceptionsFatalOption_cff
process.options = cms.untracked.PSet(
numberOfStreams = cms.untracked.uint32(nStreams),
... |
#!/usr/bin/env python3
import cv2
import time
import os
from server.startracker.catalog import Catalog
from server.startracker.image import ImageUtils
assets_dir = "/home/igarcia/Nextcloud/University/TFG/reports/assets"
catalogs_path = "./server/startracker/catalogs/out"
catalog = Catalog(f"{catalogs_path}/hip_2000.cs... |
#!/usr/bin/env python
#
# Electrum - lightweight STRAKS client
# Copyright (C) 2013 ecdsa@github
#
# 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 lim... |
"""
Módulo para recuperação de dados climáticos do PCBr.
A documentação do Projeto pode ser encontrada no Portal
http://pclima.inpe.br/
As escolhas para o download de dados são definidas através
de um JSON que pode ser gerado utilizando do Portal API.
http://pclima.inpe.br/anali... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.FileItem import FileItem
from alipay.aop.api.constant.ParamConstants import *
class AnttechBlockchainQueryconditionQueryRequest(object):
def __init__(self, biz_model=None):
self._biz_model = biz_model
self._version =... |
"""
Article object definitions
"""
from collections import OrderedDict
from elifearticle import utils
class BaseObject:
"base object for shared functions"
def __str__(self):
"""
Return `str` representation of the simple object properties,
if there is a list or dict just return an emp... |
# tests.test_testing
import io
from unittest import TestCase
from unittest import mock
from bdemeta.testing import trim, run_one, RunResult, run_tests, MockRunner
def gen_value(length):
result = ''
for i in range(length):
result += chr(ord('A') + (i % 26))
return result
class TestMockRunner(Test... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import tinymce.models
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Goods',
fields=[
('id', m... |
#!/usr/bin/env python
from __future__ import division, absolute_import, print_function
import numpy as np
from scipy.stats import t
"""
Defines common error measures.
Definition
----------
def bias(y_obs,y_mod): bias
def mae(y_obs,y_mod): mean absolute error
def mse(y_obs,y_mod... |
# -*- coding: utf-8 -*-
"""Finitely Presented Groups and its algorithms. """
from __future__ import print_function, division
from sympy.core.basic import Basic
from sympy.core import Symbol, Mod
from sympy.printing.defaults import DefaultPrinting
from sympy.utilities import public
from sympy.utilities.iterables import... |
"""Example serializing custom types"""
from datetime import datetime
from event_two import event
import json
# Serializar
def default(obj):
"""Encode datetime to string in YYYY-MM-DDTHH:MM:SS format (RFC3339)"""
if isinstance(obj, datetime):
return obj.isoformat()
return obj
def pairs_hook(pairs... |
from utils import stringifySong
from datetime import datetime
import logging
logger = logging.getLogger(__name__)
class Migrater(object):
"""Migrater"""
def __init__(self, migrateFrom, migrateTo, mock=False):
# Store clients
self.source = migrateFrom
self.target = migrateTo
se... |
"""
The MIT License (MIT)
Copyright (c) 2015-present Rapptz
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, modify, merg... |
from flask_ember.util.string import dasherize
class ResourceGenerator:
def __init__(self, ember, resource_class):
self.ember = ember
self.resource_class = resource_class
def generate(self, app):
# TODO generation of api endpoints etc
resource = self.resource_class
nam... |
SECURITY_CONFIG_ACTIONS = [
'DeleteAccountPublicAccessBlock',
'DeleteDeliveryChannel',
'DeleteDetector',
'DeleteFlowLogs',
'DeleteRule',
'DeleteTrail',
'DisableEbsEncryptionByDefault',
'DisableRule',
'StopConfigurationRecorder',
'StopLogging',
]
def rule(event):
if event['e... |
from GLOBAL_VARIABLES import PLAYER_NAME
import copy
def opponents(parent_folder_ts: str, ts_filename: str) -> list:
"""
Extracts the names of the players in a tournament
Parameters:
parent_folder_ts (str): the parent folder where the tournament summary file is located
... |
from keras import backend as K
from keras.models import *
from keras.layers import *
import os
from datetime import datetime
import tensorflow as tf
import numpy as np
class AgedModel:
def __init__(self, model=None, age=None):
self.graph = tf.Graph()
with self.graph.as_default():
self.session = tf.Sessi... |
import logging
import os
from datetime import date
from typing import Optional
import pandas as pd
from . import lahman
from .datasources import fangraphs
_DATA_FILENAME = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data', 'fangraphs_teams.csv')
def team_ids(season: Optional[int] = None, league: str... |
##############################
# Project: 大富翁遊戲主程式 #
# Version: 0.1 #
# Date: 2021/07/15 #
# Author: Antallen #
# Content: 使用 Player 物件
##############################
# 引用 random 類別中的 randrange() 函數
from random import randrange
# 引用 Player 物件
import Player
# 引用 Chance 物件
import Ch... |
import json
# a Python object (dict):
x = {
"name": "John",
"age": 30,
"city": "New York"
}
# convert into JSON:
y = json.dumps(x)
# the result is a JSON string:
print(y) |
# This file is licensed under the Apache License v2.0 with LLVM Exceptions.
# See https://llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
"""Repository rules to configure the terminfo used by LLVM.
Most users should pick one of the explicit rules to configure th... |
# dialogs.folder
"""A collection of dialogs to do things to all fonts in a given folder."""
# import
from actions import actionsFolderDialog
from ufo2otf import UFOsToOTFsDialog
from otf2ufo import OTFsToUFOsDialog
from woff2ufo import WOFFsToUFOsDialog
# export
__all__ = [
'actionsFolderDialog',
'OTFsToUF... |
import sys,os
sys.path.append(os.path.dirname(os.getcwd()))
from app.models import User
from app import db
u = User(username=sys.argv[1])
u.set_password(sys.argv[2])
db.session.add(u)
db.session.commit() |
# SIKULI INTERFACE FOR TAGUI FRAMEWORK ~ TEBEL.ORG #
# timeout in seconds for finding a web element
setAutoWaitTimeout(10)
# delay in seconds between scanning for inputs
scan_period = 0.5
# counter to track current tagui sikuli step
tagui_count = '0'
# prevent premature exit on unhandled exception
setThrowException... |
from os import path
from setuptools import find_packages, setup
# requirements from requirements.txt
root_dir = path.dirname(path.abspath(__file__))
with open(path.join(root_dir, "requirements.txt"), "r") as f:
requirements = f.read().splitlines()
# long description from README
with open(path.join(root_dir, "REA... |
# Copyright 2017 The TensorFlow 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 applica... |
class Frame:
def __init__(self, surface, imgs):
self.idx = 0
self.imgs = imgs
self.num = len(imgs)
self.surface = surface
@property
def img(self):
return self.imgs[self.idx]
@property
def is_last_frame(self):
return self.idx == self.num - 1
def ... |
""" This is a little GUI to launch the playlist importer.
It launches the import script in a command prompt window.
"""
import os
import urllib2
import subprocess
import sys
# This requires wxPython 3.0.2.0.
# For compatibility with virtualenv you can use the wheels from
# https://www.lfd.uci.edu/~gohlke/pythonlibs... |
# Copyright 2016 The TensorFlow 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 applica... |
from edb import Resource
import json
# Create resources on in the database. Does nothing if they already exists.
# For convinience; create() returns the Resource object.
my_list: list = Resource("my_list").create(list())
my_dictionary: dict = Resource("my_dictionary").create(dict())
# Dictionary
my_dictionary["a_new... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.