text stringlengths 1 927k |
|---|
#!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2015 Thomas Voegtlin
#
# 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... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'PyConLightningTalkProposal'
db.create_table(u'pycon_pyconlightningtalkproposal', (
... |
import datetime
import pprint
import pymongo
import sys
import json
import time
import copy
from pymongo import MongoClient
import sys
sys.path.insert(0, '/home/nevolin/public_html/cryptoproto/')
from mysettings import dtNow
import DAL
client = DAL.openConnection()
db=client.crypto
if not len(sys.argv) >= 2:
pri... |
from distutils.core import setup
setup( name = 'weekdate',
version = '0.1',
author = 'Kenneth P. J. Dyer',
author_email = 'kenneth@avoceteditors.com',
url = 'https://github.com/kennethpjdyer/weekdate',
description = 'Basic utility... |
from dataclasses import dataclass
from enum import Enum
from pathlib import Path
from typing import Optional, Union, List, Dict, Any
@dataclass
class ConfZSource:
"""Source configuration for :class:`~confz.ConfZ` models."""
ConfZSources = Union[ConfZSource, List[ConfZSource]]
class FileFormat(Enum):
"""En... |
"""
This code contains examples of how to call and use the SCoPP-Monitoring module.
"""
# Import the necessary modules:
import monitoring_algorithms
import environments as envs
# Initialize environment class
environment = envs.Debugger()
# Initialize monitoring algorithm instance
way_point_allocator = monitoring_algo... |
from . import BaseResult
class RecordResult(BaseResult):
@property
def url(self):
return self.component.url
@property
def duration(self):
return self.component.duration
@property
def size(self):
return self.component.size |
# coding: utf-8
# Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... |
# Copyright 2021 The ParallelAccel 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 appl... |
VERSION = (0, 8, 1)
__version__ = '.'.join(map(str, VERSION)) |
import json
import os
import pytest
from datetime import datetime, timedelta
import boto3
from httmock import urlmatch, HTTMock
from moto import mock_s3
from app import storage as test_storage
from data import model, database
from data.logs_model import logs_model
from storage import S3Storage, StorageContext, Dist... |
"""BCP module."""
import asyncio
from functools import partial
from typing import List
from mpf.core.events import QueuedEvent
from mpf.core.mpf_controller import MpfController
from mpf.core.bcp.bcp_server import BcpServer
from mpf.core.utility_functions import Util
from mpf.core.bcp.bcp_interface import BcpInterfac... |
# -*- coding: utf-8 -*-
import mock
import time
import threading
from elasticsearch import helpers, Elasticsearch
from elasticsearch.serializer import JSONSerializer
from .test_cases import TestCase
lock_side_effect = threading.Lock()
def mock_process_bulk_chunk(*args, **kwargs):
"""
Threadsafe way of mocki... |
import json
import os
import pygame
from find_path import solve_maze
pygame.init()
def maze_gen():
"""takes in put from the user and returns a map
Returns:
dict: the json file containing all the maps
"""
res = {}
for i in range(1): # for each of the mazes (9)
print("this is maze... |
from typing import Any, Dict, List, Optional, Tuple
from bs4 import BeautifulSoup
from pfr_api.parse.parser import RowParser, IdentityParser, \
StrToIntParser, NullableStrToIntParser, \
NullableStrToFloatParser, StrPercentageToFloatParser, \
NullableStrPercentageToFloatParser
PARSERS = {
'year_id': ... |
from __future__ import absolute_import
import jsonschema
import six
__all__ = ("Csp", "Hpkp", "ExpectCT", "ExpectStaple")
from six.moves.urllib.parse import urlsplit, urlunsplit
from sentry.interfaces.base import Interface, InterfaceValidationError
from sentry.interfaces.schemas import validate_and_default_interfac... |
"""
bank.accounts
~~~~~~~~~~~~~
This module contains code for managing accounts.
"""
from .cards import Card
from .exceptions import InsufficientBalance, AccountError, ExceedsLimit
import time, datetime
class Account:
"""
Base class for accounts, handles balances & transactions.
:param account_id: Unique... |
#!/usr/bin/python3
# alert.py
import math
from data import mongo
from data import gdacs
from data import wildfires
import geopy.distance
import pymongo
from time import sleep
from datetime import datetime
from config import MONGODB_USER, MONGODB_PASS
def monitor_danger(time_threshold=5 * 60, distance_thresholds={"hu... |
# diffhelpers.py - pure Python implementation of diffhelpers.c
#
# Copyright 2009 Matt Mackall <mpm@selenic.com> and others
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
def addlines(fp, hunk, lena, lenb, a, b):
while True... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'BachelorETL.settings')
try:
from django.core.management import execute_from_command_line
except ... |
#!/usr/bin/env python
NAME = 'Teros WAF'
def is_waf(self):
# credit goes to W3AF
return self.matchcookie('^st8id=') |
import spotify_manager
import re as re
from functools import lru_cache
MENU_PAGE_SIZE = 6
# Screen render types
MENU_RENDER_TYPE = 0
NOW_PLAYING_RENDER = 1
SEARCH_RENDER = 2
# Menu line item types
LINE_NORMAL = 0
LINE_HIGHLIGHT = 1
LINE_TITLE = 2
spotify_manager.refresh_devices()
class LineItem():
def __init_... |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure tha... |
from miscellanies.torch.distributed import is_main_process
from contextlib import nullcontext
import torch.distributed
from miscellanies.torch.distributed import is_dist_available_and_initialized, get_world_size
import socket
import pprint
import os
from miscellanies.yaml_ops import load_yaml
from .sweep_utils import p... |
'''Some helper functions for PyTorch, including:
- get_mean_and_std: calculate the mean and std value of dataset.
- msr_init: net parameter initialization.
- progress_bar: progress bar mimic xlua.progress.
'''
import os
import sys
import time
import math
import torch
import torch.nn as nn
import torch.nn.in... |
# -*- coding: utf-8 -*-
"""
@author: Jonathan Massey
@description: Compute the PCA of a flow field
@contact: jmom1n15@soton.ac.uk
"""
from torch import pca_lowrank |
# Copyright (c) 2018 Aaron LI <aly@aaronly.me>
# MIT License
"""
Custom Ansible template filters to crypt/hash passwords.
"""
import os
import base64
import crypt
import hashlib
def cryptpass(p):
"""
Crypt the given plaintext password with salted SHA512 scheme,
which is supported by Linux/BSDs.
"""
... |
from pyramid.settings import asbool
from magpie.constants import get_constant
from magpie.utils import get_logger
LOGGER = get_logger(__name__)
def includeme(config):
from magpie.ui.management.views import ManagementViews
LOGGER.info("Adding UI management...")
config.add_route(ManagementViews.view_group... |
from django.urls import path
import report.views
app_name = 'report'
urlpatterns = [
path('', report.views.ReportView.as_view(), name='report'),
] |
import sys
import pytest
if sys.version_info > (3, 0):
import unittest.mock as mock
else:
import mock
class MatchApiContext(object):
def __init__(self, mock_context):
self._mock_context = mock_context
self._expected_response = {'has_value': 'yes', }
mock_response = mock.MagicMoc... |
class Solution:
def validPalindrome(self, s: str) -> bool:
deleted = 0
left, right = 0, len(s) - 1
while left < right:
if s[left] == s[right]:
left += 1
right -= 1
else:
deleted += 1
if deleted >= 2:
... |
#!/usr/bin/env python2
# Copyright (c) 2015 The Bitcoin Core developers
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
from test_framework.test_framework import ComparisonTestFramework
from test_framework.util import *
from... |
import torch
import torch.nn.functional as F
from torch import FloatTensor, LongTensor, Tensor
from typing import Dict, Tuple
from . import ModelOut
from .ops import act, ones, zeros, reshape_as
from torch import nn
Batch = Tuple[FloatTensor, LongTensor]
def activation_loss(x: Tensor, y: LongTensor) -> Tensor:
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-07-26 15:01
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tasks', '0002_many_to_many_for_conditions'),
]
operations = [
migrations.Alter... |
"""
WTForms-Alchemy
---------------
Generates WTForms forms from SQLAlchemy models.
"""
from setuptools import setup
import os
import re
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
PY3 = sys.version_info[0] == 3
def get_version():
filename = os.path.join(HERE, 'wtforms_alchemy', '__init__.py'... |
# -*- coding: utf-8 -*-
import luigi
import requests
class downloader(luigi.Task):
filepath = luigi.Parameter()
url = luigi.Parameter()
def output(self):
return luigi.LocalTarget(self.filepath, format=luigi.format.Nop)
def run(self):
r = requests.get(self.url)
with self.outp... |
# to run basic test for all envs
import inspect
from gridworld.utils.wrapper.wrappers import ImageInputWarpper
from gridworld.utils.test_util import *
import gridworld
import os
import importlib
from gridworld.envs.fourrooms import FourroomsBase
path = os.path.dirname(__file__)
envs_path = os.path.join(path, 'gridwor... |
# -*- coding: utf8 -*-
__author__ = 'Aleksandrov Oleg, 4231'
from PDFGenDAOPostgres import PDFGenDAOPostgres
from PDFGenDAOMySQL import PDFGenDAOMySQL
import settings
class FormData:
__dao = None
__qs = []
__small_qr = []
__version = "0.1"
__id_user = "null"
__id_owner = "null"
__id_premis... |
# Copyright 2018 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... |
"""Utility functions."""
import h5py
import numpy as np
from torch.utils import data
def save_dict_h5py(data, fname):
"""Save dictionary containing numpy arrays to h5py file."""
with h5py.File(fname, 'w') as hf:
for key in data.keys():
hf.create_dataset(key, data=data[key])
def load_di... |
from collections import defaultdict
import graphene
from django.core.exceptions import ValidationError
from django.db.utils import IntegrityError
from ....core.permissions import ShippingPermissions
from ....core.tracing import traced_atomic_transaction
from ....product import models as product_models
from ....shippi... |
#!/usr/bin/env python3
"""
Tests of ktrain text classification flows
"""
import sys
import os
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID";
os.environ["CUDA_VISIBLE_DEVICES"]="0"
sys.path.insert(0,'../..')
import IPython
from unittest import TestCase, main, skip
import numpy as np
import ktrain
from ktrain import text ... |
# Copyright (C) 2019 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
from os.path import abspath, dirname, join
import collections
import ddt
from flask.json import dumps
from ggrc.converters import get_importables
from ggrc.models import inflector, all_models
from ggrc.mode... |
#!/bin/env python2.7
# import the two lookup tables from the excel file
# This requires xlrd.
# 1) open terminal
# 2) pip install xlrd
# if you get "ImportError", pip install -U pip setuptools then repeat
import sqlite3 # provides python with a library for sqlite
import xlrd
SQLITE_FILE = "UKRoadData.sqlite"
# opens... |
# -*- coding: utf-8 -*-
#
# 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 writing, software
... |
from . import tritam_tracking
from . import tritam_api_constant
from . import tritam_sms |
from qtpy import compat
from glue import config
def export_data(data, components=None, exporter=None):
if exporter is None:
exporters = {}
for e in config.data_exporter:
if e.extension == '':
fltr = "{0} (*)".format(e.label)
else:
fltr = "{0... |
import tensorflow as tf
def cov(x):
mean_x = tf.reduce_mean(x, axis=0, keepdims=True)
mx = tf.matmul(tf.transpose(mean_x), mean_x)
vx = tf.matmul(tf.transpose(x), x) / tf.cast(tf.shape(x)[0], tf.float64)
cov_xx = vx - mx
return cov_xx
def inv_cov(x):
return tf.linalg.inv(cov(x)) |
class ReadTimeout(Exception):
pass
class FatalError(Exception):
pass
class SynchronizationError(Exception):
pass
class PayloadOverflow(Exception):
pass
class ConnectionLost(Exception):
pass |
from polymath import UNSET_SHAPE, DEFAULT_SHAPES
import builtins
import operator
from collections import OrderedDict, Mapping, Sequence, deque
import functools
from numbers import Integral, Rational, Real
import contextlib
import traceback
import uuid
import numpy as np
import importlib
from .graph import Graph
from .d... |
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'f_monthpython.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ... |
import argparse
import os
import time
from typing import List, Optional
import glob
from multiprocessing import Process
import numpy as np
from astropy.io import fits
from pkg_resources import resource_filename
from pypeit.pypeitsetup import PypeItSetup
from pypeit.core import framematch
from pypeit import pypeit
fr... |
from operator import attrgetter
import pyangbind.lib.xpathhelper as xpathhelper
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType
from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType
from pyangbind.lib.base import PybindBase
from de... |
# Generated by Django 3.2.4 on 2021-07-01 01:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('recipes', '0003_alter_recipe_description'),
]
operations = [
migrations.AddField(
model_name='recipe',
name='difficu... |
"""
Dogstatsd tasks
"""
from __future__ import print_function, absolute_import
import os
import shutil
from distutils.dir_util import copy_tree
import invoke
from invoke import task
from invoke.exceptions import Exit
from .build_tags import get_build_tags, get_default_build_tags
from .utils import get_build_flags, b... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from... |
import time
import random
import RPi.GPIO as GPIO
import Adafruit_WS2801
import Adafruit_GPIO.SPI as SPI
class RhapsodyPixels:
numpixels = 0
myPixels = None
pixel_groups = None
def __init__(self, numpixels):
self.numpixels = numpixels
self.pixel_groups = dict()
self.myPixels ... |
import asyncio
async def sleep_task(num):
for i in range(5):
print(f'process task: {num} iter: {i}')
await asyncio.sleep(1)
return num
loop = asyncio.get_event_loop()
task_list = [loop.create_task(sleep_task(i)) for i in range(2)]
loop.run_until_complete(asyncio.wait(task_list))
loop.run_until... |
# Importando funções.
from random import randint
from time import sleep
from operator import itemgetter
# Declarando os dicionários.
jogadores = dict()
colocacao = list()
# Colocando os jogadores e seus valores no dicionário, e mostrando eles na tela.
for r in range(1, 5):
jogadores[f'jogador{r}'] = randint(1, 6)... |
import logging
from typing import Optional
import requests
from mtp_common import nomis
from prison.models import Prison, PrisonerLocation
logger = logging.getLogger('mtp')
def fetch_prisoner_location_from_nomis(prisoner_location: PrisonerLocation) -> Optional[PrisonerLocation]:
new_location = None
try:
... |
# Generated by Django 3.1.11 on 2021-07-23 09:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("evaluation", "0008_evaluation_input_prefixes"),
]
operations = [
migrations.RemoveField(model_name="submission", name="creators_ip",),
... |
# Copyright 2021 AI Singapore
#
# 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... |
# Copyright 2021 ONDEWO GmbH
#
# 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 writing, ... |
"""
CryptoAPIs
Crypto APIs 2.0 is a complex and innovative infrastructure layer that radically simplifies the development of any Blockchain and Crypto related applications. Organized around REST, Crypto APIs 2.0 can assist both novice Bitcoin/Ethereum enthusiasts and crypto experts with the development of thei... |
import numpy as np
from gym.envs.mujoco import AntEnv as AntEnv_
class AntEnv(AntEnv_):
@property
def action_scaling(self):
if (not hasattr(self, 'action_space')) or (self.action_space is None):
return 1.0
if self._action_scaling is None:
lb, ub = self.action_space.low,... |
# Copyright (c) 2021, NVIDIA CORPORATION.
from decimal import Decimal
import pyarrow as pa
import pytest
from cudf.core.column import DecimalColumn
@pytest.mark.parametrize(
"data",
[
[Decimal("1.1"), Decimal("2.2"), Decimal("3.3"), Decimal("4.4")],
[Decimal("-1.1"), Decimal("2.2"), Decimal... |
fade_old_max_wait = 1 # Wait no more than this many seconds to fade out old action
import kivy
kivy.require('1.9.0')
from kivy.animation import Animation
from kivy.clock import Clock
class Action:
def __init__(self, action, old_action, client):
self.action = action
self.old_action = old_action
... |
#Importamos la librería random para el flip de la moneda
import random
print("\tWelcome to the Coin Toss App")
#Pedimos la cantidad de veces que se va tirar la moneda
flip = int(input("How many times would you like me to flip the coin: "))
r = input("Would you like to see the result of each flip (y/n): ").lower()
#Crea... |
'''
Created on Sat Nov 05 2016
Copyright (c) 2016 Leniel Macaferi's Consulting
'''
import os
import pandas as pd
from sklearn.naive_bayes import GaussianNB
from sklearn.model_selection import cross_val_score
path = os.path.realpath('..')
# Loading the data used to train
trainingSet = pd.read_csv(os.path.join(p... |
"""
Testing script to check edge cases for word_pattern.py
"""
import unittest
from word_pattern import Solution
class WordPatternTests(unittest.TestCase):
"""
Test suite to check edge cases for word patterns.
"""
def test_small_valid_word_pattern(self):
self.assertTrue(Solution().word_patt... |
# -*- coding: utf-8 -*-
#
# pymatgen documentation build configuration file, created by
# sphinx-quickstart on Tue Nov 15 00:13:52 2011.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# Al... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import time
from six.moves import xrange
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "1"
import numpy as np
import tensorflow as tf
import utils
from model import Config, BiRNN
tf.flags.DEFINE_string("... |
import logging
from datetime import timedelta
from sqlalchemy.sql import func, select
from couchers import email, urls
from couchers.config import config
from couchers.constants import EMAIL_TOKEN_VALIDITY
from couchers.crypto import urlsafe_secure_token
from couchers.db import session_scope
from couchers.models impo... |
"""
Python Interchangeable Virtual Instrument Library
Copyright (c) 2016-2017 Alex Forencich
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... |
from solutions.SUM import sum_solution
class TestSum():
"""Class to test sum_solution"""
def test_sum(self):
"""Happy path test"""
assert sum_solution.compute(1, 2) == 3
def test_check_bounds(self):
"""Raise value error if integer passed in is out of limit"""
try:
... |
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '9u1))8ol#(lg^cyoxbw4-+50uue^a+p%vdsfv%$^#$^&gbg6346sddfbg^$%dsn+_t#9y)yjl4!%r)bv'
... |
# coding=utf-8
import datetime
import os
import traceback
os.environ['DJANGO_SETTINGS_MODULE'] = 'ace_office.settings'
from config.conf_core import *
from django.utils import timezone
from apscheduler.schedulers.background import BackgroundScheduler
from modules.system.models import SystemConfig, DataBackup
from modul... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
import sys
import traceback
from telegram import ParseMode
from . import menus, keyboards
from ..sources import wf, twitch
from ..utils import utils
from ..utils.logging import logger
from ..utils.loadconfig import config
warframe = wf.Warframe()
tw = twitch.Twitch()
... |
#!/usr/bin/env python
import unittest
import rclpy
from rclpy.executors import MultiThreadedExecutor, SingleThreadedExecutor
from flexbe_core import EventState, OperatableStateMachine
from flexbe_core.core.exceptions import StateError, StateMachineError, UserDataError
class TestExceptions(unittest.TestCase):
def... |
%pylab inline
from scipy import *
import sys, time
from pybrain.rl.environments.mazes import Maze, MDPMazeTask
from pybrain.rl.learners.valuebased import ActionValueTable
from pybrain.rl.agents import LearningAgent
from pybrain.rl.learners import Q, SARSA
from pybrain.rl.experiments import Experiment
from pybrain.rl.... |
import operator
import warnings
import numpy as np
import pytest
import pandas as pd
from pandas import (
Categorical,
DataFrame,
Series,
date_range,
)
import pandas._testing as tm
from pandas.tests.arrays.categorical.common import TestCategorical
class TestCategoricalOpsWithFactor(TestCategorical):... |
import os
from glob import glob
from pathlib import Path
import torch
_root_dir = os.path.dirname(os.path.abspath(__file__))
ROOT_PATH = Path(_root_dir).parent.parent
def mkdir_ifnotexists(directory):
if not os.path.exists(directory):
os.mkdir(directory)
def get_class(kls):
parts = kls.split('.')
... |
import os
import functools
import textwrap
from conans.errors import ConanInvalidConfiguration
from conans import ConanFile, CMake, tools
required_conan_version = ">=1.33.0"
class PranavCSV2Conan(ConanFile):
name = "pranav-csv2"
license = "MIT"
description = "Various header libraries mostly future std li... |
# https://adventofcode.com/2019/day/2
#
# --- Day 2: 1202 Program Alarm ---
#
#
#
def readOpCode(op):
if op == 1:
print("add")
return
elif op == 2:
print("mul")
elif op == 99:
print("break")
intInput = [1,9,10,3,2,3,11,0,99,30,40,50]
def loadintCode(fname='input'):
... |
# 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... |
class UPIValidation:
end_point = "/payout/v1/validation/upiDetails"
req_type = "GET"
def __init__(self, **kwargs):
self.name = kwargs["name"]
self.vpa = kwargs["vpa"] |
import os
import shutil
from pathlib import Path
import yaml
# gui home paths
from core.gui import themes
HOME_PATH = Path.home().joinpath(".coretk")
BACKGROUNDS_PATH = HOME_PATH.joinpath("backgrounds")
CUSTOM_EMANE_PATH = HOME_PATH.joinpath("custom_emane")
CUSTOM_SERVICE_PATH = HOME_PATH.joinpath("custom_services")... |
# =========================================================================
# Copyright 2021-present ShanHe, Inc.
# -------------------------------------------------------------------------
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this work except in compliance with the Licens... |
from __future__ import print_function
from ctypes import c_int
BASE = int(1e9 + 7)
class TreeMatrix:
def __init__(self, N):
self.mat = (c_int * ((N + 1) * (N + 1)))()
self.N = N
@staticmethod
def lowbit(x):
return x & (-x)
def add(self, x, y, val):
x, y = x + 1, y +... |
"""Download example datasets from https://github.com/pyansys/example-data"""
import shutil
import os
import urllib.request
EXAMPLE_REPO = "https://github.com/pyansys/example-data/raw/master/result_files/"
def delete_downloads():
"""Delete all downloaded examples to free space or update the files"""
from ansy... |
# Copyright 2020 Huy Le Nguyen (@usimarit)
#
# 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 t... |
from django.core.management.base import BaseCommand
from apps.cms.models import Content
from apps.cms.presets import CONTENT_PRESETS
class Command(BaseCommand):
help = "Initialize cms data from hardcoded presets"
def handle(self, *args, **kwargs):
for content_type, value in CONTENT_PRESETS.items():
... |
import subprocess
import re
import os
from ajenti.api import plugin
from ajenti.api.sensors import Sensor
from ajenti.plugins.dashboard.api import ConfigurableWidget
@plugin
class SMARTSensor (Sensor):
id = 'smart'
timeout = 5
def get_variants(self):
r = []
for s in os.listdir('/dev'):
... |
from openslides_backend.permissions.permissions import Permissions
from tests.system.action.base import BaseActionTestCase
class PollDeleteTest(BaseActionTestCase):
def test_delete_correct(self) -> None:
self.set_models({"poll/111": {"meeting_id": 1}, "meeting/1": {}})
response = self.request("pol... |
import torch
from torch_geometric.nn import SGConv
def test_sg_conv():
in_channels, out_channels = (16, 32)
edge_index = torch.tensor([[0, 0, 0, 1, 2, 3], [1, 2, 3, 0, 0, 0]])
num_nodes = edge_index.max().item() + 1
x = torch.randn((num_nodes, in_channels))
conv = SGConv(in_channels, out_channels... |
#! /usr/bin/env python
"""Run a YOLO_v2 style detection model on test images."""
import argparse
import colorsys
import imghdr
import os
import random
import numpy as np
from keras import backend as K
from keras.models import load_model
from PIL import Image, ImageDraw, ImageFont
from yad2k.models.keras_yolo import y... |
import logging
from .util import get_timestamp
logger = logging.getLogger(__name__)
class Set(object):
def __init__(self, name, sparseDataStrategy='None', unit='', tags=[]):
self.name = name
self.sparseDataStrategy = sparseDataStrategy
self.unit = unit
self.tags = tags
s... |
import os
import numpy as np
from gym import spaces
import mujoco_py
from gym_kuka_mujoco.envs.assets import kuka_asset_dir
from gym_kuka_mujoco.utils.quaternion import identity_quat, subQuat, quatAdd, mat2Quat
from gym_kuka_mujoco.utils.kinematics import forwardKinSite, forwardKinJacobianSite
from .base_controller i... |
from dagger.pipeline.io import IO
from dagger.utilities.config_validator import Attribute
class AthenaIO(IO):
ref_name = "athena"
@classmethod
def init_attributes(cls, orig_cls):
cls.add_config_attributes(
[
Attribute(
attribute_name="schema", comme... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.