content
stringlengths
0
894k
type
stringclasses
2 values
from typing import get_type_hints, TypeVar, Type __all__ = ["Storage"] T = TypeVar('T') class Storage(dict): """ A Storage object is like a dictionary except `obj.foo` can be used in addition to `obj['foo']`. >>> o = Storage(a=1) >>> o.a 1 >>> o['a'] 1 >...
python
from libarduino import pinMode,digitalWrite,analogRead import time class Actuator(): def __init__(self, port): self.port = port pinMode(self.port, 'OUTPUT') def activate(self): digitalWrite(self.port, 1) def deactivate(self): digitalWrite(self.port, 0) class Ranger(): ...
python
from django import forms class CartAddForm(forms.Form): quantity = forms.IntegerField(min_value=1, max_value=9)
python
#!/usr/bin/python # Copyright 2020 Makani Technologies 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
python
#-*- coding: utf-8 -*- __all__ = ['LEA','ECB','CBC','CTR','CFB','OFB','CCM','GCM','CMAC'] from .LEA import LEA from .ECB import ECB from .CBC import CBC from .CTR import CTR from .CFB import CFB from .OFB import OFB from .CCM import CCM from .GCM import GCM from .CMAC import CMAC from .CipherMode i...
python
# Copyright 2019 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
python
#This file contains a common EKF tracking code for both elevator and rover #It checks variable from file config.npy to figure out its own type import time from datetime import datetime import subprocess import numpy as np from numpy import linalg from numpy.linalg import inv import math import cmath import linalgfu...
python
from Jumpscale import j class Nodes: def __init__(self, session, url): self._session = session self._base_url = url j.data.schema.add_from_path( "/sandbox/code/github/threefoldtech/jumpscaleX_threebot/ThreeBotPackages/tfgrid/directory/models" ) self._model = j.d...
python
#!/usr/bin/env python # # Copyright (c) 2019 Opticks Team. All Rights Reserved. # # This file is part of Opticks # (see https://bitbucket.org/simoncblyth/opticks). # # 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...
python
class Frame: def __init__(self, size): self.type = None # whether this is an audio/video frame self.data = None # this is the raw frame data self.codec = None # codec self.time_stamp = 0 # TS of the frame self.size = size class AudioFrame(Frame): def __init__(self):...
python
import traceback import math import numpy as np import pandas as pd from .CostModule import CostModule class CollectionCost(CostModule): """ Assumptions: 1. System contains central inverters of 1 MW rating each. The inverter being considered is a containerized solution which includes a co-located LV/M...
python
# Copyright (c) 2013 The SAYCBridge Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from z3b import enum import core.suit as suit import z3 _honor_names = ('ace', 'king', 'queen', 'jack', 'ten') _honor_values = (4, 3, 2, 1, 0) def...
python
# An XOR linked list is a more memory efficient doubly linked list. # Instead of each node holding next and prev fields, it holds a field named both, # which is an XOR of the next node and the previous node. # Implement an XOR linked list; it has an add(element) which adds the # element to the end, and a get(index) whi...
python
from app import const BASE_ID = const.AIRTABLE_MAP_BY_GEOGRAPHIC_AREA_BASE_ID AREA_CONTACT_TABLE_NAME = "Area Contact" AREA_TARGET_COMMUNITY_TABLE_NAME = "Area Target Community" class AirtableGeographicAreaTypes: AREA_TYPE_CITY = "City" AREA_TYPE_POLYGON = "Polygon" AREA_TYPE_REGION = "Region" AREA_...
python
from csv import DictReader from scrapy import Item from pyproj import Proj, transform from jedeschule.spiders.nordrhein_westfalen_helper import NordRheinWestfalenHelper from jedeschule.spiders.school_spider import SchoolSpider from jedeschule.items import School # for an overview of the data provided by the State o...
python
# Generated by Django 3.2 on 2022-02-12 21:34 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('reservations', '0001_initial'), ] operations = [ migrations.AlterField( model_name='reservation',...
python
import hashlib import os import errno def hashpasswd(passwd): return hashlib.sha512(passwd.encode('utf-8')).hexdigest() def create_path(path): if not os.path.exists(os.path.dirname(path)): try: os.makedirs(os.path.dirname(path)) except OSError as exc: # Guard against race condit...
python
#!/usr/bin/untitled #created by Reyad import smtplib import json # import datetime # import mysql.connector import pymysql # import MySQLdb from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from datetime import datetime # import datetime from email.mime.applicat...
python
from is_wire.core import Channel, Message, Subscription from google.protobuf.struct_pb2 import Struct import socket channel = Channel("amqp://guest:guest@10.10.2.7:30000") subscription = Subscription(channel) # Prepare request struct = Struct() struct.fields["value"].number_value = 1.0 request = Message(content=struc...
python
import logging from omega import __version__ from tests.interfaces.test_web_interfaces import TestWebInterfaces logger = logging.getLogger(__name__) class TestSys(TestWebInterfaces): async def test_sever_version(self): ver = await self.server_get("sys", "version", is_pickled=False) self.assertEq...
python
from montague.ast import ( And, Call, ComplexType, Exists, ForAll, IfAndOnlyIf, IfThen, Iota, Lambda, Not, Or, TYPE_ENTITY, TYPE_EVENT, TYPE_TRUTH_VALUE, TYPE_WORLD, Var, ) def test_variable_to_str(): assert str(Var("a")) == "a" def test_and_to_str...
python
from recommendation.api.types.related_articles import candidate_finder from recommendation.utils import configuration import recommendation EXPECTED = [('Q22686', 1.0), ('Q3752663', 0.8853468379287844), ('Q2462124', 0.861691557168689), ('Q432473', 0.8481581254555062), ('Q242351', 0.8379904779822078), ('Q86...
python
""" Objects Defining objects imitating the behavior of Python's built-in objects but linked to the database. """ from yuno.objects.dict import YunoDict from yuno.objects.list import YunoList
python
import ptypes from ptypes import * ## string primitives class LengthPrefixedAnsiString(pstruct.type): _fields_ = [ (pint.uint32_t, 'Length'), (lambda s: dyn.clone(pstr.string, length=s['Length'].li.int()), 'String'), ] def str(self): return self['String'].li.str() class LengthPrefi...
python
############################################################################## # Copyright (c) 2016 ZTE Corporation # feng.xiaowei@zte.com.cn # All rights reserved. This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, ...
python
import sys def raise_from(my_exception, other_exception): raise my_exception, None, sys.exc_info()[2] # noqa: W602, E999
python
from flask import Flask app = Flask(__name__) @app.route('/hello/<name>') def hello(name: str) -> str: return f"Hello {name}!"
python
#!/usr/bin/env python import roslib; roslib.load_manifest('teleop_twist_keyboard') import rospy from geometry_msgs.msg import Twist import sys, select, termios, tty, rospy import curses msg = """ Reading from the keyboard and Publishing to Twist! --------------------------- Moving options: -------------------------...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np from Box2D.b2 import contactListener from parameters import * from creatures import Animatronic class nnContactListener(contactListener): def __init__(self): contactListener.__init__(self) self.sensors = dict() def BeginC...
python
# coding: utf-8 # Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. import click from services.waas.src.oci_cli_waas.generated import waas_cli from oci_cli import cli_util from oci_cli import custom_types # noqa: F401 from oci_cli import json_skeleton_utils # oci waas purge-cache purge-cac...
python
"""""" from SSNRoom import SSNRoom import json class WallRoom(SSNRoom): def __init__(self, room): super().__init__(room) # self._load() self.wall_store = None def _load(self): self.wall_store = json.loads(self.room.topic) print("hi") # room_events = self.room.g...
python
# -*- coding: utf-8 -*- # # escpostools/commands/cmd_test.py # # Copyright 2018 Base4 Sistemas Ltda ME # # 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/L...
python
# This is a preliminary version of the code from typing import Any import time import torch import numpy from torch import Tensor from torch import autograd from torch.autograd import Variable from torch.autograd import grad def hessian_vec(grad_vec, var, retain_graph=False): v = torch.ones_like(var) vec, = a...
python
# automatically generated by the FlatBuffers compiler, do not modify # namespace: DeepSeaScene import flatbuffers from flatbuffers.compat import import_numpy np = import_numpy() class SubpassDependency(object): __slots__ = ['_tab'] @classmethod def SizeOf(cls): return 28 # SubpassDependency...
python
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.feature_selection import mutual_info_classif def draw_cat_plot(df: pd.DataFrame, id_var: str, cat_feats: list, *, output_filename: str =None): """ Draw plot showing value counts of categorical features. ...
python
import numpy as np from lmfit import Parameters, minimize, report_fit from lmfit.models import LinearModel, GaussianModel from lmfit.lineshapes import gaussian def per_iteration(pars, iter, resid, *args, **kws): """iteration callback, will abort at iteration 23 """ # print( iter, ', '.join(["%s=%.4f" % (p....
python
from typing import List class Solution: def maximum69Number (self, num: int) -> int: ls = list('%d'%num) ans = 0 try: index = ls.index(6) ls[index] = 9 for it in ls: ans = ans * 10 + it return ans except ValueError a...
python
from __future__ import absolute_import, division, print_function from scitbx.array_family import flex # import dependency from simtbx.nanoBragg import shapetype from simtbx.nanoBragg import convention from simtbx.nanoBragg import nanoBragg import libtbx.load_env # possibly implicit from cctbx import crystal import os ...
python
import brainscore from brainscore.benchmarks._neural_common import NeuralBenchmark, average_repetition from brainscore.metrics.ceiling import InternalConsistency, RDMConsistency from brainscore.metrics.rdm import RDMCrossValidated from brainscore.metrics.regression import CrossRegressedCorrelation, pls_regression, pear...
python
import json, time, argparse, getpass, re, requests try: input = raw_input except NameError: pass parser = argparse.ArgumentParser(description='Bytom UTXO Tool') parser.add_argument('-o', '--url', default='http://127.0.0.1:9888', dest='endpoint', help='API endpoint') parser.add_argument('--http-user', default=No...
python
S = set() S.add(5) S.add(3) S.add(1) # Prints out the numbers 5, 3, 1 in no particular order for element in S: print "{} is in the set".format(element) S.remove(3) S.remove(5) s.remove(1)
python
# Copyright 2019 Google LLC. 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 applicable law or a...
python
import sqlite3 import os.path from os import listdir, getcwd import sys from os import listdir from os.path import isfile, join BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) db_dir = os.path.join(BASE_DIR,"sql/") img_dir = os.path.join(BASE_DIR,"images/") full_dir = lambda x,y: x+y known_fac...
python
data = open('data/input6.txt', 'r') orbs = data.readlines() d = {} for orb in orbs: c1 = orb[:3] c2 = orb[4:7] d[c2] = c1 s = 0 for p in d: curr_p = p while curr_p in d: curr_p = d[curr_p] s += 1 print(s) trajet_you = [] curr = 'YOU' while True: if curr not in d: break c...
python
#! /usr/bin/env python # # Check the option usage. # Make sure the union member matches the option type. # import sys, os, fnmatch # just use the first letter of the member name - should be unique opt_suffix = { 'b' : 'AT_BOOL', 'a' : 'AT_IARF', 'n' : 'AT_NUM', 'l' : 'AT_LINE', 't' : 'AT_POS' }...
python
from pathlib import Path import pytest from md_translate.exceptions import ObjectNotFoundException, FileIsNotMarkdown from md_translate.files_worker import FilesWorker TEST_FIRST_FILE = 'tests/test_data/md_files_folder/first_file.md' TEST_SECOND_FILE = 'tests/test_data/md_files_folder/second_file.md' class Setting...
python
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from telemetry.page import page as page_module from telemetry.page import page_set as page_set_module class Top20Page(page_module.Page): def __init__(se...
python
# -*- coding: utf-8 -*- ## # @file backend.py # @brief # @author wondereamer # @version 0.5 # @date 2016-07-10 from quantity.digger.event.rpc import EventRPCServer from quantity.digger.event.eventengine import ZMQEventEngine from quantity.digger.interaction.interface import BackendInterface from quantity.digger.util...
python
#%% Test Module from pyCMC import CMC def test_results(returnVal, tname): if 'status' in returnVal.keys(): if returnVal['status']['error_code'] == 0: print('{} works!'.format(tname)) else: print('Error message: {}'.format(returnVal['status']['error_message'])) else: print(returnVal) with open('./cmc_key...
python
from django.http import HttpResponse, HttpRequest, HttpResponseRedirect from django.template import RequestContext from django.shortcuts import render_to_response from django.core.context_processors import csrf from django.conf import settings from django.contrib.auth.models import User, Group from reports.models impo...
python
#!/Users/juan/venv-3.8.6/bin/python3.8 # Copyright 2020 Telleztec.com, Juan Tellez, All Rights Reserved # import boto3 import datetime import argparse # convert bytes to kb, mb, and gb def to_units(b, unit): if unit=='b': return b elif unit=='k': return round(b/1000, 2) elif unit=='m': ...
python
from django.db.models import Count from tastypie.resources import ModelResource, ALL_WITH_RELATIONS from tastypie import http, fields from tastypie.exceptions import ImmediateHttpResponse from tastypie.bundle import Bundle import json from django.core.exceptions import ValidationError, ObjectDoesNotExist from django....
python
""" Copyright 2017 Balwinder Sodhi Licenced under MIT Licence as available here: https://opensource.org/licenses/MIT THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT....
python
# # Sample: Gamut clamping # from lcms import * Lab = cmsCIELab(80, -200, 50) print "Original", Lab # # Desaturates color to bring it into gamut. # The gamut boundaries are specified as: # -120 <= a <= 120 # -130 <= b <= 130 cmsClampLab(Lab, 120, -120, 130, -130) print "Constrained", Lab
python
from django.urls import path from . import views urlpatterns = [ path("numbers", views.NumberListView.as_view(), name="number_list_view"), path("numbers/<int:pk>/", views.NumberView.as_view(), name="number_view"), path("numbers/add_number/", views.NumberEditView.as_view(), name="add_number"), path('nu...
python
import re import pytest from ratus import Evaluator, __version__ from ratus.execer import Executor, ExecutorError from ratus.parse import ( BinaryOp, BinaryOpType, Float, Function, Integer, Parser, ParserError, String, UnaryOp, UnaryOpType, ) from ratus.token import Token, Toke...
python
from hilbert import main main()
python
from rest_framework import serializers from attendance.models import Attendance, AttendanceBlock, Session class SessionSerializer(serializers.ModelSerializer): subject = serializers.SerializerMethodField() class Meta: model = Session fields = [ "subject", "start", ...
python
from __future__ import division import numpy as np import matplotlib.pyplot as plt import scipy.optimize as opt import scipy.stats as st from math import exp, copysign, log, sqrt, pi import sys sys.path.append('..') from rto_l1 import * # ground truth parameter thetatruth = np.array([0.5, 1.0, 0, 0.1, 0.0, 0.0, 0.0,...
python
import requests import json def send(text, path): requests.post('https://meeting.ssafy.com/hooks/k13xxxszfp8z8ewir4qndiw63c', data=json.dumps({"attachments": [{ "color": "#FF8000", "text": str(text), "author_name": "django", "author_icon": "http://www.matter...
python
#-*- coding: utf-8 -*- import datetime from PyQt4 import QtGui from campos import CampoNum, CampoCad from controllers.orden_controller import initData, translateView, updateData, checkValidacion, Save class OrdenView(QtGui.QGroupBox): def __init__(self, parent=None): super(OrdenView, self).__init__(parent) ...
python
#!/usr/bin/env python3 from distutils.core import setup import os os.system("make ") setup(name='pi', version='1.0', description='pi digits compute', author='mathm', author_email='mingtinglai@58.com', url="https://igit.58corp.com/mingtinglai/pi", )
python
import os import sys import threading import boto3 import logging import shutil from botocore.client import Config from matplotlib import pyplot as plt from botocore.exceptions import ClientError from boto3.s3.transfer import TransferConfig END_POINT_URL = 'http://uvo1baooraa1xb575uc.vm.cld.sr/' A_KEY = 'AKIAtEpiGWUc...
python
#coding:utf-8 import hashlib from scrapy.dupefilters import RFPDupeFilter from scrapy.utils.url import canonicalize_url class URLSha1Filter(RFPDupeFilter): """根据urlsha1过滤""" def __init__(self, path=None, debug=False): self.urls_seen = set() RFPDupeFilter.__init__(self, path) def re...
python
from sys import * sid = 11 if len(argv) <= 1 else int(argv[1]) from random import * seed(sid) for cas in range(int(input())): input() m = {} for i, v in enumerate(map(int, input().split())): m.setdefault(v, []).append(i) b = [v for i, v in sorted((choice(l), v) for v, l in m.items())] print(len(b)...
python
# # Project FrameVis - Video Frame Visualizer Script # @author David Madison # @link github.com/dmadison/FrameVis # @version v1.0.1 # @license MIT - Copyright (c) 2019 David Madison # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associate...
python
import os import pickle import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from task_dyva.utils import save_figure from task_dyva.visualization import PlotModelLatents class FigureS6(): """Analysis methods and plotting routines to reproduce Figure S6 from the manusc...
python
import random from flask import render_template, redirect, flash, url_for, request, jsonify from flask_login import login_user, logout_user, current_user, login_required from sqlalchemy import desc from app import app, db, login_manager, forms from app.models import User, Game, GameMove from app.decorators import not_i...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jan 15 15:49:57 2018 @author: pranavjain This model predicts the quality of the red wine. Also, an optimal model is built using Backward Elimination. Required Data to predict Fixed acidity Volatile acidity Citric acid Residual sugar Chlorides Free sul...
python
from mqtt_panel.web.component import Component class Modal(Component): def __init__(self): super().__init__(4) def _body(self, fh): self._write_render(fh, '''\ <div id="modal" class="d-none"></div> ''', indent=self._indent)
python
from gym_gazebo2.envs.MARA.mara import MARAEnv from gym_gazebo2.envs.MARA.mara_random import MARARandEnv from gym_gazebo2.envs.MARA.mara_real import MARARealEnv from gym_gazebo2.envs.MARA.mara_camera import MARACameraEnv from gym_gazebo2.envs.MARA.mara_orient import MARAOrientEnv from gym_gazebo2.envs.MARA.mara_collisi...
python
# Dependencies import requests as req from config import api_key url = f"http://www.omdbapi.com/?apikey={api_key}&t=" # Who was the director of the movie Aliens? movie = req.get(url + "Aliens").json() print("The director of Aliens was " + movie["Director"] + ".") # What was the movie Gladiator rated? movie = req.get...
python
"""Clean Code in Python - Chapter 9: Common Design Patterns > Monostate Pattern """ from log import logger class SharedAttribute: def __init__(self, initial_value=None): self.value = initial_value self._name = None def __get__(self, instance, owner): if instance is None:...
python
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in th...
python
# Eyetracker type # EYETRACKER_TYPE = "IS4_Large_Peripheral" # 4C eyetracker #EYETRACKER_TYPE = "Tobii T120" # Old eyetracker EYETRACKER_TYPE = "simulation" # test # EYETRACKER_TYPE = "Tobii Pro X3-120 EPU" # Tobii X3 SCREEN_SIZE_X = 1920 SCREEN_SIZE_Y = 1080 #Pilot condition PILOT_CONDITION_TEXT_INTERVENTION = True...
python
#- # Copyright (c) 2013 Robert M. Norton # All rights reserved. # # @BERI_LICENSE_HEADER_START@ # # Licensed to BERI Open Systems C.I.C. (BERI) under one or more contributor # license agreements. See the NOTICE file distributed with this work for # additional information regarding copyright ownership. BERI licenses t...
python
import os import telebot token = os.environ['TELEGRAM_TOKEN'] bot = telebot.TeleBot(token) def medit(message_text,chat_id, message_id,reply_markup=None,parse_mode=None): return bot.edit_message_text(chat_id=chat_id,message_id=message_id,text=message_text,reply_markup=reply_markup, ...
python
# -*- coding: utf-8 -*- # # Tencent is pleased to support the open source community by making QT4C available. # Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved. # QT4C is licensed under the BSD 3-Clause License, except for the third-party components listed below. # A copy of the BSD ...
python
from spire.mesh import ModelController from spire.schema import SchemaDependency from platoon import resources from platoon.models import * class QueueController(ModelController): resource = resources.Queue version = (1, 0) mapping = 'id subject name status' model = Queue schema = SchemaDependenc...
python
import argparse import shutil import errno import time import glob import os import cv2 import numpy as np from merge_tools import do_merge_box DEBUG = True class MergeBox(object): def __init__(self): args = self.parse_arguments() self.output_dir = args.output_dir self.input_dir = args....
python
"""Tests""" import unittest from html_classes_obfuscator import html_classes_obfuscator class TestsGenerateCSS(unittest.TestCase): """Tests Args: unittest (unittest.TestCase): Unittest library """ def test_generate_css_simple_case(self) -> None: """Test""" new_css = html_cl...
python
import urllib.request def obtain_webpage(url: str): return urllib.request.urlopen(url)
python
filepath = 'Prometheus_Unbound.txt' with open(filepath) as fp: line = fp.readline() cnt = 1 while line: print("Line {}: {}".format(cnt, line.strip())) line = fp.readline() cnt += 1
python
# Time: O(nlogn) # Space: O(n) import collections # hash, sort class Solution(object): def findWinners(self, matches): """ :type matches: List[List[int]] :rtype: List[List[int]] """ lose = collections.defaultdict(int) players_set = set() for x, y in matche...
python
# flake8: noqa elections_resp = { 'kind': 'civicinfo#electionsQueryResponse', 'elections': [{ 'id': '2000', 'name': 'VIP Test Election', 'electionDay': '2021-06-06', 'ocdDivisionId': 'ocd-division/country:us' }, { 'id': '4803', 'name': 'Los Angeles County Elec...
python
def readFile(path): try: with open(path, "r") as file: return file.read() except: print( "{Error: Failed to load file. File doesn't exist or invalid file path, " + "Message: Please check arguments or import strings.}" ) return "" class Stack:...
python
import discord from discord.ext import commands from discord.ext.commands import Bot import asyncio import time import logging import random import googletrans prefix = "$" BOT_TOKEN = "token-goes-here" intents = discord.Intents.default() intents.members = True client = commands.Bot(command_prefix=pr...
python
"""Helper file to check if user has valid permissions.""" from application.common.common_exception import (UnauthorizedException, ResourceNotAvailableException) from application.model.models import User, UserProjectRole, RolePermission, \ Permission, UserOrgRole, Org...
python
#!/bin/python3 # this script should be run with a "script" command to save the output into a file import requests import io import json # put the instance needed here inst='https://octodon.social/api/v1/timelines/public?local=1' with io.open("toots.txt","a",encoding="utf8") as f: while True: res = reque...
python
/home/runner/.cache/pip/pool/40/4e/54/4dc30f225358504ac2a93685d7323e0851fea2c2a9937f25f1d53d20f9
python
# Licensed under MIT license - see LICENSE.rst # -*- coding: utf-8 -*- """Utility functions.""" import numpy as np __all__ = ['mag_to_flux', 'flux_to_mag', 'e1_e2_to_shape'] def mag_to_flux(mag, zeropoint=27.0): """Convert magnitude into flux unit. """ return 10.0 ** ((zeropoint - mag) / 2.5) def flux_...
python
#!/usr/bin/env python3 import os import sys import json import random from pathlib import Path from PySide6 import QtCore, QtWidgets from pikepdf import Pdf, Encryption class ProtectPdfWindow(QtWidgets.QWidget): def __init__(self, lang_file='en.json'): super().__init__() if os.path.isfile(lang_fi...
python
def remap( x, oMin, oMax, nMin, nMax ): #range check if oMin == oMax: print("Warning: Zero input range") return None if nMin == nMax: print("Warning: Zero output range") return None #check reversed input range reverseInput = False oldMin = min( oMi...
python
import pandas as pd import mysql.connector import json from pandas.io.json import json_normalize from sqlalchemy import create_engine import pymysql.cursors import datetime def connect(): """ Connect to MySQL database """ source = None try: source = pymysql.connect(host='35.220.139.166', ...
python
import pandas as pd import numpy as np import helper_functions.DataFrames as dfimport def FillNaNWithCurrentDistribution(column, df): ''' Input : The name of the column to witch the fillig strategy should be applied to, plus the DataFrame object contanig the relevant data. Output : The ...
python
################################################################################ # Copyright (C) 2013 Jaakko Luttinen # # This file is licensed under the MIT License. ################################################################################ """ Unit tests for bayespy.utils.linalg module. """ import numpy as n...
python
# Taken from https://github.com/ojroques/garbled-circuit import json # HELPER FUNCTIONS def parse_json(json_path): with open(json_path) as json_file: return json.load(json_file)
python
"""Support the binary sensors of a BloomSky weather station.""" from __future__ import annotations import voluptuous as vol from homeassistant.components.binary_sensor import ( PLATFORM_SCHEMA, BinarySensorDeviceClass, BinarySensorEntity, ) from homeassistant.const import CONF_MONITORED_CONDITIONS from ho...
python
import pygame from buttons.image_button import ImageButton class CardComponent: def __init__(self, screen, x, y, suit, value): self.flipped = False self.value = value self.suit = suit card_image = f"assets/{value}_{suit}.png" self.card = ImageButton(screen, x, y, card_imag...
python
import os import time import torch import argparse import torchvision import torch.nn as nn import torch.utils.data import torch.optim as optim import torchvision.transforms as transforms from utils.function import * from model.SE import SEresnet, loss_fn_kd from torch.optim import lr_scheduler from torch.utils.data ...
python