content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
"""
A simple example, have fun!
"""
__title__ = 'pgrsearch'
__author__ = 'Ex_treme'
__license__ = 'MIT'
__copyright__ = 'Copyright 2018, Ex_treme'
from TEDT import TEDT
urls = [
'http://www.cankaoxiaoxi.com/china/20170630/2158196.shtml', # 参考消息
'http://news.ifeng.com/a/20180121/553323... |
try:
from mushroom_rl.environments.dm_control_env import DMControl
import numpy as np
def test_dm_control():
np.random.seed(1)
mdp = DMControl('hopper', 'hop', 1000, .99, task_kwargs={'random': 1})
mdp.reset()
for i in range(10):
ns, r, ab, _ = mdp.step(
... |
# 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 agreed to in writing, software
#... |
from django.db import models
from home.info_holder import get_release_type_id
from home.models import WhatTorrent
RELEASE_PRIORITIES = [
(get_release_type_id('Album'), 1000),
(get_release_type_id('EP'), 990),
(get_release_type_id('Soundtrack'), 986),
# (get_release_type_id('Single'), 985),
(get_r... |
from .Bible import Book, Verse
from .Bible_Parser_Base import BibleParserBase
import xml.etree.ElementTree as ET
import os.path
class BibleParserXML(BibleParserBase):
name = "XML"
fileEndings = ["xml"]
def __init__(self, file_name):
BibleParserBase.__init__(self, file_name)
def loadInfo(self)... |
num=float(input("Enter a number:"))
if num<0: print("\nNumber entered is negative.")
elif num>0: print("\nNumber entered is positive.")
else: print("\nNumber entered is zero.")
|
# Copyright (c) 2012 - 2015 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
import os, random
from jenkinsflow import jobload
from .framework import api_select
here = os.path.abspath(os.path.dirname(__file__))
_context = dict(
exec_time=1,
params... |
from datetime import datetime
from app import database as db
class ChatroomMessages(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
chatroomID = db.Column(db.Integer)
message = db.Column(db.String(10050), nullable = False)
sentUserID = db.Column(db.Integer, nullable=False)
timestamp = ... |
from pathlib import Path
import nibabel as nib
from skimage.transform import resize
from PIL import ImageOps
import tensorflow as tf
import numpy as np
from scipy import ndimage
class TensorflowDatasetLoader:
def __init__(self, idxs, config):
depth = config['depth']
height = config['height']
... |
# Copyright 2020 Xilinx 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 writing, ... |
from tartiflette import Directive
from tartiflette.types.exceptions.tartiflette import SkipExecution
class Skip:
async def on_field_execution(
self, directive_args, next_resolver, parent_result, args, ctx, info
):
if directive_args["if"]:
raise SkipExecution()
return await... |
"""
Expect error directives
"""
from __future__ import (
absolute_import,
unicode_literals,
)
from pyparsing import (
Literal,
Optional,
Word,
alphanums,
restOfLine,
)
import six
from pysoa.common.types import Error
from pysoa.test.plan.grammar.assertions import (
assert_actual_list_no... |
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
# Copyright (c) 2018 Juniper Networks, Inc.
# All rights reserved.
# Use is subject to license terms.
#
# Author: cklewar
import argparse
from lib.processor import TaskProcessor
from lib.processor import ServiceProcessor
from lib.pluginfactory import Emitt... |
# Smallest Multiple -- Solved
# Solution = 232792560
import math
from Timer import Timer
Stopwatch = Timer()
def LCM(n,p):
return (n*p) // math.gcd(n,p)
Solution = 1
for i in range(2, 21):
Solution = LCM(Solution, i)
print('The least common multiple of all of the numbers from 1 to 20 is: ', Solution)
Stop... |
import imghdr
import string
import random
from flask import abort
import os
from werkzeug.utils import secure_filename
from app.config import Config
def validate_image(stream):
header = stream.read(512)
stream.seek(0)
format = imghdr.what(None, header)
if not format:
return None
return '.' + (format if f... |
from lib.action import BitBucketAction
class UpdateServiceAction(BitBucketAction):
def run(self, repo, id, url):
"""
Update a service/hook
"""
bb = self._get_client(repo=repo)
success, result = bb.service.update(
service_id=id,
URL=url
)
... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import torch
import os
import sys
import numpy as np
import argparse
from copy import deepcopy
from torchvision import transforms
from models.vae import ConditionalVAE, ConditionalVAE_conv
from utils import *
import time
def main_LGLvKR_Fine(args):
os... |
#!/usr/bin/python3
from brownie.test import given, strategy
# Does the RewardAdded event fire?
@given(_amt=strategy("uint256", max_value=(10 ** 18), exclude=0))
def test_reward_added_fires(multi, reward_token, alice, _amt):
multi.stake(10 ** 18, {"from": alice})
reward_token.approve(multi, _amt, {"from": ali... |
import json
import statistics
import time
import urllib.request
from multiprocessing import Pool
with open("payload_performance.json", "r") as json_file:
json_list = list(json_file)
data_points = []
for json_str in json_list:
result = json.loads(json_str)
if not result:
continue
body = {"data... |
from __future__ import absolute_import, unicode_literals
import pytest
from six import string_types
from c8.fabric import TransactionFabric
from c8.exceptions import (
TransactionStateError,
TransactionExecuteError,
TransactionJobResultError
)
from c8.job import TransactionJob
from tests.helpers import cl... |
# 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! ***
from enum import Enum
__all__ = [
'AdministratorType',
'CatalogCollationType',
'IdentityType',
'InstancePoolLicenseType',
'Managed... |
import os
base_path = "/workspace/soft-Q-learning-for-text-generation/data/yelp-gpt2"
max_source_length = 512
max_decoding_length = 5
source_vocab_file = os.path.join(base_path, "vocab.source")
target_vocab_file = os.path.join(base_path, "vocab.target")
train = {
"batch_size": 12,
"allow_smaller_final_batch... |
import argparse
import os
import time
import logging
from logging import getLogger
import urllib
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim
import torch.utils.data as data
import torchvision.transforms as transforms
import torchvision.datasets as... |
from django.shortcuts import render,redirect
from django.contrib.auth import authenticate, login,logout
from django.contrib.auth.forms import AuthenticationForm
def login_request(request):
if request.method=='POST':
username=request.POST['username']
password=request.POST['password']
print(username,password)
u... |
from topology import topology
from json import load,dump
def convert(geojson,topojson,object_name=False, *args, **kwargs):
if isinstance(geojson,dict):
input_dict = geojson
elif isinstance(geojson,str) or isinstance(geojson,unicode):
inFile = open(geojson)
input_dict = load(inFile)
... |
# -*- coding: utf-8 -*-
import re
import lxml
import lxml.etree
from lxml.html.clean import Cleaner
import parsel
_clean_html = Cleaner(
scripts=True,
javascript=False, # onclick attributes are fine
comments=True,
style=True,
links=True,
meta=True,
page_structure=False, # <title> may be... |
class Endpoint:
index = 0
latency = 0
caches = {}
requests = {}
def __init__(self, index, latency):
self.index = index
self.latency = latency
self.caches = {}
self.requests = {}
def add_cache(self, index, latency):
self.caches[index] = latency
def a... |
from collections import Sequence
from tornado.web import RequestHandler
from hybrid.util import imports
from hybrid.metaclass import CatchExceptionMeta
class CastException(Exception):
pass
class BaseHandler(RequestHandler):
__metaclass__ = CatchExceptionMeta
def getviewfunc(self, view, module):
i... |
from app.automata_learning.black_box.pac_learning.smart_teacher.equivalence import equivalence
def model_compare(hypothesis_pre, hypothesis_now, upper_guard, system):
# Do not compare for the first time
if hypothesis_pre is None:
return True, []
eq_flag, ctx = equivalence(hypothesis_now, hypothes... |
from .user_config import load_data, save_data
|
import pandas as pd
import numpy as np
import random
import plotly.express as px
import pickle
class ShapeEstimator:
def __init__(self, connections_file_name, duplicate_data=False, point_details_file_name=None, color_definitions_file=None, optimized_points_file=None):
self.data = self.load_data(connection... |
# -*- coding: utf-8 -*-
"""
Editor: Zhao Xinlu
School: BUPT
Date: 2018-02-13
Function: 1~n整数中1出现的次数
"""
def numOf1Between1AndN(n):
"""
计数,累计1在1~n的总次数,时间效率较低
:param n:
:return:
"""
if n == 0:
return 0
if n < 0:
return None
count = 0
for i in range(1, n+1):
co... |
#
# Marco Panato
# PyMusicServer
#
import logging
import globals
from time import sleep
from database.sqlite3.dbManager import DbManager
from database.DataManager import DataManager
from music.manager import PyMusicManager
from settings.settingsprovider import SettingsProvider
from utils.threadingutils import runina... |
import logging
from aiogram import Bot, Dispatcher, executor
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.utils.executor import start_webhook
from app import handlers
from app.commands import set_commands
from app.settings import (WEBHOOK_IS_ACTIVE, WEBHOOK_URL, WEBHOOK_PATH,
... |
#!/usr/bin/env python
# Copyright (c) 2014 Miguel Sarabia
# Imperial College London
#
#
# 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 ... |
from deco.sources import Dataset
import numpy as np
def squeeze_rec(item):
if isinstance(item, list):
new_list = []
for subitem in item:
new_list.append(squeeze_rec(subitem))
if len(new_list) == 1:
new_list = new_list[0]
return new_list
else:... |
"""
Index
- all bib files for use with `glottolog refsearch`
- all languoid info files for use with `glottolog langsearch`
This will take about
- about 15 minutes to create an index of about 450 MB for references and
- a couple of minutes and create an index of about 60 MB for languoids.
"""
from pyglottolog import ft... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""=================================================================
@Project : Algorithm_YuweiYin/LeetCode-All-Solution/Python3
@File : LC-0094-Binary-Tree-Inorder-Traversal.py
@Author : [YuweiYin](https://github.com/YuweiYin)
@Date : 2022-03-06
=====================... |
# Copyright 2018 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, s... |
#!/usr/bin/env python
"""
Run the Matplotlib test suite, using the mplcairo backend to patch out
Matplotlib's agg backend.
.. PYTEST_DONT_REWRITE
"""
from argparse import ArgumentParser
import os
from pathlib import Path
import sys
import warnings
os.environ["MPLBACKEND"] = "agg" # Avoid irrelevant framework issues... |
import os
import numpy as np
import pandas as pd
data=pd.read_csv("C:/Users/Dell/OneDrive/Desktop/spotify_dataset.csv")
print(data.Index)
data=pd.read_csv("C:/Users/Dell/OneDrive/Desktop/spotify_dataset.csv", index_col=0)
data.head()
data.shape
data.info()
data.isnull()
data.isnull().sum() # We don't have ... |
# AGC028a
def main():
n, m = map(int, input().split())
s = input()
t = input()
from fractions import gcd
def lcm_base(a, b):
return a * b // gcd(a, b)
l = lcm_base(len(s), len(t))
for i in range(l, l*2, l):
x = [-1]*i
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
#written by Joshua Shaffer ([email protected])
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
import math
def main():
data0 = input("experimental group technical replicate 1 experimental gene Cq/Ct value: ")
data1 = input("experimental group tec... |
#/usr/bin/env python
"""Parsers for the Sprinzl tRNA databases.
"""
from cogent.util.misc import InverseDict
from string import strip, maketrans
from cogent.core.sequence import RnaSequence
from cogent.core.info import Info as InfoClass
__author__ = "Rob Knight"
__copyright__ = "Copyright 2007-2012, The Cogent Project... |
import os
from pathlib import Path
DEFAULT_ROOT_PATH = Path(os.path.expanduser(os.getenv("CHIA_ROOT", "~/.chia/testnet4"))).resolve()
|
from __future__ import absolute_import
from .accuracy import accuracy
from .classification import evaluate_classification, show_confusion_matrix
from .distance import compute_distance_matrix
from .lfw import evaluate_lfw
from .rank import evaluate_rank
|
#
# PySNMP MIB module JUNIPER-V1-TRAPS-MPLS (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/JUNIPER-V1-TRAPS-MPLS
# Produced by pysmi-0.3.4 at Wed May 1 14:01:25 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... |
import json
import ssl
import asyncio
import logging
import websockets
log = logging.getLogger('mattermostdriver.websocket')
log.setLevel(logging.INFO)
class Websocket:
def __init__(self, options, token):
self.options = options
if options['debug']:
log.setLevel(logging.DEBUG)
self._token = token
async de... |
USE_MMDET = True
_base_ = [
'../_base_/models/faster_rcnn_r50_fpn.py',
'../_base_/datasets/mot_challenge_det.py', '../_base_/default_runtime.py'
]
model = dict(
detector=dict(
rpn_head=dict(bbox_coder=dict(clip_border=False)),
roi_head=dict(
bbox_head=dict(bbox_coder=dict(clip_bo... |
class ContainerModuleNotFound(Exception):
pass # Raised when Container module is not found
|
import pytest
from ..bootstrap import check_dependencies
def test_check_dependencies():
check_dependencies([])
check_dependencies(["which", "cd"])
with pytest.raises(AssertionError, match="this-does-not-exist is not installed"):
check_dependencies(["this-does-not-exist"])
|
class Solution:
# @param {string} s
# @param {string} p
# @return {boolean}
def isMatch(self, s, p):
dp=[[False for i in range(len(p)+1)] for j in range(len(s)+1)]
dp[0][0]=True
for i in range(1,len(p)+1):
if p[i-1]=='*':
if i>=2:
d... |
uci_moves = []
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
for n1 in range(1, 9):
for l1 in letters:
for n2 in range(1, 9):
for l2 in letters:
uci = l1 + str(n1) + l2 + str(n2)
uci_moves.append(uci)
promotions_white = ['a7a8', 'b7b8', 'c7c8', 'd7d8', 'e7e... |
import os
import json
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("FMT")
src_path = "data/en/manifest_{}_en_cmon_clean.json"
tgt_path = "data/en/spk_{}/manifest_{}_en_cmon_clean.json"
tgt_txt_path = "data/en/spk_{}/manifest_{}_en_cmon_clean.txt"
for env in ["valid", "train"]:
... |
##########################################################################
# Author: Samuca
#
# brief: plays a mp3 song
#
# this is a list exercise available on youtube:
# https://www.youtube.com/playlist?list=PLHz_AreHm4dm6wYOIW20Nyg12TAjmMGT-
#########################################################################... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for the SYSTEMTIME structure implementation."""
from __future__ import unicode_literals
import decimal
import unittest
from dfdatetime import systemtime
class SystemtimeTest(unittest.TestCase):
"""Tests for the SYSTEMTIME structure."""
# pylint: disable=p... |
"""
REST APIs that are only used in v1 (the legacy API).
"""
|
import sqlite3
connection = sqlite3.connect('categories.db')
with open('categories.sql') as f:
connection.executescript(f.read())
cur = connection.cursor()
cur.execute("INSERT INTO categories (name) VALUES (?)",
('Food',)
)
connection.commit()
connection.close()
|
import unittest
import os
from web3 import Web3
from solcx import install_solc
# install_solc(version='latest')
install_solc(version='0.7.0')
from solcx import compile_source
EXTRA_GAS = int(os.environ.get("EXTRA_GAS", "0"))
proxy_url = os.environ.get('PROXY_URL', 'http://localhost:9090/solana')
proxy = Web3(Web3.HTT... |
import sys, os, time, serial, logging, threading
DEFAULT_TTY = '/dev/ttyUSB0'
DEFAULT_BAUD = 9600
TIMEOUT = 3.0
log = logging.getLogger(__name__)
class ArduinoSerial(object):
def __init__(self,tty=DEFAULT_TTY,baud=DEFAULT_BAUD):
self._exit = threading.Event()
self.tty = tty
self.baud = b... |
from pathlib import Path
import torch
from models.models import TfIdfModel
from data.data_preprocessing import TfIdfPreprocessor
def main():
preprocessor = TfIdfPreprocessor.load_from_checkpoint(
list(Path("test_checkpoints").glob("*.pkl"))[0]
)
model_checkpoint = torch.load(list(Path("test_check... |
from dataclasses import dataclass
from typing import Any
import torch
@dataclass
class EpochData:
epoch_id: int
duration_train: int
duration_test: int
loss_train: float
accuracy: float
loss: float
class_precision: Any
class_recall: Any
client_id: str = None
def to_csv_line(se... |
def twoNumberSum(array, targetSum):
# Write your code here.
for i in range (len(array)-1):
firstNum = array[i]
for j in range (i+1,len(array)):
secondNum =array[j]
if firstNum +secondNum ==targetSum:
return [firstNum,secondNum]
return []
|
"""
paper: Memory Fusion Network for Multi-View Sequential Learning
From: https://github.com/pliang279/MFN
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
__all__ = ['MFN']
class MFN(nn.Module):
def __init__(self, args):
super(MFN, self).__init__()
self.d_l,self.d_a,self.d_v = args.feature... |
"""
Handles incoming motion commands and translates them to actions.
Copyright (c) 2013 Sean Watson
Licensed under the MIT license
"""
import threading
import logging
import time
class MotionHandler(threading.Thread):
"""Translates motion commands to actions.
When a new motion command is received over the ... |
import numpy as np
"""
scan_options ={
"l" : length,
'x' : exclude,
'c' : column,
'b' : partitions,
'D' : corrlength,
'V' : verbosity,
'o' : file_out
}
"""
def cond_entropy(bins, t, partitions):
"""
:param bins: The discrete version fo the times series
:type bins: array of ints
:param t: the time del... |
"""
This module contains implementation of REST API views for materials app.
"""
import json
import logging
from django.conf import settings
from django.core import serializers
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
from django.db.models import Count, F, Q, QuerySet
from django... |
from conans import ConanFile
class TestConan(ConanFile):
name = "Test"
version = "0.1"
settings = "os", "compiler", "build_type", "arch"
description = "Package for Test"
url = "None"
license = "None"
def package(self):
self.copy("*", dst="lib", src="obj/libs")
self.copy("*.... |
import os
import shutil
import logging
import feedcache
import jinja2
import shelve
import staticrss.feed
def _update_feeds(feed_urls, storage):
"""Read urls from *feed_urls* and update the *storage*"""
cache_storage = shelve.open('.cache')
cache = feedcache.Cache(cache_storage)
for url in feed_urls:... |
import matplotlib.pyplot as plt
import numpy as np
def qm(x0, n):
x = np.empty(n+1)
x[0] = x0
for t in range(n):
x[t+1] = 4 * x[t] * (1 - x[t])
return x
x = qm(0.1, 250)
fig, ax = plt.subplots(figsize=(10, 6.5))
ax.plot(x, 'b-', lw=2, alpha=0.8)
ax.set_xlabel('time', fontsize=16)
plt.show()
|
from .version import __version__
from .bconfig import BConfig, Identity
from .binarize import * |
from lan_lex import *
from lan_parser import *
from lan_ast import *
|
# fabfile
# Fabric command definitions for running lock tests.
#
# Author: Benjamin Bengfort <[email protected]>
# Created: Tue Jun 13 12:47:15 2017 -0400
#
# Copyright (C) 2017 Bengfort.com
# For license information, see LICENSE.txt
#
# ID: fabfile.py [] [email protected] $
"""
Fabric command definitions f... |
from output.models.sun_data.combined.xsd005.xsd005_xsd.xsd005 import (
Base,
Ext,
Root,
Rst,
)
__all__ = [
"Base",
"Ext",
"Root",
"Rst",
]
|
import numpy as np
from sklearn.tree import DecisionTreeClassifier as Tree
from sklearn.linear_model import LogisticRegression as LR
from sklearn.isotonic import IsotonicRegression as Iso
from sklearn.base import BaseEstimator, ClassifierMixin
from sklearn.utils.validation import check_X_y, check_array, check_is_fitted... |
from .file_transfer_direction import FileTransferDirection
from .transfer_properties import TransferProperties
from .file_transfer_status import FileTransferStatus
from .transfer_statistics import TransferStatistics
from .file_transfer_exception import FileTransferException
from .file_transfer_status import FileTransfe... |
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
# For license information, please see license.txt
from __future__ import unicode_literals
import webnotes
from install_erpnext import exec_in_shell
from webnotes.model.doc import addchild
from webnotes.model.bean im... |
from numpy import array
import utils.readers as rd
from pyrr import matrix44 as mat4
# classe um objeto generico
class Object3d:
# construtor
def __init__(self, name, color, nVet, vao, vbo):
self.name = name # nome
self.color = color # cor
self.model = mat4.create_identity() # m... |
import os
import logging
from flask import Flask
from flask_mail import Mail
from flask_login import LoginManager
from flask_sqlalchemy import SQLAlchemy
__version__ = '0.1.dev'
app = Flask('databoard')
# Load default main config
app_stage = os.getenv('DATABOARD_STAGE', 'DEVELOPMENT').upper()
if app_stage in ['PRO... |
# Load an example mesh.
#
import pyvista
from pyvista import examples
mesh = pyvista.read(examples.antfile)
mesh.plot(cpos='xz')
#
# Load a vtk file.
#
mesh = pyvista.read('my_mesh.vtk') # doctest:+SKIP
#
# Load a meshio file.
#
mesh = pyvista.read("mesh.obj") # doctest:+SKIP
|
import numpy as np
import cv2
import math
class Image:
def __init__(self, name, image):
self.original = image
self.name = name
self.ysize = image.shape[0]
self.xsize = image.shape[1]
# Convert image to Grayscale
def toGrayscale(self, image):
return cv2.cvtColor(i... |
import pyfmodex, time, yaml
import numpy as np
import os
import random
import ctypes
from pyfmodex.constants import *
import logging, copy
from smooth import SmoothVal
from sound_global_state import new_channel, from_dB, VelocityFilter
import sound_global_state
from auto_sounds import AutomationGroup
system = None
# ... |
import numpy as np
import math
import scipy.stats
import estimator
class GaussEstimator(estimator.Estimator):
def __init__(self,k):
super().__init__(k)
self.mu = 0
self.std = 1
def solve(self):
self.mu = self.moments[1]
self.std = math.sqrt(self.moments[2] - self.mu*se... |
# -*- coding: utf-8 -*-
# Copyright (c) 2013 Spotify AB
import re
def deserialize(d, **kw):
names = re.sub("(?:(?:#|//).*?[\r\n])|/[*](?:.|\n)*?[*]/", " ", d).split()
if names[:1] != ['Start']:
names.insert(0, 'Start')
return (
[('v%d' % i, v_name)
for i, v_name in enumerate(nam... |
from netapp.netapp_object import NetAppObject
class Nfsv4ClientStatsInfo(NetAppObject):
"""
structure containing statistics for NFSv4 operations
"""
_rename_ops = None
@property
def rename_ops(self):
"""
total 'rename' NFSv4 operations
Range : [0..2^64-1].
"... |
import numpy as np
chislo = input('Загадай число от 0 до 99: ')
char_num = input('При делении // на 10 получается число отличное от 0?(да/нет): ')
if char_num == 'да':
odd_or_not = input('Число, полученное при делении // на 10 делится на 2 без остатка?(да/нет): ')
if odd_or_not == 'да':
char_num = inpu... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Term based tool to view *colored*, *incremental* diff in a *Git/Mercurial/Svn*
workspace or from stdin, with *side by side* and *auto pager* support. Requires
python (>= 2.5.0) and ``less``.
"""
import sys
import os
import re
import signal
import subprocess
import sel... |
# test_ptypes.py
# Copyright (c) 2013-2016 Pablo Acosta-Serafini
# See LICENSE for details
# pylint: disable=C0103,C0111,W0108
# Standard library imports
import sys
import numpy
# Putil imports
import putil.ptypes
from putil.test import AE, AI
###
# Global variables
###
emsg = lambda msg: (
'[START CONTRACT MSG:... |
#!/usr/bin/python
# parseacunetix.py
#
# By Adrien de Beaupre [email protected] | [email protected]
# Copyright 2011 Intru-Shun.ca Inc.
# v0.09
# 16 October 2011
#
# The current version of these scripts are at: http://dshield.handers.org/adebeaupre/ossams-parser.tgz
#
# Parses acunetix XML output
# http... |
import typing
from mcpython import shared
from mcpython.common.network.package.AbstractPackage import (
AbstractPackage,
DefaultPackage,
)
async def set_client_var(side, state):
shared.is_client = state
class NetworkManager:
PACKAGE_TYPES: typing.Dict[bytes, typing.Type[AbstractPackage]] = {}
... |
import os
from lib.fmd.workflow import FileManagementWorkflow
from lib.fmd.decorators import GetStage, ListStage
from lib.file.tmpfile import TemporaryFile
class GetAction(object):
def execute(self, context):
fadm = FileManagementWorkflow()
if context.fid == "all":
context.log.status('G... |
from tests.utils import W3CTestCase
class TestRtlIb(W3CTestCase):
vars().update(W3CTestCase.find_tests(__file__, 'rtl-ib'))
|
import json
from datetime import datetime
from jnius import autoclass
PythonActivity = autoclass('org.kivy.android.PythonActivity')
PythonService = autoclass('org.kivy.android.PythonService')
TaskScheduler = autoclass('org.atq.atq.TaskScheduler')
def _to_millis(time: datetime):
return int(time.timestamp() * 10... |
from typing import Dict, List, Tuple, Union, Any
import torch
import numpy as np
import os
import logging
from torch.nn.modules.rnn import LSTMCell
from torch.nn.modules.linear import Linear
import torch.nn.functional as F
from allennlp.data import Vocabulary
from allennlp.models.model import Model
from allennlp.nn.ut... |
from rich import box
from ...helper import deprecate_by
class PlotMixin:
"""Provide helper functions for :class:`Document` to plot and visualize itself."""
def _ipython_display_(self):
"""Displays the object in IPython as a side effect"""
self.summary()
def __rich_console__(self, consol... |
import h5py
from whacc import utils
import matplotlib.pyplot as plt
import numpy as np
H5_list = utils.get_h5s('/Users/phil/Dropbox/Autocurator/testing_data/MP4s/')
H5_FILE = H5_list[0]
with h5py.File(H5_FILE, 'r') as hf:
for k in hf.keys():
print(k)
print(hf['trial_nums_and_frame_nums'][:])
# with... |
# Natural Language Toolkit: Parser Utility Functions
#
# Author: Ewan Klein <[email protected]>
#
# URL: <http://nltk.sf.net>
# For license information, see LICENSE.TXT
"""
Utility functions for parsers.
"""
######################################################################
#{ Test Suites
##############... |
"""
Labels display text to users
"""
from kivy.uix.label import Label
from kivy.properties import StringProperty, NumericProperty, BooleanProperty, ColorProperty
__all__ = [
'CupertinoLabel'
]
class CupertinoLabel(Label):
"""
iOS style Label
.. image:: ../_static/label/demo.png
"""
text = ... |
# Assemble release folder
import os
import sys
import shutil
import glob
import pathlib
target = "ogm_release"
binext = ""
libext = ".so"
_from = "."
if len(sys.argv) >= 2:
_from = sys.argv[1]
if os.name == 'nt':
binext = ".exe"
libext = ".dll"
dlibext = "d" + libext
if os.... |
'''
Renames cTAKES XMI output files (named like doc%d.xmi) to use the original document name.
E.g. Plaintext abc.txt -> cTAKES doc0.xmi -> renamed abc.xmi
'''
import os
from ctakes.format import XMI
if __name__ == '__main__':
def _cli():
import optparse
parser = optparse.OptionParser(usage='Usage... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.