content stringlengths 5 1.05M |
|---|
# https://www.hackerrank.com/challenges/three-month-preparation-kit-contacts/problem
#!/bin/python3
import math
import os
import random
import re
import sys
from collections import Counter
#
# Complete the 'contacts' function below.
#
# The function is expected to return an INTEGER_ARRAY.
# The function accepts 2D_S... |
#coding=UTF-8
'''
Created on 2011-7-2
@author: Administrator
'''
try:
import cookielib
import mechanize
import simplejson as sj
import random
import time
import urllib
import os
from pyquery.pyquery import PyQuery
import re
import mimetypes
except Exception,e:
raise "puterr... |
# coding: UTF-8
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from .menu_interface import MenuInterface
from scenes.elements import (
GameDiv,
GameTextElement,
ButtonGroup,
)
from consts.i18n import (
RESTART,
EXIT,
DRAW_MESSAGE,
... |
#Aula 2 - Variaveis, tipos, entradas, saidas e operadores matematicos
# Formulario Basico Python3
'''Fassa um formulário perguntando Nome, CPF, Idade, Altura, Endereço, Contato'''
print ('Preencha o formulário a seguir\n\n\n')
nome = input('Qual seu nome?\nR: ')
cpf = input('Qual o seu CPF?\nR: ')
idade = input('Qual a... |
#from colorama import init
#init()
from colorama import Fore
print(Fore.BLUE + "Something in Blue")
print(Fore.RED + "Something in Red")
|
from .networks import get_network
|
# Generated by Django 2.0.5 on 2018-09-21 17:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('contract_scanner', '0008_contract_auction'),
]
operations = [
migrations.AddField(
model_name='contract',
name='regi... |
#!/usr/bin/python2.4
# Copyright 2008 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Program to parse hammer output and sort tests by how long they took to run.
The output should be from the CommandTest in SConst... |
from utilities.math import Vector2, _pyi_Vector2_type, _pyi_Vector2_item_type
from constants import MOUSE_MODE_CONFINED, MOUSE_MODE_CAPTURED
from pygame import mouse as _mouse, event, display
from pygame.cursors import Cursor
from typing import List, Union
from types import ModuleType
import sys
_captured = False
c... |
MAX_FILE_SIZE = 150000000 # 150Mb
S3_UPLOADS_BUCKET = "pollingstations-uploads-dev"
|
import re
from pylatex import NoEscape, Package
from pylatex.base_classes import Environment, ContainerCommand
class LatexSection(Environment):
"""This class is generic and allow the creation of any section like
.. code-block:: latex
\begin{name}
Some content
\end{name}
The... |
from enum import Enum
from when_ml_pipeline_meets_hydra.api.deployment import bar, foo
class DeploymentSubCommand(Enum):
FOO = "foo"
BAR = "bar"
def _print_help():
subs = [sub.value for sub in DeploymentSubCommand]
print(f"Please add 'c/deployment_sub={subs}' to your command!")
def process_deploy... |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
import calculator_service_pb2 as calculator__service__pb2
class CalculatorStub(object):
"""Missing associated documentation comment in .proto file"""
def __init__(self, channel):
"""Constructor.
Args:
... |
import FWCore.ParameterSet.Config as cms
# AlCaReco for muon based alignment using beam-halo muons in the CSC overlap regions
OutALCARECOMuAlBeamHalo_noDrop = cms.PSet(
SelectEvents = cms.untracked.PSet(
SelectEvents = cms.vstring('pathALCARECOMuAlBeamHalo')
),
outputCommands = cms.untracked.vstrin... |
import os
def get_full_path(filename):
return os.path.join(os.path.dirname(os.path.realpath(__file__)), filename) if filename else ''
|
# Import libraries
from tbwrapper import *
import json
import random
import time
## Python Wrapper Tests - Out of ThinksBoards.io Package Scope
#############################################################################
#---------------------------------------------------------------------------#
# CREATE... |
GENERAL_ACKNOWLEDGEMENTS = {
"positive": ["Sounds cool! ", "Great! ", "Wonderful! ", "Cool!", "Nice!"],
"neutral": ["Okay. ", "Oh. ", "Huh. ", "Well. ", "Gotcha. ", "Aha. "],
"negative": ["Hmm... ", "I see.", "That's okay.", "Okay."],
}
|
#! /usr/bin/env python
"""Author: Scott Staniewicz
Functions to assist input and output of SAR data
Email: scott.stanie@utexas.edu
"""
import collections
import glob
import math
import os
import pprint
import re
import sys
import numpy as np
import matplotlib.pyplot as plt
from insar.log import get_log
logger = get_lo... |
# ------------------------------------------------------------------------------------------------------
# Copyright (c) Leo Hanisch. All rights reserved.
# Licensed under the BSD 3-Clause License. See LICENSE.txt in the project root for license information.
# ---------------------------------------------------------... |
from test_plus.test import TestCase
from ..models import Profile, Task, Team
from .factories import ProfileFactory, TaskFactory, TeamFactory
from to_do_list.users.tests.factories import UserFactory
from ..helper_functions import calculate_reputation_gain, give_reputation_reward
from mock import patch
class TestProfi... |
import sys, atexit
from time import sleep
from mowaysim import *
print 'Executing ' + __name__ + ' test...'
if __name__ == '__main__':
atexit.register(exit_mow)
channel = 8
moway.usbinit_moway()
ret = moway.init_moway(channel)
if ret == 0:
print 'Moway RFUSB Connected'
else:
print 'Moway RFUSB not co... |
import requests
test_url = "https://playground.learnqa.ru/api/homework_cookie"
class TestCookie:
def test_cookie(self):
print("Expected cookie is {'HomeWork': 'hw_value'}")
actual_response = requests.get(test_url)
actual_cookie = dict(actual_response.cookies)
assert actual_respons... |
from . import openacademy_course
from . import openacademy_session
from . import partner
|
from django.core.management.base import BaseCommand
from iRiffSync.iRiffClient import iRiffClient
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('page', nargs='+', type=int)
def handle(self, *args, **options):
for page in options['page']:
client = iRiffClient()
... |
# Copyright (c) Open-MMLab. All rights reserved.
import torch
from torch.nn.parallel._functions import _get_stream
def scatter(input, devices, streams=None):
"""Scatters tensor across multiple GPUs.
"""
if streams is None:
streams = [None] * len(devices)
if isinstance(input, list):
ch... |
# -*- coding: utf-8 -*-
from cleo import Application
from .. import __version__
application = Application('Orator', __version__, complete=True)
# Migrations
from .migrations import (
InstallCommand, MigrateCommand,
MigrateMakeCommand, RollbackCommand,
StatusCommand, ResetCommand, RefreshCommand
)
applic... |
supported_languages = {
# .c,.h: C
"c": "C",
"h": "C",
# .cc .cpp .cxx .c++ .h .hh : CPP
"cc": "CPP",
"cpp": "CPP",
"cxx": "CPP",
"c++": "CPP",
"h": "CPP",
"hh": "CPP",
# .py .pyw, .pyc, .pyo, .pyd : PYTHON
"py": "PYTHON",
"pyw": "PYTHON",
"pyc": "PYTHON",
"py... |
import pathlib
import os.path
import tempfile
import app.git as git
basedir = os.path.abspath(os.path.dirname(__file__))
class TestGitRepoFromPath:
def test_none(self):
assert git.repo_from_path(None) is None
def test_empty(self):
assert git.repo_from_path('') is None
def test_bad_d... |
# -*- coding: utf-8 -*-
from setuptools import find_packages
from setuptools import setup
test_reqs = ["pytest", "pytest-docker-fixtures", "pytest-aiohttp>=0.3.0"]
setup(
name="guillotina_gcloudstorage",
version=open("VERSION").read().strip(),
description="guillotina gcloud storage support",
long_de... |
# Copyright 2012 OpenStack Foundation
# 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 requ... |
from .db import get_connection, get_data_dict
from flask import render_template, url_for, make_response
import requests
import traceback
import math
import logging
logger = logging.getLogger()
def do_packaging():
context = {'packaging_page': True}
conn = get_connection()
cur = conn.cursor()
query = """... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# -----------------------------------------------------------------... |
# -*- coding: utf-8 -*-
"""
proxy.py
~~~~~~~~
⚡⚡⚡ Fast, Lightweight, Pluggable, TLS interception capable proxy server focused on
Network monitoring, controls & Application development, testing, debugging.
:copyright: (c) 2013-present by Abhinav Singh and contributors.
:license: BSD, see LICENSE... |
"""Various forms used within the application."""
from wtforms import (
Form, StringField, PasswordField, validators, SelectMultipleField,
BooleanField
)
class LoginForm(Form):
"""Login form validator."""
username = StringField('username', [validators.Length(min=6, max=35)])
password = PasswordFi... |
import requests
from requests.exceptions import HTTPError
import json
try:
from config import log_level
except:
log_level = 6
finally:
from .__debug import Console
console = Console(log_level)
class Req:
def __init__(self):
self.host = ""
self.session = requests.session()
... |
# Generated by Django 2.1.2 on 2018-12-06 08:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('trade', '0021_auto_20181130_1205'),
]
operations = [
migrations.AddField(
model_name='goodsitems',
name='original_pr... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10a1 on 2016-06-23 01:35
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0027_auto_20160622_1737'),
]
operations =... |
"""
Unit Tests For NBeats Models
"""
import pytest
from kerasbeats import utilities, NBeatsModel
class TestNBeatsConfiguration():
def test_generic_prediction_output(self, numeric_data, generic_model):
"""Confirms that model works w/ univariate time series + prediction
has the correct shape"""
... |
#string
s="I am a string"
print(type(s)) #will say str
#boolean
yes = True #boolean True
print(type(yes))
no = False #Boolean false
print(type(no))
#List -- ordered and changeable
alpha_list =["a","b","c"] #list initialization
print(type(alpha_list)) #will say tuple if this is a tuple why can ... |
numstr = '345'
print(numstr.isdecimal(), end=' ')
numstr = '10.75'
print(numstr.isdecimal(), end=' ')
alnumstr = 'AB123'
print(alnumstr.isdecimal())
# True False False |
"""Defines all the materials and their material properties.
Base class Material allows for users to define a material, while some specific commonly used materials are predefined to help speed up the design process.
Users should check that the right material properties are assumed for their parts."""
from . import Q_, ... |
#!/home/vigliens/python/bin/python
# sqsub -r 1h -f xeon -q mpi --mpp 8GB -o 23_graphlab -n 8 /home/vigliens/python/bin/python /home/vigliens/Documents/2_CODE/4_SCRIPTS/MPI/23_graphlab_mini_example.py
# for ((i=0; i<=47;i++)); do echo `sqsub -r 4h -f xeon -q mpi --mpp 4GB -o 23_graphlab_0_01 -n 8 /home/vigliens/python... |
# -*- coding: utf-8 -*-
"""Main module."""
import pandas as pd
class _Network:
# TODO: add H2/CH4 composition
LEVELS = {"HP": 5.5e5, "MP": 2.0e5, "BP+": 1.1e5, "BP": 1.025e5} # Pa
LHV = 38.1e3 # kJ/kg
V_MAX = 2.0 # m/s
T_GRND = 10 + 273.15 # K
def __init__(self):
self.bus = pd... |
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
def one():
fig = plt.figure()
ax1 = fig.add_subplot(121, aspect='equal', autoscale_on=False, xlim=(-0, 2), ylim=(-1.5, 1.5))
ax2 = fig.add_subplot(122, aspect='equal', autoscale_on=False, xlim=(-1.1, 1.1), ylim=(-1.1,... |
import unittest
from mock import patch
class TestPyPiXMLRPC(unittest.TestCase):
@patch('xmlrpclib.ServerProxy')
def test_search(self, sp):
from cheeseprism.rpc import PyPi
out = PyPi.search('five.intid')
assert sp.called
assert out
@patch('xmlrpclib.ServerProxy')
def ... |
__copyright__ = """
Copyright (C) 2012 Andreas Kloeckner
Copyright (C) 2016, 2017 Matt Wala
"""
__license__ = """
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 wit... |
import config
from bot import Bot
import bot_common
IS_PRINTER_ENABLED = False
def increment_bigbrain(self, message):
self.state['bigbrain_counter'] += 1
text = f'Big brain moments: {self.state["bigbrain_counter"]}'
self.send_privmsg(message.channel, text)
self.write_state()
def increment_smallbra... |
# Copyright 2021, Yahoo
# Licensed under the terms of the Apache 2.0 license. See the LICENSE file in the project root for terms
from .BaseExecutor import BaseExecutor
class SelfTargetExecutor(BaseExecutor):
__target_type__ = "self"
def execute(self) -> None:
raise NotImplementedError()
|
from ctypes import *
import numpy as np
Painter = cdll.LoadLibrary('./Rasterizer/libPainter.so')
def ProjectPaint(points, normals, point_colors, color, depth, world2cam, intrinsic):
Painter.ProjectPaint(c_void_p(points.ctypes.data), c_void_p(normals.ctypes.data), c_void_p(point_colors.ctypes.data),
c_void_p(color.c... |
#!~/anaconda3/bin/python3
# ******************************************************
# Author: Pengshuai Yang
# Last modified: 2021-08-04 15:10
# Email: yps18@mails.tsinghua.edu.cn
# Filename: utils.py
# Description:
# auxillary functions
# ******************************************************
import os
def check_d... |
import pytest
import nsrt_mk3_dev
@pytest.fixture(scope="session")
def nsrt(request):
return nsrt_mk3_dev.NsrtMk3Dev(port=request.config.getoption('--vcomm'))
def pytest_addoption(parser):
parser.addoption("--vcomm", action="store", default='COM20')
|
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in co... |
import datetime
import blessed
from word_search import WordSearch
class Game:
def __init__(self, filename="words_dictionary.json"):
self.word_search = WordSearch.generate_json(filename, width=100, height=100)
self.terminal = blessed.Terminal()
self.keys = {
# code - (method, ... |
import numpy as np
import csv
import random as rd
import os
HERE = os.path.dirname(os.path.abspath(__file__)) # useful to locate data files with respect to this fil
data_dir = os.path.join(os.path.dirname(os.path.dirname(HERE)), "data")
print(f"DATA_PATH: {data_dir}")
np.random.seed(2019)
def load_data() -> tuple:
... |
from tkinter import N
from tkinter.messagebox import NO
from typing import List
class Song:
def __init__(self, name, artist, album) -> None:
self.name = name
self.artist = artist
self.album = album
pass
def set_artist(self, artist):
self.artist = artist
... |
from string import ascii_letters, whitespace, digits
from .Token import Token, TokenTypes
class Lexer:
def __init__(self, code):
self.chars = iter(code)
self.advance()
def getTokens(self):
tokens = []
while self.c != "\0":
tokens.append(self.getNextToken())
... |
"""
Tests for catalyst.pipeline.Pipeline
"""
import inspect
from unittest import TestCase
from mock import patch
from catalyst.pipeline import Factor, Filter, Pipeline
from catalyst.pipeline.data import USEquityPricing
from catalyst.pipeline.graph import display_graph
from catalyst.utils.numpy_utils import... |
from typing import Literal
import functools
from abc import abstractmethod
from restools.timeintegration import TimeIntegrationChannelFlowV1, TimeIntegrationChannelFlowV2
from restools.data_access_strategies import free_data_after_access_strategy, hold_data_in_memory_after_access_strategy
class TimeIntegration3DBuil... |
import plotly.graph_objs as go
from plotly.offline import plot
import os
import requests
from rsi_divergence_finder import *
from timeframe import TimeFrame
import talib
real_path = os.path.dirname(os.path.realpath(__file__))
os.chdir(real_path)
def plot_rsi_divergence(candles_df, divergences, pair, file_name):
... |
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
import datetime
import sys
def index(request):
'''Portfolio: overview of all initiatives'''
from service.ReportService import ReportService
import Config
report = ReportService(Config.config)
startR... |
import cv2
import numpy as np
import torch
import torch.nn as nn
from torch.nn import functional as F
class GradCAM():
def __init__(self, model, target_layer, use_cuda):
self.model = model.eval()
self.target_layer = target_layer
self.use_cuda = use_cuda
self.feature_map = 0
... |
# The Intersection Component
# Tung M. Phan
# California Institute of Technology
# August 6, 2018
#
import os
from PIL import Image
dir_path = os.path.dirname(os.path.realpath(__file__))
#intersection_fig = dir_path + "/components/imglib/intersection_states/intersection_lights.png"
intersection_fig = os.path.dirname(di... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
print ( "You should not see any errors when this is run" )
|
from airflow import DAG
from airflow.operators.python_operator import PythonOperator
from datetime import datetime, timedelta
import os
import logging
import pendulum
import json
import yaml
import tableauserverclient as TSC
default_args = {
'owner': 'airflow',
'depends_on_past': False,
'start_date': date... |
import re
from configparser import ConfigParser
from selenium.webdriver.common.by import By
class PageObject:
__slots__ = [
"config",
"current_section"
]
PoToBy = {
"id": By.ID,
"xpath": By.XPATH,
"p_link_text": By.PARTIAL_LINK_TEXT,
"link_text": By.LINK_T... |
#coding:utf-8
#
# id: bugs.core_5823
# title: No permission for SELECT access to blob field in stored procedure
# decription:
# Confirmed bug on 3.0.4.33034
# Checked on: 3.0.4.33053, 4.0.0.1249: OK
#
# tracker_id: CORE-5823
# min_versions: ['3.0... |
#coding=utf-8
import time
from bs4 import BeautifulSoup
from pymongo import MongoClient
import requests
import urlparse
import json
import redis
import config
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
job_redis = redis.Redis(host=config.Redis_ip, port=config.Redis_port, db=config.Redis_db)
def search_al... |
import flwr as fl
import sys
# Start Flower server for three rounds of federated learning
# This requires 3 clients to be trained federatedly.
if __name__ == "__main__":
strategy = fl.server.strategy.FedAvg(
fraction_fit=1,
fraction_eval=1,
min_fit_clients=3,
min_eval_clients=3,
... |
# import numpy as np
# from regression_model.config.core import config
# from regression_model.processing.features import ExtractLetterTransformer
def test_ExtractLetterTransformer(train_features):
# TODO...
# PITA as saple_input_)data has NaNs in it so needs to be transformed before
# being passed to E... |
import bcrypt
from urllib.parse import urlencode
from django.contrib.auth import get_user_model
from django.utils import timezone
from rest_framework.authtoken.models import Token
from magic_links.models import MagicLinkCredential
from magic_links.settings import api_settings
User = get_user_model()
def authenticat... |
import grimagents.settings as settings
def test_training_wrapper_path():
"""Tests for the correct path to training_wrapper.py"""
assert settings.get_training_wrapper_path().parts[-1] == ('training_wrapper.py')
assert settings.get_training_wrapper_path().exists()
|
# -*- coding: utf-8 -*-
"""
--------------------------------------
@File : __init__.py.py
@Author : maixiaochai
@Email : maixiaochai@outlook.com
@Created on : 2020/5/22 15:47
--------------------------------------
"""
from .api import *
from .model import *
from .scheduler import *
|
# config.py
# Enable Flask's debugging feature. Should be False in production
DEBUG = True |
import logging
import re
import time
import requests
from pyquery import PyQuery
from pikapi.spiders.spider import Spider
logger = logging.getLogger(__name__)
class SpiderTxt(Spider):
name = 'txt'
start_urls = [
"http://www.proxylists.net/http_highanon.txt",
"http://ab57.ru/downloads/proxyl... |
from marvinbot.cache import cache
from telegram.ext.filters import BaseFilter
import re
class RegexpFilter(BaseFilter):
def __init__(self, pattern, mode='match', **options):
"""Takes a pattern, and returns a match object if it complies.
Support caching."""
if mode not in ['match', 'search... |
# 12. 整数转罗马数字
#
# 20200721
# huao
# 理解规则,把数字划分为不同的区域即可
class Solution:
def intToRoman(self, num: int) -> str:
romanNum = ""
thousand = num // 1000
if thousand > 0:
for i in range(thousand):
romanNum += "M"
num %= 1000
hundred = num // 100
... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import os
import sys
import re
import json
import argparse
import html2text
SCRIPT_PATH=os.path.dirname(os.path.realpath(__file__))
from EnChDict import EnChDict
stardict_db = "%s/stardict.sqlite.db" % SCRIPT_PATH
ANKI_ENGLISH_NOTE_FIELDS = ["word", "phonetic", "definiti... |
"""This module contains the GeneFlow AgaveWrapper class."""
import itertools
import os
import time
import urllib.parse
try:
from agavepy.agave import Agave
from agavepy.asynchronous import AgaveAsyncResponse
except ImportError: pass
from geneflow.log import Log
class AgaveWrapper:
"""
Agave wrapper... |
#!/usr/bin/env python
'''Check-only run of AStyle and on ubxlib and report results.'''
import os # For sep
import subprocess
import u_report
import u_utils
import u_settings
# Prefix to put at the start of all prints
PROMPT = "u_run_astyle_"
# The name of the AStyle configuration file to look for
# in the... |
# Generated by Django 3.1.2 on 2020-11-22 13:39
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Pazienti',
fields=[
('id', models.AutoField... |
# Copyright (c) 2020 fortiss GmbH
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
import numpy as np
from modules.runtime.scenario.scenario_generation.config_readers.config_readers_interfaces import ConfigReaderControlledAgents
from bark.world.goal_definition import GoalDe... |
#!python3
# -*- coding:utf-8 -*-
import traceback
import subprocess as subp
from subprocess import SubprocessError, TimeoutExpired
try:
result = subp.run(args=["ls", "-l"])
print(result.returncode)
result = subp.run(args=["firefox", "https://www.google.com"], shell=True)
print(result.returncode)
exce... |
# © 2020 Nokia
# Licensed under the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
# !/usr/bin/env python3
# coding: utf-8
# Author: Élie de Panafieu <elie.de_panafieu@nokia-bell-labs.com>
from fitting_text_distance.tools.matrix_operations import *
class Distribution:
"""Probability distribution... |
#!/usr/bin/env python3
from copy import deepcopy
import re
discs = []
with open('fifteen.in', 'r') as f:
for line in f:
m = re.match(r'Disc #(\d+) has (\d+) positions; at time=0, it is at position (\d+).', line)
disc, npositions, position = map(int, m.group(1, 2, 3))
discs.append((npositi... |
import garapa
import png
def init_joystick():
for key in ['right', 'left', 'up', 'down', 'a', 'b', 'select', 'start']:
garapa.set_input(key, 0)
def dump_sprite(base_addr=0x8000):
name_suffix = (base_addr - 0x8000) / 0x0010
png_data = [[]]
colors = [
0xffffff,
0xc0c0c0,
... |
"""
Copyright (C) 2019 Interactive Brokers LLC. All rights reserved. This code is subject to the terms
and conditions of the IB API Non-Commercial License or the IB API Commercial License, as applicable.
"""
"""
The Decoder knows how to transform a message's payload into higher level
IB message (eg: order info, mkt d... |
#!/usr/bin/env python
import argparse
import json
import subprocess
def read_json(f):
f = open(f)
j = json.loads(f.read())
f.close()
return j
def update_task_definitions(container_name, task_definition, family, image_name, tag, env):
for d in task_definition['containerDefinitions']:
d['n... |
"""
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Ex_1:
Input: haystack = "hello", needle = "ll"
Output: 2
Ex_2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
Clarification:
What should we return when needle is an empty string? This i... |
from worker.worker import Worker
from worker.http_worker import HttpClient
|
"""Test the ORM's `Customer` model."""
import pytest
from urban_meal_delivery import db
class TestSpecialMethods:
"""Test special methods in `Customer`."""
def test_create_customer(self, customer):
"""Test instantiation of a new `Customer` object."""
assert customer is not None
def tes... |
"""
Incrementally tweak specified axes. Build new faces!
"""
from argparse import ArgumentParser
import pprint
import numpy as np
from pylearn2.gui.patch_viewer import PatchViewer
import theano
from adversarial import sampler, util
# Parse arguments
parser = ArgumentParser(description=('Experiment with tweaking ea... |
"""
elevate.views
~~~~~~~~~~~~~
:copyright: (c) 2017-present by Justin Mayer.
:copyright: (c) 2014-2016 by Matt Robenolt.
:license: BSD, see LICENSE for more details.
"""
from urllib.parse import urlparse, urlunparse
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirec... |
from PIL import ImageFont
from typing import Type
import tkinter as tk
from ..util import font
# determine if we can use 'arialbd' as a default font:
DEFAULT_FONTS = [
'arialbd.ttf',
'DroidSansMono.ttf',
]
DEFAULT_FONTS.extend(font.find_system_fonts())
for fnt in DEFAULT_FONTS:
default_font = fnt
try:
... |
import json
import time
import aiohttp
from sanic.exceptions import ServerError, Unauthorized
from spider.ehall.auth_server import auth_server, auth_server_load_cookies
async def auth_ehall(session: aiohttp.ClientSession, cookies: dict):
""" 登录到 ehall 平台 """
# 载入 Cookies
auth_server_load_cookies(session... |
from aiogram.types import (InlineKeyboardButton, InlineKeyboardMarkup,
KeyboardButton, ReplyKeyboardMarkup)
def craft_startup_keyboard() -> ReplyKeyboardMarkup:
"""
Method for crafting startup keyboard with function /today, /next, /week
"""
buttons = [
KeyboardButto... |
# Library Imports
from typing import List, Union, Mapping, NamedTuple
from typing_extensions import TypeAlias
try:
from typing import Literal
except ImportError:
from typing_extensions import Literal
# User-Defined Structs
# > Passbolt types
PassboltFolderIdType: TypeAlias = str
PassboltResourceIdType: TypeA... |
from keras import backend as K
import os
# Parameters
candle_lib = '/data/BIDS-HPC/public/candle/Candle/common'
def initialize_parameters():
print('Initializing parameters...')
# Obtain the path of the directory of this script
file_path = os.path.dirname(os.path.realpath(__file__))
# Import the ... |
import typing
def main() -> typing.NoReturn:
s = input()
t = input()
n = len(s)
print(sum(s[i] != t[i] for i in range(n)))
main()
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from flask import Flask, escape
from flask_jsonp import jsonpify
import data
import json
application = Flask(__name__)
@application.route("/")
def hello():
return "<h1 style='color:blue'>Hello There!</h1>\n"
@application.route("/api/api2")
def api2():
return "<h1 sty... |
import os, json
def check_extension(draft):
remainder = ""
for i in draft[::-1]:
if i == ".":
extension = (remainder + i)[::-1]
break
remainder += i
return extension
def check_draft_file(draft):
key = []
for i in draft:
if i == "{":
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.