content stringlengths 5 1.05M |
|---|
# Lines explained at QuickNotes.txt at line 37
import torch
import torch.nn as nn
class FFN(nn.Module):
def __init__(self):
super(FFN, self).__init__()
self.l1=nn.Linear(3,6)
self.l2=nn.Linear(6,3)
self.l3=nn.Linear(3,2)
self.l4=nn.Softmax(dim=-1)
self.Activation=n... |
#!/usr/bin/env python -O
# -*- coding: utf-8 -*-
"""
# @Time : 08/07/18 10:18 PM
# @Author : ZHIMIN HOU
# @FileName: run_OffActorCritic.py
# @Software: PyCharm
# @Github : https://github.com/hzm2016
# off-policy control
"""
import argparse
import numpy as np
import os
import signal
import sys
from domains impor... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the MSIE zone settings Windows Registry plugin."""
from __future__ import unicode_literals
import unittest
from plaso.formatters import winreg # pylint: disable=unused-import
from plaso.parsers.winreg_plugins import msie_zones
from tests.parsers.winreg_pl... |
from django.contrib import admin
from django.core.exceptions import ValidationError
from django.forms import ModelForm
from django.urls import reverse
from django.utils.translation import ugettext_lazy as _
from waldur_core.core.admin import ExecutorAdminAction, PasswordWidget
from waldur_core.quotas.admin import Quot... |
"""
PyRPM
=====
PyRPM is a pure python, simple to use, module to read information from a RPM file.
"""
from collections import namedtuple
import hashlib
import re
import stat
import struct
import sys
if sys.version < '3':
try:
from io import StringIO as BytesIO
except ImportError:
from io imp... |
# Cazoo - 2021-05-13
# This code is free to use and re-distribute, but I cannot be held responsible for damages that it may or may not cause.
#####################
### sys
import json
import os
import re
import copy
from typing import List, Tuple
### Library
import nuthouse01_core as core
#import nuthouse0... |
"""
# BotSys.py
#
# Copyright (C) 2021 Christopher Stephen Rafuse <ImpishDeathTech@protonmail.ch>
# All rights reserved
#
# BSD-3-Clause
"""
import discord, sys, subprocess, time, logging, os, json, data.Token
from discord.ext import commands
from discord.errors import LoginFailure
# structure representing the bot... |
"""
Form utilities for the web app.
"""
from collections import namedtuple
from textwrap import indent, dedent
from enum import Enum, auto
class FormInputs(Enum):
STRING = auto()
TEXTAREA = auto()
NUMERIC = auto()
FILE = auto()
def get_input_elem(*args):
name, label, f_type, default = args
pi... |
#!/usr/bin/env python
#
# Inputs: Exon BED file (stranded, BED6)
# enriched bin BED file (stranded, BED6)
#
# For each enriched bin, it finds the *smallest* exon that the bin is contained by
# Then, we calculate the location of the bin relative to the 5' donor and 3' acceptor
#
# If a bin is w/in 200bp of the d... |
import string
import cognitive_face as CF
import requests
import serial
import cv2
import sys
import time
import thread
ser = serial.Serial('//dev//tty96B0', 9600)
KEY1 = '96ac51d9ccf74f258ecfc1ae8ece5e44'
KEY2 = '3a2dcc5f86fc4a8e9330c506a2573289'
CF.Key.set(KEY1)
BASE_URL = 'https://westcentralus.api.cognitive.micro... |
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
import time
from pprint import pprint
import socket
class InstagramBot:
def __init__(self, username, password, driver):
self.username = username
self.password = password
self.drive... |
from django.contrib import admin
from .models import User, InterestedIn, Organization, Role
class InterestedInInline(admin.TabularInline):
model = InterestedIn
extra = 0
@admin.register(User)
class UserAdmin(admin.ModelAdmin):
inlines = [InterestedInInline]
class RoleInline(admin.TabularInline):
m... |
import re
class Regex:
def __init__(self, pattern:str):
self.pattern = pattern
def getMatches(self, text:str):
lst = re.findall('('+self.pattern+')', text)
if lst != []:
if isinstance(lst[0],tuple):
return lst
else:
lst2 = []
... |
from .parser import parse_file, parse_path, parse_string, Parser
from . import astnodes
from .visitors import NodeVisitor, NodeTransformer
|
"""
Space : O(1)
Time : O(n)
"""
class Solution:
def minDominoRotations(self, A: List[int], B: List[int]) -> int:
ansTop, ansBot = 0, 0
revTop, revBot = 0, 0
n = len(A)
top, bot = A[0], B[0]
chainA, chainB = True, True
for i in range(1, n):
if cha... |
#!/usr/bin/env python3
import connexion
from flask_cors import CORS
from openapi_server import encoder
import os
import sys
sys.path.append(os.path.dirname(os.path.abspath(__file__))+"/../../../../ARAX/ARAXQuery")
sys.path.append(os.path.dirname(os.path.abspath(__file__))+"/../../../../reasoningtool/QuestionAnswerin... |
import ast
import metaflow as mf
from metaflow.flowspec import FlowSpecMeta
from metaflow.graph import parse_flow
from metaflow.meta import FOREACH, IS_STEP, JOIN, META_KEY, ORIG_FN, PREV_STEP
from metaflow.parameters import Parameter
from .decorators import get_meta
class StepVisitor(ast.NodeVisitor):
def __ini... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# __author__ = 'Benjamin'
from setuptools import find_packages, setup
VERSION = '0.1'
setup(
name="redfish",
version='0.1',
packages=find_packages(),
# package_data={'models': 'models.py'},
author='Benjamin',
author_email='contact@blawesom.com',
d... |
# license: Creative Commons License
# Title: Big data strategies seminar. Challenge 1. www.iaac.net
# Created by: Diego Pajarito
#
# is licensed under a license Creative Commons Attribution 4.0 International License.
# http://creativecommons.org/licenses/by/4.0/
# This script only refers to the paper-based activity. T... |
from decimal import Decimal, InvalidOperation
from typing import Any, Union
# Here even though we got __future__ annotations using FVal does not seem to work
AcceptableFValInitInput = Union[float, bytes, Decimal, int, str, 'FVal']
AcceptableFValOtherInput = Union[int, 'FVal']
class FVal(object):
"""A value to re... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2021 Chris Caron <lead2gold@gmail.com>
# All rights reserved.
#
# This code is licensed under the MIT License.
#
# 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 th... |
from .env import *
from .version import __version__
from persia import logger as logger
from persia import prelude as prelude
from persia import ctx as ctx
from persia import sparse as sparse
from persia import data as data
from persia import error as error
from persia import service as service
from persia import util... |
from dataclasses import dataclass, field
from typing import Optional
from siri.siri_utility.siri_utility_v1_1 import EmptyType
__NAMESPACE__ = "http://www.siri.org.uk/siri"
@dataclass
class AbstractTopicPermissionStructure:
"""
Type for Abstract Permission Topic.
:ivar allow: Whether the participant may... |
#!/usr/bin/env python
import hither2 as hi
import time
# Define a hither function that squares the input
# and simulates a long computation with a delay
@hi.function('sqr_with_delay', '0.1.0')
def sqr_with_delay(x, delay=None):
if delay is not None:
time.sleep(delay)
return x * x
# Create a parallel ... |
from django.contrib import admin
# Register your models here.
from .models import Category, Article
class CategoryAdmin(admin.ModelAdmin):
list_display = ('name', 'slug', 'image', 'approved')
list_filter = ('name', 'approved',)
search_fields = ('name',)
prepopulated_fields = {'slug': ('name',)}
o... |
# Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""cbuildbot logic for uploading prebuilts and managing binhosts."""
from datetime import datetime
import glob
import os
from chromite.cbuildbot imp... |
"""
Gestakomur:
Með gestakomum er átt við hve margir gestir koma til þess að gista. Hver gestur kemur aðeins einu sinni og skal aðeins teljast einu sinni þó svo hann gisti fleiri en eina nótt.
Dæmi: 2 hópar frá Austurríki koma og gista.
Hópur 1 telur þrjá gesti sem gista í fjórar nætur.
Hópur 2 telur tvo gesti sem gist... |
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
from onnx import onnx_pb
from athena.onnx import constants, util,graph
from athena.onnx.handler import athena_op
from athena.onnx.onnx_opset import general
@athena_op(["DropoutOp"],onnx_op... |
#!/usr/bin/env python3
import sys
import fire
from craterdata.mooncraterdataset import MoonCraterDataset
def download(filepath:str):
MoonCraterDataset(filepath, download=True)
sys.exit(fire.Fire(download)) |
from ndfinance.brokers.base.data_provider import DataProvider, OHLCVT
from ndfinance.analysis.technical import TechnicalIndicator
from ndfinance.brokers.base import TimeIndexer
from ndfinance.utils import array_utils
from ndfinance.brokers.base import TimeFrames, asset
from ndfinance.data.crawlers import get_yf_ticker_... |
import json
def load_config(folder):
"""
Loads the configuration file for the Canvas API and returns it.
Params:
folder (String) : The folder containing the config.
Returns:
json : The config file as a JSON object.
"""
try:
with open(f'{folder}/config.json', 'r') as f:
... |
import unittest
# these classes are imported into __init__.py
from myimports.boo import (Booger, Boogeyman, OogieBoogie)
# bookbag must be imported directly, as it is *not* defined
# in `myimports.boo.__init__.py` (it is commented out)
from myimports.boo.kbag import Bookbag
class TestImportFromModule(unittest.TestCa... |
# Dependencies
import csv
import torch
import torch.nn as nn
import torch.optim as optim
def main(channels, resize, normalization, database_path, model_LoadWeights, output_csv_file):
"""
Create .csv file with outputs from the model for corresponding patients
Args:
- channels (int) : gra... |
"""Top-level package for QUalClient."""
__author__ = """John Jamison"""
__email__ = 'john.jamison1989@gmail.com'
__version__ = '0.5'
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from numpy import log2
from copy import deepcopy
from utils import *
from . import bot_utils
from .dialog_management_components import *
from . import config as cfg
from . import entity_checker
from .actions.ActionFactory import ActionFactory
from .actions import confirm... |
"""
diff_by_one.py
Donald Knuth, Art of Computer Programming, Volume 4 Facsimile 0
Exercise #28
Find pairs of SGB word vectors that differ by +/-1 in each component.
"""
from get_words import get_words
def gen_variations(word,fragment,depth,variations):
"""
Recursive backtracking method to assemble strings
... |
"""
Test and logging script for the churn_library.py script
Author: Eugenio
Date: Feb, 2022
"""
import os
import logging
import pandas as pd
import numpy as np
import churn_library as cl
logging.basicConfig(
filename='./logs/churn_library.log',
level=logging.INFO,
filemode='w+',
format='%(name)s - %(l... |
from typing import Union
from disnake import GuildCommandInteraction
from disnake.ext.commands import (
bot_has_permissions,
BucketType,
Cog,
command,
Context,
guild_only,
max_concurrency,
slash_command,
)
from data import Utils
class Dj(Cog, name="dj.pause"):
def __init__(self, ... |
def <caret>f(x):
return 42 |
import os
from tempfile import mkstemp
try:
from unittest2 import TestCase
except ImportError:
from unittest import TestCase
from scheme import *
class TestFormat(TestCase):
def test_read_via_format(self):
fileno, filename = mkstemp()
os.write(fileno, b'{"attr": "value"}')
os.clos... |
from django.urls import path
from . import views
urlpatterns = [
# path(<url_qe_vjen_si_kerkese>, <funksioni qe do ekzekutohet>)
path(r'libra/<int:id>/', views.libra, name='libra'),
path(r'autore/<int:id>/', views.autore, name='autore'),
path(r'libratemi/', views.librat_e_mi, name='librat_e_mi'),
... |
# coding=utf-8
# Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import logging
impor... |
( WRAP_REPEAT,
WRAP_CLAMP,
WRAP_ERROR ) = list(range(3))
|
from ic_20_largest_stack_item import MaxStackDouble, MaxStackIterate
def test_max_stack_iterate_middle():
st = MaxStackIterate()
st.push(1)
st.push(3)
st.push(5)
st.push(4)
st.push(10)
st.push(4)
st.push(9)
assert st.get_max() == 10
def test_max_stack_iterate_first():
st = MaxStackIterate()
st.push(3)
... |
class ProbabilityList():
## Unlike frequency table, self.total must never change!
def __init__(self, prior):
self.prob_list = list(prior)
if len(self.prob_list) < 1:
raise ValueError('Need at least 1 symbol')
for prob in self.prob_list:
if prob < 0:
... |
"""scripts/click_types.py
Custom click parameter types and utilities.
"""
from typing import List, Any, Tuple, Dict
import pathlib
import glob
import re
import os
import string
import click
class GlobbityGlob(click.ParamType):
"""Expands a glob pattern to Path objects"""
name = 'glob'
def convert(self... |
"""CSV File IO methods."""
# builtins
import pathlib
from typing import Any
# 3d party/FOSS
import pandas as pd
# this
from afwerx_datathon.io.factory import ReaderFactory
from afwerx_datathon.io.types import DataType, PathLike
class CSVReader(ReaderFactory):
"""CSV reader concretion."""
def __init__(
... |
# MIT License
#
# Copyright (c) 2020-2021 Markus Prasser
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify,... |
import time, json, yaml, requests
class LegrandBiticinoAPI:
def __init__(self):
self.configFile = "config.yaml"
self.CONFIG = self.load_yaml()
# As a very first step let's initialise the config file
for parameter in ['client_id', 'client_secret', 'redirect_uri', 'Ocp-Apim-Subscription-Key']:
i... |
from PySide import QtGui, QtCore
class ScaledPixmapLabel(QtGui.QLabel):
"""The ScaledPixmapLabel contains a pixmap, which is correctly resized
with the label itself.
"""
def __init__(self, pixmap, *args, **kwargs):
QtGui.QLabel.__init__(self)
self._pixmap = pixmap
self.setSize... |
import yaml
from concurrent.futures import ThreadPoolExecutor, wait
from netmiko import ConnectHandler
def netmiko_show(device_dict):
net_connect = ConnectHandler(**device_dict)
prompt = net_connect.find_prompt()
return prompt
if __name__ =="__main__":
WORKERS = 10
yaml_file = "devices.yml"
with o... |
from overload.overload import overload
|
import csv
import random
file_name = "/home/jdieter/eloquent/Datasets/longturkclean.tsv"
out_file = "/home/jdieter/eloquent/Datasets/longturkclean2.tsv"
data = []
with open(file_name, 'r') as f:
csvreader = csv.reader(f, delimiter='\t')
for row in csvreader:
if not (row[1].startswith('I do not know') ... |
#! /usr/bin/env python
#
""" Combine MetaSearch and MetaURL to get data from IRSA """
import os
import numpy as np
from .metasearch import download_metadata, _test_kind_
from . import buildurl
import warnings
# This enables multiprocess downloading
from . import io
# Combining metadata with buildurl
def metatab... |
from unittest import mock
import cocrawler.config as config
def test_merge_dicts():
a = {'a': {'a': 1}}
b = {'b': {'b': 2}}
c = config.merge_dicts(a, b)
assert c == {'a': {'a': 1}, 'b': {'b': 2}}
a = {'a': {'a': 1}, 'b': {'c': 3}}
c = config.merge_dicts(a, b)
assert c == {'a': {'a': 1... |
#!/usr/bin/python
# coding: utf-8
from bs4 import BeautifulSoup
import urllib2
import time
from datetime import datetime
import sys
TODAY=datetime.today().strftime('%Y%m%d')
def getDataOnDate(dateStr):
url='http://www.cffex.com.cn/fzjy/mrhq/%s/%s/index.xml'%(dateStr[:-2],dateStr[-2:])
headers={'User-Agent':'Mozilla... |
# Copyright (c) 2019-2020 Manfred Moitzi
# License: MIT License
""" :class:`DXFEntity` is the super class of all DXF entities.
The current entity system uses the features of the latest supported DXF version.
The stored DXF version of the document is used to warn users if they use
unsupported DXF features of the curre... |
from django.contrib.auth.models import User
from image_loader.image.models import MainImage, Image
from image_loader.plan.models import UserPlan, Plan
from rest_framework.test import APITestCase
from django.urls import reverse
from django.core.files import File
class TestAPI(APITestCase):
@classmethod
def setUpTes... |
from Temporal import Temporal
class User(Temporal):
def __init__(self, display_name, start, aliases=list(), end=None):
Temporal.__init__(self, start, end)
self.display_name = display_name
self.aliases = aliases
def __str__(self):
return '<User: ' + self.display_name + '>'
... |
import numpy as np
def run(config):
lr = config["hyperparameters"]["learning_rate"]
bs = config["hyperparameters"]["batch_size"]
rpn = config["hyperparameters"]["ranks_per_node"]
return sum(config["arch_seq"]) + lr + bs + rpn
|
#!/usr/bin/env python
'''
Output the parameters that makemodel supports with their ranges
'''
import makemodel
import json, sys
from collections import OrderedDict
#extract from arguments to makemodel
opts = makemodel.getoptions()
create = 'CREATE TABLE params (rmse DOUBLE, top DOUBLE, R DOUBLE, auc DOUBLE'
#every... |
import json
import unittest2
from google.appengine.ext import testbed
from google.appengine.ext import ndb
from models.sitevar import Sitevar
from sitevars.notifications_enable import NotificationsEnable
class TestNotificationsEnable(unittest2.TestCase):
def setUp(self):
self.testbed = testbed.Testbed(... |
n, k = (int(i) for i in input().split())
fib = [0]*(n+2)
fib[0], fib[1] = 0, 1
for i in range(2, n+2):
fib[i] = fib[i-1] + fib[i-2]
if n == 1:
if k == 1:
print("0")
else:
print("1")
else:
ans = ""
for i in reversed(range(1, n+1)):
if k > fib[1+i]:
ans += "1"
... |
def mean(vals):
try :
total = sum(vals)
length = len(vals)
except TypeError :
raise TypeError("The list contained non-numeric elements.")
except :
print "Something unknown happened with the list."
return total/length
|
#! /usr/bin/env python
from ..common.device_base import Device_Base
from .device_insteon_base import Device_Insteon_Base
paddle_events = {"DON", "DON3", "DON4", "DON5", "DOF", "DOF3", "DOF4", "DOF5", "DIM", "BRT", "DFON", "DFOF", "FDUP", "FDDOWN", "FDSTOP"}
class Device_Insteon_Controller(Device_Base, Device_Inste... |
# This file is a DRAFT of a generic implementation. IT SHOULD NOT BE USED AS A REFERENCE
from multiprocessing import Manager as IPCManager
from glycan_profiling.chromatogram_tree import Unmodified
from glycan_profiling.task import TaskBase
from .temp_store import TempFileManager, SpectrumMatchStore
from .spectrum_... |
# coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import HEADRequest
class ThisOldHouseIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?thisoldhouse\.com/(?:watch|how-to|tv-episode|(?:[^/]+/)?\d+)/(?P<id>[^/?#]+)'
_TESTS = [{
'url': 'https://ww... |
import cv2
import numpy as np
import glob
import os
import argparse
def get_noise(img, value=10):
'''
#生成噪声图像
value= 大小控制雨滴的多少
'''
noise = np.random.uniform(0, 256, img.shape[0:2])
# 控制噪声水平,取浮点数,只保留最大的一部分作为噪声
v = value * 0.01
noise[np.where(noise < (256 - v))] = 0
# 噪声做初次模糊
k ... |
#Utility to redirect the output to a text widget
#(from http://stackoverflow.com/)
#Modified by G.Vianello (giacomov@slac.stanford.edu)
import subprocess
import sys
import threading
import re
from tkinter import *
from time import localtime, strftime
import getpass
from GtBurst.HyperlinkManager import HyperlinkManager
... |
"""Robot OpenCV and Controller Script
Retrieve camera information from stream (expected from raspicam.py)
Applies OpenCV algorithms through video stills
Sends OpenCV results to the rc controller via http call (server.js)
Receives robot commands from http call result
Set the controller location with --server <ADDRESS>... |
from os import listdir
from os.path import isfile, join
from typing import List
def find_translation(path: str, prefix: str, postfix: str) -> List[str]:
return [
f[len(prefix) : -len(postfix)]
for f in listdir(path)
if f.startswith(prefix)
and f.endswith(postfix)
and isfile... |
# encoding: utf-8
from __future__ import division, absolute_import, with_statement, print_function
from flask import Blueprint
setting_bp = Blueprint('setting', __name__)
from . import views
|
"""Test suite for the punter library."""
import pytest
import punter.exceptions as exc
from punter.api import search
from punter.helpers import get_query_type, get_endpoint
class TestQueryType(object):
def test_query_type_email_valid(self):
emails = [
'johndoe@gmail.com',
'john.... |
import bokeh.layouts as bkl
import bokeh.plotting as bkp
from bokeh.io import export_png, export_svgs
import numpy as np
import sys,os
#make it so we can import models/etc from parent folder
sys.path.insert(1, os.path.join(sys.path[0], '../bayesian-coresets-private/examples/common'))
from plotting import *
size_x_axis... |
'''
Created on Jul 1, 2018
@author: Burkhard A. Meier
'''
# module imports
import turtle
our_turtle = turtle.Turtle() # save turtle instance in local variable
our_turtle.color('blue') # set color to blue
our_turtle.hideturtle() # hide the turtle
for _draw in range(20):
our_tur... |
#!/router/bin/python
import os
import sys
def add_root_to_path ():
"""adds trex_control_plane root dir to script path, up to `depth` parent dirs"""
root_dirname = 'trex_control_plane'
file_path = os.path.dirname(os.path.realpath(__file__))
components = file_path.split(os.sep)
sys.pa... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
import phenox as px
if __name__ == "__main__":
led_target = px.PX_LED_RED
#led_target = px.PX_LED_GREEN
led_is_on = False
while True:
time.sleep(1.0)
px.set_led(led_target, led_is_on)
led_is_on = not led_is_on
|
from typing import List
from ingest.importer.conversion.template_manager import TemplateManager
from ingest.importer.submission.entity import Entity
from ingest.importer.submission.entity_map import EntityMap
from ingest.importer.submission.errors import LinkedEntityNotFound, InvalidLinkInSpreadsheet, MultipleProcesse... |
# -*- coding: utf-8 -*-
__author__ = "Rajesh"
import pandas as pd
import urllib.request
import json
dList = []
for i in range(1,10):
print (i)
url = 'https://api-v2.themuse.com/jobs?location=MD&page='
url = url + str(i)
try:
req = urllib.request.Request(url, headers={'content-... |
import matplotlib.pyplot as plt
from celeba_datagen import genxyclz
anno_file_path = 'anno/celeba_train1_anno.txt'
img_dir_path = '../datasets/CelebA/img_align_celeba/'
ishape = [140, 128, 3]
total_examples = 25000 # 3000
batch_size = 1000
total_batches = total_examples//batch_size
gen = genxyclz(
anno_file_path=an... |
"""Define the `function` function
"""
__docformat__ = "restructuredtext en"
import sys, traceback, logging
_logger = logging.getLogger('theano.compile.function')
from io import In
from function_module import orig_function
from profiling import ProfileStats
from pfunc import pfunc
from numpy import any #for to work in... |
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 13 20:12:38 2019
@author: Rozan
"""
import matplotlib
import numpy as np
import pandas as pd
from scipy.sparse import csr_matrix, hstack
from sklearn.ensemble import RandomForestRegressor
from sklearn.feature_extraction.text import CountVectorizer
matplotlib.style.us... |
import pickle
from logging import getLogger
from os import environ as env
from os import path
from mr_owlf_mls.service.process import Process
from pymongo import MongoClient
from service import database
DB_NAME = env.get('APP_DB_NAME', 'mr-owlf-db')
CLF_FILE = env.get('APP_CLF_FILE', '../tmp/classifier.pkl')
VECTORI... |
""" Made by Shadofer#7312, left until further notice on dogehouse's future. """
""" BUILT-IN MODULES """
""" General asynchronous functionality. """
import asyncio
from asyncio.events import AbstractEventLoop
""" Formatting/Dumping responses. """
from json import dumps, loads
""" Type-checking. """
from typing imp... |
"""
A control model to test whether the models I have developed create any improvement in accuracy
"""
import torch.nn as nn
import torch
import torch.optim as optim
from torchvision import datasets
from torchvision.transforms import ToTensor
from torch.utils.data import DataLoader, random_split
import time
import tor... |
"""Data"""
import logging
import os
from emmental import Meta
from emmental.data import EmmentalDataLoader, emmental_collate_fn
from torch.utils.data import DistributedSampler, RandomSampler
from bootleg import log_rank_0_info
from bootleg.data import bootleg_collate_fn
from cand_gen.dataset import CandGenContextData... |
'''
An example from the textbook "Python: Visual QuickStart Guide"
A collection of functions for printing simple shapes
'''
CHAR = '*'
def rectangle(height,width):
"""
this function prints a rectangle
:param height: the height of the rectangle
:param width: the width of the rectangle
:return: None... |
"""
Admin controllers for the Administrators module.
This file is subject to the terms and conditions defined in file 'LICENSE',
which is part of this source code package.
"""
# pylint: disable=no-member
from datetime import datetime
from flask import jsonify, abort, request
from marshmallow import ValidationError
... |
'''
This code is due to Yutong Deng (@yutongD), Yingtong Dou (@Yingtong Dou) and UIC BDSC Lab
DGFraud (A Deep Graph-based Toolbox for Fraud Detection)
https://github.com/safe-graph/DGFraud
'''
import tensorflow as tf
import argparse
from algorithms.GEM.GEM import GEM
from algorithms.GeniePath.GeniePath import GeniePat... |
# Generated by Django 2.2.4 on 2020-03-26 03:47
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Station',
fields=[
('id', models.AutoField(... |
#!/usr/bin/env python3
import argparse
import sys
import Cerbrutus
banner = """
\t================================================================
\t __ ___ ____ ____ ____ __ __ ______ __ __ _____
\t / ] / _]| \ | \ | \| | || || | |/ ___/
\t / / / [_ | D )| o )| ... |
import os
import unittest
from data import city_visit
from data import point
from data import read_csv
from ranker import point_type_rank_adjuster
from ranker import rank_adjuster_interface
from ranker import test_util
class PointTypeRankAdjusterTest(test_util.RankAdjusterTestUtils):
def setUp(self):
self.p... |
""" Test stimuli module
Run tests with::
py.test test_stimuli.py
"""
import os
import numpy as np
import numpy.testing as npt
from nipraxis import stimuli
# Example onset, duration, amplitude triplets
COND_TEST = """\
10 6.0 1
20 4.0 2
24 2.0 0.1"""
# Name of file to write for testing
COND_... |
# This file is Copyright (c) 2020 Gregory Davill <greg.davill@gmail.com>
# License: BSD
from migen import *
from litex.soc.interconnect.stream import Endpoint
class VideoStream(Module):
def __init__(self):
# VGA output
self.red = red = Signal(8)
self.green = green = Signal(8)
s... |
# deforder.py
# contains all the default orders, also called deforders
# deforders are executed directly, there is no need to worker.hear()
class Deforders:
def __init__(self, target, **kwargs):
# kwarg handling
"""
Deforder constructor
Args:
target (discord.etc) : the channel or guild that ... |
"""
Documentation https://developers.facebook.com/docs/messenger-platform/implementation#send_message
https://developers.facebook.com/docs/messenger-platform/send-api-reference#request
"""
from models import SendMessageModel, Element, Button
from .enums import ResponseType
import jsonpickle
import json
import os
impor... |
#!/usr/bin/env python
# Run this to simulate pressing the pair button on Solo.
import struct
import sys
button_filename = "/dev/input/event0"
button_error = False
button_file = None
# event is:
# struct input_event {
# struct timeval time;
# unsigned short type;
# unsigned short code;
# un... |
import requests
import urllib.request
import time
from bs4 import BeautifulSoup as Soup
PUZZLE_URL="https://www.npr.org/series/4473090/sunday-puzzle"
def scrape(url=PUZZLE_URL, puzzles=None):
response = requests.get(url)
soup = Soup(response.text, "html.parser")
return soup.findAll("div", {"class": "i... |
import json
import sys
exclude = {'','',''}
visited = []
queue = []
WEXEA_DICT_PATH = '<path to WEXEA dictionaries>'
ENTITY_TYPE = "FOOD"
CATEGORY = "Category:Food and drink"
#CATEGORY = "Category:Drugs"
def bfs(visited, hierarchy,root):
keep = {}
rules = []
visited.append(root)
queue.append(root... |
#!/usr/bin/env python
# coding: utf-8
# ## Script takes data from GitHup repository .csv
import datetime
data = datetime.datetime.now()
data1 = data.strftime("%d-%m-%Y %H:%M:%S")
import pandas as pd
url = 'https://raw.githubusercontent.com/pcm-dpc/COVID-19/master/dati-andamento-nazionale/dpc-covid19-ita-andamento-naz... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.