content stringlengths 5 1.05M |
|---|
from random import choice
'''
s: fn fv fn
| fn fv
;
fn: "O" n
| "O" np
| "Ele"
;
np: "Diogo";
n: "gato"
| "crocodilo"
;
fv: "caçou"
| "viu"
;
Exemplo: O gato viu O diogo.
'''
g = {'s': [
['fn', 'fv', 'fn'],
['fn', 'fv'],
],
'fn': [
["o", "n"],
['o', 'np'],
['ele'],
],
... |
### Task API Views ###
from django.db.models import Q, Count
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from braces.views import CsrfExemptMixin
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_frame... |
"""Test suite for the `indcomp._maic` module.
"""
import indcomp.exceptions as e
import numpy as np
import pytest
from indcomp import MAIC
from indcomp.datasets import load_NICE_DSU18
from matplotlib.pyplot import Figure
from pytest_steps import optional_step, test_steps
@pytest.fixture
def data_NICE_DSU18():
""... |
import os
import logging
from tqdm import tqdm
import numpy as np
import argparse
import time
import sys
import mxnet as mx
from mxnet import gluon, ndarray as nd
from mxnet.gluon.data.vision import transforms
from mxnet.contrib.quantization import *
import gluoncv
gluoncv.utils.check_version('0.6.0')
from gluoncv.mo... |
#!/usr/bin/env python
# coding=utf-8
#
# Copyright © 2018 VMware, 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 r... |
# proxy module
from __future__ import absolute_import
from mayavi.sources.point_load import *
|
import numpy as np
import gurobipy as gurobi
from .problem import Problem
class PC(Problem):
_ATTRIBUTES = [
('cpu', 37),
('hd', 10),
('manufacturer', 8),
('ram', 10),
('monitor', 8),
('pctype', 3),
]
_ATTR_TO_COSTS = {
'pctype': [50, 0, 80],
... |
__title__ = "mountainproject"
name = "mountainproject"
import mountainproject.client as client
Client = client.Client
|
import sruthi
records = sruthi.searchretrieve('https://suche.staatsarchiv.djiktzh.ch/SRU/', query='Zurich')
print("records.count:", records.count)
print("len(records.records):", len(records.records))
print("records[0]:", records[0]) # print the first record
print("records[-1]:", records[-1]) # pri... |
#!/usr/bin/python
"""
KGS generates PDB-files with a 'REMARK Tree-path' in the header that can be used to
reconstruct the exploration path from any file to the initial. This program reads a PDB-file
parses the path and prints the contents of all PDB-files in the path (assumed to be
"""
import sys
def writePath(pdbP... |
from enum import Enum
import json
from .utils import config_log
from .errors import *
logger = config_log()
def _parser_generic(record: dict) -> dict:
return json.loads(record.get('body'))
def _parser_sns(record: dict) -> dict:
return json.loads(json.loads(record.get('body')).get('Message'))
def _parser_sns... |
import os
import pdb
import tempfile
import datetime
import random
import string
from traceback import print_exc as xp
from lazy_regression_tests.utils import ppp, getpath, UnavailableLibrary
#################################################################
# Depencies for test
#####################################... |
from setuptools import setup, find_packages
with open("README.md") as f:
LONG_DESCRIPTION = f.read()
setup(
name="wcxf",
version="2.0",
author="David M. Straub, Jason Aebischer",
author_email="david.straub@tum.de, jason.aebischer@tum.de",
license="MIT",
url="https://wcxf.github.io",
de... |
#!/usr/bin/python
# Copyright 2016 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 appli... |
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
sns.set_style("whitegrid")
#==============================================================================
# for test
#==============================================================================
df=pd.read_csv('reduced.csv'... |
#
# Copyright 2013 Red Hat, 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 dataclasses import dataclass, field
from typing import List, Optional
from bindings.gmd.abstract_object_type import AbstractObjectType
from bindings.gmd.dq_element_property_type import DqElementPropertyType
from bindings.gmd.dq_scope_property_type import DqScopePropertyType
from bindings.gmd.li_lineage_property_ty... |
#works better with smaller data set
import os
CAT_SOURCE_DIR = os.path.join('/Users/seanjudelyons/Downloads/Find/PetImages/Cat/')
TRAINING_CATS_DIR = os.path.join('/Users/seanjudelyons/Downloads/Find/cats-v-dogs/training/dogs/')
TESTING_CATS_DIR = os.path.join('/Users/seanjudelyons/Downloads/Find/cats-v-dogs/testing/... |
#!/usr/bin/env python3
import math
import wpilib
from ctre import WPI_VictorSPX
from wpilib.command import Subsystem
class Intake_Sub(Subsystem):
"""Operate the drivetrain."""
def __init__(self, robot):
"""Save the robot object, and assign and save hardware ports
connected to the drive motor... |
# Copyright (c) 2021 Bill Chen
# License: MIT (see LICENSE)
from . import core, il_util, loader, mesh
from .core import *
from .il_util import *
from .loader import *
from .mesh import *
__all__ = core.__all__ + il_util.__all__ + loader.__all__ + mesh.__all__
__version__ = "0.2.dev"
__name__ = "mesh_illustris"
__auth... |
# -*- coding: utf-8 -*-
"""@package Methods.Machine.SlotW12.build_geometry_wind
SlotW12 build_geometry_wind method
@date Created on Tue Mar 07 14:54:30 2015
@copyright (C) 2014-2015 EOMYS ENGINEERING.
@author pierre_b
"""
from numpy import arcsin, exp
from pyleecan.Classes.Arc1 import Arc1
from pyleecan.Classes.Arc3 ... |
import os
import sys
# Make it possible to import inside unittests without writing "abzar." at the start
sys.path.append(os.path.abspath("dh_helpcenter"))
|
import utils
from utils import digitutils as dutils
import ANN as ann
import os
import numpy as np
import matplotlib.pyplot as plt
from multiprocessing import Pool
import cv2
from scipy.stats import entropy
network_model1 = """
{
"input_shape" : [28,28,1],
"layers" : [
{
"type" : "Conv2D",
... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
import abc
from typing import Dict, NamedTuple, Optional, Sequence
from google.protobuf.timestamp_pb2 import Timestamp
from optur.proto.sampler_pb2 import SamplerConfig
from optur.proto.search_space_pb2 import Distribution, ParameterValue, SearchSpace
from optur.proto.study_pb2 import AttributeValue, Target
from optu... |
from pymongo import MongoClient
from random import randint
client = MongoClient('localhost',port=27017)
db=client.AIR_RESERVATION_SYSTEM_MONGODB6
##
flight1={'flight_id':"fl1",
'avail_seats':["A1","A2","A3","B1","B2","B3"],
'airline':"AA Air",
'src_aport':"S",
'dest_apor... |
# -*- coding: utf-8 -*-
"""
This module contains classes to work with custom OpenFOAM classes, e.g., lists
and dictionaries.
"""
from __future__ import division, print_function
import os
import foampy
from collections import OrderedDict
import numpy as np
class FoamDict(OrderedDict):
"""Object that represents an... |
# -*- coding:utf-8 -*-
def create_http_response(status,response_body):
# 9. 拼接响应报文.
# 9.1 响应行
response_line = "HTTP/1.1 %s OK\r\n" % (status)
# 9.2 响应头
response_header = "Server:Python3-vscodeIDE/2.1\r\n"
# 9.3 响应空行
response_blank = "\r\n"
# 9.4 响应主体
response_data = (response_line ... |
import shutil, errno, os
from mythic import *
from sys import exit
import subprocess
from Settings.MythicSettings import *
def mobile_ext():
temp = "./Templates/MobileConfigChrome/"
payload = "./Payloads/MobileConfigChrome_Payload"
def copyanything(src, dst):
try:
shutil.copytree(s... |
numAlunos, numAlunoDesejado = map(int, input().split())
alunos = [input() for x in range(numAlunos)]
print(f'{sorted(alunos)[numAlunoDesejado - 1]}') |
#!/usr/bin/env python3
"""
One-time utility to convert our ipdModel HDF5 files to NumPy's .npz format
"""
import argparse
import re
import sys
import h5py
import numpy as np
def run(argv):
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("file_name", help="Path to hdf5 file")
args = p.pa... |
import os
import s3fs
import tqdm
from argparse import ArgumentParser
import numpy as np
import joblib
from path import Path
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
from sklearn.model_selection import train_test_split
from collections import OrderedDict
from metasense import BOARD_CON... |
import sqlite3
# open in two steps
conn = sqlite3.connect('a.sqlite') #cria o ficheiro na diretoria do programa
cur = conn.cursor() #uma espécie de handle
cur.execute('DROP TABLE IF EXISTS Counts') #drop the table se existir
cur.execute('''
CREATE TABLE Counts (org TEXT, count INTEGER)''')
fname = input('Enter file... |
from mako.template import Template
from mako import exceptions
src_ranges = (
("r", 0, 5),
("u", 0, 5),
("i", 0, 4),
("ts", 0, 2),
("id", 0, 4),
("t", 6, 7),
)
swizzles = (
("32", "widen",
(None, None),
(None,),
(".h0", "0,16"),
(".h1", "16,16"),
(".b0", "0,8"),
... |
import numpy as np
import math
import copy
def qlearn(env, num_iters, alpha, gamma, epsilon, max_steps, use_softmax_policy, init_beta=None, k_exp_sched=None):
""" Runs tabular Q learning algorithm for stochastic environment.
Args:
env: instance of environment object
num_iters (int): Number of... |
from pyculas.Expression import *
from pyculas.formats import *
|
# -*- coding: utf-8 -*-
"""Custom paraview filter to map line orientation to cells."""
import numpy as np
import vtk
from paraview.util.vtkAlgorithm import smdomain, smproperty, smproxy
from vtk.numpy_interface import algorithms as algs
from vtkmodules.numpy_interface import dataset_adapter as dsa
from vtkmodules.util.... |
from sklearn.linear_model import LogisticRegression
from sklearn import svm
from pandas_confusion import ConfusionMatrix,BinaryConfusionMatrix
import os,errno,re,codecs,unidecode
#functions for fixing unicode issues
def remove_non_ascii(text):
return unidecode(unicode(text, encoding = "utf-8"))
def fixUnicode(te... |
import FWCore.ParameterSet.Config as cms
from Validation.TrackerHits.trackerHitsValidation_cfi import *
trackerHitsValidation = cms.Sequence(trackerHitsValid)
trackerSiStripHitsValidation = cms.Sequence(trackerSiStripHitsValid)
from Configuration.Eras.Modifier_phase1Pixel_cff import phase1Pixel
phase1Pixel.toReplace... |
import requests
import numpy
import time
#Class to store each pokemon for the tournament.
class Pokemon:
def __init__(self, pokedex, name = "", types = "", hp = 0, attack = 0, defense = 0, sataack = 0, sdefense = 0, speed = 0):
#stats & info
self.pokedex = pokedex
self.name = name
s... |
import dataclasses
import typing
import os
import re
import subprocess
import math
root_dir = '/mnt/d/Data/models/language_models'
langs = ['BG', 'CZ', 'FR', 'GE', 'HAU', 'HR', 'JP', 'KO', 'MAN', 'PL', 'PT', 'RU', 'SP', 'SWE', 'TA', 'TH', 'TU', 'VN']
seed = 1917
specials_set = {'<unk>', "<s>", "</s>"}
unknown_patte... |
import numpy as np
import os
import sys
import types
import pywt
import pandas as pd
import numpy as np
#import matplotlib.pyplot as plt
#import requests, io
from scipy.io import wavfile
import mywavfile
#from features import mfcc, logfbank
#https://python-speech-features.readthedocs.io/en/latest/
from python_speech_f... |
import random
from django.db import connection
from django.core import management
from django.core.management.color import no_style
from django.core.management.base import BaseCommand, CommandError
import winrepo.settings as settings
from profiles.models import Country, Profile, Recommendation
class Command(BaseComma... |
import requests, json
class SpotifyOauthClient():
def __init__(self):
# self.CLIENT_ID = ""
# self.CLIENT_SECRET = ""
self.CLIENT_ID = ""
self.CLIENT_SECRET = ""
self.REDIRECT_URI = "http://127.0.0.1:5000/redirect/"
self.SCOPE = "user-top-read user-read-private user... |
import sys
sys.path.insert(0, '../../../lib/')
import ph
"""
Como gerente de compras para una gran empresa de seguros usted debe decidir si actualizar o no los computadores
de la oficina. A usted se le ha dicho que el costo promedio de los computadores es de 2100 USD. Una muestra
de 64 minoristas revela un precio prom... |
import sublime, sublime_plugin
import threading
import time
i=0
class timer(threading.Thread): #The timer class is derived from the class threading.Thread
def __init__(self, num, interval):
threading.Thread.__init__(self)
self.thread_num = num
self.interval = interval
self.thre... |
"""
A quick test of the pyloxone_api module
From the command line, run:
> python -m pyloxone_api username password url
where username, password host and port are your Loxone login credentials
"""
import asyncio
import logging
import sys
from miniserver import MiniServer
_LOGGER = logging.getLogger("pyloxone_api")... |
from flask import Flask
from flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
class Hello(Resource):
def get(self):
return {'status': 'success', 'message': 'Hello! This is your first API request.'}
api.add_resource(Hello, '/')
if __name__ == '__main__':
app.run(debug=True)
|
from typing import List
import pandas as pd
from fhirpipe.analyze.attribute import Attribute
from fhirpipe.analyze.sql_column import SqlColumn
def clean_dataframe(
df, attributes: List[Attribute], primary_key_column,
):
""" Apply cleaning scripts and concept maps.
This function takes the dataframe produ... |
__author__ = 'Neil Butcher'
from PyQt4 import QtCore, QtGui
from Roles import GlobalRolesWidget
from People import PopulationWidget
from StandardTimes import StandardEventTimesWidget
from Events import EventTemplateWidget
class InstitutionCoreWidget(QtGui.QWidget):
commandIssued = QtCore.pyqtSignal(QtGui.QUndoCo... |
#!/usr/bin/env python
import os
import shutil
import subprocess
import sys
from pathlib import Path
from typing import Tuple
from vsh import api
from vsh.vendored.click import command, echo, option, style
@command()
@option('-v', 'verbose', count=True, help="More spam")
@option('-i', '--interactive', is_flag=True, h... |
# @describe: This is a module of realtime detection of hand. Learned from @murtaza's workshop.
#
# @Author: Magical-Doge
#
# @Personal URL: Https://github.com/Magical-Doge, if you like plz pity me for a ★star!!
#
# @Environments require:
#
# Package Version
# --------------------- ---------
# python ... |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) 2009- Spyder Project Contributors
#
# Distributed under the terms of the MIT License
# (see spyder/__init__.py for details)
# --------------------------------------------------------------------... |
import urllib
import time
import numpy as np
from datetime import date
import warnings
warnings.filterwarnings("ignore")
urlorig='ftp://ftp.datasus.gov.br/dissemin/publicos'
page=urllib.request.urlopen(urlorig).read()
line=page.decode("utf-8", "replace").replace('�','Á').split('\r\n')
line=line[:-1]
listdir=[]
for l i... |
import math
import tempfile
import pathlib
import numpy as np
import h5py
import scri
import pytest
def generate_bit_widths(bit_width):
possible_widths = 2 ** np.arange(0, int(np.log2(bit_width)))
bit_widths = []
while np.sum(bit_widths) < bit_width:
next_width = np.random.choice(possible_widths)
... |
from copy import copy
def saddle_points(matrix):
if not matrix:
return []
if len(set(map(len, matrix))) != 1:
raise ValueError('irregular matrix')
# Saddle point is a point where the element is the biggest in its row but the smallest in its column.
# First off, I guess I'd create colum... |
ENDPOINTS = [
{
"name": "samos",
"url": "http://doms.coaps.fsu.edu:8890/ws/search/samos",
"fetchParallel": True,
"fetchThreads": 8,
"itemsPerPage": 1000,
"metadataUrl": "http://doms.jpl.nasa.gov/ws/metadata/dataset?shortName=SAMOS&format=umm-json"
},
{
... |
# Listing_20-2.py
# Copyright Warren & Csrter Sande, 2013
# Released under MIT license http://www.opensource.org/licenses/mit-license.php
# Version $version ----------------------------
# Adding an event handler for the button
import sys
from PyQt4 import QtCore, QtGui, uic
form_class = uic.loadUiType("MyFirstGui... |
import minizinc
from minizinc import Model
print("Hi there, excited to run MZN")
# Create a MiniZinc model
basic_voting_model = Model("base_model.mzn")
gecode_solver = minizinc.Solver.lookup("gecode")
instance = minizinc.Instance(gecode_solver, basic_voting_model)
# set some parameters like this
# instance["a"] = 1
... |
from __future__ import absolute_import, division, print_function, unicode_literals
import json
import six
from cloak.serverapi.server import Server
from cloak.serverapi.utils.encoding import force_text
from ._base import BaseCommand
class Command(BaseCommand):
brief = "Show information about this server"
... |
'''
configy test suite
'''
# pylint: disable=W0104
import os
from configy import config, testconfig, load_config, ConfigyError, to_bool
from configy.config_container import build_config
BASE_DIR = os.path.dirname(__file__)
try:
import unittest2 as unittest # pylint: disable=F0401
except ImportError:
import u... |
def countingSort(arr, exp1):
n = len(arr)
output = [0] * (n)
count = [0] * (10)
for i in range(0, n):
index = (arr[i]/exp1)
count[int((index)%10)] += 1
for i in range(1,10):
count[i] += count[i-1]
i = n-1
while i>=0:
index = (arr[i]/exp1)
output[ count[ int((index)%10) ] - 1] = arr[i]
count[int((inde... |
#!/usr/bin/env vpython
# Copyright 2020 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
import collections
import logging
import sys
import unittest
import test_env
test_env.setup_test_env()
from google.protob... |
import sys
import os
import unittest
sys.path.append('../')
from app import app, netcdf_functions
class NetcdfWrapperTestCase(unittest.TestCase):
def setUp(self):
"""setup client testing"""
self.app = app
#app.config["DEBUG"] = True
#self.context = flask.Flask(__name__) ... |
#!/usr/bin/env python3
from numpy import *
from scipy import *
from scipy.interpolate import interp1d
from scipy.interpolate import pchip
import sys
import os
import argparse
import json
parser = argparse.ArgumentParser(description='Produce bd-rate report')
parser.add_argument('run',nargs=2,help='Run folders to compa... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
FOOD = ["Canned Vegetables", "Canned Meat", "Fresh Vegetables",
"Fresh Meat", "Dried Beans"]
HYGIENE = ["Toilet Paper", "ToothPaste", "Deodorant", "ToothBrush",
"Shampoo", "Soap", "HandSoap", "Tissues"]
SEX = ["Male", "Female"]
WANTS = ["Phone Call", "Vi... |
import sys
from PyQt5.QtWidgets import *
class MyWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(300, 300, 400, 300)
self.label1 = QLabel(self)
self.label1.resize(300, 30)
self.label1.move(10, 10)
self.btn1 = QPushButton("click", self)... |
#import required packages
import pandas as pd
import re
import html.parser
import urllib.request
import urllib.parse
import string
# read the 50 dimensional GloVe vectors from the file
def read_glove_vecs(file):
with open(file, 'r') as f:
words = set()
word_to_vec_map = {}
for lin... |
name = 'wsipre'
# For relative imports to work
import os, sys; sys.path.append(os.path.dirname(os.path.realpath(__file__)))
|
"""Ensure OpenID Connect Authorization Request 'claims' are preserved across authorization.
The claims parameter is an optional query param for the Authorization Request endpoint
but if it is provided and is valid it needs to be deserialized (from urlencoded JSON)
and persisted with the authorization code itself, th... |
# https://github.com/CellProfiling/HPA-Cell-Segmentation
# https://www.kaggle.com/linshokaku/faster-hpa-cell-segmentation
import os
import sys
import cv2
import imageio
import numpy as np
import torch
import torch.nn
import torch.nn.functional as F
from skimage import transform, util
import os.path
import urllib
imp... |
#!/usr/bin/python3
import yaml
import pandas as pd
import re
import sys
from query import get_reddit_data
from textgenrnn import textgenrnn
def process_title_text(text):
# Handle common HTML entities
text = re.sub(r'<', '<', text)
text = re.sub(r'>', '>', text)
text = re.sub(r'&', '&', tex... |
"""Empty init file to ensure documentation for the renderer is created."""
from flow.renderer.pyglet_renderer import PygletRenderer
__all__ = ['PygletRenderer']
|
from django.shortcuts import render, resolve_url
from django.contrib.auth.decorators import login_required
from gui.decorators import profile_required
from gui.utils import collect_view_data
from gui.signals import view_faq
from api.decorators import setting_required
@login_required
@profile_required
def api(request... |
import json, os
import numpy as np
import argparse
"对类名编号"
category = {1: "echinus", 2: "scallop", 3: "starfish", 4: "holothurian", 5: "waterweeds"}
def json_append(added_json_path, raw_json_path, added_json_image, new_json_path):
with open(added_json_image) as f:
add_image_jsRecord = f.readlines()
... |
def train_lstm_model(filenames):
print("Training LSTM based sequence to sequence model")
|
import requests
import threading
import random
import os
import time
import datetime
from colorama import Fore, init
from sys import stdout
init(convert=True, autoreset=True)
green, red, white, cyan, yellow, reset = (
Fore.LIGHTGREEN_EX,
Fore.LIGHTRED_EX,
Fore.WHITE,
Fore.LIGHTCYAN_EX,
... |
import util
def run():
print("***[ setup ]***")
print("== checking {cli} version".format(cli=util.cli))
output = util.run_cmd([util.cli, "version"])
assert len(output) == 2
if util.cli == "pfs":
assert "pfs cli: 0.2.0" in output[1]
else:
assert "riff cli: 0.3.0" in o... |
#####################################################################################
# MIT License #
# #
# Copyright (C) 2019 Charly Lamothe ... |
from django import forms
from .models import Post, Thread
class ThreadForm(forms.ModelForm):
name = forms.CharField(label="Thread name")
is_a_poll = forms.BooleanField(label="Include a poll?", required=False)
class Meta:
model = Thread
fields = ['name']
class PostForm(forms.ModelForm):... |
import json
import os
import unittest
import numpy as np
import core
root_dir = os.path.join(os.path.dirname(
os.path.abspath(__file__)), '../model')
class TestCore(unittest.TestCase):
def test_initialize_cpu(self):
core.initialize(False)
core.finalize()
def test_invalid_speaker_id(self... |
from hashlib import md5
import argparse
import time
#Encode function
def encode(hashObject, encoding='utf8'):
return md5(hashObject.encode(encoding)).hexdigest()
#Decode function
def decode(hashObject,filepath):
#Open a wordlist file with file path given by user
try:
file = open(filepath,"r")
... |
import json
import time
import requests
# 크롤링 대상 URL 목록
PAGE_URL_LIST = [
'http://example.com/page1.html',
'http://example.com/page2.html',
'http://example.com/page3.html'
]
def fetch_pages():
"""페이지의 내용을 추출합니다"""
# 처리 기록 전용 로그 파일과 오류 기록 전용 로그 파일을 append 모드로 엽니다
with open('craw... |
# coding=utf-8
"""
Module
"""
from __future__ import absolute_import
import configparser
from textwrap import dedent
from datacube.config import LocalConfig
from tests import util
def test_find_config():
files = util.write_files({
'base.conf': dedent("""\
[datacube]
db_hostname: ... |
def isValid(key):
s = 0
for i in range(len(key)-1):
s += (o(key[i])+1)*(i+1)
print s%0x24
return s % 0x24 == o(key[len(key)-1])
def o(c):
v = ord(c)
if v > 0x2f and v <= 0x39:
return v-0x30
if v <= 0x40 or v > 0x5a:
print 'wrong'
exit()
return v - 0x37
key = 'Z'*14+'A'+'L'
print isVali... |
import tensorflow as tf
DT = 0.5 # detection/classification threshold
a_pos = 1.0 # Explanation mask composition factors
a_neg = 1.0
a_bg = 1.0
def normalize(x, axis=(-2, -1), reduce_min=True, reduce_max=True):
if reduce_min: x -= tf.reduce_min(x, axis=axis, keepdims=True)
if reduce_max:
x_max = tf.reduc... |
class ErrorS:
def __init__(self, tipo, descripcion):
self.tipo = tipo
self.descripcion = descripcion
def __str__(self):
return "ERROR => tipo: %s, descripcion: %s " % (
self.tipo, self.descripcion,)
class Error:
def __init__(self, lexema, tipo, descripcion, columna, fila)... |
from tkinter import *
from tkinter import messagebox as tk_message_box
import argparse
from Helper import *
parser = argparse.ArgumentParser()
parser.add_argument('--you', help="you first or not,'true' or 'false',default you first", choices=['true', 'false'], default='true')
args = parser.parse_args()
# main window
r... |
"""Imports unittest as a replacement for testing.pybase.googletest."""
import inspect
import itertools
import os
import tempfile
# pylint: disable=wildcard-import
from unittest import *
unittest_main = main
# pylint: disable=invalid-name
# pylint: disable=undefined-variable
def main(*args, **kwargs):
"""Delegate... |
class Solution(object):
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
visited = set()
visited.add(n)
while n != 1:
n, num = 0, n
while num > 0:
n += (num % 10) ** 2
num /= 10
if n... |
from var import Var
from firebot import CMD_HELP
from firebot.utils import fire_on_cmd
@fire.on(fire_on_cmd(pattern="stat$"))
async def stats(event):
if event.fwd_from:
return
botusername = Var.TG_BOT_USER_NAME_BF_HER
noob = "stats"
if event.reply_to_msg_id:
await event.get_reply_messa... |
"""
Created: 20 May 2020
Author: Jordan Prechac
"""
from django import forms
from customer_success.models import PathwayAction
# -----------------------------------------------------------------------------
class PathwayActionInlineForm(forms.ModelForm):
class Meta:
model = PathwayAction
fields ... |
"""
tests.test_extract_rss.py
~~~~~~~~~~~~~~~~~~~~
Test suite for the extract_rss.py module
"""
import pytest
from newscrawler.extract_rss import extract_rss
from newscrawler.utils import coerce_url
def test_zeit():
url = coerce_url("zeit.de")
assert isinstance(extract_rss(url), list)
def test_spiegel():... |
import os
from urllib.request import urlopen
from io import BytesIO
from zipfile import ZipFile
import subprocess
import glob
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
from lib.helpers.dct import *
def visualize_segments(img_path, img, sigma, k, min):
print('Visualizing segments')
... |
"""
縦横断方向に値を線形補間
入力ポイント間は直線
"""
import geopandas as gpd
import numpy as np
import pandas as pd
from scipy import interpolate
class PtOnEdge:
def __init__(self, fp: str) -> None:
"""
横断ラインの始点または終点を縦断方向に並べたポイントデータ
Parameters
--------
fp : str
ポイントデータのファイルパス
... |
"""
Topic modeling with deep Boltzmann machines.
"""
from ...base import AnnotationModel
from ...due import due, BibTeX
@due.dcite(BibTeX("""
@article{DBLP:journals/corr/MontiLLAM16,
author = {Ricardo Pio Monti and Romy Lorenz and Robert Leech and
Christoforos Anagnostopoulos and Giova... |
import os
import imp
from setuptools import setup
from setuptools import Extension
dirname = os.path.dirname(__file__)
path_version = os.path.join(dirname, "vaex/ui/_version.py")
version = imp.load_source('version', path_version)
name = 'vaex'
author = "Maarten A. Breddels"
author_email = "maartenbreddels@gmail.com"
... |
from PIL import ImageChops
import numpy as np
from utilities_d_v2 import *
''' file che contiene le funzioni che applicano i filtri '''
# produce gradiente radiale con colore esterno azzurro scuro e interno chiaro
def hudson(in_image, intensity=1, alpha=1):
bg_image = radial_gradient(in_image.shape[:2][::-1], [1... |
from __future__ import absolute_import
from tensorflow.keras.layers import Layer
from abc import ABC, abstractmethod
from decomon.layers.core import F_HYBRID
class GradientLayer(ABC, Layer):
"""
Abstract class that contains the common information of every implemented layers
"""
def __init__(
... |
#!/usr/bin/python3
#
# This script allows to extract build ids from binaries published in our realm java S3 bucket.
#
# The user can specify an individual version or a set, that will be outputed as a table.
#
# The process can be slow and resource consuming, as it needs to download each release, extract it
# to finall... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.