content stringlengths 5 1.05M |
|---|
# Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed
# under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Licens... |
from pyspark.context import SparkContext
from pyspark.conf import SparkConf
from pyspark.mllib.tree import DecisionTree
from pyspark.mllib.feature import StandardScaler
from pyspark.mllib.regression import LabeledPoint
from pyspark.mllib.recommendation import Rating, ALS, MatrixFactorizationModel
from pyspark.mllib.eva... |
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import catboost as cb
# 原始数据路径
training_path = 'D://train_data.csv'
source_data_path = 'D://preliminary-testing.csv'
# --------读取原始数据-------
# training数据
train_data = pd.read_csv(training_path, names=['S1', 'C1', 'S2', 'C2', 'S3', 'C3', 'S4',... |
from django.db import models
from django.contrib.auth.models import User
class Tweet(models.Model):
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
content = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
index_together = (('user', 'cr... |
from django.conf import settings
def _(_x):
return _x
MSG_BASE_TEMPLATE = getattr(settings, "PT_SUBSCR_MSG_BASE_TEMPLATE", "base.html")
NEWS_FROM = getattr(settings, "PT_SUBSCR_NEWS_FROM", "news@localhost")
NEWS_SUBJECT_PREFIX = getattr(settings, "PT_SUBSCR_SUBJECT_PREFIX", "[News:]")
SUBSCRIPTION_SUCCESS_MS... |
from twisted.plugin import IPlugin
from heufybot.moduleinterface import IBotModule
from heufybot.modules.commandinterface import BotCommand
from heufybot.utils.timeutils import now, timestamp
from zope.interface import implements
from datetime import datetime
class TimeCommand(BotCommand):
implements(IPlugin, IBo... |
#!/usr/bin/env python
import itertools
import json
import os
import struct
import tempfile
import bitstring
import bread as b
import pytest
# Shared structs for bread struct test
test_struct = [
{
"endianness": b.BIG_ENDIAN
},
("flag_one", b.boolean),
("flag_two", b.boolean),
("flag_thre... |
from setuptools import setup, find_packages
NAME = "appboy-client"
VERSION = "0.0.1"
REQUIRES = [
'requests==2.22.0',
]
EXTRAS = {
'dev': [
'tox',
],
}
setup(
name=NAME,
version=VERSION,
description="Appboy python client",
author_email="azh@hellofresh.com",
keywords=["HelloFr... |
# 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... |
#!/usr/bin/env python
import psycopg2
from psycopg2 import pool
class Connection:
def __init__(self, conn_settings):
try:
self.__db_name = conn_settings['db_name']
self.__db_user = conn_settings['db_user']
self.__db_password = conn_settings['db_password']
self.__db_host = conn_settings['db... |
import sys
if sys.version_info < (3, 7):
from ._zoom import ZoomValidator
from ._uirevision import UirevisionValidator
from ._style import StyleValidator
from ._pitch import PitchValidator
from ._layerdefaults import LayerdefaultsValidator
from ._layers import LayersValidator
from ._domain ... |
from unittest import TestCase
import numpy as np
from scattertext import OncePerDocFrequencyRanker
from scattertext.termscoring.CohensD import CohensD, HedgesR
from scattertext.test.test_termDocMatrixFactory import build_hamlet_jz_corpus_with_meta, build_hamlet_jz_corpus
class TestCohensD(TestCase):
def test_get_... |
# author: Bartlomiej "furas" Burek (https://blog.furas.pl)
# date: 2021.12.11
#
# title: scrape responsive table from site whose url doesnt change
# url: https://stackoverflow.com/questions/70317002/scrape-responsive-table-from-site-whose-url-doesnt-change/70317874#70317874
# [scrape responsive table from site whose ... |
import tensorflow as tf
def lstm_graph(n_steps, n_inputs, n_outputs, n_neurons, n_layers, learning_rate, seed):
with tf.name_scope('inputs'):
x = tf.placeholder(tf.float32, [None, n_steps, n_inputs], name='X_input')
y = tf.placeholder(tf.float32, [None, n_outputs], name='y_input')
keep_pr... |
#!/usr/bin/env python
import sys
sys.path.append('../Graph')
import Graph as G
def minVertexDFS(availColors, source, graph):
if source.color is None:
nsc = [graph.opposite(source, e).color
for e in graph.incidentEdges(source)]
nsc = [n for n in nsc if n is not None]
mc = [x ... |
import torch
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import sys
from os.path import join as pjoin
import scanpy as sc
import squidpy as sq
import anndata
from sklearn.metrics import r2_score, mean_squared_error
from gpsa import VariationalGPSA, rbf_kernel
from gpsa... |
# noqa: D100
from .._internals import IterableConstants
class IndexLevel(metaclass=IterableConstants):
"""Contains constants for available data frame index levels."""
DATE = 'date'
IMO = 'imo'
|
from time import sleep
from picamerax import PiCamera
camera = PiCamera()
camera.resolution = (1024, 768)
camera.start_preview()
# Camera warm-up time
sleep(2)
camera.capture('foo.jpg', resize=(320, 240))
|
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from ..utils.error import (exception_type
, check_is_int)
class tunnelSnake:
def __init__(self, serie, shift: int, threshold):
self.serie= serie
self.shift= shift
self.threshold= threshol... |
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 25 09:24:01 2014
@author: Sukhbinder Singh
Fig to data
http://www.icare.univ-lille1.fr/wiki/index.php/How_to_convert_a_matplotlib_figure_to_a_numpy_array_or_a_PIL_image
"""
import numpy
import PIL
def fig2data ( fig ):
"""
@brief Convert a M... |
name = "spft"
|
import falcon
import json
import os
from serializer import Serializer, hashing
from falcon_multipart.middleware import MultipartMiddleware
from executor import fit_implementation, implementation_predict,\
bump_version, bump_settings, implementation_tasks
import xml.etree.cElementTree as etree
i... |
from pypot.creatures import PoppyHumanoid as PH
import numpy as np
import time
import matplotlib.pyplot as plt
joint_names = ["l_shoulder_y","l_shoulder_x","l_arm_z","l_elbow_y"]
# joint_names = ["l_shoulder_x","l_arm_z","l_elbow_y"]
speed_limit = 30 # degrees per second
p = PH()
def get_position():
pos = np.arr... |
import dlib # 人脸处理的库 Dlib
import numpy as np # 数据处理的库 Numpy
import cv2 # 图像处理的库 OpenCv
import os # 读写文件
import shutil # 读写文件
class GetFace():
# Dlib 正向人脸检测器
detector = dlib.get_frontal_face_detector()
# Dlib 68 点特征预测器
d = os.path.dirname(__file__) # 返回当前文件所在的目录
... |
# coding: utf-8
import theano
import theano.tensor as T
import numpy as np
from rnn_tools import contextwin
def embedding_test():
# nv :: ボキャブラリーの個数
# de :: 埋め込み空間の次元
# cs :: コンテキストウィンドウサイズ
nv, de, cs = 1000, 50, 5
# 行列 (ボキャブラリーの個数+1)x(埋め込み空間の次元) - この単語の埋め込み空間も学習パラメータの1つ
embeddings = theano.... |
""" Write addition, substraccion, multiplication and division
operations that each result in the number 8. Be sure to enclose
your operations in 'print' statements to see the results. """
print(5+3)
print(10-2)
print(4*2)
print(int(16/2)) #not float |
import torch
from torch import nn
__all__ = ['ContextBlock', 'FPA']
def constant_init(module, val, bias=0):
if hasattr(module, 'weight') and module.weight is not None:
nn.init.constant_(module.weight, val)
if hasattr(module, 'bias') and module.bias is not None:
nn.init.constant_(module.bias, b... |
# -*- coding: utf-8 -*-
"""Generate the Resilient customizations required for fn_qradar_advisor"""
try:
from resilient import ImportDefinition
except ImportError:
# Support Apps running on resilient-circuits < v35.0.195
from resilient_circuits.util import ImportDefinition
def codegen_reload_data():
... |
import FWCore.ParameterSet.Config as cms
# input source from shared memory
source = cms.Source("DaqSource",
readerPluginName = cms.untracked.string('FUShmReader'),
evtsPerLS = cms.untracked.uint32(50)
)
|
# nghttp2 Conan package
# Dmitriy Vetutnev, Odant, 2018
from conans import ConanFile, CMake, tools
from conans.errors import ConanException
import os, glob
def get_safe(options, name):
try:
return getattr(options, name, None)
except ConanException:
return None
class Nghttp2Conan(ConanFile)... |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
x1, e1 = np.loadtxt('test10.dat', usecols=(1, 2), unpack=True)
x2, e2 = np.loadtxt('test100.dat', usecols=(1, 2), unpack=True)
x3, e3 = np.loadtxt('test1000.dat', usecols=(1, 2), unpack=True)
x4, e4 = np.loadtxt('test10000.dat', us... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from random import random
from time import sleep
import threading
class Trabajador:
def __init__(self,uid):
self.uid = uid
self.code = False ## Por defecto esta en modo activo o a la escucha
self.semaforo = threading.Semaphore(0)
self.conexi... |
from .retrieve_operations import api as retrieve_operations |
class Transaction:
def __init__(self, first_name, last_name, username, email, address, address2, country, postal, payment_method, cc_name, cc_number, cc_expiration, cc_cvv, ):
self.__first_name = first_name
self.__last_name = last_name
self.__username = username
self.__email = email
... |
"""Get the default protocol engine."""
from typing_extensions import Literal
from fastapi import Depends, status
from opentrons.hardware_control import HardwareControlAPI
from opentrons.protocol_engine import ProtocolEngine
from robot_server.errors import ErrorDetails
from robot_server.hardware import get_hardware
f... |
# This file uses Google Maps API to find the nearby '"'liquor_stores' given a location(lat, long).
# Various options for search in the Google Maps API:
# https://maps.googleapis.com/maps/api/place/findplacefromtext/output?parameters
# https://maps.googleapis.com/maps/api/place/textsearch/output?parameters
# https://ma... |
from typing import List
import numpy as np
from evobench.model.solution import Solution
def shuffle(a: np.ndarray, order: np.ndarray) -> np.ndarray:
if a.shape[-1] != order.shape[0]:
raise AssertionError('Both array and order must be of the same shape')
shuffled = a[..., order]
return shuffled
... |
import sys
import numpy as np
import cv2
from PyQt5 import QtGui
from PyQt5.QtGui import QPixmap, QPalette, QBrush
from PyQt5.QtWidgets import QWidget, QMessageBox, QApplication, QDesktopWidget, QMainWindow, QPushButton, QHBoxLayout, \
QLabel, QFileDialog, QGridLayout
import rlsb
import sp
import sxt
import wxf_t... |
# -*- coding: utf-8 -*-
from FGJumperMaster import FGJumperMaster
import cv2
from glob import glob
sample_folder = "./samples_roi"
sample_path_list = glob("%s/*.png"%(sample_folder))
# 遍历所有的样本图片
for sp in sample_path_list:
print(sp)
img = cv2.imread(sp)
JM = FGJumperMaster(img)
cv2.imwrite('./out... |
import os.path as osp
import mmcv
import numpy as np
from tools_yuan.convert_data.utils import parse_xml_coder
from tools_yuan.convert_data.utils import track_progress_yuan
import getpass
"""
Author: Yuan Yuan
Date:2018/12/16
Location:SCU
"""
def main():
xml_dir = osp.join('/media/', getpass.getuser(), 'Data/Dou... |
#
# This file is part of Zhockon Platform project.
#
# Copyright (C) 2009-2010 William Oliveira de Lagos <williamx64@gmail.com>
#
# Zhockon is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of ... |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import pickle
def plot_power_and_frequency(config):
n_profiles = config.Clustering.n_clusters
fig, ax_pcs = plt.subplots(2, 1)
for a in ax_pcs:
a.grid()
with open(config.IO.freq_distr, 'rb') as f:
freq_distr = pic... |
#!/usr/bin/python
from datetime import datetime
from datetime import timedelta
import subprocess
import time
import logging
from wrappers import GPhoto
from wrappers import Identify
from wrappers import Curl
#sudo /usr/local/bin/gphoto2 --capture-image-and-download --filename 'test3.jpg'
#curl --form "fileupload=@te... |
#!/usr/bin/env python
# coding=utf-8
import argparse
import os
import re
import subprocess
import sys
import json
from scipy.weave.converters import default
def _find_package_pid(adb_path, package):
"""Find the pid of the Flutter application process."""
ps_output = subprocess.check_output([adb_path, 'shell',... |
import glob
import cv2
import pickle
import numpy as np
struct = {}
info = np.loadtxt('./list.csv', dtype=str, delimiter=',')
for item in info[1:]:
if not item[0] in struct:
struct[item[0]] = []
struct[item[0]].append((int(item[1]), int(item[2]), item[3]))
blk_list = [
'0f8deb9380bed80d9c93c28b... |
from .noproxy import NoProxyError
|
"""style module. Contains functions to standardize styles for matplotlib-based plots"""
import seaborn as sns
import matplotlib as mpl
import matplotlib.pyplot as plt
def discrete_palette(palette='Set2', n=8):
"""Default discrete palette"""
return sns.color_palette(palette, n)
def diverging_cmap(cmap='RdBu... |
from os import getenv
from json import loads as load_json
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from django.db.models import F
from django.forms.models import model_to_dict
from jwt import encode as encode_jwt, decode as decode_jwt
from authentication.models import Us... |
import app_pages as ap
import callbacks
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
from adu_app import app
from app_modules import NavigationBar
app.layout = html.Div([
dcc.Location(id='url', refresh=False),
Navigation... |
import numpy as np
import math
import shm
from auv_math.math_utils import rotate
from auv_math.quat import quat_from_axis_angle
from auv_python_helpers.angles import abs_heading_sub_degrees
from mission.framework.combinators import Sequential, While
from mission.framework.helpers import call_if_function
from mission.... |
import warnings
import numpy as np
import scipy.optimize
def approximate_correlation_matrix(C_initial: np.ndarray,
n_max_post_fit: int = 5
) -> (np.ndarray, np.ndarray, dict):
"""Generate a valid correlation matrix from an initial matrix.
... |
"""
Find pragma and run *aaS code
SYNOPSIS
========
::
python3 compile.py
DESCRIPTION
===========
1. Find user-annotated pragma
2. Run transformation
3. Upload Deployment and Make Lambda Code
ENVIRONMENT
==========
AWS CREDENTIAL
BENCHMARK DIRECTORY
ModuleConfigClass
FILES
=====
Application Code
OUTPUT
=====... |
# BSD 3-Clause License
#
# Copyright (c) 2020, IPASC
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of... |
import os
from pathlib import Path
from unittest.mock import patch
import OpenSSL
import pynubank
from pynubank import NuException
from pynubank.utils.certificate_generator import CertificateGenerator
from pynubank.utils.http import HttpClient
def mock_error(_):
raise NuException('failed')
def mock_certs(*arg... |
from django.db import models
from django.contrib.auth import get_user_model
from utils.model_mixins import BaseAppModelMixin
User = get_user_model()
class Airline(BaseAppModelMixin, models.Model):
"""model for airlines"""
title = models.CharField(unique=True, max_length=225)
# an airline without an act... |
#!/usr/bin/env python3
import csv
class MacroSpecificBit(object):
'''Represents single entry in macro*Table_*.csv'''
def __init__(self, full_bit_name, wl, bl):
self.full_bit_name = full_bit_name
self.wl = int(wl)
self.bl = int(bl)
@property
def macro_type(self):
'''Ma... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
A spatial transformer network, a LeNet network (taken from the generic
what pathway as the exact same structure for comparaison of performance) +
A spatial transformer module.
@author: Ghassan Dabane
"""
import torch
import torch.nn as nn
import torch.nn.functional a... |
from flask.ext.script import Manager, Server, Shell
from flask.ext.migrate import Migrate, MigrateCommand
from flask_sitemap import Sitemap
import app
import os
import logging
from logging.handlers import RotatingFileHandler
from loader import Load
basedir = os.path.dirname(os.path.abspath(__file__))
LOG_DIR = os.pa... |
"""
Copyright (c) 2019, bravobravo-au
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the... |
#
# PySNMP MIB module XYLAN-FLT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/XYLAN-FLT-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:38:32 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... |
from flask import Flask, render_template, redirect
from flask_pymongo import PyMongo
import scrape_mars
app = Flask(__name__)
mongo = PyMongo(app, uri="mongodb://localhost:27017/mars")
@app.route('/')
def home():
mars = mongo.db.mars_collection.find_one()
return render_template ('index.html', mars=mars)
@app... |
'''
Report either the best hits, best equal hits or all hits from a blast search.
FOR THIS VERSION WE ARE USING THE BLAST WITH TAXID ADDED AT THE END OF THE LINE (e.g. from GI to TAX)
Note that we use the HIGHEST bit score here for this calculation.
We generate a table of [phage NC_ id, host tax id]. We need to r... |
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... |
import os
import random
import time
from flask import Flask, render_template, redirect, request
from flask_sqlalchemy import SQLAlchemy
database_file = os.getenv('DATABASE', 'sqlite:///data/data.db')
app = Flask(__name__, static_folder='static', static_url_path='')
app.config['SQLALCHEMY_DATABASE_URI'] = database_fi... |
"""
Tests for dhcp2net.dhcp
"""
from asyncio import Queue, TimeoutError
from nose.tools import eq_, raises
from dhcp2nest.util import async_test
from dhcp2nest.dhcp import DhcpEvent, find_events
MATCHING_TESTS = (
(('Oct 23 17:57:13 charon dhcpd: DHCPREQUEST for 192.168.100.83 '
'(192.168.100.1) from a0:0b... |
import os
from enum import Enum
from adventofcode import AdventDay
class FieldType(Enum):
FREE = 0
TREE = 1
PASSED = 2
class Grid:
def __init__(self, input_path) -> None:
self.rows = list()
self.line_width = 0
for line in open(input_path, "r"):
line = line.rstrip()
... |
import os
import json
import jsonlines
import logging
import pandas as pd
from tqdm import tqdm
from collections import defaultdict
from typing import List, Dict, Any
from sklearn.preprocessing import LabelEncoder
from transformers import AutoTokenizer, PreTrainedTokenizerFast
class TrainingProcessor:
"""
Thi... |
from setuptools import setup
setup(name = "py-opensmtpd-rspamd",
version = "0.0.1",
description = "py-opensmtpd-rspamd is an Rspamd filter for the OpenSMTPD MTA",
author = "Gilles Chehade",
author_email = "gilles@poolp.org",
packages = [ "opensmtpd_rspamd" ],
scripts = [
"... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2017-2018, FJTC
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright not... |
# *****************************************************************
# Copyright (c) 2013 Massachusetts Institute of Technology
#
# Developed exclusively at US Government expense under US Air Force contract
# FA8721-05-C-002. The rights of the United States Government to use, modify,
# reproduce, release, perform, displ... |
#!/usr/bin/env python
import sys
import time
import math
#import hashlib
from reportlab.pdfgen import canvas
from reportlab.lib.units import mm
from reportlab.graphics.barcode import code128
rawdata = []
for arg in sys.argv[1:]:
try:
if int(arg) > 0:
rawdata.append(int(arg))
except:
pass
i... |
"""
Created on Wed Mar 28 13:19:34 2018
@author: mohammad
"""
import os
import numpy as np
import pandas as pd
from pylab import find
import scipy.io
from sklearn.externals import joblib
# -----------------------------------------------------------------------------
# returns a list of the training and testing file ... |
def treemap(f, d: dict):
return {k: treemap(f, v) if isinstance(v, dict) else f(v) for k, v in d.items()}
def listmap(f, l: list):
return [listmap(f, e) if isinstance(e, list) else f(e) for e in l]
|
"""Placeholder helpers."""
from typing import Any, Dict, Set
from homeassistant.util.yaml import Placeholder
class UndefinedSubstitution(Exception):
"""Error raised when we find a substitution that is not defined."""
def __init__(self, placeholder: str) -> None:
"""Initialize the undefined substitut... |
"""Tune hyper-parameters for pre-trained LMs on the resource."""
import json
import logging
import os
from typing import Optional
import click
import skopt
from .... import baselines, settings, utils
from ....vendor.skopt import CheckpointSaver
logger = logging.getLogger(__name__)
# constants
COMPRESSION_LEVEL ... |
# Written by Danilo Bargen, SO 2013
import socket
def is_valid_ipv4_address(address):
try:
socket.inet_pton(socket.AF_INET, address)
except AttributeError: # no inet_pton here, sorry
try:
socket.inet_aton(address)
except socket.error:
return False
retur... |
from tesi_ao import sandbox, package_data
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate.interpolate import interp1d
'''
all the following is related to actuator #63
'''
wyko, bmc = sandbox.create_devices()
actuator_list = [63]
mcl0, cplm0, cpla0 = sandbox.main_calibration(
wy... |
from setuptools import setup
from package_info import USERNAME, VERSION
setup(name='{}-{}'.format(USERNAME, 'gym-magic-square'),
version=VERSION,
description='Gym User Env - Solve Magic Square problem',
author='Pawel Gniewek',
author_email='gniewko.pablo@gmail.com',
license='MIT License',
inst... |
from mopro.config import config
config.load_yaml('tests/test_config.yaml')
def test_init_database():
from mopro.database import initialize_database
initialize_database()
def test_setup_database():
from mopro.database import initialize_database, setup_database
initialize_database()
setup_data... |
# pylint: disable=missing-class-docstring,missing-function-docstring,missing-module-docstring
from __future__ import annotations
from configpile import Err, parsers
def test_integer() -> None:
assert parsers.int_parser.parse("345") == 345
assert isinstance(parsers.int_parser.parse("qwe"), Err)
def test_sep... |
from flask import request, Blueprint, current_app
from flask.json import jsonify
from ckanpackager import logic
from ckanpackager.lib.statistics import statistics
from ckanpackager.lib.utils import BadRequestError
status = Blueprint('status', __name__)
@status.route('/', methods=['POST'])
@status.route('/status', m... |
import os
root_path = os.path.realpath(__file__) |
#!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('VERSION.txt', 'r') as v:
version = v.read().strip()
with open('README.rst', 'r') as r:
readme = r.read()
download_url = (
'https://github.com/juliomalegria/django-chunked-uploa... |
import sys
import os
import random
from typing import Any, Tuple
import numpy as np
from tqdm import tqdm
from src import GenerationCommands
from src import GenerationCommand
from src import MakeCutouts
from src import GenerateJob
#stuff im using from source instead of installs
# i want to run clip from source, not a... |
from django.conf.urls import url
from wagtail.users.views import users
app_name = 'wagtailusers_users'
urlpatterns = [
url(r'^$', users.index, name='index'),
url(r'^add/$', users.create, name='add'),
url(r'^([^\/]+)/$', users.edit, name='edit'),
url(r'^([^\/]+)/delete/$', users.delete, name='delete'),... |
#!/usr/bin/env python
def reshape(data, n):
results = []
while data:
results.append(data[:n])
del data[:n]
return results
def format_bytes(inbytes):
byte_codes = inbytes.encode("utf-8")
shaped = reshape([b for b in byte_codes], 16)
return shaped
def format(infile):
data =... |
from ojos_ca.interface.view.django.sys import(
SeqView, SysVarView
)
from ojos_ca.usecase.interactor.django import (
ApiKeyHeaderInteractor, RequestSerialInteractor,
)
from ojos_ca.usecase.interactor.django.sys import (
GetSeqInteractor, PostSeqInteractor,
PutSeqInteractor, DeleteSeqInteractor,
GetS... |
"""
SALTS XBMC Addon
Copyright (C) 2014 tknorris
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
T... |
import sys, os, time
from signal import SIGTERM
"""
So I wrote this daemon to keep track of long=running simulations, which run
on SLURM, which I want to inherit.
The recipe for building this daemon is from
References:
Fork a Daemon Process on UNIX,
Hermann, Jurgen. 2001.
... |
import spacy
from medspacy.io.db_connect import DbConnect
from medspacy.io.db_reader import DbReader
from medspacy.io.db_writer import DbWriter
from medspacy.io.doc_consumer import DocConsumer
from medspacy.io.pipeline import Pipeline
from medspacy.context import ConTextComponent
from medspacy.section_detect... |
from collections import defaultdict
def is_valid(password, condition):
last_value = None
counts = defaultdict(int)
password = str(password)
for index in range(len(password)):
next_value = int(password[index])
if last_value and last_value > next_value:
return False
... |
from text_processing import text_normalizer
from time import time
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from sklearn.decomposition import NMF, LatentDirichletAllocation
from joblib import dump, load
import pickle
import os
import spacy
import numpy as np
from gensim.models.phrases... |
class OverrideAttr:
def __init__(self, name) -> None:
self.name = name
def __set__(self, instance, value):
print('__set__ is called')
instance.__dict__[self.name] = value
class ProxyClass:
overrideAttr = OverrideAttr('overrideAttr')
pc = ProxyClass()
print(pc.overrideAttr)
pc.__dict... |
# Copyright 2015 Google 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... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def maxPathSum(self, root: TreeNode) -> int:
global_max = -2**31
def helper(node: TreeNode):
if ... |
import os
import logging
from mlonmcu.environment.environment import Environment
from mlonmcu.environment.config import DefaultsConfig, PathConfig, RepoConfig
from mlonmcu.environment.writer import create_environment_dict
class MyEnvironment(Environment):
def __init__(self):
self._home = "/foo/bar"
... |
from django.conf.urls import url
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns=[
#............
url(r'^$',views.image_list,name='indexImages'),
url(r'^search/', views.search_results, name='search_results'),
url(r'^image/(\d+)',views.image,name... |
# -*- coding: utf-8 -*-
"""test driven data-wrangling and validation
PYTEST_DONT_REWRITE
"""
# Datatest Core API (__all__ property defined in submodules)
from .validation import * # Validation error and functions.
from .difference import * # Difference classes.
from .acceptances import ( # Acceptance context mange... |
import os
import re
from pdb import set_trace
from os.path import join
def main():
data_root = os.path.expanduser("~/dataset/pets/train")
name2dir = {}
for dir in os.listdir(data_root):
catergory_name = re.match(r'([a-zA-Z_]*)_[0-9]*.jpg', os.listdir(join(data_root, dir))[0])
... |
import time
import random
import math
import matplotlib.pyplot as plt
import numpy as np
class SequencialSearch:
def __init__(self, total_numbers, valor_a_ser_encontrado): # Estou definindo o número de valores do vetor e a chave
self.valor_a_ser_encontrado = valor_a_ser_encontrado
self.total_num... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.