text stringlengths 1 927k |
|---|
from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from selenium.common.exceptions import NoSuchElementException
from .helpers import SeleniumTestCase
class LareRequestTest(SeleniumTestCase):
def test_lare_request_depth_1(self):
self.browser_get_reverse('index')
... |
# @Auther : wuwuwu
# @Time : 2020/4/15
# @File : q23.py
# @Description : 直方图均衡化
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
def histogramEqualization(img, Zmax=255):
"""
直方图均衡化
:param img:
:param Zmax: 像素的最大取值
:return:
"""
H, W, C = img.shape
S = H * W * ... |
from board import Board
from logging import getLogger, DEBUG, basicConfig
from libfastbb import FastBitBoard
import numpy as np
import utilities
class FastBitBoardTester(Board):
def __init__(self, rows=8, columns=8):
super(FastBitBoardTester, self).__init__()
self._impl = FastBitBoard()
se... |
"""
Some codes from https://github.com/Newmu/dcgan_code
"""
from __future__ import division
import math
import json
import random
import pprint
import scipy.misc
import numpy as np
from time import gmtime, strftime
from six.moves import xrange
from glob import glob
import cv2
import imageio
import tensorflow as tf
imp... |
__author__ = 'joesacher'
import datetime as dt
class AlienTag(object):
def __init__(self, taglist_entry):
self.disc = 0
self.last = 0
self.last_last = 0
self.id = 0
self.ant = 0
self.count = 0
self.proto = 0
self.rssi = 0
self.freq = 0
# ... |
from idaapi import *
'''
Author: Chris Eagle
Name: Clemency function fixup plugin defcon 25
How: Install into <idadir>/plugins
Activate within a function using Alt-8
'''
class clemency_plugin_t(plugin_t):
flags = 0
wanted_name = "Fix Clemency Functions"
wanted_hotkey = "Alt-8"
comment = ""
help = ... |
# Generated by Django 3.1.1 on 2020-09-23 19:14
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Network',
fields=[
('id', models.AutoField(... |
# 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 ... |
#!/usr/bin/python3
'''
(C) Copyright 2018-2021 Intel Corporation.
SPDX-License-Identifier: BSD-2-Clause-Patent
'''
import traceback
import threading
import random
import base64
from apricot import TestWithServers
from general_utils import DaosTestError, get_random_bytes
from pydaos.raw import DaosApiError
from da... |
import os
import argparse
import pandas as pd
from tqdm import tqdm
import torch
import torch.nn as nn
import pytorch_lightning as pl
from pytorch_lightning.callbacks import ModelCheckpoint
from utils.models import EfficientNetModel, EfficientNetSSL
from utils.transforms import get_transforms
from utils.loaders impo... |
"""Define the command line iterface."""
import os
import glob
def _file_path():
"""Determine the file path."""
return os.environ.get("EFI_MONITOR_FILE_PATH", "/sys/firmware/efi/efivars/dump*")
def _files():
"""Find the dump_files."""
return glob.glob(_file_path())
def check():
"""Check for efi... |
from panda3d.physics import SpriteParticleRenderer
class SpriteParticleRendererExt(SpriteParticleRenderer):
"""
Contains methods to extend functionality
of the SpriteParticleRenderer class
"""
# Initialize class variables for texture, source file and node for texture and
# node path textures ... |
from adapters.rgbw_adapter import RGBWAdapter
from adapters.generic.blind_adapter import BlindAdapter
from adapters.zemismart.ZMCSW002D import ZMCSW002D
from adapters.zemismart.ZML03EZ import ZML03EZ
zemismart_adapters = {
'LXZB-12A': RGBWAdapter, # Zemismart RGB LED downlight
'ZM-CSW002-D': ZMCSW002D, # ... |
import basic_SPN as cipher
pbox = {0:0, 1:4, 2:8, 3:12, 4:1, 5:5, 6:9, 7:13, 8:2, 9:6, 10:10, 11:14, 12:3, 13:7, 14:11, 15:15}
# test pbox functionality/symmetry
def testPBox(statem: list, pbox: dict):
staten = [0]*len(pbox)
for tpi, tp in enumerate(statem):
staten[pbox[tpi]] = tp
#print (staten)
... |
"""
SEP: 0002
Title: Federation protocol
Author: stellar.org
Status: Final
Created: 2017-10-30
Updated: 2019-10-10
Version 1.1.0
"""
from typing import Any, Coroutine, Dict, Optional, Union
from ..client.base_async_client import BaseAsyncClient
from ..client.base_sync_client import BaseSyncClient
from ..client.request... |
import os
import numpy as np
import pytest
from jina import Document, __windows__
cur_dir = os.path.dirname(os.path.abspath(__file__))
def test_uri_to_blob():
doc = Document(uri=os.path.join(cur_dir, 'test.png'))
doc.convert_image_uri_to_blob()
assert isinstance(doc.blob, np.ndarray)
assert doc.mim... |
import numpy as np
from ..builder import SCALAR_SCHEDULERS
from .base import BaseScalarScheduler
@SCALAR_SCHEDULERS.register_module()
class StepScalarScheduler(BaseScalarScheduler):
def __init__(self, scales, num_iters, by_epoch=False):
super(StepScalarScheduler, self).__init__()
self.by_epoch =... |
# coding:utf8
import torch as t
import torchvision as tv
import torchnet as tnt
from torch.utils import data
from transformer_net import TransformerNet
import utils
from PackedVGG import Vgg16
from torch.nn import functional as F
import tqdm
import os
import ipdb
# from WCT2_train import WCT2
# import model
from Lap... |
# -*- coding: utf-8 -*-
"""
File to test Indexing Techniques
"""
__created__ = "2009-09-14"
__updated__ = "2009-09-14"
__author__ = "João Chaves <joaochaves@gpr.com.br>"
from os.path import join, exists
from os import remove, getcwd
from sys import platform, path
from pyisis.files import MasterFile
from pyisis.conf... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import io
from setuptools import setup
setup(
name='qnapstats',
description='Python API for obtaining QNAP NAS system stats',
long_description=io.open('README.rst', encoding='utf-8').read(),
version='0.3.1',
license='MIT',
author='Colin O\'Dell',
... |
from ciscosupportsdk.apisession import ApiSession
SERVICE_BASE_URL = "/software/v4.0"
class AutomatedSoftwareDistributionApi(object):
"""
Cisco Automated Software Distribution service provides software
information and download URLs to assist you in upgrading your
device/application to the latest vers... |
from rest_framework import serializers
from scripts.models import ScriptVersion
# Serializers define the API representation.
class ScriptSerializer(serializers.ModelSerializer):
name = serializers.CharField(source="script.name")
score = serializers.ReadOnlyField(source="votes.count")
class Meta:
... |
import functools
from tornado.routing import PathMatches
from core import PipelineDelegate
class MethodMatches(PathMatches):
"""Matches request path and maethod."""
def __init__(self, path_pattern, method: str):
super().__init__(path_pattern)
self.method = method.upper()
def match(self,... |
import numpy as np
from collections import defaultdict
# the type of float to use throughout the session.
_FLOATX = 'float32'
_EPSILON = 10e-8
_UID_PREFIXES = defaultdict(int)
_IMAGE_DIM_ORDERING = 'tf'
_LEGACY_WEIGHT_ORDERING = False
def epsilon():
'''Returns the value of the fuzz
factor used in numeric ex... |
from .setup_budget import Command
from .clear_budget import Command |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('library', '0006_auto_20170516_0903'),
]
operations = [
migrations.RenameField(
model_name='borrowitem',
... |
#!/usr/bin/env python
#
# Copyright (c) 2012 Dave Pifke.
#
# 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, modify,... |
import numpy as np
import matplotlib.pyplot as plt
# from scipy.constants import G
# Setting plotting parameters
from matplotlib import rc,rcParams
rc('text', usetex=True)
rc('axes', linewidth=2)
rc('font', weight='bold')
rc('font', **{'family': 'serif', 'serif':['Computer Modern']})
def find_vel_init(M1, M2, A):
pe... |
import sys
from vyperlogix.misc import _utils
from django.utils.datastructures import SortedDict as SortedDictFromList
from vyperlogix.classes.SmartObject import SmartObject
def fields_for_model(model, formfield_callback=lambda f: f.formfield()):
"""
Returns a list of fields for the given Django model class... |
# -*- coding: utf-8 -*-
import base64
import datetime
import json
import sys
import time
import random
import traceback
from datetime import date
from calendar import monthrange
import hashlib
import re
import execjs
from dateutil.relativedelta import relativedelta
from requests.utils import add_dict_to_cookiejar
rel... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 27 16:54:42 2017
@author: Xiaobo
"""
import numpy as np
from mpi4py import MPI
import commands
import os
import sys
path = os.path.dirname(os.path.realpath(__file__))
sys.path.append(path)
#sys.path.append('/Users/Xiaobo/git/CloudMerge/CloudMerge/cl... |
from django.urls import path
from . import views
app_name = "lists"
urlpatterns = [
path('', views.home_page, name="home"),
path('the-only-list-in-the-world/', views.view_list,
name='view_list')
] |
# This file is part of Indico.
# Copyright (C) 2002 - 2019 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from __future__ import unicode_literals
from indico.modules.admin.views import WPAdmin
from indico.util.i... |
"Dummy cache backend"
from django.core.cache.backends.base import BaseCache
class CacheClass(BaseCache):
def __init__(self, *args, **kwargs):
pass
def add(self, key, *args, **kwargs):
self.validate_key(key)
return True
def get(self, key, default=None):
self.validate_key(k... |
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 12 09:12:00 2016
Average the spatial influence of the morphology
@author: young
"""
import os
from os.path import join
import pylab as plt
import numpy as np
def average_data_in_dif_folder(dirName,dataName,z_pos,numRotation,idxSection):
yfileName = dirName+'_0/'+dataN... |
import sqlite3
import time
import random
from tqdm import tqdm
# Setup
dbFile = 'ISC/Rasp-main/Database.db'
DBDelay = 2 # seconds
# Data
general = dict()
charger = dict()
sevcon = dict()
bms1 = dict()
bms2 = dict()
bms3 = dict()
bms = [bms1, bms2, bms3]
def init_dict():
'''
Initializes internal dictionaries... |
# Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.d (the "License");
# you may not use this file except in compliance with the License.
#
# Credits to Hitalo-Sama and FTG Modules
from datetime import datetime
from emoji import emojize
from math import sqrt... |
from collections import OrderedDict
from datetime import date, datetime
from distutils.version import LooseVersion
import itertools
import operator
import re
import sys
import numpy as np
import pytest
from pandas._libs.internals import BlockPlacement
from pandas.compat import lrange
import pandas as pd
from pandas ... |
from livy.session import LivySession # noqa: F401
from livy.models import ( # noqa: F401
SessionKind,
SessionState,
SparkRuntimeError,
) |
from __future__ import absolute_import
import unittest
import random
import future.utils
import networkx as nx
import igraph as ig
import numpy as np
import ndlib.models.ModelConfig as mc
import ndlib.models.epidemics as epd
import ndlib.models.opinions as opn
import ndlib.utils as ut
__author__ = 'Giulio Rossetti'
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import gzip
import json
import re
import logging
import sys
import datetime as dt
import os
from operator import itemgetter
from statistics import median, mean
import argparse
from time import time, sleep
from itertools import groupby
from collections import namedtuple
from... |
from selenium import webdriver
from bs4 import BeautifulSoup
import pandas as pd
from Domain.website import Website
from selenium.webdriver.firefox.options import Options
from Repository.file_repository import FileRepository
class WebsiteService:
def __init__(self, website_repository: FileRepository):
s... |
import dependency_injector.providers as providers
import dependency_injector.containers as containers
class Engine(object):
def go(self):
return "I'm going."
class Car(object):
def __init__(self, engine: Engine):
self.engine = engine
def go(self):
print(self.engine.go())
cla... |
from __future__ import annotations
from random import random
import numpy as np
from tetris.ai.network import Network
class Population:
def __init__(self, size: int = 500, old_pop: Population = None,
parent_candidates_pct: float = .1, offspring_pct: float = .3,
mutation_chance:... |
##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... |
"""
Script to upload the data set of New York Taxi trips in S3 data lake
Sources
http://www.nyc.gov/html/tlc/html/about/trip_record_data.shtml
https://github.com/toddwschneider/nyc-taxi-data/blob/master/setup_files/raw_data_urls.txt
Example
>>> sample_url = 'https://s3.amazonaws.com/nyc-tlc/trip+data/fhv_tripdata_2015... |
#!/usr/bin/env python
#
# Copyright 2016-present Tuan Le.
#
# Licensed under the MIT License.
# You may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://opensource.org/licenses/mit-license.html
#
# Unless required by applicable law or agreed to in writing, so... |
from abc import ABC, abstractmethod
from typing import Generic, TypeVar
H = TypeVar("H")
T = TypeVar("T")
class BaseHistory(Generic[H, T], ABC):
@abstractmethod
def add(self, entry: T) -> None:
pass
@abstractmethod
def retrieve(self) -> H:
pass |
# -*- coding: utf-8 -*-
import numpy as np
np.set_printoptions(precision=6, threshold=1e3)
import torch
from torchvision import datasets, transforms
import copy
import torch.nn as nn
from torch.utils.data import DataLoader
def mnist_iid(dataset, K, M):
dict_users, all_idxs = {}, [i for i in range(len(dataset))... |
from typing import Callable, List, Set, Tuple, TypeVar, Optional
import warnings
from allennlp.common.checks import ConfigurationError
from allennlp.data.tokenizers import Token
TypedSpan = Tuple[int, Tuple[int, int]]
TypedStringSpan = Tuple[str, Tuple[int, int]]
class InvalidTagSequence(Exception):
def __init... |
# Bruce Maxwell
# Fall 2020
# CS 5001 Project 7
# First L-system project
# Some test code
import turtle
import turtle_interpreter as ti
# useful goto function
def goto(x, y):
turtle.up()
turtle.goto(x, y)
turtle.down()
# main function that makes a small tree in a pot
def makeTree():
# set up the win... |
import sys
import shutil
import logging
from astropy.io import fits
from pyaxe import config as config_util
from . import axetasks
from .axeerror import aXeSIMError
# make sure there is a logger
_log = logging.getLogger(__name__)
"""
The following deal with axe simulations
"""
class DispImator(object):
"""Cl... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: release-1.16
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import si... |
import asyncio
import importlib
import logging
import pkgutil
from abc import ABC, abstractmethod
from collections import OrderedDict
from types import FunctionType
def get_package_modules(package):
package_modules = []
for importer, module_name, is_package in pkgutil.iter_modules(package.__path__):
f... |
"""
An ASGI middleware.
Based on Tom Christie's `sentry-asgi <https://github.com/encode/sentry-asgi>`_.
"""
import asyncio
import inspect
import urllib
from sentry_sdk._functools import partial
from sentry_sdk._types import MYPY
from sentry_sdk.hub import Hub, _should_send_default_pii
from sentry_sdk.integrations._w... |
from .models import DeferredWebReflectedBase
from . import PACKAGE_PATH
from pathlib import Path
from typing import Union
import sqlalchemy
def run_sql_file(sql_subpath: Union[str, Path], engine: sqlalchemy.engine.Engine) -> None:
sql_path = Path(PACKAGE_PATH, 'sql', sql_subpath).resolve()
if not sql_path.is_... |
import _plotly_utils.basevalidators
class SymbolValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(self, plotly_name="symbol", parent_name="scatter.marker", **kwargs):
super(SymbolValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... |
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
VERSION = (0, 1)
backendapp = "django_wysiwyg"
# Do some settings checks.
if backendapp not in settings.INSTALLED_APPS:
raise ImproperlyConfigured(
"The '{}' application is required to use the '{}' plugin.".format(ba... |
#
# Last value cache
# Uses XPUB subscription messages to re-send data
#
import zmq
def main():
ctx = zmq.Context.instance()
frontend = ctx.socket(zmq.SUB)
frontend.connect("tcp://*:5557")
backend = ctx.socket(zmq.XPUB)
backend.bind("tcp://*:5558")
# Subscribe to every single topic from publi... |
# ####################################################################################################################################################
# ______ _______ _______ _ _______ _______ _ _______ _______ ______ _____
# ( __ \ ( ___ ) ( ____ ) | \ /\ ( __... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from . import _utilities... |
# -*- encoding: utf-8 -*-
import json
import re
import operator
import logging
from ..forms import XEditableUpdateForm
from .base import DatatableView
from django import get_version
from django.http import HttpResponse, HttpResponseBadRequest
from django.views.decorators.csrf import ensure_csrf_cookie
from django.db... |
import os
from google.appengine.api.app_identity import get_default_version_hostname, get_application_id
from secrets import SESSION_KEY
if 'SERVER_SOFTWARE' in os.environ and os.environ['SERVER_SOFTWARE'].startswith('Dev'):
DEBUG = True
HOME_URL = 'http://localhost' + ':8085'
else:
DEBUG = False
HOME... |
# -*- coding: utf-8 -*-
import random
import logging
from scrapy.downloadermiddlewares.useragent import UserAgentMiddleware
logger = logging.getLogger(__name__)
class RotateUserAgentMiddleware(UserAgentMiddleware):
"""避免被ban策略之一:使用useragent池。
使用注意:需在settings.py中进行相应的设置。
更好的方式是使用:
pip install scrapy-fa... |
import json
import sys
import os
from tqdm import tqdm
from mdf_refinery.validator import Validator
from mdf_refinery.parsers.tab_parser import parse_tab
# VERSION 0.3.0
# This is the converter for the NIST X-Ray Transition Energies Database
# Arguments:
# input_path (string): The file or directory where the data... |
# (C) Datadog, Inc. 2010-2018
# All rights reserved
# Licensed under Simplified BSD License (see LICENSE)
import pytest
from . import common, metrics
pytestmark = [pytest.mark.integration, pytest.mark.usefixtures("dd_environment")]
def test_check(aggregator, check):
service_check_tags = common._config_sc_tags(... |
from nxp_imu.I2C import I2C
from nxp_imu.IMU import IMU
# class Namespace(object):
# def __init__(self, **kwds):
# self.__dict__.update(kwds)
__version__ = '0.6.1'
__author__ = 'Kevin J. Walchko'
__license__ = 'MIT'
__copyright__ = '2017 Kevin J. Walchko' |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from .. import _utilitie... |
from ethereum import tester as t
from ethereum import utils
from ethereum import transactions
import rlp
import serpent
s = t.state()
c = s.abi_contract('check_for_impurity.se')
#from ethereum.slogging import LogRecorder, configure_logging, set_level
#config_string = ':info,eth.vm.log:trace,eth.vm.op:trace,eth.vm.stac... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import ... |
import os
import sys
from setuptools import setup, find_packages
from fnmatch import fnmatchcase
from distutils.util import convert_path
standard_exclude = ('*.pyc', '*~', '.*', '*.bak', '*.swp*')
standard_exclude_directories = ('.*', 'CVS', '_darcs', './build', './dist', 'EGG-INFO', '*.egg-info')
def find_package_dat... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2018-03-16 22:26
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('syntacticstrutting', '0001_initial'),
]
operations = [
migrations.CreateMod... |
# Importing the necessary libraries
import pandas as pd
import geopandas as gpd
import fiona
import matplotlib.pyplot as plt
import folium
import os
from folium.plugins import StripePattern
dir=os.path.dirname("/home/ado/Desktop/new_datacranchers/data_crunchers_knbs/app/data_processing/open_source_data_values/folium_m... |
# ==================================================================================================
# Copyright 2012 Twitter, Inc.
# --------------------------------------------------------------------------------------------------
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use thi... |
"""
WSGI config for annotation_project project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('D... |
from django.db import models
class Mission(models.Model):
name = models.CharField(max_length=200)
start_date = models.DateTimeField('date discovered')
def __unicode__(self):
return self.name
class Planet(models.Model):
name = models.CharField(max_length=200)
discovery_date = models.DateT... |
from sklearn_evaluation import ClassifierEvaluator
# import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
def test_can_plot():
data = datasets.make_classification(200,
... |
import requests
import pprint
# Configuration:
# filename = file to upload
filename='app.py'
# url = GET API for presigning
url = "https://vqdrwi0ee1.execute-api.us-east-1.amazonaws.com/Prod/PreSign"
# Get presign response
result = requests.get(url).json()
# Print some debug information
pp = pprint.PrettyPrinter(in... |
with open("input.txt", "r") as f:
lines = f.readlines()
for line1 in lines:
for line2 in lines:
total = int(line1) + int(line2)
if total == 2020:
print(f"line1: {line1}")
print(f"line2: {line2}")
print(f"Multiply: {int(line1) * int... |
from __future__ import unicode_literals
import itertools
import re
from .common import InfoExtractor
from ..compat import compat_str
from ..utils import (
clean_html,
determine_ext,
dict_get,
extract_attributes,
ExtractorError,
float_or_none,
int_or_none,
parse_duration,
str_or_non... |
# Copyright 2020,2021 Sony Corporation.
# Copyright 2021 Sony Group Corporation.
#
# 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 ... |
'''
Source codes for Python Machine Learning By Example 3rd Edition (Packt Publishing)
Chapter 5 Predicting Online Ads Click-through with Logistic Regression
Author: Yuxi (Hayden) Liu (yuxi.liu.ece@gmail.com)
'''
from sklearn.feature_extraction import DictVectorizer
X_dict = [{'interest': 'tech', 'occupation': 'prof... |
#
# main.py: a shared, automated test suite for Subversion
#
# Subversion is a tool for revision control.
# See http://subversion.tigris.org for more information.
#
# ====================================================================
# Licensed to the Apache Software Foundation (ASF) under one
# or more cont... |
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
# 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 Apach... |
'''
TCS Codevita Question, 2020
Elections are going on, and there are two candidates A and B, contesting with each other. There is a queue of voters and in this queue some of them are supporters of A and some of them are supporters of B. Many of them are neutral. The fate of the election will be decided on which side ... |
# -*- coding: utf-8 -*-
#!/usr/bin/env python
"""
When running computations on the background or through a scheduler such as
Slurm, print statement are lost. Although you can redirect the standard outputs
in the former case, the procedure is not as straightforward in the latter case.
Fortunately, Clustertools offers ... |
def func():
for _ range(10):
from package.module import foo
foo
# <ref> |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from .. import _utilities, _tables
from ... |
import torch
from pipert import Routine
from pipert.core.message import Message
from pipert.core.routine import RoutineTypes
from pipert.utils.structures import Instances, Boxes
from queue import Empty
import time
import cv2
import pkg_resources
class FaceDetection(Routine):
routine_type = RoutineTypes.PROCESSING... |
import configparser
# CONFIG
config = configparser.ConfigParser()
config.read('dwh.cfg')
IAM_ROLE = config['IAM_ROLE']['ARN']
LOG_DATA = config['S3']['LOG_DATA']
SONG_DATA = config['S3']['SONG_DATA']
LOG_JSONPATH = config['S3']['LOG_JSONPATH']
# DROP TABLES
staging_events_table_drop = "DROP TABLE IF EXISTS stagin... |
#! /usr/bin/env python
from __future__ import print_function
import sys
import os
import glob
import platform
# distutils is deprecated and vendored into setuptools now.
from setuptools import setup
from setuptools import Extension
from setuptools import find_packages
# Extra compiler arguments passed to *all* extens... |
# -*- coding: utf-8 -*-
import xadmin
from xadmin import views
from .models import Project, Config, API, Case, CaseStep, HostIP, Variables, Report, ModelWithFileField, Pycode
from djcelery.models import TaskState, WorkerState, PeriodicTask, IntervalSchedule, CrontabSchedule, TaskMeta
class BaseSetting(object):
e... |
# https://leetcode.com/problems/decode-ways/
import string
import fileinput
from typing import Dict
class Solution:
MAPPING = dict(zip(map(str, range(1, 28)), string.ascii_uppercase))
def _numDecodings(self, s: str, mem: Dict[str, int]) -> int:
if s in mem:
return mem[s]
mem[s]... |
# Copyright 2020 The SODA Authors.
# Copyright (c) 2016 Huawei Technologies Co., Ltd.
# 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.ap... |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2020 JinTian.
#
# This file is part of alfred
# (see http://jinfagang.github.io).
#
# 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 co... |
#-----------------------------------------------------
# Mimas: conference submission and review system
# (c) Allan Kelly 2016-2020 http://www.allankelly.net
# Licensed under MIT License, see LICENSE file
# ----------------------------------------------------- |
""" Hyperparameters for MJC 2D navigation with discontinous target region. """
from __future__ import division
from datetime import datetime
import os.path
import numpy as np
from gps import __file__ as gps_filepath
from gps.agent.mjc.agent_mjc import AgentMuJoCo
from gps.algorithm.algorithm_traj_opt_pilqr import Al... |
"""Provide support for PEP 425 compatibility tags triples."""
import distutils.util
import os
import os.path
import platform
import sys
import sysconfig
INTERPRETER_SHORT_NAMES = {
"python": "py", # Generic.
"cpython": "cp",
"pypy": "pp",
"ironpython": "ip",
"jython": "jy",
}
_32_BIT_INTERPRET... |
"""
Provide the class Message and its subclasses.
"""
class Message(object):
message = ''
message_args = ()
def __init__(self, filename, loc):
self.filename = filename
self.lineno = loc.lineno
self.col = getattr(loc, 'col_offset', 0)
def __str__(self):
return '%s:%s: ... |
from rdflib.term import Literal # required for doctests
assert Literal # avoid warning
from rdflib.namespace import Namespace # required for doctests
assert Namespace # avoid warning
from rdflib.py3compat import format_doctest_out
__doc__ = format_doctest_out("""\
RDFLib defines the following kinds of Graphs:
* :c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.