content stringlengths 5 1.05M |
|---|
"""Exports the "troupe" decorator that can be applied to Actor
definitions. This decorator turns a regular Actor into a dynamic
Actor Troupe, where multiple Actors are spun up on-demand to handle
messages.
This pattern is especially useful for situations where multiple
requests are received and processing individual ... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from typing import Dict, Optional, Tuple, Sequence
import collections
import json
import logging
import pathlib
import random
import time
im... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 17 09:44:13 2020
@author: u7075106
"""
def sum_odd_digits(num):
x = num
sum_o = 0
while x >= 1:
d = x%10
print(d)
if d%2 == 1:
sum_o = sum_o + d
x = int(x/10)
return sum_o
def su... |
import traceback
from datetime import datetime, timedelta
from functools import wraps
from typing import Union, Optional, Callable, Any
import jwt
from flask import g, request, has_request_context
from werkzeug.local import LocalProxy
from anubis.config import config
from anubis.models import User, TAForCourse, Profe... |
# Copyright 2016 Google Inc. 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 ... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
from os import path
WINDOW_TITLE = 'Interface' # Título da janela.
SCREEN_SIZE = (800, 600) # Dimensões da janela.
FONT_SIZE = 14 # Tamanho da fonte a ser utilizada.
DOT_RADIUS = 4 # Raio dos pontos do mapa.
LINE_W... |
import argparse
import html
import json
import os
import string
import sys
from copy import deepcopy
import dbus
from dbus.mainloop.glib import DBusGMainLoop, threads_init
from gi.repository import Gio, GLib
__version__ = '1.2.0'
__author__ = 'un.def <me@undef.im>'
class Formatter(string.Formatter):
_FORMAT_F... |
from max_profit import max_profit
def test_simple():
stocks = [1, 2, 3, 4]
assert (max_profit(stocks) == [1, 4])
def test_empty():
stocks = []
assert (max_profit(stocks) == [])
def test_one_elt():
stocks = [1]
assert (max_profit(stocks) == [1, 1])
def test_medium():
stocks = [5, 10, 2, 5... |
class StringIdentifierException(Exception):
'''
Raised if a String identifier (e.g. an observation "name")
does not match our constraints. See the utilities method
for those expectations/constraints.
'''
pass
class AttributeValueError(Exception):
'''
Raised by the attribute subclasses... |
#$Id$
class BankRule:
"""This class is used to create object for bank rules."""
def __init__(self):
"""Initialize parameters for Bank rules."""
self.rule_id = ''
self.rule_name = ''
self.rule_order = 0
self.apply_to = ''
self.target_account_id = ''
self.a... |
from ..database import Base
from ..database import autocommit_engine
from ..tenants import models as t_models
from ..policies import models as p_models
import pytest
@pytest.fixture()
def test_db():
Base.metadata.create_all(bind=autocommit_engine)
yield
Base.metadata.drop_all(bind=autocommit_engine)
|
import numba
from numba.types import float64
import numpy as np
from privates import NamedStruct
FAIL_MSG = "Numba not found"
class Point(NamedStruct):
x: float64
y: float64
def distance_from_origin(self):
return np.sqrt(self.x**2 + self.y**2)
class Rectangle(Point):
width: float64
h... |
import sys
import os
import argparse
import logging
import time
import numpy as np
from skimage import filters
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../../')
parser = argparse.ArgumentParser(description='Generate predicted coordinates'
' from probability map... |
# https://www.python.org/dev/peps/pep-0440/
__version__ = '1.13.3'
|
t = int(input())
answers = []
for a in range(t):
counter = 0
saver = 0
saver2 = 0
n = int(input())
line = [int(b) for b in input().split()]
final = {}
for c in range(len(line)):
final.update({line[c]:final[line[c]].append(c)})
print(final)
for bl in answers:
print(bl)
|
from enum import auto
from ...util.misc import StringEnum
from ...util.colormaps import AVAILABLE_COLORMAPS
class Interpolation(StringEnum):
"""INTERPOLATION: Vispy interpolation mode.
The spatial filters used for interpolation are from vispy's
spatial filters. The filters are built in the file below:
... |
from timeseers.linear_trend import LinearTrend
from timeseers.timeseries_model import TimeSeriesModel
from timeseers.fourier_seasonality import FourierSeasonality
from timeseers.logistic_growth import LogisticGrowth
from timeseers.indicator import Indicator
from timeseers.constant import Constant
from timeseers.regress... |
from read_wordcount_corpus import read_wordcount_corpus
import MeCab
#mecab_parse用
m = MeCab.Tagger ('-d /usr/local/lib/mecab/dic/mecab-ipadic-neologd')
#mecabFormatを作成
def mecab_parse(text):
mecabFormat = []
for txt in m.parse(text).split('\n'):
t = txt.split('\t')
if len(t)==2:
... |
from setuptools import setup, find_packages
setup(
name='cross_dataset_common',
version='0.1.5',
description='Utilities for preparing processed data to be loaded into database',
url='https://github.com/hubmapconsortium/cross-dataset-common',
author='Sean Donahue',
author_email='seandona@andrew.... |
# -*- encoding: utf-8 -*-
# Copyright (c) 2020 Stephen Bunn <stephen@bunn.io>
# ISC License <https://choosealicense.com/licenses/isc>
"""Predefined background (bg) chalk colors."""
from ..chalk import Chalk
from ..color import Color
black = Chalk(background=Color.BLACK)
red = Chalk(background=Color.RED)
green = Chal... |
#!/usr/bin/env python3
# psw_factorial, an implementation of the prime swing factorial.
# The claim is that this is the fastest known algorithm for
# computing the factorial. It is based on the prime factorization of n!.
# See Peter Luschny, https://oeis.org/A000142/a000142.pdf
# Also http://www.luschny.de/math/factor... |
import unittest
import mock
from pyhpecw7.features.vxlan import Vxlan, Tunnel, L2EthService
from .base_feature_test import BaseFeatureCase
INTERFACE = 'FortyGigE1/0/2'
INSTANCE = '100'
VSI = 'VSI_VXLAN_100'
TUNNEL = '20'
class VxlanTestCase(BaseFeatureCase):
@mock.patch('pyhpecw7.comware.HPCOM7')
def setUp(... |
import re
import xml.etree.ElementTree as ET
kashf = open('KashfAlZunun.txt', mode='r', encoding='utf-8')
text = kashf.read()
denoised_text = re.sub(r'\.{2,}', '', text)
elementsKashf = denoised_text.split(".")
kashfalzunun = ET.Element("kashf")
y = 1
for x in range(0, len(elementsKashf)-1):
WordsElement = re.finda... |
# Copyright 2020 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... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 CERN.
#
# CDS-ILS is free software; you can redistribute it and/or modify it under
# the terms of the MIT License; see LICENSE file for more details.
"""CDS-ILS MARCXML to JSON fields values mapping."""
from __future__ import unicode_literals
from cds_ils.importer.error... |
from __future__ import print_function
from tractor.lsqr_optimizer import LsqrOptimizer
import numpy as np
logverb = print
logmsg = print
class ConstrainedOptimizer(LsqrOptimizer):
def optimize_loop(self, tractor, dchisq=0., steps=50, **kwargs):
R = {}
self.hitLimit = False
for step in ra... |
from . import utils
from .clip import CLIPForImageText
from .huggingface_text import HFAutoModelForTextPrediction
from .timm_image import TimmAutoModelForImagePrediction
from .numerical_mlp import NumericalMLP
from .categorical_mlp import CategoricalMLP
from .numerical_transformer import NumericalTransformer
from .cate... |
#/bin/env python
# -*-coding:utf=8 -*-
import os,time,subprocess,shlex
import urllib2
def upload_yeelink(image_name, log_file):
url = 'http://api.yeelink.net/v1.0/device/719/sensor/8613/photos'
length = os.path.getsize(image_name)
image_data = open(image_name, 'rb')
request = urllib2.Request(url, data=i... |
import collections, copy
# Part one
class Image:
def __init__(self, enhancement_algorithm, fill=0):
if isinstance(enhancement_algorithm, str):
enhancement_algorithm = list(map('.#'.index, enhancement_algorithm))
self.enhancement_algorithm = enhancement_algorithm
self.fill = fill... |
import sqlite3
northwind_conn = sqlite3.connect('northwind_small.sqlite3')
northwind_cursor1 = northwind_conn.cursor()
most_expensive_query = (
'SELECT ProductName FROM ' +
'(SELECT * FROM Product ' +
'Order by UnitPrice DESC LIMIT 10);'
)
most... |
import logging
import os
from django.conf import settings
from django.db import models
from django.utils.timezone import now
from django.utils.functional import cached_property
from django import template
import apps.web as web
from apps.web.utils import PublicStorage, BundleStorage
from datetime import datetime, timed... |
import math
import itertools
# class Error is derived from super class Exception
class Error(Exception):
# Error is derived class for Exception, but
# Base class for exceptions in this module
pass
class Bunny_Console_Error(Error):
def __init__(self, prev, nex, msg):
self.prev ... |
import requests
from functools import partialmethod
def raise_for_status_hook(response: requests.Response, *args, **kwargs):
response.raise_for_status()
class ApigeeClient:
def __init__(
self,
apigee_org: str,
username: str = None,
password: str = None,
access_token: ... |
"""
Copyright (C) 2021 Patrick Maloney
"""
import requests
from typing import Tuple
from dataclasses import dataclass
from geopy.geocoders import Nominatim
# TODO: Documentation
@dataclass()
class Properties:
updated: str
generated_at: str
update_time: str
valid_times: str
elevation: float
@da... |
#!/usr/bin/env python
"""The setup script."""
import os
from setuptools import setup, find_namespace_packages
with open("README.rst") as readme_file:
readme = readme_file.read()
# The requirements section should be kept in sync with the environment.yml file
requirements = [
# fmt: off
"chalice>=1.13",
... |
"""Fix for pyaudio (or rather portaudio) debug messages
These get very annoying and break npyscreen interface, even though everything
works properly.
Stolen from http://stackoverflow.com/q/7088672
"""
from ctypes import (
CFUNCTYPE,
c_char_p,
c_int,
cdll
)
def _py_error_handler(filename, line, funct... |
# Generated by Django 3.2.5 on 2021-07-08 13:09
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Journalist',
fields=[
... |
# import third party libs
from flask import Blueprint
api = Blueprint("api", __name__, url_prefix="/api")
from . import vrf
from . import vrfs
|
from django.db import models
# internal text/value object
class SurveyQuestion(object):
def __init__(self, value, text):
self.value = value
self.text = text
class SurveyAnswerValues(object):
def __init__(self, option, votes, votespercent):
self.option = option
self.votes = vo... |
# container-service-extension
# Copyright (c) 2017 VMware, Inc. All Rights Reserved.
# SPDX-License-Identifier: BSD-2-Clause
import functools
import hashlib
import os
import pathlib
import stat
import sys
import threading
import click
import requests
# chunk size in bytes for file reading
BUF_SIZE = 65536
# chunk s... |
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
import logging
import emission.storage.decorations.stats_queries as esds
impo... |
from ..lang import H
from ..lang import sig
from ..lang import L
@sig(H/ str >> [str])
def lines(string):
"""
lines :: String -> [String]
lines breaks a string up into a list of strings at newline characters.
The resulting strings do not contain newlines.
"""
return L[[]] if not string else L... |
_base_ = '../model.py'
model = dict(
type='ImageClassifier',
task='classification',
pretrained=None,
backbone=dict(),
neck=dict(type='GlobalAveragePooling'),
head=dict(
in_channels=-1,
loss=dict(type='CrossEntropyLoss', loss_weight=1.0),
topk=(1, 5)
)
)
checkpoint_c... |
class Solution(object):
def minMeetingRooms(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: int
"""
start=[]
end = []
for i in intervals:
start.append(i[0])
end.append(i[1])
start.sort()
end.sort(... |
#!/usr/bin/env python3
#
# format.py
# Copyright (c) 2017 Dylan Brown. All rights reserved.
#
# NOTES
# Use Python 3. Run from the `build/` directory.
import os
import sys
import json
CLANG_FORMAT_EXE = "/usr/local/opt/llvm/bin/clang-format"
# Ensure we don't silently fail by running Python 2.
assert sys.version_... |
#!/usr/bin/env python
# system
import os
import copy
import numpy as np
import threading
import time
import math
# drake
import lcm
from drake import lcmt_iiwa_command, lcmt_iiwa_status ,lcmt_robot_state
import pydrake
from pydrake.solvers import ik
from robotlocomotion import robot_plan_t
from bot_core import robot_... |
def list_check(lst):
"""Are all items in lst a list?
>>> list_check([[1], [2, 3]])
True
>>> list_check([[1], "nope"])
False
"""
t = [1 if isinstance(x, list) else 0 for x in lst]
return len(lst) == sum(t) |
from rest_framework import serializers
from rdmo.core.serializers import TranslationSerializerMixin
from ..models import Task
class TaskExportSerializer(TranslationSerializerMixin, serializers.ModelSerializer):
start_attribute = serializers.CharField(source='start_attribute.uri', default=None, read_only=True)
... |
from django import forms
from .models import Car, Owner
class AddCarForm(forms.ModelForm):
class Meta:
model = Car
fields = [
"brand",
"model",
"color",
"plate_number"
]
|
import argparse
import logging
import time
from api.ingest import IngestAPI
from ena.ena_api import EnaApi
from ena.util import write_xml
logging.getLogger('ena.ena_api').setLevel(logging.DEBUG)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Submits sequencing run entities to ENA')
... |
import asyncio
import logging
import os
import uvloop
from functools import partial
from inspect import isawaitable
from multiprocessing import Process
from ssl import create_default_context, Purpose
from signal import (
SIGTERM, SIGINT,
signal as signal_func,
Signals
)
from socket import (
socket,
... |
# 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 ... |
import time
from lib.rotation import Rotation
rot = Rotation(18, 0, 180)
rot.setup()
time.sleep(2)
rot.cleanup()
|
# -*- coding: utf-8 -*-
"""
Example using the functions in TopomapArray to plot a set of 10:20 EEG sensors
onto a single subplot.
@author: KensingtonSka (Rhys Hobbs)
"""
import numpy as np
import matplotlib.pyplot as plt
from TopomapArray import project_onto_zplane, gen_grid_size, project_onto_grid
# %% Hy... |
from datetime import datetime, timedelta
from nose.tools import eq_
from mock import Mock, patch
import amo
import amo.tests
from addons.models import Addon
from users.models import UserProfile
from devhub.models import ActivityLog
from mkt.developers.models import (AddonPaymentAccount, CantCancel,
... |
def find_higher(first, window):
for i in range(len(window)):
if window[i] > first:
return (i, window[i])
return None
with open('B-large-practice.in') as file:
T = int(file.readline())
for case in range(1, T+1):
(emax, regain, n) = map(int, file.readline().split())
wi... |
import ast
import atexit
import json
import os
import time
from datetime import datetime, timedelta
from random import randrange
import git
from apscheduler.schedulers.background import BackgroundScheduler
from dotenv import load_dotenv
from flask import Flask, redirect
from newsapi import NewsApiClient
COUNTRIES_LAN... |
"""
Copyright: Wenyi Tang 2017-2018
Author: Wenyi Tang
Email: wenyi.tang@intel.com
Created Date: Oct 15th 2018
Improved train/benchmark/infer script
Type --helpfull to get full doc.
"""
# Import models in development
try:
from Exp import *
except ImportError as ex:
pass
import tensorflow as tf
from importlib... |
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------
# ZTE.ZXA10.get_inventory
# ---------------------------------------------------------------------
# Copyright (C) 2007-2019 The NOC Project
# See LICENSE for details
# --------------------------------------------------------... |
from __future__ import absolute_import, print_function
import sys
if sys.version_info < (3, 0):
import __builtin__ as builtins
else:
import builtins
from collections import namedtuple
# TODO : use basemsg and develop a generic way of converting python type to custom type
if sys.version_info < (3, 0):
... |
# coding: utf-8
from fabric.api import *
# from fab_deploy.db import mysql
from fab_deploy import pip, utils, system, crontab, vcs, db
|
import numpy as np
import sympy as sp
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
def gauss(x,y):
exp_term = -1.0/(2*(1-corr_hw**2))*((x-mean_h)**2/var_h+(y-mean_w)**2/var_w-2*corr_hw*(x-mean_h)*(y-mean_w)/(std_h*std_w))
return 1.0 / (2*np.pi*std_h*std_w*np.sqrt(1-corr_hw**2)) * np.exp(exp_term)... |
from ._base import PatternBase
from ._next import Next
from ._inspect import is_iterable
class Chord(PatternBase):
"""
Simply put the input into a list
"""
def __init__(self, values):
assert is_iterable(values)
self.values = None
super().__init__(values=values)
def iterat... |
"""
MINIMUM CloudBolt version required: v9.2
This Plug-in configures servers for RKE, deploys a Kubernetes cluster with
`rke up`, and creates the required CloudBolt objects to manage the deployed
cluster from CloudBolt.
"""
import os
import time
import yaml
from common.methods import set_progress
from containerorche... |
import pickle
class ResultWrapper:
def __init__(self, parent_task, path):
self.parent_task = parent_task
self.result_path = path
def set(self, result):
# Todo Save numpy, pytorch and pandas using custom serialization
# save the results
with open(self.result_path + '.... |
#!/usr/bin/env python
# encoding: utf-8
'''Functions for feature transformations'''
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import sklearn as skl
from common.functions import vec, row
from pylab import *
def get_one_hot_encoding(x):
'''
INPUT:
x: pand... |
ERR_MSG_DATASET_INFO_NOT_FOUND = 'DataSetInfo object not found'
ERR_MSG_INVALID_DATASET_INFO_OBJECT_ID = 'Invalid DataSetInfo object id.'
ERR_MSG_DATASET_INFO_NOT_FOUND_CURRENT_USER = ('DataSetInfo object not found'
' for the current user.')
ERR_MSG_FAILED_TO_READ_DATA... |
from django.contrib.auth.decorators import login_required
from django.urls import path, include
from .views import *
urlpatterns = [
path('auth/', include('allauth.urls')),
path('settings', login_required(SettingsView.as_view()), name="user.settings"),
path('user/<username>', ProfileView.as_view(), name="u... |
from eth2spec.test.context import spec_test, with_phases
from eth2spec.test.helpers.deposits import (
prepare_genesis_deposits,
)
def create_valid_beacon_state(spec):
deposit_count = spec.MIN_GENESIS_ACTIVE_VALIDATOR_COUNT
deposits, _ = prepare_genesis_deposits(spec, deposit_count, spec.MAX_EFFECTIVE_BALA... |
"""
log utils
"""
from ytdlmusic.params import is_verbose
def print_debug(message):
"""
print "[debug] " + message only if --verbose
"""
if is_verbose():
print("[debug] " + message)
|
# Ivan Carvalho
# Solution to https://www.urionlinejudge.com.br/judge/problems/view/1087
#!/usr/bin/env python2.7
# encoding : utf-8
while True:
a,b,c,d = [int(i) for i in raw_input().split(" ")]
diferencax = abs(a-c)
diferencay = abs(b-d)
if a == 0 and b == 0 and c== 0 and d == 0:
break
else:
if a == c and b ... |
#
# Copyright 2020-2021 Hewlett Packard Enterprise Development LP
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, ... |
import glob
import zlib
import numpy
import pytest
import rasterio
from rasterio.windows import Window
from nodata.scripts.alpha import (
all_valid, init_worker, finalize_worker, compute_window_mask,
NodataPoolMan)
def test_all_valid():
assert (
all_valid(numpy.empty((2, 2), dtype='uint8'), 0) =... |
from parlai.agents.programr.parser.exceptions import ParserException
from parlai.agents.programr.parser.pattern.matcher import EqualsMatch
from parlai.agents.programr.parser.pattern.nodes.base import PatternNode
#from parlai.agents.programr.nlp.semantic.semantic_similarity import SemanticSimilarity
DEBUG = False
cl... |
import os.path
from cStringIO import StringIO
from django.test import TestCase
from storages.backends.overwrite import OverwriteStorage
from localshop.apps.packages import models
from localshop.apps.packages import utils
from localshop.apps.packages.tests import factories
from localshop.utils import TemporaryMediaRo... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from .pix3d_evaluation import Pix3DEvaluator, transform_meshes_to_camera_coord_system
|
from tkinter import *
root = Tk()
root.title("sliders")
root.iconbitmap(None)
root.geometry("400x400")
# Drop Down Boxes
def show():
myLabel = Label(root, text=clicked.get()).pack()
options = [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
]
clicked = StringVar()... |
# -*- coding: utf-8 -*-
# This file is part of Kaleidoscope.
#
# (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.
# pylin... |
import dns.resolver
import subprocess
# query the server and parse the response
server_answer = str(dns.resolver.resolve('current.cvd.clamav.net', 'TXT').response.answer[0]).replace('"', ':').split(':')
# save list entrys in spezific variables
server_clamav_version = server_answer[1]
server_daily_database_version = se... |
from flask import Flask, render_template #importando o framework do Flask
app = Flask(__name__)
@app.route('/') #criando uma rota na primeira pagina
def home():
return render_template(
'index.html'
)
if __name__ == '__main__':
app.run(debug=True) |
#!/usr/bin/env python3
import logging
import os
import pathlib
import socket
import subprocess
import sys
import tempfile
from configparser import ConfigParser
from typing import Generator, cast
import boto3
from botocore.exceptions import ClientError
from glacier_backup.db import GlacierDB
from glacier_backup.uplo... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-08-13 03:50
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('proso_user', '0001_initial'),
('proso_subscription',... |
import csv
import io
from io import TextIOWrapper
from io import TextIOBase
from django.urls import reverse
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.views import View
from django.views.generic import TemplateView, CreateView
from django.views... |
import cv2 as cv
image = cv.imread() |
__version__ = "0.2"
# flake8: noqa
from .horizon import horizon, KM, MILES
from .sunpos import sunpos
from .tppss import (
above_horizon,
sunrise_sunset,
sunrise_sunset_details,
sunrise_sunset_year,
SunriseSunset,
times_in_day,
)
|
#!/usr/bin/env python3
import sys
import os
from inotify_simple import INotify, flags
SERVER_NAME = os.environ['server_name'].replace(' ', '_')
LOG_DIR = f'/srv/{SERVER_NAME}/logs'
LATEST_LOG = f'{LOG_DIR}/latest.log'
class McDirWatcher:
def __init__(self):
self.inotify = INotify()
watch_flags = ... |
from discord.ext import commands
from src.config import OPERATOR_ROLE
class PlaybackCog(commands.Cog):
def __init__(self):
self.on_join_server = []
self.on_leave_server = []
def add_join_server_callback(self, callback):
self.on_join_server.append(callback)
def add_leave_server_callback(self, callback):
... |
#!/usr/bin/python
import sys
import socket
import time
from random import randint
from rosbridge_library.util import json
# ##################### variables begin ########################################
# these parameters should be changed to match the actual environment #
# ################################... |
from __future__ import absolute_import
from .vertexartist import *
from .edgeartist import *
from .faceartist import *
__all__ = [name for name in dir() if not name.startswith('_')]
|
# Alex Eidt
import tkinter as tk
import string
import imageio
import numpy as np
import numexpr as ne
import keyboard
from PIL import Image, ImageTk, ImageFont, ImageDraw
# Mirror image stream along vertical axis.
MIRROR = True
# Video Stream to use.
STREAM = '<video0>'
# Background color of the ASCII stream.
BACKGR... |
import aioredis
from aiohttp.web import Application
def setup_redis(app: Application):
app.on_startup.append(_init_redis)
app.on_shutdown.append(_close_redis)
async def _init_redis(app: Application):
conf = app['config']['redis']
redis = await aioredis.create_pool((conf['host'], conf['port']),
... |
# Copyright 2014 Mirantis, 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 or ... |
# ------------------------------------------------------------------------------
# _dm.py
#
# Parser for the jam 'm' debug flag output - which contains details of
# timestamps, whether or not a file was updated, and gristed targets to file
# bindings.
#
# November 2015, Antony Wallace
# --------------------------------... |
from django.test import TestCase
# local test models
from models import Holder, Inner, InnerInline
from models import Holder2, Inner2, Holder3, Inner3
class TestInline(TestCase):
fixtures = ['admin-views-users.xml']
def setUp(self):
holder = Holder(dummy=13)
holder.save()
Inner(dummy... |
FILE_NAME = "[a-zA-Z0-9\-\_\.]+"
LEGAL_FILENAME_REGEX = '[a-zA-Z0-9 \._-]+$'
LEGAL_PATHNAME_REGEX = '[a-zA-Z0-9 \._-]+$'
LEGAL_FILENAME_URL_REGEX = LEGAL_FILENAME_REGEX[:-1]
LEGAL_PATHNAME_URL_REGEX = LEGAL_PATHNAME_REGEX[:-1]
UUID_URL_REGEX = '[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}'
HEX_R... |
#coding:utf-8
#
# id: bugs.core_4806
# title: Regression: generators can be seen/modified by unprivileged users
# decription:
# We create sequence ('g') and three users and one role.
# First user ('big_brother') is granted to use generator directly.
# ... |
import requests
import json
import urllib3
import socket
import time
from rmf_door_msgs.msg import DoorMode
class DoorClientAPI:
def __init__(self,url,api_key,api_value,door_id):
self.url = url
self.header = {api_key:api_value}
self.data = {"id": door_id}
count = 0
self.con... |
import imageio
import glob
import os
images = []
for filename in glob.glob(os.path.join(r"C:\Users\emrea\Desktop\'22 codes\deep-ternaloc\deep-ternaloc\Studies\emre\data\plt_files",'*.png')):
images.append(imageio.imread(filename))
imageio.mimsave('movie6eniyi.gif', images,duration=1)
|
import bpy
from bpy.types import (
AddonPreferences,
Curve,
Material,
Menu,
Object,
Operator,
Panel,
PropertyGroup,
UIList
)
from bpy.props import (
BoolProperty,
CollectionProperty,
EnumProperty,
FloatProperty,
FloatVectorProperty,
IntProperty,
PointerPro... |
from django.db import models
from django.conf import settings
from mainapp.models import Product
class Basket(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='basket')
product = models.ForeignKey(Product, on_delete=models.CASCADE)
quantity = models.P... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.