content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
#CGI(Common Gateway Interface),通用网关接口,它是一段程序,运行在服务器上如:HTTP服务器,提供同客户端HTML页面的接口
'''
开启apache: sudo apachectl start
重启apache: sudo apachectl restart
关闭apache: sudo apachectl stop
'''
#http://localhost/cgi-bin/hello.py
#/private/etc/apache2/httpd.conf apache服务器的配置路径
#/资源库/WebServer/Documents apache服务器访问路径
#/资... | python |
class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
idx = len(nums1) - 1
hi1, hi2 = m -... | python |
"""Manages plotting, provides a single interface
for different plots with different backends."""
from __future__ import print_function, absolute_import
import os
import sys
import importlib
import traceback
import numpy
from matplotlib.colors import LinearSegmentedColormap
from vcs.colors import matplotlib2vcs
import ... | python |
# -*- coding: utf-8 -*-
"""
@author: Aditya Intwala
Copyright (C) 2016, Aditya Intwala.
Licensed under the Apache License 2.0. See LICENSE file in the project root for full license information.
"""
import cv2
from Core.Math.Point2 import Point2
class Eraser():
@staticmethod
def ErasePixel(img, pixel):
... | python |
#!/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 "Licen... | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-10-25 15:27
from __future__ import unicode_literals
import calaccess_raw.annotations
import calaccess_raw.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('calaccess_raw', '0007_auto_20160831_0132'... | python |
import numpy as np
import matplotlib.pyplot as plt
import struct
import os, sys
import re
import copy
class Matrix:
"""
Class to Read and Hangle Matrix files
"""
def __init__(self,Path): # Give the Path of the folder containing all the mtrx files
# Read PATH and open file
self.Path = Pa... | python |
import os
import sys
import logging
import json
import typing
import collections
from ConfigSpace.configuration_space import ConfigurationSpace, Configuration
from ConfigSpace.hyperparameters import FloatHyperparameter, IntegerHyperparameter
__author__ = "Marius Lindauer"
__copyright__ = "Copyright 2016, ML4AAD"
__li... | python |
#!/usr/bin/env python3
# This is run by the "run-tests" script.
import unittest
import signal
import socket
class TestTimeout(unittest.TestCase):
def test_timeout(self):
port = 12346
s = socket.socket()
s.connect(("0.0.0.0", port))
# Assumes the server has --timeout 1
signal... | python |
import numpy as np
matrizquadrada = int(input("Definir o tamanho Matriz: "))
Geracoes = int(input("Definir quantas geracoes: "))
# Considerando 1 como celula viva e 0 como celula morta.
# Rodar o jogo no terminal
# A cada geração irá aplicar as condições do jogo, criando assim uma nova matriz atualizada.
def atual... | python |
import itertools
def reduce_undefined(obj):
if isinstance(obj, dict):
r = {}
for k, v in obj.items():
if v == UNDEFINED:
pass
else:
r[k] = reduce_undefined(v)
return r
elif isinstance(obj, (tuple, list)):
r = []
for ... | python |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import abc
import time
import datetime
import importlib
from pathlib import Path
from typing import Type, Iterable
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
import pandas as pd
from tqdm import tqdm
from loguru impo... | python |
#!/usr/bin/env python
## This file comes from Jennifer Fourquier's excellent ghost-tree project
## Some modifications by Lela Andrews to fit within akutils framework
##
## Ghost-tree is provided under BSD license
##
## Copyright (c) 2015--, ghost-tree development team.
## All rights reserved.
##
"""
This file can be do... | python |
from distutils import log
from setuptools import setup
try:
from setuptools.command import egg_info
egg_info.write_toplevel_names
except (ImportError, AttributeError):
pass
else:
def _top_level_package(name):
return name.split('.', 1)[0]
def _hacked_write_toplevel_names(cmd, basename, file... | python |
import sys
from collections import OrderedDict
from functools import partial
import torch
import torch.nn as nn
import torch.nn.functional as functional
from ptsemseg.models._util import try_index
from modules import IdentityResidualBlock, ABN, GlobalAvgPool2d
from modules.bn import ABN, InPlaceABN, InPlaceABNSync
... | python |
import logging
from flask import Flask
from flask.logging import default_handler
from flask_logging_decorator import trace
app = Flask(__name__)
app.logger.setLevel(logging.WARN)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
default_handler.setFormatter(formatter)
@app.rout... | python |
import logging
import os
import torch
from transformers import BertTokenizer
from .data_cls import BertDataBunch
from .learner_cls import BertLearner
from .modeling import (
BertForMultiLabelSequenceClassification,
XLNetForMultiLabelSequenceClassification,
RobertaForMultiLabelSequenceClassification,
Dis... | python |
"""
handles logging for:
- auth
- contact
- msg
- label
- report
- att
modules
"""
import csv
from datetime import datetime
import os
import shutil
from config import config
log_dir = config.data["log"]["log_dir"]
logfiles = config.data["log"]["logfiles"]
def get_logpath(logtype):
filen... | python |
import io
import json
import unittest
from datetime import datetime
from unittest.mock import Mock
import boto3
from botocore.response import StreamingBody
from botocore.stub import Stubber, ANY
from redis import StrictRedis
from s3_log_shipper.parsers import ParserManager, Parser
from s3_log_shipper.shipper import R... | python |
from pyramid.config import Configurator
from pyramid.static import static_view
import kinto.core
def includeme(config):
config.scan("kinto.tests.core.testapp.views")
# Add an example route with trailing slash (here to serve static files).
# This is only used to test 404 redirection in ``test_views_errors... | python |
class BaseFilter:
"""
This is the reference implementation for all filters/hooks.
Just passes the data as-is without changing it.
"""
def register(self, kernel, shell):
self.kernel = kernel
self.shell = shell
shell.events.register('post_run_cell', self.post_run_cell)
... | python |
"""
常见的颜色名称
"""
color_dict={
"almond":(239,222,205),
"amaranth":(229,43,80),
"amazon":(59,122,87),
"amber":(255,191,0),
"sae":(255,126,0),
"amethyst":(153,102,204),
"ao":(0,128,0),
"apricot":(251,206,177),
"aqua":(0,255,255),
"aquamarine":(127,255,212),
"arsenic":(59,68,75),
"artichoke":(143,151,121),
"asparagus":(135,... | python |
import argparse, operator
from collections import defaultdict
from gpToDict import gpToDict, makeEntities
from utility import readFromFile
def run(target):
fileType = target.split('.')[-1]
if fileType == 'data':
entities = makeEntities(gpToDict(target)[0])
elif fileType == 'json':
entities ... | python |
from modules.discriminator import MultiScaleDiscriminator, RandomWindowDiscriminator
from modules.generator import Aligner, Decoder, Encoder
from modules.mel import MelSpectrogram
| python |
from django_roa.remoteauth.models import User
from django.contrib.auth.backends import ModelBackend
class RemoteUserModelBackend(ModelBackend):
"""
Authenticates against django_roa.remoteauth.models.RemoteUser.
"""
def authenticate(self, username=None, password=None, **kwargs):
try:
... | python |
"""
Mountain Car environment adapted from OpenAI gym [1].
* default reward is 0 (instead of -1)
* reward in goal state is 1 (instead of 0)
* also implemented as a generative model (in addition to an online model)
* render function follows the rlberry rendering interface.
[1] https://github.com/openai/gym/blob/m... | python |
from django.conf import settings
from django.conf.urls import patterns, url, include
from views import login, logout, connect
urlpatterns = patterns('',
url(r'^login/$', login,
{'template_name': 'registration/login.html'}, name='fb_login'),
url... | python |
from django.contrib import admin
from .models import Category, Product, LaptopsCategory, SmartPhonesCategory
from django import forms
from django.forms import ValidationError
from PIL import Image
# Настройка изображения
class AdminForm(forms.ModelForm):
MIN_RESOLUTION = (400, 400)
def __init__(self, *args, ... | python |
'''
Created on Nov 13, 2017
@author: khoi.ngo
'''
# /usr/bin/env python3.6
import sys
import asyncio
import json
import os.path
import logging.handlers
# import shutil
import time
import random
from indy import signus, wallet, pool, ledger
from indy.error import IndyError
import abc
sys.path.append(os.path.join(os.pat... | python |
# Copyright 2017 Division of Medical Image Computing, German Cancer Research Center (DKFZ)
#
# 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
#... | python |
from os import read
import sys
import argparse
import numpy as np
import shlex
import subprocess
import numpy as np
from operator import itemgetter
def init_chrom_list():
chrom_list = []
for i in range(1, 23):
chrom_list.append(str(i))
chrom_list.append('X')
chrom_list.append('Y')
return(ch... | python |
from itertools import takewhile
import os
import setuptools
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as f:
long_description = str.join('', takewhile(lambda l: not l.startswith('Installation'), f.readlines()[15:]))
setuptools.setup(
name = 'OverloadingFixed',
version = '1.11',
... | python |
# -*- coding: utf-8 -*-
# Copyright 2014 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
import os
import unittest
from splinter import Browser
from .base import BaseBrowserTests
from .fake_webapp import app, EXAMPLE_APP
fro... | python |
import pandas as pd
from ggplot import *
import sys
def data_clean():
dat = pd.read_csv(sys.argv[1], header=False)
dat1 = dat
dat = dat.drop(['q1','lambda1','mu1'], axis=1)
dat1 = dat1.drop(['q0','lambda0','mu0'], axis=1)
dat['Parity'] = 'Viviparity'
dat1['Parity'] = 'Oviparity'
dat.columns = ['Lambda','Mu','Q'... | python |
#python program to reverse the array
array = [10,20,30,40,50];
print("Array in reverse order: ");
#Loop through the array in reverse order
for i in range(len(array)-1, -1, -1):
print(array[i])
| python |
# pylint: disable=missing-function-docstring, missing-module-docstring/
def ones():
print(22)
from numpy import ones
g = ones(6)
print(g)
| python |
#!/usr/bin/env python
import sys, os
import pprint
""" Hardlink UCI History oral histories files for loading into Nuxeo """
raw_dir = u"/apps/content/raw_files/UCI/UCIHistory/OralHistories/ContentFiles/"
new_path_dir = u"/apps/content/new_path/UCI/UCIHistory/OralHistories/"
pp = pprint.PrettyPrinter()
def main(argv=... | python |
import argparse
import yaml
import logging
import numpy as np
import glob
from astropy.coordinates import SkyCoord, Angle
from astropy import units as u
from astropy.convolution import Tophat2DKernel, Gaussian2DKernel
from os import path
from copy import deepcopy
from fermiAnalysis.batchfarm import utils
from simCRprop... | python |
#!/usr/bin/env python
#
# Copyright (c) 2001 - 2016 The SCons Foundation
#
# 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 us... | python |
from toykoin.daemon.messages import _verify_headers, add_headers
import pytest
def test_headers():
_verify_headers(add_headers("version", b""))
_verify_headers(add_headers("version", b"\x01"))
_verify_headers(add_headers("a" * 12, b"\x01"))
with pytest.raises(Exception, match="Wrong payload length"):... | python |
from django.conf.urls import patterns, include, url
from django.views.generic.base import TemplateView
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
url(r... | python |
import os
from flask import Flask, render_template, url_for, request, redirect
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object('config.DevelopmentConfig')
app.secret_key = app.config.get('SECRET_KEY')
db = SQLAlchemy(app)
from . import routes | python |
import pytest
from dredis.commands import REDIS_COMMANDS
# got the list from a real redis server using the following code:
"""
import pprint
import redis
r = redis.StrictRedis()
commands = r.execute_command('COMMAND')
pprint.pprint({c[0]: int(c[1]) for c in commands})
"""
EXPECTED_ARITY = {
'append': 3,
'aski... | python |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'threading_design.ui'
#
# Created: Thu Aug 6 13:47:18 2015
# by: PyQt4 UI code generator 4.10.4
from PyQt5 import QtCore, QtGui
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from PyQt5.QtWidgets impor... | python |
# global
import torch
from typing import Union, Optional, Tuple, List
def argsort(x: torch.Tensor,
axis: int = -1,
descending: bool = False,
stable: bool = True)\
-> torch.Tensor:
return torch.argsort(x, dim=axis, descending=descending)
| python |
#!/usr/bin/env python
import os, sys
temp=list();
header=1;
sys.path.append('../../Libs/Python')
from BiochemPy import Reactions, Compounds, InChIs
CompoundsHelper = Compounds()
Compounds_Dict = CompoundsHelper.loadCompounds()
Structures_Dict = CompoundsHelper.loadStructures(["InChI"],["ModelSEED"])
diff_file = open... | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-02-10 19:34
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='GreenSh... | python |
import shutil
import os
from dataclasses import dataclass
from typing import Generator
import pytest
import fabsite
from test import path
@dataclass
class Pages:
blog_path: str
undated_path: str
dated_path: str
normal_post_path: str
md_post_path: str
no_md_post_path: str
@pytest.fixture
de... | python |
"""
Configuration utils.
Author: Henrik Thostrup Jensen <htj@ndgf.org>
Copyright: Nordic Data Grid Facility (2009, 2010)
"""
import ConfigParser
import re
from sgas.ext.python import ConfigDict
# configuration defaults
DEFAULT_AUTHZ_FILE = '/etc/sgas.authz'
DEFAULT_HOSTNAME_CHECK_DEPTH = '2'
# serve... | python |
# -*- coding: utf-8 -*-
'''utility module for package rankorder.'''
import numpy as np
def rankdata(a, method):
'''assigns ranks to values dealing appropriately with ties.
ranks start at zero and increase with increasing value.
the value np.nan is assigned the highest rank.
Parameters... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# imaparchiver/__main__.py
#
# imaparchiver package start
#
# This file is part of imaparchiver.
# See the LICENSE file for the software license.
# (C) Copyright 2015-2019, Oliver Maurhart, dyle71@gmail.com
# ... | python |
#!/usr/bin/env python
from __future__ import print_function
import cProfile
import pstats
import argparse
from examples.pybullet.utils.pybullet_tools.kuka_primitives import BodyPose, BodyConf, Command, get_grasp_gen, \
get_stable_gen, get_ik_fn, get_free_motion_gen, \
get_holding_motion_gen, get_movable_coll... | python |
"""Calculate collision matrix of direct solution of LBTE."""
# Copyright (C) 2020 Atsushi Togo
# All rights reserved.
#
# This file is part of phono3py.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistribu... | python |
import argparse
import dataclasses
from pathlib import Path
from typing import Dict, List, Optional
from omegaconf import DictConfig, OmegaConf as oc
from .. import settings, logger
@dataclasses.dataclass
class Paths:
query_images: Path
reference_images: Path
reference_sfm: Path
query_list: Path
... | python |
from urllib.request import urlopen as ureq
from bs4 import BeautifulSoup
import requests
import os, os.path, csv
my_url = 'https://www.newegg.com/Laptops-Notebooks/Category/ID-223?Tid=17489'
# loading connection/grabbing page
xClient = ureq(my_url)
p_html = xClient.read()
# html parsing
page_soup = BeautifulSoup(p_h... | python |
# by amounra : http://www.aumhaa.com
from __future__ import with_statement
import contextlib
from _Framework.SubjectSlot import SubjectEvent
from _Framework.Signal import Signal
from _Framework.NotifyingControlElement import NotifyingControlElement
from _Framework.Util import in_range
from _Framework.Debug import debu... | python |
# -*- encoding: utf-8
import sys
import pytest
import lswifi
# WirelessNetworkBss
class TestElements:
def test_parse_rates(self):
test1 = lswifi.elements.OutObject(
value="1(b) 2(b) 5.5(b) 11(b) 6(b) 9 12(b) 18 24(b) 36 48 54"
)
test2 = lswifi.elements.OutObject(
... | python |
import kaggle
import pathlib
import shutil
# You need to have ~/.kaggle/kaggle.json in your device.
competition_name = 'tgs-salt-identification-challenge'
out_path = pathlib.Path('Dataset')
def download(train: bool = True) -> None:
fn = 'train' if train else 'test'
print(f'[INFO] Downloading {fn} data.')
... | python |
#!/usr/bin/env python
# Copyright 2015-2016 Yelp 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 by applicable law ... | python |
from discord.ext import commands
from ytdl.source import YTDLSource
from asyncio import sleep
class Kakatua(commands.Cog):
def __init__(self, bot: commands.Bot):
self.bot = bot
self.playlist = []
self.player = None
@commands.command()
async def check(self, ctx: commands.Context, ... | python |
from __future__ import division
from mmcv import Config
from mmcv.runner import obj_from_dict
from mmdet import datasets, __version__
from mmdet.apis import (train_detector, get_root_logger)
from mmdet.models import build_detector
import os
import os.path as osp
import getpass
import torch
"""
Author:Yuan Yuan
Date:2... | python |
import csv
import time
from gensim.models.doc2vec import Doc2Vec
from chatterbot import ChatBot
data_input_filename = 'training_data.csv'
doc2vec_filename = 'doc2vecmodel'
punctuation = ['.',',',';','!','?','(',')']
data_input_file = open(data_input_filename, 'r', encoding='UTF-8', newline='')
csv_reader = csv.reader... | python |
from setuptools import setup, find_packages
install_requires = [
"setuptools>=41.0.0",
"numpy>=1.16.0",
"joblib",
"scipy"
]
extras_require = {
"tf": ["tensorflow==2.0.0"],
"tf_gpu": ["tensorflow-gpu==2.0.0"]
}
setup(
name="tf2gan",
version="0.0.0",
description="Generative Adversar... | python |
from images import api
urlpatterns = api.urlpatterns
| python |
# coding=utf8
# Author: TomHeaven, hanlin_tan@nudt.edu.cn, 2017.08.19
from __future__ import print_function
from tensorflow.contrib.layers import conv2d, avg_pool2d
import tensorflow as tf
import numpy as np
from data_v3 import DatabaseCreator
import time
import tqdm
import cv2
import re
import os
import argparse
impo... | python |
# ------------------------------------------------------------------------------
# Program: The LDAR Simulator (LDAR-Sim)
# File: Operator
# Purpose: Initialize and manage operator detection module
#
# Copyright (C) 2018-2020 Thomas Fox, Mozhou Gao, Thomas Barchyn, Chris Hugenholtz
#
# This program is f... | python |
# Generated from parser/TinyPy.g4 by ANTLR 4.5.1
from antlr4 import *
if __name__ is not None and "." in __name__:
from .TinyPyParser import TinyPyParser
else:
from TinyPyParser import TinyPyParser
# This class defines a complete listener for a parse tree produced by TinyPyParser.
class TinyPyListener(ParseTre... | python |
import os
import sys
import argparse
import pathlib
import fpipelite.data.project
import fpipelite.data.data
import json
def print_parser(parser:argparse.ArgumentParser):
parser.add_argument("path", type=pathlib.Path,nargs="?", default=".")
parser.description = "Prints the data for a found project via {path}."... | python |
class SesDevException(Exception):
pass
class AddRepoNoUpdateWithExplicitRepo(SesDevException):
def __init__(self):
super().__init__(
"The --update option does not work with an explicit custom repo."
)
class BadMakeCheckRolesNodes(SesDevException):
def __init__(self):
... | python |
#!/usr/bin/python
# main.py
"""
@author: Maxime Dréan.
Github: https://github.com/maximedrn
Telegram: https://t.me/maximedrn
Copyright © 2022 Maxime Dréan. All rights reserved.
Any distribution, modification or commercial use is strictly prohibited.
"""
# Selenium module imports: pip install seleni... | python |
#!/usr/bin/env python3
"""Driver for controlling leg position"""
from inpromptu import Inpromptu, cli_method
from .five_bar_kins import FiveBarKinematics2D
from .odrive_driver import OdriveDriver
import odrive
class ParetoLeg(Inpromptu):
#class ParetoLeg(object):
# constants
CALIB_ANGLE_DEGS = [90, 90]
... | python |
import _km_omp as _cp
import networkx as nx
from itertools import compress
import numpy as np
import scipy
from scipy.sparse import triu
def detect(G, nodes_in_part1, nodes_in_part2, part_to_project, resol = 1, node_capacity = {}, num_samples = 100, consensus_threshold=0.9, significance_level = 0.05, num_rand_nets = ... | python |
# Webhooks for external integrations.
from __future__ import absolute_import
from typing import Text
from django.http import HttpRequest, HttpResponse
from zerver.lib.actions import check_send_message
from zerver.lib.response import json_success
from zerver.decorator import REQ, has_request_variables, api_key_only_we... | python |
# -*- coding: utf-8 -*-
"""The interface for Windows Registry objects."""
import abc
from plaso.dfwinreg import definitions
class WinRegistryFile(object):
"""Class that defines a Windows Registry file."""
_KEY_PATH_SEPARATOR = u'\\'
def __init__(self, ascii_codepage=u'cp1252', key_path_prefix=u''):
"""I... | python |
#!/usr/bin/env python
import sys
sys.path.append('../')
from logparser import SLCT
input_dir = '../logs/HDFS/' # The input directory of log file
output_dir = 'SLCT_result/' # The output directory of parsing results
log_file = 'HDFS_2k.log' # The input log file name
log_format = '<Date> <Time> <Pid> <Level> <Com... | python |
import logging
import os
import queue
import threading
import time
import traceback
import uuid
from signal import SIGINT, SIGTERM, signal
import zmq
from pyrsistent import pmap
from rx.subject import Subject
from .mixins import (
AuthenticationMixin,
NotificationsMixin,
RouterClientMixin,
WebserverMi... | python |
str1 = “Hello”
str2 = “World”
str1 + str2 | python |
#!/usr/bin/env python
# Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
appid.py -- Chromium appid header file generation utility.
"""
import optparse
import sys
GENERATED_APPID_INCLUDE_FILE_CONTEN... | python |
"""
Torrent Search Plugin for Userbot.
CMD:
`.tsearch` <query>\n
`.ts` <query or reply>\n
`.movie torrentz2.eu|idop.se` <query>
"""
import cfscrape # https://github.com/Anorov/cloudflare-scrape
from bs4 import BeautifulSoup as bs
import requests
import asyncio
from uniborg.util import admin_cmd, humanbytes
from datet... | python |
# Generated by Django 3.2.4 on 2021-06-16 10:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0002_auto_20210616_1024'),
]
operations = [
migrations.AddField(
model_name='address',
name='created_at'... | python |
"""Test ComprehensionChecker"""
def should_be_a_list_copy():
"""Using the copy() method would be more efficient."""
original = range(10_000)
filtered = []
for i in original:
filtered.append(i)
def should_be_a_list_comprehension_filtered():
"""A List comprehension would be mor... | python |
start = [90.0, 30.0, 30.0, 0.0, 0.0, 0.0]
scan = [90.0, 90.0, 0.0, 0.0, 0.0, 0.0]
grip = [90.0, 120.0, 30.0, 0.0, 0.0, 0.0]
evaluate = [90.0, 120.0, -30.0, 0.0, 0.0, 0.0]
trash = [-90.0, 120.0, 30.0, 0.0, 0.0, 0.0]
transport_a = [180.0, 120.0, 30.0, 0.0, 0.0, 0.0]
transport_b = [0.0, 120.0, 30.0, 0.0, 0.0, 0.0]
detach ... | python |
#!/usr/bin/env python
import numpy as np;
import sys;
import string;
import numpy.linalg as lg
import argparse as ap
atb=1.88971616463
parser=ap.ArgumentParser(description="Parse polarisation from Gaussian logfile")
parser.add_argument("-f","--logfile", help="Gaussian logfile")
args=parser.parse_args()
inputfile=args... | python |
"""Import all the LINQ observable extension methods."""
# flake8: noqa
from . import all
from . import amb
from . import and_
from . import some
from . import asobservable
from . import average
from . import buffer
from . import bufferwithtime
from . import bufferwithtimeorcount
from . import case
from . import catch
... | python |
from django.shortcuts import render, redirect
from django.core.files.storage import FileSystemStorage
from .models import Document
from .forms import DocumentForm
import logging
from cid.locals import get_cid
from collections import OrderedDict
from common.mq.kafka import producer
import os
KAFKA_BROKER_URL = os.e... | python |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# BioSTEAM: The Biorefinery Simulation and Techno-Economic Analysis Modules
# Copyright (C) 2020, Yoel Cortes-Pena <yoelcortes@gmail.com>
# Bioindustrial-Park: BioSTEAM's Premier Biorefinery Models and Results
# Copyright (C) 2020, Yalin Li <yalinli2@illinois.edu>,
# Saran... | python |
# Taken from https://ubuntuforums.org/showthread.php?t=2117981
import os
import re
import subprocess
import time
if __name__ == '__main__':
cmd = 'synclient -m 100'
p = subprocess.Popen(cmd, stdout = subprocess.PIPE, stderr = subprocess.STDOUT, shell = True)
skip = False
first = True
... | python |
import pyxel,math
from pyxel import init,image,tilemap,mouse,run,btn,cls,KEY_SPACE,btnp,KEY_Q,quit,text,clip,pix,line,rect,rectb,circ,circb,blt,bltm,pal
class App:
def __init__(self):
init(256, 256, caption="Pyxel Draw API",scale=1)
image(0).load(0, 0, "assets/cat_16x16.png")
image(1).load(0... | python |
import os
import shutil
from django.conf import settings
from django.core.management import BaseCommand
import django
class Command(BaseCommand):
help = "Update django locales for three-digit codes"
args = ""
def handle(self, *args, **options):
# if we were feeling ambitious we could get this from... | python |
import pytest
pytestmark = [pytest.mark.django_db]
def test_single_member(mailchimp, post, mailchimp_member):
mailchimp.mass_subscribe(
list_id='test1-list-id',
members=[mailchimp_member],
)
post.assert_called_once_with(
url='lists/test1-list-id',
payload={
... | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from decimal import Decimal
from django.conf import settings
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.core.validators import MinValueValidator
from django.db import models
from django.temp... | python |
# import sys
# sys.path.append("/root/csdc3/src/sensors/")
# sys.path.append("/root/csdc3/src/utils/")
# from sensor_manager import SensorManager
# from sensor_constants import *
# from statistics import median
def returnRandInt(minValue, maxValue):
return int(random.random()*(maxValue - minValue + 1)) % (maxValue... | python |
# Generated by Django 2.1.1 on 2018-10-27 17:56
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('music', '0007_auto_20181027_1618'),
]
operations = [
migrations.AddField(
model_name='favorite'... | python |
from st2common.runners.base_action import Action
from thehive4pyextended import TheHiveApiExtended
__all__ = [
'PromoteAlertToCaseAction'
]
class PromoteAlertToCaseAction(Action):
def run(self, alert_id, case_template=None):
api = TheHiveApiExtended(self.config['thehive_url'], self.config['thehive_ap... | python |
from django.contrib import admin
from django.urls import path
from . import views
app_name = 'todoapp'
urlpatterns = [
# ex: /todo/
path('', views.index, name='index'),
# ex: /todo/tasks/
path('tasks/', views.tasks, name='tasks'),
# ex: /todo/hashtags/
path('hashtags/', views.hashtags, name=... | python |
import sys
from time import sleep
from sense_hat import SenseHat
class Morse:
senseHat = None
sentence = None
multiplierSpeed = 1
transcriber = None
flashColor = [255,255,255]
loop = False
def __init__(self):
if len(sys.argv) < 2:
print("ERROR: This scri... | python |
from __future__ import print_function
import os
import sys, logging
import json
import re
import mechanize
import boto3
mechlog = logging.getLogger("mechanize")
mechlog.addHandler(logging.StreamHandler(sys.stdout))
if os.getenv('DEBUG') != None:
logging.basicConfig(level=logging.DEBUG)
mechlog.setLevel(loggi... | python |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright (c) 2014, Lars Asplund lars.anders.asplund@gmail.com
from vunit.color_printer import ColorPrinter
from xml... | python |
# META: timeout=long
import pytest
from webdriver import Element
from tests.support.asserts import (
assert_element_has_focus,
assert_error,
assert_events_equal,
assert_in_events,
assert_success,
)
from tests.support.inline import inline
@pytest.fixture
def tracked_events():
return [
... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.