text stringlengths 1 927k |
|---|
import wx
import wx.lib.intctrl
import wx.lib.rcsizer as rcs
import socket
import sys
import re
import six
import datetime
import Model
import Utils
import JChip
import ChipReader
from JChip import EVT_CHIP_READER
import RaceResult
import Ultra
import HelpSearch
from ReadSignOnSheet import GetTagNums
HOST, PORT = JCh... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Use text editor to edit the script and type in valid Instagram username/password
import urllib
from bot.lib.InstagramAPI import InstagramAPI
video_url = 'https://instagram.fmad3-2.fna.fbcdn.net/t50.2886-16/17157217_1660580944235536_866261046376005632_n.mp4' #a valid ... |
# -*- coding: utf-8 -*-
""" Contains the AutoCompleteMode """
import logging
from pyqode.qt import QtCore, QtGui
from pyqode.core.api import TextHelper
from pyqode.core.api.mode import Mode
class AutoCompleteMode(Mode):
""" Automatically complete quotes and parentheses
Generic auto complete mode that automat... |
# -*- coding: utf-8 -*-
"""
mslib.mswms.dataaccess
~~~~~~~~~~~~~~~~~~~~~~
This module provides functions to access data
This file is part of mss.
:copyright: Copyright 2008-2014 Deutsches Zentrum fuer Luft- und Raumfahrt e.V.
:copyright: Copyright 2011-2014 Marc Rautenhaus (mr)
:copyrigh... |
#!/usr/bin/env python3
import subprocess
import sys
import time
from typing import List
import gflags
FLAGS = gflags.FLAGS
gflags.DEFINE_bool("use_updates", False, "Issue update calls instead of query calls")
class Mainnet:
"""Wrapper to run against subnetworks in mainnet concurrently."""
def __init__(self... |
from torchvision import transforms
transform1 = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean = [0.485,0.456,0.406], std = [0.229,0.224,0.225]),
])
cut = transforms.Compose([
transforms.Resize(256),
transforms.Cent... |
import os
import logging
import sentry_sdk
from aiogram import Bot, Dispatcher, executor, types
from datetime import datetime, timedelta
from pypi_tools.logic import remove_track_for_package
import pypi_tools.data as d
from pypi_tools.helpers import validate_input
import pypi_tools.vizualizer as v
import pypi_tools.rea... |
from pizza import Pizza
class VeggiePizza(Pizza):
def __init__(self):
self.name = 'Veggie Pizza'
self.dough = 'Crust'
self.sauce = 'Marinara sauce'
self.toppings.append('Shredded mozzarella')
self.toppings.append('Grated parmesan')
self.toppings.append('Diced onion'... |
import time
class Timer:
"""Simple Timer"""
def __init__(self):
self.start = time.perf_counter()
def end(self, precision: int = 3) -> str:
return '%.{}f'.format(precision) % (time.perf_counter() - self.start) |
# Copyright 2020 The Pigweed 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('django_chatterbot', '0015_statement_persona'),
]
operations = [
migrations.AddField(
model_name='statement',
name='stemmed_text',
field=models.CharField(... |
from typing import List
from fastapi import Depends, FastAPI, HTTPException, Request, Response
from sqlalchemy.orm import Session
from . import crud, models, schemas
from .database import SessionLocal, engine
models.Base.metadata.create_all(bind=engine)
app = FastAPI()
@app.middleware("http")
async def db_session... |
""" TSI{0,1,2,3,5} are private tables used by Microsoft Visual TrueType (VTT)
tool to store its hinting source data.
TSI2 is the index table containing the lengths and offsets for the glyph
programs that are contained in the TSI3 table. It uses the same format as
the TSI0 table.
"""
from fontTools.misc.py23 import *
f... |
import pygraphviz as pgv
from .printer import Printer
class GraphPrinter(Printer):
"""
Exports flows to graphviz
"""
def __init__(self, *args, **kwargs):
super(GraphPrinter, self).__init__(*args, **kwargs)
def new_obj(self):
return pgv.AGraph(strict=False, directed=True, rankdir='... |
import time
from os import getenv
from flask import jsonify, abort
from google.cloud import firestore
from google.oauth2 import id_token
from google.auth.transport import requests as g_requests
from api import (
process_ok_exam_upload,
is_admin,
clear_collection,
get_announcements,
get_email_from_... |
from sqlalchemy import Column, Integer, ForeignKey, DateTime
from sqlalchemy.sql.sqltypes import Boolean, String
from app.db.database import Base
class UserModel(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
username = Column(String, nullable=False, index=True)
di... |
# Copyright (c) 2016-present, Facebook, Inc.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import unittest
from typing import Callable
from ..get_exit_nodes import ExitNodeGenerator
from ..model_generator import Configuration
from .test_f... |
from random import randrange
from time import time
def bubble_sort(arr):
for i in range(len(arr)):
for j in range(len(arr)-1, i, -1):
if arr[j] < arr[j-1]:
# меняем элементы местами
arr[j], arr[j-1] = arr[j-1], arr[j]
return arr
def opt_bubble_sort(arr):
... |
import re
import sys
import json
import requests
from bs4 import BeautifulSoup
def scrape_nominate_movie(year):
film_index = "https://eiga.com/movie/"
re_time = re.compile(r"/\d*分/")
re_production_studio = re.compile(r"配給:[^<]*")
re_title = re.compile(r"映画「[^」]*」")
re_date = re.compile(r"\d*年\d*月... |
# 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 ... |
# Copyright 2017 Red Hat, Inc. <http://www.redhat.com>
#
# 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 b... |
from unittest import TestCase
import os
import os.path as osp
import numpy as np
from datumaro.components.annotation import (
AnnotationType, Bbox, Caption, Label, LabelCategories, Mask, Points,
Polygon, PolyLine,
)
from datumaro.components.converter import Converter
from datumaro.components.dataset import (
... |
import os
import numpy as np
import cv2
import json
import pandas as pd
import tensorflow as tf
from tensorboard.backend.event_processing import event_accumulator as ea
from matplotlib import pyplot as plt
from matplotlib import colors as colors
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanv... |
#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Creature()
result.template = "object/mobile/shared_giant_veermok.iff"
result.attribute_template_id = 9
result.st... |
print('Exercício Python #012 - Calculando Descontos')
a6 = float(input('Preço: '))
b6 = int(input('Desconto:'))
c6 = a6 * b6 / 100
d6 = a6 - c6
print(' O valor com o desconto de {} % é de {} Reais '.format(b6, d6)) |
import asyncio
import copy
import getpass
import logging
import os
import time
import uuid
import warnings
import yaml
import dask
import dask.distributed
import distributed.security
from distributed.deploy import SpecCluster, ProcessInterface
from distributed.utils import Log, Logs
import kubernetes_asyncio as kubern... |
from django.test import TestCase
from django.urls import reverse
from unittest import mock
from .fixtures import FixturesMixin
from .models import Person, Tab, User
import hashlib
# Create your tests here.
class TestRegister(FixturesMixin, TestCase):
def test_create_and_login(self):
self.client.post('/r... |
import p1.m1 |
"""
This test will initialize the display using displayio and draw a solid green
background, a smaller purple rectangle, and some yellow text.
"""
import board
import terminalio
import displayio
from adafruit_display_text import label
from adafruit_st7735r import ST7735R
# Release any resources currently in use for t... |
""" Class for the Sequence to sequence model for ATIS."""
import os
import torch
import torch.nn.functional as F
from . import torch_utils
from . import utils_bert
from data_util.vocabulary import DEL_TOK, UNK_TOK
from .encoder import Encoder, Encoder_Gnn
from .embedder import Embedder
from .token_predictor import ... |
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 15 10:58:44 2019
@author: DELL
"""
from __future__ import print_function, division
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def d(u, v):
diff = u - v
return diff.dot(diff)
def get_data(limit=None):
print("Reading in and tra... |
import string
import time
import threading
import urllib
import re
import io
import sys
from time import sleep
import pickle
import pandas as pd
import psycopg2
def formats(first, middle, last, domain):
"""
Create a list of 30 possible email formats combining:
- First name: [empty] | Full | Init... |
"""
SQLite backend for the sqlite3 module in the standard library.
"""
import datetime
import decimal
import functools
import math
import operator
import re
import statistics
import warnings
from itertools import chain
from sqlite3 import dbapi2 as Database
import pytz
from django.core.exceptions import ImproperlyCon... |
# imports - standard imports
import os.path as osp
import subprocess
# imports - test imports
import pytest
# imports - module imports
from ccapi.__attr__ import (
read,
pardir,
strip,
safe_decode,
sequence_filter,
get_revision
)
def call(*args, **kwargs):
subprocess.call(args, **kwargs)
... |
from sklearn import tree
from sklearn import neighbors
from sklearn import gaussian_process
#[height, weight, shoe size]
X = [[181,80,10],[161,70,6],[171,66,7],[176,88,7],[189,100,8],[141,80,5],[156,78,6],[161,50,6],[171,60,7],[151,78,7],[171,40,7]]
#Gender
Y = ['male','male','male','male','male','female','female','fe... |
import requests
from classes.login import Login
from classes.logger import logger
log = logger().log
with open('config/accounts.txt') as accounts_file:
accounts = accounts_file.read().splitlines()
def run(x):
req = requests.Session()
log("{} Attempting Login".format(x.split(':')[0]))
l = Login(req)... |
# Copyright 2015 Google LLC
#
# 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, s... |
""" Basic tests for Photos 5 on MacOS 10.15.7 """
import datetime
import os
import os.path
import pathlib
import sqlite3
import tempfile
import time
from collections import Counter, namedtuple
import pytest
import osxphotos
from osxphotos._constants import _UNKNOWN_PERSON
from osxphotos.utils import _get_os_version
... |
import os
def solve():
filepath = os.path.join(os.path.dirname(__file__), '013_numbers.txt')
with open(filepath) as f:
numbers = [int(x) for x in f]
return int(str(sum(numbers))[:10])
if __name__ == '__main__':
print(solve()) |
from django.conf import settings
import requests
import socket
BASE_HOST = '127.0.0.1'
PORT = 4040
class Ngrok(object):
def __init__(self, port=PORT, *args, **kwargs):
super(Ngrok, self).__init__(*args, **kwargs)
self.port = port
self._check_launch_ngrok()
def _check_launch_ngrok(s... |
# This file is not meant for public use and will be removed in SciPy v2.0.0.
# Use the `scipy.sparse` namespace for importing the functions
# included below.
import warnings
from . import _data
__all__ = [ # noqa: F822
'isscalarlike',
'matrix',
'name',
'npfunc',
'spmatrix',
'validateaxis',
]... |
import os
from urllib.error import URLError, HTTPError
from urllib.request import urlretrieve
import tqdm
import tarfile
import zipfile
import shutil
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
def download_file(
origin: str,
cache_subdir: str = "datasets") -> str:
fn... |
# Copyright 2021 The MLX Contributors
#
# SPDX-License-Identifier: Apache-2.0
# coding: utf-8
"""
MLX API
MLX API Extension for Kubeflow Pipelines # noqa: E501
OpenAPI spec version: 0.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_impo... |
import time
from contextlib import contextmanager
from collections import deque
import gym
from mpi4py import MPI
import tensorflow as tf
import numpy as np
import stable_baselines.common.tf_util as tf_util
from stable_baselines.common.tf_util import total_episode_reward_logger
from stable_baselines.common import exp... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'mslib/msui/ui/ui_topview_window.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_TopViewWindow(object):
def setupUi(self, Top... |
import os
import time
with open('hosts.txt') as file:
dump = file.read()
dump = dump.splitlines()
for ip in dump:
print("Verificando o IP", ip)
print("-" * 60)
os.system('ping -n 2 {}'.format(ip))
print("-" * 60)
time.sleep(5) |
# -*- coding: utf-8 -*-
'''
:codeauthor: Pedro Algarvio (pedro@algarvio.me)
:codeauthor: Alexandru Bleotu (alexandru.bleotu@morganstanley.com)
salt.utils.schema
~~~~~~~~~~~~~~~~~
Object Oriented Configuration - JSON Schema compatible generator
This code was inspired by `jsl`__, "A Python DSL... |
import numpy as np
from ..element_h1 import ElementH1
class ElementTetP2(ElementH1):
nodal_dofs = 1
edge_dofs = 1
dim = 3
maxdeg = 2
dofnames = ['u', 'u']
doflocs = np.array([[0., 0., 0.],
[1., 0., 0.],
[0., 1., 0.],
[0., ... |
import traceback
from pathlib import Path
import hashlib
import yaml
def get_media_dirs(media_dir_stream):
result = dict()
movie_dir_map = dict()
for media_location in media_dir_stream[0].replace('\n', '').replace('\r', '').split(','):
movie_dir_map[hashlib.md5(media_location.encode('utf-8')).hexd... |
import logging
import math
import os
import pickle
import re
import PIL.Image
import numpy as np
from mtcnn import MTCNN
from numpy import expand_dims
from sklearn import preprocessing, neighbors
from tensorflow_core.python.keras.models import load_model
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DATASET_D... |
"""
What do you want from this file?
1. I need to look up when to raise what.
Then read on the docstrings.
2. I have to add a new exception.
Make sure you catch it somewhere. Sometimes you'll realize you cannot catch it.
Especially, if your new exception indicates bug in the Raiden codebase,
you are no... |
import os
from io import open
from typing import Dict
from setuptools import find_packages, setup
here = os.path.abspath(os.path.dirname(__file__))
about: Dict[str, str] = {}
path = os.path.join(here, "awswrangler", "__metadata__.py")
with open(file=path, mode="r", encoding="utf-8") as f:
exec(f.read(), about)
w... |
# 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 ... |
from django.db import models
from wagtail.wagtailadmin.edit_handlers import (
FieldPanel, ObjectList, StreamFieldPanel, TabbedInterface
)
from wagtail.wagtailcore import blocks
from wagtail.wagtailcore.fields import StreamField
from wagtail.wagtailcore.models import PageManager
from data_research.blocks import (
... |
from __future__ import annotations
from time import sleep
from detect import DetectionSession, DetectPlugin
from typing import Any, List
import numpy as np
import cv2
import imutils
from gi.repository import GLib, Gst
from scrypted_sdk.types import ObjectDetectionModel, ObjectDetectionResult, ObjectsDetected
class Ope... |
# coding=utf-8
import sys
import signal
import time
from multiprocessing import Process
from allocator import Allocator, Event
class Manager(object):
"""A manager manage multi allocators, when told to stop, manager would tell the allocator to stop."""
def __init__(self, cfg_list):
self.allocator_li... |
# -*- coding: utf-8 -*-
# --------------------------------------------------------
# Licensed under the terms of the BSD 3-Clause License
# (see LICENSE for details).
# Copyright © 2018-2021, A.A Suvorov
# All rights reserved.
# --------------------------------------------------------
"""Tests prototype.py"""
from patt... |
import log
log.basicConfig(level=log.ERROR) # 设置日志输出级别
# 获取logger对象,如果不指定name则返回root对象,多次使用相同的name调用getLogger方法返回同一个logger对象
log = log.getLogger("error")
log.error("Test error message!!") |
"""
Python - Amortized Analysis
Amortized analysis involves estimating the run time for the sequence of operations in a program without taking into consideration the span of the data distribution in the input values. A simple example is finding a value in a sorted list is quicker than in an unsorted list. If the lis... |
import barnum, random, time, json, requests, math, os
from mysql.connector import connect, Error
from kafka import KafkaProducer
# CONFIG
userSeedCount = 10000
itemSeedCount = 1000
purchaseGenCount = 500000
purchaseGenEveryMS = 100
pageviewMultiplier = 75 # Translates to 75x purchases, currently 750/... |
import numpy as np
from gcn.graphconv import ap_approximate
def Model17(adj, alpha, y_train, y_test):
k = int(np.ceil(4 * alpha))
prediction, time = ap_approximate(adj, y_train, alpha, k)
predicted_labels = np.argmax(prediction, axis=1)
prediction = np.zeros(prediction.shape)
prediction[np.arange(... |
import django.dispatch
adoption_level_change = django.dispatch.Signal(providing_args=["level", "request"])
blurb_read = django.dispatch.Signal(providing_args=["request"]) |
# coding: utf-8
"""
Copyright 2016 SmartBear Software
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 l... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Bioindustrial-Park: BioSTEAM's Premier Biorefinery Models and Results
# Copyright (C) 2022-2023, Sarang Bhagwat <sarangb2@illinois.edu> (this biorefinery)
#
# This module is under the UIUC open-source license. See
# github.com/BioSTEAMDevelopmentGroup/biosteam/blob/mas... |
"""
Provides support for working with BOSS targets.
In qusp, a target is identified by a unique plate-mjd-fiber. They are implemented as dictionaries and
must have at least 'plate', 'mjd', and 'fiber' keys specified. The Target model is designed to be flexible,
in that other attributes can be added to targets as neede... |
#
# 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 appl... |
import os
import sys
import shutil
import invoke
from invoke import task
from .utils import bin_name, get_build_flags, get_version_numeric_only, load_release_versions
from .utils import REPO_PATH
from .build_tags import get_build_tags, get_default_build_tags, LINUX_ONLY_TAGS, REDHAT_AND_DEBIAN_ONLY_TAGS, REDHAT_AND_D... |
import itertools
from emoji_chengyu.puzzle import gen_puzzle
def emoji_chengyu():
N = 100
pg = gen_puzzle()
puzzles = list(itertools.islice(pg, N))
puzzles.sort(key=lambda p: sum(p.mask), reverse=True)
M = 20
for puzzle in puzzles[:M]:
print(''.join(puzzle.puzzle), puzzle.chengyu_ite... |
# -*- coding: utf-8 -*-
# MooQuant
#
# Copyright 2011-2015 Gabriel Martin Becedillas Ruiz
#
# 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
#
# ... |
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from future.builtins import * # NOQA
from struct import unpack
from obspy.core.util.libnames import _load_cdll
# Import shared libsegy
clibsegy = _load_cdll("segy")
def unpack_head... |
#!/usr/bin/python
import urllib2
import xml.etree.ElementTree as ElementTree
import re
def refine_table(table):
result = table
result = re.sub(r"<td.*?>", "<td>", result)
result = re.sub(r"<tr.*?>", "<tr>", result)
result = re.sub(r"<a.*?>(.*?)</a>", "\\1", result)
result = re.sub(r"<span.*?>(.*?)... |
import datetime
from django.shortcuts import render, get_object_or_404
# Create your views here.
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.status import HTTP_200_OK
from rest_framework.views import APIView
from content.models import Content
from ... |
import sys, os.path
import gensim
from gensim.models import Word2Vec
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
def plot2d_demo(model, words=None):
assert (
model.vector_size >= 2
), "This function expects a model of size 2 (2-dimension word vectors) or h... |
# Copyright 2019 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... |
import numpy as np
import matplotlib.pyplot as plt
# Plot a spiral dataset
def generateArm(rotation, step):
theta = np.random.rand(500) * step
r = np.exp(theta) - 1
x = r * np.cos(theta) + (np.random.rand(500) - 0.5) / 7
y = r * np.sin(theta) + (np.random.rand(500) - 0.5) / 7
x, y = x * np.cos(r... |
"""
The Code contains functions to calculate univariate statistics for categorical features, given a dataset.
"""
import numpy as np
from parallelm.mlops.stats.health.histogram_data_objects import CategoricalHistogramDataObject
class CategoricalHistogram(object):
"""
Class is responsible for providing fit ... |
from . import models
from . import controllers |
from django.apps import AppConfig
class ApiConfig(AppConfig):
name = 'vaccine_card.api' |
# coding=utf-8
# Author: Tom Lambert
# Content: Implementierung der Sort-Klasse für ab6.
class Sort(object):
"""Implementiert Sortier-Algorithmen mit der Möglichkeit einer statistischen Auswertung"""
def __init__(self):
self.counter_swap = 0 # entspricht ca 2 Elementabrufen und 2 Elementzuweisungen
... |
import _plotly_utils.basevalidators
class TickangleValidator(_plotly_utils.basevalidators.AngleValidator):
def __init__(
self, plotly_name="tickangle", parent_name="icicle.marker.colorbar", **kwargs
):
super(TickangleValidator, self).__init__(
plotly_name=plotly_name,
p... |
import tensorflow as tf
def get_width_upright(bboxes):
with tf.name_scope('BoundingBoxTransform/get_width_upright'):
bboxes = tf.cast(bboxes, tf.float32)
x1, y1, x2, y2 = tf.split(bboxes, 4, axis=1)
width = x2 - x1 + 1.
height = y2 - y1 + 1.
# Calculate up right point of b... |
import os
import tqdm
import glob
import fiona
import geopandas as gpd
from fire import Fire
def sn7_convert_geojsons_to_csv(json_dirs, output_csv_path, population='proposal'):
'''
Convert jsons to csv
Population is either "ground" or "proposal"
'''
first_file = True # switch that will be turned... |
# -*- coding: utf-8
from __future__ import absolute_import
import unittest
from oaxmlapi import commands, datatypes
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
class TestModifyOnConditionClass(unittest.TestCase):
def test_str(self):
slip = data... |
# Copyright (c) 2018 PaddlePaddle 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 app... |
#!/usr/bin/env python3
import uinput
from elm327 import ELM327, PROTOCOLS
from mrcrowbar import models as mrc
import math
import time
from optparse import OptionParser
class OptParser( OptionParser ):
def format_epilog( self, formatter ):
return '\n{}\n'.format( '\n'.join( [formatter._format_text( x ) fo... |
def is_leap(year):
leap = False
if year>=1900:
if year%4 == 0:
leap = True
if year%100 == 0 and year%400 != 0:
leap = False
return leap
year = int(input()) |
import itertools
from ... import options as opts
from ... import types
from ...charts.chart import RectChart
from ...globals import ChartType
class Scatter(RectChart):
"""
<<< Scatter >>>
The scatter diagram on the rectangular coordinate system can be used to
show the relationship between x and y of... |
import requests
import json
from stockfish import Stockfish
stockfish = Stockfish('stockfish_20090216_x64_bmi2.exe', parameters={"Threads": 8, "Minimum Thinking Time": 300})
stockfish.set_depth(15)
stockfish.set_skill_level(25)
api_key = 'REPLACE_WITH_API_KEY'
headers = {'Authorization': f'Bearer {api_key}'}
game_st... |
import json
from .theExceptions import (CreationError, DeletionError, UpdateError)
class Index(object) :
"""An index on a collection's fields. Indexes are meant to de created by ensureXXX functions of Collections.
Indexes have a .infos dictionary that stores all the infos about the index"""
def __init__(self... |
# coding=utf8
from flask import Flask, render_template
from flask_restful.utils import cors
from flask_cors import CORS, cross_origin
import config
import models
from resources_v1.predictions import predictions_api_v1
from templates.templates import home
app = Flask(__name__)
CORS(app)
app.register_blueprint(predic... |
import time
import os
import datetime
import json
import logging
import requests
from utils.server_chan import server_push
from utils.qq_email import qq_email_push
from utils.qmsg import qmsg_push
from login import CampusLogin
def initLogging():
logging.getLogger().setLevel(logging.INFO)
logging.basicConfig(... |
# Copyright 2018 D-Wave Systems 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 or agreed to in wri... |
import cv2;
class Display(object):
def __init__(self):
pass;
def showFrame(self, frame, windowName = "frame"):
cv2.namedWindow(windowName, cv2.WINDOW_NORMAL);
cv2.imshow(windowName, frame);
def end(self):
cv2.destroyAllWindows(); |
from django.db import connection, models
from django.db.models import OuterRef, Subquery
from django.utils import timezone
from simple_history.utils import get_change_reason_from_object
class HistoryDescriptor:
def __init__(self, model):
self.model = model
def __get__(self, instance, owner):
... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... |
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... |
# --------------
# Importing header files
import numpy as np
#New record
new_record=[[50, 9, 4, 1, 0, 0, 40, 0]]
#Code starts here
#Loading data file and saving it into a new numpy array
data = np.genfromtxt(path, delimiter=",", skip_header=1)
print(data.shape)
#Concatenating the new record to the existing ... |
# ------------------------------------------------------------------------------
# Copyright (c) 2013-2022, Nucleic Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ----------------------------------------------... |
"""Module for the XacroFile substitution class."""
from pathlib import Path
from typing import Text, cast
import xacro
from launch.launch_context import LaunchContext
from launch.some_substitutions_type import SomeSubstitutionsType
from launch.substitution import Substitution
from launch.substitutions import Substit... |
"""The file has unit tests for the AWSBidAdvisor."""
import unittest
from mock import patch, MagicMock
import datetime
from dateutil.tz import tzutc
from cloud_provider.aws.aws_bid_advisor import AWSBidAdvisor
REFRESH_INTERVAL = 10
REGION = 'us-west-2'
class AWSBidAdvisorTest(unittest.TestCase):
"""
Tests f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.