content stringlengths 5 1.05M |
|---|
import os
import unittest
import paramiko
from shutil import copyfile
from paramiko.client import RejectPolicy, WarningPolicy
from tests.utils import make_tests_data_path
from webssh.policy import (
AutoAddPolicy, get_policy_dictionary, load_host_keys,
get_policy_class, check_policy_setting
)
class TestPolic... |
#!/usr/bin/python
#
# Copyright 2019 Polyaxon, 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 o... |
# users/views.py
from rest_framework import viewsets
from . import models
from . import serializers
from rest_framework import permissions
class UserViewSet(viewsets.ModelViewSet):
queryset = models.CustomUser.objects.all()
serializer_class = serializers.UserSerializer
permission_classes = (permissions.IsA... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.signup, name='signup'),
]
|
# 133. Clone Graph 133
# ttungl@gmail.com
# Definition for a undirected graph node
# class UndirectedGraphNode:
# def __init__(self, x):
# self.label = x
# self.neighbors = []
class Solution:
def __init__(self):
self.visited = {}
# @param node, a undirected graph node
# @return ... |
from .Bible import *
class BibleParserBase:
name = "Base"
fileEndings = []
def __init__(self, file_name):
self.file_name = file_name
self.bible = Bible()
def isValidFileEnding(self, file_name):
for ending in self.fileEndings:
if '.'+ending in file_name:
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.core.validators
class Migration(migrations.Migration):
dependencies = [
('api', '0050_remove_userpreferences_accept_friend_requests'),
]
operations = [
migrations.AddFi... |
""" Unit Conversion Agent for Whyis
Uses <http://tetherless-world.github.io/whyis/inference>
as a template.
"""
from __future__ import division
from past.utils import old_div
import nltk, re, pprint
from rdflib import *
from rdflib.resource import Resource
from time import time
from whyis import autonomic
fro... |
import discord
from discord.commands import slash_command
from discord.ext import commands
class BonkV1(commands.Cog):
def __init__(self, bot):
self.bot = bot
@slash_command(name="bonk", description="bonkkk")
async def bonk_user(self, ctx):
embedVar = discord.Embed()
e... |
# Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
import os
import win32security,win32file,win32api,ntsecuritycon,win32con
from security_enums import TRUSTEE_TYPE,TRUSTEE_FORM,ACE_FLAGS,ACCESS_MODE
fname = os.path.join(win32api.GetTempPath(), "win32security_test.txt")
f=open(fname, "w")
f.write("Hello from Python\n");
f.close()
print("Testing on file", fname)
new_pr... |
# -*- coding:utf-8 -*-
# __author__="X1gang"
# Date:2018/12/02
import os,sys
from conf.settings import USER_BANK_FILE
from core.log_write import user_logger,bank_logger
from core.login import json_func,check_online
users_atm = json_func(USER_BANK_FILE)
def check_amount(amount):
if not amount.isdigit() or not(f... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 4.0.0-a53ec6ee1b on 2019-05-07.
# 2019, SMART Health IT.
import os
import io
import unittest
import json
from . import familymemberhistory
from .fhirdate import FHIRDate
class FamilyMemberHistoryTests(unittest.TestCase):
def instantiate_fro... |
import git
import os
import shutil
import platform
from tkinter import *
import jsonCreator
#import imp
from git import Repo,remote
import webbrowser
#import finalPrinter
import subprocess
from subprocess import Popen, PIPE, STDOUT
import stat
#try:
#imp.find_module('pyperclip')
#found = True
#except ImportErro... |
import matplotlib.pyplot as plt
class Stduent(object):
def __init__(self,name,score):
self.name = name
self.score = score
bart = Stduent()
|
import os,sys; sys.path.insert(0, os.path.abspath('.'))
from absl import app, flags, logging
import json
from time import sleep
import torch
import random
import pyglet
from truss_state import TrussState, BreakableTrussState
from models.config import args
from bfs import AStarNode, GreedyNode, search
from view import ... |
import glfw
from OpenGL.GL import *
class DisplayManager:
delta = 0
def __init__(self, width, height, title):
self.window = None
self.title = ''
self.last_time = 0
self.create_window(width, height, title)
def create_window(self, width, height, title):
if not glfw.... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/cloud/dialogflow_v2/proto/session.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf.internal import enum_type_wrapper
from google.protobuf import descriptor... |
from typing import List
from moodle import BaseMoodle
from moodle.base.general import GeneralStatus
from .page import PagesResponse
class BasePage(BaseMoodle):
def get_pages_by_courses(self, courseids: List[int]) -> PagesResponse:
"""Returns a list of pages in a provided list of courses, if no list is pr... |
import numpy as np
import cv2
class DinoResultsHandler:
def __init__(self, database):
self.database = database
def drawGreenBox(self, queryImage, segImage, kpImage):
# green box
gray = cv2.cvtColor(segImage,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(gray,127,255,0)
... |
import numpy as np
from swervedrive.icr.timescaler import TimeScaler
def assert_scaling_bounds(beta_dot_b, beta_2dot_b, phi_2dot_b, dbeta, d2beta, dphi_dot):
""" Function to ensure that the inequalities in the second paper hold,
given certain velocity/acceleeration bounds and commands. """
scaler = TimeSc... |
"""
This plugin is primarily useful for plugin authors who want to debug
their plugins.
It prints each hook that is called to stderr, along with details of
the event that was passed to the hook.
To do that, this plugin overrides :meth:`nose2.events.Plugin.register`
and, after registration, replaces all existing
:clas... |
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... |
# funções
def l():
print('+ ' * 20)
def soma(a, b):
print('+ ' * 15)
print(f'A vale {a} e B vale {b}')
s = a + b
print(f'A soma de A e B vale {s}')
# programa principal
soma(b=4, a=5)
soma(8, 9)
soma(2, 1)
# empacotar parametros
def contador(*num):
tam = len(num)
s = 0
for n in n... |
from flask import request
from flask_login import current_user
from oarepo_enrollment_permissions.proxies import current_enrollment_permissions
class PermissionCollection:
def __init__(self, *permissions, combining_operation='or'):
self.permissions = permissions
self.combining_operation = combini... |
# -*- coding: utf-8 -*-
# Copyright (c) Vispy Development Team. All Rights Reserved.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
from .base_camera import BaseCamera
from .perspective import PerspectiveCamera
from .panzoom import PanZoomCamera
from .arcball import ArcballCamera
from .turnta... |
import sys
import os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', 'bitpay')))
from splinter import Browser
import time
import six
import json
from bitpay_client import Client
import bitpay_key_utils as key_utils
import re
ROOT_ADDRESS = os.environ['RCROOTADDRESS']
USER_NAME = os.... |
import os
import luigi
from resolving import ResolvingWorkflow
def resolve_separately(identifier, max_jobs=48, target='local'):
task = ResolvingWorkflow
path = '/g/kreshuk/data/FIB25/data.n5'
exp_path = '/g/kreshuk/data/FIB25/exp_data/mc.n5'
# objects_group = 'resolving/oracle/perfect_oracle'
o... |
from __future__ import annotations
from dataclasses import dataclass
import bbgo_pb2
from ..enums import ChannelType
from ..enums import DepthType
@dataclass
class Subscription:
exchange: str
channel: ChannelType
symbol: str
depth: DepthType = None
interval: str = None
def to_pb(self) -> b... |
"""Unit tests for the Robot Framework Jenkins plugin source."""
from .jenkins_plugin_test_case import JenkinsPluginTestCase, JenkinsPluginTestsMixin
class RobotFrameworkJenkinsPluginTest(JenkinsPluginTestCase, JenkinsPluginTestsMixin):
"""Unit tests for the Robot Framework Jenkins plugin metrics."""
source_... |
from django.conf import settings
from .utils import is_valid_ip
from . import defaults as defs
NON_PUBLIC_IP_PREFIX = tuple([ip.lower() for ip in defs.IPWARE_NON_PUBLIC_IP_PREFIX])
TRUSTED_PROXY_LIST = tuple([ip.lower() for ip in getattr(settings, 'IPWARE_TRUSTED_PROXY_LIST', [])])
def get_ip(request, real_ip_only=... |
from setuptools import setup, find_packages
setup(
name='lib',
description='Holds the demo classes',
version='0.0.1',
author='James Dooley',
author_email='xxx@yyy.com',
packages=find_packages(exclude=('test',)),
url=''
)
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 7 12:57:47 2017
@author: ayanava
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import os
iters = [1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000]
acc_8 = [48.333333333333336, 50.0, 90.8333... |
"""2D plots of sound fields etc."""
import matplotlib as _mpl
import matplotlib.pyplot as _plt
from mpl_toolkits import axes_grid1 as _axes_grid1
import numpy as _np
from . import default as _default
from . import util as _util
def _register_cmap_clip(name, original_cmap, alpha):
"""Create a color map with "over... |
import sys
import numpy as np
def minCostPath(cost,m,n):
# cost is the matrix we are trying to traverse
# m is the row idx of cost matrix
# n is the column index of the cost matrix
if (n < 0) or (m < 0):
return sys.maxsize
elif n == 0 and m == 0:
return cost[m][n]
else:
return cost[m][n] + min (minCos... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@File : progressHelper.py
@Time : 2018/12/28
@Author : Yaronzz
@Version : 2.0
@Contact : yaronhuang@foxmail.com
@Desc : Show ProgressBar
"""
import sys
import threading
class ProgressTool(object):
def __init__(self, maxCou... |
from sortedcontainers import SortedList
import numpy as np
from .utils import log_grad
def identify_turning_points(
x_raw, local_radius=17, peak_ratio=0.2, min_log_grad=0.01):
"""
Identifies the set of 'turning points' in a time series.
Time complexity is O(N log(local_radius)).
Parameters
----------
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
File: convert_camrest_data.py
"""
import json
import ast
import numpy as np
def convert_text_for_sample(input_file, out_file):
kbs = []
dialogs = []
count = 0
with open(input_file, 'r') as fr, open(out_file, 'w') as fw:
for l... |
#!/usr/bin/env python3
""" FormatBlock - Escape Codes
Functions to test against/strip terminal escape codes from strings.
-Christopher Welborn 2-17-18
"""
import re
from typing import (
Any,
Dict,
List,
)
_codepats = (
# Colors.
r'(([\d;]+)?m{1})',
# Cursor show/hide.
r'(\?25l)',
... |
#coding=utf-8
import pandas as pd
import statsmodels.api as sm
#import pylab
import glob
def Lowess_detrend(x,y):
# z = sm.nonparametric.lowess(y, x)
# z1 = sm.nonparametric.lowess(y, x, frac=0.1)
# z45 = sm.nonparametric.lowess(y, x, frac=0.45)
z9 = sm.nonparametric.lowess(y, x, frac=0.9)
# ... |
# -*- coding: utf-8 -*-
'''
Anonymize reactions: randomize participant ids so that they do not match
the ids of the source data.
'''
import gazelib
import random
def run(input_files, output_files):
# Read reaction sequences
seqs = gazelib.io.load_json(input_files[0])
# Generate 100 random participant ids... |
__author__ = 'Thomas Kountis'
class BaseWhitelist(object):
def __init__(self):
pass
def allow(self, host, port):
pass
class DefaultWhitelist(BaseWhitelist):
def __init__(self):
BaseWhitelist.__init__(self)
def allow(self, host, port):
return True
class StaticLis... |
# Copyright (c) 2015-2020 The Botogram Authors (see AUTHORS)
#
# 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, mod... |
from flask import (
Blueprint,
redirect,
render_template,
request,
flash,
)
from flask_babel import gettext
from flask_login import login_required
from app.models import EmailOut
from .forms import *
from .logic import get_emails, send_email
from app.modules.contacts.logic import get_contact
ema... |
import argparse
import logging
import time
from collections import Counter
from pathlib import Path
import PIL
import cv2
import numpy as np
import torch
from utils.datasets import LoadImages
from constants import DEFAULT_IOU_THRESHOLD, DEFAULT_CONF_THRESHOLD, DEFAULT_DETECTED_IMAGE_DIR, \
DEFAULT_INPUT_RESOLUTIO... |
import tensorflow as tf
from utils.bert import bert_utils
from task_module import pretrain, classifier, pretrain_albert
def get_pretrain_logits(model_config,
model_api,
features,
labels,
logits,
mode,
target,
embedding_table_adv=None,
embedding_seq_adv=None,
stop... |
from pelita.player import SimpleTeam
from .demo_player import KangarooPlayer
# (please use relative imports inside your package)
# The default myteam factory function, which this package must export.
# It must return an instance of `SimpleTeam` containing
# the name of the myteam and the respective instances for
# t... |
# -*- coding: utf-8 -*-
# Copyright (c) 2020-2021 Ramon van der Winkel.
# All rights reserved.
# Licensed under BSD-3-Clause-Clear. See LICENSE file for details.
from django.utils import timezone
from django.test import TestCase
from BasisTypen.models import IndivWedstrijdklasse
from Competitie.models import (Comp... |
import time
from authlib.integrations.sqla_oauth2 import OAuth2ClientMixin, OAuth2TokenMixin, OAuth2AuthorizationCodeMixin
from sqlalchemy import Column, Integer, ForeignKey
from sqlalchemy.orm import relationship
from core.models import Base, ModelMixin
class Client(Base, ModelMixin, OAuth2ClientMixin):
__tablen... |
import logging
import unittest
import psycopg2
import sqlalchemy
import testing.postgresql
from pedsnetdcc.indexes import _indexes_sql, add_indexes, drop_indexes
from pedsnetdcc.utils import make_conn_str, stock_metadata
from pedsnetdcc.transform_runner import TRANSFORMS
from pedsnetdcc.db import Statement
logging.b... |
# -----------------------------------------------------------
# Behave Step Definitions for Aries DIDComm File and MIME Types, RFC 0044:
# https://github.com/hyperledger/aries-rfcs/blob/main/features/0044-didcomm-file-and-mime-types/README.md
#
# -----------------------------------------------------------
from behave ... |
import ConfigSpace
def get_hyperparameter_search_space_small(seed):
"""
Small version of gradient boosting config space
Parameters
----------
seed: int
Random seed that will be used to sample random configurations
Returns
-------
cs: ConfigSpace.ConfigurationSpace
The... |
# -*- coding: utf-8 -*-
import os, sys, random
import argparse
import numpy as np
import toml
import asteval
from pbpl import compton
# import Geant4 as g4
# from Geant4.hepunit import *
import h5py
import pbpl.common as common
from pbpl.common.units import *
from collections import namedtuple
def get_parser():
pa... |
#!/usr/bin/env python
# pylint: disable=missing-docstring
#
# Copyright 2017, 2018 Red Hat, Inc. and/or its affiliates
# and other contributors as indicated by the @author tags.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You m... |
"""
Elvis main module: the golden-layout panel creator.
"""
import panel as pn
import os
from .bokeh import HoloviewsBokeh
from enum import Enum
from .themes import LayoutTheme
class Block(Enum):
stack = 'stack'
row = 'row'
column = 'column'
class GoldenPanel:
"""
Generates a... |
import re
import random
import torch
from pytorch_pretrained_bert import BertTokenizer, BertModel, BertForMaskedLM
from scripts.baseline_utils import process_baseline
from collections import defaultdict
def get_tokenized_text(sen, tokenizer):
marked_text = "[CLS] " + sen + " [SEP] "
tokenized_text = tokenizer... |
import nibabel as nib
import numpy as np
import torch
from functools import partial
from collections import defaultdict
from pairwise_measures import PairwiseMeasures
from src.utils import apply_transform, non_geometric_augmentations, generate_affine, to_var_gpu, batch_adaptation, soft_dice
def evaluate(args, preds, t... |
# -*- coding: utf-8 -*-
import scrapy
from ..items import YangguangItem
class YgSpider(scrapy.Spider):
name = 'yg'
allowed_domains = ['wz.sun0769.com']
start_urls = ['http://wz.sun0769.com/index.php/question/questionType?type=4&page=0']
def parse(self, response):
"""提取列表页的数据"""
# 1.提... |
from typing import Optional
import numbers
import dynet as dy
import numpy as np
from xnmt import logger
from xnmt.param_collections import ParamManager
from xnmt.persistence import serializable_init, Serializable
from xnmt import utils
"""
The purpose of this module is mostly to expose the DyNet trainers to YAML se... |
from batchgenerators.utilities.file_and_folder_operations import *
import numpy as np
if __name__ == '__main__':
# input_file = '/home/fabian/data/nnUNet_preprocessed/Task004_Hippocampus/nnUNetPlansv2.1_plans_3D.pkl'
# output_file = '/home/fabian/data/nnUNet_preprocessed/Task004_Hippocampus/nnUNetPlansv2.1_LIS... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ####################################################################################
# Copyright (c) 2016, Francesco De Carlo #
# All rights reserved. #
# ... |
from selenium import webdriver
import constants as const
class Add_Skill:
driver = None
def __init__(self, driver):
self.driver = driver
def move_to_skills(self):
self.driver.get(const.CONNECTIONS)
def get_people(self):
xpath = '//div[contains(@class, "mn-connection-card"... |
from logics.classes.predicate.semantics import Model
class ArithmeticModel(Model):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fixed_denotations.update({
'0': 0,
's': lambda x: x + 1,
'+': lambda x, y: x + y,
'*': lamb... |
#! /usr/bin/env python
# by caozj
# Jun 4, 2019
# 8:09:11 PM
import os
os.environ["KERAS_BACKEND"] = "tensorflow"
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
import time
import argparse
import numpy as np
import dca_modpp.api
import Cell_BLAST as cb
import utils
def parse_args():
parser = argparse.ArgumentParser()... |
import typing as t
import os
import yaml
from loguru import logger
__all__ = ["config"]
class ConfigClass:
database: str
cogs: t.List[str]
admins: t.List[int]
token: str
invite: str
source: str
ball: t.Dict[str, t.List[str]]
log_channel: int
def __init__(self) -> None:
... |
"""The Config class contains the general settings that we want all
environments to have by default.Other environment classes
inherit from it and can be used to set settings that are only unique to
them. Additionally, the dictionary app_config is used to export the
environments we've specified.
"""
impor... |
""" author:
name : Do Viet Chinh
personal email: dovietchinh1998@mgail.com
personal facebook: https://www.facebook.com/profile.php?id=100005935236259
VNOpenAI team: vnopenai@gmail.com
via team :
date:
26.3.2021
"""
import numpy as np
import cv2
import os
impo... |
#
# Copyright (c) 2018 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
from django.views import generic
from openstack_dashboard.api.rest import urls
from openstack_dashboard.api.rest import utils as rest_utils
from starlingx_dashboard.api import fm
@urls.register
class AlarmSummary(generic.View)... |
import json
from phonenumbers import NumberParseException
from utils.db_api.database import TimedBaseModel, db
from utils.db_api.models.custumers import Custumer
class Phone(TimedBaseModel):
__tablename__ = "phones"
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
customer_id = db.Colum... |
from fnal_column_analysis_tools import hist
from fnal_column_analysis_tools.hist import plot
from fnal_column_analysis_tools.util import numpy as np
from .systematics import jet_pt_systs,jet_weight_systs
def fill_plots_presel(dataset,gencat,systematic,leadingak8jet,weight,plots):
genW = np.sign(weight)
plots['... |
import base64
import json
from datetime import datetime
from enum import Enum
from typing import List
from urllib.parse import urljoin
import requests
from pygrocy.utils import parse_date, parse_float, parse_int, localize_datetime
DEFAULT_PORT_NUMBER = 9192
class ShoppingListItem(object):
def __init__(self, par... |
# -*- coding: utf-8 -*-
u"""履歴管理"""
from __future__ import absolute_import, division, print_function
from maya import cmds
_RECENT_FILES_KEY = "squid_recent_fbx_files"
_RECENT_FILES_LIMIT = 10
def get_recent_files():
u"""最近使用したファイルリストを返す
Returns:
list of unicode: 最近使用したファイルリスト
"""
if not cm... |
"""
ASGI spec conformance test suite.
Calling the functions with an ASGI channel layer instance will return you a
single TestCase instance that checks for conformity on that instance.
You MUST also pass along an expiry value to the sets of tests, to allow the
suite to wait correctly for expiry. It's suggested you con... |
import csv
import tempfile
import pytest
from datarobot_batch_scoring.batch_scoring import run_batch_predictions
from utils import PickableMock
from datarobot_batch_scoring.reader import DETECT_SAMPLE_SIZE_SLOW
def test_gzipped_csv(live_server, ui):
base_url = '{webhost}/predApi/v1.0/'.format(webhost=live_serve... |
# LIGHT:
# 1) методами строк очистить текст от знаков препинания;
# 2) сформировать list со словами (split);
# 3) привести все слова к нижнему регистру (map);
# 4) получить из list пункта 3, dict, ключами которого являются слова, а значениями их количество появлений в тексте;
# 5) вывести 5 наиболее часто встречающихся... |
""" *******************************************************************************************************************
|
| Name : get_tags.py
| Description : Retrieves a list of all tags associated with a client via the RiskSense REST API.
| Copyright : (c) RiskSense, Inc.
| License : Apache-2.0 (... |
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import bibtexparser
from utility_library.constants import *
from utility_library.util import *
import collections
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
import matplotli... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
header_test_suite = {
"name": "Header tests",
"scenarios": [
{
"name": "simple header",
"args": ["-b", "basic", "--header=0,3"],
"input": '''\
1,2
3,4
5,6
7,8
9,0
1,2
3,4
''' ,
"output": '''\
+---+---+
| 1 | 2 |
+---+---+
| 3 | 4 |
| 5 | 6 |
+---+---+
| 7 | 8 |
+---+---+
... |
# getter & setter
class CovidtatusVo(object):
... |
#!/usr/bin/env python3
# ver 1.0
import requests
import os
import datetime
from time import sleep
from lxml import html
import pandas as pd
item={'気温':'temp','降水量':'rain','湿度':'humd','気圧':'pres','風速':'wind','日照時間':'sun','積雪深':'snow'}
listdf=pd.read_csv('crawl.txt',comment='#')
for i,v in listdf.iterrows():
obsn... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import argparse
import sys
from imma_formats import TABLES
def log(level, message):
sys.stderr.write('[{level}] {message}\n'.format(level=level,
message=message))
def parse_line(line):
'''
Parses a line in the I... |
# coding: utf-8
import pprint
import six
from enum import Enum
class RestCountryState:
swagger_types = {
'code': 'str',
'country_code': 'str',
'id': 'str',
'name': 'str',
}
attribute_map = {
'code': 'code','country_code': 'countryCode','id': 'id','name': 'na... |
# -*- coding: utf-8 -*-
#
# infer_score.py
#
# Copyright 2020 Amazon.com, Inc. or its affiliates. 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.apach... |
import typer
import hashlib
from pathlib import Path
from typing import Optional
from tqdm import tqdm
app = typer.Typer()
# Main command
@app.command()
def main(algorithm: str, path: str, compare_with: Optional[str] = typer.Argument(None)):
hash = Hash(algorithm, path, compare_with) # Initialize a Hash object
... |
# -*- coding: utf-8 -*-
from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import User
from rest_framework import serializers
from rest_framework.validators import UniqueValidator
from user_manage import models
# Json结构化返回数据写法
class UserSerializer(serializers.ModelSerializer):
... |
# coding:utf-8
import maya.cmds as cmds
name = "ASSET_ribbon_PART"
length = 5
ribbon = cmds.nurbsPlane(name="surf_{}".format(name), axis=[0,1,0], degree=3, lengthRatio=length, patchesU=1, patchesV=5, constructionHistory=False)[0]
cmds.rebuildSurface(ribbon, degreeU=1, degreeV=3, spansU=0, spansV=length, construction... |
from pytest import fixture, mark
from sls.document import Document, Position
from sls.indent.indent import Indentation
from sls.services.hub import ServiceHub
from tests.e2e.utils.fixtures import hub
indent_unit = " "
@fixture
def ws(magic):
return magic()
@fixture
def indentor():
return Indentation(ser... |
#!/usr/bin/env python3
# A very simple load tester
# Copyright 2018 Google
# Sebastian Weigand tdg@google.com
import poke
import os
import signal
import time
import argparse
from multiprocessing import Pool
from functools import partial
parser = argparse.ArgumentParser(
description='A simple load tester!', epilog... |
import datetime
import numpy as np
import os
import json
def calc_metric_score(y=None, preds=None, metric=None, threshold=None):
if threshold:
preds = preds > threshold
return(metric(y, preds))
def calc_threshold_metric_score(y=None,
preds=None,
... |
# REQUIRES: python-psutil
# llvm.org/PR33944
# REQUIRES: nowindows
# FIXME: This test is fragile because it relies on time which can
# be affected by system performance. In particular we are currently
# assuming that `short.py` can be successfully executed within 2
# seconds of wallclock time.
# Test per test timeou... |
from rubiks_cube_gym.envs.rubiks_cube_222 import RubiksCube222Env
import numpy as np
from operator import itemgetter
class RubiksCube222EnvOrtega(RubiksCube222Env):
def __init__(self):
super(RubiksCube222EnvOrtega, self).__init__()
self.FF = None
self.OLL = None
def check_FF(self):
... |
import threading
"""
Threaded class which monitor all services health, recover from failure if possible, reports to server and
restarts App
TODO: implement
@param service_objs
"""
class MonitorThread(threading.Thread):
def __init__(self, app):
threading.Thread.__init__(self)
self.... |
#!/usr/bin/env python
"""Publisher node for weight sensor.
"""
import glob
import os
import rospy
import serial
import time
from std_msgs.msg import Float32MultiArray
from std_srvs.srv import Empty
class WeightPublisher(object):
"""Publisher ROS node for weight sensors.
Topics
------
weights : Float3... |
"""
This module computes the canonical HRF used in
fMRIstat, both the 2-term spectral approximation
and the Taylor series approximation, to a shifted
version of the canonical Glover HRF.
References
----------
Liao, C.H., Worsley, K.J., Poline, J-B., Aston, J.A.D., Duncan, G.H.,
Evans, A.C. (2002). \'Estimating t... |
"""
Given an integer array nums, return true if there exists a triple of indices (i, j, k) such that i < j < k and nums[i] < nums[j] < nums[k]. If no such indices exists, return false.
Example 1:
Input: nums = [1,2,3,4,5]
Output: true
Explanation: Any triplet where i < j < k is valid.
Example 2:
Input: nums = [5,... |
import numpy as np
class circlequeue:
def __init__(self, _len, _dim):
self.length = _len
self.dimension = _dim
self.data = np.zeros((_len, _dim))
self.index_start = 0
self.index_end = 0
self.datasize = 0
def add(self, new_data):
self.data[self.index_end... |
# -*- coding: UTF-8 -*-
#-----------IMPORTACIONES Y LIBRERÍAS----------------------------------
import numpy as np
#Comandos trabajados: savetxt,array,loadtxt
import os as o
#Comandos trabajados: system,name,remove,getcwd
from time import sleep
#---------------parte gráfica de la jugabilidad-------------------------
d... |
#copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve.
#
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#Unless required by applicable l... |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
from google.ads.google_ads.v4.proto.resources import keyword_view_pb2 as google_dot_ads_dot_googleads__v4_dot_proto_dot_resources_dot_keyword__view__pb2
from google.ads.google_ads.v4.proto.services import keyword_view_service_pb2 as goog... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.