text stringlengths 1 927k |
|---|
"""
elasticapm.base
~~~~~~~~~~
:copyright: (c) 2011-2017 Elasticsearch
Large portions are
:copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import datetime
import logging
import os
import platform
import soc... |
import argparse
from sys import platform
from models import * # set ONNX_EXPORT in models.py
from utils.datasets import *
from utils.utils import *
def detect(save_img=False):
img_size = (320, 192) if ONNX_EXPORT else opt.img_size # (320, 192) or (416, 256) or (608, 352) for (height, width)
out, source, we... |
# coding=utf-8
# pylint: disable-msg=E1101,W0612
import numpy as np
import pytest
import pandas as pd
import pandas.util.testing as tm
from .common import TestData
class TestSeriesReplace(TestData):
def test_replace(self):
N = 100
ser = pd.Series(np.random.randn(N))
ser[0:4] = np.nan
... |
# coding=utf-8
# Copyright 2021, Google Inc. and The HuggingFace Inc. team. 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... |
import os
import statistics
import csv
from collections import Counter
import pandas as pd
import numpy as np
class ExpSetup:
def __init__(self, ped_x, ped_y, ped_orient, ped_speed, car_speed, min_dist, min_ttc, min_dist_awa, det, col):
self.ped_x = ped_x
self.ped_y = ped_y
self.ped_orient... |
import os
class Service(object):
"""
The base class for all services. All services inherit from this class
"""
def __init__(self, prefix, artifacts, graph):
self._artifacts = artifacts
self._prefix = prefix
self._proc = None
self._graph = graph
def start(self, arg... |
OntCversion = '2.0.0'
from ontology.interop.System.ExecutionEngine import GetExecutingScriptHash, GetCallingScriptHash, GetEntryScriptHash
from ontology.interop.System.Runtime import CheckWitness, GetTime, Notify, Serialize, Deserialize
ContractAddress = GetExecutingScriptHash()
def Main(opration, args):
if opra... |
# Copyright (c) 2012, Willow Garage, Inc.
# 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
# notice, this list of cond... |
from .pygame import PyGameGUI |
from django import forms
from tempus_dominus.widgets import DatePicker
class ConsumerRegistrationForm(forms.Form):
GENDER = [
('Male', 'Male'),
('Female', 'Female'),
('Transgender', 'Transgender'),
('Not to Specify', 'Not to Specify'),
]
BLOOD_TYPE = [
('A+', 'A+'),... |
#
# 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... |
from .base_gamma import BaseGamma
from .isomorphism import (one2many, many2one)
from .algo import (factor, get_xy, gcd, inv_element)
from math import log
from fimath import Matrix
import itertools
class GammaZero(BaseGamma):
def __init__(self, *args, **kwargs):
super(__class__, self).__init__(*args, **kw... |
#!/usr/bin/env python
# coding: utf-8
# In this notebook, I delete a triple from the neighbourhood of the target triple based on the **L2 metric = euclidean distance** between the candidate triple's embedding and the target triple's embedding
#
# - 'triple' embedding is computed by applying the model's scoring functi... |
from hashlib import sha256
import json
import time
import multiprocessing
import time
import numpy as np
class Block:
def __init__(
self, depth, transactions, timestamp,
previous_hash, nonce=0
):
self.depth = depth
self.transactions = transactions
self.timestamp = timest... |
import io
import json
import time
import pytest
from dummyserver.server import HAS_IPV6
from dummyserver.testcase import HTTPDummyServerTestCase, IPv6HTTPDummyServerTestCase
from hip.base import DEFAULT_PORTS
from hip.poolmanager import PoolManager
from hip.exceptions import MaxRetryError, NewConnectionError, Unrewin... |
# Copyright (c) OpenMMLab. All rights reserved.
import os.path as osp
import platform
import shutil
import time
import warnings
import torch
import mmcv
import wandb
from mmcv.runner.hooks import HOOKS, Hook
from mmcv.runner.base_runner import BaseRunner
from mmcv.runner.builder import RUNNERS
from mmcv.runner.checkpoi... |
# -*- coding:utf-8 -*-
import copy
import numpy as np
from scipy._lib.six import xrange
class KDTree:
def __init__(self, bucket_size, dimensions, parent=None):
self.bucket_size = bucket_size
self.parent = None
self.left = None
self.right = None
self.split_dimension = None
... |
# Copyright 2021 The TensorFlow Probability 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 o... |
# -*- coding: utf-8 -*-
# This code is copy from https://github.com/tensorflow/tensorflow/pull/36773.
"""Group Convolution Modules."""
from tensorflow.python.framework import tensor_shape
from tensorflow.python.keras import activations
from tensorflow.python.keras import constraints
from tensorflow.python.keras import... |
"""Test Stuff."""
from unittest import TestCase
import pkg_resources
from productionsystem.config import ConfigSystem
# def setup_module(module):
# """ setup any state specific to the execution of the given module."""
# config_instance = ConfigSystem.setup(None) # pylint: disable=no-member
# config_insta... |
"""General-purpose utilities."""
import numpy as np
from scipy.linalg import expm
import random
import math
import operator
import sys
import json
import openfermion
from openfermion import hermitian_conjugated
from openfermion.ops import SymbolicOperator
from networkx.readwrite import json_graph
import lea
import col... |
import warnings
from .coin_spend import CoinSpend as CoinSolution # noqa
warnings.warn("`CoinSolution` is now `CoinSpend`") |
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
from __future__ import absolute_import
from builtins import * # NOQA
from future import standard_library
standard_library.install_aliases() # NOQA
import argparse
import os
import random
# This prevents num... |
# 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 sys
from pymunk import Body, Circle, ShapeFilter
from configsingleton import ConfigSingleton
from common import *
from common.drawing import draw_circle
class Landmark(object):
def __init__(self, mask, radius):
self.body = Body(0, 0, Body.STATIC)
self.body.position = 0, 0
self.body.a... |
import urllib.request
# http://beans-r-us.appspot.com/prices.html
# http://www.beans-r-us.biz/prices.html
# http://www.moneycontrol.com/india/stockpricequote/computers-software/tataconsultancyservices/TCS
baseUrl = 'http://beans-r-us.appspot.com/prices.html'
page = urllib.request.urlopen( baseUrl )
text = page.read()... |
from django.urls import re_path
from .api import PostLikeViewSet, CommentLikeViewSet, AuthorLikeViewSet
urlpatterns = [
re_path(r'^author/(?P<author_id>[a-z0-9-\.-]+)/post/(?P<post_id>[a-z0-9-:\.-]+)/likes/?$', PostLikeViewSet.as_view({
"get": "get_post_likes",
"post": "add_post_like",
... |
def selection_sort(alist):
for fill_slot in range(len(alist) - 1,0,-1):
position_of_max = 0
for location in range(1, fill_slot + 1):
if alist[location] > alist[position_of_max]:
position_of_max = location
temp = alist[fill_slot]
alist[fill_slot] = alist[p... |
#!/usr/bin/env python
import xml.etree.ElementTree as ET
class brocade_interface_ext(object):
"""Auto generated class.
"""
def __init__(self, **kwargs):
self._callback = kwargs.pop('callback')
def get_vlan_brief_input_request_type_get_request_vlan_id(self, **kwargs):
"""A... |
#!/usr/bin/env python3
# Copyright (c) 2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
import test_framework.loginit
#
# Helper script to create the cache
# (see BitcoinTestFramework.setup_chain)
#
... |
from app.validators.validator import Validator
class AnswerValidator(Validator):
def __init__(self, schema_element):
super().__init__(schema_element)
self.answer = schema_element
self.context["answer_id"] = self.answer["id"] |
# -*- coding: utf-8 -*-
"""
This module contains the Airtest Core APIs.
"""
import os
import time
from six.moves.urllib.parse import parse_qsl, urlparse
from airtest.core.cv import Template, loop_find, try_log_screen
from airtest.core.error import TargetNotFoundError
from airtest.core.settings import Settings as ST
f... |
# Copyright 2020 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
import logging
logger = logging.getLogger(__name__)
def read_all(sock):
sock.settimeout(5.0)
data = ""
while True:
part = sock.recv(4096)
data += part
if len(part) < 4096:
break
return data |
#!/usr/env/python
"""
Author: Ralf Hauenschild
E-Mail: ralf_hauenschild@gmx.de
"""
import sys
import os
import numpy
import matplotlib
import matplotlib as mpl
import matplotlib.pyplot as plt
import pylab as py
import matplotlib.cm as cm
import math
c = []
sens = [] # sens (recall)
senserror = []
specloss = [] # 1... |
import os
import multiprocessing
import numpy as np
import pytest
from csv import reader
from csv import Sniffer
import shutil
from keras import optimizers
from keras import initializers
from keras import callbacks
from keras.models import Sequential, Model
from keras.layers import Input, Dense, Dropout, add, dot, Lam... |
# -*- test-case-name: twisted.conch.test.test_cftp -*-
# Copyright (c) 2001-2009 Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Implementation module for the I{cftp} command.
"""
import os, sys, getpass, struct, tty, fcntl, stat
import fnmatch, pwd, time, glob
from twisted.conch.client import connect, d... |
__version__ = '2.35.24' |
# -*- coding: utf-8 -*-
import sys
sys.path.append('./')
from lazyconfig import lazyconfig
def get_name():
return lazyconfig.config.name |
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 11 16:56:51 2019
@author: x
"""
import numpy as np
from collections import Counter
class MetricesConstants(object):
#qrs_cutoff_distance = 0.2
qrs_cutoff_distance = 0.120 #https://www.sciencedirect.com/science/article/abs/pii/S1746809417300216
def sample_to_tim... |
from keras.utils.generic_utils import get_custom_objects
from main import IMain
class KerasMain(IMain):
def init_costum_objects(self, costum_objects):
get_custom_objects().update(
costum_objects) |
# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup ------------------------------------------------------------... |
# -*- coding: utf-8 -*-
"""Tools for handling LaTeX."""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from io import BytesIO, open
from base64 import encodestring
import os
import tempfile
import shutil
import subprocess
from IPython.utils.process import find_cm... |
import argparse
import glob
from os.path import join, realpath, dirname
from tqdm import tqdm
from multiprocessing import Pool
from lib.pysot.datasets import OTBDataset
from lib.pysot.evaluation import OPEBenchmark
from lib.pysot.visualization import draw_success_precision
if __name__ == '__main__':
parser = argp... |
###########################################################################
#
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/l... |
# -*- coding: utf-8 -*-
import time
import numpy as np
from PyQt4 import QtGui, QtCore
from ..Stage import Stage, MoveFuture, StageInterface
from acq4.drivers.PatchStar import PatchStar as PatchStarDriver
from acq4.util.Mutex import Mutex
from acq4.util.Thread import Thread
from acq4.pyqtgraph import debug, ptime, Spin... |
import os
import json
import requests
from typing import Optional
from . import credentials
from . import info
from . import session
class Client(session.Session):
_SCHOOL_NAME : str = None
_EMAIL : str = None
_ID : int = None
_PASSWORD : str = None
markingPeriods : list = []
hasCachedCredenti... |
import numpy as np
import mindspore
from mindspore import context, ops, Tensor, nn
from mindspore.common.parameter import Parameter, ParameterTuple
import copy
context.set_context(mode=context.PYNATIVE_MODE, device_target="CPU")
_update_op = ops.MultitypeFuncGraph("update_op")
@_update_op.register("Tensor", "Tens... |
import tensorflow as tf
class BaseTrain:
def __init__(self, sess, model, data, config, logger):
self.model = model
self.logger = logger
self.config = config
self.sess = sess
self.data = data
self.init = tf.group(tf.global_variables_initializer(), tf.local_variables_... |
from datautil.dataloader import batch_iter
import torch.nn.functional as F
import torch.optim as optim
import torch.nn.utils as nn_utils
import time
import torch
import numpy as np
from config.Const import *
class NMT(object):
def __init__(self, encoder, decoder):
super(NMT, self).__init__()
self.... |
""""CDMI Models
Copyright 2015 Archive Analytics Solutions - University of Liverpool
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 ... |
# -*- coding: utf-8 -*-
"""
Profile: http://hl7.org/fhir/StructureDefinition/Slot
Release: R5
Version: 4.5.0
Build ID: 0d95498
Last updated: 2021-04-03T00:34:11.075+00:00
"""
from pydantic.validators import bytes_validator # noqa: F401
from fhir.resources import fhirtypes # noqa: F401
from fhir.resources import slot
... |
import os
import subprocess
from celestial.strings import Filesystems
from celestial.client.system import cmdline
def get_fs_types(path):
"""
Fetch a list of possible filesystem types
:param path:
:return: a list of strings with the possible filesystem type, else None
"""
if not os.path.exist... |
def test():
print(ds) |
#!/usr/bin/env python3
import sys
import codecs
def main():
syllable_counts = {}
filepath = sys.argv[1]
lines = codecs.open(filepath, encoding="iso-8859-1").read().split("\n")
for line in lines:
if line.startswith(";;;") or len(line) == 0 or line.isspace():
continue
w... |
import itertools
import re
from abc import ABCMeta, abstractmethod
from collections import deque
from pathlib import Path
from typing import List
from startrek.exceptions import ScriptException
from startrek.utils import pairwise
OMITTED = 'OMITTED'
class ScriptBase(metaclass=ABCMeta):
def __init__(self, script_... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__version__ = '1.0.0' |
from . import models
import pandas as pd
import zipfile
import os
import re
# def curve_io_formatter(x_column, y_columns, y_names, x_axis, y_axis, log=False):
# curves = []
# for index, output in enumerate(y_columns):
# curve = {round(float(k), 3): round(float(v), 3) for k, v in zip(x_column, output)}
... |
# Copyright 2019 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from pants.backend.python.rules.setup_py_util import distutils_repr
testdata = {
'foo': 'bar',
'baz': {
'qux': [123, 456],
'quux': ('abc', b'xyz'),
'corge': {1, 2, 3}
}... |
from django.contrib import admin
#importar classes
from .models import Publicacao, Tag
# Register your models here.
admin.site.register(Publicacao)
admin.site.register(Tag) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 16 05:48:26 2021
@author: thales
Generate random samples from parsers
"""
from numpy.random import (poisson , binomial, randint)
from tokenlib import (Item , Etok, mk_stream)
import lib
import state
def bernoulli(p):
return binomial(1,p)
... |
import numpy as np
from onpolicy.envs.mpe.core import World, Agent, Landmark
from onpolicy.envs.mpe.scenario import BaseScenario
import random
#
# # the non-ensemble version of <ensemble_push>
#
#
class Scenario(BaseScenario):
def make_world(self, args):
world = World()
world.world_length = ar... |
#
# PySNMP MIB module GBOND-TDIM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/GBOND-TDIM-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:05:16 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... |
import functools
import inspect
import itertools
import sys
import warnings
from collections import defaultdict
from collections import deque
from typing import Dict
from typing import List
from typing import Optional
from typing import Tuple
import attr
import py.path
import _pytest
from _pytest._code.code import Fo... |
import _plotly_utils.basevalidators
class ColorbarValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(
self, plotly_name="colorbar", parent_name="choroplethmapbox", **kwargs
):
super(ColorbarValidator, self).__init__(
plotly_name=plotly_name,
parent_... |
from .models import Choice
from .models import Question
from django.contrib import admin
# Register your models here.
class ChoiceInline(admin.TabularInline):
model = Choice
extra = 1
class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question_text']}),
('Date inf... |
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import sys
import six
import llnl.util.tty as tty
import llnl.util.tty.colify as colify
import spack.repo
import spack.... |
# Generated by Django 3.2 on 2021-04-26 09:28
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('leads', '0002_rename_leads... |
from setuptools import setup, find_packages
setup(name="lockex",
version="0.3",
description="Get lock from zookeeper and execute",
packages=find_packages(exclude=["__pycache__"]),
install_requires=['click==7.1.1', 'python_gflags==3.1.2', 'kazoo==2.8.0', 'pure-sasl==0.6.2', 'psutil==5.7.0', 'futu... |
from test.unit_tests.providers import common
from test.unit_tests.providers.common import ProviderTestCase
from totalimpact.providers.provider import Provider, ProviderContentMalformedError
from test.utils import http
import os
import collections
from nose.tools import assert_equals, assert_items_equal, raises, nottes... |
# ===============================================================================
# Copyright 2012 Jake Ross
#
# 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/licens... |
# -*- coding: utf-8 -*-
"""
Created on Sat May 15 00:21:05 2021
@author: marina
"""
import os
import shutil
import pyedflib
import numpy as np
import pandas as pd
import sys
import mne
from pywt import wavedec
from sklearn.preprocessing import LabelEncoder
import matplotlib.pyplot as plt
from scipy import signal
from... |
import pyspark
from pyspark import SparkContext
from pyspark.sql import Row
from pyspark.sql import SQLContext
from pyspark import SparkFiles
import os
import pandas as pd
sc =SparkContext()
sqlContext = SQLContext(sc)
data_dir="/work/irlin355_1/gratienj/ParallelProgrammingCourse/BigDataHadoopSpark/data"
file = os.p... |
"""
Reproject a Raster using ST_Transform
=====================================
The `ST_Transform()` function (and a few others like `ST_SnapToGrid()`) can be used on
both `Geometry` and `Raster` types. In `GeoAlchemy2`, this function is only defined for
`Geometry` as it can not be defined for several types at the sam... |
# python3
# Copyright 2018 DeepMind Technologies Limited. 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 re... |
bl_info = {
"name": "RenderWare importer/exporter for GTA III/VC/SA (.dff)",
"author": "Ago Allikmaa (maxorator)",
"version": (0, 9, 2),
"blender": (2, 6, 3),
"location": "File > Import-Export > Renderware (.dff) ",
"description": "RenderWare importer/exporter for GTA III/VC/SA",
"category":... |
#!/usr/bin/env python3
import sys
import os
import argparse
import gzip
def readfastagz(File) :
Dic={}
with gzip.open(File, "r") as ReadL :
for ligne in ReadL:
ligne=ligne.decode('utf-8').replace('\n','')
if ligne[0]=='>' :
Key=ligne.split(' ')[0].split('|')[0].split('\t')[0].replace('>','')
... |
# coding=utf-8
import json
import requests
import time
# noinspection PyPackageRequirements
import websocket
# noinspection PyPackageRequirements
from bs4 import BeautifulSoup
from threading import Thread
from urllib.parse import urlparse
import metasmoke
from globalvars import GlobalVars
import datahandling
# noinsp... |
# --------------
# import packages
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import re
from nltk.corpus import stopwords
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.naiv... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
import onnx
from ..base import Base
from . import expect
class Xor(Base):
@staticmethod
def export():
node = onnx.helper.make_node(... |
"""
Tests for the pandas.io.common functionalities
"""
import codecs
import errno
from functools import partial
from io import (
BytesIO,
StringIO,
UnsupportedOperation,
)
import mmap
import os
from pathlib import Path
import tempfile
import pytest
from pandas.compat import is_platform_windows
import pand... |
# -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.async_support.hitbtc import hitbtc
import base64
import math
from ccxt.base.errors import ExchangeError
from ccxt.base.errors imp... |
"""Module with generic methods."""
from __future__ import annotations
import functools
import numbers
from typing import (
TYPE_CHECKING,
Any,
Callable,
Iterable,
List,
Optional,
Sequence,
Tuple,
TypeVar,
Union,
cast,
overload,
)
import numpy as np
import scipy.integra... |
import pytest
import numpy
import mdct.windows
def test_kbd():
M = 100
w = mdct.windows.kaiser_derived(M, beta=4.)
assert numpy.allclose(w[:M//2] ** 2 + w[-M//2:] ** 2, 1.)
with pytest.raises(ValueError):
mdct.windows.kaiser_derived(M + 1, beta=4.)
assert numpy.allclose(
mdct.wi... |
from matplotlib.pyplot import show
import torch
from torch.autograd import Variable
from torch.cuda.amp import GradScaler, autocast
import numpy as np
from sklearn.metrics import roc_auc_score
from callbacks.cb_handler import CallbackHandler
from callbacks.cb_base import BaseCB
from callbacks.cb_lr_patch_clf import LR... |
from random import shuffle, sample
with open('data.txt', 'r') as f:
contents = f.readlines()
contents = sample(contents, len(contents))
with open('train_data.txt', 'w') as f:
[f.write(content) for content in contents[: 601]]
with open('test_data.txt', 'w') as f:
[f.write(content) for content in contents[601:]] |
# Copyright 2018-2021 Xanadu Quantum Technologies 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... |
# -*- coding: utf-8 -*-
"""Django page CMS test suite module"""
import django
from django.conf import settings
from django.test.client import Client
from django.template import Template, RequestContext, TemplateDoesNotExist
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_t... |
import logging
import multiprocessing
import sys
import time
from data import Pointer, SUCC_LIST_LEN
from node import Node
def launch_node(ip, pred, succ_list):
node = Node(ip=ip, pred=pred, succ_list=succ_list)
p = multiprocessing.Process(target=node.start)
p.daemon = True
p.start()
return node,... |
from __future__ import division, print_function
import numpy
from sklearn.linear_model.logistic import LogisticRegression
from sklearn.metrics import roc_auc_score, mean_squared_error, log_loss
from sklearn.base import clone
from sklearn.datasets import make_blobs
from hep_ml import nnet
from hep_ml.commonutils impor... |
from setuptools import setup
version_info = {}
exec(open("harrison/package_version.py").read(), version_info)
setup(
name="harrison",
version=version_info["__version__"],
author="Body Labs, Metabolize",
author_email="github@paulmelnikow.com",
description="Time a block of code",
long_descriptio... |
# Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved.
import dace
import numpy as np
import pytest
from dace.libraries import standard
from dace.transformation import interstate
def _make_sdfg(name, storage=dace.dtypes.StorageType.CPU_Heap, isview=False):
N = dace.symbol('N', dtype=dace.int... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from . import __version__ as app_version
app_name = "factory_powerstations"
app_title = "Factory Powerstations"
app_publisher = "Alex Tas"
app_description = "Factory Management System"
app_icon = "octicon octicon-file-directory"
app_color = "grey"
app_ema... |
# based on a Java version:
# Based on original version written in BCPL by Dr Martin Richards
# in 1981 at Cambridge University Computer Laboratory, England
# and a C++ version derived from a Smalltalk version written by
# L Peter Deutsch.
# Java version: Copyright (C) 1995 Sun Microsystems, Inc.
# Translation fr... |
#!/usr/bin/env python
"""Working with nested data hands-on exercise / coding challenge."""
""" code by myounker 1 Sep 2018 """
import json
import os
# Get the absolute path for the directory where this file is located "here"
here = os.path.abspath(os.path.dirname(__file__))
#open file with interfaces and import te... |
from logging import Filter as _Filter
from betterLogger import config
class Filter(_Filter):
def filter(self, record):
return (not config.log_whitelist_on or any(record.name.startswith(name) for name in config.log_whitelist)) and \
not any(record.name.startswith(name) for name in config.lo... |
#!/usr/bin/env python
###############################################################################
# Simple PIL-based flexagon generator
#
# For the time being, it creates only 2D trihexaflexagons.
#
# Daniel Prokesch <daniel.prokesch@gmail.com>
#######################################################################... |
# -*- coding: utf-8 -*-
"""
Copyright [2009-2018] EMBL-European Bioinformatics Institute
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... |
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
class SoccerdatacrawlerPipeline(object):
def process_item(self, item, spider):
return item |
import re
from collections import Counter
def words(text): return re.findall(r'\w+', text.lower())
WORDS = Counter()
TOTAL_WORDS = 0
def init(filename = 'big.txt'):
global WORDS
global TOTAL_WORDS
#统计词频,并存储为词典
WORDS = Counter(words(open(filename).read()))
#统计总词数
TOTAL_WORDS=sum(WORDS.values()... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.