content stringlengths 5 1.05M |
|---|
# -*- coding:utf-8 -*-
'''
Created on 2014年2月16日
@author: xuer
'''
import logging
import math
from common.JieQi.JDate import JDate
logger = logging.getLogger(__name__)
# ========角度变换===============
rad = 180 * 3600 / math.pi # 每弧度的角秒数
RAD = 180 / math.pi # 每弧度的角度数
def rad2mrad(v): # 对超过0-2PI的角度转为0-2PI
v = v... |
# 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, ... |
"""
Core bioinformatics abstractions and I/O.
""" |
import base64
import collections
import factorio
import gzip
import lupa
from PIL import Image
import re
import StringIO
def make_table(lua_table):
if isinstance(lua_table, unicode) or isinstance(lua_table, int) \
or isinstance(lua_table, float):
return lua_table
keys = list(lua_table.keys(... |
# project/_config.py
import os
# from datetime import timedelta
# Grabs the folder where the script runs.
basedir = os.path.abspath(os.path.dirname(__file__))
# Enable debug mode.
DEBUG = True
# Secret key for session management.
SECRET_KEY = ""
# Session lifetime (matches lifetime of Esri tokens)
# PERMANENT_SESS... |
from selenium.webdriver.support.select import Select
class ProjectHelper:
def __init__(self, app):
self.app = app
project_cache = None
def open_home_page(self):
wd = self.app.wd
if not (wd.current_url.endswith("manage_proj_page.php") and
len(wd.find_elements_by_n... |
from telebot import types, apihelper
from types import SimpleNamespace
from modules import jsondb, polling
import requests
import telebot
import base64
import json
import re
# Автор: Роман Сергеев
# Электронная почта: grzd.me@gmail.com
# Telegram: @uheplm
# ------------------------------------
# Если вы - программист,... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
__version__ = '1.0.1'
setup(
name='google_music_manager_auth',
python_requires=">=3",
version=__version__,
packages=find_packages(),
author="Jay MOULIN",
author_email="jaymoulin@gmail.com",
descripti... |
# -------------------------------------------------------------------------------------------------------------------------------------------------------------
import sys
# ---------------------------------------------------------------------------------------------------------------------------------------------------... |
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import pip
# numpy and scipy are necessary for scikit-learn
pip.main(['install', 'numpy'])
pip.main(['install', 'scipy'])
setup(
name='skool',
version='0.1.0',
author='Michal Vlasak',
author_email='daeatel@g... |
import colorsys
import numpy as np
import RPi.GPIO as GPIO
import time
rPin =26
gPin =19
bPin =13
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(rPin, GPIO.OUT)
GPIO.setup(gPin, GPIO.OUT)
GPIO.setup(bPin, GPIO.OUT)
GPIO.output(rPin, GPIO.LOW)
GPIO.output(gPin, GPIO.LOW)
GPIO.output(bPin, GPIO.LOW)
re... |
'''
Copyright 2016, EMC, Inc.
Author(s):
George Paulos
'''
import os
import sys
import subprocess
# set path to common libraries
sys.path.append(subprocess.check_output("git rev-parse --show-toplevel", shell=True).rstrip("\n") + "/test/fit_tests/common")
import fit_common
# Select test group here using @attr
from n... |
import os
DATA_PATH = os.path.join("raw_data")
RESULTS_PATH = os.path.join("results")
|
from os import system
class Py3status:
def __init__(self):
#pass
self.c = CountDownTimer(1500)
self.notified = False
"""
Empty and basic py3status class.
NOTE: py3status will NOT execute:
- methods starting with '_'
- methods decorated by @property and @staticme... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#add the path of the twitter egg
import sys
egg_path = '/home/users/web/........./cgi-bin/PyPkg/twitter-1.14.3-py2.7.egg'
sys.path.append(egg_path)
# Import the CGI, string, sys, and md5crypt modules
import json, urllib2, re, time, datetime, sys, cgi, os
import sq... |
from .converter import *
from .classifier import *
__all__ = ['Grocery']
class GroceryException(Exception):
pass
class GroceryNotTrainException(GroceryException):
def __init__(self):
self.message = 'Text model has not been trained.'
class Grocery(object):
def __init__(self, name, custom_token... |
# https://leetcode.com/problems/rotate-image
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
for i in range(len(matrix)):
for j in range(i,len(matrix)):
if i != j:
... |
# 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
# distributed under t... |
# -*- coding: utf-8 -*-
"""
Least-squares Transformation (LST).
See https://iopscience.iop.org/article/10.1088/1741-2552/abcb6e.
"""
import numpy as np
from numpy import ndarray
from scipy.linalg import pinv
from sklearn.base import BaseEstimator, TransformerMixin
from joblib import Parallel, delayed
def lst_kernel(S... |
import numpy as np
from addressing import ImpliedAddressing
from helpers import generate_classes_from_string
from instructions.base_instructions import StackPush, StackPull, RegisterModifier, Inc, Dec
# stack push instructions
from instructions.generic_instructions import Instruction
class Php(ImpliedAddressing, St... |
import os
__location__ = os.path.realpath(
os.path.join(os.getcwd(), os.path.dirname(__file__)))
directory = os.path.join(__location__, 'data/raw')
for name in os.listdir(directory):
print name
# with open() |
from flask import Flask, render_template, Response
import yaml
app = Flask(__name__)
with open("config.yml") as file:
web_config = yaml.load(file, Loader=yaml.FullLoader)
@app.route("/")
def index():
return render_template("index.html", invite_url=web_config["web"]["bot_invite"])
@app.route("/added")
def add... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('CHANGELOG.rst') as history_file:
history = history_file.read()
requirements = [
'Click>=6.0',
'rueckenwind',
'docker',
'pyyaml',
]
test_r... |
from email.mime import image
import praw
import pprint
import requests
import PIL
from PIL import Image
import os
PIL.Image.MAX_IMAGE_PIXELS = 131460604
class Scraper:
def __init__(self, id, secret):
self.reddit = praw.Reddit(client_id=id, client_secret=secret, user_agent='WallpaperScrap... |
import pandas as pd
from cobra.model_building import univariate_selection
def mock_data():
return pd.DataFrame({"var1_enc": [0.42] * 10,
"var2_enc": [0.94] * 10,
"var3_enc": [0.87] * 10})
class TestUnivariateSelection:
def test_preselection_classification(s... |
"""
@file
@brief
@author
@details
"""
from unittest import TestCase
from agent import Agent
class TestAgent(TestCase):
def setUp(self) -> None:
self.agent = Agent(2, 1, 3)
def test_triangular_profile(self) -> None:
self.agent.generate_motion_profile(4, 100)
|
import datetime
import logging
import os
import xml.etree.ElementTree as etree
from io import StringIO
import numpy as np
import pandas as pd
from hydropandas.observation import GroundwaterObs, WaterlvlObs
from lxml.etree import iterparse
logger = logging.getLogger(__name__)
def read_xml_fname(
fname,
ObsCl... |
"""
This controller provides helper methods to the front-end views that manage lookup files.
"""
import logging
import csv
import json
import time
import datetime
from splunk.clilib.bundle_paths import make_splunkhome_path
from splunk import AuthorizationFailed, ResourceNotFound
from splunk.rest import simpleRequest
... |
# -*- coding: utf-8 -*-
__author__ = "radek.augustyn@email.cz"
from cgiserver import runServer, PathContainer
__SYMBOLNAMES = None
__SYMBOLS = None
__DUMP_SYMBOLS_PROC = None
def getWFSData(databaseName, tableName, bbox, srsName, schemaName="", sqlQuery=""):
from shapely.wkb import loads
import geojson
... |
# 使用**解包映射型实参的示例
def puts(n, s):
"""连续打印输出n个s"""
for _ in range(n):
print(s, end='')
d1 = {'n': 3, 's': '*'} # 3个'*'
d2 = {'s': '+', 'n' :7} # 7个'+'
puts(**d1)
print()
puts(**d2)
|
import random
x=0
i = int(raw_input("\nWhich one do you need? (1 = coin, 2 = dice):"))
while x==0:
if i==1:
y = random.randint(1, 2)
if y == 1:
print "heads"
if y == 2:
print "tails"
... |
import pytest
pytest_plugins = ["pytester"]
@pytest.fixture
def sample_test_file(testdir):
testdir.makepyfile(
"""
import pytest
def test_ok():
assert True
def test_not_ok():
assert False
@pytest.mark.parametrize('param', ("foo", "bar"))
... |
"""
Test for issue 51:
https://github.com/pandas-profiling/pandas-profiling/issues/51
"""
from pathlib import Path
import pandas as pd
import pandas_profiling
import requests
import numpy as np
def test_issue51(get_data_file):
# Categorical has empty ('') value
file_name = get_data_file(
"buggy1.pkl... |
import os.path
import re
#import xml.etree.ElementTree as ET
from bs4 import BeautifulSoup
#...................#
#VERSION 6 - 8/30/18
#THIS WORKS - prints all AJ files where search matches, prints paper publication date, and line matches
rootDir = '/Users/jenniferkoch/Documents/astro_software_cite/AJ/'
searchstring... |
import torch
from torch import nn
import torch.nn.functional as F
from .utils import NestedTensor, nested_tensor_from_tensor_list
from .backbone import build_backbone
from .transformer import build_transformer
class Caption(nn.Module):
def __init__(self, backbone, transformer, hidden_dim, vocab_size):
su... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
RULES = [
('Daily, except Xmas day', 'RRULE:FREQ=DAILY;\nEXRULE:FREQ=YEARLY;BYMONTH=12;BYMONTHDAY=25'),
('Daily, Weekdays, except Xmas day',
'RRULE:FREQ=DAILY;BYDAY=MO,TU,WE,TH,FR;\nEXRULE:FREQ=YEARL... |
"""
Create Traffic Study Tables
"""
import pdb
import sys
import psycopg2
import _setpath
from config.secrets import TRAFFIC_STUDY_DB
import table_config
dbname = TRAFFIC_STUDY_DB["dbname"]
user = TRAFFIC_STUDY_DB["user"]
password = TRAFFIC_STUDY_DB["password"]
host = TRAFFIC_STUDY_DB["host"]
port = 5432
pdb.set_tr... |
import webbrowser
class Movie():
"""
The "Movie" class represents a movie object with the following attributes:
Args:
param1(string): Title
param2(int): Release Year
param3(string): Storyline
param4(string): Poster Image URL
param5(string): Trailer Youtube URL
""... |
print('='*8,'Dissecando uma String','='*8)
a = input('Digite algo qualquer:')
print('O tipo primitivo desse valor e {}'.format(type(a)))
print('O valor e alphanumerico? {}.'.format(a.isalnum()))
print('O valor e alfabetico? {}.'.format(a.isalpha()))
print('O valor e um numero? {}.'.format(a.isnumeric()))
print('O valor... |
import re
text = input()
matches = re.finditer(r"(^|(?<=\s))-?([0]|[1-9][0-9]*)(\.[0-9]+)?($|(?=\s))", text)
output = list()
for match in matches:
output.append(match.group())
print(' '.join(output))
|
class request_handler():
"""
This Class Handles the Parsing of Dialogflow Requests and get details like Intent, Parameters, Session ID etc
:param dialogflowRequestJson: The Dialogflow Request JSON
"""
def __init__(self,dialogflowRequestJson):
self.resjson = dialogflowRequestJson
def get... |
#import required packages
from flask import Flask, render_template, request,session
from flask_sqlalchemy import SQLAlchemy
from static.mpesa_config import generate_access_token, register_mpesa_url, stk_push
import os
import pymysql
#create a Flask object
application = Flask(__name__)
#establish a connectio... |
import re
import enchant
from nltk.corpus import stopwords
from nltk.stem.snowball import SnowballStemmer
from nltk.stem import WordNetLemmatizer
from pipe import Pipe
from .patterns import NEGATIVE_CONSTRUCTS
from .patterns import NEGATIVE_EMOTICONS
from .patterns import POSITIVE_EMOTICONS
from .patterns import URLS... |
import qrcode
def get_qrcode(ssid, psk):
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4,
)
qr.add_data("WIFI:S:{0};T:WPA;P:{1};;".format(ssid, psk))
qr.make(fit=True)
return qr.get_matrix()
def get_qrcode... |
from flask import url_for
import flask_admin
from flask_admin import helpers as admin_helpers
from app_core import app, db
from models import security, RestrictedModelView, UserModelView, InvoiceModelView, UtilityModelView, Role, User, BronzeData, Invoice, Utility
# Create admin
admin = flask_admin.Admin(
app,
... |
import os
from environs import Env
env = Env()
env.read_env()
BOT_TOKEN = env.str('BOT_TOKEN')
ADMINS = env.list('ADMINS')
if not BOT_TOKEN:
print('You have forgot to set BOT_TOKEN')
quit()
HEROKU_APP_NAME = os.getenv('HEROKU_APP_NAME')
# webhook settings https://epicker-bot.herokuapp.com/
WEBHOOK_HOST = f... |
import json
def register_user(self):
"""helper function for registering a user."""
return self.client.post(
'api/v1/auth/signup',
data=json.dumps({
"confirm": "password123",
"password": "password123",
"email": 'kamardaniel@gmail.com',
"username":... |
# Copyright 2017 The Armada Authors.
#
# 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 w... |
# -*- coding: utf-8 -*-
#
# ramstk.views.gtk3.design_electric.components.meter.py is part of the RAMSTK
# Project.
#
# All rights reserved.
# Copyright since 2007 Doyle "weibullguy" Rowland doyle.rowland <AT> reliaqual <DOT> com
"""Meter Input Panel."""
# Standard Library Imports
from typing import Any, Di... |
from .octree import *
from .frontend import *
|
from django.apps import AppConfig
class AjaxSelectConfig(AppConfig):
"""
Django 1.7+ enables initializing installed applications
and autodiscovering modules
On startup, search for and import any modules called `lookups.py` in all installed apps.
Your LookupClass subclass may register itself.
... |
from __future__ import division
import numpy as np
from itertools import izip
from dipy.viz import fvtk
from dipy.viz import window, actor
from dipy.viz.axycolor import distinguishable_colormap
from dipy.tracking.streamline import get_bounding_box_streamlines
from itertools import chain
from dipy.viz import interac... |
"""Required modules"""
import re
import csv
import sys
import numpy as np
import scipy.io as sio
import xlrd
import numexpr as ne
DATE = xlrd.XL_CELL_DATE
TEXT = xlrd.XL_CELL_TEXT
BLANK = xlrd.XL_CELL_BLANK
EMPTY = xlrd.XL_CELL_EMPTY
ERROR = xlrd.XL_CELL_ERROR
NUMBER = xlrd.XL_CELL_NUMBER
def read_excel(filename, sh... |
import time
import unittest
from unittest.mock import patch
import pytest
from werkzeug.exceptions import Unauthorized
from flask_slack import decorators
@pytest.mark.usefixtures('client_class', 'config')
class SlackSignatureRequiredTests(unittest.TestCase):
@patch('hmac.compare_digest', unsafe=True)
def t... |
"""Replace Arabic characters."""
# ------------------------ Import libraries and functions ---------------------
from typing import Any
import re
from cleaning_utils.constants import DIACRITICS, DIGITS, LETTERS, NUNATIONS
from cleaning_utils.types import FunctionType
# ---------------------------- function definitio... |
""" Defines the ContourPolyPlot class.
"""
from __future__ import with_statement
# Major library imports
from numpy import array, linspace, meshgrid, transpose
# Enthought library imports
from traits.api import Bool, Dict
# Local relative imports
from base_contour_plot import BaseContourPlot
from contour.contour im... |
# example input:
# categories names and their corresponding intervals
# category at location x corresponds to interval equal or greater than intervals location x and less than location x + 1
# except for last category, has no end
# categories = pd.Series(["low", "moderate", "high", "very high", "extremely high"], dty... |
c_open = '\x1B['
close = c_open + 'm'
colors = {
# fg only
'red':';31m',
'green':';32m',
'white':';37m',
'blue':';34m',
# fg and bg
'redblack':'31;40m',
'greenblack':'32;40m',
'whiteblack':'37;40m',
'blueblack':'34;40m',
'magenta':'35;40m',
'cayn':'36;40m',
'yellow':... |
#!/usr/bin/env python
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License")... |
import streamlit as st
from src import home, about, source, mail, guess_number, guess_word, tic_tac_toe
def init():
st.session_state.page = 'Homepage'
st.session_state.project = False
st.session_state.game = False
st.session_state.pages = {
'Homepage': home.main,
'About me': about.ma... |
import math
import numba
import numpy as np
import torch
import torchvision
from functools import partial
from torch import Tensor
from typing import Any, Dict, List, Tuple, Union
from layers.functions.prior_box import PriorBox
from models.retinaface import RetinaFace
from utils.nms.py_cpu_nms import py_cpu_nms
@num... |
from .discovery import FileDiscovery, load_config
|
from .models import (
User,
Chat,
YandexDiskToken,
UserSettings
)
from .queries import (
UserQuery,
ChatQuery,
YandexDiskTokenQuery
)
|
# i += 1 |
def add_edge(edge1: int, edge2: int, edge_list: int) -> bool:
try:
edge_list.append((edge1, edge2))
return True
except:
return False
#bruteforce search
f=lambda n,e,m=1:any(all(t*m//m**a%m!=t*m//m**b%m for(a,b)in e)for t in range(m**n))and m or f(n,e,m+1)
if __name__ == "__main__":
... |
#!/usr/bin/env python3
#
# Author: Yipeng Sun <syp at umd dot edu>
# License: BSD 2-clause
# Last Change: Thu Mar 11, 2021 at 12:30 AM +0100
import os
import pytest
import yaml
from pyBabyMaker.io.NestedYAMLLoader import NestedYAMLLoader
from pyBabyMaker.io.TupleDump import PyTupleDump
PWD = os.path.dirname(os.path.... |
# Auto-download any Github/Gitlab raw file and save it with custom name
# Jakob Ketterer, November 2020
import urllib.request
import os
if __name__ == "__main__":
file_name = "pred_world_03-07.csv"
# file_name = "ihme-covid19.zip"
dir_name = os.path.join("./data-raw/UCLA-SuEIR", file_name)
url =... |
from .base_datamodule import BaseDataModule
from .scannet_datamodule import ScanNetDataModule
from .synthetic_datamodule import SyntheticDataModule
|
#!/usr/bin/env python3
from LogLevels import LogLevel
from LoggerAbc import Logger
import datetime
class Text_Logger(Logger):
def __init__ (self,logLocation, logSource):
self._logLocation_ = logLocation
self._logSource_ = logSource
def _writeLog_(self, logLevel, logMessage):
logL... |
class arithmetic():
def __init__(self):
pass
''' levenshtein distance '''
def levenshtein(self,first,second):
if len(first) > len(second):
first,second = second,first
if len(first) == 0:
return len(second)
if len(second) == ... |
from file_indexer_api.common.connection_handler_factory import ConnectionHandlerFactory
class Searcher():
def __init__(self):
self.searcher = ConnectionHandlerFactory.create_connection_handler('indexer')
def search(self, query):
return self.searcher.get_handler(query)
|
"""Input/output utility functions for UCCA scripts."""
import os
import sys
import time
from collections import defaultdict
from glob import glob
from itertools import filterfalse, chain
from xml.etree.ElementTree import ParseError
from ucca.convert import file2passage, passage2file, from_text, to_text, split2segments... |
# lint-amnesty, pylint: disable=missing-function-docstring, missing-module-docstring
def plugin_settings(settings):
# Queue to use for updating persistent grades
settings.RECALCULATE_GRADES_ROUTING_KEY = settings.DEFAULT_PRIORITY_QUEUE
# Queue to use for updating grades due to grading policy change
set... |
import requests
import codecs
import os
import time
import json
url = 'http://pinyin.sogou.com/dict/ywz/ajax/make_list.php'
def download(tag_id, tag_page, tag_type="tag"):
fn = 'data-%s-%s-%s.json' % (tag_type, tag_id, tag_page)
if os.path.exists(fn):
print '* exists %s' % fn
return
form = {
'tag_i... |
import sqlalchemy as sa
# Define a version number for the database generated by these writers
# Increment this version number any time a change is made to the schema of the
# assets database
ASSET_DB_VERSION = 2
def generate_asset_db_metadata(bind=None):
# NOTE: When modifying this schema, update the ASSET_DB_V... |
import logging
class hereApi(object):
"""Base class for HERE Search,
which is used to fetch address using HERE.
"""
def __init__(self, config, timeout=None):
"""Returns a Api instance.
Args:
config (array): Json object to fetch keys.
timeout (int): Timeout limit for ... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import math
import operator
import warnings
from typing import Any, List, Union, Dict, Optional, Callable, Iterable, NoReturn, TypeVar
import torch
import torch.nn as nn
from nni.common.serializer import Translatable
from nni.retiarii.serialize... |
from distutils.dir_util import copy_tree, remove_tree
import os
import shutil
def _copy_function(source, destination):
print('Bootstrapping project at %s' % destination)
copy_tree(source, destination)
def create_app():
cwd = os.getcwd()
game_logic_path = os.path.join(cwd, 'game_logic')
game_app_... |
from django.contrib.auth import get_user_model
from django.db import models
User = get_user_model()
class Chat(models.Model):
from_user = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name='from_chats')
to_user = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name='to_chats')
... |
from typing import Optional
from watchmen_auth import PrincipalService
from watchmen_model.admin import User, UserRole
from watchmen_model.common import TenantId, UserId
from watchmen_utilities import is_blank
def fake_super_admin() -> PrincipalService:
return PrincipalService(User(
userId='1',
userName='imma-s... |
import tensorflow as tf
a = tf.linspace(-10., 10., 10)
with tf.GradientTape() as tape:
tape.watch(a)
y = tf.sigmoid(a)
grads = tape.gradient(y, [a])
print('x:', a.numpy())
print('y:', y.numpy())
print('grad:', grads[0].numpy())
|
from respite.inflector import pluralize, cc2us
def route(regex, view, method, name):
"""
Route the given view.
:param regex: A string describing a regular expression to which the request path will be matched.
:param view: A string describing the name of the view to delegate the request to.
:pa... |
from django.db import models
class Account(models.Model):
"""
Stores all attachments of the IHNA accounts to the corefacility accounts
"""
email = models.EmailField(db_index=True, unique=True,
help_text="The user e-mail as typed for the IHNA personal page")
user = mod... |
"""
A module for establishing fractional upper limits on modulation for a
light curve *with calibrated photon weights*. Uses include upper
limits on pulsars and on orbital modulation eclipsing MSP binaries.
The basic idea is to proceed by Monte Carlo. For each iteration, psuedo-
random numbers are drawn from a unifo... |
import logging
import threading
from contextlib import contextmanager
import ipfshttpclient
import multibase
from lru import LRU
from . import unixfs_pb2
logger = logging.getLogger(__name__)
class InvalidIPFSPathException(Exception):
pass
class CachedIPFS:
def __init__(
self,
ipfs_client... |
# Juju requires higher frame size for large models
MAX_FRAME_SIZE = 2**26
# Not all charms use the openstack-origin. The openstack specific
# charms do, but some of the others use an alternate origin key
# depending on who the author was.
ORIGIN_KEYS = {
'ceph': 'source',
'ceph-osd': 'source',
'ceph-mon':... |
# Copyright 2009-2014 Eucalyptus Systems, Inc.
#
# 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; version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# b... |
#-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2020, Anaconda, Inc., and Bokeh Contributors.
# All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-------------------------------------------------------------------... |
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
import backend.Modules.Routes.Routes as Routes
class Notification():
__instance = None
@staticmethod
def getInstance():
""" Static access method. """
i... |
# xxx4pods plugin by AliAbdul
from Podcast import Podcast
##################################################
class xxx4pods(Podcast):
def __init__(self):
Podcast.__init__(self, "xxx4pods", "xxx4pods.png", "http://xxx4pods.com/podcasts/podcast.xml")
##################################################
def getPlug... |
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import os
import pkg_resources
OUTPUT = "output"
HASH_PREFIX = "a"
CONFIG_PARAM_NAME = "/servicecatalog-factory/config"
PUBLISHED_VERSION = pkg_resources.require("aws-service-catalog-factory")[0].version
... |
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
return self.searchInsertRecurse(nums, 0, target)
def searchInsertRecurse(self, nums: List[int], start: int, target: int) -> int:
if not nums:
return 0
mid = len(nums) // 2
... |
from datetime import datetime
from sqlalchemy import desc
from app.models import Session, DatabaseHelper
from app.models.environment import Environment
from app.models.schema.environment import EnvironmentForm
from app.utils.logger import Log
class EnvironmentDao(object):
log = Log("EnvironmentDao")
@stati... |
import pandas as pd
from sqlalchemy import create_engine
import os
import urllib
# Create a connection to the database.
DB_CREDENTIALS = os.environ.get("DATABASE_PARAMS")
SQLALCHEMY_DATABASE_URI = "mssql+pyodbc:///?odbc_connect=%s" % urllib.parse.quote_plus(
DB_CREDENTIALS
)
# Change file variable when an update... |
""" Path to href conversion (and back). """
from mdtools import util
def path_to_href_abs(target, base_dir):
""" Generate absolute href (/root/a/b/c.md)
- target: Path to target
- base_dir_abs: The Path to base directory, used to generate absolute hrefs
- Output: href if successful, or None.
""... |
import json
from django.http import HttpResponseNotAllowed, HttpResponseRedirect, HttpResponse, Http404
from shorturls import ShortURL
from longurls import LongURL
from urlparse import urlparse
import webapp2
import secure.settings as settings
from parsers import Parsers
from trafficfilters import TrafficFilters
import... |
import pytest
from cleo import CommandTester
@pytest.mark.parametrize(
"commandline,expected",
[
("-c my_new_container", "container my_new_container created.\n"),
# ("-m my_container", "X-Object-Meta: test\n"),
# ("-u my_container --headers {\"X-Container-Meta-Test\": \"my metadata\"}"... |
#
# This file is part of LiteDRAM.
#
# Copyright (c) 2018-2021 Florent Kermarrec <florent@enjoy-digital.fr>
# Copyright (c) 2020 Antmicro <www.antmicro.com>
# SPDX-License-Identifier: BSD-2-Clause
import math
from migen import *
from litex.soc.interconnect import stream
from litedram.common import LiteDRAMNativePor... |
"""
入口程序
包都按需导入, 不需要使用的模块则不会导入
因此安装过程可以选用不完整安装
但依赖模块都都是固定的
"""
import sys
import os
from conf import Config
app = None
def can_not_load(name):
print(f"无法加载 {name} 系统, 该系统或其依赖可能不存在", file=sys.stderr)
def main():
"""
入口程序
:return:
"""
if __name__ != "__main__" and Config.program != "websit... |
from rest_framework import mixins, viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import (
AllowAny,
IsAuthenticated
)
from api.serializers import (RetrieveCourseModelSerializer,
ResultContestModelSerializer, ListCours... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.