content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 4 23:44:15 2021
Wave packet dynamics solver for wavepacket dynamics with N vibrational modes
(N = 1 ,2)
For linear coordinates, use SPO method
For curvilinear coordinates, use RK4 method
@author: Bing Gu
"""
import numpy as np
import proplot as ... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class Grouper(nn.Module):
def __init__(self, model, padder):
super(Grouper, self).__init__()
self.model = model
self.padder = padder
def forward(self, z, u):
raise NotImplementedError
def normalize_weights(... |
import ctypes
import numpy as np
from ._internal.type import *
from ._internal.logging import *
class Type:
bool = bool
int = int
uint = "uint"
float = float
bool2 = "vector<bool,2>"
int2 = "vector<int,2>"
uint2 = "vector<uint,2>"
float2 = "vector<float,2>"
bool3 = "vector<bool,3>... |
{ 'targets': [
{
'target_name': 'curlcpp_jni',
'type': 'static_library',
'dependencies': [],
'sources': [
'curlcpp/src/cookie.cpp',
'curlcpp/src/cookie_date.cpp',
'curlcpp/src/cookie_datetime.cpp',
'curlcpp/src/cookie_time.cpp',
'curlcpp/src/curl_cooki... |
#/usr/bin/env python3
# -*- coding: utf-8 -*-
if __name__ == '__main__':
a = list(map(float, input("Введите элементы массива: ").split()))
c = float(input("Введите число С: "))
s = 0
for item in a:
if item < c:
s += 1
print ('Количество элементов меньше С: ', s)
... |
"""Twilio Telemetry/Sensor Demo For Quickstart and Quest."""
import time
import sys
import yaml
from yaml import Loader
import subprocess
import json
from grove.i2c import Bus
import iothub_client
from iothub_client import IoTHubClient, IoTHubClientError, \
IoTHubTransportProvider, IoTHubClientResult
from iothub_cl... |
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT
"""
This example sends MIDI out. It sends NoteOn and then NoteOff with a random pitch bend.
"""
import time
import random
import adafruit_ble
from adafruit_ble.advertising.standard import ProvideServicesAdvertiseme... |
import json
from unittest import TestCase
import responses
from aioresponses import CallbackResult, aioresponses
from flask_jwt_extended import create_access_token
from requests import PreparedRequest
from requests.exceptions import ConnectTimeout
from dimensigon.domain.entities import Server, Dimension
from dimensig... |
from flask import Flask
from config import Config
import os
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(config_class)
from graph.schema import graph
from main.main import main
app.register_blueprint(graph)
app.register_blueprint(main)
if not os.path... |
########################################################################
#
# File Name: HTMLImageElement
#
#
### This file is automatically generated by GenerateHtml.py.
### DO NOT EDIT!
"""
WWW: http://4suite.com/4DOM e-mail: support@4suite.com
Copyright (c) 2000 Fourthought Inc, USA. All Right... |
import argparse
import sys
import os
from concurrent.futures import ThreadPoolExecutor
from requests import Session
from threading import Event, Thread
from azureml.core import Workspace, Experiment, Run
from azureml._run_impl.run_watcher import RunWatcher
parser = argparse.ArgumentParser()
parser.add_argument('--su... |
"""
Test suite for the airbnb source
"""
from decimal import Decimal
import pytest
from booking_sites_parser.models import Address
from booking_sites_parser.sources.airbnb_plus import AirbnbPlus
PROPERTY_URL: str = 'https://www.airbnb.co.uk/rooms/plus/4950937'
PROPERTY_ID: int = 4950937
PROPERTY_TITLE: str = 'Peace... |
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# #########################################################################
# Copyright (c) 2020, UChicago Argonne, LLC. All rights reserved. #
# #
# Copyright 2020. UChicago Argonne, LLC. This ... |
import logging
import traceback
import time
import concurrent.futures
from spaceone.core.service import *
from spaceone.monitoring.error import *
from spaceone.monitoring.manager.inventory_manager import InventoryManager
from spaceone.monitoring.manager.secret_manager import SecretManager
from spaceone.monitoring.mana... |
"""Create a "Quicklook" Thumbail for the given observation.
A Thumbail image is created from a given JPEG file (see module
documentation for ``make_jpeg.py`` for further details). A
thumbnail is a JPEG image reduced to 128 x 128 pixel size. The
thumbails are used by the ``acsql`` web application for quickly viewing
m... |
"""Tests for the arXiv compiler service."""
|
import importlib
import __init__ as paper
importlib.reload(paper)
app = paper.app('.')
app.run()
|
"""
Module to define base classes.
"""
import sys
import traceback
from abc import ABC, abstractmethod
from datetime import timedelta
from os import makedirs
from os.path import exists as pexists, join as pjoin
from pathlib import Path
from shutil import copyfile
from timeit import default_timer as timer
import num... |
import time
import unittest
from selenium import webdriver
from selenium.webdriver.common.by import By
from utils.config import Config, DRIVER_PATH, PIC_PATH, REPORT_PATH
from utils.deal_imgs import deal_pic
from utils.log import logger
from utils.HTMLTestRunner import HTMLTestRunner
class TestRenting(unittest.TestCa... |
__author__ = 'shishir'
import os
class MailConfig(object):
smtp_host = 'smtp.gmail.com'
smtp_port = 587
user = 'XXXX@gmail.com'
password = 'XXXX' # yeah - please use encryption!!
TEMPLATES_DIR = os.path.realpath("templates")
TABLE_TEMPLATE = 'table.jinja'
|
print "Running test without NIDAQmx installed"
import DAQmxConfigTest
from PyDAQmx import *
print DAQmxGetPersistedTaskAttribute(1,2,3,5,4)
|
ERROR_ON = 'ERROR!!! LINEA %d , COLUMNA %d : '
# TYPE CHECKER
WRONG_SIGNATURE = 'EL METODO "%s" YA ESTA DEFINIDO EN "%s" CON OTRA SIGNATURA.'
SELF_IS_READONLY = 'LA VARIABLE self SOLAMENTE ES read-only.'
LOCAL_ALREADY_DEFINED = 'LA VARIABLE "%s" YA ESTA DEFINIDA EN EL METODO "%s".'
INCOMPATIBLE_TYPES = 'NO SE PUEDE C... |
import connexion
import six
from swagger_server.models.version import Version # noqa: E501
import swagger_server.response_code.default_controller as dc
def version_get(): # noqa: E501
"""version (open)
Version # noqa: E501
:rtype: Version
"""
return dc.version_get()
|
import torch
from torch.optim import Adam
import yaml
from newtonnet.layers.activations import get_activation_by_string
from newtonnet.models import NewtonNet
from newtonnet.train import Trainer
from newtonnet.data import parse_train_test
# torch.autograd.set_detect_anomaly(True)
torch.set_default_tensor_type(torch.... |
"""
Make a figure of confusion matrices given the results. Actual class is on the
left side (rows), and Predicted class is on the top (columns). Uses the
average of all found trials.
Figure outputs are saved under ./fig_bcn_confusion/
This is for chapter 3 of my thesis.
Ideas for improvement:
- Better color scheme
... |
from PIL import Image
from numpy import ndenumerate as iterate_
from stegano import lsb
image_file = "gray.png"
result_file = "gray_with_result.png"
image_pixels_file = "image_pixels.txt"
new_image = "new_image_file.png"
"""
Question 1:
Print image to new file
"""
grayscale = Image.open(image_file).convert('L')
inter... |
import unittest
import pandas as pd
from tests.helpers import skip_on_github_actions
from tests.RME import RMETestCase
from weather_forecast_retrieval.data.hrrr import FileLoader
from weather_forecast_retrieval.hrrr_preprocessor import HRRRPreprocessor
@unittest.skipIf(
skip_on_github_actions(), 'On Github Acti... |
import sys
import random
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
import torch.nn.init as init
import numpy as np
from dataset_vqacp import Dictionary, VQAFeatureDataset
from base_model import Model
import utils
import opts
from train import train
from transformer import Transformer
... |
import json
import os
from pathlib import Path
import pandas
FIXTURES_OUT = "../../ocdb/fixtures/"
class GradeSystemTypeCollection:
def __init__(self):
self.grade_system_types = []
self.count = 0
def add(self, name):
self.count += 1
self.grade_system_types.append(
... |
#
# Copyright 2016-2021 Razorbill Instruments Ltd.
# This file is part of the Razorbill Lab Python library which is
# available under the MIT licence - see the LICENCE file for more.
#
"""
Module for interfacing a dummy instrument which is actually the python shell.
Useful for testing
"""
from . import Instrument, Chi... |
#This file takes new wifi log data and cleans it for database submission
import zipfile
import os
import csv
import shutil
import time
def main():
os.chdir("..")
while True:
while os.path.isfile(r"Data\new_data\CSI WiFiLogs.zip"):
zip1 = zipfile.ZipFile(r"Data... |
import atexit
import logging
import nengo
from nengo.cache import get_default_decoder_cache
import numpy as np
from rig.machine_control import MachineController
from rig.machine_control.consts import AppState
from rig.place_and_route import Cores
import rig.place_and_route
import six
import time
from .builder import M... |
import numpy as np
class ForwardTask(object):
def __init__(self, num_legs=4, num_motors=12):
"""Initializes the task."""
self._num_legs = num_legs
self._num_motors = num_motors
self.current_base_pos = np.zeros(3)
self.last_base_pos = np.zeros(3)
self.current_motor_... |
from rest_framework import serializers
class SimConfigSerializer(serializers.Serializer):
customer_arrival_interval = serializers.IntegerField(required=True)
order_preparation_time = serializers.IntegerField(required=True)
order_taker_interval = serializers.IntegerField(required=True)
time_taken_by_se... |
# -*- coding: utf-8 -*-
from libs.sudoku_rule_keeper import SudokuRuleKeeper
strs = ["(1,2,3,4,5,6,7,8,1)","(x,x,x,x,x,x,x,x,x)","(x,x,x,x,x,x,x,x,x)","(1,x,x,x,x,x,x,x,x)","(x,x,x,x,x,x,x,x,x)","(x,x,x,x,x,x,x,x,x)","(x,x,x,x,x,x,x,x,x)","(x,x,x,x,x,x,x,x,x)","(x,x,x,x,x,x,x,x,x)"]
sudoku_rule_keeper = SudokuRuleKe... |
def get_reddit_posts(subreddit, post_num, before_time, API_limit, API_wait):
#Base url
base_url = "https://api.pushshift.io/reddit/submission/search"
#Getting the posts before July 1st
before_time = int(time.mktime(time.strptime('1 July, 2020', '%d %B, %Y'))), # The latest pull time
#... <removed co... |
from django.db import models
from apps.game.location.models import Location
class Event(models.Model):
name = models.CharField(max_length=100)
effect_type = models.IntegerField(default=0)
effect = models.IntegerField(default=0)
location = models.OneToOneField(Location, on_delete=models.CASCADE)
def _... |
# system specific parameters and functions
import sys
sys.path
sys.platform
sys.setrecursionlimit
sys.stdout
sys.stderr
sys.stdin
|
import typing
from . import enums, models
class Parser:
@staticmethod
def _parse_parameter(parameter: str) -> typing.Dict[str, str]:
parameters: typing.Dict[str, str] = {}
attribute: str
value: str
while parameter:
attribute, parameter = map(str.strip, parameter.s... |
import unittest
import munch
import basecrm
from basecrm.test.testutils import BaseTestCase
class SourcesServiceTests(BaseTestCase):
def test_service_property_exists(self):
self.assertTrue(hasattr(self.client, 'sources'))
def test_method_list_exists(self):
self.assertTrue(hasattr(self.client... |
import os
from flask import (render_template, url_for, redirect, request, g,
current_app, abort)
from flask_mail import Message
from . import aflafrettir
from .forms import ContactForm, SearchForm
from ..models import User, Category, Post, About, Image
from .. import mail, imgs, babel
from helper... |
import cv2
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Flatten
from tensorflow.keras.layers import Conv2D
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.layers import MaxPooling2D
from tensorflow.keras.preprocessing.image import ImageDataGenerat... |
import setuptools
from setuptools import dist
dist.Distribution().fetch_build_eggs(['cython>=0.x', 'numpy>=1.16.2', 'wheel'])
from distutils.extension import Extension
from Cython.Build import cythonize
import numpy
import os, sys
from glob import glob
import version
SOURCE_URL = 'https://github.com/matrix-profil... |
"""Module defining decoders."""
from opennmt.decoders.decoder import Decoder
from opennmt.decoders.decoder import get_sampling_probability
from opennmt.decoders.rnn_decoder import AttentionalRNNDecoder
from opennmt.decoders.rnn_decoder import RNMTPlusDecoder
from opennmt.decoders.rnn_decoder import RNNDecoder
from o... |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0.
import argparse
from awscrt import io
import sys
import threading
import time
from uuid import uuid4
import json
import random
from threading import Timer
from SensorPublisher import SensorPublisher
# This sam... |
""" List comparison """
def compare_two_lists(reference, to_cmp):
"""
Compare two python lists and return True
if reference list is having all elements of
to_cmp list.
"""
return all(elem in reference for elem in to_cmp)
list1 = [1, 2, 3, 4]
list2 = [1]
ret = compare_two_lists(list1, list2)
print("List1:", l... |
from unittest import TestCase
from os import path as os_path
from pandas import read_csv
from genes2doe.convert import extract_genes
class Test_Converter(TestCase):
folder = os_path.join(
os_path.dirname(
os_path.realpath(__file__)
),
'data'
)
input = os_path.join(
... |
n = int(input())
total = 0
for bitNumber in range(64,-1,-1):
bit = 1<<bitNumber
if bit & n:
total += (bit * bitNumber) // 2
n -= bit
total += n + 1
print(total)
|
from collections import Counter
from dataclasses import dataclass
import sys
N_DIRS = 6
MAX_DAY = 23
MAX_SIZE = 3
COSTS = (0, 1, 3, 7)
CUT_COST = 4
MAX_TREES_HEUR = 7
MIN_TREES_HEUR = 10
MIN_TREES_3_HEUR = 4
MAX_SEEDS_HEUR = 3
def debug(*text):
print(*text, file=sys.stderr, flush=True)
@dataclass(frozen=True... |
'''
###################################
Modified from Mike's predict_acc.py
###################################
'''
import os
import sys
import random
import pickle
import numpy as np
import pandas as pd
from keras.utils import to_categorical
from keras.models import load_model
base_data_path = os.path.join('/tmp2/b... |
from statistics import median
with open("input.txt") as f:
values = [int(i) for i in f.readline().split(",")]
print(sum(abs(i - median(values)) for i in values))
|
from pycgp.cgp import CGP
from pycgp.cgpfunctions import *
def build_funcLib():
return [CGP.CGPFunc(f_sum, 'sum', 2),
CGP.CGPFunc(f_aminus, 'aminus', 2),
CGP.CGPFunc(f_mult, 'mult', 2),
CGP.CGPFunc(f_exp, 'exp', 2),
CGP.CGPFunc(f_abs, 'abs', 1),
CGP.CGPFu... |
# -*- coding: utf-8 -*-
import pytest
import time
import aerospike
from aerospike import exception, predicates
from aerospike_helpers.operations import operations, map_operations
from aerospike_helpers import expressions as exp
TEST_NS = 'test'
TEST_SET = 'background_scan1'
TEST_SET2 = 'background_scan2'
TEST_SET3 = ... |
from django.conf.urls import patterns, url
# Uncomment the next two lines to enable the admin:
from article import views
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'newsdemo.views.home', name='home'),
# url(r'^newsdemo/', include('newsdemo.foo.urls')),
# Uncomment the admin/doc lin... |
from .node import Node
class Declaration(Node):
def __init__(self, location: [int], kind: str):
super().__init__(location, kind)
|
from .Point import Point |
"""
[Solubility](https://www.codechef.com/MAY21C/problems/SOLBLTY)
Suppose for a unit rise in temperature, the solubility of sugar in water increases by Bg100 mL.
Chef does an experiment to check how much sugar (in g) he can dissolve given that he initially has 1 liter of water at
X degrees and the solubility of suga... |
import pathlib
import re
from setuptools import setup, find_packages
_HERE = pathlib.Path(__file__).parent
def _resolve_path(*parts):
"""Get a filename from a list of path components, relative to this file."""
return _HERE.joinpath(*parts).absolute()
def _read(*parts):
"""Read a file's contents into a... |
import pytest
from bit.format import (
address_to_public_key_hash, bytes_to_wif, coords_to_public_key,
get_version, point_to_public_key, public_key_to_coords,
public_key_to_address, verify_sig, wif_checksum_check, wif_to_bytes
)
from .samples import (
BITCOIN_ADDRESS, BITCOIN_ADDRESS_COMPRESSED, BITCOI... |
import os
import jwt
from fastapi import HTTPException
from passlib.context import CryptContext
from datetime import datetime, timedelta
class Auth:
hasher = CryptContext(schemes=['bcrypt'])
secret = "BlockchainIsFun"
valid_time_in_mins = 30
def encode_password(self, password):
return self.ha... |
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
import sys
class custom_table(QTableWidget):
def __init__(self, parent=None):
QTableWidget.__init__(self, parent)
self.chkbox1 = QCheckBox(self.horizontalHeader())
def resizeEvent(self, event=None):
... |
from .pedal import BasePedal
from enum import IntEnum
class DelayType(IntEnum):
DEFAULT = 0
DIGITAL = 0
SINGLE = 0
PAN = 1
STEREO = 2
DUAL_SERIES = 3
DUAL_PARALLEL = 4
DUAL_LR = 5
REVERSE = 6
ANALOG = 7
TAPE_ECHO = 8
MODULATE = 9
SDE_3000 = 10
class Delay(BasePedal)... |
from sqlalchemy import orm
import pikka_bird_server.database as db
from pikka_bird_server.models.base import Base
class Collection(db.Base, Base):
"""
Collection of Reports. This is what the collector sends in a POST.
"""
__table__ = db.Base.metadata.tables['collections']
machin... |
class Piece:
...
|
from .models import *
from .data import *
#from .predictor import *
__all__ = [
'graph_nodes_from_csv'
'print_node_classifiers',
'node_classifier'
]
|
from typing import TYPE_CHECKING
from PySide6.QtCore import Qt
if not TYPE_CHECKING:
AlignmentFlag = Qt.AlignmentFlag
ItemDataRole = Qt.ItemDataRole
else:
from enum import IntEnum
class AlignmentFlag(IntEnum, Qt.Alignment):
AlignLeading = Qt.AlignLeading
AlignLeft = Qt.AlignLeft
... |
#!/usr/bin/env python
# encoding=utf8
import requests
import time
import sys
import re
import shutil
import hashlib
import multiprocessing as mp
import subprocess as sp
def download_ipdb(url, path):
response = requests.get(url, verify=False)
etag_value = response.headers.get("ETag")
curre... |
import pulumi
import pulumi_random as random
resource_lexical_name = random.RandomPet("aA-Alpha_alpha.🤯⁉️")
pulumi.export("bB-Beta_beta.💜⁉", resource_lexical_name.id)
|
# -*- coding:utf-8 -*-
from rest_framework import generics
from rest_framework.filters import OrderingFilter, SearchFilter
from rest_framework.permissions import IsAuthenticated
from django_filters.rest_framework import DjangoFilterBackend
from account.serializers.note import NoteModelSerializer
from account.models im... |
import csv
import random
import string
import cv2
import imgaug
import keras_ocr
import matplotlib.pyplot as plt
import numpy as np
import sklearn.model_selection
from utils.Agent import *
# from google.colab.patches import cv2_imshow
class KerasOcrFineTune(Agent):
def __init__(self, inputs, outputs, data_sch... |
from output.models.nist_data.list_pkg.positive_integer.schema_instance.nistschema_sv_iv_list_positive_integer_min_length_4_xsd.nistschema_sv_iv_list_positive_integer_min_length_4 import NistschemaSvIvListPositiveIntegerMinLength4
__all__ = [
"NistschemaSvIvListPositiveIntegerMinLength4",
]
|
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import pymongo
from scrapy.conf import settings
from AdvanceSpider.items import ErrorItem
class AdvancespiderPipeline(object):... |
import torch
import torch.nn as nn
from uninas.modules.attention.abstract import AbstractAttentionModule
from uninas.utils.torch.misc import make_divisible
from uninas.register import Register
@Register.attention_module()
class SqueezeExcitationChannelModule(AbstractAttentionModule):
"""
Squeeze-and-Excitatio... |
from setuptools import setup, find_packages
requirements = [
's3fs',
'autogluon',
'mxnet',
'pyyaml',
]
setup(
name='autogluon-benchmark',
version='0.0.1',
packages=find_packages(exclude=('docs', 'tests', 'scripts')),
url='https://github.com/Innixma/autogluon-benchmark',
license='Ap... |
# coding=utf-8
# Development server
from slideatlas import create_app
app = create_app()
app.run(host='0.0.0.0', port=8080)
|
#!/usr/bin/env python
"""manage state transition details"""
#
# Copyright 2017-2018 IBM 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... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import Tuple
class SelfAttention(nn.Module):
"""SelfAttention class"""
def __init__(self, input_dim: int, da: int, r: int) -> None:
"""Instantiating SelfAttention class
Args:
input_dim (int): dimension ... |
import argparse
import pprint
import json
import spotipy
import numpy as np
import pandas as pd
import spotipy.util as util
from spotipy.oauth2 import SpotifyClientCredentials
from .generatePlaylist import *
from .processing_ import *
from .training import *
"""
python main.py --cid --sid --randomforest
... |
import os
os.environ["CUDA_VISIBLE_DEVICES"]="-1"
import tensorflow as tf
from keras.layers import Dense, Flatten, Lambda, Activation, MaxPooling2D
from keras.layers.convolutional import Convolution2D
from keras.models import Sequential
from keras.optimizers import Adam
import helper
# tf.python.control_flow_ops = tf... |
# Generated by Django 4.0.4 on 2022-05-25 22:06
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ContactForm', '0007_alter_contactformentry_organization'),
]
operations = [
migrations.AlterField(
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-10-27 03:07
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('promgen', '0012_auto_20161027_0306'),
]
operations = [
migrations.AlterFiel... |
from nbapy import constants
from nbapy.nba_api import NbaAPI
class ShotChart:
_endpoint = "shotchartdetail"
def __init__(
self,
player_id: str,
team_id=constants.TeamID.Default,
game_id=constants.GameID.Default,
league_id=constants.League.Default,
season=consta... |
from statistical_analysis_tools.pairwise_overlap.undirectional_overlaps import undirectional_overlaps
from statistical_analysis_tools.pairwise_overlap.directional_overlaps import directional_overlaps
from statistical_analysis_tools.pairwise_overlap.overlap_stats_table import overlap_stats_table
def pairwise_overlap(m... |
#Transactions classes.
from python_tests.Classes.Consensus.SpamFilter import SpamFilter
from python_tests.Classes.Transactions.Data import Data
#RPC class.
from python_tests.Meros.RPC import RPC
#Transactions verifier.
from python_tests.Tests.Transactions.Verify import verifyTransaction
#Ed25519 lib.
import ed25519
... |
"""Parameters from the command line."""
import argparse
def parameter_parser():
"""
A method to parse up command line parameters. By default it gives an embedding of the Facebook food network.
The default hyperparameters give a good quality representation and good candidate cluster means without grid sear... |
#!/usr/bin/python
# ex:set fileencoding=utf-8:
from __future__ import unicode_literals
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.utils.translation import ugettext_lazy as _
from .models import Email
from .models import User
@admin.register(User)
c... |
# -*- coding: utf8-*-
'''
Created on Ago 18, 2013
@author: hidura
'''
from .general import general
class validation:
def patient(self, inputs, objName):
error_msj = ""
if objName == "addPatient":
if "_name" not in inputs:
error_msj += "El nombre del paciente no... |
# Given N friends, each one can remain single or can be paired up with some other friend. Each friend can be paired only once. Find out the total number of ways in which friends can remain single or can be paired up.
# Note: Since answer can be very large, return your answer mod 10^9+7.
# Example 1:
# Input:N ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.9 on 2019-06-12 21:06
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cmdb', '0003_auto_20190612_2044'),
]
operations = [
migrations.AddField(
... |
"""
Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note: You are not suppose to use the l... |
import rosebot_drive_system
import rosebot_servos
import rosebot_sensors
class RoseBot:
def __init__(self):
self.drive_system = rosebot_drive_system.DriveSystem()
self.servos = rosebot_servos.Servos()
self.ultrasonic_sensor = rosebot_sensors.UltrasonicSensor()
self.line_sensors = rosebot_sensors.Line... |
from datetime import datetime
from flask import Flask
from flask import render_template
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
# using sqlite for testing
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
db = SQLAlchemy(app)
# this class along with any others should be in seperate ... |
import json
import boto3
import os
def lambda_handler(event, context):
s3 = boto3.client("s3")
outbucket = os.environ['OUTPUT_BUCKET']
#this assumes the batch size is 1
record = json.loads(event['Records'][0]['body'])
x_offset = record['chip_info']['orig_x']
y_offset = record['chi... |
#python 3.7.3
import argparse
from datetime import datetime
import logging
import os
from pathlib import Path
import shutil
import re
import sys
import pyexiv2
#########################################
def valid_path(mypath: str):
if pattern.match(mypath).end() == len(mypath):
return mypath
else:
... |
import pytest
from numpy import float64, asarray, ndarray, int64, inf
from numpy.testing import assert_allclose
from pyqumo.errors import RowsSumsError
from pyqumo.matrix import fix_stochastic, CellValueError, \
RowSumError, row2string, matrix2string, array2string, \
parse_array, is_square, is_vector, MatrixSh... |
string1 = "Linux"
string2 = "Hint"
joined_string = string1 + string2
print(joined_string)
|
from app.config import email_conf
from app.database.models import Event, User
from fastapi import BackgroundTasks
from fastapi_mail import FastMail, MessageSchema
from sqlalchemy.orm.session import Session
mail = FastMail(email_conf)
def send(
session: Session, event_used: int, user_to_send: int,
tit... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'createelectiondialog.ui'
#
# Created: Thu Nov 13 11:01:10 2014
# by: PyQt4 UI code generator 4.10.3
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
... |
import pymysql
def send_data_to_sql(data, connection_settings):
sql = ""
try:
# Open database connection
db_conn = pymysql.connect(host=connection_settings['host'], port=connection_settings['port'], user=connection_settings['user'], passwd=connection_settings['password'], db=connection_setting... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.