content stringlengths 5 1.05M |
|---|
import pandas as pd
from input_output.Saver import Saver
from joblib import dump, load
from os.path import isfile
# Saver specific for the Titanic task
# The Saver saves the predictions to an submission file
class TitanicSaver(Saver):
def save_predictions(self, predictions, file_name):
df = pd.DataFrame(pr... |
# Copyright 2020 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
# -*- coding: utf-8 -*-
"""
==================================================
Example demonstrating Contour Domain in ShapeWorks
==================================================
"""
import os
import glob
import shapeworks as sw
import subprocess
import numpy as np
from ShapeCohortGen.CohortGenerator import Supershap... |
from django.apps import AppConfig
class Intro2AppConfig(AppConfig):
name = 'intro2App'
|
"""MQTT component mixins and helpers."""
from __future__ import annotations
from abc import abstractmethod
from collections.abc import Callable
import json
import logging
import voluptuous as vol
from homeassistant.const import (
ATTR_CONFIGURATION_URL,
ATTR_MANUFACTURER,
ATTR_MODEL,
ATTR_NAME,
A... |
from django.http import (
HttpResponse,
HttpResponseServerError,
JsonResponse,
)
def index(request):
version = 3
html = "<html><body><h1>Hello</h1><p>What do you want to learn today?</p><p>Version {}</p></body></html>".format(version)
return HttpResponse(html)
def healthcheck(request):
r... |
from docs.src.index001 import api
from ninja.testing import TestClient
client = TestClient(api)
def test_api():
response = client.get("/add?a=1&b=2")
assert response.json() == {"result": 3}
|
import tracemalloc
import linecache
from tracemalloc import Snapshot
nframe = 100
def display_top(snapshot, key_type='lineno', limit=10):
snapshot = snapshot.filter_traces((
tracemalloc.Filter(False, "<frozen importlib._bootstrap>"),
tracemalloc.Filter(False, "<unknown>"),
))
top_stats = s... |
class Solution:
def pivotIndex(self, nums: List[int]) -> int:
total = sum(nums)
left = 0
for idx, num in enumerate(nums):
right = total - num - left
if left == right:
return idx
left += num
return -1
|
from gpiozero import Button
from PiBlynk import Blynk
import time
token = "---token---"
blynk = Blynk(token)
SW_pin = 13
button = Button(SW_pin)
def cnct_cb():
print ("Connected: ")
blynk.on_connect(cnct_cb)
def fun_notify():
print("alert")
blynk.notify("Alert") # beep the smartphone
button.when_pressed = fun_... |
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
import os
import plotly.offline as py_off
from plotly.graph_objs import *
import pandas as pd
from fbprophet import Prophet
from fbprophet.plot import plot_plotly
import matplotlib.pyplot as plt
import p... |
"""
Tests for the CLI
"""
import os
import sys
import time
import random
import tempfile
import subprocess
from io import open # pypy and py27 compat
import bsdf
import bsdf_cli
this_dir = os.path.dirname(__file__)
tempfilename = os.path.join(tempfile.gettempdir(), 'bsdf_cli_test.bsdf')
class StringIO:
def _... |
"""added cancel to agent
Revision ID: 73db0f22e1e6
Revises: 89ffd52f1f00
Create Date: 2020-09-19 07:28:37.769815
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '73db0f22e1e6'
down_revision = '89ffd52f1f00'
branch_labels = None
depends_on = None
def upgrade():... |
import socket
from threading import Lock, Thread
from PyQt5.QtCore import QObject, pyqtSlot, pyqtSignal
class SocketServer(QObject, Thread):
onopen = pyqtSignal()
onconnect = pyqtSignal(QObject)
onmessage = pyqtSignal(QObject, str)
ondisconnect = pyqtSignal(QObject)
onclose = pyqtSignal()
onerror = p... |
"""Internal mixt stuff."""
|
import subprocess
from queue import Queue
from signal import SIGINT, signal
from threading import Thread
from time import time
from tkinter import BOTH, Tk, font, ttk
import matplotlib.pyplot as plt
from controllers.alarmController import AlarmController, AlarmType
from controllers.communicationController import Micr... |
from .SpecImports import *
from toontown.toonbase import ToontownGlobals
CogParent = 100001
BattleCellId = 0
BattleCells = {BattleCellId: {'parentEntId': CogParent,
'pos': Point3(0, 0, 0)}}
CogData = []
ReserveCogData = []
|
import setuptools
setuptools.setup(
name='zsec-aws-tools-extensions',
python_requires='>=3.8',
packages=['zsec_aws_tools_extensions'],
install_requires=[
'boto3',
'toolz',
'attrs',
'zsec-aws-tools >= 0.1.17',
],
tests_require=[
'toolz',
'pytest',
... |
from . utils import *
import networkx as nx
import copy
from rdkit import Chem
from .mol_parse import mol_to_nx, apply_unit_info
def prepare_dict(text):
mol = Chem.MolFromMolBlock(text)
# prepare netowork x object
g = mol_to_nx(mol)
# set unit info
apply_unit_info(g, text)
# share connecti... |
import logging
import openpyxl
from ExcelRobot.reader import ExcelReader
from ExcelRobot.utils import (BoolFormat, DataType, DateFormat, NumberFormat,
copy_file, del_file, excel_name2coord,
get_file_path, is_file, random_temp_file)
from six import PY2
from xl... |
from backports.tempfile import TemporaryDirectory
import pytest
@pytest.fixture(scope='session')
def shared_tempdir():
d = TemporaryDirectory()
yield d.name
try:
d.cleanup()
except Exception:
pass
|
from queue import Queue
def truckTour(petrolpumps):
# Your code here.
# we need to know the index of the pump that allows us to
# travel along the entire circle
route = Queue()
# put all of the pumps in the queue
for p in petrolpumps:
# insert the current pump into the queue
... |
import torch
from torch import nn
import kornia.augmentation as K
class ImageAugmentations(nn.Module):
def __init__(self, output_size, augmentations_number, p=0.7):
super().__init__()
self.output_size = output_size
self.augmentations_number = augmentations_number
self.augmentation... |
import logging
from django.core.exceptions import ObjectDoesNotExist
from django.db import DataError
from ApiManager.models import ProjectInfo, ModuleInfo, TestCaseInfo, UserInfo, EnvInfo
logger = logging.getLogger('HttpRunnerManager')
'''用户注册信息落地'''
def add_register_data(**kwargs):
user_info = UserInfo.object... |
"""
Scheduler
"""
|
#!/usr/bin/env python
# coding=utf-8
def main():
for line in open('testdata.txt', 'r'):
tokens = line.split(';')
print('assertTrue("%s".equals(cw.write(new BigDecimal("%s"))));' %
(tokens[1].strip(), tokens[0].strip()))
if __name__ == "__main__":
main()
|
import pytest
from slovnet.shape import (
X, x, xx, XX, Xx, Xx_Xx, OTHER,
RU, EN, NUM, PUNCT,
word_shape,
format_shape as s
)
from slovnet.token import tokenize
TESTS = [
[
'В',
[s(RU, X)],
],
[
'ИЛ-2',
[s(RU, XX)],
],
[
'105г.',
[... |
# SPDX-FileCopyrightText: 2021 Scott Shawcroft, written for Adafruit Industries
#
# SPDX-License-Identifier: MIT
import array
import time
import board
import digitalio
import rp2pio
import adafruit_pioasm
trigger = digitalio.DigitalInOut(board.D4)
trigger.switch_to_output(True)
# signed 16 bit
s16 = array.array("H",... |
"""The ghosts at each side of the stage"""
import time
import music_visualization_system as mvs
import pymvf
class Ghosts:
def __init__(self, dmx: mvs.dmx.ESPDMX):
pass
def _main(self) -> None:
while True:
time.sleep(1)
def __call__(self, buffer: pymvf.buffer.Buffer) -> Non... |
from pyramid.httpexceptions import HTTPConflict
from h.auth.util import client_authority
from h.presenters import TrustedUserJSONPresenter
from h.schemas import ValidationError
from h.schemas.api.user import CreateUserAPISchema, UpdateUserAPISchema
from h.services.user_unique import DuplicateUserError
from h.views.api... |
from django import template
from django.core.urlresolvers import reverse
from xformmanager.models import *
from django.contrib.contenttypes.models import ContentType
from types import ListType,TupleType
from hq.models import *
import graphing.dbhelper as dbhelper
import xformmanager.adapter.querytools as qtools
... |
"""Neural networks with extremely low-precision weights and activations, such as
Binarized Neural Networks (BNNs), usually contain a mix of low-precision weights (e.g.
1-bit) and higher-precision weights (e.g. 8-bit, 16-bit, or 32-bit). Examples of this
include the first and last layers of image classificiation models... |
#!/usr/bin/env python
from distutils.core import setup, Extension
chromosone_module = Extension(
'gene_pool',
sources=['chromosone.cpp'],
extra_compile_args = ['--std=c++17', '-g3', '-O0' ],
libraries = ['stdc++'],
language='C++17', )
setup(
name='gene_pool',
version='0.1.0',
descrip... |
"""
Robot conversions module.
"""
def convert_to_valid_kernel_size(size):
"""
Purpose:
Converts a list/tuple given in robot to a tuple of ints.
Args:
size - list/tuple of strings, length 2.
Returns
kernel_size - A tuple of ints.
"""
kernel_size = (int(float(size[0])), in... |
"""Unit test package for sample_prj."""
|
from requests import get as old_get
# 访问 jsonp 时的模版,下面的模版用来配合 get_from_file 使用本地文件进行测试
URL_TEMPLATE = "https://news.cctv.com/2019/07/gaiban/cmsdatainterface/page/{}_{}.jsonp"
# URL_TEMPLATE = "./test_data/{}_{}.jsonp"
# 爬取数据的延时
FETCH_DELAY = 2
# 支持的新闻类别
SUPPORTED_CLASS = {
'主页': 'news',
'国内': 'china',
'国际': 'worl... |
re.sub(r'\[(\d+)\]', r'\1', '[52] apples and [31] mangoes')
re.sub(r'(_)?_', r'\1', '_foo_ __123__ _baz_')
re.sub(r'\d+', r'(\g<0>0)', '52 apples and 31 mangoes')
re.sub(r'.*', r'Hi. \g<0>. Have a nice day', 'Hello world', count=1)
re.sub(r'(\w+),(\w+)', r'\2,\1', 'a,b 42,24')
words = ['effort', 'flee', 'facade', ... |
from colour import Colour
class Paddle:
def __init__(self, root, canvas, x, y):
self.root = root
self.canvas = canvas
self.speed = 0
self.width = 80
self.height = 20
self.coords = [x, y, x + self.width, y + self.height]
self.paused = False
self.paddl... |
import torch
class BaseAgent(object):
def __init__(self, filename, args={}):
self.filename = filename
self.age = 0
# Arguments used to generate agent
self.args = args
self.initialize_loss_acc()
def increment_age(self):
self.age += 1
def initialize_loss_ac... |
import pdb
import openmdao
import numpy as np
import openmdao.api as om
from pyNA.src.data import Data
from pyNA.src.settings import Settings
from pyNA.src.noise_src_py.split_subbands import split_subbands
from pyNA.src.noise_src_py.ground_reflections import ground_reflections
from pyNA.src.noise_src_py.lateral_attenua... |
from django.db import models
from django.utils.translation import ugettext as _
from simple_history.models import HistoricalRecords
from users.models import User
class Topic(models.Model):
class Meta:
ordering = ('order',)
title = models.CharField(max_length=256)
order = models.PositiveIntegerF... |
"""
TCKDB backend app models associations module
This module contains association tables used in Many-to-Many data models
Create a Table to associate LJ and trans with a species per Network
(https://docs.sqlalchemy.org/en/13/core/metadata.html)
Extracted from species and not used, should be implemented once we have ... |
# -*- coding: utf-8 -*-#
# -------------------------------------------------------------------------------
# File : agentframework.py
# Author:
# Date : 2019-11-21 08:27
# Desc :
# -------------------------------------------------------------------------------
import random
class Agent:
def __init__(self, e... |
# -*- coding: utf-8 -*-
# + {}
import torch
import torchvision.transforms as transforms
from torchvision import models
from torchvision.datasets import ImageFolder, DatasetFolder
import torchvision.datasets as Datasets
from torch.utils.data import DataLoader,Dataset
from torch.autograd import Variable
from torch impor... |
import sqlite3
import os
def initialize():
os.remove("data/database.db")
db = sqlite3.connect("data/database.db")
c = db.cursor()
c.execute('CREATE TABLE IF NOT EXISTS '
'accounts('
'username TEXT PRIMARY KEY, '
'password TEXT)')
c.execute('CREAT... |
import os
import glob
from matplotlib import markers
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from read3Dwrl import read3Dwrl
from exFacialCurve import exFacialCurve
from visualizeCurve import visualizeCurve
faceFoldr = 'faceFolder'
fileType = ".wrl"
folderContent = ... |
from __future__ import annotations
from dataclasses import dataclass
from math import sin, cos, pi
from itertools import product, combinations
from typing import Callable
@dataclass
class Point:
x: int
y: int
z: int
def __hash__(self) -> int:
return hash(self.x) + hash(self.y) + hash(self.z)... |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright (c) 2015, Lars Asplund lars.anders.asplund@gmail.com
"""
Module containing the CodecVHDLRecordType class.
... |
# -*- coding: utf-8 -*-
import os
import torch
from torchvision import models, transforms as T
from PIL import Image
from utils import imagenet_idx_to_label
model = models.mobilenet_v3_small(pretrained=True)
model.eval()
transforms = T.Compose(
[
T.ToTensor(),
T.Resize(256),
T.CenterCrop(2... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import odoo.tests
@odoo.tests.common.at_install(False)
@odoo.tests.common.post_install(True)
class TestUi(odoo.tests.HttpCase):
post_install = True
at_install = False
def test_01_admin_rte(self):
s... |
from pyfy import AsyncSpotify as Spotify, AuthError, ClientCreds
import pytest
pytestmark = pytest.mark.asyncio
## This submodule must test authentication without having a client credentials model set to the client.
empty_client_creds = ClientCreds()
async def test_user_is_authenticated_by_access_token(
user_c... |
from dataclasses import dataclass, field
from typing import List, Optional
from bindings.wfs.abstract_projection_clause import AbstractProjectionClause
from bindings.wfs.abstract_query_expression_type import AbstractQueryExpressionType
from bindings.wfs.abstract_selection_clause import AbstractSelectionClause
from bind... |
#!/usr/bin/env python
import socket
def minion_ip():
return {
'minion_ip': socket.gethostbyname(socket.getfqdn())
} |
import os
import subprocess
import sys
import Constants
def execute_cmd_error_catch(cmd):
(outs, errs) = execute_cmd(cmd)
if errs:
print('ERROR.')
print(errs, file=sys.stderr)
sys.exit(0)
else:
print('Done.')
def execute_cmd(cmd):
# TODO: sort out how to deal with e... |
from src.core import *
from src.envs.collision_v1.entities import *
import numpy as np
import cv2 as cv
import torch
BALL_COLOR = (0,0,255) # red
BACKGROUND = (255, 230, 200) # light blue
class Collision_v1(Environment):
'''
Simple environment with entities (balls) bouncing around. The collisions between the ... |
#!/usr/bin/env python
from optparse import OptionParser
from telnetlib import Telnet
def main():
usage = "usage: %prog [options] GRIDFTP_SERVER_FQDN GRIDFTP_SERVER_PORT"
parser = OptionParser(usage)
parser.add_option('--timeout', type='int', default=5,
help="Telnet timeout value in... |
#*****************************
#date:2016-07-26
#author:luolongqiang
#*****************************
import os, sys, cv2, copy, time, argparse
import numpy as np
from numpy import array
from math import sqrt
from pandas import DataFrame
from multiprocessing import Pool, cpu_count
def GetFileList(FindPath, FlagStr=[]):... |
"""
biosignalsnotebooks module intended to give the user the possibility of programatically generate a
Notebook.
"""
import json
import os
import re
import shutil
import warnings
import importlib.util
import nbformat as nb
from .notebook_files.MainFiles.group_by_difficulty import STAR_TABLE_HEADER
from .notebook_fil... |
from datetime import datetime
from mantisconnect2.project import Issue
from mantisconnect2.project import Project
class SimpleProject(Project):
"""
Simple Project
"""
def __init__(self, mantis_soap_connector, name):
Project.__init__(self, mantis_soap_connector, name)
def _make_issue_data... |
#!/bin/python3
from collections import Counter
def note(magazine, ransom):
mag_c = Counter(magazine)
ran_c = Counter(ransom)
intersection = sum((mag_c & ran_c).values())
ran_length = sum(ran_c.values())
if ran_length == intersection:
return "Yes"
else:
return "No"
if __name_... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from typing import TYPE_CHECKING, Any
import pytest
from flask import current_app
if TYPE_CHECKING:
from smorest_sfs.extensions.celery import Celery
def test_create_task(celery_ext: "Celery", celery_worker: Any) -> None:
# pylint: disable=W0612
@celery_ext.... |
from __future__ import print_function
import os
import sys
import pandas as pd
"""
To download a new VDJdb database:
Go to https://vdjdb.cdr3.net/search and select "Export as:" -> TSV
And place the downloaded file at public_datasets/VDJdb.tsv
"""
def findEpitopes(sequences):
"""
sequences: a pandas datafram... |
# from @GZTime
from manimlib.imports import *
class CubicSum(Scene):
def construct(self):
titles = [Text("Manim Homework Vol.2", font='Orbitron Medium', stroke_width=0),
Text("@GZTime", font='Orbitron Medium', stroke_width=0).scale(0.5)]
titles[0].move_to(UP*0.5)
titles[1].move... |
class LocalIPythonEnvironment:
def __init__(self, ip, port):
try:
from IPython.display import HTML, display
except NameError:
return None
self.base_url = "http://{0}:{1}".format(
ip,
port)
self.externally_available = True
def ... |
RANDOM = [
"https://www.youtube.com/watch?v=M7X6oYg6iro", # Indochine - L'aventurier
"https://www.youtube.com/watch?v=IkU158B5VzQ", # Celine Dion & Garou - Sous Le Vent
"https://www.youtube.com/watch?v=Y9GCM9DZUJo", # Claudio Capéo - Un homme debout
"https://www.youtube.com/watch?v=E7bgWEAMdwo", # Danie... |
#------------------------------------------------------------------------------
# Copyright (c) 2007, Riverbank Computing Limited
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in enthought/LICENSE.txt and may be redistributed only
# under the conditi... |
# encoding=utf-8
from abc import abstractmethod
from db.select import Select
class Builder(object):
def __init__(self, db):
self.db = db
def select(self):
return Select(self.db)
@classmethod
@abstractmethod
def one(cls, sql):
pass
def insert(self, table, params):
... |
def cylinder_surface_area(radius, height, has_top_and_bottom):
side_area = height * 6.28 * radius
if has_top_and_bottom:
top_area = 3.14 * radius ** 2
return side_area + 2 * top_area
else:
return side_area
|
# -*- coding: utf-8 -*-
import datetime
import logging
from django.contrib import messages
from django.contrib.auth.decorators import login_required, user_passes_test
try:
from django.core.urlresolvers import reverse_lazy
except ImportError:
from django.urls import reverse_lazy
from django.utils.encoding imp... |
import pytest
from botx import Bot, MessageBuilder, TestClient
@pytest.mark.asyncio
async def test_hello_format(
bot: Bot, builder: MessageBuilder, client: TestClient
) -> None:
builder.body = "/hello"
await client.send_command(builder.message)
command_result = client.command_results[0]
assert ... |
"""app/utils
utils
The helper classes and functions here exist to reduce large repetitive code
blocks throughout the project. They may contain functions or classes from
module but do not change the parameters of the class
Modules
-------
templates utilities for localization templates
"""
from itertools import re... |
#!/usr/bin/env python
"""
deltaBD: simulate quantitative SIP data
Usage:
deltaBD [options] <OTU_table> <exp_design>
deltaBD -h | --help
deltaBD --version
Options:
<OTU_table> OTU table file ('true abundances').
<exp_design> Experimental design table. (See Description)
-b=<b> The number of e... |
"""
Defines a new topological diagram from inputs
Inputs:
T: (trailObjects) Trail members in the topological diagram
L: (pointLoadObjects) Point Loads in the topological diagram
D: (deviationObjects) Deviation members in the topological diagram
S: (supportObjects) Supports in the ... |
"""f = w^T * x + b"""
import os
import numpy as np
import numpy.random as random
from keras.preprocessing.sequence import pad_sequences
from keras.preprocessing.text import Tokenizer
def calcWs(alphas, data, labels):
X = np.mat(data)
labels = np.mat(labels).transpose()
m,n = np.shape(X)
w = np.zeros(... |
from pylatex import Command, NoEscape, UnsafeCommand
def setup_document(doc):
doc.preamble.append(Command("setlength", arguments=NoEscape("\\parindent"), extra_arguments="0in"))
doc.preamble.append(Command("makeatletter"))
doc.preamble.append(Command("newlength", arguments=NoEscape("\\bibhang")))
doc.... |
from __future__ import print_function
import sys, random
from operator import attrgetter
from collections import OrderedDict
from copy import deepcopy
from sklearn.preprocessing import normalize
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
from scipy.stats import rankdata
import numpy... |
from xonsh.cli_utils import ArgparseCompleter
from xonsh.completers.tools import get_filter_function
from xonsh.parsers.completion_context import CommandContext
def xonsh_complete(command: CommandContext):
"""Completer for ``xonsh`` command using its ``argparser``"""
from xonsh.main import parser
compl... |
#
# Not working with socket.io@2.0.3
# Use socket.io@1.7.2 instead
#
from socketIO_client import SocketIO, LoggingNamespace
with SocketIO('http://localhost/socket.io', 3000, LoggingNamespace) as socketIO:
socketIO.emit('client-event')
socketIO.wait(seconds=1)
|
# The MIT License (MIT)
# Copyright (c) 2017 Massachusetts Institute of Technology
#
# Authors: Cody Rude
# This software has been created in projects supported by the US National
# Science Foundation and NASA (PI: Pankratius)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this so... |
print('='*5, 'Cálculo de desconto', '='*5)
p = float(input('Digite o preço do produto: R$ '))#preço
d = float(input('Digite o desconto em (%): '))#desconto
vd = (p*d/100)#valor do desconto
np = p-vd#novo preço
print('Preço original do produto: R$ {:.2f} \nDesconto: {}%'.format(p, d))
print('Valor do desconto: R$ {:.2f}... |
class FacebookUser:
def __init__(self, usuario):
self.nombre_usuario = usuario
self.muro = []
self.amigos = []
def pubilcar(self, post):
self.muro.append(post)
def agregar_amigo(self, otro_usuario):
self.amigos.append(otro_usuario.nombre_usuario)
otro_usuari... |
from xarl.agents.xasac.xasac import *
|
#!/usr/bin/env python
"""
Copyright (c) 2006-2021 sqlmap developers (http://sqlmap.org/)
See the file 'LICENSE' for copying permission
"""
from lib.core.enums import DBMS
from lib.core.settings import DERBY_SYSTEM_DBS
from lib.core.unescaper import unescaper
from plugins.dbms.derby.enumeration import Enumeration
fro... |
#-*- coding: utf-8 -*-
'''
Created on 2016. 11. 19
Updated on 2016. 01. 09
'''
from __future__ import print_function
import os
import sys
sys.path.append(os.getcwd()) # add the executed path to system PATH
import copy
import re
import subprocess
from xml.etree import ElementTree
from utils import PrettyStringBuilder... |
from pyramid.config import Configurator
from tracim_backend.config import CFG
from tracim_backend.extensions import hapic
from tracim_backend.lib.agenda.agenda import AgendaApi
from tracim_backend.lib.utils.authorization import check_right
from tracim_backend.lib.utils.authorization import has_personal_access
from tra... |
"""
Build engine application entry
"""
from nspawn.app.engine.main import BuildMain
if __name__ == "__main__":
BuildMain().perform()
|
import sublime, sublime_plugin
import os, webbrowser, shlex, json, collections
def ionicv2_ask_custom_path(project_path, type):
sublime.active_window().show_input_panel("Ionic v2 CLI custom path", "ionic", lambda ionicv2_custom_path: ionicv2_prepare_project(project_path, ionicv2_custom_path) if type == "create_new... |
import os
import unittest
import nbox
from nbox import utils
from functools import lru_cache
@lru_cache
def get_model(*args, **kwargs):
return nbox.load(*args, **kwargs)
@lru_cache
def get_parser(*args, **kwargs):
model = get_model(*args, **kwargs)
return model.text_parser
class ImportTest(unittest.... |
#!/usr/bin/env python3
import os
import time
import pyperclip
import urllib.request
print("Iniciando chatbot..")
from chatbot.chatbot import Chatbot
chatbot = Chatbot()
chatbot.main(["--rootDir",".","--test", "daemon", "--modelTag", "spanish", "--keepAll"])
from vision import look
from ui import say
recent_value =... |
"""test string format error"""
# pylint: disable=print-statement,unsupported-binary-operation,line-too-long
from __future__ import print_function
PARG_1 = PARG_2 = PARG_3 = 1
def pprint():
"""Test string format"""
print("%s %s" % {'PARG_1': 1, 'PARG_2': 2}) # [too-few-format-args]
print("%s" % (PARG_1, ... |
import heterocl as hcl
import numpy as np
import time
def gemm_vhls(m=1024, n=1024, k=1024, dtype=hcl.Int()):
matrix_1 = hcl.placeholder((m, k), dtype=dtype)
matrix_2 = hcl.placeholder((k, n), dtype=dtype)
def kernel(matrix_1, matrix_2):
r = hcl.reduce_axis(0, k, 'k')
return hcl.compute((m... |
from dataclasses import dataclass
from cadence.cadence_types import TimeoutType, ActivityType, WorkflowExecution, WorkflowExecutionCloseStatus
from cadence.exception_handling import deserialize_exception
class IllegalStateException(BaseException):
pass
class IllegalArgumentException(BaseException):
pass
... |
#!/usr/bin/env python
"""Fileset extensions for grow.
Sample podspec:
extensions:
preprocessors:
- extensions.fileset.grow.FilesetPreprocessor
preprocessors:
- kind: fileset
deployments:
localhost:
destination: fileset
host: localhost:8088
env:
na... |
from kivy.uix.screenmanager import Screen
from kivy.app import App
class AddCardScreen(Screen):
def card_number_input(self):
# Link the main screen
self.app = App.get_running_app()
# Link the specific screen
self.screen = self.app.root.ids['add_card_screen']
#Link the ... |
'''This module contains all the constants for the track geom package'''
from enum import Enum, unique
GET_LINK_STATE = '/gazebo/get_link_state'
GET_MODEL_STATE = '/gazebo/get_model_state'
SET_MODEL_STATE = '/gazebo/set_model_state'
SPAWN_SDF_MODEL = '/gazebo/spawn_sdf_model'
SPAWN_URDF_MODEL = '/gazebo/spawn_urdf_mode... |
###############################################################################
# WaterTAP Copyright (c) 2021, The Regents of the University of California,
# through Lawrence Berkeley National Laboratory, Oak Ridge National
# Laboratory, National Renewable Energy Laboratory, and National Energy
# Technology Laboratory ... |
import warnings
from typing import Tuple, Sequence, List, Dict, Optional, TextIO
import networkx as nx
import sympy
from sympy import Expr, Symbol, Eq
class Element:
def __init__(self, kind: str, name: str, nodes: Sequence[str], parameters: Sequence[str]) -> None:
self.name = name
self.kind = kin... |
from opentera.redis.RedisRPCClient import RedisRPCClient
from opentera.config.ConfigManager import ConfigManager
from opentera.modules.BaseModule import ModuleNames
from datetime import datetime
if __name__ == '__main__':
config = ConfigManager()
config.load_config('../../config/TeraServerConfig.ini')
st... |
from __future__ import print_function
import os
import sys
try:
import IDF
except ImportError:
test_fw_path = os.getenv('TEST_FW_PATH')
if test_fw_path and test_fw_path not in sys.path:
sys.path.insert(0, test_fw_path)
import IDF
@IDF.idf_example_test(env_tag='Example_ExtFlash')
def test_exam... |
import pytest
@pytest.mark.parametrize("name", [
("ufw"),
])
def test_packages(host, name):
pkg = host.package(name)
assert pkg.is_installed
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.