text stringlengths 1 927k |
|---|
# Copyright 2010 Google 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, publish, dis-
# trib... |
#!/usr/bin/env python
print "Content-type: text/html\n"
#######################################
# ----A script to extract tweet from twitter
# streaming API and inserting into database
# using psycopg2 and twython module-----
# Author: Suman baral
# Emai: shumanbaral@gmail.com
# Date: DD/MM/YYYY
# Version: 1.0... |
"""The n-dimensional hypersphere.
The n-dimensional hypersphere embedded in (n+1)-dimensional
Euclidean space.
"""
import logging
import math
from itertools import product
from scipy.stats import beta
import geomstats.algebra_utils as utils
import geomstats.backend as gs
from geomstats.geometry.base import Embedded... |
from __future__ import absolute_import
import re
import logging
from collections import defaultdict
from aleph.core import db, celery, USER_QUEUE, USER_ROUTING_KEY
from aleph.text import match_form
from aleph.model import Entity, EntityIdentity, Reference, Document, Alert
from aleph.model.common import merge_data
fro... |
# ===============================================================================
# Copyright 2016 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/licenses/LICE... |
from flask import Flask
UPLOAD_FOLDER = "D:/Education & Job Related & Personal Info/Job Related/Bootcamp/Metis/edm_generator/flask-web-apps/upload"
# app = Flask(__name__, template_folder='templates\webaudiofont-master\examples')
app = Flask(__name__, template_folder='templates')
app.secret_key = "secret key"
app.co... |
# -*- coding: utf-8 -*-
'''
Create ssh executor system
'''
# Import python libs
from __future__ import absolute_import, print_function
import base64
import copy
import getpass
import json
import logging
import multiprocessing
import subprocess
import hashlib
import tarfile
import os
import re
import sys
import time
imp... |
from yt.fields.field_info_container import FieldInfoContainer
from yt.fields.particle_fields import add_union_field
from yt.frontends.enzo_p.misc import nested_dict_get
rho_units = "code_mass / code_length**3"
vel_units = "code_velocity"
acc_units = "code_velocity / code_time"
energy_units = "code_velocity**2"
known_... |
arr = [[1, 2, 3, 12],
[4, 5, 6, 45],
[7, 8, 9, 78]]
x = 12
print("start")
w = len(arr)
h = len(arr[0])
i = 0
j = 0
ibak = -1
jbak = -1
while i < w and j < h and arr[i][j] < x and (i != ibak or j != jbak):
ibak = i
jbak = j
print("ij", i, j)
ib = i
ie = w - 1
i2 = -1
print("ibe", ib, ie)
while ib <... |
#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/component/weapon/shared_scope_weapon_sm_s02.iff"
result.attribute_t... |
from __future__ import absolute_import
import logging
import os
import six
import subprocess
import tempfile
import time
from email.utils import parseaddr
from functools import partial
from operator import attrgetter
from random import randrange
import lxml
import toronado
from django.conf import settings
from djang... |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
# coding=utf-8
# run script
import sys, os, argparse
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # so here won't have poll allocator info
# remove all the annoying warnings from tf v1.10 to v1.13
import logging
logging.getLogger('tensorflow').disabled = True
from tqdm import tqdm
import numpy as np
import tensorflow as... |
import pandas as pd
def compute_directed_edges(edges_w_features):
"""
Converts the undirected edge information into a directed format, by duplicating each edge and flipping the node
attributes to make it point in the opposite direction. This makes computation from the viewpoint of each node
simpler.
... |
from __future__ import absolute_import
# Copyright (c) 2010-2017 openpyxl
import pytest
from openpyxl.xml.functions import fromstring, tostring
from openpyxl.tests.helper import compare_xml
@pytest.fixture
def NonVisualGraphicFrameProperties():
from ..graphic import NonVisualGraphicFrameProperties
return No... |
"""NDG XACML package
NERC DataGrid
"""
__author__ = "P J Kershaw"
__date__ = "16/03/10"
__copyright__ = "(C) 2010 Science and Technology Facilities Council"
__contact__ = "Philip.Kershaw@stfc.ac.uk"
__license__ = "BSD - see LICENSE file in top-level directory"
__contact__ = "Philip.Kershaw@stfc.ac.uk"
__revision__ = ... |
"""
Interact with and debug a running app in the console.
Synchronous
~~~~~~~~~~~
Config:
all (bool):
``True`` to process any message, ``False`` (default) to restrict to defined channels.
console (str):
Use a different embedded console. By default, :meth:`code.interact` is used, but set this
... |
# -*- coding: utf-8 -*-
#
# Copyright 2019 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/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
# -*- coding: utf-8 -*-
#
# packaging.py
#
# Copyright (C) 2012, 2013 Steve Canny scanny@cisco.com
#
# This module is part of python-pptx and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
'''
The :mod:`pptx.packaging` module coheres around the concerns of reading and
writing p... |
import math
figure = str(input())
if figure == 'square':
length_of_side = float(input())
area = length_of_side * length_of_side
print(f'{area:.3f}')
elif figure == 'rectangle':
length_of_side_one = float(input())
length_of_side_two = float(input())
area = length_of_side_one * length_of_side_t... |
import os
from PIL import Image
import argparse
import shutil
def main(folderPath, height, width):
if(folderPath != os.getcwd()):
os.chdir(folderPath)
os.makedirs('scaled_images', exist_ok=True)
data = os.listdir('.')
count = 0
for _file in data:
try:
image = Image.open... |
from problem import Problem
import numpy as np
import itertools
import csv
import sys
class Vertex_Cover(Problem):
def __init__(self, N, data):
super().__init__()
# self.solver = solvers_dict[solver.lower()]()
self.P = {"N": N}
self.data = data
# data[:,0] is number of elem... |
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="serial-teleinfo",
version="1.0.1",
author="Ugo Méda",
author_email="meda.ugo@gmail.com",
description="Utilities to connect to a Teleinformation serial device",
long_description=long_de... |
########
# Copyright (c) 2018 Cloudify Platform 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.apache.org/licenses/LICENSE-2.0
#
# Unless requi... |
"""Module containing the Events class used for event handling."""
from __future__ import annotations
import contextlib
import functools
import itertools as it
import pathlib
from typing import TYPE_CHECKING
from PyQt5 import QtWidgets
import lightning_pass.gui.gui_util.event_decorators as decorators
from lightning_p... |
from __future__ import print_function, division
import os
import numpy as np
from keras.layers import BatchNormalization, Activation
from keras.layers import Input, Dense, Flatten, Dropout
from keras.layers.advanced_activations import LeakyReLU
from keras.layers.convolutional import UpSampling3D, Conv3D, Deconv3D
from... |
# Copyright (c) 2019, Facebook, Inc. and its affiliates. All Rights Reserved
__version__ = "0.6.1"
from .tokenization import BertTokenizer, BasicTokenizer, WordpieceTokenizer
from .modeling import (BertConfig, BertModel, BertForPreTraining, PROP,
BertForMaskedLM, BertForNextSentencePrediction,
... |
#!/usr/bin/env python
import sys
import time
def write(data):
sys.stdout.write(data + '\n')
sys.stdout.flush()
def main():
msg = 'announce attribute next-hop 1.2.3.4 med 100 as-path [ 100 101 102 103 104 105 106 107 108 109 110 ] nlri %s'
write(msg % ' '.join('%d.0.0.0/8' % ip for ip in range(0, 22... |
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
# NOTE: Created with generate_compiled_resources_gyp.py, please do not edit.
{
'targets': [
{
'target_name': 'global-extracted',
'includes... |
import numpy as np
from utils import read_file
file_path = './input/day7.txt'
def parse_file(file_content):
return [int(x) for x in file_content.split(',')]
def fuel(steps):
return steps*(steps+1)/2
data = parse_file(read_file(file_path))
np_data = np.array(data)
median = np.median(np_data)
distance_su... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-10-21 03:05
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('publicly_traded_companies', '0003_auto_20171003_0207'),
... |
# -*- coding: utf-8 -*-
from time import sleep
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
def main():
# Your Facebo... |
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... |
#!/usr/bin/env python
import telnetlib # importing the Telnet Python module
import time # importing it for time.sleep(1) line
TELNET_PORT = 23
TELNET_TIMEOUT = 6 # in seconds
# Creating a function which establishes remote telnet connection
def send_command(remote_conn, cmd):
cmd = cmd.rstrip... |
import matplotlib
# Do not use X for plotting
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
from matplotlib.ticker import FormatStrFormatter
from tempfile import NamedTemporaryFile
def plot_to_file(symbol, timestamp, close, score):
fig, ax1 = plt.subplots()
... |
import os
import copy
from trishanku.tpi.reader.hocon import HoconFileReader, HoconStringReader, HoconConfigDictReader
from setu.core.constants import SetuConfigOption
from .validator import ConfigValidator
from .config import Config, SetuConfig, UserConfig
from pprint import pprint
class ConfigCreator:
SETU_CONF... |
from .conftest import GoProCameraTest
from socket import timeout
from urllib import error
class GpControlSetTest(GoProCameraTest):
def test_gp_control_set(self):
# on success, this is an empty json blob
self.responses['/gp/gpControl/setting/foo/bar'] = '{}'
assert '{}' == self.goprocam.gp... |
"""
Python 3 Object-Oriented Programming 4th ed.
Chapter 2, Objects in Python.
"""
import ecommerce.database
class Vendor:
def __init__(self, name: str) -> None:
self.name = name |
'''
quail_serial:
This module handles serial interaction with Quail, collecting data from a serial port input and handing it to
various queues to be processed by the GUI. This is a secondary process that is meant to run in parallel with the GUI,
rather than blocking it.
The Quail class has three primary objects that ... |
import json
from datetime import timedelta
from multiprocessing import set_start_method
from typing import List, AsyncGenerator
import pytest
from resotocore.analytics import AnalyticsEventSender
from resotocore.db.graphdb import ArangoGraphDB
from resotocore.db.model import GraphUpdate
from resotocore.dependencies i... |
"""SCons.Scanner
The Scanner package for the SCons software construction utility.
"""
#
# __COPYRIGHT__
#
# 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
# w... |
import numpy as np
def optimalTau(probabilities, ylabels):
""" Finds the Optimal tau based on the F1 score"""
#STEP 1 SORT PROBABILITIES AND LABELS
sortedIndexes = np.argsort( probabilities )
probabilities1 = probabilities[ sortedIndexes ]
... |
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals, division, absolute_import
import contextlib
import os
import os.path
import platform
import sys
sys.path.append('.')
sys.path.append('./fatuv')
import unittest
import fatuv as uv
__dir__ = os.path.dirname(__file__)
PY2_RERAISE = '''
... |
"""
WSGI config for superhero_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.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJ... |
from setuptools import setup
with open("README.md","r") as fh:
long_description = fh.read()
setup(
name="Easy-QLearning",
version="1.0.0",
description="Simplify the creation of QLearning",
py_modules=["EQL"],
package_dir={'': 'src'},
classifiers=[
"Programming Language :: Python ::... |
"""Custom S3 storage backends to store files in subfolders."""
from storages.backends.s3boto3 import S3Boto3Storage
class MediaRootS3BotoStorage(S3Boto3Storage):
location = 'media'
class StaticRootS3BotoStorage(S3Boto3Storage):
location = 'static'
class SitemapRootS3BotoStorage(S3Boto3Storage):
locati... |
from __future__ import print_function
import numpy as np
from bokeh.browserlib import view
from bokeh.document import Document
from bokeh.models.glyphs import *
from bokeh.models import (
Plot, Range1d, LinearAxis, Grid, ColumnDataSource, PanTool, WheelZoomTool
)
from bokeh.session import Session
document = Docu... |
from midiutil import MIDIFile
def degree_to_note(root, mode, degree):
"""Convert a list of relative degrees to midi note numbers.
Parameters
----------
key - MIDI note number for the root note
mode - a number for the mode (0 - Ionian (major),
1 - Dorian, ..., 5 - Aeolian (minor), ..... |
import logging
import inspect
from functools import wraps
from ray import cloudpickle as pickle
from ray._raylet import PythonFunctionDescriptor
from ray import cross_language, Language
from ray._private.client_mode_hook import client_mode_convert_function
from ray._private.client_mode_hook import client_mode_should_c... |
import pytest
import flopt
from flopt import Variable, Problem, Solver
from flopt.performance import CustomDataset
@pytest.fixture(scope='function')
def a():
return Variable('a', lowBound=2, upBound=4, cat='Continuous')
@pytest.fixture(scope='function')
def b():
return Variable('b', lowBound=2, upBound=4, ca... |
from manim2.imports import *
class Dedo_i1(ImageMobject):
def __init__(self,**kwargs):
digest_config(self, kwargs)
ImageMobject.__init__(self,"fingers/dedo3")
self.set_opacity(1)
class Dedo_i2(ImageMobject):
def __init__(self,**kwargs):
digest_config(self, kwargs)
ImageMobject.__init__(self,"fingers/dedo4... |
from PyQt5.Qt import QMainWindow, QTabWidget, QAction
from pyqt_sql_demo.widgets.connection import ConnectionWidget
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setMinimumWidth(640)
self.setMinimumHeight(480)
# Set up QTabWidget as a central widget
... |
import asyncio
import collections
import gc
import logging
import pytest
import re
import socket
import sys
import time
import uuid
import warnings
import docker as docker_mod
import memcache
import aiomcache
mcache_server_option = None
def pytest_addoption(parser):
parser.addoption(
'--memcached', hel... |
"""
pluginName = slowmo
Senario When motion tracking triggered take a slow motion video
---------------------------------------------------------------
You have a project where you want to capture a slow motion video
sequence. This plugin will monitor the camera view using motion
tracking and tigger a video at a hig... |
"""Tests for :mod:`.schedule`."""
from unittest import TestCase
from datetime import datetime, timedelta
from pytz import timezone, UTC
from ... import schedule
ET = timezone('US/Eastern')
class TestSchedule(TestCase):
"""Verify that scheduling functions work as expected."""
def test_monday_morning(self):
... |
import string
def find_all_lines(file_path):
with open("text.txt", "r") as file:
all_lines = file.read().split("\n")
return all_lines
def find_count_letters(current_line):
count = 0
for char in current_line:
if char.isalpha():
count += 1
return count
def find_count_... |
from __future__ import print_function
from __future__ import absolute_import
#######################################################################
#
# Push Service for Enigma-2
# Coded by betonme (c) 2012 <glaserfrank(at)gmail.com>
# Support: http://www.i-have-a-dreambox.com/wbb2/thread.php?threadid=167779
#... |
# -*- test-case-name: twisted.names.test.test_names -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Asynchronous client DNS
The functions exposed in this module can be used for asynchronous name
resolution and dns queries.
If you need to create a resolver with specific requirements, s... |
import socket
conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
conn.bind(("127.0.0.1", 14900))
conn.listen(10)
while True:
try:
clientsocket, address = conn.accept()
data_bin = clientsocket.recv(16384)
data = data_bin.decode("utf-8")
data = data.split(" ")
area = ... |
from urllib.parse import urlparse
from syft.workers.model_centric_fl_worker import ModelCentricFLWorker
from syft.federated.fl_job import FLJob
class FLClient:
def __init__(self, url, auth_token, verbose=False):
self.url = url
self.auth_token = auth_token
self.worker_id = None
url... |
import json
import os
from pathlib import Path
from typing import Callable
def get_test_resource(relative_path):
dir = Path(os.path.dirname(os.path.realpath(__file__)))
return str(dir / relative_path)
def load_json_resource(relative_path, preprocess: Callable = None):
with open(get_test_resource(relativ... |
from __future__ import absolute_import
import sys
sys.path.append('./')
import timeit
import argparse
import os
import os.path as osp
import numpy as np
import math
import time
from PIL import Image, ImageFile
import torch
from torch import nn, optim
from torch.backends import cudnn
from torch.utils.data import DataLo... |
"""
Test lldb data formatter subsystem.
"""
from __future__ import print_function
import os
import time
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class StdUniquePtrDataFormatterTestCase(TestBase):
mydir = TestBase.compute_mydir(... |
import _plotly_utils.basevalidators
class TitlefontValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(
self, plotly_name='titlefont', parent_name='layout', **kwargs
):
super(TitlefontValidator, self).__init__(
plotly_name=plotly_name,
parent_name=p... |
# IMPORTATION STANDARD
# IMPORTATION THIRDPARTY
import pandas as pd
import pytest
from degiro_connector.trading.models import trading_pb2
# IMPORTATION INTERNAL
from gamestonk_terminal.portfolio.brokers.degiro.degiro_model import DegiroModel
# pylint: disable=E1101
# pylint: disable=W0603
# pylint: disable=E1111
@... |
"""This module supports instance configuration for so3g. Eventually
this might be loaded from config file, perhaps ~/.so3g. But for now it's
hard-coded to return sensible defaults.
"""
DEFAULTS = {
'patch_g3frame': True, # boolean.
'use_astropy': 'try', # string. yes, no, try
'use_pixell': 'try', ... |
from mayan.apps.testing.tests.base import GenericViewTestCase
from ..events import event_cache_partition_purged, event_cache_purged
from ..permissions import (
permission_cache_purge, permission_cache_view
)
from .mixins import CacheTestMixin, CacheViewTestMixin
class CacheViewTestCase(
CacheTestMixin, Cach... |
# Copyright 2020 The StackStorm Authors.
# Copyright 2019 Extreme Networks, 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 ... |
# Generated by Django 2.2.5 on 2019-10-06 08:54
from django.db import migrations, models
import smart_contract.models
class Migration(migrations.Migration):
dependencies = [
('smart_contract', '0036_auto_20191004_1119'),
]
operations = [
migrations.AddField(
model_name='user... |
from django.utils.version import get_version
VERSION = (1, 9, 0, 'final', 0)
__version__ = get_version(VERSION)
def setup():
"""
Configure the secure (this happens as a side effect of accessing the
first setting), configure logging and populate the app registry.
"""
from django.apps import apps
... |
import FWCore.ParameterSet.Config as cms
# output block for alcastream HCAL Isotrk
# output module
# module alcastreamHcalIsotrkOutput = PoolOutputModule
OutALCARECOHcalCalIsoTrk_noDrop = cms.PSet(
# use this in case of filter available
SelectEvents = cms.untracked.PSet(
SelectEvents = cms.vstring('p... |
#!/usr/bin/env python3.6
# -*- coding: utf-8 -*-
import os
import sys
import glob
import json
import logging
import itertools
import toolz
import statistics
from matplotlib import rc
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
rc('text', usetex=True)
import matplotlib.pyplot as plt
import numpy a... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 19 10:59:51 2020
@author: suyu
"""
from sklearn.model_selection import train_test_split,GridSearchCV,PredefinedSplit
from sklearn.metrics import make_scorer,mean_squared_error,roc_auc_score,mean_absolute_error,log_loss
from xgboost import XGBClassifier,XGBRegressor
import... |
# GDB 'explore' command.
# Copyright (C) 2012-2019 Free Software Foundation, Inc.
# 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 late... |
import datetime
import re
import django.utils.timezone
import djchoices
import polymorphic.models
import sizefield.models
from django.conf import settings
from django.db import models, transaction, IntegrityError
from django.urls import reverse
from django.utils import timezone
from django.utils.translation import uge... |
import logging
import re
from streamlink.plugin import Plugin, pluginmatcher
from streamlink.plugin.plugin import parse_params
from streamlink.stream.akamaihd import AkamaiHDStream
from streamlink.utils.url import update_scheme
log = logging.getLogger(__name__)
@pluginmatcher(re.compile(
r"akamaihd://(?P<url>\S... |
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
class Data(object):
def __init__(self, value, should_prepare=True, prepare_with=None):
"""
A container object that carries meta information about the data.
``value`` should be the data to be returned to the client. This may
be post-processed.
``should_prepare`` determines w... |
#!/usr/bin/env python
from funlib.show.neuroglancer import add_layer
import argparse
import daisy
import glob
import neuroglancer
import os
import webbrowser
import numpy as np
import zarr
parser = argparse.ArgumentParser()
parser.add_argument(
'--file',
'-f',
type=str,
action='append',
help="The ... |
print("something!")
def find_the_avg_for_contigious_subarray(arr, K):
"""
Sliding window...
"""
window_start = 0
window_sum = 0
avg = []
for k in range(len(arr)):
window_sum += arr[k]
if k >= (K-1):
avg.append(window_sum / K)
window_sum -= arr[... |
"""
This tutorial introduces logistic regression using Theano and stochastic
gradient descent.
Logistic regression is a probabilistic, linear classifier. It is parametrized
by a weight matrix :math:`W` and a bias vector :math:`b`. Classification is
done by projecting data points onto a set of hyperplanes, the distance... |
"""
HiPPI algorithm as described in ICCV 2019 paper
.. moduleauthor:: François-Xavier Dupé
"""
import numpy as np
import graph_matching_tools.algorithms.multiway.utils as utils
def hippi_multiway_matching(s, sizes, knode, u_dim, iterations=100, tolerance=1e-6, init=None):
"""
HiPPI method for multi-graph ma... |
# Copyright 2017 The Sonnet Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... |
# 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/python
# coding=utf-8
# P(c | d) = P(c) * П [P(tk | c)];
# P(c | d) = log (P(c)) + Sum [ log(P(tk | c)) ]
# P(tk | c) = (Tkc + 1) / (Sum(Tkc) + B)
import math
from pprint import pprint
import itertools
class MultinomialNaiveBayes(object):
def __init__(self):
self.V = None
self.prepro... |
import errno
import os
import subprocess
from pytest import fail
KB = 1000
MB = KB * KB
GB = MB * KB
KiB = 1024
MiB = KiB * KiB
GiB = MiB * KiB
class CmdExecutor:
def __init__(self):
pass
def execute(self, command, log_path=None):
process = subprocess.Popen(command, shell=True, stderr=sub... |
# Copyright 2016 Massachusetts Open Cloud
#
# 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... |
"""
WSGI config for ourrevolution 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/1.10/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
from whitenoise.django import... |
from django import template
from ..forms import AccessTokenForm
register = template.Library()
@register.simple_tag(takes_context=True)
def get_token_url_form(context, purpose='', label='', url_name='',
**url_kwargs):
return AccessTokenForm(
purpose=purpose,
user=context['r... |
from datetime import datetime
import peewee as pw
from xmrbackers import config
db = pw.PostgresqlDatabase(
config.DB_NAME,
user=config.DB_USER,
password=config.DB_PASS,
host=config.DB_HOST,
)
class User(pw.Model):
"""
User model is for pure user authentication management
and reporting.... |
#!/usr/bin/env python
"""
Parts of this file were taken from the pyzmq project
(https://github.com/zeromq/pyzmq) which have been permitted for use under the
BSD license. Parts are from lxml (https://github.com/lxml/lxml)
"""
import os
import sys
import shutil
import warnings
import re
# may need to work around setup... |
"""
Авто генерики для REST API.
"""
import logging
import json
from rest_framework.generics import (
ListAPIView, RetrieveAPIView, UpdateAPIView,
CreateAPIView, DestroyAPIView, GenericAPIView
)
from rest_framework.response import Response
from rest_framework.serializers import BaseSerializer
from ..exception... |
#!/usr/bin/env python
#==============================================================================
#author :Miryam de Lhoneux
#email :miryam.de_lhoneux@lingfil.uu.se
#date :2015/12/30
#version :1.0
#Python version :2.7.6
#==============================================================================
"""FUNCT... |
from __future__ import annotations
# Copyright 2020, 2021 Evandro Chagas Ribeiro da Rosa <evandro.crr@posgrad.ufsc.br>
# Copyright 2020, 2021 Rafael de Santiago <r.santiago@ufsc.br>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License... |
# Generated by Django 3.2.6 on 2021-09-08 11:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0004_alter_user_password'),
]
operations = [
migrations.AlterField(
model_name='user',
name='first_name',
... |
"""
This module is responsible for everything related with logs.
TODO: Make this docstring better
"""
import sys
import syslog
from datetime import datetime, date
from typing import Optional
from enum import Enum
from pydantic import BaseModel
class MsgStatus(str, Enum):
"""
Enum type indicating the t... |
# To add a new artifact module, import it here as shown below:
# from scripts.artifacts.fruitninja import get_fruitninja
# Also add the grep search for that module using the same name
# to the 'tosearch' data structure.
import traceback
from scripts.artifacts.accounts_ce import get_accounts_ce
from scripts.artifa... |
# coding: utf-8
"""
DriveLogData.py
The Clear BSD License
Copyright (c) – 2016, NetApp, Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the limitations in the disclaimer below) provided that the following conditions are met:
*... |
from __future__ import unicode_literals
import tornado.ioloop
import tornado.web
import tornado.websocket
import logging
from leapcast.apps.default import *
from leapcast.services.rest import *
from leapcast.services.websocket import *
class LEAPserver(object):
def start(self):
logging.info('Starting LE... |
import sys
sys.path.append("..")
import torch
from torch import nn
import torch.nn.functional as F
import random
import argparse
try:
from torchqrnn import QRNN
except:
# to stop python 3.7.x breaking
QRNN = None
from models.EncoderDecoder import (
EncoderModel,
DecoderModel,
EncoderDecoderMo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.