content stringlengths 5 1.05M |
|---|
from allmydata.storage.backends.cloud.u1.u1_container import configure_u1_container
configure_container = configure_u1_container
|
# 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... |
# -*- coding: utf-8 -*-
import calendar
from copy import deepcopy
from datetime import date, datetime, time
from typing import Any, Dict, List
from uuid import UUID
from croniter import croniter
from flask import abort, jsonify
from marshmallow import ValidationError
import simplejson as json
from chaosplt_account.mo... |
instructions = input()
h_count = 0
v_count = 0
for letter in instructions:
if letter == "H":
h_count += 1
elif letter == "V":
v_count += 1
if h_count%2 == 0:
if v_count%2 == 0:
print("1 2\n3 4")
elif v_count%2 == 1:
print("2 1\n4 3")
elif h_count%2 == 1:
if v_count%2 ... |
import FWCore.ParameterSet.Config as cms
XMLIdealGeometryESSource = cms.ESSource("XMLIdealGeometryESSource",
geomXMLFiles = cms.vstring('Geometry/CMSCommonData/data/materials.xml',
'Geometry/CMSCommonData/data/rotations.xml',
'Geometry/CMSCommonData/data/normal/cmsextent.xml',
'Geometry/... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import asyncio
import logging
import uuid
import os
import time
logging.basicConfig(format=u'%(filename)s[LINE:%(lineno)d]# %(levelname)-8s [%(asctime)s] %(message)s',
level=logging.DEBUG)
import os.path
import sys
SOCKET_PING... |
import numpy as np
import os
import seas.video
from seas.video import load, dfof, rotate, rescale
from seas.filemanager import sort_experiments, get_exp_span_string, read_yaml
from seas.rois import roi_loader, make_mask, get_masked_region, insert_masked_region, draw_bounding_box
from seas.hdf5manager import hdf5ma... |
import os
import torch
import torchvision
import torchvision.transforms as transforms
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
# transforms
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5,), (0.5,))])
# datasets
trainset = torchvision... |
from django.urls import reverse
from service_catalog.models.documentation import Doc
from tests.test_service_catalog.base_test_request import BaseTestRequest
class TestCustomerCatalogViews(BaseTestRequest):
def setUp(self):
super(TestCustomerCatalogViews, self).setUp()
self.client.login(username... |
#
# Copyright 2022 European Centre for Medium-Range Weather Forecasts (ECMWF)
#
# 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 req... |
# Copyright 2021 Zilliz. 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 agree... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from . import math
from . import utilities
from . import validations
from . import activations
from . import initializers
from .utilities import *
from .validations import *
from .math import *
from .find_ne... |
#! /usr/bin/python3
r'''###############################################################################
###################################################################################
#
#
# GPT-2 with Relative Global Attention
# Version 0.5
#
# PLEASE NOTE THAT THIS IS A WORK IN PROGRESS
# CHECK BACK FOR UPDATES S... |
#!/usr/bin/env python3
import numpy as np
from sklearn import preprocessing
print('Label Encoding')
# Sample input labels
input_labels = ['red','black','red','green','black','yellow','white']
# Creating the label encoder
encoder = preprocessing.LabelEncoder()
encoder.fit(input_labels)
# encoding a set of labels
test... |
'''
Code for the PyTorch implementation of
"DeepFocus: a Few-Shot Microscope Slide Auto-Focus using a Sample-invariant CNN-based Sharpness Function"
Copyright (c) 2020 Idiap Research Institute, http://www.idiap.ch/
Written by Adrian Shajkofci <[email protected]>,
All rights reserved.
This file is part of Deep... |
import datetime
dt_utc = datetime.datetime(2018, 12, 31, 5, 0, 30, 1000,
tzinfo=datetime.timezone.utc)
print(dt_utc.tzinfo)
# UTC
print(type(dt_utc.tzinfo))
# <class 'datetime.timezone'>
print(dt_utc.utcoffset())
# 0:00:00
print(type(dt_utc.utcoffset()))
# <class 'datetime.timedelta'>
d... |
from System import Random
rand = Random()
def randomBool():
if rand.Next(0,2) < 1:
return "True"
else:
return "False"
def run_script():
print("(" + randomBool() + ", " + randomBool() + ", " + randomBool() + ")" )
|
# -*- coding: utf-8 -*-
# Resource object code
#
# Created by: The Resource Compiler for PyQt5 (Qt v5.14.1)
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore
qt_resource_data = b"\
\x00\x00\x12\xe4\
\x00\
\x00\x66\x71\x78\x9c\xcd\x1d\x6b\x73\xdb\x36\xf2\xf3\xe9\x57\xa0\
\xce\x97\x38\x... |
#!/usr/bin/env python3
from setuptools import setup, find_packages
setup(
name="tv_report",
version="1.1.7",
author="Justin Dray",
author_email="[email protected]",
url="https://github.com/justin8/tv_report",
description="A parser for tv show episode files of various formats",
packages=find_pa... |
# python cloudmesh/compute/awsboto/test_boto.py
import sys
import traceback
from pprint import pprint
import boto3
from cloudmesh.configuration.Config import Config
config = Config()
# pprint(config.data)
credentials = config['cloudmesh.cloud.awsboto.credentials']
pprint(credentials)
new_yaml_data_dict = {
'User... |
#encoding:utf-8
from system.models import *
import hashlib
Customer.objects.create(
CustomerAccount = 'customer1',
CustomerName = 'customer1',
CustomerPassword = hashlib.md5('123456').hexdigest(),
CustomerTelephone = '11111111',
CustomerEmail = '[email protected]',
CustomerAddress = 'far away')
Customer.objects.cr... |
class FTLSerializer():
def serialize(self, ast):
body = ast['body']
comment = ast['comment']
string = u''
if comment is not None:
string += self.dumpComment(comment) + u'\n\n'
for entry in body:
string += self.dumpEntry(entry)
return string
... |
import math
class sample:
def __init__(self,a=[],r=1):
self.dat = a
self.rate = r
def __getitem__(self,i):#no interpolation
return self.dat[int(i*self.rate)]
def __len__(self):
return len(self.dat)/self.rate
class linterpSample(sample):
def __getitem__(self,i):
i... |
def menu(parent_id=0, menutree=None):
menutree = menutree or []
cur = g.db.execute('select id, parent, alias, title, ord from static where parent="'+ str(parent_id) +'" and ord>0 order by ord')
fetch = cur.fetchall()
if not fetch:
return None
return [{'id':raw[0], 'parent':raw[1], 'alias':... |
# coding:utf-8
"""
[email protected]
package A : pack num, pack length
package B : pack lenght, pack payload
Client Send pA, get ack, then send pB, Server give ack
python ttcp.py -m server
python ttcp.py -m client
"""
import socket
import time
import struct
import sys
import argparse
INT_LEN = struct.calcsize('... |
import platform
from setuptools import setup, find_packages
from sys import argv
import setuptools
TORCH_MAJOR = 1
TORCH_MINOR = 3
import pprint
extra_compile_args = []
if platform.system() != 'Windows':
extra_compile_args += ['-Wno-unused-variable']
if (TORCH_MAJOR > 1) or (TORCH_MAJOR == 1 and TORCH_MINOR > 2):
... |
import numpy as np
import matplotlib.pyplot as plt
def plot2D(array, cmap='viridis'):
plt.figure(0)
plt.imshow(np.repeat(array, repeats=5, axis=0), cmap=cmap)
plt.show()
def plot3D(array, n_cols=3, cmap='viridis'):
plt.figure(0)
n, h, w = array.shape
n_cols = min(n, n_cols)
n_rows = int(np... |
# -*- coding: utf-8 -*-
"""
s3://sanhe-aws-athena-practice/data/db_learn_athena/
"""
import boto3
from .config import aws_profile, bucket_name, dbname
ses = boto3.Session(profile_name=aws_profile)
s3 = ses.resource("s3")
bucket = s3.Bucket(bucket_name)
if bucket.creation_date is None:
s3.create_bucket(Bucket=buc... |
def KMPSearch(pat, txt):
pat_len = len(pat)
txt_len = len(txt)
lps = [0] * pat_len
pat_index = 0
computeLPSArray(pat, pat_len, lps)
txt_index = 0
while txt_index < txt_len:
if pat[pat_index] == txt[txt_index]:
txt_index += 1
pat_index += 1
if pat_index == pat_len:
print ("Fou... |
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 7 14:56:22 2020
@author: sj
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import rscls
colors = ['#000000','#CACACA', '#02FF00', '#00FFFF', '#088505', '#FF00FE', '#AA562E', '#8C0085', '#FD0000', '#FFFF00... |
# pip install pygame
import pygame
# Import random for random numbers
import random
# pip install pyserial
import serial
import json
# change the port as necessary by your OS
ser = serial.Serial('/dev/cu.usbserial-02301AC2', 9600)
from pygame.locals import (
K_UP,
K_DOWN,
K_LEFT,
K_RIGHT,
K_ESC... |
"""Corpus Loaders"""
from typing import Optional
from speechcorpusy.interface import AbstractCorpus, ConfCorpus
from speechcorpusy import presets
def load_preset(
name: str,
root: Optional[str] = None,
download: Optional[bool] = None,
conf: Optional[ConfCorpus] = None,
) -> AbstractCorpus:
"... |
# RAFT's main model class
import os
import os.path as osp
import sys
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
import moorpy as mp
import pyhams.pyhams as ph
import raft.member2pnl as pnl
import raft.raft_fowt as fowt
from raft.helpers import *
#import F6T1RNA as structural ... |
#--------------------------------------------------------------------------
# File and Version Information:
# $Id: SegGeometryStore.py 11400 2016-02-23 00:07:50Z [email protected] $
#
# Description:
# Module SegGeometryStore...
#
#------------------------------------------------------------------------
"""
... |
import re
from dataclasses import dataclass
from typing import Iterator, Type
@dataclass
class Token:
value: str
def __repr__(self) -> str:
return f'{self.__class__.__name__}("{self.value}")'
class StringToken(Token):
pass
class BraceToken(Token):
pass
class TokenizeError(Exception):
... |
from django.conf.urls import patterns, url
from . import views
from ideahub.apps.accounts.forms import LoginForm
urlpatterns = patterns('',
# TODO: Fix these temporary mappings
url(r'^login/?$', views.login, name='login'),
url(r'^signup/?$', views.signup, name='signup'),
url(r'^get_started/?$', views.g... |
# Generated with love
import typing
from vkbottle.types import responses
from .access import APIAccessibility
from .method import BaseMethod
class AccountBan(BaseMethod):
access_token_type: APIAccessibility = [APIAccessibility.USER]
async def __call__(self, owner_id: int = None) -> responses.ok_response.OkRe... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2021-03-30 00:53
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('mooringlicensing', '0044_feeseasonapplicationtype'),
]
operations = [
migrations.R... |
# Copyright 2020-present NAVER Corp. Under BSD 3-clause license
"""
Merge kapture objects for reconstructions.
"""
from kapture.io.binary import array_to_file
from kapture.io.tar import TarCollection
import numpy as np
import os
import shutil
from typing import Dict, List, Union, Optional, Tuple, Type
import kapture... |
# https://www.pyimagesearch.com/2021/03/29/multi-template-matching-with-opencv/
import numpy as np
import argparse
import cv2
# Source: https://www.pyimagesearch.com/2015/02/16/faster-non-maximum-suppression-python/
# Malisiewicz et al.
def non_max_suppression_fast(boxes, overlapThresh):
# if there are no boxes, ... |
configfile: 'config_spocd1_pi.yaml'
bedtools = "/usr/local/Cellar/bedtools/2.27.1/bin/bedtools"
rule all:
input:
expand("Processed/v3/mapped/{sample}_unique_sorted_edited_TE.bed", sample = config["samples"]),
expand("Processed/v3/mapped/{sample}_unique_sorted_edited_nTE.bed", sample = config["samples"]),
ex... |
import torch
import argparse
device_ids = [0, 1]
device = torch.device('cuda:{}'.format(min(device_ids)) if torch.cuda.is_available() else 'cpu')
def parse(args):
# 1. arg parser
parser = argparse.ArgumentParser()
parser.add_argument('--epoch', type=int, default=13) # 13
parser.add_a... |
import csv
import os
import discord
from discord.ext import commands
# ----------------------------------------------------------------------------------------------
# Returns the ping of the bot, useful for testing bot lag and as a simple functionality command
# ------------------------------------------------------... |
import numpy as np
from scipysound import Sound
import phasevocoder
#TODO ease in playback adjustments
class SoundPlus(Sound):
def __init__(self, y, sr, chunk_size=2048):
self._init_offset = 0
super().__init__(y, sr, chunk_size)
def _init_stretching(self):
super()._init_stretching()
... |
#import stuff
import sqlite3, string, random
from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash
from contextlib import closing
#configuration
DATABASE = '/tmp/loonus.db'
DEBUG = True
SECRET_KEY = 'development key'
USERNAME = 'admin'
PASSWORD = 'default'
#create app
app = Fla... |
"""Defines the configuration to be loaded before running any experiment"""
from configobj import ConfigObj
import string
class Config(object):
def __init__(self, filename: string):
"""
Read from a config file
:param filename: name of the file to read from
"""
self.filename... |
#!/usr/bin/env python3
from os import environ
from github import Github
gh_ref = environ['GITHUB_REPOSITORY']
gh_sha = environ['INPUT_SHA']
exit(1)
print('Getting status of %s @ %s...' % (gh_ref, gh_sha))
status = Github(environ['INPUT_TOKEN']
).get_repo(gh_ref).get_commit(sha=gh_sha).get_combined_s... |
from __future__ import annotations # define out of order or recursive
from typing import Any, Dict, List, Optional
from errors import LoxRuntimeError
from loxcallable import LoxCallable
from loxfunction import LoxFunction
from token_class import Token
class LoxClass(LoxCallable):
def __init__(
self, na... |
include("$(MPY_DIR)/extmod/uasyncio/manifest.py")
freeze("$(MPY_DIR)/drivers/dht", "dht.py")
freeze("$(MPY_DIR)/drivers/lm75", "lm75.py")
freeze("$(MPY_DIR)/drivers/display", ("lcd160cr.py", "lcd160cr_test.py"))
freeze("$(MPY_DIR)/drivers/onewire", "onewire.py")
|
import pytest
import collections
from os import path
from shconfparser.reader import Reader
from shconfparser.shsplit import ShowSplit
from shconfparser.parser import Parser
class TestParser:
@pytest.fixture
def setup(self):
file_path = path.abspath('data/shcommands.txt')
p = Parser()
... |
import numpy as np
import multiprocessing
import functools
import itertools
from count_table import NoisedCountTable, BlockResult, calculate_mean_and_aggregation_error, implicit_ae
"""
Python hdpview
"""
def run(block, epsilon, ratio, prng, alpha=2, beta=1.2, gamma=1.0, theta=None, verbose=False):
"""Run HDPView
... |
def two_point_crossover(parent_1, parent_2, crossover_point_1, crossover_point_2):
mask = ['0' for _ in range(len(parent_1))]
for i in range(crossover_point_1, crossover_point_2 + 1):
mask[i] = '1'
crossover_mask = ''.join(mask)
offspring_1 = []
offspring_2 = []
for parent_1_dna, parent_... |
"""
From mitbbs for Facebook
"""
def count_zero_for_factorial(n):
i = 1
count = 0
while i <= n:
num = i
while num % 5 == 0:
count += 1
num /= 5
i += 1
return count
def fact(n):
if n == 1:
return n
return n * fact(n-1)
N = 51
print count... |
# -*- coding: utf-8 -*-
from odoo import http
# class CowinSettings(http.Controller):
# @http.route('/cowin_settings/cowin_settings/', auth='public')
# def index(self, **kw):
# return "Hello, world"
# @http.route('/cowin_settings/cowin_settings/objects/', auth='public')
# def list(self, **kw):... |
import os
from conans import ConanFile, tools
class ExprtkConan(ConanFile):
name = "exprtk"
version = "20181202"
description = "ExprTk is a simple to use, easy to integrate and extremely efficient run-time mathematical expression parser and evaluation engine"
topics = ("conan", "exprtk", "math-express... |
from datetime import datetime
import pytest
from loguru import logger
import app.internal.google_connect as google_connect
from app.routers.event import create_event
from app.database.models import OAuthCredentials
from app.routers.user import create_user
from google.oauth2.credentials import Credentials
from googlea... |
import threading
from threading import Thread, Semaphore, Lock
import random
from time import sleep
#configurable variables
STASH = 25
BUCKET_SIZE = 5
NUM_FROLFERS = 5
#Locking Structures
stashLock = Lock()
fieldLock = Lock()
stashEmpty = Semaphore(0)
stashFull = Semaphore(0)
#other global vars
discs_on_field = 0
rn... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.18 on 2019-02-28 20:27
from __future__ import unicode_literals
from django.db import migrations
def forward(apps, schema_editor):
Area = apps.get_model('guides','Area')
for area in [
'ART: Applications and Real-Time',
'INT: Internet',
... |
#!/usr/bin/python
# Classification (U)
"""Program: initate_dump.py
Description: Integration testing of initate_dump in elastic_db_dump.py.
Usage:
test/integration/elastic_db_dump/initate_dump.py
Arguments:
"""
# Libraries and Global Variables
# Standard
import sys
import os
import shutil
i... |
class Solution:
def findLatestStep(self, arr: List[int], m: int) -> int:
n = len(arr)
parent, size, result, bitsArray, count = [x for x in range(n)], [1] * n, -1, [0] * n, Counter()
def find(x):
if parent[x] == x:
return x
else:
... |
# -*- coding: utf-8 -*-
"""
Solace
======
*a multilingual support system*
Solace is a multilingual support system developed at Plurk
for end user support. The application design is heavily
influenced by bulletin boards like phpBB and the new
stackoverflow programming community site.
For more information consult th... |
from spaceone.core.service import *
from spaceone.identity.manager.endpoint_manager import EndpointManager
@authentication_handler
@authorization_handler
@mutation_handler
@event_handler
class EndpointService(BaseService):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
sel... |
#!/usr/bin/env python3
import os
import sys
import textwrap
self_path = os.path.dirname(os.path.realpath(__file__));
f = open(self_path + "/unicode/CaseFolding.txt", "r")
status_list = [ "C", "F" ]
folding_list = [ dict(), dict(), dict() ]
# Filter the foldings for "full" folding.
for line in f:
comment_off =... |
#TODO add offline mode
from asciimatics.event import KeyboardEvent
from asciimatics.widgets import *
from asciimatics.scene import Scene
from asciimatics.screen import Screen
from asciimatics.exceptions import ResizeScreenError, StopApplication, NextScene
import sys
import os
try:
import magic
except ImportError:
p... |
"""
A simple library of functions that provide feature importances
for scikit-learn random forest regressors and classifiers.
MIT License
Terence Parr, http://parrt.cs.usfca.edu
Kerem Turgutlu, https://www.linkedin.com/in/kerem-turgutlu-12906b65
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as p... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import frappe
import json
from frappe import _
import frappe.utils
import frappe.async
import frappe.sessions
import frappe.utils.file_manager
import frappe.desk.form.run_method
from frappe.utils.response import build_response
import datetime
from datetime... |
# codiing=utf-8
import logging
from flask import Blueprint, request, abort, g
bp = Blueprint("ws", __name__, url_prefix="/ws")
log = logging.getLogger(__name__)
@bp.before_request
def ensure_ws():
ws = request.environ.get('wsgi.websocket')
if not ws:
return abort(400)
g.ws = ws
@bp.route("")
de... |
# my_app/tests.py
from django.test import TestCase
from .models import School
class SchoolTest(TestCase):
fixtures = ["fake.json", ]
def test_average_school(self):
school = School.objects.get(id=1)
average = school.average()
# مقداری که من انتظار دارم دریافت کنم
ext_avg = "19... |
from __future__ import absolute_import, unicode_literals
from datetime import datetime, timedelta
import pytest
from case import Mock
from kombu import Exchange, Queue
from celery import uuid
from celery.app.amqp import Queues, utf8dict
from celery.five import keys
from celery.utils.time import to_utc
class test_T... |
from django.contrib.sessions.models import Session
from django.core import management
from django.core.management import BaseCommand
from django.utils import timezone
from shop.models.orders import OrderDetail
from shop.models.accounts import Company, Contact, Address
class Command(BaseCommand):
help = "Cleans s... |
import numpy as np
def make_it(x):
"""Ensures that x is an iterator.
If x is not iterable, wrap it as a one-elemened tuple.
"""
try:
return iter(x)
except TypeError:
x = (x,)
return iter(x)
@np.vectorize
def replace_nan(x, rep=np.infty):
"""Replace any nan in x with... |
#!/usr/bin/env python3
# Copyright (C) 2019-2020 All rights reserved.
# FILENAME: examples/cookies.py
# VERSION: 0.2.1
# CREATED: 2021-08-19 14:02
# AUTHOR: Aekasitt Guruvanich <[email protected]>
# DESCRIPTION:
#
# HISTORY:
#*************************************************************
from fastapi import Fast... |
# coding: utf-8
"""
Gitea API.
This documentation describes the Gitea API. # noqa: E501
OpenAPI spec version: 1.16.7
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class User(object):
"""NOTE: This class is auto gener... |
import rulr.Utils
from rulr.Utils.Event import Event
import numpy as np
import cv2
import base64
class Base(rulr.Utils.Viewable):
def __init__(self, value_or_property):
super().__init__()
self.on_set = Event()
# TODO : Needs testing if this works (so far always false which is as expected)
if no... |
from ._binarystream import _BinaryStream
from collections import OrderedDict
from struct import *
class WORLDGRAPH:
def __init__(self, stream):
self._stream = stream
self._vertices = OrderedDict()
self._edges = OrderedDict()
self._outgouingEdges = {}
self._vertexUid = 0
... |
from serpent.window_controller import WindowController
import subprocess
import shlex
import re
class LinuxWindowController(WindowController):
def __init__(self):
pass
def locate_window(self, name):
return subprocess.check_output(shlex.split(f"xdotool search --onlyvisible --name \"^{name}$... |
from PySide2 import QtWidgets
import sys
from Python.pyside2.main import Ui_Form
class MainWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.ui = Ui_Form()
self.ui.setupUi(self)
self.setWindowTitle("Learning")
if __name__ == '__main__':
... |
import numpy as np
import math
import scipy.sparse.linalg
from scipy.sparse import csr_matrix as csr
from scipy.sparse import bmat
# Class containing all the data that should be distributed per proc
class fineProc():
def __init__(self):
# Local dofs and data
self.dim = 2
self.n ... |
"""
Implementation of the OpenWeatherMap API.
"""
__author__ = '[email protected] (Ajay Roopakalu)'
OPEN_WEATHER_MAP_URL = 'http://api.openweathermap.org/data/2.5'
WEATHER_URL = '/weather'
import requests
import log
logging = log.Log(__name__)
def GetCurrentExternalWeather(app_id, city_id):
"""Get current weat... |
# This is a regression example where we calculate the slope of the correlation
# between the variable x and y
mult = lambda x, y: x * y
x = [70, 57, 63, 70, 53, 75, 58]
y = [1, 1, 1, 1, 2, 2, 1]
s = 0
for i in range(len(x)):
s += mult(x[i], y[i])
b = (s - (1/7) * 9 * 446)/(28816 - (1/7) * 446**2)
a = (1/7) * s... |
import sys
from optparse import OptionParser
from datetime import datetime, timedelta
import os
import json
from haralyzer import HarParser, HarPage
import harparser
import numpy as np
SILENCE_THRESH = 2.0
TDT = 0.95 #95th percentile of bytes cumulative
def compute_aft(path):
print("\tComputing AFT, input-video=%... |
info = {
"UNIT_NUMBERS": {
"walâ": 0,
"isá": 1,
"dalawá": 2,
"tatló": 3,
"ápat": 4,
"limá": 5,
"anim": 6,
"pitó": 7,
"waló": 8,
"siyám": 9
},
"DIRECT_NUMBERS": {
"sampû": 10
},
"TENS": {},
"HUNDREDS": {},
... |
import sys
#import nltk
import math
import time
import string
import numpy as np
import gensim
import tagger as t
import pybrain
from pybrain.datasets import supervised
from pybrain.tools.shortcuts import buildNetwork
from sklearn import svm
from sklearn.linear_model import SGDClassifier
from sklearn.linear_model im... |
# stdlib imports
import re
# third party imports
import numpy as np
import logging
from strec.subtype import SubductionSelector
def get_weights(origin, config):
"""Get list of GMPEs and their weights for a given earthquake.
Args:
origin (Origin object): ShakeMap Origin object, containing earthquake
... |
"""
Main file to calculate the embeddings with OGRE/DOGRE/WOGRE, and performing link prediction and node classification task.
In order to calculate the embedding, you first must have an edge list file:
"datasets/name_of_dataset.txt" - An edge list txt file. If the graph is unweighted it consists of 2 columns: sour... |
from setuptools import setup
setup(
name = 'mongofs',
packages = ['mongofs'], # this must be the same as the name above
version = '0.1.0.2',
description = 'Access Mongo documents in a FUSE filesystem',
author = 'Paulo Costa',
author_email = '[email protected]',
url = 'https://github.com/paulo-raca/mo... |
import torch
import re
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvision
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
from torchvision.datasets import ImageFolder
from skimage import io, transform
import string
import matp... |
"""Formal Concept Analysis concepts."""
import operator
import typing
__all__ = ['Concept',
'Infimum', 'Atom', 'Supremum']
from . import algorithms
class Pair:
"""Formal concept as pair of extent and intent."""
objects = ()
properties = ()
def __init__(self,
lattice,
... |
import requests
from ..constants import SITES_URL, USERS_URL
class SiteService:
def __init__(self, vault):
self.vault = vault
def get_sites(self):
"""
get all sites
:return: dict
"""
request_url = self.vault.base_url + SITES_URL
headers = self.vault.get... |
class CacheException(Exception):
pass
class InvalidCachePackage(CacheException):
pass
class BadLinkError(CacheException):
"""
Error raised when a symbolic link is bad.
Can also arise when the link is possibly malicious.
"""
pass
class BadPathError(CacheException):
pass |
import pytest
from pygears.typing import Uint, Ufixp, Int, Tuple, Fixp, cast
def test_ufixp_type_cast():
assert cast(Ufixp[8, 16], Uint) == Uint[8]
assert cast(Ufixp[8, 16], Uint[16]) == Uint[16]
assert cast(Ufixp[16, 8], Uint) == Uint[16]
with pytest.raises(TypeError):
cast(Ufixp[8, 16], Uin... |
from __future__ import absolute_import
from .base_datasource import DataSource
from .cuckoo_report import CuckooReport
from .darpa_tc_json import DARPATCJson
from .elasticsearch_qs import ElasticSearchQSSerach
from .fireeye_ax_report import FireEyeAXReport
from .hx_triage import HXTriage
from .memory import WindowsMem... |
from .context import BM25Summarizer, Doc, tf_context, load_raw_corpus
import numpy as np
import pytest
@pytest.mark.skip()
@pytest.mark.parametrize("tf_type, result", [('binary', np.array([0.636, 0.364])),
('raw', np.array([0.636, 0.364])),
... |
import xlrd
from itertools import product
def get_rows(filename, sheet, num_relays, relay_id):
#get num of rows
num_labels_rows = 3 -1 #it counts from 0
workbook = xlrd.open_workbook(filename)
worksheet = workbook.sheet_by_name(sheet)
num_rows = worksheet.nrows
num_clean_rows = num_row... |
if not 0:
print("zero value int is False")
if not 0.0:
print("zero value float is False")
if not None:
print("None is False")
if not '':
print("empty string is False")
if not []:
print("empty list is False")
if not ():
print("empty tuple is False")
if not {}:
print("empty dict is False... |
import logging
from abc import ABC, abstractmethod
from .coupler import NoCoupler, IdentityCoupler, coupler_map
from .coupler import AdditiveCoupler, SubtractiveCoupler, MultiplicativeCoupler
logger = logging.getLogger(__name__)
# =============================================================================
# =====... |
#!/usr/bin/env python3
import numpy as np
import rospy
import rospkg
import os
import yaml
from cv_bridge import CvBridge
import debugpy
debugpy.listen(("localhost", 5678))
from duckietown.dtros import DTROS, NodeType, TopicType, DTParam, ParamType
from sensor_msgs.msg import CompressedImage, Image
from geometry_msgs.... |
"""Unit tests for editing pre and post bash scripts, comments, etc."""
from __future__ import absolute_import
import os
import unittest
from click.testing import CliRunner
from aiida.cmdline.utils.multi_line_input import edit_pre_post, edit_comment
class TestMultilineInput(unittest.TestCase):
"""Test functions ... |
import os.path as op
from nose.tools import eq_, ok_
from flask_admin.contrib import fileadmin
from flask_admin import Admin
from flask import Flask
from . import setup
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
def create_view():
app, admin = setup()
class MyF... |
import requests
from requests_html import HTML
import time
def parse_data(html):
summary_stats = html.find(".js-post-summary-stats")
summary_content = html.find(".s-post-summary--content")
posts_lst = []
for i in range(len(summary_content)):
post_dict = {}
post_dict["votes"] = summary_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.