text stringlengths 2 999k |
|---|
# coding=utf-8
# Copyright 2020 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by a... |
from rest_framework import permissions
class IsOwnerOrReadOnly(permissions.BasePermission):
"""
This permission only allows owner to edit posts
"""
def has_object_permission(self, request, view, obj):
if request.method in permissions.SAFE_METHODS:
return True
return obj.user... |
#!/usr/bin/env python
import sys
import os
import argparse
import tensorflow as tf
from shutil import copyfile
from model import OpenNsfwModel, InputType
from image_utils import create_tensorflow_image_loader
from image_utils import create_yahoo_image_loader
import numpy as np
IMAGE_LOADER_TENSORFLOW = "tensorflow"... |
#! /usr/bin/env python
# Standard Imports
import smtplib
import mimetypes
from email import encoders
# from email.message import Message
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text... |
from modules.package.apt_helper import AptPackage
import modules.options_helper as opt_helper
def main(options):
# available config keys
options_registry = ["name","update","status"]
# verify config option provided match registry
opt_helper.check_options(options, options_registry)
... |
# Copyright 2021 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
class call_if(object):
def __init__(self, cond):
self.condition = cond
def __call__(self, func):
def inner(*args, **kwargs):
if getattr(args[0], self.condition):
return func(*args, **kwargs)
else:
return None
return inner |
# -*- coding: utf-8 -*-
#
# cognito documentation build configuration file, created by
# sphinx-quickstart on Thu Feb 13 12:04:14 2020.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# A... |
# Generated by Django 3.2.3 on 2021-05-27 17:42
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... |
# Lint as: python3
# 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 agr... |
# See "Writing benchmarks" in the asv docs for more information.
# https://asv.readthedocs.io/en/latest/writing_benchmarks.html
# or the napari documentation on benchmarking
# https://github.com/napari/napari/blob/main/docs/BENCHMARKS.md
import numpy as np
from napari.layers import Points
class Points2DSuite:
""... |
"""
The worker module provides interface for the rabbitmq client.
It provides classes to create pika clients to connect to rabbitmq broker server, interact with
and publish/subscribe to rabbitmq via creating channels, methods to publish, subscribe/consume,
stop consuming, start publishing, start connection, stop conn... |
# This is an auto-generated file. Do not edit it.
from twisted.python import versions
version = versions.Version('twisted.words', 8, 2, 0)
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
import os
from subprocess import Popen
import sys
from gi import require_version
require_version('AyatanaAppIndicator3', '0.1')
require_version('Gtk', '3.0')
from gi.repository import Gtk, GObject
from gi.repository import AyatanaAppIndicator3 as appindicator
class Sto... |
"""Callbacks: utilities called at certain points during model training.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import csv
import six
import numpy as np
import time
import json
import warnings
import io
from collections import deque
f... |
from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from django.contrib.auth import update_session_auth_hash, login, authenticate
from django.contrib import messages
from django.contrib.auth import logout
from social_django.models import Use... |
import os
import gc
import json
import time
import tqdm
import argparse
import datetime
import torch.distributed as dist
import torch.utils.data.distributed
from warpctc_pytorch import CTCLoss
from novograd import (AdamW,
Novograd)
from linknet import (SemsegLoss,
MaskSimila... |
"""added public id for users
Revision ID: 7cf6acee3bbb
Revises: fb69e94ff942
Create Date: 2019-02-15 19:55:34.010287
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '7cf6acee3bbb'
down_revision = 'fb69e94ff942'
branch_labels = None
depends_on = None
def upgra... |
# web_app/__init__.py
'''
this init file creates the app - it is the entry point into the
web_app folder
'''
from flask import Flask
'''
By importing these routes, I am able to initialize each page
when running my web_app.
'''
from web_app.models import db, migrate
from web_app.routes.home_routes import home_routes
... |
'''
Plyer
=====
'''
__all__ = ('orientation', 'proximity')
__version__ = '1.2.5dev'
from plyer import facades
from plyer.utils import Proxy
#: Orientation proxy to :class:`plyer.facades.Orientation`
orientation = Proxy('orientation', facades.Orientation)
#: Proximity proxy to :class:`plyer.facades.Proximity`
pro... |
from ..ServiceCore import Service
from ...conf.ServiceConfig import ServiceConfig
class IJob(Service):
def __init__(self,jobConfig: ServiceConfig,services: [Service]):
super().__init__(serviceConfig=jobConfig)
#region Private Methods
def _check_services(self, svcs: [Service]):
pass
... |
"""
@brief test tree node (time=2s)
"""
import os
import unittest
import datetime
import pandas
from pyquickhelper.pycode import ExtTestCase
from mathenjeu.datalog import enumerate_qcmlog, enumerate_qcmlogdf
class TestLocalAppData(ExtTestCase):
def test_datalog(self):
this = os.path.abspath(os.path.... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-"""
# @Project : stock_quant
# @Date : 2022/1/10 19:14
# @Author : Adolf
# @File : Ma5Ma10.py
import pandas_ta as ta
from BackTrader.base_back_trader import TradeStructure
from StrategyLib.StrategyLibConfig.Ma5Ma10_config import ma5ma10_config
class Ma5Ma10Strategy... |
# coding: utf-8
#!/usr/bin/env python
import paho.mqtt.client as mqtt
import json
# Configuration
BROKER_ADDRESS = '127.0.0.1'
MQTT_PORT = 1883
KEEP_ALIVE = 50
USER = 'username'
PASSWORD = 'yourpass'
topics_in = ""
responses = []
sent = []
# Define event callback
def on_connect(client, userdata, flags, rc):
... |
import unittest
import shape7
class Test_Shape7(unittest.TestCase):
coords = (
(-74.012666, 40.70136),
(-74.012962, 40.700478),
(-74.01265, 40.699074)
)
encoded = (
243, 223, 202, 70, 224, 182,
232, 38, 207, 4, 227, 13,
240, 4, 247, 21
)
tolerance = ... |
import FWCore.ParameterSet.Config as cms
from RecoLocalTracker.SiStripRecHitConverter.StripCPEfromTrackAngle_cfi import *
from RecoLocalTracker.SiStripRecHitConverter.SiStripRecHitMatcher_cfi import *
from RecoTracker.TransientTrackingRecHit.TransientTrackingRecHitBuilder_cfi import *
from RecoTracker.MeasurementDet.... |
from UE4Parse.BinaryReader import BinaryStream
from UE4Parse.IoObjects.FMinimalName import FMinimalName
from UE4Parse.IoObjects.FPackageObjectIndex import FPackageObjectIndex
class FScriptObjectEntry:
ObjectName: FMinimalName
GlobalIndex: FPackageObjectIndex
OuterIndex: FPackageObjectIndex
CDOClassInd... |
import glob
import subprocess
from setuptools import setup, find_packages, Extension
def build_libs():
subprocess.call(['cmake', '.'])
subprocess.call(['make'])
build_libs()
setup(
name='jetbot',
version='0.3.0a',
description='ALGYAN AI Study Kit based on NVIDIA Jetbot and Jetson Nano',
... |
# -*- coding: utf-8 -*-
import time
from .common import ApiTestBase, compat_mock, compat_urllib_parse
class TagsTests(ApiTestBase):
"""Tests for TagsEndpointsMixin."""
@staticmethod
def init_all(api):
return [
{'name': 'test_tag_info', 'test': TagsTests('test_tag_info', api)},
... |
from aicsimageio import AICSImage, imread, imread_dask
import czifile as zis
filename = r"C:\Users\m1srh\Downloads\Tumor_H.E_uncompressed_TSeries_3\Tumor_H&E_uncompressed_TSeries_3.czi"
# get CZI object
czi = zis.CziFile(filename)
# add axes and shape information using czifile package
print(czi.axes)
print(czi.shap... |
#!/usr/bin/env python
import pytest
"""
Test 1871. Jump Game VII
"""
@pytest.fixture(scope="session")
def init_variables_1871():
from src.leetcode_1871_jump_game_vii import Solution
solution = Solution()
def _init_variables_1871():
return solution
yield _init_variables_1871
class TestCl... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Copyright Blaze 2021.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
https://www.boost.org/LICENSE_1_0.txt)
"""
from typing import List, TypeVar, Dict
from .utils import rand_with... |
import os
import numpy as np
import pytest
from threeML.io.file_utils import within_directory
from threeML.utils.time_interval import TimeIntervalSet
from threeML.utils.time_series.event_list import EventListWithDeadTime, EventList
from threeML.utils.data_builders.time_series_builder import TimeSeriesBuilder
from three... |
import tensorflow as tf
import glob
import os
import re
##########################
# Settings #
##########################
# Which experiment to extract
import tensorflow.python.framework.errors_impl
ex = "ex4"
# Which tag should be extracted
#'eval/Reward (SMA)' 'eval/Entropy'
tags = ['eval/Reward (SM... |
"""레포지터리 패턴 구현."""
from __future__ import annotations
from typing import List, Optional, Type, TypeVar
from sqlalchemy.orm import Session
from fastmsa.core import AbstractRepository, Entity
from fastmsa.orm import get_sessionmaker
E = TypeVar("E", bound=Entity)
class SqlAlchemyRepository(AbstractRepository[E]):
... |
import argparse
import configparser
from bioblend.galaxy import GalaxyInstance
import glob
import os
# logging
import logging
logging.basicConfig(format='%(asctime)s %(message)s', level=logging.DEBUG)
log = logging.getLogger('kickstart')
def get_galaxy_item(galaxy_library_contents, item_type, item_name):
# remov... |
# Copyright (c) OpenMMLab. All rights reserved.
from abc import ABCMeta, abstractmethod
from .decode_head import BaseDecodeHead
class BaseCascadeDecodeHead(BaseDecodeHead, metaclass=ABCMeta):
"""Base class for cascade decode head used in
:class:`CascadeEncoderDecoder."""
def __init__(self, *args, **kwar... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
"""
The ``mlflow.keras`` module provides an API for logging and loading Keras models. This module
exports Keras models with the following flavors:
Keras (native) format
This is the main flavor that can be loaded back into Keras.
:py:mod:`mlflow.pyfunc`
Produced for use by generic pyfunc-based deployment tools ... |
import time
from django.db import connections
from django.db.utils import OperationalError
from django.core.management.base import BaseCommand
class Command(BaseCommand):
"""Django command to pause execution until database is available"""
def handle(self, *args, **options):
self.stdout.write('Waitin... |
"""newspaper_project URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
C... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
BLEU scoring of generated translations against reference translations.
"""
import argparse
import os
import sys
fr... |
from django.conf import settings
from django.urls import include, path
from django.conf.urls.static import static
from django.contrib import admin
from django.views.generic import TemplateView
from django.views import defaults as default_views
urlpatterns = [
path("", TemplateView.as_view(template_name="pages/home... |
import cogs.utils.sandbox |
# Valid Number
'''
A valid number can be split up into these components (in order):
A decimal number or an integer.
(Optional) An 'e' or 'E', followed by an integer.
A decimal number can be split up into these components (in order):
(Optional) A sign character (either '+' or '-').
One of the following formats:
At le... |
import numpy as np
import tabulate
import matplotlib.pyplot as plt
def display(data):
print("ProcessID\tArrival Time\tBurst Time")
for i in range(len(data)):
print("{}\t\t{}\t\t{}".format(
data[i][0], data[i][1], data[i][2]))
print("\n")
def change(processInOrder, arrived):
for i... |
import base64
import json
import os
import os.path
import shlex
import string
from datetime import datetime
from distutils.version import StrictVersion
from .. import errors
from .. import tls
from ..constants import DEFAULT_HTTP_HOST
from ..constants import DEFAULT_UNIX_SOCKET
from ..constants import DEFAULT_NPIPE
fr... |
if True:
a = 1
else:
a = 2
if False:
a = 1
elif False:
a = 2
elif False:
a = 3
else:
a = 4
for i in range (3):
a = 1
else:
a = 2
while False:
a = 1
else:
a = 2
try:
a = 1
except:
a = 2
else:
a = 3
|
def convert_date(date):
# Convert date from dd/mm/yy format to day-mon-YY format
res = str(date.day)
if date.day in (1,21,31):
res += 'st'
elif date.day in (2,22):
res += 'nd'
elif date.day in (3,23):
res += 'rd'
else:
res += 'th'
months = ['', 'January', 'Feb... |
#
# This file is part Protein Engineering Analysis Tool (PEAT)
# (C) Copyright Jens Erik Nielsen, University College Dublin 2003-
# All rights reserved
#
#
# Written by D Farrell, April 2008
#
from Tkinter import *
import csv
class TableImporter:
"""Provides import utility methods for the Table and Table Model ... |
from __future__ import annotations
__copyright__ = """
Copyright (C) 2021 Kaushik Kulkarni
"""
__license__ = """
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 wit... |
from pkg_resources import parse_version
from configparser import ConfigParser
import setuptools
assert parse_version(setuptools.__version__)>=parse_version('36.2')
# note: all settings are in settings.ini; edit there, not here
config = ConfigParser()
config.read('settings.ini')
cfg = config['DEFAULT']
readme = open('R... |
import gc
import numpy as np
import time
import ray
from hyperka.ea_funcs.utils import div_list
from hyperka.hyperbolic.metric import compute_hyperbolic_distances, normalization
g = 1000000000
@ray.remote(num_cpus=1)
def cal_rank(task, sim, top_k):
mean = 0
mrr = 0
num = [0 for k in top_k]
for i in ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File : ampel/contrib/sample/t2/T2SNcosmoComp.py
# License : BSD-3-Clause
# Author : jnordin@physik.hu-berlin.de
# Date : 03.04.2021
# Last Modified Date: 03.04.2021
# Last Modified By : jnordin@physik.hu-berlin.de
from typi... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import numpy as np
import unittest
from sklearn.base import clone
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression, LogisticRegression
from econml.dml import LinearDML
fro... |
# Copyright (c) Microsoft Corporation and contributors.
# Licensed under the MIT License.
import numpy as np
import pandas as pd
from sklearn.metrics import adjusted_rand_score
from sklearn.mixture import GaussianMixture
from sklearn.model_selection import ParameterGrid
from .base import BaseCluster
class GaussianC... |
# -*- coding: utf-8 -*-
# Scrapy settings for jianshu project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
# http://scrapy.readthedocs.org/en/latest... |
# ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Written by Bin Xiao (Bin.Xiao@microsoft.com)
# ------------------------------------------------------------------------------
from __future__ import absolute_import
from __futu... |
import matplotlib, sys
matplotlib.use('Agg')
import matplotlib.pyplot as m_plot
if __name__=='__main__':
counts = []
with open(sys.argv[1], 'r') as f:
for line in f:
name, value = line.strip().split('\t')
counts.append((int(value), name))
counts.sort(reverse=True)
counts... |
# coding: utf-8
"""
NiFi Rest Api
The Rest Api provides programmatic access to command and control a NiFi instance in real time. Start and stop processors, monitor queues, query provenance data, and more. Each endpoint below includes a description, ... |
import argparse
import os
import subprocess
import sys
CGO1_SUFFIX='.cgo1.go'
def call(cmd, cwd, env=None):
# sys.stderr.write('{}\n'.format(' '.join(cmd)))
return subprocess.call(cmd, stdin=None, stderr=sys.stderr, stdout=sys.stdout, cwd=cwd, env=env)
def process_cgo1_go(source_root, prefix, src_path, ds... |
"""
Given a binary tree and a sum, find all root-to-leaf
paths where each path's sum equals the given sum.
For example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
return
[
[5,4,11,2],
... |
from flask import Flask, request
import json
import cloudinary
import cloudinary.uploader
import string
import random
import luckyface
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
# cloudinary.config(
# cloud_name=os.environ['CLOUDINARY_CLOUD_NAME'],
# api_key=os.environ['CLOUDINARY_API_KEY'],
... |
# -*- coding: utf-8 -*-
# Copyright (c) 2015, Soldeva, SRL and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class TabladeChoferes(Document):
pass
|
from io import open
from setuptools import find_packages, setup
with open('logarhythm/logarhythm.py', 'r') as f:
for line in f:
if line.startswith('__version__'):
version = line.strip().split('=')[1].strip(' \'"')
break
else:
version = '0.0.1'
with open('README.md', 'r... |
# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
# Name: tinyNotation.py
# Purpose: A simple notation input format.
#
# Authors: Michael Scott Cuthbert
#
# Copyright: Copyright © 2009-2012, 2015 Michael Scott Cuthbert and the music21 Project
#... |
from django.db import models
from django.contrib import admin
class Product(models.Model):
product_text = models.CharField(max_length=200)
product_COD = models.FloatField()
def __str__(self):
return self.product_text
class ProductAdmin(admin.ModelAdmin):
# fields displayed on edit and add pa... |
"""
[2017-12-04] Challenge #343 [Easy] Major scales
https://www.reddit.com/r/dailyprogrammer/comments/7hhyin/20171204_challenge_343_easy_major_scales/
# Background
For the purpose of this challenge, the 12 musical notes in the *chromatic scale* are named:
C C# D D# E F F# G G# A A# B
The interval betwe... |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"totensor": "000_utils.ipynb",
"toarray": "000_utils.ipynb",
"to3dtensor": "000_utils.ipynb",
"to2dtensor": "000_utils.ipynb",
"to1dtensor": "000_utils.ipynb",
"to... |
# ***Before using this example the motor/controller combination must be
# ***tuned and the settings saved to the Roboclaw using IonMotion.
# ***The Min and Max Positions must be at least 0 and 50000
import time
from roboclaw import Roboclaw
try: # if on win32 or linux
from serial import SerialException, Se... |
# -*- coding: utf-8 -*-
from pyramid import httpexceptions
from pyramid.view import view_config
from h import models
from h.i18n import TranslationString as _ # noqa: N813
@view_config(
route_name="admin.staff",
request_method="GET",
renderer="h:templates/admin/staff.html.jinja2",
permission="admin... |
# This file is designed to provide a user with the commands required to configure their external module.
# NOTE - this file will not automatically execute any commands, the user must manually copy the commands and run them.
# TODO - add option to export commands to shell script
# Currently export of PYTHONPATH is only... |
import os
import cv2
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import itemfreq
def correct_photo(path, filename):
image = cv2.imread(os.path.join(path, filename))
pallete, image = change_colors_on_photo(image)
image = remove_noise(image)
img_pallet = create_pallete(pallet... |
import time
import serial
import serial.tools.list_ports as slp
class DigitalIO(object):
def __init__(self, name):
self.o_state = 0
self.i_state = 0
def _apply_mask(self, value, mask):
self.o_state = (self.o_state & ~mask) | (value & mask)
def read(self):
raise NotImple... |
import matplotlib.pyplot as plt
import matplotlib.dates as d
from numpy import linspace
from .analysis import polyfit
def plot_water_levels(station, dates, levels):
""" Plots the station water level history against time """
# Return early if data is invalid
if len(dates) != len(levels):
print("fl... |
import torch
from mmdet.core import bbox2result
from mmdet.models.builder import DETECTORS
from ...core.utils import flip_tensor
from .single_stage import SingleStageDetector
@DETECTORS.register_module()
class CenterNet(SingleStageDetector):
"""Implementation of CenterNet(Objects as Points)
<https://arxiv.o... |
from .Section import *
class SectionParagraph(Section):
def __init__(self, api, data):
"""
Internal use only: initialize section object
"""
if (not(data==None) & (type(data) == dict) &
("sectionType" in data.keys())
):
if data["sectio... |
import os
import glob
import sys
import functools
import jsonpickle
from collections import OrderedDict
from Orange.widgets import widget, gui, settings
import Orange.data
from Orange.data.io import FileFormat
from DockerClient import DockerClient
from BwBase import OWBwBWidget, ConnectionDict, BwbGuiElements, getIconN... |
# global
import mxnet as mx
import math
import numpy as np
from typing import Union, Tuple, Optional, List
from ivy.functional.backends.mxnet import _flat_array_to_1_dim_array, _handle_flat_arrays_in_out, _handle_flat_arrays_in
def flip(x: mx.ndarray.ndarray.NDArray,
axis: Optional[Union[int, Tuple[int], List... |
# Copyright 2013, 2014 Intel Corporation.
# 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
#
# Unles... |
"""
Couette Flow
"""
import numpy as np
from lettuce.unit import UnitConversion
from lettuce.boundary import BounceBackBoundary, EquilibriumBoundaryPU
class CouetteFlow2D(object):
def __init__(self, resolution, reynolds_number, mach_number, lattice):
self.resolution = resolution
self.units = Uni... |
import pymorphy2
import re
def tokenize(text):
# List of allowed POS, others won't be included
# in the final set.
allowedPOS = ['NOUN', 'VERB']
morpher = pymorphy2.MorphAnalyzer()
text = re.sub(r'[^а-я0-9 ]', ' ', text.lower())
while ' ' in text:
text = text.replace(' ', ' ... |
#!/usr/bin/env python3
from test_base import run_test
if __name__ == '__main__':
reference_hive_node_url = 'http://127.0.0.1:8090'
test_hive_node_url = 'http://127.0.0.1:8080'
payload = {
"jsonrpc":"2.0",
"method":"database_api.list_comments",
"params" : {
"start" : ['s... |
# -*- coding:utf-8 -*-
import cv2
#读取图片
img = cv2.imread("picture.bmp", cv2.IMREAD_UNCHANGED)
#灰度图像
p = img[88, 142]
print(p)
#显示图像
cv2.imshow("Demo", img)
#等待显示
cv2.waitKey(0)
cv2.destroyAllWindows()
#写入图像
cv2.imwrite("testyxz.jpg", img)
|
import Event, RemoveFocusEvent
import eventFunction, mouseFunction
print('FalseClickEvent library imported')
class FalseClickEvent(Event.Event):
def update(self):
RemoveFocusEvent.RemoveFocusEvent(self.object)
self.updateStatus(eventFunction.Status.RESOLVED)
def __init__(self,application,
... |
# 문자열 다루기 기본
```python
def solution(s):
if (len(s) == 4 or len(s) == 6) and s.isdigit():
return True
else:
return False
# if len(s) == 4 or 6 이라고만 하면 왜 자꾸 길이조건이 안될까
```
|
dictionary = {'a1':'1','a2':'2','a3':'3'}
print(dictionary)
result = dictionary['a2']
print(result) |
#!/usr/bin/env python
from utils import utils, inspector
from datetime import datetime
from urllib.parse import urljoin, urlparse
import os.path
archive = 2006
INDEX_URLS = [
"https://www.amtrakoig.gov/reports/all-audits",
"https://www.amtrakoig.gov/reports/all-investigations",
"https://www.amtrakoig.gov/readi... |
from django.core.validators import validate_comma_separated_integer_list
from django.db import models
MASTERY_TYPES = {
0: 'School',
1: 'Domain',
2: 'Bloodline',
3: 'Mystery',
4: 'Patron',
}
class Mastery(models.Model):
"""
A generic class to represent gerarchy of Schools, Domains, Blood... |
import numpy as np
import pandas as pd
from pandas import Int64Index, TimedeltaIndex, timedelta_range
import pandas.util.testing as tm
class TestTimedeltaIndex(object):
def test_union(self):
i1 = timedelta_range('1day', periods=5)
i2 = timedelta_range('3day', periods=5)
result = i1.unio... |
import sys
import os
# local path to the code
local_path = "/Users/zhengz11/myscripts/git_clone/pn_kc/pn_kc/"
sys.path.append(local_path)
# exec(open(local_path + "/connectivity/startup.py").read())
import mushroom_2to3.connect as cc
import mushroom_2to3.analysis_routine as ar
from mushroom_2to3.shuffle import *
fr... |
import warnings
from collections import Counter
import re
import random
import numpy as np
def first(x):
"""Returns the first not-NA value, helper function for pd.DataFrame.apply.
Args:
x (pd.Series): columns/rows passed in pd.DataFrame.apply function
Returns:
flexible: first not-NA value... |
# -*- coding: utf-8 -*-
from gtts import gTTS, gTTSError, __version__
from gtts.lang import tts_langs
import click
import logging
import logging.config
# Click settings
CONTEXT_SETTINGS = {
'help_option_names': ['-h', '--help']
}
# Logger settings
LOGGER_SETTINGS = {
'version': 1,
'formatters': {
... |
from webwhatsapi.objects.whatsapp_object import WhatsappObject, driver_needed
from webwhatsapi.helper import safe_str
from webwhatsapi.objects.message import Message
##TODO: Fix relative imports for Python3
class ChatMetaClass(type):
"""
Chat type factory
"""
def __call__(cls, js_obj, driver=None):
... |
import csv
import gc
import glob
import json
import os
import shutil
import sys
import warnings
from collections import Counter
from multiprocessing import Process, Queue
from pprint import pprint
# Prevent Keras info message; "Using TensorFlow backend."
STDERR = sys.stderr
sys.stderr = open(os.devnull, "w")
sys.stde... |
import uuid
import json
import time
import random
import urllib3
import datetime
import contextlib
import subprocess
import concurrent.futures
from threading import Thread, Lock
from collections import defaultdict
import boto3
import requests
from botocore.client import Config
from botocore.exceptions import ClientErr... |
from pwn import *
r = remote("54.65.72.116", 31337)
print r.recvuntil("> ")
d = open("start.rb").read()
r.send(d)
r.interactive()
|
# Leetcode 844. Backspace String Compare
#
# Link: https://leetcode.com/problems/backspace-string-compare/
# Difficulty: Easy
# Solution using two pointers.
# Complexity:
# O(N) time | where N represent the lenght of the longest input string
# O(1) space
class Solution:
def backspaceCompare(self, s: str, t: s... |
import factory
import factory.fuzzy
from faker import Faker
from risk_maker.risk.config import FieldType
from risk_maker.risk.models import RiskField, RiskType, Risk
fake = Faker()
class RiskTypeFactory(factory.django.DjangoModelFactory):
class Meta:
model = RiskType
name = factory.Faker('word')
... |
def sieve(m):
l = [True]*(int(m**.5)+2)
l[0], l[1] = False, False
for i in range(2, len(l)):
if not l[i]:
continue
for j in range(i*2, len(l), i):
l[j] = False
return l
def reverse_primes(l):
for i in range(len(l)-1, 1, -1):
if l[i]:
yield... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.