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/rabbishuki/mychag/blob/master/Server/db/mysql.js
Github Open Source
Open Source
MIT
2,017
mychag
rabbishuki
JavaScript
Code
408
1,251
var mysql = require('mysql'), pool = mysql.createPool({ host: process.env.host, user: process.env.user, password: process.env.password, database: process.env.database }); function validate(string) { return pool.escape(string) || ''; } function query(string, callback) { pool.getConnection(function (err, connection) { if(err) console.error(err); connection.query(string, function (error, results = [], fields = []) { connection.release(); if (error) console.error(error); callback({ error, results, fields }); }); }); } function insertArray(table, array, duplicate) { // Validate Keys and Values. var keys = validate(Object.keys(array[0])), splitKeys = keys.split(/\s*'| |,\s*/).filter(Boolean), values = array.map(value => validate(Object.keys(value).map(v => Array.isArray(value[v]) ? JSON.stringify(value[v]) : value[v]))); //array.map(value => validate(Object.keys(value).map(v => value[v]))); // Build request string. var request = [ 'INSERT INTO', table, '(', splitKeys, ') VALUES ', values.map(value => '(' + value + ')') // array.map(val => `( ${Object.values(val).map(v => v ? "'" + v + "'" : 'null').join(", ")})`) ]; // Upsert. if (duplicate) { request.push('ON DUPLICATE KEY UPDATE', splitKeys.map((x, i) => x + '=VALUES(' + x + ')')) } return request.join(' '); } function location(lat, lng, radius, limit, type) { var typeText = ''; if (type) typeText = 'AND z.type = ' + type; return `SELECT * FROM ( SELECT z.id, z.formatted_address, z.lat, z.lng, z.date, z.json, z.type, z.active, z.approved, p.radius, p.distance_unit * DEGREES(ACOS(COS(RADIANS(p.latpoint)) * COS(RADIANS(z.lat)) * COS(RADIANS(p.longpoint - z.lng)) + SIN(RADIANS(p.latpoint)) * SIN(RADIANS(z.lat)))) AS distance FROM tb_events AS z JOIN ( SELECT ${lat} AS latpoint, ${lng} AS longpoint, ${radius} AS radius, 111.045 AS distance_unit ) AS p ON 1=1 WHERE z.lat BETWEEN p.latpoint - (p.radius / p.distance_unit) AND p.latpoint + (p.radius / p.distance_unit) AND z.lng BETWEEN p.longpoint - (p.radius / (p.distance_unit * COS(RADIANS(p.latpoint)))) AND p.longpoint + (p.radius / (p.distance_unit * COS(RADIANS(p.latpoint)))) ${typeText} ) AS d WHERE approved = 1 AND active = 1 AND distance <= radius ORDER BY distance LIMIT ${limit}`; } function formatAdsForUser(ads) { return ads.map(function (ad) { var json = {}; try { json = JSON.parse(ad.json); } catch (e) { console.log(`Error parsing ad with id #${ad.id}`); }; return { id: ad.id, date: ad.date, title: json.title || '', imgFile: json.imgFile || '', comment: json.comment || '', moreInfo: json.moreInfo || '', type: ad.type, location: { lat: ad.lat, lng: ad.lng, formatted_address: ad.formatted_address, distance: ad.distance }, userInfo: { name: json.name || '', phone: json.phone || '', email: json.email || '' }, out: { Link: json.Link || '', LinkText: json.LinkText || '' } } }); }; function update(id, col, value) { return `UPDATE tb_events SET ${col} = ${value} WHERE id = ${id}`; } module.exports = { v: validate, q: query, i: insertArray, l: location, f: formatAdsForUser, u: update, };
21,129
https://github.com/DaveCS1/JB.Toolkit/blob/master/JB.Toolkit/Scripts/CustomFunctions.js
Github Open Source
Open Source
MIT
2,020
JB.Toolkit
DaveCS1
JavaScript
Code
2,813
7,860
/* ************************************************************************ REUSABLES JAVASCRIPT CUSTOM FUNCTIONS - CAN BE COPIED TO ANOTHER PROJECT ************************************************************************ */ /** @description I.e. http://domina.com/ */ function BaseUrl() { return window.location.protocol + "//" + window.location.host + "/" } /** @description Create Url affix: UrlAction("<Action>","<Controler>","<data>"); */ function UrlAction() { var base = window.location.protocol + "//" + window.location.host + "/" + arguments[1] + "/" + arguments[0]; for (var i = 2; i < arguments.length; ++i) base = base + "/" + arguments[i]; return base; } /** @description Create Url affix: UrlApiAction("<end-point>", "<action / data>"); */ function UrlApiAction() { var base = window.location.protocol + "//" + window.location.host + "/" + arguments[0] + "/" + arguments[1]; for (var i = 2; i < arguments.length; ++i) base = base + "/" + arguments[i]; return base; } /** @description Returns browser, i.e. Chrome, Opera, IE */ function GetBrowser() { if (navigator.userAgent.indexOf("Chrome") != -1) { return "Chrome"; } else if (navigator.userAgent.indexOf("Opera") != -1) { return "Opera"; } else if (navigator.userAgent.indexOf("MSIE") != -1) { return "IE"; } else if (navigator.userAgent.indexOf("NET CLR") != -1) { return "IE"; } else if (navigator.userAgent.indexOf("Windows NT") != -1) { return "IE"; } else if (navigator.userAgent.indexOf("Firefox") != -1) { return "Firefox"; } else { return "unknown"; } } /** @description Disabled mouse right click on page */ function DisableRightClick() { $(function () { $(this).bind("contextmenu", function (e) { e.preventDefault(); }); }); } /** @description Enabled mouse right click on page */ function EnableRightClick() { $(document).unbind("contextmenu"); $(document).bind("contextmenu", function (e) { return true; }); } /** @description Shows print with preview window (if available) */ function PrintWindow() { if (GetBrowser() == "IE") { try { // IE's 'Print preview' : var OLECMDID = 7; /* OLECMDID values: * 6 - print * 7 - print preview * 1 - open window * 4 - Save As */ var PROMPT = 1; // 2 DONTPROMPTUSER var WebBrowser = '<OBJECT ID="WebBrowser1" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>'; document.body.insertAdjacentHTML('beforeEnd', WebBrowser); WebBrowser1.ExecWB(OLECMDID, PROMPT); WebBrowser1.outerHTML = ""; } catch (err) { window.print(); } } else { window.print(); } } /** @description Set the selected dropdown entry by text rather than key value */ function SetDropDownByText(dropDownId, textToFind) { var dd = document.getElementById(dropDownId); for (var i = 0; i < dd.options.length; i++) { if (dd.options[i].text === textToFind) { dd.selectedIndex = i; break; } } } /** @description Disables a HTML element, sets readonly and adds a 'disabled' class name * @param {string} id ID of element to disable * @param {boolean} includeParent In bootstrap, often elements are nested inside another, so include parent */ function DisableElement(id, includeParent) { if (includeParent) { $("#" + id).parent().addClass('disabled'); $("#" + id).parent().attr('disabled', 'disabled'); $("#" + id).parent().attr('readonly', 'readonly'); } $("#" + id).addClass('disabled'); $("#" + id).attr('disabled', 'disabled'); $("#" + id).attr('readonly', 'readonly'); } /** @description Enable a HTML element, sets readonly and adds a 'disabled' class name * @param {string} id ID of element to enable * @param {boolean} includeParent In bootstrap, often elements are nested inside another, so include parent */ function EnableElement(id, includeParent) { if (includeParent) { $("#" + id).parent().removeClass('disabled'); $("#" + id).parent().removeAttr('disabled'); $("#" + id).parent().removeAttr('readonly'); } $("#" + id).removeClass('disabled'); $("#" + id).removeAttr('disabled'); $("#" + id).removeAttr('readonly'); } /** @description Writes text to a file location * @param {string} content Text to write * @param {string} filePath File path where to save the file */ function WriteToFile(content, filePath) { var textToWrite = content; var textFileAsBlob = new Blob([textToWrite], { type: 'text/plain' }); if (!filePath) filePath = "log-" + GetTimestamp() + ".txt"; if ('msSaveOrOpenBlob' in navigator) { navigator.msSaveOrOpenBlob(textFileAsBlob, filePath); } else { var downloadLink = document.createElement('a'); downloadLink.download = filePath; downloadLink.innerHTML = 'Download File'; if ('webkitURL' in window) { // Chrome allows the link to be clicked without actually adding it to the DOM. downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob); } else { // Firefox requires the link to be added to the DOM before it can be clicked. downloadLink.href = window.URL.createObjectURL(textFileAsBlob); downloadLink.click(function () { document.body.removeChild(event.target); }); downloadLink.style.display = 'none'; document.body.appendChild(downloadLink); } downloadLink.click(); } } /** @description Starts a file download session * @param {string} targetLinkId Some a href link to use as template (can be a hidden link) * @param {string} downloadUrl Source URl */ function DownloadFile(targetLinkId, downloadUrl) { var req = new XMLHttpRequest(); req.open("GET", downloadUrl, true); req.responseType = "blob"; req.setRequestHeader('my-custom-header', 'custom-value'); // adding some headers (if needed) req.onload = function (event) { var blob = req.response; var fileName = null; var contentType = req.getResponseHeader("content-type"); // IE/EDGE seems not returning some response header if (req.getResponseHeader("content-disposition")) { var contentDisposition = req.getResponseHeader("content-disposition"); fileName = contentDisposition.substring(contentDisposition.indexOf("=") + 1); fileName = fileName.substring(1, fileName.length - 1); } else { fileName = "unnamed." + contentType.substring(contentType.indexOf("/") + 1); } if (window.navigator.msSaveOrOpenBlob) { // Internet Explorer window.navigator.msSaveOrOpenBlob(new Blob([blob], { type: contentType }), fileName); } else { var el = document.getElementById(targetLinkId); el.href = window.URL.createObjectURL(blob); el.download = fileName; el.click(); } }; req.send(); } /** @description Shows a JQuery UI Dialogue, header classes can be: success, dangeer, warning, info, secondary, light, dark, white or default */ function JqueryUIDialog(containerId, title, message, headerClassName, timeoutInMs) { var tmpID = GenerateGUID(); $("#" + containerId).append("<div id=" + tmpID + "></div>") $("#" + tmpID).html(message); $("#" + tmpID).dialog({ title: title, modal: true, dialogClass: (headerClassName == "success" || headerClassName == "danger" || headerClassName == "warning" || headerClassName == "info" || headerClassName == "secondary" || headerClassName == "light" || headerClassName == "dark" || headerClassName == "white" || headerClassName == "default") ? "header-" + headerClassName : "header-default", buttons: [{ text: "Ok", click: function () { $(this).dialog("close"); $("#" + tmpID).remove(); } }], }); if (timeoutInMs) { setTimeout(function () { try { $("#" + tmpID).remove(); } catch (e) { } }, timeoutInMs); } } /** @description Format time in AM / PM format */ function FormatAMPM(date) { var hours = date.getHours(); var minutes = date.getMinutes(); var ampm = hours >= 12 ? 'PM' : 'AM'; hours = hours % 12; hours = hours ? hours : 12; // the hour '0' should be '12' minutes = minutes < 10 ? '0' + minutes : minutes; var strTime = hours + ':' + minutes + ' ' + ampm; return strTime; } /** @description Format number to 2 decimal places */ function FormatCurrency(amount) { if (!amount) return ""; var neg = false; if (amount < 0) { neg = true; total = Math.abs(amount); } return (neg ? "-" : '') + parseFloat(amount, 10).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "1,").toString(); } /** @description Simulate a mouse click on an element by ID */ function SimulateClickById(id) { var evt = document.createEvent("MouseEvents"); evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); var a = document.getElementById(id); a.dispatchEvent(evt); } /** @description Simulate a mouse click on an element by class name */ function SimulateClickByClass(className) { var evt = document.createEvent("MouseEvents"); evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); var a = document.getElementsByClassName(className)[0]; a.dispatchEvent(evt); } /** @description Simulate a mouse click on an element by query selector */ function SimulateClickByQuerySelector(query) { var evt = document.createEvent("MouseEvents"); evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); var a = document.querySelector(query); a.dispatchEvent(evt); } /** @description Show / Select a Boostrap tab */ function ShowTab(id) { $("#" + id).trigger('click'); } /** @description Checks whether a string is valid json */ function IsJsonString(str) { try { JSON.parse(str); } catch (e) { return false; } return true; } /** @description After copying text to clipboard, this function shows a tooltip indicating success */ function ShowCopiedTooltip(btn) { try { btn.classList.add("tooltipped"); if (btn.id.indexOf("eBtn") > -1) btn.classList.add("tooltipped-n"); else btn.classList.add("tooltipped-s"); setTimeout(function () { btn.classList.remove("tooltipped"); btn.classList.remove("tooltipped-s"); btn.classList.remove("tooltipped-n"); }, 3000); } catch (err) { } } /** @description Use $("#someElem").invisible(); instead of $("#someElem").hide() to keep element on page * Use $("#someElem").visible(); instead of $("#someElem").show() to keep element on page */ (function ($) { $.fn.invisible = function () { return this.each(function () { $(this).css("visibility", "hidden"); }); }; $.fn.visible = function () { return this.each(function () { $(this).css("visibility", "visible"); }); }; }(jQuery)); /** @description Use $("#someElem").fadeInVisibility(); instead of $("#someElem").fadeIn() to keep element on page * Use $("#someElem").fadeOutVisibility(); instead of $("#someElem").fadeOut() to keep element on page */ (function ($) { $.fn.fadeInVisibility = function () { return this.each(function () { $(this).css('opacity', 0); $(this).css('visibility', 'visible'); $(this).animate({ opacity: 1 }, 1000); }); }; $.fn.fadeOutVisibility = function () { return this.each(function () { $(this).animate({ opacity: 0 }, 1000); $(this).css('visibility', 'hidden'); }); }; }(jQuery)); function AddDays(theDate, days) { return new Date(theDate.getTime() + days * 24 * 60 * 60 * 1000); } /** @description Organises entries in a dropdown by text alphabetically */ function SortSelectPickerOptionsByText(elementId) { var my_options = $("#" + elementId + " option"); my_options.sort(function (a, b) { if (a.text > b.text) return 1; else if (a.text < b.text) return -1; else return 0; }); $("#" + elementId).empty().append(my_options).selectpicker("refresh"); } /** @description Parses text using regular expressions, and any links (i.e. https://something.com) found are converted * to actual <a href= links */ function ConvertUrlInTextToLinks(text) { return (text || "").replace( /([^\S]|^)(((https?\:\/\/)|(www\.))(\S+))/gi, function (match, space, url) { var hyperlink = url; if (!hyperlink.match('^https?:\/\/')) { hyperlink = 'http://' + hyperlink; } return space + '<a href="' + hyperlink + '">' + url + '</a>'; } ); }; /** @description Returns whether or not an email address is valid using regular expressions */ function ValidateEmailAddress(email) { var expression = /(?!.*\.{2})^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")@(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i; var allOK; var parts = email.split(';') for (var i = 0; i < parts.length; i++) { var theEmail = parts[i]; if (theEmail.indexOf('<') !== -1 || theEmail.indexOf('>') !== -1) { var parts2 = theEmail.split("<"); var parts3 = parts2[1].split(">"); theEmail = parts3[0]; } if (i > 0 && theEmail != "") allOK = expression.test(String(theEmail).toLowerCase()); if (allOK == false) return false; } return true; } /** @description Input mask of different types (i.e. if set to MONEY or NUMBER you can't enter text into the input filed). * Checks types include: NUMBER, MONEY, NUMBER-SPACE-COMMA and DATE */ function ValidateDataType(obj, type) { // delete, backspace, shift, tab if (!(event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 16)) { if (type == "NUMBER") { // arrows, dash if (event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 109 || event.keyCode == 189) { // invert negative positive if '-' pressed if (event.keyCode == 109 || event.keyCode == 189) { if (obj.value.includes("-")) { obj.value = obj.value.replace("-", ""); event.preventDefault(); } else { obj.value = "-" + obj.value; event.preventDefault(); } } } else { // Ensure that it is a number and stop the keypress if (!((event.keyCode > 47 && event.keyCode < 58) || (event.keyCode > 94 && event.keyCode < 106))) { event.preventDefault(); } } } if (type == "NUMBER-SPACE-COMMA") { // arrows, dash, comma, space if (event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 109 || event.keyCode == 189 || event.keyCode == 188 || event.keyCode == 32) { // invert negative positive if '-' pressed if (event.keyCode == 109 || event.keyCode == 189) { if (obj.value.includes("-")) { obj.value = obj.value.replace("-", ""); event.preventDefault(); } else { obj.value = "-" + obj.value; event.preventDefault(); } } } else { // Ensure that it is a number and stop the keypress if (!((event.keyCode > 47 && event.keyCode < 58) || (event.keyCode > 94 && event.keyCode < 106))) { event.preventDefault(); } } } else if (type == "MONEY") { // arrows, dash, full stop if (event.keyCode == 190 || event.keyCode == 110 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 109 || event.keyCode == 189) { // only allow 1 full stop if (event.keyCode == 190 || event.keyCode == 110) { if (obj.value.includes(".")) { event.preventDefault(); } } // invert negative positive if '-' pressed if (event.keyCode == 109 || event.keyCode == 189) { if (obj.value.includes("-")) { obj.value = obj.value.replace("-", ""); event.preventDefault(); } else { obj.value = "-" + obj.value; event.preventDefault(); } } } else { // Ensure that it is a number and stop the keypress if (!((event.keyCode > 47 && event.keyCode < 58) || (event.keyCode > 94 && event.keyCode < 106))) { event.preventDefault(); } else { var n = obj.value.indexOf("."); if (n != -1) { if (obj.value.length - n > 2) event.preventDefault(); } } } } else if (type == "DATE") { // arrows, slash if (event.keyCode == 191 || event.keyCode == 111 || event.keyCode == 37 || event.keyCode == 39) { // only allow 1 full stop if (event.keyCode == 191 || event.keyCode == 111) { if (obj.value.length == 2 || obj.value.length == 5) { if (obj.value.length > 9) { event.preventDefault(); } } else { event.preventDefault(); } } } else { // Ensure that it is a number and stop the keypress if (!((event.keyCode > 47 && event.keyCode < 58) || (event.keyCode > 94 && event.keyCode < 106))) { event.preventDefault(); } // only allow certain quanity of number unless slash is entered else { if (obj.value.length > 9) { event.preventDefault(); } else if (obj.value.length == 2 || obj.value.length == 5) { event.preventDefault(); } } } } } } /** @description Input make helper. I.e. if set to DATE, the after you enter say '22' a forward slash will * then be automatically appended to the input field * Checks types include: DATE */ function DataTypeHelper(obj, type) { // allows user not to have to enter slash '/' if (type == "DATE") { if (obj.value.length == 2 || obj.value.length == 5) { if (event.keyCode != 8) obj.value = obj.value + "/"; } } } /** @description Simply returns a random integer */ function GetRandomInt(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min; } /** @description Get number sequence timestamp based on date and time (long) */ function GetTimestamp() { let current_datetime = new Date() let formatted_date = "" + current_datetime.getFullYear() + "" + (current_datetime.getMonth() + 1) + "" + current_datetime.getDate() + "-" + current_datetime.getHours() + "" + current_datetime.getMinutes() + "" + current_datetime.getSeconds(); return formatted_date } /** @description Get number sequence timestamp based on date only (short) */ function GetDateOnlyTimestamp() { let current_datetime = new Date() let formatted_date = "" + current_datetime.getFullYear() + "" + (current_datetime.getMonth() + 1) + "" + current_datetime.getDate(); return formatted_date } /** @description custom copy to clipboard (in case native doesn't work) * Basically creates a hidden text area on focus pane, copies of a control to it, and does * a browser method for highlighting and copying the text * @param {any} elementObject The element id if a text area or input to copy to the clipboard * @param {string} placeholderClass Class name of any element on the page to use for the DOM */ function CustomCopyToClipboard(elementObject, placeholderClass) { try { var randomNumber = GetRandomInt(1, 999); var targetId = "_hiddenCopyText_" + randomNumber; var target = document.getElementById(targetId); target = document.createElement("textarea"); target.style.position = "absolute"; target.style.left = "-9999px"; target.style.top = "0"; target.id = targetId; if (placeholderClass) $("." + placeholderClass).append(target); else document.body.appendChild(target); // trim whitespace var brRegex = /<br\s*[\/]?>/gi; try { target.textContent = elementObject.textContent.replace(brRegex, "\r\n").replace(/<\/?[a-zA-Z]+\/?>/g, '').trim(); } catch (err1) { try { target.textContent = elementObject.val().replace(brRegex, "\r\n").replace(/<\/?[a-zA-Z]+\/?>/g, '').trim(); if (target.textContent == "") target.textContent = elementObject.text().replace(brRegex, "\r\n").replace(/<\/?[a-zA-Z]+\/?>/g, '').trim(); } catch (err2) { try { target.textContent = elementObject.text().replace(brRegex, "\r\n").replace(/<\/?[a-zA-Z]+\/?>/g, '').trim(); } catch (err2) { try { target.textContent = elementObject.html().replace(brRegex, "\r\n").replace(/<\/?[a-zA-Z]+\/?>/g, '').trim(); } catch (err3) { } } } } target.focus(); target.setSelectionRange(0, target.value.length); document.execCommand("copy", false, target.textContent); $('#' + targetId).remove(); } catch (err) { } } /** @description Convert base64 string to byte array * @param {string} base64 Base64 string */ function ConvertDataURIToBinary(base64) { var raw = window.atob(base64); var rawLength = raw.length; var array = new Uint8Array(new ArrayBuffer(rawLength)); for (var i = 0; i < rawLength; i++) { array[i] = raw.charCodeAt(i); } return array; } /** @description Simply positions 1 element next to another element */ function PositionElementRelativeToAnother(source, target) { source.position({ my: "left top", at: "left bottom", of: target, collision: "fit" }); } /** @description Generate a unique GUID */ function GenerateGUID() { // Public Domain/MIT var d = new Date().getTime(); //Timestamp var d2 = (performance && performance.now && (performance.now() * 1000)) || 0;//Time in microseconds since page-load or 0 if unsupported return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { var r = Math.random() * 16;//random number between 0 and 16 if (d > 0) { //Use timestamp until depleted r = (d + r) % 16 | 0; d = Math.floor(d / 16); } else { //Use microseconds since page-load if supported r = (d2 + r) % 16 | 0; d2 = Math.floor(d2 / 16); } return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16); }); } /** @description Dropdown onChange will always fire even if selecting the same item */ $.fn.alwaysChange = function (callback) { return this.filter('select').each(function () { var elem = this; var $this = $(this); $this.change(function () { callback($this.val()); }).focus(function () { elem.selectedIndex = -1; elem.blur(); }); }); } /** @description Force redraw of an element */ function RedrawElement(id) { $("#" + id).hide().show(0); } /** @description JQuery DataTables, particular server side, responsive database sometimes have trouble rendering * (particularly, aligning the headers with the body in the table), this function seems to resolve it. Call after creation */ function RefreshDataTableColumnsWidths(tableId) { let table = $('#' + tableId).DataTable(); table.columns.adjust(); table.responsive.recalc(); table.columns.adjust(); setTimeout(function () { table.columns.adjust(); table.responsive.recalc(); table.columns.adjust(); }, 250); $(window).resize(); $(window).trigger('resize'); window.dispatchEvent(new Event('resize')); }
18,952
https://github.com/brain-not-found/xnxx/blob/master/views/ajoutcarte.php
Github Open Source
Open Source
MIT
null
xnxx
brain-not-found
PHP
Code
42
231
<?PHP include "../entities/carte.php"; include "../core/carteC.php"; if (isset($_POST['username']) and isset($_POST['mail']) and isset($_POST['type']) and isset($_POST['nom']) and isset($_POST['prenom']) and isset($_POST['tel']) and isset($_POST['age'])){ $carte1=new carte($_POST['username'],$_POST['mail'],$_POST['type'],$_POST['nom'],$_POST['prenom'],$_POST['tel'],$_POST['age']); //Partie2 /* var_dump($carte1); } */ //Partie3 $carte1C=new carteC(); $carte1C->ajoutercarte($carte1); header('Location: Gestion Client.php'); } else{ echo "vérifier les champs"; } //*/ ?>
43,947
https://github.com/hmac/nvim-treesitter/blob/master/queries/surface/folds.scm
Github Open Source
Open Source
Apache-2.0
2,022
nvim-treesitter
hmac
Scheme
Code
15
33
; Surface folds similar to HTML and includes blocks [ (tag) (component) (block) ] @fold
15,389
https://github.com/XiaofengdiZhu/percentage/blob/master/percentage/percentage/TrayIcon.cs
Github Open Source
Open Source
MIT
2,020
percentage
XiaofengdiZhu
C#
Code
309
957
using System; using System.Drawing; using System.Runtime.InteropServices; using System.Windows.Forms; namespace percentage { class TrayIcon { [DllImport("user32.dll", CharSet = CharSet.Auto)] static extern bool DestroyIcon(IntPtr handle); private const string iconFont = "pannetje_10"; private const int iconFontSize = 8; private string batteryPercentage; private NotifyIcon notifyIcon; public TrayIcon() { ContextMenu contextMenu = new ContextMenu(); MenuItem menuItem = new MenuItem(); notifyIcon = new NotifyIcon(); // initialize contextMenu contextMenu.MenuItems.AddRange(new MenuItem[] { menuItem }); // initialize menuItem menuItem.Index = 0; menuItem.Text = "退出"; menuItem.Click += new System.EventHandler(menuItem_Click); notifyIcon.ContextMenu = contextMenu; batteryPercentage = "?"; notifyIcon.Visible = true; Timer timer = new Timer(); timer.Tick += new EventHandler(timer_Tick); timer.Interval = 1000; // in miliseconds timer.Start(); } private void timer_Tick(object sender, EventArgs e) { PowerStatus powerStatus = SystemInformation.PowerStatus; batteryPercentage = (powerStatus.BatteryLifePercent * 100).ToString(); bool charging = SystemInformation.PowerStatus.BatteryChargeStatus.HasFlag(BatteryChargeStatus.Charging); using (Bitmap bitmap = new Bitmap(DrawText(batteryPercentage, new Font(iconFont, iconFontSize), Color.White, Color.Transparent))) { System.IntPtr intPtr = bitmap.GetHicon(); try { using (Icon icon = Icon.FromHandle(intPtr)) { notifyIcon.Icon = icon; notifyIcon.Text = batteryPercentage + "%"; if (!charging) { int seconds = SystemInformation.PowerStatus.BatteryLifeRemaining; if (seconds > 0) { int mins = seconds / 60; notifyIcon.Text += "\n剩余" + " " + (mins / 60) + ":" + (mins % 60); } } else { notifyIcon.Text = "已连接电源"; } } } finally { DestroyIcon(intPtr); } } } private void menuItem_Click(object sender, EventArgs e) { notifyIcon.Visible = false; notifyIcon.Dispose(); Application.Exit(); } private Image DrawText(String text, Font font, Color textColor, Color backColor) { var textSize = GetImageSize(text, font); Image image = new Bitmap((int) textSize.Width, (int) textSize.Height); using (Graphics graphics = Graphics.FromImage(image)) { // paint the background graphics.Clear(backColor); // create a brush for the text using (Brush textBrush = new SolidBrush(textColor)) { graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit; graphics.DrawString(text, font, textBrush, 0, 0); graphics.Save(); } } return image; } private static SizeF GetImageSize(string text, Font font) { using (Image image = new Bitmap(1, 1)) using (Graphics graphics = Graphics.FromImage(image)) return graphics.MeasureString(text, font); } } }
31,852
https://github.com/TrickyPi/swc/blob/master/crates/swc_ecma_ast/src/lib.rs
Github Open Source
Open Source
Apache-2.0
null
swc
TrickyPi
Rust
Code
655
2,756
#![cfg_attr(docsrs, feature(doc_cfg))] #![deny(unreachable_patterns)] #![deny(missing_copy_implementations)] #![deny(trivial_casts)] #![deny(trivial_numeric_casts)] #![deny(unreachable_pub)] #![deny(clippy::all)] #![allow(clippy::enum_variant_names)] #![allow(clippy::clone_on_copy)] // #![deny(variant_size_differences)] use serde::{Deserialize, Serialize}; use swc_common::{ast_node, EqIgnoreSpan, Span}; pub use self::{ class::{ Class, ClassMember, ClassMethod, ClassProp, Constructor, Decorator, MethodKind, PrivateMethod, PrivateProp, StaticBlock, }, decl::{ClassDecl, Decl, FnDecl, VarDecl, VarDeclKind, VarDeclarator}, expr::{ ArrayLit, ArrowExpr, AssignExpr, AwaitExpr, BinExpr, BlockStmtOrExpr, CallExpr, Callee, ClassExpr, CondExpr, Expr, ExprOrSpread, FnExpr, Import, MemberExpr, MemberProp, MetaPropExpr, MetaPropKind, NewExpr, ObjectLit, OptCall, OptChainBase, OptChainExpr, ParenExpr, PatOrExpr, PropOrSpread, SeqExpr, SpreadElement, Super, SuperProp, SuperPropExpr, TaggedTpl, ThisExpr, Tpl, TplElement, UnaryExpr, UpdateExpr, YieldExpr, }, function::{Function, Param, ParamOrTsParamProp}, ident::{BindingIdent, Id, Ident, IdentExt, PrivateName}, jsx::{ JSXAttr, JSXAttrName, JSXAttrOrSpread, JSXAttrValue, JSXClosingElement, JSXClosingFragment, JSXElement, JSXElementChild, JSXElementName, JSXEmptyExpr, JSXExpr, JSXExprContainer, JSXFragment, JSXMemberExpr, JSXNamespacedName, JSXObject, JSXOpeningElement, JSXOpeningFragment, JSXSpreadChild, JSXText, }, lit::{BigInt, Bool, Lit, Null, Number, Regex, Str}, module::{Module, ModuleItem, Program, Script}, module_decl::{ DefaultDecl, ExportAll, ExportDecl, ExportDefaultDecl, ExportDefaultExpr, ExportDefaultSpecifier, ExportNamedSpecifier, ExportNamespaceSpecifier, ExportSpecifier, ImportDecl, ImportDefaultSpecifier, ImportNamedSpecifier, ImportSpecifier, ImportStarAsSpecifier, ModuleDecl, ModuleExportName, NamedExport, }, operators::{AssignOp, BinaryOp, UnaryOp, UpdateOp}, pat::{ ArrayPat, AssignPat, AssignPatProp, KeyValuePatProp, ObjectPat, ObjectPatProp, Pat, RestPat, }, prop::{ AssignProp, ComputedPropName, GetterProp, KeyValueProp, MethodProp, Prop, PropName, SetterProp, }, stmt::{ BlockStmt, BreakStmt, CatchClause, ContinueStmt, DebuggerStmt, DoWhileStmt, EmptyStmt, ExprStmt, ForInStmt, ForOfStmt, ForStmt, IfStmt, LabeledStmt, ReturnStmt, Stmt, SwitchCase, SwitchStmt, ThrowStmt, TryStmt, VarDeclOrExpr, VarDeclOrPat, WhileStmt, WithStmt, }, typescript::{ Accessibility, TruePlusMinus, TsArrayType, TsAsExpr, TsCallSignatureDecl, TsConditionalType, TsConstAssertion, TsConstructSignatureDecl, TsConstructorType, TsEntityName, TsEnumDecl, TsEnumMember, TsEnumMemberId, TsExportAssignment, TsExprWithTypeArgs, TsExternalModuleRef, TsFnOrConstructorType, TsFnParam, TsFnType, TsGetterSignature, TsImportEqualsDecl, TsImportType, TsIndexSignature, TsIndexedAccessType, TsInferType, TsInstantiation, TsInterfaceBody, TsInterfaceDecl, TsIntersectionType, TsKeywordType, TsKeywordTypeKind, TsLit, TsLitType, TsMappedType, TsMemberName, TsMethodSignature, TsModuleBlock, TsModuleDecl, TsModuleName, TsModuleRef, TsNamespaceBody, TsNamespaceDecl, TsNamespaceExportDecl, TsNonNullExpr, TsOptionalType, TsParamProp, TsParamPropParam, TsParenthesizedType, TsPropertySignature, TsQualifiedName, TsRestType, TsSetterSignature, TsThisType, TsThisTypeOrIdent, TsTplLitType, TsTupleElement, TsTupleType, TsType, TsTypeAliasDecl, TsTypeAnn, TsTypeAssertion, TsTypeElement, TsTypeLit, TsTypeOperator, TsTypeOperatorOp, TsTypeParam, TsTypeParamDecl, TsTypeParamInstantiation, TsTypePredicate, TsTypeQuery, TsTypeQueryExpr, TsTypeRef, TsUnionOrIntersectionType, TsUnionType, }, }; #[macro_use] mod macros; mod class; mod decl; mod expr; mod function; mod ident; mod jsx; mod lit; mod module; mod module_decl; mod operators; mod pat; mod prop; mod stmt; mod typescript; /// Represents a invalid node. #[ast_node("Invalid")] #[derive(Eq, Hash, Copy, EqIgnoreSpan)] #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] pub struct Invalid { pub span: Span, } #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialOrd, Ord, PartialEq, Eq, Hash)] pub enum EsVersion { #[serde(rename = "es3")] Es3, #[serde(rename = "es5")] Es5, #[serde(rename = "es2015")] Es2015, #[serde(rename = "es2016")] Es2016, #[serde(rename = "es2017")] Es2017, #[serde(rename = "es2018")] Es2018, #[serde(rename = "es2019")] Es2019, #[serde(rename = "es2020")] Es2020, #[serde(rename = "es2021")] Es2021, #[serde(rename = "es2022")] Es2022, } impl EsVersion { /// Get the latest version. This is `es2022` for now, but it will be changed /// if a new version of specification is released. pub const fn latest() -> Self { EsVersion::Es2022 } } impl Default for EsVersion { fn default() -> Self { EsVersion::Es5 } } #[cfg(feature = "rkyv")] #[derive(Debug, Clone, Copy)] pub struct EncodeJsWord; #[cfg(feature = "rkyv")] impl rkyv::with::ArchiveWith<swc_atoms::JsWord> for EncodeJsWord { type Archived = rkyv::Archived<String>; type Resolver = rkyv::Resolver<String>; unsafe fn resolve_with( field: &swc_atoms::JsWord, pos: usize, resolver: Self::Resolver, out: *mut Self::Archived, ) { use rkyv::Archive; let s = field.to_string(); s.resolve(pos, resolver, out); } } #[cfg(feature = "rkyv")] impl<S> rkyv::with::SerializeWith<swc_atoms::JsWord, S> for EncodeJsWord where S: ?Sized + rkyv::ser::Serializer, { fn serialize_with( field: &swc_atoms::JsWord, serializer: &mut S, ) -> Result<Self::Resolver, S::Error> { rkyv::string::ArchivedString::serialize_from_str(field, serializer) } } #[cfg(feature = "rkyv")] impl<D> rkyv::with::DeserializeWith<rkyv::Archived<String>, swc_atoms::JsWord, D> for EncodeJsWord where D: ?Sized + rkyv::Fallible, { fn deserialize_with( field: &rkyv::Archived<String>, deserializer: &mut D, ) -> Result<swc_atoms::JsWord, D::Error> { use rkyv::Deserialize; let s: String = field.deserialize(deserializer)?; Ok(s.into()) } } #[cfg(feature = "rkyv")] impl rkyv::with::ArchiveWith<Option<swc_atoms::JsWord>> for EncodeJsWord { type Archived = rkyv::Archived<Option<String>>; type Resolver = rkyv::Resolver<Option<String>>; unsafe fn resolve_with( field: &Option<swc_atoms::JsWord>, pos: usize, resolver: Self::Resolver, out: *mut Self::Archived, ) { use rkyv::Archive; let s = field.as_ref().map(|s| s.to_string()); s.resolve(pos, resolver, out); } } #[cfg(feature = "rkyv")] impl<S> rkyv::with::SerializeWith<Option<swc_atoms::JsWord>, S> for EncodeJsWord where S: ?Sized + rkyv::ser::Serializer, { fn serialize_with( value: &Option<swc_atoms::JsWord>, serializer: &mut S, ) -> Result<Self::Resolver, S::Error> { value .as_ref() .map(|value| rkyv::string::ArchivedString::serialize_from_str(value, serializer)) .transpose() } } #[cfg(feature = "rkyv")] impl<D> rkyv::with::DeserializeWith<rkyv::Archived<Option<String>>, Option<swc_atoms::JsWord>, D> for EncodeJsWord where D: ?Sized + rkyv::Fallible, { fn deserialize_with( field: &rkyv::Archived<Option<String>>, deserializer: &mut D, ) -> Result<Option<swc_atoms::JsWord>, D::Error> { use rkyv::Deserialize; let s: Option<String> = field.deserialize(deserializer)?; Ok(s.map(|s| s.into())) } }
28,964
https://github.com/shubh24/MfoPaper/blob/master/code/MFO/new/main.m
Github Open Source
Open Source
BSD-2-Clause
2,016
MfoPaper
shubh24
MATLAB
Code
47
140
clear all clc SearchAgents_no=30; % Number of search agents Max_iteration=1500; % Maximum numbef of iterations [ess dat] = file("../../data/ks_100_0"); [Best_score,Best_pos,cg_curve]=MFO1(SearchAgents_no,Max_iteration, ess, dat); display(['The best solution obtained by MFO is : ', num2str(Best_pos)]); display(['The best optimal value of the objective funciton found by MFO is : ', num2str(Best_score)]);
34,384
https://github.com/Nebulis/blog/blob/master/src/pages/asia/malaysia/east-malaysia/semenggoh-nature-reserve.tsx
Github Open Source
Open Source
MIT
null
blog
Nebulis
TypeScript
Code
854
5,354
import React, { useContext } from "react" import { PageProps } from "gatsby" import i18n from "i18next" import SEO from "../../../../components/layout/seo" import { useCustomTranslation } from "../../../../i18n-hook" import { Comments } from "../../../../components/core/comments" import translationFr from "../../../../locales/fr/asia/malaysia/east-malaysia/semenggoh-nature-reserve.json" import translationEn from "../../../../locales/en/asia/malaysia/east-malaysia/semenggoh-nature-reserve.json" import { MalaysiaBlogLayout, MalaysiaHeadline, malaysiaPrice } from "../../../../components/core/asia/malaysia/malaysia" import { Booking, How, HowMuch, Introduction, SectionContent, Visit, WhatTimeOfYear, When, Where, } from "../../../../components/core/section" import { Conclusion } from "../../../../components/core/conclusion" import { Divider } from "../../../../components/core/divider" import { Quote } from "../../../../components/core/quote" import HomeImgUrl from "../../../../images/asia/malaysia/east-malaysia/semenggoh-nature-reserve/semenggoh-nature-reserve-main.jpg" import SemenggohMap from "../../../../images/asia/malaysia/east-malaysia/semenggoh-nature-reserve/semenggoh-nature-reserve-map.jpg" import { Title } from "../../../../components/core/title" import { GroupOfImages, ImageAsLandscape, ImageAsPortrait, TwoImagesSameSizeOrToGroup, } from "../../../../components/images/layout" import { SharedCardMalaysiaImages } from "../../../../components/images/asia/malaysia/shared-card-malaysia-images" import { MapContainer, Table } from "../../../../components/layout/layout" import { css } from "@emotion/react" import { malaysiaPrimaryColor } from "../../../../components/core/asia/malaysia/malaysia.variables" import { SemenggohNatureReserveImages } from "../../../../components/images/asia/malaysia/east-malaysia/semenggoh-nature-reserve" import { getLink } from "../../../../components/core/links/links.utils" import { ApplicationContext } from "../../../../components/application" const namespace = "asia/malaysia/east-malaysia/semenggoh-nature-reserve" const id = "semenggoh-nature-reserve" i18n.addResourceBundle("fr", namespace, translationFr) i18n.addResourceBundle("en", namespace, translationEn) const IndexPage: React.FunctionComponent<PageProps> = ({ location }) => { const { development } = useContext(ApplicationContext) const { t, i18n } = useCustomTranslation([namespace, "common"]) const title = t(`common:country.malaysia.card.${id}`) const orangutanLinkPublished = development || getLink("orangutan").published const malaysiaPriceWithLang = malaysiaPrice(i18n.languageCode) return ( <> <SEO title={title} fullTitle={t("full-title")} socialNetworkDescription={t("social-network-description")} googleDescription={t("google-description")} image={HomeImgUrl} location={location} /> <MalaysiaBlogLayout page={id} location={location}> <Title title={title} linkId={id} /> <ImageAsLandscape> <SharedCardMalaysiaImages image="semenggohNatureReserve" /> </ImageAsLandscape> <Quote>{t("quote")}</Quote> <Divider /> <Introduction>{t("introduction")}</Introduction> <Divider /> <Where title={t("where.title")}> <p>{t("where.part1")}</p> </Where> <How title={t("how.title")}> <p>{t("how.part1")}</p> <p>{t("how.part2")}</p> <p>{t("how.part3")}</p> </How> <When title={t("when.title")}> <p>{t("when.part1")}</p> <p>{t("when.part2")}</p> <p>{t("when.part3")}</p> <p>{t("when.part4")}</p> <p>{t("when.part5")}</p> </When> <WhatTimeOfYear title={t("what-time-of-year.title")}> <p>{t("what-time-of-year.part1")}</p> <p>{t("what-time-of-year.part2")}</p> <p>{t("what-time-of-year.part3")}</p> <p>{t("what-time-of-year.part4")}</p> </WhatTimeOfYear> <HowMuch title={t("how-much.title")}> <p>{t("how-much.part1")}</p> <Table className="mb3"> <thead> <tr> <th>{i18n.languageCode === "fr" ? "Catégorie" : "Category"}</th> <th>{i18n.languageCode === "fr" ? "Étranger" : "Foreigner"}</th> <th>Local</th> </tr> </thead> <tbody> <tr> <td>{i18n.languageCode === "fr" ? "Adulte" : "Adult"}</td> <td>{malaysiaPriceWithLang(10)}</td> <td>{malaysiaPriceWithLang(5)}</td> </tr> <tr> <td>{i18n.languageCode === "fr" ? "Retraité" : "Senior Citizen"}</td> <td>{malaysiaPriceWithLang(10)}</td> <td>{malaysiaPriceWithLang(3)}</td> </tr> <tr> <td>{i18n.languageCode === "fr" ? "Personne Handicapée" : "Disabled person"}</td> <td>{malaysiaPriceWithLang(5)}</td> <td>{malaysiaPriceWithLang(3)}</td> </tr> <tr> <td>{i18n.languageCode === "fr" ? "Enfant (6-7 ans)" : "Children (6-7 years old)"}</td> <td>{malaysiaPriceWithLang(5)}</td> <td>{malaysiaPriceWithLang(2)}</td> </tr> <tr> <td>{i18n.languageCode === "fr" ? "Enfant (moins de 6 ans)" : "Children ( below 6 years old)"}</td> <td>{i18n.languageCode === "fr" ? "Gratuit" : "Free"}</td> <td>{i18n.languageCode === "fr" ? "Gratuit" : "Free"}</td> </tr> </tbody> </Table> </HowMuch> <Booking title={t("where-to-book.title")}> <p>{t("where-to-book.part1")}</p> </Booking> <Visit title={t("visit.title")}> {/* just to have the correct space*/} <SectionContent /> <Divider /> <section> <MalaysiaHeadline>{t("visit1.title")}</MalaysiaHeadline> <Divider /> <SectionContent> <p>{t("visit1.part1")}</p> <ImageAsLandscape> <SemenggohNatureReserveImages image="history" /> </ImageAsLandscape> <p>{t("visit1.part2")}</p> <p>{t("visit1.part3")}</p> <ul> <li>{t("visit1.part4")}</li> <li>{t("visit1.part5")}</li> <li>{t("visit1.part6")}</li> </ul> <p>{t("visit1.part7")}</p> <p>{t("visit1.part8")}</p> <ImageAsPortrait> <SemenggohNatureReserveImages image="history2" /> </ImageAsPortrait> <p>{t("visit1.part9")}</p> <p>{t("visit1.part10")}</p> <p>{t("visit1.part11")}</p> <p>{t("visit1.part12")}</p> <MapContainer css={css` max-width: 500px; margin-left: auto; margin-right: auto; `} > <img src={SemenggohMap} alt="Map of Semenggoh Nature Reserve" /> </MapContainer> </SectionContent> </section> <Divider /> <section> <MalaysiaHeadline>{t("visit2.title")}</MalaysiaHeadline> <Divider /> <SectionContent> <p>{t("visit2.part1")}</p> <p>{t("visit2.part2")}</p> <TwoImagesSameSizeOrToGroup> <SemenggohNatureReserveImages image="briefing" /> <SemenggohNatureReserveImages image="briefing2" /> </TwoImagesSameSizeOrToGroup> <p>{t("visit2.part3")}</p> <p>{t("visit2.part4")}</p> <p>{t("visit2.part5")}</p> <p className="i tc" css={css` color: ${malaysiaPrimaryColor}; `} > {t("visit2.part6")} </p> <p>{t("visit2.part7")}</p> <p>{t("visit2.part8")}</p> <GroupOfImages> <TwoImagesSameSizeOrToGroup css={css` max-width: 900px; `} > <SemenggohNatureReserveImages image="briefing3" imgStyle={{ objectFit: "contain" }} /> <SemenggohNatureReserveImages image="briefing4" imgStyle={{ objectFit: "contain" }} /> </TwoImagesSameSizeOrToGroup> <TwoImagesSameSizeOrToGroup css={css` max-width: 900px; `} > <SemenggohNatureReserveImages image="briefing5" imgStyle={{ objectFit: "contain" }} /> <SemenggohNatureReserveImages image="briefing6" imgStyle={{ objectFit: "contain" }} /> </TwoImagesSameSizeOrToGroup> <TwoImagesSameSizeOrToGroup css={css` max-width: 900px; `} > <SemenggohNatureReserveImages image="briefing7" imgStyle={{ objectFit: "contain" }} /> <SemenggohNatureReserveImages image="briefing8" imgStyle={{ objectFit: "contain" }} /> </TwoImagesSameSizeOrToGroup> <ImageAsLandscape> <SemenggohNatureReserveImages image="briefing9" /> </ImageAsLandscape> <ImageAsPortrait> <SemenggohNatureReserveImages image="briefing10" /> </ImageAsPortrait> <TwoImagesSameSizeOrToGroup> <SemenggohNatureReserveImages image="briefing11" /> <SemenggohNatureReserveImages image="briefing12" /> </TwoImagesSameSizeOrToGroup> <ImageAsLandscape> <SemenggohNatureReserveImages image="briefing13" /> </ImageAsLandscape> <ImageAsLandscape> <SemenggohNatureReserveImages image="briefing14" /> </ImageAsLandscape> </GroupOfImages> <p>{t("visit2.part9")}</p> </SectionContent> </section> <Divider /> <section> <MalaysiaHeadline>{t("visit3.title")}</MalaysiaHeadline> <Divider /> <SectionContent> <p>{t("visit3.part1")}</p> <p>{t("visit3.part2")}</p> <p>{t("visit3.part3")}</p> <p>{t("visit3.part4")}</p> <p>{t("visit3.part5")}</p> <p>{t("visit3.part6")}</p> <p>{t("visit3.part7")}</p> </SectionContent> </section> <Divider /> <section> <MalaysiaHeadline>{t("visit4.title")}</MalaysiaHeadline> <Divider /> <SectionContent> <p>{t("visit4.part1")}</p> <p>{t("visit4.part2")}</p> <ImageAsPortrait> <SemenggohNatureReserveImages image="feeding" /> </ImageAsPortrait> <p>{t("visit4.part3")}</p> <p>{t("visit4.part4")}</p> <p>{t("visit4.part5")}</p> <p>{t("visit4.part6")}</p> <p>{t("visit4.part7")}</p> <p>{t("visit4.part8")}</p> <p>{t("visit4.part9")}</p> <p>{t("visit4.part10")}</p> <GroupOfImages> <ImageAsLandscape> <SemenggohNatureReserveImages image="feeding2" /> </ImageAsLandscape> <ImageAsLandscape> <SemenggohNatureReserveImages image="feeding3" /> </ImageAsLandscape> <ImageAsLandscape> <SemenggohNatureReserveImages image="feeding4" /> </ImageAsLandscape> <ImageAsLandscape> <SemenggohNatureReserveImages image="feeding5" /> </ImageAsLandscape> <ImageAsLandscape> <SemenggohNatureReserveImages image="feeding19" /> </ImageAsLandscape> </GroupOfImages> <p>{t("visit4.part11")}</p> <p>{t("visit4.part12")}</p> <p>{t("visit4.part13")}</p> <p>{t("visit4.part14")}</p> <GroupOfImages> <ImageAsLandscape> <SemenggohNatureReserveImages image="feeding6" /> </ImageAsLandscape> <ImageAsLandscape> <SemenggohNatureReserveImages image="feeding7" /> </ImageAsLandscape> <ImageAsLandscape> <SemenggohNatureReserveImages image="feeding8" /> </ImageAsLandscape> <ImageAsLandscape> <SemenggohNatureReserveImages image="feeding9" /> </ImageAsLandscape> <ImageAsLandscape> <SemenggohNatureReserveImages image="feeding10" /> </ImageAsLandscape> <ImageAsLandscape> <SemenggohNatureReserveImages image="feeding11" /> </ImageAsLandscape> <ImageAsLandscape> <SemenggohNatureReserveImages image="feeding12" /> </ImageAsLandscape> </GroupOfImages> <p>{t("visit4.part15")}</p> <GroupOfImages> <ImageAsLandscape> <SemenggohNatureReserveImages image="feeding13" /> </ImageAsLandscape> <ImageAsLandscape> <SemenggohNatureReserveImages image="feeding14" /> </ImageAsLandscape> <ImageAsLandscape> <SemenggohNatureReserveImages image="feeding15" /> </ImageAsLandscape> <ImageAsLandscape> <SemenggohNatureReserveImages image="feeding16" /> </ImageAsLandscape> <ImageAsLandscape> <SemenggohNatureReserveImages image="feeding17" /> </ImageAsLandscape> <ImageAsLandscape> <SemenggohNatureReserveImages image="feeding18" /> </ImageAsLandscape> <ImageAsLandscape> <SemenggohNatureReserveImages image="feeding20" /> </ImageAsLandscape> <ImageAsLandscape> <SemenggohNatureReserveImages image="feeding21" /> </ImageAsLandscape> </GroupOfImages> <p>{t("visit4.part16")}</p> <p>{t("visit4.part17")}</p> </SectionContent> </section> <Divider /> <section> <MalaysiaHeadline>{t("visit5.title")}</MalaysiaHeadline> <Divider /> <SectionContent> <p>{t("visit5.part1")}</p> <p>{t("visit5.part2")}</p> <p>{t("visit5.part3")}</p> <p>{t("visit5.part4")}</p> <p>{t("visit5.part5")}</p> <p>{t("visit5.part6")}</p> <p>{t("visit5.part7")}</p> <GroupOfImages> <ImageAsLandscape> <SemenggohNatureReserveImages image="family" /> </ImageAsLandscape> <ImageAsLandscape> <SemenggohNatureReserveImages image="family2" /> </ImageAsLandscape> <ImageAsLandscape> <SemenggohNatureReserveImages image="family3" /> </ImageAsLandscape> </GroupOfImages> <p>{t("visit5.part8")}</p> <p>{t("visit5.part9")}</p> </SectionContent> </section> <Divider /> <section> <MalaysiaHeadline>{t("visit6.title")}</MalaysiaHeadline> <Divider /> <SectionContent> <p>{t("visit6.part1")}</p> <p>{t("visit6.part2")}</p> <p>{t("visit6.part3")}</p> {orangutanLinkPublished && <p>{t("visit6.part4")}</p>} <p>{t("visit6.part5")}</p> <TwoImagesSameSizeOrToGroup title1={i18n.languageCode === "fr" ? "Mme Magic" : "Mrs. Magic"} title2={i18n.languageCode === "fr" ? "Mr Magic" : "Mr. Magic"} titleClassName="tc" > <SemenggohNatureReserveImages image="bonus" imgStyle={{ objectFit: "contain" }} /> <SemenggohNatureReserveImages image="bonus2" imgStyle={{ objectFit: "contain" }} /> </TwoImagesSameSizeOrToGroup> </SectionContent> </section> </Visit> <Divider /> <Conclusion> <p>{t("conclusion")}</p> <ul> <li>{t("question1")}</li> <li>{t("question2")}</li> </ul> <p>{t("love")}</p> </Conclusion> <Divider /> <Comments collectionName={namespace} location={location} facebookQuote={`${t("facebook.part1")}\n${t("facebook.part2")}`} pinterest={{ description: t("pinterest"), nodes: i18n.languageCode === "fr" ? [ <SemenggohNatureReserveImages image="cardFr1" key="cardFr1" />, <SemenggohNatureReserveImages image="cardFr2" key="cardFr1" />, ] : [ <SemenggohNatureReserveImages image="cardEn1" key="cardEn1" />, <SemenggohNatureReserveImages image="cardEn2" key="cardEn1" />, ], }} /> </MalaysiaBlogLayout> </> ) } export default IndexPage
30,674
https://github.com/mirunakyuz/ojs/blob/master/src/Ojs/UserBundle/OAuth/ResourceOwner/GenericOAuth2ResourceOwner.php
Github Open Source
Open Source
MIT
null
ojs
mirunakyuz
PHP
Code
59
280
<?php namespace Ojs\UserBundle\OAuth\ResourceOwner; use HWI\Bundle\OAuthBundle\OAuth\ResourceOwner\GenericOAuth2ResourceOwner as BaseClass; use HWI\Bundle\OAuthBundle\Security\Core\Authentication\Token\OAuthToken; use Ojs\CoreBundle\Service\OrcidService; class GenericOAuth2ResourceOwner extends BaseClass { /** * Override for Orcid * * {@inheritDoc} */ public function getUserInformation(array $accessToken, array $extraParameters = array()) { if(!array_key_exists('orcid', $accessToken)) { return parent::getUserInformation($accessToken, $extraParameters); } $orcidService = new OrcidService(); $bio = $orcidService->getBio($accessToken["orcid"]); $response = $this->getUserResponse(); $response->setResponse($bio); $response->setResourceOwner($this); $response->setOAuthToken(new OAuthToken($accessToken)); return $response; } }
39,157
https://github.com/bbakernoaa/eccodes/blob/master/examples/F90/bufr_expanded.f90
Github Open Source
Open Source
Apache-2.0
2,021
eccodes
bbakernoaa
Fortran Free Form
Code
208
544
! (C) Copyright 2005- ECMWF. ! ! This software is licensed under the terms of the Apache Licence Version 2.0 ! which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. ! ! In applying this licence, ECMWF does not waive the privileges and immunities granted to it by ! virtue of its status as an intergovernmental organisation nor does it submit to any jurisdiction. ! ! ! FORTRAN 90 Implementation: bufr_expanded ! ! Description: how to read all the expanded data values from BUFR messages. ! ! program bufr_expanded use eccodes implicit none integer :: ifile integer :: iret integer :: ibufr integer :: i integer :: count=0 integer(kind=4) :: numberOfValues real(kind=8), dimension(:), allocatable :: values call codes_open_file(ifile,'../../data/bufr/syno_1.bufr','r') ! The first bufr message is loaded from file, ! ibufr is the bufr id to be used in subsequent calls call codes_bufr_new_from_file(ifile,ibufr,iret) do while (iret/=CODES_END_OF_FILE) write(*,*) 'message: ',count ! We need to instruct ecCodes to expand all the descriptors ! i.e. unpack the data values call codes_set(ibufr,"unpack",1); ! Get the expanded data values call codes_get(ibufr,'numericValues',values) numberOfValues=size(values) do i=1,numberOfValues write(*,*) ' ',i,values(i) enddo ! Release the bufr message call codes_release(ibufr) ! Load the next bufr message call codes_bufr_new_from_file(ifile,ibufr,iret) ! Free array deallocate(values) count=count+1 end do ! Close file call codes_close_file(ifile) end program bufr_expanded
27,077
https://github.com/leereilly/unreal.hx/blob/master/Haxe/Externs/unreal/USoundNodeOscillator.hx
Github Open Source
Open Source
MIT
2,016
unreal.hx
leereilly
Haxe
Code
314
689
/** * * WARNING! This file was autogenerated by: * _ _ _____ ___ _ _ __ __ * | | | | ___| / | | | | |\ \ / / * | | | | |__ / /| | | |_| | \ V / * | | | | __| / /_| | | _ | / \ * | |_| | |___ \___ | | | | |/ /^\ \ * \___/\____/ |_/ \_| |_/\/ \/ * * This file was autogenerated by UE4HaxeExternGenerator using UHT definitions. It only includes UPROPERTYs and UFUNCTIONs. Do not modify it! * In order to add more definitions, create or edit a type with the same name/package, but with an `_Extra` suffix **/ package unreal; /** WARNING: This type was not defined as DLL export on its declaration. Because of that, its properties/methods are inaccessible Defines how a sound oscillates **/ @:glueCppIncludes("Sound/SoundNodeOscillator.h") @:noClass @:uextern extern class USoundNodeOscillator extends unreal.USoundNode { /** A center of 0.5 would oscillate around 0.5. **/ public var CenterMax : unreal.Float32; /** A center of 0.5 would oscillate around 0.5. **/ public var CenterMin : unreal.Float32; /** Offset into the sine wave. Value modded by 2 * PI. **/ public var OffsetMax : unreal.Float32; /** Offset into the sine wave. Value modded by 2 * PI. **/ public var OffsetMin : unreal.Float32; /** A frequency of 20 would oscillate at 10Hz. **/ public var FrequencyMax : unreal.Float32; /** A frequency of 20 would oscillate at 10Hz. **/ public var FrequencyMin : unreal.Float32; /** An amplitude of 0.25 would oscillate between 0.75 and 1.25. **/ public var AmplitudeMax : unreal.Float32; /** An amplitude of 0.25 would oscillate between 0.75 and 1.25. **/ public var AmplitudeMin : unreal.Float32; /** Whether to oscillate pitch. **/ public var bModulatePitch : Bool; /** Whether to oscillate volume. **/ public var bModulateVolume : Bool; }
41,395
https://github.com/mubaidr/prisma-nestjs-graphql/blob/master/@generated/tag/tag-unchecked-create.input.ts
Github Open Source
Open Source
MIT
null
prisma-nestjs-graphql
mubaidr
TypeScript
Code
52
171
import { Field } from '@nestjs/graphql'; import { InputType } from '@nestjs/graphql'; import { ArticleUncheckedCreateNestedManyWithoutTagsInput } from '../article/article-unchecked-create-nested-many-without-tags.input'; @InputType() export class TagUncheckedCreateInput { @Field(() => String, { nullable: true }) id?: string; @Field(() => String, { nullable: fals e }) name!: string; @Field(() => ArticleUncheckedCreateNestedManyWithoutTagsInput, { nullable: true }) articles?: ArticleUncheckedCreateNestedManyWithoutTagsInput; }
11,323
https://github.com/anayarojo/ionic-movies/blob/master/src/app/pipes/image-filter.pipe.ts
Github Open Source
Open Source
MIT
null
ionic-movies
anayarojo
TypeScript
Code
30
88
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'imageFilter' }) export class ImageFilterPipe implements PipeTransform { transform(movies: any[]): any[] { return movies.filter(m => { return m.backdrop_path; }); } }
9,238
https://github.com/gtfierro/reasonable/blob/master/benches/python/buildings/AMRL(v1.1).ttl
Github Open Source
Open Source
BSD-3-Clause
2,022
reasonable
gtfierro
Turtle
Code
1,005
7,159
@prefix bf: <https://brickschema.org/schema/1.0.2/BrickFrame#> . @prefix bldg: <http://buildsys.org/ontologies/AMRL#> . @prefix brick: <https://brickschema.org/schema/1.0.2/Brick#> . @prefix brick1: <https://brickschema.org/schema/1.1/Brick#> . @prefix brick_v_1_0_2: <https://brickschema.org/schema/1.0.2/Brick#> . @prefix brickframe: <https://brickschema.org/schema/1.0.2/BrickFrame#> . @prefix btag: <https://brickschema.org/schema/1.0.2/BrickTag#> . @prefix owl: <http://www.w3.org/2002/07/owl#> . @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> . @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . @prefix tag: <https://brickschema.org/schema/1.1/BrickTag#> . @prefix xml: <http://www.w3.org/XML/1998/namespace> . @prefix xsd: <http://www.w3.org/2001/XMLSchema#> . bldg:AHU01 a brick1:Air_Handler_Unit ; brickframe:hasSite bldg:AMRL ; brick1:feeds bldg:VAVRM1100C, bldg:VAVRM1115, bldg:VAVRM1119, bldg:VAVRM1120, bldg:VAVRM1123, bldg:VAVRM1126, bldg:VAVRM1127, bldg:VAVRM1128 ; brick1:hasPoint bldg:AMRL.AHU.AHU01.Heating_Valve_Output, bldg:AMRL.AHU.AHU01.Outside_Air_Temp, bldg:AMRL.AHU.AHU01.Outside_Air_Temp_Virtual, bldg:AMRL.AHU.AHU01.Supply_Air_Temp, bldg:AMRL.AHU.AHU01.Supply_Air_Temp_Setpoint . bldg:floor1 a brick1:Floor ; brickframe:hasSite bldg:AMRL ; brick1:hasPart bldg:RM1100C_room, bldg:RM1115_room, bldg:RM1119_room, bldg:RM1120_room, bldg:RM1123_room, bldg:RM1126_room, bldg:RM1127_room, bldg:RM1128_room . brick_v_1_0_2:Ambient_Illumination_Sensor a owl:Class ; rdfs:subClassOf brick_v_1_0_2:Illumination_Sensor . brick_v_1_0_2:Green_Button_Meter a owl:Class ; rdfs:subClassOf brick_v_1_0_2:Building_Electric_Meter . brick_v_1_0_2:PlugStrip a owl:Class ; rdfs:subClassOf brick1:Equipment . brick_v_1_0_2:RTU a owl:Class ; rdfs:subClassOf brick1:AHU . brick_v_1_0_2:Thermostat_Mode_Command a owl:Class ; rdfs:subClassOf brick1:Command . brick_v_1_0_2:Thermostat_Status a owl:Class ; rdfs:subClassOf brick1:Status . brickframe:areaSquareFeet a owl:ObjectProperty ; rdfs:range brickframe:Label . brickframe:areaSquareMeters a owl:ObjectProperty ; rdfs:range brickframe:Label . brickframe:humanName a owl:ObjectProperty ; rdfs:range brickframe:Label . brickframe:isSiteOf a owl:ObjectProperty ; rdfs:domain brick_v_1_0_2:Site ; owl:inverseOf brickframe:hasSite . brickframe:numFloors a owl:ObjectProperty ; rdfs:range brickframe:Label . brickframe:primaryFunction a owl:ObjectProperty ; rdfs:range brickframe:Label . brickframe:timezone a owl:ObjectProperty ; rdfs:range brickframe:Label . brickframe:zipCode a owl:ObjectProperty ; rdfs:range brickframe:Label . bldg:AMRL.AHU.AHU01.Heating_Valve_Output a brick1:Command ; brickframe:hasSite bldg:AMRL ; brickframe:pointname "AMRL.AHU.AHU01.Heating Valve Output" ; brickframe:uuid "0c31ab88-2c96-3f58-8a9d-79fe0d856fa9" . bldg:AMRL.AHU.AHU01.Outside_Air_Temp a brick1:Outside_Air_Temperature_Sensor ; brickframe:hasSite bldg:AMRL ; brickframe:pointname "AMRL.AHU.AHU01.Outside Air Temp" ; brickframe:uuid "3a17f7d8-4913-30a6-b576-0b5c34ae0273" . bldg:AMRL.AHU.AHU01.Outside_Air_Temp_Virtual a brick1:Outside_Air_Temperature_Sensor ; brickframe:hasSite bldg:AMRL ; brickframe:pointname "AMRL.AHU.AHU01.Outside Air Temp Virtual" ; brickframe:uuid "76b07c5e-f417-307f-98e4-007d61e74ccc" . bldg:AMRL.AHU.AHU01.Supply_Air_Temp a brick1:Supply_Air_Temperature_Sensor ; brickframe:hasSite bldg:AMRL ; brickframe:pointname "AMRL.AHU.AHU01.Supply Air Temp" ; brickframe:uuid "0891f710-7917-3abb-ad0a-1f7e39113401" . bldg:AMRL.AHU.AHU01.Supply_Air_Temp_Setpoint a brick_v_1_0_2:Supply_Air_Temperature_Setpoint ; brickframe:hasSite bldg:AMRL ; brickframe:pointname "AMRL.AHU.AHU01.Supply Air Temp Setpoint" ; brickframe:uuid "08336cd2-24aa-32bc-b6da-a4ec1bb00136" . bldg:AMRL.ZONE.AHU01.RM1100C.Day_Night_Mode a brick_v_1_0_2:Mode ; brickframe:pointname "AMRL.ZONE.AHU01.RM1100C.Day Night Mode" ; brickframe:uuid "f80bc9f8-aaf6-310c-a8f1-d3eb24ff08b1" . bldg:AMRL.ZONE.AHU01.RM1100C.Heating_Mode a brick1:Heating_Command ; brickframe:hasSite bldg:AMRL ; brickframe:pointname "AMRL.ZONE.AHU01.RM1100C.Heating Mode" ; brickframe:uuid "8ee86b42-50bf-33e5-974c-15599ef6675c" . bldg:AMRL.ZONE.AHU01.RM1100C.Zone_Air_Temp a brick1:Zone_Air_Temperature_Sensor ; brickframe:hasSite bldg:AMRL ; brickframe:pointname "AMRL.ZONE.AHU01.RM1100C.Zone Air Temp" ; brickframe:uuid "138db62b-9cf2-31b5-9564-e47a5850376d" . bldg:AMRL.ZONE.AHU01.RM1100C.Zone_Air_Temp_Setpoint a brick_v_1_0_2:Zone_Air_Temperature_Setpoint ; brickframe:pointname "AMRL.ZONE.AHU01.RM1100C.Zone Air Temp Setpoint" ; brickframe:uuid "e51c2ab4-ae08-3f8c-aafd-ec2cc1d0907c" . bldg:AMRL.ZONE.AHU01.RM1115.Day_Night_Mode a brick_v_1_0_2:Mode ; brickframe:pointname "AMRL.ZONE.AHU01.RM1115.Day Night Mode" ; brickframe:uuid "604760f0-95b7-36ef-9189-bade46ad42d3" . bldg:AMRL.ZONE.AHU01.RM1115.Heating_Mode a brick1:Heating_Command ; brickframe:hasSite bldg:AMRL ; brickframe:pointname "AMRL.ZONE.AHU01.RM1115.Heating Mode" ; brickframe:uuid "a82719bc-4e8d-3d82-a648-c7e3ba25d559" . bldg:AMRL.ZONE.AHU01.RM1115.Zone_Air_Temp a brick1:Zone_Air_Temperature_Sensor ; brickframe:hasSite bldg:AMRL ; brickframe:pointname "AMRL.ZONE.AHU01.RM1115.Zone Air Temp" ; brickframe:uuid "b07a7bba-246b-3e4e-a35d-96636fdca680" . bldg:AMRL.ZONE.AHU01.RM1115.Zone_Air_Temp_Setpoint a brick_v_1_0_2:Zone_Air_Temperature_Setpoint ; brickframe:pointname "AMRL.ZONE.AHU01.RM1115.Zone Air Temp Setpoint" ; brickframe:uuid "9ff36e8a-a4a5-33ab-a8db-9671138178f4" . bldg:AMRL.ZONE.AHU01.RM1119.Day_Night_Mode a brick_v_1_0_2:Mode ; brickframe:pointname "AMRL.ZONE.AHU01.RM1119.Day Night Mode" ; brickframe:uuid "ee9c9bef-9e45-3da7-a07b-11c7359c91b2" . bldg:AMRL.ZONE.AHU01.RM1119.Heating_Mode a brick1:Heating_Command ; brickframe:hasSite bldg:AMRL ; brickframe:pointname "AMRL.ZONE.AHU01.RM1119.Heating Mode" ; brickframe:uuid "da712660-64fe-3cc3-8167-4a1a74845885" . bldg:AMRL.ZONE.AHU01.RM1119.Zone_Air_Temp a brick1:Zone_Air_Temperature_Sensor ; brickframe:hasSite bldg:AMRL ; brickframe:pointname "AMRL.ZONE.AHU01.RM1119.Zone Air Temp" ; brickframe:uuid "932b9d63-5607-374a-bb6a-1e5d8b6f2f8e" . bldg:AMRL.ZONE.AHU01.RM1119.Zone_Air_Temp_Setpoint a brick_v_1_0_2:Zone_Air_Temperature_Setpoint ; brickframe:pointname "AMRL.ZONE.AHU01.RM1119.Zone Air Temp Setpoint" ; brickframe:uuid "b2e05176-81d7-3361-95b8-82be82b1bee4" . bldg:AMRL.ZONE.AHU01.RM1120.Day_Night_Mode a brick_v_1_0_2:Mode ; brickframe:pointname "AMRL.ZONE.AHU01.RM1120.Day Night Mode" ; brickframe:uuid "70e0144b-c81a-3348-b1ad-e991e567837b" . bldg:AMRL.ZONE.AHU01.RM1120.Heating_Mode a brick1:Heating_Command ; brickframe:hasSite bldg:AMRL ; brickframe:pointname "AMRL.ZONE.AHU01.RM1120.Heating Mode" ; brickframe:uuid "72fe5c8e-32a6-30c1-9e24-f525c70c956a" . bldg:AMRL.ZONE.AHU01.RM1120.Zone_Air_Temp a brick1:Zone_Air_Temperature_Sensor ; brickframe:hasSite bldg:AMRL ; brickframe:pointname "AMRL.ZONE.AHU01.RM1120.Zone Air Temp" ; brickframe:uuid "9b591dea-1755-3db9-bc50-9b5bf56d21e7" . bldg:AMRL.ZONE.AHU01.RM1120.Zone_Air_Temp_Setpoint a brick_v_1_0_2:Zone_Air_Temperature_Setpoint ; brickframe:pointname "AMRL.ZONE.AHU01.RM1120.Zone Air Temp Setpoint" ; brickframe:uuid "9d342f5b-eff0-33ba-b41f-6f6dcb959761" . bldg:AMRL.ZONE.AHU01.RM1123.Day_Night_Mode a brick_v_1_0_2:Mode ; brickframe:pointname "AMRL.ZONE.AHU01.RM1123.Day Night Mode" ; brickframe:uuid "ed169917-6aea-3c7b-82b6-2eab057b7c2a" . bldg:AMRL.ZONE.AHU01.RM1123.Heating_Mode a brick1:Heating_Command ; brickframe:hasSite bldg:AMRL ; brickframe:pointname "AMRL.ZONE.AHU01.RM1123.Heating Mode" ; brickframe:uuid "0fcff82c-6b09-3ff4-97ba-e0e0fac689ad" . bldg:AMRL.ZONE.AHU01.RM1123.Zone_Air_Temp a brick1:Zone_Air_Temperature_Sensor ; brickframe:hasSite bldg:AMRL ; brickframe:pointname "AMRL.ZONE.AHU01.RM1123.Zone Air Temp" ; brickframe:uuid "dd6ebd3a-1323-3aab-b29b-1dcadbe3f482" . bldg:AMRL.ZONE.AHU01.RM1123.Zone_Air_Temp_Setpoint a brick_v_1_0_2:Zone_Air_Temperature_Setpoint ; brickframe:pointname "AMRL.ZONE.AHU01.RM1123.Zone Air Temp Setpoint" ; brickframe:uuid "8692bd53-c092-3353-9764-06acad02ceaa" . bldg:AMRL.ZONE.AHU01.RM1126.Day_Night_Mode a brick_v_1_0_2:Mode ; brickframe:pointname "AMRL.ZONE.AHU01.RM1126.Day Night Mode" ; brickframe:uuid "1651c7a2-c726-39ee-8ba4-68ab7d643410" . bldg:AMRL.ZONE.AHU01.RM1126.Heating_Mode a brick1:Heating_Command ; brickframe:hasSite bldg:AMRL ; brickframe:pointname "AMRL.ZONE.AHU01.RM1126.Heating Mode" ; brickframe:uuid "e1c43fd6-3cae-3e0d-ba3e-d8594a6d39dc" . bldg:AMRL.ZONE.AHU01.RM1126.Zone_Air_Temp a brick1:Zone_Air_Temperature_Sensor ; brickframe:hasSite bldg:AMRL ; brickframe:pointname "AMRL.ZONE.AHU01.RM1126.Zone Air Temp" ; brickframe:uuid "8e25b107-d703-34ed-adaa-d68ba16e3080" . bldg:AMRL.ZONE.AHU01.RM1126.Zone_Air_Temp_Setpoint a brick_v_1_0_2:Zone_Air_Temperature_Setpoint ; brickframe:pointname "AMRL.ZONE.AHU01.RM1126.Zone Air Temp Setpoint" ; brickframe:uuid "62b175d3-aee3-39b0-a614-d0e2d9337897" . bldg:AMRL.ZONE.AHU01.RM1127.Day_Night_Mode a brick_v_1_0_2:Mode ; brickframe:pointname "AMRL.ZONE.AHU01.RM1127.Day Night Mode" ; brickframe:uuid "81597d05-8388-3499-a3a7-52ea690e8be8" . bldg:AMRL.ZONE.AHU01.RM1127.Heating_Mode a brick1:Heating_Command ; brickframe:hasSite bldg:AMRL ; brickframe:pointname "AMRL.ZONE.AHU01.RM1127.Heating Mode" ; brickframe:uuid "a61a4ff4-a92b-3502-9d66-0563b5545345" . bldg:AMRL.ZONE.AHU01.RM1127.Zone_Air_Temp a brick1:Zone_Air_Temperature_Sensor ; brickframe:hasSite bldg:AMRL ; brickframe:pointname "AMRL.ZONE.AHU01.RM1127.Zone Air Temp" ; brickframe:uuid "c39adf7c-c1ab-3328-9cbc-7dff5c2dd681" . bldg:AMRL.ZONE.AHU01.RM1127.Zone_Air_Temp_Setpoint a brick_v_1_0_2:Zone_Air_Temperature_Setpoint ; brickframe:pointname "AMRL.ZONE.AHU01.RM1127.Zone Air Temp Setpoint" ; brickframe:uuid "b0fee9fb-deff-3938-a97d-4d177a973f8d" . bldg:AMRL.ZONE.AHU01.RM1128.Day_Night_Mode a brick_v_1_0_2:Mode ; brickframe:pointname "AMRL.ZONE.AHU01.RM1128.Day Night Mode" ; brickframe:uuid "f553c937-e8d4-324f-94df-f287c18faaab" . bldg:AMRL.ZONE.AHU01.RM1128.Heating_Mode a brick1:Heating_Command ; brickframe:hasSite bldg:AMRL ; brickframe:pointname "AMRL.ZONE.AHU01.RM1128.Heating Mode" ; brickframe:uuid "061ab343-c571-3ea0-bb6e-0cf5bfead41a" . bldg:AMRL.ZONE.AHU01.RM1128.Zone_Air_Temp a brick1:Zone_Air_Temperature_Sensor ; brickframe:hasSite bldg:AMRL ; brickframe:pointname "AMRL.ZONE.AHU01.RM1128.Zone Air Temp" ; brickframe:uuid "7ca741f3-8c8f-37ab-8466-0db9a9f92015" . bldg:AMRL.ZONE.AHU01.RM1128.Zone_Air_Temp_Setpoint a brick_v_1_0_2:Zone_Air_Temperature_Setpoint ; brickframe:pointname "AMRL.ZONE.AHU01.RM1128.Zone Air Temp Setpoint" ; brickframe:uuid "cbf882ad-3f9e-3987-8882-d16a16e8d918" . bldg:RM1100C a brick1:HVAC_Zone ; brickframe:hasSite bldg:AMRL ; brick1:hasPart bldg:RM1100C_room . bldg:RM1115 a brick1:HVAC_Zone ; brickframe:hasSite bldg:AMRL ; brick1:hasPart bldg:RM1115_room . bldg:RM1119 a brick1:HVAC_Zone ; brickframe:hasSite bldg:AMRL ; brick1:hasPart bldg:RM1119_room . bldg:RM1120 a brick1:HVAC_Zone ; brickframe:hasSite bldg:AMRL ; brick1:hasPart bldg:RM1120_room . bldg:RM1123 a brick1:HVAC_Zone ; brickframe:hasSite bldg:AMRL ; brick1:hasPart bldg:RM1123_room . bldg:RM1126 a brick1:HVAC_Zone ; brickframe:hasSite bldg:AMRL ; brick1:hasPart bldg:RM1126_room . bldg:RM1127 a brick1:HVAC_Zone ; brickframe:hasSite bldg:AMRL ; brick1:hasPart bldg:RM1127_room . bldg:RM1128 a brick1:HVAC_Zone ; brickframe:hasSite bldg:AMRL ; brick1:hasPart bldg:RM1128_room . bldg:VAVRM1100C a brick1:VAV ; brickframe:hasSite bldg:AMRL ; brick1:feeds bldg:RM1100C ; brick1:hasPoint bldg:AMRL.ZONE.AHU01.RM1100C.Day_Night_Mode, bldg:AMRL.ZONE.AHU01.RM1100C.Heating_Mode, bldg:AMRL.ZONE.AHU01.RM1100C.Zone_Air_Temp, bldg:AMRL.ZONE.AHU01.RM1100C.Zone_Air_Temp_Setpoint . bldg:VAVRM1115 a brick1:VAV ; brickframe:hasSite bldg:AMRL ; brick1:feeds bldg:RM1115 ; brick1:hasPoint bldg:AMRL.ZONE.AHU01.RM1115.Day_Night_Mode, bldg:AMRL.ZONE.AHU01.RM1115.Heating_Mode, bldg:AMRL.ZONE.AHU01.RM1115.Zone_Air_Temp, bldg:AMRL.ZONE.AHU01.RM1115.Zone_Air_Temp_Setpoint . bldg:VAVRM1119 a brick1:VAV ; brickframe:hasSite bldg:AMRL ; brick1:feeds bldg:RM1119 ; brick1:hasPoint bldg:AMRL.ZONE.AHU01.RM1119.Day_Night_Mode, bldg:AMRL.ZONE.AHU01.RM1119.Heating_Mode, bldg:AMRL.ZONE.AHU01.RM1119.Zone_Air_Temp, bldg:AMRL.ZONE.AHU01.RM1119.Zone_Air_Temp_Setpoint . bldg:VAVRM1120 a brick1:VAV ; brickframe:hasSite bldg:AMRL ; brick1:feeds bldg:RM1120 ; brick1:hasPoint bldg:AMRL.ZONE.AHU01.RM1120.Day_Night_Mode, bldg:AMRL.ZONE.AHU01.RM1120.Heating_Mode, bldg:AMRL.ZONE.AHU01.RM1120.Zone_Air_Temp, bldg:AMRL.ZONE.AHU01.RM1120.Zone_Air_Temp_Setpoint . bldg:VAVRM1123 a brick1:VAV ; brickframe:hasSite bldg:AMRL ; brick1:feeds bldg:RM1123 ; brick1:hasPoint bldg:AMRL.ZONE.AHU01.RM1123.Day_Night_Mode, bldg:AMRL.ZONE.AHU01.RM1123.Heating_Mode, bldg:AMRL.ZONE.AHU01.RM1123.Zone_Air_Temp, bldg:AMRL.ZONE.AHU01.RM1123.Zone_Air_Temp_Setpoint . bldg:VAVRM1126 a brick1:VAV ; brickframe:hasSite bldg:AMRL ; brick1:feeds bldg:RM1126 ; brick1:hasPoint bldg:AMRL.ZONE.AHU01.RM1126.Day_Night_Mode, bldg:AMRL.ZONE.AHU01.RM1126.Heating_Mode, bldg:AMRL.ZONE.AHU01.RM1126.Zone_Air_Temp, bldg:AMRL.ZONE.AHU01.RM1126.Zone_Air_Temp_Setpoint . bldg:VAVRM1127 a brick1:VAV ; brickframe:hasSite bldg:AMRL ; brick1:feeds bldg:RM1127 ; brick1:hasPoint bldg:AMRL.ZONE.AHU01.RM1127.Day_Night_Mode, bldg:AMRL.ZONE.AHU01.RM1127.Heating_Mode, bldg:AMRL.ZONE.AHU01.RM1127.Zone_Air_Temp, bldg:AMRL.ZONE.AHU01.RM1127.Zone_Air_Temp_Setpoint . bldg:VAVRM1128 a brick1:VAV ; brickframe:hasSite bldg:AMRL ; brick1:feeds bldg:RM1128 ; brick1:hasPoint bldg:AMRL.ZONE.AHU01.RM1128.Day_Night_Mode, bldg:AMRL.ZONE.AHU01.RM1128.Heating_Mode, bldg:AMRL.ZONE.AHU01.RM1128.Zone_Air_Temp, bldg:AMRL.ZONE.AHU01.RM1128.Zone_Air_Temp_Setpoint . brick_v_1_0_2:Building_Electric_Meter a owl:Class ; rdfs:subClassOf brick_v_1_0_2:Electric_Meter . brick_v_1_0_2:Illumination_Sensor a owl:Class ; rdfs:subClassOf brick1:Sensor . brickframe:hasSite a owl:ObjectProperty ; rdfs:range brick_v_1_0_2:Site . bldg:RM1100C_room a brick1:Room ; brickframe:hasSite bldg:AMRL . bldg:RM1115_room a brick1:Room ; brickframe:hasSite bldg:AMRL . bldg:RM1119_room a brick1:Room ; brickframe:hasSite bldg:AMRL . bldg:RM1120_room a brick1:Room ; brickframe:hasSite bldg:AMRL . bldg:RM1123_room a brick1:Room ; brickframe:hasSite bldg:AMRL . bldg:RM1126_room a brick1:Room ; brickframe:hasSite bldg:AMRL . bldg:RM1127_room a brick1:Room ; brickframe:hasSite bldg:AMRL . bldg:RM1128_room a brick1:Room ; brickframe:hasSite bldg:AMRL . brick_v_1_0_2:Site a owl:Class ; rdfs:subClassOf brick1:Location . bldg:AMRL a brick_v_1_0_2:Site ; brickframe:AreaSquareFeet "7502" ; brickframe:Country "US" .
49,067
https://github.com/invantage/npm-gate/blob/master/test/runScript.spec.js
Github Open Source
Open Source
Apache-2.0
null
npm-gate
invantage
JavaScript
Code
758
3,007
/* eslint no-underscore-dangle: 0 */ import expect from 'expect' import isPromise from 'is-promise' import mockFn from 'execa' import runScript from '../src/runScript' jest.mock('execa') expect.extend({ toBeAPromise() { expect.assert(isPromise(this.actual), 'expected %s to be a Promise', this.actual) return this } }) const packageJSON = { scripts: { test: 'noop', test2: 'noop' }, 'lint-staged': {} } describe('runScript', () => { beforeEach(() => { mockFn.mockReset() mockFn.mockImplementation(() => Promise.resolve(true)) }) it('should return an array', () => { expect(runScript('test', ['test.js'], packageJSON)).toBeA('array') }) it('should throw for non-existend script', () => { expect(() => { runScript('missing-module', ['test.js'], packageJSON)[0].task() }).toThrow() }) it('should work with a single command', async () => { const res = runScript('test', ['test.js'], packageJSON) expect(res.length).toBe(1) expect(res[0].title).toBe('test') expect(res[0].task).toBeA('function') const taskPromise = res[0].task() expect(taskPromise).toBeAPromise() await taskPromise }) it('should work with multiple commands', async () => { const res = runScript(['test', 'test2'], ['test.js'], packageJSON) expect(res.length).toBe(2) expect(res[0].title).toBe('test') expect(res[1].title).toBe('test2') let taskPromise = res[0].task() expect(taskPromise).toBeAPromise() await taskPromise expect(mockFn.mock.calls.length).toEqual(1) expect(mockFn.mock.calls[0]).toEqual(['npm', ['run', '--silent', 'test', '--', 'test.js'], {}]) taskPromise = res[1].task() expect(taskPromise).toBeAPromise() await taskPromise expect(mockFn.mock.calls.length).toEqual(2) expect(mockFn.mock.calls[1]).toEqual(['npm', ['run', '--silent', 'test2', '--', 'test.js'], {}]) }) it('should respect chunk size', async () => { const res = runScript(['test'], ['test1.js', 'test2.js'], packageJSON, { config: { chunkSize: 1 } }) const taskPromise = res[0].task() expect(taskPromise).toBeAPromise() await taskPromise expect(mockFn.mock.calls.length).toEqual(2) expect(mockFn.mock.calls[0]).toEqual(['npm', ['run', '--silent', 'test', '--', 'test1.js'], {}]) expect(mockFn.mock.calls[1]).toEqual(['npm', ['run', '--silent', 'test', '--', 'test2.js'], {}]) }) it('should support non npm scripts', async () => { const res = runScript(['node --arg=true ./myscript.js', 'git add'], ['test.js'], packageJSON) expect(res.length).toBe(2) expect(res[0].title).toBe('node --arg=true ./myscript.js') expect(res[1].title).toBe('git add') let taskPromise = res[0].task() expect(taskPromise).toBeAPromise() await taskPromise expect(mockFn.mock.calls.length).toEqual(1) expect(mockFn.mock.calls[0][0]).toContain('node') expect(mockFn.mock.calls[0][1]).toEqual(['--arg=true', './myscript.js', 'test.js']) taskPromise = res[1].task() expect(taskPromise).toBeAPromise() await taskPromise expect(mockFn.mock.calls.length).toEqual(2) expect(mockFn.mock.calls[1][0]).toContain('git') expect(mockFn.mock.calls[1][1]).toEqual(['add', 'test.js']) }) it('should pass cwd to execa if gitDir option is set for non-npm tasks', async () => { const res = runScript(['test', 'git add'], ['test.js'], packageJSON, { gitDir: '../' }) let taskPromise = res[0].task() expect(taskPromise).toBeAPromise() await taskPromise expect(mockFn.mock.calls.length).toEqual(1) expect(mockFn.mock.calls[0]).toEqual(['npm', ['run', '--silent', 'test', '--', 'test.js'], {}]) taskPromise = res[1].task() expect(taskPromise).toBeAPromise() await taskPromise expect(mockFn.mock.calls.length).toEqual(2) expect(mockFn.mock.calls[1][0]).toMatch(/git$/) expect(mockFn.mock.calls[1][1]).toEqual(['add', 'test.js']) expect(mockFn.mock.calls[1][2]).toEqual({ cwd: '../' }) }) it('should not pass `gitDir` as `cwd` to `execa()` if a non-git binary is called', async () => { const res = runScript(['jest'], ['test.js'], packageJSON, { gitDir: '../' }) const taskPromise = res[0].task() expect(taskPromise).toBeAPromise() await taskPromise expect(mockFn.mock.calls.length).toEqual(1) expect(mockFn.mock.calls[0]).toEqual(['jest', ['test.js'], {}]) }) it('should use --silent in non-verbose mode', async () => { const res = runScript('test', ['test.js'], packageJSON, { verbose: false }) const taskPromise = res[0].task() expect(taskPromise).toBeAPromise() await taskPromise expect(mockFn.mock.calls.length).toEqual(1) expect(mockFn.mock.calls[0]).toEqual(['npm', ['run', '--silent', 'test', '--', 'test.js'], {}]) }) it('should not use --silent in verbose mode', async () => { const res = runScript('test', ['test.js'], packageJSON, { verbose: true }) const taskPromise = res[0].task() expect(taskPromise).toBeAPromise() await taskPromise expect(mockFn.mock.calls.length).toEqual(1) expect(mockFn.mock.calls[0]).toEqual(['npm', ['run', 'test', '--', 'test.js'], {}]) }) it('should throw error for failed linters', async () => { const linteErr = new Error() linteErr.stdout = 'Mock error' linteErr.stderr = '' mockFn.mockImplementation(() => Promise.reject(linteErr)) const res = runScript('mock-fail-linter', ['test.js'], packageJSON) const taskPromise = res[0].task() try { await taskPromise } catch (err) { expect(err.message) .toMatch(`🚫 mock-fail-linter found some errors. Please fix them and try committing again. ${linteErr.stdout} ${linteErr.stderr}`) } }) it('should allow trapping of filenames', async () => { const res = runScript([ { "command" : "test", trap:true }], ['file1.js', 'file2.js'], packageJSON) const taskPromise = res[0].task() expect(taskPromise).toBeAPromise() await taskPromise expect(mockFn.mock.calls.length).toEqual(1) expect(mockFn.mock.calls[0]).toEqual([ 'npm', [ 'run', '--silent', 'test' ], {} ]) }) it('should allow command name', async () => { const res = runScript([{ name: 'compressing svg', command: 'test' }], ['test.js'], packageJSON) const taskPromise = res[0].task() expect(taskPromise).toBeAPromise() await taskPromise expect(mockFn.mock.calls.length).toEqual(1) expect(res[0].title).toBe('compressing svg') expect(mockFn.mock.calls[0]).toEqual(['npm', ['run', '--silent', 'test', '--', 'test.js'], {}]) }) it('should allow complex command with templating', async () => { const res = runScript([ "echo <-o <>.test> --option <--ext=<extension> paraminthemiddle --file=<full>> --paraminbetween <--dir=<path> --out=<filename>.tar.gz> --end"], ['file1.js', 'file2.js'], packageJSON) const taskPromise = res[0].task() expect(taskPromise).toBeAPromise() await taskPromise expect(mockFn.mock.calls.length).toEqual(1) expect(mockFn.mock.calls[0]).toEqual([ 'echo', [ '-o file1.js.test', '-o file2.js.test', '--option', '--ext=js paraminthemiddle --file=file1.js', '--ext=js paraminthemiddle --file=file2.js', '--paraminbetween', '--dir=. --out=file1.tar.gz', '--dir=. --out=file2.tar.gz', '--end' ], {} ]) }) it('should allow complex command with templating and a double extension', async () => { const res = runScript([ "compress <--in=<full> --out=<path>/bin/<filename>.tar.gz>"], ['file1.js', 'file2.js'], packageJSON) const taskPromise = res[0].task() expect(taskPromise).toBeAPromise() await taskPromise expect(mockFn.mock.calls.length).toEqual(1) expect(mockFn.mock.calls[0]).toEqual([ 'compress', [ '--in=file1.js --out=./bin/file1.tar.gz', '--in=file2.js --out=./bin/file2.tar.gz', '' ], {} ]) }) it('should throw error for absent command', async () => { try { const res = runScript({ "name": 'empty command' }, ['test.js'], packageJSON) const taskPromise = res[0].task() await taskPromise } catch (err) { expect(err.message).toMatch( `Command could not be found. You're package.json is probably wrong.` ) } }) it('should allow complex command with expression the ressemble protected ones', async () => { const res = runScript(['compress <personal>'], ['file1.js', 'file2.js'], packageJSON) const taskPromise = res[0].task() expect(taskPromise).toBeAPromise() await taskPromise expect(mockFn.mock.calls.length).toEqual(1) expect(mockFn.mock.calls[0]).toEqual([ 'compress', [ '<personal>', 'file1.js', 'file2.js' ], {}]) }) })
3,389
https://github.com/fibersel/catboost/blob/master/library/cpp/threading/future/core/future-inl.h
Github Open Source
Open Source
Apache-2.0
2,021
catboost
fibersel
C
Code
2,052
7,167
#pragma once #if !defined(INCLUDE_FUTURE_INL_H) #error "you should never include future-inl.h directly" #endif // INCLUDE_FUTURE_INL_H namespace NThreading { namespace NImpl { //////////////////////////////////////////////////////////////////////////////// template <typename T> using TCallback = std::function<void(const TFuture<T>&)>; template <typename T> using TCallbackList = TVector<TCallback<T>>; // TODO: small vector //////////////////////////////////////////////////////////////////////////////// enum class TError { Error }; template <typename T> class TFutureState: public TAtomicRefCount<TFutureState<T>> { enum { NotReady, ExceptionSet, ValueMoved, // keep the ordering of this and following values ValueSet, ValueRead, }; private: mutable TAtomic State; TAdaptiveLock StateLock; TCallbackList<T> Callbacks; mutable THolder<TSystemEvent> ReadyEvent; std::exception_ptr Exception; union { char NullValue; T Value; }; void AccessValue(TDuration timeout, int acquireState) const { int state = AtomicGet(State); if (Y_UNLIKELY(state == NotReady)) { if (timeout == TDuration::Zero()) { ythrow TFutureException() << "value not set"; } if (!Wait(timeout)) { ythrow TFutureException() << "wait timeout"; } state = AtomicGet(State); } TryRethrowWithState(state); switch (AtomicGetAndCas(&State, acquireState, ValueSet)) { case ValueSet: break; case ValueRead: if (acquireState != ValueRead) { ythrow TFutureException() << "value being read"; } break; case ValueMoved: ythrow TFutureException() << "value was moved"; default: Y_ASSERT(state == ValueSet); } } public: TFutureState() : State(NotReady) , NullValue(0) { } template <typename TT> TFutureState(TT&& value) : State(ValueSet) , Value(std::forward<TT>(value)) { } TFutureState(std::exception_ptr exception, TError) : State(ExceptionSet) , Exception(std::move(exception)) , NullValue(0) { } ~TFutureState() { if (State >= ValueMoved) { // ValueMoved, ValueSet, ValueRead Value.~T(); } } bool HasValue() const { return AtomicGet(State) >= ValueMoved; // ValueMoved, ValueSet, ValueRead } void TryRethrow() const { int state = AtomicGet(State); TryRethrowWithState(state); } bool HasException() const { return AtomicGet(State) == ExceptionSet; } const T& GetValue(TDuration timeout = TDuration::Zero()) const { AccessValue(timeout, ValueRead); return Value; } T ExtractValue(TDuration timeout = TDuration::Zero()) { AccessValue(timeout, ValueMoved); return std::move(Value); } template <typename TT> void SetValue(TT&& value) { bool success = TrySetValue(std::forward<TT>(value)); if (Y_UNLIKELY(!success)) { ythrow TFutureException() << "value already set"; } } template <typename TT> bool TrySetValue(TT&& value) { TSystemEvent* readyEvent = nullptr; TCallbackList<T> callbacks; with_lock (StateLock) { int state = AtomicGet(State); if (Y_UNLIKELY(state != NotReady)) { return false; } new (&Value) T(std::forward<TT>(value)); readyEvent = ReadyEvent.Get(); callbacks = std::move(Callbacks); AtomicSet(State, ValueSet); } if (readyEvent) { readyEvent->Signal(); } if (callbacks) { TFuture<T> temp(this); for (auto& callback : callbacks) { callback(temp); } } return true; } void SetException(std::exception_ptr e) { bool success = TrySetException(std::move(e)); if (Y_UNLIKELY(!success)) { ythrow TFutureException() << "value already set"; } } bool TrySetException(std::exception_ptr e) { TSystemEvent* readyEvent; TCallbackList<T> callbacks; with_lock (StateLock) { int state = AtomicGet(State); if (Y_UNLIKELY(state != NotReady)) { return false; } Exception = std::move(e); readyEvent = ReadyEvent.Get(); callbacks = std::move(Callbacks); AtomicSet(State, ExceptionSet); } if (readyEvent) { readyEvent->Signal(); } if (callbacks) { TFuture<T> temp(this); for (auto& callback : callbacks) { callback(temp); } } return true; } template <typename F> bool Subscribe(F&& func) { with_lock (StateLock) { int state = AtomicGet(State); if (state == NotReady) { Callbacks.emplace_back(std::forward<F>(func)); return true; } } return false; } void Wait() const { Wait(TInstant::Max()); } bool Wait(TDuration timeout) const { return Wait(timeout.ToDeadLine()); } bool Wait(TInstant deadline) const { TSystemEvent* readyEvent = nullptr; with_lock (StateLock) { int state = AtomicGet(State); if (state != NotReady) { return true; } if (!ReadyEvent) { ReadyEvent.Reset(new TSystemEvent()); } readyEvent = ReadyEvent.Get(); } Y_ASSERT(readyEvent); return readyEvent->WaitD(deadline); } void TryRethrowWithState(int state) const { if (Y_UNLIKELY(state == ExceptionSet)) { Y_ASSERT(Exception); std::rethrow_exception(Exception); } } }; //////////////////////////////////////////////////////////////////////////////// template <> class TFutureState<void>: public TAtomicRefCount<TFutureState<void>> { enum { NotReady, ValueSet, ExceptionSet, }; private: TAtomic State; TAdaptiveLock StateLock; TCallbackList<void> Callbacks; mutable THolder<TSystemEvent> ReadyEvent; std::exception_ptr Exception; public: TFutureState(bool valueSet = false) : State(valueSet ? ValueSet : NotReady) { } TFutureState(std::exception_ptr exception, TError) : State(ExceptionSet) , Exception(std::move(exception)) { } bool HasValue() const { return AtomicGet(State) == ValueSet; } void TryRethrow() const { int state = AtomicGet(State); TryRethrowWithState(state); } bool HasException() const { return AtomicGet(State) == ExceptionSet; } void GetValue(TDuration timeout = TDuration::Zero()) const { int state = AtomicGet(State); if (Y_UNLIKELY(state == NotReady)) { if (timeout == TDuration::Zero()) { ythrow TFutureException() << "value not set"; } if (!Wait(timeout)) { ythrow TFutureException() << "wait timeout"; } state = AtomicGet(State); } TryRethrowWithState(state); Y_ASSERT(state == ValueSet); } void SetValue() { bool success = TrySetValue(); if (Y_UNLIKELY(!success)) { ythrow TFutureException() << "value already set"; } } bool TrySetValue() { TSystemEvent* readyEvent = nullptr; TCallbackList<void> callbacks; with_lock (StateLock) { int state = AtomicGet(State); if (Y_UNLIKELY(state != NotReady)) { return false; } readyEvent = ReadyEvent.Get(); callbacks = std::move(Callbacks); AtomicSet(State, ValueSet); } if (readyEvent) { readyEvent->Signal(); } if (callbacks) { TFuture<void> temp(this); for (auto& callback : callbacks) { callback(temp); } } return true; } void SetException(std::exception_ptr e) { bool success = TrySetException(std::move(e)); if (Y_UNLIKELY(!success)) { ythrow TFutureException() << "value already set"; } } bool TrySetException(std::exception_ptr e) { TSystemEvent* readyEvent = nullptr; TCallbackList<void> callbacks; with_lock (StateLock) { int state = AtomicGet(State); if (Y_UNLIKELY(state != NotReady)) { return false; } Exception = std::move(e); readyEvent = ReadyEvent.Get(); callbacks = std::move(Callbacks); AtomicSet(State, ExceptionSet); } if (readyEvent) { readyEvent->Signal(); } if (callbacks) { TFuture<void> temp(this); for (auto& callback : callbacks) { callback(temp); } } return true; } template <typename F> bool Subscribe(F&& func) { with_lock (StateLock) { int state = AtomicGet(State); if (state == NotReady) { Callbacks.emplace_back(std::forward<F>(func)); return true; } } return false; } void Wait() const { Wait(TInstant::Max()); } bool Wait(TDuration timeout) const { return Wait(timeout.ToDeadLine()); } bool Wait(TInstant deadline) const { TSystemEvent* readyEvent = nullptr; with_lock (StateLock) { int state = AtomicGet(State); if (state != NotReady) { return true; } if (!ReadyEvent) { ReadyEvent.Reset(new TSystemEvent()); } readyEvent = ReadyEvent.Get(); } Y_ASSERT(readyEvent); return readyEvent->WaitD(deadline); } void TryRethrowWithState(int state) const { if (Y_UNLIKELY(state == ExceptionSet)) { Y_ASSERT(Exception); std::rethrow_exception(Exception); } } }; //////////////////////////////////////////////////////////////////////////////// template <typename T> inline void SetValueImpl(TPromise<T>& promise, const T& value) { promise.SetValue(value); } template <typename T> inline void SetValueImpl(TPromise<T>& promise, T&& value) { promise.SetValue(std::move(value)); } template <typename T> inline void SetValueImpl(TPromise<T>& promise, const TFuture<T>& future, std::enable_if_t<!std::is_void<T>::value, bool> = false) { future.Subscribe([=](const TFuture<T>& f) mutable { T const* value; try { value = &f.GetValue(); } catch (...) { promise.SetException(std::current_exception()); return; } promise.SetValue(*value); }); } template <typename T> inline void SetValueImpl(TPromise<void>& promise, const TFuture<T>& future) { future.Subscribe([=](const TFuture<T>& f) mutable { try { f.TryRethrow(); } catch (...) { promise.SetException(std::current_exception()); return; } promise.SetValue(); }); } template <typename T, typename F> inline void SetValue(TPromise<T>& promise, F&& func) { try { SetValueImpl(promise, func()); } catch (...) { const bool success = promise.TrySetException(std::current_exception()); if (Y_UNLIKELY(!success)) { throw; } } } template <typename F> inline void SetValue(TPromise<void>& promise, F&& func, std::enable_if_t<std::is_void<TFunctionResult<F>>::value, bool> = false) { try { func(); } catch (...) { promise.SetException(std::current_exception()); return; } promise.SetValue(); } } //////////////////////////////////////////////////////////////////////////////// class TFutureStateId { private: const void* Id; public: template <typename T> explicit TFutureStateId(const NImpl::TFutureState<T>& state) : Id(&state) { } const void* Value() const noexcept { return Id; } }; inline bool operator==(const TFutureStateId& l, const TFutureStateId& r) { return l.Value() == r.Value(); } inline bool operator!=(const TFutureStateId& l, const TFutureStateId& r) { return !(l == r); } //////////////////////////////////////////////////////////////////////////////// template <typename T> inline TFuture<T>::TFuture(const TIntrusivePtr<TFutureState>& state) noexcept : State(state) { } template <typename T> inline void TFuture<T>::Swap(TFuture<T>& other) { State.Swap(other.State); } template <typename T> inline bool TFuture<T>::HasValue() const { return State && State->HasValue(); } template <typename T> inline const T& TFuture<T>::GetValue(TDuration timeout) const { EnsureInitialized(); return State->GetValue(timeout); } template <typename T> inline T TFuture<T>::ExtractValue(TDuration timeout) { EnsureInitialized(); return State->ExtractValue(timeout); } template <typename T> inline const T& TFuture<T>::GetValueSync() const { return GetValue(TDuration::Max()); } template <typename T> inline T TFuture<T>::ExtractValueSync() { return ExtractValue(TDuration::Max()); } template <typename T> inline void TFuture<T>::TryRethrow() const { if (State) { State->TryRethrow(); } } template <typename T> inline bool TFuture<T>::HasException() const { return State && State->HasException(); } template <typename T> inline void TFuture<T>::Wait() const { EnsureInitialized(); return State->Wait(); } template <typename T> inline bool TFuture<T>::Wait(TDuration timeout) const { EnsureInitialized(); return State->Wait(timeout); } template <typename T> inline bool TFuture<T>::Wait(TInstant deadline) const { EnsureInitialized(); return State->Wait(deadline); } template <typename T> template <typename F> inline const TFuture<T>& TFuture<T>::Subscribe(F&& func) const { EnsureInitialized(); if (!State->Subscribe(std::forward<F>(func))) { func(*this); } return *this; } template <typename T> template <typename F> inline TFuture<TFutureType<TFutureCallResult<F, T>>> TFuture<T>::Apply(F&& func) const { auto promise = NewPromise<TFutureType<TFutureCallResult<F, T>>>(); Subscribe([promise, func = std::forward<F>(func)](const TFuture<T>& future) mutable { NImpl::SetValue(promise, [&]() { return func(future); }); }); return promise; } template <typename T> inline TFuture<void> TFuture<T>::IgnoreResult() const { auto promise = NewPromise(); Subscribe([=](const TFuture<T>& future) mutable { NImpl::SetValueImpl(promise, future); }); return promise; } template <typename T> inline bool TFuture<T>::Initialized() const { return bool(State); } template <typename T> inline TMaybe<TFutureStateId> TFuture<T>::StateId() const noexcept { return State != nullptr ? MakeMaybe<TFutureStateId>(*State) : Nothing(); } template <typename T> inline void TFuture<T>::EnsureInitialized() const { if (!State) { ythrow TFutureException() << "state not initialized"; } } //////////////////////////////////////////////////////////////////////////////// inline TFuture<void>::TFuture(const TIntrusivePtr<TFutureState>& state) noexcept : State(state) { } inline void TFuture<void>::Swap(TFuture<void>& other) { State.Swap(other.State); } inline bool TFuture<void>::HasValue() const { return State && State->HasValue(); } inline void TFuture<void>::GetValue(TDuration timeout) const { EnsureInitialized(); State->GetValue(timeout); } inline void TFuture<void>::GetValueSync() const { GetValue(TDuration::Max()); } inline void TFuture<void>::TryRethrow() const { if (State) { State->TryRethrow(); } } inline bool TFuture<void>::HasException() const { return State && State->HasException(); } inline void TFuture<void>::Wait() const { EnsureInitialized(); return State->Wait(); } inline bool TFuture<void>::Wait(TDuration timeout) const { EnsureInitialized(); return State->Wait(timeout); } inline bool TFuture<void>::Wait(TInstant deadline) const { EnsureInitialized(); return State->Wait(deadline); } template <typename F> inline const TFuture<void>& TFuture<void>::Subscribe(F&& func) const { EnsureInitialized(); if (!State->Subscribe(std::forward<F>(func))) { func(*this); } return *this; } template <typename F> inline TFuture<TFutureType<TFutureCallResult<F, void>>> TFuture<void>::Apply(F&& func) const { auto promise = NewPromise<TFutureType<TFutureCallResult<F, void>>>(); Subscribe([promise, func = std::forward<F>(func)](const TFuture<void>& future) mutable { NImpl::SetValue(promise, [&]() { return func(future); }); }); return promise; } template <typename R> inline TFuture<R> TFuture<void>::Return(const R& value) const { auto promise = NewPromise<R>(); Subscribe([=](const TFuture<void>& future) mutable { try { future.TryRethrow(); } catch (...) { promise.SetException(std::current_exception()); return; } promise.SetValue(value); }); return promise; } inline bool TFuture<void>::Initialized() const { return bool(State); } inline TMaybe<TFutureStateId> TFuture<void>::StateId() const noexcept { return State != nullptr ? MakeMaybe<TFutureStateId>(*State) : Nothing(); } inline void TFuture<void>::EnsureInitialized() const { if (!State) { ythrow TFutureException() << "state not initialized"; } } //////////////////////////////////////////////////////////////////////////////// template <typename T> inline TPromise<T>::TPromise(const TIntrusivePtr<TFutureState>& state) noexcept : State(state) { } template <typename T> inline void TPromise<T>::Swap(TPromise<T>& other) { State.Swap(other.State); } template <typename T> inline const T& TPromise<T>::GetValue() const { EnsureInitialized(); return State->GetValue(); } template <typename T> inline T TPromise<T>::ExtractValue() { EnsureInitialized(); return State->ExtractValue(); } template <typename T> inline bool TPromise<T>::HasValue() const { return State && State->HasValue(); } template <typename T> inline void TPromise<T>::SetValue(const T& value) { EnsureInitialized(); State->SetValue(value); } template <typename T> inline void TPromise<T>::SetValue(T&& value) { EnsureInitialized(); State->SetValue(std::move(value)); } template <typename T> inline bool TPromise<T>::TrySetValue(const T& value) { EnsureInitialized(); return State->TrySetValue(value); } template <typename T> inline bool TPromise<T>::TrySetValue(T&& value) { EnsureInitialized(); return State->TrySetValue(std::move(value)); } template <typename T> inline void TPromise<T>::TryRethrow() const { if (State) { State->TryRethrow(); } } template <typename T> inline bool TPromise<T>::HasException() const { return State && State->HasException(); } template <typename T> inline void TPromise<T>::SetException(const TString& e) { EnsureInitialized(); State->SetException(std::make_exception_ptr(yexception() << e)); } template <typename T> inline void TPromise<T>::SetException(std::exception_ptr e) { EnsureInitialized(); State->SetException(std::move(e)); } template <typename T> inline bool TPromise<T>::TrySetException(std::exception_ptr e) { EnsureInitialized(); return State->TrySetException(std::move(e)); } template <typename T> inline TFuture<T> TPromise<T>::GetFuture() const { EnsureInitialized(); return TFuture<T>(State); } template <typename T> inline TPromise<T>::operator TFuture<T>() const { return GetFuture(); } template <typename T> inline bool TPromise<T>::Initialized() const { return bool(State); } template <typename T> inline void TPromise<T>::EnsureInitialized() const { if (!State) { ythrow TFutureException() << "state not initialized"; } } //////////////////////////////////////////////////////////////////////////////// inline TPromise<void>::TPromise(const TIntrusivePtr<TFutureState>& state) noexcept : State(state) { } inline void TPromise<void>::Swap(TPromise<void>& other) { State.Swap(other.State); } inline void TPromise<void>::GetValue() const { EnsureInitialized(); State->GetValue(); } inline bool TPromise<void>::HasValue() const { return State && State->HasValue(); } inline void TPromise<void>::SetValue() { EnsureInitialized(); State->SetValue(); } inline bool TPromise<void>::TrySetValue() { EnsureInitialized(); return State->TrySetValue(); } inline void TPromise<void>::TryRethrow() const { if(State) { State->TryRethrow(); } } inline bool TPromise<void>::HasException() const { return State && State->HasException(); } inline void TPromise<void>::SetException(const TString& e) { EnsureInitialized(); State->SetException(std::make_exception_ptr(yexception() << e)); } inline void TPromise<void>::SetException(std::exception_ptr e) { EnsureInitialized(); State->SetException(std::move(e)); } inline bool TPromise<void>::TrySetException(std::exception_ptr e) { EnsureInitialized(); return State->TrySetException(std::move(e)); } inline TFuture<void> TPromise<void>::GetFuture() const { EnsureInitialized(); return TFuture<void>(State); } inline TPromise<void>::operator TFuture<void>() const { return GetFuture(); } inline bool TPromise<void>::Initialized() const { return bool(State); } inline void TPromise<void>::EnsureInitialized() const { if (!State) { ythrow TFutureException() << "state not initialized"; } } //////////////////////////////////////////////////////////////////////////////// template <typename T> inline TPromise<T> NewPromise() { return {new NImpl::TFutureState<T>()}; } inline TPromise<void> NewPromise() { return {new NImpl::TFutureState<void>()}; } template <typename T> inline TFuture<T> MakeFuture(const T& value) { return {new NImpl::TFutureState<T>(value)}; } template <typename T> inline TFuture<std::remove_reference_t<T>> MakeFuture(T&& value) { return {new NImpl::TFutureState<std::remove_reference_t<T>>(std::forward<T>(value))}; } template <typename T> inline TFuture<T> MakeFuture() { struct TCache { TFuture<T> Instance{new NImpl::TFutureState<T>(Default<T>())}; }; return Singleton<TCache>()->Instance; } template <typename T> inline TFuture<T> MakeErrorFuture(std::exception_ptr exception) { return {new NImpl::TFutureState<T>(std::move(exception), NImpl::TError::Error)}; } inline TFuture<void> MakeFuture() { struct TCache { TFuture<void> Instance{new NImpl::TFutureState<void>(true)}; }; return Singleton<TCache>()->Instance; } }
11,746
https://github.com/programmercintasunnah/kp-ibnu_masud_kampar-ci/blob/master/application/views/login/index.php
Github Open Source
Open Source
MIT
null
kp-ibnu_masud_kampar-ci
programmercintasunnah
PHP
Code
176
748
<div class="container"> <div class="row"> <div class="login-container col-lg-4 col-md-6 col-sm-8 col-xs-12"> <div class="login-content"> <div class="login-header"> <h4 class="tg">YAYASAN NIDA' AS-SUNNAH KAMPAR</h4> <h4 class="tg">PPS. TAHFIZH AL-QUR'AN</h4> <h2 class="tg"><strong>IBNU MAS'UD</strong></h2> <h4 class="tg">KAMPAR</h4> <div class="login-title text-center"> <img class="gmbr" src="<?= base_url("assets/") ?>img/icon.png" alt=""> </div> </div> <div class="login-body"> <?= $this->session->flashdata('message'); ?> <form role="form" action="<?= base_url("login") ?>" method="post" class="login-form"> <div class="form-group "> <div class="pos-r"> <input id="username" type="text" name="username" placeholder="Username..." value="<?= set_value(("username")) ?>" autocomplete="off" autofocus class="form-username form-control"> <i class="fa fa-user"></i> <span></span> </div> <?= form_error('username', '<small class="pl-3 b">', '</small>') ?> </div> <div class="form-group"> <div class="pos-r"> <input id="password" type="password" name="password" placeholder="Password..." class="form-password form-control"> <i class="fa fa-lock"></i> <span></span> </div> <?= form_error('password', '<small class="pl-3 b">', '</small>') ?> </div> <!-- <div class="form-group text-right"> <a href="#" class="bold"> Forgot password?</a> </div> --> <div class="form-group"> <button type="submit" class="btn btn-default form-control"><strong>LOGIN</strong></button> </div> <a href="" class="">Lupa Password ?</a> </form> </div> <!-- end login-body --> </div><!-- end login-content --> <div class="login-footer text-center template"> <!-- <h5>Don't have an account?<a href="#" class="bold"> Sign up </a> </h5> <h5>Bootstrap login template made by <a href="https://github.com/azouaoui-med" class="bold"> Mohamed Azouaoui</a></h5> --> </div> </div> <!-- end login-container --> </div> </div><!-- end container -->
5,083
https://github.com/uk-gov-mirror/hmrc.professional-subscriptions-frontend/blob/master/app/models/auditing/AuditSubmissionData.scala
Github Open Source
Open Source
Apache-2.0
null
hmrc.professional-subscriptions-frontend
uk-gov-mirror
Scala
Code
366
1,200
/* * Copyright 2021 HM Revenue & Customs * * 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 models.auditing import models.{Address, PSub} import play.api.libs.functional.syntax._ import play.api.libs.json.{JsValue, Json, Writes, __} sealed trait AuditSubmissionData { val subscriptions: Map[Int, Seq[PSub]] } object AuditSubmissionData { def apply(npsData: Map[Int, Int], amountsAlreadyInCode: Option[Boolean], subscriptions: Map[Int, Seq[PSub]], yourEmployersNames: Option[Seq[String]], yourEmployer: Option[Boolean], address: Option[Address]): AuditSubmissionData = (yourEmployersNames, yourEmployer) match { case (Some(employersNames), Some(yourEmp)) => ContainsCurrentYearUserData( previouslyClaimedAmountsFromNPS = npsData, hasUserChangedClaimedAmount = amountsAlreadyInCode, subscriptions = subscriptions, yourEmployersNames = employersNames, yourEmployer = yourEmp, userCurrentCitizensDetailsAddress = address ) case _ => PreviousYearsUserData( previouslyClaimedAmountsFromNPS = npsData, hasUserChangedClaimedAmount = amountsAlreadyInCode, subscriptions = subscriptions, userCurrentCitizensDetailsAddress = address ) } implicit val writes: Writes[AuditSubmissionData] = new Writes[AuditSubmissionData] { override def writes(o: AuditSubmissionData): JsValue = { o match { case x: ContainsCurrentYearUserData => Json.toJson(x)(ContainsCurrentYearUserData.writes) case x: PreviousYearsUserData => Json.toJson(x)(PreviousYearsUserData.writes) } } } } case class ContainsCurrentYearUserData( previouslyClaimedAmountsFromNPS: Map[Int, Int], hasUserChangedClaimedAmount: Option[Boolean], subscriptions: Map[Int, Seq[PSub]], yourEmployersNames: Seq[String], yourEmployer: Boolean, userCurrentCitizensDetailsAddress: Option[Address] ) extends AuditSubmissionData object ContainsCurrentYearUserData { // imports required for the writes below import models.PSubsByYear.pSubsByYearFormats import models.NpsDataFormats.npsDataFormatsFormats implicit lazy val writesAddress: Writes[Address] = ( (__ \ "line1").writeNullable[String] and (__ \ "line2").writeNullable[String] and (__ \ "line3").writeNullable[String] and (__ \ "line4").writeNullable[String] and (__ \ "line5").writeNullable[String] and (__ \ "postcode").writeNullable[String] and (__ \ "country").writeNullable[String] )(unlift(Address.unapply)) implicit val writes: Writes[ContainsCurrentYearUserData] = Json.writes[ContainsCurrentYearUserData] } case class PreviousYearsUserData( previouslyClaimedAmountsFromNPS: Map[Int, Int], hasUserChangedClaimedAmount: Option[Boolean], subscriptions: Map[Int, Seq[PSub]], userCurrentCitizensDetailsAddress: Option[Address] ) extends AuditSubmissionData object PreviousYearsUserData { // imports required for the writes below import models.PSubsByYear.pSubsByYearFormats import models.NpsDataFormats.npsDataFormatsFormats implicit lazy val writesAddress: Writes[Address] = ( (__ \ "line1").writeNullable[String] and (__ \ "line2").writeNullable[String] and (__ \ "line3").writeNullable[String] and (__ \ "line4").writeNullable[String] and (__ \ "line5").writeNullable[String] and (__ \ "postcode").writeNullable[String] and (__ \ "country").writeNullable[String] )(unlift(Address.unapply)) implicit val writes: Writes[PreviousYearsUserData] = Json.writes[PreviousYearsUserData] }
871
https://github.com/galuf/BookTravel/blob/master/src/containers/Login/login.js
Github Open Source
Open Source
LicenseRef-scancode-public-domain
2,019
BookTravel
galuf
JavaScript
Code
172
689
import React, { Component } from 'react'; //import client from '../../config/client' import firebase from 'firebase' import Formulario from './form' import Forms2 from './form2' import styled from 'styled-components' import HeaderHome from '../../components/header' const Sesion = styled.div` width: 100%; ` const Registrate = styled.div` text-align: center; margin-top: 20px; ` const Log =({handlerChangeMode})=>( <Sesion> <Formulario /> <br/> <Registrate onClick={()=>handlerChangeMode(false)} style={{color:'green',textDecoration:'underline green' }}> Registrate </Registrate> </Sesion> ) const Registro =({handlerChangeMode})=>( <div> <Forms2/> <br/> <Registrate onClick={()=>handlerChangeMode(true)} style={{color:'green',textDecoration:'underline green'}} > Ya tengo una cuenta</Registrate> </div> ) class Login extends Component { handleAuth(){ const provider = new firebase.auth.GoogleAuthProvider(); firebase.auth().signInWithPopup(provider) .then(result => console.log(`${result.user.email} Has iniciado sesion`)) .catch(error => console.log(`Error ${error.code}: ${error.message}`)); } constructor(props) { super(props); this.state = { email: '', password: '', displayname:'', Loginmode:true }; // this.handleAuth = this.handleAuth.bind(this); } handlerChangeMode=(node)=>{ this.setState({ Loginmode:node }) } componentWillMount(){ firebase.auth().onAuthStateChanged(user => { this.setState({ user }); console.log(user) }); } handleLogOut(){ firebase.auth().signOut() .then(result => console.log(`${result.user.email} Has cerrado sesion`)) .catch(error => console.log(`Error ${error.code}: ${error.message}`)); } render() { return ( <div> <HeaderHome titulo="Iniciar Sesion"/> {this.state.Loginmode ?<Log handlerChangeMode={this.handlerChangeMode}/> :<Registro handlerChangeMode={this.handlerChangeMode}/> } </div> ); } } export default Login;
3,741
https://github.com/siku2/AoC2018/blob/master/src/puzzles/day7.rs
Github Open Source
Open Source
MIT
null
AoC2018
siku2
Rust
Code
489
1,608
use std::collections::hash_map::Entry; use std::collections::HashMap; use std::collections::HashSet; use std::io::BufRead; use regex::Regex; use utils; fn get_connections(lines: &Vec<String>) -> Vec<(&str, &str)> { let mut connections: Vec<(&str, &str)> = Vec::new(); let line_parser = Regex::new(r#"Step (?P<first>\w+) must be finished before step (?P<second>\w+) can begin\."#).unwrap(); for line in lines { let captures = line_parser.captures(line).unwrap(); let first = captures.name("first").unwrap().as_str(); let second = captures.name("second").unwrap().as_str(); connections.push((first, second)); } connections } fn build_dependency_graph<'a>(connections: Vec<(&'a str, &'a str)>) -> HashMap<&'a str, Vec<&'a str>> { let mut graph: HashMap<&str, Vec<&str>> = HashMap::new(); for (from, to) in connections { match graph.entry(to) { Entry::Occupied(ref mut entry) => entry.get_mut().push(from), Entry::Vacant(entry) => { entry.insert(vec!(from)); } } if let Entry::Vacant(entry) = graph.entry(from) { entry.insert(Vec::new()); } } graph } fn get_choices<'a>(graph: &HashMap<&'a str, Vec<&str>>, owned: &HashSet<&str>) -> Vec<&'a str> { let mut choices = Vec::new(); for (&node, deps) in graph { if !owned.contains(node) && deps.iter().all(|dep| owned.contains(dep)) { choices.push(node); } } choices } pub fn solve_first<T: BufRead>(input: T) -> String { let lines = utils::get_lines(input); let connections = get_connections(&lines); let graph = build_dependency_graph(connections); let start = *graph.iter() .find(|&(_, n)| n.is_empty()) .expect("no start, rip").0; let mut order = String::from(start); let mut owned: HashSet<&str> = HashSet::new(); owned.insert(start); loop { let mut choices = get_choices(&graph, &owned); choices.sort(); choices.reverse(); if let Some(choice) = choices.pop() { owned.insert(choice); order.push_str(choice); } else { break; } } order } #[derive(Debug)] struct Worker<'a> { id: u8, letter: Option<&'a str>, ticks: u32, } impl<'a> Worker<'a> { fn new(id: u8) -> Worker<'a> { Worker { id, letter: None, ticks: 0 } } fn get_time(letter: &str) -> u32 { let index = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".chars() .position(|l| l.to_string().as_str() == letter) .expect("what dis?"); 60 + index as u32 + 1 } fn is_done(&self) -> bool { self.letter.is_some() && self.can_work() } fn can_work(&self) -> bool { self.ticks == 0 } fn get_letter(&mut self) -> &'a str { let letter = self.letter.unwrap(); self.letter = None; letter } fn tick(&mut self) { if self.ticks > 0 { self.ticks -= 1; } } fn work(&mut self, letter: &'a str) { self.ticks = Worker::get_time(letter); self.letter = Some(letter); } } pub fn solve_second<T: BufRead>(input: T) -> u32 { let lines = utils::get_lines(input); let connections = get_connections(&lines); let graph = build_dependency_graph(connections); let mut workers: Vec<Worker> = vec![Worker::new(1), Worker::new(2), Worker::new(3), Worker::new(3), Worker::new(4)]; let mut total_ticks = 0; let mut order = String::new(); let mut owned: HashSet<&str> = HashSet::new(); loop { for worker in workers.iter_mut() { worker.tick(); if worker.is_done() { let letter = worker.get_letter(); owned.insert(letter); order.push_str(letter); } } let mut choices = get_choices(&graph, &owned); for worker in &workers { if let Some(letter) = worker.letter { if let Some(index) = choices.iter() .position(|&choice| choice == letter) { choices.remove(index); } } } choices.sort(); choices.reverse(); if choices.is_empty() && workers.iter().all(|w| w.can_work()) { break; } for worker in workers.iter_mut() { if worker.can_work() { if let Some(letter) = choices.pop() { worker.work(letter); } } } total_ticks += 1; } total_ticks } pub fn solve<T: BufRead>(problem: u8, input: T) -> Result<String, String> { match problem { 1 => Result::Ok(solve_first(input)), 2 => Result::Ok(solve_second(input).to_string()), _ => Result::Err("This problem only has 2 parts!".to_string()) } }
34,686
https://github.com/ValorZard/Shooty-Game-2/blob/master/Assets/Scripts/UI/UIEndScreen.cs
Github Open Source
Open Source
MIT
2,022
Shooty-Game-2
ValorZard
C#
Code
192
459
/* Programmer: Manhattan Calabro */ using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; public class UIEndScreen : MonoBehaviour { // Private variables // Reference to the player and enemy lists private FindEntities m_Entities; // Start is called before the first frame update void Start() { m_Entities = GetComponentInParent<FindEntities>(); } // Update is called once per frame void Update() { // Only run if the screen isn't showing if(!GetActive()) { // If all players are inactive... if(AllObjectsInactive(m_Entities.GetPlayersManualRefresh())) // ... the players have lost ShowScreen("GAME OVER"); } } // Check if the objects are active private bool AllObjectsInactive(List<GameObject> objects) { // If the list has objects... if(objects.Count != 0) // Go through the list for(int i = 0; i < objects.Count; i++) // If the object is active... if(objects[i].activeSelf) // ... all objects are not inactive return false; // Otherwise, all objects are inactive return true; } // Activates the screen private void ShowScreen(string str) { // Go through all the children of this object for(int i = 0; i < transform.childCount; i++) // Enable the child transform.GetChild(i).gameObject.SetActive(true); // Change the text GetComponentInChildren<TextMeshProUGUI>().text = str; } public bool GetActive() { return transform.GetChild(0).gameObject.activeSelf; } }
38,666
https://github.com/amymcgovern/spacesettlers/blob/master/src/spacesettlers/graphics/ShipGraphics.java
Github Open Source
Open Source
MIT
2,023
spacesettlers
amymcgovern
Java
Code
669
2,227
package spacesettlers.graphics; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Polygon; import java.awt.Shape; import java.awt.geom.AffineTransform; import java.awt.geom.Ellipse2D; import spacesettlers.gui.JSpaceSettlersComponent; import spacesettlers.objects.Flag; import spacesettlers.objects.Ship; import spacesettlers.utilities.Position; /** * The ship drawing class, mostly re-used from spacewar 1 (but modified to allow * a ship to be any color and to show its number in the team) * * @author amy */ public class ShipGraphics extends SpacewarGraphics { public static final Color THRUST_COLOR = new Color(255, 242, 23); public static final Color THRUST_SPUTTER_COLOR = new Color(193, 72, 8); public static final Color SHIELD_COLOR = new Color(190, 40, 140); public static final Shape SHIP_SHAPE = new Polygon(new int[]{54, 108, 100, 141, 85, 73, 106, 89, 80, 40, 54, -54, -40, -80, -89, -106, -73, -85, -141, -100, -108, -54, 54}, new int[]{-89, 3, 18, 89, 89, 69, 69, 38, 53, 53, 75, 75, 53, 53, 38, 69, 69, 89, 89, 18, 3, -89, -89}, 23); public static final Shape THRUST_SHAPE = new Polygon(new int[]{44, -44, 0}, new int[]{65, 65, 200}, 3); public static final Shape THRUST_SPUTTER_SHAPE = new Polygon(new int[]{30, -30, 0}, new int[]{65, 65, 170}, 3); public static final Color SHIP_SHIELD_COLOR = Color.WHITE; private Ship ship; Color shipColor, idColor; /** * Create a new ship graphic and specify the ship and the color for the team * * @param shipColor * @param ship */ public ShipGraphics(Ship ship, Color shipColor) { super(ship.getRadius(), ship.getRadius()); this.shipColor = shipColor; this.ship = ship; this.idColor = new Color(255 - shipColor.getRed(), 255 - shipColor.getGreen(), 255 - shipColor.getBlue()); } @Override public void draw(Graphics2D graphics) { graphics.setStroke(JSpaceSettlersComponent.THIN_STROKE); final AffineTransform transform = AffineTransform.getTranslateInstance(drawLocation.getX(), drawLocation.getY()); transform.rotate(ship.getPosition().getOrientation() + Math.PI / 2); transform.scale(.10, .10); // if (ship.getActiveCommand().thrust) { // final Shape newThrustShape = transform.createTransformedShape(THRUST_SHAPE); // g.setPaint(THRUST_COLOR); // g.fill(newThrustShape); // } else if (ship.getActiveCommand().thrust) { // final Shape newThrustShape = transform.createTransformedShape(THRUST_SPUTTER_SHAPE); // g.setPaint(THRUST_SPUTTER_COLOR); // g.fill(newThrustShape); // } Shape newShipShape = transform.createTransformedShape(SHIP_SHAPE); // color the ship to match the team graphics.setPaint(shipColor); graphics.fill(newShipShape); // now show the information about the ship graphics.setFont(JSpaceSettlersComponent.FONT12); // show the id of the ship inside the ship // graphics.setPaint(idColor); //graphics.drawString(ship.getId().toString(), (int) drawLocation.getX() - 3, (int) drawLocation.getY() + 3); String number = Integer.toString((int)ship.getEnergy()); graphics.setPaint(idColor); graphics.drawString(number, (int) drawLocation.getX() + 12, (int) drawLocation.getY() + 12); // number = Integer.toString(ship.getDeaths()); // g.drawString(number, ship.getPosition().getX() + 12, ship.getPosition().getY() + 1); // // if (ship.getName() != null) { // g.drawString(ship.getName(), ship.getPosition().getX() + 12, ship.getPosition().getY() - 10); // } // // show the velocity graphics.setStroke(JSpaceSettlersComponent.THIN_STROKE); graphics.drawLine( (int) drawLocation.getX(), (int) drawLocation.getY(), (int) (drawLocation.getX() + ship.getPosition().getTranslationalVelocityX()), (int) (drawLocation.getY() + ship.getPosition().getTranslationalVelocityY())); // number = Integer.toString(ship.getKills()); // g.setPaint(Color.PINK); // g.drawString(number, ship.getPosition().getX() - 24, ship.getPosition().getY() - 10); // // number = Integer.toString(ship.getHits()); // g.setPaint(Color.GRAY); // g.drawString(number, ship.getPosition().getX() - 24, ship.getPosition().getY() + 1); // // paint the number of beacons number = Integer.toString(ship.getNumBeacons()); graphics.setPaint(BeaconGraphics.BEACON_COLOR); graphics.drawString(number, (int) drawLocation.getX() - 24, (int) drawLocation.getY() + 23); // paint the number of cores currently held by the ship number = Integer.toString(ship.getNumCores()); graphics.setPaint(this.shipColor); graphics.drawString(number, (int) drawLocation.getX() + 24, (int) drawLocation.getY() + 23); // if the ship is shielded, show the shield around it if (ship.isShielded()) { double shieldRadius = ship.getRadius() + 4; final Ellipse2D.Double shieldShape = new Ellipse2D.Double(drawLocation.getX() - shieldRadius, drawLocation.getY() - shieldRadius, 2 * shieldRadius, 2 * shieldRadius); graphics.setStroke(JSpaceSettlersComponent.THIN_STROKE); graphics.setColor(SHIP_SHIELD_COLOR); graphics.draw(shieldShape); } // if the ship is frozen from an EMP, show a ring around it (in the ship's own color) if (ship.getFreezeCount() > 0) { double shieldRadius = ship.getRadius() + 2; final Ellipse2D.Double shieldShape = new Ellipse2D.Double(drawLocation.getX() - shieldRadius, drawLocation.getY() - shieldRadius, 2 * shieldRadius, 2 * shieldRadius); graphics.setStroke(JSpaceSettlersComponent.THIN_STROKE); graphics.setColor(shipColor); graphics.draw(shieldShape); } // if the ship has a flag, put a tiny flag inside the ship if (ship.isCarryingFlag()) { AffineTransform transformFlag = AffineTransform.getTranslateInstance(drawLocation.getX(), drawLocation.getY()); transformFlag.scale(Flag.FLAG_RADIUS / 2.0, Flag.FLAG_RADIUS / 2.0); Shape tinyFlag = transformFlag.createTransformedShape(FlagGraphics.FLAG_SHAPE); if (shipColor.equals(Color.WHITE)) { graphics.setColor(Color.BLACK); } else { graphics.setColor(Color.WHITE); } graphics.fill(tinyFlag); } } /** * Only draw a ship if it is alive and drawable (ships should always be drawable) */ public boolean isDrawable() { if (ship.isAlive() && ship.isDrawable()) { return true; } else { return false; } } /** * Return the location of the center of the ship */ public Position getActualLocation() { return ship.getPosition(); } }
32,146
https://github.com/HananMohammed/moltaqa/blob/master/resources/views/front/advantage/index.blade.php
Github Open Source
Open Source
MIT
null
moltaqa
HananMohammed
PHP
Code
54
285
<section id="section-1-3" class="describe-1"> <div class="container"> <div class="row flex"><!-- Row begin --> <div class="col-md-6 col-sm-12 col-xs-12"> <div class="image"> <img src="{{asset_public('storage/uploads/'.$data["advantage"][0]->image)}}" alt="describe" class="b20-1" data-sr-id="2" style="; visibility: visible; -webkit-transform: translateY(20px) scale(1); opacity: 0;transform: translateY(20px) scale(1); opacity: 1;"> </div> </div> <div class="col-md-6 col-sm-12 col-xs-12"> <h2 class="light">@lang('front.advantage')</h2> <p>{{$data["advantage"][0]->title}}</p> <ul class="list-style pb-15"> {!! $data["advantage"][0]->text !!} </ul> </div> </div> </div> </section>
6,021
https://github.com/udyvish/loki/blob/master/cmd/promtail/Dockerfile
Github Open Source
Open Source
Apache-2.0, LicenseRef-scancode-unknown-license-reference
2,019
loki
udyvish
Dockerfile
Code
75
275
# Directories in this file are referenced from the root of the project not this folder # This file is intented to be called from the root like so: # docker build -t grafana/promtail -f cmd/promtail/Dockerfile . FROM grafana/loki-build-image:0.2.1 as build ARG GOARCH="amd64" COPY . /go/src/github.com/grafana/loki WORKDIR /go/src/github.com/grafana/loki RUN make clean && make promtail FROM alpine:3.9 RUN apk add --update --no-cache ca-certificates tzdata COPY --from=build /go/src/github.com/grafana/loki/cmd/promtail/promtail /usr/bin/promtail COPY cmd/promtail/promtail-local-config.yaml /etc/promtail/local-config.yaml COPY cmd/promtail/promtail-docker-config.yaml /etc/promtail/docker-config.yaml ENTRYPOINT ["/usr/bin/promtail"]
12,615
https://github.com/billsong0407/BeatsBot/blob/master/commands/lyrictrivia.js
Github Open Source
Open Source
MIT
null
BeatsBot
billsong0407
JavaScript
Code
459
1,143
//import discord-quiz npm as dquiz const dquiz = require ('./trivia-module.js'); //initialize arrays of questions, correct answers and wrong answers with matching index per question set var questionPool = [ 'That tonights gonna be a good night', 'Lets start living dangerously', 'Shawtys like a melody in my head', 'You dont have to put on the red light', 'We push and pull like a magnet do', 'So Ima light it up like dynamite, whoa oh oh', 'She was more like a beauty queen from a movie scene', 'I threw a wish in the well, dont ask me, Ill never tell ', 'Y hacer de tu cuerpo todo un manuscrito (sube, sube, sube)', 'Theres not a thing that I would change', 'Look into my eyes and Ill own you', 'We found love in a hopeless place', 'Yeah its pretty clear, I aint no size two', 'Everybody just have a good time', 'To the place I belong, West Virginia, mountain mama', 'Now and then I think of when we were together', 'ileon nae mam moleugo neomuhae neomuhae', 'Somebody once told me the world is gonna roll me', 'take me by the hand, Lead me to the land that you understand', 'Inochi sae tamashii sae kesshite oshiku nado wa nai' ]; var answerPool = [ 'I Gotta Feeling', 'Cake By the Ocean', 'Replay', 'Roxanne', 'Shape of You', 'Dynamite', 'Billie Jean', 'Call Me Maybe', 'Despacito', 'Just the Way You Are', 'Moves Like Jagger', 'We Found Love', 'All About That Bass', 'Party Rock Anthem', 'Take Me Home, Country Roads', 'Somebody That I Used To Know', 'TT', 'All Star', 'Ocean Man', 'Shinzou wo Sasageyo' ]; var wrongPool = [ ['Its Gonna Be Me', 'Baby One More Time', 'Like a Prayer'], ['Rockstar', 'Dance Monkey', 'Starboy'], ['Thunder', 'Take Me to Church', 'Faded'], ['Despacito', 'Rockstar', 'Counting Stars'], ['Demons', 'Love Yourself', 'Bad Guy'], ['Dont Let Me Down','Bad Guy','Airplanes'], ['Bad Guy','Stay With Me','Bad Romance'], ['Wrecking Ball','Uptown Funk','Radioactive'], ['Hotline Bling','Forget You','Gods Plan'], ['See You Again','Perfect','Somebody That I Used To Know'], ['Payphone','Airplanes','TiK ToK'], ['One More Night','Shake It Off','Firework'], ['Thrift Shop','Bad Guy','Dark Horse'], ['Sexy And I Know It','Love The Way You Lie','Firework'], ['Radioactive','Wrecking Ball','Somebody That I Used To Know'], ['Thinking Out Loud','California Gurls','Lucid Dreams'], ['What is Love','Cheer Up','Fancy'], ['Rockstar','Ocean Man','Perfect'], ['Land Man','Sea Man','Lotion Man'], ['Guren no Yumiya','Boku no sensou','koi no hime hime pettanko'] ]; //generate random number for selecting a random question with its answers function randNum(poolLength){ return Math.floor(Math.random()*poolLength); } //main driver (generates a question per play) module.exports = { name: 'lyrictrivia', cooldown: 11, description: 'lyrics trivia game: guess the song based on the lyrics', execute(message, args) { var rNum = randNum(questionPool.length); //message.channel.send(rNum); message.channel.send('You have 10 seconds to guess the song title of the following piece of lyrics!'); dquiz.ask_question(questionPool[rNum], answerPool[rNum], wrongPool[rNum]); // dquiz.log_question_container(); dquiz.trivia(message, 10); // Runs the trivia command //dquiz.trivia(message, 10, 'ffb7c5'); }, };
30,884
https://github.com/ziegeer/autocert/blob/master/api/utils/docstr.py
Github Open Source
Open Source
MIT
null
autocert
ziegeer
Python
Code
25
84
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import inspect def docstr(): frame = inspect.currentframe().f_back funcname = frame.f_code.co_name globals_ = frame.f_globals func = globals_[funcname] return func.__doc__
13,710
https://github.com/qtothec/pyomo/blob/master/examples/pyomo/diet/diet2.py
Github Open Source
Open Source
BSD-3-Clause
2,020
pyomo
qtothec
Python
Code
216
721
# ___________________________________________________________________________ # # Pyomo: Python Optimization Modeling Objects # Copyright 2017 National Technology and Engineering Solutions of Sandia, LLC # Under the terms of Contract DE-NA0003525 with National Technology and # Engineering Solutions of Sandia, LLC, the U.S. Government retains certain # rights in this software. # This software is distributed under the 3-clause BSD License. # ___________________________________________________________________________ # # Imports # from pyomo.environ import * infinity = float('inf') # # Model # model = AbstractModel() model.NUTR = Set() model.FOOD = Set() model.cost = Param(model.FOOD, within=PositiveReals) model.f_min = Param(model.FOOD, within=NonNegativeReals, default=0.0) def f_max_validate (model, value, j): return model.f_max[j] > model.f_min[j] model.f_max = Param(model.FOOD, validate=f_max_validate, default=infinity) model.n_min = Param(model.NUTR, within=NonNegativeReals, default=0.0) def n_max_validate (model, value, j): return value > model.n_min[j] model.n_max = Param(model.NUTR, validate=n_max_validate, default=infinity) model.amt = Param(model.NUTR, model.FOOD, within=NonNegativeReals) # -------------------------------------------------------- def Buy_bounds(model, i): return (model.f_min[i],model.f_max[i]) model.Buy = Var(model.FOOD, bounds=Buy_bounds, within=NonNegativeIntegers) # -------------------------------------------------------- def Total_Cost_rule(model): ans = 0 for j in model.FOOD: ans = ans + model.cost[j] * model.Buy[j] return ans model.Total_Cost = Objective(rule=Total_Cost_rule, sense=minimize) def Nutr_Amt_rule(model, i): ans = 0 for j in model.FOOD: ans = ans + model.amt[i,j] * model.Buy[j] return ans #model.Nutr_Amt = Objective(model.NUTR, rule=Nutr_Amt_rule) # -------------------------------------------------------- def Diet_rule(model, i): expr = 0 for j in model.FOOD: expr = expr + model.amt[i,j] * model.Buy[j] return (model.n_min[i], expr, model.n_max[i]) model.Diet = Constraint(model.NUTR, rule=Diet_rule)
19,447
https://github.com/zhmu/ananas/blob/master/external/gcc-12.1.0/gcc/config/i386/dragonfly.h
Github Open Source
Open Source
LGPL-2.1-only, FSFAP, LGPL-3.0-only, GPL-3.0-only, GPL-2.0-only, GCC-exception-3.1, LGPL-2.0-or-later, Zlib, LicenseRef-scancode-public-domain, GPL-3.0-or-later
2,022
ananas
zhmu
C++
Code
377
950
/* Definitions for Intel 386 running DragonFly with ELF format Copyright (C) 2014-2022 Free Software Foundation, Inc. Contributed by John Marino <gnugcc@marino.st> This file is part of GCC. GCC is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. GCC 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. Under Section 7 of GPL version 3, you are granted additional permissions described in the GCC Runtime Library Exception, version 3.1, as published by the Free Software Foundation. You should have received a copy of the GNU General Public License and a copy of the GCC Runtime Library Exception along with this program; see the files COPYING3 and COPYING.RUNTIME respectively. If not, see <http://www.gnu.org/licenses/>. */ /* Override the default comment-starter of "/". */ #undef ASM_COMMENT_START #define ASM_COMMENT_START "#" #undef ASM_APP_ON #define ASM_APP_ON "#APP\n" #undef ASM_APP_OFF #define ASM_APP_OFF "#NO_APP\n" #undef DBX_REGISTER_NUMBER #define DBX_REGISTER_NUMBER(n) \ (TARGET_64BIT ? dbx64_register_map[n] : svr4_dbx_register_map[n]) #undef NO_PROFILE_COUNTERS #define NO_PROFILE_COUNTERS 1 /* Tell final.cc that we don't need a label passed to mcount. */ #undef MCOUNT_NAME #define MCOUNT_NAME ".mcount" /* Make gcc agree with <machine/ansi.h>. */ #undef SIZE_TYPE #define SIZE_TYPE (TARGET_64BIT ? "long unsigned int" : "unsigned int") #undef PTRDIFF_TYPE #define PTRDIFF_TYPE (TARGET_64BIT ? "long int" : "int") #undef WCHAR_TYPE_SIZE #define WCHAR_TYPE_SIZE (TARGET_64BIT ? 32 : BITS_PER_WORD) #undef SUBTARGET_EXTRA_SPECS /* i386.h bogusly defines it. */ #define SUBTARGET_EXTRA_SPECS \ { "dfbsd_dynamic_linker", DFBSD_DYNAMIC_LINKER } /* Don't default to pcc-struct-return, we want to retain compatibility with older gcc versions AND pcc-struct-return is nonreentrant. (even though the SVR4 ABI for the i386 says that records and unions are returned in memory). */ #undef DEFAULT_PCC_STRUCT_RETURN #define DEFAULT_PCC_STRUCT_RETURN 0 /* DragonFly sets the rounding precision of the FPU to 53 bits. Let the compiler get the contents of <float.h> and std::numeric_limits correct. */ #undef TARGET_96_ROUND_53_LONG_DOUBLE #define TARGET_96_ROUND_53_LONG_DOUBLE (!TARGET_64BIT) /* Static stack checking is supported by means of probes. */ #define STACK_CHECK_STATIC_BUILTIN 1 /* Support for i386 was removed from DragonFly in 2007 */ #define SUBTARGET32_DEFAULT_CPU "i486" #define TARGET_ASM_FILE_END file_end_indicate_exec_stack
15,715
https://github.com/dr-vij/SpiceSharp/blob/master/SpiceSharp/Components/RLC/Resistors/Parameters.cs
Github Open Source
Open Source
MIT
2,022
SpiceSharp
dr-vij
C#
Code
347
900
using SpiceSharp.ParameterSets; using SpiceSharp.Attributes; namespace SpiceSharp.Components.Resistors { /// <summary> /// Parameters for a <see cref="Resistor" />. /// </summary> /// <seealso cref="ParameterSet"/> [GeneratedParameters] public partial class Parameters : ParameterSet<Parameters> { /// <summary> /// The minimum resistance for any resistor. /// </summary> public const double MinimumResistance = 1e-12; /// <summary> /// Gets or sets the temperature parameter in degrees Kelvin. /// </summary> /// <value> /// The temperature of the resistor. /// </value> [GreaterThan(0), Finite] private GivenParameter<double> _temperature = new GivenParameter<double>(Constants.ReferenceTemperature, false); /// <summary> /// Gets or sets the resistance of the resistor. /// </summary> /// <value> /// The resistance. /// </value> /// <remarks> /// If the resistance is limited to <see cref="MinimumResistance" /> to avoid numerical instability issues. /// If a 0 Ohm resistance is wanted, consider using an ideal voltage source instead. /// </remarks> [ParameterName("resistance"), ParameterName("r"), ParameterInfo("Resistance", Units = "\u03a9", IsPrincipal = true)] [GreaterThanOrEquals(0), LowerLimit(MinimumResistance), Finite] private GivenParameter<double> _resistance; /// <summary> /// Gets or sets the resistor operating temperature in degrees Celsius. /// </summary> /// <value> /// The resistor operating temperature in degrees Celsius. /// </value> [ParameterName("temp"), ParameterInfo("Instance operating temperature", Units = "\u00b0C", Interesting = false)] [DerivedProperty, GreaterThan(-Constants.CelsiusKelvin), Finite] public double TemperatureCelsius { get => Temperature - Constants.CelsiusKelvin; set => Temperature = value + Constants.CelsiusKelvin; } /// <summary> /// Gets or sets the width of the resistor. /// </summary> /// <value> /// The width of the resistor. /// </value> [ParameterName("w"), ParameterInfo("Width", Units = "m")] [GreaterThan(0), Finite] private GivenParameter<double> _width = new GivenParameter<double>(1.0, false); /// <summary> /// Gets or sets the length of the resistor. /// </summary> /// <value> /// The length of the resistor. /// </value> [ParameterName("l"), ParameterInfo("Length", Units = "m")] [GreaterThanOrEquals(0), Finite] private GivenParameter<double> _length; /// <summary> /// Gets or sets the number of resistors in parallel. /// </summary> /// <value> /// The number of resistors in parallel. /// </value> [ParameterName("m"), ParameterInfo("Parallel multiplier")] [GreaterThanOrEquals(0), Finite] private double _parallelMultiplier = 1.0; /// <summary> /// Gets or sets the number of resistors in series. /// </summary> /// <value> /// The number of resistors in series. /// </value> [ParameterName("n"), ParameterInfo("Series multiplier")] [GreaterThan(0), Finite] private double _seriesMultiplier = 1.0; } }
12,211
https://github.com/AdaCore/spat/blob/master/src/util/gnatcoll-opt_parse-extension.adb
Github Open Source
Open Source
WTFPL
2,020
spat
AdaCore
Ada
Code
667
1,612
------------------------------------------------------------------------------ -- G N A T C O L L -- -- -- -- Copyright (C) 2009-2019, AdaCore -- -- Copyright (C) 2020, Heisenbug Ltd. -- -- -- -- This library is free software; you can redistribute it and/or modify it -- -- under terms of the GNU General Public License as published by the Free -- -- Software Foundation; either version 3, or (at your option) any later -- -- version. This library is distributed in the hope that it will be useful, -- -- but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN- -- -- TABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- ------------------------------------------------------------------------------ with Ada.Characters.Handling; package body GNATCOLL.Opt_Parse.Extension is function "+" (Self : in String) return XString renames To_XString; function "+" (Self : in XString) return String renames To_String; function Parse_One_Option (Short, Long : in String; Args : in XString_Array; Pos : in Positive; New_Pos : out Parser_Return) return XString; --------------------------------------------------------------------------- -- Parse_One_Option --------------------------------------------------------------------------- function Parse_One_Option (Short : in String; Long : in String; Args : in XString_Array; Pos : in Positive; New_Pos : out Parser_Return) return XString is begin if Args (Pos) = Long or else (Short /= "" and then Args (Pos) = Short) then if Pos + 1 > Args'Last or else Args (Pos + 1).Starts_With ("-") then -- No more arguments or already next option. New_Pos := Pos + 1; return Null_XString; end if; New_Pos := Pos + 2; return Args (Pos + 1); elsif Args (Pos).Starts_With (Long & "=") then New_Pos := Pos + 1; return Args (Pos).Slice (Long'Last + 2, Args (Pos).Length); elsif Short /= "" and then Args (Pos).Starts_With (Short) then New_Pos := Pos + 1; return Args (Pos).Slice (Short'Last + 1, Args (Pos).Length); else New_Pos := Error_Return; return +""; end if; end Parse_One_Option; package body Parse_Option_With_Default is type Option_Parser is new GNATCOLL.Opt_Parse.Parser_Type with null record; overriding function Usage (Self : Option_Parser) return String is ("[" & Long & (if Short = "" then "" else "|" & Short) & " " & Ada.Characters.Handling.To_Upper (Long (3 .. Long'Last)) & "]"); overriding function Help_Name (Dummy : Option_Parser) return String is (Long & ", " & Short); overriding function Parse_Args (Self : in out Option_Parser; Args : in XString_Array; Pos : in Positive; Result : in out Parsed_Arguments) return Parser_Return; type Internal_Result is new Parser_Result with record Result : Arg_Type; end record; type Internal_Result_Access is access all Internal_Result; overriding procedure Release (Self : in out Internal_Result) is null; Self_Val : aliased Option_Parser := Option_Parser'(Name => +Long (3 .. Long'Last), Help => +Help, Parser => Parser.Data, Opt => True, Position => <>); Self : constant Parser_Access := Self_Val'Unchecked_Access; ------------------------------------------------------------------------ -- Get ------------------------------------------------------------------------ function Get (Args : Parsed_Arguments := No_Parsed_Arguments) return Arg_Type is begin if not Enabled then return Default_Val; end if; declare R : constant Parser_Result_Access := Self.Get_Result (Args); begin if R /= null then return Internal_Result (R.all).Result; else return Default_Val; end if; end; end Get; ------------------------------------------------------------------------ -- Parse_Args ------------------------------------------------------------------------ overriding function Parse_Args (Self : in out Option_Parser; Args : in XString_Array; Pos : in Positive; Result : in out Parsed_Arguments) return Parser_Return is New_Pos : Parser_Return; Raw : constant XString := Parse_One_Option (Short, Long, Args, Pos, New_Pos); begin if New_Pos /= Error_Return then declare Res : constant Internal_Result_Access := new Internal_Result'(Start_Pos => Pos, End_Pos => Pos, Result => Convert (+Raw)); begin Result.Ref.Get.Results (Self.Position) := Res.all'Unchecked_Access; end; end if; return New_Pos; end Parse_Args; begin if Enabled then Parser.Data.Opts_Parsers.Append (Self); Parser.Data.All_Parsers.Append (Self); Self.Position := Parser.Data.All_Parsers.Last_Index; end if; end Parse_Option_With_Default; end GNATCOLL.Opt_Parse.Extension;
36,056
https://github.com/sergeyrachev/sandstream/blob/master/test/mock_callback_pat.h
Github Open Source
Open Source
MIT
null
sandstream
sergeyrachev
C
Code
23
99
#pragma once #include "matcher.h" #include "callback_pat.h" namespace mock{ class callback_pat_t : public challenge::callback_pat_t{ public: callback_pat_t(); ~callback_pat_t() final; MOCK_METHOD1(on_pat, void(const challenge::pat_t &update)); }; }
12,489
https://github.com/strengthandwill/wiki-contacts-android/blob/master/src/com/kahkong/wikicontacts/service/PreferencesServiceImpl.java
Github Open Source
Open Source
Apache-2.0
2,014
wiki-contacts-android
strengthandwill
Java
Code
135
458
package com.kahkong.wikicontacts.service; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.preference.PreferenceManager; /** * * @author Poh Kah Kong * */ public class PreferencesServiceImpl implements PreferencesService { private static PreferencesService instance; private final boolean BOOLEAN_DEFAULTVALUE = false; private final String CALLERID_KEY = "callerid"; private final String INFOHIDDEN_KEY = "infohidden"; private SharedPreferences sharedPreferences; private PreferencesServiceImpl() { } public synchronized static PreferencesService getInstance() { if (instance==null) { instance = new PreferencesServiceImpl(); } return instance; } public void setSharedPreferences(Context context) { sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); } public boolean getCallerId() { return getBoolean(CALLERID_KEY); } public void setCallerId(boolean value) { setBoolean(CALLERID_KEY, value); } public boolean getInfoHidden() { return getBoolean(INFOHIDDEN_KEY); } public void setInfoHidden(boolean value) { setBoolean(INFOHIDDEN_KEY, value); } public boolean getBoolean(String key) { return sharedPreferences.getBoolean(key, BOOLEAN_DEFAULTVALUE); } public void setBoolean(String key, boolean value) { Editor editor = sharedPreferences.edit(); editor.putBoolean(key, value); editor.commit(); } }
40,638
https://github.com/viant/datly/blob/master/router/marshal/json/marshaller_uint.go
Github Open Source
Open Source
Apache-2.0
2,023
datly
viant
Go
Code
389
1,468
package json import ( "github.com/francoispqt/gojay" "github.com/viant/xunsafe" "strconv" "unsafe" ) type uintMarshaller struct { defaultValue string dTag *DefaultTag } func newUintMarshaller(dTag *DefaultTag) *uintMarshaller { var zeroValue uint if dTag._value != nil { zeroValue, _ = dTag._value.(uint) } return &uintMarshaller{ dTag: dTag, defaultValue: strconv.Itoa(int(zeroValue)), } } func (i *uintMarshaller) MarshallObject(ptr unsafe.Pointer, sb *MarshallSession) error { asUint := xunsafe.AsUint(ptr) if asUint == 0 { sb.WriteString(i.defaultValue) return nil } return appendInt(int(asUint), sb) } func (i *uintMarshaller) UnmarshallObject(pointer unsafe.Pointer, decoder *gojay.Decoder, auxiliaryDecoder *gojay.Decoder, session *UnmarshalSession) error { return decoder.AddUint64(xunsafe.AsUint64Ptr(pointer)) } type uint8Marshaller struct { defaultValue string dTag *DefaultTag } func newUint8Marshaller(tag *DefaultTag) *uint8Marshaller { var zeroValue uint8 if tag._value != nil { zeroValue, _ = tag._value.(uint8) } return &uint8Marshaller{ defaultValue: strconv.Itoa(int(zeroValue)), dTag: tag, } } func (i *uint8Marshaller) MarshallObject(ptr unsafe.Pointer, sb *MarshallSession) error { asUint8 := xunsafe.AsUint8(ptr) if asUint8 == 0 { sb.WriteString(i.defaultValue) return nil } return appendInt(int(asUint8), sb) } func (i *uint8Marshaller) UnmarshallObject(pointer unsafe.Pointer, decoder *gojay.Decoder, auxiliaryDecoder *gojay.Decoder, session *UnmarshalSession) error { return decoder.AddUint8((*uint8)(pointer)) } type uint16Marshaller struct { zeroValue string dTag *DefaultTag } func newUint16Marshaller(dTag *DefaultTag) *uint16Marshaller { var zeroValue uint16 if dTag._value != nil { zeroValue, _ = dTag._value.(uint16) } return &uint16Marshaller{ zeroValue: strconv.Itoa(int(zeroValue)), dTag: dTag, } } func (i *uint16Marshaller) MarshallObject(ptr unsafe.Pointer, sb *MarshallSession) error { asUint16 := xunsafe.AsUint16(ptr) if asUint16 == 0 { sb.WriteString(i.zeroValue) return nil } return appendInt(int(asUint16), sb) } func (i *uint16Marshaller) UnmarshallObject(pointer unsafe.Pointer, decoder *gojay.Decoder, auxiliaryDecoder *gojay.Decoder, session *UnmarshalSession) error { return decoder.AddUint16((*uint16)(pointer)) } type uint32Marshaller struct { zeroValue string dTag *DefaultTag } func newUint32Marshaller(dTag *DefaultTag) *uint32Marshaller { var zeroValue uint32 if dTag._value != nil { zeroValue, _ = dTag._value.(uint32) } return &uint32Marshaller{ zeroValue: strconv.Itoa(int(zeroValue)), dTag: dTag, } } func (i *uint32Marshaller) MarshallObject(ptr unsafe.Pointer, sb *MarshallSession) error { asUint32 := xunsafe.AsUint32(ptr) if asUint32 == 0 { sb.WriteString(i.zeroValue) return nil } return appendInt(int(asUint32), sb) } func (i *uint32Marshaller) UnmarshallObject(pointer unsafe.Pointer, decoder *gojay.Decoder, auxiliaryDecoder *gojay.Decoder, session *UnmarshalSession) error { return decoder.AddUint32((*uint32)((pointer))) } type uint64Marshaller struct { zeroValue string dTag *DefaultTag } func newUint64Marshaller(dTag *DefaultTag) *uint64Marshaller { var zeroValue uint64 if dTag._value != nil { zeroValue, _ = dTag._value.(uint64) } return &uint64Marshaller{ zeroValue: strconv.Itoa(int(zeroValue)), dTag: dTag, } } func (i *uint64Marshaller) MarshallObject(ptr unsafe.Pointer, sb *MarshallSession) error { asUint64 := xunsafe.AsUint64(ptr) if asUint64 == 0 { sb.WriteString(i.zeroValue) return nil } return appendInt(int(asUint64), sb) } func (i *uint64Marshaller) UnmarshallObject(pointer unsafe.Pointer, decoder *gojay.Decoder, auxiliaryDecoder *gojay.Decoder, session *UnmarshalSession) error { return decoder.AddUint64((*uint64)((pointer))) }
45,788
https://github.com/WXM99/SE228_SpringbootDemo/blob/master/ebook-backend/src/516015910018-hw2/main/java/ebook/controller/BookInfoController.java
Github Open Source
Open Source
MIT
2,019
SE228_SpringbootDemo
WXM99
Java
Code
168
699
package ebook.controller; import ebook.model.BookDetails; import ebook.model.BookInOrder; import ebook.model.BookInfoBrief; import ebook.model.outOfDB.WholeBook; import ebook.repository.BookRepository; import ebook.service.BookService; import net.sf.json.JSONObject; import org.hibernate.annotations.Source; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.web.bind.annotation.*; import java.awt.print.Book; import java.io.IOException; import java.util.List; import java.util.Map; @RestController @RequestMapping(value="/api") @CrossOrigin("*") public class BookInfoController { @Autowired private BookService bookService; @RequestMapping(value = "/get_all_book", method = RequestMethod.POST, produces = "application/json;charset=UTF-8") @ResponseBody public List<BookInfoBrief> get_all_book() throws IOException { return this.bookService.allBook(); } @RequestMapping(value = "/find_book", method = RequestMethod.POST, produces = "application/json;charset=UTF-8") @ResponseBody public BookInfoBrief find_book(@RequestBody JSONObject input) throws IOException { return this.bookService.findBook(input); } @RequestMapping(value = "/find_whole_book", method = RequestMethod.POST, produces = "application/json;charset=UTF-8") @ResponseBody public WholeBook find_whole_book(@RequestBody JSONObject input) throws IOException { return this.bookService.find(input); } @RequestMapping(value = "/find_book_with_page", method = RequestMethod.POST, produces = "application/json;charset=UTF-8") @ResponseBody public List<BookInfoBrief> find_book_with_page(@RequestBody JSONObject input) throws IOException { return this.bookService.findBookWithPage(input); } @RequestMapping(value = "/search_book", method = RequestMethod.POST, produces = "application/json;charset=UTF-8") @ResponseBody public List<BookInfoBrief> search_book(@RequestBody JSONObject input) throws IOException { return this.bookService.searchBook(input); } @RequestMapping(value = "/add_details", method = RequestMethod.POST, produces = "application/json;charset=UTF-8") @ResponseBody public BookDetails add_details(@RequestBody JSONObject input) throws IOException { return this.bookService.addDetails(input); } }
35,070
https://github.com/123FLO321/SwiftTileserverCache/blob/master/Sources/SwiftTileserverCache/Model/Style.swift
Github Open Source
Open Source
MIT
2,021
SwiftTileserverCache
123FLO321
Swift
Code
30
67
// // Style.swift // SwiftTileserverCache // // Created by Florian Kostenzer on 03.03.20. // import Vapor public struct Style: Content { public var id: String public var name: String }
9,605
https://github.com/xiacijie/omr-wala-linkage/blob/master/third_party/omr/gc/structs/HashTableIterator.cpp
Github Open Source
Open Source
Apache-2.0
null
omr-wala-linkage
xiacijie
C++
Code
277
697
/******************************************************************************* * Copyright (c) 1991, 2016 IBM Corp. and others * * This program and the accompanying materials are made available under * the terms of the Eclipse Public License 2.0 which accompanies this * distribution and is available at https://www.eclipse.org/legal/epl-2.0/ * or the Apache License, Version 2.0 which accompanies this distribution and * is available at https://www.apache.org/licenses/LICENSE-2.0. * * This Source Code may also be made available under the following * Secondary Licenses when the conditions for such availability set * forth in the Eclipse Public License, v. 2.0 are satisfied: GNU * General Public License, version 2 with the GNU Classpath * Exception [1] and GNU General Public License, version 2 with the * OpenJDK Assembly Exception [2]. * * [1] https://www.gnu.org/software/classpath/license.html * [2] http://openjdk.java.net/legal/assembly-exception.html * * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception *******************************************************************************/ /** * @file * @ingroup GC_Structs */ #include "HashTableIterator.hpp" #include "Debug.hpp" /** * \brief Get the next slot of a J9HashTable * \ingroup GC_Structs * * @return A slot pointer (NULL when no more slots) * * Continues the interation of all nodes in a J9HashTable * */ void ** GC_HashTableIterator::nextSlot() { void **value; if (_firstIteration) { _firstIteration = false; value = (void **)hashTableStartDo(_hashTable, &_handle); } else { value = (void **)hashTableNextDo(&_handle); } return value; } /** * \brief Remove the current slot in a J9HashTable * \ingroup GC_Structs * * Removes the current slot in a J9HashTable (not valid in Out Of Process) * */ void GC_HashTableIterator::removeSlot() { hashTableDoRemove(&_handle); } void GC_HashTableIterator::disableTableGrowth() { hashTableSetFlag(_hashTable, J9HASH_TABLE_DO_NOT_REHASH); } /** * Re-enable table growth which has been disabled by disableTableGrowth(). */ void GC_HashTableIterator::enableTableGrowth() { hashTableResetFlag(_hashTable, J9HASH_TABLE_DO_NOT_REHASH); }
38,777
https://github.com/i-gaven/Just_a_dumper/blob/master/all_headers/百度贴吧-全球最大中文兴趣社区-9.3.8(越狱应用)_headers/TBCPicFilterView.h
Github Open Source
Open Source
MIT
2,018
Just_a_dumper
i-gaven
Objective-C
Code
113
446
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard. // #import "TBCAutoLayoutScrollView.h" @class NSArray, NSMutableArray; @protocol TBCPicEditorProtocol; @interface TBCPicFilterView : TBCAutoLayoutScrollView { id <TBCPicEditorProtocol> _filterDelegate; NSMutableArray *_filterButtonArray; NSArray *_filterArray; NSArray *_filterNameArray; } @property(copy, nonatomic) NSArray *filterNameArray; // @synthesize filterNameArray=_filterNameArray; @property(copy, nonatomic) NSArray *filterArray; // @synthesize filterArray=_filterArray; @property(retain, nonatomic) NSMutableArray *filterButtonArray; // @synthesize filterButtonArray=_filterButtonArray; @property(nonatomic) __weak id <TBCPicEditorProtocol> filterDelegate; // @synthesize filterDelegate=_filterDelegate; - (void).cxx_destruct; - (void)onSetFilterWithIndex:(unsigned long long)arg1; - (void)filterIconImage:(id)arg1 WithIndex:(unsigned long long)arg2; - (void)filterPic:(id)arg1; - (void)updateFilterSelectionWithFilterIndex:(long long)arg1; - (id)createFilterButtonWithIndex:(unsigned long long)arg1; - (void)setupCurrentButtonWithIndex:(unsigned long long)arg1; - (void)setupUI; - (void)setupFilterArray; - (void)dealloc; - (id)initWithFrame:(struct CGRect)arg1; @end
40,846
https://github.com/markmckinnon/cLeapp/blob/master/scripts/artifacts/googleDocs.py
Github Open Source
Open Source
Apache-2.0
2,022
cLeapp
markmckinnon
Python
Code
295
1,077
import os import sqlite3 import datetime from scripts.artifact_report import ArtifactHtmlReport from scripts.cleapfuncs import logfunc, tsv, timeline, is_platform_windows, open_sqlite_db_readonly, does_column_exist_in_db def get_editor(file_found): if 'slides' in file_found.lower(): return 'Google Slides' elif 'sheets' in file_found.lower(): return 'Google Sheets' else: return 'Google Docs' def get_googleDocs(files_found, report_folder, seeker, wrap_text): source_file = '' for file_found in files_found: file_name = str(file_found) if (file_name.lower().endswith('doclist.db')): app_name = get_editor(file_found) db = open_sqlite_db_readonly(file_name) cursor = db.cursor() cursor.execute(''' select accountHolderName, dbFilePath, datetime(lastAppMetadataSyncTime/1000, 'unixepoch') as LastAppMetadataSynctime from appMetadata244, account244 where account_id = account;''') all_rows = cursor.fetchall() usageentries = len(all_rows) if usageentries > 0: report = ArtifactHtmlReport(f'{app_name} - Metadata Files') report.start_artifact_report(report_folder, f'{app_name} - Metadata Files') report.add_script() data_headers = ('account_holder_name', 'db_file_path', 'LastAppMetadataSynctime') # Don't remove the comma, that is required to make this a tuple as there is only 1 element data_list = [] for row in all_rows: data_list.append((row[0], row[1], row[2])) report.write_artifact_data_table(data_headers, data_list, file_found) report.end_artifact_report() tsvname = f'{app_name} - Metadata Files' tsv(report_folder, data_headers, data_list, tsvname, source_file) tlactivity = f'{app_name} - Metadata Files' timeline(report_folder, tlactivity, data_list, data_headers) else: logfunc(f'No {app_name} - Metadata Files found') db.close continue if (file_name.lower().endswith('storage.db')): # skip -journal and other files app_name = get_editor(file_found) db = open_sqlite_db_readonly(file_name) cursor = db.cursor() cursor.execute(''' select path, sizeInBytes, key, type from stash left join DocumentStorageMetadata on stashId = stash.rowid;''') all_rows = cursor.fetchall() usageentries = len(all_rows) if usageentries > 0: report = ArtifactHtmlReport(f'{app_name} - Stash Files') report.start_artifact_report(report_folder, f'{app_name} - Stash Files') report.add_script() data_headers = ('path', 'size_in_bytes', 'key', 'type') # Don't remove the comma, that is required to make this a tuple as there is only 1 element data_list = [] for row in all_rows: data_list.append((row[0], row[1], row[2], row[3])) report.write_artifact_data_table(data_headers, data_list, file_found) report.end_artifact_report() tsvname = f'{app_name} - Stash Files' tsv(report_folder, data_headers, data_list, tsvname, source_file) tlactivity = f'{app_name} - Stash Files' timeline(report_folder, tlactivity, data_list, data_headers) else: logfunc(f'No {app_name} - Stash Files found') db.close continue return
25,424
https://github.com/JackFish/jfinal-weixin/blob/master/src/com/jfinal/weixin/sdk/msg/InMsgParser.java
Github Open Source
Open Source
Apache-2.0
2,022
jfinal-weixin
JackFish
Java
Code
1,029
5,437
/** * Copyright (c) 2011-2014, James Zhan 詹波 (jfinal@126.com). * * Licensed under the Apache License, Version 2.0 (the "License"); */ package com.jfinal.weixin.sdk.msg; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import com.jfinal.weixin.sdk.msg.in.event.InVerifyFailEvent; import com.jfinal.weixin.sdk.msg.in.event.InVerifySuccessEvent; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element; import com.jfinal.kit.StrKit; import com.jfinal.weixin.sdk.msg.in.InImageMsg; import com.jfinal.weixin.sdk.msg.in.InLinkMsg; import com.jfinal.weixin.sdk.msg.in.InLocationMsg; import com.jfinal.weixin.sdk.msg.in.InMsg; import com.jfinal.weixin.sdk.msg.in.InShortVideoMsg; import com.jfinal.weixin.sdk.msg.in.InTextMsg; import com.jfinal.weixin.sdk.msg.in.InVideoMsg; import com.jfinal.weixin.sdk.msg.in.InVoiceMsg; import com.jfinal.weixin.sdk.msg.in.event.InCustomEvent; import com.jfinal.weixin.sdk.msg.in.event.InFollowEvent; import com.jfinal.weixin.sdk.msg.in.event.InLocationEvent; import com.jfinal.weixin.sdk.msg.in.event.InMassEvent; import com.jfinal.weixin.sdk.msg.in.event.InMenuEvent; import com.jfinal.weixin.sdk.msg.in.event.InQrCodeEvent; import com.jfinal.weixin.sdk.msg.in.event.InShakearoundUserShakeEvent; import com.jfinal.weixin.sdk.msg.in.event.InShakearoundUserShakeEvent.AroundBeacon; import com.jfinal.weixin.sdk.msg.in.event.InTemplateMsgEvent; import com.jfinal.weixin.sdk.msg.in.event.ScanCodeInfo; import com.jfinal.weixin.sdk.msg.in.speech_recognition.InSpeechRecognitionResults; public class InMsgParser { private InMsgParser() {} /** * 从 xml 中解析出各类消息与事件 */ public static InMsg parse(String xml) { try { return doParse(xml); } catch (DocumentException e) { throw new RuntimeException(e); } } /** * 消息类型 * 1:text 文本消息 * 2:image 图片消息 * 3:voice 语音消息 * 4:video 视频消息 * shortvideo 小视频消息 * 5:location 地址位置消息 * 6:link 链接消息 * 7:event 事件 */ private static InMsg doParse(String xml) throws DocumentException { Document doc = DocumentHelper.parseText(xml); Element root = doc.getRootElement(); String toUserName = root.elementText("ToUserName"); String fromUserName = root.elementText("FromUserName"); Integer createTime = Integer.parseInt(root.elementText("CreateTime")); String msgType = root.elementText("MsgType"); if ("text".equals(msgType)) return parseInTextMsg(root, toUserName, fromUserName, createTime, msgType); if ("image".equals(msgType)) return parseInImageMsg(root, toUserName, fromUserName, createTime, msgType); if ("voice".equals(msgType)) return parseInVoiceMsgAndInSpeechRecognitionResults(root, toUserName, fromUserName, createTime, msgType); if ("video".equals(msgType)) return parseInVideoMsg(root, toUserName, fromUserName, createTime, msgType); if ("shortvideo".equals(msgType)) //支持小视频 return parseInShortVideoMsg(root, toUserName, fromUserName, createTime, msgType); if ("location".equals(msgType)) return parseInLocationMsg(root, toUserName, fromUserName, createTime, msgType); if ("link".equals(msgType)) return parseInLinkMsg(root, toUserName, fromUserName, createTime, msgType); if ("event".equals(msgType)) return parseInEvent(root, toUserName, fromUserName, createTime, msgType); throw new RuntimeException("无法识别的消息类型 " + msgType + ",请查阅微信公众平台开发文档"); } private static InMsg parseInTextMsg(Element root, String toUserName, String fromUserName, Integer createTime, String msgType) { InTextMsg msg = new InTextMsg(toUserName, fromUserName, createTime, msgType); msg.setContent(root.elementText("Content")); msg.setMsgId(root.elementText("MsgId")); return msg; } private static InMsg parseInImageMsg(Element root, String toUserName, String fromUserName, Integer createTime, String msgType) { InImageMsg msg = new InImageMsg(toUserName, fromUserName, createTime, msgType); msg.setPicUrl(root.elementText("PicUrl")); msg.setMediaId(root.elementText("MediaId")); msg.setMsgId(root.elementText("MsgId")); return msg; } private static InMsg parseInVoiceMsgAndInSpeechRecognitionResults(Element root, String toUserName, String fromUserName, Integer createTime, String msgType) { String recognition = root.elementText("Recognition"); if (StrKit.isBlank(recognition)) { InVoiceMsg msg = new InVoiceMsg(toUserName, fromUserName, createTime, msgType); msg.setMediaId(root.elementText("MediaId")); msg.setFormat(root.elementText("Format")); msg.setMsgId(root.elementText("MsgId")); return msg; } else { InSpeechRecognitionResults msg = new InSpeechRecognitionResults(toUserName, fromUserName, createTime, msgType); msg.setMediaId(root.elementText("MediaId")); msg.setFormat(root.elementText("Format")); msg.setMsgId(root.elementText("MsgId")); msg.setRecognition(recognition); // 与 InVoiceMsg 唯一的不同之处 return msg; } } private static InMsg parseInVideoMsg(Element root, String toUserName, String fromUserName, Integer createTime, String msgType) { InVideoMsg msg = new InVideoMsg(toUserName, fromUserName, createTime, msgType); msg.setMediaId(root.elementText("MediaId")); msg.setThumbMediaId(root.elementText("ThumbMediaId")); msg.setMsgId(root.elementText("MsgId")); return msg; } private static InMsg parseInShortVideoMsg(Element root, String toUserName, String fromUserName, Integer createTime, String msgType) { InShortVideoMsg msg = new InShortVideoMsg(toUserName, fromUserName, createTime, msgType); msg.setMediaId(root.elementText("MediaId")); msg.setThumbMediaId(root.elementText("ThumbMediaId")); msg.setMsgId(root.elementText("MsgId")); return msg; } private static InMsg parseInLocationMsg(Element root, String toUserName, String fromUserName, Integer createTime, String msgType) { InLocationMsg msg = new InLocationMsg(toUserName, fromUserName, createTime, msgType); msg.setLocation_X(root.elementText("Location_X")); msg.setLocation_Y(root.elementText("Location_Y")); msg.setScale(root.elementText("Scale")); msg.setLabel(root.elementText("Label")); msg.setMsgId(root.elementText("MsgId")); return msg; } private static InMsg parseInLinkMsg(Element root, String toUserName, String fromUserName, Integer createTime, String msgType) { InLinkMsg msg = new InLinkMsg(toUserName, fromUserName, createTime, msgType); msg.setTitle(root.elementText("Title")); msg.setDescription(root.elementText("Description")); msg.setUrl(root.elementText("Url")); msg.setMsgId(root.elementText("MsgId")); return msg; } // 解析各种事件 @SuppressWarnings("rawtypes") private static InMsg parseInEvent(Element root, String toUserName, String fromUserName, Integer createTime, String msgType) { String event = root.elementText("Event"); String eventKey = root.elementText("EventKey"); // 关注/取消关注事件(包括二维码扫描关注,二维码扫描关注事件与扫描带参数二维码事件是两回事) if (("subscribe".equals(event) || "unsubscribe".equals(event)) && StrKit.isBlank(eventKey)) { return new InFollowEvent(toUserName, fromUserName, createTime, msgType, event); } // 扫描带参数二维码事件之一 1: 用户未关注时,进行关注后的事件推送 String ticket = root.elementText("Ticket"); if ("subscribe".equals(event) && StrKit.notBlank(eventKey) && eventKey.startsWith("qrscene_")) { InQrCodeEvent e = new InQrCodeEvent(toUserName, fromUserName, createTime, msgType, event); e.setEventKey(eventKey); e.setTicket(ticket); return e; } // 扫描带参数二维码事件之二 2: 用户已关注时的事件推送 if ("SCAN".equals(event)) { InQrCodeEvent e = new InQrCodeEvent(toUserName, fromUserName, createTime, msgType, event); e.setEventKey(eventKey); e.setTicket(ticket); return e; } // 上报地理位置事件 if ("LOCATION".equals(event)) { InLocationEvent e = new InLocationEvent(toUserName, fromUserName, createTime, msgType, event); e.setLatitude(root.elementText("Latitude")); e.setLongitude(root.elementText("Longitude")); e.setPrecision(root.elementText("Precision")); return e; } // 自定义菜单事件之一 1:点击菜单拉取消息时的事件推送 if ("CLICK".equals(event)) { InMenuEvent e = new InMenuEvent(toUserName, fromUserName, createTime, msgType, event); e.setEventKey(eventKey); return e; } // 自定义菜单事件之二 2:点击菜单跳转链接时的事件推送 if ("VIEW".equals(event)) { InMenuEvent e = new InMenuEvent(toUserName, fromUserName, createTime, msgType, event); e.setEventKey(eventKey); return e; } // 扫码推事件 if ("scancode_push".equals(event)) { InMenuEvent e = new InMenuEvent(toUserName, fromUserName, createTime, msgType, event); e.setEventKey(eventKey); Element scanCodeInfo = root.element("ScanCodeInfo"); String scanType = scanCodeInfo.elementText("ScanType"); String scanResult = scanCodeInfo.elementText("ScanResult"); e.setScanCodeInfo(new ScanCodeInfo(scanType, scanResult)); return e; } // 扫码推事件且弹出“消息接收中”提示框 if ("scancode_waitmsg".equals(event)) { InMenuEvent e = new InMenuEvent(toUserName, fromUserName, createTime, msgType, event); e.setEventKey(eventKey); Element scanCodeInfo = root.element("ScanCodeInfo"); String scanType = scanCodeInfo.elementText("ScanType"); String scanResult = scanCodeInfo.elementText("ScanResult"); e.setScanCodeInfo(new ScanCodeInfo(scanType, scanResult)); return e; } // 5. pic_sysphoto:弹出系统拍照发图,这个后台其实收不到该菜单的消息,点击它后,调用的是手机里面的照相机功能,而照相以后再发过来时,就收到的是一个图片消息了 if ("pic_sysphoto".equals(event)) { InMenuEvent e = new InMenuEvent(toUserName, fromUserName, createTime, msgType, event); e.setEventKey(eventKey); return e; } // pic_photo_or_album:弹出拍照或者相册发图 if ("pic_photo_or_album".equals(event)) { InMenuEvent e = new InMenuEvent(toUserName, fromUserName, createTime, msgType, event); e.setEventKey(eventKey); return e; } // pic_weixin:弹出微信相册发图器 if ("pic_weixin".equals(event)) { InMenuEvent e = new InMenuEvent(toUserName, fromUserName, createTime, msgType, event); e.setEventKey(eventKey); return e; } // location_select:弹出地理位置选择器 if ("location_select".equals(event)) { InMenuEvent e = new InMenuEvent(toUserName, fromUserName, createTime, msgType, event); e.setEventKey(eventKey); return e; } // media_id:下发消息(除文本消息) if ("media_id".equals(event)) { InMenuEvent e = new InMenuEvent(toUserName, fromUserName, createTime, msgType, event); e.setEventKey(eventKey); return e; } // view_limited:跳转图文消息URL if ("view_limited".equals(event)) { InMenuEvent e = new InMenuEvent(toUserName, fromUserName, createTime, msgType, event); e.setEventKey(eventKey); return e; } // 模板消息是否送达成功通知事件 if ("TEMPLATESENDJOBFINISH".equals(event)) { InTemplateMsgEvent e = new InTemplateMsgEvent(toUserName, fromUserName, createTime, msgType, event); e.setMsgId(root.elementText("MsgID")); e.setStatus(root.elementText("Status")); return e; } // 群发任务结束时是否送达成功通知事件 if ("MASSSENDJOBFINISH".equals(event)) { InMassEvent e = new InMassEvent(toUserName, fromUserName, createTime, msgType, event); e.setMsgId(root.elementText("MsgID")); e.setStatus(root.elementText("Status")); e.setTotalCount(root.elementText("TotalCount")); e.setFilterCount(root.elementText("FilterCount")); e.setSentCount(root.elementText("SentCount")); e.setErrorCount(root.elementText("ErrorCount")); return e; } // 多客服接入会话事件 if ("kf_create_session".equals(event)) { InCustomEvent e = new InCustomEvent(toUserName, fromUserName, createTime, msgType, event); e.setKfAccount(root.elementText("KfAccount")); return e; } // 多客服关闭会话事件 if ("kf_close_session".equals(event)) { InCustomEvent e = new InCustomEvent(toUserName, fromUserName, createTime, msgType, event); e.setKfAccount(root.elementText("KfAccount")); return e; } // 多客服转接会话事件 if ("kf_switch_session".equals(event)) { InCustomEvent e = new InCustomEvent(toUserName, fromUserName, createTime, msgType, event); e.setKfAccount(root.elementText("KfAccount")); e.setToKfAccount(root.elementText("ToKfAccount")); return e; } // 微信摇一摇事件 if ("ShakearoundUserShake".equals(event)){ InShakearoundUserShakeEvent e = new InShakearoundUserShakeEvent(toUserName, fromUserName, createTime, msgType); e.setEvent(event); Element c = root.element("ChosenBeacon"); e.setUuid(c.elementText("Uuid")); e.setMajor(Integer.parseInt(c.elementText("Major"))); e.setMinor(Integer.parseInt(c.elementText("Minor"))); e.setDistance(Float.parseFloat(c.elementText("Distance"))); List list = root.elements("AroundBeacon"); if (list != null && list.size() > 0) { AroundBeacon aroundBeacon = null; List<AroundBeacon> aroundBeacons = new ArrayList<AroundBeacon>(); for (Iterator it = list.iterator(); it.hasNext();) { Element elm = (Element) it.next(); aroundBeacon = new AroundBeacon(); aroundBeacon.setUuid(elm.elementText("Uuid")); aroundBeacon.setMajor(Integer.parseInt(elm.elementText("Major"))); aroundBeacon.setMinor(Integer.parseInt(elm.elementText("Minor"))); aroundBeacon.setDistance(Float.parseFloat(elm.elementText("Distance"))); aroundBeacons.add(aroundBeacon); } e.setAroundBeaconList(aroundBeacons); } return e; } // 资质认证成功 || 名称认证成功 || 年审通知 || 认证过期失效通知 if ("qualification_verify_success".equals(event) || "naming_verify_success".equals(event) || "annual_renew".equals(event) || "verify_expired".equals(event)) { InVerifySuccessEvent e = new InVerifySuccessEvent(toUserName, fromUserName, createTime, msgType, event); e.setExpiredTime(root.elementText("expiredTime")); return e; } // 资质认证失败 || 名称认证失败 if ("qualification_verify_fail".equals(event) || "naming_verify_fail".equals(event)) { InVerifyFailEvent e = new InVerifyFailEvent(toUserName, fromUserName, createTime, msgType, event); e.setFailTime(root.elementText("failTime")); e.setFailReason(root.elementText("failReason")); return e; } throw new RuntimeException("无法识别的事件类型" + event + ",请查阅微信公众平台开发文档"); } }
49,351
https://github.com/kbsriram/thormor/blob/master/src/cli/org/thormor/cli/CShowCommand.java
Github Open Source
Open Source
JSON, MIT, BSD-2-Clause
2,012
thormor
kbsriram
Java
Code
404
1,376
package org.thormor.cli; import org.thormor.vault.CLinkedVault; import org.thormor.vault.CVault; import org.thormor.provider.IProgressMonitor; import java.util.List; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.Calendar; import java.text.SimpleDateFormat; import java.io.IOException; import java.io.File; import org.json2012.JSONObject; import org.json2012.JSONArray; import org.json2012.JSONException; class CShowCommand implements ICommand { public void process(String args[]) { List<CLinkedVault> recip = U.getRecipients(args, 1); if (recip == null) { return; } ArrayList<JSONObject> messages = new ArrayList<JSONObject>(); for (CLinkedVault lv: recip) { try { mergeMessages(messages, lv); } catch (IOException ioe) { ioe.printStackTrace(); } } Collections.sort(messages, new Comparator<JSONObject>() { public int compare(JSONObject a, JSONObject b) { long delta = a.optLong("created", 0) - b.optLong("created", 0); if (delta == 0) { return 0; } if (delta < 0) { return -1; } return 1; } }); Date cur = new Date(); for (JSONObject entry: messages) { formatMessage(entry, cur); } } public String getName() { return "show"; } public String getUsage() { return "\tshow [names]\n"+ "\t\tShow saved content shared from all your linked vaults, or\n"+ "\t\tonly from a specific list of people."; } static void formatMessage(JSONObject entry, Date cur) { formatDate(entry.optLong("created"), cur); System.out.print(" <"); System.out.print(entry.optString("alias")); System.out.print("> "); String type = entry.optString("type"); if ("thormor/text".equals(type)) { System.out.println(formatText(entry.optString("text"))); } else if ("thormor/file".equals(type)) { System.out.println(formatText(entry.optString("text"))); String src = entry.optString("local_src"); if (src != null) { String name = entry.optString("name"); System.out.print("\tFilename: "); if (name != null) { System.out.print(name); } System.out.println(); System.out.print("\tDownloaded: "); System.out.println(src); } } else { System.out.println("Unknown type"); try { System.out.println(entry.toString(2)); } catch (JSONException ign) {ign.printStackTrace();} } } private final void mergeMessages (ArrayList<JSONObject> messages, CLinkedVault lv) throws IOException { JSONObject inbox = lv.readLocalInbox(); if (inbox == null) { return; } String alias = lv.getAlias(); if (alias == null) { alias = lv.getId().toString(); } JSONArray entries = inbox.optJSONArray("entries"); if (entries == null) { return; } for (int i=0; i<entries.length(); i++) { JSONObject entry = entries.optJSONObject(i); if (entry == null) { continue; } // augment object with misc info. U.put(entry, "alias", alias); if ("thormor/file".equals(entry.optString("type"))) { File f = CFetchCommand.getDownloadLocation (lv, entry.optString("src"), entry.optString("name")); if (f.canRead()) { U.put(entry, "local_src", f.toString()); } } messages.add(entry); } } private static String formatText(String s) { if (s == null) { return ""; } return s.replaceAll("\\n", "\n\t"); } private static void formatDate(long ts, Date cur) { Date tsdate = new Date(ts); s_calendar.setTime(tsdate); int tsday = s_calendar.get(Calendar.DAY_OF_WEEK); s_calendar.setTime(cur); int curday = s_calendar.get(Calendar.DAY_OF_WEEK); if (tsday == curday) { System.out.print(s_short_format.format(tsdate)); } else { System.out.print(s_long_format.format(tsdate)); } } private final static SimpleDateFormat s_short_format = new SimpleDateFormat("HH:mm"); private final static SimpleDateFormat s_long_format = new SimpleDateFormat("MMM d, yyyy HH:mm"); private final static Calendar s_calendar = Calendar.getInstance(); }
1,352
https://github.com/abobija/words-and-synonyms/blob/master/src/main/resources/public/js/script.js
Github Open Source
Open Source
MIT
2,019
words-and-synonyms
abobija
JavaScript
Code
388
1,206
/** * Main script fof application which * purpose is to initialize UI and send requests to service * on button click events etc... * * Script depends on * - jQuery * - Bootstrap * - ./modal */ const KEY_ENTER = 13; const KEY_SPACE = 32; let isSearcherBusy = false; const $search = $('#search').focus(); const $searchResultsList = $('#searchResultsList'); const $notInDatabaseInfo = $('#notInDatabaseInfo'); /** * Attaching events etc... */ $search.keypress(e => { if(e.keyCode == KEY_SPACE) { return e.preventDefault(); } if(e.keyCode == KEY_ENTER && ! isSearcherBusy) { search($search.val()); } }); /** * Search service for word * * @param keyword - Word for search */ var search = keyword => { keyword = keyword.trim(); if(keyword.length > 0) { isSearcherBusy = true; $searchResultsList.empty(); $notInDatabaseInfo.hide(); Service.search(keyword, response => { let wordIsInDatabase = false; $.each(response, function() { const wordVal = this.value; if(keyword.toLowerCase() == wordVal.toLowerCase()) { wordIsInDatabase = true; } const $li = $('<li />'); const $ahref = $('<a href="#" />').html(wordVal); let loaded = false; $ahref.click(() => { if(! loaded) { const $synonymsList = $('<ul />'); const $addSynonym = $('<a href="#" />').html('Add new synonym...'); $li.append($synonymsList); $synonymsList.append( $('<li />').append($addSynonym.click(() => { const $synonym = $('<input type="text" class="form-control" placeholder="Synonym..." />'); new Modal({ title: 'New synonym', content: $('<div />') .append($('<p />').html('Synonym for "' + wordVal + '"')) .append($synonym), ok: { callback: mdl => { const synonym = $synonym.val().trim(); if(synonym.length < 2) { alert('Synonym should be wide at least 2 characters'); } else { mdl.close(); Service.addSynonymToWord( synonym, wordVal, response => { $('<li />') .append($('<span />').html(response.value)) .insertBefore($addSynonym); }, e => alert(e.responseJSON.message) ); } } } }).show(() => $synonym.focus()); })) ); Service.getSynonymsOfWord(wordVal, response => { $.each(response, function() { $synonymsList.prepend( $('<li />').append($('<span />').html(this.value)) ); }); }); loaded = true; } }); $searchResultsList.append( $li.append($ahref) ); }); if(! wordIsInDatabase && keyword.length > 1) { $notInDatabaseInfo .empty() .append('Word ') .append($('<strong />').html(keyword)) .append(' has not been added, yet. ') .append($('<a href="#" />').html('Add now...').click(function() { const $word = $('<input type="text" class="form-control" value="' + keyword + '" />'); new Modal({ title: 'New word', content: $('<div />') .append($('<p />').html('Type value of new word...')) .append($word), ok: { callback: mdl => { const _word = $word.val().trim(); if(_word.length < 2) { alert('Word should be wide at least 2 characters'); } else { mdl.close(); Service.addWord( _word, response => { $search.val(''); search(response.value); }, e => alert(e.responseJSON.message) ); } } } }).show(() => $word.focus()); })) .show(); } isSearcherBusy = false; }); } };
39,736
https://github.com/Remalloc/simple_proxy_pool/blob/master/simple_proxy_pool/config.py
Github Open Source
Open Source
BSD-3-Clause
2,019
simple_proxy_pool
Remalloc
Python
Code
23
133
REQUEST_HEADERS = { "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) " "AppleWebKit/537.36 (KHTML, like Gecko) " "Chrome/71.0.3578.98 " "Safari/537.36" }
37,376
https://github.com/carlosclayton/app-delivery/blob/master/resources/views/layouts/app.blade.php
Github Open Source
Open Source
MIT
null
app-delivery
carlosclayton
PHP
Code
436
1,680
<!DOCTYPE html> <html lang="{{ app()->getLocale() }}"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- CSRF Token --> <meta name="csrf-token" content="{{ csrf_token() }}"> <title>{{ config('app.name', 'Laravel') }}</title> <!-- Styles --> <link href="{{ (env('APP_ENV') === 'local') ? mix('css/app.css') : asset('css/app.css') }}" rel="stylesheet"> <!-- Tell the browser to be responsive to screen width --> <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport"> <!-- Bootstrap 3.3.7 --> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> <!-- Google Font --> <!-- <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700,300italic,400italic,600italic"> --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.3.5/themes/default/style.min.css"/> </head> <body class="hold-transition skin-green sidebar-mini"> <div id="app"> <!-- Site wrapper --> <div class="wrapper"> <header class="main-header"> <!-- Logo --> <a href="../../index2.html" class="logo"> <!-- mini logo for sidebar mini 50x50 pixels --> <span class="logo-mini"><b>A</b>LT</span> <!-- logo for regular state and mobile devices --> <span class="logo-lg"><b>Admin</b>LTE</span> </a> <!-- Header Navbar: style can be found in header.less --> <nav class="navbar navbar-static-top"> <!-- Sidebar toggle button--> <a href="#" class="sidebar-toggle" data-toggle="push-menu" role="button"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </a> <div class="navbar-custom-menu"> <ul class="nav navbar-nav"> <!-- Messages: style can be found in dropdown.less--> <!-- User Account: style can be found in dropdown.less --> <li class="dropdown user user-menu"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <span class="hidden-xs"><i class="fa fa-fw fa-user"></i> {{ Auth::user()->name }} <span class="caret"></span> </span> </a> <ul class="dropdown-menu"> <!-- User image --> <li class="user-header"> <img src="https://convention.nriva.org/2017/wp-content/themes/Nriva2017/images/user-dummy.png" class="img-circle" alt="User Image"> <p> {{ Auth::user()->name }} <small>{{ Auth::user()->created_at }}</small> </p> </li> <!-- Menu Footer--> <li class="user-footer"> <div class="pull-right"> <a class="btn btn-default btn-flat" href="{{ route('logout') }}" onclick="event.preventDefault(); document.getElementById('logout-form').submit();"> {{ __('Logout') }} </a> <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;"> @csrf </form> </div> </li> </ul> </li> </ul> </div> </nav> </header> <!-- =============================================== --> <!-- Left side column. contains the sidebar --> <aside class="main-sidebar"> <!-- sidebar: style can be found in sidebar.less --> <section class="sidebar"> <!-- Sidebar user panel --> <!-- search form --> <form action="#" method="get" class="sidebar-form"> <div class="input-group"> <input type="text" name="q" class="form-control" placeholder="Search..."> <span class="input-group-btn"> <button type="submit" name="search" id="search-btn" class="btn btn-flat"><i class="fa fa-search"></i> </button> </span> </div> </form> <!-- /.search form --> <!-- sidebar menu: : style can be found in sidebar.less --> <ul class="sidebar-menu" data-widget="tree"> <li class="header">MENU PRINCIPAL</li> <li> <a href="{{ route('home') }}"> <i class="fa fa-dashboard"></i> <span>Dashboard</span> </a> </li> </ul> </section> <!-- /.sidebar --> </aside> <!-- =============================================== --> <!-- Content Wrapper. Contains page content --> <div class="content-wrapper"> @yield('body') </div> <!-- /.content-wrapper --> <footer class="main-footer"> <div class="pull-right hidden-xs"> <b>Version</b> 2.4.0 </div> <strong>Copyright &copy; 2014-2016 <a href="https://adminlte.io">Almsaeed Studio</a>.</strong> All rights reserved. </footer> </div> </div> </body> <!-- Scripts --> <script src="{{ (env('APP_ENV') === 'local') ? mix('js/app.js') : asset('js/app.js') }}" defer></script> </html>
36,376
https://github.com/dragoneena12/lapi-website-gatsby/blob/master/src/components/Characters/Fetherdra.tsx
Github Open Source
Open Source
0BSD
2,023
lapi-website-gatsby
dragoneena12
TSX
Code
147
929
import React from "react" import { StaticImage } from "gatsby-plugin-image" import * as classes from "./Fetherdra.module.scss" const Fetherdra: React.FC = () => ( <div className={classes.Container}> <div className={classes.Description}> <h2>フェザードラゴネット(Feather Dragonet)</h2> <ul className={classes.List}> <li>種族:ドラゴン?</li> <li>性別:♂?</li> </ul> <p> <a href="https://suko-doge.booth.pm/" target="_blank" rel="noopenner noreferrer" className={classes.Link} > バウワウナード </a> 製のフェザドラちゃん改変です。あおくてかわいい。 </p> <p> <a href="https://hub.vroid.com/characters/5332191322326023168/models/7463918390285866524" target="_blank" rel="noopenner noreferrer" className={classes.Link} > VRoidHubで見る </a> </p> </div> <StaticImage className={classes.Large4} src="../../images/fetherdra/pic1.jpg" alt="fetherdra picture" placeholder="none" /> <StaticImage className={classes.Large2} src="../../images/fetherdra/pic2.jpg" alt="fetherdra picture" placeholder="none" /> <StaticImage className={classes.Large1} src="../../images/fetherdra/pic3.png" alt="fetherdra picture" placeholder="none" /> <StaticImage className={classes.Image} src="../../images/fetherdra/pic4.png" alt="fetherdra picture" placeholder="none" /> <StaticImage className={classes.Large6} src="../../images/fetherdra/pic5.png" alt="fetherdra picture" placeholder="none" /> <StaticImage className={classes.Image} src="../../images/fetherdra/pic6.png" alt="fetherdra picture" placeholder="none" /> <StaticImage className={classes.Image} src="../../images/fetherdra/pic7.png" alt="fetherdra picture" placeholder="none" /> <StaticImage className={classes.Image} src="../../images/fetherdra/pic8.png" alt="fetherdra picture" placeholder="none" /> <StaticImage className={classes.Image} src="../../images/fetherdra/pic9.png" alt="fetherdra picture" placeholder="none" /> <StaticImage className={classes.Large5} src="../../images/fetherdra/pic10.png" alt="fetherdra picture" placeholder="none" /> <StaticImage className={classes.Image} src="../../images/fetherdra/pic11.png" alt="fetherdra picture" placeholder="none" /> <StaticImage className={classes.Large3} src="../../images/fetherdra/pic12.png" alt="fetherdra picture" placeholder="none" /> </div> ) export default Fetherdra
14,801
https://github.com/J-Keven/Gobarber-api/blob/master/src/modules/appointments/repositories/IAppointmentsRepository.ts
Github Open Source
Open Source
MIT
2,020
Gobarber-api
J-Keven
TypeScript
Code
53
247
import ICreateAppotmentsDTO from '@modules/appointments/dtos/ICreateAppointmentsDTO'; import Appointments from '../infra/typeorm/entities/Appointments'; import IFindAllInMonthFromProviderDTO from '../dtos/IFindAllInMonthFromProviderDTO'; import IFindAllInDayFromProviderDTO from '../dtos/IFindAllInDayFromProviderDTO'; import IFindByDateDTO from '../dtos/IFindByDateDTO'; export default interface IAppointmentsRepository { create(data: ICreateAppotmentsDTO): Promise<Appointments>; findByDate(data: IFindByDateDTO): Promise<Appointments | undefined>; findAllInMonthFromProvider( data: IFindAllInMonthFromProviderDTO, ): Promise<Appointments[]>; findAllInDayFromProvider( data: IFindAllInDayFromProviderDTO, ): Promise<Appointments[]>; } // Aplicando o princípio LSP - Liskov substitution Principle
41,556
https://github.com/liebeskind/Spoke/blob/master/src/editor/nodes/BoxColliderNode.js
Github Open Source
Open Source
MIT
2,019
Spoke
liebeskind
JavaScript
Code
167
553
import THREE from "../../vendor/three"; import EditorNodeMixin from "./EditorNodeMixin"; export default class BoxColliderNode extends EditorNodeMixin(THREE.Object3D) { static legacyComponentName = "box-collider"; static nodeName = "Box Collider"; static _geometry = new THREE.BoxBufferGeometry(); static _material = new THREE.Material(); static async deserialize(editor, json) { const node = await super.deserialize(editor, json); node.walkable = !!json.components.find(c => c.name === "walkable"); return node; } constructor(editor) { super(editor); const boxMesh = new THREE.Mesh(BoxColliderNode._geometry, BoxColliderNode._material); const box = new THREE.BoxHelper(boxMesh, 0x00ff00); box.layers.set(1); this.helper = box; this.add(box); this.walkable = false; } copy(source, recursive) { super.copy(source, false); if (recursive) { for (const child of source.children) { if (child !== this.helper) { const clonedChild = child.clone(); this.add(clonedChild); } } } this.walkable = source.walkable; return this; } serialize() { const components = { "box-collider": {} }; if (this.walkable) { components.walkable = {}; } return super.serialize(components); } prepareForExport() { super.prepareForExport(); this.remove(this.helper); this.addGLTFComponent("box-collider", { // TODO: Remove exporting these properties. They are already included in the transform props. position: this.position, rotation: { x: this.rotation.x, y: this.rotation.y, z: this.rotation.z }, scale: this.scale }); } }
6,860
https://github.com/rajabishek/queueless/blob/master/app/Exceptions/OrganisationNotFoundException.php
Github Open Source
Open Source
MIT
2,016
queueless
rajabishek
PHP
Code
9
28
<?php namespace Queueless\Exceptions; class OrganisationNotFoundException extends AbstractNotFoundException { }
49,863
https://github.com/roots/bud/blob/master/examples/babel/bud.config.js
Github Open Source
Open Source
MIT
2,023
bud
roots
JavaScript
Code
23
112
export default async bud => { bud.entry('app', ['app.js', 'app.css']) bud.babel .setPresets({ '@babel/preset-env': '@babel/preset-env', }) .setPlugins({ '@babel/plugin-transform-runtime': [ '@babel/plugin-transform-runtime', {helpers: false}, ], }) }
14,616
https://github.com/CaoLP/hay/blob/master/Vendor/croogo/croogo/Settings/Controller/SettingsAppController.php
Github Open Source
Open Source
MIT
2,015
hay
CaoLP
PHP
Code
40
126
<?php App::uses('AppController', 'Controller'); /** * Settings Application controller * * @category Settings.Controllers * @package Croogo.Settings * @version 1.0 * @author Fahad Ibnay Heylaal <contact@fahad19.com> * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @link http://www.croogo.org */ class SettingsAppController extends AppController { }
25,782
https://github.com/neatLines/logFinder/blob/master/server/models/oneHost.go
Github Open Source
Open Source
MIT
2,019
logFinder
neatLines
Go
Code
14
37
package models // type Host struct { Hostname string `json:"hostname"` Appname string `json:"appname"` }
16,326
https://github.com/ArrogantWombatics/openbsd-src/blob/master/gnu/usr.bin/perl/cpan/Unicode-Collate/t/loc_ta.t
Github Open Source
Open Source
BSD-3-Clause
2,019
openbsd-src
ArrogantWombatics
Perl
Code
276
1,745
BEGIN { unless ('A' eq pack('U', 0x41)) { print "1..0 # Unicode::Collate cannot pack a Unicode code point\n"; exit 0; } unless (0x41 == unpack('U', 'A')) { print "1..0 # Unicode::Collate cannot get a Unicode code point\n"; exit 0; } if ($ENV{PERL_CORE}) { chdir('t') if -d 't'; @INC = $^O eq 'MacOS' ? qw(::lib) : qw(../lib); } } use strict; use warnings; BEGIN { $| = 1; print "1..104\n"; } my $count = 0; sub ok ($;$) { my $p = my $r = shift; if (@_) { my $x = shift; $p = !defined $x ? !defined $r : !defined $r ? 0 : $r eq $x; } print $p ? "ok" : "not ok", ' ', ++$count, "\n"; } use Unicode::Collate::Locale; ok(1); ######################### my $objTa = Unicode::Collate::Locale-> new(locale => 'TA', normalization => undef); ok($objTa->getlocale, 'ta'); $objTa->change(level => 1); my $Kssa = "\x{B95}\x{BCD}\x{BB7}"; my $v = "\x{BCD}"; for my $h (0, 1) { no warnings 'utf8'; my $t = $h ? pack('U', 0xFFFF) : ""; $objTa->change(highestFFFF => 1) if $h; ok($objTa->lt("\x{B94}$t", "\x{B82}")); ok($objTa->lt("\x{B82}$t", "\x{B83}")); ok($objTa->lt("\x{B83}$t", "\x{B95}$v")); ok($objTa->lt("\x{B95}$v$t", "\x{B95}")); ok($objTa->lt("\x{B95}$t", "\x{B99}$v")); ok($objTa->lt("\x{B99}$v$t", "\x{B99}")); ok($objTa->lt("\x{B99}$t", "\x{B9A}$v")); ok($objTa->lt("\x{B9A}$v$t", "\x{B9A}")); ok($objTa->lt("\x{B9A}$t", "\x{B9E}$v")); ok($objTa->lt("\x{B9E}$v$t", "\x{B9E}")); ok($objTa->lt("\x{B9E}$t", "\x{B9F}$v")); ok($objTa->lt("\x{B9F}$v$t", "\x{B9F}")); ok($objTa->lt("\x{B9F}$t", "\x{BA3}$v")); ok($objTa->lt("\x{BA3}$v$t", "\x{BA3}")); ok($objTa->lt("\x{BA3}$t", "\x{BA4}$v")); ok($objTa->lt("\x{BA4}$v$t", "\x{BA4}")); ok($objTa->lt("\x{BA4}$t", "\x{BA8}$v")); ok($objTa->lt("\x{BA8}$v$t", "\x{BA8}")); ok($objTa->lt("\x{BA8}$t", "\x{BAA}$v")); ok($objTa->lt("\x{BAA}$v$t", "\x{BAA}")); ok($objTa->lt("\x{BAA}$t", "\x{BAE}$v")); ok($objTa->lt("\x{BAE}$v$t", "\x{BAE}")); ok($objTa->lt("\x{BAE}$t", "\x{BAF}$v")); ok($objTa->lt("\x{BAF}$v$t", "\x{BAF}")); ok($objTa->lt("\x{BAF}$t", "\x{BB0}$v")); ok($objTa->lt("\x{BB0}$v$t", "\x{BB0}")); ok($objTa->lt("\x{BB0}$t", "\x{BB2}$v")); ok($objTa->lt("\x{BB2}$v$t", "\x{BB2}")); ok($objTa->lt("\x{BB2}$t", "\x{BB5}$v")); ok($objTa->lt("\x{BB5}$v$t", "\x{BB5}")); ok($objTa->lt("\x{BB5}$t", "\x{BB4}$v")); ok($objTa->lt("\x{BB4}$v$t", "\x{BB4}")); ok($objTa->lt("\x{BB4}$t", "\x{BB3}$v")); ok($objTa->lt("\x{BB3}$v$t", "\x{BB3}")); ok($objTa->lt("\x{BB3}$t", "\x{BB1}$v")); ok($objTa->lt("\x{BB1}$v$t", "\x{BB1}")); ok($objTa->lt("\x{BB1}$t", "\x{BA9}$v")); ok($objTa->lt("\x{BA9}$v$t", "\x{BA9}")); ok($objTa->lt("\x{BA9}$t", "\x{B9C}$v")); ok($objTa->lt("\x{B9C}$v$t", "\x{B9C}")); ok($objTa->lt("\x{B9C}$t", "\x{BB6}$v")); ok($objTa->lt("\x{BB6}$v$t", "\x{BB6}")); ok($objTa->lt("\x{BB6}$t", "\x{BB7}$v")); ok($objTa->lt("\x{BB7}$v$t", "\x{BB7}")); ok($objTa->lt("\x{BB7}$t", "\x{BB8}$v")); ok($objTa->lt("\x{BB8}$v$t", "\x{BB8}")); ok($objTa->lt("\x{BB8}$t", "\x{BB9}$v")); ok($objTa->lt("\x{BB9}$v$t", "\x{BB9}")); ok($objTa->lt("\x{BB9}$t", "${Kssa}$v")); ok($objTa->lt("${Kssa}$v$t", "${Kssa}")); ok($objTa->lt("${Kssa}$t", "\x{BBE}")); } # 104
5,055
https://github.com/hwbeeson/wepppy/blob/master/wepppy/wepp/soils/soilsdb/data/Database/la/PELHAM(LS).sol
Github Open Source
Open Source
BSD-3-Clause
null
wepppy
hwbeeson
Solidity
Code
71
217
95.1 # This WEPP soil input file was made using USDA-SCS Soil-5 (1992) data # base. Assumptions: soil albedo=0.23, initial sat.=0.75. If you have # any question, please contact Reza Savabi, Ph: (317)-494-5051 # Soil Name: PELHAM Rec. ID: GA0015 Tex.:loamy sand 1 1 'PELHAM' 'LS' 3 .23 .75 5505466.00 .008752 2.35 13.65 685.8 76.5 7.9 1.50 5.8 1.5 1422.4 66.2 22.5 .50 9.0 1.4 1727.2 59.4 27.5 .17 11.0 1.4
32,262
https://github.com/Cherobin/GameJamUnivali2020/blob/master/ApocalipseCHI/src/apiPS/PS_Som2.java
Github Open Source
Open Source
Apache-2.0
2,020
GameJamUnivali2020
Cherobin
Java
Code
801
1,982
package apiPS; import java.io.*; import javax.sound.sampled.*; /* * Created on 02/02/2009 * Atualizado Para Verção 1.0 * Desenvolvido Por Dennis Kerr Coelho * PalmSoft Tecnologia */ public class PS_Som2 { private static final int ECHO_NUMBER = 1; // how many echoes to add private static final double DECAY = 0.5; // the decay for each echo private static AudioInputStream stream; private static AudioFormat format = null; private static SourceDataLine line = null; byte[] audiosample; public PS_Som2(String fnm){ createInput(fnm); /*if (!isRequiredFormat()) { // not in SamplesPlayer Console.debug("Format unsuitable for echoing"); System.exit(0); }*/ createOutput(); int numBytes = (int)(stream.getFrameLength() * format.getFrameSize()); Console.debug("Size in bytes: " + numBytes); audiosample = getSamples(numBytes); } public void play(){ Console.debug("tocou"); playsample(audiosample); } private static void createInput(String fnm) // Set up the audio input stream from the sound file { try { // link an audio stream to the sampled sound's file stream = AudioSystem.getAudioInputStream( new File(fnm) ); format = stream.getFormat(); Console.debug("Audio format: " + format); // convert ULAW/ALAW formats to PCM format if ( (format.getEncoding() == AudioFormat.Encoding.ULAW) || (format.getEncoding() == AudioFormat.Encoding.ALAW) ) { AudioFormat newFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, format.getSampleRate(), format.getSampleSizeInBits()*2, format.getChannels(), format.getFrameSize()*2, format.getFrameRate(), true); // big endian // update stream and format details stream = AudioSystem.getAudioInputStream(newFormat, stream); Console.debug("Converted Audio format: " + newFormat); format = newFormat; } } catch (UnsupportedAudioFileException e) { Console.debug( e.getMessage()); System.exit(0); } catch (IOException e) { Console.debug( e.getMessage()); System.exit(0); } } // end of createInput() private static boolean isRequiredFormat() // Only 8-bit PCM signed or unsigned audio can be echoed { if ( ((format.getEncoding() == AudioFormat.Encoding.PCM_UNSIGNED) || (format.getEncoding() == AudioFormat.Encoding.PCM_SIGNED)) && (format.getSampleSizeInBits() == 8)) return true; else return false; } // end of isRequiredFormat() private static void createOutput() // set up the SourceDataLine going to the JVM's mixer { try { DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); if (!AudioSystem.isLineSupported(info)) { Console.debug("Line does not support: " + format); System.exit(0); } // get a line of the required format line = (SourceDataLine) AudioSystem.getLine(info); line.open(format); } catch (Exception e) { Console.debug( e.getMessage()); System.exit(0); } } // end of createOutput() private static byte[] getSamples(int numBytes) /* Load all the samples from the AudioInputStream as a single byte array. Return a _modified_ byte array, after the echo effect has been applied. */ { // read the entire stream into samples[] byte[] samples = new byte[numBytes]; DataInputStream dis = new DataInputStream(stream); try { dis.readFully(samples); } catch (IOException e) { Console.debug( e.getMessage()); System.exit(0); } /* Create a byte array by applying the audio effect. This line is the main point of difference from SamplesPlayer, which returns samples unchanged. */ //return echoSamples(samples, numBytes); return samples; } // end of getSamples() private static byte[] echoSamples(byte[] samples, int numBytes) /* The echo effect is ECHO_NUMBER (4) copies of the original sound added to the end of the original. The volume of each one is reduced (decayed) by DECAY (0.5) over its predecessor. The change to a byte is done by echoSample() */ { int numTimes = ECHO_NUMBER + 1; double currDecay = 1.0; short sample, newSample; byte[] newSamples = new byte[numBytes*numTimes]; for (int j=0; j < numTimes; j++) { for (int i=0; i < numBytes; i++) newSamples[i + (numBytes*j)] = echoSample(samples[i], currDecay); currDecay *= DECAY; } return newSamples; } // end of echoSamples() private static byte echoSample(byte sampleByte, double currDecay) /* Since the effect is restricted to samples which are PCM signed or unsigned, and 8-bit, we do not have to worry about big/little endian or strange byte formats. The byte represents the amplitude (loudness) of the sample. The byte is converted to a short, divided by the decay, then returned as a byte. An unsigned byte needs masking as it is converted since Java stores shorts in signed form, so we cut away any excessive bits before the short is created (which uses 16 bits). */ { short sample, newSample; if (format.getEncoding() == AudioFormat.Encoding.PCM_UNSIGNED) { sample = (short)(sampleByte & 0xff); // unsigned 8 bit --> short newSample = (short)(sample * currDecay); return (byte) newSample; } else if (format.getEncoding() == AudioFormat.Encoding.PCM_SIGNED) { sample = (short)sampleByte; // signed 8 bit --> short newSample = (short)(sample * currDecay); return (byte) newSample; } else return sampleByte; // no change } // end of echoSample private static void playsample(byte[] samples) /* The samples[] byte array is connected to a stream, read in chunks, and passed to the SourceDataLine. */ { // byte array --> stream InputStream source = new ByteArrayInputStream(samples); int numRead = 0; byte[] buf = new byte[line.getBufferSize()]; line.start(); // read and play chunks of the audio try { while ((numRead = source.read(buf, 0, buf.length)) >= 0) { int offset = 0; while (offset < numRead) offset += line.write(buf, offset, numRead-offset); } } catch (IOException e) { Console.debug( e.getMessage()); } // wait until all data is played, then close the line line.drain(); line.stop(); line.close(); Console.debug("terminou de tocar"); } // end of play() } // end of EchoSamplesPlayer class
45,143
https://github.com/Peracek/Bedouin/blob/master/src/server/api/templates/controller.ts
Github Open Source
Open Source
MIT
2,019
Bedouin
Peracek
TypeScript
Code
227
619
import { TemplateDir } from '@shared/types/TemplateDir' import { Template } from '@shared/types/Template' import TemplateDeployDTO from '@shared/types/TemplateDeployDTO' import { log } from '@common/logger' import * as templateManager from 'templateManager' import TemplateDefinition from 'templateManager/TemplateDefinition' import { APIError, APIErrorType as ErrType } from 'api/APIError' import { deployTemplate as deploy } from './flow/deployTemplate' const getTemplateDirs = async (): Promise<TemplateDir[]> => { try { const templates = await templateManager.getTemplateDirs() return templates } catch(err) { log('error', err) if(err.code === 'ENOENT') { throw new APIError({ apiErrortype: ErrType.FILE_OR_DIRECTORY_NOT_FOUND, status: 400 }) } else { throw err } } } const getTemplate = async (dirPath: string) => { let templateDef: TemplateDefinition try { templateDef = await templateManager.getTemplate({ dirPath }) } catch(err) { if(err.code === 'ENOENT') { throw new APIError({ apiErrortype: ErrType.FILE_OR_DIRECTORY_NOT_FOUND, status: 400 }) } else { throw err } } const result: Template = { dirName: dirPath, templateSpec: templateDef.templateSpec, parametersSpec: templateDef.paramsSpec } // return templateDef return result } const deployTemplate = async (dirPath: string, paramValues: {[key: string]: any}, user?: {name: string, email: string}): Promise<TemplateDeployDTO> => { let templateDef: TemplateDefinition let jobName: string try { templateDef = await templateManager.getTemplate({ dirPath }) } catch(err) { if(err.code === 'ENOENT') { throw new APIError({ apiErrortype: ErrType.FILE_OR_DIRECTORY_NOT_FOUND }) } else { throw err } } try { jobName = await deploy(templateDef, paramValues, user) } catch(err) { throw err } return { jobName } } export { getTemplateDirs, getTemplate, deployTemplate }
11,661
https://github.com/rkluszczynski/avro-cli/blob/master/src/main/java/io/github/rkluszczynski/avro/cli/command/kafka/KafkaConsumption.java
Github Open Source
Open Source
MIT
2,021
avro-cli
rkluszczynski
Java
Code
140
641
package io.github.rkluszczynski.avro.cli.command.kafka; import io.github.rkluszczynski.avro.cli.CliMainParameters; import io.github.rkluszczynski.avro.cli.CommandException; import io.github.rkluszczynski.avro.cli.command.CliCommand; import io.github.rkluszczynski.avro.cli.command.CliCommandParameters; import org.springframework.kafka.listener.KafkaMessageListenerContainer; import org.springframework.stereotype.Component; import java.time.Duration; import java.util.concurrent.CountDownLatch; import static io.github.rkluszczynski.avro.cli.command.CommandNames.KAFKA_CONSUME; import static io.github.rkluszczynski.avro.cli.command.kafka.KafkaMessageConsumer.ofConsumeParameters; import static java.util.Objects.isNull; import static java.util.concurrent.TimeUnit.MILLISECONDS; @Component public class KafkaConsumption implements CliCommand { private final ConsumeParameters consumeParameters = new ConsumeParameters(); private final CountDownLatch awaitLatch = new CountDownLatch(1); @Override public String execute(CliMainParameters mainParameters) { final KafkaMessageConsumer messageConsumer = ofConsumeParameters(consumeParameters); final KafkaMessageListenerContainer<String, String> listenerContainer = messageConsumer.getListenerContainer(); listenerContainer.start(); registerContainerShutdownHook(listenerContainer); try { final Duration consumeDuration = consumeParameters.getDuration(); if (isNull(consumeDuration)) { awaitLatch.await(); } else { awaitLatch.await(consumeDuration.toMillis(), MILLISECONDS); } } catch (InterruptedException ex) { throw new CommandException("Kafka consumer interrupted!", ex); } finally { listenerContainer.stop(); } return ""; } private void registerContainerShutdownHook(KafkaMessageListenerContainer<String, String> listenerContainer) { Runtime.getRuntime().addShutdownHook(new Thread(() -> { if (listenerContainer.isRunning()) { listenerContainer.stop(); } })); } @Override public String getCommandName() { return KAFKA_CONSUME.getCliCommand(); } @Override public CliCommandParameters getParameters() { return consumeParameters; } }
45,372
https://github.com/ZJKCode/ZJKReflectUtil/blob/master/ZJKReflectUtil/Classes/ReflectUtil.m
Github Open Source
Open Source
MIT
2,019
ZJKReflectUtil
ZJKCode
Objective-C
Code
982
4,069
// // ReflectUtil.m // ZJKReflectUtil // // Created by zhangjikuan on 2019/11/4. // #import "ReflectUtil.h" #import <objc/message.h> #import <objc/runtime.h> #import "objc/objc.h" #import "objc/objc-api.h" #define ARRAY(...) ([NSArray arrayWithObjects: IDARRAY(__VA_ARGS__) count: IDCOUNT(__VA_ARGS__)] #define $set(...) ((NSSet *)[NSSet setWithObjects:__VA_ARGS__,nil]) @implementation ReflectUtil -(id)init{ self=[super init]; if (self) { typeind=[[NSMutableDictionary alloc] init]; [typeind setValue:@"0" forKey:@"Ti"]; //for integer data type; [typeind setValue:@"1" forKey:@"Td"]; //for double data type; [typeind setValue:@"2" forKey:@"Tq"]; //for long long int data type; [typeind setValue:@"3" forKey:@"Tl"]; //for long data type; [typeind setValue:@"4" forKey:@"Tf"]; //for float data type; [typeind setValue:@"5" forKey:@"TQ"]; // for unsigned long long int data type; [typeind setValue:@"6" forKey:@"Tc"];// for BOOL datatype; [typeind setValue:@"7" forKey:@"T@\"NSString\""];//for NSString data type; [typeind setValue:@"8" forKey:@"T@\"NSDate\""]; // for NSDate data type; [typeind setValue:@"9" forKey:@"T@\"NSData\""];// for NSData data type; [typeind setValue:@"10" forKey:@"T@"];//for id data type; return self; } return nil; } //使用默认构造函数的构建器 -(id)buildTargetObjectByClassName:(NSString *)classname{ Class defineclass = [self getClassByName:classname]; #if !__has_feature(objc_arc) id selfdefine=[[[defineclass alloc]init] autorelease]; #else id selfdefine =[[defineclass alloc]init]; #endif return selfdefine; } // use the dictionary and constructor and classname to instant an object. -(id)buildTargetObjectByClassName:(NSString *)classname andInitParamWithMap:(NSDictionary *)param andConstructorName:(NSString *)constructor{ if (!classname) { return nil; } id instance = [[self getClassByName:classname] alloc]; SEL sel = NSSelectorFromString(constructor); NSMethodSignature *singlenature =[instance methodSignatureForSelector:sel]; NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:singlenature]; [invocation setTarget:instance]; [invocation setSelector:sel]; NSUInteger i = 1; for (NSString *key in [param allKeys]) { id object =[param valueForKey:key]; [invocation setArgument:&object atIndex:++i]; } [invocation invoke]; void* data = NULL; if ([singlenature methodReturnLength]) { [invocation getReturnValue:&data]; } return (__bridge id)data; return nil; } - (NSMethodSignature *)classMethodSignatureWithClass:(Class)clazz selector:(SEL)selector{ printf("%s",method_getTypeEncoding(class_getClassMethod(clazz, selector))); return [NSMethodSignature signatureWithObjCTypes:method_getTypeEncoding(class_getClassMethod(clazz, selector))]; } -(id)dynamicCallingBySingleton:(NSString *)classname andInitParamWithArray:(NSArray *)param andMethodName:(NSString *)method{ if (!classname) { return nil; } Class class = [self getClassByName:classname]; SEL sel = NSSelectorFromString(method); NSMethodSignature *singlenature =[self classMethodSignatureWithClass:class selector:sel]; NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:singlenature]; [invocation setTarget:class]; [invocation setSelector:sel]; NSUInteger i = 1; for (id object in param) { [invocation setArgument:(void *)&object atIndex:++i]; } [invocation invoke]; void* data = NULL; if ([singlenature methodReturnLength]!=0) { [invocation getReturnValue:&data]; } return (__bridge id)data; return nil; } // use the array and constructor and classname to instant an object -(id)buildTargetObjectByClassName:(NSString *)classname andInitParamWithArray:(NSArray *)param andConstructorName:(NSString *)constructor{ if (!classname) { return nil; } id instance = [[self getClassByName:classname] alloc]; SEL sel=NSSelectorFromString(constructor); NSMethodSignature *singlenature =[instance methodSignatureForSelector:sel]; NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:singlenature]; [invocation setTarget:instance]; [invocation setSelector:sel]; NSUInteger i = 1; for (id object in param) { [invocation setArgument:(void *)&object atIndex:++i]; } [invocation invoke]; void* data = NULL; if ([singlenature methodReturnLength]) { [invocation getReturnValue:&data]; } return (__bridge id)data; } // use the array and constructor and classname to instant an object -(id)buildTargetObjectByClassName:(NSString *)classname andSingleParam:(NSObject *)param andConstructorName:(NSString *)constructor{ if (!classname) { return nil; } id instance =[[self getClassByName:classname] alloc]; SEL sel = NSSelectorFromString(constructor); NSMethodSignature *singlenature = [instance methodSignatureForSelector:sel]; NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:singlenature]; [invocation setTarget:instance]; [invocation setSelector:sel]; [invocation setArgument:&param atIndex:2]; [invocation invoke]; void* data = NULL; if ([singlenature methodReturnLength]) { [invocation getReturnValue:&data]; } return (__bridge id)data; } /* - (id)performSelector:(SEL)aSelector withParameters:(void *)firstParameter, ... { NSMethodSignature *signature = [self methodSignatureForSelector:aSelector]; NSUInteger length = [signature numberOfArguments]; NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature]; [invocation setTarget:self]; [invocation setSelector:aSelector]; [invocation setArgument:&firstParameter atIndex:2]; va_list arg_ptr; va_start(arg_ptr, firstParameter); for (NSUInteger i = 3; i < length; ++i) { void *parameter = va_arg(arg_ptr, void *); [invocation setArgument:&parameter atIndex:i]; } va_end(arg_ptr); [invocation invoke]; if ([signature methodReturnLength]) { id data; [invocation getReturnValue:&data]; return data; } return nil; } */ -(id)transformResult:(NSMutableDictionary *)resultset ToObject:(NSString *)classname{ Class defineclass=NSClassFromString(classname); id selfdefineobj=[[defineclass alloc] init]; unsigned int outcount; int i; objc_property_t *propertyX=class_copyPropertyList(defineclass, &outcount);//获得属性列表 for (i=0; i<outcount; i++) { objc_property_t currentproperty=propertyX[i]; const char* propertyname=property_getName(currentproperty); NSString *objcname=[[NSString alloc] initWithCString:propertyname encoding:NSUTF8StringEncoding]; NSString *methodlowercase=[NSMutableString stringWithFormat:@"%@%@:",@"set",objcname]; SEL mysel=[self confirmWithMethodWillbeCalling:defineclass methodName:methodlowercase]; NSString *datatype=[self getPropertyType:currentproperty]; NSString *tind=[typeind valueForKey:datatype]; id values=[self setValueFor:objcname datatypeind:[tind intValue] valueMap:resultset] ; #if !__has_feature(objc_arc) [objcname release]; #endif if (values!=nil && mysel) { //objc_msgSend(selfdefineobj,mysel,values); [self InvokenFunctionByName:mysel instance:selfdefineobj andSingleParam:values]; } } return selfdefineobj; } // use the array and method name and instance to dynamic calling a method of the current instance. -(id)dynamicCallingByInstance:(NSObject *)instance andInitParamWithArray:(NSArray *)param andMethodName:(NSString *)method{ SEL sel=NSSelectorFromString(method); NSMethodSignature *singlenature =[instance methodSignatureForSelector:sel]; NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:singlenature]; [invocation setTarget:instance]; [invocation setSelector:sel]; NSUInteger i = 1; for (id object in param) { [invocation setArgument:(void *)&object atIndex:++i]; } [invocation invoke]; void* data; if ([singlenature methodReturnLength]!=0) { [invocation getReturnValue:&data]; return (__bridge id)data; } return nil; } -(id)setValueFor:(NSString *)column datatypeind:(NSInteger)ind valueMap:(NSMutableDictionary *)result{ id returnvalue=nil; switch (ind) { case 0: //int returnvalue=[[NSNumber alloc] initWithInt:([result valueForKey:column]==nil ? 0 : [[result valueForKey:column] intValue])]; break; case 1: //double returnvalue=[[NSNumber alloc] initWithDouble:([result valueForKey:column]==nil ? 0.0: [[result valueForKey:column] doubleValue])]; break; case 2: //longlong returnvalue =[[NSNumber alloc] initWithLongLong:([result valueForKey:column]==nil ? 0: [[result valueForKey:column] longLongValue])]; break; case 3://long returnvalue =[[NSNumber alloc] initWithLongLong:([result valueForKey:column]==nil ? 0: [[result valueForKey:column] longValue])]; break; case 4: //float returnvalue=[[NSNumber alloc] initWithDouble:([result valueForKey:column]==nil ? 0.0: [[result valueForKey:column] floatValue])]; break; case 5: //unsignedlonglongint returnvalue=[[NSNumber alloc] initWithDouble:([result valueForKey:column]==nil ? 0.0: [[result valueForKey:column] unsignedLongLongValue])]; break; case 6: //bool returnvalue = [[NSNumber alloc] initWithBool:[[result valueForKey:column] boolValue]]; break; case 7: //string returnvalue=[result valueForKey:column]==nil ? @"" : [result valueForKey:column]; break; case 8: //date returnvalue=[result valueForKey:column]; break; case 9: //data returnvalue=[result valueForKey:column]; break; case 10: //id returnvalue=[result objectForKey:column]; break; default: break; } return returnvalue ; } -(SEL)confirmWithMethodWillbeCalling:(Class)myclass methodName:(NSString *)name{ unsigned int outcount; Method *methods=class_copyMethodList(myclass, &outcount); int i; for(i=0;i<outcount;i++){ Method methodx=methods[i]; SEL mesel=method_getName(methodx); NSString *methodinfo=NSStringFromSelector(mesel); if([name compare:methodinfo options:NSCaseInsensitiveSearch|NSNumericSearch]==NSOrderedSame){ free(methods); return mesel; } } free(methods); return nil; } -(NSString *) getPropertyType:(objc_property_t )property { const char *attributes = property_getAttributes(property); NSString *typestring=[NSMutableString stringWithCString:attributes encoding:NSUTF8StringEncoding]; NSArray *typecomponent=[typestring componentsSeparatedByString:@","]; if ([typecomponent count]>0) { return (NSString *)[typecomponent objectAtIndex:0]; } return @""; } -(NSMutableDictionary *)transformNsObjectToMap:(NSObject *)obj{ #if !__has_feature(objc_arc) NSMutableDictionary *dict=[[[NSMutableDictionary alloc] init] autorelease]; #else NSMutableDictionary *dict=[[NSMutableDictionary alloc] init]; #endif unsigned int outcount; int i; objc_property_t *propertyX=class_copyPropertyList([obj class], &outcount);//获得属性列表 for (i=0; i<outcount; i++) { objc_property_t currentproperty=propertyX[i]; const char* propertyname=property_getName(currentproperty); #if !__has_feature(objc_arc) NSString *objcname=[[[NSString alloc] initWithCString:propertyname encoding:NSUTF8StringEncoding] autorelease]; #else NSString *objcname=[[NSString alloc] initWithCString:propertyname encoding:NSUTF8StringEncoding]; #endif // NSString *methodlowercase=objcname; // SEL method=NSSelectorFromString(methodlowercase); // id value=objc_msgSend(obj,method); id value =nil; [dict setValue:value==nil ? @"" :value forKey:objcname ]; } return dict; } -(Class)getClassByName:(NSString *)classname{ Class defineclass=NSClassFromString(classname); return defineclass; } -(void)InvokenFunctionByName:(SEL)sel instance:(id)instance andSingleParam:(NSObject *)param { NSMethodSignature *singlenature = [instance methodSignatureForSelector:sel]; NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:singlenature]; [invocation setTarget:instance]; [invocation setSelector:sel]; [invocation setArgument:&param atIndex:2]; [invocation invoke]; } @end
38,219
https://github.com/Claude-Ray/LeetCode/blob/master/Algorithms/arranging-coins.js
Github Open Source
Open Source
MIT
2,019
LeetCode
Claude-Ray
JavaScript
Code
38
81
/** * @param {number} n * @return {number} */ var arrangeCoins = function (n) { n = n * 2; let root = Math.ceil(Math.sqrt(n)); while (root * (root - 1) > n) root--; return root - 1; };
32,498
https://github.com/moashraf/kafigroup/blob/master/resources/views/profile.blade.php
Github Open Source
Open Source
MIT
2,021
kafigroup
moashraf
Blade
Code
378
2,065
<x-layout> <section id="profile-info" class="bg-light" style="direction: rtl;"> <div class="container"> <div class="main-body"> <div class="row gutters-sm"> <div class="col-md-4 mb-3"> <div class="card"> <div class="card-body"> <div class="d-flex flex-column align-items-center text-center"> <img src="https://bootdey.com/img/Content/avatar/avatar7.png" alt="Admin" class="rounded-circle" width="150"> <div class="mt-3"> <h4>علي حسن</h4> <p><strong>عدد النقاط</strong> 10,000</p> <hr class="hr-add"> <a href=""class="btn btn-info">الباقات</a> <a href="" type="button" class="btn btn-info">اعلاناتي</a> <a href="#" class="btn btn-light mt-3 ml-2 mr-2"> قائمه المفضلات <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-heart" viewBox="0 0 16 16"> <path d="M8 2.748l-.717-.737C5.6.281 2.514.878 1.4 3.053c-.523 1.023-.641 2.5.314 4.385.92 1.815 2.834 3.989 6.286 6.357 3.452-2.368 5.365-4.542 6.286-6.357.955-1.886.838-3.362.314-4.385C13.486.878 10.4.28 8.717 2.01L8 2.748zM8 15C-7.333 4.868 3.279-3.04 7.824 1.143c.06.055.119.112.176.171a3.12 3.12 0 0 1 .176-.17C12.72-3.042 23.333 4.867 8 15z"/> </svg></a> </div> </div> </div> </div> <div class="card mt-3"> <form class="list-group list-group-flush"> <li class="list-group-item d-flex justify-content-between align-items-center flex-wrap"> <i class="ti-facebook text-info"></i> <div class="text-secondary"> <input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="https/ialyzaafan.com"> </div> </li> <li class="list-group-item d-flex justify-content-between align-items-center flex-wrap"> <i class="ti-youtube text-danger"></i> <div class="text-secondary"> <input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="@alyZaafan"> </div> </li> <li class="list-group-item d-flex justify-content-between align-items-center flex-wrap"> <i class="ti-twitter text-info"></i> <div class="text-secondary"> <input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="@alyZaafan"> </div> </li> <li class="list-group-item d-flex justify-content-between align-items-center flex-wrap"> <i class="ti-instagram text-purple"></i> <div class="text-secondary"> <input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="@alyZaafan"> </div> </li> </form> </div> </div> <div class="col-md-8"> <div class="card mb-3"> <div class="card-body"> <form action=""> <div class="form-group"> <label for="exampleInputEmail1">الاسم كاملا</label> <input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="علي حسن"> </div> <div class="form-group"> <label for="exampleInputEmail1">البريد الاكترومي</label> <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="ialyzaafan@gmail.com"> </div> <div class="form-group"> <label for="exampleInputEmail1">الهاتف</label> <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="01119255735"> </div> <div class="form-group"> <label for="inputState">العمر</label> <select id="inputState" class="form-control"> <option>اختر العمر</option> <option selected>من 18 - الى 25</option> <option>من 26 الى 35</option> <option>من 36 الى 45</option> <option>من 46 الى 60</option> <option>اكثر من 60</option> </select> </div> <div class="form-group"> <label for="inputState">نوع المستخدم</label> <select id="inputState" class="form-control"> <option selected>بائع</option> <option>مشتري</option> <option>بائع و مشتري</option> </select> </div> <div class="accordion" id="accordionExample"> <div class="accordion-item"> <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne"> <h5>لتغيير كلمه المرور</h5> </button> <div id="collapseOne" class="accordion-collapse collapse" aria-labelledby="headingOne" data-bs-parent="#accordionExample"> <div class="form-group"> <label for="password">ادخل كلمه المرور الحاليه </label> <input type="password" class="form-control" id="password" aria-describedby="password" placeholder="***********"> </div> <div class="form-group"> <label for="password">ادخل كلمه المرور الجديده </label> <input type="password" class="form-control" id="password" aria-describedby="password" placeholder="***********"> </div> <div class="form-group"> <label for="password">اعد ادخال كامه المرور الجديده</label> <input type="password" class="form-control" id="password" aria-describedby="password" placeholder="***********"> </div> <a href="./forget-pass.html">هل نسيت كلمه المرور ؟</a> </div> </div> </div> </form> <div class="links"> </div> </div> </div> <a href="" type="button" class="btn btn-primary">حفظ</a> </div> </div> </div> </div> </section> </x-layout>
21,727
https://github.com/chineping/jenkins-pipeline-scripts/blob/master/vars/withWhiteSourceWrapper.groovy
Github Open Source
Open Source
MIT
2,020
jenkins-pipeline-scripts
chineping
Groovy
Code
187
802
#!/usr/bin/groovy import hudson.model.* def call(Closure body=null) { this.vars = [:] call(vars, body) } def call(Map vars, Closure body=null) { echo "[JPL] Executing `vars/withWhiteSourceWrapper.groovy`" vars = vars ?: [:] def RELEASE = vars.get("RELEASE", env.RELEASE ?: false).toBoolean() def RELEASE_VERSION = vars.get("RELEASE_VERSION", env.RELEASE_VERSION ?: null) String WHITESOURCE_TOKEN = vars.get("WHITESOURCE_TOKEN", "27651afa-9e00-4c57-9f0e-7df9358e6750").trim() vars.productVersion = vars.get("productVersion", "").trim() vars.product = vars.get("product", "nabla").trim() vars.projectToken = vars.get("projectToken", "").trim() #productToken 2dcf60630aca4d3fb29fe59ad731d488747f2f6b0ba04b8b8664ae3629a1c3ae vars.jobUserKey = vars.get("jobUserKey", "cf5b762ee7ab4f2cb9fdab9728e59c2a3ccc2d77cb9b4718986dfe90fac671bb").trim() if (vars.projectToken?.trim()) { vars.requesterEmail = vars.get("requesterEmail", 'alban.andrieu@free.fr').trim() vars.isFingerprintEnabled = vars.get("isFingerprintEnabled", false).toBoolean() vars.whithSourceOutputFile = vars.get("whithSourceOutputFile", "whithsource.log").trim() //vars.skipFailure = vars.get("skipFailure", false).toBoolean() try { //tee("${vars.whithSourceOutputFile}") { if (!RELEASE_VERSION) { echo 'No RELEASE_VERSION specified' RELEASE_VERSION = getSemVerReleasedVersion(vars) ?: "LATEST" vars.productVersion = "${RELEASE_VERSION}" } whitesource jobApiToken: WHITESOURCE_TOKEN, jobCheckPolicies: 'global', jobForceUpdate: 'global', jobUserKey: vars.jobUserKey, libExcludes: '', libIncludes: '', product: vars.product, productVersion: vars.productVersion, projectToken: vars.projectToken, requesterEmail: vars.requesterEmail if (body) { body() } //} // tee } catch (exc) { //currentBuild.result = 'UNSTABLE' echo "WARNING : There was a problem with aqua scan" + exc.toString() } finally { archiveArtifacts artifacts: "${vars.whithSourceOutputFile}, aqua.html", excludes: null, fingerprint: vars.isFingerprintEnabled, onlyIfSuccessful: false, allowEmptyArchive: true } } else { echo "WARNING : There was a problem with whitesrouce scan, projectToken cannot be empty" } }
6,256
https://github.com/Biacode/hermes-core/blob/master/api/rest/rest-facade/src/test/kotlin/org/biacode/hermes/core/api/rest/facade/test/AbstractFacadeImplTest.kt
Github Open Source
Open Source
Apache-2.0
2,018
hermes-core
Biacode
Kotlin
Code
37
164
package org.biacode.hermes.core.api.rest.facade.test import org.biacode.hermes.core.api.rest.facade.test.helper.FacadeImplTestHelperTestHelper import org.easymock.EasyMockRunner import org.easymock.EasyMockSupport import org.junit.runner.RunWith /** * Created by Arthur Asatryan. * Date: 1/13/18 * Time: 4:56 PM */ @RunWith(EasyMockRunner::class) abstract class AbstractFacadeImplTest : EasyMockSupport() { protected val helper = FacadeImplTestHelperTestHelper() }
14,166
https://github.com/mjFer/USVG/blob/master/Assets/USVG/SVG/DOM/SVGGeometry.cs
Github Open Source
Open Source
MIT
2,021
USVG
mjFer
C#
Code
318
1,100
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; namespace USVG { public class SVGGeometry : SVGElement { protected Vector2[] vectors_2d; protected Mesh msh; protected MeshFilter filter; protected Renderer renderer; protected SVGGeometry(Dictionary<string, string> _attrList) : base(_attrList) { } public override void Render(SVGElement parent, Material baseMaterial, onRenderCallback cb) { if (_gameobject == null) { _gameobject = new GameObject(name); _gameobject.AddComponent(typeof(MeshRenderer)); if (parent != null) _gameobject.transform.parent = parent.gameObject.transform; } if (vectors_2d != null && vectors_2d.Length > 0){ SVGGenerals.OptimizePoints(ref vectors_2d); // Use the triangulator to get indices for creating triangles Triangulator tr = new Triangulator(vectors_2d); int[] indices = tr.Triangulate(); // Create the Vector3 vertices Vector3[] vertices = new Vector3[vectors_2d.Length]; for (int i = 0; i < vertices.Length; i++) { vertices[i] = new Vector3(vectors_2d[i].x, vectors_2d[i].y, 0); } // Create the mesh if (msh == null) msh = new Mesh(); msh.vertices = vertices; msh.triangles = indices; if (fillColor != null) { // Use vertex colors Color[] colors = new Color[vertices.Length]; for (int i = 0; i < colors.Length; i++) { colors[i] = new Color(fillColor.R, fillColor.G, fillColor.B, fillOpacity); } msh.colors = colors; } //Normals //Vector3[] normals = new Vector3[vectors_2d.Length]; //for (int i = 0; i < normals.Length; i++) { // normals[i] = new Vector3(0, 0, 1); //} msh.RecalculateNormals(); msh.RecalculateBounds(); msh.RecalculateTangents(); //Generate Path mesh if (stroke != null) { stroke.GenerateMesh(vertices); Mesh strokeMesh = stroke.GetMesh(); CombineInstance combine = new CombineInstance(); combine.mesh = strokeMesh; combine.transform = _gameobject.transform.localToWorldMatrix; msh.CombineMeshes(new CombineInstance[] { combine }); } if (filter == null) filter = gameObject.GetComponent<MeshFilter>(); if (filter == null) filter = gameObject.AddComponent(typeof(MeshFilter)) as MeshFilter; filter.sharedMesh = msh; if (renderer == null) renderer = gameObject.GetComponent<Renderer>(); renderer.sharedMaterial = baseMaterial; //renderer.material = baseMaterial; //renderer.material.name = name + "-material"; //renderer.sortingLayerName = "USVG"; renderer.sortingOrder = element_number; //renderer.material.color = new Color(UnityEngine.Random.value, UnityEngine.Random.value, UnityEngine.Random.value); //if (fillColor != null){ // renderer.material.color = new Color(fillColor.R, fillColor.G, fillColor.B, fillOpacity); // renderer.material.renderQueue = 3000 + element_number; //} if (cb != null) { cb.Invoke(this.name + "_msh", msh); //cb.Invoke(renderer.material.name, renderer.material); } } } } }
41,745
https://github.com/hampgoodwin/infra/blob/master/cmd/cpfuzz/1-download.sh
Github Open Source
Open Source
Apache-2.0
2,020
infra
hampgoodwin
Shell
Code
115
405
#!/bin/bash set -e context=$(kubectl config get-contexts --output name | grep automated-clearing-house) dir="fuzz-"$(date +"%Y-%m-%d") containers=($(kubectl --context "$context" get pods -n apps | grep fuzz | cut -d' ' -f1)) echo "found ${#containers[@]} fuzz containers" subdir="" if [[ "$1" != "" ]]; then subdir="$1" else subdir="crashers" fi for container in "${containers[@]}" do name=$(echo "$container" | grep -E -o -o '(.*)fuzz' | tr -d ' ' | rev | cut -c5- | rev) echo "downloading $name fuzz data from $container" mkdir -p "$dir"/"$name"/"$subdir" files=($(kubectl --context "$context" exec -n apps "$container" -- ls -1 /go/src/github.com/moov-io/"$name"/test/fuzz-reader/crashers/)) echo "downloading ${#files[@]} files from $container" for file in "${files[@]}" do kubectl --context "$context" cp apps/"$container":/go/src/github.com/moov-io/"$name"/test/fuzz-reader/crashers/"$file" "$dir"/"$name"/"$subdir"/"$file" done done echo "Saved files in $dir"
20,543
https://github.com/awslabs/aws-trusted-advisor-explorer/blob/master/source/verify-ta-check-status-lambda.py
Github Open Source
Open Source
Apache-2.0, MIT-0
2,022
aws-trusted-advisor-explorer
awslabs
Python
Code
350
1,317
###################################################################################################################### # Copyright 2019 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://www.apache.org/licenses/ # # # # or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES # # OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions # # and limitations under the License. # ###################################################################################################################### import json,re,boto3,logging,os from botocore.exceptions import ClientError class AWSTrustedAdvisorExplorerGenericException(Exception): pass logger = logging.getLogger() if "LOG_LEVEL" in os.environ: numeric_level = getattr(logging, os.environ['LOG_LEVEL'].upper(), None) if not isinstance(numeric_level, int): raise ValueError('Invalid log level: %s' % loglevel) logger.setLevel(level=numeric_level) def sanitize_json(x): d = x.copy() if os.environ['MASK_PII'].lower() == 'true': for k, v in d.items(): if 'AccountId' in k: d[k] = sanitize_string(v) if 'AccountName' in k: d[k] = v[:3]+'-MASKED-'+v[-3:] if 'AccountEmail' in k: d[k] = v[:3]+'-MASKED-'+v[-3:] return d def sanitize_string(x): y = str(x) if os.environ['MASK_PII'].lower() == 'true': pattern=re.compile('\d{12}') y = re.sub(pattern,lambda match: ((match.group()[1])+'XXXXXXX'+(match.group()[-4:])), y) return y def verify_trusted_advisor_check_status(supportClient,checkId): logger.info("Verify status of Check:"+checkId) response = supportClient.describe_trusted_advisor_check_refresh_statuses( checkIds=[checkId] ) logger.info(sanitize_json(response)) return response #Assume Role in Child Account def assumeRole(accountId): logger.info('Variables passed to assumeRole(): '+sanitize_string(accountId)) roleArn="arn:aws:iam::"+str(accountId)+":role/"+os.environ['IAMRoleName'] #STS assume role call stsClient = boto3.client('sts') roleCredentials = stsClient.assume_role(RoleArn=roleArn, RoleSessionName="AWSTrustedAdvisorExplorerAssumeRole") return roleCredentials def lambda_handler(event, context): try: logger.info(sanitize_json(event)) logger.info("Assume role in child account") roleCredentials=assumeRole(event['AccountId']) logger.info("Create boto3 support client using the temporary credentials") supportClient=boto3.client("support",region_name="us-east-1", aws_access_key_id = roleCredentials['Credentials']['AccessKeyId'], aws_secret_access_key = roleCredentials['Credentials']['SecretAccessKey'], aws_session_token=roleCredentials['Credentials']['SessionToken']) response = verify_trusted_advisor_check_status(supportClient, event['CheckId']) logger.info("Append the Refresh Status '"+response['statuses'][0]['status']+"' to response." + " This will be consumed by downstream Lambda") event["RefreshStatus"] = response['statuses'][0]['status'] logger.info("Refresh for Check "+event['CheckId']+" Returned Refresh Wait Time in Seconds:"+ str((response['statuses'][0]['millisUntilNextRefreshable'])/1000)) logger.info("Rounding Wait Time to:"+str(round((response['statuses'][0]['millisUntilNextRefreshable'])/1000))) if round((response['statuses'][0]['millisUntilNextRefreshable'])/1000) <= 3600: event['WaitTimeInSec']= round((response['statuses'][0]['millisUntilNextRefreshable'])/1000) else: logger.info("Skipping Refresh for Check "+event['CheckId']+" as wait time"+ str(round((response['statuses'][0]['millisUntilNextRefreshable'])/1000))+ "is greater than 1 hour") event['WaitTimeInSec']= 0 return event except ClientError as e: e = sanitize_string(e) logger.error("Unexpected client error %s" % e) raise AWSTrustedAdvisorExplorerGenericException(e) except Exception as f: f = sanitize_string(f) logger.error("Unexpected exception: %s" % f) raise AWSTrustedAdvisorExplorerGenericException(f)
24,469
https://github.com/BoniLindsley/pymap/blob/master/pymap/backend/redis/mailbox.py
Github Open Source
Open Source
MIT
null
pymap
BoniLindsley
Python
Code
1,153
4,346
from __future__ import annotations from collections.abc import Iterable, Mapping, Sequence from datetime import datetime from typing import Optional import msgpack from aioredis import Redis, ResponseError, WatchError from pymap.bytes import HashStream from pymap.concurrent import Event from pymap.exceptions import MailboxNotFound, MailboxConflict, TemporaryFailure from pymap.flags import FlagOp from pymap.interfaces.message import CachedMessage from pymap.listtree import ListTree from pymap.mailbox import MailboxSnapshot from pymap.mime import MessageContent from pymap.parsing.message import AppendMessage from pymap.parsing.modutf7 import modutf7_encode, modutf7_decode from pymap.parsing.specials import ObjectId, SequenceSet from pymap.parsing.specials.flag import Flag from pymap.selected import SelectedSet, SelectedMailbox from pymap.threads import ThreadKey from .keys import CleanupKeys, NamespaceKeys, ContentKeys, MailboxKeys from .message import Message from .scripts.mailbox import MailboxScripts from .scripts.namespace import NamespaceScripts from ..mailbox import MailboxDataInterface, MailboxSetInterface __all__ = ['Message', 'MailboxData', 'MailboxSet'] _scripts = MailboxScripts() _ns_scripts = NamespaceScripts() _ChangesRaw = Sequence[tuple[bytes, Mapping[bytes, bytes]]] class MailboxData(MailboxDataInterface[Message]): """Implementation of :class:`~pymap.backend.mailbox.MailboxDataInterface` for the redis backend. """ def __init__(self, redis: Redis, mailbox_id: bytes, uid_validity: int, keys: MailboxKeys, ns_keys: NamespaceKeys, cl_keys: CleanupKeys) -> None: super().__init__() self._redis = redis self._mailbox_id = ObjectId(mailbox_id) self._uid_validity = uid_validity self._selected_set = SelectedSet() self._keys = keys self._ns_keys = ns_keys self._cl_keys = cl_keys @property def mailbox_id(self) -> ObjectId: return self._mailbox_id @property def readonly(self) -> bool: return False @property def uid_validity(self) -> int: return self._uid_validity @property def selected_set(self) -> SelectedSet: return self._selected_set def _get_msg(self, uid: int, msg_raw: bytes) -> Message: msg = msgpack.unpackb(msg_raw, raw=True) msg_flags = {Flag(flag) for flag in msg[b'flags']} msg_email_id = ObjectId.maybe(msg[b'email_id']) msg_thread_id = ObjectId.maybe(msg[b'thread_id']) msg_time = datetime.fromisoformat(msg[b'date'].decode('ascii')) return Message(uid, msg_time, msg_flags, email_id=msg_email_id, thread_id=msg_thread_id, redis=self._redis, ns_keys=self._ns_keys) async def update_selected(self, selected: SelectedMailbox, *, wait_on: Event = None) -> SelectedMailbox: last_mod_seq = selected.mod_sequence if wait_on is not None: await self._wait_updates(selected, last_mod_seq) if last_mod_seq is None: await self._load_initial(selected) else: await self._load_updates(selected, last_mod_seq) return selected async def append(self, append_msg: AppendMessage, *, recent: bool = False) -> Message: redis = self._redis keys = self._keys ns_keys = self._ns_keys when = append_msg.when or datetime.now() content = MessageContent.parse(append_msg.literal) content_hash = HashStream().digest(content) new_email_id = ObjectId.new_email_id(content_hash) ct_keys = ContentKeys(ns_keys, new_email_id) new_uid, email_id, thread_id = await _scripts.add( redis, ns_keys, ct_keys, keys, recent=recent, flags=[str(flag) for flag in append_msg.flag_set], date=when.isoformat().encode('ascii'), email_id=new_email_id.value, thread_id=ObjectId.random_thread_id().value, thread_keys=['\0'.join(thread_key) for thread_key in ThreadKey.get_all(content.header)], message=append_msg.literal, message_json=content.json, header=bytes(content.header), header_json=content.header.json) return Message(new_uid, when, append_msg.flag_set, email_id=ObjectId(email_id), thread_id=ObjectId(thread_id), redis=redis, ns_keys=ns_keys) async def copy(self, uid: int, destination: MailboxData, *, recent: bool = False) -> Optional[int]: redis = self._redis keys = self._keys ns_keys = self._ns_keys dest_keys = destination._keys try: dest_uid = await _scripts.copy(redis, ns_keys, keys, dest_keys, source_uid=uid, recent=recent) except ResponseError as exc: if 'message not found' in str(exc): return None raise return dest_uid async def move(self, uid: int, destination: MailboxData, *, recent: bool = False) -> Optional[int]: redis = self._redis keys = self._keys ns_keys = self._ns_keys dest_keys = destination._keys try: dest_uid = await _scripts.move(redis, ns_keys, keys, dest_keys, source_uid=uid, recent=recent) except ResponseError as exc: if 'message not found' in str(exc): return None raise return dest_uid async def get(self, uid: int, cached_msg: CachedMessage) -> Message: redis = self._redis keys = self._keys message_raw = await redis.hget(keys.uids, uid) if message_raw is None: if not isinstance(cached_msg, Message): raise TypeError(cached_msg) return Message.copy_expunged(cached_msg) return self._get_msg(uid, message_raw) async def update(self, uid: int, cached_msg: CachedMessage, flag_set: frozenset[Flag], mode: FlagOp) -> Message: keys = self._keys ns_keys = self._ns_keys try: message_raw = await _scripts.update( self._redis, ns_keys, keys, uid=uid, mode=bytes(mode), flags=[str(flag) for flag in flag_set]) except ResponseError as exc: if 'message not found' not in str(exc): raise if not isinstance(cached_msg, Message): raise TypeError(cached_msg) return Message.copy_expunged(cached_msg) return self._get_msg(uid, message_raw) async def delete(self, uids: Iterable[int]) -> None: keys = self._keys ns_keys = self._ns_keys uids = list(uids) if not uids: return await _scripts.delete(self._redis, ns_keys, keys, self._cl_keys, uids=uids) async def claim_recent(self, selected: SelectedMailbox) -> None: keys = self._keys async with self._redis.pipeline() as multi: multi.smembers(keys.recent) multi.unlink(keys.recent) recent, _ = await multi.execute() for uid_bytes in recent: selected.session_flags.add_recent(int(uid_bytes)) async def find_deleted(self, seq_set: SequenceSet, selected: SelectedMailbox) -> Sequence[int]: if not seq_set.is_all: return await super().find_deleted(seq_set, selected) deleted = await self._redis.smembers(self._keys.deleted) return [int(uid) for uid in deleted] async def cleanup(self) -> None: pass async def snapshot(self) -> MailboxSnapshot: next_uid, num_exists, num_recent, num_unseen, first_unseen = \ await _scripts.snapshot(self._redis, self._keys) return MailboxSnapshot(self.mailbox_id, self.readonly, self.uid_validity, self.permanent_flags, self.session_flags, num_exists, num_recent, num_unseen, first_unseen, next_uid) def _get_mod_seq(self, changes: _ChangesRaw) -> Optional[bytes]: try: ret = changes[-1][0] except IndexError: return None else: left, right = ret.rsplit(b'-', 1) next_right = int(right) + 1 return b'%b-%i' % (left, next_right) async def _load_initial(self, selected: SelectedMailbox) -> None: keys = self._keys async with self._redis.pipeline() as multi: multi.hgetall(keys.uids) multi.xrevrange(keys.changes, count=1) msg_raw_map, last_changes = await multi.execute() messages = [self._get_msg(int(uid), msg_raw) for uid, msg_raw in msg_raw_map.items()] selected.mod_sequence = self._get_mod_seq(last_changes) selected.set_messages(messages) def _get_changes(self, changes: _ChangesRaw) \ -> tuple[Sequence[Message], frozenset[int]]: expunged = frozenset(int(fields[b'uid']) for _, fields in changes if fields[b'type'] == b'expunge') messages: list[Message] = [] for _, fields in changes: uid = int(fields[b'uid']) if fields[b'type'] != b'fetch' or uid in expunged: continue msg = self._get_msg(uid, fields[b'message']) messages.append(msg) return messages, expunged async def _load_updates(self, selected: SelectedMailbox, last_mod_seq: bytes) -> None: keys = self._keys async with self._redis.pipeline() as multi: multi.xlen(keys.changes) multi.xrange(keys.changes, min=last_mod_seq) multi.xrevrange(keys.changes, count=1) changes_len, changes, last_changes = await multi.execute() if len(changes) == changes_len: return await self._load_initial(selected) messages, expunged = self._get_changes(changes) selected.mod_sequence = self._get_mod_seq(last_changes) selected.add_updates(messages, expunged) async def _wait_updates(self, selected: SelectedMailbox, last_mod_seq: bytes) -> None: keys = self._keys redis = self._redis await redis.xread({keys.changes: last_mod_seq}, block=1000, count=1) class MailboxSet(MailboxSetInterface[MailboxData]): """Implementation of :class:`~pymap.backend.mailbox.MailboxSetInterface` for the redis backend. """ def __init__(self, redis: Redis, keys: NamespaceKeys, cl_keys: CleanupKeys) -> None: super().__init__() self._redis = redis self._keys = keys self._cl_keys = cl_keys @property def delimiter(self) -> str: return '/' async def set_subscribed(self, name: str, subscribed: bool) -> None: if subscribed: await self._redis.sadd(self._keys.subscribed, name) else: await self._redis.srem(self._keys.subscribed, name) async def list_subscribed(self) -> ListTree: mailboxes = await self._redis.smembers(self._keys.subscribed) return ListTree(self.delimiter).update('INBOX', *( modutf7_decode(name) for name in mailboxes)) async def list_mailboxes(self) -> ListTree: mailboxes = await _ns_scripts.list(self._redis, self._keys) return ListTree(self.delimiter).update('INBOX', *( modutf7_decode(name) for name in mailboxes)) async def get_mailbox(self, name: str) -> MailboxData: redis = self._redis name_key = modutf7_encode(name) try: mbx_id, uid_val = await _ns_scripts.get( redis, self._keys, name=name_key) except ResponseError as exc: if 'mailbox not found' in str(exc): raise KeyError(name_key) from exc raise mbx_keys = MailboxKeys(self._keys, mbx_id) return MailboxData(redis, mbx_id, uid_val, mbx_keys, self._keys, self._cl_keys) async def add_mailbox(self, name: str) -> ObjectId: name_key = modutf7_encode(name) mbx_id = ObjectId.random_mailbox_id() try: await _ns_scripts.add(self._redis, self._keys, name=name_key, mailbox_id=mbx_id.value) except ResponseError as exc: if 'mailbox already exists' in str(exc): raise ValueError(name_key) from exc raise return mbx_id async def delete_mailbox(self, name: str) -> None: name_key = modutf7_encode(name) try: await _ns_scripts.delete(self._redis, self._keys, self._cl_keys, name=name_key) except ResponseError as exc: if 'mailbox not found' in str(exc): raise KeyError(name_key) from exc raise async def rename_mailbox(self, before: str, after: str) -> None: redis = self._redis async with redis.pipeline() as pipe: await pipe.watch(self._keys.mailboxes) pipe.multi() pipe.hgetall(self._keys.mailboxes) all_keys, = await pipe.execute() all_mbx = {modutf7_decode(key): ns for key, ns in all_keys.items()} tree = ListTree(self.delimiter).update('INBOX', *all_mbx.keys()) before_entry = tree.get(before) after_entry = tree.get(after) if before_entry is None: raise MailboxNotFound(before) elif after_entry is not None: raise MailboxConflict(after) async with redis.pipeline() as multi: for before_name, after_name in tree.get_renames(before, after): before_id = all_mbx[before_name] before_key = modutf7_encode(before_name) after_key = modutf7_encode(after_name) multi.hset(self._keys.mailboxes, after_key, before_id) multi.hdel(self._keys.mailboxes, before_key) multi.hincrby(self._keys.uid_validity, after_key) if before == 'INBOX': inbox_id = ObjectId.random_mailbox_id() multi.hset(self._keys.mailboxes, b'INBOX', inbox_id.value) multi.hincrby(self._keys.uid_validity, b'INBOX') try: await multi.execute() except WatchError as exc: msg = 'Mailboxes changed externally, please try again.' raise TemporaryFailure(msg) from exc
10,881
https://github.com/leikang123/LKCompiler/blob/master/src/main/system/Platform.java
Github Open Source
Open Source
BSD-3-Clause
2,022
LKCompiler
leikang123
Java
Code
25
83
package main.system; import main.type.TypeTable; import main.utils.ErrorHandler; public interface Platform { TypeTable typeTable(); CodeGenerator codeGenerator(CodeGeneratorOptions opts, ErrorHandler h); Assembler assembler(ErrorHandler h); Linker linker(ErrorHandler h); } }
42,248
https://github.com/dvn1627/gamificator/blob/master/app/Http/Controllers/Api/ContactsController.php
Github Open Source
Open Source
MIT
null
gamificator
dvn1627
PHP
Code
423
1,410
<?php namespace App\Http\Controllers\Api; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use App\Http\Controllers\Controller; use Illuminate\Http\Response; use Validator; use App\Models\ContactType; use App\Models\Contact; class ContactsController extends Controller { /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth:api', ['except' => []]); header("Access-Control-Allow-Origin: " . getOrigin($_SERVER)); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $user = auth()->user(); $streamer = $user->streamer()->first(); $contacts = $streamer->contacts()->get(); for ($i = 0; $i < count($contacts); $i++) { $type = $contacts[$i]->type()->first(); $contacts[$i]->type = $type['name']; } return response()->json(['data' => [ 'contacts' => $contacts, ]]); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * * @return \Illuminate\Http\Response */ public function store(Request $request) { $validator = Validator::make($request->all(), [ 'contact' => 'required|max:255|unique:contacts', 'contact_type_id' => 'required|numeric|min:1', ] ); $user = auth()->user(); $streamer = $user->streamer()->first(); if ($validator->fails()) { return response()->json([ 'errors' => $validator->errors(), ]); } if (!ContactType::find($request->contact_type_id)) { return response()->json([ 'errors' => ['contact type id not found'], ]); } $contact = new Contact(); $contact->contact = $request->contact; $contact->contact_type_id = $request->contact_type_id; $contact->streamer_id = $streamer->id; $contact->save(); return response()->json([ 'message' => 'new contact created successful', 'data' => [ 'id' => $contact->id, ] ]); } /** * Display the specified resource. * * @param int $id * * @return \Illuminate\Http\Response */ public function show(Request $request) { $id = $request->id; $contact = Contact::find($id); if (!$contact) { return response()->json([ 'errors' => ['contact id not found'], ]); } $type = $contact->type()->first(); $contact->type = $type['name']; return response()->json([ 'data' => $contact, ]); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * * @return \Illuminate\Http\Response */ public function update(Request $request) { $validator = Validator::make($request->all(), [ 'id' => 'required|numeric|min:1', 'contact' => 'required|max:255|unique:contacts', 'contact_type_id' => 'required|numeric|min:1', ]); $user = auth()->user(); $streamer = $user->streamer()->first(); if ($validator->fails()) { return response()->json([ 'errors' => $validator->errors(), ]); } if (!ContactType::find($request->contact_type_id)) { return response()->json([ 'errors' => ['contact type id not found'], ]); } $contact = Contact::find($request->id); if (!$contact) { return response()->json([ 'errors' => ['contact id not found'], ]); } $contact->contact = $request->contact; $contact->contact_type_id = $request->contact_type_id; $contact->streamer_id = $streamer->id; $contact->save(); return response()->json([ 'message' => 'contact type update successful', ]); } /** * Remove the specified resource from storage. * * @param int $id * * @return \Illuminate\Http\Response */ public function destroy(Request $request) { $validator = Validator::make($request->all(), [ 'id' => 'required|numeric', ]); if ($validator->fails()) { return response()->json([ 'errors' => $validator->errors(), ]); } $contact = Contact::find($request->id); if (!$contact) { return response()->json([ 'errors' => ['contact id not found'], ]); } $contact->delete(); return response()->json([ 'message' => 'contact delete successful', ]); } }
29,650
https://github.com/mstsuite/MuST/blob/master/MST/lib/computeProdExpan.F90
Github Open Source
Open Source
BSD-3-Clause
2,023
MuST
mstsuite
Fortran Free Form
Code
457
1,673
! ******************************************************************* ! * * ! * This subroutine aims to compute the spherical harmonic * ! * expansion of the product of two real functions, f and g, which * ! * are expanded in spherical harmonics up to lmax_f and lmax_g, * ! * respectively. The product function h = f*g is expanded up to * ! * lmax_h. * ! * * ! * Note: jmax = (lmax+1)*(lmax+2)/2. It is easy to show that * ! * * ! * L' L" * * ! * h (r) = sum C * f (r) * g (r) = sum C * f (r) * g (r) * ! * L" L,L' L,L" L L' L,L' L,L' L L' * ! * * ! ******************************************************************* subroutine computeProdExpan(nr,lmax_f,f,lmax_g,g,lmax_h,h) use KindParamModule, only : IntKind, RealKind, CmplxKind ! use MathParamModule, only : CZERO, CONE ! use ErrorHandlerModule, only : ErrorHandler ! use GauntFactorsModule, only : getK3 use GauntFactorsModule, only : getNumK3 use GauntFactorsModule, only : getGauntFactor ! use IntegerFactorsModule, only : lofk, mofk, jofk, kofj, m1m ! implicit none ! integer (kind=intKind), intent(in) :: nr, lmax_f, lmax_g, lmax_h integer (kind=intKind) :: kmax_f, kmax_g, kmax_h, jl_f, jl_g, jl_h, ir, j, m_f, m_g, kl_h, kl_f, kl_g integer (kind=IntKind), pointer :: nj3(:,:) integer (kind=IntKind), pointer :: kj3(:,:,:) ! real (kind=RealKind), pointer :: cgnt(:,:,:) ! complex (kind=CmplxKind), intent(in) :: f(:,:), g(:,:) complex (kind=CmplxKind), intent(out) :: h(:,:) complex (kind=CmplxKind) :: cfac ! if (size(f,1) < nr) then call ErrorHandler('computeProdExpan','size(f,1) < nr',size(f,1),nr) else if (size(f,2) < (lmax_f+1)*(lmax_f+2)/2) then call ErrorHandler('computeProdExpan','size(f,2) < jmax_f',size(f,2),(lmax_f+1)*(lmax_f+2)/2) else if (size(g,1) < nr) then call ErrorHandler('computeProdExpan','size(g,1) < nr',size(g,1),nr) else if (size(g,2) < (lmax_g+1)*(lmax_g+2)/2) then call ErrorHandler('computeProdExpan','size(g,2) < jmax_g',size(g,2),(lmax_g+1)*(lmax_g+2)/2) else if (size(h,1) < nr) then call ErrorHandler('computeProdExpan','size(h,1) < nr',size(h,1),nr) else if (size(h,2) < (lmax_h+1)*(lmax_h+2)/2) then call ErrorHandler('computeProdExpan','size(h,2) < jmax_h',size(h,2),(lmax_h+1)*(lmax_h+2)/2) endif ! kmax_f = (lmax_f+1)**2 kmax_g = (lmax_g+1)**2 kmax_h = (lmax_h+1)**2 ! nj3 => getNumK3() kj3 => getK3() cgnt => getGauntFactor() ! h = CZERO do kl_g = 1, kmax_g m_g = mofk(kl_g) jl_g = jofk(kl_g) do kl_f = 1, kmax_f m_f = mofk(kl_f) jl_f = jofk(kl_f) do j = 1, nj3(kl_f,kl_g) kl_h = kj3(j,kl_f,kl_g) if (mofk(kl_h) >= 0 .and. kl_h <= kmax_h) then jl_h = jofk(kl_h) if (m_f >= 0 .and. m_g >= 0) then cfac = cgnt(j,kl_f,kl_g) do ir = 1, nr h(ir,jl_h) = h(ir,jl_h) + cfac*conjg(f(ir,jl_f))*g(ir,jl_g) enddo else if (m_f < 0 .and. m_g >= 0) then cfac = cgnt(j,kl_f,kl_g)*m1m(m_f) do ir = 1, nr h(ir,jl_h) = h(ir,jl_h) + cfac*f(ir,jl_f)*g(ir,jl_g) enddo else if (m_f >= 0 .and. m_g < 0) then cfac = cgnt(j,kl_f,kl_g)*m1m(m_g) do ir = 1, nr h(ir,jl_h) = h(ir,jl_h) + cfac*conjg(f(ir,jl_f)*g(ir,jl_g)) enddo else cfac = cgnt(j,kl_f,kl_g)*m1m(m_f+m_g) do ir = 1, nr h(ir,jl_h) = h(ir,jl_h) + cfac*f(ir,jl_f)*conjg(g(ir,jl_g)) enddo endif endif enddo enddo enddo ! end subroutine computeProdExpan
14,995
https://github.com/manumaticx/Sandstorm.CookiePunch/blob/master/Resources/Private/KlaroTranslations/build.js
Github Open Source
Open Source
MIT
2,022
Sandstorm.CookiePunch
manumaticx
JavaScript
Code
440
1,369
var fs = require("fs"); var path = require("path"); const Handlebars = require("handlebars"); const yaml = require("js-yaml"); const templateDir = __dirname; const klaroTranslationsDir = path.join( __dirname, "../../../node_modules/klaro/src/translations" ); const fusionTranslationFile = path.join( __dirname, "../../Private/Fusion", "Config.Translations.fusion" ); const settingsYamlTranslationFile = path.join( __dirname, "../../../Configuration", "Settings.Translations.yaml" ); const xlfTranslationsDir = path.join(__dirname, "../../Private/Translations"); const xlfName = "Klaro"; ``; const autoGeneratedNotice = ` ################################################################################################ # IMPORTANT: This file was auto-generated as part of the build process to convert translations # # provided by klaro. -> see package.json -> "yarn run build:translations" # ################################################################################################ `; const fusionTemplate = Handlebars.compile( fs.readFileSync(path.join(templateDir, "fusionTemplate.hbs"), { encoding: "utf-8", }) ); const xlfTemplate = Handlebars.compile( fs.readFileSync(path.join(templateDir, "xlfTemplate.hbs"), { encoding: "utf-8", }) ); const enJson = yaml.load( fs.readFileSync(path.join(klaroTranslationsDir, "en.yml"), { encoding: "utf-8", }) ); const enFlattened = flattenJson(enJson); fs.readdir(klaroTranslationsDir, function (err, files) { files .filter((file) => file.indexOf(".yml") >= 0) .forEach((file) => { const language = file.replace(".yml", ""); const json = yaml.load( fs.readFileSync(path.join(klaroTranslationsDir, file), "utf8") ); const flattened = flattenJson(json); const xlfUnits = buildXlfUnits(flattened, language); if (language === "en") { const fusion = fusionTemplate({ units: xlfUnits, }); fs.writeFileSync(fusionTranslationFile, fusion, { encoding: "utf8", flag: "w", }); const settingsYaml = yaml.dump({ Sandstorm: { CookiePunch: { translations: jsonToYamlWithPath( json, `Sandstorm.CookiePunch:${xlfName}:` ), }, }, }); fs.writeFileSync( settingsYamlTranslationFile, autoGeneratedNotice + settingsYaml, { encoding: "utf8", flag: "w" } ); } const xlf = xlfTemplate({ units: xlfUnits, source: "en", target: language !== "en" ? language : undefined, }); const dir = path.join(xlfTranslationsDir, language); if (!fs.existsSync(dir)) { fs.mkdirSync(dir); } fs.writeFileSync(path.join(dir, `${xlfName}.xlf`), xlf, { encoding: "utf8", flag: "w", }); }); }); function buildXlfUnits(flattened, language) { return Object.keys(flattened).map((key) => { if (language !== "en") { return { id: key, target: flattened[key], source: enFlattened[key], language: language, }; } else { return { id: key, source: flattened[key], language: language, }; } }); } function flattenJson(data) { var result = {}; function recurse(cur, prop) { if (Object(cur) !== cur) { result[prop] = cur; } else if (Array.isArray(cur)) { for (var i = 0, l = cur.length; i < l; i++) recurse(cur[i], prop ? prop + "." + i : "" + i); if (l == 0) result[prop] = []; } else { var isEmpty = true; for (var p in cur) { isEmpty = false; recurse(cur[p], prop ? prop + "." + p : p); } if (isEmpty) result[prop] = {}; } } recurse(data, ""); return result; } function jsonToYamlWithPath(data, path = "") { let clonedData = JSON.parse(JSON.stringify(data)); function recurse(current, path) { if (typeof current === "object") { for (let property in current) { if (current.hasOwnProperty(property)) { if (typeof current[property] === "object") { recurse(current[property], path + property + "."); } else { current[property] = path + property; } } } } } recurse(clonedData, path); return clonedData; }
35,267
https://github.com/wojtekblack/ludumdare30/blob/master/project/Assets/Animations/MovingPlatform1.anim.meta
Github Open Source
Open Source
MIT
2,014
ludumdare30
wojtekblack
Unity3D Asset
Code
6
37
fileFormatVersion: 2 guid: 9557195970daf794b8708f4cd5753972 NativeFormatImporter: userData:
17,047
https://github.com/petnagy/android_architect_playground/blob/master/app/src/main/java/com/playground/android_architect_playground/inject/modules/ColorFragmentModule.java
Github Open Source
Open Source
Apache-2.0
null
android_architect_playground
petnagy
Java
Code
39
191
package com.playground.android_architect_playground.inject.modules; import android.arch.lifecycle.LifecycleRegistry; import com.playground.android_architect_playground.inject.PerActivity; import com.playground.android_architect_playground.pages.colorpage.ColorActivity; import com.playground.android_architect_playground.pages.colorpage.view.ColorFragment; import dagger.Module; import dagger.Provides; /** * Created by petnagy on 2017. 07. 06.. */ @Module public class ColorFragmentModule { @Provides LifecycleRegistry provideLifeCycleRegistry(ColorFragment fragment) { return new LifecycleRegistry(fragment); } }
40,836
https://github.com/universal-development/parsers-service/blob/master/parsers-service-app/src/main/java/com/unidev/parsers/controller/ParserController.java
Github Open Source
Open Source
Apache-2.0
null
parsers-service
universal-development
Java
Code
75
401
package com.unidev.parsers.controller; import com.unidev.parsers.model.Parser; import com.unidev.parsers.model.ParserRequest; import com.unidev.parsers.model.ParserResponse; import com.unidev.parsers.service.ParsersService; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @RestController @RequestMapping("/api") public class ParserController { @Autowired private ParsersService parsersService; @GetMapping("parsers") public List<String> fetch() { return parsersService.parserIds(); } @PostMapping("parser/{id}") public Mono<ParserResponse> parser(@PathVariable("id") String id, @RequestBody ParserRequest parserRequest) { Optional<Parser> parser = parsersService.fetchParser(id); if (!parser.isPresent()) { throw new ParserNotFoundException(); } return Mono.just(parser.get().process(parserRequest)); } }
21,179
https://github.com/thdiaman/GDDownloader/blob/master/helpers.py
Github Open Source
Open Source
Apache-2.0
2,018
GDDownloader
thdiaman
Python
Code
212
530
import json def get_number_of(gdownloader, repo_api_address, statistic_type, parameter = None): """ Posts a request using an instance of GithubDownloader and returns the number of a given statistic (e.g. number of issues, number of commits, etc.). :param gdownloader: an instance of GithubDownloader. :param statistic_type: the type for which the statistic is downloaded. :param parameter: an optional parameter for the statistic (e.g. for issues set this to "state=all" to get all of them). :returns: the value for the statistic as an absolute number. """ r = gdownloader.download_request(repo_api_address + "/" + statistic_type, ["per_page=100"] if parameter == None else ["per_page=100", parameter]) if "link" in r.headers: address = r.headers["link"].split(',')[1].split('<')[1].split('>')[0] data = gdownloader.download_object(address) return 100 * (int(address.split('=')[-1]) - 1) + len(data) if data != None else None else: data = json.loads(r.text or r.content) if r.status_code != 204 else {} return len(data) def read_file_in_lines(filename): """ Reads a file into lines. :param filename: the filename of the file to be read. :returns: a list with the lines of the file. """ with open(filename) as infile: lines = infile.readlines() return [line.strip() for line in lines] def print_usage(): """ Prints the usage information of this python file. """ print("Usage: python gddownloader.py arg") print("where arg can be one of the following:") print(" github url (e.g. https://github.com/user/repo)") print(" path to txt file containing github urls")
5,376
https://github.com/fdeleo/alugaqui-webserver/blob/master/node_modules/intern/browser_modules/dojo/_debug/Observable.ts
Github Open Source
Open Source
MIT
2,017
alugaqui-webserver
fdeleo
TypeScript
Code
484
1,454
import core = require('./interfaces'); import lang = require('./lang'); import Scheduler = require('./Scheduler'); interface ICallbackObject { removed?: boolean; callback: core.IObserver<any>; } interface INotification { newValue: any; oldValue: any; callbacks: Array<ICallbackObject>; } // TODO: `informImmediately` is a strange beast, but something that is useful. // I need to experiment with a different mechanism for calling the observer // initially than providing a boolean parameter to `observe()`. class Observable implements core.IObservable { private _callbacks: { [property: string]: ICallbackObject[] }; private _notifications: { [property: string]: INotification }; private _timer: core.IHandle; constructor(props?: any) { if (props) { lang.mixin(this, props); } Object.defineProperties(this, { _callbacks: { value: {} }, _dispatch: { configurable: true, value: this._dispatch.bind(this), writable: true }, _notifications: { value: Object.create(null), writable: true }, _timer: { value: null, writable: true } }); } private _dispatch() { if (this._timer) { this._timer.remove(); this._timer = null; } // Grab the current notifications and immediately create a new hash // to start storing any notifications that might be generated this turn var notifications = this._notifications; this._notifications = Object.create(null); for (var property in notifications) { var notification = notifications[property]; if (this._isEqual(notification.oldValue, notification.newValue)) { // If a different-value notification is in-flight and something changes // the value back to what it started as, skip the notification continue; } var callback: ICallbackObject; for (var i = 0; (callback = notification.callbacks[i]); i++) { // If a callback was removed after the notification was scheduled to // start, don't call it if (!callback.removed) { callback.callback.call(this, notification.newValue, notification.oldValue); } } } } _isEqual(a: any, b: any): boolean { return lang.isEqual(a, b); } /* tslint:disable:no-unused-variable */ private _notify<T>(property: string, newValue: T, oldValue: T): void { /* tslint:enable:no-unused-variable */ var callbacks = this._callbacks[property]; if (!callbacks || !callbacks.length) { return; } var notification = this._notifications[property]; if (notification) { notification.newValue = newValue; } else { // Create a notification and give it a copy of the callbacks // that are currently registered this._notifications[property] = { newValue: newValue, oldValue: oldValue, callbacks: callbacks.slice(0) }; } this._schedule(); } observe<T>(property: string, callback: core.IObserver<T>): core.IHandle { var callbackObject: ICallbackObject = { callback: callback }; if (!this._callbacks[property]) { var oldDescriptor = lang.getPropertyDescriptor(this, property), currentValue: any = (<any> this)[property], descriptor: PropertyDescriptor = { configurable: true, enumerable: true }; if (oldDescriptor && !('value' in oldDescriptor)) { descriptor.get = oldDescriptor.get; if (oldDescriptor.set) { descriptor.set = function (value: any) { oldDescriptor.set.apply(this, arguments); var newValue = descriptor.get.call(this); this._notify(property, newValue, currentValue); currentValue = newValue; }; } } else { // property descriptor.get = () => { return currentValue; }; if (oldDescriptor.writable) { descriptor.set = function (newValue: any) { this._notify(property, newValue, currentValue); currentValue = newValue; }; } } Object.defineProperty(this, property, descriptor); this._callbacks[property] = [callbackObject]; } else { this._callbacks[property].push(callbackObject); } var self = this; return { remove: function () { this.remove = () => {}; // remove from in-flight notifications callbackObject.removed = true; // remove from future notifications lang.pullFromArray(self._callbacks[property], callbackObject); } }; } _schedule(): void { if (!this._timer) { this._timer = Scheduler.schedule(this._dispatch); } } } export = Observable;
9,504
https://github.com/ulises-jeremias/pdytr/blob/master/practica-4/resources/given/jade/src/jade/src/jade/core/mobility/MobileAgentClassLoader.java
Github Open Source
Open Source
MIT, LGPL-2.1-only, LGPL-2.0-or-later
2,021
pdytr
ulises-jeremias
Java
Code
505
1,513
/***************************************************************** JADE - Java Agent DEvelopment Framework is a framework to develop multi-agent systems in compliance with the FIPA specifications. Copyright (C) 2000 CSELT S.p.A. GNU Lesser General Public License This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, version 2.1 of the License. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *****************************************************************/ package jade.core.mobility; import jade.core.ServiceFinder; import jade.core.IMTPException; import jade.core.ServiceException; import jade.util.Logger; //#MIDP_EXCLUDE_FILE /** @author Giovanni Rimassa - FRAMeTech s.r.l. */ class MobileAgentClassLoader extends ClassLoader { private AgentMobilitySlice classServer; private String agentName; private String sliceName; private ServiceFinder finder; private Logger myLogger = Logger.getMyLogger(AgentMobilityService.NAME); public MobileAgentClassLoader(String an, String sn, ServiceFinder sf, ClassLoader parent) throws IMTPException, ServiceException { //#PJAVA_EXCLUDE_BEGIN super(parent); //#PJAVA_EXCLUDE_END agentName = an; sliceName = sn; finder = sf; classServer = (AgentMobilitySlice)finder.findSlice(AgentMobilitySlice.NAME, sliceName); if (classServer == null) { throw new ServiceException("Code source container "+sliceName+" does not exist or does not support mobility"); } } protected Class findClass(String name) throws ClassNotFoundException { byte[] classFile; try { if(myLogger.isLoggable(Logger.FINE)) { myLogger.log(Logger.FINE,"Remote retrieval of code for class " + name); } try { classFile = classServer.fetchClassFile(name, agentName); } catch(IMTPException imtpe) { // Get a fresh slice and retry classServer = (AgentMobilitySlice)finder.findSlice(AgentMobilitySlice.NAME, sliceName); classFile = classServer.fetchClassFile(name, agentName); } } catch (IMTPException imtpe) { imtpe.printStackTrace(); throw new ClassNotFoundException(name); } catch (ServiceException se) { throw new ClassNotFoundException(name); } if (classFile != null) { if(myLogger.isLoggable(Logger.FINE)) { myLogger.log(Logger.FINE,"Code of class " + name + " retrieved. Length is " + classFile.length); } return defineClass(name, classFile, 0, classFile.length); } else { throw new ClassNotFoundException(name); } } protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { Class c = null; if(myLogger.isLoggable(Logger.FINER)) { myLogger.log(Logger.FINER,"Loading class " + name); } //#PJAVA_EXCLUDE_BEGIN c = super.loadClass(name, resolve); //#PJAVA_EXCLUDE_END //#DOTNET_EXCLUDE_BEGIN /*#PJAVA_INCLUDE_BEGIN In PersonalJava loadClass(String, boolean) is abstract --> we must implement it // 1) Try to see if the class has already been loaded c = findLoadedClass(name); // 2) Try to load the class using the system class loader if(c == null) { try { c = findSystemClass(name); } catch (ClassNotFoundException cnfe) { } } // 3) If still not found, try to load the class from the proper site if(c == null) { c = findClass(name); } if(resolve) { resolveClass(c); } #PJAVA_INCLUDE_END*/ //#DOTNET_EXCLUDE_END /*#DOTNET_INCLUDE_BEGIN System.Type myType = System.Type.GetType(name); if (myType == null) { //resolveClass(c); boolean found = false; int i = 0; System.Reflection.Assembly[] assemblies = System.AppDomain.get_CurrentDomain().GetAssemblies(); while (!found && i<assemblies.length) { myType = assemblies[i].GetType(name); found = (myType != null); i++; } c = Class.FromType( myType ); } #DOTNET_INCLUDE_END*/ if(myLogger.isLoggable(Logger.FINER)) { myLogger.log(Logger.FINER,"Class " + name + " loaded" ); } return c; } }
21,662
https://github.com/ghandhikus/TworcyGierStrona/blob/master/src/main/java/com/clockwise/tworcy/model/chat/ChatService.java
Github Open Source
Open Source
MIT
2,016
TworcyGierStrona
ghandhikus
Java
Code
37
130
package com.clockwise.tworcy.model.chat; import java.util.List; import org.springframework.stereotype.Repository; import org.springframework.stereotype.Service; import com.clockwise.tworcy.model.account.Account; public @Service @Repository interface ChatService { public void getMessages(Account account, List<String> json, Integer lastMessage); public void newMessages(Account account, String[] messages); public void newMessage(Account account, String msg); }
27,494
https://github.com/UrosGligovic/crawl/blob/master/src/main/java/rs/ugligovic/crawl/crawlers/PageCrawler.java
Github Open Source
Open Source
Apache-2.0
null
crawl
UrosGligovic
Java
Code
63
158
/* * 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. */ package rs.ugligovic.crawl.crawlers; import java.time.LocalDate; import java.time.LocalDateTime; import org.jsoup.nodes.Document; /** * * @author Uros Gligovic */ public interface PageCrawler { void setDocument(Document document); String findHeadline(); String findContent(); LocalDate findDate(); String findAuthor(); }
14,214
https://github.com/zodsoft/SCJMapper-V2/blob/master/Joystick/Options.cs
Github Open Source
Open Source
MIT
2,016
SCJMapper-V2
zodsoft
C#
Code
1,398
4,054
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using System.IO; using System.Xml.Linq; using System.Windows.Forms; namespace SCJMapper_V2.Joystick { /// <summary> /// Maintains an Options - something like: /// /// <options type="joystick" instance="1"> /// <!-- Make all piloting input linear --> /// <pilot exponent="1" /> /// </options> /// /// <options type="joystick" instance="2" > /// <flight_move_strafe_longitudinal invert="1" /> /// </options> /// /// [type] : set to shared, keyboard, xboxpad, or joystick /// [instance] : set to the device number; js1=1, js2=2, etc /// [optiongroup] : set to what group the option should affect (for available groups see default actionmap) /// [option] : instance, sensitivity, exponent, nonlinearity *instance is a bug that will be fixed to 'invert' in the future /// [value] : for invert use 0/1; for others use 0.0 to 2.0 /// /// options are given per deviceClass and instance - it seems /// </summary> public class Options { private static readonly log4net.ILog log = log4net.LogManager.GetLogger( System.Reflection.MethodBase.GetCurrentMethod( ).DeclaringType ); // Support only one set of independent options (string storage) List<string> m_stringOptions = new List<string>( ); // Support only one set of TuningParameters (there is only ONE Joystick Pitch, Yaw, Roll control possible, they can be on different instances however) DeviceTuningParameter m_tuningP = null; // pitch DeviceTuningParameter m_tuningY = null; // yaw DeviceTuningParameter m_tuningR = null; // roll DeviceTuningParameter m_tuningVert = null; // strafe vertical DeviceTuningParameter m_tuningLat = null; // strafe lateral DeviceTuningParameter m_tuningLon = null; // strafe longitudinal // Have to support Inverters for all possible JS Instances here - right now 4 are supported - provide them for all 12 we support.. public List<OptionsInvert> m_inverter = new List<OptionsInvert>( ); // all inverters private List<CheckBox> m_invertCB = null; // Options owns and handles all Inversions // ctor public Options( JoystickList jsList ) { m_tuningP = new DeviceTuningParameter( ); m_tuningY = new DeviceTuningParameter( ); m_tuningR = new DeviceTuningParameter( ); m_tuningVert = new DeviceTuningParameter( ); m_tuningLat = new DeviceTuningParameter( ); m_tuningLon = new DeviceTuningParameter( ); // create inverters ( for ( int i = 0; i < ( int )OptionsInvert.Inversions.I_LAST; i++ ) { OptionsInvert inv = new OptionsInvert((OptionsInvert.Inversions)i); m_inverter.Add( inv ); } } public int Count { get { return ( m_stringOptions.Count + ( ( m_tuningP != null ) ? 1 : 0 ) + ( ( m_tuningY != null ) ? 1 : 0 ) + ( ( m_tuningR != null ) ? 1 : 0 ) ); } } // provide access to Tuning items /// <summary> /// Returns the Pitch-Tuning item /// </summary> public DeviceTuningParameter TuneP { get { return m_tuningP; } } /// <summary> /// Returns the Yaw-Tuning item /// </summary> public DeviceTuningParameter TuneY { get { return m_tuningY; } } /// <summary> /// Returns the Roll-Tuning item /// </summary> public DeviceTuningParameter TuneR { get { return m_tuningR; } } /// <summary> /// Returns the Strafe Vertical-Tuning item /// </summary> public DeviceTuningParameter TuneVert { get { return m_tuningVert; } } /// <summary> /// Returns the Strafe Lateral-Tuning item /// </summary> public DeviceTuningParameter TuneLat { get { return m_tuningLat; } } /// <summary> /// Returns the Strafe Longitudinal-Tuning item /// </summary> public DeviceTuningParameter TuneLon { get { return m_tuningLon; } } /// <summary> /// Returns the inverter based on the enum given /// </summary> /// <param name="item">The inverter enum</param> /// <returns>An Inverter object</returns> public OptionsInvert Inverter( OptionsInvert.Inversions item ) { // instance is 1.. - array is 0... return m_inverter[( int )item]; } /// <summary> /// Assign the GUI Invert Checkboxes for further handling /// </summary> public List<CheckBox> InvertCheckList { set { m_invertCB = value; // assuming the ENUM sequence of Checkboxes here... // Note: the flight Flight ones above are not handled twice i.e. are assigned below but not used int i = 0; foreach ( OptionsInvert inv in m_inverter ) { inv.CBInvert = m_invertCB[i++]; } } } /// <summary> /// Clears all Inverters /// </summary> public void ResetInverter( ) { foreach ( OptionsInvert inv in m_inverter ) { inv.Reset( ); } } private string[] FormatXml( string xml ) { try { XDocument doc = XDocument.Parse( xml ); return doc.ToString( ).Split( new string[] { string.Format( "\n" ) }, StringSplitOptions.RemoveEmptyEntries ); } catch ( Exception ) { return new string[] { xml }; } } /// <summary> /// Dump the Options as partial XML nicely formatted /// </summary> /// <returns>the action as XML fragment</returns> public string toXML( ) { string r = ""; // and dump the contents of plain string options foreach ( string x in m_stringOptions ) { if ( !string.IsNullOrWhiteSpace( x ) ) { foreach ( string line in FormatXml( x ) ) { r += string.Format( "\t{0}", line ); } } r += string.Format( "\n" ); } // dump Tuning r += m_tuningY.Options_toXML( ); r += m_tuningP.Options_toXML( ); r += m_tuningR.Options_toXML( ); r += m_tuningLat.Options_toXML( ); r += m_tuningVert.Options_toXML( ); r += m_tuningLon.Options_toXML( ); r += m_inverter[( int )OptionsInvert.Inversions.flight_aim_pitch].Options_toXML( ); r += m_inverter[( int )OptionsInvert.Inversions.flight_aim_yaw].Options_toXML( ); r += m_inverter[( int )OptionsInvert.Inversions.flight_view_pitch].Options_toXML( ); r += m_inverter[( int )OptionsInvert.Inversions.flight_view_yaw].Options_toXML( ); // r += m_inverter[( int )OptionsInvert.Inversions.flight_move_strafe_vertical].Options_toXML( ); // r += m_inverter[( int )OptionsInvert.Inversions.flight_move_strafe_lateral].Options_toXML( ); // r += m_inverter[( int )OptionsInvert.Inversions.flight_move_strafe_longitudinal].Options_toXML( ); r += m_inverter[( int )OptionsInvert.Inversions.flight_throttle].Options_toXML( ); return r; } /// <summary> /// Read an Options from XML - do some sanity check /// </summary> /// <param name="xml">the XML action fragment</param> /// <returns>True if an action was decoded</returns> public Boolean fromXML( string xml ) { /* * This can be a lot of the following options * try to do our best.... * * <options type="joystick" instance="1"> <pilot_rot_moveyaw instance="1" sensitivity="0.8" exponent="1.2" /> </options> * <options type="joystick" instance="1"> <flight> <nonlinearity_curve> <point in="0.1" out="0.001"/> <point in="0.25" out="0.02"/> <point in="0.5" out="0.1"/> <point in="0.75" out="0.125"/> <point in="0.85" out="0.15"/> <point in="0.90" out="0.175"/> <point in="0.925" out="0.25"/> <point in="0.94" out="0.45"/> <point in="0.95" out="0.75"/> </nonlinearity_curve> </flight> </options> */ XmlReaderSettings settings = new XmlReaderSettings( ); settings.ConformanceLevel = ConformanceLevel.Fragment; settings.IgnoreWhitespace = true; settings.IgnoreComments = true; XmlReader reader = XmlReader.Create( new StringReader( xml ), settings ); reader.Read( ); string type = ""; string instance = ""; int nInstance = 0; if ( reader.HasAttributes ) { type = reader["type"]; if ( !( ( type.ToLowerInvariant( ) == "joystick" ) || ( type.ToLowerInvariant( ) == "xboxpad" ) ) ) { // save as plain text if ( !m_stringOptions.Contains( xml ) ) m_stringOptions.Add( xml ); return true; } // further on.. instance = reader["instance"]; if ( !int.TryParse( instance, out nInstance ) ) nInstance = 0; reader.Read( ); // try to disassemble the items /* * <flight> instance="0/1" sensitivity="n.nn" exponent="n.nn" (instance should be invert) * <flight_move> * <flight_move_pitch> * <flight_move_yaw> * <flight_move_roll> * <flight_move_strafe_vertical> * <flight_move_strafe_lateral> * <flight_move_strafe_longitudinal> * <flight_throttle> invert="0/1" * <flight_throttle_abs> * <flight_throttle_rel> * <flight_aim> * <flight_aim_pitch> * <flight_aim_yaw> * <flight_view> * <flight_view_pitch> * <flight_view_yaw> * * <nonlinearity_curve> <point in="0.1" out="0.001"/> * .. </nonlinearity_curve> * * * */ while ( !reader.EOF ) { if ( reader.Name.ToLowerInvariant( ) == "flight_move_pitch" ) { m_tuningP.Options_fromXML( reader, type, int.Parse( instance ) ); } else if ( reader.Name.ToLowerInvariant( ) == "flight_move_yaw" ) { m_tuningY.Options_fromXML( reader, type, int.Parse( instance ) ); } else if ( reader.Name.ToLowerInvariant( ) == "flight_move_roll" ) { m_tuningR.Options_fromXML( reader, type, int.Parse( instance ) ); } else if ( reader.Name.ToLowerInvariant( ) == "flight_move_strafe_vertical" ) { m_tuningVert.Options_fromXML( reader, type, int.Parse( instance ) ); //m_inverter[( int )OptionsInvert.Inversions.flight_move_strafe_vertical].Options_fromXML( reader, type, int.Parse( instance ) ); } else if ( reader.Name.ToLowerInvariant( ) == "flight_move_strafe_lateral" ) { m_tuningLat.Options_fromXML( reader, type, int.Parse( instance ) ); //m_inverter[( int )OptionsInvert.Inversions.flight_move_strafe_lateral].Options_fromXML( reader, type, int.Parse( instance ) ); } else if ( reader.Name.ToLowerInvariant( ) == "flight_move_strafe_longitudinal" ) { m_tuningLon.Options_fromXML( reader, type, int.Parse( instance ) ); //m_inverter[( int )OptionsInvert.Inversions.flight_move_strafe_longitudinal].Options_fromXML( reader, type, int.Parse( instance ) ); } else if ( reader.Name.ToLowerInvariant( ) == "flight_aim_pitch" ) { m_inverter[( int )OptionsInvert.Inversions.flight_aim_pitch].Options_fromXML( reader, type, int.Parse( instance ) ); } else if ( reader.Name.ToLowerInvariant( ) == "flight_aim_yaw" ) { m_inverter[( int )OptionsInvert.Inversions.flight_aim_yaw].Options_fromXML( reader, type, int.Parse( instance ) ); } else if ( reader.Name.ToLowerInvariant( ) == "flight_view_pitch" ) { m_inverter[( int )OptionsInvert.Inversions.flight_view_pitch].Options_fromXML( reader, type, int.Parse( instance ) ); } else if ( reader.Name.ToLowerInvariant( ) == "flight_view_yaw" ) { m_inverter[( int )OptionsInvert.Inversions.flight_view_yaw].Options_fromXML( reader, type, int.Parse( instance ) ); } // Throttle abs/rel are treated the same and use the throttle group only else if ( reader.Name.ToLowerInvariant( ) == "flight_throttle" ) { m_inverter[( int )OptionsInvert.Inversions.flight_throttle].Options_fromXML( reader, type, int.Parse( instance ) ); } else if ( reader.NodeType != XmlNodeType.EndElement ) { //?? log.InfoFormat( "Options.fromXML: unknown node - {0} - stored as is", reader.Name ); if ( !m_stringOptions.Contains( xml ) ) m_stringOptions.Add( xml ); } reader.Read( ); } } return true; } } }
36,568
https://github.com/darthcav/tutorial-java-rest-google/blob/master/src/main/java/io/github/cavweb20/google/GoogleResponse.java
Github Open Source
Open Source
MIT
2,015
tutorial-java-rest-google
darthcav
Java
Code
93
269
package io.github.cavweb20.google; /** * * @author cavweb20 */ public class GoogleResponse { private ResponseData responseData = null; private String responseDetails = null; private int responseStatus; private Cursor cursor; public Cursor getCursor() { return cursor; } public void setCursor(Cursor cursor) { this.cursor = cursor; } public ResponseData getResponseData() { return responseData; } public void setResponseData(ResponseData responseData) { this.responseData = responseData; } public String getResponseDetails() { return responseDetails; } public void setResponseDetails(String responseDetails) { this.responseDetails = responseDetails; } public int getResponseStatus() { return responseStatus; } public void setResponseStatus(int responseStatus) { this.responseStatus = responseStatus; } }
283
https://github.com/robertdigital/fix-rust/blob/master/fixclient/src/connector/memstore.rs
Github Open Source
Open Source
Apache-2.0
2,018
fix-rust
robertdigital
Rust
Code
239
746
use std::io::{self}; use super::{MessageStore, MessageStoreState}; use super::super::sender::Sender; use super::super::FixSessionConfig; use fix::frame::FixFrame; pub struct MemoryMessageStore { state: MessageStoreState, messages : Vec<FixFrame>, } impl MemoryMessageStore { pub fn new( _cfg: &FixSessionConfig ) -> io::Result<MemoryMessageStore> { Ok( MemoryMessageStore { state : MessageStoreState::new(), messages: vec![], }) } pub fn add_to_store(&mut self, frame: FixFrame) { self.messages.push( frame ); let _ = self.state.incr_sender_seq_num(); } pub fn overwrite_seqs(&mut self, sender: i32, target: i32 ) { self.state.overwrite_seqs( sender, target ); } } impl MessageStore for MemoryMessageStore { fn init(&mut self, _sender: Sender) { } fn overwrite_target_seq(&mut self, new_seq: i32) -> io::Result<()> { self.state.target_seq = new_seq; Ok( () ) } fn overwrite_sender_seq(&mut self, new_seq: i32) -> io::Result<()> { self.state.sender_seq = new_seq; Ok( () ) } fn sent(&mut self, frame: &FixFrame) -> io::Result<()> { self.messages.push( frame.clone() ); Ok( () ) } fn received(&mut self, _frame: &FixFrame) -> io::Result<()> { Ok( () ) } fn query(&mut self, begin: i32, end: i32) -> io::Result<Vec<FixFrame>> { let mut subset = vec![]; for frame in self.messages.iter() { let seq = frame.header.msg_seq_num; if seq >= begin && (end == 0 || seq <= end) { subset.push( frame.clone() ); } } Ok( subset ) } fn incr_sender_seq_num(&mut self) -> io::Result<i32> { Ok ( self.state.incr_sender_seq_num() ) } fn incr_target_seq_num(&mut self) -> io::Result<i32> { Ok ( self.state.incr_target_seq_num() ) } fn reset_seqs(&mut self) -> io::Result<()> { self.state.reset(); Ok( () ) } fn get_state(&self) -> &MessageStoreState { &self.state } fn close(self) -> io::Result<()> { Ok( () ) } }
1,614
https://github.com/krishnaIndia/MaidsafeJenkins/blob/master/src/main/java/com/jenkinsci/plugins/MaidsafeJenkins/Exception/TooManyPRForModule.java
Github Open Source
Open Source
MIT
null
MaidsafeJenkins
krishnaIndia
Java
Code
40
108
package com.jenkinsci.plugins.MaidsafeJenkins.Exception; public class TooManyPRForModule extends Exception { private String moduleName; public TooManyPRForModule(String moduleName) { this.moduleName = moduleName; } @Override public String getMessage() { return "More than one matching Pull Request found in module - " + moduleName; } }
8,065
https://github.com/ashish-narwal/nalaf/blob/master/nalaf/domain/bio/gnormplus.py
Github Open Source
Open Source
Apache-2.0
2,022
nalaf
ashish-narwal
Python
Code
301
994
import difflib from nalaf.learning.taggers import Tagger from nalaf.utils.ncbi_utils import GNormPlus from nalaf.utils.uniprot_utils import Uniprot from nalaf.structures.data import Entity class GNormPlusGeneTagger(Tagger): """ Performs tagging for genes with GNormPlus. Is able to add normalisations for uniprot as well. :type crf_suite: nalaf.learning.crfsuite.CRFSuite """ def __init__(self, ggp_e_id, entrez_gene_id, uniprot_id): super().__init__([ggp_e_id, entrez_gene_id, uniprot_id]) def __find_offset_adjustments(self, s1, s2, start_offset): return [(start_offset+i1, j2-j1-i2+i1) for type, i1, i2, j1, j2 in difflib.SequenceMatcher(None, s1, s2).get_opcodes() if type in ['replace', 'insert']] def tag(self, dataset, annotated=False, uniprot=False, process_only_abstract=True): """ :type dataset: nalaf.structures.data.Dataset :param annotated: if True then saved into annotations otherwise into predicted_annotations """ with GNormPlus() as gnorm: for doc_id, doc in dataset.documents.items(): if process_only_abstract: genes, gnorm_title, gnorm_abstract = gnorm.get_genes_for_pmid(doc_id, postproc=True) if uniprot: with Uniprot() as uprot: list_of_ids = gnorm.uniquify_genes(genes) genes_mapping = uprot.get_uniprotid_for_entrez_geneid(list_of_ids) else: genes_mapping = {} # find the title and the abstract parts = iter(doc.parts.values()) title = next(parts) abstract = next(parts) adjustment_offsets = [] if title.text != gnorm_title: adjustment_offsets += self.__find_offset_adjustments(title.text, gnorm_title, 0) if abstract.text != gnorm_abstract: adjustment_offsets += self.__find_offset_adjustments(abstract.text, gnorm_abstract, len(gnorm_title)) for start, end, text, gene_id in genes: if 0 <= start < end <= len(title.text): part = title else: part = abstract # we have to readjust the offset since GnormPlus provides # offsets for title and abstract together offset = len(title.text) + 1 start -= offset end -= offset for adjustment_offset, adjustment in adjustment_offsets: if start > adjustment_offset: start -= adjustment # discussion which confidence value for gnormplus because there is no value supplied ann = Entity(class_id=self.predicts_classes[0], offset=start, text=text, confidence=0.5) try: norm_dict = { self.predicts_classes[1]: gene_id, self.predicts_classes[2]: genes_mapping[gene_id] } except KeyError: norm_dict = {self.predicts_classes[1]: gene_id} norm_string = '' # todo normalized_text (stemming ... ?) ann.norms = norm_dict ann.normalized_text = norm_string if annotated: part.annotations.append(ann) else: part.predicted_annotations.append(ann) else: # todo this is not used for now anywhere, might need to be re-worked or excluded # genes = gnorm.get_genes_for_text(part.text) pass
14,819
https://github.com/TANHAIYU/Self-calibration-using-Homography-Constraints/blob/master/cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_RealSchur_RealSchur_MatrixType.cpp
Github Open Source
Open Source
BSD-3-Clause
2,020
Self-calibration-using-Homography-Constraints
TANHAIYU
C++
Code
96
215
#include <Eigen/Dense> #include <iostream> using namespace Eigen; using namespace std; int main(int, char**) { cout.precision(3); MatrixXd A = MatrixXd::Random(6,6); cout << "Here is a random 6x6 matrix, A:" << endl << A << endl << endl; RealSchur<MatrixXd> schur(A); cout << "The orthogonal matrix U is:" << endl << schur.matrixU() << endl; cout << "The quasi-triangular matrix T is:" << endl << schur.matrixT() << endl << endl; MatrixXd U = schur.matrixU(); MatrixXd T = schur.matrixT(); cout << "U * T * U^T = " << endl << U * T * U.transpose() << endl; return 0; }
27,533
https://github.com/NemesisGames/Amazon/blob/master/src/Amazon.Route53/Actions/ListTrafficPolicyInstancesByPolicyRequest.cs
Github Open Source
Open Source
MIT
2,020
Amazon
NemesisGames
C#
Code
10
28
namespace Amazon.Route53 { public sealed class ListTrafficPolicyInstancesByPolicyRequest { } }
14,020
https://github.com/pprpc/ftconn/blob/master/relay-ms/logic/LRelayStepTwo.go
Github Open Source
Open Source
Apache-2.0
null
ftconn
pprpc
Go
Code
137
572
package logic import ( "fmt" errc "github.com/pprpc/ftconn/common/errorcode" "github.com/pprpc/ftconn/model/ftconn" "github.com/pprpc/util/common" "github.com/pprpc/core" "github.com/pprpc/core/packets" "xcthings.com/protoc/ftconnrelay/RelayStepTwo" lc "github.com/pprpc/ftconn/relay-ms/common" m "github.com/pprpc/ftconn/relay-ms/model" ) // LRelayStepTwo RelayStepTwo Business logic func LRelayStepTwo(c pprpc.RPCConn, pkg *packets.CmdPacket, req *RelayStepTwo.Req) (resp *RelayStepTwo.Resp, code uint64, err error) { if lc.AuthDevice(req.Did, req.DidSignkey) == false { code = errc.ACCOUNTNOTMATCH err = fmt.Errorf("Did: %s, SignKey: %s not match", req.Did, req.DidSignkey) return } q := new(ftconn.Relayinfo) q.SessionKey = req.SessionKey code, err = q.GetBySessionKey() if err != nil { return } if q.UserID != req.RemoteUid || q.Did != req.Did { code = errc.CONNSESSIONKEYNOTMATCH err = fmt.Errorf("SessionKey: %s not match(%d - %s)", req.SessionKey, req.RemoteUid, req.Did) return } curMS := common.GetTimeMs() if curMS-q.UserTime > 3000 { code = errc.SESSIONKEYTIMEOUT err = fmt.Errorf("SessionKey: %s timeout(%d - %s), %d - %d = %d", req.SessionKey, req.RemoteUid, req.Did, curMS, q.UserTime, curMS-q.UserTime) return } resp, code, err = m.MRelayStepTwo(req) return }
13,183
https://github.com/rgrempel/purescript-sequences/blob/master/test/Utils.purs
Github Open Source
Open Source
MIT
null
purescript-sequences
rgrempel
PureScript
Code
1,080
2,423
module Tests.Utils where import Prelude import Data.Array as A import Data.Function (on) import Data.Foldable (class Foldable, intercalate, foldr, foldMap) import Data.Maybe (Maybe(Nothing, Just)) import Data.Monoid (class Monoid, mempty) import Data.Monoid.Additive (Additive(Additive)) import Data.Newtype (un) import Control.Alt (class Alt, (<|>)) import Control.Plus (class Plus, empty) import Control.Alternative (class Alternative) import Control.MonadPlus (class MonadPlus) import Control.MonadZero (class MonadZero) import Test.QuickCheck (class Testable, QC, (<?>), quickCheck', Result) import Test.QuickCheck.Arbitrary (class Arbitrary, arbitrary) import Test.QuickCheck.Gen (Gen()) import Data.Sequence as S import Data.Sequence.NonEmpty as NES import Data.Sequence.Ordered as OS ----------------------------- --- newtype wrappers ----------------- -- Data.Sequence newtype ArbSeq a = ArbSeq (S.Seq a) unArbSeq :: forall b. ArbSeq b -> S.Seq b unArbSeq (ArbSeq xs) = xs instance eqArbSeq :: (Eq a) => Eq (ArbSeq a) where eq = eq `on` unArbSeq instance ordArbSeq :: (Ord a) => Ord (ArbSeq a) where compare = compare `on` unArbSeq instance functorArbSeq :: Functor ArbSeq where map f = ArbSeq <<< map f <<< unArbSeq instance applyArbSeq :: Apply ArbSeq where apply fs xs = ArbSeq (apply (unArbSeq fs) (unArbSeq xs)) instance applicativeArbSeq :: Applicative ArbSeq where pure = ArbSeq <<< pure instance bindArbSeq :: Bind ArbSeq where bind xs f = ArbSeq (bind (unArbSeq xs) (unArbSeq <<< f)) instance monadArbSeq :: Monad ArbSeq instance showArbSeq :: (Show a) => Show (ArbSeq a) where show = show <<< unArbSeq instance semigroupArbSeq :: Semigroup (ArbSeq a) where append (ArbSeq xs) (ArbSeq ys) = ArbSeq (xs <> ys) instance monoidArbSeq :: Monoid (ArbSeq a) where mempty = ArbSeq mempty instance altArbSeq :: Alt ArbSeq where alt (ArbSeq xs) (ArbSeq ys) = ArbSeq (xs <|> ys) instance plusArbSeq :: Plus ArbSeq where empty = ArbSeq empty instance alternativeArbseq :: Alternative ArbSeq instance monadPlusArbSeq :: MonadPlus ArbSeq instance monadZeroArbSeq :: MonadZero ArbSeq instance arbitraryArbSeq :: (Arbitrary a) => Arbitrary (ArbSeq a) where arbitrary = (ArbSeq <<< S.fromFoldable) <$> (arbitrary :: Gen (Array a)) -------------------------- -- Data.Sequence.NonEmpty newtype ArbNESeq a = ArbNESeq (NES.Seq a) unArbNESeq :: forall b. ArbNESeq b -> NES.Seq b unArbNESeq (ArbNESeq xs) = xs instance eqArbNESeq :: (Eq a) => Eq (ArbNESeq a) where eq = eq `on` unArbNESeq instance ordArbNESeq :: (Ord a) => Ord (ArbNESeq a) where compare = compare `on` unArbNESeq instance functorArbNESeq :: Functor ArbNESeq where map f = ArbNESeq <<< map f <<< unArbNESeq instance applyArbNESeq :: Apply ArbNESeq where apply fs xs = ArbNESeq (apply (unArbNESeq fs) (unArbNESeq xs)) instance applicativeArbNESeq :: Applicative ArbNESeq where pure = ArbNESeq <<< pure instance bindArbNESeq :: Bind ArbNESeq where bind xs f = ArbNESeq (bind (unArbNESeq xs) (unArbNESeq <<< f)) instance monadArbNESeq :: Monad ArbNESeq instance showArbNESeq :: (Show a) => Show (ArbNESeq a) where show = show <<< unArbNESeq instance semigroupArbNESeq :: Semigroup (ArbNESeq a) where append (ArbNESeq xs) (ArbNESeq ys) = ArbNESeq (xs <> ys) instance altArbNESeq :: Alt ArbNESeq where alt (ArbNESeq xs) (ArbNESeq ys) = ArbNESeq (xs <|> ys) instance arbitraryArbNESeq :: (Arbitrary a) => Arbitrary (ArbNESeq a) where arbitrary = ArbNESeq <$> (NES.Seq <$> arbitrary <*> (unArbSeq <$> arbitrary)) -------------------------- -- Data.Sequence.Ordered newtype ArbOSeq a = ArbOSeq (OS.OrdSeq a) unArbOSeq :: forall b. ArbOSeq b -> OS.OrdSeq b unArbOSeq (ArbOSeq xs) = xs instance eqArbOSeq :: (Eq a) => Eq (ArbOSeq a) where eq = eq `on` unArbOSeq instance showArbOSeq :: (Show a) => Show (ArbOSeq a) where show = show <<< unArbOSeq instance semigroupArbOrdSeq :: (Ord a) => Semigroup (ArbOSeq a) where append (ArbOSeq xs) (ArbOSeq ys) = ArbOSeq (xs <> ys) instance monoidArbOrdSeq :: (Ord a) => Monoid (ArbOSeq a) where mempty = ArbOSeq mempty instance arbitraryArbOrdSeq :: (Ord a, Arbitrary a) => Arbitrary (ArbOSeq a) where arbitrary = (ArbOSeq <<< OS.fromFoldable) <$> (arbitrary :: Gen (Array a)) -------------------------- foldableSize :: forall f a. Foldable f => f a -> Int foldableSize = un Additive <<< foldMap (const (Additive 1)) check1 :: forall e p. (Testable p) => p -> QC e Unit check1 = quickCheck' 1 abs :: Int -> Int abs x = if x < 0 then (-x) else x integerBetween :: Int -> Int -> Int -> Int integerBetween lo hi x = (abs x `mod` hi - lo) + lo sorted :: forall a. Show a => Ord a => Array a -> Result sorted xs = xs == A.sort xs <?> show xs <> " is not sorted." sortedRev :: forall a. Show a => Ord a => Array a -> Result sortedRev xs = xs == A.reverse (A.sort xs) <?> show xs <> " is not sorted in reverse order." ------------- -- Min/Max -- TODO: Remove this (once 0.7.0 is released) newtype Min a = Min a runMin :: forall a. Min a -> a runMin (Min a) = a instance eqMin :: (Eq a) => Eq (Min a) where eq (Min a) (Min b) = a == b instance ordMin :: (Ord a) => Ord (Min a) where compare (Min a) (Min b) = compare a b instance semigroupMin :: (Ord a) => Semigroup (Min a) where append a b = case compare a b of LT -> a EQ -> a GT -> b -- Non-standard appending of `Semigroup a => Maybe a` where `Just x` takes -- takes priority over `Nothing`. See -- https://www.reddit.com/r/haskell/comments/39tumu/make_semigroup_a_superclass_of_monoid/cs6hlca -- (referenced by Phil Freeman in https://github.com/purescript/purescript-maybe/pull/11) -- for the reasoning why the PureScript standard differs from that of Haskell maybeAppend' :: forall a. Semigroup a => Maybe a -> Maybe a -> Maybe a maybeAppend' Nothing y = y maybeAppend' x Nothing = x maybeAppend' x y = append <$> x <*> y foldableMinimum :: forall f a. Ord a => Foldable f => f a -> Maybe a foldableMinimum = map runMin <<< foldr (maybeAppend' <<< Just <<< Min) Nothing newtype Max a = Max a runMax :: forall a. Max a -> a runMax (Max a) = a instance eqMax :: (Eq a) => Eq (Max a) where eq (Max a) (Max b) = a == b instance ordMax :: (Ord a) => Ord (Max a) where compare (Max a) (Max b) = compare a b instance semigroupMax :: (Ord a) => Semigroup (Max a) where append a b = case compare a b of LT -> b EQ -> a GT -> a foldableMaximum :: forall f a. Ord a => Foldable f => f a -> Maybe a foldableMaximum = map runMax <<< foldr (maybeAppend' <<< Just <<< Max) Nothing ------------------------------------------------------------------------------- err :: Array String -> String err messages = "Did not hold for: " <> intercalate ", " messages
29,428
https://github.com/Cheng-Yi-Lin/Software2/blob/master/catkin_ws/src/pmcn/bot_arm/src/tsp_salesman_nagivation_node.py
Github Open Source
Open Source
CC-BY-2.0
null
Software2
Cheng-Yi-Lin
Python
Code
360
3,113
#!/usr/bin/env python import rospy import socket import pygame from duckietown_msgs.msg import Twist2DStamped, BoolStamped, StopLineReading from std_msgs.msg import String, Int32, Int16 from Adafruit_PWM_Servo_Driver import PWM from Adafruit_MotorHAT import Adafruit_MotorHAT import time import urllib2 from __builtin__ import True class Qwer_Player(object): def __init__(self): self.node_name = rospy.get_name() rospy.loginfo("[%s] Initializing " %(self.node_name)) self.pub_e_stop = rospy.Publisher("wheels_driver_node/emergency_stop",BoolStamped,queue_size=1) self.pub_lanefollowing=rospy.Publisher("joy_mapper_node/joystick_override",BoolStamped,queue_size=1) self.pub_joy_override = rospy.Publisher("joy_mapper_node/joystick_override", BoolStamped, queue_size=1) self.pub_voice = rospy.Publisher("~Voice", String, queue_size=1) self.sub_voice = rospy.Subscriber("~Voice", String, self.cb_SoundPlayer, queue_size=1) self.sub_tag_id = rospy.Subscriber("tag_detections_test", Int32, self.get_Apriltag, queue_size=1) self.pub_switch = rospy.Publisher("joy_mapper_node/switchSpeed", BoolStamped, queue_size=1) #set global variable #self.pub_CommodityInfo=rospy.Publisher("commodity_info",String, queue_size=1) self.sub_commodity = rospy.Subscriber("~commodity_info", String, self.salesman, queue_size=1) self.pub_at_stop_line = rospy.Publisher("stop_line_filter_node/at_stop_line",BoolStamped,queue_size=1) self.type_back=rospy.Publisher("open_loop_intersection_control_node/turn_type", Int16, queue_size=1) self.pub_stop_line_reading = rospy.Publisher("stop_line_filter_node/stop_line_reading", StopLineReading, queue_size=1) self.pub_at_stop_back = rospy.Publisher("~at_stop_back",BoolStamped,queue_size=1) self.flag = 0 self.sound = '' self.n_stop = False self.path_commodity=list() self.path_commodity.append(0) self.car_action_check=1 self.back_info=0 self.last_commodity_tag=0 self.car_read_action() self.last_action="" #self.path_commodity=None def car_read_action(self): while True: strhttp='http://192.168.0.100/tsp/read_car_action.php?car_id=1' req = urllib2.Request(strhttp) response = urllib2.urlopen(req) the_page = response.read() #self.car_action_check=int(the_page) """ if(self.car_action_check!=int(the_page)): self.car_action_check=int(the_page) e_stop_msg=BoolStamped() e_stop_msg.data=int(the_page) self.pub_lanefollowing.publish(e_stop_msg) """ #print("yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy") #print(self.last_commodity_tag) if(self.car_action_check==1 and int(the_page)==0 and self.last_commodity_tag!=0): self.car_action_check=int(the_page) e_stop_msg=BoolStamped() e_stop_msg.data=int(the_page) self.pub_lanefollowing.publish(e_stop_msg) print("lllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllll") #print(self.last_commodity_tag) #strhttp='http://192.168.0.100/tsp/car_recode_navigation.php?car_id=1&tag_id='+str(self.last_commodity_tag) #req = urllib2.Request(strhttp) #response = urllib2.urlopen(req) #the_page_1 = response.read() #print(the_page_1) print(self.last_action) #print("Sssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss") if self.last_action=="B": stop_line_reading_msg = StopLineReading() stop_line_reading_msg.stop_line_detected = True stop_line_reading_msg.at_stop_line = 1 self.pub_stop_line_reading.publish(stop_line_reading_msg) print("ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo") stop_msg=BoolStamped() stop_msg.data=True self.pub_at_stop_back.publish(stop_msg) time.sleep(5) #print("ttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt") self.turn=3 self.type_back.publish(self.turn) self.last_commodity_tag=0 if(self.car_action_check!=int(the_page)): #if(True): self.car_action_check=int(the_page) e_stop_msg=BoolStamped() e_stop_msg.data=int(the_page) self.pub_lanefollowing.publish(e_stop_msg) #print("EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEee") def salesman(self,Commodity): #print("1111111111111111111111QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ") #print(Commodity) #print(Commodity.data) #print(Commodity.data[0]) #print(Commodity.data[1]) if(len(Commodity.data)): self.path_commodity=Commodity.data.split(" ") #print(self.path_commodity[0]) #print(self.path_commodity[1]) def get_Apriltag(self,Tag): i=0 while(self.path_commodity[i]): #print self.path_commodity[i] i+=1 tag_id = Int32() tag_id.data = Tag.data commodity_exist=0 #print("wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww") rospy.loginfo("Now found Id = %d------------- and flag = %d" %(tag_id.data, self.flag)) i=0 tag_node=int(tag_id.data/4) while(len(self.path_commodity)>i+1): #print(len(self.path_commodity[i])) #print(self.path_commodity[i]) sss=self.path_commodity[i] #print("wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww") #print(self.path_commodity[i]) #print("wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww") if(int(sss)==tag_node): commodity_exist=1 self.path_commodity[i]=-1 break i=i+1 print(commodity_exist) #print("YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY") if commodity_exist==1: #print("qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq") strhttp='http://192.168.0.100/tsp/car_record_action.php?car_id=1&car_action=1' req = urllib2.Request(strhttp) response = urllib2.urlopen(req) the_page = response.read() strhttp='http://192.168.0.100/tsp/car_recode_navigation.php?car_id=1&tag_id='+str(tag_id.data) #strhttp='http://192.168.0.100/tsp/car_recode_navigation.php?car_id=1&tag_id='+str(taginfo.id) req = urllib2.Request(strhttp) response = urllib2.urlopen(req) the_page = response.read() self.last_action=the_page[0] self.last_commodity_tag=tag_id.data #print(self.last_commodity_tag) self.sound="/home/ubuntu/duckietown/catkin_ws/src/summer_school/qwer_nutn/socket_qwer/include/socket_qwer/1234.mp3" rospy.loginfo(' ---------Found Tag playing guide vocie-----------') #e_stop_msg = BoolStamped() #e_stop_msg.data = True #self.pub_e_stop.publish(e_stop_msg) msg = String() msg.data = 'at def get_apriltag(self,Tag) and tag_id.data = 350' self.pub_voice.publish(msg) if tag_id.data == 0: self.flag = 0 else: self.flag = 1 def cb_SoundPlayer(self,nowstr): pygame.mixer.init() rospy.loginfo("Welcome to SoundPlayer ^_^") pygame.mixer.music.load(self.sound) pygame.mixer.music.play(0,1) pygame.mixer.music.fadeout(5000) pygame.mixer.music.set_volume(1) #The value argument is between 0.0 and 1.0 #pygame.mixer.music.set_endevent(self.set_event_fun) time.sleep(5) print("music end") # while pygame.mixer.music.get_busy(): #it will play sound until the sound finished # pygame.time.Clock().tick(10) if __name__ == "__main__": rospy.init_node("tsp_salesman_nagivation_node",anonymous=False) qwer_player = Qwer_Player() rospy.spin()
34,005
https://github.com/mandyzore/fuzzysearch/blob/master/src/fuzzysearch/_substitutions_only_lp_template.h
Github Open Source
Open Source
MIT
2,017
fuzzysearch
mandyzore
C
Code
202
726
#define DO_FREES free(sub_counts) static PyObject * FUNCTION_NAME(PyObject *self, PyObject *args) { /* input params */ const char *subsequence; const char *sequence; int subseq_len, seq_len, max_substitutions; unsigned int *sub_counts; unsigned int seq_idx, subseq_idx, count_idx; DECLARE_VARS; if (!PyArg_ParseTuple( args, #ifdef IS_PY3K "y#y#i", #else #if PY_HEX_VERSION >= 0x02070000 "t#t#i", #else "s#s#i", #endif #endif &subsequence, &subseq_len, &sequence, &seq_len, &max_substitutions )) { return NULL; } /* this is required because simple_memmem_with_needle_sum() returns the haystack if the needle is empty */ if (subseq_len == 0) { PyErr_SetString(PyExc_ValueError, "subsequence must not be empty"); return NULL; } sub_counts = (unsigned int *) malloc (sizeof(unsigned int) * subseq_len); if (sub_counts == NULL) { return PyErr_NoMemory(); } PREPARE; if (seq_len < subseq_len) { DO_FREES; RETURN_AT_END; } for (seq_idx = 0; seq_idx < subseq_len - 1; ++seq_idx) { sub_counts[seq_idx] = 0; for (subseq_idx = 0; subseq_idx <= seq_idx; ++subseq_idx) { sub_counts[seq_idx - subseq_idx] += subsequence[subseq_idx] != sequence[seq_idx]; } } sub_counts[seq_idx] = 0; for (seq_idx = subseq_len-1; seq_idx < seq_len;) { for (subseq_idx = 0; subseq_idx < subseq_len; ++subseq_idx) { sub_counts[(seq_idx - subseq_idx) % subseq_len] += subsequence[subseq_idx] != sequence[seq_idx]; } ++seq_idx; count_idx = seq_idx % subseq_len; if (sub_counts[count_idx] <= max_substitutions) { OUTPUT_VALUE(seq_idx - subseq_len); } sub_counts[count_idx] = 0; } DO_FREES; RETURN_AT_END; } #undef DO_FREES
40,012
https://github.com/KickSeason/neon-js/blob/master/src/transactions/typings/Transaction.d.ts
Github Open Source
Open Source
MIT
2,018
neon-js
KickSeason
TypeScript
Code
305
576
import { Account, Balance, Claims } from '../../wallet'; import { TransactionInput, TransactionAttribute, TransactionOutput, Witness, } from './components'; /** * Transactions are what you use to interact with the blockchain. * A transaction is made up of components found in the component file. * Besides those components which are found in every transaction, there are also special data that is unique to each transaction type. These 'exclusive' data can be found in the exclusive file. * This class is a wrapper around the various transaction building methods found in this folder. */ export class Transaction { public type: number public version: number public attributes: TransactionAttribute[] public inputs: TransactionInput[] public outputs: TransactionOutput[] public scripts: Witness[] constructor(tx?: Transaction) /** Exclusive Data */ exclusiveData(): object /** Transaction hash. */ hash(): string /** Creates a ClaimTransaction with the given parameters. */ static createClaimTx(publicKeyOrAddress: string, claimData: Claims, override: object): Transaction /** Creates a ContractTransaction with the given parameters. */ static createContractTx(balances: Balance, intents: TransactionOutput[], override: object): Transaction /** Creates an InvocationTransaction with the given parameters. */ static createInvocationTx(balance: Balance, intents: TransactionOutput[], invoke: object | string, gasCost: number, override: object): Transaction static deserialize(hexstring: string): Transaction /** Adds a TransactionOutput. TransactionOutput can be given as a TransactionOutput object or as human-friendly values. This is detected by the number of arguments provided. */ addOutput (assetSymOrTxOut: string|object, value: number, address: string): Transaction /** Add an attribute. */ addAttribute (usage: number, data: string): Transaction /** Add a remark. */ addRemark (remark: string): Transaction /** Calculate the inputs required based on existing outputs provided. Also takes into account the fees required through the gas property. */ calculate (balance: Balance): Transaction /** Serialize the transaction and return it as a hexstring. */ serialize (signed?: boolean): string /** Serializes the exclusive data in this transaction */ serializeExclusiveData (): string /** Signs a transaction. */ sign (signer: Account|string): Transaction }
2,086
https://github.com/i-gaven/Just_a_dumper/blob/master/all_headers/百度地图-出行导航必备的智能路线规划软件-10.6.5(越狱应用)_headers/BNUGCCommentRefreshController.h
Github Open Source
Open Source
MIT
2,018
Just_a_dumper
i-gaven
Objective-C
Code
156
593
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard. // #import <Foundation/NSObject.h> @class BasePage, NSNumber, NSString, NSTimer; @interface BNUGCCommentRefreshController : NSObject { NSTimer *_timer; _Bool _delayInvokeBlock; _Bool _isRunning; int _newItemCount; double _interval; NSString *_cuid; NSString *_signKey; NSNumber *_eventId; NSNumber *_detailId; NSNumber *_clientLatestCommentId; CDUnknownBlockType _refreshBlock; BasePage *_lastTopPage; } @property(nonatomic) __weak BasePage *lastTopPage; // @synthesize lastTopPage=_lastTopPage; @property(copy, nonatomic) CDUnknownBlockType refreshBlock; // @synthesize refreshBlock=_refreshBlock; @property(nonatomic) int newItemCount; // @synthesize newItemCount=_newItemCount; @property(nonatomic) _Bool isRunning; // @synthesize isRunning=_isRunning; @property(retain, nonatomic) NSNumber *clientLatestCommentId; // @synthesize clientLatestCommentId=_clientLatestCommentId; @property(retain, nonatomic) NSNumber *detailId; // @synthesize detailId=_detailId; @property(retain, nonatomic) NSNumber *eventId; // @synthesize eventId=_eventId; @property(retain, nonatomic) NSString *signKey; // @synthesize signKey=_signKey; @property(retain, nonatomic) NSString *cuid; // @synthesize cuid=_cuid; @property(nonatomic) double interval; // @synthesize interval=_interval; @property(nonatomic) _Bool delayInvokeBlock; // @synthesize delayInvokeBlock=_delayInvokeBlock; - (void).cxx_destruct; - (void)parseResult:(id)arg1; - (void)requestNewCommentCountFromServer; - (_Bool)checkNeedStopTimer; - (void)stop; - (void)timerRefresh; - (void)start; - (id)initWithInterval:(double)arg1 Block:(CDUnknownBlockType)arg2; @end
39,910
https://github.com/UnixJunkie/ocamlnet/blob/master/code/tests/netclient/http_bench/specs/framed-basicauth-fails.sh
Github Open Source
Open Source
BSD-3-Clause
null
ocamlnet
UnixJunkie
Shell
Code
30
88
. helpers.sh start_test_server \ -line 1 -file data/require-basicauth \ -line 9 -file data/require-basicauth trap "stop_test_server" EXIT request \ -realm testrealm -user testuser -password testpassword -basic-auth \ -get / \ -run
27,086
https://github.com/jtlivingston/earthquake-eventpages/blob/master/src/htdocs/modules/scientific/ScientificModule.js
Github Open Source
Open Source
LicenseRef-scancode-public-domain-disclaimer, LicenseRef-scancode-unknown-license-reference
2,016
earthquake-eventpages
jtlivingston
JavaScript
Code
168
639
'use strict'; var EventModule = require('base/EventModule'), Util = require('util/Util'); var DEFAULTS = { title: 'Scientific', hash: 'scientific', cssUrl: 'modules/scientific/index.css', pages: [ /** * NOTE: pages that are bundled in the scientific module must be added * to the "browserify:scientific" target. */ { className: 'scientific/ScientificSummaryPage', dependencyBundle: 'modules/scientific/index.js', options: { title: '', hash: 'summary' }, productTypes: [ 'origin', 'phase-data', 'moment-tensor', 'focal-mechanism', 'finite-fault' ] }, { className: 'scientific/HypocenterPage', dependencyBundle: 'modules/scientific/index.js', options: { title: 'Origin', hash: 'origin' }, productTypes: [ 'origin', 'phase-data' ] }, { className: 'scientific/MomentTensorPage', dependencyBundle: 'modules/scientific/index.js', options: { title: 'Moment Tensor', hash: 'moment-tensor' }, productTypes: ['moment-tensor'] }, { className: 'scientific/FocalMechanismPage', dependencyBundle: 'modules/scientific/index.js', options: { title: 'Focal Mechanism', hash: 'focal-mechanism' }, productTypes: ['focal-mechanism'] }, { className: 'scientific/FiniteFaultPage', dependencyBundle: 'modules/scientific/index.js', options: { title: 'Finite Fault', hash: 'finite-fault' }, productTypes: ['finite-fault'] }, { className: 'scientific/IrisProductsPage', dependencyBundle: 'modules/scientific/index.js', options: { title: 'Waveforms', hash: 'waveforms' } } ] }; var ScientificModule = function (options) { options = Util.extend({}, DEFAULTS, options || {}); this._event = options.event; EventModule.call(this, options); }; ScientificModule.prototype = Object.create(EventModule.prototype); module.exports = ScientificModule;
6,005
https://github.com/JIAmengxuan/bwbble/blob/master/mg-ref/sample_usage.sh
Github Open Source
Open Source
MIT
null
bwbble
JIAmengxuan
Shell
Code
144
644
#!/bin/bash ####################################### ## compile mg-ref ####################################### make clean; make ####################################### ## clean up the output directory ####################################### if [ -d "mg-ref-output" ]; then echo "directory mg-ref-output found" rm mg-ref-output/SNP.extract.chr*.data rm mg-ref-output/INDEL.extract.chr*.data else echo "create directory mg-ref-output" mkdir mg-ref-output fi ####################################### ## download and extract variants from vcf files ####################################### for chr in chr1 chr2 chr3 chr4 chr5 chr6 chr7 chr8 chr9 chr10 chr11 chr12 chr13 chr14 chr15 chr16 chr17 chr18 chr19 chr20 chr21 chr22 chrX do echo "start download $chr" wget ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/release/20110521/ALL.$chr.phase1_release_v3.20101123.snps_indels_svs.genotypes.vcf.gz echo "start unzip $chr" gunzip ALL.$chr.phase1_release_v3.20101123.snps_indels_svs.genotypes.vcf.gz echo "start extract $chr" ./data_prep ALL.$chr.phase1_release_v3.20101123.snps_indels_svs.genotypes.vcf echo "remove $chr" rm ALL.$chr.phase1_release_v3.20101123.snps_indels_svs.genotypes.vcf done ####################################### ## download GRCh37 if not exist ####################################### if [ -f "human_g1k_v37.fasta" ] then echo "file human_g1k_v37.fasta found" else wget ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/human_g1k_v37.fasta.gz gunzip human_g1k_v37.fasta.gz fi ####################################### ## create reference multi-genome: ## reference_w_snp_and_bubble.fasta in this sample ####################################### echo "start comb" output_dir=mg-ref-output ./comb human_g1k_v37.fasta $output_dir/reference_w_snp.fasta $output_dir/reference_w_snp_and_bubble.fasta $output_dir/meta.data
30,803
https://github.com/cwkuehl/csbp/blob/master/CSBP/Services/Repositories/MaMandantRep.cs
Github Open Source
Open Source
MIT
null
csbp
cwkuehl
C#
Code
117
360
// <copyright file="MaMandantRep.cs" company="cwkuehl.de"> // Copyright (c) cwkuehl.de. All rights reserved. // </copyright> namespace CSBP.Services.Repositories { using System.Collections.Generic; using CSBP.Apis.Services; using Microsoft.EntityFrameworkCore; /// <summary> /// Klasse für MA_Mandant-Repository. /// </summary> public partial class MaMandantRep { /// <summary> /// Executes a SQL command. /// </summary> /// <param name="daten">Service data for database access.</param> /// <param name="sql">SQL command.</param> public void Execute(ServiceDaten daten, string sql) { var db = GetDb(daten); db.Database.ExecuteSqlRaw(sql); } /// <summary> /// Executes many SQL command. /// </summary> /// <param name="daten">Service data for database access.</param> /// <param name="sql">List of SQL commands.</param> public void Execute(ServiceDaten daten, List<string> sql) { if (sql == null) return; var db = GetDb(daten); foreach (var s in sql) { db.Database.ExecuteSqlRaw(s); } } } }
9,354
https://github.com/kaboudian/InterviewSeminarAtFDA/blob/master/programs/defib/fhn-electrodes/defib_s3.frag
Github Open Source
Open Source
MIT
null
InterviewSeminarAtFDA
kaboudian
GLSL
Code
153
374
#version 300 es precision highp float ; precision highp int ; in vec2 cc ; uniform sampler2D icolor ; uniform sampler2D activeElectrodes ; uniform sampler2D electrodeCoordinates ; uniform float electrodeSize ; layout (location = 0 ) out vec4 ocolor ; #define paces(l) (texture( activeElectrodes, l).r>.5 && \ length(cc-(l))<electrodeSize ) void main(){ vec4 color = texture( icolor, cc ) ; vec2 crd = texture( electrodeCoordinates, cc ).xy ; float dx = (cc.x - crd.x )>0. ? 1. : -1. ; float dy = (cc.y - crd.y )>0. ? 1. : -1. ; vec2 size = vec2(textureSize(electrodeCoordinates,0).xy) ; vec2 ii = vec2(dx,0.)/size ; vec2 jj = vec2(0.,dy)/size ; if ( paces( crd+ii ) ) color.r = 1. ; if ( paces( crd+jj ) ) color.r = 1. ; if ( paces( crd+ii+jj ) ) color.r = 1. ; if ( paces( crd ) ) color.r = 1. ; ocolor = vec4(color) ; return ; }
41,407
https://github.com/jogonzal/UwMachineLearningHw4/blob/master/Problem4SVM/Statistics/Transformer.cs
Github Open Source
Open Source
BSD-3-Clause
2,017
UwMachineLearningHw4
jogonzal
C#
Code
33
98
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Problem1BiasAndVariance.Statistics { public static class Transformer { public static double BoolToDouble(bool input) { return input ? 1.0 : 0.0; } } }
50,204
https://github.com/StrahinjaJacimovic/mikrosdk_click_v2/blob/master/clicks/speaker/lib/include/speaker.h
Github Open Source
Open Source
MIT
2,022
mikrosdk_click_v2
StrahinjaJacimovic
C
Code
963
1,753
/**************************************************************************** ** Copyright (C) 2020 MikroElektronika d.o.o. ** Contact: https://www.mikroe.com/contact ** ** 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. ****************************************************************************/ /*! * @file speaker.h * @brief This file contains API for Speaker Click Driver. */ #ifndef SPEAKER_H #define SPEAKER_H #ifdef __cplusplus extern "C"{ #endif #include "drv_digital_out.h" /*! * @addtogroup speaker Speaker Click Driver * @brief API for configuring and manipulating Speaker Click driver. * @{ */ /** * @defgroup speaker_map Speaker MikroBUS Map * @brief MikroBUS pin mapping of Speaker Click driver. */ /** * @addtogroup speaker_map * @{ */ /** * @brief MikroBUS pin mapping. * @details Mapping pins of Speaker Click to the selected MikroBUS. */ #define SPEAKER_MAP_MIKROBUS( cfg, mikrobus ) \ cfg.pwr = MIKROBUS( mikrobus, MIKROBUS_INT ); \ cfg.sb = MIKROBUS( mikrobus, MIKROBUS_PWM ) /*! @} */ // speaker_map /*! @} */ // speaker /** * @brief Speaker Click context object. * @details Context object definition of Speaker Click driver. */ typedef struct { digital_out_t pwr; /**< Shutdown Mode pin. */ digital_out_t sb; /**< BTL/SE Control pin. */ } speaker_t; /** * @brief Speaker Click configuration object. * @details Configuration object definition of Speaker Click driver. */ typedef struct { pin_name_t pwr; /**< Shutdown Mode pin. */ pin_name_t sb; /**< BTL/SE Control pin. */ } speaker_cfg_t; /** * @brief Speaker Click return value data. * @details Predefined enum values for driver return values. */ typedef enum { SPEAKER_OK = 0, SPEAKER_ERROR = -1 } speaker_return_value_t; /*! * @addtogroup speaker Speaker Click Driver * @brief API for configuring and manipulating Speaker Click driver. * @{ */ /** * @brief Speaker configuration object setup function. * @details This function initializes click configuration structure to initial * values. * @param[out] cfg : Click configuration structure. * See #speaker_cfg_t object definition for detailed explanation. * @return Nothing. * @note The all used pins will be set to unconnected state. */ void speaker_cfg_setup ( speaker_cfg_t *cfg ); /** * @brief Speaker initialization function. * @details This function initializes all necessary pins and peripherals used * for this click board. * @param[out] ctx : Click context object. * See #speaker_t object definition for detailed explanation. * @param[in] cfg : Click configuration structure. * See #speaker_cfg_t object definition for detailed explanation. * @return @li @c 0 - Success, * @li @c -1 - Error. * * See #err_t definition for detailed explanation. * @note None. */ err_t speaker_init ( speaker_t *ctx, speaker_cfg_t *cfg ); /** * @brief Speaker default configuration function. * @details This function executes a default configuration of Speaker * click board. * @param[in] ctx : Click context object. * See #speaker_t object definition for detailed explanation. * @return @li @c 0 - Success, * @li @c -1 - Error. * * See #err_t definition for detailed explanation. * @note This function can consist any necessary configuration or setting to put * device into operating mode. */ err_t speaker_default_cfg ( speaker_t *ctx ); /** * @brief Speaker enables the slave amplifier function. * @details This function enables the slave amplifier by * clears the SB ( INT ) pin on the low level * of the Speaker click board™. * @param[in] ctx : Click context object. * See #speaker_t object definition for detailed explanation. * @return @li @c 0 - Success, * @li @c -1 - Error. * * @note None. */ err_t speaker_enable_slave_amp ( speaker_t *ctx ); /** * @brief Speaker disables the slave amplifier function. * @details This function disables the slave amplifier by * sets the SB ( INT ) pin on the high level * of the Speaker click board™. * @param[in] ctx : Click context object. * See #speaker_t object definition for detailed explanation. * @return @li @c 0 - Success, * @li @c -1 - Error. * * @note None. */ err_t speaker_disable_slave_amp ( speaker_t *ctx ); /** * @brief Speaker shutdown mode function. * @details This function enables the shutdown mode by * clears the PWR ( PWM ) pin on the low level * of the Speaker click board™. * @param[in] ctx : Click context object. * See #speaker_t object definition for detailed explanation. * @return @li @c 0 - Success, * @li @c -1 - Error. * * @note None. */ err_t speaker_shutdown ( speaker_t *ctx ); /** * @brief Speaker normal operation mode function. * @details This function enables the shutdown mode by * sets the PWR ( PWM ) pin on the high level * of the Speaker click board™. * @param[in] ctx : Click context object. * See #speaker_t object definition for detailed explanation. * @return @li @c 0 - Success, * @li @c -1 - Error. * * @note None. */ err_t speaker_normal_operation ( speaker_t *ctx ); #ifdef __cplusplus } #endif #endif // SPEAKER_H /*! @} */ // speaker // ------------------------------------------------------------------------ END
44,088
https://github.com/saluk/keyteki/blob/master/server/game/cards/01-Core/DeipnoSpymaster.js
Github Open Source
Open Source
AGPL-3.0-only
2,020
keyteki
saluk
JavaScript
Code
51
169
const Card = require('../../Card.js'); class DeipnoSpymaster extends Card { setupCardAbilities(ability) { this.omni({ target: { cardType: 'creature', controller: 'self', gameAction: ability.actions.forRemainderOfTurn((context) => ({ effect: ability.effects.canUse((card) => card === context.target) })) }, effect: 'allow {0} to be used for the remainder of the turn' }); } } DeipnoSpymaster.id = 'deipno-spymaster'; module.exports = DeipnoSpymaster;
28,193
https://github.com/NunoEdgarGFlowHub/open-data-certificate/blob/master/db/migrate/20130613221052_add_api_id_to_response_cache_map.rb
Github Open Source
Open Source
MIT
2,021
open-data-certificate
NunoEdgarGFlowHub
Ruby
Code
12
44
class AddApiIdToResponseCacheMap < ActiveRecord::Migration def change add_column :response_cache_maps, :api_id, :string end end
32,202
https://github.com/aliyun/alibabacloud-ecs-easy-sdk/blob/master/incubator-plugins/preemptive-instance-recommendation/src/main/java/com/aliyun/ecs/easysdk/preemptiveinstance/impl/PreemptiveInstanceBaseServiceCachedImpl.java
Github Open Source
Open Source
Apache-2.0
2,021
alibabacloud-ecs-easy-sdk
aliyun
Java
Code
494
2,223
/* * Copyright (c) 2021-present, Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.aliyun.ecs.easysdk.preemptiveinstance.impl; import java.util.List; import com.alibaba.fastjson.JSON; import com.aliyun.ecs.easysdk.biz.model.Response; import com.aliyun.ecs.easysdk.container.annotation.Autowired; import com.aliyun.ecs.easysdk.container.annotation.BeanProperty; import com.aliyun.ecs.easysdk.container.annotation.Qualifier; import com.aliyun.ecs.easysdk.preemptiveinstance.CacheService; import com.aliyun.ecs.easysdk.preemptiveinstance.PreemptiveInstanceBaseService; import com.aliyun.ecs.easysdk.preemptiveinstance.model.EcsInstanceType; import com.aliyun.ecs.easysdk.preemptiveinstance.model.PreemptiveInstanceRecommendation; import com.aliyun.ecs.easysdk.preemptiveinstance.model.PreemptiveInstanceRecommendationRequest; import com.aliyun.ecs.easysdk.preemptiveinstance.model.SpotPrice; import com.aliyuncs.ecs.model.v20140526.DescribeAvailableResourceResponse.AvailableZone; import com.aliyuncs.ecs.model.v20140526.DescribeInstanceTypeFamiliesResponse.InstanceTypeFamily; import com.aliyuncs.ecs.model.v20140526.DescribeRegionsResponse; import com.aliyuncs.ecs.model.v20140526.DescribeZonesResponse.Zone; import com.google.common.collect.Lists; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; public class PreemptiveInstanceBaseServiceCachedImpl implements PreemptiveInstanceBaseService { @Autowired @Qualifier(filters = {@BeanProperty(key = "cached", value = "false")}) private PreemptiveInstanceBaseService preemptiveInstanceBaseService; @Autowired private CacheService cacheService; public void init() { } @Override public Response<List<AvailableZone>> describeAvailableResource(String regionId, Integer cores, Integer memory, String instanceType) { return preemptiveInstanceBaseService.describeAvailableResource(regionId, cores, memory, instanceType); } @Override public Response<SpotPrice> describeLatestSpotPrice(String regionId, String zoneId, String instanceType) { String value = cacheService.get(Lists.newArrayList("describeLatestSpotPrice", regionId, zoneId, instanceType)); if (StringUtils.isNotBlank(value)) { SpotPrice spotPrice = JSON.parseObject(value, SpotPrice.class); return new Response(spotPrice); } Response<List<SpotPrice>> listResponse = describeSpotPriceHistory(regionId, null, instanceType, 3); if (!listResponse.getSuccess() || CollectionUtils.isEmpty(listResponse.getData())) { return preemptiveInstanceBaseService.describeLatestSpotPrice(regionId, zoneId, instanceType); } List<SpotPrice> latestPrice = listResponse.getData(); SpotPrice suitablePrice = null; for (SpotPrice spotPrice : latestPrice) { if (spotPrice.getZoneId().equals(zoneId)) { suitablePrice = spotPrice; } cacheService.put(Lists.newArrayList("describeLatestSpotPrice", regionId, spotPrice.getZoneId(), instanceType), JSON.toJSONString(spotPrice)); } cacheService.put(Lists.newArrayList("describeLatestSpotPrice", regionId, zoneId, instanceType), JSON.toJSONString(suitablePrice)); return new Response<>(suitablePrice); } @Override public Response<List<SpotPrice>> describeSpotPriceHistory(String regionId, String zoneId, String instanceType, int hours) { String value = cacheService.get(Lists.newArrayList("describeSpotPriceHistory", regionId, zoneId, instanceType, String.valueOf(hours))); if (StringUtils.isNotBlank(value)) { List<SpotPrice> spotPrices = JSON.parseArray(value, SpotPrice.class); return new Response(spotPrices); } Response<List<SpotPrice>> listResponse = preemptiveInstanceBaseService.describeSpotPriceHistory(regionId, zoneId, instanceType, hours); if (listResponse.getSuccess() && CollectionUtils.isNotEmpty(listResponse.getData())) { for (SpotPrice spotPrice : listResponse.getData()) { cacheService.put(Lists.newArrayList("describeLatestSpotPrice", regionId, spotPrice.getZoneId(), instanceType, String.valueOf(hours)), JSON.toJSONString(spotPrice)); } cacheService.put(Lists.newArrayList("describeSpotPriceHistory", regionId, zoneId, instanceType, String.valueOf(hours)), JSON.toJSONString(listResponse.getData())); } else { cacheService.put(Lists.newArrayList("describeSpotPriceHistory", regionId, zoneId, instanceType, String.valueOf(hours)), JSON.toJSONString(Lists.newArrayList())); } return listResponse; } @Override public Response<EcsInstanceType> describeInstanceType(String instanceType) { String value = cacheService.get(Lists.newArrayList("describeInstanceType", instanceType)); if (StringUtils.isNotBlank(value)) { EcsInstanceType ecsInstanceType = JSON.parseObject(value, EcsInstanceType.class); return new Response(ecsInstanceType); } Response<EcsInstanceType> ecsInstanceTypeResponse = preemptiveInstanceBaseService.describeInstanceType( instanceType); if (ecsInstanceTypeResponse.getSuccess() && null != ecsInstanceTypeResponse.getData()) { cacheService.put(Lists.newArrayList("describeInstanceType", instanceType), JSON.toJSONString(ecsInstanceTypeResponse.getData())); } else { cacheService.put(Lists.newArrayList("describeInstanceType", instanceType), JSON.toJSONString(null)); } return ecsInstanceTypeResponse; } @Override public Response<List<EcsInstanceType>> describeInstanceTypes(String instanceFamily, String region) { String value = cacheService.get(Lists.newArrayList("describeInstanceTypes", instanceFamily, region)); if (StringUtils.isNotBlank(value)) { List<EcsInstanceType> spotPrices = JSON.parseArray(value, EcsInstanceType.class); return new Response(spotPrices); } Response<List<EcsInstanceType>> listResponse = preemptiveInstanceBaseService.describeInstanceTypes( instanceFamily, region); if (listResponse.getSuccess() && CollectionUtils.isNotEmpty(listResponse.getData())) { cacheService.put(Lists.newArrayList("describeInstanceTypes", instanceFamily, region), JSON.toJSONString(listResponse.getData())); } else { cacheService.put(Lists.newArrayList("describeInstanceTypes", instanceFamily, region), JSON.toJSONString(null)); } return listResponse; } @Override public Response<List<InstanceTypeFamily>> describeInstanceTypeFamily() { return preemptiveInstanceBaseService.describeInstanceTypeFamily(); } @Override public Response<String> getInstanceFamily(String instanceType) { return preemptiveInstanceBaseService.getInstanceFamily(instanceType); } @Override public Response<List<Zone>> describeZones(String regionId) { return preemptiveInstanceBaseService.describeZones(regionId); } @Override public Response<List<PreemptiveInstanceRecommendation>> describeRecommendInstanceType(String region, String zone, PreemptiveInstanceRecommendationRequest productCategory) { return preemptiveInstanceBaseService.describeRecommendInstanceType(region, zone, productCategory); } @Override public Response<List<DescribeRegionsResponse.Region>> describeAllRegions() { return preemptiveInstanceBaseService.describeAllRegions(); } }
32,765
https://github.com/daima3629/werewolf/blob/master/cogs/status.py
Github Open Source
Open Source
MIT
null
werewolf
daima3629
Python
Code
130
665
from discord.ext import commands # ゲーム開始前:nothing # 参加者募集中:waiting # ゲーム中:playing class GameStatus(commands.Cog): def __init__(self, bot): self.bot = bot async def cog_check(self, ctx): if ctx.guild is None: await ctx.send('サーバー内でのみ実行できるコマンドです') return False if not ctx.author.guild_permissions.administrator: await ctx.send('コマンドを実行する権限がありません') return False return True @commands.command() async def create(self, ctx): if self.bot.game_status == 'playing': await ctx.send('ゲーム中です') return if self.bot.game_status == 'waiting': await ctx.send('既に参加者募集中です') return self.bot.game_status = 'waiting' await ctx.send('参加者の募集を開始しました') # ゲームを開始するコマンド # 編成テンプレート(urils.roles)から役職を割り振る(Player.roleに役職名をセット) # ステータスを変更する # ゲーム開始メッセージを送信 @commands.command() async def start(self, ctx): pass @commands.command() async def set_nothing(self, ctx): self.bot.game_status = 'nothing' await ctx.send(f'game_status を {self.bot.game_status} に変更しました') @commands.command() async def set_playing(self, ctx): self.bot.game_status = 'playing' await ctx.send(f'game_status を {self.bot.game_status} に変更しました') @commands.command() async def set_waiting(self, ctx): self.bot.game_status = 'waiting' await ctx.send(f'game_status を {self.bot.game_status} に変更しました') @commands.command() async def game_status(self, ctx): await ctx.send(f'現在の game_status は {self.bot.game_status} です') def setup(bot): bot.add_cog(GameStatus(bot))
48,192