content stringlengths 5 1.05M |
|---|
# Generated by Django 2.0.2 on 2018-02-20 22:54
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('topology', '0003_link_status_and_openvpn_parser'),
]
operations = [
migrations.AlterField(
mode... |
#Abstraction is hiding of info and only providing info that is needed
class PlayerCharacter:
def __init__(self, name, age):
self._name = name
self._age = age
def run(self):
print(run)
def speak(self):
print(f'Am called {self._name} and am {self._age} of age.')
... |
import csv
with open('template.csv', 'rb') as csvSrc:
bufferReader = csv.reader(csvSrc, delimiter=',')
bufferWriter = csv.writer(open('complete.csv', 'wb'), delimiter=',')
bufferWriter.writerow(['template','blob code'])
for line in bufferReader:
line.insert(1, "")
for c in line[0]:
... |
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/topics/item-pipeline.html
from scrapy.exceptions import DropItem
from structuredDataCrawler.items import PipeSeedItem
from structuredDataCrawler.items import SeedItem
from collections impor... |
from ctypes import *
import lib
def init():
lib.libln.ln_arch_init()
def cleanup():
lib.libln.ln_arch_cleanup()
|
from rx.subjects import ReplaySubject
values = ReplaySubject()
subscription = values.subscribe(
on_next=print,
on_error=print,
on_completed=lambda: print("Done")
)
values.on_next(0)
values.on_next(1)
subscription.dispose()
values.on_next(2)
print("=" * 10)
values = ReplaySubject()
subscription1 = values.... |
"""
This script forms a list of URLS by doing google_searches over the IOCS of a previously extracted article. We will generate new dictionaries from these URLS to *populate our dictionaries with further IOC information (future work, just adding it to the database currently and can query it thorugh SQL on i.e. an MD5 h... |
#
# vim: set encoding=utf-8
# This file is part of khmer, http://github.com/ged-lab/khmer/, and is
# Copyright (C) Michigan State University, 2014. It is licensed under
# the three-clause BSD license; see doc/LICENSE.txt.
# Contact: khmer-project@idyll.org
#
import sys
import os
import argparse
from khmer import extra... |
import numpy as np
from . import _librootnumpy
__all__ = [
'array',
]
def array(arr, copy=True):
"""Convert a ROOT TArray into a NumPy array.
Parameters
----------
arr : ROOT TArray
A ROOT TArrayD, TArrayF, TArrayL, TArrayI or TArrayS
copy : bool, optional (default=True)
If ... |
#!/usr/bin/env python3
from argparse import ArgumentParser
import json
import shlex
import os
from itertools import chain
header = """# Auto-generated SSH configuration file for a given Ansible
# Krake inventory:
#
# {hosts_file}
#
"""
def translate_hosts_to_conf(fname):
with open(fname) as f:
hosts... |
import random
import string
import pyperclip
from user import User
class Credentials():
"""
Create a new Credentials class to create new objects
"""
credentials_list = []
def __init__(self, account, userName, password):
"""
Method to define credentials to be stored
"""
... |
"""Assignment - Blocky
=== ===
Diane Horton and David Liu
Department of Computer Science,
University of Toronto
=== Module Description ===
This file contains the Block class, the main data structure used in the game.
"""
from typing import Optional, Tuple, List
import random
import math
from renderer import COLOUR... |
from django.conf import settings
from django.urls import include, path
from .admin import admin_site
urlpatterns = [
path('', include('frontend.urls')),
path('', include('goals.urls')),
path('', include('accounts.urls')),
path('', include('analytics.urls')),
path('accounts/', include('django.contr... |
# -*- coding : utf-8 -*-
import urllib.request
import urllib.parse
import requests
import json
import time
import multiprocessing
import os
# -------- send request by urllib --------
base_url = "http://10.33.3.93:8008"
def urllib_request(num):
params = urllib.parse.urlencode({'uniqueid':314})
url = base_ur... |
# Distributed DL Server runs on worker nodes
# @author: Trung Phan
# @created date: 2021-07-19
# @last modified date:
# @note:
from multiprocessing import Process
from ddlf.worker import *
def main(i):
worker = Worker(id=i+1, host='localhost', N=3, port=8888+i)
worker.start()
processes = []
for i in range(3)... |
# -*- coding: utf-8 -*-
'''
The MIT License (MIT)
Copyright (c) 2016 Wolfgang Almeida <wolfgang.almeida@yahoo.com>
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, i... |
import pandas as pd
import re
import os
FOOTNOTE_RE = re.compile(r'\[[0-9]+\]')
NUMBER_RE = re.compile(r'[0-9]+')
NEW_LINE_RE = re.compile(r'\r\n')
NEW_LINE_2_RE = re.compile(r'\n\n')
def read_data(file_name):
"""Reading and limiting data to the 100 most common genres"""
if not os.path.isfile(file_name):
... |
"""
Copyright (c) 2019 Cisco and/or its affiliates.
This software is licensed to you under the terms of the Cisco Sample
Code License, Version 1.0 (the "License"). You may obtain a copy of the
License at
https://developer.cisco.com/docs/licenses
All use of the material herein must be in accordance wi... |
"""
Hello! I am the comment heading the top level __init__.py in skeleton.
"""
from importlib.metadata import version
__version__ = version("skeleton-JCSCHINDLER01")
from skeleton import sub1
from skeleton import sub2
|
class Solution:
def findDifferentBinaryString(self, nums: List[str]) -> str:
# We will begin by using a conditional statement to check if NOT in nums
if not nums:
# If the list is empty, we will return an empty string
return ""
# We will then create a variable to sto... |
import torch
for i in range(3):
print(f"start allocate {i}")
a = torch.zeros((4, 4), device=torch.device("cuda:0"))
print(f"end allocate {i}")
|
### MDP Value Iteration and Policy Iteratoin
# You might not need to use all parameters
import numpy as np
import gym
import time
from assignment1.lake_envs import *
np.set_printoptions(precision=3)
def policy_evaluation(P, nS, V, policy, gamma=0.9, max_iteration=1000, tol=1e-3):
"""Evaluate the value function from... |
#!/usr/bin/env python
# Copyright Contributors to the Open Shading Language project.
# SPDX-License-Identifier: BSD-3-Clause
# https://github.com/imageworks/OpenShadingLanguage
failthresh = 0.03 # allow a little more LSB noise between platforms
failpercent = .5
outputs = [ "out.exr", "out_02.exr" ]
command = test... |
# -*- coding: utf-8 -*-
"""
Created on Wed May 22 23:14:02 2019
@author: yoelr
"""
import biosteam as bst
from .._exceptions import DimensionError
__all__ = ('DisplayUnits',)
setattr_ = object.__setattr__
getattr_ = object.__getattribute__
class DisplayUnits:
"""Create a DisplayUnits object where default units ... |
import functools
import hashlib
import re
@functools.lru_cache(maxsize=None)
def get_hash(secret):
return hashlib.md5(secret.encode('utf8')).hexdigest()
@functools.lru_cache(maxsize=None)
def get_stretch_hash(secret):
for _ in range(2017):
secret = hashlib.md5(secret.encode('utf8')).hexdigest()
... |
from algo import constants as co
from algo.asset import Algo
from algo.util_algo import get_transfer_asset
from common.ExporterTypes import TX_TYPE_LP_DEPOSIT, TX_TYPE_LP_WITHDRAW
from common.make_tx import _make_tx_exchange, make_reward_tx, make_swap_tx, make_unknown_tx
def handle_unknown(exporter, txinfo):
row ... |
"""
Random Variables.
This module implements random variables. Random variables are the main in- and outputs
of probabilistic numerical methods.
"""
from typing import Any, Callable, Dict, Generic, Optional, Tuple, TypeVar, Union
import numpy as np
from probnum import utils as _utils
from probnum.type import (
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 26 09:39:51 2019
@author: Tobias Andermann (tobias.andermann@bioenv.gu.se)
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import colors
import glob
import zipfile
import collections
def get_test_results(fastqc_log_content):... |
import argparse
import re
from typing import List
import deduce
from loguru import logger
from tqdm import tqdm
from deidentify.methods import train_utils
from deidentify.base import Document
from deidentify.dataset.corpus_loader import CORPUS_PATH, CorpusLoader
from deidentify.methods.deduce.deduce_labeler import De... |
import sys
def eprint(*args, **kwargs):
print >> sys.stderr, ' '.join(map(lambda x: "%s" % x, args))
|
import numpy as np
import keras
from keras.models import Sequential
from sklearn.metrics import confusion_matrix
from keras.layers import Dense, Dropout
import pandas as pd
df = pd.read_csv('RevData/bottleTrain/bottleMyoData1.csv')
df.columns = ['Unit 1','Unit 2','Unit 3','Unit 4','Unit 5','Unit 6','Unit 7','Unit 8'... |
from typing import Hashable, Generator, List, Tuple, Union
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .. import Graph
import pandas as pd
import networkx as nx
from networkx.classes.reportviews import NodeView
from networkx.classes.coreviews import AdjacencyView, AtlasView
class _GrandAdjacencyVie... |
# Copyright 1997 - 2018 by IXIA Keysight
#
# 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, p... |
# Settings file to allow parsing API documentation of Django modules,
# and provide defaults to use in the documentation.
#
# This file is placed in a subfolder,
# so the docs root is not used by find_packages()
STATIC_URL = "/static/"
SECRET_KEY = "docs"
USE_I18N = True
INSTALLED_APPS = [
"fluent_dashboard",
... |
from rest_framework.serializers import ModelSerializer
from v1.users.models import User
class UserSerializer(ModelSerializer):
class Meta:
model = User
fields = ['url', 'username', 'email', 'is_staff', 'phone']
|
from aiocloudflare.commons.auth import Auth
class Webhook(Auth):
_endpoint1 = "accounts"
_endpoint2 = "stream/webhook"
_endpoint3 = None
|
##
# Copyright (c) 2011-2017 Apple 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 applicab... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
from collections import OrderedDict
import tensorflow as tf
try:
from tensorflow.python.keras._impl.keras.layers import Layer
from tensorflow.python.keras._impl.keras.layers import core
except ImportError:
from tenso... |
from rest_framework.generics import ListAPIView
from ...models import Brand
from ..serializer.brand_serializer import BrandSerializer
class BrandList(ListAPIView):
serializer_class = BrandSerializer
def get_queryset(self, *args, **kwargs):
return Brand.objects.filter(category__pk=self.kwargs['pk'])
|
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/echo/')
def echo():
kwargs = {}
kwargs['thing'] = request.args.get('thing')
kwargs['place'] = request.args.get('place')
return render_template('flask3.html', **kwargs)
app.run(port=9999, debug=True)
|
# Migrated from Databricks to run on dataproc
# pip install:
# python_moztelemetry
# git+https://github.com/FirefoxGraphics/telemetry.git#egg=pkg&subdirectory=analyses/bigquery_shim
# boto3==1.16.20
# six==1.15.0
import argparse
import datetime
import json
import os
import sys
import time
import boto3
import requests... |
# Exercício 037
num = int(input('Digite um número inteiro qualquer: '))
n = int(input('''Escolha qual a base decimal para conversão:
1 - Binário;
2 - Octal;
3 - Hexadecimal\n'''))
if n == 1:
print(bin(num)[2:])
elif n == 2:
print(oct(num)[2:])
elif n == 3:
print(hex(num)[2:])
else:
print('OPÇÃO INVÁ... |
"""Create a BigQuery table, view a table schema, list all tables in a project."""
from .clients import LOGGER, gcs, gbq
from .tables import list_all_tables, get_table_schema, get_table
from .insert import gcs_csv_to_table
from .storage import upload_csv_data
from config import (
LOCAL_CSV_FILEPATH,
REMOTE_CSV_D... |
# This file is part of the History Store (histore).
#
# Copyright (C) 2018-2021 New York University.
#
# The History Store (histore) is released under the Revised BSD License. See
# file LICENSE for full license details.
"""Unit tests for the persistent archive."""
import os
import pandas as pd
import pytest
from hi... |
import json
import unittest
import app
from app import create_app
class HelloWorldTestCase(unittest.TestCase):
def setUp(self):
self.client = create_app('test').test_client()
def test_version(self):
response = self.client.get('/seer/api/v1/version', follow_redirects=True)
self.assert... |
import pandas as pd
import numpy as np
class MetricProcessor:
def __init__(self, features, learning_type, path, reduced=False, bins=0, scale=True):
self.features = features.copy()
self.learning_type = learning_type
self.path = path
self.reduced = reduced
self.bins = bi... |
# -----------------------------------------------------------------------------
# Copyright (c) 2015-2021, NeXpy Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING, distributed with this software.
# -------------------------------------------------... |
from box import Box, BoxKeyError
import sys
from collections import OrderedDict
from argparse import ArgumentParser, SUPPRESS
import os
import yaml
if not sys.warnoptions:
import warnings
warnings.simplefilter("always")
def represent_dictionary_order(self, dict_data):
return self.represent_mapping('tag:y... |
from wagtail.core.utils import resolve_model_string
from django.contrib.admin.utils import quote
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from generic_chooser.widgets import AdminChooser
class CollectionChooser(AdminChooser):
choose_one_text = _('Choose a collection... |
# -*- encoding: utf-8 -*-
import io
import re
from glob import glob
from os.path import basename
from os.path import dirname
from os.path import join
from os.path import splitext
from setuptools import find_packages
from setuptools import setup
def read(*names, **kwargs):
return io.open(
join(dirname(__f... |
#Archivos Externos II - 2
from io import open
# creamos un txt, APERTURA
archivo_texto = open("archivo.txt","r") #r : modo lectura
#
archivo_texto.seek(len(archivo_texto.readline()))
print(archivo_texto.read()) |
class Node:
def __init__(self, value = None, left = None, right = None):
self.value = value
self.left = left
self.right = right
class Binary_Tree:
def __init__(self, root = None):
self.root = root
def pre_order(self):
pre_order_list = []
def traverse(root)... |
class Libro():
def __init__(self,titulo,autor,fecha,editorial,ISBN):
self.titulo=titulo
self.autor=autor
self.fecha=fecha
self.editorial=editorial
self.ISBN=ISBN
def setTitulo(self,titulo):
self.titulo=titulo
def setAutor(self,autor):
self.autor=auto... |
import sys
#import pandas as pd
import numpy as np
import mvpa2.suite as mvpa2
fn1 = '/scratch/scratch/ucjtbob/narps1_only_subval_model/BIC_level2/BIC_medians.nii.gz'
fn2 = '/scratch/scratch/ucjtbob/narps1_only_entropy_model/BIC_level2/BIC_medians.nii.gz'
fn3 = '/scratch/scratch/ucjtbob/narps1_subval_entropy/BIC_level... |
"""utilities for formatting
Author: Keisuke Okumura
Affiliation: TokyoTech & OSX
"""
from __future__ import annotations
import numpy as np
def get_relative_pos(
target_pos: np.ndarray, current_pos: np.ndarray
) -> np.ndarray:
"""get relative position
Args:
target_pos (np.ndarray): target positi... |
import numpy as np
from tqdm import tqdm
from baselines.common.runners import AbstractEnvRunner
import cv2
class Runner(AbstractEnvRunner):
"""
We use this object to make a mini batch of experiences
__init__:
- Initialize the runner
run():
- Make a mini batch
"""
def __init__(self, *, ... |
from django.urls import path
from django.urls.resolvers import URLPattern
from .import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('',views.home,name='home'),
path(r'^ajax/newsletter/$', views.newsletter, name='newsletter'),
path('create-admin',vie... |
import tensorflow as tf
import tensorflow.contrib.layers as tcl
class Discriminator(object):
def __init__(self):
self.name = 'D_conv'
def __call__(self, x, local_x, reuse=False):
with tf.variable_scope(self.name) as scope:
if reuse:
scope.reuse_variables()
... |
from __future__ import division
import os
import sys
import torch
import tqdm
import time
import math
import numpy as np
from scipy.stats import gamma
import torch.nn as nn
from os.path import join
from sklearn.cluster import AffinityPropagation, AgglomerativeClustering
from sklearn_extra.cluster import KMedoids
impor... |
from cleo import Command as CLICommand
from ..services.Brew import Brew
from ..services.Configuration import Configuration
from ..services.Dnsmasq import Dnsmasq
from ..services.Nginx import Nginx
class InstallCommand(CLICommand):
"""
Installs Foreman
install
"""
configuration = Configuration()... |
#!/usr/bin/python3
"""
Piccolo script per estrarre le annotazioni dai database physionet
"""
import os
"""
# Shit for sorting
records = ['00.atr', '00.dat', '00.hea', '00.qrs', '01.atr', '01.dat', '01.hea', '01.qrs', '03.atr', '03.dat', '03.hea', '03.qrs', '05.atr', '05.dat', '05.hea', '05.qrs', '06.atr', '06.dat', '... |
"""Test is_positive_definite."""
import numpy as np
from toqito.matrix_props import is_positive_definite
def test_is_is_positive_definite():
"""Check that positive definite matrix returns True."""
mat = np.array([[2, -1, 0], [-1, 2, -1], [0, -1, 2]])
np.testing.assert_equal(is_positive_definite(mat), Tru... |
import numpy as np
# 3x2
a = [
[[1, 2], [7, 8], [13, 14]],
[[2, 3], [8, 9], [14, 15]]]
# 3 x 3
b = [
[
[[1, 2, 3], [10, 11, 12], [19, 20, 21]],
[[2, 3, 4], [11, 12, 13], [20, 21, 22]]
],
[
[[4, 5, 6], [13, 14, 15], [21, 22, 23]],
[[5, 6, 7], [14, 15, 16], [22, 23,... |
# Generated by Django 3.0.2 on 2020-02-07 17:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Question', '0011_question_subject'),
]
operations = [
migrations.AlterField(
model_name='question',
name='subject',
... |
"""
This submodule contains helper functions to help with quick prototyping
using easymunk together with pyxel.
Intended to help with debugging and prototyping, not for actual production use
in a full application. The methods contained in this module is opinionated
about your coordinate system and not very optimized (... |
from flask import Flask, render_template, request, redirect, url_for, abort, flash
from . import main
from .forms import PitchForm, CommentForm
from ..models import User, Pitch, Comments
# from ..pitches import get_pitch
from flask_login import login_required, current_user
from .. import db
import markdown2
import date... |
#!/usr/bin/python
# encoding: utf-8
#pylint: disable=R0904
""" The altium parser test class """
# upconvert.py - A universal hardware design file format converter using
# Format: upverter.com/resources/open-json-format/
# Development: github.com/upverter/schematic-file-converter
#
# Copyright 2011 Upverter, Inc... |
# Generated by Django 3.1 on 2021-02-24 22:42
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("measures", "0004_rename_condition_component_measurement"),
]
operations = [
migrations.AlterModelOptions(
name="measurecondition",
... |
import firebase_admin
import json
import logging
from firebase_admin import credentials
from firebase_admin import firestore
from firebase_admin import storage
from pathlib import Path
class FirebaseManager(object):
def __init__(self, songsFolder, keysFolder):
'''
Constructor
'''
w... |
import json
from typing import Any
import requests
class Goo:
"""
gooAPIをpythonで使えるようにする
"""
def __init__(self, app_id:str, request_id:str) -> None:
self.app_id = app_id
self.request_id = request_id
def textpair(self, text1:str, text2:str) -> Any:
# textpair AP... |
from openpyxl import Workbook,load_workbook
from itertools import product,chain
'''
从Excel文件中载入阻抗列表,经过计划并格式化
'''
def loadfromexcel ( excelfilename ):
"""
从指定的Excel文件中读取所有有效行并返回所有行组成的元组
:param excelfilename
:return:allrows
"""
wb=load_workbook( filename= excelfilename )
ws=wb.active
a... |
#!/usr/bin/env python
from bagmetti.rules.filter import FilterRule
import rospy
import rostest
from geometry_msgs.msg import TransformStamped
from sensor_msgs.msg import Imu
from tf2_msgs.msg import TFMessage
import six
import unittest
class TestFilter(unittest.TestCase):
def setUp(self):
self.make_inc... |
#core models
from django.db import models
from django.contrib.auth.models import User
class Document(models.Model):
owner = models.ForeignKey(User, related_name='owner')
file_name = models.CharField(max_length=50)
allowed_users = models.ManyToManyField(User, related_name = "allowed_docs", null=True, blank... |
from typing import List
from spinta.utils.aiotools import adrain
from spinta import commands
from spinta.components import Context
from spinta.commands.write import push_stream
from spinta.manifests.components import Manifest
from spinta.manifests.backend.helpers import read_sync_versions
from spinta.manifests.backend... |
# -*- coding: utf-8 -*-
import json
import sys
from pathlib import Path
from typing import Optional, Dict, Any, List
from OpenSSL import crypto
from cryptography import x509
from cryptography.x509.oid import NameOID
from jwcrypto import jwk, jws
__author__ = 'lundberg'
METADATA = Path('./fido_alliance_mds.jwt')
ROO... |
from __future__ import unicode_literals
import pytest
from conftest import snode
def test_ancestors_leaf(binary_tree_path):
assert binary_tree_path.nodes[6].ancestor_path() == [
binary_tree_path.nodes[6],
binary_tree_path.nodes[2],
binary_tree_path.nodes[0],
]
def test_ancestors_root... |
#--- Aula 3 07-11-2019
#--- Operações matemáticas
#--- Declaração de variáveis do tipo inteiro
numero1 = 10
numero2 = 15
#--- Operação de soma entre dois números inteiros
resultado = numero1 + numero2
print(resultado)
#--- Operação de subtração entre dois números inteiros
resultado = numero1 - numero2
print(resul... |
from .coco_evaluation import COCOEvaluator
from .evaluator import (
DatasetEvaluator,
DatasetEvaluators,
inference_context,
inference_on_dataset,
)
from .lvis_evaluation import LVISEvaluator
from .pascal_voc_evaluation import PascalVOCDetectionEvaluator
from .testing import print_csv_format, verify_resu... |
#!/usr/bin/env python
import ari
import logging
import threading
logging.basicConfig(level=logging.ERROR)
client = ari.connect('http://localhost:8088', 'asterisk', 'asterisk')
# Note: this uses the 'extra' sounds package
sounds = ['press-1', 'or', 'press-2']
channel_timers = {}
class MenuState(object):
"""A s... |
#!/usr/bin/env python3
import sys
import os
import pandas as pd
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from beehaviour.csv_utils import list_all_files
class VideoQC:
def __init__(self, csv_num):
self.csv_num = csv_num
self.bees_num_frames_tracked = []
self... |
string = input("enter string: ")
def reverse(string):
return string[::-1]
def check_palindrome(string):
return string == reverse(string)
print(check_palindrome(string)) |
# -*- coding: utf-8 -*-
# @Time: 2020/9/28 20:43
# @Author: GraceKoo
# @File: interview_60.py
# @Desc: https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-lcof/
from collections import deque
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right =... |
# Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... |
from . import _lzham
class LZHAMCompressor:
def __init__(self, filters=None):
self.kwargs = {}
self._reinit = False
self.parse_filters(filters)
self._handler = _lzham.lzham_compress_init(**self.kwargs)
def reinit(self):
self._handler = _lzham.lzham_compress_reinit(sel... |
# Pseudorandom number generator using ChaCha8. This does NOT provide
# key erasure / forward secrecy / backtracking resistance.
# Copyright (c) 2015 Taylor R. Campbell
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the followin... |
import discord
import os
import datetime
import time
import re
from youtube_dl import utils as ytutils
from typing import Optional, Union
# this file is for utility functions that do NOT require access to discord,
# e.g. general utility functions
# format current time
def get_cur_time() -> str:
return "{:%m/%d/%... |
import sys
print('Creating the "Affluence" analytics from the csv file')
sys.stdout.flush()
import pandas as pd
df = pd.read_csv("../ressource/data/output.csv")
from matplotlib import pyplot as plt
import plotly.express as px
df['time'].unique()
df['date'].unique()
x =df['time'].value_counts().index
y =df['time'].val... |
#!/usr/bin/env python
# Imports
try:
import sys
import traceback
from math import sin, cos, pi
except ImportError, err:
print "ERROR: Cannot load module: %s" % (err)
sys.exit(2)
def sqr(x):
return x*x
def branin(x, y):
# sqr(y-(5.1/(4*sqr(M_PI)))*sqr(x)
# +5*x/M_PI-6)... |
# -*- coding: utf-8 -*-
import logya.util
site_root = 'tests/fixtures/site/'
site_paths = logya.util.paths(site_root)
def test_encode_content():
text = logya.util.encode_content({}, '')
assert 2 == text.count('---\n')
def test_slugify():
for value, expected in [
('ac/dc', 'ac-dc'),
('A... |
"""svgen/svgen/elements.py
"""
# Standard Library
import abc
# Third-Party
import numpy as np
class Element(metaclass=abc.ABCMeta):
def __init__(self, kw: dict):
self.kw = self.kwargs(kw)
@abc.abstractmethod
def render(self, array: np.ndarray) -> str:
pass
@staticmethod
def kwar... |
import pygame
from events import *
from pygame.locals import *
class clickable:
rect = None
click_enabled = True
mouse_button_down = False
last_pos = None
pressed = False
double_click_timeout = 200
double_click_timer = 0
frame_time = 0
def __init__(self):
self.options["pressed"] = {}
def set_gui(self, gu... |
from time import time
from importlib import reload
import partools.utils as u
from . import gl
from .init import init
from .functions import finish
from .functions import get_query_list
from .process import process_query_list
from .recover import recover
@u.log_exeptions
def download(**kwargs):
"""Performs mult... |
'''
family 0x0d
Chat navigation.
'''
import struct
import logging
import util
import oscar
x0d_name="Chat nav"
log = logging.getLogger('oscar.snac.x0d')
subcodes = {}
@util.gen_sequence
def x0d_init(o, sock, cb):
log.info('initializing')
me = (yield None); assert me
sock.send_snac(*os... |
"""
Three-way conversion between "native" Python data representation, CBOR, and JSON.
See README.md for details.
"""
from ._cbor_json_codecs import ( # noqa: F401
native_from_cbor, cbor_from_native,
jsonable_from_native, native_from_jsonable,
jsonable_from_cbor, cbor_from_jsonable,
base58_encode, base... |
#!/usr/bin/env python
from ATK.Core import DoubleInPointerFilter, DoubleOutPointerFilter
from ATK.Dynamic import DoubleGainExpanderFilter, DoubleGainColoredExpanderFilter, DoubleGainMaxColoredExpanderFilter
from ATK.Tools import DoubleApplyGainFilter
import matplotlib.pyplot as plt
sample_rate = 96000
def filter(in... |
import torch.nn.functional as F
import numpy as np
def mse_arr_loss(outputs, gt, window=10000):
loss = 0
outputs = outputs[-window:]
weights = list(np.linspace(0, 1, len(outputs) + 1))[1:]
for output, w in zip(outputs, weights):
loss += F.mse_loss(output, gt) * w
return 2 * loss/len(output... |
#-*- coding:UTF-8 -*-
import time
import random
from utils.cam import Cam
from utils.ultrasonic import UltraSonic
from utils.driver import Driver
from utils.servo import Servo
class Car():
def __init__(self, init_speed = 10):
self.cam = Cam()
self.ultrasonic = UltraSonic()
self.driver = Dri... |
import pandas as pd
from keras import Sequential
from keras.callbacks import EarlyStopping
from keras.layers import Dense, Dropout
from keras.optimizers import RMSprop, Adam
import numpy as np
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error... |
###############################################################################
#
# Copyright (c) 2012 Ruslan Spivak
#
# 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, inc... |
'''Constants and methods for astronomy & astrophysics'''
# Astronomy utilities module
import numpy as np
import scipy as sc
from scipy import integrate
# constants for astronomy
rsun_cm = 6.955e10
rsun_cm_s = 'cm'
lsun_erg_s = 3.839e33
lsun_erg_s_unit = 'erg/s'
msun_g = 1.9891e33
msun_unit = 'erg s^-1'
mass_earth_g... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.