content stringlengths 5 1.05M |
|---|
#Pickling
import pickle
class Animal:
def __init__(self, number_of_paws, color):
self.number_of_paws = number_of_paws
self.color = color
class Sheep(Animal):
def __init__(self, color):
Animal.__init__(self, 4, color)
mary = Sheep("white")
print(str.format("My sheep mary is {0} and ha... |
import math
import urllib.request
import os
import glob
import subprocess
import shutil
from tile_convert import bbox_to_xyz, tile_edges
from osgeo import gdal
from argparse import ArgumentParser
from PIL import Image
#---------- CONFIGURATION -----------#
tile_server = "https://tiles-preview.firststreet.org/histori... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 27 07:44:34 2020
@author: danie
"""
from itertools import combinations_with_replacement
x = input().split()
string = sorted(x[0])
size = int(x[1])
items = list(combinations_with_replacement(string,size))
for item in items:
print(''.join(item)) |
from .pdf_element import PdfElement
from ..exc import PdfError
class PdfCatalog(PdfElement):
"""PDF Root catalog element."""
def __init__(self, obj, obj_key=None, document=None):
if obj['Type'] != 'Catalog':
raise PdfError('Type "Catalog" expected, got "{}"'.format(obj['Type']))
... |
#!/usr/bin/env python
'''
Author: Rich Wellum ([email protected])
Adapted and enhanced (fwiw) for use with NX-OS
by Hank Preston ([email protected])
This is a tool to take an NX-OS Base Virtual Box image from CCO and create a
new box that has been bootstrapped for use with Vagrant.
- Initial configuration... |
from django.contrib import admin
from . models import Product
# Register your models here.
admin.site.register(Product) |
#!/usr/bin/env python2
# Copyright (c) 2014 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Test re-org scenarios with a mempool that contains transactions
# that spend (directly or indirectly) coin... |
import pymongo
from datetime import datetime
from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017/')
#db = client['primer']
#coll = db['dataset']
db = client['test']
coll = db['restaurants']
result = coll.insert_one(
{
"address": {
"street": "2 Avenue",
... |
#-----------------------------------------------------------------------
#Copyright 2019 Centrum Wiskunde & Informatica, Amsterdam
#
#Author: Daniel M. Pelt
#Contact: [email protected]
#Website: http://dmpelt.github.io/foam_ct_phantom/
#License: MIT
#
#This file is part of foam_ct_phantom, a Python package for generating... |
import os
import typing
from pathlib import Path
import cv2
import numpy as np
from PyQt5 import Qt
import inspect
from PyQt5 import QtGui
from PyQt5.QtGui import QIcon, QPixmap, QImage, qRgb
from PyQt5.QtWidgets import QLayout, QGridLayout, QLayoutItem, QMessageBox, QApplication, QMainWindow, QVBoxLayout, \
QGroup... |
import abc
import os
import time
import requests
import six
from . import sdk_exceptions
from .clients import JobsClient, ModelsClient
from .clients.base_client import BaseClient
from .logger import MuteLogger
class S3FilesDownloader(object):
def __init__(self, logger=MuteLogger()):
self.logger = logger... |
#!/usr/bin/env python3
from chewing import userphrase
def main():
list = userphrase.find_all()
##print(list)
for item in list:
print()
print('phrase:', item[0])
print('bopomofo:', item[1])
if __name__ == '__main__':
main()
|
import sys
sys.path.append('.')
from util.game import Game
from util.func import Case
from util.card import Card, CardList, CardSuit
from util.player import Player
from typing import List, Optional, Tuple
import random
class LevelUp(Game):
### Constants
PLAYERNUM: int = 4
CARDPOOL: List[Card] = [Card(i) fo... |
#!/usr/bin/env python
"""Tests for `musicdwh` package."""
import pytest
import pandas as pd
from pandas._testing import assert_frame_equal
import sqlalchemy as sqla
from musicdwh.musicdwh import import_hb, import_wwc, import_lov, ip_convert_country, import_game, upload_to_db
HB_FILE_PATH_INS = './data/hb/2021/04/28... |
from qtrader.utils.preprocessor import rolling1d
from qtrader.utils.preprocessor import rolling2d
|
import json
import mimetypes
import os
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.apps import apps
from django.core.servers.basehttp import FileWrapper
from django.http import (HttpResponse, HttpResponseNotFound,
HttpResponseBadRequest, ... |
"""
__init__
Establish this Flask app.
"""
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from flask_httpauth import HTTPBasicAuth
from flask_json import FlaskJSON
import logging
import os
app = Flask(__name__)
app.con... |
#
# Copyright (C) 2018 ETH Zurich, University of Bologna
# and GreenWaves Technologies
#
# 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
#
# U... |
from bs4 import BeautifulSoup as bs
import pandas as pd
import requests
import time
# Returns the page
def fetch_res(url):
return requests.get(url)
# Url structure: root_url + numpages
root_url = "https://news.ycombinator.com/news?p="
numpages = 25
hds, links = [], []
# Generate links for us to fetch
for i in ra... |
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
##############################################################################
# Integration testing for the MIE workflow API
#
# PRECONDITIONS:
# MIE base stack must be deployed in your AWS account
#
# Boto... |
#! /usr/bin/env python
# -*- coding: UTF-8 -*-
__version__ = '0.1.1'
from wptranslate.translator import translate
# Silent pyflakes
translate
|
"""
=================================
Compare (:mod:`macroeco.compare`)
=================================
This module contains functions that compare the goodness of fit of a
distribution/curve to data or the fit of two distributions/curves to each
other.
.. autosummary::
:toctree: generated/
nll
lrt
AIC... |
import argparse
import copy
import os
import time
from flax import linen as nn
from flax import optim
import jax
import jax.numpy as jnp
import numpy as np
import ray
from alpa import (parallelize, global_config, set_parallelize_options, testing,
DeviceCluster, LocalPhysicalDeviceMesh)
from alpa.mo... |
# Custom model builders
from core.misc import MODELS
@MODELS.register_func('UNet_model')
def build_unet_model(C):
from models.unet import UNet
return UNet(6, 2)
@MODELS.register_func('UNet_OSCD_model')
def build_unet_oscd_model(C):
from models.unet import UNet
return UNet(26, 2)
@MODELS.register_... |
"""
The configure.mccs module contains Python classes that represent the various
aspects of MCCS configuration that may be specified in a SubArray.configure
command.
"""
from typing import List
__all__ = [
"MCCSConfiguration",
"StnConfiguration",
"SubarrayBeamConfiguration",
"SubarrayBeamTarget"
]
c... |
#Faça um programa que abra e reproduza um arquivo de audio MP3
#pygame.init()
#pygame.mixer.music.load()
#pygame.mixer.music.play()
#pygame.event.wait() |
import pandas as pd
import re
from yahooquery.utils import (
_convert_to_list, _convert_to_timestamp, _history_dataframe, _flatten_list)
from yahooquery.base import _YahooFinance
class Ticker(_YahooFinance):
"""
Base class for interacting with Yahoo Finance API
Attributes
----------
symbols:... |
# -*- coding: utf-8 -*-
# @Time : 2019/1/27 下午4:09
# @Author : shiwei-Du
# @Email : [email protected]
# @File : __init__.py
# @Software: PyCharm |
# -*- coding: utf-8 -*-
from reversion import revisions as reversion
from django.db.models import Count
from optparse import make_option
from django.core.management.base import BaseCommand
from website.apps.core.models import Language
def condense_classification(classif):
condensers = {
'Austronesian': "A... |
# Copyright (c) 2013, TeamPRO and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe,json
from frappe import msgprint, _
def execute(filters=None):
columns, data = [], []
row = []
columns = get_columns()
data = get_data(filters)
return columns, da... |
'''
@author: Nia Catlin
Various config file handling routines
'''
import ConfigParser, os, time
import _winreg
CONFIG_FILE = None
config = None
def writeConfig():
try:
with open(CONFIG_FILE, 'w') as configfile:
config.write(configfile)#,space_around_delimiters=False)
except: print('Faile... |
import os
import cv2
import argparse
import numpy as np
from tqdm import tqdm
from PIL import Image
# argparse
parser = argparse.ArgumentParser()
parser.add_argument('--load_path', help='load_path', type=str)
parser.add_argument('--save_path', help='save_path', type=str)
args = parser.parse_args()
def get_path():
... |
# for item in "Python":
# print(item)
# for item in ["Mosh", "John", "Sarah"]:
# print(item)
# for item in [1, 2, 3, 4]:
# print(item)
# for item in range(10):
# print(item)
# for item in range(5, 10, 2):
# print(item)
"""
write a program to calculate all shopping item in sh... |
# Generated by Django 2.0.8 on 2019-06-17 08:16
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('wagtailimages', '0001_squashed_0021'),
('app_challenges_sections_units', '0010_auto_20190617_0808'),
]
oper... |
import pytest # Pytest library for Python unit testing
from ukpostcodes.postcode import Postcode
# List of all correct and valid UK post codes
formatting_positive_value = [
"EC1A 1BB", # already formatted
"EC1A1BB", # uppercase but no space
"ec1a1bb", # lower case with no spaces
# Other combination... |
import os
import time
"""
NOTE: @ time of crawling, The domain link should be like http://cse.nitk.ac.in and not like http://cse.nitk.ac.in/
TO DO: remove repeated lines in levels array
"""
fp = open("sitemap_links.txt", "r")
site_links = []
n = 10
levels = [[] for x in range(n)]
link = fp.readline()
# creating ar... |
import asyncio
import dataclasses
from datetime import datetime, timedelta
import json
import logging
import re
from typing import Any, Dict, Tuple, List, Iterable, Optional
import aiohttp
import pandas as pd
import elasticsearch
from bs4 import BeautifulSoup
from newspaper import Article
from omegaconf import DictCon... |
import os
import sys
# Windows only
# Check that git is installed
if os.path.isfile("C:\Program Files\Git\git-cmd.exe") == False:
print("Git not installed. Install to continue, or simply change\npath in code to point to proper exe.")
sys.exit(0)
# Check proper message arguments, define commit message.
try:
msg ... |
"""
Create a mesh from a KnitNetwork by finding the cycles (faces) of the
network.
---
[NOTE] This algorithm relies on finding cycles (quads and triangles) for the
supplied network. This is not a trivial task in 3d space - at least to my
knowledge. Assigning a geometrybase to the KnitNetwork on initialization
and choos... |
#!/usr/bin/python
"""
Plot functions of redshift for RSDs.
"""
import numpy as np
import pylab as P
from rfwrapper import rf
import matplotlib.patches
import matplotlib.cm
import os
cosmo = rf.experiments.cosmo
fname = 'spherex-fsig8-scaledep.pdf'
names = [ 'gSPHEREx1_mgscaledep', 'gSPHEREx2_mgscaledep', 'EuclidRef_... |
import os
import numpy as np
class DeepDIVADatasetAdapter(object):
"""
Creates a directory & file based training environment that natively works with DeepDIVA CNN implementation.
Symlinks are used to reference files in self.root directory.
"""
def __init__(self, input_dir):
self.root = in... |
#py_socket_client_pig.py
import socket
from py_socket_connector_info import\
ip_address, port, protocol_family_name, socket_type
#create a socket:
with socket.socket(protocol_family_name, socket_type) as soc:
soc.connect( (ip_address, port) )
print("Yea! We're talking to {}\n".format(ip_address))
w... |
from django.shortcuts import render
import os
from mimetypes import guess_type
from django.conf import settings
from django.utils.encoding import force_bytes
from wsgiref.util import FileWrapper
from django.http import Http404, HttpResponse
from django.core.urlresolvers import reverse
from django.db.models import Q
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
@AUTHOR:Joselyn Zhao
@CONTACT:[email protected]
@HOME_PAGE:joselynzhao.top
@SOFTWERE:PyCharm
@FILE:20052901.py
@TIME:2020/5/29 19:24
@DES:3. 无重复字符的最长子串
'''
class Solution:
def __init__(self,word):
self.lengthOfLongestSubstring(word)
def lengthOfLongest... |
#!/usr/bin/env python
from time import sleep
from sys import exit
try:
from pyfiglet import figlet_format
except ImportError:
exit("This script requires the pyfiglet module\nInstall with: sudo pip install pyfiglet")
import unicornhat as unicorn
print("""Figlet
You should see scrolling text that is defined... |
#!/usr/bin/env python
from wsgiref.simple_server import make_server
if False:
from serve_wsgi_basic import application
else:
from serve_wsgi_map import application
httpd = make_server('162.242.218.22', 8081, application)
httpd.serve_forever()
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution0437:
def pathSum(self, root, target):
# define global result and path
self.result = 0
... |
from __future__ import absolute_import
# Interface to the Salesforce BULK API
import os
from collections import namedtuple
from httplib2 import Http
import requests
import urllib2
import urlparse
import requests
import xml.etree.ElementTree as ET
from tempfile import TemporaryFile, NamedTemporaryFile
import StringIO
i... |
# Copyright (c) 2020 Graphcore Ltd. All rights reserved.
"""
This module exposes dynamic sparse layers through simple classes with a consistent API.
There are also dense layers wrapped in the same interface in order to make it easier
to build models where the layers can be switched from sparse to dense easily.
The spa... |
"""add config table
Revision ID: 088598e662be
Revises: 6a55d8748a29
Create Date: 2017-07-17 18:21:14.762529
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '088598e662be'
down_revision = '6a55d8748a29'
branch_labels = None
depends_on = None
configs = sa.table... |
#!/usr/bin/env python3
from SPARQLWrapper import SPARQLWrapper, JSON
import validators
import requests
import json
#############
# Constants
__author__ = "Sylvain Boissel <[email protected]>"
SPARQL_TIMEFORMAT = "%Y-%m-%dT%H:%M:%SZ"
WD_ROOT_URL = 'https://www.wikidata.org'
WD_BASE_URL = WD_ROOT_URL + '/wiki/'
WD_A... |
from django.test import TestCase
from models import Image, Comment, Profile
import datetime as dt
from django.contrib.auth.models.import User
# Create your tests here.
|
from checkov.terraform.context_parsers.base_parser import BaseContextParser
class DataContextParser(BaseContextParser):
def __init__(self):
definition_type = "data"
super().__init__(definition_type=definition_type)
def get_entity_context_path(self, entity_block):
entity_type = next(it... |
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
#
# Ubuntu System Tests
# Copyright (C) 2014-2016 Canonical
#
# 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 v... |
__author__ = 'alanseciwa'
'''
This code removes b' characters from utf-8 formatted tweets. This allows tweets to have hex values
of emojis used in tweets. After stripping away the unwanted characters, it is outputted to a new
cvs file.
'''
import sys
import csv
def clean(t):
# set csv file to variable
csv... |
# Reverse the order of words
def rev_words(sentence):
words = sentence.split()
return ' '.join(words[::-1])
sentence = 'perfect makes practice';
res = rev_words(sentence)
print(len(res))
for c in sentence:
print(f"'{c}', ", end='') |
import pytest
class TestDocTrackingPandasDataframe:
@pytest.mark.skip()
def test_doc(self):
# Python 3.6.8
from dbnd import log_metric, log_dataframe
import pandas as pd
transactions_df = pd.read_csv("data/example.csv")
# log dataframe
log_dataframe(
... |
from django.shortcuts import render
from .datatables import BookDataTables
from sspdatatables.utils.decorator import ensure_ajax, dt_json_response
from collections import OrderedDict
def overview(request):
book_datatables = BookDataTables()
context = book_datatables.get_table_frame()
context.update({
... |
import pandas as pd
from time import sleep
from airbnb_pricer.utils.async_run import async_run
from airbnb_pricer.airbnb.skipped_columns import skipped_columns
def load_airbnb_links(cur_links_table):
cur_urls = cur_links_table.url.tolist()
cur_tables = async_run(_load_airbnb_link, cur_urls)
cur_links_ta... |
"""
Summary: Contains classes for the database.
Classes: BaseModel with subclasses Program
"""
from peewee import *
import json
with open("config.json", "r") as f:
config = json.load(f)
print config
db = SqliteDatabase(config["dbname"])
class BaseModel(Model):
class Meta:
database = db
cla... |
import numpy as np
import pandas as pd
from sklearn.metrics import mean_absolute_error
from estimate_start_times.config import DEFAULT_CSV_IDS, EventLogIDs
logs = [
"insurance",
"BPI_Challenge_2012_W_Two_TS",
"BPI_Challenge_2017_W_Two_TS",
"Application_to_Approval_Government_Agency",
"callcentre",... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
carry = 0
start, prev = l1, None
# both lists haven't ... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 11 09:33:07 2020
@author: HI
"""
import xlwings as xw
import math
from scipy.stats import norm
@xw.func
def GBlackScholesNGreeek(S,X,T,r,q,sigam,corp):
data=[S,X,T,r,q,sigam,corp]
d1=(math.log(data[0]/data[1])+(data[4]+data[5]**2/2)*data[2]/365)/((data[5])*math... |
from .migration_target import MigrationTarget
from .mount_point import MountPoint
from .workload import Workload
from .serializable import Serializable
from enum import Enum
from time import sleep
X = 5
class MigrationState(Enum):
NOT_STARTED = 1
RUNNING = 2
ERROR = 3
SUCCESS = 4
class Migration(S... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('vendors', '0020_auto_20140930_1435'),
]
operations = [
migrations.RunSQL(
"""ALTER TABLE "vendors_vendor" ALTER ... |
#!/usr/bin/env python3
import isce
import numpy as np
import shelve
import os
import logging
import argparse
from isceobj.Constants import SPEED_OF_LIGHT
import datetime
from isceobj.Util.Poly2D import Poly2D
def cmdLineParse():
'''
Command line parser.
'''
parser = argparse.ArgumentParser(descriptio... |
#! python3
# messenger.py - Weather API that sends me text messages
from twilio.rest import Client
import requests, bs4
# rest API from twilio
# Your Account SID from twilio.com/console
account_sid = "AC7226356ef66d2de53d535237cba9e2dc"
# Your Auth Token from twilio.com/console
auth_token = "xxxxxxxxxxxxxxxxxxxxxxx... |
import os
os.fsformat('/flash')
|
from malcolm.core import Part, method_takes, REQUIRED
from malcolm.modules.builtin.vmetas import StringMeta
@method_takes(
"name", StringMeta("Name of the Part within the controller"), REQUIRED)
class DummyPart(Part):
"""Defines a dummy part"""
def __init__(self, params):
super(DummyPart, self).__... |
"""3D mesh manipulation utilities."""
from builtins import str
from collections import OrderedDict
import numpy as np
from transforms3d import quaternions
from transforms3d.quaternions import axangle2quat, mat2quat
import os.path as osp
import pyassimp
import pprint
import hashlib
import mmcv
cur_dir = osp.dirname(os... |
def ackermann(m, n):
if m == 0:
return n+1
elif m > 0:
if n == 0:
return ackermann(m-1, 1)
elif n > 0:
return ackermann(m-1, ackermann(m, n-1))
print 'invalid input'
if __name__ == '__main__':
print ackermann(3, 4)
print ackermann(-1, 2)
|
import time
import numpy as np
import tensorflow as tf
def average_completion(exp):
completion_time = 0
number_task = 0
for job in exp.simulation.cluster.jobs:
for task in job.tasks:
number_task += 1
# completion_time += (task.finished_timestamp - task.started_timestamp) # ... |
# coding: utf-8
import sublime
st_version = int(sublime.version())
if st_version > 3000:
from JoomlaPack.lib.file import File
from JoomlaPack.lib.folder import Folder
from JoomlaPack.lib.helper import Helper
from JoomlaPack.lib.json import Json
from JoomlaPack.lib.manifest import Manifest
from ... |
import pytest
import socket
# import main.client
# from main.client import prompt
# import main.server
from main.util import Hall, Room, User, create_socket
from main.banner import Ascii_Banner, Text
def test_can_successfully_create_to_a_hall():
hall = Hall()
assert hall
def test_Ascii_Banner():
msg = 'msg'... |
import threading
import taco.constants
import logging
import os
import uuid
import Queue
settings_lock = threading.Lock()
settings = {}
chat_log = []
chat_log_lock = threading.Lock()
chat_uuid = uuid.uuid4().hex
chat_uuid_lock = threading.Lock()
stop = threading.Event()
public_keys_lock = threading.Lock()
public_... |
#
# Copyright (c) 2017 nexB Inc. and others. All rights reserved.
# http://nexb.com and https://github.com/nexB/scancode-toolkit/
# The ScanCode software is licensed under the Apache License version 2.0.
# Data generated with ScanCode require an acknowledgment.
# ScanCode is a trademark of nexB Inc.
#
# You may not use... |
# -*- Mode: Python; tab-width: 2; indent-tabs-mode:nil; -*-
# vim: set ts=2 et sw=2 tw=80:
#
# Copyright (c) 2013 The MathJax Consortium
#
# 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
#
# ht... |
"""
Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants represented by strings.
You need to help them find out their common interest with the least list index sum. If there is a choice tie between answers, output all of them with no order requirement. You co... |
import os
import re
import socket
import sys
from enum import Enum
import click
import hjson as json
import inotify.adapters
import inotify.constants
from prometheus_client import Gauge
class Module(Enum):
DHCP4 = 1
DHCP6 = 2
class KeaExporter:
subnet_pattern = re.compile(
r"subnet\[(?P<subnet_... |
import FWCore.ParameterSet.Config as cms
from Calibration.TkAlCaRecoProducers.ALCARECOSiStripCalCosmics_cff import ALCARECOSiStripCalCosmics
from CalibTracker.SiStripCommon.prescaleEvent_cfi import prescaleEvent
from HLTrigger.HLTfilters.triggerResultsFilter_cfi import triggerResultsFilter
ALCARECOSiStripCalCosmicsNa... |
from __future__ import print_function
import os
import numpy as np
import pickle as pk
from glob import glob as glob
from .imdb import IMDB
from common.utility.utils import calc_total_skeleton_length, calc_kpt_bound_pad, \
compute_similarity_transform, calc_total_skeleton_length_bone
from common.utility.visuali... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for the RC4 decrypter object."""
import unittest
from cryptography.hazmat.primitives.ciphers import algorithms
from dfvfs.encryption import decrypter
from dfvfs.lib import definitions
from tests.encryption import test_lib
class DecrypterTestCase(test_lib.Decr... |
__version__ = '0.1.0'
default_app_config = 'telegrambot.apps.TelegrambotConfig'
|
import os
here = os.path.dirname(__file__)
DEBUG = True
TEMPLATE_DEBUG = DEBUG
USE_SAML2 = False
ADMINS = (
('Gijs Molenaar', '[email protected]'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(here, '../../database/sqlite3.db'),
... |
# -*- coding: utf-8 -*-
"""
@file
@brief Abstract class to connect to a SQL server using various way.
It will be used to implement magic functions
"""
import re
import sqlite3
class InterfaceSQLException(BaseException):
"""
a specific exception
"""
def __init__(self, message):
"""
@... |
from . import backend
from . import datasets
from . import losses
from . import metrics
from . import model
from .optim import *
from .utils import *
from .testing import *
|
# -*- coding: utf-8 -*-
import os
from flask import Blueprint, render_template, send_from_directory, abort, redirect, url_for, flash
from flask import current_app as APP
from flask.ext.login import login_user, login_required, current_user
from fbone.extensions import db, login_manager
from fbone.core.oauth import OAu... |
import argparse
import json
import yaml
import os
from os.path import join, basename, splitext
def pp_json(json_thing, sort=True, indents=4):
if isinstance(json_thing, str):
print(json.dumps(json.loads(json_thing), sort_keys=sort, indent=indents))
else:
print(json.dumps(json_thing, sort_keys=s... |
#!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset:4 -*-
###############################################################################
#
# Copyright (C) 2015, 2016 Daniel Rodriguez
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License ... |
for i in range(1,100):
print(i) |
"""Patching modules and objects"""
import contextlib
import sys
def begin_patch(module, member, new_value):
if isinstance(module, str):
if module not in sys.modules:
return None
module = sys.modules[module]
if not hasattr(module, member):
old_member = None
else:
... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Score'
db.create_table(u'ratings_score', (
(u... |
"""
Sample definitions.
"""
from pymontecarlo.options.sample.base import *
from pymontecarlo.options.sample.substrate import *
from pymontecarlo.options.sample.inclusion import *
from pymontecarlo.options.sample.horizontallayers import *
from pymontecarlo.options.sample.verticallayers import *
from pymontecarlo.option... |
from gym_kuka_mujoco.utils.insertion import hole_insertion_samples
import os
import mujoco_py
# Get the model path
model_filename = 'full_peg_insertion_experiment.xml'
model_path = os.path.join('..','..', 'gym_kuka_mujoco', 'envs', 'assets',
model_filename)
# Construct the model and simulati... |
# Generated by Django 3.0.10 on 2020-11-29 18:26
from django.db import migrations
import kaffepause.accounts.models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0001_initial'),
]
operations = [
migrations.AlterModelManagers(
name='account',
... |
#!/usr/bin/env python
# coding: utf-8
# Copyright (c) - Damian Avila
# pylint: disable = C0103
"""
Packaging
"""
# inspired from
# http://jupyter-notebook.readthedocs.io/en/stable/examples/Notebook/Distributing%20Jupyter%20Extensions%20as%20Python%20Packages.html#Example---Server-extension-and-nbextension
import o... |
"""
DIA-PreResNet for CIFAR/SVHN, implemented in Gluon.
Original papers: 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
"""
__all__ = ['CIFARDIAPreResNet', 'diapreresnet20_cifar10', 'diapreresnet20_cifar100', 'diapreresnet20_svhn',
'diapreresnet56_cifar10', 'diapre... |
from MOOSEplot import geoplot as gp
from MOOSEplot import plotCommon as pc
from datetime import datetime
from matplotlib import pyplot as plt
## First define a StandardPlot object from GeoPlot.
Gplot=gp.StandardPlot()
## Load and Parse the namelist.
## Note, you will likely need to change the wrf_path in the namelist... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# look this: http://picamera.readthedocs.io/en/release-1.2/recipes1.html
import io
import os
import sys
import time
import struct
import socket
import picamera
from PIL import Image
import cv2
import numpy as np
def photographToFile():
# Explicitly open a new file cal... |
import os,random
from threading import Thread
from time import sleep
import playsound
from termcolor import colored
from config import *
import numpy as np
from PIL import Image
def get_ansi_color_code(r, g, b):
if r == g and g == b:
if r < 8:
return 16
if r > 248:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.