content stringlengths 5 1.05M |
|---|
"""
byceps.announce.text_assembly.guest_server
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Announce user badge events.
:Copyright: 2014-2022 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from flask_babel import gettext
from ...events.guest_server import GuestServerRegistered
from ..... |
'''
Given two .txt files that have lists of numbers in them, find the numbers that are overlapping.
One .txt file has a list of all prime numbers under 1000, and the other .txt file has a list of happy numbers up to 1000.
(If you forgot, prime numbers are numbers that cannot be divided by any other number.
And yes, ... |
#encoding:utf-8
subreddit = 'SrGrafo'
t_channel = '@r_SrGrafo'
def send_post(submission, r2t):
return r2t.send_simple(submission)
|
# flake8: noqa
from .body import BodyViewSet
from .jurisdiction import JurisdictionViewSet
from .office import OfficeViewSet
from .party import PartyViewSet
|
age = 12
male = "f"
location = "Russia"
locations = ["Russia", "Ukraine", "Belarus"]
is_programmer = True
is_admin = False
if (age >= 12
and male == "f"
and location in locations
and (is_programmer or is_admin)):
print("Доступ открыт")
if age >= 12 \
and male == "m" \
and location in locations ... |
from collections import OrderedDict
from unittest import TestCase
import unittest
from justamodel.exceptions import ValidationError, ModelValidationError
from justamodel.model import Model, Field, PolymorphicModel
from justamodel.serializer import DictModelSerializer, JsonModelSerializer, make_field_filter, \
iter_... |
from threading import Thread
from tensorflow.python import ipu
import tensorflow as tf
NUM_ITERATIONS = 100
#
# Configure the IPU system
#
cfg = ipu.config.IPUConfig()
cfg.auto_select_ipus = 1
cfg.configure_ipu_system()
#
# The input data and labels
#
def create_dataset():
mnist = tf.keras.datasets.mnist
(x_t... |
"""
River Sizes:
You're given a two-dimensional array (a matrix) of potentially unequal height and width containing only 0s and 1s.
Each 0 represents land, and each 1 represents part of a river.
A river consists of any number of 1s that are either horizontally or vertically adjacent (but not diagonally adjacent).
The ... |
# problem name: Count the Arrays
# problem link: https://codeforces.com/contest/1312/problem/D
# contest link: https://codeforces.com/contest/1312
# time: (?)
# author: reyad
# other_tags: (?)
# N.B. : This solution should be submitted with python 3.7, it doesn't work with
# previous versions of python becau... |
"""
Validators for WTForms used in the Digital Marketplace frontend
EmailValidator -- validate that a string is a valid email address
GreaterThan -- compare the values of two fields
FourDigitYear -- validate that a four digit year value is provided
DateValidator -- Error messages for a date input
"""
import datetime
... |
import os
from abc import ABCMeta, abstractmethod
import torch
from torch.utils import data
from torchvision import transforms
from PIL import Image
from target_transforms import ClassLabel
from utils import load_value_file
def images_loader(paths: dict) -> list:
images = []
for path in paths:
with ... |
import discord
from discord.ext import commands
class NoPatron(commands.CheckFailure):
"""Exception raised when you need to donate to use a command."""
pass
async def has_money(bot, userid, money):
async with bot.pool.acquire() as conn:
return await conn.fetchval(
'SELECT money FROM... |
"""Defining graphs using the networkx package."""
import os
import networkx
import numpy as np
import matplotlib.pyplot as plt
from .plot_graph import get_positions, get_colours, get_colours_extend
def nx_create_graph(graph):
"""Covert a graph from the simple_graph package into networkx format."""
G = netwo... |
import xlrd as xl
import numpy as np
import matplotlib.pyplot as plt
from flask import Flask, jsonify, request, render_template, Markup, json, session, redirect, url_for,session
import io
import base64
from funf import ds1,ds2
from dc import att1,att2
import json
app = Flask(__name__)
app.config["TEMPLATES... |
import json
from . import api, root
from .decorators import gateway_belong_to_user, require_basic_or_oauth
from userver.object.gateway import Gateway, Location
from utils.errors import KeyDuplicateError, PatchError
from .forms.form_gateway import AddGatewayForm, PatchGateway
from flask import request, Response
from .f... |
"""Example program to test pyatag."""
import asyncio
import logging
import aiohttp
from pyatag import AtagException, AtagOne
from pyatag.discovery import async_discover_atag
logging.basicConfig()
_LOGGER = logging.getLogger(__name__)
_LOGGER.setLevel(logging.DEBUG)
async def main():
"""Initializ... |
import math
import random
print math.log(32)
print math.log(32, 10)
print math.log(32, 2)
print math.log10(64)
print math.trunc(3.233)
print math.trunc(3.78)
print math.trunc(-232.83)
print math.trunc(-232.1)
l = [1, 2, 3]
random.seed(1234)
print random.choice(l)
print random.choice(l)
print random.choice(l)
print rand... |
import json
import logging
import os
import shutil
import subprocess
import sys
from dataclasses import dataclass
from typing import Optional, List, Dict, Any
from rustimport import settings
_logger = logging.getLogger(__name__)
class Cargo:
def __init__(self, executable_path: Optional[str] = None):
sel... |
#-*- coding: utf-8 -*-
import os
#os.mkdir('tmp2')
def verifica_ws():
print (os.getcwd())
if os.path.exists('Audio'):
print('existe a pasta Audio')
else:
print('não existe a pasta Audio')
print('Criando a pasta Audio')
os.makedirs('Audio')
if os.path.exists('Slow'):
print('existe a pasta Slow')
else... |
import json
from dad_joke import DadJoke
class Database:
def __init__(self, filename='db.json'):
self.jokes = []
self.filename = filename
self.read_from_file()
def add_record(self, record):
self.jokes.append(record)
def get_records(self):
return self.jokes
d... |
# This file is executed on every boot (including wake-boot from deepsleep)
# import esp
# esp.osdebug(None)
# import webrepl
# webrepl.start()
import gc
import network
import machine
from config import SSID, PASSWORD
def establish_connection():
wifi = network.WLAN(network.STA_IF)
if not wifi.isconnected():
... |
#!/usr/bin/env python
#
# Copyright (c) 2013 GhostBSD
#
# See COPYING for licence terms.
#
# create_cfg.py v 1.4 Friday, January 17 2014 Eric Turgeon
#
import os
import pickle
from subprocess import Popen, PIPE
# Directory use from the installer.
tmp = "/tmp/.gbi/"
installer = "/usr/local/lib/gbi/"
# Installer data f... |
from pathlib import Path
from fhir.resources.valueset import ValueSet as _ValueSet
from oops_fhir.utils import ValueSet
from oops_fhir.r4.code_system.adverse_event_causality_method import (
AdverseEventCausalityMethod as AdverseEventCausalityMethod_,
)
__all__ = ["AdverseEventCausalityMethod"]
_resource = _V... |
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import os
import numpy as np
import torch
from pterotactyl.utility import utils
BASE_MESH_SIZE = 1824
BASE_CHART_SIZE = 25
# replay buffer u... |
# coding=utf-8
# Copyright 2021 The OneFlow 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 require... |
'''
Prime numbers are numbers that can only be cleanly divided by themselves and 1.
https://en.wikipedia.org/wiki/Prime_number
You need to write a function that checks whether if the number passed into it is a prime number or not.
e.g. 2 is a prime number because it's only divisible by 1 and 2.
But 4 is not a prime num... |
from typing import Union
from tps.utils import load_dict, prob2bool
from tps.symbols import punctuation, accent
from tps.modules import Processor
class Replacer(Processor):
def __init__(self, dict_source: Union[str, tuple, list, dict]=None,
name: str="Replacer"):
"""
Base class f... |
"""This module wraps some state loading, holding, and saving
functionality into python class implementation.
"""
import json
from collections import Counter
from dataclasses import dataclass
from pathlib import Path
@dataclass
class AnonState:
state_path: Path
vf_filename: str = "state_cache.json"
tc_file... |
from typing import List
import pandas as pd
from concurrent.futures import ThreadPoolExecutor
import requests
url = "https://dawa.aws.dk/postnumre/reverse"
def get_zipcode(series: pd.Series, client: requests.Session) -> str:
resp = client.get(url, params={"x": series.longitude, "y": series.latitude})
if resp... |
#!/usr/bin/python
# Copyright (C) 2015, WSID
# 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, merge, publ... |
__author__ = 'cjm'
import logging
import requests
# TODO: inherit a generic ResultSet model
class Concept:
"""
A SG concept (payload of search)
"""
def __init__(self, obj={}):
self.id = obj['curie']
self.deprecated = obj['deprecated']
self.labels = obj['labels']
... |
import os
import argparse
import pandas as pd
from typing import Optional
from transformers import AutoTokenizer, AutoModel, T5ForConditionalGeneration
from nltk.translate.chrf_score import corpus_chrf
from tqdm.auto import tqdm
from ..utils import load_model
from .metrics import evaluate_style_transfer
def paraphr... |
#!/usr/bin/python
#
# test decoder error measures
#
#
import os
import sys
#import random as random
import math as m
import numpy as np
import unittest
import mock
import tests.common as tc
import abt_constants
from abtclass import *
import hmm_bt as hbt # this test did it right(!)
# b3 class modified by ... |
#!/usr/bin/env python
"""
Created by howie.hu at 2021/4/25.
Description:模型实现
Changelog: all notable changes to this file will be documented
"""
from keras import layers
from keras.callbacks import ModelCheckpoint, TensorBoard
from keras.models import Sequential
from src.classifier.model_lib.char_cnn.kera... |
""" Tests for utils. """
import collections
from datetime import datetime, timedelta
from unittest import mock
from unittest.mock import Mock, patch
from uuid import uuid4
import ddt
from django.conf import settings
from django.test import TestCase
from django.test.utils import override_settings
from opaque_keys.edx.l... |
from django.test import TestCase
from django.template.loader import Template, Context
class TemplateTestCase(TestCase):
BASE_TEMPLATE = """ """
def setUp(self):
self.template_txt = self.BASE_TEMPLATE
def test_can_override_django_h5bp_css_block(self):
context = Context({})
self.t... |
from misc2_module.misc import MiscModule
|
#!/usr/bin/python
import urllib
import urllib2
import ssl
import json
import copy
from ansible.module_utils.basic import AnsibleModule
def get_workspace(host, token, name):
url = "http://" + host + "/api/workspaces"
form_values = {'token': token }
form_data = urllib.urlencode(form_values)
request =... |
import os
import sys
from nndct_shared.base import SingletonMeta
from nndct_shared.utils import io, NndctScreenLogger
try:
import matplotlib.pyplot as plt
except ImportError:
_enable_plot = False
else:
_enable_plot = True
class Plotter(metaclass=SingletonMeta):
counter = 0
figure_dict = {}
def __ini... |
import dash_bootstrap_components as dbc
import dash_daq as daq
import dash_html_components as html
import pretty_midi
dropdown_color = 'black'
dropdown_backgroundColor = 'lightgray'
def add(orchestra, instrument_list, custom_id):
def set_id(index, set_type):
return {
'type': set_type,
... |
from marltoolbox.algos.adaptive_mechanism_design.amd import \
AdaptiveMechanismDesign
|
import torch
from colossalai.zero.sharded_param import ShardedParamV2
from colossalai.utils import get_current_device
from typing import List
class BucketizedTensorCopy(object):
def __init__(
self,
chunk_size: int,
):
r"""
torch.nn.Parameter CPU (fp32) -> ShardedParam GPU (fp... |
from output.models.nist_data.atomic.any_uri.schema_instance.nistschema_sv_iv_atomic_any_uri_pattern_3_xsd.nistschema_sv_iv_atomic_any_uri_pattern_3 import NistschemaSvIvAtomicAnyUriPattern3
__all__ = [
"NistschemaSvIvAtomicAnyUriPattern3",
]
|
import unittest
from unittest.mock import MagicMock
# pylint: disable=unused-wildcard-import
from simulation.apps import *
from simulation.loopix import *
from simulation.messages import *
from simulation.multicast.base import *
from simulation.simrandom import *
from simulation.simulation import *
from simulation.uti... |
import pytest
from principal import soma
def test_soma():
assert soma(2,4) == 6
assert soma(8, -4) == 4
assert soma(0, 0) == 0
|
#!/usr/bin/env python
import os
import versioneer
from setuptools import setup
from distutils import log
from distutils.command.clean import clean
from distutils.dir_util import remove_tree
base_path = os.path.dirname(os.path.abspath(__file__))
long_description = """
This package consists of a couple o... |
from ._version import __version__, version_info
from .NullAuthenticator import NullAuthenticator |
from django.db import models
# Create your models here.
class User(models.Model):
code = models.CharField(max_length = 200)
email = models.CharField(max_length = 100)
password = models.CharField(max_length = 20)
birth_date = models.DateTimeField()
class Profile(models.Model):
name = models.CharField(max_length ... |
# -*- coding: utf-8 -*-
"""052 - Progressão Aritmética
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1XxsY2LOjklht2ABKc1B0VXPOppV9E7Dh
"""
num = int(input('\nDigite o Primeiro número da PA: '))
razão = int(input('Digite a Razão da PA: '))
for c in ra... |
from src import *
class PointNetEncoder(nn.Module):
def __init__(self, dim_latent, breadth=128, is_variational = False):
super(PointNetEncoder, self).__init__()
self.is_variational = is_variational
if is_variational:
self.filename = 'variational-' + self.filename
self.encoder = PN1_Module(input_num_chan... |
from PyQt5 import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from deritradeterminal.util.deribit_api import RestClient
from deritradeterminal.managers.ConfigManager import ConfigManager
class StopMarketSellThread(QThread):
signeler = pyqtSignal(bool,str,str)
def pr... |
class BallMovement:
""" Represents movement for the Ball """
def __init__(self, speed):
""" Initialize with the speed """
self.speed = speed
self.initialSpeed = speed
def reset(self):
""" Reset the ball movement to the initial speed """
self.... |
import unittest
import string
import inspect
from enum import Enum
from uuid import uuid4
from functools import wraps
from datetime import datetime
from odm import mapper
from odm.types import JSONType, UUIDType, ChoiceType
from sqlalchemy.orm import relationship
from sqlalchemy import Column, String, Boolean, DateTi... |
import datetime
from keepsake.packages import get_imported_packages
def test_get_imported_packages():
assert "keepsake" in get_imported_packages()
|
import numpy as np
from numgrad._utils._expand_to import _expand_to
from numgrad._utils._unbroadcast import _unbroadcast_to
from numgrad._variable import Variable
from numgrad._vjp import _register_vjp, differentiable
# https://numpy.org/doc/stable/reference/arrays.ndarray.html#special-methods
def _getitem_vjp(dy, _... |
import torch
import torch.nn.functional as F
from torch.autograd import Variable
import torchvision.datasets as datasets
import torchvision.transforms as T
import bcolz
use_gpu = True
cuda_available = torch.cuda.is_available()
device = torch.device("cuda" if (cuda_available and use_gpu) else "cpu")
def save_array(fna... |
#!/usr/bin/python
# coding: utf-8 -*-
# (c) 2020, Bianca Henderson <bianca@redhat.com>
# 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
ANSIBLE_METADATA = {'metadata_version': '1.1',
... |
import os
def main():
os.system("python \"iid_train.py\" --server_config=2 --cuda_device=\"cuda:1\" --img_to_load=-1 --load_previous=0 --test_mode=0 --patch_size=256 --batch_size=64 --net_config=2 --num_blocks=0 "
"--plot_enabled=0 --debug_mode=0 --version_name=\"maps2rgb_rgb2maps_v4.13\" --iteration... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2021-01-22 12:28
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_depend... |
from .base import FunctionalTest
class PostLikeTest(FunctionalTest):
def test_search_post_title(self):
self.browser.get(self.live_server_url)
self.move_to_default_board()
# 현준이는 좋아요를 받기 위해서 아재개그를 올린다.
self.add_post('반성문을 영어로 해석하면??', '글로벌\n(글로 벌 받는것)\nㅋㅋㅋㅋㅋ꿀잼')
# 게시물이 하나 ... |
from __future__ import division
def odds_stats(odds):
# we fist calculate the total of odds at stake
# so there are only three possible outcomes in a match,either 1,2,3
hometeam_percentage = (odds[0] * 100) / (odds[0] + odds[1])
awayteam_percentage = (odds[1] * 100) / (odds[0] + odds[1])
print 'A... |
#!/usr/bin/env python
from ruffus import *
import sys
import os
import shutil
import cgatcore.experiment as E
from cgatcore import pipeline as P
PARAMS = P.get_parameters("pipeline.yml")
@originate('dependency_check.done')
def dependency_check(outfile):
deps = ["wget", "unzip", "tar", "udocker", "time"]
for ... |
# -*- coding: utf-8 -*-
import json_lines
__author__ = 'drumcap'
import scrapy
from vanilla_scrap.items import MovieCommentItem
from urllib.parse import urlparse, parse_qs
from datetime import datetime
import re
import random
import time
import json
extract_nums = lambda s: re.search('\d+', s).group(0)
sanitize_str... |
import os # NOQA
from mock import patch
import confluent.docker_utils as utils
def test_imports():
""" Basic sanity tests until we write some real tests """
import confluent.docker_utils # noqa
def test_add_registry_and_tag():
""" Inject registry and tag values from environment """
base_image =... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (C) 2015-2020 Florent Rougon
#
# This file is distributed under the terms of the DO WHAT THE FUCK YOU WANT TO
# PUBLIC LICENSE version 2, dated December 2004, by Sam Hocevar. You should
# have received a copy of this license along with this file. You can als... |
# -*- coding: utf-8 -*-
from setup import *
def plot_signal_location(report, plot_width=900, plot_height=200):
fig = bplt.figure(title='Signal location', plot_width=plot_width,
plot_height=plot_height,
tools='xpan,xzoom_in,xzoom_out,xwheel_zoom,reset',
... |
CLIENT_TO_SERVER_RPC = 1
CLIENT_CREATE_ENTITY = 2
SERVER_TO_CLIENT_RPC = 3
CLIENT_DESTROY_ENTITY = 4
|
# -* coding: UTF-8 -*-
"""Tests for Plato base class."""
from __future__ import print_function, unicode_literals
import unittest
from .base import Plato
from .kle_parser import Key
class TestPlato(unittest.TestCase):
"""Tests for Plato."""
def test_calculate_layout_width_height(self):
"""Test Plat... |
import os
import argparse
import numpy as np
import torch
from torch.utils.data import DataLoader
from datasets import Cifar10Dataset
from networks import Generator, Discriminator, weights_init_normal
from helpers import print_args, print_losses
from helpers import save_sample, adjust_learning_rate
def init_training(... |
import numpy as np
import pandas as pd
class DataModel:
"""
This class implements a data model - values at time points and provides methods for working with these data.
"""
def __init__(self, n=0, values=None, times=None):
"""
A constructor that takes values and a time point.
... |
import logging
from typing import NamedTuple, Optional, List, Tuple
from lightbus.api import Api
from lightbus.message import EventMessage, RpcMessage, ResultMessage
from lightbus.utilities.internal_queue import InternalQueue
logger = logging.getLogger(__name__)
class SendEventCommand(NamedTuple):
message: Eve... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Python APRS Module Tests."""
__author__ = 'Greg Albrecht W2GMD <oss@undef.net>' # NOQA pylint: disable=R0801
__copyright__ = 'Copyright 2017 Greg Albrecht and Contributors' # NOQA pylint: disable=R0801
__license__ = 'Apache License, Version 2.0' # NOQA pylint: disab... |
import logging
from functools import lru_cache
@lru_cache(maxsize=2048)
class Logger(object):
def __init__(self, name, level=logging.INFO, *args, **kwargs):
format = '%(asctime)s: %(name)s: %(process)d: %(levelname)-8s: %(threadName)-11s: %(message)s'
logging.basicConfig(format=format, level=level)... |
from flask import Flask, render_template, request
import re
import base64
import io
import numpy as np
from PIL import Image
from classifier import model as ml
model, graph = ml()
app = Flask(__name__)
app.config['TEMPLATES_AUTO_RELOAD'] = True
def convertImage(imgData1):
img = Image.open(io.BytesIO(
bas... |
import datetime
import os
import sys
from api.infrastructure.mysql import connection
try:
sys.path.insert(1, os.path.join(sys.path[0], '../..'))
from users import getCustomersPerUser
except:
pass
try:
sys.path.insert(1, os.path.join(sys.path[0], '..'))
from users import getCustomersPerUser
except... |
A = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
def lista_menor_10(lista):
numero_do_usuario = int(input('Digite o número desejado: '))
lista_menor_10 = []
for elemento in lista:
if elemento < numero_do_usuario:
lista_menor_10.append(elemento)
print(lista_menor_10)
if __n... |
import requests
import time
import os
import json
'''Configuration'''
BASE_URL = 'http://yao.example.com'
''''''
sess = requests.Session()
sess.headers.update({'Referer': BASE_URL})
status_map = [
'Created', # 0
'Starting', # 1
'Running', # 2
'Stopped', # 3
'Finished', # 4
'Failed', # 5... |
__version__ = "0.1"
__all__ = ["twitter_client","tweet_analyzer","user_analyzer"]
from .tweet_analyzer import TweetAnalyzer
from .tweet_analyzer import UserAnalyzer
from .twitter_client import TwitterClient
|
import tkinter as tk
import tkinter.font as tkFont
class Font:
def __init__(self, family, h1_size=26, h2_size=22, h3_size=14, body_size=12):
self.family = family
self.h1 = tkFont.Font(family=family, size=h1_size, weight='bold')
self.h2 = tkFont.Font(family=family, size=h2_size, weight='bold... |
import abc
import logging
import os
import re
import signal
import sys
import typing
from contextlib import contextmanager
import sh
from cached_property import cached_property
from kubeyard import base_command
from kubeyard import minikube
from kubeyard import settings
from kubeyard.commands import custom_script
... |
from .address import AddressEntry, SearchAddressResponse
from .base import BaseModel
from .coordinates import Coordinates
from .item import Item, ItemCreate, ItemInDB, ItemUpdate
from .msg import Msg
from .need import NeedCreate, PublicNeed, PublicNeedPpeType
from .posttag import PosttagPostcodeFullResponse, PosttagRes... |
# -*- coding: utf-8 -*-
# @Author: Lutz Reiter, Design Research Lab, Universität der Künste Berlin
# @Date: 2016-10-22 16:07:52
# @Last Modified by: lutzer
# @Last Modified time: 2016-10-25 00:31:45
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: Lutz Reiter, Design Research Lab, Universität der Künste Be... |
import unittest
import solver
class TestSolution(unittest.TestCase):
def test_solve(self):
self.assertEqual(solver.solve(2, 2), 1)
self.assertEqual(solver.solve(3, 3), 4)
self.assertEqual(solver.solve(5, 5), 15)
|
import numpy as np
from . import xray
import numexpr as ne
import pandas as pd
import time as ttime
# def get_transition_grid(E_step, E_range, n, ascend=True):
# dE = (E_range*2/n - 2*E_step)/(n-1)
# steps = E_step + np.arange(n)*dE
# if not ascend:
# steps = steps[::-1]
# return np.cumsum(steps... |
import os
import sys
def run_macrobase(cmd='pipeline', conf='conf/batch.conf', profiler=None,
**kwargs):
extra_args = ' '.join(['-D{key}={value}'.format(key=key, value=value)
for key, value in kwargs.items()])
if profiler == 'yourkit':
extra_args += ' -agentpath:/App... |
from __future__ import absolute_import, division, print_function
import tensorflow as tf
from models.resnet import resnet_18, resnet_34, resnet_50, resnet_101, resnet_152
import config
from prepare_data import generate_datasets
import math
def get_model():
model = resnet_50()
if config.model == "resnet18":
... |
import numpy
import h5py
import json
h5 = h5py.File("data/geomodelgrids/USGS_SFCVM_detailed_v21-1.h5", "r")
auxiliary = json.loads(h5.attrs["auxiliary"])
fault_blocks = sorted(auxiliary["fault_block_ids"].items(), key=lambda x: x[1])
print("Fault Blocks")
for label, value in fault_blocks:
lines = [
" ... |
# coding: utf-8
from django.db import models
from django.utils.translation import ugettext_lazy as _
TYPE_CHOICES = (
(1, _(u'Participante')),
(2, _(u'Organizador')),
)
class Subscription(models.Model):
email = models.EmailField(_(u'Email'))
type = models.IntegerField(_(u'Tipo'), choices=TYPE_CHOICE... |
# time_hello_split.py
from webpie import WPApp, WPHandler
import time
class Greeter(WPHandler):
def hello(self, request, relpath):
return "Hello, World!\n"
class Clock(WPHandler):
def time(self, request, relpath): # 1
return time.ctime()+"\n", "text/plain" # 2
class TopHandler(WPHand... |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
import imageClassify_pb2 as imageClassify__pb2
class ImageClassifyGrpcStub(object):
"""The greeting service definition.
"""
def __init__(self, cha... |
import os
import json
import io
import markdown
from flask import Flask, render_template, request
from jinja2 import Environment
app = Flask(__name__)
@app.route("/")
def home():
return render_template("home.html")
@app.route('/projects')
def projects():
data = get_static_json("static/projects/projects.json... |
from grafanalib.core import (
Alert,
Graph,
Template,
Templating,
)
from grafanalib.cloudwatch import CloudwatchMetricsTarget
from lib.elasticsearch import (
generate_elasticsearch_cpu_graph,
generate_elasticsearch_jvm_memory_pressure_graph,
generate_elasticsearch_documents_graph,
gene... |
# coding: utf8
from __future__ import unicode_literals, print_function, division
from xml.etree.ElementTree import fromstring
from pyramid.config import Configurator
from mock import Mock
def main(global_config, **settings):
"""called when bootstrapping a pyramid app using clld/tests/test.ini."""
from clld i... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
###
### IMPORTANT: This is NOT a Buck binary, it runs using the system python3
###
import ctypes
import fcntl
import os... |
# parse 是一个工具模块
# https://docs.python.org/3/library/urllib.parse.html#module-urllib.parse
from urllib import parse
# b'name=Ashe&hobbies=%5B%27%E6%91%84%E5%BD%B1%27%2C+%27%E6%97%85%E8%A1%8C%27%5D'
print(parse.urlencode({'name': 'Ashe', 'hobbies': ['摄影', '旅行']}).encode('utf-8'))
o = parse.urlparse('https://zlikun:123... |
"""
This is main.
"""
from utils import ProjectUtils
if __name__ == '__main__':
utils = ProjectUtils()
df_news_cleaned, df_news_cleaned_path = utils.clean_export_news_file()
print('df_news_cleaned_path:', df_news_cleaned_path)
df_news_partial, df_news_partial_path = utils.create_sentiment_positivity... |
from mock import patch
from unittest import TestCase
from infi import asi
@asi.gevent_friendly
def simple_function():
return 1
def a_generator():
inner_call = lambda n: n
for i in range(2):
yield asi.gevent_friendly(inner_call)(i)
class GeventFriendlyTestCase(TestCase):
def test_simple_func... |
"""General utilities."""
def _var_names(var_names):
"""Handle var_names input across arviz.
Parameters
----------
var_names: str, list, or None
Returns
-------
var_name: list or None
"""
if var_names is None:
return None
elif isinstance(var_names, str):
retur... |
import CI
import CI.builder.system
import os
description = 'configure the Fish shell'
features = CI.Features(
copy_standard_config = CI.Boolean(),
change_user_shell = CI.Boolean(),
)
CI.builder.system.features.packages = [
'fish',
]
class FishChangeUserShellAction(object):
description = "choos... |
# (c) Copyright 2014,2015 Hewlett-Packard Development Company, L.P.
#
# 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 a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.