repo_name stringlengths 6 97 | path stringlengths 3 341 | text stringlengths 8 1.02M |
|---|---|---|
nishantkshyp2004/backend-coding-challenge-django | app/note_taking/serializers.py | <filename>app/note_taking/serializers.py
from rest_framework import serializers
from note_taking.models import NoteTaking
from django.contrib.auth.models import User
class NoteTakingSerializer(serializers.ModelSerializer):
"""
NoteTaking Serializer class.
"""
owner = serializers.ReadOnlyField(source='... |
nishantkshyp2004/backend-coding-challenge-django | app/note_taking/models.py | <reponame>nishantkshyp2004/backend-coding-challenge-django
from django.db import models
TAGS_CHOICES = [("office", "office"),
("shopping", "shopping"),
("holiday", "holiday"),
("study", "study"),
("personal", "personal"),
("friends", "frie... |
nishantkshyp2004/backend-coding-challenge-django | app/note_taking/permissions.py | <filename>app/note_taking/permissions.py
from rest_framework import permissions
class NoteTakingPermissions(permissions.BasePermission):
"""
NoteTaking permission class
"""
def has_permission(self, request, view):
"""
Check if the request is in SAFE_METHODS('GET', 'HEAD', 'OPTIONS') o... |
nishantkshyp2004/backend-coding-challenge-django | app/note_taking/filters.py | from rest_framework import filters
class CustomSearchFilter(filters.SearchFilter):
"""
Customer search filter to return the search field as tags
if tags is present in the query parameter as true else call super.
"""
def get_search_fields(self, view, request):
if request.query_params.get('t... |
nishantkshyp2004/backend-coding-challenge-django | app/note_taking/migrations/0001_initial.py | # Generated by Django 4.0 on 2021-12-19 20:45
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0012_alter_user_first_name_max_length'),
]
operations = [
migrations.CreateModel(... |
nishantkshyp2004/backend-coding-challenge-django | app/note_taking/views.py | <filename>app/note_taking/views.py
from note_taking.models import NoteTaking
from note_taking.serializers import NoteTakingSerializer, UserSerializer
from django.contrib.auth.models import User
from note_taking.permissions import NoteTakingPermissions, UserPermissions
from note_taking.filters import CustomSearchFilter
... |
danielsela42/rotsedatamodel | py/rotsedatamodel/io/nptools.py | <filename>py/rotsedatamodel/io/nptools.py
'''
Created on Dec 19, 2017
@author: Daniel
'''
import numpy as np
def case_insensative_recarray(dtype):
''' for single named fields, create a tuple of the lowercase and uppercase versions.
Args:
dtype: np data type
Process:
For each dtype elem... |
danielsela42/rotsedatamodel | py/rotsedatamodel/tests/test_m2f.py | <reponame>danielsela42/rotsedatamodel
'''
Created on Dec 13, 2017
@author: arnon
'''
import unittest as ut
import numpy as np
from rotsedatamodel.match2fits import multimatch2fits, getmatch
from rotseutil import readfits
def remove_spaces(s):
# remove spaces in a string
return s.strip()
def compare_recar... |
danielsela42/rotsedatamodel | py/rotsedatamodel/io/fitstools.py | '''
Created on Dec 20, 2017
@author: daniel
'''
from .nptools import add_recarray_field
from astropy.io import fits as pyfits
def readfits(filepath):
''' creates a numpy based structure from a FITS file generated by match2fits.
Args:
filepath: path to FITS file.
Process:
Opens FITS fil... |
future-standard/Counting-ICCV-DSSINet | models/CRFVGG.py | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
import torch
import torch.nn as nn
import torch.nn.functional as F
from src.network import Conv2d, FC, Conv2d_dilated, np_to_variable
from src.vgg import vgg16
import numpy as np
from torch.autograd import Variable
import logging
## CRFFeatureRF
class MessagePassing(nn.M... |
future-standard/Counting-ICCV-DSSINet | src/RawLoader.py | import numpy as np
from scipy.ndimage import imread
import os
import random
import sys
import itertools
from density_gen import Gauss2D, read_image_label_fix, read_image_label_apdaptive, \
read_image_label_3d, read_image, save_density_map, get_annoted_kneighbors
import copy
import re
from collections import namedtupl... |
future-standard/Counting-ICCV-DSSINet | src/density_gen.py | import cv2
from scipy.ndimage import imread
import numpy as np
import os
from sklearn.neighbors import NearestNeighbors
import collections
from itertools import repeat
import scipy.io as scio
from PIL import Image
def save_density_map(density_map, output_dir, fname='results.png'):
density_map = 255.0 * (density_... |
future-standard/Counting-ICCV-DSSINet | src/datasets.py | import socket
hostname = socket.gethostname()
SHANG_PATH = ''
UCFEC_PATH = ''
WORLD_PATH = ''
TRANCOS_PATH = ''
UCF_PATH = ''
UCSD_PATH = ''
datasets = {
'shanghaiA': {
"density_method": "adaptive",
"density_method_config": {'downsize':32},
"train_image_path": SHANG_PATH + '/part_A_final... |
future-standard/Counting-ICCV-DSSINet | src/train_options.py | <gh_stars>10-100
import argparse
import os
import torch
from datetime import datetime
import shutil
import time
import random
import glob
import logging
import sys
try:
from pycrayon import CrayonClient
except ImportError:
CrayonClient = None
class TrainOptions():
def __init__(self):
self.initiali... |
tanyapole/OVANet | utils/utils.py | from models.basenet import *
import os
import torch
import neptune
import socket
def get_model_mme(net, num_class=13, temp=0.05, top=False, norm=True):
dim = 2048
if "resnet" in net:
model_g = ResBase(net, top=top)
if "resnet18" in net:
dim = 512
if net == "resnet34":
... |
Suveesh/Disaster-Response-Pipeline | models/train_classifier.py | <filename>models/train_classifier.py
# In[1]:
import sys
import nltk
import warnings
warnings.filterwarnings('ignore') # "error", "ignore", "always", "default", "module" or "once"
nltk.download('punkt')
nltk.download('wordnet')
import pandas as pd
import numpy as np
import re
from sqlalchemy import create_engine
fr... |
Suveesh/Disaster-Response-Pipeline | data/process_data.py | <filename>data/process_data.py
# In[1]:
import sys
import pandas as pd
import numpy as np
import re
from sqlalchemy import create_engine
# In[2]:
def load_data(messages_filepath, categories_filepath):
'''
Function to load Messages and Categories Data set from the csv file and merge
into a single data f... |
JugglingNumbers/cma-es | cma/__init__.py | from .core import CMA
|
JugglingNumbers/cma-es | notebook/utils/plot.py | import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
from matplotlib.ticker import FormatStrFormatter, LogLocator
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
from scipy.stats import chi2
import tensorflow as tf
def plot_3d_surface(
fitness_fn,
xlim,
ylim,
zlim=None,
... |
JugglingNumbers/cma-es | notebook/tensorboard_example.py | import logging
import os
import tensorflow as tf
if os.getcwd().split(os.sep)[-1] == 'notebook':
os.chdir('..')
from cma import CMA
def main():
logging.basicConfig(level=logging.INFO, format="%(asctime)s (%(levelname)s) %(message)s")
tf.random.set_seed(123)
max_epochs = 500
log_dir = 'logs/g... |
JugglingNumbers/cma-es | notebook/utils/__init__.py | <reponame>JugglingNumbers/cma-es<gh_stars>10-100
from .plot import (
plot_3d_surface,
plot_2d_contour,
plot_generations,
draw_confidence_ellipse,
plot_mean_coordinates,
)
|
JugglingNumbers/cma-es | setup.py | import setuptools
description = (
"Covariance Matrix Adaptation Evolution Strategy (CMA-ES) implemented with TensorFlow"
)
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name='cma-es',
packages=['cma'],
version='1.5.0',
license='MIT',
author="<NAME>",
... |
bernardkucina/vislice | tekstovni_umeski.py | <gh_stars>0
import model
def izpis_poraza(igra):
return f'IZGUBIL SI , <NAME>: {igra.geslo}'
def izpis_zmage(igra):
return f'ZMAGAL SI, <NAME>: {igra.geslo},' + f'POTREBOVAL SI {len(igra.napacne_crke())} UGIBOV'
def izpis_igra(igra):
text = (
f'Stanje gesla: {igra.praviln_del_gesla()} \n '
... |
renovate-bot/python-deploy | google/cloud/deploy_v1/services/cloud_deploy/async_client.py | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
murilobsd/unaerp | s1/pro_inte/servidor/cliente.py | #!/usr/bin/env python3
#
# Copyright (c) 2020 <NAME>' <<EMAIL>>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND ... |
murilobsd/unaerp | s1/pro_inte/servidor/servidor.py | <filename>s1/pro_inte/servidor/servidor.py
#!/usr/bin/env python3
#
# Copyright (c) 2020 <NAME>' <<EMAIL>>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies... |
jrnp97/auth0-python-api-samples | 00-Starter-Seed/server.py | """Python Flask API Auth0 integration example
"""
from functools import wraps
import json
from os import environ as env
from typing import Dict
from six.moves.urllib.request import urlopen
from dotenv import load_dotenv, find_dotenv
from flask import Flask, request, jsonify, _request_ctx_stack, Response
from flask_c... |
SmellyGeekBoy/piface-led-flasher | ledflasher.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# ledflasher.py
#
# Copyright 2014 <NAME>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at yo... |
akasa9525/grouper | grouper/processLabels.py | <gh_stars>1-10
import os
from subprocess import call
import pandas as pd
from collections import defaultdict
import logging
#run BLAST and return list of label files in order [TS->ASdb, AS->TSdb]
def runBLAST(faFile1, faFile2, outdir, threads):
logger = logging.getLogger("grouper")
TSdb = os.path.sep.join([outdir, ... |
akasa9525/grouper | grouper/filtGraph.py | from __future__ import print_function
import os
import pandas as pd
import math
import logging
class EquivCollection(object):
def __init__(self):
self.tnames = []
self.eqClasses = {}
self.hasNames = False
def setNames(self, names):
self.tnames = names
self... |
akasa9525/grouper | grouper/iterLabel.py | <filename>grouper/iterLabel.py
import sys
import os
import argparse
import itertools
import statistics
import re
import csv
import fileinput
import numpy as np
from collections import defaultdict
from subprocess import call
import pandas as pd
from collections import Counter
alpha = 0.8 #ratio alloted to the probabili... |
akasa9525/grouper | setup.py | from setuptools import setup
setup(name='biogrouper',
python_requires="<3.0",
version='0.1.3',
scripts=['bin/Grouper'],
description='Graph-based clustering and annotation for improved de novo transcriptome analysis',
url='https://github.com/COMBINE-lab/Grouper',
author='<NAME>, <NAM... |
akasa9525/grouper | grouper/eqnet.py | from __future__ import print_function
import itertools
import pandas as pd
import numpy as np
import os
import logging
import json
import networkx as nx
import math
from tqdm import tqdm
def buildNetFile(sampdirs, netfile, cutoff, auxDir, status_file,writecomponents=False):
logger = logging.getLogge... |
Ansud/supres_founder | source/structures/intervals.py | """
Intervals storage.
There is array of intervals, sorted by start.
The main functionality - detect is point belongs to any of them or not.
"""
class Intervals:
def __init__(self):
self.intervals = list()
def add(self, start: float, end: float):
# Let simplify my life and call normalize man... |
Ansud/supres_founder | find_levels.py | <filename>find_levels.py
"""
Main executable file used to start project
"""
import asyncio
from source.core import run_project
def main():
asyncio.run(run_project())
if __name__ == "__main__":
main()
|
Ansud/supres_founder | source/parser/__init__.py | """
Python project
"""
from .csv import parse_csv
|
Ansud/supres_founder | source/parse_arguments.py | """
Argument specifications and parsing
"""
import argparse
class ArgumentParser:
def __init__(self):
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(help='Commands help')
parser.add_argument("--price-sorted", help="Sort levels by price instead of count", action='sto... |
Ansud/supres_founder | source/core.py | """
Entry point for all operations
"""
import asyncio
from .analyzer import filter_daily_bars, filter_data, find_levels
from .downloader import download_daily_data, download_intraday_data
from .parse_arguments import ArgumentParser
from .parser import parse_csv
async def return_empty():
return list()
def load... |
Ansud/supres_founder | source/downloader/__init__.py | """
Python project
"""
from .base import download_daily_data, download_intraday_data
|
Ansud/supres_founder | source/parser/csv.py | <filename>source/parser/csv.py<gh_stars>1-10
"""
Parse CSV file to list of OHLC tuples
"""
import csv
from typing import Optional
from source.structures import OHLCData
async def parse_csv(
file_name: str,
delimiter: Optional[str] = ',',
positions: Optional[list] = None
):
"""
Pa... |
Ansud/supres_founder | source/analyzer/finder.py | <reponame>Ansud/supres_founder
"""
Process data to find levels
"""
def inc_count(prices, level, bottom):
if level not in prices:
prices[level] = dict(b=0, t=0)
if bottom:
prices[level]['b'] += 1
else:
prices[level]['t'] += 1
def find_levels(data: list, threshold: int, price_sort... |
Ansud/supres_founder | source/structures/ohlc.py | """
Data storage class
TODO: Add ability to analyse bar type
"""
class OHLCData:
def __init__(self, open, high, low, close):
self.open = float(open)
self.high = float(high)
self.low = float(low)
self.close = float(close)
def linearize(self):
return self.open, self.hig... |
Ansud/supres_founder | source/structures/__init__.py | <reponame>Ansud/supres_founder
"""
Python project
"""
from .ohlc import OHLCData
|
Ansud/supres_founder | source/downloader/base.py | <filename>source/downloader/base.py
"""
Grab data from internet
May be i will support more sources, but currently only alphavantage is supported,
thus this file a bit ridiculous
"""
from .alphavantage import get_daily_data, get_intraday_data
async def download_daily_data(ticker: str):
print('Start downloading d... |
Ansud/supres_founder | source/downloader/alphavantage.py | <reponame>Ansud/supres_founder<filename>source/downloader/alphavantage.py
"""
Grab data from alphavantage
"""
import json
import urllib.parse
import urllib.request
from datetime import datetime
import aiohttp
from source.structures import OHLCData
# Base alphavantage settings
BASE_URL = 'https://www.alphavantage.co... |
Ansud/supres_founder | source/analyzer/__init__.py | """
Python project
"""
from .finder import find_levels
from .filter import filter_daily_bars, filter_data
|
Ansud/supres_founder | source/analyzer/filter.py | <gh_stars>1-10
"""
Process daily and intraday data to filter out wrong levels
"""
from source.structures.intervals import Intervals
def filter_daily_bars(daily: list):
"""
Remove ordinary bars and leave only bars with high shadow
"""
return daily
def filter_data(daily: list, intraday: list, fuzz: f... |
moemoe89/simple-api-flask | src/models/__init__.py | <reponame>moemoe89/simple-api-flask<gh_stars>0
from flask_bcrypt import Bcrypt
from flask_sqlalchemy import SQLAlchemy
bcrypt = Bcrypt()
db = SQLAlchemy()
from .UserModel import UserModel, UserSchema |
moemoe89/simple-api-flask | src/models/UserModel.py | <filename>src/models/UserModel.py
import datetime
from marshmallow import fields, Schema
from . import db, bcrypt
class UserModel(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(128), nullable=False)
email = db.Column(db.String(128), unique=True, nu... |
moemoe89/simple-api-flask | src/app.py | <filename>src/app.py
from flask import Flask
from .config import app_config
from .models import db, bcrypt
def create_app(env_name):
app = Flask(__name__)
app.config.from_object(app_config[env_name])
bcrypt.init_app(app)
db.init_app(app)
@app.route('/', methods=['GET'])
def index():
return 'Pong'
... |
jadermcs/ZeCarioca | preprocess.py | import os
import glob
import tqdm
import random
import pandas as pd
path = "clear_threads/"
files = glob.glob(path+"*_*.tsv")
random.seed(42)
random.shuffle(files)
frames = []
counter = 0
for filein in tqdm.tqdm(files[:100000]):
counter += 1
df = pd.read_csv(filein, delimiter='\t', quoting=3, header=None,
... |
jadermcs/ZeCarioca | finetune.py | <reponame>jadermcs/ZeCarioca<gh_stars>0
import json
import tqdm
import torch
from torch.utils.data import Dataset, DataLoader
from transformers import GPT2Tokenizer, GPT2LMHeadModel
from transformers import Trainer, TrainingArguments
from datasets import load_dataset, load_metric
checkpoint = "models/adrenaline_multiw... |
jadermcs/ZeCarioca | train.py | <reponame>jadermcs/ZeCarioca
import os
import math
import tqdm
import glob
import pandas as pd
import torch
from torch.utils.data import Dataset, DataLoader
from sklearn.model_selection import train_test_split
from transformers import GPT2Tokenizer, GPT2LMHeadModel
from transformers import Trainer, TrainingArguments
fr... |
jadermcs/ZeCarioca | processdialog.py | <reponame>jadermcs/ZeCarioca
import json
import tqdm
import random
from transformers import GPT2Tokenizer, GPT2LMHeadModel
random.seed(42)
with open("synthetic.augmented.json") as fin:
data = json.load(fin)
tokens = data['ontology']['intents'] + data['ontology']['actions'] + ["<sos_u>", "<sos_b>", "<sos_a>", ... |
Pebaz/RGB | src/main.py | <filename>src/main.py
"""
MIT License
Copyright (c) 2018 <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, ... |
Pebaz/RGB | src/compilers/pound_define.py | <filename>src/compilers/pound_define.py
"""
MIT License
Copyright (c) 2018 <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 u... |
Pebaz/RGB | src/compilers/struct.py | <gh_stars>10-100
"""
MIT License
Copyright (c) 2018 <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... |
vlevorato/covid-ml-models | covid_ml/ml/feature_engineering.py | <gh_stars>1-10
from datetime import datetime, timedelta
import pandas as pd
import numpy as np
from dsbox.ml.feature_engineering.timeseries import RollingWindower, Shifter
def preprocess_location(dataframe, location='France'):
return dataframe[dataframe['location'] == location]
def preprocess_tests(dataframe):
... |
vlevorato/covid-ml-models | tests/test_workflow_covidml_datascience.py | from dsbox.utils import execute_dag
from workflow import workflow_covidml_datascience
execute_dag(workflow_covidml_datascience.dag, verbose=True)
|
vlevorato/covid-ml-models | covid_ml/config/env_vars.py | <reponame>vlevorato/covid-ml-models
from airflow.models import Variable
import os
"""
Using dictionary for config variables to be able to change the way to assign values.
(by default, using environment variables).
"""
config_variables = dict()
env_list = [
'COVIDML_PROJECT_PATH',
'COVIDML_DATA_PATH',
'COV... |
vlevorato/covid-ml-models | covid_ml/ml/ml_metadata.py | cols_to_shift = ['prop_cases_vs_tests',
'new_cases_2',
'new_tests',
'nouveaux_patients_reanimation',
'nouveaux_patients_hospitalises',
'new_patients_gueris',
'reproduction_rate',
'new_deaths']
ref_ops... |
vlevorato/covid-ml-models | tests/test_feature_engineering.py | <reponame>vlevorato/covid-ml-models<filename>tests/test_feature_engineering.py
import unittest
import pandas as pd
from pandas.util.testing import assert_frame_equal
from covid_ml.ml.feature_engineering import prepare_data
class TestFE(unittest.TestCase):
def test_prepare_data(self):
# given
df =... |
vlevorato/covid-ml-models | covid_ml/ml/model.py | import os
from datetime import datetime
import pandas as pd
import numpy as np
from dsbox.ml.metrics import root_mean_squared_error
from dsbox.operators.data_unit import DataInputUnit
from dsbox.utils import write_object_file, load_object_file
from dsbox.ml.feature_selection.greedy import greedy_feature_selection
from... |
vlevorato/covid-ml-models | covid_ml/utils/bq_generation.py | <filename>covid_ml/utils/bq_generation.py
import pandas as pd
def generate_data_viz_query(template_query, joining_field='date',
bq_dataset=None, targets=None):
pre_query = 'WITH'
for target in targets:
pre_query += ' predictions_data_{0} AS ' \
'( SELEC... |
vlevorato/covid-ml-models | workflow/workflow_covidml_datascience.py | from datetime import datetime, timedelta
from airflow import DAG
from airflow.operators.bash import BashOperator
from airflow.operators.dummy import DummyOperator
from airflow.operators.python import BranchPythonOperator
from airflow.operators.trigger_dagrun import TriggerDagRunOperator
from airflow.utils.task_group i... |
vlevorato/covid-ml-models | covid_ml/utils/io.py | <filename>covid_ml/utils/io.py
from datetime import datetime
import pandas as pd
def dummy_function(dataframe):
return dataframe
def export_data(dataframe, model_type_data_unit=None, target=None):
df_model_type = model_type_data_unit.read_data()
model_type = df_model_type['model_type'].values[0]
pri... |
vlevorato/covid-ml-models | workflow/workflow_covidml_export_data_to_bq.py | from airflow import DAG
from airflow.providers.google.cloud.operators.bigquery import BigQueryInsertJobOperator
from airflow.utils.task_group import TaskGroup
from dsbox.operators.bq_unit import DataOutputBigQueryUnit
from dsbox.operators.data_operator import DataOperator
from dsbox.operators.data_unit import DataInput... |
vlevorato/covid-ml-models | workflow/workflow_covidml_source_data.py | from airflow import DAG
from airflow.operators.dummy import DummyOperator
from dsbox.operators.data_operator import DataOperator
from dsbox.operators.data_unit import DataInputFileUnit, DataOutputFileUnit
from covid_ml.config.commons import dag_args, data_paths
from covid_ml.utils.io import dummy_function
dag = DAG(d... |
vlevorato/covid-ml-models | covid_ml/config/commons.py | from datetime import datetime, timedelta
from covid_ml.config.env_vars import config_variables
dag_start_date = datetime(2020, 12, 1)
# airflow common dag args
dag_args = {
'start_date': dag_start_date,
'retries': 1,
'retry_delay': timedelta(minutes=5),
'max_active_runs': 1
}
data_paths = {
'raw... |
Sophia-yu-kk/go-btfs | bin/find_dependlib.py | #!/usr/bin/env python
"""Script to find go library dependency"""
import os
import re
import subprocess
# start libs
start_libs = (
"go-ipfs-config",
"interface-go-ipfs-core",
"go-path",
"go-libp2p",
"go-multiaddr"
)
def helper(d, pkg, path):
if pkg not in d:
... |
postgres-ci/example-python-project | project_test.py | import unittest
from project import sum;
class ProjectTestCase(unittest.TestCase) :
def test_sum(self) :
assets = [
(0, 0, 0),
(2, 1, 1),
(4, 2, 2)
]
for asset in assets :
expected, a, b = asset
self.assertEqual(expected, sum(a, b))
if __name__ == '__main__':
unittest.main() |
maxwell-k/qbe | django_qbe/exports.py | # -*- coding: utf-8 -*-
import csv
from collections import OrderedDict, Callable
from io import StringIO, BytesIO
import six
from django.http import StreamingHttpResponse
__all__ = ("formats", )
class FormatsException(Exception):
pass
class Formats(OrderedDict):
def add(self, format):
parent = s... |
maxwell-k/qbe | django_qbe/savedqueries/models.py | <reponame>maxwell-k/qbe
from builtins import object
import pickle
from django.db import models
from django.utils.translation import ugettext_lazy as _
try:
from django.utils.timezone import now
except ImportError:
from datetime import datetime
now = datetime.now
from picklefield.fields import PickledObjec... |
maxwell-k/qbe | django_qbe/settings.py | <reponame>maxwell-k/qbe<filename>django_qbe/settings.py
# -*- coding: utf-8 -*-
from django.conf import settings
# admin
QBE_ADMIN = getattr(settings, "QBE_ADMIN", "admin")
QBE_ADMIN_SITE = getattr(settings,
"QBE_ADMIN_SITE", "%s.admin_site" % QBE_ADMIN)
# auth
QBE_ACCESS_FOR = getattr(settin... |
maxwell-k/qbe | setup.py | import codecs
import re
from os import path
from setuptools import setup, find_packages
def read(*parts):
file_path = path.join(path.dirname(__file__), *parts)
return codecs.open(file_path).read()
def find_version(*parts):
version_file = read(*parts)
version_match = re.search(r"^__version__ = ['\"](... |
maxwell-k/qbe | django_qbe/urls.py | <reponame>maxwell-k/qbe
# -*- coding: utf-8 -*-
try:
from django.conf.urls import url
except ImportError:
# Backward compatibility for Django prior to 1.6
from django.conf.urls.defaults import url
from django_qbe.exports import formats
from . import views
urlpatterns = [
url(r'^$', views.qbe_form, name... |
maxwell-k/qbe | django_qbe/savedqueries/apps.py | <reponame>maxwell-k/qbe
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
class QBESavedQueriesConfig(AppConfig):
name = 'django_qbe.savedqueries'
verbose_name = _("Query by Example")
|
maxwell-k/qbe | django_qbe/savedqueries/south_migrations/0001_initial.py | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'SavedQuery'
db.create_table('savedqueries_savedquery', (
('query_hash', self.gf(... |
maxwell-k/qbe | django_qbe/savedqueries/admin.py | <reponame>maxwell-k/qbe
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from django.contrib import admin
try:
from django.contrib.admin.utils import unquote
except ImportError:
# Backward compatibility for Django prior to 1.7
from django.contrib.admin.uti... |
maxwell-k/qbe | django_qbe/savedqueries/__init__.py | <filename>django_qbe/savedqueries/__init__.py<gh_stars>10-100
default_app_config = 'django_qbe.savedqueries.apps.QBESavedQueriesConfig'
|
maxwell-k/qbe | django_qbe/operators.py | from builtins import object
from django.conf import settings
from django.db import connections
from django.db.models.fields import Field
from importlib import import_module
from future.utils import with_metaclass
DATABASES = settings.DATABASES
BACKEND_TO_OPERATIONS = {
'mysql': 'MySQLOperations',
'oracle': 'O... |
jobscore/ansible-role-resque-exporter | molecule/default/tests/test_default.py | <gh_stars>0
import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_services_running_and_enabled(host):
assert host.service('prometheus-resque-exporter').is_enabled
assert host.service... |
Belyanova/Python_-training | model/configurations_user.py | <gh_stars>0
from sys import maxsize
class Configurations_user:
def __init__(self, firstname=None, middlename=None, last_name=None, nickname=None, title=None, company=None, address=None,
phone_home=None,phone_mobile=None, phone_work=None, mail1=None, mail2=None, mail3=None, bd_day=None, bd_month=No... |
Belyanova/Python_-training | fixture/orm.py | <reponame>Belyanova/Python_-training
from datetime import datetime
from pony.orm import *
from model.configurations_group import Configurations_group
from model.configurations_user import Configurations_user
from pymysql.converters import decoders
class ORM_fixture:
db = Database()
class ORMGroup(db.Entity)... |
Belyanova/Python_-training | bdd/user/user_scenarios.py | from pytest_bdd import scenario
from .user_steps import *
@scenario('users.feature', 'Add new user')
def test_add_new_user():
pass
@scenario('users.feature', 'Delete a user')
def test_delete_user():
pass
@scenario('users.feature', 'Edit a user')
def test_edit_user():
pass |
Belyanova/Python_-training | test/test_edit_group.py | # -*- coding: utf-8 -*-
from random import randrange
from model.configurations_group import Configurations_group
import random
import pytest
import allure
def test_case(app,db,check_ui,json_groups):
group = json_groups
with allure.step('Given a non-empty group list'):
if len(db.get_group_list()) == 0... |
Belyanova/Python_-training | test/test_user.py | <reponame>Belyanova/Python_-training
import re
from model.configurations_user import Configurations_user
import pytest
import allure
def test_user_on_home_page(app, db, json_users):
user = json_users
with allure.step('Given a non-empty user list'):
if app.user.count() == 0:
app.user.add_ne... |
Belyanova/Python_-training | fixture/user_group.py | from selenium.webdriver.support.ui import Select
from model.configurations_user import Configurations_user
from model.configurations_group import Configurations_group
class UserGroupHelper:
def __init__(self, app):
self.app = app
def group_selection(self, group):
wd = self.app.wd
wd.f... |
Belyanova/Python_-training | test/test_user_add_group.py | from model.configurations_user import Configurations_user
from model.configurations_group import Configurations_group
import random
import pytest
import allure
def test_user_add_group(app, db):
user_new = Configurations_user("User_name2", "name", "Last_name", "Nickname", "Title", "Company", "Address",
... |
Belyanova/Python_-training | test/test_db_matches_ui.py | <gh_stars>0
from model.configurations_group import Configurations_group
from timeit import timeit
def test_group_list(app, db):
print(timeit(lambda: app.group.get_group_list(), number=1))
def clean (group):
return Configurations_group (id=group.id, name=group.name.strip())
print(timeit(lambda:map(... |
Belyanova/Python_-training | fixture/db.py | import pymysql
from model.configurations_group import Configurations_group
from model.configurations_user import Configurations_user
from model.user_in_group import UserGroup
class DbFixture:
def __init__(self, host, name, user, password):
self.host = host
self.name = name
self.user = user... |
Belyanova/Python_-training | test/test_add_user.py | <gh_stars>0
# -*- coding: utf-8 -*-
from model.configurations_user import Configurations_user
import pytest
import allure
def test_user(app, db, check_ui, json_users):
user = json_users
with allure.step('Given a user list'):
old_users = db.get_user_list()
with allure.step('When I add a user %s the... |
Belyanova/Python_-training | generator/user.py | <reponame>Belyanova/Python_-training<gh_stars>0
from model.configurations_user import Configurations_user
import random
import string
import os.path
import jsonpickle
import getopt
import sys
from random import randint
try:
opts, args = getopt.getopt(sys.argv[1:],"n:f:", ["number of users", "file"])
except getopt... |
Belyanova/Python_-training | bdd/user/user_steps.py | <gh_stars>0
from pytest_bdd import given, when, then
from model.configurations_user import Configurations_user
import random
@given('a user list', target_fixture="user_list")
def user_list(db):
return db.get_user_list()
@given('a user', target_fixture="new_user")
def new_user():
return(Configurations_user("U... |
Belyanova/Python_-training | check_db_connection.py | <gh_stars>0
import pymysql
from fixture.orm import ORM_fixture
from model.configurations_group import Configurations_group
db = ORM_fixture (host="127.0.0.1", name="addressbook", user="root", password="")
try:
l = db.get_users_not_in_group(Configurations_group(id="60"))
for item in l:
print(item)
... |
Belyanova/Python_-training | fixture/user.py | from selenium.webdriver.support.ui import Select
from model.configurations_user import Configurations_user
import re
class UserHelper:
def __init__(self, app):
self.app = app
def open_users_page(self):
wd = self.app.wd
if not (wd.current_url.endswith("/index.php") and (wd.find_elemen... |
Belyanova/Python_-training | test/test_edit_user.py | <filename>test/test_edit_user.py
# -*- coding: utf-8 -*-
from model.configurations_user import Configurations_user
import re
import random
import pytest
import allure
def test_case(app, db, check_ui,json_users):
user = json_users
with allure.step('Given a non-empty user list'):
if len(db.get_user_list... |
Belyanova/Python_-training | test/test_del_user.py | # -*- coding: utf-8 -*-
from model.configurations_user import Configurations_user
import random
import pytest
import allure
def test_delete_first_group(app, db, check_ui, json_users):
user = json_users
with allure.step('Given a non-empty user list'):
if len(db.get_user_list()) == 0:
app.us... |
Belyanova/Python_-training | data/users.py | from model.configurations_user import Configurations_user
user = Configurations_user("User_name", "name", "Last_name", "Nickname", "Title", "Company", "Address", "999888777",
"12345678", "87654321", "e-mail_1", "e-mail_2", "e-mail_3", "1", "April", "1998", "1",
... |
Belyanova/Python_-training | data/groups.py | from model.configurations_group import Configurations_group
testdata = [
Configurations_group(name="name1", header="header1", footer="footer1"),
Configurations_group(name="name2", header="header2", footer="footer2"),
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.