hexsha stringlengths 40 40 | size int64 5 1.05M | ext stringclasses 98
values | lang stringclasses 21
values | max_stars_repo_path stringlengths 3 945 | max_stars_repo_name stringlengths 4 118 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 368k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 945 | max_issues_repo_name stringlengths 4 118 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 134k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 945 | max_forks_repo_name stringlengths 4 135 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 5 1.05M | avg_line_length float64 1 1.03M | max_line_length int64 2 1.03M | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c4a495c936f6c9940618d22b7baadbc01990be87 | 2,960 | c | C | hg/ffaToFa/ffaToFa.c | CEpBrowser/CEpBrowser--from-UCSC-CGI-BIN | dabbcca824503a7d3342714047bd55787b52188d | [
"IJG"
] | null | null | null | hg/ffaToFa/ffaToFa.c | CEpBrowser/CEpBrowser--from-UCSC-CGI-BIN | dabbcca824503a7d3342714047bd55787b52188d | [
"IJG"
] | null | null | null | hg/ffaToFa/ffaToFa.c | CEpBrowser/CEpBrowser--from-UCSC-CGI-BIN | dabbcca824503a7d3342714047bd55787b52188d | [
"IJG"
] | null | null | null | /* ffaToFa - convert Greg Schulers .ffa fasta files to our .fa files */
#include "common.h"
#include "portable.h"
#include "linefile.h"
#include "hash.h"
#include "hCommon.h"
static char const rcsid[] = "$Id: ffaToFa.c,v 1.4 2006/03/30 16:53:35 angie Exp $";
FILE *errLog;
void warnHandler(char *format, va_list args)
/* Default error message handler. */
{
if (format != NULL)
{
vfprintf(stderr, format, args);
vfprintf(errLog, format, args);
fprintf(stderr, "\n");
fprintf(errLog, "\n");
}
}
void usage()
/* Explain usage and exit. */
{
errAbort(
"ffaToFa convert Greg Schuler .ffa fasta files to UCSC .fa fasta files\n"
"usage:\n"
" ffaToFa file.ffa faDir trans\n"
"where ffaDir is directory full of .ffa files, faDir is where you want\n"
"to put the corresponding .fa files, trans is a table that\n"
"translates from one name to the other and cloneSizes is a file\n"
"that lists the size of each clone.\n"
"If you put 'stdin' for file.ffa, it will read from standard input.\n");
}
void ffaToFa(char *inFile, char *outDir, char *outTabName)
/* convert Greg Schulers .ffa fasta files to our .fa files */
{
struct lineFile *in;
FILE *out = NULL, *tab;
int lineSize;
char *line;
char ucscName[128];
char path[512];
static char lastPath[512];
int outFileCount = 0;
struct hash *uniqClone = newHash(16);
struct hash *uniqFrag = newHash(19);
boolean ignore = FALSE;
makeDir(outDir);
errLog = mustOpen("ffaToFa.err", "w");
tab = mustOpen(outTabName, "w");
printf("Converting %s", inFile);
fflush(stdout);
if (sameString(inFile, "stdin"))
in = lineFileStdin(TRUE);
else
in = lineFileOpen(inFile, TRUE);
while (lineFileNext(in, &line, &lineSize))
{
if (line[0] == '>')
{
ignore = FALSE;
gsToUcsc(line+1, ucscName);
faRecNameToFaFileName(outDir, ucscName, path);
if (hashLookup(uniqFrag, ucscName))
{
ignore = TRUE;
warn("Duplicate %s in %s, ignoring all but first",
ucscName, inFile);
}
else
{
hashAdd(uniqFrag, ucscName, NULL);
}
if (!sameString(path, lastPath))
{
strcpy(lastPath, path);
carefulClose(&out);
if (hashLookup(uniqClone, path))
{
warn("Duplicate %s in %s ignoring all but first",
ucscName, inFile);
}
else
{
hashAdd(uniqClone, path, NULL);
out = mustOpen(path, "w");
++outFileCount;
if ((outFileCount&7) == 0)
{
putc('.', stdout);
fflush(stdout);
}
}
}
if (out != NULL && !ignore)
{
fprintf(out, ">%s\n", ucscName);
fprintf(tab, "%s\t%s\n", ucscName, line+1);
}
}
else
{
if (out != NULL && !ignore)
{
fputs(line, out);
fputc('\n', out);
}
}
}
carefulClose(&out);
fclose(tab);
lineFileClose(&in);
printf("Made %d .fa files in %s\n", outFileCount, outDir);
}
int main(int argc, char *argv[])
/* Process command line. */
{
if (argc != 4)
usage();
ffaToFa(argv[1], argv[2], argv[3]);
return 0;
}
| 22.769231 | 83 | 0.625338 |
40a47fe9c8051ee50fd95d68f0506a94b9fe687e | 3,331 | py | Python | my_utils.py | naseemap47/TrafficSign-ComputerVision-python | bdccf9f62180c70714af75feb50286b1fa4c1e93 | [
"MIT"
] | 1 | 2022-02-25T18:49:45.000Z | 2022-02-25T18:49:45.000Z | my_utils.py | naseemap47/TrafficSign-ComputerVision-python | bdccf9f62180c70714af75feb50286b1fa4c1e93 | [
"MIT"
] | null | null | null | my_utils.py | naseemap47/TrafficSign-ComputerVision-python | bdccf9f62180c70714af75feb50286b1fa4c1e93 | [
"MIT"
] | null | null | null | import os
import glob
import shutil
from sklearn.model_selection import train_test_split
import shutil
import csv
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import tensorflow as tf
import numpy as np
def split_data(path_to_data, path_to_save_train, path_to_save_val, split_size=0.2):
folders = os.listdir(path_to_data)
for folder in folders:
full_path = os.path.join(path_to_data, folder)
path_to_images = glob.glob(os.path.join(full_path, '*png'))
x_train, x_val = train_test_split(path_to_images, test_size=split_size)
for x in x_train:
path_to_folder = os.path.join(path_to_save_train, folder)
if not os.path.isdir(path_to_folder):
os.makedirs(path_to_folder)
shutil.copy(x, path_to_folder)
for x in x_val:
path_to_folder = os.path.join(path_to_save_val, folder)
if not os.path.isdir(path_to_folder):
os.makedirs(path_to_folder)
shutil.copy(x, path_to_folder)
def order_test_data(path_to_csv, path_to_data):
try:
with open(path_to_csv, 'r') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
for i,row in enumerate(reader):
if i==0:
continue
img_name = row[-1].replace('Test/', '')
label = row[-2]
path_to_folder = os.path.join(path_to_data, label)
img_full_path = os.path.join(path_to_data, img_name)
if not os.path.isdir(path_to_folder):
os.makedirs(path_to_folder)
shutil.move(img_full_path, path_to_folder)
except:
print("[INFO] : Error reading csv file")
def create_generators(batch_size, path_to_train_data, path_to_val_data, path_to_test_data):
preprocessor = ImageDataGenerator(
rescale = 1/225,
rotation_range=10,
width_shift_range=0.1,
height_shift_range=0.1
)
test_preprocessor = ImageDataGenerator(
rescale = 1 / 225
)
train_generators = preprocessor.flow_from_directory(
path_to_train_data,
target_size=(70,70),
color_mode='rgb',
class_mode='categorical',
batch_size=batch_size,
shuffle=True
)
val_generators = test_preprocessor.flow_from_directory(
path_to_val_data,
target_size=(70,70),
color_mode='rgb',
class_mode='categorical',
batch_size=batch_size,
shuffle=False
)
test_generators = test_preprocessor.flow_from_directory(
path_to_test_data,
target_size=(70,70),
color_mode='rgb',
class_mode='categorical',
batch_size=batch_size,
shuffle=False
)
return train_generators, val_generators, test_generators
def predict_with_model(img_path, model):
image = tf.io.read_file(img_path)
image = tf.image.decode_png(image, channels=3)
image = tf.image.convert_image_dtype(image, dtype=tf.float32)
image = tf.image.resize(image, [70,70]) # (70,70,3)
image = tf.expand_dims(image, axis=0) # (1,70,70,3)
predictions = model.predict(image) #[0.009,0.09,0.99, 0.0009,...]
predictions = np.argmax(predictions) # 3
return predictions
| 30.842593 | 91 | 0.639147 |
67a7d295ff7a1e2aff9b01c814eda64de78fa31b | 12,504 | dart | Dart | lib/ui/invoice/edit/invoice_edit_items.dart | iammohsinar/admin-portal | 94794b3e24cb3e4718611abf0392eb18735c313c | [
"AAL"
] | 2 | 2021-08-15T21:20:42.000Z | 2021-08-19T09:41:11.000Z | lib/ui/invoice/edit/invoice_edit_items.dart | iammohsinar/admin-portal | 94794b3e24cb3e4718611abf0392eb18735c313c | [
"AAL"
] | null | null | null | lib/ui/invoice/edit/invoice_edit_items.dart | iammohsinar/admin-portal | 94794b3e24cb3e4718611abf0392eb18735c313c | [
"AAL"
] | null | null | null | import 'package:invoiceninja_flutter/ui/app/forms/custom_field.dart';
import 'package:invoiceninja_flutter/ui/app/forms/decorated_form_field.dart';
import 'package:invoiceninja_flutter/ui/app/help_text.dart';
import 'package:invoiceninja_flutter/ui/app/invoice/invoice_item_view.dart';
import 'package:invoiceninja_flutter/ui/app/invoice/tax_rate_dropdown.dart';
import 'package:invoiceninja_flutter/ui/app/scrollable_listview.dart';
import 'package:invoiceninja_flutter/ui/invoice/edit/invoice_edit_items_vm.dart';
import 'package:invoiceninja_flutter/ui/invoice/edit/invoice_edit_vm.dart';
import 'package:invoiceninja_flutter/utils/completers.dart';
import 'package:invoiceninja_flutter/utils/dialogs.dart';
import 'package:invoiceninja_flutter/utils/formatting.dart';
import 'package:flutter/material.dart';
import 'package:invoiceninja_flutter/data/models/models.dart';
import 'package:invoiceninja_flutter/utils/localization.dart';
class InvoiceEditItems extends StatefulWidget {
const InvoiceEditItems({
Key key,
@required this.viewModel,
@required this.entityViewModel,
}) : super(key: key);
final EntityEditItemsVM viewModel;
final EntityEditVM entityViewModel;
@override
_InvoiceEditItemsState createState() => _InvoiceEditItemsState();
}
class _InvoiceEditItemsState extends State<InvoiceEditItems> {
int selectedItemIndex;
void _showInvoiceItemEditor(int lineItemIndex, BuildContext context) {
showDialog<ItemEditDetails>(
context: context,
builder: (BuildContext context) {
final viewModel = widget.viewModel;
final invoice = viewModel.invoice;
return ItemEditDetails(
viewModel: viewModel,
entityViewModel: widget.entityViewModel,
key: ValueKey('__${lineItemIndex}__'),
invoiceItem: invoice.lineItems[lineItemIndex],
index: lineItemIndex,
);
});
}
@override
Widget build(BuildContext context) {
final localization = AppLocalization.of(context);
final viewModel = widget.viewModel;
final invoice = viewModel.invoice;
final itemIndex = viewModel.invoiceItemIndex;
final invoiceItem =
itemIndex != null && invoice.lineItems.length > itemIndex
? invoice.lineItems[itemIndex]
: null;
if (invoiceItem != null && itemIndex != selectedItemIndex) {
viewModel.clearSelectedInvoiceItem();
WidgetsBinding.instance.addPostFrameCallback((duration) async {
_showInvoiceItemEditor(itemIndex, context);
});
}
if (invoice.lineItems.isEmpty) {
return HelpText(localization.clickPlusToAddItem);
}
return ScrollableListView(
children: [
for (int i = 0; i < invoice.lineItems.length; i++)
InvoiceItemListTile(
invoice: invoice,
invoiceItem: invoice.lineItems[i],
onTap: () => _showInvoiceItemEditor(i, context),
)
],
);
}
}
class ItemEditDetails extends StatefulWidget {
const ItemEditDetails({
Key key,
@required this.index,
@required this.invoiceItem,
@required this.viewModel,
@required this.entityViewModel,
}) : super(key: key);
final int index;
final InvoiceItemEntity invoiceItem;
final EntityEditItemsVM viewModel;
final EntityEditVM entityViewModel;
@override
ItemEditDetailsState createState() => ItemEditDetailsState();
}
class ItemEditDetailsState extends State<ItemEditDetails> {
final _productKeyController = TextEditingController();
final _notesController = TextEditingController();
final _costController = TextEditingController();
final _qtyController = TextEditingController();
final _discountController = TextEditingController();
final _custom1Controller = TextEditingController();
final _custom2Controller = TextEditingController();
final _custom3Controller = TextEditingController();
final _custom4Controller = TextEditingController();
TaxRateEntity _taxRate1;
TaxRateEntity _taxRate2;
TaxRateEntity _taxRate3;
List<TextEditingController> _controllers = [];
final _debouncer = Debouncer();
@override
void didChangeDependencies() {
if (_controllers.isNotEmpty) {
return;
}
final invoiceItem = widget.invoiceItem;
_productKeyController.text = invoiceItem.productKey;
_notesController.text = invoiceItem.notes;
_costController.text = formatNumber(invoiceItem.cost, context,
formatNumberType: FormatNumberType.inputMoney);
_qtyController.text = formatNumber(invoiceItem.quantity, context,
formatNumberType: FormatNumberType.inputAmount);
_discountController.text = formatNumber(invoiceItem.discount, context,
formatNumberType: FormatNumberType.inputMoney);
_custom1Controller.text = invoiceItem.customValue1;
_custom2Controller.text = invoiceItem.customValue2;
_custom3Controller.text = invoiceItem.customValue3;
_custom4Controller.text = invoiceItem.customValue4;
_controllers = [
_productKeyController,
_notesController,
_costController,
_qtyController,
_discountController,
_custom1Controller,
_custom2Controller,
_custom3Controller,
_custom4Controller,
];
_controllers.forEach(
(dynamic controller) => controller.addListener(_onTextChanged));
_taxRate1 =
TaxRateEntity(name: invoiceItem.taxName1, rate: invoiceItem.taxRate1);
_taxRate2 =
TaxRateEntity(name: invoiceItem.taxName2, rate: invoiceItem.taxRate2);
_taxRate3 =
TaxRateEntity(name: invoiceItem.taxName3, rate: invoiceItem.taxRate3);
super.didChangeDependencies();
}
@override
void dispose() {
_controllers.forEach((dynamic controller) {
controller.removeListener(_onTextChanged);
controller.dispose();
});
super.dispose();
}
void _onTextChanged() {
_debouncer.run(() {
_onChanged();
});
}
void _onChanged() {
var invoiceItem = widget.invoiceItem.rebuild((b) => b
..productKey = _productKeyController.text.trim()
..notes = _notesController.text
..cost = parseDouble(_costController.text)
..quantity = parseDouble(_qtyController.text)
..discount = parseDouble(_discountController.text)
..customValue1 = _custom1Controller.text.trim()
..customValue2 = _custom2Controller.text.trim()
..customValue3 = _custom3Controller.text.trim()
..customValue4 = _custom4Controller.text.trim());
if (_taxRate1 != null) {
invoiceItem = invoiceItem.applyTax(_taxRate1);
}
if (_taxRate2 != null) {
invoiceItem = invoiceItem.applyTax(_taxRate2, isSecond: true);
}
if (_taxRate3 != null) {
invoiceItem = invoiceItem.applyTax(_taxRate3, isThird: true);
}
if (invoiceItem != widget.invoiceItem) {
widget.viewModel.onChangedInvoiceItem(invoiceItem, widget.index);
}
}
@override
Widget build(BuildContext context) {
final localization = AppLocalization.of(context);
final viewModel = widget.viewModel;
final company = viewModel.company;
return AlertDialog(
actions: [
TextButton(
child: Text(localization.remove.toUpperCase()),
onPressed: () => confirmCallback(
context: context,
callback: () {
widget.viewModel.onRemoveInvoiceItemPressed(widget.index);
Navigator.of(context).pop();
}),
),
TextButton(
child: Text(localization.done.toUpperCase()),
onPressed: () {
viewModel.clearSelectedInvoiceItem();
Navigator.of(context).pop();
},
)
],
content: SingleChildScrollView(
child: Column(
children: <Widget>[
DecoratedFormField(
label: localization.product,
controller: _productKeyController,
onSavePressed: widget.entityViewModel.onSavePressed,
),
DecoratedFormField(
keyboardType: TextInputType.multiline,
label: localization.description,
controller: _notesController,
maxLines: 4,
),
CustomField(
controller: _custom1Controller,
field: widget.invoiceItem.isTask
? CustomFieldType.task1
: CustomFieldType.product1,
onSavePressed: widget.entityViewModel.onSavePressed,
value: _custom1Controller.text,
),
CustomField(
controller: _custom2Controller,
field: widget.invoiceItem.isTask
? CustomFieldType.task2
: CustomFieldType.product2,
onSavePressed: widget.entityViewModel.onSavePressed,
value: _custom2Controller.text,
),
CustomField(
controller: _custom3Controller,
field: widget.invoiceItem.isTask
? CustomFieldType.task3
: CustomFieldType.product3,
onSavePressed: widget.entityViewModel.onSavePressed,
value: _custom3Controller.text,
),
CustomField(
controller: _custom4Controller,
field: widget.invoiceItem.isTask
? CustomFieldType.task4
: CustomFieldType.product4,
onSavePressed: widget.entityViewModel.onSavePressed,
value: _custom4Controller.text,
),
DecoratedFormField(
label: localization.unitCost,
controller: _costController,
keyboardType: TextInputType.numberWithOptions(decimal: true),
onSavePressed: widget.entityViewModel.onSavePressed,
),
company.enableProductQuantity
? DecoratedFormField(
label: localization.quantity,
controller: _qtyController,
keyboardType:
TextInputType.numberWithOptions(decimal: true),
onSavePressed: widget.entityViewModel.onSavePressed,
)
: Container(),
company.enableProductDiscount
? DecoratedFormField(
label: localization.discount,
controller: _discountController,
keyboardType:
TextInputType.numberWithOptions(decimal: true),
onSavePressed: widget.entityViewModel.onSavePressed,
)
: Container(),
if (company.enableFirstItemTaxRate || _taxRate1.name.isNotEmpty)
TaxRateDropdown(
onSelected: (taxRate) {
setState(() {
_taxRate1 = taxRate;
_onChanged();
});
},
labelText: localization.tax +
(company.settings.enableInclusiveTaxes
? ' - ${localization.inclusive}'
: ''),
initialTaxName: _taxRate1.name,
initialTaxRate: _taxRate1.rate,
),
if (company.enableSecondItemTaxRate || _taxRate2.name.isNotEmpty)
TaxRateDropdown(
onSelected: (taxRate) {
setState(() {
_taxRate2 = taxRate;
_onChanged();
});
},
labelText: localization.tax +
(company.settings.enableInclusiveTaxes
? ' - ${localization.inclusive}'
: ''),
initialTaxName: _taxRate2.name,
initialTaxRate: _taxRate2.rate,
),
if (company.enableThirdItemTaxRate || _taxRate3.name.isNotEmpty)
TaxRateDropdown(
onSelected: (taxRate) {
setState(() {
_taxRate3 = taxRate;
_onChanged();
});
},
labelText: localization.tax +
(company.settings.enableInclusiveTaxes
? ' - ${localization.inclusive}'
: ''),
initialTaxName: _taxRate3.name,
initialTaxRate: _taxRate3.rate,
),
],
),
),
);
}
}
| 35.123596 | 81 | 0.622521 |
4d7c85b08abc16353a88035c13620e699e76a8f3 | 2,729 | swift | Swift | ViewControllerTransition/NavigationTransition.swift | wuwen1030/ViewControllerTransitionDemo | 13771519f3eee58cfc9520e34ba46cee57573192 | [
"MIT"
] | null | null | null | ViewControllerTransition/NavigationTransition.swift | wuwen1030/ViewControllerTransitionDemo | 13771519f3eee58cfc9520e34ba46cee57573192 | [
"MIT"
] | null | null | null | ViewControllerTransition/NavigationTransition.swift | wuwen1030/ViewControllerTransitionDemo | 13771519f3eee58cfc9520e34ba46cee57573192 | [
"MIT"
] | null | null | null | //
// NavigationTransition.swift
// ViewControllerTransition
//
// Created by Ben on 15/7/21.
// Copyright (c) 2015年 X-Team. All rights reserved.
//
import UIKit
class NavigationTransition: NSObject, UINavigationControllerDelegate {
let pushAnimator = PushAnimator()
let popAnimator = PopAnimator()
private var popInteractiveAnimator: UIPercentDrivenInteractiveTransition?
weak var navigationController: UINavigationController?
func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
if operation == UINavigationControllerOperation.Push {
return pushAnimator
} else {
return popAnimator
}
}
func navigationController(navigationController: UINavigationController, interactionControllerForAnimationController animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return animationController is PopAnimator ? popInteractiveAnimator : nil
}
func wireToNavigationController(navigationController:UINavigationController) {
self.navigationController = navigationController
let gestureRecognizer = navigationController.interactivePopGestureRecognizer
gestureRecognizer.enabled = false
let pan = UIPanGestureRecognizer(target: self, action: "handlePan:")
navigationController.view.addGestureRecognizer(pan)
}
func handlePan(gestureRecognizer:UIPanGestureRecognizer) -> Void {
let translation = gestureRecognizer.translationInView(gestureRecognizer.view!)
let width = gestureRecognizer.view!.bounds.size.width
let progress = translation.x / width
switch gestureRecognizer.state
{
case UIGestureRecognizerState.Began:
popInteractiveAnimator = UIPercentDrivenInteractiveTransition()
navigationController?.popViewControllerAnimated(true)
case UIGestureRecognizerState.Changed:
popInteractiveAnimator?.updateInteractiveTransition(progress)
case UIGestureRecognizerState.Cancelled, UIGestureRecognizerState.Ended:
if progress > 0.5
{
popInteractiveAnimator?.finishInteractiveTransition()
}
else
{
popInteractiveAnimator?.cancelInteractiveTransition()
}
popInteractiveAnimator = nil
default:
println("Stupid language")
}
}
}
| 40.132353 | 281 | 0.717112 |
9c04b167047f407090fbad313f8d256d7f205462 | 411 | ts | TypeScript | packages/krowdy-ui-views/src/SelectInfo/SelectInfo.d.ts | ghondar/krowdy-ghondar | 662a3f7e553345cb63bad06f049732aa286a85b8 | [
"MIT"
] | 10 | 2019-11-25T21:02:39.000Z | 2020-02-13T05:10:26.000Z | packages/krowdy-ui-views/src/SelectInfo/SelectInfo.d.ts | ghondar/krowdy-ghondar | 662a3f7e553345cb63bad06f049732aa286a85b8 | [
"MIT"
] | 15 | 2020-04-17T00:26:43.000Z | 2022-02-26T19:48:46.000Z | packages/krowdy-ui-views/src/SelectInfo/SelectInfo.d.ts | ghondar/krowdy-ghondar | 662a3f7e553345cb63bad06f049732aa286a85b8 | [
"MIT"
] | 1 | 2020-03-05T21:23:18.000Z | 2020-03-05T21:23:18.000Z | export type SelectInfoProps = {
disabled?: boolean;
icon?: React.ReactNode;
rightIcon?: React.ReactNode;
src?: string;
subtitle?: string;
title?: string;
width?: number;
classes?: {
color?: string;
popper?: string;
primary?: string;
secondary?: string;
};
clickAndClose?: boolean;
}
declare const SelectInfo: React.ComponentType<SelectInfoProps>;
export default SelectInfo; | 20.55 | 63 | 0.686131 |
3d17baecd375d596f1da88aaa6e0932c1e753346 | 6,883 | go | Go | src/startupscriptgenerator/src/node/scriptgenerator_test.go | cormacpayne/Oryx | 7528f892db093e4f49a8d6586e0a41b45381673a | [
"MIT"
] | null | null | null | src/startupscriptgenerator/src/node/scriptgenerator_test.go | cormacpayne/Oryx | 7528f892db093e4f49a8d6586e0a41b45381673a | [
"MIT"
] | null | null | null | src/startupscriptgenerator/src/node/scriptgenerator_test.go | cormacpayne/Oryx | 7528f892db093e4f49a8d6586e0a41b45381673a | [
"MIT"
] | 1 | 2020-07-30T12:52:25.000Z | 2020-07-30T12:52:25.000Z | // --------------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
// --------------------------------------------------------------------------------------------
package main
import (
"fmt"
)
func ExampleNodeStartupScriptGenerator_getPackageJsonStartCommand_subDir() {
gen := &NodeStartupScriptGenerator{
SourcePath: "/a/b",
}
packageJson := &packageJson{
Scripts: &packageJsonScripts{
Start: "node server.js",
},
}
command := gen.getPackageJsonStartCommand(packageJson, "/a/b/c/package.json")
fmt.Println(command)
// Output:
// npm --prefix=/a/b/c start
}
func ExampleNodeStartupScriptGenerator_getPackageJsonStartCommand_rootDir() {
gen := &NodeStartupScriptGenerator{
SourcePath: "/a/b",
}
packageJson := &packageJson{
Scripts: &packageJsonScripts{
Start: "node server.js",
},
}
command := gen.getPackageJsonStartCommand(packageJson, "/a/b/package.json")
fmt.Println(command)
// Output:
// npm start
}
func ExampleNodeStartupScriptGenerator_getPackageJsonStartCommand_subDirDebug() {
gen := &NodeStartupScriptGenerator{
SourcePath: "/a/b",
RemoteDebugging: true,
}
packageJson := &packageJson{
Scripts: &packageJsonScripts{
Start: "node server.js",
},
}
command := gen.getPackageJsonStartCommand(packageJson, "/a/b/c/package.json")
fmt.Println(command)
// Output:
// export PATH=/opt/node-wrapper/:$PATH
// export ORYX_NODE_INSPECT_PARAM="--inspect=0.0.0.0"
// npm --prefix=/a/b/c start --scripts-prepend-node-path false
}
func ExampleNodeStartupScriptGenerator_getPackageJsonStartCommand_rootDirDebug() {
gen := &NodeStartupScriptGenerator{
SourcePath: "/a/b",
RemoteDebugging: true,
}
packageJson := &packageJson{
Scripts: &packageJsonScripts{
Start: "node server.js",
},
}
command := gen.getPackageJsonStartCommand(packageJson, "/a/b/package.json")
fmt.Println(command)
// Output:
// export PATH=/opt/node-wrapper/:$PATH
// export ORYX_NODE_INSPECT_PARAM="--inspect=0.0.0.0"
// npm start --scripts-prepend-node-path false
}
func ExampleNodeStartupScriptGenerator_getUserProvidedJsFileCommand_sameDir() {
gen := &NodeStartupScriptGenerator{
SourcePath: "/a/b",
}
command := gen.getUserProvidedJsFileCommand("/a/b/server.js")
fmt.Println(command)
// Output:
// node server.js
}
func ExampleNodeStartupScriptGenerator_getUserProvidedJsFileCommand_subDir() {
gen := &NodeStartupScriptGenerator{
SourcePath: "/a/b",
}
command := gen.getUserProvidedJsFileCommand("/a/b/c/server.js")
fmt.Println(command)
// Output:
// node c/server.js
}
func ExampleNodeStartupScriptGenerator_getPackageJsonMainCommand_rootDir() {
gen := &NodeStartupScriptGenerator{
SourcePath: "/a/b",
}
packageJson := &packageJson{
Main: "server.js",
}
command := gen.getPackageJsonMainCommand(packageJson, "/a/b/package.json")
fmt.Println(command)
// Output:
// node server.js
}
func ExampleNodeStartupScriptGenerator_getPackageJsonMainCommand_subDir() {
gen := &NodeStartupScriptGenerator{
SourcePath: "/a/b",
}
packageJson := &packageJson{
Main: "server.js",
}
command := gen.getPackageJsonMainCommand(packageJson, "/a/b/c/package.json")
fmt.Println(command)
// Output:
// node c/server.js
}
func ExampleNodeStartupScriptGenerator_getStartupCommandFromJsFile_simpleNodeCommand() {
gen := &NodeStartupScriptGenerator{}
command := gen.getStartupCommandFromJsFile("a/b/c.js")
fmt.Println(command)
// Output:
// node a/b/c.js
}
func ExampleNodeStartupScriptGenerator_getStartupCommandFromJsFile_customServerPassedIn() {
gen := &NodeStartupScriptGenerator{
UsePm2: true,
}
command := gen.getStartupCommandFromJsFile("a/b/c.js")
fmt.Println(command)
// Output:
// pm2 start --no-daemon a/b/c.js
}
func ExampleNodeStartupScriptGenerator_getStartupCommandFromJsFile_debuggingFlagShouldBeIncluded() {
gen := &NodeStartupScriptGenerator{
RemoteDebugging: true,
RemoteDebuggingBreakBeforeStart: false,
}
command := gen.getStartupCommandFromJsFile("a/b/c.js")
fmt.Println(command)
// Output:
// node --inspect=0.0.0.0 a/b/c.js
}
func ExampleNodeStartupScriptGenerator_getStartupCommandFromJsFile_debuggingbrkFlagShouldBeIncluded() {
gen := &NodeStartupScriptGenerator{
RemoteDebugging: true,
RemoteDebuggingBreakBeforeStart: true,
}
command := gen.getStartupCommandFromJsFile("a/b/c.js")
fmt.Println(command)
// Output:
// node --inspect-brk=0.0.0.0 a/b/c.js
}
func ExampleNodeStartupScriptGenerator_getStartupCommandFromJsFile_debuggingWithHostAndPort() {
gen := &NodeStartupScriptGenerator{
RemoteDebugging: true,
RemoteDebuggingPort: "1234",
}
command := gen.getStartupCommandFromJsFile("a/b/c.js")
fmt.Println(command)
// Output:
// node --inspect=0.0.0.0:1234 a/b/c.js
}
func ExampleNodeStartupScriptGenerator_getStartupCommandFromJsFile_debuggingbrkWithHostButNoPort() {
gen := &NodeStartupScriptGenerator{
RemoteDebugging: true,
RemoteDebuggingBreakBeforeStart: true,
}
command := gen.getStartupCommandFromJsFile("a/b/c.js")
fmt.Println(command)
// Output:
// node --inspect-brk=0.0.0.0 a/b/c.js
}
func ExampleNodeStartupScriptGenerator_getStartupCommandFromJsFile_debuggingbrkWithHostAndPort() {
gen := &NodeStartupScriptGenerator{
RemoteDebugging: true,
RemoteDebuggingBreakBeforeStart: true,
RemoteDebuggingPort: "1234",
}
command := gen.getStartupCommandFromJsFile("a/b/c.js")
fmt.Println(command)
// Output:
// node --inspect-brk=0.0.0.0:1234 a/b/c.js
}
func ExampleNodeStartupScriptGenerator_getStartupCommandFromJsFile_debuggingLegacyNodeVersion() {
gen := &NodeStartupScriptGenerator{
RemoteDebugging: true,
RemoteDebuggingBreakBeforeStart: false,
UseLegacyDebugger: true,
}
command := gen.getStartupCommandFromJsFile("a/b/c.js")
fmt.Println(command)
// Output:
// node --debug=0.0.0.0 a/b/c.js
}
func ExampleNodeStartupScriptGenerator_getStartupCommandFromJsFile_debuggingbrkLegacyNodeVersion() {
gen := &NodeStartupScriptGenerator{
RemoteDebugging: true,
RemoteDebuggingBreakBeforeStart: true,
UseLegacyDebugger: true,
}
command := gen.getStartupCommandFromJsFile("a/b/c.js")
fmt.Println(command)
// Output:
// node --debug-brk=0.0.0.0 a/b/c.js
}
func ExampleNodeStartupScriptGenerator_getStartupCommandFromJsFile_debuggingbrkWithHostAndPortLegacyNodeVersion() {
gen := &NodeStartupScriptGenerator{
RemoteDebugging: true,
RemoteDebuggingBreakBeforeStart: true,
RemoteDebuggingPort: "1234",
UseLegacyDebugger: true,
}
command := gen.getStartupCommandFromJsFile("a/b/c.js")
fmt.Println(command)
// Output:
// node --debug-brk=0.0.0.0:1234 a/b/c.js
}
| 29.41453 | 115 | 0.715967 |
f9c94e7e74b9d0549862947d618fb88735eaf234 | 9,901 | go | Go | internal/tool/testing/mock_internalgitaly/internalgitaly.go | abaer123/gitlab-agent | 71c94d781ae2a7ae2851bb946c37fe01b1ed3da0 | [
"MIT"
] | null | null | null | internal/tool/testing/mock_internalgitaly/internalgitaly.go | abaer123/gitlab-agent | 71c94d781ae2a7ae2851bb946c37fe01b1ed3da0 | [
"MIT"
] | null | null | null | internal/tool/testing/mock_internalgitaly/internalgitaly.go | abaer123/gitlab-agent | 71c94d781ae2a7ae2851bb946c37fe01b1ed3da0 | [
"MIT"
] | null | null | null | // Code generated by MockGen. DO NOT EDIT.
// Source: gitlab.com/gitlab-org/cluster-integration/gitlab-agent/internal/gitaly (interfaces: PoolInterface,FetchVisitor,PathEntryVisitor,PathFetcherInterface,PollerInterface)
// Package mock_internalgitaly is a generated GoMock package.
package mock_internalgitaly
import (
context "context"
reflect "reflect"
gomock "github.com/golang/mock/gomock"
api "gitlab.com/gitlab-org/cluster-integration/gitlab-agent/internal/api"
gitaly "gitlab.com/gitlab-org/cluster-integration/gitlab-agent/internal/gitaly"
gitalypb "gitlab.com/gitlab-org/gitaly/proto/go/gitalypb"
)
// MockPoolInterface is a mock of PoolInterface interface.
type MockPoolInterface struct {
ctrl *gomock.Controller
recorder *MockPoolInterfaceMockRecorder
}
// MockPoolInterfaceMockRecorder is the mock recorder for MockPoolInterface.
type MockPoolInterfaceMockRecorder struct {
mock *MockPoolInterface
}
// NewMockPoolInterface creates a new mock instance.
func NewMockPoolInterface(ctrl *gomock.Controller) *MockPoolInterface {
mock := &MockPoolInterface{ctrl: ctrl}
mock.recorder = &MockPoolInterfaceMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockPoolInterface) EXPECT() *MockPoolInterfaceMockRecorder {
return m.recorder
}
// PathFetcher mocks base method.
func (m *MockPoolInterface) PathFetcher(arg0 context.Context, arg1 *api.GitalyInfo) (gitaly.PathFetcherInterface, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "PathFetcher", arg0, arg1)
ret0, _ := ret[0].(gitaly.PathFetcherInterface)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// PathFetcher indicates an expected call of PathFetcher.
func (mr *MockPoolInterfaceMockRecorder) PathFetcher(arg0, arg1 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PathFetcher", reflect.TypeOf((*MockPoolInterface)(nil).PathFetcher), arg0, arg1)
}
// Poller mocks base method.
func (m *MockPoolInterface) Poller(arg0 context.Context, arg1 *api.GitalyInfo) (gitaly.PollerInterface, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Poller", arg0, arg1)
ret0, _ := ret[0].(gitaly.PollerInterface)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Poller indicates an expected call of Poller.
func (mr *MockPoolInterfaceMockRecorder) Poller(arg0, arg1 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Poller", reflect.TypeOf((*MockPoolInterface)(nil).Poller), arg0, arg1)
}
// MockFetchVisitor is a mock of FetchVisitor interface.
type MockFetchVisitor struct {
ctrl *gomock.Controller
recorder *MockFetchVisitorMockRecorder
}
// MockFetchVisitorMockRecorder is the mock recorder for MockFetchVisitor.
type MockFetchVisitorMockRecorder struct {
mock *MockFetchVisitor
}
// NewMockFetchVisitor creates a new mock instance.
func NewMockFetchVisitor(ctrl *gomock.Controller) *MockFetchVisitor {
mock := &MockFetchVisitor{ctrl: ctrl}
mock.recorder = &MockFetchVisitorMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockFetchVisitor) EXPECT() *MockFetchVisitorMockRecorder {
return m.recorder
}
// Entry mocks base method.
func (m *MockFetchVisitor) Entry(arg0 *gitalypb.TreeEntry) (bool, int64, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Entry", arg0)
ret0, _ := ret[0].(bool)
ret1, _ := ret[1].(int64)
ret2, _ := ret[2].(error)
return ret0, ret1, ret2
}
// Entry indicates an expected call of Entry.
func (mr *MockFetchVisitorMockRecorder) Entry(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Entry", reflect.TypeOf((*MockFetchVisitor)(nil).Entry), arg0)
}
// StreamChunk mocks base method.
func (m *MockFetchVisitor) StreamChunk(arg0, arg1 []byte) (bool, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "StreamChunk", arg0, arg1)
ret0, _ := ret[0].(bool)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// StreamChunk indicates an expected call of StreamChunk.
func (mr *MockFetchVisitorMockRecorder) StreamChunk(arg0, arg1 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StreamChunk", reflect.TypeOf((*MockFetchVisitor)(nil).StreamChunk), arg0, arg1)
}
// MockPathEntryVisitor is a mock of PathEntryVisitor interface.
type MockPathEntryVisitor struct {
ctrl *gomock.Controller
recorder *MockPathEntryVisitorMockRecorder
}
// MockPathEntryVisitorMockRecorder is the mock recorder for MockPathEntryVisitor.
type MockPathEntryVisitorMockRecorder struct {
mock *MockPathEntryVisitor
}
// NewMockPathEntryVisitor creates a new mock instance.
func NewMockPathEntryVisitor(ctrl *gomock.Controller) *MockPathEntryVisitor {
mock := &MockPathEntryVisitor{ctrl: ctrl}
mock.recorder = &MockPathEntryVisitorMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockPathEntryVisitor) EXPECT() *MockPathEntryVisitorMockRecorder {
return m.recorder
}
// Entry mocks base method.
func (m *MockPathEntryVisitor) Entry(arg0 *gitalypb.TreeEntry) (bool, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Entry", arg0)
ret0, _ := ret[0].(bool)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Entry indicates an expected call of Entry.
func (mr *MockPathEntryVisitorMockRecorder) Entry(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Entry", reflect.TypeOf((*MockPathEntryVisitor)(nil).Entry), arg0)
}
// MockPathFetcherInterface is a mock of PathFetcherInterface interface.
type MockPathFetcherInterface struct {
ctrl *gomock.Controller
recorder *MockPathFetcherInterfaceMockRecorder
}
// MockPathFetcherInterfaceMockRecorder is the mock recorder for MockPathFetcherInterface.
type MockPathFetcherInterfaceMockRecorder struct {
mock *MockPathFetcherInterface
}
// NewMockPathFetcherInterface creates a new mock instance.
func NewMockPathFetcherInterface(ctrl *gomock.Controller) *MockPathFetcherInterface {
mock := &MockPathFetcherInterface{ctrl: ctrl}
mock.recorder = &MockPathFetcherInterfaceMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockPathFetcherInterface) EXPECT() *MockPathFetcherInterfaceMockRecorder {
return m.recorder
}
// FetchFile mocks base method.
func (m *MockPathFetcherInterface) FetchFile(arg0 context.Context, arg1 *gitalypb.Repository, arg2, arg3 []byte, arg4 int64) ([]byte, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "FetchFile", arg0, arg1, arg2, arg3, arg4)
ret0, _ := ret[0].([]byte)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// FetchFile indicates an expected call of FetchFile.
func (mr *MockPathFetcherInterfaceMockRecorder) FetchFile(arg0, arg1, arg2, arg3, arg4 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FetchFile", reflect.TypeOf((*MockPathFetcherInterface)(nil).FetchFile), arg0, arg1, arg2, arg3, arg4)
}
// StreamFile mocks base method.
func (m *MockPathFetcherInterface) StreamFile(arg0 context.Context, arg1 *gitalypb.Repository, arg2, arg3 []byte, arg4 int64, arg5 gitaly.FileVisitor) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "StreamFile", arg0, arg1, arg2, arg3, arg4, arg5)
ret0, _ := ret[0].(error)
return ret0
}
// StreamFile indicates an expected call of StreamFile.
func (mr *MockPathFetcherInterfaceMockRecorder) StreamFile(arg0, arg1, arg2, arg3, arg4, arg5 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StreamFile", reflect.TypeOf((*MockPathFetcherInterface)(nil).StreamFile), arg0, arg1, arg2, arg3, arg4, arg5)
}
// Visit mocks base method.
func (m *MockPathFetcherInterface) Visit(arg0 context.Context, arg1 *gitalypb.Repository, arg2, arg3 []byte, arg4 bool, arg5 gitaly.FetchVisitor) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Visit", arg0, arg1, arg2, arg3, arg4, arg5)
ret0, _ := ret[0].(error)
return ret0
}
// Visit indicates an expected call of Visit.
func (mr *MockPathFetcherInterfaceMockRecorder) Visit(arg0, arg1, arg2, arg3, arg4, arg5 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Visit", reflect.TypeOf((*MockPathFetcherInterface)(nil).Visit), arg0, arg1, arg2, arg3, arg4, arg5)
}
// MockPollerInterface is a mock of PollerInterface interface.
type MockPollerInterface struct {
ctrl *gomock.Controller
recorder *MockPollerInterfaceMockRecorder
}
// MockPollerInterfaceMockRecorder is the mock recorder for MockPollerInterface.
type MockPollerInterfaceMockRecorder struct {
mock *MockPollerInterface
}
// NewMockPollerInterface creates a new mock instance.
func NewMockPollerInterface(ctrl *gomock.Controller) *MockPollerInterface {
mock := &MockPollerInterface{ctrl: ctrl}
mock.recorder = &MockPollerInterfaceMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockPollerInterface) EXPECT() *MockPollerInterfaceMockRecorder {
return m.recorder
}
// Poll mocks base method.
func (m *MockPollerInterface) Poll(arg0 context.Context, arg1 *gitalypb.Repository, arg2, arg3 string) (*gitaly.PollInfo, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Poll", arg0, arg1, arg2, arg3)
ret0, _ := ret[0].(*gitaly.PollInfo)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Poll indicates an expected call of Poll.
func (mr *MockPollerInterfaceMockRecorder) Poll(arg0, arg1, arg2, arg3 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Poll", reflect.TypeOf((*MockPollerInterface)(nil).Poll), arg0, arg1, arg2, arg3)
}
| 37.362264 | 176 | 0.764973 |
c7ae7690efbd4618f721fb391483edf29afeb0dd | 17,861 | py | Python | survos2/server/unet2d/unet2d.py | DiamondLightSource/SuRVoS2 | 42bacfb6a5cc267f38ca1337e51a443eae1a9d2b | [
"MIT"
] | 4 | 2017-10-10T14:47:16.000Z | 2022-01-14T05:57:50.000Z | survos2/server/unet2d/unet2d.py | DiamondLightSource/SuRVoS2 | 42bacfb6a5cc267f38ca1337e51a443eae1a9d2b | [
"MIT"
] | 1 | 2022-01-11T21:11:12.000Z | 2022-01-12T08:22:34.000Z | survos2/server/unet2d/unet2d.py | DiamondLightSource/SuRVoS2 | 42bacfb6a5cc267f38ca1337e51a443eae1a9d2b | [
"MIT"
] | 2 | 2018-03-06T06:31:29.000Z | 2019-03-04T03:33:18.000Z | # -*- coding: utf-8 -*-
"""Classes for 2d U-net training and prediction.
"""
import json
from loguru import logger
import os
import sys
import warnings
from functools import partial
from pathlib import Path
from zipfile import ZipFile
import numpy as np
#from pytorch3dunet.unet3d.losses import GeneralizedDiceLoss
import torch
import torch.nn.functional as F
from fastai.callbacks import CSVLogger, SaveModelCallback
from fastai.utils.mem import gpu_mem_get_free_no_cache
from fastai.vision import (SegmentationItemList, dice, get_transforms,
imagenet_stats, lr_find, models, open_image,
unet_learner, crop_pad, Image, pil2tensor)
import matplotlib as mpl
mpl.use('Agg')
from matplotlib import pyplot as plt
from skimage import exposure, img_as_ubyte, io, img_as_float
from tqdm import tqdm
warnings.filterwarnings("ignore", category=UserWarning)
class Unet2dTrainer:
"""Class that takes in 2d images and corresponding segmentations and
trains a 2dUnet with a pretrained ResNet34 encoder.
Args:
data_im_out_dir (pathlib.Path): Path to directory containing image slices.
seg_im_out_dir (pathlib.Path): Path to to directory containing label slices.
codes (list of str): Names of the label classes, must be the same length as
number of classes.
im_size (int): Size of images to input to network.
weight_decay (float): Value of the weight decay regularisation term to use.
"""
def __init__(self, data_im_out_dir, seg_im_out_dir, codes, use_gdl=False):
self.data_dir = data_im_out_dir
self.label_dir = seg_im_out_dir
self.codes = codes
self.multilabel = len(codes) > 2
self.image_size = 256
# Params for learning rate finder
self.lr_find_lr_diff = 15
self.lr_find_loss_threshold = 0.05
self.lr_find_adjust_value = 1
self.gdl = None
# if use_gdl:
# self.gdl = GeneralizedDiceLoss(sigmoid_normalization=False)
# Params for model training
self.weight_decay = float(1e-2)
self.pct_lr_inc = 0.4
# Set up model ready for training
self.batch_size = self.get_batchsize()
self.create_training_dataset()
self.setup_metrics_and_loss()
self.create_model()
def setup_metrics_and_loss(self):
"""Sets instance attributes for loss function and evaluation metrics
according to whether binary or multilabel segmentation is being
performed.
"""
if self.multilabel:
logger.info("Setting up for multilabel segmentation since there are "
f"{len(self.codes)} classes")
self.metrics = self.accuracy
self.monitor = 'accuracy'
self.loss_func = None
else:
logger.info("Setting up for binary segmentation since there are "
f"{len(self.codes)} classes")
self.metrics = [partial(dice, iou=True)]
self.monitor = 'dice'
self.loss_func = self.bce_loss
# If Generalised dice loss is selected, overwrite loss function
if self.gdl:
logger.info("Using generalised dice loss.")
self.loss_func = self.generalised_dice_loss
def create_training_dataset(self):
"""Creates a fastai segmentation dataset and stores it as an instance
attribute.
"""
logger.info("Creating training dataset from saved images.")
src = (SegmentationItemList.from_folder(self.data_dir)
.split_by_rand_pct()
.label_from_func(self.get_label_name, classes=list(self.codes.keys())))
self.data = (src.transform(get_transforms(), size=self.image_size, tfm_y=True)
.databunch(bs=self.batch_size)
.normalize(imagenet_stats))
def create_model(self):
"""Creates a deep learning model linked to the dataset and stores it as
an instance attribute.
"""
logger.info("Creating 2d U-net model for training.")
self.model = unet_learner(self.data, models.resnet34, metrics=self.metrics,
wd=self.weight_decay, loss_func=self.loss_func,
callback_fns=[partial(CSVLogger,
filename='unet_training_history',
append=True),
partial(SaveModelCallback,
monitor=self.monitor, mode='max',
name="best_unet_model")])
def train_model(self, num_cyc_frozen=10, num_cyc_unfrozen=5):
"""Performs transfer learning training of model for a number of cycles
with parameters frozen or unfrozen and a learning rate that is determined automatically.
"""
if num_cyc_frozen > 0:
logger.info("Finding learning rate for frozen Unet model.")
lr_to_use = self.find_appropriate_lr()
logger.info(
f"Training frozen Unet for {num_cyc_frozen} cycles with learning rate of {lr_to_use}.")
self.model.fit_one_cycle(num_cyc_frozen, slice(
lr_to_use/50, lr_to_use), pct_start=self.pct_lr_inc)
if num_cyc_unfrozen > 0:
self.model.unfreeze()
logger.info("Finding learning rate for unfrozen Unet model.")
lr_to_use = self.find_appropriate_lr()
logger.info(
f"Training unfrozen Unet for {num_cyc_unfrozen} cycles with learning rate of {lr_to_use}.")
self.model.fit_one_cycle(num_cyc_unfrozen, slice(
lr_to_use/50, lr_to_use), pct_start=self.pct_lr_inc)
def save_model_weights(self, model_filepath):
"""Saves the model weights to a specified location.
Args:
model_filepath (pathlib.Path): Full path to location to save model
weights excluding file extension.
"""
self.model.save(model_filepath)
json_path = model_filepath.parent/f"{model_filepath.name}_codes.json"
zip_path = model_filepath.with_suffix('.zip')
logger.info(
f"Zipping the model weights to: {zip_path}")
with open(json_path, 'w') as jf:
json.dump(self.codes, jf)
with ZipFile(zip_path, mode='w') as zf:
zf.write(json_path, arcname=json_path.name)
zf.write(model_filepath.with_suffix('.pth'),
arcname=model_filepath.with_suffix('.pth').name)
os.remove(json_path)
os.remove(model_filepath.with_suffix('.pth'))
def predict_single_slice(self, data):
"""Takes in a 2d data array and returns the max and argmax of the predicted probabilities.
Args:
data (numpy.array): The 2d data array to be fed into the U-net.
Returns:
torch.tensor: A 3d torch tensor containing a 2d array with max probabilities
and a 2d array with argmax indices.
"""
data = img_as_float(data)
data = Image(pil2tensor(data, dtype=np.float32))
self.fix_odd_sides(data)
prediction = self.model.predict(data)[2]
return torch.max(prediction, dim=0)
def output_prediction_figure(self, model_path):
"""Saves a figure containing image slice data for three random images
fromthe validation dataset along with the corresponding ground truth
label image and corresponding prediction output from the model attached
to this class instance. The image is saved to the same directory as the
model weights.
Args:
model_path (pathlib.Path): Full path to the model weights file,
this is used to get the directory and name of the model not to
load and predict.
"""
# Remove the restriction on the model prediction size
self.model.data.single_ds.tfmargs['size'] = None
filename_list = self.data.valid_ds.items[:3]
img_list = []
pred_list = []
gt_list = []
for fn in filename_list:
img_list.append(open_image(fn))
gt_list.append(io.imread(self.get_label_name(fn)))
for img in img_list:
self.fix_odd_sides(img)
pred_list.append(img_as_ubyte(self.model.predict(img)[1][0]))
# Horrible conversion from Fastai image to unit8 data array
img_list = [img_as_ubyte(exposure.rescale_intensity(
x.data.numpy()[0, :, :])) for x in img_list]
# Create the plot
fig = plt.figure(figsize=(12, 12))
columns = 3
rows = 3
j = 0
for i in range(columns*rows)[::3]:
img = img_list[j]
gt = gt_list[j]
pred = pred_list[j]
col1 = fig.add_subplot(rows, columns, i + 1)
plt.imshow(img, cmap='gray')
col2 = fig.add_subplot(rows, columns, i + 2)
plt.imshow(gt, cmap='gray')
col3 = fig.add_subplot(rows, columns, i + 3)
plt.imshow(pred, cmap='gray')
j += 1
if i == 0:
col1.title.set_text('Data')
col2.title.set_text('Ground Truth')
col3.title.set_text('Prediction')
plt.suptitle(f"Predictions for {model_path.name}", fontsize=16)
plt_out_pth = model_path.parent/f'{model_path.stem}_prediction_image.png'
logger.info(f"Saving example image predictions to {plt_out_pth}")
plt.savefig(plt_out_pth, dpi=300)
def return_fast_prediction_volume(self, data_volume):
"""Predicts slices in a volume and returns segmented volume.
"""
logger.info("Predicting output for training volume.")
zdim, ydim, xdim = data_volume.shape
if ydim%2 != 0:
ydim += 1
if xdim%2 != 0:
xdim += 1
vol_out = np.zeros((zdim, ydim, xdim))
for i, z_slice in enumerate(data_volume):
vol_out[i] = self.predict_single_slice(z_slice)[1]
return vol_out
def find_appropriate_lr(self):
"""Function taken from https://forums.fast.ai/t/automated-learning-rate-suggester/44199
which attempts to automatically find a learning rate from the fastai lr_find function.
Returns:
float: A value for a sensible learning rate to use for training.
"""
lr_find(self.model)
#Get loss values and their corresponding gradients, and get lr values
losses = np.array(self.model.recorder.losses)
assert(self.lr_find_lr_diff < len(losses))
loss_grad = np.gradient(losses)
learning_rates = self.model.recorder.lrs
#Search for index in gradients where loss is lowest before the loss spike
#Initialize right and left idx using the lr_diff as a spacing unit
#Set the local min lr as -1 to signify if threshold is too low
local_min_lr = 0.001 # Add as default value to fix bug
r_idx = -1
l_idx = r_idx - self.lr_find_lr_diff
while (l_idx >= -len(losses)) and (abs(loss_grad[r_idx] - loss_grad[l_idx])
> self.lr_find_loss_threshold):
local_min_lr = learning_rates[l_idx]
r_idx -= 1
l_idx -= 1
lr_to_use = local_min_lr * self.lr_find_adjust_value
return lr_to_use
def get_batchsize(self):
"""Provides an appropriate batch size based upon free GPU memory.
Returns:
int: A batch size for model training.
"""
gpu_free_mem = gpu_mem_get_free_no_cache()
if gpu_free_mem > 8200:
batch_size = 8
else:
batch_size = 4
logger.info(f"Using batch size of {batch_size}, have {gpu_free_mem} MB" \
" of GPU RAM free.")
return batch_size
def fix_odd_sides(self, example_image):
"""Replaces an an odd image dimension with an even dimension by padding.
Taken from https://forums.fast.ai/t/segmentation-mask-prediction-on-different-input-image-sizes/44389/7.
Args:
example_image (fastai.vision.Image): The image to be fixed.
"""
if (list(example_image.size)[0] % 2) != 0:
example_image = crop_pad(example_image,
size=(list(example_image.size)[
0]+1, list(example_image.size)[1]),
padding_mode='reflection')
if (list(example_image.size)[1] % 2) != 0:
example_image = crop_pad(example_image,
size=(list(example_image.size)[0], list(
example_image.size)[1] + 1),
padding_mode='reflection')
def bce_loss(self, logits, labels):
"""Function to calulate Binary Cross Entropy loss from predictions.
Args:
logits (torch.Tensor): output from network.
labels (torch.Tensor): ground truth label values.
Returns:
torch.Tensor: The BCE loss calulated on the predictions.
"""
logits = logits[:, 1, :, :].float()
labels = labels.squeeze(1).float()
return F.binary_cross_entropy_with_logits(logits, labels)
def generalised_dice_loss(self, logits, labels):
labels = F.one_hot(torch.squeeze(labels), len(self.codes))
labels = labels.permute((0, 3, 1, 2))
return self.gdl(logits, labels)
def accuracy(self, input, target):
"""Calculates and accuracy metric between predictions and ground truth
labels.
Args:
input (torch.Tensor): The predictions.
target (torchTensor): The desired output (ground truth).
Returns:
[type]: [description]
"""
target = target.squeeze(1)
return (input.argmax(dim=1) == target).float().mean()
def get_label_name(self, img_fname):
"""Converts a path fo an image slice to a path for corresponding label
slice.
Args:
img_fname (pathlib.Path): Path to an image slice file.
Returns:
pathlib.Path: Path to the corresponding segmentation label slice file.
"""
return self.label_dir/f'{"seg" + img_fname.stem[4:]}{img_fname.suffix}'
class Unet2dPredictor:
"""Class that can either load in fastai 2d Unet model weights or take an
instance of a trained fastai Unet learner. It can then predict 2d
segmentations of image slices provided and save them to disk.
"""
def __init__(self, root_dir, model_path=None):
self.dummy_fns = ['data_z_stack_0.png', 'seg_z_stack_0.png']
self.dummy_dir = root_dir/'dummy_imgs'
self.root_dir = root_dir
def create_dummy_files(self):
logger.info(f"Creating dummy images in {self.dummy_dir}.")
os.makedirs(self.dummy_dir, exist_ok=True)
for fn in self.dummy_fns:
dummy_im = np.random.randint(256, size=(256, 256))
io.imsave(self.dummy_dir/fn, img_as_ubyte(dummy_im))
def create_dummy_dataset(self):
"""Creates a fastai segmentation dataset and stores it as an instance
attribute.
"""
logger.info("Creating training dataset from dummy images.")
src = (SegmentationItemList.from_folder(self.dummy_dir)
.split_by_rand_pct()
.label_from_func(self.get_label_name, classes=self.codes))
self.data = (src.transform(get_transforms(), size=256, tfm_y=True)
.databunch()
.normalize(imagenet_stats))
def get_label_name(self, img_fname):
"""Converts a path fo an image slice to a path for corresponding label
slice.
Args:
img_fname (pathlib.Path): Path to an image slice file.
Returns:
pathlib.Path: Path to the corresponding segmentation label slice file.
"""
return self.dummy_dir/f'{"seg" + img_fname.stem[4:]}{img_fname.suffix}'
def create_model_from_zip(self, weights_fn):
"""Creates a deep learning model linked to the dataset and stores it as
an instance attribute. Returns labels saved with model (dict or list).
"""
weights_fn = weights_fn.resolve()
logger.info(f"Unzipping the model weights and label classes from {weights_fn}")
output_dir = self.root_dir/"extracted_model_files"
output_dir.mkdir(exist_ok=True)
with ZipFile(weights_fn, mode='r') as zf:
zf.extractall(output_dir)
# Load in the label classes from the json file
with open(output_dir/f"{weights_fn.stem}_codes.json") as jf:
codes = json.load(jf)
# Instance variable should always be a list
if isinstance(codes, dict):
logger.info("Converting label dictionary into list.")
self.codes = [f"label_val_{i}" for i in codes]
else:
self.codes = codes
# Have to create dummy files and datset before loading in model weights
self.create_dummy_files()
self.create_dummy_dataset()
logger.info("Creating 2d U-net model for prediction.")
self.model = unet_learner(
self.data, models.resnet34, model_dir=output_dir)
logger.info("Loading in the saved weights.")
self.model.load(weights_fn.stem)
# Remove the restriction on the model prediction size
self.model.data.single_ds.tfmargs['size'] = None
return codes
def get_model_from_trainer(self, trainer):
self.model = trainer.model
| 41.82904 | 112 | 0.615979 |
2f171cfbda93ea56b8be48268214dfd38add4d31 | 1,172 | php | PHP | app/Http/Controllers/ChecksController.php | nmfzone/car-rent-system | 8edd0fee38dd27119bc2ecab644d1c20413077be | [
"MIT"
] | 2 | 2017-05-17T03:13:26.000Z | 2017-05-29T05:04:53.000Z | app/Http/Controllers/ChecksController.php | nmfzone/car-rent-system | 8edd0fee38dd27119bc2ecab644d1c20413077be | [
"MIT"
] | 1 | 2021-01-04T22:58:52.000Z | 2021-01-04T22:58:52.000Z | app/Http/Controllers/ChecksController.php | nmfzone/car-rent-system | 8edd0fee38dd27119bc2ecab644d1c20413077be | [
"MIT"
] | 1 | 2020-04-26T13:20:49.000Z | 2020-04-26T13:20:49.000Z | <?php
namespace App\Http\Controllers;
use App\Car;
use Carbon\Carbon;
use Illuminate\Http\Request;
class ChecksController extends Controller
{
/**
* Create a new controller instance.
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$cars = Car::with([
'carType',
'bookings',
]);
$displayResult = false;
if (! is_null($request->date_range)) {
$dates = explode(' - ', $request->date_range);
try {
$cars = $cars->freeOn(
Carbon::createFromFormat('d/m/Y H:i', $dates[0]),
Carbon::createFromFormat('d/m/Y H:i', $dates[1])
);
$displayResult = true;
} catch (\Exception $e) {
//
}
}
$cars = $cars->paginate(10);
return view('checks.index', compact('cars', 'displayResult'));
}
}
| 22.113208 | 70 | 0.5 |
38de07fd44bfd58544b68aaaa658b1ce9da031c2 | 1,772 | h | C | usr.sbin/amd/include/uwait.h | weiss/original-bsd | b44636d7febc9dcf553118bd320571864188351d | [
"Unlicense"
] | 114 | 2015-01-18T22:55:52.000Z | 2022-02-17T10:45:02.000Z | usr.sbin/amd/include/uwait.h | JamesLinus/original-bsd | b44636d7febc9dcf553118bd320571864188351d | [
"Unlicense"
] | null | null | null | usr.sbin/amd/include/uwait.h | JamesLinus/original-bsd | b44636d7febc9dcf553118bd320571864188351d | [
"Unlicense"
] | 29 | 2015-11-03T22:05:22.000Z | 2022-02-08T15:36:37.000Z | /*
* Copyright (c) 1989 Jan-Simon Pendry
* Copyright (c) 1989 Imperial College of Science, Technology & Medicine
* Copyright (c) 1989, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Jan-Simon Pendry at Imperial College, London.
*
* %sccs.include.redist.c%
*
* @(#)uwait.h 8.1 (Berkeley) 06/06/93
*
* $Id: uwait.h,v 5.2.2.1 1992/02/09 15:10:01 jsp beta $
*
*/
#if defined(mc68k) || defined(mc68000) || defined(mc68020) || defined(sparc) || defined(hp9000s300) || defined(hp9000s800)
#define BITS_BIGENDIAN
#endif
#if defined(vax) || defined(i386)
#define BITS_LITTLENDIAN
#endif
#if !defined BITS_BIGENDIAN && !defined BITS_LITTLENDIAN
#error Do not know my byte ordering
#endif
/*
* Structure of the information in the first word returned by both
* wait and wait3. If w_stopval==WSTOPPED, then the second structure
* describes the information returned, else the first. See WUNTRACED below.
*/
union wait {
int w_status; /* used in syscall */
/*
* Terminated process status.
*/
struct {
#ifdef BITS_LITTLENDIAN
unsigned short w_Termsig:7; /* termination signal */
unsigned short w_Coredump:1; /* core dump indicator */
unsigned short w_Retcode:8; /* exit code if w_termsig==0 */
#endif
#ifdef BITS_BIGENDIAN
unsigned short w_Fill1:16; /* high 16 bits unused */
unsigned short w_Retcode:8; /* exit code if w_termsig==0 */
unsigned short w_Coredump:1; /* core dump indicator */
unsigned short w_Termsig:7; /* termination signal */
#endif
} w_U;
};
#define w_termsig w_U.w_Termsig
#define w_coredump w_U.w_Coredump
#define w_retcode w_U.w_Retcode
#define WIFSIGNALED(x) ((x).w_termsig != 0)
#define WIFEXITED(x) ((x).w_termsig == 0)
| 30.551724 | 122 | 0.715011 |
04e124f2cef38fad53f90f88e803c3182ef480e2 | 105 | sql | SQL | _/Ch01/listHistoryTables.sql | paullewallencom/oracle-978-1-8496-8372-2 | f064eeb155c4ca25bebacf099b53d0f350ceaf79 | [
"Apache-2.0"
] | null | null | null | _/Ch01/listHistoryTables.sql | paullewallencom/oracle-978-1-8496-8372-2 | f064eeb155c4ca25bebacf099b53d0f350ceaf79 | [
"Apache-2.0"
] | null | null | null | _/Ch01/listHistoryTables.sql | paullewallencom/oracle-978-1-8496-8372-2 | f064eeb155c4ca25bebacf099b53d0f350ceaf79 | [
"Apache-2.0"
] | null | null | null | SELECT table_name
FROM dictionary
WHERE table_name like 'DBA/_HIST/_%' ESCAPE '/'
ORDER BY table_name; | 26.25 | 48 | 0.771429 |
f35bf1b82f316ea680226b5676ab2edd7fefbb3d | 4,349 | swift | Swift | TradingSimulator/market.historic/HistoricQuote.swift | machille/TradingSimulator | 4a92833a7d056a22e4225870c424e7e9c13ad1e4 | [
"MIT",
"Unlicense"
] | null | null | null | TradingSimulator/market.historic/HistoricQuote.swift | machille/TradingSimulator | 4a92833a7d056a22e4225870c424e7e9c13ad1e4 | [
"MIT",
"Unlicense"
] | null | null | null | TradingSimulator/market.historic/HistoricQuote.swift | machille/TradingSimulator | 4a92833a7d056a22e4225870c424e7e9c13ad1e4 | [
"MIT",
"Unlicense"
] | null | null | null | //
// HistoricQuote.swift
// Trading
//
// Created by Maroun Achille on 23/10/2018.
// Copyright © 2018 Maroun Achille. All rights reserved.
//
import Foundation
class HistoricQuote {
var id: String
var name: String
var type: String
var marketPlace: String
private var hist = [StockQuote]()
private var histWeekly = [StockQuote]()
var minDate: Date? {
if hist.count > 0 {
return hist.first?.dateQuote
} else {
return nil
}
}
var maxDate: Date? {
if hist.count > 0 {
return hist.last?.dateQuote
} else {
return nil
}
}
var lastQuote: StockQuote? {
if hist.count > 0 {
return hist.last
} else {
return nil
}
}
var lastVar: Double {
if hist.count > 0 {
let lastQuote = hist[hist.count-1].close
let beforeLastQuote = hist[hist.count-2].close
return Calculate.roundnumber( ((lastQuote - beforeLastQuote) / lastQuote ) * 100.00, 2.0)
} else {
return 0.0
}
}
init (id: String, name: String, type: String , marketPlace: String) {
self.id = id
self.name = name
self.type = type
self.marketPlace = marketPlace
}
func addQuote(dateQuote: Date, close: Double, open: Double, high: Double, low: Double, volume: Double) {
let sQuote: StockQuote = StockQuote(dateQuote: dateQuote, close: close, open: open, high: high, low: low, volume: volume)
hist.append(sQuote)
}
func addQuote(sQuote: StockQuote) {
hist.append(sQuote)
}
func getHist(contain: String) -> [StockQuote] {
if contain == ChartType.Weekly.rawValue {
return getHistWeekly()
} else {
return hist
}
}
func getHist(contain: String, from: Date , to: Date) -> [StockQuote] {
if contain == ChartType.Weekly.rawValue {
return getHistWeekly().filter { $0.dateQuote > from && $0.dateQuote <= to}
} else {
return hist.filter { $0.dateQuote > from && $0.dateQuote <= to}
}
}
func nextDate(contain: String, nDate: Date ) -> Date? {
let temp = getHist(contain: contain)
var cpt = 0
if let index = temp.firstIndex(where: { (item) -> Bool in item.dateQuote == nDate }) {
cpt = index + 1
if cpt < temp.count {
return temp[cpt].dateQuote
}
}
return nil
}
private func getHistWeekly() -> [StockQuote] {
if histWeekly.count != 0 {
return histWeekly
}
let calendar = Calendar.current
var week: Int = 0
var svweek: Int = 0
var first = true
var fpDateQuote: Date = Date()
var fpClose : Double = 0.0
var fpOpen : Double = 0.0
var fpHigh : Double = -1.0
var fpLow : Double = 9999999999.0
var fpVolume: Double = 0.0
for sQuote in hist {
week = calendar.component(.weekOfYear, from: sQuote.dateQuote)
if (first) {
fpOpen = sQuote.open
fpDateQuote = sQuote.dateQuote
svweek = week
first = false
}
if week != svweek {
let sQuoteWeek = StockQuote(dateQuote: fpDateQuote, close: fpClose, open: fpOpen, high: fpHigh, low: fpLow, volume: fpVolume)
histWeekly.append(sQuoteWeek)
fpOpen = sQuote.open
fpDateQuote = sQuote.dateQuote
svweek = week
fpHigh = -1
fpLow = 9999999999.0
fpVolume = 0.0
}
fpDateQuote = sQuote.dateQuote
fpClose = sQuote.close
fpHigh = max(fpHigh, sQuote.high);
fpLow = min(fpLow, sQuote.low);
fpVolume += sQuote.volume
}
let sQuotelast = StockQuote(dateQuote: fpDateQuote, close: fpClose, open: fpOpen, high: fpHigh, low: fpLow, volume: fpVolume)
histWeekly.append(sQuotelast)
return histWeekly
}
}
| 28.801325 | 141 | 0.51782 |
2d153cd887ad493f38993f34cbcf829b93dd63c0 | 1,640 | lua | Lua | mods/base/Hooks/EnvironmentManager.lua | Luffyyy/Raid-BLT-Lua | f951def0dc4e673e835e4ad8a8ecf65a1f7e6338 | [
"MIT"
] | 1 | 2017-10-20T01:06:05.000Z | 2017-10-20T01:06:05.000Z | mods/base/Hooks/EnvironmentManager.lua | Luffyyy/Raid-BLT-Lua | f951def0dc4e673e835e4ad8a8ecf65a1f7e6338 | [
"MIT"
] | null | null | null | mods/base/Hooks/EnvironmentManager.lua | Luffyyy/Raid-BLT-Lua | f951def0dc4e673e835e4ad8a8ecf65a1f7e6338 | [
"MIT"
] | 2 | 2019-04-19T18:42:03.000Z | 2019-08-29T14:50:24.000Z | --Sky texture code / Ported from BeardLib.
core:import("CoreClass")
core:import("CoreEnvironmentHandler")
core:import("CoreEnvironmentFeeder")
core:module("CoreEnvironmentManager")
EnvironmentManager = EnvironmentManager or CoreClass.class()
Hooks:PostHook(EnvironmentManager, "init", "BLT.EnvironmentManager.Init", function(self)
local feeder_class = CoreEnvironmentFeeder.SkyTexturePathFeeder
self._feeder_class_map[feeder_class.DATA_PATH_KEY] = feeder_class
if feeder_class.FILTER_CATEGORY then
local filter_list = self._predefined_environment_filter_map[feeder_class.FILTER_CATEGORY]
if not filter_list then
filter_list = {}
self._predefined_environment_filter_map[feeder_class.FILTER_CATEGORY] = filter_list
end
table.insert(filter_list, feeder_class.DATA_PATH_KEY)
end
end)
CoreEnvironmentFeeder.SkyTexturePathFeeder = CoreEnvironmentFeeder.SkyTexturePathFeeder or CoreClass.class(CoreEnvironmentFeeder.StringFeeder)
local SkyTex = CoreEnvironmentFeeder.SkyTexturePathFeeder
SkyTex.APPLY_GROUP_ID = CoreEnvironmentFeeder.Feeder.get_next_id()
SkyTex.DATA_PATH_KEY = Idstring("others/sky_texture"):key()
SkyTex.IS_GLOBAL = true
SkyTex.FILTER_CATEGORY = "Sky texture path"
function SkyTex:apply(handler, viewport, scene)
if self._current and Underlay:loaded() then
local texture = self._current
if texture then
local material = Underlay:material(Idstring("sky"))
if material and DB:has(Idstring("texture"), texture:id()) then
Application:set_material_texture(material, Idstring("diffuse_texture"), texture:id(), Idstring("normal"))
end
end
end
end | 45.555556 | 143 | 0.792073 |
9836f618224c5e0d43a88715e5abe198bfa47bf5 | 598 | asm | Assembly | programs/oeis/031/A031373.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 22 | 2018-02-06T19:19:31.000Z | 2022-01-17T21:53:31.000Z | programs/oeis/031/A031373.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 41 | 2021-02-22T19:00:34.000Z | 2021-08-28T10:47:47.000Z | programs/oeis/031/A031373.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 5 | 2021-02-24T21:14:16.000Z | 2021-08-09T19:48:05.000Z | ; A031373: Primes p(7n-1).
; 13,41,71,103,139,179,223,257,293,347,383,431,463,509,569,607,647,691,743,797,839,883,941,991,1033,1087,1123,1187,1231,1289,1321,1409,1451,1489,1549,1597,1627,1697,1747,1801,1871,1913,1987,2027,2083,2131,2203,2251,2297,2351,2393,2447,2531,2591,2657,2689,2729,2789,2837,2897,2957,3019,3079,3163,3209,3259,3323,3371,3449,3499,3541,3593,3643,3701,3767,3823,3881,3929,4003,4051,4111,4159,4231,4273,4349,4421,4481,4523,4597,4651,4721,4787,4831,4919,4967,5009,5077,5119,5197,5273
mul $0,7
add $0,4
seq $0,98090 ; Numbers k such that 2k-3 is prime.
sub $0,5
mul $0,2
add $0,7
| 59.8 | 474 | 0.752508 |
3e5c71758148c57c53eef230198ba278b3777cb0 | 6,084 | c | C | platform/mcu/stm32l475/Middlewares/USB_Host/Core/Src/usbh_pipes.c | jinlongliu/AliOS-Things | ce051172a775f987183e7aca88bb6f3b809ea7b0 | [
"Apache-2.0"
] | 12 | 2020-12-04T15:06:22.000Z | 2022-01-19T09:57:47.000Z | platform/mcu/stm32l475/Middlewares/USB_Host/Core/Src/usbh_pipes.c | IamBaoMouMou/AliOS-Things | 195a9160b871b3d78de6f8cf6c2ab09a71977527 | [
"Apache-2.0"
] | 3 | 2018-12-17T13:06:46.000Z | 2018-12-28T01:40:59.000Z | platform/mcu/stm32l475/Middlewares/USB_Host/Core/Src/usbh_pipes.c | IamBaoMouMou/AliOS-Things | 195a9160b871b3d78de6f8cf6c2ab09a71977527 | [
"Apache-2.0"
] | 6 | 2019-08-30T09:43:03.000Z | 2021-04-05T04:20:41.000Z | /**
******************************************************************************
* @file usbh_pipes.c
* @author MCD Application Team
* @version V3.2.2
* @date 07-July-2015
* @brief This file implements functions for opening and closing Pipes
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2017 STMicroelectronics International N.V.
* All rights reserved.</center></h2>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted, provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of other
* contributors to this software may be used to endorse or promote products
* derived from this software without specific written permission.
* 4. This software, including modifications and/or derivative works of this
* software, must execute solely and exclusively on microcontroller or
* microprocessor devices manufactured by or for STMicroelectronics.
* 5. Redistribution and use of this software other than as permitted under
* this license is void and will automatically terminate your rights under
* this license.
*
* THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY
* RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT
* SHALL STMICROELECTRONICS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "usbh_pipes.h"
/** @addtogroup USBH_LIB
* @{
*/
/** @addtogroup USBH_LIB_CORE
* @{
*/
/** @defgroup USBH_PIPES
* @brief This file includes opening and closing Pipes
* @{
*/
/** @defgroup USBH_PIPES_Private_Defines
* @{
*/
/**
* @}
*/
/** @defgroup USBH_PIPES_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @defgroup USBH_PIPES_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBH_PIPES_Private_Variables
* @{
*/
/**
* @}
*/
/** @defgroup USBH_PIPES_Private_Functions
* @{
*/
static uint16_t USBH_GetFreePipe (USBH_HandleTypeDef *phost);
/**
* @brief USBH_Open_Pipe
* Open a pipe
* @param phost: Host Handle
* @param pipe_num: Pipe Number
* @param dev_address: USB Device address allocated to attached device
* @param speed : USB device speed (Full/Low)
* @param ep_type: end point type (Bulk/int/ctl)
* @param mps: max pkt size
* @retval USBH Status
*/
USBH_StatusTypeDef USBH_OpenPipe (USBH_HandleTypeDef *phost,
uint8_t pipe_num,
uint8_t epnum,
uint8_t dev_address,
uint8_t speed,
uint8_t ep_type,
uint16_t mps)
{
USBH_LL_OpenPipe(phost,
pipe_num,
epnum,
dev_address,
speed,
ep_type,
mps);
return USBH_OK;
}
/**
* @brief USBH_ClosePipe
* Close a pipe
* @param phost: Host Handle
* @param pipe_num: Pipe Number
* @retval USBH Status
*/
USBH_StatusTypeDef USBH_ClosePipe (USBH_HandleTypeDef *phost,
uint8_t pipe_num)
{
USBH_LL_ClosePipe(phost, pipe_num);
return USBH_OK;
}
/**
* @brief USBH_Alloc_Pipe
* Allocate a new Pipe
* @param phost: Host Handle
* @param ep_addr: End point for which the Pipe to be allocated
* @retval Pipe number
*/
uint8_t USBH_AllocPipe (USBH_HandleTypeDef *phost, uint8_t ep_addr)
{
uint16_t pipe;
pipe = USBH_GetFreePipe(phost);
if (pipe != 0xFFFF)
{
phost->Pipes[pipe] = 0x8000 | ep_addr;
}
return pipe;
}
/**
* @brief USBH_Free_Pipe
* Free the USB Pipe
* @param phost: Host Handle
* @param idx: Pipe number to be freed
* @retval USBH Status
*/
USBH_StatusTypeDef USBH_FreePipe (USBH_HandleTypeDef *phost, uint8_t idx)
{
if(idx < 11)
{
phost->Pipes[idx] &= 0x7FFF;
}
return USBH_OK;
}
/**
* @brief USBH_GetFreePipe
* @param phost: Host Handle
* Get a free Pipe number for allocation to a device endpoint
* @retval idx: Free Pipe number
*/
static uint16_t USBH_GetFreePipe (USBH_HandleTypeDef *phost)
{
uint8_t idx = 0;
for (idx = 0 ; idx < 11 ; idx++)
{
if ((phost->Pipes[idx] & 0x8000) == 0)
{
return idx;
}
}
return 0xFFFF;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| 27.04 | 81 | 0.58021 |
75e6d2f237e8baf2358330b4e4cdb48f38ca1f57 | 8,614 | php | PHP | src/Game/Map/Generator/Path.php | ekinhbayar/tower-defense | 17f8c763c7534f065ea6a2eb710dad8a9240e838 | [
"MIT"
] | 2 | 2017-03-13T17:04:29.000Z | 2017-03-16T16:58:07.000Z | src/Game/Map/Generator/Path.php | ekinhbayar/tower-defense | 17f8c763c7534f065ea6a2eb710dad8a9240e838 | [
"MIT"
] | null | null | null | src/Game/Map/Generator/Path.php | ekinhbayar/tower-defense | 17f8c763c7534f065ea6a2eb710dad8a9240e838 | [
"MIT"
] | null | null | null | <?php declare(strict_types = 1);
namespace Game\Map\Generator;
use Game\Entity\Coordinates;
use Game\Entity\Map\Path as PathTile;
/**
* Rules:
*
* - Drawing a path from point a to point b
* - Tiles must be placed random
* - Tiles must be connected
* - New tiles must be biased to point b
* - No paths along the edges of the map
* - There must be no tiles next to each other unless it's an intersection
*
* Implementation:
*
* - Individual paths are generated from the spawn point to each player
* - Each direction (for new tile placement) has a 25% chance of being hit by default
* - Each direction (for new tile placement) is biased towards the player's position
* - Each direction (for new tile placement) is biased towards positions not yet in eth path to the player
* - Tiles are not allowed to touch the edges
* - Tiles are not allowed to go outside the map
*/
class Path
{
const BIAS = 20;
private $path = [];
private $width;
private $height;
private $tileSize;
public function __construct(int $width, int $height, int $tileSize)
{
$this->width = $width;
$this->height = $height;
$this->tileSize = $tileSize;
}
public function generate(array $players, Coordinates $spawnPoint)
{
while ($player = array_shift($players)) {
$this->generatePathToPlayer($player, $spawnPoint);
}
return $this->path;
}
private function generatePathToPlayer(Coordinates $player, Coordinates $spawnPoint)
{
$playerPath = [];
$pathTile = new PathTile(
new Coordinates($spawnPoint->getX(), $spawnPoint->getY())
);
$playerPath[$this->convertTileToKey($pathTile)] = $pathTile;
while ($pathTile->getPositionX() !== $player->getX() || $pathTile->getPositionY() !== $player->getY()) {
$pathTile = $this->getNextTile($playerPath, $pathTile, $player);
$playerPath[$this->convertTileToKey($pathTile)] = $pathTile;
$this->path = array_merge($this->path, $playerPath);
}
}
private function convertTileToKey(PathTile $tile): string
{
return $tile->getPositionX() . 'x' . $tile->getPositionY();
}
private function getNextTile(array $playerPath, PathTile $currentTile, Coordinates $player): PathTile
{
// base chance of hitting a certain direction
$possibilities = [
'top' => 25,
'bottom' => 25,
'left' => 25,
'right' => 25,
];
$possibilities = $this->biasTowardsPlayer($possibilities, $currentTile, $player);
$possibilities = $this->biasTowardsNewTiles($possibilities, $currentTile, $playerPath);
//$possibilities = $this->removeChanceOfHittingTheEdge($possibilities, $currentTile, $player);
$possibilities = $this->removeChanceOfGoingOutsideTheMap($possibilities, $currentTile);
$possibilities = $this->removeChanceOfIntroducingBlocks($possibilities, $currentTile);
$newDirection = random_int(0, array_sum($possibilities));
$currentChance = 0;
foreach ($possibilities as $direction => $possibility) {
$currentChance += $possibility;
if ($newDirection <= $currentChance) {
return $this->getTileCoordinatesBasedOnDirectionAndPreviousTile($direction, $currentTile);
}
}
}
private function biasTowardsPlayer(array $chances, PathTile $currentTile, Coordinates $player): array
{
if ($player->getX() < $currentTile->getPositionX()) {
$chances['left'] += self::BIAS;
}
if ($player->getX() > $currentTile->getPositionX()) {
$chances['right'] += self::BIAS;
}
if ($player->getY() < $currentTile->getPositionY()) {
$chances['top'] += self::BIAS;
}
if ($player->getY() > $currentTile->getPositionY()) {
$chances['bottom'] += self::BIAS;
}
return $chances;
}
private function biasTowardsNewTiles(array $chances, PathTile $currentTile, array $playerPath): array
{
if ($this->tileExists($currentTile->moveLeft(), $playerPath)) {
$chances['left'] -= self::BIAS;
}
if ($this->tileExists($currentTile->moveRight(), $playerPath)) {
$chances['right'] -= self::BIAS;
}
if ($this->tileExists($currentTile->moveUp(), $playerPath)) {
$chances['top'] -= self::BIAS;
}
if ($this->tileExists($currentTile->moveDown(), $playerPath)) {
$chances['bottom'] -= self::BIAS;
}
return $chances;
}
private function removeChanceOfHittingTheEdge(array $chances, PathTile $currentTile, Coordinates $player): array
{
$newTile = $currentTile->moveLeft();
if ($newTile->getPositionX() === 0 && ($newTile->getPositionX() !== $player->getX() || $newTile->getPositionY() !== $player->getY())) {
$chances['left'] = 0;
}
$newTile = $currentTile->moveRight();
if ($newTile->getPositionX() === 1180 && ($newTile->getPositionX() !== $player->getX() || $newTile->getPositionY() !== $player->getY())) {
$chances['right'] = 0;
}
$newTile = $currentTile->moveUp();
if ($newTile->getPositionY() === 0 && ($newTile->getPositionX() !== $player->getX() || $newTile->getPositionY() !== $player->getY())) {
$chances['top'] = 0;
}
$newTile = $currentTile->moveDown();
if ($newTile->getPositionY() === 780 && ($newTile->getPositionX() !== $player->getX() || $newTile->getPositionY() !== $player->getY())) {
$chances['bottom'] = 0;
}
return $chances;
}
private function removeChanceOfGoingOutsideTheMap(array $chances, PathTile $currentTile): array
{
$newTile = $currentTile->moveLeft();
if ($newTile->getPositionX() < 0) {
$chances['left'] = 0;
}
$newTile = $currentTile->moveRight();
if ($newTile->getPositionX() > 1180) {
$chances['right'] = 0;
}
$newTile = $currentTile->moveUp();
if ($newTile->getPositionY() < 0) {
$chances['top'] = 0;
}
$newTile = $currentTile->moveDown();
if ($newTile->getPositionY() > 780) {
$chances['bottom'] = 0;
}
return $chances;
}
private function removeChanceOfIntroducingBlocks(array $chances, PathTile $currentTile): array
{
$upTile = $currentTile->moveUp();
$downTile = $currentTile->moveDown();
$leftTile = $currentTile->moveLeft();
$rightTile = $currentTile->moveRight();
$chances['top'] -= (int) ($this->getNumberOfNeighbors($upTile) / 2);
$chances['bottom'] -= (int) ($this->getNumberOfNeighbors($downTile) / 2);
$chances['left'] -= (int) ($this->getNumberOfNeighbors($leftTile) / 2);
$chances['right'] -= (int) ($this->getNumberOfNeighbors($rightTile) / 2);
return $chances;
}
private function getNumberOfNeighbors(PathTile $tile): int
{
$neighbors = 0;
$upTile = $tile->moveUp();
$downTile = $tile->moveDown();
$leftTile = $tile->moveLeft();
$rightTile = $tile->moveRight();
if (array_key_exists($this->convertTileToKey($upTile), $this->path)) {
$neighbors++;
}
if (array_key_exists($this->convertTileToKey($downTile), $this->path)) {
$neighbors++;
}
if (array_key_exists($this->convertTileToKey($leftTile), $this->path)) {
$neighbors++;
}
if (array_key_exists($this->convertTileToKey($rightTile), $this->path)) {
$neighbors++;
}
return $neighbors;
}
private function tileExists(PathTile $tile, array $playerPath): bool
{
$key = $this->convertTileToKey($tile);
if (array_key_exists($key, $playerPath)) {
return true;
}
return false;
}
private function getTileCoordinatesBasedOnDirectionAndPreviousTile(string $direction, PathTile $currentTile): PathTile
{
switch ($direction) {
case 'top':
return $currentTile->moveUp();
case 'bottom':
return $currentTile->moveDown();
case 'left':
return $currentTile->moveLeft();
case 'right':
return $currentTile->moveRight();
}
}
}
| 30.874552 | 146 | 0.574994 |
330bcb8284fec7ff83c5b51b2973e481ae9b2a12 | 1,376 | py | Python | app/main/models/utils.py | tmeftah/e-invoice | 7cfe31e9391eb60ab3d06f0055bd2f1e9a524971 | [
"MIT"
] | 2 | 2019-06-10T19:30:06.000Z | 2020-04-30T01:05:04.000Z | app/main/models/utils.py | tmeftah/e-invoice | 7cfe31e9391eb60ab3d06f0055bd2f1e9a524971 | [
"MIT"
] | null | null | null | app/main/models/utils.py | tmeftah/e-invoice | 7cfe31e9391eb60ab3d06f0055bd2f1e9a524971 | [
"MIT"
] | 3 | 2019-01-23T21:37:29.000Z | 2020-04-08T13:22:29.000Z | from datetime import datetime
import sqlalchemy as sa
from flask_sqlalchemy import Model
from sqlalchemy import ForeignKey
from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy.orm import relationship
from app.main.extensions import db
class BaseMixin(Model):
def save_to_db(self):
try:
db.session.add(self)
db.session.commit()
except:
db.session.rollback()
raise
def delete_from_db(self):
try:
db.session.delete(self)
db.session.commit()
except:
db.session.rollback()
raise
class UserMixin(BaseMixin, Model):
@declared_attr
def createdAt(cls):
return sa.Column(sa.DateTime, default=datetime.utcnow)
@declared_attr
def updateAt(cls):
return sa.Column(sa.DateTime)
@declared_attr
def createdBy_id(cls):
return sa.Column(sa.Integer, ForeignKey('users.id'),
nullable=False)
@declared_attr
def updatedBy_id(cls):
return sa.Column(sa.Integer, ForeignKey('users.id'))
@declared_attr
def createdBy(cls):
return relationship(
'UserModel', foreign_keys=[cls.createdBy_id])
@declared_attr
def updatedBy(cls):
return relationship(
'UserModel', foreign_keys=[cls.updatedBy_id])
| 23.322034 | 62 | 0.634448 |
426e63ccb9340e89e82f3c6ffe4f06e627d6da2a | 1,177 | sql | SQL | consumer_data.package.sql | morten-egan/random_ninja | d0c1faf54448dd7e8e6d5ba13a1c75920a89c879 | [
"MIT"
] | 12 | 2018-02-14T11:51:59.000Z | 2021-12-11T14:58:08.000Z | consumer_data.package.sql | morten-egan/random_ninja | d0c1faf54448dd7e8e6d5ba13a1c75920a89c879 | [
"MIT"
] | 21 | 2017-04-12T13:22:34.000Z | 2022-03-27T18:01:06.000Z | consumer_data.package.sql | morten-egan/random_ninja | d0c1faf54448dd7e8e6d5ba13a1c75920a89c879 | [
"MIT"
] | 6 | 2017-04-09T08:16:06.000Z | 2020-06-24T08:08:48.000Z | create or replace package consumer_data
as
/** Data for generating random consumer data.
* @author Morten Egan
* @version 0.0.1
* @project NINJA_RANDOM
*/
npg_version varchar2(250) := '1.3.0';
nonfood_categories varchar2(32000) := 'Home and Kitchen,Fashion,Electronics,Beauty,Leisure,Furniture,Tools';
food_categories varchar2(32000) := 'Vegetables,Fruits,Meats,Canned goods,Dry goods,Dairy,Fish,Beverages,Frozen food,Bread,Candy and Snacks,Condiments';
service_category varchar2(32000) := 'Plumber,Carpenter,Builder,Consultant,Contractor';
type consumer_item is record (
item_name varchar2(4000)
, item_price_start number
, item_price_end number
);
type consumer_item_list is table of consumer_item;
type category_items_list is table of consumer_item_list index by varchar2(4000);
items category_items_list;
type additive_group_rec is record (
group_name varchar2(50)
, additives varchar2(4000)
);
type additive_group_list is table of additive_group_rec;
additives additive_group_list;
init_data varchar2(250);
end consumer_data;
/
| 32.694444 | 161 | 0.712829 |
53ccaedd2a8bec95f73ec3072e4ef9456f5a8a37 | 741 | java | Java | GalaxyQuests/src/main/java/com/galaxy/galaxyquests/menu/menus/questsmenus/StandardQuestMenu.java | MangoPlex/Minecraft-Projects | d97e6fa74855e39f77bf117a25b2f2d45d31ccf5 | [
"MIT"
] | null | null | null | GalaxyQuests/src/main/java/com/galaxy/galaxyquests/menu/menus/questsmenus/StandardQuestMenu.java | MangoPlex/Minecraft-Projects | d97e6fa74855e39f77bf117a25b2f2d45d31ccf5 | [
"MIT"
] | null | null | null | GalaxyQuests/src/main/java/com/galaxy/galaxyquests/menu/menus/questsmenus/StandardQuestMenu.java | MangoPlex/Minecraft-Projects | d97e6fa74855e39f77bf117a25b2f2d45d31ccf5 | [
"MIT"
] | null | null | null | package com.galaxy.galaxyquests.menu.menus.questsmenus;
import com.galaxy.galaxyquests.QuestsPlugin;
import com.galaxy.galaxyquests.objects.quest.Quest;
import com.galaxy.galaxyquests.objects.quest.QuestType;
import me.hyfe.simplespigot.config.Config;
import org.bukkit.entity.Player;
import java.util.Collection;
public class StandardQuestMenu extends AbstractQuestMenu {
private final QuestType questType;
public StandardQuestMenu(QuestsPlugin plugin, Config config, Player player, QuestType questType) {
super(plugin, config, player);
this.questType = questType;
}
@Override
public Collection<Quest> quests() {
return this.plugin.getQuestCache().getQuests(this.questType).values();
}
} | 32.217391 | 102 | 0.766532 |
401e288ac3539a4c43bd8a86f1eae91fa5099647 | 6,557 | py | Python | BALSAMIC/commands/report/deliver.py | ashwini06/BALSAMIC | f13d9414d67c006f58d5dc3cfd8f64803f83c2ad | [
"MIT"
] | null | null | null | BALSAMIC/commands/report/deliver.py | ashwini06/BALSAMIC | f13d9414d67c006f58d5dc3cfd8f64803f83c2ad | [
"MIT"
] | null | null | null | BALSAMIC/commands/report/deliver.py | ashwini06/BALSAMIC | f13d9414d67c006f58d5dc3cfd8f64803f83c2ad | [
"MIT"
] | null | null | null | import os
import sys
import logging
import glob
import json
import yaml
import click
import copy
import snakemake
import datetime
from collections import defaultdict
from yapf.yapflib.yapf_api import FormatFile
from BALSAMIC.utils.cli import get_from_two_key
from BALSAMIC.utils.cli import merge_dict_on_key
from BALSAMIC.utils.cli import get_file_extension
from BALSAMIC.utils.cli import find_file_index
from BALSAMIC.utils.cli import write_json
from BALSAMIC.utils.cli import get_snakefile
from BALSAMIC.utils.cli import CaptureStdout
from BALSAMIC.utils.rule import get_result_dir
from BALSAMIC.utils.exc import BalsamicError
LOG = logging.getLogger(__name__)
@click.command(
"deliver",
short_help="Creates a YAML file with output from variant caller and alignment.",
)
@click.option(
"--sample-config",
required=True,
help="Sample config file. Output of balsamic config sample",
)
@click.pass_context
def deliver(context, sample_config):
"""
cli for deliver sub-command.
Writes <case_id>.hk in result_directory.
"""
LOG.info(f"BALSAMIC started with log level {context.obj['loglevel']}.")
LOG.debug("Reading input sample config")
with open(sample_config, "r") as fn:
sample_config_dict = json.load(fn)
result_dir = get_result_dir(sample_config_dict)
dst_directory = os.path.join(result_dir, "delivery_report")
LOG.info("Creatiing delivery_report directory")
os.makedirs(dst_directory, exist_ok=True)
yaml_write_directory = os.path.join(result_dir, "delivery_report")
os.makedirs(yaml_write_directory, exist_ok=True)
analysis_type = sample_config_dict["analysis"]["analysis_type"]
sequencing_type = sample_config_dict["analysis"]["sequencing_type"]
snakefile = get_snakefile(analysis_type, sequencing_type)
LOG.info("Creating report file")
report_file_name = os.path.join(
yaml_write_directory, sample_config_dict["analysis"]["case_id"] + "_report.html"
)
with CaptureStdout():
snakemake.snakemake(
snakefile=snakefile,
dryrun=True,
quiet=True,
report=report_file_name,
configfiles=[sample_config],
)
with CaptureStdout():
snakemake.snakemake(
snakefile=snakefile,
config={"delivery": "True"},
dryrun=True,
configfiles=[sample_config],
quiet=True,
)
delivery_file_name = os.path.join(
yaml_write_directory, sample_config_dict["analysis"]["case_id"] + ".hk"
)
delivery_file_raw = os.path.join(
yaml_write_directory,
sample_config_dict["analysis"]["case_id"] + "_delivery_raw.hk",
)
with open(delivery_file_raw, "r") as fn:
delivery_file_raw_dict = json.load(fn)
delivery_file_ready = os.path.join(
yaml_write_directory,
sample_config_dict["analysis"]["case_id"] + "_delivery_ready.hk",
)
with open(delivery_file_ready, "r") as fn:
delivery_file_ready_dict = json.load(fn)
with CaptureStdout() as summary:
snakemake.snakemake(
snakefile=snakefile,
config={"delivery": "True"},
dryrun=True,
summary=True,
configfiles=[sample_config],
quiet=True,
)
summary = [i.split("\t") for i in summary]
summary_dict = [dict(zip(summary[0], value)) for value in summary[1:]]
output_files_merged_interm = merge_dict_on_key(
dict_1=summary_dict, dict_2=delivery_file_raw_dict, by_key="output_file"
)
output_files_merged = merge_dict_on_key(
dict_1=output_files_merged_interm,
dict_2=delivery_file_ready_dict,
by_key="output_file",
)
delivery_json = dict()
delivery_json["files"] = list()
for item in output_files_merged:
if "date" in item:
warnings = list()
interm_dict = copy.deepcopy(item)
interm_dict["path"] = interm_dict.get("output_file")
interm_dict["step"] = interm_dict.get("rulename", "unknown")
file_path_index = find_file_index(interm_dict["path"])
if len(file_path_index) > 1:
LOG.warning("More than one index found for %s" % interm_dict["path"])
LOG.warning("Taking %s index file" % list(file_path_index)[0])
interm_dict["path_index"] = file_path_index[0] if file_path_index else ""
interm_dict["format"] = get_file_extension(interm_dict["path"])
interm_dict["tag"] = ",".join(interm_dict.get("wildcard_name", ["unknown"]))
interm_dict["id"] = "unknown"
delivery_id = list()
delivery_id.append(
get_from_two_key(
interm_dict,
from_key="wildcard_name",
by_key="wildcard_value",
by_value="sample",
default=None,
)
)
delivery_id.append(
get_from_two_key(
interm_dict,
from_key="wildcard_name",
by_key="wildcard_value",
by_value="case_name",
default=None,
)
)
delivery_id = list(filter(None, delivery_id))
if len(delivery_id) > 1:
LOG.error(f"Ambiguous delivery id. Wilcard has both: {delivery_id}")
raise BalsamicError("Delivery file parsing process failed.")
if delivery_id:
interm_dict["id"] = delivery_id[0]
delivery_json["files"].append(interm_dict)
delivery_json["files"].append(
{
"path": report_file_name,
"date": datetime.date.today().isoformat(),
"step": "balsamic_delivery",
"format": ".html",
"tag": "report",
"id": sample_config_dict["analysis"]["case_id"],
}
)
write_json(delivery_json, delivery_file_name)
with open(delivery_file_name + ".yaml", "w") as fn:
yaml.dump(delivery_json, fn, default_flow_style=False)
LOG.info(f"Housekeeper delivery file {delivery_file_name}")
LOG.info(f"Workflow report file {report_file_name}")
# for entries in deliveries:
# delivery_file = entries[2]
# if os.path.isfile(delivery_file):
# print(Color(u"[{green}\u2713{/green}]"), entries)
# else:
# print(Color(u"[{red}\u2717{/red}]"), entries)
# break
# print(dag)
| 33.454082 | 88 | 0.626354 |
83e76ff507bc1ee459b572353ca72fc619d0ea8b | 174,438 | rs | Rust | gen/adsense1d4-cli/src/main.rs | eiz/google-apis-rs | 76b4dcbe7c9eb76879465484fe4396e8df6f73af | [
"MIT-feh",
"Apache-2.0",
"MIT"
] | null | null | null | gen/adsense1d4-cli/src/main.rs | eiz/google-apis-rs | 76b4dcbe7c9eb76879465484fe4396e8df6f73af | [
"MIT-feh",
"Apache-2.0",
"MIT"
] | null | null | null | gen/adsense1d4-cli/src/main.rs | eiz/google-apis-rs | 76b4dcbe7c9eb76879465484fe4396e8df6f73af | [
"MIT-feh",
"Apache-2.0",
"MIT"
] | null | null | null | // DO NOT EDIT !
// This file was generated automatically from 'src/mako/cli/main.rs.mako'
// DO NOT EDIT !
#![allow(unused_variables, unused_imports, dead_code, unused_mut)]
extern crate tokio;
#[macro_use]
extern crate clap;
use std::env;
use std::io::{self, Write};
use clap::{App, SubCommand, Arg};
use google_adsense1d4::{api, Error, oauth2};
mod client;
use client::{InvalidOptionsError, CLIError, arg_from_str, writer_from_opts, parse_kv_arg,
input_file_from_opts, input_mime_from_opts, FieldCursor, FieldError, CallType, UploadProtocol,
calltype_from_str, remove_json_null_values, ComplexType, JsonType, JsonTypeInfo};
use std::default::Default;
use std::str::FromStr;
use serde_json as json;
use clap::ArgMatches;
enum DoitError {
IoError(String, io::Error),
ApiError(Error),
}
struct Engine<'n> {
opt: ArgMatches<'n>,
hub: api::AdSense,
gp: Vec<&'static str>,
gpm: Vec<(&'static str, &'static str)>,
}
impl<'n> Engine<'n> {
async fn _accounts_adclients_get_ad_code(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.accounts().adclients_get_ad_code(opt.value_of("account-id").unwrap_or(""), opt.value_of("ad-client-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"tag-partner" => {
call = call.tag_partner(value.unwrap_or(""));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["tag-partner"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit().await,
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
async fn _accounts_adclients_list(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.accounts().adclients_list(opt.value_of("account-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"page-token" => {
call = call.page_token(value.unwrap_or(""));
},
"max-results" => {
call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer"));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["max-results", "page-token"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit().await,
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
async fn _accounts_adunits_customchannels_list(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.accounts().adunits_customchannels_list(opt.value_of("account-id").unwrap_or(""), opt.value_of("ad-client-id").unwrap_or(""), opt.value_of("ad-unit-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"page-token" => {
call = call.page_token(value.unwrap_or(""));
},
"max-results" => {
call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer"));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["max-results", "page-token"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit().await,
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
async fn _accounts_adunits_get(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.accounts().adunits_get(opt.value_of("account-id").unwrap_or(""), opt.value_of("ad-client-id").unwrap_or(""), opt.value_of("ad-unit-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit().await,
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
async fn _accounts_adunits_get_ad_code(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.accounts().adunits_get_ad_code(opt.value_of("account-id").unwrap_or(""), opt.value_of("ad-client-id").unwrap_or(""), opt.value_of("ad-unit-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit().await,
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
async fn _accounts_adunits_list(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.accounts().adunits_list(opt.value_of("account-id").unwrap_or(""), opt.value_of("ad-client-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"page-token" => {
call = call.page_token(value.unwrap_or(""));
},
"max-results" => {
call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer"));
},
"include-inactive" => {
call = call.include_inactive(arg_from_str(value.unwrap_or("false"), err, "include-inactive", "boolean"));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["include-inactive", "max-results", "page-token"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit().await,
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
async fn _accounts_alerts_delete(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.accounts().alerts_delete(opt.value_of("account-id").unwrap_or(""), opt.value_of("alert-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
match match protocol {
CallType::Standard => call.doit().await,
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok(mut response) => {
Ok(())
}
}
}
}
async fn _accounts_alerts_list(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.accounts().alerts_list(opt.value_of("account-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"locale" => {
call = call.locale(value.unwrap_or(""));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["locale"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit().await,
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
async fn _accounts_customchannels_adunits_list(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.accounts().customchannels_adunits_list(opt.value_of("account-id").unwrap_or(""), opt.value_of("ad-client-id").unwrap_or(""), opt.value_of("custom-channel-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"page-token" => {
call = call.page_token(value.unwrap_or(""));
},
"max-results" => {
call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer"));
},
"include-inactive" => {
call = call.include_inactive(arg_from_str(value.unwrap_or("false"), err, "include-inactive", "boolean"));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["include-inactive", "max-results", "page-token"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit().await,
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
async fn _accounts_customchannels_get(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.accounts().customchannels_get(opt.value_of("account-id").unwrap_or(""), opt.value_of("ad-client-id").unwrap_or(""), opt.value_of("custom-channel-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit().await,
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
async fn _accounts_customchannels_list(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.accounts().customchannels_list(opt.value_of("account-id").unwrap_or(""), opt.value_of("ad-client-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"page-token" => {
call = call.page_token(value.unwrap_or(""));
},
"max-results" => {
call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer"));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["max-results", "page-token"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit().await,
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
async fn _accounts_get(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.accounts().get(opt.value_of("account-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"tree" => {
call = call.tree(arg_from_str(value.unwrap_or("false"), err, "tree", "boolean"));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["tree"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit().await,
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
async fn _accounts_list(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.accounts().list();
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"page-token" => {
call = call.page_token(value.unwrap_or(""));
},
"max-results" => {
call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer"));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["max-results", "page-token"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit().await,
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
async fn _accounts_payments_list(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.accounts().payments_list(opt.value_of("account-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit().await,
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
async fn _accounts_reports_generate(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut download_mode = false;
let mut call = self.hub.accounts().reports_generate(opt.value_of("account-id").unwrap_or(""), opt.value_of("start-date").unwrap_or(""), opt.value_of("end-date").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"use-timezone-reporting" => {
call = call.use_timezone_reporting(arg_from_str(value.unwrap_or("false"), err, "use-timezone-reporting", "boolean"));
},
"start-index" => {
call = call.start_index(arg_from_str(value.unwrap_or("-0"), err, "start-index", "integer"));
},
"sort" => {
call = call.add_sort(value.unwrap_or(""));
},
"metric" => {
call = call.add_metric(value.unwrap_or(""));
},
"max-results" => {
call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer"));
},
"locale" => {
call = call.locale(value.unwrap_or(""));
},
"filter" => {
call = call.add_filter(value.unwrap_or(""));
},
"dimension" => {
call = call.add_dimension(value.unwrap_or(""));
},
"currency" => {
call = call.currency(value.unwrap_or(""));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
if key == "alt" && value.unwrap_or("unset") == "media" {
download_mode = true;
}
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["currency", "dimension", "filter", "locale", "max-results", "metric", "sort", "start-index", "use-timezone-reporting"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit().await,
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
if !download_mode {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
} else {
let bytes = hyper::body::to_bytes(response.into_body()).await.expect("a string as API currently is inefficient").to_vec();
ostream.write_all(&bytes).expect("write to be complete");
ostream.flush().expect("io to never fail which should really be fixed one day");
}
Ok(())
}
}
}
}
async fn _accounts_reports_saved_generate(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.accounts().reports_saved_generate(opt.value_of("account-id").unwrap_or(""), opt.value_of("saved-report-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"start-index" => {
call = call.start_index(arg_from_str(value.unwrap_or("-0"), err, "start-index", "integer"));
},
"max-results" => {
call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer"));
},
"locale" => {
call = call.locale(value.unwrap_or(""));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["locale", "max-results", "start-index"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit().await,
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
async fn _accounts_reports_saved_list(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.accounts().reports_saved_list(opt.value_of("account-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"page-token" => {
call = call.page_token(value.unwrap_or(""));
},
"max-results" => {
call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer"));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["max-results", "page-token"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit().await,
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
async fn _accounts_savedadstyles_get(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.accounts().savedadstyles_get(opt.value_of("account-id").unwrap_or(""), opt.value_of("saved-ad-style-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit().await,
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
async fn _accounts_savedadstyles_list(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.accounts().savedadstyles_list(opt.value_of("account-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"page-token" => {
call = call.page_token(value.unwrap_or(""));
},
"max-results" => {
call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer"));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["max-results", "page-token"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit().await,
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
async fn _accounts_urlchannels_list(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.accounts().urlchannels_list(opt.value_of("account-id").unwrap_or(""), opt.value_of("ad-client-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"page-token" => {
call = call.page_token(value.unwrap_or(""));
},
"max-results" => {
call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer"));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["max-results", "page-token"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit().await,
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
async fn _adclients_list(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.adclients().list();
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"page-token" => {
call = call.page_token(value.unwrap_or(""));
},
"max-results" => {
call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer"));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["max-results", "page-token"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit().await,
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
async fn _adunits_customchannels_list(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.adunits().customchannels_list(opt.value_of("ad-client-id").unwrap_or(""), opt.value_of("ad-unit-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"page-token" => {
call = call.page_token(value.unwrap_or(""));
},
"max-results" => {
call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer"));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["max-results", "page-token"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit().await,
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
async fn _adunits_get(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.adunits().get(opt.value_of("ad-client-id").unwrap_or(""), opt.value_of("ad-unit-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit().await,
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
async fn _adunits_get_ad_code(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.adunits().get_ad_code(opt.value_of("ad-client-id").unwrap_or(""), opt.value_of("ad-unit-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit().await,
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
async fn _adunits_list(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.adunits().list(opt.value_of("ad-client-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"page-token" => {
call = call.page_token(value.unwrap_or(""));
},
"max-results" => {
call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer"));
},
"include-inactive" => {
call = call.include_inactive(arg_from_str(value.unwrap_or("false"), err, "include-inactive", "boolean"));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["include-inactive", "max-results", "page-token"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit().await,
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
async fn _alerts_delete(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.alerts().delete(opt.value_of("alert-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
match match protocol {
CallType::Standard => call.doit().await,
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok(mut response) => {
Ok(())
}
}
}
}
async fn _alerts_list(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.alerts().list();
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"locale" => {
call = call.locale(value.unwrap_or(""));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["locale"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit().await,
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
async fn _customchannels_adunits_list(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.customchannels().adunits_list(opt.value_of("ad-client-id").unwrap_or(""), opt.value_of("custom-channel-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"page-token" => {
call = call.page_token(value.unwrap_or(""));
},
"max-results" => {
call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer"));
},
"include-inactive" => {
call = call.include_inactive(arg_from_str(value.unwrap_or("false"), err, "include-inactive", "boolean"));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["include-inactive", "max-results", "page-token"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit().await,
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
async fn _customchannels_get(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.customchannels().get(opt.value_of("ad-client-id").unwrap_or(""), opt.value_of("custom-channel-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit().await,
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
async fn _customchannels_list(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.customchannels().list(opt.value_of("ad-client-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"page-token" => {
call = call.page_token(value.unwrap_or(""));
},
"max-results" => {
call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer"));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["max-results", "page-token"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit().await,
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
async fn _metadata_dimensions_list(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.metadata().dimensions_list();
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit().await,
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
async fn _metadata_metrics_list(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.metadata().metrics_list();
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit().await,
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
async fn _payments_list(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.payments().list();
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit().await,
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
async fn _reports_generate(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut download_mode = false;
let mut call = self.hub.reports().generate(opt.value_of("start-date").unwrap_or(""), opt.value_of("end-date").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"use-timezone-reporting" => {
call = call.use_timezone_reporting(arg_from_str(value.unwrap_or("false"), err, "use-timezone-reporting", "boolean"));
},
"start-index" => {
call = call.start_index(arg_from_str(value.unwrap_or("-0"), err, "start-index", "integer"));
},
"sort" => {
call = call.add_sort(value.unwrap_or(""));
},
"metric" => {
call = call.add_metric(value.unwrap_or(""));
},
"max-results" => {
call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer"));
},
"locale" => {
call = call.locale(value.unwrap_or(""));
},
"filter" => {
call = call.add_filter(value.unwrap_or(""));
},
"dimension" => {
call = call.add_dimension(value.unwrap_or(""));
},
"currency" => {
call = call.currency(value.unwrap_or(""));
},
"account-id" => {
call = call.add_account_id(value.unwrap_or(""));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
if key == "alt" && value.unwrap_or("unset") == "media" {
download_mode = true;
}
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["account-id", "currency", "dimension", "filter", "locale", "max-results", "metric", "sort", "start-index", "use-timezone-reporting"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit().await,
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
if !download_mode {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
} else {
let bytes = hyper::body::to_bytes(response.into_body()).await.expect("a string as API currently is inefficient").to_vec();
ostream.write_all(&bytes).expect("write to be complete");
ostream.flush().expect("io to never fail which should really be fixed one day");
}
Ok(())
}
}
}
}
async fn _reports_saved_generate(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.reports().saved_generate(opt.value_of("saved-report-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"start-index" => {
call = call.start_index(arg_from_str(value.unwrap_or("-0"), err, "start-index", "integer"));
},
"max-results" => {
call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer"));
},
"locale" => {
call = call.locale(value.unwrap_or(""));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["locale", "max-results", "start-index"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit().await,
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
async fn _reports_saved_list(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.reports().saved_list();
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"page-token" => {
call = call.page_token(value.unwrap_or(""));
},
"max-results" => {
call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer"));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["max-results", "page-token"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit().await,
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
async fn _savedadstyles_get(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.savedadstyles().get(opt.value_of("saved-ad-style-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit().await,
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
async fn _savedadstyles_list(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.savedadstyles().list();
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"page-token" => {
call = call.page_token(value.unwrap_or(""));
},
"max-results" => {
call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer"));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["max-results", "page-token"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit().await,
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
async fn _urlchannels_list(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.urlchannels().list(opt.value_of("ad-client-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"page-token" => {
call = call.page_token(value.unwrap_or(""));
},
"max-results" => {
call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer"));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["max-results", "page-token"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit().await,
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
async fn _doit(&self, dry_run: bool) -> Result<Result<(), DoitError>, Option<InvalidOptionsError>> {
let mut err = InvalidOptionsError::new();
let mut call_result: Result<(), DoitError> = Ok(());
let mut err_opt: Option<InvalidOptionsError> = None;
match self.opt.subcommand() {
("accounts", Some(opt)) => {
match opt.subcommand() {
("adclients-get-ad-code", Some(opt)) => {
call_result = self._accounts_adclients_get_ad_code(opt, dry_run, &mut err).await;
},
("adclients-list", Some(opt)) => {
call_result = self._accounts_adclients_list(opt, dry_run, &mut err).await;
},
("adunits-customchannels-list", Some(opt)) => {
call_result = self._accounts_adunits_customchannels_list(opt, dry_run, &mut err).await;
},
("adunits-get", Some(opt)) => {
call_result = self._accounts_adunits_get(opt, dry_run, &mut err).await;
},
("adunits-get-ad-code", Some(opt)) => {
call_result = self._accounts_adunits_get_ad_code(opt, dry_run, &mut err).await;
},
("adunits-list", Some(opt)) => {
call_result = self._accounts_adunits_list(opt, dry_run, &mut err).await;
},
("alerts-delete", Some(opt)) => {
call_result = self._accounts_alerts_delete(opt, dry_run, &mut err).await;
},
("alerts-list", Some(opt)) => {
call_result = self._accounts_alerts_list(opt, dry_run, &mut err).await;
},
("customchannels-adunits-list", Some(opt)) => {
call_result = self._accounts_customchannels_adunits_list(opt, dry_run, &mut err).await;
},
("customchannels-get", Some(opt)) => {
call_result = self._accounts_customchannels_get(opt, dry_run, &mut err).await;
},
("customchannels-list", Some(opt)) => {
call_result = self._accounts_customchannels_list(opt, dry_run, &mut err).await;
},
("get", Some(opt)) => {
call_result = self._accounts_get(opt, dry_run, &mut err).await;
},
("list", Some(opt)) => {
call_result = self._accounts_list(opt, dry_run, &mut err).await;
},
("payments-list", Some(opt)) => {
call_result = self._accounts_payments_list(opt, dry_run, &mut err).await;
},
("reports-generate", Some(opt)) => {
call_result = self._accounts_reports_generate(opt, dry_run, &mut err).await;
},
("reports-saved-generate", Some(opt)) => {
call_result = self._accounts_reports_saved_generate(opt, dry_run, &mut err).await;
},
("reports-saved-list", Some(opt)) => {
call_result = self._accounts_reports_saved_list(opt, dry_run, &mut err).await;
},
("savedadstyles-get", Some(opt)) => {
call_result = self._accounts_savedadstyles_get(opt, dry_run, &mut err).await;
},
("savedadstyles-list", Some(opt)) => {
call_result = self._accounts_savedadstyles_list(opt, dry_run, &mut err).await;
},
("urlchannels-list", Some(opt)) => {
call_result = self._accounts_urlchannels_list(opt, dry_run, &mut err).await;
},
_ => {
err.issues.push(CLIError::MissingMethodError("accounts".to_string()));
writeln!(io::stderr(), "{}\n", opt.usage()).ok();
}
}
},
("adclients", Some(opt)) => {
match opt.subcommand() {
("list", Some(opt)) => {
call_result = self._adclients_list(opt, dry_run, &mut err).await;
},
_ => {
err.issues.push(CLIError::MissingMethodError("adclients".to_string()));
writeln!(io::stderr(), "{}\n", opt.usage()).ok();
}
}
},
("adunits", Some(opt)) => {
match opt.subcommand() {
("customchannels-list", Some(opt)) => {
call_result = self._adunits_customchannels_list(opt, dry_run, &mut err).await;
},
("get", Some(opt)) => {
call_result = self._adunits_get(opt, dry_run, &mut err).await;
},
("get-ad-code", Some(opt)) => {
call_result = self._adunits_get_ad_code(opt, dry_run, &mut err).await;
},
("list", Some(opt)) => {
call_result = self._adunits_list(opt, dry_run, &mut err).await;
},
_ => {
err.issues.push(CLIError::MissingMethodError("adunits".to_string()));
writeln!(io::stderr(), "{}\n", opt.usage()).ok();
}
}
},
("alerts", Some(opt)) => {
match opt.subcommand() {
("delete", Some(opt)) => {
call_result = self._alerts_delete(opt, dry_run, &mut err).await;
},
("list", Some(opt)) => {
call_result = self._alerts_list(opt, dry_run, &mut err).await;
},
_ => {
err.issues.push(CLIError::MissingMethodError("alerts".to_string()));
writeln!(io::stderr(), "{}\n", opt.usage()).ok();
}
}
},
("customchannels", Some(opt)) => {
match opt.subcommand() {
("adunits-list", Some(opt)) => {
call_result = self._customchannels_adunits_list(opt, dry_run, &mut err).await;
},
("get", Some(opt)) => {
call_result = self._customchannels_get(opt, dry_run, &mut err).await;
},
("list", Some(opt)) => {
call_result = self._customchannels_list(opt, dry_run, &mut err).await;
},
_ => {
err.issues.push(CLIError::MissingMethodError("customchannels".to_string()));
writeln!(io::stderr(), "{}\n", opt.usage()).ok();
}
}
},
("metadata", Some(opt)) => {
match opt.subcommand() {
("dimensions-list", Some(opt)) => {
call_result = self._metadata_dimensions_list(opt, dry_run, &mut err).await;
},
("metrics-list", Some(opt)) => {
call_result = self._metadata_metrics_list(opt, dry_run, &mut err).await;
},
_ => {
err.issues.push(CLIError::MissingMethodError("metadata".to_string()));
writeln!(io::stderr(), "{}\n", opt.usage()).ok();
}
}
},
("payments", Some(opt)) => {
match opt.subcommand() {
("list", Some(opt)) => {
call_result = self._payments_list(opt, dry_run, &mut err).await;
},
_ => {
err.issues.push(CLIError::MissingMethodError("payments".to_string()));
writeln!(io::stderr(), "{}\n", opt.usage()).ok();
}
}
},
("reports", Some(opt)) => {
match opt.subcommand() {
("generate", Some(opt)) => {
call_result = self._reports_generate(opt, dry_run, &mut err).await;
},
("saved-generate", Some(opt)) => {
call_result = self._reports_saved_generate(opt, dry_run, &mut err).await;
},
("saved-list", Some(opt)) => {
call_result = self._reports_saved_list(opt, dry_run, &mut err).await;
},
_ => {
err.issues.push(CLIError::MissingMethodError("reports".to_string()));
writeln!(io::stderr(), "{}\n", opt.usage()).ok();
}
}
},
("savedadstyles", Some(opt)) => {
match opt.subcommand() {
("get", Some(opt)) => {
call_result = self._savedadstyles_get(opt, dry_run, &mut err).await;
},
("list", Some(opt)) => {
call_result = self._savedadstyles_list(opt, dry_run, &mut err).await;
},
_ => {
err.issues.push(CLIError::MissingMethodError("savedadstyles".to_string()));
writeln!(io::stderr(), "{}\n", opt.usage()).ok();
}
}
},
("urlchannels", Some(opt)) => {
match opt.subcommand() {
("list", Some(opt)) => {
call_result = self._urlchannels_list(opt, dry_run, &mut err).await;
},
_ => {
err.issues.push(CLIError::MissingMethodError("urlchannels".to_string()));
writeln!(io::stderr(), "{}\n", opt.usage()).ok();
}
}
},
_ => {
err.issues.push(CLIError::MissingCommandError);
writeln!(io::stderr(), "{}\n", self.opt.usage()).ok();
}
}
if dry_run {
if err.issues.len() > 0 {
err_opt = Some(err);
}
Err(err_opt)
} else {
Ok(call_result)
}
}
// Please note that this call will fail if any part of the opt can't be handled
async fn new(opt: ArgMatches<'n>) -> Result<Engine<'n>, InvalidOptionsError> {
let (config_dir, secret) = {
let config_dir = match client::assure_config_dir_exists(opt.value_of("folder").unwrap_or("~/.google-service-cli")) {
Err(e) => return Err(InvalidOptionsError::single(e, 3)),
Ok(p) => p,
};
match client::application_secret_from_directory(&config_dir, "adsense1d4-secret.json",
"{\"installed\":{\"auth_uri\":\"https://accounts.google.com/o/oauth2/auth\",\"client_secret\":\"hCsslbCUyfehWMmbkG8vTYxG\",\"token_uri\":\"https://accounts.google.com/o/oauth2/token\",\"client_email\":\"\",\"redirect_uris\":[\"urn:ietf:wg:oauth:2.0:oob\",\"oob\"],\"client_x509_cert_url\":\"\",\"client_id\":\"620010449518-9ngf7o4dhs0dka470npqvor6dc5lqb9b.apps.googleusercontent.com\",\"auth_provider_x509_cert_url\":\"https://www.googleapis.com/oauth2/v1/certs\"}}") {
Ok(secret) => (config_dir, secret),
Err(e) => return Err(InvalidOptionsError::single(e, 4))
}
};
let auth = oauth2::InstalledFlowAuthenticator::builder(
secret,
oauth2::InstalledFlowReturnMethod::HTTPRedirect,
).persist_tokens_to_disk(format!("{}/adsense1d4", config_dir)).build().await.unwrap();
let client = hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots());
let engine = Engine {
opt: opt,
hub: api::AdSense::new(client, auth),
gp: vec!["alt", "fields", "key", "oauth-token", "pretty-print", "quota-user", "user-ip"],
gpm: vec![
("oauth-token", "oauth_token"),
("pretty-print", "prettyPrint"),
("quota-user", "quotaUser"),
("user-ip", "userIp"),
]
};
match engine._doit(true).await {
Err(Some(err)) => Err(err),
Err(None) => Ok(engine),
Ok(_) => unreachable!(),
}
}
async fn doit(&self) -> Result<(), DoitError> {
match self._doit(false).await {
Ok(res) => res,
Err(_) => unreachable!(),
}
}
}
#[tokio::main]
async fn main() {
let mut exit_status = 0i32;
let arg_data = [
("accounts", "methods: 'adclients-get-ad-code', 'adclients-list', 'adunits-customchannels-list', 'adunits-get', 'adunits-get-ad-code', 'adunits-list', 'alerts-delete', 'alerts-list', 'customchannels-adunits-list', 'customchannels-get', 'customchannels-list', 'get', 'list', 'payments-list', 'reports-generate', 'reports-saved-generate', 'reports-saved-list', 'savedadstyles-get', 'savedadstyles-list' and 'urlchannels-list'", vec![
("adclients-get-ad-code",
Some(r##"Get Auto ad code for a given ad client."##),
"Details at http://byron.github.io/google-apis-rs/google_adsense1d4_cli/accounts_adclients-get-ad-code",
vec![
(Some(r##"account-id"##),
None,
Some(r##"Account which contains the ad client."##),
Some(true),
Some(false)),
(Some(r##"ad-client-id"##),
None,
Some(r##"Ad client to get the code for."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("adclients-list",
Some(r##"List all ad clients in the specified account."##),
"Details at http://byron.github.io/google-apis-rs/google_adsense1d4_cli/accounts_adclients-list",
vec![
(Some(r##"account-id"##),
None,
Some(r##"Account for which to list ad clients."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("adunits-customchannels-list",
Some(r##"List all custom channels which the specified ad unit belongs to."##),
"Details at http://byron.github.io/google-apis-rs/google_adsense1d4_cli/accounts_adunits-customchannels-list",
vec![
(Some(r##"account-id"##),
None,
Some(r##"Account to which the ad client belongs."##),
Some(true),
Some(false)),
(Some(r##"ad-client-id"##),
None,
Some(r##"Ad client which contains the ad unit."##),
Some(true),
Some(false)),
(Some(r##"ad-unit-id"##),
None,
Some(r##"Ad unit for which to list custom channels."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("adunits-get",
Some(r##"Gets the specified ad unit in the specified ad client for the specified account."##),
"Details at http://byron.github.io/google-apis-rs/google_adsense1d4_cli/accounts_adunits-get",
vec![
(Some(r##"account-id"##),
None,
Some(r##"Account to which the ad client belongs."##),
Some(true),
Some(false)),
(Some(r##"ad-client-id"##),
None,
Some(r##"Ad client for which to get the ad unit."##),
Some(true),
Some(false)),
(Some(r##"ad-unit-id"##),
None,
Some(r##"Ad unit to retrieve."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("adunits-get-ad-code",
Some(r##"Get ad code for the specified ad unit."##),
"Details at http://byron.github.io/google-apis-rs/google_adsense1d4_cli/accounts_adunits-get-ad-code",
vec![
(Some(r##"account-id"##),
None,
Some(r##"Account which contains the ad client."##),
Some(true),
Some(false)),
(Some(r##"ad-client-id"##),
None,
Some(r##"Ad client with contains the ad unit."##),
Some(true),
Some(false)),
(Some(r##"ad-unit-id"##),
None,
Some(r##"Ad unit to get the code for."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("adunits-list",
Some(r##"List all ad units in the specified ad client for the specified account."##),
"Details at http://byron.github.io/google-apis-rs/google_adsense1d4_cli/accounts_adunits-list",
vec![
(Some(r##"account-id"##),
None,
Some(r##"Account to which the ad client belongs."##),
Some(true),
Some(false)),
(Some(r##"ad-client-id"##),
None,
Some(r##"Ad client for which to list ad units."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("alerts-delete",
Some(r##"Dismiss (delete) the specified alert from the specified publisher AdSense account."##),
"Details at http://byron.github.io/google-apis-rs/google_adsense1d4_cli/accounts_alerts-delete",
vec![
(Some(r##"account-id"##),
None,
Some(r##"Account which contains the ad unit."##),
Some(true),
Some(false)),
(Some(r##"alert-id"##),
None,
Some(r##"Alert to delete."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
]),
("alerts-list",
Some(r##"List the alerts for the specified AdSense account."##),
"Details at http://byron.github.io/google-apis-rs/google_adsense1d4_cli/accounts_alerts-list",
vec![
(Some(r##"account-id"##),
None,
Some(r##"Account for which to retrieve the alerts."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("customchannels-adunits-list",
Some(r##"List all ad units in the specified custom channel."##),
"Details at http://byron.github.io/google-apis-rs/google_adsense1d4_cli/accounts_customchannels-adunits-list",
vec![
(Some(r##"account-id"##),
None,
Some(r##"Account to which the ad client belongs."##),
Some(true),
Some(false)),
(Some(r##"ad-client-id"##),
None,
Some(r##"Ad client which contains the custom channel."##),
Some(true),
Some(false)),
(Some(r##"custom-channel-id"##),
None,
Some(r##"Custom channel for which to list ad units."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("customchannels-get",
Some(r##"Get the specified custom channel from the specified ad client for the specified account."##),
"Details at http://byron.github.io/google-apis-rs/google_adsense1d4_cli/accounts_customchannels-get",
vec![
(Some(r##"account-id"##),
None,
Some(r##"Account to which the ad client belongs."##),
Some(true),
Some(false)),
(Some(r##"ad-client-id"##),
None,
Some(r##"Ad client which contains the custom channel."##),
Some(true),
Some(false)),
(Some(r##"custom-channel-id"##),
None,
Some(r##"Custom channel to retrieve."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("customchannels-list",
Some(r##"List all custom channels in the specified ad client for the specified account."##),
"Details at http://byron.github.io/google-apis-rs/google_adsense1d4_cli/accounts_customchannels-list",
vec![
(Some(r##"account-id"##),
None,
Some(r##"Account to which the ad client belongs."##),
Some(true),
Some(false)),
(Some(r##"ad-client-id"##),
None,
Some(r##"Ad client for which to list custom channels."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("get",
Some(r##"Get information about the selected AdSense account."##),
"Details at http://byron.github.io/google-apis-rs/google_adsense1d4_cli/accounts_get",
vec![
(Some(r##"account-id"##),
None,
Some(r##"Account to get information about."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("list",
Some(r##"List all accounts available to this AdSense account."##),
"Details at http://byron.github.io/google-apis-rs/google_adsense1d4_cli/accounts_list",
vec![
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("payments-list",
Some(r##"List the payments for the specified AdSense account."##),
"Details at http://byron.github.io/google-apis-rs/google_adsense1d4_cli/accounts_payments-list",
vec![
(Some(r##"account-id"##),
None,
Some(r##"Account for which to retrieve the payments."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("reports-generate",
Some(r##"Generate an AdSense report based on the report request sent in the query parameters. Returns the result as JSON; to retrieve output in CSV format specify "alt=csv" as a query parameter."##),
"Details at http://byron.github.io/google-apis-rs/google_adsense1d4_cli/accounts_reports-generate",
vec![
(Some(r##"account-id"##),
None,
Some(r##"Account upon which to report."##),
Some(true),
Some(false)),
(Some(r##"start-date"##),
None,
Some(r##"Start of the date range to report on in "YYYY-MM-DD" format, inclusive."##),
Some(true),
Some(false)),
(Some(r##"end-date"##),
None,
Some(r##"End of the date range to report on in "YYYY-MM-DD" format, inclusive."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("reports-saved-generate",
Some(r##"Generate an AdSense report based on the saved report ID sent in the query parameters."##),
"Details at http://byron.github.io/google-apis-rs/google_adsense1d4_cli/accounts_reports-saved-generate",
vec![
(Some(r##"account-id"##),
None,
Some(r##"Account to which the saved reports belong."##),
Some(true),
Some(false)),
(Some(r##"saved-report-id"##),
None,
Some(r##"The saved report to retrieve."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("reports-saved-list",
Some(r##"List all saved reports in the specified AdSense account."##),
"Details at http://byron.github.io/google-apis-rs/google_adsense1d4_cli/accounts_reports-saved-list",
vec![
(Some(r##"account-id"##),
None,
Some(r##"Account to which the saved reports belong."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("savedadstyles-get",
Some(r##"List a specific saved ad style for the specified account."##),
"Details at http://byron.github.io/google-apis-rs/google_adsense1d4_cli/accounts_savedadstyles-get",
vec![
(Some(r##"account-id"##),
None,
Some(r##"Account for which to get the saved ad style."##),
Some(true),
Some(false)),
(Some(r##"saved-ad-style-id"##),
None,
Some(r##"Saved ad style to retrieve."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("savedadstyles-list",
Some(r##"List all saved ad styles in the specified account."##),
"Details at http://byron.github.io/google-apis-rs/google_adsense1d4_cli/accounts_savedadstyles-list",
vec![
(Some(r##"account-id"##),
None,
Some(r##"Account for which to list saved ad styles."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("urlchannels-list",
Some(r##"List all URL channels in the specified ad client for the specified account."##),
"Details at http://byron.github.io/google-apis-rs/google_adsense1d4_cli/accounts_urlchannels-list",
vec![
(Some(r##"account-id"##),
None,
Some(r##"Account to which the ad client belongs."##),
Some(true),
Some(false)),
(Some(r##"ad-client-id"##),
None,
Some(r##"Ad client for which to list URL channels."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
]),
("adclients", "methods: 'list'", vec![
("list",
Some(r##"List all ad clients in this AdSense account."##),
"Details at http://byron.github.io/google-apis-rs/google_adsense1d4_cli/adclients_list",
vec![
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
]),
("adunits", "methods: 'customchannels-list', 'get', 'get-ad-code' and 'list'", vec![
("customchannels-list",
Some(r##"List all custom channels which the specified ad unit belongs to."##),
"Details at http://byron.github.io/google-apis-rs/google_adsense1d4_cli/adunits_customchannels-list",
vec![
(Some(r##"ad-client-id"##),
None,
Some(r##"Ad client which contains the ad unit."##),
Some(true),
Some(false)),
(Some(r##"ad-unit-id"##),
None,
Some(r##"Ad unit for which to list custom channels."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("get",
Some(r##"Gets the specified ad unit in the specified ad client."##),
"Details at http://byron.github.io/google-apis-rs/google_adsense1d4_cli/adunits_get",
vec![
(Some(r##"ad-client-id"##),
None,
Some(r##"Ad client for which to get the ad unit."##),
Some(true),
Some(false)),
(Some(r##"ad-unit-id"##),
None,
Some(r##"Ad unit to retrieve."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("get-ad-code",
Some(r##"Get ad code for the specified ad unit."##),
"Details at http://byron.github.io/google-apis-rs/google_adsense1d4_cli/adunits_get-ad-code",
vec![
(Some(r##"ad-client-id"##),
None,
Some(r##"Ad client with contains the ad unit."##),
Some(true),
Some(false)),
(Some(r##"ad-unit-id"##),
None,
Some(r##"Ad unit to get the code for."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("list",
Some(r##"List all ad units in the specified ad client for this AdSense account."##),
"Details at http://byron.github.io/google-apis-rs/google_adsense1d4_cli/adunits_list",
vec![
(Some(r##"ad-client-id"##),
None,
Some(r##"Ad client for which to list ad units."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
]),
("alerts", "methods: 'delete' and 'list'", vec![
("delete",
Some(r##"Dismiss (delete) the specified alert from the publisher's AdSense account."##),
"Details at http://byron.github.io/google-apis-rs/google_adsense1d4_cli/alerts_delete",
vec![
(Some(r##"alert-id"##),
None,
Some(r##"Alert to delete."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
]),
("list",
Some(r##"List the alerts for this AdSense account."##),
"Details at http://byron.github.io/google-apis-rs/google_adsense1d4_cli/alerts_list",
vec![
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
]),
("customchannels", "methods: 'adunits-list', 'get' and 'list'", vec![
("adunits-list",
Some(r##"List all ad units in the specified custom channel."##),
"Details at http://byron.github.io/google-apis-rs/google_adsense1d4_cli/customchannels_adunits-list",
vec![
(Some(r##"ad-client-id"##),
None,
Some(r##"Ad client which contains the custom channel."##),
Some(true),
Some(false)),
(Some(r##"custom-channel-id"##),
None,
Some(r##"Custom channel for which to list ad units."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("get",
Some(r##"Get the specified custom channel from the specified ad client."##),
"Details at http://byron.github.io/google-apis-rs/google_adsense1d4_cli/customchannels_get",
vec![
(Some(r##"ad-client-id"##),
None,
Some(r##"Ad client which contains the custom channel."##),
Some(true),
Some(false)),
(Some(r##"custom-channel-id"##),
None,
Some(r##"Custom channel to retrieve."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("list",
Some(r##"List all custom channels in the specified ad client for this AdSense account."##),
"Details at http://byron.github.io/google-apis-rs/google_adsense1d4_cli/customchannels_list",
vec![
(Some(r##"ad-client-id"##),
None,
Some(r##"Ad client for which to list custom channels."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
]),
("metadata", "methods: 'dimensions-list' and 'metrics-list'", vec![
("dimensions-list",
Some(r##"List the metadata for the dimensions available to this AdSense account."##),
"Details at http://byron.github.io/google-apis-rs/google_adsense1d4_cli/metadata_dimensions-list",
vec![
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("metrics-list",
Some(r##"List the metadata for the metrics available to this AdSense account."##),
"Details at http://byron.github.io/google-apis-rs/google_adsense1d4_cli/metadata_metrics-list",
vec![
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
]),
("payments", "methods: 'list'", vec![
("list",
Some(r##"List the payments for this AdSense account."##),
"Details at http://byron.github.io/google-apis-rs/google_adsense1d4_cli/payments_list",
vec![
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
]),
("reports", "methods: 'generate', 'saved-generate' and 'saved-list'", vec![
("generate",
Some(r##"Generate an AdSense report based on the report request sent in the query parameters. Returns the result as JSON; to retrieve output in CSV format specify "alt=csv" as a query parameter."##),
"Details at http://byron.github.io/google-apis-rs/google_adsense1d4_cli/reports_generate",
vec![
(Some(r##"start-date"##),
None,
Some(r##"Start of the date range to report on in "YYYY-MM-DD" format, inclusive."##),
Some(true),
Some(false)),
(Some(r##"end-date"##),
None,
Some(r##"End of the date range to report on in "YYYY-MM-DD" format, inclusive."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("saved-generate",
Some(r##"Generate an AdSense report based on the saved report ID sent in the query parameters."##),
"Details at http://byron.github.io/google-apis-rs/google_adsense1d4_cli/reports_saved-generate",
vec![
(Some(r##"saved-report-id"##),
None,
Some(r##"The saved report to retrieve."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("saved-list",
Some(r##"List all saved reports in this AdSense account."##),
"Details at http://byron.github.io/google-apis-rs/google_adsense1d4_cli/reports_saved-list",
vec![
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
]),
("savedadstyles", "methods: 'get' and 'list'", vec![
("get",
Some(r##"Get a specific saved ad style from the user's account."##),
"Details at http://byron.github.io/google-apis-rs/google_adsense1d4_cli/savedadstyles_get",
vec![
(Some(r##"saved-ad-style-id"##),
None,
Some(r##"Saved ad style to retrieve."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("list",
Some(r##"List all saved ad styles in the user's account."##),
"Details at http://byron.github.io/google-apis-rs/google_adsense1d4_cli/savedadstyles_list",
vec![
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
]),
("urlchannels", "methods: 'list'", vec![
("list",
Some(r##"List all URL channels in the specified ad client for this AdSense account."##),
"Details at http://byron.github.io/google-apis-rs/google_adsense1d4_cli/urlchannels_list",
vec![
(Some(r##"ad-client-id"##),
None,
Some(r##"Ad client for which to list URL channels."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
]),
];
let mut app = App::new("adsense1d4")
.author("Sebastian Thiel <byronimo@gmail.com>")
.version("3.0.0+20201002")
.about("Accesses AdSense publishers' inventory and generates performance reports.")
.after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_adsense1d4_cli")
.arg(Arg::with_name("url")
.long("scope")
.help("Specify the authentication a method should be executed in. Each scope requires the user to grant this application permission to use it.If unset, it defaults to the shortest scope url for a particular method.")
.multiple(true)
.takes_value(true))
.arg(Arg::with_name("folder")
.long("config-dir")
.help("A directory into which we will store our persistent data. Defaults to a user-writable directory that we will create during the first invocation.[default: ~/.google-service-cli")
.multiple(false)
.takes_value(true))
.arg(Arg::with_name("debug")
.long("debug")
.help("Debug print all errors")
.multiple(false)
.takes_value(false));
for &(main_command_name, about, ref subcommands) in arg_data.iter() {
let mut mcmd = SubCommand::with_name(main_command_name).about(about);
for &(sub_command_name, ref desc, url_info, ref args) in subcommands {
let mut scmd = SubCommand::with_name(sub_command_name);
if let &Some(desc) = desc {
scmd = scmd.about(desc);
}
scmd = scmd.after_help(url_info);
for &(ref arg_name, ref flag, ref desc, ref required, ref multi) in args {
let arg_name_str =
match (arg_name, flag) {
(&Some(an), _ ) => an,
(_ , &Some(f)) => f,
_ => unreachable!(),
};
let mut arg = Arg::with_name(arg_name_str)
.empty_values(false);
if let &Some(short_flag) = flag {
arg = arg.short(short_flag);
}
if let &Some(desc) = desc {
arg = arg.help(desc);
}
if arg_name.is_some() && flag.is_some() {
arg = arg.takes_value(true);
}
if let &Some(required) = required {
arg = arg.required(required);
}
if let &Some(multi) = multi {
arg = arg.multiple(multi);
}
scmd = scmd.arg(arg);
}
mcmd = mcmd.subcommand(scmd);
}
app = app.subcommand(mcmd);
}
let matches = app.get_matches();
let debug = matches.is_present("debug");
match Engine::new(matches).await {
Err(err) => {
exit_status = err.exit_code;
writeln!(io::stderr(), "{}", err).ok();
},
Ok(engine) => {
if let Err(doit_err) = engine.doit().await {
exit_status = 1;
match doit_err {
DoitError::IoError(path, err) => {
writeln!(io::stderr(), "Failed to open output file '{}': {}", path, err).ok();
},
DoitError::ApiError(err) => {
if debug {
writeln!(io::stderr(), "{:#?}", err).ok();
} else {
writeln!(io::stderr(), "{}", err).ok();
}
}
}
}
}
}
std::process::exit(exit_status);
}
| 47.896211 | 526 | 0.404923 |
f69bd62683277c12f3b9b5f200c9872d6ed7fc9f | 1,638 | dart | Dart | lib/0_provider_overview/provider_overview_11/counter.dart | md-siam/provider_tutorial | 32fb5b4b2838e7869e44020689ae50931c1615ea | [
"MIT"
] | null | null | null | lib/0_provider_overview/provider_overview_11/counter.dart | md-siam/provider_tutorial | 32fb5b4b2838e7869e44020689ae50931c1615ea | [
"MIT"
] | null | null | null | lib/0_provider_overview/provider_overview_11/counter.dart | md-siam/provider_tutorial | 32fb5b4b2838e7869e44020689ae50931c1615ea | [
"MIT"
] | null | null | null | import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'count_notifier.dart';
class MyCounterApp extends StatelessWidget {
const MyCounterApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Counter',
debugShowCheckedModeBanner: false,
theme: ThemeData(primaryColor: Colors.blue),
home: const CounterHomePage(),
);
}
}
class CounterHomePage extends StatelessWidget {
const CounterHomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: ChangeNotifierProvider<Counter>(
create: (_) => Counter(),
child: Builder(
builder: (context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'${context.watch<Counter>().counter}',
style: const TextStyle(
fontSize: 50.0,
),
),
const SizedBox(height: 20.0),
ElevatedButton(
child: const Text(
'Increment',
style: TextStyle(
fontSize: 20.0,
),
),
onPressed: () {
context.read<Counter>().increment();
},
),
],
);
},
),
),
),
);
}
}
| 27.3 | 60 | 0.473138 |
79cdd94603fdc7a856ce2923544bd81ff24d03a3 | 3,118 | kt | Kotlin | android/testSrc/com/android/tools/idea/gradle/project/upgrade/AgpUpgradeAssistantIntegrationTest.kt | phpc0de/idea-android | 79e20f027ca1d047b91aa7acd92fb71fa2968a09 | [
"Apache-2.0"
] | null | null | null | android/testSrc/com/android/tools/idea/gradle/project/upgrade/AgpUpgradeAssistantIntegrationTest.kt | phpc0de/idea-android | 79e20f027ca1d047b91aa7acd92fb71fa2968a09 | [
"Apache-2.0"
] | null | null | null | android/testSrc/com/android/tools/idea/gradle/project/upgrade/AgpUpgradeAssistantIntegrationTest.kt | phpc0de/idea-android | 79e20f027ca1d047b91aa7acd92fb71fa2968a09 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2020 The Android Open Source Project
*
* 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
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.gradle.project.upgrade
import com.android.ide.common.repository.GradleVersion
import com.android.tools.idea.gradle.project.facet.gradle.GradleFacet
import com.android.tools.idea.projectsystem.ProjectSystemService
import com.android.tools.idea.projectsystem.ProjectSystemSyncManager.SyncResult.SUCCESS
import com.android.tools.idea.testing.AndroidGradleTestCase
import com.google.common.truth.Truth.assertThat
import com.intellij.openapi.module.ModuleManager
import java.io.File
class AgpUpgradeAssistantIntegrationTest : AndroidGradleTestCase() {
fun testUpgradeBasic40() {
loadProject("upgrade/Projects/Basic40", null, "6.1.1", "4.0.0", "1.3.72")
val appModule = ModuleManager.getInstance(project).modules.first { it.name == "Basic40.app" }
assertThat(ProjectSystemService.getInstance(project).projectSystem.getSyncManager().getLastSyncResult()).isEqualTo(SUCCESS)
assertThat(GradleFacet.getInstance(appModule)?.configuration?.LAST_SUCCESSFUL_SYNC_AGP_VERSION).isEqualTo("4.0.0")
val processor = AgpUpgradeRefactoringProcessor(project, GradleVersion.parse("4.0.0"), GradleVersion.parse("4.1.0"))
processor.run()
assertThat(ProjectSystemService.getInstance(project).projectSystem.getSyncManager().getLastSyncResult()).isEqualTo(SUCCESS)
assertThat(GradleFacet.getInstance(appModule)?.configuration?.LAST_SUCCESSFUL_SYNC_AGP_VERSION).isEqualTo("4.1.0")
// We can't straightforwardly assert the exact contents of build.gradle, because the test infrastructure patches it with repository
// declarations to make it work in the test environment
val projectBuildFile = File(project.basePath, "build.gradle")
val projectBuildFileLines = projectBuildFile.readLines().map { it.trim() }
assertThat(projectBuildFileLines).contains("classpath 'com.android.tools.build:gradle:4.1.0'")
assertThat(projectBuildFileLines).doesNotContain("google()")
assertThat(projectBuildFileLines).contains("ext.kotlin_version = \"1.3.72\"")
val appBuildFile = File(File(project.basePath, "app"), "build.gradle")
assertThat(appBuildFile.readText()).isEqualTo(File(File(project.basePath, "app"), "build.gradle.expected").readText())
val gradleWrapperFile = File(File(File(project.basePath, "gradle"), "wrapper"), "gradle-wrapper.properties")
val distributionUrlLine = gradleWrapperFile.readLines().first { it.contains("distributionUrl") }
assertThat(distributionUrlLine).contains("gradle-7.0.2-bin.zip")
}
} | 55.678571 | 135 | 0.776139 |
02b7b32dc130e49902517d8d0c5b4360f7a172ea | 3,984 | lua | Lua | General.lua | Road-block/TinyTooltip | 76460bb00a1d2a0b7c6942123a4600def84b2ffe | [
"MIT"
] | 4 | 2022-01-27T07:38:06.000Z | 2022-03-24T12:04:56.000Z | General.lua | Road-block/TinyTooltip | 76460bb00a1d2a0b7c6942123a4600def84b2ffe | [
"MIT"
] | null | null | null | General.lua | Road-block/TinyTooltip | 76460bb00a1d2a0b7c6942123a4600def84b2ffe | [
"MIT"
] | null | null | null |
local LibEvent = LibStub:GetLibrary("LibEvent.7000")
local DEAD = DEAD
local CopyTable = CopyTable
local addon = TinyTooltip
BigTipDB = {}
TinyTooltipCharacterDB = {}
local function ColorStatusBar(self, value)
if (addon.db.general.statusbarColor == "auto") then
local unit = "mouseover"
local focus = GetMouseFocus()
if (focus and focus.unit) then
unit = focus.unit
end
local r, g, b
if (UnitIsPlayer(unit)) then
r, g, b = GetClassColor(select(2,UnitClass(unit)))
else
r, g, b = GameTooltip_UnitColor(unit)
if (g == 0.6) then g = 0.9 end
if (r==1 and g==1 and b==1) then r, g, b = 0, 0.9, 0.1 end
end
self:SetStatusBarColor(r, g, b)
elseif (value and addon.db.general.statusbarColor == "smooth") then
HealthBar_OnValueChanged(self, value, true)
end
end
LibEvent:attachEvent("VARIABLES_LOADED", function()
--CloseButton
if (ItemRefCloseButton and not IsAddOnLoaded("ElvUI")) then
ItemRefCloseButton:SetSize(14, 14)
ItemRefCloseButton:SetPoint("TOPRIGHT", -4, -4)
ItemRefCloseButton:SetNormalTexture("Interface\\\Buttons\\UI-StopButton")
ItemRefCloseButton:SetPushedTexture("Interface\\\Buttons\\UI-StopButton")
ItemRefCloseButton:GetNormalTexture():SetVertexColor(0.9, 0.6, 0)
end
--StatusBar
local bar = GameTooltipStatusBar
bar.bg = bar:CreateTexture(nil, "BACKGROUND")
bar.bg:SetAllPoints()
bar.bg:SetColorTexture(1, 1, 1)
bar.bg:SetVertexColor(0.2, 0.2, 0.2, 0.8)
bar.TextString = bar:CreateFontString(nil, "OVERLAY")
bar.TextString:SetPoint("CENTER")
bar.TextString:SetFont(NumberFontNormal:GetFont(), 11, "THINOUTLINE")
bar.capNumericDisplay = true
bar.lockShow = 1
bar:HookScript("OnShow", function(self)
ColorStatusBar(self)
end)
bar:HookScript("OnValueChanged", function(self, hp)
if (hp <= 0) then
local min, max = self:GetMinMaxValues()
self.TextString:SetFormattedText("|cff999999%s|r |cffffcc33<%s>|r", AbbreviateLargeNumbers(max), DEAD)
else
TextStatusBar_UpdateTextString(self)
end
ColorStatusBar(self, hp)
end)
bar:HookScript("OnShow", function(self)
if (addon.db.general.statusbarHeight == 0) then
self:Hide()
end
end)
--Variable
addon.db = addon:MergeVariable(addon.db, BigTipDB)
if (addon.db.general.SavedVariablesPerCharacter) then
local db = CopyTable(addon.db)
addon.db = addon:MergeVariable(db, TinyTooltipCharacterDB)
end
LibEvent:trigger("tooltip:variables:loaded")
--Init
LibEvent:trigger("TINYTOOLTIP_GENERAL_INIT")
--ShadowText
GameTooltipHeaderText:SetShadowOffset(1, -1)
GameTooltipHeaderText:SetShadowColor(0, 0, 0, 0.9)
GameTooltipText:SetShadowOffset(1, -1)
GameTooltipText:SetShadowColor(0, 0, 0, 0.9)
Tooltip_Small:SetShadowOffset(1, -1)
Tooltip_Small:SetShadowColor(0, 0, 0, 0.9)
end)
LibEvent:attachTrigger("tooltip:cleared, tooltip:hide", function(self, tip)
LibEvent:trigger("tooltip.style.border.color", tip, unpack(addon.db.general.borderColor))
LibEvent:trigger("tooltip.style.background", tip, unpack(addon.db.general.background))
if (tip.BigFactionIcon) then tip.BigFactionIcon:Hide() end
if tip.SetBackdrop then
tip:SetBackdrop(nil)
elseif tip.NineSlice then
tip.NineSlice:Hide()
end
end)
LibEvent:attachTrigger("tooltip:show", function(self, tip)
if (tip ~= GameTooltip) then return end
LibEvent:trigger("tooltip.statusbar.position", addon.db.general.statusbarPosition, addon.db.general.statusbarOffsetX, addon.db.general.statusbarOffsetY)
local w = GameTooltipStatusBar.TextString:GetWidth() + 10
if (GameTooltipStatusBar:IsShown() and w > tip:GetWidth()) then
tip:SetMinimumWidth(w+2)
tip:Show()
end
end)
| 36.888889 | 156 | 0.673444 |
86180e3d99aeb57751c5725d4bc61c889c016899 | 150 | go | Go | event/reply.go | frolFomich/message | 33015efc68ba9a38266f30815942cd1c26cd1f33 | [
"Apache-2.0"
] | null | null | null | event/reply.go | frolFomich/message | 33015efc68ba9a38266f30815942cd1c26cd1f33 | [
"Apache-2.0"
] | null | null | null | event/reply.go | frolFomich/message | 33015efc68ba9a38266f30815942cd1c26cd1f33 | [
"Apache-2.0"
] | null | null | null | package event
type Reply interface {
Event
Items() interface{}
HasMore() interface{}
}
type ReplayReply interface {
Reply
SubjectId() string
}
| 11.538462 | 28 | 0.726667 |
22efe3f84f3436eb3b8ea09ca9829fddb8a35343 | 730 | h | C | MeetRTCSDK/MeetRTCSDK/WebRTCAVRecordingDelegate.h | Teamxrtc/MeetRTC_iOS | 62ea0539ce03f6e24b059803310a8d41f97784c4 | [
"Apache-2.0"
] | 44 | 2016-01-21T05:37:48.000Z | 2020-11-05T15:12:56.000Z | MeetRTC/libs/include/MeetRTCSDK/WebRTCAVRecordingDelegate.h | sahwar/MeetRTC_iOS | 62ea0539ce03f6e24b059803310a8d41f97784c4 | [
"Apache-2.0"
] | 18 | 2016-01-21T08:37:24.000Z | 2018-05-04T12:58:11.000Z | MeetRTC/libs/include/MeetRTCSDK/WebRTCAVRecordingDelegate.h | sahwar/MeetRTC_iOS | 62ea0539ce03f6e24b059803310a8d41f97784c4 | [
"Apache-2.0"
] | 27 | 2016-01-21T07:51:21.000Z | 2021-01-25T09:02:31.000Z | //
// WebRTCRecordingDelegate.m
// meet-webrtc-sdk
//
// Created by Gupta, Harish on 5/13/15.
// Copyright 2014 Comcast Cable Communications Management, LLC
//
#import <Foundation/Foundation.h>
typedef enum
{
WebRTCAVRecordingStarted,
WebRTCAVRecordingEnded,
WebRTCAVRecordingWarning,
} RecordingEventTypes;
extern NSString * const WebRTCRecordEventKey;
extern NSString * const WebRTCRecordEventDetailKey;
@protocol WebRTCAVRecordingDelegate <NSObject>
/** Recording state consist:
* Event: Type of event, e.g. WebRTCAVRecordingStarted
* Event Description: Reason for the event.
**/
- (void) onRecordingEvent:(NSDictionary *)state;
- (void) onRecordingError:(NSString*)error errorCode:(NSInteger)code;
@end | 27.037037 | 69 | 0.765753 |
4080cbc74aab13bf70b7493d894d9ac6bdeeaca7 | 3,779 | py | Python | ibl/datasets/pitts.py | adujardin/OpenIBL | ad708f80e2d1618c763cd18f128bcefc5758d518 | [
"MIT"
] | 182 | 2020-08-05T12:36:46.000Z | 2022-03-17T01:50:53.000Z | ibl/datasets/pitts.py | CaiYingFeng/OpenIBL | 5ab80d65afa42ca22210c4c08983fdc156696bab | [
"MIT"
] | 32 | 2020-08-24T19:16:32.000Z | 2022-03-26T02:07:53.000Z | ibl/datasets/pitts.py | CaiYingFeng/OpenIBL | 5ab80d65afa42ca22210c4c08983fdc156696bab | [
"MIT"
] | 42 | 2020-08-15T03:42:06.000Z | 2022-03-23T09:28:47.000Z | from __future__ import print_function, absolute_import
import os.path as osp
from collections import namedtuple
import torch.distributed as dist
from ..utils.data import Dataset
from ..utils.osutils import mkdir_if_missing
from ..utils.serialization import write_json, read_mat
from ..utils.dist_utils import synchronize
def parse_dbStruct(path):
matStruct = read_mat(path)
dbImage = [f[0].item() for f in matStruct[1]]
utmDb = matStruct[2].T
qImage = [f[0].item() for f in matStruct[3]]
utmQ = matStruct[4].T
numDb = matStruct[5].item()
numQ = matStruct[6].item()
dbStruct = namedtuple('dbStruct',
['dbImage', 'utmDb', 'qImage', 'utmQ', 'numDb', 'numQ'])
return dbStruct(dbImage, utmDb, qImage, utmQ, numDb, numQ)
class Pittsburgh(Dataset):
def __init__(self, root, scale='250k', verbose=True):
super(Pittsburgh, self).__init__(root)
self.scale = scale
self.arrange()
self.load(verbose, scale)
def arrange(self):
if self._check_integrity(self.scale):
return
raw_dir = osp.join(self.root, 'raw')
if (not osp.isdir(raw_dir)):
raise RuntimeError("Dataset not found.")
db_root = osp.join('Pittsburgh', 'images')
q_root = osp.join('Pittsburgh', 'queries')
identities = []
utms = []
q_pids, db_pids = {}, {}
def register(split):
struct = parse_dbStruct(osp.join(raw_dir, 'pitts'+self.scale+'_'+split+'.mat'))
q_ids = []
for fpath, utm in zip(struct.qImage, struct.utmQ):
sid = fpath.split('_')[0]
if (sid not in q_pids.keys()):
pid = len(identities)
q_pids[sid] = pid
identities.append([])
utms.append(utm.tolist())
q_ids.append(pid)
identities[q_pids[sid]].append(osp.join(q_root, fpath))
assert(utms[q_pids[sid]]==utm.tolist())
db_ids = []
for fpath, utm in zip(struct.dbImage, struct.utmDb):
sid = fpath.split('_')[0]
if (sid not in db_pids.keys()):
pid = len(identities)
db_pids[sid] = pid
identities.append([])
utms.append(utm.tolist())
db_ids.append(pid)
identities[db_pids[sid]].append(osp.join(db_root, fpath))
assert(utms[db_pids[sid]]==utm.tolist())
return q_ids, db_ids
q_train_pids, db_train_pids = register('train')
# train_pids = q_train_pids + db_train_pids
q_val_pids, db_val_pids = register('val')
q_test_pids, db_test_pids = register('test')
assert len(identities)==len(utms)
# for pid in q_test_pids:
# if (len(identities[pid])!=24):
# print (identities[pid])
# Save meta information into a json file
meta = {'name': 'Pittsburgh_'+self.scale,
'identities': identities, 'utm': utms}
try:
rank = dist.get_rank()
except:
rank = 0
if rank == 0:
write_json(meta, osp.join(self.root, 'meta_'+self.scale+'.json'))
# Save the training / test split
splits = {
# 'train': sorted(train_pids),
'q_train': sorted(q_train_pids),
'db_train': sorted(db_train_pids),
'q_val': sorted(q_val_pids),
'db_val': sorted(db_val_pids),
'q_test': sorted(q_test_pids),
'db_test': sorted(db_test_pids)}
if rank == 0:
write_json(splits, osp.join(self.root, 'splits_'+self.scale+'.json'))
synchronize()
| 36.336538 | 91 | 0.555967 |
1f12ef9a1f249d7dcf1e6fb3894424310b1800ce | 2,622 | css | CSS | src/css/components/Explorer.css | tomohiroyoshida/viron | 7fd7e52e1b945e1b163d6b45c3fb1fafc88dab27 | [
"MIT"
] | 1,002 | 2018-01-31T02:42:51.000Z | 2022-03-30T02:20:05.000Z | src/css/components/Explorer.css | tomohiroyoshida/viron | 7fd7e52e1b945e1b163d6b45c3fb1fafc88dab27 | [
"MIT"
] | 169 | 2018-01-31T02:50:32.000Z | 2022-03-30T03:28:20.000Z | src/css/components/Explorer.css | tomohiroyoshida/viron | 7fd7e52e1b945e1b163d6b45c3fb1fafc88dab27 | [
"MIT"
] | 66 | 2018-02-01T23:43:16.000Z | 2022-03-03T06:56:02.000Z | :root {
--component-explorer-column-min-count: 1;
}
.Explorer {
position: relative;
display: block;
&__head {
@apply --layout-center-center;
padding: 24px;
}
&__title {
@apply --text-truncate;
flex-grow: 1;
font-size: 1.6rem;
}
&__control {
@apply --layout-center-start;
& .Icon {
@mixin hover {
color: var(--color-base-blue);
}
width: 16px;
height: 16px;
margin-right: 24px;
cursor: pointer;
&:last-child {
margin-right: 0;
}
}
}
&__body {
}
&__progressWrapper {
@apply --layout-center-center;
height: 100px;
}
&__progress {
@apply --animation-spin;
transform-origin: center center;
& .Icon {
width: 24px;
height: 24px;
}
}
&__label {
padding: 0 24px 4px;
margin-bottom: 24px;
font-size: 1.2rem;
border-bottom: 1px solid var(--color-base-gray-tertiary);
}
&__droparea {
@mixin hover {
border-color: var(--color-base-blue);
}
@apply --layout-column-center-center;
position: relative;
height: 192px;
padding: 12px;
margin: 0 24px 24px;
cursor: pointer;
background-color: rgba(72, 72, 72, 0.03);
border: 2px dashed var(--color-base-gray-secondary);
border-radius: 6px;
&--active {
border-color: var(--color-base-blue);
}
&--mini {
height: 80px;
}
}
&__dragHandler {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
&__input {
display: none;
}
&__dropareaLabel {
position: relative;
margin-bottom: 24px;
font-size: 1.6rem;
color: var(--color-base-gray-secondary);
}
&__dropareaButton {
@mixin hover {
opacity: 0.5;
}
position: relative;
color: var(--color-base-blue);
text-decoration: underline;
cursor: pointer;
}
&__list {
display: grid;
grid-gap: 2px;
grid-template-columns: repeat(var(--component-explorer-column-min-count), 1fr);
grid-auto-rows: auto;
}
&__item {
@mixin hover {
opacity: 0.8;
}
position: relative;
cursor: pointer;
background-repeat: no-repeat;
background-position: center center;
background-size: cover;
&::before {
position: relative;
display: block;
padding-top: 100%;
content: "";
}
}
&__error {
color: var(--color-base-gray);
}
&__tail {
flex-shrink: 0;
padding-bottom: 24px;
margin: 24px 24px 0;
}
&__blocker {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
}
| 16.490566 | 83 | 0.561022 |
57d6de9552373edc49a955519863e8dd237a76d0 | 2,844 | kt | Kotlin | app/src/main/java/com/gmail/tofibashers/blacklist/data/repo/BlacklistPhoneNumberItemRepository.kt | TofiBashers/Blacklist | 1e72f8e59f52205a89a18864302bc2cf6f5f04ad | [
"Apache-2.0"
] | 6 | 2018-06-29T18:54:30.000Z | 2019-11-24T13:49:55.000Z | app/src/main/java/com/gmail/tofibashers/blacklist/data/repo/BlacklistPhoneNumberItemRepository.kt | TofiBashers/Blacklist | 1e72f8e59f52205a89a18864302bc2cf6f5f04ad | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/gmail/tofibashers/blacklist/data/repo/BlacklistPhoneNumberItemRepository.kt | TofiBashers/Blacklist | 1e72f8e59f52205a89a18864302bc2cf6f5f04ad | [
"Apache-2.0"
] | null | null | null | package com.gmail.tofibashers.blacklist.data.repo
import com.gmail.tofibashers.blacklist.data.datasource.IDatabaseSource
import com.gmail.tofibashers.blacklist.data.datasource.IMemoryDatasource
import com.gmail.tofibashers.blacklist.data.db.entity.mapper.DbBlacklistPhoneNumberItemMapper
import com.gmail.tofibashers.blacklist.data.memory.mapper.MemoryBlacklistPhoneNumberItemMapper
import com.gmail.tofibashers.blacklist.entity.BlacklistPhoneNumberItem
import com.gmail.tofibashers.blacklist.entity.mapper.BlacklistPhoneNumberItemMapper
import io.reactivex.Completable
import io.reactivex.Flowable
import io.reactivex.Maybe
import io.reactivex.Single
import javax.inject.Inject
import javax.inject.Singleton
/**
* Created by TofiBashers on 20.01.2018.
*/
@Singleton
class BlacklistPhoneNumberItemRepository
@Inject
constructor(
private val databaseSource: IDatabaseSource,
private val memoryDatasource: IMemoryDatasource,
private val dbBlacklistPhoneNumberItemMapper: DbBlacklistPhoneNumberItemMapper,
private val blacklistPhoneNumberItemMapper: BlacklistPhoneNumberItemMapper,
private val memoryBlacklistPhoneNumberItemMapper: MemoryBlacklistPhoneNumberItemMapper
) : IBlacklistPhoneNumberItemRepository {
override fun getAllWithChanges(): Flowable<List<BlacklistPhoneNumberItem>> {
return databaseSource.getAllBlacklistPhoneNumberItemsWithChanges()
.map { dbBlacklistPhoneNumberItemMapper.toBlacklistPhoneNumberItemsList(it) }
}
override fun getByNumber(number: String): Maybe<BlacklistPhoneNumberItem> =
databaseSource.getBlacklistPhoneNumberItemByNumber(number)
.map { dbBlacklistPhoneNumberItemMapper.toBlacklistPhoneNumberItemItem(it) }
override fun deleteBlacklistPhoneNumberItem(blacklistPhoneNumberItem: BlacklistPhoneNumberItem): Completable {
return Single.fromCallable { blacklistPhoneNumberItemMapper.toDbBlacklistPhoneNumberItem(blacklistPhoneNumberItem) }
.flatMapCompletable { databaseSource.deleteBlacklistPhoneNumberItem(it) }
}
override fun removeSelectedBlacklistPhoneNumberItem(): Completable =
memoryDatasource.removeSelectedBlacklistPhoneNumberItem()
override fun getSelectedBlacklistPhoneNumberItem(): Maybe<BlacklistPhoneNumberItem> {
return memoryDatasource.getSelectedBlacklistPhoneNumberItem()
.map(memoryBlacklistPhoneNumberItemMapper::toBlacklistPhoneNumberItem)
}
override fun putSelectedBlacklistPhoneNumberItem(blacklistPhoneNumberItem: BlacklistPhoneNumberItem): Completable {
return Single.fromCallable { blacklistPhoneNumberItemMapper.toMemoryBlacklistPhoneNumberItem(blacklistPhoneNumberItem) }
.flatMapCompletable(memoryDatasource::putSelectedBlacklistPhoneNumberItem)
}
} | 48.20339 | 128 | 0.812236 |
8150365b02b045219ca58b4b0a4641ea72f34116 | 9,205 | rs | Rust | ui/src/lib.rs | Barogthor/RustOpengl | bfffd4483df4e49cfd5309dba2feaa2ffcc8d0b5 | [
"MIT"
] | null | null | null | ui/src/lib.rs | Barogthor/RustOpengl | bfffd4483df4e49cfd5309dba2feaa2ffcc8d0b5 | [
"MIT"
] | null | null | null | ui/src/lib.rs | Barogthor/RustOpengl | bfffd4483df4e49cfd5309dba2feaa2ffcc8d0b5 | [
"MIT"
] | null | null | null |
pub use winit;
pub type LoopType = winit::event_loop::EventLoop<()>;
use winit::event::{VirtualKeyCode, MouseButton, Event};
use math::glm;
use crate::InputState::{Pressed, Released};
const MAX_MOUSE_BUTTONS: usize = 256;
const MAX_KEY_BUTTONS: usize = 512;
pub type Sensitivity = f32;
pub enum Gesture {
NoGesture,
KeyHold(VirtualKeyCode),
KeyTrigger(VirtualKeyCode),
ButtonHold(MouseButton),
ButtonTrigger(MouseButton),
AnyOf(Vec<Gesture>),
AllOf(Vec<Gesture>),
QuitTrigger,
}
pub enum Analog2d {
NoAnalog2d,
Mouse {
sensitivity: Sensitivity,
},
MouseWheel {
sensitivity: Sensitivity,
},
Gestures {
x_positive: Gesture,
x_negative: Gesture,
y_positive: Gesture,
y_negative: Gesture,
step: Sensitivity,
},
Sum {
analogs: Vec<Analog2d>,
},
}
pub struct Input {
mouse_buttons: [InputState; MAX_MOUSE_BUTTONS],
key_buttons: [InputState; MAX_KEY_BUTTONS],
mouse_wheel_dir: glm::Vec2,
mouse_rel: glm::Vec2,
quit_requested_index: u64,
current_index: u64,
mouse_grabbed: bool,
new_mouse_grabbed: bool,
}
impl Input {
pub fn poll_gesture(&self, gesture: &Gesture) -> bool {
match *gesture {
Gesture::QuitTrigger => self.quit_requested_index == self.current_index,
Gesture::KeyHold(code) => match self.key_buttons[code as usize] {
InputState::Pressed(_) => true,
InputState::Released(_) => false,
},
Gesture::KeyTrigger(code) => match self.key_buttons[code as usize] {
InputState::Pressed(index) => self.current_index == index,
InputState::Released(_) => false,
},
Gesture::ButtonHold(button) => match self.mouse_buttons[mouse_button_index(&button)] {
InputState::Pressed(_) => true,
InputState::Released(_) => false,
},
Gesture::ButtonTrigger(button) => {
match self.mouse_buttons[mouse_button_index(&button)] {
InputState::Pressed(index) => self.current_index == index,
InputState::Released(_) => false,
}
}
Gesture::AnyOf(ref subgestures) => subgestures
.iter()
.any(|subgesture| self.poll_gesture(subgesture)),
Gesture::AllOf(ref subgestures) => subgestures
.iter()
.all(|subgesture| self.poll_gesture(subgesture)),
Gesture::NoGesture => false,
}
}
pub fn poll_analog2d(&self, motion: &Analog2d) -> glm::Vec2 {
match *motion {
Analog2d::Sum { ref analogs } => analogs
.iter()
.map(|analog| self.poll_analog2d(analog))
.fold(glm::vec2(0., 0.), |v1, v2| v1 + v2),
Analog2d::Mouse { sensitivity } => (&self.mouse_rel) * sensitivity,
Analog2d::Gestures {
ref x_positive,
ref x_negative,
ref y_positive,
ref y_negative,
step,
} => glm::vec2(
if self.poll_gesture(x_positive) {
step
} else if self.poll_gesture(x_negative) {
-step
} else {
0.0
},
if self.poll_gesture(y_positive) {
step
} else if self.poll_gesture(y_negative) {
-step
} else {
0.0
},
),
Analog2d::MouseWheel { sensitivity } => { (&self.mouse_wheel_dir) * sensitivity }
Analog2d::NoAnalog2d => glm::vec2(0., 0.),
}
}
pub fn set_cursor_grabbed(&mut self, grabbed: bool) {
self.new_mouse_grabbed = grabbed
}
pub fn is_mouse_grabbed(&self) -> bool {
self.mouse_grabbed
}
pub fn update(&mut self, event: &Event<()>) {
match event {
Event::WindowEvent { event, .. } => match event {
winit::event::WindowEvent::KeyboardInput {
device_id,
input,
is_synthetic,
} => match (input.virtual_keycode, input.state) {
(Some(key), winit::event::ElementState::Pressed) => {
self.key_buttons[key as usize] = Pressed(self.current_index)
}
(Some(key), winit::event::ElementState::Released) => {
self.key_buttons[key as usize] = Released(self.current_index)
}
(None, _) => {}
},
winit::event::WindowEvent::Focused(flag) => {}
winit::event::WindowEvent::MouseWheel {
device_id,
delta,
phase,
..
} => match delta {
winit::event::MouseScrollDelta::LineDelta(x, y) => {
self.mouse_wheel_dir += glm::vec2(*x, *y);
}
_ => {}
},
winit::event::WindowEvent::MouseInput {
device_id,
state,
button,
..
} => match state {
winit::event::ElementState::Pressed => {
self.mouse_buttons[mouse_button_index(button) as usize] =
Pressed(self.current_index)
}
winit::event::ElementState::Released => {
self.mouse_buttons[mouse_button_index(button) as usize] =
Released(self.current_index)
}
},
winit::event::WindowEvent::CursorMoved {
device_id,
position,
..
} => {}
winit::event::WindowEvent::CloseRequested => {
self.quit_requested_index = self.current_index
}
_ => {}
},
winit::event::Event::DeviceEvent {
event: winit::event::DeviceEvent::Motion { axis, value },
..
} => {
if *axis < 2 {
self.mouse_rel[*axis as usize] += *value as f32;
}
}
_ => {}
}
}
pub fn create() -> Self {
Self {
mouse_buttons: [InputState::Released(0); MAX_MOUSE_BUTTONS],
key_buttons: [InputState::Released(0); MAX_KEY_BUTTONS],
mouse_wheel_dir: glm::vec2(0.0, 0.0),
mouse_rel: glm::vec2(0.0, 0.0),
quit_requested_index: 0,
current_index: 1,
mouse_grabbed: false,
new_mouse_grabbed: false,
}
}
pub fn tick_reset(&mut self) {
self.current_index += 1;
self.mouse_rel = glm::vec2(0.0, 0.0);
self.mouse_wheel_dir = glm::vec2(0.0, 0.0);
}
}
#[derive(Debug, Hash, PartialEq, Eq, Clone, Copy)]
pub enum InputState {
Pressed(u64),
Released(u64),
}
fn mouse_button_index(button: &MouseButton) -> usize {
match button {
MouseButton::Left => 0,
MouseButton::Middle => 1,
MouseButton::Right => 2,
MouseButton::Other(id) => *id as usize,
}
}
type Key = VirtualKeyCode;
pub struct Binding {
pub exit: Gesture,
pub movement: Analog2d,
pub look: Analog2d,
pub jump: Gesture,
pub fall: Gesture,
pub fullscreen: Gesture,
pub scroll: Analog2d,
pub toggle_mouse: Gesture,
pub toggle_torch_light: Gesture,
pub swap_color: Gesture,
}
impl Binding {
pub fn create() -> Self {
Self {
exit: Gesture::KeyTrigger(Key::Escape),
movement: Analog2d::Gestures {
x_positive: Gesture::AnyOf(vec![
Gesture::KeyHold(Key::D),
Gesture::KeyHold(Key::Right),
]),
x_negative: Gesture::AnyOf(vec![
Gesture::KeyHold(Key::Q),
Gesture::KeyHold(Key::Left),
]),
y_positive: Gesture::AnyOf(vec![
Gesture::KeyHold(Key::Z),
Gesture::KeyHold(Key::Up),
]),
y_negative: Gesture::AnyOf(vec![
Gesture::KeyHold(Key::S),
Gesture::KeyHold(Key::Down),
]),
step: 0.15,
},
look: Analog2d::Mouse { sensitivity: 0.015 },
jump: Gesture::KeyHold(Key::Space),
fall: Gesture::KeyHold(Key::C),
fullscreen: Gesture::KeyTrigger(Key::F),
scroll: Analog2d::MouseWheel { sensitivity: 0.030 },
toggle_mouse: Gesture::ButtonHold(MouseButton::Right),
toggle_torch_light: Gesture::KeyTrigger(Key::T),
swap_color: Gesture::KeyTrigger(Key::R),
}
}
}
| 32.411972 | 98 | 0.490712 |
37b42643b7bda12b1f1b3f934e3cd381725cea42 | 5,289 | sql | SQL | Database/10082017.sql | azadhamza/sindhtv | f83f2f73842b19424d3e327dd1abebc7ba6aa867 | [
"MIT"
] | null | null | null | Database/10082017.sql | azadhamza/sindhtv | f83f2f73842b19424d3e327dd1abebc7ba6aa867 | [
"MIT"
] | null | null | null | Database/10082017.sql | azadhamza/sindhtv | f83f2f73842b19424d3e327dd1abebc7ba6aa867 | [
"MIT"
] | null | null | null | /*
SQLyog Enterprise - MySQL GUI v7.15
MySQL - 5.6.17 : Database - sindh_tv_db
*********************************************************************
*/
/*!40101 SET NAMES utf8 */;
/*!40101 SET SQL_MODE=''*/;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*Table structure for table `content` */
DROP TABLE IF EXISTS `content`;
CREATE TABLE `content` (
`content_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`content_type_id` int(11) DEFAULT NULL,
`title` varchar(255) DEFAULT NULL,
`description` text,
`detail_description` text,
`end_date` datetime DEFAULT NULL,
`start_date` datetime DEFAULT NULL,
`data` text,
`is_active` tinyint(1) DEFAULT '1' COMMENT '0=inactive, 1=active',
`modified_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`is_approved` tinyint(1) DEFAULT '1',
`channel_id` int(11) DEFAULT NULL,
`category_id` int(11) DEFAULT NULL,
PRIMARY KEY (`content_id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;
/*Data for the table `content` */
insert into `content`(`content_id`,`content_type_id`,`title`,`description`,`detail_description`,`end_date`,`start_date`,`data`,`is_active`,`modified_time`,`is_approved`,`channel_id`,`category_id`) values (1,17,'Test','<p>This is Test</p>',NULL,'0000-00-00 00:00:00','0000-00-00 00:00:00','a:1:{s:8:\"category\";s:1:\"8\";}',1,'2017-10-05 01:23:09',1,3,NULL);
insert into `content`(`content_id`,`content_type_id`,`title`,`description`,`detail_description`,`end_date`,`start_date`,`data`,`is_active`,`modified_time`,`is_approved`,`channel_id`,`category_id`) values (2,17,'Test 2','<p>This is test </p>',NULL,'0000-00-00 00:00:00','2017-10-04 00:25:08','a:1:{s:8:\"category\";s:1:\"4\";}',1,'2017-10-05 00:37:38',1,3,NULL);
insert into `content`(`content_id`,`content_type_id`,`title`,`description`,`detail_description`,`end_date`,`start_date`,`data`,`is_active`,`modified_time`,`is_approved`,`channel_id`,`category_id`) values (3,18,'Video A','<p>???????This is test</p>','Episode 1','0000-00-00 00:00:00','0000-00-00 00:00:00','a:3:{s:12:\"sub_category\";s:7:\"episode\";s:4:\"type\";s:4:\"link\";s:4:\"link\";s:0:\"\";}',1,'2017-10-08 13:55:24',1,3,14);
insert into `content`(`content_id`,`content_type_id`,`title`,`description`,`detail_description`,`end_date`,`start_date`,`data`,`is_active`,`modified_time`,`is_approved`,`channel_id`,`category_id`) values (4,18,'Video C','<p>dsff</p>','09/22/2017','0000-00-00 00:00:00','0000-00-00 00:00:00','a:4:{s:12:\"sub_category\";s:4:\"date\";s:8:\"category\";s:1:\"7\";s:4:\"type\";s:4:\"link\";s:4:\"link\";s:0:\"\";}',1,'2017-10-08 13:56:49',1,3,14);
insert into `content`(`content_id`,`content_type_id`,`title`,`description`,`detail_description`,`end_date`,`start_date`,`data`,`is_active`,`modified_time`,`is_approved`,`channel_id`,`category_id`) values (6,18,'Video C','<p>THis is test</p>','09/21/2017','0000-00-00 00:00:00','0000-00-00 00:00:00','a:3:{s:12:\"sub_category\";s:4:\"date\";s:4:\"type\";s:4:\"link\";s:4:\"link\";s:15:\"www.youtube.com\";}',1,'2017-10-08 13:55:58',1,3,14);
insert into `content`(`content_id`,`content_type_id`,`title`,`description`,`detail_description`,`end_date`,`start_date`,`data`,`is_active`,`modified_time`,`is_approved`,`channel_id`,`category_id`) values (7,18,'Video A','<p>THis is test</p>','Episode 2','0000-00-00 00:00:00','0000-00-00 00:00:00','a:3:{s:12:\"sub_category\";s:7:\"episode\";s:4:\"type\";s:4:\"link\";s:4:\"link\";s:0:\"\";}',1,'2017-10-08 13:56:43',1,3,14);
/*Table structure for table `video_category` */
DROP TABLE IF EXISTS `video_category`;
CREATE TABLE `video_category` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`category` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`channel_id` int(11) NOT NULL,
`icon` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=latin1;
/*Data for the table `video_category` */
insert into `video_category`(`id`,`category`,`channel_id`,`icon`) values (1,'Morning Show',2,NULL);
insert into `video_category`(`id`,`category`,`channel_id`,`icon`) values (2,'Drama',2,NULL);
insert into `video_category`(`id`,`category`,`channel_id`,`icon`) values (3,'Music',2,NULL);
insert into `video_category`(`id`,`category`,`channel_id`,`icon`) values (4,'Kids & Cooking Show',2,NULL);
insert into `video_category`(`id`,`category`,`channel_id`,`icon`) values (5,'User Videos',2,NULL);
insert into `video_category`(`id`,`category`,`channel_id`,`icon`) values (11,'Talk Show',3,'assets/images/menu/talkshow_menu.png');
insert into `video_category`(`id`,`category`,`channel_id`,`icon`) values (12,'Reports',3,'assets/images/menu/morning_menu.png');
insert into `video_category`(`id`,`category`,`channel_id`,`icon`) values (13,'Education, Health, Youth & Women Affairs',3,'assets/images/menu/editorvideo_menu.png');
insert into `video_category`(`id`,`category`,`channel_id`,`icon`) values (14,'Mysticism & Literature',3,'assets/images/menu/drama_menu.png');
insert into `video_category`(`id`,`category`,`channel_id`,`icon`) values (15,'User Videos',3,'assets/images/menu/user_video.png');
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; | 77.779412 | 444 | 0.673473 |
b3c4001063004d842269dd0f692d2b2f977dc1bd | 2,460 | rb | Ruby | lib/td/task_list.rb | marktermaat/td-terminal | cf3a1ce5bd7b47b1dd4958eade46a3513d6a812a | [
"MIT"
] | null | null | null | lib/td/task_list.rb | marktermaat/td-terminal | cf3a1ce5bd7b47b1dd4958eade46a3513d6a812a | [
"MIT"
] | null | null | null | lib/td/task_list.rb | marktermaat/td-terminal | cf3a1ce5bd7b47b1dd4958eade46a3513d6a812a | [
"MIT"
] | null | null | null | require_relative 'task'
require_relative 'command_error'
module Td
class TaskList
def initialize(io, presenter)
@io = io
@presenter = presenter
@tasks = @io.read_tasks
end
def list
@presenter.present_tasks(@tasks)
end
def start_task(task_number)
task = find_task(task_number)
task.events << {'action' => 'start', 'timestamp' => Time.now.utc.to_s}
update_and_show_tasks
end
def pause_task(task_number)
task = find_task(task_number)
task.events << {'action' => 'pause', 'timestamp' => Time.now.utc.to_s}
update_and_show_tasks
end
def finish_task(task_number)
task = find_task(task_number)
task.events << {'action' => 'done', 'timestamp' => Time.now.utc.to_s}
update_and_show_tasks
end
def add_task(topic, description)
@tasks << Td::Task.new(nil, topic, description)
sort_tasks
update_and_show_tasks
end
def delete_task(task_number)
if task_number.include?('.')
task_number, note_number = task_number.split('.')
task = find_task(task_number)
task.notes.delete_at(note_number.to_i - 1)
else
task = find_task(task_number)
@tasks.delete(task)
sort_tasks
end
update_and_show_tasks
end
def edit_task(task_number, description)
if task_number.include?('.')
task_number, note_number = task_number.split('.')
task = find_task(task_number)
task.notes[note_number.to_i - 1] = description
else
task = find_task(task_number)
task.description = description
end
update_and_show_tasks
end
def add_note(task_number, note)
task = find_task(task_number)
task.notes << note
update_and_show_tasks
end
def get_started_task()
@tasks.find {|t| t.doing?}
end
private
def find_task(task_number)
task = @tasks.find {|t| t.id.to_s == task_number.to_s}
raise Td::CommandError.new "Task '#{task_number}' not found." if task.nil?
task
end
def update_and_show_tasks
@io.write_tasks(@tasks)
list
end
def sort_tasks
@tasks = @tasks
.group_by { |t| t.topic}
.sort_by { |topic, _| topic }
.map {|_topic, tasks| tasks }
.flatten
@tasks.each_with_index { |task, index| task.id = index + 1 }
end
end
end | 25.625 | 80 | 0.610569 |
cdf2dcc7d7928719a790610623588257c318bac7 | 1,077 | kt | Kotlin | platform/platform-impl/src/com/intellij/ide/ClientCopyPasteManager.kt | 06needhamt/intellij-community | 63d7b8030e4fdefeb4760e511e289f7e6b3a5c5b | [
"Apache-2.0"
] | null | null | null | platform/platform-impl/src/com/intellij/ide/ClientCopyPasteManager.kt | 06needhamt/intellij-community | 63d7b8030e4fdefeb4760e511e289f7e6b3a5c5b | [
"Apache-2.0"
] | null | null | null | platform/platform-impl/src/com/intellij/ide/ClientCopyPasteManager.kt | 06needhamt/intellij-community | 63d7b8030e4fdefeb4760e511e289f7e6b3a5c5b | [
"Apache-2.0"
] | null | null | null | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide
import com.intellij.openapi.components.service
import com.intellij.openapi.editor.Document
import org.jetbrains.annotations.ApiStatus
import java.awt.datatransfer.ClipboardOwner
import java.awt.datatransfer.DataFlavor
import java.awt.datatransfer.Transferable
/**
* A per-client service managing clipboard.
* Take a look at [CopyPasteManagerEx]
*/
@ApiStatus.Internal
interface ClientCopyPasteManager : ClipboardOwner {
companion object {
@JvmStatic
fun getCurrentInstance(): ClientCopyPasteManager = service()
}
fun areDataFlavorsAvailable(vararg flavors: DataFlavor): Boolean
fun setContents(content: Transferable)
fun getContents(): Transferable?
fun <T> getContents(flavor: DataFlavor): T?
fun stopKillRings()
fun stopKillRings(document: Document)
fun getAllContents(): Array<Transferable>
fun removeContent(t: Transferable?)
fun moveContentToStackTop(t: Transferable?)
} | 34.741935 | 140 | 0.790158 |
0c3ca22982d18edc4dbcba9ed6fb539b7bafdd7c | 3,705 | swift | Swift | ExampleSwift/Paginator-ExampleSwift/JSONHTTPRequestHandler.swift | anton-filimonov/Paginator | 866f21e7f1ec1e095c4c3beef113cbdaf779489c | [
"MIT"
] | null | null | null | ExampleSwift/Paginator-ExampleSwift/JSONHTTPRequestHandler.swift | anton-filimonov/Paginator | 866f21e7f1ec1e095c4c3beef113cbdaf779489c | [
"MIT"
] | null | null | null | ExampleSwift/Paginator-ExampleSwift/JSONHTTPRequestHandler.swift | anton-filimonov/Paginator | 866f21e7f1ec1e095c4c3beef113cbdaf779489c | [
"MIT"
] | null | null | null | //
// JSONHTTPRequestHandler.swift
// Paginator-ExampleSwift
//
// Created by Anton Filimonov on 11/11/2017.
// Copyright © 2017 Anton Filimonov. All rights reserved.
//
import Foundation
import AFPaginator
class JSONHTTPRequestHandler: DataRequestHandler {
let requestTimeout: TimeInterval = 30
let errorDomain = "JSONHTTPRequestHandlerErrorDomain"
var processingDataTasks: [URLSessionDataTask] = []
lazy var urlSession: URLSession = {
return URLSession(configuration: URLSessionConfiguration.default)
}()
deinit {
self.cancelAllRequests()
}
//MARK: DataRequestHandler
func sendRequest(configuration requestConfiguration: Any,
completion completionHandler: @escaping (Any?, Error?) -> Void) {
guard let requestConfiguration = requestConfiguration as? HTTPRequestConfiguration,
let requestUrl = self.makeUrl(for: requestConfiguration)
else { return }
let request = URLRequest(url: requestUrl,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: self.requestTimeout)
let dataTask = self.urlSession.dataTask(with: request) {
[weak self] (data, _, error) in
guard let `self` = self else { return }
defer {
self.removeCompletedTasks()
}
guard error == nil else {
completionHandler(nil, error)
return
}
guard let data = data else {
completionHandler(nil, NSError(domain: self.errorDomain, code: 1000, userInfo: nil))
return
}
if let result = try? JSONSerialization.jsonObject(with: data, options: [.allowFragments]) {
completionHandler(result, nil)
} else {
completionHandler(nil, NSError(domain: self.errorDomain, code: 1000, userInfo: nil))
}
}
self.processingDataTasks.append(dataTask)
dataTask.resume()
}
func cancelAllRequests() {
for dataTask in self.processingDataTasks {
dataTask.cancel()
}
self.processingDataTasks.removeAll()
}
//MARK: Helpers
func makeUrl(for configuration: HTTPRequestConfiguration) -> URL? {
var requestUrl = configuration.baseUrl
if let path = configuration.requestPath {
if let url = URL(string: path, relativeTo: configuration.baseUrl) {
requestUrl = url
} else {
return nil
}
}
var components = URLComponents(url: requestUrl, resolvingAgainstBaseURL: true)
var query = components?.query ?? ""
if query.count > 0 {
query.append("&")
}
components?.query = configuration.parameters.reduce(query) {
(lastResult, keyValuePair) -> String in
let value: String
if let stringValue = keyValuePair.value as? String {
value = stringValue
} else if let numberValue = keyValuePair.value as? NSNumber {
value = numberValue.stringValue
} else {
return lastResult
}
return lastResult + "&" + keyValuePair.key + "=" + value
}
return components?.url
}
func removeCompletedTasks() {
self.processingDataTasks = self.processingDataTasks.filter({ (task) -> Bool in
return task.state != .completed
})
}
}
| 32.5 | 103 | 0.565452 |
68466d8b6fa5d7f1d7de7c1c4e0596495d63dc79 | 771 | swift | Swift | Application/Enigma/Utilities/Protocols.swift | aaryankotharii/enigma7-iOS | 4084896acd85b45b1cee65554a8e493326255745 | [
"MIT"
] | 1 | 2021-02-03T17:27:10.000Z | 2021-02-03T17:27:10.000Z | Application/Enigma/Utilities/Protocols.swift | aaryankotharii/enigma7-iOS | 4084896acd85b45b1cee65554a8e493326255745 | [
"MIT"
] | null | null | null | Application/Enigma/Utilities/Protocols.swift | aaryankotharii/enigma7-iOS | 4084896acd85b45b1cee65554a8e493326255745 | [
"MIT"
] | 1 | 2021-02-03T17:26:48.000Z | 2021-02-03T17:26:48.000Z | //
// Protocols.swift
// Enigma
//
// Created by Aaryan Kothari on 15/01/21.
// Copyright © 2021 Aaryan Kothari. All rights reserved.
//
import UIKit
// MARK:- PROTOCOLS
/// SHARE DELEGATE
/// setShare: changes icon of info tab when true
protocol ShareDelegate : class {
func setShare(bool : Bool, image: UIImage?)
}
/// LOGOUT DELEGATE
/// empties default and returns rootViewController
protocol LogoutDelegate: class {
func logout()
}
/// SIGNIN DELEGATE
/// persists token and sends it to Watch.
protocol SigninDelegate: class {
func didSignin(_ token: String)
}
/// COUNTDOWN DELEGATE
protocol CountdownDelegate: class {
func didSignin(_ token: String)
}
/// PREVIEW DELEGATE
protocol PreviewDelegate : class {
func hintPreviewed()
}
| 18.357143 | 57 | 0.706874 |
3074d48bd556b8814db1fa1021d9a751d227375b | 4,401 | dart | Dart | lib/meta/views/tabs/sections/pub/elements/search_result_tile.dart | FlutterMatic/desktop | 5480f5436733350eda936824e60ea4b7ee5d3ee5 | [
"BSD-3-Clause"
] | 5 | 2022-01-21T02:16:57.000Z | 2022-02-26T17:34:21.000Z | lib/meta/views/tabs/sections/pub/elements/search_result_tile.dart | FlutterMatic/desktop | 5480f5436733350eda936824e60ea4b7ee5d3ee5 | [
"BSD-3-Clause"
] | 45 | 2022-01-09T09:01:38.000Z | 2022-02-27T12:36:01.000Z | lib/meta/views/tabs/sections/pub/elements/search_result_tile.dart | FlutterMatic/FlutterMatic-desktop | 5480f5436733350eda936824e60ea4b7ee5d3ee5 | [
"BSD-3-Clause"
] | 2 | 2021-12-04T07:25:16.000Z | 2021-12-04T07:26:26.000Z | // 🐦 Flutter imports:
import 'package:flutter/material.dart';
// 📦 Package imports:
import 'package:pub_api_client/pub_api_client.dart';
// 🌎 Project imports:
import 'package:fluttermatic/app/constants/constants.dart';
import 'package:fluttermatic/components/widgets/buttons/rectangle_button.dart';
import 'package:fluttermatic/components/widgets/ui/snackbar_tile.dart';
import 'package:fluttermatic/components/widgets/ui/spinner.dart';
import 'package:fluttermatic/core/services/logs.dart';
import 'package:fluttermatic/meta/utils/app_theme.dart';
import 'package:fluttermatic/meta/views/tabs/sections/pub/dialogs/package_info.dart';
import 'package:fluttermatic/meta/views/tabs/sections/pub/models/pkg_data.dart';
class PubPackageSearchResultTile extends StatefulWidget {
final PkgViewData package;
const PubPackageSearchResultTile({Key? key, required this.package})
: super(key: key);
@override
State<PubPackageSearchResultTile> createState() =>
_PubPackageSearchResultTileState();
}
class _PubPackageSearchResultTileState
extends State<PubPackageSearchResultTile> {
PackagePublisher? _pkgInfo;
Future<void> _fetchPkgInfo() async {
try {
PackagePublisher _info = await PubClient()
.packagePublisher(widget.package.name)
.timeout(const Duration(seconds: 5));
if (mounted) {
setState(() => _pkgInfo = _info);
}
} catch (_, s) {
await logger.file(LogTypeTag.error, 'Failed to get package info.',
stackTraces: s);
}
}
@override
void initState() {
_fetchPkgInfo();
super.initState();
}
@override
void dispose() {
_pkgInfo = null;
super.dispose();
}
@override
Widget build(BuildContext context) {
return RectangleButton(
width: 500,
onPressed: () {
showDialog(
context: context,
builder: (_) => PubPackageDialog(pkgInfo: widget.package),
);
},
padding: const EdgeInsets.all(5),
child: Row(
children: <Widget>[
HSeparators.xSmall(),
Expanded(
child: Text(
widget.package.name,
style: TextStyle(
color:
Theme.of(context).isDarkTheme ? Colors.white : Colors.black,
),
),
),
Row(
children: <Widget>[
const Tooltip(
message: 'Verified Publisher',
child: Icon(Icons.verified, size: 15, color: kGreenColor),
),
HSeparators.xSmall(),
if (_pkgInfo == null)
const Padding(
padding: EdgeInsets.symmetric(horizontal: 10),
child: Spinner(size: 8, thickness: 1),
)
else
Text(
_pkgInfo!.publisherId ?? 'Unknown',
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 13.5,
color: (Theme.of(context).isDarkTheme
? Colors.white
: Colors.black)
.withOpacity(0.5),
),
),
HSeparators.xSmall(),
// Show a copy icon to copy the dependency directly on when
// hovering to avoid UI distraction.
RectangleButton(
width: 30,
height: 30,
padding: EdgeInsets.zero,
color: Colors.transparent,
hoverColor: Colors.blueGrey.withOpacity(0.2),
child: Icon(
Icons.content_copy,
size: 13,
color: (Theme.of(context).isDarkTheme
? Colors.white
: Colors.black)
.withOpacity(0.5),
),
onPressed: () {
ScaffoldMessenger.of(context).clearSnackBars();
ScaffoldMessenger.of(context).showSnackBar(
snackBarTile(
context,
'Dependency has been copied to your clipboard.',
type: SnackBarType.done,
),
);
},
),
],
),
],
),
);
}
}
| 31.212766 | 85 | 0.535106 |
5dbff56a55f793c3390119cca991bb023c637c72 | 1,934 | go | Go | mangle.go | KarpelesLab/iso9660 | 23d0ef3da166cbc74daa3b0c4653fbde2426f8e9 | [
"Apache-2.0"
] | 8 | 2020-04-11T15:44:17.000Z | 2021-03-04T22:36:06.000Z | mangle.go | KarpelesLab/iso9660 | 23d0ef3da166cbc74daa3b0c4653fbde2426f8e9 | [
"Apache-2.0"
] | 2 | 2020-04-12T06:33:37.000Z | 2020-04-12T11:05:25.000Z | mangle.go | KarpelesLab/iso9660 | 23d0ef3da166cbc74daa3b0c4653fbde2426f8e9 | [
"Apache-2.0"
] | 1 | 2020-04-11T19:00:02.000Z | 2020-04-11T19:00:02.000Z | package iso9660
import (
"path"
"strings"
)
func manglePath(input string) (string, string) {
nonEmptySegments := splitPath(path.Clean(input))
dirSegments := nonEmptySegments[:len(nonEmptySegments)-1]
name := nonEmptySegments[len(nonEmptySegments)-1]
for i := 0; i < len(dirSegments); i++ {
dirSegments[i] = mangleDirectoryName(dirSegments[i])
}
name = mangleFileName(name)
return path.Join(dirSegments...), name
}
func splitPath(input string) []string {
rawSegments := strings.Split(input, "/")
var nonEmptySegments []string
for _, s := range rawSegments {
if len(s) > 0 {
nonEmptySegments = append(nonEmptySegments, s)
}
}
return nonEmptySegments
}
// See ECMA-119 7.5
func mangleFileName(input string) string {
input = strings.ToUpper(input)
split := strings.Split(input, ".")
version := "1"
var filename, extension string
if len(split) == 1 {
filename = split[0]
} else {
filename = strings.Join(split[:len(split)-1], "_")
extension = split[len(split)-1]
}
// enough characters for the `.ignition` extension
extension = mangleDString(extension, 8)
maxRemainingFilenameLength := primaryVolumeFileIdentifierMaxLength - (1 + len(version))
if len(extension) > 0 {
maxRemainingFilenameLength -= (1 + len(extension))
}
filename = mangleDString(filename, maxRemainingFilenameLength)
if len(extension) > 0 {
return filename + "." + extension + ";" + version
}
return filename + ";" + version
}
// See ECMA-119 7.6
func mangleDirectoryName(input string) string {
return mangleDString(input, primaryVolumeDirectoryIdentifierMaxLength)
}
func mangleDString(input string, maxCharacters int) string {
input = strings.ToUpper(input)
var mangledString string
for i := 0; i < len(input) && i < maxCharacters; i++ {
r := rune(input[i])
if strings.ContainsRune(dCharacters, r) {
mangledString += string(r)
} else {
mangledString += "_"
}
}
return mangledString
}
| 23.02381 | 88 | 0.701138 |
55dddcb241a2c7c09ed990a0fea7eed826fb1e5e | 2,402 | sql | SQL | src/main/resources/db/migration/oracle/V2.6.0.20181010185036__schema-user-import-scheduler.sql | patrickfischer1/WebAPI | 759334d4161267b1f728a624590b566bb64abaec | [
"Apache-2.0"
] | 99 | 2015-01-06T18:24:25.000Z | 2022-03-10T16:34:04.000Z | src/main/resources/db/migration/oracle/V2.6.0.20181010185036__schema-user-import-scheduler.sql | patrickfischer1/WebAPI | 759334d4161267b1f728a624590b566bb64abaec | [
"Apache-2.0"
] | 1,261 | 2015-01-01T17:33:35.000Z | 2022-03-28T18:16:27.000Z | src/main/resources/db/migration/oracle/V2.6.0.20181010185036__schema-user-import-scheduler.sql | patrickfischer1/WebAPI | 759334d4161267b1f728a624590b566bb64abaec | [
"Apache-2.0"
] | 159 | 2015-01-12T13:39:42.000Z | 2022-03-15T13:39:31.000Z | CREATE SEQUENCE ${ohdsiSchema}.user_import_job_seq;
CREATE TABLE ${ohdsiSchema}.user_import_job(
id NUMBER(19) NOT NULL,
is_enabled CHAR(1) DEFAULT '0' NOT NULL,
start_date TIMESTAMP WITH TIME ZONE,
frequency VARCHAR(100) NOT NULL,
recurring_times INTEGER NOT NULL,
recurring_until_date TIMESTAMP WITH TIME ZONE,
cron VARCHAR(255) NOT NULL,
last_executed_at TIMESTAMP WITH TIME ZONE,
executed_times INTEGER DEFAULT 0 NOT NULL,
is_closed CHAR(1) DEFAULT '0' NOT NULL,
provider_type VARCHAR(100) NOT NULL,
preserve_roles CHAR(1) DEFAULT '1' NOT NULL ,
CONSTRAINT pk_user_import_job PRIMARY KEY(id)
);
CREATE TABLE ${ohdsiSchema}.user_import_job_weekdays(
user_import_job_id NUMBER(19) NOT NULL,
day_of_week VARCHAR(100) NOT NULL,
CONSTRAINT pk_user_import_job_weekdays PRIMARY KEY(user_import_job_id, day_of_week)
);
INSERT INTO ${ohdsiSchema}.sec_permission(id, value, description)
SELECT ${ohdsiSchema}.sec_permission_id_seq.nextval, 'user:import:job:get', 'List user import jobs' FROM dual;
INSERT INTO ${ohdsiSchema}.sec_permission(id, value, description)
SELECT ${ohdsiSchema}.sec_permission_id_seq.nextval, 'user:import:job:post', 'Create new user import job' FROM dual;
INSERT INTO ${ohdsiSchema}.sec_permission(id, value, description)
SELECT ${ohdsiSchema}.sec_permission_id_seq.nextval, 'user:import:job:*:put', 'Update user import job' FROM dual;
INSERT INTO ${ohdsiSchema}.sec_permission(id, value, description)
SELECT ${ohdsiSchema}.sec_permission_id_seq.nextval, 'user:import:job:*:get', 'Get user import job' FROM dual;
INSERT INTO ${ohdsiSchema}.sec_permission(id, value, description)
SELECT ${ohdsiSchema}.sec_permission_id_seq.nextval, 'user:import:job:*:delete', 'Delete user import job' FROM dual;
INSERT INTO ${ohdsiSchema}.sec_permission(id, value, description)
SELECT ${ohdsiSchema}.sec_permission_id_seq.nextval, 'user:import:job:*:history:get', 'Get user import history' FROM dual;
INSERT INTO ${ohdsiSchema}.sec_role_permission(id, role_id, permission_id)
SELECT ${ohdsiSchema}.SEC_ROLE_PERMISSION_SEQUENCE.nextval, sr.id, sp.id
FROM ${ohdsiSchema}.sec_permission SP, ${ohdsiSchema}.sec_role sr
WHERE sp.value IN (
'user:import:job:get',
'user:import:job:post',
'user:import:job:*:put',
'user:import:job:*:get',
'user:import:job:*:delete',
'user:import:job:*:history:get')
AND sr.name IN ('admin'); | 50.041667 | 124 | 0.763114 |
471efb29ee10651d682db0be2510a304a8d90ea0 | 1,185 | swift | Swift | Package.swift | taketo1024/swm-hfk | 5c41ada793cd9365a2b5ef2737998ced487b6016 | [
"MIT"
] | null | null | null | Package.swift | taketo1024/swm-hfk | 5c41ada793cd9365a2b5ef2737998ced487b6016 | [
"MIT"
] | null | null | null | Package.swift | taketo1024/swm-hfk | 5c41ada793cd9365a2b5ef2737998ced487b6016 | [
"MIT"
] | null | null | null | // swift-tools-version:5.3
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "swm-hfk",
products: [
.library(
name: "SwmHFK",
targets: ["SwmHFK"]
),
],
dependencies: [
.package(
url: "https://github.com/taketo1024/swm-core.git",
from:"1.2.6"
// path: "../swm-core"
),
.package(
url: "https://github.com/taketo1024/swm-knots.git",
from: "1.1.0"
),
.package(
url: "https://github.com/taketo1024/swm-homology.git",
from: "1.3.0"
// path: "../swm-homology/"
),
],
targets: [
.target(
name: "SwmHFK",
dependencies: [
.product(name: "SwmCore", package: "swm-core"),
.product(name: "SwmKnots", package: "swm-knots"),
.product(name: "SwmHomology", package: "swm-homology"),
],
resources: [.process("Resources")]
),
.testTarget(
name: "SwmHFKTests",
dependencies: ["SwmHFK"]
),
]
)
| 25.76087 | 96 | 0.498734 |
180ea7461cf9e432c05b8e0e7ea08a76c94477b4 | 1,383 | rb | Ruby | app/graphql/mutations/edit_contact.rb | KojoOwusu/ContactApp | f85f9bd220aaf11de43fd0403ed4c142f7bdcf31 | [
"MIT"
] | null | null | null | app/graphql/mutations/edit_contact.rb | KojoOwusu/ContactApp | f85f9bd220aaf11de43fd0403ed4c142f7bdcf31 | [
"MIT"
] | null | null | null | app/graphql/mutations/edit_contact.rb | KojoOwusu/ContactApp | f85f9bd220aaf11de43fd0403ed4c142f7bdcf31 | [
"MIT"
] | null | null | null | module Mutations
class EditContact < BaseMutation
# TODO: define return fields
field :contact, Types::ContactType, null: false
# TODO: define arguments
argument :id, ID, required: true
argument :firstname, String, required:false
argument :lastname, String, required:false
argument :phonenumbers, [Types::Input::PhoneNumberInput], required: false
argument :emails, [Types::Input::EmailInput], required: false
argument :twitterusername, String, required: false
# TODO: define resolve method
def resolve(id:,**attributes)
contact=Contact.find(id)
if attributes.key?(:phonenumbers)
phonenumber = Phonenumber.find_by(contact_id:contact.id)
attributes[:phonenumbers].each do |item|
phonenumber.contact_id=contact.id
phonenumber.phonenumber=item[:phonenumber]
phonenumber.purpose = item[:purpose]
phonenumber.save
end
elsif attributes.key?(:emails)
email = Email.find_by(contact_id:contact.id)
attributes[:emails].each do |item|
email.contact_id=contact.id
email.email=item[:email]
email.purpose = item[:purpose]
email.save
end
end
contact.tap do |item|
item.update!(attributes.slice(:firstname,:lastname,:twitterusername))
end
{contact:contact}
end
end
end
| 33.731707 | 77 | 0.662328 |
c389746153356eeedc2b1ca801168493d966f429 | 3,099 | sql | SQL | db/db.sql | EliuFlorez/codeigniter-credit | 145505b662f3682ab5549f08690076067fc5fa84 | [
"MIT"
] | null | null | null | db/db.sql | EliuFlorez/codeigniter-credit | 145505b662f3682ab5549f08690076067fc5fa84 | [
"MIT"
] | null | null | null | db/db.sql | EliuFlorez/codeigniter-credit | 145505b662f3682ab5549f08690076067fc5fa84 | [
"MIT"
] | null | null | null | --
-- Table structure for table `settings`
--
CREATE TABLE IF NOT EXISTS `credit_users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(120) DEFAULT NULL,
`password` varchar(120) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
--
-- Dumping data for table `credit_users`
--
INSERT INTO `credit_users` (`id`, `username`, `password`) VALUES
(1, 'admin', 'admin');
CREATE TABLE IF NOT EXISTS `credit_settings` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`base_min` double NOT NULL,
`base_max` double NOT NULL,
`base_efectiva` float NOT NULL,
`base_nomina` float NOT NULL,
`simple_min` double NOT NULL,
`simple_max` double NOT NULL,
`simple_efectiva` float NOT NULL,
`simple_nomina` float NOT NULL,
`ampliada_min` double NOT NULL,
`ampliada_max` double NOT NULL,
`ampliada_efectiva` float NOT NULL,
`ampliada_nomina` float NOT NULL,
`credit_1_mmin` double NOT NULL,
`credit_1_mmax` double NOT NULL,
`credit_1_pmin` double NOT NULL,
`credit_1_pmax` double NOT NULL,
`credit_1_seguro` float NOT NULL,
`credit_2_mmin` double NOT NULL,
`credit_2_mmax` double NOT NULL,
`credit_2_pmin` double NOT NULL,
`credit_2_pmax` double NOT NULL,
`credit_2_seguro` float NOT NULL,
`credit_3_mmin` double NOT NULL,
`credit_3_mmax` double NOT NULL,
`credit_3_pmin` double NOT NULL,
`credit_3_pmax` double NOT NULL,
`credit_3_seguro` float NOT NULL,
`credit_4_mmin` double NOT NULL,
`credit_4_mmax` double NOT NULL,
`credit_4_pmin` double NOT NULL,
`credit_4_pmax` double NOT NULL,
`credit_4_seguro` float NOT NULL,
`credit_5_mmin` double NOT NULL,
`credit_5_mmax` double NOT NULL,
`credit_5_pmin` double NOT NULL,
`credit_5_pmax` double NOT NULL,
`credit_5_seguro` float NOT NULL,
`credit_6_mmin` double NOT NULL,
`credit_6_mmax` double NOT NULL,
`credit_6_pmin` double NOT NULL,
`credit_6_pmax` double NOT NULL,
`credit_6_seguro` float NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
--
-- Dumping data for table `settings`
--
INSERT INTO `credit_settings` (`id`, `base_min`, `base_max`, `base_efectiva`, `base_nomina`, `simple_min`, `simple_max`, `simple_efectiva`, `simple_nomina`, `ampliada_min`, `ampliada_max`, `ampliada_efectiva`, `ampliada_nomina`,
`credit_1_mmin`,
`credit_1_mmax`,
`credit_1_pmin`,
`credit_1_pmax`,
`credit_1_seguro`,
`credit_2_mmin`,
`credit_2_mmax`,
`credit_2_pmin`,
`credit_2_pmax`,
`credit_2_seguro`,
`credit_3_mmin`,
`credit_3_mmax`,
`credit_3_pmin`,
`credit_3_pmax`,
`credit_3_seguro`,
`credit_4_mmin`,
`credit_4_mmax`,
`credit_4_pmin`,
`credit_4_pmax`,
`credit_4_seguro`,
`credit_5_mmin`,
`credit_5_mmax`,
`credit_5_pmin`,
`credit_5_pmax`,
`credit_5_seguro`,
`credit_6_mmin`,
`credit_6_mmax`,
`credit_6_pmin`,
`credit_6_pmax`,
`credit_6_seguro`
) VALUES
(1,0,1000,30.4,26.84,1001,10000,27.4,24.46,10001,0,25.4,22.85,800,20000,8,36,2.5,800,20000,8,36,2.5,1000,2000,6,12,2.5,3000,20000,12,36,2.5,4000,6000,24,24,2.5,800,5000,8,24,2.5);
| 29.798077 | 228 | 0.719264 |
1cbca78b3c2108dd916ec49be4ae22fb13bf9155 | 8,083 | asm | Assembly | Transynther/x86/_processed/NONE/_zr_/i9-9900K_12_0xa0.log_21829_1660.asm | ljhsiun2/medusa | 67d769b8a2fb42c538f10287abaf0e6dbb463f0c | [
"MIT"
] | 9 | 2020-08-13T19:41:58.000Z | 2022-03-30T12:22:51.000Z | Transynther/x86/_processed/NONE/_zr_/i9-9900K_12_0xa0.log_21829_1660.asm | ljhsiun2/medusa | 67d769b8a2fb42c538f10287abaf0e6dbb463f0c | [
"MIT"
] | 1 | 2021-04-29T06:29:35.000Z | 2021-05-13T21:02:30.000Z | Transynther/x86/_processed/NONE/_zr_/i9-9900K_12_0xa0.log_21829_1660.asm | ljhsiun2/medusa | 67d769b8a2fb42c538f10287abaf0e6dbb463f0c | [
"MIT"
] | 3 | 2020-07-14T17:07:07.000Z | 2022-03-21T01:12:22.000Z | .global s_prepare_buffers
s_prepare_buffers:
push %r11
push %r13
push %r8
push %r9
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_WC_ht+0x18871, %rsi
lea addresses_WC_ht+0x3971, %rdi
nop
nop
and %r8, %r8
mov $34, %rcx
rep movsl
nop
nop
nop
nop
nop
sub %r11, %r11
lea addresses_WC_ht+0xf371, %rsi
lea addresses_WC_ht+0x16f1, %rdi
nop
nop
nop
add $49789, %r13
mov $41, %rcx
rep movsb
xor $506, %r11
lea addresses_UC_ht+0x13429, %r11
clflush (%r11)
nop
nop
nop
nop
nop
inc %r9
mov (%r11), %r13w
nop
nop
inc %rdi
lea addresses_normal_ht+0x12fcd, %r13
nop
nop
nop
nop
nop
cmp %rdi, %rdi
mov (%r13), %rcx
nop
nop
nop
nop
nop
xor $59660, %r11
lea addresses_WC_ht+0x2771, %rdi
sub $31593, %r9
mov $0x6162636465666768, %r13
movq %r13, (%rdi)
nop
nop
nop
nop
nop
inc %rcx
lea addresses_normal_ht+0xca71, %r13
nop
nop
xor %rcx, %rcx
mov $0x6162636465666768, %rdi
movq %rdi, %xmm1
and $0xffffffffffffffc0, %r13
vmovntdq %ymm1, (%r13)
nop
nop
nop
nop
nop
sub $51432, %r13
lea addresses_WT_ht+0x1df4d, %rsi
lea addresses_WC_ht+0x4971, %rdi
clflush (%rsi)
nop
nop
nop
nop
dec %rbx
mov $41, %rcx
rep movsl
nop
nop
nop
nop
and %r8, %r8
lea addresses_UC_ht+0x13b71, %rsi
lea addresses_normal_ht+0xb5d1, %rdi
nop
add %r11, %r11
mov $60, %rcx
rep movsq
nop
nop
nop
lfence
lea addresses_UC_ht+0x13771, %rsi
xor %rbx, %rbx
mov (%rsi), %di
nop
nop
nop
nop
sub $11458, %rdi
lea addresses_A_ht+0x1d371, %r9
nop
nop
and $33430, %r8
movb $0x61, (%r9)
nop
nop
nop
nop
sub %rdi, %rdi
lea addresses_A_ht+0xc8, %rsi
lea addresses_D_ht+0xab8d, %rdi
nop
nop
nop
nop
sub %r11, %r11
mov $40, %rcx
rep movsw
nop
xor $31840, %r13
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %r9
pop %r8
pop %r13
pop %r11
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r13
push %r14
push %r9
push %rax
push %rbp
push %rsi
// Store
lea addresses_WT+0x6371, %rax
nop
nop
nop
and %rsi, %rsi
movw $0x5152, (%rax)
nop
nop
nop
add %r10, %r10
// Store
lea addresses_A+0x1a371, %rbp
nop
nop
nop
nop
nop
xor %r10, %r10
movl $0x51525354, (%rbp)
nop
nop
cmp $56899, %rax
// Store
mov $0x41740b0000000371, %rsi
nop
xor %r13, %r13
movb $0x51, (%rsi)
inc %r13
// Store
lea addresses_UC+0x15371, %r10
nop
and %r13, %r13
mov $0x5152535455565758, %rax
movq %rax, %xmm1
vmovups %ymm1, (%r10)
nop
nop
nop
sub %rax, %rax
// Store
lea addresses_WT+0x4371, %r9
sub %r13, %r13
mov $0x5152535455565758, %rbp
movq %rbp, %xmm0
movups %xmm0, (%r9)
nop
nop
nop
xor $49663, %rax
// Faulty Load
lea addresses_UC+0x19b71, %rbp
nop
cmp $51957, %r10
mov (%rbp), %r9
lea oracles, %r13
and $0xff, %r9
shlq $12, %r9
mov (%r13,%r9,1), %r9
pop %rsi
pop %rbp
pop %rax
pop %r9
pop %r14
pop %r13
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'src': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_UC', 'AVXalign': False, 'size': 16}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'NT': True, 'same': False, 'congruent': 10, 'type': 'addresses_WT', 'AVXalign': False, 'size': 2}}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 11, 'type': 'addresses_A', 'AVXalign': False, 'size': 4}}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 11, 'type': 'addresses_NC', 'AVXalign': False, 'size': 1}}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 11, 'type': 'addresses_UC', 'AVXalign': False, 'size': 32}}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 10, 'type': 'addresses_WT', 'AVXalign': False, 'size': 16}}
[Faulty Load]
{'src': {'NT': False, 'same': True, 'congruent': 0, 'type': 'addresses_UC', 'AVXalign': False, 'size': 8}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'same': False, 'congruent': 6, 'type': 'addresses_WC_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 9, 'type': 'addresses_WC_ht'}}
{'src': {'same': False, 'congruent': 11, 'type': 'addresses_WC_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 6, 'type': 'addresses_WC_ht'}}
{'src': {'NT': False, 'same': False, 'congruent': 3, 'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 2}, 'OP': 'LOAD'}
{'src': {'NT': False, 'same': True, 'congruent': 1, 'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 8}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 10, 'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 8}}
{'OP': 'STOR', 'dst': {'NT': True, 'same': False, 'congruent': 5, 'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 32}}
{'src': {'same': False, 'congruent': 2, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 9, 'type': 'addresses_WC_ht'}}
{'src': {'same': False, 'congruent': 11, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 5, 'type': 'addresses_normal_ht'}}
{'src': {'NT': False, 'same': False, 'congruent': 9, 'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 2}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 11, 'type': 'addresses_A_ht', 'AVXalign': False, 'size': 1}}
{'src': {'same': False, 'congruent': 0, 'type': 'addresses_A_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 2, 'type': 'addresses_D_ht'}}
{'00': 21829}
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
*/
| 31.574219 | 2,999 | 0.656192 |
4e5878f6ccfa619d49b2d60793464fab4961e863 | 349 | kt | Kotlin | libnavui-maps/src/main/java/com/mapbox/navigation/ui/maps/snapshotter/model/SnapshotError.kt | bikemap/mapbox-navigation-android | 5de9c3c9484466b641ab8907ce9ed316598bad56 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT"
] | null | null | null | libnavui-maps/src/main/java/com/mapbox/navigation/ui/maps/snapshotter/model/SnapshotError.kt | bikemap/mapbox-navigation-android | 5de9c3c9484466b641ab8907ce9ed316598bad56 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT"
] | null | null | null | libnavui-maps/src/main/java/com/mapbox/navigation/ui/maps/snapshotter/model/SnapshotError.kt | bikemap/mapbox-navigation-android | 5de9c3c9484466b641ab8907ce9ed316598bad56 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT"
] | 1 | 2021-07-15T16:29:31.000Z | 2021-07-15T16:29:31.000Z | package com.mapbox.navigation.ui.maps.snapshotter.model
/**
* The state is returned if there is an error generating the snapshot
* @param errorMessage an error message
* @param throwable an optional throwable value expressing the error
*/
class SnapshotError internal constructor(
val errorMessage: String?,
val throwable: Throwable?
)
| 29.083333 | 69 | 0.770774 |
7b90c0820d84c9b6c3bdaa9713f97e0a35314995 | 6,711 | swift | Swift | ios/RIBs/Classes/ComponentizedBuilder.swift | bpollman/RIBs | c682404370559deecbc0313966aba90581cb57f2 | [
"Apache-2.0"
] | 10 | 2020-02-20T07:23:06.000Z | 2022-01-24T15:12:36.000Z | ios/RIBs/Classes/ComponentizedBuilder.swift | bpollman/RIBs | c682404370559deecbc0313966aba90581cb57f2 | [
"Apache-2.0"
] | 14 | 2021-02-17T01:47:05.000Z | 2021-02-24T07:45:19.000Z | ios/RIBs/Classes/ComponentizedBuilder.swift | bpollman/RIBs | c682404370559deecbc0313966aba90581cb57f2 | [
"Apache-2.0"
] | 2 | 2021-02-03T12:52:05.000Z | 2021-03-10T14:56:40.000Z | //
// Copyright (c) 2017. Uber Technologies
//
// 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
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
/// Utility that instantiates a RIB and sets up its internal wirings.
/// This class ensures the strict one to one relationship between a
/// new instance of the RIB and a single new instance of the component.
/// Every time a new RIB is built a new instance of the corresponding
/// component is also instantiated.
///
/// This is the most generic version of the builder class that supports
/// both dynamic dependencies injected when building the RIB as well
/// as dynamic dependencies for instantiating the component. For more
/// convenient base class, please refer to `SimpleComponentizedBuilder`.
///
/// - note: Subclasses should override the `build(with)` method to
/// implement the actual RIB building logic, with the given component
/// and dynamic dependency.
/// - SeeAlso: SimpleComponentizedBuilder
open class ComponentizedBuilder<Component, Router, DynamicBuildDependency, DynamicComponentDependency>: Buildable {
// Builder should not directly retain an instance of the component.
// That would make the component's lifecycle longer than the built
// RIB. Instead, whenever a new instance of the RIB is built, a new
// instance of the DI component should also be instantiated.
/// Initializer.
///
/// - parameter componentBuilder: The closure to instantiate a new
/// instance of the DI component that should be paired with this RIB.
public init(componentBuilder: @escaping (DynamicComponentDependency) -> Component) {
self.componentBuilder = componentBuilder
}
/// Build a new instance of the RIB with the given dynamic dependencies.
///
/// - parameter dynamicBuildDependency: The dynamic dependency to use
/// to build the RIB.
/// - parameter dynamicComponentDependency: The dynamic dependency to
/// use to instantiate the component.
/// - returns: The router of the RIB.
public final func build(withDynamicBuildDependency dynamicBuildDependency: DynamicBuildDependency, dynamicComponentDependency: DynamicComponentDependency) -> Router {
return build(withDynamicBuildDependency: dynamicBuildDependency, dynamicComponentDependency: dynamicComponentDependency).1
}
/// Build a new instance of the RIB with the given dynamic dependencies.
///
/// - parameter dynamicBuildDependency: The dynamic dependency to use
/// to build the RIB.
/// - parameter dynamicComponentDependency: The dynamic dependency to
/// use to instantiate the component.
/// - returns: The tuple of component and router of the RIB.
public final func build(withDynamicBuildDependency dynamicBuildDependency: DynamicBuildDependency, dynamicComponentDependency: DynamicComponentDependency) -> (Component, Router) {
let component = componentBuilder(dynamicComponentDependency)
// Ensure each componentBuilder invocation produces a new component
// instance.
let newComponent = component as AnyObject
if lastComponent === newComponent {
assertionFailure("\(self) componentBuilder should produce new instances of component when build is invoked.")
}
lastComponent = newComponent
return (component, build(with: component, dynamicBuildDependency))
}
/// Abstract method that must be overriden to implement the RIB building
/// logic using the given component and dynamic dependency.
///
/// - note: This method should never be invoked directly. Instead
/// consumers of this builder should invoke `build(with dynamicDependency:)`.
/// - parameter component: The corresponding DI component to use.
/// - parameter dynamicBuildDependency: The given dynamic dependency.
/// - returns: The router of the RIB.
open func build(with component: Component, _ dynamicBuildDependency: DynamicBuildDependency) -> Router {
fatalError("This method should be oevrriden by the subclass.")
}
// MARK: - Private
private let componentBuilder: (DynamicComponentDependency) -> Component
private weak var lastComponent: AnyObject?
}
/// A convenient base builder class that does not require any build or
/// component dynamic dependencies.
///
/// - note: If the build method requires dynamic dependency, please
/// refer to `DynamicBuildComponentizedBuilder`. If component instantiation
/// requires dynamic dependency, please refer to `DynamicComponentizedBuilder`.
/// If both require dynamic dependencies, please use `ComponentizedBuilder`.
/// - SeeAlso: ComponentizedBuilder
open class SimpleComponentizedBuilder<Component, Router>: ComponentizedBuilder<Component, Router, (), ()> {
/// Initializer.
///
/// - parameter componentBuilder: The closure to instantiate a new
/// instance of the DI component that should be paired with this RIB.
#if compiler(>=5.0)
public init(componentBuilder: @escaping () -> Component) {
super.init(componentBuilder: componentBuilder)
}
#else
public override init(componentBuilder: @escaping () -> Component) {
super.init(componentBuilder: componentBuilder)
}
#endif
/// This method should not be directly invoked.
public final override func build(with component: Component, _ dynamicDependency: ()) -> Router {
return build(with: component)
}
/// Abstract method that must be overriden to implement the RIB building
/// logic using the given component.
///
/// - note: This method should never be invoked directly. Instead
/// consumers of this builder should invoke `build(with dynamicDependency:)`.
/// - parameter component: The corresponding DI component to use.
/// - returns: The router of the RIB.
open func build(with component: Component) -> Router {
fatalError("This method should be oevrriden by the subclass.")
}
/// Build a new instance of the RIB.
///
/// - returns: The router of the RIB.
public final func build() -> Router {
return build(withDynamicBuildDependency: (), dynamicComponentDependency: ())
}
}
| 45.965753 | 183 | 0.720012 |
0b3b1b7fa53f607bfa6820806f9bdec88c43a29d | 2,092 | py | Python | sushy/tests/unit/resources/fabric/test_endpoint.py | sapcc/sushy | 7016cc0f31050ab656e1e26c80bd44ce3e9fd57a | [
"Apache-2.0"
] | 37 | 2017-03-24T10:17:37.000Z | 2022-02-10T19:42:26.000Z | sushy/tests/unit/resources/fabric/test_endpoint.py | sapcc/sushy | 7016cc0f31050ab656e1e26c80bd44ce3e9fd57a | [
"Apache-2.0"
] | 4 | 2020-07-08T10:53:30.000Z | 2020-07-30T11:56:20.000Z | sushy/tests/unit/resources/fabric/test_endpoint.py | sapcc/sushy | 7016cc0f31050ab656e1e26c80bd44ce3e9fd57a | [
"Apache-2.0"
] | 29 | 2017-07-19T21:28:06.000Z | 2021-06-09T05:20:32.000Z | # 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
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import json
from unittest import mock
import sushy
from sushy.resources.fabric import endpoint
from sushy.tests.unit import base
class EndpointTestCase(base.TestCase):
def setUp(self):
super(EndpointTestCase, self).setUp()
self.conn = mock.Mock()
with open('sushy/tests/unit/json_samples/'
'endpoint.json') as f:
self.json_doc = json.load(f)
self.conn.get.return_value.json.return_value = self.json_doc
self.fab_endpoint = endpoint.Endpoint(
self.conn, '/redfish/v1/Fabrics/SAS/Endpoints/Drive1',
redfish_version='1.0.2')
def test__parse_atrtributes(self):
self.fab_endpoint._parse_attributes(self.json_doc)
self.assertEqual('Drive1', self.fab_endpoint.identity)
self.assertEqual('SAS Drive', self.fab_endpoint.name)
self.assertEqual(sushy.PROTOCOL_TYPE_SAS,
self.fab_endpoint.endpoint_protocol)
self.assertEqual(sushy.ENTITY_TYPE_DRIVE,
self.fab_endpoint.connected_entities[0].entity_type)
self.assertEqual(sushy.ENTITY_ROLE_TARGET,
self.fab_endpoint.connected_entities[0].entity_role)
con_entity = self.fab_endpoint.connected_entities[0]
self.assertEqual(sushy.DURABLE_NAME_FORMAT_NAA,
con_entity.identifiers[0].durable_name_format)
self.assertEqual('32ADF365C6C1B7C3',
con_entity.identifiers[0].durable_name)
| 40.230769 | 78 | 0.68021 |
bec2d68f16fc71343214ce7092df319c4798b5db | 1,111 | swift | Swift | Scroggle/Common/Extensions/UIViewControllerExtension.swift | intere/scroggle | 31803c880f20ba11da0c6a4e0d7a3fad7c61797f | [
"MIT"
] | 2 | 2017-10-23T14:46:11.000Z | 2019-03-28T16:29:34.000Z | Scroggle/Common/Extensions/UIViewControllerExtension.swift | intere/scroggle | 31803c880f20ba11da0c6a4e0d7a3fad7c61797f | [
"MIT"
] | 8 | 2018-07-15T16:14:14.000Z | 2018-11-13T12:43:20.000Z | Scroggle/Common/Extensions/UIViewControllerExtension.swift | intere/scroggle | 31803c880f20ba11da0c6a4e0d7a3fad7c61797f | [
"MIT"
] | null | null | null | //
// UIViewControllerExtension.swift
// Scroggle
//
// Created by Eric Internicola on 10/9/18.
// Copyright © 2018 Eric Internicola. All rights reserved.
//
import UIKit
extension UIViewController {
/// Are we currently in the portrait layout?
var isPortrait: Bool {
return view.bounds.height > view.bounds.width
}
/// Are we currently in the landscape layout?
var isLandscape: Bool {
return view.bounds.width > view.bounds.height
}
/// Is this device an iPad?
var isPad: Bool {
return UIDevice.current.userInterfaceIdiom == .pad
}
/// Is the current device one of the "X" models?
/// (FWIW, I hate having to resort to this, it's an anti pattern, but it is necessary)
var isXdevice: Bool {
guard UIDevice.current.userInterfaceIdiom == .phone else {
return false
}
guard max(UIScreen.main.bounds.size.height, UIScreen.main.bounds.size.width) >= 812 else {
return false
}
// 812.0 on iPhone X, XS.
// 896.0 on iPhone XS Max, XR.
return true
}
}
| 25.837209 | 98 | 0.621962 |
868fb7bfb9d661bfdb8583a4e22a67365647e725 | 1,993 | go | Go | Godeps/_workspace/src/github.com/0xfaded/eval/testgen/common.go | mewbak/godebug-1 | bfb01ae9c26601793d8cf00f074489f7ad52288a | [
"Apache-2.0"
] | 3,042 | 2015-02-04T06:29:20.000Z | 2022-02-16T01:29:31.000Z | Godeps/_workspace/src/github.com/0xfaded/eval/testgen/common.go | mewbak/godebug-1 | bfb01ae9c26601793d8cf00f074489f7ad52288a | [
"Apache-2.0"
] | 92 | 2015-02-04T06:28:39.000Z | 2021-05-05T19:26:41.000Z | Godeps/_workspace/src/github.com/0xfaded/eval/testgen/common.go | mewbak/godebug-1 | bfb01ae9c26601793d8cf00f074489f7ad52288a | [
"Apache-2.0"
] | 162 | 2015-02-19T21:12:02.000Z | 2020-12-15T18:49:22.000Z | package main
import (
"bufio"
"go/build"
"fmt"
"io"
"io/ioutil"
"strings"
"os"
"os/exec"
)
func compileExpr(expr string) (compileErrors []string, err error) {
return compileExprWithDefs(expr, "")
}
func compileExprWithDefs(expr, defs string) (compileErrors []string, err error) {
return compileExprWithDefsAndGlobals(expr, defs, "")
}
func compileExprWithDefsAndGlobals(expr, defs, globals string) (compileErrors []string, err error) {
body := `package main
%s
func main() {
%s
(func(...interface{}) {})(%s)
}
`
return compile(expr, defs, globals, body)
}
func compileVoidExpr(expr string) (compileErrors []string, err error) {
return compileVoidExprWithDefs(expr, "")
}
func compileVoidExprWithDefs(expr, defs string) (compileErrors []string, err error) {
return compileVoidExprWithDefsAndGlobals(expr, defs, "")
}
func compileVoidExprWithDefsAndGlobals(expr, defs, globals string) (compileErrors []string, err error) {
body := `package main
%s
func main() {
%s
%s
}
`
return compile(expr, defs, globals, body)
}
func compile(expr, defs, globals, body string) (compileErrors []string, err error) {
f, err := ioutil.TempFile("/tmp", "testgen")
if err != nil {
return nil, err
}
defer os.Remove(f.Name())
_, err = fmt.Fprintf(f, body, globals, defs, expr);
if err != nil {
return nil, err
}
// -e prints all errors
cmd := exec.Command(build.ToolDir + "/8g", "-e", "-o", "/dev/null", f.Name())
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
if err := cmd.Start(); err != nil {
return nil, err
}
buf := bufio.NewReader(stdout)
line, rerr := buf.ReadString('\n')
for rerr == nil {
if strings.Index(line, ": ") != -1 {
// Remove filename prefix
s := strings.SplitN(line, ": ", 2)[1]
// Remove trailing \n
s = s[:len(s)-1]
compileErrors = append(compileErrors, s)
}
line, rerr = buf.ReadString('\n')
}
if rerr != io.EOF {
return nil, rerr
} else {
return compileErrors, nil
}
}
| 19.732673 | 104 | 0.651781 |
ddd9be8fd2f56bfffe2ab8e3bb747b8bde8c5c5c | 78 | php | PHP | src/Database/Model.php | Ahmed-Ibrahimm/bubble-web | fa81bb7e84ab8d08f36efc90ed6a4e698ecf274e | [
"MIT"
] | 13 | 2021-07-21T07:57:31.000Z | 2021-07-25T21:40:21.000Z | src/Database/Model.php | Ahmed-Ibrahimm/bubble-web | fa81bb7e84ab8d08f36efc90ed6a4e698ecf274e | [
"MIT"
] | 1 | 2021-08-22T23:15:52.000Z | 2021-08-24T07:51:32.000Z | src/Database/Model.php | Ahmed-Ibrahimm/bubble-web | fa81bb7e84ab8d08f36efc90ed6a4e698ecf274e | [
"MIT"
] | 1 | 2021-08-20T20:41:59.000Z | 2021-08-20T20:41:59.000Z | <?php
namespace DinoPHP\Database;
abstract class Model extends Database {
} | 11.142857 | 39 | 0.769231 |
0a0e7a2776eea5b95fdcae59ccd057721e5c05a2 | 2,637 | ts | TypeScript | .storybook/main.ts | curology/radiance-ui | a7c286f20371ce7256bb8b067d15990afa7c791f | [
"MIT"
] | 17 | 2020-03-29T19:10:10.000Z | 2022-02-16T17:23:30.000Z | .storybook/main.ts | curology/radiance-ui | a7c286f20371ce7256bb8b067d15990afa7c791f | [
"MIT"
] | 509 | 2020-01-29T13:57:58.000Z | 2022-03-31T16:49:11.000Z | .storybook/main.ts | curology/radiance-ui | a7c286f20371ce7256bb8b067d15990afa7c791f | [
"MIT"
] | 8 | 2020-07-15T17:57:22.000Z | 2021-04-30T18:23:08.000Z | const path = require('path');
const CircularDependencyPlugin = require('circular-dependency-plugin');
const babelConfig = require('../babel.config');
const toPath = (_path: string) => path.join(process.cwd(), _path);
/**
* {@link https://storybook.js.org/docs/ember/configure/overview#configure-your-storybook-project Configure your storybook project}
*
* {@link https://github.com/storybookjs/storybook/blob/b3c4a8a4fd846977ef777d0e9f4aa5c77b0796e7/lib/core-common/src/types.ts#L224 June 2021 `next` types}
*/
const config = {
/**
* Storybook convention is to include "stories" in the filename, but it is also
* a requirement for Storybook default configuration to work correctly
*/
stories: ['../stories/**/*.stories.@(tsx|mdx)'],
logLevel: 'debug',
addons: [
'@storybook/addon-knobs',
'@storybook/addon-a11y',
'@storybook/addon-storysource',
{
name: '@storybook/addon-docs',
options: {
configureJSX: true,
babelOptions: {},
},
},
{
name: '@storybook/addon-essentials',
options: {
backgrounds: false,
controls: false,
docs: false, // Uses custom config above
},
},
],
typescript: {
check: true,
checkOptions: {},
},
babel: babelConfig,
webpackFinal: (config, { configType }) => {
// Allow resolving absolute paths within `/stories`, e.g. import * from 'stories/utils';
config.resolve.modules.push(path.resolve(__dirname, '..'));
if (configType === 'DEVELOPMENT') {
config.plugins.push(
new CircularDependencyPlugin({
exclude: /node_modules/,
// add errors to webpack instead of warnings
failOnError: true,
allowAsyncCycles: false,
// set the current working directory for displaying module paths
cwd: process.cwd(),
}),
);
}
/**
* Until Storybook migrates its own internal @emotion usage from
* v10 to v11, this allows us to maintain compatibility
*/
const emotion11CompatibleConfig = {
...config,
resolve: {
...config.resolve,
alias: {
...config.resolve.alias,
'@emotion/core': toPath('node_modules/@emotion/react'),
'@emotion/styled': toPath('node_modules/@emotion/styled'),
'emotion-theming': toPath('node_modules/@emotion/react'),
},
},
};
// Return the altered config
return emotion11CompatibleConfig;
},
reactOptions: {
fastRefresh: true,
// TODO: Does not play well with emotion theming
// strictMode: true,
},
};
module.exports = config;
| 29.3 | 154 | 0.622298 |
0edada282b20395f6590e81d40de359e2b20807f | 6,354 | c | C | deps/unixODBC-2.3.4/Drivers/MiniSQL/SQLStatistics.c | abdalla/docker-image-for-python-boto3-mysql | 43cc72ff611ddc7578ff2c815c73fc333d27074a | [
"MIT"
] | null | null | null | deps/unixODBC-2.3.4/Drivers/MiniSQL/SQLStatistics.c | abdalla/docker-image-for-python-boto3-mysql | 43cc72ff611ddc7578ff2c815c73fc333d27074a | [
"MIT"
] | null | null | null | deps/unixODBC-2.3.4/Drivers/MiniSQL/SQLStatistics.c | abdalla/docker-image-for-python-boto3-mysql | 43cc72ff611ddc7578ff2c815c73fc333d27074a | [
"MIT"
] | null | null | null | /********************************************************************
* SQLStatistics
*
**********************************************************************
*
* This code was created by Peter Harvey (mostly during Christmas 98/99).
* This code is LGPL. Please ensure that this message remains in future
* distributions and uses of this code (thats about all I get out of it).
* - Peter Harvey pharvey@codebydesign.com
*
********************************************************************/
#include <config.h>
#include "driver.h"
enum nSQLStatistics
{
TABLE_CAT = 1,
TABLE_SCHEM,
TABLE_NAME,
NON_UNIQUE,
INDEX_QUALIFIER,
INDEX_NAME,
TYPE,
ORDINAL_POSITION,
COLUMN_NAME,
ASC_OR_DESC,
CARDINALITY,
PAGES,
FILTER_CONDITION,
COL_MAX
};
m_field aSQLStatistics[] =
{
"", "", 0, 0, 0,
"TABLE_CAT", "sys", CHAR_TYPE, 50, 0,
"TABLE_SCHEM", "sys", CHAR_TYPE, 50, 0,
"TABLE_NAME", "sys", CHAR_TYPE, 50, 0,
"NON_UNIQUE", "sys", INT_TYPE, 3, 0,
"INDEX_QUALIFIER", "sys", CHAR_TYPE, 50, 0,
"INDEX_NAME", "sys", CHAR_TYPE, 50, 0,
"TYPE", "sys", INT_TYPE, 3, 0,
"ORDINAL_POSITION", "sys", CHAR_TYPE, 50, 0,
"COLUMN_NAME", "sys", CHAR_TYPE, 50, 0,
"ASC_OR_DESC", "sys", INT_TYPE, 3, 0,
"CARDINALITY", "sys", INT_TYPE, 3, 0,
"PAGES", "sys", INT_TYPE, 3, 0,
"FILTER_CONDITION", "sys", CHAR_TYPE, 50, 0
};
SQLRETURN SQLStatistics( SQLHSTMT hDrvStmt,
SQLCHAR *szCatalogName,
SQLSMALLINT nCatalogNameLength,
SQLCHAR *szSchemaName,
SQLSMALLINT nSchemaNameLength,
SQLCHAR *szTableName, /* MUST BE SUPPLIED */
SQLSMALLINT nTableNameLength,
SQLUSMALLINT nTypeOfIndex,
SQLUSMALLINT nReserved )
{
HDRVSTMT hStmt = (HDRVSTMT)hDrvStmt;
m_result *pResults; /* mSQL DATA */
m_field *pField; /* mSQL field */
COLUMNHDR *pColumnHeader;
int nColumn;
long nCols;
long nCurRow;
long nRow;
char szBuffer[101];
int nIndexColumns = 0;
int nNormalColumns = 0;
/* SANITY CHECKS */
if( hStmt == SQL_NULL_HSTMT )
return SQL_INVALID_HANDLE;
sprintf( hStmt->szSqlMsg, "hStmt = $%08lX", hStmt );
logPushMsg( hStmt->hLog, __FILE__, __FILE__, __LINE__, LOG_WARNING, LOG_WARNING, hStmt->szSqlMsg );
if ( szTableName == NULL )
{
logPushMsg( hStmt->hLog, __FILE__, __FILE__, __LINE__, LOG_WARNING, LOG_WARNING, "SQL_ERROR No table name" );
return SQL_ERROR;
}
if ( szTableName[0] == '\0' )
{
logPushMsg( hStmt->hLog, __FILE__, __FILE__, __LINE__, LOG_WARNING, LOG_WARNING, "SQL_ERROR No table name" );
return SQL_ERROR;
}
/**************************
* close any existing result
**************************/
if ( hStmt->hStmtExtras->aResults )
_FreeResults( hStmt->hStmtExtras );
if ( hStmt->pszQuery != NULL )
free( hStmt->pszQuery );
hStmt->pszQuery = NULL;
/************************
* generate a result set listing columns (these will be our rows)
************************/
pResults = msqlListFields( ((HDRVDBC)hStmt->hDbc)->hDbcExtras->hServer, szTableName );
if ( pResults == NULL )
{
sprintf( hStmt->szSqlMsg, "SQL_ERROR Query failed. %s", msqlErrMsg );
logPushMsg( hStmt->hLog, __FILE__, __FILE__, __LINE__, LOG_WARNING, LOG_WARNING, hStmt->szSqlMsg );
return SQL_ERROR;
}
/************************
* how many columns are indexs?
************************/
nIndexColumns = 0;
while ( pField = msqlFetchField( pResults ) )
{
if ( pField->type == IDX_TYPE)
nIndexColumns++;
}
msqlFieldSeek( pResults, 0 );
nNormalColumns = msqlNumFields( pResults ) - nIndexColumns;
/**************************
* allocate memory for columns headers and result data (row 0 is column header while col 0 is reserved for bookmarks)
**************************/
hStmt->hStmtExtras->nCols = COL_MAX-1;
hStmt->hStmtExtras->nRows = nIndexColumns;
hStmt->hStmtExtras->nRow = 0;
hStmt->hStmtExtras->aResults = malloc( sizeof(char*) * (hStmt->hStmtExtras->nRows+1) * (hStmt->hStmtExtras->nCols+1) );
memset( hStmt->hStmtExtras->aResults, 0, sizeof(char*) * (hStmt->hStmtExtras->nRows+1) * (hStmt->hStmtExtras->nCols+1) );
if ( hStmt->hStmtExtras->aResults == NULL )
{
logPushMsg( hStmt->hLog, __FILE__, __FILE__, __LINE__, LOG_WARNING, LOG_WARNING, "Not enough memory. (malloc failed)" );
hStmt->hStmtExtras->nRows = 0;
hStmt->hStmtExtras->nCols = 0;
msqlFreeResult( pResults );
return SQL_ERROR;
}
/**************************
* gather column header information (save col 0 for bookmarks)
**************************/
for ( nColumn = 1; nColumn < COL_MAX; nColumn++ )
{
(hStmt->hStmtExtras->aResults)[nColumn] = malloc( sizeof(COLUMNHDR) );
pColumnHeader = (COLUMNHDR*)(hStmt->hStmtExtras->aResults)[nColumn];
memset( pColumnHeader, 0, sizeof(COLUMNHDR) );
_NativeToSQLColumnHeader( pColumnHeader, &(aSQLStatistics[nColumn]) );
}
/************************
* gather data (save col 0 for bookmarks and factor out normal columns)
************************/
nCols = hStmt->hStmtExtras->nCols;
hStmt->hStmtExtras->nRow = 0;
for ( nCurRow = 1; nCurRow <= msqlNumFields( pResults ); nCurRow++ )
{
pField = msqlFetchField( pResults );
if ( pField->type == IDX_TYPE)
{
hStmt->hStmtExtras->nRow++;
nRow = hStmt->hStmtExtras->nRow;
for ( nColumn = 1; nColumn < COL_MAX; nColumn++ )
{
switch ( nColumn )
{
case TABLE_NAME:
(hStmt->hStmtExtras->aResults)[nRow*nCols+nColumn] = (char*)strdup( szTableName );
break;
case INDEX_NAME:
(hStmt->hStmtExtras->aResults)[nRow*nCols+nColumn] = (char*)strdup( pField->name );
break;
case NON_UNIQUE:
(hStmt->hStmtExtras->aResults)[nRow*nCols+nColumn] = (char *)strdup( IS_NOT_NULL( pField->flags ) ? "0" : "1" );
break;
default:
(hStmt->hStmtExtras->aResults)[nRow*nCols+nColumn] = NULL;
} /* switch nColumn */
} /* for nColumn */
} /* if */
} /* for nRow */
hStmt->hStmtExtras->nRow = 0;
/**************************
* free the snapshot
**************************/
msqlFreeResult( pResults );
logPushMsg( hStmt->hLog, __FILE__, __FILE__, __LINE__, LOG_INFO, LOG_INFO, "SQL_SUCCESS" );
return SQL_SUCCESS;
}
| 31.929648 | 122 | 0.58955 |
0aa5f90596d86d3afb54fb1d31550610b9032d24 | 11,834 | swift | Swift | JivoShared/Models/Guest/Guest+Update.swift | JivoChat/JMShared | 062cd25e989e7ab2f5c4379ddfd1744fa78987c5 | [
"MIT"
] | null | null | null | JivoShared/Models/Guest/Guest+Update.swift | JivoChat/JMShared | 062cd25e989e7ab2f5c4379ddfd1744fa78987c5 | [
"MIT"
] | null | null | null | JivoShared/Models/Guest/Guest+Update.swift | JivoChat/JMShared | 062cd25e989e7ab2f5c4379ddfd1744fa78987c5 | [
"MIT"
] | null | null | null | //
// Guest+Update.swift
// JivoMobile
//
// Created by Stan Potemkin on 05.09.2020.
// Copyright © 2020 JivoSite. All rights reserved.
//
import Foundation
import JMCodingKit
extension Guest {
public func performApply(inside context: IDatabaseContext, with change: BaseModelChange) {
if let c = change as? GuestBaseChange {
if _ID == "" { _ID = c.ID }
if _agentID == 0 { _agentID = abs(c.agentID ?? _agentID) }
if _startDate == nil { _startDate = Date() }
if not(c.siteID.isEmpty) { _channelID = c.siteID }
}
if !(change is GuestRemovalChange) {
_lastUpdate = Date()
_disappearDate = nil
}
if let c = change as? GuestGeneralChange {
_sourceIP = c.sourceIP
_sourcePort = c.sourcePort
_regionCode = c.regionCode
_countryCode = c.countryCode
_countryName = c.countryName
_regionName = c.regionName
_cityName = c.cityName
_organization = c.organization
}
else if let c = change as? GuestClientChange {
_clientID = c.clientID
}
else if let c = change as? GuestNameChange {
_name = c.name
}
else if let c = change as? GuestProactiveChange {
_proactiveAgent = context.agent(for: c.proactiveAgentID, provideDefault: true)
}
else if let c = change as? GuestStatusChange {
_status = c.status
}
else if let c = change as? GuestPageLinkChange {
_pageLink = c.link
}
else if let c = change as? GuestPageTitleChange {
_pageTitle = c.title
}
else if let c = change as? GuestStartTimeChange {
_startDate = Date().addingTimeInterval(-c.timestamp)
}
else if let c = change as? GuestUTMChange {
_utm = context.insert(of: ClientSessionUTM.self, with: c.utm)
}
else if let c = change as? GuestVisitsChange {
_visitsNumber = c.number
}
else if let c = change as? GuestNavigatesChange {
_navigatesNumber = c.number
}
else if let c = change as? GuestVisibleChange {
_visible = c.value
}
else if let c = change as? GuestAgentsChange {
let attendees = c.agentIDs.map {
ChatAttendeeGeneralChange(
ID: $0,
relation: "attendee",
comment: nil,
invitedBy: nil,
isAssistant: false,
receivedMessageID: 0,
unreadNumber: 0,
notifications: nil
)
}
_attendees.set(context.insert(of: ChatAttendee.self, with: attendees))
}
else if let c = change as? GuestWidgetVersionChange {
_widgetVersion = c.version
}
else if let _ = change as? GuestUpdateChange {
_lastUpdate = Date()
}
else if let _ = change as? GuestRemovalChange {
_disappearDate = Date()
}
}
public func performDelete(inside context: IDatabaseContext) {
context.customRemove(objects: _attendees.toArray(), recursive: true)
context.customRemove(objects: [_utm].flatten(), recursive: true)
}
}
public func GuestChangeParse(for item: String) -> GuestBaseChange? {
let args = item.split(separator: "\t", omittingEmptySubsequences: false).map(String.init)
guard args.count >= 4 else { return nil }
switch args[3] {
case "+": return GuestGeneralChange(arguments: args)
case "cid": return GuestClientChange(arguments: args)
case "name": return GuestNameChange(arguments: args)
case "status": return GuestStatusChange(arguments: args)
case "pa_id": return GuestProactiveChange(arguments: args)
case "purl": return GuestPageLinkChange(arguments: args)
case "ptitle": return GuestPageTitleChange(arguments: args)
case "startsec": return GuestStartTimeChange(arguments: args)
case "utm": return GuestUTMChange(arguments: args)
case "visits": return GuestVisitsChange(arguments: args)
case "navcount": return GuestNavigatesChange(arguments: args)
case "visible": return GuestVisibleChange(arguments: args)
case "agentids": return GuestAgentsChange(arguments: args)
case "wversion": return GuestWidgetVersionChange(arguments: args)
case "-": return GuestRemovalChange(arguments: args)
default: return nil
}
}
open class GuestBaseChange: BaseModelChange {
public let ID: String
public let siteID: String
public let agentID: Int?
open override var stringKey: DatabaseContextMainKey<String>? {
return DatabaseContextMainKey(key: "_ID", value: ID)
}
public init(ID: String) {
self.ID = ID
self.siteID = String()
self.agentID = nil
super.init()
}
public init(arguments: [String]) {
ID = arguments.stringOrEmpty(at: 0)
siteID = arguments.stringOrEmpty(at: 1)
agentID = arguments.stringOrEmpty(at: 2).toInt()
super.init()
}
required public init(json: JsonElement) {
fatalError("init(json:) has not been implemented")
}
open override var isValid: Bool {
guard !ID.isEmpty else { return false }
guard !siteID.isEmpty else { return false }
return true
}
}
open class GuestGeneralChange: GuestBaseChange {
public let sourceIP: String
public let sourcePort: Int
public let regionCode: Int
public let countryCode: String
public let countryName: String
public let regionName: String
public let cityName: String
public let organization: String
override init(arguments: [String]) {
sourceIP = arguments.stringOrEmpty(at: 4)
sourcePort = arguments.stringOrEmpty(at: 5).toInt()
regionCode = arguments.stringOrEmpty(at: 6).toInt()
countryCode = arguments.stringOrEmpty(at: 7)
countryName = arguments.stringOrEmpty(at: 8)
regionName = arguments.stringOrEmpty(at: 9)
cityName = arguments.stringOrEmpty(at: 10)
organization = arguments.stringOrEmpty(at: 13)
super.init(arguments: arguments)
}
required public init(json: JsonElement) {
fatalError("init(json:) has not been implemented")
}
}
open class GuestClientChange: GuestBaseChange {
public let clientID: Int
override init(arguments: [String]) {
clientID = arguments.stringOrEmpty(at: 4).toInt()
super.init(arguments: arguments)
}
required public init(json: JsonElement) {
fatalError("init(json:) has not been implemented")
}
}
open class GuestStatusChange: GuestBaseChange {
public let status: String
override init(arguments: [String]) {
status = arguments.stringOrEmpty(at: 4)
super.init(arguments: arguments)
}
required public init(json: JsonElement) {
fatalError("init(json:) has not been implemented")
}
}
open class GuestProactiveChange: GuestBaseChange {
public let proactiveAgentID: Int
override init(arguments: [String]) {
proactiveAgentID = arguments.stringOrEmpty(at: 4).toInt()
super.init(arguments: arguments)
}
required public init(json: JsonElement) {
fatalError("init(json:) has not been implemented")
}
}
open class GuestNameChange: GuestBaseChange {
public let name: String
override init(arguments: [String]) {
name = arguments.stringOrEmpty(at: 4)
super.init(arguments: arguments)
}
required public init(json: JsonElement) {
fatalError("init(json:) has not been implemented")
}
}
open class GuestPageLinkChange: GuestBaseChange {
public let link: String
override init(arguments: [String]) {
link = arguments.stringOrEmpty(at: 4)
super.init(arguments: arguments)
}
required public init(json: JsonElement) {
fatalError("init(json:) has not been implemented")
}
}
open class GuestPageTitleChange: GuestBaseChange {
public let title: String
override init(arguments: [String]) {
title = arguments.stringOrEmpty(at: 4)
super.init(arguments: arguments)
}
required public init(json: JsonElement) {
fatalError("init(json:) has not been implemented")
}
}
open class GuestStartTimeChange: GuestBaseChange {
public let timestamp: TimeInterval
override init(arguments: [String]) {
timestamp = TimeInterval(arguments.stringOrEmpty(at: 4).toInt())
super.init(arguments: arguments)
}
required public init(json: JsonElement) {
fatalError("init(json:) has not been implemented")
}
}
open class GuestUTMChange: GuestBaseChange {
private static var jsonCoder = JsonCoder()
public let utm: ClientSessionUTMGeneralChange?
override init(arguments: [String]) {
utm = GuestUTMChange.jsonCoder.decode(raw: arguments.stringOrEmpty(at: 4))?.parse()
super.init(arguments: arguments)
}
required public init(json: JsonElement) {
fatalError("init(json:) has not been implemented")
}
}
open class GuestVisitsChange: GuestBaseChange {
public let number: Int
override init(arguments: [String]) {
number = arguments.stringOrEmpty(at: 4).toInt()
super.init(arguments: arguments)
}
required public init(json: JsonElement) {
fatalError("init(json:) has not been implemented")
}
}
open class GuestNavigatesChange: GuestBaseChange {
public let number: Int
override init(arguments: [String]) {
number = arguments.stringOrEmpty(at: 4).toInt()
super.init(arguments: arguments)
}
required public init(json: JsonElement) {
fatalError("init(json:) has not been implemented")
}
}
open class GuestVisibleChange: GuestBaseChange {
public let value: Bool
override init(arguments: [String]) {
value = arguments.stringOrEmpty(at: 4).toBool()
super.init(arguments: arguments)
}
required public init(json: JsonElement) {
fatalError("init(json:) has not been implemented")
}
}
open class GuestAgentsChange: GuestBaseChange {
private static var jsonCoder = JsonCoder()
public let agentIDs: [Int]
override init(arguments: [String]) {
let idsArgument = arguments.stringOrEmpty(at: 4)
let idsSource: String
if idsArgument.hasPrefix("[") {
idsSource = idsArgument
}
else if idsArgument == "false" {
idsSource = "[]"
}
else {
idsSource = "[\(idsArgument)]"
}
agentIDs = GuestAgentsChange.jsonCoder.decode(raw: idsSource)?.intArray ?? []
super.init(arguments: arguments)
}
required public init(json: JsonElement) {
fatalError("init(json:) has not been implemented")
}
}
open class GuestWidgetVersionChange: GuestBaseChange {
public let version: String
override init(arguments: [String]) {
version = arguments.stringOrEmpty(at: 4)
super.init(arguments: arguments)
}
required public init(json: JsonElement) {
fatalError("init(json:) has not been implemented")
}
}
public final class GuestUpdateChange: GuestBaseChange {
}
open class GuestRemovalChange: GuestBaseChange {
override init(arguments: [String]) {
super.init(arguments: arguments)
}
required public init(json: JsonElement) {
fatalError("init(json:) has not been implemented")
}
}
| 32.333333 | 94 | 0.625063 |
1750fb832112782e817d7bf23e384766672f343b | 2,196 | html | HTML | _posts/CS-algorithm/2010-05-21-Longest common subsequence problem..html | cutepig123/cutepig123.github.io | 38e8dde720d79b6e7816bbbe15913edc234b7ad7 | [
"MIT"
] | 3 | 2022-02-08T03:51:49.000Z | 2022-02-16T06:03:07.000Z | _posts/CS-algorithm/2010-05-21-Longest common subsequence problem..html | cutepig123/cutepig123.github.io | 38e8dde720d79b6e7816bbbe15913edc234b7ad7 | [
"MIT"
] | 394 | 2021-03-14T03:17:40.000Z | 2022-03-15T02:55:38.000Z | _posts/CS-algorithm/2010-05-21-Longest common subsequence problem..html | cutepig123/cutepig123.github.io | 38e8dde720d79b6e7816bbbe15913edc234b7ad7 | [
"MIT"
] | 1 | 2021-08-29T09:22:25.000Z | 2021-08-29T09:22:25.000Z | <p>http://en.wikipedia.org/wiki/Longest_common_subsequence_problem</p><p> </p><p><h3><span id="LCS_function_defined"><em>LCS</em> function defined</span></h3> <p>Let two sequences be defined as follows: <em>X</em> = (<em>x</em><sub>1</sub>, <em>x</em><sub>2</sub>...<em>x</em><sub>m</sub>) and <em>Y</em> = (<em>y</em><sub>1</sub>, <em>y</em><sub>2</sub>...<em>y</em><sub>n</sub>). The prefixes of <em>X</em> are <em>X</em><sub>1, 2,...m</sub>; the prefixes of <em>Y</em> are <em>Y</em><sub>1, 2,...n</sub>. Let <em>LCS</em>(<em>X</em><sub><em>i</em></sub>, <em>Y</em><sub><em>j</em></sub>) represent the set of longest common subsequence of prefixes <em>X<sub>i</sub></em> and <em>Y<sub>j</sub></em>. This set of sequences is given by the following.</p> <dl><dd><img alt="LCS\left(X_{i},Y_{j}\right) = \begin{cases} \empty & \mbox{ if }\ i = 0 \mbox{ or } j = 0 \\ \textrm{ ( } LCS\left(X_{i-1},Y_{j-1}\right), x_i) & \mbox{ if } x_i = y_j \\ \mbox{longest}\left(LCS\left(X_{i},Y_{j-1}\right),LCS\left(X_{i-1},Y_{j}\right)\right) & \mbox{ if } x_i \ne y_j \\ \end{cases}" src="http://upload.wikimedia.org/math/e/4/9/e49ef6db695cb7edc3da7d67325fd97a.png" /></dd></dl> <p>To find the longest subsequences common to <em>X<sub>i</sub></em> and <em>Y<sub>j</sub></em>, compare the elements <em>x<sub>i</sub></em> and <em>y<sub>i</sub></em>. If they are equal, then the sequence <em>LCS</em>(<em>X</em><sub><em>i</em>-1</sub>, <em>Y</em><sub><em>j</em>-1</sub>) is extended by that element, <em>x<sub>i</sub></em>. If they are not equal, then the longer of the two sequences, <em>LCS</em>(<em>X</em><sub><em>i</em></sub>, <em>Y</em><sub><em>j</em>-1</sub>), and <em>LCS</em>(<em>X</em><sub><em>i</em>-1</sub>, <em>Y</em><sub><em>j</em></sub>), is retained. (If they are both the same length, but not identical, then both are retained.) Notice that the subscripts are reduced by 1 in these formulas. That can result in a subscript of 0. Since the sequence elements are defined to start at 1, it was necessary to add the requirement that the LCS is empty when a subscript is zero.</p></p><p> </p><p>http://www.csie.ntnu.edu.tw/~u91029/LongestCommonSubsequence.html </p> | 2,196 | 2,196 | 0.6398 |
98a121f287d5874310e82b7b11b6f6d195cc5d9f | 1,017 | html | HTML | manuscript/page-52/body.html | marvindanig/cheri | 1f9cdfe02edfbc170d890515ff0a3802d971582f | [
"BlueOak-1.0.0",
"CC-BY-4.0",
"Unlicense"
] | null | null | null | manuscript/page-52/body.html | marvindanig/cheri | 1f9cdfe02edfbc170d890515ff0a3802d971582f | [
"BlueOak-1.0.0",
"CC-BY-4.0",
"Unlicense"
] | null | null | null | manuscript/page-52/body.html | marvindanig/cheri | 1f9cdfe02edfbc170d890515ff0a3802d971582f | [
"BlueOak-1.0.0",
"CC-BY-4.0",
"Unlicense"
] | null | null | null | <div class="leaf flex"><div class="inner justify"><p class="no-indent ">revenu…. Les femmes… je les ai vues."</p><p>Il disait ces choses basses d'une voix assoupie, dont Léa écoutait le son plein et doux et recevait le souffle tiède sur son oreille. Il avait saisi le long collier de Léa et roulait les grosses perles entre ses doigts. Elle passa son bras sous la tête de Chéri et le rapprocha d'elle, sans arrière-pensée, confiante dans l'habitude qu'elle avait de cet enfant, et elle le berça.</p><p>"Je suis bien, soupira-t-il. T'es un frère, je suis bien…."</p><p>Elle sourit comme sous une louange très précieuse. Chéri semblait s'endormir. Elle regardait de tout près les cils brillants, comme mouillés, rabattus sur la joue, et cette joue amaigrie qui portait les traces d'une fatigue sans bonheur. La lèvre supérieure, rasée du matin, bleuissait déjà, et les lampes roses rendaient un sang factice à la bouche….</p><p class=" stretch-last-line ">"Pas de femmes! déclara Chéri comme en songe.</p></div> </div> | 1,017 | 1,017 | 0.757129 |
f081d74683e4da50d27ee2a254cfa3157f59305b | 924 | py | Python | tests/functional/modules/test_zos_tso_command.py | IBM/zos-core-collection-ftp | 017d2e031d64984571bd9bb330f49adaced387a6 | [
"Apache-2.0"
] | 4 | 2021-03-17T02:24:02.000Z | 2022-01-28T22:08:17.000Z | tests/functional/modules/test_zos_tso_command.py | IBM/zos-core-collection-ftp | 017d2e031d64984571bd9bb330f49adaced387a6 | [
"Apache-2.0"
] | null | null | null | tests/functional/modules/test_zos_tso_command.py | IBM/zos-core-collection-ftp | 017d2e031d64984571bd9bb330f49adaced387a6 | [
"Apache-2.0"
] | null | null | null | from __future__ import absolute_import, division, print_function
__metaclass__ = type
import os
import sys
import warnings
import ansible.constants
import ansible.errors
import ansible.utils
import pytest
from pprint import pprint
# The positive path test
def test_zos_tso_command_listuser(ansible_adhoc):
hosts = ansible_adhoc(inventory='localhost', connection='local')
print('--- hosts.all ---')
pprint(hosts.all)
pprint(hosts.all.options)
pprint(vars(hosts.all.options['inventory_manager']))
pprint(hosts.all.options['inventory_manager']._inventory.hosts)
hosts.all.options['inventory_manager']._inventory.hosts
results = hosts.localhost.zos_tso_command(commands=["LU"])
print('--- results.contacted ---')
pprint(results.contacted)
for result in results.contacted.values():
assert result.get("output")[0].get("rc") == 0
assert result.get("changed") is True
| 30.8 | 68 | 0.737013 |
84c680eb4910e3f169fa2e131c421229a6b29712 | 108 | h | C | Source/iPhone/HomeNavigationBar.h | reddit/AlienBlue | cc37f574c244ec2b49ad780a7edb100f0df0e400 | [
"BSD-3-Clause"
] | 23 | 2021-10-04T19:39:05.000Z | 2022-03-30T15:00:15.000Z | Source/iPhone/HomeNavigationBar.h | reddit/AlienBlue | cc37f574c244ec2b49ad780a7edb100f0df0e400 | [
"BSD-3-Clause"
] | null | null | null | Source/iPhone/HomeNavigationBar.h | reddit/AlienBlue | cc37f574c244ec2b49ad780a7edb100f0df0e400 | [
"BSD-3-Clause"
] | 1 | 2021-10-05T18:21:49.000Z | 2021-10-05T18:21:49.000Z | #import "ABCustomOutlineNavigationBar.h"
@interface HomeNavigationBar : ABCustomOutlineNavigationBar
@end
| 18 | 59 | 0.851852 |
87815b0b36080bec278145a51271d9e6a723aeb2 | 876 | html | HTML | manuscript/page-559/body.html | marvindanig/anne-of-green-gables | 3f17157e2812837c098131408547de5261c202a1 | [
"CECILL-B"
] | null | null | null | manuscript/page-559/body.html | marvindanig/anne-of-green-gables | 3f17157e2812837c098131408547de5261c202a1 | [
"CECILL-B"
] | null | null | null | manuscript/page-559/body.html | marvindanig/anne-of-green-gables | 3f17157e2812837c098131408547de5261c202a1 | [
"CECILL-B"
] | null | null | null | <div class="leaf flex"><div class="inner justify"><p>“I don’t see how I’m going to eat breakfast,” said Anne rapturously. “Breakfast seems so commonplace at such an exciting moment. I’d rather feast my eyes on that dress. I’m so glad that puffed sleeves are still fashionable. It did seem to me that I’d never get over it if they went out before I had a dress with them. I’d never have felt quite satisfied, you see. It was lovely of Mrs. Lynde to give me the ribbon too. I feel that I ought to be a very good girl indeed. It’s at times like this I’m sorry I’m not a model little girl; and I always resolve that I will be in future. But somehow it’s hard to carry out your resolutions when irresistible temptations come. Still, I really will make an extra effort after this.”</p></div> </div> | 876 | 876 | 0.763699 |
fb218c0a49a4e04a527626e4cb6d9b9fd0982229 | 373 | go | Go | pkg/tsuru/model_certificate_set_data.go | tsuru/go-tsuruclient | 0d2868229cfd46041fa9987ced88e6061934a316 | [
"BSD-3-Clause"
] | 5 | 2018-04-05T18:56:53.000Z | 2021-05-13T01:43:44.000Z | pkg/tsuru/model_certificate_set_data.go | tsuru/go-tsuruclient | 0d2868229cfd46041fa9987ced88e6061934a316 | [
"BSD-3-Clause"
] | 3 | 2019-10-23T14:30:49.000Z | 2021-07-06T19:35:42.000Z | pkg/tsuru/model_certificate_set_data.go | tsuru/go-tsuruclient | 0d2868229cfd46041fa9987ced88e6061934a316 | [
"BSD-3-Clause"
] | 10 | 2018-04-05T18:55:54.000Z | 2021-08-12T19:57:40.000Z | /*
* Tsuru
*
* Open source, extensible and Docker-based Platform as a Service (PaaS)
*
* API version: 1.6
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package tsuru
type CertificateSetData struct {
Cname string `json:"cname,omitempty"`
Certificate []byte `json:"certificate,omitempty"`
Key []byte `json:"key,omitempty"`
}
| 21.941176 | 72 | 0.686327 |
729f61d18224f6efbb54c2a3dabb25344051c6b4 | 1,911 | rs | Rust | src/tg_bot/mod.rs | savelev1/telegram-remote-hopr-chat | e88dcd5e6f7a238ec80374d9b9474a1ae39e633d | [
"Apache-2.0"
] | null | null | null | src/tg_bot/mod.rs | savelev1/telegram-remote-hopr-chat | e88dcd5e6f7a238ec80374d9b9474a1ae39e633d | [
"Apache-2.0"
] | null | null | null | src/tg_bot/mod.rs | savelev1/telegram-remote-hopr-chat | e88dcd5e6f7a238ec80374d9b9474a1ae39e633d | [
"Apache-2.0"
] | null | null | null | use std::sync::mpsc::Sender;
use std::thread;
use futures::StreamExt;
use telegram_bot::*;
use tokio::runtime::Runtime;
pub struct TgBot {
token: String,
api: Api,
pub is_started: bool,
}
impl TgBot {
pub fn new(token: &String) -> TgBot {
TgBot {
token: token.clone(),
api: Api::new(token),
is_started: false,
}
}
pub async fn run(&mut self, sender: Sender<Message>) {
let cloned_sender = sender.clone();
let token = self.token.clone();
thread::Builder::new().name("tg_bot".to_string()).spawn(move || {
Runtime::new().unwrap().block_on(async {
let thread_api = Api::new(token);
let mut stream = thread_api.stream();
loop {
if let Some(result) = stream.next().await {
if let Ok(update) = result {
if let UpdateKind::Message(message) = update.kind {
cloned_sender.send(message).unwrap_or_default();
}
}
}
}
})
}).unwrap();
}
pub async fn send(&self, message: &Message, text: &String) {
if text.trim().len() > 0 {
if let Err(_err) = self.api.send(message.chat.text(format!("{}", text)).parse_mode(ParseMode::Html)).await {
println!("Error sending message to bot: {}", _err);
}
}
}
pub async fn send_pre(&self, message: &Message, text: &String) {
if text.trim().len() > 0 {
self.send(message, &format!("<pre>{}</pre>", text)).await;
}
}
pub async fn send_code(&self, message: &Message, text: &String) {
if text.trim().len() > 0 {
self.send(message, &format!("<code>{}</code>", text)).await;
}
}
} | 30.822581 | 120 | 0.487703 |
3ff175ed1edcd5dd0e8f896b5023724654cf721c | 574 | asm | Assembly | oeis/069/A069126.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 11 | 2021-08-22T19:44:55.000Z | 2022-03-20T16:47:57.000Z | oeis/069/A069126.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 9 | 2021-08-29T13:15:54.000Z | 2022-03-09T19:52:31.000Z | oeis/069/A069126.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 3 | 2021-08-22T20:56:47.000Z | 2021-09-29T06:26:12.000Z | ; A069126: Centered 13-gonal numbers.
; 1,14,40,79,131,196,274,365,469,586,716,859,1015,1184,1366,1561,1769,1990,2224,2471,2731,3004,3290,3589,3901,4226,4564,4915,5279,5656,6046,6449,6865,7294,7736,8191,8659,9140,9634,10141,10661,11194,11740,12299,12871,13456,14054,14665,15289,15926,16576,17239,17915,18604,19306,20021,20749,21490,22244,23011,23791,24584,25390,26209,27041,27886,28744,29615,30499,31396,32306,33229,34165,35114,36076,37051,38039,39040,40054,41081,42121,43174,44240,45319,46411,47516,48634,49765,50909,52066,53236,54419
add $0,1
bin $0,2
mul $0,13
add $0,1
| 71.75 | 497 | 0.790941 |
134b8d3f6fea8d0b45bf4f0a00b17dff0cb83314 | 570 | h | C | src/IOChannels/IO_Channel_Hw.h | dajuly20/ControlPi | e03ed36eb062007051ac9d35cde01f441d82bde7 | [
"MIT"
] | null | null | null | src/IOChannels/IO_Channel_Hw.h | dajuly20/ControlPi | e03ed36eb062007051ac9d35cde01f441d82bde7 | [
"MIT"
] | null | null | null | src/IOChannels/IO_Channel_Hw.h | dajuly20/ControlPi | e03ed36eb062007051ac9d35cde01f441d82bde7 | [
"MIT"
] | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: HW_Channel.h
* Author: julian
*
* Created on December 18, 2018, 6:45 PM
*/
#ifndef HW_CHANNEL_H
#define HW_CHANNEL_H
#include "IO_Channel.h"
class IO_Channel_Hw : public IO_Channel {
public:
IO_Channel_Hw(configEntity* _conf);
IO_Channel_Hw(const IO_Channel_Hw& orig);
virtual ~IO_Channel_Hw();
IO_Channel_Hw(){};
};
#endif /* HW_CHANNEL_H */
| 19 | 79 | 0.703509 |
40b13a714ce92da08268e92417452d13acbc8847 | 1,495 | py | Python | release/stubs.min/Autodesk/Revit/DB/__init___parts/LayoutRuleFixedNumber.py | YKato521/ironpython-stubs | b1f7c580de48528490b3ee5791b04898be95a9ae | [
"MIT"
] | null | null | null | release/stubs.min/Autodesk/Revit/DB/__init___parts/LayoutRuleFixedNumber.py | YKato521/ironpython-stubs | b1f7c580de48528490b3ee5791b04898be95a9ae | [
"MIT"
] | null | null | null | release/stubs.min/Autodesk/Revit/DB/__init___parts/LayoutRuleFixedNumber.py | YKato521/ironpython-stubs | b1f7c580de48528490b3ee5791b04898be95a9ae | [
"MIT"
] | null | null | null | class LayoutRuleFixedNumber(LayoutRule, IDisposable):
"""
This class indicate the layout rule of a Beam System is Fixed-Number.
LayoutRuleFixedNumber(numberOfLines: int)
"""
def Dispose(self):
""" Dispose(self: LayoutRuleFixedNumber,A_0: bool) """
pass
def ReleaseManagedResources(self, *args):
""" ReleaseManagedResources(self: APIObject) """
pass
def ReleaseUnmanagedResources(self, *args):
""" ReleaseUnmanagedResources(self: APIObject) """
pass
def __enter__(self, *args):
""" __enter__(self: IDisposable) -> object """
pass
def __exit__(self, *args):
""" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) """
pass
def __init__(self, *args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self, numberOfLines):
""" __new__(cls: type,numberOfLines: int) """
pass
NumberOfLines = property(
lambda self: object(), lambda self, v: None, lambda self: None
)
"""Get or set the number of the beams in a beam system.
Get: NumberOfLines(self: LayoutRuleFixedNumber) -> int
Set: NumberOfLines(self: LayoutRuleFixedNumber)=value
"""
| 28.207547 | 221 | 0.630769 |
d25386e21888918ada21c8ca00f67cbe32b8351a | 317 | php | PHP | app/Http/Controllers/Admin/HomeController.php | rupa4ok/refactor_blog | c3d2a53dacc623f8d8521e200d37c543fdeb43b3 | [
"MIT"
] | null | null | null | app/Http/Controllers/Admin/HomeController.php | rupa4ok/refactor_blog | c3d2a53dacc623f8d8521e200d37c543fdeb43b3 | [
"MIT"
] | 84 | 2021-03-13T21:06:17.000Z | 2022-03-31T21:01:42.000Z | app/Http/Controllers/Admin/HomeController.php | rupa4ok/refactor_blog | c3d2a53dacc623f8d8521e200d37c543fdeb43b3 | [
"MIT"
] | null | null | null | <?php
namespace App\Http\Controllers\Admin;
use App\Entity\Article\Article;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class HomeController extends Controller
{
public function index()
{
$articles = $articles = Article::get();;
return view('admin.home', compact('articles'));
}
} | 17.611111 | 49 | 0.728707 |
3e5bc336c643877e42ac3214957f8f2be26778f3 | 730 | c | C | base/libsys/common.c | losso3000/demoscene | f1dc78bcfcc43bdfbd85c90366fdeb948e0ab365 | [
"Artistic-2.0"
] | null | null | null | base/libsys/common.c | losso3000/demoscene | f1dc78bcfcc43bdfbd85c90366fdeb948e0ab365 | [
"Artistic-2.0"
] | null | null | null | base/libsys/common.c | losso3000/demoscene | f1dc78bcfcc43bdfbd85c90366fdeb948e0ab365 | [
"Artistic-2.0"
] | null | null | null | #include "rawio.h"
#include "hardware.h"
#include "common.h"
void Log(const char *format, ...) {
va_list args;
va_start(args, format);
kvprintf(format, (kvprintf_fn_t *)DPutChar, NULL, args);
va_end(args);
}
__noreturn void Panic(const char *format, ...) {
va_list args;
va_start(args, format);
kvprintf(format, (kvprintf_fn_t *)DPutChar, NULL, args);
va_end(args);
exit(10);
}
__regargs void MemDump(void *ptr, int n) {
char *data = ptr;
while (n > 0) {
short m = min(n, 16);
short i = 0;
DPutChar('$');
DPutLong((int)data);
DPutChar(':');
while (m--) {
if ((i++ & 3) == 0)
DPutChar(' ');
DPutByte(*data++);
n--;
}
DPutChar('\n');
}
}
| 15.869565 | 58 | 0.560274 |
5be39d468a9a7a7a33d11a7559e816f32304775d | 297 | swift | Swift | swiftui_classic-tabview_show-hide/Presentation/Navigation/Models/BottomNavTabItem.swift | alexis-ag/swiftui_navbar_show-hide | 5989a4ee3ea8dea042891b6a5ea2e9832810d2b9 | [
"MIT"
] | 1 | 2021-09-27T17:22:17.000Z | 2021-09-27T17:22:17.000Z | swiftui_classic-tabview_show-hide/Presentation/Navigation/Models/BottomNavTabItem.swift | alexis-ag/swiftui_navbar_show-hide | 5989a4ee3ea8dea042891b6a5ea2e9832810d2b9 | [
"MIT"
] | null | null | null | swiftui_classic-tabview_show-hide/Presentation/Navigation/Models/BottomNavTabItem.swift | alexis-ag/swiftui_navbar_show-hide | 5989a4ee3ea8dea042891b6a5ea2e9832810d2b9 | [
"MIT"
] | 2 | 2021-09-27T17:22:48.000Z | 2022-01-12T09:06:00.000Z | import Foundation
struct BottomNavTabItem: Identifiable {
var id: Int { type.id }
let type: BottomNavTab
let notificationsCount: Int
init(
type: BottomNavTab,
badge: Int = 0
) {
self.type = type
self.notificationsCount = badge
}
} | 19.8 | 39 | 0.589226 |
83e32d86c1679512615451fae8e23f1ad3472564 | 1,351 | go | Go | plugins/govppmux/plugin_api_govppmux.go | mhalaj1/vpp-agent | 6eac586bfd7d893ae74736da966fa0d40919ecc1 | [
"Apache-2.0"
] | 184 | 2017-07-18T07:01:15.000Z | 2022-03-22T15:08:21.000Z | plugins/govppmux/plugin_api_govppmux.go | mhalaj1/vpp-agent | 6eac586bfd7d893ae74736da966fa0d40919ecc1 | [
"Apache-2.0"
] | 724 | 2017-07-21T10:14:21.000Z | 2022-03-13T18:02:20.000Z | plugins/govppmux/plugin_api_govppmux.go | mhalaj1/vpp-agent | 6eac586bfd7d893ae74736da966fa0d40919ecc1 | [
"Apache-2.0"
] | 155 | 2017-07-17T05:42:34.000Z | 2022-03-26T02:30:07.000Z | // Copyright (c) 2019 Cisco and/or its affiliates.
//
// 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
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package govppmux
import (
"go.ligato.io/vpp-agent/v3/plugins/govppmux/vppcalls"
"go.ligato.io/vpp-agent/v3/plugins/vpp"
)
// API for other plugins to get connectivity to VPP.
type API interface {
// VPPInfo returns VPP information which is retrieved immediatelly after connecting to VPP.
VPPInfo() VPPInfo
vpp.Client
}
// VPPInfo defines retrieved information about the connected VPP instance.
type VPPInfo struct {
Connected bool
vppcalls.VersionInfo
vppcalls.SessionInfo
Plugins []vppcalls.PluginInfo
}
// GetReleaseVersion returns VPP release version (XX.YY), which is normalized from GetVersion.
func (vpp VPPInfo) GetReleaseVersion() string {
if len(vpp.Version) < 5 {
return ""
}
return vpp.Version[:5]
}
| 30.022222 | 94 | 0.746854 |
8649175746e6c28d70d9df759236abc2e700ce87 | 13,818 | rs | Rust | src/uu/touch/src/touch.rs | rivy/rust.coreutils | 4fbf39efd44bdd8eb145fe66517c922d13de7891 | [
"MIT"
] | null | null | null | src/uu/touch/src/touch.rs | rivy/rust.coreutils | 4fbf39efd44bdd8eb145fe66517c922d13de7891 | [
"MIT"
] | 6 | 2022-03-15T04:42:34.000Z | 2022-03-31T04:38:52.000Z | src/uu/touch/src/touch.rs | crazystylus/coreutils | 33c49666c35171afcd9158446b4aa762f58ea1dd | [
"MIT"
] | null | null | null | // This file is part of the uutils coreutils package.
//
// (c) Nick Platt <platt.nicholas@gmail.com>
// (c) Jian Zeng <anonymousknight96 AT gmail.com>
//
// For the full copyright and license information, please view the LICENSE file
// that was distributed with this source code.
// spell-checker:ignore (ToDO) filetime strptime utcoff strs datetime MMDDhhmm clapv PWSTR lpszfilepath hresult
pub extern crate filetime;
#[macro_use]
extern crate uucore;
use clap::{crate_version, Arg, ArgGroup, Command};
use filetime::*;
use std::fs::{self, File};
use std::path::{Path, PathBuf};
use uucore::display::Quotable;
use uucore::error::{FromIo, UError, UResult, USimpleError};
use uucore::format_usage;
static ABOUT: &str = "Update the access and modification times of each FILE to the current time.";
const USAGE: &str = "{} [OPTION]... [USER]";
pub mod options {
// Both SOURCES and sources are needed as we need to be able to refer to the ArgGroup.
pub static SOURCES: &str = "sources";
pub mod sources {
pub static DATE: &str = "date";
pub static REFERENCE: &str = "reference";
pub static CURRENT: &str = "current";
}
pub static HELP: &str = "help";
pub static ACCESS: &str = "access";
pub static MODIFICATION: &str = "modification";
pub static NO_CREATE: &str = "no-create";
pub static NO_DEREF: &str = "no-dereference";
pub static TIME: &str = "time";
}
static ARG_FILES: &str = "files";
fn to_local(mut tm: time::Tm) -> time::Tm {
tm.tm_utcoff = time::now().tm_utcoff;
tm
}
fn local_tm_to_filetime(tm: time::Tm) -> FileTime {
let ts = tm.to_timespec();
FileTime::from_unix_time(ts.sec as i64, ts.nsec as u32)
}
#[uucore::main]
pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let matches = uu_app().get_matches_from(args);
let files = matches.values_of_os(ARG_FILES).ok_or_else(|| {
USimpleError::new(
1,
r##"missing file operand
Try 'touch --help' for more information."##,
)
})?;
let (mut atime, mut mtime) =
if let Some(reference) = matches.value_of_os(options::sources::REFERENCE) {
stat(Path::new(reference), !matches.is_present(options::NO_DEREF))?
} else {
let timestamp = if let Some(date) = matches.value_of(options::sources::DATE) {
parse_date(date)?
} else if let Some(current) = matches.value_of(options::sources::CURRENT) {
parse_timestamp(current)?
} else {
local_tm_to_filetime(time::now())
};
(timestamp, timestamp)
};
for filename in files {
// FIXME: find a way to avoid having to clone the path
let pathbuf = if filename == "-" {
pathbuf_from_stdout()?
} else {
PathBuf::from(filename)
};
let path = pathbuf.as_path();
if !path.exists() {
if matches.is_present(options::NO_CREATE) {
continue;
}
if matches.is_present(options::NO_DEREF) {
show!(USimpleError::new(
1,
format!(
"setting times of {}: No such file or directory",
filename.quote()
)
));
continue;
}
if let Err(e) = File::create(path) {
show!(e.map_err_context(|| format!("cannot touch {}", path.quote())));
continue;
};
// Minor optimization: if no reference time was specified, we're done.
if !matches.is_present(options::SOURCES) {
continue;
}
}
// If changing "only" atime or mtime, grab the existing value of the other.
// Note that "-a" and "-m" may be passed together; this is not an xor.
if matches.is_present(options::ACCESS)
|| matches.is_present(options::MODIFICATION)
|| matches.is_present(options::TIME)
{
let st = stat(path, !matches.is_present(options::NO_DEREF))?;
let time = matches.value_of(options::TIME).unwrap_or("");
if !(matches.is_present(options::ACCESS)
|| time.contains(&"access".to_owned())
|| time.contains(&"atime".to_owned())
|| time.contains(&"use".to_owned()))
{
atime = st.0;
}
if !(matches.is_present(options::MODIFICATION)
|| time.contains(&"modify".to_owned())
|| time.contains(&"mtime".to_owned()))
{
mtime = st.1;
}
}
if matches.is_present(options::NO_DEREF) {
set_symlink_file_times(path, atime, mtime)
} else {
filetime::set_file_times(path, atime, mtime)
}
.map_err_context(|| format!("setting times of {}", path.quote()))?;
}
Ok(())
}
pub fn uu_app<'a>() -> Command<'a> {
Command::new(uucore::util_name())
.version(crate_version!())
.about(ABOUT)
.override_usage(format_usage(USAGE))
.infer_long_args(true)
.arg(
Arg::new(options::HELP)
.long(options::HELP)
.help("Print help information."),
)
.arg(
Arg::new(options::ACCESS)
.short('a')
.help("change only the access time"),
)
.arg(
Arg::new(options::sources::CURRENT)
.short('t')
.help("use [[CC]YY]MMDDhhmm[.ss] instead of the current time")
.value_name("STAMP")
.takes_value(true),
)
.arg(
Arg::new(options::sources::DATE)
.short('d')
.long(options::sources::DATE)
.help("parse argument and use it instead of current time")
.value_name("STRING"),
)
.arg(
Arg::new(options::MODIFICATION)
.short('m')
.help("change only the modification time"),
)
.arg(
Arg::new(options::NO_CREATE)
.short('c')
.long(options::NO_CREATE)
.help("do not create any files"),
)
.arg(
Arg::new(options::NO_DEREF)
.short('h')
.long(options::NO_DEREF)
.help(
"affect each symbolic link instead of any referenced file \
(only for systems that can change the timestamps of a symlink)",
),
)
.arg(
Arg::new(options::sources::REFERENCE)
.short('r')
.long(options::sources::REFERENCE)
.help("use this file's times instead of the current time")
.value_name("FILE")
.allow_invalid_utf8(true),
)
.arg(
Arg::new(options::TIME)
.long(options::TIME)
.help(
"change only the specified time: \"access\", \"atime\", or \
\"use\" are equivalent to -a; \"modify\" or \"mtime\" are \
equivalent to -m",
)
.value_name("WORD")
.possible_values(&["access", "atime", "use"])
.takes_value(true),
)
.arg(
Arg::new(ARG_FILES)
.multiple_occurrences(true)
.takes_value(true)
.min_values(1)
.allow_invalid_utf8(true),
)
.group(ArgGroup::new(options::SOURCES).args(&[
options::sources::CURRENT,
options::sources::DATE,
options::sources::REFERENCE,
]))
}
fn stat(path: &Path, follow: bool) -> UResult<(FileTime, FileTime)> {
let metadata = if follow {
fs::symlink_metadata(path)
} else {
fs::metadata(path)
}
.map_err_context(|| format!("failed to get attributes of {}", path.quote()))?;
Ok((
FileTime::from_last_access_time(&metadata),
FileTime::from_last_modification_time(&metadata),
))
}
fn parse_date(str: &str) -> UResult<FileTime> {
// This isn't actually compatible with GNU touch, but there doesn't seem to
// be any simple specification for what format this parameter allows and I'm
// not about to implement GNU parse_datetime.
// http://git.savannah.gnu.org/gitweb/?p=gnulib.git;a=blob_plain;f=lib/parse-datetime.y
let formats = vec!["%c", "%F"];
for f in formats {
if let Ok(tm) = time::strptime(str, f) {
return Ok(local_tm_to_filetime(to_local(tm)));
}
}
if let Ok(tm) = time::strptime(str, "@%s") {
// Don't convert to local time in this case - seconds since epoch are not time-zone dependent
return Ok(local_tm_to_filetime(tm));
}
Err(USimpleError::new(
1,
format!("Unable to parse date: {}", str),
))
}
fn parse_timestamp(s: &str) -> UResult<FileTime> {
let now = time::now();
let (format, ts) = match s.chars().count() {
15 => ("%Y%m%d%H%M.%S", s.to_owned()),
12 => ("%Y%m%d%H%M", s.to_owned()),
13 => ("%y%m%d%H%M.%S", s.to_owned()),
10 => ("%y%m%d%H%M", s.to_owned()),
11 => ("%Y%m%d%H%M.%S", format!("{}{}", now.tm_year + 1900, s)),
8 => ("%Y%m%d%H%M", format!("{}{}", now.tm_year + 1900, s)),
_ => {
return Err(USimpleError::new(
1,
format!("invalid date format {}", s.quote()),
))
}
};
let tm = time::strptime(&ts, format)
.map_err(|_| USimpleError::new(1, format!("invalid date format {}", s.quote())))?;
let mut local = to_local(tm);
local.tm_isdst = -1;
let ft = local_tm_to_filetime(local);
// We have to check that ft is valid time. Due to daylight saving
// time switch, local time can jump from 1:59 AM to 3:00 AM,
// in which case any time between 2:00 AM and 2:59 AM is not valid.
// Convert back to local time and see if we got the same value back.
let ts = time::Timespec {
sec: ft.unix_seconds(),
nsec: 0,
};
let tm2 = time::at(ts);
if tm.tm_hour != tm2.tm_hour {
return Err(USimpleError::new(
1,
format!("invalid date format {}", s.quote()),
));
}
Ok(ft)
}
// TODO: this may be a good candidate to put in fsext.rs
/// Returns a PathBuf to stdout.
///
/// On Windows, uses GetFinalPathNameByHandleW to attempt to get the path
/// from the stdout handle.
fn pathbuf_from_stdout() -> UResult<PathBuf> {
#[cfg(unix)]
{
Ok(PathBuf::from("/dev/stdout"))
}
#[cfg(windows)]
{
use std::os::windows::prelude::AsRawHandle;
use winapi::shared::minwindef::{DWORD, MAX_PATH};
use winapi::shared::winerror::{
ERROR_INVALID_PARAMETER, ERROR_NOT_ENOUGH_MEMORY, ERROR_PATH_NOT_FOUND,
};
use winapi::um::errhandlingapi::GetLastError;
use winapi::um::fileapi::GetFinalPathNameByHandleW;
use winapi::um::winnt::WCHAR;
let handle = std::io::stdout().lock().as_raw_handle();
let mut file_path_buffer: [WCHAR; MAX_PATH as usize] = [0; MAX_PATH as usize];
// Couldn't find this in winapi
const FILE_NAME_OPENED: DWORD = 0x8;
// https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfinalpathnamebyhandlea#examples
// SAFETY: We transmute the handle to be able to cast *mut c_void into a
// HANDLE (i32) so rustc will let us call GetFinalPathNameByHandleW. The
// reference example code for GetFinalPathNameByHandleW implies that
// it is safe for us to leave lpszfilepath uninitialized, so long as
// the buffer size is correct. We know the buffer size (MAX_PATH) at
// compile time. MAX_PATH is a small number (260) so we can cast it
// to a u32.
let ret = unsafe {
GetFinalPathNameByHandleW(
std::mem::transmute(handle),
file_path_buffer.as_mut_ptr(),
file_path_buffer.len() as u32,
FILE_NAME_OPENED,
)
};
let buffer_size = match ret {
ERROR_PATH_NOT_FOUND | ERROR_NOT_ENOUGH_MEMORY | ERROR_INVALID_PARAMETER => {
return Err(USimpleError::new(
1,
format!("GetFinalPathNameByHandleW failed with code {}", ret),
))
}
e if e == 0 => {
return Err(USimpleError::new(
1,
format!(
"GetFinalPathNameByHandleW failed with code {}",
// SAFETY: GetLastError is thread-safe and has no documented memory unsafety.
unsafe { GetLastError() }
),
));
}
e => e as usize,
};
// Don't include the null terminator
Ok(String::from_utf16(&file_path_buffer[0..buffer_size])
.map_err(|e| USimpleError::new(1, e.to_string()))?
.into())
}
}
#[cfg(test)]
mod tests {
#[cfg(windows)]
#[test]
fn test_get_pathbuf_from_stdout_fails_if_stdout_is_not_a_file() {
// We can trigger an error by not setting stdout to anything (will
// fail with code 1)
assert!(super::pathbuf_from_stdout()
.err()
.expect("pathbuf_from_stdout should have failed")
.to_string()
.contains("GetFinalPathNameByHandleW failed with code 1"));
}
}
| 34.373134 | 115 | 0.539369 |
e04d90760a08ca704985a16eb1a43ee96f1dfdc2 | 5,630 | dart | Dart | lib/homescreen/cakepage.dart | ShashiniU/HouseOfCake | 1ae32c0390a42d359b57561ebe9993102cc35ceb | [
"MIT"
] | null | null | null | lib/homescreen/cakepage.dart | ShashiniU/HouseOfCake | 1ae32c0390a42d359b57561ebe9993102cc35ceb | [
"MIT"
] | null | null | null | lib/homescreen/cakepage.dart | ShashiniU/HouseOfCake | 1ae32c0390a42d359b57561ebe9993102cc35ceb | [
"MIT"
] | 5 | 2021-01-13T05:48:58.000Z | 2021-01-16T07:10:04.000Z | import 'package:flutter/material.dart';
import 'cake_detailspage.dart';
class CakePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
backgroundColor: Colors.pink[100],
body: ListView(
children: [
SizedBox(height: 15.0),
Container(
padding: EdgeInsets.only(right: 9.0, left: 7.0),
width: MediaQuery.of(context).size.width - 30.0,
height: MediaQuery.of(context).size.height - 50.0,
child: GridView.count(
crossAxisCount: 2,
primary: false,
crossAxisSpacing: 5.0,
mainAxisSpacing: 10.0,
childAspectRatio: 0.8,
children: [
//six cake cards
_cakeCard(
'Red and white rounded\n anniversary cake',
'Rs.3500/=',
'assets/imghome/anniversary.jpg',
false,
false,
context),
_cakeCard(
' Structuredwith rose\n flowers ribbon cake',
'Rs.4000/=',
'assets/imghome/birthday5.jpg',
false,
false,
context),
_cakeCard('Structured birthday cake\n', 'Rs.3000/=',
'assets/imghome/birthday1.jpg', false, false, context),
_cakeCard(' Mixed food\ntheme cake', 'Rs.3800',
'assets/imghome/fav2.jpg', false, false, context),
_cakeCard('Fruit cake with nut\n', 'Rs.2800',
'assets/imghome/fruit1.jpg', false, false, context),
_cakeCard('Ribbon Birthday Cake\n', 'Rs.2500',
'assets/imghome/birthday.jpg', false, false, context),
],
),
),
SizedBox(height: 200.0)
],
),
);
}
Widget _cakeCard(String name, String price, String imgPath, bool isAdded,
bool isFavorite, context) {
return Padding(
padding: EdgeInsets.only(top: 1.0, bottom: 1.0, left: 2.0, right: 2.0),
child: InkWell(
onTap: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => CakeDetailsPage(
assetPath: imgPath, cakeprice: price, cakename: name)));
},
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15.0),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.2),
spreadRadius: 3.0,
blurRadius: 7.0)
],
color: Colors.white),
child: Column(
children: [
Padding(
padding: EdgeInsets.all(1.0),
child:
Row(mainAxisAlignment: MainAxisAlignment.end, children: [
isFavorite
? Icon(Icons.favorite, color: Color(0xffd81b60))
: Icon(Icons.favorite_border, color: Color(0xffd81b60))
])),
Hero(
tag: imgPath,
child: Container(
height: 45.0,
width: 80.0,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(imgPath), fit: BoxFit.contain)),
),
),
SizedBox(height: 7.0),
Text(price,
style: TextStyle(
color: Color(0xffd81b60),
//fontFamily: 'Varela',
fontSize: 12.0)),
Text(name,
textAlign: TextAlign.center,
maxLines: 4,
style: TextStyle(
color: Color(0xffd81b60),
//fontFamily: 'Varela',
fontSize: 15.0)),
Padding(
padding: EdgeInsets.all(8.0),
child: Container(color: Color(0xFFEBEBEB), height: 1.0)),
Padding(
padding: EdgeInsets.only(left: 5.0, right: 5.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
if (!isAdded) ...[
Icon(Icons.shopping_basket,
color: Color(0xffd81b60), size: 14.0),
Text('Add to cart',
style: TextStyle(
fontFamily: 'Varela',
color: Color(0xffd81b60),
fontSize: 14.0)),
],
// if (isAdded) ...[
// Icon(Icons.remove_circle_outline,
// color: Color(0xFFD17E50), size: 12.0),
// Text('3',
// style: TextStyle(
// fontFamily: 'Varela',
// color: Color(0xFFD17E50),
// fontWeight: FontWeight.bold,
// fontSize: 12.0)),
// Icon(Icons.add_circle_outline,
// color: Color(0xFFD17E50), size: 12.0),
// ]
],
),
),
],
),
),
),
);
}
}
| 37.533333 | 79 | 0.431083 |
f2c48d6759e4ec7ca620cd34680f0f1b9a5419b0 | 499 | swift | Swift | Wiki App/Parser/CGThumbnail.swift | d4rkl0rd3r3b05/MediaWiki-API-sample | 62dae67a88f84d1a8f4eb06757f91b9f142a691f | [
"MIT"
] | null | null | null | Wiki App/Parser/CGThumbnail.swift | d4rkl0rd3r3b05/MediaWiki-API-sample | 62dae67a88f84d1a8f4eb06757f91b9f142a691f | [
"MIT"
] | null | null | null | Wiki App/Parser/CGThumbnail.swift | d4rkl0rd3r3b05/MediaWiki-API-sample | 62dae67a88f84d1a8f4eb06757f91b9f142a691f | [
"MIT"
] | null | null | null | //
// CGThumbnail.swift
//
// Create by Mayank Gupta on 2/11/2017
// Copyright © 2017. All rights reserved.
//
import Foundation
public struct CGThumbnail{
var height : Int!
var source : String!
var width : Int!
/**
* Instantiate the instance using the passed dictionary values to set the properties values
*/
init(fromDictionary dictionary: NSDictionary){
height = dictionary["height"] as? Int
source = dictionary["source"] as? String
width = dictionary["width"] as? Int
}
}
| 18.481481 | 92 | 0.699399 |
864951c982b940122ebfdb9bf1d379458054d6a5 | 352 | go | Go | internal/views/command_test.go | themenucha/k9s | abab960612b7c48729933054d018c9c7e9c5daf4 | [
"Apache-2.0"
] | 1 | 2020-05-12T06:41:18.000Z | 2020-05-12T06:41:18.000Z | internal/views/command_test.go | themenucha/k9s | abab960612b7c48729933054d018c9c7e9c5daf4 | [
"Apache-2.0"
] | null | null | null | internal/views/command_test.go | themenucha/k9s | abab960612b7c48729933054d018c9c7e9c5daf4 | [
"Apache-2.0"
] | null | null | null | package views
import (
"testing"
"github.com/derailed/k9s/internal/config"
"github.com/stretchr/testify/assert"
)
func TestCommandPush(t *testing.T) {
c := newCommand(NewApp(config.NewConfig(ks{})))
c.pushCmd("fred")
c.pushCmd("blee")
p, top := c.previousCmd()
assert.Equal(t, "fred", p)
assert.True(t, top)
assert.True(t, c.lastCmd())
}
| 17.6 | 48 | 0.684659 |
43bbe384f4a4b844ce3ad3aa067805652f13357e | 388 | sql | SQL | sqls/sqlite3/2020080107_create_quota_limit.up.sql | kujilabo/cocotola-api | 1ac06348e5332b686c42fb981835b36f30df936a | [
"MIT"
] | null | null | null | sqls/sqlite3/2020080107_create_quota_limit.up.sql | kujilabo/cocotola-api | 1ac06348e5332b686c42fb981835b36f30df936a | [
"MIT"
] | 36 | 2021-07-24T00:22:36.000Z | 2022-02-13T02:10:45.000Z | sqls/sqlite3/2020080107_create_quota_limit.up.sql | kujilabo/cocotola-api | 1ac06348e5332b686c42fb981835b36f30df936a | [
"MIT"
] | null | null | null | create table `quota_limit` (
`organization_id` int not null
,`app_user_id` int not null
,`name` varchar(40) not null
,`unit` varchar(8) not null
,`date` datetime not null
,`count` int not null
,primary key(`organization_id`, `app_user_id`, `name`, `unit`, `date`)
,foreign key(`organization_id`) references `organization`(`id`)
,foreign key(`app_user_id`) references `app_user`(`id`)
);
| 32.333333 | 70 | 0.719072 |
48467ee6ba0f4bf2b0c601f87838e5fbeb91abc1 | 1,387 | dart | Dart | lib/features/number_trivia/data/datasources/number_trivia_remote_data_source.dart | karlreginaldo/curious_digit | 048021f32f78ea4ff8b3cade7d4bc5024a3322fe | [
"MIT"
] | 1 | 2021-04-28T13:50:56.000Z | 2021-04-28T13:50:56.000Z | lib/features/number_trivia/data/datasources/number_trivia_remote_data_source.dart | karlreginaldo/curious_digit | 048021f32f78ea4ff8b3cade7d4bc5024a3322fe | [
"MIT"
] | 3 | 2021-04-23T21:00:13.000Z | 2021-04-23T21:15:32.000Z | lib/features/number_trivia/data/datasources/number_trivia_remote_data_source.dart | mikagura12/curious_digit | 048021f32f78ea4ff8b3cade7d4bc5024a3322fe | [
"MIT"
] | null | null | null | import '../../../../core/error/exception.dart';
import '../models/number_trivia_model.dart';
import 'package:http/http.dart' as http;
abstract class NumberTriviaRemoteDataSource {
///USE THIS API: http://numbersapi.com/1
///
///THROW [SERVEREXCEPTION] IF THE SERVER CRASH
Future<NumberTriviaModel> getConcreteNumberTrivia(int number);
///USE THIS API: http://numbersapi.com/random
///
///THROW [SERVEREXCEPTION] IF THE SERVER CRASH
Future<NumberTriviaModel> getRandomNumberTrivia();
//THIS METHOD IS MY OPTIONS FOR CLEAN ARCHITECTURE PURPOSE
Future<NumberTriviaModel> getTriviaModel(String url);
}
class NumberTriviaRemoteDataSourceImpl implements NumberTriviaRemoteDataSource {
final http.Client _client;
NumberTriviaRemoteDataSourceImpl(this._client);
@override
Future<NumberTriviaModel> getConcreteNumberTrivia(int number) async =>
getTriviaModel('http://numbersapi.com/$number');
@override
Future<NumberTriviaModel> getRandomNumberTrivia() async =>
getTriviaModel('http://numbersapi.com/random');
@override
Future<NumberTriviaModel> getTriviaModel(String url) async {
final response = await _client.get(
url,
headers: {
'Content-Type': 'application/json',
},
);
return response.statusCode == 200
? NumberTriviaModel.fromJson(response.body)
: throw ServerException();
}
}
| 30.152174 | 80 | 0.726027 |
1fc8783e919e362c0d29e16760eb86f1b00e2ae1 | 20,467 | html | HTML | docs/docs/src_js_views_portals_PortalUsagesView.js.html | wykhuh/metacatui | a328f00edf75636839c752fbbbcf1f770689ae11 | [
"Apache-2.0"
] | null | null | null | docs/docs/src_js_views_portals_PortalUsagesView.js.html | wykhuh/metacatui | a328f00edf75636839c752fbbbcf1f770689ae11 | [
"Apache-2.0"
] | null | null | null | docs/docs/src_js_views_portals_PortalUsagesView.js.html | wykhuh/metacatui | a328f00edf75636839c752fbbbcf1f770689ae11 | [
"Apache-2.0"
] | null | null | null | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>MetacatUI Dev Docs: Source: src/js/views/portals/PortalUsagesView.js</title>
<script src="scripts/prettify/prettify.js"> </script>
<script src="scripts/prettify/lang-css.js"> </script>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
<link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">
<link type="text/css" rel="stylesheet" href="styles/style.css">
</head>
<body>
<div id="main">
<h1 class="page-title">Source: src/js/views/portals/PortalUsagesView.js</h1>
<section>
<article>
<pre class="prettyprint source linenums"><code>define(["jquery",
"underscore",
"backbone",
"collections/SolrResults",
"collections/Filters",
"collections/bookkeeper/Usages",
"views/portals/PortalListView",
"text!templates/portals/portalList.html"],
function($, _, Backbone, SearchResults, Filters, Usages, PortalListView, Template){
/**
* @class PortalUsagesView
* @classdesc A view that shows a list of Portal Usages
* @classcategory Views/Portals
* @extends PortalListView
* @since 2.14.0
* @constructor
*/
return PortalListView.extend(
/** @lends PortalUsagesView.prototype */{
/**
* A reference to the Usages collection that is rendered in this view
* @type {Usages}
*/
usagesCollection: null,
/**
* Renders this view
*/
render: function(){
try{
//If the "my portals" feature is disabled, exit now
if(MetacatUI.appModel.get("showMyPortals") === false){
return;
}
//Insert the template
this.$el.html(this.template());
if( !this.usagesCollection ){
this.usagesCollection = new Usages();
}
//When in DataONE Plus Preview mode, search for portals in Solr first,
// then create Usage models for each portal in Solr.
if( MetacatUI.appModel.get("dataonePlusPreviewMode") ){
this.listenTo(this.searchResults, "sync", function(){
//Create a Usage for each portal found in Solr
this.searchResults.each(function(searchResult){
this.usagesCollection.add({
instanceId: searchResult.get("seriesId"),
status: "active",
quantity: 1,
nodeId: searchResult.get("datasource")
});
}, this);
//Merge the Usages and Search Results
this.mergeSearchResults();
//Update the view with info about the corresponding Usage model
this.showUsageInfo();
});
if( MetacatUI.appModel.get("dataonePlusPreviewPortals").length ){
this.altReposChecked = 0;
this.altReposToCheck = [];
this.additionalPortalsToDisplay = [];
_.each( MetacatUI.appModel.get("alternateRepositories"), function(altRepo){
var portalsInThisRepo = _.where(MetacatUI.appModel.get("dataonePlusPreviewPortals"),
{ datasource: altRepo.identifier });
if( portalsInThisRepo.length ){
var searchResults = new SearchResults();
this.listenToOnce(searchResults, "reset", function(){
if( searchResults.length ){
this.additionalPortalsToDisplay = this.additionalPortalsToDisplay.concat( searchResults.models );
}
if(typeof this.altReposChecked == "number" ){
this.altReposChecked++;
if( this.altReposChecked == this.altReposToCheck ){
//Call the PortalListView render function
PortalListView.prototype.render.call(this);
}
}
//Create a Usage for each portal found in Solr
searchResults.each(function(searchResult){
this.usagesCollection.add({
instanceId: searchResult.get("seriesId"),
status: "active",
quantity: 1,
nodeId: searchResult.get("datasource")
});
}, this);
//Merge the Usages and Search Results
this.mergeSearchResults(searchResults);
//Update the view with info about the corresponding Usage model
this.showUsageInfo();
});
//Create a Filters() collection
var portalFilters = new Filters();
portalFilters.mustMatchIds = true;
portalFilters.addWritePermissionFilter();
portalFilters.add({
fields: ["obsoletedBy"],
values: ["*"],
matchSubstring: false,
exclude: true
});
portalFilters.add({
fields: ["datasource"],
values: [altRepo.identifier],
matchSubstring: false,
exclude: false
});
var portalIds = _.pluck(portalsInThisRepo, "seriesId");
portalFilters.add({
fields: ["seriesId"],
values: portalIds,
operator: "OR",
matchSubstring: false
});
searchResults.rows = portalIds.length;
searchResults.fields = this.searchFields;
searchResults.queryServiceUrl = altRepo.queryServiceUrl;
searchResults.setQuery( portalFilters.getQuery() );
this.altReposToCheck++;
//Get the first page of results
searchResults.toPage(0);
}
}, this);
return;
}
//Call the PortalListView render function
PortalListView.prototype.render.call(this);
//Don't do anything else in this render function
return;
}
//When the collection has been fetched, redner the Usage list
this.listenToOnce(this.usagesCollection, "sync", this.getSearchResultsForUsages);
//Listen to the collection for errors
this.listenToOnce(this.usagesCollection, "error", this.showError);
//When the SearchResults are retrieved, merge them with the Usages collection
this.listenToOnce(this.searchResults, "sync", function(){
this.mergeSearchResults();
//Update the view with info about the corresponding Usage model
this.showUsageInfo();
});
//Fetch the collection
this.usagesCollection.fetch({
quotaType: "portal",
subject: MetacatUI.appUserModel.get("username")
});
}
catch(e){
console.error("Failed to render the PortalUsagesView: ", e);
}
},
/**
* Using the Usages collection, this function creates Filters that search for
* the portal objects for those Usages
* @param {Usages} usages The Usages collection to get search results for
*/
getSearchResultsForUsages: function(usages){
try{
//Set the number of portals to the number of usages found
this.numPortals = this.usagesCollection.length;
var portalIds = this.usagesCollection.pluck("instanceId");
//If there are no given filters, create a Filter for the seriesId of each portal Usage
if( !this.filters && portalIds.length ){
this.filters = new Filters();
this.filters.mustMatchIds = true;
this.filters.add({
fields: ["seriesId"],
values: portalIds,
operator: "OR",
matchSubstring: false,
exclude: false
});
//Only get Portals that the user is an owner of
this.filters.addWritePermissionFilter();
}
//If the filters set on this view is an array of JSON, add it to a Filters collection
else if( this.filters.length && !Filters.prototype.isPrototypeOf(this.filters) ){
//Create search filters for finding the portals
var filters = new Filters();
filters.add( this.filters );
this.filters = filters;
}
else{
this.filters = new Filters();
}
this.getSearchResults();
}
catch(e){
this.showError();
console.error("Failed to create search results for the portal list: ", e);
}
},
/**
* Merges the SearchResults collection with the Usages collection
*/
mergeSearchResults: function(searchResults){
if(typeof searchResults == "undefined"){
var searchResults = this.searchResults;
}
this.usagesCollection.mergeCollections(searchResults);
//If in DataONE Plus Preview mode, total the portal count from Solr and use that as the portal totalUsage
if( MetacatUI.appModel.get("dataonePlusPreviewMode") ){
var portalQuotas = MetacatUI.appUserModel.getQuotas("portal");
if( portalQuotas.length ){
portalQuotas[0].set("totalUsage", this.usagesCollection.length);
}
}
},
/**
* Shows the Usage info for each Portal in this view
*/
showUsageInfo: function(){
this.usagesCollection.each(function(usage){
//Find the list item HTML element for this Usage
var listItem = this.$("[data-seriesId='" + usage.get("instanceId") + "']");
//If a list item is found, update it
if( listItem.length ){
//Disable the Edit button if the Usage status is "inactive"
if( usage.get("status") == "inactive" ){
listItem.find(".edit.btn")
.attr("disabled", "disabled")
.popover({
trigger: "hover focus click",
placement: "top",
delay: {
show: 800
},
html: true,
content: "To edit this " + MetacatUI.appModel.get("portalTermSingular") + ", contact us at " +
"<a href='mailto:" + MetacatUI.appModel.get("emailContact") + "'>" +
MetacatUI.appModel.get("emailContact") + "</a>" +
" to activate it. It may be deactivated because your " +
MetacatUI.appModel.get("dataonePlusName") + " membership has ended."
});
}
}
}, this);
//Add a "Create" button to create a new portal, since we know the total Usage and
// remaining Quota now.
this.renderCreateButton();
}
});
});
</code></pre>
</article>
</section>
</div>
<nav>
<h2><a href="index.html">Home</a></h2><h3>Namespaces</h3><ul><li><a href="AppConfig.html">AppConfig</a></li><li><a href="MetacatUI.html">MetacatUI</a></li><li><a href="Utilities.html">Utilities</a></li></ul><h3>Classes</h3><ul><li class='category-heading' data-category='Collections'>Collections</li><li><a href="AccessPolicy.html">AccessPolicy</a></li><li><a href="Citations.html">Citations</a></li><li><a href="DataPackage.html">DataPackage</a></li><li><a href="Filters.html">Filters</a></li><li><a href="ObjectFormats.html">ObjectFormats</a></li><li><a href="QualityReport.html">QualityReport</a></li><li><a href="SolrResults.html">SolrResults</a></li><li><a href="Units.html">Units</a></li><li><a href="UserGroup.html">UserGroup</a></li><li class='category-heading' data-category='Collections/Bookkeeper'>Collections/Bookkeeper</li><li><a href="Quotas.html">Quotas</a></li><li><a href="Usages.html">Usages</a></li><li class='category-heading' data-category='Collections/QueryFields'>Collections/QueryFields</li><li><a href="QueryFields.html">QueryFields</a></li><li class='category-heading' data-category='Models'>Models</li><li><a href="AccessRule.html">AccessRule</a></li><li><a href="AppModel.html">AppModel</a></li><li><a href="Citation.html">Citation</a></li><li><a href="CollectionModel.html">CollectionModel</a></li><li><a href="DataONEObject.html">DataONEObject</a></li><li><a href="LookupModel.html">LookupModel</a></li><li><a href="Map.html">Map</a></li><li><a href="QualityCheck.html">QualityCheck</a></li><li><a href="Search.html">Search</a></li><li><a href="SolrResult.html">SolrResult</a></li><li><a href="Stats.html">Stats</a></li><li class='category-heading' data-category='Models/Bookkeeper'>Models/Bookkeeper</li><li><a href="Quota.html">Quota</a></li><li><a href="Subscription.html">Subscription</a></li><li><a href="Usage.html">Usage</a></li><li class='category-heading' data-category='Models/Filters'>Models/Filters</li><li><a href="BooleanFilter.html">BooleanFilter</a></li><li><a href="ChoiceFilter.html">ChoiceFilter</a></li><li><a href="DateFilter.html">DateFilter</a></li><li><a href="Filter.html">Filter</a></li><li><a href="FilterGroup.html">FilterGroup</a></li><li><a href="NumericFilter.html">NumericFilter</a></li><li><a href="SpatialFilter.html">SpatialFilter</a></li><li><a href="ToggleFilter.html">ToggleFilter</a></li><li class='category-heading' data-category='Models/Formats'>Models/Formats</li><li><a href="ObjectFormat.html">ObjectFormat</a></li><li class='category-heading' data-category='Models/Metadata'>Models/Metadata</li><li><a href="ScienceMetadata.html">ScienceMetadata</a></li><li class='category-heading' data-category='Models/Metadata/EML211'>Models/Metadata/EML211</li><li><a href="EML211.html">EML211</a></li><li><a href="EMLAttribute.html">EMLAttribute</a></li><li><a href="EMLDataTable.html">EMLDataTable</a></li><li><a href="EMLEntity.html">EMLEntity</a></li><li><a href="EMLGeoCoverage.html">EMLGeoCoverage</a></li><li><a href="EMLMeasurementScale.html">EMLMeasurementScale</a></li><li><a href="EMLNonNumericDomain.html">EMLNonNumericDomain</a></li><li><a href="EMLNumericDomain.html">EMLNumericDomain</a></li><li><a href="EMLOtherEntity.html">EMLOtherEntity</a></li><li><a href="EMLTemporalCoverage.html">EMLTemporalCoverage</a></li><li><a href="EMLUnit.html">EMLUnit</a></li><li class='category-heading' data-category='Models/Metadata/EML220'>Models/Metadata/EML220</li><li><a href="EMLText.html">EMLText</a></li><li class='category-heading' data-category='Models/Portals'>Models/Portals</li><li><a href="PortalImage.html">PortalImage</a></li><li><a href="PortalModel.html">PortalModel</a></li><li><a href="PortalSectionModel.html">PortalSectionModel</a></li><li class='category-heading' data-category='Models/QueryFields'>Models/QueryFields</li><li><a href="QueryField.html">QueryField</a></li><li class='category-heading' data-category='Router'>Router</li><li><a href="UIRouter.html">UIRouter</a></li><li class='category-heading' data-category='Views'>Views</li><li><a href="AccessPolicyView.html">AccessPolicyView</a></li><li><a href="AccessRuleView.html">AccessRuleView</a></li><li><a href="AppView.html">AppView</a></li><li><a href="ColorPaletteView.html">ColorPaletteView</a></li><li><a href="DataCatalogViewWithFilters.html">DataCatalogViewWithFilters</a></li><li><a href="DataItemView.html">DataItemView</a></li><li><a href="DataPackageView.html">DataPackageView</a></li><li><a href="DraftsView.html">DraftsView</a></li><li><a href="EditCollectionView.html">EditCollectionView</a></li><li><a href="EditorView.html">EditorView</a></li><li><a href="GroupListView.html">GroupListView</a></li><li><a href="ImageUploaderView.html">ImageUploaderView</a></li><li><a href="MarkdownEditorView.html">MarkdownEditorView</a></li><li><a href="MarkdownView.html">MarkdownView</a></li><li><a href="MetadataView.html">MetadataView</a></li><li><a href="MetricModalView.html">MetricModalView</a></li><li><a href="MetricsChartView.html">MetricsChartView</a></li><li><a href="NavbarView.html">NavbarView</a></li><li><a href="RegisterCitationView.html">RegisterCitationView</a></li><li><a href="TableEditorView.html">TableEditorView</a></li><li><a href="TOCView.html">TOCView</a></li><li><a href="UserView.html">UserView</a></li><li class='category-heading' data-category='Views/Filters'>Views/Filters</li><li><a href="BooleanFilterView.html">BooleanFilterView</a></li><li><a href="ChoiceFilterView.html">ChoiceFilterView</a></li><li><a href="DateFilterView.html">DateFilterView</a></li><li><a href="FilterGroupsView.html">FilterGroupsView</a></li><li><a href="FilterGroupView.html">FilterGroupView</a></li><li><a href="FilterView.html">FilterView</a></li><li><a href="NumericFilterView.html">NumericFilterView</a></li><li><a href="ToggleFilterView.html">ToggleFilterView</a></li><li class='category-heading' data-category='Views/Metadata'>Views/Metadata</li><li><a href="EML211EditorView.html">EML211EditorView</a></li><li><a href="EMLAttributeView.html">EMLAttributeView</a></li><li><a href="EMLEntityView.html">EMLEntityView</a></li><li><a href="EMlGeoCoverageView.html">EMlGeoCoverageView</a></li><li><a href="EMLMeasurementScaleView.html">EMLMeasurementScaleView</a></li><li><a href="EMLMethodsView.html">EMLMethodsView</a></li><li><a href="EMLOtherEntityView.html">EMLOtherEntityView</a></li><li><a href="EMLPartyView.html">EMLPartyView</a></li><li><a href="EMLTempCoverageView.html">EMLTempCoverageView</a></li><li><a href="EMLView.html">EMLView</a></li><li><a href="ScienceMetadataView.html">ScienceMetadataView</a></li><li class='category-heading' data-category='Views/Portals'>Views/Portals</li><li><a href="PortalDataView.html">PortalDataView</a></li><li><a href="PortalHeaderView.html">PortalHeaderView</a></li><li><a href="PortalListView.html">PortalListView</a></li><li><a href="PortalLogosView.html">PortalLogosView</a></li><li><a href="PortalMembersView.html">PortalMembersView</a></li><li><a href="PortalSectionView.html">PortalSectionView</a></li><li><a href="PortalUsagesView.html">PortalUsagesView</a></li><li><a href="PortalView.html">PortalView</a></li><li><a href="PortalVisualizationsView.html">PortalVisualizationsView</a></li><li class='category-heading' data-category='Views/Portals/Editor'>Views/Portals/Editor</li><li><a href="PortalEditorView.html">PortalEditorView</a></li><li><a href="PortEditorDataView.html">PortEditorDataView</a></li><li><a href="PortEditorImageView.html">PortEditorImageView</a></li><li><a href="PortEditorLogosView.html">PortEditorLogosView</a></li><li><a href="PortEditorMdSectionView.html">PortEditorMdSectionView</a></li><li><a href="PortEditorSectionsView.html">PortEditorSectionsView</a></li><li><a href="PortEditorSectionView.html">PortEditorSectionView</a></li><li><a href="PortEditorSettingsView.html">PortEditorSettingsView</a></li><li class='category-heading' data-category='Views/QueryBuilder'>Views/QueryBuilder</li><li><a href="QueryBuilder.html">QueryBuilder</a></li><li><a href="QueryRuleView.html">QueryRuleView</a></li><li class='category-heading' data-category='Views/SearchSelect'>Views/SearchSelect</li><li><a href="AnnotationFilter.html">AnnotationFilter</a></li><li><a href="NodeSelect.html">NodeSelect</a></li><li><a href="QueryFieldSelectView.html">QueryFieldSelectView</a></li><li><a href="SearchableSelectView.html">SearchableSelectView</a></li><li class='category-heading' data-category='Deprecated'>Deprecated</li><li><a href="ExternalView.html">ExternalView</a></li><li><a href="LogsSearch.html">LogsSearch</a></li></ul><h3>Global</h3><ul><li><a href="global.html#appConfigPath">appConfigPath</a></li></ul>
</nav>
<br class="clear">
<footer>
Documentation generated by <a href="https://github.com/jsdoc/jsdoc">JSDoc 3.6.3</a> on Mon Dec 07 2020 17:33:36 GMT-0600 (Central Standard Time)
</footer>
<script> prettyPrint(); </script>
<script src="scripts/linenumber.js"> </script>
</body>
</html>
| 55.920765 | 8,642 | 0.624078 |
bb125f9d7ea66d9bbde72f9951b6c80305a244d2 | 849 | html | HTML | app/directives/lmPost/lmPost.html | peferron/lilymandarin-web | 6c191133d770382c345cdb7a3219bb2f065cedbf | [
"MIT"
] | null | null | null | app/directives/lmPost/lmPost.html | peferron/lilymandarin-web | 6c191133d770382c345cdb7a3219bb2f065cedbf | [
"MIT"
] | null | null | null | app/directives/lmPost/lmPost.html | peferron/lilymandarin-web | 6c191133d770382c345cdb7a3219bb2f065cedbf | [
"MIT"
] | null | null | null | <div class="lm-post__header">
<!-- <h3 class="lm-post__header__date">{{post.firstValidationTime | FancyDate}}</h3> -->
<lm-admin class="lm-post__header__admin">
<lm-status article="post"></lm-status>
</lm-admin>
</div>
<div class="lm-post__content">
<a ng-href="{{clickable ? ('/post/' + post.id + '/' + post.slug) : ''}}" target="_blank" class="lm-post__poster">
<img class="lm-post__poster__img" ng-src="{{post | ImgSrc: 500}}">
</a>
<div class="lm-post__text">
<h1 class="zh-cn">{{post.lines[0]['zh-CN']}}</h1>
<h4 class="pinyin">{{post.lines[0]['pinyin']}}</h4>
<h4 class="en-us">{{post.lines[0]['en-US']}}</h4>
<h4 class="fr-fr">{{post.lines[0]['fr-FR']}}</h4>
<lm-social class="lm-social--compact" url="socialUrl" text="socialText"></lm-social>
</div>
</div>
| 44.684211 | 117 | 0.573616 |
a1a2f6169c420ac890ba8a92891cd2ed888f4bb3 | 2,324 | h | C | protocol/zigbee/app/framework/plugin/reporting/reporting-tokens.h | lmnotran/gecko_sdk | 2e82050dc8823c9fe0e8908c1b2666fb83056230 | [
"Zlib"
] | 82 | 2016-06-29T17:24:43.000Z | 2021-04-16T06:49:17.000Z | protocol/zigbee/app/framework/plugin/reporting/reporting-tokens.h | lmnotran/gecko_sdk | 2e82050dc8823c9fe0e8908c1b2666fb83056230 | [
"Zlib"
] | 6 | 2022-01-12T18:22:08.000Z | 2022-03-25T10:19:27.000Z | protocol/zigbee/app/framework/plugin/reporting/reporting-tokens.h | lmnotran/gecko_sdk | 2e82050dc8823c9fe0e8908c1b2666fb83056230 | [
"Zlib"
] | 56 | 2016-08-02T10:50:50.000Z | 2021-07-19T08:57:34.000Z | /***************************************************************************//**
* @file
* @brief Tokens for the Reporting plugin.
*******************************************************************************
* # License
* <b>Copyright 2018 Silicon Laboratories Inc. www.silabs.com</b>
*******************************************************************************
*
* The licensor of this software is Silicon Laboratories Inc. Your use of this
* software is governed by the terms of Silicon Labs Master Software License
* Agreement (MSLA) available at
* www.silabs.com/about-us/legal/master-software-license-agreement. This
* software is distributed to you in Source Code format and is governed by the
* sections of the MSLA applicable to Source Code.
*
******************************************************************************/
#ifdef UC_BUILD
#include "reporting-config.h"
#endif
#ifdef UC_BUILD
#if (EMBER_AF_PLUGIN_REPORTING_ENABLE_EXPANDED_TABLE == 1)
#define EXPANDED_TABLE
#endif
#else // !UC_BUILD
#ifdef EMBER_AF_PLUGIN_REPORTING_ENABLE_EXPANDED_TABLE
#define EXPANDED_TABLE
#endif
#endif // UC_BUILD
#ifdef EXPANDED_TABLE
#else
#define CREATOR_REPORT_TABLE (0x8725)
// This key is used for an indexed token and the subsequent 0x7F keys are also reserved
#define NVM3KEY_REPORT_TABLE (NVM3KEY_DOMAIN_ZIGBEE | 0x4000)
#ifdef DEFINETYPES
// Include or define any typedef for tokens here
#endif //DEFINETYPES
#ifdef DEFINETOKENS
// Define the actual token storage information here
// Following is for backward compatibility.
// The default reporting will generate a table that is mandatory
// but user may still allocate some table for adding more reporting over
// the air or by cli as part of reporting plugin.
#if defined EMBER_AF_GENERATED_REPORTING_CONFIG_DEFAULTS_TABLE_SIZE
#define REPORT_TABLE_SIZE (EMBER_AF_GENERATED_REPORTING_CONFIG_DEFAULTS_TABLE_SIZE + EMBER_AF_PLUGIN_REPORTING_TABLE_SIZE)
#else
#define REPORT_TABLE_SIZE (EMBER_AF_PLUGIN_REPORTING_TABLE_SIZE)
#endif
DEFINE_INDEXED_TOKEN(REPORT_TABLE,
EmberAfPluginReportingEntry,
REPORT_TABLE_SIZE,
{ EMBER_ZCL_REPORTING_DIRECTION_REPORTED,
EMBER_AF_PLUGIN_REPORTING_UNUSED_ENDPOINT_ID })
#endif //DEFINETOKENS
#endif //EXPANDED_TABLE
| 38.098361 | 122 | 0.669966 |
f732cd2e6067cb2dff3a7afdcaf0f777773a02a8 | 6,592 | c | C | src/backend/utils/adt/pivot.c | haolinw/gpdb | 16a9465747a54f0c61bac8b676fe7611b4f030d8 | [
"PostgreSQL",
"Apache-2.0"
] | null | null | null | src/backend/utils/adt/pivot.c | haolinw/gpdb | 16a9465747a54f0c61bac8b676fe7611b4f030d8 | [
"PostgreSQL",
"Apache-2.0"
] | null | null | null | src/backend/utils/adt/pivot.c | haolinw/gpdb | 16a9465747a54f0c61bac8b676fe7611b4f030d8 | [
"PostgreSQL",
"Apache-2.0"
] | null | null | null | #include "postgres.h"
#include "funcapi.h"
#include "catalog/pg_type.h"
#include "utils/array.h"
#include "utils/builtins.h"
#include "utils/lsyscache.h"
/* array primitives for looping that should have already existed */
typedef struct _array_iter {
ArrayType *array;
char *ptr;
int32 index;
int32 max;
int16 typlen;
bool typbyval;
char typalign;
} array_iter;
void array_loop(ArrayType *array, int32 start, array_iter *iter);
bool array_next(array_iter *iter, Datum *value, bool *isna);
/* Internal static helper functions */
static Datum oid_pivot_accum(FunctionCallInfo fcinfo, Oid type);
/*
* External facing wrapper functions to allow for proper type extraction
*/
Datum
int4_pivot_accum(PG_FUNCTION_ARGS)
{
return oid_pivot_accum(fcinfo, INT4OID);
}
Datum
int8_pivot_accum(PG_FUNCTION_ARGS)
{
return oid_pivot_accum(fcinfo, INT8OID);
}
Datum
float8_pivot_accum(PG_FUNCTION_ARGS)
{
return oid_pivot_accum(fcinfo, FLOAT8OID);
}
void array_loop(ArrayType *array, int32 start, array_iter *iter)
{
iter->array = array;
iter->ptr = ARR_DATA_PTR(array);
iter->max = ARR_DIMS(array)[0];
get_typlenbyvalalign(ARR_ELEMTYPE(array),
&iter->typlen,
&iter->typbyval,
&iter->typalign);
/* If we are starting in the middle of the array, then scan forward */
start = start - ARR_LBOUND(array)[0];
if (start <= 0)
iter->index = start;
else
{
/*
* could probably be more efficient for fixed length arrays, but
* they would still require adjustments for nulls.
*/
iter->index = 0;
while (start--)
{
Datum d;
bool isna;
array_next(iter, &d, &isna);
}
}
}
bool array_next(array_iter *iter, Datum *value, bool *isna)
{
bits8 *nulls;
if (iter->index >= iter->max)
{
*value = (Datum) 0;
*isna = true;
return false;
}
if (iter->index < 0)
{
*value = (Datum) 0;
*isna = true;
iter->index++;
return true;
}
nulls = ARR_NULLBITMAP(iter->array);
if (nulls && !(nulls[iter->index / 8] & (1 << (iter->index % 8))))
{
*value = (Datum) 0;
*isna = true;
iter->index++;
return true;
}
*isna = false;
if (iter->typlen > 0)
{ /* fixed length */
if (iter->typlen <= 8)
{
switch (iter->typlen)
{
case 1:
*value = Int8GetDatum(*((int8*) iter->ptr));
break;
case 2:
*value = Int16GetDatum(*((int16*) iter->ptr));
break;
case 4:
*value = Int32GetDatum(*((int16*) iter->ptr));
break;
case 8:
*value = Int64GetDatum(*((int16*) iter->ptr));
break;
default:
elog(ERROR, "unexpected data type");
break;
}
}
else
{
*value = PointerGetDatum(iter->ptr);
}
iter->ptr += iter->typlen;
}
else
{ /* variable length */
*value = PointerGetDatum(iter->ptr);
iter->ptr += VARSIZE(iter->ptr);
}
iter->ptr = (char*) att_align_nominal(iter->ptr, iter->typalign);
iter->index++;
return true;
}
/*
* pivot_find() - Searchs an array of labels for a matching value.
*
* Returns: index of found value, or -1 if not found
*
* It may eventually do something smarter than a linear scan, but
* for now this is sufficient given that we don't know anything about the
* order of 'labels'.
*
*/
static int pivot_find(ArrayType *labels, text *attr)
{
char *labelsp;
int i, nelem, asize;
int16 typlen;
bool typbyval;
char typalign;
if (ARR_ELEMTYPE(labels) != TEXTOID)
ereport(ERROR,
(errcode(ERRCODE_DATATYPE_MISMATCH),
errmsg("pivot_accum: labels are not type text")));
/* Text alignment properties */
get_typlenbyvalalign(TEXTOID, &typlen, &typbyval, &typalign);
/* Get the size of the input attribute, we'll use this for fast compares */
asize = VARSIZE(attr);
/* The labels array is an array of varying length text, scan it adding
the length of the previous entry until we are done or we have found
a match. */
labelsp = (char *) ARR_DATA_PTR(labels);
nelem = ARR_DIMS(labels)[0];
for (i = 0; i < nelem; i++)
{
int lsize = VARSIZE(labelsp);
if (asize == lsize && !memcmp(attr, labelsp, lsize))
return i; /* Found */
labelsp = labelsp + lsize;
labelsp = (char*) att_align_nominal(labelsp, typalign);
}
return -1; /* Not found */
}
/*
* pivot_accum() - Pivot and accumulate
*/
static Datum oid_pivot_accum(FunctionCallInfo fcinfo, Oid type)
{
ArrayType *data;
ArrayType *labels;
text *attr;
int i;
/* Simple argument validation */
if (PG_NARGS() != 4)
ereport(ERROR,
(errcode(ERRCODE_DATATYPE_MISMATCH),
errmsg("pivot_accum called with %d input arguments",
PG_NARGS())));
if (PG_ARGISNULL(1) || PG_ARGISNULL(2) || PG_ARGISNULL(3))
{
if (PG_ARGISNULL(0))
PG_RETURN_NULL();
PG_RETURN_ARRAYTYPE_P(PG_GETARG_ARRAYTYPE_P(0));
}
labels = PG_GETARG_ARRAYTYPE_P(1);
attr = PG_GETARG_TEXT_P(2);
/* Do nothing if the attr isn't in the labels array. */
if ((i = pivot_find(labels, attr)) < 0)
{
if (PG_ARGISNULL(0))
PG_RETURN_NULL();
PG_RETURN_ARRAYTYPE_P(PG_GETARG_ARRAYTYPE_P(0));
}
/* Get the data array, or make it if null */
if (!PG_ARGISNULL(0))
{
data = PG_GETARG_ARRAYTYPE_P(0);
Assert(ARR_DIMS(labels)[0] == ARR_DIMS(data)[0]);
}
else
{
int elsize, size, nelem;
Oid eltype = type;
switch (type) {
case INT4OID:
/* addition of two int4 should be int8, otherwise it may cause overflow in addition*/
elsize = 8;
eltype = INT8OID;
break;
case INT8OID:
case FLOAT8OID:
elsize = 8;
break;
default:
elsize = 0; /* Fixes complier warnings */
Assert(false);
}
nelem = ARR_DIMS(labels)[0];
size = nelem * elsize + ARR_OVERHEAD_NONULLS(1);
data = (ArrayType *) palloc(size);
SET_VARSIZE(data, size);
data->ndim = 1;
data->dataoffset = 0;
data->elemtype = eltype;
ARR_DIMS(data)[0] = nelem;
ARR_LBOUND(data)[0] = 1;
memset(ARR_DATA_PTR(data), 0, nelem * elsize);
}
/*
* Should we think about upconverting the arrays? Or is the assumption that
* the pivot isn't usually doing much aggregation?
*/
switch (type) {
case INT4OID:
{
int64 *datap = (int64*) ARR_DATA_PTR(data);
int32 value = PG_GETARG_INT32(3);
datap[i] += value;
break;
}
case INT8OID:
{
int64 *datap = (int64*) ARR_DATA_PTR(data);
int64 value = PG_GETARG_INT64(3);
datap[i] += value;
break;
}
case FLOAT8OID:
{
float8 *datap = (float8*) ARR_DATA_PTR(data);
float8 value = PG_GETARG_FLOAT8(3);
datap[i] += value;
break;
}
default:
Assert(false);
}
PG_RETURN_ARRAYTYPE_P(data);
}
| 22.120805 | 89 | 0.642445 |
5822780e7a167405886a5437dec434915e072058 | 530 | h | C | usr/libexec/securityd/SecDbBackupManager.h | lechium/tvOS135Headers | 46cd30d3f0f7962eaa0c3f925cd71f414c65e2ac | [
"MIT"
] | 2 | 2020-07-26T20:30:54.000Z | 2020-08-10T04:26:23.000Z | usr/libexec/securityd/SecDbBackupManager.h | lechium/tvOS135Headers | 46cd30d3f0f7962eaa0c3f925cd71f414c65e2ac | [
"MIT"
] | 1 | 2020-07-26T20:45:31.000Z | 2020-08-09T09:30:46.000Z | usr/libexec/securityd/SecDbBackupManager.h | lechium/tvOS135Headers | 46cd30d3f0f7962eaa0c3f925cd71f414c65e2ac | [
"MIT"
] | null | null | null | //
// Generated by classdumpios 1.0.1 (64 bit) (iOS port by DreamDevLost)(Debug version compiled Jun 10 2020 10:03:13).
//
// Copyright (C) 1997-2019 Steve Nygard.
//
#import <objc/NSObject.h>
__attribute__((visibility("hidden")))
@interface SecDbBackupManager : NSObject
{
}
+ (id)manager; // IMP=0x00000001000a1c1c
- (id)wrapItemKey:(id)arg1 forKeyclass:(int)arg2 error:(id *)arg3; // IMP=0x00000001000a1d3c
- (void)verifyBackupIntegrity:(_Bool)arg1 completion:(CDUnknownBlockType)arg2; // IMP=0x00000001000a1c24
@end
| 26.5 | 120 | 0.732075 |
d4b3861797d0a7053ff57ec127060695944e7578 | 12,259 | rs | Rust | src/port_1_2/p1sel0.rs | chrismolli/msp430fr6972 | a3c38a455c8830b3d2c6674564e2ed98d06ee1fc | [
"MIT"
] | null | null | null | src/port_1_2/p1sel0.rs | chrismolli/msp430fr6972 | a3c38a455c8830b3d2c6674564e2ed98d06ee1fc | [
"MIT"
] | null | null | null | src/port_1_2/p1sel0.rs | chrismolli/msp430fr6972 | a3c38a455c8830b3d2c6674564e2ed98d06ee1fc | [
"MIT"
] | null | null | null | #[doc = "Register `P1SEL0` reader"]
pub struct R(crate::R<P1SEL0_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<P1SEL0_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::convert::From<crate::R<P1SEL0_SPEC>> for R {
fn from(reader: crate::R<P1SEL0_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `P1SEL0` writer"]
pub struct W(crate::W<P1SEL0_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<P1SEL0_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl core::convert::From<crate::W<P1SEL0_SPEC>> for W {
fn from(writer: crate::W<P1SEL0_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Field `P1SEL0_0` reader - P1SEL0_0"]
pub struct P1SEL0_0_R(crate::FieldReader<bool, bool>);
impl P1SEL0_0_R {
pub(crate) fn new(bits: bool) -> Self {
P1SEL0_0_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for P1SEL0_0_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `P1SEL0_0` writer - P1SEL0_0"]
pub struct P1SEL0_0_W<'a> {
w: &'a mut W,
}
impl<'a> P1SEL0_0_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | (value as u8 & 0x01);
self.w
}
}
#[doc = "Field `P1SEL0_1` reader - P1SEL0_1"]
pub struct P1SEL0_1_R(crate::FieldReader<bool, bool>);
impl P1SEL0_1_R {
pub(crate) fn new(bits: bool) -> Self {
P1SEL0_1_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for P1SEL0_1_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `P1SEL0_1` writer - P1SEL0_1"]
pub struct P1SEL0_1_W<'a> {
w: &'a mut W,
}
impl<'a> P1SEL0_1_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | ((value as u8 & 0x01) << 1);
self.w
}
}
#[doc = "Field `P1SEL0_2` reader - P1SEL0_2"]
pub struct P1SEL0_2_R(crate::FieldReader<bool, bool>);
impl P1SEL0_2_R {
pub(crate) fn new(bits: bool) -> Self {
P1SEL0_2_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for P1SEL0_2_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `P1SEL0_2` writer - P1SEL0_2"]
pub struct P1SEL0_2_W<'a> {
w: &'a mut W,
}
impl<'a> P1SEL0_2_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 2)) | ((value as u8 & 0x01) << 2);
self.w
}
}
#[doc = "Field `P1SEL0_3` reader - P1SEL0_3"]
pub struct P1SEL0_3_R(crate::FieldReader<bool, bool>);
impl P1SEL0_3_R {
pub(crate) fn new(bits: bool) -> Self {
P1SEL0_3_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for P1SEL0_3_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `P1SEL0_3` writer - P1SEL0_3"]
pub struct P1SEL0_3_W<'a> {
w: &'a mut W,
}
impl<'a> P1SEL0_3_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 3)) | ((value as u8 & 0x01) << 3);
self.w
}
}
#[doc = "Field `P1SEL0_4` reader - P1SEL0_4"]
pub struct P1SEL0_4_R(crate::FieldReader<bool, bool>);
impl P1SEL0_4_R {
pub(crate) fn new(bits: bool) -> Self {
P1SEL0_4_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for P1SEL0_4_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `P1SEL0_4` writer - P1SEL0_4"]
pub struct P1SEL0_4_W<'a> {
w: &'a mut W,
}
impl<'a> P1SEL0_4_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 4)) | ((value as u8 & 0x01) << 4);
self.w
}
}
#[doc = "Field `P1SEL0_5` reader - P1SEL0_5"]
pub struct P1SEL0_5_R(crate::FieldReader<bool, bool>);
impl P1SEL0_5_R {
pub(crate) fn new(bits: bool) -> Self {
P1SEL0_5_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for P1SEL0_5_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `P1SEL0_5` writer - P1SEL0_5"]
pub struct P1SEL0_5_W<'a> {
w: &'a mut W,
}
impl<'a> P1SEL0_5_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 5)) | ((value as u8 & 0x01) << 5);
self.w
}
}
#[doc = "Field `P1SEL0_6` reader - P1SEL0_6"]
pub struct P1SEL0_6_R(crate::FieldReader<bool, bool>);
impl P1SEL0_6_R {
pub(crate) fn new(bits: bool) -> Self {
P1SEL0_6_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for P1SEL0_6_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `P1SEL0_6` writer - P1SEL0_6"]
pub struct P1SEL0_6_W<'a> {
w: &'a mut W,
}
impl<'a> P1SEL0_6_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 6)) | ((value as u8 & 0x01) << 6);
self.w
}
}
#[doc = "Field `P1SEL0_7` reader - P1SEL0_7"]
pub struct P1SEL0_7_R(crate::FieldReader<bool, bool>);
impl P1SEL0_7_R {
pub(crate) fn new(bits: bool) -> Self {
P1SEL0_7_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for P1SEL0_7_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `P1SEL0_7` writer - P1SEL0_7"]
pub struct P1SEL0_7_W<'a> {
w: &'a mut W,
}
impl<'a> P1SEL0_7_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 7)) | ((value as u8 & 0x01) << 7);
self.w
}
}
impl R {
#[doc = "Bit 0 - P1SEL0_0"]
#[inline(always)]
pub fn p1sel0_0(&self) -> P1SEL0_0_R {
P1SEL0_0_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - P1SEL0_1"]
#[inline(always)]
pub fn p1sel0_1(&self) -> P1SEL0_1_R {
P1SEL0_1_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - P1SEL0_2"]
#[inline(always)]
pub fn p1sel0_2(&self) -> P1SEL0_2_R {
P1SEL0_2_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - P1SEL0_3"]
#[inline(always)]
pub fn p1sel0_3(&self) -> P1SEL0_3_R {
P1SEL0_3_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - P1SEL0_4"]
#[inline(always)]
pub fn p1sel0_4(&self) -> P1SEL0_4_R {
P1SEL0_4_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - P1SEL0_5"]
#[inline(always)]
pub fn p1sel0_5(&self) -> P1SEL0_5_R {
P1SEL0_5_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 6 - P1SEL0_6"]
#[inline(always)]
pub fn p1sel0_6(&self) -> P1SEL0_6_R {
P1SEL0_6_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 7 - P1SEL0_7"]
#[inline(always)]
pub fn p1sel0_7(&self) -> P1SEL0_7_R {
P1SEL0_7_R::new(((self.bits >> 7) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - P1SEL0_0"]
#[inline(always)]
pub fn p1sel0_0(&mut self) -> P1SEL0_0_W {
P1SEL0_0_W { w: self }
}
#[doc = "Bit 1 - P1SEL0_1"]
#[inline(always)]
pub fn p1sel0_1(&mut self) -> P1SEL0_1_W {
P1SEL0_1_W { w: self }
}
#[doc = "Bit 2 - P1SEL0_2"]
#[inline(always)]
pub fn p1sel0_2(&mut self) -> P1SEL0_2_W {
P1SEL0_2_W { w: self }
}
#[doc = "Bit 3 - P1SEL0_3"]
#[inline(always)]
pub fn p1sel0_3(&mut self) -> P1SEL0_3_W {
P1SEL0_3_W { w: self }
}
#[doc = "Bit 4 - P1SEL0_4"]
#[inline(always)]
pub fn p1sel0_4(&mut self) -> P1SEL0_4_W {
P1SEL0_4_W { w: self }
}
#[doc = "Bit 5 - P1SEL0_5"]
#[inline(always)]
pub fn p1sel0_5(&mut self) -> P1SEL0_5_W {
P1SEL0_5_W { w: self }
}
#[doc = "Bit 6 - P1SEL0_6"]
#[inline(always)]
pub fn p1sel0_6(&mut self) -> P1SEL0_6_W {
P1SEL0_6_W { w: self }
}
#[doc = "Bit 7 - P1SEL0_7"]
#[inline(always)]
pub fn p1sel0_7(&mut self) -> P1SEL0_7_W {
P1SEL0_7_W { w: self }
}
#[doc = "Writes raw bits to the register."]
pub unsafe fn bits(&mut self, bits: u8) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "Port 1 Selection 0\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [p1sel0](index.html) module"]
pub struct P1SEL0_SPEC;
impl crate::RegisterSpec for P1SEL0_SPEC {
type Ux = u8;
}
#[doc = "`read()` method returns [p1sel0::R](R) reader structure"]
impl crate::Readable for P1SEL0_SPEC {
type Reader = R;
}
#[doc = "`write(|w| ..)` method takes [p1sel0::W](W) writer structure"]
impl crate::Writable for P1SEL0_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets P1SEL0 to value 0"]
impl crate::Resettable for P1SEL0_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}
| 28.377315 | 405 | 0.56122 |
9633b21dc70eb5c8dc3e55773c71baa1b0049e97 | 1,925 | php | PHP | src/Checkout.php | cathrinevaage/commerce | 32457c2d45a8f5cd7b83d6139097a714ef429873 | [
"MIT"
] | 1 | 2020-01-14T13:21:39.000Z | 2020-01-14T13:21:39.000Z | src/Checkout.php | cathrinevaage/commerce | 32457c2d45a8f5cd7b83d6139097a714ef429873 | [
"MIT"
] | 6 | 2021-02-02T16:08:09.000Z | 2021-09-28T08:39:44.000Z | src/Checkout.php | cathrinevaage/commerce | 32457c2d45a8f5cd7b83d6139097a714ef429873 | [
"MIT"
] | 1 | 2020-08-11T07:55:52.000Z | 2020-08-11T07:55:52.000Z | <?php
namespace Netflex\Commerce;
use Carbon\Carbon;
use Netflex\Support\ReactiveObject;
/**
* @property-read int $id
* @property-read int $order_id
* @property Carbon $checkout_start
* @property Carbon $checkout_end
* @property string $firstname
* @property string $surname
* @property string $company
* @property string $address
* @property string $postal
* @property string $city
* @property string $shipping_firstname
* @property string $shipping_surname
* @property string $shipping_company
* @property string $shipping_address
* @property string $shipping_postal
* @property string $shipping_city
* @property float $shipping_cost
* @property float $shipping_tax
* @property float $shipping_total
* @property float $expedition_cost
* @property float $expedition_tax
* @property float $expedition_total
* @property string $shipping_tracking_code
* @property string $shipping_tracking_url
* @property string $ip
* @property string $user_agent
* @property Carbon $updated
*/
class Checkout extends ReactiveObject
{
public function getOrderIdAttribute($value)
{
return (int) $value;
}
public function getShippingCostAttribute($value)
{
return (float) $value;
}
public function getShippingTaxAttribute($value)
{
return (float) $value;
}
public function getShippingTotalAttribute($value)
{
return (float) $value;
}
public function getExpeditionCostAttribute($value)
{
return (float) $value;
}
public function getExpeditionTaxAttribute($value)
{
return (float) $value;
}
public function getExpeditionTotalAttribute($value)
{
return (float) $value;
}
public function getCheckoutStartAttribute($value)
{
return !empty($value) ? new Carbon($value) : null;
}
public function getCheckoutEndAttribute($value)
{
return (!empty($value) && $value !== '0000-00-00 00:00:00') ? new Carbon($value) : null;
}
}
| 22.916667 | 92 | 0.717922 |
f70c88729ab9cdc07bf4d6f8cfef840eb5324378 | 212 | h | C | iOSStudy/iOSStudy/src/Features/CallStack/NKCallStackSymbols/NKCallStackSymbols.h | nchkdxlq/iOSStudy | 8febd53409c36655193a62c8362353f3c6eda62e | [
"MIT"
] | null | null | null | iOSStudy/iOSStudy/src/Features/CallStack/NKCallStackSymbols/NKCallStackSymbols.h | nchkdxlq/iOSStudy | 8febd53409c36655193a62c8362353f3c6eda62e | [
"MIT"
] | null | null | null | iOSStudy/iOSStudy/src/Features/CallStack/NKCallStackSymbols/NKCallStackSymbols.h | nchkdxlq/iOSStudy | 8febd53409c36655193a62c8362353f3c6eda62e | [
"MIT"
] | null | null | null | //
// NKCallStackSymbols.h
// iOSStudy
//
// Created by Knox on 2021/11/1.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface NKCallStackSymbols : NSObject
@end
NS_ASSUME_NONNULL_END
| 12.470588 | 40 | 0.745283 |
276d35c46de325233ce40640c14f197540de865e | 31,693 | sql | SQL | public_html/install/database.sql | sorge13248/lightschool | e2f6e5f4d30301b0c43cb84161de50bfd8c394e9 | [
"Apache-2.0"
] | null | null | null | public_html/install/database.sql | sorge13248/lightschool | e2f6e5f4d30301b0c43cb84161de50bfd8c394e9 | [
"Apache-2.0"
] | null | null | null | public_html/install/database.sql | sorge13248/lightschool | e2f6e5f4d30301b0c43cb84161de50bfd8c394e9 | [
"Apache-2.0"
] | null | null | null | -- phpMyAdmin SQL Dump
-- version 4.8.0
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Aug 11, 2019 at 03:04 PM
-- Server version: 10.1.31-MariaDB
-- PHP Version: 7.2.4
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `lightschool`
--
-- --------------------------------------------------------
--
-- Table structure for table `access`
--
CREATE TABLE IF NOT EXISTS `access` (
`id` int(25) NOT NULL AUTO_INCREMENT,
`user` int(10) UNSIGNED NOT NULL,
`date` varchar(19) COLLATE utf8mb4_unicode_ci NOT NULL,
`ip` varchar(32) COLLATE utf8mb4_unicode_ci NOT NULL,
`allow` tinyint(1) NOT NULL DEFAULT '1',
`logged_in` tinyint(1) NOT NULL DEFAULT '1',
`agent` varchar(512) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT 'User agent',
`type` varchar(24) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `user_id` (`user`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Stand-in structure for view `all_users`
-- (See below for the actual view)
--
CREATE TABLE IF NOT EXISTS `all_users` (
`id` int(10) unsigned
,`email` varchar(249)
,`password` varchar(255)
,`username` varchar(100)
,`status` tinyint(2) unsigned
,`verified` tinyint(1) unsigned
,`resettable` tinyint(1) unsigned
,`roles_mask` int(10) unsigned
,`registered` int(10) unsigned
,`last_login` int(10) unsigned
,`force_logout` mediumint(7) unsigned
,`name` varchar(128)
,`surname` varchar(128)
,`profile_picture` int(11)
,`wallpaper` varchar(55)
,`taskbar` longtext
,`type` varchar(11)
,`accent` varchar(6)
,`theme` varchar(64)
,`plan` tinyint(2) unsigned
,`twofa` blob
,`privacy_search_visible` tinyint(1)
,`privacy_show_email` tinyint(1)
,`privacy_show_username` tinyint(1)
,`privacy_send_messages` tinyint(1) unsigned
,`privacy_ms_office` tinyint(1) unsigned
,`privacy_share_documents` tinyint(1) unsigned
,`password_last_change` timestamp
,`blocked` varchar(1204)
,`taskbar_size` tinyint(4)
);
-- --------------------------------------------------------
--
-- Table structure for table `app_catalog`
--
CREATE TABLE IF NOT EXISTS `app_catalog` (
`unique_name` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL,
`version` float UNSIGNED NOT NULL DEFAULT '1',
`category` varchar(32) COLLATE utf8mb4_unicode_ci NOT NULL,
`author` int(10) UNSIGNED DEFAULT NULL,
`visible` tinyint(1) NOT NULL DEFAULT '1',
`icon` tinyint(1) UNSIGNED NOT NULL DEFAULT '1',
`system` tinyint(1) UNSIGNED NOT NULL DEFAULT '0',
`settings` tinyint(1) UNSIGNED NOT NULL DEFAULT '0' COMMENT 'App has settings page',
`name_en` varchar(32) COLLATE utf8mb4_unicode_ci NOT NULL,
`name_it` varchar(32) COLLATE utf8mb4_unicode_ci NOT NULL,
`detail_en` longtext COLLATE utf8mb4_unicode_ci,
`detail_it` longtext COLLATE utf8mb4_unicode_ci,
`features` varchar(512) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`preview` tinyint(1) UNSIGNED NOT NULL DEFAULT '0',
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`t_icon` varchar(5) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
PRIMARY KEY (`unique_name`),
KEY `category` (`category`),
KEY `author` (`author`),
KEY `visible` (`visible`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `app_catalog`
--
INSERT INTO `app_catalog` (`unique_name`, `version`, `category`, `author`, `visible`, `icon`, `system`, `settings`, `name_en`, `name_it`, `detail_en`, `detail_it`, `features`, `preview`, `timestamp`, `t_icon`) VALUES
('contact', 1, 'system', NULL, 1, 1, 0, 1, 'Contact', 'Contatti', NULL, NULL, NULL, 0, '2019-01-01 07:00:00', NULL),
('desktop', 1, 'system', NULL, 1, 1, 0, 0, 'Desktop', 'Desktop', NULL, NULL, NULL, 0, '2019-01-01 07:00:00', NULL),
('diary', 1, 'system', NULL, 1, 1, 0, 0, 'Diary', 'Diario', NULL, NULL, NULL, 0, '2019-01-01 07:00:00', NULL),
('file-manager', 1, 'system', NULL, 1, 1, 0, 0, 'File Manager', 'Gestore file', '<p>Take notes, upload files and organize them in folders</p>', '<p>Prendi appunti, carica file e organizzali in cartelle</p>', NULL, 0, '2019-01-01 07:00:00', NULL),
('message', 1, 'system', NULL, 1, 1, 0, 0, 'Message', 'Messaggi', NULL, NULL, NULL, 0, '2019-01-01 07:00:00', NULL),
('project', 0.1, 'system', NULL, 1, 1, 0, 0, 'WhiteBoard', 'LIM', NULL, NULL, NULL, 1, '2019-08-10 08:40:00', NULL),
('quiz', 0.1, 'system', NULL, 0, 1, 0, 0, 'Quiz', 'Quiz', NULL, NULL, NULL, 1, '2019-01-01 07:00:00', NULL),
('reader', 1, 'system', NULL, 1, 1, 0, 0, 'Reader', 'Lettore', NULL, NULL, NULL, 0, '2019-01-01 07:00:00', NULL),
('register', 0.1, 'system', NULL, 0, 1, 0, 0, 'Register', 'Registro', NULL, NULL, NULL, 1, '2019-01-01 07:00:00', NULL),
('settings', 1, 'system', NULL, 1, 1, 1, 0, 'Settings', 'Impostazioni', NULL, NULL, NULL, 0, '2019-01-01 07:00:00', NULL),
('share', 1, 'system', NULL, 1, 1, 0, 0, 'Share', 'Condivisioni', NULL, NULL, NULL, 0, '2019-01-01 07:00:00', NULL),
('social', 0.1, 'system', NULL, 0, 1, 0, 0, 'Social', 'Social', NULL, NULL, NULL, 1, '2019-08-06 06:00:00', NULL),
('store', 1, 'system', NULL, 1, 1, 1, 0, 'LightStore', 'LightStore', NULL, NULL, NULL, 0, '2019-01-01 07:00:00', NULL),
('t-dark', 1, 'themes', NULL, 1, 0, 0, 0, 'Default', 'Scuro', NULL, NULL, NULL, 0, '2019-01-01 07:00:00', 'white'),
('t-default', 1, 'themes', NULL, 1, 0, 1, 0, 'Default', 'Predefinito', NULL, NULL, NULL, 0, '2019-01-01 07:00:00', 'black'),
('timetable', 1, 'system', NULL, 1, 1, 0, 0, 'Timetable', 'Orario', NULL, NULL, NULL, 0, '2019-01-01 07:00:00', NULL),
('trash', 1, 'system', NULL, 1, 1, 0, 0, 'Trash', 'Cestino', NULL, NULL, NULL, 0, '2019-01-01 07:00:00', NULL),
('writer', 1, 'system', NULL, 1, 1, 0, 0, 'Writer', 'Writer', NULL, NULL, NULL, 0, '2019-01-01 07:00:00', NULL);
-- --------------------------------------------------------
--
-- Table structure for table `app_category`
--
CREATE TABLE IF NOT EXISTS `app_category` (
`name` varchar(32) COLLATE utf8mb4_unicode_ci NOT NULL,
`sub` varchar(32) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`visible` tinyint(1) NOT NULL DEFAULT '1',
`icon` tinyint(1) NOT NULL DEFAULT '1',
`name_en` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL,
`name_it` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL,
PRIMARY KEY (`name`),
KEY `sub` (`sub`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `app_category`
--
INSERT INTO `app_category` (`name`, `sub`, `visible`, `icon`, `name_en`, `name_it`) VALUES
('dark-themes', 'themes', 1, 0, 'Dark themes', 'Temi scuri'),
('light-themes', 'themes', 1, 0, 'Light themes', 'Temi chiari'),
('system', NULL, 1, 1, 'LightSchool System', 'Sistema LightSchool'),
('themes', NULL, 1, 0, 'Themes', 'Temi');
-- --------------------------------------------------------
--
-- Table structure for table `app_purchase`
--
CREATE TABLE IF NOT EXISTS `app_purchase` (
`id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`user` int(10) UNSIGNED NOT NULL,
`app` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`application_launcher` tinyint(1) UNSIGNED NOT NULL DEFAULT '1',
`data` longtext COLLATE utf8mb4_unicode_ci,
PRIMARY KEY (`id`),
UNIQUE KEY `user` (`user`,`app`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `contact`
--
CREATE TABLE IF NOT EXISTS `contact` (
`id` int(25) NOT NULL AUTO_INCREMENT COMMENT 'ID univoco',
`user_id` int(10) UNSIGNED NOT NULL COMMENT 'ID utente di chi salva il contatto',
`name` varchar(128) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT 'Nome del contatto',
`surname` varchar(128) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT 'Cognome del contatto',
`contact_id` int(10) UNSIGNED DEFAULT NULL COMMENT 'ID del contatto',
`fav` tinyint(1) NOT NULL DEFAULT '0',
`trash` tinyint(1) NOT NULL DEFAULT '0',
`deleted` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `contact_id` (`contact_id`),
KEY `user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `country`
--
CREATE TABLE IF NOT EXISTS `country` (
`code` varchar(2) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
`name` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
PRIMARY KEY (`code`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `country`
--
INSERT INTO `country` (`code`, `name`) VALUES
('AD', 'Andorra'),
('AE', 'United Arab Emirates'),
('AF', 'Afghanistan'),
('AG', 'Antigua and Barbuda'),
('AI', 'Anguilla'),
('AL', 'Albania'),
('AM', 'Armenia'),
('AN', 'Netherlands Antilles'),
('AO', 'Angola'),
('AQ', 'Antarctica'),
('AR', 'Argentina'),
('AT', 'Austria'),
('AU', 'Australia'),
('AW', 'Aruba'),
('AZ', 'Azerbaijan'),
('BA', 'Bosnia and Herzegovina'),
('BB', 'Barbados'),
('BD', 'Bangladesh'),
('BE', 'Belgium'),
('BF', 'Burkina Faso'),
('BG', 'Bulgaria'),
('BH', 'Bahrain'),
('BI', 'Burundi'),
('BJ', 'Benin'),
('BM', 'Bermuda'),
('BN', 'Brunei Darussalam'),
('BO', 'Bolivia'),
('BR', 'Brazil'),
('BS', 'Bahamas'),
('BT', 'Bhutan'),
('BV', 'Bouvet Island'),
('BW', 'Botswana'),
('BY', 'Belarus'),
('BZ', 'Belize'),
('CA', 'Canada'),
('CC', 'Cocos (Keeling) Islands'),
('CF', 'Central African Republic'),
('CG', 'Congo'),
('CH', 'Switzerland'),
('CI', 'Ivory Coast'),
('CK', 'Cook Islands'),
('CL', 'Chile'),
('CM', 'Cameroon'),
('CN', 'China'),
('CO', 'Colombia'),
('CR', 'Costa Rica'),
('CU', 'Cuba'),
('CV', 'Cape Verde'),
('CX', 'Christmas Island'),
('CY', 'Cyprus'),
('CZ', 'Czech Republic'),
('DE', 'Germany'),
('DJ', 'Djibouti'),
('DK', 'Denmark'),
('DM', 'Dominica'),
('DO', 'Dominican Republic'),
('DS', 'American Samoa'),
('DZ', 'Algeria'),
('EC', 'Ecuador'),
('EE', 'Estonia'),
('EG', 'Egypt'),
('EH', 'Western Sahara'),
('ER', 'Eritrea'),
('ES', 'Spain'),
('ET', 'Ethiopia'),
('FI', 'Finland'),
('FJ', 'Fiji'),
('FK', 'Falkland Islands (Malvinas)'),
('FM', 'Micronesia, Federated States of'),
('FO', 'Faroe Islands'),
('FR', 'France'),
('FX', 'France, Metropolitan'),
('GA', 'Gabon'),
('GB', 'United Kingdom'),
('GD', 'Grenada'),
('GE', 'Georgia'),
('GF', 'French Guiana'),
('GH', 'Ghana'),
('GI', 'Gibraltar'),
('GK', 'Guernsey'),
('GL', 'Greenland'),
('GM', 'Gambia'),
('GN', 'Guinea'),
('GP', 'Guadeloupe'),
('GQ', 'Equatorial Guinea'),
('GR', 'Greece'),
('GS', 'South Georgia South Sandwich Islands'),
('GT', 'Guatemala'),
('GU', 'Guam'),
('GW', 'Guinea-Bissau'),
('GY', 'Guyana'),
('HK', 'Hong Kong'),
('HM', 'Heard and Mc Donald Islands'),
('HN', 'Honduras'),
('HR', 'Croatia (Hrvatska)'),
('HT', 'Haiti'),
('HU', 'Hungary'),
('ID', 'Indonesia'),
('IE', 'Ireland'),
('IL', 'Israel'),
('IM', 'Isle of Man'),
('IN', 'India'),
('IO', 'British Indian Ocean Territory'),
('IQ', 'Iraq'),
('IR', 'Iran (Islamic Republic of)'),
('IS', 'Iceland'),
('IT', 'Italy'),
('JE', 'Jersey'),
('JM', 'Jamaica'),
('JO', 'Jordan'),
('JP', 'Japan'),
('KE', 'Kenya'),
('KG', 'Kyrgyzstan'),
('KH', 'Cambodia'),
('KI', 'Kiribati'),
('KM', 'Comoros'),
('KN', 'Saint Kitts and Nevis'),
('KP', 'Korea, Democratic People\'s Republic of'),
('KR', 'Korea, Republic of'),
('KW', 'Kuwait'),
('KY', 'Cayman Islands'),
('KZ', 'Kazakhstan'),
('LA', 'Lao People\'s Democratic Republic'),
('LB', 'Lebanon'),
('LC', 'Saint Lucia'),
('LI', 'Liechtenstein'),
('LK', 'Sri Lanka'),
('LR', 'Liberia'),
('LS', 'Lesotho'),
('LT', 'Lithuania'),
('LU', 'Luxembourg'),
('LV', 'Latvia'),
('LY', 'Libyan Arab Jamahiriya'),
('MA', 'Morocco'),
('MC', 'Monaco'),
('MD', 'Moldova, Republic of'),
('ME', 'Montenegro'),
('MG', 'Madagascar'),
('MH', 'Marshall Islands'),
('MK', 'Macedonia'),
('ML', 'Mali'),
('MM', 'Myanmar'),
('MN', 'Mongolia'),
('MO', 'Macau'),
('MP', 'Northern Mariana Islands'),
('MQ', 'Martinique'),
('MR', 'Mauritania'),
('MS', 'Montserrat'),
('MT', 'Malta'),
('MU', 'Mauritius'),
('MV', 'Maldives'),
('MW', 'Malawi'),
('MX', 'Mexico'),
('MY', 'Malaysia'),
('MZ', 'Mozambique'),
('NA', 'Namibia'),
('NC', 'New Caledonia'),
('NE', 'Niger'),
('NF', 'Norfolk Island'),
('NG', 'Nigeria'),
('NI', 'Nicaragua'),
('NL', 'Netherlands'),
('NO', 'Norway'),
('NP', 'Nepal'),
('NR', 'Nauru'),
('NU', 'Niue'),
('NZ', 'New Zealand'),
('OM', 'Oman'),
('PA', 'Panama'),
('PE', 'Peru'),
('PF', 'French Polynesia'),
('PG', 'Papua New Guinea'),
('PH', 'Philippines'),
('PK', 'Pakistan'),
('PL', 'Poland'),
('PM', 'St. Pierre and Miquelon'),
('PN', 'Pitcairn'),
('PR', 'Puerto Rico'),
('PS', 'Palestine'),
('PT', 'Portugal'),
('PW', 'Palau'),
('PY', 'Paraguay'),
('QA', 'Qatar'),
('RE', 'Reunion'),
('RO', 'Romania'),
('RS', 'Serbia'),
('RU', 'Russian Federation'),
('RW', 'Rwanda'),
('SA', 'Saudi Arabia'),
('SB', 'Solomon Islands'),
('SC', 'Seychelles'),
('SD', 'Sudan'),
('SE', 'Sweden'),
('SG', 'Singapore'),
('SH', 'St. Helena'),
('SI', 'Slovenia'),
('SJ', 'Svalbard and Jan Mayen Islands'),
('SK', 'Slovakia'),
('SL', 'Sierra Leone'),
('SM', 'San Marino'),
('SN', 'Senegal'),
('SO', 'Somalia'),
('SR', 'Suriname'),
('SS', 'South Sudan'),
('ST', 'Sao Tome and Principe'),
('SV', 'El Salvador'),
('SY', 'Syrian Arab Republic'),
('SZ', 'Swaziland'),
('TC', 'Turks and Caicos Islands'),
('TD', 'Chad'),
('TF', 'French Southern Territories'),
('TG', 'Togo'),
('TH', 'Thailand'),
('TJ', 'Tajikistan'),
('TK', 'Tokelau'),
('TM', 'Turkmenistan'),
('TN', 'Tunisia'),
('TO', 'Tonga'),
('TP', 'East Timor'),
('TR', 'Turkey'),
('TT', 'Trinidad and Tobago'),
('TV', 'Tuvalu'),
('TW', 'Taiwan'),
('TY', 'Mayotte'),
('TZ', 'Tanzania, United Republic of'),
('UA', 'Ukraine'),
('UG', 'Uganda'),
('UM', 'United States minor outlying islands'),
('US', 'United States'),
('UY', 'Uruguay'),
('UZ', 'Uzbekistan'),
('VA', 'Vatican City State'),
('VC', 'Saint Vincent and the Grenadines'),
('VE', 'Venezuela'),
('VG', 'Virgin Islands (British)'),
('VI', 'Virgin Islands (U.S.)'),
('VN', 'Vietnam'),
('VU', 'Vanuatu'),
('WF', 'Wallis and Futuna Islands'),
('WS', 'Samoa'),
('XK', 'Kosovo'),
('YE', 'Yemen'),
('ZA', 'South Africa'),
('ZM', 'Zambia'),
('ZR', 'Zaire'),
('ZW', 'Zimbabwe');
-- --------------------------------------------------------
--
-- Stand-in structure for view `desktop`
-- (See below for the actual view)
--
CREATE TABLE IF NOT EXISTS `desktop` (
`user_id` int(11) unsigned
,`id` int(11) unsigned
,`name` varchar(128)
,`type` varchar(64)
,`surname` varchar(128)
,`diary_type` varchar(24)
,`diary_priority` tinyint(4)
,`diary_date` date
,`diary_color` varchar(6)
,`icon` varchar(24)
,`username` varchar(100)
,`file_url` longtext
,`file_type` varchar(255)
,`deleted` varchar(19)
);
-- --------------------------------------------------------
--
-- Table structure for table `error_report`
--
CREATE TABLE IF NOT EXISTS `error_report` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`type` varchar(128) COLLATE utf8mb4_unicode_ci NOT NULL,
`description` varchar(128) COLLATE utf8mb4_unicode_ci NOT NULL,
`detail` varchar(128) COLLATE utf8mb4_unicode_ci NOT NULL,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `file`
--
CREATE TABLE IF NOT EXISTS `file` (
`id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`user_id` int(10) UNSIGNED NOT NULL COMMENT 'Nome utente',
`type` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT 'Cartella, quaderno, diario o file',
`name` varchar(128) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT 'Titolo cartella, quaderno o file',
`diary_type` varchar(24) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT 'Tipo diario',
`diary_date` date DEFAULT NULL,
`diary_reminder` date DEFAULT NULL,
`diary_priority` tinyint(1) DEFAULT '0' COMMENT 'Priorità diario',
`diary_color` varchar(6) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`n_ver` tinyint(4) NOT NULL DEFAULT '1',
`header` longtext COLLATE utf8mb4_unicode_ci,
`cypher` blob,
`html` blob,
`footer` longtext COLLATE utf8mb4_unicode_ci,
`file_url` longtext COLLATE utf8mb4_unicode_ci COMMENT 'Indirizzo URL file',
`file_type` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT 'Tipo file',
`file_size` int(16) UNSIGNED DEFAULT NULL COMMENT 'Dimensione file',
`fav` tinyint(1) NOT NULL DEFAULT '0',
`icon` varchar(24) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT 'Icona',
`create_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Data di creazione',
`last_view` varchar(19) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT 'Ultima vista',
`last_edit` varchar(19) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT 'Ultima modifica',
`folder` int(16) UNSIGNED DEFAULT NULL,
`trash` tinyint(1) NOT NULL DEFAULT '0',
`history` int(11) UNSIGNED DEFAULT NULL,
`bypass` timestamp NULL DEFAULT NULL,
`deleted` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `Username` (`user_id`),
KEY `history` (`history`),
KEY `deleted` (`deleted`),
KEY `trash` (`trash`),
KEY `folder` (`folder`),
KEY `fav` (`fav`),
KEY `type` (`type`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `message_actors`
--
CREATE TABLE IF NOT EXISTS `message_actors` (
`id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`list_id` int(10) UNSIGNED NOT NULL,
`user_id` int(10) UNSIGNED NOT NULL,
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `message_chat`
--
CREATE TABLE IF NOT EXISTS `message_chat` (
`id` int(25) UNSIGNED NOT NULL AUTO_INCREMENT,
`message_list_id` int(10) UNSIGNED NOT NULL,
`sender` int(10) UNSIGNED NOT NULL COMMENT 'Chi invia',
`cypher` blob,
`body` blob,
`attachment` blob,
`date` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Data',
`is_read` timestamp NULL DEFAULT NULL COMMENT 'Letto o no',
PRIMARY KEY (`id`),
KEY `sender` (`sender`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `message_list`
--
CREATE TABLE IF NOT EXISTS `message_list` (
`id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`subject` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `plan`
--
CREATE TABLE IF NOT EXISTS `plan` (
`id` tinyint(2) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` varchar(32) COLLATE utf8mb4_unicode_ci NOT NULL,
`disk_space` int(9) UNSIGNED NOT NULL COMMENT 'in MB',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `plan`
--
INSERT INTO `plan` (`id`, `name`, `disk_space`) VALUES
(1, 'basic', 10),
(2, 'admin', 100);
-- --------------------------------------------------------
--
-- Table structure for table `project`
--
CREATE TABLE IF NOT EXISTS `project` (
`id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`code` varchar(6) COLLATE utf8mb4_unicode_ci NOT NULL,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `gen_id` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `project_files`
--
CREATE TABLE IF NOT EXISTS `project_files` (
`id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`project` varchar(6) COLLATE utf8mb4_unicode_ci NOT NULL,
`file` int(10) UNSIGNED NOT NULL,
`user` int(10) UNSIGNED NOT NULL,
`editable` tinyint(1) UNSIGNED NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `whiteboard_2` (`project`,`file`),
KEY `whiteboard` (`project`),
KEY `file` (`file`),
KEY `user` (`user`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `school`
--
CREATE TABLE IF NOT EXISTS `school` (
`id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL,
`address` varchar(128) COLLATE utf8mb4_unicode_ci NOT NULL,
`city` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL,
`country` varchar(2) COLLATE utf8mb4_unicode_ci NOT NULL,
`emergency` tinyint(1) NOT NULL DEFAULT '0',
`emergency_text` varchar(256) COLLATE utf8mb4_unicode_ci NOT NULL,
PRIMARY KEY (`id`),
KEY `country` (`country`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `share`
--
CREATE TABLE IF NOT EXISTS `share` (
`id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'ID univoco',
`sender` int(10) UNSIGNED NOT NULL COMMENT 'Chi condivide',
`receiving` int(10) UNSIGNED NOT NULL COMMENT 'Chi riceve',
`file` int(11) UNSIGNED NOT NULL COMMENT 'ID del file condiviso',
`comment` varchar(128) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT 'Commento di chi condivide',
`timestamp` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Data di condivisione',
`edit` tinyint(1) NOT NULL DEFAULT '0',
`deleted` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `receiving` (`receiving`),
KEY `sender` (`sender`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `theme`
--
CREATE TABLE IF NOT EXISTS `theme` (
`id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`author` int(10) UNSIGNED DEFAULT NULL,
`name` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL,
`unique_name` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL,
`icon` varchar(5) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'black' COMMENT 'Allowed values: white/black',
PRIMARY KEY (`id`),
KEY `author` (`author`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `theme`
--
INSERT INTO `theme` (`id`, `author`, `name`, `unique_name`, `icon`) VALUES
(1, NULL, 'Default', 'default', 'black'),
(2, NULL, 'Dark', 'dark', 'white'),
(3, NULL, 'Stupid', 'stupid', 'black');
-- --------------------------------------------------------
--
-- Table structure for table `timetable`
--
CREATE TABLE IF NOT EXISTS `timetable` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user` int(10) UNSIGNED NOT NULL,
`year` varchar(32) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`day` tinyint(1) UNSIGNED NOT NULL,
`slot` tinyint(1) UNSIGNED NOT NULL,
`subject` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL,
`book` varchar(64) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`fore` varchar(6) COLLATE utf8mb4_unicode_ci DEFAULT 'black',
`deleted` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `user` (`user`,`year`,`day`,`slot`,`deleted`),
KEY `year` (`year`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE IF NOT EXISTS `users` (
`id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`email` varchar(249) COLLATE utf8mb4_unicode_ci NOT NULL,
`password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`username` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`status` tinyint(2) UNSIGNED NOT NULL DEFAULT '0',
`verified` tinyint(1) UNSIGNED NOT NULL DEFAULT '0',
`resettable` tinyint(1) UNSIGNED NOT NULL DEFAULT '1',
`roles_mask` int(10) UNSIGNED NOT NULL DEFAULT '0',
`registered` int(10) UNSIGNED NOT NULL,
`last_login` int(10) UNSIGNED DEFAULT NULL,
`force_logout` mediumint(7) UNSIGNED NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `email` (`email`),
UNIQUE KEY `username` (`username`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `users_confirmations`
--
CREATE TABLE IF NOT EXISTS `users_confirmations` (
`id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`user_id` int(10) UNSIGNED NOT NULL,
`email` varchar(249) COLLATE utf8mb4_unicode_ci NOT NULL,
`selector` varchar(16) COLLATE utf8mb4_unicode_ci NOT NULL,
`token` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`expires` int(10) UNSIGNED NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `selector` (`selector`),
KEY `email_expires` (`email`(191),`expires`),
KEY `user_id` (`user_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `users_expanded`
--
CREATE TABLE IF NOT EXISTS `users_expanded` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(128) COLLATE utf8mb4_unicode_ci NOT NULL,
`surname` varchar(128) COLLATE utf8mb4_unicode_ci NOT NULL,
`profile_picture` int(11) DEFAULT NULL,
`wallpaper` varchar(55) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`taskbar` longtext COLLATE utf8mb4_unicode_ci,
`taskbar_size` tinyint(4) DEFAULT NULL,
`type` varchar(11) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'student',
`accent` varchar(6) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`theme` varchar(64) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`plan` tinyint(2) UNSIGNED NOT NULL DEFAULT '1',
`twofa` blob,
`deac_twofa` varchar(128) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`privacy_search_visible` tinyint(1) NOT NULL DEFAULT '1',
`privacy_show_email` tinyint(1) NOT NULL DEFAULT '0',
`privacy_show_username` tinyint(1) NOT NULL DEFAULT '0',
`privacy_send_messages` tinyint(1) UNSIGNED NOT NULL DEFAULT '1',
`privacy_share_documents` tinyint(1) UNSIGNED NOT NULL DEFAULT '1',
`privacy_ms_office` tinyint(1) UNSIGNED NOT NULL DEFAULT '1',
`password_last_change` timestamp NULL DEFAULT NULL,
`blocked` varchar(1204) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `users_remembered`
--
CREATE TABLE IF NOT EXISTS `users_remembered` (
`id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
`user` int(10) UNSIGNED NOT NULL,
`selector` varchar(24) COLLATE utf8mb4_unicode_ci NOT NULL,
`token` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`expires` int(10) UNSIGNED NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `selector` (`selector`),
KEY `user` (`user`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `users_resets`
--
CREATE TABLE IF NOT EXISTS `users_resets` (
`id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
`user` int(10) UNSIGNED NOT NULL,
`selector` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL,
`token` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`expires` int(10) UNSIGNED NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `selector` (`selector`),
KEY `user_expires` (`user`,`expires`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `users_school`
--
CREATE TABLE IF NOT EXISTS `users_school` (
`id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`user` int(10) UNSIGNED NOT NULL,
`school` int(10) UNSIGNED NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `users_throttling`
--
CREATE TABLE IF NOT EXISTS `users_throttling` (
`bucket` varchar(44) COLLATE utf8mb4_unicode_ci NOT NULL,
`tokens` float UNSIGNED NOT NULL,
`replenished_at` int(10) UNSIGNED NOT NULL,
`expires_at` int(10) UNSIGNED NOT NULL,
PRIMARY KEY (`bucket`),
KEY `expires_at` (`expires_at`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Structure for view `all_users`
--
DROP TABLE IF EXISTS `all_users`;
CREATE VIEW `all_users` AS select `users`.`id` AS `id`,`users`.`email` AS `email`,`users`.`password` AS `password`,`users`.`username` AS `username`,`users`.`status` AS `status`,`users`.`verified` AS `verified`,`users`.`resettable` AS `resettable`,`users`.`roles_mask` AS `roles_mask`,`users`.`registered` AS `registered`,`users`.`last_login` AS `last_login`,`users`.`force_logout` AS `force_logout`,`users_expanded`.`name` AS `name`,`users_expanded`.`surname` AS `surname`,`users_expanded`.`profile_picture` AS `profile_picture`,`users_expanded`.`wallpaper` AS `wallpaper`,`users_expanded`.`taskbar` AS `taskbar`,`users_expanded`.`type` AS `type`,`users_expanded`.`accent` AS `accent`,`users_expanded`.`theme` AS `theme`,`users_expanded`.`plan` AS `plan`,`users_expanded`.`twofa` AS `twofa`,`users_expanded`.`privacy_search_visible` AS `privacy_search_visible`,`users_expanded`.`privacy_show_email` AS `privacy_show_email`,`users_expanded`.`privacy_show_username` AS `privacy_show_username`,`users_expanded`.`privacy_send_messages` AS `privacy_send_messages`,`users_expanded`.`privacy_ms_office` AS `privacy_ms_office`,`users_expanded`.`privacy_share_documents` AS `privacy_share_documents`,`users_expanded`.`password_last_change` AS `password_last_change`,`users_expanded`.`blocked` AS `blocked`,`users_expanded`.`taskbar_size` AS `taskbar_size` from (`users` join `users_expanded` on((`users`.`id` = `users_expanded`.`id`))) ;
-- --------------------------------------------------------
--
-- Structure for view `desktop`
--
DROP TABLE IF EXISTS `desktop`;
CREATE VIEW `desktop` AS select `file`.`user_id` AS `user_id`,`file`.`id` AS `id`,`file`.`name` AS `name`,`file`.`type` AS `type`,NULL AS `surname`,`file`.`diary_type` AS `diary_type`,`file`.`diary_priority` AS `diary_priority`,`file`.`diary_date` AS `diary_date`,`file`.`diary_color` AS `diary_color`,`file`.`icon` AS `icon`,NULL AS `username`,`file`.`file_url` AS `file_url`,`file`.`file_type` AS `file_type`,`file`.`deleted` AS `deleted` from `file` where ((`file`.`fav` = 1) and isnull(`file`.`history`) and (`file`.`trash` = 0)) union select `contact`.`user_id` AS `user_id`,`contact`.`id` AS `id`,`contact`.`name` AS `name`,'contact' AS `type`,`contact`.`surname` AS `surname`,NULL AS `diary_type`,NULL AS `diary_priority`,NULL AS `diary_date`,NULL AS `diary_color`,`users_expanded`.`profile_picture` AS `icon`,`users`.`username` AS `username`,NULL AS `file_url`,NULL AS `file_type`,`contact`.`deleted` AS `deleted` from ((`contact` join `users_expanded`) join `users`) where ((`contact`.`fav` = 1) and (`contact`.`contact_id` = `users_expanded`.`id`) and (`users_expanded`.`id` = `users`.`id`)) ;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
| 35.730552 | 1,430 | 0.643675 |
32717dd65faed04c77fc46d99ced99d0429f1bcc | 1,468 | kt | Kotlin | app/src/main/java/com/android/photoalbum/repository/db/PhotosDao.kt | zaidbintariq89/PhotoAlbum | 280c939cd356d920a32232afe9e03756dca63fdc | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/android/photoalbum/repository/db/PhotosDao.kt | zaidbintariq89/PhotoAlbum | 280c939cd356d920a32232afe9e03756dca63fdc | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/android/photoalbum/repository/db/PhotosDao.kt | zaidbintariq89/PhotoAlbum | 280c939cd356d920a32232afe9e03756dca63fdc | [
"Apache-2.0"
] | null | null | null | package com.android.photoalbum.repository.db
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.room.*
import com.android.photoalbum.model.AlbumsDetails
import com.android.photoalbum.model.PhotosModel
import com.android.photoalbum.utils.RoomConfig
@Dao
interface PhotosDao {
@Insert
fun insertAllPhotoAlbums(photos: List<PhotosModel>)
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertAnAlbum(album: PhotosModel)
@Query(RoomConfig.SELECT_ALL_PHOTOS)
fun getAll(): LiveData<List<PhotosModel>>
// for Testing purpose
@Query(RoomConfig.SELECT_ALL_PHOTOS)
fun getAllAlbums(): List<PhotosModel>
@Query("SELECT * FROM photos WHERE albumId = :photoId")
fun loadAllAlbumsByIds(photoId: Int): List<PhotosModel>
@Query("SELECT DISTINCT albumId FROM photos")
fun getDistinctAlbumIds(): IntArray
@Delete
fun delete(album: PhotosModel)
@Query("DELETE FROM photos")
fun deleteAll()
@Transaction
fun updateContentsInDb(photos: List<PhotosModel>) {
deleteAll()
insertAllPhotoAlbums(photos)
}
@Transaction
fun getAlbumsByGroup(): List<AlbumsDetails> {
val listAlbums = ArrayList<AlbumsDetails>()
val albumIds = getDistinctAlbumIds()
albumIds.forEach {
val list = loadAllAlbumsByIds(it)
listAlbums.add(AlbumsDetails(it, list))
}
return listAlbums
}
} | 26.690909 | 59 | 0.712534 |
1438695bebf00e33d0c58992a9e1ca505487dfe7 | 465 | css | CSS | src/styles/session/companies.module.css | semanadeinformatica/website-2020 | 961ed1ad329e561d01efeeef2c1710b77b9c3d3e | [
"MIT"
] | 1 | 2019-07-02T18:09:39.000Z | 2019-07-02T18:09:39.000Z | src/styles/session/companies.module.css | semanadeinformatica/website-2019 | 6e0f73a7dcbfb9b7e148b1be7f9c3bad34be27e2 | [
"MIT"
] | 23 | 2019-07-05T15:12:26.000Z | 2022-02-26T17:43:57.000Z | src/styles/session/companies.module.css | semanadeinformatica/website-2020 | 961ed1ad329e561d01efeeef2c1710b77b9c3d3e | [
"MIT"
] | null | null | null | @import url("../common/palette.css");
.companiesContainer {
border-top: 1px solid #cecece;
border-bottom: 1px solid #cecece;
margin-bottom: 40px;
}
.companiesRow {
text-align: center;
padding: 40px 0;
align-items: center;
}
@media screen and (max-width: 767px) {
.companiesRow {
text-align: center;
padding-top: 100px;
padding-bottom: 0;
align-items: center;
}
.companiesContainer .companyLogo {
margin-bottom: 100px;
}
}
| 17.884615 | 38 | 0.662366 |
b1d7c2488ff332cfc3de1e39f6d4f3822ac68257 | 6,811 | c | C | qemu/hw/rx/rx-gdbsim.c | hyunjoy/scripts | 01114d3627730d695b5ebe61093c719744432ffa | [
"Apache-2.0"
] | 44 | 2022-03-16T08:32:31.000Z | 2022-03-31T16:02:35.000Z | qemu/hw/rx/rx-gdbsim.c | hyunjoy/scripts | 01114d3627730d695b5ebe61093c719744432ffa | [
"Apache-2.0"
] | 1 | 2022-03-29T02:30:28.000Z | 2022-03-30T03:40:46.000Z | qemu/hw/rx/rx-gdbsim.c | hyunjoy/scripts | 01114d3627730d695b5ebe61093c719744432ffa | [
"Apache-2.0"
] | 18 | 2022-03-19T04:41:04.000Z | 2022-03-31T03:32:12.000Z | /*
* RX QEMU GDB simulator
*
* Copyright (c) 2019 Yoshinori Sato
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2 or later, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "qemu/osdep.h"
#include "qemu/cutils.h"
#include "qemu/error-report.h"
#include "qapi/error.h"
#include "qemu-common.h"
#include "cpu.h"
#include "hw/hw.h"
#include "hw/sysbus.h"
#include "hw/loader.h"
#include "hw/rx/rx62n.h"
#include "sysemu/sysemu.h"
#include "sysemu/qtest.h"
#include "sysemu/device_tree.h"
#include "hw/boards.h"
#include "qom/object.h"
/* Same address of GDB integrated simulator */
#define SDRAM_BASE EXT_CS_BASE
struct RxGdbSimMachineClass {
/*< private >*/
MachineClass parent_class;
/*< public >*/
const char *mcu_name;
uint32_t xtal_freq_hz;
};
typedef struct RxGdbSimMachineClass RxGdbSimMachineClass;
struct RxGdbSimMachineState {
/*< private >*/
MachineState parent_obj;
/*< public >*/
RX62NState mcu;
};
typedef struct RxGdbSimMachineState RxGdbSimMachineState;
#define TYPE_RX_GDBSIM_MACHINE MACHINE_TYPE_NAME("rx62n-common")
DECLARE_OBJ_CHECKERS(RxGdbSimMachineState, RxGdbSimMachineClass,
RX_GDBSIM_MACHINE, TYPE_RX_GDBSIM_MACHINE)
static void rx_load_image(RXCPU *cpu, const char *filename,
uint32_t start, uint32_t size)
{
static uint32_t extable[32];
long kernel_size;
int i;
kernel_size = load_image_targphys(filename, start, size);
if (kernel_size < 0) {
fprintf(stderr, "qemu: could not load kernel '%s'\n", filename);
exit(1);
}
cpu->env.pc = start;
/* setup exception trap trampoline */
/* linux kernel only works little-endian mode */
for (i = 0; i < ARRAY_SIZE(extable); i++) {
extable[i] = cpu_to_le32(0x10 + i * 4);
}
rom_add_blob_fixed("extable", extable, sizeof(extable), VECTOR_TABLE_BASE);
}
static void rx_gdbsim_init(MachineState *machine)
{
MachineClass *mc = MACHINE_GET_CLASS(machine);
RxGdbSimMachineState *s = RX_GDBSIM_MACHINE(machine);
RxGdbSimMachineClass *rxc = RX_GDBSIM_MACHINE_GET_CLASS(machine);
MemoryRegion *sysmem = get_system_memory();
const char *kernel_filename = machine->kernel_filename;
const char *dtb_filename = machine->dtb;
if (machine->ram_size < mc->default_ram_size) {
char *sz = size_to_str(mc->default_ram_size);
error_report("Invalid RAM size, should be more than %s", sz);
g_free(sz);
}
/* Allocate memory space */
memory_region_add_subregion(sysmem, SDRAM_BASE, machine->ram);
/* Initialize MCU */
object_initialize_child(OBJECT(machine), "mcu", &s->mcu, rxc->mcu_name);
object_property_set_link(OBJECT(&s->mcu), "main-bus", OBJECT(sysmem),
&error_abort);
object_property_set_uint(OBJECT(&s->mcu), "xtal-frequency-hz",
rxc->xtal_freq_hz, &error_abort);
object_property_set_bool(OBJECT(&s->mcu), "load-kernel",
kernel_filename != NULL, &error_abort);
if (!kernel_filename) {
if (machine->firmware) {
rom_add_file_fixed(machine->firmware, RX62N_CFLASH_BASE, 0);
} else if (!qtest_enabled()) {
error_report("No bios or kernel specified");
exit(1);
}
}
qdev_realize(DEVICE(&s->mcu), NULL, &error_abort);
/* Load kernel and dtb */
if (kernel_filename) {
ram_addr_t kernel_offset;
/*
* The kernel image is loaded into
* the latter half of the SDRAM space.
*/
kernel_offset = machine->ram_size / 2;
rx_load_image(RX_CPU(first_cpu), kernel_filename,
SDRAM_BASE + kernel_offset, kernel_offset);
if (dtb_filename) {
ram_addr_t dtb_offset;
int dtb_size;
g_autofree void *dtb = load_device_tree(dtb_filename, &dtb_size);
if (dtb == NULL) {
error_report("Couldn't open dtb file %s", dtb_filename);
exit(1);
}
if (machine->kernel_cmdline &&
qemu_fdt_setprop_string(dtb, "/chosen", "bootargs",
machine->kernel_cmdline) < 0) {
error_report("Couldn't set /chosen/bootargs");
exit(1);
}
/* DTB is located at the end of SDRAM space. */
dtb_offset = machine->ram_size - dtb_size;
rom_add_blob_fixed("dtb", dtb, dtb_size,
SDRAM_BASE + dtb_offset);
/* Set dtb address to R1 */
RX_CPU(first_cpu)->env.regs[1] = SDRAM_BASE + dtb_offset;
}
}
}
static void rx_gdbsim_class_init(ObjectClass *oc, void *data)
{
MachineClass *mc = MACHINE_CLASS(oc);
mc->init = rx_gdbsim_init;
mc->default_cpu_type = TYPE_RX62N_CPU;
mc->default_ram_size = 16 * MiB;
mc->default_ram_id = "ext-sdram";
}
static void rx62n7_class_init(ObjectClass *oc, void *data)
{
RxGdbSimMachineClass *rxc = RX_GDBSIM_MACHINE_CLASS(oc);
MachineClass *mc = MACHINE_CLASS(oc);
rxc->mcu_name = TYPE_R5F562N7_MCU;
rxc->xtal_freq_hz = 12 * 1000 * 1000;
mc->desc = "gdb simulator (R5F562N7 MCU and external RAM)";
};
static void rx62n8_class_init(ObjectClass *oc, void *data)
{
RxGdbSimMachineClass *rxc = RX_GDBSIM_MACHINE_CLASS(oc);
MachineClass *mc = MACHINE_CLASS(oc);
rxc->mcu_name = TYPE_R5F562N8_MCU;
rxc->xtal_freq_hz = 12 * 1000 * 1000;
mc->desc = "gdb simulator (R5F562N8 MCU and external RAM)";
};
static const TypeInfo rx_gdbsim_types[] = {
{
.name = MACHINE_TYPE_NAME("gdbsim-r5f562n7"),
.parent = TYPE_RX_GDBSIM_MACHINE,
.class_init = rx62n7_class_init,
}, {
.name = MACHINE_TYPE_NAME("gdbsim-r5f562n8"),
.parent = TYPE_RX_GDBSIM_MACHINE,
.class_init = rx62n8_class_init,
}, {
.name = TYPE_RX_GDBSIM_MACHINE,
.parent = TYPE_MACHINE,
.instance_size = sizeof(RxGdbSimMachineState),
.class_size = sizeof(RxGdbSimMachineClass),
.class_init = rx_gdbsim_class_init,
.abstract = true,
}
};
DEFINE_TYPES(rx_gdbsim_types)
| 32.903382 | 79 | 0.634709 |
65d6de92d4a70452000d8ed3126ad9dc67ce41fb | 3,753 | swift | Swift | EnumWindows/Windows.swift | mandrigin/AlfredSwitchWindows | cfff58a0da8b533826275661f5103ff2f173ae05 | [
"Unlicense"
] | 328 | 2017-02-22T19:05:54.000Z | 2022-03-18T20:08:55.000Z | EnumWindows/Windows.swift | xcodebuild/cerebro-mac-switch-window | a993db8c756b4e6263da0dd4926a9faac6b3898d | [
"MIT"
] | 41 | 2017-02-18T12:28:23.000Z | 2022-02-12T02:38:20.000Z | EnumWindows/Windows.swift | xcodebuild/cerebro-mac-switch-window | a993db8c756b4e6263da0dd4926a9faac6b3898d | [
"MIT"
] | 36 | 2017-07-21T20:20:21.000Z | 2022-02-14T21:08:25.000Z | import Foundation
class WindowInfoDict : Searchable, ProcessNameProtocol {
private let windowInfoDict : Dictionary<NSObject, AnyObject>;
init(rawDict : UnsafeRawPointer) {
windowInfoDict = unsafeBitCast(rawDict, to: CFDictionary.self) as Dictionary
}
var name : String {
return self.dictItem(key: "kCGWindowName", defaultValue: "")
}
var hasName : Bool {
return self.windowInfoDict["kCGWindowName" as NSObject] != nil
}
var windowTitle: String {
return self.name
}
var number: UInt32 {
return self.dictItem(key: "kCGWindowNumber", defaultValue: 0)
}
var processName : String {
return self.dictItem(key: "kCGWindowOwnerName", defaultValue: "")
}
var appName : String {
return self.dictItem(key: "kCGWindowOwnerName", defaultValue: "")
}
var pid : Int {
return self.dictItem(key: "kCGWindowOwnerPID", defaultValue: -1)
}
var bounds : CGRect {
let dict = self.dictItem(key: "kCGWindowBounds", defaultValue: NSDictionary())
guard let bounds = CGRect.init(dictionaryRepresentation: dict) else {
return CGRect.zero
}
return bounds
}
var alpha : Float {
return self.dictItem(key: "kCGWindowAlpha", defaultValue: 0.0)
}
var tabIndex: Int {
return 0
}
func dictItem<T>(key : String, defaultValue : T) -> T {
guard let value = windowInfoDict[key as NSObject] as? T else {
return defaultValue
}
return value
}
static func == (lhs: WindowInfoDict, rhs: WindowInfoDict) -> Bool {
return lhs.processName == rhs.processName && lhs.name == rhs.name
}
var hashValue: Int {
return "\(self.processName)-\(self.name)".hashValue
}
var searchStrings: [String] {
return [self.processName, self.name]
}
var isProbablyMenubarItem : Bool {
// Our best guess, if it's very small and attached to the top of the screen, it is probably something
// related to the menubar
return self.bounds.minY <= 0 || self.bounds.height < 30
}
var isVisible : Bool {
return self.alpha > 0
}
}
struct Windows {
static var any : WindowInfoDict? {
get {
guard let wl = CGWindowListCopyWindowInfo([.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID) else {
return nil
}
return (0..<CFArrayGetCount(wl)).flatMap { (i : Int) -> [WindowInfoDict] in
guard let windowInfoRef = CFArrayGetValueAtIndex(wl, i) else {
return []
}
let wi = WindowInfoDict(rawDict: windowInfoRef)
return [wi]
}.first
}
}
static var all : [WindowInfoDict] {
get {
guard let wl = CGWindowListCopyWindowInfo([.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID) else {
return []
}
return (0..<CFArrayGetCount(wl)).flatMap { (i : Int) -> [WindowInfoDict] in
guard let windowInfoRef = CFArrayGetValueAtIndex(wl, i) else {
return []
}
let wi = WindowInfoDict(rawDict: windowInfoRef)
// We don't want to clutter our output with unnecessary windows that we can't switch to anyway.
guard wi.name.characters.count > 0 && !wi.isProbablyMenubarItem && wi.isVisible else {
return []
}
return [wi]
}
}
}
}
| 30.024 | 125 | 0.56195 |
47db574043c31e4395146924ebd99628ff5ead26 | 6,998 | dart | Dart | lib/pages/sign_up/sign_up_page.dart | ricarthlima/flutter-ahead-gymapp-dotcode | 42f7ada99d0c7c128be0be7f65fed5d303d1115a | [
"MIT"
] | 1 | 2021-08-02T12:01:15.000Z | 2021-08-02T12:01:15.000Z | lib/pages/sign_up/sign_up_page.dart | ricarthlima/flutter-ahead-gymapp-dotcode | 42f7ada99d0c7c128be0be7f65fed5d303d1115a | [
"MIT"
] | null | null | null | lib/pages/sign_up/sign_up_page.dart | ricarthlima/flutter-ahead-gymapp-dotcode | 42f7ada99d0c7c128be0be7f65fed5d303d1115a | [
"MIT"
] | null | null | null | import 'package:flutter/material.dart';
import 'package:gym_app/pages/shared_widgets/dialogs.dart';
import 'package:gym_app/pages/sign_up/sign_up_service.dart';
import 'package:gym_app/shared/constants/custom_colors.dart';
class SignUpPage extends StatefulWidget {
@override
_SignUpPageState createState() => _SignUpPageState();
}
class _SignUpPageState extends State<SignUpPage> {
TextEditingController _nameInputController = TextEditingController();
TextEditingController _mailInputController = TextEditingController();
TextEditingController _passwordInputController = TextEditingController();
TextEditingController _confirmInputController = TextEditingController();
bool showPassword = false;
final _formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return Container(
height: MediaQuery.of(context).size.height * 0.9,
padding: EdgeInsets.symmetric(horizontal: 40, vertical: 30),
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Colors.white,
CustomColors().getGradientSecondaryColor(),
],
),
),
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
"Cadastre-se! É de graça ;)",
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
Padding(
padding: EdgeInsets.only(bottom: 10),
),
Form(
key: _formKey,
child: Column(
children: [
TextFormField(
validator: (value) {
if (value!.length < 10) {
return "Digite um nome maior";
}
return null;
},
controller: _nameInputController,
autofocus: true,
decoration: InputDecoration(
labelText: "Nome Completo",
prefixIcon: Icon(
Icons.person,
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(),
),
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(),
),
),
),
TextFormField(
validator: (value) {
if (value!.length < 5) {
return "Esse e-mail parece curto demais";
} else if (!value.contains("@")) {
return "Esse e-mail está meio estranho, não?";
}
return null;
},
controller: _mailInputController,
autofocus: true,
decoration: InputDecoration(
labelText: "E-mail",
labelStyle: TextStyle(),
prefixIcon: Icon(
Icons.mail_outline,
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(),
),
enabledBorder: UnderlineInputBorder(),
),
),
Padding(
padding: EdgeInsets.only(
bottom: 15,
),
),
TextFormField(
validator: (value) {
if (value!.length < 6) {
return "A senha deve ter pelo menos 6 caracteres";
}
return null;
},
controller: _passwordInputController,
obscureText: (this.showPassword == true) ? false : true,
decoration: InputDecoration(
labelText: "Senha",
labelStyle: TextStyle(),
prefixIcon: Icon(
Icons.vpn_key_sharp,
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(),
),
enabledBorder: UnderlineInputBorder(),
),
),
(this.showPassword == false)
? TextFormField(
validator: (value) {
if (value != _passwordInputController.text) {
return "As senhas devem ser iguais";
}
return null;
},
controller: _confirmInputController,
obscureText: true,
decoration: InputDecoration(
labelText: "Confirme a Senha",
prefixIcon: Icon(
Icons.vpn_key_sharp,
),
),
)
: Container(),
Row(
children: [
Checkbox(
value: this.showPassword,
onChanged: (bool? newValue) {
setState(() {
this.showPassword = newValue!;
});
},
activeColor: Colors.blue,
),
Text(
"Mostrar senha",
)
],
),
],
),
),
// ignore: deprecated_member_use
RaisedButton(
onPressed: () {
_doSignUp();
},
child: Text("Casdastrar"),
color: CustomColors().getActiveSecondaryButton(),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50),
),
),
],
),
),
);
}
void _doSignUp() {
if (_formKey.currentState!.validate()) {
SignUpService().signUp(
context,
_nameInputController.text,
_mailInputController.text,
_passwordInputController.text,
);
} else {
showDialog(
context: context,
builder: (context) {
return ErrorDialog(
message: "Há erros no seu formulário.",
);
},
);
}
}
}
| 35.165829 | 76 | 0.426122 |
af52ca2e0bf2bdb248efbedf6ef09363109b0808 | 366 | rb | Ruby | Formula/font-yanone-kaffeesatz.rb | mxalbert1996/homebrew-fonts | d3a705771f29804f16ce442f920f2fa161d0bead | [
"BSD-2-Clause"
] | 17 | 2019-01-19T16:32:34.000Z | 2022-03-30T23:13:32.000Z | Formula/font-yanone-kaffeesatz.rb | mxalbert1996/homebrew-fonts | d3a705771f29804f16ce442f920f2fa161d0bead | [
"BSD-2-Clause"
] | 25 | 2019-01-11T23:53:24.000Z | 2022-03-29T03:15:18.000Z | Formula/font-yanone-kaffeesatz.rb | mxalbert1996/homebrew-fonts | d3a705771f29804f16ce442f920f2fa161d0bead | [
"BSD-2-Clause"
] | 11 | 2019-03-08T22:58:06.000Z | 2021-12-20T01:11:06.000Z | class FontYanoneKaffeesatz < Formula
head "https://github.com/google/fonts/raw/main/ofl/yanonekaffeesatz/YanoneKaffeesatz%5Bwght%5D.ttf", verified: "github.com/google/fonts/"
desc "Yanone Kaffeesatz"
homepage "https://fonts.google.com/specimen/Yanone+Kaffeesatz"
def install
(share/"fonts").install "YanoneKaffeesatz[wght].ttf"
end
test do
end
end
| 33.272727 | 139 | 0.759563 |
7a3f3d18f3a5d81f9b4c8a4f125a2737012f46d4 | 1,084 | rs | Rust | src/command.rs | euclio/cargo-msrv | 893011b291ecbd1211b384dbb92c6c615b99169a | [
"Apache-2.0",
"MIT"
] | 148 | 2020-08-25T21:07:25.000Z | 2022-03-22T02:38:32.000Z | src/command.rs | euclio/cargo-msrv | 893011b291ecbd1211b384dbb92c6c615b99169a | [
"Apache-2.0",
"MIT"
] | 265 | 2019-10-02T23:30:34.000Z | 2022-03-31T22:44:59.000Z | src/command.rs | euclio/cargo-msrv | 893011b291ecbd1211b384dbb92c6c615b99169a | [
"Apache-2.0",
"MIT"
] | 14 | 2019-10-03T07:50:06.000Z | 2022-02-24T01:43:19.000Z | use crate::errors::TResult;
use std::ffi::OsStr;
use std::path::Path;
use std::process::{Child, Command, Stdio};
pub fn command_with_output<I: IntoIterator<Item = V>, V: AsRef<OsStr>>(
commands: I,
) -> TResult<Child> {
command_impl(commands, None)
.pipe_output()
.spawn()
.map_err(From::from)
}
pub fn command<I: IntoIterator<Item = V>, V: AsRef<OsStr>>(
commands: I,
dir: Option<&Path>,
) -> TResult<Child> {
command_impl(commands, dir)
.pipe_output()
.spawn()
.map_err(From::from)
}
trait PipeCliOutput {
fn pipe_output(&mut self) -> &mut Command;
}
impl PipeCliOutput for Command {
fn pipe_output(&mut self) -> &mut Command {
self.stdout(Stdio::piped());
self.stderr(Stdio::piped())
}
}
fn command_impl<I: IntoIterator<Item = V>, V: AsRef<OsStr>>(
commands: I,
current_dir: Option<&Path>,
) -> Command {
let mut cmd = Command::new("rustup");
let _ = cmd.args(commands);
if let Some(dir) = current_dir {
let _ = cmd.current_dir(dir);
}
cmd
}
| 22.122449 | 71 | 0.602399 |
f079e98b160d8a91575eae2e0aca827d1791d471 | 8,205 | js | JavaScript | ~2017/2014_bsDetect/detect.0.3.js | redcamel/RedRnd | ffd37eb08e945ca0a5ea21dc2e25174739bd5392 | [
"MIT"
] | 1 | 2020-08-19T00:40:02.000Z | 2020-08-19T00:40:02.000Z | ~2017/2014_bsDetect/detect.0.3.js | redcamel/RedRnd | ffd37eb08e945ca0a5ea21dc2e25174739bd5392 | [
"MIT"
] | null | null | null | ~2017/2014_bsDetect/detect.0.3.js | redcamel/RedRnd | ffd37eb08e945ca0a5ea21dc2e25174739bd5392 | [
"MIT"
] | 1 | 2020-08-19T00:40:03.000Z | 2020-08-19T00:40:03.000Z | function DETECT(W, doc){
var platform, app, agent, device,
flash, browser, bVersion, os, osVersion, cssPrefix, stylePrefix, transform3D,
b, bStyle, div, keyframe,
v, a, c;
agent = navigator.userAgent.toLowerCase(),
platform = navigator.platform.toLowerCase(),
app = navigator.appVersion.toLowerCase(),
flash = 0, device = 'pc',
(function(){
var i;
function ie(){
if( agent.indexOf( 'msie' ) < 0 && agent.indexOf( 'trident' ) < 0 ) return;
if( agent.indexOf( 'iemobile' ) > -1 ) os = 'winMobile';
return browser = 'ie', bVersion = agent.indexOf( 'msie' ) < 0 ? 11 : parseFloat( /msie ([\d]+)/.exec( agent )[1] );
}
function chrome(){
var i;
if( agent.indexOf( i = 'chrome' ) < 0 && agent.indexOf( i = 'crios' ) < 0 ) return;
return browser = 'chrome', bVersion = parseFloat( ( i == 'chrome' ? /chrome\/([\d]+)/ : /webkit\/([\d]+)/ ).exec( agent )[1] );
}
function firefox(){
if( agent.indexOf( 'firefox' ) < 0 ) return;
return browser = 'firefox', bVersion = parseFloat( /firefox\/([\d]+)/.exec( agent )[1] );
}
function safari(){
if( agent.indexOf( 'safari' ) < 0 ) return;
return browser = 'safari', bVersion = parseFloat( /version\/([\d]+)/.exec( agent )[1] );
}
function opera(){
var i;
if( agent.indexOf( i = 'opera' ) < 0 && agent.indexOf( i = 'opr' ) < 0 ) return;
return browser = 'opera', bVersion = ( i == 'opera' ) ? parseFloat( /version\/([\d]+)/.exec( agent )[1] ) : parseFloat( /opr\/([\d]+)/.exec(agent)[1] );
}
function naver(){if( agent.indexOf( 'naver' ) > -1 ) return browser = 'naver';}
if( agent.indexOf( 'android' ) > -1 ){
browser = os = 'android';
if( agent.indexOf( 'mobile' ) == -1 ) browser += 'Tablet', device = 'tablet';
else device = 'mobile';
i = /android ([\d.]+)/.exec( agent );
if( i ) i = i[1].split('.'), osVersion = parseFloat( i[0] + '.' + i[1] );
else osVersion = 0;
i = /version\/([\d.]+)/.exec( agent );
if( i ) bVersion = parseFloat( i[1] );
naver() || opera() || chrome() || firefox();
}else if( agent.indexOf( i = 'ipad' ) > -1 || agent.indexOf( i = 'iphone' ) > -1 ){
device = i == 'ipad' ? 'tablet' : 'mobile', browser = os = i;
if( i = /os ([\d_]+)/.exec( agent ) ) i = i[1].split('_'), osVersion = parseFloat( i[0] + '.' + i[1] );
else osVersion = 0;
if( i = /version\/([\S]+)/.exec( agent ) ) bVersion = parseFloat( i[1] );
else if( i = /webkit\/([\d]+)/.exec( agent ) ) bVersion = parseFloat( i[1] );
else bVersion = 0;
naver() || opera() || chrome() || firefox() || safari();
}else{
if( platform.indexOf( 'win' ) > -1 ){
os = 'win', i = 'windows nt ';
if( agent.indexOf( i + '5.1' ) > -1 ) osVersion = 'xp';
else if( agent.indexOf( i + '6.0' ) > -1 ) osVersion = 'vista';
else if( agent.indexOf( i + '6.1' ) > -1 ) osVersion = '7';
else if( agent.indexOf( i + '6.2' ) > -1 ) osVersion = '8';
else if( agent.indexOf( i + '6.3' ) > -1 ) osVersion = '8.1';
ie() || opera() || chrome() || firefox() || safari();
}else if( platform.indexOf( 'mac' ) > -1 ){
os = 'mac';
i = /os x ([\d._]+)/.exec(agent)[1].replace( '_', '.' ).split('.');
osVersion = parseFloat( i[0] + '.' + i[1] );
opera() || chrome() || firefox() || safari();
}else{
os = app.indexOf( 'x11' ) > -1 ? 'unix' : app.indexOf( 'linux' ) > -1 ? 'linux' : 0;
osVersion = 0;
chrome() || firefox();
}
}
})(),
(function(){
var plug, t0;
plug = navigator.plugins;
if( browser == 'ie' ) try{t0 = new ActiveXObject( 'ShockwaveFlash.ShockwaveFlash' ).GetVariable( '$version' ).substr( 4 ).split( ',' ), flash = parseFloat( t0[0] + '.' + t0[1] );}catch( e ){}
else if( ( t0 = plug['Shockwave Flash 2.0'] ) || ( t0 = plug['Shockwave Flash'] ) ) t0 = t0.description.split( ' ' )[2].split( '.' ), flash = parseFloat( t0[0] + '.' + t0[1] );
else if( agent.indexOf( 'webtv' ) > -1 ) flash = agent.indexOf( 'webtv/2.6' ) > -1 ? 4 : agent.indexOf("webtv/2.5") > -1 ? 3 : 2;
})(),
b = doc.body, bStyle = b.style, div = doc.createElement( 'div' ),
div.innerHTML = '<div style="opacity:.55;position:fixed;top:100px;visibility:hidden;-webkit-overflow-scrolling:touch">a</div>',
div = div.getElementsByTagName( 'div' )[0],
c = doc.createElement( 'canvas' ), c = 'getContext' in c ? c : null,
a = doc.createElement( 'audio' ), a = 'canPlayType' in a ? a : null,
v = doc.createElement( 'video' ), v = 'canPlayType' in v ? v : null;
switch( browser ){
case'ie': cssPrefix = '-ms-', stylePrefix = 'ms'; transform3D = bVersion > 9 ? 1 : 0;
if( bVersion == 6 ) doc.execCommand( 'BackgroundImageCache', false, true ), b.style.position = 'relative';
break;
case'firefox': cssPrefix = '-moz-', stylePrefix = 'Moz'; transform3D = 1; break;
case'opera': cssPrefix = '-o-', stylePrefix = 'O'; transform3D = 0; break;
default: cssPrefix = '-webkit-', stylePrefix = 'webkit'; transform3D = os == 'android' ? ( osVersion < 4 ? 0 : 1 ) : 0;
}
if( keyframe = W['CSSRule'] ){
if( keyframe.WEBKIT_KEYFRAME_RULE ) keyframe = '-webkit-keyframes';
else if( keyframe.MOZ_KEYFRAME_RULE ) keyframe = '-moz-keyframes';
else if( keyframe.KEYFRAME_RULE ) keyframe = 'keyframes';
else keyframe = null;
}
return {
'device':device, 'browser':browser, 'browserVer':bVersion, 'os':os, 'osVer':osVersion, 'flash':flash, 'sony':agent.indexOf( 'sony' ) > -1 ? 1 : 0,
//dom
root:b.scrollHeight ? b : doc.documentElement,
scroll:doc.documentElement && typeof doc.documentElement.scrollLeft == 'number' ? 'scroll' : 'page',
insertBefore:div.insertBefore ? 1 : 0, png:( browser == 'ie' && bVersion > 7 ) ? 1 : 0,
opacity:div.style.opacity == '0.55' ? 1 : 0, text:div.textContent ? 'textContent' : div.innerText ? 'innerText' : 'innerHTML',
cstyle:( doc.defaultView && doc.defaultView.getComputedStyle ) ? 1 : 0,
//css3
cssPrefix:cssPrefix, stylePrefix:stylePrefix, filterFix:browser == 'ie' && bVersion == 8 ? ';-ms-' : ';',
transition:( stylePrefix + 'Transition' in bStyle || 'transition' in bStyle ) ? 1 : 0, transform3D:transform3D, keyframe:keyframe ? 1 : 0,
transform:stylePrefix + ('Transform' in bStyle || 'transform' in bStyle ) ? 1 : 0,
//html5
canvas:c ? 1 : 0, canvasText:( c && c.getContext('2d').fillText ) ? 1 : 0,
audio:a ? 1 : 0,
audioMp3:a && a.canPlayType('audio/mpeg;').indexOf('no') < 0 ? 1 : 0,
audioOgg:a && a.canPlayType('audio/ogg;').indexOf('no') < 0 ? 1 : 0,
audioWav:a && a.canPlayType('audio/wav;').indexOf('no') < 0 ? 1 : 0,
audioMp4:a && a.canPlayType('audio/mp4;').indexOf('no') < 0 ? 1 : 0,
video:v ? 1 : 0,
videoCaption:'track' in doc.createElement('track') ? 1 : 0,
videoPoster:v && 'poster' in v ? 1 : 0,
videoWebm:v && v.canPlayType( 'video/webm; codecs="vp8,mp4a.40.2"' ).indexOf( 'no' ) == -1 ? 1 : 0,
videH264:v && v.canPlayType( 'video/mp4; codecs="avc1.42E01E,m4a.40.2"' ).indexOf( 'no' ) == -1 ? 1 : 0,
videoTeora:v && v.canPlayType( 'video/ogg; codecs="theora,vorbis"' ).indexOf( 'no' ) == -1 ? 1 : 0,
local:( W.localStorage && 'setItem' in localStorage ) ? 1 : 0,
geo:( navigator.geolocation ) ? 1 : 0, worker:W.Worker ? 1 : 0, file:W.FileReader ? 1 : 0, message:W.postMessage ? 1 : 0,
history:( 'pushState' in history ) ? 1 : 0, offline:W.applicationCache ? 1 : 0,
db:W.openDatabase ? 1 : 0, socket:W.WebSocket ? 1 : 0
};
} | 62.159091 | 199 | 0.520049 |
22df2352a8c7df58c16f7cd011838934505331eb | 751 | kt | Kotlin | plugins/analysis/common/src/main/kotlin/arrow/meta/plugins/analysis/phases/analysis/solver/ast/context/descriptors/ClassDescriptor.kt | lidonis/arrow-meta | c0dc0551926f9693fc64a95865c74a2b2e0af1e6 | [
"Apache-2.0"
] | null | null | null | plugins/analysis/common/src/main/kotlin/arrow/meta/plugins/analysis/phases/analysis/solver/ast/context/descriptors/ClassDescriptor.kt | lidonis/arrow-meta | c0dc0551926f9693fc64a95865c74a2b2e0af1e6 | [
"Apache-2.0"
] | null | null | null | plugins/analysis/common/src/main/kotlin/arrow/meta/plugins/analysis/phases/analysis/solver/ast/context/descriptors/ClassDescriptor.kt | lidonis/arrow-meta | c0dc0551926f9693fc64a95865c74a2b2e0af1e6 | [
"Apache-2.0"
] | null | null | null | package arrow.meta.plugins.analysis.phases.analysis.solver.ast.context.descriptors
interface ClassDescriptor : DeclarationDescriptor, ClassifierDescriptorWithTypeParameters {
fun getUnsubstitutedMemberScope(): MemberScope
val constructors: Collection<ConstructorDescriptor>
val companionObjectDescriptor: ClassDescriptor?
val kind: ClassKind
val isCompanionObject: Boolean
val isData: Boolean
val isInline: Boolean
val isFun: Boolean
val isValue: Boolean
val thisAsReceiverParameter: ReceiverParameterDescriptor
val unsubstitutedPrimaryConstructor: ConstructorDescriptor?
val sealedSubclasses: Collection<ClassDescriptor>
enum class ClassKind {
CLASS, INTERFACE, ENUM_CLASS, ENUM_ENTRY, ANNOTATION_CLASS, OBJECT
}
}
| 34.136364 | 91 | 0.825566 |
7147f507975c495d71f68dd8da06595e33417a74 | 576 | ts | TypeScript | clients/node/client-codedeploy-node/types/_GitHubLocation.ts | pravgupt/aws-sdk-js-v3 | 1fd0fab5da141d934eb98624d6c23b347806bb47 | [
"Apache-2.0"
] | null | null | null | clients/node/client-codedeploy-node/types/_GitHubLocation.ts | pravgupt/aws-sdk-js-v3 | 1fd0fab5da141d934eb98624d6c23b347806bb47 | [
"Apache-2.0"
] | null | null | null | clients/node/client-codedeploy-node/types/_GitHubLocation.ts | pravgupt/aws-sdk-js-v3 | 1fd0fab5da141d934eb98624d6c23b347806bb47 | [
"Apache-2.0"
] | null | null | null | /**
* <p>Information about the location of application artifacts stored in GitHub.</p>
*/
export interface _GitHubLocation {
/**
* <p>The GitHub account and repository pair that stores a reference to the commit that represents the bundled artifacts for the application revision. </p> <p>Specified as account/repository.</p>
*/
repository?: string;
/**
* <p>The SHA1 commit ID of the GitHub commit that represents the bundled artifacts for the application revision.</p>
*/
commitId?: string;
}
export type _UnmarshalledGitHubLocation = _GitHubLocation;
| 33.882353 | 197 | 0.734375 |
75bbe8c96fbc2600b73bf98d8dabd15e5d5f29bb | 10,238 | dart | Dart | lib/lists/AboutView.dart | babanomania/CleanToDO | 62ac2b6fabb5ed28f8656ffcb9bfe870473b675f | [
"Apache-2.0"
] | 14 | 2018-05-05T21:52:25.000Z | 2019-02-14T02:30:46.000Z | lib/lists/AboutView.dart | clean-apps/CleanToDO | 62ac2b6fabb5ed28f8656ffcb9bfe870473b675f | [
"Apache-2.0"
] | 18 | 2018-05-08T00:16:25.000Z | 2018-07-07T08:37:12.000Z | lib/lists/AboutView.dart | babanomania/CleanToDO | 62ac2b6fabb5ed28f8656ffcb9bfe870473b675f | [
"Apache-2.0"
] | 5 | 2018-06-02T00:47:48.000Z | 2018-12-03T14:17:30.000Z | import 'package:flutter/material.dart';
import 'package:clean_todo/data/DataCache.dart';
import 'package:clean_todo/settings/SettingsManager.dart';
import 'package:clean_todo/settings/LoginScreen.dart';
import 'package:clean_todo/styles/AppIcons.dart';
import 'package:clean_todo/settings/Themes.dart';
import 'package:clean_todo/main.dart';
class AboutView extends StatefulWidget {
String appVersion = "1.4.201806230";
DataCache cache;
SettingsManager settings;
AboutView({ this.cache, this.settings,});
@override
_AboutViewState createState() => new _AboutViewState();
}
class _AboutViewState extends State<AboutView> {
_doFixCounts(){
widget.cache.reset_category_counts()
.whenComplete(
() => showDialog(
context: context,
builder: (_) => new AlertDialog(
content: new Text('sidebar list counts\' re-calculation done'),
actions: <Widget>[
new FlatButton(
onPressed: () => Navigator.pop(_),
child: new Text( "OK" )
)
],
),
)
);
}
_updateShowCompletedTasks(value){
this.setState( () {
widget.cache.showCompletedTasks = value;
widget.settings.showCompleted = value;
});
}
_showSortListView(){
String sortString = widget.cache.sortTasks;
return showModalBottomSheet<void>(
context: context,
builder: (BuildContext context){
return new ListView (
children: <Widget>[
new ListTile(
title: new Text( 'Sort Tasks', style: new TextStyle( fontSize: 20.0 ), ),
),
new ListTile(
leading: new Icon( Icons.sort_by_alpha ),
title: new Text( 'Albhabetically' ),
onTap: ((){
this.updateSortTasks('SORT_BY_ALPHA');
Navigator.pop(context);
}),
trailing: sortString == 'SORT_BY_ALPHA' ? new Icon( Icons.check ) : null,
),
new ListTile(
leading: new Icon( Icons.date_range ),
title: new Text( 'Due Date' ),
onTap: ((){
this.updateSortTasks('SORT_BY_DUE');
Navigator.pop(context);
}),
trailing: sortString == 'SORT_BY_DUE' ? new Icon( Icons.check ) : null,
),
new ListTile(
leading: new Icon( Icons.add_circle_outline ),
title: new Text( 'Creation Date' ),
onTap: ((){
this.updateSortTasks('SORT_BY_CREA');
Navigator.pop(context);
}),
trailing: sortString == 'SORT_BY_CREA' ? new Icon( Icons.check ) : null,
),
new ListTile(
leading: new Icon( Icons.check ),
title: new Text( 'Completed' ),
onTap: ((){
this.updateSortTasks('SORT_BY_COMPLETED');
Navigator.pop(context);
}),
trailing: sortString == 'SORT_BY_COMPLETED' ? new Icon( Icons.check ) : null,
),
],
);
//return ;
}
);
}
updateSortTasks(value){
this.setState((){
widget.cache.sortTasks = value;
widget.settings.sortString = value;
});
}
_updateColor(value) {
this.setState(() {
widget.settings.theme = value;
});
runApp(
new CleanToDoApp(
cache: widget.cache,
settings: widget.settings,
),
);
}
IconButton colorIcon( Color btnColor, AppColors color, context ){
String themeColor = widget.settings.theme == null ? 'blue' : widget.settings.theme;
return new IconButton(
icon: new CircleAvatar(
backgroundColor: btnColor,
minRadius: 40.0,
child: color.index.toString() == themeColor ? new Icon( Icons.check, size: 30.0,) : null,
),
iconSize: 75.0,
onPressed: () => _updateColor(color.index.toString())
);
}
_showColorPopup(){
showModalBottomSheet<void>(
context: context,
builder: (BuildContext context){
return new ListView (
children: <Widget>[
new ListTile(
title: new Text( 'Select New Color', style: new TextStyle( fontSize: 20.0 ), ),
),
new ListTile(
title: new Row(
children: <Widget>[
colorIcon(Colors.blue, AppColors.BLUE, context),
colorIcon(Colors.indigo, AppColors.INDIGO, context),
colorIcon(Colors.cyan, AppColors.CYAN, context),
colorIcon(Colors.teal, AppColors.TEAL, context),
],
),
),
new ListTile(
title: new Row(
children: <Widget>[
colorIcon(Colors.brown, AppColors.BROWN, context),
colorIcon(Colors.purple, AppColors.PURPLE, context),
colorIcon(Colors.deepPurple, AppColors.DEEP_PURPLE, context),
colorIcon(Colors.amber, AppColors.AMBER, context),
],
),
),
new ListTile(
title: new Row(
children: <Widget>[
colorIcon(Colors.red, AppColors.RED, context),
colorIcon(Colors.pink, AppColors.PINK, context),
colorIcon(Colors.blueGrey, AppColors.BLUE_GREY, context),
colorIcon(Colors.black, AppColors.BLACK, context),
],
),
),
],
);
//return ;
}
);
}
@override
Widget build(BuildContext context) {
AppIcons icons = new AppIcons();
DataCache cacheN = widget.cache;
SettingsManager settingsN = widget.settings;
bool isShowCompletedTasks = cacheN.showCompletedTasks ;
bool isEnableNotificationSounds = settingsN.notification_sounds;
bool isEnableNotificationVibrations = settingsN.notification_vibrations;
return new Scaffold(
appBar: new AppBar(
title: new Text( 'About' ),
),
body: new ListView(
children: <Widget>[
new Card(
child: new ListTile(
leading: cacheN.userData.abbr == null ?
new Icon( Icons.account_circle ):
new CircleAvatar(
child: new Text( cacheN.userData.abbr, style: new TextStyle( color: Colors.white ), ),
backgroundColor: Theme.of(context).primaryColor,
),
title: new Text( cacheN.userData.userName == null ? 'User Data' : cacheN.userData.userName ),
subtitle: cacheN.userData.email == null ? null : new Text( cacheN.userData.email ),
trailing: new RaisedButton(
color: Colors.red,
child: new Text( "clear", style: new TextStyle( color: Colors.white ), ),
onPressed: ((){
cacheN.clean_all().whenComplete( ((){
cacheN.userData.userName = null;
cacheN.userData.abbr = null;
settingsN.username = null;
runApp(
new LoginScreen(
cache: cacheN,
settings: settingsN,
),
);
}) );
}),
),
),
),
new Card(
child: new Column(
children: <Widget>[
new ListTile(
leading: icons.reCaluclateCountsIcon(context),
title: new Text( "Fix Sidebar Counts" ),
onTap: () => _doFixCounts(),
),
new ListTile(
leading: new Icon( isShowCompletedTasks ? Icons.check_box : Icons.check_box_outline_blank ),
title: new Text( isShowCompletedTasks ? 'Hide Completed Tasks' : 'Show Completed Tasks' ),
onTap: () => _updateShowCompletedTasks( !isShowCompletedTasks ),
),
new ListTile(
leading: new Icon( Icons.sort ),
title: new Text( "Sort" ),
onTap: () => _showSortListView(),
),
new ListTile(
leading: new Icon( Icons.color_lens ),
title: new Text( "Color Scheme" ),
onTap: () => _showColorPopup(),
),
]
),
),
/*
new Card(
child: new Column(
children: <Widget>[
new ListTile(
leading: new Icon( Icons.notifications_active ),
title: new Text( isEnableNotificationSounds ? "Disable Notification Sounds" : "Enable Notification Sounds" ),
onTap: () => this.setState( () => settingsN.notification_sounds = !isEnableNotificationSounds ),
),
new ListTile(
leading: new Icon( Icons.notifications_paused ),
title: new Text( isEnableNotificationVibrations ? "Disable Notification Vibrations" : "Enable Notification Vibrations" ),
onTap: () => this.setState( () => settingsN.notification_vibrations = !isEnableNotificationVibrations ),
),
],
),
),
*/
new Card(
child: new Column(
children: <Widget>[
new ListTile(
title: new Text( "Application Version" ),
subtitle: new Text( settingsN.projectVersion ),
),
]
),
),
],
),
);
}
} | 30.20059 | 141 | 0.492186 |
abf3c6f48520f62bcae8d0141f53bfa50cb8f103 | 320 | go | Go | ds/keystore/keystore.go | r2ishiguro/mls | 554b58f362c78b4e15049c40081e8c118aaaffe1 | [
"Apache-2.0"
] | 13 | 2018-06-02T21:20:55.000Z | 2022-02-04T08:36:56.000Z | ds/keystore/keystore.go | r2ishiguro/mls | 554b58f362c78b4e15049c40081e8c118aaaffe1 | [
"Apache-2.0"
] | null | null | null | ds/keystore/keystore.go | r2ishiguro/mls | 554b58f362c78b4e15049c40081e8c118aaaffe1 | [
"Apache-2.0"
] | null | null | null | // Copyright 2018, Oath Inc
// Licensed under the terms of the Apache 2.0 license. See LICENSE file in https://github.com/r2ishiguro/mls for terms.
package keystore
type KeyStore interface {
Register(id string, key []byte) error
Lookup(id string) ([]byte, error)
Delete(id string) error
List() ([]string, error)
}
| 26.666667 | 119 | 0.728125 |
5803999f362b7378de72cbef805ead84fe383698 | 553 | h | C | samples/client/petstore/objc/SwaggerClient/SWGSanitizer.h | sowderca/swagger-codegen | 3185606124afdd878aae16e34560b01ead8d4141 | [
"Apache-2.0"
] | null | null | null | samples/client/petstore/objc/SwaggerClient/SWGSanitizer.h | sowderca/swagger-codegen | 3185606124afdd878aae16e34560b01ead8d4141 | [
"Apache-2.0"
] | 1 | 2022-02-27T03:23:46.000Z | 2022-02-27T03:23:46.000Z | samples/client/petstore/objc/SwaggerClient/SWGSanitizer.h | sowderca/swagger-codegen | 3185606124afdd878aae16e34560b01ead8d4141 | [
"Apache-2.0"
] | null | null | null | #import <Foundation/Foundation.h>
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
* Do not edit the class manually.
*/
@protocol SWGSanitizer <NSObject>
/**
* Sanitize object for request
*
* @param object The query/path/header/form/body param to be sanitized.
*/
- (id) sanitizeForSerialization:(id) object;
/**
* Convert parameter to NSString
*/
- (NSString *) parameterToString: (id) param;
@end
@interface SWGSanitizer : NSObject <SWGSanitizer>
@end
| 18.433333 | 76 | 0.716094 |
545053e033181780d9d163a83fa4f1f9055e3923 | 2,126 | go | Go | tty.go | srlehn/go-tty | 52a7a459c99d7599633bb3cc5712fac15b0e8a99 | [
"MIT"
] | 16 | 2016-05-13T03:05:51.000Z | 2018-03-14T11:45:31.000Z | vendor/github.com/mattn/go-tty/tty.go | yamamoto-febc/terraform-provider-sakuracloud | a53cc28ed10bb3a6c77ab8140da680ddc7686212 | [
"Apache-2.0"
] | 57 | 2016-05-19T13:14:55.000Z | 2017-05-23T13:43:17.000Z | tty.go | srlehn/go-tty | 52a7a459c99d7599633bb3cc5712fac15b0e8a99 | [
"MIT"
] | 4 | 2016-08-06T13:49:04.000Z | 2016-12-19T12:17:34.000Z | package tty
import (
"os"
"strings"
"unicode"
)
func Open() (*TTY, error) {
return open()
}
func (tty *TTY) Raw() (func() error, error) {
return tty.raw()
}
func (tty *TTY) MustRaw() func() error {
f, err := tty.raw()
if err != nil {
panic(err.Error())
}
return f
}
func (tty *TTY) Buffered() bool {
return tty.buffered()
}
func (tty *TTY) ReadRune() (rune, error) {
return tty.readRune()
}
func (tty *TTY) Close() error {
return tty.close()
}
func (tty *TTY) Size() (int, int, error) {
return tty.size()
}
func (tty *TTY) SizePixel() (int, int, int, int, error) {
return tty.sizePixel()
}
func (tty *TTY) Input() *os.File {
return tty.input()
}
func (tty *TTY) Output() *os.File {
return tty.output()
}
// Display types.
const (
displayNone = iota
displayRune
displayMask
)
func (tty *TTY) readString(displayType int) (string, error) {
rs := []rune{}
loop:
for {
r, err := tty.readRune()
if err != nil {
return "", err
}
switch r {
case 13:
break loop
case 8, 127:
if len(rs) > 0 {
rs = rs[:len(rs)-1]
if displayType != displayNone {
tty.Output().WriteString("\b \b")
}
}
default:
if unicode.IsPrint(r) {
rs = append(rs, r)
switch displayType {
case displayRune:
tty.Output().WriteString(string(r))
case displayMask:
tty.Output().WriteString("*")
}
}
}
}
return string(rs), nil
}
func (tty *TTY) ReadString() (string, error) {
defer tty.Output().WriteString("\n")
return tty.readString(displayRune)
}
func (tty *TTY) ReadPassword() (string, error) {
defer tty.Output().WriteString("\n")
return tty.readString(displayMask)
}
func (tty *TTY) ReadPasswordNoEcho() (string, error) {
defer tty.Output().WriteString("\n")
return tty.readString(displayNone)
}
func (tty *TTY) ReadPasswordClear() (string, error) {
s, err := tty.readString(displayMask)
tty.Output().WriteString(
strings.Repeat("\b", len(s)) +
strings.Repeat(" ", len(s)) +
strings.Repeat("\b", len(s)))
return s, err
}
type WINSIZE struct {
W int
H int
}
func (tty *TTY) SIGWINCH() chan WINSIZE {
return tty.sigwinch()
}
| 17.008 | 61 | 0.619473 |
5ce3588d39690f42e1fbdfc59e009e390598f890 | 4,283 | css | CSS | css/style.css | Saqif280/abubadruddin | 7efa8b9ef98fda9773e054ceab7b7e6ea66cf6bb | [
"MIT"
] | null | null | null | css/style.css | Saqif280/abubadruddin | 7efa8b9ef98fda9773e054ceab7b7e6ea66cf6bb | [
"MIT"
] | null | null | null | css/style.css | Saqif280/abubadruddin | 7efa8b9ef98fda9773e054ceab7b7e6ea66cf6bb | [
"MIT"
] | null | null | null | /* ELEMENT STYLES */
body{
font-family: 'Lato', sans-serif;
background-color: #F9FAFC;
color: #1F2D3D;
}
p{
color: #3C4858;
}
h1,h2,h3,h4{
color: #1F2D3D;
}
h1{
font-size: 3rem;
}
h2{
font-size: 2rem;
}
h3{
font-size: 1.6rem;
}
h4{
font-size: 1rem;
margin-bottom: -30px;
font-style: italic;
}
a {
transition: all;
transition-duration: 300ms;
color: #009EEB;
text-decoration: inherit;
}
a:hover, a:focus{
color: #592DEA;
}
table, th, td {
border: 1px solid #C0CCDA;
border-collapse: collapse;
}
th, td{
padding: 5px 10px;
}
table {
min-width: 600px;
}
th {
text-align: left;
min-width: 100px;
}
table tr:nth-child(odd) {
background-color: #fff;
}
img {
padding-right: 40px;
padding-bottom: 20px;
padding-top: 10px;
width: 100%;
height: auto;
}
/* CLASS STYLES */
.section--hero{
padding-top: 60px;
padding-bottom: 80px;
margin-bottom: 40px;
opacity: 0;
}
.section--hero-home{
background:
linear-gradient(
rgba(0, 0, 0, 0.45),
rgba(0, 0, 0, 0.45)
),
url('../img/compressed/lake0.jpg');
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
.section--hero-101{
background:
linear-gradient(
rgba(0, 0, 0, 0.15),
rgba(0, 0, 0, 0.15)
),
url('../img/compressed/map0.jpg');
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
.section--hero-111{
background:
linear-gradient(
rgba(0, 0, 0, 0.15),
rgba(0, 0, 0, 0.15)
),
url('../img/compressed/globe0.jpg');
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
.section--hero-121{
background:
linear-gradient(
rgba(0, 0, 0, 0.25),
rgba(0, 0, 0, 0.25)
),
url('../img/compressed/drone0.jpg');
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
.section--hero-122{
background:
linear-gradient(
rgba(0, 0, 0, 0.25),
rgba(0, 0, 0, 0.25)
),
url('../img/compressed/tech0.jpg');
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
.section--hero-205{
background:
linear-gradient(
rgba(0, 0, 0, 0.25),
rgba(0, 0, 0, 0.25)
),
url('../img/compressed/map1.jpg');
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
.section--hero-220{
background:
linear-gradient(
rgba(0, 0, 0, 0.25),
rgba(0, 0, 0, 0.25)
),
url('../img/compressed/globe1.jpg');
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
.section--hero-222{
background:
linear-gradient(
rgba(0, 0, 0, 0.45),
rgba(0, 0, 0, 0.45)
),
url('../img/compressed/coding0.jpg');
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
.section--hero h1{
color: #ffffff;
text-shadow: 1px 1px 5px rgba(0,0,0,0.5);
}
.section--hero h3{
color: #EFF2F7;
text-shadow: 1px 1px 5px rgba(0,0,0,0.5);
}
.section--hero a{
color: #85D7FF;
text-shadow: 1px 1px 5px rgba(0,0,0,0.5);
}
.section--hero a:hover, .banner a:focus{
text-shadow: 1px 1px 5px rgba(0,0,0,0.5);
}
.section--video{
position: relative;
height: 400px;
width: 100%;
overflow: hidden;
}
.section--video video{
position: absolute;
top: 50%;
left: 50%;
min-width: 100%;
min-height: 100%;
width: auto;
height: auto;
z-index: 0;
-ms-transform: translateX(-50%) translateY(-50%);
-moz-transform: translateX(-50%) translateY(-50%);
-webkit-transform: translateX(-50%) translateY(-50%);
transform: translateX(-50%) translateY(-50%);
}
.content{
max-width: 1000px;
margin-left: auto;
margin-right: auto;
opacity: 0;
}
.footer{
height: 100px;
opacity: 0;
}
.logo{
width: 200px;
}
/* HELPERS */
.spacer{
height: 100px;
} | 20.014019 | 57 | 0.561522 |
5b58c47d3a5d965988729b2c16ec0453603f58ef | 3,044 | sql | SQL | celerio-engine/src/test/resources/minimal.sql | Soundatnj/Codegen | fbfacb639e286f9f3f3a18986f74ea275bebd887 | [
"Apache-2.0"
] | 77 | 2015-11-14T18:30:19.000Z | 2021-11-24T14:37:42.000Z | celerio-engine/src/test/resources/minimal.sql | Soundatnj/Codegen | fbfacb639e286f9f3f3a18986f74ea275bebd887 | [
"Apache-2.0"
] | 10 | 2015-11-21T09:22:22.000Z | 2018-03-25T14:53:02.000Z | celerio-engine/src/test/resources/minimal.sql | Soundatnj/Codegen | fbfacb639e286f9f3f3a18986f74ea275bebd887 | [
"Apache-2.0"
] | 42 | 2015-11-18T11:23:44.000Z | 2021-09-08T09:28:26.000Z |
-- _______________________
-- NOTE ABOUT Primary Keys
--
-- 1/ For each numerical pk, Celerio expects by convention a sequence.
-- sequence name = seq_<tablename>
-- For example, if the Table is 'BANK_ACCOUNT', the sequence name should be 'seq_bank_account'
--
-- 2/ By convention, for all pk that are char(32), Celerio will configure hibernate to use
-- an UUIDHexGenerator. Therefore no sequence is needed for these pk.
--
-- 3/ For pk that are char(x) where x is different from 32, Celerio configure hibernate
-- with the "assigned" generator, which means that you must provide manually the pk value.
--
CREATE TABLE ADDRESS (
address_id smallint not null IDENTITY,
street_name varchar(255) ,
city varchar(255) not null,
version smallint default 0,
primary key (address_id)
);
-- _________________________________________________________________
--
-- ACCOUNT
-- _________________________________________________________________
CREATE TABLE ACCOUNT (
account_id char(32) not null,
address_id smallint,
login varchar(255) not null,
password varchar(255) not null,
email varchar(255) not null,
is_enabled bool,
last_access_date timestamp,
first_name varchar(255),
last_name varchar(255),
version smallint default 0,
constraint account_unique_1 unique (login),
constraint account_unique_2 unique (email),
constraint account_unique_3 unique (address_id),
constraint account_fk_1 foreign key (address_id) references ADDRESS,
primary key (account_id)
);
CREATE TABLE ROLE (
role_id smallint generated by default as identity,
name_locale varchar(255) not null,
constraint role_unique_1 unique (name_locale),
primary key (role_id)
);
CREATE TABLE ACCOUNT_ROLE (
account_id char(32) not null,
role_id smallint not null,
constraint account_role_fk_1 foreign key (account_id) references ACCOUNT,
constraint account_role_fk_2 foreign key (role_id) references ROLE,
primary key (account_id, role_id)
);
CREATE TABLE DOCUMENT (
document_id char(32) not null,
account_id char(32) not null,
document_content_type varchar(255) not null,
document_size integer not null,
document_file_name varchar(255) not null,
document_binary bytea,
version smallint default 0,
constraint document_fk_1 foreign key (account_id) references ACCOUNT,
primary key (document_id)
);
CREATE TABLE LEGACY (
name varchar(16) not null,
code varchar(8) not null,
dept smallint not null,
extra_info varchar(255) not null,
primary key (name, code, dept)
);
| 34.988506 | 98 | 0.632392 |
56e57e62522874ebd1be7dbd71d274141a067016 | 132 | ts | TypeScript | videos/3c072f6b-b4a7-400c-aa14-55d1006beca4/1080p_270.ts | Krystian19/cactus-fake-video-cdn-service | 263942b309ecc4bfb07308f20b6352f5b7dfe505 | [
"MIT"
] | null | null | null | videos/3c072f6b-b4a7-400c-aa14-55d1006beca4/1080p_270.ts | Krystian19/cactus-fake-video-cdn-service | 263942b309ecc4bfb07308f20b6352f5b7dfe505 | [
"MIT"
] | 1 | 2018-11-12T14:41:37.000Z | 2018-11-12T14:41:37.000Z | videos/3c072f6b-b4a7-400c-aa14-55d1006beca4/1080p_270.ts | Krystian19/cactus-fake-video-cdn-service | 263942b309ecc4bfb07308f20b6352f5b7dfe505 | [
"MIT"
] | 1 | 2018-11-12T14:29:29.000Z | 2018-11-12T14:29:29.000Z | version https://git-lfs.github.com/spec/v1
oid sha256:241bdfefc87e5a06be2806f190c69b97fbee19bee6cfa3dfdd8f520091ef207f
size 1340252
| 33 | 75 | 0.886364 |
1be55c0e91b0ea069ae56d77021b2a347de8eb3d | 6,583 | py | Python | evry_project_strategy/nodes/agent_sweep.py | mmahdi/Mission_coordination_project | baa13e22b6ae00ad134565feb4263ce8512f53c1 | [
"MIT"
] | null | null | null | evry_project_strategy/nodes/agent_sweep.py | mmahdi/Mission_coordination_project | baa13e22b6ae00ad134565feb4263ce8512f53c1 | [
"MIT"
] | null | null | null | evry_project_strategy/nodes/agent_sweep.py | mmahdi/Mission_coordination_project | baa13e22b6ae00ad134565feb4263ce8512f53c1 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
import rospy
from geometry_msgs.msg import Twist, Pose2D
from sensor_msgs.msg import Range
from nav_msgs.msg import Odometry
from tf.transformations import euler_from_quaternion
from evry_project_plugins.srv import DistanceToFlag
class Robot:
def __init__(self, robot_name):
"""Constructor of the class Robot
The required publishers / subscribers are created.
The attributes of the class are initialized
Args:
robot_name (str): Name of the robot, like robot_1, robot_2 etc. To be used for your subscriber and publisher with the robot itself
"""
self.speed = 0.0
self.angle = 0.0
self.sonar = 0.0 #Sonar distance
self.x, self.y = 0.0, 0.0 #coordinates of the robot
self.yaw = 0.0 #yaw angle of the robot
self.robot_name = robot_name
'''Listener and publisher'''
rospy.Subscriber(self.robot_name + "/sensor/sonar_front", Range, self.callbackSonar)
rospy.Subscriber(self.robot_name + "/odom", Odometry, self.callbackPose)
self.cmd_vel_pub = rospy.Publisher(self.robot_name + "/cmd_vel", Twist, queue_size = 1)
def callbackSonar(self,msg):
"""Callback function that gets the data coming from the ultrasonic sensor
Args:
msg (Range): Message that contains the distance separating the US sensor from a potential obstacle
"""
self.sonar = msg.range
def get_sonar(self):
"""Method that returns the distance separating the ultrasonic sensor from a potential obstacle
"""
return self.sonar
def callbackPose(self, msg):
"""Callback function that gets the data coming from the ultrasonic sensor
Args:
msg (Odometry): Message that contains the coordinates of the agent
"""
self.x = msg.pose.pose.position.x
self.y = msg.pose.pose.position.y
quaternion = msg.pose.pose.orientation
quaternion_list = [quaternion.x, quaternion.y, quaternion.z, quaternion.w]
roll, pitch, yaw = euler_from_quaternion (quaternion_list)
self.yaw = yaw
def get_robot_pose(self):
"""Method that returns the position and orientation of the robot"""
return self.x, self.y, self.yaw
def constraint(self, val, min=-2.0, max=2.0):
"""Method that limits the linear and angular velocities sent to the robot
Args:
val (float): [Desired velocity to send
min (float, optional): Minimum velocity accepted. Defaults to -2.0.
max (float, optional): Maximum velocity accepted. Defaults to 2.0.
Returns:
float: Limited velocity whose value is within the range [min; max]
"""
#DO NOT TOUCH
if val < min: return min
if val > max: return max
return val
def set_speed_angle(self,linear,angular):
"""Method that publishes the proper linear and angular velocities commands on the related topic to move the robot
Args:
linear (float): desired linear velocity
angular (float): desired angular velocity
"""
cmd_vel = Twist()
cmd_vel.linear.x = self.constraint(linear)
cmd_vel.angular.z = self.constraint(angular, min=-1, max=1)
self.cmd_vel_pub.publish(cmd_vel)
def getDistanceToFlag(self):
"""Get the distance separating the agent from a flag. The service 'distanceToFlag' is called for this purpose.
The current position of the robot and its id should be specified. The id of the robot corresponds to the id of the flag it should reach
Returns:
float: the distance separating the robot from the flag
"""
rospy.wait_for_service('/distanceToFlag')
try:
service = rospy.ServiceProxy('/distanceToFlag', DistanceToFlag)
pose = Pose2D()
pose.x = self.x
pose.y = self.y
result = service(pose, int(self.robot_name[-1])) #int(robot_name[-1]) corresponds to the id of the robot. It is also the id of the related flag
return result.distance
except rospy.ServiceException as e :
print("Service call failed: %s"%e)
def sweep():
"""Main loop"""
#from random import randint
robot_name = rospy.get_param("~robot_name")
robot = Robot(robot_name)
print(f"Robot : {robot_name} is starting..")
rospy.sleep(5)
deltaD = 0
previousD = robot.getDistanceToFlag()
velocity = 2
angle = 0
parcourue = 0
while not rospy.is_shutdown():
#Write here your strategy..
sonar = float(robot.get_sonar())
distance = float(robot.getDistanceToFlag())
deltaD = previousD - distance
previousD = distance
print(robot_name, "flag", round(robot.getDistanceToFlag(), 3), "sonar", sonar,'parcourue', round(parcourue, 3), 'deltaD', round(deltaD, 3))
if deltaD < 0:
print(robot_name, 'finished')
robot.set_speed_angle(-2, 0)
rospy.sleep(.5)
robot.set_speed_angle(0, 0)
rospy.signal_shutdown('')
else:
if sonar < 3:
print(robot_name, 'obstacle ahead')
velocity = 0
else:
velocity = 2
if parcourue > 26.5:
print(robot_name, "checking..")
seen = False
robot.set_speed_angle(0,1)
for j in range(6):
if robot.get_sonar() < 4: seen = True
else : None
rospy.sleep(.1)
robot.set_speed_angle(0,-1)
for j in range(11):
if robot.get_sonar() < 4: seen = True
else : None
rospy.sleep(.1)
robot.set_speed_angle(0,1)
for j in range(6):
if robot.get_sonar() < 4: seen = True
else : None
rospy.sleep(.1)
robot.set_speed_angle(0,0)
if seen :
print(robot_name, 'sweep detected obstacle')
rospy.sleep(2 * int(robot_name[-1]))
parcourue = -100
parcourue += deltaD
#Finishing by publishing the desired speed. DO NOT TOUCH.
robot.set_speed_angle(velocity,angle)
rospy.sleep(.1)
if __name__ == "__main__":
print("Running ROS..")
rospy.init_node("Controller", anonymous = True)
sweep()
| 36.572222 | 158 | 0.597448 |
5ad1169a55616ba252441ac166367474065a3509 | 21,473 | swift | Swift | Buddies/View/AddContactView.swift | webex/webex-ios-sdk-example-buddies | 9de337997edef0220e650a19a2148b801018afb7 | [
"MIT"
] | 2 | 2019-03-16T02:12:00.000Z | 2019-07-05T02:25:48.000Z | Buddies/View/AddContactView.swift | webex/webex-ios-sdk-example-buddies | 9de337997edef0220e650a19a2148b801018afb7 | [
"MIT"
] | null | null | null | Buddies/View/AddContactView.swift | webex/webex-ios-sdk-example-buddies | 9de337997edef0220e650a19a2148b801018afb7 | [
"MIT"
] | 3 | 2019-09-24T19:30:41.000Z | 2020-11-06T23:01:15.000Z | // Copyright 2016-2019 Cisco Systems Inc
//
// 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, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import WebexSDK
class AddContactView: UIView, UITextFieldDelegate , UICollectionViewDelegate, UICollectionViewDataSource, UITableViewDelegate, UITableViewDataSource,UISearchBarDelegate{
// MARK: - UI variables
var spaceCreatedBlock: ((SpaceModel, Bool)->())?
private var backView : UIView?
private var addedCollectionView: UICollectionView?
private var buddiesCollectionView: UICollectionView?
private var peopleTableView: UITableView?
private var segmentControll: UISegmentedControl?
private var searchBarBackView: UIView?
private var searchBar: UISearchBar?
private var spaceNameTextFeild: MKTextField?
private var addedContactList: [Contact] = []
private var peopleList : [Contact] = []
private var viewWidth = 0
private var viewHeight = 0
private var backViewWidth = 0
private var backViewHeight = 0
enum SegmentType : Int{
case Buddies = 0
case People = 1
}
// MARK: - WebexSDK: listing people/ create space
func requetPeopleList(searchStr: String){
KTActivityIndicator.singleton.show(title: "Loading...")
if let email = EmailAddress.fromString(searchStr) {
WebexSDK?.people.list(email: email, max: 20) {
(response: ServiceResponse<[Person]>) in
KTActivityIndicator.singleton.hide()
switch response.result {
case .success(let value):
self.peopleList.removeAll()
for person in value{
if let tempContack = Contact(person: person){
self.peopleList.append(tempContack)
}
}
self.peopleTableView?.reloadData()
break
case .failure:
break
}
}
} else {
WebexSDK?.people.list(displayName: searchStr, max: 20) {
(response: ServiceResponse<[Person]>) in
KTActivityIndicator.singleton.hide()
switch response.result {
case .success(let value):
self.peopleList.removeAll()
for person in value{
if let tempContack = Contact(person: person){
self.peopleList.append(tempContack)
}
}
self.peopleTableView?.reloadData()
break
case .failure:
break
}
}
}
}
func requestCreateSpace(){
// let localSpaceId = Space.getSpaceSpaceId(contacts: self.addedContactList)
// if let spaceModel = User.CurrentUser.findLocalSpaceWithId(localSpaceId: localSpaceId){
// if(self.spaceCreatedBlock != nil){
// self.spaceCreatedBlock!(spaceModel,false)
// }
// self.disMiss()
// return;
// }
var spaceTitle = self.spaceNameTextFeild?.text
KTActivityIndicator.singleton.show(title: "Creating")
// if(spaceTitle?.length == 0){
// spaceTitle = Space.getSpaceSpaceName(contacts: self.addedContactList)
// }
WebexSDK?.spaces.create(title: spaceTitle!) { (response: ServiceResponse<Space>) in
switch response.result {
case .success(let value):
if let createdSpace = SpaceModel(space: value){
let threahSpace = DispatchGroup()
for contact in self.addedContactList{
DispatchQueue.global().async(group: threahSpace, execute: DispatchWorkItem(block: {
WebexSDK?.memberships.create(spaceId: createdSpace.spaceId, personEmail:EmailAddress.fromString(contact.email)!, completionHandler: { (response: ServiceResponse<Membership>) in
switch response.result{
case .success(_):
createdSpace.spaceMembers?.append(contact)
break
case .failure(let error):
KTInputBox.alert(error: error)
break
}
})
}))
}
// createdSpace.localSpaceId = localSpaceId
threahSpace.notify(queue: DispatchQueue.global(), execute: {
DispatchQueue.main.async {
KTActivityIndicator.singleton.hide()
if(self.spaceCreatedBlock != nil){
self.spaceCreatedBlock!(createdSpace, true)
}
self.disMiss()
}
})
}
break
case .failure(let error):
DispatchQueue.main.async {
KTActivityIndicator.singleton.hide()
KTInputBox.alert(error: error)
}
break
}
}
}
// MARK: - UI Implementation
override init(frame: CGRect) {
super.init(frame: frame)
self.viewWidth = Int(frame.size.width)
self.viewHeight = Int(frame.size.height)
self.backViewWidth = viewWidth - 60
self.backViewHeight = viewHeight - 60
self.setUpSubViews()
}
func setUpSubViews(){
self.setUpBlurView()
self.setUpTitleView()
self.setUpAddedCollectionView()
self.setUpSegmentView()
self.setUpBuddiesCollectionView()
self.setUPBottomBtnView()
}
func setUpBlurView(){
let blurView = UIVisualEffectView(frame: CGRect(x: 0, y: 0, width: viewWidth, height: viewHeight))
blurView.effect = UIBlurEffect(style: .extraLight)
blurView.alpha = 0.7
self.addSubview(blurView)
}
func setUpTitleView(){
self.backView = UIView(frame: CGRect(x: 30, y: 30, width: backViewWidth, height: backViewHeight))
self.backView?.backgroundColor = UIColor.white
self.backView?.setShadow(color: UIColor.gray, radius: 0.5, opacity: 0.5, offsetX: 0, offsetY: 0)
self.addSubview(self.backView!)
let titleLabel = UILabel(frame: CGRect(x: 15, y: 10, width: backViewWidth-30, height: 30))
titleLabel.font = Constants.Font.InputBox.Title
titleLabel.textColor = Constants.Color.Theme.DarkControl
titleLabel.text = "New Space"
titleLabel.textAlignment = .center
self.backView?.addSubview(titleLabel)
self.spaceNameTextFeild = MKTextField(frame: CGRect(x: 30, y: 40, width: backViewWidth-60, height: 40))
self.spaceNameTextFeild?.delegate = self;
self.spaceNameTextFeild?.textAlignment = .center
self.spaceNameTextFeild?.tintColor = Constants.Color.Theme.Main;
self.spaceNameTextFeild?.layer.borderColor = UIColor.clear.cgColor
self.spaceNameTextFeild?.font = Constants.Font.InputBox.Input
self.spaceNameTextFeild?.bottomBorderEnabled = true;
self.spaceNameTextFeild?.floatingPlaceholderEnabled = false
self.spaceNameTextFeild?.rippleEnabled = false;
self.spaceNameTextFeild?.placeholder = "input space name"
self.spaceNameTextFeild?.returnKeyType = .done;
self.backView?.addSubview(self.spaceNameTextFeild!)
}
func setUpAddedCollectionView(){
if(self.addedCollectionView == nil){
let layout = UICollectionViewFlowLayout();
layout.scrollDirection = UICollectionViewScrollDirection.horizontal;
layout.minimumLineSpacing = 3;
layout.minimumInteritemSpacing = 5;
layout.sectionInset = UIEdgeInsets(top: 10, left: 0, bottom: 0, right: 10);
layout.itemSize = CGSize(60,60)
self.addedCollectionView = UICollectionView(frame:CGRect(x: 5, y: 80, width: backViewWidth-10, height: 60), collectionViewLayout: layout);
self.addedCollectionView?.register(ContactCollectionViewCell.self, forCellWithReuseIdentifier: "AddedContactCollectionCell");
self.addedCollectionView?.delegate = self;
self.addedCollectionView?.dataSource = self;
self.addedCollectionView?.showsHorizontalScrollIndicator = false
self.addedCollectionView?.backgroundColor = UIColor.white
self.addedCollectionView?.allowsMultipleSelection = true
self.addedCollectionView?.alwaysBounceHorizontal = true
}
self.backView?.addSubview(self.addedCollectionView!)
}
func setUpSegmentView(){
if(self.segmentControll == nil){
self.segmentControll = UISegmentedControl(items: ["Buddies","People"])
self.segmentControll?.frame = CGRect(x: 30, y: 155, width: backViewWidth-60, height: 30)
self.segmentControll?.addTarget(self, action: #selector(segmentClicked(sender:)), for: .valueChanged)
self.segmentControll?.tintColor = Constants.Color.Theme.Main
let attr = NSDictionary(object: Constants.Font.InputBox.Button, forKey: NSAttributedStringKey.font as NSCopying)
self.segmentControll?.setTitleTextAttributes(attr as [NSObject : AnyObject] , for: .normal)
self.segmentControll?.selectedSegmentIndex = 0
self.backView?.addSubview(self.segmentControll!)
}
}
@objc func segmentClicked(sender: UISegmentedControl){
if(sender.selectedSegmentIndex == SegmentType.Buddies.rawValue){
self.peopleTableView?.removeFromSuperview()
self.setUpBuddiesCollectionView()
}else{
self.buddiesCollectionView?.removeFromSuperview()
self.setUpPeopleTableView()
}
}
func setUpBuddiesCollectionView(){
if(self.buddiesCollectionView == nil){
let layout = UICollectionViewFlowLayout();
layout.scrollDirection = UICollectionViewScrollDirection.vertical;
layout.minimumLineSpacing = 0;
layout.minimumInteritemSpacing = 0;
layout.itemSize = CGSize((backViewWidth-20)/3, (backViewWidth-20)/3);
layout.sectionInset = UIEdgeInsets(top: 10, left: 0, bottom: 5, right: 0);
self.buddiesCollectionView = UICollectionView(frame:CGRect(x: 5, y: 185, width: backViewWidth-10, height: backViewHeight-235), collectionViewLayout: layout);
self.buddiesCollectionView?.register(ContactCollectionViewCell.self, forCellWithReuseIdentifier: "BuddiesCollectionViewCell");
self.buddiesCollectionView?.delegate = self;
self.buddiesCollectionView?.dataSource = self;
self.buddiesCollectionView?.backgroundColor = UIColor.white
self.buddiesCollectionView?.alwaysBounceVertical = true
}
self.backView?.addSubview(self.buddiesCollectionView!)
}
func setUpPeopleTableView(){
if(self.peopleTableView == nil){
self.peopleTableView = UITableView(frame: CGRect(x: 5, y: 185, width: backViewWidth-10, height: backViewHeight-235))
self.peopleTableView?.separatorStyle = .none
self.peopleTableView?.backgroundColor = UIColor.white
self.peopleTableView?.delegate = self
self.peopleTableView?.dataSource = self
}
self.backView?.addSubview(self.peopleTableView!)
}
func setUPBottomBtnView(){
let btnBackView = UIView(frame: CGRect(x: 0, y: backViewHeight-50, width: backViewWidth, height: 50))
let line = CALayer()
line.frame = CGRect(x: 0.0, y: 0.0, width: Double(backViewWidth), height: 0.5)
line.backgroundColor = Constants.Color.Theme.DarkControl.cgColor
btnBackView.layer .addSublayer(line)
let cancelBtn = UIButton(frame: CGRect(x: 0.0, y: 0.0, width: Double(backViewWidth/2), height: 50.0))
cancelBtn.setTitle("Cancel", for: .normal)
cancelBtn.setTitleColor(Constants.Color.Theme.DarkControl, for: .normal)
cancelBtn.addTarget(self, action: #selector(disMiss), for: .touchUpInside)
cancelBtn.titleLabel?.font = Constants.Font.InputBox.Button
btnBackView.addSubview(cancelBtn)
let createBtn = UIButton(frame: CGRect(x: Double(backViewWidth/2), y: 0.0, width: Double(backViewWidth/2), height: 50.0))
createBtn.setTitle("Create", for: .normal)
createBtn.setTitleColor(Constants.Color.Theme.Main, for: .normal)
createBtn.addTarget(self, action: #selector(createSpaceBtnClicked), for: .touchUpInside)
createBtn.titleLabel?.font = Constants.Font.InputBox.Button
btnBackView.addSubview(createBtn)
let line1 = CALayer()
line1.frame = CGRect(x: Double(backViewWidth)/2, y: 0.0, width:0.5, height: 50)
line1.backgroundColor = Constants.Color.Theme.DarkControl.cgColor
btnBackView.layer .addSublayer(line1)
self.backView?.addSubview(btnBackView)
}
// MARK: Page Logic Implementation
func checkAddedPeopleList(choosedContact: Contact)->Bool{
let email = choosedContact.email
if(self.addedContactList.find(equality: { $0.email == email }) == nil){
return true
}else{
return false
}
}
func popUpOnWindow(){
self.backView?.alpha = 0.0
self.backView?.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
((UIApplication.shared.delegate) as! AppDelegate).window?.addSubview(self)
UIView.animate(withDuration: 0.2, animations: {
UIView.setAnimationCurve(.easeInOut)
self.backView?.alpha = 1.0
self.backView?.transform = CGAffineTransform(scaleX: 1, y: 1)
}) { (_) in
}
}
@objc func disMiss(){
UIView.animate(withDuration: 0.2, animations: {
UIView.setAnimationCurve(.easeInOut)
self.alpha = 0.0
self.backView?.alpha = 0.0
self.backView?.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
}) { (_) in
self.removeFromSuperview()
}
}
@objc func createSpaceBtnClicked(){
self.requestCreateSpace()
}
// MARK: UIcollectionView Delegate
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if(collectionView == self.buddiesCollectionView){
return User.CurrentUser.getSingleMemberSpace().count
}else{
return (self.addedContactList.count)
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if(collectionView == self.buddiesCollectionView){
let contact = User.CurrentUser[indexPath.item]?.contact
let cell: ContactCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "BuddiesCollectionViewCell", for: indexPath) as! ContactCollectionViewCell
cell.updateUIElements(cellWidth: (backViewWidth-20)/3, showDeleteBtn: false, contact: contact, onDelete: nil)
return cell
}else{
let contact = self.addedContactList[indexPath.row]
let cell:ContactCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "AddedContactCollectionCell", for: indexPath) as! ContactCollectionViewCell;
cell.updateUIElements(cellWidth: 60 , showDeleteBtn: true, contact: contact, onDelete: {
cell.contact?.isChoosed = false
let email = cell.contact?.email
_ = self.addedContactList.removeObject(equality: { $0.email == email })
self.addedCollectionView?.reloadData()
self.buddiesCollectionView?.reloadData()
self.peopleTableView?.reloadData()
})
return cell
}
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if(collectionView == self.buddiesCollectionView){
let cell: ContactCollectionViewCell = collectionView.cellForItem(at: indexPath) as! ContactCollectionViewCell
if(cell.contact?.isChoosed)!{
cell.contact?.isChoosed = false
cell.updateSelection()
let email = cell.contact?.email
_ = self.addedContactList.removeObject(equality: { $0.email == email })
self.addedCollectionView?.reloadData()
}else{
if(self.checkAddedPeopleList(choosedContact: cell.contact!)){
cell.contact?.isChoosed = true
cell.updateSelection()
self.addedContactList.insert(cell.contact!, at: 0)
self.addedCollectionView?.reloadData()
}
}
}
}
// MARK: - UITableView Delegate
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 40
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if(self.searchBar == nil){
self.searchBarBackView = UIView(frame: CGRect(x: 0, y: 0, width: (self.backView?.frame.size.width)!, height: 40))
self.searchBarBackView?.backgroundColor = UIColor.white
self.searchBar = UISearchBar(frame: CGRect(0, 10, Constants.Size.screenWidth-90, 20))
self.searchBar?.tintColor = Constants.Color.Theme.Main
self.searchBar?.backgroundImage = UIImage()
self.searchBar?.delegate = self
self.searchBar?.returnKeyType = .search
self.searchBar?.showsCancelButton = true
self.searchBarBackView?.addSubview(self.searchBar!)
}
return self.searchBarBackView
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return CGFloat(peopleTableCellHeight)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.peopleList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let index = indexPath.row
let contactModel = self.peopleList[index]
let cell = PeopleListTableCell(searchedContactModel: contactModel)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell: PeopleListTableCell = tableView.cellForRow(at: indexPath) as! PeopleListTableCell
if(cell.contactModel?.isChoosed)!{
cell.contactModel?.isChoosed = false
cell.updateSelection()
let email = cell.contactModel?.email
_ = self.addedContactList.removeObject(equality: { $0.email == email })
self.addedCollectionView?.reloadData()
}else{
if(self.checkAddedPeopleList(choosedContact: cell.contactModel!)){
cell.contactModel?.isChoosed = true
cell.updateSelection()
self.addedContactList.insert(cell.contactModel!, at: 0)
self.addedCollectionView?.reloadData()
}
}
}
// MARK: SearchBar Delegate
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchBar.resignFirstResponder()
if let searchStr = searchBar.text{
self.requetPeopleList(searchStr: searchStr)
}
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
// Hide the cancel button
searchBar.resignFirstResponder()
searchBar.text = ""
}
// MARK: TextField Delegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 45.590234 | 204 | 0.622363 |
5bb8b65e5b041e2b99695061318dcfb59f553d50 | 208 | sql | SQL | conf/evolutions/default/6.sql | styleandsubstance/StockTraderBackend | d5067c6695c281e0751ec8d254dc19e3c7c4cf26 | [
"Apache-2.0"
] | null | null | null | conf/evolutions/default/6.sql | styleandsubstance/StockTraderBackend | d5067c6695c281e0751ec8d254dc19e3c7c4cf26 | [
"Apache-2.0"
] | null | null | null | conf/evolutions/default/6.sql | styleandsubstance/StockTraderBackend | d5067c6695c281e0751ec8d254dc19e3c7c4cf26 | [
"Apache-2.0"
] | null | null | null | # --- !Ups
INSERT INTO DataSource VALUES (nextval('datasource_id_seq'), 'SymbolIndustry');
INSERT INTO DataSource VALUES (nextval('datasource_id_seq'), 'MarketWatchQuarterlyBalanceSheet');
# --- !Downs
| 34.666667 | 98 | 0.740385 |