content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright 2015-2017 by ExopyPulses Authors, see AUTHORS for more details.
#
# Distributed under the terms of the BSD license.
#
# The full license is in the file LICENCE, distributed with this software.
# ---------... | python |
import torch
import torch.nn as nn
"""
initial
"""
class InitialBlock(nn.Module):
def __init__(self, in_channels, out_channels, bias=False, relu=True):
super(InitialBlock, self).__init__()
if (relu):
activation = nn.ReLU
else:
activation = nn.PReLU
# maini... | python |
'''
A flask application for controlled experiment on
the attention on clickbait healdines
'''
# imports
from flask import Flask, render_template, url_for, redirect, request, jsonify, session
from flask_session import Session
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime, date, timedelta
import ... | python |
# -*- coding: utf-8 -*-
# Scraping all the 10 qoutes here:http://quotes.toscrape.com/
# All the authors,tags and text
# follow pagination link with scarpy
import scrapy
class QuotesSpider(scrapy.Spider):
name = "quotes"
allowed_domains = ["toscrape.com"]
start_urls = ['http://quotes.toscrape.com']
def parse(s... | python |
import numpy as np
import pandas as pd
from fmow_helper import (
BASELINE_CATEGORIES, MIN_WIDTHS, WIDTHS, centrality, softmax, lerp, create_submission,
csv_parse, read_merged_Plog
)
BASELINE_CNN_NM = 'baseline/data/output/predictions/soft-predictions-cnn-no_metadata.txt'
BASELINE_CNN = 'baseli... | python |
#!/usr/bin/python
"""
Copyright 2014 The Trustees of Princeton University
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 ... | python |
import os
from setuptools import find_packages, setup
def read(*parts):
filename = os.path.join(os.path.dirname(__file__), *parts)
with open(filename, encoding="utf-8") as fp:
return fp.read()
setup(
name="django-formtools",
use_scm_version={"version_scheme": "post-release", "local_scheme": ... | python |
#!/usr/bin/python
import cStringIO as StringIO
from fnmatch import fnmatch
import difflib
import os
import sys
def get_name(filename):
return os.path.splitext(filename)[0]
def list_dir(dir_path, filter_func):
return sorted(filter(filter_func, os.listdir(dir_path)), key=get_name)
def main():
test_dir ... | python |
# -*- coding: utf-8 -*-
from ..utils import get_offset, verify_series
def ohlc4(open_, high, low, close, offset=None, **kwargs):
"""Indicator: OHLC4"""
# Validate Arguments
open_ = verify_series(open_)
high = verify_series(high)
low = verify_series(low)
close = verify_series(close)
offset =... | python |
#
# Copyright (c) 2021 Incisive Technology Ltd
#
# 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, merge, pu... | python |
#!/usr/bin/env python2.7
import socket
import sys
import os
import json
import time
import serial
import availablePorts
import argparse
DATA_AMOUNT = 1024
MAXLINE = 40
def getArgs():
parser = argparse.ArgumentParser(prog=sys.argv[0])
parser.add_argument('-p','--port',type=int,default=10000,dest='port',he... | python |
# coding: utf-8
# In[1]:
import netCDF4
# In[2]:
#url = 'http://52.70.199.67:8080/opendap/ugrids/RENCI/maxele.63.nc'
url = 'http://ingria.coas.oregonstate.edu/opendap/ACTZ/ocean_his_3990_04-Dec-2015.nc'
# In[3]:
nc = netCDF4.Dataset(url)
# In[4]:
nc.variables.keys()
# In[5]:
nc.variables['lat_rho']
# I... | python |
from django.db import models
from django.conf import settings
from mainapp.models import Product
class Order(models.Model):
FORMING = 'FM'
SENT_TO_PROCEED = 'STP'
PROCEEDED = 'PRD'
PAID = 'PD'
READY = 'RDY'
CANCEL = 'CNC'
ORDER_STATUS_CHOICES = (
(FORMING, 'формируется'),
... | python |
import gluonts.mx.model.predictor as pred
from kensu.gluonts.ksu_utils.dataset_helpers import make_dataset_reliable
from kensu.utils.helpers import eventually_report_in_mem
from gluonts.dataset.common import ListDataset
from kensu.utils.kensu_provider import KensuProvider
from kensu.gluonts.model.forecast import Sampl... | python |
from __future__ import absolute_import
from __future__ import print_function
from select import select
import termios
import os
import sys
import optparse
import subprocess
import random
import time
#import cv2
import curses
#from awscli.customizations.emr.constants import TRUE
from keras.optimizers import RMSprop, Ad... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 3 10:51:05 2016
@author: dyanni3
"""
# %% imports and prep
from threading import Lock
import numpy as np
from numpy.random import rand as r
from collections import defaultdict as d, defaultdict
from PIL import Image
from functools import reduce
f... | python |
import tensorflow as tf
import numpy as np
from load_data import load_data
import sklearn.preprocessing as prep
from tensorflow.examples.tutorials.mnist import input_data
from sklearn.metrics import accuracy_score
class LR(object):
def __init__(self,
n_input=750,
n_class=2,
... | python |
# --------------------------------------------------------
# High Resolution Transformer
# Copyright (c) 2021 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Rao Fu, RainbowSecret
# --------------------------------------------------------
import os
import pdb
import logging
import tor... | python |
from fixtures.builder import FixtureBuilder
def build():
fixture = FixtureBuilder('TUFTestFixtureDelegated')\
.create_target('testtarget.txt')\
.publish(with_client=True)\
.delegate('unclaimed', ['level_1_*.txt'])\
.create_target('level_1_target.txt', signing_role='unclaimed')\
... | python |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Uso: test_fs.py part_file_name")
exit(1)
# testa tamanho do FS virtual total
statinfo = os.stat(sys.argv[1])
if statinfo.st_size != 4194304:
print("Tamanho invalido. Deve ter exatamente 4Mb (41... | python |
'''
有一些原木,现在想把这些木头切割成一些长度相同的小段木头,需要得到的小段的数目至少为 k。当然,我们希望得到的小段越长越好,你需要计算能够得到的小段木头的最大长度。
Example
样例 1
输入:
L = [232, 124, 456]
k = 7
输出: 114
Explanation: 我们可以把它分成114cm的7段,而115cm不可以
样例 2
输入:
L = [1, 2, 3]
k = 7
输出: 0
说明:很显然我们不能按照题目要求完成。
Challenge
O(n log Len), Len为 n 段原木中最大的长度
Notice
木头长度的单位是厘米。原木的长度都是正整数,我们要求切割得到的小段木头... | python |
import logging
from autobahn.twisted.websocket import WebSocketServerProtocol
logger = logging.getLogger(__name__)
class PsutilRemoteServerProtocol(WebSocketServerProtocol):
def onConnect(self, request):
logger.info("Client connecting: {}".format(request.peer))
def onOpen(self):
logger.inf... | python |
DEFAULT_SYSTEM = 'frontera.tacc.utexas.edu'
| python |
#!/usr/bin/env python3
"""Positive Negative.
Given 2 int values, return True if one is negative and one is positive.
Except if the parameter "negative" is True, then return
True only if both are negative.
source: https://codingbat.com/prob/p162058
"""
def pos_neg(a: int, b: int, negative: bool) -> bool:
"""Di... | python |
import numpy as np
import pandas as pd
from gensim.models import Word2Vec
from sklearn.decomposition import TruncatedSVD
from sklearn.model_selection import StratifiedKFold
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
def creat... | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2017-12-01 05:18
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Interface', '0003_auto_20171201_0503'),
]
operations = [
migrations.AddFiel... | python |
"""Support for Xiaomi Mi Air Quality Monitor (PM2.5) and Humidifier."""
from __future__ import annotations
from dataclasses import dataclass
import logging
from miio import AirQualityMonitor, DeviceException
from miio.gateway.gateway import (
GATEWAY_MODEL_AC_V1,
GATEWAY_MODEL_AC_V2,
GATEWAY_MODEL_AC_V3,
... | python |
import subprocess
import sys
import getopt
import os
from datetime import datetime, time
def substring(s, debut, fin):
pos = s.find(debut)
if pos >= 0:
if fin == "":
return s[pos+len(debut):]
else:
pos2 = s.find(fin, pos)
if pos2 >= 0:
return... | python |
from twitchstream.outputvideo import TwitchBufferedOutputStream
import argparse
import time
import numpy as np
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
required = parser.add_argument_group('required arguments')
required.add_argument('-s', '--streamkey',
... | python |
from __future__ import unicode_literals
from .base import Base
from trustar2.base import fluent, ParamsSerializer, Param, get_timestamp
from trustar2.trustar_enums import AttributeTypes, ObservableTypes
@fluent
class Entity(Base):
FIELD_METHOD_MAPPING = {
"validFrom": "set_valid_from",
"validTo... | python |
# Copyright (c) 2019, Digi International, Inc.
#
# 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, merge, pu... | python |
# Copyright 2017 The Wallaroo Authors.
#
# 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 ... | python |
# -*- coding: utf-8 -*-
# Copyright (c) 2019 by University of Kassel, Tu Dortmund, RWTH Aachen University and Fraunhofer
# Institute for Energy Economics and Energy System Technology (IEE) Kassel and individual
# contributors (see AUTHORS file for details). All rights reserved.
import numpy as np
import pandas as pd
... | python |
"""Hacs models."""
| python |
# -*- encoding: utf-8 -*-
import json
import logging
import shlex
from aws_gate.constants import (
AWS_DEFAULT_PROFILE,
AWS_DEFAULT_REGION,
DEFAULT_OS_USER,
DEFAULT_SSH_PORT,
DEFAULT_KEY_ALGORITHM,
DEFAULT_KEY_SIZE,
PLUGIN_INSTALL_PATH,
DEBUG,
DEFAULT_GATE_KEY_PATH,
)
from aws_gate.... | python |
import json
from flask import make_response
def get_response(status, body):
response = make_response(str(body), status)
response.headers['Content-Type'] = 'application/json'
response.headers['Access-Control-Allow-Origin'] = '*'
return response
def error_handler(message, status=400):
return get_r... | python |
# Copyright (c) Fraunhofer MEVIS, Germany. All rights reserved.
# **InsertLicense** code
__author__ = 'gchlebus'
from data.cityscapes.cityscapes_labels import Label
labels = [
Label("background", 0, 0, "bg", 0, False, False, (0, 0, 0)),
Label("liver", 1, 1, "liver", 0, False, False, (255, 255, 255)),
]
| python |
import picamera
from time import sleep
import face_recognition
from time import time
import os
# https://picamera.readthedocs.io/en/release-1.0/api.html
def get_number_faces():
time_now = int(time())
# take picture
camera = picamera.PiCamera()
# set resolution
camera.resolution = (1024, 768)... | python |
from rest_framework import serializers
from . import models
class LabeledImageSerializer(serializers.ModelSerializer):
class Meta:
model = models.LabeledImage
fields = '__all__'
class ImageSerializer(serializers.ModelSerializer):
labeled_images = LabeledImageSerializer(many=True, read_only... | python |
from setuptools import setup, find_packages
setup(
version='0.6.3',
name='vinepy',
description='Python wrapper for the Vine Private API',
license='MIT',
author='David Gomez Urquiza',
author_email='david.gurquiza@gmail.com',
install_requires=['requests'],
url='https://github.com/davoclav... | python |
from .jschemalite import match, sample_match, to_json_schema
__all__ = ['match','sample_match','to_json_schema']
| python |
# Copyright 2022 Kaiyu Zheng
#
# 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 writin... | python |
"""
Harness for GP Bandit Optimisation.
-- kandasamy@cs.cmu.edu
"""
# pylint: disable=import-error
# pylint: disable=no-member
# pylint: disable=invalid-name
# pylint: disable=relative-import
# pylint: disable=super-on-old-class
from argparse import Namespace
import numpy as np
# Local imports
from bo import acqu... | python |
from rec_to_nwb.processing.nwb.components.iterator.multi_thread_data_iterator import MultiThreadDataIterator
from rec_to_nwb.processing.nwb.components.iterator.multi_thread_timestamp_iterator import MultiThreadTimestampIterator
from rec_to_nwb.processing.nwb.components.position.old_pos_timestamp_manager import OldPosTi... | python |
import gmpy2
n = 61460246439415037572177153632567252974745825750571288306818039521504649853292397058615041720699737467645963503594622773977391347884815005023877160625719128613453317553969604006686164013006897862637976548043387891127509135486424826628097846027041745648859637224222999183046451259665159100806312570205297... | python |
import pandas as pd
class ProjectSQLiteHandler:
def __init__(self, database='project_manager'):
import sqlite3 as lite
self.connection = lite.connect(database)
self.cursor = self.connection.cursor()
def closeDatabase(self):
self.cursor.close()
self.connection.close()
... | python |
# coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# 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 applicab... | python |
# Specific imports.
from ml_util import split_dataset_at_feature
# Public interface.
__all__ = ['ID3']
# Current version.
__version__ = '0.0.1'
# Author.
__author__ = "Michalis Vrettas, PhD - Email: michail.vrettas@gmail.com"
# ID3 class definition.
class ID3(object):
"""
Description:
TBD
"""
... | python |
# 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.
# ---------------------------------------------------------------------... | python |
"""Base class for deriving trainable modules."""
# local
from ivy.stateful.module import Module
class Sequential(Module):
def __init__(self, *sub_modules, device=None, v=None):
"""A sequential container. Modules will be added to it in the order they are
passed in the constructor.
:param ... | python |
import os
current_path = os.path.abspath(os.path.dirname(__file__))
filelist_path = current_path + "/filelist.txt"
filelist = open(filelist_path, "w")
for filename in os.listdir(current_path):
if filename.split(".")[1] == "mp4":
if filename.find("[") != -1:
print(filename.find("["))
... | python |
'''
Bank Transfer System
'''
__author__ = 'Dilmuratjohn'
import sys
import pymysql
class Transfer(object):
def __init__(self,connection):
self.connection = connection
def check_account(self,account):
print("checking account[%s]..." %(account))
cursor=self.connection.cursor()
... | python |
import graphene
from .. import type_
from .... import ops
##__________________________________________________________________||
class CommonInputFields:
"""Common input fields of mutations for creating and updating file paths"""
path = graphene.String()
note = graphene.String()
class CreateProductFil... | python |
from django.conf import settings
from wq.db.patterns.models import LabelModel
if settings.WITH_GIS:
from django.contrib.gis.db import models
class GeometryModel(LabelModel):
name = models.CharField(max_length=255)
geometry = models.GeometryField(srid=settings.SRID)
class PointModel(Label... | python |
import collections
import event_model
import itertools
from bluesky.plans import count
from intake.catalog.utils import RemoteCatalogError
import numpy
import ophyd.sim
import os
import pytest
import time
import uuid
def normalize(gen):
"""
Converted any pages to singles.
"""
for name, doc in gen:
... | python |
from flask import Flask, request
import json
import webbrowser, random, threading
import base64
import io
import matplotlib.image as mpimg # TODO: remove matplotlib dependency
import numpy as np
from laserCAM import Project, Image, Engraving, Laser, Machine, Preprocessor
import os
app = Flask(__... | python |
from terrascript import _resource
class circonus_check(_resource): pass
check = circonus_check
class circonus_contact_group(_resource): pass
contact_group = circonus_contact_group
class circonus_graph(_resource): pass
graph = circonus_graph
class circonus_metric(_resource): pass
metric = circonus_metric
class circo... | python |
from django.conf.urls import url, include
from rest_framework.urlpatterns import format_suffix_patterns
from .views import CreateView, DetailsView
from rest_framework.authtoken.views import obtain_auth_token
urlpatterns = {
url(r'^bucketlists/$', CreateView.as_view(), name="create"),
url(r'^bucketlists/(?P<p... | python |
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: Apache-2.0
#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
#
# Modifications Copyright OpenSearch Contributors. See
# GitHub history for details.
#
# Licensed to ... | python |
# -*-coding:Utf-8 -*
# Sprites display
import harfang as hg
class Sprite:
tex0_program = None
spr_render_state = None
spr_model = None
vs_pos_tex0_decl = None
@classmethod
def init_system(cls):
cls.tex0_program = hg.LoadProgramFromAssets("shaders/sprite.vsb", "shaders/sprite.fsb")
cls.vs_pos_tex0_decl = ... | python |
from transformers import AutoModelForSequenceClassification, AutoTokenizer
import torch
from torch.utils.data import DataLoader, SequentialSampler, TensorDataset
from transformers import glue_processors as processors
from transformers import glue_output_modes as output_modes
from transformers import glue_convert_exampl... | python |
''' watchsnmp.py
set snmp device(s) to monitor
set snmp oid list to monitor
get snmp info from devices using oid list
save snmp data
read saved snmp data
diff from prev smp data
graph snmp data
send alert email
'''
from snmp_helper import snmp_get_oid_v3,snmp_extract
from watchdata import WatchData
import time
ip='1... | python |
from . import mod_process
from . import sn_constant
from . import sn_phossite
from . import sn_result
from . import sn_utils
from .sn_lib import SpectronautLibrary
| python |
import re
import logging
import munch
from . import shell
from builtins import staticmethod
import os
LSPCI_D_REGEX = re.compile("(([0-9a-f]{4}):([0-9a-f]{2}):([0-9a-f]{2}).([0-9a-f]))\s*")
class Device(munch.Munch):
def __init__(self, domain, bus, slot, function, info):
super().__init__(dict(domain=dom... | python |
import numpy as np
from PIL import Image as Image
from scipy.ndimage import median_filter as _median_filter
from skimage.restoration import denoise_tv_bregman as _denoise_tv_bregman
import tensorflow as tf
def _get_image_from_arr(img_arr):
return Image.fromarray(
np.asarray(img_arr, dtype='uint8'))
def ... | python |
#!/usr/bin/env python
import os
import sys
import matplotlib.pyplot as plt
import nibabel as nib
import nilearn.image as nimage
import numpy as np
import pandas as pd
import seaborn as sns
import scipy.linalg as la
from glob import glob
from budapestcode.utils import compute_tsnr
from budapestcode.viz import make_mo... | python |
import ConfigParser
import os
from core.basesingleton import BaseSingleton
from core.settings import Settings
class ConfigurationManager(BaseSingleton):
@classmethod
def load_configuration(cls):
cls.get_instance()._load_configuration()
@classmethod
def save_configuration(cls):
cls.ge... | python |
###############################################################################
#
# \file ResultProcessor.py
# \author Sudnya Diamos <sudnyadiamos@gmail.com>
# \date Saturday August 12, 2017
# \brief Class that converts a probability distribution over classes to class
# label and returns result as a j... | python |
# Generated by Django 3.0.6 on 2020-05-16 17:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('confesion', '0004_remove_confesion_comentarios'),
]
operations = [
migrations.AddField(
model_name='comentario',
nam... | python |
import pytest
MODEL = 'ecmwf'
class VariableInfo:
def __init__(self):
self.name = 'Product'
@pytest.mark.parametrize("key", [
'cf_V', 'cf_A', 'cf_V_adv', 'cf_A_adv'])
def test_get_cf_title(key):
from model_evaluation.plotting.plotting import _get_cf_title
var = VariableInfo()
field_name... | python |
#! -*- codinf:utf-8 -*-
import time
import pandas as pd
import numpy as np
import torch
from numba import njit
from pyteomics.mgf import read
from pyteomics.mgf import read_header
"""
This script is used to compare the use-time of NDP and DLEAMS
"""
@njit
def caculate_spec(bin_spec):
ndp_spec = np.math.sqrt(np.do... | python |
import pylab
import numpy
import ardustat_library_simple as ard
import time
import sys
from glob import glob
import os
def get_latest():
data_files = glob("*.dat")
high_time = 0
recent_file = "foo"
for d in data_files:
if os.path.getmtime(d) > high_time:
high_time = os.path.getmtime(d)
recent_file = d
re... | python |
import numpy as np
from ..prediction import *
def test_predict_seebeck():
try:
predict_seebeck(1234, 62, 400)
except(TypeError):
pass
else:
raise Exception("Bad input allowed",
"Error not raised when `compound` isn't a string")
try:
predict_se... | python |
import numpy as np
import pandas as pd
import pytest
from scipy.sparse import coo_matrix
from collie.cross_validation import random_split, stratified_split
from collie.interactions import ExplicitInteractions, Interactions
def test_bad_random_split_HDF5Interactions(hdf5_interactions):
with pytest.raises(Assertio... | python |
from .loader import TableData
class MeasurementTypeData(TableData):
DATA = [
{"measurement_type_id": 0, "name": "generic measurement"},
{"measurement_type_id": 1, "name": "generic liquid sample"},
{"measurement_type_id": 2, "name": "whole blood"},
{"measurement_type_id": 3, "name":... | python |
import matplotlib.pyplot as plt
from torchvision import transforms, datasets
from torchvision.models import vgg19, densenet121, vgg16
from torchvision import datasets, models, transforms
import torchvision
from torch import nn, optim
import torch
import torch.nn.functional as F
from collections import OrderedDi... | python |
import subprocess
import os
import signal
import psutil
import time
class ShellProcessRunner(object):
def __init__(self):
self.cmd = None
self.started = False
def start(self):
if self.started:
return
if self.cmd is None:
raise Exception("Process cmd is ... | python |
import os
import fnmatch
import re
import subprocess
import sys
import readline
import shutil
import random
settings_file = '%s/.infinispan_dev_settings' % os.getenv('HOME')
upstream_url = 'git@github.com:infinispan/infinispan.git'
### Known config keys
local_mvn_repo_dir_key = "local_mvn_repo_dir"
maven_pom_xml_namesp... | python |
import pandas as pd
import torch
from torch import nn
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print("Device Being used:", device)
torch.autograd.set_detect_anomaly(True)
from torch.autograd import Variable
import numpy as np
from torch import optim
from sklearn import metrics
impo... | python |
# -*- coding: utf-8 -*-
# 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 require... | python |
# Copyright 2021 Miljenko Šuflaj
#
# 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 t... | python |
# Generated by Django 2.2.7 on 2020-04-10 05:42
import blog.models
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_MOD... | python |
from __future__ import absolute_import
import tangos.testing.simulation_generator
from tangos import parallel_tasks as pt
from tangos import testing
import tangos
import sys
import time
from six.moves import range
from nose.plugins.skip import SkipTest
def setup():
pt.use("multiprocessing")
testing.init_blan... | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Tests for PL-SQL recall file parser."""
import unittest
from plaso.formatters import pls_recall as _ # pylint: disable=unused-import
from plaso.lib import timelib
from plaso.parsers import pls_recall
from tests.parsers import test_lib
class PlsRecallTest(test_lib.Parse... | python |
from predicate import predicate
class Annotation(predicate):
"""
"""
| python |
"""
Tests the geomeTRIC molecule class.
"""
import pytest
import geometric
import os
import numpy as np
from . import addons
datad = addons.datad
def test_blank_molecule():
mol = geometric.molecule.Molecule()
assert len(mol) == 0
class TestAlaGRO:
@classmethod
def setup_class(cls):
try: cls... | python |
from amep.commands.make_dataset.sub_command import MakeDataset # NOQA
| python |
import argparse
import numpy as np
import pandas as pd
import joblib
from src import config
TRAINING_DATA = config.TRAINING_DATA
TEST_DATA = config.TEST_DATA
FOLDS = config.FOLDS
def predict(MODEL, FOLDS):
MODEL = MODEL
df = pd.read_csv(TEST_DATA)
text_idx = df["id"].values
predictions = None
... | python |
# INI handling sample
import configparser
config = configparser.ConfigParser()
config.read('python-test.ini', encoding="UTF-8")
sections = config.sections()
print(sections)
pt3 = config.get('RECT', 'pt3', fallback = '855,774') # don't care : 'RECT' section or 'pt3' option not exists, default value = '855,774'
print(p... | python |
import os
import warnings
import sys
import pandas as pd
import numpy as np
from sklearn import metrics
from sklearn.model_selection import train_test_split
from sklearn import preprocessing
from sklearn.naive_bayes import GaussianNB
import mlflow
import mlflow.sklearn
import logging
logging.basicConfig(level=logg... | python |
# Copyright 2019 Mycroft AI 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 writin... | python |
"""
`neo_blue`
========================================================
Copyright 2020 Alorium Technology
Contact: info@aloriumtech.com
Description:
This is a very simple CircuitPython program that turns the
Evo M51 NeoPixel blue.
"""
from aloriumtech import board, digitalio, neopixel
neo = neopixel.NeoPixel(board... | python |
import os
import time
import numpy as np
import matplotlib.pyplot as plt
import torch
from torch.nn import DataParallel
from torch.optim import lr_scheduler
from torch.utils.data import DataLoader
from torchvision.transforms import transforms
from networks.discriminator import get_discriminator
from networks.resnet i... | python |
import os
import numpy as np
from PIL import Image
from tensorflow.python.keras.models import load_model
from scripts.util import normalise_data
def get_character(label):
if label == 10:
return '+'
elif label == 11:
return '-'
elif label == 12:
return '*'
elif label == 13:
... | python |
from setuptools import setup, find_packages
import os
import glob
this_directory = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(this_directory, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
VERSIONFILE="gdelttools/_version.py"
with open(VERSIONFILE, "rt") as vfile:
f... | python |
# Copyright (c) 2020 kamyu. All rights reserved.
#
# Google Code Jam 2008 Round 3 - Problem C. No Cheating
# https://code.google.com/codejam/contest/32002/dashboard#s=p2
#
# Time: O(E * sqrt(V)) = O(M * N * sqrt(M * N))
# Space: O(V) = O(M * N)
#
import collections
# Time: O(E * sqrt(V))
# Space: O(V)
# Source code... | python |
# Generated by Django 3.0.3 on 2020-03-13 11:01
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('eadmin', '0004_auto_20200313_0713'),
]
operations = [
migrations.CreateModel(
name='Products',
... | python |
# BSD 3-Clause License
#
# Copyright (C) 2021 THL A29 Limited, a Tencent company. 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 copyrig... | python |
if __name__ == "__main__":
print('HELLO WORLD')
| python |
def aumentar(preco=0, taxa=0, sit=False):
"""
->> Calcular o aumento de um valor
:param preco: Valor a aumentar
:param taxa: Valor (porcentagem) do aumento
:param sit: Valor (opcional) informando se deve ou não realizar a formatação.
:return: O valor aumentado conforme a taxa
"""
res ... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.