content stringlengths 5 1.05M |
|---|
#NAME: move.py
#DATE: 12/11/2018
#AUTH: Ryan McCartney, EEE Undergraduate, Queen's University Belfast
#DESC: A python class for moving the wheelchair in an intuative manner
#COPY: Copyright 2018, All Rights Reserved, Ryan McCartney
import numpy as np
import threading
import time
import requests
import pygame
from req... |
from django.conf.urls import url
from app_one import views
app_name = 'app_one'
urlpatterns = [
url(r"^$", views.TaskList.as_view(), name="task_list"),
url(r"^task/new/$", views.CreateTask.as_view(), name="create_task"),
url(r"^task/update/(?P<pk>\d+)/$",
views.UpdateTask.as_view(), nam... |
import random
import os
import sys
import hashlib
from flask import request
import app
__alpha__ = [ 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', 'a', 's', 'd',
'f', 'g', 'h', 'j', 'k', 'l', 'z', 'x', 'c', 'v', 'b', 'n', 'm',
'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', 'A', 'S', 'D',
... |
from trio_websocket import ConnectionClosed
import logging as log
#log.basicConfig(level=log.DEBUG)
async def message_gen(ws):
while True:
try:
msg = await ws.get_message()
log.debug("Got message: %s"% msg)
yield msg
except ConnectionClosed:
log.info(... |
"""
The MIT License (MIT)
Copyright (c) 2020 Shaun Barlow
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,... |
#! python 3.6
# Create Date: 2019-07-29
# Author: Scc_hy
# Function: 堆排序 HeapSort
# 加载包
from .data import get_data
from .data import get_figure2draw
def big_endian(ds, root, end):
"""
将堆的末端子节点作调整,使得子节点永远小于父节点
:param: ds get_figure2draw
:param: root int 开始(list index)
:param: end int 结束(li... |
from torch.nn.modules.module import Module
import torch
import numpy as np
from torch.autograd import Variable
from ..functions.GANet import MyLoss2Function
from ..functions.GANet import MyLossFunction
from ..functions.GANet import SgaFunction
from ..functions.GANet import LgaFunction
from ..functions.GANet import Lga... |
from rest_framework import serializers
from .models import Tweet, Hashtag
class HashtagSerializer(serializers.ModelSerializer):
"""
Serializing all the Hashtags
"""
class Meta:
model = Hashtag
fields = ('name',)
class TweetSerializer(serializers.ModelSerializer):
"""
Seriali... |
# -*- coding: utf-8 -*-
import unittest
from pyparsing import ParseException
from cwr.grammar.field import basic
"""
Tests for Alphanumeric (A) fields.
The following cases are tested (all tests are done for default and compulsory fields):
- Default name is set correctly
- Given name is set correctly
- Creating a n... |
import datetime
from protector.query.query import Query
from protector.influxdb.keyword import Keyword
from protector.influxdb.time_expression import TimeExpression
class SelectQuery(Query):
"""
Construct new InfluxDB select statement object
"""
# QUERY KEYS
OPTIONAL_KEY_WHERE_STMT = 'where_stmt'... |
from __future__ import absolute_import
from rest_framework.response import Response
from sentry.api.base import DocSection, Endpoint
from sentry.api.bases.group import GroupPermission
from sentry.api.serializers import serialize
from sentry.models import Event
class EventDetailsEndpoint(Endpoint):
doc_section =... |
#!/usr/bin/env python
# Copyright (c) 2020-2021 VMware, Inc. All Rights Reserved.
# SPDX-License-Identifier: BSD-2 License
# The full license information can be found in LICENSE.txt
# in the root directory of this project.
import logging
import os
import sqlite3
import unittest
import uuid
from lydian.apps.rules impo... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
def warn(*args, **kwargs):
pass
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.db.models import Q
from django.core.files.storage import FileSystemStorage
#his=[]
#from .models import *
def upload_OD(request):
defa... |
from django.core.management import BaseCommand
from ._streams import create_streams
class Command(BaseCommand):
help = 'Adds some sample streams'
def handle(self, *args, **options):
create_streams()
self.stdout.write(self.style.SUCCESS('Successfully created streams'))
|
# Import things
from flask import Flask, json , jsonify, request
import mysql.connector as mysql
from flask_cors import CORS
import datetime
def createDBConnection():
# Create a connection to the database
db = mysql.connect(
host = "SQL-SERVER",
user = "SQLL-USERNAME",
passwd =... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import matplotlib.pyplot as plt
import tweepy
import re
import sys,csv
import pandas as pd
import numpy as np
import os
import nltk
import pycountry
import string
# In[2]:
from textblob import TextBlob
class SentimentAnalysis:
def __init__(self):
self.... |
import timeit
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def timed_run(function, count, length, min_sequence_length, max_sequence_length) -> float:
return timeit.timeit(
stmt="{}(input_list=input_list, min_sequence_length={}, max_sequence_length={})"
... |
import datasets
if __name__ == '__main__':\
datasets.Sprites('./data/', train=True, transform=None) |
import unittest
import pytest
import numpy as np
from extra_foam.algorithms.azimuthal_integ import (
AzimuthalIntegrator, ConcentricRingsFinder, energy2wavelength, compute_q
)
class TestAzimuthalIntegrationMisc(unittest.TestCase):
def testEnergyToWavelength(self):
# 12.4 keV -> 1 A
self.asse... |
# -*- coding: UTF-8 -*-
# Copyright (c) 2019 PaddlePaddle 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
#
... |
# The Expat License
#
# Copyright (c) 2017, Shlomi Fish
#
# 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, ... |
## Fake responses for testing
tiled = b'''<?xml version="1.0"?>
<inventory>
<url>https://e4ftl01.cr.usgs.gov//MODV6_Cmp_B/MOLT/MOD13A2.006/2000.02.18/MOD13A2.A2000049.h18v06.006.2015136104646.hdf</url>
<url>https://e4ftl01.cr.usgs.gov//MODV6_Cmp_B/MOLT/MOD13A2.006/2000.03.05/MOD13A2.A2000065.h18v06.006.2015136022922.h... |
"""MIT License
Copyright (c) 2021 gunyu1019
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, publish, dist... |
from docsie_universal_importer.providers.base import StorageTreeRequestSerializer, DownloaderRequestSerializer
class DropboxStorageTreeRequestSerializer(StorageTreeRequestSerializer):
pass
class DropboxDownloaderSerializer(DownloaderRequestSerializer):
pass
|
from docx import Document
from docx.shared import Cm
from docx.enum.section import WD_ORIENT
import os
import get_qlik_sense
import shutil
import sys
import argparse
import datetime
from clint.textui import progress
year = datetime.date.today().year
month = datetime.date.today().month
day = datetime.d... |
# auth.py
from flask import Blueprint, render_template, redirect, url_for, request, flash, g
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import login_user, logout_user, login_required, current_user
from models import User
from common import db
auth_blueprint = Bl... |
import zmq
import threading
import pickle
import json
def thread_send():
context = zmq.Context()
socket = context.socket(zmq.PUSH)
socket.setsockopt(zmq.SNDHWM, 100)
socket.bind('tcp://*:5557')
id = 0
while True:
task_id = "{}".format(id)
with open('./data/dog.jpg','rb') as f:
... |
# python3
from collections import namedtuple
Bracket = namedtuple("Bracket", ["char", "position"])
def find_mismatch(text):
stack = []
for i, char in enumerate(text):
val = Bracket(char, i + 1)
if val[0] in '([{':
stack.append(val)
else:
if val[0] in '}])':
... |
#!/usr/bin/env python3
# coding=utf-8
import sys
import requests
import yaml
from pathlib import Path
from loguru import logger
class YuQue:
def __init__(self, token):
self.token = token
self.uri = 'https://www.yuque.com/api/v2'
logger.info("TOKEN:{}", self.token)
def _get(self, url, ... |
import graphene
from graphene_django.converter import convert_django_field
from taggit.managers import TaggableManager
from dcim.fields import MACAddressField, WWNField
from ipam.fields import IPAddressField, IPNetworkField
@convert_django_field.register(TaggableManager)
def convert_field_to_tags_list(field, registr... |
#!/usr/bin/env python
#!/usr/bin/env python
# Paging
PAGE_SIZE = 15
# Cache
CACHE_EXPIRATION_QUICK = 60
CACHE_EXPIRATION_SHORT = 60 * 60 * 4
CACHE_EXPIRATION_MEDIUM = 60 * 60 * 12
CACHE_EXPIRATION_LONG = 60 * 60 * 24
CACHE_PAGE_MAX = 10
# User Types
USER_TYPE_SEEKER = "student"
USER_TYPE_TALENT = "admin"
USER_TYPES ... |
"""
Copyright 2014 Rackspace
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
dist... |
# -*- coding: utf-8 -*-
import pytz
from django.contrib.auth import get_user_model
from django.contrib.postgres.fields import JSONField
from django.contrib.postgres.indexes import BrinIndex
from django.db import models
from django.urls import reverse
from django.utils.translation import ugettext_lazy as _
class Devic... |
import socket
def clientFunc():
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
text = 'I love jingjing'
data = text.encode()
#send
sock.sendto(data, ('127.0.0.1', 7852))
data, addr = sock.recvfrom(200)
data = data.decode()
print(data)
if __name__ == '__main__':
clientFunc... |
from os_urlpattern.parsed_piece_view import (FuzzyView, LastDotSplitFuzzyView,
LengthView, MixedView, MultiView,
PieceView, view_cls_from_pattern)
from os_urlpattern.pattern import Pattern
def test_view_cls_from_pattern():
d... |
from collections import defaultdict
class Solution:
"""
@param list_of_set: Initial list of set
@return: The final number of sets
"""
def setUnion(self, list_of_set):
# Write your code here
if not list_of_set or len(list_of_set) == 0:
return 0
self.forward_dict... |
from enum import Enum
__NAMESPACE__ = "http://www.opengis.net/gml"
class GraphTypeType(Enum):
"""
Graph-specific styling property.
"""
TREE = "TREE"
BICONNECTED = "BICONNECTED"
|
import re
text = 'This is some text -- with punctuation.'
pattern = 'is'
print('Text :', text)
print('Pattern:', pattern)
m = re.match(pattern, text)
print('Match :', m)
s = re.search(pattern, text)
print('Search :', s) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from hearing_screening import db
import datetime
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
input_code = db.Column(db.String(128), nullable=False)
passed_screening = db.Column(db.Boolean, default=False)
created = db.Column(db.Date... |
from rest_framework import generics
from ..serializers import reference
from ...models import (
Nationality,
NativeLanguage,
Citizenship,
TrainingDirection,
)
class TrainingDirectionList(generics.ListCreateAPIView):
"""
Список национальностей
"""
queryset = TrainingDirection.objects.a... |
versions = {
'api_version': 'v2',
'application_version': '2.0'}
|
# 220. Contains Duplicate III
# ttungl@gmail.com
# Given an array of integers, find out whether there are two distinct indices i and j
# in the array such that the absolute difference between nums[i] and nums[j] is
# at most t and the absolute difference between i and j is at most k.
class Solution(object):
def... |
"""
Various helper methods for topography
"""
def euclidian_distance(ptA, ptB):
"""
Returns the shortest path distance between the two Points
"""
if (ptA.X != ptB.X or ptA.Y != ptB.Y):
return ( (ptA.X - ptB.X)**2 + (ptA.Y - ptB.Y)**2 ) ** (1/2)
return 0.0
|
# -*- coding: utf-8 -*-
from scrapy.spiders import Spider
from scrapy.selector import Selector
from gorden_crawler.items import BaseItem, ImageItem, SkuItem, Color
from scrapy import Request
from scrapy_redis.spiders import RedisSpider
from urllib import quote
import re
import execjs
from scrapy.utils.response import... |
# Copyright 2016 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... |
from bs4 import BeautifulSoup
import pandas as pd
import numpy as np
import os
import re
import requests
## Dates for data from archive.org
dates = ['20180718125608', '20170713111636', '20160716091733', '20150706182249' ]
## Listing the football seasons from the dates the data was gathered
seasons = [int(i[:... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 16 18:48:39 2021
Copyright 2021 Cyriaque Perier
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
Unles... |
"""Defines a generator network for MNIST."""
import numpy as np
import torch
from torch import nn
from utils import get_norm_layer, init_net, choose_rand_patches, Patch2Image, RandomCrop
class Reshape(nn.Module):
def __init__(self, *args):
super(Reshape, self).__init__()
self.shape = args
d... |
from vk_bot.core.modules.basicplug import BasicPlug
from bs4 import BeautifulSoup
import requests
class Lurk(BasicPlug):
command = ("лурк",)
doc = "Поиск по лукру. Аналогично вики"
def main(self):
text = " ".join(self.text[1:])
url = f"http://lurkmore.to/{text}"
req = requests.get... |
# -*- coding: utf-8 -*-
'''
###################################################
# WARNING
# project documentation build configuration file
# This file is modified and is a template copy
# generated by project_quickstart
# Run sphinx-quickstart to start from scratch
###################################################
... |
"""Adding a field to track category keywords
Revision ID: 391a19c44a98
Revises: 2c5bd010030f
Create Date: 2015-04-04 23:32:06.075000
"""
# revision identifiers, used by Alembic.
revision = '391a19c44a98'
down_revision = '2c5bd010030f'
from alembic import op
import sqlalchemy as sa
... |
"""
@author: Gabriele Girelli
@contact: gigi.ga90@gmail.com
"""
import argparse
from joblib import cpu_count, delayed, Parallel # type: ignore
import logging
import os
from radiantkit import argtools as ap
from radiantkit import image, path
import re
import sys
def init_parser(subparsers: argparse._SubParsersAction... |
from validation import vworkspace
with vworkspace() as w:
w.props.memory_effects_only = False
w.all_functions.validate_phases("internalize_parallel_code")
|
#!/usr/bin/env python
#
# Copyright (C) 2016 The Android Open Source Project
#
# 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 req... |
"""
IMAGE PROCESSING HW3.
ASHENA G.MOHAMMADI
"""
# %% IMPORT MODULES
import os
from sklearn.model_selection import train_test_split, KFold
from sklearn.metrics import confusion_matrix, classification_report
import numpy as np
import pandas as pd
import PIL as pil
import keras
import matplotlib.pyplot as plt
... |
bl_info = {
"name": "Quake 3 Model (.md3)",
"author": "Vitaly Verhovodov",
"version": (0, 2, 1),
"blender": (2, 72, 0),
"location": "File > Import-Export > Quake 3 Model",
"description": "Quake 3 Model format (.md3)",
"warning": "",
"wiki_url": "http://wiki.blender.org/index.php/Extensio... |
#!/usr/bin/env python
import StringIO
import subprocess, shlex
import os
import time
from datetime import datetime, time, timedelta
from PIL import Image
import ImageChops
from hotqueue import HotQueue
import redis
import json
from time import sleep
import sys, gc
import ephem
import signal
import pipan
# Initialise... |
from .bbox_head import BBoxHead
from .convfc_bbox_head import ConvFCBBoxHead, SharedFCBBoxHead
from .double_bbox_head import DoubleConvFCBBoxHead
from .gcn_bbox_head import GCNBBoxHead
__all__ = [
'BBoxHead', 'ConvFCBBoxHead', 'SharedFCBBoxHead', 'DoubleConvFCBBoxHead', 'GCNBBoxHead'
]
|
from django.apps import AppConfig
from django.conf import settings
from django.test.signals import setting_changed
from two_factor.plugins.registry import registry
class TwoFactorPhoneNumberConfig(AppConfig):
name = 'two_factor.plugins.phonenumber'
verbose_name = "Django Two Factor Authentication – Phone Met... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
from ..core import get_core_context
from .defines import ENGINE_NAME
def get_job_engine():
return get_core_context().lookup(ENGINE_NAME)
__all__ = ['get_job_engine']
|
import settings
from handler import Handler
from models import JpFamily
from models import EnFamily
import util
from handler import select_font
# page to layout all blogs
class Sort(Handler):
@select_font
def get(self, lang):
# insert font to en database
select_lang = lang
if lang == '... |
#!/usr/bin/env python
# (C) Copyright IBM Corporation 2004
# All Rights Reserved.
#
# 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
# on the... |
from django.template import Library
from evap.evaluation.models import Semester
register = Library()
@register.inclusion_tag("results_semester_menu.html")
def include_results_semester_menu():
return dict(semesters=Semester.get_all_with_published_courses())
|
# File: character_select.py
# Authors: BearsOnUnicycles
# Since: 4/18/18
# This module handles the character selection screen, and once both players have select
# it then loads the arena with the chosen characters
from src import engine, input_handler as ih, game_objects, scenes
INPUT = ih.Handler()
BOXES = {'box1':... |
from .. import Provider as ColorProvider
class Provider(ColorProvider):
pass
|
import random
import turtle
def shoot(radius):
distance = random.randrange(0, radius+50) # Generate a random number between 0 and radius+50 that will represent the arrow distance. 50 will be the margin of error
angle = random.randrange(0,360) # Generate the angle which the arrow will be shoot
... |
import os
from flask import Flask
def import_blueprints() -> None:
global admin_blueprint
global core_blueprint
global user_blueprint
global err_blueprint
from admin.views import admin_blueprint
from core.views import core_blueprint
from users.views import user_blueprint
from err_page... |
import numpy as np
from traits.api import (HasTraits, Instance, Float, Enum, Int, Property,
cached_property, Any)
from traitsui.api import View, HSplit, ToolBar, Action, Item, VGroup
from pyface.api import ImageResource
from enable.api import ComponentEditor
from chaco.api import (create_line_p... |
#
# -------------------------------------------------------------------------
#
# Part of the CodeChecker project, under the Apache License v2.0 with
# LLVM Exceptions. See LICENSE for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#
# -------------------------------------------------... |
import logging
import json
import requests
from datetime import datetime
from quantumleapclient.exceptions import QuantumLeapClientException
logger = logging.getLogger(__name__)
fmt = "%(asctime)s|%(levelname)s |%(name)s:%(funcName)s:%(lineno)s-%(message)s"
class Client(object):
def __init__(self, host='loca... |
import time
import sys
from datetime import datetime, timedelta
from pytest import raises
from thespian.test import *
from thespian.actors import *
from thespian.troupe import troupe, UpdateTroupeSettings
max_listen_wait = timedelta(seconds=6.5)
max_ask_wait = timedelta(seconds=2.5)
class Bee(Actor):
def rece... |
#!/bin/python3
"""
A linked list is said to contain a cycle if any node is visited more than once while traversing the list.
Complete the function provided for you in your editor.
It has one parameter: a pointer to a Node object named head that points to the head of a linked list.
Your function must return a boolean de... |
import numpy as np
import scipy as sp
import pylab as plt
def gen_grid(nx,ny,nz):
i_f=np.arange(nx)
i_c=np.arange(nx)+0.5
j_f=np.arange(ny)
j_c=np.arange(ny)+0.5
dxx=dyy=2e3
dx=np.ones((ny,nx))*dxx
dy=np.ones((ny,nx))*dyy
x_f=i_f*dxx
x_c=i_c*dxx
y_f=j_f*dxx
y_c=j_c*dxx
... |
from typing import Union
from boa3.builtin.interop.blockchain import Block, Transaction
from boa3.builtin.type import UInt256
class Ledger:
"""
A class used to represent the Ledger native contract
"""
@classmethod
def get_block(cls, index_or_hash: Union[int, UInt256]) -> Block:
"""
... |
#!/usr/bin/env python
"""
| Src: https://rhiever.github.io/tpot/examples/Boston_Example/
| Src: https://github.com/rhiever/tpot/blob/master/docs/sources/examples/Boston_Example.md
| License: GPLv3 https://github.com/rhiever/tpot/blob/master/LICENSE
"""
import json
import logging
import os
import os.path
from collecti... |
import os
import subprocess
import shutil
import sys
from setuptools import Extension
from setuptools.command.build_ext import build_ext
from distutils.spawn import find_executable
CMAKE_EXE = os.environ.get('CMAKE_EXE', find_executable('cmake'))
def check_for_cmake():
if not CMAKE_EXE:
print('cmake exec... |
class Node:
"""Node wrapper class implementation.
Useful for tracking depth of a node when
constructing the merkle proof"""
def __init__(self, direction, tx):
self._direction = direction
self._tx = tx
def __eq__(self, other):
"""Overrides the default implementation"""
if isinstance(self, other.__class__... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-09-30 00:11
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('ctrack', '0003_auto_20160927_0705'),
]
operations ... |
import mongoengine
class CloudTunesDocumentMixin(object):
def update_fields(self, **data):
for key, value in data.items():
setattr(self, key, value)
class EmbeddedDocument(mongoengine.EmbeddedDocument,
CloudTunesDocumentMixin):
meta = {
'abstract': True,
... |
# -*- coding: utf-8 -*-
import click
from aiida.utils.cli import command
from aiida.utils.cli import options
from aiida_quantumespresso.utils.cli import options as options_qe
@command()
@options.code('--pw', 'code_pw', callback_kwargs={'entry_point': 'quantumespresso.pw'})
@options.code('--hp', 'code_hp', callback_kw... |
# oauth 视图
import re
from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from django.contrib.auth import login
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View
from django_redis import get_redis_connection
from pymysql import DatabaseErro... |
"""
Creates Hand Joints
"""
import maya.cmds as mc
from ..Utils import String as String
# TODO: Mirror creation on given axis
# TODO: create hand using joint chain, to allow for naming digits more specifically
class Hand():
def __init__(self,
characterName = '',
suffix = '',
... |
# EssentialParameterNeighbors.py
# Marcio Gameiro
# 2020-09-18
# MIT LICENSE
from DSGRN import *
def essential_network_spec(parameter_graph):
"""Returns the essential network specification"""
# Get network specification
net_spec = parameter_graph.network().specification()
# Get list of node specificat... |
import h5py
import numpy as np
filename = "resources\\random_label3D_predictions.h5"
with h5py.File(filename, 'r') as f:
# List all groups
print("Keys: %s" % f.keys())
a_group_key = list(f.keys())[0]
# Get the data
data = list(f[a_group_key])
print(data)
|
import base64
import io
from enum import Enum
import qrcode
import qrcode.image.svg
from . import _FilterBase
#
# @see https://pypi.org/project/qrcode/
#
class _Format(Enum):
SVG = 1
PNG = 2
def _parse_format(format: str) -> _Format:
if format.upper() == 'PNG':
return _Format.PNG
return _... |
import pytest
from qtpy.QtCore import Qt
from qtpy.QtWidgets import QLabel, QPushButton
from napari._qt.widgets.qt_extension2reader import Extension2ReaderTable
from napari._tests.utils import restore_settings_on_exit
from napari.settings import get_settings
@pytest.fixture
def extension2reader_widget(qtbot):
de... |
import os, sys
import numpy as np
import pyworld as pw
from scipy.io import wavfile as wf
fs = int(sys.argv[1])
f0_file = sys.argv[2]
sp_file = sys.argv[3]
ap_file = sys.argv[4]
dest = sys.argv[5]
# Locations
f0 = np.loadtxt(f0_file)
sp = np.loadtxt(sp_file)
ap = np.loadtxt(ap_file)
y = pw.synthesize(f0, sp, ap, fs,... |
import json
import re
from abc import ABC
from threading import Lock
# A callback that only triggers exactly once, after being called N times
class CountDownCallback:
def __init__(self, count, delegate):
self._count = count
self._delegate = delegate
self._lock = Lock()
def __call__(s... |
"""Supervisr Core deploy page ManagementCommand"""
import logging
import os
from django.conf import settings
from django.core.management.base import BaseCommand
LOGGER = logging.getLogger(__name__)
DEPLOY_PAGE_HTML = """
<!DOCTYPE html>
<html>
<head>
<meta content="width=device-width, initial-scale=1, maximum-scal... |
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import scipy.optimize
import multiprocessing as mp
import copy
import pickle
import gasdynamics as gd
from heat_flux import heat_flux
from plug_nozzle_angelino import plug_nozzle
import MOC
import MOC_its
## NASA CEA CONSTAN... |
from setuptools import setup
VERSION = open('__version__').read()
from os import path
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='alembic-migrate',
version=VERSION,
url='https... |
#binary search method to check the elements in given list:......
l=[3,3,4,7,9,2,1,2,0,-6]
l.sort()
print(l)
left=0
right=len(l)-1
search=int(input("Search value="))
print("left = ",left ,",right=",right,l[left:right+1])
while True:
mid=(left+right)//2
if search==l[mid]:
print("Found at ",mid)
br... |
# s.remove(3)
s = {1, 2, 3}
s.remove(3)
print(s)
|
# coding: utf-8
"""
Idomoo API
OpenAPI spec version: 2.0
Contact: dev.support@idomoo.com
"""
from __future__ import absolute_import
# python 2 and python 3 compatibility library
import six
from idomoo.api_client import ApiClient
class LibraryApi(object):
"""NOTE: This class is auto generated ... |
def merge(a, b):
(c, m, n) = ([], len(a), len(b))
i, j = 0, 0
while i+j < m+n:
if i == m:
c.append(b[j])
j += 1
elif j == n:
c.append(a[i])
i += 1
elif a[i] <= b[j]:
c.append(a[i])
i += 1
elif a[i] > b[j... |
from rest_framework.test import APITestCase
from django.urls import reverse
from faker import Faker
class TestSetUp(APITestCase):
def setUp(self) -> None:
self.regiter_url = reverse('register')
self.login_url = reverse('login')
self.sections_url = reverse('sections')
self.faker = ... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'decompress.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog2(object):
def setupUi2(self, Dialog):
... |
NAME = 'rapidsms-site'
VERSION = __version__ = '1.7'
|
import numpy as np
import tensorflow as tf
import pickle
image_size = 28
num_labels = 10
# grayscale
num_channels = 1
batch_size = 16
patch_size = 5
depth = 16
num_hidden = 64
# Reformat data as a cube
# Reformat labels as float 1-hot encodings
def reformat(dataset, labels):
dataset = dataset.reshape((-1, ima... |
# -*- python -*-
# -*- coding: utf-8 -*-
#
# (c) 2013-2021 parasim inc
# (c) 2010-2021 california institute of technology
# all rights reserved
#
# Author(s): Lijun Zhu
# the package
import altar
import altar.cuda
# publish the protocol for norms
from altar.norms.Norm import Norm as norm
# implementations
@altar... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.