content stringlengths 5 1.05M |
|---|
import argparse
import logging
import os
import subprocess
import sys
DEFAULT_OUTPUT_DIRECTORY_NAME = "converted-text"
DEFAULT_CHECK_COMMAND = "which"
WINDOWS_CHECK_COMMAND = "where"
TESSERACT_DATA_PATH_VAR = 'TESSDATA_PREFIX'
VALID_IMAGE_EXTENSIONS = [".jpg", ".jpeg", ".gif", ".png", ".tga", ".tif", ".bmp"]
def cr... |
# Copyright IBM Corp, All Rights Reserved.
#
# SPDX-License-Identifier: Apache-2.0
#
from . cluster import release_cluster, delete_cluster
|
img_enhanc_alg = ""
input_img = []
with open("input/day20.txt") as inp:
flag = True
for vrst in inp:
if flag:
flag = False
img_enhanc_alg = vrst[:-1]
elif vrst == "\n":
continue
else:
input_img.append(list(vrst[:-1]))
def bin_to_int(b):
... |
from typing import Dict, Set
from pynvml import nvmlInit, nvmlDeviceGetCount, nvmlDeviceGetHandleByIndex, nvmlDeviceGetMemoryInfo, nvmlShutdown
def get_gpus_info() -> Dict:
gpu_info = dict()
nvmlInit()
for i in range(nvmlDeviceGetCount()):
handle = nvmlDeviceGetHandleByIndex(i)
gpu_mem_in... |
## Calculation of Einstein oscillator contributions to entropy (S)
import math
import numpy as np
from scipy.integrate import quad
#import params.py for all input parameters
from params import *
##########################################################################
S_e = []
WE_array = [wE_1, wE_2,... |
from django.db import models
from django.contrib.auth.models import User
from datetime import datetime
class UserProfile(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE) #extending user model
name = models.CharField(max_length=100) #username as per the db
mail_id=models.CharField(max_length... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.quantization import QuantStub, DeQuantStub, fuse_modules
class ConvBNReLU(nn.Sequential):
"""
三个层在计算过程中应当进行融合
使用ReLU作为激活函数可以限制
数值范围,从而有利于量化处理。
"""
def __init__(self, n_in, n_out,
kernel_s... |
import os
import sys
from setuptools import find_packages, setup
from setuptools.command.test import test as TestCommand
import edutalk
BASE_DIR = os.path.dirname(__file__)
class PyTest(TestCommand):
user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")]
def initialize_options(self):
... |
#coding:utf-8
__author__ = 'phabio'
import MySQLdb
#-----------MySQL测试代码-------------
def mysql_test():
try:
sql='select * from proc'
conn=MySQLdb.connect(host='127.0.0.1',user='root',passwd='1234',db='mysql',port=3306)
cur=conn.cursor()
cur.execute(sql)
print 'conn:%s' %... |
from app.core.security import get_password_hash
from fastapi import HTTPException, status
from app.db.schemas import user as user_schema
from app.db.models.User import User
from sqlalchemy.orm import Session
from typing import List
def get_user(db: Session, user_id: int):
user = db.query(User).filter(User.id == u... |
class Solution:
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
length = len(nums)
half = length // 2
while True:
best = nums[random.randrange(length)]
count = 0
for elem in nums:
i... |
# Generated by Django 3.1.8 on 2021-04-12 08:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("core", "0075_various_model_field_options"),
]
operations = [
migrations.AddField(
model_name="report",
name="origina... |
# Copyright 2013-2018 ARM Limited
#
# 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 w... |
from ..base.base_delete_connector import BaseDeleteConnector
import json
from .....utils.error_response import ErrorResponder
class GuardiumDeleteConnector(BaseDeleteConnector):
def __init__(self, api_client):
self.api_client = api_client
def delete_query_connection(self, search_id):
# Not im... |
import itertools
from collections import OrderedDict, namedtuple
import numpy as np
from sympy import Indexed
from devito.ir.support import Stencil
from devito.exceptions import DSEException
from devito.symbolics import retrieve_indexed, q_indirect
__all__ = ['collect']
def collect(exprs):
"""
Determine gr... |
# '''
# (c) REACT LAB, Harvard University
# Author: Ninad Jadhav
# '''
#!/usr/bin/env python3
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import json
import glob, os
import seaborn as sns
from mpl_toolkits.mplot3d import Axes3D
import argparse
SMALL_SIZE = 8
MEDIUM_SIZE = 10
BIGGER_SIZE... |
"""
Content-Length header validators to use in the mock.
"""
from typing import Dict
from mock_vws._services_validators.exceptions import (
AuthenticationFailure,
ContentLengthHeaderNotInt,
ContentLengthHeaderTooLarge,
)
def validate_content_length_header_is_int(
request_headers: Dict[str, str],
... |
#Brian Condon
#Trying to access just the virginica data
#23/4/18
import numpy
#I created another csv file after having trouble splitting up the columns to just the setosa file.
data = numpy.genfromtxt('data/virginica.csv', delimiter = ',')
#Virginica Petal Length
virginpl = data[:,2]
meanvirginpl = numpy.mean(data[... |
# -*- coding: utf-8 -*-
"""
idfy_rest_client.models.person_person_information
This file was automatically generated for Idfy by APIMATIC v2.0 ( https://apimatic.io )
"""
from idfy_rest_client.api_helper import APIHelper
class PersonPersonInformation(object):
"""Implementation of the 'Person.P... |
from unittest import TestCase
import matplotlib.pyplot as plt
import data_visualization as dv
from day_container import DayContainer
from day_deck import DayDeck
from datetime import date
class Test(TestCase):
def setUp(self):
pass
def test_presentation_dendrogram(self):
linkage_list = [[0.0,... |
from invoke import task
@task(aliases=["f"])
def black(c):
c.run("black .")
@task(aliases=["t"])
def test(c):
c.run("coverage run -m pytest --junitxml=junit.xml")
c.run("coverage xml")
@task(aliases=["l"])
def lint(c):
c.run("pycodestyle --max-line-length=120 .")
|
import asyncio
import json
import logging
import sys
from asyncio.events import AbstractEventLoop
from datetime import datetime, timezone
from typing import Any, AsyncGenerator, Callable, Optional, Union
from ansq.tcp import consts
from ansq.tcp.exceptions import (
ConnectionClosedError,
NSQUnauthorized,
P... |
import unittest
import pycqed as pq
import os
import matplotlib.pyplot as plt
from pycqed.analysis_v2 import measurement_analysis as ma
from pycqed.analysis_v2 import Two_state_T1_analysis as Ta
class Test_efT1_analysis(unittest.TestCase):
@classmethod
def tearDownClass(self):
plt.close('all')
@c... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('courses', '0014_delete_meta'),
]
operations = [
migrations.CreateModel(
name='Time',
fields=[
... |
# Copyright (c) 2018 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 ... |
##########################################################################
#
# pgAdmin 4 - PostgreSQL Tools
#
# Copyright (C) 2013 - 2020, The pgAdmin Development Team
# This software is released under the PostgreSQL Licence
#
##########################################################################
import json
import... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-11-02 00:12
from __future__ import unicode_literals
import cointrol.core.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0002_auto_20171102_0054'),
]
operations = [
mig... |
from setuptools import setup, find_namespace_packages
setup(
name="cart",
version="0.1.0",
description="LI tech challenge",
author="Felipe Galvao",
packages=find_namespace_packages(),
)
|
# Standard library
# 3rd party packages
import pytest
import numpy as np
import pandas as pd
# Local source
from parametrization_clean.domain.neural_network.extract_data import (individuals_to_features_df,
individuals_to_features_and_outputs_df)
fr... |
import os
import torchvision.datasets as datasets
import torchvision.transforms as transforms
from torch.utils.data import Dataset
import zipfile
import urllib.request
import shutil
import torch
from PIL import Image
import pandas as pd
__all__ = names = ('TinyImagenet200', 'Imagenet1000','MiniImagenet')
class Tin... |
import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Auth:
CLIENT_ID = ('763939110671-5fdvscgtkn6veo1j48sc5nfisvv1hlcj'
'.apps.googleusercontent.com')
CLIENT_SECRET = '4AVsXRma87DjZbloWjd1xEte'
REDIRECT_URI = 'https://localhost:5000/gCallback'
AUTH_URI = 'https://accounts.google.... |
#!/usr/bin/env python3
from lib.lcmd import send_command
from lib.lfiles import send_getfile_command, send_putfile_command
from lib.colors import colored, colored_for_input
from lib.general_utils import LEXResult, MAX_BODY_SIZE, readfile, writefile, create_tar_file
from lib.splash_utils import *
from lib.config import... |
# Generated by Django 3.0.6 on 2020-05-10 12:50
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('oneevent', '0010_remove_... |
import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import os
import time
# img = cv.imread('./teste_2.png')
img = cv.imread('./darcy_surgery_basis.png')
# img = cv.bitwise_not(img)
img_cropped = img[100:400,300:600]
img_HSV = cv.cvtColor(img, cv.COLOR_BGR2HSV)
# cv.circle(i... |
from typing import Union, Any # I didn't do this, pycharm did this for me.
import matplotlib.pyplot as plt
import datetime
import seaborn as sns
import pandas as pd
# this data comes from ECDC testing data
# https://opendata.ecdc.europa.eu/covid19/testing/csv/data.csv
# These are two functions which I have tried to... |
from flask import jsonify
from app.api import bp
@bp.route('/')
def index():
return jsonify({"status": 200})
|
# Generated by Django 2.1.5 on 2019-01-09 23:14
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('control', '0012_remove_mptt_on_theme'),
]
operations = [
migrations.AlterModelOptions(
name='questionnaire',
options={'order... |
# Copyright (c) 2018, Zebula Sampedro, CU Research Computing
import unittest
from traitlets import (
Float,
Integer,
)
from optionsspawner.forms import NumericalInputField
class NumericalInputFieldTestCase(unittest.TestCase):
"""Tests for optionsspawner.forms.characterfield.NumericalInputField."""
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Решите задачу: создайте словарь, связав его с переменной school , и наполните данными,
# которые бы отражали количество учащихся в разных классах (1а, 1б, 2б, 6а, 7в и т. п.).
# Внесите изменения в словарь согласно следующему: а) в одном из классов изменилось
# коли... |
from scapy.all import *
print('Start Scanning')
ans, unans = sr(IP(dst="192.168.0.2-254")/ICMP())
print(ans)
print(unans)
print('*' * 80)
ans, unans = sr( IP(dst="192.168.0.*")/TCP(dport=80,flags="S") )
print(ans)
print(unans)
print('*' * 80) |
# Copyright 2019 The Magenta Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
from numpy import add, argmax as np_argmax, array, concatenate
from pandas import DataFrame
from torch import argmax, no_grad
from torch.nn import CrossEntropyLoss
from torch.optim.lr_scheduler import ReduceLROnPlateau
from torch.utils.data import DataLoader
from tqdm.auto import tqdm
def train(model, num_epochs, tra... |
"""
Available configurations:
prtr_db_file_path: full file path in the filesystem to the raw PRTR data in
.accdb file format.
country_code: country code by which the data is filtered in the import.
csv_out_dir: directory to which the imported data is saved in CSV format
(facilities.csv & rel... |
from django.conf.urls import url
from .views import group_list, group_detail, create_group, join_group, edit_group, edit_group_save
urlpatterns = [
url(r'^list/$', group_list, name='group_list'),
url(r'^(?P<pk>[0-9]+)/$', group_detail, name='group_detail'),
url(r'^create/$', create_group, name='create_gro... |
from pytest import raises
from mite import zmq
from mite.utils import _msg_backend_module, spec_import
def test_spec_import():
# Perhaps hacky that I used another imported thing
# Seemed most concise way to test
spec = "mite.utils:_msg_backend_module"
assert spec_import(spec) == _msg_backend_module
... |
import pytest
from requests import get
from urllib.parse import urljoin
def test_new_story_page(wait_for_api, login_user):
"""
GIVEN a user has logged in (login_user)
WHEN the '/stories/newstory' page is navigated to (GET)
THEN check the response is valid and page title is correct
"""
request_s... |
VERSION = (1, 3)
__version__ = ".".join(map(str, VERSION))
from .filters import (
MultiSelectFilter, MultiSelectRelatedFilter, MultiSelectDropdownFilter,
MultiSelectRelatedDropdownFilter, DropdownFilter, ChoicesDropdownFilter,
RelatedDropdownFilter, BooleanAnnotationFilter
)
|
# -*- coding: utf-8 -*-
'''
Monit service module. This module will create a monit type
service watcher.
'''
from __future__ import absolute_import
# Import python libs
import re
# Import salt libs
import salt.utils
# Function alias to make sure not to shadow built-in's
__func_alias__ = {
'id_': 'id',
'reload... |
"""A simple example plugin."""
def replace(m, **kwargs):
"""Replace with groups."""
text = "Here are your groups: "
for group in m.groups():
if group is not None:
text += "(%s)" % group
return text
|
import paho.mqtt.client as mqtt
from busylight.lights.embrava import Blynclight
import logging
logging.basicConfig(level=logging.INFO)
class busylamp:
lamp_color = (255, 255, 255)
state = False
def __init__(self):
self.light = Blynclight.first_light()
# self.light.blink((255, 255, 255), 1... |
#
# 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... |
#!/usr/bin/env python3
# vim: set et ts=4 sw=4:
# Written for python 3.5
"""
Solution to my daughter's beads packing puzzle, [Goo-Seul] puzzle in Korean.
It seems that finding all possible solutions needs
very long time (NP-complete). Thus let user place some pieces
before this program solve() with the rest of pieces... |
from flask import jsonify, request, url_for, g, current_app, render_template
from app import db
from app.deals.models import Deal
from app.api import bp
from app.api.auth import token_auth
from app.api.errors import bad_request
from app.email import send_email
@bp.route('/deals/<int:id>', methods=['GET'])
@token_auth.... |
# -*- encoding: utf-8 -*-
# Copyright (c) 2016 b<>com
#
# Authors: Vincent FRANCOISE <vincent.francoise@b-com.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/li... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest
from pytest import raises, approx, mark
from EasyVision.vision import *
from EasyVision.processors import *
import cv2
import json
import numpy as np
from tests.common import *
@mark.main
def test_stereo_camera():
camera = StereoCamera(
left_cam... |
# Copyright 2015 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 req... |
"""
事前準備に
$ pip install pandas
$ pip install openpyxl
$ pip install xlrd
が必要
リファレンス
https://pandas.pydata.org/pandas-docs/stable/reference/index.html
"""
import pandas as pd
import openpyxl
excel_in_path1 = './data/excel_in_header_2sheet.xlsx'
print("********何も指定せず読み込み********")
# 何も指定しない場合は最初のシートになる
df = pd.rea... |
import unittest
import binascii
from neo3 import vm, contracts
from neo3.core import syscall_name_to_int
from tests.contracts.interop.utils import test_engine
class StdLibTestCase(unittest.TestCase):
def test_binary_serialization(self):
engine = test_engine(has_snapshot=True)
original_item = 100
... |
# global variables will be assigned here
# can be imported in any module to make life easier.
from userbot.config import Config
import asyncio
from telethon.tl.types import ChannelParticipantsAdmins
from userbot import ALIVE_NAME, AUTOPIC_FONT_COLOUR, AUTOPIC_FONT, AUTOPIC_COMMENT
AUTO_PIC_FONT = str(AUTOPIC_FONT) if... |
import typing
from UniGrammarRuntime.backends.multilanguage.CoCoR import CoCoRParser, CoCoRParserFactory
from UniGrammarRuntime.DSLMetadata import DSLMetadata
from UniGrammarRuntime.grammarClasses import LL
from UniGrammarRuntime.ToolMetadata import Product, ToolMetadata
from UniGrammarRuntimeCore.ICompiler import Dum... |
import re
import os
import sys
import json
import collections
import logging
import argparse
from e2edutch import util
from e2edutch import conll
logger = logging.getLogger('e2edutch')
class DocumentState(object):
def __init__(self):
self.doc_key = None
self.text = []
self.sentences = []... |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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... |
"""
A collection of tools for working with Nastran files
"""
from .bulk import *
from .n2p import *
from .op2 import *
from . import op4
|
import argparse
import time
from tokenize import String
from pyspark.sql import SparkSession
from pyspark.sql.types import StructType, StructField, FloatType, LongType, DecimalType, IntegerType, StringType, DateType
from schema import *
def run_tpch_q03(source_lineitem, source_orders, source_customers, output_uri):... |
import pyttsx
engine = pyttsx.init()
engine.say('Hello World')
engine.runAndWait()
|
import cv2
import numpy as np
import sys
import json
import requests
image = "pics/test_face.jpg"
if len(sys.argv) >= 2:
image = sys.argv[1]
color_img=cv2.imread(image)
shape = '['+str(color_img.shape)[1:-1]+']'
print(shape)
imagedata = json.dumps(color_img.tolist())
data = '{"inputs":[{"name":"input","datatype":... |
# Collection of classes for loading the raw data without any preprocessing from the original file
# formats and directory structures of the original datasets.
import os
import glob
from abc import ABC, abstractmethod
import numpy as np
import pandas as pd
class BaseHandler(ABC):
def __init__(self, base_dir):
... |
#
# Copyright 2018-2019 IBM Corp. 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 applicable law... |
import ast
import collections
import os
import subprocess
def run_command(command):
try:
return subprocess.check_output(command.split())
except subprocess.CalledProcessError as e:
print("command '{}' return with error (code {}): {}".format(e.cmd, e.returncode, e.output))
def get_user_queue(u... |
#!/usr/bin/python
#
# Copyright 2015 Google Inc. 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 b... |
import abc
class AbstractCar(metaclass=abc.ABCMeta):
@abc.abstractproperty
def description(self):
pass
@abc.abstractproperty
def cost(self):
pass
|
#!/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates
import argparse
import datetime
import json
import math
import multiprocessing
import os
import pathlib
import platform
import re
import signal
import subprocess
import sys
import time
# Iterate every second
interval = 1
USER_HZ = os.sysconf(os.sy... |
# -*- coding:utf-8 -*-
"""
生成测试用例的代码
当Case的编码方式way使用shiwu的时候,需要把实物组件,转变成代码
"""
import json
import random
from tcase.models import Case, Shiwu
shiwu_data_model = '''
data_{id} = ShiwuDataHandle(body={body}, cycle={cycle})
'''
shiwu_code_model = '''
def shiwu_{id}(l):
data = data_{id}.get()
if data:
l... |
#
# Copyright (c) 2021 The Markovflow Contributors.
#
# 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... |
from django.test import TestCase
import factory
import factory.django
from passsystem.models import Pass, User, Organisation, Roles, Vehicle, Identity
class UserFactory(factory.django.DjangoModelFactory):
class Meta:
model = User
#user_id = models.AutoField(primary_key=True)
user_cre... |
"""Tests for the :mod:`assertionlib.functions` module."""
from collections import OrderedDict
from assertionlib import assertion
from assertionlib.functions import get_sphinx_domain
def test_get_sphinx_domain() -> None:
"""Tests for :func:`~assertionlib.functions.get_sphinx_domain`."""
v1 = get_sphinx_domai... |
simple_example = "x > 42 AND y != true OR z == 'yes'"
parentheses = "(x <= 42 OR y == 'yes' ) AND (y == 'no' OR x >= 17)"
operators_precedence = "x < 5.15 OR x > 10 AND y == 'eligible'"
implicit_boolean_cast = "z OR x AND y"
constant_statements = "444 AND True OR 'yes'"
|
"""Unit test package for {{cookiecutter.project_slug}}."""
|
import unittest
from typing import List, Optional, Union, Dict
import marshmallow
from marshmallow_dataclass import dataclass
class TestClassSchema(unittest.TestCase):
def test_simple_union(self):
@dataclass
class IntOrStr:
value: Union[int, str]
schema = IntOrStr.Schema()
... |
# Copyright 2015-2017 ARM Limited
#
# 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 w... |
# -*- coding: utf8 -*-
"""
*URL Watcher* Plugin
--------------------
Watches HTTP/S URLs and gives detailed info when URLs are from YouTube or 4chan. Otherwise if it's a page, it shows the page title;
if it's a binary file, shows file size and file type.
Bot ignores URLs when message has ``!nk`` in it
"""
im... |
import datetime
import random
from django.core.cache import cache
from django.core.cache.utils import make_template_fragment_key
from django.core.management.base import BaseCommand, CommandError
from django.db.models import Min
from main.models import GeneratedQ
DAILY_COUNT = 25
class Command(BaseCommand):
help... |
# Generated by Django 1.11.6 on 2018-01-29 18:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("confirmation", "0005_confirmation_realm"),
]
operations = [
migrations.AddField(
model_name="realmcreationkey",
nam... |
import math
from ev3dev2simulator.state.RobotSimulator import RobotSimulator
from ev3dev2simulator.state.WorldState import WorldState
from ev3dev2simulator.config.config import get_simulation_settings
class WorldSimulator:
def __init__(self, world_state: WorldState):
self.world_state = world_state
... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: agent.proto
"""Generated protocol buffer code."""
from google.protobuf.internal import enum_type_wrapper
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf... |
#!/usr/bin/env python3.6
import bulleter
def read_file(this_file):
a = bulleter.read_file(this_file)
if a == None:
print("Text processing Unsuccessful!")
else:
print("Successful! Check project folder for new.txt document")
def processor():
bulleter.process_document()
def output():
... |
# -*- coding:utf-8 -*-
'''
Some common function used by the CMS.
'''
import uuid
import random
import logging
import time
import hashlib
import re
from difflib import HtmlDiff
import markdown
from markdown.extensions.wikilinks import WikiLinkExtension
from playhouse.postgres_ext import PostgresqlExtDatabase
import to... |
#
# liberator:utilities.py
#
# The Initial Developer of the Original Code is
# Minh Minh <hnimminh at[@] outlook dot[.] com>
# Portions created by the Initial Developer are Copyright (C) the Initial Developer.
# All Rights Reserved.
#
import syslog
import json
import random
from threading import Thread
from uuid impor... |
import FWCore.ParameterSet.Config as cms
# common and strip files
totemGeomXMLFiles = cms.vstring(
'Geometry/CMSCommonData/data/materials.xml',
'Geometry/CMSCommonData/data/rotations.xml',
'Geometry/CMSCommonData/data/extend/cmsextent.xml',
'Geometry/CMSCommonData/data/cms/2017/v1/cms.xml',
'Geomet... |
# Game Menus
# This script stores the blueprints for different menu's
import os
import game
def title_screen():
os.system('clear') # Clears the screen
print(
"""
##############################
# Welcome to the Text RPG! #
##############################
- Play -
- Help -... |
from .globals import AwsApiGateway, AwsDynamoDB, AwsLambda, HttpHeaders, SkillItem
from .messages import ErrorMessages
__all__ = ["AwsApiGateway", "AwsDynamoDB", "AwsLambda", "ErrorMessages", "HttpHeaders", "SkillItem"]
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
import json
import os
import sys
import re
import hashlib
from datetime import datetime, timedelta
import locale
locale.setlocale(locale.LC_ALL, 'C')
import dateparser
## try a few common formats first, then fall back to date parser (slow)
def _text_to_datetime( text ):
... |
import os,socket,struct,json,re,hashlib
def myfloat(value, prec=4):
""" round and return float """
return round(float(value), prec)
# F = (C × 9/5) + 32
def CtoF(value):
return (float(value) * 9/5) + 32
def id_to_address(address,slen=14):
slen = slen * -1
m = hashlib.md5()
m.up... |
#import sys
#sys.path.insert(0, '/home/len/data/fotos.fotos')
from fotos import app as application |
#!/usr/bin/env python
# Copyright (c) 2016 Cisco and/or its affiliates.
# 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... |
# -*- coding: utf-8 -*-
#
# || ____ _ __
# +------+ / __ )(_) /_______________ _____ ___
# | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \
# +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
# || || /_____/_/\__/\___/_/ \__,_/ /___/\___/
#
# Copyright (C) 2017 Bitcraze AB
#
# Th... |
# -*- coding: utf-8 -*-
'''
The core behaviors used by minion and master
'''
# pylint: disable=W0232
# Import python libs
import time
import os
import multiprocessing
import logging
# Import salt libs
import salt.daemons.masterapi
from raet import raeting
from raet.lane.stacking import LaneStack
from raet.lane.yardin... |
import json
import logging
import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
@classmethod
def init_app(cls, app):
"""Send logs to stdout."""
file_handler = logging.StreamHandler()
file_handler.setLevel(logging.WARNING)
app.logger.addHandler(file_han... |
#Miaosen Zhou
from HB_Function import FBDunction
import cv2
#from imutils.video.pivideostream import PiVideoStream
#import imutils
import time
import numpy as np
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
body_cascade = cv2.CascadeClassifier('haarcascade_fullbody.xml')
class VideoCam... |
Solution to [Re.findall() & Re.finditer()](https://www.hackerrank.com/challenges/re-findall-re-finditer) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.