content stringlengths 5 1.05M |
|---|
import os
os.environ['ComplianceMode'] = 'True'
os.environ['SendToSlack'] = 'True'
os.environ['SendToSNS'] = 'True'
os.environ['RoleName'] = 'HUITPublicResourceCompliance-us-east-1'
os.environ['LogLevel'] = 'INFO'
os.environ['Topic'] = 'arn:aws:sns:us-east-1:077179288803:dynamodb'
os.environ['SlackURL'] = 'https://hook... |
# SPDX-FileCopyrightText: 2021 Melissa LeBlanc-Williams for Adafruit Industries
#
# SPDX-License-Identifier: MIT
import sys
import time
from adafruit_blinka import agnostic
import board
import digitalio
# from Adafruit_GPIO import Platform
# print("Platform = ", Platform.platform_detect(), Platform.pi_version())
prin... |
import math
import torch
import torch.nn as nn
from mmcv.runner import load_checkpoint
from mmedit.models.common import (PixelShufflePack, ResidualBlockNoBN,
make_layer)
from mmedit.models.registry import BACKBONES
from mmedit.utils import get_root_logger
class UpsampleModule(nn.Se... |
#!/usr/bin/env python
# Copyright 2016 Andy Chu. 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
"""
oil.py - A busybox-lik... |
import numpy as np
import pandas as pd
from ..lsa import LSA
from ..utils import PrimitiveT, find_applicable_primitives, valid_dfs
class TestLSA(PrimitiveT):
primitive = LSA
def test_strings(self):
x = pd.Series(['The dogs ate food.',
'She ate a pineapple',
... |
from dataclasses import dataclass, field
from sys import getsizeof
from typing import Any, Dict, List
from paralleldomain.model.annotation.common import Annotation
from paralleldomain.model.geometry.point_3d import Point3DGeometry
@dataclass
class Point3D(Point3DGeometry):
"""Represents a 3D Point.
Args:
... |
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
from .models import Profile
from .tokens import account_activation_token
from django.utils.encoding import force_bytes, force_text
from django.utils.http import urlsafe_base64_encode, urlsafe_... |
from lml.plugin import PluginInfo
from moban import constants
@PluginInfo(
constants.TEMPLATE_ENGINE_EXTENSION, tags=[constants.TEMPLATE_COPY]
)
class ContentForwardEngine(object):
"""
Does no templating, works like 'copy'.
Respects templating directories, for example: naughty.template
could exi... |
# -*- coding: utf-8 -*-
"""
Feature Engineering
"""
import numpy as np
from functions import inv_log
from helpers import *
from preprocessing import *
def build_poly(x, degree, roots=False):
"""polynomial basis functions for input data x, for j=0 up to j=degree."""
assert type(degree) == int, "de... |
"""
Demo/test program for the DS18B20 driver.
See https://github.com/sensemakersamsterdam/astroplant_explorer
"""
#
# (c) Sensemakersams.org and others. See https://github.com/sensemakersamsterdam/astroplant_explorer
# Author: Ted van der Togt
#
# Warning: if import of ae_* modules fails, then you need to set up PYTHON... |
#!/usr/bin/python3
#Copyright 2018 Nicolas Bonnand
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import (QFileDialog,QInputDialog,QAbstractScrollArea,QAbstractItemView,QDockWidget,QCompleter,QItemDelegate,QHeaderView,QDesktopWidget,QTreeView,QSizePolicy,QTableView)
from PyQt5.QtCore import (QTimer,... |
def moduluo(dividend, divisor):
return dividend%divisor == 0
for i in range(1, 101):
output = ''
if moduluo(i, 3):
output += 'Fizz'
if moduluo(i, 5):
output += 'Buzz'
if i != 100:
print(f"{i}," if output == '' else f"{output},", end=" ")
else:
print(output... |
import os
def breakpoint():
import rpdb2
os.system("winpdb -r &")
rpdb2.start_embedded_debugger("password")
|
from django.shortcuts import render, reverse
from django.core.paginator import Paginator
from django.http import HttpResponseRedirect
from django.views import View
from django.contrib.auth import logout
from django.contrib.auth.password_validation import validate_password
from django.contrib.auth import get_user_model
... |
import json
import os
import threading
import time
from queue import Queue
from flask import Flask
app = Flask(__name__)
tasks = {}
@app.route('/deploy/<name>/', methods=['GET', 'POST'])
def run_script(name):
try:
config_file_path = None
for file_path in ['/etc/hook.json', './hook.json']:
... |
"""
Bombs away
Ported from BASIC to Python3 by Bernard Cooke (bernardcooke53)
Tested with Python 3.8.10, formatted with Black and type checked with mypy.
"""
import random
from typing import Iterable
def _stdin_choice(prompt: str, *, choices: Iterable[str]) -> str:
ret = input(prompt)
while ret not in choice... |
import unittest, os
import nbformat as nbf
import sys, os
myPath = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, myPath + '/../journal_migration/')
sys.path.insert(0, myPath + '/../util/')
from journal_markdown import journalMarkdown
class testJournalMarkdown(unittest.TestCase):
def setUp(self):
... |
import os
import requests
# configuration, set DOMAIN and NAMECHEAP_DDNS_PW as env vars
HOST = '@'
DOMAIN = os.environ['DOMAIN']
PW = os.environ['NAMECHEAP_DDNS_PW']
ENDPOINT = 'https://dynamicdns.park-your-domain.com/update?'
# get the IP address of the system
def get_ip():
return requests.get('https://dynamicd... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2017-12-08 04:56
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_depende... |
{
'targets': [
{
'target_name': 'addon',
'sources': [
'../../tmp/linear_model.cc',
'../../tmp/particle.cc',
'../../tmp/fastslam.cc',
'addon.cc'
],
'include_dirs': [
'src',
'.',
'/opt/intel/compilers_and_lib... |
""""
Script for preprocessing and train-test splitting the white wine dataset.
Usage:
preprocess.py <data_folder> <raw_data_file>
Options:
"""
from docopt import docopt
from sklearn.model_selection import train_test_split, cross_val_score, cross_validate
from sklearn.preprocessing import StandardScaler
from sklea... |
number = ["1", "2", "3", "4", "5", "6","7", "8", "9", "10"]; # inputing datas to number
print (number[0]); # print the 0 value from array output : 1
print (number[1]); # print the 1 value from array output : 2
print (number[2]); # print the 2 value from array output : 3
print (number[3]); # print the 3 value from arra... |
from ...abc import Expression
class CONTAINS(Expression):
def __init__(self, app, *, arg_what, arg_substring):
super().__init__(app)
self.Value = arg_what
self.Substring = arg_substring
def __call__(self, context, event, *args, **kwargs):
value = self.evaluate(self.Value, context, event, *args, **kwargs... |
# https://leetcode.com/problems/search-in-rotated-sorted-array/
from typing import List
import unittest
MINIMUM_ARRAY_LENGTH = 1
MAXIMUM_ARRAY_LENGTH = 5 * 10**3
MINIMUM_NUMBER_VALUE = -10**4
MAXIMUM_NUMBER_VALUE = 10**4
class SolutionValidator(object):
def validate_array_length(self, array_len: int) -> None:
... |
import cv2
import numpy as np
#load colored image
img_1 = cv2.imread("Images\\sunflower.png", 1)
#load grayscale image
img_2 = cv2.imread("Images\\sunflower.png", 0)
#resizing images
resized_img_1 = cv2.resize(img_1, (int(img_1.shape[1]/2), int(img_1.shape[0]/2)))
#printing images' shape(dimension)
pri... |
import contact_angle as cnt
import mdtraj as md
import numpy as np
from contact_angle.utils.general import get_fn
def test_flipped():
"""Same trajectory, but rotated around x-axis - should give same contact angle
"""
traj = md.load(get_fn('chol-tail-original.dcd'),
top=get_fn('chol-wetting.ho... |
# *****************************************************************************
# Copyright (c) 2019, Intel Corporation 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 sou... |
from pydantic import EmailStr, SecretStr
from server.domain.common.types import ID
from server.seedwork.application.commands import Command
class CreateUser(Command[ID]):
email: EmailStr
password: SecretStr
class DeleteUser(Command[None]):
id: ID
class ChangePassword(Command[None]):
email: EmailS... |
from rich.console import Console
from rich.progress import Progress, BarColumn, TextColumn, TimeRemainingColumn
from rich.table import Table
from rich.text import Text
from rich.markdown import Markdown
from sheraf.health.utils import discover_models
from .checks import check_conflict_resolution, check_attributes_inde... |
from datetime import date, datetime
from typing import Optional
import numpy as np
import pandas as pd
from autumn.tools.inputs.database import get_input_db
from autumn.tools.inputs.demography.queries import get_population_by_agegroup
from autumn.tools.utils.utils import check_list_increasing
TINY_NUMBER = 1e-6
de... |
import os
class Config:
"""
This is the parent configuration class that contains the main configurations that are to work on the application
"""
NEWS_API = os.environ.get('NEWS_API_KEY')
SECRET_KEY = os.environ.get('SECRET_KEY')
BASE_URL = 'https://newsapi.org/v2/{}?q={}&apiKey={}'
class ProdC... |
#!/usr/bin/python
# -'''- coding: utf-8 -'''-
import sys, os
from PySide.QtCore import *
from PySide.QtGui import *
class Launcher(QDialog):
nukepressed = Signal()
mayapressed = Signal()
def __init__(self, parent=None):
super(Launcher, self).__init__(parent)
# Define Widgets
# ... |
# uncompyle6 version 3.7.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]
# Embedded file name: T:\InGame\Gameplay\Scripts\Server\sims\template_affordance_provider\tunable_affordance_template_discipline.py
# Compiled at: 2017-02-2... |
_=[print("%s: %d points"%T)for T in sorted([(T[0],sum([int(s)for s in T[1].split()]))for R in __import__("sys").stdin for T in[R.split(":")]if all(x.isdigit()for x in T[1].split())],key=lambda x:-x[1])]
|
import unittest
from flaskr.textHandler import TextHandler
class TestTextHandler(unittest.TestCase):
EXPECTED = "français"
def test_remove(self):
result = TextHandler.remove_indicator(TextHandler.HEADER + self.EXPECTED + TextHandler.FOOTER)
self.assertEqual(self.EXPECTED, result)
def te... |
from thundra.application.application_info_provider import ApplicationInfoProvider
from thundra.config import config_names
from thundra.config.config_provider import ConfigProvider
class GlobalApplicationInfoProvider(ApplicationInfoProvider):
def __init__(self, application_info_provider=None):
self.applica... |
#!/usr/bin/env python
import argparse
import asyncio
import json
import statistics
import time
from datetime import datetime
from typing import Any, Dict
import aiohttp
import uvicorn
from loguru import logger
from starlette.applications import Starlette
from starlette.responses import PlainTextResponse
from starlett... |
from datetime import timedelta
import numpy as np
import pandas as pd
import pytest
from go_utils.cleanup import (
adjust_timezones,
camel_case,
filter_invalid_coords,
remove_homogenous_cols,
rename_latlon_cols,
replace_column_prefix,
round_cols,
standardize_null_vals,
)
camel_case_da... |
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 4 22:04:11 2018
first version of Master thesis codes, initial model
@author: JingQIN
"""
import math
import numpy as np
import decimal
class Quaternion(object):
"""class of Quaternion that do the simple operations
Attributes:
a -- a float paramete... |
"""
:mod:`boardinghouse.management.commands.loaddata`
This replaces the ``loaddata`` command with one that takes a new
option: ``--schema``. This is required when non-shared-models are
included in the file(s) to be loaded, and the schema with this name
will be used as a target.
After completing the load, we ensure th... |
#!/usr/bin/env python
# flake8: noqa: F401, F402, F403, F405
"""A script used to determine unique response keys for each response type"""
import sys
from itertools import chain
from pprint import pprint
from pyinaturalist.constants import PROJECT_DIR
sys.path.insert(0, PROJECT_DIR)
from test.sample_data import *
RES... |
# -*- coding: utf-8 -*-
# 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 "Lic... |
brick = """
▗▄▄▄▄▄▄▄▄▄▄▄▄▖
▐████████████▌
▐████████████▌
▝▀▀▀▀▀▀▀▀▀▀▀▀▘
"""
glass = [
"""
┏━━━━━━━━━━━━┓
┃ ┃
┃ ┃
┗━━━━━━━━━━━━┛
""",
"""
┏━┳━━┳━━━━┳━━┓
┃ ┗ ┛ ┏┫
┣┛ ┃
┗━━━━━━┻━━━┻━┛
""",
"""
┏━┳━━━┳━━━┳━━┓
┃ ┗┓ ┗ ┏┛ ━┫
... |
""" Unittests """
|
from django.core.urlresolvers import reverse
from django_webtest import WebTest
import webtest
from django.contrib.auth.models import User
from evap.evaluation.models import Semester, Questionnaire, UserProfile, Course, Contribution
import os.path
def lastform(page):
return page.forms[max(page.forms.keys())]
... |
# coding=utf-8
#
# @lc app=leetcode id=105 lang=python
#
# [105] Construct Binary Tree from Preorder and Inorder Traversal
#
# https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description/
#
# algorithms
# Medium (39.51%)
# Likes: 1725
# Dislikes: 49
# Total Accepted: 226.4K... |
from CursoEmVideoPython import titulo
def cadastro(nome, idade):
f = open('pessoas_cadastradas.txt', 'a')
f.write('\n')
f.write(f'{nome:<22}{idade} anos')
print(f'{nome} de {idade} anos cadastrado com sucesso')
def exibir():
titulo.destaque('Pessoas cadastradas')
f = open('pessoas_cadastradas... |
from telegram.ext import Updater, CommandHandler
from telegram import ParseMode
import conf
def start(bot, update):
update.message.reply_text("The chat id to config is: `{}`".format(update.message.chat_id),
parse_mode=ParseMode.MARKDOWN)
tg = Updater(conf.SECRET)
tg.dispatcher.add_... |
"""
Contains the constructs for defining the data model when deserialising
the yaml documents, and forms the basis of the intercomparison workflow.
"""
import math
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple, Union
import attr
from affine import Affine # type: ignore
import numpy # ty... |
import sys
# Package brave split into two paths.
# path2/brave/robin.py and path3/brave/_robin.so
sys.path.insert(0, 'path2')
sys.path.insert(0, 'path3')
from brave import robin
assert(robin.run() == "AWAY!")
|
"""empty message
Revision ID: 4b7b5a7ddc5c
Revises: 2a5fdb834d35
Create Date: 2016-02-01 18:31:56.369000
"""
# revision identifiers, used by Alembic.
revision = '4b7b5a7ddc5c'
down_revision = '2a5fdb834d35'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - ... |
class Complex :
def __init__(self, x, y) :
self.x=x
self.y=y
def add(self,other) :
return Complex(self.x+other.x,self.y+other.y)
def subtract(self,other) :
return Complex(self.x-other.x,self.y-other.y)
def multiply(self,other) :
return Complex(self.x*other.x-self.x*other.y,
self.x*other.y-self.... |
from main.base_element import BaseElement
from selenium.webdriver.common.by import By
from main.base_page import BasePage
class ProductPage(BasePage):
@property
def product_name(self):
locator = (By.CSS_SELECTOR, 'div.box h1')
return BaseElement(driver=self.driver, locator=locator)
@prop... |
#############
# RPS LOGIC
moves = ["rock", "paper", "scissors", "lose"]
def get_win(a, b):
# Find the lower index of the array that Alicia chose vs.
# lower index of the array that Bruce chose.
lower = min(moves.index(a), moves.index(b))
# Find the higher index of the array that Alicia chose vs.
... |
import codecs
import json
from collections import namedtuple
class Settings:
def __init__(self, data_dir):
self._data_dir = data_dir
self._setting_path = self._data_dir + "/settings.json"
self.default_prefix = "^"
with codecs.open(self._setting_path, "r", encoding="utf8") as f:
... |
"""
This module handles the execution of the users module. It should ideally
be called in an subprocess (like code_runner does) in a secure enviroment
with all code files prepared.
This overhead is needed to avoid having extra testcases loaded by the grader.
`test_module` loads the tester code loaded in a file. In th... |
import click
import logging
from .utils import get_pangea_group
from pangea_api.contrib.tagging import Tag
from pangea_api import (
Knex,
User,
)
from .api import process_group
logger = logging.getLogger(__name__) # Same name as calling module
@click.group('pangea')
def capalyzer_pangea_cli():
pass
... |
"""
Workaround for having too many threads running on 32-bit systems when
logging to buildlogger that still allows periodically flushing messages
to the buildlogger server.
This is because a utils.timer.AlarmClock instance is used for each
buildlogger.BuildloggerTestHandler, but only dismiss()ed when the Python
proces... |
__author__ = "jacksonsr45@gmail.com"
new_skill = {
'knight': {
'attack speed': {
},
'move speed': {
},
'attack distance': {
},
'defense': {
},
'magic attack': {
},
'dodge': {
},
},
'paladin': {
'att... |
"""
tomaty.py
~~~~~~~~
This module is the main module for tomaty and contains Tomaty, the main contain
tomaty is a gtk based application that implements the Pomodoro technique to
help users focus better on their work and encourage healthy lifestyle habits.
This continues to be a work in progress. Expect many changes... |
from random import randint
def guess(min = 1, max = 3):
return randint(min, max)
def user_game(default=5):
# Get a limit value from the user, this value is going to be the limit of
# the guessing, if not provided the default will be used as limit
limit = input(f'Enter the limit for the guess (default is {default... |
# Uses python3
import sys
def get_optimal_value(capacity, weights, values):
sorted_by_fraction = sorted(zip(weights, values), key=lambda item: item[1] / item[0])
value = 0.
while 0 < capacity and len(sorted_by_fraction):
weight_i, value_i = c.pop() # pop the item on top
x = 1.0
if ... |
#!/usr/bin/python3
"""
Demonstrates the use of Psi4 from Python level.
Useful notes:
o Use psi4.core module for most of the work
o Useful modules within psi4.core:
- MintsHelper
- Molecule
- BasisSet
- ExternalPotential
others
o Psi4 defines its own matrix type (psi4.core.Matrix).
... |
#! /usr/bin/python3
# p104
animals = ['bear','python','peacock','kangaroo','whale','platypus']
print("The animal at 1 is %s",animals[0])
print("The third animal is %s",animals[2])
print("The first animal is %s",animals[0])
print("The animal at 3 is %s",animals[2])
print("The fifth animal is %s",animals[4])
print("The... |
#! /usr/bin/env python3
# coding=utf-8
#================================================================
# Copyright (C) 2018 * Ltd. All rights reserved.
#
# Editor : VIM
# File name : yolov3.py
# Author : YunYang1994
# Created date: 2018-11-21 18:41:35
# Description : YOLOv3: An Incremental Imp... |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import pprint
from selenium.webdriver.support.ui import WebDriverWait
from pytesseract import image_to_string
from PIL import Image
import time
import io
import pytesseract
import pytesseract as tss
import requests
import argparse
from selen... |
from enum import Enum
class OperationTypes(Enum):
Single = 0
Multiple = 1 |
import traceback
import inspect
import platform
from time import time
import zlib
import bz2
import lzma
import warnings
from typing import (
Optional,
List,
Tuple,
Dict,
Any,
AsyncIterator
)
from pymprpc.errors import (
ProtocolSyntaxException,
LoginError,
RequestError,
MethodEr... |
# ###########################################################################
#
# CLOUDERA APPLIED MACHINE LEARNING PROTOTYPE (AMP)
# (C) Cloudera, Inc. 2021
# All rights reserved.
#
# Applicable Open Source License: Apache 2.0
#
# NOTE: Cloudera open source products are modular software products
# made up of hu... |
"""
Mass constants
Base unit: Gram
"""
from fractions import Fraction
# US customary (mass in g) (avoirdupois - avdp)
OZ = Fraction(28.349523125) # ounce
GR = Fraction(2/875) * OZ # grain (16/7000)
DR = Fraction(1/16) * OZ # dram
LB = 16 * OZ # pound
CWT = 100 * 16 * OZ # US hundred... |
from typing import Any, List, Literal, Optional, Tuple
import torch
from pytorch_lightning.metrics.classification.confusion_matrix import (
ConfusionMatrix as ConfusionMatrixBase,
)
from torch import Tensor
from ..custom_types import Annotation
from ..visualization import plot_confusion_matrix
from .utilities imp... |
from conformance_checking.algorithms import (
Act2VecWmdConformance,
Act2VecIctConformance,
Trace2VecCosineConformance,
)
import numpy as np
def main():
model_traces = [
["hi", "foo"],
["hi", "foo"],
["bar"],
[],
["a", "long", "trace", "with", "doubled", "words... |
import wxconfig as cfg
import unittest
from unittest.mock import patch
import definitions
import algotrader.connections.ds as ds
class TestDataSource(unittest.TestCase):
def setUp(self) -> None:
# Setup config
cfg.Config().load(fr"{definitions.ROOT_DIR}\tests\testconfig.yaml")
def test_inst... |
from unittest.mock import Mock, patch
import pytest
def test_subscription_inst():
from tartiflette.subscription.subscription import Subscription
r = Subscription("a")
assert r._implementation is None
assert r._schema_name == "default"
assert r._name == "a"
@pytest.fixture
def a_subscription():... |
from models.models import User
import os
import sys
from werkzeug.utils import secure_filename
from flask import Flask, render_template, url_for, request, redirect, session, jsonify, Blueprint, flash
from scoss import smoss
import requests
from sctokenizer import Source
from scoss import Scoss
from scoss.metrics import... |
from collections import OrderedDict
import heterocl as hcl
import heterocl.tvm as tvm
class PPAC_config:
"""Wrap PPAC parameters and function names."""
def __init__(self, multi_bit=False, word_bits=None, elem_bits=None):
"""Initialize PPAC configurations
Parameters
----------
m... |
from typing import Iterable, Tuple
import numpy as np
from unittest import TestCase
import numpy.testing as npt
from distancematrix.util import diag_indices_of
from distancematrix.consumer.contextual_matrix_profile import ContextualMatrixProfile
from distancematrix.consumer.contextmanager import GeneralStaticManager
... |
from . import BaseAnnotationDefinition
class Subtitle(BaseAnnotationDefinition):
"""
Subtitle annotation object
"""
type = "subtitle"
def __init__(self, text, label, attributes=None, description=None):
super().__init__(description=description, attributes=attributes)
self.text ... |
import string
class Base62(object):
"""
Helper class for encoding/decoding with Base 62. The code is borrowed from:
https://stackoverflow.com/a/2549514/1396314
"""
BASE_LIST = string.digits + string.ascii_letters
BASE_DICT = dict((c, i) for i, c in enumerate(BASE_LIST))
@staticmethod
... |
#!/usr/bin/env python
# encoding=utf8
import os
import re
import sys
import struct
import pprint
import random
import argparse
import datetime
import tiddlywiki as tiddly
import cdam_gen_files as gen
import importlib
import bitarray
importlib.reload(sys)
# sys.setdefaultencoding('utf8')
VERSION = "1.0"
BINARY_VER =... |
import numpy as np
from numpy.linalg import inv
import matplotlib.pyplot as plt
from matplotlib import animation
from matplotlib import patches
# import pylab
import time
import math
class KalmanFilter:
"""
Class to keep track of the estimate of the robots current state using the
Kalman Filter
"""
... |
"""
This script allows the user to find out actual full names of GitHub repositories
to avoid duplicated projects in a dataset.
The script makes requests to GitHub API, saves unique full names of repositories
and optionally saves all JSON responses containing repositories metadata.
It accepts
* path to csv file -- ... |
import numpy as np
import tensorflow as tf
import tempfile
import urllib
import os
import math
import pandas as pd
import argparse
import sys
import csv
DIR_SUMMARY = './summary'
DIR_MODEL = './model'
class ML:
def __init__(self, learning_rate=0.05, epochs=10, batch_size=100,
data_path='./data/t... |
# Copyright 2021-2022 NVIDIA Corporation
#
# 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 ... |
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.core import mail
from django.template import Context, Template
from django.test.client import RequestFactory
from djblets.avatars.tests import DummyAvatarService
from djblets.extensions.extension import ExtensionInfo
from d... |
from .about import NAME, VERSION, __version__
from .sonyflake import SonyFlake
__all__ = ["SonyFlake"]
|
# Copyright 2018 NOKIA
#
# 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 in... |
from web.api import BaseAPI
from data_models import government_models
from utils import mongo
class LordApi(BaseAPI):
def __init__(self):
BaseAPI.__init__(self)
self._db = mongo.MongoInterface()
self._db_table = 'api_lords'
def request(self, args):
name = args["name"]
... |
# unp.py - functions for handling Belarusian UNP numbers
# coding: utf-8
#
# Copyright (C) 2020 Arthur de Jong
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of th... |
import ase
import ase.calculators.lj
from interlayer_energies_demo import generate_geometry
import scipy.optimize
import numpy as np
def eval_energy(df, sigma, epsilon):
"""
"""
print(sigma, epsilon)
energy = []
for it, row in df.iterrows():
atoms = generate_geometry.create_graphene_geom(r... |
database = 'medidas.db'
def selecionar_tabela():
"Escolhe a tabela desejada"
opcoes = {"1": "peso", "2": "peito", "3": "braco", "4": "quadril", "5": "perna", "q": "sair"}
print("Digite o numero da tabela a seguir:")
print("[1] peso")
print("[2] peito")
print("[3] braco")
print("[... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# code for python2
import rospy
import serial
import time
import signal
import sys
from kondo_b3mservo_rosdriver.msg import Multi_servo_command
from kondo_b3mservo_rosdriver.msg import Multi_servo_info
import Kondo_B3M_functions as Kondo_B3M
id = []
num = 0
initial_process... |
from task_allocation.allocation import Allocation
class RandomAllocation(Allocation):
def __init__(self, randomizer, agents, jobs):
super().__init__()
if len(agents) == len(jobs):
matching = randomizer.sample(jobs, k=len(agents))
else:
matching = randomizer.choices(... |
from propara.data.proglobal_dataset_reader import ProGlobalDatasetReader
from allennlp.common.testing import AllenNlpTestCase
class TestDataReader(AllenNlpTestCase):
def test_read_from_file(self):
sc_reader = ProGlobalDatasetReader()
dataset = sc_reader.read('tests/fixtures/proglobal_toy_data.tsv... |
#! /usr/bin/env python3
import sys
#1 DONE!!! Passed 9/10
def translate_sequence(rna_sequence, genetic_code):
pass
# Read and get the RNA string
rna = rna_sequence.upper()
print ("\n \n RNA String: ", rna)
x=len(rna)
if x < 3:
return ''
# RNA codon table(make sure you have it)
protein... |
'''
test dssNet generation
'''
import pipe
import sys
import time
import logging
Gen_ID = sys.argv[1]
logging.basicConfig(filename='%s.log'%Gen_ID,level=logging.DEBUG)
pipeout=pipe.setup_pipe_l(Gen_ID)
pipin = pipe.setup_pipe_w()
# send to control center
def send_netCoord(val):
update = 'update n p controlla... |
from lxml.etree import HTML as LXHTML
from lxml.etree import XML as LXML
from xdict.jprint import pdir,pobj
from nvhtml import txt
from nvhtml import lvsrch
from nvhtml import fs
from nvhtml import engine
from nvhtml import utils
from nvhtml.consts import *
import lxml.sax
import argparse
from efdir import fs
import ... |
from django import forms
INTERVAL_CHOICES = [(k, k) for k in ('minutes', 'hours', 'days', 'weeks',
'months', 'years')]
class StatsFilterForm(forms.Form):
"""Form for filtering the statistics shown in the admin interface ."""
start = forms.DateTimeField()
end = forms.... |
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
"""
ddupdate plugin updating data on changeip.com.
See: ddupdate(8)
See:
http://www.changeip.com/accounts/knowledgebase.php?action=displayarticle&id=34
"""
from ddupdate.ddplugin import ServicePlugin, ServiceError
from ddupdate.ddplugin import http_basic_auth_setup, get_response
class ChangeAddressPlugin(ServicePl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.