content
stringlengths
0
894k
type
stringclasses
2 values
import findspark findspark.init('/opt/spark') import schedule import pyspark from pyspark.sql import SparkSession from pyspark.sql.functions import col, udf, lit import random import smtplib, ssl from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart import schedule import time from random ...
python
class Test(object): __slots__ = 'name', 'word_set', 'target', 'longest_subsequence',\ 'verbose', 'actual' def __init__(self, json_object): self.name = json_object['name'] self.word_set = json_object['word_set'] self.target = json_object['target'] self.longest_subsequence = j...
python
numbers = [int(el) for el in input().split(", ")] positive = [str(x) for x in numbers if x >= 0] negative = [str(x) for x in numbers if x < 0] even = [str(x) for x in numbers if x % 2 == 0] odd = [str(x) for x in numbers if not x % 2 == 0] print("Positive:", ', '.join(positive)) print("Negative:", ', '.join(negative)...
python
# ------ your setttings ------ TrainModule = 'OutputOshaberi' # your sensation folder name device = 'cuda' # debugging device # ------ end of settings ----- if __name__ == '__main__': from importlib import import_module from multiprocessing import Value module = import_module(TrainModule) func = module...
python
year = int(input()) if year%4==0: cond=True if year%100==0 and cond==True: cond=False if year%400==0 and cond==False: print(f"{year} is a Leap Year!!") else: print(f"{year} is not a Leap Year")
python
from flask import Flask,request import os import base64 from lib.logger import Logger from termcolor import colored import sys def main(mongoclient,server_logger,port): app = Flask('app') ## Get the cookie/victim ID from a request def get_cookie(request): d = request.cookies if d: return base64.b64decode(...
python
''' PyTorch Dataset Handling. The dataset folder should comprise of two subfolders namely "train" and "test" where both folders has subfolders that named according to their class names. ''' import os import glob import cv2 import torch from torch.utils import data from torch.utils.data import Dataset, dataset class ...
python
import numpy as np from perturbative_solver import solve_oscillon from matplotlib import pyplot as plt from progress.bar import Bar ############################################################################ # Edit these parameters: ############################################################################ # the v...
python
from PIL import Image from csv import reader inputFilename: str = "./dist/flag.csv" outputFilename: str = "./writeup/flag.png" with open(inputFilename, "r") as csv_file: csv_reader = reader(csv_file) list_of_rows = list(csv_reader) size = [len(list_of_rows[0]), len(list_of_rows)] outputImage: Image = Image.n...
python
import unittest import ttrw from unittest.mock import patch test_dictionary = { "en": { "adverbs": ["test"], "adjectives": ["test"], "nouns": ["test"] }, "pl": { "adverbs": ["bardzo"], "adjectives": ["maly"], "nouns": ["ksiazka"] } } class TestTTRW(unit...
python
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distribu...
python
import graphene from graphql_auth.bases import MutationMixin, DynamicArgsMixin from users.mixins import PasswordSetAdminMixin class PasswordSetAdmin(MutationMixin, DynamicArgsMixin, PasswordSetAdminMixin, graphene.Mutation): _required_args = ["new_password1", "new_password2"] class Arguments: id = gr...
python
# -*- coding: utf-8 -*- import os import unittest import sqlite3 import tempfile import bottle from bottle.ext import sqlite ''' python3 moves unicode to str ''' try: unicode except NameError: unicode = str class SQLiteTest(unittest.TestCase): def setUp(self): self.app = bottle.Bottle(catchall=...
python
# This code is designed to compare the absolute difference between one # reference burn_cell test and multiple other burn_cell tests. # burn_cell_testing.py must be run before running this. # Around line 195, you choose which elements you will compare the xn and ydot of # To change what you investigate, you must chan...
python
#!/usr/bin/python import socket,os import platform """ NETLINK related stuff Astrit Zhushi 2011, a.zhushi@cs.ucl.ac.uk """ NETLINK_CONNECTOR=11 NETLINK_ADD_MEMBERSHIP=1 def get_cn_idx_iwlagn(): uname = platform.uname()[2] infile = open("/usr/src/linux-headers-%s/include/linux/connector.h" %(uname), "r") flag ...
python
""" Employee service. """ from department_app import db from department_app.models.department import Department from department_app.models.employee import Employee def add_employee_service(forename, surname, birthdate, department_id, salary): """ Adds employee to db. :param forename: employee first name ...
python
### tensorflow==2.3.1 import tensorflow as tf import tensorflow_datasets as tfds import numpy as np def representative_dataset_gen_480x640(): for data in raw_test_data.take(10): image = data['image'].numpy() image = tf.image.resize(image, (480, 640)) image = image[np.newaxis,:,:,:] ...
python
import bayesiancoresets as bc import numpy as np import warnings warnings.filterwarnings('ignore', category=UserWarning) #tests will generate warnings (due to pathological data design for testing), just ignore them np.seterr(all='raise') np.set_printoptions(linewidth=500) np.random.seed(100) tol = 1e-9 def test_empty...
python
# MIT License # # Copyright (c) 2018 Silvia Amabilino # # 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, modify, me...
python
# ro_prefixes.py """ Central list of prefixes commonly used with ROs extended to support ro model updates and extensions for earth science (01/2017) by Raul Palma """ __authors__ = "Graham Klyne (GK@ACM.ORG), Raul Palma" __copyright__ = "Copyright 2011-2013, University of Oxford" __license__ = "MIT (http:/...
python
import random from lxml import etree from typing import List from PIL import ImageDraw from nonebot.log import logger try: import ujson as json except ModuleNotFoundError: import json from .base_handle import BaseHandle, BaseData from ..config import draw_config from ..util import remove_prohibit...
python
"""Queries to answer following questions""" # How many total Characters are there? QUERY_1 = '''SELECT COUNT(*) FROM charactercreator_character;''' # How many of each specific subclass? QUERY_2 = '''SELECT ( SELECT COUNT(*) FROM charactercreator_thief ) AS thief_class, ( SELECT COUNT(*) FROM c...
python
from astutils import ast def test_terminal(): value = 'a' t = ast.Terminal(value) r = repr(t) assert r == "Terminal('a', 'terminal')", r r = str(t) assert r == 'a', r r = len(t) assert r == 1, r r = t.flatten() assert r == value, r def test_hash(): # different AST node in...
python
num1 = 111 num2 = 222 num3 = 3333333333 num3 = 333 num4 = 44444
python
# =============================================================================== # # # # This file has been generated automatically!! Do not change this manually! # # ...
python
import os import sys import zipfile import asc_parse import wget import multiprocessing import urllib.request as request from contextlib import closing import argparse import shutil import glob # A decimal value that will decrease the output file size as it increases REDUCE_BY = 1.0 # A decimal value t...
python
import numpy as np import pandas as pd import os def prm_to_df(prm): """Convert prm to a pandas DataFrame""" values = list(prm.values()) columns = list(prm.keys()) df_prm = pd.DataFrame(columns=columns) for value, column in zip(values, columns): df_prm[column] = [value] return (df_prm)...
python
import time import random #import pygame import threading ''' Start with the person in an empty room with zombies coming at them. The maze, is part of the "nice to have" section, but not pertinent. ''' class Zombies: def __init__(self, xcor, ycor): self.xcor = xcor self.ycor= ycor self.image = '' #the above e...
python
# -*- coding: utf-8 -*- from .schema import dump, load from .loaded import LoadedValue from .schema import CallableFunc __all__ = ['dump', 'load', 'LoadedValue', 'CallableFunc']
python
#!/usr/bin/env python # Author: CloudNClock @ github # Date 2020/01/26 # Usage: DDNS updating for namesilo import urllib3 import xmltodict import requests import time import sys import datetime import configparser import xml.etree.ElementTree as ET # Update DNS in namesilo def update(currentIP,recordID,targetDomain...
python
import torch from abc import ABCMeta, abstractmethod from torchtrainer.utils.mixins import CudaMixin from .callbacks import Callback, CallbackContainer, History from .meters import ZeroMeasurementsError from enum import Enum from itertools import chain from torch.autograd import Variable from .utils.defaults import pa...
python
version = '0.66' short_version = version full_version = version
python
from flask import url_for from authentek.database.models import User def test_get_user(client, db, user, admin_headers): # test 404 user_url = url_for('api.user_by_id', user_id="100000") rep = client.get(user_url, headers=admin_headers) assert rep.status_code == 404 db.session.add(user) db.se...
python
''' setup ''' import re import io from distutils.command.build_ext import build_ext as build_ext_orig from setuptools import setup, find_packages, Extension # source: https://stackoverflow.com/a/39671214 __version__ = re.search( r'__version__\s*=\s*[\'"]([^\'"]*)[\'"]', io.open('nei_vcf/__init__.py', encoding...
python
#!/usr/bin/env python3 """opencv module tests""" import sys import os import inspect import logging import cv2 import numpy as np import matplotlib.pyplot as plt from matplotlib import colors from matplotlib import ticker from matplotlib.colors import LinearSegmentedColormap logger = logging.getLogger("OPENCV") d...
python
# Generated by Django 3.2.7 on 2021-09-03 10:07 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import phonenumber_field.modelfields class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(sett...
python
# -*- coding: utf-8 -*- import pytest from great_expectations.core import ( ExpectationConfiguration, ExpectationValidationResult, ) from great_expectations.render.renderer.renderer import Renderer def test_render(): # ??? Should this really return the input object? # Seems like raising NotImplemente...
python
from MyCodes.personal import title, inputInt, inputFloat from urllib.request import urlopen title('Exercício 113', 50, 34) a = inputInt('Digite um valor inteiro: ') b = inputFloat('Digite um valor real: ') print(f'O valor inteiro é {a} e o valor real é {b:.1f}.') title('Exercício 114', 50, 34) try: pag = urlopen(...
python
# Copyright 2017 Gustavo Baratto. 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 law...
python
from .block import * from .chain import * __version__ = "0.0.1"
python
import time from multiprocessing.pool import ThreadPool from core.events import EventHandler from core.keystore import KeyStore as kb from core.packetcap import pktcap from core.actionModule import actionModule from core.mymsf import myMsf class msfActionModule(actionModule): seentargets = dict() def __init...
python
string = 'emir','zarina','baizak','nazira' string = string.replace('emir','vanya') print(string)
python
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
python
import os import tempfile from pathlib import Path from test.splitgraph.commands.test_commit_diff import _alter_diff_splitting_dataset from test.splitgraph.conftest import API_RESOURCES, OUTPUT from unittest import mock from unittest.mock import call, patch, sentinel import httpretty import pytest from click import Cl...
python
name = "CheeseBurger"
python
import json import requests from requests.auth import HTTPBasicAuth as BasicAuth from requests.packages import urllib3 from urllib3.exceptions import InsecureRequestWarning urllib3.disable_warnings(InsecureRequestWarning) url = "https://sbx-nxos-mgmt.cisco.com:443/ins" username = "admin" password = "Admin_1234!" da...
python
# Generated by Django 2.1 on 2019-05-15 22:22 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main_app', '0006_deviceconfig_last_modify'), ] operations = [ migrations.AlterField( model_name='deviceconfig', name='...
python
class Diplomacy: """ Respresents every player diplomacy stances with others """ def __init__(self, stances=None): """ Initialize Diplomacy Args: stances (list(int)): stances with other player Note: there's 8 stances with other players """...
python
from portfolyo import dev, testing from portfolyo.tools import frames from numpy import nan import portfolyo as pf import numpy as np import pandas as pd import pytest @pytest.mark.parametrize("series_or_df", ["series", "df"]) @pytest.mark.parametrize("bound", ["right", "left"]) @pytest.mark.parametrize( ("in_val...
python
import sublime from ui.read import settings as read_settings from ui.write import write, highlight as write_highlight from lookup import file_type as lookup_file_type from ui.read import x as ui_read from ui.read import spots as read_spots from ui.read import regions as ui_regions from core.read import read as core_rea...
python
import random, time, torch import numpy as np from nlplingo.oregon.event_models.uoregon.define_opt import opt from nlplingo.oregon.event_models.uoregon.tools.utils import * from nlplingo.oregon.event_models.uoregon.models.pipeline._01.readers import read_abstract_train_data from nlplingo.oregon.event_models.uoregon.mod...
python
from dbnd._core.cli.click_utils import _help from dbnd._core.cli.service_auto_completer import completer from dbnd._core.task_build.task_registry import get_task_registry from dbnd._vendor import click @click.command() @click.argument("search", default="", autocompletion=completer.config()) @click.option("--module", ...
python
# Copyright 2016 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. """The page cycler v2. For details, see design doc: https://docs.google.com/document/d/1EZQX-x3eEphXupiX-Hq7T4Afju5_sIdxPWYetj7ynd0 """ from core import pe...
python
from typing import List from machine.params import Parameters from machine.plugin import Plugin from machine.connection import Connection from machine.plugin import PluginGenerator, PluginResult class Sequence(Plugin): def __init__(self, plugins: List[PluginGenerator]): assert len(plugins) > 0, "Sequence...
python
# You are given N pairs of numbers. # In every pair, the first number is always smaller than the second number. # A pair (c, d) can follow another pair (a, b) if b < c. # Chain of pairs can be formed in this fashion. # You have to find the longest chain which can be formed from the given set of pairs. dp = [[0]*10...
python
""" This is the geo_mean atom. geo_mean(x,y) = sqrt(x * y) If either x or y is a vector, the atom is applied elementwise. It is a CONCAVE atom. It is DECREASING in the first argument, and DECREASING in the second argument. It returns a SCALAR expression if the both arguments are SCALAR. ...
python
import torch __TESTS__ = { } def get_tests(): for k, v in __TESTS__.items(): yield k, v def register(test): name = getattr(test, "__name__", test.__class__.__name__) if name in __TESTS__: raise RuntimeError(f'Encountered a test name collision "{name}"') __TESTS__[name] = test retu...
python
from os import path from glob import glob from cStringIO import StringIO import numpy as np import h5py from scipy.sparse.csgraph import connected_components from scipy.sparse import csr_matrix from util import sort_nicely, veclen, filter_reindex def convert_sequence_to_hdf5(filename_pattern, loader_function, hdf_ou...
python
# This script created by Joseph Aaron Campbell - 10/2020 # this script references https://www.agisoft.com/forum/index.php?topic=10564.msg47949#msg47949 # Use this as a learning tool only. # I am not responsible for any damage to data or hardware if the script is not properly utilized. # Following Code tested and ba...
python
load("//tools/bzl:maven_jar.bzl", "maven_jar") AWS_SDK_VER = "2.16.19" AWS_KINESIS_VER = "2.3.4" JACKSON_VER = "2.10.4" def external_plugin_deps(): maven_jar( name = "junit-platform", artifact = "org.junit.platform:junit-platform-commons:1.4.0", sha1 = "34d9983705c953b97abb01e1cd04647f4727...
python
import collections from typing import List from thinglang.lexer.values.identifier import Identifier, GenericIdentifier from thinglang.symbols.merged_symbol import MergedSymbol from thinglang.symbols.symbol import Symbol from thinglang.utils import collection_utils class SymbolMap(object): """ Describes a sym...
python
# encoding:utf-8 from numpy import * import math import copy import pickle class C4_5DTree(object): def __init__(self): # 构造方法 self.tree = {} # 生成的树 self.dataSet = [] # 数据集 self.labels = [] # 标签集 def loadDataSet(self, path, labels, split): recordlist = [] with open...
python
import logging import subprocess import sys class Spotify(): def __init__(self, args): logging.info("Spotify Connect client started.") command = "spotifyd --no-daemon" self.process = subprocess.Popen(command, shell=True) def stop(self): self.process.kill() l...
python
# Copyright (c) 2016 Anki, 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 in the file LICENSE.txt or at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
python
# -*- coding: utf-8 -*- from django.conf.urls import url, include from django.contrib.auth.decorators import login_required from children.views import ChildrenTemplateView, ChildrenDetailView, ChildrenUpdateView from children.views import ChildrenCreateView, ChildrenDeleteView, ChildListJson urlpatterns = [ ur...
python
from biosimulators_utils.model_lang.bngl.validation import validate_model, read_model from biosimulators_utils.utils.core import flatten_nested_list_of_strings import os import shutil import tempfile import unittest class BgnlValidationTestCase(unittest.TestCase): FIXTURE_DIR = os.path.join(os.path.dirname(__file...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # # king_phisher/security_keys.py # # 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 above copyright # notice, th...
python
import sys nodes = [] class node: value = -1 visited = False dist = 2e30 prev = None idx = -1 neighbors = [] def __init__(self, v): self.value = v def getNeighbors(x,y,input): result = [] if y>1: result.append(input[y-1][x]) if y+1<len(input): result.ap...
python
#!/usr/bin/env python from distutils.core import setup setup(name='Ignition', version='0.1.8', description='Run multiple programs in a specific order and monitor their state', author='Luka Cehovin', author_email='luka.cehovin@gmail.com', url='https://github.com/lukacu/ignition/', packages=['ignition'], scripts...
python
from ..class_boids import Boids import numpy as np from nose.tools import assert_equal,assert_almost_equal import os import yaml def init_trial_boids(): pathtofile = 'fixtures/regression_fixtures.yml' data=yaml.load(open( os.path.join(os.path.dirname(__file__),pathtofile))) pos_start = [data['befor...
python
# Copyright (c) 2014-2018, F5 Networks, 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 agreed ...
python
import numpy as np import torch from net import Net from generator import Generator import utils EPOCHS = 100000 BATCH_SIZE = 32 LR = 1e-3 LR_STEP = 0.1 LR_FAILS = 3 SIZE = (40, 40) MARGIN = 1 NOISE = 0.1 MAX_LENGTH = 5 DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu') np.set_printoptions(thr...
python
# в разработке class NavigationHelper: def __init__(self, app): self.app = app def open_home_page(self): wd = self.wd # open home page wd.get("http://localhost/adressbook/group.php") def open_group_page(self): wd = self.wd # open group page wd.find_...
python
"""ReBias Copyright (c) 2020-present NAVER Corp. MIT license Implementation for simple statcked convolutional networks. """ import torch import torch.nn as nn class SimpleConvNet(nn.Module): def __init__(self, num_classes=None, kernel_size=7, feature_pos='post'): super(SimpleConvNet, self).__init__() ...
python
import tensorflow as tf import numpy as np class Convolutional_NN(object): def __init__(self): pass def lr_network(self, input_shape, label_shape): """ Create loss function and the list of metrics Arguments: input_shape: [list / tuple] input shape ...
python
# -*- coding: utf-8 -*- """ Created on Sat Feb 06 15:07:49 2016 @author: Mike """ from __future__ import division import pandas as pd import numpy as np import matplotlib.lines as mlines import matplotlib.pyplot as plt from matplotlib.legend_handler import HandlerLine2D import os from geopy.distance import vincenty fr...
python
# Copyright (c) Facebook, Inc. and its affiliates. (http://www.facebook.com) a.b -= 2 a[0] += 1 a[0:2] += 1
python
import re class JSVM(object): _memory = {} _program = [] _js_methods = {} def __init__(self, code=""): # TODO: parse automatically the 'swap' method # function Bn(a,b){var c=a[0];a[0]=a[b%a.length];a[b]=c;return a}; def _swap(args): a = list(args[0]) b...
python
#!/usr/bin/python """ entry point """ import datetime import traceback import six import tempfile import io import signal import json import gzip # config file from pandaserver.config import panda_config from pandaserver.taskbuffer.Initializer import initializer from pandaserver.taskbuffer.TaskBuffer import taskBu...
python
# -*- coding: UTF-8 -*- #!usr/env/bin python 3.6 from matplotlib.font_manager import FontProperties import matplotlib.lines as mlines import matplotlib.pyplot as plt import numpy as np def file2matrix(file_name): file = open(file_name) array_lines = file.readlines() number_of_lines = len(array_lines) ...
python
# Copyright (c) 2022 Manuel Olguín Muñoz <molguin@kth.se> # # 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...
python
# Copyright (c) 2020 Graphcore Ltd. All rights reserved. import torch import poptorch # half_stats_begin model = torch.nn.Sequential() model.add_module('lin', torch.nn.Linear(16, 16)) model.add_module('bn', torch.nn.BatchNorm1d(16)) model.float() opts = poptorch.Options() opts.Precision.runningStatisticsAlwaysFloat(...
python
# Generated by Django 2.2.24 on 2022-02-24 22:20 from django.db import migrations def commit_old_currencies_deactivation(apps, schema_editor): Currency = apps.get_model("exchange", "Currency") db_alias = schema_editor.connection.alias Currency.objects.using(db_alias).filter(code__in=["MRO", "VEF"]).update...
python
#! /usr/bin/python # # xindice_python_delete.py # # Apr/13/2012 # import math import cgi import string import sys import os import xml.dom.minidom import pycurl # import json # ------------------------------------------------------------------ sys.path.append ('/var/www/data_base/common/python_common') # from text_...
python
"""Wrapper for the CIFAR-10 dataset, which is provided in the `torchvision` package. The model and data transform are taken directly from: https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html """ # Chuan-Zheng Lee <czlee@stanford.edu> # July 2021 from pathlib import Path import torch import torch....
python
#Un alumno desea saber cual será su calificación final en la materia de Algoritmos. #Dicha calificación se compone de los siguientes porcentajes: #55% del promedio de sus tres calificaciones parciales. #30% de la calificación del examen final. #15% de la calificación de un trabajo final. parcial1 = float(input("Dig...
python
from ..utils import Object class EditMessageMedia(Object): """ Edits the content of a message with an animation, an audio, a document, a photo or a video. The media in the message can't be replaced if the message was set to self-destruct. Media can't be replaced by self-destructing media. Media in an album ...
python
# Generated by Django 3.0.7 on 2020-09-06 08:59 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('exams', '0020_auto_20200906_1408'), ] operations = [ migrations.AlterField( model_name='questio...
python
""" Tox21 dataset loader. """ from __future__ import division from __future__ import unicode_literals import os import logging import deepchem import dglt.contrib.moses.moses.data.featurizer as feat from dglt.contrib.moses.moses.data.reader.utils import AdditionalInfo from dglt.contrib.moses.moses.data.reader.data_lo...
python
import os import sys import time from monk.pip_functionality_tests.keras.test_default_train import test_default_train from monk.pip_functionality_tests.keras.test_default_eval_infer import test_default_eval_infer from monk.pip_functionality_tests.keras.test_update_copy_from import test_update_copy_from from monk.pip...
python
""" .log to view bot log For all users """ import asyncio from telethon import events from telethon.tl.types import ChannelParticipantsAdmins from uniborg.util import admin_cmd @borg.on(admin_cmd(pattern="log")) @borg.on(events.NewMessage(pattern=r"\.log(.*)",incoming=True)) async def _(event): if event.fwd_from:...
python
import rigor.importer import argparse def main(): parser = argparse.ArgumentParser(description='Imports images and metadata into the database') parser.add_argument('database', help='Database to use') parser.add_argument('directories', metavar='dir', nargs='+', help='Directory containing images and metadata to impo...
python
""" this is a transfer tool for existed oai data (train, val , test, debug) it will crop the image into desired size include two part crop the data and save it into new direc ( the code will be based on dataloader) generate a new directory which should provide the same train,val,test and debug set, but point to the cro...
python
#-*- coding: utf-8 -*- """ security ~~~~~~~~ Generic User class for interfacing with use accounts + authentication. """ import hashlib import random from utils import Storage, to36, valid_email, \ ALPHANUMERICS as ALPHAS username_regex = r'([A-Za-z0-9_%s]){%s,%s}$' passwd_regex = r'([A-Za-z0-9%s]...
python
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2018-10-26 11:01 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('auth', '0008_alter_user_u...
python
import re S = input() if re.search(r'^(hi)+$', S): print('Yes') else: print('No')
python
# -*- Mode: Python3; coding: utf-8; indent-tabs-mpythoode: nil; tab-width: 4 -*- import os import numpy as np PATH = "../Images/" def organize(data): # ndArray print("Original:") print(data[:2]) # Preparar, remodelar Array height, width, channels = data.shape data = data.flatten() # ve...
python
from arrp import clear def test_clear(): clear("test_dataset")
python
from multiprocessing import Pool from .rabbitmq.rmq_consumer import CocoRMQConsumer from .kafka.kafka_consumer import CocoKafkaConsumer from .redis.redis_consumer import CocoRedisConsumer from .logger import logger import time # this is aka mixture of a consumer factory and threadpool class CocoConsumerManager(object...
python
# Suites of test positions are normally stored in many different EPD files. # We keep them in one big JSON file instead, with standardized IDs, because # that makes it easier to keep track of scores over time. # # This program imports a new EPD test suite into that JSON file. import sys import json import chess impor...
python