repo_name stringlengths 6 97 | path stringlengths 3 341 | text stringlengths 8 1.02M |
|---|---|---|
UnBArqDsw2021-1/2021.1_G04_Cardeal | docs/assets/adapter.py | # Código com exemplo com implementação de Adapter patterns
class Target:
# O Target define a interface específica do domínio usada pelo código do cliente.
def request(self) -> str:
return "Alvo: o comportamento do alvo padrão."
class Adaptee:
# O Adaptee contém alguns comportamentos úteis, mas... |
UnBArqDsw2021-1/2021.1_G04_Cardeal | docs/assets/bridge.py | # Exemplo da utilização do design pattern Bridge
from __future__ import annotations
from abc import ABC, abstractmethod
class Abstraction:
"""
A abstração define a interface para a parte de "controle" dos dois
hierarquias de classes. Ele mantém uma referência a um objeto do
Hierarquia de implementa... |
lilab-bcb/skylab | docker/zarr-to-loom/ss2_plate_zarr_to_loom.py | <filename>docker/zarr-to-loom/ss2_plate_zarr_to_loom.py
#!/usr/bin/env python3
import os
import sys
import zarr
import loompy
import scipy as sc
from scipy.sparse import coo_matrix
import argparse
import numpy as np
def main():
description = """This script converts SS2 pipeline zarr output into loom"""
pars... |
lilab-bcb/skylab | docker/ss2-plate-aggregation/ss2_zarr_merge.py | <filename>docker/ss2-plate-aggregation/ss2_zarr_merge.py<gh_stars>0
#!/usr/bin/env python3
import os
import zarr
import argparse
import numpy as np
from zarr import Blosc
COMPRESSOR = Blosc(cname='lz4', clevel=5, shuffle=Blosc.SHUFFLE, blocksize=0)
class MismatchingInputHeader(Exception):
pass
class PathNotDi... |
lilab-bcb/skylab | docker/zarr-output/test_create_zarr_optimus.py | import tempfile
import zarr
import pandas as pd
import create_zarr_optimus as target_test_code
def test_add_cell_metrics():
path = tempfile.mkdtemp()
store = zarr.DirectoryStore(path)
root = zarr.group(store, overwrite=True)
test_data_location="test/data/"
test_metrics_file=test_data_location + "m... |
lilab-bcb/skylab | test/run_portability_test.py | <gh_stars>10-100
"""Runs a single portability test from a test directory."""
import argparse
import datetime
import glob
import json
import os
import sys
import time
import requests
# This is what we need to find in a test directory. I guess we'll glob the PR
# test WDL itself since it's named after the pipeline.
TE... |
lilab-bcb/skylab | docker/zarr-to-loom/optimus_zarr_to_loom.py | <reponame>lilab-bcb/skylab<filename>docker/zarr-to-loom/optimus_zarr_to_loom.py
#!/usr/bin/env python3
import os
import sys
import zarr
import loompy
import scipy as sc
from scipy.sparse import coo_matrix
import argparse
import numpy as np
# Custom Exception
class UnexpectedInputFormat(Exception):
pass
def mai... |
lilab-bcb/skylab | docker/zarr-output/create_zarr_optimus.py | import argparse
import csv
import gzip
import re
import numpy as np
import zarr
from scipy import sparse
from zarr import Blosc
import pandas as pd
import logging
COMPRESSOR = Blosc(cname="lz4", clevel=5, shuffle=Blosc.SHUFFLE, blocksize=0)
# the number of rows in a chunk for expression counts
CHUNK_ROW_SIZE = 10000... |
lilab-bcb/skylab | docker/modify-gtf/SetGeneNameToId.py | #!/usr/bin/env python
import argparse
import re
parser = argparse.ArgumentParser(description="Set the gene_name within a gtf to be equivalent to the values within gene_id.")
parser.add_argument('--in-gtf-file', dest='ingtf', help='input gtf file')
parser.add_argument('--out-gtf-file', dest='outgtf', help='output gtf ... |
khanhhua/erlbot | script/update-bus-stops.py | <filename>script/update-bus-stops.py
import json
import urllib
from urlparse import urlparse
import httplib2 as http #External library if __name__=="__main__":
#Authentication parameters
headers = {
'AccountKey' : os.environ['ACCOUNT_KEY'],
'accept' : 'application/json'
} #this is by default
with open("bus... |
GaryJones/sublime | characterCounter.py | <reponame>GaryJones/sublime<filename>characterCounter.py
import sublime, sublime_plugin
class PositionListener(sublime_plugin.EventListener):
def on_selection_modified(self,view):
text = "Position: "
sels = view.sel()
for s in sels:
text += " " + str(s.begin())
if not s.empty():
... |
yesbigstrong/Searchable-Symmetric-Encryption | client/sse_client.py | '''
The MIT License (MIT)
Copyright (c) 2016 <NAME>
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, merge,... |
yesbigstrong/Searchable-Symmetric-Encryption | jmap/jmap.py | <reponame>yesbigstrong/Searchable-Symmetric-Encryption
'''
The MIT License (MIT)
Copyright (c) 2016 <NAME>
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 with... |
Engine-B/CDM | objectModel/Python/cdm/persistence/modeljson/data_partition_persistence.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
from typing import Optional, List, TYPE_CHECKING
import dateutil.parser
from cdm.enums import CdmObjectType
from cdm.utilities import logger, TraitToPropertyMap
... |
Engine-B/CDM | objectModel/Python/tests/persistence/modeljson/test_modeljson.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
import unittest
import json
import os
from cdm.enums import CdmStatusLevel, CdmObjectType
from cdm.objectmodel import CdmDocumentDefinition, CdmManifestDefinition... |
Engine-B/CDM | objectModel/Python/cdm/utilities/primitive_appliers.py | <reponame>Engine-B/CDM
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
from typing import cast, TYPE_CHECKING
from cdm.enums import CdmAttributeContextType
from .applier_state import ApplierState
from .attribu... |
Engine-B/CDM | objectModel/Python/cdm/objectmodel/cdm_object_ref.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
from abc import abstractmethod
from typing import cast, Optional, Union, TYPE_CHECKING
from cdm.enums import CdmAttributeContextType, CdmObjectType
from cdm.util... |
Engine-B/CDM | objectModel/Python/cdm/persistence/modeljson/manifest_persistence.py | <reponame>Engine-B/CDM<filename>objectModel/Python/cdm/persistence/modeljson/manifest_persistence.py
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
from typing import List, Optional, TYPE_CHECKING
from collecti... |
Engine-B/CDM | objectModel/Python/cdm/persistence/cdmfolder/types/document_content.py | <reponame>Engine-B/CDM
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
from typing import Union, List
from .cdm_import import Import
from .trait import Trait
from .data_type import DataType
from .purpose import... |
Engine-B/CDM | objectModel/Python/cdm/objectmodel/cdm_purpose_def.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
from typing import Optional, TYPE_CHECKING
from cdm.enums import CdmObjectType
from cdm.utilities import ResolveOptions, logger, Errors
from .cdm_object_def impo... |
Engine-B/CDM | objectModel/Python/cdm/objectmodel/cdm_parameter_def.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
from typing import Optional, TYPE_CHECKING
from cdm.enums import CdmObjectType
from cdm.utilities import ResolveOptions, logger, Errors
from .cdm_object import C... |
Engine-B/CDM | objectModel/Python/cdm/persistence/cdmfolder/types/entity_attribute.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
from typing import Union, List
from cdm.utilities import JObject
from .entity_reference import EntityReference
from .purpose_reference import PurposeReference
fr... |
yuvalif/flume-ng-zeromq | vagrant/zmq-client.py | # based on: https://learning-0mq-with-pyzmq.readthedocs.io/en/latest/pyzmq/patterns/pushpull.html
import time
import zmq
def producer():
context = zmq.Context()
zmq_socket = context.socket(zmq.PUSH)
zmq_socket.bind("tcp://127.0.0.1:5557")
# Start your result manager and workers before you start your p... |
mir-group/PyfileUtils | pyfile_utils/output.py | import inspect
import logging
import sys
from logging import FileHandler, StreamHandler
from os import makedirs
from os.path import abspath, relpath, isfile, isdir
from typing import Optional
from .config import Config
class Output:
"""Class to manage file and folders
Args:
run_name: unique name of... |
mir-group/PyfileUtils | tests/test_output.py | <filename>tests/test_output.py
"""
Config tests
"""
import pytest
import tempfile
from os.path import isdir, isfile
from pyfile_utils.output import Output
# set up two config to test
minimal_config = dict(stringv="3x0e", intv=1, nonev=None, boolv=True)
configs_to_test = [dict(), minimal_config]
class TestInit:
... |
mir-group/PyfileUtils | pyfile_utils/auto_init.py | <gh_stars>100-1000
from typing import Optional, Union, List
import inspect
import logging
from .config import Config
def instantiate_from_cls_name(
module,
class_name: str,
prefix: Optional[Union[str, List[str]]] = [],
positional_args: dict = {},
optional_args: Optional[dict] = None,
all_args... |
mir-group/PyfileUtils | pyfile_utils/__init__.py | <reponame>mir-group/PyfileUtils<filename>pyfile_utils/__init__.py
from ._version import __version__
from .config import Config
from .auto_init import (
instantiate_from_cls_name,
instantiate,
get_w_prefix,
)
from .savenload import (
save_file,
load_file,
load_callable,
atomic_write,
fin... |
mir-group/PyfileUtils | setup.py | from setuptools import setup, find_packages
from pathlib import Path
package_names = ["pyfile", "utils"]
_name = "_".join(package_names)
name = "-".join(package_names)
# see https://packaging.python.org/guides/single-sourcing-package-version/
version_dict = {}
with open(Path(__file__).parents[0] / _name / "_version.p... |
dkasak/fingerprinter | tests/__init__.py | <filename>tests/__init__.py
"""Unit test package for fingerprinter."""
|
dkasak/fingerprinter | fingerprinter/__init__.py | <reponame>dkasak/fingerprinter
"""Top-level package for fingerprinter."""
__author__ = """<NAME>"""
__email__ = '<EMAIL>'
__version__ = '0.1.0'
|
dkasak/fingerprinter | fingerprinter/fingerprinter.py | """Main module."""
import collections
from typing import Generator
import bs4
from bs4 import BeautifulSoup
class Fingerprinter:
def __init__(self, contents):
soup = bs4.BeautifulSoup(contents, features="html.parser")
ids = collections.Counter(Fingerprinter.ids(soup))
classes = collecti... |
dkasak/fingerprinter | fingerprinter/cli.py | """Fingerprint HTML files."""
import sys
import click
from fingerprinter.fingerprinter import Fingerprinter
@click.command()
@click.argument("files", required=False, nargs=-1)
def main(files):
"""Fingerprint HTML files."""
if files:
for file in files:
contents = open(file, "r")
... |
rachitnaruzu/resultnotifier | backend/config.py | DATABASE_USER = '<DATABASE_USER>'
DATABASE_PASSWORD = '<DATABASE_PASSWORD>'
DATABASE_HOST = '<DATABASE_HOST>'
DATABASE_PORT = '<DATABASE_PORT>'
DATABASE_NAME = '<DATABASE_NAME>'
SECRET_KEY = '<SECRET_KEY>'
GCM_API_KEY = '<GCM_API_KEY>'
PROJECT_NAME = '<PROJECT_NAME>'
PROJECT_FCM_JSON_FILE = '<PROJECT_FCM_JSON_FILE>'
|
rachitnaruzu/resultnotifier | backend/databaseutil.py | <reponame>rachitnaruzu/resultnotifier<filename>backend/databaseutil.py
import os
import psycopg2
import config
INSERT_CMD = "INSERT INTO users (hash,registrationid) VALUES (%s,%s);"
FETCH_CMD1 = "SELECT registrationid FROM users;"
FETCH_CMD2 = "SELECT registrationid FROM (SELECT registrationid FROM users WHERE hash = ... |
rachitnaruzu/resultnotifier | backend/update_recent_viewed.py | from databaseutil import DatabaseUtility
dbutil = DatabaseUtility()
dbutil.update_avghits()
dbutil.clear_low_average_hits()
dbutil.cur.execute("SELECT displayname, oldviews, views, avghits FROM files ORDER BY avghits DESC LIMIT 10;")
for row in dbutil.cur.fetchall():
print(row) |
rachitnaruzu/resultnotifier | backend/registration.py | <gh_stars>0
import hashlib
from databaseutil import DatabaseUtility
def generate_hash(registration_id):
return str(hashlib.sha256(registration_id.encode()).hexdigest());
def register(registration_id):
hash = generate_hash(registration_id)
dbutil = DatabaseUtility()
if dbutil.is_present(hash, registrat... |
rachitnaruzu/resultnotifier | backend/notification.py | <filename>backend/notification.py
import json
import requests as rq
import datetime
from databaseutil import DatabaseUtility
import extractbeta as ex
import config
from oauth2client import service_account as sa
CONTENT_TYPE = "application/json"
API_KEY = "Bearer " + config.GCM_API_KEY
FCM_SEND_URL = "https://fcm.googl... |
rachitnaruzu/resultnotifier | backend/main.py | from flask import Flask,request, abort
import os
import datetime
import hashlib
from databaseutil import DatabaseUtility
import json
import hmac
import base64
from datetime import datetime as dt, timedelta as td
import config
dbutil = DatabaseUtility()
app = Flask(__name__)
KEY = config.SECRET_KEY # should be same as... |
rachitnaruzu/resultnotifier | backend/seed.py | from databaseutil import DatabaseUtility
dbutil = DatabaseUtility()
dbutil.createtables()
|
rachitnaruzu/resultnotifier | backend/extractbeta.py | <gh_stars>0
import re
import requests as rq
from bs4 import BeautifulSoup
'''
return a list of all the currenttly available data (result, notice, schedule, etc.....
implement this method to return a list in this format (ex: a webscrape logic):
[
{
'displayname': '2015 CSE VII SEM', # the name which w... |
bkornpob/pyaXeHelper | pyaxehelper/pyaxehelper.py | <gh_stars>0
import copy,os,glob
import pandas as pd
import numpy as np
from astropy.io import fits
from astropy.stats import sigma_clipped_stats
from scipy.interpolate import interp1d
def change_catalog_order(catalog):
x = read_catalog(catalog)
y = x.T.iloc[0:14].copy()
z = y.copy()
z1,z11 = z.iloc[11]... |
mattip/vmprof-server | webapp/views.py | <reponame>mattip/vmprof-server<gh_stars>0
import os
import socket
from django.shortcuts import render
from django.conf import settings
def index(request):
ctx = {
'registration_enabled': settings.REGISTRATION_ENABLED,
}
return render(request, 'webapp/index.html', ctx)
def json_serialize(response, ... |
mattip/vmprof-server | vmprofile/migrations/0010_auto_20220223_1047.py | # Generated by Django 3.2.12 on 2022-02-23 10:49
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('vmprofile', '0009_auto_20161222_1342'),
]
operations = [
migrations.AlterField(
model_name='runtimedata',
name='cre... |
mattip/vmprof-server | vmprofile/views.py | # -*- coding: utf-8 -*-
import io
import json
import hashlib
import datetime
try:
from urlparse import urlparse as parse
except ImportError:
from urllib import parse
from django.conf import settings
from django.contrib import auth
from django.contrib.auth.models import User
from django.http import HttpResponse... |
mattip/vmprof-server | vmlog/models.py | import uuid
from jitlog.parser import _parse_jitlog
from django.db import models
from django.contrib import admin
from vmprofile.models import RuntimeData
from vmcache.cache import get_reader
def get_profile_storage_directory(profile, filename):
return "log/%s/%s" % (profile.pk, filename)
class BinaryJitLog... |
mattip/vmprof-server | vmprofile/management/commands/cleanup_old_logs.py | <filename>vmprofile/management/commands/cleanup_old_logs.py
from datetime import timedelta
from django.core.management.base import BaseCommand
from django.utils import timezone
from vmprofile.models import RuntimeData
from django.core.exceptions import ObjectDoesNotExist
class Command(BaseCommand):
help = 'Clea... |
mattip/vmprof-server | vmprofile/management/commands/generate_api_token.py | <gh_stars>0
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand
from rest_framework.authtoken.models import Token
class Command(BaseCommand):
DEFAULT_USERNAME = 'api_user'
help = 'Generate new API token for uploading profile logs'
def add_arguments(self, parse... |
mattip/vmprof-server | webapp/urls.py |
from django.contrib import admin
from django.conf import settings
from rest_framework import routers
from vmprofile.views import MeView, RuntimeDataViewSet, TokenViewSet
from vmlog.views import (meta, trace, stitches, upload_jit)
from vmprofile.views import runtime_new, runtime_freeze
from vmprofile.views import uplo... |
mattip/vmprof-server | vmprofile/migrations/0007_auto_20160915_1542.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-09-15 15:42
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import vmprofile.models
import uuid
def forward_func(apps, schema_editor):
RuntimeData = apps.... |
corneliusroemer/unwetter | tests/test_dwd.py | <reponame>corneliusroemer/unwetter
from unwetter import dwd
from .assets import xmls, alert_1
def test_parse_xml_alert_simple():
expected = alert_1.event
assert dwd.parse_xml(xmls['alert_1']) == expected
|
corneliusroemer/unwetter | src/unwetter/regions.py | #!/user/bin/env python3.6
import yaml
with open('config/regions.yml', 'r') as fp:
REGIONS = {key: value for key, value in yaml.safe_load(fp.read()).items() if value.get('districts')}
for name, region in REGIONS.items():
region['name'] = name
def best_match(districts):
"""
Takes a list of districts... |
corneliusroemer/unwetter | src/unwetter/wina.py | <reponame>corneliusroemer/unwetter<filename>src/unwetter/wina.py
#!/user/bin/env python3.6
from ftplib import FTP_TLS
from io import BytesIO
import os
import ssl
from html import escape
from datetime import datetime
from uuid import uuid4
from . import db, generate
with open('assets/wina_template.xml', 'r') as fp:
... |
corneliusroemer/unwetter | src/unwetter/generate/helpers.py | <reponame>corneliusroemer/unwetter<gh_stars>1-10
#!/user/bin/env python3.6
import pytz
def rreplace(s, old, new, occurrence=-1):
"""
Replace old with new starting from end of the string
:param s: The string to be transformed
:param old: Search string
:param new: Replacement string
:param occur... |
corneliusroemer/unwetter | src/unwetter/sentry.py | <gh_stars>1-10
import os
import sentry_sdk
def init():
sentry_sdk.init(
os.environ.get('SENTRY_DSN'),
release=os.environ.get('HEROKU_SLUG_COMMIT'),
)
with sentry_sdk.configure_scope() as scope:
scope.set_tag(
'heroku-release',
f"{os.environ.get('HEROKU_APP... |
corneliusroemer/unwetter | tests/generate/test_blocks.py | from unwetter.generate import title
from ..assets import events
def test_title_alert_simple():
assert title(events['alert_1']) == '🚨 Neue Meldung: Amtliche WARNUNG vor GLÄTTE'
def test_title_alert_simple_wina():
assert (title(events['alert_1'], variant='wina_headline')
== 'Amtliche Unwetterwar... |
corneliusroemer/unwetter | tests/assets/helpers.py | from os.path import dirname
from pathlib import Path
ASSETS = Path(dirname(__file__))
def load_asset(name):
with open(ASSETS / name, 'r') as fp:
return fp.read()
|
corneliusroemer/unwetter | src/unwetter/generate/__init__.py | #!/user/bin/env python3.6
import os
import re
from .. import db
from .blocks import *
from .helpers import rreplace, upper_first
from . import urls
from ..config import SEVERITY_FILTER, STATES_FILTER
def describe_new_event(event):
text = f'''
{title(event, variant='wina_body')}
+++ Gültigkeit +++
{upper_firs... |
corneliusroemer/unwetter | scheduler.py | #!/user/bin/env python3.6
"""
Contains regular jobs like updating the DB
"""
from time import sleep
from apscheduler.schedulers.blocking import BlockingScheduler
from unwetter import db, slack, wina, sentry
from unwetter.config import filter_event
sentry.init()
sched = BlockingScheduler()
@sched.scheduled_job('i... |
corneliusroemer/unwetter | src/unwetter/generate/grammar.py | #!/user/bin/env python3.6
def genitive(region):
article_mapping = {
'der': 'des',
'die': 'der',
'das': 'des',
}
grammar = region['grammar']
if not grammar['gender']:
return grammar['genitive']
else:
article = article_mapping[grammar['gender']]
return... |
corneliusroemer/unwetter | src/unwetter/data/test_events/frost.py | from datetime import datetime
event = {
"_id": {
"$oid": "5c10e71dd8893200044e21ff"
},
"id": "2.49.0.1.276.0.DWD.PVW.1544533440000.3542dc6f-6e7d-4e1d-8190-ee5ac50641ba.DEU",
"sender": "<EMAIL>",
"sent": {
"$date": "2018-12-11T13:04:00.000Z"
},
"status": "Actual",
"msg_ty... |
andreinonea/sparrow | src/main/python/Sparrow/Sparrow.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'sparrow.ui'
#
# Created by: PyQt5 UI code generator 5.12.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWind... |
ShubhamAvasthi/LinkedIn-Automation-Scripts | send_connection_requests.py | from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
from selenium.common.exceptions import NoSuchElementException, ElementClickInterceptedException
from pr... |
geovanniuni/Practica2 | pygame_trabajo.py | <filename>pygame_trabajo.py
import pygame
import pygame.locals
pygame.init()
#pantalla = pygame.display.set_mode((600,600))
pantalla = pygame.display.set_mode((600,600))
b=pygame.sprite.Sprite()
b.image = pygame.image.load("mario_3.png").convert_alpha()
y1=b.image.subsurface((137,355,32,40))
y2=b.image.subsurfac... |
rimsha-aziz/SQLAlchemy-ClimateAnalysis | flask_app.py | import datetime as dt
import numpy as np
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func
from flask import Flask, jsonify
###########################################
# Setup Database
#######################################... |
ricardoauribe/leetcode | merge_in_between_lists.py | <filename>merge_in_between_lists.py
# merge in between lists
# https://leetcode.com/problems/merge-in-between-linked-lists/
# time O(n), space O(1)
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def printVals(self):
while self.next:
... |
ricardoauribe/leetcode | count_of_matches_in_tournament.py | # Count matches in a tournament
# https://leetcode.com/problems/count-of-matches-in-tournament/submissions/
# time O(nlogn), space O(nlogn)
class Solution:
def numberOfMatches(self, n: int) -> int:
if n <= 1:
return 0
else:
m = n//2
reminder = n%2
ret... |
GolosChain/eos | tests/test_api/Tests/Verificators/OutputBaseVerificator.py | import re
import unittest
def verifyOutputContains(output, value):
for line in output:
if value in line:
return
unittest.TestCase.assertTrue(unittest.TestCase(), False, "The value \'" + value + "\' not found in the cleos output")
def verifyOutputContainsRegex(output, regex):
for line... |
GolosChain/eos | tests/test_api/Suite/Framework/NodeosApiTestCase.py | <gh_stars>10-100
import unittest
from abc import abstractmethod
from Suite.Framework.NodeosApiTest import NodeosApiTest
class NodeosApiTestCase(unittest.TestCase):
def setUp(self) -> None:
apiClient = NodeosApiTest.instance.apiClient
contractsManager = NodeosApiTest.instance.contractsManager
... |
GolosChain/eos | tests/test_api/Suite/Tools/Nodeos.py | #!/usr/bin/python3
import subprocess
import shutil
import os
from Suite.Framework.eprint import eprint
class Nodeos:
workingDir = "./"
dataDir = workingDir + "data.dir"
def __init__(self, path, mongo, enableOutput):
self.enableOutput = enableOutput
self.clearWorkingDir()
self.sta... |
GolosChain/eos | tests/python_tests/nodeos_voting_test.py | <filename>tests/python_tests/nodeos_voting_test.py
#!/usr/bin/env python3
from testUtils import Utils
import testUtils
from Cluster import Cluster
from WalletMgr import WalletMgr
from Node import Node
from TestHelper import TestHelper
import decimal
import math
import re
import time
#################################... |
GolosChain/eos | tests/test_api/Tests/Verificators/TransactionExecutionVerificator.py | <filename>tests/test_api/Tests/Verificators/TransactionExecutionVerificator.py
from Tests.Verificators.OutputBaseVerificator import *
def verifyAccountCreated(output):
verifyOutputContains(output, "cyber <= cyber::newaccount")
def verifyContractWasSet(output):
verifyOutputContains(output, "cyber <= cyber::se... |
GolosChain/eos | tools/name_pretty_printer.py | # Pretty_printer for gdb name types.
# Execute: `source name_pretty_printer.py` to enable it.
import gdb
def name_to_string(value):
charmap = ".12345abcdefghijklmnopqrstuvwxyz"
name = ''
tmp = value
ch = charmap[int(tmp & 0xF)]
if ch != '.':
name = ch
tmp /= 16
for i in range(0,12)... |
GolosChain/eos | tests/test_api/Tests/Utils/JsonUtils.py | <filename>tests/test_api/Tests/Utils/JsonUtils.py
import json
from testfixtures import *
def jsonArg(a):
return " '" + json.dumps(a) + "' "
def jsonToPython(jsonString):
jsonDocumemt = json.loads(jsonString)
if type(jsonDocumemt) is dict:
return Object(jsonDocumemt)
if type(jsonDocumemt) is ... |
GolosChain/eos | tests/test_api/Suite/Tools/ContractsManager.py | <reponame>GolosChain/eos<gh_stars>10-100
from os import listdir
class ContractsManager:
def __init__(self, contracts):
self.contractsMap={}
for contract in contracts:
self.addContract(contract)
def addContract(self, directory):
pathSegments = directory.split('/')
... |
GolosChain/eos | tests/test_api/Tests/Verificators/BootSequenceVerificator.py | <filename>tests/test_api/Tests/Verificators/BootSequenceVerificator.py
from Tests.Verificators.OutputBaseVerificator import *
from Tests.Utils.JsonUtils import *
from testfixtures import *
import hashlib
def verifyContractHash(output, contractName, contractsManager):
path = contractsManager.getWasmFilePath(contra... |
GolosChain/eos | tests/test_api/Suite/Tools/Wallet.py | <filename>tests/test_api/Suite/Tools/Wallet.py
import os
from pathlib import Path
class Wallet:
walletName = "test_suite_wallet"
mainKeyName = "main_active_key"
def __init__(self, cleos):
self.cleos = cleos
self.keys = {}
self.createWallet()
self.importKey("<KEY>", "<KEY>... |
GolosChain/eos | tools/strace_decode.py | #!/usr/bin/env python3
import sys
import subprocess
from pprint import pprint
class LineInfo:
full = ''
num = 0
addr = ''
exe = ''
class Addr2LineDecoder:
args = []
result = {}
addr = ''
source = ''
def __init__(self, exe):
self.args = ['/usr/bin/addr2line', '-Cfip... |
GolosChain/eos | tests/test_api/Tests/Cases/Runner.py | from Suite.Framework.NodeosApiTest import WalletTestSuite
from os import path
import sys
if __name__ == '__main__':
currentDir = path.dirname(path.abspath(__file__))
sys.exit(not WalletTestSuite().execute(currentDir))
|
GolosChain/eos | tests/test_api/Tests/Cases/BootSequenceTest.py | <filename>tests/test_api/Tests/Cases/BootSequenceTest.py
from Suite.Framework.WalletTestCase import WalletTestCase
from abc import abstractmethod
from Tests.Verificators.TransactionExecutionVerificator import *
from Tests.Verificators.BootSequenceVerificator import *
class BootSequenceTest(WalletTestCase):
@abstr... |
GolosChain/eos | tests/python_tests/ee-test.py | <reponame>GolosChain/eos<filename>tests/python_tests/ee-test.py
#!/usr/bin/python3
# Tests for Event Engine.
# Preconditions:
# - nodeos run with enabled event_engine_plugin
# - event_engine_plugin write events in `events.dump` which located (or symlinked) in current directory
# - `tech.test` account created and conta... |
GolosChain/eos | tests/python_tests/nodeos_under_min_avail_ram.py | <gh_stars>10-100
#!/usr/bin/env python3
from core_symbol import CORE_SYMBOL
from Cluster import Cluster
from WalletMgr import WalletMgr
from Node import Node
from TestHelper import TestHelper
from testUtils import Utils
import testUtils
import time
import decimal
import math
import re
Print=Utils.Print
errorExit=Uti... |
GolosChain/eos | tests/test_api/Suite/Framework/WalletTestCase.py | from Suite.Framework.NodeosApiTestCase import NodeosApiTestCase
from abc import abstractmethod
from Suite.Framework.NodeosApiTest import WalletTestSuite
class WalletTestCase(NodeosApiTestCase):
@abstractmethod
def setApiTestExecutables(self, apiClient, contractsManager):
walletTest = WalletTestSuite.in... |
GolosChain/eos | tests/test_api/Suite/Tools/Cleos.py | import subprocess
import shlex
from Suite.Framework.eprint import eprint
class Cleos:
def __init__(self, path, remoteHost, printDialog):
self.path = path
self.remoteHost = remoteHost
self.printDialog = printDialog
def exec(self, params):
execTuple = (self.path, '-u', "http://"... |
GolosChain/eos | tests/test_api/Suite/Framework/NodeosApiTest.py | <gh_stars>10-100
import unittest
import argparse
import re
import atexit
import sys
from os import listdir
from os.path import isfile
from Suite.Tools.Nodeos import Nodeos
from Suite.Tools.Cleos import Cleos
from Suite.Tools.Wallet import Wallet
from Suite.Tools.ApiClient import ApiClient
from Suite.Tools.ContractsMa... |
GolosChain/eos | tests/test_api/Suite/Tools/ApiClient.py | <filename>tests/test_api/Suite/Tools/ApiClient.py
import requests
import json
from Suite.Framework.eprint import eprint
class ApiClient:
def __init__(self, host, port, apiClientDialog):
self.url = "http://" + host + ":" + str(port) + "/v1/chain/"
self.apiClientDialog = apiClientDialog
def sen... |
GolosChain/eos | tests/test_api/Tests/Cases/ApiTest.py | # from Suite.Framework.NodeosApiTestCase import NodeosApiTestCase
#
# class ApiTest(NodeosApiTestCase):
# def setApitTestExecutables(self, apiClient, contractsManager):
# self.apiClient = apiClient
# self.contractsManager = contractsManager
#
# def test_2_getSystemContractsAbiThroughApi(self):
#... |
GolosChain/eos | tests/test_api/Tests/Cases/GetAccountTest.py | from Suite.Framework.WalletTestCase import WalletTestCase
from Tests.Utils.JsonUtils import jsonArg
from abc import abstractmethod
from Tests.Verificators.TransactionExecutionVerificator import *
from Tests.Verificators.GetAccountVerificator import *
class GetAccountTest(WalletTestCase):
@abstractmethod
def ... |
GolosChain/eos | tests/test_api/Tests/Verificators/GetAccountVerificator.py | <reponame>GolosChain/eos
from Tests.Verificators.OutputBaseVerificator import *
import unittest
import re
def verifyGetNewAccount(output, testKey):
verifyOutputContainsRegex(output, "[ ]+owner[ ]+1:[ ]+1 " + testKey)
verifyOutputContainsRegex(output, "[ ]+active[ ]+1:[ ]+1 " + testKey)
verifyAccountLiquid... |
boyombo/django-mcq | mcq/core/tests/test_general.py | def test_home(client):
response = client.get('/')
#import pdb;pdb.set_trace()
assert response.status_code == 200
assert response.template_name == ['home.html']
|
boyombo/django-mcq | mcq/question/views.py | from csv import DictReader
from django.shortcuts import render, redirect
from django.contrib import messages
from question.forms import BatchForm
from question.models import Batch, Question, Option
from question.models import QUESTION_NAME, CORRECT_NAME
def new_batch(request):
if request.method == 'POST':
... |
boyombo/django-mcq | mcq/question/urls.py | from django.conf.urls import url
from question import views
urlpatterns = [
url(r'batch/$', views.new_batch, name='new_batch'),
]
|
boyombo/django-mcq | mcq/question/models.py | <reponame>boyombo/django-mcq
from __future__ import unicode_literals
from datetime import datetime
from django.db import models
QUESTION_NAME = 'QUESTION'
CORRECT_NAME = 'CORRECT'
FIELD_NAMES = [
QUESTION_NAME,
'A',
'B',
'C',
'D',
'E',
CORRECT_NAME
]
class Category(models.Model):
na... |
boyombo/django-mcq | mcq/core/tests/factories.py | <filename>mcq/core/tests/factories.py
import factory
import factory.django
import factory.fuzzy
from question import models as question
class Category(factory.django.DjangoModelFactory):
class Meta:
model = question.Category
name = factory.fuzzy.FuzzyText()
class Batch(factory.django.DjangoModelFa... |
boyombo/django-mcq | mcq/question/tests/test_views.py | import pytest
from django.core.files.uploadedfile import SimpleUploadedFile
from core.tests import factories
from question.models import Question, Batch, Option
@pytest.mark.django_db
def test_batch_get_status(client):
'''GET request status is 200.'''
response = client.get('/question/batch/')
assert resp... |
boyombo/django-mcq | mcq/question/admin.py | from django.contrib import admin
from question.models import Category, Batch, Question, Option
@admin.register(Category, Batch, Question, Option)
class QuestionAdmin(admin.ModelAdmin):
pass
#@admin.register(Batch)
#class BatchAdmin(admin.ModelAdmin):
# exclude = ['uploaded_on']
# form = BatchForm
#
# ... |
boyombo/django-mcq | mcq/question/migrations/0002_auto_20160409_2118.py | <reponame>boyombo/django-mcq<gh_stars>0
# -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-04-09 21:18
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('question', '0001_initial'),
]
operations = [... |
boyombo/django-mcq | mcq/question/migrations/0001_initial.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-04-09 18:02
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
... |
boyombo/django-mcq | mcq/question/forms.py | <filename>mcq/question/forms.py
from django import forms
from models import Batch, FIELD_NAMES
from csv import DictReader
class BatchForm(forms.ModelForm):
#name = forms.CharField(
# widget=forms.TextInput(attrs={'class': 'form-control'}))
#category = forms.ModelChoiceField(
# widget=forms.Choi... |
boyombo/django-mcq | mcq/question/tests/test_forms.py | import pytest
from django.core.files.uploadedfile import SimpleUploadedFile
from question.forms import BatchForm
from core.tests import factories
@pytest.mark.django_db
def test_upload(suf, form_data):
form = BatchForm(form_data, {'question_file': suf})
assert form.is_valid()
#@pytest.mark.django_db
#def t... |
SanjarbekSaminjonov/payme-integration | order/migrations/0005_alter_order_amount_alter_order_amount_for_payme.py | <filename>order/migrations/0005_alter_order_amount_alter_order_amount_for_payme.py
# Generated by Django 4.0.2 on 2022-04-07 16:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('order', '0004_order_amount_for_payme_alter_order_place_id'),
]
op... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.