content stringlengths 5 1.05M |
|---|
from rest_framework import serializers
from .models import *
from tno.models import Proccess, CustomList, Catalog
from orbit.models import OrbitRun
import humanize
from django.utils import timezone
from django.conf import settings
import urllib.parse
from datetime import datetime
class PredictRunSerializer(serializer... |
r"""Inference method base class."""
import abc
import argparse
from typing import ClassVar, Dict, Optional
import torch
from lmp.model import BaseModel
from lmp.tknzr import BaseTknzr
class BaseInfer(abc.ABC):
r"""Inference method abstract base class.
All inference methods must inherit :py:class:`lmp.infer... |
import os, sys
import json
import csv
import collections
import random
from pprint import pprint
from playsound import playsound
import datetime
from six import string_types
from boto3 import Session
from botocore.exceptions import BotoCoreError, ClientError
from contextlib import closing
from pollySpeak import newSess... |
import math
import sys
import itertools
import itertools
import collections
def sa(Type= int):
return [Type(x) for x in input().split()]
def solve(t):
n = int(input())
s = input()
cc = collections.defaultdict(int)
for i in range(len(s)-1):
cc[s[i:i+2]] += 1
result = max(cc.items(), key= lambda x: x... |
# Copyright (c) ZenML GmbH 2022. 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:
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... |
# -*- coding: utf-8 -*-
"""
Geometrical imaging equations, Paraxial optical calculations
"""
import numpy as np
import scipy.constants as const
# Need to clarify some of these functions
#could break into newton imaging equations and gaussian imaging equations.
#newtons were derived in 1666 using similar triangles,... |
from .listing import Listing
from .details import Detail
from .details import EditDetails
from .details import remove_job
|
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl
MARKET_VALUE = float(input("Enter Market Value: "))
MARKET_VALUE = MARKET_VALUE / 1000
LOCATION = float(input("Enter House Location: "))
PERSONAL_ASSET = float(input("Enter Asset Value: "))
PERSONAL_ASSET = PERSONAL_ASSET / 1000
P... |
import json
import os
import cv2
import torch
import sys
from Detected import Image_Processor
from Datasets_BFDF import get_dataloader
import numpy as np
mask_model = "MODEL/pose2seg_release.pkl"
keypoints_model = "COCO-Keypoints/keypoint_rcnn_R_101_FPN_3x.yaml"
P = Image_Processor(mask_model, keypoints_mod... |
import chex
import jax
import jax.numpy as jnp
from typing import Callable, Optional, Tuple
from .moment import MomentTransform
from .unscented import UnscentedTransform
from chex import Array, dataclass
from scipy.special import factorial
from sklearn.utils.extmath import cartesian
from numpy.polynomial.hermite_e impo... |
def is_armstrong_number(number):
exp = len(str(number))
digits = [int(d) ** exp for d in str(number)]
return number == sum(digits)
|
lostFights=int(input()); helmetPrice=float(input()); swordPrice=float(input()); shieldPrice=float(input()); armorPrice=float(input())
every2ndGame=2; every3rdGame=3; brokenShieldTimes=0; expenses=0
brokenHelmet=False; swordBroken=False
for k in range(1,lostFights+1):
if k==every2ndGame:
brokenHelmet=Tr... |
#!/usr/local/bin/python
# Code Fights Spiral Numbers Problem
def spiralNumbers(n):
r, c = 0, 0 # Starting location
# Delta for row or column increments: first direction is left to right
dr, dc = 0, 1
spiral = [[0] * n for _ in range(n)]
for i in range(1, n * n + 1):
spiral[r][c] = i
... |
import geopandas as gpd
from sqlalchemy import create_engine
vineyards_query = open("sql/vineyards.sql").read()
all_classes_query = open("sql/all_classes.sql").read()
engine = create_engine('postgresql://test_user:test_user@172.17.0.2:5432/test_user')
gdf = gpd.GeoDataFrame.from_postgis(vineyards_query, engine)
gdf.... |
def all_productions(productions):
all_productions = [i for i in productions.values()]
_productions = []
for p in all_productions:
_productions += p
return _productions
|
class SessionHelper:
def __init__(self, app):
self.app = app
def login(self, user):
wd = self.app.wd
self.app.open_auth_form()
wd.find_element_by_id("user_login").click()
wd.find_element_by_id("user_login").clear()
wd.find_element_by_id("user_login").send_key... |
import numpy as np
import openmdao.api as om
class AerodynamicHeating(om.ExplicitComponent):
"""
Defines the Aerodynamic heating equations for the shuttle reentry problem.
References
----------
.. [1] Betts, John T., Practical Methods for Optimal Control and Estimation Using Nonlinear
... |
# file: calc.py
def calc():
hint = '''
'?' - help
'*' - multiplication. Ex.: x * y
'/' - division. Ex.: x / y
'+' - addition. Ex.: x + y
'-' - subtraction. Ex.: x - y
'**' - exponentiation. Ex.: x ** y
'()' - prioritization. Ex.: (x + y) * z
'%' - remainder of division. Ex.: x % y
'//' - obtaining the integer part... |
"""
analysis_view
~~~~~~~~~~~~~
The view for the analysis panel.
"""
import tkinter as tk
import tkinter.ttk as ttk
import tkinter.messagebox
import datetime
from . import util
from .. import funcs
from . import mtp
from . import tooltips
from . import date_picker
from open_cp.gui.common import CoordType
import open_... |
import RPi.GPIO as GPIO
import binascii
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(12, GPIO.OUT)
GPIO.setup(16, GPIO.OUT)
GPIO.setup(5, GPIO.OUT)
GPIO.setup(6, GPIO.OUT)
GPIO.setup(13, GPIO.OUT)
GPIO.setup(19, GPIO.OUT)
pin = [12, 16, 5, 6, 13, 19]
k = 0
st="110101011010111"
cols = 6
rows = len(st)/3
arr = [[0]*... |
#!/usr/bin/env python3
"""
@author: MD.Nazmuddoha Ansary
"""
from __future__ import print_function
from termcolor import colored
#--------------------------------------------------------------------------------------------------------------------------------------------------
import argparse
parser = argparse.ArgumentP... |
# Given an array arr[] of size N containing positive integers and an integer X, find the element in the array which is smaller than X and closest to it.
# https://practice.geeksforgeeks.org/problems/find-immediate-smaller-than-x/0/
# time is O(n) | space is O(1)
def immediateSmaller(arr, n, x):
smallest = -1
... |
# coding=utf-8
"""
Implement a selection of EWS services (operations).
Exchange is very picky about things like the order of XML elements in SOAP requests, so we need to generate XML
automatically instead of taking advantage of Python SOAP libraries and the WSDL file.
Exchange EWS operations overview:
https://doc... |
# Generated by Django 3.0.3 on 2020-11-14 14:41
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('post', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='post',
name='date',
... |
##############################################################################
# Copyright 2009, Gerhard Weis
# 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 ... |
##############################################
# The MIT License (MIT)
# Copyright (c) 2014 Kevin Walchko
# see LICENSE for full details
##############################################
# this directory contains things for testing and fake sources
# import pygecko.test.fake_camera as cv2
# from pygecko.test.process impo... |
from add_vhost_4.Guessers.Posix_Guesser import Posix_Guesser
import os
import subprocess
class DebianLikeVHostEntry:
def __init__(self, vhost_desired):
self.vhost_desired = vhost_desired
self.guesser = Posix_Guesser()
self.vhost_file_entry = self.guesser.guess_debian_like_vhost_file(self.v... |
# encoding: UTF-8
import os
from vilya.models.project import CodeDoubanProject
from vilya.models.pull import PullRequest
from tests.base import TestApp
from mock import patch
import tests
from tests.base import TestCase
from tests.utils import clone, mock_method
data_path = os.path.join(os.path.dirname(tests.__file... |
import json
import os
import re
from typing import Union, Optional
import requests
from catcher.steps.step import Step, update_variables
from catcher.utils.logger import debug, warning
from catcher.utils.misc import fill_template, fill_template_str
from catcher.utils import file_utils
class Http(Step):
"""
... |
import os
import unittest
import test_data.test_static
from jivago.wsgi.routing.serving.static_file_routing_table import StaticFileRoutingTable
FILENAME = "foobar.html"
class StaticFileRoutingTableTest(unittest.TestCase):
def setUp(self):
self.routing_table = StaticFileRoutingTable(os.path.dirname(test... |
def build_network_trivial2(config, input_var=None):
from lasagne.layers import InputLayer, DenseLayer
from lasagne.nonlinearities import rectify, softmax
import lasagne
network = InputLayer(shape=(None, config.img_colors, config.img_size, config.img_size), input_var=input_var)
network = DenseLayer... |
import networkx as nx
from ged4py.algorithm import graph_edit_dist
g1 = nx.Graph()
g1.add_edge("A", "B")
g1.add_node("C", weight=1)
g2 = g1.copy()
g1.add_edge("A", "C")
ged = graph_edit_dist.compare(g1, g2, print_details=True, normalized=False)
print(ged)
############################################
# g1 = nx.Grap... |
# File: splunk_views.py
#
# Copyright (c) 2014-2022 Splunk 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 appli... |
description = 'MHG humidity generator'
group = 'optional'
tango_base = 'tango://phys.kws3.frm2:10000/kws3/'
devices = {
'mhg_flowrate': device('nicos.devices.tango.WindowTimeoutAO',
description = 'Flow rate through humidity cell',
tangodevice = tango_base + 'mhg/flowrate',
fmtstr = '%.1f'... |
# ZC's common list!
# https://leetcode.com/problems/remove-nth-node-from-end-of-list/submissions/
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution_single_pass:
def removeNthFromEnd(self, head: ListNode, n: ... |
import markdown
class MathJaxPattern(markdown.inlinepatterns.Pattern):
def __init__(self):
markdown.inlinepatterns.Pattern.__init__(self, r'(?<!\\)(\$\$?)(.+?)\2')
def handleMatch(self, m):
node = markdown.util.etree.Element('mathjax')
node.text = markdown.util.AtomicString(m.group(2)... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import torch
DEBUG_DATASETS = ['Debug28', 'Debug224']
def make_minibatches(dataset, batch_size):
"""Test helper to make a minibatches array like train.py"""
minibatches = []
for env in dataset:
X = torch.stack([env[i][0] for i... |
from src.plotting.utils import functions as func
def test_fetch_columns_options():
data = [{"col1": ["row1", "row2"], "col2": ["row1", "row2"]}]
# column option dropdown
expected = [{"label": "col1", "value": "col1"}, {"label": "col2", "value": "col2"}]
output = func.fetch_columns_options(data)
... |
from quickdraw import QuickDrawData
qd = QuickDrawData()
print(qd.drawing_names) |
from base import Base
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.orm import relationship
class m_GroupMachine(Base):
__tablename__ = 'm_GroupMachine'
groupId = Column(String(16), primary_key=True)
name = Column(String(32), nullable=False) |
from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated
from api.models import Todo
from api.serializers import TodoSerializer
class TodoViewSet(viewsets.ModelViewSet):
serializer_class = TodoSerializer
queryset = Todo.objects.all()
permission_classes = (IsAuthenticated,... |
from qiskit import QuantumCircuit, execute, Aer
from math import pi
import numpy as np
import random
import matplotlib.pyplot as plt
from matplotlib import cm
def plot_height(height,color_map='terrain'):
# note that this function produces an image, but does not return anything
Lmax = max(max(height.keys()))+... |
from components.datasets import get_dataset
from components.log import logger
from components.config import Config
if __name__ == '__main__':
datasets = {
# 'Kalantari',
# 'Stanford',
'EPFL',
}
for ds in datasets:
logger.info("Start to prepare %s dataset." % ds)
dat... |
import os
import torch.nn as nn
import torch
from torchvision import models
os.environ['TORCH_HOME'] = 'models'
# alexnet_model = models.alexnet(pretrained=True)
mobilenet_v3l_model = models.mobilenet_v3_large(pretrained=True)
resnet50_model = models.resnet50(pretrained=True)
# class AlexNetPlusLatent(nn.Module):
# ... |
# -*- coding: utf-8 -*-
import scrapy
from scrapy.loader import ItemLoader
from datetime import datetime
from urllib.parse import urlparse
from crawler.items import PatentItem
class PatentSpider(scrapy.Spider):
name = 'patent'
allowed_domains = ['justia.com']
start_urls = ['https://patents.justia.com/assi... |
__author__ = 'Shayan Fazeli'
__email__ = 'shayan@cs.ucla.edu'
"""
Plauthor: Distribution Plots
==========
The modules in this file are designed to assist the user in plotting the distribution-related scatter plots
and other variants of graphics demonstration, shedding light on how the data points are located in the s... |
"""
Message notification and handling.
This file is part of the everest project.
See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information.
Created on Nov 24, 2011.
"""
from everest.entities.system import UserMessage
from everest.interfaces import IUserMessage
from everest.interfaces import IUserMes... |
# Generated by Django 2.1.7 on 2020-05-13 20:28
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('server', '0004_auto_20200419_0748'),
]
operations = [
migrations.AlterField(
model_name='settin... |
'''
"Node discovery". *Hack*
This implementation of p2p node discovery takes
advantage of docker and information sharing through
environment variables. REAL discovery should probably happen
through DNS.
'''
# returns a list of node addresses
def discoverNodes():
import os
import random
numNodes... |
# Copyright 2017 The TensorFlow 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 applica... |
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... |
from __future__ import division
import numpy as np
import argparse
import matplotlib.pyplot as plt
plt.switch_backend('agg')
import pickle
import gzip
import time
import tkinter as tk
from env.cross import crossing
# from visual import Visual
import tensorflow as tf
np.set_printoptions(threshold=np.inf)
class Traff... |
"""
adbwp.message
~~~~~~~~~~~~~
Object representation of a message.
"""
import collections
import typing
from . import consts, enums, exceptions, header, hints, payload
__all__ = ['Message', 'new', 'from_header', 'connect', 'auth_signature', 'auth_rsa_public_key',
'open', 'ready', 'write', 'cl... |
from .common import MEDIAWIKI_API_URL
from rdfsync.wb2rdf.conversion import Converter
import pytest
converter = Converter(endpoint=MEDIAWIKI_API_URL, input_format='ttl')
wikibase_id = 'Q5'
def test_wrong_params_in_constructor():
with pytest.raises(ValueError):
Converter(endpoint=MEDIAWIKI_API_URL, day_nu... |
# ░░░░░░░░░░░░░░░░░░░░░░░
# ░░░░░▄▀▀▀▄░░░░░░░░░░░░░
# ▄███▀░◐░░░▌░░░░░░░░░░░
# ░░░░▌░░░░░▐░░░░░░░░░░░░
# ░░░░▐░░░░░▐░░░░░░░░░░░░
# ░░░░▌░░░░░▐▄▄░░░░░░░░░░
# ░░░░▌░░░░▄▀▒▒▀▀▀▀▄░░░░░
# ░░░▐░░░░▐▒▒▒▒▒▒▒▒▀▀▄░░░
# ░░░▐░░░░▐▄▒▒▒▒▒▒▒▒▒▒▀▄░
# ░░░░▀▄░░░░▀▄▒▒▒▒▒▒▒▒▒▒▀▄
# ░░░░░░▀▄▄▄▄▄█▄▄▄▄▄▄▄▄▄▄▄▀▄
# ░░░░░░░░░░░▌▌░▌▌░░░░░░░
# ░░░... |
from app.config import config
def allowed_file(filename):
"""Checking the downloaded file for a valid extension"""
return '.' in filename and \
filename.rsplit('.', 1)[1].lower(
) in config['APP']['ALLOWED_FILE_TO_PREVIEW']
|
# Generate some data and write to CSV.
#
# Stanley H.I. Lio
# hlio@hawaii.edu
import numpy as np
t = np.arange(0.0,2.0,0.05)
s = 1 + np.sin(2*np.pi*t)
with open('data.csv','w') as f:
for p in zip(t,s):
f.write('{},{}\n'.format(*p))
|
import io
import unittest
from contextlib import redirect_stdout
from unittest.mock import patch
class TestQ(unittest.TestCase):
@patch('builtins.input', side_effect=[
'2',
'4',
'hey',
'rain',
'day',
'wet',
'draaxiny',
'4',
'bump',
'u... |
from flask_bcrypt import generate_password_hash, check_password_hash
from .db import db
class Movie(db.Document):
name = db.StringField(required=True, unique=True)
casts = db.ListField(db.StringField(), required=True)
genres = db.ListField(db.StringField(), required=True)
added_by = db.ReferenceField... |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
from awscrt import io, mqtt, auth, http
from awsiot import mqtt_connection_builder
import time as t
import json
import awsyy
CONST_ADVERT_PATH = "./advertisements/"
CONST_AD_BUCKET_NAME = "iot-fastgame-proj-ads"
# D... |
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse
from django.urls import reverse
from .models import Song
from django.views.generic import ListView, DetailView
from rest_framework import viewsets
from .api.serializer import SongSerializer
# Create your views here.
class Song... |
# for Coverage
from mock import patch, MagicMock
class TestAll:
def setup(self):
pass
# setup() before each test method
def teardown(self):
pass
# teardown() after each test method
@classmethod
def setup_class(cls):
pass
# setup_class() before any meth... |
import os
def check_curses():
import subprocess, sys
try:
import curses
except:
subprocess.check_call([sys.executable, "-m", "pip", "install", 'windows-curses'])
import curses
try:
import curses
except:
check_curses()
def cls():
os.system('cls' if os.name == 'nt' else '... |
# coding=utf-8
words = [u",",u"safasf"]
a = {u",", u"。", u"”", u"“", u"(", u")", u"(", u")", u"!", u"?", u" "}
print set(words)-a |
#!/usr/bin/env python
"""
Copyright (C) 2006 Google 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 agree... |
from . import survey_result # noqa
|
db_password = 'Sql1965#' |
# Rgb driver for either led strips based on
# the ws2812b (also sold as neopixels) and respective strips
#
# author: ulno
# created: 2017-05-22
#
import gc
import neopixel
gc.collect()
from uiot._rgb_base import RGB_Base
from uiot import colors as _c
gc.collect()
class RGB_Multi(RGB_Base):
def __init__(self, n... |
# Author: bbrighttaer
# Project: jova
# Date: 10/24/19
# Time: 9:30 AM
# File: tb.py
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import collections
import torch
import numpy as np
# From PTan
class TBMeanTracker... |
# iodata.py
# Contact: Tetsuya Yamada <tetsuyamada1222@gmail.com>
"""
"""
import os
from pathlib import Path
import pickle
import numpy as np
import pandas as pd
def load_data(path, prefecture, metrics, period):
""" Returns data for particular metrics during designated period in a prefecture.
Parameters
... |
from touhou_calendar import days_for, format_twitter, format_discord_embed, format_upcoming_twitter, format_upcoming_discord_embed
import json
import os
import sys
import logging
import datetime
import argparse
from urllib.parse import urlparse
import redis # We're webscale now.
logging.basicConfig()
parser = argpar... |
'''
Created on Oct, 2017
@author: hugo
'''
import argparse
from core.build_data.webquestions import *
parser = argparse.ArgumentParser()
parser.add_argument('-fb', '--freebase_path', required=True, type=str, help='path to the freebase data')
parser.add_argument('-mid2key', '--mid2key_path', required=True, type=str, ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
import sys
import six
if six.PY2:
# to evade UnicodeDecodeError on plistlib.writePlist
reload(sys)
sys.setdefaultencoding('utf-8')
import argparse
import shutil
import os.path
from yamlfred.utils import TemporaryDirectory
... |
# api/core/auth.py
from flask import g, make_response, jsonify
from flask.ext.restful import abort
from .setup import auth
from ..models import User
@auth.verify_password
def verify_password(username_or_token, password):
u = User.verify_api_key(username_or_token)
if not u:
u = User.by_email(username_... |
import json
from os.path import expanduser
import sys
DEFAULT_JENKINS_CONFIG = expanduser('~/.config/jenkins/config.json')
class Config:
def __init__(self, path=DEFAULT_JENKINS_CONFIG):
self.path = path
self._config = {}
self._read_config()
def _read_config(self):
with open(... |
#!/usr/bin/env python3
#
# pico.workflow.blackboard - Defines the blackboard passed between services.
#
# The blackboard essentially is a dict with some convenience wrappers to ease
# getting and putting values in the dict using 'paths'. E.g. to add a value
# to a list element, use add_to_list('path/to/elem', va... |
import re
from emmet.node import Attribute, Element, Text
class Parser:
"""
Parser which extracts patterns from emmet abbreviations.
Each "extract" method accepts a "tap" callback as a parameter, which will be called
with the result of the parse, only if there was a match. The type of the parse
... |
import re
class DBPedia(object):
# These correspond to labels that have been misrecognized
BLACKLIST_URIS = {"http://dbpedia.org/resource/Glossary_of_tennis_terms",
"http://dbpedia.org/resource/Good_Movie",
"http://dbpedia.org/resource/Sierra_Entertainment",
"http://dbpedia.org/resource/Nice",
... |
from abc import ABCMeta
from collections import defaultdict
from typing import Dict, Optional, Union
from pydantic import BaseModel
class BaseConfig(BaseModel):
"""Basic configuration data class
"""
@classmethod
def from_dict(cls, dic: Dict) -> "BaseConfig":
return cls(
**dic
... |
from setuptools import setup, find_packages
setup(
name='django_neomodel',
version='0.0.4',
description='Use Neo4j with Django!',
long_description=open('README.rst').read(),
author='Robin Edwards',
author_email='robin.ge@gmail.com',
zip_safe=True,
url='http://github.com/robinedwards/dja... |
import numpy as np
from ...bandit import Bandit
from .base import BanditPolicy
class GradientPolicy(BanditPolicy):
"""
Multi-Armed Bandit Solver with Softmax Action Selection Strategy.
Refer to Section 2.8 of Reinforcement Learning: An Introduction.
:param bandit: The Bandit to solve
:param alp... |
from .simplex import Simplex
__version__ = "0.2.0"
__author__ = "Romain Muller <oprax@me.com>"
__all__ = ["Simplex", "__version__", "__author__"]
|
#$ python q7.py
k = 1
ninc= 0 #non-increasing numbers
ratio = 1.0
while ratio >= 0.001:
temp = k
while temp > 9: #Non-increase control start
if (temp%10) > ((temp/10)%10):
break
temp/=10
if temp < 10:
ninc += 1 #Non-increase control finish
k+=1
r... |
import torchvision
import cv2
import numpy as np
class GaussianBlur:
def __init__(self, kernel_size, min=0.1, max=2.0):
self.min = min
self.max = max
self.kernel_size = kernel_size
def __call__(self, sample):
sample = np.array(sample)
prob = np.random.random_sample()
... |
from scriba.settings.base import *
ENVIRONMENT = 'production'
DEBUG = True
ALLOWED_HOSTS = [
'178.128.41.130',
'englishapp.tk',
'www.englishapp.tk',
'scriba-prod.eu-west-2.elasticbeanstalk.com'
]
SESSION_COOKIE_SECURE = True
SESSION_COOKIE_HTTPONLY = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDE... |
'''
Created on 25-01-2011
@author: fearless-spider
'''
import csv
listing = csv.reader(open('south-dakotacat.csv', 'rb'), delimiter='^', quotechar='~')
catlisting = csv.reader(open('category.csv', 'rb'), delimiter='^', quotechar='~')
categoryWriter = csv.writer(open('categorynew.csv', 'wb'), delimiter='^', quotechar=... |
#!/usr/bin/env python3
""" Collection of shared color handling functions and constants """
import debugging
import conf
def rgb2hex(rgb):
"""Convert RGB to HEX"""
debugging.dprint(rgb)
(red_value, green_value, blue_value) = rgb
hexval = "#%02x%02x%02x" % (red_value, green_value, blue_value)
retur... |
import subprocess
from pathlib import Path
from typing import Optional, List
from fire import Fire
class PrepDrNMTData:
def __init__(self, data_dir: str,
pretrained_model_name: str,
beam_sizes: Optional[List[int]] = None,
num_shards: Optional[List[int]] = None):... |
import os
root_path = os.path.dirname(os.path.dirname(__file__))
def load_keywords():
collector = set()
for filename in os.listdir(os.path.join(root_path, "keywords")):
if filename.startswith("."):
continue
fr = open(os.path.join(root_path, "keywords", filename), "r")
for ... |
from foxtrot.models.missions.triggers.boolean import BooleanTrigger
from foxtrot.models.missions.triggers.frame import FrameTrigger
from foxtrot.models.missions.triggers.population import PopulationTrigger
from foxtrot.models.missions.triggers.room import RoomTrigger
|
# -*- coding: utf-8 -*-
import inlineplz.linters.jsonlint as jsonlint
def test_jsonlint():
input = [
("21.json", "21.json: line 1, col 25, found: ',' - expected: ':'."),
(
"25.json",
"25.json: line 1, col 1, found: 'INVALID' - expected: 'STRING', 'NUMBER', 'NULL', 'TRUE', ... |
from flask import (
Blueprint
)
from myflaskapp.posts.resources import posts
blueprint = Blueprint("posts", __name__, static_folder="../static")
blueprint.add_url_rule('/create_post', view_func=posts.create_post, methods=['POST'])
blueprint.add_url_rule('/get_posts', view_func=posts.get_posts, methods=['GET'])
|
# Copyright (c) 2020 KU Leuven
import sparsechem as sc
import scipy.io
import scipy.sparse
import numpy as np
import pandas as pd
import torch
import tqdm
import sys
import argparse
from torch.utils.data import DataLoader
from scipy.special import expit
from collections import OrderedDict
parser = argparse.ArgumentPar... |
import pytest
import requests
from webdriver_manager.chrome import ChromeDriverManager
def test_use_proxy():
session = requests.Session()
session.proxies = {
"http": "http://127.0.0.1:1", # it's a error proxy
"https": "http://127.0.0.1:1",
}
with pytest.raises(requests.exceptions.Pr... |
# Copyright 2018-2020 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... |
from pylatex import Section, Command, NoEscape
def add_experience(doc, cv_data):
with doc.create(Section("Research Experience")):
for index, research in enumerate(cv_data["research"]):
doc.append(Command("textbf", arguments=NoEscape(research["title"])))
doc.append(", ")
... |
import numpy as np
import sys
import time
import struct
num_kv_to_generate = 3000000000 # 3 billion
batch_size = 100
num_batches = num_kv_to_generate/batch_size
dump_file = "/users/aarati_K/realhdd/kv_insert"
f = open(dump_file, 'wb')
start = time.time()
for i in range(num_batches):
rns = np.random.randint(0, sys... |
# from datetime import datetime
from pathlib import Path
import os
import tom_lib.utils as ut
from tom_lib.nlp.topic_model import NonNegativeMatrixFactorization, LatentDirichletAllocation
from tom_lib.structure.corpus import Corpus
# from tom_lib.visualization.visualization import Visualization
import logging
logging.... |
import sys
import struct
import time
from smbus2 import SMBus, i2c_msg
class TOF:
"""
Each object corresponds to a VL53L1X sensor on the RPS board
"""
def __init__(self, bus, sensor_id):
self.bus = bus
self.sensor_id = sensor_id
self.distance = 0
self.is_robot = False
... |
import time
import board
import debouncer
import busio as io
import digitalio
import pulseio
import adafruit_ssd1306
i2c = io.I2C(board.SCL, board.SDA)
reset_pin = digitalio.DigitalInOut(board.D11)
oled = adafruit_ssd1306.SSD1306_I2C(128, 32, i2c, reset=reset_pin)
button_select = debouncer.Debouncer(board.D7, mode=dig... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.