identifier
stringlengths
42
383
collection
stringclasses
1 value
open_type
stringclasses
1 value
license
stringlengths
0
1.81k
date
float64
1.99k
2.02k
title
stringlengths
0
100
creator
stringlengths
1
39
language
stringclasses
157 values
language_type
stringclasses
2 values
word_count
int64
1
20k
token_count
int64
4
1.32M
text
stringlengths
5
1.53M
__index_level_0__
int64
0
57.5k
https://github.com/ericlay14/Docketeer/blob/master/src/components/tabs/Yml.js
Github Open Source
Open Source
MIT
null
Docketeer
ericlay14
JavaScript
Code
528
1,803
import React, { useEffect, useState } from 'react'; import { useSelector, useDispatch } from 'react-redux'; import * as actions from '../../actions/actions'; import * as helper from '../helper/commands'; import { makeStyles } from '@material-ui/core/styles'; import Table from '@material-ui/core/Table'; import TableBody from '@material-ui/core/TableBody'; import TableCell from '@material-ui/core/TableCell'; import TableContainer from '@material-ui/core/TableContainer'; import TableHead from '@material-ui/core/TableHead'; import TableRow from '@material-ui/core/TableRow'; /** * Displays all running docker-compose container networks; drag and drop or upload functionality * * @param {*} props */ const useStyles = makeStyles(() => ({ root: { '& .MuiTextField-root': { marginLeft: 5, marginBottom: 15, width: 220, verticalAlign: 'middle', }, }, button: { marginLeft: 5, width: 100, verticalAlign: 'top', }, verifiedIcon: { verticalAlign: 'top', color: 'green', }, description: { marginLeft: 5, marginBottom: 30, }, })); const Yml = () => { const classes = useStyles(); const [filePath, setFilePath] = useState(''); const [ymlFile, setYmlFile] = useState(''); const [ymlFileName, setYmlFileName] = useState(''); // ymlFileName is specifically for the dockerComposeUp helper fn const dispatch = useDispatch(); const composeStack = useSelector((state) => state.networkList.composeStack); const getContainerStacks = (data) => dispatch(actions.getContainerStacks(data)); const composeDown = (data) => dispatch(actions.composeDown(data)); useEffect(() => { // upon page render, get list of currently running container networks helper.dockerComposeStacks(getContainerStacks); const holder = document.getElementById('drag-file'); const uploadHolder = document.getElementById('uploadFile'); holder.ondragover = () => { holder.style = 'background-color: #EDEDED'; return false; }; holder.ondragleave = () => { holder.style = 'background-color: white'; return false; }; holder.ondragend = () => { return false; }; uploadHolder.onchange = (e) => { e.preventDefault(); if ( e.target.files.length && e.target.files[0].type === 'application/x-yaml' ) { const ymlFile = e.target.files[0]; const filePath = e.target.files[0].path; const reader = new FileReader(); reader.readAsText(ymlFile); reader.onload = function (e) { setYmlFile(e.target.result); }; // get yml file name from the filepath for composing up a new container network const ymlRegex = /\/docker-compose.*.yml/; const ymlFileName = filePath.match(ymlRegex)[0].replace('/', ''); const directoryPath = filePath.replace(ymlRegex, ''); setFilePath(directoryPath); setYmlFileName(ymlFileName); }; }; }, []); // creates table of running container networks const TableData = () => { return composeStack.map((container, index) => { return ( <TableRow key={index}> <TableCell> <span className="container-name">{container.Name}</span> </TableCell> <TableCell> <span className="container-id">{container.ID}</span> </TableCell> <TableCell> <span className="container-drive">{container.Driver}</span> </TableCell> <TableCell> <span className="container-scope">{container.Scope}</span> </TableCell> <TableCell> <span className="container-createdAt">{container.CreatedAt}</span> </TableCell> {container.FilePath && container.YmlFileName && ( // container network will only have a filepath and ymlfilename property if it was composed-up through the application itself // only the containers composed up from the application will have a compose down button <TableCell className="btn-compose-up"> <button className="btn" onClick={() => { helper .dockerComposeDown(container.FilePath, container.YmlFileName) .then((res) => { if (res) { helper.dockerComposeStacks(getContainerStacks, container.FilePath, container.YmlFileName); setYmlFile(''); setFilePath(''); setYmlFileName(''); } }) .catch((err) => console.log(err)); }} > Docker Compose Down </button> </TableCell> )} </TableRow> ); }); }; return ( <div className="renderContainers"> <div className="header"> <h1 className="tabTitle">Docker Compose</h1> </div> <div className="settings-container"> <div id="drag-file"> Upload your Docker Compose file here to compose {ymlFile && ( <pre style={{ margin: '1rem 0rem' }}> <code>{ymlFile}</code> </pre> )} <br /> </div> <div className="btn-compose-up"> <input id="uploadFile" type="file" accept=".yml"></input> <button className="btn" onClick={() => { helper .dockerComposeUp(filePath, ymlFileName) .then((res) => { if (res) { helper.dockerComposeStacks(getContainerStacks, filePath, ymlFileName); setYmlFile(''); setFilePath(''); setYmlFileName(''); } }) .catch((err) => console.log(err)); }} > Docker Compose Up </button> </div> </div> <div className="settings-container"> <TableContainer> <Table> <TableHead> <TableRow> <TableCell>Name</TableCell> <TableCell>Container ID</TableCell> <TableCell>Driver</TableCell> <TableCell>Scope</TableCell> <TableCell>Created At</TableCell> </TableRow> </TableHead> <TableBody> <TableData /> </TableBody> </Table> </TableContainer> </div> </div> ); }; export default Yml;
30,662
https://github.com/JetBrains/intellij-community/blob/master/java/java-tests/testData/inspection/redundantCast/FieldAccessOnTheLeftOfAssignment.java
Github Open Source
Open Source
Apache-2.0
2,023
intellij-community
JetBrains
Java
Code
34
99
abstract class Foo { protected int field; public int f(Bar t){ ((<warning descr="Casting 't' to 'Foo' is redundant">Foo</warning>)t).field = 0; return ((<warning descr="Casting 't' to 'Foo' is redundant">Foo</warning>)t).field; } } class Bar extends Foo{}
48,965
https://github.com/hyller/GladiatorLibrary/blob/master/Visual C++ Example/第14章 数据库及其相关技术/实例339~342药品库存管理系统/源程序代码/MedicAdmin/ChangePasswordDlg.cpp
Github Open Source
Open Source
Unlicense
2,022
GladiatorLibrary
hyller
C++
Code
140
878
// ChangePasswordDlg.cpp : implementation file // #include "stdafx.h" #include "MedicAdmin.h" #include "ChangePasswordDlg.h" #include "MainFrm.h" #include "MedicAdminDoc.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CChangePasswordDlg dialog CChangePasswordDlg::CChangePasswordDlg(CWnd* pParent /*=NULL*/) : CDialog(CChangePasswordDlg::IDD, pParent) { //{{AFX_DATA_INIT(CChangePasswordDlg) m_account = _T(""); m_password = _T(""); m_password2 = _T(""); m_oldPassword = _T(""); //}}AFX_DATA_INIT } void CChangePasswordDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CChangePasswordDlg) DDX_Text(pDX, IDC_ACCOUNT_EDIT, m_account); DDX_Text(pDX, IDC_NEW_PASSWORD_EDIT, m_password); DDX_Text(pDX, IDC_NEW_PASSWORD2_EDIT, m_password2); DDX_Text(pDX, IDC_OLD_PASSWORD_EDIT, m_oldPassword); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CChangePasswordDlg, CDialog) //{{AFX_MSG_MAP(CChangePasswordDlg) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CChangePasswordDlg message handlers void CChangePasswordDlg::OnOK() { // TODO: Add extra validation here UpdateData(); CMainFrame* theFrm=(CMainFrame*)AfxGetMainWnd(); CMedicAdminDoc* pDoc=(CMedicAdminDoc*)theFrm->GetActiveDocument(); CUser* theUser=&pDoc->theUser; CUserSet* theSet=&pDoc->theUserSet; theSet->m_strFilter="UserAccount='"+theUser->GetAccount()+"'"; theSet->Requery(); if(m_oldPassword==theUser->GetPassword()) { if((m_password==m_password2)&&(m_password != "")) { theUser->SetPassword(m_password); theUser->ModifyPassword(theSet); AfxMessageBox("修改密码成功!"); CDialog::OnOK(); } else if(m_password == "") { AfxMessageBox("请输入新密码!"); } else { AfxMessageBox("两次输入的密码不匹配!"); m_password=""; m_password2=""; UpdateData(FALSE); } } else { AfxMessageBox("输入的密码不正确,您无权修改密码!"); m_oldPassword=""; m_password=""; m_password2=""; UpdateData(FALSE); } }
9,844
https://github.com/heartshare/wocenter/blob/master/services/MenuService.php
Github Open Source
Open Source
BSD-3-Clause
2,017
wocenter
heartshare
PHP
Code
854
3,627
<?php namespace wocenter\services; use wocenter\backend\modules\menu\models\Menu; use wocenter\core\Service; use wocenter\interfaces\ModularityInfoInterface; use wocenter\Wc; use wocenter\helpers\ArrayHelper; use Yii; /** * 菜单服务类 * * @author E-Kevin <e-kevin@qq.com> */ class MenuService extends Service { /** * @var string|array|callable|Menu 菜单类 */ public $menuModel = '\wocenter\backend\modules\menu\models\Menu'; /** * @inheritdoc */ public function getId() { return 'menu'; } /** * 根据查询条件获取指定(单个或多个)分类的菜单数据 * * @param string|array $category 分类ID * @param array $condition 查询条件 * @param integer|boolean $duration 缓存时间 * * @return array 如果$category分类ID为字符串,则返回该分类的一维数组,否则返回二维数组['backend' => [], 'frontend' => [], 'main' => []] */ public function getMenus($category = '', array $condition = [], $duration = 60) { $menus = $this->getMenusByCategoryWithFilter($category, $condition, false, $duration); if (is_string($category)) { return isset($menus[$category]) ? $menus[$category] : []; } else { return $menus; } } /** * 根据查询条件和$filterCategory指标 [获取 || 不获取] 指定分类(单个或多个)的菜单数据 * * @param string|array $category 分类ID * @param array $condition 查询条件 * @param boolean $filterCategory 过滤指定$category分类的菜单,默认:不过滤 * @param integer|boolean $duration 缓存时间 * * @return array ['backend' => [], 'frontend' => [], 'main' => []] */ public function getMenusByCategoryWithFilter($category = '', array $condition = [], $filterCategory = false, $duration = 60) { /** @var Menu $menuModel */ $menuModel = Yii::createObject($this->menuModel); $menus = ArrayHelper::listSearch( $menuModel->getAll($duration), array_merge([ 'category_id' => [ $filterCategory ? (is_array($category) ? 'not in' : 'neq') : (is_array($category) ? 'in' : 'eq'), $category, ], ], $condition) ); return $menus ? ArrayHelper::index($menus, 'id', 'category_id') : []; } /** * 同步所有已安装模块的菜单项,此处不获取缓存中的菜单项 * * @return boolean */ public function syncMenus() { /** @var Menu $menuModel */ $menuModel = $this->menuModel; // 获取已经安装的模块菜单配置信息 $allInstalledMenuConfig = $this->_getMenuConfigs(); // 获取数据库里的所有模块菜单数据,不包括用户自建数据 $menuInDatabase = $this->getMenus('backend', [ 'created_type' => $menuModel::CREATE_TYPE_BY_MODULE ], false); $updateDbMenus = $this->_convertMenuData2Db($allInstalledMenuConfig, 0, $menuInDatabase); $this->_fixMenuData($menuInDatabase, $updateDbMenus); // 操作数据库 $this->_updateMenus($updateDbMenus); // 删除菜单缓存 $this->clearCache(); return true; } /** * 获取所有已安装模块的菜单配置数据 * * @param boolean $treeToList 是否把树型结构数组转换为一维数组,默认为`false`,不转换 * * @return array */ protected function _getMenuConfigs($treeToList = false) { $arr = []; // 获取所有已经安装的模块配置文件 foreach (Wc::$service->getModularity()->getInstalledModules() as $moduleId => $row) { /* @var $infoInstance ModularityInfoInterface */ $infoInstance = $row['infoInstance']; $arr = ArrayHelper::merge($arr, $this->_formatMenuConfig($infoInstance->getMenus())); } return $treeToList ? ArrayHelper::treeToList($arr, 'items') : $arr; } /** * 格式化菜单配置数据,主要把键值`name`转换成键名,方便使用\yii\helpers\ArrayHelper::merge合并相同键名的数组到同一分组下 * * @param array $menus 菜单数据 * * @return array */ protected function _formatMenuConfig($menus) { $arr = []; if (empty($menus)) { return $arr; } foreach ($menus as $key => $menu) { $key = isset($menu['name']) ? $menu['name'] : $key; $arr[$key] = $menu; if (isset($menu['items'])) { $arr[$key]['items'] = $this->_formatMenuConfig($menu['items']); } } return $arr; } /** * 初始化菜单配置数据,用于补全修正菜单数组。可用字段必须存在于$this->menuModel数据表里 * * @param array $menus */ protected function _initMenuConfig(&$menus = []) { $menus['url'] = isset($menus['url']) ? $menus['url'] : 'javascript:;'; $menus['full_url'] = isset($menus['full_url']) ? $menus['full_url'] : $menus['url']; $menus['params'] = isset($menus['params']) ? serialize($menus['params']) : ''; // 模块ID if (!isset($menus['modularity']) && $menus['full_url'] != 'javascript:;') { preg_match('/\w+/', $menus['full_url'], $modularity); $menus['modularity'] = $modularity[0]; } $menus['category_id'] = Yii::$app->id; $menus['created_type'] = Menu::CREATE_TYPE_BY_MODULE; $menus['show_on_menu'] = isset($menus['show_on_menu']) ? 1 : 0; $menus['alias_name'] = isset($menus['alias_name']) ? $menus['alias_name'] : $menus['name']; // 需要补全的字段 $fields = ['icon_html', 'description']; foreach ($fields as $field) { if (!isset($menus[$field])) { $menus[$field] = ''; } } } /** * 转换菜单数据,用以插入数据库 * * @param array $menus 需要转换的菜单配置信息 * @param integer $parentId 数组父级ID * @param array &$menuInDatabase 数据库里的菜单数据 * * @return array ['create', 'update'] * @throws \yii\db\Exception */ protected function _convertMenuData2Db(array $menus, $parentId = 0, &$menuInDatabase = []) { if (empty($menus)) { return []; } $arr = []; /** @var Menu $menuModel */ $menuModel = $this->menuModel; foreach ($menus as $row) { $this->_initMenuConfig($row); // 排除没有设置归属模块的数据以及中断该数据的子数据 // todo 改为系统日志记录该错误或抛出系统异常便于更正? if (empty($row['modularity'])) { continue; } $items = ArrayHelper::remove($row, 'items', []); $row['parent_id'] = $parentId; $arr['menuConfig'][] = $row; $condition = [ 'name' => $row['name'], 'modularity' => $row['modularity'], 'full_url' => $row['full_url'], 'parent_id' => $row['parent_id'], ]; if (!empty($items) // 存在子级菜单配置数据 || $row['parent_id'] == 0 // 菜单为顶级菜单 ) { // 数据库里存在数据 if (($data = ArrayHelper::listSearch($menuInDatabase, $condition, true))) { // 检测数据是否改变 foreach ($row as $key => $value) { if ($data[0][$key] != $value) { $arr['update'][$data[0]['id']][$key] = $value; } } $arr = ArrayHelper::merge($arr, $this->_convertMenuData2Db($items, $data[0]['id'], $menuInDatabase)); } else { // 不存在父级菜单则递归新建父级菜单 if (Yii::$app->getDb()->createCommand()->insert($menuModel::tableName(), $row)->execute()) { $find = $menuModel::find()->where($row)->asArray()->one(); // 同步更新数据库已有数据 $menuInDatabase[] = $find; $arr = ArrayHelper::merge($arr, $this->_convertMenuData2Db($items, $find['id'], $menuInDatabase)); } } } // 数据库里存在数据 if ( ($data = ArrayHelper::listSearch($menuInDatabase, $condition, true)) || // 最底层菜单可以修改`name`字段 ($data = ArrayHelper::listSearch($menuInDatabase, [ 'modularity' => $row['modularity'], 'full_url' => $row['full_url'], 'parent_id' => $row['parent_id'], ], true)) ) { // 检测数据是否改变 foreach ($row as $key => $value) { if ($data[0][$key] != $value) { $arr['update'][$data[0]['id']][$key] = $value; } } } else { // 排序,便于批量插入数据库 ksort($row); $arr['create'][] = $row; // 同步更新数据库已有数据 $menuInDatabase[] = $row; } } return $arr; } /** * 对比数据库已有数据,修正待写入数据库的菜单数据 * * @param array $menuInDatabase 数据库里的菜单数据 * @param array $arr 待处理数组 ['create', 'update'] */ private function _fixMenuData($menuInDatabase = [], &$arr = []) { foreach ($menuInDatabase as $row) { // 配置数据里已删除,则删除数据库对应数据 if ( !ArrayHelper::listSearch($arr['menuConfig'], [ 'name' => $row['name'], 'modularity' => $row['modularity'], 'full_url' => $row['full_url'], ], true) && (!key_exists($row['id'], isset($arr['update']) ? $arr['update'] : [])) ) { $arr['delete'][$row['id']] = $row['id']; } } } /** * 更新所有模块菜单 * * @param array $array 需要操作的数据 ['delete', 'create', 'update'] */ private function _updateMenus($array) { /** @var Menu $menuModel */ $menuModel = $this->menuModel; if (!empty($array['delete'])) { Yii::$app->getDb()->createCommand()->delete($menuModel::tableName(), ['id' => $array['delete']]) ->execute(); } if (!empty($array['create'])) { Yii::$app->getDb()->createCommand()->batchInsert($menuModel::tableName(), array_keys($array['create'][0]), $array['create']) ->execute(); } if (!empty($array['update'])) { foreach ($array['update'] as $id => $row) { Yii::$app->getDb()->createCommand()->update($menuModel::tableName(), $row, ['id' => $id]) ->execute(); } } } /** * 删除缓存 */ public function clearCache() { /** @var Menu $menuModel */ $menuModel = Yii::createObject($this->menuModel); $menuModel->clearCache(); } }
49,441
https://github.com/CLionMesonIntegration/CLionMesonIntegration/blob/master/src/main/gen/com/nonnulldinu/clionmeson/mesonbuildlang/psi/MesonBuildAssignmentStatement.java
Github Open Source
Open Source
MIT
2,020
CLionMesonIntegration
CLionMesonIntegration
Java
Code
36
142
// This is a generated file. Not intended for manual editing. package com.nonnulldinu.clionmeson.mesonbuildlang.psi; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface MesonBuildAssignmentStatement extends PsiElement { @NotNull MesonBuildAtrop getAtrop(); @Nullable MesonBuildFullExpression getFullExpression(); @NotNull MesonBuildIdExpression getIdExpression(); @Nullable PsiElement getNewline(); }
9,316
https://github.com/notDanish/zombie-game/blob/master/Game/Assets/Scripts/SelectByKeyPress.cs
Github Open Source
Open Source
MIT
2,020
zombie-game
notDanish
C#
Code
36
157
using UnityEngine; using System.Collections; public class SelectByKeyPress : MonoBehaviour { void OnTriggerEnter( Collider other){ other.gameObject.GetComponent<Renderer>().material.color = Color.red; } void OnTriggerExit( Collider other){ other.gameObject.GetComponent<Renderer>().material.color = Color.blue; } void OnTriggerStay( Collider other ){ if(Input.GetKeyDown(KeyCode.Space)){ Destroy(other.gameObject); } } }
3,687
https://github.com/anatolek/deviation_of_two_curves/blob/master/aprox2curves.py
Github Open Source
Open Source
Unlicense
null
deviation_of_two_curves
anatolek
Python
Code
385
1,198
#! /usr/bin/python3 import os import math from scipy.interpolate import interp1d N = 100 # number of points of approximation f1 = 'data/exp/M186/p_p0.txt' # data for curve №1 f2 = 'data/theory/M186/upper.xy' # data for curve №2 # x must be first column n1 = 2 # column for curve №1 n2 = 2 # column for curve №2 scale1x = 1 # scale for curve №1 along the x axis scale2x = 1 # scale for curve №2 along the x axis scale1y = 638331.089701564 # scale for curve №1 along the y axis 638331.089701564 scale2y = 1 # scale for curve №2 along the y axis # function of extract of data def extract_data(filename, column, scale): infile = open(filename, 'r') numbers = [] for line in infile: words = line.split() if words[0] == '#': infile.readline() else: number = float(words[column])*scale numbers.append(number) infile.close() return numbers # find X1 and X2 _f1 = open(f1, 'r') _f2 = open(f2, 'r') for line in _f1: words = line.split() if words[0] == '#': _f1.readline() else: x11 = [float(w) for w in _f1.readline().split()] x12 = [float(w) for w in _f1.readlines()[-1].split()] for line in _f2: words = line.split() if words[0] == '#': _f2.readline() else: x21 = [float(w) for w in _f2.readline().split()] x22 = [float(w) for w in _f2.readlines()[-1].split()] _f1.close() _f2.close() if x11[0]*scale1x > x21[0]*scale2x: x1 = x11[0]*scale1x else: x1 = x21[0]*scale2x if x12[0]*scale1x > x22[0]*scale2x: x2 = x22[0]*scale2x else: x2 = x12[0]*scale1x i = 0 lx = [] for _ in range (N): if i+1 < N: lx.append(x1+(x2-x1)/(N-1)*i) else: lx.append(x2) i+=1 _lx1 = extract_data(f1, 0, scale1x) _lx2 = extract_data(f2, 0, scale2x) _ly1 = extract_data(f1, n1-1, scale1y) _ly2 = extract_data(f2, n2-1, scale2y) ly1_f = interp1d(_lx1, _ly1) #ly2_f = interp1d(_lx2, _ly2) ly1 = ly1_f(lx) #ly2 = ly2_f(lx) z = 0 ly2 = [] for _ in range (N): if z < N/2: ly2.append(_ly2[0]) else: ly2.append(_ly2[3]) z+=1 curv = open('Curves.txt', 'w') j = 0 for _ in range (N): curv.write(str(lx[j]) + '\t') curv.write(str(ly1[j]) + '\t') curv.write(str(ly2[j]) + '\n') j+=1 curv.close() k = 0 dy = [] for _ in range (N): dy_ = (ly1[k]-ly2[k]) dy.append(dy_) k+=1 dys = sum(dy)/N l = 0 sig_i = [] otn_i = [] for _ in range (N): sig_i_=(dy[l]-dys)**2 sig_i.append(sig_i_) otn_i_ = math.fabs(dy[l]/ly1[l])*100 otn_i.append(otn_i_) l+=1 sigma = (sum(sig_i)/N)**0.5 otn = sum(otn_i)/N print('Standard deviation: ', sigma) print('Medium relative precision: ', otn, '%')
42,060
https://github.com/edkotkas/alia/blob/master/tests/logger.ts
Github Open Source
Open Source
ISC
2,023
alia
edkotkas
TypeScript
Code
95
319
import env from '../src/env' import Log from '../src/logger' describe('Logger', () => { beforeEach(() => { spyOn(console, 'info').and.callFake(() => ({})) spyOn(console, 'error').and.callFake(() => ({})) env.verbose = false }) it('should call console info', () => { Log.info('test') expect(console.info).toHaveBeenCalledOnceWith('test') }) it('should call console error', () => { const err = new Error('test') Log.error(err) expect(console.error).toHaveBeenCalledOnceWith('test') }) it('should log error message with stack trace', () => { env.verbose = true const error = new Error('error') Log.error(error) expect(console.error).toHaveBeenCalledOnceWith(error) }) it('should log error message w/o stack trace', () => { env.verbose = false const error = new Error('error') Log.error(error) expect(console.error).toHaveBeenCalledOnceWith('error') }) })
9,002
https://github.com/shngmsw/stat.ink/blob/master/migrations/m180616_111627_missing_octo_gears.php
Github Open Source
Open Source
MIT
null
stat.ink
shngmsw
PHP
Code
120
591
<?php /** * @copyright Copyright (C) 2015-2018 AIZAWA Hina * @license https://github.com/fetus-hina/stat.ink/blob/master/LICENSE MIT * @author AIZAWA Hina <hina@bouhime.com> */ use app\components\db\GearMigration; use app\components\db\Migration; use yii\db\Query; class m180616_111627_missing_octo_gears extends Migration { use GearMigration; public function safeUp() { $this->upGear2( static::name2key('Octoleet Goggles'), 'Octoleet Goggles', 'headgear', static::name2key('Grizzco'), null, 21004 ); $this->upGear2( static::name2key('Fresh Octo Tee'), 'Fresh Octo Tee', 'clothing', static::name2key('Cuttlegear'), static::name2key('Ink Saver (Sub)'), 3 ); $brand = (new Query()) ->select(['id']) ->from('brand2') ->where(['key' => static::name2key('Grizzco')]) ->scalar(); $this->update( 'gear2', ['brand_id' => $brand], ['key' => [ static::name2key('Octoleet Armor'), static::name2key('Octoleet Boots'), ]] ); } public function safeDown() { $this->downGear2(static::name2key('Octoleet Goggles')); $this->downGear2(static::name2key('Fresh Octo Tee')); $brand = (new Query()) ->select(['id']) ->from('brand2') ->where(['key' => static::name2key('Cuttlegear')]) ->scalar(); $this->update( 'gear2', ['brand_id' => $brand], ['key' => [ static::name2key('Octoleet Armor'), static::name2key('Octoleet Boots'), ]] ); } }
18,717
https://github.com/artm-tech/ERC20/blob/master/token/contracts/CrowdsaleWallet.sol
Github Open Source
Open Source
MIT
null
ERC20
artm-tech
Solidity
Code
45
138
// SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "@openzeppelin/contracts/finance/PaymentSplitter.sol"; /** * @title Artemis Payment Splitting Wallet */ contract CrowdsaleWallet is PaymentSplitter { /** * @dev Constructs the payment splitting crowdsale wallet */ constructor( address[] memory payees, uint256[] memory shares_ ) PaymentSplitter( payees, shares_ ) {} }
37,282
https://github.com/endual/manager/blob/master/src/main/java/com/haiyu/manager/dao/dic/DurationModeMapper.java
Github Open Source
Open Source
MIT
2,020
manager
endual
Java
Code
28
121
package com.haiyu.manager.dao.dic; import com.haiyu.manager.pojo.dic.DurationModeDO; import org.apache.ibatis.annotations.Mapper; import tk.mapper.MyMapper; /** * 车票有效期类别 * * @author lzx * @date 2020-09-08 15:02:08 */ @Mapper public interface DurationModeMapper extends MyMapper<DurationModeDO> { }
4,298
https://github.com/NawaMan/FunctionalJ/blob/master/functionalj-core/src/test/java/functionalj/lens/lenses/time/TimeLensTest.java
Github Open Source
Open Source
MIT
2,022
FunctionalJ
NawaMan
Java
Code
58
304
package functionalj.lens.lenses.time; import static functionalj.lens.lenses.java.time.LocalDateLens.theLocalDate; import static org.junit.Assert.assertEquals; import java.time.LocalDate; import org.junit.Test; import lombok.val; public class TimeLensTest { @Test public void testLocalDate() { val localDate1 = LocalDate.of(2019, 3, 3); val localDate2 = theLocalDate.day.changeTo(5).apply(localDate1); assertEquals("2019-03-03", localDate1.toString()); assertEquals("2019-03-05", localDate2.toString()); val localDate3 = theLocalDate.month.toMay.apply(localDate2); assertEquals("2019-05-05", localDate3.toString()); val localDateTime1 = theLocalDate.atTime(6, 0).apply(localDate3); assertEquals("2019-05-05T06:00", localDateTime1.toString()); val period1 = theLocalDate.periodFrom(localDate1).apply(localDate3); assertEquals("P2M2D", period1.toString()); } }
45,846
https://github.com/VasquezSRE/Debut/blob/master/core/View.php
Github Open Source
Open Source
MIT
2,017
Debut
VasquezSRE
PHP
Code
255
657
<?php namespace core; use Exception; use core\Config; use Twig_Environment; use Twig_Extension_Debug; use Twig_Loader_Filesystem; use Twig_Extensions_Extension_Text; class View { public function __construct() {} /** * Agrega el archivo de la vista * * @param string $view * * @return void */ public static function render($view, $args = []) { extract($args, EXTR_SKIP); $file = "../app/Views/$view"; // Directorio de las vistas if (is_readable($file)) { require $file; } else { throw new Exception('La vista $file no ha sido encontrada'); } } /** * Agrega el archivo de la vista usando el motor de plantillas Twig * * @param string $template La plantilla * @param array $args Array asociativo con los datos que se le pasen a la vista * * @return void */ public static function make($template, array $args = []) { $loader = new Twig_Loader_Filesystem(APP . 'Views'); // Archivo de configuración de la aplicación $app_config = Config::get('app'); // Configuramos el entorno de twig a partir de la configuración general // Establecemos si se usará o no cache para las vistas $cache = (!$app_config['debug']) ? ROOT . 'storage/cache' : false; // Es necesario dar permisos para el modo producción (true debug) $twig = new Twig_Environment($loader, array( 'debug' => $app_config['debug'], 'cache' => $cache, )); // ----------------------- EXTENSIONES --------------------------------------- // Añade extensiones útiles para el motor de plantillas => http://twig.sensiolabs.org/doc/extensions/index.html#extensions-install $twig->addExtension(new Twig_Extensions_Extension_Text()); // Añade extensiones para depurar $twig->addExtension(new Twig_Extension_Debug()); // --------------------------------------------------------------------------- // Añadimos los datos de la sesión // esto nos permite pasar datos temporales a la vista $twig->addGlobal('session', $_SESSION); // Eliminamos los mensajes temporales clear_flash_messages(); echo $twig->render($template, $args); } }
11,545
https://github.com/giggio/servicebus_exporter/blob/master/create-index.sh
Github Open Source
Open Source
MIT
2,020
servicebus_exporter
giggio
Shell
Code
41
133
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" pushd $DIR/charts helm package servicebusexporter --destination=.deploy cr upload -o giggio -r servicebus_exporter -p .deploy popd pushd $DIR cr index -i index.yaml -p ./charts/.deploy/ -o giggio -r servicebus_exporter -c https://github.com/giggio/servicebus_exporter/ popd
47,731
https://github.com/dhmontgomery/pioneer-press-code/blob/master/sos-scraper/turnout.r
Github Open Source
Open Source
MIT
2,018
pioneer-press-code
dhmontgomery
R
Code
607
1,610
# Scrapes turnout data for the Aug. 9, 2016 Minnesota primary election from the Minnesota Secretary of State's FTP file, processes that data and saves it. # Requires countycode-fips converter.csv to be in the working directory. These should have been provided if you downloaded this entire folder. # Also requires a username and password to access the Secretary of State's FTP server. This is not provided. It should be placed in a file called "sospw.txt" in the working directory; that file should be a single line with the format "username:password" with no quotes. # Note that this will calculate turnout percentage as a share of registered voters. The Secretary of State's formal turnout percentages are based on total eligible voters in the state, but there's no available figure on the congressional district level. # Will output three csv files: "mnturnout.csv", "cdturnout.csv" and "hdturnout.csv" # Code by David H. Montgomery for the Pioneer Press. library(RCurl) library(tidyr) library(plyr) library(dplyr) # Load the password from the file. You need a working password for this to work. pw <- scan("sospw.txt", what = character(), quiet = TRUE) # Read the precinct results file in from the FTP server. turnout <- read.table( textConnection( getURL("ftp://ftp.sos.state.mn.us/20160809/pctstats.txt",userpwd = pw)), sep=";", quote = "\"", # Don't count apostrophes as strings, otherwise things like "Mary's Point" will break the data. colClasses=c("factor","numeric","factor","factor",rep("numeric",8)) #Set classes for each column. Important to make precinct IDs show up as strings, so you get "0005" instead of "5". ) colnames(turnout) <- c("State","CountyID","PrecinctID","PrecinctName ","HasReported","amReg","SameDayReg","Num.sigs","AbsenteeBallots","FederalAbsentees","PresAbsentees","TotalVoted") # Assign column names turnout <- turnout[,-c(10:11)] # Drop some unneeded columns. # Load a table that converts between the Secretary of State's county codes and formal FIPS codes. fips <- read.csv("../countycode-fips converter.csv") fips <- fips[,-3] # Drop an unnecessary column colnames(fips) <- c("CountyID","County","FIPS") # Label columns turnout <- merge(fips,turnout, by = "CountyID") # Merge with the voting data by County IDs turnout$VTD <- paste0(turnout$FIPS,turnout$PrecinctID) # Combine the FIPs code and the Precinct IDs to create a nine-digit VTD code. turnout$turnout.pct <- as.numeric(turnout$TotalVoted/(turnout[,7]+turnout[,8])) # Calculate percentage of voters divided by total registered, including those registered before Election Day and on it. turnout$absentee.rate <- as.numeric(turnout$AbsenteeBallots/turnout$TotalVoted) # Calculate the percentage of voters who voted absentee. # Load in a second table with details about each precinct, which we'll merge with our turnout results for a more readable and informative table. Same format as above. precincts <- read.table( textConnection( getURL("ftp://ftp.sos.state.mn.us/20160809/PrctTbl.txt",userpwd = pw)), sep=";", quote = "\"", colClasses=c("numeric",rep("factor",2),"numeric",rep("factor",6)) ) precincts <- precincts[,-c(6:10)] # Drop some unneeded columns colnames(precincts) <- c("CountyID","PrecinctID","PrecinctName","CongressionalDistrict","LegislativeDistrict") precincts <- merge(fips,precincts, by = "CountyID") # Label columns precincts$VTD <- paste0(precincts$FIPS,precincts$PrecinctID) # Concatenate nine-digit VTD votes for the precinct data. turnout <- merge(precincts,turnout[,c(7:15)], by = "VTD") # Merge the turnout data with the precinct data by VTDs. write.csv(turnout,"mnturnout.csv", row.names=FALSE) # Save this turnout data to disk. # Create a table showing turnout results by congressional district. cdturnout <- turnout %>% group_by(CongressionalDistrict) %>% summarise( votes = sum(TotalVoted), # Add a column for total votes. RV = sum(amReg) + sum(SameDayReg), # Add a column for registered voters combining Election Day and pre-election registrations Reporting = sum(HasReported)) # Add a column for the number of precincts reporting. cdturnout$pct <- cdturnout$votes / cdturnout$RV # Calculate turnout percentage as a share of registered voters # Repeat the same calculation but for state house district. hdturnout <- turnout %>% group_by(LegislativeDistrict) %>% summarise( votes = sum(TotalVoted), RV = sum(amReg) + sum(SameDayReg)) hdturnout$pct <- hdturnout$votes / hdturnout$RV # Write the congressional district and legislative district into spreadsheets write.csv(cdturnout,"cdturnout.csv", row.names=FALSE) write.csv(hdturnout,"hdturnout.csv", row.names=FALSE) # Return some summary stats on the command line. print(paste0("Precincts reporting: ",sum(turnout[,9]),"/",nrow(turnout)," (",round(sum(turnout[,9])/nrow(turnout),4),")")) print(paste0("Total votes: ",sum(turnout$TotalVoted))) print(paste0("Total registered: ",sum(turnout$amReg) + sum(turnout$SameDayReg))) print(paste0("Percent of RVs voting: ",round(sum(turnout$TotalVoted)/(sum(turnout$amReg)+sum(turnout$SameDayReg)),4))) print(paste0("Percent of eligibles voting: ",round(sum(turnout$TotalVoted)/3967061,4)))
41,315
https://github.com/maximacgfx/example-app/blob/master/database/seeders/NewsTagPivotSeeder.php
Github Open Source
Open Source
MIT
2,021
example-app
maximacgfx
PHP
Code
63
217
<?php namespace Database\Seeders; use Illuminate\Database\Seeder; use App\Models\News; use App\Models\NewsTag; class NewsTagPivotSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { // создать связи между постами и тегами // dd(News::first()->tags()); // dd(NewsTag::first()->news()); // $this->table ='news_tags_pivot'; foreach(News::all() as $post) { foreach(NewsTag::all() as $tag) { if (rand(1, 20) == 10) { $post->tags()->attach($tag->id); } } } } }
25,696
https://github.com/nikup/SofiaTransport/blob/master/SofiaTransport/ViewModels/TypesViewModel.cs
Github Open Source
Open Source
MIT
2,013
SofiaTransport
nikup
C#
Code
121
413
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using SofiaTransport.Models; namespace SofiaTransport.ViewModels { class TypesViewModel { private ObservableCollection<TypeModel> types; public IEnumerable<TypeModel> Types { get { if (this.types == null) { this.Types = this.GetGeneratedTypes(); } return this.types; } set { if (this.types != value) { if (this.types == null) { this.types = new ObservableCollection<TypeModel>(); } this.types.Clear(); foreach (var item in value) { this.types.Add(item); } } } } public TypesViewModel() { } private IEnumerable<TypeModel> GetGeneratedTypes() { TypeModel[] types = { new TypeModel() { Name = "Автобус", ID = 1, Buses=BusesViewModel.GetBuses() }, new TypeModel() { Name = "Тролей", ID = 2, Buses=TrolleysViewModel.GetTrolleys() }, new TypeModel() { Name = "Трамвай", ID = 3, Buses=TramsViewModel.GetTrams() }, }; return types; } } }
20,025
https://github.com/purm/IvmpDotNet/blob/master/IvmpDotNet.Core/Wrappings/WorldManager.cs
Github Open Source
Open Source
MIT
2,021
IvmpDotNet
purm
C#
Code
77
327
using IvmpDotNet.SDK; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IvmpDotNet.Wrappings { public class WorldManager : IWorldManager { public bool SetTime(int iHour, int iMinute) { return Imports.World.World_SetTime(iHour, iMinute); } public bool SetMinuteDuration(int iMinuteDuration) { return Imports.World.World_SetMinuteDuration(iMinuteDuration); } public bool SetDayOfWeek(DaysOfWeek iDay) { return Imports.World.World_SetDayOfWeek((int)iDay); } public bool SetTrafficLightsState(int iState) { return Imports.World.World_SetTrafficLightsState(iState); } public bool SetTrafficLightsLocked(bool b) { return Imports.World.World_SetTrafficLightsLocked(b); } public bool SetTrafficLightsPhaseDuration(TrafficLightPhases iPhase, int iDuration) { return Imports.World.World_SetTrafficLightsPhaseDuration((int)iPhase, iDuration); } } }
39,700
https://github.com/abrorxonobidov/almix/blob/master/frontend/components/MyLightGalleryWidget.php
Github Open Source
Open Source
BSD-3-Clause
null
almix
abrorxonobidov
PHP
Code
53
181
<?php /** * Created by PhpStorm. * User: Abrorxon Obidov * Date: 07-Feb-21 * Time: 18:00 */ namespace frontend\components; use kowap\lightgallery\LightGalleryWidget; use yii\helpers\Json; class MyLightGalleryWidget extends LightGalleryWidget { public function registerClientScript() { $view = $this->getView(); MyLightGalleryAsset::register($view); $options = Json::encode($this->options); $js = '$("#' . $this->id . '").lightGallery(' . $options . ');'; $view->registerJs($js); } }
9,764
https://github.com/awcarlsson/marius/blob/master/examples/training/scripts/ogbn_proteins_multi_gpu.sh
Github Open Source
Open Source
Apache-2.0
2,021
marius
awcarlsson
Shell
Code
25
70
# preprocess the ogbn_proteins graph and put preprocessed graph into output dir marius_preprocess ogbn_proteins output_dir/ # run marius on the preprocessed input marius_train examples/training/configs/ogbn_proteins_multi_gpu.ini info
33,114
https://github.com/chemalot/chemalot/blob/master/src/com/genentech/struchk/oeStruchk/MolReorder.java
Github Open Source
Open Source
GPL-1.0-or-later, GPL-3.0-only, GPL-2.0-only, Apache-2.0
2,023
chemalot
chemalot
Java
Code
1,182
4,223
/* Copyright 2008-2015 Genentech Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed 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.genentech.struchk.oeStruchk; import java.util.Random; import openeye.oechem.OEAtomBase; import openeye.oechem.OEAtomBaseIter; import openeye.oechem.OEAtomBaseVector; import openeye.oechem.OEAtomStereo; import openeye.oechem.OEBondBase; import openeye.oechem.OEBondBaseIter; import openeye.oechem.OEBondStereo; import openeye.oechem.OEExprOpts; import openeye.oechem.OEGraphMol; import openeye.oechem.OEMolBase; import openeye.oechem.OEQMol; import openeye.oechem.OESMILESFlag; import openeye.oechem.OESubSearch; import openeye.oechem.OEUnaryAtomPred; import openeye.oechem.OEUnaryBondPred; import openeye.oechem.oechem; import com.genentech.oechem.tools.Atom; import com.genentech.oechem.tools.AtomHasStereoSpecifiedFunctor; /** * This class provides a function to randomly reorder atoms in an OEGrapMol. * * This is to be used to validate the smiles canonicalization routine in oechem. * @author albertgo * */ public class MolReorder { private static final Random rand = new Random(); private static final int NCHECK = 20; private static int outFlavor = OESMILESFlag.AtomStereo | OESMILESFlag.BondStereo | OESMILESFlag.Isotopes | OESMILESFlag.Hydrogens | OESMILESFlag.Canonical; private MolReorder() { } public static OEGraphMol reorder(OEGraphMol inMol) { OEAtomBase[] ats = new OEAtomBase[inMol.NumAtoms()]; int atIdx = 0; OEAtomBaseIter aIt = inMol.GetAtoms(); while( aIt.hasNext() ) ats[atIdx++] = aIt.next(); aIt.delete(); // generate random atom sequence for(int from=0; from<ats.length; from++) { int to = rand.nextInt(ats.length); OEAtomBase at = ats[from]; ats[from] = ats[to]; ats[to] = at; } // create new atoms and keep copy in the order of the old molecule OEGraphMol tmpMol = new OEGraphMol(); OEAtomBase[] newAtomsAtOldPos = new OEAtomBase[inMol.GetMaxAtomIdx()]; for(int i=0; i<ats.length; i++) { if( ats[i] == null) continue; newAtomsAtOldPos[ats[i].GetIdx()] = tmpMol.NewAtom(ats[i]); } // generate random bond sequence OEBondBase[] bds = new OEBondBase[inMol.NumBonds()]; int bdIdx = 0; OEBondBaseIter bIt = inMol.GetBonds(); while( bIt.hasNext() ) bds[bdIdx++] = bIt.next(); bIt.delete(); // generate bond random sequence for(int from=0; from<bds.length; from++) { int to = rand.nextInt(bds.length); OEBondBase bd = bds[from]; bds[from] = bds[to]; bds[to] = bd; } // create new bonds and keep copy in order of old molecule OEBondBase[] newBondsInOldPos = new OEBondBase[inMol.GetMaxBondIdx()]; for(int i=0; i<bds.length; i++ ) { OEBondBase bd = bds[i]; if(bd == null) continue; OEAtomBase at1 = newAtomsAtOldPos[bd.GetBgn().GetIdx()]; OEAtomBase at2 = newAtomsAtOldPos[bd.GetEnd().GetIdx()]; if(rand.nextBoolean()) { // random swap OEAtomBase tmpAt = at1; at1 = at2; at2 = tmpAt; } newBondsInOldPos[bd.GetIdx()] = tmpMol.NewBond(at1, at2, bd.GetOrder() ); } // copy tetrahedral chirality from old to new OEAtomBaseVector oldVec = new OEAtomBaseVector(); OEAtomBaseVector newVec = new OEAtomBaseVector(); aIt = inMol.GetAtoms(); while( aIt.hasNext() ) { OEAtomBase oldAt = aIt.next(); if( ! oldAt.HasStereoSpecified(OEAtomStereo.Tetrahedral) ) continue; OEAtomBase newAt = newAtomsAtOldPos[oldAt.GetIdx()]; for (OEAtomBaseIter neighborsIt=oldAt.GetAtoms(); neighborsIt.hasNext();) { OEAtomBase oldAtNeighbor = neighborsIt.next(); OEAtomBase newAtNeighbor = newAtomsAtOldPos[oldAtNeighbor.GetIdx()]; oldVec.add(oldAtNeighbor); newVec.add(newAtNeighbor); } int stereo = oldAt.GetStereo(oldVec, OEAtomStereo.Tetrahedral); newAt.SetStereo(newVec, OEAtomStereo.Tetrahedral, stereo); newVec.clear(); oldVec.clear(); } aIt.delete(); // copy double bond stereochemistry from old to new bIt = inMol.GetBonds(); while( bIt.hasNext() ) { OEBondBase oldBd = bIt.next(); if(! oldBd.HasStereoSpecified(OEBondStereo.CisTrans)) continue; OEBondBase newBd = newBondsInOldPos[oldBd.GetIdx()]; // SetStereo needs two atoms connected to the beginning and end point of // a double bond in a vector. OEAtomBase at1 = oldBd.GetBgn(); OEAtomBase at2 = oldBd.GetEnd(); // find atom on beginning atom OEAtomBase oldNat = Atom.findExoNeighbor(at1, at2); // find exocyclic bond from at1, not being at2 if( oldNat == null) continue; // should not happen bond has no other bonds oldVec.add(oldNat); newVec.add(newAtomsAtOldPos[oldNat.GetIdx()]); // find atom on end atom oldNat = Atom.findExoNeighbor(at2, at1); // find exocyclic bond from at1, not being at2 if( oldNat == null) { newVec.clear(); oldVec.clear(); continue; // should not happen bond has no other bonds } oldVec.add(oldNat); newVec.add(newAtomsAtOldPos[oldNat.GetIdx()]); // now set the stereochemistry int stereo = oldBd.GetStereo(oldVec, OEBondStereo.CisTrans); newBd.SetStereo(newVec, OEBondStereo.CisTrans, stereo); newVec.clear(); oldVec.clear(); } bIt.delete(); newVec.delete(); oldVec.delete(); oechem.OEFindRingAtomsAndBonds(tmpMol); oechem.OEAssignAromaticFlags(tmpMol); return tmpMol; } /** * Create canonical Smiles adding additional checks to the openeye functionality * in order to fix shortcomings: * * - If mol has stereo atoms invert stereo centers and try atom atom match, if * that works return lexically smaller smiles to circumvent OEBug on eg. * 1,4 Dimetyl cyclohexan. * - Invert all stero centers non no-chiral atoms and try atom atom match if * that works return lexically smaller smiles. * - invert all double bonds if atom atom match yields same compound return * lexically smaller smiles. * - generate NCHECK molecule objects with random atom and bond orderings, * compare for smallest smiles. */ public static String myCanonicalSmi(OEGraphMol mol) { oechem.OESuppressHydrogens(mol,false,false,true); oechem.OEPerceiveChiral(mol); int smiFlavor = outFlavor; String minSmi = oechem.OECreateSmiString(mol, smiFlavor); if( (smiFlavor & OESMILESFlag.ISOMERIC) == 0) return minSmi; OEQMol qMol = new OEQMol(mol); qMol.BuildExpressions(OEExprOpts.ExactAtoms, OEExprOpts.ExactBonds); OESubSearch subSearch = new OESubSearch(qMol); qMol.delete(); // invert all atoms with stereochemistry and check for lowest smiles // catches C[C@H]1CCC[C@H]1C OEGraphMol tmpMol = new OEGraphMol(mol); OEUnaryAtomPred functor = new AtomHasStereoSpecifiedFunctor(); if( invertAtoms(functor, tmpMol) > 1) { if(subSearch.SingleMatch(tmpMol)) { // this is a smiles which did not get canonized correctly String smi2 = oechem.OECreateSmiString(tmpMol, smiFlavor); if(smi2.compareTo(minSmi) < 0 ) { minSmi = smi2; } } } functor.delete(); // invert all stereo centers which have stereo but are not chiral // catches C[C@H]1CC[C@H](CC1)CC[C@@H](C)Cl tmpMol.Clear(); oechem.OEAddMols(tmpMol, mol); functor = new AtomStereoNonChiralFunctor(); if( invertAtoms(functor, tmpMol) > 1) { if(subSearch.SingleMatch(tmpMol)) { // this is a smiles which did not get canonized correctly String smi2 = oechem.OECreateSmiString(tmpMol, smiFlavor); if(smi2.compareTo(minSmi) < 0 ) { minSmi = smi2; } } } functor.delete(); // invert all double bonds // catches C/C(=N/OC(=O)CCC(=O)O/N=C(\\C)/c1cccs1)/c2cccs2 tmpMol.Clear(); oechem.OEAddMols(tmpMol, mol); OEUnaryBondPred bFunctor = new BondHasStereoSpecifiedFunctor(); if( invertBonds(bFunctor, tmpMol) > 0) { if(subSearch.SingleMatch(tmpMol)) { // this is a smiles which did not get canonized correctly String smi2 = oechem.OECreateSmiString(tmpMol, smiFlavor); if(smi2.compareTo(minSmi) < 0 ) { minSmi = smi2; } } } bFunctor.delete(); subSearch.delete(); // now generate NCHECK mol objects with random ordering and check for // smallest smiles for(int i=1; i<=NCHECK; i++) { tmpMol = MolReorder.reorder(mol); String smi2 = oechem.OECreateSmiString(tmpMol, smiFlavor); if( smi2.compareTo(minSmi) < 0 ) { minSmi = smi2; } } tmpMol.delete(); return minSmi; } /** Invert double bond stereochemistry on bonds in bondFunctor */ private static int invertBonds(OEUnaryBondPred bondFunctor, OEMolBase mol) { int count =0; OEAtomBaseVector vec = new OEAtomBaseVector(); OEBondBaseIter bIt = mol.GetBonds(bondFunctor); while( bIt.hasNext() ) { OEBondBase bd = bIt.next(); if(! bd.HasStereoSpecified() ) continue; if( bd.IsInRing() ) continue; OEAtomBase at1 = bd.GetBgn(); OEAtomBase at2 = bd.GetEnd(); vec.add(Atom.findExoNeighbor(at1, at2)); vec.add(Atom.findExoNeighbor(at2, at1)); int stereo = bd.GetStereo(vec, OEBondStereo.CisTrans); stereo = stereo == OEBondStereo.Cis ? OEBondStereo.Trans : OEBondStereo.Cis; bd.SetStereo(vec, OEBondStereo.CisTrans, stereo); vec.clear(); count++; } vec.delete(); bIt.delete(); return count; } /** Invert atoms identified by atomFunctor */ private static int invertAtoms(OEUnaryAtomPred atomFunctor, OEMolBase mol) { int count =0; OEAtomBaseVector atVec = new OEAtomBaseVector(); OEAtomBaseIter aIt = mol.GetAtoms(atomFunctor); while( aIt.hasNext() ) { OEAtomBase at = aIt.next(); invertStereo(at, atVec); count++; } aIt.delete(); atVec.delete(); return count; } private static void invertStereo(OEAtomBase at, OEAtomBaseVector atVec) { atVec.clear(); OEAtomBaseIter neighborsIt=at.GetAtoms(); while( neighborsIt.hasNext() ) { OEAtomBase atNeighbor = neighborsIt.next(); atVec.add(atNeighbor); } neighborsIt.delete(); int stereo = at.GetStereo(atVec, OEAtomStereo.Tetrahedral); if(stereo == OEAtomStereo.Left ) stereo = OEAtomStereo.Right; else stereo = OEAtomStereo.Left; at.SetStereo(atVec, OEAtomStereo.Tetrahedral, stereo); } public static final void main(String...args) { OEGraphMol mol = new OEGraphMol(); String smi = "C[C@@H]2[C@@H]([C@H]([C@H]2Cl)C)Cl"; smi = "C[C@@H]2[C@H]([C@H]([C@@H]2Cl)C)Cl"; smi = "C[C@@H](O)CCCCCC[C@H](O)C"; oechem.OEParseSmiles(mol, smi); for(int i=0; i<2000; i++) { mol = reorder(mol); System.err.printf("%4d %s\n",i,myCanonicalSmi(mol)); } } }
8,196
https://github.com/l3dlp-sandbox/Rocket.Chat/blob/master/apps/meteor/client/providers/AvatarUrlProvider.tsx
Github Open Source
Open Source
MIT
null
Rocket.Chat
l3dlp-sandbox
TypeScript
Code
141
467
import React, { useMemo, FC } from 'react'; import { getURL } from '../../app/utils/lib/getURL'; import { AvatarUrlContext } from '../contexts/AvatarUrlContext'; import { useSetting } from '../contexts/SettingsContext'; import { roomCoordinator } from '../lib/rooms/roomCoordinator'; const AvatarUrlProvider: FC = ({ children }) => { const cdnAvatarUrl = String(useSetting('CDN_PREFIX') || ''); const externalProviderUrl = String(useSetting('Accounts_AvatarExternalProviderUrl') || ''); const contextValue = useMemo( () => ({ getUserPathAvatar: ((): ((uid: string, etag?: string) => string) => { if (externalProviderUrl) { return (uid: string): string => externalProviderUrl.trim().replace(/\/+$/, '').replace('{username}', uid); } if (cdnAvatarUrl) { return (uid: string, etag?: string): string => `${cdnAvatarUrl}/avatar/${uid}${etag ? `?etag=${etag}` : ''}`; } return (uid: string, etag?: string): string => getURL(`/avatar/${uid}${etag ? `?etag=${etag}` : ''}`); })(), getRoomPathAvatar: ({ type, ...room }: any): string => roomCoordinator.getRoomDirectives(type || room.t)?.getAvatarPath({ username: room._id, ...room }) || '', }), [externalProviderUrl, cdnAvatarUrl], ); return <AvatarUrlContext.Provider children={children} value={contextValue} />; }; export default AvatarUrlProvider;
40,374
https://github.com/nayosx/SimpleDemoRoom/blob/master/app/src/main/java/com/ado/formulario/database/RoomBD.java
Github Open Source
Open Source
MIT
null
SimpleDemoRoom
nayosx
Java
Code
62
224
package com.ado.formulario.database; import androidx.room.*; import android.content.Context; import com.ado.formulario.dao.NoteDao; import com.ado.formulario.model.Note; @Database(entities = {Note.class}, version = 1, exportSchema = false) public abstract class RoomBD extends RoomDatabase { private static RoomBD baseDeDatos; private static String DATABASE_NAME = "baseDeDatosParaNotas"; public synchronized static RoomBD getInstance(Context context) { if (baseDeDatos == null) { baseDeDatos = Room.databaseBuilder(context.getApplicationContext(), RoomBD.class, DATABASE_NAME).allowMainThreadQueries().fallbackToDestructiveMigration().build(); } return baseDeDatos; } public abstract NoteDao noteDao(); }
42,313
https://github.com/mbbo/whatsNewPHP/blob/master/src/Command/SevenZero.php
Github Open Source
Open Source
MIT
null
whatsNewPHP
mbbo
PHP
Code
127
527
<?php namespace App\Command; use App\Definition\Logger; use App\Object\LoggerEmpty; use App\Object\Calcul; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class SevenZero extends Command { public function configure() { $this->setName('sevenZero') ->setDescription('Some PHP 7.0 new features'); } public function execute(InputInterface $input, OutputInterface $output) { $sevenZero = new Calcul(); //Scalar type declarations $output->writeln($sevenZero->scalarSum(1, 5)); //Return type declarations $output->writeln($sevenZero->sum(1, 2)); $output->writeln($sevenZero->sommeTableaux([1,2,3], [4,5,6], [7,8,9])); //Null coalescing operator $identifiant = $_GET['utilisateur'] ?? 'Nothing'; $output->writeln($identifiant); $identifiant = $_GET['utilisateur'] ?? $_POST['utilisateur'] ?? 'Nothing'; $output->writeln($identifiant); //Spaceship operator $output->writeln(1 <=> 1); $output->writeln(1 <=> 2); $output->writeln(2 <=> 1); //Constant arrays using define() define('ANIMALS', [ 'dog', 'cat', 'bird' ]); $output->writeln(ANIMALS[1]); //Anonymous classes $app = new LoggerEmpty(); $app->setLogger(new class implements Logger { public function log(string $msg) { echo $msg; } }); var_dump($app->getLogger()); //Unicode codepoint escape syntax echo "\u{aa}"; echo "\u{0000aa}"; echo "\u{9999}"; } }
23,572
https://github.com/ningyu1/easybase/blob/master/easybase-core/src/main/java/io/ningyu/core/security/service/IRoleService.java
Github Open Source
Open Source
Apache-2.0
2,021
easybase
ningyu1
Java
Code
80
319
package io.ningyu.core.security.service; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.IService; import io.ningyu.core.security.dto.CreateRole; import io.ningyu.core.security.dto.UpdateRole; import io.ningyu.core.security.entity.Role; /** * @ClassName: IRoleService * @Description: 角色相关操作接口 */ public interface IRoleService extends IService<Role> { /** * 分页查询角色列表 * @param page * @param role * @return */ Page<Role> selectRoleList(Page<Role> page, Role role); /** * 创建角色 * @param role * @return */ boolean createRole(CreateRole role); /** * 更新角色 * @param role * @return */ boolean updateRole(UpdateRole role); /** * 删除角色 * @param roleId * @return */ boolean deleteRole(Integer roleId); }
50,057
https://github.com/CalvinWilliams1012/WednesdayMyDudes/blob/master/assets/js/clicker/GameView.js
Github Open Source
Open Source
MIT
2,017
WednesdayMyDudes
CalvinWilliams1012
JavaScript
Code
10
38
function GameView(){} GameView.prototype.render = function(data) { // body... console.log(data.frogs); };
7,639
https://github.com/lenneTech/nest-server/blob/master/src/server/modules/user/inputs/user-create.input.ts
Github Open Source
Open Source
MIT
2,022
nest-server
lenneTech
TypeScript
Code
43
96
import { InputType } from '@nestjs/graphql'; import { CoreUserCreateInput } from '../../../../core/modules/user/inputs/core-user-create.input'; /** * User input to create a new user */ @InputType({ description: 'User input to create a new user' }) export class UserCreateInput extends CoreUserCreateInput { // Extend UserCreateInput here }
17,905
https://github.com/Cingozzz/Distribution/blob/master/f/fhir/src/main/scala/typings/fhir/fhir/CapabilityStatementMessagingSupportedMessage.scala
Github Open Source
Open Source
MIT
2,021
Distribution
Cingozzz
Scala
Code
128
409
package typings.fhir.fhir import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} /** * Messages supported by this system */ trait CapabilityStatementMessagingSupportedMessage extends StObject with BackboneElement { /** * Contains extended information for property 'mode'. */ var _mode: js.UndefOr[Element] = js.undefined /** * Message supported by this system */ var definition: Reference /** * sender | receiver */ var mode: code } object CapabilityStatementMessagingSupportedMessage { inline def apply(definition: Reference, mode: code): CapabilityStatementMessagingSupportedMessage = { val __obj = js.Dynamic.literal(definition = definition.asInstanceOf[js.Any], mode = mode.asInstanceOf[js.Any]) __obj.asInstanceOf[CapabilityStatementMessagingSupportedMessage] } extension [Self <: CapabilityStatementMessagingSupportedMessage](x: Self) { inline def setDefinition(value: Reference): Self = StObject.set(x, "definition", value.asInstanceOf[js.Any]) inline def setMode(value: code): Self = StObject.set(x, "mode", value.asInstanceOf[js.Any]) inline def set_mode(value: Element): Self = StObject.set(x, "_mode", value.asInstanceOf[js.Any]) inline def set_modeUndefined: Self = StObject.set(x, "_mode", js.undefined) } }
4,615
https://github.com/websemantics/oea.svg/blob/master/src/Draw2D/FClasses/Graphical/RectNode.js
Github Open Source
Open Source
MIT
2,021
oea.svg
websemantics
JavaScript
Code
208
592
/** * Draw2D.svg : RectNode * * @author Adnan M.Sagar, PhD. <adnan@websemantics.io> * @copyright 2004-2016 Web Semantics, Inc. (http://websemantics.io) * @license http://www.opensource.org/licenses/mit-license.php MIT * @since 8th November 2005 * @package websemantics/oea/draw2d.svg/fclasses/graphical */ RectNode.prototype = new SVGNode(); function RectNode(x, y, w, h, r, s) { var argv = RectNode.arguments; var argc = RectNode.length; this.className = "RectNode"; if (argv.length == 0) this.initRectNode(0, 0, 0, 0, 0, 1); else this.initRectNode(x, y, w, h, r, s); } RectNode.prototype.initRectNode = function(x, y, w, h, r, s) { this.initSVGNode(); this.initRect(x, y, w, h); this.setRotate(r); this.setScale(s); } RectNode.prototype.onMove = function() { return this.transform(); } RectNode.prototype.onRotate = function() { return this.transform(); } RectNode.prototype.onScale = function() { return this.transform(); } RectNode.prototype.transform = function() { this.transformRectNode(); } RectNode.prototype.transformRectNode = function() { if (this.Node == null) return false; this.y = this.y || 0; this.x = this.x || 0; var attr = " translate(" + this.x + " , " + this.y + ")"; if (this.r > 0 || this.s != 1) { attr += " translate(" + this.xo + " , " + this.yo + ")" + " rotate(" + this.r + ")" + " scale(" + this.s + ")" + " translate(-" + this.xo + " , -" + this.yo + ")"; } this.Node.setAttribute('transform', attr); return true; }
44,361
https://github.com/liuzq71/miilink/blob/master/zed_system/zed3_axiethlite/zed3_axiethlite.ip_user_files/ipstatic/axi_gpio_v2_0/hdl/src/vhdl/axi_gpio.vhd
Github Open Source
Open Source
MIT
2,022
miilink
liuzq71
VHDL
Code
2,991
10,160
------------------------------------------------------------------------------- -- AXI_GPIO - entity/architecture pair ------------------------------------------------------------------------------- -- -- *************************************************************************** -- DISCLAIMER OF LIABILITY -- -- This file contains proprietary and confidential information of -- Xilinx, Inc. ("Xilinx"), that is distributed under a license -- from Xilinx, and may be used, copied and/or disclosed only -- pursuant to the terms of a valid license agreement with Xilinx. -- -- XILINX IS PROVIDING THIS DESIGN, CODE, OR INFORMATION -- ("MATERIALS") "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER -- EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING WITHOUT -- LIMITATION, ANY WARRANTY WITH RESPECT TO NONINFRINGEMENT, -- MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE. Xilinx -- does not warrant that functions included in the Materials will -- meet the requirements of Licensee, or that the operation of the -- Materials will be uninterrupted or error-free, or that defects -- in the Materials will be corrected. Furthermore, Xilinx does -- not warrant or make any representations regarding use, or the -- results of the use, of the Materials in terms of correctness, -- accuracy, reliability or otherwise. -- -- Xilinx products are not designed or intended to be fail-safe, -- or for use in any application requiring fail-safe performance, -- such as life-support or safety devices or systems, Class III -- medical devices, nuclear facilities, applications related to -- the deployment of airbags, or any other applications that could -- lead to death, personal injury or severe property or -- environmental damage (individually and collectively, "critical -- applications"). Customer assumes the sole risk and liability -- of any use of Xilinx products in critical applications, -- subject only to applicable laws and regulations governing -- limitations on product liability. -- -- Copyright 2009 Xilinx, Inc. -- All rights reserved. -- -- This disclaimer and copyright notice must be retained as part -- of this file at all times. -- *************************************************************************** -- ------------------------------------------------------------------------------- -- Filename: axi_gpio.vhd -- Version: v2.0 -- Description: General Purpose I/O for AXI Interface -- ------------------------------------------------------------------------------- -- Structure: -- axi_gpio.vhd -- -- axi_lite_ipif.vhd -- -- interrupt_control.vhd -- -- gpio_core.vhd ------------------------------------------------------------------------------- -- Author: KSB -- History: -- ~~~~~~~~~~~~~~ -- KSB 07/28/09 -- ^^^^^^^^^^^^^^ -- First version of axi_gpio. Based on xps_gpio 2.00a -- -- KSB 05/20/10 -- ^^^^^^^^^^^^^^ -- Updated for holes in address range -- ~~~~~~~~~~~~~~ -- VB 09/23/10 -- ^^^^^^^^^^^^^^ -- Updated for axi_lite_ipfi_v1_01_a -- ~~~~~~~~~~~~~~ ------------------------------------------------------------------------------- -- Naming Conventions: -- active low signals: "*_n" -- clock signals: "clk", "clk_div#", "clk_#x" -- reset signals: "rst", "rst_n" -- generics: "C_*" -- user defined types: "*_TYPE" -- state machine next state: "*_ns" -- state machine current state: "*_cs" -- combinatorial signals: "*_cmb" -- pipelined or register delay signals: "*_d#" -- counter signals: "*cnt*" -- clock enable signals: "*_ce" -- internal version of output port "*_i" -- device pins: "*_pin" -- ports: - Names begin with Uppercase -- processes: "*_PROCESS" -- component instantiations: "<ENTITY_>I_<#|FUNC> ------------------------------------------------------------------------------- library ieee; use ieee.std_logic_1164.all; use ieee.std_logic_unsigned.all; use ieee.numeric_std.all; use ieee.std_logic_misc.all; use std.textio.all; ------------------------------------------------------------------------------- -- AXI common package of the proc common library is used for different -- function declarations ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- axi_gpio_v2_0_8 library is used for axi4 component declarations ------------------------------------------------------------------------------- library axi_lite_ipif_v3_0_3; use axi_lite_ipif_v3_0_3.ipif_pkg.calc_num_ce; use axi_lite_ipif_v3_0_3.ipif_pkg.INTEGER_ARRAY_TYPE; use axi_lite_ipif_v3_0_3.ipif_pkg.SLV64_ARRAY_TYPE; ------------------------------------------------------------------------------- -- axi_gpio_v2_0_8 library is used for interrupt controller component -- declarations ------------------------------------------------------------------------------- library interrupt_control_v3_1_2; ------------------------------------------------------------------------------- -- axi_gpio_v2_0_8 library is used for axi_gpio component declarations ------------------------------------------------------------------------------- library axi_gpio_v2_0_8; ------------------------------------------------------------------------------- -- Defination of Generics : -- ------------------------------------------------------------------------------- -- AXI generics -- C_BASEADDR -- Base address of the core -- C_HIGHADDR -- Permits alias of address space -- by making greater than xFFF -- C_S_AXI_ADDR_WIDTH -- Width of AXI Address interface (in bits) -- C_S_AXI_DATA_WIDTH -- Width of the AXI Data interface (in bits) -- C_FAMILY -- XILINX FPGA family -- C_INSTANCE -- Instance name ot the core in the EDK system -- C_GPIO_WIDTH -- GPIO Data Bus width. -- C_ALL_INPUTS -- Inputs Only. -- C_INTERRUPT_PRESENT -- GPIO Interrupt. -- C_IS_BIDIR -- Selects gpio_io_i as input. -- C_DOUT_DEFAULT -- GPIO_DATA Register reset value. -- C_TRI_DEFAULT -- GPIO_TRI Register reset value. -- C_IS_DUAL -- Dual Channel GPIO. -- C_ALL_INPUTS_2 -- Channel2 Inputs only. -- C_IS_BIDIR_2 -- Selects gpio2_io_i as input. -- C_DOUT_DEFAULT_2 -- GPIO2_DATA Register reset value. -- C_TRI_DEFAULT_2 -- GPIO2_TRI Register reset value. ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- Defination of Ports -- ------------------------------------------------------------------------------- -- AXI signals -- s_axi_awaddr -- AXI Write address -- s_axi_awvalid -- Write address valid -- s_axi_awready -- Write address ready -- s_axi_wdata -- Write data -- s_axi_wstrb -- Write strobes -- s_axi_wvalid -- Write valid -- s_axi_wready -- Write ready -- s_axi_bresp -- Write response -- s_axi_bvalid -- Write response valid -- s_axi_bready -- Response ready -- s_axi_araddr -- Read address -- s_axi_arvalid -- Read address valid -- s_axi_arready -- Read address ready -- s_axi_rdata -- Read data -- s_axi_rresp -- Read response -- s_axi_rvalid -- Read valid -- s_axi_rready -- Read ready -- GPIO Signals -- gpio_io_i -- Channel 1 General purpose I/O in port -- gpio_io_o -- Channel 1 General purpose I/O out port -- gpio_io_t -- Channel 1 General purpose I/O -- TRI-STATE control port -- gpio2_io_i -- Channel 2 General purpose I/O in port -- gpio2_io_o -- Channel 2 General purpose I/O out port -- gpio2_io_t -- Channel 2 General purpose I/O -- TRI-STATE control port -- System Signals -- s_axi_aclk -- AXI Clock -- s_axi_aresetn -- AXI Reset -- ip2intc_irpt -- AXI GPIO Interrupt ------------------------------------------------------------------------------- entity axi_gpio is generic ( -- -- System Parameter C_FAMILY : string := "virtex7"; -- -- AXI Parameters C_S_AXI_ADDR_WIDTH : integer range 9 to 9 := 9; C_S_AXI_DATA_WIDTH : integer range 32 to 128 := 32; -- -- GPIO Parameter C_GPIO_WIDTH : integer range 1 to 32 := 32; C_GPIO2_WIDTH : integer range 1 to 32 := 32; C_ALL_INPUTS : integer range 0 to 1 := 0; C_ALL_INPUTS_2 : integer range 0 to 1 := 0; C_ALL_OUTPUTS : integer range 0 to 1 := 0;--2/28/2013 C_ALL_OUTPUTS_2 : integer range 0 to 1 := 0;--2/28/2013 C_INTERRUPT_PRESENT : integer range 0 to 1 := 0; C_DOUT_DEFAULT : std_logic_vector (31 downto 0) := X"0000_0000"; C_TRI_DEFAULT : std_logic_vector (31 downto 0) := X"FFFF_FFFF"; C_IS_DUAL : integer range 0 to 1 := 0; C_DOUT_DEFAULT_2 : std_logic_vector (31 downto 0) := X"0000_0000"; C_TRI_DEFAULT_2 : std_logic_vector (31 downto 0) := X"FFFF_FFFF" ); port ( -- AXI interface Signals -------------------------------------------------- s_axi_aclk : in std_logic; s_axi_aresetn : in std_logic; s_axi_awaddr : in std_logic_vector(C_S_AXI_ADDR_WIDTH-1 downto 0); s_axi_awvalid : in std_logic; s_axi_awready : out std_logic; s_axi_wdata : in std_logic_vector(C_S_AXI_DATA_WIDTH-1 downto 0); s_axi_wstrb : in std_logic_vector((C_S_AXI_DATA_WIDTH/8)-1 downto 0); s_axi_wvalid : in std_logic; s_axi_wready : out std_logic; s_axi_bresp : out std_logic_vector(1 downto 0); s_axi_bvalid : out std_logic; s_axi_bready : in std_logic; s_axi_araddr : in std_logic_vector(C_S_AXI_ADDR_WIDTH-1 downto 0); s_axi_arvalid : in std_logic; s_axi_arready : out std_logic; s_axi_rdata : out std_logic_vector(C_S_AXI_DATA_WIDTH-1 downto 0); s_axi_rresp : out std_logic_vector(1 downto 0); s_axi_rvalid : out std_logic; s_axi_rready : in std_logic; -- Interrupt--------------------------------------------------------------- ip2intc_irpt : out std_logic; -- GPIO Signals------------------------------------------------------------ gpio_io_i : in std_logic_vector(C_GPIO_WIDTH-1 downto 0); gpio_io_o : out std_logic_vector(C_GPIO_WIDTH-1 downto 0); gpio_io_t : out std_logic_vector(C_GPIO_WIDTH-1 downto 0); gpio2_io_i : in std_logic_vector(C_GPIO2_WIDTH-1 downto 0); gpio2_io_o : out std_logic_vector(C_GPIO2_WIDTH-1 downto 0); gpio2_io_t : out std_logic_vector(C_GPIO2_WIDTH-1 downto 0) ); ------------------------------------------------------------------------------- -- fan-out attributes for XST ------------------------------------------------------------------------------- attribute MAX_FANOUT : string; attribute MAX_FANOUT of s_axi_aclk : signal is "10000"; attribute MAX_FANOUT of s_axi_aresetn : signal is "10000"; ------------------------------------------------------------------------------- -- Attributes for MPD file ------------------------------------------------------------------------------- attribute IP_GROUP : string ; attribute IP_GROUP of axi_gpio : entity is "LOGICORE"; attribute SIGIS : string ; attribute SIGIS of s_axi_aclk : signal is "Clk"; attribute SIGIS of s_axi_aresetn : signal is "Rst"; attribute SIGIS of ip2intc_irpt : signal is "INTR_LEVEL_HIGH"; end entity axi_gpio; ------------------------------------------------------------------------------- -- Architecture Section ------------------------------------------------------------------------------- architecture imp of axi_gpio is -- Pragma Added to supress synth warnings attribute DowngradeIPIdentifiedWarnings: string; attribute DowngradeIPIdentifiedWarnings of imp : architecture is "yes"; ------------------------------------------------------------------------------- -- constant added for webtalk information ------------------------------------------------------------------------------- --function chr(sl: std_logic) return character is -- variable c: character; -- begin -- case sl is -- when '0' => c:= '0'; -- when '1' => c:= '1'; -- when 'Z' => c:= 'Z'; -- when 'U' => c:= 'U'; -- when 'X' => c:= 'X'; -- when 'W' => c:= 'W'; -- when 'L' => c:= 'L'; -- when 'H' => c:= 'H'; -- when '-' => c:= '-'; -- end case; -- return c; -- end chr; -- --function str(slv: std_logic_vector) return string is -- variable result : string (1 to slv'length); -- variable r : integer; -- begin -- r := 1; -- for i in slv'range loop -- result(r) := chr(slv(i)); -- r := r + 1; -- end loop; -- return result; -- end str; type bo2na_type is array (boolean) of natural; -- boolean to --natural conversion constant bo2na : bo2na_type := (false => 0, true => 1); ------------------------------------------------------------------------------- -- Function Declarations ------------------------------------------------------------------------------- type BOOLEAN_ARRAY_TYPE is array(natural range <>) of boolean; ---------------------------------------------------------------------------- -- This function returns the number of elements that are true in -- a boolean array. ---------------------------------------------------------------------------- function num_set( ba : BOOLEAN_ARRAY_TYPE ) return natural is variable n : natural := 0; begin for i in ba'range loop n := n + bo2na(ba(i)); end loop; return n; end; ---------------------------------------------------------------------------- -- This function returns a num_ce integer array that is constructed by -- taking only those elements of superset num_ce integer array -- that will be defined by the current case. -- The superset num_ce array is given by parameter num_ce_by_ard. -- The current case the ard elements that will be used is given -- by parameter defined_ards. ---------------------------------------------------------------------------- function qual_ard_num_ce_array( defined_ards : BOOLEAN_ARRAY_TYPE; num_ce_by_ard : INTEGER_ARRAY_TYPE ) return INTEGER_ARRAY_TYPE is variable res : INTEGER_ARRAY_TYPE(num_set(defined_ards)-1 downto 0); variable i : natural := 0; variable j : natural := defined_ards'left; begin while i /= res'length loop -- coverage off while defined_ards(j) = false loop j := j+1; end loop; -- coverage on res(i) := num_ce_by_ard(j); i := i+1; j := j+1; end loop; return res; end; ---------------------------------------------------------------------------- -- This function returns a addr_range array that is constructed by -- taking only those elements of superset addr_range array -- that will be defined by the current case. -- The superset addr_range array is given by parameter addr_range_by_ard. -- The current case the ard elements that will be used is given -- by parameter defined_ards. ---------------------------------------------------------------------------- function qual_ard_addr_range_array( defined_ards : BOOLEAN_ARRAY_TYPE; addr_range_by_ard : SLV64_ARRAY_TYPE ) return SLV64_ARRAY_TYPE is variable res : SLV64_ARRAY_TYPE(0 to 2*num_set(defined_ards)-1); variable i : natural := 0; variable j : natural := defined_ards'left; begin while i /= res'length loop -- coverage off while defined_ards(j) = false loop j := j+1; end loop; -- coverage on res(i) := addr_range_by_ard(2*j); res(i+1) := addr_range_by_ard((2*j)+1); i := i+2; j := j+1; end loop; return res; end; function qual_ard_ce_valid( defined_ards : BOOLEAN_ARRAY_TYPE ) return std_logic_vector is variable res : std_logic_vector(0 to 31); begin res := (others => '0'); if defined_ards(defined_ards'right) then res(0 to 3) := "1111"; res(12) := '1'; res(13) := '1'; res(15) := '1'; else res(0 to 3) := "1111"; end if; return res; end; ---------------------------------------------------------------------------- -- This function returns the maximum width amongst the two GPIO Channels -- and if there is only one channel, it returns just the width of that -- channel. ---------------------------------------------------------------------------- function max_width( dual_channel : INTEGER; channel1_width : INTEGER; channel2_width : INTEGER ) return INTEGER is begin if (dual_channel = 0) then return channel1_width; else if (channel1_width > channel2_width) then return channel1_width; else return channel2_width; end if; end if; end; ------------------------------------------------------------------------------- -- Constant Declarations ------------------------------------------------------------------------------- constant C_AXI_MIN_SIZE : std_logic_vector(31 downto 0):= X"000001FF"; constant ZERO_ADDR_PAD : std_logic_vector(0 to 31) := (others => '0'); constant INTR_TYPE : integer := 5; constant INTR_BASEADDR : std_logic_vector(0 to 31):= X"00000100"; constant INTR_HIGHADDR : std_logic_vector(0 to 31):= X"000001FF"; constant GPIO_HIGHADDR : std_logic_vector(0 to 31):= X"0000000F"; constant MAX_GPIO_WIDTH : integer := max_width (C_IS_DUAL,C_GPIO_WIDTH,C_GPIO2_WIDTH); constant ARD_ADDR_RANGE_ARRAY : SLV64_ARRAY_TYPE := qual_ard_addr_range_array( (true,C_INTERRUPT_PRESENT=1), (ZERO_ADDR_PAD & X"00000000", ZERO_ADDR_PAD & GPIO_HIGHADDR, ZERO_ADDR_PAD & INTR_BASEADDR, ZERO_ADDR_PAD & INTR_HIGHADDR ) ); constant ARD_NUM_CE_ARRAY : INTEGER_ARRAY_TYPE := qual_ard_num_ce_array( (true,C_INTERRUPT_PRESENT=1), (4,16) ); constant ARD_CE_VALID : std_logic_vector(0 to 31) := qual_ard_ce_valid( (true,C_INTERRUPT_PRESENT=1) ); constant IP_INTR_MODE_ARRAY : INTEGER_ARRAY_TYPE(0 to 0+bo2na(C_IS_DUAL=1)) := (others => 5); constant C_USE_WSTRB : integer := 0; constant C_DPHASE_TIMEOUT : integer := 8; ------------------------------------------------------------------------------- -- Signal and Type Declarations ------------------------------------------------------------------------------- signal ip2bus_intrevent : std_logic_vector(0 to 1); signal GPIO_xferAck_i : std_logic; signal Bus2IP_Data_i : std_logic_vector(0 to C_S_AXI_DATA_WIDTH-1); signal Bus2IP1_Data_i : std_logic_vector(0 to C_S_AXI_DATA_WIDTH-1); signal Bus2IP2_Data_i : std_logic_vector(0 to C_S_AXI_DATA_WIDTH-1); -- IPIC Used Signals signal ip2bus_data : std_logic_vector(0 to C_S_AXI_DATA_WIDTH-1); signal bus2ip_addr : std_logic_vector(0 to C_S_AXI_ADDR_WIDTH-1); signal bus2ip_data : std_logic_vector(0 to C_S_AXI_DATA_WIDTH-1); signal bus2ip_rnw : std_logic; signal bus2ip_cs : std_logic_vector(0 to 0 + bo2na (C_INTERRUPT_PRESENT=1)); signal bus2ip_rdce : std_logic_vector(0 to calc_num_ce(ARD_NUM_CE_ARRAY)-1); signal bus2ip_wrce : std_logic_vector(0 to calc_num_ce(ARD_NUM_CE_ARRAY)-1); signal Intrpt_bus2ip_rdce : std_logic_vector(0 to 15); signal Intrpt_bus2ip_wrce : std_logic_vector(0 to 15); signal intr_wr_ce_or_reduce : std_logic; signal intr_rd_ce_or_reduce : std_logic; signal ip2Bus_RdAck_intr_reg_hole : std_logic; signal ip2Bus_RdAck_intr_reg_hole_d1 : std_logic; signal ip2Bus_WrAck_intr_reg_hole : std_logic; signal ip2Bus_WrAck_intr_reg_hole_d1 : std_logic; signal bus2ip_be : std_logic_vector(0 to (C_S_AXI_DATA_WIDTH / 8) - 1); signal bus2ip_clk : std_logic; signal bus2ip_reset : std_logic; signal bus2ip_resetn : std_logic; signal intr2bus_data : std_logic_vector(0 to C_S_AXI_DATA_WIDTH-1); signal intr2bus_wrack : std_logic; signal intr2bus_rdack : std_logic; signal intr2bus_error : std_logic; signal ip2bus_data_i : std_logic_vector(0 to C_S_AXI_DATA_WIDTH-1); signal ip2bus_data_i_D1 : std_logic_vector(0 to C_S_AXI_DATA_WIDTH-1); signal ip2bus_wrack_i : std_logic; signal ip2bus_wrack_i_D1 : std_logic; signal ip2bus_rdack_i : std_logic; signal ip2bus_rdack_i_D1 : std_logic; signal ip2bus_error_i : std_logic; signal IP2INTC_Irpt_i : std_logic; ------------------------------------------------------------------------------- -- Architecture ------------------------------------------------------------------------------- begin -- architecture IMP AXI_LITE_IPIF_I : entity axi_lite_ipif_v3_0_3.axi_lite_ipif generic map ( C_S_AXI_ADDR_WIDTH => C_S_AXI_ADDR_WIDTH, C_S_AXI_DATA_WIDTH => C_S_AXI_DATA_WIDTH, C_S_AXI_MIN_SIZE => C_AXI_MIN_SIZE, C_USE_WSTRB => C_USE_WSTRB, C_DPHASE_TIMEOUT => C_DPHASE_TIMEOUT, C_ARD_ADDR_RANGE_ARRAY => ARD_ADDR_RANGE_ARRAY, C_ARD_NUM_CE_ARRAY => ARD_NUM_CE_ARRAY, C_FAMILY => C_FAMILY ) port map ( S_AXI_ACLK => s_axi_aclk, S_AXI_ARESETN => s_axi_aresetn, S_AXI_AWADDR => s_axi_awaddr, S_AXI_AWVALID => s_axi_awvalid, S_AXI_AWREADY => s_axi_awready, S_AXI_WDATA => s_axi_wdata, S_AXI_WSTRB => s_axi_wstrb, S_AXI_WVALID => s_axi_wvalid, S_AXI_WREADY => s_axi_wready, S_AXI_BRESP => s_axi_bresp, S_AXI_BVALID => s_axi_bvalid, S_AXI_BREADY => s_axi_bready, S_AXI_ARADDR => s_axi_araddr, S_AXI_ARVALID => s_axi_arvalid, S_AXI_ARREADY => s_axi_arready, S_AXI_RDATA => s_axi_rdata, S_AXI_RRESP => s_axi_rresp, S_AXI_RVALID => s_axi_rvalid, S_AXI_RREADY => s_axi_rready, -- IP Interconnect (IPIC) port signals Bus2IP_Clk => bus2ip_clk, Bus2IP_Resetn => bus2ip_resetn, IP2Bus_Data => ip2bus_data_i_D1, IP2Bus_WrAck => ip2bus_wrack_i_D1, IP2Bus_RdAck => ip2bus_rdack_i_D1, --IP2Bus_WrAck => ip2bus_wrack_i, --IP2Bus_RdAck => ip2bus_rdack_i, IP2Bus_Error => ip2bus_error_i, Bus2IP_Addr => bus2ip_addr, Bus2IP_Data => bus2ip_data, Bus2IP_RNW => bus2ip_rnw, Bus2IP_BE => bus2ip_be, Bus2IP_CS => bus2ip_cs, Bus2IP_RdCE => bus2ip_rdce, Bus2IP_WrCE => bus2ip_wrce ); ip2bus_data_i <= intr2bus_data or ip2bus_data; ip2bus_wrack_i <= intr2bus_wrack or (GPIO_xferAck_i and not(bus2ip_rnw)) or ip2Bus_WrAck_intr_reg_hole;-- Holes in Address range ip2bus_rdack_i <= intr2bus_rdack or (GPIO_xferAck_i and bus2ip_rnw) or ip2Bus_RdAck_intr_reg_hole; -- Holes in Address range I_WRACK_RDACK_DELAYS: process(Bus2IP_Clk) is begin if (Bus2IP_Clk'event and Bus2IP_Clk = '1') then if (bus2ip_reset = '1') then ip2bus_wrack_i_D1 <= '0'; ip2bus_rdack_i_D1 <= '0'; ip2bus_data_i_D1 <= (others => '0'); else ip2bus_wrack_i_D1 <= ip2bus_wrack_i; ip2bus_rdack_i_D1 <= ip2bus_rdack_i; ip2bus_data_i_D1 <= ip2bus_data_i; end if; end if; end process I_WRACK_RDACK_DELAYS; ip2bus_error_i <= intr2bus_error; ---------------------- --REG_RESET_FROM_IPIF: convert active low to active hig reset to rest of -- the core. ---------------------- REG_RESET_FROM_IPIF: process (s_axi_aclk) is begin if(s_axi_aclk'event and s_axi_aclk = '1') then bus2ip_reset <= not(bus2ip_resetn); end if; end process REG_RESET_FROM_IPIF; --------------------------------------------------------------------------- -- Interrupts --------------------------------------------------------------------------- INTR_CTRLR_GEN : if (C_INTERRUPT_PRESENT = 1) generate constant NUM_IPIF_IRPT_SRC : natural := 1; constant NUM_CE : integer := 16; signal errack_reserved : std_logic_vector(0 to 1); signal ipif_lvl_interrupts : std_logic_vector(0 to NUM_IPIF_IRPT_SRC-1); begin ipif_lvl_interrupts <= (others => '0'); errack_reserved <= (others => '0'); --- Addr 0X11c, 0X120, 0X128 valid addresses, remaining are holes Intrpt_bus2ip_rdce <= "0000000" & bus2ip_rdce(11) & bus2ip_rdce(12) & '0' & bus2ip_rdce(14) & "00000"; Intrpt_bus2ip_wrce <= "0000000" & bus2ip_wrce(11) & bus2ip_wrce(12) & '0' & bus2ip_wrce(14) & "00000"; intr_rd_ce_or_reduce <= or_reduce(bus2ip_rdce(4 to 10)) or Bus2IP_RdCE(13) or or_reduce(Bus2IP_RdCE(15 to 19)); intr_wr_ce_or_reduce <= or_reduce(bus2ip_wrce(4 to 10)) or bus2ip_wrce(13) or or_reduce(bus2ip_wrce(15 to 19)); I_READ_ACK_INTR_HOLES: process(Bus2IP_Clk) is begin if (Bus2IP_Clk'event and Bus2IP_Clk = '1') then if (bus2ip_reset = '1') then ip2Bus_RdAck_intr_reg_hole <= '0'; ip2Bus_RdAck_intr_reg_hole_d1 <= '0'; else ip2Bus_RdAck_intr_reg_hole_d1 <= intr_rd_ce_or_reduce; ip2Bus_RdAck_intr_reg_hole <= intr_rd_ce_or_reduce and (not ip2Bus_RdAck_intr_reg_hole_d1); end if; end if; end process I_READ_ACK_INTR_HOLES; I_WRITE_ACK_INTR_HOLES: process(Bus2IP_Clk) is begin if (Bus2IP_Clk'event and Bus2IP_Clk = '1') then if (bus2ip_reset = '1') then ip2Bus_WrAck_intr_reg_hole <= '0'; ip2Bus_WrAck_intr_reg_hole_d1 <= '0'; else ip2Bus_WrAck_intr_reg_hole_d1 <= intr_wr_ce_or_reduce; ip2Bus_WrAck_intr_reg_hole <= intr_wr_ce_or_reduce and (not ip2Bus_WrAck_intr_reg_hole_d1); end if; end if; end process I_WRITE_ACK_INTR_HOLES; INTERRUPT_CONTROL_I : entity interrupt_control_v3_1_2.interrupt_control generic map ( C_NUM_CE => NUM_CE, C_NUM_IPIF_IRPT_SRC => NUM_IPIF_IRPT_SRC, C_IP_INTR_MODE_ARRAY => IP_INTR_MODE_ARRAY, C_INCLUDE_DEV_PENCODER => false, C_INCLUDE_DEV_ISC => false, C_IPIF_DWIDTH => C_S_AXI_DATA_WIDTH ) port map ( -- Inputs From the IPIF Bus Bus2IP_Clk => Bus2IP_Clk, Bus2IP_Reset => bus2ip_reset, Bus2IP_Data => bus2ip_data, Bus2IP_BE => bus2ip_be, Interrupt_RdCE => Intrpt_bus2ip_rdce, Interrupt_WrCE => Intrpt_bus2ip_wrce, -- Interrupt inputs from the IPIF sources that will -- get registered in this design IPIF_Reg_Interrupts => errack_reserved, -- Level Interrupt inputs from the IPIF sources IPIF_Lvl_Interrupts => ipif_lvl_interrupts, -- Inputs from the IP Interface IP2Bus_IntrEvent => ip2bus_intrevent(IP_INTR_MODE_ARRAY'range), -- Final Device Interrupt Output Intr2Bus_DevIntr => IP2INTC_Irpt_i, -- Status Reply Outputs to the Bus Intr2Bus_DBus => intr2bus_data, Intr2Bus_WrAck => intr2bus_wrack, Intr2Bus_RdAck => intr2bus_rdack, Intr2Bus_Error => intr2bus_error, Intr2Bus_Retry => open, Intr2Bus_ToutSup => open ); -- registering interrupt I_INTR_DELAY: process(Bus2IP_Clk) is begin if (Bus2IP_Clk'event and Bus2IP_Clk = '1') then if (bus2ip_reset = '1') then ip2intc_irpt <= '0'; else ip2intc_irpt <= IP2INTC_Irpt_i; end if; end if; end process I_INTR_DELAY; end generate INTR_CTRLR_GEN; ----------------------------------------------------------------------- -- Assigning the intr2bus signal to zero's when interrupt is not -- present ----------------------------------------------------------------------- REMOVE_INTERRUPT : if (C_INTERRUPT_PRESENT = 0) generate intr2bus_data <= (others => '0'); ip2intc_irpt <= '0'; intr2bus_error <= '0'; intr2bus_rdack <= '0'; intr2bus_wrack <= '0'; ip2Bus_WrAck_intr_reg_hole <= '0'; ip2Bus_RdAck_intr_reg_hole <= '0'; end generate REMOVE_INTERRUPT; gpio_core_1 : entity axi_gpio_v2_0_8.gpio_core generic map ( C_DW => C_S_AXI_DATA_WIDTH, C_AW => C_S_AXI_ADDR_WIDTH, C_GPIO_WIDTH => C_GPIO_WIDTH, C_GPIO2_WIDTH => C_GPIO2_WIDTH, C_MAX_GPIO_WIDTH => MAX_GPIO_WIDTH, C_INTERRUPT_PRESENT => C_INTERRUPT_PRESENT, C_DOUT_DEFAULT => C_DOUT_DEFAULT, C_TRI_DEFAULT => C_TRI_DEFAULT, C_IS_DUAL => C_IS_DUAL, C_DOUT_DEFAULT_2 => C_DOUT_DEFAULT_2, C_TRI_DEFAULT_2 => C_TRI_DEFAULT_2, C_FAMILY => C_FAMILY ) port map ( Clk => Bus2IP_Clk, Rst => bus2ip_reset, ABus_Reg => Bus2IP_Addr, BE_Reg => Bus2IP_BE(0 to C_S_AXI_DATA_WIDTH/8-1), DBus_Reg => Bus2IP_Data_i(0 to MAX_GPIO_WIDTH-1), RNW_Reg => Bus2IP_RNW, GPIO_DBus => IP2Bus_Data(0 to C_S_AXI_DATA_WIDTH-1), GPIO_xferAck => GPIO_xferAck_i, GPIO_Select => bus2ip_cs(0), GPIO_intr => ip2bus_intrevent(0), GPIO2_intr => ip2bus_intrevent(1), GPIO_IO_I => gpio_io_i, GPIO_IO_O => gpio_io_o, GPIO_IO_T => gpio_io_t, GPIO2_IO_I => gpio2_io_i, GPIO2_IO_O => gpio2_io_o, GPIO2_IO_T => gpio2_io_t ); Bus2IP_Data_i <= Bus2IP1_Data_i when bus2ip_cs(0) = '1' and bus2ip_addr (5) = '0'else Bus2IP2_Data_i; BUS_CONV_ch1 : for i in 0 to C_GPIO_WIDTH-1 generate Bus2IP1_Data_i(i) <= Bus2IP_Data(i+ C_S_AXI_DATA_WIDTH-C_GPIO_WIDTH); end generate BUS_CONV_ch1; BUS_CONV_ch2 : for i in 0 to C_GPIO2_WIDTH-1 generate Bus2IP2_Data_i(i) <= Bus2IP_Data(i+ C_S_AXI_DATA_WIDTH-C_GPIO2_WIDTH); end generate BUS_CONV_ch2; end architecture imp;
15,578
https://github.com/AndresMorales-gif/Entregas/blob/master/microservicio/dominio/src/test/java/com/ceiba/envio/servicio/testdatabuilder/EnvioTestDataBuilder.java
Github Open Source
Open Source
Apache-2.0
null
Entregas
AndresMorales-gif
Java
Code
124
434
package com.ceiba.envio.servicio.testdatabuilder; import com.ceiba.envio.modelo.entidad.Envio; public class EnvioTestDataBuilder { private Long id; private String remitente; private String destinatario; private Long zona; private Boolean envioPlus; private Long pesoCarga; public EnvioTestDataBuilder() { this.remitente = "123456"; this.destinatario = "654321"; this.zona = 1L; this.envioPlus = Boolean.FALSE; this.pesoCarga = 15L; } public EnvioTestDataBuilder conId(Long id) { this.id = id; return this; } public EnvioTestDataBuilder conRemitente(String remitente) { this.remitente = remitente; return this; } public EnvioTestDataBuilder conDestinatario(String destinatario) { this.destinatario = destinatario; return this; } public EnvioTestDataBuilder conZona(Long zona) { this.zona = zona; return this; } public EnvioTestDataBuilder conEnvioPlus(Boolean envioPlus) { this.envioPlus = envioPlus; return this; } public EnvioTestDataBuilder conPesoCarga(Long pesoCarga) { this.pesoCarga = pesoCarga; return this; } public Envio build() { return new Envio(id,remitente, destinatario, zona, envioPlus, pesoCarga); } }
38,598
https://github.com/jloisel/phpdir/blob/master/applications/backend/modules/login/validators/emailexistsvalidator.php
Github Open Source
Open Source
Apache-2.0
2,013
phpdir
jloisel
PHP
Code
79
247
<?php /** * Validates that the email is a valid email and * an administrator has this email. * * @author Jerome Loisel */ class EmailExistsValidator extends sfValidatorEmail { protected function configure($options = array(), $messages = array()) { parent::configure ( $options, $messages ); if(is_array($messages)) { foreach($messages as $name => $value) { $this->addMessage($name, $value); } } } protected function doClean($value) { parent::doClean($value); $q = Doctrine::getTable('Customer')->createQuery(); $q->where('email=?',$value); $q->limit(1); if($q->count() == 0) { throw new sfValidatorError($this,'email_not_exist',array('value' => $value)); } } } ?>
34,530
https://github.com/aks-cefz7k/boruishaoz/blob/master/OpenATC-Admin-ui/OpenATC-Admin-web/src/views/Service/serviceUtil.js
Github Open Source
Open Source
MulanPSL-1.0
null
boruishaoz
aks-cefz7k
JavaScript
Code
188
405
/** * Copyright (c) 2020 kedacom * OpenATC is licensed under Mulan PSL v2. * You can use i18n software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * http://license.coscl.org.cn/MulanPSL2 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. **/ import i18n from '../../i18n/index.js' export default class ServiceUtil { // eslint-disable-next-line no-useless-constructor constructor () {} getContent (row) { let control = row.control let res = row.controlName if (control === 22) { res = i18n.t('openatc.greenwaveoptimize.phase') let phases = row.phases if (phases) { let phaseIdArr = [] for (let dir of phases) { if (dir.type !== 0) { let phaseId = dir.id phaseIdArr.push(phaseId) } } res = res + ' ' + phaseIdArr.join('、') } } else if (control === 4) { let value = row.value ? row.value : 1 res = i18n.t('openatc.dutyroute.stage') + ' ' + value } return res } }
44,456
https://github.com/compwright/Core52/blob/master/objects/AutoLoader.php
Github Open Source
Open Source
MIT
2,018
Core52
compwright
PHP
Code
502
1,341
<?php /** * Core52 Class Autoloader * * This class works directly with __autoload() to loop through possible * locations for classes. It allows you to specify specific folders to * look in for an unknown class and you can also specify exactly where * specific classes are located. * * Originally written during the Core revamp that happened Spring 2009 * in preparation for National Momentum development. * * * @author "Jake A. Smith" <jake@companyfiftytwo.com> * @package Core52 * @version 1.0 **/ class AutoClassLoader { /** * Holds an array of paths * * @var array **/ protected $paths; /** * Holds the name of the class we're trying to load * * @var string **/ protected $name; /** * Bool val if we've found the class or not * * @var bool **/ protected $found; protected $oddballs; public static $throw = TRUE; public static function Register() { spl_autoload_register('core52_autoload'); ini_set('unserialize_callback_func', 'core52_autoload'); } public static function Unregister() { spl_autoload_unregister('core52_autoload'); ini_set('unserialize_callback_func', 'core52_autoload'); } public static function ThrowExceptions($throw) { self::$throw = (boolean) $throw; } /** * The Constuctor * * @return void * @author Jake A. Smith **/ public function __construct($name) { $this->name = $name; } /** * Adds path value to $paths array. * * @return void * @author Jake A. Smith **/ public function attempt($path) { $this->paths[] = $path; } /** * Saves oddball name / path stuff. * * @return bool * @author Jake A. Smith **/ public function oddball($name, $path) { $this->oddballs[] = array( 'name' => $name, 'path' => $path ); } /** * Run through all the paths until we find the class * * @return void * @author Jake A. Smith **/ public function process() { $this->_process_paths(); $this->_process_oddballs(); if($this->found) { // found return true; } elseif(count(spl_autoload_functions()) > 1) { // not found, but there are more autoload functions registered on the stack... return false; } else { // end of the line... $this->_throw_exception(); return false; } } /** * Throws an exception if the class was not found. * * @return void * @author Jake A. Smith **/ private function _throw_exception() { if(self::$throw) { throw new AutoClassLoaderException('Could not load class: '. $this->name); } } /** * Run through all the paths returning true if we find it and false if we don't. * * @return bool * @author Jake A. Smith **/ private function _process_paths() { foreach($this->paths as $path) { if(file_exists($path . $this->name .'.php')) { include($path . $this->name .'.php'); $this->found = true; return true; } } return false; } /** * Run through all the oddball possibilities, returning true if we find it, false if we don't. * * @return bool * @author Jake A. Smith **/ private function _process_oddballs() { if(count($this->oddballs) > 0) { foreach($this->oddballs as $oddball) { if($this->name == $oddball['name']) { include($oddball['path']); $this->found = true; return true; } } } } } // END AutoClassLoader class class AutoClassLoaderException extends Exception {} function core52_autoload($name) { $class = new AutoClassLoader($name); $class->attempt(PATH_MODELS); // Model $class->attempt(PATH_OBJECTS); // App objects $class->attempt(PATH_CORE_OBJECTS); // Core objects $class->oddball('DatabaseConnection', PATH_CORE_OBJECTS . 'Database.php'); $class->process(); } AutoClassLoader::Register();
40,716
https://github.com/osrg/nova/blob/master/nova/tests/virt/docker/test_driver.py
Github Open Source
Open Source
Apache-2.0
null
nova
osrg
Python
Code
534
2,453
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (c) 2013 dotCloud, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable 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 contextlib import socket import mock from nova import context from nova import exception from nova.openstack.common import jsonutils from nova.openstack.common import units from nova import test from nova.tests import utils import nova.tests.virt.docker.mock_client from nova.tests.virt.test_virt_drivers import _VirtDriverTestCase from nova.virt.docker import hostinfo from nova.virt.docker import network class DockerDriverTestCase(_VirtDriverTestCase, test.TestCase): driver_module = 'nova.virt.docker.DockerDriver' def setUp(self): super(DockerDriverTestCase, self).setUp() self.stubs.Set(nova.virt.docker.driver.DockerDriver, 'docker', nova.tests.virt.docker.mock_client.MockClient()) def fake_setup_network(self, instance, network_info): return self.stubs.Set(nova.virt.docker.driver.DockerDriver, '_setup_network', fake_setup_network) def fake_get_registry_port(self): return 5042 self.stubs.Set(nova.virt.docker.driver.DockerDriver, '_get_registry_port', fake_get_registry_port) # Note: using mock.object.path on class throws # errors in test_virt_drivers def fake_teardown_network(container_id): return self.stubs.Set(network, 'teardown_network', fake_teardown_network) self.context = context.RequestContext('fake_user', 'fake_project') def test_driver_capabilities(self): self.assertFalse(self.connection.capabilities['has_imagecache']) self.assertFalse(self.connection.capabilities['supports_recreate']) #NOTE(bcwaldon): This exists only because _get_running_instance on the # base class will not let us set a custom disk/container_format. def _get_running_instance(self, obj=False): instance_ref = utils.get_test_instance(obj=obj) network_info = utils.get_test_network_info() network_info[0]['network']['subnets'][0]['meta']['dhcp_server'] = \ '1.1.1.1' image_info = utils.get_test_image_info(None, instance_ref) image_info['disk_format'] = 'raw' image_info['container_format'] = 'docker' self.connection.spawn(self.ctxt, jsonutils.to_primitive(instance_ref), image_info, [], 'herp', network_info=network_info) return instance_ref, network_info def test_get_host_stats(self): self.mox.StubOutWithMock(socket, 'gethostname') socket.gethostname().AndReturn('foo') socket.gethostname().AndReturn('bar') self.mox.ReplayAll() self.assertEqual('foo', self.connection.get_host_stats()['host_hostname']) self.assertEqual('foo', self.connection.get_host_stats()['host_hostname']) def test_get_available_resource(self): memory = { 'total': 4 * units.Mi, 'free': 3 * units.Mi, 'used': 1 * units.Mi } disk = { 'total': 50 * units.Gi, 'available': 25 * units.Gi, 'used': 25 * units.Gi } # create the mocks with contextlib.nested( mock.patch.object(hostinfo, 'get_memory_usage', return_value=memory), mock.patch.object(hostinfo, 'get_disk_usage', return_value=disk) ) as ( get_memory_usage, get_disk_usage ): # run the code stats = self.connection.get_available_resource(nodename='test') # make our assertions get_memory_usage.assert_called_once_with() get_disk_usage.assert_called_once_with() expected_stats = { 'vcpus': 1, 'vcpus_used': 0, 'memory_mb': 4, 'memory_mb_used': 1, 'local_gb': 50L, 'local_gb_used': 25L, 'disk_available_least': 25L, 'hypervisor_type': 'docker', 'hypervisor_version': 1000, 'hypervisor_hostname': 'test', 'cpu_info': '?', 'supported_instances': ('[["i686", "docker", "lxc"],' ' ["x86_64", "docker", "lxc"]]') } self.assertEqual(expected_stats, stats) def test_plug_vifs(self): # Check to make sure the method raises NotImplementedError. self.assertRaises(NotImplementedError, self.connection.plug_vifs, instance=utils.get_test_instance(), network_info=None) def test_unplug_vifs(self): # Check to make sure the method raises NotImplementedError. self.assertRaises(NotImplementedError, self.connection.unplug_vifs, instance=utils.get_test_instance(), network_info=None) def test_create_container(self, image_info=None): instance_href = utils.get_test_instance() if image_info is None: image_info = utils.get_test_image_info(None, instance_href) image_info['disk_format'] = 'raw' image_info['container_format'] = 'docker' self.connection.spawn(self.context, instance_href, image_info, 'fake_files', 'fake_password') self._assert_cpu_shares(instance_href) def test_create_container_vcpus_2(self, image_info=None): flavor = utils.get_test_flavor(options={ 'name': 'vcpu_2', 'flavorid': 'vcpu_2', 'vcpus': 2 }) instance_href = utils.get_test_instance(flavor=flavor) if image_info is None: image_info = utils.get_test_image_info(None, instance_href) image_info['disk_format'] = 'raw' image_info['container_format'] = 'docker' self.connection.spawn(self.context, instance_href, image_info, 'fake_files', 'fake_password') self._assert_cpu_shares(instance_href, vcpus=2) def _assert_cpu_shares(self, instance_href, vcpus=4): container_id = self.connection.find_container_by_name( instance_href['name']).get('id') container_info = self.connection.docker.inspect_container(container_id) self.assertEqual(vcpus * 1024, container_info['Config']['CpuShares']) def test_create_container_wrong_image(self): instance_href = utils.get_test_instance() image_info = utils.get_test_image_info(None, instance_href) image_info['disk_format'] = 'raw' image_info['container_format'] = 'invalid_format' self.assertRaises(exception.InstanceDeployFailure, self.test_create_container, image_info) @mock.patch.object(network, 'teardown_network') @mock.patch.object(nova.virt.docker.driver.DockerDriver, 'find_container_by_name', return_value={'id': 'fake_id'}) def test_destroy_container(self, byname_mock, teardown_mock): instance = utils.get_test_instance() self.connection.destroy(self.context, instance, 'fake_networkinfo') byname_mock.assert_called_once_with(instance['name']) teardown_mock.assert_called_with('fake_id') def test_get_memory_limit_from_sys_meta_in_object(self): instance = utils.get_test_instance(obj=True) limit = self.connection._get_memory_limit_bytes(instance) self.assertEqual(2048 * units.Mi, limit) def test_get_memory_limit_from_sys_meta_in_db_instance(self): instance = utils.get_test_instance(obj=False) limit = self.connection._get_memory_limit_bytes(instance) self.assertEqual(2048 * units.Mi, limit)
5,104
https://github.com/alhaag/skeleton-node-api/blob/master/model/news.js
Github Open Source
Open Source
MIT
2,016
skeleton-node-api
alhaag
JavaScript
Code
221
658
/** * Model news * * Modelo que representa o documento news. * Agrega validações e comportamentos de persistencia no BD. * * @author André Luiz Haag <andreluizhaag@gmail.com> * @license LICENSE.md * @see middlewares/images */ /** * dependencies */ var mongoose = require('mongoose'); var validate = require('mongoose-validator'); var slug = require('mongoose-slug-generator'); var mongoosePaginate = require('mongoose-paginate'); var ImageModel = require('./image'); /** * setup plugins */ mongoose.plugin(slug); mongoose.plugin(mongoosePaginate); /** * Definição do modelo */ var NewsSchema = new mongoose.Schema({ slug: { type: String, slug: ["title"], unique: true }, title: { type: String, required: true, validade: [ validate({ validator: 'isLength', arguments: [1, 255], message: 'Título deve possuir de {ARGS[0]} a {ARGS[1]} characteres' }) ] }, shortDescription: { type: String, required: true, validade: [ validate({ validator: 'isLength', arguments: [1, 255], message: 'Breve descrição deve possuir de {ARGS[0]} a {ARGS[1]} characteres' }) ] }, description: { type: String, required: true }, createdAt: { type: Date, "default": Date.now }, updatedAt: { type: Date, //required: true }, keyWords: { type: String, required: false, validade: [ validate({ validator: 'isLength', arguments: [0, 255], message: 'Palavras chave deve possuir de {ARGS[0]} a {ARGS[1]} characteres' }) ] }, images: { type: [ImageModel], required: false } }); // Generate the slug on save NewsSchema.pre('save', function (next) { /*if (this.isNew) { this.createdAt = Date.now(); }*/ this.updatedAt = Date.now(); next(); }); module.exports = mongoose.model('news', NewsSchema);
15,383
https://github.com/xhigher/nettyboot/blob/master/nettyboot-rpcclient/src/main/java/com/nettyboot/rpcclient/SimpleClient.java
Github Open Source
Open Source
Apache-2.0
2,021
nettyboot
xhigher
Java
Code
440
1,626
package com.nettyboot.rpcclient; import com.nettyboot.rpcmessage.MessageDecoder; import com.nettyboot.rpcmessage.MessageEncoder; import com.nettyboot.rpcmessage.SimpleMessage; import io.netty.bootstrap.Bootstrap; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; import io.netty.handler.timeout.IdleStateHandler; import io.netty.util.concurrent.DefaultThreadFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.InetSocketAddress; public class SimpleClient { private static final Logger logger = LoggerFactory.getLogger(SimpleClient.class); private final boolean soKeepalive = true; private final boolean soReuseaddr = true; private final boolean tcpNodelay = true; private final int connTimeout = 5000; private final int soRcvbuf = 1024 * 128; private final int soSndbuf = 1024 * 128; private final String serverIP; private final int serverPort; private final HandlerContext handlerContext; private final Bootstrap bootstrap; private final NioEventLoopGroup eventLoopGroup; private ChannelFuture channelFuture; public SimpleClient(HandlerContext handlerContext, String ip, int port) { this.handlerContext = handlerContext; this.serverIP = ip; this.serverPort = port; bootstrap = new Bootstrap(); bootstrap.channel(NioSocketChannel.class); bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connTimeout); bootstrap.option(ChannelOption.SO_KEEPALIVE, this.soKeepalive); bootstrap.option(ChannelOption.SO_REUSEADDR, this.soReuseaddr); bootstrap.option(ChannelOption.TCP_NODELAY, this.tcpNodelay); bootstrap.option(ChannelOption.SO_RCVBUF, this.soRcvbuf); bootstrap.option(ChannelOption.SO_SNDBUF, this.soSndbuf); ChannelInitializer<SocketChannel> initializer = new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline cp = ch.pipeline(); cp.addLast(new MessageEncoder()); cp.addLast(new LengthFieldBasedFrameDecoder(1024*1024*10, 0, 4, 0, 0)); cp.addLast(new MessageDecoder()); cp.addLast(new IdleStateHandler(60, 0, 0)); cp.addLast(new ClientHandler(SimpleClient.this)); } }; eventLoopGroup = new NioEventLoopGroup(1, new DefaultThreadFactory(serverIP.substring(serverIP.lastIndexOf(".")+1)+"-"+serverPort+"-client-ip")); bootstrap.group(eventLoopGroup).handler(initializer); channelFuture = this.connect(); } private ChannelFuture connect() { try { ChannelFuture channelFuture = bootstrap.connect(new InetSocketAddress(serverIP, serverPort)); channelFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) throws Exception { if (channelFuture.isSuccess()) { logger.info("Connection " + channelFuture.channel() + " is well established"); } else { logger.warn(String.format("Connection get failed on %s due to %s", channelFuture.cause().getMessage(), channelFuture.cause())); } } }); logger.info("connect to " + getAddress()); return channelFuture; } catch (Exception e) { logger.error("Failed to connect to " + getAddress(), e); } return null; } private ChannelFuture getChannelFuture() { if(channelFuture != null) { if(channelFuture.isSuccess()) { if(channelFuture.channel().isActive()) { return channelFuture; }else { channelFuture.channel().close(); channelFuture = this.connect(); } } }else { channelFuture = this.connect(); } return null; } public void handleMessage(CallbackContext context, SimpleMessage message) { handlerContext.handleMessage(context, message); } public void sendMessage(SimpleMessage message, long timeout) throws Exception { this.sendMessage(null, null, message, timeout); } public void sendMessage(Channel channel, String allowOrigin, SimpleMessage message, long timeout) throws Exception { ChannelFuture channelFuture = getChannelFuture(); if (channelFuture != null) { try { logger.info("sendMessage message = {}", message.toString()); CallbackPool.put(message.getMsgid(), channel, allowOrigin, timeout); channelFuture.channel().writeAndFlush(message); } catch (Exception e) { throw new SimpleException(SimpleException.ExceptionType.connection, "Failed to transport", e); } } else { throw new SimpleException(SimpleException.ExceptionType.internal, "Socket channel is not well established"); } } public void tryToReconnect() { if(channelFuture != null) { if(channelFuture.isSuccess()) { channelFuture.channel().close(); logger.info("tryToReconnect close: {}", channelFuture); } } channelFuture = this.connect(); logger.info("tryToReconnect: {}", channelFuture); } public void shutdown() { if (eventLoopGroup != null) { eventLoopGroup.shutdownGracefully(); channelFuture = null; } } public String getAddress() { return serverIP + ":" + serverPort; } public boolean isClosed() { return channelFuture==null || !channelFuture.isSuccess() || !channelFuture.channel().isActive() || this.eventLoopGroup.isShutdown(); } }
16,761
https://github.com/pvicky9586/proyect_laravel7/blob/master/app/Http/Controllers/Livewire/AppMenu.php
Github Open Source
Open Source
MIT
2,020
proyect_laravel7
pvicky9586
PHP
Code
18
60
<?php namespace App\Http\Controllers\Livewire; use Livewire\Component; class AppMenu extends Component { public function render() { return view('livewire.app-menu'); } }
22,892
https://github.com/adrienemery/auv-control-ui/blob/master/src/views/Dashboard.vue
Github Open Source
Open Source
MIT
null
auv-control-ui
adrienemery
Vue
Code
722
2,804
<template> <div class="section"> <div class="columns"> <!-- Left Hand Side --> <div class="column is-half"> <!-- Top Buttons --> <div class="buttons" style="margin-bottom: 20px; margin-top: 5px"> <button class="button is-info" @click="startTrip">Start</button> <button class="button" @click='stop'>Pause</button> <button class="button" @click='resumeTrip'>Resume</button> <button class="button is-success is-pulled-right" @click="addWaypoint">+WP</button> <button class="button is-danger is-pulled-right" @click="removeWaypoint">-WP</button> <button class="button is-pulled-right" @click="clearTrip">Clear Trip</button> </div> <!-- Map --> <div ref="map" id="map"></div> </div> <!-- Right Hand Side --> <div class="column is-half"> <b-tabs v-model="activeTab"> <b-tab-item label="Charts"> <div class="chart"> <!-- Charts --> <line-chart :chart-data="plotData" :options="plotOptions" :height="200"/> <line-chart :chart-data="pidPlotData" :options="pidPlotOptions" :height="200"/> </div> </b-tab-item> <b-tab-item label="Camera"> <img :src="img" alt="" height="400px"> </b-tab-item> </b-tabs> </div> </div> </div> </template> <script> import { mapState, mapGetters } from "vuex" import LineChart from '@/components/LineChart' export default { name: "dashboard", components: { LineChart }, computed: { ...mapState([ 'img', 'currentPosition', 'auvData', 'navData', 'plotLabels', 'plotHeadingData', 'plotHeadingData', 'waypoint', 'trip', 'plotTargetHeadingData', 'plotHeadingErrorData', 'plotPidOutputData', 'heading', 'waypointCircleRadius', ]), ...mapGetters([ 'numCompletedWaypoints', ]), asvPosition() { return this.currentPosition }, }, data() { return { activeTab: 0, center: { lat: 49.2827, lng: -123.1207 }, showAsvMarker: true, showMarkerCircles: true, tripMarkers: [], tripCircles: [], plotData: null, pidPlotData: null, flagIcon: 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png', pidPlotOptions: { animation: false, responsive: true, maintainAspectRatio: false, backgroundColor: 'black', scales: { yAxes: [{ ticks: { beginAtZero: true, min: -100, stepSize: 25, max: 100 } }], } }, plotOptions: { animation: false, responsive: true, maintainAspectRatio: false, backgroundColor: 'black', scales: { yAxes: [{ ticks: { beginAtZero: true, min: 0, stepSize: 60, max: 360 } }], } }, } }, created () { this.getUserLocation() if (this.currentPosition) { this.center = this.currentPosition } }, mounted () { this.initMap() }, watch: { numCompletedWaypoints (newVal, oldVal) { for (var i=0; i < this.tripMarkers.length; i++) { // if we have completed this waypoint then we set a new icon // so its clear to visually determine which waypoints have been completed if (i < this.numCompletedWaypoints) { let marker = this.tripMarkers[i] if (marker.getIcon() !== this.flagIcon){ marker.setIcon(this.flagIcon) } } } }, trip (newVal, oldVal) { this.updateTrip() }, currentPosition (newVal, oldVal) { // set the map center to the ASV position the first time data comes throught if (oldVal === null) { this.map.setCenter(newVal) } }, heading (newVal, oldVal) { this.asvMarker.icon.rotation = newVal this.asvMarker.setIcon({ path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW, scale: 3, rotation: newVal }) }, asvPosition (newVal, oldVal) { this.asvMarker.setPosition(newVal) }, navData(newData, oldData) { this.plotData = { labels: this.plotLabels, backgroundColor: 'black', datasets: [ { fill: false, label: 'Target Heading', borderColor: 'blue', data: this.plotTargetHeadingData, pointRadius: 0, }, { fill: false, label: 'Heading', borderColor: 'green', data: this.plotHeadingData, pointRadius: 0, }, ] } this.pidPlotData = { labels: this.plotLabels, backgroundColor: 'black', datasets: [ { fill: false, label: 'PID Error', borderColor: 'red', data: this.plotHeadingErrorData, pointRadius: 0, }, { fill: false, label: 'PID Output', borderColor: 'green', data: this.plotPidOutputData, pointRadius: 0, }, ] } }, }, methods: { getUserLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function (position) { console.log(position) }) } else { console.log("Geolocation is not supported by this browser") } }, initMap() { this.map = new google.maps.Map(this.$refs.map, { zoom: 17, center: this.center, disableDefaultUI: true, zoomControl: true, }) let vm = this this.map.addListener('center_changed', function() { vm.updateMapCenter() }); this.asvMarker = new google.maps.Marker({ position: this.currentPosition, map: this.map, icon: { path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW, scale: 3, rotation: this.heading }, }) this.updateTrip() }, clearTrip() { this.deleteMarkers() this.$store.commit('CLEAR_TRIP') }, deleteMarkers() { for (var i = 0; i < this.tripMarkers.length; i++) { this.tripMarkers[i].setMap(null) } this.tripMarkers = [] for (var i = 0; i < this.tripCircles.length; i++) { this.tripCircles[i].setMap(null) } this.tripCircles = [] }, updateTrip() { // redraw the trip markers this.deleteMarkers() for (let i=0; i<this.trip.length; i++) { let waypoint = this.trip[i] let marker = new google.maps.Marker({ position: waypoint, draggable: true, map: this.map, label: (i + 1).toString() }) var circle = new google.maps.Circle({ strokeColor: '#FF0000', strokeOpacity: 0.8, strokeWeight: 1, fillColor: '#FF0000', fillOpacity: 0.35, map: this.map, center: waypoint, radius: this.waypointCircleRadius }) this.tripCircles.push(circle) this.tripMarkers.push(marker) let vm = this marker.addListener('dragend', function() { vm.updateTripMarker(i) }) } }, updateTripMarker(index) { this.trip[index] = this.tripMarkers[index].getPosition() this.tripCircles[index].setCenter(this.tripMarkers[index].getPosition()) }, addWaypoint() { // add a waypoint to the trip this.$store.commit('ADD_WAYPOINT', this.map.getCenter()) }, removeWaypoint() { // remove the most recetn waypoint to the trip this.$store.commit('REMOVE_WAYPOINT') }, updateMapCenter() { let center = this.map.getCenter() this.center.lat = center.lat() this.center.lng = center.lng() }, moveToWaypoint() { this.$wamp.call("nav.move_to_waypoint", [this.waypoint]) }, startTrip() { this.updateTrip() this.$wamp.call("nav.start_trip", [this.trip]) }, resumeTrip() { this.$wamp.call("nav.resume_trip") }, stop() { this.$wamp.call("nav.stop") }, } }; </script> <style scoped> #map { width: 100%; height: 400px; min-width:300px; background-color: grey; } .template { padding-top: 20px; } .chart { max-width: 100%; } .map-icon-label .map-icon { font-size: 8px; color: #FFFFFF; line-height: 10px; text-align: center; white-space: nowrap; } .section { padding-top: 24px; width: 100%; } </style>
30,354
https://github.com/kitsonk/swc/blob/master/ecmascript/minifier/tests/terser/compress/sequences/negate_iife_for/input.js
Github Open Source
Open Source
Apache-2.0, MIT
2,022
swc
kitsonk
JavaScript
Code
22
49
(function () {})(); for (i = 0; i < 5; i++) console.log(i); (function () {})(); for (; i < 10; i++) console.log(i);
40,325
https://github.com/aculclasure/code-journal/blob/master/go/exercism/go/linked-list/linked_list.go
Github Open Source
Open Source
MIT
null
code-journal
aculclasure
Go
Code
429
875
package linkedlist import "errors" // Node represents a node in the linked list. type Node struct { Val interface{} prev, next *Node } // Next returns the next node. func (e *Node) Next() *Node { return e.next } // Prev returns the previous node. func (e *Node) Prev() *Node { return e.prev } // ErrEmptyList is an error indicating a list operation // was performed against an empty list. var ErrEmptyList = errors.New("list cannot be empty") // List represents a doubly-linked list. type List struct { head, tail *Node } // NewList accepts a slice of items and returns a // doubly-linked list containing the items in the // same order. func NewList(args ...interface{}) *List { if len(args) == 0 { return &List{} } list := &List{} for _, v := range args { list.PushBack(v) } return list } // PushFront accepts an item v and pushes it to the front // of the linked list. func (l *List) PushFront(v interface{}) { n := &Node{next: l.head, Val: v} if l.head == nil { l.tail = n } else { l.head.prev = n } l.head = n } // PushBack accepts an item v and appends it to the // linked list. func (l *List) PushBack(v interface{}) { n := &Node{prev: l.tail, Val: v} if l.tail == nil { l.head = n } else { l.tail.next = n } l.tail = n } // PopFront removes and returns the first item of the linked // list or returns an error otherwise. func (l *List) PopFront() (interface{}, error) { firstNode := l.First() if firstNode == nil { return nil, ErrEmptyList } l.head = firstNode.Next() if l.head == nil { l.tail = nil } else { l.head.prev = nil } return firstNode.Val, nil } // PopBack removes and returns the last item of the linked // list or returns an error otherwise. func (l *List) PopBack() (interface{}, error) { lastNode := l.Last() if lastNode == nil { return nil, ErrEmptyList } l.tail = lastNode.Prev() if l.tail == nil { l.head = nil } else { l.tail.next = nil } return lastNode.Val, nil } // First returns the first Node in the list. func (l *List) First() *Node { return l.head } // Last returns the last Node in the list. func (l *List) Last() *Node { return l.tail } // Reverse reverses the items in the given list and returns // the reversed list. func (l *List) Reverse() { for e := l.First(); e != nil; e = e.Prev() { e.next, e.prev = e.prev, e.next } l.head, l.tail = l.tail, l.head }
9,797
https://github.com/sionescu/iolib/blob/master/src/multiplex/scheduler.lisp
Github Open Source
Open Source
MIT
2,023
iolib
sionescu
Common Lisp
Code
350
909
;;;; -*- Mode: Lisp; indent-tabs-mode: nil -*- ;;; ;;; --- Controlling the queue of scheduled events and running expired timers. ;;; ;;; Copyright (C) 2003 Zach Beane <xach@xach.com> ;;; ;;; 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. (in-package :iolib/multiplex) ;;; ;;; Public interface ;;; (defun schedule-timer (schedule timer) (priority-queue-insert schedule timer) (values timer)) (defun unschedule-timer (schedule timer) (priority-queue-remove schedule timer) (values timer)) (defun reschedule-timer (schedule timer) (incf (%timer-expire-time timer) (%timer-relative-time timer)) (priority-queue-insert schedule timer)) (defun reschedule-timer-relative-to-now (timer now) (setf (%timer-expire-time timer) (+ now (%timer-relative-time timer)))) ;;; ;;; The scheduler ;;; (defun peek-schedule (schedule) (priority-queue-maximum schedule)) (defun time-to-next-timer (schedule) (when-let ((timer (peek-schedule schedule))) (%timer-expire-time timer))) ;;; ;;; Expiring timers ;;; (defun dispatch-timer (timer) (funcall (%timer-function timer))) (defun timer-reschedulable-p (timer) (symbol-macrolet ((relative-time (%timer-relative-time timer)) (one-shot (%timer-one-shot timer))) (and relative-time (not one-shot)))) (defun expire-pending-timers (schedule now) (let ((expired-p nil) (timers-to-reschedule ())) (flet ((handle-expired-timer (timer) (when (timer-reschedulable-p timer) (push timer timers-to-reschedule)) (dispatch-timer timer)) (%return () (dolist (timer timers-to-reschedule) (reschedule-timer schedule timer)) (return* expired-p))) (loop (let ((next-timer (peek-schedule schedule))) (unless next-timer (%return)) (cond ((timer-expired-p next-timer now) (setf expired-p t) (handle-expired-timer (priority-queue-extract-maximum schedule))) (t (%return))))))))
48,060
https://github.com/DiKiALiF/sekolah/blob/master/kelas 12/laravel 8/resources/views/pembeli.blade.php
Github Open Source
Open Source
MIT
2,021
sekolah
DiKiALiF
Blade
Code
27
310
<html> <body> <h1>Tampil Data</h1> @foreach($pmbl as $data) <fieldset> <legend>Pembeli {{$data->id_pembeli}}</legend> <table> <tr><td>Id</td><td>:</td><td>{{$data->id_pembeli}}</td></tr> <tr><td>Nama Suplier</td><td>:</td><td>{{$data->nama}}</td></tr> <tr><td>Jenis Kelamin</td><td>:</td><td>{{$data->jns_kelamin}}</td></tr> <tr><td>Alamat</td><td>:</td><td>{{$data->alamat}}</td></tr> <tr><td>Kode Pos</td><td>:</td><td>{{$data->kode_pos}}</td></tr> <tr><td>Kota</td><td>:</td><td>{{$data->kota}}</td></tr> <tr><td>Tanggal Lahir</td><td>:</td><td>{{$data->tgl_lahir}}</td></tr> </table> </fieldset> @endforeach </body> </html>
11,014
https://github.com/desancheztorres/smc/blob/master/resources/views/admin/users/index.blade.php
Github Open Source
Open Source
MIT
null
smc
desancheztorres
PHP
Code
56
284
@extends('admin.layouts.app') @section('page_title', 'Users') @section('content') @include('admin.users.partials.header') <!-- CONTENT--> <div class="tab-content" id="pills-tabContent"> <div class="tab-pane fade show active" id="pills-blogs" role="tabpanel" aria-labelledby="pills-blogs-tab"> <section class="tables"> <div class="container-fluid"> <div class="row"> <div class="col"> <div class="card"> <div class="card-header d-flex align-items-center"> <h3 class="h4"> Blogs - List <span class="badge badge-primary">{{ $all_users }}</span> </h3> </div> <div class="card-body"> @include('admin.users.partials.list') </div> </div> </div> </div> </div> </section> </div> </div> @endsection
3,237
https://github.com/kupl/starlab-benchmarks/blob/master/Benchmarks_with_Functional_Bugs/Java/Bears-169/src/thirdeye/thirdeye-pinot/src/main/java/com/linkedin/thirdeye/completeness/checker/DataCompletenessJobRunner.java
Github Open Source
Open Source
MIT
null
starlab-benchmarks
kupl
Java
Code
385
1,924
package com.linkedin.thirdeye.completeness.checker; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Lists; import com.linkedin.thirdeye.anomaly.job.JobConstants.JobStatus; import com.linkedin.thirdeye.anomaly.job.JobRunner; import com.linkedin.thirdeye.anomaly.task.TaskConstants.TaskStatus; import com.linkedin.thirdeye.anomaly.task.TaskConstants.TaskType; import com.linkedin.thirdeye.datalayer.dto.AnomalyFunctionDTO; import com.linkedin.thirdeye.datalayer.dto.DatasetConfigDTO; import com.linkedin.thirdeye.datalayer.dto.JobDTO; import com.linkedin.thirdeye.datalayer.dto.TaskDTO; import com.linkedin.thirdeye.datasource.DAORegistry; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** job runner for data completeness job * */ public class DataCompletenessJobRunner implements JobRunner { private static final Logger LOG = LoggerFactory.getLogger(DataCompletenessJobRunner.class); private static final DAORegistry DAO_REGISTRY = DAORegistry.getInstance(); private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private DataCompletenessJobContext dataCompletenessJobContext; private DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyyMMddHHmm"); public DataCompletenessJobRunner(DataCompletenessJobContext dataCompletenessJobContext) { this.dataCompletenessJobContext = dataCompletenessJobContext; } @Override public void run() { DateTime now = new DateTime(); long checkDurationEndTime = now.getMillis(); long checkDurationStartTime = now.minus(TimeUnit.MILLISECONDS.convert( DataCompletenessConstants.LOOKBACK_TIME_DURATION, DataCompletenessConstants.LOOKBACK_TIMEUNIT)).getMillis(); String checkerEndTime = dateTimeFormatter.print(checkDurationEndTime); String checkerStartTime = dateTimeFormatter.print(checkDurationStartTime); String jobName = String.format("%s-%s-%s", TaskType.DATA_COMPLETENESS.toString(), checkerStartTime, checkerEndTime); dataCompletenessJobContext.setCheckDurationStartTime(checkDurationStartTime); dataCompletenessJobContext.setCheckDurationEndTime(checkDurationEndTime); dataCompletenessJobContext.setJobName(jobName); Set<String> datasetsToCheck = new HashSet<>(); for (DatasetConfigDTO datasetConfig : DAO_REGISTRY.getDatasetConfigDAO().findActiveRequiresCompletenessCheck()) { datasetsToCheck.add(datasetConfig.getDataset()); } for (AnomalyFunctionDTO anomalyFunction : DAO_REGISTRY.getAnomalyFunctionDAO().findAllActiveFunctions()) { if (anomalyFunction.isRequiresCompletenessCheck()) { datasetsToCheck.add(anomalyFunction.getCollection()); } } dataCompletenessJobContext.setDatasetsToCheck(Lists.newArrayList(datasetsToCheck)); // create data completeness job long jobExecutionId = createJob(); dataCompletenessJobContext.setJobExecutionId(jobExecutionId); // create data completeness tasks createTasks(); } public Long createJob() { Long jobExecutionId = null; try { LOG.info("Creating data completeness job"); JobDTO jobSpec = new JobDTO(); jobSpec.setJobName(dataCompletenessJobContext.getJobName()); jobSpec.setScheduleStartTime(System.currentTimeMillis()); jobSpec.setStatus(JobStatus.SCHEDULED); jobSpec.setTaskType(TaskType.DATA_COMPLETENESS); jobSpec.setConfigId(0); // Data completeness job does not have a config id jobExecutionId = DAO_REGISTRY.getJobDAO().save(jobSpec); LOG.info("Created JobSpec {} with jobExecutionId {}", jobSpec, jobExecutionId); } catch (Exception e) { LOG.error("Exception in creating data completeness job", e); } return jobExecutionId; } protected List<DataCompletenessTaskInfo> createDataCompletenessTasks(DataCompletenessJobContext dataCompletenessJobContext) { List<DataCompletenessTaskInfo> tasks = new ArrayList<>(); // create 1 task, which will get data and perform check DataCompletenessTaskInfo dataCompletenessCheck = new DataCompletenessTaskInfo(); dataCompletenessCheck.setDataCompletenessType(DataCompletenessConstants.DataCompletenessType.CHECKER); dataCompletenessCheck.setDataCompletenessStartTime(dataCompletenessJobContext.getCheckDurationStartTime()); dataCompletenessCheck.setDataCompletenessEndTime(dataCompletenessJobContext.getCheckDurationEndTime()); dataCompletenessCheck.setDatasetsToCheck(dataCompletenessJobContext.getDatasetsToCheck()); tasks.add(dataCompletenessCheck); // create 1 task, for cleanup DataCompletenessTaskInfo cleanup = new DataCompletenessTaskInfo(); cleanup.setDataCompletenessType(DataCompletenessConstants.DataCompletenessType.CLEANUP); tasks.add(cleanup); return tasks; } public List<Long> createTasks() { List<Long> taskIds = new ArrayList<>(); try { LOG.info("Creating data completeness checker tasks"); List<DataCompletenessTaskInfo> dataCompletenessTasks = createDataCompletenessTasks(dataCompletenessJobContext); LOG.info("DataCompleteness tasks {}", dataCompletenessTasks); for (DataCompletenessTaskInfo taskInfo : dataCompletenessTasks) { String taskInfoJson = null; try { taskInfoJson = OBJECT_MAPPER.writeValueAsString(taskInfo); } catch (JsonProcessingException e) { LOG.error("Exception when converting DataCompletenessTaskInfo {} to jsonString", taskInfo, e); } TaskDTO taskSpec = new TaskDTO(); taskSpec.setTaskType(TaskType.DATA_COMPLETENESS); taskSpec.setJobName(dataCompletenessJobContext.getJobName()); taskSpec.setStatus(TaskStatus.WAITING); taskSpec.setStartTime(System.currentTimeMillis()); taskSpec.setTaskInfo(taskInfoJson); taskSpec.setJobId(dataCompletenessJobContext.getJobExecutionId()); long taskId = DAO_REGISTRY.getTaskDAO().save(taskSpec); taskIds.add(taskId); LOG.info("Created dataCompleteness task {} with taskId {}", taskSpec, taskId); } } catch (Exception e) { LOG.error("Exception in creating data completeness tasks", e); } return taskIds; } }
15,595
https://github.com/ric2b/Vivaldi-browser/blob/master/update_notifier/thirdparty/wxWidgets/samples/drawing/drawing.cpp
Github Open Source
Open Source
BSD-3-Clause
2,022
Vivaldi-browser
ric2b
C++
Code
8,135
32,006
///////////////////////////////////////////////////////////////////////////// // Name: samples/drawing/drawing.cpp // Purpose: shows and tests wxDC features // Author: Robert Roebling // Modified by: // Created: 04/01/98 // Copyright: (c) Robert Roebling // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// // ============================================================================ // declarations // ============================================================================ // ---------------------------------------------------------------------------- // headers // ---------------------------------------------------------------------------- // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" // for all others, include the necessary headers (this file is usually all you // need because it includes almost all "standard" wxWidgets headers #ifndef WX_PRECOMP #include "wx/wx.h" #endif #include "wx/colordlg.h" #include "wx/image.h" #include "wx/artprov.h" #include "wx/dcbuffer.h" #include "wx/dcgraph.h" #include "wx/overlay.h" #include "wx/graphics.h" #include "wx/filename.h" #include "wx/metafile.h" #include "wx/settings.h" #if wxUSE_SVG #include "wx/dcsvg.h" #endif #if wxUSE_POSTSCRIPT #include "wx/dcps.h" #endif // ---------------------------------------------------------------------------- // resources // ---------------------------------------------------------------------------- // the application icon #ifndef wxHAS_IMAGES_IN_RESOURCES #include "../sample.xpm" #endif // Standard DC supports drawing with alpha on OSX and GTK3. #if defined(__WXOSX__) || defined(__WXGTK3__) #define wxDRAWING_DC_SUPPORTS_ALPHA 1 #else #define wxDRAWING_DC_SUPPORTS_ALPHA 0 #endif // __WXOSX__ || __WXGTK3__ // ---------------------------------------------------------------------------- // global variables // ---------------------------------------------------------------------------- static wxBitmap *gs_bmpNoMask = NULL, *gs_bmpWithColMask = NULL, *gs_bmpMask = NULL, *gs_bmpWithMask = NULL, *gs_bmp4 = NULL, *gs_bmp4_mono = NULL, *gs_bmp36 = NULL; // ---------------------------------------------------------------------------- // private classes // ---------------------------------------------------------------------------- // Define a new application type, each program should derive a class from wxApp class MyApp : public wxApp { public: // override base class virtuals // ---------------------------- // this one is called on application startup and is a good place for the app // initialization (doing it here and not in the ctor allows to have an error // return: if OnInit() returns false, the application terminates) virtual bool OnInit() wxOVERRIDE; virtual int OnExit() wxOVERRIDE { DeleteBitmaps(); return 0; } protected: void DeleteBitmaps(); bool LoadImages(); }; class MyFrame; // define a scrollable canvas for drawing onto class MyCanvas: public wxScrolledWindow { public: MyCanvas( MyFrame *parent ); void OnPaint(wxPaintEvent &event); void OnMouseMove(wxMouseEvent &event); void OnMouseDown(wxMouseEvent &event); void OnMouseUp(wxMouseEvent &event); void ToShow(int show) { m_show = show; Refresh(); } int GetPage() { return m_show; } // set or remove the clipping region void Clip(bool clip) { m_clip = clip; Refresh(); } #if wxUSE_GRAPHICS_CONTEXT bool HasRenderer() const { return m_renderer != NULL; } void UseGraphicRenderer(wxGraphicsRenderer* renderer); bool IsDefaultRenderer() const { if ( !m_renderer ) return false; return m_renderer == wxGraphicsRenderer::GetDefaultRenderer(); } wxGraphicsRenderer* GetRenderer() const { return m_renderer; } void EnableAntiAliasing(bool use) { m_useAntiAliasing = use; Refresh(); } #endif // wxUSE_GRAPHICS_CONTEXT void UseBuffer(bool use) { m_useBuffer = use; Refresh(); } void ShowBoundingBox(bool show) { m_showBBox = show; Refresh(); } void GetDrawingSize(int* width, int* height) const; void Draw(wxDC& dc); protected: enum DrawMode { Draw_Normal, Draw_Stretch }; void DrawTestLines( int x, int y, int width, wxDC &dc ); void DrawCrossHair(int x, int y, int width, int heigth, wxDC &dc); void DrawTestPoly(wxDC& dc); void DrawTestBrushes(wxDC& dc); void DrawText(wxDC& dc); void DrawImages(wxDC& dc, DrawMode mode); void DrawWithLogicalOps(wxDC& dc); #if wxDRAWING_DC_SUPPORTS_ALPHA || wxUSE_GRAPHICS_CONTEXT void DrawAlpha(wxDC& dc); #endif #if wxUSE_GRAPHICS_CONTEXT void DrawGraphics(wxGraphicsContext* gc); #endif void DrawRegions(wxDC& dc); void DrawCircles(wxDC& dc); void DrawSplines(wxDC& dc); void DrawDefault(wxDC& dc); void DrawGradients(wxDC& dc); void DrawSystemColours(wxDC& dc); void DrawRegionsHelper(wxDC& dc, wxCoord x, bool firstTime); private: MyFrame *m_owner; int m_show; wxBitmap m_smile_bmp; wxIcon m_std_icon; bool m_clip; wxOverlay m_overlay; bool m_rubberBand; wxPoint m_anchorpoint; wxPoint m_currentpoint; #if wxUSE_GRAPHICS_CONTEXT wxGraphicsRenderer* m_renderer; bool m_useAntiAliasing; #endif bool m_useBuffer; bool m_showBBox; wxCoord m_sizeX; wxCoord m_sizeY; wxDECLARE_EVENT_TABLE(); }; // Define a new frame type: this is going to be our main frame class MyFrame : public wxFrame { public: // ctor(s) MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size); // event handlers (these functions should _not_ be virtual) void OnQuit(wxCommandEvent& event); void OnAbout(wxCommandEvent& event); void OnClip(wxCommandEvent& event); #if wxUSE_GRAPHICS_CONTEXT void OnGraphicContextNone(wxCommandEvent& WXUNUSED(event)) { m_canvas->UseGraphicRenderer(NULL); } void OnGraphicContextDefault(wxCommandEvent& WXUNUSED(event)) { m_canvas->UseGraphicRenderer(wxGraphicsRenderer::GetDefaultRenderer()); } #if wxUSE_CAIRO void OnGraphicContextCairo(wxCommandEvent& WXUNUSED(event)) { m_canvas->UseGraphicRenderer(wxGraphicsRenderer::GetCairoRenderer()); } #endif // wxUSE_CAIRO #ifdef __WXMSW__ #if wxUSE_GRAPHICS_GDIPLUS void OnGraphicContextGDIPlus(wxCommandEvent& WXUNUSED(event)) { m_canvas->UseGraphicRenderer(wxGraphicsRenderer::GetGDIPlusRenderer()); } #endif #if wxUSE_GRAPHICS_DIRECT2D void OnGraphicContextDirect2D(wxCommandEvent& WXUNUSED(event)) { m_canvas->UseGraphicRenderer(wxGraphicsRenderer::GetDirect2DRenderer()); } #endif #endif // __WXMSW__ void OnAntiAliasing(wxCommandEvent& event) { m_canvas->EnableAntiAliasing(event.IsChecked()); } void OnAntiAliasingUpdateUI(wxUpdateUIEvent& event) { event.Enable(m_canvas->GetRenderer() != NULL); } #endif // wxUSE_GRAPHICS_CONTEXT void OnBuffer(wxCommandEvent& event); void OnCopy(wxCommandEvent& event); void OnSave(wxCommandEvent& event); void OnShow(wxCommandEvent &event); void OnOption(wxCommandEvent &event); void OnBoundingBox(wxCommandEvent& evt); void OnBoundingBoxUpdateUI(wxUpdateUIEvent& evt); #if wxUSE_COLOURDLG wxColour SelectColour(); #endif // wxUSE_COLOURDLG void PrepareDC(wxDC& dc) wxOVERRIDE; int m_backgroundMode; int m_textureBackground; wxMappingMode m_mapMode; double m_xUserScale; double m_yUserScale; int m_xLogicalOrigin; int m_yLogicalOrigin; bool m_xAxisReversed, m_yAxisReversed; #if wxUSE_DC_TRANSFORM_MATRIX wxDouble m_transform_dx; wxDouble m_transform_dy; wxDouble m_transform_scx; wxDouble m_transform_scy; wxDouble m_transform_rot; #endif // wxUSE_DC_TRANSFORM_MATRIX wxColour m_colourForeground, // these are _text_ colours m_colourBackground; wxBrush m_backgroundBrush; MyCanvas *m_canvas; wxMenuItem *m_menuItemUseDC; private: // any class wishing to process wxWidgets events must use this macro wxDECLARE_EVENT_TABLE(); }; // ---------------------------------------------------------------------------- // constants // ---------------------------------------------------------------------------- // IDs for the controls and the menu commands enum { // menu items File_Quit = wxID_EXIT, File_About = wxID_ABOUT, MenuShow_First = wxID_HIGHEST, File_ShowDefault = MenuShow_First, File_ShowText, File_ShowLines, File_ShowBrushes, File_ShowPolygons, File_ShowMask, File_ShowMaskStretch, File_ShowOps, File_ShowRegions, File_ShowCircles, File_ShowSplines, #if wxDRAWING_DC_SUPPORTS_ALPHA || wxUSE_GRAPHICS_CONTEXT File_ShowAlpha, #endif // wxDRAWING_DC_SUPPORTS_ALPHA || wxUSE_GRAPHICS_CONTEXT #if wxUSE_GRAPHICS_CONTEXT File_ShowGraphics, #endif File_ShowSystemColours, File_ShowGradients, MenuShow_Last = File_ShowGradients, #if wxUSE_GRAPHICS_CONTEXT File_DC, File_GC_Default, #if wxUSE_CAIRO File_GC_Cairo, #endif // wxUSE_CAIRO #ifdef __WXMSW__ #if wxUSE_GRAPHICS_GDIPLUS File_GC_GDIPlus, #endif #if wxUSE_GRAPHICS_DIRECT2D File_GC_Direct2D, #endif #endif // __WXMSW__ #endif // wxUSE_GRAPHICS_CONTEXT File_BBox, File_Clip, File_Buffer, #if wxUSE_GRAPHICS_CONTEXT File_AntiAliasing, #endif File_Copy, File_Save, MenuOption_First, MapMode_Text = MenuOption_First, MapMode_Lometric, MapMode_Twips, MapMode_Points, MapMode_Metric, UserScale_StretchHoriz, UserScale_ShrinkHoriz, UserScale_StretchVertic, UserScale_ShrinkVertic, UserScale_Restore, AxisMirror_Horiz, AxisMirror_Vertic, LogicalOrigin_MoveDown, LogicalOrigin_MoveUp, LogicalOrigin_MoveLeft, LogicalOrigin_MoveRight, LogicalOrigin_Set, LogicalOrigin_Restore, #if wxUSE_DC_TRANSFORM_MATRIX TransformMatrix_Set, TransformMatrix_Reset, #endif // wxUSE_DC_TRANSFORM_MATRIX #if wxUSE_COLOURDLG Colour_TextForeground, Colour_TextBackground, Colour_Background, #endif // wxUSE_COLOURDLG Colour_BackgroundMode, Colour_TextureBackgound, MenuOption_Last = Colour_TextureBackgound }; // ---------------------------------------------------------------------------- // event tables and other macros for wxWidgets // ---------------------------------------------------------------------------- // Create a new application object: this macro will allow wxWidgets to create // the application object during program execution (it's better than using a // static object for many reasons) and also declares the accessor function // wxGetApp() which will return the reference of the right type (i.e. MyApp and // not wxApp) wxIMPLEMENT_APP(MyApp); // ============================================================================ // implementation // ============================================================================ // ---------------------------------------------------------------------------- // the application class // ---------------------------------------------------------------------------- bool MyApp::LoadImages() { gs_bmpNoMask = new wxBitmap; gs_bmpWithColMask = new wxBitmap; gs_bmpMask = new wxBitmap; gs_bmpWithMask = new wxBitmap; gs_bmp4 = new wxBitmap; gs_bmp4_mono = new wxBitmap; gs_bmp36 = new wxBitmap; wxPathList pathList; // special hack for Unix in-tree sample build, don't do this in real // programs, use wxStandardPaths instead pathList.Add(wxFileName(argv[0]).GetPath()); pathList.Add("."); pathList.Add(".."); pathList.Add("../drawing"); pathList.Add("../../../samples/drawing"); wxString path = pathList.FindValidPath("pat4.bmp"); if ( !path ) return false; /* 4 colour bitmap */ gs_bmp4->LoadFile(path, wxBITMAP_TYPE_BMP); /* turn into mono-bitmap */ gs_bmp4_mono->LoadFile(path, wxBITMAP_TYPE_BMP); wxMask* mask4 = new wxMask(*gs_bmp4_mono, *wxBLACK); gs_bmp4_mono->SetMask(mask4); path = pathList.FindValidPath("pat36.bmp"); if ( !path ) return false; gs_bmp36->LoadFile(path, wxBITMAP_TYPE_BMP); wxMask* mask36 = new wxMask(*gs_bmp36, *wxBLACK); gs_bmp36->SetMask(mask36); path = pathList.FindValidPath("image.bmp"); if ( !path ) return false; gs_bmpNoMask->LoadFile(path, wxBITMAP_TYPE_BMP); gs_bmpWithMask->LoadFile(path, wxBITMAP_TYPE_BMP); gs_bmpWithColMask->LoadFile(path, wxBITMAP_TYPE_BMP); path = pathList.FindValidPath("mask.bmp"); if ( !path ) return false; gs_bmpMask->LoadFile(path, wxBITMAP_TYPE_BMP); wxMask *mask = new wxMask(*gs_bmpMask, *wxBLACK); gs_bmpWithMask->SetMask(mask); mask = new wxMask(*gs_bmpWithColMask, *wxWHITE); gs_bmpWithColMask->SetMask(mask); return true; } // `Main program' equivalent: the program execution "starts" here bool MyApp::OnInit() { if ( !wxApp::OnInit() ) return false; #if wxUSE_LIBPNG wxImage::AddHandler( new wxPNGHandler ); #endif // Create the main application window MyFrame *frame = new MyFrame("Drawing sample", wxDefaultPosition, wxSize(550, 840)); // Show it frame->Show(true); if ( !LoadImages() ) { wxLogError("Can't load one of the bitmap files needed " "for this sample from the current or parent " "directory, please copy them there."); // still continue, the sample can be used without images too if they're // missing for whatever reason } return true; } void MyApp::DeleteBitmaps() { wxDELETE(gs_bmpNoMask); wxDELETE(gs_bmpWithColMask); wxDELETE(gs_bmpMask); wxDELETE(gs_bmpWithMask); wxDELETE(gs_bmp4); wxDELETE(gs_bmp4_mono); wxDELETE(gs_bmp36); } // ---------------------------------------------------------------------------- // MyCanvas // ---------------------------------------------------------------------------- // the event tables connect the wxWidgets events with the functions (event // handlers) which process them. wxBEGIN_EVENT_TABLE(MyCanvas, wxScrolledWindow) EVT_PAINT (MyCanvas::OnPaint) EVT_MOTION (MyCanvas::OnMouseMove) EVT_LEFT_DOWN (MyCanvas::OnMouseDown) EVT_LEFT_UP (MyCanvas::OnMouseUp) wxEND_EVENT_TABLE() #include "smile.xpm" MyCanvas::MyCanvas(MyFrame *parent) : wxScrolledWindow(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxHSCROLL | wxVSCROLL) { m_owner = parent; m_show = File_ShowDefault; m_smile_bmp = wxBitmap(smile_xpm); m_std_icon = wxArtProvider::GetIcon(wxART_INFORMATION); m_clip = false; m_rubberBand = false; #if wxUSE_GRAPHICS_CONTEXT m_renderer = NULL; m_useAntiAliasing = true; #endif m_useBuffer = false; m_showBBox = false; m_sizeX = 0; m_sizeY = 0; } void MyCanvas::DrawTestBrushes(wxDC& dc) { static const wxCoord WIDTH = 200; static const wxCoord HEIGHT = 80; wxCoord x = 10, y = 10; dc.SetBrush(*wxGREEN_BRUSH); dc.DrawRectangle(x, y, WIDTH, HEIGHT); dc.DrawText("Solid green", x + 10, y + 10); y += HEIGHT; dc.SetBrush(wxBrush(*wxRED, wxBRUSHSTYLE_CROSSDIAG_HATCH)); dc.DrawRectangle(x, y, WIDTH, HEIGHT); dc.DrawText("Diagonally hatched red", x + 10, y + 10); y += HEIGHT; dc.SetBrush(wxBrush(*wxBLUE, wxBRUSHSTYLE_CROSS_HATCH)); dc.DrawRectangle(x, y, WIDTH, HEIGHT); dc.DrawText("Cross hatched blue", x + 10, y + 10); y += HEIGHT; dc.SetBrush(wxBrush(*wxCYAN, wxBRUSHSTYLE_VERTICAL_HATCH)); dc.DrawRectangle(x, y, WIDTH, HEIGHT); dc.DrawText("Vertically hatched cyan", x + 10, y + 10); y += HEIGHT; dc.SetBrush(wxBrush(*wxBLACK, wxBRUSHSTYLE_HORIZONTAL_HATCH)); dc.DrawRectangle(x, y, WIDTH, HEIGHT); dc.DrawText("Horizontally hatched black", x + 10, y + 10); y += HEIGHT; dc.SetBrush(wxBrush(*gs_bmpMask)); dc.DrawRectangle(x, y, WIDTH, HEIGHT); dc.DrawText("Stipple mono", x + 10, y + 10); y += HEIGHT; dc.SetBrush(wxBrush(*gs_bmpNoMask)); dc.DrawRectangle(x, y, WIDTH, HEIGHT); dc.DrawText("Stipple colour", x + 10, y + 10); } void MyCanvas::DrawTestPoly(wxDC& dc) { wxBrush brushHatch(*wxRED, wxBRUSHSTYLE_FDIAGONAL_HATCH); dc.SetBrush(brushHatch); wxPoint star[5]; star[0] = wxPoint(100, 60); star[1] = wxPoint(60, 150); star[2] = wxPoint(160, 100); star[3] = wxPoint(40, 100); star[4] = wxPoint(140, 150); dc.DrawText("You should see two (irregular) stars below, the left one " "hatched", 10, 10); dc.DrawText("except for the central region and the right " "one entirely hatched", 10, 30); dc.DrawText("The third star only has a hatched outline", 10, 50); dc.DrawPolygon(WXSIZEOF(star), star, 0, 30); dc.DrawPolygon(WXSIZEOF(star), star, 160, 30, wxWINDING_RULE); wxBrush brushHatchGreen(*wxGREEN, wxBRUSHSTYLE_FDIAGONAL_HATCH); dc.SetBrush(brushHatchGreen); wxPoint star2[10]; star2[0] = wxPoint(0, 100); star2[1] = wxPoint(-59, -81); star2[2] = wxPoint(95, 31); star2[3] = wxPoint(-95, 31); star2[4] = wxPoint(59, -81); star2[5] = wxPoint(0, 80); star2[6] = wxPoint(-47, -64); star2[7] = wxPoint(76, 24); star2[8] = wxPoint(-76, 24); star2[9] = wxPoint(47, -64); int count[2] = {5, 5}; dc.DrawPolyPolygon(WXSIZEOF(count), count, star2, 450, 150); } void MyCanvas::DrawTestLines( int x, int y, int width, wxDC &dc ) { dc.SetPen( wxPen( *wxBLACK, width ) ); dc.SetBrush( *wxWHITE_BRUSH ); dc.DrawText(wxString::Format("Testing lines of width %d", width), x + 10, y - 10); dc.DrawRectangle( x+10, y+10, 100, 190 ); dc.DrawText("Solid/dot/short dash/long dash/dot dash", x + 150, y + 10); dc.SetPen( wxPen( *wxBLACK, width ) ); dc.DrawLine( x+20, y+20, 100, y+20 ); dc.SetPen( wxPen( *wxBLACK, width, wxPENSTYLE_DOT) ); dc.DrawLine( x+20, y+30, 100, y+30 ); dc.SetPen( wxPen( *wxBLACK, width, wxPENSTYLE_SHORT_DASH) ); dc.DrawLine( x+20, y+40, 100, y+40 ); dc.SetPen( wxPen( *wxBLACK, width, wxPENSTYLE_LONG_DASH) ); dc.DrawLine( x+20, y+50, 100, y+50 ); dc.SetPen( wxPen( *wxBLACK, width, wxPENSTYLE_DOT_DASH) ); dc.DrawLine( x+20, y+60, 100, y+60 ); dc.DrawText("Hatches", x + 150, y + 70); dc.SetPen( wxPen( *wxBLACK, width, wxPENSTYLE_BDIAGONAL_HATCH) ); dc.DrawLine( x+20, y+70, 100, y+70 ); dc.SetPen( wxPen( *wxBLACK, width, wxPENSTYLE_CROSSDIAG_HATCH) ); dc.DrawLine( x+20, y+80, 100, y+80 ); dc.SetPen( wxPen( *wxBLACK, width, wxPENSTYLE_FDIAGONAL_HATCH) ); dc.DrawLine( x+20, y+90, 100, y+90 ); dc.SetPen( wxPen( *wxBLACK, width, wxPENSTYLE_CROSS_HATCH) ); dc.DrawLine( x+20, y+100, 100, y+100 ); dc.SetPen( wxPen( *wxBLACK, width, wxPENSTYLE_HORIZONTAL_HATCH) ); dc.DrawLine( x+20, y+110, 100, y+110 ); dc.SetPen( wxPen( *wxBLACK, width, wxPENSTYLE_VERTICAL_HATCH) ); dc.DrawLine( x+20, y+120, 100, y+120 ); dc.DrawText("User dash", x + 150, y + 140); wxPen ud( *wxBLACK, width, wxPENSTYLE_USER_DASH ); wxDash dash1[6]; dash1[0] = 8; // Long dash <---------+ dash1[1] = 2; // Short gap | dash1[2] = 3; // Short dash | dash1[3] = 2; // Short gap | dash1[4] = 3; // Short dash | dash1[5] = 2; // Short gap and repeat + ud.SetDashes( 6, dash1 ); dc.SetPen( ud ); dc.DrawLine( x+20, y+140, 100, y+140 ); dash1[0] = 5; // Make first dash shorter ud.SetDashes( 6, dash1 ); dc.SetPen( ud ); dc.DrawLine( x+20, y+150, 100, y+150 ); dash1[2] = 5; // Make second dash longer ud.SetDashes( 6, dash1 ); dc.SetPen( ud ); dc.DrawLine( x+20, y+160, 100, y+160 ); dash1[4] = 5; // Make third dash longer ud.SetDashes( 6, dash1 ); dc.SetPen( ud ); dc.DrawLine( x+20, y+170, 100, y+170 ); wxPen penWithCap(*wxBLACK, width); dc.SetPen(penWithCap); dc.DrawText("Default cap", x+270, y+40); dc.DrawLine( x+200, y+50, x+250, y+50); penWithCap.SetCap(wxCAP_BUTT); dc.SetPen(penWithCap); dc.DrawText("Butt ", x+270, y+60); dc.DrawLine( x+200, y+70, x+250, y+70); penWithCap.SetCap(wxCAP_ROUND); dc.SetPen(penWithCap); dc.DrawText("Round cap", x+270, y+80); dc.DrawLine( x+200, y+90, x+250, y+90); penWithCap.SetCap(wxCAP_PROJECTING); dc.SetPen(penWithCap); dc.DrawText("Projecting cap", x+270, y+100); dc.DrawLine( x+200, y+110, x+250, y+110); } void MyCanvas::DrawCrossHair(int x, int y, int width, int heigth, wxDC &dc) { dc.DrawText("Cross hair", x + 10, y + 10); dc.SetClippingRegion(x, y, width, heigth); dc.SetPen(wxPen(*wxBLUE, 2)); dc.CrossHair(x + width / 2, y + heigth / 2); dc.DestroyClippingRegion(); } void MyCanvas::DrawDefault(wxDC& dc) { // Draw circle centered at the origin, then flood fill it with a different // color. Done with a wxMemoryDC because Blit (used by generic // wxDoFloodFill) from a window that is being painted gives unpredictable // results on wxGTK { wxImage img(21, 21, false); img.Clear(1); wxBitmap bmp(img); { wxMemoryDC mdc(bmp); mdc.SetBrush(dc.GetBrush()); mdc.SetPen(dc.GetPen()); mdc.DrawCircle(10, 10, 10); wxColour c; if (mdc.GetPixel(11, 11, &c)) { mdc.SetBrush(wxColour(128, 128, 0)); mdc.FloodFill(11, 11, c, wxFLOOD_SURFACE); } } bmp.SetMask(new wxMask(bmp, wxColour(1, 1, 1))); dc.DrawBitmap(bmp, -10, -10, true); } dc.DrawCheckMark(5, 80, 15, 15); dc.DrawCheckMark(25, 80, 30, 30); dc.DrawCheckMark(60, 80, 60, 60); // this is the test for "blitting bitmap into DC damages selected brush" bug wxCoord rectSize = m_std_icon.GetWidth() + 10; wxCoord x = 100; dc.SetPen(*wxTRANSPARENT_PEN); dc.SetBrush( *wxGREEN_BRUSH ); dc.DrawRectangle(x, 10, rectSize, rectSize); dc.DrawBitmap(m_std_icon, x + 5, 15, true); x += rectSize + 10; dc.DrawRectangle(x, 10, rectSize, rectSize); dc.DrawIcon(m_std_icon, x + 5, 15); x += rectSize + 10; dc.DrawRectangle(x, 10, rectSize, rectSize); // test for "transparent" bitmap drawing (it intersects with the last // rectangle above) //dc.SetBrush( *wxTRANSPARENT_BRUSH ); if (m_smile_bmp.IsOk()) dc.DrawBitmap(m_smile_bmp, x + rectSize - 20, rectSize - 10, true); dc.SetBrush( *wxBLACK_BRUSH ); dc.DrawRectangle( 0, 160, 1000, 300 ); // draw lines wxBitmap bitmap(20,70); wxMemoryDC memdc; memdc.SelectObject( bitmap ); memdc.SetBrush( *wxBLACK_BRUSH ); memdc.SetPen( *wxWHITE_PEN ); memdc.DrawRectangle(0,0,20,70); memdc.DrawLine( 10,0,10,70 ); // to the right wxPen pen = *wxRED_PEN; memdc.SetPen(pen); memdc.DrawLine( 10, 5,10, 5 ); memdc.DrawLine( 10,10,11,10 ); memdc.DrawLine( 10,15,12,15 ); memdc.DrawLine( 10,20,13,20 ); /* memdc.SetPen(*wxRED_PEN); memdc.DrawLine( 12, 5,12, 5 ); memdc.DrawLine( 12,10,13,10 ); memdc.DrawLine( 12,15,14,15 ); memdc.DrawLine( 12,20,15,20 ); */ // same to the left memdc.DrawLine( 10,25,10,25 ); memdc.DrawLine( 10,30, 9,30 ); memdc.DrawLine( 10,35, 8,35 ); memdc.DrawLine( 10,40, 7,40 ); // XOR draw lines dc.SetPen(*wxWHITE_PEN); memdc.SetLogicalFunction( wxINVERT ); memdc.SetPen( *wxWHITE_PEN ); memdc.DrawLine( 10,50,10,50 ); memdc.DrawLine( 10,55,11,55 ); memdc.DrawLine( 10,60,12,60 ); memdc.DrawLine( 10,65,13,65 ); memdc.DrawLine( 12,50,12,50 ); memdc.DrawLine( 12,55,13,55 ); memdc.DrawLine( 12,60,14,60 ); memdc.DrawLine( 12,65,15,65 ); memdc.SelectObject( wxNullBitmap ); dc.DrawBitmap( bitmap, 10, 170 ); wxImage image = bitmap.ConvertToImage(); image.Rescale( 60,210 ); bitmap = wxBitmap(image); dc.DrawBitmap( bitmap, 50, 170 ); // test the rectangle outline drawing - there should be one pixel between // the rect and the lines dc.SetPen(*wxWHITE_PEN); dc.SetBrush( *wxTRANSPARENT_BRUSH ); dc.DrawRectangle(150, 170, 49, 29); dc.DrawRectangle(200, 170, 49, 29); dc.SetPen(*wxWHITE_PEN); dc.DrawLine(250, 210, 250, 170); dc.DrawLine(260, 200, 150, 200); // test the rectangle filled drawing - there should be one pixel between // the rect and the lines dc.SetPen(*wxTRANSPARENT_PEN); dc.SetBrush( *wxWHITE_BRUSH ); dc.DrawRectangle(300, 170, 49, 29); dc.DrawRectangle(350, 170, 49, 29); dc.SetPen(*wxWHITE_PEN); dc.DrawLine(400, 170, 400, 210); dc.DrawLine(300, 200, 410, 200); // a few more tests of this kind dc.SetPen(*wxRED_PEN); dc.SetBrush( *wxWHITE_BRUSH ); dc.DrawRectangle(300, 220, 1, 1); dc.DrawRectangle(310, 220, 2, 2); dc.DrawRectangle(320, 220, 3, 3); dc.DrawRectangle(330, 220, 4, 4); dc.SetPen(*wxTRANSPARENT_PEN); dc.SetBrush( *wxWHITE_BRUSH ); dc.DrawRectangle(300, 230, 1, 1); dc.DrawRectangle(310, 230, 2, 2); dc.DrawRectangle(320, 230, 3, 3); dc.DrawRectangle(330, 230, 4, 4); // and now for filled rect with outline dc.SetPen(*wxRED_PEN); dc.SetBrush( *wxWHITE_BRUSH ); dc.DrawRectangle(500, 170, 49, 29); dc.DrawRectangle(550, 170, 49, 29); dc.SetPen(*wxWHITE_PEN); dc.DrawLine(600, 170, 600, 210); dc.DrawLine(500, 200, 610, 200); // test the rectangle outline drawing - there should be one pixel between // the rect and the lines dc.SetPen(*wxWHITE_PEN); dc.SetBrush( *wxTRANSPARENT_BRUSH ); dc.DrawRoundedRectangle(150, 270, 49, 29, 6); dc.DrawRoundedRectangle(200, 270, 49, 29, 6); dc.SetPen(*wxWHITE_PEN); dc.DrawLine(250, 270, 250, 310); dc.DrawLine(150, 300, 260, 300); // test the rectangle filled drawing - there should be one pixel between // the rect and the lines dc.SetPen(*wxTRANSPARENT_PEN); dc.SetBrush( *wxWHITE_BRUSH ); dc.DrawRoundedRectangle(300, 270, 49, 29, 6); dc.DrawRoundedRectangle(350, 270, 49, 29, 6); dc.SetPen(*wxWHITE_PEN); dc.DrawLine(400, 270, 400, 310); dc.DrawLine(300, 300, 410, 300); // Added by JACS to demonstrate bizarre behaviour. // With a size of 70, we get a missing red RHS, // and the height is too small, so we get yellow // showing. With a size of 40, it draws as expected: // it just shows a white rectangle with red outline. int totalWidth = 70; int totalHeight = 70; wxBitmap bitmap2(totalWidth, totalHeight); wxMemoryDC memdc2; memdc2.SelectObject(bitmap2); memdc2.SetBackground(*wxYELLOW_BRUSH); memdc2.Clear(); // Now draw a white rectangle with red outline. It should // entirely eclipse the yellow background. memdc2.SetPen(*wxRED_PEN); memdc2.SetBrush(*wxWHITE_BRUSH); memdc2.DrawRectangle(0, 0, totalWidth, totalHeight); memdc2.SetPen(wxNullPen); memdc2.SetBrush(wxNullBrush); memdc2.SelectObject(wxNullBitmap); dc.DrawBitmap(bitmap2, 500, 270); // Repeat, but draw directly on dc // Draw a yellow rectangle filling the bitmap x = 600; int y = 270; dc.SetPen(*wxYELLOW_PEN); dc.SetBrush(*wxYELLOW_BRUSH); dc.DrawRectangle(x, y, totalWidth, totalHeight); // Now draw a white rectangle with red outline. It should // entirely eclipse the yellow background. dc.SetPen(*wxRED_PEN); dc.SetBrush(*wxWHITE_BRUSH); dc.DrawRectangle(x, y, totalWidth, totalHeight); } void MyCanvas::DrawText(wxDC& dc) { // set underlined font for testing dc.SetFont( wxFontInfo(12).Family(wxFONTFAMILY_MODERN).Underlined() ); dc.DrawText( "This is text", 110, 10 ); dc.DrawRotatedText( "That is text", 20, 10, -45 ); // use wxSWISS_FONT and not wxNORMAL_FONT as the latter can't be rotated // under MSW (it is not TrueType) dc.SetFont( *wxSWISS_FONT ); wxString text; dc.SetBackgroundMode(wxBRUSHSTYLE_TRANSPARENT); for ( int n = -180; n < 180; n += 30 ) { text.Printf(" %d rotated text", n); dc.DrawRotatedText(text , 400, 400, n); } dc.SetFont( wxFontInfo(18).Family(wxFONTFAMILY_SWISS) ); dc.DrawText( "This is Swiss 18pt text.", 110, 40 ); wxCoord length; wxCoord height; wxCoord descent; dc.GetTextExtent( "This is Swiss 18pt text.", &length, &height, &descent ); text.Printf( "Dimensions are length %d, height %d, descent %d", length, height, descent ); dc.DrawText( text, 110, 80 ); text.Printf( "CharHeight() returns: %d", dc.GetCharHeight() ); dc.DrawText( text, 110, 120 ); dc.DrawRectangle( 100, 40, 4, height ); // test the logical function effect wxCoord y = 150; dc.SetLogicalFunction(wxINVERT); // text drawing should ignore logical function dc.DrawText( "There should be a text below", 110, y ); dc.DrawRectangle( 110, y, 100, height ); y += height; dc.DrawText( "Visible text", 110, y ); dc.DrawRectangle( 110, y, 100, height ); dc.DrawText( "Visible text", 110, y ); dc.DrawRectangle( 110, y, 100, height ); dc.SetLogicalFunction(wxCOPY); y += height; dc.DrawRectangle( 110, y, 100, height ); dc.DrawText( "Another visible text", 110, y ); y += height; dc.DrawText("And\nmore\ntext on\nmultiple\nlines", 110, y); y += 5*height; dc.SetTextForeground(*wxBLUE); dc.DrawRotatedText("Rotated text\ncan have\nmultiple lines\nas well", 110, y, 15); y += 7*height; dc.SetFont(wxFontInfo(12).Family(wxFONTFAMILY_TELETYPE)); dc.SetTextForeground(wxColour(150, 75, 0)); dc.DrawText("And some text with tab characters:\n123456789012345678901234567890\n\taa\tbbb\tcccc", 10, y); } static const struct { wxString name; wxRasterOperationMode rop; } rasterOperations[] = { { "wxAND", wxAND }, { "wxAND_INVERT", wxAND_INVERT }, { "wxAND_REVERSE", wxAND_REVERSE }, { "wxCLEAR", wxCLEAR }, { "wxCOPY", wxCOPY }, { "wxEQUIV", wxEQUIV }, { "wxINVERT", wxINVERT }, { "wxNAND", wxNAND }, { "wxNO_OP", wxNO_OP }, { "wxOR", wxOR }, { "wxOR_INVERT", wxOR_INVERT }, { "wxOR_REVERSE", wxOR_REVERSE }, { "wxSET", wxSET }, { "wxSRC_INVERT", wxSRC_INVERT }, { "wxXOR", wxXOR }, }; void MyCanvas::DrawImages(wxDC& dc, DrawMode mode) { dc.DrawText("original image", 0, 0); dc.DrawBitmap(*gs_bmpNoMask, 0, 20, 0); dc.DrawText("with colour mask", 0, 100); dc.DrawBitmap(*gs_bmpWithColMask, 0, 120, true); dc.DrawText("the mask image", 0, 200); dc.DrawBitmap(*gs_bmpMask, 0, 220, 0); dc.DrawText("masked image", 0, 300); dc.DrawBitmap(*gs_bmpWithMask, 0, 320, true); int cx = gs_bmpWithColMask->GetWidth(), cy = gs_bmpWithColMask->GetHeight(); wxMemoryDC memDC; for ( size_t n = 0; n < WXSIZEOF(rasterOperations); n++ ) { wxCoord x = 120 + 150*(n%4), y = 20 + 100*(n/4); dc.DrawText(rasterOperations[n].name, x, y - 20); memDC.SelectObject(*gs_bmpWithColMask); if ( mode == Draw_Stretch ) { dc.StretchBlit(x, y, cx, cy, &memDC, 0, 0, cx/2, cy/2, rasterOperations[n].rop, true); } else { dc.Blit(x, y, cx, cy, &memDC, 0, 0, rasterOperations[n].rop, true); } } } void MyCanvas::DrawWithLogicalOps(wxDC& dc) { static const wxCoord w = 60; static const wxCoord h = 60; // reuse the text colour here dc.SetPen(wxPen(m_owner->m_colourForeground)); dc.SetBrush(*wxTRANSPARENT_BRUSH); size_t n; for ( n = 0; n < WXSIZEOF(rasterOperations); n++ ) { wxCoord x = 20 + 150*(n%4), y = 20 + 100*(n/4); dc.DrawText(rasterOperations[n].name, x, y - 20); dc.SetLogicalFunction(rasterOperations[n].rop); dc.DrawRectangle(x, y, w, h); dc.DrawLine(x, y, x + w, y + h); dc.DrawLine(x + w, y, x, y + h); } // now some filled rectangles dc.SetBrush(wxBrush(m_owner->m_colourForeground)); for ( n = 0; n < WXSIZEOF(rasterOperations); n++ ) { wxCoord x = 20 + 150*(n%4), y = 500 + 100*(n/4); dc.DrawText(rasterOperations[n].name, x, y - 20); dc.SetLogicalFunction(rasterOperations[n].rop); dc.DrawRectangle(x, y, w, h); } } #if wxDRAWING_DC_SUPPORTS_ALPHA || wxUSE_GRAPHICS_CONTEXT void MyCanvas::DrawAlpha(wxDC& dc) { wxDouble margin = 20 ; wxDouble width = 180 ; wxDouble radius = 30 ; dc.SetPen( wxPen( wxColour( 128, 0, 0 ), 12 )); dc.SetBrush(*wxRED_BRUSH); wxRect r(margin,margin+width*0.66,width,width) ; dc.DrawRoundedRectangle( r.x, r.y, r.width, r.width, radius ) ; dc.SetPen( wxPen( wxColour( 0, 0, 128 ), 12)); dc.SetBrush( wxColour(0, 0, 255, 192) ); r.Offset( width * 0.8 , - width * 0.66 ) ; dc.DrawRoundedRectangle( r.x, r.y, r.width, r.width, radius ) ; dc.SetPen( wxPen( wxColour( 128, 128, 0 ), 12)); dc.SetBrush( wxBrush( wxColour( 192, 192, 0, 192))); r.Offset( width * 0.8 , width *0.5 ) ; dc.DrawRoundedRectangle( r.x, r.y, r.width, r.width, radius ) ; dc.SetPen( *wxTRANSPARENT_PEN ) ; dc.SetBrush( wxBrush( wxColour(255,255,128,128) ) ); dc.DrawRoundedRectangle( 0 , margin + width / 2 , width * 3 , 100 , radius) ; dc.SetTextBackground( wxColour(160, 192, 160, 160) ); dc.SetTextForeground( wxColour(255, 128, 128, 128) ); dc.SetFont( wxFontInfo(40).Family(wxFONTFAMILY_SWISS).Italic() ); dc.DrawText( "Hello!", 120, 80 ); } #endif // wxDRAWING_DC_SUPPORTS_ALPHA || wxUSE_GRAPHICS_CONTEXT #if wxUSE_GRAPHICS_CONTEXT const int BASE = 80.0; const int BASE2 = BASE/2; const int BASE4 = BASE/4; // modeled along Robin Dunn's GraphicsContext.py sample void MyCanvas::DrawGraphics(wxGraphicsContext* gc) { wxFont font = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT); gc->SetFont(font,*wxBLACK); // make a path that contains a circle and some lines, centered at 0,0 wxGraphicsPath path = gc->CreatePath() ; path.AddCircle( 0, 0, BASE2 ); path.MoveToPoint(0, -BASE2); path.AddLineToPoint(0, BASE2); path.MoveToPoint(-BASE2, 0); path.AddLineToPoint(BASE2, 0); path.CloseSubpath(); path.AddRectangle(-BASE4, -BASE4/2, BASE2, BASE4); // Now use that path to demonstrate various capabilities of the graphics context gc->PushState(); // save current translation/scale/other state gc->Translate(60, 75); // reposition the context origin gc->SetPen(wxPen("navy")); gc->SetBrush(wxBrush("pink")); for( int i = 0 ; i < 3 ; ++i ) { wxString label; switch( i ) { case 0 : label = "StrokePath"; break; case 1 : label = "FillPath"; break; case 2 : label = "DrawPath"; break; } wxDouble w, h; gc->GetTextExtent(label, &w, &h, NULL, NULL); gc->DrawText(label, -w/2, -BASE2-h-4); switch( i ) { case 0 : gc->StrokePath(path); break; case 1 : gc->FillPath(path); break; case 2 : gc->DrawPath(path); break; } gc->Translate(2*BASE, 0); } gc->PopState(); // restore saved state gc->PushState(); // save it again gc->Translate(60, 200); // offset to the lower part of the window gc->DrawText("Scale", 0, -BASE2); gc->Translate(0, 20); gc->SetBrush(wxBrush(wxColour(178, 34, 34, 128)));// 128 == half transparent for( int i = 0 ; i < 8 ; ++i ) { gc->Scale(1.08, 1.08); // increase scale by 8% gc->Translate(5,5); gc->DrawPath(path); } gc->PopState(); // restore saved state gc->PushState(); // save it again gc->Translate(400, 200); gc->DrawText("Rotate", 0, -BASE2); // Move the origin over to the next location gc->Translate(0, 75); // draw our path again, rotating it about the central point, // and changing colors as we go for ( int angle = 0 ; angle < 360 ; angle += 30 ) { gc->PushState(); // save this new current state so we can // pop back to it at the end of the loop wxImage::RGBValue val = wxImage::HSVtoRGB(wxImage::HSVValue(angle / 360.0, 1, 1)); gc->SetBrush(wxBrush(wxColour(val.red, val.green, val.blue, 64))); gc->SetPen(wxPen(wxColour(val.red, val.green, val.blue, 128))); // use translate to artfully reposition each drawn path gc->Translate(1.5 * BASE2 * cos(wxDegToRad(angle)), 1.5 * BASE2 * sin(wxDegToRad(angle))); // use Rotate to rotate the path gc->Rotate(wxDegToRad(angle)); // now draw it gc->DrawPath(path); gc->PopState(); } gc->PopState(); gc->PushState(); gc->Translate(60, 400); const wxString labelText("Scaled smiley inside a square"); gc->DrawText(labelText, 0, 0); // Center a bitmap horizontally wxDouble textWidth; gc->GetTextExtent(labelText, &textWidth, NULL); const wxDouble rectWidth = 100; wxDouble x0 = (textWidth - rectWidth) / 2; gc->DrawRectangle(x0, BASE2, rectWidth, 100); gc->DrawBitmap(m_smile_bmp, x0, BASE2, rectWidth, 100); gc->PopState(); // Draw graphics bitmap and its subbitmap gc->PushState(); gc->Translate(300, 400); gc->DrawText("Smiley as a graphics bitmap", 0, 0); wxGraphicsBitmap gbmp1 = gc->CreateBitmap(m_smile_bmp); gc->DrawBitmap(gbmp1, 0, BASE2, 50, 50); int bmpw = m_smile_bmp.GetWidth(); int bmph = m_smile_bmp.GetHeight(); wxGraphicsBitmap gbmp2 = gc->CreateSubBitmap(gbmp1, 0, bmph/5, bmpw/2, bmph/2); gc->DrawBitmap(gbmp2, 80, BASE2, 50, 50*(bmph/2)/(bmpw/2)); gc->PopState(); } #endif // wxUSE_GRAPHICS_CONTEXT void MyCanvas::DrawCircles(wxDC& dc) { int x = 100, y = 100, r = 20; dc.SetPen( *wxRED_PEN ); dc.SetBrush( *wxGREEN_BRUSH ); dc.DrawText("Some circles", 0, y); dc.DrawCircle(x, y, r); dc.DrawCircle(x + 2*r, y, r); dc.DrawCircle(x + 4*r, y, r); y += 2*r; dc.DrawText("And ellipses", 0, y); dc.DrawEllipse(x - r, y, 2*r, r); dc.DrawEllipse(x + r, y, 2*r, r); dc.DrawEllipse(x + 3*r, y, 2*r, r); y += 2*r; dc.DrawText("And arcs", 0, y); dc.DrawArc(x - r, y, x + r, y, x, y); dc.DrawArc(x + 4*r, y, x + 2*r, y, x + 3*r, y); dc.DrawArc(x + 5*r, y, x + 5*r, y, x + 6*r, y); y += 2*r; dc.DrawEllipticArc(x - r, y, 2*r, r, 0, 90); dc.DrawEllipticArc(x + r, y, 2*r, r, 90, 180); dc.DrawEllipticArc(x + 3*r, y, 2*r, r, 180, 270); dc.DrawEllipticArc(x + 5*r, y, 2*r, r, 270, 360); // same as above, just transparent brush dc.SetPen( *wxRED_PEN ); dc.SetBrush( *wxTRANSPARENT_BRUSH ); y += 2*r; dc.DrawText("Some circles", 0, y); dc.DrawCircle(x, y, r); dc.DrawCircle(x + 2*r, y, r); dc.DrawCircle(x + 4*r, y, r); y += 2*r; dc.DrawText("And ellipses", 0, y); dc.DrawEllipse(x - r, y, 2*r, r); dc.DrawEllipse(x + r, y, 2*r, r); dc.DrawEllipse(x + 3*r, y, 2*r, r); y += 2*r; dc.DrawText("And arcs", 0, y); dc.DrawArc(x - r, y, x + r, y, x, y); dc.DrawArc(x + 4*r, y, x + 2*r, y, x + 3*r, y); dc.DrawArc(x + 5*r, y, x + 5*r, y, x + 6*r, y); y += 2*r; dc.DrawEllipticArc(x - r, y, 2*r, r, 0, 90); dc.DrawEllipticArc(x + r, y, 2*r, r, 90, 180); dc.DrawEllipticArc(x + 3*r, y, 2*r, r, 180, 270); dc.DrawEllipticArc(x + 5*r, y, 2*r, r, 270, 360); } void MyCanvas::DrawSplines(wxDC& dc) { #if wxUSE_SPLINES dc.DrawText("Some splines", 10, 5); // values are hardcoded rather than randomly generated // so the output can be compared between native // implementations on platforms with different random // generators const int R = 300; const wxPoint center( R + 20, R + 20 ); const int angles[7] = { 0, 10, 33, 77, 13, 145, 90 }; const int radii[5] = { 100 , 59, 85, 33, 90 }; const int numPoints = 200; wxPoint pts[numPoints]; // background spline calculation unsigned int radius_pos = 0; unsigned int angle_pos = 0; int angle = 0; for ( int i = 0; i < numPoints; i++ ) { angle += angles[ angle_pos ]; int r = R * radii[ radius_pos ] / 100; pts[ i ].x = center.x + (wxCoord)( r * cos(wxDegToRad(angle)) ); pts[ i ].y = center.y + (wxCoord)( r * sin(wxDegToRad(angle)) ); angle_pos++; if ( angle_pos >= WXSIZEOF(angles) ) angle_pos = 0; radius_pos++; if ( radius_pos >= WXSIZEOF(radii) ) radius_pos = 0; } // background spline drawing dc.SetPen(*wxRED_PEN); dc.DrawSpline(WXSIZEOF(pts), pts); // less detailed spline calculation wxPoint letters[4][5]; // w letters[0][0] = wxPoint( 0,1); // O O letters[0][1] = wxPoint( 1,3); // * * letters[0][2] = wxPoint( 2,2); // * O * letters[0][3] = wxPoint( 3,3); // * * * * letters[0][4] = wxPoint( 4,1); // O O // x1 letters[1][0] = wxPoint( 5,1); // O*O letters[1][1] = wxPoint( 6,1); // * letters[1][2] = wxPoint( 7,2); // O letters[1][3] = wxPoint( 8,3); // * letters[1][4] = wxPoint( 9,3); // O*O // x2 letters[2][0] = wxPoint( 5,3); // O*O letters[2][1] = wxPoint( 6,3); // * letters[2][2] = wxPoint( 7,2); // O letters[2][3] = wxPoint( 8,1); // * letters[2][4] = wxPoint( 9,1); // O*O // W letters[3][0] = wxPoint(10,0); // O O letters[3][1] = wxPoint(11,3); // * * letters[3][2] = wxPoint(12,1); // * O * letters[3][3] = wxPoint(13,3); // * * * * letters[3][4] = wxPoint(14,0); // O O const int dx = 2 * R / letters[3][4].x; const int h[4] = { -R/2, 0, R/4, R/2 }; for ( int m = 0; m < 4; m++ ) { for ( int n = 0; n < 5; n++ ) { letters[m][n].x = center.x - R + letters[m][n].x * dx; letters[m][n].y = center.y + h[ letters[m][n].y ]; } dc.SetPen( wxPen( *wxBLUE, 1, wxPENSTYLE_DOT) ); dc.DrawLines(5, letters[m]); dc.SetPen( wxPen( *wxBLACK, 4) ); dc.DrawSpline(5, letters[m]); } #else dc.DrawText("Splines not supported.", 10, 5); #endif } void MyCanvas::DrawGradients(wxDC& dc) { static const int TEXT_HEIGHT = 15; // LHS: linear wxRect r(10, 10, 50, 50); dc.DrawText("wxRIGHT", r.x, r.y); r.Offset(0, TEXT_HEIGHT); dc.GradientFillLinear(r, *wxWHITE, *wxBLUE, wxRIGHT); r.Offset(0, r.height + 10); dc.DrawText("wxLEFT", r.x, r.y); r.Offset(0, TEXT_HEIGHT); dc.GradientFillLinear(r, *wxWHITE, *wxBLUE, wxLEFT); r.Offset(0, r.height + 10); dc.DrawText("wxDOWN", r.x, r.y); r.Offset(0, TEXT_HEIGHT); dc.GradientFillLinear(r, *wxWHITE, *wxBLUE, wxDOWN); r.Offset(0, r.height + 10); dc.DrawText("wxUP", r.x, r.y); r.Offset(0, TEXT_HEIGHT); dc.GradientFillLinear(r, *wxWHITE, *wxBLUE, wxUP); wxRect gfr = wxRect(r); // RHS: concentric r = wxRect(200, 10, 50, 50); dc.DrawText("Blue inside", r.x, r.y); r.Offset(0, TEXT_HEIGHT); dc.GradientFillConcentric(r, *wxBLUE, *wxWHITE); r.Offset(0, r.height + 10); dc.DrawText("White inside", r.x, r.y); r.Offset(0, TEXT_HEIGHT); dc.GradientFillConcentric(r, *wxWHITE, *wxBLUE); r.Offset(0, r.height + 10); dc.DrawText("Blue in top left corner", r.x, r.y); r.Offset(0, TEXT_HEIGHT); dc.GradientFillConcentric(r, *wxBLUE, *wxWHITE, wxPoint(0, 0)); r.Offset(0, r.height + 10); dc.DrawText("Blue in bottom right corner", r.x, r.y); r.Offset(0, TEXT_HEIGHT); dc.GradientFillConcentric(r, *wxBLUE, *wxWHITE, wxPoint(r.width, r.height)); // check that the area filled by the gradient is exactly the interior of // the rectangle r.x = 350; r.y = 30; dc.DrawText("The interior should be filled but", r.x, r.y); r.y += 15; dc.DrawText(" the red border should remain visible:", r.x, r.y); r.y += 15; r.width = r.height = 50; wxRect r2 = r; r2.x += 60; wxRect r3 = r; r3.y += 60; wxRect r4 = r2; r4.y += 60; dc.SetPen(*wxRED_PEN); dc.DrawRectangle(r); r.Deflate(1); dc.GradientFillLinear(r, *wxGREEN, *wxBLACK, wxNORTH); dc.DrawRectangle(r2); r2.Deflate(1); dc.GradientFillLinear(r2, *wxBLACK, *wxGREEN, wxSOUTH); dc.DrawRectangle(r3); r3.Deflate(1); dc.GradientFillLinear(r3, *wxGREEN, *wxBLACK, wxEAST); dc.DrawRectangle(r4); r4.Deflate(1); dc.GradientFillLinear(r4, *wxBLACK, *wxGREEN, wxWEST); #if wxUSE_GRAPHICS_CONTEXT if (m_renderer) { wxGCDC &gdc = (wxGCDC&)dc; wxGraphicsContext *gc = gdc.GetGraphicsContext(); wxGraphicsPath pth; wxGraphicsGradientStops stops; double boxX, boxY, boxWidth, boxHeight; gfr.Offset(0, gfr.height + 10); dc.DrawText("Linear Gradient with Stops", gfr.x, gfr.y); gfr.Offset(0, TEXT_HEIGHT); stops = wxGraphicsGradientStops(*wxRED, *wxBLUE); stops.Add(wxColour(255,255,0), 0.33f); stops.Add(*wxGREEN, 0.67f); gc->SetBrush(gc->CreateLinearGradientBrush(gfr.x, gfr.y, gfr.x + gfr.width, gfr.y + gfr.height, stops)); pth = gc->CreatePath(); pth.MoveToPoint(gfr.x,gfr.y); pth.AddLineToPoint(gfr.x + gfr.width,gfr.y); pth.AddLineToPoint(gfr.x + gfr.width,gfr.y+gfr.height); pth.AddLineToPoint(gfr.x,gfr.y+gfr.height); pth.CloseSubpath(); gc->FillPath(pth); pth.GetBox(&boxX, &boxY, &boxWidth, &boxHeight); dc.CalcBoundingBox(wxRound(boxX), wxRound(boxY)); dc.CalcBoundingBox(wxRound(boxX+boxWidth), wxRound(boxY+boxHeight)); wxGraphicsGradientStops simpleStops(*wxRED, *wxBLUE); gfr.Offset(0, gfr.height + 10); dc.DrawText("Radial Gradient from Red to Blue without intermediary Stops", gfr.x, gfr.y); gfr.Offset(0, TEXT_HEIGHT); gc->SetBrush(gc->CreateRadialGradientBrush(gfr.x + gfr.width / 2, gfr.y + gfr.height / 2, gfr.x + gfr.width / 2, gfr.y + gfr.height / 2, gfr.width / 2, simpleStops)); pth = gc->CreatePath(); pth.MoveToPoint(gfr.x,gfr.y); pth.AddLineToPoint(gfr.x + gfr.width,gfr.y); pth.AddLineToPoint(gfr.x + gfr.width,gfr.y+gfr.height); pth.AddLineToPoint(gfr.x,gfr.y+gfr.height); pth.CloseSubpath(); gc->FillPath(pth); pth.GetBox(&boxX, &boxY, &boxWidth, &boxHeight); dc.CalcBoundingBox(wxRound(boxX), wxRound(boxY)); dc.CalcBoundingBox(wxRound(boxX+boxWidth), wxRound(boxY+boxHeight)); gfr.Offset(0, gfr.height + 10); dc.DrawText("Radial Gradient from Red to Blue with Yellow and Green Stops", gfr.x, gfr.y); gfr.Offset(0, TEXT_HEIGHT); gc->SetBrush(gc->CreateRadialGradientBrush(gfr.x + gfr.width / 2, gfr.y + gfr.height / 2, gfr.x + gfr.width / 2, gfr.y + gfr.height / 2, gfr.width / 2, stops)); pth = gc->CreatePath(); pth.MoveToPoint(gfr.x,gfr.y); pth.AddLineToPoint(gfr.x + gfr.width,gfr.y); pth.AddLineToPoint(gfr.x + gfr.width,gfr.y+gfr.height); pth.AddLineToPoint(gfr.x,gfr.y+gfr.height); pth.CloseSubpath(); gc->FillPath(pth); pth.GetBox(&boxX, &boxY, &boxWidth, &boxHeight); dc.CalcBoundingBox(wxRound(boxX), wxRound(boxY)); dc.CalcBoundingBox(wxRound(boxX+boxWidth), wxRound(boxY+boxHeight)); gfr.Offset(0, gfr.height + 10); dc.DrawText("Linear Gradient with Stops and Gaps", gfr.x, gfr.y); gfr.Offset(0, TEXT_HEIGHT); stops = wxGraphicsGradientStops(*wxRED, *wxBLUE); stops.Add(wxColour(255,255,0), 0.33f); stops.Add(wxTransparentColour, 0.33f); stops.Add(wxTransparentColour, 0.67f); stops.Add(*wxGREEN, 0.67f); gc->SetBrush(gc->CreateLinearGradientBrush(gfr.x, gfr.y + gfr.height, gfr.x + gfr.width, gfr.y, stops)); pth = gc->CreatePath(); pth.MoveToPoint(gfr.x,gfr.y); pth.AddLineToPoint(gfr.x + gfr.width,gfr.y); pth.AddLineToPoint(gfr.x + gfr.width,gfr.y+gfr.height); pth.AddLineToPoint(gfr.x,gfr.y+gfr.height); pth.CloseSubpath(); gc->FillPath(pth); pth.GetBox(&boxX, &boxY, &boxWidth, &boxHeight); dc.CalcBoundingBox(wxRound(boxX), wxRound(boxY)); dc.CalcBoundingBox(wxRound(boxX+boxWidth), wxRound(boxY+boxHeight)); gfr.Offset(0, gfr.height + 10); dc.DrawText("Radial Gradient with Stops and Gaps", gfr.x, gfr.y); gfr.Offset(0, TEXT_HEIGHT); gc->SetBrush(gc->CreateRadialGradientBrush(gfr.x + gfr.width / 2, gfr.y + gfr.height / 2, gfr.x + gfr.width / 2, gfr.y + gfr.height / 2, gfr.width / 2, stops)); pth = gc->CreatePath(); pth.MoveToPoint(gfr.x,gfr.y); pth.AddLineToPoint(gfr.x + gfr.width,gfr.y); pth.AddLineToPoint(gfr.x + gfr.width,gfr.y+gfr.height); pth.AddLineToPoint(gfr.x,gfr.y+gfr.height); pth.CloseSubpath(); gc->FillPath(pth); pth.GetBox(&boxX, &boxY, &boxWidth, &boxHeight); dc.CalcBoundingBox(wxRound(boxX), wxRound(boxY)); dc.CalcBoundingBox(wxRound(boxX+boxWidth), wxRound(boxY+boxHeight)); gfr.Offset(0, gfr.height + 10); dc.DrawText("Gradients with Stops and Transparency", gfr.x, gfr.y); gfr.Offset(0, TEXT_HEIGHT); stops = wxGraphicsGradientStops(*wxRED, wxTransparentColour); stops.Add(*wxRED, 0.33f); stops.Add(wxTransparentColour, 0.33f); stops.Add(wxTransparentColour, 0.67f); stops.Add(*wxBLUE, 0.67f); stops.Add(*wxBLUE, 1.0f); pth = gc->CreatePath(); pth.MoveToPoint(gfr.x,gfr.y); pth.AddLineToPoint(gfr.x + gfr.width,gfr.y); pth.AddLineToPoint(gfr.x + gfr.width,gfr.y+gfr.height); pth.AddLineToPoint(gfr.x,gfr.y+gfr.height); pth.CloseSubpath(); gc->SetBrush(gc->CreateRadialGradientBrush(gfr.x + gfr.width / 2, gfr.y + gfr.height / 2, gfr.x + gfr.width / 2, gfr.y + gfr.height / 2, gfr.width / 2, stops)); gc->FillPath(pth); stops = wxGraphicsGradientStops(wxColour(255,0,0, 128), wxColour(0,0,255, 128)); stops.Add(wxColour(255,255,0,128), 0.33f); stops.Add(wxColour(0,255,0,128), 0.67f); gc->SetBrush(gc->CreateLinearGradientBrush(gfr.x, gfr.y, gfr.x + gfr.width, gfr.y, stops)); gc->FillPath(pth); pth.GetBox(&boxX, &boxY, &boxWidth, &boxHeight); dc.CalcBoundingBox(wxRound(boxX), wxRound(boxY)); dc.CalcBoundingBox(wxRound(boxX+boxWidth), wxRound(boxY+boxHeight)); gfr.Offset(0, gfr.height + 10); dc.DrawText("Stroked path with a gradient pen", gfr.x, gfr.y); gfr.Offset(0, TEXT_HEIGHT); pth = gc->CreatePath(); pth.MoveToPoint(gfr.x + gfr.width/2, gfr.y); pth.AddLineToPoint(gfr.x + gfr.width, gfr.y + gfr.height/2); pth.AddLineToPoint(gfr.x + gfr.width/2, gfr.y + gfr.height); pth.AddLineToPoint(gfr.x, gfr.y + gfr.height/2); pth.CloseSubpath(); stops = wxGraphicsGradientStops(*wxRED, *wxBLUE); stops.Add(wxColour(255,255,0), 0.33f); stops.Add(*wxGREEN, 0.67f); wxGraphicsPen pen = gc->CreatePen( wxGraphicsPenInfo(wxColour(0,0,0)).Width(6).Join(wxJOIN_BEVEL).LinearGradient( gfr.x + gfr.width/2, gfr.y, gfr.x + gfr.width/2, gfr.y + gfr.height, stops)); gc->SetPen(pen); gc->StrokePath(pth); } #endif // wxUSE_GRAPHICS_CONTEXT } void MyCanvas::DrawSystemColours(wxDC& dc) { wxFont mono(wxFontInfo().Family(wxFONTFAMILY_TELETYPE)); wxSize textSize; { wxDCFontChanger setMono(dc, mono); textSize = dc.GetTextExtent("#01234567"); } int lineHeight = textSize.GetHeight(); wxRect r(textSize.GetWidth() + 10, 10, 100, lineHeight); wxString title = "System colours"; const wxSystemAppearance appearance = wxSystemSettings::GetAppearance(); const wxString appearanceName = appearance.GetName(); if ( !appearanceName.empty() ) title += wxString::Format(" for \"%s\"", appearanceName); if ( appearance.IsDark() ) title += " (using dark system theme)"; dc.DrawText(title, 10, r.y); r.y += 2*lineHeight; dc.DrawText(wxString::Format("Window background is %s", appearance.IsUsingDarkBackground() ? "dark" : "light"), 10, r.y); r.y += 3*lineHeight; dc.SetPen(*wxTRANSPARENT_PEN); static const struct { wxSystemColour index; const char* name; } sysColours[] = { { wxSYS_COLOUR_3DDKSHADOW, "wxSYS_COLOUR_3DDKSHADOW" }, { wxSYS_COLOUR_3DLIGHT, "wxSYS_COLOUR_3DLIGHT" }, { wxSYS_COLOUR_ACTIVEBORDER, "wxSYS_COLOUR_ACTIVEBORDER" }, { wxSYS_COLOUR_ACTIVECAPTION, "wxSYS_COLOUR_ACTIVECAPTION" }, { wxSYS_COLOUR_APPWORKSPACE, "wxSYS_COLOUR_APPWORKSPACE" }, { wxSYS_COLOUR_BTNFACE, "wxSYS_COLOUR_BTNFACE" }, { wxSYS_COLOUR_BTNHIGHLIGHT, "wxSYS_COLOUR_BTNHIGHLIGHT" }, { wxSYS_COLOUR_BTNSHADOW, "wxSYS_COLOUR_BTNSHADOW" }, { wxSYS_COLOUR_BTNTEXT, "wxSYS_COLOUR_BTNTEXT" }, { wxSYS_COLOUR_CAPTIONTEXT, "wxSYS_COLOUR_CAPTIONTEXT" }, { wxSYS_COLOUR_DESKTOP, "wxSYS_COLOUR_DESKTOP" }, { wxSYS_COLOUR_GRADIENTACTIVECAPTION, "wxSYS_COLOUR_GRADIENTACTIVECAPTION" }, { wxSYS_COLOUR_GRADIENTINACTIVECAPTION, "wxSYS_COLOUR_GRADIENTINACTIVECAPTION" }, { wxSYS_COLOUR_GRAYTEXT, "wxSYS_COLOUR_GRAYTEXT" }, { wxSYS_COLOUR_HIGHLIGHTTEXT, "wxSYS_COLOUR_HIGHLIGHTTEXT" }, { wxSYS_COLOUR_HIGHLIGHT, "wxSYS_COLOUR_HIGHLIGHT" }, { wxSYS_COLOUR_HOTLIGHT, "wxSYS_COLOUR_HOTLIGHT" }, { wxSYS_COLOUR_INACTIVEBORDER, "wxSYS_COLOUR_INACTIVEBORDER" }, { wxSYS_COLOUR_INACTIVECAPTIONTEXT, "wxSYS_COLOUR_INACTIVECAPTIONTEXT" }, { wxSYS_COLOUR_INACTIVECAPTION, "wxSYS_COLOUR_INACTIVECAPTION" }, { wxSYS_COLOUR_INFOBK, "wxSYS_COLOUR_INFOBK" }, { wxSYS_COLOUR_INFOTEXT, "wxSYS_COLOUR_INFOTEXT" }, { wxSYS_COLOUR_LISTBOXHIGHLIGHTTEXT, "wxSYS_COLOUR_LISTBOXHIGHLIGHTTEXT" }, { wxSYS_COLOUR_LISTBOXTEXT, "wxSYS_COLOUR_LISTBOXTEXT" }, { wxSYS_COLOUR_LISTBOX, "wxSYS_COLOUR_LISTBOX" }, { wxSYS_COLOUR_MENUBAR, "wxSYS_COLOUR_MENUBAR" }, { wxSYS_COLOUR_MENUHILIGHT, "wxSYS_COLOUR_MENUHILIGHT" }, { wxSYS_COLOUR_MENUTEXT, "wxSYS_COLOUR_MENUTEXT" }, { wxSYS_COLOUR_MENU, "wxSYS_COLOUR_MENU" }, { wxSYS_COLOUR_SCROLLBAR, "wxSYS_COLOUR_SCROLLBAR" }, { wxSYS_COLOUR_WINDOWFRAME, "wxSYS_COLOUR_WINDOWFRAME" }, { wxSYS_COLOUR_WINDOWTEXT, "wxSYS_COLOUR_WINDOWTEXT" }, { wxSYS_COLOUR_WINDOW, "wxSYS_COLOUR_WINDOW" } }; for (int i = 0; i < wxSYS_COLOUR_MAX; i++) { wxString colourName(sysColours[i].name); wxColour c(wxSystemSettings::GetColour(sysColours[i].index)); { wxDCFontChanger setMono(dc, mono); dc.DrawText(c.GetAsString(wxC2S_HTML_SYNTAX), 10, r.y); } dc.SetBrush(wxBrush(c)); dc.DrawRectangle(r); dc.DrawText(colourName, r.GetRight() + 10, r.y); r.y += lineHeight; } } void MyCanvas::DrawRegions(wxDC& dc) { dc.DrawText("You should see a red rect partly covered by a cyan one " "on the left", 10, 5); dc.DrawText("and 5 smileys from which 4 are partially clipped on the right", 10, 5 + dc.GetCharHeight()); dc.DrawText("The second copy should be identical but right part of it " "should be offset by 10 pixels.", 10, 5 + 2*dc.GetCharHeight()); DrawRegionsHelper(dc, 10, true); DrawRegionsHelper(dc, 350, false); } void MyCanvas::DrawRegionsHelper(wxDC& dc, wxCoord x, bool firstTime) { wxCoord y = 100; dc.DestroyClippingRegion(); dc.SetBrush( *wxWHITE_BRUSH ); dc.SetPen( *wxTRANSPARENT_PEN ); dc.DrawRectangle( x, y, 310, 310 ); dc.SetClippingRegion( x + 10, y + 10, 100, 270 ); dc.SetBrush( *wxRED_BRUSH ); dc.DrawRectangle( x, y, 310, 310 ); dc.SetClippingRegion( x + 10, y + 10, 100, 100 ); dc.SetBrush( *wxCYAN_BRUSH ); dc.DrawRectangle( x, y, 310, 310 ); dc.DestroyClippingRegion(); wxRegion region(x + 110, y + 20, 100, 270); #if !defined(__WXMOTIF__) if ( !firstTime ) region.Offset(10, 10); #endif dc.SetDeviceClippingRegion(region); dc.SetBrush( *wxGREY_BRUSH ); dc.DrawRectangle( x, y, 310, 310 ); if (m_smile_bmp.IsOk()) { dc.DrawBitmap( m_smile_bmp, x + 150, y + 150, true ); dc.DrawBitmap( m_smile_bmp, x + 130, y + 10, true ); dc.DrawBitmap( m_smile_bmp, x + 130, y + 280, true ); dc.DrawBitmap( m_smile_bmp, x + 100, y + 70, true ); dc.DrawBitmap( m_smile_bmp, x + 200, y + 70, true ); } } void MyCanvas::GetDrawingSize(int* width, int* height) const { if ( width ) *width = m_sizeX; if ( height ) *height = m_sizeY; } void MyCanvas::OnPaint(wxPaintEvent &WXUNUSED(event)) { if ( m_useBuffer ) { wxBufferedPaintDC bpdc(this); Draw(bpdc); } else { wxPaintDC pdc(this); Draw(pdc); } } void MyCanvas::Draw(wxDC& pdc) { #if wxUSE_GRAPHICS_CONTEXT wxGCDC gdc; if ( m_renderer ) { wxGraphicsContext* context; if ( wxPaintDC *paintdc = wxDynamicCast(&pdc, wxPaintDC) ) { context = m_renderer->CreateContext(*paintdc); } else if ( wxMemoryDC *memdc = wxDynamicCast(&pdc, wxMemoryDC) ) { context = m_renderer->CreateContext(*memdc); } #if wxUSE_METAFILE && defined(wxMETAFILE_IS_ENH) else if ( wxMetafileDC *metadc = wxDynamicCast(&pdc, wxMetafileDC) ) { context = m_renderer->CreateContext(*metadc); } #endif else { wxFAIL_MSG( "Unknown wxDC kind" ); return; } context->SetAntialiasMode(m_useAntiAliasing ? wxANTIALIAS_DEFAULT : wxANTIALIAS_NONE); gdc.SetBackground(GetBackgroundColour()); gdc.SetGraphicsContext(context); } wxDC &dc = m_renderer ? static_cast<wxDC&>(gdc) : pdc; #else wxDC &dc = pdc ; #endif // Adjust scrolled contents for screen drawing operations only. if ( wxDynamicCast(&pdc, wxBufferedPaintDC) || wxDynamicCast(&pdc, wxPaintDC) ) { PrepareDC(dc); } m_owner->PrepareDC(dc); dc.SetBackgroundMode( m_owner->m_backgroundMode ); if ( m_owner->m_backgroundBrush.IsOk() ) dc.SetBackground( m_owner->m_backgroundBrush ); if ( m_owner->m_colourForeground.IsOk() ) dc.SetTextForeground( m_owner->m_colourForeground ); if ( m_owner->m_colourBackground.IsOk() ) dc.SetTextBackground( m_owner->m_colourBackground ); if ( m_owner->m_textureBackground) { if ( ! m_owner->m_backgroundBrush.IsOk() ) { dc.SetBackground(wxBrush(wxColour(0, 128, 0))); } } if ( m_clip ) dc.SetClippingRegion(100, 100, 100, 100); dc.Clear(); if ( m_owner->m_textureBackground ) { dc.SetPen(*wxMEDIUM_GREY_PEN); for ( int i = 0; i < 200; i++ ) dc.DrawLine(0, i*10, i*10, 0); } switch ( m_show ) { case File_ShowDefault: DrawDefault(dc); break; case File_ShowCircles: DrawCircles(dc); break; case File_ShowSplines: DrawSplines(dc); break; case File_ShowRegions: DrawRegions(dc); break; case File_ShowText: DrawText(dc); break; case File_ShowLines: DrawTestLines( 0, 100, 0, dc ); DrawTestLines( 0, 320, 1, dc ); DrawTestLines( 0, 540, 2, dc ); DrawTestLines( 0, 760, 6, dc ); DrawCrossHair( 0, 0, 400, 90, dc); break; case File_ShowBrushes: DrawTestBrushes(dc); break; case File_ShowPolygons: DrawTestPoly(dc); break; case File_ShowMask: DrawImages(dc, Draw_Normal); break; case File_ShowMaskStretch: DrawImages(dc, Draw_Stretch); break; case File_ShowOps: DrawWithLogicalOps(dc); break; #if wxDRAWING_DC_SUPPORTS_ALPHA || wxUSE_GRAPHICS_CONTEXT case File_ShowAlpha: DrawAlpha(dc); break; #endif // wxDRAWING_DC_SUPPORTS_ALPHA || wxUSE_GRAPHICS_CONTEXT #if wxUSE_GRAPHICS_CONTEXT case File_ShowGraphics: DrawGraphics(gdc.GetGraphicsContext()); break; #endif case File_ShowGradients: DrawGradients(dc); break; case File_ShowSystemColours: DrawSystemColours(dc); break; default: break; } // For drawing with raw wxGraphicsContext // there is no bounding box to obtain. if ( m_showBBox #if wxUSE_GRAPHICS_CONTEXT && m_show != File_ShowGraphics #endif // wxUSE_GRAPHICS_CONTEXT ) { dc.SetPen(wxPen(wxColor(0, 128, 0), 1, wxPENSTYLE_DOT)); dc.SetBrush(*wxTRANSPARENT_BRUSH); dc.DrawRectangle(dc.MinX(), dc.MinY(), dc.MaxX()-dc.MinX()+1, dc.MaxY()-dc.MinY()+1); } // Adjust drawing area dimensions only if screen drawing is invoked. if ( wxDynamicCast(&pdc, wxBufferedPaintDC) || wxDynamicCast(&pdc, wxPaintDC) ) { wxCoord x0, y0; dc.GetDeviceOrigin(&x0, &y0); m_sizeX = dc.LogicalToDeviceX(dc.MaxX()) - x0 + 1; m_sizeY = dc.LogicalToDeviceY(dc.MaxY()) - y0 + 1; } } void MyCanvas::OnMouseMove(wxMouseEvent &event) { #if wxUSE_STATUSBAR { wxClientDC dc(this); PrepareDC(dc); m_owner->PrepareDC(dc); wxPoint pos = dc.DeviceToLogical(event.GetPosition()); wxString str; str.Printf( "Current mouse position: %d,%d", pos.x, pos.y ); m_owner->SetStatusText( str ); } if ( m_rubberBand ) { int x,y, xx, yy ; event.GetPosition(&x,&y); CalcUnscrolledPosition( x, y, &xx, &yy ); m_currentpoint = wxPoint( xx , yy ) ; wxRect newrect ( m_anchorpoint , m_currentpoint ) ; wxClientDC dc( this ) ; PrepareDC( dc ) ; wxDCOverlay overlaydc( m_overlay, &dc ); overlaydc.Clear(); #ifdef __WXMAC__ dc.SetPen( *wxGREY_PEN ); dc.SetBrush( wxColour( 192,192,192,64 ) ); #else dc.SetPen( wxPen( *wxLIGHT_GREY, 2 ) ); dc.SetBrush( *wxTRANSPARENT_BRUSH ); #endif dc.DrawRectangle( newrect ); } #else wxUnusedVar(event); #endif // wxUSE_STATUSBAR } void MyCanvas::OnMouseDown(wxMouseEvent &event) { int x,y,xx,yy ; event.GetPosition(&x,&y); CalcUnscrolledPosition( x, y, &xx, &yy ); m_anchorpoint = wxPoint( xx , yy ) ; m_currentpoint = m_anchorpoint ; m_rubberBand = true ; CaptureMouse() ; } void MyCanvas::OnMouseUp(wxMouseEvent &event) { if ( m_rubberBand ) { ReleaseMouse(); { wxClientDC dc( this ); PrepareDC( dc ); wxDCOverlay overlaydc( m_overlay, &dc ); overlaydc.Clear(); } m_overlay.Reset(); m_rubberBand = false; wxPoint endpoint = CalcUnscrolledPosition(event.GetPosition()); // Don't pop up the message box if nothing was actually selected. if ( endpoint != m_anchorpoint ) { wxLogMessage("Selected rectangle from (%d, %d) to (%d, %d)", m_anchorpoint.x, m_anchorpoint.y, endpoint.x, endpoint.y); } } } #if wxUSE_GRAPHICS_CONTEXT void MyCanvas::UseGraphicRenderer(wxGraphicsRenderer* renderer) { m_renderer = renderer; if (renderer) { int major, minor, micro; renderer->GetVersion(&major, &minor, &micro); wxString str = wxString::Format("Graphics renderer: %s %i.%i.%i", renderer->GetName(), major, minor, micro); m_owner->SetStatusText(str, 1); } else { m_owner->SetStatusText(wxEmptyString, 1); } Refresh(); } #endif // wxUSE_GRAPHICS_CONTEXT #if wxUSE_DC_TRANSFORM_MATRIX #include "wx/valnum.h" class TransformDataDialog : public wxDialog { public: TransformDataDialog(wxWindow* parent, wxDouble dx, wxDouble dy, wxDouble scx, wxDouble scy, wxDouble rotAngle) : wxDialog(parent, wxID_ANY, "Affine transformation parameters") , m_dx(dx) , m_dy(dy) , m_scx(scx) , m_scy(scy) , m_rotAngle(rotAngle) { wxBoxSizer* sizer = new wxBoxSizer(wxVERTICAL); const int border = wxSizerFlags::GetDefaultBorder(); wxFlexGridSizer* paramSizer = new wxFlexGridSizer(2, wxSize(border, border)); paramSizer->Add(new wxStaticText(this, wxID_ANY, "Translation X:"), wxSizerFlags().CentreVertical()); wxFloatingPointValidator<wxDouble> val_dx(1, &m_dx, wxNUM_VAL_NO_TRAILING_ZEROES); paramSizer->Add(new wxTextCtrl(this, wxID_ANY, "", wxDefaultPosition, wxDefaultSize, 0, val_dx), wxSizerFlags().CentreVertical()); paramSizer->Add(new wxStaticText(this, wxID_ANY, "Translation Y:"), wxSizerFlags().CentreVertical()); wxFloatingPointValidator<wxDouble> val_dy(1, &m_dy, wxNUM_VAL_NO_TRAILING_ZEROES); paramSizer->Add(new wxTextCtrl(this, wxID_ANY, "", wxDefaultPosition, wxDefaultSize, 0, val_dy), wxSizerFlags().CentreVertical()); paramSizer->Add(new wxStaticText(this, wxID_ANY, "Scale X (0.2 - 5):"), wxSizerFlags().CentreVertical()); wxFloatingPointValidator<wxDouble> val_scx(2, &m_scx, wxNUM_VAL_NO_TRAILING_ZEROES); paramSizer->Add(new wxTextCtrl(this, wxID_ANY, "", wxDefaultPosition, wxDefaultSize, 0, val_scx), wxSizerFlags().CentreVertical()); paramSizer->Add(new wxStaticText(this, wxID_ANY, "Scale Y (0.2 - 5):"), wxSizerFlags().CentreVertical()); wxFloatingPointValidator<wxDouble> val_scy(2, &m_scy, wxNUM_VAL_NO_TRAILING_ZEROES); paramSizer->Add(new wxTextCtrl(this, wxID_ANY, "", wxDefaultPosition, wxDefaultSize, 0, val_scy), wxSizerFlags().CentreVertical()); paramSizer->Add(new wxStaticText(this, wxID_ANY, "Rotation angle (deg):"), wxSizerFlags().CentreVertical()); wxFloatingPointValidator<wxDouble> val_rot(1, &m_rotAngle, wxNUM_VAL_NO_TRAILING_ZEROES); paramSizer->Add(new wxTextCtrl(this, wxID_ANY, "", wxDefaultPosition, wxDefaultSize, 0, val_rot), wxSizerFlags().CentreVertical()); sizer->Add(paramSizer, wxSizerFlags().DoubleBorder()); wxSizer *btnSizer = CreateSeparatedButtonSizer(wxOK | wxCANCEL); sizer->Add(btnSizer, wxSizerFlags().Expand().Border()); SetSizerAndFit(sizer); } virtual bool TransferDataFromWindow() wxOVERRIDE { if ( !wxDialog::TransferDataFromWindow() ) return false; if ( m_scx < 0.2 || m_scx > 5.0 || m_scy < 0.2 || m_scy > 5.0 ) { if ( !wxValidator::IsSilent() ) wxBell(); return false; } return true; } void GetTransformationData(wxDouble* dx, wxDouble* dy, wxDouble* scx, wxDouble* scy, wxDouble* rotAngle) const { if ( dx ) *dx = m_dx; if ( dy ) *dy = m_dy; if ( scx ) *scx = m_scx; if ( scy ) *scy = m_scy; if ( rotAngle ) *rotAngle = m_rotAngle; } private: wxDouble m_dx; wxDouble m_dy; wxDouble m_scx; wxDouble m_scy; wxDouble m_rotAngle; }; #endif // wxUSE_DC_TRANSFORM_MATRIX // ---------------------------------------------------------------------------- // MyFrame // ---------------------------------------------------------------------------- // the event tables connect the wxWidgets events with the functions (event // handlers) which process them. It can be also done at run-time, but for the // simple menu events like this the static method is much simpler. wxBEGIN_EVENT_TABLE(MyFrame, wxFrame) EVT_MENU (File_Quit, MyFrame::OnQuit) EVT_MENU (File_About, MyFrame::OnAbout) EVT_MENU (File_Clip, MyFrame::OnClip) #if wxUSE_GRAPHICS_CONTEXT EVT_MENU (File_GC_Default, MyFrame::OnGraphicContextDefault) EVT_MENU (File_DC, MyFrame::OnGraphicContextNone) #if wxUSE_CAIRO EVT_MENU (File_GC_Cairo, MyFrame::OnGraphicContextCairo) #endif // wxUSE_CAIRO #ifdef __WXMSW__ #if wxUSE_GRAPHICS_GDIPLUS EVT_MENU (File_GC_GDIPlus, MyFrame::OnGraphicContextGDIPlus) #endif #if wxUSE_GRAPHICS_DIRECT2D EVT_MENU (File_GC_Direct2D, MyFrame::OnGraphicContextDirect2D) #endif #endif // __WXMSW__ EVT_MENU (File_AntiAliasing, MyFrame::OnAntiAliasing) EVT_UPDATE_UI (File_AntiAliasing, MyFrame::OnAntiAliasingUpdateUI) #endif // wxUSE_GRAPHICS_CONTEXT EVT_MENU (File_Buffer, MyFrame::OnBuffer) EVT_MENU (File_Copy, MyFrame::OnCopy) EVT_MENU (File_Save, MyFrame::OnSave) EVT_MENU (File_BBox, MyFrame::OnBoundingBox) EVT_UPDATE_UI (File_BBox, MyFrame::OnBoundingBoxUpdateUI) EVT_MENU_RANGE(MenuShow_First, MenuShow_Last, MyFrame::OnShow) EVT_MENU_RANGE(MenuOption_First, MenuOption_Last, MyFrame::OnOption) wxEND_EVENT_TABLE() // frame constructor MyFrame::MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size) : wxFrame((wxFrame *)NULL, wxID_ANY, title, pos, size) { // set the frame icon SetIcon(wxICON(sample)); wxMenu *menuScreen = new wxMenu; menuScreen->Append(File_ShowDefault, "&Default screen\tF1"); menuScreen->Append(File_ShowText, "&Text screen\tF2"); menuScreen->Append(File_ShowLines, "&Lines screen\tF3"); menuScreen->Append(File_ShowBrushes, "&Brushes screen\tF4"); menuScreen->Append(File_ShowPolygons, "&Polygons screen\tF5"); menuScreen->Append(File_ShowMask, "&Mask screen\tF6"); menuScreen->Append(File_ShowMaskStretch, "1/&2 scaled mask\tShift-F6"); menuScreen->Append(File_ShowOps, "&Raster operations screen\tF7"); menuScreen->Append(File_ShowRegions, "Re&gions screen\tF8"); menuScreen->Append(File_ShowCircles, "&Circles screen\tF9"); #if wxDRAWING_DC_SUPPORTS_ALPHA || wxUSE_GRAPHICS_CONTEXT menuScreen->Append(File_ShowAlpha, "&Alpha screen\tF10"); #endif // wxDRAWING_DC_SUPPORTS_ALPHA || wxUSE_GRAPHICS_CONTEXT menuScreen->Append(File_ShowSplines, "Spl&ines screen\tF11"); menuScreen->Append(File_ShowGradients, "&Gradients screen\tF12"); #if wxUSE_GRAPHICS_CONTEXT menuScreen->Append(File_ShowGraphics, "&Graphics screen"); #endif menuScreen->Append(File_ShowSystemColours, "System &colours"); wxMenu *menuFile = new wxMenu; #if wxUSE_GRAPHICS_CONTEXT // Number the different renderer choices consecutively, starting from 0. int accel = 0; m_menuItemUseDC = menuFile->AppendRadioItem ( File_DC, wxString::Format("Use wx&DC\t%d", accel++) ); menuFile->AppendRadioItem ( File_GC_Default, wxString::Format("Use default wx&GraphicContext\t%d", accel++) ); #if wxUSE_CAIRO menuFile->AppendRadioItem ( File_GC_Cairo, wxString::Format("Use &Cairo\t%d", accel++) ); #endif // wxUSE_CAIRO #ifdef __WXMSW__ #if wxUSE_GRAPHICS_GDIPLUS menuFile->AppendRadioItem ( File_GC_GDIPlus, wxString::Format("Use &GDI+\t%d", accel++) ); #endif #if wxUSE_GRAPHICS_DIRECT2D menuFile->AppendRadioItem ( File_GC_Direct2D, wxString::Format("Use &Direct2D\t%d", accel++) ); #endif #endif // __WXMSW__ #endif // wxUSE_GRAPHICS_CONTEXT menuFile->AppendSeparator(); menuFile->AppendCheckItem(File_BBox, "Show bounding box\tCtrl-E", "Show extents used in drawing operations"); menuFile->AppendCheckItem(File_Clip, "&Clip\tCtrl-C", "Clip/unclip drawing"); menuFile->AppendCheckItem(File_Buffer, "&Use wx&BufferedPaintDC\tCtrl-Z", "Buffer painting"); #if wxUSE_GRAPHICS_CONTEXT menuFile->AppendCheckItem(File_AntiAliasing, "&Anti-Aliasing in wxGraphicContext\tCtrl-Shift-A", "Enable Anti-Aliasing in wxGraphicContext") ->Check(); #endif menuFile->AppendSeparator(); #if wxUSE_METAFILE && defined(wxMETAFILE_IS_ENH) menuFile->Append(File_Copy, "Copy to clipboard"); #endif menuFile->Append(File_Save, "&Save...\tCtrl-S", "Save drawing to file"); menuFile->AppendSeparator(); menuFile->Append(File_About, "&About\tCtrl-A", "Show about dialog"); menuFile->AppendSeparator(); menuFile->Append(File_Quit, "E&xit\tAlt-X", "Quit this program"); wxMenu *menuMapMode = new wxMenu; menuMapMode->Append( MapMode_Text, "&TEXT map mode" ); menuMapMode->Append( MapMode_Lometric, "&LOMETRIC map mode" ); menuMapMode->Append( MapMode_Twips, "T&WIPS map mode" ); menuMapMode->Append( MapMode_Points, "&POINTS map mode" ); menuMapMode->Append( MapMode_Metric, "&METRIC map mode" ); wxMenu *menuUserScale = new wxMenu; menuUserScale->Append( UserScale_StretchHoriz, "Stretch &horizontally\tCtrl-H" ); menuUserScale->Append( UserScale_ShrinkHoriz, "Shrin&k horizontally\tCtrl-G" ); menuUserScale->Append( UserScale_StretchVertic, "Stretch &vertically\tCtrl-V" ); menuUserScale->Append( UserScale_ShrinkVertic, "&Shrink vertically\tCtrl-W" ); menuUserScale->AppendSeparator(); menuUserScale->Append( UserScale_Restore, "&Restore to normal\tCtrl-0" ); wxMenu *menuAxis = new wxMenu; menuAxis->AppendCheckItem( AxisMirror_Horiz, "Mirror horizontally\tCtrl-M" ); menuAxis->AppendCheckItem( AxisMirror_Vertic, "Mirror vertically\tCtrl-N" ); wxMenu *menuLogical = new wxMenu; menuLogical->Append( LogicalOrigin_MoveDown, "Move &down\tCtrl-D" ); menuLogical->Append( LogicalOrigin_MoveUp, "Move &up\tCtrl-U" ); menuLogical->Append( LogicalOrigin_MoveLeft, "Move &right\tCtrl-L" ); menuLogical->Append( LogicalOrigin_MoveRight, "Move &left\tCtrl-R" ); menuLogical->AppendSeparator(); menuLogical->Append( LogicalOrigin_Set, "Set to (&100, 100)\tShift-Ctrl-1" ); menuLogical->Append( LogicalOrigin_Restore, "&Restore to normal\tShift-Ctrl-0" ); #if wxUSE_DC_TRANSFORM_MATRIX wxMenu *menuTransformMatrix = new wxMenu; menuTransformMatrix->Append(TransformMatrix_Set, "Set &transformation matrix"); menuTransformMatrix->AppendSeparator(); menuTransformMatrix->Append(TransformMatrix_Reset, "Restore to &normal"); #endif // wxUSE_DC_TRANSFORM_MATRIX wxMenu *menuColour = new wxMenu; #if wxUSE_COLOURDLG menuColour->Append( Colour_TextForeground, "Text &foreground..." ); menuColour->Append( Colour_TextBackground, "Text &background..." ); menuColour->Append( Colour_Background, "Background &colour..." ); #endif // wxUSE_COLOURDLG menuColour->AppendCheckItem( Colour_BackgroundMode, "&Opaque/transparent\tCtrl-B" ); menuColour->AppendCheckItem( Colour_TextureBackgound, "Draw textured back&ground\tCtrl-T" ); // now append the freshly created menu to the menu bar... wxMenuBar *menuBar = new wxMenuBar; menuBar->Append(menuFile, "&Drawing"); menuBar->Append(menuScreen, "Scree&n"); menuBar->Append(menuMapMode, "&Mode"); menuBar->Append(menuUserScale, "&Scale"); menuBar->Append(menuAxis, "&Axis"); menuBar->Append(menuLogical, "&Origin"); #if wxUSE_DC_TRANSFORM_MATRIX menuBar->Append(menuTransformMatrix, "&Transformation"); #endif // wxUSE_DC_TRANSFORM_MATRIX menuBar->Append(menuColour, "&Colours"); // ... and attach this menu bar to the frame SetMenuBar(menuBar); #if wxUSE_STATUSBAR CreateStatusBar(2); SetStatusText("Welcome to wxWidgets!"); #endif // wxUSE_STATUSBAR m_mapMode = wxMM_TEXT; m_xUserScale = 1.0; m_yUserScale = 1.0; m_xLogicalOrigin = 0; m_yLogicalOrigin = 0; m_xAxisReversed = m_yAxisReversed = false; #if wxUSE_DC_TRANSFORM_MATRIX m_transform_dx = 0.0; m_transform_dy = 0.0; m_transform_scx = 1.0; m_transform_scy = 1.0; m_transform_rot = 0.0; #endif // wxUSE_DC_TRANSFORM_MATRIX m_backgroundMode = wxBRUSHSTYLE_SOLID; m_colourForeground = *wxBLACK; m_colourBackground = *wxLIGHT_GREY; m_textureBackground = false; m_canvas = new MyCanvas( this ); m_canvas->SetScrollbars( 10, 10, 100, 240 ); } // event handlers void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event)) { // true is to force the frame to close Close(true); } void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event)) { wxString msg; msg.Printf( "This is the about dialog of the drawing sample.\n" "This sample tests various primitive drawing functions\n" "(without any attempts to prevent flicker).\n" "Copyright (c) Robert Roebling 1999" ); wxMessageBox(msg, "About Drawing", wxOK | wxICON_INFORMATION, this); } void MyFrame::OnClip(wxCommandEvent& event) { m_canvas->Clip(event.IsChecked()); } void MyFrame::OnBuffer(wxCommandEvent& event) { m_canvas->UseBuffer(event.IsChecked()); } void MyFrame::OnCopy(wxCommandEvent& WXUNUSED(event)) { #if wxUSE_METAFILE && defined(wxMETAFILE_IS_ENH) wxMetafileDC dc; if (!dc.IsOk()) return; m_canvas->Draw(dc); wxMetafile *mf = dc.Close(); if (!mf) return; mf->SetClipboard(); delete mf; #endif } void MyFrame::OnSave(wxCommandEvent& WXUNUSED(event)) { wxString wildCard = "Bitmap image (*.bmp)|*.bmp;*.BMP"; #if wxUSE_LIBPNG wildCard.Append("|PNG image (*.png)|*.png;*.PNG"); #endif #if wxUSE_SVG wildCard.Append("|SVG image (*.svg)|*.svg;*.SVG"); #endif #if wxUSE_POSTSCRIPT wildCard.Append("|PostScript file (*.ps)|*.ps;*.PS"); #endif wxFileDialog dlg(this, "Save as bitmap", wxEmptyString, wxEmptyString, wildCard, wxFD_SAVE | wxFD_OVERWRITE_PROMPT); if (dlg.ShowModal() == wxID_OK) { int width, height; m_canvas->GetDrawingSize(&width, &height); wxFileName fn(dlg.GetPath()); wxString ext = fn.GetExt().Lower(); #if wxUSE_SVG if (ext == "svg") { #if wxUSE_GRAPHICS_CONTEXT // Graphics screen can only be drawn using GraphicsContext if (m_canvas->GetPage() == File_ShowGraphics) { wxLogMessage("Graphics screen can not be saved as SVG."); return; } wxGraphicsRenderer* tempRenderer = m_canvas->GetRenderer(); m_canvas->UseGraphicRenderer(NULL); #endif wxSVGFileDC svgdc(dlg.GetPath(), width, height, 72, "Drawing sample"); svgdc.SetBitmapHandler(new wxSVGBitmapEmbedHandler()); m_canvas->Draw(svgdc); #if wxUSE_GRAPHICS_CONTEXT m_canvas->UseGraphicRenderer(tempRenderer); #endif } else #endif #if wxUSE_POSTSCRIPT if ( ext == "ps" ) { #if wxUSE_GRAPHICS_CONTEXT // Graphics screen can only be drawn using wxGraphicsContext if (m_canvas->GetPage() == File_ShowGraphics) { wxLogMessage("Graphics screen can not be saved as PostScript file."); return; } wxGraphicsRenderer* curRenderer = m_canvas->GetRenderer(); m_canvas->UseGraphicRenderer(NULL); #endif // wxUSE_GRAPHICS_CONTEXT wxPrintData printData; printData.SetPrintMode(wxPRINT_MODE_FILE); printData.SetFilename(dlg.GetPath()); printData.SetOrientation(wxPORTRAIT); printData.SetPaperId(wxPAPER_A4); wxPostScriptDC psdc(printData); // Save current scale factor const double curUserScaleX = m_xUserScale; const double curUserScaleY = m_yUserScale; // Change the scale temporarily to fit the drawing into the page. int w, h; psdc.GetSize(&w, &h); double sc = wxMin((double)w / width, (double)h / height); m_xUserScale *= sc; m_yUserScale *= sc; psdc.StartDoc("Drawing sample"); // Define default font. psdc.SetFont( wxFontInfo(10).Family(wxFONTFAMILY_MODERN) ); psdc.StartPage(); m_canvas->Draw(psdc); psdc.EndPage(); psdc.EndDoc(); // Restore original scale facor m_xUserScale = curUserScaleX; m_yUserScale = curUserScaleY; #if wxUSE_GRAPHICS_CONTEXT m_canvas->UseGraphicRenderer(curRenderer); #endif // wxUSE_GRAPHICS_CONTEXT } else #endif // wxUSE_POSTSCRIPT { wxBitmap bmp(width, height); wxMemoryDC mdc(bmp); mdc.SetBackground(*wxWHITE_BRUSH); mdc.Clear(); m_canvas->Draw(mdc); bmp.ConvertToImage().SaveFile(dlg.GetPath()); } } } void MyFrame::OnShow(wxCommandEvent& event) { const int show = event.GetId(); #if wxDRAWING_DC_SUPPORTS_ALPHA || wxUSE_GRAPHICS_CONTEXT // Make sure we do use a graphics context when selecting one of the screens // requiring it. #if wxDRAWING_DC_SUPPORTS_ALPHA // If DC supports drawing with alpha // then GC is necessary only for graphics screen. if ( show == File_ShowGraphics ) #else // wxUSE_GRAPHICS_CONTEXT // DC doesn't support drawing with alpha // so GC is necessary both for alpha and graphics screen. if ( show == File_ShowAlpha || show == File_ShowGraphics ) #endif // wxDRAWING_DC_SUPPORTS_ALPHA, wxUSE_GRAPHICS_CONTEXT { if ( !m_canvas->HasRenderer() ) m_canvas->UseGraphicRenderer(wxGraphicsRenderer::GetDefaultRenderer()); // Disable selecting wxDC, if necessary. m_menuItemUseDC->Enable(!m_canvas->HasRenderer()); } else { m_menuItemUseDC->Enable(true); } #endif // wxDRAWING_DC_SUPPORTS_ALPHA || wxUSE_GRAPHICS_CONTEXT m_canvas->ToShow(show); } void MyFrame::OnOption(wxCommandEvent& event) { switch (event.GetId()) { case MapMode_Text: m_mapMode = wxMM_TEXT; break; case MapMode_Lometric: m_mapMode = wxMM_LOMETRIC; break; case MapMode_Twips: m_mapMode = wxMM_TWIPS; break; case MapMode_Points: m_mapMode = wxMM_POINTS; break; case MapMode_Metric: m_mapMode = wxMM_METRIC; break; case LogicalOrigin_MoveDown: m_yLogicalOrigin += 10; break; case LogicalOrigin_MoveUp: m_yLogicalOrigin -= 10; break; case LogicalOrigin_MoveLeft: m_xLogicalOrigin += 10; break; case LogicalOrigin_MoveRight: m_xLogicalOrigin -= 10; break; case LogicalOrigin_Set: m_xLogicalOrigin = m_yLogicalOrigin = -100; break; case LogicalOrigin_Restore: m_xLogicalOrigin = m_yLogicalOrigin = 0; break; case UserScale_StretchHoriz: m_xUserScale *= 1.10; break; case UserScale_ShrinkHoriz: m_xUserScale /= 1.10; break; case UserScale_StretchVertic: m_yUserScale *= 1.10; break; case UserScale_ShrinkVertic: m_yUserScale /= 1.10; break; case UserScale_Restore: m_xUserScale = m_yUserScale = 1.0; break; case AxisMirror_Vertic: m_yAxisReversed = !m_yAxisReversed; break; case AxisMirror_Horiz: m_xAxisReversed = !m_xAxisReversed; break; #if wxUSE_DC_TRANSFORM_MATRIX case TransformMatrix_Set: { TransformDataDialog dlg(this, m_transform_dx, m_transform_dy, m_transform_scx, m_transform_scy, m_transform_rot); if ( dlg.ShowModal() == wxID_OK ) { dlg.GetTransformationData(&m_transform_dx, &m_transform_dy, &m_transform_scx, &m_transform_scy, &m_transform_rot); } } break; case TransformMatrix_Reset: m_transform_dx = 0.0; m_transform_dy = 0.0; m_transform_scx = 1.0; m_transform_scy = 1.0; m_transform_rot = 0.0; break; #endif // wxUSE_DC_TRANSFORM_MATRIX #if wxUSE_COLOURDLG case Colour_TextForeground: m_colourForeground = SelectColour(); break; case Colour_TextBackground: m_colourBackground = SelectColour(); break; case Colour_Background: { wxColour col = SelectColour(); if ( col.IsOk() ) { m_backgroundBrush.SetColour(col); } } break; #endif // wxUSE_COLOURDLG case Colour_BackgroundMode: m_backgroundMode = m_backgroundMode == wxBRUSHSTYLE_SOLID ? wxBRUSHSTYLE_TRANSPARENT : wxBRUSHSTYLE_SOLID; break; case Colour_TextureBackgound: m_textureBackground = ! m_textureBackground; break; default: // skip Refresh() return; } m_canvas->Refresh(); } void MyFrame::OnBoundingBox(wxCommandEvent& evt) { m_canvas->ShowBoundingBox(evt.IsChecked()); } void MyFrame::OnBoundingBoxUpdateUI(wxUpdateUIEvent& evt) { #if wxUSE_GRAPHICS_CONTEXT evt.Enable(m_canvas->GetPage() != File_ShowGraphics); #else wxUnusedVar(evt); #endif // wxUSE_GRAPHICS_CONTEXT / !wxUSE_GRAPHICS_CONTEXT } void MyFrame::PrepareDC(wxDC& dc) { #if wxUSE_DC_TRANSFORM_MATRIX if ( dc.CanUseTransformMatrix() ) { wxAffineMatrix2D mtx; mtx.Translate(m_transform_dx, m_transform_dy); mtx.Rotate(wxDegToRad(m_transform_rot)); mtx.Scale(m_transform_scx, m_transform_scy); dc.SetTransformMatrix(mtx); } #endif // wxUSE_DC_TRANSFORM_MATRIX dc.SetLogicalOrigin( m_xLogicalOrigin, m_yLogicalOrigin ); dc.SetAxisOrientation( !m_xAxisReversed, m_yAxisReversed ); dc.SetUserScale( m_xUserScale, m_yUserScale ); dc.SetMapMode( m_mapMode ); } #if wxUSE_COLOURDLG wxColour MyFrame::SelectColour() { wxColour col; wxColourData data; wxColourDialog dialog(this, &data); if ( dialog.ShowModal() == wxID_OK ) { col = dialog.GetColourData().GetColour(); } return col; } #endif // wxUSE_COLOURDLG
1,792
https://github.com/ddkq/dedao/blob/master/newshenzhen/shanghai/application/Api/Controller/AppController.class.php
Github Open Source
Open Source
Apache-2.0
2,019
dedao
ddkq
PHP
Code
38
162
<?php /** * 微信小程序 */ namespace Api\Controller; use Common\Controller\AppframeController; class AppController extends AppframeController { public function app_get_slide(){ $slide = I('slide'); $slides = sp_getslide($slide); foreach ($slides as $key => $value) { $slides[$key]['slide_pic'] = 'http://www.cdddkqyy.com'.$slides[$key]['slide_pic']; } $this->ajaxReturns($slides,"JSON") ; } }
7,049
https://github.com/Hyperfoil/Hyperfoil/blob/master/api/src/main/java/io/hyperfoil/api/session/WriteAccess.java
Github Open Source
Open Source
Apache-2.0
2,022
Hyperfoil
Hyperfoil
Java
Code
29
109
package io.hyperfoil.api.session; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public interface WriteAccess extends ReadAccess { Logger log = LogManager.getLogger(WriteAccess.class); boolean trace = log.isTraceEnabled(); void unset(Session session); Session.Var createVar(Session session, Session.Var existing); }
23,006
https://github.com/superk589/Family/blob/master/Sources/Shared/TypeAlias.swift
Github Open Source
Open Source
MIT
null
Family
superk589
Swift
Code
38
96
#if os(macOS) import Cocoa public typealias ViewController = NSViewController public typealias View = NSView public typealias Insets = NSEdgeInsets #else import UIKit public typealias ViewController = UIViewController public typealias View = UIView public typealias Insets = UIEdgeInsets #endif
357
https://github.com/hatpick/DroneMyoGlass/blob/master/jni/sdk/v2_0_1/ARDroneLib/FFMPEG/ffmpeg/libavcodec/error_resilience.c
Github Open Source
Open Source
Apache-2.0
2,022
DroneMyoGlass
hatpick
C
Code
3,599
16,746
/* * Error resilience / concealment * * Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * Error resilience / concealment. */ #include <limits.h> #include "avcodec.h" #include "dsputil.h" #include "mpegvideo.h" #include "h264.h" #include "rectangle.h" #include "thread.h" /* * H264 redefines mb_intra so it is not mistakely used (its uninitialized in h264) * but error concealment must support both h264 and h263 thus we must undo this */ #undef mb_intra static void decode_mb(MpegEncContext *s, int ref){ s->dest[0] = s->current_picture.data[0] + (s->mb_y * 16* s->linesize ) + s->mb_x * 16; s->dest[1] = s->current_picture.data[1] + (s->mb_y * (16>>s->chroma_y_shift) * s->uvlinesize) + s->mb_x * (16>>s->chroma_x_shift); s->dest[2] = s->current_picture.data[2] + (s->mb_y * (16>>s->chroma_y_shift) * s->uvlinesize) + s->mb_x * (16>>s->chroma_x_shift); if(CONFIG_H264_DECODER && s->codec_id == CODEC_ID_H264){ H264Context *h= (void*)s; h->mb_xy= s->mb_x + s->mb_y*s->mb_stride; memset(h->non_zero_count_cache, 0, sizeof(h->non_zero_count_cache)); assert(ref>=0); if(ref >= h->ref_count[0]) //FIXME it is posible albeit uncommon that slice references differ between slices, we take the easy approuch and ignore it for now. If this turns out to have any relevance in practice then correct remapping should be added ref=0; fill_rectangle(&s->current_picture.ref_index[0][4*h->mb_xy], 2, 2, 2, ref, 1); fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1); fill_rectangle(h->mv_cache[0][ scan8[0] ], 4, 4, 8, pack16to32(s->mv[0][0][0],s->mv[0][0][1]), 4); assert(!FRAME_MBAFF); ff_h264_hl_decode_mb(h); }else{ assert(ref==0); MPV_decode_mb(s, s->block); } } /** * @param stride the number of MVs to get to the next row * @param mv_step the number of MVs per row or column in a macroblock */ static void set_mv_strides(MpegEncContext *s, int *mv_step, int *stride){ if(s->codec_id == CODEC_ID_H264){ H264Context *h= (void*)s; assert(s->quarter_sample); *mv_step= 4; *stride= h->b_stride; }else{ *mv_step= 2; *stride= s->b8_stride; } } /** * replaces the current MB with a flat dc only version. */ static void put_dc(MpegEncContext *s, uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr, int mb_x, int mb_y) { int dc, dcu, dcv, y, i; for(i=0; i<4; i++){ dc= s->dc_val[0][mb_x*2 + (i&1) + (mb_y*2 + (i>>1))*s->b8_stride]; if(dc<0) dc=0; else if(dc>2040) dc=2040; for(y=0; y<8; y++){ int x; for(x=0; x<8; x++){ dest_y[x + (i&1)*8 + (y + (i>>1)*8)*s->linesize]= dc/8; } } } dcu = s->dc_val[1][mb_x + mb_y*s->mb_stride]; dcv = s->dc_val[2][mb_x + mb_y*s->mb_stride]; if (dcu<0 ) dcu=0; else if(dcu>2040) dcu=2040; if (dcv<0 ) dcv=0; else if(dcv>2040) dcv=2040; for(y=0; y<8; y++){ int x; for(x=0; x<8; x++){ dest_cb[x + y*(s->uvlinesize)]= dcu/8; dest_cr[x + y*(s->uvlinesize)]= dcv/8; } } } static void filter181(int16_t *data, int width, int height, int stride){ int x,y; /* horizontal filter */ for(y=1; y<height-1; y++){ int prev_dc= data[0 + y*stride]; for(x=1; x<width-1; x++){ int dc; dc= - prev_dc + data[x + y*stride]*8 - data[x + 1 + y*stride]; dc= (dc*10923 + 32768)>>16; prev_dc= data[x + y*stride]; data[x + y*stride]= dc; } } /* vertical filter */ for(x=1; x<width-1; x++){ int prev_dc= data[x]; for(y=1; y<height-1; y++){ int dc; dc= - prev_dc + data[x + y *stride]*8 - data[x + (y+1)*stride]; dc= (dc*10923 + 32768)>>16; prev_dc= data[x + y*stride]; data[x + y*stride]= dc; } } } /** * guess the dc of blocks which do not have an undamaged dc * @param w width in 8 pixel blocks * @param h height in 8 pixel blocks */ static void guess_dc(MpegEncContext *s, int16_t *dc, int w, int h, int stride, int is_luma){ int b_x, b_y; for(b_y=0; b_y<h; b_y++){ for(b_x=0; b_x<w; b_x++){ int color[4]={1024,1024,1024,1024}; int distance[4]={9999,9999,9999,9999}; int mb_index, error, j; int64_t guess, weight_sum; mb_index= (b_x>>is_luma) + (b_y>>is_luma)*s->mb_stride; error= s->error_status_table[mb_index]; if(IS_INTER(s->current_picture.mb_type[mb_index])) continue; //inter if(!(error&DC_ERROR)) continue; //dc-ok /* right block */ for(j=b_x+1; j<w; j++){ int mb_index_j= (j>>is_luma) + (b_y>>is_luma)*s->mb_stride; int error_j= s->error_status_table[mb_index_j]; int intra_j= IS_INTRA(s->current_picture.mb_type[mb_index_j]); if(intra_j==0 || !(error_j&DC_ERROR)){ color[0]= dc[j + b_y*stride]; distance[0]= j-b_x; break; } } /* left block */ for(j=b_x-1; j>=0; j--){ int mb_index_j= (j>>is_luma) + (b_y>>is_luma)*s->mb_stride; int error_j= s->error_status_table[mb_index_j]; int intra_j= IS_INTRA(s->current_picture.mb_type[mb_index_j]); if(intra_j==0 || !(error_j&DC_ERROR)){ color[1]= dc[j + b_y*stride]; distance[1]= b_x-j; break; } } /* bottom block */ for(j=b_y+1; j<h; j++){ int mb_index_j= (b_x>>is_luma) + (j>>is_luma)*s->mb_stride; int error_j= s->error_status_table[mb_index_j]; int intra_j= IS_INTRA(s->current_picture.mb_type[mb_index_j]); if(intra_j==0 || !(error_j&DC_ERROR)){ color[2]= dc[b_x + j*stride]; distance[2]= j-b_y; break; } } /* top block */ for(j=b_y-1; j>=0; j--){ int mb_index_j= (b_x>>is_luma) + (j>>is_luma)*s->mb_stride; int error_j= s->error_status_table[mb_index_j]; int intra_j= IS_INTRA(s->current_picture.mb_type[mb_index_j]); if(intra_j==0 || !(error_j&DC_ERROR)){ color[3]= dc[b_x + j*stride]; distance[3]= b_y-j; break; } } weight_sum=0; guess=0; for(j=0; j<4; j++){ int64_t weight= 256*256*256*16/distance[j]; guess+= weight*(int64_t)color[j]; weight_sum+= weight; } guess= (guess + weight_sum/2) / weight_sum; dc[b_x + b_y*stride]= guess; } } } /** * simple horizontal deblocking filter used for error resilience * @param w width in 8 pixel blocks * @param h height in 8 pixel blocks */ static void h_block_filter(MpegEncContext *s, uint8_t *dst, int w, int h, int stride, int is_luma){ int b_x, b_y, mvx_stride, mvy_stride; uint8_t *cm = ff_cropTbl + MAX_NEG_CROP; set_mv_strides(s, &mvx_stride, &mvy_stride); mvx_stride >>= is_luma; mvy_stride *= mvx_stride; for(b_y=0; b_y<h; b_y++){ for(b_x=0; b_x<w-1; b_x++){ int y; int left_status = s->error_status_table[( b_x >>is_luma) + (b_y>>is_luma)*s->mb_stride]; int right_status= s->error_status_table[((b_x+1)>>is_luma) + (b_y>>is_luma)*s->mb_stride]; int left_intra= IS_INTRA(s->current_picture.mb_type [( b_x >>is_luma) + (b_y>>is_luma)*s->mb_stride]); int right_intra= IS_INTRA(s->current_picture.mb_type [((b_x+1)>>is_luma) + (b_y>>is_luma)*s->mb_stride]); int left_damage = left_status&(DC_ERROR|AC_ERROR|MV_ERROR); int right_damage= right_status&(DC_ERROR|AC_ERROR|MV_ERROR); int offset= b_x*8 + b_y*stride*8; int16_t *left_mv= s->current_picture.motion_val[0][mvy_stride*b_y + mvx_stride* b_x ]; int16_t *right_mv= s->current_picture.motion_val[0][mvy_stride*b_y + mvx_stride*(b_x+1)]; if(!(left_damage||right_damage)) continue; // both undamaged if( (!left_intra) && (!right_intra) && FFABS(left_mv[0]-right_mv[0]) + FFABS(left_mv[1]+right_mv[1]) < 2) continue; for(y=0; y<8; y++){ int a,b,c,d; a= dst[offset + 7 + y*stride] - dst[offset + 6 + y*stride]; b= dst[offset + 8 + y*stride] - dst[offset + 7 + y*stride]; c= dst[offset + 9 + y*stride] - dst[offset + 8 + y*stride]; d= FFABS(b) - ((FFABS(a) + FFABS(c) + 1)>>1); d= FFMAX(d, 0); if(b<0) d= -d; if(d==0) continue; if(!(left_damage && right_damage)) d= d*16/9; if(left_damage){ dst[offset + 7 + y*stride] = cm[dst[offset + 7 + y*stride] + ((d*7)>>4)]; dst[offset + 6 + y*stride] = cm[dst[offset + 6 + y*stride] + ((d*5)>>4)]; dst[offset + 5 + y*stride] = cm[dst[offset + 5 + y*stride] + ((d*3)>>4)]; dst[offset + 4 + y*stride] = cm[dst[offset + 4 + y*stride] + ((d*1)>>4)]; } if(right_damage){ dst[offset + 8 + y*stride] = cm[dst[offset + 8 + y*stride] - ((d*7)>>4)]; dst[offset + 9 + y*stride] = cm[dst[offset + 9 + y*stride] - ((d*5)>>4)]; dst[offset + 10+ y*stride] = cm[dst[offset +10 + y*stride] - ((d*3)>>4)]; dst[offset + 11+ y*stride] = cm[dst[offset +11 + y*stride] - ((d*1)>>4)]; } } } } } /** * simple vertical deblocking filter used for error resilience * @param w width in 8 pixel blocks * @param h height in 8 pixel blocks */ static void v_block_filter(MpegEncContext *s, uint8_t *dst, int w, int h, int stride, int is_luma){ int b_x, b_y, mvx_stride, mvy_stride; uint8_t *cm = ff_cropTbl + MAX_NEG_CROP; set_mv_strides(s, &mvx_stride, &mvy_stride); mvx_stride >>= is_luma; mvy_stride *= mvx_stride; for(b_y=0; b_y<h-1; b_y++){ for(b_x=0; b_x<w; b_x++){ int x; int top_status = s->error_status_table[(b_x>>is_luma) + ( b_y >>is_luma)*s->mb_stride]; int bottom_status= s->error_status_table[(b_x>>is_luma) + ((b_y+1)>>is_luma)*s->mb_stride]; int top_intra= IS_INTRA(s->current_picture.mb_type [(b_x>>is_luma) + ( b_y >>is_luma)*s->mb_stride]); int bottom_intra= IS_INTRA(s->current_picture.mb_type [(b_x>>is_luma) + ((b_y+1)>>is_luma)*s->mb_stride]); int top_damage = top_status&(DC_ERROR|AC_ERROR|MV_ERROR); int bottom_damage= bottom_status&(DC_ERROR|AC_ERROR|MV_ERROR); int offset= b_x*8 + b_y*stride*8; int16_t *top_mv= s->current_picture.motion_val[0][mvy_stride* b_y + mvx_stride*b_x]; int16_t *bottom_mv= s->current_picture.motion_val[0][mvy_stride*(b_y+1) + mvx_stride*b_x]; if(!(top_damage||bottom_damage)) continue; // both undamaged if( (!top_intra) && (!bottom_intra) && FFABS(top_mv[0]-bottom_mv[0]) + FFABS(top_mv[1]+bottom_mv[1]) < 2) continue; for(x=0; x<8; x++){ int a,b,c,d; a= dst[offset + x + 7*stride] - dst[offset + x + 6*stride]; b= dst[offset + x + 8*stride] - dst[offset + x + 7*stride]; c= dst[offset + x + 9*stride] - dst[offset + x + 8*stride]; d= FFABS(b) - ((FFABS(a) + FFABS(c)+1)>>1); d= FFMAX(d, 0); if(b<0) d= -d; if(d==0) continue; if(!(top_damage && bottom_damage)) d= d*16/9; if(top_damage){ dst[offset + x + 7*stride] = cm[dst[offset + x + 7*stride] + ((d*7)>>4)]; dst[offset + x + 6*stride] = cm[dst[offset + x + 6*stride] + ((d*5)>>4)]; dst[offset + x + 5*stride] = cm[dst[offset + x + 5*stride] + ((d*3)>>4)]; dst[offset + x + 4*stride] = cm[dst[offset + x + 4*stride] + ((d*1)>>4)]; } if(bottom_damage){ dst[offset + x + 8*stride] = cm[dst[offset + x + 8*stride] - ((d*7)>>4)]; dst[offset + x + 9*stride] = cm[dst[offset + x + 9*stride] - ((d*5)>>4)]; dst[offset + x + 10*stride] = cm[dst[offset + x + 10*stride] - ((d*3)>>4)]; dst[offset + x + 11*stride] = cm[dst[offset + x + 11*stride] - ((d*1)>>4)]; } } } } } static void guess_mv(MpegEncContext *s){ uint8_t fixed[s->mb_stride * s->mb_height]; #define MV_FROZEN 3 #define MV_CHANGED 2 #define MV_UNCHANGED 1 const int mb_stride = s->mb_stride; const int mb_width = s->mb_width; const int mb_height= s->mb_height; int i, depth, num_avail; int mb_x, mb_y, mot_step, mot_stride; set_mv_strides(s, &mot_step, &mot_stride); num_avail=0; for(i=0; i<s->mb_num; i++){ const int mb_xy= s->mb_index2xy[ i ]; int f=0; int error= s->error_status_table[mb_xy]; if(IS_INTRA(s->current_picture.mb_type[mb_xy])) f=MV_FROZEN; //intra //FIXME check if(!(error&MV_ERROR)) f=MV_FROZEN; //inter with undamaged MV fixed[mb_xy]= f; if(f==MV_FROZEN) num_avail++; else if(s->last_picture.data[0] && s->last_picture.motion_val[0]){ const int mb_y= mb_xy / s->mb_stride; const int mb_x= mb_xy % s->mb_stride; const int mot_index= (mb_x + mb_y*mot_stride) * mot_step; s->current_picture.motion_val[0][mot_index][0]= s->last_picture.motion_val[0][mot_index][0]; s->current_picture.motion_val[0][mot_index][1]= s->last_picture.motion_val[0][mot_index][1]; s->current_picture.ref_index[0][4*mb_xy] = s->last_picture.ref_index[0][4*mb_xy]; } } if((!(s->avctx->error_concealment&FF_EC_GUESS_MVS)) || num_avail <= mb_width/2){ for(mb_y=0; mb_y<s->mb_height; mb_y++){ for(mb_x=0; mb_x<s->mb_width; mb_x++){ const int mb_xy= mb_x + mb_y*s->mb_stride; if(IS_INTRA(s->current_picture.mb_type[mb_xy])) continue; if(!(s->error_status_table[mb_xy]&MV_ERROR)) continue; s->mv_dir = s->last_picture.data[0] ? MV_DIR_FORWARD : MV_DIR_BACKWARD; s->mb_intra=0; s->mv_type = MV_TYPE_16X16; s->mb_skipped=0; s->dsp.clear_blocks(s->block[0]); s->mb_x= mb_x; s->mb_y= mb_y; s->mv[0][0][0]= 0; s->mv[0][0][1]= 0; decode_mb(s, 0); } } return; } for(depth=0;; depth++){ int changed, pass, none_left; none_left=1; changed=1; for(pass=0; (changed || pass<2) && pass<10; pass++){ int mb_x, mb_y; int score_sum=0; changed=0; for(mb_y=0; mb_y<s->mb_height; mb_y++){ for(mb_x=0; mb_x<s->mb_width; mb_x++){ const int mb_xy= mb_x + mb_y*s->mb_stride; int mv_predictor[8][2]={{0}}; int ref[8]={0}; int pred_count=0; int j; int best_score=256*256*256*64; int best_pred=0; const int mot_index= (mb_x + mb_y*mot_stride) * mot_step; int prev_x, prev_y, prev_ref; if((mb_x^mb_y^pass)&1) continue; if(fixed[mb_xy]==MV_FROZEN) continue; assert(!IS_INTRA(s->current_picture.mb_type[mb_xy])); assert(s->last_picture_ptr && s->last_picture_ptr->data[0]); j=0; if(mb_x>0 && fixed[mb_xy-1 ]==MV_FROZEN) j=1; if(mb_x+1<mb_width && fixed[mb_xy+1 ]==MV_FROZEN) j=1; if(mb_y>0 && fixed[mb_xy-mb_stride]==MV_FROZEN) j=1; if(mb_y+1<mb_height && fixed[mb_xy+mb_stride]==MV_FROZEN) j=1; if(j==0) continue; j=0; if(mb_x>0 && fixed[mb_xy-1 ]==MV_CHANGED) j=1; if(mb_x+1<mb_width && fixed[mb_xy+1 ]==MV_CHANGED) j=1; if(mb_y>0 && fixed[mb_xy-mb_stride]==MV_CHANGED) j=1; if(mb_y+1<mb_height && fixed[mb_xy+mb_stride]==MV_CHANGED) j=1; if(j==0 && pass>1) continue; none_left=0; if(mb_x>0 && fixed[mb_xy-1]){ mv_predictor[pred_count][0]= s->current_picture.motion_val[0][mot_index - mot_step][0]; mv_predictor[pred_count][1]= s->current_picture.motion_val[0][mot_index - mot_step][1]; ref [pred_count] = s->current_picture.ref_index[0][4*(mb_xy-1)]; pred_count++; } if(mb_x+1<mb_width && fixed[mb_xy+1]){ mv_predictor[pred_count][0]= s->current_picture.motion_val[0][mot_index + mot_step][0]; mv_predictor[pred_count][1]= s->current_picture.motion_val[0][mot_index + mot_step][1]; ref [pred_count] = s->current_picture.ref_index[0][4*(mb_xy+1)]; pred_count++; } if(mb_y>0 && fixed[mb_xy-mb_stride]){ mv_predictor[pred_count][0]= s->current_picture.motion_val[0][mot_index - mot_stride*mot_step][0]; mv_predictor[pred_count][1]= s->current_picture.motion_val[0][mot_index - mot_stride*mot_step][1]; ref [pred_count] = s->current_picture.ref_index[0][4*(mb_xy-s->mb_stride)]; pred_count++; } if(mb_y+1<mb_height && fixed[mb_xy+mb_stride]){ mv_predictor[pred_count][0]= s->current_picture.motion_val[0][mot_index + mot_stride*mot_step][0]; mv_predictor[pred_count][1]= s->current_picture.motion_val[0][mot_index + mot_stride*mot_step][1]; ref [pred_count] = s->current_picture.ref_index[0][4*(mb_xy+s->mb_stride)]; pred_count++; } if(pred_count==0) continue; if(pred_count>1){ int sum_x=0, sum_y=0, sum_r=0; int max_x, max_y, min_x, min_y, max_r, min_r; for(j=0; j<pred_count; j++){ sum_x+= mv_predictor[j][0]; sum_y+= mv_predictor[j][1]; sum_r+= ref[j]; if(j && ref[j] != ref[j-1]) goto skip_mean_and_median; } /* mean */ mv_predictor[pred_count][0] = sum_x/j; mv_predictor[pred_count][1] = sum_y/j; ref [pred_count] = sum_r/j; /* median */ if(pred_count>=3){ min_y= min_x= min_r= 99999; max_y= max_x= max_r=-99999; }else{ min_x=min_y=max_x=max_y=min_r=max_r=0; } for(j=0; j<pred_count; j++){ max_x= FFMAX(max_x, mv_predictor[j][0]); max_y= FFMAX(max_y, mv_predictor[j][1]); max_r= FFMAX(max_r, ref[j]); min_x= FFMIN(min_x, mv_predictor[j][0]); min_y= FFMIN(min_y, mv_predictor[j][1]); min_r= FFMIN(min_r, ref[j]); } mv_predictor[pred_count+1][0] = sum_x - max_x - min_x; mv_predictor[pred_count+1][1] = sum_y - max_y - min_y; ref [pred_count+1] = sum_r - max_r - min_r; if(pred_count==4){ mv_predictor[pred_count+1][0] /= 2; mv_predictor[pred_count+1][1] /= 2; ref [pred_count+1] /= 2; } pred_count+=2; } skip_mean_and_median: /* zero MV */ pred_count++; if (!fixed[mb_xy] && 0) { if (s->avctx->codec_id == CODEC_ID_H264) { // FIXME } else { ff_thread_await_progress((AVFrame *) s->last_picture_ptr, mb_y, 0); } if (!s->last_picture.motion_val[0] || !s->last_picture.ref_index[0]) goto skip_last_mv; prev_x = s->last_picture.motion_val[0][mot_index][0]; prev_y = s->last_picture.motion_val[0][mot_index][1]; prev_ref = s->last_picture.ref_index[0][4*mb_xy]; } else { prev_x = s->current_picture.motion_val[0][mot_index][0]; prev_y = s->current_picture.motion_val[0][mot_index][1]; prev_ref = s->current_picture.ref_index[0][4*mb_xy]; } /* last MV */ mv_predictor[pred_count][0]= prev_x; mv_predictor[pred_count][1]= prev_y; ref [pred_count] = prev_ref; pred_count++; skip_last_mv: s->mv_dir = MV_DIR_FORWARD; s->mb_intra=0; s->mv_type = MV_TYPE_16X16; s->mb_skipped=0; s->dsp.clear_blocks(s->block[0]); s->mb_x= mb_x; s->mb_y= mb_y; for(j=0; j<pred_count; j++){ int score=0; uint8_t *src= s->current_picture.data[0] + mb_x*16 + mb_y*16*s->linesize; s->current_picture.motion_val[0][mot_index][0]= s->mv[0][0][0]= mv_predictor[j][0]; s->current_picture.motion_val[0][mot_index][1]= s->mv[0][0][1]= mv_predictor[j][1]; if(ref[j]<0) //predictor intra or otherwise not available continue; decode_mb(s, ref[j]); if(mb_x>0 && fixed[mb_xy-1]){ int k; for(k=0; k<16; k++) score += FFABS(src[k*s->linesize-1 ]-src[k*s->linesize ]); } if(mb_x+1<mb_width && fixed[mb_xy+1]){ int k; for(k=0; k<16; k++) score += FFABS(src[k*s->linesize+15]-src[k*s->linesize+16]); } if(mb_y>0 && fixed[mb_xy-mb_stride]){ int k; for(k=0; k<16; k++) score += FFABS(src[k-s->linesize ]-src[k ]); } if(mb_y+1<mb_height && fixed[mb_xy+mb_stride]){ int k; for(k=0; k<16; k++) score += FFABS(src[k+s->linesize*15]-src[k+s->linesize*16]); } if(score <= best_score){ // <= will favor the last MV best_score= score; best_pred= j; } } score_sum+= best_score; s->mv[0][0][0]= mv_predictor[best_pred][0]; s->mv[0][0][1]= mv_predictor[best_pred][1]; for(i=0; i<mot_step; i++) for(j=0; j<mot_step; j++){ s->current_picture.motion_val[0][mot_index+i+j*mot_stride][0]= s->mv[0][0][0]; s->current_picture.motion_val[0][mot_index+i+j*mot_stride][1]= s->mv[0][0][1]; } decode_mb(s, ref[best_pred]); if(s->mv[0][0][0] != prev_x || s->mv[0][0][1] != prev_y){ fixed[mb_xy]=MV_CHANGED; changed++; }else fixed[mb_xy]=MV_UNCHANGED; } } // printf(".%d/%d", changed, score_sum); fflush(stdout); } if(none_left) return; for(i=0; i<s->mb_num; i++){ int mb_xy= s->mb_index2xy[i]; if(fixed[mb_xy]) fixed[mb_xy]=MV_FROZEN; } // printf(":"); fflush(stdout); } } static int is_intra_more_likely(MpegEncContext *s){ int is_intra_likely, i, j, undamaged_count, skip_amount, mb_x, mb_y; if(!s->last_picture_ptr || !s->last_picture_ptr->data[0]) return 1; //no previous frame available -> use spatial prediction undamaged_count=0; for(i=0; i<s->mb_num; i++){ const int mb_xy= s->mb_index2xy[i]; const int error= s->error_status_table[mb_xy]; if(!((error&DC_ERROR) && (error&MV_ERROR))) undamaged_count++; } if(s->codec_id == CODEC_ID_H264){ H264Context *h= (void*)s; if(h->ref_count[0] <= 0 || !h->ref_list[0][0].data[0]) return 1; } if(undamaged_count < 5) return 0; //almost all MBs damaged -> use temporal prediction //prevent dsp.sad() check, that requires access to the image if(CONFIG_MPEG_XVMC_DECODER && s->avctx->xvmc_acceleration && s->pict_type == AV_PICTURE_TYPE_I) return 1; skip_amount= FFMAX(undamaged_count/50, 1); //check only upto 50 MBs is_intra_likely=0; j=0; for(mb_y= 0; mb_y<s->mb_height-1; mb_y++){ for(mb_x= 0; mb_x<s->mb_width; mb_x++){ int error; const int mb_xy= mb_x + mb_y*s->mb_stride; error= s->error_status_table[mb_xy]; if((error&DC_ERROR) && (error&MV_ERROR)) continue; //skip damaged j++; if((j%skip_amount) != 0) continue; //skip a few to speed things up if(s->pict_type==AV_PICTURE_TYPE_I){ uint8_t *mb_ptr = s->current_picture.data[0] + mb_x*16 + mb_y*16*s->linesize; uint8_t *last_mb_ptr= s->last_picture.data [0] + mb_x*16 + mb_y*16*s->linesize; if (s->avctx->codec_id == CODEC_ID_H264) { // FIXME } else { ff_thread_await_progress((AVFrame *) s->last_picture_ptr, mb_y, 0); } is_intra_likely += s->dsp.sad[0](NULL, last_mb_ptr, mb_ptr , s->linesize, 16); // FIXME need await_progress() here is_intra_likely -= s->dsp.sad[0](NULL, last_mb_ptr, last_mb_ptr+s->linesize*16, s->linesize, 16); }else{ if(IS_INTRA(s->current_picture.mb_type[mb_xy])) is_intra_likely++; else is_intra_likely--; } } } //printf("is_intra_likely: %d type:%d\n", is_intra_likely, s->pict_type); return is_intra_likely > 0; } void ff_er_frame_start(MpegEncContext *s){ if(!s->error_recognition) return; memset(s->error_status_table, MV_ERROR|AC_ERROR|DC_ERROR|VP_START|AC_END|DC_END|MV_END, s->mb_stride*s->mb_height*sizeof(uint8_t)); s->error_count= 3*s->mb_num; s->error_occurred = 0; } /** * adds a slice. * @param endx x component of the last macroblock, can be -1 for the last of the previous line * @param status the status at the end (MV_END, AC_ERROR, ...), it is assumed that no earlier end or * error of the same type occurred */ void ff_er_add_slice(MpegEncContext *s, int startx, int starty, int endx, int endy, int status){ const int start_i= av_clip(startx + starty * s->mb_width , 0, s->mb_num-1); const int end_i = av_clip(endx + endy * s->mb_width , 0, s->mb_num); const int start_xy= s->mb_index2xy[start_i]; const int end_xy = s->mb_index2xy[end_i]; int mask= -1; if(s->avctx->hwaccel) return; if(start_i > end_i || start_xy > end_xy){ av_log(s->avctx, AV_LOG_ERROR, "internal error, slice end before start\n"); return; } if(!s->error_recognition) return; mask &= ~VP_START; if(status & (AC_ERROR|AC_END)){ mask &= ~(AC_ERROR|AC_END); s->error_count -= end_i - start_i + 1; } if(status & (DC_ERROR|DC_END)){ mask &= ~(DC_ERROR|DC_END); s->error_count -= end_i - start_i + 1; } if(status & (MV_ERROR|MV_END)){ mask &= ~(MV_ERROR|MV_END); s->error_count -= end_i - start_i + 1; } if(status & (AC_ERROR|DC_ERROR|MV_ERROR)) { s->error_occurred = 1; s->error_count= INT_MAX; } if(mask == ~0x7F){ memset(&s->error_status_table[start_xy], 0, (end_xy - start_xy) * sizeof(uint8_t)); }else{ int i; for(i=start_xy; i<end_xy; i++){ s->error_status_table[ i ] &= mask; } } if(end_i == s->mb_num) s->error_count= INT_MAX; else{ s->error_status_table[end_xy] &= mask; s->error_status_table[end_xy] |= status; } s->error_status_table[start_xy] |= VP_START; if(start_xy > 0 && s->avctx->thread_count <= 1 && s->avctx->skip_top*s->mb_width < start_i){ int prev_status= s->error_status_table[ s->mb_index2xy[start_i - 1] ]; prev_status &= ~ VP_START; if(prev_status != (MV_END|DC_END|AC_END)) s->error_count= INT_MAX; } } void ff_er_frame_end(MpegEncContext *s){ int i, mb_x, mb_y, error, error_type, dc_error, mv_error, ac_error; int distance; int threshold_part[4]= {100,100,100}; int threshold= 50; int is_intra_likely; int size = s->b8_stride * 2 * s->mb_height; Picture *pic= s->current_picture_ptr; if(!s->error_recognition || s->error_count==0 || s->avctx->lowres || s->avctx->hwaccel || s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU || s->picture_structure != PICT_FRAME || // we dont support ER of field pictures yet, though it should not crash if enabled s->error_count==3*s->mb_width*(s->avctx->skip_top + s->avctx->skip_bottom)) return; if(s->current_picture.motion_val[0] == NULL){ av_log(s->avctx, AV_LOG_ERROR, "Warning MVs not available\n"); for(i=0; i<2; i++){ pic->ref_index[i]= av_mallocz(s->mb_stride * s->mb_height * 4 * sizeof(uint8_t)); pic->motion_val_base[i]= av_mallocz((size+4) * 2 * sizeof(uint16_t)); pic->motion_val[i]= pic->motion_val_base[i]+4; } pic->motion_subsample_log2= 3; s->current_picture= *s->current_picture_ptr; } if(s->avctx->debug&FF_DEBUG_ER){ for(mb_y=0; mb_y<s->mb_height; mb_y++){ for(mb_x=0; mb_x<s->mb_width; mb_x++){ int status= s->error_status_table[mb_x + mb_y*s->mb_stride]; av_log(s->avctx, AV_LOG_DEBUG, "%2X ", status); } av_log(s->avctx, AV_LOG_DEBUG, "\n"); } } #if 1 /* handle overlapping slices */ for(error_type=1; error_type<=3; error_type++){ int end_ok=0; for(i=s->mb_num-1; i>=0; i--){ const int mb_xy= s->mb_index2xy[i]; int error= s->error_status_table[mb_xy]; if(error&(1<<error_type)) end_ok=1; if(error&(8<<error_type)) end_ok=1; if(!end_ok) s->error_status_table[mb_xy]|= 1<<error_type; if(error&VP_START) end_ok=0; } } #endif #if 1 /* handle slices with partitions of different length */ if(s->partitioned_frame){ int end_ok=0; for(i=s->mb_num-1; i>=0; i--){ const int mb_xy= s->mb_index2xy[i]; int error= s->error_status_table[mb_xy]; if(error&AC_END) end_ok=0; if((error&MV_END) || (error&DC_END) || (error&AC_ERROR)) end_ok=1; if(!end_ok) s->error_status_table[mb_xy]|= AC_ERROR; if(error&VP_START) end_ok=0; } } #endif /* handle missing slices */ if(s->error_recognition>=4){ int end_ok=1; for(i=s->mb_num-2; i>=s->mb_width+100; i--){ //FIXME +100 hack const int mb_xy= s->mb_index2xy[i]; int error1= s->error_status_table[mb_xy ]; int error2= s->error_status_table[s->mb_index2xy[i+1]]; if(error1&VP_START) end_ok=1; if( error2==(VP_START|DC_ERROR|AC_ERROR|MV_ERROR|AC_END|DC_END|MV_END) && error1!=(VP_START|DC_ERROR|AC_ERROR|MV_ERROR|AC_END|DC_END|MV_END) && ((error1&AC_END) || (error1&DC_END) || (error1&MV_END))){ //end & uninit end_ok=0; } if(!end_ok) s->error_status_table[mb_xy]|= DC_ERROR|AC_ERROR|MV_ERROR; } } #if 1 /* backward mark errors */ distance=9999999; for(error_type=1; error_type<=3; error_type++){ for(i=s->mb_num-1; i>=0; i--){ const int mb_xy= s->mb_index2xy[i]; int error= s->error_status_table[mb_xy]; if(!s->mbskip_table[mb_xy]) //FIXME partition specific distance++; if(error&(1<<error_type)) distance= 0; if(s->partitioned_frame){ if(distance < threshold_part[error_type-1]) s->error_status_table[mb_xy]|= 1<<error_type; }else{ if(distance < threshold) s->error_status_table[mb_xy]|= 1<<error_type; } if(error&VP_START) distance= 9999999; } } #endif /* forward mark errors */ error=0; for(i=0; i<s->mb_num; i++){ const int mb_xy= s->mb_index2xy[i]; int old_error= s->error_status_table[mb_xy]; if(old_error&VP_START) error= old_error& (DC_ERROR|AC_ERROR|MV_ERROR); else{ error|= old_error& (DC_ERROR|AC_ERROR|MV_ERROR); s->error_status_table[mb_xy]|= error; } } #if 1 /* handle not partitioned case */ if(!s->partitioned_frame){ for(i=0; i<s->mb_num; i++){ const int mb_xy= s->mb_index2xy[i]; error= s->error_status_table[mb_xy]; if(error&(AC_ERROR|DC_ERROR|MV_ERROR)) error|= AC_ERROR|DC_ERROR|MV_ERROR; s->error_status_table[mb_xy]= error; } } #endif dc_error= ac_error= mv_error=0; for(i=0; i<s->mb_num; i++){ const int mb_xy= s->mb_index2xy[i]; error= s->error_status_table[mb_xy]; if(error&DC_ERROR) dc_error ++; if(error&AC_ERROR) ac_error ++; if(error&MV_ERROR) mv_error ++; } av_log(s->avctx, AV_LOG_INFO, "concealing %d DC, %d AC, %d MV errors\n", dc_error, ac_error, mv_error); is_intra_likely= is_intra_more_likely(s); /* set unknown mb-type to most likely */ for(i=0; i<s->mb_num; i++){ const int mb_xy= s->mb_index2xy[i]; error= s->error_status_table[mb_xy]; if(!((error&DC_ERROR) && (error&MV_ERROR))) continue; if(is_intra_likely) s->current_picture.mb_type[mb_xy]= MB_TYPE_INTRA4x4; else s->current_picture.mb_type[mb_xy]= MB_TYPE_16x16 | MB_TYPE_L0; } // change inter to intra blocks if no reference frames are available if (!s->last_picture.data[0] && !s->next_picture.data[0]) for(i=0; i<s->mb_num; i++){ const int mb_xy= s->mb_index2xy[i]; if(!IS_INTRA(s->current_picture.mb_type[mb_xy])) s->current_picture.mb_type[mb_xy]= MB_TYPE_INTRA4x4; } /* handle inter blocks with damaged AC */ for(mb_y=0; mb_y<s->mb_height; mb_y++){ for(mb_x=0; mb_x<s->mb_width; mb_x++){ const int mb_xy= mb_x + mb_y * s->mb_stride; const int mb_type= s->current_picture.mb_type[mb_xy]; int dir = !s->last_picture.data[0]; error= s->error_status_table[mb_xy]; if(IS_INTRA(mb_type)) continue; //intra if(error&MV_ERROR) continue; //inter with damaged MV if(!(error&AC_ERROR)) continue; //undamaged inter s->mv_dir = dir ? MV_DIR_BACKWARD : MV_DIR_FORWARD; s->mb_intra=0; s->mb_skipped=0; if(IS_8X8(mb_type)){ int mb_index= mb_x*2 + mb_y*2*s->b8_stride; int j; s->mv_type = MV_TYPE_8X8; for(j=0; j<4; j++){ s->mv[0][j][0] = s->current_picture.motion_val[dir][ mb_index + (j&1) + (j>>1)*s->b8_stride ][0]; s->mv[0][j][1] = s->current_picture.motion_val[dir][ mb_index + (j&1) + (j>>1)*s->b8_stride ][1]; } }else{ s->mv_type = MV_TYPE_16X16; s->mv[0][0][0] = s->current_picture.motion_val[dir][ mb_x*2 + mb_y*2*s->b8_stride ][0]; s->mv[0][0][1] = s->current_picture.motion_val[dir][ mb_x*2 + mb_y*2*s->b8_stride ][1]; } s->dsp.clear_blocks(s->block[0]); s->mb_x= mb_x; s->mb_y= mb_y; decode_mb(s, 0/*FIXME h264 partitioned slices need this set*/); } } /* guess MVs */ if(s->pict_type==AV_PICTURE_TYPE_B){ for(mb_y=0; mb_y<s->mb_height; mb_y++){ for(mb_x=0; mb_x<s->mb_width; mb_x++){ int xy= mb_x*2 + mb_y*2*s->b8_stride; const int mb_xy= mb_x + mb_y * s->mb_stride; const int mb_type= s->current_picture.mb_type[mb_xy]; error= s->error_status_table[mb_xy]; if(IS_INTRA(mb_type)) continue; if(!(error&MV_ERROR)) continue; //inter with undamaged MV if(!(error&AC_ERROR)) continue; //undamaged inter s->mv_dir = MV_DIR_FORWARD|MV_DIR_BACKWARD; if(!s->last_picture.data[0]) s->mv_dir &= ~MV_DIR_FORWARD; if(!s->next_picture.data[0]) s->mv_dir &= ~MV_DIR_BACKWARD; s->mb_intra=0; s->mv_type = MV_TYPE_16X16; s->mb_skipped=0; if(s->pp_time){ int time_pp= s->pp_time; int time_pb= s->pb_time; if (s->avctx->codec_id == CODEC_ID_H264) { //FIXME } else { ff_thread_await_progress((AVFrame *) s->next_picture_ptr, mb_y, 0); } s->mv[0][0][0] = s->next_picture.motion_val[0][xy][0]*time_pb/time_pp; s->mv[0][0][1] = s->next_picture.motion_val[0][xy][1]*time_pb/time_pp; s->mv[1][0][0] = s->next_picture.motion_val[0][xy][0]*(time_pb - time_pp)/time_pp; s->mv[1][0][1] = s->next_picture.motion_val[0][xy][1]*(time_pb - time_pp)/time_pp; }else{ s->mv[0][0][0]= 0; s->mv[0][0][1]= 0; s->mv[1][0][0]= 0; s->mv[1][0][1]= 0; } s->dsp.clear_blocks(s->block[0]); s->mb_x= mb_x; s->mb_y= mb_y; decode_mb(s, 0); } } }else guess_mv(s); /* the filters below are not XvMC compatible, skip them */ if(CONFIG_MPEG_XVMC_DECODER && s->avctx->xvmc_acceleration) goto ec_clean; /* fill DC for inter blocks */ for(mb_y=0; mb_y<s->mb_height; mb_y++){ for(mb_x=0; mb_x<s->mb_width; mb_x++){ int dc, dcu, dcv, y, n; int16_t *dc_ptr; uint8_t *dest_y, *dest_cb, *dest_cr; const int mb_xy= mb_x + mb_y * s->mb_stride; const int mb_type= s->current_picture.mb_type[mb_xy]; error= s->error_status_table[mb_xy]; if(IS_INTRA(mb_type) && s->partitioned_frame) continue; // if(error&MV_ERROR) continue; //inter data damaged FIXME is this good? dest_y = s->current_picture.data[0] + mb_x*16 + mb_y*16*s->linesize; dest_cb= s->current_picture.data[1] + mb_x*8 + mb_y*8 *s->uvlinesize; dest_cr= s->current_picture.data[2] + mb_x*8 + mb_y*8 *s->uvlinesize; dc_ptr= &s->dc_val[0][mb_x*2 + mb_y*2*s->b8_stride]; for(n=0; n<4; n++){ dc=0; for(y=0; y<8; y++){ int x; for(x=0; x<8; x++){ dc+= dest_y[x + (n&1)*8 + (y + (n>>1)*8)*s->linesize]; } } dc_ptr[(n&1) + (n>>1)*s->b8_stride]= (dc+4)>>3; } dcu=dcv=0; for(y=0; y<8; y++){ int x; for(x=0; x<8; x++){ dcu+=dest_cb[x + y*(s->uvlinesize)]; dcv+=dest_cr[x + y*(s->uvlinesize)]; } } s->dc_val[1][mb_x + mb_y*s->mb_stride]= (dcu+4)>>3; s->dc_val[2][mb_x + mb_y*s->mb_stride]= (dcv+4)>>3; } } #if 1 /* guess DC for damaged blocks */ guess_dc(s, s->dc_val[0], s->mb_width*2, s->mb_height*2, s->b8_stride, 1); guess_dc(s, s->dc_val[1], s->mb_width , s->mb_height , s->mb_stride, 0); guess_dc(s, s->dc_val[2], s->mb_width , s->mb_height , s->mb_stride, 0); #endif /* filter luma DC */ filter181(s->dc_val[0], s->mb_width*2, s->mb_height*2, s->b8_stride); #if 1 /* render DC only intra */ for(mb_y=0; mb_y<s->mb_height; mb_y++){ for(mb_x=0; mb_x<s->mb_width; mb_x++){ uint8_t *dest_y, *dest_cb, *dest_cr; const int mb_xy= mb_x + mb_y * s->mb_stride; const int mb_type= s->current_picture.mb_type[mb_xy]; error= s->error_status_table[mb_xy]; if(IS_INTER(mb_type)) continue; if(!(error&AC_ERROR)) continue; //undamaged dest_y = s->current_picture.data[0] + mb_x*16 + mb_y*16*s->linesize; dest_cb= s->current_picture.data[1] + mb_x*8 + mb_y*8 *s->uvlinesize; dest_cr= s->current_picture.data[2] + mb_x*8 + mb_y*8 *s->uvlinesize; put_dc(s, dest_y, dest_cb, dest_cr, mb_x, mb_y); } } #endif if(s->avctx->error_concealment&FF_EC_DEBLOCK){ /* filter horizontal block boundaries */ h_block_filter(s, s->current_picture.data[0], s->mb_width*2, s->mb_height*2, s->linesize , 1); h_block_filter(s, s->current_picture.data[1], s->mb_width , s->mb_height , s->uvlinesize, 0); h_block_filter(s, s->current_picture.data[2], s->mb_width , s->mb_height , s->uvlinesize, 0); /* filter vertical block boundaries */ v_block_filter(s, s->current_picture.data[0], s->mb_width*2, s->mb_height*2, s->linesize , 1); v_block_filter(s, s->current_picture.data[1], s->mb_width , s->mb_height , s->uvlinesize, 0); v_block_filter(s, s->current_picture.data[2], s->mb_width , s->mb_height , s->uvlinesize, 0); } ec_clean: /* clean a few tables */ for(i=0; i<s->mb_num; i++){ const int mb_xy= s->mb_index2xy[i]; int error= s->error_status_table[mb_xy]; if(s->pict_type!=AV_PICTURE_TYPE_B && (error&(DC_ERROR|MV_ERROR|AC_ERROR))){ s->mbskip_table[mb_xy]=0; } s->mbintra_table[mb_xy]=1; } }
31,968
https://github.com/accup/VyJit/blob/master/src/canvas-renderer/index.ts
Github Open Source
Open Source
MIT
2,021
VyJit
accup
TypeScript
Code
16
31
export * from './core' export * from './color' export * from './plot' export * from './pseudocolor'
13,516
https://github.com/Sevgo24/Proyect_SRGDA/blob/master/SGRDA.DA/DATipoenvioFactura.cs
Github Open Source
Open Source
Unlicense
2,021
Proyect_SRGDA
Sevgo24
C#
Code
337
1,893
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Practices.EnterpriseLibrary.Common; using Microsoft.Practices.EnterpriseLibrary.Data; using Microsoft.Practices.ServiceLocation; using SGRDA.Entities; using System.Data.Common; using System.Data; namespace SGRDA.DA { public class DATipoenvioFactura { private Database oDataBase = new DatabaseProviderFactory().Create("conexion"); public List<BETipoenvioFactura> ListarPaginacion(string owner, string param, int st, int pagina, int cantRegxPag) { DbCommand oDbCommand = oDataBase.GetStoredProcCommand("SGRDASS_LISTAR_TIPOENVIOFACTURA_PAGE"); oDataBase.AddInParameter(oDbCommand, "@owner", DbType.String, owner); oDataBase.AddInParameter(oDbCommand, "@param", DbType.String, param); oDataBase.AddInParameter(oDbCommand, "@estado", DbType.Int32, st); oDataBase.AddInParameter(oDbCommand, "@PageIndex", DbType.Int32, 50); oDataBase.AddInParameter(oDbCommand, "@PageSize", DbType.Int32, 50); oDataBase.AddOutParameter(oDbCommand, "@RecordCount", DbType.Int32, 50); oDataBase.ExecuteNonQuery(oDbCommand); string results = Convert.ToString(oDataBase.GetParameterValue(oDbCommand, "@RecordCount")); Database oDataBase1 = new DatabaseProviderFactory().Create("conexion"); DbCommand oDbCommand1 = oDataBase1.GetStoredProcCommand("SGRDASS_LISTAR_TIPOENVIOFACTURA_PAGE", owner, param, st, pagina, cantRegxPag, ParameterDirection.Output); var lista = new List<BETipoenvioFactura>(); //var Tipoenviofactura = new BETipoenvioFactura(); using (IDataReader reader = oDataBase1.ExecuteReader(oDbCommand1)) { while (reader.Read()) lista.Add(new BETipoenvioFactura(reader, Convert.ToInt32(results))); } return lista; } public int Eliminar(BETipoenvioFactura TipoenvioFactura) { DbCommand oDbCommand = oDataBase.GetStoredProcCommand("SGRDASU_INACTIVAR_TIPOENVIOFACTURA"); oDataBase.AddInParameter(oDbCommand, "@OWNER", DbType.String, TipoenvioFactura.OWNER); oDataBase.AddInParameter(oDbCommand, "@LIC_SEND", DbType.String, TipoenvioFactura.LIC_SEND); oDataBase.AddInParameter(oDbCommand, "@LOG_USER_UPDATE", DbType.String, TipoenvioFactura.LOG_USER_UPDATE); int r = oDataBase.ExecuteNonQuery(oDbCommand); return r; } public int Insertar(BETipoenvioFactura TipoenvioFactura) { DbCommand oDbCommand = oDataBase.GetStoredProcCommand("SGRDASI_TIPOENVIOFACTURA"); oDataBase.AddInParameter(oDbCommand, "@OWNER", DbType.String, TipoenvioFactura.OWNER); oDataBase.AddInParameter(oDbCommand, "@LIC_FSEND", DbType.String, TipoenvioFactura.LIC_FSEND.ToUpper()); oDataBase.AddInParameter(oDbCommand, "@LOG_USER_CREAT", DbType.String, TipoenvioFactura.LOG_USER_CREAT); int n = oDataBase.ExecuteNonQuery(oDbCommand); return n; } public BETipoenvioFactura Obtener(string owner, decimal id) { DbCommand oDbCommand = oDataBase.GetStoredProcCommand("SGRDASS_OBTENER_TIPOENVIOFACTURA"); oDataBase.AddInParameter(oDbCommand, "@OWNER", DbType.String, owner); oDataBase.AddInParameter(oDbCommand, "@LIC_SEND", DbType.String, id); BETipoenvioFactura ent = null; using (IDataReader dr = oDataBase.ExecuteReader(oDbCommand)) { while (dr.Read()) { ent = new BETipoenvioFactura(); ent.OWNER = dr.GetString(dr.GetOrdinal("OWNER")); ent.LIC_SEND = dr.GetDecimal(dr.GetOrdinal("LIC_SEND")); ent.LIC_FSEND = dr.GetString(dr.GetOrdinal("LIC_FSEND")); } } return ent; } public int Actualizar(BETipoenvioFactura TipoenvioFactura) { DbCommand oDbCommand = oDataBase.GetStoredProcCommand("SGRDASU_TIPOENVIOFACTURA"); oDataBase.AddInParameter(oDbCommand, "@OWNER", DbType.String, TipoenvioFactura.OWNER); oDataBase.AddInParameter(oDbCommand, "@LIC_SEND", DbType.String, TipoenvioFactura.LIC_SEND); oDataBase.AddInParameter(oDbCommand, "@LIC_FSEND", DbType.String, TipoenvioFactura.LIC_FSEND.ToUpper()); oDataBase.AddInParameter(oDbCommand, "@LOG_USER_UPDATE", DbType.String, TipoenvioFactura.LOG_USER_UPDATE); int r = oDataBase.ExecuteNonQuery(oDbCommand); return r; } public int ObtenerXDescripcion(BETipoenvioFactura TipoenvioFactura) { DbCommand oDbCommand = oDataBase.GetStoredProcCommand("SGRDASS_OBTENER_TIPOENVIOFACTURA_DESC"); oDataBase.AddInParameter(oDbCommand, "@OWNER", DbType.String, TipoenvioFactura.OWNER); oDataBase.AddInParameter(oDbCommand, "@LIC_FSEND", DbType.String, TipoenvioFactura.LIC_FSEND); int r = Convert.ToInt32(oDataBase.ExecuteScalar(oDbCommand)); return r; } public List<BETipoenvioFactura> Listar(string owner) { DbCommand oDbCommand = oDataBase.GetStoredProcCommand("SGRDASS_TIPO_ENVIO_FAC"); oDataBase.AddInParameter(oDbCommand, "@owner", DbType.String, owner); var lista = new List<BETipoenvioFactura>(); using (IDataReader dr = oDataBase.ExecuteReader(oDbCommand)) { BETipoenvioFactura ent = new BETipoenvioFactura(); while (dr.Read()) { ent = new BETipoenvioFactura(); ent.OWNER = dr.GetString(dr.GetOrdinal("OWNER")); ent.LIC_SEND = dr.GetDecimal(dr.GetOrdinal("LIC_SEND")); ent.LIC_FSEND = dr.GetString(dr.GetOrdinal("LIC_FSEND")); lista.Add(ent); } } return lista; } } }
9,625
https://github.com/remiX-/ImgurUploader/blob/master/src/ImgurModels/LocalImage.cs
Github Open Source
Open Source
MIT
null
ImgurUploader
remiX-
C#
Code
101
314
using Prism.Mvvm; using System.IO; namespace ImgurUploader { public class LocalImage : BindableBase { #region Vars string localPath; string fileName; long fileSize; public string LocalPath { get { return localPath; } set { SetProperty(ref localPath, value); FileInfo fi = new FileInfo(LocalPath); if (fi.Exists) { fileName = fi.Name; fileSize = fi.Length / 1000; } } } public string FileName { get { return fileName; } set { SetProperty(ref fileName, value); } } public long FileSize { get { return fileSize; } set { SetProperty(ref fileSize, value); } } #endregion public LocalImage(string localPath) { if (!string.IsNullOrWhiteSpace(localPath)) { LocalPath = localPath; } } } }
7,343
https://github.com/jmaargh/punter/blob/master/.gitignore
Github Open Source
Open Source
MIT
2,019
punter
jmaargh
Ignore List
Code
2
11
/target /image.png
22,882
https://github.com/thamerla/SocialOpinion-Public/blob/master/SocialOpinionAPI/Core/RequestBuilder.cs
Github Open Source
Open Source
MIT
2,021
SocialOpinion-Public
thamerla
C#
Code
500
1,822
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; namespace SocialOpinionAPI.Core { public class RequestBuilder { private const string VERSION = "1.0"; private const string SIGNATURE_METHOD = "HMAC-SHA1"; private readonly OAuthInfo oauth; private readonly string method; private readonly IDictionary<string, string> customParameters; private readonly string url; public RequestBuilder(OAuthInfo oauth, string method, string url) { this.oauth = oauth; this.method = method; this.url = url; customParameters = new Dictionary<string, string>(); } public RequestBuilder AddParameter(string name, string value) { customParameters.Add(name, value.EncodeDataString()); return this; } public string ExecuteJsonParamsInBody(string postBody) { var timespan = GetTimestamp(); var nonce = CreateNonce(); var parameters = new Dictionary<string, string>(customParameters); AddOAuthParameters(parameters, timespan, nonce); var signature = GenerateSignature(parameters); var headerValue = GenerateAuthorizationHeaderValue(parameters, signature); var request = (HttpWebRequest)WebRequest.Create(GetRequestUrl()); request.Method = method; request.ContentType = "application/json"; request.Headers.Add("Authorization", headerValue); WriteRequestBody(request, postBody); var response = request.GetResponse(); string content; using (var stream = response.GetResponseStream()) { using (var reader = new StreamReader(stream)) { content = reader.ReadToEnd(); } } request.Abort(); return content; } public string Execute() { var timespan = GetTimestamp(); var nonce = CreateNonce(); var parameters = new Dictionary<string, string>(customParameters); AddOAuthParameters(parameters, timespan, nonce); var signature = GenerateSignature(parameters); var headerValue = GenerateAuthorizationHeaderValue(parameters, signature); var request = (HttpWebRequest)WebRequest.Create(GetRequestUrl()); request.Method = method; request.ContentType = "application/x-www-form-urlencoded"; request.Headers.Add("Authorization", headerValue); WriteRequestBody(request); // It looks like a bug in HttpWebRequest. It throws random TimeoutExceptions // after some requests. Abort the request seems to work. More info: // http://stackoverflow.com/questions/2252762/getrequeststream-throws-timeout-exception-randomly var response = request.GetResponse(); string content; using (var stream = response.GetResponseStream()) { using (var reader = new StreamReader(stream)) { content = reader.ReadToEnd(); } } request.Abort(); return content; } private void WriteRequestBody(HttpWebRequest request) { if (method == "GET") return; var requestBody = Encoding.ASCII.GetBytes(GetCustomParametersString()); using (var stream = request.GetRequestStream()) stream.Write(requestBody, 0, requestBody.Length); } private void WriteRequestBody(HttpWebRequest request, string body) { if (method == "GET") return; var requestBody = Encoding.ASCII.GetBytes(body); using (var stream = request.GetRequestStream()) stream.Write(requestBody, 0, requestBody.Length); } private string GetRequestUrl() { if (method != "GET" || customParameters.Count == 0) return url; return string.Format("{0}?{1}", url, GetCustomParametersString()); } private string GetCustomParametersString() { return customParameters.Select(x => string.Format("{0}={1}", x.Key, x.Value)).Join("&"); } private string GenerateAuthorizationHeaderValue(IEnumerable<KeyValuePair<string, string>> parameters, string signature) { return new StringBuilder("OAuth ") .Append(parameters.Concat(new KeyValuePair<string, string>("oauth_signature", signature)) .Where(x => x.Key.StartsWith("oauth_")) .Select(x => string.Format("{0}=\"{1}\"", x.Key, x.Value.EncodeDataString())) .Join(",")) .ToString(); } private string GenerateSignature(IEnumerable<KeyValuePair<string, string>> parameters) { var dataToSign = new StringBuilder() .Append(method).Append("&") .Append(url.EncodeDataString()).Append("&") .Append(parameters .OrderBy(x => x.Key) .Select(x => string.Format("{0}={1}", x.Key, x.Value)) .Join("&") .EncodeDataString()); var signatureKey = string.Format("{0}&{1}", oauth.ConsumerSecret.EncodeDataString(), oauth.AccessSecret.EncodeDataString()); var sha1 = new HMACSHA1(Encoding.ASCII.GetBytes(signatureKey)); var signatureBytes = sha1.ComputeHash(Encoding.ASCII.GetBytes(dataToSign.ToString())); return Convert.ToBase64String(signatureBytes); } private void AddOAuthParameters(IDictionary<string, string> parameters, string timestamp, string nonce) { parameters.Add("oauth_version", VERSION); parameters.Add("oauth_consumer_key", oauth.ConsumerKey); parameters.Add("oauth_nonce", nonce); parameters.Add("oauth_signature_method", SIGNATURE_METHOD); parameters.Add("oauth_timestamp", timestamp); parameters.Add("oauth_token", oauth.AccessToken); } private static string GetTimestamp() { return ((int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString(); } private static string CreateNonce() { return new Random().Next(0x0000000, 0x7fffffff).ToString("X8"); } } public static class RequestBuilderExtensions { public static string Join<T>(this IEnumerable<T> items, string separator) { return string.Join(separator, items.ToArray()); } public static IEnumerable<T> Concat<T>(this IEnumerable<T> items, T value) { return items.Concat(new[] { value }); } public static string EncodeDataString(this string value) { if (string.IsNullOrEmpty(value)) return string.Empty; return Uri.EscapeDataString(value); } } }
32,327
https://github.com/andes/andes-fhir-server/blob/master/src/config.ts
Github Open Source
Open Source
MIT
2,020
andes-fhir-server
andes
TypeScript
Code
242
860
const { VERSIONS } = require('@asymmetrik/node-fhir-server-core').constants; /** * @name mongoConfig * @summary Configurations for our Mongo instance */ export const mongoConfig = { connection: process.env.MONGO_HOSTNAME, db_name: process.env.MONGO_DB_NAME, options: { auto_reconnect: true, useUnifiedTopology: true } }; // Set up whitelist let whitelist_env = process.env.WHITELIST && process.env.WHITELIST.split(',').map(host => host.trim()) || false; // If no whitelist is present, disable cors // If it's length is 1, set it to a string, so * works // If there are multiple, keep them as an array let whitelist = whitelist_env && whitelist_env.length === 1 ? whitelist_env[0] : whitelist_env; const AUTH = process.env.SERVER_AUTH === 'true'; /** * @name fhirServerConfig * @summary @asymmetrik/node-fhir-server-core configurations. */ export const fhirServerConfig = { auth: AUTH ? { // En este caso estoy poniendo esto para que me lea el scope automáticamente. // type: 'smart', // resourceServer: 'http://localhost:3000', strategy: { name: 'bearer', service: './src/services/auth/auth.service.js' } } : undefined, server: { // support various ENV that uses PORT vs SERVER_PORT port: process.env.PORT || 3000, // allow Access-Control-Allow-Origin corsOptions: { maxAge: 86400, origin: whitelist } }, logging: { level: process.env.LOGGING_LEVEL }, // security: [ // { // url: 'authorize', // valueUri: `${env.AUTH_SERVER_URI}/authorize` // }, // { // url: 'token', // valueUri: `${env.AUTH_SERVER_URI}/token` // } // ], profiles: { patient: { service: './src/services/patient/patient.service.js', versions: [VERSIONS['4_0_0']] }, practitioner: { service: './src/services/practitioner/practitioner.service.js', versions: [VERSIONS['4_0_0']] }, organization: { service: './src/services/organization/organization.service.js', versions: [VERSIONS['4_0_0']] }, documentReference: { service: './src/services/documentreference/documentreference.service.js', versions: [VERSIONS['4_0_0']] }, bundle: { service: './src/services/bundle/bundle.service.js', versions: [VERSIONS['4_0_0']] } } };
42,811
https://github.com/robotomize/gokuu/blob/master/provider/ecb/csv_test.go
Github Open Source
Open Source
Apache-2.0
2,021
gokuu
robotomize
Go
Code
587
2,207
package ecb import ( "errors" "testing" "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" "github.com/robotomize/gokuu/label" ) func TestParseCSV(t *testing.T) { t.Parallel() decodeFn := decodeCSV() if err := decodeFn([]byte("nothing"), nil); err != nil { if !errors.Is(err, errMissingIterFunc) { t.Errorf("iterate throw error: %v", err) } } } func TestMarkDecodeCSV(t *testing.T) { t.Parallel() testCases := []struct { name string err error bytes []byte }{ { name: "test_invalid_markup_0", err: errDecodeToken, bytes: []byte(`Date; CZK, DKK, GBP, 18 June 2021, 1, 7.4364, 0.85785, 19 June 2021, 25.0, 1.23, 2, `), }, { name: "test_invalid_markup_1", err: errDecodeToken, bytes: []byte(`Date, CZK, DKK, GBP,18 June 2021, 0, 7.4364, 0.85785, 19 June 2021, 25.0, 1.23, 2, `), }, { name: "test_invalid_markup_2", err: errDecodeToken, bytes: []byte(`Date, CZK, DKK, GBP, 18 June 2021, 20, 7.4364, 0.85785, 19 June 2021; 25.0, 1.23, 34, `), }, { name: "test_invalid_markup_3", err: errDecodeToken, bytes: []byte(`Date, USD, JPY, 18 June 2021, 1.1898, 131.12, `), }, { name: "test_invalid_header_field_0", err: errAttributeNotValid, bytes: []byte(`, CZK, DKK, GBP, 18 June 2021, 2, 7.4364, 0.85785, 19 June 2021, 25.0, 1.23, 3, `), }, { name: "test_invalid_header_field_1", err: errAttributeNotValid, bytes: []byte(`;, CZK, DKK, GBP, 18 June 2021, 11, 7.4364, 0.85785, 19 June 2021, 25.0, 1.23, 32, `), }, { name: "test_invalid_rate_0", err: errAttributeNotValid, bytes: []byte(`Date, CZK, DKK, GBP, 18 June 2021, 0, 7.4364, 0.85785, 19 June 2021, 25.0, 1.23, 0, `), }, { name: "test_invalid_rate_1", err: errAttributeNotValid, bytes: []byte(`Date, CZK, DKK, GBP, 18 June 2021, -1, 7.4364, 0.85785, 19 June 2021, 25.0, 1.23, -1, `), }, { name: "test_invalid_rate_2", err: errAttributeNotValid, bytes: []byte(`Date, CZK, DKK, GBP, 18 June 2021, dgsd, 7.4364, 0.85785, 19 June 2021, 25.0, 1.23, 11, `), }, { name: "test_invalid_date_0", err: errAttributeNotValid, bytes: []byte(`Date, CZK, DKK, GBP, wrong type, 1, 7.4364, 0.85785, 19 June 2021, 25.0, 1.23, 1, `), }, { name: "test_invalid_extra_symbol", bytes: []byte(`Date, GPK, DKK, GBP, 19 June 2021, 1, 7.4364, 0.85785, 19 June 2021, 25.0, 1.23, 1, `), }, } for _, tc := range testCases { tc := tc t.Run(tc.name, func(t *testing.T) { t.Parallel() decodeFn := decodeCSV() err := decodeFn(tc.bytes, func(rate euroLatestRates) error { return nil }) if !errors.Is(err, tc.err) { diff := cmp.Diff(tc.err, err, cmpopts.EquateErrors()) t.Errorf("mismatch (-want, +got):\n%s", diff) } }) } } func TestDataMatchingDecodeCSV(t *testing.T) { t.Parallel() testCases := []struct { name string data map[string]map[label.Symbol]float64 bytes []byte }{ { name: "test_data_matching_0", data: map[string]map[label.Symbol]float64{ "2021-06-18": { "USD": 1.1898, "JPY": 131.12, "BGN": 1.9558, }, }, bytes: []byte(`Date, USD, JPY, BGN, 18 June 2021, 1.1898, 131.12, 1.9558, `), }, { name: "test_data_matching_1", data: map[string]map[label.Symbol]float64{ "2021-06-18": { "CZK": 25.519, "DKK": 7.4364, "GBP": 0.85785, }, "2021-06-19": { "CZK": 25.0, "DKK": 1.23, "GBP": 0.81, }, }, bytes: []byte(`Date, CZK, DKK, GBP, 18 June 2021, 25.519, 7.4364, 0.85785, 19 June 2021, 25.0, 1.23, 0.81, `), }, { name: "test_data_matching_2", data: map[string]map[label.Symbol]float64{ "2021-06-18": { "USD": 1.1898, "JPY": 131.12, }, }, bytes: []byte("Date, USD, JPY\n 18 June 2021, 1.1898, 131.12"), }, } for _, tc := range testCases { tc := tc t.Run(tc.name, func(t *testing.T) { t.Parallel() decodeFn := decodeCSV() var rates []euroLatestRates if err := decodeFn(tc.bytes, func(rate euroLatestRates) error { rates = append(rates, rate) return nil }); err != nil { t.Fatalf("iterate throw error: %v", err) } if diff := cmp.Diff(len(tc.data), len(rates)); diff != "" { t.Errorf("mismatch (-want, +got):\n%s", diff) } for _, rate := range rates { dateTime := rate.time.Format("2006-01-02") testPairs, ok := tc.data[dateTime] if !ok { t.Errorf("unknown datetime in test dataset") } for _, pair := range rate.rates { rate, ok := testPairs[pair.symbol] if !ok { t.Errorf("unknown currency symbol in test dataset") } if diff := cmp.Diff(rate, pair.rate); diff != "" { t.Errorf("mismatch (-want, +got):\n%s", diff) } } } }) } }
8,293
https://github.com/kyx0r/kiss-find/blob/master/lib/render.js
Github Open Source
Open Source
MIT
null
kiss-find
kyx0r
JavaScript
Code
226
775
async function readFile(filename = '/dev/stdin') { const buffer = new ArrayBuffer(1024) const handle = await tjs.fs.open(filename, 'r') let csv = '' let data = await handle.read(buffer.length) while (data.length) { csv += new TextDecoder().decode(data) data = await handle.read(buffer.length) } return csv } function html(pieces) { let result = pieces[0] const substitutions = [].slice.call(arguments, 1) for (var i = 0; i < substitutions.length; ++i) { result += substitutions[i] + pieces[i + 1] } return result } ;(async () => { const script = new TextDecoder().decode(await tjs.fs.readFile('docs/search.js')) const style = new TextDecoder().decode(await tjs.fs.readFile('docs/style.css')) const body = (await readFile()) .split('\n') .filter((line) => line !== '') .map((entry) => entry.split(',')) .map(([name, version, uri, path, branch, description]) => { const href = (url) => { if (url.includes('sr.ht/')) return [url, 'tree', branch, 'item', path].join('/') if (url.includes('github.com/')) return [url, 'tree', branch, path].join('/') return url } function a(url, name) { const text = name ?? url?.replace('https://', '') return `<a href=${url}>${text}</a>` } const td = (name, content) => `<td class=${name}>${content}</td>` const package = [ `<tr>`, [ ' ' + td('name', a(href(uri ?? ''), name)), td('version', version), td('url', a(uri)), td('description', description), ].join('\n '), `</tr>`, ].join('\n ') return package }) .join('\n ') console.log(html` <head> <script> ${script} </script> <style> ${style} </style> </head> <body> <h1>Kiss find (<a href=https://github.com/jedahan/kiss-find/>source</a>)</h1> <input type=search placeholder=search class=hidden autofocus/> <table id=packages> <thead> <tr> <th>name</th> <th>version</th> <th>url</th> <th>description</th> </tr> </thead> <tbody id=packagesBody> ${body} </tbody> </table> </body> `) })()
17,224
https://github.com/cortside/cortside.core/blob/master/src/ValueTypes/QuantityType.cs
Github Open Source
Open Source
MIT
null
cortside.core
cortside
C#
Code
462
1,372
using System; using System.Runtime.Serialization; using System.Security.Permissions; namespace Cortside.Core.Types { [Serializable] public struct QuantityType : IComparable, IDataType, ISerializable { DecimalType myValue; public static readonly QuantityType DEFAULT = new QuantityType(TypeState.DEFAULT); public static readonly QuantityType UNSET = new QuantityType(TypeState.UNSET); #region State management public bool IsValid { get { return myValue.IsValid; } } public bool IsDefault { get { return myValue.IsDefault; } } public bool IsUnset { get { return myValue.IsUnset; } } #endregion #region Constructors private QuantityType(TypeState state) { if (state == TypeState.DEFAULT) { myValue = DecimalType.DEFAULT; } else if (state == TypeState.UNSET) { myValue = DecimalType.UNSET; } else { myValue = new DecimalType(0); } } public QuantityType(IntegerType value) { myValue = (DecimalType)value; } public QuantityType(Int32 value) { myValue = value; } public QuantityType(Decimal value) { myValue = value; } public QuantityType(Double value) { myValue = value; } #endregion #region Parse and ToString() public static QuantityType Parse(String value) { if (value == null) { return UNSET; } return new QuantityType(Decimal.Parse(value)); } //what should we do for ToString here? public override string ToString() { return myValue.ToString(); } public string Display() { return myValue.ToString(); } #endregion #region Equality operators and methods public static int Compare(QuantityType leftHand, QuantityType rightHand) { return DecimalType.Compare(leftHand.myValue, rightHand.myValue); } public static bool operator ==(QuantityType leftHand, QuantityType rightHand) { return Compare(leftHand, rightHand) == 0; } public static bool operator !=(QuantityType leftHand, QuantityType rightHand) { return Compare(leftHand, rightHand) != 0; } public static bool operator <(QuantityType leftHand, QuantityType rightHand) { return Compare(leftHand, rightHand) < 0; } public static bool operator <=(QuantityType leftHand, QuantityType rightHand) { return Compare(leftHand, rightHand) <= 0; } public static bool operator >(QuantityType leftHand, QuantityType rightHand) { return Compare(leftHand, rightHand) > 0; } public static bool operator >=(QuantityType leftHand, QuantityType rightHand) { return Compare(leftHand, rightHand) >= 0; } #endregion #region Object Support, IComparable and other stuff int IComparable.CompareTo(Object value) { if (!(value is QuantityType)) { throw new InvalidTypeException("QuantityType"); } if (value == null) { throw new InvalidArgumentException("value"); } QuantityType compareTo = (QuantityType)value; return Compare(this, compareTo); } public int CompareTo(QuantityType value) { return Compare(this, value); } public override bool Equals(Object value) { if (value is QuantityType) { return Compare(this, (QuantityType)value) == 0; } return false; } public static bool Equals(QuantityType leftHand, QuantityType rightHand) { return Compare(leftHand, rightHand) == 0; } public override int GetHashCode() { return myValue.GetHashCode(); } public TypeCode GetTypeCode() { return TypeCode.Decimal; } #endregion [SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)] QuantityType(SerializationInfo info, StreamingContext context) { myValue = new DecimalType((Decimal)(info.GetValue("myValue", typeof(Decimal)))); } [SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)] void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { if (this.Equals(DEFAULT)) { info.SetType(typeof(QuantityType_DEFAULT)); } else if (this.Equals(UNSET)) { info.SetType(typeof(QuantityType_UNSET)); } else { info.SetType(typeof(QuantityType)); info.AddValue("myValue", myValue.ToDecimal()); } } } [Serializable] public struct QuantityType_DEFAULT : IObjectReference { public object GetRealObject(StreamingContext context) { return QuantityType.DEFAULT; } } [Serializable] public struct QuantityType_UNSET : IObjectReference { public object GetRealObject(StreamingContext context) { return QuantityType.UNSET; } } }
2,704
https://github.com/shwinshaker/adversarial_robustness_pytorch/blob/master/core/utils/logger.py
Github Open Source
Open Source
MIT
2,022
adversarial_robustness_pytorch
shwinshaker
Python
Code
47
176
import logging class Logger(object): """ Helper class for logging. Arguments: path (str): Path to log file. """ def __init__(self, path): self.logger = logging.getLogger() self.path = path self.setup_file_logger() print ('Logging to file: ', self.path) def setup_file_logger(self): hdlr = logging.FileHandler(self.path, 'w+') self.logger.addHandler(hdlr) self.logger.setLevel(logging.INFO) def log(self, message): print (message) self.logger.info(message)
47,812
https://github.com/olifink/qspread/blob/master/src/spread/german/cfg3.asm
Github Open Source
Open Source
MIT
2,018
qspread
olifink
Assembly
Code
143
886
* Spreadsheet 29/11-91 * - configuration information (english) * include win1_mac_config02 include win1_mac_olicfg include win1_keys_wstatus include win1_keys_k section config xref.l qs_vers * * Qjump's standard config block 02 Tab mkcfhead {QSpread Spezial},qs_vers ;-----------------user function definitions----------------------- mkcfitem 'Taba',string,0,cst_mcn1,,,{Funktion 1 } mkcfitem 'Tabb',string,0,cst_mcn2,,,{Funktion 2 } mkcfitem 'Tabc',string,0,cst_mcn3,,,{Funktion 3 } mkcfitem 'Tabd',string,0,cst_mcn4,,,{Funktion 4 } mkcfitem 'Tabe',string,0,cst_mcn5,,,{Funktion 5 } ;-----------------digit names------------------------------------- mkcfitem 'Tabf',string,0,cst_dig0,,,{Ziffer Ÿ0'} mkcfitem 'Tabg',string,0,cst_dig1,,,{Ziffer Ÿ1'} mkcfitem 'Tabh',string,0,cst_dig2,,,{Ziffer Ÿ2'} mkcfitem 'Tabi',string,0,cst_dig3,,,{Ziffer Ÿ3'} mkcfitem 'Tabj',string,0,cst_dig4,,,{Ziffer Ÿ4'} mkcfitem 'Tabk',string,0,cst_dig5,,,{Ziffer Ÿ5'} mkcfitem 'Tabl',string,0,cst_dig6,,,{Ziffer Ÿ6'} mkcfitem 'Tabm',string,0,cst_dig7,,,{Ziffer Ÿ7'} mkcfitem 'Tabn',string,0,cst_dig8,,,{Ziffer Ÿ8'} mkcfitem 'Tabo',string,0,cst_dig9,,,{Ziffer Ÿ9'} ;-----------------external functions------------------------------ * mkcfitem 'Tabp',string,0,cst_nxfn,,,{Externer Zahlenjob},cfs.file * mkcfitem 'Tabq',string,0,cst_sxfn,,,{Externer Textjob},cfs.file mkcfend * * Configuration data ds.w 0 cfgstrg mcn1,60,{} cfgstrg mcn2,60,{} cfgstrg mcn3,60,{} cfgstrg mcn4,60,{} cfgstrg mcn5,60,{} cfgstrg dig0,20,{Null} cfgstrg dig1,20,{Eins} cfgstrg dig2,20,{Zwei} cfgstrg dig3,20,{Drei} cfgstrg dig4,20,{Vier} cfgstrg dig5,20,{F‡nf} cfgstrg dig6,20,{Sechs} cfgstrg dig7,20,{Sieben} cfgstrg dig8,20,{Acht} cfgstrg dig9,20,{Neun} ; cfgstrg nxfn,36,{ram1_num_obj} ; cfgstrg sxfn,36,{ram1_str_obj} ds.w 0 end
28,233
https://github.com/alex/asciinema/blob/master/asciinema/timer.py
Github Open Source
Open Source
MIT
2,015
asciinema
alex
Python
Code
22
66
import time def timeit(callable, *args): start_time = time.time() ret = callable(*args) end_time = time.time() duration = end_time - start_time return (duration, ret)
13,395
https://github.com/avgust13/Account-Manager/blob/master/src/renderer/components/DropdownMenuButton/DropdownMenuButton.scss
Github Open Source
Open Source
MIT
2,021
Account-Manager
avgust13
SCSS
Code
70
266
$button-height: 24px; .DropdownMenuButton { $self: &; &--active { background: var(--color-gray-100); } &__menu { background: var(--color-white); border-radius: 3px; box-shadow: 0 0 3px rgba(0, 0, 0, 0.3); padding: 6px 0; position: fixed; } &__option { align-items: center; display: flex; height: 30px; padding: 12px; transition: background 0.1s; white-space: nowrap; &:focus { background: var(--color-gray-100); } &:not(&--disabled) { cursor: pointer; &:hover { background: var(--color-gray-100); } } &--disabled { color: var(--color-gray-300); cursor: default; } } }
1,367
https://github.com/mpfeiffermway/relution-plugin/blob/master/relution-publisher/src/main/java/org/jenkinsci/plugins/relution_publisher/net/responses/AssetResponse.java
Github Open Source
Open Source
Apache-2.0
2,013
relution-plugin
mpfeiffermway
Java
Code
11
59
package org.jenkinsci.plugins.relution_publisher.net.responses; import org.jenkinsci.plugins.relution_publisher.entities.Asset; public class AssetResponse extends ApiResponse<Asset> { }
8,137
https://github.com/workze/jallcode/blob/master/local/src/main/java/kafkastaff/KafkaConsumerFactory.java
Github Open Source
Open Source
Apache-2.0
null
jallcode
workze
Java
Code
7
22
package kafkastaff; public class KafkaConsumerFactory { }
24,115
https://github.com/N-I-N-0/NSMBWii-Mod/blob/master/Kamek/src/numpad.cpp
Github Open Source
Open Source
MIT
null
NSMBWii-Mod
N-I-N-0
C++
Code
1,405
6,003
#include <common.h> #include <game.h> #include "sfx.h" #include "numpad.h" CREATE_STATE(dNumpadSpawner_c, Hidden); CREATE_STATE(dNumpadSpawner_c, ShowWait); CREATE_STATE(dNumpadSpawner_c, ButtonActivateWait); CREATE_STATE(dNumpadSpawner_c, Wait); CREATE_STATE(dNumpadSpawner_c, HideWait); dNumpadSpawner_c *dNumpadSpawner_c::instance = 0; dActor_c *dNumpadSpawner_c::build() { void *buffer = AllocFromGameHeap1(sizeof(dNumpadSpawner_c)); dNumpadSpawner_c *c = new(buffer) dNumpadSpawner_c; instance = c; return c; } const char *NumPadFileList[] = {0}; const SpriteData NumPadSpriteData = { ProfileId::NumPad, 8, -8 , 0 , 0, 0x100, 0x100, 0, 0, 0, 0, 0 }; Profile NumPadProfile(&dNumpadSpawner_c::build, SpriteId::NumPad, &NumPadSpriteData, ProfileId::NumPad, ProfileId::NumPad, "NumPad", NumPadFileList); #define ANIM_BUTTON_APPEAR 0 //0, 0, 1, 2, 3, 4, 6, 8 #define ANIM_WINDOW_APPEAR 7 #define ANIM_BUTTON_DESELECT 9 //9, 10, 11, 12, 13, 14, 15, 16 #define ANIM_WINDOW_DISAPPEAR 16 #define ANIM_BUTTON_HIT 18 //19, 20, 21, 22, 23, 24, 25, 26 #define ANIM_BUTTON_SELECTED_IDLE 27 //28, 29, 30, 31, 32, 33, 34, 35 #define ANIM_BG_IN 36 #define ANIM_WINDOW_LOOP 37 #define ANIM_BG_OUT 38 #define ANIM_BUTTON_SELECT 39 //40, 41, 42, 43, 44, 45, 46, 47 int numberToSelect; int num1 = -1; int num2 = -1; int num3 = -1; int finalNumber; /*****************************************************************************/ // Events dNumpadSpawner_c::dNumpadSpawner_c() : state(this, &StateID_ShowWait) { layoutLoaded = false; visible = false; } int dNumpadSpawner_c::onCreate() { if (!layoutLoaded) { OSReport("1\n"); bool gotFile = layout.loadArc("NumPad.arc", false); if (!gotFile) return false; selected = 1; lastTopRowChoice = 1; layout.build("NumPad.brlyt"); OSReport("2\n"); if (IsWideScreen()) { layout.layout.rootPane->scale.x = 1.0f; } else { layout.clippingEnabled = true; layout.clipX = 0; layout.clipY = 52; layout.clipWidth = 640; layout.clipHeight = 352; layout.layout.rootPane->scale.x = 0.731f; layout.layout.rootPane->scale.y = 0.7711f; } OSReport("3\n"); static const char *brlanNames[] = { "NumPad_appearButtons.brlan", "NumPad_appearWindow.brlan", "NumPad_deselectButton.brlan", "NumPad_disappearWindow.brlan", "NumPad_hitButton.brlan", "NumPad_idleSelectedButton.brlan", "NumPad_inBG.brlan", "NumPad_loopWindow.brlan", "NumPad_outBG.brlan", "NumPad_selectButton.brlan", }; OSReport("4\n"); static const char *groupNames[] = { "A00_inWindow", "A00_inWindow", "A00_inWindow", "G_nineButton_00", "G_eightButton_00", "G_sevenButton_00", "G_sixButton_00", "G_fiveButton_00", "G_fourButton_00", "G_threeButton_00", "G_twoButton_00", "G_oneButton_00", "G_nineButton_00", "G_eightButton_00", "G_sevenButton_00", "G_sixButton_00", "G_fiveButton_00", "G_fourButton_00", "G_threeButton_00", "G_twoButton_00", "G_oneButton_00", "G_nineButton_00", "G_eightButton_00", "G_sevenButton_00", "G_sixButton_00", "G_fiveButton_00", "G_fourButton_00", "G_threeButton_00", "G_twoButton_00", "G_oneButton_00", "G_nineButton_00", "G_eightButton_00", "G_sevenButton_00", "G_sixButton_00", "G_fiveButton_00", "G_fourButton_00", "G_threeButton_00", "G_twoButton_00", "G_oneButton_00", "G_nineButton_00", "G_eightButton_00", "G_sevenButton_00", "G_sixButton_00", "G_fiveButton_00", "G_fourButton_00", "G_threeButton_00", "G_twoButton_00", "G_oneButton_00", "C00_BG_00", "C00_BG_00", }; static const int brlanIDs[] = { 1, 3, 7, //A00_inWindow 0, 0, 0, //Numbers 0, 0, 0, 0, 0, 0, 2, 2, 2, //Numbers 2, 2, 2, 2, 2, 2, 4, 4, 4, //Numbers 4, 4, 4, 4, 4, 4, 5, 5, 5, //Numbers 5, 5, 5, 5, 5, 5, 9, 9, 9, //Numbers 9, 9, 9, 9, 9, 9, 8, 8, //C00_BG_00 }; OSReport("5\n"); layout.loadAnimations(brlanNames, 10); OSReport("loadAnimations\n"); layout.loadGroups(groupNames, brlanIDs, 50); OSReport("loadGroups\n"); layout.disableAllAnimations(); OSReport("disableAllAnimations\n"); layout.drawOrder = 140; OSReport("6\n"); static const char *tbNames[] = { "T_numberS_00", "T_number_00", "T_one_00", "T_one_01", "T_two_00", "T_two_01", "T_three_00", "T_three_01", "T_four_00", "T_four_01", "T_five_00", "T_five_01", "T_six_00", "T_six_01", "T_seven_00", "T_seven_01", "T_eight_00", "T_eight_01", "T_nine_00", "T_nine_01", }; layout.getTextBoxes(tbNames, &T_numberS_00, 20); OSReport("7\n"); for (int i = 1; i < 10; i++) { char middle[16]; sprintf(middle, "YesButtonMidd_0%d", i); BtnMid[i - 1] = layout.findPictureByName(middle); char right[16]; sprintf(right, "YesButtonRigh_0%d", i); BtnRight[i - 1] = layout.findPictureByName(right); char left[16]; sprintf(left, "YesButtonLeft_0%d", i); BtnLeft[i - 1] = layout.findPictureByName(left); } OSReport("8\n"); Buttons[0] = layout.findPaneByName("P_oneButton_00"); Buttons[1] = layout.findPaneByName("P_twoButton_00"); Buttons[2] = layout.findPaneByName("P_threeButton_00"); Buttons[3] = layout.findPaneByName("P_fourButton_00"); Buttons[4] = layout.findPaneByName("P_fiveButton_00"); Buttons[5] = layout.findPaneByName("P_sixButton_00"); Buttons[6] = layout.findPaneByName("P_sevenButton_00"); Buttons[7] = layout.findPaneByName("P_eightButton_00"); Buttons[8] = layout.findPaneByName("P_nineButton_00"); OSReport("Found buttons: %p, %p, %p, %p, %p, %p, %p, %p, %p\n", Buttons[0], Buttons[1], Buttons[2], Buttons[3], Buttons[4], Buttons[5], Buttons[6], Buttons[7], Buttons[8]); layoutLoaded = true; } visible = false; return true; } int dNumpadSpawner_c::onExecute() { state.execute(); layout.execAnimations(); layout.update(); return true; } int dNumpadSpawner_c::onDraw() { if (visible) { layout.scheduleForDrawing(); } return true; } int dNumpadSpawner_c::onDelete() { instance = 0; if (StageC4::instance) StageC4::instance->_1D = 0; // disable no-pause return layout.free(); } // Hidden void dNumpadSpawner_c::beginState_Hidden() { } void dNumpadSpawner_c::executeState_Hidden() { } void dNumpadSpawner_c::endState_Hidden() { } // ShowWait void dNumpadSpawner_c::beginState_ShowWait() { OSReport("9\n"); nw4r::snd::SoundHandle handle; PlaySoundWithFunctionB4(SoundRelatedClass, &handle, SE_SYS_KO_DIALOGUE_IN, 1); OSReport("10\n"); layout.disableAllAnimations(); // layout.enableNonLoopAnim(ANIM_WINDOW_APPEAR); OSReport("11\n"); visible = true; scaleEase = 0.0; StageC4::instance->_1D = 1; // enable no-pause } void dNumpadSpawner_c::executeState_ShowWait() { OSReport("12\n"); // if (!layout.isAnimOn(ANIM_WINDOW_APPEAR)) { selected = 1; OSReport("13\n"); // layout.enableNonLoopAnim(ANIM_BUTTON_APPEAR); // layout.enableNonLoopAnim(ANIM_BUTTON_APPEAR+1); // layout.enableNonLoopAnim(ANIM_BUTTON_APPEAR+2); // layout.enableNonLoopAnim(ANIM_BUTTON_APPEAR+3); // layout.enableNonLoopAnim(ANIM_BUTTON_APPEAR+4); // layout.enableNonLoopAnim(ANIM_BUTTON_APPEAR+5); // layout.enableNonLoopAnim(ANIM_BUTTON_APPEAR+6); // layout.enableNonLoopAnim(ANIM_BUTTON_APPEAR+7); // layout.enableNonLoopAnim(ANIM_BUTTON_APPEAR+8); OSReport("14\n"); state.setState(&StateID_ButtonActivateWait); // } } void dNumpadSpawner_c::endState_ShowWait() { OSReport("15\n"); nw4r::snd::SoundHandle handle; // PlaySoundWithFunctionB4(SoundRelatedClass, &handle, SE_OBJ_CLOUD_BLOCK_TO_JUGEM, 1); timer = 1; } // ButtonActivateWait void dNumpadSpawner_c::beginState_ButtonActivateWait() { } void dNumpadSpawner_c::executeState_ButtonActivateWait() { if (!layout.isAnyAnimOn()) state.setState(&StateID_Wait); } void dNumpadSpawner_c::endState_ButtonActivateWait() { } // Wait void dNumpadSpawner_c::beginState_Wait() { } void dNumpadSpawner_c::executeState_Wait() { if (timer < 90) { scaleEase = -((cos(timer * 3.14 /20)-0.9)/timer*10)+1; timer++; return; } int nowPressed = Remocon_GetPressed(GetActiveRemocon()); int newSelection = -1; if (nowPressed & WPAD_ONE) { // Hide the thing state.setState(&StateID_HideWait); } else if (nowPressed & WPAD_UP) { // Move up if (selected == 1) newSelection = 1; else if (selected == 2) newSelection = 2; else if (selected == 3) newSelection = 3; else if (selected == 4) newSelection = 1; else if (selected == 5) newSelection = 2; else if (selected == 6) newSelection = 3; else if (selected == 7) newSelection = 4; else if (selected == 8) newSelection = 5; else if (selected == 9) newSelection = 6; } else if (nowPressed & WPAD_DOWN) { // Move down if (selected == 1) newSelection = 4; else if (selected == 2) newSelection = 5; else if (selected == 3) newSelection = 6; else if (selected == 4) newSelection = 7; else if (selected == 5) newSelection = 8; else if (selected == 6) newSelection = 9; else if (selected == 7) newSelection = 7; else if (selected == 8) newSelection = 8; else if (selected == 9) newSelection = 9; } else if (nowPressed & WPAD_LEFT) { // Move left if (selected == 1) newSelection = 1; else if (selected == 2) newSelection = 1; else if (selected == 3) newSelection = 2; else if (selected == 4) newSelection = 4; else if (selected == 5) newSelection = 4; else if (selected == 6) newSelection = 5; else if (selected == 7) newSelection = 7; else if (selected == 8) newSelection = 7; else if (selected == 9) newSelection = 8; } else if (nowPressed & WPAD_RIGHT) { // Move right if (selected == 1) newSelection = 2; else if (selected == 2) newSelection = 3; else if (selected == 3) newSelection = 3; else if (selected == 4) newSelection = 5; else if (selected == 5) newSelection = 6; else if (selected == 6) newSelection = 6; else if (selected == 7) newSelection = 8; else if (selected == 8) newSelection = 9; else if (selected == 9) newSelection = 9; } else if (nowPressed & WPAD_TWO) { nw4r::snd::SoundHandle handle; PlaySoundWithFunctionB4(SoundRelatedClass, &handle, SE_SYS_DECIDE, 1); selectNumber(selected); int convert[10] = {0, 11, 10, 9, 8, 7, 6, 5, 4, 3}; int animID = convert[selected]; layout.enableNonLoopAnim(ANIM_BUTTON_HIT+animID); } else if (nowPressed & WPAD_PLUS) { doSummon(); } if (newSelection > -1) { OSReport("oldSelection = %d\n", selected); OSReport("newSelection = %d\n", newSelection); nw4r::snd::SoundHandle handle; PlaySoundWithFunctionB4(SoundRelatedClass, &handle, SE_SYS_CURSOR, 1); int newconvert[10] = {0, 8, 7, 6, 5, 4, 3, 2, 1, 0}; int convert[10] = {0, 11, 10, 9, 8, 7, 6, 5, 4, 3}; // int newconvert[10] = {0, 6, 5, 4, 3, 2, 1, 2, 1, 0}; int animID = convert[selected]; int newanimID = newconvert[newSelection]; layout.enableNonLoopAnim(ANIM_BUTTON_DESELECT+animID); layout.enableNonLoopAnim(ANIM_BUTTON_SELECT+newanimID); selected = newSelection; } } void dNumpadSpawner_c::endState_Wait() { } // HideWait void dNumpadSpawner_c::beginState_HideWait() { nw4r::snd::SoundHandle handle; PlaySoundWithFunctionB4(SoundRelatedClass, &handle, SE_SYS_DIALOGUE_OUT_AUTO, 1); layout.enableNonLoopAnim(ANIM_WINDOW_DISAPPEAR); layout.enableNonLoopAnim(ANIM_BUTTON_DESELECT+selected); timer = 26; // PlaySoundWithFunctionB4(SoundRelatedClass, &handle, SE_OBJ_CS_KINOHOUSE_DISAPP, 1); HideSelectCursor(SelectCursorPointer, 0); } void dNumpadSpawner_c::executeState_HideWait() { if (timer > 0) { timer--; scaleEase = -((cos(timer * 3.14 /13.5)-0.9)/timer*10)+1; if (scaleEase < 0.0f) scaleEase = 0.0f; } if (!layout.isAnimOn(ANIM_WINDOW_DISAPPEAR)) this->Delete(1); } void dNumpadSpawner_c::endState_HideWait() { visible = false; } void dNumpadSpawner_c::selectNumber(int num) { OSReport("num is %d\n", num); if(numberToSelect == 0) { num1 = num; char str[3]; sprintf(str, "%03d", num1); wchar_t numToShow[3]; OSReport("yes %s\n", str); numToShow[0] = str[0]; numToShow[1] = str[1]; numToShow[2] = str[2]; OSReport("yes %s\n", numToShow); T_number_00->SetString(numToShow, 0, 3); T_numberS_00->SetString(numToShow, 0, 3); numberToSelect++; return; } if(numberToSelect == 1) { num2 = num; char str[3]; sprintf(str, "%03d", ((num1 * 10) + num2)); wchar_t numToShow[3]; OSReport("yes %s\n", str); numToShow[0] = str[0]; numToShow[1] = str[1]; numToShow[2] = str[2]; OSReport("yes %s\n", numToShow); T_number_00->SetString(numToShow, 0, 3); T_numberS_00->SetString(numToShow, 0, 3); numberToSelect++; return; } if(numberToSelect == 2) { num3 = num; char str[3]; sprintf(str, "%03d", ((num1 * 100) + (num2 * 10) + num3)); wchar_t numToShow[3]; OSReport("yes %s\n", str); numToShow[0] = str[0]; numToShow[1] = str[1]; numToShow[2] = str[2]; OSReport("yes %s\n", numToShow); T_number_00->SetString(numToShow, 0, 3); T_numberS_00->SetString(numToShow, 0, 3); doSummon(); } } void dNumpadSpawner_c::doSummon() { if(num2 == -1) { finalNumber = num1; } else if(num3 == -1) { finalNumber = (num1 * 10) + num2; } else if(num3 > -1) { finalNumber = (num1 * 100) + (num2 * 10) + num3; } OSReport("finalnumber = %d\n", finalNumber); dAcPy_c *player = dAcPy_c::findByID(0); CreateActor(finalNumber, 0, player->pos, 0, 0); num1 = -1; num2 = -1; num3 = -1; numberToSelect = 0; state.setState(&StateID_HideWait); }
701
https://github.com/ruoshuixuelabi/spring-cloud-code/blob/master/ch6-2/ch6-2-provider-service/src/main/java/cn/springcloud/book/controller/TestController.java
Github Open Source
Open Source
Apache-2.0
2,022
spring-cloud-code
ruoshuixuelabi
Java
Code
44
181
package cn.springcloud.book.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class TestController { @RequestMapping(value = "/getUser",method = RequestMethod.GET) public String getUser(@RequestParam("username") String username) throws Exception{ if(username.equals("spring")) { return "This is real user"; }else { throw new Exception(); } } }
23,163
https://github.com/apollographql/apollo-scalajs/blob/master/tests/src/test/scala/com/apollographql/scalajs/ApolloLinkTest.scala
Github Open Source
Open Source
MIT
2,023
apollo-scalajs
apollographql
Scala
Code
66
272
package com.apollographql.scalajs import com.apollographql.scalajs.link.{ApolloLink, GraphQLRequest, HttpLink, HttpLinkOptions} import org.scalatest.{Assertion, AsyncFunSuite} import scala.concurrent.Promise import scala.scalajs.js class ApolloLinkTest extends AsyncFunSuite { js.Dynamic.global.window.fetch = UnfetchFetch implicit override def executionContext = scala.concurrent.ExecutionContext.Implicits.global test("Can perform a query with an HttpLink") { val resultPromise = Promise[Assertion] ApolloLink.execute( new HttpLink(HttpLinkOptions("https://graphql-currency-rates.glitch.me")), GraphQLRequest( gql( """{ | rates(currency: "USD") { | currency | } |}""".stripMargin ) ) ).forEach { res => resultPromise.success(assert(true)) } resultPromise.future } }
28,050
https://github.com/lwyj123/vue-endless/blob/master/src/utils/audio.js
Github Open Source
Open Source
MIT
null
vue-endless
lwyj123
JavaScript
Code
123
437
import store from '../store'; // let dist = { // 'backgroundMusic': require('static/audio/bgm.wav'), // 'fight-attack' : require('static/audio/fight-attack.wav'), // } let dist = {}; let AudioList = []; window.AudioList = AudioList; let GameAudio = function (opt){ this.$AudioList = AudioList; this.src = opt.src || dist[opt.key]; this.id = this.src + Date.now(); this.opt = Object.assign({ autoplay : true, loop : false, },opt); // this.start(); } GameAudio.prototype = { start : function(){ let opt = this.opt; if(this.$el){ this.stop(); } this.$el = document.createElement('audio'); this.$el.src = this.src; this.$el.volume = 0.2; (opt.autoplay) && (this.$el.autoplay = "autoplay"); if(opt.loop){ this.$el.loop = "loop"; }else{ this.$el.addEventListener('ended',() => this.stop(), false); } document.body.appendChild(this.$el); this.$AudioList.push(this.$el); }, pause : function(){ this.$el.pause(); }, stop : function(){ this.$AudioList.splice(this.$AudioList.findIndex(a => a.id = this.id), 1); document.body.removeChild(this.$el); this.$el = null; } } export default GameAudio;
32,622
https://github.com/Ferfortlima/AtlasFMTool/blob/master/controller/js/AdjustCanvas.js
Github Open Source
Open Source
MIT
2,018
AtlasFMTool
Ferfortlima
JavaScript
Code
219
560
function adjustSizes() { var topBarIcons = document.getElementById("topBarIconGroup"); var topBarIconsSmall = document.getElementById("topBarIconGroupSmall"); var canvas = document.getElementById("graphContainer"); var modelName = document.getElementById("modelName"); var height = window.innerHeight; var width = window.innerWidth; canvasWidth = width - 90; canvasHeight = height - 95; canvas.style.width = canvasWidth + "px"; canvas.style.height = canvasHeight + "px"; // center model name input text modelName.style.marginLeft = width / 2 - modelName.clientWidth / 2 + "px"; if (width <= 600) { // topBarIcons.style.display = "block"; topBarIcons.style.display = "none"; topBarIconsSmall.style.display = "block"; } else { topBarIcons.style.display = "block"; topBarIconsSmall.style.display = "none"; } } window.onresize = function() { adjustSizes(); adjustTooltips(); }; adjustTooltips = function() { var tooltips = document.getElementsByClassName("tooltip"); // center tooltip var width = window.innerWidth; var top; var left; // LeftBar Create Association top = 66 + 68 + 34 - tooltips[9].clientHeight / 2; tooltips[9].style.top = top + "px"; // TopBar left = width - (6 * 57 + 57 / 2 + tooltips[0].clientHeight / 2); tooltips[0].style.left = left + "px"; left = width - (5 * 57 + 57 / 2 + tooltips[0].clientHeight / 2); tooltips[1].style.left = left + "px"; left = width - (4 * 57 + 57 / 2 + tooltips[0].clientHeight / 2); tooltips[2].style.left = left + "px"; left = width - (3 * 57 + 57 / 2 + tooltips[0].clientHeight / 2); tooltips[3].style.left = left + "px"; };
30,711
https://github.com/BorjaPintos/fullcalendar/blob/master/packages/__tests__/src/event-drag/validRange.ts
Github Open Source
Open Source
MIT
2,022
fullcalendar
BorjaPintos
TypeScript
Code
175
568
import { DayGridViewWrapper } from '../lib/wrappers/DayGridViewWrapper' describe('validRange event dragging', () => { describe('when start constraint', () => { describe('when in month view', () => { pushOptions({ initialView: 'dayGridMonth', initialDate: '2017-06-01', validRange: { start: '2017-06-06' }, events: [ { start: '2017-06-07', end: '2017-06-10' }, ], editable: true, }) it('won\'t go before validRange', (done) => { let modifiedEvent: any = false let calendar = initCalendar({ eventDrop(arg) { modifiedEvent = arg.event }, }) let dayGridWrapper = new DayGridViewWrapper(calendar).dayGrid $(dayGridWrapper.getEventEls()).simulate('drag', { end: dayGridWrapper.getDayEl('2017-06-06').previousElementSibling, // the invalid day before callback() { expect(modifiedEvent).toBe(false) done() }, }) }) }) }) describe('when end constraint', () => { describe('when in month view', () => { pushOptions({ initialView: 'dayGridMonth', initialDate: '2017-06-01', validRange: { end: '2017-06-09' }, events: [ { start: '2017-06-04', end: '2017-06-07' }, ], editable: true, }) it('won\'t go after validRange', (done) => { let modifiedEvent: any = false let calendar = initCalendar({ eventDrop(arg) { modifiedEvent = arg.event }, }) let dayGridWrapper = new DayGridViewWrapper(calendar).dayGrid $(dayGridWrapper.getEventEls()).simulate('drag', { end: dayGridWrapper.getDayEl('2017-06-08').nextElementSibling, // the invalid day after callback() { expect(modifiedEvent).toBe(false) done() }, }) }) }) }) })
3,544
https://github.com/hudeany/java-utilities-no-dependencies/blob/master/src/de/soderer/utilities/json/schema/validator/ExtendedBaseJsonSchemaValidator.java
Github Open Source
Open Source
MIT
2,016
java-utilities-no-dependencies
hudeany
Java
Code
61
259
package de.soderer.utilities.json.schema.validator; import de.soderer.utilities.json.JsonNode; import de.soderer.utilities.json.JsonObject; import de.soderer.utilities.json.schema.JsonSchemaDefinitionError; import de.soderer.utilities.json.schema.JsonSchemaDependencyResolver; public abstract class ExtendedBaseJsonSchemaValidator extends BaseJsonSchemaValidator { protected JsonObject parentValidatorData; protected ExtendedBaseJsonSchemaValidator(JsonObject parentValidatorData, JsonSchemaDependencyResolver jsonSchemaDependencyResolver, String jsonSchemaPath, Object validatorData, JsonNode jsonNode, String jsonPath) throws JsonSchemaDefinitionError { super(jsonSchemaDependencyResolver, jsonSchemaPath, validatorData, jsonNode, jsonPath); if (parentValidatorData == null) { throw new JsonSchemaDefinitionError("ParentValidatorData is 'null'", jsonSchemaPath); } else { this.parentValidatorData = parentValidatorData; } } }
27,650
https://github.com/msgilligan/jsr354-ri/blob/master/src/test/java/org/javamoney/moneta/function/MonetaryRoundedFactoryBuilderTest.java
Github Open Source
Open Source
Apache-2.0
null
jsr354-ri
msgilligan
Java
Code
252
1,345
package org.javamoney.moneta.function; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import java.math.MathContext; import java.math.RoundingMode; import javax.money.MonetaryOperator; import org.testng.annotations.Test; public class MonetaryRoundedFactoryBuilderTest { @Test(expectedExceptions = NullPointerException.class) public void shouldReturnErrorWhenMonetaryOperatorIsNull() { MonetaryOperator roundingOperator = null; MonetaryRoundedFactory.of(roundingOperator); fail(); } @Test(expectedExceptions = NullPointerException.class) public void shouldReturnErrorWhenMathContextIsNull() { MathContext mathContext = null; MonetaryRoundedFactory.of(mathContext); fail(); } @Test(expectedExceptions = NullPointerException.class) public void shouldReturnErrorWhenRoundingModeIsNull() { RoundingMode roundingMode = null; MonetaryRoundedFactory.withRoundingMode(roundingMode); fail(); } @Test public void shouldReturnTheSameMonetaryOperator() { MonetaryOperator monetaryOperator = m -> m; MonetaryRoundedFactory factory = MonetaryRoundedFactory.of(monetaryOperator); assertNotNull(factory); assertEquals(monetaryOperator, factory.getRoundingOperator()); } @Test public void shouldReturnTheSameMathContextOperator() { MonetaryRoundedFactory factory = MonetaryRoundedFactory.of(MathContext.DECIMAL32); assertNotNull(factory); assertNotNull(factory.getRoundingOperator()); } @Test public void shouldReturnMathContextOperator() { int precision = 6; RoundingMode roundingMode = RoundingMode.HALF_EVEN; MonetaryRoundedFactory factory = MonetaryRoundedFactory .withRoundingMode(roundingMode).withPrecision(precision) .build(); assertNotNull(factory); MonetaryOperator roundingOperator = factory.getRoundingOperator(); assertNotNull(roundingOperator); assertTrue(PrecisionContextRoundedOperator.class.isInstance(roundingOperator)); MathContext result = PrecisionContextRoundedOperator.class.cast(roundingOperator).getMathContext(); assertEquals(precision, result.getPrecision()); assertEquals(roundingMode, result.getRoundingMode()); } @Test public void shouldReturnScaleRoundingOperator() { int scale = 6; RoundingMode roundingMode = RoundingMode.HALF_EVEN; MonetaryRoundedFactory factory = MonetaryRoundedFactory .withRoundingMode(roundingMode).withScale(scale) .build(); assertNotNull(factory); MonetaryOperator roundingOperator = factory.getRoundingOperator(); assertNotNull(roundingOperator); assertTrue(ScaleRoundedOperator.class.isInstance(roundingOperator)); ScaleRoundedOperator result = ScaleRoundedOperator.class.cast(roundingOperator); assertEquals(scale, result.getScale()); assertEquals(roundingMode, result.getRoundingMode()); } @Test public void shouldReturnMathContextScaleOperator() { int precision = 6; int scale = 3; RoundingMode roundingMode = RoundingMode.HALF_EVEN; MonetaryRoundedFactory factory = MonetaryRoundedFactory .withRoundingMode(roundingMode).withPrecision(precision).withScale(scale) .build(); assertNotNull(factory); MonetaryOperator roundingOperator = factory.getRoundingOperator(); assertNotNull(roundingOperator); assertTrue(PrecisionScaleRoundedOperator.class.isInstance(roundingOperator)); PrecisionScaleRoundedOperator result = PrecisionScaleRoundedOperator.class.cast(roundingOperator); assertEquals(precision, result.getMathContext().getPrecision()); assertEquals(scale, result.getScale()); assertEquals(roundingMode, result.getMathContext().getRoundingMode()); } @Test public void shouldReturnScaleMathContextOperator() { int precision = 6; int scale = 3; RoundingMode roundingMode = RoundingMode.HALF_EVEN; MonetaryRoundedFactory factory = MonetaryRoundedFactory .withRoundingMode(roundingMode).withScale(scale).withPrecision(precision) .build(); assertNotNull(factory); MonetaryOperator roundingOperator = factory.getRoundingOperator(); assertNotNull(roundingOperator); assertTrue(PrecisionScaleRoundedOperator.class.isInstance(roundingOperator)); PrecisionScaleRoundedOperator result = PrecisionScaleRoundedOperator.class.cast(roundingOperator); assertEquals(precision, result.getMathContext().getPrecision()); assertEquals(scale, result.getScale()); assertEquals(roundingMode, result.getMathContext().getRoundingMode()); } }
5,693
https://github.com/brgcode/compas_wood/blob/master/src/compas_wood/CGAL/slicer_test.py
Github Open Source
Open Source
MIT
null
compas_wood
brgcode
Python
Code
176
566
import os import numpy as np from compas_view2.app import App from compas_view2.objects import Collection from compas.geometry import Point from compas.geometry import Vector from compas.geometry import Plane from compas.geometry import Polyline from compas.datastructures import Mesh from compas_wood import HERE #? from compas_wood.CGAL import slicer def test_slicer(): print("Start") FILE = os.path.join(HERE, 'data', '3DBenchy.stl')#'../..', # ============================================================================== # Get benchy and construct a mesh # ============================================================================== benchy = Mesh.from_stl(FILE) # ============================================================================== # Create planes # ============================================================================== # replace by planes along a curve bbox = benchy.bounding_box() x, y, z = zip(*bbox) zmin, zmax = min(z), max(z) normal = Vector(0, 0, 1) planes = [] for i in np.linspace(zmin, zmax, 50): plane = Plane(Point(0, 0, i), normal) planes.append(plane) # ============================================================================== # Slice # ============================================================================== M = benchy.to_vertices_and_faces() pointsets = slicer.slice_mesh(M, planes) # ============================================================================== # Process output # ============================================================================== polylines = [] for points in pointsets: points = [Point(*point) for point in points] print(points[0]) polyline = Polyline(points) polylines.append(polyline) print(len(polylines)) print("End") return polylines result = test_slicer() #viewer viewer = App(show_grid=False,width = 3840,height = 2160-250) viewer.add(Collection(result),color = (0, 0, 0.0), linewidth = 1) viewer.run()
50,247
https://github.com/SoftwareDefinedBuildings/mortar-analytics/blob/master/simultaneous_heating_cooling_ahus/app.py
Github Open Source
Open Source
BSD-2-Clause
2,022
mortar-analytics
SoftwareDefinedBuildings
Python
Code
371
1,526
__author__ = "Anand Krishnan Prakash" __email__ = "akprakash@lbl.gov" import pymortar import datetime import pandas as pd import argparse def get_error_message(x): dt_format = "%Y-%m-%d %H:%M:%S" st = x.name st_str = st.strftime(dt_format) site = x.site ahu = x.ahu msg = "At time: {0}, in the site: {1}, the AHU: {2} has both heating and cooling valves open".format( st_str, site, ahu ) return msg def ahu_analysis(client, start_time, end_time): st = start_time.strftime("%Y-%m-%dT%H:%M:%SZ") et = end_time.strftime("%Y-%m-%dT%H:%M:%SZ") query = """SELECT ?cooling_point ?heating_point ?ahu WHERE { ?cooling_point rdf:type/rdfs:subClassOf* brick:Cooling_Valve_Command . ?heating_point rdf:type/rdfs:subClassOf* brick:Heating_Valve_Command . ?ahu bf:hasPoint ?cooling_point . ?ahu bf:hasPoint ?heating_point . };""" resp = client.qualify([query]) if resp.error != "": print("ERROR: ", resp.error) points_view = pymortar.View( sites=resp.sites, name="point_type_data", definition=query, ) point_streams = pymortar.DataFrame( name="points_data", aggregation=pymortar.MAX, window="15m", timeseries=[ pymortar.Timeseries( view="point_type_data", dataVars=["?cooling_point", "?heating_point"] ) ] ) time_params = pymortar.TimeParams( start=st, end=et ) request = pymortar.FetchRequest( sites=resp.sites, views=[points_view], time=time_params, dataFrames=[ point_streams ], ) response = client.fetch(request) ahu_df = response["points_data"] ahus = [ahu[0] for ahu in response.query("select ahu from point_type_data")] error_df_list = [] for ahu in ahus: heat_cool_query = """ SELECT cooling_point_uuid, heating_point_uuid, site FROM point_type_data WHERE ahu = "{0}"; """.format(ahu) res = response.query(heat_cool_query) cooling_uuid = res[0][0] heating_uuid = res[0][1] site = res[0][2] df = response["points_data"][[cooling_uuid, heating_uuid]].dropna() df.columns = ['cooling', 'heating'] df['site'] = site df['ahu'] = ahu.split('#')[1] df['simultaneous_heat_cool'] = False df.loc[((df.cooling > 0) & (df.heating > 0)), 'simultaneous_heat_cool'] = True if not df[df['simultaneous_heat_cool'] == True].empty: error_df_list.append(df[df['simultaneous_heat_cool'] == True]) if len(error_df_list) > 0: error_df = pd.concat(error_df_list, axis=0)[['site', 'ahu']] error_df.index.name = 'time' error_msgs = error_df.apply(lambda x: get_error_message(x), axis=1).values for msg in error_msgs: print(msg) return error_df else: return pd.DataFrame() if __name__ == "__main__": parser = argparse.ArgumentParser(description='configure app parameters') # parser.add_argument("-time_interval", help="length of time interval (in minutes) when you want to check if a zone is both heating and cooling", type=int, default=60, nargs='?') parser.add_argument("-st", help="start time for analysis in yyyy-mm-ddThh:mm:ss format", type=str, default="2017-06-21T00:00:00", nargs='?') parser.add_argument("-et", help="end time for analysis in yyyy-mm-ddThh:mm:ss format", type=str, default="2017-07-01T00:00:00", nargs='?') parser.add_argument("-filename", help="filename to store result of analysis", type=str, default="simultaneous_heat_cool_ahu.csv", nargs='?') # resample_minutes = parser.parse_args().time_interval try: start_time = datetime.datetime.strptime(parser.parse_args().st, "%Y-%m-%dT%H:%M:%S") end_time = datetime.datetime.strptime(parser.parse_args().et, "%Y-%m-%dT%H:%M:%S") except Exception as e: raise Exception("Incorrect format for st or et. Use yyyy-mm-ddThh:mm:ss") filename = parser.parse_args().filename client = pymortar.Client({}) error_df = ahu_analysis(client=client, start_time=start_time, end_time=end_time) if not error_df.empty: print("Writing results to {0}".format(filename)) error_df.to_csv(filename) else: print("No ahus match the condition")
32,618
https://github.com/ozylog/ozylog-validator/blob/master/src/index.js
Github Open Source
Open Source
MIT
2,018
ozylog-validator
ozylog
JavaScript
Code
29
65
// @flow 'use strict'; export {default as validator, addValidator} from './validator'; export {default as sanitizer} from './sanitizer'; export {default as Rules} from './Rules'; export {default as Rule} from './Rule';
29,876
https://github.com/quickbundle/quickbundle-5.0_javasec/blob/master/archetype/quickbundle-securityweb/src/main/java/org/quickbundle/third/quartz/jobexecuting/util/JobExecutingException.java
Github Open Source
Open Source
Apache-2.0
2,018
quickbundle-5.0_javasec
quickbundle
Java
Code
137
597
//代码生成时,文件路径: E:/platform/myProject/svn/oss/quickbundle/trunk/quickbundle-securityweb/src/main/java/org/quickbundle/third/quartz/jobexecuting/util/exception/JobExecutingException.java //代码生成时,系统时间: 2012-04-02 22:28:49 //代码生成时,操作系统用户: qb /* * 系统名称:单表模板 --> quickbundle-securityweb * * 文件名称: org.quickbundle.third.quartz.jobexecuting.util.exception --> JobExecutingException.java * * 功能描述: * * 版本历史: 2012-04-02 22:28:49 创建1.0.0版 (白小勇) * */ package org.quickbundle.third.quartz.jobexecuting.util; import org.quickbundle.base.exception.RmRuntimeException; /** * 功能、用途、现存BUG: * * @author 白小勇 * @version 1.0.0 * @see 需要参见的其它类 * @since 1.0.0 */ public class JobExecutingException extends RmRuntimeException { /** * 构造函数 */ public JobExecutingException() { super(); } /** * 构造函数: * @param msg */ public JobExecutingException(String msg) { super(msg); } /** * 构造函数: * @param t */ public JobExecutingException(Throwable t) { super(t); } /** * 构造函数: * @param msg * @param t */ public JobExecutingException(String msg, Throwable t) { super(msg, t); } /** * 构造函数: * @param msg * @param t * @param returnObj */ public JobExecutingException(String msg, Throwable t, Object returnObj) { super(msg, t, returnObj); } }
1,380
https://github.com/mhnam/first-steps-with-tensorflow/blob/master/rnn_ptb/simple-examples/rnnlm-0.2b/convert.c
Github Open Source
Open Source
MIT
2,021
first-steps-with-tensorflow
mhnam
C
Code
96
380
// this simple program converts srilm output obtained in -debug 2 test mode to raw per-word probabilities #include <stdio.h> void goToDelimiter(int delim, FILE *fi) { int ch=0; while (ch!=delim) { ch=fgetc(fi); if (feof(fi)) { exit(1); } } } int main() { int str[1000]; float prob_other; goToDelimiter('\n', stdin); while (1) { fscanf(stdin, "%s", str); fscanf(stdin, "%s", str); fscanf(stdin, "%s", str); fscanf(stdin, "%s", str); fscanf(stdin, "%s", str); fscanf(stdin, "%s", str); if (strcmp(str, (char *)"=")) { goToDelimiter('\n', stdin); goToDelimiter('\n', stdin); goToDelimiter('\n', stdin); goToDelimiter('\n', stdin); } goToDelimiter(']', stdin); goToDelimiter(' ', stdin); fscanf(stdin, "%f", &prob_other); printf("%E\n", prob_other); goToDelimiter('\n', stdin); } }
33,980
https://github.com/biscout24/toguru-scala-client/blob/master/core/src/main/scala/toguru/implicits/Toggle.scala
Github Open Source
Open Source
MIT
null
toguru-scala-client
biscout24
Scala
Code
33
144
package toguru.implicits import toguru.api.Toggling import toguru.impl.{ToggleState, TogglesString} object toggle { implicit class TogglesToString(toggles: Iterable[ToggleState]) { def buildString(implicit toggling: Toggling): String = TogglesString.build { import toggling.client toggles.map(t => t.id -> client.forcedToggle(t.id).getOrElse(t.condition.applies(client))) } } }
1,722
https://github.com/tyrion70/polygon-adapter/blob/master/index.js
Github Open Source
Open Source
MIT
null
polygon-adapter
tyrion70
JavaScript
Code
262
760
const rp = require('request-promise') const retries = process.env.RETRIES || 3 const delay = process.env.RETRY_DELAY || 1000 const timeout = process.env.TIMEOUT || 1000 const requestRetry = (options, retries) => { return new Promise((resolve, reject) => { const retry = (options, n) => { return rp(options) .then(response => { if (response.body.error) { if (n === 1) { reject(response) } else { setTimeout(() => { retries-- retry(options, retries) }, delay) } } else { return resolve(response) } }) .catch(error => { if (n === 1) { reject(error) } else { setTimeout(() => { retries-- retry(options, retries) }, delay) } }) } return retry(options, retries) }) } const createRequest = (input, callback) => { let url = 'https://api.polygon.io/v1/' const endpoint = input.data.endpoint || 'conversion' const from = input.data.from || 'EUR' const to = input.data.to || 'USD' url = url + endpoint + '/' + from + '/' + to const queryObj = { amount: '1', apikey: process.env.API_KEY } const options = { url: url, qs: queryObj, json: true, timeout, resolveWithFullResponse: true } requestRetry(options, retries) .then(response => { const result = response.body.converted response.body.result = result callback(response.statusCode, { jobRunID: input.id, data: response.body, result, statusCode: response.statusCode }) }) .catch(error => { callback(error.statusCode, { jobRunID: input.id, status: 'errored', error, statusCode: error.statusCode }) }) } exports.gcpservice = (req, res) => { createRequest(req.body, (statusCode, data) => { res.status(statusCode).send(data) }) } exports.handler = (event, context, callback) => { createRequest(event, (statusCode, data) => { callback(null, data) }) } exports.handlerv2 = (event, context, callback) => { createRequest(JSON.parse(event.body), (statusCode, data) => { callback(null, { statusCode: statusCode, body: JSON.stringify(data), isBase64Encoded: false }) }) } module.exports.createRequest = createRequest
44,450
https://github.com/JLimperg/lean4/blob/master/tests/playground/map_perf.lean
Github Open Source
Open Source
Apache-2.0
2,022
lean4
JLimperg
Lean
Code
199
368
abbrev Map1 : Type := RBMap Nat Bool (λ a b, a < b) abbrev Map2 : Type := HashMap Nat Bool def mkMap1Aux : Nat → Map1 → Map1 | 0 m := m | (n+1) m := mkMap1Aux n (m.insert n (n % 10 = 0)) def mkMap2Aux : Nat → Map2 → Map2 | 0 m := m | (n+1) m := mkMap2Aux n (m.insert n (n % 10 = 0)) def mkMap1 (n : Nat) := mkMap1Aux n {} def mkMap2 (n : Nat) := mkMap2Aux n {} def tst1 (n : Nat) : IO Unit := do let m := mkMap1 n, let v := m.fold (λ (r : Nat) (k : Nat) (v : Bool), if v then r + 1 else r) 0, IO.println ("Result " ++ toString v) def tst2 (n : Nat) : IO Unit := do let m := mkMap2 n, let v := m.fold (λ (r : Nat) (k : Nat) (v : Bool), if v then r + 1 else r) 0, IO.println ("Result " ++ toString v) def main (xs : List String) : IO Unit := timeit "tst1" (tst1 xs.head.toNat) *> timeit "tst2" (tst2 xs.head.toNat)
20,948
https://github.com/webclinic017/VectorBTanalysis/blob/master/.venv/share/jupyter/lab/staging/node_modules/@krassowski/jupyterlab-lsp/lib/overrides/defaults.d.ts
Github Open Source
Open Source
MIT, BSD-3-Clause
2,020
VectorBTanalysis
webclinic017
TypeScript
Code
11
31
import { ICodeOverridesRegistry } from './tokens'; export declare const language_specific_overrides: ICodeOverridesRegistry;
12,271
https://github.com/youyo/zabbix-aws-integration/blob/master/cmd/zabbix-aws-integration/cmd/ec2Discovery.go
Github Open Source
Open Source
MIT
2,018
zabbix-aws-integration
youyo
Go
Code
296
1,273
package cmd import ( "context" "fmt" "log" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" "github.com/spf13/cobra" ) type ( Ec2DiscoveryItem struct { InstanceID string `json:"{#INSTANCE_ID}"` InstanceName string `json:"{#INSTANCE_NAME}"` InstanceRole string `json:"{#INSTANCE_ROLE}"` InstancePublicIp string `json:"{#INSTANCE_PUBLIC_IP}"` InstancePrivateIp string `json:"{#INSTANCE_PRIVATE_IP}"` ZabbixHostGroup string `json:"{#ZABBIX_HOST_GROUP}"` } Ec2DiscoveryItems []Ec2DiscoveryItem Ec2DiscoveryData struct { Data Ec2DiscoveryItems `json:"data"` } ) func fetchRunningInstances(ec2Service *ec2.EC2) (resp *ec2.DescribeInstancesOutput, err error) { params := &ec2.DescribeInstancesInput{ Filters: []*ec2.Filter{ { Name: aws.String("instance-state-name"), Values: []*string{aws.String("running")}, }, }, } ctx, cancelFn := context.WithTimeout( context.Background(), RequestTimeout, ) defer cancelFn() resp, err = ec2Service.DescribeInstancesWithContext(ctx, params) return } func fetchInstanceName(ec2Instance *ec2.Instance) (instnaceName string) { for _, tag := range ec2Instance.Tags { if *tag.Key == "Name" { instnaceName = *tag.Value } } return } func fetchInstanceRole(ec2Instance *ec2.Instance) (instnaceRole string) { for _, tag := range ec2Instance.Tags { if *tag.Key == "Role" { instnaceRole = *tag.Value } } return } func buildEc2DiscoveryData(resp *ec2.DescribeInstancesOutput) (ec2DiscoveryData Ec2DiscoveryData, err error) { var ec2DiscoveryItems Ec2DiscoveryItems for _, v := range resp.Reservations { for _, i := range v.Instances { instanceName := fetchInstanceName(i) instanceRole := fetchInstanceRole(i) ec2DiscoveryItems = append(ec2DiscoveryItems, Ec2DiscoveryItem{ InstanceID: *i.InstanceId, InstanceName: instanceName, InstanceRole: instanceRole, InstancePublicIp: *i.PublicIpAddress, InstancePrivateIp: *i.PrivateIpAddress, ZabbixHostGroup: zabbixAwsIntegration.Ec2.Discovery.ZabbixHostGroup, }) } } ec2DiscoveryData = Ec2DiscoveryData{ec2DiscoveryItems} return } func ec2Discovery(arn, accessKey, secretAccessKey, region string) (ec2DiscoveryData Ec2DiscoveryData, err error) { sess, creds, err := NewCredentials( arn, accessKey, secretAccessKey, ) if err != nil { return } config := NewConfig(creds, region) ec2Service := NewEc2Service(sess, config) resp, err := fetchRunningInstances(ec2Service) if err != nil { return } ec2DiscoveryData, err = buildEc2DiscoveryData(resp) return } var ec2DiscoveryCmd = &cobra.Command{ Use: "discovery", //Short: "", //Long: ``, Run: func(cmd *cobra.Command, args []string) { d, err := ec2Discovery( zabbixAwsIntegration.Arn, zabbixAwsIntegration.AccessKey, zabbixAwsIntegration.SecretAccessKey, zabbixAwsIntegration.Region, ) if err != nil { log.Fatal(err) } s, err := Jsonize(d) if err != nil { log.Fatal(err) } fmt.Println(s) }, } func init() { ec2Cmd.AddCommand(ec2DiscoveryCmd) ec2DiscoveryCmd.PersistentFlags().StringVarP(&zabbixAwsIntegration.Ec2.Discovery.ZabbixHostGroup, "zabbix-host-group", "", "aws_integrations", "Zabbix HostGroup") }
7,811
https://github.com/tanyaweaver/Prtfolio/blob/master/scripts/controllers/resumeController.js
Github Open Source
Open Source
MIT
null
Prtfolio
tanyaweaver
JavaScript
Code
23
84
(function(module) { var resumeController = {}; resumeController.index = function() { if($('#resume section').length === 0) { ResumeSection.fetchAll(); } $('#resume').show().siblings().hide(); }; module.resumeController = resumeController; })(window);
22,062
https://github.com/pvmoore/ppl2/blob/master/src/ppl2/check/check_module.d
Github Open Source
Open Source
MIT
2,019
ppl2
pvmoore
D
Code
1,652
5,314
module ppl2.check.check_module; import ppl2.internal; /// /// Check semantics after all types have been resolved. /// final class ModuleChecker { private: Module module_; StopWatch watch; Set!string stringSet; IdentifierResolver identifierResolver; EscapeAnalysis escapeAnalysis; public: this(Module module_) { this.module_ = module_; this.stringSet = new Set!string; this.identifierResolver = new IdentifierResolver(module_); this.escapeAnalysis = new EscapeAnalysis(module_); } void clearState() { watch.reset(); } ulong getElapsedNanos() { return watch.peek().total!"nsecs"; } void check() { watch.start(); recursiveVisit(module_); checkAttributes(); watch.stop(); } //========================================================================== void visit(AddressOf n) { } void visit(Alias n) { } void visit(Array n) { if(!n.countExpr().isA!LiteralNumber) { module_.addError(n.countExpr(), "Array count expression must be a const", true); } } void visit(As n) { Type fromType = n.leftType; Type toType = n.rightType; if(fromType.isPtr && toType.isPtr) { /// ok - bitcast pointers } else if(fromType.isPtr && !toType.isInteger) { errorBadExplicitCast(module_, n, fromType, toType); } else if(!fromType.isInteger && toType.isPtr) { errorBadExplicitCast(module_, n, fromType, toType); } } void visit(Binary n) { assert(n.numChildren==2, "Binary numChildren=%s. Expecting 2".format(n.numChildren)); if(n.left.isTypeExpr) { module_.addError(n.left, "Expecting an expression here not a type", true); } if(n.right.isTypeExpr) { module_.addError(n.right, "Expecting an expression here not a type", true); } /// Check the types if(n.isPtrArithmetic) { } else { if(!areCompatible(n.rightType, n.leftType)) { module_.addError(n, "Types are incompatible: %s and %s".format(n.leftType, n.rightType), true); } } if(n.op.isAssign) { if(n.op!=Operator.ASSIGN && n.leftType.isPtr && n.rightType.isInteger) { /// int* a = 10 /// a += 10 } else if(!n.rightType.canImplicitlyCastTo(n.leftType)) { errorBadImplicitCast(module_, n, n.rightType, n.leftType); } /// Check whether we are modifying a const variable if(!n.parent.isInitialiser) { auto id = n.left().as!Identifier; if(id && id.target.isVariable && id.target.getVariable.isConst) { module_.addError(n, "Cannot modify const %s".format(id.name), true); } } } else { } } void visit(Break n) { } void visit(Call n) { auto paramTypes = n.target.paramTypes(); auto argTypes = n.argTypes(); /// Ensure we have the correct number of arguments if(paramTypes.length != argTypes.length) { module_.addError(n, "Expecting %s arguments, not %s".format(paramTypes.length, argTypes.length), true); } /// Ensure the arguments can implicitly cast to the parameters foreach(i, p; n.target.paramTypes()) { if(!argTypes[i].canImplicitlyCastTo(p)) { errorBadImplicitCast(module_, n.arg(i.to!int), argTypes[i], p); } } } void visit(Case n) { } void visit(Closure n) { } void visit(Composite n) { } void visit(Constructor n) { } void visit(Continue n) { } void visit(Dot n) { } void visit(Enum n) { } void visit(EnumMember n) { /// Must be convertable to element type // todo - should have been removed } void visit(EnumMemberValue n) { } void visit(ExpressionRef n) { } void visit(Function n) { auto retType = n.getType.getFunctionType.returnType; switch(n.name) { case "operator==": case "operator<>": case "operator<": case "operator>": case "operator<=": case "operator>=": if(retType.isPtr || !retType.isBool) { module_.addError(n, "%s must return bool".format(n.name), true); } break; case "operator[]": if(n.params.numParams==2) { /// get if(retType.isValue && retType.isVoid) { module_.addError(n, "operator:(this,int) must not return void", true); } } else if(n.params.numParams==3) { /// set } break; case "__user_main": if(retType.isVoid && retType.isValue) break; // void ok if(retType.category()==Type.INT && retType.isValue) break; // int ok module_.addError(n, "main/WinMain can only return int or void", true); break; default: break; } } void visit(FunctionType n) { } void visit(Identifier n) { void checkReadOnlyAssignment(Access access, string moduleName) { // // allow writing to indexed pointer value // auto idx = findAncestor!Index; // if(idx) return; // if(access.isReadOnly && moduleName!=module_.canonicalName) { auto a = n.getAncestor!Binary; if(a && a.op.isAssign && n.isDescendentOf(a.left)) { module_.addError(n, "Property is readonly", true); } } } void checkPrivateAccess(Access access, string moduleName) { if(access.isPrivate && moduleName!=module_.canonicalName) { module_.addError(n, "Property is private", true); } } if(n.target.isMemberVariable) { auto var = n.target.getVariable; checkPrivateAccess(var.access, var.getModule.canonicalName); checkReadOnlyAssignment(var.access, var.getModule.canonicalName); /// Check for static access to non-static variable if(!var.isStatic) { /// if(n.parent.isDot) { auto s = n.previous(); // todo } else { auto con = n.getContainer; if(con.isFunction) { if(con.as!LiteralFunction.getFunction.isStatic) { module_.addError(n, "Static access to non-static variable", true); } } else assert(false, "todo"); } } } if(n.target.isMemberFunction) { auto func = n.target.getFunction; checkPrivateAccess(func.access, func.moduleName); checkReadOnlyAssignment(func.access, func.moduleName); } } void visit(If n) { if(n.isExpr) { /// Type must not be void if(n.type.isVoid && n.type.isValue) { module_.addError(n, "If must not have void result", true); } /// Both then and else are required if(!n.hasThen || !n.hasElse) { module_.addError(n, "If must have both a then and an else result", true); } /// Don't allow any returns in then or else block auto array = new DynamicArray!Return; n.selectDescendents!Return(array); if(array.length>0) { module_.addError(array[0], "An if used as a result cannot return", true); } } } void visit(Import n) { } void visit(Index n) { auto lit = n.index().as!LiteralNumber; if(lit) { /// Index is a const. Check the bounds if(n.isArrayIndex) { Array array = n.exprType().getArrayType; assert(array); auto count = array.countExpr().as!LiteralNumber; assert(count); if(lit.value.getInt() >= count.value.getInt()) { module_.addError(n, "Array bounds error. %s >= %s".format(lit.value.getInt(), count.value.getInt()), true); } } else if(n.isTupleIndex) { Tuple tuple = n.exprType().getTuple; assert(tuple); auto count = tuple.numMemberVariables(); assert(count); if(lit.value.getInt() >= count) { module_.addError(n, "Array bounds error. %s >= %s".format(lit.value.getInt(), count), true); } } else { /// ptr } } else { if(n.isTupleIndex) { module_.addError(n, "Tuple index must be a const number", true); } /// We could add a runtime check here in debug mode } if(n.exprType.isKnown) { } } void visit(Initialiser n) { } void visit(Is n) { } void visit(LiteralArray n) { /// Check for too many values if(n.length() > n.type.countAsInt()) { module_.addError(n, "Too many values specified (%s > %s)".format(n.length(), n.type.countAsInt()), true); } foreach(i, left; n.elementTypes()) { if(!left.canImplicitlyCastTo(n.type.subtype)) { errorBadImplicitCast(module_, n.elementValues()[i], left, n.type.subtype); } } } void visit(LiteralFunction n) { assert(n.first().isA!Parameters); /// Check for duplicate Variable names Variable[string] map; n.recurse!Variable((v) { if(v.name) { auto ptr = v.name in map; if(ptr) { auto v2 = *ptr; bool sameScope = v.parent is v2.parent; if(sameScope) { module_.addError(v, "Variable '%s' is declared more than once in this scope (Previous declaration is on line %s)" .format(v.name, v2.line+1), true); } else if(v.isLocalAlloc) { /// Check for shadowing auto res = identifierResolver.find(v.name, v.previous()); if(res.found) { module_.addError(v, "Variable '%s' is shadowing another variable declared on line %s".format(v.name, res.line+1), true); } } } map[v.name] = v; } }); escapeAnalysis.analyse(n); } void visit(LiteralMap n) { } void visit(LiteralNull n) { } void visit(LiteralNumber n) { Type* ptr; switch(n.parent.id()) with(NodeID) { case VARIABLE: ptr = &n.parent.as!Variable.type; break; default: break; } if(ptr) { auto parentType = *ptr; if(!n.type.canImplicitlyCastTo(parentType)) { errorBadImplicitCast(module_, n, n.type, parentType); } } } void visit(LiteralString n) { } void visit(LiteralTuple n) { Tuple tuple = n.type.getTuple; assert(tuple); auto structTypes = tuple.memberVariableTypes(); /// Check for too many values if(n.numElements > tuple.numMemberVariables) { module_.addError(n, "Too many values specified", true); } if(n.numElements==0) { } if(n.names.length > 0) { /// This uses name=value to initialise elements /// Check that the names are valid and are not repeated stringSet.clear(); foreach(i, name; n.names) { if(stringSet.contains(name)) { module_.addError(n.children[i], "Tuple member %s initialised more than once".format(name), true); } stringSet.add(name); auto v = tuple.getMemberVariable(name); if(!v) { module_.addError(n.children[i], "Tuple does not have member %s".format(name), true); } } auto elementTypes = n.elementTypes(); foreach(i, name; n.names) { auto var = tuple.getMemberVariable(name); auto left = elementTypes[i]; auto right = var.type; if(!left.canImplicitlyCastTo(right)) { errorBadImplicitCast(module_, n.elements()[i], left, right); } } } else { /// This is a list of elements /// Check that the element types match the struct members foreach(i, t; n.elementTypes()) { auto left = t; auto right = structTypes[i]; if(!left.canImplicitlyCastTo(right)) { errorBadImplicitCast(module_, n.elements()[i], left, right); } } } } void visit(Loop n ) { } void visit(Module n) { /// Ensure all global variables have a unique name stringSet.clear(); foreach(v; module_.getVariables()) { if(stringSet.contains(v.name)) { module_.addError(v, "Global variable %s declared more than once".format(v.name), true); } stringSet.add(v.name); } } void visit(ModuleAlias n) { } void visit(Parameters n) { /// Check that all arg names are unique stringSet.clear(); foreach(i, a; n.paramNames) { if(stringSet.contains(a)) { module_.addError(n.getParam(i), "Duplicate parameter name", true); } stringSet.add(a); } } void visit(Parenthesis n) { } void visit(Return n) { } void visit(Select n) { assert(n.isSwitch); /// Check that each clause can be converted to the type of the switch value auto valueType = n.valueType(); foreach(c; n.cases()) { foreach(expr; c.conds()) { if(!expr.getType.canImplicitlyCastTo(valueType)) { errorBadImplicitCast(module_, expr, expr.getType, valueType); } } } /// Check that all clauses are const integers foreach(c; n.cases()) { foreach(expr; c.conds()) { auto lit = expr.as!LiteralNumber; if(!lit || (!lit.getType.isInteger && !lit.getType.isBool)) { module_.addError(expr, "Switch-style Select clauses must be of const integer type", true); } } } } void visit(Struct n) { stringSet.clear(); foreach(v; n.getMemberVariables()) { /// Variables must have a name if(v.name.length==0) { module_.addError(v, "Struct variable must have a name", true); } else { /// Names must be unique if(stringSet.contains(v.name)) { module_.addError(v, "Struct %s has duplicate member %s".format(n.name, v.name), true); } stringSet.add(v.name); } } } void visit(Tuple n) { stringSet.clear(); foreach(v; n.getMemberVariables()) { /// Names must be unique if(v.name) { if(stringSet.contains(v.name)) { module_.addError(v, "Tuple has duplicate member %s".format(v.name), true); } stringSet.add(v.name); } } } void visit(TypeExpr n) { } void visit(Unary n) { } void visit(ValueOf n) { } void visit(Variable n) { if(n.isConst) { if(!n.isGlobal && !n.isStructMember) { /// Initialiser must be const auto ini = n.initialiser(); if(!ini.isConst) { module_.addError(n, "Const initialiser must be const", true); } } } if(n.isStructMember) { auto s = n.getStruct; if(s.isPOD && !n.access.isPublic) { module_.addError(n, "POD struct member variables must be public", true); } } if(n.isStatic) { if(!n.parent.id==NodeID.STRUCT) { module_.addError(n, "Static variables are only allowed in a struct", true); } } if(n.type.isStruct) { } if(n.type.isTuple) { auto tuple = n.type.getTuple(); /// Tuples must only contain variable declarations foreach(v; tuple.children) { if(!v.isVariable) { module_.addError(n, "A tuple must only contain variable declarations", true); } else { auto var = cast(Variable)v; if(var.hasInitialiser) { module_.addError(n, "A tuple must not have variable initialisation", true); } } } } if(n.isParameter) { } if(n.isLocalAlloc) { } } //========================================================================== private: void recursiveVisit(ASTNode m) { //dd("check", typeid(m)); m.visit!ModuleChecker(this); foreach(n; m.children) { recursiveVisit(n); } } void checkAttributes() { void check(ASTNode node, Attribute a) { bool ok = true; final switch(a.type) with(Attribute.Type) { case EXPECT: ok = node.isIf; break; case INLINE: ok = node.isFunction; break; case LAZY: ok = node.isFunction; break; case MEMOIZE: ok = node.isFunction; break; case MODULE: ok = node.isModule; break; case NOTNULL: break; case PACK: ok = node.id==NodeID.STRUCT; break; case POD: ok = node.id==NodeID.STRUCT; break; case PROFILE: ok = node.isFunction; break; case RANGE: ok = node.isVariable; break; } if(!ok) { module_.addError(node, "%s attribute cannot be applied to %s". format(a.name, node.id.to!string.toLower), true); } } module_.recurse!ASTNode((n) { auto attribs = n.attributes; foreach(a; attribs) { check(n, a); } }); } }
23,085
https://github.com/yulqen/twdft/blob/master/twdft.fish
Github Open Source
Open Source
MIT
2,019
twdft
yulqen
Fish
Code
63
151
#complete -c twdft -l create_inspection -d "Port Facility Name" -a "(twdft complete_site (commandline -cp))" #complete -f -c twdft -d "Create inspection" -a "(twdft complete_site)" complete -f -c twdft -d "Port Facility" -a "(twdft_complete_site)" complete -f -c twdft -l inspectiondate -d "Inspection date" complete -f -c twdft -l inspectiontime -d "Inspection time" complete -f -c twdft -l opencard -d "Open inspection card in vim"
41,831
https://github.com/SakurajimaMaii/Utils/blob/master/libraries/VastSwipeView/src/main/java/com/gcode/vastswipeview/exception/VastSwipeViewNotInit.kt
Github Open Source
Open Source
MIT
null
Utils
SakurajimaMaii
Kotlin
Code
36
94
package com.gcode.vastswipeview.exception /** * @OriginalAuthor: Vast Gui * @OriginalDate: * @EditAuthor: Vast Gui * @EditDate: 2021/12/17 */ internal data class VastSwipeViewNotInit( override val message: String, override val cause: Throwable? = null ) : Throwable(message, cause) {}
31,441
https://github.com/tryboy/polarphp/blob/master/unittests/utils/StringPoolTest.cpp
Github Open Source
Open Source
PHP-3.01
null
polarphp
tryboy
C++
Code
121
314
// This source file is part of the polarphp.org open source project // // Copyright (c) 2017 - 2019 polarphp software foundation // Copyright (c) 2017 - 2019 zzu_softboy <zzu_softboy@163.com> // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://polarphp.org/LICENSE.txt for license information // See https://polarphp.org/CONTRIBUTORS.txt for the list of polarphp project authors // // Created by polarboy on 2018/07/15. #include "polarphp/utils/StringPool.h" #include "gtest/gtest.h" using namespace polar; using namespace polar::basic; using namespace polar::utils; namespace { TEST(PooledStringPtrTest, testOperatorEquals) { StringPool pool; const PooledStringPtr a = pool.intern("a"); const PooledStringPtr b = pool.intern("b"); EXPECT_FALSE(a == b); } TEST(PooledStringPtrTest, testOperatorNotEquals) { StringPool pool; const PooledStringPtr a = pool.intern("a"); const PooledStringPtr b = pool.intern("b"); EXPECT_TRUE(a != b); } } // anonymous namespace
47,178
https://github.com/YiduoQiu/Jeesite-demo/blob/master/src/main/java/com/thinkgem/jeesite/modules/aqtrzj/service/CzzAqtrzjService.java
Github Open Source
Open Source
Apache-2.0
null
Jeesite-demo
YiduoQiu
Java
Code
131
973
package com.thinkgem.jeesite.modules.aqtrzj.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.thinkgem.jeesite.common.persistence.Page; import com.thinkgem.jeesite.common.service.CrudService; import com.thinkgem.jeesite.common.utils.StringUtils; import com.thinkgem.jeesite.modules.aqtrzj.entity.CzzAqtrzj; import com.thinkgem.jeesite.modules.aqtrzj.dao.CzzAqtrzjDao; import com.thinkgem.jeesite.modules.aqtrzj.entity.CzzAqtrzjDt1; import com.thinkgem.jeesite.modules.aqtrzj.dao.CzzAqtrzjDt1Dao; /** * 安全投入资金计划Service * @author qyd * @version 2018-08-27 */ @Service @Transactional(readOnly = true) public class CzzAqtrzjService extends CrudService<CzzAqtrzjDao, CzzAqtrzj> { @Autowired private CzzAqtrzjDt1Dao czzAqtrzjDt1Dao; public CzzAqtrzj get(String id) { CzzAqtrzj czzAqtrzj = super.get(id); czzAqtrzj.setCzzAqtrzjDt1List(czzAqtrzjDt1Dao.findList(new CzzAqtrzjDt1(czzAqtrzj))); return czzAqtrzj; } public List<CzzAqtrzj> findList(CzzAqtrzj czzAqtrzj) { return super.findList(czzAqtrzj); } public Page<CzzAqtrzj> findPage(Page<CzzAqtrzj> page, CzzAqtrzj czzAqtrzj) { return super.findPage(page, czzAqtrzj); } @Transactional(readOnly = false) public void save(CzzAqtrzj czzAqtrzj) { super.save(czzAqtrzj); for (CzzAqtrzjDt1 czzAqtrzjDt1 : czzAqtrzj.getCzzAqtrzjDt1List()){ if (czzAqtrzjDt1.getId() == null){ continue; } if (CzzAqtrzjDt1.DEL_FLAG_NORMAL.equals(czzAqtrzjDt1.getDelFlag())){ if (StringUtils.isBlank(czzAqtrzjDt1.getId())){ czzAqtrzjDt1.setTestDataMain(czzAqtrzj); czzAqtrzjDt1.preInsert(); czzAqtrzjDt1Dao.insert(czzAqtrzjDt1); }else{ czzAqtrzjDt1.preUpdate(); czzAqtrzjDt1Dao.update(czzAqtrzjDt1); } }else{ czzAqtrzjDt1Dao.delete(czzAqtrzjDt1); } } } @Transactional(readOnly = false) public void delete(CzzAqtrzj czzAqtrzj) { super.delete(czzAqtrzj); czzAqtrzjDt1Dao.delete(new CzzAqtrzjDt1(czzAqtrzj)); } }
46,569
https://github.com/javra/lean/blob/master/tests/lean/prodtst.lean
Github Open Source
Open Source
Apache-2.0
2,022
lean
javra
Lean
Code
22
44
-- inductive prod2 (A B : Type₊) := mk : A → B → prod2 A B set_option pp.universes true check @prod2
5,596
https://github.com/dream-png/HotelSystem/blob/master/src/com/hyc/www/test/TestHotelDao.java
Github Open Source
Open Source
Apache-2.0
2,022
HotelSystem
dream-png
Java
Code
279
1,219
/* * Copyright (c) 2019. 黄钰朝 * * 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.hyc.www.test; import com.hyc.www.dao.inter.HotelDao; import com.hyc.www.po.Hotel; import com.hyc.www.util.BeanFactory; import java.math.BigDecimal; import java.util.LinkedList; import static com.hyc.www.util.UUIDUtils.getUUID; /** * @author <a href="mailto:kobe524348@gmail.com">黄钰朝</a> * @program XHotel * @description 测试酒店Dao * @date 2019-04-18 03:05 */ public class TestHotelDao { public static void main(String[] args) { HotelDao hotelDao = (HotelDao) BeanFactory.getBean(BeanFactory.DaoType.HotelDao); /** * 测试查询酒店全部信息功能 */ System.out.println("测试查询酒店全部信息功能"); Hotel hotel = hotelDao.getHotel("1020"); if (hotel != null) { System.out.println(hotel.getNumber()); System.out.println(hotel.getId()); System.out.println(hotel.getStatus()); System.out.println(hotel.getArea()); System.out.println(hotel.getGmtModified()); } else { System.out.println(hotel); } /** * 测试获取所有酒店信息的功能 */ System.out.println("测试获取所有酒店信息的功能"); LinkedList list = hotelDao.getAllHotels(); System.out.println(list.size()); for ( int i = 0; i < list.size(); i++) { hotel = (Hotel) list.get(i); System.out.println(hotel.getGmtModified()); System.out.println(hotel.getNumber()); System.out.println(hotel.getName()); } /** * 测试通过酒店id删除酒店的功能 */ System.out.println("测试通过酒店id删除酒店的功能"); System.out.println(hotelDao.deleteById("5")); /** * 测试通过编号删除酒店的功能 */ System.out.println("测试通过酒店编号删除酒店的功能"); System.out.println(hotelDao.deleteByNumber("0")); /** * 测试更新酒店信息的功能 */ System.out.println("测试更新酒店信息的功能"); hotel = hotelDao.getHotel("0000"); if (hotel != null) { hotel.setArea(BigDecimal.valueOf(1000.90)); System.out.println(hotelDao.update(hotel)); } /** * 测试增加酒店的功能 */ System.out.println("测试增加酒店的功能"); hotel = new Hotel(); hotel.setNumber("1020"); hotel.setPhoto("test2"); System.out.println(hotelDao.addHotel(null)); /** * 测试模糊查询 */ System.out.println(hotelDao.findByName("test"). size()); /** * 批量增加酒店 */ for (int i = 0; i < 30; i++) { hotel = new Hotel(); hotel.setId(getUUID()); hotel.setNumber("01020" + i); hotel.setName("广州精品酒店第" + i + "号酒店"); hotel.setArea(new BigDecimal(i + 110)); System.out.println("add hotel"); hotelDao.addHotel(hotel); } } }
32,693
https://github.com/PinkDiamond1/openiban/blob/master/openibanlib/providers/OpenIBAN.py
Github Open Source
Open Source
MIT
2,015
openiban
PinkDiamond1
Python
Code
57
218
''' Created on Apr 30, 2015 @author: nabu ''' from openibanlib.providers.interfaces import IBANProvider class OpenIBAN(IBANProvider): """ OpenIBAN provider: https://openiban.com/ """ PROVIDER_URL = "https://openiban.com/validate/XXXXXXXX?getBIC=true" def _request_params(self): return dict() def _validate(self,response): json = response.json() if 'valid' in json: return json['valid'] def _parse_bank_data(self, response): json = response.json() if 'bankData' in json: return json['bankData'] def _prepare_url(self,ibn): return self.PROVIDER_URL.replace( 'XXXXXXXX', ibn )
48,125
https://github.com/thereR4lights/ember-styleguide/blob/master/app/styles/components/_es-navbar.scss
Github Open Source
Open Source
MIT
2,019
ember-styleguide
thereR4lights
SCSS
Code
383
1,555
/** Navbar in header **/ .navbar { margin-bottom: 0; &.navbar-inverse { background-color: $orange; border-color: transparent; border-radius: 0; padding: 0; .mr-auto { margin-right: auto; } .navbar-collapse, .navbar-form { border-color: $orange-darkest; } .navbar-toggler { border-color: $white; &:hover { background-color: $orange-darker; } .navbar-toggler-icon { background-image: str-replace(url("data:image/svg+xml;charset=utf8,%3Csvg viewBox='0 0 30 30' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath stroke='#ffffff' stroke-width='2' stroke-linecap='round' stroke-miterlimit='10' d='M4 7h22M4 15h22M4 23h22'/%3E%3C/svg%3E"), "#", "%23"); } } .navbar-brand { img { @media screen and (min-width: 768px) { margin-bottom: 0; margin-right: 10px; padding-bottom: 0; } } } .navbar-nav { margin-top: 0; li { align-content: stretch; display: flex; flex-flow: column wrap; justify-content: center; min-width: 100%; @media screen and (min-width: 992px){ min-width: auto; flex-flow: row wrap; } a { align-items: center; color: $white; display: flex; flex: 1; min-height: 50px; padding: 0 0.5em; text-decoration: none; &:focus { outline: 5px auto -webkit-focus-ring-color; } } &.active { a { background-color: white; color: $orange-darkest; } } &.show { a { background-color: white; color: $orange-darkest; } .dropdown-menu { background-color: white; border-radius: 0; margin: 0 -1px; @media screen and (min-width: 768px) { border-radius: 0 0 4px 4px; border-color-top: white; } .dropdown-item { min-height: 36px; &:hover, :focus { background-color: $orange-lightest; color: $orange-darkest; outline: 0 !important; } } .dropdown-divider { border: 1px solid $orange-lightest; } } } } } form.navbar-right.navbar-form { @media screen and (min-width: 768px) { margin-bottom: 0; } .input-group { min-width: 100%; padding: 0.25em 0; } .form-control { background: url(/images/search-icon.svg) rgba(255, 255, 255, 0.1) 10px 8px no-repeat; border-color: transparent; border-radius: 3px; border-right: 0; box-shadow: none; color: white; font-family: 'Roboto', sans-serif; min-width: 100%; padding: 0.25em 0.5em; &:-ms-input-placeholder { color: $orange-lightest !important; } &:-ms-input-placeholder { color: $orange-lightest !important; } &::placeholder { color: $orange-lightest !important; } &::placeholder { color: $orange-lightest !important; } } } } } // Algolia overrides .ds-dataset-1 { span.ds-suggestions { @media screen and (min-width: 0px) and (max-width: 768px) { z-index: 1000 !important; } } } .algolia-docsearch-footer { border-top-color: $orange-lighter; } .algolia-docsearch-suggestion { border-bottom-color: $orange-lighter; } .algolia-docsearch-suggestion--highlight { color: $orange-darker; } .algolia-docsearch-suggestion--subcategory-column { border-right-color: $orange-lighter; color: $gray-darkest; background-color: $orange-lightest; } .algolia-autocomplete { width: 100%; } .algolia-autocomplete .aa-input, .algolia-autocomplete .aa-hint { width: 100%; } .algolia-autocomplete .aa-hint { color: #999; } .algolia-autocomplete .aa-dropdown-menu { width: 100%; background-color: #fff; border: 1px solid #999; border-top: none; } .algolia-autocomplete .aa-dropdown-menu .aa-suggestion { cursor: pointer; padding: 5px 4px; } .algolia-autocomplete .aa-dropdown-menu .aa-suggestion.aa-cursor { background-color: #B2D7FF; } .algolia-autocomplete .aa-dropdown-menu .aa-suggestion em { font-weight: bold; font-style: normal; }
12,426
https://github.com/dkomarov/jitsi-meet/blob/master/react/features/filmstrip/components/web/Thumbnail.js
Github Open Source
Open Source
Apache-2.0
null
jitsi-meet
dkomarov
JavaScript
Code
2,679
7,958
// @flow import { withStyles } from '@material-ui/styles'; import clsx from 'clsx'; import debounce from 'lodash/debounce'; import React, { Component } from 'react'; import { createScreenSharingIssueEvent, sendAnalytics } from '../../../analytics'; import { Avatar } from '../../../base/avatar'; import { isMobileBrowser } from '../../../base/environment/utils'; import { MEDIA_TYPE, VideoTrack } from '../../../base/media'; import { getParticipantByIdOrUndefined, hasRaisedHand, pinParticipant } from '../../../base/participants'; import { connect } from '../../../base/redux'; import { ASPECT_RATIO_NARROW } from '../../../base/responsive-ui/constants'; import { isTestModeEnabled } from '../../../base/testing'; import { getLocalAudioTrack, getLocalVideoTrack, getTrackByMediaTypeAndParticipant, updateLastTrackVideoMediaEvent } from '../../../base/tracks'; import { getVideoObjectPosition } from '../../../face-centering/functions'; import { PresenceLabel } from '../../../presence-status'; import { getCurrentLayout, LAYOUTS } from '../../../video-layout'; import { DISPLAY_MODE_TO_CLASS_NAME, DISPLAY_VIDEO, SHOW_TOOLBAR_CONTEXT_MENU_AFTER, VIDEO_TEST_EVENTS } from '../../constants'; import { computeDisplayModeFromInput, getDisplayModeInput, isVideoPlayable, showGridInVerticalView } from '../../functions'; import ThumbnailAudioIndicator from './ThumbnailAudioIndicator'; import ThumbnailBottomIndicators from './ThumbnailBottomIndicators'; import ThumbnailTopIndicators from './ThumbnailTopIndicators'; declare var interfaceConfig: Object; /** * The type of the React {@code Component} state of {@link Thumbnail}. */ export type State = {| /** * Indicates that the canplay event has been received. */ canPlayEventReceived: boolean, /** * The current display mode of the thumbnail. */ displayMode: number, /** * Whether popover is visible or not. */ popoverVisible: boolean, /** * Indicates whether the thumbnail is hovered or not. */ isHovered: boolean |}; /** * The type of the React {@code Component} props of {@link Thumbnail}. */ export type Props = {| /** * The audio track related to the participant. */ _audioTrack: ?Object, /** * The current layout of the filmstrip. */ _currentLayout: string, /** * Indicates whether the local video flip feature is disabled or not. */ _disableLocalVideoFlip: boolean, /** * Indicates whether enlargement of tiles to fill the available space is disabled. */ _disableTileEnlargement: boolean, /** * The height of the Thumbnail. */ _height: number, /** * Indicates whether the thumbnail should be hidden or not. */ _isHidden: boolean, /** * Whether or not there is a pinned participant. */ _isAnyParticipantPinned: boolean, /** * Indicates whether audio only mode is enabled. */ _isAudioOnly: boolean, /** * Indicates whether the participant associated with the thumbnail is displayed on the large video. */ _isCurrentlyOnLargeVideo: boolean, /** * Whether we are currently running in a mobile browser. */ _isMobile: boolean, /** * Whether we are currently running in a mobile browser in portrait orientation. */ _isMobilePortrait: boolean, /** * Indicates whether the participant is screen sharing. */ _isScreenSharing: boolean, /** * Indicates whether the video associated with the thumbnail is playable. */ _isVideoPlayable: boolean, /** * Disable/enable the dominant speaker indicator. */ _isDominantSpeakerDisabled: boolean, /** * Indicates whether testing mode is enabled. */ _isTestModeEnabled: boolean, /** * The current local video flip setting. */ _localFlipX: boolean, /** * An object with information about the participant related to the thumbnail. */ _participant: Object, /** * Whether or not the participant has the hand raised. */ _raisedHand: boolean, /** * The video object position for the participant. */ _videoObjectPosition: string, /** * The video track that will be displayed in the thumbnail. */ _videoTrack: ?Object, /** * The width of the thumbnail. */ _width: number, /** * The redux dispatch function. */ dispatch: Function, /** * An object containing the CSS classes. */ classes: Object, /** * The horizontal offset in px for the thumbnail. Used to center the thumbnails from the last row in tile view. */ horizontalOffset: number, /** * The ID of the participant related to the thumbnail. */ participantID: ?string, /** * Styles that will be set to the Thumbnail's main span element. */ style?: ?Object |}; const defaultStyles = theme => { return { indicatorsContainer: { position: 'absolute', padding: `${theme.spacing(1)}px`, zIndex: 10, width: '100%', boxSizing: 'border-box', display: 'flex', left: 0, '&.tile-view-mode': { padding: `${theme.spacing(2)}px` } }, indicatorsTopContainer: { top: 0, justifyContent: 'space-between' }, indicatorsBottomContainer: { bottom: 0 }, indicatorsBackground: { backgroundColor: 'rgba(0, 0, 0, 0.7)', borderRadius: '4px', display: 'flex', alignItems: 'center', maxWidth: '100%', overflow: 'hidden', '&:not(:empty)': { padding: '2px' }, '& > *:not(:last-child)': { marginRight: '4px' }, '&:not(.top-indicators) > span:last-child': { marginRight: '6px' } }, containerBackground: { position: 'absolute', top: 0, left: 0, height: '100%', width: '100%', borderRadius: '4px', backgroundColor: theme.palette.ui02 }, borderIndicator: { position: 'absolute', width: '100%', height: '100%', zIndex: '9', borderRadius: '4px' }, activeSpeaker: { '& .active-speaker-indicator': { boxShadow: `inset 0px 0px 0px 4px ${theme.palette.link01Active} !important` } }, raisedHand: { '& .raised-hand-border': { boxShadow: `inset 0px 0px 0px 2px ${theme.palette.warning02} !important` } } }; }; /** * Implements a thumbnail. * * @augments Component */ class Thumbnail extends Component<Props, State> { /** * The long touch setTimeout handler. */ timeoutHandle: Object; /** * Timeout used to detect double tapping. * It is active while user has tapped once. */ _firstTap: ?TimeoutID; /** * Initializes a new Thumbnail instance. * * @param {Object} props - The read-only React Component props with which * the new instance is to be initialized. */ constructor(props: Props) { super(props); const state = { canPlayEventReceived: false, displayMode: DISPLAY_VIDEO, popoverVisible: false, isHovered: false }; this.state = { ...state, displayMode: computeDisplayModeFromInput(getDisplayModeInput(props, state)) }; this.timeoutHandle = null; this._clearDoubleClickTimeout = this._clearDoubleClickTimeout.bind(this); this._onCanPlay = this._onCanPlay.bind(this); this._onClick = this._onClick.bind(this); this._onMouseEnter = this._onMouseEnter.bind(this); this._onMouseMove = debounce(this._onMouseMove.bind(this), 100, { leading: true, trailing: false }); this._onMouseLeave = this._onMouseLeave.bind(this); this._onTestingEvent = this._onTestingEvent.bind(this); this._onTouchStart = this._onTouchStart.bind(this); this._onTouchEnd = this._onTouchEnd.bind(this); this._onTouchMove = this._onTouchMove.bind(this); this._showPopover = this._showPopover.bind(this); this._hidePopover = this._hidePopover.bind(this); } /** * Starts listening for audio level updates after the initial render. * * @inheritdoc * @returns {void} */ componentDidMount() { this._onDisplayModeChanged(); } /** * Stops listening for audio level updates on the old track and starts * listening instead on the new track. * * @inheritdoc * @returns {void} */ componentDidUpdate(prevProps: Props, prevState: State) { if (prevState.displayMode !== this.state.displayMode) { this._onDisplayModeChanged(); } } /** * Handles display mode changes. * * @returns {void} */ _onDisplayModeChanged() { const input = getDisplayModeInput(this.props, this.state); this._maybeSendScreenSharingIssueEvents(input); } /** * Sends screen sharing issue event if an issue is detected. * * @param {Object} input - The input used to compute the thumbnail display mode. * @returns {void} */ _maybeSendScreenSharingIssueEvents(input) { const { _currentLayout, _isAudioOnly, _isScreenSharing } = this.props; const { displayMode } = this.state; const tileViewActive = _currentLayout === LAYOUTS.TILE_VIEW; if (!(DISPLAY_VIDEO === displayMode) && tileViewActive && _isScreenSharing && !_isAudioOnly) { sendAnalytics(createScreenSharingIssueEvent({ source: 'thumbnail', ...input })); } } /** * Implements React's {@link Component#getDerivedStateFromProps()}. * * @inheritdoc */ static getDerivedStateFromProps(props: Props, prevState: State) { if (!props._videoTrack && prevState.canPlayEventReceived) { const newState = { ...prevState, canPlayEventReceived: false }; return { ...newState, displayMode: computeDisplayModeFromInput(getDisplayModeInput(props, newState)) }; } const newDisplayMode = computeDisplayModeFromInput(getDisplayModeInput(props, prevState)); if (newDisplayMode !== prevState.displayMode) { return { ...prevState, displayMode: newDisplayMode }; } return null; } _clearDoubleClickTimeout: () => void; /** * Clears the first click timeout. * * @returns {void} */ _clearDoubleClickTimeout() { clearTimeout(this._firstTap); this._firstTap = undefined; } _showPopover: () => void; /** * Shows popover. * * @private * @returns {void} */ _showPopover() { this.setState({ popoverVisible: true }); } _hidePopover: () => void; /** * Hides popover. * * @private * @returns {void} */ _hidePopover() { this.setState({ popoverVisible: false }); } /** * Returns an object with the styles for thumbnail. * * @returns {Object} - The styles for the thumbnail. */ _getStyles(): Object { const { canPlayEventReceived } = this.state; const { _currentLayout, _disableTileEnlargement, _height, _isHidden, _isScreenSharing, _participant, _videoObjectPosition, _videoTrack, _width, horizontalOffset, style } = this.props; const tileViewActive = _currentLayout === LAYOUTS.TILE_VIEW; const jitsiVideoTrack = _videoTrack?.jitsiTrack; const track = jitsiVideoTrack?.track; const isPortraitVideo = ((track && track.getSettings()?.aspectRatio) || 1) < 1; let styles: { avatar: Object, thumbnail: Object, video: Object } = { thumbnail: {}, avatar: {}, video: {} }; const avatarSize = Math.min(_height / 2, _width - 30); let { left } = style || {}; if (typeof left === 'number' && horizontalOffset) { left += horizontalOffset; } let videoStyles = null; const doNotStretchVideo = (isPortraitVideo && tileViewActive) || _disableTileEnlargement || _isScreenSharing; if (canPlayEventReceived || _participant.local) { videoStyles = { objectFit: doNotStretchVideo ? 'contain' : 'cover' }; } else { videoStyles = { display: 'none' }; } if (videoStyles.objectFit === 'cover') { videoStyles.objectPosition = _videoObjectPosition; } styles = { thumbnail: { ...style, left, height: `${_height}px`, minHeight: `${_height}px`, minWidth: `${_width}px`, width: `${_width}px` }, avatar: { height: `${avatarSize}px`, width: `${avatarSize}px` }, video: videoStyles }; if (_isHidden) { styles.thumbnail.display = 'none'; } return styles; } _onClick: () => void; /** * On click handler. * * @returns {void} */ _onClick() { const { _participant, dispatch } = this.props; const { id, pinned } = _participant; dispatch(pinParticipant(pinned ? null : id)); } _onMouseEnter: () => void; /** * Mouse enter handler. * * @returns {void} */ _onMouseEnter() { this.setState({ isHovered: true }); } /** * Mouse move handler. * * @returns {void} */ _onMouseMove() { if (!this.state.isHovered) { // Workaround for the use case where the layout changes (for example the participant pane is closed) // and as a result the mouse appears on top of the thumbnail. In these use cases the mouse enter // event on the thumbnail is not triggered in Chrome. this.setState({ isHovered: true }); } } _onMouseLeave: () => void; /** * Mouse leave handler. * * @returns {void} */ _onMouseLeave() { this.setState({ isHovered: false }); } _onTouchStart: () => void; /** * Handler for touch start. * * @returns {void} */ _onTouchStart() { this.timeoutHandle = setTimeout(this._showPopover, SHOW_TOOLBAR_CONTEXT_MENU_AFTER); if (this._firstTap) { this._clearDoubleClickTimeout(); this._onClick(); return; } this._firstTap = setTimeout(this._clearDoubleClickTimeout, 300); } _onTouchEnd: () => void; /** * Cancel showing popover context menu after x miliseconds if the no. Of miliseconds is not reached yet, * or just clears the timeout. * * @returns {void} */ _onTouchEnd() { clearTimeout(this.timeoutHandle); } _onTouchMove: () => void; /** * Cancel showing Context menu after x miliseconds if the number of miliseconds is not reached * before a touch move(drag), or just clears the timeout. * * @returns {void} */ _onTouchMove() { clearTimeout(this.timeoutHandle); } /** * Renders a fake participant (youtube video) thumbnail. * * @param {string} id - The id of the participant. * @returns {ReactElement} */ _renderFakeParticipant() { const { _isMobile, _participant: { avatarURL } } = this.props; const styles = this._getStyles(); const containerClassName = this._getContainerClassName(); return ( <span className = { containerClassName } id = 'sharedVideoContainer' onClick = { this._onClick } { ...(_isMobile ? {} : { onMouseEnter: this._onMouseEnter, onMouseMove: this._onMouseMove, onMouseLeave: this._onMouseLeave }) } style = { styles.thumbnail }> {avatarURL ? ( <img className = 'sharedVideoAvatar' src = { avatarURL } /> ) : this._renderAvatar(styles.avatar)} </span> ); } /** * Renders the avatar. * * @param {Object} styles - The styles that will be applied to the avatar. * @returns {ReactElement} */ _renderAvatar(styles) { const { _participant } = this.props; const { id } = _participant; return ( <div className = 'avatar-container' style = { styles }> <Avatar className = 'userAvatar' participantId = { id } /> </div> ); } /** * Returns the container class name. * * @returns {string} - The class name that will be used for the container. */ _getContainerClassName() { let className = 'videocontainer'; const { displayMode } = this.state; const { _isDominantSpeakerDisabled, _participant, _currentLayout, _isAnyParticipantPinned, _raisedHand, classes } = this.props; className += ` ${DISPLAY_MODE_TO_CLASS_NAME[displayMode]}`; if (_raisedHand) { className += ` ${classes.raisedHand}`; } if (_currentLayout === LAYOUTS.TILE_VIEW) { if (!_isDominantSpeakerDisabled && _participant?.dominantSpeaker) { className += ` ${classes.activeSpeaker} dominant-speaker`; } } else if (_isAnyParticipantPinned) { if (_participant?.pinned) { className += ` videoContainerFocused ${classes.activeSpeaker}`; } } else if (!_isDominantSpeakerDisabled && _participant?.dominantSpeaker) { className += ` ${classes.activeSpeaker} dominant-speaker`; } return className; } _onCanPlay: Object => void; /** * Canplay event listener. * * @param {SyntheticEvent} event - The event. * @returns {void} */ _onCanPlay(event) { this.setState({ canPlayEventReceived: true }); const { _isTestModeEnabled, _videoTrack } = this.props; if (_videoTrack && _isTestModeEnabled) { this._onTestingEvent(event); } } _onTestingEvent: Object => void; /** * Event handler for testing events. * * @param {SyntheticEvent} event - The event. * @returns {void} */ _onTestingEvent(event) { const { _videoTrack, dispatch } = this.props; const jitsiVideoTrack = _videoTrack?.jitsiTrack; dispatch(updateLastTrackVideoMediaEvent(jitsiVideoTrack, event.type)); } /** * Renders a remote participant's 'thumbnail. * * @param {boolean} local - Whether or not it's the local participant. * @returns {ReactElement} */ _renderParticipant(local = false) { const { _audioTrack, _currentLayout, _disableLocalVideoFlip, _isMobile, _isMobilePortrait, _isScreenSharing, _isTestModeEnabled, _localFlipX, _participant, _videoTrack, classes } = this.props; const { id } = _participant || {}; const { isHovered, popoverVisible } = this.state; const styles = this._getStyles(); let containerClassName = this._getContainerClassName(); const videoTrackClassName = !_disableLocalVideoFlip && _videoTrack && !_isScreenSharing && _localFlipX ? 'flipVideoX' : ''; const jitsiVideoTrack = _videoTrack?.jitsiTrack; const videoTrackId = jitsiVideoTrack && jitsiVideoTrack.getId(); const videoEventListeners = {}; if (local) { if (_isMobilePortrait) { styles.thumbnail.height = styles.thumbnail.width; containerClassName = `${containerClassName} self-view-mobile-portrait`; } } else { if (_videoTrack && _isTestModeEnabled) { VIDEO_TEST_EVENTS.forEach(attribute => { videoEventListeners[attribute] = this._onTestingEvent; }); } videoEventListeners.onCanPlay = this._onCanPlay; } const video = _videoTrack && <VideoTrack className = { local ? videoTrackClassName : '' } eventHandlers = { videoEventListeners } id = { local ? 'localVideo_container' : `remoteVideo_${videoTrackId || ''}` } muted = { local ? undefined : true } style = { styles.video } videoTrack = { _videoTrack } />; return ( <span className = { containerClassName } id = { local ? 'localVideoContainer' : `participant_${id}` } { ...(_isMobile ? { onTouchEnd: this._onTouchEnd, onTouchMove: this._onTouchMove, onTouchStart: this._onTouchStart } : { onClick: this._onClick, onMouseEnter: this._onMouseEnter, onMouseMove: this._onMouseMove, onMouseLeave: this._onMouseLeave } ) } style = { styles.thumbnail }> {local ? <span id = 'localVideoWrapper'>{video}</span> : video} <div className = { classes.containerBackground } /> <div className = { clsx(classes.indicatorsContainer, classes.indicatorsTopContainer, _currentLayout === LAYOUTS.TILE_VIEW && 'tile-view-mode' ) }> <ThumbnailTopIndicators currentLayout = { _currentLayout } hidePopover = { this._hidePopover } indicatorsClassName = { classes.indicatorsBackground } isHovered = { isHovered } local = { local } participantId = { id } popoverVisible = { popoverVisible } showPopover = { this._showPopover } /> </div> <div className = { clsx(classes.indicatorsContainer, classes.indicatorsBottomContainer, _currentLayout === LAYOUTS.TILE_VIEW && 'tile-view-mode' ) }> <ThumbnailBottomIndicators className = { classes.indicatorsBackground } currentLayout = { _currentLayout } local = { local } participantId = { id } /> </div> { this._renderAvatar(styles.avatar) } { !local && ( <div className = 'presence-label-container'> <PresenceLabel className = 'presence-label' participantID = { id } /> </div> )} <ThumbnailAudioIndicator _audioTrack = { _audioTrack } /> <div className = { clsx(classes.borderIndicator, 'raised-hand-border') } /> <div className = { clsx(classes.borderIndicator, 'active-speaker-indicator') } /> </span> ); } /** * Implements React's {@link Component#render()}. * * @inheritdoc * @returns {ReactElement} */ render() { const { _participant } = this.props; if (!_participant) { return null; } const { isFakeParticipant, local } = _participant; if (local) { return this._renderParticipant(true); } if (isFakeParticipant) { return this._renderFakeParticipant(); } return this._renderParticipant(); } } /** * Maps (parts of) the redux state to the associated props for this component. * * @param {Object} state - The Redux state. * @param {Object} ownProps - The own props of the component. * @private * @returns {Props} */ function _mapStateToProps(state, ownProps): Object { const { participantID } = ownProps; const participant = getParticipantByIdOrUndefined(state, participantID); const id = participant?.id; const isLocal = participant?.local ?? true; const tracks = state['features/base/tracks']; const _videoTrack = isLocal ? getLocalVideoTrack(tracks) : getTrackByMediaTypeAndParticipant(tracks, MEDIA_TYPE.VIDEO, participantID); const _audioTrack = isLocal ? getLocalAudioTrack(tracks) : getTrackByMediaTypeAndParticipant(tracks, MEDIA_TYPE.AUDIO, participantID); const _currentLayout = getCurrentLayout(state); let size = {}; let _isMobilePortrait = false; const { defaultLocalDisplayName, disableLocalVideoFlip, disableTileEnlargement, iAmRecorder, iAmSipGateway } = state['features/base/config']; const { localFlipX } = state['features/base/settings']; const _isMobile = isMobileBrowser(); switch (_currentLayout) { case LAYOUTS.VERTICAL_FILMSTRIP_VIEW: case LAYOUTS.HORIZONTAL_FILMSTRIP_VIEW: { const { horizontalViewDimensions = { local: {}, remote: {} }, verticalViewDimensions = { local: {}, remote: {}, gridView: {} } } = state['features/filmstrip']; const _verticalViewGrid = showGridInVerticalView(state); const { local, remote } = _currentLayout === LAYOUTS.VERTICAL_FILMSTRIP_VIEW ? verticalViewDimensions : horizontalViewDimensions; const { width, height } = (isLocal ? local : remote) ?? {}; size = { _width: width, _height: height }; if (_verticalViewGrid) { const { width: _width, height: _height } = verticalViewDimensions.gridView.thumbnailSize; size = { _width, _height }; } _isMobilePortrait = _isMobile && state['features/base/responsive-ui'].aspectRatio === ASPECT_RATIO_NARROW; break; } case LAYOUTS.TILE_VIEW: { const { width, height } = state['features/filmstrip'].tileViewDimensions.thumbnailSize; size = { _width: width, _height: height }; break; } } return { _audioTrack, _currentLayout, _defaultLocalDisplayName: defaultLocalDisplayName, _disableLocalVideoFlip: Boolean(disableLocalVideoFlip), _disableTileEnlargement: Boolean(disableTileEnlargement), _isHidden: isLocal && iAmRecorder && !iAmSipGateway, _isAudioOnly: Boolean(state['features/base/audio-only'].enabled), _isCurrentlyOnLargeVideo: state['features/large-video']?.participantId === id, _isDominantSpeakerDisabled: interfaceConfig.DISABLE_DOMINANT_SPEAKER_INDICATOR, _isMobile, _isMobilePortrait, _isScreenSharing: _videoTrack?.videoType === 'desktop', _isTestModeEnabled: isTestModeEnabled(state), _isVideoPlayable: id && isVideoPlayable(state, id), _localFlipX: Boolean(localFlipX), _participant: participant, _raisedHand: hasRaisedHand(participant), _videoObjectPosition: getVideoObjectPosition(state, participant?.id), _videoTrack, ...size }; } export default connect(_mapStateToProps)(withStyles(defaultStyles)(Thumbnail));
39,920
https://github.com/ericktateishi/scoreplay-album/blob/master/src/test/mock/season.js
Github Open Source
Open Source
MIT
null
scoreplay-album
ericktateishi
JavaScript
Code
16
36
export default [ { id: 862, name: "top" }, { id: 694, name: "test2" }, ]
8,608
https://github.com/Stratus3D/programming_erlang_exercises/blob/master/chapter_25/exercise_5/src/ping_pong.erl
Github Open Source
Open Source
MIT
2,020
programming_erlang_exercises
Stratus3D
Erlang
Code
9
42
-module(ping_pong). -export([ping/1]). % Sample CGI function ping(_Arg) -> [<<"foobar">>].
35,741
https://github.com/wiseminds/flutter_music_query/blob/master/example/lib/src/bloc/BlocProvider.dart
Github Open Source
Open Source
MIT
null
flutter_music_query
wiseminds
Dart
Code
79
295
import 'package:flutter/widgets.dart'; import './BlocBase.dart'; class BlocProvider<T extends BlocBase> extends StatefulWidget { final Key? key; final Widget child; final T bloc; static Type _typeOf<T>() => T; BlocProvider({this.key, required this.child, required this.bloc}) : super(key: key); @override State<StatefulWidget> createState() => _BlocProviderState(); static T? of<T extends BlocBase>(final BuildContext context) { final type = _typeOf<BlocProvider<T>>(); BlocProvider<T>? provider = context.findAncestorWidgetOfExactType<BlocProvider<T>>(); return provider?.bloc; } } class _BlocProviderState<T> extends State<BlocProvider<BlocBase>> { @override Widget build(BuildContext context) => widget.child; @override void dispose() { print("Provider dispose!"); widget.bloc.dispose(); super.dispose(); } }
8,481
https://github.com/whigg/hdf5plotter/blob/master/hdf5plotter/tests/test_plot.py
Github Open Source
Open Source
MIT
2,015
hdf5plotter
whigg
Python
Code
25
59
# -*- coding: utf-8 -*- import numpy as np from nose.tools import eq_ from hdf5plotter._plot import plot def test_plot(): plot([1, 2, 3], [1, 4, 9])
21,549
https://github.com/gitter-badger/Light.Data2/blob/master/test/Light.Data.Mysql.Test/Mysql_BaseFieldAggregateTest.cs
Github Open Source
Open Source
MIT
2,020
Light.Data2
gitter-badger
C#
Code
12,330
47,577
using System; using System.Collections.Generic; using System.Text; using Xunit; using Xunit.Abstractions; using System.Linq; using System.Threading.Tasks; using System.Threading; namespace Light.Data.Mysql.Test { public class Mysql_BaseFieldAggregateTest : BaseTest { class BytesEqualityComparer : IEqualityComparer<byte[]> { public bool Equals(byte[] x, byte[] y) { if (x == null && y == null) { return true; } else if (x != null && y != null) { if (x.Length != y.Length) { return false; } else { for (int i = 0; i < x.Length; i++) { if (x[i] != y[i]) { return false; } } return true; } } else { return false; } } public int GetHashCode(byte[] obj) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < obj.Length; i++) { sb.AppendFormat("{0:X2}", obj[i]); } return sb.ToString().GetHashCode(); } } public Mysql_BaseFieldAggregateTest(ITestOutputHelper output) : base(output) { } #region base test List<TeBaseFieldAggregateField> CreateBaseFieldTableList(int count) { List<TeBaseFieldAggregateField> list = new List<TeBaseFieldAggregateField>(); DateTime now = DateTime.Now; DateTime d = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, 0); for (int i = 1; i <= count; i++) { int x = i % 5 == 0 ? -1 : 1; TeBaseFieldAggregateField item = new TeBaseFieldAggregateField(); item.BoolField = i % 3 == 0; item.BoolFieldNull = i % 2 == 0 ? null : (bool?)(item.BoolField); item.ByteField = (byte)(i % 256); item.ByteFieldNull = i % 2 == 0 ? null : (byte?)(item.ByteField); item.SbyteField = (sbyte)((i % 128) * x); item.SbyteFieldNull = i % 2 == 0 ? null : (sbyte?)(item.SbyteField); item.Int16Field = (short)((i % 20) * x); item.Int16FieldNull = i % 2 == 0 ? null : (short?)(item.Int16Field); item.Int32Field = (int)((i % 23) * x); item.Int32FieldNull = i % 2 == 0 ? null : (int?)(item.Int32Field); item.Int64Field = (long)((i % 25) * x); item.Int64FieldNull = i % 2 == 0 ? null : (long?)(item.Int64Field); item.UInt16Field = (ushort)(i % 27); item.UInt16FieldNull = i % 2 == 0 ? null : (ushort?)(item.UInt16Field); item.UInt32Field = (uint)(i % 28); item.UInt32FieldNull = i % 2 == 0 ? null : (uint?)(item.UInt32Field); item.UInt64Field = (ulong)(i % 31); item.UInt64FieldNull = i % 2 == 0 ? null : (ulong?)(item.UInt64Field); item.FloatField = (float)((i % 19) * 0.1 * x); item.FloatFieldNull = i % 2 == 0 ? null : (float?)(item.FloatField); item.DoubleField = (double)((i % 22) * 0.1 * x); item.DoubleFieldNull = i % 2 == 0 ? null : (double?)(item.DoubleField); item.DecimalField = (decimal)((i % 26) * 0.1 * x); item.DecimalFieldNull = i % 2 == 0 ? null : (decimal?)(item.DecimalField); item.DateTimeField = d.AddHours(i * 2); item.DateTimeFieldNull = i % 2 == 0 ? null : (DateTime?)(item.DateTimeField); item.VarcharField = "testtest" + item.Int32Field; item.VarcharFieldNull = i % 2 == 0 ? null : item.VarcharField; item.TextField = "texttext" + item.Int32Field; item.TextFieldNull = i % 2 == 0 ? null : item.TextField; item.BigDataField = Encoding.UTF8.GetBytes(item.VarcharField); item.BigDataFieldNull = i % 2 == 0 ? null : item.BigDataField; item.EnumInt32Field = (EnumInt32Type)(i % 5 - 1); item.EnumInt32FieldNull = i % 2 == 0 ? null : (EnumInt32Type?)(item.EnumInt32Field); item.EnumInt64Field = (EnumInt64Type)(i % 5 - 1); item.EnumInt64FieldNull = i % 2 == 0 ? null : (EnumInt64Type?)(item.EnumInt64Field); list.Add(item); } return list; } List<TeBaseFieldAggregateField> CreateAndInsertBaseFieldTableList(int count) { var list = CreateBaseFieldTableList(count); commandOutput.Enable = false; context.TruncateTable<TeBaseFieldAggregateField>(); context.BatchInsert(list); commandOutput.Enable = true; return list; } [Fact] public void TestCase_Query_Select_Where() { List<TeBaseFieldAggregateField> list = CreateAndInsertBaseFieldTableList(45); int ex = 0; int ac = 0; ex = list.Where(x => x.Int16Field > 10).Count(); ac = context.Query<TeBaseFieldAggregateField>().Where(x => x.Int16Field > 10).AggregateField(x => new { Count = Function.Count() }).Count; Assert.Equal(ex, ac); ex = list.Where(x => x.Int16Field > 10 && x.Int16Field < 20).Count(); ac = context.Query<TeBaseFieldAggregateField>().Where(x => x.Int16Field > 10 && x.Int16Field < 20).AggregateField(x => new { Count = Function.Count() }).Count; Assert.Equal(ex, ac); ex = list.Where(x => x.Int16Field < 10 || x.Int16Field > 20).Count(); ac = context.Query<TeBaseFieldAggregateField>().Where(x => x.Int16Field < 10 || x.Int16Field > 20).AggregateField(x => new { Count = Function.Count() }).Count; Assert.Equal(ex, ac); ex = list.Where(x => x.Int16Field > 10 && x.Int16Field < 20).Count(); ac = context.Query<TeBaseFieldAggregateField>().Where(x => x.Int16Field > 10).WhereWithAnd(x => x.Int16Field < 20).AggregateField(x => new { Count = Function.Count() }).Count; Assert.Equal(ex, ac); ex = list.Where(x => x.Int16Field < 10 || x.Int16Field > 20).Count(); ac = context.Query<TeBaseFieldAggregateField>().Where(x => x.Int16Field < 10).WhereWithOr(x => x.Int16Field > 20).AggregateField(x => new { Count = Function.Count() }).Count; Assert.Equal(ex, ac); ex = list.Where(x => x.Int16Field > 20).Count(); ac = context.Query<TeBaseFieldAggregateField>().Where(x => x.Int16Field < 10).Where(x => x.Int16Field > 20).AggregateField(x => new { Count = Function.Count() }).Count; Assert.Equal(ex, ac); ex = list.Count(); ac = context.Query<TeBaseFieldAggregateField>().Where(x => x.Int16Field < 10).WhereReset().AggregateField(x => new { Count = Function.Count() }).Count; Assert.Equal(ex, ac); } [Fact] public async Task TestCase_Query_Select_Async() { List<TeBaseFieldAggregateField> list = CreateAndInsertBaseFieldTableList(45); int ex = 0; int ac = 0; ex = list.Count(); ac = (await context.Query<TeBaseFieldAggregateField>().AggregateFieldAsync(x => new { Count = Function.Count() }, CancellationToken.None)).Count; Assert.Equal(ex, ac); } [Fact] public void TestCase_Query_Select_Count() { List<TeBaseFieldAggregateField> list = CreateAndInsertBaseFieldTableList(45); int ex = 0; int ac = 0; ex = list.Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.Count() }).Count; Assert.Equal(ex, ac); ex = list.Where(x => x.Int16Field > 10).Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.CountCondition(x.Int16Field > 10) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.BoolField).Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.Count(x.BoolField) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.BoolFieldNull).Where(x => x != null).Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.Count(x.BoolFieldNull) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.ByteField).Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.Count(x.ByteField) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.ByteFieldNull).Where(x => x != null).Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.Count(x.ByteFieldNull) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.SbyteField).Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.Count(x.SbyteField) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.SbyteFieldNull).Where(x => x != null).Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.Count(x.SbyteFieldNull) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.Int16Field).Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.Count(x.Int16Field) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.Int16FieldNull).Where(x => x != null).Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.Count(x.Int16FieldNull) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.Int32Field).Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.Count(x.Int32Field) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.Int32FieldNull).Where(x => x != null).Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.Count(x.Int32FieldNull) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.Int64Field).Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.Count(x.Int64Field) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.Int64FieldNull).Where(x => x != null).Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.Count(x.Int64FieldNull) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.UInt16Field).Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.Count(x.UInt16Field) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.UInt16FieldNull).Where(x => x != null).Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.Count(x.UInt16FieldNull) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.UInt32Field).Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.Count(x.UInt32Field) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.UInt32FieldNull).Where(x => x != null).Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.Count(x.UInt32FieldNull) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.UInt64Field).Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.Count(x.UInt64Field) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.UInt64FieldNull).Where(x => x != null).Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.Count(x.UInt64FieldNull) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.FloatField).Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.Count(x.FloatField) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.FloatFieldNull).Where(x => x != null).Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.Count(x.FloatFieldNull) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.DoubleField).Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.Count(x.DoubleField) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.DoubleFieldNull).Where(x => x != null).Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.Count(x.DoubleFieldNull) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.DateTimeField).Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.Count(x.DateTimeField) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.DateTimeFieldNull).Where(x => x != null).Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.Count(x.DateTimeFieldNull) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.VarcharField).Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.Count(x.VarcharField) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.VarcharFieldNull).Where(x => x != null).Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.Count(x.VarcharFieldNull) }).Count; Assert.Equal(ex, ac); //ex = list.Select(x => x.TextField).Count(); //ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.Count(x.TextField) }).Count; //Assert.Equal(ex, ac); //ex = list.Select(x => x.TextFieldNull).Where(x => x != null).Count(); //ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.Count(x.TextFieldNull) }).Count; //Assert.Equal(ex, ac); ex = list.Select(x => x.BigDataField).Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.Count(x.BigDataField) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.BigDataFieldNull).Where(x => x != null).Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.Count(x.BigDataFieldNull) }).Count; Assert.Equal(ex, ac); } [Fact] public void TestCase_Query_Select_DistinctCount() { List<TeBaseFieldAggregateField> list = CreateAndInsertBaseFieldTableList(45); int ex = 0; int ac = 0; ex = list.Select(x => x.BoolField).Distinct().Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.DistinctCount(x.BoolField) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.BoolFieldNull).Where(x => x != null).Distinct().Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.DistinctCount(x.BoolFieldNull) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.ByteField).Distinct().Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.DistinctCount(x.ByteField) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.ByteFieldNull).Where(x => x != null).Distinct().Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.DistinctCount(x.ByteFieldNull) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.SbyteField).Distinct().Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.DistinctCount(x.SbyteField) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.SbyteFieldNull).Where(x => x != null).Distinct().Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.DistinctCount(x.SbyteFieldNull) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.Int16Field).Distinct().Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.DistinctCount(x.Int16Field) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.Int16FieldNull).Where(x => x != null).Distinct().Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.DistinctCount(x.Int16FieldNull) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.Int32Field).Distinct().Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.DistinctCount(x.Int32Field) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.Int32FieldNull).Where(x => x != null).Distinct().Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.DistinctCount(x.Int32FieldNull) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.Int64Field).Distinct().Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.DistinctCount(x.Int64Field) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.Int64FieldNull).Where(x => x != null).Distinct().Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.DistinctCount(x.Int64FieldNull) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.UInt16Field).Distinct().Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.DistinctCount(x.UInt16Field) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.UInt16FieldNull).Where(x => x != null).Distinct().Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.DistinctCount(x.UInt16FieldNull) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.UInt32Field).Distinct().Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.DistinctCount(x.UInt32Field) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.UInt32FieldNull).Where(x => x != null).Distinct().Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.DistinctCount(x.UInt32FieldNull) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.UInt64Field).Distinct().Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.DistinctCount(x.UInt64Field) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.UInt64FieldNull).Where(x => x != null).Distinct().Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.DistinctCount(x.UInt64FieldNull) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.FloatField).Distinct().Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.DistinctCount(x.FloatField) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.FloatFieldNull).Where(x => x != null).Distinct().Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.DistinctCount(x.FloatFieldNull) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.DoubleField).Distinct().Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.DistinctCount(x.DoubleField) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.DoubleFieldNull).Where(x => x != null).Distinct().Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.DistinctCount(x.DoubleFieldNull) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.DateTimeField).Distinct().Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.DistinctCount(x.DateTimeField) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.DateTimeFieldNull).Where(x => x != null).Distinct().Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.DistinctCount(x.DateTimeFieldNull) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.VarcharField).Distinct().Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.DistinctCount(x.VarcharField) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.VarcharFieldNull).Where(x => x != null).Distinct().Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.DistinctCount(x.VarcharFieldNull) }).Count; Assert.Equal(ex, ac); //ex = list.Select(x => x.TextField).Distinct().Count(); //ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.DistinctCount(x.TextField) }).Count; //Assert.Equal(ex, ac); //ex = list.Select(x => x.TextFieldNull).Where(x => x != null).Distinct().Count(); //ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.DistinctCount(x.TextFieldNull) }).Count; //Assert.Equal(ex, ac); ex = list.Select(x => x.BigDataField).Distinct(new BytesEqualityComparer()).Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.DistinctCount(x.BigDataField) }).Count; Assert.Equal(ex, ac); ex = list.Select(x => x.BigDataFieldNull).Where(x => x != null).Distinct(new BytesEqualityComparer()).Count(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.DistinctCount(x.BigDataFieldNull) }).Count; Assert.Equal(ex, ac); } [Fact] public void TestCase_Query_Select_LongCount() { List<TeBaseFieldAggregateField> list = CreateAndInsertBaseFieldTableList(45); long ex = 0; long ac = 0; ex = list.LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.LongCount() }).LongCount; Assert.Equal(ex, ac); ex = list.Where(x => x.Int16Field > 10).LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.LongCountCondition(x.Int16Field > 10) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.BoolField).LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.LongCount(x.BoolField) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.BoolFieldNull).Where(x => x != null).LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.LongCount(x.BoolFieldNull) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.ByteField).LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.LongCount(x.ByteField) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.ByteFieldNull).Where(x => x != null).LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.LongCount(x.ByteFieldNull) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.SbyteField).LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.LongCount(x.SbyteField) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.SbyteFieldNull).Where(x => x != null).LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.LongCount(x.SbyteFieldNull) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.Int16Field).LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.LongCount(x.Int16Field) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.Int16FieldNull).Where(x => x != null).LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.LongCount(x.Int16FieldNull) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.Int32Field).LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.LongCount(x.Int32Field) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.Int32FieldNull).Where(x => x != null).LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.LongCount(x.Int32FieldNull) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.Int64Field).LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.LongCount(x.Int64Field) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.Int64FieldNull).Where(x => x != null).LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.LongCount(x.Int64FieldNull) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.UInt16Field).LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.LongCount(x.UInt16Field) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.UInt16FieldNull).Where(x => x != null).LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.LongCount(x.UInt16FieldNull) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.UInt32Field).LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.LongCount(x.UInt32Field) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.UInt32FieldNull).Where(x => x != null).LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.LongCount(x.UInt32FieldNull) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.UInt64Field).LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.LongCount(x.UInt64Field) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.UInt64FieldNull).Where(x => x != null).LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.LongCount(x.UInt64FieldNull) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.FloatField).LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.LongCount(x.FloatField) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.FloatFieldNull).Where(x => x != null).LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.LongCount(x.FloatFieldNull) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.DoubleField).LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.LongCount(x.DoubleField) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.DoubleFieldNull).Where(x => x != null).LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.LongCount(x.DoubleFieldNull) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.DateTimeField).LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.LongCount(x.DateTimeField) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.DateTimeFieldNull).Where(x => x != null).LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.LongCount(x.DateTimeFieldNull) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.VarcharField).LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.LongCount(x.VarcharField) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.VarcharFieldNull).Where(x => x != null).LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.LongCount(x.VarcharFieldNull) }).LongCount; Assert.Equal(ex, ac); //ex = list.Select(x => x.TextField).LongCount(); //ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.LongCount(x.TextField) }).LongCount; //Assert.Equal(ex, ac); //ex = list.Select(x => x.TextFieldNull).Where(x => x != null).LongCount(); //ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.LongCount(x.TextFieldNull) }).LongCount; //Assert.Equal(ex, ac); ex = list.Select(x => x.BigDataField).LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.LongCount(x.BigDataField) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.BigDataFieldNull).Where(x => x != null).LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.LongCount(x.BigDataFieldNull) }).LongCount; Assert.Equal(ex, ac); } [Fact] public void TestCase_Query_Select_DistinctLongCount() { List<TeBaseFieldAggregateField> list = CreateAndInsertBaseFieldTableList(45); long ex = 0; long ac = 0; ex = list.Select(x => x.BoolField).Distinct().LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.DistinctLongCount(x.BoolField) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.BoolFieldNull).Where(x => x != null).Distinct().LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.DistinctLongCount(x.BoolFieldNull) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.ByteField).Distinct().LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.DistinctLongCount(x.ByteField) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.ByteFieldNull).Where(x => x != null).Distinct().LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.DistinctLongCount(x.ByteFieldNull) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.SbyteField).Distinct().LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.DistinctLongCount(x.SbyteField) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.SbyteFieldNull).Where(x => x != null).Distinct().LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.DistinctLongCount(x.SbyteFieldNull) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.Int16Field).Distinct().LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.DistinctLongCount(x.Int16Field) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.Int16FieldNull).Where(x => x != null).Distinct().LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.DistinctLongCount(x.Int16FieldNull) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.Int32Field).Distinct().LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.DistinctLongCount(x.Int32Field) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.Int32FieldNull).Where(x => x != null).Distinct().LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.DistinctLongCount(x.Int32FieldNull) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.Int64Field).Distinct().LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.DistinctLongCount(x.Int64Field) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.Int64FieldNull).Where(x => x != null).Distinct().LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.DistinctLongCount(x.Int64FieldNull) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.UInt16Field).Distinct().LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.DistinctLongCount(x.UInt16Field) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.UInt16FieldNull).Where(x => x != null).Distinct().LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.DistinctLongCount(x.UInt16FieldNull) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.UInt32Field).Distinct().LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.DistinctLongCount(x.UInt32Field) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.UInt32FieldNull).Where(x => x != null).Distinct().LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.DistinctLongCount(x.UInt32FieldNull) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.UInt64Field).Distinct().LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.DistinctLongCount(x.UInt64Field) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.UInt64FieldNull).Where(x => x != null).Distinct().LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.DistinctLongCount(x.UInt64FieldNull) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.FloatField).Distinct().LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.DistinctLongCount(x.FloatField) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.FloatFieldNull).Where(x => x != null).Distinct().LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.DistinctLongCount(x.FloatFieldNull) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.DoubleField).Distinct().LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.DistinctLongCount(x.DoubleField) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.DoubleFieldNull).Where(x => x != null).Distinct().LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.DistinctLongCount(x.DoubleFieldNull) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.DateTimeField).Distinct().LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.DistinctLongCount(x.DateTimeField) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.DateTimeFieldNull).Where(x => x != null).Distinct().LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.DistinctLongCount(x.DateTimeFieldNull) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.VarcharField).Distinct().LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.DistinctLongCount(x.VarcharField) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.VarcharFieldNull).Where(x => x != null).Distinct().LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.DistinctLongCount(x.VarcharFieldNull) }).LongCount; Assert.Equal(ex, ac); //ex = list.Select(x => x.TextField).Distinct().LongCount(); //ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.DistinctLongCount(x.TextField) }).LongCount; //Assert.Equal(ex, ac); //ex = list.Select(x => x.TextFieldNull).Where(x => x != null).Distinct().LongCount(); //ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.DistinctLongCount(x.TextFieldNull) }).LongCount; //Assert.Equal(ex, ac); ex = list.Select(x => x.BigDataField).Distinct(new BytesEqualityComparer()).LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.DistinctLongCount(x.BigDataField) }).LongCount; Assert.Equal(ex, ac); ex = list.Select(x => x.BigDataFieldNull).Where(x => x != null).Distinct(new BytesEqualityComparer()).LongCount(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongCount = Function.DistinctLongCount(x.BigDataFieldNull) }).LongCount; Assert.Equal(ex, ac); } [Fact] public void TestCase_Query_Select_Sum() { List<TeBaseFieldAggregateField> list = CreateAndInsertBaseFieldTableList(45); int ex = 0; int ac = 0; int? ex_n = null; int? ac_n = null; ex = list.Select(x => (int)x.ByteField).Sum(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.Sum(x.ByteField) }).Sum; Assert.Equal(ex, ac); ex_n = list.Select(x => (int?)x.ByteFieldNull).Where(x => x != null).Sum(); ac_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.Sum(x.ByteFieldNull) }).Sum; Assert.Equal(ex_n, ac_n); ex = list.Select(x => (int)x.SbyteField).Sum(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.Sum(x.SbyteField) }).Sum; Assert.Equal(ex, ac); ex_n = list.Select(x => (int?)x.SbyteFieldNull).Where(x => x != null).Sum(); ac_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.Sum(x.SbyteFieldNull) }).Sum; Assert.Equal(ex_n, ac_n); ex = list.Select(x => (int)x.Int16Field).Sum(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.Sum(x.Int16Field) }).Sum; Assert.Equal(ex, ac); ex_n = list.Select(x => (int?)x.Int16FieldNull).Where(x => x != null).Sum(); ac_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.Sum(x.Int16FieldNull) }).Sum; Assert.Equal(ex_n, ac_n); ex = list.Select(x => x.Int32Field).Sum(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.Sum(x.Int32Field) }).Sum; Assert.Equal(ex, ac); ex_n = list.Select(x => x.Int32FieldNull).Where(x => x != null).Sum(); ac_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.Sum(x.Int32FieldNull) }).Sum; Assert.Equal(ex_n, ac_n); ex = list.Select(x => (int)x.UInt16Field).Sum(); ac = (int)context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.Sum(x.UInt16Field) }).Sum; Assert.Equal(ex, ac); ex_n = list.Select(x => (int?)x.UInt16FieldNull).Where(x => x != null).Sum(); ac_n = (int?)context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.Sum(x.UInt16FieldNull) }).Sum; Assert.Equal(ex_n, ac_n); ex = list.Select(x => (int)x.UInt32Field).Sum(); ac = (int)context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.Sum(x.UInt32Field) }).Sum; Assert.Equal(ex, ac); ex_n = list.Select(x => (int?)x.UInt32FieldNull).Where(x => x != null).Sum(); ac_n = (int?)context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.Sum(x.UInt32FieldNull) }).Sum; Assert.Equal(ex_n, ac_n); long exl = 0; long acl = 0; long? exl_n = null; long? acl_n = null; exl = list.Select(x => x.Int64Field).Sum(); acl = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.Sum(x.Int64Field) }).Sum; Assert.Equal(exl, acl); exl_n = list.Select(x => x.Int64FieldNull).Where(x => x != null).Sum(); acl_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.Sum(x.Int64FieldNull) }).Sum; Assert.Equal(exl_n, acl_n); exl = list.Select(x => (long)x.UInt64Field).Sum(); acl = (long)context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.Sum(x.UInt64Field) }).Sum; Assert.Equal(exl, acl); exl_n = list.Select(x => (long?)x.UInt64FieldNull).Where(x => x != null).Sum(); acl_n = (long?)context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.Sum(x.UInt64FieldNull) }).Sum; Assert.Equal(exl_n, acl_n); float exf = 0; float acf = 0; float? exf_n = null; float? acf_n = null; exf = list.Select(x => x.FloatField).Sum(); acf = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.Sum(x.FloatField) }).Sum; Assert.Equal(exf, acf, 4); exf_n = list.Select(x => x.FloatFieldNull).Where(x => x != null).Sum(); acf_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.Sum(x.FloatFieldNull) }).Sum; Assert.Equal(exf_n.Value, acf_n.Value, 4); double exd = 0; double acd = 0; double? exd_n = null; double? acd_n = null; exd = list.Select(x => x.DoubleField).Sum(); acd = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.Sum(x.DoubleField) }).Sum; Assert.Equal(exd, acd); exd_n = list.Select(x => x.DoubleFieldNull).Where(x => x != null).Sum(); acd_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.Sum(x.DoubleFieldNull) }).Sum; Assert.Equal(exd_n, acd_n); decimal exm = 0; decimal acm = 0; decimal? exm_n = null; decimal? acm_n = null; exm = list.Select(x => x.DecimalField).Sum(); acm = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.Sum(x.DecimalField) }).Sum; Assert.Equal(exm, acm); exm_n = list.Select(x => x.DecimalFieldNull).Where(x => x != null).Sum(); acm_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.Sum(x.DecimalFieldNull) }).Sum; Assert.Equal(exm_n, acm_n); ac_n = context.Query<TeBaseFieldAggregateField>().Where(x => x.Int32FieldNull == null).AggregateField(x => new { Sum = Function.Sum(x.Int32FieldNull) }).Sum; Assert.Null(ac_n); acm_n = context.Query<TeBaseFieldAggregateField>().Where(x => x.DecimalFieldNull == null).AggregateField(x => new { Sum = Function.Sum(x.DecimalFieldNull) }).Sum; Assert.Null(acm_n); } [Fact] public void TestCase_Query_Select_LongSum() { List<TeBaseFieldAggregateField> list = CreateAndInsertBaseFieldTableList(45); long ex = 0; long ac = 0; long? ex_n = null; long? ac_n = null; ex = list.Select(x => (long)x.ByteField).Sum(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongSum = Function.LongSum(x.ByteField) }).LongSum; Assert.Equal(ex, ac); ex_n = list.Select(x => (long?)x.ByteFieldNull).Where(x => x != null).Sum(); ac_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongSum = Function.LongSum(x.ByteFieldNull) }).LongSum; Assert.Equal(ex_n, ac_n); ex = list.Select(x => (long)x.SbyteField).Sum(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongSum = Function.LongSum(x.SbyteField) }).LongSum; Assert.Equal(ex, ac); ex_n = list.Select(x => (long?)x.SbyteFieldNull).Where(x => x != null).Sum(); ac_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongSum = Function.LongSum(x.SbyteFieldNull) }).LongSum; Assert.Equal(ex_n, ac_n); ex = list.Select(x => (long)x.Int16Field).Sum(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongSum = Function.LongSum(x.Int16Field) }).LongSum; Assert.Equal(ex, ac); ex_n = list.Select(x => (long?)x.Int16FieldNull).Where(x => x != null).Sum(); ac_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongSum = Function.LongSum(x.Int16FieldNull) }).LongSum; Assert.Equal(ex_n, ac_n); ex = list.Select(x => (long)x.Int32Field).Sum(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongSum = Function.LongSum(x.Int32Field) }).LongSum; Assert.Equal(ex, ac); ex_n = list.Select(x => (long?)x.Int32FieldNull).Where(x => x != null).Sum(); ac_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongSum = Function.LongSum(x.Int32FieldNull) }).LongSum; Assert.Equal(ex_n, ac_n); ex = list.Select(x => (long)x.UInt16Field).Sum(); ac = (long)context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.LongSum(x.UInt16Field) }).Sum; Assert.Equal(ex, ac); ex_n = list.Select(x => (long?)x.UInt16FieldNull).Where(x => x != null).Sum(); ac_n = (long?)context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.LongSum(x.UInt16FieldNull) }).Sum; Assert.Equal(ex_n, ac_n); ex = list.Select(x => (long)x.UInt32Field).Sum(); ac = (long)context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.LongSum(x.UInt32Field) }).Sum; Assert.Equal(ex, ac); ex_n = list.Select(x => (long?)x.UInt32FieldNull).Where(x => x != null).Sum(); ac_n = (long?)context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.LongSum(x.UInt32FieldNull) }).Sum; Assert.Equal(ex_n, ac_n); ac_n = context.Query<TeBaseFieldAggregateField>().Where(x => x.Int32FieldNull == null).AggregateField(x => new { LongSum = Function.LongSum(x.Int32FieldNull) }).LongSum; Assert.Null(ac_n); } [Fact] public void TestCase_Query_Select_DistinctSum() { List<TeBaseFieldAggregateField> list = CreateAndInsertBaseFieldTableList(45); int ex = 0; int ac = 0; int? ex_n = null; int? ac_n = null; ex = list.Select(x => (int)x.ByteField).Distinct().Sum(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.DistinctSum(x.ByteField) }).Sum; Assert.Equal(ex, ac); ex_n = list.Select(x => (int?)x.ByteFieldNull).Where(x => x != null).Distinct().Sum(); ac_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.DistinctSum(x.ByteFieldNull) }).Sum; Assert.Equal(ex_n, ac_n); ex = list.Select(x => (int)x.SbyteField).Distinct().Sum(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.DistinctSum(x.SbyteField) }).Sum; Assert.Equal(ex, ac); ex_n = list.Select(x => (int?)x.SbyteFieldNull).Where(x => x != null).Distinct().Sum(); ac_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.DistinctSum(x.SbyteFieldNull) }).Sum; Assert.Equal(ex_n, ac_n); ex = list.Select(x => (int)x.Int16Field).Distinct().Sum(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.DistinctSum(x.Int16Field) }).Sum; Assert.Equal(ex, ac); ex_n = list.Select(x => (int?)x.Int16FieldNull).Where(x => x != null).Distinct().Sum(); ac_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.DistinctSum(x.Int16FieldNull) }).Sum; Assert.Equal(ex_n, ac_n); ex = list.Select(x => x.Int32Field).Distinct().Sum(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.DistinctSum(x.Int32Field) }).Sum; Assert.Equal(ex, ac); ex_n = list.Select(x => x.Int32FieldNull).Where(x => x != null).Distinct().Sum(); ac_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.DistinctSum(x.Int32FieldNull) }).Sum; Assert.Equal(ex_n, ac_n); ex = list.Select(x => (int)x.UInt16Field).Distinct().Sum(); ac = (int)context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.DistinctSum(x.UInt16Field) }).Sum; Assert.Equal(ex, ac); ex_n = list.Select(x => (int?)x.UInt16FieldNull).Where(x => x != null).Distinct().Sum(); ac_n = (int?)context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.DistinctSum(x.UInt16FieldNull) }).Sum; Assert.Equal(ex_n, ac_n); ex = list.Select(x => (int)x.UInt32Field).Distinct().Sum(); ac = (int)context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.DistinctSum(x.UInt32Field) }).Sum; Assert.Equal(ex, ac); ex_n = list.Select(x => (int?)x.UInt32FieldNull).Where(x => x != null).Distinct().Sum(); ac_n = (int?)context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.DistinctSum(x.UInt32FieldNull) }).Sum; Assert.Equal(ex_n, ac_n); long exl = 0; long acl = 0; long? exl_n = null; long? acl_n = null; exl = list.Select(x => x.Int64Field).Distinct().Sum(); acl = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.DistinctSum(x.Int64Field) }).Sum; Assert.Equal(exl, acl); exl_n = list.Select(x => x.Int64FieldNull).Where(x => x != null).Distinct().Sum(); acl_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.DistinctSum(x.Int64FieldNull) }).Sum; Assert.Equal(exl_n, acl_n); exl = list.Select(x => (long)x.UInt64Field).Distinct().Sum(); acl = (long)context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.DistinctSum(x.UInt64Field) }).Sum; Assert.Equal(exl, acl); exl_n = list.Select(x => (long?)x.UInt64FieldNull).Where(x => x != null).Distinct().Sum(); acl_n = (long?)context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.DistinctSum(x.UInt64FieldNull) }).Sum; Assert.Equal(exl_n, acl_n); float exf = 0; float acf = 0; float? exf_n = null; float? acf_n = null; exf = list.Select(x => x.FloatField).Distinct().Sum(); acf = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.DistinctSum(x.FloatField) }).Sum; Assert.Equal(exf, acf); exf_n = list.Select(x => x.FloatFieldNull).Where(x => x != null).Distinct().Sum(); acf_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.DistinctSum(x.FloatFieldNull) }).Sum; Assert.Equal(exf_n, acf_n); double exd = 0; double acd = 0; double? exd_n = null; double? acd_n = null; exd = list.Select(x => x.DoubleField).Distinct().Sum(); acd = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.DistinctSum(x.DoubleField) }).Sum; Assert.Equal(exd, acd, 4); exd_n = list.Select(x => x.DoubleFieldNull).Where(x => x != null).Distinct().Sum(); acd_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.DistinctSum(x.DoubleFieldNull) }).Sum; Assert.Equal(exd_n, acd_n); decimal exm = 0; decimal acm = 0; decimal? exm_n = null; decimal? acm_n = null; exm = list.Select(x => x.DecimalField).Distinct().Sum(); acm = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.DistinctSum(x.DecimalField) }).Sum; Assert.Equal(exm, acm); exm_n = list.Select(x => x.DecimalFieldNull).Where(x => x != null).Distinct().Sum(); acm_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.DistinctSum(x.DecimalFieldNull) }).Sum; Assert.Equal(exm_n, acm_n); ac_n = context.Query<TeBaseFieldAggregateField>().Where(x => x.Int32FieldNull == null).AggregateField(x => new { LongSum = Function.DistinctSum(x.Int32FieldNull) }).LongSum; Assert.Null(ac_n); acm_n = context.Query<TeBaseFieldAggregateField>().Where(x => x.DecimalFieldNull == null).AggregateField(x => new { Sum = Function.DistinctSum(x.DecimalFieldNull) }).Sum; Assert.Null(acm_n); } [Fact] public void TestCase_Query_Select_DistinctLongSum() { List<TeBaseFieldAggregateField> list = CreateAndInsertBaseFieldTableList(45); long ex = 0; long ac = 0; long? ex_n = null; long? ac_n = null; ex = list.Select(x => (long)x.ByteField).Distinct().Sum(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongSum = Function.DistinctLongSum(x.ByteField) }).LongSum; Assert.Equal(ex, ac); ex_n = list.Select(x => (long?)x.ByteFieldNull).Where(x => x != null).Distinct().Sum(); ac_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongSum = Function.DistinctLongSum(x.ByteFieldNull) }).LongSum; Assert.Equal(ex_n, ac_n); ex = list.Select(x => (long)x.SbyteField).Distinct().Sum(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongSum = Function.DistinctLongSum(x.SbyteField) }).LongSum; Assert.Equal(ex, ac); ex_n = list.Select(x => (long?)x.SbyteFieldNull).Where(x => x != null).Distinct().Sum(); ac_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongSum = Function.DistinctLongSum(x.SbyteFieldNull) }).LongSum; Assert.Equal(ex_n, ac_n); ex = list.Select(x => (long)x.Int16Field).Distinct().Sum(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongSum = Function.DistinctLongSum(x.Int16Field) }).LongSum; Assert.Equal(ex, ac); ex_n = list.Select(x => (long?)x.Int16FieldNull).Where(x => x != null).Distinct().Sum(); ac_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongSum = Function.DistinctLongSum(x.Int16FieldNull) }).LongSum; Assert.Equal(ex_n, ac_n); ex = list.Select(x => (long)x.Int32Field).Distinct().Sum(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongSum = Function.DistinctLongSum(x.Int32Field) }).LongSum; Assert.Equal(ex, ac); ex_n = list.Select(x => (long?)x.Int32FieldNull).Where(x => x != null).Distinct().Sum(); ac_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { LongSum = Function.DistinctLongSum(x.Int32FieldNull) }).LongSum; Assert.Equal(ex_n, ac_n); ex = list.Select(x => (long)x.UInt16Field).Distinct().Sum(); ac = (long)context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.DistinctLongSum(x.UInt16Field) }).Sum; Assert.Equal(ex, ac); ex_n = list.Select(x => (long?)x.UInt16FieldNull).Where(x => x != null).Distinct().Sum(); ac_n = (long?)context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.DistinctLongSum(x.UInt16FieldNull) }).Sum; Assert.Equal(ex_n, ac_n); ex = list.Select(x => (long)x.UInt32Field).Distinct().Sum(); ac = (long)context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.DistinctLongSum(x.UInt32Field) }).Sum; Assert.Equal(ex, ac); ex_n = list.Select(x => (long?)x.UInt32FieldNull).Where(x => x != null).Distinct().Sum(); ac_n = (long?)context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Sum = Function.DistinctLongSum(x.UInt32FieldNull) }).Sum; Assert.Equal(ex_n, ac_n); ac_n = context.Query<TeBaseFieldAggregateField>().Where(x => x.Int32FieldNull == null).AggregateField(x => new { LongSum = Function.DistinctLongSum(x.Int32FieldNull) }).LongSum; Assert.Null(ac_n); } [Fact] public void TestCase_Query_Select_Avg() { List<TeBaseFieldAggregateField> list = CreateAndInsertBaseFieldTableList(45); double ex = 0; double ac = 0; double? ex_n = null; double? ac_n = null; ex = list.Select(x => (int)x.ByteField).Average(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Avg = Function.Avg(x.ByteField) }).Avg; Assert.Equal(ex, ac, 4); ex_n = list.Select(x => (int?)x.ByteFieldNull).Where(x => x != null).Average(); ac_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Avg = Function.Avg(x.ByteFieldNull) }).Avg; Assert.Equal(ex_n.Value, ac_n.Value, 4); ex = list.Select(x => (int)x.SbyteField).Average(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Avg = Function.Avg(x.SbyteField) }).Avg; Assert.Equal(ex, ac, 4); ex_n = list.Select(x => (int?)x.SbyteFieldNull).Where(x => x != null).Average(); ac_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Avg = Function.Avg(x.SbyteFieldNull) }).Avg; Assert.Equal(ex_n.Value, ac_n.Value, 4); ex = list.Select(x => (int)x.Int16Field).Average(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Avg = Function.Avg(x.Int16Field) }).Avg; Assert.Equal(ex, ac, 4); ex_n = list.Select(x => (int?)x.Int16FieldNull).Where(x => x != null).Average(); ac_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Avg = Function.Avg(x.Int16FieldNull) }).Avg; Assert.Equal(ex_n.Value, ac_n.Value, 4); ex = list.Select(x => x.Int32Field).Average(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Avg = Function.Avg(x.Int32Field) }).Avg; Assert.Equal(ex, ac, 4); ex_n = list.Select(x => x.Int32FieldNull).Where(x => x != null).Average(); ac_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Avg = Function.Avg(x.Int32FieldNull) }).Avg; Assert.Equal(ex_n.Value, ac_n.Value, 4); ex = list.Select(x => x.Int64Field).Average(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Avg = Function.Avg(x.Int64Field) }).Avg; Assert.Equal(ex, ac, 4); ex_n = list.Select(x => x.Int64FieldNull).Where(x => x != null).Average(); ac_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Avg = Function.Avg(x.Int64FieldNull) }).Avg; Assert.Equal(ex_n.Value, ac_n.Value, 4); ex = list.Select(x => (int)x.UInt16Field).Average(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Avg = Function.Avg(x.UInt16Field) }).Avg; Assert.Equal(ex, ac, 4); ex_n = list.Select(x => (int?)x.UInt16FieldNull).Where(x => x != null).Average(); ac_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Avg = Function.Avg(x.UInt16FieldNull) }).Avg; Assert.Equal(ex_n.Value, ac_n.Value, 4); ex = list.Select(x => (int)x.UInt32Field).Average(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Avg = Function.Avg(x.UInt32Field) }).Avg; Assert.Equal(ex, ac, 4); ex_n = list.Select(x => (int?)x.UInt32FieldNull).Where(x => x != null).Average(); ac_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Avg = Function.Avg(x.UInt32FieldNull) }).Avg; Assert.Equal(ex_n.Value, ac_n.Value, 4); ex = list.Select(x => (long)x.UInt64Field).Average(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Avg = Function.Avg(x.UInt64Field) }).Avg; Assert.Equal(ex, ac, 4); ex_n = list.Select(x => (long?)x.UInt64FieldNull).Where(x => x != null).Average(); ac_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Avg = Function.Avg(x.UInt64FieldNull) }).Avg; Assert.Equal(ex_n.Value, ac_n.Value, 4); ex = list.Select(x => x.FloatField).Average(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Avg = Function.Avg(x.FloatField) }).Avg; Assert.Equal(ex, ac, 4); ex_n = list.Select(x => x.FloatFieldNull).Where(x => x != null).Average(); ac_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Avg = Function.Avg(x.FloatFieldNull) }).Avg; Assert.Equal(ex_n.Value, ac_n.Value, 4); ex = list.Select(x => x.DoubleField).Average(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Avg = Function.Avg(x.DoubleField) }).Avg; Assert.Equal(ex, ac, 4); ex_n = list.Select(x => x.DoubleFieldNull).Where(x => x != null).Average(); ac_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Avg = Function.Avg(x.DoubleFieldNull) }).Avg; Assert.Equal(ex_n.Value, ac_n.Value, 4); decimal exm = 0; decimal acm = 0; decimal? exm_n = null; decimal? acm_n = null; exm = list.Select(x => x.DecimalField).Average(); acm = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Avg = Function.Avg(x.DecimalField) }).Avg; Assert.Equal(exm, acm, 4); exm_n = list.Select(x => x.DecimalFieldNull).Where(x => x != null).Average(); acm_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Avg = Function.Avg(x.DecimalFieldNull) }).Avg; Assert.Equal(exm_n.Value, acm_n.Value, 4); ac_n = context.Query<TeBaseFieldAggregateField>().Where(x => x.Int32FieldNull == null).AggregateField(x => new { Avg = Function.Avg(x.Int32FieldNull) }).Avg; Assert.Null(ac_n); acm_n = context.Query<TeBaseFieldAggregateField>().Where(x => x.DecimalFieldNull == null).AggregateField(x => new { Avg = Function.Avg(x.DecimalFieldNull) }).Avg; Assert.Null(acm_n); } [Fact] public void TestCase_Query_Select_DistinctAvg() { List<TeBaseFieldAggregateField> list = CreateAndInsertBaseFieldTableList(45); double ex = 0; double ac = 0; double? ex_n = null; double? ac_n = null; ex = list.Select(x => (int)x.ByteField).Distinct().Average(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Avg = Function.DistinctAvg(x.ByteField) }).Avg; Assert.Equal(ex, ac, 4); ex_n = list.Select(x => (int?)x.ByteFieldNull).Where(x => x != null).Distinct().Average(); ac_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Avg = Function.DistinctAvg(x.ByteFieldNull) }).Avg; Assert.Equal(ex_n.Value, ac_n.Value, 4); ex = list.Select(x => (int)x.SbyteField).Distinct().Average(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Avg = Function.DistinctAvg(x.SbyteField) }).Avg; Assert.Equal(ex, ac, 4); ex_n = list.Select(x => (int?)x.SbyteFieldNull).Where(x => x != null).Distinct().Average(); ac_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Avg = Function.DistinctAvg(x.SbyteFieldNull) }).Avg; Assert.Equal(ex_n.Value, ac_n.Value, 4); ex = list.Select(x => (int)x.Int16Field).Distinct().Average(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Avg = Function.DistinctAvg(x.Int16Field) }).Avg; Assert.Equal(ex, ac, 4); ex_n = list.Select(x => (int?)x.Int16FieldNull).Where(x => x != null).Distinct().Average(); ac_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Avg = Function.DistinctAvg(x.Int16FieldNull) }).Avg; Assert.Equal(ex_n.Value, ac_n.Value, 4); ex = list.Select(x => x.Int32Field).Distinct().Average(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Avg = Function.DistinctAvg(x.Int32Field) }).Avg; Assert.Equal(ex, ac, 4); ex_n = list.Select(x => x.Int32FieldNull).Where(x => x != null).Distinct().Average(); ac_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Avg = Function.DistinctAvg(x.Int32FieldNull) }).Avg; Assert.Equal(ex_n.Value, ac_n.Value, 4); ex = list.Select(x => x.Int64Field).Distinct().Average(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Avg = Function.DistinctAvg(x.Int64Field) }).Avg; Assert.Equal(ex, ac, 4); ex_n = list.Select(x => x.Int64FieldNull).Where(x => x != null).Distinct().Average(); ac_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Avg = Function.DistinctAvg(x.Int64FieldNull) }).Avg; Assert.Equal(ex_n.Value, ac_n.Value, 4); ex = list.Select(x => (int)x.UInt16Field).Distinct().Average(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Avg = Function.DistinctAvg(x.UInt16Field) }).Avg; Assert.Equal(ex, ac, 4); ex_n = list.Select(x => (int?)x.UInt16FieldNull).Where(x => x != null).Distinct().Average(); ac_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Avg = Function.DistinctAvg(x.UInt16FieldNull) }).Avg; Assert.Equal(ex_n.Value, ac_n.Value, 4); ex = list.Select(x => (int)x.UInt32Field).Distinct().Average(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Avg = Function.DistinctAvg(x.UInt32Field) }).Avg; Assert.Equal(ex, ac, 4); ex_n = list.Select(x => (int?)x.UInt32FieldNull).Where(x => x != null).Distinct().Average(); ac_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Avg = Function.DistinctAvg(x.UInt32FieldNull) }).Avg; Assert.Equal(ex_n.Value, ac_n.Value, 4); ex = list.Select(x => (long)x.UInt64Field).Distinct().Average(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Avg = Function.DistinctAvg(x.UInt64Field) }).Avg; Assert.Equal(ex, ac, 4); ex_n = list.Select(x => (long?)x.UInt64FieldNull).Where(x => x != null).Distinct().Average(); ac_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Avg = Function.DistinctAvg(x.UInt64FieldNull) }).Avg; Assert.Equal(ex_n.Value, ac_n.Value, 4); ex = list.Select(x => x.FloatField).Distinct().Average(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Avg = Function.DistinctAvg(x.FloatField) }).Avg; Assert.Equal(ex, ac, 4); ex_n = list.Select(x => x.FloatFieldNull).Where(x => x != null).Distinct().Average(); ac_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Avg = Function.DistinctAvg(x.FloatFieldNull) }).Avg; Assert.Equal(ex_n.Value, ac_n.Value, 4); ex = list.Select(x => x.DoubleField).Distinct().Average(); ac = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Avg = Function.DistinctAvg(x.DoubleField) }).Avg; Assert.Equal(ex, ac, 4); ex_n = list.Select(x => x.DoubleFieldNull).Where(x => x != null).Distinct().Average(); ac_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Avg = Function.DistinctAvg(x.DoubleFieldNull) }).Avg; Assert.Equal(ex_n.Value, ac_n.Value, 4); decimal exm = 0; decimal acm = 0; decimal? exm_n = null; decimal? acm_n = null; exm = list.Select(x => x.DecimalField).Distinct().Average(); acm = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Avg = Function.DistinctAvg(x.DecimalField) }).Avg; Assert.Equal(exm, acm, 4); exm_n = list.Select(x => x.DecimalFieldNull).Where(x => x != null).Distinct().Average(); acm_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Avg = Function.DistinctAvg(x.DecimalFieldNull) }).Avg; Assert.Equal(exm_n.Value, acm_n.Value, 4); ac_n = context.Query<TeBaseFieldAggregateField>().Where(x => x.Int32FieldNull == null).AggregateField(x => new { Avg = Function.DistinctAvg(x.Int32FieldNull) }).Avg; Assert.Null(ac_n); acm_n = context.Query<TeBaseFieldAggregateField>().Where(x => x.DecimalFieldNull == null).AggregateField(x => new { Avg = Function.DistinctAvg(x.DecimalFieldNull) }).Avg; Assert.Null(acm_n); } [Fact] public void TestCase_Query_Select_Max() { List<TeBaseFieldAggregateField> list = CreateAndInsertBaseFieldTableList(45); byte exb = list.Select(x => x.ByteField).Max(); byte acb = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Max = Function.Max(x.ByteField) }).Max; Assert.Equal(exb, acb); byte? exb_n = list.Select(x => x.ByteFieldNull).Max(); byte? acb_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Max = Function.Max(x.ByteFieldNull) }).Max; Assert.Equal(exb_n, acb_n); sbyte exsb = list.Select(x => x.SbyteField).Max(); sbyte acsb = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Max = Function.Max(x.SbyteField) }).Max; Assert.Equal(exb, acb); sbyte? exsb_n = list.Select(x => x.SbyteFieldNull).Max(); sbyte? acsb_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Max = Function.Max(x.SbyteFieldNull) }).Max; Assert.Equal(exsb_n, acsb_n); short exi16 = list.Select(x => x.Int16Field).Max(); short aci16 = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Max = Function.Max(x.Int16Field) }).Max; Assert.Equal(exi16, aci16); short? exi16_n = list.Select(x => x.Int16FieldNull).Max(); short? aci16_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Max = Function.Max(x.Int16FieldNull) }).Max; Assert.Equal(exi16_n, aci16_n); int exi32 = list.Select(x => x.Int32Field).Max(); int aci32 = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Max = Function.Max(x.Int32Field) }).Max; Assert.Equal(exi32, aci32); int? exi32_n = list.Select(x => x.Int32FieldNull).Max(); int? aci32_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Max = Function.Max(x.Int32FieldNull) }).Max; Assert.Equal(exi32_n, aci32_n); long exi64 = list.Select(x => x.Int64Field).Max(); long aci64 = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Max = Function.Max(x.Int64Field) }).Max; Assert.Equal(exi64, aci64); long? exi64_n = list.Select(x => x.Int64FieldNull).Max(); long? aci64_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Max = Function.Max(x.Int64FieldNull) }).Max; Assert.Equal(exi64_n, aci64_n); ushort exui16 = list.Select(x => x.UInt16Field).Max(); ushort acui16 = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Max = Function.Max(x.UInt16Field) }).Max; Assert.Equal(exi16, aci16); ushort? exui16_n = list.Select(x => x.UInt16FieldNull).Max(); ushort? acui16_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Max = Function.Max(x.UInt16FieldNull) }).Max; Assert.Equal(exi16_n, aci16_n); uint exui32 = list.Select(x => x.UInt32Field).Max(); uint acui32 = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Max = Function.Max(x.UInt32Field) }).Max; Assert.Equal(exi32, aci32); uint? exui32_n = list.Select(x => x.UInt32FieldNull).Max(); uint? acui32_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Max = Function.Max(x.UInt32FieldNull) }).Max; Assert.Equal(exi32_n, aci32_n); ulong exui64 = list.Select(x => x.UInt64Field).Max(); ulong acui64 = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Max = Function.Max(x.UInt64Field) }).Max; Assert.Equal(exi64, aci64); ulong? exui64_n = list.Select(x => x.UInt64FieldNull).Max(); ulong? acui64_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Max = Function.Max(x.UInt64FieldNull) }).Max; Assert.Equal(exi64_n, aci64_n); float exf = list.Select(x => x.FloatField).Max(); float acf = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Max = Function.Max(x.FloatField) }).Max; Assert.Equal(exf, acf); float? exf_n = list.Select(x => x.FloatFieldNull).Max(); float? acf_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Max = Function.Max(x.FloatFieldNull) }).Max; Assert.Equal(exf_n, acf_n); double exd = list.Select(x => x.DoubleField).Max(); double acd = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Max = Function.Max(x.DoubleField) }).Max; Assert.Equal(exd, acd); double? exd_n = list.Select(x => x.DoubleFieldNull).Max(); double? acd_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Max = Function.Max(x.DoubleFieldNull) }).Max; Assert.Equal(exd_n, acd_n); decimal exm = list.Select(x => x.DecimalField).Max(); decimal acm = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Max = Function.Max(x.DecimalField) }).Max; Assert.Equal(exm, acm); decimal? exm_n = list.Select(x => x.DecimalFieldNull).Max(); decimal? acm_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Max = Function.Max(x.DecimalFieldNull) }).Max; Assert.Equal(exm_n, acm_n); DateTime ext = list.Select(x => x.DateTimeField).Max(); DateTime act = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Max = Function.Max(x.DateTimeField) }).Max; Assert.Equal(exm, acm); DateTime? ext_n = list.Select(x => x.DateTimeFieldNull).Max(); DateTime? act_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Max = Function.Max(x.DateTimeFieldNull) }).Max; Assert.Equal(exm_n, acm_n); aci32_n = context.Query<TeBaseFieldAggregateField>().Where(x => x.Int32FieldNull == null).AggregateField(x => new { Max = Function.Max(x.Int32FieldNull) }).Max; Assert.Null(aci32_n); } [Fact] public void TestCase_Query_Select_Min() { List<TeBaseFieldAggregateField> list = CreateAndInsertBaseFieldTableList(45); byte exb = list.Select(x => x.ByteField).Min(); byte acb = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Min = Function.Min(x.ByteField) }).Min; Assert.Equal(exb, acb); byte? exb_n = list.Select(x => x.ByteFieldNull).Min(); byte? acb_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Min = Function.Min(x.ByteFieldNull) }).Min; Assert.Equal(exb_n, acb_n); sbyte exsb = list.Select(x => x.SbyteField).Min(); sbyte acsb = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Min = Function.Min(x.SbyteField) }).Min; Assert.Equal(exb, acb); sbyte? exsb_n = list.Select(x => x.SbyteFieldNull).Min(); sbyte? acsb_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Min = Function.Min(x.SbyteFieldNull) }).Min; Assert.Equal(exsb_n, acsb_n); short exi16 = list.Select(x => x.Int16Field).Min(); short aci16 = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Min = Function.Min(x.Int16Field) }).Min; Assert.Equal(exi16, aci16); short? exi16_n = list.Select(x => x.Int16FieldNull).Min(); short? aci16_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Min = Function.Min(x.Int16FieldNull) }).Min; Assert.Equal(exi16_n, aci16_n); int exi32 = list.Select(x => x.Int32Field).Min(); int aci32 = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Min = Function.Min(x.Int32Field) }).Min; Assert.Equal(exi32, aci32); int? exi32_n = list.Select(x => x.Int32FieldNull).Min(); int? aci32_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Min = Function.Min(x.Int32FieldNull) }).Min; Assert.Equal(exi32_n, aci32_n); long exi64 = list.Select(x => x.Int64Field).Min(); long aci64 = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Min = Function.Min(x.Int64Field) }).Min; Assert.Equal(exi64, aci64); long? exi64_n = list.Select(x => x.Int64FieldNull).Min(); long? aci64_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Min = Function.Min(x.Int64FieldNull) }).Min; Assert.Equal(exi64_n, aci64_n); ushort exui16 = list.Select(x => x.UInt16Field).Min(); ushort acui16 = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Min = Function.Min(x.UInt16Field) }).Min; Assert.Equal(exi16, aci16); ushort? exui16_n = list.Select(x => x.UInt16FieldNull).Min(); ushort? acui16_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Min = Function.Min(x.UInt16FieldNull) }).Min; Assert.Equal(exi16_n, aci16_n); uint exui32 = list.Select(x => x.UInt32Field).Min(); uint acui32 = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Min = Function.Min(x.UInt32Field) }).Min; Assert.Equal(exi32, aci32); uint? exui32_n = list.Select(x => x.UInt32FieldNull).Min(); uint? acui32_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Min = Function.Min(x.UInt32FieldNull) }).Min; Assert.Equal(exi32_n, aci32_n); ulong exui64 = list.Select(x => x.UInt64Field).Min(); ulong acui64 = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Min = Function.Min(x.UInt64Field) }).Min; Assert.Equal(exi64, aci64); ulong? exui64_n = list.Select(x => x.UInt64FieldNull).Min(); ulong? acui64_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Min = Function.Min(x.UInt64FieldNull) }).Min; Assert.Equal(exi64_n, aci64_n); float exf = list.Select(x => x.FloatField).Min(); float acf = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Min = Function.Min(x.FloatField) }).Min; Assert.Equal(exf, acf); float? exf_n = list.Select(x => x.FloatFieldNull).Min(); float? acf_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Min = Function.Min(x.FloatFieldNull) }).Min; Assert.Equal(exf_n, acf_n); double exd = list.Select(x => x.DoubleField).Min(); double acd = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Min = Function.Min(x.DoubleField) }).Min; Assert.Equal(exd, acd); double? exd_n = list.Select(x => x.DoubleFieldNull).Min(); double? acd_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Min = Function.Min(x.DoubleFieldNull) }).Min; Assert.Equal(exd_n, acd_n); decimal exm = list.Select(x => x.DecimalField).Min(); decimal acm = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Min = Function.Min(x.DecimalField) }).Min; Assert.Equal(exm, acm); decimal? exm_n = list.Select(x => x.DecimalFieldNull).Min(); decimal? acm_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Min = Function.Min(x.DecimalFieldNull) }).Min; Assert.Equal(exm_n, acm_n); DateTime ext = list.Select(x => x.DateTimeField).Min(); DateTime act = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Min = Function.Min(x.DateTimeField) }).Min; Assert.Equal(exm, acm); DateTime? ext_n = list.Select(x => x.DateTimeFieldNull).Min(); DateTime? act_n = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Min = Function.Min(x.DateTimeFieldNull) }).Min; Assert.Equal(exm_n, acm_n); aci32_n = context.Query<TeBaseFieldAggregateField>().Where(x => x.Int32FieldNull == null).AggregateField(x => new { Min = Function.Min(x.Int32FieldNull) }).Min; Assert.Null(aci32_n); } [Fact] public void TestCase_Query_Select_Mutli() { List<TeBaseFieldAggregateField> list = CreateAndInsertBaseFieldTableList(45); var ex1 = list.Count(); var ex2 = list.Where(x => x.Int32FieldNull != null).Select(x => x.Int32FieldNull).Count(); var ex3 = list.Where(x => x.Int16Field > 10).Count(); var ex4 = list.Where(x => x.Int32FieldNull != null).Select(x => x.Int32FieldNull).Sum(); var ex5 = list.Where(x => x.Int32FieldNull != null).Select(x => x.Int32FieldNull).Average(); var ex6 = list.Where(x => x.Int32FieldNull != null).Select(x => x.Int32FieldNull).Max(); var ex7 = list.Where(x => x.Int32FieldNull != null).Select(x => x.Int32FieldNull).Min(); var obj = context.Query<TeBaseFieldAggregateField>().AggregateField(x => new { Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.Int32FieldNull), Avg = Function.Avg(x.Int32FieldNull), Max = Function.Max(x.Int32FieldNull), Min = Function.Min(x.Int32FieldNull), }); Assert.Equal(ex1, obj.Count); Assert.Equal(ex2, obj.CountField); Assert.Equal(ex3, obj.CountCondition); Assert.Equal(ex4, obj.Sum); Assert.Equal(ex5.Value, obj.Avg.Value, 4); Assert.Equal(ex6, obj.Max); Assert.Equal(ex7, obj.Min); } class AggregateModel { public int KeyData { get; set; } public int Count { get; set; } public int CountField { get; set; } public int CountCondition { get; set; } public int Sum { get; set; } public double Avg { get; set; } public DateTime Max { get; set; } public DateTime Min { get; set; } } [Fact] public void TestCase_Aggregate_GroupBy() { List<TeBaseFieldAggregateField> list = CreateAndInsertBaseFieldTableList(45); var ex1 = list.GroupBy(x => x.Int32Field).Select(g => new { KeyData = g.Key, Count = g.Count(), CountField = g.Count(x => x.Int32FieldNull != null), CountCondition = g.Count(x => x.Int16Field > 10), Sum = g.Sum(x => x.ByteField), Avg = g.Average(x => x.Int64Field), Max = g.Max(x => x.DateTimeField), Min = g.Min(x => x.DateTimeField), }).ToList().OrderBy(x => x.KeyData).ToList(); var ac1 = context.Query<TeBaseFieldAggregateField>().Aggregate(x => new { KeyData = x.Int32Field, Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).ToList().OrderBy(x => x.KeyData).ToList(); AssertExtend.StrictEqual(ex1, ac1); var ex1_1 = list.GroupBy(x => x.Int32Field).Select(g => new AggregateModel { KeyData = g.Key, Count = g.Count(), CountField = g.Count(x => x.Int32FieldNull != null), CountCondition = g.Count(x => x.Int16Field > 10), Sum = g.Sum(x => x.ByteField), Avg = g.Average(x => x.Int64Field), Max = g.Max(x => x.DateTimeField), Min = g.Min(x => x.DateTimeField), }).ToList().OrderBy(x => x.KeyData).ToList(); var ac1_1 = context.Query<TeBaseFieldAggregateField>().Aggregate(x => new AggregateModel { KeyData = x.Int32Field, Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).ToList().OrderBy(x => x.KeyData).ToList(); AssertExtend.StrictEqual(ex1_1, ac1_1); var ex2 = list.GroupBy(x => new { x.VarcharField, x.ByteField }).Select(g => new { Key1 = g.Key.VarcharField, Key2 = g.Key.ByteField, Count = g.Count(), CountField = g.Count(x => x.Int32FieldNull != null), CountCondition = g.Count(x => x.Int16Field > 10), Sum = g.Sum(x => x.Int32Field), Avg = g.Average(x => x.Int32Field), Max = g.Max(x => x.Int32Field), Min = g.Min(x => x.Int32Field), }).ToList().OrderBy(x => x.Key1).ThenBy(x => x.Key2).ToList(); var ac2 = context.Query<TeBaseFieldAggregateField>().Aggregate(x => new { Key1 = x.VarcharField, Key2 = x.ByteField, Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.Int32Field), Avg = Function.Avg(x.Int32Field), Max = Function.Max(x.Int32Field), Min = Function.Min(x.Int32Field), }).ToList().OrderBy(x => x.Key1).ThenBy(x => x.Key2).ToList(); AssertExtend.StrictEqual(ex2, ac2); var ex3 = list.GroupBy(x => x.VarcharField).Select(g => new { KeyData = g.Key, CountField = g.Count(x => x.Int32FieldNull != null) }).ToList().OrderBy(x => x.KeyData).ToList(); var ac3 = context.Query<TeBaseFieldAggregateField>().Aggregate(x => new { KeyData = x.VarcharField, CountField = Function.Count(x.Int32FieldNull), }).ToList().OrderBy(x => x.KeyData).ToList(); AssertExtend.StrictEqual(ex3, ac3); } [Fact] public async Task TestCase_Aggregate_GroupBy_Async() { List<TeBaseFieldAggregateField> list = CreateAndInsertBaseFieldTableList(45); var ex1 = list.GroupBy(x => x.Int32Field).Select(g => new { KeyData = g.Key, Count = g.Count(), CountField = g.Count(x => x.Int32FieldNull != null), CountCondition = g.Count(x => x.Int16Field > 10), Sum = g.Sum(x => x.ByteField), Avg = g.Average(x => x.Int64Field), Max = g.Max(x => x.DateTimeField), Min = g.Min(x => x.DateTimeField), }).ToList().OrderBy(x => x.KeyData).ToList(); var ac1 = (await context.Query<TeBaseFieldAggregateField>().Aggregate(x => new { KeyData = x.Int32Field, Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).ToListAsync(CancellationToken.None)).OrderBy(x => x.KeyData).ToList(); AssertExtend.StrictEqual(ex1, ac1); var ex1_1 = list.GroupBy(x => x.Int32Field).Select(g => new AggregateModel { KeyData = g.Key, Count = g.Count(), CountField = g.Count(x => x.Int32FieldNull != null), CountCondition = g.Count(x => x.Int16Field > 10), Sum = g.Sum(x => x.ByteField), Avg = g.Average(x => x.Int64Field), Max = g.Max(x => x.DateTimeField), Min = g.Min(x => x.DateTimeField), }).ToList().OrderBy(x => x.KeyData).ToList(); var ac1_1 = (await context.Query<TeBaseFieldAggregateField>().Aggregate(x => new AggregateModel { KeyData = x.Int32Field, Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).ToListAsync(CancellationToken.None)).OrderBy(x => x.KeyData).ToList(); AssertExtend.StrictEqual(ex1_1, ac1_1); } [Fact] public void TestCase_Aggregate_GroupBy_Nofield() { List<TeBaseFieldAggregateField> list = CreateAndInsertBaseFieldTableList(45); var ex1 = list.Count(); var ex2 = list.Where(x => x.Int32FieldNull != null).Select(x => x.Int32FieldNull).Count(); var ex3 = list.Where(x => x.Int16Field > 10).Count(); var ex4 = list.Where(x => x.Int32FieldNull != null).Select(x => x.Int32FieldNull).Sum(); var ex5 = list.Where(x => x.Int32FieldNull != null).Select(x => x.Int32FieldNull).Average(); var ex6 = list.Where(x => x.Int32FieldNull != null).Select(x => x.Int32FieldNull).Max(); var ex7 = list.Where(x => x.Int32FieldNull != null).Select(x => x.Int32FieldNull).Min(); var obj = context.Query<TeBaseFieldAggregateField>().Aggregate(x => new { Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.Int32FieldNull), Avg = Function.Avg(x.Int32FieldNull), Max = Function.Max(x.Int32FieldNull), Min = Function.Min(x.Int32FieldNull), }).First(); Assert.Equal(ex1, obj.Count); Assert.Equal(ex2, obj.CountField); Assert.Equal(ex3, obj.CountCondition); Assert.Equal(ex4, obj.Sum); Assert.Equal(ex5.Value, obj.Avg.Value, 4); Assert.Equal(ex6, obj.Max); Assert.Equal(ex7, obj.Min); } [Fact] public void TestCase_Aggregate_GroupBy_Where() { List<TeBaseFieldAggregateField> list = CreateAndInsertBaseFieldTableList(45); List<AggregateModel> ex = null; List<AggregateModel> ac = null; ex = list .Where(x => x.Id > 10) .GroupBy(x => x.Int32Field).Select(g => new AggregateModel { KeyData = g.Key, Count = g.Count(), CountField = g.Count(x => x.Int32FieldNull != null), CountCondition = g.Count(x => x.Int16Field > 10), Sum = g.Sum(x => x.ByteField), Avg = g.Average(x => x.Int64Field), Max = g.Max(x => x.DateTimeField), Min = g.Min(x => x.DateTimeField), }).ToList().OrderBy(x => x.KeyData).ToList(); ac = context.Query<TeBaseFieldAggregateField>() .Where(x => x.Id > 10) .Aggregate(x => new AggregateModel { KeyData = x.Int32Field, Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).ToList().OrderBy(x => x.KeyData).ToList(); AssertExtend.StrictEqual(ex, ac); ex = list .Where(x => x.DateTimeFieldNull != null) .GroupBy(x => x.Int32Field).Select(g => new AggregateModel { KeyData = g.Key, Count = g.Count(), CountField = g.Count(x => x.Int32FieldNull != null), CountCondition = g.Count(x => x.Int16Field > 10), Sum = g.Sum(x => x.ByteField), Avg = g.Average(x => x.Int64Field), Max = g.Max(x => x.DateTimeField), Min = g.Min(x => x.DateTimeField), }).ToList().OrderBy(x => x.KeyData).ToList(); ac = context.Query<TeBaseFieldAggregateField>() .Where(x => x.DateTimeFieldNull != null) .Aggregate(x => new AggregateModel { KeyData = x.Int32Field, Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).ToList().OrderBy(x => x.KeyData).ToList(); AssertExtend.StrictEqual(ex, ac); ex = list .Where(x => x.DateTimeFieldNull != null && x.Id > 10) .GroupBy(x => x.Int32Field).Select(g => new AggregateModel { KeyData = g.Key, Count = g.Count(), CountField = g.Count(x => x.Int32FieldNull != null), CountCondition = g.Count(x => x.Int16Field > 10), Sum = g.Sum(x => x.ByteField), Avg = g.Average(x => x.Int64Field), Max = g.Max(x => x.DateTimeField), Min = g.Min(x => x.DateTimeField), }).ToList().OrderBy(x => x.KeyData).ToList(); ac = context.Query<TeBaseFieldAggregateField>() .Where(x => x.DateTimeFieldNull != null) .WhereWithAnd(x => x.Id > 10) .Aggregate(x => new AggregateModel { KeyData = x.Int32Field, Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).ToList().OrderBy(x => x.KeyData).ToList(); AssertExtend.StrictEqual(ex, ac); ex = list .Where(x => x.DateTimeFieldNull != null || x.Id > 10) .GroupBy(x => x.Int32Field).Select(g => new AggregateModel { KeyData = g.Key, Count = g.Count(), CountField = g.Count(x => x.Int32FieldNull != null), CountCondition = g.Count(x => x.Int16Field > 10), Sum = g.Sum(x => x.ByteField), Avg = g.Average(x => x.Int64Field), Max = g.Max(x => x.DateTimeField), Min = g.Min(x => x.DateTimeField), }).ToList().OrderBy(x => x.KeyData).ToList(); ac = context.Query<TeBaseFieldAggregateField>() .Where(x => x.DateTimeFieldNull != null) .WhereWithOr(x => x.Id > 10) .Aggregate(x => new AggregateModel { KeyData = x.Int32Field, Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).ToList().OrderBy(x => x.KeyData).ToList(); AssertExtend.StrictEqual(ex, ac); } [Fact] public void TestCase_Aggregate_GroupBy_OrderBy() { List<TeBaseFieldAggregateField> list = CreateAndInsertBaseFieldTableList(45); List<AggregateModel> ex = null; List<AggregateModel> ac = null; ex = list .GroupBy(x => x.Int32Field).Select(g => new AggregateModel { KeyData = g.Key, Count = g.Count(), CountField = g.Count(x => x.Int32FieldNull != null), CountCondition = g.Count(x => x.Int16Field > 10), Sum = g.Sum(x => x.ByteField), Avg = g.Average(x => x.Int64Field), Max = g.Max(x => x.DateTimeField), Min = g.Min(x => x.DateTimeField), }).OrderByDescending(x => x.KeyData).ToList(); ac = context.Query<TeBaseFieldAggregateField>() .Aggregate(x => new AggregateModel { KeyData = x.Int32Field, Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).OrderByDescending(x => x.KeyData).ToList(); AssertExtend.StrictEqual(ex, ac); ex = list .GroupBy(x => x.Int32Field).Select(g => new AggregateModel { KeyData = g.Key, Count = g.Count(), CountField = g.Count(x => x.Int32FieldNull != null), CountCondition = g.Count(x => x.Int16Field > 10), Sum = g.Sum(x => x.ByteField), Avg = g.Average(x => x.Int64Field), Max = g.Max(x => x.DateTimeField), Min = g.Min(x => x.DateTimeField), }).OrderBy(x => x.KeyData).ToList(); ac = context.Query<TeBaseFieldAggregateField>() .Aggregate(x => new AggregateModel { KeyData = x.Int32Field, Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).OrderBy(x => x.KeyData).ToList(); AssertExtend.StrictEqual(ex, ac); ex = list .GroupBy(x => x.Int32Field).Select(g => new AggregateModel { KeyData = g.Key, Count = g.Count(), CountField = g.Count(x => x.Int32FieldNull != null), CountCondition = g.Count(x => x.Int16Field > 10), Sum = g.Sum(x => x.ByteField), Avg = g.Average(x => x.Int64Field), Max = g.Max(x => x.DateTimeField), Min = g.Min(x => x.DateTimeField), }).OrderBy(x => x.Max).ToList(); ac = context.Query<TeBaseFieldAggregateField>() .Aggregate(x => new AggregateModel { KeyData = x.Int32Field, Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).OrderBy(x => x.Max).ToList(); AssertExtend.StrictEqual(ex, ac); ex = list .GroupBy(x => x.Int32Field).Select(g => new AggregateModel { KeyData = g.Key, Count = g.Count(), CountField = g.Count(x => x.Int32FieldNull != null), CountCondition = g.Count(x => x.Int16Field > 10), Sum = g.Sum(x => x.ByteField), Avg = g.Average(x => x.Int64Field), Max = g.Max(x => x.DateTimeField), Min = g.Min(x => x.DateTimeField), }).OrderByDescending(x => x.Max).ToList(); ac = context.Query<TeBaseFieldAggregateField>() .Aggregate(x => new AggregateModel { KeyData = x.Int32Field, Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).OrderByDescending(x => x.Max).ToList(); AssertExtend.StrictEqual(ex, ac); ex = list .GroupBy(x => x.Int32Field).Select(g => new AggregateModel { KeyData = g.Key, Count = g.Count(), CountField = g.Count(x => x.Int32FieldNull != null), CountCondition = g.Count(x => x.Int16Field > 10), Sum = g.Sum(x => x.ByteField), Avg = g.Average(x => x.Int64Field), Max = g.Max(x => x.DateTimeField), Min = g.Min(x => x.DateTimeField), }).OrderByDescending(x => x.Sum).ThenBy(x => x.KeyData).ToList(); ac = context.Query<TeBaseFieldAggregateField>() .Aggregate(x => new AggregateModel { KeyData = x.Int32Field, Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).OrderByDescending(x => x.Sum).OrderByConcat(x => x.KeyData).ToList(); AssertExtend.StrictEqual(ex, ac); ex = list .GroupBy(x => x.Int32Field).Select(g => new AggregateModel { KeyData = g.Key, Count = g.Count(), CountField = g.Count(x => x.Int32FieldNull != null), CountCondition = g.Count(x => x.Int16Field > 10), Sum = g.Sum(x => x.ByteField), Avg = g.Average(x => x.Int64Field), Max = g.Max(x => x.DateTimeField), Min = g.Min(x => x.DateTimeField), }).OrderBy(x => x.KeyData).ToList(); ac = context.Query<TeBaseFieldAggregateField>() .Aggregate(x => new AggregateModel { KeyData = x.Int32Field, Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).OrderByDescending(x => x.Sum).OrderBy(x => x.KeyData).ToList(); AssertExtend.StrictEqual(ex, ac); ex = context.Query<TeBaseFieldAggregateField>() .Aggregate(x => new AggregateModel { KeyData = x.Int32Field, Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).ToList(); ac = context.Query<TeBaseFieldAggregateField>() .Aggregate(x => new AggregateModel { KeyData = x.Int32Field, Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).OrderByDescending(x => x.Sum).OrderByReset().ToList(); AssertExtend.StrictEqual(ex, ac); } [Fact] public void TestCase_Aggregate_GroupBy_Having() { List<TeBaseFieldAggregateField> list = CreateAndInsertBaseFieldTableList(45); List<AggregateModel> ex = null; List<AggregateModel> ac = null; ex = list .GroupBy(x => x.Int32Field).Select(g => new AggregateModel { KeyData = g.Key, Count = g.Count(), CountField = g.Count(x => x.Int32FieldNull != null), CountCondition = g.Count(x => x.Int16Field > 10), Sum = g.Sum(x => x.ByteField), Avg = g.Average(x => x.Int64Field), Max = g.Max(x => x.DateTimeField), Min = g.Min(x => x.DateTimeField), }).Where(x => x.Sum > 10).OrderByDescending(x => x.KeyData).ToList(); ac = context.Query<TeBaseFieldAggregateField>() .Aggregate(x => new AggregateModel { KeyData = x.Int32Field, Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).Having(x => x.Sum > 10).ToList().OrderByDescending(x => x.KeyData).ToList(); AssertExtend.StrictEqual(ex, ac); ex = list .GroupBy(x => x.Int32Field).Select(g => new AggregateModel { KeyData = g.Key, Count = g.Count(), CountField = g.Count(x => x.Int32FieldNull != null), CountCondition = g.Count(x => x.Int16Field > 10), Sum = g.Sum(x => x.ByteField), Avg = g.Average(x => x.Int64Field), Max = g.Max(x => x.DateTimeField), Min = g.Min(x => x.DateTimeField), }).Where(x => x.Sum > 10 && x.Sum < 20).OrderByDescending(x => x.KeyData).ToList(); ac = context.Query<TeBaseFieldAggregateField>() .Aggregate(x => new AggregateModel { KeyData = x.Int32Field, Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).Having(x => x.Sum > 10 && x.Sum < 20).ToList().OrderByDescending(x => x.KeyData).ToList(); AssertExtend.StrictEqual(ex, ac); ex = list .GroupBy(x => x.Int32Field).Select(g => new AggregateModel { KeyData = g.Key, Count = g.Count(), CountField = g.Count(x => x.Int32FieldNull != null), CountCondition = g.Count(x => x.Int16Field > 10), Sum = g.Sum(x => x.ByteField), Avg = g.Average(x => x.Int64Field), Max = g.Max(x => x.DateTimeField), Min = g.Min(x => x.DateTimeField), }).Where(x => x.Sum > 10 && x.Sum < 20).OrderByDescending(x => x.KeyData).ToList(); ac = context.Query<TeBaseFieldAggregateField>() .Aggregate(x => new AggregateModel { KeyData = x.Int32Field, Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).Having(x => x.Sum > 10).HavingWithAnd(x => x.Sum < 20).ToList().OrderByDescending(x => x.KeyData).ToList(); AssertExtend.StrictEqual(ex, ac); ex = list .GroupBy(x => x.Int32Field).Select(g => new AggregateModel { KeyData = g.Key, Count = g.Count(), CountField = g.Count(x => x.Int32FieldNull != null), CountCondition = g.Count(x => x.Int16Field > 10), Sum = g.Sum(x => x.ByteField), Avg = g.Average(x => x.Int64Field), Max = g.Max(x => x.DateTimeField), Min = g.Min(x => x.DateTimeField), }).Where(x => x.Sum < 10 || x.Sum > 20).OrderByDescending(x => x.KeyData).ToList(); ac = context.Query<TeBaseFieldAggregateField>() .Aggregate(x => new AggregateModel { KeyData = x.Int32Field, Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).Having(x => x.Sum < 10).HavingWithOr(x => x.Sum > 20).ToList().OrderByDescending(x => x.KeyData).ToList(); AssertExtend.StrictEqual(ex, ac); ex = list .GroupBy(x => x.Int32Field).Select(g => new AggregateModel { KeyData = g.Key, Count = g.Count(), CountField = g.Count(x => x.Int32FieldNull != null), CountCondition = g.Count(x => x.Int16Field > 10), Sum = g.Sum(x => x.ByteField), Avg = g.Average(x => x.Int64Field), Max = g.Max(x => x.DateTimeField), Min = g.Min(x => x.DateTimeField), }).Where(x => x.Sum > 20).OrderByDescending(x => x.KeyData).ToList(); ac = context.Query<TeBaseFieldAggregateField>() .Aggregate(x => new AggregateModel { KeyData = x.Int32Field, Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).Having(x => x.Sum < 10).Having(x => x.Sum > 20).ToList().OrderByDescending(x => x.KeyData).ToList(); AssertExtend.StrictEqual(ex, ac); ex = list .GroupBy(x => x.Int32Field).Select(g => new AggregateModel { KeyData = g.Key, Count = g.Count(), CountField = g.Count(x => x.Int32FieldNull != null), CountCondition = g.Count(x => x.Int16Field > 10), Sum = g.Sum(x => x.ByteField), Avg = g.Average(x => x.Int64Field), Max = g.Max(x => x.DateTimeField), Min = g.Min(x => x.DateTimeField), }).OrderByDescending(x => x.KeyData).ToList(); ac = context.Query<TeBaseFieldAggregateField>() .Aggregate(x => new AggregateModel { KeyData = x.Int32Field, Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).Having(x => x.Sum < 10).HavingReset().ToList().OrderByDescending(x => x.KeyData).ToList(); AssertExtend.StrictEqual(ex, ac); } [Fact] public void TestCase_Aggregate_GroupBy_Date() { List<TeBaseFieldAggregateField> list = CreateAndInsertBaseFieldTableList(45); var ex = list .GroupBy(x => x.DateTimeField.Date).Select(g => new { KeyData = g.Key, Count = g.Count(), CountField = g.Count(x => x.Int32FieldNull != null), CountCondition = g.Count(x => x.Int16Field > 10), Sum = g.Sum(x => x.ByteField), Avg = g.Average(x => x.Int64Field), Max = g.Max(x => x.DateTimeField), Min = g.Min(x => x.DateTimeField), }).OrderByDescending(x => x.KeyData).ToList(); var ac = context.Query<TeBaseFieldAggregateField>() .Aggregate(x => new { KeyData = x.DateTimeField.Date, Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).OrderByDescending(x => x.KeyData).ToList(); AssertExtend.StrictEqual(ex, ac); } [Fact] public void TestCase_Aggregate_GroupBy_DateTime() { List<TeBaseFieldAggregateField> list = CreateAndInsertBaseFieldTableList(45); List<AggregateModel> ex = null; List<AggregateModel> ac = null; ex = list .GroupBy(x => x.DateTimeField.Year).Select(g => new AggregateModel { KeyData = g.Key, Count = g.Count(), CountField = g.Count(x => x.Int32FieldNull != null), CountCondition = g.Count(x => x.Int16Field > 10), Sum = g.Sum(x => x.ByteField), Avg = g.Average(x => x.Int64Field), Max = g.Max(x => x.DateTimeField), Min = g.Min(x => x.DateTimeField), }).OrderByDescending(x => x.KeyData).ToList(); ac = context.Query<TeBaseFieldAggregateField>() .Aggregate(x => new AggregateModel { KeyData = x.DateTimeField.Year, Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).OrderByDescending(x => x.KeyData).ToList(); AssertExtend.StrictEqual(ex, ac); ex = list .GroupBy(x => x.DateTimeField.Month).Select(g => new AggregateModel { KeyData = g.Key, Count = g.Count(), CountField = g.Count(x => x.Int32FieldNull != null), CountCondition = g.Count(x => x.Int16Field > 10), Sum = g.Sum(x => x.ByteField), Avg = g.Average(x => x.Int64Field), Max = g.Max(x => x.DateTimeField), Min = g.Min(x => x.DateTimeField), }).OrderByDescending(x => x.KeyData).ToList(); ac = context.Query<TeBaseFieldAggregateField>() .Aggregate(x => new AggregateModel { KeyData = x.DateTimeField.Month, Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).OrderByDescending(x => x.KeyData).ToList(); AssertExtend.StrictEqual(ex, ac); ex = list .GroupBy(x => x.DateTimeField.Month).Select(g => new AggregateModel { KeyData = g.Key, Count = g.Count(), CountField = g.Count(x => x.Int32FieldNull != null), CountCondition = g.Count(x => x.Int16Field > 10), Sum = g.Sum(x => x.ByteField), Avg = g.Average(x => x.Int64Field), Max = g.Max(x => x.DateTimeField), Min = g.Min(x => x.DateTimeField), }).OrderByDescending(x => x.KeyData).ToList(); ac = context.Query<TeBaseFieldAggregateField>() .Aggregate(x => new AggregateModel { KeyData = x.DateTimeField.Month, Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).OrderByDescending(x => x.KeyData).ToList(); AssertExtend.StrictEqual(ex, ac); ex = list .GroupBy(x => x.DateTimeField.Month).Select(g => new AggregateModel { KeyData = g.Key, Count = g.Count(), CountField = g.Count(x => x.Int32FieldNull != null), CountCondition = g.Count(x => x.Int16Field > 10), Sum = g.Sum(x => x.ByteField), Avg = g.Average(x => x.Int64Field), Max = g.Max(x => x.DateTimeField), Min = g.Min(x => x.DateTimeField), }).OrderByDescending(x => x.KeyData).ToList(); ac = context.Query<TeBaseFieldAggregateField>() .Aggregate(x => new AggregateModel { KeyData = x.DateTimeField.Month, Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).OrderByDescending(x => x.KeyData).ToList(); AssertExtend.StrictEqual(ex, ac); ex = list .GroupBy(x => x.DateTimeField.Day).Select(g => new AggregateModel { KeyData = g.Key, Count = g.Count(), CountField = g.Count(x => x.Int32FieldNull != null), CountCondition = g.Count(x => x.Int16Field > 10), Sum = g.Sum(x => x.ByteField), Avg = g.Average(x => x.Int64Field), Max = g.Max(x => x.DateTimeField), Min = g.Min(x => x.DateTimeField), }).OrderByDescending(x => x.KeyData).ToList(); ac = context.Query<TeBaseFieldAggregateField>() .Aggregate(x => new AggregateModel { KeyData = x.DateTimeField.Day, Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).OrderByDescending(x => x.KeyData).ToList(); AssertExtend.StrictEqual(ex, ac); ex = list .GroupBy(x => x.DateTimeField.Hour).Select(g => new AggregateModel { KeyData = g.Key, Count = g.Count(), CountField = g.Count(x => x.Int32FieldNull != null), CountCondition = g.Count(x => x.Int16Field > 10), Sum = g.Sum(x => x.ByteField), Avg = g.Average(x => x.Int64Field), Max = g.Max(x => x.DateTimeField), Min = g.Min(x => x.DateTimeField), }).OrderByDescending(x => x.KeyData).ToList(); ac = context.Query<TeBaseFieldAggregateField>() .Aggregate(x => new AggregateModel { KeyData = x.DateTimeField.Hour, Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).OrderByDescending(x => x.KeyData).ToList(); AssertExtend.StrictEqual(ex, ac); ex = list .GroupBy(x => x.DateTimeField.Minute).Select(g => new AggregateModel { KeyData = g.Key, Count = g.Count(), CountField = g.Count(x => x.Int32FieldNull != null), CountCondition = g.Count(x => x.Int16Field > 10), Sum = g.Sum(x => x.ByteField), Avg = g.Average(x => x.Int64Field), Max = g.Max(x => x.DateTimeField), Min = g.Min(x => x.DateTimeField), }).OrderByDescending(x => x.KeyData).ToList(); ac = context.Query<TeBaseFieldAggregateField>() .Aggregate(x => new AggregateModel { KeyData = x.DateTimeField.Minute, Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).OrderByDescending(x => x.KeyData).ToList(); AssertExtend.StrictEqual(ex, ac); ex = list .GroupBy(x => x.DateTimeField.Second).Select(g => new AggregateModel { KeyData = g.Key, Count = g.Count(), CountField = g.Count(x => x.Int32FieldNull != null), CountCondition = g.Count(x => x.Int16Field > 10), Sum = g.Sum(x => x.ByteField), Avg = g.Average(x => x.Int64Field), Max = g.Max(x => x.DateTimeField), Min = g.Min(x => x.DateTimeField), }).OrderByDescending(x => x.KeyData).ToList(); ac = context.Query<TeBaseFieldAggregateField>() .Aggregate(x => new AggregateModel { KeyData = x.DateTimeField.Second, Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).OrderByDescending(x => x.KeyData).ToList(); AssertExtend.StrictEqual(ex, ac); } [Fact] public void TestCase_Aggregate_GroupBy_DateTime_Format() { List<TeBaseFieldAggregateField> list = CreateAndInsertBaseFieldTableList(45); List<string> formats = new List<string> { "yyyyMMdd", "yyyyMM", "yyyy-MM-dd", "yyyy-MM", "dd-MM-yyyy", "MM-dd-yyyy", "yyyy/MM/dd", "yyyy/MM", "dd/MM/yyyy", "MM/dd/yyyy" }; foreach (string format in formats) { var ex = list .GroupBy(x => x.DateTimeField.ToString(format)).Select(g => new { KeyData = g.Key, Count = g.Count(), CountField = g.Count(x => x.Int32FieldNull != null), CountCondition = g.Count(x => x.Int16Field > 10), Sum = g.Sum(x => x.ByteField), Avg = g.Average(x => x.Int64Field), Max = g.Max(x => x.DateTimeField), Min = g.Min(x => x.DateTimeField), }).OrderByDescending(x => x.KeyData).ToList(); var ac = context.Query<TeBaseFieldAggregateField>() .Aggregate(x => new { KeyData = x.DateTimeField.ToString(format), Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).OrderByDescending(x => x.KeyData).ToList(); AssertExtend.StrictEqual(ex, ac); } } [Fact] public void TestCase_Aggregate_GroupBy_String() { List<TeBaseFieldAggregateField> list = CreateAndInsertBaseFieldTableList(45); var ex = list .GroupBy(x => x.VarcharField.Substring(0, 9)).Select(g => new { KeyData = g.Key, Count = g.Count(), CountField = g.Count(x => x.Int32FieldNull != null), CountCondition = g.Count(x => x.Int16Field > 10), Sum = g.Sum(x => x.ByteField), Avg = g.Average(x => x.Int64Field), Max = g.Max(x => x.DateTimeField), Min = g.Min(x => x.DateTimeField), }).OrderByDescending(x => x.KeyData).ToList(); var ac = context.Query<TeBaseFieldAggregateField>() .Aggregate(x => new { KeyData = x.VarcharField.Substring(0, 9), Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).OrderByDescending(x => x.KeyData).ToList(); AssertExtend.StrictEqual(ex, ac); } [Fact] public void TestCase_Aggregate_GroupBy_SelectInsert() { List<TeBaseFieldAggregateField> list = CreateAndInsertBaseFieldTableList(200); context.TruncateTable<TeBaseFieldAggregateFieldGroupBy>(); var ex = list .Where(x => x.Id > 10) .GroupBy(x => new { KeyData = x.Int32Field, MonthData = x.DateTimeField.Month }).Select(g => new TeBaseFieldAggregateFieldGroupBy { KeyData = g.Key.KeyData, MonthData = g.Key.MonthData, CountData = g.Count(), CountFieldData = g.Count(x => x.Int32FieldNull != null), CountConditionData = g.Count(x => x.Int16Field > 10), SumData = g.Sum(x => x.ByteField), AvgData = g.Average(x => x.Int64Field), MaxData = g.Max(x => x.DateTimeField), MinData = g.Min(x => x.DateTimeField), }).ToList().OrderBy(x => x.KeyData).ThenBy(x => x.MonthData).ToList(); var ret = context.Query<TeBaseFieldAggregateField>() .Where(x => x.Id > 10) .Aggregate(x => new { KeyData = x.Int32Field, MonthData = x.DateTimeField.Month, CountData = Function.Count(), CountFieldData = Function.Count(x.Int32FieldNull), CountConditionData = Function.CountCondition(x.Int16Field > 10), SumData = Function.Sum(x.ByteField), AvgData = Function.Avg(x.Int64Field), MaxData = Function.Max(x.DateTimeField), MinData = Function.Min(x.DateTimeField), }).OrderBy(x => x.KeyData).OrderByConcat(x => x.MonthData) .SelectInsert(x => new TeBaseFieldAggregateFieldGroupBy() { KeyData = x.KeyData, MonthData = x.MonthData, CountData = x.CountData, CountFieldData = x.CountFieldData, CountConditionData = x.CountConditionData, SumData = x.SumData, AvgData = x.AvgData, MaxData = x.MaxData, MinData = x.MinData }); Assert.Equal(ex.Count, ret); var ac = context.Query<TeBaseFieldAggregateFieldGroupBy>().ToList(); AssertExtend.StrictEqual(ex, ac); } [Fact] public async Task TestCase_Aggregate_GroupBy_SelectInsertAsync() { List<TeBaseFieldAggregateField> list = CreateAndInsertBaseFieldTableList(200); context.TruncateTable<TeBaseFieldAggregateFieldGroupBy>(); var ex = list .Where(x => x.Id > 10) .GroupBy(x => new { KeyData = x.Int32Field, MonthData = x.DateTimeField.Month }).Select(g => new TeBaseFieldAggregateFieldGroupBy { KeyData = g.Key.KeyData, MonthData = g.Key.MonthData, CountData = g.Count(), CountFieldData = g.Count(x => x.Int32FieldNull != null), CountConditionData = g.Count(x => x.Int16Field > 10), SumData = g.Sum(x => x.ByteField), AvgData = g.Average(x => x.Int64Field), MaxData = g.Max(x => x.DateTimeField), MinData = g.Min(x => x.DateTimeField), }).ToList().OrderBy(x => x.KeyData).ThenBy(x => x.MonthData).ToList(); var ret = await context.Query<TeBaseFieldAggregateField>() .Where(x => x.Id > 10) .Aggregate(x => new { KeyData = x.Int32Field, MonthData = x.DateTimeField.Month, CountData = Function.Count(), CountFieldData = Function.Count(x.Int32FieldNull), CountConditionData = Function.CountCondition(x.Int16Field > 10), SumData = Function.Sum(x.ByteField), AvgData = Function.Avg(x.Int64Field), MaxData = Function.Max(x.DateTimeField), MinData = Function.Min(x.DateTimeField), }).OrderBy(x => x.KeyData).OrderByConcat(x => x.MonthData) .SelectInsertAsync(x => new TeBaseFieldAggregateFieldGroupBy() { KeyData = x.KeyData, MonthData = x.MonthData, CountData = x.CountData, CountFieldData = x.CountFieldData, CountConditionData = x.CountConditionData, SumData = x.SumData, AvgData = x.AvgData, MaxData = x.MaxData, MinData = x.MinData }, CancellationToken.None); Assert.Equal(ex.Count, ret); var ac = context.Query<TeBaseFieldAggregateFieldGroupBy>().ToList(); AssertExtend.StrictEqual(ex, ac); } [Fact] public void TestCase_Aggregate_GroupBy_Single() { List<TeBaseFieldAggregateField> list = CreateAndInsertBaseFieldTableList(45); { var ex = list.GroupBy(x => x.Int32Field).Select(g => new { KeyData = g.Key, Count = g.Count(), CountField = g.Count(x => x.Int32FieldNull != null), CountCondition = g.Count(x => x.Int16Field > 10), Sum = g.Sum(x => x.ByteField), Avg = g.Average(x => x.Int64Field), Max = g.Max(x => x.DateTimeField), Min = g.Min(x => x.DateTimeField), }).OrderBy(x => x.KeyData).First(); var ac = context.Query<TeBaseFieldAggregateField>().Aggregate(x => new { KeyData = x.Int32Field, Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).OrderBy(x => x.KeyData).First(); AssertExtend.StrictEqual(ex, ac); } { var ex = list.GroupBy(x => x.Int32Field).Select(g => new { KeyData = g.Key, Count = g.Count(), CountField = g.Count(x => x.Int32FieldNull != null), CountCondition = g.Count(x => x.Int16Field > 10), Sum = g.Sum(x => x.ByteField), Avg = g.Average(x => x.Int64Field), Max = g.Max(x => x.DateTimeField), Min = g.Min(x => x.DateTimeField), }).OrderBy(x => x.KeyData).ElementAt(5); var ac = context.Query<TeBaseFieldAggregateField>().Aggregate(x => new { KeyData = x.Int32Field, Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).OrderBy(x => x.KeyData).ElementAt(5); AssertExtend.StrictEqual(ex, ac); } } [Fact] public async Task TestCase_Aggregate_GroupBy_SingleAsync() { List<TeBaseFieldAggregateField> list = CreateAndInsertBaseFieldTableList(45); { var ex = list.GroupBy(x => x.Int32Field).Select(g => new { KeyData = g.Key, Count = g.Count(), CountField = g.Count(x => x.Int32FieldNull != null), CountCondition = g.Count(x => x.Int16Field > 10), Sum = g.Sum(x => x.ByteField), Avg = g.Average(x => x.Int64Field), Max = g.Max(x => x.DateTimeField), Min = g.Min(x => x.DateTimeField), }).OrderBy(x => x.KeyData).First(); var ac = await context.Query<TeBaseFieldAggregateField>().Aggregate(x => new { KeyData = x.Int32Field, Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).OrderBy(x => x.KeyData).FirstAsync(CancellationToken.None); AssertExtend.StrictEqual(ex, ac); } { var ex = list.GroupBy(x => x.Int32Field).Select(g => new { KeyData = g.Key, Count = g.Count(), CountField = g.Count(x => x.Int32FieldNull != null), CountCondition = g.Count(x => x.Int16Field > 10), Sum = g.Sum(x => x.ByteField), Avg = g.Average(x => x.Int64Field), Max = g.Max(x => x.DateTimeField), Min = g.Min(x => x.DateTimeField), }).OrderBy(x => x.KeyData).ElementAt(5); var ac = await context.Query<TeBaseFieldAggregateField>().Aggregate(x => new { KeyData = x.Int32Field, Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).OrderBy(x => x.KeyData).ElementAtAsync(5, CancellationToken.None); AssertExtend.StrictEqual(ex, ac); } } [Fact] public void TestCase_Aggregate_GroupBy_PageSize() { const int tol = 21; const int cnt = 8; List<TeBaseFieldAggregateField> list = CreateAndInsertBaseFieldTableList(45); int times = tol / cnt; times++; for (int i = 0; i < times; i++) { { var ex = list.GroupBy(x => x.Int32Field).Select(g => new { KeyData = g.Key, Count = g.Count(), CountField = g.Count(x => x.Int32FieldNull != null), CountCondition = g.Count(x => x.Int16Field > 10), Sum = g.Sum(x => x.ByteField), Avg = g.Average(x => x.Int64Field), Max = g.Max(x => x.DateTimeField), Min = g.Min(x => x.DateTimeField), }).OrderBy(x => x.KeyData).Skip(cnt * i).Take(cnt).ToList(); var ac = context.Query<TeBaseFieldAggregateField>().Aggregate(x => new { KeyData = x.Int32Field, Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).OrderBy(x => x.KeyData).PageSize(i + 1, cnt).ToList(); AssertExtend.StrictEqual(ex, ac); } { var ex = list.GroupBy(x => x.Int32Field).Select(g => new { KeyData = g.Key, Count = g.Count(), CountField = g.Count(x => x.Int32FieldNull != null), CountCondition = g.Count(x => x.Int16Field > 10), Sum = g.Sum(x => x.ByteField), Avg = g.Average(x => x.Int64Field), Max = g.Max(x => x.DateTimeField), Min = g.Min(x => x.DateTimeField), }).OrderBy(x => x.KeyData).Skip(cnt * i).Take(cnt).ToList(); var ac = context.Query<TeBaseFieldAggregateField>().Aggregate(x => new { KeyData = x.Int32Field, Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).OrderBy(x => x.KeyData).Range(i * cnt, (i + 1) * cnt).ToList(); AssertExtend.StrictEqual(ex, ac); } } { var ex = list.GroupBy(x => x.Int32Field).Select(g => new { KeyData = g.Key, Count = g.Count(), CountField = g.Count(x => x.Int32FieldNull != null), CountCondition = g.Count(x => x.Int16Field > 10), Sum = g.Sum(x => x.ByteField), Avg = g.Average(x => x.Int64Field), Max = g.Max(x => x.DateTimeField), Min = g.Min(x => x.DateTimeField), }).OrderBy(x => x.KeyData).Where(x => x.KeyData > cnt).Take(cnt).ToList(); var ac = context.Query<TeBaseFieldAggregateField>().Aggregate(x => new { KeyData = x.Int32Field, Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).OrderBy(x => x.KeyData).Having(x => x.KeyData > cnt).PageSize(1, cnt).ToList(); AssertExtend.StrictEqual(ex, ac); } { var ex = list.GroupBy(x => x.Int32Field).Select(g => new { KeyData = g.Key, Count = g.Count(), CountField = g.Count(x => x.Int32FieldNull != null), CountCondition = g.Count(x => x.Int16Field > 10), Sum = g.Sum(x => x.ByteField), Avg = g.Average(x => x.Int64Field), Max = g.Max(x => x.DateTimeField), Min = g.Min(x => x.DateTimeField), }).OrderByDescending(x => x.KeyData).Take(cnt).ToList(); var ac = context.Query<TeBaseFieldAggregateField>().Aggregate(x => new { KeyData = x.Int32Field, Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).OrderByDescending(x => x.KeyData).PageSize(1, cnt).ToList(); AssertExtend.StrictEqual(ex, ac); } { var ex = list.GroupBy(x => x.Int32Field).Select(g => new { KeyData = g.Key, Count = g.Count(), CountField = g.Count(x => x.Int32FieldNull != null), CountCondition = g.Count(x => x.Int16Field > 10), Sum = g.Sum(x => x.ByteField), Avg = g.Average(x => x.Int64Field), Max = g.Max(x => x.DateTimeField), Min = g.Min(x => x.DateTimeField), }).OrderBy(x => x.KeyData).Where(x => x.KeyData > cnt).Take(cnt).ToList(); var ac = context.Query<TeBaseFieldAggregateField>().Aggregate(x => new { KeyData = x.Int32Field, Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).OrderBy(x => x.KeyData).Having(x => x.KeyData > cnt).Range(0, cnt).ToList(); AssertExtend.StrictEqual(ex, ac); } { var ex = list.GroupBy(x => x.Int32Field).Select(g => new { KeyData = g.Key, Count = g.Count(), CountField = g.Count(x => x.Int32FieldNull != null), CountCondition = g.Count(x => x.Int16Field > 10), Sum = g.Sum(x => x.ByteField), Avg = g.Average(x => x.Int64Field), Max = g.Max(x => x.DateTimeField), Min = g.Min(x => x.DateTimeField), }).OrderByDescending(x => x.KeyData).Take(cnt).ToList(); var ac = context.Query<TeBaseFieldAggregateField>().Aggregate(x => new { KeyData = x.Int32Field, Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).OrderByDescending(x => x.KeyData).Range(0, cnt).ToList(); AssertExtend.StrictEqual(ex, ac); } } [Fact] public void TestCase_Aggregate_GroupBy_TakeSkip() { const int tol = 21; const int cnt = 8; List<TeBaseFieldAggregateField> list = CreateAndInsertBaseFieldTableList(45); int times = tol / cnt; times++; for (int i = 0; i < times; i++) { { var ex = list.GroupBy(x => x.Int32Field).Select(g => new { KeyData = g.Key, Count = g.Count(), CountField = g.Count(x => x.Int32FieldNull != null), CountCondition = g.Count(x => x.Int16Field > 10), Sum = g.Sum(x => x.ByteField), Avg = g.Average(x => x.Int64Field), Max = g.Max(x => x.DateTimeField), Min = g.Min(x => x.DateTimeField), }).OrderBy(x => x.KeyData).Skip(cnt * i).ToList(); var ac = context.Query<TeBaseFieldAggregateField>().Aggregate(x => new { KeyData = x.Int32Field, Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).OrderBy(x => x.KeyData).Skip(cnt * i).ToList(); AssertExtend.StrictEqual(ex, ac); } { var ex = list.GroupBy(x => x.Int32Field).Select(g => new { KeyData = g.Key, Count = g.Count(), CountField = g.Count(x => x.Int32FieldNull != null), CountCondition = g.Count(x => x.Int16Field > 10), Sum = g.Sum(x => x.ByteField), Avg = g.Average(x => x.Int64Field), Max = g.Max(x => x.DateTimeField), Min = g.Min(x => x.DateTimeField), }).OrderBy(x => x.KeyData).Take(cnt * i).ToList(); var ac = context.Query<TeBaseFieldAggregateField>().Aggregate(x => new { KeyData = x.Int32Field, Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).OrderBy(x => x.KeyData).Take(cnt * i).ToList(); AssertExtend.StrictEqual(ex, ac); } { var ex = list.GroupBy(x => x.Int32Field).Select(g => new { KeyData = g.Key, Count = g.Count(), CountField = g.Count(x => x.Int32FieldNull != null), CountCondition = g.Count(x => x.Int16Field > 10), Sum = g.Sum(x => x.ByteField), Avg = g.Average(x => x.Int64Field), Max = g.Max(x => x.DateTimeField), Min = g.Min(x => x.DateTimeField), }).OrderBy(x => x.KeyData).Skip(cnt * i).Take(cnt).ToList(); var ac = context.Query<TeBaseFieldAggregateField>().Aggregate(x => new { KeyData = x.Int32Field, Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).OrderBy(x => x.KeyData).Skip(cnt * i).Take(cnt).ToList(); AssertExtend.StrictEqual(ex, ac); } } { var ex = list.GroupBy(x => x.Int32Field).Select(g => new { KeyData = g.Key, Count = g.Count(), CountField = g.Count(x => x.Int32FieldNull != null), CountCondition = g.Count(x => x.Int16Field > 10), Sum = g.Sum(x => x.ByteField), Avg = g.Average(x => x.Int64Field), Max = g.Max(x => x.DateTimeField), Min = g.Min(x => x.DateTimeField), }).OrderBy(x => x.KeyData).Where(x => x.KeyData > cnt).Take(cnt).ToList(); var ac = context.Query<TeBaseFieldAggregateField>().Aggregate(x => new { KeyData = x.Int32Field, Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).OrderBy(x => x.KeyData).Having(x => x.KeyData > cnt).Take(cnt).ToList(); AssertExtend.StrictEqual(ex, ac); } { var ex = list.GroupBy(x => x.Int32Field).Select(g => new { KeyData = g.Key, Count = g.Count(), CountField = g.Count(x => x.Int32FieldNull != null), CountCondition = g.Count(x => x.Int16Field > 10), Sum = g.Sum(x => x.ByteField), Avg = g.Average(x => x.Int64Field), Max = g.Max(x => x.DateTimeField), Min = g.Min(x => x.DateTimeField), }).OrderByDescending(x => x.KeyData).Take(cnt).ToList(); var ac = context.Query<TeBaseFieldAggregateField>().Aggregate(x => new { KeyData = x.Int32Field, Count = Function.Count(), CountField = Function.Count(x.Int32FieldNull), CountCondition = Function.CountCondition(x.Int16Field > 10), Sum = Function.Sum(x.ByteField), Avg = Function.Avg(x.Int64Field), Max = Function.Max(x.DateTimeField), Min = Function.Min(x.DateTimeField), }).OrderByDescending(x => x.KeyData).Take(cnt).ToList(); AssertExtend.StrictEqual(ex, ac); } } #endregion } }
41,406
https://github.com/sandialabs/nnsd-common/blob/master/src/DatabaseLib/Interpreters/SMARTInterpreter.cs
Github Open Source
Open Source
MIT
2,021
nnsd-common
sandialabs
C#
Code
76
308
using gov.sandia.sld.common.configuration; using gov.sandia.sld.common.data; using gov.sandia.sld.common.utilities; using System.Collections.Generic; using System.Data.SQLite; namespace gov.sandia.sld.common.db.interpreters { public class SMARTInterpreter : BaseInterpreter, IDataInterpreter { public void Interpret(Data data, SQLiteConnection conn) { if (data.Type == ECollectorType.SMART) { ListData<HardDisk> disks = data as ListData<HardDisk>; if (disks == null) return; long device_id = GetDeviceID(data, conn); if(device_id >= 0) { List<string> drive_letter_list = HardDisk.FailingDrives(disks.Data); SmartStatus smart_status = new SmartStatus(); EStatusType status = smart_status.GetStatus(drive_letter_list); SetDeviceStatus(device_id, status, SmartStatus.Types, drive_letter_list.JoinStrings(", "), conn); } } } } }
47,203