content stringlengths 5 1.05M |
|---|
# 2. Tic-Tac-Toe
# You will receive a field of a tic-tac-toe game in three lines containing numbers separated by a single space.
# Legend:
# • 0 - empty space
# • 1 - first player move
# • 2 - second player move
# Find out who the winner is. If the first player wins print "First player won",
# otherwise if the second p... |
import datetime
import re
def extract_show_name(show_name):
show_name_words = __extract_urls(show_name) \
.replace('.', ' ') \
.split()
show_name_words = __remove_release_date(show_name_words)
show_name_words = __remove_sample_word(show_name_words)
show_name_words = __remove_garbage_w... |
from datetime import datetime
z = int(input())
tuples = []
for i in range(z):
line = input()
s = line.split(" ")
date = s[0]
time = s[1]
message = ""
for x in range(2, len(s)):
if x != 2:
message = message + " "
message = message + s[x]
d = s[0] + " " + s[1]
... |
# -*- coding: utf-8 -*-
import scrapy
from spider.items import SpiderItem
from scrapy.selector import Selector
import traceback
class IfengSpider(scrapy.Spider):
name = "ifeng"
allowed_domains = ["ifeng.com"]
start_urls = (
'http://finance.ifeng.com/a/20150701/13811668_0.shtml',
)
def pars... |
"""MySQLdb execution moc."""
import inspect
import mocbase
def connect(*args, **kwargs):
return MocConnection()
class MocConnection(object):
def cursor(self, cursor):
return MocCursor()
class MocCursor(object):
def execute(self, sql):
msg = 'Execute yourSQL\n {}'.format(sql)
... |
import json
def my_func(file_a, file_b):
my_dict = {}
file_1 = open(file_a, encoding='utf-8')
list_1 = [string.strip() for string in file_1.readlines()]
file_2 = open(file_b, encoding='utf-8')
list_2 = [string.strip() for string in file_2.readlines()]
if len(list_1) <= len(list_2):
for ... |
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
import pyqtgraph.parametertree.parameterTypes as pTypes
from pyqtgraph.parametertree import (
Parameter,
ParameterTree,
ParameterItem,
registerParameterType,
)
class SettingsWidget(ParameterTree):
def __init__(self, *args, **kwargs):
... |
# This is the unit test of the create_model function
# Author: Seif Ashraf
# Testing Methodology
# send return types example as a dict to the function to simulate the output of the annotations function
# let create_model() process input and get its output
# compare its output types with a sample model
# NOTE: t... |
import time
import os
import argparse
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
parser = argparse.ArgumentParser()
parser.add_argument('--tol', type=float, default=1e-3)
parser.add_argument('--adjoint', type=eval, default=False)
parser.add_argument('--niters', type=int, default... |
from ...models.models import MotionBlock
from ..action_set import ActionSet
from ..agenda_item.agenda_creation import (
CreateActionWithAgendaItemMixin,
agenda_creation_properties,
)
from ..agenda_item.create import AgendaItemCreate
from ..create_action_with_dependencies import CreateActionWithDependencies
from... |
from collections import namedtuple
BluprintRoute = namedtuple('Route',
['path', 'name', 'handler', 'methods', 'context', 'on_request', 'on_response'])
BluprintStatic = namedtuple('Route',
['route', 'path'])
class Blueprint:
def __init__(self, name, url_pref... |
import logging
from django.conf import settings
from django.contrib.auth.models import Group
from django.core.management.base import BaseCommand
logger = logging.getLogger(__name__)
def command():
logger.info("Initiating Groups")
initial_groups = [
{
'name': settings.EMPLOYEE,
},... |
# -*- coding: utf-8 -*-
"""
Microsoft-Windows-MediaFoundation-MFReadWrite
GUID : 4b7eac67-fc53-448c-a49d-7cc6db524da7
"""
from construct import Int8sl, Int8ul, Int16ul, Int16sl, Int32sl, Int32ul, Int64sl, Int64ul, Bytes, Double, Float32l, Struct
from etl.utils import WString, CString, SystemTime, Guid
from etl.dtyp imp... |
import jieba
from jieba import analyse
jieba.enable_parallel(4)
# 引入TF-IDF关键词抽取接口
tfidf = analyse.extract_tags
# 原始文本
text = "线程是程序执行时的最小单位,它是进程的一个执行流,\
是CPU调度和分派的基本单位,一个进程可以由很多个线程组成,\
线程间共享进程的所有资源,每个线程有自己的堆栈和局部变量。\
线程由CPU独立调度执行,在多CPU环境下就允许多个线程同时运行。\
同样多线程也可以实现并发操作,每个请求分配一个线程来处理。"
# ... |
import os
from configparser import ConfigParser
import os
def check():
config = ConfigParser()
if not os.path.exists("config.ini"):
config["MongoDB"] = {
"uri": "mongodb://localhost:27017",
"name": "OpenLoop",
}
config["Customize"] = {
"name": "OpenL... |
import os
from dotenv import load_dotenv
load_dotenv()
SECRET_KEY = os.getenv('SECRET_KEY')
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL')
MAIL_SERVER = 'smtp.gmail.com'
MAIL_PORT = 465
MAIL_USE_SSL = True
MAIL_USERNAME = 'sojiremora@gmail.com'
MAIL_PASSWORD = os.getenv('MAIL_PASSWORD')
STRIPE_SECRET_KEY = os.get... |
# Copyright 2016 Hewlett Packard Enterprise Development Company LP
#
# Author: Federico Ceratto <federico.ceratto@hpe.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.... |
import turtle
turtle.goto(0,0)
UP = 0
DOWN=1
LEFT=2
RIGHT=3
direction = None
def up():
global direction
direction=UP
print("You pressed the up key.")
on_move()
def down():
global direction
direction=DOWN
print("You pressed the down key.")
on_move()
def left():
global dire... |
"""Pipeline config file API."""
# -----------------------------------------------------------------------------
# Imports:
# -----------------------------------------------------------------------------
try:
from collections import OrderedDict
except ImportError:
from ordereddict import OrderedDict
import os... |
from datetime import date
from . import base
from . import mixins
class TransformedRecord(
mixins.GenericCompensationMixin,
mixins.GenericDepartmentMixin,
mixins.GenericIdentifierMixin, mixins.GenericPersonMixin,
mixins.GenericJobTitleMixin,
mixins.MembershipMixin, mixins.OrganizationMixin, mixin... |
from setuptools import setup
setup(
name="windtools",
version="0.0.1",
author="Gabriele Calvo",
author_email="gcalvo87@gmail.com",
description="Simple windtools and wind distribution chart generator from raw data and frequency tables.",
keywords="windtools wind rose analysis data weibull distri... |
from .tensorboard_logger import TensorboardLogger
|
import os
from ..sprite import Sprite
import pygame
class PotionSpeedDown(Sprite):
"""
Represents a potion to heal the hero
"""
def __init__(
self,
position,
screen,
path: str = 'advancing_hero/images/sprites/potions/potion_speed_down',
) -> None:
super().__... |
################################################################################
# Copyright (C) 2019 drinfernoo #
# #
# This Program is free software; you can redistribute it and/or modify ... |
# Generated by Django 3.2.7 on 2021-11-02 16:59
from django.db import migrations
from django.db.models import Count
def _remove_duplicated(TokenTransferModel):
for transfer in (
TokenTransferModel.objects.values_list("ethereum_tx", "log_index")
.annotate(c=Count("*"))
.filter(c__gt=1)
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2017-11-13 19:36
from __future__ import unicode_literals
from django.conf import settings
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
import global_resources.models
class Migration(migrations.Migration... |
import qrcode
qr = qrcode.QRCode()
qr.add_data('智者千虑,必有一失。')
qr.make(fit=True)
image = qr.make_image()
image.convert('RGBA')
image.save('qr-code.png')
|
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
import sys
sys.path.append("../")
import jieba
jieba.load_userdict("userdict.txt")
import jieba.posseg as pseg
test_sent = "l+navtion+cf1 l-navtion-cf1 l-navtion-co1 l+navtion+cn2 l.navtion.cn2 l#navtion#cn2 l:navtion:cn2 l:navtion|cn2 l-na... |
class Solution:
def jump(self, nums: List[int]) -> int:
ans = 0
end = 0
farthest = 0
for i in range(len(nums) - 1):
farthest = max(farthest, i + nums[i])
if farthest >= len(nums) - 1:
ans += 1
break
if i == end:
ans += 1
end = farthest
return ans... |
/home/runner/.cache/pip/pool/bd/ab/68/c4576606bea27beb1355754d3ce3c6deec0c0d62539c41029e6ef10c2c |
# -*- coding: utf-8 -*-
#
# Unless explicitly stated otherwise all files in this repository are licensed
# under the Apache 2 License.
#
# This product includes software developed at Datadog
# (https://www.datadoghq.com/).
#
# Copyright 2018 Datadog, Inc.
#
"""Add trello card details to the Issue and PullRequest mode... |
from flask import Flask, render_template, request, redirect, url_for
app = Flask(__name__)
@app.route('/<user>', methods=['POST'])
def greet(user):
if request.method == 'POST':
return redirect(url_for('user', usr = user))
return f"<h1>Good Morning!!</h1>"
@app.route('/<usr>')
def user(usr):
retur... |
import collections
import inspect
import sys
class PluginLibrary(type):
def __init__(cls, name, bases, attrs):
module_name = cls.__module__.lower()
class_name = name.lower()
if not hasattr(cls, 'cache'):
cls.cache = collections.defaultdict(dict)
else:
# Do ... |
import pytest
from pactman import Consumer, Like, Provider, Term
from pactman.mock.request import Request
def test_v2():
pact = Consumer('consumer').has_pact_with(Provider('provider'), version='2.0.0')
pact.given("the condition exists").upon_receiving("a request") \
.with_request("GET", "/path", que... |
import numpy as np
from sklearn.utils import check_random_state
from mne.io import BaseRaw
from joblib import Memory
from .core_smica import SMICA
from .mne import ICA, transfer_to_mne
from .utils import fourier_sampling
location = './cachedir'
memory = Memory(location, verbose=0)
def _transform_set(M, D):
'''... |
from scipy.special import erfc as erfc
import numpy as np
import datetime
import os
def __init__():
pass
def mesh_quarter_uc(a1, a2, width, height):
"""
mesh_quarter_uc(a1, a2, width, height)
Create meshgrid covering a quarter-unit-cell from (0,0) to (0.5*a1, 0.5*a2).
Unit cell must be rec... |
# 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 by applicable law or ag... |
# SPDX-License-Identifier: Apache-2.0
# Copyright 2020 igo95862
# 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 ... |
dataset_paths = {
'cars_train': '',
'cars_test': '',
'cats_train': '',
'cats_test': '',
'celeba_train': '/raid/quanpeng/train_test_split_0.8/train',
'celeba_test': '/raid/quanpeng/train_test_split_0.8/test',
'celeba_train_sketch': '',
'celeba_test_sketch': '',
'celeba_train_segmentation': '',
'celeba_test_seg... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Unit tests for `weblayer.request`.
"""
import unittest
try: # pragma: no cover
from mock import Mock
except: # pragma: no cover
pass
def _was_called_with(m, *args, **kwargs):
""" Takes a mock and the args and kwargs it should have been
called with,... |
#
# Simple S-expression parser
#
DELIMS = {
'(': ')',
'[': ']',
'{': '}',
}
class ParseException(Exception):
def __init__(self, line, col, message, *args, **kwargs):
super().__init__(f'{line}:{col}: {message}', *args, **kwargs)
self.line = line
self.col = col
def _atom(cur):
"""Parse atom (literal values)... |
import pytest
from .Week5Bonus_NumberOfCornerRectangles import Solution
s = Solution()
@pytest.mark.parametrize(
"grid,expected",
[
([[1, 0, 0, 1, 0], [0, 0, 1, 0, 1], [0, 0, 0, 1, 0], [1, 0, 1, 0, 1]], 1),
([[1, 1, 1], [1, 1, 1], [1, 1, 1]], 9),
([[1, 1, 1, 1]], 0),
],
)
... |
# --------------------------------------------------------
# Scene Graph Generation by Iterative Message Passing
# Licensed under The MIT License [see LICENSE for details]
# Written by Danfei Xu
# --------------------------------------------------------
import tensorflow as tf
from networks.network import Network
imp... |
import gocept.testing.assertion
import mock
import unittest
import zeit.content.cp.interfaces
import zeit.content.cp.testing
class AreaValidationTest(
unittest.TestCase,
gocept.testing.assertion.Exceptions):
def setUp(self):
super(AreaValidationTest, self).setUp()
self.interface =... |
import cv2
import numpy as np
## functions of AA for detection
def warp_image_and_bbox(img, bboxes, M, fill=(0, 0, 0)):
rows, cols, _ = img.shape
n_boxes = bboxes.shape[0]
# warp image
img = cv2.warpAffine(img, M, (cols, rows), borderValue=fill)
# warp bboxes
x1 = bboxes[:, 0].reshape(-1, 1... |
# Copyright (c) Facebook, Inc. and its affiliates.
# Copyright (c) Marvin Eisenberger.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from scipy import sparse
import numpy as np
from torch_geometric.nn import fps, knn_graph
import matplotli... |
# coding=utf-8
import sys
import inspect
import logging
logger = logging.getLogger(__name__)
status_codes = {
200: 'OK',
201: 'Created',
202: 'Accepted',
204: 'No Content',
300: 'Multiple Choices',
301: 'Moved Permanently',
302: 'Found',
304: 'Not Modified',
400: 'Bad Request',
... |
import unittest
from calculator import menu
from unittest.mock import patch
@patch('platform.system')
@patch('os.system')
class TestMenuClass(unittest.TestCase):
def test_should_call_os_when_linux(self, mock_os_system, mock_platform_system):
# set up
os_name = 'Linux'
# mock return
... |
import requests
def consulta()
r: requests.get('https://api.github.com/user', auth=('user', 'pass'))
r.status_code
200
r.headers['content-type']
'application/json; charset=utf8'
r.encoding
'utf-8'
r.text
'{"type":"User"...'
r.json()
{'private_gists': 419, 'total_private_repos': 77,}
|
"""Pipeline
"""
from sklearn.ensemble import RandomForestClassifier
from sklearn.pipeline import Pipeline, FeatureUnion
from .features import features_generator
SEED = 42
RF_PARAMS = {
'n_estimators': 10,
'random_state': SEED
}
PARAM_GRID = {
'estimator__max_depth': [10, 20],
}
estimator = RandomForest... |
from dataclasses import dataclass, field
from typing import List, Dict
from kloppy.domain.models.common import DatasetType
from .common import Dataset, DataRecord
from ...utils import docstring_inherit_attributes
@dataclass
@docstring_inherit_attributes(DataRecord)
class Code(DataRecord):
"""
Single code
... |
"""
Test Contract Manager
"""
from starfish.network.ethereum import EthereumNetwork
from starfish.network.ethereum.contract.contract_manager import ContractManager
def test_contract_load_local_artiacts_package(config):
# test pre-loaded contracts from non local test nodes
network = EthereumNetwork(conf... |
from ..remote import RemoteModel
from infoblox_netmri.utils.utils import check_api_availability
class EventNetworkAnalysisGridRemote(RemoteModel):
"""
| ``EventID:`` none
| ``attribute type:`` string
| ``EventCategory:`` none
| ``attribute type:`` string
| ``EventCate... |
from enum import Enum
from pydantic import BaseModel
DomainName = str
AppToken = str
Url = str
class WebhookData(BaseModel):
token: str
webhook_id: str
webhook_secret_key: str
class InstallData(BaseModel):
auth_token: str
class SaleorPermissions(str, Enum):
MANAGE_APPS = "MANAGE_APPS"
MA... |
# -*-coding:utf-8-*-
import torch.nn as nn
import torch.nn.functional as func
class LeNet(nn.Module):
def __init__(self, num_classes):
super(LeNet, self).__init__()
self.conv1 = nn.Conv2d(3, 6, kernel_size=5)
self.conv2 = nn.Conv2d(6, 16, kernel_size=5)
self.fc1 = nn.Linear(16*5*5,... |
# Generated by Django 3.2.10 on 2021-12-20 21:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('financials', '0016_auto_20211220_2101'),
]
operations = [
migrations.AddField(
model_name='company',
name='ticker',... |
from unittest.case import TestCase
from NonCryptographicHash import fastHash
import chess.pgn
import io
import Constants
class ChessScript:
def __init__(self, pgn):
self.pgn = pgn
with io.StringIO(pgn) as pgn_io:
self.game = chess.pgn.read_game(pgn_io)
self.headers = self.game.h... |
import os, shutil, zipfile
from PuzzleLib.Datasets.InputLoader import InputLoader
class PathLoader(InputLoader):
def __init__(self, onFile=None, exts=None, dataname=None, cachename=None, onFileList=None, doOpen=True):
super().__init__(onFile, exts, dataname, cachename, onFileList)
self.doOpen = doOpen
class ... |
# Generated by Django 3.1.7 on 2021-05-16 14:54
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('msgs', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='classmessege',
... |
# ------------------------------------------------------------------------------
# Test Multiday Event Page
# ------------------------------------------------------------------------------
import sys
import datetime as dt
import pytz
from django.test import TestCase
from django.contrib.auth.models import User
from djan... |
n=int(input("How many elements want to insert ?"))
lst=[]
for i in range(n):
a=int(input())
lst.append(a)
for i in range(n-1):
if lst[i]<lst[i+1]:
lst[i+1]=lst[i]
a=lst[i+1]
print("Smallest number of list :",a)
|
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.backend_bases import key_press_handler
import tkinter as Tk
from columnplot.mappings import MapPlotBase
class ColumnPlotBase():
def __init__(self, params):
self._ca... |
#!env python3
#Copyright 2021-2022 Eric Vyncke
#
#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... |
import json
def CreateObjects(thing):
for key in thing.__dict__:
if(type(thing.__dict__[key]) == dict):
newObj = jsonObj(thing.__dict__[key])
thing.__dict__[key] = newObj
CreateObjects(thing.__dict__[key])
elif (type(thing.__dict__[key]) == list):
for... |
# bot.py
import os
import asyncio
import discord
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('TOKEN')
client = commands.Bot(command_prefix='!')
@client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
@client.command()
async def... |
"""
Copyright (c) 2016-present, Facebook, Inc.
All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree. An additional grant
of patent rights can be found in the PATENTS file in the same directory.
"""
from lte.protos.policydb_pb... |
import numpy as np
import pandas as pd
import requests, lxml
import os
from datetime import datetime
import datetime
from bs4 import BeautifulSoup
from flask import Flask, request, render_template
PEOPLE_FOLDER = os.path.join('static', 'images/icons')
import os
def images(code):
if(code=='800'):
... |
import logging
from functools import partial
from collections import OrderedDict
import json
from torch import nn
import torch
from transformers import (
BertForMaskedLM, BertTokenizer,
GPT2DoubleHeadsModel, GPT2Tokenizer,
XLNetLMHeadModel, XLNetTokenizer,
TransfoXLLMHeadModel, TransfoXLTokenizer,
... |
"""
Created on 2012-02-21
@author: guillaume
"""
class BaseDataPoint(object):
"""Base class defining an experimental point."""
def __init__(self, val=0.0, err=0.0, par=None, par_conv=None, plot_data=None, calc_observable=None):
"""Constructor"""
self.val = float(val)
self.err = floa... |
from enum import Enum
TEST = r"""/->-\
| | /----\
| /-+--+-\ |
| | | | v |
\-+-/ \-+--/
\------/ """.splitlines()
TEST2 = r"""/>-<\
| |
| /<+-\
| | | v
\>+</ |
| ^
\<->/""".splitlines()
Direction = Enum('Direction', [('UP', '^'), ('DOWN', 'v'), ('LEFT', '<'), ('RIGHT', '>')])
RULES = {
'U... |
import time
import taichi as tc
from taichi.gui.image_viewer import show_image
tc.core.print_all_units()
tc.core.test()
tex = tc.Texture('const', value=(0.1, 0.1, 0.1, 0.1))
tex = tex.flip(0)
try:
tc.core.test_raise_error()
except Exception as e:
print 'Exception:', e
img = tc.util.imread(tc.get_asset_path(... |
#!/usr/bin/env python
import pytest
"""
Test 621. Task Scheduler
"""
@pytest.fixture(scope="session")
def init_variables_621():
from src.leetcode_621_task_scheduler import Solution
solution = Solution()
def _init_variables_621():
return solution
yield _init_variables_621
class TestClass... |
# coding: utf-8
#
# Copyright 2020 The Oppia 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 requi... |
# Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
import torch
import torch.nn as nn
from torch.distributions import constraints
from pyro.distributions.torch_transform import TransformModule
from pyro.distributions.transforms.householder import Householder
from pyro.distribution... |
r"""
Values are light weight object which can be assimilated as native type.
"""
from simput.core import ObjectValue
class Array(ObjectValue):
def __init__(self, state_value):
self._array_location = None
self._array_name = None
# Initialize state
self.state = state_value
@pro... |
from yggdrasil.metaschema import normalizer as normalizer_mod
from yggdrasil.metaschema.properties.MetaschemaProperty import MetaschemaProperty
class DefaultMetaschemaProperty(MetaschemaProperty):
r"""Property class for 'default' property."""
name = 'default'
_replaces_existing = True
_validate = Fal... |
from os.path import join
from logging import getLogger
from shutil import rmtree
from raptiformica.settings import conf
from raptiformica.settings.load import on_disk_mapping, try_delete_config, try_update_config_mapping
from raptiformica.shell.git import clone_source
log = getLogger(__name__)
def determine_clone_... |
"""
Created on 04 Dec 2020
@author: Jade Page (jade.page@southcoastscience.com)
"""
import sys
# --------------------------------------------------------------------------------------------------------------------
class SagemakerTrialManager(object):
"""
classdocs
"""
# --------------------------... |
"""Downloads videos from a YouTube playlist for analysis."""
import os
import subprocess
def download_playlist(playlist_url, output_directory):
"""Downloads all of the videos from playlist_url into output_directory."""
output_file_format = os.path.join(output_directory, '%(title)s.%(ext)s')
subprocess.r... |
import digitalocean
from allauth.socialaccount.models import SocialToken
class DigitalOceanCloud:
def __init__(self, user):
self.social_token = SocialToken.objects.filter(
account__user=user, account__provider="digitalocean"
).first()
def get_all_sizes(self):
sizes = []
... |
""" proxy for controlling serial devices on remote computer through labrad
--- example usage
import labrad
from serial_server.proxy import SerialProxy
cxn = labrad.connect()
serial = SerialProxy(cxn.yesr5_serial)
# ``serial'' now acts like pyserial 3.x library
ser = serial.Serial('COM10')
ser.timeout = 0.1
ser.write... |
"""
PubMedQA: A Dataset for Biomedical Research Question Answering
https://arxiv.org/pdf/1909.06146.pdf
PubMedQA is a novel biomedical question answering (QA) dataset collected from
PubMed abstracts. The task of PubMedQA is to answer research questions with
yes/no/maybe (e.g.: Do preoperative statins reduce atrial fib... |
# generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/home/suntao/workspace/stbot/lilibot/robots/catkin_ws/install/include".split(';') if "/home/suntao/workspace/stbot/lilibot/robots/catkin_ws/install/include" != "" else []
PROJECT_CATKIN_DEPENDS = "rosc... |
"""
Test search classes
"""
try:
import numpy as np
from sklearn.linear_model import LogisticRegression
from skdist.distribute import search
from skdist.distribute.search import (
DistGridSearchCV, DistRandomizedSearchCV
)
_import_error = None
except Exception as e:
_import_erro... |
import unittest
from fuzza.transformer import init
class TestTransformer(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.data = [
b'this is string',
b'aaa',
b'kkoopq'
]
def test_dynamic_module_import_success(self):
config = {
... |
"""
MIT License
Copyright (c) 2019-present Josh B
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish... |
# Average data points and get rid of error messages
# and plot
# Makes 2 plots in the graphs/ directory
# One plot uses the average throughput, and the other uses the min throughpu
import glob
import os
import plot_normalized_throughput
import re
import shutil
from helper import *
def clean_data(args):
path = 'ou... |
from sklearn import preprocessing
def onehot():
enc = preprocessing.OneHotEncoder(sparse=False)
data = enc.fit_transform([[0, 0, 3], [1, 1, 0], [0, 2, 1], [1, 0, 2]])
print(data)
if __name__ == "__main__":
onehot() |
"""Tests for certbot_postfix.installer."""
from contextlib import contextmanager
import copy
import functools
import os
import pkg_resources
import six
import unittest
import mock
from certbot import errors
from certbot.tests import util as certbot_test_util
# pylint: disable=unused-import, no-name-in-module
from ac... |
# -*- coding: utf-8 -*-
import re
from .cmd_connect import (CMD_CONNECT, CMD_DISCONNECT,
CMD_RECONNECT, CMD_RECONNECT_CONDITIONAL)
from .cmd_fetch import CMD_FETCH
from .cmd_local import (CMD_LRUN, CMD_LRUN_EXCLAMATION,
CMD_LFAILED, CMD_LSUCCEED)
from .cmd_misc import... |
"""
Indian Pines Dataset
"""
import numpy as np
import pdb
import os
import wget
import scipy as sp
from scipy.io import loadmat
from osgeo import gdal
import osgeo.gdalnumeric as gdn
from sklearn.decomposition import PCA
from sklearn import metrics, preprocessing
from sklearn.neighbors import kneighbors_graph
from... |
#
# This file is part of eo-filling.py.
# Copyright (C) 2020 Rennan Marujo.
#
# eo-filling.py is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
#
# Standard library imports
import logging
# Third party imports
import numpy
def get_from... |
#
# Copyright (c) 2021, NVIDIA CORPORATION.
#
# 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 ... |
n = int(input('Digite um número: '))
n2 = n*2
n3 = n*3
n4 = n**(1/2)
print('O dobro do número {} é igual a {}. \nO seu triplo é {}. \nA raíz quadrada dele é {:.2f}.'.format(n, n2, n3, n4))
|
import datetime
import pytz
import six
import zeit.cms.interfaces
import zeit.cms.testcontenttype.interfaces
import zeit.cms.testing
import zeit.content.image.testing
import zeit.wysiwyg.html
import zope.component
import zope.interface
ZCML_LAYER = zeit.cms.testing.ZCMLLayer(bases=(
zeit.content.image.testing.CON... |
import pytest
from pelorus.utils import (
BadAttributePathError,
collect_bad_attribute_path_error,
get_nested,
)
ROOT = dict(foo=dict(bar=dict()))
PATH = "foo.bar.baz.quux"
SLICED_PATH = ["foo", "bar"]
VALUE = dict()
def test_nested_lookup_default():
assert get_nested(ROOT, PATH, default=None) is No... |
#! /usr/bin/env python
import flask
from pathlib import Path
import importlib.util
from collections.abc import Mapping
from dataclasses import dataclass, field
from typing import Sequence
from schema import Use
from tollan.utils.fmt import pformat_yaml
from tollan.utils.log import get_logger, timeit, logit
from tolla... |
# Copyright Cloudinary
import json, re, sys
from os.path import basename
import urllib
import cloudinary
import socket
from cloudinary import utils
from cloudinary.api import Error
from cloudinary.poster.encode import multipart_encode
from cloudinary.poster.streaminghttp import register_openers
from cloudinar... |
from __future__ import absolute_import
from .tfidf import TFIDF
from .textrank import TextRank
import jieba
#easton: cost a lot of time
import jieba.posseg
import os
from operator import itemgetter
from .textrank import textrank
try:
from .analyzer import ChineseAnalyzer
except ImportError:
pass
default_tfidf ... |
def _wasm_bindgen_transition(settings, attr):
return {"//command_line_option:platforms": "@io_bazel_rules_rust//rust/platform:wasm"}
wasm_bindgen_transition = transition(
implementation = _wasm_bindgen_transition,
inputs = [],
outputs = ["//command_line_option:platforms"],
)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.