text
stringlengths
1
1.05M
#!/bin/bash (set -o igncr) 2>/dev/null && set -o igncr; # this comment is required # The above line ensures that the script can be run on Cygwin/Linux even with Windows CRNL # # Run 'mkdocs serve' on port 8000 (default) # Make sure the MkDocs version is consistent with the documentation content # - require that at least version 1.0 is used because of use_directory_urls = True default # - must use "file.md" in internal links whereas previously "file" would work # - it is not totally clear whether version 1 is needed but try this out to see if it helps avoid broken links checkMkdocsVersion() { local mkdocsVersion mkdocsVersionFull requiredMajorVersion # Required MkDocs version is at least 1 requiredMajorVersion="1" # On Cygwin, mkdocs --version gives: mkdocs, version 1.0.4 from /usr/lib/python3.6/site-packages/mkdocs (Python 3.6) # On Debian Linux, similar to Cygwin: mkdocs, version 0.17.3 mkdocsVersionFull=$(${mkdocsExe} --version) echo "MkDocs --version: ${mkdocsVersionFull}" if [ -z "${mkdocsVersionFull}" ]; then echo "Unable to determine MkDocs version." exit 1 fi mkdocsVersion=$(echo ${mkdocsVersionFull} | cut -d ' ' -f 3) echo "MkDocs full version number: ${mkdocsVersion}" mkdocsMajorVersion=$(echo ${mkdocsVersion} | cut -d '.' -f 1) echo "MkDocs major version number: ${mkdocsMajorVersion}" if [ "${mkdocsMajorVersion}" -lt "${requiredMajorVersion}" ]; then echo "" echo "MkDocs version for this documentation must be version ${requiredMajorVersion} or later." echo "MkDocs mersion that is found is ${mkdocsMajorVersion}, from full version ${mkdocsVersion}." exit 1 else echo "" echo "MkDocs major version (${mkdocsMajorVersion}) is OK for this documentation." fi } # Determine the operating system that is running the script: # - mainly care whether Cygwin or MINGW # - sets the ${operatingSystem} global variable checkOperatingSystem() { local os if [ ! -z "${operatingSystem}" ]; then # Have already checked operating system so return return fi operatingSystem="unknown" os=$(uname | tr [a-z] [A-Z]) case "${os}" in CYGWIN*) operatingSystem="cygwin" ;; LINUX*) operatingSystem="linux" ;; MINGW*) operatingSystem="mingw" ;; esac } # Check the source files for issues # - the main issue is internal links need to use [](file.md), not [](file) checkSourceDocs() { # Currently don't do anything but could check the above # Need one line to not cause an error : } # Set the MkDocs executable to use, depending operating system and PATH: # - sets the global ${mkdocsExe} variable # - return 0 if the executable is found, exit with 1 if not setMkDocsExe() { if [ "${operatingSystem}" = "cygwin" -o "${operatingSystem}" = "linux" ]; then # Is usually in the PATH. mkdocsExe="mkdocs" if hash py 2>/dev/null; then echo "mkdocs is not found (not in PATH)." exit 1 fi elif [ "${operatingSystem}" = "mingw" ]; then # This is used by Git Bash: # - calling 'hash' is a way to determine if the executable is in the path if hash py 2>/dev/null; then mkdocsExe="py -m mkdocs" else # Try adding the Windows folder to the PATH and rerun: # - not sure why C:\Windows is not in the path in the first place PATH=/C/Windows:${PATH} if hash py 2>/dev/null; then mkdocsExe="py -m mkdocs" else echo 'mkdocs is not found in C:\Windows.' exit 1 fi fi fi return 0 } # Entry point into the script. # Check the operating system. checkOperatingSystem # Set the MkDocs executable: # - will exit if MkDocs is not found setMkDocsExe # Make sure the MkDocs version is OK: # - will exit if version is not found checkMkdocsVersion # Check the source files for issues. checkSourceDocs # Get the folder where this script is located since it may have been run from any folder. scriptFolder=$(cd $(dirname "$0") && pwd) # Change to the folder where the script is since other actions below are relative to that. cd ${scriptFolder} cd ../mkdocs-project # Run MkDocs: # - use port 8000 for user documentation port=8000 echo "View the website using http://localhost:${port}" echo "Stop the server with CTRL-C" ${mkdocsExe} serve -a 0.0.0.0:${port} # Exit with MkDocs exit status. exit $?
class Main { constructor() { } public run() { if (!Detector.webgl) { Detector.addGetWebGLMessage(null); } else { App.run() // App.viewOther(ExpConfig.Game_SceneJump) } } }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.software_pages = void 0; var software_pages = { "viewBox": "0 0 64 64", "children": [{ "name": "g", "attribs": {}, "children": [{ "name": "polygon", "attribs": { "fill": "none", "stroke": "#000000", "stroke-width": "2", "stroke-miterlimit": "10", "points": "11,11 32,11 32,53 1,53 1,21 \t" }, "children": [{ "name": "polygon", "attribs": { "fill": "none", "stroke": "#000000", "stroke-width": "2", "stroke-miterlimit": "10", "points": "11,11 32,11 32,53 1,53 1,21 \t" }, "children": [] }] }, { "name": "polyline", "attribs": { "fill": "none", "stroke": "#000000", "stroke-width": "2", "stroke-miterlimit": "10", "points": "1,21 11,21 11,11 \t" }, "children": [{ "name": "polyline", "attribs": { "fill": "none", "stroke": "#000000", "stroke-width": "2", "stroke-miterlimit": "10", "points": "1,21 11,21 11,11 \t" }, "children": [] }] }] }, { "name": "g", "attribs": {}, "children": [{ "name": "polygon", "attribs": { "fill": "none", "stroke": "#000000", "stroke-width": "2", "stroke-miterlimit": "10", "points": "53,11 32,11 32,53 63,53 63,21 \t" }, "children": [{ "name": "polygon", "attribs": { "fill": "none", "stroke": "#000000", "stroke-width": "2", "stroke-miterlimit": "10", "points": "53,11 32,11 32,53 63,53 63,21 \t" }, "children": [] }] }, { "name": "polyline", "attribs": { "fill": "none", "stroke": "#000000", "stroke-width": "2", "stroke-miterlimit": "10", "points": "63,21 53,21 53,11 \t" }, "children": [{ "name": "polyline", "attribs": { "fill": "none", "stroke": "#000000", "stroke-width": "2", "stroke-miterlimit": "10", "points": "63,21 53,21 53,11 \t" }, "children": [] }] }] }, { "name": "line", "attribs": { "fill": "none", "stroke": "#000000", "stroke-width": "2", "stroke-miterlimit": "10", "x1": "32", "y1": "6", "x2": "32", "y2": "58" }, "children": [] }] }; exports.software_pages = software_pages;
class URLSanitizer: @classmethod def _get_sanitized_url(cls, url): # Remove query parameters if '?' in url: url = url.split('?')[0] # Remove fragments if '#' in url: url = url.split('#')[0] # Remove trailing slashes if url.endswith('/'): url = url[:-1] return url
/****************************************************************************** * * Copyright(c) 2013 Realtek Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of version 2 of the GNU General Public License as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA * * ******************************************************************************/ #include <rtw_odm.h> #include <hal_data.h> const char *odm_comp_str[] = { /* BIT0 */"ODM_COMP_DIG", /* BIT1 */"ODM_COMP_RA_MASK", /* BIT2 */"ODM_COMP_DYNAMIC_TXPWR", /* BIT3 */"ODM_COMP_FA_CNT", /* BIT4 */"ODM_COMP_RSSI_MONITOR", /* BIT5 */"ODM_COMP_CCK_PD", /* BIT6 */"ODM_COMP_ANT_DIV", /* BIT7 */"ODM_COMP_PWR_SAVE", /* BIT8 */"ODM_COMP_PWR_TRAIN", /* BIT9 */"ODM_COMP_RATE_ADAPTIVE", /* BIT10 */"ODM_COMP_PATH_DIV", /* BIT11 */"ODM_COMP_PSD", /* BIT12 */"ODM_COMP_DYNAMIC_PRICCA", /* BIT13 */"ODM_COMP_RXHP", /* BIT14 */"ODM_COMP_MP", /* BIT15 */"ODM_COMP_CFO_TRACKING", /* BIT16 */"ODM_COMP_ACS", /* BIT17 */"PHYDM_COMP_ADAPTIVITY", /* BIT18 */"PHYDM_COMP_RA_DBG", /* BIT19 */"PHYDM_COMP_TXBF", /* BIT20 */"ODM_COMP_EDCA_TURBO", /* BIT21 */"ODM_COMP_EARLY_MODE", /* BIT22 */"ODM_FW_DEBUG_TRACE", /* BIT23 */NULL, /* BIT24 */"ODM_COMP_TX_PWR_TRACK", /* BIT25 */"ODM_COMP_RX_GAIN_TRACK", /* BIT26 */"ODM_COMP_CALIBRATION", /* BIT27 */NULL, /* BIT28 */"ODM_PHY_CONFIG", /* BIT29 */"BEAMFORMING_DEBUG", /* BIT30 */"ODM_COMP_COMMON", /* BIT31 */"ODM_COMP_INIT", /* BIT32 */"ODM_COMP_NOISY_DETECT", /* BIT33 */"ODM_COMP_DFS", }; #define RTW_ODM_COMP_MAX 34 const char *odm_ability_str[] = { /* BIT0 */"ODM_BB_DIG", /* BIT1 */"ODM_BB_RA_MASK", /* BIT2 */"ODM_BB_DYNAMIC_TXPWR", /* BIT3 */"ODM_BB_FA_CNT", /* BIT4 */"ODM_BB_RSSI_MONITOR", /* BIT5 */"ODM_BB_CCK_PD", /* BIT6 */"ODM_BB_ANT_DIV", /* BIT7 */"ODM_BB_PWR_SAVE", /* BIT8 */"ODM_BB_PWR_TRAIN", /* BIT9 */"ODM_BB_RATE_ADAPTIVE", /* BIT10 */"ODM_BB_PATH_DIV", /* BIT11 */"ODM_BB_PSD", /* BIT12 */"ODM_BB_RXHP", /* BIT13 */"ODM_BB_ADAPTIVITY", /* BIT14 */"ODM_BB_CFO_TRACKING", /* BIT15 */"ODM_BB_NHM_CNT", /* BIT16 */"ODM_BB_PRIMARY_CCA", /* BIT17 */"ODM_BB_TXBF", /* BIT18 */NULL, /* BIT19 */NULL, /* BIT20 */"ODM_MAC_EDCA_TURBO", /* BIT21 */"ODM_MAC_EARLY_MODE", /* BIT22 */NULL, /* BIT23 */NULL, /* BIT24 */"ODM_RF_TX_PWR_TRACK", /* BIT25 */"ODM_RF_RX_GAIN_TRACK", /* BIT26 */"ODM_RF_CALIBRATION", }; #define RTW_ODM_ABILITY_MAX 27 const char *odm_dbg_level_str[] = { NULL, "ODM_DBG_OFF", "ODM_DBG_SERIOUS", "ODM_DBG_WARNING", "ODM_DBG_LOUD", "ODM_DBG_TRACE", }; #define RTW_ODM_DBG_LEVEL_NUM 6 void rtw_odm_dbg_comp_msg(void *sel, _adapter *adapter) { HAL_DATA_TYPE *pHalData = GET_HAL_DATA(adapter); DM_ODM_T *odm = &pHalData->odmpriv; int cnt = 0; u64 dbg_comp = 0; int i; rtw_hal_get_odm_var(adapter, HAL_ODM_DBG_FLAG, &dbg_comp, NULL); DBG_871X_SEL_NL(sel, "odm.DebugComponents = 0x%016llx\n", dbg_comp); for (i=0;i<RTW_ODM_COMP_MAX;i++) { if (odm_comp_str[i]) DBG_871X_SEL_NL(sel, "%cBIT%-2d %s\n", (BIT0 & (dbg_comp >> i)) ? '+' : ' ', i, odm_comp_str[i]); } } inline void rtw_odm_dbg_comp_set(_adapter *adapter, u64 comps) { rtw_hal_set_odm_var(adapter, HAL_ODM_DBG_FLAG, &comps, _FALSE); } void rtw_odm_dbg_level_msg(void *sel, _adapter *adapter) { HAL_DATA_TYPE *pHalData = GET_HAL_DATA(adapter); DM_ODM_T *odm = &pHalData->odmpriv; int cnt = 0; u32 dbg_level = 0; int i; rtw_hal_get_odm_var(adapter, HAL_ODM_DBG_LEVEL, &dbg_level, NULL); DBG_871X_SEL_NL(sel, "odm.DebugLevel = %u\n", dbg_level); for (i=0;i<RTW_ODM_DBG_LEVEL_NUM;i++) { if (odm_dbg_level_str[i]) DBG_871X_SEL_NL(sel, "%u %s\n", i, odm_dbg_level_str[i]); } } inline void rtw_odm_dbg_level_set(_adapter *adapter, u32 level) { rtw_hal_set_odm_var(adapter, HAL_ODM_DBG_LEVEL, &level, _FALSE); } void rtw_odm_ability_msg(void *sel, _adapter *adapter) { HAL_DATA_TYPE *pHalData = GET_HAL_DATA(adapter); DM_ODM_T *odm = &pHalData->odmpriv; int cnt = 0; u32 ability = 0; int i; ability = rtw_phydm_ability_get(adapter); DBG_871X_SEL_NL(sel, "odm.SupportAbility = 0x%08x\n", ability); for (i=0;i<RTW_ODM_ABILITY_MAX;i++) { if (odm_ability_str[i]) DBG_871X_SEL_NL(sel, "%cBIT%-2d %s\n", (BIT0 << i) & ability ? '+' : ' ', i, odm_ability_str[i]); } } inline void rtw_odm_ability_set(_adapter *adapter, u32 ability) { rtw_phydm_ability_set(adapter, ability); } /* set ODM_CMNINFO_IC_TYPE based on chip_type */ void rtw_odm_init_ic_type(_adapter *adapter) { HAL_DATA_TYPE *hal_data = GET_HAL_DATA(adapter); DM_ODM_T *odm = &hal_data->odmpriv; u4Byte ic_type = chip_type_to_odm_ic_type(rtw_get_chip_type(adapter)); rtw_warn_on(!ic_type); ODM_CmnInfoInit(odm, ODM_CMNINFO_IC_TYPE, ic_type); } inline void rtw_odm_set_force_igi_lb(_adapter *adapter, u8 lb) { HAL_DATA_TYPE *hal_data = GET_HAL_DATA(adapter); hal_data->u1ForcedIgiLb = lb; } inline u8 rtw_odm_get_force_igi_lb(_adapter *adapter) { HAL_DATA_TYPE *hal_data = GET_HAL_DATA(adapter); return hal_data->u1ForcedIgiLb; } void rtw_odm_adaptivity_ver_msg(void *sel, _adapter *adapter) { DBG_871X_SEL_NL(sel, "ADAPTIVITY_VERSION "ADAPTIVITY_VERSION"\n"); } #define RTW_ADAPTIVITY_EN_DISABLE 0 #define RTW_ADAPTIVITY_EN_ENABLE 1 void rtw_odm_adaptivity_en_msg(void *sel, _adapter *adapter) { struct registry_priv *regsty = &adapter->registrypriv; struct mlme_priv *mlme = &adapter->mlmepriv; HAL_DATA_TYPE *hal_data = GET_HAL_DATA(adapter); DM_ODM_T *odm = &hal_data->odmpriv; DBG_871X_SEL_NL(sel, "RTW_ADAPTIVITY_EN_"); if (regsty->adaptivity_en == RTW_ADAPTIVITY_EN_DISABLE) { DBG_871X_SEL(sel, "DISABLE\n"); } else if (regsty->adaptivity_en == RTW_ADAPTIVITY_EN_ENABLE) { DBG_871X_SEL(sel, "ENABLE\n"); } else { DBG_871X_SEL(sel, "INVALID\n"); } } #define RTW_ADAPTIVITY_MODE_NORMAL 0 #define RTW_ADAPTIVITY_MODE_CARRIER_SENSE 1 void rtw_odm_adaptivity_mode_msg(void *sel, _adapter *adapter) { struct registry_priv *regsty = &adapter->registrypriv; DBG_871X_SEL_NL(sel, "RTW_ADAPTIVITY_MODE_"); if (regsty->adaptivity_mode == RTW_ADAPTIVITY_MODE_NORMAL) { DBG_871X_SEL(sel, "NORMAL\n"); } else if (regsty->adaptivity_mode == RTW_ADAPTIVITY_MODE_CARRIER_SENSE) { DBG_871X_SEL(sel, "CARRIER_SENSE\n"); } else { DBG_871X_SEL(sel, "INVALID\n"); } } #define RTW_ADAPTIVITY_DML_DISABLE 0 #define RTW_ADAPTIVITY_DML_ENABLE 1 void rtw_odm_adaptivity_dml_msg(void *sel, _adapter *adapter) { struct registry_priv *regsty = &adapter->registrypriv; DBG_871X_SEL_NL(sel, "RTW_ADAPTIVITY_DML_"); if (regsty->adaptivity_dml == RTW_ADAPTIVITY_DML_DISABLE) { DBG_871X_SEL(sel, "DISABLE\n"); } else if (regsty->adaptivity_dml == RTW_ADAPTIVITY_DML_ENABLE) { DBG_871X_SEL(sel, "ENABLE\n"); } else { DBG_871X_SEL(sel, "INVALID\n"); } } void rtw_odm_adaptivity_dc_backoff_msg(void *sel, _adapter *adapter) { struct registry_priv *regsty = &adapter->registrypriv; DBG_871X_SEL_NL(sel, "RTW_ADAPTIVITY_DC_BACKOFF:%u\n", regsty->adaptivity_dc_backoff); } void rtw_odm_adaptivity_config_msg(void *sel, _adapter *adapter) { rtw_odm_adaptivity_ver_msg(sel, adapter); rtw_odm_adaptivity_en_msg(sel, adapter); rtw_odm_adaptivity_mode_msg(sel, adapter); rtw_odm_adaptivity_dml_msg(sel, adapter); rtw_odm_adaptivity_dc_backoff_msg(sel, adapter); } bool rtw_odm_adaptivity_needed(_adapter *adapter) { struct registry_priv *regsty = &adapter->registrypriv; struct mlme_priv *mlme = &adapter->mlmepriv; bool ret = _FALSE; if (regsty->adaptivity_en == RTW_ADAPTIVITY_EN_ENABLE) ret = _TRUE; return ret; } void rtw_odm_adaptivity_parm_msg(void *sel, _adapter *adapter) { HAL_DATA_TYPE *pHalData = GET_HAL_DATA(adapter); DM_ODM_T *odm = &pHalData->odmpriv; rtw_odm_adaptivity_config_msg(sel, adapter); DBG_871X_SEL_NL(sel, "%10s %16s %16s %22s %12s\n" , "TH_L2H_ini", "TH_EDCCA_HL_diff", "TH_L2H_ini_mode2", "TH_EDCCA_HL_diff_mode2", "EDCCA_enable"); DBG_871X_SEL_NL(sel, "0x%-8x %-16d 0x%-14x %-22d %-12d\n" , (u8)odm->TH_L2H_ini , odm->TH_EDCCA_HL_diff , (u8)odm->TH_L2H_ini_mode2 , odm->TH_EDCCA_HL_diff_mode2 , odm->EDCCA_enable ); DBG_871X_SEL_NL(sel, "%15s %9s\n", "AdapEnableState", "Adap_Flag"); DBG_871X_SEL_NL(sel, "%-15x %-9x\n" , odm->Adaptivity_enable , odm->adaptivity_flag ); } void rtw_odm_adaptivity_parm_set(_adapter *adapter, s8 TH_L2H_ini, s8 TH_EDCCA_HL_diff, s8 TH_L2H_ini_mode2, s8 TH_EDCCA_HL_diff_mode2, u8 EDCCA_enable) { HAL_DATA_TYPE *pHalData = GET_HAL_DATA(adapter); DM_ODM_T *odm = &pHalData->odmpriv; odm->TH_L2H_ini = TH_L2H_ini; odm->TH_EDCCA_HL_diff = TH_EDCCA_HL_diff; odm->TH_L2H_ini_mode2 = TH_L2H_ini_mode2; odm->TH_EDCCA_HL_diff_mode2 = TH_EDCCA_HL_diff_mode2; odm->EDCCA_enable = EDCCA_enable; } void rtw_odm_get_perpkt_rssi(void *sel, _adapter *adapter) { HAL_DATA_TYPE *hal_data = GET_HAL_DATA(adapter); DM_ODM_T *odm = &(hal_data->odmpriv); DBG_871X_SEL_NL(sel,"RxRate = %s, RSSI_A = %d(%%), RSSI_B = %d(%%)\n", HDATA_RATE(odm->RxRate), odm->RSSI_A, odm->RSSI_B); } void rtw_odm_acquirespinlock(_adapter *adapter, RT_SPINLOCK_TYPE type) { PHAL_DATA_TYPE pHalData = GET_HAL_DATA(adapter); _irqL irqL; switch(type) { case RT_IQK_SPINLOCK: _enter_critical_bh(&pHalData->IQKSpinLock, &irqL); default: break; } } void rtw_odm_releasespinlock(_adapter *adapter, RT_SPINLOCK_TYPE type) { PHAL_DATA_TYPE pHalData = GET_HAL_DATA(adapter); _irqL irqL; switch(type) { case RT_IQK_SPINLOCK: _exit_critical_bh(&pHalData->IQKSpinLock, &irqL); default: break; } } #ifdef CONFIG_DFS_MASTER inline u8 rtw_odm_get_dfs_domain(_adapter *adapter) { HAL_DATA_TYPE *hal_data = GET_HAL_DATA(adapter); PDM_ODM_T pDM_Odm = &(hal_data->odmpriv); return pDM_Odm->DFS_RegionDomain; } inline VOID rtw_odm_radar_detect_reset(_adapter *adapter) { phydm_radar_detect_reset(GET_ODM(adapter)); } inline VOID rtw_odm_radar_detect_disable(_adapter *adapter) { phydm_radar_detect_disable(GET_ODM(adapter)); } /* called after ch, bw is set */ inline VOID rtw_odm_radar_detect_enable(_adapter *adapter) { phydm_radar_detect_enable(GET_ODM(adapter)); } inline BOOLEAN rtw_odm_radar_detect(_adapter *adapter) { return phydm_radar_detect(GET_ODM(adapter)); } #endif /* CONFIG_DFS_MASTER */
<filename>bin/cmd/publish.js let helper = require("../../src/util/helper"); module.exports = { command: "publish", desc: "publish project", paras: ["[name]"], fn: function (params) { let name = params[0]; return require("../../index").publish(helper.getAppInfo(process.cwd(), name, false)); } };
<filename>CoordenacaoFacil/models/Abstract.py from CoordenacaoFacil import db class Abstract(): def __init__(self, code="", name="", createdAt=""): self.code = code self.name = name self.createdAt = createdAt def create(self, abstract=None): db.abstracts.insert({ "code": abstract.code, "name": abstract.name, "createdAt": abstract.createdAt, }) return True def getAllAbstracts(self): abstracts = db.abstracts.find({}) return abstracts def getAllAbstractsByCourse(self, course=""): abstracts = db.abstracts.find({"course.code": course}) return abstracts def getAbstractByCode(self, code=""): abstract = db.abstracts.find_one({"code": code}) return abstract
/* * Copyright 2014-present Open Networking Foundation * * 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 org.onlab.graph; import org.junit.Test; import java.util.HashSet; import java.util.Set; import static com.google.common.collect.ImmutableSet.of; import static org.junit.Assert.assertEquals; import static org.onlab.graph.GraphPathSearch.ALL_PATHS; /** * Test of the Bellman-Ford algorithm. */ public class BellmanFordGraphSearchTest extends BreadthFirstSearchTest { @Override protected AbstractGraphPathSearch<TestVertex, TestEdge> graphSearch() { return new BellmanFordGraphSearch<>(); } @Test @Override public void defaultGraphTest() { executeDefaultTest(7, 5, new TestDoubleWeight(5.0)); } @Test public void defaultHopCountWeight() { weigher = null; executeDefaultTest(10, 3, new ScalarWeight(3.0)); } @Test public void searchGraphWithNegativeCycles() { Set<TestVertex> vertexes = new HashSet<>(vertexes()); vertexes.add(Z); Set<TestEdge> edges = new HashSet<>(edges()); edges.add(new TestEdge(G, Z, new TestDoubleWeight(1.0))); edges.add(new TestEdge(Z, G, new TestDoubleWeight(-2.0))); graph = new AdjacencyListsGraph<>(vertexes, edges); GraphPathSearch<TestVertex, TestEdge> search = graphSearch(); Set<Path<TestVertex, TestEdge>> paths = search.search(graph, A, H, weigher, ALL_PATHS).paths(); assertEquals("incorrect paths count", 1, paths.size()); Path p = paths.iterator().next(); assertEquals("incorrect src", A, p.src()); assertEquals("incorrect dst", H, p.dst()); assertEquals("incorrect path length", 5, p.edges().size()); assertEquals("incorrect path cost", new TestDoubleWeight(5), p.cost()); paths = search.search(graph, A, G, weigher, ALL_PATHS).paths(); assertEquals("incorrect paths count", 0, paths.size()); paths = search.search(graph, A, null, weigher, ALL_PATHS).paths(); printPaths(paths); assertEquals("incorrect paths count", 6, paths.size()); } @Test public void testNegativeEdge() { graph = new AdjacencyListsGraph<>(of(A, B, C, D), of(new TestEdge(A, B, W3), new TestEdge(A, C, W4), new TestEdge(C, B, NW2), new TestEdge(B, C, W2), new TestEdge(A, D, W5), new TestEdge(D, B, new TestDoubleWeight(-3)))); GraphPathSearch<TestVertex, TestEdge> gs = graphSearch(); Set<Path<TestVertex, TestEdge>> paths = gs.search(graph, A, B, weigher, 1).paths(); printPaths(paths); assertEquals("incorrect path count", 1, paths.size()); assertEquals("incoreect path cost", new TestDoubleWeight(2), paths.iterator().next().cost()); executeSearch(graphSearch(), graph, A, B, weigher, 2, W2); } @Test public void multipleNegatives() { graph = new AdjacencyListsGraph<>(of(A, B, C, D, E), of(new TestEdge(A, B, W1), new TestEdge(B, C, W1), new TestEdge(C, D, W1), new TestEdge(D, E, W1), new TestEdge(A, B, new TestDoubleWeight(-4)), new TestEdge(A, C, new TestDoubleWeight(-3)), new TestEdge(A, D, NW1), new TestEdge(D, C, NW1))); executeSearch(graphSearch(), graph, A, E, weigher, 2, NW1); executeSinglePathSearch(graphSearch(), graph, A, E, weigher, 1, NW1); executeSearch(graphSearch(), graph, B, C, weigher, 1, W1); } @Test public void manualWeights() { graph = new AdjacencyListsGraph<>(of(A, B, C), of(new TestEdge(A, B, new TestDoubleWeight(-3.3)), new TestEdge(B, C, new TestDoubleWeight(1.3)), new TestEdge(A, C, new TestDoubleWeight(-1.9)), new TestEdge(B, C, new TestDoubleWeight(1.5)))); executeSearch(graphSearch(), graph, A, C, weigher, 1, new TestDoubleWeight(-2.0)); } }
mkdir -p /env mkdir -p /etc/solr/conf echo "HOSTNAME=$HOSTNAME" > /env/hostname.env genvsubst --env /env --any --sub $BUILD_TEMPLATES_DIR/solr/conf --out=/etc/solr/conf genvsubst --env /env --any --sub $BUILD_TEMPLATES_DIR/solr/bin --out=/usr/lib/solr/bin
module PoolParty module Remote # Select a list of instances based on their status def nodes(hsh={}) # _nodes[hsh] ||= list_of_instances.select_with_hash(hsh) end # Select the list of instances, either based on the neighborhoods # loaded from /etc/poolparty/neighborhood.json # or by the remote_base on keypair def list_of_instances return @list_of_instances if @list_of_instances @containing_cloud = self n = Neighborhoods.load_default @list_of_instances = (n.empty? ? _list_of_instances : n.instances) end private # Cache the instances_by_status here def _nodes @_nodes ||= {} end # List the instances for the current key pair, regardless of their states # If no keypair is passed, select them all def _list_of_instances(select={}) @describe_instances ||= remote_base.describe_instances(options).select_with_hash(select) end # If the cloud is starting an instance, it will not be listed in # the running instances, so we need to keep track of the instance # that is being started so we can add it to the neighborhood list def started_instance @started_instance ||= [] end # Reset the cache of descriptions def reset_remoter_base! @_nodes = @list_of_instances = @describe_instances = nil end end end
#!/bin/bash # # This library holds golang related utility functions. # os::golang::verify_go_version ensure the go tool exists and is a viable version. function os::golang::verify_go_version() { os::util::ensure::system_binary_exists 'go' local go_version go_version=($(go version)) if [[ "${go_version[2]}" != go1.6* ]]; then os::log::info "Detected go version: ${go_version[*]}." if [[ -z "${PERMISSIVE_GO:-}" ]]; then os::log::error "Please install Go version 1.6 or use PERMISSIVE_GO=y to bypass this check." return 1 else os::log::warn "Detected golang version doesn't match preferred Go version for Origin." os::log::warn "This version mismatch could lead to differences in execution between this run and the Origin CI systems." return 0 fi fi } readonly -f os::golang::verify_go_version
override func willTransition(to presentationStyle: MSMessagesAppPresentationStyle) { // Called before the extension transitions to a new presentation style. switch presentationStyle { case .compact: // Logic for handling transition to compact presentation style // Prepare for the change in presentation style for compact mode case .expanded: // Logic for handling transition to expanded presentation style // Prepare for the change in presentation style for expanded mode @unknown default: // Handle any unknown presentation styles break } } override func didTransition(to presentationStyle: MSMessagesAppPresentationStyle) { // Called after the extension transitions to a new presentation style. switch presentationStyle { case .compact: // Logic for handling transition to compact presentation style // Finalize any behaviors associated with the change in presentation style for compact mode case .expanded: // Logic for handling transition to expanded presentation style // Finalize any behaviors associated with the change in presentation style for expanded mode @unknown default: // Handle any unknown presentation styles break } }
const sort = (arr) => { for (let i = 0; i < arr.length; i++) { let min = i; for (let j = i + 1; j < arr.length; j++) { if (arr[j] < arr[min]) { min = j; } } if (min !== i) { let temp = arr[i]; arr[i] = arr[min]; arr[min] = temp; } } return arr; } console.log(sort([7, 5, 9, 3, 1]));
#!/usr/bin/env bash set -xeo pipefail if [[ "$(pwd)" == "$(cd "$(dirname "$0")"; pwd -P)" ]]; then echo "Can only be executed from project root!" exit 1 fi declare -x OC_TEST_ALT_HOME [[ -z "${OC_TEST_ALT_HOME}" ]] && OC_TEST_ALT_HOME=1 pushd tests/acceptance ./run.sh "$@" popd
<filename>lib/poolparty/core/array.rb =begin rdoc Array extensions =end require "enumerator" class Array def to_os map {|a| a.to_os } end def collect_with_index &block self.enum_for(:each_with_index).collect &block end def runnable(quiet=true) self.join(" \n ").runnable(quiet) end def nice_runnable(quiet=true) self.flatten.reject{|e| (e.nil? || e.empty?) }.join(" \n ").chomp.nice_runnable(quiet) end def to_string(pre="") map {|a| a.to_string(pre)}.join("\n") end def get_named(str="") map {|a| a.name == str ? a : nil }.reject {|a| a.nil? } end def respec_string(ns=[]) "'#{map {|e| e.to_option_string }.join("', '")}'" end # Example nodes.select_with_hash(:status=>'running') def select_with_hash(conditions={}) return self if conditions.empty? select do |node| conditions.any? do |k,v| ( node.has_key?(k) && node[k]==v ) or ( node.respond_to?(k) && node.send(k)==v ) end end end def wrapping_next(id) raise "Element #{id} not in array" unless index(id) index(id) >= size-1 ? at(0) : at(index(id)+1) end end
import re string = "This movie was released in 1980" # search for substring of 4 digits result = re.search(r'\d{4}', string) # print the year if result: print(result.group())
package io.latent.storm.rabbitmq; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import backtype.storm.tuple.Tuple; /** * This interface describes an object that will perform the work of mapping * incoming {@link Tuple}s to {@link Message} objects for posting on a RabbitMQ * exchange. * */ public abstract class TupleToMessage implements Serializable { protected void prepare(@SuppressWarnings("rawtypes") Map stormConfig) {} /** * Convert the incoming {@link Tuple} on the Storm stream to a {@link Message} * for posting to RabbitMQ. * * @param input * The incoming {@link Tuple} from Storm * @return The {@link Message} for the {@link RabbitMQProducer} to publish. If * transformation fails this should return Message.NONE. */ protected Message produceMessage(Tuple input) { return Message.forSending( extractBody(input), specifyHeaders(input), determineExchangeName(input), determineRoutingKey(input), specifyContentType(input), specifyContentEncoding(input), specifyMessagePersistence(input) ); } /** * Extract message body as a byte array from the incoming tuple. This is required. * This implementation must handle errors and should return null upon on unresolvable * errors. * * @param input the incoming tuple * @return message body as a byte array or null if extraction cannot be performed */ protected abstract byte[] extractBody(Tuple input); /** * Determine the exchange where the message is published to. This can be * derived based on the incoming tuple or a fixed value. * * @param input the incoming tuple * @return the exchange where the message is published to. */ protected abstract String determineExchangeName(Tuple input); /** * Determine the routing key used for this message. This can be derived based on * the incoming tuple or a fixed value. Default implementation provides no * routing key. * * @param input the incoming tuple * @return the routing key for this message */ protected String determineRoutingKey(Tuple input) { return ""; // rabbitmq java client library treats "" as no routing key } /** * Specify the headers to be sent along with this message. The default implementation * return an empty map. * * @param input the incoming tuple * @return the headers as a map */ protected Map<String, Object> specifyHeaders(Tuple input) { return new HashMap<String, Object>(); } /** * Specify message body content type. Default implementation skips the provision * of this detail. * * @param input the incoming tuple * @return content type */ protected String specifyContentType(Tuple input) { return null; } /** * Specify message body content encoding. Default implementation skips the provision * of this detail. * * @param input the incoming tuple * @return content encoding */ protected String specifyContentEncoding(Tuple input) { return null; } /** * Specify whether each individual message should make use of message persistence * when it's on a rabbitmq queue. This does imply queue durability or high availability * or just avoidance of message loss. To accomplish that please read rabbitmq docs * on High Availability, Publisher Confirms and Queue Durability in addition to * having this return true. By default, message persistence returns false. * * @param input the incoming tuple * @return whether the message should be persistent to disk or not. Defaults to not. */ protected boolean specifyMessagePersistence(Tuple input) { return false; } }
import React from 'react'; import { IntlProvider as ReactIntlProvider } from 'react-intl'; import { connect } from 'react-redux'; // import { actions as routingActions } from '../../modules/routing'; import translation from '../../../messages/translations.json'; import { query } from '../../utils/url'; const defaultLocale = 'en'; const qs = query(window.location.search.substr(1).split('&')); class IntlProvider extends React.Component { render() { return ( <ReactIntlProvider {...this.props} defaultLocale={defaultLocale} locale={qs['locale'] || defaultLocale} messages={translation[qs['locale']]} /> ); } } export default IntlProvider;
package ExerciciosExtras.exercicios.orientacaoaobjeto; public class Processador { String nomeProcessador; double qtdMaxProcessamento; double qtdEmProcessamento = 0; Computador computador; Processador(Computador computador, String processador, double qtdMaxProcessamento) { this.computador = computador; this.nomeProcessador = processador; this.qtdMaxProcessamento = qtdMaxProcessamento; } void processar(double qtdProcessamento){ if (!this.computador.estaLigado()) { System.out.println("Computador está desligado"); } else if (this.qtdEmProcessamento + qtdProcessamento > this.qtdMaxProcessamento) { System.out.println("Capacidade máxima de processamento atingida"); } else { System.out.println("Alocada memória"); this.qtdEmProcessamento += qtdProcessamento; } } void liberarMemoria(double qtdProcessamento){ if (!this.computador.estaLigado()) { System.out.println("Computador está desligado"); } else if (this.qtdEmProcessamento - qtdProcessamento < 0) { System.out.println("Processamento não pode liberar mais memória"); } else { System.out.println("Desalocada memória"); this.qtdEmProcessamento -= qtdProcessamento; } } void zerarMemoria(){ this.qtdEmProcessamento = 0; } }
import random def generate_password(character_list, min_length): password = '' for i in range(min_length): password += random.choice(character_list) return password if __name__ == '__main__': character_list = ['a', 'b', 'c', 'd', 'e','1','2','3','4','5'] min_length = 8 password = generate_password(character_list, min_length) print(password)
#!/bin/bash # LICENSE UPL 1.0 # # Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. # # Since: Mar, 2020 # Author: mohammed.qureshi@oracle.com # Description: Checks the status of Oracle Database and Locks # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. # export ORACLE_SID=${ORACLE_SID^^} if [ "$DG_OBSERVER_ONLY" = "true" ]; then "$ORACLE_BASE/$CHECK_DB_FILE" exit $? elif "$ORACLE_BASE/$LOCKING_SCRIPT" --check --file "$ORACLE_BASE/oradata/.${ORACLE_SID}.create_lck"; then exit 1 # create lock held, DB is still initializing elif ! "$ORACLE_BASE/$LOCKING_SCRIPT" --check --file "$ORACLE_BASE/oradata/.${ORACLE_SID}.exist_lck"; then exit 1 # exist lock not held, DB is still initializing elif "$ORACLE_BASE/$CHECK_DB_FILE"; then # DB health is good exit 0 elif test -f "$ORACLE_BASE/oradata/.${ORACLE_SID}.nochk"; then exit 1 # Skip health check elif pgrep -f pmon > /dev/null; then # DB procs detected exit 1 else # No DB procs detected "$ORACLE_BASE/$LOCKING_SCRIPT" --release --file "$ORACLE_BASE/oradata/.${ORACLE_SID}.exist_lck" # Kill the process that keeps the container alive pkill -9 -f "tail.*alert" fi
import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader, Dataset import torchvision.datasets as dset import torchvision.transforms as transforms # Step 1: Define a custom dataset class class SiameseDataset(Dataset): def __init__(self, image_folder_dataset, transform=None): self.image_folder_dataset = image_folder_dataset self.transform = transform def __getitem__(self, index): img0_tuple = self.image_folder_dataset.imgs[index] img0 = dset.folder.default_loader(img0_tuple[0]) if self.transform is not None: img0 = self.transform(img0) should_get_same_class = random.randint(0, 1) if should_get_same_class: while True: img1_tuple = random.choice(self.image_folder_dataset.imgs) if img0_tuple[1] == img1_tuple[1]: break else: while True: img1_tuple = random.choice(self.image_folder_dataset.imgs) if img0_tuple[1] != img1_tuple[1]: break img1 = dset.folder.default_loader(img1_tuple[0]) if self.transform is not None: img1 = self.transform(img1) return img0, img1, torch.from_numpy(np.array([int(img1_tuple[1] != img0_tuple[1])], dtype=np.float32)) def __len__(self): return len(self.image_folder_dataset.imgs) # Step 2: Implement the Siamese network model class SiameseNetwork(nn.Module): def __init__(self): super(SiameseNetwork, self).__init__() self.cnn = nn.Sequential( nn.Conv2d(1, 64, kernel_size=10), nn.ReLU(inplace=True), nn.MaxPool2d(2), nn.Conv2d(64, 128, kernel_size=7), nn.ReLU(inplace=True), nn.MaxPool2d(2), nn.Conv2d(128, 128, kernel_size=4), nn.ReLU(inplace=True), nn.MaxPool2d(2), nn.Conv2d(128, 256, kernel_size=4), nn.ReLU(inplace=True) ) self.fc = nn.Sequential( nn.Linear(256 * 6 * 6, 4096), nn.Sigmoid() ) def forward_once(self, x): output = self.cnn(x) output = output.view(output.size()[0], -1) output = self.fc(output) return output def forward(self, input1, input2): output1 = self.forward_once(input1) output2 = self.forward_once(input2) return output1, output2 # Step 3: Define a custom contrastive loss function class ContrastiveLoss(nn.Module): def __init__(self, margin=2.0): super(ContrastiveLoss, self).__init__() self.margin = margin def forward(self, output1, output2, label): euclidean_distance = F.pairwise_distance(output1, output2, keepdim=True) loss_contrastive = torch.mean((1-label) * torch.pow(euclidean_distance, 2) + (label) * torch.pow(torch.clamp(self.margin - euclidean_distance, min=0.0), 2)) return loss_contrastive
class MechanismManager { constructor() { this.supportedMechanisms = new Set(); } addMechanism(mechanism) { this.supportedMechanisms.add(mechanism); } removeMechanism(mechanism) { this.supportedMechanisms.delete(mechanism); } isMechanismSupported(mechanism) { return this.supportedMechanisms.has(mechanism); } } // Example usage: const manager = new MechanismManager(); manager.addMechanism("mech1"); manager.addMechanism("mech2"); console.log(manager.isMechanismSupported("mech1")); // Output: true console.log(manager.isMechanismSupported("mech3")); // Output: false manager.removeMechanism("mech1"); console.log(manager.isMechanismSupported("mech1")); // Output: false
import os from ray.tune.result import EXPR_PROGRESS_FILE from ray.tune.logger import CSVLogger class PathmindCSVLogger(CSVLogger): def __init__(self, logdir): """Initialize the PathmindCSVLogger. Args: logdir (str): The directory where the log file will be created or appended to. """ self.logdir = logdir progress_file = os.path.join(self.logdir, EXPR_PROGRESS_FILE) self._continuing = ( os.path.exists(progress_file) and os.path.getsize(progress_file) > 0 ) self._file = open(progress_file, "a") self._csv_out = None def on_result(self, result): """Log the result of each iteration to the CSV file. Args: result (dict): The result of the current iteration. """ if self._csv_out is None: self._csv_out = csv.DictWriter(self._file, result.keys()) if not self._continuing: self._csv_out.writeheader() self._csv_out.writerow(result) self._file.flush() def close(self): """Close the CSV file.""" if self._file is not None: self._file.close()
def format_package_name(pkgname): pkgname = pkgname.strip().lower() if pkgname.startswith("lib"): pkgname = pkgname[3:] elif pkgname.startswith("python-"): pkgname = pkgname[7:] elif pkgname.startswith("ruby-"): pkgname = pkgname[5:] return pkgname
#!/bin/bash remote= for arg; do [[ "$arg" =~ :.*/$ ]] && remote=$arg && continue case "$arg" in *) exit 1;; esac done [ "$remote" ] || exit 1 self=$(readlink -e "$0") || exit 1 self=$(dirname "${self}") || exit 1 rsync --inplace --delete --out-format="%t %o %f ... %n" --filter=". ${self}/rs-filter" -Phac "$remote" "${self}/../"
# ASX FlexUnit Runner mxmlc asx_test/src/asx_test.mxml \ -output=asx_test/bin/asx_test.swf \ -debug=true \ -sp+=asx/src \ -sp+=asx_test/src \ -library-path+=asx_test/libs # ASX SpecRunner # mxmlc specs/AsxSpecRunner.mxml \ # -output=bin/AsxSpecs.swf \ # -debug=true \ # -sp specs \ # -sp src \ # -sp ../spectacular-as3/src/ \ # -sp ../hamcrest-as3/hamcrest/src \ # swc compc \ -sp+=asx/src \ -include-sources asx/src \ -output asx/bin/asx.swc # generate docs # asdoc \ # -doc-sources src \ # -source-path src \ # -main-title "ASX API Documentation" \ # -window-title "ASX API Documentation" \ # -output doc
# some unit tests for the bytecode decoding from pypy.jit.metainterp import pyjitpl from pypy.jit.metainterp import jitprof from pypy.jit.metainterp.history import BoxInt, ConstInt from pypy.jit.metainterp.history import History from pypy.jit.metainterp.resoperation import ResOperation, rop from pypy.jit.metainterp.optimizeopt.util import equaloplists from pypy.jit.codewriter.jitcode import JitCode def test_portal_trace_positions(): jitcode = JitCode("f") jitcode.setup(None) portal = JitCode("portal") portal.setup(None) class FakeStaticData: cpu = None warmrunnerdesc = None mainjitcode = portal metainterp = pyjitpl.MetaInterp(FakeStaticData(), FakeStaticData()) metainterp.framestack = [] class FakeHistory: operations = [] history = metainterp.history = FakeHistory() metainterp.newframe(portal, "green1") history.operations.append(1) metainterp.newframe(jitcode) history.operations.append(2) metainterp.newframe(portal, "green2") history.operations.append(3) metainterp.popframe() history.operations.append(4) metainterp.popframe() history.operations.append(5) metainterp.popframe() history.operations.append(6) assert metainterp.portal_trace_positions == [("green1", 0), ("green2", 2), (None, 3), (None, 5)] assert metainterp.find_biggest_function() == "green1" metainterp.newframe(portal, "green3") history.operations.append(7) metainterp.newframe(jitcode) history.operations.append(8) assert metainterp.portal_trace_positions == [("green1", 0), ("green2", 2), (None, 3), (None, 5), ("green3", 6)] assert metainterp.find_biggest_function() == "green1" history.operations.extend([9, 10, 11, 12]) assert metainterp.find_biggest_function() == "green3" def test_remove_consts_and_duplicates(): class FakeStaticData: cpu = None warmrunnerdesc = None def is_another_box_like(box, referencebox): assert box is not referencebox assert isinstance(box, referencebox.clonebox().__class__) assert box.value == referencebox.value return True metainterp = pyjitpl.MetaInterp(FakeStaticData(), None) metainterp.history = History() b1 = BoxInt(1) b2 = BoxInt(2) c3 = ConstInt(3) boxes = [b1, b2, b1, c3] dup = {} metainterp.remove_consts_and_duplicates(boxes, 4, dup) assert boxes[0] is b1 assert boxes[1] is b2 assert is_another_box_like(boxes[2], b1) assert is_another_box_like(boxes[3], c3) assert equaloplists(metainterp.history.operations, [ ResOperation(rop.SAME_AS, [b1], boxes[2]), ResOperation(rop.SAME_AS, [c3], boxes[3]), ]) assert dup == {b1: None, b2: None} # del metainterp.history.operations[:] b4 = BoxInt(4) boxes = [b2, b4, "something random"] metainterp.remove_consts_and_duplicates(boxes, 2, dup) assert is_another_box_like(boxes[0], b2) assert boxes[1] is b4 assert equaloplists(metainterp.history.operations, [ ResOperation(rop.SAME_AS, [b2], boxes[0]), ]) def test_get_name_from_address(): class FakeMetaInterpSd(pyjitpl.MetaInterpStaticData): def __init__(self): pass metainterp_sd = FakeMetaInterpSd() metainterp_sd.setup_list_of_addr2name([(123, 'a'), (456, 'b')]) assert metainterp_sd.get_name_from_address(123) == 'a' assert metainterp_sd.get_name_from_address(456) == 'b' assert metainterp_sd.get_name_from_address(789) == ''
REM FILE NAME: tab_rep.sql REM LOCATION: Object Management\Tables\Reports REM FUNCTION: Document table extended parameters REM TESTED ON: 8.0.4.1, 8.1.5, 8.1.7, 9.0.1 REM PLATFORM: non-specific REM REQUIRES: dba_tables REM REM This is a part of the Knowledge Xpert for Oracle Administration library. REM Copyright (C) 2001 Quest Software REM All rights reserved. REM REM******************** Knowledge Xpert for Oracle Administration ******************** COLUMN owner format a10 heading 'Owner' COLUMN table_name format a15 heading 'Table' COLUMN tablespace_name format a12 heading 'Tablespace' COLUMN table_type_owner format a10 heading 'Type|Owner' COLUMN table_type format a13 heading 'Type' COLUMN iot_name format a10 heading 'IOT|Overflow' COLUMN iot_type format a12 heading 'IOT or|Overflow' COLUMN nested format a6 heading 'Nested' SET lines 130 verify off feedback off pages 58 START title132 'Extended Table Report' SPOOL rep_out\tab_rep SELECT owner, table_name, tablespace_name, iot_name, LOGGING, partitioned, iot_type, TEMPORARY, NESTED FROM dba_tables WHERE owner LIKE UPPER ('%&owner%'); SPOOL off SET verify on lines 80 pages 22 feedback on TTITLE OFF
#!/bin/sh . /scripts/A-config.sh echo Restarting local firewire capture... sudo killall dvsource-firewire sudo killall -9 dvsource-firewire sudo killall dvgrab sudo killall -9 dvgrab sleep 2 sudo dvsource-firewire -c 1 -h $DVHOST -p $DVPORT & sudo dvsource-firewire -h $DVHOST -p $DVPORT
package com.ulfy.master.ui.view; import android.content.Context; import android.util.AttributeSet; import android.view.View; import com.ulfy.android.mvvm.IViewModel; import com.ulfy.android.ui_injection.Layout; import com.ulfy.android.ui_injection.ViewClick; import com.ulfy.master.R; import com.ulfy.master.application.vm.ListVM; import com.ulfy.master.ui.activity.ContactBookActivity; import com.ulfy.master.ui.activity.CountryCodeActivity; import com.ulfy.master.ui.activity.List1Activity; import com.ulfy.master.ui.activity.List2Activity; import com.ulfy.master.ui.activity.List3Activity; import com.ulfy.master.ui.activity.List4Activity; import com.ulfy.master.ui.activity.List5Activity; import com.ulfy.master.ui.activity.StaggeredAutoFullActivity; import com.ulfy.master.ui.activity.StaggeredRandomRatioActivity; import com.ulfy.master.ui.activity.VideoListActivity; import com.ulfy.master.ui.base.BaseView; @Layout(id = R.layout.view_list) public class ListView extends BaseView { private ListVM vm; public ListView(Context context) { super(context); init(context, null); } public ListView(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs); } private void init(Context context, AttributeSet attrs) { } @Override public void bind(IViewModel model) { vm = (ListVM) model; } /** * click: list1TV * 列表页一 */ @ViewClick(ids = R.id.list1TV) private void list1TV(View v) { List1Activity.startActivity(); } /** * click: list2TV * 列表页二 */ @ViewClick(ids = R.id.list2TV) private void list2TV(View v) { List2Activity.startActivity(); } /** * click: list3TV * 列表页三 */ @ViewClick(ids = R.id.list3TV) private void list3TV(View v) { List3Activity.startActivity(); } /** * click: list4TV * 列表页四 */ @ViewClick(ids = R.id.list4TV) private void list4TV(View v) { List4Activity.startActivity(); } /** * click: list5TV * 列表项五 */ @ViewClick(ids = R.id.list5TV) private void list5TV(View v) { List5Activity.startActivity(); } /** * click: list6TV * 列表项六:国家列表 */ @ViewClick(ids = R.id.list6TV) private void list6TV(View v) { CountryCodeActivity.startActivity(); } /** * click: list7TV * 列表七:联系人列表 */ @ViewClick(ids = R.id.list7TV) private void list7TV(View v) { ContactBookActivity.startActivity(); } /** * click: list8TV * 列表八:瀑布流列表 */ @ViewClick(ids = R.id.list8TV) private void list8TV(View v) { StaggeredAutoFullActivity.startActivity(); } /** * click: list9TV * 列表九:瀑布流列表 */ @ViewClick(ids = R.id.list9TV) private void list9TV(View v) { StaggeredRandomRatioActivity.startActivity(); } /** * click: videoListIV * 视频列表页 */ @ViewClick(ids = R.id.videoListIV) private void videoListIV(View v) { VideoListActivity.startActivity(); } }
CREATE TABLE departments ( id SERIAL PRIMARY KEY, name TEXT NOT NULL, budget NUMERIC NOT NULL ); CREATE TABLE employees ( id SERIAL PRIMARY KEY, name TEXT NOT NULL, salary NUMERIC NOT NULL, dept_id INTEGER REFERENCES departments(id) );
#!/bin/sh ../../src/pipeline/config/bootstrap.sh gerardo 070615 43000 43100
def main(): while True: print("1. SSH弱口令爆破") print("2. MySQL弱口令爆破") print("输入exit退出") user_input = input("请选择操作: ") if user_input == "1": print("开始SSH弱口令爆破") # Add code to initiate SSH brute force attack elif user_input == "2": print("开始MySQL弱口令爆破") # Add code to initiate MySQL brute force attack elif user_input.lower() == "exit": print("退出程序") break else: print("无效的选项,请重新输入\n") if __name__ == "__main__": main()
#include <stdlib.h> // ORACLE INT foo(INT, INT, INT, ADDR, ADDR, INT, ADDR, INT, ADDR, INT) int foo(int r1, int r2, int r3, int* r4, int* r5, int r6, int* stack1, int stack2, int* stack3, int stack4) { return r1 + r2 + r3 + *r4 + *r5 + r6 + *stack1 + stack2 + *stack3 + stack4; } int main() { int _4 = 4; int _5 = 5; int _7 = 7; int _9 = 9; for (int i = 0; i < 100; i++) { foo(1, 2, 3, &_4, &_5, 6, &_7, 8, &_9, 10); } }
db.collection.find({ field: { $gt: givenValue } });
import os class DirectoryTraversal: def __init__(self, path, files=[]): self.path = path self.files = files def traverse_files(self, extension): result = [] for root, _, filenames in os.walk(self.path): for filename in filenames: if filename.endswith("." + extension): result.append(filename) return result
package dev.arkav.openoryx.net.data; import dev.arkav.openoryx.net.packets.StatType; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; public class StatData implements DataPacket { public byte statType = 0; public int statValue; public String stringStatValue; public StatData() { } public void read(DataInput in) throws IOException { this.statType = in.readByte(); if(this.isStringStat()) { this.stringStatValue = in.readUTF(); } else { this.statValue = in.readInt(); } } public void write(DataOutput out) throws IOException { out.writeByte(this.statType); if(this.isStringStat()) { out.writeUTF(this.stringStatValue); } else { out.writeInt(this.statValue); } } private boolean isStringStat() { switch (this.statType) { case StatType.NAME_STAT: return true; case StatType.GUILD_NAME_STAT: return true; case StatType.PET_NAME_STAT: return true; case StatType.ACCOUNT_ID_STAT: return true; case StatType.OWNER_ACCOUNT_ID_STAT: return true; default: return false; } } }
const io = require('socket.io'); const port = process.env.PORT || 3001; const server = io(port, () => { console.log('port connected and running on ', port) });
package com.digirati.taxman.rest.server.infrastructure.web; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.context.RequestScoped; import javax.enterprise.inject.Produces; import javax.ws.rs.core.UriInfo; /** * An application wide thread-local context that maintains the active URI for the current request. */ @ApplicationScoped class WebContextHolder { private final ThreadLocal<UriInfo> localUri = new ThreadLocal<>(); void setUriInfo(UriInfo info) { localUri.set(info); } void clear() { localUri.remove(); } /** * A request scoped bean that returns the {@link UriInfo} of the request active in the current * thread. * * @return The {@link UriInfo} of the active request. */ @RequestScoped @Produces UriInfo uriInfo() { return localUri.get(); } }
@test "parcel bundle should include necessary code (no tree-shaking)" { run grep -q span dist/Example.bs.js [ "$status" -eq 0 ] run grep -q "hello" dist/Example.bs.js [ "$status" -eq 0 ] } @test "parcel bundle should include unnecessary code (no tree-shaking)" { run grep -q blockquote dist/Example.bs.js [ "$status" -eq 0 ] } @test "webpack bundle should include necessary code (tree-shaking)" { # This is the variant from Css_Selector.Element.tToJs run grep -q "[-866592054,\"span\"]" dist/bundle.webpack.js [ "$status" -eq 0 ] # This is the constructor for span elements run grep -q "\"span\",Object.assign" dist/bundle.webpack.js [ "$status" -eq 0 ] run grep -q "hello" dist/bundle.webpack.js [ "$status" -eq 0 ] } @test "webpack bundle should disclude unnecessary code (tree-shaking)" { # This is the variant from Css_Selector.Element.tToJs run grep -q "[573069007,\"blockquote\"]" dist/bundle.webpack.js [ "$status" -eq 0 ] # This is the constructor for blockquote elements run grep -q "\"blockquote\",Object.assign" dist/bundle.webpack.js [ "$status" -eq 1 ] } @test "webpack jsx bundle should include necessary code (tree-shaking)" { # This is the variant from Css_Selector.Element.tToJs run grep -q "[-866592054,\"span\"]" dist/bundle.webpack.jsx.js [ "$status" -eq 0 ] # This is the constructor for span elements run grep -q "\"span\",Object.assign" dist/bundle.webpack.jsx.js [ "$status" -eq 0 ] run grep -q "Hello, world!" dist/bundle.webpack.jsx.js [ "$status" -eq 0 ] } @test "webpack jsx bundle should disclude unnecessary code (tree-shaking)" { # This is the variant from Css_Selector.Element.tToJs run grep -q "[573069007,\"blockquote\"]" dist/bundle.webpack.jsx.js [ "$status" -eq 0 ] # This is the constructor for blockquote elements run grep -q "\"blockquote\",Object.assign" dist/bundle.webpack.jsx.js [ "$status" -eq 1 ] } @test "rollup bundle should include necessary code (tree-shaking)" { # This is the variant from Css_Selector.Element.tToJs run grep -q "\"span\"" dist/bundle.rollup.js [ "$status" -eq 0 ] # This is the constructor for span elements run grep -q "\"span\", Object.assign" dist/bundle.rollup.js [ "$status" -eq 0 ] run grep -q "hello" dist/bundle.rollup.js [ "$status" -eq 0 ] } @test "rollup bundle should disclude unnecessary code (tree-shaking)" { # This is the variant from Css_Selector.Element.tToJs run grep -q "\"blockquote\"" dist/bundle.rollup.js [ "$status" -eq 0 ] # This is the constructor for blockquote elements run grep -q "\"blockquote\", Object.assign" dist/bundle.rollup.js [ "$status" -eq 1 ] }
<!DOCTYPE html> <html> <head> <title>Online Store</title> </head> <body> <h1>Online Store</h1> <form> <select id="filterPrice"> <option value="ascending">Price (Low to High)</option> <option value="descending">Price (High to Low)</option> </select> <select id="filterCategory"> <option value="all">All Categories</option> <option value="electronics">Electronics</option> <option value="home">Home</option> <option value="garden">Garden</option> </select> <input type="submit" value="Filter" /> </form> <ul id="productsList"> <li>Product A | Price: $20 | Category: Electronics</li> <li>Product B | Price: $30 | Category: Home</li> <li>Product C | Price: $10 | Category: Garden</li> <li>Product D | Price: $50 | Category: Electronics</li> <li>Product E | Price: $25 | Category: Home</li> </ul> <script> // Get values from selection boxes let order = document.getElementById('filterPrice').value; let category = document.getElementById('filterCategory').value; // Get list of products let productsList = document.getElementById('productsList'); let products = productsList.children; // Sort products based on order and category // ... // Update the dom // ... </script> </body> </html>
<gh_stars>1-10 /** * Copyright © 2016-2021 The Thingsboard Authors * * 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.ciat.bim.server.queue.setting; import lombok.Data; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Data @Component public class TbQueueTransportApiSettings { @Value("${queue.transport_api.requests_topic}") private String requestsTopic; @Value("${queue.transport_api.responses_topic}") private String responsesTopic; @Value("${queue.transport_api.max_pending_requests}") private int maxPendingRequests; @Value("${queue.transport_api.max_requests_timeout}") private int maxRequestsTimeout; @Value("${queue.transport_api.max_callback_threads}") private int maxCallbackThreads; @Value("${queue.transport_api.request_poll_interval}") private long requestPollInterval; @Value("${queue.transport_api.response_poll_interval}") private long responsePollInterval; }
#!/bin/sh PATH=/sbin:/bin:/usr/sbin:/usr/bin ROOT_MOUNT=/mnt/root ROOT_IMAGE_PCR=9 IP=$(which ip) LN=$(which ln) MKDIR=$(which mkdir) MKNOD=$(which mknod) MKTEMP=$(which mktemp) MODPROBE=$(which modprobe) MOUNT=$(which mount) SLEEP=$(which sleep) [ -z "$CONSOLE" ] && CONSOLE="/dev/console" # debug logging failure sequence # give access to a shell fatal() { echo $1 >$CONSOLE echo >$CONSOLE PS1='measured# ' exec sh } # production logging failure sequence (no shell) fatal_prod() { echo $1 >$CONSOLE echo >$CONSOLE } # break points for debugging maybe_break () { if [ "${BREAK:-}" = "$1" ]; then fatal "Spawning shell at breakpoint: '$1' ..." fi } # sanity [ ! -x $IP ] && fatal "No ip command." [ ! -x $LN ] && fatal "No ln command." [ ! -x $MKDIR ] && fatal "No mkdir command." [ ! -x $MKNOD ] && fatal "No mknod command." [ ! -x $MKTEMP ] && fatal "No mktemp command." [ ! -x $MODPROBE ] && fatal "No modprobe command." [ ! -x $MOUNT ] && fatal "No mount command." [ ! -x $SLEEP ] && fatal "No sleep command." makedir () { for DIR in $@; do if [ ! -e $DIR ]; then $MKDIR -p $DIR fi done } early_setup () { makedir /proc /sys $MOUNT -t proc proc /proc $MOUNT -t sysfs sysfs /sys makedir /tmp /run $LN -s /run /var/run } tss_setup () { $MODPROBE -i tpm-tis # tcsd needs loopback networking if ! $IP addr add 127.0.0.1/8 dev lo ; then fatal "failed to give loopback a localhost address" fi if ! $IP link set up dev lo ; then fatal "failed to bring up loopback device" fi # get udev rules executed. we care about tpm & removable media if ! /etc/init.d/udev start ; then fatal "failed to start udev" fi # run tcsd if ! /etc/init.d/trousers start ; then fatal "failed to start tcsd" fi } read_args() { [ -z "$CMDLINE" ] && CMDLINE=`cat /proc/cmdline` for arg in $CMDLINE; do optarg=`expr "x$arg" : 'x[^=]*=\(.*\)'` case $arg in ro) ROOT_MODE=$arg ;; rw) ROOT_MODE=$arg ;; root=*) ROOT_DEVICE=$optarg ;; measureroot) ROOT_MEASURE=true ;; rootimg=*) ROOT_IMAGE=$optarg ;; rootimgpcr=*) ROOT_IMAGE_PCR=$optarg ;; console=*) if [ -z "${console_params}" ]; then console_params=$arg else console_params="$console_params $arg" fi ;; break=*) BREAK=$optarg ;; esac done } # parameter is name of rootfs image # sets ROOT_IMAGE_PATH variable with absolute path to rootfs image find_rootimg() { local rootimg=$1 [ -z $rootimg ] && fatal "No image for root file system provided." echo "Searching for $rootimg in removable media ..." for i in $(seq 1 5); do for device in `ls /run/media 2>/dev/null`; do if [ -f /run/media/$device/$rootimg ] ; then ROOT_IMAGE_PATH=/run/media/$device/$rootimg echo "found root image: $ROOT_IMAGE_PATH" break fi done [ ! -z $ROOT_IMAGE_PATH ] && break echo "No image found on iteration $i ..." $SLEEP 1 done [ -z $ROOT_IMAGE_PATH ] && fatal "could not find root image: $rootimg" } # mount supplied fs image on supplied directory mount_rootimg() { local root_img=$1 local root_mnt=$2 local loop_dev=/dev/loop0 [ -z $root_img ] && fatal "no image file passed to mount_rootimg" [ -z $root_mnt ] && fatal "no mount point passed to mount_rootimg " makedir $root_mnt [ ! -b $loop_dev ] && $MKNOD $loop_dev b 7 0 if ! $MOUNT -o ${ROOT_MODE},loop,noatime,nodiratime $root_img $root_mnt ; then fatal "Failed to mount rootfs image." fi } measure_file() { local file=$1 local pcr=$2 local data="" [ -z $file ] && fatal "no file provided to measure_file" [ ! -f $file ] && fatal "not a file: $file" [ -z $pcr ] && fatal "no PCR provided to measure_file" if ! echo $pcr | grep -q '^[0-9]*$' ; then fatal "value for PCR provided to measure_file isn't a number: $pcr" fi # adding 'coreutils' to get sha1sum adds ~3MB to the initramfs # wonder how long it takes the TPM to hash the whole rootfs? echo "measuring rootfs: $file" data=$(sha1sum -b $file | awk '{ print $1 }' | tr -d '\n') echo "extending PCR $pcr with value $data" echo -n "$data" | tpm_extendpcr --pcr $pcr [ $? -ne 0 ] && fatal "tpm_extendpcr failed" } boot_root() { local rootmnt=$1 [ -z $rootmnt ] && fatal "no root mount given to boot_root" /etc/init.d/trousers stop 2>/dev/null /etc/init.d/udev stop 2>/dev/null # use devtmpfs if available if grep -q devtmpfs /proc/filesystems; then $MOUNT -t devtmpfs devtmpfs $rootmnt/dev fi cd $rootmnt exec switch_root -c $CONSOLE $rootmnt /sbin/init } early_setup read_args maybe_break "tss-setup" tss_setup maybe_break "find-rootimg" find_rootimg $ROOT_IMAGE maybe_break "measure-root" if [ ! -z ${ROOT_MEASURE} ]; then measure_file $ROOT_IMAGE_PATH $ROOT_IMAGE_PCR fi maybe_break "mount-rootimg" mount_rootimg $ROOT_IMAGE_PATH $ROOT_MOUNT maybe_break "boot-root" boot_root $ROOT_MOUNT # fall through == failure fatal "Failed to switch to root image: $ROTO_IMAGE ... unable to continue."
package com.cetekot.jokes.persistence.entity; import lombok.Data; import javax.persistence.*; import java.text.MessageFormat; /** * Copyright: Copyright (c) 2020 * * @author Andrei 'cetekot' Larin * @version 1.0 */ @Entity @Table( name = "jokes" ) @Data public class Joke { @Id @Column( name = "id" ) @GeneratedValue( strategy = GenerationType.IDENTITY ) private Long id; @Column( name = "line", nullable = false ) private String line; @Override public String toString() { return MessageFormat.format( "Joke [id={0}, line={1}]", id, line ); } }
<reponame>fernetjs/beaglejs require("blanket")(["/lib/scraper.js", "/lib/bone.js", "/lib/beagle.js"]); var expect = require('expect.js'), request = require('request'), beagle = require('../lib/beagle.js'), Bone = require('../lib/bone.js'); var host = "http://localhost:3000/"; describe('BeagleJS', function(){ describe('#scrape()', function(){ it('should have a function named scrape()', function(){ expect(beagle.scrape).to.be.a('function'); }); it('should throw an error if options are wrong', function(done){ beagle.scrape("htt://", function(err, bone){ expect(err).to.be.ok(); beagle.scrape({ urlNot: "test" }, function(err, bone){ expect(err).to.be.ok(); expect(err.message).to.be.equal("cannot scrape that, expected property 'url' or 'uri'"); done(); }); }); }); it('should allow to call it with an URL', function(done){ beagle.scrape(host, function(err, bone){ expect(err).to.be(null); expect(bone).to.not.be(undefined); done(); }); }); it('should allow to call it with request options', function(done){ beagle.scrape({ url: host, headers: {'User-Agent': 'Mozilla/7'} }, function(err, bone){ expect(err).to.be(null); expect(bone).to.not.be(undefined); done(); }); }); it('should allow to call it with a Response object', function(done){ request(host, function (error, response, body) { if (error) { callback(error); return; } beagle.scrape(response, function(err, bone){ expect(err).to.be(null); expect(bone).to.not.be(undefined); done(); }); }); }); it('should return an object type of Bone', function(done){ beagle.scrape(host, function(err, bone){ expect(err).to.be(null); expect(bone).to.be.a(Bone); done(); }); }); describe('Bone', function(){ it('should have a property uri with URL properties', function(done){ beagle.scrape(host + "opengraph", function(err, bone){ expect(bone.uri).to.not.be(undefined); var keys = ["protocol", "host", "port", "path"]; for(var i=0; i < keys.length; i++){ expect(bone.uri[keys[i]]).to.not.be(undefined); } done(); }); }); it('should get correctly Open Graph data if it is present', function(done){ beagle.scrape(host + "opengraph", function(err, bone){ expect(bone.title).to.be.equal('OG-Title'); expect(bone.images).to.be.an('array'); expect(bone.images.length).to.be.equal(1); expect(bone.images[0]).to.be.equal(host + 'OG-Image'); expect(bone.preview).to.be.equal('OG-Description'); done(); }); }); it('should get correctly Meta data if it is present', function(done){ beagle.scrape(host + "metadata", function(err, bone){ expect(bone.title).to.be.equal('META-Title'); expect(bone.images).to.be.an('array'); expect(bone.images.length).to.be.equal(1); expect(bone.images[0]).to.be.equal(host + 'META-Image'); expect(bone.preview).to.be.equal('META-Description'); done(); }); }); it('should get data from DOM as downfall for OG & META', function(done){ beagle.scrape(host + "dom", function(err, bone){ expect(bone.title).to.be.equal('DOM-Title'); expect(bone.images).to.be.an('array'); expect(bone.images.length).to.be.equal(4); for(var i=0; i < 2; i++){ expect(bone.images[i]).to.be.equal(host + 'DOM-Image' + i); } expect(bone.images[2]).to.be.equal("http://example.com/DOM-Image2"); expect(bone.images[3]).to.be.equal("http://www.example.com/DOM-Image3"); expect(bone.preview).to.be.equal('DOM-Description'); done(); }); }); it('should get correctly Image of favicon', function(done){ beagle.scrape(host + "favicon", function(err, bone){ expect(bone.favicon).to.be.an('string'); expect(bone.favicon).to.be.equal('http://example.com/someicon.png'); done(); }); }); }); }); });
<gh_stars>10-100 // auto generated by kmigrator // KMIGRATOR:0017_auto_20200627_1032:<KEY> exports.up = async (knex) => { await knex.raw(` BEGIN; -- -- Alter field user on forgotpasswordaction -- SET CONSTRAINTS "ForgotPasswordAction_user_3c52ec86_fk_User_id" IMMEDIATE; ALTER TABLE "ForgotPasswordAction" DROP CONSTRAINT "ForgotPasswordAction_user_3c52ec86_fk_User_id"; ALTER TABLE "ForgotPasswordAction" ALTER COLUMN "user" DROP NOT NULL; ALTER TABLE "ForgotPasswordAction" ADD CONSTRAINT "ForgotPasswordAction_user_3c52ec86_fk_User_id" FOREIGN KEY ("user") REFERENCES "User" ("id") DEFERRABLE INITIALLY DEFERRED; COMMIT; `) } exports.down = async (knex) => { await knex.raw(` BEGIN; -- -- Alter field user on forgotpasswordaction -- SET CONSTRAINTS "ForgotPasswordAction_user_3c52ec86_fk_User_id" IMMEDIATE; ALTER TABLE "ForgotPasswordAction" DROP CONSTRAINT "ForgotPasswordAction_user_3c52ec86_fk_User_id"; ALTER TABLE "ForgotPasswordAction" ALTER COLUMN "user" SET NOT NULL; ALTER TABLE "ForgotPasswordAction" ADD CONSTRAINT "ForgotPasswordAction_user_3c52ec86_fk_User_id" FOREIGN KEY ("user") REFERENCES "User" ("id") DEFERRABLE INITIALLY DEFERRED; COMMIT; `) }
<filename>admin/src/pages/Customers.js import React from 'react'; import { Table, TableHeader, TableCell, TableFooter, TableContainer, Input, Card, CardBody, Pagination, } from '@windmill/react-ui'; import useAsync from '../hooks/useAsync'; import useFilter from '../hooks/useFilter'; import NotFound from '../components/table/NotFound'; import UserServices from '../services/UserServices'; import Loading from '../components/preloader/Loading'; import PageTitle from '../components/Typography/PageTitle'; import CustomerTable from '../components/customer/CustomerTable'; const Customers = () => { const { data, loading } = useAsync(UserServices.getAllUsers); const { userRef, handleChangePage, totalResults, resultsPerPage, dataTable, serviceData, handleSubmitUser, } = useFilter(data); return ( <> <PageTitle>Customers</PageTitle> <Card className="min-w-0 shadow-xs overflow-hidden bg-white dark:bg-gray-800 mb-5"> <CardBody> <form onSubmit={handleSubmitUser} className="py-3 grid gap-4 lg:gap-6 xl:gap-6 md:flex xl:flex" > <div className="flex-grow-0 md:flex-grow lg:flex-grow xl:flex-grow"> <Input ref={userRef} className="border h-12 text-sm focus:outline-none block w-full bg-gray-100 border-transparent focus:bg-white" type="search" name="search" placeholder="Search by name/email/phone" /> <button type="submit" className="absolute right-0 top-0 mt-5 mr-1" ></button> </div> </form> </CardBody> </Card> {loading ? ( <Loading loading={loading} /> ) : serviceData.length !== 0 ? ( <TableContainer className="mb-8"> <Table> <TableHeader> <tr> <TableCell>ID</TableCell> <TableCell>Joining Date</TableCell> <TableCell>Name</TableCell> <TableCell>Email</TableCell> <TableCell>Phone</TableCell> <TableCell className="text-right">Actions</TableCell> </tr> </TableHeader> <CustomerTable customers={dataTable} /> </Table> <TableFooter> <Pagination totalResults={totalResults} resultsPerPage={resultsPerPage} onChange={handleChangePage} label="Table navigation" /> </TableFooter> </TableContainer> ) : ( <NotFound title="Customer" /> )} </> ); }; export default Customers;
#!/usr/bin/env sh test_file=$1 python $test_file --local_rank $SLURM_PROCID --world_size $SLURM_NPROCS --host $HOST --port 29500
#!/bin/sh # base16-shell (https://github.com/chriskempson/base16-shell) # Base16 Shell template by Chris Kempson (http://chriskempson.com) # Mexico Light scheme by Sheldon Johnson color00="f8/f8/f8" # Base 00 - Black color01="ab/46/42" # Base 08 - Red color02="53/89/47" # Base 0B - Green color03="f7/9a/0e" # Base 0A - Yellow color04="7c/af/c2" # Base 0D - Blue color05="96/60/9e" # Base 0E - Magenta color06="4b/80/93" # Base 0C - Cyan color07="38/38/38" # Base 05 - White color08="b8/b8/b8" # Base 03 - Bright Black color09=$color01 # Base 08 - Bright Red color10=$color02 # Base 0B - Bright Green color11=$color03 # Base 0A - Bright Yellow color12=$color04 # Base 0D - Bright Blue color13=$color05 # Base 0E - Bright Magenta color14=$color06 # Base 0C - Bright Cyan color15="18/18/18" # Base 07 - Bright White color16="dc/96/56" # Base 09 color17="a1/69/46" # Base 0F color18="e8/e8/e8" # Base 01 color19="d8/d8/d8" # Base 02 color20="58/58/58" # Base 04 color21="28/28/28" # Base 06 color_foreground="38/38/38" # Base 05 color_background="f8/f8/f8" # Base 00 if [ -n "$TMUX" ]; then # Tell tmux to pass the escape sequences through # (Source: http://permalink.gmane.org/gmane.comp.terminal-emulators.tmux.user/1324) put_template() { printf '\033Ptmux;\033\033]4;%d;rgb:%s\033\033\\\033\\' $@; } put_template_var() { printf '\033Ptmux;\033\033]%d;rgb:%s\033\033\\\033\\' $@; } put_template_custom() { printf '\033Ptmux;\033\033]%s%s\033\033\\\033\\' $@; } elif [ "${TERM%%[-.]*}" = "screen" ]; then # GNU screen (screen, screen-256color, screen-256color-bce) put_template() { printf '\033P\033]4;%d;rgb:%s\007\033\\' $@; } put_template_var() { printf '\033P\033]%d;rgb:%s\007\033\\' $@; } put_template_custom() { printf '\033P\033]%s%s\007\033\\' $@; } elif [ "${TERM%%-*}" = "linux" ]; then put_template() { [ $1 -lt 16 ] && printf "\e]P%x%s" $1 $(echo $2 | sed 's/\///g'); } put_template_var() { true; } put_template_custom() { true; } else put_template() { printf '\033]4;%d;rgb:%s\033\\' $@; } put_template_var() { printf '\033]%d;rgb:%s\033\\' $@; } put_template_custom() { printf '\033]%s%s\033\\' $@; } fi # 16 color space put_template 0 $color00 put_template 1 $color01 put_template 2 $color02 put_template 3 $color03 put_template 4 $color04 put_template 5 $color05 put_template 6 $color06 put_template 7 $color07 put_template 8 $color08 put_template 9 $color09 put_template 10 $color10 put_template 11 $color11 put_template 12 $color12 put_template 13 $color13 put_template 14 $color14 put_template 15 $color15 # 256 color space put_template 16 $color16 put_template 17 $color17 put_template 18 $color18 put_template 19 $color19 put_template 20 $color20 put_template 21 $color21 # foreground / background / cursor color if [ -n "$ITERM_SESSION_ID" ]; then # iTerm2 proprietary escape codes put_template_custom Pg 383838 # foreground put_template_custom Ph f8f8f8 # background put_template_custom Pi 383838 # bold color put_template_custom Pj d8d8d8 # selection color put_template_custom Pk 383838 # selected text color put_template_custom Pl 383838 # cursor put_template_custom Pm f8f8f8 # cursor text else put_template_var 10 $color_foreground if [ "$BASE16_SHELL_SET_BACKGROUND" != false ]; then put_template_var 11 $color_background if [ "${TERM%%-*}" = "rxvt" ]; then put_template_var 708 $color_background # internal border (rxvt) fi fi put_template_custom 12 ";7" # cursor (reverse video) fi # clean up unset -f put_template unset -f put_template_var unset -f put_template_custom unset color00 unset color01 unset color02 unset color03 unset color04 unset color05 unset color06 unset color07 unset color08 unset color09 unset color10 unset color11 unset color12 unset color13 unset color14 unset color15 unset color16 unset color17 unset color18 unset color19 unset color20 unset color21 unset color_foreground unset color_background
const crypto = require('crypto'); function encryptDataAes256(plainText, secretKey) { const iv = crypto.randomBytes(16); // Random initialization vector const salt = crypto.randomBytes(64); // Salt should be as large as possible const key = crypto.pbkdf2Sync(Buffer.from(secretKey), salt, 2145, 32, 'sha512'); // Key length should be 32 bytes const cipher = crypto.createCipheriv('aes-256-gcm', key, iv); let encrypted = cipher.update(Buffer.from(plainText)); encrypted = Buffer.concat([encrypted, cipher.final()]); const aad = Buffer.from('123456'); // Additional authentication data const tag = cipher.getAuthTag(); return Buffer.concat([salt, iv, tag, encrypted, aad]).toString('base64'); } let plainText = 'Hello World!'; let secretKey = '123456'; let encryptedData = encryptDataAes256(plainText, secretKey); console.log(encryptedData);
<reponame>gaunthan/design-patterns-by-golang<gh_stars>0 package observer import "fmt" func ExampleObserver() { weather := NewSubject() joe := NewObserver("joe") weather.attach(joe) tom := NewObserver("tom") weather.attach(tom) weather.notify("today is sunshiny") fmt.Println("---") weather.detach(joe) weather.notify("tomorrow is cloudy") fmt.Println("---") weather.detach(tom) weather.notify("oh my god") // Output: // joe: received "today is sunshiny" // tom: received "today is sunshiny" // --- // tom: received "tomorrow is cloudy" // --- // }
package cfg.cmd; import java.util.List; import cfg.serialize.FieldRangeType; import cfg.serialize.OutputDataFormat; import cfg.serialize.OutputType; import cfg.serialize.SerializeDataUtil; import cfg.serialize.exceptions.SheetDataException; import cfg.serialize.exceptions.SheetDefineException; import cfg.source.WorkbookInfo; import cfg.source.data.SheetInfo; /** * 数据生成命令 * * @author xuzhuoxi<br> * create on 2017年9月4日.<br> */ public class CmdDataHandler extends CmdHandlerBase { public CmdDataHandler(CmdArgsRuntime cmdArgs) { super(cmdArgs); } @Override protected void handleArgs() { super.handleArgs(); String[] dataOut = this.splitArg(CmdArgKeys.KEY_DATAOUT); for (int i = 0; i < dataOut.length; i++) { this.runtimeArgs.getDataFormats().add(OutputDataFormat.from(dataOut[i])); } } @Override protected boolean argsVerify() { if (!super.argsVerify()) { return false; } if (!this.runtimeArgs.hasOutputDataFormat()) { System.err.println("Params \"-DataOut\" is must."); return false; } return true; } @Override protected void doExecute() { String filePath = this.runtimeArgs.getSourcePath(); String targetFolder = this.runtimeArgs.getTargetPath(); List<OutputDataFormat> dataFormats = this.runtimeArgs.getDataFormats(); FieldRangeType fieldRangeType = this.runtimeArgs.getFieldRangeType(); WorkbookInfo info = new WorkbookInfo(filePath); try { info.loadSheetInfos(); } catch (SheetDefineException e1) { e1.printStackTrace(); System.exit(1); } List<SheetInfo> sheets = info.getSheetInfos(); try { for (OutputDataFormat dataFormat : dataFormats) { SerializeDataUtil.serializeData(sheets, dataFormat, fieldRangeType, targetFolder + "/data/" + fieldRangeType.getValue(), dataFormat.getFieldKey()); } } catch (SheetDataException e) { System.out.println("Data Format Error: " + e.getLoc()); e.printStackTrace(); System.exit(1); } } /** * @param args * -Source (非必要,可以直接在project.json中配置)<br> * 配置表文件路径,字符串,支持文件或文件夹<br> * * -Target (非必要,可以直接在project.json中配置)<br> * 输出文件夹路径,支持文件夹<br> * * -Field (必要)<br> * 配置字段选择输出数据,支持client,server,db<br> * * -DataOut (当OutType=data时)<br> * 输出数据,支持json,binary,sql,多个间用英文逗号(,)分隔 <br> */ public static void main(String[] args) { CmdArgsRuntime cmdArgsRuntime = CmdArgsRuntime.createArgsMap(args); cmdArgsRuntime.setOutType(OutputType.Data); // System.out.println("Handle Data Task:" + cmdArgsRuntime.toString()); new CmdDataHandler(cmdArgsRuntime).execute(); } }
<filename>tapestry-core/src/main/java/org/apache/tapestry5/internal/services/SaxTemplateParser.java // 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 org.apache.tapestry5.internal.services; import org.apache.tapestry5.internal.parser.*; import org.apache.tapestry5.ioc.Location; import org.apache.tapestry5.ioc.Resource; import org.apache.tapestry5.ioc.internal.util.CollectionFactory; import org.apache.tapestry5.ioc.internal.util.InternalUtils; import org.apache.tapestry5.ioc.internal.util.TapestryException; import org.apache.tapestry5.ioc.util.ExceptionUtils; import javax.xml.namespace.QName; import java.net.URL; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import static org.apache.tapestry5.internal.services.SaxTemplateParser.Version.*; /** * SAX-based template parser logic, taking a {@link Resource} to a Tapestry * template file and returning * a {@link ComponentTemplate}. * * Earlier versions of this code used the StAX (streaming XML parser), but that * was really, really bad for Google App Engine. This version uses SAX under the * covers, but kind of replicates the important bits of the StAX API as * {@link XMLTokenStream}. * * @since 5.2.0 */ @SuppressWarnings( {"JavaDoc"}) public class SaxTemplateParser { private static final String MIXINS_ATTRIBUTE_NAME = "mixins"; private static final String TYPE_ATTRIBUTE_NAME = "type"; private static final String ID_ATTRIBUTE_NAME = "id"; public static final String XML_NAMESPACE_URI = "http://www.w3.org/XML/1998/namespace"; private static final Map<String, Version> NAMESPACE_URI_TO_VERSION = CollectionFactory.newMap(); { NAMESPACE_URI_TO_VERSION.put("http://tapestry.apache.org/schema/tapestry_5_0_0.xsd", T_5_0); NAMESPACE_URI_TO_VERSION.put("http://tapestry.apache.org/schema/tapestry_5_1_0.xsd", T_5_1); // 5.2 didn't change the schmea, so the 5_1_0.xsd was still used. // 5.3 fixes an incorrect element name in the XSD ("replacement" should be "replace") // The parser code here always expected "replace". NAMESPACE_URI_TO_VERSION.put("http://tapestry.apache.org/schema/tapestry_5_3.xsd", T_5_3); // 5.4 is pretty much the same as 5.3, but allows block inside extend // as per TAP5-1847 NAMESPACE_URI_TO_VERSION.put("http://tapestry.apache.org/schema/tapestry_5_4.xsd", T_5_4); } /** * Special namespace used to denote Block parameters to components, as a * (preferred) alternative to the t:parameter * element. The simple element name is the name of the parameter. */ private static final String TAPESTRY_PARAMETERS_URI = "tapestry:parameter"; /** * URI prefix used to identify a Tapestry library, the remainder of the URI * becomes a prefix on the element name. */ private static final String LIB_NAMESPACE_URI_PREFIX = "tapestry-library:"; /** * Pattern used to parse the path portion of the library namespace URI. A * series of simple identifiers with slashes * allowed as seperators. */ private static final Pattern LIBRARY_PATH_PATTERN = Pattern.compile("^[a-z]\\w*(/[a-z]\\w*)*$", Pattern.CASE_INSENSITIVE); private static final Pattern ID_PATTERN = Pattern.compile("^[a-z]\\w*$", Pattern.CASE_INSENSITIVE); /** * Any amount of mixed simple whitespace (space, tab, form feed) mixed with * at least one carriage return or line * feed, followed by any amount of whitespace. Will be reduced to a single * linefeed. */ private static final Pattern REDUCE_LINEBREAKS_PATTERN = Pattern.compile( "[ \\t\\f]*[\\r\\n]\\s*", Pattern.MULTILINE); /** * Used when compressing whitespace, matches any sequence of simple * whitespace (space, tab, formfeed). Applied after * REDUCE_LINEBREAKS_PATTERN. */ private static final Pattern REDUCE_WHITESPACE_PATTERN = Pattern.compile("[ \\t\\f]+", Pattern.MULTILINE); // Note the use of the non-greedy modifier; this prevents the pattern from // merging multiple // expansions on the same text line into a single large // but invalid expansion. private static final Pattern EXPANSION_PATTERN = Pattern.compile("\\$\\{\\s*(((?!\\$\\{).)*)\\s*}"); private static final char EXPANSION_STRING_DELIMITTER = '\''; private static final char OPEN_BRACE = '{'; private static final char CLOSE_BRACE = '}'; private static final Set<String> MUST_BE_ROOT = CollectionFactory.newSet("extend", "container"); private final Resource resource; private final XMLTokenStream tokenStream; private final StringBuilder textBuffer = new StringBuilder(); private final List<TemplateToken> tokens = CollectionFactory.newList(); // This starts pointing at tokens but occasionally shifts to a list inside // the overrides Map. private List<TemplateToken> tokenAccumulator = tokens; /** * Primarily used as a set of componentIds (to check for duplicates and * conflicts). */ private final Map<String, Location> componentIds = CollectionFactory.newCaseInsensitiveMap(); /** * Map from override id to a list of tokens; this actually works both for * overrides defined by this template and * overrides provided by this template. */ private Map<String, List<TemplateToken>> overrides; private boolean extension; private Location textStartLocation; private boolean active = true; private boolean strictMixinParameters = false; private final Map<String, Boolean> extensionPointIdSet = CollectionFactory.newCaseInsensitiveMap(); public SaxTemplateParser(Resource resource, Map<String, URL> publicIdToURL) { this.resource = resource; this.tokenStream = new XMLTokenStream(resource, publicIdToURL); } public ComponentTemplate parse(boolean compressWhitespace) { try { tokenStream.parse(); TemplateParserState initialParserState = new TemplateParserState() .compressWhitespace(compressWhitespace); root(initialParserState); return new ComponentTemplateImpl(resource, tokens, componentIds, extension, strictMixinParameters, overrides); } catch (Exception ex) { throw new TapestryException(String.format("Failure parsing template %s: %s", resource, ExceptionUtils.toMessage(ex)), tokenStream.getLocation(), ex); } } void root(TemplateParserState state) { while (active && tokenStream.hasNext()) { switch (tokenStream.next()) { case DTD: dtd(); break; case START_ELEMENT: rootElement(state); break; case END_DOCUMENT: // Ignore it. break; default: textContent(state); } } } private void rootElement(TemplateParserState initialState) { TemplateParserState state = setupForElement(initialState); String uri = tokenStream.getNamespaceURI(); String name = tokenStream.getLocalName(); Version version = NAMESPACE_URI_TO_VERSION.get(uri); if (T_5_1.sameOrEarlier(version)) { if (name.equalsIgnoreCase("extend")) { extend(state); return; } } if (version != null) { if (name.equalsIgnoreCase("container")) { container(state); return; } } element(state); } private void extend(TemplateParserState state) { extension = true; while (active) { switch (tokenStream.next()) { case START_ELEMENT: if (isTemplateVersion(Version.T_5_1) && isElementName("replace")) { replace(state); break; } boolean is54 = isTemplateVersion(Version.T_5_4); if (is54 && isElementName("block")) { block(state); break; } throw new RuntimeException( is54 ? "Child element of <extend> must be <replace> or <block>." : "Child element of <extend> must be <replace>."); case END_ELEMENT: return; // Ignore spaces and comments directly inside <extend>. case COMMENT: case SPACE: break; // Other non-whitespace content (characters, etc.) are forbidden. case CHARACTERS: if (InternalUtils.isBlank(tokenStream.getText())) break; default: unexpectedEventType(); } } } /** * Returns true if the <em>local name</em> is the element name (ignoring case). */ private boolean isElementName(String elementName) { return tokenStream.getLocalName().equalsIgnoreCase(elementName); } /** * Returns true if the template version is at least the required version. */ private boolean isTemplateVersion(Version requiredVersion) { Version templateVersion = NAMESPACE_URI_TO_VERSION.get(tokenStream.getNamespaceURI()); return requiredVersion.sameOrEarlier(templateVersion); } private void replace(TemplateParserState state) { String id = getRequiredIdAttribute(); addContentToOverride(setupForElement(state), id); } private void unexpectedEventType() { XMLTokenType eventType = tokenStream.getEventType(); throw new IllegalStateException(String.format("Unexpected XML parse event %s.", eventType .name())); } private void dtd() { DTDData dtdInfo = tokenStream.getDTDInfo(); tokenAccumulator.add(new DTDToken(dtdInfo.rootName, dtdInfo.publicId, dtdInfo .systemId, getLocation())); } private Location getLocation() { return tokenStream.getLocation(); } /** * Processes an element through to its matching end tag. * * An element can be: * * a Tapestry component via &lt;t:type&gt; * * a Tapestry component via t:type="type" and/or t:id="id" * * a Tapestry component via a library namespace * * A parameter element via &lt;t:parameter&gt; * * A parameter element via &lt;p:name&gt; * * A &lt;t:remove&gt; element (in the 5.1 schema) * * A &lt;t:content&gt; element (in the 5.1 schema) * * A &lt;t:block&gt; element * * The body &lt;t:body&gt; * * An ordinary element */ void element(TemplateParserState initialState) { TemplateParserState state = setupForElement(initialState); String uri = tokenStream.getNamespaceURI(); String name = tokenStream.getLocalName(); Version version = NAMESPACE_URI_TO_VERSION.get(uri); if (T_5_1.sameOrEarlier(version)) { if (name.equalsIgnoreCase("remove")) { removeContent(); return; } if (name.equalsIgnoreCase("content")) { limitContent(state); return; } if (name.equalsIgnoreCase("extension-point")) { extensionPoint(state); return; } if (name.equalsIgnoreCase("replace")) { throw new RuntimeException( "The <replace> element may only appear directly within an extend element."); } if (MUST_BE_ROOT.contains(name)) mustBeRoot(name); } if (version != null) { if (name.equalsIgnoreCase("body")) { body(); return; } if (name.equalsIgnoreCase("container")) { mustBeRoot(name); } if (name.equalsIgnoreCase("block")) { block(state); return; } if (name.equalsIgnoreCase("parameter")) { if (T_5_3.sameOrEarlier(version)) { throw new RuntimeException( String.format("The <parameter> element has been deprecated in Tapestry 5.3 in favour of '%s' namespace.", TAPESTRY_PARAMETERS_URI)); } classicParameter(state); return; } possibleTapestryComponent(state, null, tokenStream.getLocalName().replace('.', '/')); return; } if (uri != null && uri.startsWith(LIB_NAMESPACE_URI_PREFIX)) { libraryNamespaceComponent(state); return; } if (TAPESTRY_PARAMETERS_URI.equals(uri)) { parameterElement(state); return; } // Just an ordinary element ... unless it has t:id or t:type possibleTapestryComponent(state, tokenStream.getLocalName(), null); } /** * Processes a body of an element including text and (recursively) nested * elements. Adds an * {@link org.apache.tapestry5.internal.parser.TokenType#END_ELEMENT} token * before returning. * * @param state */ private void processBody(TemplateParserState state) { while (active) { switch (tokenStream.next()) { case START_ELEMENT: // The recursive part: when we see a new element start. element(state); break; case END_ELEMENT: // At the end of an element, we're done and can return. // This is the matching end element for the start element // that invoked this method. endElement(state); return; default: textContent(state); } } } private TemplateParserState setupForElement(TemplateParserState initialState) { processTextBuffer(initialState); return checkForXMLSpaceAttribute(initialState); } /** * Handles an extension point, putting a RenderExtension token in position * in the template. * * @param state */ private void extensionPoint(TemplateParserState state) { // An extension point adds a token that represents where the override // (either the default // provided in the parent template, or the true override from a child // template) is positioned. String id = getRequiredIdAttribute(); if (extensionPointIdSet.containsKey(id)) { throw new TapestryException(String.format("Extension point '%s' is already defined for this template. Extension point ids must be unique.", id), getLocation(), null); } else { extensionPointIdSet.put(id, true); } tokenAccumulator.add(new ExtensionPointToken(id, getLocation())); addContentToOverride(state.insideComponent(false), id); } private String getRequiredIdAttribute() { String id = getSingleParameter("id"); if (InternalUtils.isBlank(id)) throw new RuntimeException(String.format("The <%s> element must have an id attribute.", tokenStream.getLocalName())); return id; } private void addContentToOverride(TemplateParserState state, String id) { List<TemplateToken> savedTokenAccumulator = tokenAccumulator; tokenAccumulator = CollectionFactory.newList(); // TODO: id should probably be unique; i.e., you either define an // override or you // provide an override, but you don't do both in the same template. if (overrides == null) overrides = CollectionFactory.newCaseInsensitiveMap(); overrides.put(id, tokenAccumulator); while (active) { switch (tokenStream.next()) { case START_ELEMENT: element(state); break; case END_ELEMENT: processTextBuffer(state); // Restore everthing to how it was before the // extention-point was reached. tokenAccumulator = savedTokenAccumulator; return; default: textContent(state); } } } private void mustBeRoot(String name) { throw new RuntimeException(String.format( "Element <%s> is only valid as the root element of a template.", name)); } /** * Triggered by &lt;t:content&gt; element; limits template content to just * what's inside. */ private void limitContent(TemplateParserState state) { if (state.isCollectingContent()) throw new IllegalStateException( "The <content> element may not be nested within another <content> element."); TemplateParserState newState = state.collectingContent().insideComponent(false); // Clear out any tokens that precede the <t:content> element tokens.clear(); // I'm not happy about this; you really shouldn't define overrides just // to clear them out, // but it is consistent. Perhaps this should be an error if overrides is // non-empty. overrides = null; // Make sure that if the <t:content> appears inside a <t:replace> or // <t:extension-point>, that // it is still handled correctly. tokenAccumulator = tokens; while (active) { switch (tokenStream.next()) { case START_ELEMENT: element(newState); break; case END_ELEMENT: // The active flag is global, once we hit it, the entire // parse is aborted, leaving // tokens with just tokens defined inside <t:content>. processTextBuffer(newState); active = false; break; default: textContent(state); } } } private void removeContent() { int depth = 1; while (active) { switch (tokenStream.next()) { case START_ELEMENT: depth++; break; // The matching end element. case END_ELEMENT: depth--; if (depth == 0) return; break; default: // Ignore anything else (text, comments, etc.) } } } private String nullForBlank(String input) { return InternalUtils.isBlank(input) ? null : input; } /** * Added in release 5.1. */ private void libraryNamespaceComponent(TemplateParserState state) { String uri = tokenStream.getNamespaceURI(); // The library path is encoded into the namespace URI. String path = uri.substring(LIB_NAMESPACE_URI_PREFIX.length()); if (!LIBRARY_PATH_PATTERN.matcher(path).matches()) throw new RuntimeException(String.format("The path portion of library namespace URI '%s' is not valid: it must be a simple identifier, or a series of identifiers seperated by slashes.", uri)); possibleTapestryComponent(state, null, path + "/" + tokenStream.getLocalName()); } /** * @param elementName * @param identifiedType * the type of the element, usually null, but may be the * component type derived from element */ private void possibleTapestryComponent(TemplateParserState state, String elementName, String identifiedType) { String id = null; String type = identifiedType; String mixins = null; int count = tokenStream.getAttributeCount(); Location location = getLocation(); List<TemplateToken> attributeTokens = CollectionFactory.newList(); for (int i = 0; i < count; i++) { QName qname = tokenStream.getAttributeName(i); if (isXMLSpaceAttribute(qname)) continue; // The name will be blank for an xmlns: attribute String localName = qname.getLocalPart(); if (InternalUtils.isBlank(localName)) continue; String uri = qname.getNamespaceURI(); String value = tokenStream.getAttributeValue(i); Version version = NAMESPACE_URI_TO_VERSION.get(uri); if (version != null) { // We are kind of assuming that the namespace URI appears once, in the outermost element of the template. // And we don't and can't handle the case that it appears multiple times in the template. if (T_5_4.sameOrEarlier(version)) { strictMixinParameters = true; } if (localName.equalsIgnoreCase(ID_ATTRIBUTE_NAME)) { id = nullForBlank(value); validateId(id, "Component id '%s' is not valid; component ids must be valid Java identifiers: start with a letter, and consist of letters, numbers and underscores."); continue; } if (type == null && localName.equalsIgnoreCase(TYPE_ATTRIBUTE_NAME)) { type = nullForBlank(value); continue; } if (localName.equalsIgnoreCase(MIXINS_ATTRIBUTE_NAME)) { mixins = nullForBlank(value); continue; } // Anything else is the name of a Tapestry component parameter // that is simply // not part of the template's doctype for the element being // instrumented. } attributeTokens.add(new AttributeToken(uri, localName, value, location)); } boolean isComponent = (id != null || type != null); // If provided t:mixins but not t:id or t:type, then its not quite a // component if (mixins != null && !isComponent) throw new TapestryException(String.format("You may not specify mixins for element <%s> because it does not represent a component (which requires either an id attribute or a type attribute).", elementName), location, null); if (isComponent) { tokenAccumulator.add(new StartComponentToken(elementName, id, type, mixins, location)); } else { tokenAccumulator.add(new StartElementToken(tokenStream.getNamespaceURI(), elementName, location)); } addDefineNamespaceTokens(); tokenAccumulator.addAll(attributeTokens); if (id != null) componentIds.put(id, location); processBody(state.insideComponent(isComponent)); } private void addDefineNamespaceTokens() { for (int i = 0; i < tokenStream.getNamespaceCount(); i++) { String uri = tokenStream.getNamespaceURI(i); // These URIs are strictly part of the server-side Tapestry template // and are not ever sent to the client. if (NAMESPACE_URI_TO_VERSION.containsKey(uri)) continue; if (uri.equals(TAPESTRY_PARAMETERS_URI)) continue; if (uri.startsWith(LIB_NAMESPACE_URI_PREFIX)) continue; tokenAccumulator.add(new DefineNamespacePrefixToken(uri, tokenStream .getNamespacePrefix(i), getLocation())); } } private TemplateParserState checkForXMLSpaceAttribute(TemplateParserState state) { for (int i = 0; i < tokenStream.getAttributeCount(); i++) { QName qName = tokenStream.getAttributeName(i); if (isXMLSpaceAttribute(qName)) { boolean compress = !"preserve".equals(tokenStream.getAttributeValue(i)); return state.compressWhitespace(compress); } } return state; } /** * Processes the text buffer and then adds an end element token. */ private void endElement(TemplateParserState state) { processTextBuffer(state); tokenAccumulator.add(new EndElementToken(getLocation())); } /** * Handler for Tapestry 5.0's "classic" &lt;t:parameter&gt; element. This * turns into a {@link org.apache.tapestry5.internal.parser.ParameterToken} * and the body and end element are provided normally. */ private void classicParameter(TemplateParserState state) { String parameterName = getSingleParameter("name"); if (InternalUtils.isBlank(parameterName)) throw new TapestryException("The name attribute of the <parameter> element must be specified.", getLocation(), null); ensureParameterWithinComponent(state); tokenAccumulator.add(new ParameterToken(parameterName, getLocation())); processBody(state.insideComponent(false)); } private void ensureParameterWithinComponent(TemplateParserState state) { if (!state.isInsideComponent()) throw new RuntimeException( "Block parameters are only allowed directly within component elements."); } /** * Tapestry 5.1 uses a special namespace (usually mapped to "p:") and the * name becomes the parameter element. */ private void parameterElement(TemplateParserState state) { ensureParameterWithinComponent(state); if (tokenStream.getAttributeCount() > 0) throw new TapestryException("A block parameter element does not allow any additional attributes. The element name defines the parameter name.", getLocation(), null); tokenAccumulator.add(new ParameterToken(tokenStream.getLocalName(), getLocation())); processBody(state.insideComponent(false)); } /** * Checks that a body element is empty. Returns after the body's close * element. Adds a single body token (but not an * end token). */ private void body() { tokenAccumulator.add(new BodyToken(getLocation())); while (active) { switch (tokenStream.next()) { case END_ELEMENT: return; default: throw new IllegalStateException(String.format("Content inside a Tapestry body element is not allowed (at %s). The content has been ignored.", getLocation())); } } } /** * Driven by the &lt;t:container&gt; element, this state adds elements for * its body but not its start or end tags. * * @param state */ private void container(TemplateParserState state) { while (active) { switch (tokenStream.next()) { case START_ELEMENT: element(state); break; // The matching end-element for the container. Don't add a // token. case END_ELEMENT: processTextBuffer(state); return; default: textContent(state); } } } /** * A block adds a token for its start tag and end tag and allows any content * within. */ private void block(TemplateParserState state) { String blockId = getSingleParameter("id"); validateId(blockId, "Block id '%s' is not valid; block ids must be valid Java identifiers: start with a letter, and consist of letters, numbers and underscores."); tokenAccumulator.add(new BlockToken(blockId, getLocation())); processBody(state.insideComponent(false)); } private String getSingleParameter(String attributeName) { String result = null; for (int i = 0; i < tokenStream.getAttributeCount(); i++) { QName qName = tokenStream.getAttributeName(i); if (isXMLSpaceAttribute(qName)) continue; if (qName.getLocalPart().equalsIgnoreCase(attributeName)) { result = tokenStream.getAttributeValue(i); continue; } // Only the named attribute is allowed. throw new TapestryException(String.format("Element <%s> does not support an attribute named '%s'. The only allowed attribute name is '%s'.", tokenStream .getLocalName(), qName.toString(), attributeName), getLocation(), null); } return result; } private void validateId(String id, String messageKey) { if (id == null) return; if (ID_PATTERN.matcher(id).matches()) return; // Not a match. throw new TapestryException(String.format(messageKey, id), getLocation(), null); } private boolean isXMLSpaceAttribute(QName qName) { return XML_NAMESPACE_URI.equals(qName.getNamespaceURI()) && "space".equals(qName.getLocalPart()); } /** * Processes text content if in the correct state, or throws an exception. * This is used as a default for matching * case statements. * * @param state */ private void textContent(TemplateParserState state) { switch (tokenStream.getEventType()) { case COMMENT: comment(state); break; case CDATA: cdata(state); break; case CHARACTERS: case SPACE: characters(); break; default: unexpectedEventType(); } } private void characters() { if (textStartLocation == null) textStartLocation = getLocation(); textBuffer.append(tokenStream.getText()); } private void cdata(TemplateParserState state) { processTextBuffer(state); tokenAccumulator.add(new CDATAToken(tokenStream.getText(), getLocation())); } private void comment(TemplateParserState state) { processTextBuffer(state); String comment = tokenStream.getText(); tokenAccumulator.add(new CommentToken(comment, getLocation())); } /** * Processes the accumulated text in the text buffer as a text token. */ private void processTextBuffer(TemplateParserState state) { if (textBuffer.length() != 0) convertTextBufferToTokens(state); textStartLocation = null; } private void convertTextBufferToTokens(TemplateParserState state) { String text = textBuffer.toString(); textBuffer.setLength(0); if (state.isCompressWhitespace()) { text = compressWhitespaceInText(text); if (InternalUtils.isBlank(text)) return; } addTokensForText(text); } /** * Reduces vertical whitespace to a single newline, then reduces horizontal * whitespace to a single space. * * @param text * @return compressed version of text */ private String compressWhitespaceInText(String text) { String linebreaksReduced = REDUCE_LINEBREAKS_PATTERN.matcher(text).replaceAll("\n"); return REDUCE_WHITESPACE_PATTERN.matcher(linebreaksReduced).replaceAll(" "); } /** * Scans the text, using a regular expression pattern, for expansion * patterns, and adds appropriate tokens for what * it finds. * * @param text * to add as * {@link org.apache.tapestry5.internal.parser.TextToken}s and * {@link org.apache.tapestry5.internal.parser.ExpansionToken}s */ private void addTokensForText(String text) { Matcher matcher = EXPANSION_PATTERN.matcher(text); int startx = 0; // The big problem with all this code is that everything gets assigned // to the // start of the text block, even if there are line breaks leading up to // it. // That's going to take a lot more work and there are bigger fish to // fry. In addition, // TAPESTRY-2028 means that the whitespace has likely been stripped out // of the text // already anyway. while (matcher.find()) { int matchStart = matcher.start(); if (matchStart != startx) { String prefix = text.substring(startx, matchStart); tokenAccumulator.add(new TextToken(prefix, textStartLocation)); } // Group 1 includes the real text of the expansion, with whitespace // around the // expression (but inside the curly braces) excluded. // But note that we run into a problem. The original // EXPANSION_PATTERN used a reluctant quantifier to match the // smallest instance of ${} possible. But if you have ${'}'} or // ${{'key': 'value'}} (maps, cf TAP5-1605) then you run into issues // b/c the expansion becomes {'key': 'value' which is wrong. // A fix to use greedy matching with negative lookahead to prevent // ${...}...${...} all matching a single expansion is close, but // has issues when an expansion is used inside a javascript function // (see TAP5-1620). The solution is to use the greedy // EXPANSION_PATTERN as before to bound the search for a single // expansion, then check for {} consistency, ignoring opening and // closing braces that occur within '' (the property expression // language doesn't support "" for strings). That should include: // 'This string has a } in it' and 'This string has a { in it.' // Note also that the property expression language doesn't support // escaping the string character ('), so we don't have to worry // about that. String expression = matcher.group(1); //count of 'open' braces. Expression ends when it hits 0. In most cases, // it should end up as 1 b/c "expression" is everything inside ${}, so // the following will typically not find the end of the expression. int openBraceCount = 1; int expressionEnd = expression.length(); boolean inQuote = false; for (int i = 0; i < expression.length(); i++) { char c = expression.charAt(i); //basically, if we're inQuote, we ignore everything until we hit the quote end, so we only care if the character matches the quote start (meaning we're at the end of the quote). //note that I don't believe expression support escaped quotes... if (c == EXPANSION_STRING_DELIMITTER) { inQuote = !inQuote; continue; } else if (inQuote) { continue; } else if (c == CLOSE_BRACE) { openBraceCount--; if (openBraceCount == 0) { expressionEnd = i; break; } } else if (c == OPEN_BRACE) { openBraceCount++; } } if (expressionEnd < expression.length()) { //then we gobbled up some } that we shouldn't have... like the closing } of a javascript //function. tokenAccumulator.add(new ExpansionToken(expression.substring(0, expressionEnd), textStartLocation)); //can't just assign to startx = matcher.start(1) + expressionEnd + 1; } else { tokenAccumulator.add(new ExpansionToken(expression.trim(), textStartLocation)); startx = matcher.end(); } } // Catch anything after the final regexp match. if (startx < text.length()) tokenAccumulator.add(new TextToken(text.substring(startx, text.length()), textStartLocation)); } static enum Version { T_5_0(5, 0), T_5_1(5, 1), T_5_3(5, 3), T_5_4(5, 4); private int major; private int minor; private Version(int major, int minor) { this.major = major; this.minor = minor; } /** * Returns true if this Version is the same as, or ordered before the other Version. This is often used to enable new * template features for a specific version. */ public boolean sameOrEarlier(Version other) { if (other == null) return false; if (this == other) return true; return major <= other.major && minor <= other.minor; } } }
class WelcomesController < ApplicationController def index @welcomes = Welcome.all end def new @welcome = Welcome.new end def create @welcome =Welcome.new(welcome_params) if @welcome.save flash[:notice] = "saved successfully" redirect_to welcomes_path else flash[:error] = @welcome.errors.full_messages.to_sentence render "new" end end def edit @welcome = Welcome.some_method(params[:id]) end def update @welcome = Welcome.some_method(params[:id]) if @welcome.update_attributes(welcome_params) flash[:notice] = "Updated successfully" redirect_to welcomes_path else flash[:error] = "editpage error" render "new" end end def delete @welcomes = Welcome.all @welcome = Welcome.find(params[:id]) if @welcome.destroy flash[:notice] = "delete successfully" render "index" else flash[:error] = "not delete" render "index" end end private def welcome_params params.require(:welcome).permit(:name, :password) end end
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package gov.nasa.jpl.memex.nutch.protocol.selenium.handlers.login; import org.apache.nutch.protocol.interactiveselenium.InteractiveSeleniumHandler; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.By; public class LoginHandler32 implements InteractiveSeleniumHandler { public void processDriver(WebDriver driver) { String OriginalURL = driver.getCurrentUrl(); driver.get(OriginalURL); //Find the login button and click on it WebElement LoginButton = driver.findElement(By.linkText("Login")); LoginButton.click(); //Find the username textbox using the name of the textbox - which is typically "Username" WebElement useremail = driver.findElement(By.linkText("Username")); //if username is not found try finding an element with "email" if (null == useremail) { useremail = driver.findElement(By.linkText("email")); } useremail.clear(); useremail.sendKeys("<EMAIL>"); WebElement password = driver.findElement(By.linkText("Password")); password.clear(); password.sendKeys("<PASSWORD>"); WebElement submitButton = driver.findElement(By.linkText("submit")); submitButton.click(); } public boolean shouldProcessURL(String URL) { return true; } }
for i in range(1, 21): if i % 2 == 0: print(i)
using System; namespace RandomNumberGenerator { class Program { static void Main(string[]args) { Random random = new Random(); int lower = 0; int upper = 10; for (int i = 0; i < 10; i++) { Console.WriteLine(random.Next(lower, upper)); } } } }
#!/bin/bash # # Copyright 2019 The Bazel Authors. 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. # # --- begin runfiles.bash initialization --- set -euo pipefail if [[ ! -d "${RUNFILES_DIR:-/dev/null}" && ! -f "${RUNFILES_MANIFEST_FILE:-/dev/null}" ]]; then if [[ -f "$0.runfiles_manifest" ]]; then export RUNFILES_MANIFEST_FILE="$0.runfiles_manifest" elif [[ -f "$0.runfiles/MANIFEST" ]]; then export RUNFILES_MANIFEST_FILE="$0.runfiles/MANIFEST" elif [[ -f "$0.runfiles/bazel_tools/tools/bash/runfiles/runfiles.bash" ]]; then export RUNFILES_DIR="$0.runfiles" fi fi if [[ -f "${RUNFILES_DIR:-/dev/null}/bazel_tools/tools/bash/runfiles/runfiles.bash" ]]; then source "${RUNFILES_DIR}/bazel_tools/tools/bash/runfiles/runfiles.bash" elif [[ -f "${RUNFILES_MANIFEST_FILE:-/dev/null}" ]]; then source "$(grep -m1 "^bazel_tools/tools/bash/runfiles/runfiles.bash " \ "$RUNFILES_MANIFEST_FILE" | cut -d ' ' -f 2-)" else echo >&2 "ERROR: cannot find @bazel_tools//tools/bash/runfiles:runfiles.bash" exit 1 fi # --- end runfiles.bash initialization --- source "$(rlocation "io_bazel/src/test/shell/integration_test_setup.sh")" \ || { echo "integration_test_setup.sh not found!" >&2; exit 1; } case "$(uname -s | tr [:upper:] [:lower:])" in msys*|mingw*|cygwin*) declare -r is_windows=true ;; *) declare -r is_windows=false ;; esac if "$is_windows"; then export MSYS_NO_PATHCONV=1 export MSYS2_ARG_CONV_EXCL="*" declare -r EXE_EXT=".exe" else declare -r EXE_EXT="" fi # Tests in this file do not actually start a Python interpreter, but plug in a # fake stub executable to serve as the "interpreter". use_fake_python_runtimes_for_testsuite #### TESTS ############################################################# # Tests that Python 2 or Python 3 is actually invoked, with and without flag # overrides. function test_python_version() { mkdir -p test touch test/main2.py test/main3.py cat > test/BUILD << EOF py_binary(name = "main2", default_python_version = "PY2", srcs = ['main2.py'], ) py_binary(name = "main3", default_python_version = "PY3", srcs = ["main3.py"], ) EOF # No flag, use the default from the rule. bazel run //test:main2 \ &> $TEST_log || fail "bazel run failed" expect_log "I am Python 2" bazel run //test:main3 \ &> $TEST_log || fail "bazel run failed" expect_log "I am Python 3" # These assertions try to override the version, which is legacy semantics. FLAG=--incompatible_allow_python_version_transitions=false # Force to Python 2. bazel run //test:main2 $FLAG --force_python=PY2 \ &> $TEST_log || fail "bazel run failed" expect_log "I am Python 2" bazel run //test:main3 $FLAG --force_python=PY2 \ &> $TEST_log || fail "bazel run failed" expect_log "I am Python 2" # Force to Python 3. bazel run //test:main2 $FLAG --force_python=PY3 \ &> $TEST_log || fail "bazel run failed" expect_log "I am Python 3" bazel run //test:main3 $FLAG --force_python=PY3 \ &> $TEST_log || fail "bazel run failed" expect_log "I am Python 3" } function test_can_build_py_library_at_top_level_regardless_of_version() { mkdir -p test cat > test/BUILD << EOF py_library( name = "lib2", srcs = ["lib2.py"], srcs_version = "PY2ONLY", ) py_library( name = "lib3", srcs = ["lib3.py"], srcs_version = "PY3ONLY", ) EOF touch test/lib2.py test/lib3.py EXPFLAG="--incompatible_allow_python_version_transitions=true" bazel build --python_version=PY2 $EXPFLAG //test:* \ &> $TEST_log || fail "bazel build failed" bazel build --python_version=PY3 $EXPFLAG //test:* \ &> $TEST_log || fail "bazel build failed" } run_suite "Tests for the Python rules without Python execution"
public class CustomerController : Controller { private readonly CustomerContext _context; public CustomerController(CustomerContext context) { _context = context; } [HttpGet] public async Task<ActionResult<IEnumerable<Customer>>> GetCustomerDetails() { return await _context.Customers.ToListAsync(); } }
static app -a 0.0.0.0 -H "{\"Cache-Control\": \"no-cache, must-revalidate\"}"
<reponame>RenukaGurumurthy/Gooru-Core-API<gh_stars>0 ///////////////////////////////////////////////////////////// // ResourceProcessor.java // gooru-api // Created by Gooru on 2014 // Copyright (c) 2014 Gooru. All rights reserved. // http://www.goorulearning.org/ // 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. ///////////////////////////////////////////////////////////// package org.ednovo.gooru.application.util; import java.io.File; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.Date; import org.ednovo.gooru.core.api.model.Code; import org.ednovo.gooru.core.api.model.Resource; import org.ednovo.gooru.core.api.model.ResourceInfo; import org.ednovo.gooru.core.api.model.ResourceType; import org.ednovo.gooru.core.constant.ParameterProperties; import org.ednovo.gooru.domain.service.TransactionBox; import org.ednovo.gooru.domain.service.redis.RedisService; import org.ednovo.gooru.domain.service.resource.ResourceService; import org.ednovo.gooru.domain.service.setting.SettingService; import org.ednovo.gooru.domain.service.storage.S3ResourceApiHandler; import org.ednovo.gooru.infrastructure.messenger.IndexHandler; import org.ednovo.gooru.infrastructure.messenger.IndexProcessor; import org.ednovo.gooru.infrastructure.persistence.hibernate.resource.ResourceRepository; import org.ednovo.gooru.infrastructure.persistence.hibernate.taxonomy.TaxonomyRespository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import com.sun.pdfview.PDFFile; public class ResourceProcessor implements ParameterProperties { @Autowired private ResourceRepository resourceRepository; @Autowired private ResourceService resourceService; @Autowired private RedisService redisService; @Autowired private TaxonomyRespository taxonomyRespository; @Autowired private S3ResourceApiHandler s3ResourceApiHandler; @Autowired private IndexProcessor indexProcessor; @Autowired private GooruImageUtil gooruImageUtil; @Autowired private SettingService settingService; @Autowired private IndexHandler indexHandler; private final Logger logger = LoggerFactory.getLogger(ResourceProcessor.class); public void updateWebResources(final Long contentId, final Integer status) { new TransactionBox() { @Override public void execute() { logger.info("Updating Resource: " + contentId + " status : " + status); resourceRepository.updateWebResource(contentId, status); } }; } public void generateResourceThumbnail(final String resourceGooruOid) throws Exception { new TransactionBox() { @Override public void execute() { try { logger.info("Updating Resource: " + resourceGooruOid); Resource resource = resourceRepository.findResourceByContentGooruId(resourceGooruOid); s3ResourceApiHandler.uploadResourceFolder(resource); } catch (Exception ex) { logger.error("Error while generating thumbnail ", ex); s3ResourceApiHandler.uploadResourceThumbnailWithNewSession(resourceGooruOid); } } }; } public void updateCodeToS3WithNewSession(final String codeUId, final String fileName) throws Exception { new TransactionBox() { @Override public void execute() { try { Code code = taxonomyRespository.findCodeByCodeUId(codeUId); if (fileName == null) { s3ResourceApiHandler.uploadCodeFolder(code); } else { // FIXME /* * s3ResourceApiHandler.uploadResourceFile(resourceGooruOid * , fileName); */ } } catch (Exception ex) { logger.error("Error while uploading To S3 ", ex); if (fileName == null) { s3ResourceApiHandler.uploadCodeFolderWithNewSession(codeUId); } else { // FIXME /* * s3ResourceApiHandler.uploadResourceFile(resourceGooruOid * , fileName); */ } } } }; } public void updateResourceToS3WithNewSession(String resourceGooruOid) throws Exception { updateResourceToS3WithNewSession(resourceGooruOid, null); } public void updateResourceToS3WithNewSession(final String resourceGooruOid, final String fileName) throws Exception { new TransactionBox() { @Override public void execute() { try { Resource resource = resourceRepository.findResourceByContentGooruId(resourceGooruOid); if (resource.getResourceType().getName().equals(ResourceType.Type.CLASSPLAN.getType())) { final String cacheKey = "collection-" + resourceGooruOid; getRedisService().deleteKey(cacheKey); } if (fileName == null) { s3ResourceApiHandler.uploadResourceFolder(resource); } else { // FIXME s3ResourceApiHandler.uploadResourceFile(resourceGooruOid, fileName); } indexHandler.setReIndexRequest(resource.getGooruOid(), IndexProcessor.INDEX, getSearchResourceType(resource), null, false, false); } catch (Exception ex) { logger.error("Error while uploading To S3 ", ex); if (fileName == null) { s3ResourceApiHandler.uploadResourceFolderWithNewSession(resourceGooruOid); } else { // FIXME /* * s3ResourceApiHandler.uploadResourceFile(resourceGooruOid * , fileName); */ } } } }; } public String getSearchResourceType(Resource resource) { String typeName = resource.getResourceType().getName(); if (typeName.equals(ResourceType.Type.CLASSPLAN.getType())) { return COLLECTION; } else if (typeName.equals(ResourceType.Type.ASSESSMENT_QUIZ.getType())) { return QUIZ; } else if (typeName.equals(ResourceType.Type.ASSESSMENT_QUESTION.getType())) { return QUESTION; } else if (typeName.equals(ResourceType.Type.QB_QUESTION.getType())) { return QB_QUESTION; } else { return RESOURCE; } } public void postPdfUpdate(final String resourceGooruOid) throws Exception { new TransactionBox() { @Override public void execute() { try { logger.info("Updating Resource: " + resourceGooruOid); Resource resource = resourceRepository.findResourceByContentGooruId(resourceGooruOid); String repoPath = resource.getOrganization().getNfsStorageArea().getInternalPath() + resource.getFolder(); /* * getGooruImageUtil().scaleImage(repoPath + * resource.getThumbnail(), repoPath, null, * ResourceImageUtil.RESOURCE_THUMBNAIL_SIZES); */ ResourceInfo resourceInfo = resourceRepository.findResourceInfo(resource.getGooruOid()); if (resourceInfo == null) { resourceInfo = new ResourceInfo(); resourceInfo.setResource(resource); } resourceInfo.setLastUpdated(new Date()); RandomAccessFile raf = new RandomAccessFile(new File(repoPath + resource.getUrl()), "r"); FileChannel channel = raf.getChannel(); ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size()); PDFFile pdffile = new PDFFile(buf); resourceInfo.setNumOfPages(pdffile.getNumPages()); resourceRepository.save(resourceInfo); resource.setResourceInfo(resourceInfo); resourceRepository.save(resource); s3ResourceApiHandler.uploadResourceFolder(resource); } catch (Exception ex) { logger.error("Error while generating thumbnail ", ex); s3ResourceApiHandler.uploadResourceFolderWithNewSession(resourceGooruOid); } } }; } public GooruImageUtil getGooruImageUtil() { return gooruImageUtil; } public void updateResourceThumbnail(String thumbnail, String resourceGooruOid) { Resource resource = resourceRepository.findResourceByContentGooruId(resourceGooruOid); resource.setThumbnail(thumbnail); resourceRepository.save(resource); } public RedisService getRedisService() { return redisService; } }
<gh_stars>0 module ImazenLicensing class V2IdLicenseText < V2LicenseText def self.supported_kinds ['id'] end def validate super # validates Owner and Id field require_values :kind, ['id'] require_values :is_public, ['false'] require_lowercase_alphanumeric(:id, 8) require_lowercase_alphanumeric(:secret, 32) require_fields [:issued, :network_grace_minutes] require_values :must_be_fetched, [nil, 'false'] unless @data[:must_be_fetched].nil? || @data[:must_be_fetched] == "false" raise "If present, field must_be_fetched must equal 'false' on an 'id' license" end unless @data[:network_grace_minutes].to_i > 2 raise "The :network_grace_minutes value must exceed 2 minutes" end # LicenseServers (optional) end end end
<reponame>1aurabrown/ervell<filename>react/components/ChannelMetadata/components/ChannelBreadcrumb/index.js import React, { Component } from 'react'; import { propType } from 'graphql-anywhere'; import styled from 'styled-components'; import channelBreadcrumbFragment from 'react/components/ChannelMetadata/components/ChannelBreadcrumb/fragments/channelBreadcrumb'; import { truncate } from 'react/components/UI/Truncate'; import ColoredChannelLink from 'react/components/UI/ColoredChannelLink'; import StickyBreadcrumbPath from 'react/components/UI/StickyBreadcrumbPath'; const CollaboratorCount = styled.span` font-weight: normal; `; export default class ChannelBreadcrumb extends Component { static propTypes = { channel: propType(channelBreadcrumbFragment).isRequired, } render() { const { channel } = this.props; return ( <StickyBreadcrumbPath> {({ mode }) => [ <StickyBreadcrumbPath.Crumb key="head"> <a href={channel.owner.href}> {channel.owner.name} {channel.counts.collaborators > 0 && <CollaboratorCount> {' '} (+{channel.counts.collaborators}) </CollaboratorCount> } </a> </StickyBreadcrumbPath.Crumb>, <StickyBreadcrumbPath.Crumb key="tail"> <ColoredChannelLink href={channel.href} visibility={channel.visibility} > {{ resting: channel.title, stuck: truncate(channel.title, 25), }[mode]} </ColoredChannelLink> </StickyBreadcrumbPath.Crumb>, ]} </StickyBreadcrumbPath> ); } }
port=$1 if !([[ -n $port ]];) then echo No port argument provided. exit fi pid=$(lsof -t -i4TCP:$port) if [[ -n $pid ]]; then echo Killing $pid on port: $port kill -9 $pid else echo Port $port is free fi
<filename>app/controllers/clickHandler.server.js var Users = require('../models/users.js') function ClickHandler() { this.getClicks = function(req, res) { Users.findOne({'github.id': req.user.github.id}, {_id: 0}).exec(function(err, result) { if (err) throw err; res.json(result.nbrClicks); }) }; this.addClick = function(req, res) { Users.findOneAndUpdate({'github.id': req.user.github.id}, {$inc: {'nbrClicks.clicks': 1}}) .exec(function(err, result) { if (err) throw err; res.json(result.nbrClicks); }); }; this.resetClicks = function(req, res) { Users.findOneAndUpdate({'github.id': req.user.github.id}, {'nbrClicks.clicks': 0}).exec(function(err, result) { if (err) throw err; res.json(result); }) } } module.exports = ClickHandler;
The error is that the variable names x and y are not defined. The code should be changed to use the variables X and Y that were passed to the function. def multiply(X,Y): # Function to multiply two numbers print(X*Y) # Changed x to X and y to Y
package resources const ( NodepoolPrefix = "kon-nodepool" NodepoolLabel = "k11n.dev/nodepool" AppLabel = "k11n.dev/app" TargetLabel = "k11n.dev/target" BuildRegistryLabel = "k11n.dev/buildRegistry" BuildImageLabel = "k11n.dev/buildImage" BuildLabel = "k11n.dev/build" BuildTypeLabel = "k11n.dev/buildType" AppReleaseLabel = "k11n.dev/appRelease" DomainLabel = "k11n.dev/domain" TargetReleaseLabel = "k11n.dev/targetRelease" AppProtocolLabel = "k11n.dev/appProtocol" KubeManagedByLabel = "app.kubernetes.io/managed-by" KubeAppLabel = "app" KubeAppVersionLabel = "app.kubernetes.io/version" KubeAppInstanceLabel = "app.kubernetes.io/instance" IstioInjectLabel = "istio-injection" Konstellation = "konstellation" BuildTypeLatest = "latest" )
<gh_stars>0 package com.study.basic.nio; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Objects; /** * <Description> * * @author hushiye * @since 9/6/21 15:59 */ public class MySocket { public static void main(String[] args) throws IOException { ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.configureBlocking(false); serverSocketChannel.socket().bind(new InetSocketAddress(9999)); ByteBuffer buf = ByteBuffer.allocate(48); while (true) { SocketChannel socketChannel = serverSocketChannel.accept(); if (Objects.nonNull(socketChannel)) { socketChannel.read(buf); System.out.println("获取到连接数据" + new String(buf.array())); } } } }
#!/bin/bash scriptPath="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" cd $scriptPath sh ./service-discovery/shells/build.sh sh ./user-service/shells/build.sh sh ./product-service/shells/build.sh
function setSessionStorage(){ var userCompany = document.getElementById('company').value; var firstName = document.getElementById('fname').value; var lastName = document.getElementById('lname').value; var address = document.getElementById('address').value; var city = document.getElementById('city').value; var state = document.getElementById('state').value; var zipCode = document.getElementById('zipCode').value; var phoneNumber = document.getElementById('phoneNumber').value; var email = document.getElementById('email').value; var reqService = document.getElementById('service').value; var reqDate = JSON.stringify(document.getElementById('date').value); var reqTime = JSON.stringify(document.getElementById('time').value); localStorage.setItem('item1', userCompany); localStorage.setItem('item2', firstName); localStorage.setItem("item3", lastName); localStorage.setItem('item4', address); localStorage.setItem('item5', city); localStorage.setItem('item6', state); localStorage.setItem('item7', zipCode); localStorage.setItem('item8', phoneNumber); localStorage.setItem('item9', email); localStorage.setItem('item10', reqService); localStorage.setItem('item11', reqDate); localStorage.setItem('item12', reqTime); } function getStorage(){ document.getElementById('userCompany').innerHTML = localStorage.getItem('item1'); document.getElementById('name').innerHTML = (localStorage.getItem('item2') + " " + localStorage.getItem("item3")); document.getElementById('address').innerHTML = localStorage.getItem('item4'); document.getElementById('city').innerHTML = localStorage.getItem('item5'); document.getElementById('state').innerHTML = localStorage.getItem('item6'); document.getElementById('zipCode').innerHTML = localStorage.getItem('item7'); document.getElementById('phoneNumber').innerHTML = localStorage.getItem('item8'); document.getElementById('email').innerHTML = localStorage.getItem('item9'); document.getElementById('reqService').innerHTML = localStorage.getItem('item10'); document.getElementById('reqDate').innerHTML = localStorage.getItem('item11'); document.getElementById('reqTime').innerHTML = localStorage.getItem('item12'); }
protected void doDecode(MessageContext messageContext) throws MessageDecodingException { if (!(messageContext instanceof SAMLMessageContext)) { log.error("Invalid message context type, this decoder only supports SAMLMessageContext"); throw new MessageDecodingException( "Invalid message context type, this decoder only supports SAMLMessageContext"); } if (!(messageContext.getInboundMessageTransport() instanceof HTTPInTransport)) { log.error("Invalid inbound message transport type, this decoder only supports HTTPInTransport"); throw new MessageDecodingException( "Invalid inbound message transport type, this decoder only supports HTTPInTransport"); } // Add the remaining logic for message decoding here // ... }
import { Extension } from '../models/index'; import { ExtensionUtility } from './extensionUtility'; import { SharedService } from '../services/shared.service'; export declare class RowMoveManagerExtension implements Extension { private extensionUtility; private sharedService; private _eventHandler; private _extension; constructor(extensionUtility: ExtensionUtility, sharedService: SharedService); dispose(): void; register(rowSelectionPlugin?: any): any; }
<filename>lib/deck.rb<gh_stars>0 class Deck attr_reader :cards def initialize(cards) @cards = cards end end
<filename>2d/src/test/java/de/bitbrain/braingdx/tmx/TiledMapManagerTest.java /* Copyright 2017 <NAME> * * 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 de.bitbrain.braingdx.tmx; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.maps.tiled.TiledMap; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.World; import de.bitbrain.braingdx.behavior.BehaviorManager; import de.bitbrain.braingdx.behavior.BehaviorManagerAdapter; import de.bitbrain.braingdx.event.*; import de.bitbrain.braingdx.graphics.GameCamera; import de.bitbrain.braingdx.graphics.GameObjectRenderManager; import de.bitbrain.braingdx.graphics.GameObjectRenderManager.GameObjectRenderer; import de.bitbrain.braingdx.physics.PhysicsManagerImpl; import de.bitbrain.braingdx.utils.GdxUtils; import de.bitbrain.braingdx.world.GameObject; import de.bitbrain.braingdx.world.GameWorld; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertFalse; import static org.mockito.Matchers.any; import static org.mockito.Mockito.*; /** * Tests and verifies the integrity of the {@link TiledMapManager} implementation used within * braingdx. * * @author <NAME> * @version 1.0.0 * @since 1.0.0 */ @RunWith(MockitoJUnitRunner.class) public class TiledMapManagerTest { @Mock private GameObjectRenderManager renderManager; @Mock private OrthographicCamera camera; private TiledMapManagerImpl tiledMapManager; private GameEventManager gameEventManager; private GameWorld world; @Before public void beforeTest() { GameCamera gameCamera = mock(GameCamera.class); when(gameCamera.getLeft()).thenReturn(0f); when(gameCamera.getTop()).thenReturn(0f); when(gameCamera.getScaledCameraWidth()).thenReturn(10f); when(gameCamera.getScaledCameraHeight()).thenReturn(10f); world = new GameWorld(); world.setCamera(gameCamera); gameEventManager = new GameEventManagerImpl(); GdxUtils.mockApplicationContext(); BehaviorManager behaviorManager = new BehaviorManager(world); world.addListener(new BehaviorManagerAdapter(behaviorManager)); GameEventRouter tiledMapEventRouter = new GameEventRouter( gameEventManager, world, new TiledMapInfoExtractor() ); behaviorManager.apply(tiledMapEventRouter); TiledMapContextFactory contextFactory = new TiledMapContextFactory( renderManager, world, gameEventManager, tiledMapEventRouter, behaviorManager, new PhysicsManagerImpl(new World(new Vector2(), true), world, behaviorManager) ); tiledMapManager = new TiledMapManagerImpl(world, gameEventManager, contextFactory) { @Override protected Map<TiledMapType, MapLayerRendererFactory> createRendererFactories() { Map<TiledMapType, MapLayerRendererFactory> mockMap = new HashMap<TiledMapType, MapLayerRendererFactory>(); for (TiledMapType type : TiledMapType.values()) { mockMap.put(type, new MockMapLayerRendererFactory()); } return mockMap; } }; } @Test(expected = NullPointerException.class) public void load_WithNullValues() throws TiledMapException { tiledMapManager.load((TiledMap) null, null, null); } @Test(expected = TiledMapException.class) public void load_withInvalidTiledMapWidth() throws TiledMapException { TiledMap map = new MockTiledMapBuilder(0, 1, 1, TiledMapType.ORTHOGONAL).addLayer().build(); tiledMapManager.load(map, camera); } @Test(expected = TiledMapException.class) public void load_withInvalidTiledMapHeight() throws TiledMapException { TiledMap map = new MockTiledMapBuilder(1, 0, 1, TiledMapType.ORTHOGONAL).addLayer().build(); tiledMapManager.load(map, camera); } @Test(expected = TiledMapException.class) public void load_withInvalidTiledMapDimensions() throws TiledMapException { TiledMap map = new MockTiledMapBuilder(0, 0, 1, TiledMapType.ORTHOGONAL).addLayer().build(); tiledMapManager.load(map, camera); } @Test(expected = TiledMapException.class) public void load_withInvalidMapLayers() throws TiledMapException { TiledMap map = new MockTiledMapBuilder(1, 0, 1, TiledMapType.ORTHOGONAL).build(); tiledMapManager.load(map, camera); } @Test public void load_withNoMapObjects() throws TiledMapException { TiledMap map = new MockTiledMapBuilder(1, 1, 1, TiledMapType.ORTHOGONAL) .addLayer() .addLayer() .addLayer() .build(); tiledMapManager.load(map, camera); assertThat(world.size()).isEqualTo(4); // 1 + 1 debug layer inOrder(renderManager).verify(renderManager, calls(1)).register(any(), any(GameObjectRenderer.class)); world.update(1f); assertThat(world.getObjects(null, true).size).isEqualTo(4); } @Test public void load_withMapObjects() throws TiledMapException { final String typeA = "typeA"; final String typeB = "typeB"; TiledMap map = new MockTiledMapBuilder(5, 5, 5, TiledMapType.ORTHOGONAL).addLayer().addLayer() .addLayer(new MockObjectLayerBuilder().addObject(0, 0, 2, typeA).addObject(0, 0, 6, typeB).build()) .addLayer().build(); tiledMapManager.load(map, camera); GameObject objectA = null; GameObject objectB = null; for (GameObject object : world.getObjects()) { if (object.getType().equals(typeA)) { objectA = object; } else if (object.getType().equals(typeB)) { objectB = object; } } assertThat(objectA).isNotNull(); assertThat(objectB).isNotNull(); assertThat(objectA.getWidth()).isEqualTo(5f); assertThat(objectA.getHeight()).isEqualTo(5f); assertThat(objectB.getWidth()).isEqualTo(10f); assertThat(objectB.getHeight()).isEqualTo(10f); assertThat(world.size()).isEqualTo(6); // 5 + 1 debug layer inOrder(renderManager).verify(renderManager, calls(3)).register(any(), any(GameObjectRenderer.class)); } @Test public void load_withMapObjectsValidAPI() throws TiledMapException { final String type = "game_object"; final AtomicBoolean failed = new AtomicBoolean(true); final AtomicBoolean firstObject = new AtomicBoolean(true); gameEventManager.register(new GameEventListener<TiledMapEvents.OnLoadGameObjectEvent>() { @Override public void onEvent(TiledMapEvents.OnLoadGameObjectEvent event) { if (firstObject.get()) { assertThat(event.getTiledMapContext().getNumberOfColumns()).isEqualTo(2); assertThat(event.getTiledMapContext().getNumberOfRows()).isEqualTo(2); assertThat(event.getTiledMapContext().highestZIndexAt(0, 0)).isGreaterThan(2); assertThat(event.getTiledMapContext().isCollision(0, 0, 1)).isFalse(); assertThat(event.getTiledMapContext().isCollision(1, 1, 1)).isFalse(); failed.set(false); firstObject.set(false); } else { assertThat(event.getTiledMapContext().getNumberOfColumns()).isEqualTo(2); assertThat(event.getTiledMapContext().getNumberOfRows()).isEqualTo(2); assertThat(event.getTiledMapContext().highestZIndexAt(0, 0)).isGreaterThan(2); assertThat(event.getTiledMapContext().isCollision(0, 0, 1)).isFalse(); assertThat(event.getTiledMapContext().isCollision(1, 1, 1)).isTrue(); } } }, TiledMapEvents.OnLoadGameObjectEvent.class); TiledMap map = new MockTiledMapBuilder(2, 2, 1, TiledMapType.ORTHOGONAL).addLayer().addLayer() .addLayer(new MockObjectLayerBuilder().addObject(0, 0, type, false).addObject(1, 1, type).build()) .addLayer().build(); tiledMapManager.load(map, camera); assertFalse(failed.get()); } @Test public void load_withSimple3x3Map_validCollisions() throws TiledMapException { TiledMapContext context = tiledMapManager.load(createSimple3x3Map(), camera); final GameObject objectA = context.getGameObjectAt(0, 1, 0); final GameObject objectB = context.getGameObjectAt(1, 1, 0); final GameObject objectC = context.getGameObjectAt(0, 0, 1); // Update the world world.update(0f); // Validate state assertThat(objectA).isNotNull(); assertThat(objectB).isNotNull(); assertThat(objectC).isNotNull(); // Validate collisions assertThat(context.isCollision(0, 0, 0)).isFalse(); assertThat(context.isCollision(1, 0, 0)).isFalse(); assertThat(context.isCollision(0, 1, 0)).isTrue(); assertThat(context.isCollision(1, 1, 0)).isTrue(); assertThat(context.isCollision(0, 0, 1)).isTrue(); assertThat(context.isCollision(1, 0, 1)).isFalse(); assertThat(context.isCollision(0, 1, 1)).isTrue(); assertThat(context.isCollision(1, 1, 1)).isTrue(); } @Test public void load_withSimple3x3Map_validCollisionsWithCollisionLayer() throws TiledMapException { TiledMapContext context = tiledMapManager.load(createSimple3x3Map(true), camera); final GameObject objectA = context.getGameObjectAt(0, 1, 0); final GameObject objectB = context.getGameObjectAt(1, 1, 0); final GameObject objectC = context.getGameObjectAt(0, 0, 1); // Update the world world.update(0f); // Validate state assertThat(objectA).isNotNull(); assertThat(objectB).isNotNull(); assertThat(objectC).isNotNull(); // Validate collisions assertThat(context.isCollision(0, 0, 0)).isFalse(); assertThat(context.isCollision(1, 0, 0)).isFalse(); assertThat(context.isCollision(0, 1, 0)).isTrue(); assertThat(context.isCollision(1, 1, 0)).isTrue(); assertThat(context.isCollision(0, 0, 1)).isTrue(); assertThat(context.isCollision(1, 0, 1)).isFalse(); assertThat(context.isCollision(0, 1, 1)).isFalse(); assertThat(context.isCollision(1, 1, 1)).isFalse(); } @Test public void load_withSimple3x3Map_validUpdatingAfterMovement() throws TiledMapException { TiledMapContext context = tiledMapManager.load(createSimple3x3Map(), camera); final GameObject objectA = context.getGameObjectAt(0, 1, 0); objectA.setPosition(1, 0); world.update(0f); assertThat(context.isCollision(1, 0, 0)).isTrue(); assertThat(context.isCollision(0, 1, 0)).isFalse(); } @Test public void load_withSimple3x3Map_validUpdatingAfterChangingLayers() throws TiledMapException { TiledMapContext context = tiledMapManager.load(createSimple3x3Map(), camera); final GameObject objectA = context.getGameObjectAt(0, 1, 0); objectA.setPosition(1, 0); world.update(0f); context.setLayerIndex(objectA, 1); world.update(0f); assertThat(context.isCollision(1, 0, 1)).isTrue(); assertThat(context.isCollision(1, 0, 0)).isFalse(); assertThat(context.isCollision(0, 1, 0)).isFalse(); } @Test(expected = TiledMapException.class) public void load_withSimple3x3Map_invalidUpdatingAfterChangingLayers() throws TiledMapException { TiledMapContext context = tiledMapManager.load(createSimple3x3Map(), camera); final GameObject objectA = context.getGameObjectAt(0, 1, 0); context.setLayerIndex(objectA, 6); } @Test public void load_withSimple3x3Map_publishCustomEventOnCollision() throws TiledMapException { TiledMap map = new MockTiledMapBuilder(2, 2, 1, TiledMapType.ORTHOGONAL) .addLayer(new MockTiledTileLayerBuilder() .addCell(0, 0) .addCell(0, 1) .addCell(1, 0) .addCell(1, 1).build()) .addLayer(new MockObjectLayerBuilder().addObject(0, 0, "event").addObject(1, 1, "player").build()) .build(); TiledMapContext context = tiledMapManager.load(map, camera); final AtomicBoolean called = new AtomicBoolean(); final GameEventListener<TestEvent> gameEventEventListener = new GameEventListener<TestEvent>() { @Override public void onEvent(TestEvent event) { called.set(true); } }; gameEventManager.register(gameEventEventListener, TestEvent.class); context.setEventFactory(new GameEventFactory() { @Override public GameEvent create(GameObject eventObject, GameObject producerObject) { return new TestEvent(); } @Override public Object[] identifiers() { return new Object[]{"event"}; } }); for (GameObject o : world.getObjects()) { if (o.getType().equals("player")) { // move player to event o.setPosition(0, 0); } } world.update(0f); assertThat(called.get()).isTrue(); } @Test public void load_withSimple3x3Map_publishOnProducerCollisionOnly() throws TiledMapException { TiledMap map = new MockTiledMapBuilder(2, 2, 1, TiledMapType.ORTHOGONAL) .addLayer(new MockTiledTileLayerBuilder().addCell(0, 0).addCell(0, 1).addCell(1, 0).addCell(1, 1).build()) .addLayer(new MockObjectLayerBuilder() .addObject(0, 0, "event", "player", true) .addObject(1, 1, "player") .addObject(1, 1, "another_player").build()) .build(); TiledMapContext context = tiledMapManager.load(map, camera); final AtomicInteger calls = new AtomicInteger(); final GameEventListener<TestEvent> gameEventEventListener = new GameEventListener<TestEvent>() { @Override public void onEvent(TestEvent event) { calls.addAndGet(1); } }; gameEventManager.register(gameEventEventListener, TestEvent.class); context.setEventFactory(new GameEventFactory() { @Override public GameEvent create(GameObject eventObject, GameObject producerObject) { return new TestEvent(); } @Override public Object[] identifiers() { return new Object[]{"event"}; } }); for (GameObject o : world.getObjects()) { if (o.getType().equals("player") || o.getType().equals("another_player")) { // move player to event o.setPosition(0, 0); } } world.update(0f); assertThat(calls.get()).isEqualTo(1); } @Test public void load_withSimple3x3Map_republishOnSticky() throws TiledMapException { TiledMap map = new MockTiledMapBuilder(2, 2, 1, TiledMapType.ORTHOGONAL) .addLayer(new MockTiledTileLayerBuilder() .addCell(0, 0) .addCell(0, 1) .addCell(1, 0) .addCell(1, 1) .build()) .addLayer(new MockObjectLayerBuilder() .addObject(0, 0, "event", null, true) .addObject(1, 1, "player") .addObject(1, 1, "another_player").build()) .build(); TiledMapContext context = tiledMapManager.load(map, camera); final AtomicInteger calls = new AtomicInteger(); final GameEventListener<TestEvent> gameEventEventListener = new GameEventListener<TestEvent>() { @Override public void onEvent(TestEvent event) { calls.addAndGet(1); } }; gameEventManager.register(gameEventEventListener, TestEvent.class); context.setEventFactory(new GameEventFactory() { @Override public GameEvent create(GameObject eventObject, GameObject producerObject) { return new TestEvent(); } @Override public Object[] identifiers() { return new Object[]{"event"}; } }); for (GameObject o : world.getObjects()) { if (o.getType().equals("player") || o.getType().equals("another_player")) { // move player to event o.setPosition(0, 0); } } world.update(0f); assertThat(calls.get()).isEqualTo(2); } @Test public void load_withSimple3x3Map_removeLastCollisionOnSimpleMove() { TiledMap map = new MockTiledMapBuilder(2, 2, 1, TiledMapType.ORTHOGONAL) .addLayer(new MockTiledTileLayerBuilder().addCell(0, 0) .addCell(0, 1) .addCell(1, 0) .addCell(1, 1) .build()) .addLayer(new MockObjectLayerBuilder().addObject(0, 0, "player").build()) .build(); TiledMapContext context = tiledMapManager.load(map, camera); world.update(0f); assertThat(context.isCollision(0, 0, 0)).isTrue(); for (GameObject o : world.getObjects()) { if (o.getType().equals("player")) { o.setPosition(1, 0); } } world.update(0f); assertThat(context.isCollision(0, 0, 0)).isFalse(); } @Test public void load_withSimple3x3Map_removeLastCollisionOnMultipleMoves() { TiledMap map = new MockTiledMapBuilder(2, 2, 1, TiledMapType.ORTHOGONAL) .addLayer(new MockTiledTileLayerBuilder() .addCell(0, 0) .addCell(0, 1) .addCell(1, 0) .addCell(1, 1) .build()) .addLayer(new MockObjectLayerBuilder().addObject(0, 0, "player").build()) .build(); TiledMapContext context = tiledMapManager.load(map, camera); world.update(0f); assertThat(context.isCollision(0, 0, 0)).isTrue(); for (GameObject o : world.getObjects()) { if (o.getType().equals("player")) { o.setPosition(1, 0); o.setPosition(0, 1); } } world.update(0f); assertThat(context.isCollision(0, 0, 0)).isFalse(); assertThat(context.isCollision(0, 1, 0)).isTrue(); } @Test public void load_withSimple3x3Map_shouldNotOverrideExistingCollision() { TiledMap map = new MockTiledMapBuilder(2, 2, 1, TiledMapType.ORTHOGONAL) .addLayer(new MockTiledTileLayerBuilder() .addCell(0, 0) .addCell(0, 1, true) .addCell(1, 0) .addCell(1, 1).build()) .addLayer(new MockObjectLayerBuilder().addObject(0, 0, "player").build()) .build(); TiledMapContext context = tiledMapManager.load(map, camera); world.update(0f); // Check for normal collision setup assertThat(context.isCollision(0, 0, 0)).isTrue(); assertThat(context.isCollision(0, 1, 0)).isTrue(); for (GameObject o : world.getObjects()) { if (o.getType().equals("player")) { o.setPosition(0, 1); } } world.update(0f); // Verify collision has moved assertThat(context.isCollision(0, 0, 0)).isFalse(); assertThat(context.isCollision(0, 1, 0)).isTrue(); for (GameObject o : world.getObjects()) { if (o.getType().equals("player")) { o.setPosition(0, 0); } } world.update(0f); // Verify that everything is back to normal assertThat(context.isCollision(0, 0, 0)).isTrue(); assertThat(context.isCollision(0, 1, 0)).isTrue(); assertThat(world.getObjects(null, true).size).isEqualTo(3); } @Test public void load_withSimple3x3Map_shouldOnlyUnloadRelevantObjects() { TiledMap map = new MockTiledMapBuilder(2, 2, 1, TiledMapType.ORTHOGONAL) .addLayer(new MockTiledTileLayerBuilder() .addCell(0, 0) .addCell(0, 1, true) .addCell(1, 0) .addCell(1, 1).build()) .addLayer(new MockObjectLayerBuilder().addObject(0, 0, "player").build()) .build(); TiledMapContext context = tiledMapManager.load(map, camera); world.update(0f); GameObject remainder = world.addObject(); assertThat(world.size()).isEqualTo(4); context.dispose(); assertThat(world.getObjects()).containsExactly(remainder); } @Test public void should_load_multiple_maps() { TiledMap map1 = new MockTiledMapBuilder(2, 2, 1, TiledMapType.ORTHOGONAL) .addLayer(new MockTiledTileLayerBuilder() .addCell(0, 0) .addCell(0, 1, true) .addCell(1, 0) .addCell(1, 1).build()) .addLayer(new MockObjectLayerBuilder().addObject(0, 0, "player1").build()) .build(); TiledMap map2 = new MockTiledMapBuilder(2, 2, 1, TiledMapType.ORTHOGONAL) .addLayer(new MockTiledTileLayerBuilder() .addCell(0, 0) .addCell(0, 1, true) .addCell(1, 0) .addCell(1, 1).build()) .addLayer(new MockObjectLayerBuilder().addObject(0, 0, "player2").build()) .build(); TiledMapContext context1 = tiledMapManager.load(map1, camera); TiledMapContext context2 = tiledMapManager.load(map2, camera); assertThat(world.getObjects()).hasSize(6); tiledMapManager.unload(context2); assertThat(world.getObjects()).hasSize(3); tiledMapManager.unload(context1); assertThat(world.getObjects()).isEmpty(); } @Test public void should_allow_duplicate_loading() { TiledMap map = new MockTiledMapBuilder(2, 2, 1, TiledMapType.ORTHOGONAL) .addLayer(new MockTiledTileLayerBuilder() .addCell(0, 0) .addCell(0, 1, true) .addCell(1, 0) .addCell(1, 1).build()) .addLayer(new MockObjectLayerBuilder().addObject(0, 0, "player1").build()) .build(); TiledMapContext context = tiledMapManager.load(map, camera); assertThat(tiledMapManager.load(map, camera)).isEqualTo(context); } /** * Creates collisions on different layers * <p> * setup: * * <pre> * x x x x * x c x * x a b x * x x x x * </pre> */ private TiledMap createSimple3x3Map(boolean collision) { // Initialization final String typeA = "a"; final String typeB = "b"; final String typeC = "c"; return new MockTiledMapBuilder(2, 2, 1, TiledMapType.ORTHOGONAL) .addLayer(new MockTiledTileLayerBuilder().addCell(0, 0).addCell(0, 1).addCell(1, 0).addCell(1, 1).build()) .addLayer(new MockObjectLayerBuilder().addObject(0, 1, typeA).addObject(1, 1, typeB).build()) .addLayer(new MockTiledTileLayerBuilder().addCell(0, 0).addCell(0, 1).addCell(1, 0).addCell(1, 1) .collision(collision).build()) .addLayer(new MockObjectLayerBuilder().addObject(0, 0, typeC).build()).build(); } private TiledMap createSimple3x3Map() { return createSimple3x3Map(false); } private class TestEvent implements GameEvent { } }
#! /usr/bin/env sh export PYTHONPATH="src:$PYTHONPATH" python3 -m pytest tests $@
// For keybind handling -- Created by <NAME> https://aerilym.github.io/ //NOTE pressing shift and = is actualy shift and + as well as just pressing +, as when you hold shift it changes the = key to +, this happens to all keys with a shift option. //NOTE the + symbol in the keybinds indicated a key combination, so shift+h is holding shift and clicking h //BINDS 1 2 Non-Shift adddestiny = ['shift+=', '+', '='] //Add destiny point removedestiny = ['shift+-', '_', '-'] //Remove destiny point fliptolight = ['shift+up', '', 'up'] //Flip dark side point to light fliptodark = ['shift+down', '', 'down'] //Flip light side point to dark hidebuttons = ['shift+h', '', 'h'] //Hide/Unhide buttons hideeye = ['shift+e', '', 'e'] //Hide/Unhide eye button toggleused = ['shift+u', '', 'u'] //Hide/Unhide used counter togglenum = ['shift+n', '', 'n'] //Hide/Unhide num counter toggleshift = ['t', '', 't'] //Toggle non-shift keybinds resetused = ['shift+i', '', 'i'] //Reset used counter binds = ['adddestiny', 'removedestiny', 'fliptolight', 'fliptodark', 'hidebuttons', 'hideeye', 'toggleused', 'togglenum', 'toggleshift', 'resetused'] bindsmap = [adddestiny, removedestiny, fliptolight, fliptodark, hidebuttons, hideeye, toggleused, togglenum, toggleshift, resetused] //Adds a destiny point to the tracker function bindadddestiny(keybinds) { if (keybinds.length == 1) { keybinds.push('') } for (var i = 0; i < keybinds.length-1; i++) { if (keybinds[i] != '') { Mousetrap.bind(keybinds[i], function(e) { add_destiny() return false; }); } } } //Removes a destiny point from the tracker function bindremovedestiny(keybinds) { if (keybinds.length == 1) { keybinds.push('') } for (var i = 0; i < keybinds.length-1; i++) { if (keybinds[i] != '') { Mousetrap.bind(keybinds[i], function(e) { remove_destiny() return false; }); } } } //Flips a dark side destiny point to a light side destiny point function bindfliptolight(keybinds) { if (keybinds.length == 1) { keybinds.push('') } for (var i = 0; i < keybinds.length-1; i++) { if (keybinds[i] != '') { Mousetrap.bind(keybinds[i], function(e) { flip('light') return false; }); } } } //Flips a light side destiny point to a dark side destiny point function bindfliptodark(keybinds) { if (keybinds.length == 1) { keybinds.push('') } for (var i = 0; i < keybinds.length-1; i++) { if (keybinds[i] != '') { Mousetrap.bind(keybinds[i], function(e) { flip('dark') return false; }); } } } //Hide/Unhide the buttons and information below the tool function bindhidebuttons(keybinds) { if (keybinds.length == 1) { keybinds.push('') } for (var i = 0; i < keybinds.length-1; i++) { if (keybinds[i] != '') { Mousetrap.bind(keybinds[i], function(e) { togglehide('settings','block') return false; }); } } } //Hide/Unhide the eye icon (the icon used for hiding the buttons) function bindhideeye(keybinds) { if (keybinds.length == 1) { keybinds.push('') } for (var i = 0; i < keybinds.length-1; i++) { if (keybinds[i] != '') { Mousetrap.bind(keybinds[i], function(e) { deleteeye('key') return false; }); } } } //Hide/Unhide the used counter function bindtoggleused(keybinds) { if (keybinds.length == 1) { keybinds.push('') } for (var i = 0; i < keybinds.length-1; i++) { if (keybinds[i] != '') { Mousetrap.bind(keybinds[i], function(e) { togglehide('destinytracker','inline-block') return false; }); } } } //Hide/Unhide the num counter function bindtogglenum(keybinds) { if (keybinds.length == 1) { keybinds.push('') } for (var i = 0; i < keybinds.length-1; i++) { if (keybinds[i] != '') { Mousetrap.bind(keybinds[i], function(e) { togglehide('destinynumber','inline-block') return false; }); } } } //Toggle non-shift keybinds function bindtoggleshift(keybinds) { if (keybinds.length == 1) { keybinds.push('') } for (var i = 0; i < keybinds.length-1; i++) { if (keybinds[i] != '') { Mousetrap.bind(keybinds[i], function(e) { altkeybinds() return false; }); } } } //Reset used counter function bindusedreset(keybinds) { if (keybinds.length == 1) { keybinds.push('') } for (var i = 0; i < keybinds.length-1; i++) { if (keybinds[i] != '') { Mousetrap.bind(keybinds[i], function(e) { update_counter('reset') return false; }); } } } Mousetrap.bind('up up down down left right left right b a enter', function() { alert('nice') }); function setkeybinds(keybindsmap) { bindadddestiny(keybindsmap[0]) bindremovedestiny(keybindsmap[1]) bindfliptolight(keybindsmap[2]) bindfliptodark(keybindsmap[3]) bindhidebuttons(keybindsmap[4]) bindhideeye(keybindsmap[5]) bindtoggleused(keybindsmap[6]) bindtogglenum(keybindsmap[7]) bindtoggleshift(keybindsmap[8]) bindusedreset(keybindsmap[9]) } setkeybinds(bindsmap) //Non-shift keybinds (only active when the button on the page is active) function bindnonshift() { //Adds a destiny point to the tracker Mousetrap.bind(adddestiny[2], function(e) { add_destiny() return false; }); //Removes a destiny point from the tracker Mousetrap.bind(removedestiny[2], function(e) { remove_destiny() return false; }); //Hide/Unhide the buttons and information below the tool Mousetrap.bind(hidebuttons[2], function(e) { togglehide('settings','block') return false; }); //Hide/Unhide the eye icon (the icon used for hiding the buttons) Mousetrap.bind(hideeye[2], function(e) { deleteeye('key') return false; }); //Flips a dark side destiny point to a light side destiny point Mousetrap.bind(fliptolight[2], function(e) { flip('light') return false; }); //Flips a light side destiny point to a dark side destiny point Mousetrap.bind(fliptodark[2], function(e) { flip('dark') return false; }); Mousetrap.bind(toggleused[2], function(e) { togglehide('destinytracker','inline-block') return false; }); Mousetrap.bind(togglenum[2], function(e) { togglehide('destinynumber','inline-block') return false; }); Mousetrap.bind(toggleshift[2], function(e) { altkeybinds() return false; }); Mousetrap.bind(resetused[2], function(e) { update_counter('reset') return false; }); } //Unbinds Non-shift keybinds when called function unbindnonshift() { Mousetrap.unbind(adddestiny[2]); Mousetrap.unbind(removedestiny[2]); Mousetrap.unbind(hidebuttons[2]); Mousetrap.unbind(hideeye[2]); Mousetrap.unbind(fliptolight[2]); Mousetrap.unbind(fliptodark[2]); Mousetrap.unbind(toggleused[2]); Mousetrap.unbind(togglenum[2]); Mousetrap.unbind(toggleshift[2]); Mousetrap.unbind(resetused[2]); } //Umbinds Non-shift keybinds when called function unbindall() { for (var i = 0; i < bindsmap.length; i++) { for (var j = 0; j < adddestiny.length-1; j++) { Mousetrap.unbind(bindsmap[i][j]) } } } function writekeybinds() { var keynum = adddestiny.length var numbinds = binds.length for (var i = 0; i < numbinds; i++) { for (var j = 0; j < keynum; j++) { docbind = document.getElementById('KB' + binds[i] + j) docbind.innerText = bindsmap[i][j].replace('+',' + ') docbind.onclick = function(){changebind(this.id);}; } } } function changebind(elementID) { var bindelement = document.getElementById(elementID) var oldBind = bindelement.innerText.replace(' + ','+') console.log(oldBind) Mousetrap.unbind(oldBind) result = window.prompt('Change keybind', oldBind); var fnstr = elementID.slice(2,-1) if (fnstr == 'adddestiny') { bindadddestiny([result]) } else if (fnstr == 'removedestiny') { bindremovedestiny([result]) } else if (fnstr == 'fliptolight') { bindfliptolight([result]) } else if (fnstr == 'fliptodark') { bindfliptodark([result]) } else if (fnstr == 'hidebuttons') { bindhidebuttons([result]) } else if (fnstr == 'hideeye') { bindhideeye([result]) } bindelement.innerText = result }
#include <windows.h> #include <string> std::wstring ExePath() { WCHAR buffer[MAX_PATH]; GetModuleFileNameW(NULL, buffer, MAX_PATH); return std::wstring(buffer); } std::wstring DirPath() { std::wstring exepath = ExePath(); std::wstring::size_type pos = exepath.find_last_of(L"\\/"); return exepath.substr(0, pos); } std::wstring CONFIG_FILE_STRING = DirPath() + L"\\plugins\\Lights.ini"; LPCWSTR CONFIG_FILE = CONFIG_FILE_STRING.c_str();
/* TRANSITIONS */ const swup = new Swup(); /* NAVIGATION MENU */ const hamburger = document.querySelector(".hamburger"); const navMenu = document.querySelector(".nav-menu"); hamburger.addEventListener("click", mobileMenu); function mobileMenu() { hamburger.classList.toggle("active"); navMenu.classList.toggle("active"); } const navLink = document.querySelectorAll(".nav-link"); navLink.forEach(n => n.addEventListener("click", closeMenu)); function closeMenu() { hamburger.classList.remove("active"); navMenu.classList.remove("active"); }; /* READ MORE */ function init () { let noOfCharac = 300; let contents = document.querySelectorAll(".content"); contents.forEach(content => { //If text length is less that noOfCharac... then hide the read more button if(content.textContent.length < noOfCharac){ content.nextElementSibling.style.display = "none"; } else{ let displayText = content.textContent.slice(0,noOfCharac); let moreText = content.textContent.slice(noOfCharac); content.innerHTML = `${displayText}<span class="dots">...</span><span class="hide more">${moreText}</span>`; } }); } init(); document.addEventListener('swup:contentReplaced', init); function readMore(btn){ let post = btn.parentElement; post.querySelector(".dots").classList.toggle("hide"); post.querySelector(".more").classList.toggle("hide"); btn.textContent == "Show full abstract" ? btn.textContent = "Hide abstract" : btn.textContent = "Show full abstract"; };
<filename>C++/LAB3/EulerLoop.h // // EulerLoop.h // LAB3 // // Created by <NAME> on 27.05.2018. // Copyright © 2018 <NAME>. All rights reserved. // #ifndef EulerLoop_h #define EulerLoop_h #endif /* EulerLoop_h */
<filename>lang/py/cookbook/v2/02/bench.py #! /usr/bin/env python # -*- coding:UTF-8 -*- import time def timeo(fun, n=10): start = time.clock() for i in xrange(n): fun() end = time.clock() thetime = end - start return fun.__name__, thetime import os def linecount_wc(): return int(os.popen('wc -l syslog').read().split()[0]) def linecount_1(): return len(open('syslog').readlines()) def linecount_2(): for count, line in enumerate(open('syslog')): pass return count + 1 def linecount_3(): # 更具技巧性,统计\n的次数 count = 0 thefile = open('syslog', 'rb') while True: block = thefile.read(65536) if not block: break count += block.count('\n') return count for f in linecount_wc, linecount_1, linecount_2, linecount_3: print f.__name__, f() for f in linecount_1, linecount_2, linecount_3: print "%s: %.2f" % timeo(f)
def sum_range(start, end): total = 0 for i in range(start,end + 1): total += i return total # Test the function print(sum_range(1, 10)) # Output: 55
<filename>resources/js/app.js /** * First we will load all of this project's JavaScript dependencies which * includes Vue and other libraries. It is a great starting point when * building robust, powerful web applications using Vue and Laravel. */ require('./bootstrap'); window.Vue = require('vue'); /** * The following block of code may be used to automatically register your * Vue components. It will recursively scan this directory for the Vue * components and automatically register them with their "basename". * * Eg. ./components/ExampleComponent.vue -> <example-component></example-component> */ // const files = require.context('./', true, /\.vue$/i) // files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default)) Vue.component('home-page', require('./components/HomePage/HomePage.vue').default); Vue.component('example-component', require('./components/ExampleComponent.vue').default); Vue.component('profile', require('./components/HomePage/Profile/Profile.vue').default); Vue.component('navbar', require('./components/HomePage/Navbar.vue').default); Vue.component('payment', require('./components/OtherPages/Payment/Payment').default); Vue.component('confirm-order', require('./components/OtherPages/ConfirmOrder/ConfirmOrder.vue').default); Vue.component('page-footer', require('./components/UI/Footer.vue').default); Vue.component('dashboard', require('./components/OtherPages/Dashboard/Dashboard').default); Vue.component('logodesign-report', require('./components/OtherPages/Report/LogoDesign').default); Vue.component('settings', require('./components/OtherPages/Dashboard/Settings').default); Vue.component('meet-the-team', require('./components/HomePage/WhatWeDo/MeetTheTeam').default); Vue.component('google-login', require('./components/UI/GoogleLogin').default); /** * Next, we will create a fresh Vue application instance and attach it to * the page. Then, you may begin adding components to this application * or customize the JavaScript scaffolding to fit your unique needs. */ import Vue from 'vue'; import VueRouter from 'vue-router'; import AboutUs from './components/OtherPages/AboutUs.vue'; import Terms from './components/OtherPages/Terms.vue'; import HomePage from './components/HomePage/HomePage.vue'; import Design from './components/OtherPages/Design/Design.vue'; import LogoDesign from './components/OtherPages/Design/LogoDesign/LogoDesign.vue'; import LogoPackage from './components/OtherPages/Design/LogoDesign/LogoPackage/LogoPackage.vue'; import LogoType from './components/OtherPages/Design/LogoDesign/LogoType/LogoType.vue'; import LogoFont from './components/OtherPages/Design/LogoDesign/LogoFont/LogoFont'; import Info from './components/OtherPages/Design/LogoDesign/Info/Info.vue'; import Branding from './components/OtherPages/Design/Branding/Branding'; import BrandingPackage from './components/OtherPages/Design/Branding/Package/Package'; import BrandingInfo from './components/OtherPages/Design/Branding/Info/Info'; import SocialMedia from './components/OtherPages/Design/SocialMedia/SocialMedia'; import SocialMediaPackage from './components/OtherPages/Design/SocialMedia/Package/Package'; import SocialMediaInfo from './components/OtherPages/Design/SocialMedia/Info/Info'; import Stationery from './components/OtherPages/Design/Stationery/Stationery'; // import StationeryPackage from './components/OtherPages/Design/Stationery/Package/Package'; // import StationeryProducts from './components/OtherPages/Design/Stationery/Info/Info'; import StationeryItems from './components/OtherPages/Design/Stationery/Items/Items'; import Packaging from './components/OtherPages/Design/Packaging/Packaging'; import PackagingProducts from './components/OtherPages/Design/Packaging/Products'; import PackagingProductsUpgrade from './components/OtherPages/Design/Packaging/upgrade/Products/Products'; import PackagingModifyProduct from './components/OtherPages/Design/Packaging/upgrade/ProductSettings/ProductSettings'; import PackagingCheckout from './components/OtherPages/Design/Packaging/upgrade/Checkout/Checkout'; import Promotional from './components/OtherPages/Design/Promotional/Promotional'; import Profile from './components/OtherPages/Profile/Profile'; import Payment from './components/OtherPages/Payment/Payment'; import store from './store'; import NotFound from './components/UI/NotFound'; import ConfirmOrder from './components/OtherPages/ConfirmOrder/ConfirmOrder'; import Home from './components/OtherPages/Dashboard/Home'; import Dashboard from './components/OtherPages/Dashboard/Dashboard'; import Settings from './components/OtherPages/Dashboard/Settings'; import UserInfo from './components/OtherPages/Dashboard/Settings/UserInfo'; import UserPassword from './components/OtherPages/Dashboard/Settings/UserPassword'; import UserSupport from './components/OtherPages/Dashboard/Settings/Support'; import GoogleLogin from './components/UI/GoogleLogin'; import LogodesignReport from './components/OtherPages/Report/LogoDesign'; // import 'vuetify/src/stylus/app.styl'; import RingLoader from 'vue-spinner/src/RingLoader.vue'; import Vuetify from 'vuetify'; import { Ripple } from 'vuetify/lib/directives'; import VueI18n from 'vue-i18n'; Vue.use(Vuetify, { iconfont: 'md', directives: { Ripple } }); Vue.use(VueRouter); const routes = [ {name: 'about', path: '/about', component: AboutUs, props: true}, {name: 'terms', path: '/terms', component: Terms}, {name: 'profile', path: '/profile', component: Profile, props: true}, { path: '/design', component: Design, props: true, // beforeEnter: (to, from, next) => { // this.$store.dispatch('resetAllStates'); // next(); // }, children: [ { path: 'logo-design', component: LogoDesign, children: [ { name: 'logopackage', path: 'package', component: LogoPackage }, { name: 'logotype', path: 'type', component: LogoType }, { name: 'logofont', path: 'font', component: LogoFont, beforeEnter: (to, from, next) => { next(); // console.log('FROM', from); // console.log('TO', to); // console.log('NEXT', next); // console.log(this.$router); // // next(); // if(from.name === 'logotype' ) { // next(); // } // else { // next('/'); // } } }, { name: 'logoinfo', path: 'info', component: Info } ] }, { path: 'branding', component: Branding, children: [ { name: 'brandingpackage', path: 'package', component: BrandingPackage, }, { name: 'brandinginfo', path: 'info', component: BrandingInfo } ] }, { path: 'social-media', component: SocialMedia, children: [ { name: 'socialmediapackage', path: 'package', component: SocialMediaPackage }, { name: 'socialmediainfo', path: 'info', component: SocialMediaInfo } ] }, { path: 'stationery', component: Stationery, children: [ // { // name: 'stationerypackage', // path: 'package', // component: StationeryPackage // }, // { // name: 'stationeryproducts', // path: 'products', // component: StationeryProducts // }, { name: 'stationeryitems', path: 'items', component: StationeryItems } ] }, { path: 'packaging', component: Packaging, children: [ { name: 'packagingproducts', path: 'products', component: PackagingProducts }, { name: 'packagingproductsupgrade', path: 'updatedproducts', component: PackagingProductsUpgrade }, { name: 'packagingmodifyproduct', path: 'modify-product', component: PackagingModifyProduct }, { name: 'packagingcheckout', path: 'checkout', component: PackagingCheckout } ] }, { name: 'promotionalinfo', path: 'promotional', component: Promotional } ] }, { path: 'confirm-order', component: ConfirmOrder }, { name: 'home', path: '/home', component: Home, // children: [ // { // name: 'dashboardsettings', // path: '/home/settings', // component: Settings // }, // { // name: 'updateUserInfo', // path: '/home/settings/info', // component: UserInfo // }, // { // name: 'updateUserPassword', // path: '/home/settings/password', // component: UserPassword // }, // { // name: 'userSupport', // path: '/home/settings/support', // component: UserSupport // } // ] }, { name: 'dashboardsettings', path: '/home/settings', component: Settings }, { name: 'updateUserInfo', path: '/home/settings/info', component: UserInfo }, { name: 'updateUserPassword', path: '/home/settings/password', component: UserPassword }, { name: 'userSupport', path: '/home/settings/support', component: UserSupport }, { name: 'payment', path: '/payment', component: Payment }, { name: 'root', path: '/', component: HomePage }, { path: '*', component: NotFound } ]; const router = new VueRouter({ routes, linkActiveClass: "active", mode: 'history', // scrollBehavior(to, from, savedPosition) { // if(to.hash) { // return { // selector: to.hash, // offset: {x:0, y:0} // } // } // } }); const waitForStorageToBeReady = async (to, from, next) => { await store.restored; next(); } router.beforeEach(waitForStorageToBeReady); import { i18n, number } from './plugins/i18n'; Vue.mixin({ methods: { number } }); export const app = new Vue({ el: '#app', router, store, i18n }); // require('./react/components/Cover'); // require('./react/components/Test/Test');
#!/bin/bash dieharder -d 203 -g 209 -S 2105767049
<gh_stars>1-10 // @noflow // Does not fully mock members // Add properties & functions as necessary export const clipboard = {writeText: s => {}} export const remote = {BrowserWindow: {}, Menu: {}} export const crashReporter = {} export const shell = {} export const ipcRenderer = {} export const globalShortcut = {} export const session = {} export const dialog = {} export const systemPreferences = {} export const ipcMain = {} export const app = {} export const screen = {} export const BrowserWindow = {} export const Menu = {}
<gh_stars>0 /** * Displays a generic and consistent error message in the UI * @param props Error data */ export function ErrorMessage(props) { if (!props || !props.message) { return null; } // TODO: could add logic here from more props return ( <div className="mt-4 alert alert-danger" role="alert">{props.message}</div> ); }
if [ "${1}." != '-ho.' ]; then echo "Making build/bin/newsamp using generated .cpp source." srcFiles=(./testSamples/newsamp/gen-cpp/txtToBin/src/boma/*.cpp) g++ -std=c++17 -O0 -g -Wall -Wextra testSamples/newsamp/main.cpp ${srcFiles[@]} -ItestSamples/newsamp -o build/bin/newsamp -lhumon else echo "Making build/bin/newsamp using generated .hpp source." g++ -std=c++17 -O0 -g -Wall -Wextra testSamples/newsamp/main.cpp -ItestSamples/newsamp -o build/bin/newsamp -lhumon fi
function xyHeatmap(data,stylename,media,plotpadding,legAlign,yAlign,breaks){ console.log(breaks) var titleYoffset = d3.select("#"+media+"Title").node().getBBox().height var subtitleYoffset=d3.select("#"+media+"Subtitle").node().getBBox().height; // return the series names from the first row of the spreadsheet var seriesNames = Object.keys(data[0]).filter(function(d){ return d != 'date'; }); //Select the plot space in the frame from which to take measurements var frame=d3.select("#"+media+"chart") var plot=d3.select("#"+media+"plot") var yOffset=d3.select("#"+media+"Subtitle").style("font-size"); yOffset=Number(yOffset.replace(/[^\d.-]/g, '')); //Get the width,height and the marginins unique to this chart var w=plot.node().getBBox().width; var h=plot.node().getBBox().height; var margin=plotpadding.filter(function(d){ return (d.name === media); }); margin=margin[0].margin[0] var colours=stylename.fillcolours console.log(colours[0]) console.log(colours) var plotWidth = w-(margin.left+margin.right); var plotHeight = h-(margin.top+margin.bottom); //roll up the data by category var catData = d3.nest() .key(function(d){return d.category;}) .entries(data); console.log("catData ",catData) //Work out the height of each cell var cellHeight=plotHeight/catData.length //Add a group for the labels var cats=plot.append("g") .attr("id",media+"catLabels") .attr("transform",function(d,i){ return "translate("+margin.left+","+(margin.top)+")"; }); //Add the labels var labels = cats.selectAll("g") .data(catData) .enter() .append("g") .attr("id",function(d){ return d.key; }) .attr("transform",function(d,i){ return "translate("+margin.left+","+(margin.top+(cellHeight*i))+")"; }); labels.append("text") .attr("class",media+"subtitle") .text(function(d){return d.key}) //Work out the cell width of each cell now that the lables are added var labelWidth=10+d3.select("#"+media+"catLabels").node().getBBox().width var cellWidth=(plotWidth-labelWidth)/catData[0].values.length //Noww add the groups for each set of rectangles var squares=plot.append("g") .attr("id","squares") var groups = squares.selectAll("g") .data(catData) .enter() .append("g") .attr("id",function(d){ return "group"+d.key; }) .attr("transform",function(d,i){ return "translate("+(labelWidth+margin.left)+","+(margin.top+(i*cellHeight))+")"; }); //Add and colour the rectangles var rects = groups.selectAll("rect") .data(function(d){ return d.values; }) .enter() .append("rect") .attr("id",function(d) {return d.value}) .attr("width",cellWidth) .attr("height",cellHeight) .attr("y",0) .attr("x",function(d,i){ return cellWidth*i; }) .attr("fill",function(d,i){ for (j=0;j<breaks.length+1;j++){ console.log("j=",j) if (d.value<breaks[j]){ return colours[j]; } if (d.value>=breaks[j]&&d.value<breaks[j+1]){ console.log(breaks[j],d.value,breaks[j+1],j,j+1,"position= ",j+1); return colours[j+1]; } } }) //create key var legend = plot.append("g") .attr("id","key") legend.selectAll("rect") .data(colours) .enter() .append("rect") .attr("width",cellWidth) .attr("height",cellHeight/1.4) .attr("x",function(d,i){ return i*labelWidth; }) .attr("fill",function(d){ return d; }); legend.selectAll("text") .data(breaks) .enter() .append("text") .attr("class",media+"subtitle") .attr("x",function(d,i){ return cellWidth+5+(i*labelWidth); }) .attr("y","1em") .text(function(d){ return "up to "+d; }); }
import java.util.Scanner; import java.lang.System; import java.lang.System; import java.util.concurrent.Semaphore; import java.util.LinkedList; import java.util.Queue; class semaphores{ Queue <Process> queue; Process p; Semaphore ss ; private static Semaphore s; public semaphores(){ s = new Semaphore(1) ; queue = new LinkedList<Process>(); } public static Semaphore getSemaphore(){ return s; } public void wait(Semaphore sem ){ sem.acquire(); if(sem.availablePermits() == 0){ queue.add(process); } } public Queue getQProcess(){ return queue; } public void signal(Semaphore sem){ sem.release(); if(sem.availablePermits()==1){ queue.remove(); } } }
def calculate_shares_to_trade(current_portfolio_value, target_percentage, asset_price): target_value = current_portfolio_value * target_percentage target_shares = target_value / asset_price return target_shares # Calculate the number of shares to trade current_portfolio_value = 50000 target_percentage = 0.3 asset_price = 150 shares_to_trade = calculate_shares_to_trade(current_portfolio_value, target_percentage, asset_price) print(shares_to_trade) # Output: 100.0
from bs4 import BeautifulSoup def parse_headings(html): # create a BS object soup = BeautifulSoup(html, 'html.parser') # use BS to extract the headings headings = soup.find_all(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']) # append all headings to a list headings_list = [] for heading in headings: headings_list.append(heading.text) return headings_list
<reponame>xfyre/tapestry-5 // ASM: a very small and fast Java bytecode manipulation framework // Copyright (c) 2000-2011 INRIA, France Telecom // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. Neither the name of the copyright holders nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. package org.apache.tapestry5.internal.plastic.asm.commons; import java.util.Collections; import java.util.Map; /** * A {@link Remapper} using a {@link Map} to define its mapping. * * @author <NAME> */ public class SimpleRemapper extends Remapper { private final Map<String, String> mapping; /** * Constructs a new {@link SimpleRemapper} with the given mapping. * * @param mapping a map specifying a remapping as follows: * <ul> * <li>for method names, the key is the owner, name and descriptor of the method (in the * form &lt;owner&gt;.&lt;name&gt;&lt;descriptor&gt;), and the value is the new method * name. * <li>for invokedynamic method names, the key is the name and descriptor of the method (in * the form .&lt;name&gt;&lt;descriptor&gt;), and the value is the new method name. * <li>for field names, the key is the owner and name of the field (in the form * &lt;owner&gt;.&lt;name&gt;), and the value is the new field name. * <li>for internal names, the key is the old internal name, and the value is the new * internal name. * </ul> */ public SimpleRemapper(final Map<String, String> mapping) { this.mapping = mapping; } /** * Constructs a new {@link SimpleRemapper} with the given mapping. * * @param oldName the key corresponding to a method, field or internal name (see {@link * #SimpleRemapper(Map)} for the format of these keys). * @param newName the new method, field or internal name. */ public SimpleRemapper(final String oldName, final String newName) { this.mapping = Collections.singletonMap(oldName, newName); } @Override public String mapMethodName(final String owner, final String name, final String descriptor) { String remappedName = map(owner + '.' + name + descriptor); return remappedName == null ? name : remappedName; } @Override public String mapInvokeDynamicMethodName(final String name, final String descriptor) { String remappedName = map('.' + name + descriptor); return remappedName == null ? name : remappedName; } @Override public String mapFieldName(final String owner, final String name, final String descriptor) { String remappedName = map(owner + '.' + name); return remappedName == null ? name : remappedName; } @Override public String map(final String key) { return mapping.get(key); } }
def split_into_words(string): result = [] # Split the string into words words = string.split(' ') # add each word to the result list for word in words: result.append(word) return result
#!/usr/bin/env bash set -ex cd "$(dirname "${BASH_SOURCE[0]}")" docker build -t "${IMAGE:-sourcegraph/redis-cache}" .
<reponame>hosituan2012/ant-dashboard<filename>src/app/routes/routes.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { LoginPageComponent } from './login-page/login-page.component'; // import { AccountPageComponent } from './account-page/account-page.component'; import { AccountPageModule } from './account-page/account-page.module'; import {routes} from './routes'; import { RouterModule } from '@angular/router'; import { NgZorroAntdModule } from 'ng-zorro-antd'; import { NzIconModule } from 'ng-zorro-antd/icon'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { SharedModule } from './../shared/shared.module'; import { ExceptionPageComponent } from './exception-page/exception-page.component'; import { PageModule } from './page/page.module'; @NgModule({ declarations: [LoginPageComponent, ExceptionPageComponent], imports: [ CommonModule, // RouterModule.forChild(routes), NgZorroAntdModule, NzIconModule, FormsModule, ReactiveFormsModule, SharedModule, AccountPageModule, PageModule ] }) export class RoutesModule { }
// evmone: Fast Ethereum Virtual Machine implementation // Copyright 2022 The evmone Authors. // SPDX-License-Identifier: Apache-2.0 #include <evmone/eof.hpp> #include <gtest/gtest.h> #include <test/utils/utils.hpp> using namespace evmone; TEST(eof, code_begin) { EOF1Header header1{1, 0}; EXPECT_EQ(header1.code_begin(), 7); EOF1Header header2{10, 0}; EXPECT_EQ(header2.code_begin(), 7); EOF1Header header3{1, 1}; EXPECT_EQ(header3.code_begin(), 10); EOF1Header header4{1, 10}; EXPECT_EQ(header4.code_begin(), 10); } TEST(eof, is_eof_code) { EXPECT_FALSE(is_eof_code(""_hex)); EXPECT_FALSE(is_eof_code("EF"_hex)); EXPECT_FALSE(is_eof_code("EF01"_hex)); EXPECT_FALSE(is_eof_code("EF02"_hex)); EXPECT_FALSE(is_eof_code("EFFF"_hex)); EXPECT_FALSE(is_eof_code("00"_hex)); EXPECT_FALSE(is_eof_code("FE"_hex)); EXPECT_TRUE(is_eof_code("EF00"_hex)); EXPECT_TRUE(is_eof_code("EF00 01 010001 00 00"_hex)); EXPECT_TRUE(is_eof_code("EF00 01 010001 020004 00 00 AABBCCDD"_hex)); EXPECT_TRUE(is_eof_code("EF00 02 ABCFEF"_hex)); } TEST(eof, read_valid_eof1_header) { struct TestCase { std::string code; uint16_t code_size; uint16_t data_size; }; const TestCase test_cases[] = { {"EF00 01 010001 00 00", 1, 0}, {"EF00 01 010006 00 600160005500", 6, 0}, {"EF00 01 010001 020001 00 00 00 AA", 1, 1}, {"EF00 01 010006 020004 00 600160005500 AABBCCDD", 6, 4}, {"EF00 01 010100 021000 00" + std::string(256, '0') + std::string(4096, 'F'), 256, 4096}, }; for (const auto& test_case : test_cases) { const auto code = from_spaced_hex(test_case.code).value(); const auto header = read_valid_eof1_header(bytes_view(code).begin()); EXPECT_EQ(header.code_size, test_case.code_size) << test_case.code; EXPECT_EQ(header.data_size, test_case.data_size) << test_case.code; } }
package com.webrdaniel.collectmydata.utils; import android.content.Context; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; public class KeyboardUtils { public static void hideKeyboard(Context activity, EditText editText) { InputMethodManager inputMethodManager = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE); if (inputMethodManager != null) inputMethodManager.hideSoftInputFromWindow(editText.getWindowToken(), 0); } public static void showKeyboard(Context activity) { InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE); if (inputMethodManager != null) inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); } public static void hideKeyboard(Context activity) { InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE); if(inputMethodManager != null && inputMethodManager.isAcceptingText()) { inputMethodManager.toggleSoftInput(InputMethodManager.HIDE_NOT_ALWAYS, 0); } } }
import { IContext } from 'overmind'; import { createActionsHook, createEffectsHook, // createReactionHook, createStateHook, } from 'overmind-react'; import { state } from './state'; import * as actions from './actions'; import * as effects from './effects'; export const config = { state, actions, effects, }; export type Context = IContext<typeof config>; export const useAppState = createStateHook<Context>(); export const useActions = createActionsHook<Context>(); export const useEffects = createEffectsHook<Context>(); // export const useReaction = createReactionHook<Context>();
import React from 'react'; import ReactTable from 'react-table'; class App extends React.Component { constructor(props) { super(props); this.state = { students: [] } } componentDidMount() { fetch('http://localhost:3000/students') .then(res => res.json()) .then(data => this.setState({ students: data })); } render() { return ( <ReactTable data={this.state.students} columns={[ { Header: 'Name', accessor: 'name' }, { Header: 'Grade', accessor: 'grade' } ]} /> ); } } export default App;
<reponame>wuximing/dsshop import {getList} from '@/api/seckill' import moment from 'moment' export default { data() { return { scrollLeft: 0, TabCur: 0, times: [], list: [], time: '', page: 1, loading: false, loadingType: 'more', }; }, onLoad(options){ let that = this; this.setNav() setTimeout(function() { that.loading = true }, 500) }, //下拉刷新 onPullDownRefresh(){ this.loadData('refresh'); }, //加载更多 onReachBottom(){ this.loadData(); }, methods: { // 设置导航 setNav(){ let time = moment().format('YYYY-MM-DD HH:00:00') if(moment().format('HH')%2 !== 0){ time = moment().subtract(1, 'hour').format('YYYY-MM-DD HH:00:00') } this.time = time this.times = [{ label: `${moment(time, "YYYY-MM-DD HH:00:00").format('H')}:00`, value: moment(time, "YYYY-MM-DD HH:00:00").format('YYYY-MM-DD HH:00:00'), active: true }, { label: `${moment(time, "YYYY-MM-DD HH:00:00").add(2, 'hour').format('H')}:00`, value: moment(time, "YYYY-MM-DD HH:00:00").add(2, 'hour').format('YYYY-MM-DD HH:00:00'), active: false }, { label: `${moment(time, "YYYY-MM-DD HH:00:00").add(4, 'hour').format('H')}:00`, value: moment(time, "YYYY-MM-DD HH:00:00").add(4, 'hour').format('YYYY-MM-DD HH:00:00'), active: false }, { label: `${moment(time, "YYYY-MM-DD HH:00:00").add(6, 'hour').format('H')}:00`, value: moment(time, "YYYY-MM-DD HH:00:00").add(6, 'hour').format('YYYY-MM-DD HH:00:00'), active: false }, { label: `${moment(time, "YYYY-MM-DD HH:00:00").add(8, 'hour').format('H')}:00`, value: moment(time, "YYYY-MM-DD HH:00:00").add(8, 'hour').format('YYYY-MM-DD HH:00:00'), active: false }] this.loadData(); }, async loadData(type='add', loading) { // 下拉刷新 if(type === 'refresh'){ this.page = 1 this.list = []; } //没有更多直接返回 if(type === 'add'){ if(this.loadingType === 'nomore'){ return; } this.loadingType = 'loading'; }else{ this.loadingType = 'more' } const that =this await getList({ limit: 6, sort: 'id', time: this.time, page: this.page },function(res){ that.list = that.list.concat(res.data) if (res.last_page > that.page){ that.page ++ that.loadingType = 'more' } else { that.loadingType = 'nomore' } }) if(type === 'refresh'){ that.loading = false setTimeout(function() { that.loading = true }, 500) if(loading == 1){ uni.hideLoading() }else{ uni.stopPullDownRefresh(); } } }, tabSelect(e) { this.TabCur = e.currentTarget.dataset.id; this.scrollLeft = (e.currentTarget.dataset.id - 1) * 60 this.time = this.times[this.TabCur].value this.loadData('refresh'); } } }