text stringlengths 1 927k |
|---|
#!venv/bin/python3
from migrate.versioning import api
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO
from FlaskMedia import db
import os.path
db.create_all()
if not os.path.exists(SQLALCHEMY_MIGRATE_REPO):
api.create(SQLALCHEMY_MIGRATE_REPO, 'db repo')
api.version_control... |
import numpy as np
import pytest
import astropy
import astropy.units as u
from astropy.tests.helper import quantity_allclose, assert_quantity_allclose
from astropy.coordinates import (SkyCoord, get_body_barycentric, Angle,
ConvertError, Longitude, CartesianRepresentation,
... |
import json
from os import path
import pytest
from {{cookiecutter.project_slug}} import {{cookiecutter.project_facade}}
@pytest.fixture
def client():
return {{cookiecutter.project_facade}}(token='testing')
@pytest.fixture
def read_fixture():
"""Fixture reader"""
def read_file(file_path):
with ... |
# -*- coding: utf-8 -*-
"""
proxy.py
~~~~~~~~
⚡⚡⚡ Fast, Lightweight, Pluggable, TLS interception capable proxy server focused on
Network monitoring, controls & Application development, testing, debugging.
:copyright: (c) 2013-present by Abhinav Singh and contributors.
:license: BSD, see LICENSE... |
from homeassistant.components.climate import ClimateDevice
from homeassistant.components.climate.const import (HVAC_MODE_AUTO,
PRESET_AWAY,
PRESET_COMFORT, PRESET_ECO,
... |
import numpy as np
JPL_OBLIQUITY = np.deg2rad(84381.448 / 3600.0)
def icrf_to_jpl_ecliptic(x, y, z, vx, vy, vz):
return _apply_x_rotation(JPL_OBLIQUITY, x, y, z, vx, vy, vz)
def jpl_ecliptic_to_icrf(x, y, z, vx, vy, vz):
return _apply_x_rotation(-JPL_OBLIQUITY, x, y, z, vx, vy, vz)
def _apply_x_rotation(... |
"""learning_py URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-b... |
def bubble_sort(lista_entrada):
for i, valor_atual in enumerate(lista_entrada):
try:
if lista_entrada[i + 1] < valor_atual:
lista_entrada[i] = lista_entrada[i + 1]
lista_entrada[i + 1] = valor_atual
bubble_sort(lista_entrada)
except IndexEr... |
#!/usr/bin/env python
import board
import busio
import adafruit_tca9548a
import adafruit_drv2605
i2c = busio.I2C(board.SCL, board.SDA)
tca = adafruit_tca9548a.TCA9548A(i2c)
drv1 = adafruit_drv2605.DRV2605(tca[0])
drv2 = adafruit_drv2605.DRV2605(tca[1])
while True:
drv1.sequence[0] = adafruit_drv2605.Effect(1... |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative wo... |
# coding: utf-8
# Copyright 2017 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... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2017 damian <damian@damian-work>
#
# Distributed under terms of the MIT license.
"""
Testing list, set and tuple, dict and generator
"""
if __name__ == "__main__":
lst = [value for value in range(10) if value %2 == 0]
print(ls... |
from django.urls import path
from . import views
urlpatterns = [
path('create/', views.createAnalysis, name='create'),
] |
import re
import logging
import ckan.lib.base as base
from ckan.common import _, c, g, request, response
# import exceptions as exceptions
import ckan.logic as logic
# import json
import pylons.configuration as configuration
# import ckanext.hdx_users.controllers.mailer as hdx_mailer
# from ckanext.hdx_theme.helpers.f... |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivat... |
from setuptools import setup, find_packages
exec(open("trio/_version.py", encoding="utf-8").read())
LONG_DESC = """\
.. image:: https://cdn.rawgit.com/python-trio/trio/9b0bec646a31e0d0f67b8b6ecc6939726faf3e17/logo/logo-with-background.svg
:width: 200px
:align: right
The Trio project's goal is to produce a prod... |
import numpy as np
from gym.envs.mujoco import mujoco_env
from gym import utils
DEFAULT_CAMERA_CONFIG = {
'trackbodyid': 1,
'distance': 4.0,
'lookat': np.array((0.0, 0.0, 2.0)),
'elevation': -20.0,
}
def mass_center(model, sim):
mass = np.expand_dims(model.body_mass, axis=1)
xpos = sim.data.... |
# 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... |
import os
import time
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import Dataset
class CustomDataset(Dataset): # custom dataset
def __init__(self, x_dat, y_dat):
x = x_dat
y = y_dat
self.len = x.shape[0]
y = y.astype('int')
... |
"""
This module will take care of any uploading to
the db, through this app.
"""
import subprocess
import click
import isort # noqa: F401
import snoop
from loguru import logger
from mysql.connector import Error, connect
fmt = "{time} - {name} - {level} - {message}"
logger.add("../logs/info.log", level="INFO", format... |
import unittest
from .type import EnumType, ValueType
from .spec import TypeSpec, ProductionSpec, PredicateSpec
class TestTrinitySpec(unittest.TestCase):
def test_type(self):
ty0 = EnumType('Type0')
ty1 = ValueType('Type1')
spec = TypeSpec()
spec.define_type(ty0)
spec.defi... |
import torch
from torch import nn
from torch.autograd import Variable
from torch.nn.parameter import Parameter
from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
from .loss_scaler import DynamicLossScaler, LossScaler
FLOAT_TYPES = (torch.FloatTensor, torch.cuda.FloatTensor)
HALF_TYPES = (torch.... |
# Когда у Васи получилось написать его первую задачу, он решил попробовать что-нибудь своё,
# например, вывести на экран фразу Компьютер, я управляю тобой! Но что-то опять пошло не так.
# Помогите Васе дописать программу.
# Sample Input:
#
# Sample Output:
# Компьютер, я управляю тобой!
# print("Компьютер, я управляю т... |
from unittest import TestCase
import numpy as np
from copulas.univariate.base import BoundedType, ParametricType, Univariate
from copulas.univariate.beta import BetaUnivariate
from copulas.univariate.gamma import GammaUnivariate
from copulas.univariate.gaussian import GaussianUnivariate
from copulas.univariate.gaussi... |
import random
from src.board import Board
from src.human_player import HumanPlayer
from src.message import Message
from src.rules import Rules
from src.spanish_message import SpanishMessage
from src.user_interface import UserInterface
from src.validator import Validator
from src.symbol import SymbolOptions
from src.con... |
# Generated by Django 3.1.1 on 2020-09-25 13:52
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('prot... |
# Copyright (c) 2018 PaddlePaddle Authors. 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 appli... |
import argparse
import os
import subprocess
import sys
def log(message, command=False):
prefix = "$" if command else "#"
print(f"{prefix} {message}", file=sys.stderr)
def run_command(description, args, capture_output=True, shell=True):
if description:
log(description)
printed_args = args.joi... |
from django.db import models
class Holiday(models.Model):
year = models.IntegerField(db_index=True)
month = models.SmallIntegerField()
day = models.SmallIntegerField()
name = models.CharField(max_length=255)
class Meta:
unique_together = ('year', 'month', 'day') |
#
# Copyright (c) 2017 Jonathan Weyn <jweyn@uw.edu>
#
# See the file LICENSE for your rights.
#
"""
Module containing database schemas. Please see the default.py schema for
example database structures.
"""
# =============================================================================
# It may no longer be necessary ... |
# Generated by Django 2.0.3 on 2018-09-30 19:24
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('perftracker', '0034_auto_20180930_1813'),
]
operations = [
migrations.RenameField(
model_name='artifactmetamodel',
old_name=... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import warnings
warnings.warn("the ``ned`` module has been moved to astroquery.ipac.ned, "
"please update your imports.", DeprecationWarning, stacklevel=2)
from astroquery.ipac.ned import * |
"""Split into train, val, test. Append period to summary. Filter out too short summary and review. Build vocab"""
from os.path import join
import json
import os
import random
import argparse
from collections import Counter
import pickle as pkl
END_TOKENS = ['.', '!', '?', '...', "'", "`", '"', ")"]
#MIN_SUM_LEN = 6
#... |
from basetestcase import BaseTestCase
from membase.api.rest_client import RestConnection
from gsiLib.gsiHelper import GsiHelper
from plasma.plasma_base import PlasmaBaseTest
class PlasmaStatsTest(PlasmaBaseTest):
def setUp(self):
super(PlasmaStatsTest, self).setUp()
def tearDown(self):
super(... |
# Copyright 2015 gRPC 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 writing... |
# -*- coding: utf-8 -*-
"""Conversion tool from Brain Vision EEG to FIF."""
# Authors: Teon Brooks <teon.brooks@gmail.com>
# Christian Brodbeck <christianbrodbeck@nyu.edu>
# Eric Larson <larson.eric.d@gmail.com>
# Jona Sassenhagen <jona.sassenhagen@gmail.com>
# Phillip Alday <philli... |
import pandas as pd
import numpy as np
from bokeh.plotting import figure, show, output_notebook,ColumnDataSource,curdoc
from bokeh.models import HoverTool, Select, Div
from bokeh.layouts import row, column
from bokeh.transform import dodge
data1 = pd.read_csv('latimes-state-totals.csv')
data1['date_time']=pd.to_datet... |
import graphene
from database.models.DeviceModel import DeviceModel
from database.models.DriverModel import DriverModel
from database.models.UserModel import UserModel
USER_TYPES = ['user', 'driver']
DEVICE_TYPES = ['device']
def get_type_by_obj(obj):
if isinstance(obj, UserModel):
return USER_TYPES[0]
... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import absolute_import, division, print_function, unicode_literals
import numpy as np
from ..utils.compat.odict import OrderedDict
from ..utils.misc import isiterable
__all__ = ['FlagCollection']
class FlagCollection(OrderedDict):
... |
import ftplib
import os
SERVER = 'uncle-**.com'
PORT = 2002
USER = 'test@uncle-**.com'
PASSWORD = ""
ftp = ftplib.FTP()
ftp.connect(SERVER,PORT)
ftp.login(USER,PASSWORD)
mypath = '/testcopyfile/stayu'
ftp.cwd(mypath) # accessed to mypath
path = r'C:\FTP_Work\Download'
allfile = os.listdir(path)
filename = 'test.t... |
from rest_framework import status
from hs_core.hydroshare import resource
from .base import HSRESTTestCase
class TestCustomScimetaEndpoint(HSRESTTestCase):
def setUp(self):
super(TestCustomScimetaEndpoint, self).setUp()
self.rtype = 'GenericResource'
self.title = 'My Test resource'
... |
from fractions import Fraction
class SquareMatrix:
"""정방행렬을 나타내는 클래스."""
def __init__(self, rows):
"""정방행렬 클래스의 initiator.
행렬의 원소를 세팅해준다.
:param rows: 행렬의 각각의 원소인 integer 혹은 Fraction들로 구성된
행렬의 각각의 행인 tuple이나 list들로 구성된
tuple이나 list가 들어와야 한다.
... |
import sentencepiece as spm
s = spm.SentencePieceProcessor('data/jpa_wiki_100000.model')
#file1 = open('jyp_train.txt', 'r')
#Lines = file1.readlines()
# for i in Lines:
# print(i)
path_input_eng = 'data/eng.txt'
path_output_eng = 'data/eng_train_1000.txt'
path_input_jyp = 'data/jyp.txt'
path_output_jyp = 'da... |
###################################################################
# #
# PLOT A LIVE GRAPH (PyQt5) #
# ----------------------------- #
# EMBED A MATPLOTLIB ANIMATION INSIDE... |
""" Decorator Parametors
In the previous ideos we saw some built-in decorators that can handle some arguments:
@wraps(fn) @lru_cache(maxsize=256) <\
def inner(): def factorial(n): \
... ... \>function call
This should loo... |
from blazeweb.config import ComponentSettings
class Settings(ComponentSettings):
def init(self):
self.add_route('/foo', 'foo:UserUpdate')
self.for_me.fooattr = True |
from __future__ import print_function
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
# If modifying these scopes, delete the file token.json.
SCOPES = ... |
import pytest
import os
import shutil
from treeshake import Shaker
def test_add_stylesheet_exists():
shaker = Shaker()
file = './tests/_data/css/stylesheet.css'
shaker.add_stylesheet(file)
added_sheets = shaker.get_private_attributes().get('stylesheets', set())
assert len(added_sheets) == 1
as... |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "swampytodo.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
# Build a version of the site with compressed javascript and css files
import sys, os, re, shutil, glob, tempfile
#********************************************************************************************************
# Run this script from a Visual Studio command prompt
# Start -> All Programs -> Visual Studio 20... |
#!/usr/bin/env python2
"""
Wrapper for libsodium library
Copyright (c) 2013-2014, Marsiske Stefan.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the a... |
import asyncio
from io import StringIO
from asynctest import TestCase as AsyncTestCase
from asynctest import mock as async_mock
from ...admin.base_server import BaseAdminServer
from ...config.base_context import ContextBuilder
from ...config.injection_context import InjectionContext
from ...connections.models.connecti... |
# -*- coding: utf8 -*-
from flask import Flask, request, session, url_for, redirect, \
render_template, abort, g, flash, send_from_directory, \
jsonify, Response
from elasticsearch import Elasticsearch
import logging
import logging.config
# site config
DEBUG = True
HOST = '0.0.0.0'
PORT = 50407
ES_HOST = 'l... |
''' Generic Puzzle Solving Framework
License: MIT
Author: Raymond Hettinger
Simple Instructions:
====================
Create your puzzle as a subclass of Puzzle().
The first step is to choose a representation of the problem
state preferably stored as a string. Set 'pos' to the starting
position and 'goal' to the... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
# -*- coding: utf-8 -*-
# filename: receive.py
import xml.etree.ElementTree as ET
def parse_xml(web_data):
if len(web_data) == 0:
return None
xmlData = ET.fromstring(web_data)
msg_type = xmlData.find('MsgType').text
if msg_type == 'text':
return TextMsg(xmlData)
elif msg_type == 'i... |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative wo... |
import re
import httpx
from bs4 import BeautifulSoup
from convert_to_json import hash_id
from cleanup import delete_from_index
from connection import app_search, engine_name
from upload_to_appsearch import upload_dict
womakers_location_page = httpx.get("https://womakerscode.org/locations")
soup = BeautifulSoup(womak... |
import psycopg2;
import time;
import numpy as np
con = psycopg2.connect(
host = "localhost",
database = "mydb",
user = "brunnom",
password = "postgres"
)
cur = con.cursor();
time1km = []
qtd1km = 0;
time15km = []
qtd15km = 0;
time2km = []
qtd2km = 0;
time25km = []
qtd25km = 0;
time3km = []
qtd3km = 0... |
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from language_model.googlon_language import GooglonLanguage
language_model = GooglonLanguage("")
while True:
text = input(">> ")
language_model.update_language_model(text=text)
language_model.print_analytics() |
"""
Support for MQTT discovery.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/mqtt/#discovery
"""
import asyncio
import json
import logging
import re
import homeassistant.components.mqtt as mqtt
from homeassistant.helpers.discovery import async_load_p... |
import os
import numpy as np
from collections import namedtuple
import logging
from natsort import natsorted
def list_files_in_folder(path, file_type=".rpt",abs_path=False):
""" List all files with a given extension for a given path. The output is sorted
Parameters
----------
path : str
... |
# Copyright 2017 The TensorFlow Authors. 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 applica... |
from flask import Flask,render_template,url_for,request
import pandas as pd
import pickle
import numpy as np
import re
filename = "model.pkl"
cv = pickle.load(open('transform.pkl',"rb"))
clf = pickle.load(open(filename,"rb"))
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
... |
BOARD_SIZE = 8
class BailOut(Exception):
pass
def validate(queens):
left = right = col = queens[-1]
for r in reversed(queens[:-1]):
left, right = left-1, right+1
if r in (left, col, right):
raise BailOut
def add_queen(queens):
for i in range(BOARD_SIZE):
test_queen... |
# Copyright 2017 The TensorFlow Authors. 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 applica... |
import os
import logging
logger = logging.getLogger(__name__)
os.environ["PYOPENCL_COMPILER_OUTPUT"] = "1"
os.environ["PYOPENCL_NO_CACHE"] = "0"
if not os.environ.get("COPPER_HOME"):
cwd = os.getcwd()
logger.info("Using current directory %s as $COPPER_HOME" % cwd)
os.environ["COPPER_HOME"] = cwd
from co... |
"""
Gui tests
https://github.com/asweigart/pyautogui
"""
def test_gui():
assert True |
import discord
from discord.ext import commands
from PIL import Image
import requests
import numpy
import scipy
import scipy.misc
import scipy.cluster
from .converter import GuildConverter, ExtensionConverter
from . import utils
import io
import traceback
from collections import deque
import asyncio
import speedtest
im... |
# Generated by Django 3.1.5 on 2021-01-19 18:09
import colorfield.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('titles', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='titles',
options={'o... |
# coding: utf-8
"""
KAMONOHASHI API
A platform for deep learning # noqa: E501
OpenAPI spec version: v2
Contact: kamonohashi-support@jp.nssol.nipponsteel.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class TrainingAp... |
"""empty message
Revision ID: 884fbf8b24ed
Revises: 84b5ddd15854
Create Date: 2022-02-13 16:31:44.422780
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '884fbf8b24ed'
down_revision = '84b5ddd15854'
branch_labels = None
depends_on = None
def upgrade():
# ... |
#!/usr/bin/env python
from __future__ import unicode_literals
from prompt_toolkit.application import Application
from prompt_toolkit.layout import Layout
from prompt_toolkit.layout.dimension import D
from prompt_toolkit.widgets import Dialog
from ptterm import Terminal
def main():
def done():
application.... |
"""
Python program to reverse a string using stack
"""
def reverse_string(st):
"""
return a string in reverse form
"""
stack = list()
# Push each character into stack
for ch in st:
stack.append(ch)
rev = ""
# Pop each character one by one until stack is not empty
while len... |
from .manager import UserManager
from django.db import models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
objects = UserManager()
username = None
email = models.EmailField(
null=False,
unique=True,
)
nick = models.CharField(
max_length=30... |
from game.pkchess.character import Character
from game.pkchess.utils.character import get_character_template
from tests.base import TestCase
__all__ = ["TestCharacter"]
class TestCharacter(TestCase):
def test_character_from_template(self):
template = get_character_template("Nearnox")
chara = Cha... |
import os
from losses import SSD_LOSS
from utils import data_utils
from networks import SSD_VGG16
import tensorflow as tf
from tensorflow.keras.optimizers import SGD, Adam
from data_generators import SSD_DATA_GENERATOR
from tensorflow.keras.callbacks import ModelCheckpoint, CSVLogger, TerminateOnNaN, LearningRateSchedu... |
from django.urls import include, path
from . import views as utils_views
urlpatterns = [
path('address/<cep>/', utils_views.AddressByCepView.as_view()),
] |
import pdb
import numpy as np
import nose
import cudamat as cm
import learn as cl
def setup():
cm.cublas_init()
def teardown():
cm.cublas_shutdown()
def test_mult_by_sigmoid_deriv():
m = 256
n = 128
c_targets = np.array(np.random.randn(m, n)*10, dtype=np.float32, order='F')
c_acts = np.array(... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 Chris Caron <lead2gold@gmail.com>
# All rights reserved.
#
# This code is licensed under the MIT License.
#
# 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 th... |
# Copyright (c) 2021, Hyunwoong Ko. 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 l... |
"""
Migration script to create tables for tracking workflow invocations.
"""
from __future__ import print_function
import datetime
import logging
from sqlalchemy import (
Column,
DateTime,
ForeignKey,
Integer,
MetaData,
Table
)
from galaxy.model.migrate.versions.util import (
create_table... |
# Copyright 2014-2016 OpenMarket Ltd
#
# 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 -*-
import os
from django.core.management.base import BaseCommand
from common.access_control.base import AccessSet
from account.repository.auth_models import BmProject
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('-project_name')
def handle(s... |
from djangular import middleware
from django.test import SimpleTestCase
from django.http import HttpRequest, HttpResponse
class AngularJsonVulnerabilityMiddlewareTest(SimpleTestCase):
def test_that_middleware_does_nothing_to_html_requests(self):
resp = HttpResponse(content_type='text/html', content='<ht... |
import unittest
import pygments
from bin import highlight
class TestHighlight(unittest.TestCase):
@staticmethod
def has_language_formatter(lang):
try:
pygments.lexers.get_lexer_by_name(lang)
return True
except pygments.utils.ClassNotFound:
return False
d... |
#!/usr/bin/env python
from setuptools import setup
with open('README.md', 'r') as file:
long_description = file.read()
with open('requirements.txt') as file:
install_requires = [line.rstrip('\r\n') for line in file]
setup(
name = 'connectedcars',
packages = ['connectedcars'],
version = '0.1.3',
licen... |
# Copyright 2016 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, s... |
import os
import glob
import shutil
from setup_app import paths
from setup_app.utils import base
from setup_app.static import AppType, InstallOption
from setup_app.config import Config
from setup_app.utils.setup_utils import SetupUtils
from setup_app.installers.base import BaseInstaller
class HttpdInstaller(BaseInsta... |
"""Support for Template vacuums."""
from __future__ import annotations
import logging
import voluptuous as vol
from homeassistant.components.vacuum import (
ATTR_FAN_SPEED,
DOMAIN as VACUUM_DOMAIN,
SERVICE_CLEAN_SPOT,
SERVICE_LOCATE,
SERVICE_PAUSE,
SERVICE_RETURN_TO_BASE,
SERVICE_SET_FAN_... |
from __future__ import print_function, division
#import scipy
import tensorflow as tf
import datetime
import matplotlib.pyplot as plt
#import sys
#from data_loader import DataLoader
import numpy as np
import os
import time
import glob
from scipy.misc import imread,imresize,imsave
import copy
import fire
from elapsedti... |
###################################################################################################
# Libraries
###################################################################################################
from __future__ import division
# Python 3 compatibility
from __future__ import print_function
# Python
fr... |
from django.shortcuts import render
from todo.models import Task
def todo(request):
tasks = Task.objects.all()
print(tasks)
return render(request, 'todo/todo.html', {'tasks': tasks}) |
# 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"); you may not u... |
from direct.controls.InputState import InputState
from pgdrive.utils import import_pygame
from pgdrive.world.pg_world import PGWorld
pygame = import_pygame()
class Controller:
def process_input(self):
raise NotImplementedError
class KeyboardController(Controller):
INCREMENT = 2e-1
def __init_... |
from cookiecutter.main import cookiecutter
from docker_cookiecutter.templates import decode_template_sources
# TODO: Actually implement this.. right now, this is mostly a stub
def cookiecutters(templates: str) -> "list[str]":
sources = decode_template_sources(templates)
result = []
for t in sources:
... |
"""Extract LIEF features from PE files"""
from h2oaicore.transformer_utils import CustomTransformer
import datatable as dt
import numpy as np
class PEImportsFeatures(CustomTransformer):
_modules_needed_by_name = ['lief==0.9.0']
_regression = True
_binary = True
_multiclass = True
_is_reproducible ... |
from common import score_and_decode as sad
from common import read_lines
def SingleCharacterXOR(f):
decoded = [sad.ScoreAndDecode(line)[1] for line in read_lines.ReadLines(f)]
scores = [sad.EnglishLikeScore(l) for l in decoded]
max_index = scores.index(max(scores))
return max_index, scores[max_index], decoded[... |
import atexit
from os import getpid
import shutil
from tempfile import mkdtemp
import logging
def mytmpdir():
if not hasattr(mytmpdir, 'dir') or not mytmpdir.dir:
mytmpdir.dir = mkdtemp(prefix="gimmemotifs.{0}.".format(getpid()))
atexit.register(shutil.rmtree, mytmpdir.dir)
return mytmpdir.dir
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 18-3-28 下午5:01
# @Author : Tom.Lee
# @File : __init__.py
# @Product : PyCharm
# @Source :
from .clazz import Clazz
from .school import School
from .user import User
from ..common import ConsoleLogger, relative_path
logg... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.