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/Mhdismaeel/EnableCors/blob/master/app/Actions/TicketType/StoreNewTypeAction.php
Github Open Source
Open Source
MIT
null
EnableCors
Mhdismaeel
PHP
Code
20
88
<?php namespace App\Actions\TicketType; use App\Models\Ticket_type; class StoreNewTypeAction { public static function execute($inputs) { $type=Ticket_type::create([ 'name'=>$inputs->name ]); return $type; } }
47,967
https://github.com/ntohidi/appinventor-sources/blob/master/appinventor/buildserver/tests/com/google/appinventor/buildserver/testComponentsAsDictKeys.scm
Github Open Source
Open Source
Apache-2.0
2,022
appinventor-sources
ntohidi
Scheme
Code
30
131
(let ((test-dict (call-yail-primitive make-yail-dictionary (*list-for-runtime* (call-yail-primitive make-dictionary-pair (*list-for-runtime* %1$s #t) '(key any) "make a pair")) '(pair) "make a dictionary"))) (call-yail-primitive yail-dictionary-lookup (*list-for-runtime* %1$s test-dict #f) '(key any any) "dictionary lookup"))
3,880
https://github.com/JBEI/foldy/blob/master/frontend/src/TagView.tsx
Github Open Source
Open Source
BSD-2-Clause, LicenseRef-scancode-unknown-license-reference, BSD-3-Clause
2,023
foldy
JBEI
TSX
Code
558
2,017
import React, { useEffect, useState } from "react"; import UIkit from "uikit"; import { Fold, getFoldPdbZip, getFolds, getJobStatus, queueJob, } from "./services/backend.service"; import { makeFoldTable } from "./util/foldTable"; import { CSVLink } from "react-csv"; import { useParams } from "react-router-dom"; import fileDownload from "js-file-download"; import { NewDockPrompt } from "./util/newDockPrompt"; function TagView(props: { setErrorText: (a: string) => void }) { let { tagStringParam } = useParams(); const [tagString] = useState<string>(tagStringParam || ""); const [folds, setFolds] = useState<Fold[] | null>(null); const [stageToStart, setStageToStart] = useState<string | null>(null); if (!tagStringParam) { throw Error("Somehow wound up with an invalid tagstring."); } useEffect(() => { getFolds(null, tagString, null, null).then(setFolds, (e) => { props.setErrorText(e.toString()); }); }, [props]); const restartWholePipelineForAnyFailedjob = () => { if (!folds) { return; } var numFoldsChanged = 0; for (const fold of folds) { if (!fold.id) { continue; } if ( getJobStatus(fold, "features") === "failed" || getJobStatus(fold, "models") === "failed" || getJobStatus(fold, "decompress_pkls") === "failed" ) { const stageToRun = "both"; queueJob(fold.id, stageToRun, false).then( () => { UIkit.notification( `Successfully started stage ${stageToRun} for ${fold.name}.` ); }, (e) => { props.setErrorText(e); } ); numFoldsChanged += 1; } } if (numFoldsChanged === 0) { UIkit.notification("No folds needed a restart."); } }; const startStageForAllFolds = () => { if (!folds) { return; } if (!stageToStart) { UIkit.notification("No stage selected."); return; } var numChanged = 0; for (const fold of folds) { if (!fold.id) { continue; } if (getJobStatus(fold, stageToStart) === "finished") { continue; } ++numChanged; queueJob(fold.id, stageToStart, false).then( () => { UIkit.notification(`Successfully started stage(s) for ${fold.name}.`); }, (e) => { props.setErrorText(e); } ); } if (numChanged === 0) { UIkit.notification(`All folds have finished stage ${stageToStart}.`); } }; const getFoldsDataForCsv = () => { if (!folds) { return ""; } return folds?.map((fold) => { const copy: any = structuredClone(fold); delete copy["docks"]; delete copy["jobs"]; if (fold.docks) { fold.docks.forEach((dock) => { copy[`dock_${dock.ligand_name}_smiles`] = dock.ligand_smiles; const energy = dock.pose_energy === null ? NaN : dock.pose_energy; copy[`dock_${dock.ligand_name}_dg`] = energy; }); } return copy; }); }; const downloadFoldPdbZip = () => { if (!folds) { return; } if (folds.some((fold) => fold.id === null)) { console.error("Some fold has a null ID..."); return; } const fold_ids = folds.map((fold) => fold.id || 0); const dirname = `${tagString}_pdbs`; getFoldPdbZip(fold_ids, dirname).then( (fold_pdb_blob) => { fileDownload(fold_pdb_blob, `${dirname}.zip`); }, (e) => { props.setErrorText(e); } ); }; return ( <div className="uk-margin-small-left uk-margin-small-right"> <h2 className="uk-heading-line uk-margin-left uk-margin-right uk-text-center"> <b>Tag: {tagString}</b> </h2> {folds ? ( <div key="loadedDiv">{makeFoldTable(folds)}</div> ) : ( <div className="uk-text-center" key="unloadedDiv"> {/* We're setting key so that the table doesn't spin... */} <div uk-spinner="ratio: 4" key="spinner"></div> </div> )} <form> <fieldset className="uk-fieldset"> <div className="uk-margin"> <button type="button" className="uk-button uk-button-primary uk-form-small" onClick={() => restartWholePipelineForAnyFailedjob()} > Restart Whole Pipeline For Any Failed Jobs </button> </div> </fieldset> <fieldset className="uk-fieldset"> <div className="uk-margin"> <CSVLink data={getFoldsDataForCsv()} className="uk-button uk-button-primary uk-form-small" filename={`${tagString}_metadata`} > Download as CSV </CSVLink> </div> </fieldset> <fieldset className="uk-fieldset"> <div className="uk-margin"> <button type="button" className="uk-button uk-button-primary uk-form-small" onClick={() => downloadFoldPdbZip()} > Downlaod Fold PDBs in Zip File </button> </div> </fieldset> <fieldset className="uk-fieldset"> <div className="uk-margin"> <select className="uk-select uk-form-width-medium uk-form-small" id="form-horizontal-select" value={stageToStart || ""} onChange={(e) => { setStageToStart(e.target.value); }} > <option></option> <option>both</option> <option>annotate</option> <option>write_fastas</option> <option>features</option> <option>models</option> <option>decompress_pkls</option> </select> <button type="button" className="uk-button uk-button-primary uk-form-small" onClick={startStageForAllFolds} > Start stage for all folds </button> </div> </fieldset> </form> <h3>Docking</h3> {folds ? ( <NewDockPrompt setErrorText={props.setErrorText} foldIds={folds.map((fold) => fold.id ?? -1)} // Should never happen, but null fold ids are replaced w/ invalid. /> ) : null} </div> ); } export default TagView;
10,031
https://github.com/sethips/DS-Unit-3-Sprint-3-Big-Data/blob/master/Sprint_Challenge_Unit_3_Big_Data.ipynb
Github Open Source
Open Source
MIT
2,019
DS-Unit-3-Sprint-3-Big-Data
sethips
Jupyter Notebook
Code
3,414
16,385
{ "cells": [ { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [], "source": [ "import dask.dataframe as dd" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "data": { "text/html": [ "<div>\n", "<style scoped>\n", " .dataframe tbody tr th:only-of-type {\n", " vertical-align: middle;\n", " }\n", "\n", " .dataframe tbody tr th {\n", " vertical-align: top;\n", " }\n", "\n", " .dataframe thead th {\n", " text-align: right;\n", " }\n", "</style>\n", "<table border=\"1\" class=\"dataframe\">\n", " <thead>\n", " <tr style=\"text-align: right;\">\n", " <th></th>\n", " <th>COMMENT_ID</th>\n", " <th>AUTHOR</th>\n", " <th>DATE</th>\n", " <th>CONTENT</th>\n", " <th>CLASS</th>\n", " </tr>\n", " </thead>\n", " <tbody>\n", " <tr>\n", " <th>0</th>\n", " <td>LZQPQhLyRh80UYxNuaDWhIGQYNQ96IuCg-AYWqNPjpU</td>\n", " <td>Julius NM</td>\n", " <td>2013-11-07T06:20:48</td>\n", " <td>Huh, anyway check out this you[tube] channel: ...</td>\n", " <td>1</td>\n", " </tr>\n", " <tr>\n", " <th>1</th>\n", " <td>LZQPQhLyRh_C2cTtd9MvFRJedxydaVW-2sNg5Diuo4A</td>\n", " <td>adam riyati</td>\n", " <td>2013-11-07T12:37:15</td>\n", " <td>Hey guys check out my new channel and our firs...</td>\n", " <td>1</td>\n", " </tr>\n", " <tr>\n", " <th>2</th>\n", " <td>LZQPQhLyRh9MSZYnf8djyk0gEF9BHDPYrrK-qCczIY8</td>\n", " <td>Evgeny Murashkin</td>\n", " <td>2013-11-08T17:34:21</td>\n", " <td>just for test I have to say murdev.com</td>\n", " <td>1</td>\n", " </tr>\n", " <tr>\n", " <th>3</th>\n", " <td>z13jhp0bxqncu512g22wvzkasxmvvzjaz04</td>\n", " <td>ElNino Melendez</td>\n", " <td>2013-11-09T08:28:43</td>\n", " <td>me shaking my sexy ass on my channel enjoy ^_^ </td>\n", " <td>1</td>\n", " </tr>\n", " <tr>\n", " <th>4</th>\n", " <td>z13fwbwp1oujthgqj04chlngpvzmtt3r3dw</td>\n", " <td>GsMega</td>\n", " <td>2013-11-10T16:05:38</td>\n", " <td>watch?v=vtaRGgvGtWQ Check this out .</td>\n", " <td>1</td>\n", " </tr>\n", " </tbody>\n", "</table>\n", "</div>" ], "text/plain": [ " COMMENT_ID AUTHOR \\\n", "0 LZQPQhLyRh80UYxNuaDWhIGQYNQ96IuCg-AYWqNPjpU Julius NM \n", "1 LZQPQhLyRh_C2cTtd9MvFRJedxydaVW-2sNg5Diuo4A adam riyati \n", "2 LZQPQhLyRh9MSZYnf8djyk0gEF9BHDPYrrK-qCczIY8 Evgeny Murashkin \n", "3 z13jhp0bxqncu512g22wvzkasxmvvzjaz04 ElNino Melendez \n", "4 z13fwbwp1oujthgqj04chlngpvzmtt3r3dw GsMega \n", "\n", " DATE CONTENT \\\n", "0 2013-11-07T06:20:48 Huh, anyway check out this you[tube] channel: ... \n", "1 2013-11-07T12:37:15 Hey guys check out my new channel and our firs... \n", "2 2013-11-08T17:34:21 just for test I have to say murdev.com \n", "3 2013-11-09T08:28:43 me shaking my sexy ass on my channel enjoy ^_^  \n", "4 2013-11-10T16:05:38 watch?v=vtaRGgvGtWQ Check this out . \n", "\n", " CLASS \n", "0 1 \n", "1 1 \n", "2 1 \n", "3 1 \n", "4 1 " ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "psy = dd.read_csv('Youtube01-Psy.csv')\n", "psy.head()" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "data": { "text/html": [ "<div>\n", "<style scoped>\n", " .dataframe tbody tr th:only-of-type {\n", " vertical-align: middle;\n", " }\n", "\n", " .dataframe tbody tr th {\n", " vertical-align: top;\n", " }\n", "\n", " .dataframe thead th {\n", " text-align: right;\n", " }\n", "</style>\n", "<table border=\"1\" class=\"dataframe\">\n", " <thead>\n", " <tr style=\"text-align: right;\">\n", " <th></th>\n", " <th>COMMENT_ID</th>\n", " <th>AUTHOR</th>\n", " <th>DATE</th>\n", " <th>CONTENT</th>\n", " <th>CLASS</th>\n", " </tr>\n", " </thead>\n", " <tbody>\n", " <tr>\n", " <th>0</th>\n", " <td>z12pgdhovmrktzm3i23es5d5junftft3f</td>\n", " <td>lekanaVEVO1</td>\n", " <td>2014-07-22T15:27:50</td>\n", " <td>i love this so much. AND also I Generate Free ...</td>\n", " <td>1</td>\n", " </tr>\n", " <tr>\n", " <th>1</th>\n", " <td>z13yx345uxepetggz04ci5rjcxeohzlrtf4</td>\n", " <td>Pyunghee</td>\n", " <td>2014-07-27T01:57:16</td>\n", " <td>http://www.billboard.com/articles/columns/pop-...</td>\n", " <td>1</td>\n", " </tr>\n", " <tr>\n", " <th>2</th>\n", " <td>z12lsjvi3wa5x1vwh04cibeaqnzrevxajw00k</td>\n", " <td>Erica Ross</td>\n", " <td>2014-07-27T02:51:43</td>\n", " <td>Hey guys! Please join me in my fight to help a...</td>\n", " <td>1</td>\n", " </tr>\n", " <tr>\n", " <th>3</th>\n", " <td>z13jcjuovxbwfr0ge04cev2ipsjdfdurwck</td>\n", " <td>Aviel Haimov</td>\n", " <td>2014-08-01T12:27:48</td>\n", " <td>http://psnboss.com/?ref=2tGgp3pV6L this is the...</td>\n", " <td>1</td>\n", " </tr>\n", " <tr>\n", " <th>4</th>\n", " <td>z13qybua2yfydzxzj04cgfpqdt2syfx53ms0k</td>\n", " <td>John Bello</td>\n", " <td>2014-08-01T21:04:03</td>\n", " <td>Hey everyone. Watch this trailer!!!!!!!! http...</td>\n", " <td>1</td>\n", " </tr>\n", " </tbody>\n", "</table>\n", "</div>" ], "text/plain": [ " COMMENT_ID AUTHOR DATE \\\n", "0 z12pgdhovmrktzm3i23es5d5junftft3f lekanaVEVO1 2014-07-22T15:27:50 \n", "1 z13yx345uxepetggz04ci5rjcxeohzlrtf4 Pyunghee 2014-07-27T01:57:16 \n", "2 z12lsjvi3wa5x1vwh04cibeaqnzrevxajw00k Erica Ross 2014-07-27T02:51:43 \n", "3 z13jcjuovxbwfr0ge04cev2ipsjdfdurwck Aviel Haimov 2014-08-01T12:27:48 \n", "4 z13qybua2yfydzxzj04cgfpqdt2syfx53ms0k John Bello 2014-08-01T21:04:03 \n", "\n", " CONTENT CLASS \n", "0 i love this so much. AND also I Generate Free ... 1 \n", "1 http://www.billboard.com/articles/columns/pop-... 1 \n", "2 Hey guys! Please join me in my fight to help a... 1 \n", "3 http://psnboss.com/?ref=2tGgp3pV6L this is the... 1 \n", "4 Hey everyone. Watch this trailer!!!!!!!! http... 1 " ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "katyperry = dd.read_csv('Youtube02-KatyPerry.csv')\n", "katyperry.head()" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "data": { "text/html": [ "<div>\n", "<style scoped>\n", " .dataframe tbody tr th:only-of-type {\n", " vertical-align: middle;\n", " }\n", "\n", " .dataframe tbody tr th {\n", " vertical-align: top;\n", " }\n", "\n", " .dataframe thead th {\n", " text-align: right;\n", " }\n", "</style>\n", "<table border=\"1\" class=\"dataframe\">\n", " <thead>\n", " <tr style=\"text-align: right;\">\n", " <th></th>\n", " <th>COMMENT_ID</th>\n", " <th>AUTHOR</th>\n", " <th>DATE</th>\n", " <th>CONTENT</th>\n", " <th>CLASS</th>\n", " </tr>\n", " </thead>\n", " <tbody>\n", " <tr>\n", " <th>0</th>\n", " <td>z13uwn2heqndtr5g304ccv5j5kqqzxjadmc0k</td>\n", " <td>Corey Wilson</td>\n", " <td>2015-05-28T21:39:52.376000</td>\n", " <td>&lt;a href=\"http://www.youtube.com/watch?v=KQ6zr6...</td>\n", " <td>0</td>\n", " </tr>\n", " <tr>\n", " <th>1</th>\n", " <td>z124jvczaz3dxhnbc04cffk43oiugj25yzo0k</td>\n", " <td>Epic Gaming</td>\n", " <td>2015-05-28T20:07:20.610000</td>\n", " <td>wierd but funny</td>\n", " <td>0</td>\n", " </tr>\n", " <tr>\n", " <th>2</th>\n", " <td>z13tczjy5xj0vjmu5231unho1ofey5zdk</td>\n", " <td>LaS Music</td>\n", " <td>2015-05-28T19:23:35.355000</td>\n", " <td>Hey guys, I&amp;#39;m a human.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Bu...</td>\n", " <td>1</td>\n", " </tr>\n", " <tr>\n", " <th>3</th>\n", " <td>z13tzr0hdpnayhqqc04cd3zqqqjkf3ngckk0k</td>\n", " <td>Cheryl Fox</td>\n", " <td>2015-05-28T17:49:35.294000</td>\n", " <td>Party Rock....lol...who wants to shuffle!!!</td>\n", " <td>0</td>\n", " </tr>\n", " <tr>\n", " <th>4</th>\n", " <td>z12pcvix4zedcjvyb04ccr1r0mr2g5xwyng0k</td>\n", " <td>PATRICK_TW</td>\n", " <td>2015-05-28T16:28:26.818000</td>\n", " <td>Party rock</td>\n", " <td>0</td>\n", " </tr>\n", " </tbody>\n", "</table>\n", "</div>" ], "text/plain": [ " COMMENT_ID AUTHOR \\\n", "0 z13uwn2heqndtr5g304ccv5j5kqqzxjadmc0k Corey Wilson \n", "1 z124jvczaz3dxhnbc04cffk43oiugj25yzo0k Epic Gaming \n", "2 z13tczjy5xj0vjmu5231unho1ofey5zdk LaS Music \n", "3 z13tzr0hdpnayhqqc04cd3zqqqjkf3ngckk0k Cheryl Fox \n", "4 z12pcvix4zedcjvyb04ccr1r0mr2g5xwyng0k PATRICK_TW \n", "\n", " DATE \\\n", "0 2015-05-28T21:39:52.376000 \n", "1 2015-05-28T20:07:20.610000 \n", "2 2015-05-28T19:23:35.355000 \n", "3 2015-05-28T17:49:35.294000 \n", "4 2015-05-28T16:28:26.818000 \n", "\n", " CONTENT CLASS \n", "0 <a href=\"http://www.youtube.com/watch?v=KQ6zr6... 0 \n", "1 wierd but funny 0 \n", "2 Hey guys, I&#39;m a human.<br /><br /><br />Bu... 1 \n", "3 Party Rock....lol...who wants to shuffle!!! 0 \n", "4 Party rock 0 " ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "lmfao = dd.read_csv('Youtube03-LMFAO.csv')\n", "lmfao.head()" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "data": { "text/html": [ "<div>\n", "<style scoped>\n", " .dataframe tbody tr th:only-of-type {\n", " vertical-align: middle;\n", " }\n", "\n", " .dataframe tbody tr th {\n", " vertical-align: top;\n", " }\n", "\n", " .dataframe thead th {\n", " text-align: right;\n", " }\n", "</style>\n", "<table border=\"1\" class=\"dataframe\">\n", " <thead>\n", " <tr style=\"text-align: right;\">\n", " <th></th>\n", " <th>COMMENT_ID</th>\n", " <th>AUTHOR</th>\n", " <th>DATE</th>\n", " <th>CONTENT</th>\n", " <th>CLASS</th>\n", " </tr>\n", " </thead>\n", " <tbody>\n", " <tr>\n", " <th>0</th>\n", " <td>z12rwfnyyrbsefonb232i5ehdxzkjzjs2</td>\n", " <td>Lisa Wellas</td>\n", " <td>NaN</td>\n", " <td>+447935454150 lovely girl talk to me xxx</td>\n", " <td>1</td>\n", " </tr>\n", " <tr>\n", " <th>1</th>\n", " <td>z130wpnwwnyuetxcn23xf5k5ynmkdpjrj04</td>\n", " <td>jason graham</td>\n", " <td>2015-05-29T02:26:10.652000</td>\n", " <td>I always end up coming back to this song&lt;br /&gt;</td>\n", " <td>0</td>\n", " </tr>\n", " <tr>\n", " <th>2</th>\n", " <td>z13vsfqirtavjvu0t22ezrgzyorwxhpf3</td>\n", " <td>Ajkal Khan</td>\n", " <td>NaN</td>\n", " <td>my sister just received over 6,500 new &lt;a rel=...</td>\n", " <td>1</td>\n", " </tr>\n", " <tr>\n", " <th>3</th>\n", " <td>z12wjzc4eprnvja4304cgbbizuved35wxcs</td>\n", " <td>Dakota Taylor</td>\n", " <td>2015-05-29T02:13:07.810000</td>\n", " <td>Cool</td>\n", " <td>0</td>\n", " </tr>\n", " <tr>\n", " <th>4</th>\n", " <td>z13xjfr42z3uxdz2223gx5rrzs3dt5hna</td>\n", " <td>Jihad Naser</td>\n", " <td>NaN</td>\n", " <td>Hello I&amp;#39;am from Palastine</td>\n", " <td>1</td>\n", " </tr>\n", " </tbody>\n", "</table>\n", "</div>" ], "text/plain": [ " COMMENT_ID AUTHOR \\\n", "0 z12rwfnyyrbsefonb232i5ehdxzkjzjs2 Lisa Wellas \n", "1 z130wpnwwnyuetxcn23xf5k5ynmkdpjrj04 jason graham \n", "2 z13vsfqirtavjvu0t22ezrgzyorwxhpf3 Ajkal Khan \n", "3 z12wjzc4eprnvja4304cgbbizuved35wxcs Dakota Taylor \n", "4 z13xjfr42z3uxdz2223gx5rrzs3dt5hna Jihad Naser \n", "\n", " DATE \\\n", "0 NaN \n", "1 2015-05-29T02:26:10.652000 \n", "2 NaN \n", "3 2015-05-29T02:13:07.810000 \n", "4 NaN \n", "\n", " CONTENT CLASS \n", "0 +447935454150 lovely girl talk to me xxx 1 \n", "1 I always end up coming back to this song<br /> 0 \n", "2 my sister just received over 6,500 new <a rel=... 1 \n", "3 Cool 0 \n", "4 Hello I&#39;am from Palastine 1 " ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "eminem = dd.read_csv('Youtube04-Eminem.csv')\n", "eminem.head()" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "data": { "text/html": [ "<div>\n", "<style scoped>\n", " .dataframe tbody tr th:only-of-type {\n", " vertical-align: middle;\n", " }\n", "\n", " .dataframe tbody tr th {\n", " vertical-align: top;\n", " }\n", "\n", " .dataframe thead th {\n", " text-align: right;\n", " }\n", "</style>\n", "<table border=\"1\" class=\"dataframe\">\n", " <thead>\n", " <tr style=\"text-align: right;\">\n", " <th></th>\n", " <th>COMMENT_ID</th>\n", " <th>AUTHOR</th>\n", " <th>DATE</th>\n", " <th>CONTENT</th>\n", " <th>CLASS</th>\n", " </tr>\n", " </thead>\n", " <tbody>\n", " <tr>\n", " <th>0</th>\n", " <td>z13lgffb5w3ddx1ul22qy1wxspy5cpkz504</td>\n", " <td>dharma pal</td>\n", " <td>2015-05-29T02:30:18.971000</td>\n", " <td>Nice song</td>\n", " <td>0</td>\n", " </tr>\n", " <tr>\n", " <th>1</th>\n", " <td>z123dbgb0mqjfxbtz22ucjc5jvzcv3ykj</td>\n", " <td>Tiza Arellano</td>\n", " <td>2015-05-29T00:14:48.748000</td>\n", " <td>I love song </td>\n", " <td>0</td>\n", " </tr>\n", " <tr>\n", " <th>2</th>\n", " <td>z12quxxp2vutflkxv04cihggzt2azl34pms0k</td>\n", " <td>Prìñçeśś Âliś Łøvê Dømíñø Mâđiś™ </td>\n", " <td>2015-05-28T21:00:08.607000</td>\n", " <td>I love song </td>\n", " <td>0</td>\n", " </tr>\n", " <tr>\n", " <th>3</th>\n", " <td>z12icv3ysqvlwth2c23eddlykyqut5z1h</td>\n", " <td>Eric Gonzalez</td>\n", " <td>2015-05-28T20:47:12.193000</td>\n", " <td>860,000,000 lets make it first female to reach...</td>\n", " <td>0</td>\n", " </tr>\n", " <tr>\n", " <th>4</th>\n", " <td>z133stly3kete3tly22petvwdpmghrlli</td>\n", " <td>Analena López</td>\n", " <td>2015-05-28T17:08:29.827000</td>\n", " <td>shakira is best for worldcup</td>\n", " <td>0</td>\n", " </tr>\n", " </tbody>\n", "</table>\n", "</div>" ], "text/plain": [ " COMMENT_ID AUTHOR \\\n", "0 z13lgffb5w3ddx1ul22qy1wxspy5cpkz504 dharma pal \n", "1 z123dbgb0mqjfxbtz22ucjc5jvzcv3ykj Tiza Arellano \n", "2 z12quxxp2vutflkxv04cihggzt2azl34pms0k Prìñçeśś Âliś Łøvê Dømíñø Mâđiś™  \n", "3 z12icv3ysqvlwth2c23eddlykyqut5z1h Eric Gonzalez \n", "4 z133stly3kete3tly22petvwdpmghrlli Analena López \n", "\n", " DATE \\\n", "0 2015-05-29T02:30:18.971000 \n", "1 2015-05-29T00:14:48.748000 \n", "2 2015-05-28T21:00:08.607000 \n", "3 2015-05-28T20:47:12.193000 \n", "4 2015-05-28T17:08:29.827000 \n", "\n", " CONTENT CLASS \n", "0 Nice song 0 \n", "1 I love song  0 \n", "2 I love song  0 \n", "3 860,000,000 lets make it first female to reach... 0 \n", "4 shakira is best for worldcup 0 " ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "shakira = dd.read_csv('Youtube05-Shakira.csv')\n", "shakira.head()" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "data": { "text/html": [ "<div>\n", "<style scoped>\n", " .dataframe tbody tr th:only-of-type {\n", " vertical-align: middle;\n", " }\n", "\n", " .dataframe tbody tr th {\n", " vertical-align: top;\n", " }\n", "\n", " .dataframe thead th {\n", " text-align: right;\n", " }\n", "</style>\n", "<table border=\"1\" class=\"dataframe\">\n", " <thead>\n", " <tr style=\"text-align: right;\">\n", " <th></th>\n", " <th>COMMENT_ID</th>\n", " <th>AUTHOR</th>\n", " <th>DATE</th>\n", " <th>CONTENT</th>\n", " <th>CLASS</th>\n", " </tr>\n", " </thead>\n", " <tbody>\n", " <tr>\n", " <th>0</th>\n", " <td>LZQPQhLyRh80UYxNuaDWhIGQYNQ96IuCg-AYWqNPjpU</td>\n", " <td>Julius NM</td>\n", " <td>2013-11-07T06:20:48</td>\n", " <td>Huh, anyway check out this you[tube] channel: ...</td>\n", " <td>1</td>\n", " </tr>\n", " <tr>\n", " <th>1</th>\n", " <td>LZQPQhLyRh_C2cTtd9MvFRJedxydaVW-2sNg5Diuo4A</td>\n", " <td>adam riyati</td>\n", " <td>2013-11-07T12:37:15</td>\n", " <td>Hey guys check out my new channel and our firs...</td>\n", " <td>1</td>\n", " </tr>\n", " <tr>\n", " <th>2</th>\n", " <td>LZQPQhLyRh9MSZYnf8djyk0gEF9BHDPYrrK-qCczIY8</td>\n", " <td>Evgeny Murashkin</td>\n", " <td>2013-11-08T17:34:21</td>\n", " <td>just for test I have to say murdev.com</td>\n", " <td>1</td>\n", " </tr>\n", " <tr>\n", " <th>3</th>\n", " <td>z13jhp0bxqncu512g22wvzkasxmvvzjaz04</td>\n", " <td>ElNino Melendez</td>\n", " <td>2013-11-09T08:28:43</td>\n", " <td>me shaking my sexy ass on my channel enjoy ^_^ </td>\n", " <td>1</td>\n", " </tr>\n", " <tr>\n", " <th>4</th>\n", " <td>z13fwbwp1oujthgqj04chlngpvzmtt3r3dw</td>\n", " <td>GsMega</td>\n", " <td>2013-11-10T16:05:38</td>\n", " <td>watch?v=vtaRGgvGtWQ Check this out .</td>\n", " <td>1</td>\n", " </tr>\n", " </tbody>\n", "</table>\n", "</div>" ], "text/plain": [ " COMMENT_ID AUTHOR \\\n", "0 LZQPQhLyRh80UYxNuaDWhIGQYNQ96IuCg-AYWqNPjpU Julius NM \n", "1 LZQPQhLyRh_C2cTtd9MvFRJedxydaVW-2sNg5Diuo4A adam riyati \n", "2 LZQPQhLyRh9MSZYnf8djyk0gEF9BHDPYrrK-qCczIY8 Evgeny Murashkin \n", "3 z13jhp0bxqncu512g22wvzkasxmvvzjaz04 ElNino Melendez \n", "4 z13fwbwp1oujthgqj04chlngpvzmtt3r3dw GsMega \n", "\n", " DATE CONTENT \\\n", "0 2013-11-07T06:20:48 Huh, anyway check out this you[tube] channel: ... \n", "1 2013-11-07T12:37:15 Hey guys check out my new channel and our firs... \n", "2 2013-11-08T17:34:21 just for test I have to say murdev.com \n", "3 2013-11-09T08:28:43 me shaking my sexy ass on my channel enjoy ^_^  \n", "4 2013-11-10T16:05:38 watch?v=vtaRGgvGtWQ Check this out . \n", "\n", " CLASS \n", "0 1 \n", "1 1 \n", "2 1 \n", "3 1 \n", "4 1 " ] }, "execution_count": 32, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df = dd.concat([psy, katyperry, lmfao, eminem, shakira])\n", "df.head()" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "data": { "text/html": [ "<div>\n", "<style scoped>\n", " .dataframe tbody tr th:only-of-type {\n", " vertical-align: middle;\n", " }\n", "\n", " .dataframe tbody tr th {\n", " vertical-align: top;\n", " }\n", "\n", " .dataframe thead th {\n", " text-align: right;\n", " }\n", "</style>\n", "<table border=\"1\" class=\"dataframe\">\n", " <thead>\n", " <tr style=\"text-align: right;\">\n", " <th></th>\n", " <th>CLASS</th>\n", " <th>0</th>\n", " </tr>\n", " </thead>\n", " <tbody>\n", " <tr>\n", " <th>count</th>\n", " <td>1956.000000</td>\n", " <td>NaN</td>\n", " </tr>\n", " <tr>\n", " <th>mean</th>\n", " <td>0.513804</td>\n", " <td>NaN</td>\n", " </tr>\n", " <tr>\n", " <th>std</th>\n", " <td>0.499937</td>\n", " <td>NaN</td>\n", " </tr>\n", " <tr>\n", " <th>min</th>\n", " <td>0.000000</td>\n", " <td>NaN</td>\n", " </tr>\n", " <tr>\n", " <th>25%</th>\n", " <td>NaN</td>\n", " <td>0.0</td>\n", " </tr>\n", " <tr>\n", " <th>50%</th>\n", " <td>NaN</td>\n", " <td>1.0</td>\n", " </tr>\n", " <tr>\n", " <th>75%</th>\n", " <td>NaN</td>\n", " <td>1.0</td>\n", " </tr>\n", " <tr>\n", " <th>max</th>\n", " <td>1.000000</td>\n", " <td>NaN</td>\n", " </tr>\n", " </tbody>\n", "</table>\n", "</div>" ], "text/plain": [ " CLASS 0\n", "count 1956.000000 NaN\n", "mean 0.513804 NaN\n", "std 0.499937 NaN\n", "min 0.000000 NaN\n", "25% NaN 0.0\n", "50% NaN 1.0\n", "75% NaN 1.0\n", "max 1.000000 NaN" ] }, "execution_count": 33, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df.describe().compute()" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "5" ] }, "execution_count": 34, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len(df.columns)" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "COMMENT_ID 1005\n", "AUTHOR 1005\n", "DATE 760\n", "CONTENT 1005\n", "CLASS 1005\n", "dtype: int64" ] }, "execution_count": 35, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Count of Spam:\n", "df[df['CLASS'] == 1].count().compute()" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "COMMENT_ID 951\n", "AUTHOR 951\n", "DATE 951\n", "CONTENT 951\n", "CLASS 951\n", "dtype: int64" ] }, "execution_count": 36, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Count of non-Spam\n", "df[df['CLASS'] == 0].count().compute()" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [ { "data": { "text/html": [ "<div>\n", "<style scoped>\n", " .dataframe tbody tr th:only-of-type {\n", " vertical-align: middle;\n", " }\n", "\n", " .dataframe tbody tr th {\n", " vertical-align: top;\n", " }\n", "\n", " .dataframe thead th {\n", " text-align: right;\n", " }\n", "</style>\n", "<table border=\"1\" class=\"dataframe\">\n", " <thead>\n", " <tr style=\"text-align: right;\">\n", " <th></th>\n", " <th>COMMENT_ID</th>\n", " <th>AUTHOR</th>\n", " <th>DATE</th>\n", " <th>CONTENT</th>\n", " <th>CLASS</th>\n", " </tr>\n", " </thead>\n", " <tbody>\n", " <tr>\n", " <th>0</th>\n", " <td>LZQPQhLyRh80UYxNuaDWhIGQYNQ96IuCg-AYWqNPjpU</td>\n", " <td>Julius NM</td>\n", " <td>2013-11-07T06:20:48</td>\n", " <td>Huh, anyway check out this you[tube] channel: ...</td>\n", " <td>1</td>\n", " </tr>\n", " <tr>\n", " <th>1</th>\n", " <td>LZQPQhLyRh_C2cTtd9MvFRJedxydaVW-2sNg5Diuo4A</td>\n", " <td>adam riyati</td>\n", " <td>2013-11-07T12:37:15</td>\n", " <td>Hey guys check out my new channel and our firs...</td>\n", " <td>1</td>\n", " </tr>\n", " <tr>\n", " <th>2</th>\n", " <td>LZQPQhLyRh9MSZYnf8djyk0gEF9BHDPYrrK-qCczIY8</td>\n", " <td>Evgeny Murashkin</td>\n", " <td>2013-11-08T17:34:21</td>\n", " <td>just for test I have to say murdev.com</td>\n", " <td>1</td>\n", " </tr>\n", " <tr>\n", " <th>3</th>\n", " <td>z13jhp0bxqncu512g22wvzkasxmvvzjaz04</td>\n", " <td>ElNino Melendez</td>\n", " <td>2013-11-09T08:28:43</td>\n", " <td>me shaking my sexy ass on my channel enjoy ^_^ </td>\n", " <td>1</td>\n", " </tr>\n", " <tr>\n", " <th>4</th>\n", " <td>z13fwbwp1oujthgqj04chlngpvzmtt3r3dw</td>\n", " <td>GsMega</td>\n", " <td>2013-11-10T16:05:38</td>\n", " <td>watch?v=vtaRGgvGtWQ Check this out .</td>\n", " <td>1</td>\n", " </tr>\n", " </tbody>\n", "</table>\n", "</div>" ], "text/plain": [ " COMMENT_ID AUTHOR \\\n", "0 LZQPQhLyRh80UYxNuaDWhIGQYNQ96IuCg-AYWqNPjpU Julius NM \n", "1 LZQPQhLyRh_C2cTtd9MvFRJedxydaVW-2sNg5Diuo4A adam riyati \n", "2 LZQPQhLyRh9MSZYnf8djyk0gEF9BHDPYrrK-qCczIY8 Evgeny Murashkin \n", "3 z13jhp0bxqncu512g22wvzkasxmvvzjaz04 ElNino Melendez \n", "4 z13fwbwp1oujthgqj04chlngpvzmtt3r3dw GsMega \n", "\n", " DATE CONTENT \\\n", "0 2013-11-07T06:20:48 Huh, anyway check out this you[tube] channel: ... \n", "1 2013-11-07T12:37:15 Hey guys check out my new channel and our firs... \n", "2 2013-11-08T17:34:21 just for test I have to say murdev.com \n", "3 2013-11-09T08:28:43 me shaking my sexy ass on my channel enjoy ^_^  \n", "4 2013-11-10T16:05:38 watch?v=vtaRGgvGtWQ Check this out . \n", "\n", " CLASS \n", "0 1 \n", "1 1 \n", "2 1 \n", "3 1 \n", "4 1 " ] }, "execution_count": 37, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df.head()" ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0 huh, anyway check out this you[tube] channel: ...\n", "1 hey guys check out my new channel and our firs...\n", "2 just for test i have to say murdev.com\n", "3 me shaking my sexy ass on my channel enjoy ^_^ \n", "4 watch?v=vtarggvgtwq check this out .\n", "Name: content_lower, dtype: object" ] }, "execution_count": 38, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df['content_lower'] = df['CONTENT'].str.lower()\n", "df['content_lower'].head()" ] }, { "cell_type": "code", "execution_count": 43, "metadata": {}, "outputs": [ { "data": { "text/html": [ "<div>\n", "<style scoped>\n", " .dataframe tbody tr th:only-of-type {\n", " vertical-align: middle;\n", " }\n", "\n", " .dataframe tbody tr th {\n", " vertical-align: top;\n", " }\n", "\n", " .dataframe thead th {\n", " text-align: right;\n", " }\n", "</style>\n", "<table border=\"1\" class=\"dataframe\">\n", " <thead>\n", " <tr style=\"text-align: right;\">\n", " <th></th>\n", " <th>COMMENT_ID</th>\n", " <th>AUTHOR</th>\n", " <th>DATE</th>\n", " <th>CONTENT</th>\n", " <th>CLASS</th>\n", " <th>content_lower</th>\n", " </tr>\n", " </thead>\n", " <tbody>\n", " <tr>\n", " <th>0</th>\n", " <td>LZQPQhLyRh80UYxNuaDWhIGQYNQ96IuCg-AYWqNPjpU</td>\n", " <td>Julius NM</td>\n", " <td>2013-11-07T06:20:48</td>\n", " <td>Huh, anyway check out this you[tube] channel: ...</td>\n", " <td>1</td>\n", " <td>huh, anyway check out this you[tube] channel: ...</td>\n", " </tr>\n", " <tr>\n", " <th>1</th>\n", " <td>LZQPQhLyRh_C2cTtd9MvFRJedxydaVW-2sNg5Diuo4A</td>\n", " <td>adam riyati</td>\n", " <td>2013-11-07T12:37:15</td>\n", " <td>Hey guys check out my new channel and our firs...</td>\n", " <td>1</td>\n", " <td>hey guys check out my new channel and our firs...</td>\n", " </tr>\n", " <tr>\n", " <th>2</th>\n", " <td>LZQPQhLyRh9MSZYnf8djyk0gEF9BHDPYrrK-qCczIY8</td>\n", " <td>Evgeny Murashkin</td>\n", " <td>2013-11-08T17:34:21</td>\n", " <td>just for test I have to say murdev.com</td>\n", " <td>1</td>\n", " <td>just for test i have to say murdev.com</td>\n", " </tr>\n", " <tr>\n", " <th>3</th>\n", " <td>z13jhp0bxqncu512g22wvzkasxmvvzjaz04</td>\n", " <td>ElNino Melendez</td>\n", " <td>2013-11-09T08:28:43</td>\n", " <td>me shaking my sexy ass on my channel enjoy ^_^ </td>\n", " <td>1</td>\n", " <td>me shaking my sexy ass on my channel enjoy ^_^ </td>\n", " </tr>\n", " <tr>\n", " <th>4</th>\n", " <td>z13fwbwp1oujthgqj04chlngpvzmtt3r3dw</td>\n", " <td>GsMega</td>\n", " <td>2013-11-10T16:05:38</td>\n", " <td>watch?v=vtaRGgvGtWQ Check this out .</td>\n", " <td>1</td>\n", " <td>watch?v=vtarggvgtwq check this out .</td>\n", " </tr>\n", " </tbody>\n", "</table>\n", "</div>" ], "text/plain": [ " COMMENT_ID AUTHOR \\\n", "0 LZQPQhLyRh80UYxNuaDWhIGQYNQ96IuCg-AYWqNPjpU Julius NM \n", "1 LZQPQhLyRh_C2cTtd9MvFRJedxydaVW-2sNg5Diuo4A adam riyati \n", "2 LZQPQhLyRh9MSZYnf8djyk0gEF9BHDPYrrK-qCczIY8 Evgeny Murashkin \n", "3 z13jhp0bxqncu512g22wvzkasxmvvzjaz04 ElNino Melendez \n", "4 z13fwbwp1oujthgqj04chlngpvzmtt3r3dw GsMega \n", "\n", " DATE CONTENT \\\n", "0 2013-11-07T06:20:48 Huh, anyway check out this you[tube] channel: ... \n", "1 2013-11-07T12:37:15 Hey guys check out my new channel and our firs... \n", "2 2013-11-08T17:34:21 just for test I have to say murdev.com \n", "3 2013-11-09T08:28:43 me shaking my sexy ass on my channel enjoy ^_^  \n", "4 2013-11-10T16:05:38 watch?v=vtaRGgvGtWQ Check this out . \n", "\n", " CLASS content_lower \n", "0 1 huh, anyway check out this you[tube] channel: ... \n", "1 1 hey guys check out my new channel and our firs... \n", "2 1 just for test i have to say murdev.com \n", "3 1 me shaking my sexy ass on my channel enjoy ^_^  \n", "4 1 watch?v=vtarggvgtwq check this out . " ] }, "execution_count": 43, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df.head()" ] }, { "cell_type": "code", "execution_count": 46, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False 1476\n", "True 480\n", "Name: content_lower, dtype: int64" ] }, "execution_count": 46, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df['content_lower'].str.contains('check', regex=False).value_counts().compute()" ] }, { "cell_type": "code", "execution_count": 48, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "COMMENT_ID 461\n", "AUTHOR 461\n", "DATE 294\n", "CONTENT 461\n", "CLASS 461\n", "content_lower 461\n", "dtype: int64" ] }, "execution_count": 48, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Number of spam that contains the word 'check':\n", "\n", "df[(df['content_lower'].str.contains('check', regex=False)) & (df['CLASS'] == 1)].count().compute()" ] }, { "cell_type": "code", "execution_count": 50, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "COMMENT_ID 19\n", "AUTHOR 19\n", "DATE 19\n", "CONTENT 19\n", "CLASS 19\n", "content_lower 19\n", "dtype: int64" ] }, "execution_count": 50, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Number of non-Spam that contains the word 'check':\n", "\n", "df[(df['content_lower'].str.contains('check', regex=False)) & (df['CLASS'] == 0)].count().compute()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Options for Scaling Up with Data:\n", "\n", "I definitely prefer Dask just because it's almost like pure pandas which is like pure python. Also in certain instances Dask has shown to perform better than technology like Spark. The huge advantage with Dask is you can run it locally on your own machine intead of renting out clusters on the cloud because Dask can utilize the cores on your machine as if they were clusters.\n", "\n", "If I really needed to scale out due to the size of the data, I'd go with Databricks Apache Spark just because it's less pain than AWS. And Apache Spark using Scala is nice because you can use either Scala DataFrames syntax or Spark SQL syntax, but both have have the same underlying physical plan and representation." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "conda_python3", "language": "python", "name": "conda_python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.5" } }, "nbformat": 4, "nbformat_minor": 2 }
29,082
https://github.com/ielm/gobo/blob/master/client/webpack/webpackConfigProd.js
Github Open Source
Open Source
MIT
2,021
gobo
ielm
JavaScript
Code
279
1,032
const { resolve } = require('path'); const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); // const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin'); const extractSass = new ExtractTextPlugin({ filename: '[name].[contenthash].css', allChunks: true, }); module.exports = { entry: { main: resolve(__dirname, '../app'), vendor: [ 'react', 'react-code-splitting', 'react-dom', 'react-helmet', 'react-redux', 'react-router-dom', 'redux', 'redux-thunk', ], }, resolve: { modules: [resolve(__dirname, '../app'), 'node_modules'], }, devtool: '#source-map', output: { filename: '[name].[chunkhash].js', path: resolve(__dirname, '../dist'), publicPath: '/', }, module: { rules: [ { test: /\.(js|jsx)$/, include: [resolve(__dirname, '../app')], use: 'babel-loader', }, { test: /\.(scss|css)$/, use: extractSass.extract({ use: [ { loader: 'css-loader', options: { minimize: true } }, { loader: 'sass-loader' }, ], }), }, { test: /\.(woff|woff2)$/, use: { loader: 'url-loader', options: { name: 'fonts/[hash].[ext]', limit: 5000, mimetype: 'application/font-woff', }, }, }, { test: /\.(ttf|eot|svg)$/, use: { loader: 'file-loader', options: { name: 'fonts/[hash].[ext]', }, }, }, ], }, plugins: [ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('production'), }, }), extractSass, new webpack.optimize.UglifyJsPlugin({ compressor: { warnings: false, screw_ie8: true, unused: true, dead_code: true, }, sourceMap: true, }), new webpack.optimize.CommonsChunkPlugin({ names: ['vendor', 'manifest'], }), new HtmlWebpackPlugin({ filename: 'index.html', title: 'Gobo', template: 'webpack/template.html', }), // new SWPrecacheWebpackPlugin({ // cacheId: 'Gobo', // filename: 'service-worker.js', // This name is referenced in manageServiceWorker.js // maximumFileSizeToCacheInBytes: 4194304, // minify: true, // navigateFallback: '/index.html', // staticFileGlobs: [ // 'static/**.*', // 'static/images/**.*', // ], // stripPrefix: 'static/', // mergeStaticsConfig: true, // Merge webpacks static outputs with the globs described above. // // runtimeCaching: [{ // // urlPattern: /^https:\/\/api\.github\.com\//, // // handler: 'fastest', // // networkTimeoutSeconds: 5000, // // options: { // // cache: { // // maxEntries: 10, // // name: 'github-api-cache' // // } // // } // // }] // }), ], };
36,744
https://github.com/bibleexchange/bibleexchange-production/blob/master/config/bible.php
Github Open Source
Open Source
MIT
null
bibleexchange-production
bibleexchange
PHP
Code
13
98
<?php return array( 'default_verse' => 'John 3:16', 'DB_HOST'=> env('SCRIPTURE_DB_HOST'), 'DB_USER_NAME'=>env('SCRIPTURE_DB_USER'), 'DB_PASSWORD'=>env('SCRIPTURE_DB_PASSWORD'), 'DATABASE_NAME'=>env('SCRIPTURE_DB_NAME') );
46,859
https://github.com/blobtoolkit/insdc-pipeline/blob/master/v1/scripts/make_taxid_list.py
Github Open Source
Open Source
MIT
2,020
insdc-pipeline
blobtoolkit
Python
Code
245
725
#!/usr/bin/env python3 import os import re from collections import defaultdict # set variables from snakemake params, wildcards, input and threads DBTITLE = snakemake.params.db ROOT = int(snakemake.wildcards.root) MASKS = set(snakemake.params.mask_ids + [32630, 111789, 6]) # mask synthetic constructs by default NODES = "%s/nodes.dmp" % snakemake.params.taxdump def node_graph(nodes_file): """ Read an NCBI nodes.dmp file and return a dict of child taxids and ranks for each taxid with descendants. """ graph = defaultdict(dict) if os.path.isfile(nodes_file): with open(nodes_file, 'r') as fh: lines = fh.readlines() for l in lines: parts = re.split(r'\t\|\t', l) tax_id = int(parts[0]) parent_id = int(parts[1]) rank = parts[2] if parent_id == tax_id: continue graph[parent_id].update({tax_id: rank}) return graph def graph_to_masked_taxids(graph, root, masks): """ Generate a set containing masked taxids from a root. """ taxids = set() def descend(root): """ Iteratively descend from a root to generate a set of taxids unless the child taxid is in the list of taxids to mask. """ if root in graph: for child, rank in graph[root].items(): if masks and int(child) in masks: continue taxids.add(child) descend(child) descend(root) return taxids def main(): masks = MASKS graph = node_graph(NODES) taxids = graph_to_masked_taxids(graph, ROOT, masks) listfile = "%s.taxids" % DBTITLE with open(listfile, 'w') as fh: fh.write("\n".join(str(taxid) for taxid in taxids)) negative_ids = MASKS if ROOT != 1: negative_ids = negative_ids | graph_to_masked_taxids(graph, 1, set([ROOT])) for mask_id in masks: negative_ids = negative_ids | graph_to_masked_taxids(graph, mask_id, set()) negative_listfile = "%s.negative.taxids" % DBTITLE with open(negative_listfile, 'w') as fh: fh.write("\n".join(str(taxid) for taxid in negative_ids)) if __name__ == '__main__': main()
35,258
https://github.com/fes300/DefinitelyTyped/blob/master/types/material__list/adapter.d.ts
Github Open Source
Open Source
MIT
2,021
DefinitelyTyped
fes300
TypeScript
Code
177
424
export class MDCListAdapter { getListItemCount(): number; getFocusedElementIndex(): number; setAttributeForElementIndex(index: number, attribute: string, value: string): void; removeAttributeForElementIndex(index: number, attribute: string): void; addClassForElementIndex(index: number, className: string): void; removeClassForElementIndex(index: number, className: string): void; /** * Focuses list item at the index specified. */ focusItemAtIndex(index: number): void; /** * Sets the tabindex to the value specified for all button/a element children of * the list item at the index specified. */ setTabIndexForListItemChildren(listItemIndex: number, tabIndexValue: number): void; /** * If the given element has an href, follows the link. */ followHref(ele: HTMLAnchorElement): void; /** * Returns true if radio button is present at given list item index. */ hasRadioAtIndex(index: number): boolean; /** * Returns true if checkbox is present at given list item index. */ hasCheckboxAtIndex(index: number): boolean; /** * Returns true if checkbox inside a list item is checked. */ isCheckboxCheckedAtIndex(index: number): boolean; /** * Sets the checked status of checkbox or radio at given list item index. */ setCheckedCheckboxOrRadioAtIndex(index: number, isChecked: boolean): void; /** * Returns true when the current focused element is inside list root. */ isFocusInsideList(): boolean; }
16,319
https://github.com/aalihusni/LebahFramework/blob/master/JavaSource/lebah/util/CalendarList.java
Github Open Source
Open Source
Apache-2.0
2,018
LebahFramework
aalihusni
Java
Code
173
485
/* ************************************************************************ LEBAH PORTAL FRAMEWORK, http://lebah.sf.net Copyright (C) 2007 Shamsul Bahrin MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ************************************************************************ */ package lebah.util; import java.util.Calendar; import java.util.Vector; /** * @author Shaiful Nizam Tajul * @version 1.01 */ public class CalendarList { Calendar cal = Calendar.getInstance(); public CalendarList() { } public Vector getDates() { Vector list = new Vector(); for (int i = 1; i < 32; i++) { list.addElement(new Integer(i)); } return list; } public Vector getMonths() { Vector list = new Vector(); list.addElement("January"); list.addElement("February"); list.addElement("March"); list.addElement("April"); list.addElement("May"); list.addElement("June"); list.addElement("July"); list.addElement("August"); list.addElement("September"); list.addElement("October"); list.addElement("November"); list.addElement("December"); return list; } public Vector getYears() { Vector list = new Vector(); int year = cal.get(Calendar.YEAR); for (int i = year; i < (year + 3); i++) { list.addElement(new Integer(i)); } return list; } }
34,676
https://github.com/simple0x47/IdNet6/blob/master/src/IdNet6/src/Events/UserLogoutSuccessEvent.cs
Github Open Source
Open Source
Apache-2.0
2,022
IdNet6
simple0x47
C#
Code
148
356
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. namespace IdNet6.Events { /// <summary> /// Event for successful user logout /// </summary> /// <seealso cref="IdNet6.Events.Event" /> public class UserLogoutSuccessEvent : Event { /// <summary> /// Initializes a new instance of the <see cref="UserLogoutSuccessEvent"/> class. /// </summary> /// <param name="subjectId">The subject identifier.</param> /// <param name="name">The name.</param> public UserLogoutSuccessEvent(string subjectId, string name) : base(EventCategories.Authentication, "User Logout Success", EventTypes.Success, EventIds.UserLogoutSuccess) { SubjectId = subjectId; DisplayName = name; } /// <summary> /// Gets or sets the subject identifier. /// </summary> /// <value> /// The subject identifier. /// </value> public string SubjectId { get; set; } /// <summary> /// Gets or sets the display name. /// </summary> /// <value> /// The display name. /// </value> public string DisplayName { get; set; } } }
24,074
https://github.com/OSSome01/ekalavya/blob/master/sub1.py
Github Open Source
Open Source
MIT
2,021
ekalavya
OSSome01
Python
Code
90
224
#!/usr/bin/env python import rospy from std_msgs.msg import String def callback(msg): #rospy.loginfo(rospy.get_caller_id() + "I heard %s", data.data) print(msg.data) def listener(): # In ROS, nodes are uniquely named. If two nodes with the same # name are launched, the previous one is kicked off. The # anonymous=True flag means that rospy will choose a unique # name for our 'listener' node so that multiple listeners can # run simultaneously. rospy.init_node('listen', anonymous=True) rospy.Subscriber("/camera/depth/points", String, callback) # spin() simply keeps python from exiting until this node is stopped rospy.spin() if __name__ == '__main__': listener()
31,716
https://github.com/bwp/SeleniumWebDriver/blob/master/third_party/gecko-16/win32/include/nsIGridPart.h
Github Open Source
Open Source
Apache-2.0
2,018
SeleniumWebDriver
bwp
C
Code
483
1,195
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef nsIGridPart_h___ #define nsIGridPart_h___ #include "nsISupports.h" #include "nsFrame.h" class nsGridRowGroupLayout; class nsGrid; class nsGridRowLayout; class nsGridRow; class nsGridLayout2; // 07373ed7-e947-4a5e-b36c-69f7c195677b #define NS_IGRIDPART_IID \ { 0x07373ed7, 0xe947, 0x4a5e, \ { 0xb3, 0x6c, 0x69, 0xf7, 0xc1, 0x95, 0x67, 0x7b } } /** * An additional interface implemented by nsBoxLayout implementations * for parts of a grid (excluding cells, which are not special). */ class nsIGridPart : public nsISupports { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_IGRIDPART_IID) virtual nsGridRowGroupLayout* CastToRowGroupLayout()=0; virtual nsGridLayout2* CastToGridLayout()=0; /** * @param aBox [IN] The other half of the |this| parameter, i.e., the box * whose layout manager is |this|. * @param aIndex [INOUT] For callers not setting aRequestor, the value * pointed to by aIndex is incremented by the index * of the row (aBox) within its row group; if aBox * is not a row/column, it is untouched. * The implementation does this by doing the aIndex * incrementing in the call to the parent row group * when aRequestor is non-null. * @param aRequestor [IN] Non-null if and only if this is a recursive * call from the GetGrid method on a child grid part, * in which case it is a pointer to that grid part. * (This may only be non-null for row groups and * grids.) * @return The grid of which aBox (a row, row group, or grid) is a part. */ virtual nsGrid* GetGrid(nsIBox* aBox, PRInt32* aIndex, nsGridRowLayout* aRequestor=nsnull)=0; /** * @param aBox [IN] The other half of the |this| parameter, i.e., the box * whose layout manager is |this|. * @param aParentBox [OUT] The box representing the next level up in * the grid (i.e., row group for a row, grid for a * row group). * @returns The layout manager for aParentBox. */ virtual nsIGridPart* GetParentGridPart(nsIBox* aBox, nsIBox** aParentBox) = 0; /** * @param aBox [IN] The other half of the |this| parameter, i.e., the box * whose layout manager is |this|. * @param aRowCount [INOUT] Row count * @param aComputedColumnCount [INOUT] Column count */ virtual void CountRowsColumns(nsIBox* aBox, PRInt32& aRowCount, PRInt32& aComputedColumnCount)=0; virtual void DirtyRows(nsIBox* aBox, nsBoxLayoutState& aState)=0; virtual PRInt32 BuildRows(nsIBox* aBox, nsGridRow* aRows)=0; virtual nsMargin GetTotalMargin(nsIBox* aBox, bool aIsHorizontal)=0; virtual PRInt32 GetRowCount() { return 1; } /** * Return the level of the grid hierarchy this grid part represents. */ enum Type { eGrid, eRowGroup, eRowLeaf }; virtual Type GetType()=0; /** * Return whether this grid part is an appropriate parent for the argument. */ bool CanContain(nsIGridPart* aPossibleChild) { Type thisType = GetType(), childType = aPossibleChild->GetType(); return thisType + 1 == childType || (thisType == eRowGroup && childType == eRowGroup); } }; NS_DEFINE_STATIC_IID_ACCESSOR(nsIGridPart, NS_IGRIDPART_IID) #endif
29,784
https://github.com/Intemporel/WoWDatabaseEditor/blob/master/WDE.MapRenderer/data/wireframe.frag
Github Open Source
Open Source
MIT
2,022
WoWDatabaseEditor
Intemporel
GLSL
Code
55
178
#version 330 core #include "../internalShaders/theengine.cginc" in vec2 Barys; out vec4 FragColor; uniform vec4 Color; uniform float Width; void main() { vec3 barys = vec3(Barys.xy, 1 - Barys.x - Barys.y); vec3 deltas = fwidth(barys); barys = smoothstep(vec3(0), deltas * Width, barys); float minBary = min(barys.x, min(barys.y, barys.z)); if (minBary > 0.5) discard; FragColor = Color; }
12,102
https://github.com/BelousAI/JavaRush/blob/master/1.JavaSyntax/src/Test/Other/rmi/server/MyService.java
Github Open Source
Open Source
Apache-2.0
null
JavaRush
BelousAI
Java
Code
58
179
package Test.Other.rmi.server; import java.rmi.Naming; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; public class MyService extends UnicastRemoteObject implements MyRemote { public MyService() throws RemoteException {} @Override public String sayHello() throws RemoteException { return "Сервер говорит: 'Привет!'"; } public static void main(String[] args) { try { MyRemote service = new MyService(); Naming.rebind("Удаленный привет", service); } catch (Exception e) { e.printStackTrace(); } } }
5,524
https://github.com/stize/dotnet-templates/blob/master/stize.webapi/content/Stize.ApiTemplate.Api.TestHost/ToDoList/ToDoListCqrsTest.cs
Github Open Source
Open Source
Apache-2.0
null
dotnet-templates
stize
C#
Code
368
1,532
using System.Collections.Generic; using System.Net; using System.Net.Http.Json; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Stize.ApiTemplate.Api.Controllers; using Stize.ApiTemplate.Api.TestHost.Extensions; using Stize.ApiTemplate.Business.Models.ToDoList; using Stize.Domain.Model; using Stize.DotNet.Delta; using Stize.DotNet.Search.Model; using Stize.Testing.Xunit.AspNetCore.Mvc; using Stize.Testing.Xunit.AspNetCore.TestHost; using Xunit; using Xunit.Abstractions; namespace Stize.ApiTemplate.Api.TestHost.ToDoList { public class ToDoListCqrsTest : BaseTest { public ToDoListCqrsTest(WebApplicationFactory<Startup> fixture, ITestOutputHelper output) : base(fixture, output) { } [Fact] public async Task GetAsyncTest() { // Arrange var entity = await this.WithEntityInTheDatabaseAsync(new Domain.Entities.ToDoList() { Name = "Before" }); var request = this.Fixture .Server .CreateApiRequest<ToDoListCqrsController>(c => c.GetAsync(default)) .WithIdentity(Identities.Basic); // Act var response = await request.SendAsync(HttpMethods.Get); // Assert Assert.True(response.IsSuccessStatusCode); var result = await response.Content.ReadFromJsonAsync<IEnumerable<ToDoListModel>>(); Assert.NotNull(result); Assert.NotEmpty(result); Assert.Single(result); } [Fact] public async Task SearchAsyncTest() { // Arrange var entity = await this.WithEntityInTheDatabaseAsync(new Domain.Entities.ToDoList() { Name = "Before" }); var page = new PageDescriptorModel() { Skip = 0, Take = 5, Envelope = true }; var request = this.Fixture .Server .CreateApiRequest<ToDoListCqrsController>(c => c.SearchAsync(page, default)) .WithIdentity(Identities.Basic); // Act var response = await request.SendAsync(HttpMethods.Post); // Assert Assert.True(response.IsSuccessStatusCode); var result = await response.Content.ReadFromJsonAsync<EnvelopedModel<ToDoListModel>>(); Assert.NotNull(result); Assert.NotEmpty(result.Data); Assert.Single(result.Data); Assert.Equal(page.Skip, result.Skip); Assert.Equal(page.Take, result.Take); Assert.Equal(1, result.Total); } [Fact] public async Task PostAsyncTest() { // Arrange var createModel = new CreateToDoListModel() { Name = "Before" }; var request = this.Fixture .Server .CreateApiRequest<ToDoListCqrsController>(c => c.PostAsync(createModel, default)) .WithIdentity(Identities.Basic); // Act var response = await request.SendAsync(HttpMethods.Post); // Assert Assert.True(response.IsSuccessStatusCode); var result = await response.Content.ReadFromJsonAsync<ToDoListModel>(); Assert.NotNull(result); Assert.Equal(1, result.Id); } [Fact] public async Task PutAsyncTest() { // Arrange var entity = await this.WithEntityInTheDatabaseAsync(new Domain.Entities.ToDoList() { Name = "Before" }); var updateToDoListModel = new UpdateToDoListModel() { Id = entity.Id, Name = "After" }; var request = this.Fixture .Server .CreateApiRequest<ToDoListCqrsController>(c => c.PutAsync(entity.Id, updateToDoListModel, default)) .WithIdentity(Identities.Basic); // Act var response = await request.SendAsync(HttpMethods.Put); // Assert Assert.True(response.IsSuccessStatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode); } [Fact] public async Task PatchAsync() { // Arrange var entity = await this.WithEntityInTheDatabaseAsync(new Domain.Entities.ToDoList() { Name = "Before" }); const string name = "After"; var delta = new Delta<UpdateToDoListModel>(); delta.TrySetPropertyValue(nameof(UpdateToDoListModel.Id), entity.Id); delta.TrySetPropertyValue(nameof(UpdateToDoListModel.Name), name); var request = this.Fixture .Server .CreateApiRequest<ToDoListCqrsController>(c => c.PatchAsync(entity.Id, delta, default)) .WithIdentity(Identities.Basic); // Act var response = await request.SendAsync(HttpMethods.Patch); // Assert Assert.True(response.IsSuccessStatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode); } [Fact] public async Task DeleteAsync() { // Arrange var entity = await this.WithEntityInTheDatabaseAsync(new Domain.Entities.ToDoList() { Name = "Before" }); var request = this.Fixture .Server .CreateApiRequest<ToDoListCqrsController>(c => c.DeleteAsync(entity.Id, default)) .WithIdentity(Identities.Basic); // Act var response = await request.SendAsync(HttpMethods.Delete); // Assert Assert.True(response.IsSuccessStatusCode); } } }
46,041
https://github.com/angular-demos/mini-app/blob/master/src/app/Shared/Models/UserEntity.ts
Github Open Source
Open Source
MIT
null
mini-app
angular-demos
TypeScript
Code
33
99
import {PostEntity} from './PostEntity'; import {UserAddressEntity} from './UserAddressEntity'; import {UserCompanyEntity} from './UserCompanyEntity'; export interface UserEntity { id: number; name: string; username: string; email: string; address: UserAddressEntity; phone: string; website: string; company: UserCompanyEntity; }
828
https://github.com/csherwood-usgs/floc_proc/blob/master/load_non.m
Github Open Source
Open Source
CC0-1.0
2,016
floc_proc
csherwood-usgs
MATLAB
Code
130
592
% load_non.m - Load the inactive classes in runs > 66 snn = zeros( NNN, nz, nt); for n=1:NNN ncname = sprintf('sand_%02d',n) snn(n,:,:)=squeeze(ncread(url,ncname,[i j 1 1],[1 1 Inf Inf])); end snns = squeeze(sum(snn)); sumsnns = sum( snns.*dzw); % total conc figure(5); clf pcolorjw( s2d*tz, h+z_w, log10(snns+eps)) colorbar title('Non-depositing Sand log_{10} Total Concentration') % fraction-weighted ws wst = squeeze(sum(repmat(ws(NCS+1:NCS+NNN),1,nz,nt).*snn)./sum(snn)); figure(6); clf pcolorjw( s2d*tz, h+z_w, 1e3*wst) colorbar title('Non-depositing Sand Settling Velocity (mm/s)') % fraction-weighted size figure(7); clf fdiamt = squeeze(sum(repmat(fdiam(NCS+1:NCS+NNN),1,nz,nt).*snn)./sum(snn)); pcolorjw( s2d*tz, h+z_w, 1e6*fdiamt) colorbar title('Non-depositing Sand Diameter (\mum)') % acoustic response Dfv = fdiam(NCS+1:NCS+NNN); rhofv = rhos(NCS+1:NCS+NNN); vnn = zeros(nz,nt); for jj=1:nt for ii=1:nz mv = squeeze(snn(:,ii,jj)); vnn(ii,jj) = acoustics(Dfv(:),mv(:),rhofv(:),.2,3e6); end end figure(8) pcolorjw( s2d*tz, h+z_w, vnn) colorbar title('Non-depositing Acoustic Response') xlabel('Days') ylabel('Elevation (m)') xlim([0 32.8]) caxis([ 0 .3]) ylim([0 3])
39,369
https://github.com/assaf/necktie/blob/master/lib/necktie/services.rb
Github Open Source
Open Source
JSON, Ruby, MIT
2,010
necktie
assaf
Ruby
Code
241
556
module Necktie class Services # Enables service to run after boot and starts it. Same as: # update_rc.d <name> defaults # service <name> start def start(name) puts " ** Starting service #{name}" sh "update-rc.d #{name} defaults" sh "service #{name} start" end # Enables service to run after boot. def enable(name) system "update-rc.d #{name} defaults" or "cannot enable #{name}" end # Disables service and stops it. Same as: # service <name> stop # update_rc.d <name> remove def stop(name) puts " ** Stopping service #{name}" sh "service #{name} stop" sh "update-rc.d -f #{name} remove" end # Disables service from running after boot. def disable(name) sh "update-rc.d -f #{name} remove" end # Restart service. Same as: # service <name> restart def restart(name) puts " ** Restarting service #{name}" sh "service #{name} restart" end # Reload configuration. Same as: # service <name> reload def reload(name) sh "service #{name} reload" end # Checks if service is running. Returns true or false based on the outcome # of service <name> status, and nil if service doesn't have a status command. # (Note: Not all services report their running state, or do so reliably) def running?(name) status = File.read("|service #{name} status 2>&1") status[/is running/] ? true : status[/is not running/] ? false : status.empty? ? false : nil; end end end # Returns Necktie::Services object. Examples: # services.restart "nginx" # services.start "mysql" unless services.running?("mysql") # services.enable "memcached" # but don't start yet def services @services ||= Necktie::Services.new end
12,696
https://github.com/otwartezabytki/otwartezabytki/blob/master/db/migrate/20120614143230_add_approved_field_to_relic.rb
Github Open Source
Open Source
BSD-3-Clause
2,017
otwartezabytki
otwartezabytki
Ruby
Code
21
54
# -*- encoding : utf-8 -*- class AddApprovedFieldToRelic < ActiveRecord::Migration def change add_column :relics, :approved, :boolean, :default => false end end
13,855
https://github.com/greenelab/mpmp/blob/master/01_explore_data/nbconverted/purity_distribution.py
Github Open Source
Open Source
BSD-3-Clause
2,022
mpmp
greenelab
Python
Code
259
737
#!/usr/bin/env python # coding: utf-8 # ## Explore tumor purity data # In[1]: import os import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from sklearn.preprocessing import StandardScaler import mpmp.config as cfg import mpmp.utilities.data_utilities as du # In[2]: purity_df = pd.read_csv(cfg.tumor_purity_data, sep='\t', index_col=0) purity_df.head() # In[3]: # visualize distribution of tumor purity values sns.set({'figure.figsize': (8, 5)}) sns.histplot(purity_df, x='purity', element='step') plt.gca().axvline(x=purity_df.purity.median(), linestyle='--', color='red') plt.xlabel('Tumor purity') # The median tumor purity value seems to be a bit higher than 0.5 (this is probably due to filtering in some cancer types for high purity samples). # # This should be reasonable enough to start with for classification, although I don't think it's the best way to do predictive modeling of this data. Really, we should just do regression, but we could also explore other binarization methods, or binarizing by cancer type. # In[4]: # visualize distribution of tumor purity values, by cancer type sample_info_df = du.load_sample_info('expression') sample_info_df.head() # In[5]: purity_cancer_df = (purity_df[['purity']] .merge(sample_info_df, left_index=True, right_index=True) .drop(columns=['id_for_stratification']) ) purity_cancer_df.head() # In[6]: sns.set({'figure.figsize': (8, 5)}) g = sns.kdeplot(data=purity_cancer_df, x='purity', hue='cancer_type', legend=False) # TODO: figure out legend # g.fig.legend(labels=[], ncol=2) plt.gca().axvline(x=purity_df.purity.median(), linestyle='--', color='red') plt.xlabel('Tumor purity') # When we facet by cancer type, we can see that quite a few cancers have a peak closer to 0.8/0.9, probably due to filtering for high-purity samples. Others have many more low-purity samples (e.g. [pancreatic cancer](https://www.cancer.gov/about-nci/organization/ccg/research/structural-genomics/tcga/studied-cancers/pancreatic)), and some are roughly centered around 0.5. # # In the future, we could look further into these differences between cancer types, depending on the results of the prediction experiments.
34,164
https://github.com/VIAME/netharn/blob/master/netharn/initializers/_nx_ext/path_embedding.py
Github Open Source
Open Source
Apache-2.0
null
netharn
VIAME
Python
Code
391
1,581
import networkx as nx from .tree_embedding import maximum_common_ordered_tree_embedding def maximum_common_path_embedding(paths1, paths2, sep='/', impl='iter-alt2', mode='chr'): """ Finds the maximum path embedding common between two sets of paths Parameters ---------- paths1, paths2: List[str] a list of paths sep: str path separator character impl: str backend runtime to use mode: str backend representation to use Returns ------- :tuple corresponding lists subpaths1 and subpaths2 which are subsets of paths1 and path2 respectively Examples -------- >>> paths1 = [ >>> '/usr/bin/python', >>> '/usr/bin/python3.6.1', >>> '/usr/lib/python3.6/dist-packages/networkx', >>> '/usr/lib/python3.6/dist-packages/numpy', >>> '/usr/include/python3.6/Python.h', >>> ] >>> paths2 = [ >>> '/usr/local/bin/python', >>> '/usr/bin/python3.6.2', >>> '/usr/local/lib/python3.6/dist-packages/networkx', >>> '/usr/local/lib/python3.6/dist-packages/scipy', >>> '/usr/local/include/python3.6/Python.h', >>> ] >>> subpaths1, subpaths2 = maximum_common_path_embedding(paths1, paths2) >>> import pprint >>> print('subpaths1 = {}'.format(pprint.pformat(subpaths1))) >>> print('subpaths2 = {}'.format(pprint.pformat(subpaths2))) subpaths1 = ['/usr/bin/python', '/usr/include/python3.6/Python.h', '/usr/lib/python3.6/dist-packages/networkx'] subpaths2 = ['/usr/local/bin/python', '/usr/local/include/python3.6/Python.h', '/usr/local/lib/python3.6/dist-packages/networkx'] """ # the longest common balanced sequence problem def _affinity(node1, node2): score = 0 for t1, t2 in zip(node1[::-1], node2[::-1]): if t1 == t2: score += 1 else: break return score node_affinity = _affinity tree1 = paths_to_otree(paths1, sep=sep) tree2 = paths_to_otree(paths2, sep=sep) subtree1, subtree2 = maximum_common_ordered_tree_embedding( tree1, tree2, node_affinity=node_affinity, impl=impl, mode=mode) subpaths1 = [sep.join(node) for node in subtree1.nodes if subtree1.out_degree[node] == 0] subpaths2 = [sep.join(node) for node in subtree2.nodes if subtree2.out_degree[node] == 0] return subpaths1, subpaths2 def paths_to_otree(paths, sep='/'): """ Generates an ordered tree from a list of path strings Parameters ---------- paths: List[str] a list of paths sep : str path separation character. defaults to "/" Returns ------- nx.OrderedDiGraph Example ------- >>> from netharn.initializers._nx_ext.tree_embedding import forest_str >>> paths = [ >>> '/etc/ld.so.conf', >>> '/usr/bin/python3.6', >>> '/usr/include/python3.6/Python.h', >>> '/usr/lib/python3.6/config-3.6m-x86_64-linux-gnu/libpython3.6.so', >>> '/usr/local/bin/gnumake.h', >>> '/usr/local/etc', >>> '/usr/local/lib/python3.6/dist-packages/', >>> ] >>> otree = paths_to_otree(paths) >>> print(forest_str(otree)) └── / ├── usr │   ├── local │   │   ├── lib │   │   │   └── python3.6 │   │   │   └── dist-packages │   │   │   └── │   │   ├── etc │   │   └── bin │   │   └── gnumake.h │   ├── lib │   │   └── python3.6 │   │   └── config-3.6m-x86_64-linux-gnu │   │   └── libpython3.6.so │   ├── include │   │   └── python3.6 │   │   └── Python.h │   └── bin │   └── python3.6 └── etc └── ld.so.conf """ otree = nx.OrderedDiGraph() for path in sorted(paths): parts = tuple(path.split(sep)) node_path = [] for i in range(1, len(parts) + 1): node = parts[0:i] otree.add_node(node) otree.nodes[node]['label'] = node[-1] node_path.append(node) for u, v in zip(node_path[:-1], node_path[1:]): otree.add_edge(u, v) if ('',) in otree.nodes: otree.nodes[('',)]['label'] = sep return otree
2,600
https://github.com/pwong3/csc413-secondgame-team12/blob/master/game/Main.java
Github Open Source
Open Source
MIT
null
csc413-secondgame-team12
pwong3
Java
Code
118
415
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author luisf */ //Reef Game************************************ package game; import java.awt.Dimension; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import javax.sound.midi.InvalidMidiDataException; import javax.sound.midi.MidiSystem; import javax.sound.midi.MidiUnavailableException; import javax.sound.midi.Sequencer; import javax.swing.*; public class Main { public static void main(String[] args) throws MidiUnavailableException, FileNotFoundException, IOException, InvalidMidiDataException { Sequencer sequencer = MidiSystem.getSequencer(); sequencer.open(); InputStream music = new BufferedInputStream(new FileInputStream(new File("images/Music.mid"))); sequencer.setSequence(music); sequencer.start(); Map map = new Map("Reef Game: Score "); map.setPreferredSize(new Dimension(640, 500)); map.setMaximumSize(new Dimension(640, 500)); map.setMinimumSize(new Dimension(640, 500)); //map.pack(); map.setResizable(false); map.run(); map.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }
13,038
https://github.com/maxemiliang/vscode-ext/blob/master/extensions/donjayamanne.python-0.3.21/out/client/linters/prospector.js
Github Open Source
Open Source
MIT
null
vscode-ext
maxemiliang
JavaScript
Code
259
882
'use strict'; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var baseLinter = require('./baseLinter'); var utils_1 = require('./../common/utils'); var Linter = (function (_super) { __extends(Linter, _super); function Linter(outputChannel, workspaceRootPath) { _super.call(this, 'prospector', outputChannel, workspaceRootPath); } Linter.prototype.isEnabled = function () { return this.pythonSettings.linting.prospectorEnabled; }; Linter.prototype.runLinter = function (filePath, txtDocumentLines) { var _this = this; if (!this.pythonSettings.linting.prospectorEnabled) { return Promise.resolve([]); } var prospectorPath = this.pythonSettings.linting.prospectorPath; var outputChannel = this.outputChannel; var linterId = this.Id; var prospectorArgs = Array.isArray(this.pythonSettings.linting.prospectorArgs) ? this.pythonSettings.linting.prospectorArgs : []; return new Promise(function (resolve, reject) { utils_1.execPythonFile(prospectorPath, prospectorArgs.concat(['--absolute-paths', '--output-format=json', filePath]), _this.workspaceRootPath, false).then(function (data) { var parsedData; try { parsedData = JSON.parse(data); } catch (ex) { outputChannel.append('#'.repeat(10) + 'Linting Output - ' + _this.Id + '#'.repeat(10) + '\n'); outputChannel.append(data); return resolve([]); } var diagnostics = []; parsedData.messages.filter(function (value, index) { return index <= _this.pythonSettings.linting.maxNumberOfProblems; }).forEach(function (msg) { var sourceLine = txtDocumentLines[msg.location.line - 1]; var sourceStart = sourceLine.substring(msg.location.character); var endCol = txtDocumentLines[msg.location.line - 1].length; // try to get the first word from the starting position var possibleProblemWords = sourceStart.match(/\w+/g); var possibleWord; if (possibleProblemWords != null && possibleProblemWords.length > 0 && sourceStart.startsWith(possibleProblemWords[0])) { possibleWord = possibleProblemWords[0]; } diagnostics.push({ code: msg.code, message: msg.message, column: msg.location.character, line: msg.location.line, possibleWord: possibleWord, type: msg.code, provider: _this.Id + " - " + msg.source }); }); resolve(diagnostics); }).catch(function (error) { _this.handleError(_this.Id, prospectorPath, error); resolve([]); }); }); }; return Linter; }(baseLinter.BaseLinter)); exports.Linter = Linter; //# sourceMappingURL=prospector.js.map
25,952
https://github.com/elfo-protocol/elfo-core/blob/master/programs/elfo-protocol/src/instructions/mod.rs
Github Open Source
Open Source
Apache-2.0
null
elfo-core
elfo-protocol
Rust
Code
42
113
pub mod close_subscription_plan; pub mod create_subscription_plan; pub mod initialize_protocol; pub mod register_node; pub mod subscribe; pub mod trigger_payment; pub mod unsubscribe; pub use close_subscription_plan::*; pub use create_subscription_plan::*; pub use initialize_protocol::*; pub use register_node::*; pub use subscribe::*; pub use trigger_payment::*; pub use unsubscribe::*;
1,609
https://github.com/efbiz/ability-exam/blob/master/portal/src/main/java/org/efbiz/ability/exam/portal/controller/action/UserAction.java
Github Open Source
Open Source
MIT
null
ability-exam
efbiz
Java
Code
319
1,524
package org.efbiz.ability.exam.portal.controller.action; import java.util.Date; import org.efbiz.ability.exam.common.domain.exam.Message; import org.efbiz.ability.exam.common.domain.user.User; import org.efbiz.ability.exam.common.util.StandardPasswordEncoderForSha1; import org.efbiz.ability.exam.portal.security.UserInfo; import org.efbiz.ability.exam.portal.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class UserAction { @Autowired private UserService userService; /** * 添加用户 * * @param user 如果添加的用户为学员,必须指定groupId。如果添加的用户为教师,则groupId为任意数字 * * @return */ @RequestMapping(value = {"/add-user"}, method = RequestMethod.POST) public @ResponseBody Message addUser(@RequestBody User user) { user.setCreateTime(new Date()); String password = user.getPassword() + "{" + user.getUserName().toLowerCase() + "}"; PasswordEncoder passwordEncoder = new StandardPasswordEncoderForSha1(); String resultPassword = passwordEncoder.encode(password); user.setPassword(resultPassword); user.setEnabled(true); user.setCreateBy(-1); user.setUserName(user.getUserName().toLowerCase()); Message message = new Message(); try { userService.addUser(user, "ROLE_STUDENT", 0, userService.getRoleMap()); } catch (Exception e) { // TODO Auto-generated catch block if (e.getMessage().contains(user.getUserName())) { message.setResult("duplicate-username"); message.setMessageInfo("重复的用户名"); } else if (e.getMessage().contains(user.getNationalId())) { message.setResult("duplicate-national-id"); message.setMessageInfo("重复的身份证"); } else if (e.getMessage().contains(user.getEmail())) { message.setResult("duplicate-email"); message.setMessageInfo("重复的邮箱"); } else if (e.getMessage().contains(user.getPhoneNum())) { message.setResult("duplicate-phone"); message.setMessageInfo("重复的电话"); } else { message.setResult(e.getCause().getMessage()); e.printStackTrace(); } } return message; } @RequestMapping(value = {"/student/update-user"}, method = RequestMethod.POST) public @ResponseBody Message updateUser(@RequestBody User user) { UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext().getAuthentication() .getPrincipal(); String password = user.getPassword() + "{" + user.getUserName() + "}"; PasswordEncoder passwordEncoder = new StandardPasswordEncoderForSha1(); String resultPassword = ""; if (user.getPassword() != null) { resultPassword = "".equals(user.getPassword().trim()) ? "" : passwordEncoder.encode(password); } user.setPassword(resultPassword); user.setEnabled(true); Message message = new Message(); try { userService.updateUser(user, null); userInfo.setTrueName(user.getTrueName()); userInfo.setEmail(user.getEmail()); userInfo.setNationalId(user.getNationalId()); userInfo.setPhoneNum(user.getPhoneNum()); } catch (Exception e) { // TODO Auto-generated catch block if (e.getMessage().contains(user.getUserName())) { message.setResult("duplicate-username"); message.setMessageInfo("重复的用户名"); } else if (e.getMessage().contains(user.getNationalId())) { message.setResult("duplicate-national-id"); message.setMessageInfo("重复的身份证"); } else if (e.getMessage().contains(user.getEmail())) { message.setResult("duplicate-email"); message.setMessageInfo("重复的邮箱"); } else if (e.getMessage().contains(user.getPhoneNum())) { message.setResult("duplicate-phone"); message.setMessageInfo("重复的电话"); } else { message.setResult(e.getCause().getMessage()); e.printStackTrace(); } } return message; } @RequestMapping(value = {"/student/change-pwd"}, method = RequestMethod.POST) public @ResponseBody Message changePassword(@RequestBody User user) { Message message = new Message(); UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext() .getAuthentication().getPrincipal(); try { String password = user.getPassword() + "{" + userInfo.getUsername() + "}"; PasswordEncoder passwordEncoder = new StandardPasswordEncoderForSha1(); String resultPassword = passwordEncoder.encode(password); user.setPassword(resultPassword); user.setUserName(userInfo.getUsername()); userService.updateUserPwd(user, null); } catch (Exception e) { e.printStackTrace(); message.setResult(e.getClass().getName()); } return message; } }
26,955
https://github.com/jessepinnell/driver-sample/blob/master/src/MCP25625Driver.hpp
Github Open Source
Open Source
MIT
null
driver-sample
jessepinnell
C++
Code
925
2,452
// MIT License // Copyright (c) 2018 Jesse Pinnell // 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. #ifndef __SRC_MCP25625DRIVER_HPP__ #define __SRC_MCP25625DRIVER_HPP__ #include <stdexcept> #include <string> #include <memory> #include <iostream> namespace driver_sample { namespace MCP25625 { class Log; /** * @brief Exception class indicating device initialization failure */ class InitializationError : public std::runtime_error { public: explicit InitializationError(const std::string &message) : std::runtime_error(message) {} virtual ~InitializationError() {} }; /** * @brief Exception class indicating a method is unimplemented */ class UnimplementedException : public std::logic_error { public: explicit UnimplementedException(const std::string &function) : std::logic_error(function + " is unimplemented") {} virtual ~UnimplementedException() {} }; /** * @brief Exception class indicating device communication failure */ class CommunicationError : public std::runtime_error { public: explicit CommunicationError(const std::string &message) : std::runtime_error(message) {} virtual ~CommunicationError() {} }; /** * @brief Exception class indicating invalid operation or address */ class InvalidArgumentError : public std::runtime_error { public: explicit InvalidArgumentError(const std::string &message) : std::runtime_error(message) {} virtual ~InvalidArgumentError() {} }; struct Status { bool rx0if_ = false, // RX0IF (CANINTF Register) rx1if_ = false, // RX1IF (CANINTF Register) tx0req_ = false, // TXREQ (TXB0CTRL Register) tx0if_ = false, // TX0IF (CANINTF Register) tx1req_ = false, // TXREQ (TXB1CTRL Register) tx1if_ = false, // TX1IF (CANINTF Register) tx2req_ = false, // TXREQ (TXB2CTRL Register) tx2if_ = false; // TX2IF (CANINTF Register) friend std::ostream &operator<<(std::ostream &os, const Status &status) { os << std::boolalpha << "\nRX0IF (CANINTF Register): " << status.rx0if_ << "\nRX1IF (CANINTF Register): " << status.rx1if_ << "\nTXREQ (TXB0CTRL Register): " << status.tx0req_ << "\nTX0IF (CANINTF Register): " << status.tx0if_ << "\nTXREQ (TXB1CTRL Register): " << status.tx1req_ << "\nTX1IF (CANINTF Register): " << status.tx1if_ << "\nTXREQ (TXB2CTRL Register): " << status.tx2req_ << "\nTX2IF (CANINTF Register): " << status.tx2if_; return os; } }; enum class ReceiveMessage { NO_RX_MESSAGE, MESSAGE_RXB0, MESSAGE_RXB1, MESSAGE_BOTH }; enum class MessageType { STANDARD_DATA_FRAME, STANDARD_REMOTE_FRAME, EXTENDED_DATA_FRAME, EXTENDED_REMOTE_FRAME }; enum class FilterMatch { RXF0, RXF1, RXF2, RXF3, RXF4, RXF5, RXF0_ROLLOVER_RXB1, RXF1_ROLLOVER_RXB1 }; struct ReceiveStatus { ReceiveMessage receive_message_; MessageType message_type_; FilterMatch filter_match_; friend std::ostream &operator<<(std::ostream &os, const ReceiveStatus &status) { os << "Receive Message: "; switch (status.receive_message_) { case ReceiveMessage::NO_RX_MESSAGE: os << "NO_RX_MESSAGE"; break; case ReceiveMessage::MESSAGE_RXB0: os << "MESSAGE_RXB0"; break; case ReceiveMessage::MESSAGE_RXB1: os << "MESSAGE_RXB1"; break; case ReceiveMessage::MESSAGE_BOTH: os << "MESSAGE_BOTH"; break; } os << "\nMessage Type: "; switch (status.message_type_) { case MessageType::STANDARD_DATA_FRAME: os << "STANDARD_DATA_FRAME"; break; case MessageType::STANDARD_REMOTE_FRAME: os << "STANDARD_REMOTE_FRAME"; break; case MessageType::EXTENDED_DATA_FRAME: os << "EXTENDED_DATA_FRAME"; break; case MessageType::EXTENDED_REMOTE_FRAME: os << "EXTENDED_REMOTE_FRAME"; break; } os << "\nFilter match: "; switch (status.filter_match_) { case FilterMatch::RXF0: os << "RXF0"; break; case FilterMatch::RXF1: os << "RXF1"; break; case FilterMatch::RXF2: os << "RXF2"; break; case FilterMatch::RXF3: os << "RXF3"; break; case FilterMatch::RXF4: os << "RXF4"; break; case FilterMatch::RXF5: os << "RXF5"; break; case FilterMatch::RXF0_ROLLOVER_RXB1: os << "RXF0_ROLLOVER_RXB1"; break; case FilterMatch::RXF1_ROLLOVER_RXB1: os << "RXF1_ROLLOVER_RXB1"; break; } return os; } }; class Driver { public: Driver(); Driver(const Driver &) = delete; Driver &operator=(const Driver &) = delete; virtual ~Driver(); /** * @brief Reset internal registers to default state and set configuration mode */ void reset(); /** * @brief Read data from register at address * * @param address The address from which to read * * @return The data read from the register */ uint8_t read(const uint8_t address); /** * @brief Read data from receive buffer * This is faster than a read() call because the rx buffer address * is part of the command * * @param receive_buffer The receive buffer address (0x0-0x3) * * @return The data read from the register */ uint8_t readReceiveBuffer(const uint8_t receive_buffer); /** * @brief Write data to the register at address * * @param address The address to which to write * @param data The data to write to the register */ void write(const uint8_t address, const uint8_t data); /** * @brief Write data to a transmit buffer * * @param address The address to which to write (0x0-0x5) * @param data The data to write to the register */ void writeTransmitBuffer(const uint8_t address, const uint8_t data); /** * @brief Instruct the controller to begin the message transmission of the transmit buffers * * @param rts_txb0 Do request-to-send for TXB0 * @param rts_txb1 Do request-to-send for TXB1 * @param rts_txb2 Do request-to-send for TXB2 */ void requestToSend(const bool rts_txb0, const bool rts_txb1, const bool rts_txb2); /** * @brief Read the message reception and transmission status * * @return The current message reception and transmission status */ MCP25625::Status readStatus(); /** * @brief Read the receive status * * @return The receive status */ MCP25625::ReceiveStatus readReceiveStatus(); private: std::mutex device_mutex_; }; } // namespace MCP25625 } // namespace driver_sample #endif // __SRC_MCP25625DRIVER_HPP__
3,418
https://github.com/soraLib/sa-form/blob/master/src/SaForm/layout/properties-controller/index.tsx
Github Open Source
Open Source
MIT
2,022
sa-form
soraLib
TypeScript
Code
122
388
import { computed, defineComponent, PropType } from 'vue'; import { BasicDrawer } from '../../drawer'; import PluginItem from './item'; import './index.scss'; import { SaController } from '../../config'; import { ElementType } from '../../element'; export default defineComponent({ name: 'SaFormLayoutController', props: { drawer: { required: true, type: Object as PropType<BasicDrawer> }, controller: { required: true, type: Object as PropType<SaController> } }, setup(props) { const plugin = computed(() => { const type = props.drawer.selected[0]?.attrs.type; if (type) { if (props.controller.plugins[type]) { return props.controller.plugins[type]; } console.warn(`[Sa warn]: Plugins not found in type ${ElementType[type]}.`); } return undefined; }); return () => ( <div class="controller-container"> { plugin.value ? plugin.value.basic?.map((item => <div class="controller-item"> <div class="controller-item-label">{item.label}</div> <div class="controller-item-plugin"> <PluginItem plugin={item} drawer={props.drawer} controller={props.controller} /> </div> </div> )) : '' }</div> ); } });
46,435
https://github.com/guess-togethr/guess-togethr-extension/blob/master/src/background/store/savedLobbies.ts
Github Open Source
Open Source
MIT
null
guess-togethr-extension
guess-togethr
TypeScript
Code
327
1,047
import { createSlice, createEntityAdapter, PayloadAction, Action, } from "@reduxjs/toolkit"; import type { XOR } from "../../utils"; import type { BackgroundRootState } from "."; // export interface FullSavedLobby { // id: string; // // identity: { publicKey: string; privateKey: string }; // isServer: boolean; // user?: string; // name?: string; // tabId?: number; // } export type FullSavedLobby = { id: string; tabId?: number } & XOR< { isServer: true; user: string; name: string }, { isServer: false; user?: string; name?: string } >; export interface ErroredLobby { id: string; error: string; tabId: number; } export type SavedLobby = XOR<FullSavedLobby, ErroredLobby>; export function isFullLobby(lobby?: SavedLobby): lobby is FullSavedLobby { return !!lobby && "isServer" in lobby; } export function isErroredLobby(lobby?: SavedLobby): lobby is ErroredLobby { return !!lobby && "error" in lobby; } const savedLobbyAdapter = createEntityAdapter<SavedLobby>(); const savedLobbySelectors = savedLobbyAdapter.getSelectors<BackgroundRootState>( (state) => state.allLobbies ); const savedLobbyLocalSelector = savedLobbyAdapter.getSelectors(); const savedLobbies = createSlice({ name: "savedLobbies", initialState: savedLobbyAdapter.getInitialState(), reducers: { saveLobby: savedLobbyAdapter.addOne, removeSavedLobby: savedLobbyAdapter.removeOne, claimSavedLobby: (state, action: PayloadAction<string>) => { const allLobbies = savedLobbyLocalSelector.selectAll(state); const existingClaimedLobby = allLobbies.find( (lobby) => lobby.tabId === (action as any).meta.tabId ); // If this tab previously claimed a lobby, either release it if it was a // normal lobby or delete it if it was an errored lobby if (existingClaimedLobby && existingClaimedLobby.id !== action.payload) { if (!isFullLobby(existingClaimedLobby)) { savedLobbyAdapter.removeOne(state, existingClaimedLobby.id); } else { delete existingClaimedLobby.tabId; } } savedLobbyAdapter.updateOne(state, { id: action.payload, changes: { tabId: (action as any).meta.tabId }, }); // Move the lobby to the top of the list const allLobbyIds = savedLobbyLocalSelector.selectIds(state); const newClaimedLobbyIndex = allLobbyIds.indexOf(action.payload); if (newClaimedLobbyIndex > 0) { allLobbyIds.unshift(...allLobbyIds.splice(newClaimedLobbyIndex, 1)); } }, releaseSavedLobby: (state, action: Action) => { const existingLobby = savedLobbyLocalSelector .selectAll(state) .find((lobby) => lobby.tabId === (action as any).meta.tabId); if (existingLobby) { if (!isFullLobby(existingLobby)) { savedLobbyAdapter.removeOne(state, existingLobby.id); } else { delete existingLobby.tabId; } } }, updateSavedLobby: savedLobbyAdapter.updateOne, }, }); export const { saveLobby, removeSavedLobby, // setMostRecentSavedLobby, claimSavedLobby, releaseSavedLobby, updateSavedLobby, } = savedLobbies.actions; export { savedLobbySelectors, savedLobbyLocalSelector, savedLobbyAdapter }; export default savedLobbies.reducer;
25,859
https://github.com/ssrisunt/akka_streams_tutorial/blob/master/src/main/scala/alpakka/env/KafkaServer.scala
Github Open Source
Open Source
Apache-2.0, MIT
2,020
akka_streams_tutorial
ssrisunt
Scala
Code
275
1,252
package alpakka.env import java.io.File import java.net.InetSocketAddress import java.nio.file.{Files, Paths} import java.util.Properties import kafka.server.{KafkaConfig, KafkaServerStartable} import org.apache.commons.io.FileUtils import org.apache.zookeeper.server.quorum.QuorumPeerConfig import org.apache.zookeeper.server.{ServerConfig, ZooKeeperServerMain} /** * KafkaServer which embedded Zookeeper, inspired by: * https://github.com/jamesward/koober/blob/master/kafka-server/src/main/scala/KafkaServer.scala * * Remarks: * - Zookeeper starts an admin server on http://localhost:8080/commands * - Shut down gracefully via exit (so that shutdown hook runs) * * Alternatives: * - Use "Embedded Kafka", see: https://github.com/manub/scalatest-embedded-kafka * - Run Kafka in docker * see: https://github.com/wurstmeister/kafka-docker * or together with kafdrop admin console: https://towardsdatascience.com/kafdrop-e869e5490d62 * - Setup Kafka server manually, see: https://kafka.apache.org/quickstart * - Use Confluent Cloud, see: https://www.confluent.io/confluent-cloud/#view-pricing */ object KafkaServer extends App { val zookeeperPort = 2181 val kafkaLogs = "/tmp/kafka-logs" val kafkaLogsPath = Paths.get(kafkaLogs) // See: https://stackoverflow.com/questions/59592518/kafka-broker-doesnt-find-cluster-id-and-creates-new-one-after-docker-restart/60864763#comment108382967_60864763 def fix25Behaviour() = { val fileWithConflictingContent = kafkaLogsPath.resolve("meta.properties").toFile if (fileWithConflictingContent.exists()) FileUtils.forceDelete(fileWithConflictingContent) } def removeKafkaLogs(): Unit = { if (kafkaLogsPath.toFile.exists()) FileUtils.forceDelete(kafkaLogsPath.toFile) } // Keeps the persistent data fix25Behaviour() // If everything fails //removeKafkaLogs() val quorumConfiguration = new QuorumPeerConfig { // Since we do not run a cluster, we are not interested in zookeeper data override def getDataDir: File = Files.createTempDirectory("zookeeper").toFile override def getDataLogDir: File = Files.createTempDirectory("zookeeper-logs").toFile override def getClientPortAddress: InetSocketAddress = new InetSocketAddress(zookeeperPort) } class StoppableZooKeeperServerMain extends ZooKeeperServerMain { def stop(): Unit = shutdown() } val zooKeeperServer = new StoppableZooKeeperServerMain() val zooKeeperConfig = new ServerConfig() zooKeeperConfig.readFrom(quorumConfiguration) val zooKeeperThread = new Thread { override def run(): Unit = zooKeeperServer.runFromConfig(zooKeeperConfig) } zooKeeperThread.start() val kafkaProperties = new Properties() kafkaProperties.put("zookeeper.connect", s"localhost:$zookeeperPort") kafkaProperties.put("broker.id", "0") kafkaProperties.put("offsets.topic.replication.factor", "1") kafkaProperties.put("log.dirs", kafkaLogs) kafkaProperties.put("delete.topic.enable", "true") kafkaProperties.put("group.initial.rebalance.delay.ms", "0") kafkaProperties.put("transaction.state.log.min.isr", "1") kafkaProperties.put("transaction.state.log.replication.factor", "1") kafkaProperties.put("zookeeper.connection.timeout.ms", "6000") kafkaProperties.put("num.partitions", "10") val kafkaConfig = KafkaConfig.fromProps(kafkaProperties) val kafka = new KafkaServerStartable(kafkaConfig) println("About to start...") kafka.startup() scala.sys.addShutdownHook{ println("About to shutdown...") kafka.shutdown() kafka.awaitShutdown() zooKeeperServer.stop() } zooKeeperThread.join() }
36,736
https://github.com/Ranod98/SMS/blob/master/app/Repository/StudentRepositoryInterface.php
Github Open Source
Open Source
MIT
null
SMS
Ranod98
PHP
Code
71
243
<?php namespace App\Repository; interface StudentRepositoryInterface{ //Get Students public function getStudents(); //show student public function showStudents($id); // Get Add Form Student public function createStudents(); //Store_Student public function storeStudents($request); // Edit Students public function editStudents($id); //Destroy Student public function destroyStudents($id); //Update Students public function updateStudents($request,$id); // Get classrooms public function getClassrooms($id); //Get Sections public function getSections($id); //uploadAttachments public function uploadStudentAttachments($request,$id); //downloadAttachment public function downloadStudentAttachments($studentname , $filename); //deleteAttachment public function deleteAttachment($request); }//end of interface
35,232
https://github.com/fenmarel/OMSCentral/blob/master/src/app/core/nav/nav.component.ts
Github Open Source
Open Source
MIT
2,022
OMSCentral
fenmarel
TypeScript
Code
110
322
import { Component, OnInit } from '@angular/core'; import { AuthService } from '../../firebase/auth.service'; import { Router } from '@angular/router'; import { UserService } from '../user.service'; import { SettingsService } from '../settings.service'; import { Store } from '@ngrx/store'; import { AuthState } from '../../state/auth/reducers'; import { getUser } from '../../state/auth/reducers'; import { Observable } from 'rxjs'; import { Logout } from '../../state/auth/actions/auth'; @Component({ selector: 'oms-nav', templateUrl: './nav.component.html', styleUrls: ['./nav.component.scss'], }) export class NavComponent implements OnInit { user$: Observable<any> | Promise<Observable<any>>; constructor( private auth: AuthService, private router: Router, private userService: UserService, private settingsService: SettingsService, private store: Store<AuthState> ) { this.user$ = this.store.select(getUser); settingsService.getSettings(); } ngOnInit() {} logout() { this.store.dispatch(new Logout()); } }
34,758
https://github.com/kelibst/fr-unitreview/blob/master/src/components/ErrOrs.js
Github Open Source
Open Source
MIT
2,021
fr-unitreview
kelibst
JavaScript
Code
251
773
import React, { Component } from 'react'; import { Alert, Button } from 'react-bootstrap'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import { unloadError } from '../store/actions/errorAction'; import Icofont from 'react-icofont'; class ErrOrs extends Component { constructor(props) { super(props); this.state = { show: true, }; } componentDidMount() { const { show } = this.state; show && setTimeout(() => { const { unloadError } = this.props; show && this.setState( { show: false, }, unloadError() ); }, 3000); } componentWillUnmount() { const { unloadError } = this.props; unloadError(); } render() { const { show } = this.state; const { errors } = this.props; // const { error } = errors?.response?.data const setShow = () => { const { unloadError, errors } = this.props; unloadError(); this.setState({ show: false, }); }; // const { error } = errors?.response?.data return ( <div> <Alert show={show} variant="danger"> <div> {/* { error?.message && (<h6 className="my-5"> {error?.message}</h6>)} */} {/* { errors?.response && (<h6 className="my-1"> Sorry something went wrong</h6>)} */} {/* { typeof(errors) == "object" && <h6>{errors?.Email}</h6>} {Array.isArray(errors) && errors.map(err => <h6 key={err}>{err}</h6>) } {typeof(errors?.response?.data?.error) === "string" && <h6 className="my-2">Sorry your session has expired! <br></br> Kindly login again.</h6>} {/* {errors?.response?.data?.error && typeof(errors?.response?.data?.error) !== "string" && Object.entries(errors?.response?.data?.error).map(error => <h6 key={error} className="my-2">{error}</h6>)} */} {/* {errors?.request && !errors?.response?.data && <h6 className="my-5"><Icofont icon="close" /> {errors.request.response}</h6>}} */} Sorry something went wrong! </div> <hr /> <div className="d-flex justify-content-end"> <Button onClick={setShow} variant="outline-danger"> close </Button> </div> </Alert> </div> ); } } const mapStateToProps = state => ({ errors: state.errors.err, }); export default connect(mapStateToProps, { unloadError })(ErrOrs);
19,305
https://github.com/joegana/BerkeleyDB/blob/master/test/com/sleepycat/je/rep/elections/ProtocolFailureTest.java
Github Open Source
Open Source
Apache-2.0
2,022
BerkeleyDB
joegana
Java
Code
817
2,413
/*- * Copyright (C) 2002, 2017, Oracle and/or its affiliates. All rights reserved. * * This file was distributed by Oracle as part of a version of Oracle Berkeley * DB Java Edition made available at: * * http://www.oracle.com/technetwork/database/database-technologies/berkeleydb/downloads/index.html * * Please see the LICENSE file included in the top-level directory of the * appropriate version of Oracle Berkeley DB Java Edition for a copy of the * license and additional information. */ package com.sleepycat.je.rep.elections; import static com.sleepycat.je.rep.impl.TextProtocol.SEPARATOR; import static com.sleepycat.je.rep.impl.TextProtocol.SEPARATOR_REGEXP; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.util.Collections; import java.util.Set; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.sleepycat.je.rep.ReplicatedEnvironment.State; import com.sleepycat.je.rep.impl.RepTestBase; import com.sleepycat.je.rep.impl.TextProtocol; import com.sleepycat.je.rep.impl.TextProtocol.Message; import com.sleepycat.je.rep.impl.TextProtocol.RequestMessage; import com.sleepycat.je.rep.impl.TextProtocol.ResponseMessage; import com.sleepycat.je.rep.impl.TextProtocol.TOKENS; import com.sleepycat.je.utilint.TestHook; /** * Check rep node resilience when there are various types of protocol message * format corruption or semantic inconsistencies. The intent here is to confine * the failure as much as possible and prevent the environment itself from * failing. The tests here are pretty basic for the most part. We can augment * them as we find more scenarios of interest. */ public class ProtocolFailureTest extends RepTestBase { @Override @Before public void setUp() throws Exception { groupSize = 3; super.setUp(); } @Override @After public void tearDown() throws Exception { super.tearDown(); } @Test public void testBadVersionReq() throws InterruptedException { testInternal(TOKENS.VERSION_TOKEN, RequestMessage.class); } @Test public void testBadVersionResp() throws InterruptedException { testInternal(TOKENS.VERSION_TOKEN, ResponseMessage.class); } @Test public void testBadNameReq() throws InterruptedException { testInternal(TOKENS.NAME_TOKEN, RequestMessage.class); } @Test public void testBadNameResp() throws InterruptedException { testInternal(TOKENS.NAME_TOKEN, ResponseMessage.class); } @Test public void testBadId() throws InterruptedException { testInternal(TOKENS.ID_TOKEN, RequestMessage.class); } @Test public void testBadIdResp() throws InterruptedException { testInternal(TOKENS.ID_TOKEN, ResponseMessage.class); } @Test public void testBadOp() throws InterruptedException { testInternal(TOKENS.OP_TOKEN, RequestMessage.class); } @Test public void testBadOpResp() throws InterruptedException { testInternal(TOKENS.OP_TOKEN, ResponseMessage.class); } @Test public void testBadPayloadRequest() { /* * Future: Need custom tests and custom code for bad payload requests. */ // testInternal(TOKENS.FIRST_PAYLOAD_TOKEN, RequestMessage.class); } @Test public void testBadPayloadResp() throws InterruptedException { testInternal(TOKENS.FIRST_PAYLOAD_TOKEN, ResponseMessage.class); } /** * Tests damage to a specific field as identified by the message token for * a specific type of message. * * @param testToken the token to be munged * @param testMessageType the type of messages (request/response) to be * munged. */ private void testInternal(TOKENS testToken, Class<? extends Message> testMessageType) throws InterruptedException { createGroup(3); closeNodes(repEnvInfo); /* Close all nodes to eliminate masters */ repEnvInfo[0].getRepConfig(). setConfigParam("je.rep.envUnknownStateTimeout", "1 ms"); repEnvInfo[0].openEnv(); final Protocol protocol = repEnvInfo[0].getRepNode().getElections().getProtocol(); final Set<String> modOps = protocol.getOps(testMessageType); final SerDeHook corruptOpHook = new SerDeHook(testToken, modOps); TextProtocol.setSerDeHook(corruptOpHook); repEnvInfo[2].getRepConfig(). setConfigParam("je.rep.envUnknownStateTimeout", "5 s"); repEnvInfo[2].openEnv(); /* Verify that hook was called by the test. */ assertTrue(corruptOpHook.count > 0); /* * Verify that nodes are up and standing, that is, not DETACHED and * there's no master or replica since the election messages were munged. */ assertEquals(State.UNKNOWN, repEnvInfo[2].getEnv().getState()); assertEquals(State.UNKNOWN, repEnvInfo[0].getEnv().getState()); /* Start sending valid messages. */ TextProtocol.setSerDeHook(null); assertTrue(findMasterWait(60000, repEnvInfo[0], repEnvInfo[2]) != null); } /** * The Hook that mungs messages. Note that since the hook is invoked from * a method that's re-entrant, its methods must be re-entrant as well, */ private class SerDeHook implements TestHook<String> { final TOKENS testToken; /* Number of times messages were actually modified. */ volatile int count; /* * Messages with this op will be modified at the token identified by * testToken. */ final Set<String> modOps; /* * Use ThreadLocal to make the doHook and getValue methods re-entrant */ final ThreadLocal<String> messageLine = new ThreadLocal<>(); /** * Hook constructor * @param testToken the token that must be munged within the message * @param modOps the ops associated with messages that should be * munged. All other messages are left intact. */ public SerDeHook(TOKENS testToken, Set<String> modOps) { super(); this.testToken = testToken; this.modOps = Collections.unmodifiableSet(modOps); } @Override public void hookSetup() { throw new UnsupportedOperationException("Method not implemented: " + "hookSetup"); } @Override public void doIOHook() throws IOException { throw new UnsupportedOperationException("Method not implemented: " + "doIOHook"); } @Override public void doHook() { throw new UnsupportedOperationException("Method not implemented: " + "doHook"); } @Override public void doHook(String origMessage) { if (origMessage == null) { messageLine.set(null); return; } final String[] tokens = origMessage.split(SEPARATOR_REGEXP); if (testToken.ordinal() >= tokens.length) { /* The messages does not have any payload. */ messageLine.set(origMessage); return; } final String opToken = tokens[TOKENS.OP_TOKEN.ordinal()]; if (!modOps.contains(opToken)) { /* Not in the set of modifiable messages */ messageLine.set(origMessage); return; } /* * Modify the token. The message format is: * <version>|<name>|<id>|<op>|<op-specific payload> */ count++; final String token = tokens[testToken.ordinal()]; final String leadSeparator = (testToken.ordinal() > 0) ? SEPARATOR : ""; final String trailingSeparator = (testToken.ordinal() == (tokens.length - 1)) ? "" : SEPARATOR ; final String badToken = leadSeparator + "bad" + token + trailingSeparator; String newMessage = origMessage. replace(leadSeparator + token + trailingSeparator, badToken); assertTrue(!messageLine.equals(origMessage)); if (testToken.equals(TOKENS.FIRST_PAYLOAD_TOKEN)) { /* Mung the rest of the payload. */ int payloadStart = newMessage.indexOf(badToken); newMessage = newMessage.substring(0, payloadStart) + leadSeparator + "badPayload"; } messageLine.set(newMessage); } @Override public String getHookValue() { try { return messageLine.get(); } finally { messageLine.remove(); } } } }
23,137
https://github.com/WosberbonDesu/Orgonet-ChatApp/blob/master/OrgonetCodesV2final/pages/ChatRoomPageU.dart
Github Open Source
Open Source
MIT
2,022
Orgonet-ChatApp
WosberbonDesu
Dart
Code
337
1,469
import 'dart:developer'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/material.dart'; import 'package:orgonetchatappv2/main.dart'; import 'package:orgonetchatappv2/models/ChatRoomModel.dart'; import 'package:orgonetchatappv2/models/MessageModel.dart'; import 'package:orgonetchatappv2/models/UserModel.dart'; class ChatRoomPage extends StatefulWidget { final UserModel targetUser; final ChatRoomModel chatroom; final UserModel userModel; final User firebaseUser; const ChatRoomPage({Key? key, required this.targetUser, required this.chatroom, required this.userModel, required this.firebaseUser}) : super(key: key); //const ChatRoomPage({Key? key}) : super(key: key); @override _ChatRoomPageState createState() => _ChatRoomPageState(); } class _ChatRoomPageState extends State<ChatRoomPage> { TextEditingController messageController = TextEditingController(); void sendMessage()async{ String msg = messageController.text.trim(); messageController.clear(); if(msg != ""){ MessageModel newMessage = MessageModel( messageid: uuid.v1(), sender: widget.userModel.uid, createdon: DateTime.now(), text: msg, seen: false ); FirebaseFirestore.instance.collection("chatrooms") .doc(widget.chatroom.chatroomid) .collection("messages").doc(newMessage.messageid) .set(newMessage.toMap()); widget.chatroom.lastMessage = msg; FirebaseFirestore.instance.collection("chatrooms").doc(widget.chatroom.chatroomid).set(widget.chatroom.toMap()); log("Message Send"); } } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.yellowAccent, appBar: AppBar( centerTitle: true, title: Row( children: [ CircleAvatar( backgroundColor: Colors.grey[300], backgroundImage: NetworkImage( widget.targetUser.profilepic.toString() ), ), SizedBox(width: 10,), Text(widget.targetUser.fullname.toString(),style: TextStyle(color: Colors.white),), ], ), backgroundColor: Colors.black, ), body: SafeArea( child: Container( child: Column( children: [ Expanded( child: Container( padding: EdgeInsets.symmetric( horizontal: 10, ), child: StreamBuilder( stream: FirebaseFirestore.instance.collection("chatrooms").doc(widget.chatroom.chatroomid) .collection("messages").orderBy("createdon",descending: true).snapshots(), builder: (context,snapshot){ if(snapshot.connectionState == ConnectionState.active){ if(snapshot.hasData){ QuerySnapshot dataSnapshot = snapshot.data as QuerySnapshot; return ListView.builder( reverse: true, itemCount: dataSnapshot.docs.length, itemBuilder: (context, index){ MessageModel currentMessage = MessageModel.fromMap(dataSnapshot.docs[index].data() as Map<String,dynamic>); return Row( mainAxisAlignment: (currentMessage.sender == widget.userModel.uid) ? MainAxisAlignment.end : MainAxisAlignment.start, children: [ Container( margin: EdgeInsets.symmetric( vertical: 2 ), padding: EdgeInsets.symmetric( vertical: 10, horizontal: 10 ), decoration: BoxDecoration( color: (currentMessage.sender == widget.userModel.uid) ? Colors.grey.shade800 : Colors.black, borderRadius: BorderRadius.circular(20) ), child: Text( currentMessage.text.toString(), style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold),) ), ] ); }, ); }else if(snapshot.hasError){ return Center( child: Text("An error occured! Please check your internet connection",style: TextStyle(color: Colors.black),), ); }else{ return Center( child: Text("Say hi! to your new Friend.",style: TextStyle(color: Colors.black),), ); } }else{ return Center( child: CircularProgressIndicator(), ); } }, ), ) ), Container( color: Colors.black54, padding: EdgeInsets.symmetric( horizontal: 15, vertical: 5 ), child: Row( children: [ Flexible( child: TextField( controller: messageController, maxLines: null, decoration: InputDecoration( border: InputBorder.none, hintStyle: TextStyle( color: Colors.black ), hintText: "Enter Message", ), ), ), IconButton( onPressed: (){ sendMessage(); }, icon: Icon(Icons.send,color: Colors.black,), ), ], ), ) ], ), ), ), ); } }
23,838
https://github.com/ycj123/Research-Project/blob/master/proFL-plugin-2.0.3/org/pitest/mutationtest/engine/gregor/mutators/ReturnValsMutator.java
Github Open Source
Open Source
MIT
null
Research-Project
ycj123
Java
Code
61
264
// // Decompiled by Procyon v0.5.36 // package org.pitest.mutationtest.engine.gregor.mutators; import org.pitest.reloc.asm.MethodVisitor; import org.pitest.mutationtest.engine.gregor.MethodInfo; import org.pitest.mutationtest.engine.gregor.MutationContext; import org.pitest.mutationtest.engine.gregor.MethodMutatorFactory; public enum ReturnValsMutator implements MethodMutatorFactory { RETURN_VALS_MUTATOR; @Override public MethodVisitor create(final MutationContext context, final MethodInfo methodInfo, final MethodVisitor methodVisitor) { return new ReturnValsMethodVisitor(this, methodInfo, context, methodVisitor); } @Override public String getGloballyUniqueId() { return this.getClass().getName(); } @Override public String getName() { return this.name(); } }
30,016
https://github.com/maiconcrespo/familiaquotes/blob/master/lib/features/quote/data/datasources/local.dart
Github Open Source
Open Source
MIT
null
familiaquotes
maiconcrespo
Dart
Code
48
347
// const String YOUR_PERSONAL_ACCESS_TOKEN = // '<YOUR_PERSONAL_ACCESS_TOKEN>'; const String parseApplicationId = 'pTdETNwxBDob63Qzb90KQXvt5h3rVvgfkXP5V5mf'; const String parseClientKey = 'wzLjRGyS2tmxTt8WvQBK7sMSpRPniKUWDEaYj8dD'; const String parseMasterKey = 'AilRFJGHZakndSpmIgpMmAwUx3u2Ztr8mi5wl4dI'; const String parseApiKey = 'FZ9kKwx7UHKwVb8EOsjgRjnYpYOu9oUDRL420lbZ'; const Map<String, dynamic> parseApiKeyIDMap = { 'X-Parse-Application-Id': 'pTdETNwxBDob63Qzb90KQXvt5h3rVvgfkXP5V5mf', 'X-Parse-REST-API-Key': 'FZ9kKwx7UHKwVb8EOsjgRjnYpYOu9oUDRL420lbZ' }; const String url = 'https://parseapi.back4app.com/graphql'; const String urlRest = 'https://www.abibliadigital.com.br/api/verses/nvi/random';
28,114
https://github.com/chrisr3/gradle-distributed-testing-plugin/blob/master/src/test/java/com/r3/testing/PropertiesTest.java
Github Open Source
Open Source
Apache-2.0
null
gradle-distributed-testing-plugin
chrisr3
Java
Code
124
530
package com.r3.testing; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class PropertiesTest { private static String username = "me"; private static String password = "me"; private static String cordaType = "corda-project"; private static String branch = "mine"; private static String targetBranch = "master"; @BeforeEach public void setUp() { System.setProperty("git.branch", branch); System.setProperty("git.target.branch", targetBranch); System.setProperty("artifactory.username", username); System.setProperty("artifactory.password", password); } @AfterEach public void tearDown() { System.setProperty("git.branch", ""); System.setProperty("git.target.branch", ""); System.setProperty("artifactory.username", ""); System.setProperty("artifactory.password", ""); } @Test public void cordaType() { Properties.setRootProjectType(cordaType); Assertions.assertEquals(cordaType, Properties.getRootProjectType()); } @Test public void getUsername() { Assertions.assertEquals(username, Properties.getUsername()); } @Test public void getPassword() { Assertions.assertEquals(password, Properties.getPassword()); } @Test public void getGitBranch() { Assertions.assertEquals(branch, Properties.getGitBranch()); } @Test public void getTargetGitBranch() { Assertions.assertEquals(targetBranch, Properties.getTargetGitBranch()); } @Test public void getPublishJunitTests() { Assertions.assertFalse(Properties.getPublishJunitTests()); System.setProperty("publish.junit", "true"); Assertions.assertTrue(Properties.getPublishJunitTests()); } }
1,585
https://github.com/blackbaud/gradle-templates/blob/master/src/componentTest/resources/expectedTemplateContent/service-bus-producer/src/main/java/com/blackbaud/service/servicebus/ProducerServiceBusProperties.java
Github Open Source
Open Source
Apache-2.0
2,017
gradle-templates
blackbaud
Java
Code
16
77
package com.blackbaud.service.servicebus; import com.blackbaud.azure.servicebus.config.ServiceBusProperties; import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties(prefix = "servicebus.producer") public class ProducerServiceBusProperties extends ServiceBusProperties { }
37,664
https://github.com/dinuworks/hope-dinesh/blob/master/web/themes/custom/apigee_cn/templates/field/field.html.twig
Github Open Source
Open Source
MIT
null
hope-dinesh
dinuworks
Twig
Code
16
42
{# /** * @file * Default template for a field. */ #} {% include '@apigee-cn/field/field.twig' %}
17,583
https://github.com/UHC-Center/UHC-Center.CoreCommons/blob/master/src/main/java/center/uhc/core/commons/PlayerUtils.java
Github Open Source
Open Source
MIT
null
UHC-Center.CoreCommons
UHC-Center
Java
Code
462
1,680
package center.uhc.core.commons; import center.uhc.core.commons.versions.NMSCore; import center.uhc.core.commons.versions.NMSVersion; import center.uhc.core.commons.versions.UniversalSound; import de.dytanic.cloudnet.driver.CloudNetDriver; import de.dytanic.cloudnet.ext.bridge.player.ICloudPlayer; import de.dytanic.cloudnet.ext.bridge.player.IPlayerManager; import net.luckperms.api.LuckPermsProvider; import net.luckperms.api.cacheddata.CachedMetaData; import net.luckperms.api.model.user.User; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Sound; import org.bukkit.entity.Player; import org.bukkit.potion.PotionEffect; import java.util.UUID; public class PlayerUtils { private static final IPlayerManager playerManager = CloudNetDriver.getInstance().getServicesRegistry().getFirstService(IPlayerManager.class); public static void broadcastActionbar(String message) { for (Player player : Bukkit.getServer().getOnlinePlayers()) { sendActionbar(player, message); } } public static void sendActionbar(Player player, String message) { NMSCore.getUtils().sendActionbar(player, message); } public static void broadcastTitle(String top, String bottom, int fadeIn, int stay, int fadeOut, boolean chat) { try { for (Player p : Bukkit.getServer().getOnlinePlayers()) { sendTitle(top, bottom, fadeIn, stay, fadeOut, p); } if (chat) { Message.broadcast(top + " §8» " + bottom); } } catch (Exception e) { Message.broadcast(top + " §8» " + bottom); } } public static void sendTitle(String top, String bottom, int fadeIn, int stay, int fadeOut, Player player) { NMSCore.getUtils().sendTitle(top, bottom, fadeIn, stay, fadeOut, player); } @Deprecated public static void broadcastSound(Sound sound, float volume, float pitch) { for (Player p : Bukkit.getServer().getOnlinePlayers()) { p.playSound(p.getLocation(), sound, volume, pitch); } } public static void broadcastSound(UniversalSound sound, float volume, float pitch) { for (Player p : Bukkit.getServer().getOnlinePlayers()) { playSound(p, sound, volume, pitch); } } public static void playSound(Player p, UniversalSound sound, float volume, float pitch) { if (NMSCore.nmsVersion == NMSVersion.ONE_POINT_EIGHT) p.playSound(p.getLocation(), sound.getSound_1_8(), volume, pitch); else if (NMSCore.nmsVersion == NMSVersion.ONE_POINT_SIXTEEN) p.playSound(p.getLocation(), sound.getSound_1_16(), volume, pitch); } @Deprecated public static void playSound(Player p, Sound sound, float volume, float pitch) { p.playSound(p.getLocation(), sound, volume, pitch); } @Deprecated public static void playSoundAt(Location loc, Sound sound, float volume, float pitch) { loc.getWorld().playSound(loc, sound, volume, pitch); } @Deprecated public static User getLuckPermsUser(Player player) { try { return LuckPermsProvider.get().getUserManager().loadUser(player.getUniqueId()).get(); } catch (Exception e) { e.printStackTrace(); return null; } } @Deprecated public static User getLuckPermsUser(UUID player) { try { return LuckPermsProvider.get().getUserManager().loadUser(player).get(); } catch (Exception e) { e.printStackTrace(); return null; } } @Deprecated public static String getPlayerPrefix(Player player) { try { User u = getLuckPermsUser(player); assert u != null; CachedMetaData metaData = u.getCachedData().getMetaData(LuckPermsProvider.get().getContextManager().getQueryOptions(u).get()); return (metaData.getPrefix() == null ? "§7" : ChatColor.translateAlternateColorCodes('&', metaData.getPrefix())); } catch (Exception e) { e.printStackTrace(); return "§7"; } } @Deprecated public static String getPlayerPrefix(UUID player) { try { User u = getLuckPermsUser(player); assert u != null; CachedMetaData metaData = u.getCachedData().getMetaData(LuckPermsProvider.get().getContextManager().getQueryOptions(u).get()); return (metaData.getPrefix() == null ? "§7" : ChatColor.translateAlternateColorCodes('&', metaData.getPrefix())); } catch (Exception e) { e.printStackTrace(); return "§7"; } } public static Player search(String input) { for (Player p : Bukkit.getServer().getOnlinePlayers()) { String name = p.getName().toLowerCase(); if (!name.startsWith(input.toLowerCase())) continue; return p; } return null; } public static boolean isOnline(UUID uuid) { ICloudPlayer cloudPlayer = playerManager.getOnlinePlayer(uuid); return cloudPlayer != null; } public static double getDistanceFromPlayer(Player player1, Player player2){ return player1.getLocation().distance(player2.getLocation()); } public static void clearInventory(Player player) { player.getInventory().clear(); player.getInventory().setHelmet(null); player.getInventory().setChestplate(null); player.getInventory().setLeggings(null); player.getInventory().setBoots(null); } public static void clearEffects(Player player) { for (PotionEffect e : player.getActivePotionEffects()) { player.removePotionEffect(e.getType()); } } }
32,884
https://github.com/nmaletm/cavobjects/blob/master/data.php
Github Open Source
Open Source
Apache-2.0
2,015
cavobjects
nmaletm
PHP
Code
635
4,105
<?php $server = 'http://cavobjects.storn.es/'; if ($_GET['render']) { $server = 'http://www.cavobject.com/'; } $serverPublic = 'http://www.cavobject.com/'; $gallery = new Gallery(); $i = 1; $object = new Object(1); $object->initGallery('Spider/spider-%d.jpg', 2); $object->setName('Spider'); $object->setDate('25/12/2014'); $object->setMaterials(array('cork stopper', 'cava wire')); $object->setTools(array('pliers', 'knife', 'pen')); $object->setMark(5); $object->setDifficulty(4); $gallery->addObject($object); $object = new Object(2); $object->initGallery('Balloon/ballon-%d.jpg', 2); $object->setName('Ballon'); $object->setDate('30/12/2014'); $object->setMaterials(array('cork stopper', 'cava wire', 'Trovit ball')); $object->setTools(array('pliers', 'knife')); $object->setMark(7); $object->setDifficulty(5); $gallery->addObject($object); $object = new Object(3); $object->initGallery('Chair/chair-%d.jpg', 3); $object->setName('Chair'); $object->setDate('06/01/2015'); $object->setMaterials(array('cork stopper', 'cava wire', 'Magnum After Dinner paper')); $object->setTools(array('pliers', 'knife')); $object->setMark(6); $object->setDifficulty(6); $gallery->addObject($object); $object = new Object(4); $object->initGallery('Bear/bear-%d.jpg', 3); $object->setName('Bear'); $object->setDate('18/01/2015'); $object->setMaterials(array('cork stopper', 'cava wire', 'Magnum After Dinner paper')); $object->setTools(array('pliers', 'knife', 'pen')); $object->setMark(2); $object->setDifficulty(2); $gallery->addObject($object); $object = new Object(5); $object->initGallery('Man-stand-up/man-stand-up-%d.jpg', 4); $object->setName('Man (stand up)'); $object->setDate('18/01/2015'); $object->setMaterials(array('cork stopper', 'cava wire', 'Magnum After Dinner paper')); $object->setTools(array('pliers', 'knife', 'pen')); $object->setMark(4); $object->setDifficulty(6); $gallery->addObject($object); $object = new Object(6); $object->initGallery('Man-sit-down/man-sit-down-%d.jpg', 2); $object->setName('Man (sit down)'); $object->setDate('18/01/2015'); $object->setMaterials(array('cork stopper', 'cava wire', 'Magnum After Dinner paper')); $object->setTools(array('pliers', 'knife', 'pen')); $object->setMark(4); $object->setDifficulty(6); $gallery->addObject($object); $object = new Object(7); $object->initGallery('Chairlift/chairlift-%d.jpg', 4); $object->setName('Chairlift'); $object->setDate('01/02/2015'); $object->setMaterials(array('cork stopper', 'cava wire', 'cava cap blocker')); $object->setTools(array('pliers', 'knife', 'pen', 'iron rasp')); $object->setMark(6); $object->setDifficulty(8); $gallery->addObject($object); $object = new Object(8); $object->initGallery('Plane/plane-%d.jpg', 6); $object->setName('Plane'); $object->setDate('07/02/2015'); $object->setMaterials(array('cork stopper', 'cava wire', 'Magnum After Dinner paper', 'Magnum stick', 'water bottle cap')); $object->setTools(array('pliers', 'knife', 'pen', 'scissors')); $object->setMark(7); $object->setDifficulty(6); $gallery->addObject($object); $object = new Object(9); $object->initGallery('Sailboat/sailboat-%d.jpg', 3); $object->setName('Sailboat'); $object->setDate('08/02/2015'); $object->setMaterials(array('cork stopper', 'cava wire', 'toothpick')); $object->setTools(array('pliers', 'knife', 'scissors', 'adhesive tape', 'pen')); $object->setMark(3); $object->setDifficulty(2); $gallery->addObject($object); $object = new Object(10); $object->initGallery('Bike/bike-%d.jpg', 4); $object->setName('Bike'); $object->setDate('08/02/2015'); $object->setMaterials(array('cork stopper', 'cava wire')); $object->setTools(array('pliers', 'knife')); $object->setMark(7); $object->setDifficulty(8); $gallery->addObject($object); $object = new Object(11); $object->initGallery('Boat/boat-%d.jpg', 4); $object->setName('Boat'); $object->setDate('10/02/2015'); $object->setMaterials(array('cork stopper', 'cava wire')); $object->setTools(array('pliers', 'knife')); $object->setMark(3); $object->setDifficulty(4); $gallery->addObject($object); $object = new Object(12); $object->initGallery('Dog/dog-%d.jpg', 4); $object->setName('Dog'); $object->setDate('11/02/2015'); $object->setMaterials(array('cork stopper', 'cava wire')); $object->setTools(array('pliers', 'knife', 'pen')); $object->setMark(3); $object->setDifficulty(4); $gallery->addObject($object); $object = new Object(13); $object->initGallery('Car/car-%d.jpg', 6); $object->setName('Car'); $object->setDate('16/02/2015'); $object->setMaterials(array('cork stopper', 'cava wire')); $object->setTools(array('pliers', 'knife', 'pen')); $object->setMark(3); $object->setDifficulty(4); $gallery->addObject($object); $object = new Object(14); $object->initGallery('Moto/moto-%d.jpg', 5); $object->setName('Motorbike'); $object->setDate('19/02/2015'); $object->setMaterials(array('cork stopper', 'cava wire')); $object->setTools(array('pliers', 'knife', 'pens')); $object->setMark(5); $object->setDifficulty(8); $gallery->addObject($object); $object = new Object(15); $object->initGallery('Windmill/windmill-%d.jpg', 4); $object->setName('Windmill'); $object->setDate('23/02/2015'); $object->setMaterials(array('cork stopper', 'cava wire')); $object->setTools(array('pliers', 'knife', 'pens','Magnum After Dinner paper')); $object->setMark(5); $object->setDifficulty(3); $gallery->addObject($object); $object = new Object(16); $object->initGallery('Mouse/mouse-%d.jpg', 5); $object->setName('Computer mouse'); $object->setDate('27/02/2015'); $object->setMaterials(array('cork stopper', 'cava wire')); $object->setTools(array('pliers', 'knife', 'pens')); $object->setMark(6); $object->setDifficulty(1); $gallery->addObject($object); $object = new Object(17); $object->initGallery('Keyboard/keyboard-%d.jpg', 3); $object->setName('Computer keyboard'); $object->setDate('27/02/2015'); $object->setMaterials(array('cork stopper', 'cava wire')); $object->setTools(array('pliers', 'knife', 'pens')); $object->setMark(6); $object->setDifficulty(1); $gallery->addObject($object); $object = new Object(18); $object->initGallery('OldTv/old-tv-%d.jpg', 6); $object->setName('Old television'); $object->setDate('27/02/2015'); $object->setMaterials(array('cork stopper', 'cava wire')); $object->setTools(array('pliers', 'knife', 'pens')); $object->setMark(8); $object->setDifficulty(1); $gallery->addObject($object); $object = new Object(19); $object->initGallery('Headphone/headphone-%d.jpg', 4); $object->setName('Headphone'); $object->setDate('28/02/2015'); $object->setMaterials(array('cork stopper', 'cava wire')); $object->setTools(array('pliers', 'knife')); $object->setMark(8); $object->setDifficulty(2); $gallery->addObject($object); $object = new Object(20); $object->initGallery('Laptop/laptop-%d.jpg', 4); $object->setName('Laptop'); $object->setDate('01/03/2015'); $object->setMaterials(array('cork stopper', 'cava wire')); $object->setTools(array('pliers', 'knife', 'pens')); $object->setMark(7); $object->setDifficulty(2); $gallery->addObject($object); $object = new Object(21); $object->initGallery('Woman/woman-%d.jpg', 3); $object->setName('Woman'); $object->setDate('01/03/2015'); $object->setMaterials(array('cork stopper', 'cava wire')); $object->setTools(array('pliers', 'knife', 'pens')); $object->setMark(1); $object->setDifficulty(6); $gallery->addObject($object); $object = new Object(22); $object->initGallery('Ketchup/ketchup-%d.jpg', 5); $object->setName('Ketchup'); $object->setDate('05/03/2015'); $object->setMaterials(array('cork stopper')); $object->setTools(array('pliers', 'knife', 'pens')); $object->setMark(6); $object->setDifficulty(4); $gallery->addObject($object); $object = new Object(23); $object->initGallery('Lamp/lamp-%d.jpg', 5); $object->setName('Lamp'); $object->setDate('16/03/2015'); $object->setMaterials(array('cork stopper', 'cava wire')); $object->setTools(array('pliers', 'knife', 'pens')); $object->setMark(8); $object->setDifficulty(7); $gallery->addObject($object); $object = new Object(24); $object->initGallery('Digger/digger-%d.jpg', 4); $object->setName('Digger'); $object->setDate('16/03/2015'); $object->setMaterials(array('cork stopper', 'cava wire', 'cava crown cork')); $object->setTools(array('pliers', 'knife', 'pens')); $object->setMark(8); $object->setDifficulty(9); $gallery->addObject($object); $object = new Object(25); $object->initGallery('Wineglass/wineglass-%d.jpg', 4); $object->setName('Wineglass'); $object->setDate('16/03/2015'); $object->setMaterials(array('cork stopper')); $object->setTools(array('knife', 'pens')); $object->setMark(4); $object->setDifficulty(7); $gallery->addObject($object); $object = new Object(26); $object->initGallery('London-phone/london-phone-%d.jpg', 2); $object->setName('London phone'); $object->setDate('16/03/2015'); $object->setMaterials(array('cork stopper')); $object->setTools(array('knife', 'pens')); $object->setMark(5); $object->setDifficulty(4); $gallery->addObject($object); $object = new Object(27); $object->initGallery('Watch/watch-%d.jpg', 3); $object->setName('Watch'); $object->setDate('20/03/2015'); $object->setMaterials(array('cork stopper', 'cava wire')); $object->setTools(array('pliers', 'knife', 'pens')); $object->setMark(5); $object->setDifficulty(4); $gallery->addObject($object); $object = new Object(28); $object->initGallery('Teo-monster/teo-monster-%d.jpg', 4); $object->setName('Teo monster'); $object->setDate('20/03/2015'); $object->setMaterials(array('cork stopper', 'cava wire')); $object->setTools(array('pliers', 'knife', 'pens')); $object->setMark(5); $object->setDifficulty(3); $gallery->addObject($object); $object = new Object(29); $object->initGallery('Shaver/shaver-%d.jpg', 3); $object->setName('Shaver'); $object->setDate('24/03/2015'); $object->setMaterials(array('cork stopper', 'cava wire')); $object->setTools(array('pliers', 'knife', 'pens')); $object->setMark(7); $object->setDifficulty(6); $gallery->addObject($object); $object = new Object(30); $object->initGallery('Sun/sun-%d.jpg', 3); $object->setName('Sun'); $object->setDate('24/03/2015'); $object->setMaterials(array('cork stopper', 'cava wire')); $object->setTools(array('pliers', 'knife', 'pens')); $object->setMark(3); $object->setDifficulty(4); $gallery->addObject($object); $object = new Object(31); $object->initGallery('Sailboat2/sailboat2-%d.jpg', 5); $object->setName('Sailboat'); $object->setDate('25/12/2015'); $object->setMaterials(array('cork stopper', 'cava wire', 'toothpick')); $object->setTools(array('pliers', 'knife')); $object->setMark(8); $object->setDifficulty(7); $gallery->addObject($object); $object = new Object(32); $object->initGallery('Scooter/scooter-%d.jpg', 3); $object->setName('Scooter'); $object->setDate('25/12/2015'); $object->setMaterials(array('cork stopper', 'cava wire')); $object->setTools(array('pliers', 'knife')); $object->setMark(8); $object->setDifficulty(5); $gallery->addObject($object);
23,328
https://github.com/trevorflanagan/dimensiondata-cloud-api/blob/master/src/main/java/com/dimensiondata/cloud/client/http/ImageServiceImpl.java
Github Open Source
Open Source
Apache-2.0
2,016
dimensiondata-cloud-api
trevorflanagan
Java
Code
128
530
package com.dimensiondata.cloud.client.http; import com.dimensiondata.cloud.client.ImageService; import com.dimensiondata.cloud.client.OrderBy; import com.dimensiondata.cloud.client.Param; import com.dimensiondata.cloud.client.model.*; import javax.xml.bind.JAXBElement; import javax.xml.namespace.QName; public class ImageServiceImpl implements ImageService { private final HttpClient httpClient; public ImageServiceImpl(String baseUrl) { httpClient = new HttpClient(baseUrl); } @Override public OsImages listOsImages(int pageSize, int pageNumber, OrderBy orderBy) { // TODO validate parameters return httpClient.get("image/osImage", OsImages.class, new Param(Param.PAGE_SIZE, pageSize), new Param(Param.PAGE_NUMBER, pageNumber), new Param(Param.ORDER_BY, orderBy.concatenateParameters())); } @Override public OsImageType getOsImage(String id) { return httpClient.get("image/osImage/" + id, OsImageType.class); } @Override public CustomerImages listCustomerImages(int pageSize, int pageNumber, OrderBy orderBy) { // TODO validate parameters return httpClient.get("image/customerImage", CustomerImages.class, new Param(Param.PAGE_SIZE, pageSize), new Param(Param.PAGE_NUMBER, pageNumber), new Param(Param.ORDER_BY, orderBy.concatenateParameters())); } @Override public CustomerImageType getCustomerImage(String id) { return httpClient.get("image/customerImage/" + id, CustomerImageType.class); } @Override public ResponseType editImageMetadata(ImageMetadataType imageMetadata) { return httpClient.post("image/editImageMetadata", new JAXBElement<>(new QName(HttpClient.DEFAULT_NAMESPACE, "imageMetadata"), ImageMetadataType.class, imageMetadata), ResponseType.class); } }
39,875
https://github.com/masud-technope/ACER-Replication-Package-ASE2017/blob/master/corpus/class/sling/1567.java
Github Open Source
Open Source
MIT
null
ACER-Replication-Package-ASE2017
masud-technope
Java
Code
225
522
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not 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 org.apache.sling.testing.mock.jcr; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import javax.jcr.RepositoryException; import javax.jcr.Workspace; import javax.jcr.observation.ObservationManager; import org.junit.Before; import org.junit.Test; public class MockWorkspaceTest { private Workspace underTest; @Before public void setUp() { underTest = MockJcr.newSession().getWorkspace(); } @Test public void testName() { assertEquals(MockJcr.DEFAULT_WORKSPACE, underTest.getName()); } @Test public void testNameSpaceRegistry() throws RepositoryException { assertNotNull(underTest.getNamespaceRegistry()); } @Test public void testObservationManager() throws RepositoryException { // just mage sure listener methods can be called, although they do // nothing ObservationManager observationManager = underTest.getObservationManager(); observationManager.addEventListener(null, 0, null, false, null, null, false); observationManager.removeEventListener(null); } @Test public void testNodeTypeManager() throws RepositoryException { assertNotNull(underTest.getNodeTypeManager()); } }
9,787
https://github.com/Ray0218/JLYKit/blob/master/Example/JLYKit/JLYPushRouter.h
Github Open Source
Open Source
MIT
2,016
JLYKit
Ray0218
C
Code
28
89
// // JLYPushRouter.h // JLYKit // // Created by 袁宁 on 2016/11/24. // Copyright © 2016年 HappyiOSYuan. All rights reserved. // #import <JLYKit/JLYBaseRouter.h> @interface JLYPushRouter : JLYBaseRouter @end
34,840
https://github.com/czahoi/XUnity.AutoTranslator/blob/master/src/XUnity.AutoTranslator.Plugin.Core/TemplatedString.cs
Github Open Source
Open Source
LicenseRef-scancode-proprietary-license, MIT
2,023
XUnity.AutoTranslator
czahoi
C#
Code
276
768
using System.Collections.Generic; namespace XUnity.AutoTranslator.Plugin.Core { internal class TemplatedString { public TemplatedString( string template, Dictionary<string, string> arguments ) { Template = template; Arguments = arguments; } public string Template { get; private set; } public Dictionary<string, string> Arguments { get; private set; } public string Untemplate( string text ) { foreach( var kvp in Arguments ) { text = text.Replace( kvp.Key, kvp.Value ); } return text; } public string PrepareUntranslatedText( string untranslatedText ) { foreach( var kvp in Arguments ) { var key = kvp.Key; var translatorFriendlyKey = CreateTranslatorFriendlyKey( key ); untranslatedText = untranslatedText.Replace( key, translatorFriendlyKey ); } return untranslatedText; } public string FixTranslatedText( string translatedText, bool useTranslatorFriendlyArgs ) { foreach( var kvp in Arguments ) { var key = kvp.Key; var translatorFriendlyKey = useTranslatorFriendlyArgs ? CreateTranslatorFriendlyKey( key ) : key; translatedText = ReplaceApproximateMatches( translatedText, translatorFriendlyKey, key ); } return translatedText; } public static string CreateTranslatorFriendlyKey( string key ) { var c = key[ 2 ]; var translatorFriendlyKey = "ZM" + (char)( c + 2 ) + "Z"; return translatorFriendlyKey; } public static string ReplaceApproximateMatches( string translatedText, string translatorFriendlyKey, string key ) { var tfKeyMaxIndex = translatorFriendlyKey.Length - 1; var cidx = tfKeyMaxIndex; var endIndex = tfKeyMaxIndex; var maxIndex = translatedText.Length - 1; for (int i = maxIndex; i >= 0; i--) { var c = translatedText[i]; if (c == ' ' || c == ' ') continue; if ((c = char.ToUpperInvariant(c)) == char.ToUpperInvariant(translatorFriendlyKey[cidx]) || c == char.ToUpperInvariant(translatorFriendlyKey[cidx = tfKeyMaxIndex])) { if (cidx == tfKeyMaxIndex) endIndex = i; cidx--; } if (cidx >= 0) continue; var lengthOfFriendlyKeyPlusSpaces = (endIndex + 1) - i; translatedText = translatedText.Remove(i, lengthOfFriendlyKeyPlusSpaces).Insert(i, key); cidx = tfKeyMaxIndex; } return translatedText; } } }
8,036
https://github.com/ForsakenW/forsaken/blob/master/ProjectX/finger.cpp
Github Open Source
Open Source
MIT
2,020
forsaken
ForsakenW
C++
Code
83
229
#include <objbase.h> #include "fingers.h" extern "C" BOOL ValidFingerPrint( char *filename ) { IFingerPrint* fp = NULL; BOOL success = FALSE; HRESULT hr; ::CoInitialize( NULL ); //may not be needed if you have already done it in your code. hr = ::CoCreateInstance(CLSID_FingerPrint, NULL, CLSCTX_INPROC_SERVER, IID_IFingerPrint, (void**) &fp ); if( FAILED(hr) ) { //fail fingerprint verification } else { success = SUCCEEDED(fp->Verify( (const unsigned char *)filename)); fp->Release(); //fingerprint verified - do game code } ::CoUninitialize(); //only needed if you called CoInitialize() return( success ); }
37,591
https://github.com/Otto-J/arco-design-vue/blob/master/packages/web-vue/components/trigger/context.ts
Github Open Source
Open Source
MIT
2,021
arco-design-vue
Otto-J
TypeScript
Code
44
118
import type { InjectionKey } from 'vue'; export interface TriggerContext { onMouseenter: () => void; onMouseleave: () => void; onFocusin: () => void; onFocusout: () => void; addChildRef: (ref: any) => void; removeChildRef: (ref: any) => void; } export const triggerInjectionKey: InjectionKey<TriggerContext> = Symbol('ArcoTrigger');
18,857
https://github.com/TrueCar/gluestick/blob/master/packages/gluestick/src/logger.js
Github Open Source
Open Source
MIT
2,020
gluestick
TrueCar
JavaScript
Code
141
352
// @flow import type { BaseLogger } from './types'; const util = require('util'); const loggerFactory = (type: string): ((values: Array<*>) => void) => { if (process.env.NODE_ENV === 'production') { return (...values) => { const log = `${type.toUpperCase()}: ${values.reduce((prev, curr) => { return prev.concat( typeof curr === 'string' ? curr : util.inspect(curr, { depth: 4 }), ); }, '')}`; process.stdout.write(`${log}\n`); }; } return (...values) => { const stringfiedValues = JSON.stringify( values, (key: string, value: any) => { return typeof value === 'function' ? `[Function: ${value.name}]` : value; }, ); // check needed for Flow, but this also assumes we're in a subprocess, which may not be // true in the near future if (process.send) { process.send({ type, value: stringfiedValues }); } }; }; const logger: BaseLogger = { info: loggerFactory('info'), success: loggerFactory('success'), error: loggerFactory('error'), warn: loggerFactory('warn'), debug: loggerFactory('debug'), }; export default logger;
8,797
https://github.com/frbl/PI-Web-API-Client-R/blob/master/R/PISubstatus.r
Github Open Source
Open Source
Apache-2.0
2,021
PI-Web-API-Client-R
frbl
R
Code
100
299
PISubstatus <- function(substatus = NULL, message = NULL, webException = NULL) { if (is.null(substatus) == FALSE) { if (check.integer(substatus) == FALSE) { return (print(paste0("Error: substatus must be an integer."))) } } if (is.null(message) == FALSE) { if (is.character(message) == FALSE) { return (print(paste0("Error: message must be a string."))) } } if (is.null(webException) == FALSE) { className <- attr(webException, "className") if ((is.null(className)) || (className != "PIWebException")) { return (print(paste0("Error: the class from the parameter webException should be PIWebException."))) } } value <- list( Substatus = substatus, Message = message, WebException = webException) valueCleaned <- rmNullObs(value) attr(valueCleaned, "className") <- "PISubstatus" return(valueCleaned) }
47,777
https://github.com/harshwinklix/winklix/blob/master/app/controllers/common/Common.js
Github Open Source
Open Source
MIT
null
winklix
harshwinklix
JavaScript
Code
651
1,961
const NewsModel = require('../../models/news') const BlogModel = require('../../models/blogs') const CmsModel = require('../../models/user/cms') const StateModel = require('../../models/user/state') const walletModel = require('../../models/wallet') const base64Img = require('base64-img') const sharp = require ('sharp') const fs = require('fs') var jwt = require('jsonwebtoken'); class Common { constructor() { return { getBlogs: this.getBlogs.bind(this), getNews: this.getNews.bind(this), viewBlogs: this.viewBlogs.bind(this), viewNews: this.viewNews.bind(this), _uploadBase64image: this._uploadBase64image.bind(this), _validateBase64: this._validateBase64.bind(this), getCms: this.getCms.bind(this), viewCms: this.viewCms.bind(this), } } async getNews(req, res) { try { let options = { page: Number(req.body.page) || 1, limit: Number(req.body.limit) || 10, sort: { createdAt: -1 }, lean: true, } let query = {} if (req.body.searchData ){ query = { $or: [{ title: { $regex: req.body.searchData, $options: "i" } }, { content: { $regex: req.body.searchData, $options: "i" } }] } } let data = await NewsModel.paginate(query, options) // console.log("news", data) res.json({ code: 200, success: true, message: "Get list successfully ", data: data }) } catch (error) { console.log("Error in catch", error) res.status(500).json({ success: false, message: "Somthing went wrong", }) } } async viewNews(req, res) { try { if(!req.query._id){ res.json({ code: 400, success: false, message: "_id is required", data: data }) }else{ let query = {_id:req.query._id, status: 'active' } let data = await NewsModel.findOne(query) // console.log("NewsModel", data) res.json({ code: 200, success: true, message: "Get data successfully ", data: data }) } } catch (error) { console.log("Error in catch", error) res.status(500).json({ success: false, message: "Somthing went wrong", }) } } async getBlogs(req, res) { try { let options = { page: Number(req.body.page) || 1, limit: Number(req.body.limit) || 10, sort: { createdAt: -1 }, lean: true, } let query = {} if (req.body.searchData ){ query = { $or: [{ title: { $regex: req.body.searchData, $options: "i" } }, { content: { $regex: req.body.searchData, $options: "i" } }] } } console.log("req.body.searchData",req.body) let data = await BlogModel.paginate(query, options) // console.log("news", data) res.json({ code: 200, success: true, message: "Get list successfully ", data: data }) } catch (error) { console.log("Error in catch", error) res.status(500).json({ success: false, message: "Somthing went wrong", }) } } async viewBlogs(req, res) { try { if(!req.query._id){ res.json({ code: 400, success: false, message: "_id is required", data: data }) }else{ let query = {_id:req.query._id, status: 'active' } let data = await BlogModel.findOne(query) // console.log("BlogModel", data) res.json({ code: 200, success: true, message: "Get data successfully ", data: data }) } } catch (error) { console.log("Error in catch", error) res.status(500).json({ success: false, message: "Somthing went wrong", }) } } async _uploadBase64image(base64,child_path) { try { let parant_path = 'public' let storagePath = `${parant_path}/${child_path}`; if (!fs.existsSync(parant_path)) { fs.mkdirSync(parant_path); } if(!fs.existsSync(storagePath)){ fs.mkdirSync(storagePath); } // console.log(global.globalPath,"............",'driver', storagePath) let filename =`${Date.now()}_image` let base64Image = await this._validateBase64(base64) let filepath = await base64Img.imgSync(base64, storagePath, filename); console.log("filepath", filepath) return filepath } catch (error) { console.error("error in _createWallet", error) } } async _validateBase64( base64Image, maxHeight = 640, maxWidth = 640 ){ try { const destructImage = base64Image.split(";"); const mimType = destructImage[0].split(":")[1]; const imageData = destructImage[1].split(",")[1]; let resizedImage = Buffer.from(imageData, "base64") resizedImage = await sharp(resizedImage).resize(maxHeight, maxWidth).toBuffer() return `data:${mimType};base64,${resizedImage.toString("base64")}` } catch (error) { console.error("error in _validateBase64", error) } } async getCms(req, res) { try { let query = {} let data = await CmsModel.find(query) // console.log("news", data) res.json({ code: 200, success: true, message: "Get list successfully ", data: data }) } catch (error) { console.log("Error in catch", error) res.status(500).json({ success: false, message: "Somthing went wrong", }) } } async getState(req, res) { try { let query = {} let data = await StateModel.find(query) // console.log("news", data) res.json({ code: 200, success: true, message: "Get list successfully ", data: data }) } catch (error) { console.log("Error in catch", error) res.status(500).json({ success: false, message: "Somthing went wrong", }) } } async viewCms(req, res) { try { if(req.query.type){ let data = await CmsModel.findOne({type:req.query.type}) res.json({ code: 200, success: true, message: "Get list successfully ", data: data }) }else{ res.json({ code: 400, success: false, message: "type is required "}) } // console.log("news", data) } catch (error) { console.log("Error in catch", error) res.status(500).json({ success: false, message: "Somthing went wrong", }) } } } module.exports = new Common();
19,317
https://github.com/Iamsdt/PSSD/blob/master/app/src/main/java/com/iamsdt/pssd/database/MyDatabase.kt
Github Open Source
Open Source
Apache-2.0
2,020
PSSD
Iamsdt
Kotlin
Code
49
149
/* * Developed By Shudipto Trafder * on 8/17/18 10:39 AM * Copyright (c) 2018 Shudipto Trafder. */ package com.iamsdt.pssd.database import androidx.room.Database import androidx.room.RoomDatabase import androidx.room.TypeConverters @TypeConverters(value = [Converters::class]) @Database(entities = [WordTable::class], version = 5, exportSchema = false) abstract class MyDatabase : RoomDatabase() { abstract val wordTableDao: WordTableDao }
5,269
https://github.com/Tim-Zhang/rust-protobuf/blob/master/protobuf-codegen/src/gen/message.rs
Github Open Source
Open Source
MIT
2,022
rust-protobuf
Tim-Zhang
Rust
Code
1,642
7,876
use std::fmt; use protobuf::descriptor::*; use protobuf::reflect::FileDescriptor; use protobuf::reflect::MessageDescriptor; use protobuf_parse::snake_case; use crate::customize::ctx::CustomizeElemCtx; use crate::customize::ctx::SpecialFieldPseudoDescriptor; use crate::customize::rustproto_proto::customize_from_rustproto_for_message; use crate::gen::code_writer::*; use crate::gen::descriptor::write_fn_descriptor; use crate::gen::enums::*; use crate::gen::field::FieldGen; use crate::gen::field::FieldKind; use crate::gen::file_and_mod::FileAndMod; use crate::gen::inside::protobuf_crate_path; use crate::gen::oneof::OneofGen; use crate::gen::oneof::OneofVariantGen; use crate::gen::protoc_insertion_point::write_protoc_insertion_point_for_message; use crate::gen::protoc_insertion_point::write_protoc_insertion_point_for_special_field; use crate::gen::rust::ident::RustIdent; use crate::gen::rust::ident_with_path::RustIdentWithPath; use crate::gen::rust::rel_path::RustRelativePath; use crate::gen::rust::snippets::expr_vec_with_capacity_const; use crate::gen::rust::snippets::EXPR_NONE; use crate::gen::rust_types_values::*; use crate::gen::scope::MessageWithScope; use crate::gen::scope::RootScope; use crate::gen::scope::WithScope; use crate::Customize; /// Protobuf message Rust type name #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct RustTypeMessage(pub RustIdentWithPath); impl fmt::Display for RustTypeMessage { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt(&self.0, f) } } impl<S: Into<RustIdentWithPath>> From<S> for RustTypeMessage { fn from(s: S) -> Self { RustTypeMessage(s.into()) } } impl RustTypeMessage { /// Code which emits default instance. pub fn default_instance(&self, customize: &Customize) -> String { format!( "<{} as {}::Message>::default_instance()", self.0, protobuf_crate_path(customize) ) } } /// Message info for codegen pub(crate) struct MessageGen<'a> { file_descriptor: &'a FileDescriptor, message_descriptor: MessageDescriptor, pub message: &'a MessageWithScope<'a>, pub root_scope: &'a RootScope<'a>, pub fields: Vec<FieldGen<'a>>, pub lite_runtime: bool, customize: CustomizeElemCtx<'a>, path: &'a [i32], info: Option<&'a SourceCodeInfo>, } impl<'a> MessageGen<'a> { pub fn new( file_descriptor: &'a FileDescriptor, message: &'a MessageWithScope<'a>, root_scope: &'a RootScope<'a>, parent_customize: &CustomizeElemCtx<'a>, path: &'a [i32], info: Option<&'a SourceCodeInfo>, ) -> anyhow::Result<MessageGen<'a>> { let message_descriptor = file_descriptor .message_by_package_relative_name(&format!("{}", message.protobuf_name_to_package())) .unwrap(); let customize = parent_customize.child( &customize_from_rustproto_for_message(message.message.proto().options.get_or_default()), &message.message, ); static FIELD_NUMBER: protobuf::rt::Lazy<i32> = protobuf::rt::Lazy::new(); let field_number = *FIELD_NUMBER.get(|| { protobuf::reflect::MessageDescriptor::for_type::<DescriptorProto>() .field_by_name("field") .expect("`field` must exist") .proto() .number() }); let fields: Vec<_> = message .fields() .into_iter() .enumerate() .map(|(id, field)| { let mut path = path.to_vec(); path.extend_from_slice(&[field_number, id as i32]); FieldGen::parse(field, root_scope, &customize, path, info) }) .collect::<anyhow::Result<Vec<_>>>()?; let lite_runtime = customize.for_elem.lite_runtime.unwrap_or_else(|| { message.file_descriptor().proto().options.optimize_for() == file_options::OptimizeMode::LITE_RUNTIME }); Ok(MessageGen { message_descriptor, file_descriptor, message, root_scope, fields, lite_runtime, customize, path, info, }) } fn rust_name(&self) -> RustIdent { self.message.rust_name() } fn mod_name(&self) -> RustRelativePath { self.message.scope.rust_path_to_file() } pub fn file_and_mod(&self) -> FileAndMod { self.message .scope .file_and_mod(self.customize.for_elem.clone()) } fn oneofs(&'a self) -> Vec<OneofGen<'a>> { self.message .oneofs() .into_iter() .map(|oneof| OneofGen::parse(self, oneof, &self.customize)) .collect() } fn required_fields(&'a self) -> Vec<&'a FieldGen> { self.fields .iter() .filter(|f| match f.kind { FieldKind::Singular(ref singular) => singular.flag.is_required(), _ => false, }) .collect() } fn message_fields(&'a self) -> Vec<&'a FieldGen> { self.fields .iter() .filter(|f| f.proto_type == field_descriptor_proto::Type::TYPE_MESSAGE) .collect() } fn fields_except_oneof(&'a self) -> Vec<&'a FieldGen> { self.fields .iter() .filter(|f| match f.kind { FieldKind::Oneof(..) => false, _ => true, }) .collect() } fn fields_except_group(&'a self) -> Vec<&'a FieldGen> { self.fields .iter() .filter(|f| f.proto_type != field_descriptor_proto::Type::TYPE_GROUP) .collect() } fn fields_except_oneof_and_group(&'a self) -> Vec<&'a FieldGen> { self.fields .iter() .filter(|f| match f.kind { FieldKind::Oneof(..) => false, _ => f.proto_type != field_descriptor_proto::Type::TYPE_GROUP, }) .collect() } fn write_match_each_oneof_variant<F>(&self, w: &mut CodeWriter, cb: F) where F: Fn(&mut CodeWriter, &OneofVariantGen, &RustValueTyped), { for oneof in self.oneofs() { let variants = oneof.variants_except_group(); if variants.is_empty() { // Special case because // https://github.com/rust-lang/rust/issues/50642 continue; } w.if_let_stmt( "::std::option::Option::Some(ref v)", &format!("self.{}", oneof.oneof.field_name())[..], |w| { w.match_block("v", |w| { for variant in variants { let ref field = variant.field; let (refv, vtype) = if field.elem_type_is_copy() { ("v", variant.rust_type(&self.file_and_mod())) } else { ("ref v", variant.rust_type(&self.file_and_mod()).ref_type()) }; w.case_block( format!("&{}({})", variant.path(&self.file_and_mod()), refv), |w| { cb( w, &variant, &RustValueTyped { value: "v".to_owned(), rust_type: vtype.clone(), }, ); }, ); } }); }, ); } } fn write_write_to_with_cached_sizes(&self, w: &mut CodeWriter) { let sig = format!( "write_to_with_cached_sizes(&self, os: &mut {protobuf_crate}::CodedOutputStream<'_>) -> {protobuf_crate}::Result<()>", protobuf_crate=protobuf_crate_path(&self.customize.for_elem), ); w.def_fn(&sig, |w| { // To have access to its methods but not polute the name space. for f in self.fields_except_oneof_and_group() { f.write_message_write_field("os", w); } self.write_match_each_oneof_variant(w, |w, variant, v| { variant .field .write_write_element(variant.elem(), w, "os", v); }); w.write_line("os.write_unknown_fields(self.special_fields.unknown_fields())?;"); w.write_line("::std::result::Result::Ok(())"); }); } fn write_default_instance_lazy(&self, w: &mut CodeWriter) { w.lazy_static_decl_get_simple( "instance", &format!("{}", self.rust_name()), &format!("{}::new", self.rust_name()), &format!("{}", protobuf_crate_path(&self.customize.for_elem)), ); } fn write_default_instance_static(&self, w: &mut CodeWriter) { w.stmt_block( &format!( "static instance: {} = {}", self.rust_name(), self.rust_name() ), |w| { for f in &self.fields_except_oneof_and_group() { w.field_entry( &f.rust_name.to_string(), &f.kind .default(&self.customize.for_elem, &self.file_and_mod(), true), ); } for o in &self.oneofs() { w.field_entry(&o.oneof.field_name().to_string(), EXPR_NONE); } w.field_entry( "special_fields", &format!( "{}::SpecialFields::new()", protobuf_crate_path(&self.customize.for_elem) ), ); }, ); w.write_line("&instance"); } fn write_default_instance(&self, w: &mut CodeWriter) { w.def_fn( &format!("default_instance() -> &'static {}", self.rust_name()), |w| { let has_map_field = self.fields.iter().any(|f| match f.kind { FieldKind::Map(..) => true, _ => false, }); if has_map_field { self.write_default_instance_lazy(w) } else { self.write_default_instance_static(w) } }, ); } fn write_compute_size(&self, w: &mut CodeWriter) { // Append sizes of messages in the tree to the specified vector. // First appended element is size of self, and then nested message sizes. // in serialization order are appended recursively."); w.comment("Compute sizes of nested messages"); // there are unused variables in oneof w.allow(&["unused_variables"]); w.def_fn("compute_size(&self) -> u64", |w| { // To have access to its methods but not polute the name space. w.write_line("let mut my_size = 0;"); for field in self.fields_except_oneof_and_group() { field.write_message_compute_field_size("my_size", w); } self.write_match_each_oneof_variant(w, |w, variant, v| { variant .field .write_element_size(variant.elem(), w, v, "my_size"); }); w.write_line(&format!( "my_size += {}::rt::unknown_fields_size(self.special_fields.unknown_fields());", protobuf_crate_path(&self.customize.for_elem) )); w.write_line("self.special_fields.cached_size().set(my_size as u32);"); w.write_line("my_size"); }); } fn write_field_accessors(&self, w: &mut CodeWriter) { for f in self.fields_except_group() { f.write_message_single_field_accessors(w); } } fn write_impl_self(&self, w: &mut CodeWriter) { w.impl_self_block(&format!("{}", self.rust_name()), |w| { w.pub_fn(&format!("new() -> {}", self.rust_name()), |w| { w.write_line("::std::default::Default::default()"); }); self.write_field_accessors(w); if !self.lite_runtime { w.write_line(""); self.write_generated_message_descriptor_data(w); } }); } fn write_unknown_fields(&self, w: &mut CodeWriter) { let sig = format!( "special_fields(&self) -> &{}::SpecialFields", protobuf_crate_path(&self.customize.for_elem) ); w.def_fn(&sig, |w| { w.write_line("&self.special_fields"); }); w.write_line(""); let sig = format!( "mut_special_fields(&mut self) -> &mut {}::SpecialFields", protobuf_crate_path(&self.customize.for_elem) ); w.def_fn(&sig, |w| { w.write_line("&mut self.special_fields"); }); } fn write_merge_from(&self, w: &mut CodeWriter) { let sig = format!( "merge_from(&mut self, is: &mut {}::CodedInputStream<'_>) -> {}::Result<()>", protobuf_crate_path(&self.customize.for_elem), protobuf_crate_path(&self.customize.for_elem), ); w.def_fn(&sig, |w| { w.while_block("let Some(tag) = is.read_raw_tag_or_eof()?", |w| { w.match_block("tag", |w| { for f in &self.fields_except_group() { f.write_merge_from_field_case_block(w); } w.case_block("tag", |w| { w.write_line(&format!("{}::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?;", protobuf_crate_path(&self.customize.for_elem))); }); }); }); w.write_line("::std::result::Result::Ok(())"); }); } fn write_impl_message_full_fn_descriptor(&self, w: &mut CodeWriter) { write_fn_descriptor( &self.message.message, self.message.scope(), &self.customize.for_elem, w, ); } fn write_generated_message_descriptor_data(&self, w: &mut CodeWriter) { let sig = format!( "generated_message_descriptor_data() -> {}::reflect::GeneratedMessageDescriptorData", protobuf_crate_path(&self.customize.for_elem) ); w.fn_block( Visibility::Path(self.message.scope().rust_path_to_file().to_reverse()), &sig, |w| { let fields = self.fields_except_group(); let oneofs = self.oneofs(); w.write_line(&format!( "let mut fields = {};", expr_vec_with_capacity_const(fields.len()) )); w.write_line(&format!( "let mut oneofs = {};", expr_vec_with_capacity_const(oneofs.len()) )); for field in fields { field.write_push_accessor("fields", w); } for oneof in oneofs { w.write_line(&format!( "oneofs.push({}::generated_oneof_descriptor_data());", oneof.type_name_relative(&self.mod_name()) )); } w.write_line(&format!( "{}::reflect::GeneratedMessageDescriptorData::new_2::<{}>(", protobuf_crate_path(&self.customize.for_elem), self.rust_name(), )); w.indented(|w| { w.write_line(&format!("\"{}\",", self.message.name_to_package())); w.write_line("fields,"); w.write_line("oneofs,"); }); w.write_line(")"); }, ); } fn write_is_initialized(&self, w: &mut CodeWriter) { w.def_fn(&format!("is_initialized(&self) -> bool"), |w| { if !self.message.message.is_initialized_is_always_true() { // TODO: use single loop for f in self.required_fields() { f.write_if_self_field_is_none(w, |w| { w.write_line("return false;"); }); } for f in self.message_fields() { if let FieldKind::Map(..) = f.kind { // TODO w.comment("TODO: check map values are initialized"); continue; } f.write_for_self_field(w, "v", |w, _t| { w.if_stmt("!v.is_initialized()", |w| { w.write_line("return false;"); }); }); } } w.write_line("true"); }); } fn write_impl_message(&self, w: &mut CodeWriter) { w.impl_for_block( &format!("{}::Message", protobuf_crate_path(&self.customize.for_elem),), &format!("{}", self.rust_name()), |w| { w.write_line(&format!( "const NAME: &'static str = \"{}\";", self.message.message.name() )); w.write_line(""); self.write_is_initialized(w); w.write_line(""); self.write_merge_from(w); w.write_line(""); self.write_compute_size(w); w.write_line(""); self.write_write_to_with_cached_sizes(w); w.write_line(""); self.write_unknown_fields(w); w.write_line(""); w.def_fn(&format!("new() -> {}", self.rust_name()), |w| { w.write_line(&format!("{}::new()", self.rust_name())); }); w.write_line(""); w.def_fn("clear(&mut self)", |w| { for f in self.fields_except_group() { f.write_clear(w); } w.write_line("self.special_fields.clear();"); }); w.write_line(""); self.write_default_instance(w); }, ); } fn write_impl_message_full(&self, w: &mut CodeWriter) { w.impl_for_block( &format!( "{}::MessageFull", protobuf_crate_path(&self.customize.for_elem), ), &format!("{}", self.rust_name()), |w| { self.write_impl_message_full_fn_descriptor(w); }, ); } fn write_impl_value(&self, w: &mut CodeWriter) { w.impl_for_block( &format!( "{}::reflect::ProtobufValue", protobuf_crate_path(&self.customize.for_elem) ), &format!("{}", self.rust_name()), |w| { w.write_line(&format!( "type RuntimeType = {}::reflect::rt::RuntimeTypeMessage<Self>;", protobuf_crate_path(&self.customize.for_elem) )); }, ) } fn write_impl_display(&self, w: &mut CodeWriter) { w.impl_for_block( "::std::fmt::Display", &format!("{}", self.rust_name()), |w| { w.def_fn( "fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result", |w| { w.write_line(&format!( "{}::text_format::fmt(self, f)", protobuf_crate_path(&self.customize.for_elem) )); }, ); }, ); } fn supports_derive_partial_eq(&self) -> bool { // There's stack overflow in the compiler when struct has too many fields // https://github.com/rust-lang/rust/issues/40119 self.fields.len() <= 500 } fn write_struct(&self, w: &mut CodeWriter) { let mut derive = Vec::new(); if self.supports_derive_partial_eq() { derive.push("PartialEq"); } derive.extend(&["Clone", "Default", "Debug"]); w.derive(&derive); write_protoc_insertion_point_for_message( w, &self.customize.for_elem, &self.message_descriptor, ); w.pub_struct(&format!("{}", self.rust_name()), |w| { if !self.fields_except_oneof().is_empty() { w.comment("message fields"); for field in self.fields_except_oneof() { field.write_struct_field(w); } } if !self.oneofs().is_empty() { w.comment("message oneof groups"); for oneof in self.oneofs() { w.field_decl_vis( Visibility::Public, &oneof.oneof.field_name().to_string(), &oneof.full_storage_type().to_code(&self.customize.for_elem), ); } } w.comment("special fields"); let customize_special_fields = self .customize .child( &Customize::default(), &SpecialFieldPseudoDescriptor { message: &self.message.message, field: "special_fields", }, ) .for_elem; write_protoc_insertion_point_for_special_field( w, &customize_special_fields, &self.message_descriptor, "special_fields", ); w.pub_field_decl( "special_fields", &format!( "{}::SpecialFields", protobuf_crate_path(&self.customize.for_elem) ), ); }); } fn write_impl_default_for_amp(&self, w: &mut CodeWriter) { w.impl_args_for_block( &["'a"], "::std::default::Default", &format!("&'a {}", self.rust_name()), |w| { w.def_fn(&format!("default() -> &'a {}", self.rust_name()), |w| { w.write_line(&format!( "<{} as {}::Message>::default_instance()", self.rust_name(), protobuf_crate_path(&self.customize.for_elem), )); }); }, ); } fn write_dummy_impl_partial_eq(&self, w: &mut CodeWriter) { w.impl_for_block( "::std::cmp::PartialEq", &format!("{}", self.rust_name()), |w| { w.def_fn("eq(&self, _: &Self) -> bool", |w| { w.comment("https://github.com/rust-lang/rust/issues/40119"); w.unimplemented(); }); }, ); } pub fn write(&self, w: &mut CodeWriter) -> anyhow::Result<()> { w.all_documentation(self.info, self.path); self.write_struct(w); w.write_line(""); self.write_impl_default_for_amp(w); if !self.supports_derive_partial_eq() { w.write_line(""); self.write_dummy_impl_partial_eq(w); } w.write_line(""); self.write_impl_self(w); w.write_line(""); self.write_impl_message(w); if !self.lite_runtime { w.write_line(""); self.write_impl_message_full(w); } if !self.lite_runtime { w.write_line(""); self.write_impl_display(w); w.write_line(""); self.write_impl_value(w); } let mod_name = message_name_to_nested_mod_name(&self.message.message.name()); let oneofs = self.oneofs(); let nested_messages: Vec<_> = self .message .to_scope() .messages() .into_iter() .filter(|nested| { // ignore map entries, because they are not used in map fields !nested.is_map() }) .collect(); let nested_enums = self.message.to_scope().enums(); if !oneofs.is_empty() || !nested_messages.is_empty() || !nested_enums.is_empty() { w.write_line(""); w.write_line(&format!( "/// Nested message and enums of message `{}`", self.message.message.name() )); w.pub_mod(&mod_name.to_string(), |w| { let mut first = true; for oneof in &oneofs { w.write_line(""); oneof.write(w); } static NESTED_TYPE_NUMBER: protobuf::rt::Lazy<i32> = protobuf::rt::Lazy::new(); let nested_type_number = *NESTED_TYPE_NUMBER.get(|| { MessageDescriptor::for_type::<DescriptorProto>() .field_by_name("nested_type") .expect("`nested_type` must exist") .proto() .number() }); let mut path = self.path.to_vec(); path.extend(&[nested_type_number, 0]); for (id, nested) in nested_messages.iter().enumerate() { let len = path.len() - 1; path[len] = id as i32; if !first { w.write_line(""); } first = false; MessageGen::new( &self.file_descriptor, nested, self.root_scope, &self.customize, &path, self.info, ) // TODO: do not unwrap. .unwrap() .write(w) // TODO: do not unwrap. .unwrap(); } static ENUM_TYPE_NUMBER: protobuf::rt::Lazy<i32> = protobuf::rt::Lazy::new(); let enum_type_number = *ENUM_TYPE_NUMBER.get(|| { MessageDescriptor::for_type::<DescriptorProto>() .field_by_name("enum_type") .expect("`enum_type` must exist") .proto() .number() }); let len = path.len() - 2; path[len] = enum_type_number; for (id, enum_type) in self.message.to_scope().enums().iter().enumerate() { let len = path.len() - 1; path[len] = id as i32; if !first { w.write_line(""); } first = false; EnumGen::new( enum_type, &self.customize, self.root_scope, &path, self.info, ) .write(w); } }); } Ok(()) } } pub(crate) fn message_name_to_nested_mod_name(message_name: &str) -> RustIdent { let mod_name = snake_case(message_name); RustIdent::new(&mod_name) }
3,008
https://github.com/Icareconnect/Backend/blob/master/app/Model/RequestDate.php
Github Open Source
Open Source
MIT
null
Backend
Icareconnect
PHP
Code
35
124
<?php namespace App\Model; use Illuminate\Database\Eloquent\Model; class RequestDate extends Model { /** * Get the Request History From RequestHistory Model. */ public function requesthistory() { return $this->hasOne('App\Model\RequestHistory','request_id','request_id'); } public function request() { return $this->hasOne('App\Model\Request','id','request_id'); } }
30,697
https://github.com/OC-Bandung/newbirms/blob/master/app/Http/Controllers/ApiBIRMS.php
Github Open Source
Open Source
MIT
2,019
newbirms
OC-Bandung
PHP
Code
4,290
20,841
<?php namespace App\Http\Controllers; use App\Illuminate\Pagination\ArrayLengthAwarePaginator; use Illuminate\Http\Request; use App\Sirup; use App\Paketlng; use App\Paketpl; use Illuminate\Support\Facades\DB; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Input; use NestedJsonFlattener\Flattener\Flattener; class ApiBIRMS extends Controller { public function contractsAll() { $ocid = env('OCID'); $results = Sirup::selectRaw('sirupID, CONCAT(\'$ocid.\',\'s-\',tahun,\'-\',sirupID) AS ocid, tahun, nama, pagu') ->orderBy('sirupID') ->paginate(env('JSON_RESULTS_PER_PAGE', 40)); } /** * Creates paginator from a simple array coming from DB::select * https://stackoverflow.com/a/44090541 * Use url parameter per_page to increase page number * * @param $array * @param $request * @return ArrayLengthAwarePaginator */ public function arrayPaginator($array, $request) { $page = Input::get('page', 1); $perPage = Input::get('per_page', env('JSON_RESULTS_PER_PAGE', 40)); $offset = ($page * $perPage) - $perPage; return new ArrayLengthAwarePaginator(array_slice($array, $offset, $perPage, true), count($array), $perPage, $page, ['path' => $request->url(), 'query' => $request->query()]); } public function contractsPerYear($year) { return $this->itemsPerYear($year,"newcontract"); } public function packagesPerYear($year) { return $this->itemsPerYear($year,"package"); } public function itemsPerYear($year, $urlType) { //$results = Sirup::where("tahun", $year)->paginate(100); $ocid = env('OCID'); $dbplanning = env('DB_PLANNING'); $sql = 'SELECT CONCAT("'.$ocid.'","s-",tahun,"-",sirupID) AS ocid, tahun AS year, nama AS title, CONCAT("'.env('API_ENDPOINT').'", "/'.$urlType.'/", "'.env('OCID').'","s-",tahun,"-",sirupID) AS uri, pagu AS value FROM '.$dbplanning.'.tbl_sirup WHERE tahun = '.$year.' AND pagu <> 0 AND metode_pengadaan IN (1,2,3,4,5,6,10,11,12) AND isswakelola = 0 UNION SELECT CONCAT("'.$ocid.'","b-",'.$year.',"-",tbl_pekerjaan.pekerjaanID) AS ocid, '.$year.' AS year, namapekerjaan AS title, CONCAT("'.env('API_ENDPOINT').'", "/'.$urlType.'/", "'.env('OCID').'","b-",'.$year.',"-",tbl_pekerjaan.pekerjaanID) AS uri, anggaran AS value FROM '.$dbplanning.'.tbl_pekerjaan WHERE tahun = '.$year.' AND iswork = 1'; $results = $this->arrayPaginator(DB::select($sql), request()); return response() ->json($results) ->header('Access-Control-Allow-Origin', '*'); } /* get_pns function pns/{kewenangan}:{year} kewenangan attribut pa => 'Pengguna Anggaran' ppk => 'Pejabat Pembuat Komitmen' ppbj => 'Pejabat Pengadaan Barang Jasa' pphp => 'Pejabat Penerima Hasil Pekerjaan' pptk => 'Pejabat Pelaksana Teknis Pekerjaan' bpwal => 'Bendahara Pengeluaran SK Walikota' bppakpa => 'Bendahara Pengeluaran SK Pengguna Anggaran/Kuasa' kelkerja => 'Anggota Kelompok Kerja ULP' example : https:/birms.bandung.go.id/api/pns/pa:2017 */ function get_pns($kewenangan,$year) { $dbplanning = env('DB_PLANNING'); $dbcontract = env('DB_CONTRACT'); $dbmain = env('DB_PRIME'); switch ($kewenangan) { case "pa" : $sktipeID = 1; break; case "ppk" : $sktipeID = 2; break; case "ppbj" : $sktipeID = 3; break; case "pphp" : $sktipeID = 4; break; case "pptk" : $sktipeID = 5; break; case "bpwal" : $sktipeID = 6; break; case "bppakpa" : $sktipeID = 7; break; case "kelkerja" : $sktipeID = 8; break; default: $sktipeID = 1; } /*$sql = 'SELECT TRIM(identity_no) AS nip , fullname AS nama , ringkasan AS kewenangan , tglsk , nosk , tbl_skpd.unitID , tbl_skpd.nama AS skpdnama FROM 2016_birms_eproject_planning.tr_sk_user LEFT OUTER JOIN tbl_sk ON tr_sk_user.skID = tbl_sk.skID LEFT OUTER JOIN tbl_sk_tipe ON tbl_sk.sktipeID = tbl_sk_tipe.sktipeID LEFT OUTER JOIN :dbmain.tbl_user ON tr_sk_user.usrID = :dbmain.tbl_user.usrID LEFT OUTER JOIN :dbmain.tbl_skpd ON tbl_sk.skpdID = :dbmain.tbl_skpd.skpdID WHERE YEAR(tglsk) = :year AND tbl_sk.sktipeID = :sktipeID AND identity_no <> \'\' GROUP BY nip, nama, kewenangan, tglsk, nosk, unitID, skpdnama ORDER BY unitID , TRIM(nip)'; $results = DB::select($sql, ['dbplanning'=> $dbplanning, 'dbcontract' => $dbcontract, 'dbmain' => $dbmain, 'year' => $year,'sktipeID' => $sktipeID]);*/ $sql = 'SELECT TRIM(identity_no) AS nip , fullname AS nama , ringkasan AS kewenangan , tglsk , nosk , tbl_skpd.unitID , tbl_skpd.nama AS skpdnama FROM '.$dbplanning.'.tr_sk_user LEFT OUTER JOIN '.$dbplanning.'.tbl_sk ON tr_sk_user.skID = tbl_sk.skID LEFT OUTER JOIN '.$dbplanning.'.tbl_sk_tipe ON tbl_sk.sktipeID = tbl_sk_tipe.sktipeID LEFT OUTER JOIN '.$dbmain.'.tbl_user ON tr_sk_user.usrID = tbl_user.usrID LEFT OUTER JOIN '.$dbmain.'.tbl_skpd ON tbl_sk.skpdID = tbl_skpd.skpdID WHERE YEAR(tglsk) = '.$year.' AND tbl_sk.sktipeID = '.$sktipeID.' AND identity_no <> \'\' GROUP BY nip, fullname, kewenangan, tglsk, nosk, unitID, skpdnama ORDER BY unitID, TRIM(nip)'; $results = $this->arrayPaginator(DB::select($sql), request()); return response() ->json($results) ->header('Access-Control-Allow-Origin', '*'); } /*--- Start Data Map Packet By Kecamatan ---*/ public function get_kecamatan_count($year) { $dbplanning = env('DB_PLANNING'); $dbcontract = env('DB_CONTRACT'); $dbmain = env('DB_PRIME'); $sql = "SELECT unitID, UPPER(TRIM(SUBSTRING(nama, POSITION(' ' IN nama), LENGTH(nama)))) AS kecamatan, CONVERT(IFNULL( (SELECT COUNT(*) FROM ".env('DB_CONTRACT').".tpekerjaan WHERE administrative_area_level_3 = kecamatan AND ta = ".$year." GROUP BY administrative_area_level_3) ,0), CHAR(50)) AS summary FROM ".env('DB_PRIME').".tbl_skpd WHERE nama LIKE 'Kecamatan%'"; $results = DB::select($sql); return response() ->json($results) ->header('Access-Control-Allow-Origin', '*'); } public function get_kecamatan_value($year) { $dbplanning = env('DB_PLANNING'); $dbcontract = env('DB_CONTRACT'); $dbmain = env('DB_PRIME'); $sql = "SELECT unitID, UPPER(TRIM(SUBSTRING(nama, POSITION(' ' IN nama), LENGTH(nama)))) AS kecamatan, CONVERT(IFNULL( (SELECT SUM(anggaran) FROM ".env('DB_CONTRACT').".tpekerjaan WHERE administrative_area_level_3 = kecamatan AND ta = ".$year." GROUP BY administrative_area_level_3) ,0), CHAR(50)) AS summary FROM ".env('DB_PRIME').".tbl_skpd WHERE nama LIKE 'Kecamatan%'"; $results = DB::select($sql); return response() ->json($results) ->header('Access-Control-Allow-Origin', '*'); } /*--- End Data Map Packet By Kecamatan ---*/ /** * This is just the array-producing party of graph1 function. It is reused in both * graph1 and graph1_csv * @return array */ public function graph1_array() { $sql = 'SELECT tahun, (nilaikontrak/1000000000) AS nilaikontrak FROM '.env('DB_CONTRACT').'.vlelang_bypaket ORDER BY tahun ASC'; $rs1 = DB::select($sql); $rowdata = array(); $data = array(); foreach($rs1 as $row) { array_push($data, array($row->tahun, (float)$row->nilaikontrak)); } array_push($rowdata, array("name"=>"Tender", "data"=> $data)); $sql = 'SELECT tahun, (nilaikontrak/1000000000) AS nilaikontrak FROM '.env('DB_CONTRACT').'.vpl_bypaket ORDER BY tahun ASC'; $rs1 = DB::select($sql); $data = array(); foreach($rs1 as $row) { array_push($data, array($row->tahun, (float)$row->nilaikontrak)); } array_push($rowdata, array("name"=>"Non Tender", "data"=> $data)); $results = $rowdata; return $results; } /*--- Start Data Statistic ---*/ public function graph1() { return response() ->json($this->graph1_array()) ->header('Access-Control-Allow-Origin', '*'); } public function graph2($year) { $sql = 'SELECT ta, COUNT(*) AS paket FROM '.env('DB_CONTRACT').'.`tlelangumum` GROUP BY ta ORDER BY ta DESC LIMIT 1'; $rscheck1 = DB::select($sql); $sql = 'SELECT ta, COUNT(*) AS paket FROM '.env('DB_CONTRACT').'.`tpengadaan` WHERE pekerjaanstatus = 7 GROUP BY ta ORDER BY ta DESC LIMIT 1'; $rscheck2 = DB::select($sql); if (($rscheck1[0]->ta < $year) || ($rscheck2[0]->ta < $year)) { $year = $rscheck2[0]->ta; } $sql = 'SELECT `tlelangumum`.`skpdID` AS `skpdID` , `tbl_skpd`.`nama` AS `nama` , `tlelangumum`.`ta` AS `ta` , SUM(`tlelangumum`.`anggaran`)/1000000000 AS `anggaran`, SUM(`tlelangumum`.`nilai_nego`)/1000000000 AS `nilai_kontrak` FROM ( '.env('DB_CONTRACT').'.`tlelangumum` LEFT JOIN '.env('DB_PRIME').'.`tbl_skpd` ON( ( `tlelangumum`.`skpdID` = '.env('DB_PRIME').'.`tbl_skpd`.`skpdID` ) ) ) WHERE ( (`tlelangumum`.`nilai_nego` <> 0) AND(`tlelangumum`.`ta` = '.$year.') AND (`tlelangumum`.`skpdID` <> 0) ) GROUP BY `tlelangumum`.`skpdID` , '.env('DB_PRIME').'.`tbl_skpd`.`nama`, `ta` UNION SELECT `tpengadaan`.`skpdID` AS `skpdID` , `tbl_skpd`.`nama` AS `nama` , `tpengadaan`.`ta` AS `ta` , SUM(`tpengadaan`.`anggaran`)/1000000000 AS `anggaran`, SUM(`tpengadaan`.`nilai_nego`)/1000000000 AS `nilai_kontrak` FROM ( '.env('DB_CONTRACT').'.`tpengadaan` LEFT JOIN '.env('DB_PRIME').'.`tbl_skpd` ON( ( `tpengadaan`.`skpdID` = '.env('DB_PRIME').'.`tbl_skpd`.`skpdID` ) ) ) WHERE ( (`tpengadaan`.`pekerjaanstatus` = 7) AND (`tpengadaan`.`ta` = '.$year.') AND (`tpengadaan`.`skpdID` <> 0) ) GROUP BY `tpengadaan`.`skpdID` , '.env('DB_PRIME').'.`tbl_skpd`.`nama`, `ta` ORDER BY `nilai_kontrak` DESC LIMIT 10'; //echo $sql; $rs1 = DB::select($sql); $rowdata = array(); $data1 = array(); //pagu anggaran $data2 = array(); //nilai kontrak foreach($rs1 as $row) { array_push($data1, array($row->nama, (float)$row->anggaran)); array_push($data2, array($row->nama, (float)$row->nilai_kontrak)); } array_push($rowdata, array("name"=>"Pagu Anggaran", "data"=> $data1)); array_push($rowdata, array("name"=>"Nilai Kontrak", "data"=> $data2)); $results = $rowdata; return response() ->json($results) ->header('Access-Control-Allow-Origin', '*'); } public function graph3($year) { $sql = 'SELECT ta, COUNT(*) AS paket FROM '.env('DB_CONTRACT').'.`tlelangumum` GROUP BY ta ORDER BY ta DESC LIMIT 1'; $rscheck1 = DB::select($sql); $sql = 'SELECT ta, COUNT(*) AS paket FROM '.env('DB_CONTRACT').'.`tpengadaan` WHERE pekerjaanstatus = 7 GROUP BY ta ORDER BY ta DESC LIMIT 1'; $rscheck2 = DB::select($sql); if (($rscheck1[0]->ta < $year) || ($rscheck2[0]->ta < $year)) { $year = $rscheck2[0]->ta; } $sql = 'SELECT ta , LEFT(tklasifikasi.kode,2) AS kodepengadaan, ( CASE LEFT(tklasifikasi.kode , 2) WHEN "01" THEN "Konstruksi" WHEN "02" THEN "Pengadaan Barang" WHEN "03" THEN "Jasa Konsultansi" WHEN "04" THEN "Jasa Lainnya" ELSE "N/A" END ) AS jenispengadaan , COUNT(0) AS paket, SUM(anggaran) AS anggaran , SUM(hps) AS hps , SUM(nilai_nego) AS nilaikontrak FROM '.env('DB_CONTRACT').'.tpengadaan LEFT JOIN '.env('DB_CONTRACT').'.tklasifikasi ON tpengadaan.klasifikasiID = tklasifikasi.klasifikasiID WHERE pekerjaanstatus = 7 AND ta = '.$year.' GROUP BY ta, kodepengadaan, jenispengadaan'; $rs2 = DB::select($sql); $data = array(); foreach($rs2 as $row) { array_push($data, array("name"=>$row->jenispengadaan, "y"=>(float)$row->nilaikontrak)); } $results = $data; return response() ->json($results) ->header('Access-Control-Allow-Origin', '*'); } public function graph4() { $sql = 'SELECT tahun, paket FROM '.env('DB_CONTRACT').'.vlelang_bypaket ORDER BY tahun ASC'; $rs1 = DB::select($sql); $rowdata = array(); $data = array(); foreach($rs1 as $row) { array_push($data, array($row->tahun, (int)$row->paket)); } array_push($rowdata, array("name"=>"Tender", "data"=> $data)); $sql = 'SELECT tahun, paket FROM '.env('DB_CONTRACT').'.vpl_bypaket ORDER BY tahun ASC'; $rs2 = DB::select($sql); $data = array(); foreach($rs2 as $row) { array_push($data, array($row->tahun, (int)$row->paket)); } array_push($rowdata, array("name"=>"Non Tender", "data"=> $data)); $results = $rowdata; return response() ->json($results) ->header('Access-Control-Allow-Origin', '*'); } /** * Converts nested array to flatten array using Flattener and * returns as BinaryFileResponse. Deletes file after is downloaded. * You can reuse this function to make csv downloads for all json functions here * @param $filePrefix * @param $nested_array * @return \Symfony\Component\HttpFoundation\BinaryFileResponse */ public function download_nested_array_csv($filePrefix, $nested_array) { $flattener = new Flattener(); $flattener->setArrayData($nested_array); $tempFileName = sys_get_temp_dir().'/'.$filePrefix.'-'.rand(); $flattener->writeCsv($tempFileName); return response()->download($tempFileName.".csv")->deleteFileAfterSend(true); } /** * Produces a csv download for graph1 * @return \Symfony\Component\HttpFoundation\BinaryFileResponse */ public function graph_csv1() { $sql = 'SELECT tahun, (nilaikontrak/1000000000) AS nilaikontrak FROM '.env('DB_CONTRACT').'.vlelang_bypaket ORDER BY tahun ASC'; $rs1 = DB::select($sql); $rowdata = array(); $data = array(); foreach($rs1 as $row) { array_push($data, array($row->tahun)); } array_push($rowdata, array("name"=>"Year", "data"=> $data)); $data = array(); foreach($rs1 as $row) { array_push($data, array((float)$row->nilaikontrak)); } array_push($rowdata, array("name"=>"Lelang", "data"=> $data)); $sql = 'SELECT tahun, (nilaikontrak/1000000000) AS nilaikontrak FROM '.env('DB_CONTRACT').'.vpl_bypaket ORDER BY tahun ASC'; $rs1 = DB::select($sql); $data = array(); foreach($rs1 as $row) { array_push($data, array((float)$row->nilaikontrak)); } array_push($rowdata, array("name"=>"Pengadaan Langsung", "data"=> $data)); $results = $rowdata; //return $results; //return $this->download_nested_array_csv('lelang',$results); return $this->download_nested_array_csv('lelang',$this->graph1_array()); } public function graph_csv2() { //TODO : return "CSV SKPD"; } public function graph_csv3() { //TODO : return "CSV Non Competitive"; } public function graph_csv4() { //TODO : return "CSV Total Procurement"; } /*--- End Data Statistic ---*/ public function search(Request $request) { $dbplanning = env("DB_PLANNING"); $dbecontract = env("DB_CONTRACT"); $dbprime = env("DB_PRIME"); $sql = "SELECT skpdID, unitID, satker, nama, singkatan FROM $dbprime.tbl_skpd WHERE isactive = 1 AND isparent = 1 ORDER BY unitID"; $rsskpd = DB::select($sql); $rowdata = array(); $data = array(); foreach($rsskpd as $row) { array_push($data, array((INT)$row->skpdID, $row->unitID, $row->satker, $row->nama, $row->singkatan)); } array_push($rowdata, array("name"=>"ref_skpd", "data"=> $data)); if (!empty($request)) { $q = $request->input('q'); $tahun = $request->input('tahun'); $skpdID = $request->input('skpdID'); $klasifikasi = $request->input('klasifikasi'); $tahap = $request->input('tahap'); $min = $request->input('min'); $max = $request->input('max'); $startdate = $request->input('startdate'); $enddate = $request->input('enddate'); switch ($tahap) { case 1: //Perencanaan $sql = ""; break; case 2: //Pengadaan /*$rspengadaan = DB::table($dbecontract.'.tpengadaan') ->select('tpengadaan.kode', 'tpengadaan.namakegiatan', 'tpengadaan.namapekerjaan', 'tpengadaan.nilai_nego','sirupID') ->leftJoin($dbecontract.'.tpekerjaan', 'tpengadaan.pid', '=', 'tpekerjaan.pid') ->leftJoin('tbl_pekerjaan', 'tpekerjaan.pekerjaanID', '=', 'tbl_pekerjaan.pekerjaanID') ->where([ ['tpengadaan.namapekerjaan', 'LIKE', '%makanan%'], ['nilai_nego', '>=', 100], ['nilai_nego', '<=', 200], ] ) ->get();*/ break; case 3: //Pemenang $sql = ""; break; case 4: //Kontrak $sql = ""; break; case 5: //Implementasi $sql = ""; break; default: $sql = "SELECT `tbl_pekerjaan`.`kodepekerjaan` , `tbl_pekerjaan`.`sirupID`, `tbl_metode`.`nama` AS metodepengadaan, `tpengadaan`.`namakegiatan` , `tpengadaan`.`namapekerjaan` , `tpengadaan`.`nilai_nego` , `tpengadaan`.skpdID, `tbl_skpd`.unitID, `tbl_skpd`.nama AS namaskpd, `tpengadaan`.ta, `tpengadaan`.anggaran, `tsumberdana`.sumberdana, `tpengadaan`.klasifikasiID, LEFT(`tklasifikasi`.kode,2) AS kodeklasifikasi, CASE WHEN LEFT(`tklasifikasi`.kode,2) = 1 THEN 'Konstruksi' WHEN LEFT(`tklasifikasi`.kode,2) = 2 THEN 'Pengadaan Barang' WHEN LEFT(`tklasifikasi`.kode,2) = 3 THEN 'Jasa Konsultansi' WHEN LEFT(`tklasifikasi`.kode,2) = 4 THEN 'Jasa Lainnya' ELSE 'N/A' END AS klasifikasi, `tbl_pekerjaan`.pilih_start, `tbl_pekerjaan`.pilih_end, `tbl_pekerjaan`.laksana_start, `tbl_pekerjaan`.laksana_end FROM `$dbecontract`.`tpengadaan` LEFT JOIN `$dbecontract`.`tpekerjaan` ON `tpengadaan`.`pid` = `tpekerjaan`.`pid` LEFT JOIN `tbl_pekerjaan` ON `tpekerjaan`.`pekerjaanID` = `tbl_pekerjaan`.`pekerjaanID` LEFT JOIN `tbl_metode` ON `tpekerjaan`.`metodeID` = `tbl_metode`.`metodeID` LEFT JOIN `$dbprime`.`tbl_skpd` ON `tpengadaan`.`skpdID` = `tbl_skpd`.`skpdID` LEFT JOIN `$dbecontract`.`tsumberdana` ON `tpengadaan`.sumberdanaid = `tsumberdana`.sumberdanaid LEFT JOIN `$dbecontract`.`tklasifikasi` ON `tpengadaan`.klasifikasiID = `tklasifikasi`.klasifikasiID WHERE true "; if (!empty($q)) { $sql .= " AND (`tpengadaan`.`namapekerjaan` LIKE '%$q%' OR `tbl_skpd`.nama LIKE '%$q%')"; } if (!empty($tahun)) { $sql .= " AND `tpengadaan`.ta = $tahun "; } /*if (!empty($skpdID)) { $sql .= " AND `tpengadaan`.skpdID = $skpdID"; }*/ if (!empty($klasifikasi)) { $sql .= " AND LEFT(`tklasifikasi`.kode,2) = $klasifikasi"; } if (!empty($min)) { $sql .= " AND (`tpengadaan`.anggaran >= $min OR `tpengadaan`.nilai_nego >= $min) "; } if (!empty($max)) { $sql .= " AND (`tpengadaan`.anggaran <= $max OR `tpengadaan`.nilai_nego <= $max) "; } echo $sql; $rspengadaan = DB::select($sql); } } else { $data['message'] = 'Silahkan isi kata yang ingin dicari terlebih dahulu'; } $data = array(); foreach($rspengadaan as $row) { array_push($data, array($row->kodepekerjaan, (int)$row->sirupID, $row->metodepengadaan, $row->namakegiatan, $row->namapekerjaan, $row->nilai_nego, $row->skpdID, $row->unitID, $row->namaskpd, $row->ta, $row->anggaran, $row->sumberdana, $row->klasifikasi, $row->pilih_start, $row->pilih_end, $row->laksana_start, $row->laksana_end)); } array_push($rowdata, array("name"=>"pengadaan", "data"=> $data)); //total kontrak array_push($rowdata, array("name"=>"totalsearch", "data"=> count($rspengadaan))); $results = $rowdata; return response() ->json($results) ->header('Access-Control-Allow-Origin', '*'); } public function jenis_belanja($jenis) { switch ($jenis) { case 1: $jenis_belanja = 'Barang/Jasa'; break; case 2: $jenis_belanja = 'Modal'; break; default: $jenis_belanja = ''; } return $jenis_belanja; } public function jenis_pengadaan($jenis) { switch ($jenis) { case 1: $jenis_pengadaan = 'Barang'; break; case 2: $jenis_pengadaan = 'Pekerjaan Konstruksi'; break; case 3: $jenis_pengadaan = 'Jasa Konsultansi'; break; case 4: $jenis_pengadaan = 'Jasa Lainnya'; break; default: $jenis_pengadaan = ''; } return $jenis_pengadaan; } public function metode_pengadaan($metode) { switch ($metode) { case 1: $metode_pengadaan = 'Lelang Umum'; break; case 2: $metode_pengadaan = 'Lelang Sederhana'; break; case 3: $metode_pengadaan = 'Lelang Terbatas'; break; case 4: $metode_pengadaan = 'Seleksi Umum'; break; case 5: $metode_pengadaan = 'Seleksi Sederhana'; break; case 6: $metode_pengadaan = 'Pemilihan Langsung'; break; case 7: $metode_pengadaan = 'Penunjukan Langsung'; break; case 8: $metode_pengadaan = 'Pengadaan Langsung'; break; case 9: $metode_pengadaan = 'e-Purchasing'; break; default: $metode_pengadaan = ''; } return $metode_pengadaan; } public function get_program($year, $kode) { $dbplanning = env('DB_PLANNING'); $sql = "SELECT Ket_Program FROM ".$dbplanning.".ta_program WHERE Tahun = ".$year." AND ta_program.ID_Prog = CONCAT(SUBSTRING_INDEX('".$kode."', '.', 1), SUBSTRING_INDEX(SUBSTRING_INDEX('".$kode."', '.', 2), '.', -1)) AND ta_program.Kd_Urusan = SUBSTRING_INDEX(SUBSTRING_INDEX('".$kode."', '.', 3), '.', -1) AND ta_program.Kd_Bidang = SUBSTRING_INDEX(SUBSTRING_INDEX('".$kode."', '.', 4), '.', -1) AND ta_program.Kd_Unit = SUBSTRING_INDEX(SUBSTRING_INDEX('".$kode."', '.', 5), '.', -1) AND ta_program.Kd_Sub = SUBSTRING_INDEX(SUBSTRING_INDEX('".$kode."', '.', 6), '.', -1) AND ta_program.Kd_Prog = SUBSTRING_INDEX(SUBSTRING_INDEX('".$kode."', '.', 7), '.', -1) "; $rsprogram = DB::select($sql); if (sizeof($rsprogram) != 0) { $rsprogram = $rsprogram[0]; $namaprogram = $rsprogram->Ket_Program; } else { $namaprogram = ""; } return $namaprogram; } /*--- Recent Data ---*/ public function get_recent_perencanaan() { $dbplanning = env('DB_PLANNING'); $dbcontract = env('DB_CONTRACT'); $dbprime = env('DB_PRIME'); $year = date('Y'); $sql = 'SELECT COUNT(*) AS jumlah FROM tbl_sirup WHERE tahun = '.$year.' AND sirupID = 0'; $rscheck = DB::select($sql); if ($rscheck[0]->jumlah == 0) { $year = date('Y') - 1; } $sql = 'SELECT CONCAT("'.env('OCID').'","s-",tahun,"-",tbl_sirup.sirupID) AS ocid, NULL AS koderekening, tbl_sirup.sirupID, tahun, nama, pagu, sumber_dana_string, jenis_belanja, jenis_pengadaan, metode_pengadaan, NULL AS procurementMethodDetails, NULL AS awardCriteria, jenis, tanggal_awal_pengadaan, tanggal_akhir_pengadaan, tanggal_awal_pekerjaan, tanggal_akhir_pekerjaan, id_satker, kldi, satuan_kerja, lokasi, isswakelola, NULL AS isready, tlelangumum.pekerjaanstatus, NULL AS created_at, NULL AS updated_at FROM '.$dbplanning.'.tbl_sirup LEFT JOIN '.$dbcontract.'.tlelangumum ON tbl_sirup.sirupID = tlelangumum.sirupID WHERE tbl_sirup.tahun = '.$year.' AND pagu <> 0 AND tlelangumum.hps <> 0 AND tlelangumum.penawaran <> 0 AND tlelangumum.nilai_nego <> 0 AND tlelangumum.pekerjaanstatus <= 3 AND (NOT ISNULL(tlelangumum.namakegiatan) AND TRIM(tlelangumum.namakegiatan) <> "") AND metode_pengadaan IN (1,2,3,4,5,6,10,11,12) AND isswakelola = 0 UNION SELECT CONCAT( "'.env('OCID').'", "b-", tbl_pekerjaan.tahun, "-", tbl_pekerjaan.pekerjaanID ) AS ocid, kodepekerjaan AS koderekening, sirupID, tbl_pekerjaan.tahun , tbl_pekerjaan.namapekerjaan AS nama , tbl_pekerjaan.anggaran AS pagu , tbl_sumberdana.sumberdana AS sumber_dana_string , 1 AS jenis_belanja , tbl_metode.jenisID AS jenis_pengadaan , ( CASE WHEN tbl_metode.nama = "Belanja Sendiri" THEN 9 WHEN tbl_metode.nama = "Kontes / Sayembara" THEN 10 WHEN tbl_metode.nama = "Pelelangan Sederhana" THEN 2 WHEN tbl_metode.nama = "Pelelangan Umum" THEN 1 WHEN tbl_metode.nama = "Pembelian Secara Elektronik" THEN 9 WHEN tbl_metode.nama = "Pemilihan Langsung" THEN 6 WHEN tbl_metode.nama = "Pengadaan Langsung" THEN 8 WHEN tbl_metode.nama = "Penunjukan Langsung" THEN 7 WHEN tbl_metode.nama = "Swakelola" THEN 21 ELSE 0 END ) AS metode_pengadaan , NULL AS procurementMethodDetails, NULL AS awardCriteria, 2 AS jenis , pilih_start AS tanggal_awal_pengadaan , pilih_end AS tanggal_akhir_pengadaan , laksana_start AS tanggal_awal_pekerjaan , laksana_end AS tanggal_akhir_pekerjaan , satker AS id_satker , "Kota Bandung" AS kldi , tbl_skpd.nama AS satuan_kerja , tbl_skpd.alamat AS lokasi , IF (tbl_metode.nama = "Swakelola" , 1 , 0) AS isswakelola, IF (ISNULL(tpekerjaan.pid),0,1) AS isready, tpekerjaan.pekerjaanstatus, tbl_pekerjaan.created AS created_at, tbl_pekerjaan.updated AS updated_at FROM '.$dbplanning.'.tbl_pekerjaan LEFT JOIN '.$dbplanning.'.tbl_sumberdana ON tbl_pekerjaan.sumberdanaID = tbl_sumberdana.sumberdanaID LEFT JOIN '.$dbprime.'.tbl_skpd ON tbl_pekerjaan.skpdID = tbl_skpd.skpdID LEFT JOIN '.$dbplanning.'.tbl_metode ON tbl_pekerjaan.metodeID = tbl_metode.metodeID LEFT JOIN '.$dbcontract.'.tpekerjaan ON tbl_pekerjaan.pekerjaanID = tpekerjaan.pekerjaanID WHERE tbl_pekerjaan.tahun = '.$year.' AND sirupID = 0 AND iswork = 1 '; //AND tpekerjaan.pekerjaanstatus <= 3 $sql .= ' ORDER BY tanggal_awal_pengadaan DESC LIMIT 10'; $rsdummy = DB::select($sql); $rowdata = array(); $data = array(); foreach($rsdummy as $row) { $pieces = explode("-", $row->ocid); $source = $pieces[2]; // s = sirup.lkpp.go.id. b = birms.bandung.go.id $data['ocid'] = $row->ocid; if ($source == "s") { $data['uri'] = env('LINK_SIRUP18').$row->sirupID; } else { $data['uri'] = ""; } $data['title'] = $row->nama; $data['koderekening'] = $row->koderekening; $data['project'] = $this->get_program($row->tahun, $row->koderekening); $data['sirupID'] = $row->sirupID; $data['SKPD'] = $row->satuan_kerja; $data['budget'] = array( 'description' =>$row->sumber_dana_string, 'amount' => array( 'amount' => $row->pagu, 'currency' => env('CURRENCY') ), 'uri' => $data['uri'] ); if ($row->jenis_pengadaan != "") { $data['mainProcurementCategory'] = $this->jenis_pengadaan($row->jenis_pengadaan); } else { $data['mainProcurementCategory'] = ""; } $data['procurementMethod'] = $row->metode_pengadaan; if ($row->metode_pengadaan != 0) { $data['procurementMethodDetails'] = $this->metode_pengadaan($row->metode_pengadaan); } else { $data['procurementMethodDetails'] = ""; } $data['awardCriteria'] = "priceOnly"; //To Do List Check Source $data['tender'] = array( 'startDate' => $row->tanggal_awal_pengadaan, 'endDate' => $row->tanggal_akhir_pengadaan ); $data['contract'] = array( 'startDate' => $row->tanggal_awal_pekerjaan, 'endDate' => $row->tanggal_akhir_pekerjaan ); $data['created_at'] = $row->created_at; $data['updated_at'] = $row->updated_at; array_push($rowdata, $data); } $results = $rowdata; //$results = $this->arrayPaginator($rowdata, request()); return response() ->json($results) ->header('Access-Control-Allow-Origin', '*'); } function get_recent_pemilihan() { $dbplanning = env('DB_PLANNING'); $dbcontract = env('DB_CONTRACT'); $dbprime = env('DB_PRIME'); $year = date('Y'); $sql = 'SELECT CONCAT("'.env('OCID').'","s-",tahun,"-",tbl_sirup.sirupID) AS ocid, tbl_sirup.sirupID, tlelangumum.skpdID, satuan_kerja, tahun, tlelangumum.kode AS koderekening, lls_id AS lelangID, namakegiatan, nama AS title, tanggal_awal_pekerjaan, tanggal_akhir_pekerjaan, metode_pengadaan, pagu, hps, jumlah_peserta, jenis, jenis_belanja, jenis_pengadaan, penawaran, nilai_nego, tlelangumum.pekerjaanstatus, tlelangumum.created, tlelangumum.updated FROM '.$dbplanning.'.tbl_sirup LEFT JOIN '.$dbcontract.'.tlelangumum ON tbl_sirup.sirupID = tlelangumum.sirupID WHERE tbl_sirup.tahun = '.$year.' AND tlelangumum.hps <> 0 AND tlelangumum.penawaran <> 0 AND tlelangumum.nilai_nego <> 0 AND tlelangumum.pekerjaanstatus = 4 AND (NOT ISNULL(tlelangumum.namakegiatan) AND TRIM(tlelangumum.namakegiatan) <> "") AND metode_pengadaan IN (1,2,3,4,5,6,10,11,12) UNION SELECT CONCAT("'.env('OCID').'","b-",tahun,"-",tbl_pekerjaan.pekerjaanID) AS ocid, tbl_pekerjaan.pekerjaanID AS sirupID, tbl_pekerjaan.skpdID, tbl_skpd.nama AS satuan_kerja, tahun, tbl_pekerjaan.kodepekerjaan AS koderekening, tbl_pekerjaan.pekerjaanID AS lelangID, tpekerjaan.namakegiatan, tbl_pekerjaan.namapekerjaan AS title, tbl_pekerjaan.pilih_start AS tanggal_awal_pekerjaan, tbl_pekerjaan.pilih_end AS tanggal_akhir_pekerjaan, ( CASE WHEN tbl_metode.nama = "Belanja Sendiri" THEN 9 WHEN tbl_metode.nama = "Kontes / Sayembara" THEN 10 WHEN tbl_metode.nama = "Pelelangan Sederhana" THEN 2 WHEN tbl_metode.nama = "Pelelangan Umum" THEN 1 WHEN tbl_metode.nama = "Pembelian Secara Elektronik" THEN 9 WHEN tbl_metode.nama = "Pemilihan Langsung" THEN 6 WHEN tbl_metode.nama = "Pengadaan Langsung" THEN 8 WHEN tbl_metode.nama = "Penunjukan Langsung" THEN 7 WHEN tbl_metode.nama = "Swakelola" THEN 21 ELSE 0 END ) AS metode_pengadaan , tbl_pekerjaan.anggaran AS pagu, tpekerjaan.hps, 1 AS jumlah_peserta, NULL AS jenis, 1 AS jenis_belanja , tbl_metode.jenisID AS jenis_pengadaan, tpengadaan_pemenang.nilai AS penawaran, tpengadaan.nilai_nego, tpengadaan.pekerjaanstatus, tpengadaan.created, tpengadaan.updated FROM '.$dbplanning.'.tbl_pekerjaan LEFT JOIN '.$dbcontract.'.tpekerjaan ON tbl_pekerjaan.pekerjaanID = tpekerjaan.pekerjaanID LEFT JOIN '.$dbcontract.'.tpengadaan ON tpekerjaan.pid = tpengadaan.pid LEFT JOIN '.$dbcontract.'.tpengadaan_pemenang ON tpengadaan.pgid = tpengadaan_pemenang.pgid LEFT JOIN '.$dbprime.'.tbl_skpd ON tbl_pekerjaan.skpdID = tbl_skpd.skpdID LEFT JOIN '.$dbplanning.'.tbl_metode ON tbl_pekerjaan.metodeID = tbl_metode.metodeID WHERE tahun = '.$year.' AND iswork = 1 AND tpengadaan.pekerjaanstatus = 4 ORDER BY updated DESC, created DESC LIMIT 10'; //die($sql); $rspengadaan = DB::select($sql); $rowdata = array(); $data = array(); foreach($rspengadaan as $row) { $pieces = explode("-", $row->ocid); $source = $pieces[2]; $data['ocid'] = $row->ocid; if ($source == "s") { $data['uri'] = env('LINK_SIRUP18').$row->sirupID; } else { $data['uri'] = ""; } $data['title'] = $row->title; $data['namakegiatan'] = $row->namakegiatan; $data['koderekening'] = $row->koderekening; $data['project'] = $this->get_program($row->tahun, $row->koderekening); $data['sirupID'] = $row->sirupID; $data['SKPD'] = $row->satuan_kerja; $data['anggaran'] = $row->pagu; $data['hps'] = $row->hps; $data['nilai_penawaran']= $row->penawaran; $data['nilai_nego'] = $row->nilai_nego; $data['jumlah_peserta'] = $row->jumlah_peserta; $data['procurementMethod'] = $row->metode_pengadaan; if ($row->metode_pengadaan != 0) { $data['procurementMethodDetails'] = $this->metode_pengadaan($row->metode_pengadaan); } else { $data['procurementMethodDetails'] = ""; } $data['awardCriteria'] = "priceOnly"; //To Do List Check Source $data['dateSigned'] = ""; $data['contract'] = array( 'startDate' => $row->tanggal_awal_pekerjaan, 'endDate' => $row->tanggal_akhir_pekerjaan ); $data['updated'] = $row->updated; array_push($rowdata, $data); } $results = $rowdata; return response() ->json($results) ->header('Access-Control-Allow-Origin', '*'); } public function get_recent_pemenang() { $dbplanning = env('DB_PLANNING'); $dbcontract = env('DB_CONTRACT'); $dbprime = env('DB_PRIME'); $year = date('Y'); $sql = 'SELECT CONCAT("'.env('OCID').'","s-",tahun,"-",tbl_sirup.sirupID) AS ocid, tbl_sirup.sirupID, tlelangumum.skpdID, satuan_kerja, tahun, tlelangumum.kode AS koderekening, lls_id AS lelangID, namakegiatan, nama AS title, tanggal_awal_pekerjaan, tanggal_akhir_pekerjaan, metode_pengadaan, pagu, hps, jumlah_peserta, jenis, jenis_belanja, jenis_pengadaan, pemenang AS perusahaannama, pemenangalamat AS perusahaanalamat, pemenangnpwp AS perusahaannpwp, penawaran, nilai_nego, tlelangumum.pekerjaanstatus, tlelangumum.created, tlelangumum.updated FROM '.$dbplanning.'.tbl_sirup LEFT JOIN '.$dbcontract.'.tlelangumum ON tbl_sirup.sirupID = tlelangumum.sirupID WHERE tbl_sirup.tahun = '.$year.' AND tlelangumum.hps <> 0 AND tlelangumum.penawaran <> 0 AND tlelangumum.nilai_nego <> 0 AND tlelangumum.pekerjaanstatus = 7 AND (NOT ISNULL(tlelangumum.namakegiatan) AND TRIM(tlelangumum.namakegiatan) <> "") AND metode_pengadaan IN (1,2,3,4,5,6,10,11,12) UNION SELECT CONCAT("'.env('OCID').'","b-",tahun,"-",tbl_pekerjaan.pekerjaanID) AS ocid, tbl_pekerjaan.pekerjaanID AS sirupID, tbl_pekerjaan.skpdID, tbl_skpd.nama AS satuan_kerja, tahun, tbl_pekerjaan.kodepekerjaan AS koderekening, tbl_pekerjaan.pekerjaanID AS lelangID, tpekerjaan.namakegiatan, tbl_pekerjaan.namapekerjaan AS title, tbl_pekerjaan.pilih_start AS tanggal_awal_pekerjaan, tbl_pekerjaan.pilih_end AS tanggal_akhir_pekerjaan, ( CASE WHEN tbl_metode.nama = "Belanja Sendiri" THEN 9 WHEN tbl_metode.nama = "Kontes / Sayembara" THEN 10 WHEN tbl_metode.nama = "Pelelangan Sederhana" THEN 2 WHEN tbl_metode.nama = "Pelelangan Umum" THEN 1 WHEN tbl_metode.nama = "Pembelian Secara Elektronik" THEN 9 WHEN tbl_metode.nama = "Pemilihan Langsung" THEN 6 WHEN tbl_metode.nama = "Pengadaan Langsung" THEN 8 WHEN tbl_metode.nama = "Penunjukan Langsung" THEN 7 WHEN tbl_metode.nama = "Swakelola" THEN 21 ELSE 0 END ) AS metode_pengadaan , tbl_pekerjaan.anggaran AS pagu, tpekerjaan.hps, 1 AS jumlah_peserta, NULL AS jenis, 1 AS jenis_belanja , tbl_metode.jenisID AS jenis_pengadaan, tpengadaan_pemenang.perusahaannama, tpengadaan_pemenang.perusahaanalamat, tpengadaan_pemenang.perusahaannpwp, tpengadaan_pemenang.nilai AS penawaran, tpengadaan.nilai_nego, tpengadaan.pekerjaanstatus, tpengadaan.created, tpengadaan.updated FROM '.$dbplanning.'.tbl_pekerjaan LEFT JOIN '.$dbcontract.'.tpekerjaan ON tbl_pekerjaan.pekerjaanID = tpekerjaan.pekerjaanID LEFT JOIN '.$dbcontract.'.tpengadaan ON tpekerjaan.pid = tpengadaan.pid LEFT JOIN '.$dbcontract.'.tpengadaan_pemenang ON tpengadaan.pgid = tpengadaan_pemenang.pgid LEFT JOIN '.$dbprime.'.tbl_skpd ON tbl_pekerjaan.skpdID = tbl_skpd.skpdID LEFT JOIN '.$dbplanning.'.tbl_metode ON tbl_pekerjaan.metodeID = tbl_metode.metodeID WHERE tahun = '.$year.' AND iswork = 1 AND tpengadaan.pekerjaanstatus = 7 ORDER BY updated DESC, created DESC LIMIT 10'; //die($sql); $rspengadaan = DB::select($sql); $rowdata = array(); $data = array(); foreach($rspengadaan as $row) { $pieces = explode("-", $row->ocid); $source = $pieces[2]; $data['ocid'] = $row->ocid; if ($source == "s") { $data['uri'] = env('LINK_SIRUP18').$row->sirupID; } else { $data['uri'] = ""; } $data['title'] = $row->title; $data['namakegiatan'] = $row->namakegiatan; $data['koderekening'] = $row->koderekening; $data['project'] = $this->get_program($row->tahun, $row->koderekening); $data['sirupID'] = $row->sirupID; $data['SKPD'] = $row->satuan_kerja; $data['anggaran'] = $row->pagu; $data['hps'] = $row->hps; $data['nilai_penawaran']= $row->penawaran; $data['perusahaannama'] = $row->perusahaannama; $data['perusahaanalamat']= $row->perusahaanalamat; $data['perusahaannpwp'] = $row->perusahaannpwp; $data['nilai_nego'] = $row->nilai_nego; $data['jumlah_peserta'] = $row->jumlah_peserta; $data['procurementMethod'] = $row->metode_pengadaan; if ($row->metode_pengadaan != 0) { $data['procurementMethodDetails'] = $this->metode_pengadaan($row->metode_pengadaan); } else { $data['procurementMethodDetails'] = ""; } $data['awardCriteria'] = "priceOnly"; //To Do List Check Source $data['dateSigned'] = ""; $data['contract'] = array( 'startDate' => $row->tanggal_awal_pekerjaan, 'endDate' => $row->tanggal_akhir_pekerjaan ); $data['updated'] = $row->updated; array_push($rowdata, $data); } $results = $rowdata; return response() ->json($results) ->header('Access-Control-Allow-Origin', '*'); } public function get_recent_kontrak() { $dbplanning = env('DB_PLANNING'); $dbcontract = env('DB_CONTRACT'); $dbprime = env('DB_PRIME'); $year = date('Y'); $sql = 'SELECT CONCAT("'.env('OCID').'","s-",tahun,"-",tbl_sirup.sirupID) AS ocid, tbl_sirup.sirupID, tlelangumum.skpdID, satuan_kerja, tahun, tlelangumum.kode AS koderekening, lls_id AS lelangID, namakegiatan, nama AS title, tanggal_awal_pekerjaan, tanggal_akhir_pekerjaan, metode_pengadaan, pagu, hps, jumlah_peserta, jenis, jenis_belanja, jenis_pengadaan, pemenang AS perusahaannama, pemenangalamat AS perusahaanalamat, pemenangnpwp AS perusahaannpwp, penawaran, nilai_nego, tlelangumum.pekerjaanstatus, tlelangumum.created, tlelangumum.updated FROM '.$dbplanning.'.tbl_sirup LEFT JOIN '.$dbcontract.'.tlelangumum ON tbl_sirup.sirupID = tlelangumum.sirupID WHERE tbl_sirup.tahun = '.$year.' AND tlelangumum.hps <> 0 AND tlelangumum.penawaran <> 0 AND tlelangumum.nilai_nego <> 0 AND tlelangumum.pekerjaanstatus = 7 AND (NOT ISNULL(tlelangumum.namakegiatan) AND TRIM(tlelangumum.namakegiatan) <> "") AND metode_pengadaan IN (1,2,3,4,5,6,10,11,12) UNION SELECT CONCAT("'.env('OCID').'","b-",tahun,"-",tbl_pekerjaan.pekerjaanID) AS ocid, tbl_pekerjaan.pekerjaanID AS sirupID, tbl_pekerjaan.skpdID, tbl_skpd.nama AS satuan_kerja, tahun, tbl_pekerjaan.kodepekerjaan AS koderekening, tbl_pekerjaan.pekerjaanID AS lelangID, tpekerjaan.namakegiatan, tbl_pekerjaan.namapekerjaan AS title, tbl_pekerjaan.pilih_start AS tanggal_awal_pekerjaan, tbl_pekerjaan.pilih_end AS tanggal_akhir_pekerjaan, ( CASE WHEN tbl_metode.nama = "Belanja Sendiri" THEN 9 WHEN tbl_metode.nama = "Kontes / Sayembara" THEN 10 WHEN tbl_metode.nama = "Pelelangan Sederhana" THEN 2 WHEN tbl_metode.nama = "Pelelangan Umum" THEN 1 WHEN tbl_metode.nama = "Pembelian Secara Elektronik" THEN 9 WHEN tbl_metode.nama = "Pemilihan Langsung" THEN 6 WHEN tbl_metode.nama = "Pengadaan Langsung" THEN 8 WHEN tbl_metode.nama = "Penunjukan Langsung" THEN 7 WHEN tbl_metode.nama = "Swakelola" THEN 21 ELSE 0 END ) AS metode_pengadaan , tbl_pekerjaan.anggaran AS pagu, tpekerjaan.hps, 1 AS jumlah_peserta, NULL AS jenis, 1 AS jenis_belanja , tbl_metode.jenisID AS jenis_pengadaan, tpengadaan_pemenang.perusahaannama, tpengadaan_pemenang.perusahaanalamat, tpengadaan_pemenang.perusahaannpwp, tpengadaan_pemenang.nilai AS penawaran, tpengadaan.nilai_nego, tpengadaan.pekerjaanstatus, tpengadaan.created, tpengadaan.updated FROM '.$dbplanning.'.tbl_pekerjaan LEFT JOIN '.$dbcontract.'.tpekerjaan ON tbl_pekerjaan.pekerjaanID = tpekerjaan.pekerjaanID LEFT JOIN '.$dbcontract.'.tpengadaan ON tpekerjaan.pid = tpengadaan.pid LEFT JOIN '.$dbcontract.'.tpengadaan_pemenang ON tpengadaan.pgid = tpengadaan_pemenang.pgid LEFT JOIN '.$dbprime.'.tbl_skpd ON tbl_pekerjaan.skpdID = tbl_skpd.skpdID LEFT JOIN '.$dbplanning.'.tbl_metode ON tbl_pekerjaan.metodeID = tbl_metode.metodeID WHERE tahun = '.$year.' AND iswork = 1 AND tpengadaan.pekerjaanstatus = 7 ORDER BY updated DESC, created DESC LIMIT 10'; //die($sql); $rspengadaan = DB::select($sql); $rowdata = array(); $data = array(); foreach($rspengadaan as $row) { $pieces = explode("-", $row->ocid); $source = $pieces[2]; $data['ocid'] = $row->ocid; if ($source == "s") { $data['uri'] = env('LINK_SIRUP18').$row->sirupID; } else { $data['uri'] = ""; } $data['title'] = $row->title; $data['namakegiatan'] = $row->namakegiatan; $data['koderekening'] = $row->koderekening; $data['project'] = $this->get_program($row->tahun, $row->koderekening); $data['sirupID'] = $row->sirupID; $data['SKPD'] = $row->satuan_kerja; $data['anggaran'] = $row->pagu; $data['hps'] = $row->hps; $data['nilai_penawaran']= $row->penawaran; $data['perusahaannama'] = $row->perusahaannama; $data['perusahaanalamat']= $row->perusahaanalamat; $data['perusahaannpwp'] = $row->perusahaannpwp; $data['nilai_nego'] = $row->nilai_nego; $data['jumlah_peserta'] = $row->jumlah_peserta; $data['procurementMethod'] = $row->metode_pengadaan; if ($row->metode_pengadaan != 0) { $data['procurementMethodDetails'] = $this->metode_pengadaan($row->metode_pengadaan); } else { $data['procurementMethodDetails'] = ""; } $data['awardCriteria'] = "priceOnly"; //To Do List Check Source $data['dateSigned'] = ""; $data['contract'] = array( 'startDate' => $row->tanggal_awal_pekerjaan, 'endDate' => $row->tanggal_akhir_pekerjaan ); $data['updated'] = $row->updated; array_push($rowdata, $data); } $results = $rowdata; return response() ->json($results) ->header('Access-Control-Allow-Origin', '*'); } public function get_skpd($year) { $dbmain = env('DB_PRIME'); $dbmain_prev= env('DB_PRIME_PREV'); if ($year <= 2016) { $sql = 'SELECT unitID, satker, nama, singkatan, alamat, telepon, email FROM '.$dbmain_prev.'.tbl_skpd '; } else { $sql = 'SELECT unitID, satker, nama, singkatan, alamat, telepon, email FROM '.$dbmain.'.tbl_skpd '; } $results = $this->arrayPaginator(DB::select($sql), request()); return response() ->json($results) ->header('Access-Control-Allow-Origin', '*'); } public function get_progres($year, $organization) { $dbplanning = env('DB_PLANNING'); $dbcontract = env('DB_CONTRACT'); $dbmain = env('DB_PRIME'); $dbmain_prev= env('DB_PRIME_PREV'); $sql = "SELECT CONCAT(REPLACE(tpekerjaan.tanggalrencana,'-',''),'.',tpengadaan.pid,'.',tpekerjaan.saltid) AS paketID, tpengadaan.pgid, tpengadaan.skpdID, tbl_skpd.nama AS skpdnama, tpengadaan.kode AS koderekening, tpengadaan.namapekerjaan, tpengadaan.jenisID, tbl_jenis.nama AS jenis_pengadaan, tpengadaan.metodeID, tbl_metode.nama AS metode_pengadaan, tbl_user.identity_no AS ppk_nip, tbl_user.fullname AS ppk_nama, tpengadaan.lokasi, tpekerjaan.lat, tpekerjaan.lng, tpengadaan.anggaran AS paguanggaran, tpengadaan.hps AS hps, tpengadaan.nilai_nego AS nilaikontrak, tpengadaan.pekerjaanstatus, tpengadaan_pemenang.perusahaannama, tpengadaan_pemenang.perusahaanalamat, tpengadaan_pemenang.perusahaannpwp, SUBSTRING_INDEX(SUBSTRING_INDEX(tprogress_pembayaran_bukti.isian,'|',5),'|',-1) AS perusahaanwakilnama, SUBSTRING_INDEX(SUBSTRING_INDEX(tprogress_pembayaran_bukti.isian,'|',6),'|',-1) AS perusahaanwakiljabatan, tkontrak_penunjukan.spk_nosurat AS spk_no, tkontrak_penunjukan.spk_tgl_surat AS spk_tgl, tkontrak_penunjukan.sp_nosurat AS sp_spmk_no, tkontrak_penunjukan.sp_tgl_surat AS sp_spmk_tgl, SUBSTRING_INDEX(SUBSTRING_INDEX(tprogress_serahterima.isian,'|',7),'|',-1) AS bapp_no, SUBSTRING_INDEX(SUBSTRING_INDEX(tprogress_serahterima.isian,'|',8),'|',-1) AS bapp_tgl, tprogress_serahterima.nosurat AS basthp_no, tprogress_serahterima.tgl_surat AS basthp_tgl, tprogress_pembayaran.nosurat AS bap_no, tprogress_pembayaran.tgl_surat AS bap_tgl, tprogress_pembayaran_bukti.nosurat AS kuitansi_no, tprogress_pembayaran_bukti.tgl_surat AS kuitansi_tgl, SUBSTRING_INDEX(SUBSTRING_INDEX(tprogress_pembayaran_bukti.isian,'|',1),'|',-1) AS suratjalan_no, SUBSTRING_INDEX(SUBSTRING_INDEX(tprogress_pembayaran_bukti.isian,'|',2),'|',-1) AS suratjalan_tgl, SUBSTRING_INDEX(SUBSTRING_INDEX(tprogress_pembayaran_bukti.isian,'|',3),'|',-1) AS faktur_no, SUBSTRING_INDEX(SUBSTRING_INDEX(tprogress_pembayaran_bukti.isian,'|',4),'|',-1) AS faktur_tgl FROM ".$dbcontract.".tpengadaan LEFT JOIN ".$dbcontract.".tpekerjaan ON tpengadaan.pid = tpekerjaan.pid "; if ($year <= 2016) { $sql .= " LEFT JOIN ".$dbmain_prev.".tbl_skpd ON tpengadaan.skpdID = tbl_skpd.skpdID "; $sql .= " LEFT JOIN ".$dbmain_prev.".tbl_user ON tpengadaan.ppkm_userid = tbl_user.usrid "; } else { $sql .= " LEFT JOIN ".$dbmain.".tbl_skpd ON tpengadaan.skpdID = tbl_skpd.skpdID "; $sql .= " LEFT JOIN ".$dbmain.".tbl_user ON tpengadaan.ppkm_userid = tbl_user.usrid "; } $sql .= " LEFT JOIN ".$dbplanning.".tbl_jenis ON tpengadaan.jenisID = tbl_jenis.jenisID LEFT JOIN ".$dbplanning.".tbl_metode ON tpengadaan.metodeID = tbl_metode.metodeID LEFT JOIN ".$dbcontract.".tpengadaan_pemenang ON tpengadaan.pgid = tpengadaan_pemenang.pgid LEFT JOIN ".$dbcontract.".tkontrak_penunjukan ON tpengadaan.pgid = tkontrak_penunjukan.pgid LEFT JOIN ".$dbcontract.".tprogress_serahterima ON tpengadaan.pgid = tprogress_serahterima.pgid LEFT JOIN ".$dbcontract.".tprogress_pembayaran ON tpengadaan.pgid = tprogress_pembayaran.pgid LEFT JOIN ".$dbcontract.".tprogress_pembayaran_bukti ON tpengadaan.pgid = tprogress_pembayaran_bukti.pgid WHERE tpengadaan.ta = ".$year." AND tpengadaan.pekerjaanstatus = 7 "; if (strtoupper($organization) <> 'ALL') { $sql .= "AND tpengadaan.skpdID = (SELECT skpdID FROM ".$dbmain.".tbl_skpd WHERE nama = '".$organization."' OR unitID = '".$organization."')"; } //die($sql); $results = $this->arrayPaginator(DB::select($sql), request()); return response() ->json($results) ->header('Access-Control-Allow-Origin', '*'); } public function get_rencana($year, $organization) { $dbplanning = env('DB_PLANNING'); $dbmain = env('DB_PRIME'); if (strtoupper($organization) == 'ALL') { $sql = 'SELECT * FROM '.$dbplanning.'.tbl_sirup WHERE tahun = '.$year.' '; } else { $sql = 'SELECT nama FROM '.$dbmain.'.tbl_skpd WHERE unitID = \''.$organization.'\''; $rsskpd = DB::select($sql); if (sizeof($rsskpd) != 0) { $rsskpd = $rsskpd[0]; $organization = $rsskpd->nama; } $sql = 'SELECT * FROM '.$dbplanning.'.tbl_sirup WHERE tahun = '.$year.' AND satuan_kerja = \''.$organization.'\''; } $results = $this->arrayPaginator(DB::select($sql), request()); return response() ->json($results) ->header('Access-Control-Allow-Origin', '*'); } }
7,194
https://github.com/Chondo94/SchoolDb/blob/master/app/SubjectYear.php
Github Open Source
Open Source
MIT
null
SchoolDb
Chondo94
PHP
Code
58
175
<?php namespace App; use Illuminate\Database\Eloquent\Model; class SubjectYear extends Model { protected $fillable = ['subject_id', 'year_id', 'teacher_id']; //esta es una relacion hijo y se coloca en singular, cuando es relacion padre va en plural public function year(){ return $this->belongsTo('App\Year'); } public function teacher(){ return $this->belongsTo('App\Teacher'); } public function subject(){ return $this->belongsTo('App\Subject'); } public function enrollments(){ return $this->hasMany('App\Enrollment'); } }
44,352
https://github.com/jbmolle/vue-keycloak-js/blob/master/src/types.ts
Github Open Source
Open Source
ISC
null
vue-keycloak-js
jbmolle
TypeScript
Code
458
1,268
import type { KeycloakConfig, KeycloakError, KeycloakInitOptions, KeycloakInstance, KeycloakLoginOptions, KeycloakProfile, KeycloakPromise, KeycloakResourceAccess, KeycloakRoles, KeycloakTokenParsed, } from 'keycloak-js' import type { App } from 'vue' export { KeycloakConfig, KeycloakError, KeycloakInitOptions, KeycloakInstance, KeycloakLoginOptions, KeycloakProfile, KeycloakPromise, KeycloakResourceAccess, KeycloakRoles, KeycloakTokenParsed, } export interface Vue2Vue3App extends App { prototype?: unknown, // eslint-disable-next-line @typescript-eslint/no-explicit-any observable?: any } export type VueKeycloakConfig = KeycloakConfig | string; export interface VueKeycloakOptions { config?: VueKeycloakConfig; init?: KeycloakInitOptions; // This is not defined in keycloak // eslint-disable-next-line @typescript-eslint/no-explicit-any logout?: any; onReady?: ( keycloak: KeycloakInstance, VueKeycloak?: VueKeycloakInstance ) => void; onInitError?: (error: Error, err: KeycloakError) => void; onAuthRefreshError?: (keycloak: KeycloakInstance) => void; onInitSuccess?(authenticated: boolean, keycloak?: KeycloakInstance, VueKeycloak?: VueKeycloakInstance): void; } export interface VueKeycloakTokenParsed extends KeycloakTokenParsed { preferred_username?: string; name?: string; } export interface VueKeycloakInstance { ready: boolean; // Flag indicating whether Keycloak has initialised and is ready authenticated: boolean; userName?: string; // Username from Keycloak. Collected from tokenParsed['preferred_username'] fullName?: string; // Full name from Keycloak. Collected from tokenParsed['name'] login?(options?: KeycloakLoginOptions): KeycloakPromise<void, void>; // [Keycloak] login function loginFn?(options?: KeycloakLoginOptions): KeycloakPromise<void, void>; // Alias for login // This is not defined in keycloak // eslint-disable-next-line @typescript-eslint/no-explicit-any logoutFn?(options?: any): KeycloakPromise<void, void> | void; // Keycloak logout function createLoginUrl?(options?: KeycloakLoginOptions): string; // Keycloak createLoginUrl function // This is not defined in keycloak // eslint-disable-next-line @typescript-eslint/no-explicit-any createLogoutUrl?(options?: any): string; // Keycloak createLogoutUrl function createRegisterUrl?(options?: KeycloakLoginOptions): string; // Keycloak createRegisterUrl function register?(options?: KeycloakLoginOptions): KeycloakPromise<void, void>; // Keycloak register function accountManagement?(): KeycloakPromise<void, void>; // Keycloak accountManagement function createAccountUrl?(): string; // Keycloak createAccountUrl function loadUserProfile?(): KeycloakPromise<KeycloakProfile, void>; // Keycloak loadUserProfile function subject?: string; // The user id idToken?: string; // The base64 encoded ID token. idTokenParsed?: VueKeycloakTokenParsed; // The parsed id token as a JavaScript object. realmAccess?: KeycloakRoles; // The realm roles associated with the token. resourceAccess?: KeycloakResourceAccess; // The resource roles associated with the token. refreshToken?: string; // The base64 encoded refresh token that can be used to retrieve a new token. refreshTokenParsed?: VueKeycloakTokenParsed; // The parsed refresh token as a JavaScript object. timeSkew?: number; // The estimated time difference between the browser time and the Keycloak server in seconds. This value is just an estimation, but is accurate enough when determining if a token is expired or not. responseMode?: string; // Response mode passed in init (default value is fragment). responseType?: string; // Response type sent to Keycloak with login requests. This is determined based on the flow value used during initialization, but can be overridden by setting this value. hasRealmRole?(role: string): boolean; // Keycloak hasRealmRole function hasResourceRole?(role: string, resource?: string): boolean; // Keycloak hasResourceRole function token?: string; // The base64 encoded token that can be sent in the Authorization header in requests to services tokenParsed?: VueKeycloakTokenParsed; // The parsed token as a JavaScript object keycloak?: KeycloakInstance; // The original keycloak instance 'as is' from keycloak-js adapter }
41,377
https://github.com/goodguyplayer/adventofcode2020/blob/master/src/main/java/challenges/challenge3/Challenge3.java
Github Open Source
Open Source
MIT
null
adventofcode2020
goodguyplayer
Java
Code
300
921
package challenges.challenge3; import interfaces.ChallengeBasics; import models.FileHandler; import java.util.List; public class Challenge3 implements ChallengeBasics { String pathexample = "src/main/java/challenges/challenge3/example.txt"; String pathchallenge = "src/main/java/challenges/challenge3/challenge.txt"; FileHandler fileHandler; public Challenge3() { } private void setFilePath(Boolean isTestingExample){ if (isTestingExample){ this.fileHandler = new FileHandler(pathexample); } else { this.fileHandler = new FileHandler(pathchallenge); } } private String expandLine(String line){ return line.concat(line); } private List<String> expandMap(List<String> map, int times){ for (int i = 0; i < times; i++) { for (int j = 0; j < map.size(); j++) { map.set(j, expandLine(map.get(j))); } } // printMap(map); return map; } private void printMap(List<String> map){ for (String line: map) { System.out.println(line); } } private Boolean isPositionATree(String position){ return (position.equals("#")) ? true : false; } // get proper line, split it, get "down" number" private String getPositionSymbol(List<String> map, int[] coordinates){ return map.get(coordinates[0]).split("")[coordinates[1]]; } private void calculateTheTrees(List<String> map, int right, int down){ List<String> expandedmap = expandMap(map, 4); int[] position = {0,0}; // "Down", "Right", starts at 0,0 String symbol = ""; int count = 0; for (int i = 1; i < map.size(); i++) { try { position[0] += down; position[1] += right; symbol = getPositionSymbol(expandedmap, position); if (isPositionATree(symbol)){ count += 1; } } catch (Exception e){ } } System.out.println(count); } @Override public void part1(Boolean isTestingExample){ setFilePath(isTestingExample); List<String> thedata = fileHandler.readFile(); calculateTheTrees(thedata, 3, 1); // thedata = expandMap(thedata,6); // int[] position = {0,0}; // "Down", "Right", starts at 0,0 // String symbol = ""; // int count = 0; // for (int i = 1; i < thedata.size(); i++) { // position[0] += 1; // position[1] += 3; // symbol = getPositionSymbol(thedata, position); // if (isPositionATree(symbol)){ // count += 1; // } // } // System.out.println(count); } @Override public void part2(Boolean isTestingExample){ setFilePath(isTestingExample); List<String> thedata = fileHandler.readFile(); calculateTheTrees(thedata, 1, 1); calculateTheTrees(thedata, 3, 1); calculateTheTrees(thedata, 5, 1); calculateTheTrees(thedata, 7, 1); calculateTheTrees(thedata, 7, 2); } }
7,894
https://github.com/profjordanov/JJ-Online-Store/blob/master/Web/JjOnlineStore.Api/Configuration/ApiMiddlewareConfiguration.cs
Github Open Source
Open Source
MIT
2,021
JJ-Online-Store
profjordanov
C#
Code
35
134
using Microsoft.AspNetCore.Builder; namespace JjOnlineStore.Api.Configuration { public static class ApiMiddlewareConfiguration { public static void UseSwagger(this IApplicationBuilder app, string endpointName) { app.UseSwagger(); app.UseSwaggerUI(setup => { setup.RoutePrefix = string.Empty; setup.SwaggerEndpoint( url: "/swagger/v1/swagger.json", name: endpointName); }); } } }
49,300
https://github.com/TrendingTechnology/vue-pincode/blob/master/src/App.vue
Github Open Source
Open Source
MIT
2,020
vue-pincode
TrendingTechnology
Vue
Code
88
360
<template> <div id="app"> <img alt="Vue logo" src="./assets/logo.png" /> <div class="container"> <vue-pincode ref="pincodeInput" @pincode="checkPincode" /> </div> </div> </template> <script> import VuePincode from "./components/VuePincode"; export default { name: "App", components: { VuePincode }, methods: { checkPincode(pincode) { setTimeout(() => { if (pincode === "1234") { this.$refs.pincodeInput.triggerSuccess(); } else { this.$refs.pincodeInput.triggerMiss(); } }, 700); } } }; </script> <style lang="scss"> #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } .container { max-width: 320px; margin: auto; } body { background: #e5e5e5; } </style>
35,690
https://github.com/fantongkw/oa/blob/master/src/main/java/com/ccc/oa/dao/DepartmentDao.java
Github Open Source
Open Source
Apache-2.0
2,021
oa
fantongkw
Java
Code
44
181
package com.ccc.oa.dao; import com.ccc.oa.model.Department; import com.ccc.oa.model.Member; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import java.util.List; @Repository(value = "DepartmentDao") public interface DepartmentDao { int deleteById(@Param("id") Long id); int insert(Department department); List<Department> selectAllDepartment(); List<Department> selectChildren(@Param("id") Long id); Department selectById(@Param("id") Long id); List<Member> selectUsers(@Param("id") Long id); int updateById(Department department); }
10,397
https://github.com/isapi/tantalis-neo3-nft-and-data-dapp/blob/master/nft-api/src/catalog/repository/nft.category.repository.ts
Github Open Source
Open Source
MIT
2,021
tantalis-neo3-nft-and-data-dapp
isapi
TypeScript
Code
21
63
import { EntityRepository, Repository } from 'typeorm'; import { NftCategoryEntity } from '../../entity/nft.category.entity'; @EntityRepository(NftCategoryEntity) export class NftCategoryRepository extends Repository<NftCategoryEntity> { }
3,691
https://github.com/tantangin/my_auth_ci3/blob/master/themes/admin/azzara/pages/Transaksi/stokin/partials/_input.php
Github Open Source
Open Source
MIT
2,022
my_auth_ci3
tantangin
PHP
Code
354
1,509
<div class="form-group"> <label for="pilih_barang">Pilih Nama Barang</label> <select class="js-data-example-ajax form-control p-1" id="pilih_barang" name="pilih_barang"> <?php if ($restok->barang_id) : ?> <option value="<?= $restok->barang_id; ?>" selected><?= $restok->barang->nama; ?></option> <?php endif; ?> </select> </div> <div class="form-group form-group-default"> <label for="nama">Nama barang</label> <input class="form-control" id="barang_id" hidden name="barang_id" readonly value="<?= $restok->barang_id ?>" /> <input class="form-control" id="nama" readonly value="<?= $restok->barang_id ? $restok->barang->nama : ''; ?>" /> </div> <div class="row"> <div class="col-md-6"> <div class="form-group form-group-default"> <label for="satuan">Satuan</label> <input class="form-control" id="satuan" readonly value="<?= $restok->barang_id ? $restok->barang->satuan->nama : ''; ?>" /> </div> </div> <div class="col-md-6"> <div class="form-group form-group-default"> <label for="stock_awal">Stok Barang</label> <input class="form-control" name="stock_awal" id="stock_awal" readonly value="<?= $restok->barang_id ? $restok->barang->stok : ''; ?>" /> <?= form_error('stock_awal', '<small class="text-danger">', '</small>'); ?> </div> </div> </div> <div class="row"> <div class="col-md-6"> <div class="form-group form-group-default"> <label for="suplier_id_" class="mb-2">Suplier</label> <input type="hidden" name="jenis" id="jenis" hidden value="<?= $restok->jenis; ?>"> <input type="hidden" name="suplier_id" id="suplier_id" hidden value="<?= $restok->suplier_id; ?>"> <select class="js-data-example-ajax form-control p-1" id="suplier_id_" name="suplier_id_"> <?php if ($restok->suplier_id) : ?> <option value="<?= $restok->suplier_id; ?>" selected><?= $restok->suplier->nama; ?></option> <?php else : ?> <option value="" selected disabled>-Pilih Suplier-</option> <?php endif; ?> </select> <?= form_error('suplier_id', '<small class="text-danger">', '</small>'); ?> </div> </div> <div class="col-md-6"> <div class="form-group form-group-default"> <label for="jumlah">Stok Tambah</label> <input class="form-control" value="<?= $restok->jumlah; ?>" type="number" name="jumlah" id="jumlah" /> <?= form_error('jumlah', '<small class="text-danger">', '</small>'); ?> </div> </div> </div> <script> $(document).ready(function() { $("#pilih_barang").select2({ ajax: { url: baseUrl + "admin/barang/data/datatable", processResults: function(data, params) { params.page = params.page || 1; return { results: data.data, pagination: { more: (params.page * 10) < data.recordsFiltered } }; }, data: function(params) { let query = { search: params.term, with: "satuan", page: params.page || 1 } // Query parameters will be ?search=[term]&type=public return query; } } }); $("#pilih_barang").on('select2:select', function(e) { let barang = e.params.data; set_barang(barang) }); $("#suplier_id_").select2({ ajax: { url: baseUrl + "admin/suplier/data/datatable", processResults: function(data, params) { params.page = params.page || 1; return { results: data.data, pagination: { more: (params.page * 10) < data.recordsFiltered } }; }, data: function(params) { let query = { search: params.term, page: params.page || 1 } // Query parameters will be ?search=[term]&type=public return query; } } }); $('#suplier_id_').on('select2:select', function(e) { let suplier = e.params.data; $("#suplier_id").val(suplier.id); }); let suplier_id = $("#suplier_id").val(); if (suplier_id) $('#suplier_id_').val(suplier_id).change(); function set_barang(barang) { $("#nama").val(barang.nama); $("#barang_id").val(barang.id); $("#satuan").val(barang.satuan.nama); $("#stock_awal").val(barang.stok); } }); </script>
50,534
https://github.com/iagodahlem/clima-cli/blob/master/tests/commands/version.test.js
Github Open Source
Open Source
MIT
2,018
clima-cli
iagodahlem
JavaScript
Code
27
82
const versionCommand = require('../../src/commands/version') describe('version command', () => { beforeEach(() => { global.console.log = jest.fn() }) it('logs the package version', () => { versionCommand() expect(console.log).toBeCalled() }) })
38,379
https://github.com/TestowanieAutomatyczneUG/laboratorium-9-SzymonWilczewski/blob/master/src/zad03/checker.py
Github Open Source
Open Source
MIT
null
laboratorium-9-SzymonWilczewski
TestowanieAutomatyczneUG
Python
Code
27
111
from src.zad03.env import Env class Checker: def __init__(self): self.env = Env() def remainder(self, file): time = self.env.getTime() if time > 17: self.env.playWavFile(file) return self.env.wavWasPlayed(file) else: return self.env.resetWav(file)
5,342
https://github.com/nandakumar131/hadoop-ozone/blob/master/hadoop-hdds/config/src/main/java/org/apache/hadoop/hdds/conf/TimeDurationUtil.java
Github Open Source
Open Source
Apache-2.0
2,022
hadoop-ozone
nandakumar131
Java
Code
521
1,223
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 org.apache.hadoop.hdds.conf; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Utility to handle time duration. */ public final class TimeDurationUtil { public static final Logger LOG = LoggerFactory.getLogger(TimeDurationUtil.class); private TimeDurationUtil() { } /** * Return time duration in the given time unit. Valid units are encoded in * properties as suffixes: nanoseconds (ns), microseconds (us), milliseconds * (ms), seconds (s), minutes (m), hours (h), and days (d). * * @param name Property name * @param vStr The string value with time unit suffix to be converted. * @param unit Unit to convert the stored property, if it exists. */ public static long getTimeDurationHelper(String name, String vStr, TimeUnit unit) { vStr = vStr.trim(); vStr = vStr.toLowerCase(); ParsedTimeDuration vUnit = ParsedTimeDuration.unitFor(vStr); if (null == vUnit) { LOG.warn("No unit for " + name + "(" + vStr + ") assuming " + unit); vUnit = ParsedTimeDuration.unitFor(unit); if (null == vUnit) { throw new IllegalArgumentException("Unexpected unit: " + unit); } } else { vStr = vStr.substring(0, vStr.lastIndexOf(vUnit.suffix())); } long raw = Long.parseLong(vStr); long converted = unit.convert(raw, vUnit.unit()); if (vUnit.unit().convert(converted, unit) < raw) { LOG.warn("Possible loss of precision converting " + vStr + vUnit.suffix() + " to " + unit + " for " + name); } return converted; } enum ParsedTimeDuration { NS { @Override TimeUnit unit() { return TimeUnit.NANOSECONDS; } @Override String suffix() { return "ns"; } }, US { @Override TimeUnit unit() { return TimeUnit.MICROSECONDS; } @Override String suffix() { return "us"; } }, MS { @Override TimeUnit unit() { return TimeUnit.MILLISECONDS; } @Override String suffix() { return "ms"; } }, S { @Override TimeUnit unit() { return TimeUnit.SECONDS; } @Override String suffix() { return "s"; } }, M { @Override TimeUnit unit() { return TimeUnit.MINUTES; } @Override String suffix() { return "m"; } }, H { @Override TimeUnit unit() { return TimeUnit.HOURS; } @Override String suffix() { return "h"; } }, D { @Override TimeUnit unit() { return TimeUnit.DAYS; } @Override String suffix() { return "d"; } }; abstract TimeUnit unit(); abstract String suffix(); static ParsedTimeDuration unitFor(String s) { for (ParsedTimeDuration ptd : values()) { // iteration order is in decl order, so SECONDS matched last if (s.endsWith(ptd.suffix())) { return ptd; } } return null; } static ParsedTimeDuration unitFor(TimeUnit unit) { for (ParsedTimeDuration ptd : values()) { if (ptd.unit() == unit) { return ptd; } } return null; } } }
47,016
https://github.com/ScottGlenn2/vole/blob/master/vole-portal/src/main/java/com/github/vole/portal/service/impl/SysMenuServiceImpl.java
Github Open Source
Open Source
Apache-2.0
2,020
vole
ScottGlenn2
Java
Code
96
525
package com.github.vole.portal.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.github.vole.portal.model.entity.SysMenu; import com.github.vole.portal.mapper.SysMenuMapper; import com.github.vole.portal.model.vo.TreeMenuAllowAccess; import com.github.vole.portal.service.ISysMenuService; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; /** * * SysMenu 表数据服务层接口实现类 * */ @Service public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService { @Override public List<TreeMenuAllowAccess> selectTreeMenuAllowAccessByMenuIdsAndPid( final List<String> menuIds, String pid) { QueryWrapper<SysMenu> ew = new QueryWrapper<SysMenu>(); ew.orderByAsc("sort"); ew.eq("parent_id", pid); List<SysMenu> sysMenus = this.list(ew); List<TreeMenuAllowAccess> treeMenuAllowAccesss = new ArrayList<TreeMenuAllowAccess>(); for(SysMenu sysMenu : sysMenus){ TreeMenuAllowAccess treeMenuAllowAccess = new TreeMenuAllowAccess(); treeMenuAllowAccess.setSysMenu(sysMenu); /** * 是否有权限 */ if(menuIds.contains(sysMenu.getId().toString())){ treeMenuAllowAccess.setAllowAccess(1); } /** * 子节点 */ if(sysMenu.getDeep() < 3){ treeMenuAllowAccess.setChildren(selectTreeMenuAllowAccessByMenuIdsAndPid(menuIds,sysMenu.getId().toString())); } treeMenuAllowAccesss.add(treeMenuAllowAccess); } return treeMenuAllowAccesss; } }
39,986
https://github.com/zettadb/zettalib/blob/master/src/vendor/mariadb-10.6.7/storage/innobase/btr/btr0bulk.cc
Github Open Source
Open Source
Apache-2.0
null
zettalib
zettadb
C++
Code
3,758
14,672
/***************************************************************************** Copyright (c) 2014, 2019, Oracle and/or its affiliates. All Rights Reserved. Copyright (c) 2017, 2021, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA *****************************************************************************/ /**************************************************//** @file btr/btr0bulk.cc The B-tree bulk load Created 03/11/2014 Shaohua Wang *******************************************************/ #include "btr0bulk.h" #include "btr0btr.h" #include "btr0cur.h" #include "btr0pcur.h" #include "ibuf0ibuf.h" #include "page0page.h" #include "trx0trx.h" /** Innodb B-tree index fill factor for bulk load. */ uint innobase_fill_factor; /** Initialize members, allocate page if needed and start mtr. Note: we commit all mtrs on failure. @return error code. */ dberr_t PageBulk::init() { buf_block_t* new_block; page_t* new_page; ut_ad(m_heap == NULL); m_heap = mem_heap_create(1000); m_mtr.start(); m_index->set_modified(m_mtr); if (m_page_no == FIL_NULL) { mtr_t alloc_mtr; /* We commit redo log for allocation by a separate mtr, because we don't guarantee pages are committed following the allocation order, and we will always generate redo log for page allocation, even when creating a new tablespace. */ alloc_mtr.start(); m_index->set_modified(alloc_mtr); uint32_t n_reserved; if (!fsp_reserve_free_extents(&n_reserved, m_index->table->space, 1, FSP_NORMAL, &alloc_mtr)) { alloc_mtr.commit(); m_mtr.commit(); return(DB_OUT_OF_FILE_SPACE); } /* Allocate a new page. */ new_block = btr_page_alloc(m_index, 0, FSP_UP, m_level, &alloc_mtr, &m_mtr); m_index->table->space->release_free_extents(n_reserved); alloc_mtr.commit(); new_page = buf_block_get_frame(new_block); m_page_no = new_block->page.id().page_no(); byte* index_id = my_assume_aligned<2> (PAGE_HEADER + PAGE_INDEX_ID + new_page); compile_time_assert(FIL_PAGE_NEXT == FIL_PAGE_PREV + 4); compile_time_assert(FIL_NULL == 0xffffffff); memset_aligned<8>(new_page + FIL_PAGE_PREV, 0xff, 8); if (UNIV_LIKELY_NULL(new_block->page.zip.data)) { mach_write_to_8(index_id, m_index->id); page_create_zip(new_block, m_index, m_level, 0, &m_mtr); } else { ut_ad(!m_index->is_spatial()); page_create(new_block, &m_mtr, m_index->table->not_redundant()); m_mtr.memset(*new_block, FIL_PAGE_PREV, 8, 0xff); m_mtr.write<2,mtr_t::MAYBE_NOP>(*new_block, PAGE_HEADER + PAGE_LEVEL + new_page, m_level); m_mtr.write<8>(*new_block, index_id, m_index->id); } } else { new_block = btr_block_get(*m_index, m_page_no, RW_X_LATCH, false, &m_mtr); new_page = buf_block_get_frame(new_block); ut_ad(new_block->page.id().page_no() == m_page_no); ut_ad(page_dir_get_n_heap(new_page) == PAGE_HEAP_NO_USER_LOW); btr_page_set_level(new_block, m_level, &m_mtr); } m_page_zip = buf_block_get_page_zip(new_block); if (!m_level && dict_index_is_sec_or_ibuf(m_index)) { page_update_max_trx_id(new_block, m_page_zip, m_trx_id, &m_mtr); } m_block = new_block; m_page = new_page; m_cur_rec = page_get_infimum_rec(new_page); ut_ad(m_is_comp == !!page_is_comp(new_page)); m_free_space = page_get_free_space_of_empty(m_is_comp); if (innobase_fill_factor == 100 && dict_index_is_clust(m_index)) { /* Keep default behavior compatible with 5.6 */ m_reserved_space = dict_index_get_space_reserve(); } else { m_reserved_space = srv_page_size * (100 - innobase_fill_factor) / 100; } m_padding_space = srv_page_size - dict_index_zip_pad_optimal_page_size(m_index); m_heap_top = page_header_get_ptr(new_page, PAGE_HEAP_TOP); m_rec_no = page_header_get_field(new_page, PAGE_N_RECS); /* Temporarily reset PAGE_DIRECTION_B from PAGE_NO_DIRECTION to 0, without writing redo log, to ensure that needs_finish() will hold on an empty page. */ ut_ad(m_page[PAGE_HEADER + PAGE_DIRECTION_B] == PAGE_NO_DIRECTION); m_page[PAGE_HEADER + PAGE_DIRECTION_B] = 0; ut_d(m_total_data = 0); return(DB_SUCCESS); } /** Insert a record in the page. @tparam fmt the page format @param[in,out] rec record @param[in] offsets record offsets */ template<PageBulk::format fmt> inline void PageBulk::insertPage(rec_t *rec, rec_offs *offsets) { ut_ad((m_page_zip != nullptr) == (fmt == COMPRESSED)); ut_ad((fmt != REDUNDANT) == m_is_comp); ut_ad(page_align(m_heap_top) == m_page); ut_ad(m_heap); const ulint rec_size= rec_offs_size(offsets); const ulint extra_size= rec_offs_extra_size(offsets); ut_ad(page_align(m_heap_top + rec_size) == m_page); ut_d(const bool is_leaf= page_rec_is_leaf(m_cur_rec)); #ifdef UNIV_DEBUG /* Check whether records are in order. */ if (page_offset(m_cur_rec) != (fmt == REDUNDANT ? PAGE_OLD_INFIMUM : PAGE_NEW_INFIMUM)) { const rec_t *old_rec = m_cur_rec; rec_offs *old_offsets= rec_get_offsets(old_rec, m_index, nullptr, is_leaf ? m_index->n_core_fields : 0, ULINT_UNDEFINED, &m_heap); ut_ad(cmp_rec_rec(rec, old_rec, offsets, old_offsets, m_index) > 0); } m_total_data+= rec_size; #endif /* UNIV_DEBUG */ rec_t* const insert_rec= m_heap_top + extra_size; /* Insert the record in the linked list. */ if (fmt != REDUNDANT) { const rec_t *next_rec= m_page + page_offset(m_cur_rec + mach_read_from_2(m_cur_rec - REC_NEXT)); if (fmt != COMPRESSED) m_mtr.write<2>(*m_block, m_cur_rec - REC_NEXT, static_cast<uint16_t>(insert_rec - m_cur_rec)); else { mach_write_to_2(m_cur_rec - REC_NEXT, static_cast<uint16_t>(insert_rec - m_cur_rec)); memcpy(m_heap_top, rec - extra_size, rec_size); } rec_t * const this_rec= fmt != COMPRESSED ? const_cast<rec_t*>(rec) : insert_rec; rec_set_bit_field_1(this_rec, 0, REC_NEW_N_OWNED, REC_N_OWNED_MASK, REC_N_OWNED_SHIFT); rec_set_bit_field_2(this_rec, PAGE_HEAP_NO_USER_LOW + m_rec_no, REC_NEW_HEAP_NO, REC_HEAP_NO_MASK, REC_HEAP_NO_SHIFT); mach_write_to_2(this_rec - REC_NEXT, static_cast<uint16_t>(next_rec - insert_rec)); } else { memcpy(const_cast<rec_t*>(rec) - REC_NEXT, m_cur_rec - REC_NEXT, 2); m_mtr.write<2>(*m_block, m_cur_rec - REC_NEXT, page_offset(insert_rec)); rec_set_bit_field_1(const_cast<rec_t*>(rec), 0, REC_OLD_N_OWNED, REC_N_OWNED_MASK, REC_N_OWNED_SHIFT); rec_set_bit_field_2(const_cast<rec_t*>(rec), PAGE_HEAP_NO_USER_LOW + m_rec_no, REC_OLD_HEAP_NO, REC_HEAP_NO_MASK, REC_HEAP_NO_SHIFT); } if (fmt == COMPRESSED) /* We already wrote the record. Log is written in PageBulk::compress(). */; else if (page_offset(m_cur_rec) == (fmt == REDUNDANT ? PAGE_OLD_INFIMUM : PAGE_NEW_INFIMUM)) m_mtr.memcpy(*m_block, m_heap_top, rec - extra_size, rec_size); else { /* Try to copy common prefix from the preceding record. */ const byte *r= rec - extra_size; const byte * const insert_rec_end= m_heap_top + rec_size; byte *b= m_heap_top; /* Skip any unchanged prefix of the record. */ for (; * b == *r; b++, r++); ut_ad(b < insert_rec_end); const byte *c= m_cur_rec - (rec - r); const byte * const c_end= std::min(m_cur_rec + rec_offs_data_size(offsets), m_heap_top); /* Try to copy any bytes of the preceding record. */ if (UNIV_LIKELY(c >= m_page && c < c_end)) { const byte *cm= c; byte *bm= b; const byte *rm= r; for (; cm < c_end && *rm == *cm; cm++, bm++, rm++); ut_ad(bm <= insert_rec_end); size_t len= static_cast<size_t>(rm - r); ut_ad(!memcmp(r, c, len)); if (len > 2) { memcpy(b, c, len); m_mtr.memmove(*m_block, page_offset(b), page_offset(c), len); c= cm; b= bm; r= rm; } } if (c < m_cur_rec) { if (!rec_offs_data_size(offsets)) { no_data: m_mtr.memcpy<mtr_t::FORCED>(*m_block, b, r, m_cur_rec - c); goto rec_done; } /* Some header bytes differ. Compare the data separately. */ const byte *cd= m_cur_rec; byte *bd= insert_rec; const byte *rd= rec; /* Skip any unchanged prefix of the record. */ for (;; cd++, bd++, rd++) if (bd == insert_rec_end) goto no_data; else if (*bd != *rd) break; /* Try to copy any data bytes of the preceding record. */ if (c_end - cd > 2) { const byte *cdm= cd; const byte *rdm= rd; for (; cdm < c_end && *rdm == *cdm; cdm++, rdm++) ut_ad(rdm - rd + bd <= insert_rec_end); size_t len= static_cast<size_t>(rdm - rd); ut_ad(!memcmp(rd, cd, len)); if (len > 2) { m_mtr.memcpy<mtr_t::FORCED>(*m_block, b, r, m_cur_rec - c); memcpy(bd, cd, len); m_mtr.memmove(*m_block, page_offset(bd), page_offset(cd), len); c= cdm; b= rdm - rd + bd; r= rdm; } } } if (size_t len= static_cast<size_t>(insert_rec_end - b)) m_mtr.memcpy<mtr_t::FORCED>(*m_block, b, r, len); } rec_done: ut_ad(fmt == COMPRESSED || !memcmp(m_heap_top, rec - extra_size, rec_size)); rec_offs_make_valid(insert_rec, m_index, is_leaf, offsets); /* Update the member variables. */ ulint slot_size= page_dir_calc_reserved_space(m_rec_no + 1) - page_dir_calc_reserved_space(m_rec_no); ut_ad(m_free_space >= rec_size + slot_size); ut_ad(m_heap_top + rec_size < m_page + srv_page_size); m_free_space-= rec_size + slot_size; m_heap_top+= rec_size; m_rec_no++; m_cur_rec= insert_rec; } /** Insert a record in the page. @param[in] rec record @param[in] offsets record offsets */ inline void PageBulk::insert(const rec_t *rec, rec_offs *offsets) { byte rec_hdr[REC_N_OLD_EXTRA_BYTES]; static_assert(REC_N_OLD_EXTRA_BYTES > REC_N_NEW_EXTRA_BYTES, "file format"); if (UNIV_LIKELY_NULL(m_page_zip)) insertPage<COMPRESSED>(const_cast<rec_t*>(rec), offsets); else if (m_is_comp) { memcpy(rec_hdr, rec - REC_N_NEW_EXTRA_BYTES, REC_N_NEW_EXTRA_BYTES); insertPage<DYNAMIC>(const_cast<rec_t*>(rec), offsets); memcpy(const_cast<rec_t*>(rec) - REC_N_NEW_EXTRA_BYTES, rec_hdr, REC_N_NEW_EXTRA_BYTES); } else { memcpy(rec_hdr, rec - REC_N_OLD_EXTRA_BYTES, REC_N_OLD_EXTRA_BYTES); insertPage<REDUNDANT>(const_cast<rec_t*>(rec), offsets); memcpy(const_cast<rec_t*>(rec) - REC_N_OLD_EXTRA_BYTES, rec_hdr, REC_N_OLD_EXTRA_BYTES); } } /** Set the number of owned records in the uncompressed page of a ROW_FORMAT=COMPRESSED record without redo-logging. */ static void rec_set_n_owned_zip(rec_t *rec, ulint n_owned) { rec_set_bit_field_1(rec, n_owned, REC_NEW_N_OWNED, REC_N_OWNED_MASK, REC_N_OWNED_SHIFT); } /** Mark end of insertion to the page. Scan all records to set page dirs, and set page header members. @tparam fmt page format */ template<PageBulk::format fmt> inline void PageBulk::finishPage() { ut_ad((m_page_zip != nullptr) == (fmt == COMPRESSED)); ut_ad((fmt != REDUNDANT) == m_is_comp); ulint count= 0; ulint n_recs= 0; byte *slot= my_assume_aligned<2>(m_page + srv_page_size - (PAGE_DIR + PAGE_DIR_SLOT_SIZE)); const page_dir_slot_t *const slot0 = slot; compile_time_assert(PAGE_DIR_SLOT_SIZE == 2); if (fmt != REDUNDANT) { uint16_t offset= mach_read_from_2(PAGE_NEW_INFIMUM - REC_NEXT + m_page); ut_ad(offset >= PAGE_NEW_SUPREMUM - PAGE_NEW_INFIMUM); offset= static_cast<uint16_t>(offset + PAGE_NEW_INFIMUM); /* Set owner & dir. */ while (offset != PAGE_NEW_SUPREMUM) { ut_ad(offset >= PAGE_NEW_SUPREMUM); ut_ad(offset < page_offset(slot)); count++; n_recs++; if (count == (PAGE_DIR_SLOT_MAX_N_OWNED + 1) / 2) { slot-= PAGE_DIR_SLOT_SIZE; mach_write_to_2(slot, offset); if (fmt != COMPRESSED) page_rec_set_n_owned<false>(m_block, m_page + offset, count, true, &m_mtr); else rec_set_n_owned_zip(m_page + offset, count); count= 0; } uint16_t next= static_cast<uint16_t> ((mach_read_from_2(m_page + offset - REC_NEXT) + offset) & (srv_page_size - 1)); ut_ad(next); offset= next; } if (slot0 != slot && (count + 1 + (PAGE_DIR_SLOT_MAX_N_OWNED + 1) / 2 <= PAGE_DIR_SLOT_MAX_N_OWNED)) { /* Merge the last two slots, like page_cur_insert_rec_low() does. */ count+= (PAGE_DIR_SLOT_MAX_N_OWNED + 1) / 2; rec_t *rec= const_cast<rec_t*>(page_dir_slot_get_rec(slot)); if (fmt != COMPRESSED) page_rec_set_n_owned<false>(m_block, rec, 0, true, &m_mtr); else rec_set_n_owned_zip(rec, 0); } else slot-= PAGE_DIR_SLOT_SIZE; mach_write_to_2(slot, PAGE_NEW_SUPREMUM); if (fmt != COMPRESSED) page_rec_set_n_owned<false>(m_block, m_page + PAGE_NEW_SUPREMUM, count + 1, true, &m_mtr); else rec_set_n_owned_zip(m_page + PAGE_NEW_SUPREMUM, count + 1); } else { rec_t *insert_rec= m_page + mach_read_from_2(PAGE_OLD_INFIMUM - REC_NEXT + m_page); /* Set owner & dir. */ while (insert_rec != m_page + PAGE_OLD_SUPREMUM) { count++; n_recs++; if (count == (PAGE_DIR_SLOT_MAX_N_OWNED + 1) / 2) { slot-= PAGE_DIR_SLOT_SIZE; mach_write_to_2(slot, page_offset(insert_rec)); page_rec_set_n_owned<false>(m_block, insert_rec, count, false, &m_mtr); count= 0; } insert_rec= m_page + mach_read_from_2(insert_rec - REC_NEXT); } if (slot0 != slot && (count + 1 + (PAGE_DIR_SLOT_MAX_N_OWNED + 1) / 2 <= PAGE_DIR_SLOT_MAX_N_OWNED)) { /* Merge the last two slots, like page_cur_insert_rec_low() does. */ count+= (PAGE_DIR_SLOT_MAX_N_OWNED + 1) / 2; rec_t *rec= const_cast<rec_t*>(page_dir_slot_get_rec(slot)); page_rec_set_n_owned<false>(m_block, rec, 0, false, &m_mtr); } else slot-= PAGE_DIR_SLOT_SIZE; mach_write_to_2(slot, PAGE_OLD_SUPREMUM); page_rec_set_n_owned<false>(m_block, m_page + PAGE_OLD_SUPREMUM, count + 1, false, &m_mtr); } if (!m_rec_no); else if (fmt != COMPRESSED) { static_assert(PAGE_N_DIR_SLOTS == 0, "compatibility"); alignas(8) byte page_header[PAGE_N_HEAP + 2]; mach_write_to_2(page_header + PAGE_N_DIR_SLOTS, 1 + (slot0 - slot) / PAGE_DIR_SLOT_SIZE); mach_write_to_2(page_header + PAGE_HEAP_TOP, m_heap_top - m_page); mach_write_to_2(page_header + PAGE_N_HEAP, (PAGE_HEAP_NO_USER_LOW + m_rec_no) | uint16_t{fmt != REDUNDANT} << 15); m_mtr.memcpy(*m_block, PAGE_HEADER + m_page, page_header, sizeof page_header); m_mtr.write<2>(*m_block, PAGE_HEADER + PAGE_N_RECS + m_page, m_rec_no); m_mtr.memcpy(*m_block, page_offset(slot), slot0 - slot); } else { /* For ROW_FORMAT=COMPRESSED, redo log may be written in PageBulk::compress(). */ mach_write_to_2(PAGE_HEADER + PAGE_N_DIR_SLOTS + m_page, 1 + (slot0 - slot) / PAGE_DIR_SLOT_SIZE); mach_write_to_2(PAGE_HEADER + PAGE_HEAP_TOP + m_page, static_cast<ulint>(m_heap_top - m_page)); mach_write_to_2(PAGE_HEADER + PAGE_N_HEAP + m_page, (PAGE_HEAP_NO_USER_LOW + m_rec_no) | 1U << 15); mach_write_to_2(PAGE_HEADER + PAGE_N_RECS + m_page, m_rec_no); } } inline bool PageBulk::needs_finish() const { ut_ad(page_align(m_cur_rec) == m_block->page.frame); ut_ad(m_page == m_block->page.frame); if (!m_page[PAGE_HEADER + PAGE_DIRECTION_B]) return true; ulint heap_no, n_heap= page_header_get_field(m_page, PAGE_N_HEAP); ut_ad((n_heap & 0x7fff) >= PAGE_HEAP_NO_USER_LOW); if (n_heap & 0x8000) { n_heap&= 0x7fff; heap_no= rec_get_heap_no_new(m_cur_rec); if (heap_no == PAGE_HEAP_NO_INFIMUM && page_header_get_field(m_page, PAGE_HEAP_TOP) == PAGE_NEW_SUPREMUM_END) return false; } else { heap_no= rec_get_heap_no_old(m_cur_rec); if (heap_no == PAGE_HEAP_NO_INFIMUM && page_header_get_field(m_page, PAGE_HEAP_TOP) == PAGE_OLD_SUPREMUM_END) return false; } return heap_no != n_heap - 1; } /** Mark end of insertion to the page. Scan all records to set page dirs, and set page header members. @tparam compressed whether the page is in ROW_FORMAT=COMPRESSED */ inline void PageBulk::finish() { ut_ad(!m_index->is_spatial()); if (!needs_finish()); else if (UNIV_LIKELY_NULL(m_page_zip)) finishPage<COMPRESSED>(); else if (m_is_comp) finishPage<DYNAMIC>(); else finishPage<REDUNDANT>(); /* In MariaDB 10.2, 10.3, 10.4, we would initialize PAGE_DIRECTION_B, PAGE_N_DIRECTION, PAGE_LAST_INSERT in the same way as we would during normal INSERT operations. Starting with MariaDB Server 10.5, bulk insert will not touch those fields. */ ut_ad(!m_page[PAGE_HEADER + PAGE_INSTANT]); /* Restore the temporary change of PageBulk::init() that was necessary to ensure that PageBulk::needs_finish() holds on an empty page. */ m_page[PAGE_HEADER + PAGE_DIRECTION_B]= PAGE_NO_DIRECTION; ut_ad(!page_header_get_field(m_page, PAGE_FREE)); ut_ad(!page_header_get_field(m_page, PAGE_GARBAGE)); ut_ad(!page_header_get_field(m_page, PAGE_LAST_INSERT)); ut_ad(!page_header_get_field(m_page, PAGE_N_DIRECTION)); ut_ad(m_total_data + page_dir_calc_reserved_space(m_rec_no) <= page_get_free_space_of_empty(m_is_comp)); ut_ad(!needs_finish()); ut_ad(page_validate(m_page, m_index)); } /** Commit inserts done to the page @param[in] success Flag whether all inserts succeed. */ void PageBulk::commit(bool success) { finish(); if (success && !dict_index_is_clust(m_index) && page_is_leaf(m_page)) ibuf_set_bitmap_for_bulk_load(m_block, innobase_fill_factor == 100); m_mtr.commit(); } /** Compress a page of compressed table @return true compress successfully or no need to compress @return false compress failed. */ bool PageBulk::compress() { ut_ad(m_page_zip != NULL); return page_zip_compress(m_block, m_index, page_zip_level, &m_mtr); } /** Get node pointer @return node pointer */ dtuple_t* PageBulk::getNodePtr() { rec_t* first_rec; dtuple_t* node_ptr; /* Create node pointer */ first_rec = page_rec_get_next(page_get_infimum_rec(m_page)); ut_a(page_rec_is_user_rec(first_rec)); node_ptr = dict_index_build_node_ptr(m_index, first_rec, m_page_no, m_heap, m_level); return(node_ptr); } /** Get split rec in left page.We split a page in half when compresssion fails, and the split rec will be copied to right page. @return split rec */ rec_t* PageBulk::getSplitRec() { rec_t* rec; rec_offs* offsets; ulint total_used_size; ulint total_recs_size; ulint n_recs; ut_ad(m_page_zip != NULL); ut_ad(m_rec_no >= 2); ut_ad(!m_index->is_instant()); ut_ad(page_get_free_space_of_empty(m_is_comp) > m_free_space); total_used_size = page_get_free_space_of_empty(m_is_comp) - m_free_space; total_recs_size = 0; n_recs = 0; offsets = NULL; rec = page_get_infimum_rec(m_page); const ulint n_core = page_is_leaf(m_page) ? m_index->n_core_fields : 0; do { rec = page_rec_get_next(rec); ut_ad(page_rec_is_user_rec(rec)); offsets = rec_get_offsets(rec, m_index, offsets, n_core, ULINT_UNDEFINED, &m_heap); total_recs_size += rec_offs_size(offsets); n_recs++; } while (total_recs_size + page_dir_calc_reserved_space(n_recs) < total_used_size / 2); /* Keep at least one record on left page */ if (page_rec_is_infimum(page_rec_get_prev(rec))) { rec = page_rec_get_next(rec); ut_ad(page_rec_is_user_rec(rec)); } return(rec); } /** Copy all records after split rec including itself. @param[in] rec split rec */ void PageBulk::copyIn( rec_t* split_rec) { rec_t* rec = split_rec; rec_offs* offsets = NULL; ut_ad(m_rec_no == 0); ut_ad(page_rec_is_user_rec(rec)); const ulint n_core = page_rec_is_leaf(rec) ? m_index->n_core_fields : 0; do { offsets = rec_get_offsets(rec, m_index, offsets, n_core, ULINT_UNDEFINED, &m_heap); insert(rec, offsets); rec = page_rec_get_next(rec); } while (!page_rec_is_supremum(rec)); ut_ad(m_rec_no > 0); } /** Remove all records after split rec including itself. @param[in] rec split rec */ void PageBulk::copyOut( rec_t* split_rec) { rec_t* rec; rec_t* last_rec; ulint n; /* Suppose before copyOut, we have 5 records on the page: infimum->r1->r2->r3->r4->r5->supremum, and r3 is the split rec. after copyOut, we have 2 records on the page: infimum->r1->r2->supremum. slot ajustment is not done. */ rec = page_rec_get_next(page_get_infimum_rec(m_page)); last_rec = page_rec_get_prev(page_get_supremum_rec(m_page)); n = 0; while (rec != split_rec) { rec = page_rec_get_next(rec); n++; } ut_ad(n > 0); /* Set last record's next in page */ rec_offs* offsets = NULL; rec = page_rec_get_prev(split_rec); const ulint n_core = page_rec_is_leaf(split_rec) ? m_index->n_core_fields : 0; offsets = rec_get_offsets(rec, m_index, offsets, n_core, ULINT_UNDEFINED, &m_heap); mach_write_to_2(rec - REC_NEXT, m_is_comp ? static_cast<uint16_t> (PAGE_NEW_SUPREMUM - page_offset(rec)) : PAGE_OLD_SUPREMUM); /* Set related members */ m_cur_rec = rec; m_heap_top = rec_get_end(rec, offsets); offsets = rec_get_offsets(last_rec, m_index, offsets, n_core, ULINT_UNDEFINED, &m_heap); m_free_space += ulint(rec_get_end(last_rec, offsets) - m_heap_top) + page_dir_calc_reserved_space(m_rec_no) - page_dir_calc_reserved_space(n); ut_ad(lint(m_free_space) > 0); m_rec_no = n; #ifdef UNIV_DEBUG m_total_data -= ulint(rec_get_end(last_rec, offsets) - m_heap_top); #endif /* UNIV_DEBUG */ } /** Set next page @param[in] next_page_no next page no */ inline void PageBulk::setNext(ulint next_page_no) { if (UNIV_LIKELY_NULL(m_page_zip)) /* For ROW_FORMAT=COMPRESSED, redo log may be written in PageBulk::compress(). */ mach_write_to_4(m_page + FIL_PAGE_NEXT, next_page_no); else m_mtr.write<4>(*m_block, m_page + FIL_PAGE_NEXT, next_page_no); } /** Set previous page @param[in] prev_page_no previous page no */ inline void PageBulk::setPrev(ulint prev_page_no) { if (UNIV_LIKELY_NULL(m_page_zip)) /* For ROW_FORMAT=COMPRESSED, redo log may be written in PageBulk::compress(). */ mach_write_to_4(m_page + FIL_PAGE_PREV, prev_page_no); else m_mtr.write<4>(*m_block, m_page + FIL_PAGE_PREV, prev_page_no); } /** Check if required space is available in the page for the rec to be inserted. We check fill factor & padding here. @param[in] length required length @return true if space is available */ bool PageBulk::isSpaceAvailable( ulint rec_size) { ulint slot_size; ulint required_space; slot_size = page_dir_calc_reserved_space(m_rec_no + 1) - page_dir_calc_reserved_space(m_rec_no); required_space = rec_size + slot_size; if (required_space > m_free_space) { ut_ad(m_rec_no > 0); return false; } /* Fillfactor & Padding apply to both leaf and non-leaf pages. Note: we keep at least 2 records in a page to avoid B-tree level growing too high. */ if (m_rec_no >= 2 && ((m_page_zip == NULL && m_free_space - required_space < m_reserved_space) || (m_page_zip != NULL && m_free_space - required_space < m_padding_space))) { return(false); } return(true); } /** Check whether the record needs to be stored externally. @return false if the entire record can be stored locally on the page */ bool PageBulk::needExt( const dtuple_t* tuple, ulint rec_size) { return page_zip_rec_needs_ext(rec_size, m_is_comp, dtuple_get_n_fields(tuple), m_block->zip_size()); } /** Store external record Since the record is not logged yet, so we don't log update to the record. the blob data is logged first, then the record is logged in bulk mode. @param[in] big_rec external recrod @param[in] offsets record offsets @return error code */ dberr_t PageBulk::storeExt( const big_rec_t* big_rec, rec_offs* offsets) { finish(); /* Note: not all fields are initialized in btr_pcur. */ btr_pcur_t btr_pcur; btr_pcur.pos_state = BTR_PCUR_IS_POSITIONED; btr_pcur.latch_mode = BTR_MODIFY_LEAF; btr_pcur.btr_cur.index = m_index; btr_pcur.btr_cur.page_cur.index = m_index; btr_pcur.btr_cur.page_cur.rec = m_cur_rec; btr_pcur.btr_cur.page_cur.offsets = offsets; btr_pcur.btr_cur.page_cur.block = m_block; dberr_t err = btr_store_big_rec_extern_fields( &btr_pcur, offsets, big_rec, &m_mtr, BTR_STORE_INSERT_BULK); /* Reset m_block and m_cur_rec from page cursor, because block may be changed during blob insert. (FIXME: Can it really?) */ ut_ad(m_block == btr_pcur.btr_cur.page_cur.block); m_block = btr_pcur.btr_cur.page_cur.block; m_cur_rec = btr_pcur.btr_cur.page_cur.rec; m_page = buf_block_get_frame(m_block); return(err); } /** Release block by commiting mtr Note: log_free_check requires holding no lock/latch in current thread. */ void PageBulk::release() { finish(); /* We fix the block because we will re-pin it soon. */ m_block->page.fix(); /* No other threads can modify this block. */ m_modify_clock = buf_block_get_modify_clock(m_block); m_mtr.commit(); } /** Start mtr and latch the block */ dberr_t PageBulk::latch() { m_mtr.start(); m_index->set_modified(m_mtr); ut_ad(m_block->page.buf_fix_count()); /* In case the block is U-latched by page_cleaner. */ if (!buf_page_optimistic_get(RW_X_LATCH, m_block, m_modify_clock, &m_mtr)) { /* FIXME: avoid another lookup */ m_block = buf_page_get_gen(page_id_t(m_index->table->space_id, m_page_no), 0, RW_X_LATCH, m_block, BUF_GET_IF_IN_POOL, &m_mtr, &m_err); if (m_err != DB_SUCCESS) { return (m_err); } ut_ad(m_block != NULL); } ut_d(const auto buf_fix_count =) m_block->page.unfix(); ut_ad(buf_fix_count); ut_ad(m_cur_rec > m_page); ut_ad(m_cur_rec < m_heap_top); return (m_err); } /** Split a page @param[in] page_bulk page to split @param[in] next_page_bulk next page @return error code */ dberr_t BtrBulk::pageSplit( PageBulk* page_bulk, PageBulk* next_page_bulk) { ut_ad(page_bulk->getPageZip() != NULL); if (page_bulk->getRecNo() <= 1) { return(DB_TOO_BIG_RECORD); } /* Initialize a new page */ PageBulk new_page_bulk(m_index, m_trx->id, FIL_NULL, page_bulk->getLevel()); dberr_t err = new_page_bulk.init(); if (err != DB_SUCCESS) { return(err); } /* Copy the upper half to the new page. */ rec_t* split_rec = page_bulk->getSplitRec(); new_page_bulk.copyIn(split_rec); page_bulk->copyOut(split_rec); /* Commit the pages after split. */ err = pageCommit(page_bulk, &new_page_bulk, true); if (err != DB_SUCCESS) { pageAbort(&new_page_bulk); return(err); } err = pageCommit(&new_page_bulk, next_page_bulk, true); if (err != DB_SUCCESS) { pageAbort(&new_page_bulk); return(err); } return(err); } /** Commit(finish) a page. We set next/prev page no, compress a page of compressed table and split the page if compression fails, insert a node pointer to father page if needed, and commit mini-transaction. @param[in] page_bulk page to commit @param[in] next_page_bulk next page @param[in] insert_father false when page_bulk is a root page and true when it's a non-root page @return error code */ dberr_t BtrBulk::pageCommit( PageBulk* page_bulk, PageBulk* next_page_bulk, bool insert_father) { page_bulk->finish(); /* Set page links */ if (next_page_bulk != NULL) { ut_ad(page_bulk->getLevel() == next_page_bulk->getLevel()); page_bulk->setNext(next_page_bulk->getPageNo()); next_page_bulk->setPrev(page_bulk->getPageNo()); } else { ut_ad(!page_has_next(page_bulk->getPage())); /* If a page is released and latched again, we need to mark it modified in mini-transaction. */ page_bulk->set_modified(); } ut_ad(!m_index->lock.have_any()); /* Compress page if it's a compressed table. */ if (page_bulk->getPageZip() != NULL && !page_bulk->compress()) { return(pageSplit(page_bulk, next_page_bulk)); } /* Insert node pointer to father page. */ if (insert_father) { dtuple_t* node_ptr = page_bulk->getNodePtr(); dberr_t err = insert(node_ptr, page_bulk->getLevel()+1); if (err != DB_SUCCESS) { return(err); } } /* Commit mtr. */ page_bulk->commit(true); return(DB_SUCCESS); } /** Log free check */ inline void BtrBulk::logFreeCheck() { if (log_sys.check_flush_or_checkpoint()) { release(); log_check_margins(); latch(); } } /** Release all latches */ void BtrBulk::release() { ut_ad(m_root_level + 1 == m_page_bulks.size()); for (ulint level = 0; level <= m_root_level; level++) { PageBulk* page_bulk = m_page_bulks.at(level); page_bulk->release(); } } /** Re-latch all latches */ void BtrBulk::latch() { ut_ad(m_root_level + 1 == m_page_bulks.size()); for (ulint level = 0; level <= m_root_level; level++) { PageBulk* page_bulk = m_page_bulks.at(level); page_bulk->latch(); } } /** Insert a tuple to page in a level @param[in] tuple tuple to insert @param[in] level B-tree level @return error code */ dberr_t BtrBulk::insert( dtuple_t* tuple, ulint level) { bool is_left_most = false; dberr_t err = DB_SUCCESS; /* Check if we need to create a PageBulk for the level. */ if (level + 1 > m_page_bulks.size()) { PageBulk* new_page_bulk = UT_NEW_NOKEY(PageBulk(m_index, m_trx->id, FIL_NULL, level)); err = new_page_bulk->init(); if (err != DB_SUCCESS) { UT_DELETE(new_page_bulk); return(err); } m_page_bulks.push_back(new_page_bulk); ut_ad(level + 1 == m_page_bulks.size()); m_root_level = level; is_left_most = true; } ut_ad(m_page_bulks.size() > level); PageBulk* page_bulk = m_page_bulks.at(level); if (is_left_most && level > 0 && page_bulk->getRecNo() == 0) { /* The node pointer must be marked as the predefined minimum record, as there is no lower alphabetical limit to records in the leftmost node of a level: */ dtuple_set_info_bits(tuple, dtuple_get_info_bits(tuple) | REC_INFO_MIN_REC_FLAG); } ulint n_ext = 0; ulint rec_size = rec_get_converted_size(m_index, tuple, n_ext); big_rec_t* big_rec = NULL; rec_t* rec = NULL; rec_offs* offsets = NULL; if (page_bulk->needExt(tuple, rec_size)) { /* The record is so big that we have to store some fields externally on separate database pages */ big_rec = dtuple_convert_big_rec(m_index, 0, tuple, &n_ext); if (big_rec == NULL) { return(DB_TOO_BIG_RECORD); } rec_size = rec_get_converted_size(m_index, tuple, n_ext); } if (page_bulk->getPageZip() != NULL && page_zip_is_too_big(m_index, tuple)) { err = DB_TOO_BIG_RECORD; goto func_exit; } if (!page_bulk->isSpaceAvailable(rec_size)) { /* Create a sibling page_bulk. */ PageBulk* sibling_page_bulk; sibling_page_bulk = UT_NEW_NOKEY(PageBulk(m_index, m_trx->id, FIL_NULL, level)); err = sibling_page_bulk->init(); if (err != DB_SUCCESS) { UT_DELETE(sibling_page_bulk); goto func_exit; } /* Commit page bulk. */ err = pageCommit(page_bulk, sibling_page_bulk, true); if (err != DB_SUCCESS) { pageAbort(sibling_page_bulk); UT_DELETE(sibling_page_bulk); goto func_exit; } /* Set new page bulk to page_bulks. */ ut_ad(sibling_page_bulk->getLevel() <= m_root_level); m_page_bulks.at(level) = sibling_page_bulk; UT_DELETE(page_bulk); page_bulk = sibling_page_bulk; /* Important: log_free_check whether we need a checkpoint. */ if (page_is_leaf(sibling_page_bulk->getPage())) { if (trx_is_interrupted(m_trx)) { err = DB_INTERRUPTED; goto func_exit; } srv_inc_activity_count(); logFreeCheck(); } } /* Convert tuple to rec. */ rec = rec_convert_dtuple_to_rec(static_cast<byte*>(mem_heap_alloc( page_bulk->m_heap, rec_size)), m_index, tuple, n_ext); offsets = rec_get_offsets(rec, m_index, offsets, level ? 0 : m_index->n_core_fields, ULINT_UNDEFINED, &page_bulk->m_heap); page_bulk->insert(rec, offsets); if (big_rec != NULL) { ut_ad(dict_index_is_clust(m_index)); ut_ad(page_bulk->getLevel() == 0); ut_ad(page_bulk == m_page_bulks.at(0)); /* Release all pages above the leaf level */ for (ulint level = 1; level <= m_root_level; level++) { m_page_bulks.at(level)->release(); } err = page_bulk->storeExt(big_rec, offsets); /* Latch */ for (ulint level = 1; level <= m_root_level; level++) { PageBulk* page_bulk = m_page_bulks.at(level); page_bulk->latch(); } } func_exit: if (big_rec != NULL) { dtuple_convert_back_big_rec(m_index, tuple, big_rec); } return(err); } /** Btree bulk load finish. We commit the last page in each level and copy the last page in top level to the root page of the index if no error occurs. @param[in] err whether bulk load was successful until now @return error code */ dberr_t BtrBulk::finish(dberr_t err) { uint32_t last_page_no = FIL_NULL; ut_ad(!m_index->table->is_temporary()); if (m_page_bulks.size() == 0) { /* The table is empty. The root page of the index tree is already in a consistent state. No need to flush. */ return(err); } ut_ad(m_root_level + 1 == m_page_bulks.size()); /* Finish all page bulks */ for (ulint level = 0; level <= m_root_level; level++) { PageBulk* page_bulk = m_page_bulks.at(level); last_page_no = page_bulk->getPageNo(); if (err == DB_SUCCESS) { err = pageCommit(page_bulk, NULL, level != m_root_level); } if (err != DB_SUCCESS) { pageAbort(page_bulk); } UT_DELETE(page_bulk); } if (err == DB_SUCCESS) { rec_t* first_rec; mtr_t mtr; buf_block_t* last_block; PageBulk root_page_bulk(m_index, m_trx->id, m_index->page, m_root_level); mtr.start(); m_index->set_modified(mtr); mtr_x_lock_index(m_index, &mtr); ut_ad(last_page_no != FIL_NULL); last_block = btr_block_get(*m_index, last_page_no, RW_X_LATCH, false, &mtr); first_rec = page_rec_get_next( page_get_infimum_rec(last_block->page.frame)); ut_ad(page_rec_is_user_rec(first_rec)); /* Copy last page to root page. */ err = root_page_bulk.init(); if (err != DB_SUCCESS) { mtr.commit(); return(err); } root_page_bulk.copyIn(first_rec); root_page_bulk.finish(); /* Remove last page. */ btr_page_free(m_index, last_block, &mtr); mtr.commit(); err = pageCommit(&root_page_bulk, NULL, false); ut_ad(err == DB_SUCCESS); } ut_ad(err != DB_SUCCESS || btr_validate_index(m_index, NULL) == DB_SUCCESS); return(err); }
39,612
https://github.com/nickuraltsev/finity/blob/master/src/configuration/BaseConfigurator.js
Github Open Source
Open Source
MIT
2,018
finity
nickuraltsev
JavaScript
Code
80
233
import mapValues from '../utils/mapValues'; export default class BaseConfigurator { constructor(parent) { this.parent = parent; } getAncestor(type) { if (this.parent) { return this.parent instanceof type ? this.parent : this.parent.getAncestor(type); } return null; } buildConfig() { const mapper = value => { if (!value) { return value; } if (value instanceof BaseConfigurator) { return value.buildConfig(); } if (Array.isArray(value)) { return value.map(mapper); } if (value && typeof value === 'object') { return mapValues(value, mapper); } return value; }; return mapValues(this.config, mapper); } }
8,582
https://github.com/axxtros/webtemplate_1/blob/master/public_html/js/common.js
Github Open Source
Open Source
MIT
2,017
webtemplate_1
axxtros
JavaScript
Code
389
1,418
/* Created on : Sep 22, 2017, 09:43:05 AM Author : axtros Közös függvények, amelyek mindenféle eszközön használhatóak. */ var BROWSER_CHROME_NAME = 'Chrome'; var BROWSER_FIREFOX_NAME = 'Firefox'; var BROWSER_IE_NAME = 'Microsoft Internet Explorer'; var BROWSER_EDGE_NAME = 'Microsoft Edge'; var BROWSER_OPERA_NAME = 'Opera'; var BROWSER_SAFARI_NAME = 'Safari'; var nVer = navigator.appVersion; var nAgt = navigator.userAgent; var browserName = navigator.appName; //a felhasználó által használt böngésző neve var fullVersion = '' + parseFloat(navigator.appVersion); var majorVersion = parseInt(navigator.appVersion, 10); var nameOffset, verOffset, ix; function initClientMetadatas() { // In Opera 15+, the true version is after "OPR/" if ((verOffset=nAgt.indexOf("OPR/"))!=-1) { browserName = BROWSER_OPERA_NAME; fullVersion = nAgt.substring(verOffset+4); } // In older Opera, the true version is after "Opera" or after "Version" else if ((verOffset=nAgt.indexOf("Opera"))!=-1) { browserName = BROWSER_OPERA_NAME; fullVersion = nAgt.substring(verOffset+6); if ((verOffset=nAgt.indexOf("Version"))!=-1) fullVersion = nAgt.substring(verOffset+8); } // In MSIE, the true version is after "MSIE" in userAgent else if ((verOffset=nAgt.indexOf("MSIE"))!=-1) { browserName = BROWSER_IE_NAME; fullVersion = nAgt.substring(verOffset+5); } // In Chrome, the true version is after "Chrome" else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) { browserName = BROWSER_CHROME_NAME; fullVersion = nAgt.substring(verOffset+7); } // In Safari, the true version is after "Safari" or after "Version" else if ((verOffset=nAgt.indexOf("Safari"))!=-1) { browserName = BROWSER_SAFARI_NAME; fullVersion = nAgt.substring(verOffset+7); if ((verOffset=nAgt.indexOf("Version"))!=-1) fullVersion = nAgt.substring(verOffset+8); } // In Firefox, the true version is after "Firefox" else if ((verOffset=nAgt.indexOf("Firefox"))!=-1) { browserName = BROWSER_FIREFOX_NAME; fullVersion = nAgt.substring(verOffset+8); } // In most other browsers, "name/version" is at the end of userAgent else if ( (nameOffset=nAgt.lastIndexOf(' ')+1) < (verOffset=nAgt.lastIndexOf('/')) ) { browserName = nAgt.substring(nameOffset,verOffset); fullVersion = nAgt.substring(verOffset+1); if (browserName.toLowerCase()==browserName.toUpperCase()) { browserName = navigator.appName; } } // trim the fullVersion string at semicolon/space if present if ((ix=fullVersion.indexOf(";"))!=-1) fullVersion=fullVersion.substring(0,ix); if ((ix=fullVersion.indexOf(" "))!=-1) fullVersion=fullVersion.substring(0,ix); majorVersion = parseInt(''+fullVersion,10); if (isNaN(majorVersion)) { fullVersion = ''+parseFloat(navigator.appVersion); majorVersion = parseInt(navigator.appVersion,10); } } /** * Nincs használva. (Ne töröld ki, lehet, hogy később kelleni fog!) * @returns {String} */ function browserDetect() { //https://stackoverflow.com/questions/38373340/how-to-get-browser-name-using-jquery-or-javascript var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0; var isFirefox = typeof InstallTrigger !== 'undefined'; var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0; var isIE = /*@cc_on!@*/false || !!document.documentMode; var isEdge = !isIE && !!window.StyleMedia; var isChrome = !!window.chrome && !!window.chrome.webstore; if(isChrome) { return BROWSER_CHROME_NAME; } else if(isIE) { return BROWSER_IE_NAME; } else if(isFirefox) { return BROWSER_FIREFOX_NAME; } else if(isEdge) { return BROWSER_EDGE_NAME; } else if(isSafari) { return BROWSER_SAFARI_NAME; } else if(isOpera) { return BROWSER_OPERA_NAME; } else return 'na'; }
47,104
https://github.com/cragkhit/elasticsearch/blob/master/references/bcb_chosen_clones/default#82598#71#84.java
Github Open Source
Open Source
Apache-2.0
2,021
elasticsearch
cragkhit
Java
Code
39
124
File createJar(File jar, String... entries) throws IOException { OutputStream out = new FileOutputStream(jar); try { JarOutputStream jos = new JarOutputStream(out); for (String e : entries) { jos.putNextEntry(new JarEntry(getPathForZipEntry(e))); jos.write(getBodyForEntry(e).getBytes()); } jos.close(); } finally { out.close(); } return jar; }
44,099
https://github.com/usernameHed/Philae-Lander/blob/master/Assets/Plugins/Unity Essentials - Attractor/Scripts/ExtGravitonCalculation.cs
Github Open Source
Open Source
MIT
null
Philae-Lander
usernameHed
C#
Code
504
1,941
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEssentials.ActionTrigger.entity; using UnityEssentials.ActionTrigger.Trigger; using UnityEssentials.Extensions; using UnityEssentials.PropertyAttribute.noNull; using UnityEssentials.PropertyAttribute.readOnly; using UnityEssentials.time; using static UnityEssentials.Attractor.Attractor; namespace UnityEssentials.Attractor { [Serializable]//to Remove public class ExtGravitonCalculation { [SerializeField]//to Remove ? private List<AttractorInfo> _attractorInfo = new List<AttractorInfo>(Attractor.DEFAULT_MAX_ATTRACTOR); public AttractorInfo AttractorIndex(int index) { return (_attractorInfo[index]); } public int AttractorCounts { get { return (_attractorInfo.Count); } } [SerializeField]//to Remove ? private List<float> _forceAmount = new List<float>(Attractor.DEFAULT_MAX_ATTRACTOR); public float ForceAmountIndex(int index) { return (_forceAmount[index]); } private AttractorInfo _closestAttractor = default; public AttractorInfo ClosestAttractor { get { return (_closestAttractor); } } private AttractorInfo _tmpAttractorInfo = new AttractorInfo(); private int _closestIndex; public void OverrideContactPointOfClosestAttractor(Vector3 newContactPoint) { _closestAttractor.ContactPoint = newContactPoint; } public void SetupGravityFields(List<Attractor> attractorApplyingForce, Vector3 position) { //calculate all force from all shape (even the ones in the same groups) _attractorInfo.Clear(); _forceAmount.Clear(); for (int i = 0; i < attractorApplyingForce.Count; i++) { Vector3 closestPoint = Vector3.zero; _tmpAttractorInfo = attractorApplyingForce[i].GetGravityDirectionFromPointInSpace(position, ref closestPoint); if (_tmpAttractorInfo.AttractorRef.CurrentGroup != null) { _tmpAttractorInfo.AttractorRef.CurrentGroup.ResetGroup(); } _attractorInfo.Add(_tmpAttractorInfo); _forceAmount.Add(0); } } public void RemoveAttractorFromOneDirection(Vector3 directionToIgnore, float dotMargin) { //settup closest valid attractor element on each group for (int i = _attractorInfo.Count - 1; i >= 0; i--) { if (_attractorInfo[i].CanApplyGravity && i != _closestIndex) { float dotGravity = Vector3.Dot(_attractorInfo[i].NormalizedDirection, directionToIgnore); //Debug.Log("dot: " + dotGravity); if (dotGravity > dotMargin) { //Debug.Log("remove " + _attractorInfo[i].AttractorRef, _attractorInfo[i].AttractorRef.gameObject); //_attractorInfo.RemoveAt(i); _tmpAttractorInfo = _attractorInfo[i]; _tmpAttractorInfo.CanApplyGravity = false; _attractorInfo[i] = _tmpAttractorInfo; //_forceAmount.RemoveAt(i); } } } } public void CalculateGravityFields() { if (_attractorInfo.Count == 0) { return; } //settup closest valid attractor element on each group for (int i = 0; i < _attractorInfo.Count; i++) { if (_attractorInfo[i].CanApplyGravity && _attractorInfo[i].AttractorRef.CurrentGroup != null) { _attractorInfo[i].AttractorRef.CurrentGroup.AttemptToSetNewClosestGravityField(_attractorInfo[i].AttractorRef, _attractorInfo[i].SqrDistance); } } //invalidate all attractor that are not the closest in each group for (int i = 0; i < _attractorInfo.Count; i++) { if (_attractorInfo[i].CanApplyGravity && _attractorInfo[i].AttractorRef.CurrentGroup != null) { bool canReallyApplyGravity = _attractorInfo[i].AttractorRef.CurrentGroup.IsTheValidOneInTheGroup(_attractorInfo[i].AttractorRef); if (_attractorInfo[i].CanApplyGravity != canReallyApplyGravity) { _tmpAttractorInfo = _attractorInfo[i]; _tmpAttractorInfo.CanApplyGravity = canReallyApplyGravity; _attractorInfo[i] = _tmpAttractorInfo; } } } //find closest index _closestIndex = -1; float shortestDistance = 9999999; for (int i = 0; i < _attractorInfo.Count; i++) { if (!_attractorInfo[i].CanApplyGravity) { continue; } if (_closestIndex == -1 || _attractorInfo[i].SqrDistance < shortestDistance) { _closestIndex = i; shortestDistance = _attractorInfo[i].SqrDistance; } } if (_closestIndex == -1) { return; } _closestAttractor = _attractorInfo[_closestIndex]; } public Vector3 CalculateForces(float mass) { if (_closestIndex == -1 || _attractorInfo.Count == 0) { Debug.Log("No Force :)"); return (Vector3.zero); } //apply default force setting for the closest gravityFields float referenceSqrDistance = _attractorInfo[_closestIndex].SqrDistance; float force = mass * _attractorInfo[_closestIndex].Gravity * AttractorSettings.Instance.Gravity; Vector3 sumForce = _attractorInfo[_closestIndex].NormalizedDirection * force; _forceAmount[_closestIndex] = force; //finally, loop though all valid forces, and apply them for (int i = 0; i < _attractorInfo.Count; i++) { if (i == _closestIndex || !_attractorInfo[i].CanApplyGravity) { continue; } float gravityOfGravityField = _attractorInfo[i].Gravity * AttractorSettings.Instance.Gravity; float sqrDistanceGravitonToGravityField = _attractorInfo[i].SqrDistance; float K = AttractorSettings.Instance.RatioEaseOutAttractors; // F = (mass_GRAVITON * gravity_ATTRACTOR) / ((distance_GRAVITON_ATTRACTOR / distance_reference) * K) float forceMagnitude = (mass * gravityOfGravityField) / ((sqrDistanceGravitonToGravityField / (referenceSqrDistance - K))); _forceAmount[i] = forceMagnitude; Vector3 forceAttraction = _attractorInfo[i].NormalizedDirection * _forceAmount[i]; sumForce += forceAttraction; } return sumForce; } } }
39,951
https://github.com/oradrs/tpt-oracle/blob/master/ti.sql
Github Open Source
Open Source
Apache-2.0
2,023
tpt-oracle
oradrs
SQL
Code
155
353
-- Copyright 2018 Tanel Poder. All rights reserved. More info at http://tanelpoder.com -- Licensed under the Apache License, Version 2.0. See LICENSE.txt for terms & conditions. @@saveset column _ti_sequence noprint new_value _ti_sequence set feedback off heading off select trim(to_char( &_ti_sequence + 1 , '0999' )) "_ti_sequence" from dual; alter session set tracefile_identifier="&_ti_sequence"; set feedback on heading on set termout off column tracefile noprint new_value trc SELECT value tracefile FROM v$diag_info WHERE name = 'Default Trace File'; -- this is from from old 9i/10g days... -- -- select value ||'/'||(select instance_name from v$instance) ||'_ora_'|| -- (select spid||case when traceid is not null then '_'||traceid else null end -- from v$process where addr = (select paddr from v$session -- where sid = (select sid from v$mystat -- where rownum = 1 -- ) -- ) -- ) || '.trc' tracefile -- from v$parameter where name = 'user_dump_dest'; set termout on @@loadset prompt New tracefile_identifier=&trc col tracefile print
46,578
https://github.com/overfy/Satpam-Discord/blob/master/Commands/PurgeCommand.js
Github Open Source
Open Source
MIT
null
Satpam-Discord
overfy
JavaScript
Code
140
374
const Discord = require('discord.js'); module.exports = { name: 'Purge', description: 'Clearing message on channel', aliases: ['purge','prune'], usage: `Purge <num>`, cooldown: 5, async execute(client, message, args) { if (!message.member.hasPermission("MANAGE_MESSAGES") || !message.member.hasPermission("ADMINISTRATOR")) return message.channel.send("You don't have the necessary authority").then(d => d.delete({timeout: 5000})) if (isNaN(args[0])) return message.channel.send("Please input a valid number.") // isNaN = is Not a Number. (case sensitive, write it right) if (args[1] > 100) return message.channel.send("Insert the number less than 100.") // Discord limited purge number into 100. if (args[0] < 2) return message.channel.send("Insert the number more than 1.") await message.delete() await message.channel.bulkDelete(args[0]) .then(messages => message.channel.send(`Deleting ${messages.size}/${args[0]} messages on this channel`)).then(d => d.delete({timeout: 5000})) // How long this message will be deleted (in ms) .catch(() => message.channel.send("Something went wrong, while deleting messages.")) // This error will be displayed when the bot doesn't have an access to do it. } };
49,125
https://github.com/jczaplew/DefinitelyTyped/blob/master/types/graphql-date/index.d.ts
Github Open Source
Open Source
MIT
2,016
DefinitelyTyped
jczaplew
TypeScript
Code
29
105
// Type definitions for graphql-date 1.0 // Project: https://github.com/tjmehta/graphql-date // Definitions by: Eric Naeseth <https://github.com/enaeseth> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import {GraphQLScalarType} from 'graphql'; declare const date: GraphQLScalarType; export = date;
125
https://github.com/bhokumar/reactive-programming/blob/master/src/main/java/com/smarttech/reactive/programming/problemsolving/sudoku/SudokuConstants.java
Github Open Source
Open Source
Apache-2.0
null
reactive-programming
bhokumar
Java
Code
38
89
package com.smarttech.reactive.programming.problemsolving.sudoku; public class SudokuConstants { public static final int BOARD_SIZE = 9; public static final int BOX_SIZE = 3; public static final int MIN_NUMBER = 1; public static final int MAX_NUMBER = 9; private SudokuConstants() {} }
48,868
https://github.com/4strid/nekodb/blob/master/test/config.js
Github Open Source
Open Source
MIT
2,021
nekodb
4strid
JavaScript
Code
16
57
module.exports = { testMongo: false, client: 'mongodb', username: '', password: '', address: 'localhost:27017', database: 'ko_db_test', }
29,984
https://github.com/imatiach-msft/fairlearn/blob/master/visualization/FairnessDashboard/src/Controls/ModelComparisonChart.tsx
Github Open Source
Open Source
MIT
null
fairlearn
imatiach-msft
TypeScript
Code
856
3,443
import _ from "lodash"; import { AccessibleChart, ChartBuilder, IPlotlyProperty, PlotlyMode, SelectionContext } from "mlchartlib"; import { getTheme, Text } from "office-ui-fabric-react"; import { ActionButton } from "office-ui-fabric-react/lib/Button"; import { ChoiceGroup, IChoiceGroupOption } from 'office-ui-fabric-react/lib/ChoiceGroup'; import { Spinner, SpinnerSize } from "office-ui-fabric-react/lib/Spinner"; import { Stack } from "office-ui-fabric-react/lib/Stack"; import React from "react"; import { AccuracyOptions } from "../AccuracyMetrics"; import { IAccuracyPickerProps, IFeatureBinPickerProps, IParityPickerProps } from "../FairnessWizard"; import { FormatMetrics } from "../FormatMetrics"; import { IFairnessContext } from "../IFairnessContext"; import { PredictionTypes } from "../IFairnessProps"; import { localization } from "../Localization/localization"; import { MetricsCache } from "../MetricsCache"; import { ParityModes } from "../ParityMetrics"; import { ModelComparisionChartStyles } from "./ModelComparisionChart.styles"; const theme = getTheme(); export interface IModelComparisonProps { dashboardContext: IFairnessContext; selections: SelectionContext; metricsCache: MetricsCache; modelCount: number; accuracyPickerProps: IAccuracyPickerProps; parityPickerProps: IParityPickerProps; featureBinPickerProps: IFeatureBinPickerProps; onEditConfigs: () => void; } export interface IState { accuracyArray?: number[]; disparityArray?: number[]; disparityInOutcomes: boolean; } export class ModelComparisonChart extends React.PureComponent<IModelComparisonProps, IState> { private readonly plotlyProps: IPlotlyProperty = { config: { displaylogo: false, responsive: true, modeBarButtonsToRemove: ['toggleSpikelines', 'hoverClosestCartesian', 'hoverCompareCartesian', 'zoom2d', 'pan2d', 'select2d', 'lasso2d', 'zoomIn2d', 'zoomOut2d', 'autoScale2d', 'resetScale2d'] }, data: [ { datapointLevelAccessors: { customdata: { path: ['index'], plotlyPath: 'customdata' } }, mode: PlotlyMode.markers, marker: { size: 14 }, type: 'scatter', xAccessor: 'Accuracy', yAccessor: 'Parity', hoverinfo: 'text' } ], layout: { autosize: true, font: { size: 10 }, margin: { t: 4, r:0 }, hovermode: 'closest', xaxis: { automargin: true, fixedrange: true, mirror: true, linecolor: theme.semanticColors.disabledBorder, linewidth: 1, title:{ text: 'Error' } }, yaxis: { automargin: true, fixedrange: true, title:{ text: 'Disparity' } }, } as any }; constructor(props: IModelComparisonProps) { super(props); this.state = { disparityInOutcomes: true }; } public render(): React.ReactNode { const styles = ModelComparisionChartStyles(); if (!this.state || this.state.accuracyArray === undefined || this.state.disparityArray === undefined) { this.loadData(); return ( <Spinner className={styles.spinner} size={SpinnerSize.large} label={localization.calculating}/> ); } const data = this.state.accuracyArray.map((accuracy, index) => { return { Parity: this.state.disparityArray[index], Accuracy: accuracy, index: index }; }); let minAccuracy: number = Number.MAX_SAFE_INTEGER; let maxAccuracy: number = Number.MIN_SAFE_INTEGER; let maxDisparity: number = Number.MIN_SAFE_INTEGER; let minDisparity: number = Number.MAX_SAFE_INTEGER; let minAccuracyIndex: number; let maxAccuracyIndex: number; let minDisparityIndex: number; let maxDisparityIndex: number; this.state.accuracyArray.forEach((value, index) => { if (value >= maxAccuracy) { maxAccuracyIndex = index; maxAccuracy = value; } if (value <= minAccuracy) { minAccuracyIndex = index; minAccuracy = value; } }); this.state.disparityArray.forEach((value, index) => { if (value >= maxDisparity) { maxDisparityIndex = index; maxDisparity = value; } if (value <= minDisparity) { minDisparityIndex = index; minDisparity = value; } }); const formattedMinAccuracy = FormatMetrics.formatNumbers(minAccuracy, this.props.accuracyPickerProps.selectedAccuracyKey); const formattedMaxAccuracy = FormatMetrics.formatNumbers(maxAccuracy, this.props.accuracyPickerProps.selectedAccuracyKey); const formattedMinDisparity = FormatMetrics.formatNumbers(minDisparity, this.props.accuracyPickerProps.selectedAccuracyKey); const formattedMaxDisparity = FormatMetrics.formatNumbers(maxDisparity, this.props.accuracyPickerProps.selectedAccuracyKey); let selectedMetric = AccuracyOptions[this.props.accuracyPickerProps.selectedAccuracyKey]; // handle custom metric case if (selectedMetric === undefined) { selectedMetric = this.props.accuracyPickerProps.accuracyOptions.find(metric => metric.key === this.props.accuracyPickerProps.selectedAccuracyKey) } const insights2 = localization.formatString( localization.ModelComparison.insightsText2, selectedMetric.title, formattedMinAccuracy, formattedMaxAccuracy, formattedMinDisparity, formattedMaxDisparity ); const metricTitleAppropriateCase = selectedMetric.alwaysUpperCase ? selectedMetric.title : selectedMetric.title.toLowerCase(); const insights3 = localization.formatString( localization.ModelComparison.insightsText3, metricTitleAppropriateCase, selectedMetric.isMinimization ? formattedMinAccuracy : formattedMaxAccuracy, FormatMetrics.formatNumbers(this.state.disparityArray[selectedMetric.isMinimization ? minAccuracyIndex : maxAccuracyIndex], this.props.accuracyPickerProps.selectedAccuracyKey) ); const insights4 = localization.formatString( localization.ModelComparison.insightsText4, metricTitleAppropriateCase, FormatMetrics.formatNumbers(this.state.accuracyArray[minDisparityIndex], this.props.accuracyPickerProps.selectedAccuracyKey), formattedMinDisparity ); const howToReadText = localization.formatString( localization.ModelComparison.howToReadText, this.props.modelCount.toString(), metricTitleAppropriateCase, selectedMetric.isMinimization ? localization.ModelComparison.lower : localization.ModelComparison.higher ); const props = _.cloneDeep(this.plotlyProps); props.data = ChartBuilder.buildPlotlySeries(props.data[0], data).map(series => { series.name = this.props.dashboardContext.modelNames[series.name]; series.text = this.props.dashboardContext.modelNames; return series; }); const accuracyMetricTitle = selectedMetric.title; props.layout.xaxis.title = accuracyMetricTitle; props.layout.yaxis.title = this.state.disparityInOutcomes ? localization.ModelComparison.disparityInOutcomes : localization.formatString(localization.ModelComparison.disparityInAccuracy, metricTitleAppropriateCase) as string return ( <Stack className={styles.frame}> <div className={styles.header}> <Text variant={"large"} className={styles.headerTitle} block>{localization.ModelComparison.title}</Text> <ActionButton iconProps={{iconName: "Edit"}} onClick={this.props.onEditConfigs} className={styles.editButton}>{localization.Report.editConfiguration}</ActionButton> </div> <div className={styles.main}> <div className={styles.chart}> <AccessibleChart plotlyProps={props} sharedSelectionContext={this.props.selections} theme={undefined} /> </div> <div className={styles.mainRight}> <Text className={styles.rightTitle} block>{localization.ModelComparison.howToRead}</Text> <Text className={styles.rightText} block>{howToReadText}</Text> <Text className={styles.insights} block>{localization.ModelComparison.insights}</Text> <div className={styles.insightsText}> <Text className={styles.textSection} block>{insights2}</Text> <Text className={styles.textSection} block>{insights3}</Text> <Text className={styles.textSection} block>{insights4}</Text> </div> </div> </div> <div> <ChoiceGroup className={styles.radio} selectedKey={this.state.disparityInOutcomes ? "outcomes" : "accuracy"} options={[ { key: 'accuracy', text: localization.formatString(localization.ModelComparison.disparityInAccuracy, metricTitleAppropriateCase) as string, styles: { choiceFieldWrapper: styles.radioOptions} }, { key: 'outcomes', text: localization.ModelComparison.disparityInOutcomes, styles: { choiceFieldWrapper: styles.radioOptions} } ]} onChange={this.disparityChanged} label={localization.ModelComparison.howToMeasureDisparity} required={false} ></ChoiceGroup> </div> </Stack>); } private async loadData(): Promise<void> { try { const accuracyPromises = new Array(this.props.modelCount).fill(0).map((unused, modelIndex) => { return this.props.metricsCache.getMetric( this.props.dashboardContext.binVector, this.props.featureBinPickerProps.selectedBinIndex, modelIndex, this.props.accuracyPickerProps.selectedAccuracyKey); }); const disparityMetric = this.state.disparityInOutcomes ? (this.props.dashboardContext.modelMetadata.predictionType === PredictionTypes.binaryClassification ? "selection_rate" : "average") : this.props.accuracyPickerProps.selectedAccuracyKey; const disparityPromises = new Array(this.props.modelCount).fill(0).map((unused, modelIndex) => { return this.props.metricsCache.getDisparityMetric( this.props.dashboardContext.binVector, this.props.featureBinPickerProps.selectedBinIndex, modelIndex, disparityMetric, ParityModes.difference); }); const accuracyArray = (await Promise.all(accuracyPromises)).map(metric => metric.global); const disparityArray = await Promise.all(disparityPromises); this.setState({accuracyArray, disparityArray}); } catch { // todo; } } private readonly disparityChanged = (ev: React.FormEvent<HTMLInputElement>, option: IChoiceGroupOption): void => { const disparityInOutcomes = option.key !== "accuracy"; if (this.state.disparityInOutcomes !== disparityInOutcomes) { this.setState({disparityInOutcomes, disparityArray: undefined}); } } // TODO: Reuse if multiselect re-enters design // private readonly applySelections = (chartId: string, selectionIds: string[], plotlyProps: IPlotlyProperty) => { // if (!plotlyProps.data || plotlyProps.data.length === 0) { // return; // } // const customData: string[] = (plotlyProps.data[0] as any).customdata; // if (!customData) { // return; // } // const colors = customData.map(modelIndex => { // const selectedIndex = this.props.selections.selectedIds.indexOf(modelIndex); // if (selectedIndex !== -1) { // return FabricStyles.plotlyColorPalette[selectedIndex % FabricStyles.plotlyColorPalette.length]; // } // return "#111111"; // }); // const shapes = customData.map(modelIndex => { // const selectedIndex = this.props.selections.selectedIds.indexOf(modelIndex); // if (selectedIndex !== -1) { // return 1 // } // return 0; // }); // Plotly.restyle(chartId, 'marker.color' as any, [colors] as any); // Plotly.restyle(chartId, 'marker.symbol' as any, [shapes] as any); // } }
22,353
https://github.com/conchyliculture/beerlog/blob/master/beerlog/events.py
Github Open Source
Open Source
MIT
2,019
beerlog
conchyliculture
Python
Code
99
329
"""Module for beerlog events""" from datetime import datetime from beerlog import constants class BaseEvent(): """Base Event type for the main process Loop. Attributes: timestamp(datetime.datetime): the time when the event was generated. type(str): a type for this event. """ def __init__(self, event_type): self.timestamp = datetime.now() self.type = event_type def __str__(self): return self.type class ErrorEvent(BaseEvent): """Event to carry error messages.""" def __init__(self, message): super().__init__(constants.EVENTTYPES.ERROR) self.message = message def __str__(self): return '{0:s}'.format(self.message) class NopEvent(BaseEvent): """An Event that does nothing.""" def __init__(self): super().__init__(constants.EVENTTYPES.NOEVENT) class UIEvent(BaseEvent): """Class for UI related events.""" def __str__(self): return 'UIEvent type:{0:s} [{1!s}]'.format( constants.EVENTTYPES[self.type], self.timestamp) # vim: tabstop=2 shiftwidth=2 expandtab
17,819
https://github.com/roryprimrose/Headless/blob/master/Headless/HtmlList.cs
Github Open Source
Open Source
MIT
2,021
Headless
roryprimrose
C#
Code
857
2,435
namespace Headless { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using System.Xml.XPath; using Headless.Activation; using Headless.Properties; /// <summary> /// The <see cref="HtmlList" /> /// class is used to represent a HTML list. /// </summary> [SupportedTag("select")] public class HtmlList : HtmlFormElement { /// <summary> /// Initializes a new instance of the <see cref="HtmlList"/> class. /// </summary> /// <param name="page"> /// The owning page. /// </param> /// <param name="node"> /// The node. /// </param> /// <exception cref="System.ArgumentNullException"> /// The <paramref name="page"/> parameter is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentNullException"> /// The <paramref name="node"/> parameter is <c>null</c>. /// </exception> public HtmlList(IHtmlPage page, IXPathNavigable node) : base(page, node) { } /// <summary> /// Deselects the specified value. /// </summary> /// <param name="value"> /// The value. /// </param> /// <exception cref="HtmlElementNotFoundException"> /// No option element found for the specified value. /// </exception> public void Deselect(string value) { var item = this[value]; if (item == null) { throw BuildItemNotFoundException(value); } item.Selected = false; } /// <summary> /// Selects the specified value. /// </summary> /// <param name="value"> /// The value. /// </param> /// <exception cref="HtmlElementNotFoundException"> /// No option element found for the specified value. /// </exception> public void Select(string value) { var item = this[value]; if (item == null) { throw BuildItemNotFoundException(value); } item.Selected = true; } /// <inheritdoc /> protected internal override IEnumerable<PostEntry> BuildPostData() { var selectedItems = SelectedItems; if (selectedItems.Count == 0) { yield break; } if (IsDropDown) { // Return only the last item var lastEntry = selectedItems.Last(); var postEntry = new PostEntry(Name, lastEntry.PostValue); yield return postEntry; } else { foreach (var selectedItem in selectedItems) { var postEntry = new PostEntry(Name, selectedItem.PostValue); yield return postEntry; } } } /// <summary> /// Determines whether the item matches the specified value. /// </summary> /// <param name="item"> /// The item. /// </param> /// <param name="value"> /// The value. /// </param> /// <returns> /// <c>true</c> if the item matches the value; otherwise <c>false</c>. /// </returns> private static bool MatchesItem(HtmlFormElement item, string value) { if (item == null) { return false; } if (item.Value == null) { if (string.IsNullOrEmpty(value)) { return true; } } else if (item.Value.Equals(value, StringComparison.Ordinal)) { return true; } if (item.Text == null) { if (string.IsNullOrEmpty(value)) { return true; } } else if (item.Text.Equals(value, StringComparison.Ordinal)) { return true; } return false; } /// <summary> /// Throws the item not found. /// </summary> /// <param name="value"> /// The value. /// </param> /// <returns> /// A <see cref="HtmlElementNotFoundException"/> value. /// </returns> private HtmlElementNotFoundException BuildItemNotFoundException(string value) { var message = string.Format(CultureInfo.CurrentCulture, Resources.HtmlList_NoOptionFoundForValue, value); return new HtmlElementNotFoundException(message, Node); } /// <summary> /// Gets a value indicating whether this instance is a drop down list. /// </summary> /// <value> /// <c>true</c> if this instance is a drop down list; otherwise, <c>false</c>. /// </value> public bool IsDropDown { get { var navigator = Node.GetNavigator(); var allowsMuliple = navigator.MoveToAttribute("multiple", string.Empty); if (allowsMuliple) { return false; } return true; } } /// <summary> /// Gets the items. /// </summary> /// <value> /// The items. /// </value> public ReadOnlyCollection<HtmlListItem> Items { get { var items = Find<HtmlListItem>().All(); return new ReadOnlyCollection<HtmlListItem>(items.ToList()); } } /// <summary> /// Gets the selected items. /// </summary> /// <value> /// The selected items. /// </value> public ReadOnlyCollection<HtmlListItem> SelectedItems { get { var items = Find<HtmlListItem>().AllByPredicate(x => x.Selected).ToList(); if (items.Count > 0) { return new ReadOnlyCollection<HtmlListItem>(items); } if (IsDropDown == false) { return new ReadOnlyCollection<HtmlListItem>(items); } // This is a drop down but nothing is explicltly selected // We will take the first available item var implicitItems = new List<HtmlListItem>(); var firstItem = Items.FirstOrDefault(); if (firstItem != null) { implicitItems.Add(firstItem); } return new ReadOnlyCollection<HtmlListItem>(implicitItems); } } /// <summary> /// Gets the selected values in the list. /// </summary> /// <value> /// The selected values in the list. /// </value> /// <exception cref="HtmlElementNotFoundException">No option element found for the specified value.</exception> public IEnumerable<string> SelectedValues { get { return SelectedItems.Select(x => x.PostValue); } set { var items = Items.ToList(); items.ForEach(x => x.Selected = false); if (value == null) { return; } foreach (var item in value) { if (string.IsNullOrEmpty(item)) { continue; } var itemValue = item; var matchingItems = items.Where(x => MatchesItem(x, itemValue)).ToList(); if (matchingItems.Count == 0) { throw BuildItemNotFoundException(item); } matchingItems.ForEach(x => x.Selected = true); } } } /// <inheritdoc /> /// <exception cref="HtmlElementNotFoundException">No option element found for the specified value.</exception> public override string Value { get { var values = SelectedValues.ToList(); if (values.Count == 0) { return string.Empty; } return values.Aggregate((current, next) => current + Environment.NewLine + next); } set { List<string> values = null; if (value != null) { values = value.Split( new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).ToList(); } SelectedValues = values; } } /// <summary> /// Gets the values available in the list. /// </summary> /// <value> /// The values available in the list. /// </value> public IEnumerable<string> Values { get { return Items.Select(x => x.PostValue); } } /// <summary> /// Gets the <see cref="HtmlListItem"/> with the specified value. /// </summary> /// <value> /// The <see cref="HtmlListItem"/>. /// </value> /// <param name="value"> /// The value. /// </param> /// <returns> /// A <see cref="HtmlListItem"/> value. /// </returns> public HtmlListItem this[string value] { get { var matchingItems = Find<HtmlListItem>().AllByPredicate(x => MatchesItem(x, value)); return matchingItems.FirstOrDefault(); } } } }
50,757
https://github.com/barryajones/troup-client/blob/master/components/Dashboard/index.tsx
Github Open Source
Open Source
Apache-2.0
2,020
troup-client
barryajones
TSX
Code
66
154
import React from 'react'; import { useRouter } from 'next/router'; import { withRedirectUser } from '@with/redirectUser'; import { withApollo } from '@with/apollo'; import { DashboardUser } from './DashboardUser'; import { DashboardTeam } from './DashboardTeam'; export const Dashboard: React.FC<{}> = () => { const { query: { team }, } = useRouter(); return <>{team ? <DashboardTeam /> : <DashboardUser />}</>; }; export default withRedirectUser(withApollo({ ssr: false })(Dashboard));
27,215
https://github.com/Energinet-DataHub/po-auth/blob/master/src/migrations/versions/7c454b8ab0d9_.py
Github Open Source
Open Source
Apache-2.0
2,022
po-auth
Energinet-DataHub
Python
Code
139
654
"""empty message Revision ID: 7c454b8ab0d9 Revises: 9720f2c9aba2 Create Date: 2022-05-19 12:03:44.487536 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '7c454b8ab0d9' down_revision = '9720f2c9aba2' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('company', sa.Column('id', sa.String(), nullable=False), sa.Column('created', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False), sa.Column('tin', sa.String(), nullable=False), sa.CheckConstraint('tin != null'), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('id'), sa.UniqueConstraint('tin') ) op.create_index(op.f('ix_company_id'), 'company', ['id'], unique=False) op.create_index(op.f('ix_company_tin'), 'company', ['tin'], unique=False) op.create_table('user_company', sa.Column('company_id', sa.String(), nullable=False), sa.Column('user_id', sa.String(), nullable=False), sa.ForeignKeyConstraint(['company_id'], ['company.id'], ), sa.ForeignKeyConstraint(['user_id'], ['user.subject'], ), sa.PrimaryKeyConstraint('company_id', 'user_id'), sa.UniqueConstraint('company_id', 'user_id') ) op.drop_index('ix_user_tin', table_name='user') op.drop_column('user', 'tin') # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('user', sa.Column('tin', sa.VARCHAR(), autoincrement=False, nullable=True)) op.create_index('ix_user_tin', 'user', ['tin'], unique=False) op.drop_table('user_company') op.drop_index(op.f('ix_company_tin'), table_name='company') op.drop_index(op.f('ix_company_id'), table_name='company') op.drop_table('company') # ### end Alembic commands ###
11,888
https://github.com/VHAINNOVATIONS/PerceptiveReach/blob/master/CI_CD/PerceptiveReachTestCases/features/PR-2084.feature
Github Open Source
Open Source
Apache-2.0
2,017
PerceptiveReach
VHAINNOVATIONS
Gherkin
Code
105
180
Feature: As any IRDS user, I want to be automatically logged out of the application after 15 minutes of inactivity PR-2084 1.1.72 Scenario: I open a web browser and navigate to http://localhost:7003/ to see the inactivity logout Given I navigate to the http://localhost:7003/ Then I should see "Perceptive Reach" When I put in "email" field as "vaphsfequia" And I put in "password" field as "FeAn#011819" And I click on check box "checky" And I click on "Login" button And I should see "Individual View" When I leave the page inactive for 900 seconds Then I should see "You're Idle. Do Something! You'll be logged out"
34,782
https://github.com/tbfajri/restful-api/blob/master/application/controllers/Kontak.php
Github Open Source
Open Source
MIT
null
restful-api
tbfajri
PHP
Code
115
454
<?php defined('BASEPATH') OR exit ('No direct script access allowed'); require APPPATH . '/libraries/REST_Controller.php'; use Restserver\Libraries\REST_Controller; class Kontak extends REST_Controller { function __construct(){ parent::__construct(); $this->load->model('kontak_model'); } // menampilkan data function index_get(){ $id = $this->get('id'); if ($id == ''){ $response = $this->kontak_model->list(); $this->response($response); } else { $response = $this->kontak_model->detail($id); $this->response($response, 200); } } // menambahkan data function index_post(){ $data = [ 'nama' => $this->post('nama'), 'nomor' => $this->post('nomor') ]; $response = $this->kontak_model->insert($data); $this->response($response); } // update data function index_put(){ $id = $this->put('id'); $data = [ 'id' => $this->put('id'), 'nama' => $this->put('nama'), 'nomor' => $this->put('nomor') ]; $response = $this->kontak_model->update($id, $data); $this->response($response); } // delete data function index_delete() { $id = $this->delete('id'); $response = $this->kontak_model->delete($id, $data); $this->response($response); } } ?>
48,953
https://github.com/dripfeeder/haven-platform/blob/master/common/filestorage/src/main/java/com/codeabovelab/dm/fs/service/SimpleFileStorageBackend.java
Github Open Source
Open Source
Apache-2.0
2,016
haven-platform
dripfeeder
Java
Code
524
1,582
/* * Copyright 2016 Code Above Lab LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or 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.codeabovelab.dm.fs.service; import com.codeabovelab.dm.common.utils.AttributeSupport; import com.codeabovelab.dm.common.utils.Throwables; import com.codeabovelab.dm.fs.FileStorage; import com.codeabovelab.dm.fs.FileStorageAbsentException; import com.codeabovelab.dm.fs.dto.DeleteOptions; import com.codeabovelab.dm.fs.dto.FileHandle; import com.codeabovelab.dm.fs.dto.ReadOptions; import com.codeabovelab.dm.fs.dto.WriteOptions; import com.codeabovelab.dm.fs.entity.FileAttribute; import com.codeabovelab.dm.fs.repository.AttributesRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import java.io.IOException; import java.io.InputStream; import java.util.*; /** * Simple backend for storing files in directory. */ @Component @Transactional public class SimpleFileStorageBackend implements FileStorage { @Autowired private BlobStorage blobStorage; @Autowired private AttributesRepository attributesRepository; @Override public String write(WriteOptions options) { FileHandle fileHandle = options.getFileHandle(); final String id = fileHandle.getId(); try(InputStream stream = fileHandle.getData()) { blobStorage.write(id, stream, options); } catch (IOException e) { throw Throwables.asRuntime(e); } /* if we update existing file and it has attributes, then we need to merge the attributes, but in future option which overwrites old attrs can be added */ AdapterImpl adapter = new AdapterImpl(UUID.fromString(id)); AttributeSupport.merge(adapter, adapter, fileHandle.getAttributes()); return id; } @Override public FileHandle read(final ReadOptions options) { final String id = options.getId(); final Map<String, String> map = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); List<FileAttribute> list = attributesRepository.findByFileId(UUID.fromString(id)); for(FileAttribute attribute: list) { map.put(attribute.getName(), attribute.getData()); } return new LazyFileHandle(map, options); } @Override public void delete(DeleteOptions options) { String id = options.getId(); try { boolean wasExists = blobStorage.delete(id); if(!wasExists && options.isFailIfAbsent()) { throw createNotExists(id); } } catch (IOException e) { throw Throwables.asRuntime(e); } List<FileAttribute> attrs = attributesRepository.findByFileId(UUID.fromString(id)); attributesRepository.delete(attrs); } private RuntimeException createNotExists(String id) { return new FileStorageAbsentException(id + " does not exists"); } private class AdapterImpl implements AttributeSupport.Adapter<FileAttribute>, AttributeSupport.Repository<FileAttribute> { private final UUID fileId; public AdapterImpl(UUID fileId) { this.fileId = fileId; } @Override public FileAttribute create() { FileAttribute attribute = new FileAttribute(); attribute.setFileId(fileId); return attribute; } @Override public void setKey(FileAttribute attr, String key) { attr.setName(key); } @Override public String getKey(FileAttribute attr) { return attr.getName(); } @Override public void setValue(FileAttribute attr, String value) { attr.setData(value); } @Override public String getValue(FileAttribute attr) { return attr.getData(); } @Override public List<FileAttribute> getAttributes() { return attributesRepository.findByFileId(fileId); } @Override public <S extends FileAttribute> List<S> save(Iterable<S> entities) { return attributesRepository.save(entities); } @Override public void delete(Iterable<? extends FileAttribute> entities) { attributesRepository.delete(entities); } } private class LazyFileHandle implements FileHandle { private final Map<String, String> attrs; private final String id; private final ReadOptions options; LazyFileHandle(Map<String, String> map, ReadOptions options) { this.options = options; this.id = options.getId(); attrs = Collections.unmodifiableMap(map); } @Override public String getId() { return id; } @Override public InputStream getData() { try { InputStream read = blobStorage.read(id); if(read == null && options.isFailIfAbsent()) { throw createNotExists(id); } return read; } catch (IOException e) { throw Throwables.asRuntime(e); } } @Override public Map<String, String> getAttributes() { return attrs; } @Override public String toString() { return "LazyFileHandle{" + "id='" + id + '\'' + ", attrs=" + attrs + '}'; } } }
13,007
https://github.com/kleopatra999/aws-sdk-ruby-record/blob/master/spec/aws-record/record/attributes/map_marshaler_spec.rb
Github Open Source
Open Source
Apache-2.0
2,016
aws-sdk-ruby-record
kleopatra999
Ruby
Code
309
747
# Copyright 2015-2016 Amazon.com, Inc. or its affiliates. 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. A copy of the License is # located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file 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. require 'spec_helper' module Aws module Record module Attributes describe MapMarshaler do let(:mappable) do Class.new do def to_h { a: 1, b: "Two", c: 3.0 } end end end describe 'type casting' do it 'type casts nil as nil' do expect(MapMarshaler.type_cast(nil)).to eq(nil) end it 'type casts nil as an empty map with option' do expect( MapMarshaler.type_cast(nil, nil_as_empty_map: true) ).to eq({}) end it 'type casts an empty string as nil' do expect(MapMarshaler.type_cast('')).to eq(nil) end it 'type casts an empty string as an empty map with option' do expect( MapMarshaler.type_cast('', nil_as_empty_map: true) ).to eq({}) end it 'type casts Hashes as themselves' do input = { a: 1, b: "Two", c: 3.0 } expected = { a: 1, b: "Two", c: 3.0 } expect(MapMarshaler.type_cast(input)).to eq(expected) end it 'type casts classes which respond to :to_h as a Hash' do input = mappable.new expected = { a: 1, b: "Two", c: 3.0 } expect(MapMarshaler.type_cast(input)).to eq(expected) end it 'raises if it cannot type cast to a Hash' do expect { MapMarshaler.type_cast(5) }.to raise_error(ArgumentError) end end describe 'serialization' do it 'serializes a map as itself' do input = { a: 1, b: "Two", c: 3.0 } expected = { a: 1, b: "Two", c: 3.0 } expect(MapMarshaler.serialize(input)).to eq(expected) end it 'serializes nil as nil' do expect(MapMarshaler.serialize(nil)).to eq(nil) end end end end end end
37,245
https://github.com/benkyodesuyo/DevOpsSample/blob/master/DevOpsSample/Program.cs
Github Open Source
Open Source
MIT
null
DevOpsSample
benkyodesuyo
C#
Code
33
93
using System; namespace DevOpsSample { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); NewMethod(); } private static void NewMethod() { if (true) { var i = 10; } } } }
30,945
https://github.com/renoagilsaputra/kopi-shop/blob/master/application/views/admin/transaksi.php
Github Open Source
Open Source
MIT
2,020
kopi-shop
renoagilsaputra
PHP
Code
247
1,135
<h1 class="mt-4">Transaksi</h1> <?= $this->session->flashdata('message'); ?> <?php if(!empty($invoices)) : ?> <a href="" data-toggle="modal" data-target="#addModal" class="btn btn-dark mb-2"><i class="fa fa-print"></i></a> <?php endif; ?> <div class="table-responsive"> <table class="table table-hover"> <thead> <tr> <th scope="col">#</th> <th scope="col">ID Invoices</th> <th scope="col">Date</th> <th scope="col">Du Date</th> <th>Status</th> <th scope="col"><i class="fa fa-cogs"></i></th> </tr> </thead> <tbody> <?php $n = 1; foreach($invoices as $in) : ?> <tr> <td><?= $n++; ?></td> <td><?= $in['id']; ?></td> <td><?= $in['date']; ?></td> <td><?= $in['du_date']; ?></td> <td> <?php if($in['status'] == "paid") : ?> <small class="badge badge-success"> <?= $in['status']; ?> </small> <?php else : ?> <small class="badge badge-secondary"> <?= $in['status']; ?> </small> <?php endif; ?> </td> <td> <?php if($in['status'] == "paid") : ?> <a href="<?= base_url('admin/transaksi_del/').$in['id']; ?>" onclick="return confirm('Yakin?')" class="btn btn-danger"><i class="fa fa-trash"></i></a> <?php else : ?> <a href="<?= base_url('admin/paid/').$in['id']; ?>" onclick="return confirm('Yakin?')" class="btn btn-warning"><i class="fa fa-money"></i> Paid</a> <?php endif; ?> <a href="<?= base_url('admin/transaksi_detail/').$in['id'].'/'.$in['id_user']; ?>" class="btn btn-info"><i class="fa fa-search"></i></a> <a href="<?= base_url('admin/cetak_detail/').$in['id'].'/'.$in['id_user']; ?>" class="btn btn-dark"><i class="fa fa-print"></i></a> </td> </tr> <?php endforeach; ?> <?php if(empty($invoices)) : ?> <tr> <td colspan="6" align="center">Data tidak ditemukan</td> </tr> <?php endif; ?> </tbody> </table> <!-- Modal --> <div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Cetak</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <form action="<?= base_url('admin/cetak') ?>" method="post" enctype="multipart/form-data"> <div class="modal-body"> <select class="form-control mb-2" name="waktu"> <option value="">Pilih Waktu</option> <?php foreach($invoices as $iv) : ?> <option value="<?= $iv['date']; ?>"><?= $iv['date']; ?></option> <?php endforeach; ?> </select> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Keluar</button> <button type="submit" class="btn btn-success">Cetak</button> </div> </form> </div> </div> </div>
36,342
https://github.com/lahiiru/DeepLab-Training-Pipeline/blob/master/docker_run.sh
Github Open Source
Open Source
MIT
null
DeepLab-Training-Pipeline
lahiiru
Shell
Code
20
117
#!/usr/bin/env bash IMAGE_NAME=deeplab:v2.0 DATASET_LOC=/home/dulanj/Datasets/CIHP/instance-level_human_parsing/instance-level_human_parsing docker run --gpus "all" -it --rm -p 80:80 \ -v $DATASET_LOC:/home/dataset:ro \ -v $(pwd)/output:/home/output \ $IMAGE_NAME
28,739
https://github.com/mauri-opskins/eos/blob/master/libraries/chain/trace.cpp
Github Open Source
Open Source
MIT
2,021
eos
mauri-opskins
C++
Code
118
489
/** * @file * @copyright defined in eos/LICENSE */ #include <eosio/chain/trace.hpp> namespace eosio { namespace chain { action_trace::action_trace( const transaction_trace& trace, const action& act, account_name receiver, bool context_free, uint32_t action_ordinal, uint32_t creator_action_ordinal, uint32_t closest_unnotified_ancestor_action_ordinal ) :action_ordinal( action_ordinal ) ,creator_action_ordinal( creator_action_ordinal ) ,closest_unnotified_ancestor_action_ordinal( closest_unnotified_ancestor_action_ordinal ) ,receiver( receiver ) ,act( act ) ,context_free( context_free ) ,trx_id( trace.id ) ,block_num( trace.block_num ) ,block_time( trace.block_time ) ,producer_block_id( trace.producer_block_id ) {} action_trace::action_trace( const transaction_trace& trace, action&& act, account_name receiver, bool context_free, uint32_t action_ordinal, uint32_t creator_action_ordinal, uint32_t closest_unnotified_ancestor_action_ordinal ) :action_ordinal( action_ordinal ) ,creator_action_ordinal( creator_action_ordinal ) ,closest_unnotified_ancestor_action_ordinal( closest_unnotified_ancestor_action_ordinal ) ,receiver( receiver ) ,act( std::move(act) ) ,context_free( context_free ) ,trx_id( trace.id ) ,block_num( trace.block_num ) ,block_time( trace.block_time ) ,producer_block_id( trace.producer_block_id ) {} } } // eosio::chain
46,335
https://github.com/Stex/acts_as_data_table/blob/master/generators/acts_as_data_table/templates/assets/js/acts_as_data_table.js
Github Open Source
Open Source
MIT
null
acts_as_data_table
Stex
JavaScript
Code
91
346
jQuery(document).ready(function() { jQuery(document).on("click", '[data-init=sortable-column]', function(e) { var active, remote, url, urlSetBase, urlToggle; e.preventDefault(); urlToggle = jQuery(this).data('urlToggle'); urlSetBase = jQuery(this).data('urlSetBase'); remote = jQuery(this).data('remote'); active = jQuery(this).data('active'); url = urlSetBase; if (e.ctrlKey || e.metaKey) { url = urlToggle; } if (remote) { jQuery.ajax({ 'url': url, dataType: 'script' }); } else { window.location.href = url; } return false; }); return jQuery(document).on("click", "[data-init=sortable-column-direction]", function(e) { var remote, url; e.preventDefault(); url = jQuery(this).data('urlChangeDirection'); remote = jQuery(this).data('remote'); if (remote) { return jQuery.ajax({ 'url': url, dataType: 'script' }); } else { return window.location.href = url; } }); });
6,950
https://github.com/sitedisks/YuYan/blob/master/YuYan.API/YuYan.Domain/Database/ip2location_db3.cs
Github Open Source
Open Source
MIT
2,021
YuYan
sitedisks
C#
Code
73
185
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace YuYan.Domain.Database { [Table("ip2location_db3")] public class ip2location_db3 { [Key] public double ip_from { get; set; } public double ip_to { get; set; } public string country_code { get; set; } public string country_name { get; set; } public string region_name { get; set; } public string city_name { get; set; } public Nullable<double> latitude { get; set; } public Nullable<double> longitude { get; set; } } }
47,828
https://github.com/aljaxus/eu.aljaxus.xena/blob/master/api/session/signin.php
Github Open Source
Open Source
MIT
2,018
eu.aljaxus.xena
aljaxus
PHP
Code
463
1,666
<?php require_once __DIR__ . '/../../inc/__util/firstload.php'; require_once __DIR__ . '/../../inc/__util/database.php'; require_once __DIR__ . '/../../inc/googleApiCli/vendor/autoload.php'; $utildb = new dbInit(); $pdo = $utildb->pdo(); $datArr = array( 'POST' => (!empty($_POST)) ? $_POST : null, 'SESSION' => null, 'is_validtoken' => null, 'msg' => [] ); function startSession($uData){ global $datArr; array_push($datArr['msg'], 'Setting up session data'); $_SESSION['u_id'] = (!empty($uData['u_id'])) ? $uData['u_id'] : null; $_SESSION['u_email'] = (!empty($uData['email'])) ? $uData['email'] : null; $_SESSION['u_email_verified'] = (!empty($uData['email_verified'])) ? $uData['email_verified'] : null; $_SESSION['u_name'] = (!empty($uData['name'])) ? $uData['name'] : null; $_SESSION['u_picture'] = (!empty($uData['picture'])) ? $uData['picture'] : null; $_SESSION['u_given_name'] = (!empty($uData['given_name'])) ? $uData['given_name'] : null; $_SESSION['u_family_name'] = (!empty($uData['family_name'])) ? $uData['family_name'] : null; $_SESSION['u_locale'] = (!empty($uData['locale'])) ? $uData['locale'] : null; array_push($datArr['msg'], 'Finished setting up session data'); } if (!empty($_POST['token'])){ // Get $id_token via HTTPS POST. // Specify the CLIENT_ID of the app that accesses the backend $client = new Google_Client(['client_id' => _GAUTH_CLIID]); $payload = $client->verifyIdToken($_POST['token']); if ($payload) { $userid = $payload['sub']; $datArr['is_validtoken'] = true; if (!empty($payload['email'])){ array_push($datArr['msg'], 'User email: '.$payload['email']); if ($stmt = $pdo->prepare('SELECT `user_id`, `user_name_first`, `user_name_last`, `user_name_full`, `user_email`, `user_email`, `user_locale` FROM `users` WHERE `user_email` = ? LIMIT 1')){ array_push($datArr['msg'], 'PDO statement successfully prepared @ SELECT FROM users WHERE email'); if ($stmt->execute([$payload['email']])){ array_push($datArr['msg'], 'PDO statement successfully executed @ SELECT FROM users WHERE email'); if ($user = $stmt->fetch()){ array_push($datArr['msg'], 'User exists in the database, logging in...'); $payload['u_id'] = $user['user_id']; startSession($payload); } else { array_push($datArr['msg'], 'User does not exist in the database, signing up...'); if ($stmt = $pdo->prepare('INSERT INTO `users` (`user_name_first`, `user_name_last`, `user_name_full`, `user_email`, `user_picture`, `user_locale`) VALUES (?, ?, ?, ?, ?, ?);')){ array_push($datArr['msg'], 'PDO statement successfully prepared @ INSERT INTO users'); if ($stmt->execute([ $payload['given_name'], (!empty($payload['family_name']))?$payload['family_name']:null, $payload['name'], $payload['email'], $payload['picture'], $payload['locale'] ])){ array_push($datArr['msg'], 'PDO statement successfully executed @ INSERT INTO users'); if ($stmt->rowCount() == 1){ if ($u_id = $pdo->lastInsertId()){ array_push($datArr['msg'], 'Successfully got user\'s ID'); array_push($datArr['msg'], 'PDO statement successfully INSERTED @ INSERT INTO users'); array_push($datArr['msg'], 'Successfully signed the user up'); $payload['u_id'] = $u_id; startSession($payload); } else { array_push($datArr['msg'], 'Failed to get user\'s ID'); } } elseif ($stmt->rowCount() > 1) { array_push($datArr['msg'], 'PDO statement failed to INSERT @ INSERT INTO users - 2 >= rows modified'); } else { array_push($datArr['msg'], 'PDO statement failed to INSERT @ INSERT INTO users - not inserted'); } } else { array_push($datArr['msg'], 'PDO statement failed to execute @ INSERT INTO users'); } } else { array_push($datArr['msg'], 'PDO statement failed to prepare @ INSERT INTO users'); } } } else { array_push($datArr['msg'], 'PDO statement failed to execute @ SELECT FROM users WHERE email'); } } else { array_push($datArr['msg'], 'PDO statement failed to prepare @ SELECT FROM users WHERE email'); } } else { array_push($datArr['msg'], 'Something went wrong! Email was not provided'); } $_SESSION['u_isloged'] = true; } else { // Invalid ID token $datArr['is_validtoken'] = false; $_SESSION['u_isloged'] = false; } } $datArr['SESSION'] = $_SESSION; header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); Header('Content-type: application/json'); echo json_encode($datArr, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES);
45,035
https://github.com/navikt/k9-dokument/blob/master/settings.gradle.kts
Github Open Source
Open Source
MIT
null
k9-dokument
navikt
Kotlin
Code
3
13
rootProject.name = "k9-dokument"
17,140
https://github.com/mustsee/nuxt-starter-template/blob/master/components/partials/Modal.vue
Github Open Source
Open Source
MIT
2,021
nuxt-starter-template
mustsee
Vue
Code
294
978
<template> <div :class="closing ? 'closing' : ''" class="modal"> <div id="overlay" @click="closeModal" /> <div id="modal" class="content container" @keydown.esc="closeModal"> <nuxt-link :to="toParent" class="icon-times" /> <slot /> </div> </div> </template> <style lang="scss" scoped> @import '~/css/_bootstrap_functions.scss'; .modal { position: fixed; z-index: 100; overflow: auto; top: 0; left: 0; bottom: 0; right: 0; max-width: 100vw; padding: 0; } .content { background: white; box-shadow: 0 0px 90px -30px var(--primary-shadow); padding: 2rem; margin-top: -100vh; transition: transform 1s !important; color: var(--body-color); position: relative; margin-left: auto; margin-right: auto; @include media-breakpoint-up(sm) { margin-top: -95vh; margin-bottom: 5vh; } @include media-breakpoint-up(l) { margin-top: -90vh; margin-bottom: 10vh; } } #overlay { position: sticky; top: 0; width: 100%; height: 100%; z-index: 0; background: rgba(0, 0, 0, 0.25); cursor: pointer; } .icon-times { position: absolute; top: 15px; right: 10px; float: right; padding: 0 10px 5px; font-size: 1.3rem; text-decoration: none; &:hover { text-decoration: none; } } .closing { pointer-events: none; opacity: 0; transition: transform 1s, opacity 1s !important; .content { transition: transform 1s, opacity 1s !important; } } p { max-width: 100%; } </style> <style> body.modal-active { overflow: hidden; } </style> <script lang="ts"> import Vue from 'vue' export default Vue.extend({ data() { return { moving: false, closing: false, askBeforeClose: false, } }, computed: { toParent(): any { const hirarchy = this.$nuxt.$route.path.split('/') const offset = hirarchy[hirarchy.length - 1] === '' ? 3 : 2 const parent = hirarchy[hirarchy.length - offset] return '/' + parent }, }, mounted() { const body = document.querySelector('body') if (body) { body.classList.add('modal-active') } }, destroyed() { this.removeModalActive() }, methods: { removeModalActive(): void { const body = document.querySelector('body') if (body) { body.classList.remove('modal-active') } }, closeModal(): void { if ( this.askBeforeClose && !confirm( 'Ihre Änderungen gehen verloren wenn Sie diese Seite verlassen.' ) ) { return } this.removeModalActive() this.$nuxt.$router.push(this.toParent) }, preventClose(): void { this.askBeforeClose = true }, }, }) </script>
33,540
https://github.com/FabianoVeglianti/syncope/blob/master/client/idm/console/src/main/java/org/apache/syncope/client/console/commons/IdMAnyDirectoryPanelAdditionalActionsProvider.java
Github Open Source
Open Source
Apache-2.0
2,020
syncope
FabianoVeglianti
Java
Code
596
2,806
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not 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 org.apache.syncope.client.console.commons; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import org.apache.syncope.client.console.PreferenceManager; import org.apache.syncope.client.console.SyncopeConsoleSession; import org.apache.syncope.client.console.pages.BasePage; import org.apache.syncope.client.console.panels.AnyDirectoryPanel; import org.apache.syncope.client.console.panels.DisplayAttributesModalPanel; import org.apache.syncope.client.console.rest.BaseRestClient; import org.apache.syncope.client.console.wicket.ajax.form.AjaxDownloadBehavior; import org.apache.syncope.client.console.wicket.markup.html.bootstrap.dialog.BaseModal; import org.apache.syncope.client.console.wizards.CSVPullWizardBuilder; import org.apache.syncope.client.console.wizards.CSVPushWizardBuilder; import org.apache.syncope.client.console.wizards.any.ProvisioningReportsPanel; import org.apache.syncope.client.console.wizards.any.ResultPage; import org.apache.syncope.client.ui.commons.Constants; import org.apache.syncope.client.ui.commons.wizards.AjaxWizard; import org.apache.syncope.common.lib.to.ProvisioningReport; import org.apache.syncope.common.lib.types.IdRepoEntitlement; import org.apache.syncope.common.rest.api.beans.AnyQuery; import org.apache.syncope.common.rest.api.beans.CSVPullSpec; import org.apache.syncope.common.rest.api.beans.CSVPushSpec; import org.apache.wicket.Component; import org.apache.wicket.PageReference; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.authroles.authorization.strategies.role.metadata.MetaDataRoleAuthorizationStrategy; import org.apache.wicket.event.IEvent; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.Model; import org.apache.wicket.model.StringResourceModel; public class IdMAnyDirectoryPanelAdditionalActionsProvider implements AnyDirectoryPanelAdditionalActionsProvider { private static final long serialVersionUID = -6768727277642238924L; protected AjaxLink<Void> csvPushLink; protected AjaxLink<Void> csvPullLink; @Override public void add( final AnyDirectoryPanel<?, ?> panel, final BaseModal<?> modal, final boolean wizardInModal, final WebMarkupContainer container, final String type, final String realm, final String fiql, final int rows, final List<String> pSchemaNames, final List<String> dSchemaNames, final PageReference pageRef) { AjaxDownloadBehavior csvDownloadBehavior = new AjaxDownloadBehavior(); WebMarkupContainer csvEventSink = new WebMarkupContainer(Constants.OUTER) { private static final long serialVersionUID = -957948639666058749L; @Override public void onEvent(final IEvent<?> event) { if (event.getPayload() instanceof AjaxWizard.NewItemCancelEvent) { ((AjaxWizard.NewItemCancelEvent<?>) event.getPayload()).getTarget(). ifPresent(target -> modal.close(target)); } else if (event.getPayload() instanceof AjaxWizard.NewItemFinishEvent) { AjaxWizard.NewItemFinishEvent<?> payload = (AjaxWizard.NewItemFinishEvent) event.getPayload(); Optional<AjaxRequestTarget> target = payload.getTarget(); if (payload.getResult() instanceof ArrayList) { modal.setContent(new ResultPage<Serializable>( null, payload.getResult()) { private static final long serialVersionUID = -2630573849050255233L; @Override protected void closeAction(final AjaxRequestTarget target) { modal.close(target); } @Override protected Panel customResultBody( final String id, final Serializable item, final Serializable result) { @SuppressWarnings("unchecked") ArrayList<ProvisioningReport> reports = (ArrayList<ProvisioningReport>) result; return new ProvisioningReportsPanel(id, reports, pageRef); } }); target.ifPresent(t -> t.add(modal.getForm())); SyncopeConsoleSession.get().success(getString(Constants.OPERATION_SUCCEEDED)); } else if (Constants.OPERATION_SUCCEEDED.equals(payload.getResult())) { target.ifPresent(modal::close); SyncopeConsoleSession.get().success(getString(Constants.OPERATION_SUCCEEDED)); } else if (payload.getResult() instanceof Exception) { SyncopeConsoleSession.get().onException((Exception) payload.getResult()); } else { SyncopeConsoleSession.get().error(payload.getResult()); } if (target.isPresent()) { ((BasePage) pageRef.getPage()).getNotificationPanel().refresh(target.get()); target.get().add(container); } } } }; csvEventSink.add(csvDownloadBehavior); panel.addOuterObject(csvEventSink); csvPushLink = new AjaxLink<Void>("csvPush") { private static final long serialVersionUID = -817438685948164787L; @Override public void onClick(final AjaxRequestTarget target) { CSVPushSpec spec = csvPushSpec(type, panel, pSchemaNames, dSchemaNames); AnyQuery query = csvAnyQuery(realm, fiql, rows, panel.getDataProvider()); target.add(modal.setContent(new CSVPushWizardBuilder(spec, query, csvDownloadBehavior, pageRef). setEventSink(csvEventSink). build(BaseModal.CONTENT_ID, AjaxWizard.Mode.EDIT))); modal.header(new StringResourceModel("csvPush", panel, Model.of(spec))); modal.show(true); } }; csvPushLink.setOutputMarkupPlaceholderTag(true).setVisible(wizardInModal).setEnabled(wizardInModal); MetaDataRoleAuthorizationStrategy.authorize(csvPushLink, Component.RENDER, String.format("%s,%s", IdRepoEntitlement.IMPLEMENTATION_LIST, IdRepoEntitlement.TASK_EXECUTE)); panel.addInnerObject(csvPushLink.setOutputMarkupId(true).setOutputMarkupPlaceholderTag(true)); csvPullLink = new AjaxLink<Void>("csvPull") { private static final long serialVersionUID = -817438685948164787L; @Override public void onClick(final AjaxRequestTarget target) { CSVPullSpec spec = csvPullSpec(type, realm); target.add(modal.setContent(new CSVPullWizardBuilder(spec, pageRef). setEventSink(csvEventSink). build(BaseModal.CONTENT_ID, AjaxWizard.Mode.EDIT))); modal.header(new StringResourceModel("csvPull", panel, Model.of(spec))); modal.show(true); } }; csvPullLink.setOutputMarkupPlaceholderTag(true).setVisible(wizardInModal).setEnabled(wizardInModal); MetaDataRoleAuthorizationStrategy.authorize(csvPullLink, Component.RENDER, String.format("%s,%s", IdRepoEntitlement.IMPLEMENTATION_LIST, IdRepoEntitlement.TASK_EXECUTE)); panel.addInnerObject(csvPullLink.setOutputMarkupId(true).setOutputMarkupPlaceholderTag(true)); } protected CSVPushSpec csvPushSpec( final String type, final AnyDirectoryPanel<?, ?> panel, final List<String> pSchemaNames, final List<String> dSchemaNames) { CSVPushSpec spec = new CSVPushSpec.Builder(type).build(); spec.setFields(PreferenceManager.getList(panel.getRequest(), DisplayAttributesModalPanel.getPrefDetailView(type)). stream().filter(name -> !Constants.KEY_FIELD_NAME.equalsIgnoreCase(name)). collect(Collectors.toList())); spec.setPlainAttrs(PreferenceManager.getList( panel.getRequest(), DisplayAttributesModalPanel.getPrefPlainAttributeView(type)). stream().filter(name -> pSchemaNames.contains(name)).collect(Collectors.toList())); spec.setDerAttrs(PreferenceManager.getList(panel.getRequest(), DisplayAttributesModalPanel.getPrefPlainAttributeView(type)). stream().filter(name -> dSchemaNames.contains(name)).collect(Collectors.toList())); return spec; } protected CSVPullSpec csvPullSpec(final String type, final String realm) { CSVPullSpec spec = new CSVPullSpec(); spec.setAnyTypeKey(type); spec.setDestinationRealm(realm); return spec; } protected AnyQuery csvAnyQuery( final String realm, final String fiql, final int rows, final AnyDataProvider<?> dataProvider) { return new AnyQuery.Builder().realm(realm). fiql(fiql).page(dataProvider.getCurrentPage() + 1).size(rows). orderBy(BaseRestClient.toOrderBy(dataProvider.getSort())). build(); } @Override public void hide() { csvPushLink.setEnabled(false); csvPushLink.setVisible(false); csvPullLink.setEnabled(false); csvPullLink.setVisible(false); } }
38,165
https://github.com/MyJetEducation/Service.EducationMarketsApi/blob/master/src/Service.WalletApi.EducationMarketsApi/Controllers/Contracts/TaskTextRequest.cs
Github Open Source
Open Source
MIT
null
Service.EducationMarketsApi
MyJetEducation
C#
Code
11
40
namespace Service.WalletApi.EducationMarketsApi.Controllers.Contracts { public class TaskTextRequest : TaskRequestBase { } }
38,244
https://github.com/louchebem06/cub3D/blob/master/src/parsing/min_char_map.c
Github Open Source
Open Source
MIT
null
cub3D
louchebem06
C
Code
132
517
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* min_char_map.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mmehran <mmehran@student.42nice.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/08/14 20:57:18 by bledda #+# #+# */ /* Updated: 2021/11/11 13:54:46 by mmehran ### ########.fr */ /* */ /* ************************************************************************** */ #include "../../header/ft_config.h" int min_char_map(char **m) { t_position p; int player; int wall; player = 0; p.y = -1; while (m[(int)++p.y]) { p.x = -1; while (m[(int)p.y][(int)++p.x]) { if (m[(int)p.y][(int)p.x] == 'N' || m[(int)p.y][(int)p.x] == 'S' || m[(int)p.y][(int)p.x] == 'E' || m[(int)p.y][(int)p.x] == 'W') player = 1; if (m[(int)p.y][(int)p.x] == '1') wall = 1; } } if (!player) ft_error("Error:\n\t-Player position not found\n", RED); if (!wall) ft_error("Error:\n\t-Wall not found\n", RED); if (!player || !wall) return (1); return (0); }
27,696
https://github.com/pig-mesh/pig/blob/master/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/component/PigOAuthRequestInterceptor.java
Github Open Source
Open Source
Apache-2.0
2,023
pig
pig-mesh
Java
Code
143
654
package com.pig4cloud.pig.common.security.component; import cn.hutool.core.collection.CollUtil; import com.baomidou.mybatisplus.core.toolkit.StringUtils; import com.pig4cloud.pig.common.core.constant.SecurityConstants; import com.pig4cloud.pig.common.core.util.WebUtils; import feign.RequestInterceptor; import feign.RequestTemplate; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpHeaders; import org.springframework.security.oauth2.core.OAuth2AccessToken; import org.springframework.security.oauth2.server.resource.web.BearerTokenResolver; import javax.servlet.http.HttpServletRequest; import java.util.Collection; /** * oauth2 feign token传递 * * 重新 OAuth2FeignRequestInterceptor ,官方实现部分常见不适用 * * @author lengleng * @date 2022/5/29 */ @Slf4j @RequiredArgsConstructor public class PigOAuthRequestInterceptor implements RequestInterceptor { private final BearerTokenResolver tokenResolver; /** * Create a template with the header of provided name and extracted extract </br> * * 1. 如果使用 非web 请求,header 区别 </br> * * 2. 根据authentication 还原请求token * @param template */ @Override public void apply(RequestTemplate template) { Collection<String> fromHeader = template.headers().get(SecurityConstants.FROM); // 带from 请求直接跳过 if (CollUtil.isNotEmpty(fromHeader) && fromHeader.contains(SecurityConstants.FROM_IN)) { return; } // 非web 请求直接跳过 if (!WebUtils.getRequest().isPresent()) { return; } HttpServletRequest request = WebUtils.getRequest().get(); // 避免请求参数的 query token 无法传递 String token = tokenResolver.resolve(request); if (StringUtils.isBlank(token)) { return; } template.header(HttpHeaders.AUTHORIZATION, String.format("%s %s", OAuth2AccessToken.TokenType.BEARER.getValue(), token)); } }
37,545
https://github.com/Yanshang1991/TensorFlowTTS/blob/master/examples/fastspeech2/__init__.py
Github Open Source
Open Source
Apache-2.0
null
TensorFlowTTS
Yanshang1991
Python
Code
8
62
from examples.fastspeech2.fastspeech2_dataset import CharactorDurationF0EnergyMelDataset import examples.fastspeech2.train_fastspeech2 import examples.fastspeech2.decode_fastspeech2
39,736
https://github.com/vishalbelsare/OG-USA/blob/master/ogcore/tests/test_parameters.py
Github Open Source
Open Source
CC0-1.0, LicenseRef-scancode-public-domain
2,022
OG-USA
vishalbelsare
Python
Code
444
1,753
import os import tempfile import pytest import numpy as np from ogcore.parameters import Specifications, revision_warnings_errors from ogcore import utils # get path to puf if puf.csv in ogcore/ directory CUR_PATH = os.path.abspath(os.path.dirname(__file__)) JSON_REVISION_FILE = """{ "revision": { "frisch": 0.3 } }""" @pytest.fixture(scope='module') def revision_file(): f = tempfile.NamedTemporaryFile(mode="a", delete=False) f.write(JSON_REVISION_FILE) f.close() # Must close and then yield for Windows platform yield f os.remove(f.name) def test_create_specs_object(): specs = Specifications() assert specs def test_compute_default_params(): specs = Specifications() specs.alpha_G = np.ones((10, 1)) specs.compute_default_params() assert specs.alpha_G[10] == 1 param_updates1 = { 'T': 4, 'S': 3, 'J': 1, 'ubi_nom_017': 1000, 'eta': np.ones((4, 3, 1)) / 12, 'ubi_nom_1864': 1200, 'ubi_nom_65p': 400, 'ubi_growthadj': True} expected1 = np.ones((7, 3, 1)) * 2180 param_updates2 = { 'T': 4, 'S': 3, 'J': 1, 'ubi_nom_017': 1000, 'eta': np.ones((4, 3, 1)) / 12, 'ubi_nom_1864': 1200, 'ubi_nom_max': 2000, 'ubi_nom_65p': 400, 'ubi_growthadj': True} expected2 = np.ones((7, 3, 1)) * 2000 param_updates3 = { 'T': 4, 'S': 3, 'J': 1, 'ubi_nom_017': 1000, 'eta': np.ones((4, 3, 1)) / 12, 'ubi_nom_1864': 1200, 'ubi_nom_65p': 400, 'ubi_growthadj': False, 'g_y_annual': 0.03} expected3 = np.array([ [[2180], [2180.], [2180.]], [[656.9250257], [656.9250257], [656.9250257]], [[197.9589401], [197.9589401], [197.9589401]], [[59.65329442], [59.65329442], [59.65329442]], [[17.97602843], [17.97602843], [17.97602843]], [[17.97602843], [17.97602843], [17.97602843]], [[17.97602843], [17.97602843], [17.97602843]]]) @pytest.mark.parametrize( 'param_updates, expected', [(param_updates1, expected1), (param_updates2, expected2), (param_updates3, expected3)], ids=['UBI growth adj', 'UBI hit max', 'UBI no growth adj']) def test_get_ubi_nom_objs(param_updates, expected): spec = Specifications() spec.update_specifications(param_updates) assert np.allclose(spec.ubi_nom_array, expected) def test_update_specifications_with_dict(): spec = Specifications() new_spec_dict = { 'frisch': 0.3, } spec.update_specifications(new_spec_dict) assert spec.frisch == 0.3 assert len(spec.errors) == 0 def test_update_specification_with_json(): spec = Specifications() new_spec_json = """ { "frisch": 0.3 } """ spec.update_specifications(new_spec_json) assert spec.frisch == 0.3 assert len(spec.errors) == 0 def test_implement_reform(): specs = Specifications() new_specs = { 'tG1': 30, 'T': 80, 'frisch': 0.3, 'tax_func_type': 'DEP' } specs.update_specifications(new_specs) assert specs.frisch == 0.3 assert specs.tG1 == 30 assert specs.T == 80 assert specs.tax_func_type == 'DEP' assert len(specs.errors) == 0 # assert len(specs.warnings) == 0 def test_implement_bad_reform1(): specs = Specifications() # tG1 has an upper bound at T / 2 new_specs = { 'tG1': 50, 'T': 80, } specs.update_specifications(new_specs, raise_errors=False) assert len(specs.errors) == 0 def test_implement_bad_reform2(): specs = Specifications() # tG1 has an upper bound at T / 2 new_specs = { 'T': 80, 'tax_func_type': 'not_a_functional_form' } specs.update_specifications(new_specs, raise_errors=False) assert len(specs.errors) > 0 assert specs.errors['tax_func_type'][0] == ( 'tax_func_type "not_a_functional_form" must be in list of ' + 'choices DEP, DEP_totalinc, GS, linear.') def test_implement_bad_reform3(): specs = Specifications() with pytest.raises(ValueError): specs.update_specifications(None, raise_errors=False) def test_revision_warnings_errors(): user_mods = {'frisch': 0.41} ew = revision_warnings_errors(user_mods) assert len(ew['errors']) == 0 assert len(ew['warnings']) == 0 user_mods = {'frisch': 0.1} bad_ew = revision_warnings_errors(user_mods) assert len(bad_ew['errors']) > 0 assert len(bad_ew['warnings']) == 0 def test_conditional_validator(): specs = Specifications() new_specs = { 'budget_balance': True, 'baseline_spending': True } specs.update_specifications(new_specs, raise_errors=False) assert len(specs.errors) > 0
38,681