content stringlengths 5 1.05M |
|---|
#
# Copyright (c) 2015-2016 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
import errno
import functools
import select
import socket
def syscall_retry_on_interrupt(func, *args):
"""Attempt system call again if interrupted by EINTR """
for _ in range(0, 5):
try:
return f... |
# -*- coding: utf-8 -*-
#
# Copyright 2015 Ternaris, Munich, Germany
#
# 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, c... |
import numpy as np
def calculate_predictions(events, cluster_info):
# This function takes existing events, and backtracks this to predictions.
predictions = np.empty((len(cluster_info), 2), dtype=np.float64)
# The predictions matrices are stored (for historical reasons) in microns. So multiply with pixel... |
import os
import unittest
from __main__ import vtk, qt, ctk, slicer
#
# TortuosityLogicTests
#
class TortuosityLogicTests:
def __init__(self, parent):
parent.title = "TortuosityLogicTests" # TODO make this more human readable by adding spaces
parent.categories = ["Testing.TestCases"]
parent.dependencies... |
#!/usr/bin/env python3
# author: greyshell
# description: demo how to use heapq library
import heapq
class MaxHeapNode(object):
def __init__(self, key):
self.key = key
def __lt__(self, other):
# compare based on val
# tweak the comparison logic to build max heap: change less_than_si... |
import logging
from gehomesdk.erd.converters.abstract import ErdReadOnlyConverter
from gehomesdk.erd.converters.primitives import *
from gehomesdk.erd.values.laundry import ErdTankSelected, TankSelected, TANK_SELECTED_MAP
_LOGGER = logging.getLogger(__name__)
class TankSelectedConverter(ErdReadOnlyConverter[TankSele... |
#!/usr/bin/env python
"""This script generates a two-column reStructuredText table in which:
- each row corresponds to a module in a Python package
- the first column links to the module documentation
- the second column links to the module source code generated by
the 'viewcode' extension
"""
__date__ =... |
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
import os
import uuid
from azure.keyvault.certificates import CertificateClient, CertificatePolicy
from key_vault_base import KeyVaultBase
class KeyVaultCertificates(Ke... |
import os
import dropbox
from .cloud_provider import CloudProvider
class DBox(CloudProvider):
def __init__(self, access_token):
"""
Initializes class
Parameters
----------
access_token : str
Dropbox access token
"""
if not isinstance(access_tok... |
#####################################
# CELERY
#####################################
from datetime import timedelta
from kombu import Exchange
from kombu import Queue
def celery_queue(key):
return Queue(key, Exchange(key), routing_key=key)
CELERY_CREATE_MISSING_QUEUES = True
CELERY_DEFAULT_QUEUE = 'default'
CE... |
from django.db import models
from django.core.validators import MaxValueValidator, MinValueValidator
from authentication.models import Account
from authentication.models import AccountManager
class Entity(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
created_by = Account
updated_at = ... |
# Lint as: python3
# Copyright 2021 Jose Carlos Provencio
#
# 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 applicabl... |
from flask import url_for, request
from flask_restplus import Namespace, Resource
import strongr.restdomain.model.gateways
from strongr.restdomain.model.oauth2 import Client
ns = Namespace('oauth', description='Operations related to oauth2 login')
@ns.route('/revoke', methods=['POST'])
class Revoke(Resource):
de... |
from hs_students import HighSchool
highSchoolStudent = HighSchool('Manasvi', 10)
print(highSchoolStudent.get_name_captalize())
print(highSchoolStudent.get_School_name())
|
from django.conf.urls import url
from . import views
from django.conf import settings
from django.conf.urls.static import static
from django.urls import path
from photos import views
from .views import BlogCreateView
urlpatterns =[
path('post/new/', BlogCreateView.as_view(), name='post_new'),
url(r'^one/', vi... |
from tests.util import BaseTest
class Test_C2025(BaseTest):
def error_code(self) -> str:
return "C2025"
def test_fail_1(self):
code = """
foo = (1 if True
else 0)
"""
result = self.run_flake8(code, True)
self.assert_error_at(result, "C2025", 1, 8... |
"""
This following demonstrates a Noise_NNpsk0+psk2_25519_ChaChaPoly_BLAKE2s handshake and initial transport messages.
"""
from dissononce.processing.impl.handshakestate import HandshakeState
from dissononce.processing.impl.symmetricstate import SymmetricState
from dissononce.processing.impl.cipherstate import CipherSt... |
from invoke import (
run,
task,
)
from . import common
LANGUAGE = 'js'
@task
def clean():
print 'cleaning %s...' % (LANGUAGE,)
with common.base_directory():
run("rm -rf %(language)s && mkdir %(language)s" % {'language': LANGUAGE})
@task(default=True)
def compile():
print 'compiling %s.... |
import math
from typing import List
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor
def _initialize_embeddings(weight: Tensor, d: int) -> None:
d_sqrt_inv = 1 / math.sqrt(d)
# This initialization is taken from torch.nn.Linear and is equivalent to:
# nn.init.kai... |
#!/usr/bin/python3
# Extract Ansible tasks from tripleo repos
import os
import yaml
TASK_ATTRS = [
"action",
"any_errors_fatal",
"args",
"async",
"become",
"become_exe",
"become_flags",
"become_method",
"become_user",
"changed_when",
"check_mode",
"collections",
"c... |
from searx import settings, autocomplete
from searx.languages import language_codes as languages
from searx.url_utils import urlencode
COOKIE_MAX_AGE = 60 * 60 * 24 * 365 * 5 # 5 years
LANGUAGE_CODES = [l[0] for l in languages]
LANGUAGE_CODES.append('all')
DISABLED = 0
ENABLED = 1
class MissingArgumentException(Ex... |
from scapy.all import *
from ccsds_base import CCSDSPacket
class PL_IF_HK_TLM_PKT_TlmPkt(Packet):
"""Pl_if App
app = PL_IF
command = HK_TLM_PKT
msg_id = PL_IF_HK_TLM_MID = 0x09de = 0x0800 + 0x1de
"""
name = "PL_IF_HK_TLM_PKT_TlmPkt"
fields_desc = [
# APPEND_ITEM CMD_VALID_COUNT 16... |
from autorop.bof.Corefile import Corefile
|
import netaddr
from django.urls import reverse
from sidekick.models import (
LogicalSystem, RoutingType,
NetworkServiceType, NetworkService,
NetworkServiceGroup,
)
from .utils import BaseTest
class NetworkServiceTest(BaseTest):
# Logical System
def test_logicalsystem_basic(self):
v = Lo... |
"""
Http related errors
"""
class HTTPError(Exception):
""" Base class for all http related errors """
status_code = 500
class HTTPForbidden(HTTPError):
""" Http forbidden error (status code 403). """
status_code = 403
class HTTPBadRequest(HTTPError):
""" Client sent a bad request. """
sta... |
# coding=utf-8
"""
Port of the ganglia gearman collector
Collects stats from gearman job server
#### Dependencies
* gearman
"""
from diamond.collector import str_to_bool
import diamond.collector
import os
import subprocess
import time
try:
import gearman
except ImportError:
gearman = None
class Gearma... |
import requests
print requests.delete("http://localhost:7215/player/", json={"uid": "K/1H5bdxo7GwMBUp8qVQz42h7ZE=", }).content
print requests.put("http://localhost:7215/player/", json={"uid": "K/1H5bdxo7GwMBUp8qVQz42h7ZE=", "team": "emc", "rank": "grunt",}).content
#print requests.put("http://localhost:7215/battlemo... |
from django.conf.urls import url
from django.contrib import admin
from django.contrib.auth.views import login, logout
from chat.views import index,register_page
app_name= "multichat"
urlpatterns = [url(r'^home/$', index),
url(r'^$', index),
url(r'^register/$', register_page),
url(r'^accounts/login/$', l... |
from .game_move import GameMove
from .game_node import GameNode
from .game_state import GameState
from .game_tree import GameTree
# from .game import Game
from .game_multithread import GameMultithread
|
from coders import NoopCoder
from sources import CsvFileSource
|
# built-in
import ctypes;
import os;
# import matey shared library
current_dir = os.path.dirname(__file__);
matey_path = os.path.join(current_dir, "matey.so");
libmatey = ctypes.CDLL(matey_path);
#### SUM #######################################################################
libmatey.sum.restype = ctypes.c_int;
lib... |
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
with open('README.md', 'r') as rm:
long_desc = rm.read()
setup(
name='soloman',
version='3.0.2',
description='For the love of Artificial Intelligence, Python and QML',
long_description=long_desc,
long_description_content_type=... |
from email.charset import Charset, QP
from email.mime.text import MIMEText
from .base import AnymailBaseBackend, BasePayload
from .._version import __version__
from ..exceptions import AnymailAPIError, AnymailImproperlyInstalled
from ..message import AnymailRecipientStatus
from ..utils import get_anymail_setting, UNSE... |
import pandas as pd
import numpy as np
class omdf:
def __init__(self,dff):
self.df = dff
self.arr = self.df.to_numpy()
def df_add_col_instr(self):
self.df['cat'] = self.df.apply(lambda row: TS(row.Summary), axis = 1)
return self.df.to_dict()
def df_add_col_dic(self,colname,... |
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals, absolute_import, division
""" http://projecteuler.net/index.php?section=problems&id=18 triangle
it has been finished in 10 minutes
using recursive method is prefered, brute force not feasible to solve this problem
"""
from proje... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, ... |
# -*- coding: utf-8 -*-
'''
Este módulo tiene todas las funciones pertinentes para obtener y/o calcular los diferentes parámetros del modelo a partir de datos y/o parámetros del artículo de Arenas.
Convención del vector de parámetros siguiendo la Supplementary Table 1 de [1]:
# Parámetros usuales
β = ... |
"""Support for TPLink lights."""
from __future__ import annotations
import logging
from typing import Any
from kasa import SmartDevice
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_COLOR_TEMP,
ATTR_HS_COLOR,
ATTR_TRANSITION,
COLOR_MODE_BRIGHTNESS,
COLOR_MODE_COLOR_TEMP,
... |
# -*- coding: utf-8 -*-
import logging
import allel
import h5py
import os
import os.path
import haplotype_plot.constants as constants
import haplotype_plot.reader as reader
import haplotype_plot.filter as strainer
import haplotype_plot.haplotyper as haplotyper
import numpy as np
logger = logging.getLogger(... |
import torch
import transformers
from packaging import version
from torch.utils.data import SequentialSampler
from transformers import BertConfig, BertForSequenceClassification
from .registry import non_distributed_component_funcs
def get_bert_data_loader(
batch_size,
total_samples,
sequence_... |
# SPDX-FileCopyrightText: 2021 European Spallation Source <info@ess.eu>
# SPDX-License-Identifier: BSD-3-Clause
__author__ = 'github.com/wardsimon'
__version__ = '0.0.1'
import numpy as np
import pytest
from easyCore.Objects.Base import Descriptor, Parameter, BaseObj
from easyCore.Objects.Groups import BaseCollecti... |
#!/usr/bin/env python3
import csv
import itertools as it
import os
import sys
def write_csv(f, cols, machines, variants):
w = csv.writer(f, delimiter=',')
headers = ["{}-{}".format(m, v) for (m, v) in it.product(machines, variants)]
w.writerow(headers)
for e in zip(*cols):
w.writerow(list(e))
... |
import torch
from torch.autograd import Variable
from deepqmc.wavefunction.wf_orbital import Orbital
from deepqmc.wavefunction.molecule import Molecule
from pyscf import gto
import matplotlib.pyplot as plt
import numpy as np
import unittest
class TestAOvalues(unittest.TestCase):
def setUp(self):
# def... |
from math import ceil
from struct import pack, unpack
import numpy as np
import ftd2xx as ftd
from timeflux.core.node import Node
from timeflux.helpers.clock import now
from timeflux.core.exceptions import WorkerInterrupt, TimefluxException
VID = 0x24f4 # Vendor ID
PID = 0x1000 # Product ID
HEADER = 0xAA... |
first = "0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1... |
# -*- coding: utf-8 -*-
# Copyright (c) 2018-2021, earthobservations developers.
# Distributed under the MIT License. See LICENSE for more info.
"""
=====
About
=====
Example for DWD RADOLAN Composite RW/SF using wetterdienst and wradlib.
Hourly and gliding 24h sum of radar- and station-based measurements (German).
Se... |
# -*- encoding: utf-8 -*-
import pandas as pd
import pytest
from deeptables.datasets import dsutils
from deeptables.models import deeptable
from deeptables.utils import consts
class TestModelInput:
def setup_class(cls):
cls.df_bank = dsutils.load_bank().sample(frac=0.01)
cls.df_movielens = dsuti... |
# This file is part of Moksha.
# Copyright (C) 2008-2010 Red Hat, Inc.
#
# 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 b... |
from ctypes import *
SHM_SIZE = 4096
SHM_KEY = 67483
try:
rt = CDLL('librt.so')
except:
rt = CDLL('librt.so.1')
shmget = rt.shmget
shmget.argtypes = [c_int, c_size_t, c_int]
shmget.restype = c_int
shmat = rt.shmat
shmat.argtypes = [c_int, POINTER(c_void_p), c_int]
shmat.restype = c_void_p
shmctl = rt.shmct... |
import pandas as pd
from numpy import datetime64
from pandas_datareader import data
from pandas.core.series import Series
from pandas.core.frame import DataFrame
from yahoofinancials import YahooFinancials
# holding period return in percents
def get_holding_period_return(df: DataFrame, start, end, col) -> float:
... |
class JobLookupError(KeyError):
"""Raised when the job store cannot find a job for update or removal."""
def __init__(self, job_id):
super().__init__(u'No job by the id of %s was found' % job_id)
class ConflictingIdError(KeyError):
"""Raised when the uniqueness of job IDs is being violated."""
... |
import pytest
from src.dataToCode.dataClasses.classData import ClassData
from src.dataToCode.dataClasses.interface import Interface
from src.dataToCode.languages.toPython.fileNameToPython import FileNameToPython
data = [
("Orc", "orc.py"),
("HighOrc", "high_orc.py"),
("PrettyLongClassName", "pretty_long_c... |
# -*- coding: utf-8 -*-
"""
# @Time : 29/06/18 12:23 PM
# @Author : ZHIMIN HOU
# @FileName: run_Control.py
# @Software: PyCharm
# @Github : https://github.com/hzm2016
"""
import numpy as np
np.random.seed(1)
import time
import gym
import gym_puddle
import gym.spaces
import pickle
from algorithms import *
from T... |
from .black_scholes_process import BlackScholesMertonProcess
|
from datetime import datetime
from os.path import dirname, join
import pytest
from city_scrapers_core.constants import COMMISSION
from city_scrapers_core.utils import file_response
from freezegun import freeze_time
from city_scrapers.spiders.chi_ssa_8 import ChiSsa8Spider
test_response = file_response(
join(dirn... |
import os, sys
sys.path.insert(0, os.path.join("..",".."))
from nodebox.graphics.context import *
from nodebox.graphics import *
# Generate compositions using random text.
font('Arial Black')
def rndText():
"""Returns a random string of up to 9 characters."""
t = u""
for i in range(random(10)):
t... |
#coding utf8
#!/usr/bin/env python
# Python 2/3 compatibility
from __future__ import print_function
import numpy as np
import cv2
import Queue
# local modules
from video import create_capture
from common import clock, draw_str
Sample_Num = 128
xx1 = lambda x1, x2: int((x1+x2)/2-(x2-x1)*0.2)
xx2 = lambda x1, x2: int... |
#!/usr/bin/env python
from __future__ import print_function, division
from multiprocessing import Pool
import os
from shutil import copy
import glob
from sqlalchemy import or_
from pyql.database.ql_database_interface import Master
from pyql.database.ql_database_interface import session
from pyql.database.ql_database... |
"""This module contains loosely related utility functions used by the Gemicai"""
from string import Template
import os
from tabulate import tabulate
from collections import Counter
from math import log
from matplotlib import pyplot as plt
import numpy as np
import itertools
from sklearn.metrics import confusion_matrix... |
# CRINGE FILE NAME ALERT(PC culture is not even rational)
import sys
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'autogger',
'USER': 'postgres_user',
'PASSWORD': 'postgres_user_password',
'HOST': 'localhost',
'PORT': '5432',... |
# --------------
# Importing header files
import numpy as np
import warnings
warnings.filterwarnings('ignore')
#New record
new_record=[[50, 9, 4, 1, 0, 0, 40, 0]]
#Reading file
data = np.genfromtxt(path, delimiter=",", skip_header=1)
#print(data)
#Code starts here
#Task -1 : In this first ta... |
import pygame
from pygame import color
import os
letter_x = pygame.image.load(os.path.join('res', 'letter_x.png'))
letter_0 = pygame.image.load(os.path.join('res', 'letter_o.png'))
class Grip:
def __init__(self) :
self.grip_line = [((0, 200), (600, 200)), #1st horizontal line
... |
from dbconnect import session, User, Offer, Skills, Languages
from tweetparse import tweetParse
def addUserToDB(mentor, twit_uid, tweet_id, screenname):
userVar = User(mentor_mentee=mentor, twitter_uid=twit_uid, original_tweet_id=tweet_id, scrn_name=screenname)
session.add(userVar)
session.commit()
ret... |
# 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
# d... |
# iNTERFACE 2 - TESTE
from tkinter import *
from tkinter import messagebox
# AINDA EM CONSTRUÇÃO AULA 2
janela = Tk()
janela.title('Systems OS')
janela.geometry('500x400')
w= Spinbox(janela, values=("Python", "HTML", "Java", "Javascript"))
w.pack()
e = Spinbox(janela, values=("carnes", "Verduras", "Legumes", "F... |
#!/usr/bin/env python3
import SimpleITK as sITK
import nibabel as nib
import numpy as np
class nibabelToSimpleITK(object):
'''
Collection of methods to convert from nibabel to simpleITK and vice versa. Note: Only applicable for 3d images for
now.
'''
@staticmethod
def sitkImageFromNib( nibIm... |
#!/usr/bin/env python3
# Programita para implementar el método de bisección
# Busca un cero de f en el intervalo [a,b]
# tol= tolerancia prescripta para detener el método numérico
# (si no sería un ciclo infinito)
# Hipótesis: las del teorema de Bolzano
# f(a) y f(b) deben tener signos opuestos
# f debe ser continua ... |
__author__ = "Samantha Lawler"
__copyright__ = "Copyright 2020"
__version__ = "1.0.1"
__maintainer__ = "Rabaa"
__email__ = "beborabaa@gmail.com"
import numpy as np
import sys
## Class: TestParticle
# Functions: Default Constructor, DataDissection, IdentifyResonance, PrintData
class TestParticle:
def __init__(sel... |
# LPS22HB/HH pressure seneor micropython drive
# ver: 2.0
# License: MIT
# Author: shaoziyang (shaoziyang@micropython.org.cn)
# v1.0 2016.4
# v2.0 2019.7
LPS22_CTRL_REG1 = const(0x10)
LPS22_CTRL_REG2 = const(0x11)
LPS22_STATUS = const(0x27)
LPS22_TEMP_OUT_L = const(0x2B)
LPS22_PRESS_OUT_XL = const(0x28)
... |
from anytree import Resolver, ChildResolverError, Walker
from src.tree_node import TreeNode
class AssetInfoTree:
def __init__(self, texture_info_list):
self.walker = Walker()
r = Resolver('name')
id = 0
self.root = TreeNode('Root', id)
id += 1
for info in text... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# https://www.redblobgames.com/articles/visibility/
# https://en.wikipedia.org/wiki/Art_gallery_problem
"Hover mouse to illuminate the visible area of the room"
from vedo import *
import numpy as np
rw = Rectangle((0,0), (1,1)).texture(dataurl+"textures/paper1.jpg")
tx = ... |
import py
import random, sys, os
from rpython.jit.backend.ppc.codebuilder import BasicPPCAssembler, PPCBuilder
from rpython.jit.backend.ppc.regname import *
from rpython.jit.backend.ppc.register import *
from rpython.jit.backend.ppc import form
from rpython.jit.backend import detect_cpu
from rpython.jit.backend.ppc.ar... |
import discord
from utils import DIGITS
from utils.config import Users
from utils.discord import help_me, get_user, DiscordInteractive
from utils.errors import UserNonexistent, NoPlays
from utils.osu.apiTools import get_recent
from utils.osu.embedding import embed_play
from utils.osu.stating import stat_play
from util... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "Christian Heider Nielsen"
__doc__ = r"""
Created on 08-12-2020
"""
from itertools import tee
from typing import Any, Generator, Iterable
import tqdm
from notus.notification import JobNotificationSession
from warg import drop_unused_... |
from util.tipo import tipo
class S_PARTY_MEMBER_CHANGE_MP(object):
def __init__(self, tracker, time, direction, opcode, data):
print(str(type(self)).split('.')[3]+'('+str(len(data))+'): '+ str(data.get_array_hex(1))[1:-1])
server_id = data.read(tipo.uint32)
player_id = data.read(tipo.uint32... |
import os
from jina.peapods.pods.k8slib.kubernetes_tools import _get_yaml
from jina import Flow
def test_custom_resource_dir():
custom_resource_dir = '/test'
flow = Flow(
name='test-flow', port_expose=8080, infrastructure='K8S', protocol='http'
).add(name='test_executor', k8s_custom_resource_dir... |
from models import OrderModel
from flask_sqlalchemy import sqlalchemy
from config import db
import uuid
class OrderActions():
# Table actions:
@classmethod
def create(cls, usastate: str, order_number: int, home_office_code: str, order_status:int):
theUuid = str(uuid.uuid4())
new_order = OrderMo... |
from io import open
from setuptools import find_packages, setup, Extension
from setuptools.command.build_ext import build_ext
import os
import re
import sys
import shutil
from distutils.version import LooseVersion
from subprocess import check_output
cwd = os.path.dirname(os.path.abspath(__file__))
try:
filepath =... |
#
# PySNMP MIB module IBMIROCAUTH-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/IBMIROCAUTH-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:40:06 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... |
import functools
import numpy as np
from itertools import groupby
import cv2
import torch
from torch import nn
from torch.nn import init
from torch.optim import lr_scheduler
from networks.block import AdaptiveInstanceNorm2d, Identity, AdaptiveInstanceLayerNorm2d, InstanceLayerNorm2d
from lib.alphabet import word_capita... |
import logging
import pytest
import csv
from ocs_ci.ocs import constants, scale_noobaa_lib
from ocs_ci.framework.testlib import scale, E2ETest
from ocs_ci.ocs.resources.objectconfigfile import ObjectConfFile
from ocs_ci.utility.utils import ocsci_log_path
from ocs_ci.ocs.utils import oc_get_all_obc_names
log = loggin... |
import paramUtils
import argparse
import metricsJsonUtils
import os
import json
# Generate a csv file for Design Explorer (DEX)
# from the input parameters and output
# metrics.
# Example output csv file for Design Explorer
"""
in:Inlet Velocity,in:Jet Velocity,in:Pannel Height,out:PMV (person ave),out:PMV (room ave),... |
import logging
import ibmsecurity.utilities.tools
logger = logging.getLogger(__name__)
module_uri = "/isam/felb"
requires_modules = None
requires_version = None
requires_model= "Appliance"
def get(isamAppliance, check_mode=False, force=False):
"""
Retrieving FELB configuration in full
"""
return isa... |
from app.experimental.views import experimental
|
# decompyle3 version 3.3.2
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.8.5 (default, Jul 28 2020, 12:59:40)
# [GCC 9.3.0]
# Embedded file name: lib\bl702\efuse_create_do.py
import os, sys, re, binascii, hashlib
from lib import bflb_utils
from lib import bflb_efuse_boothd_create
ef_sf_aes_mode_list = [
'N... |
import os
import shutil
def get_filename(file_dir):
filenames=[]
for root, dirs, files in os.walk(file_dir):
for file in files:
filenames.append(os.path.join(root, file))
return filenames
# True针对行号False针对列号
def refile(filename, newfilename, rerow=True ,recol=True ):
... |
#!/usr/bin/env python
'''Given desired set of parameters, generates all configurations
obtained by enumerate each parameter individually (continuous are discretized).
'''
import sys, re, MySQLdb, argparse, os, json, subprocess
import pandas as pd
import makemodel
import numpy as np
from MySQLdb.cursors import DictC... |
# -*- coding: utf-8 -*-
# ToMaTo (Topology management software)
# Copyright (C) 2010 Dennis Schwerdel, University of Kaiserslautern
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either vers... |
# This is a modification of stlehmann/Flask-MQTT
# https://github.com/stlehmann/Flask-MQTT
from logzero import logger
import paho.mqtt.client as mqtt
from paho.mqtt.client import ( # noqa: F401
Client,
MQTT_ERR_SUCCESS,
MQTT_ERR_ACL_DENIED,
MQTT_ERR_AGAIN,
MQTT_ERR_AUTH,
MQTT_ERR_CONN_LOST,
... |
__author__ = 'petlja'
from docutils import nodes
from docutils.parsers.rst import directives
from docutils.parsers.rst import Directive
def setup(app):
app.connect('html-page-context', html_page_context_handler)
app.add_stylesheet('notes.css')
app.add_javascript('notes.js')
app.add_directive('infono... |
import discord
from jinja2 import Environment, FileSystemLoader
from configurations import CONFIG
from game_constants import RARITY_COLORS
from search import _
from util import flatten
class Views:
WHITE = discord.Color.from_rgb(254, 254, 254)
BLACK = discord.Color.from_rgb(0, 0, 0)
RED = discord.Color.f... |
def set_clock(time, buttons):
res=[int(time.split(":")[0]), int(time.split(":")[1])]
for i in buttons:
if i=="M":
res[1]=(res[1]+1)%60
elif i=="H":
res[0]=(res[0]+1)%24
return "{:d}:{:02d}".format(res[0] if res[0] else 24, res[1]) |
def outer_function(msg):
def inner_function():
print(msg)
return inner_function
hi_func=outer_function('Hi')
bye_func=outer_function('Bye')
hi_func()
bye_func()
|
import discord
from discord.ext import commands
class Build_info(commands.Cog, name='Build_info'):
def __init__(self, bot):
self.bot = bot
@commands.command(description="Displays build info")
async def build_info(self,ctx,file_override=None):
if file_override is None:
file= 'buildinfo.conf'
with open(fi... |
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 1 23:51:03 2017
@author: Mayur
"""
"""
Grader
A regular polygon has n number of sides. Each side has length s.
The area of a regular polygon is: (0.25∗n∗s^2)/tan(π/n)
The perimeter of a polygon is: length of the boundary of the polygon
Write a function... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019-07-04 11:04
# @Author : minp
# @contact : king101125s@gmail.com
# @Site :
# @File : stockdb.py
# @Software: PyCharm
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["runoobdb2"]
mycol = mydb["sites"]
m... |
import os
import unittest
import pawnpy
basedir = os.path.dirname(os.path.realpath(__file__))
class TestCompile(unittest.TestCase):
def test_compile(self):
pawnpy.cc(os.path.join(basedir, '../pawnpy/pawn/examples/hello.p'),
basedir + '/hello.amx',
os.path.join(basedir... |
from flask import Flask, url_for
from flask_migrate import Migrate
from flask_security import Security
from flask_security.utils import encrypt_password
from flask_admin import helpers as admin_helpers
from adminlte.admin import AdminLte, admins_store, admin_db
from adminlte.models import Role
from adminlte.views impor... |
import time
from pymongo import MongoClient
from kiroku.config import MONGO_LOGIN
client = MongoClient(MONGO_LOGIN)
db = client['krk']
def insert_update(data, collection_name):
"""
Insert if the item has unique _id else update the item.
:param dict data: Data to be inserted into the database
:pa... |
import json
def create_row_w_validated_params(cls, validated_params, rqst_errors):
found_specific_concern_rows = cls.check_for_specific_concern_rows_with_given_question(
validated_params["rqst_specific_concern_question"],
rqst_errors
)
specific_concern_row = None
if not found_specific... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.