text
stringlengths
1
1.05M
#!/bin/zsh -euo pipefail rm -rf `dirname $0`/../target/*
import windowmanager from '../global'; import { SyncCallback } from '../utils/index'; let callbacks = []; let isReady = false; /** * Executes callback when windowmanager is ready. * @memberof windowmanager * @method * @param {callback} */ windowmanager.onReady = function (callback) { // Check if callback is not a function: if (!(callback && callback.constructor && callback.call && callback.apply)) { throw new Error('onReady expects a function passed as the callback argument!'); } // Check if already ready: if (isReady) { callback(); } // Check to see if callback is already in callbacks: if (callbacks.indexOf(callback) >= 0) { return; } callbacks.push(callback); }; /** * Returns if windowmanager is ready. * @memberof windowmanager * @method * @returns {Boolean} */ windowmanager.isReady = () => { return isReady; }; export default new SyncCallback(function () { isReady = true; for (const callback of callbacks) { callback(); } callbacks = []; });
#!/bin/bash #make sure deps are up to date rm -r node_modules npm install # get current version VERSION=$(node --eval "console.log(require('./package.json').version);") # Build git checkout -b build npm test || exit 1 npm run prepublish git add dist/leaflet-src.js dist/leaflet.js -f # create the bower and component files copyfiles -u 1 build/*.json ./ tin -v $VERSION git add component.json bower.json -f git commit -m "build $VERSION" # Tag and push echo git tag $VERSION # git push --tags git@github.com:leaflet/leaflet.git $VERSION # # # Publish JS modules # npm publish # # # Cleanup # git checkout master # git branch -D build
<reponame>bamboolife/PanelSwitchHelper package com.example.demo; import android.app.Dialog; import android.content.Intent; import android.os.Bundle; import android.view.Gravity; import android.view.View; import android.widget.ExpandableListView; import android.widget.PopupWindow; import android.widget.SimpleExpandableListAdapter; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.databinding.DataBindingUtil; import androidx.fragment.app.DialogFragment; import com.effective.BuildConfig; import com.effective.R; import com.effective.databinding.ActivityMainLayoutBinding; import com.example.demo.anno.ApiContentType; import com.example.demo.anno.ApiResetType; import com.example.demo.anno.ChatPageType; import com.example.demo.scene.api.ContentActivity; import com.example.demo.scene.api.CusPanelActivity; import com.example.demo.scene.api.DefaultHeightPanelActivity; import com.example.demo.scene.api.ResetActivity; import com.example.demo.scene.chat.ChatActivity; import com.example.demo.scene.chat.ChatCusContentScrollActivity; import com.example.demo.scene.chat.ChatDialog; import com.example.demo.scene.chat.ChatDialogFragment; import com.example.demo.scene.chat.ChatFragmentActivity; import com.example.demo.scene.chat.ChatPopupWindow; import com.example.demo.scene.chat.ChatSuperActivity; import com.example.demo.scene.feed.FeedActivity; import com.example.demo.scene.feed.FeedDialogActivity; import com.example.demo.scene.live.huya.PcHuyaLiveActivity; import com.example.demo.scene.live.douyin.PhoneDouyinLiveActivity; import com.example.demo.scene.video.BiliBiliSampleActivity; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class MainActivity extends AppCompatActivity{ private ActivityMainLayoutBinding mBinding; final String activity_title = "聊天场景 Activity实现"; final String activity_1 = "activity 无标题栏"; final String activity_2 = "activity 有标题栏"; final String activity_3 = "activity 自定义标题栏"; final String activity_4 = "activity 有标题栏,状态栏着色"; final String activity_5 = "activity 无标题栏,状态栏透明,不绘制到状态栏"; final String activity_6 = "activity 无标题栏,状态栏透明,绘制到状态栏"; final String fragment_title = "聊天场景 Fragment实现"; final String fragment_1 = "fragment 无标题栏"; final String fragment_2 = "fragment 自定义标题栏"; final String fragment_3 = "fragment 自定义标题栏,状态栏着色"; final String fragment_4 = "fragment 自定义标题栏,状态栏透明"; final String window_title = "聊天场景 other window 实现"; final String window_1 = "DialogFragment"; final String window_2 = "PopupWindow"; final String window_3 = "Dialog"; final String scene_title = "扩展场景"; final String scene_1 = "视频播放(优于b站)"; final String scene_2 = "信息流评论(同微信朋友圈效果)"; // final String scene_2_2 = "信息流评论(同微信朋友圈效果-非dialog)"; final String scene_3 = "PC直播(优于虎牙效果)"; final String scene_4 = "手机直播(优于抖音效果)"; final String scene_5 = "复杂聊天场景"; final String api_content_container_title = "api 内容容器及扩展"; final String api_content_container_1 = "基于 LinearLayout 实现"; final String api_content_container_2 = "基于 RelativeLayout 实现"; final String api_content_container_3 = "基于 FrameLayout 实现"; final String api_content_container_4 = "自定义布局实现"; final String api_define_content_container_scroll_title = "api 内容容器内部布局干预滑动"; final String api_define_content_container_scroll = "内容区域干预子View滑动行为"; final String api_cus_panel_title = "api 面板扩展及默认高度设置"; final String api_cus_panel = "自定义PanelView"; final String api_cus_panel_height = "未获取输入法高度前高度兼容"; final String api_reset_title = "api 自动隐藏软键盘/面板"; final String api_reset_1 = "点击内容容器收起面板(默认处理)"; final String api_reset_2 = "点击空白 View 收起面板"; final String api_reset_3 = "点击原生 RecyclerView 收起面板"; final String api_reset_4 = "点击自定义 RecyclerView 收起面板"; final String api_reset_5 = "关闭点击内容容器收起面板"; final String[] groupStrings = { activity_title, fragment_title, window_title, scene_title, api_content_container_title, api_define_content_container_scroll_title, api_cus_panel_title, api_reset_title}; final String[][] childStrings = { {activity_1,activity_2,activity_3,activity_4,activity_5,activity_6}, {fragment_1,fragment_2,fragment_3,fragment_4}, {window_1,window_2,window_3}, {scene_1,scene_2,scene_3,scene_4,scene_5}, {api_content_container_1,api_content_container_2,api_content_container_3,api_content_container_4}, {api_define_content_container_scroll}, {api_cus_panel,api_cus_panel_height}, {api_reset_1,api_reset_2,api_reset_3,api_reset_4,api_reset_5} }; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main_layout); mBinding.version.setText("version : " + BuildConfig.VERSION); final String TITLE = "TITLE"; List<Map<String, String>> groupData = new ArrayList<Map<String, String>>(); List<List<Map<String, String>>> childData = new ArrayList<List<Map<String, String>>>(); for (int i = 0; i < groupStrings.length; i++) { Map<String, String> curGroupMap = new HashMap<String, String>(); groupData.add(curGroupMap); curGroupMap.put(TITLE, groupStrings[i]); List<Map<String, String>> children = new ArrayList<Map<String, String>>(); for (int j = 0; j < childStrings[i].length; j++) { Map<String, String> curChildMap = new HashMap<String, String>(); children.add(curChildMap); curChildMap.put(TITLE, childStrings[i][j]); } childData.add(children); } SimpleExpandableListAdapter adapter = new SimpleExpandableListAdapter(this, groupData, R.layout.list_parent_title_layout, new String[]{TITLE}, new int[]{R.id.title}, childData, R.layout.list_sub_title_layout, new String[]{TITLE}, new int[]{R.id.title}); mBinding.list.setAdapter(adapter); mBinding.list.setOnChildClickListener(new ExpandableListView.OnChildClickListener() { @Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { switch (childStrings[groupPosition][childPosition]){ case activity_1:{ ChatActivity.start(MainActivity.this, ChatPageType.DEFAULT); break; } case activity_2:{ ChatActivity.start(MainActivity.this, ChatPageType.TITLE_BAR); break; } case activity_3:{ ChatActivity.start(MainActivity.this, ChatPageType.CUS_TITLE_BAR); break; } case activity_4:{ ChatActivity.start(MainActivity.this, ChatPageType.COLOR_STATUS_BAR); break; } case activity_5:{ ChatActivity.start(MainActivity.this, ChatPageType.TRANSPARENT_STATUS_BAR); break; } case activity_6:{ ChatActivity.start(MainActivity.this, ChatPageType.TRANSPARENT_STATUS_BAR_DRAW_UNDER); break; } case fragment_1:{ ChatFragmentActivity.startFragment(MainActivity.this, ChatPageType.DEFAULT); break; } case fragment_2:{ ChatFragmentActivity.startFragment(MainActivity.this, ChatPageType.TITLE_BAR); break; } case fragment_3:{ ChatFragmentActivity.startFragment(MainActivity.this, ChatPageType.COLOR_STATUS_BAR); break; } case fragment_4:{ ChatFragmentActivity.startFragment(MainActivity.this, ChatPageType.TRANSPARENT_STATUS_BAR); break; } case window_1:{ DialogFragment dialogFragment = new ChatDialogFragment(); dialogFragment.showNow(getSupportFragmentManager(), "dialogFragment"); break; } case window_2:{ PopupWindow popupWindow = new ChatPopupWindow(MainActivity.this); popupWindow.showAtLocation(mBinding.getRoot(), Gravity.NO_GRAVITY, 0, 0); break; } case window_3:{ Dialog dialog = new ChatDialog(MainActivity.this); dialog.show(); break; } case scene_1:{ startActivity(new Intent(MainActivity.this, BiliBiliSampleActivity.class)); break; } case scene_2:{ startActivity(new Intent(MainActivity.this, FeedDialogActivity.class)); break; } // case scene_2_2:{ // startActivity(new Intent(MainActivity.this, FeedActivity.class)); // break; // } case scene_3:{ startActivity(new Intent(MainActivity.this, PcHuyaLiveActivity.class)); break; } case scene_4:{ startActivity(new Intent(MainActivity.this, PhoneDouyinLiveActivity.class)); break; } case scene_5:{ startActivity(new Intent(MainActivity.this, ChatSuperActivity.class)); break; } case api_cus_panel:{ startActivity(new Intent(MainActivity.this, CusPanelActivity.class)); break; } case api_cus_panel_height:{ startActivity(new Intent(MainActivity.this, DefaultHeightPanelActivity.class)); break; } case api_define_content_container_scroll:{ ChatCusContentScrollActivity.start(MainActivity.this); break; } case api_content_container_1:{ ContentActivity.start(MainActivity.this, ApiContentType.Linear); break; } case api_content_container_2:{ ContentActivity.start(MainActivity.this, ApiContentType.Relative); break; } case api_content_container_3:{ ContentActivity.start(MainActivity.this, ApiContentType.Frame); break; } case api_content_container_4:{ ContentActivity.start(MainActivity.this, ApiContentType.CUS); break; } case api_reset_1:{ ResetActivity.start(MainActivity.this, ApiResetType.ENABLE); break; } case api_reset_2:{ ResetActivity.start(MainActivity.this, ApiResetType.ENABLE_EmptyView); break; } case api_reset_3:{ ResetActivity.start(MainActivity.this, ApiResetType.ENABLE_RecyclerView); break; } case api_reset_4:{ ResetActivity.start(MainActivity.this, ApiResetType.ENABLE_HookActionUpRecyclerview); break; } case api_reset_5:{ ResetActivity.start(MainActivity.this, ApiResetType.DISABLE); break; } } return true; } }); } }
class Complex: def __init__(self, real, imaginary): self.real = real self.imaginary = imaginary def add(self, other): return Complex(self.real + other.real, self.imaginary + other.imaginary) def subtract(self, other): return Complex(self.real - other.real, self.imaginary - other.imaginary) def multiply(self, other): real = self.real * other.real - self.imaginary * other.imaginary imaginary = self.real * other.imaginary + self.imaginary * other.real return Complex(real, imaginary) def divide(self, other): real = (self.real * other.real + self.imaginary * other.imaginary) \ / (other.real ** 2 + other.imaginary ** 2) imaginary = (self.imaginary * other.real - self.real * other.imaginary) \ / (other.real ** 2 + other.imaginary ** 2) return Complex(real, imaginary)
import web3 from './web3'; import utils from './utils'; export { web3, utils };
#!/bin/bash # monarco-eeprom.sh # HAT ID EEPROM update tool for the Monarco HAT board. # # https://www.monarco.io # https://github.com/monarco/ # # Copyright 2018 REX Controls s.r.o. http://www.rexcontrols.com # Author: Vlastimil Setka # # This file is covered by the BSD 3-Clause License # see LICENSE.txt in the root directory of this project # or <https://opensource.org/licenses/BSD-3-Clause> # set -e GPIO_WR_ENABLE=26 SCRIPTPATH=$(dirname $(readlink -f $0)) echo "Monarco HAT ID EEPROM flash tool, version 1.2" echo "(c) REX Controls 2018, http://www.rexcontrols.com" echo "" if [ $EUID -ne 0 ]; then echo "ERROR: Root user required for Monarco HAT EEPROM ID update, UID $EUID detected! Please run as root. Exiting." 1>&2 exit 3 fi MODE=$1 FILE=$2 if [ "$MODE" == "flash" ]; then if [ ! -f "$FILE" ]; then echo "ERROR: Invalid file '$FILE'" 1>&2 exit 2 fi elif [ "$MODE" == "update" ]; then if [ ! -f /proc/device-tree/hat/uuid ]; then echo "ERROR: Missing HAT ID in /proc" 1>&2 exit 3 fi if [ "$(cat /proc/device-tree/hat/uuid | tr '\0' '\n')" != "fe0f39bf-7c03-4eb6-9a91-df861ae5abcd" ]; then echo "ERROR: Invalid HAT UUID in /proc" 1>&2 exit 3 fi if [[ "$(uname -r)" =~ ^([0-9]).([0-9]+).([0-9]+) ]]; then KERNEL_MAJOR=${BASH_REMATCH[1]} KERNEL_MINOR=${BASH_REMATCH[2]} echo KERNEL_MAJOR: \"$KERNEL_MAJOR\" KERNEL_MINOR: \"$KERNEL_MINOR\" else echo "ERROR: Kernel detection failed" 1>&2 exit 3 fi if [[ "$(cat /proc/device-tree/hat/product_ver | tr '\0' '\n')" =~ 0x([0-9])([0-9][0-9][0-9]) ]]; then HAT_VER_DT=${BASH_REMATCH[1]} HAT_VER_HW=${BASH_REMATCH[2]} echo HAT_VER_DT: \"$HAT_VER_DT\" HAT_VER_HW: \"$HAT_VER_HW\" else echo "ERROR: Invalid HAT PRODUCT_VER in /proc" 1>&2 exit 3 fi if [ "$KERNEL_MAJOR" -eq 4 ] && [ "$KERNEL_MINOR" -eq 4 ]; then if [ "$HAT_VER_DT" == "0" ]; then echo; echo "EEPROM MATCHING KERNEL, OK, EXITING."; echo exit 0 else FILE=$SCRIPTPATH/eeprom-bin/eeprom-v0${HAT_VER_HW}-monarco-hat-1.eep printf "\nEEPROM NEEDS DOWNGRADE, CONTINUE? TYPE yes: " read READ [ "$READ" == "yes" ] || ( echo "Cancelled."; exit 9 ) fi elif ( [ "$KERNEL_MAJOR" -eq 4 ] && [ "$KERNEL_MINOR" -ge 9 ] ) || ( [ "$KERNEL_MAJOR" -gt 4 ] ); then if [ "$HAT_VER_DT" == "1" ]; then echo; echo "EEPROM MATCHING KERNEL, OK, EXITING."; echo exit 0 else FILE=$SCRIPTPATH/eeprom-bin/eeprom-v1${HAT_VER_HW}-monarco-hat-4-9.eep printf "\nEEPROM NEEDS UPGRADE, CONTINUE? TYPE yes: " read READ [ "$READ" == "yes" ] || ( echo "Cancelled."; exit 9 ) fi else echo "ERROR: Unsupported kernel version" 1>&2 exit 3 fi echo else echo "Usage:" echo " $0 update" echo " $0 flash <.eep file>" exit 1 fi modprobe i2c_dev dtoverlay i2c-gpio i2c_gpio_sda=0 i2c_gpio_scl=1 rc=$? if [ $rc != 0 ]; then echo "ERROR: loading dtoverlay i2c-gpio failed (rc $rc), exiting" exit 4 fi if [ ! -e /sys/class/i2c-adapter/i2c-3 ]; then echo "ERROR: Missing i2c-3 device, something failed, exiting" exit 4 fi modprobe at24 if [ ! -d "/sys/class/i2c-adapter/i2c-3/3-0050" ]; then echo "24c32 0x50" > /sys/class/i2c-adapter/i2c-3/new_device fi if [ ! -e "/sys/class/i2c-adapter/i2c-3/3-0050/eeprom" ]; then echo "ERROR: missing eeprom device file, something failed, exiting" exit 5 fi if [ ! -e "/sys/class/gpio/gpio${GPIO_WR_ENABLE}" ]; then echo "${GPIO_WR_ENABLE}" > /sys/class/gpio/export fi echo "out" > /sys/class/gpio/gpio${GPIO_WR_ENABLE}/direction echo "0" > /sys/class/gpio/gpio${GPIO_WR_ENABLE}/value echo "# Writing EEPROM:" dd if=$FILE of=/sys/class/i2c-adapter/i2c-3/3-0050/eeprom status=progress rc=$? if [ $rc != 0 ]; then echo "ERROR: ERITE FAILED (rc $rc), exiting" exit 6 fi echo "" echo "# Checking EEPROM:" TMPFILE=$(mktemp) dd of=$TMPFILE if=/sys/class/i2c-adapter/i2c-3/3-0050/eeprom status=progress rc=$? if [ $rc != 0 ]; then echo "ERROR: ERITE FAILED (rc $rc), exiting" exit 7 fi echo "in" > /sys/class/gpio/gpio${GPIO_WR_ENABLE}/direction RES=0 cmp -n $(stat --printf=%s "$FILE") "$FILE" "$TMPFILE" || RES=$? echo "" if [ $RES != 0 ]; then echo "ERROR: EEPROM Check failed!" exit 10 else echo "EEPROM FLASH FINISHED OK!" echo "REBOOT YOUR DEVICE TO TAKE EFFECT." echo fi
package io.opensphere.shapefile; import java.awt.Component; import java.awt.Dimension; import java.io.File; import java.util.HashSet; import java.util.Set; import io.opensphere.core.importer.ImportCallbackAdapter; import io.opensphere.mantle.data.DataGroupInfo; import io.opensphere.mantle.data.DataTypeInfo; import io.opensphere.mantle.data.impl.DefaultDataGroupInfoAssistant; import io.opensphere.mantle.datasources.IDataSource; import io.opensphere.shapefile.config.v1.ShapeFileSource; /** * The Class ShapeFileDataGroupInfoAssistant. */ public class ShapeFileDataGroupInfoAssistant extends DefaultDataGroupInfoAssistant { /** The controller. */ private final ShapeFileDataSourceController myController; /** * Instantiates a new default data group info assistant. * * @param controller the controller */ public ShapeFileDataGroupInfoAssistant(ShapeFileDataSourceController controller) { super(); myController = controller; } @Override public boolean canDeleteGroup(DataGroupInfo dgi) { return true; } @Override public boolean canReImport(DataGroupInfo dgi) { return true; } @Override public void deleteGroup(DataGroupInfo dgi, Object source) { if (dgi.hasMembers(false)) { DataTypeInfo dti = dgi.getMembers(false).iterator().next(); if (dti instanceof ShapeFileDataTypeInfo) { ShapeFileDataTypeInfo cdti = (ShapeFileDataTypeInfo)dti; myController.removeSource(cdti.getFileSource(), true, myController.getToolbox().getUIRegistry().getMainFrameProvider().get()); } } } @Override public Component getSettingsUIComponent(Dimension preferredSize, DataGroupInfo dataGroup) { if (dataGroup.hasMembers(false)) { DataTypeInfo dti = dataGroup.getMembers(false).iterator().next(); if (dti instanceof ShapeFileDataTypeInfo) { ShapeFileDataTypeInfo cdti = (ShapeFileDataTypeInfo)dti; ShapeFileDataGroupSettingsPanel panel = new ShapeFileDataGroupSettingsPanel(myController, cdti.getFileSource(), dataGroup); panel.setPreferredSize(preferredSize); panel.setMaximumSize(preferredSize); panel.setMinimumSize(preferredSize); panel.setSize(preferredSize); return panel; } } return null; } @Override public void reImport(DataGroupInfo dgi, Object source) { if (dgi.hasMembers(false)) { DataTypeInfo dti = dgi.getMembers(false).iterator().next(); if (dti instanceof ShapeFileDataTypeInfo) { final ShapeFileDataTypeInfo cdti = (ShapeFileDataTypeInfo)dti; final ShapeFileSource shapeFileSource = cdti.getFileSource(); Set<String> namesInUse = new HashSet<>(); for (IDataSource src : myController.getSourceList()) { namesInUse.add(src.getName()); } namesInUse.remove(shapeFileSource.getName()); // Save the source to be re-added on failure. We really only // want the original source to be removed when the replacement // with the new one succeeds. final ShapeFileSource backupSource = new ShapeFileSource(shapeFileSource); myController.removeSource(shapeFileSource, true, myController.getToolbox().getUIRegistry().getMainFrameProvider().get()); // It doesn't matter whether this is a file or a URL, I just // want to know whether it failed. ImportCallbackAdapter callback = new ImportCallbackAdapter() { @Override public void fileImportComplete(boolean success, File file, Object responseObject) { if (!success) { myController.addSource(backupSource); } } }; myController.getFileImporter().importFileSource(shapeFileSource, namesInUse, callback, null); } } } }
class PropertiesParser: def __init__(self, file_path): self.file_path = file_path def load_properties_file(self): """ This method loads the properties/ini file :return: this method returns a dictionary containing the parsed key-value pairs """ properties = {} try: with open(self.file_path, 'r') as file: for line in file: line = line.strip() if line and not line.startswith('#'): key, value = line.split('=') properties[key.strip()] = value.strip() except FileNotFoundError: print(f"File '{self.file_path}' not found.") except Exception as e: print(f"An error occurred while reading the file: {e}") return properties # Usage parser = PropertiesParser('example.properties') parsed_properties = parser.load_properties_file() print(parsed_properties) # Output: {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
#!/bin/sh EXTERNAL_ALL_PACKAGES=$(cat <<EOF all: providers: mpi: - mvapich2@2.3 arch=linux-rhel7-broadwell lapack: - openblas threads=openmp blas: - openblas threasd=openmp buildable: true version: [] EOF ) EXTERNAL_PACKAGES=$(cat <<EOF cmake:: buildable: True variants: ~openssl ~ncurses version: - 3.18.0 externals: - spec: cmake@3.18.0 arch=linux-rhel7-broadwell modules: - cmake/3.18.0 cuda:: buildable: False version: - 10.2.89 externals: - spec: cuda@10.2.89 arch=linux-rhel7-broadwell modules: - cuda/10.2.89 cudnn:: buildable: true version: - 8.0.4.30-10.2-linux-x64 gcc:: buildable: False version: - 8.3.1 externals: - spec: gcc@8.3.1 arch=linux-rhel7-broadwell modules: - gcc/8.3.1 hwloc:: buildable: False version: - 2.0.2 externals: - spec: hwloc@2.0.2 arch=linux-rhel7-broadwell prefix: /usr/lib64/libhwloc.so mvapich2:: buildable: True version: - 2.3 externals: - spec: mvapich2@2.3%gcc@8.3.1 arch=linux-rhel7-broadwell prefix: /usr/tce/packages/mvapich2/mvapich2-2.3-gcc-8.3.1/ openblas:: buildable: True variants: threads=openmp version: - 0.3.10 opencv:: buildable: true variants: build_type=RelWithDebInfo ~calib3d+core~cuda~dnn~eigen+fast-math~features2d~flann~gtk+highgui+imgproc~ipp~ipp_iw~jasper~java+jpeg~lapack~ml~opencl~opencl_svm~openclamdblas~openclamdfft~openmp+png~powerpc~pthreads_pf~python~qt+shared~stitching~superres+tiff~ts~video~videoio~videostab~vsx~vtk+zlib version: - 4.1.0 perl:: buildable: False version: - 5.16.3 externals: - spec: perl@5.16.3 arch=linux-rhel7-broadwell prefix: /usr/bin python:: buildable: True variants: +shared ~readline ~zlib ~bz2 ~lzma ~pyexpat version: - 3.7.2 externals: - spec: python@3.7.2 arch=linux-rhel7-broadwell modules: - python/3.7.2 rdma-core:: buildable: False version: - 20 externals: - spec: rdma-core@20 arch=linux-rhel7-broadwell prefix: /usr EOF )
<filename>studio/schemas/heroSmall.js<gh_stars>0 export default { title: "Hero Small", name: "heroSmall", type: "object", fields: [ { title: "Hero image", name: "image", type: "image", }, { title: "Alt text", name: "alt", type: "string", }, ], };
MATLAB="/usr/local/MATLAB/R2018b" Arch=glnxa64 ENTRYPOINT=mexFunction MAPFILE=$ENTRYPOINT'.map' PREFDIR="/home/hadi/.matlab/R2018b" OPTSFILE_NAME="./setEnv.sh" . $OPTSFILE_NAME COMPILER=$CC . $OPTSFILE_NAME echo "# Make settings for sprdmpF45" > sprdmpF45_mex.mki echo "CC=$CC" >> sprdmpF45_mex.mki echo "CFLAGS=$CFLAGS" >> sprdmpF45_mex.mki echo "CLIBS=$CLIBS" >> sprdmpF45_mex.mki echo "COPTIMFLAGS=$COPTIMFLAGS" >> sprdmpF45_mex.mki echo "CDEBUGFLAGS=$CDEBUGFLAGS" >> sprdmpF45_mex.mki echo "CXX=$CXX" >> sprdmpF45_mex.mki echo "CXXFLAGS=$CXXFLAGS" >> sprdmpF45_mex.mki echo "CXXLIBS=$CXXLIBS" >> sprdmpF45_mex.mki echo "CXXOPTIMFLAGS=$CXXOPTIMFLAGS" >> sprdmpF45_mex.mki echo "CXXDEBUGFLAGS=$CXXDEBUGFLAGS" >> sprdmpF45_mex.mki echo "LDFLAGS=$LDFLAGS" >> sprdmpF45_mex.mki echo "LDOPTIMFLAGS=$LDOPTIMFLAGS" >> sprdmpF45_mex.mki echo "LDDEBUGFLAGS=$LDDEBUGFLAGS" >> sprdmpF45_mex.mki echo "Arch=$Arch" >> sprdmpF45_mex.mki echo "LD=$LD" >> sprdmpF45_mex.mki echo OMPFLAGS= >> sprdmpF45_mex.mki echo OMPLINKFLAGS= >> sprdmpF45_mex.mki echo "EMC_COMPILER=gcc" >> sprdmpF45_mex.mki echo "EMC_CONFIG=optim" >> sprdmpF45_mex.mki "/usr/local/MATLAB/R2018b/bin/glnxa64/gmake" -j 1 -B -f sprdmpF45_mex.mk
def remove_duplicates(arr): seen = set() result = [] for item in arr: if item not in seen: seen.add(item) result.append(item) return result
from typing import List def process_merit_variables(merit_variables: str) -> List[str]: # Split the input string into individual variables variables_list = merit_variables.split() # Filter out variables containing the substring "CTB" filtered_variables = [var for var in variables_list if "CTB" not in var] return filtered_variables
def bubblesort(arr): n = len(arr) for i in range(n): for j in range(0, n-i-1): if arr[j] > arr[j+1] : arr[j], arr[j+1] = arr[j+1], arr[j] arr = [3, 11, 1, 5, 9, 6] bubblesort(arr) print ("Sorted array is:") for i in range(len(arr)): print ("%d" %arr[i])
<reponame>nevermined-io/cryptoarts<gh_stars>1-10 import React from 'react' import { IconProps } from './icons.interface' export const CloseIcon = ({color = 'currentColor', size = 24, onClick}: IconProps & { onClick?: () => void }) => { return ( <div onClick={onClick} style={{ cursor: 'pointer' }}> <svg width={size} height={size} viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M12.59 0L7 5.59L1.41 0L0 1.41L5.59 7L0 12.59L1.41 14L7 8.41L12.59 14L14 12.59L8.41 7L14 1.41L12.59 0Z" style={{fill: color}}/> </svg> </div> ) }
<gh_stars>0 /* funzioni su liste - elementi consecutivi Scrivere un metodo Scala consecutivi che, data una lista generica di n elementi, restituisce la lista di n-1 coppie che contiene tutti gli elementi consecutivi della lista di ingresso. Ad esempio, se in ingresso viene dato List(3,6,5,7), il metodo deve produrre List((3,6),(6,5),(5,7)). Se la lista di ingresso contiene meno di due elementi, la funzione deve produrre la lista vuota. */ object E9 extends App { def consecutivi[T](l: List[T]):List[(T,T)] = { if (l.size<2) Nil else l.sliding(2,1).map(x=>(x(0),x(1))).toList } println(consecutivi(List(3,6,5,7))) println(consecutivi(List(1))) }
<gh_stars>1-10 #!/usr/bin/env node 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = lengthBetween; //----------- THIRD PARTY MODULES ----// var validator = require('validator'); function lengthBetween(options) { return function () { var str = arguments[0] + ''; return validator.isLength(str, options); }; } module.exports = exports['default'];
python cli.py --ckpt_name=moe_model.pickle
""" Code illustration: 8.07 Gravity Simulation Tkinter GUI Application Development Blueprints """ import math import tkinter as tk w = 700 h = 700 root = tk.Tk() root.geometry('{}x{}'.format(w, h)) canvas = tk.Canvas(root, height=h, width=w, bg='black') canvas.pack() root.update_idletasks() class Planet: sun_mass = 1.989 * math.pow(10, 30) G = 6.67 * math.pow(10, -11) def __init__(self, name, mass, distance, radius, color, canvas): self.name = name self.mass = mass self.distance = distance self.radius = radius self.canvas = canvas self.color = color self.angular_velocity = -math.sqrt(self.gravitational_force() / (self.mass * self.distance)) self.oval_id = self.draw_initial_planet() self.scaled_radius = self.radius_scaler(self.radius) self.scaled_distance = self.distance_scaler(self.distance) def distance_scaler(self, value): #[57.91, 4497.1] scaled to [0, self.canvas.winfo_width()/2] return (self.canvas.winfo_width() / 2 - 1) * (value - 1e10) / ( 2.27e11 - 1e10) + 1 def radius_scaler(self, value): #[2439, 6051.8] scaled to [0, self.canvas.winfo_width()/2] return (16 * (value - 2439) / (6052 - 2439)) + 2 def draw_initial_planet(self): screen_dim = self.canvas.winfo_width() scaled_distance = self.distance_scaler(self.distance) scaled_radius = self.radius_scaler(self.radius) y = screen_dim / 2 x = screen_dim / 2 + scaled_distance oval_id = self.canvas.create_oval( x - scaled_radius, y - scaled_radius, x + scaled_radius, y + scaled_radius, fill=self.color, outline=self.color) return oval_id def gravitational_force(self): f = self.G * (self.mass * self.sun_mass) / math.pow(self.distance, 2) return f def angular_position(self, t): theta = (0 + self.angular_velocity * t) return theta def coordinates(self, theta): screen_dim = self.canvas.winfo_width() y = self.scaled_distance * math.sin(theta) + screen_dim / 2 x = self.scaled_distance * math.cos(theta) + screen_dim / 2 return (x, y) def update_location(self, t): theta = self.angular_position(t) x, y = self.coordinates(theta) scaled_radius = self.scaled_radius self.canvas.create_rectangle(x, y, x, y, outline="grey") self.canvas.coords(self.oval_id, x - scaled_radius, y - scaled_radius, x + scaled_radius, y + scaled_radius) class Moon(Planet): earth_mass = 5.973 * math.pow(10, 24) def __init__(self, name, mass, distance, radius, color, canvas, earth): super().__init__(name, mass, distance, radius, color, canvas) self.angular_velocity = -math.sqrt(self.gravitational_force() / (self.mass * self.distance)) self.earth = earth self.scaled_distance = 25 # since distance scaling was based on distance from sun self.scaled_radius = 2 # since moon's scaled radius was getting negative def gravitational_force(self): f = self.G * (self.mass * self.earth_mass) / math.pow(self.distance, 2) return f def coordinates(self, t): theta = self.angular_position(t) earth_x, earth_y = self.earth.coordinates(self.earth.angular_position(t)) dist = self.scaled_distance x = earth_x + dist * math.cos(theta) y = earth_y + dist * math.sin(theta) return (x, y) def update_location(self, t): x, y = self.coordinates(t) scaled_radius = self.scaled_radius self.canvas.create_rectangle(x, y, x, y, outline="red") self.canvas.coords(self.oval_id, x - scaled_radius, y - scaled_radius, x + scaled_radius, y + scaled_radius) #name,mass,distance,radius, color, canvas mercury = Planet("Mercury", 3.302e23, 5.7e10, 2439.7, 'red2', canvas) venus = Planet("Venus", 4.8685e24, 1.08e11, 6051.8, 'CadetBlue1', canvas) earth = Planet("Earth", 5.973e24, 1.49e11, 6378, 'RoyalBlue1', canvas) mars = Planet("Mars", 6.4185e23, 2.27e11, 3396, 'tomato2', canvas) planets = [mercury, venus, earth, mars] moon = Moon("Moon", 7.347e22, 3.844e5, 173, 'white', canvas, earth) time = 0 time_step = 100000 def update_bodies_position(): global time, time_step for planet in planets: planet.update_location(time) moon.update_location(time) time = time + time_step root.after(100, update_bodies_position) update_bodies_position() root.mainloop()
package pages; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; public class StudentGradeDetails extends SideMenu { @FindBy(xpath = "//*[text()='Close']/..") private WebElement buttonClose; }
<filename>2-resources/__DATA-Structures/Data-Structures-Algos-Codebase-master/ALGO/UNSORTED/Range.js //Write a range function that takes two arguments, start and end, and returns an array containing all the numbers from start up to (and including) end. function range( start, end ) { let array = []; for ( let i = start; i <= end; i++ ) { array.push( i ); } return array; } console.log( range( 1, 10 ) );
<reponame>tynes/bmultisig /*! * routelist.js - route list manager * Copyright (c) 2018, The Bcoin Developers (MIT License). * https://github.com/bcoin-org/bcoin */ 'use strict'; const assert = require('bsert'); const Route = require('bweb/lib/route'); // handler for Route const _handler = (req, res) => {}; /** * Route List */ class RouteList { /** * Create a route list. * @constructor */ constructor() { this._get = []; this._post = []; this._put = []; this._del = []; } /** * Get lists by methods. * @private * @param {String} method * @returns {RouteItem[]} */ _handlers(method) { assert(typeof method === 'string'); switch (method.toUpperCase()) { case 'GET': return this._get; case 'POST': return this._post; case 'PUT': return this._put; case 'DELETE': return this._del; default: return null; } } /** * check if request matches route in list * @param {Request} req * @param {Response} res * @returns {Boolean} */ has(req) { const routes = this._handlers(req.method); if (!routes) return false; for (const route of routes) { const params = route.match(req.pathname); if (!params) continue; req.params = params; return true; } return false; } /** * Add a GET route. * @param {String} path * @param {Function} handler */ get(path) { this._get.push(new ListItem(path)); } /** * Add a POST route. * @param {String} path * @param {Function} handler */ post(path) { this._post.push(new ListItem(path)); } /** * Add a PUT route. * @param {String} path * @param {Function} handler */ put(path) { this._put.push(new ListItem(path)); } /** * Add a DELETE route. * @param {String} path * @param {Function} handler */ del(path) { this._del.push(new ListItem(path)); } } /** * Route list item */ class ListItem extends Route { /** * Create a route list item. * @constructor * @ignore */ constructor(path) { super(path, _handler); } } module.exports = RouteList;
#!/usr/bin/bash for i in `cat files-to-beautify.txt` do rm -f $i.orig /cygdrive/c/Users/mpolia/Downloads/AStyle_3.1_windows/AStyle/bin/AStyle.exe --indent=spaces=2 --indent-classes --indent-switches --break-blocks --pad-comma --pad-oper --pad-paren-out --pad-header --add-braces --convert-tabs --style=allman $i done
export class Student { docId: string; name: string; email: string; mobile: string; profileImage: string; fatherName: string; fatherEmail: string; fatherMobile: string; address: string; remarks: string; gender: number; // 0 -> Male | 1 -> Female | 2 -> Other salutation: number; // 0 -> Mr. | 1 -> Prof | 2 -> Dr.. | 3 -> Er. status: number; // 0 -> Lead | 1 -> Inpocess | 2 -> Mature | 3 -> inMature birthDate: Date; appointmentDate: Date; followUpDate: Date; appointmentsHistory: any[]; createdOn: Date; updatedOn: Date; active?: boolean; // optional attributes authId?: string; password?: <PASSWORD>; batch?: any; // current batch previousBatches?: any[]; // previous batches previousBatchesHashcode?: string[]; // previous batches docId } /* sub-collections: appointments, transactions(fee) */
from airflow.operators.sensors import ExternalTaskSensor from airflow.operators.dummy_operator import DummyOperator def create_external_task_sensor(dag_id, task_id, sensor_task_id, main_task_id, main_dag): # Create the ExternalTaskSensor to wait for the specified task from the specified DAG external_sensor = ExternalTaskSensor( task_id=sensor_task_id, external_dag_id=dag_id, external_task_id=task_id, mode='reschedule', poke_interval=60, # Adjust the poke interval as per requirements timeout=7200, # Adjust the timeout as per requirements dag=main_dag ) # Create a dummy task to be triggered after the sensor task completes main_task = DummyOperator( task_id=main_task_id, dag=main_dag ) # Set the main task to be triggered by the sensor task upon successful completion external_sensor >> main_task return external_sensor, main_task
<reponame>Ninjadrian/ProyectoPOO_EquipoA<filename>src/colegio/Curso.java<gh_stars>0 package colegio; /** * @author CesarCuellar */ public class Curso { private String codigo; private String nombre; private int horas; private Docente unDocente; public Curso(String codigo, String nombre, int horas, Docente unDocente) { this.codigo = codigo; this.nombre = nombre; this.horas = horas; this.unDocente = unDocente; } public String getCodigo() { return codigo; } public void setCodigo(String codigo) { this.codigo = codigo; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public int getHoras() { return horas; } public void setHoras(int horas) { this.horas = horas; } public Docente getUnDocente() { return unDocente; } public void setUnDocente(Docente unDocente) { this.unDocente = unDocente; } @Override public String toString() { return this.getNombre(); } }
#!/bin/bash # vim: fdl=1: set -v # prints each statement here, including comments trap read debug # puts a read request after each executable line #=> 1 softwares - appmenu-gtk-module 0 install # for *8192eu* pacman -S appmenu-gtk-module # #=> 1 softwares - appmenu-gtk-module 1 uninstall # pacman -Rs appmenu-gtk-module # true #=> 1 softwares - dkms 0 install # for *8192eu* pacman -S dkms reboot #=> 1 softwares - dkms 0 install # this caused $userresources not to be respected in ~/.xinitrc and poor fonts in gVim pacman -Rs dkms reboot
<filename>src/interceptors/test.interceptor.ts import { CallHandler, ExecutionContext, Injectable, NestInterceptor, RequestTimeoutException, } from '@nestjs/common'; import { Reflector } from '@nestjs/core'; import { Observable, of, throwError, TimeoutError } from 'rxjs'; import { catchError, tap, timeout } from 'rxjs/operators'; import { Cache } from '../cache/cache.entity'; @Injectable() export class MyTestInterceptor implements NestInterceptor { constructor(private reflector: Reflector) {} async intercept( context: ExecutionContext, next: CallHandler, ): Promise<Observable<any>> { const method = context.getHandler(); const cacheTimeInSec = this.reflector.get<number>('cacheTime', method); const controllerName = context.getClass().name; const actionName = method.name; const cachedData = await Cache.findOne({ where: { controllerName, actionName, }, }); if (cachedData) { if (+cachedData.createdAt + cacheTimeInSec + 10000 > +new Date()) { console.log('Used cached data'); return of(JSON.parse(cachedData.dataJson)); } else { console.log('Removing old cache data', cachedData.id); await cachedData.remove(); } } console.log('Generating live data'); return next.handle().pipe( tap(async (data) => { const cache = new Cache(); cache.controllerName = controllerName; cache.actionName = actionName; cache.dataJson = JSON.stringify(data); await cache.save(); }), ); } }
<reponame>Bellian/GGJ2020 import { GameState } from "./gameState"; import { EventListener } from "../eventListener"; import { Server } from "../server"; import { GameStateChoose } from "./gameStateChoose"; const eventListener = EventListener.get(); const joinTime = 30000; export class GameStateJoin extends GameState { //nextState = undefined; nextState = GameStateChoose as any; timerStarted!: number; deviceJoinedCallback: any; tick(delta: number){ if(this.timerStarted === undefined) { return; } const timeLeft = joinTime - (Date.now() - this.timerStarted); if(timeLeft <= 0){ console.log('timer is up, next state'); this.exit(); } } enter(){ window.addEventListener('keydown', (e) => { if(e.key.toLowerCase() === 's'){ this.timerStarted = 0; } }) this.deviceJoinedCallback = eventListener.on('deviceJoined', (device) => { if(!this.timerStarted){ this.startTimer(); } this.server.airConsole.message(device.deviceId, { action: 'updateState', data: { state: 'join', timerStarted: this.timerStarted, duration: joinTime, } }) }); } exit() { eventListener.off('deviceJoined', this.deviceJoinedCallback); this.server.airConsole.setActivePlayers(20); super.exit(); } startTimer(){ console.log('player joined, starting timer'); this.timerStarted = Date.now(); } }
# Generate order of i,j,k indices from Gamess output # Also see the SETLAB routine in inputb.src for the ordering # Example notation: # XYZ # 2X def count_vals(s): x,y,z = 0,0,0 mult = 1 for c,c1 in zip(s,s[1:]+' '): #print 'c,c1',c,c1 if c.isdigit(): continue if c1.isdigit(): mult = int(c1) if c == 'X': x += mult elif c == 'Y': y += mult elif c == 'Z': z += mult mult = 1 if not c.isdigit() and c not in ['S','X','Y','Z']: print 'Error, unknown character',c return x,y,z # order by max number of repeats, then x,y,z def to_string(x,y,z): order = [('x',x),('y',y),('z',z)] order.sort(key=lambda x:x[1],reverse=True) s = '' for c,n in order: s += c*n return s # order by x,y,z def to_string_simple(x,y,z): s = 'x'*x s += 'y'*y s += 'z'*z return s # used in Python script to autogen def create_get_ijk(order_list): out_str = """ def get_ijk(): ijk = [] %s return ijk""" shell_name = ['S', 'P', 'D', 'F', 'G', 'H', 'I'] current_sum = -1 body_str = "" for x,y,z,s in order_list: new_sum = x+y+z if new_sum != current_sum: body_str += ' # '+shell_name[new_sum] + '\n' current_sum = new_sum body_str += ' ijk.append( (%d,%d,%d,"%s") )\n'%(x,y,z,s) return out_str%body_str # generate C++ used in CartesianTensor.h def create_getABC(order_list): out_str = """ template<class T, class Point_t, class Tensor_t, class GGG_t> void CartesianTensor<T,Point_t, Tensor_t, GGG_t>::getABC(int n, int& a, int& b, int& c) { // following Gamess notation switch(n) { %s default: std::cerr <<"CartesianTensor::getABC() - Incorrect index." << std::endl; APP_ABORT(""); break; } } """ shell_name = ['S', 'P', 'D', 'F', 'G', 'H', 'I'] idx = 0 body_str = '' current_sum = -1 for x,y,z,s in order_list: new_sum = x+y+z if new_sum != current_sum: body_str += ' // '+shell_name[new_sum] + '\n' current_sum = new_sum body_str += ' case %d: // %s\n'%(idx,s) body_str += ' a = %d; b = %d; c = %d;\n'%(x,y,z) body_str += ' break;\n' idx += 1 return out_str%body_str # generate C++ used in SoaCartesianTensor.h def create_getABC_SoA(order_list): out_str = """ template<class T> void SoaCartesianTensor<T>::getABC(int n, int& a, int& b, int& c) { // following Gamess notation switch(n) { %s default: std::cerr <<"CartesianTensor::getABC() - Incorrect index." << std::endl; APP_ABORT(""); break; } } """ shell_name = ['S', 'P', 'D', 'F', 'G', 'H', 'I'] idx = 0 body_str = '' current_sum = -1 for x,y,z,s in order_list: new_sum = x+y+z if new_sum != current_sum: body_str += ' // '+shell_name[new_sum] + '\n' current_sum = new_sum body_str += ' case %d: // %s\n'%(idx,s) body_str += ' a = %d; b = %d; c = %d;\n'%(x,y,z) body_str += ' break;\n' idx += 1 return out_str%body_str def create_gms_order_for_pyscf(order_list): pad = ' '*4 out_str = pad + "d_gms_order = {\n%s%s}" body_str = '' current_sum = -1 shell_list = list() for x,y,z,s in order_list: new_sum = x + y + z if new_sum != current_sum: if current_sum >= 0: body_str += 2*pad + '%d:[%s],\n'%(current_sum, ','.join(shell_list)) shell_list = list() current_sum = new_sum expanded_shell_name = to_string(*count_vals(s)) shell_list.append('"%s"'%expanded_shell_name.lower()) body_str += 2*pad + '%d:[%s],\n'%(current_sum, ','.join(shell_list)) return out_str%(body_str,pad) def read_order(fname): order_list = [] already_seen = dict() with open(fname, 'r') as f: for line in f: #line = line.rstrip() if not line: continue order = line[9:16].strip() if order.startswith('1'): order = order[1:] if order not in already_seen: x,y,z = count_vals(order.strip()) order_list.append((x,y,z,order.strip())) already_seen[order] = 1 #new_sum = x + y + z #if new_sum != current_sum: # print ' # ',shell_name[new_sum] # current_sum = new_sum #print order,x,y,z #print " ijk.append('%s')"%to_string(x,y,z) return order_list if __name__ == "__main__": # The file 'order.txt' is taken from Gamess output order_list = read_order('order.txt') # Create get_ijk for gen_cartesian_tensor.py #print create_get_ijk(order_list) # Create getABC for CartesianTensor.h.in #print create_getABC(order_list) # Create getABC for SoaCartesianTensor.h.in #print create_getABC_SoA(order_list) # Create order dictionary for PyscfToQmcpack.py in QMCTools print create_gms_order_for_pyscf(order_list)
#!/usr/bin/env bash # Tags: no-parallel CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) # shellcheck source=../shell_config.sh . "$CURDIR"/../shell_config.sh DATABASE='test_02177' SESSION_ID="$RANDOM$RANDOM$RANDOM" ${CLICKHOUSE_CURL} -sS "${CLICKHOUSE_URL}" -d "DROP DATABASE IF EXISTS ${DATABASE}" ${CLICKHOUSE_CURL} -sS "${CLICKHOUSE_URL}" -d "CREATE DATABASE ${DATABASE}" CLICKHOUSE_URL_PARAMS="database=${DATABASE}" [ -v CLICKHOUSE_LOG_COMMENT ] && CLICKHOUSE_URL_PARAMS="${CLICKHOUSE_URL_PARAMS}&log_comment=${CLICKHOUSE_LOG_COMMENT}" CLICKHOUSE_URL="${CLICKHOUSE_PORT_HTTP_PROTO}://${CLICKHOUSE_HOST}:${CLICKHOUSE_PORT_HTTP}/?${CLICKHOUSE_URL_PARAMS}" ${CLICKHOUSE_CURL} -sS "${CLICKHOUSE_URL}&session_id=${SESSION_ID}" -d 'CREATE TEMPORARY TABLE t AS SELECT currentDatabase()' ${CLICKHOUSE_CURL} -sS "${CLICKHOUSE_URL}&session_id=${SESSION_ID}" -d 'SELECT * FROM t' ${CLICKHOUSE_CURL} -sS "${CLICKHOUSE_URL}" -d "DROP DATABASE ${DATABASE}"
var _pooling2d_8hpp = [ [ "Pooling2d", "_pooling2d_8hpp.xhtml#ae2e93e304cf516841c521e3eaee025cd", null ] ];
def breadth_first_search(graph, root): visited = [] queue = [root] while queue: node = queue.pop(0) if node not in visited: visited.append(node) queue.extend(graph[node]) return visited
def render_item(caption, checked): item_id = "item_id" # Unique identifier for the checkbox item item_name = "item_name" # Name attribute for the checkbox item checked_str = ' checked' if checked else '' # String " checked" if checkbox should be initially checked html_code = f'<input type="checkbox" id="{item_id}" name="{item_name}"{checked_str}>\n' html_code += f'<label for="{item_id}">{caption}</label>' return html_code
<filename>eventuate-tram-consumer-http-micronaut/src/main/java/io/eventuate/tram/consumer/http/EventuateTramHttpMessageConsumerFactory.java package io.eventuate.tram.consumer.http; import io.eventuate.tram.consumer.common.MessageConsumerImplementation; import io.github.resilience4j.circuitbreaker.CircuitBreaker; import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig; import io.github.resilience4j.retry.Retry; import io.github.resilience4j.retry.RetryConfig; import io.micronaut.context.annotation.Factory; import javax.inject.Singleton; import java.time.Duration; @Factory public class EventuateTramHttpMessageConsumerFactory { @Singleton public MessageConsumerImplementation messageConsumerImplementation(CircuitBreaker circuitBreaker, Retry retry, ProxyClient proxyClient, HeartbeatService heartbeatService, EventuateTramHttpMessageController eventuateTramHttpMessageController, HttpConsumerProperties httpConsumerProperties) { return new EventuateTramHttpMessageConsumer(circuitBreaker, retry, proxyClient, heartbeatService, eventuateTramHttpMessageController, httpConsumerProperties.getHttpConsumerBaseUrl()); } @Singleton public CircuitBreaker circuitBreaker(HttpConsumerProperties httpConsumerProperties) { CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig .custom() .minimumNumberOfCalls(httpConsumerProperties.getRequestCircuitBreakerCalls()) .waitDurationInOpenState(Duration.ofMillis(httpConsumerProperties.getRequestCircuitBreakerTimeout())) .build(); return CircuitBreaker.of("HttpConsumerCircuitBreaker", circuitBreakerConfig); } @Singleton public Retry retry(HttpConsumerProperties httpConsumerProperties) { RetryConfig retryConfig = RetryConfig .custom() .waitDuration(Duration.ofMillis(httpConsumerProperties.getRetryRequestTimeout())) .maxAttempts(httpConsumerProperties.getRetryRequests()) .build(); return Retry.of("HttpConsumerRetry", retryConfig); } }
#!/bin/sh export CLASSPATH=../dirA ./user.groovy
<gh_stars>0 /* eslint-disable no-console */ import PropTypes from 'prop-types'; import sinon from 'sinon'; import { expect } from 'chai'; import { shallow } from 'enzyme'; import { Alert } from '../src'; describe('<Alert />', function () { describe('Has default props', function () { const component = shallow(<Alert />); it('Has type of success', function () { expect(component.find('div').hasClass('alert bg-success')).to.equal(true); }); }); it('Has a top div to pass in className', function () { const component = shallow(<Alert className='classname' />); expect(component.find('div.alert').hasClass('classname')).to.equal(true); }); it('Has type of warning', function () { const component = shallow(<Alert type='warning' />); expect(component.find('div').hasClass('alert bg-warning')).to.equal(true); }); it('Has type of info', function () { const component = shallow(<Alert type='info' />); expect(component.find('div').hasClass('alert bg-info')).to.equal(true); }); it('Has type of danger', function () { const component = shallow(<Alert type='danger' />); expect(component.find('div').hasClass('alert bg-danger')).to.equal(true); }); it('Has type of remove', function () { const component = shallow(<Alert type='remove' />); expect(component.find('div').hasClass('alert bg-danger')).to.equal(true); }); it('Has a close button', function () { const component = shallow(<Alert isDismissible={true} />); expect(component.find('button').hasClass('toast-close-button')).to.equal(true); }); it('Is dismissible', function () { const component = shallow(<Alert isDismissible={true} />); expect(component.find('div').hasClass('closable')).to.equal(true); }); it('Has an onClose change', function () { const onClick = sinon.spy(); const component = shallow(<Alert onClose={onClick} isDismissible={true} />); component.find('button').simulate('click'); expect(onClick.calledOnce).to.equal(true); }); before(function () { sinon.stub(console, 'error', (warning) => { throw new Error(warning); }); }); it('Should throw proptype error with invalid type property', function () { expect(function () { shallow(<Alert type='invalid' />); }).to.throw(/Unknown Alert Type/); }); after(function () { console.error.restore(); }); });
package com.muhammadsabeelahmed.entv.Activities; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.os.Handler; import com.muhammadsabeelahmed.entv.Global; import com.muhammadsabeelahmed.entv.R; public class SplashActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); new Handler().postDelayed(new Runnable() { @Override public void run() { Global.changeActivity(SplashActivity.this, new DashboardActivity()); overridePendingTransition(R.anim.fadein, R.anim.fadeout); finish(); } }, 4000); } }
<reponame>lqldev/SpadgerWeather<gh_stars>0 package com.lqldev.spadgerweather; import android.app.ProgressDialog; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.annotation.Nullable; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.TextView; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; import com.lqldev.spadgerweather.db.City; import com.lqldev.spadgerweather.db.County; import com.lqldev.spadgerweather.db.Province; import com.lqldev.spadgerweather.util.HttpUtil; import com.lqldev.spadgerweather.util.Utility; import org.litepal.crud.DataSupport; import java.io.IOException; import java.util.ArrayList; import java.util.List; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; /** * Created by Administrator on 2017-03-17. */ public class ChooseAreaFragment extends android.support.v4.app.Fragment { private static final String TAG = "ChooseAreaFragment"; public static final int LEVEL_PROVINCE = 0; public static final int LEVEL_CITY = 1; public static final int LEVEL_COUNTY = 2; private static final String WEATHER_REQUEST_ADDR = "http://guolin.tech/api/china"; /** * 前端view */ private TextView titleText; private Button backButton; private ListView listView; private ProgressDialog progressDialog; private ArrayAdapter<String> adapter; private List<String> dataList = new ArrayList<>(); /** * 当前各级别数据列表 */ private List<Province> provinceList; private List<City> cityList; private List<County> countyList; //当前点击的选项相应的对象,用于共享给下一级子查询 private Province selectedProvince; private City selectedCity; //当前列表所在级别 private int currentLevel; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.choose_area, container, false); titleText = (TextView) view.findViewById(R.id.title_text); backButton = (Button) view.findViewById(R.id.back_button); listView = (ListView) view.findViewById(R.id.list_view); adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, dataList); listView.setAdapter(adapter); return view; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (currentLevel == LEVEL_PROVINCE) { //当前是省份列表,点击后查询该省的城市信息 selectedProvince = provinceList.get(position); queryCities(); } else if (currentLevel == LEVEL_CITY) { //当前是城市列表,点击后查询该市的县信息 selectedCity = cityList.get(position); queryCounties(); } else if (currentLevel == LEVEL_COUNTY) { //当前是县列表,点击后查询并展示对应的天气信息,并显示 String weatherId = countyList.get(position).getWeatherId(); if (getActivity() instanceof MainActivity) { WeatherActivity.start(getActivity(),weatherId); getActivity().finish(); } else if (getActivity() instanceof WeatherActivity) { WeatherActivity weatherActivity = (WeatherActivity)getActivity(); weatherActivity.drawerLayout.closeDrawers(); weatherActivity.swipeRefresh.setRefreshing(true); weatherActivity.requestWeather(weatherId); } } } }); backButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (currentLevel == LEVEL_COUNTY) { queryCities(); } else if (currentLevel == LEVEL_CITY) { queryProvinces(); } } }); //第一次进来显示显示所有省份 queryProvinces(); } /** * 查询显示省份列表:优先数据库查询,没有再请求网络接口查询 */ private void queryProvinces() { titleText.setText("中国"); backButton.setVisibility(View.GONE); //先查数据库是否有记录 provinceList = DataSupport.findAll(Province.class); if (provinceList.size() > 0) { dataList.clear(); for (Province p : provinceList) { dataList.add(p.getProvinceName()); } adapter.notifyDataSetChanged(); listView.setSelection(0); currentLevel = LEVEL_PROVINCE; } else { //数据库不存在记录,请求网络数据 queryFromSever(WEATHER_REQUEST_ADDR, LEVEL_PROVINCE); } } /** * 查询显示当前省内市级列表:优先数据库查询,没有再请求网络接口查询 */ private void queryCities() { titleText.setText(selectedProvince.getProvinceName()); backButton.setVisibility(View.VISIBLE); //先查数据库是否有记录 cityList = DataSupport.where("provinceid = ?", String.valueOf(selectedProvince.getId())).find(City.class); if (cityList.size() > 0) { dataList.clear(); for (City c : cityList) { dataList.add(c.getCityName()); } adapter.notifyDataSetChanged(); listView.setSelection(0); currentLevel = LEVEL_CITY; } else { //数据库不存在记录,请求网络数据 queryFromSever(WEATHER_REQUEST_ADDR + "/" + selectedProvince.getProvinceCode(), LEVEL_CITY); } } /** * 查询显示当前市内县级列表:优先数据库查询,没有再请求网络接口查询 */ private void queryCounties() { titleText.setText(selectedCity.getCityName()); backButton.setVisibility(View.VISIBLE); //先查数据库是否有记录 countyList = DataSupport.where("cityid = ?", String.valueOf(selectedCity.getId())).find(County.class); if (countyList.size() > 0) { dataList.clear(); for (County c : countyList) { dataList.add(c.getCountyName()); } adapter.notifyDataSetChanged(); listView.setSelection(0); currentLevel = LEVEL_COUNTY; } else { //数据库不存在记录,请求网络数据 queryFromSever(WEATHER_REQUEST_ADDR + "/" + selectedProvince.getProvinceCode() + "/" + selectedCity.getCityCode(), LEVEL_COUNTY); } } private void queryFromSever(final String addr, final int type) { showProgressDialog(); HttpUtil.sendOkHttpRequest(addr, new Callback() { @Override public void onFailure(Call call, IOException e) { //本方法在回调函数中,需要切回UI线程做处理(涉及dialog操作) final String requestAddress = addr; final String errorMsg = e.getMessage(); getActivity().runOnUiThread(new Runnable() { @Override public void run() { closeProgressDialog(); Log.w(TAG, "queryFromSever > onFailure: 请求失败(请求地址:" + requestAddress + " 错误信息:" + requestAddress +")" ); Toast.makeText(getContext(), "加载失败!", Toast.LENGTH_SHORT).show(); } }); } @Override public void onResponse(Call call, Response response) throws IOException { //注意!注意!注意!这里是body的string方法返回里面的内容,不是toString方法(那时对象地内存址了) final String responseText = response.body().string(); boolean result = false; //根据不同类型解释请求结果,并保存到数据库(供queryProvinces、queryCities、queryCounties使用) switch (type) { case LEVEL_PROVINCE: result = Utility.handleProvinceResponse(responseText); break; case LEVEL_CITY: result = Utility.handleCityResponse(responseText, selectedProvince.getId()); break; case LEVEL_COUNTY: result = Utility.handleCountyResponse(responseText, selectedCity.getId()); break; } if (result) { //如果成功,因为本方法属于回调,在okHTTP里面调用,需要切回到ui线程做ui更新操作 getActivity().runOnUiThread(new Runnable() { @Override public void run() { closeProgressDialog(); switch (type) { case LEVEL_PROVINCE: queryProvinces(); break; case LEVEL_CITY: queryCities(); break; case LEVEL_COUNTY: queryCounties(); break; } } }); } else { //本方法在回调函数中,需要切回UI线程做处理(涉及dialog操作) getActivity().runOnUiThread(new Runnable() { @Override public void run() { closeProgressDialog(); Log.w(TAG, "queryFromSever > onResponse: 数据解析异常:" + responseText); Toast.makeText(getContext(), "加载失败!", Toast.LENGTH_SHORT).show(); } }); } } }); } /** * 显示进度条对话框 */ private void showProgressDialog() { if (progressDialog == null) { progressDialog = new ProgressDialog(getActivity()); progressDialog.setMessage("正在加载..."); progressDialog.setCanceledOnTouchOutside(false); } progressDialog.show(); } /** * 关闭进度条对话框 */ private void closeProgressDialog() { progressDialog.dismiss(); } }
describe('App', function () { var Ctrl, scope; beforeEach(module('app')); beforeEach(inject(['$rootScope', '$controller', function ($rootScope, $controller) { scope = $rootScope.$new(); Ctrl = $controller('Main', { $scope: scope }); }])); it('should work', function () { expect(scope.test).toBe('OK'); }); });
import java.io.File; import java.nio.file.*; import java.util.concurrent.TimeUnit; public class DependencyManager { private static final long TIMEOUT_MS = 500; public void waitReload(File moduleDir) { long startTime = System.currentTimeMillis(); long elapsedTime = 0; // Monitor the module directory for changes while (elapsedTime < TIMEOUT_MS) { try { WatchService watchService = FileSystems.getDefault().newWatchService(); Path path = moduleDir.toPath(); path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY); WatchKey key = watchService.poll(TIMEOUT_MS - elapsedTime, TimeUnit.MILLISECONDS); if (key != null) { // Changes detected, trigger reload reloadDependencies(); break; } elapsedTime = System.currentTimeMillis() - startTime; } catch (Exception e) { e.printStackTrace(); } } } private void reloadDependencies() { // Perform the reload logic here System.out.println("Reloading dependencies..."); } public static void main(String[] args) { DependencyManager manager = new DependencyManager(); File moduleDir = new File("path_to_module_directory"); manager.waitReload(moduleDir); } }
require 'json' require 'hashie' require 'etcdv3' class Shja::Db attr_reader :connection def initialize( endpoints: 'http://127.0.0.1:2379' ) @connection = ::Etcdv3.new(endpoints: endpoints) end def save_movie(movie) movie = movie_class.new(movie) unless movie.kind_of?(movie_class) connection.put(to_key(movie), movie.to_json.force_encoding('ASCII-8BIT')) end def get_movie(key) movie = connection.get(to_key(key)).kvs[0]&.value to_movie(movie) end def find_movies(prefix_key) rtn = [] # prefix_key = "movie/#{prefix_key}" # TODO 'movies' should be another place key = to_key(prefix_key) connection.get(key, range_end: key.succ).kvs.each do |movie| movie = to_movie(movie.value) if block_given? yield movie else rtn << movie end end rtn end def years key = "#{prefix}/movie" [].tap do |rtn| connection.get(key, range_end: key.succ, keys_only: true).kvs.each do |k| rtn << k.key.split('/')[2].split('-')[0] end rtn.uniq! rtn.sort! rtn.reverse! end end def to_key(obj) if obj.respond_to?(:key) obj = obj.key end "#{prefix}/#{obj}" end def to_movie(str) if str movie = JSON.load(str.dup.force_encoding('UTF-8')) movie = movie_class.new(movie) else nil end end def prefix raise "Unimplemented" end def movie_class raise "Unimplemented" end def destroy_db! connection.del(prefix, range_end: prefix.succ) end end require 'shja/db/carib'
<gh_stars>10-100 /* Copyright (C) 2001-2003 <NAME> Copyright (C) 2005-2012 Grame Copyright (C) 2013 Samsung Electronics This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #define LOG_TAG "JAMSHMSERVICE" #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <binder/MemoryHeapBase.h> #include <binder/IServiceManager.h> #include <binder/IPCThreadState.h> #include <utils/Log.h> #include <sys/stat.h> #include <sys/socket.h> #include <sys/types.h> #include <sys/un.h> #include <sys/wait.h> #include "BnAndroidShm.h" #include "AndroidShm.h" #include "JackConstants.h" #include <fcntl.h> #include <signal.h> #include <limits.h> #include <errno.h> #include <dirent.h> #include <sys/mman.h> #include <linux/ashmem.h> #include <cutils/ashmem.h> #include "JackError.h" // remove ALOGI log #define jack_d //#define jack_d ALOGI #define jack_error ALOGE #define MEMORY_SIZE 10*1024 namespace android { jack_shmtype_t Shm::jack_shmtype = shm_ANDROID; /* The JACK SHM registry is a chunk of memory for keeping track of the * shared memory used by each active JACK server. This allows the * server to clean up shared memory when it exits. To avoid memory * leakage due to kill -9, crashes or debugger-driven exits, this * cleanup is also done when a new instance of that server starts. */ /* per-process global data for the SHM interfaces */ jack_shm_id_t Shm::registry_id; /* SHM id for the registry */ jack_shm_fd_t Shm::registry_fd = JACK_SHM_REGISTRY_FD; jack_shm_info_t Shm::registry_info = { JACK_SHM_NULL_INDEX, 0, 0, { MAP_FAILED } }; /* pointers to registry header and array */ jack_shm_header_t *Shm::jack_shm_header = NULL; jack_shm_registry_t *Shm::jack_shm_registry = NULL; char Shm::jack_shm_server_prefix[JACK_SERVER_NAME_SIZE] = ""; /* jack_shm_lock_registry() serializes updates to the shared memory * segment JACK uses to keep track of the SHM segments allocated to * all its processes, including multiple servers. * * This is not a high-contention lock, but it does need to work across * multiple processes. High transaction rates and realtime safety are * not required. Any solution needs to at least be portable to POSIX * and POSIX-like systems. * * We must be particularly careful to ensure that the lock be released * if the owning process terminates abnormally. Otherwise, a segfault * or kill -9 at the wrong moment could prevent JACK from ever running * again on that machine until after a reboot. */ #define JACK_SEMAPHORE_KEY 0x282929 #define JACK_SHM_REGISTRY_KEY JACK_SEMAPHORE_KEY #define JACK_REGISTRY_NAME "/jack-shm-registry" int Shm::semid = -1; pthread_mutex_t Shm::mutex = PTHREAD_MUTEX_INITIALIZER; //sp<IAndroidShm> Shm::mShmService; sp<IMemoryHeap> Shm::mShmMemBase[JACK_SHM_HEAP_ENOUGH_COUNT] = {0,}; Shm* Shm::ref = NULL; Shm* Shm::Instantiate() { if(Shm::ref == NULL) { jack_d("shm::Instantiate is called"); Shm::ref = new Shm; //AndroidShm::instantiate(); } return ref; } Shm::Shm() { } Shm::~Shm() { } sp<IAndroidShm> Shm::getShmService(){ return interface_cast<IAndroidShm>(defaultServiceManager()->getService(String16("com.samsung.android.jam.IAndroidShm"))); } //sp<IAndroidShm>& Shm::getShmService() { // if (mShmService.get() == 0) { // sp<IServiceManager> sm = defaultServiceManager(); // sp<IBinder> binder; // do { // binder = sm->getService(String16("com.samsung.android.jam.IAndroidShm")); // if (binder != 0) // break; // ALOGW("CameraService not published, waiting..."); // usleep(500000); // 0.5 s // } while(true); // mShmService = interface_cast<IAndroidShm>(binder); // } // ALOGE_IF(mShmService==0, "no CameraService!?"); // return mShmService; //} void Shm::shm_copy_from_registry (jack_shm_info_t* /*si*/, jack_shm_registry_index_t ) { // not used } void Shm::shm_copy_to_registry (jack_shm_info_t* /*si*/, jack_shm_registry_index_t*) { // not used } void Shm::jack_release_shm_entry (jack_shm_registry_index_t index) { /* the registry must be locked */ jack_shm_registry[index].size = 0; jack_shm_registry[index].allocator = 0; memset (&jack_shm_registry[index].id, 0, sizeof (jack_shm_registry[index].id)); jack_shm_registry[index].fd = 0; } int Shm::release_shm_info (jack_shm_registry_index_t index) { /* must NOT have the registry locked */ if (jack_shm_registry[index].allocator == GetPID()) { if (jack_shm_lock_registry () < 0) { jack_error ("jack_shm_lock_registry fails..."); return -1; } jack_release_shm_entry (index); jack_shm_unlock_registry (); jack_d ("release_shm_info: success!"); } else jack_error ("release_shm_info: error!"); return 0; } char* Shm::shm_addr (unsigned int fd) { if(fd >= JACK_SHM_HEAP_ENOUGH_COUNT) { jack_error("ignore to get memory buffer : index[%d] is too big", fd); return NULL; } sp<IAndroidShm> service = Shm::getShmService(); if(service == NULL){ jack_error("shm service is null"); return NULL; } mShmMemBase[fd] = service->getBuffer(fd); if(mShmMemBase[fd] == NULL) { jack_error("fail to get memory buffer"); return NULL; } return ((char *) mShmMemBase[fd]->getBase()); } int Shm::shm_lock_registry (void) { pthread_mutex_lock (&mutex); return 0; } void Shm::shm_unlock_registry (void) { pthread_mutex_unlock (&mutex); } void Shm::release_shm_entry (jack_shm_registry_index_t index) { /* the registry must be locked */ jack_shm_registry[index].size = 0; jack_shm_registry[index].allocator = 0; memset (&jack_shm_registry[index].id, 0, sizeof (jack_shm_registry[index].id)); } void Shm::remove_shm (jack_shm_id_t *id) { int shm_fd = -1; jack_d("remove_id [%s]",(char*)id); if(!strcmp((const char*)id, JACK_REGISTRY_NAME)) { shm_fd = registry_fd; } else { for (int i = 0; i < MAX_SHM_ID; i++) { if(!strcmp((const char*)id, jack_shm_registry[i].id)) { shm_fd = jack_shm_registry[i].fd; break; } } } if (shm_fd >= 0) { sp<IAndroidShm> service = getShmService(); if(service != NULL) { service->removeShm(shm_fd); } else { jack_error("shm service is null"); } } jack_d ("[APA] jack_remove_shm : ok "); } int Shm::access_registry (jack_shm_info_t * ri) { jack_d("access_registry\n"); /* registry must be locked */ sp<IAndroidShm> service = getShmService(); if(service == NULL){ jack_error("shm service is null"); return EINVAL; } int shm_fd = service->getRegistryIndex(); strncpy (registry_id, JACK_REGISTRY_NAME, sizeof (registry_id) - 1); registry_id[sizeof (registry_id) - 1] = '\0'; if(service->isAllocated(shm_fd) == FALSE) { //jack_error ("Cannot mmap shm registry segment (%s)", // strerror (errno)); jack_error ("Cannot mmap shm registry segment"); //close (shm_fd); ri->ptr.attached_at = NULL; registry_fd = JACK_SHM_REGISTRY_FD; return EINVAL; } ri->fd = shm_fd; registry_fd = shm_fd; ri->ptr.attached_at = shm_addr(shm_fd); if(ri->ptr.attached_at == NULL) { ALOGE("attached pointer is null !"); jack_shm_header = NULL; jack_shm_registry = NULL; return 0; } /* set up global pointers */ ri->index = JACK_SHM_REGISTRY_INDEX; jack_shm_header = (jack_shm_header_t*)(ri->ptr.attached_at); jack_shm_registry = (jack_shm_registry_t *) (jack_shm_header + 1); jack_d("jack_shm_header[%p],jack_shm_registry[%p]", jack_shm_header, jack_shm_registry); //close (shm_fd); // steph return 0; } int Shm::GetUID() { return getuid(); } int Shm::GetPID() { return getpid(); } int Shm::jack_shm_lock_registry (void) { // TODO: replace semaphore to mutex pthread_mutex_lock (&mutex); return 0; } void Shm::jack_shm_unlock_registry (void) { // TODO: replace semaphore to mutex pthread_mutex_unlock (&mutex); return; } void Shm::shm_init_registry () { if(jack_shm_header == NULL) return; /* registry must be locked */ memset (jack_shm_header, 0, JACK_SHM_REGISTRY_SIZE); jack_shm_header->magic = JACK_SHM_MAGIC; //jack_shm_header->protocol = JACK_PROTOCOL_VERSION; jack_shm_header->type = jack_shmtype; jack_shm_header->size = JACK_SHM_REGISTRY_SIZE; jack_shm_header->hdr_len = sizeof (jack_shm_header_t); jack_shm_header->entry_len = sizeof (jack_shm_registry_t); for (int i = 0; i < MAX_SHM_ID; ++i) { jack_shm_registry[i].index = i; } } void Shm::set_server_prefix (const char *server_name) { snprintf (jack_shm_server_prefix, sizeof (jack_shm_server_prefix), "jack-%d:%s:", GetUID(), server_name); } /* create a new SHM registry segment * * sets up global registry pointers, if successful * * returns: 0 if registry created successfully * nonzero error code if unable to allocate a new registry */ int Shm::create_registry (jack_shm_info_t * ri) { jack_d("create_registry\n"); /* registry must be locked */ int shm_fd = 0; strncpy (registry_id, JACK_REGISTRY_NAME, sizeof (registry_id) - 1); registry_id[sizeof (registry_id) - 1] = '\0'; sp<IAndroidShm> service = getShmService(); if(service == NULL){ jack_error("shm service is null"); return EINVAL; } if((shm_fd = service->allocShm(JACK_SHM_REGISTRY_SIZE)) < 0) { jack_error("Cannot create shm registry segment"); registry_fd = JACK_SHM_REGISTRY_FD; return EINVAL; } service->setRegistryIndex(shm_fd); /* set up global pointers */ ri->fd = shm_fd; ri->index = JACK_SHM_REGISTRY_INDEX; registry_fd = shm_fd; ri->ptr.attached_at = shm_addr(shm_fd); ri->size = JACK_SHM_REGISTRY_SIZE; jack_shm_header = (jack_shm_header_t*)(ri->ptr.attached_at); jack_shm_registry = (jack_shm_registry_t *) (jack_shm_header + 1); jack_d("create_registry jack_shm_header[%p], jack_shm_registry[%p]", jack_shm_header, jack_shm_registry); /* initialize registry contents */ shm_init_registry (); //close (shm_fd); // steph return 0; } int Shm::shm_validate_registry () { /* registry must be locked */ if(jack_shm_header == NULL) { return -1; } if ((jack_shm_header->magic == JACK_SHM_MAGIC) //&& (jack_shm_header->protocol == JACK_PROTOCOL_VERSION) && (jack_shm_header->type == jack_shmtype) && (jack_shm_header->size == JACK_SHM_REGISTRY_SIZE) && (jack_shm_header->hdr_len == sizeof (jack_shm_header_t)) && (jack_shm_header->entry_len == sizeof (jack_shm_registry_t))) { return 0; /* registry OK */ } return -1; } int Shm::server_initialize_shm (int new_registry) { int rc; jack_d("server_initialize_shm\n"); if (jack_shm_header) return 0; /* already initialized */ if (shm_lock_registry () < 0) { jack_error ("jack_shm_lock_registry fails..."); return -1; } rc = access_registry (&registry_info); if (new_registry) { remove_shm (&registry_id); rc = ENOENT; } switch (rc) { case ENOENT: /* registry does not exist */ rc = create_registry (&registry_info); break; case 0: /* existing registry */ if (shm_validate_registry () == 0) break; /* else it was invalid, so fall through */ case EINVAL: /* bad registry */ /* Apparently, this registry was created by an older * JACK version. Delete it so we can try again. */ release_shm (&registry_info); remove_shm (&registry_id); if ((rc = create_registry (&registry_info)) != 0) { //jack_error ("incompatible shm registry (%s)", // strerror (errno)); jack_error ("incompatible shm registry"); //#ifndef USE_POSIX_SHM // jack_error ("to delete, use `ipcrm -M 0x%0.8x'", JACK_SHM_REGISTRY_KEY); //#endif } break; default: /* failure return code */ break; } shm_unlock_registry (); return rc; } // here begin the API int Shm::register_server (const char *server_name, int new_registry) { int i, res = 0; jack_d("register_server new_registry[%d]\n", new_registry); set_server_prefix (server_name); if (server_initialize_shm (new_registry)) return ENOMEM; if (shm_lock_registry () < 0) { jack_error ("jack_shm_lock_registry fails..."); return -1; } /* See if server_name already registered. Since server names * are per-user, we register the unique server prefix string. */ for (i = 0; i < MAX_SERVERS; i++) { if (strncmp (jack_shm_header->server[i].name, jack_shm_server_prefix, JACK_SERVER_NAME_SIZE) != 0) continue; /* no match */ if (jack_shm_header->server[i].pid == GetPID()) { res = 0; /* it's me */ goto unlock; } /* see if server still exists */ if (kill (jack_shm_header->server[i].pid, 0) == 0) { res = EEXIST; /* other server running */ goto unlock; } /* it's gone, reclaim this entry */ memset (&jack_shm_header->server[i], 0, sizeof (jack_shm_server_t)); } /* find a free entry */ for (i = 0; i < MAX_SERVERS; i++) { if (jack_shm_header->server[i].pid == 0) break; } if (i >= MAX_SERVERS) { res = ENOSPC; /* out of space */ goto unlock; } /* claim it */ jack_shm_header->server[i].pid = GetPID(); strncpy (jack_shm_header->server[i].name, jack_shm_server_prefix, JACK_SERVER_NAME_SIZE - 1); jack_shm_header->server[i].name[JACK_SERVER_NAME_SIZE - 1] = '\0'; unlock: shm_unlock_registry (); return res; } int Shm::unregister_server (const char * /* server_name */) { int i; if (shm_lock_registry () < 0) { jack_error ("jack_shm_lock_registry fails..."); return -1; } for (i = 0; i < MAX_SERVERS; i++) { if (jack_shm_header->server[i].pid == GetPID()) { memset (&jack_shm_header->server[i], 0, sizeof (jack_shm_server_t)); } } shm_unlock_registry (); return 0; } int Shm::initialize_shm (const char *server_name) { int rc; if (jack_shm_header) return 0; /* already initialized */ set_server_prefix (server_name); if (shm_lock_registry () < 0) { jack_error ("jack_shm_lock_registry fails..."); return -1; } if ((rc = access_registry (&registry_info)) == 0) { if ((rc = shm_validate_registry ()) != 0) { jack_error ("Incompatible shm registry, " "are jackd and libjack in sync?"); } } shm_unlock_registry (); return rc; } int Shm::initialize_shm_server (void) { // not used return 0; } int Shm::initialize_shm_client (void) { // not used return 0; } int Shm::cleanup_shm (void) { int i; int destroy; jack_shm_info_t copy; if (shm_lock_registry () < 0) { jack_error ("jack_shm_lock_registry fails..."); return -1; } for (i = 0; i < MAX_SHM_ID; i++) { jack_shm_registry_t* r; r = &jack_shm_registry[i]; memcpy (&copy, r, sizeof (jack_shm_info_t)); destroy = FALSE; /* ignore unused entries */ if (r->allocator == 0) continue; /* is this my shm segment? */ if (r->allocator == GetPID()) { /* allocated by this process, so unattach and destroy. */ release_shm (&copy); destroy = TRUE; } else { /* see if allocator still exists */ if (kill (r->allocator, 0)) { if (errno == ESRCH) { /* allocator no longer exists, * so destroy */ destroy = TRUE; } } } if (destroy) { int index = copy.index; if ((index >= 0) && (index < MAX_SHM_ID)) { remove_shm (&jack_shm_registry[index].id); release_shm_entry (index); } r->size = 0; r->allocator = 0; } } shm_unlock_registry (); return TRUE; } jack_shm_registry_t * Shm::get_free_shm_info () { /* registry must be locked */ jack_shm_registry_t* si = NULL; int i; for (i = 0; i < MAX_SHM_ID; ++i) { if (jack_shm_registry[i].size == 0) { break; } } if (i < MAX_SHM_ID) { si = &jack_shm_registry[i]; } return si; } int Shm::shmalloc (const char * /*shm_name*/, jack_shmsize_t size, jack_shm_info_t* si) { jack_shm_registry_t* registry; int shm_fd; int rc = -1; char name[SHM_NAME_MAX+1]; if (shm_lock_registry () < 0) { jack_error ("jack_shm_lock_registry fails..."); return -1; } sp<IAndroidShm> service = getShmService(); if(service == NULL){ rc = errno; jack_error("shm service is null"); goto unlock; } if ((registry = get_free_shm_info ()) == NULL) { jack_error ("shm registry full"); goto unlock; } snprintf (name, sizeof (name), "/jack-%d-%d", GetUID(), registry->index); if (strlen (name) >= sizeof (registry->id)) { jack_error ("shm segment name too long %s", name); goto unlock; } if((shm_fd = service->allocShm(size)) < 0) { rc = errno; jack_error ("Cannot create shm segment %s", name); goto unlock; } //close (shm_fd); registry->size = size; strncpy (registry->id, name, sizeof (registry->id) - 1); registry->id[sizeof (registry->id) - 1] = '\0'; registry->allocator = GetPID(); registry->fd = shm_fd; si->fd = shm_fd; si->index = registry->index; si->ptr.attached_at = MAP_FAILED; /* not attached */ rc = 0; /* success */ jack_d ("[APA] jack_shmalloc : ok "); unlock: shm_unlock_registry (); return rc; } void Shm::release_shm (jack_shm_info_t* /*si*/) { // do nothing } void Shm::release_lib_shm (jack_shm_info_t* /*si*/) { // do nothing } void Shm::destroy_shm (jack_shm_info_t* si) { /* must NOT have the registry locked */ if (si->index == JACK_SHM_NULL_INDEX) return; /* segment not allocated */ remove_shm (&jack_shm_registry[si->index].id); release_shm_info (si->index); } int Shm::attach_shm (jack_shm_info_t* si) { jack_shm_registry_t *registry = &jack_shm_registry[si->index]; if((si->ptr.attached_at = shm_addr(registry->fd)) == NULL) { jack_error ("Cannot mmap shm segment %s", registry->id); close (si->fd); return -1; } return 0; } int Shm::attach_lib_shm (jack_shm_info_t* si) { int res = attach_shm(si); if (res == 0) si->size = jack_shm_registry[si->index].size; // Keep size in si struct return res; } int Shm::attach_shm_read (jack_shm_info_t* si) { jack_shm_registry_t *registry = &jack_shm_registry[si->index]; if((si->ptr.attached_at = shm_addr(registry->fd)) == NULL) { jack_error ("Cannot mmap shm segment %s", registry->id); close (si->fd); return -1; } return 0; } int Shm::attach_lib_shm_read (jack_shm_info_t* si) { int res = attach_shm_read(si); if (res == 0) si->size = jack_shm_registry[si->index].size; // Keep size in si struct return res; } int Shm::resize_shm (jack_shm_info_t* si, jack_shmsize_t size) { jack_shm_id_t id; /* The underlying type of `id' differs for SYSV and POSIX */ memcpy (&id, &jack_shm_registry[si->index].id, sizeof (id)); release_shm (si); destroy_shm (si); if (shmalloc ((char *) id, size, si)) { return -1; } return attach_shm (si); } void Shm::jack_shm_copy_from_registry (jack_shm_info_t* si, jack_shm_registry_index_t t) { Shm::Instantiate()->shm_copy_from_registry(si,t); } void Shm::jack_shm_copy_to_registry (jack_shm_info_t* si, jack_shm_registry_index_t* t) { Shm::Instantiate()->shm_copy_to_registry(si,t); } int Shm::jack_release_shm_info (jack_shm_registry_index_t t) { return Shm::Instantiate()->release_shm_info(t); } char* Shm::jack_shm_addr (jack_shm_info_t* si) { if(si != NULL) { return (char*)si->ptr.attached_at; } else { jack_error ("jack_shm_addr : jack_shm_info_t is NULL!"); return NULL; } } int Shm::jack_register_server (const char *server_name, int new_registry) { return Shm::Instantiate()->register_server(server_name, new_registry); } int Shm::jack_unregister_server (const char *server_name) { return Shm::Instantiate()->unregister_server(server_name); } int Shm::jack_initialize_shm (const char *server_name) { return Shm::Instantiate()->initialize_shm(server_name); } int Shm::jack_initialize_shm_server (void) { return Shm::Instantiate()->initialize_shm_server(); } int Shm::jack_initialize_shm_client () { return Shm::Instantiate()->initialize_shm_client(); } int Shm::jack_cleanup_shm (void) { return Shm::Instantiate()->cleanup_shm(); } int Shm::jack_shmalloc (const char *shm_name, jack_shmsize_t size, jack_shm_info_t* result) { return Shm::Instantiate()->shmalloc(shm_name, size, result); } void Shm::jack_release_shm (jack_shm_info_t* si) { Shm::Instantiate()->release_shm(si); } void Shm::jack_release_lib_shm (jack_shm_info_t* si) { Shm::Instantiate()->release_lib_shm(si); } void Shm::jack_destroy_shm (jack_shm_info_t* si) { Shm::Instantiate()->destroy_shm(si); } int Shm::jack_attach_shm (jack_shm_info_t* si) { return Shm::Instantiate()->attach_shm(si); } int Shm::jack_attach_lib_shm (jack_shm_info_t* si) { return Shm::Instantiate()->attach_lib_shm(si); } int Shm::jack_attach_shm_read (jack_shm_info_t* si) { return Shm::Instantiate()->attach_shm_read(si); } int Shm::jack_attach_lib_shm_read (jack_shm_info_t* si) { return Shm::Instantiate()->attach_lib_shm_read(si); } int Shm::jack_resize_shm (jack_shm_info_t* si, jack_shmsize_t size) { return Shm::Instantiate()->resize_shm(si, size); } }; void jack_shm_copy_from_registry (jack_shm_info_t* si, jack_shm_registry_index_t t) { android::Shm::jack_shm_copy_from_registry(si, t); } void jack_shm_copy_to_registry (jack_shm_info_t* si, jack_shm_registry_index_t* t) { android::Shm::jack_shm_copy_to_registry(si, t); } int jack_release_shm_info (jack_shm_registry_index_t t) { return android::Shm::jack_release_shm_info(t); } char* jack_shm_addr (jack_shm_info_t* si) { return android::Shm::jack_shm_addr(si); } int jack_register_server (const char *server_name, int new_registry) { return android::Shm::jack_register_server(server_name, new_registry); } int jack_unregister_server (const char *server_name) { return android::Shm::jack_unregister_server(server_name); } int jack_initialize_shm (const char *server_name) { return android::Shm::jack_initialize_shm(server_name); } int jack_initialize_shm_server (void) { return android::Shm::jack_initialize_shm_server(); } int jack_initialize_shm_client (void) { return android::Shm::jack_initialize_shm_client(); } int jack_cleanup_shm (void) { return android::Shm::jack_cleanup_shm(); } int jack_shmalloc (const char *shm_name, jack_shmsize_t size, jack_shm_info_t* result) { return android::Shm::jack_shmalloc(shm_name, size, result); } void jack_release_shm (jack_shm_info_t* si) { android::Shm::jack_release_shm(si); } void jack_release_lib_shm (jack_shm_info_t* si) { android::Shm::jack_release_lib_shm(si); } void jack_destroy_shm (jack_shm_info_t* si) { android::Shm::jack_destroy_shm(si); } int jack_attach_shm (jack_shm_info_t* si) { return android::Shm::jack_attach_shm(si); } int jack_attach_lib_shm (jack_shm_info_t* si) { return android::Shm::jack_attach_lib_shm(si); } int jack_attach_shm_read (jack_shm_info_t* si) { return android::Shm::jack_attach_shm_read(si); } int jack_attach_lib_shm_read (jack_shm_info_t* si) { return android::Shm::jack_attach_lib_shm_read(si); } int jack_resize_shm (jack_shm_info_t* si, jack_shmsize_t size) { return android::Shm::jack_resize_shm(si, size); } void jack_instantiate() { android::AndroidShm::instantiate(); }
export default { root: 'src', server: { port: 3000 } };
#!/bin/bash if [ "$#" -ne 3 ]; then echo "Usage: ./run_oncloud.sh project-name bucket-name mainclass-basename" echo "Example: ./run_oncloud.sh cloud-training-demos cloud-training-demos JavaProjectsThatNeedHelp" exit fi PROJECT=ps-becfr-bigdata-dev BUCKET=ps2bq_tmp_folder MAIN=com.google.cloud.teleport.templates.MultiPubSubToBigQuery echo "project=$PROJECT bucket=$BUCKET main=$MAIN" export PATH=/usr/lib/jvm/java-8-openjdk-amd64/bin/:$PATH mvn compile -e exec:java \ -Dexec.mainClass=$MAIN \ -Dexec.args="--project=$PROJECT \ --stagingLocation=gs://$BUCKET/staging/ \ --tempLocation=gs://$BUCKET/staging/ \ --runner=DataflowRunner"
import UserService = require('../services/user-service'); import UserModel = require('../models/user-model'); import sequalizeModel = require("../models/user-model"); import Sequelize = require('sequelize'); import token_auth = require('../../JWT_Checker/loginToken') import GroupMemberModel = require('../models/group-member-model') import {environment} from '../../../core/environment' var express = require('express'); var jwt = require('jsonwebtoken'); var bcrypt = require('bcrypt'); var router = express.Router(); var service = new UserService(); router.get('/test', (req, res) => { res.send('Test Passed') }) router.get('/list', token_auth, (req, res) => { service.getList(req.query.searchValue).then((result) => { res.send(result); }).catch((error) => { res.send(error); }); }); router.get('/single', token_auth, (req, res) => { var User = <number>req.query.rowid; service.get(User).then((result) => { res.send(result); }).catch((error) => { res.send(error); }); }); //1/3/18: Robust way to do /create and /login router.post('/single', token_auth, (req, res) => { var request = <App.User>req.body; UserModel.model.findAll({ where: { email: request.email} }).then(user => { if(user.length >= 1) { return res.status(422).json({ message: "User already exists." }) } else { bcrypt.hash(request.password, 10, (err, hash) => { if (err) { return res.status(500).json({ error:err, message:"Hash failed." }) } else { request.password = <PASSWORD> service.create(request) .then(result => { res.status(201).json({ message: "User created." }) }).catch(err => { res.status(500).json({ error:err, message:"User could not be created. Check email to ensure it is in the correct format." }) }); } }) } }).catch(err => { res.status(500).json({ message:"Model could not be created.", error:err }) }) }); router.put('/updatePassword', token_auth, (req, res) => { bcrypt.compare(req.body.oldPassword, req.body.password, (err, result) => { if(err) { //bcrypt hashing error return res.status(500).json({ message: 'bcrypt hash comparison failure. Try again in a few minutes.' }) } else if(result) { bcrypt.hash(req.body.newPassword, 10, (err, hash) => { if(err) { return res.status(500).json({ error:err, message:"Hash failed." }) } else { req.body.password = <PASSWORD> req.body.currUser.password = <PASSWORD> service.update(<App.User>req.body.currUser) .then(result => { res.status(204).json({ message: "Hash compare successful. Password updated.", user: req.body.currUser }) }).catch(err => { res.status(500).json({ error:err, message:"Password could not be changed." }) }) } }) } else if(!result) { return res.status(401).json({ message: 'Authorization failed.' }) } }) }) router.post('/login', (req, res) => { UserModel.model.findAll({ where: {email: req.body.email} }).then(user => { if(user.length < 1) { //If supplied email is not found as a user in the database return res.status(404).json({ message: 'User not found.' }) } bcrypt.compare(req.body.password, user[0].password, (err, result) => { if(err) { //bcrypt hashing error return res.status(500).json({ message: 'bcrypt hash comparison failure. Try again in a few minutes.' }) } else if(result) { //If input pw hash matches db pw hash const login_token = jwt.sign( { email: user[0].email, ID: user[0].ID }, environment.JWT_SECRET_KEY, { expiresIn: "30 days" //expiresIn: "10s" //testing } ); return res.status(200).json({ message: "Token granted.", token: login_token, userID: user[0].ID, admin: user[0].administrator, firstName: user[0].firstName, lastName: user[0].lastName }); } else if(!result) { //If hash comparison does not match return res.status(401).json({ message: 'Authorization failed.' }) } }) }).catch(err => { return res.status(500).json({ error:err }) }); }); //This request generates an API key (JWT) to be used for Google Earth KML files and such. Not to be confused with login "session" JWT above. // router.post('/generatekey', token_auth, (req, res) => { // UserModel.Model.findAll({ // where: {email: req.body.email} // }).then(user => { // if(user.length < 1) { //If supplied email is not found as a user in the database // return res.status(404).json({ // message: 'User not found.' // }) // } // console.log('In Generate Key') // let userID: number = req.body.userID // var d = new Date().getTime(); // var apikey: string // var request = <App.APIKey>req.body; // var uuid = 'xxxxxxxx-xxxx'.replace(/[xy]/g, function(c) // { // var r = (d + Math.random()*16)%16 | 0; // d = Math.floor(d/16); // return (c=='x' ? r : (r&0x3|0x8)).toString(16); // }); // request.apikey = uuid // request.userID = req.body.userID // bcrypt.compare(req.body.password, user[0].password, (err, result) => { // if(err) { //bcrypt hashing error // return res.status(500).json({ // message: 'bcrypt hash comparison failed.'//1/11/18 erroring here // }) // } // if(result) { // const api_token = jwt.sign( // { // email: user[0].email, // firstName: user[0].firstName, //Use first+last name combo instead of ID to ensure key is different than login key // lastName: user[0].lastName // }, // environment.JWT_SECRET_KEY, // { // expiresIn: "30 days" // } // ); // return res.status(200).json({ // message: "Token granted.", // token: api_token, // userID: user[0].ID, // admin: user[0].administrator // }); // } else if(!result) { //If hash comparison does not match // return res.status(401).json({ // message: 'Authorization failed.' // }) // } // }) // }).catch(err => { // return res.status(500).json({ // error:err // }) // }); // }) router.put('/update', token_auth, (req, res) => { var request = <App.User>req.body; service.update(request).then((result) => { res.send(result); }).catch((error) => { res.send(error); }); }); router.delete('/delete', token_auth, (req, res) => { var ID = <number>req.query.ID; service.delete(ID).then((result) => { res.send(result); }).catch((error) => { res.send(error); }); }); export = router;
/* * Copyright 2019 <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 io.openvalidation.antlr.test.transformation; import static io.openvalidation.common.unittesting.astassertion.ModelRootAssertion.assertVariable; import io.openvalidation.antlr.ANTLRExecutor; import io.openvalidation.antlr.test.ANTLRRunner; import io.openvalidation.common.ast.ASTArithmeticalOperator; import io.openvalidation.common.ast.ASTModel; import io.openvalidation.common.data.DataPropertyType; import io.openvalidation.common.data.DataSchema; import io.openvalidation.common.data.DataVariableReference; import io.openvalidation.common.utils.Constants; import io.openvalidation.common.utils.GrammarBuilder; import org.junit.jupiter.api.Test; public class PTArithmeticTransformerTest { @Test void test_simple_addition_with_2_numbers() throws Exception { // assemble String input = GrammarBuilder.create().with(2).ADD(3).AS("varx").getText(); // act ASTModel astActual = ANTLRExecutor.run(input); // assert assertVariable(astActual) .hasSizeOf(1) .first() .hasName("varx") .arithmetic() .hasPreprocessedSource() .operation() .hasSizeOf(2) .first() .staticNumber(2.0) .hasOperator(null) .parentOperation() .second() .staticNumber(3.0) .hasOperator(ASTArithmeticalOperator.Addition); } @Test void test_simple_addition_with_multiple_numbers() throws Exception { // assemble String input = GrammarBuilder.create().with(1).ADD(2).ADD(3).ADD(4).AS("varx").getText(); // act ASTModel astActual = ANTLRExecutor.run(input); // assert assertVariable(astActual) .hasSizeOf(1) .first() .hasName("varx") .arithmetic() .hasPreprocessedSource() .operation() .hasSizeOf(4) .first() .staticNumber(1.0) .hasOperator(null) .parentOperation() .second() .staticNumber(2.0) .hasOperator(ASTArithmeticalOperator.Addition) .parentOperation() .atIndex(2) .staticNumber(3.0) .hasOperator(ASTArithmeticalOperator.Addition) .parentOperation() .atIndex(3) .staticNumber(4.0) .hasOperator(ASTArithmeticalOperator.Addition); } @Test void test_arithmetic_with_number_and_property() throws Exception { // assemble String input = GrammarBuilder.create().with(2).ADD().with("person.age").AS("varname").toString(); String schema = "{person: {age: 25}}"; ANTLRRunner.run( input, schema, r -> { r.variables() .hasSizeOf(1) .first() .hasName("varname") .arithmetic() .hasPreprocessedSource() .operation() .hasSizeOf(2) .first() .staticNumber(2.0) .hasOperator(null) .parentOperation() .second() .hasOperator(ASTArithmeticalOperator.Addition) .propertyValue() .hasPath("person.age"); }); } @Test void test_arithmetic_with_number_and_variable_reference() throws Exception { // assemble // 2 + personsage AS varname String input = GrammarBuilder.create().with(2).ADD().with("personsage").AS("varname").toString(); DataSchema schema = new DataSchema(); schema.addVariable(new DataVariableReference("personsage", DataPropertyType.Decimal)); // act ASTModel ast = ANTLRExecutor.run(input, schema); // assert assertVariable(ast) .hasSizeOf(1) .first() .hasName("varname") .arithmetic() .hasPreprocessedSource() .operation() .hasSizeOf(2) .first() .staticNumber(2.0) .hasOperator(null) .parentOperation() .second() .hasOperator(ASTArithmeticalOperator.Addition) .variableValue() .hasName("personsage"); } @Test void test_arithmetic_with_variable_reference_and_property() throws Exception { // assemble String input = GrammarBuilder.create() .with("person.dog.siblings") .AS("personsage") .PARAGRAPH() .with("person.dog.siblings") .ADD() .with("personsage") .AS("varname") .toString(); String schema = "{person: {dog: {siblings: 10}}}"; ANTLRRunner.run( input, schema, r -> { // assert r.variables() .hasSizeOf(2) .second() .hasName("varname") .arithmetic() .hasPreprocessedSource() .operation() .hasSizeOf(2) .first() .propertyValue() .hasPath("person.dog.siblings") .hasType(DataPropertyType.Decimal) .parentOperation() .second() .hasOperator(ASTArithmeticalOperator.Addition) .variableValue() .hasName("personsage") .hasType(DataPropertyType.Decimal); }); } @Test void test_arithmetic_with_variable_reference_and_semantic_sugar() throws Exception { // assemble String input = GrammarBuilder.create() .with(18) .ADD() .with("das angegebene personsage und so") .AS("varname") .toString(); DataSchema schema = new DataSchema(); schema.addVariable(new DataVariableReference("personsage", DataPropertyType.Decimal)); // act ASTModel ast = ANTLRExecutor.run(input, schema); // assert assertVariable(ast) .hasSizeOf(1) .first() .hasName("varname") .arithmetic() .hasPreprocessedSource() .operation() .hasSizeOf(2) .first() .staticNumber(18.0) // .hasPreprocessedSource("18") .parentOperation() .second() .hasOperator(ASTArithmeticalOperator.Addition) .variableValue() .hasName("personsage") .hasType(DataPropertyType.Decimal); } @Test void test_arithmetic_with_number_and_property_and_semantic_sugar_reference() throws Exception { // assemble String input = GrammarBuilder.create().with("the age").ADD().with("18 years old").AS("newage").toString(); String schema = "{age: 25}"; ANTLRRunner.run( input, schema, r -> { // assert r.variables() .hasSizeOf(1) .first() .hasName("newage") .arithmetic() .hasPreprocessedSource() .operation() .hasSizeOf(2) .first() .hasOperator(null) .propertyValue() .hasPath("age") .parentOperation() .second() .hasOperator(ASTArithmeticalOperator.Addition) .staticNumber(18.0); }); } @Test void grouping_simple_subgroup() throws Exception { // assemble String input = GrammarBuilder.create().with("1").MULTIPLY().with("(2").ADD("3)").AS("newage").toString(); // act ASTModel ast = ANTLRExecutor.run(input); // assert assertVariable(ast) .hasSizeOf(1) .first() .hasName("newage") .arithmeticalOperation() .hasSizeOf(2) .first() .hasOperator(null) .staticNumber(1.0) .parentOperation() .firstSubOperation() .hasOperator(ASTArithmeticalOperator.Multiplication) .hasSizeOf(2) .first() .hasOperator(null) .staticNumber(2.0) .parentOperation() .second() .hasOperator(ASTArithmeticalOperator.Addition) .staticNumber(3.0); } @Test void _grouping_multiple_sub_operations() throws Exception { // assemble String input = GrammarBuilder.create() .with("(10") .POWEROF() .with("2)") .MINUS("Person.Age") .MINUS() .with("(20") .ADD() .with("2)") .AS("variable") .getText(); // act ASTModel ast = ANTLRExecutor.run(input); // assert assertVariable(ast) .hasSizeOf(1) .first() .hasName("variable") .arithmeticalOperation() .hasNoOperator() .hasSizeOf(3) .firstSubOperation() .hasNoOperator() .hasSizeOf(2) .first() .hasNoOperator() .staticNumber(10d) .parentOperation() .second() .hasOperator(ASTArithmeticalOperator.Power) .staticNumber(2d) .parentOperation() .parentOperation() .first() .hasOperator(ASTArithmeticalOperator.Subtraction) .staticString("Person.Age") .parentOperation() .secondSubOperation() .hasOperator(ASTArithmeticalOperator.Subtraction) .hasSizeOf(2) .first() .hasNoOperator() .staticNumber(20d) .parentOperation() .second() .hasOperator(ASTArithmeticalOperator.Addition) .staticNumber(2d); } @Test void grouping_operation_as_first_element_in_suboperation() throws Exception { // assemble String input = GrammarBuilder.create() .with("(1") .POWEROF() .with("2)") .POWEROF() .with("((3") .POWEROF() .with("4)") .POWEROF() .with("5)") .AS("variable") .getText(); // (1^2)^((3^4)^5) // act ASTModel ast = ANTLRExecutor.run(input); // assert assertVariable(ast) .hasSizeOf(1) .first() .hasName("variable") .arithmeticalOperation() .hasNoOperator() .hasSizeOf(2) .firstSubOperation() .hasNoOperator() .hasSizeOf(2) .first() .hasNoOperator() .staticNumber(1d) .parentOperation() .second() .hasOperator(ASTArithmeticalOperator.Power) .staticNumber(2d) .parentOperation() .parentOperation() .secondSubOperation() .hasOperator(ASTArithmeticalOperator.Power) .hasSizeOf(2) .firstSubOperation() .hasNoOperator() .hasSizeOf(2) .first() .hasNoOperator() .staticNumber(3d) .parentOperation() .second() .hasOperator(ASTArithmeticalOperator.Power) .staticNumber(4d) .parentOperation() .parentOperation() .first() .hasOperator(ASTArithmeticalOperator.Power) .staticNumber(5d); } @Test void grouping_triple_nesting_left_aligned() throws Exception { // assemble String input = GrammarBuilder.create() .with("1") .POWEROF() .with("(((2") .POWEROF() .with("3)") .POWEROF() .with("4)") .POWEROF() .with("5)") .AS("variable") .getText(); // act ASTModel ast = ANTLRExecutor.run(input); // assert assertVariable(ast) .hasSizeOf(1) .first() .hasName("variable") .arithmeticalOperation() .hasNoOperator() .hasSizeOf(2) .first() .staticNumber(1d) .parentOperation() .firstSubOperation() .hasOperator(ASTArithmeticalOperator.Power) .hasSizeOf(2) .first() .hasOperator(ASTArithmeticalOperator.Power) .staticNumber(5d) .parentOperation() .firstSubOperation() .hasNoOperator() .hasSizeOf(2) .first() .hasOperator(ASTArithmeticalOperator.Power) .staticNumber(4d) .parentOperation() .firstSubOperation() .hasNoOperator() .hasSizeOf(2) .first() .hasNoOperator() .staticNumber(2d) .parentOperation() .second() .hasOperator(ASTArithmeticalOperator.Power) .staticNumber(3d); } @Test void grouping_triple_nesting_right_aligned() throws Exception { // assemble String input = GrammarBuilder.create() .with("1") .POWEROF() .with("(2") .POWEROF() .with("(3") .POWEROF() .with("(4") .POWEROF() .with("5)))") .AS("variable") .getText(); // act ASTModel ast = ANTLRExecutor.run(input); // assert assertVariable(ast) .hasSizeOf(1) .first() .hasName("variable") .arithmeticalOperation() .hasNoOperator() .hasSizeOf(2) .first() .staticNumber(1d) .parentOperation() .firstSubOperation() .hasOperator(ASTArithmeticalOperator.Power) .hasSizeOf(2) .first() .hasNoOperator() .staticNumber(2d) .parentOperation() .firstSubOperation() .hasOperator(ASTArithmeticalOperator.Power) .hasSizeOf(2) .first() .hasNoOperator() .staticNumber(3d) .parentOperation() .firstSubOperation() .hasOperator(ASTArithmeticalOperator.Power) .hasSizeOf(2) .first() .hasNoOperator() .staticNumber(4d) .parentOperation() .second() .hasOperator(ASTArithmeticalOperator.Power) .staticNumber(5d); } @Test void grouping_triple_nesting_alternating() throws Exception { // assemble // 1 ^ ( ( 2 ^ ( 3 ^ 4 ) ) ^ 5 ) String input = GrammarBuilder.create() .with("1") .POWEROF() .with("((2") .POWEROF() .with("(3") .POWEROF() .with("4))") .POWEROF() .with("5)") .AS("variable") .getText(); // act ASTModel ast = ANTLRExecutor.run(input); // assert assertVariable(ast) .hasSizeOf(1) .first() .hasName("variable") .arithmeticalOperation() .hasNoOperator() .hasSizeOf(2) .first() .staticNumber(1d) .parentOperation() .firstSubOperation() .hasOperator(ASTArithmeticalOperator.Power) .hasSizeOf(2) .firstSubOperation() .hasNoOperator() .hasSizeOf(2) .first() .hasNoOperator() .staticNumber(2d) .parentOperation() .firstSubOperation() .hasOperator(ASTArithmeticalOperator.Power) .hasSizeOf(2) .first() .hasNoOperator() .staticNumber(3d) .parentOperation() .second() .hasOperator(ASTArithmeticalOperator.Power) .staticNumber(4d) .parentOperation() .parentOperation() .parentOperation() .first() .hasOperator(ASTArithmeticalOperator.Power) .staticNumber(5d); } @Test void grouping_with_global_parentheses() throws Exception { // assemble String input = GrammarBuilder.create().with("(1").ADD().with("2)").AS("variable").getText(); // act ASTModel ast = ANTLRExecutor.run(input); // assert assertVariable(ast) .hasSizeOf(1) .first() .hasName("variable") .arithmeticalOperation() .hasNoOperator() .hasSizeOf(2) .first() .staticNumber(1d) .parentOperation() .second() .staticNumber(2d); } @Test void grouping_with_global_parentheses_double() throws Exception { // assemble String input = GrammarBuilder.create().with("((1").ADD().with("2))").AS("variable").getText(); // act ASTModel ast = ANTLRExecutor.run(input); // assert assertVariable(ast) .hasSizeOf(1) .first() .hasName("variable") .arithmeticalOperation() .hasNoOperator() .hasSizeOf(2) .first() .staticNumber(1d) .parentOperation() .second() .staticNumber(2d); } @Test void grouping_with_subgroup_double_parentheses() throws Exception { // assemble String input = GrammarBuilder.create().with("1").MULTIPLY().with("((2").ADD("3))").AS("newage").toString(); // act ASTModel ast = ANTLRExecutor.run(input); // assert assertVariable(ast) .hasSizeOf(1) .first() .hasName("newage") .arithmeticalOperation() .hasSizeOf(2) .first() .hasOperator(null) .staticNumber(1.0) .parentOperation() .firstSubOperation() .hasOperator(ASTArithmeticalOperator.Multiplication) .hasSizeOf(2) .first() .hasOperator(null) .staticNumber(2.0) .parentOperation() .second() .hasOperator(ASTArithmeticalOperator.Addition) .staticNumber(3.0); } @Test void grouping_atom_with_parentheses() throws Exception { // assemble String input = GrammarBuilder.create().with("1").ADD().with("(2)").AS("newage").toString(); // act ASTModel ast = ANTLRExecutor.run(input); // assert assertVariable(ast) .hasSizeOf(1) .first() .hasName("newage") .arithmeticalOperation() .hasSizeOf(2) .first() .hasNoOperator() .staticNumber(1.0) .parentOperation() .second() .hasOperator(ASTArithmeticalOperator.Addition) .staticNumber(2.0); } @Test void grouping_with_global_parentheses_and_redundant_parentheses() throws Exception { // assemble String input = GrammarBuilder.create().with("((1)").ADD().with("(2))").AS("variable").getText(); // act ASTModel ast = ANTLRExecutor.run(input); // assert assertVariable(ast) .hasSizeOf(1) .first() .hasName("variable") .arithmeticalOperation() .hasNoOperator() .hasSizeOf(2) .first() .staticNumber(1d) .parentOperation() .second() .staticNumber(2d); } @Test void grouping_with_global_parentheses_double_and_redundant_parentheses() throws Exception { // assemble String input = GrammarBuilder.create().with("(((1)").ADD().with("(2)))").AS("variable").getText(); // act ASTModel ast = ANTLRExecutor.run(input); // assert assertVariable(ast) .hasSizeOf(1) .first() .hasName("variable") .arithmeticalOperation() .hasNoOperator() .hasSizeOf(2) .first() .staticNumber(1d) .parentOperation() .second() .staticNumber(2d); } @Test void grouping_subgroup_with_variable_directly_after_open_parenthesis() throws Exception { // assemble String input = GrammarBuilder.create().with("1").MULTIPLY().with("(var").ADD("3)").AS("newage").toString(); DataSchema schema = new DataSchema(); schema.addVariable(new DataVariableReference("var", DataPropertyType.Decimal)); // act ASTModel ast = ANTLRExecutor.run(input, schema); // assert assertVariable(ast) .hasSizeOf(1) .first() .hasName("newage") .arithmeticalOperation() .hasSizeOf(2) .first() .hasNoOperator() .staticNumber(1.0) .parentOperation() .firstSubOperation() .hasOperator(ASTArithmeticalOperator.Multiplication) .hasSizeOf(2) .first() .hasNoOperator() .variableValue() .hasType(DataPropertyType.Decimal) .hasName("var") .parentOperation() .second() .hasOperator(ASTArithmeticalOperator.Addition) .staticNumber(3.0); } @Test void grouping_subgroup_with_variable_with_space_after_open_parenthesis() throws Exception { // assemble String input = GrammarBuilder.create() .with("1") .MULTIPLY() .with("( var") .ADD("3)") .AS("newage") .toString(); DataSchema schema = new DataSchema(); schema.addVariable(new DataVariableReference("var", DataPropertyType.Decimal)); // act ASTModel ast = ANTLRExecutor.run(input, schema); // assert assertVariable(ast) .hasSizeOf(1) .first() .hasName("newage") .arithmeticalOperation() .hasSizeOf(2) .first() .hasNoOperator() .staticNumber(1.0) .parentOperation() .firstSubOperation() .hasOperator(ASTArithmeticalOperator.Multiplication) .hasSizeOf(2) .first() .hasNoOperator() .variableValue() .hasType(DataPropertyType.Decimal) .hasName("var") .parentOperation() .second() .hasOperator(ASTArithmeticalOperator.Addition) .staticNumber(3.0); } @Test void grouping_subgroup_with_variable_directly_before_closing_parenthesis() throws Exception { // assemble String input = GrammarBuilder.create().with("1").MULTIPLY().with("(2").ADD("var)").AS("newage").toString(); DataSchema schema = new DataSchema(); schema.addVariable(new DataVariableReference("var", DataPropertyType.Decimal)); // act ASTModel ast = ANTLRExecutor.run(input, schema); // assert assertVariable(ast) .hasSizeOf(1) .first() .hasName("newage") .arithmeticalOperation() .hasSizeOf(2) .first() .hasNoOperator() .staticNumber(1.0) .parentOperation() .firstSubOperation() .hasOperator(ASTArithmeticalOperator.Multiplication) .hasSizeOf(2) .first() .hasNoOperator() .staticNumber(2.0) .parentOperation() .second() .hasOperator(ASTArithmeticalOperator.Addition) .variableValue() .hasType(DataPropertyType.Decimal) .hasName("var"); } @Test void grouping_subgroup_with_variable_with_spacing_before_closing_parenthesis() throws Exception { // assemble String input = GrammarBuilder.create() .with("1") .MULTIPLY() .with("(2") .ADD("var )") .AS("newage") .toString(); DataSchema schema = new DataSchema(); schema.addVariable(new DataVariableReference("var", DataPropertyType.Decimal)); // act ASTModel ast = ANTLRExecutor.run(input, schema); // assert assertVariable(ast) .hasSizeOf(1) .first() .hasName("newage") .arithmeticalOperation() .hasSizeOf(2) .first() .hasNoOperator() .staticNumber(1.0) .parentOperation() .firstSubOperation() .hasOperator(ASTArithmeticalOperator.Multiplication) .hasSizeOf(2) .first() .hasNoOperator() .staticNumber(2.0) .parentOperation() .second() .hasOperator(ASTArithmeticalOperator.Addition) .variableValue() .hasType(DataPropertyType.Decimal) .hasName("var"); } @Test void grouping_with_noise_text() throws Exception { // assemble String input = GrammarBuilder.create() .with("1") .MULTIPLY() .with("hallo(2") .ADD("3 )hallo") .AS("newage") .toString(); DataSchema schema = new DataSchema(); schema.addVariable(new DataVariableReference("var", DataPropertyType.Decimal)); // act ASTModel ast = ANTLRExecutor.run(input, schema); // assert assertVariable(ast) .hasSizeOf(1) .first() .hasName("newage") .arithmeticalOperation() .hasSizeOf(2) .first() .hasOperator(null) .staticNumber(1.0) .parentOperation() .firstSubOperation() .hasOperator(ASTArithmeticalOperator.Multiplication) .hasSizeOf(2) .first() .hasOperator(null) .staticNumber(2.0) .parentOperation() .second() .hasOperator(ASTArithmeticalOperator.Addition) .staticNumber(3.0); } @Test void grouping_subgroup_with_property_directly_after_open_parenthesis() throws Exception { // assemble String input = GrammarBuilder.create() .with("1") .MULTIPLY() .with("(Person.Age") .ADD("3)") .AS("newage") .toString(); String schema = "{Person: {Age: 25}}"; // assert ANTLRRunner.run( input, schema, r -> { r.variables() .hasSizeOf(1) .first() .hasName("newage") .arithmeticalOperation() .hasSizeOf(2) .first() .hasNoOperator() .staticNumber(1.0) .parentOperation() .firstSubOperation() .hasOperator(ASTArithmeticalOperator.Multiplication) .hasSizeOf(2) .first() .hasNoOperator() .propertyValue() .hasType(DataPropertyType.Decimal) .hasPath("Person.Age") .parentOperation() .second() .hasOperator(ASTArithmeticalOperator.Addition) .staticNumber(3.0); }); } @Test void grouping_subgroup_with_property_with_space_after_open_parenthesis() throws Exception { // assemble String input = GrammarBuilder.create() .with("1") .MULTIPLY() .with("( Person.Age") .ADD("3)") .AS("newage") .toString(); String schema = "{Person: {Age: 25}}"; // assert ANTLRRunner.run( input, schema, r -> { r.variables() .hasSizeOf(1) .first() .hasName("newage") .arithmeticalOperation() .hasSizeOf(2) .first() .hasNoOperator() .staticNumber(1.0) .parentOperation() .firstSubOperation() .hasOperator(ASTArithmeticalOperator.Multiplication) .hasSizeOf(2) .first() .hasNoOperator() .propertyValue() .hasType(DataPropertyType.Decimal) .hasPath("Person.Age") .parentOperation() .second() .hasOperator(ASTArithmeticalOperator.Addition) .staticNumber(3.0); }); } @Test void grouping_subgroup_with_property_directly_before_closing_parenthesis() throws Exception { // assemble String input = GrammarBuilder.create() .with("1") .MULTIPLY() .with("(2") .ADD("Person.Age)") .AS("newage") .toString(); String schema = "{Person: {Age: 25}}"; // assert ANTLRRunner.run( input, schema, r -> { r.variables() .hasSizeOf(1) .first() .hasName("newage") .arithmeticalOperation() .hasSizeOf(2) .first() .hasNoOperator() .staticNumber(1.0) .parentOperation() .firstSubOperation() .hasOperator(ASTArithmeticalOperator.Multiplication) .hasSizeOf(2) .first() .hasNoOperator() .staticNumber(2.0) .parentOperation() .second() .hasOperator(ASTArithmeticalOperator.Addition) .propertyValue() .hasType(DataPropertyType.Decimal) .hasPath("Person.Age"); }); } @Test void grouping_subgroup_with_property_with_spacing_before_closing_parenthesis() throws Exception { // assemble String input = GrammarBuilder.create() .with("1") .MULTIPLY() .with("(2") .ADD("Person.Age )") .AS("newage") .toString(); String schema = "{Person: {Age: 25}}"; // assert ANTLRRunner.run( input, schema, r -> { r.variables() .hasSizeOf(1) .first() .hasName("newage") .arithmeticalOperation() .hasSizeOf(2) .first() .hasNoOperator() .staticNumber(1.0) .parentOperation() .firstSubOperation() .hasOperator(ASTArithmeticalOperator.Multiplication) .hasSizeOf(2) .first() .hasNoOperator() .staticNumber(2.0) .parentOperation() .second() .hasOperator(ASTArithmeticalOperator.Addition) .propertyValue() .hasType(DataPropertyType.Decimal) .hasPath("Person.Age"); }); } @Test void static_numbers_in_arithmetic_have_source() throws Exception { String input = GrammarBuilder.create().with(1).MULTIPLY(2).AS("variable").getText(); ASTModel ast = ANTLRExecutor.run(input); assertVariable(ast) .hasSizeOf(1) .first() .arithmeticalOperation() .first() .hasPreprocessedSource("1") .staticNumber() .hasValue(1.0) .hasPreprocessedSource("1") .parentOperation() .second() .hasPreprocessedSource(Constants.MULTIPLY_TOKEN + Constants.KEYWORD_SYMBOL + "MULTIPLY 2") .staticNumber() .hasValue(2.0) .hasPreprocessedSource("2"); } @Test void static_numbers_with_sugar_in_arithmetic_have_source() throws Exception { String input = GrammarBuilder.create().with("1€").MULTIPLY(2).AS("variable").getText(); ASTModel ast = ANTLRExecutor.run(input); assertVariable(ast) .hasSizeOf(1) .first() .arithmeticalOperation() .first() .hasPreprocessedSource("1€") .staticNumber() .hasValue(1.0) .hasPreprocessedSource("1€") .parentOperation() .second() .hasPreprocessedSource(Constants.MULTIPLY_TOKEN + Constants.KEYWORD_SYMBOL + "MULTIPLY 2") .staticNumber() .hasValue(2.0) .hasPreprocessedSource("2"); } @Test void static_strings_in_arithmetic_have_source() throws Exception { String input = GrammarBuilder.create().with("A banana").MULTIPLY("an apple").AS("variable").getText(); ASTModel ast = ANTLRExecutor.run(input); assertVariable(ast) .hasSizeOf(1) .first() .arithmeticalOperation() .first() .hasPreprocessedSource("A banana") .staticString() .hasValue("A banana") .hasPreprocessedSource("A banana") .parentOperation() .second() .hasPreprocessedSource( Constants.MULTIPLY_TOKEN + Constants.KEYWORD_SYMBOL + "MULTIPLY an apple") .staticString() .hasValue("an apple") .hasPreprocessedSource("an apple"); } @Test void static_properties_in_arithmetic_have_source() throws Exception { String input = GrammarBuilder.create() .with("Person.Age") .MULTIPLY("Giraffe.Height") .AS("variable") .getText(); String schema = "{Person: {Age: 25}, Giraffe: {Height: 5}}"; // assert ANTLRRunner.run( input, schema, r -> { r.variables() .hasSizeOf(1) .first() .arithmeticalOperation() .first() .hasPreprocessedSource("Person.Age") .propertyValue() .hasPath("Person.Age") .hasType(DataPropertyType.Decimal) .hasPreprocessedSource("Person.Age") .parentOperation() .second() .hasPreprocessedSource( Constants.MULTIPLY_TOKEN + Constants.KEYWORD_SYMBOL + "MULTIPLY Giraffe.Height") .propertyValue() .hasPath("Giraffe.Height") .hasType(DataPropertyType.Decimal) .hasPreprocessedSource("Giraffe.Height"); }); } @Test void static_variables_in_arithmetic_have_source() throws Exception { String input = GrammarBuilder.create().with("Age").MULTIPLY("Height").AS("variable").getText(); DataSchema schema = new DataSchema(); schema.addVariable(new DataVariableReference("Age", DataPropertyType.Decimal)); schema.addVariable(new DataVariableReference("Height", DataPropertyType.Decimal)); ASTModel ast = ANTLRExecutor.run(input, schema); assertVariable(ast) .hasSizeOf(1) .first() .arithmeticalOperation() .first() .hasPreprocessedSource("Age") .variableValue() .hasName("Age") .hasType(DataPropertyType.Decimal) .hasPreprocessedSource("Age") .parentOperation() .second() .hasPreprocessedSource( Constants.MULTIPLY_TOKEN + Constants.KEYWORD_SYMBOL + "MULTIPLY Height") .variableValue() .hasName("Height") .hasType(DataPropertyType.Decimal) .hasPreprocessedSource("Height"); } @Test void arithmetic_operand_on_right_side_should_be_null_using_spaces() throws Exception { String input = GrammarBuilder.create().with("2").MULTIPLY(" ").AS("variable").toString(); ASTModel ast = ANTLRExecutor.run(input); assertVariable(ast) .hasSizeOf(1) .first() .arithmeticalOperation() .first() .staticNumber(2.0) .parentOperation() .second() .hasPreprocessedSource() .hasNoOperand(); } @Test void arithmetic_operand_on_right_side_should_be_null_using_UNIX_NL() throws Exception { String input = GrammarBuilder.create().with("2").MULTIPLY("\n\n").AS("variable").toString(); ASTModel ast = ANTLRExecutor.run(input); assertVariable(ast) .hasSizeOf(1) .first() .arithmeticalOperation() .first() .staticNumber(2.0) .parentOperation() .second() .hasPreprocessedSource() .hasNoOperand(); } @Test void arithmetic_operand_on_right_side_should_be_null_using_UNIX_NL_and_spaces() throws Exception { String input = GrammarBuilder.create().with("2").MULTIPLY(" \n \n ").AS("variable").toString(); ASTModel ast = ANTLRExecutor.run(input); assertVariable(ast) .hasSizeOf(1) .first() .arithmeticalOperation() .first() .staticNumber(2.0) .parentOperation() .second() .hasPreprocessedSource() .hasNoOperand(); } @Test void arithmetic_operand_on_right_side_should_be_null_using_WINDOWS_NL_and_spaces() throws Exception { String input = GrammarBuilder.create().with("2").MULTIPLY(" \r\n \r\n ").AS("variable").toString(); ASTModel ast = ANTLRExecutor.run(input); assertVariable(ast) .hasSizeOf(1) .first() .arithmeticalOperation() .first() .staticNumber(2.0) .parentOperation() .second() .hasPreprocessedSource() .hasNoOperand(); } }
#!/bin/bash function stop_task_wrong_arg() { run_dm_ctl $WORK_DIR "127.0.0.1:$MASTER_PORT" \ "stop-task" \ "stop-task \[-s source ...\] <task-name | task-file> \[flags\]" 1 }
<reponame>hugleMr/Eazax-cases import RemoteSpine from "../../../eazax-ccc/components/remote/RemoteSpine"; import Toast from "../../../scripts/common/components/global/Toast"; const { ccclass, property } = cc._decorator; @ccclass export default class Case_RemoteSpine extends cc.Component { @property(RemoteSpine) protected remoteSpine: RemoteSpine = null; @property(cc.EditBox) protected urlEditorBox: cc.EditBox = null; @property(cc.EditBox) protected skinEditorBox: cc.EditBox = null; @property(cc.EditBox) protected animEditorBox: cc.EditBox = null; protected onLoad() { this.init(); this.registerEvent(); } protected start() { this.reloadTexture(); } protected registerEvent() { this.urlEditorBox.node.on('editing-did-ended', this.onUrlEditorBoxEnded, this); this.skinEditorBox.node.on('editing-did-ended', this.onSkinEditorBoxEnded, this); this.animEditorBox.node.on('editing-did-ended', this.onAnimEditorBoxEnded, this); } protected onUrlEditorBoxEnded(editorBox: cc.EditBox) { this.reloadTexture(); } protected onSkinEditorBoxEnded(editorBox: cc.EditBox) { const skin = this.skinEditorBox.string; this.remoteSpine.skeleton.setSkin(skin); } protected onAnimEditorBoxEnded(editorBox: cc.EditBox) { const anim = this.animEditorBox.string; this.remoteSpine.skeleton.animation = anim; } protected init() { this.skinEditorBox.string = this.remoteSpine.defaultSkin; this.animEditorBox.string = this.remoteSpine.defaultAnimation; } protected async reloadTexture() { let url = this.urlEditorBox.string; if (url !== '') { Toast.show('🌀 正在加载远程骨骼...'); } this.remoteSpine.set(null); const result = await this.remoteSpine.load(url); if (result.url !== '') { if (result.loaded) { Toast.show('🎉 远程骨骼加载成功'); } else { Toast.show('❌ 远程骨骼加载失败'); } } } }
<gh_stars>1-10 /* * 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 com.alipay.sofa.ark.container.test; import com.alipay.sofa.ark.container.ArkContainer; import com.alipay.sofa.ark.spi.pipeline.PipelineContext; import com.alipay.sofa.ark.spi.service.classloader.ClassLoaderService; import java.net.URL; /** * @author qilong.zql * @since 0.1.0 */ public class TestHelper { private final static String MOCK_BIZ_IDENTITY = "Mock Biz:Mock Version"; private ArkContainer arkContainer; public TestHelper(Object object) { this.arkContainer = (ArkContainer) object; } public ClassLoader createTestClassLoader() { PipelineContext context = arkContainer.getPipelineContext(); URL[] classpath = context.getLaunchCommand().getClasspath(); ClassLoaderService classloaderService = arkContainer.getArkServiceContainer().getService( ClassLoaderService.class); return new TestClassLoader(MOCK_BIZ_IDENTITY, classpath, classloaderService.getSystemClassLoader()); } public boolean isStarted() { return arkContainer.isStarted(); } }
#!/usr/bin/env bash saved=("$@") while test $# -gt 0; do case "$1" in --help|-h) printf "Usage:\ngenerateredefinesfile.sh <filename> <jump instruction for the platform> <prefix of what is being mapped from> <prefix of what is being mapped to>\n" exit 1;; esac shift done set -- "${saved[@]}" jump="$2" prefix1="$3" prefix2="$4" while read -r line; do # Skip empty lines and comment lines starting with semicolon if [[ "$line" =~ ^\;.*$|^[[:space:]]*$ ]]; then continue fi # Remove the CR character in case the sources are mapped from # a Windows share and contain CRLF line endings line="${line//$'\r'/}" # Only process the entries that begin with "#" if [[ "$line" =~ ^#.*$ ]]; then line="${line//#/}" printf "LEAF_ENTRY %s%s, _TEXT\n" "$prefix1" "$line" printf " %s EXTERNAL_C_FUNC(%s%s)\n" "$jump" "$prefix2" "$line" printf "LEAF_END %s%s, _TEXT\n\n" "$prefix1" "$line" fi done < "$1"
# Program to print the first 20 prime numbers def is_prime(num): # Base case if num == 1: return False elif num == 2: return True elif num % 2 == 0: return False # Iterate from 3 to the sqrt of number i = 3 while(i * i <= num): if num % i == 0: return False i = i + 2 return True # Print the first 20 prime numbers n = 2 count = 0 while count < 20: if is_prime(n): print(n, end=' ', flush=True) count += 1 n += 1
<filename>scrapy_do/client/commands.py #------------------------------------------------------------------------------- # Author: <NAME> <<EMAIL>> # Date: 24.01.2018 # # Licensed under the 3-Clause BSD License, see the LICENSE file for details. #------------------------------------------------------------------------------- import sys import os from scrapy_do.client.archive import build_project_archive from scrapy_do.utils import exc_repr from collections import namedtuple #------------------------------------------------------------------------------- Command = namedtuple('Command', [ 'arg_setup', 'arg_process', 'url_setup', 'response_parse', 'method' ]) #------------------------------------------------------------------------------- def url_append(path): """ Return a function computing an URL by appending the path to the appropriate argument """ return lambda args: args.url + path #------------------------------------------------------------------------------- # Status #------------------------------------------------------------------------------- def status_arg_setup(subparsers): parser = subparsers.add_parser('status', help='Status of the service') parser.set_defaults(command='status') def status_rsp_parse(rsp): data = [] for k, v in rsp.items(): data.append([k, v]) headers = ['key', 'value'] return {'headers': headers, 'data': data} status_cmd = Command( status_arg_setup, lambda x: {}, url_append('/status.json'), status_rsp_parse, 'GET') #------------------------------------------------------------------------------- # List projects #------------------------------------------------------------------------------- def list_projects_arg_setup(subparsers): parser = subparsers.add_parser('list-projects', help='List the projects') parser.set_defaults(command='list-projects') def list_projects_rsp_parse(rsp): data = [] for project in rsp['projects']: data.append([project]) headers = ['name'] return {'headers': headers, 'data': data} list_projects_cmd = Command( list_projects_arg_setup, lambda x: {}, url_append('/list-projects.json'), list_projects_rsp_parse, 'GET') #------------------------------------------------------------------------------- # List spiders #------------------------------------------------------------------------------- def list_spiders_arg_setup(subparsers): parser = subparsers.add_parser('list-spiders', help='List the spiders') parser.set_defaults(command='list-spiders') parser.add_argument('--project', type=str, default=None, help='project name') def list_spiders_arg_process(args): if args.project is None: print('[!] You need to specify the project name.') sys.exit(1) return {'project': args.project} def list_spiders_rsp_parse(rsp): data = [] for spider in rsp['spiders']: data.append([spider]) headers = ['name'] return {'headers': headers, 'data': data} list_spiders_cmd = Command( list_spiders_arg_setup, list_spiders_arg_process, url_append('/list-spiders.json'), list_spiders_rsp_parse, 'GET') #------------------------------------------------------------------------------- # List jobs #------------------------------------------------------------------------------- def list_jobs_arg_setup(subparsers): parser = subparsers.add_parser('list-jobs', help='List the jobs') parser.set_defaults(command='list-jobs') parser.add_argument('--status', type=str, default='ACTIVE', choices=['ACTIVE', 'COMPLETED', 'SCHEDULED', 'PENDING', 'RUNNING', 'CANCELED', 'SUCCESSFUL', 'FAILED'], help='job status of the jobs to list') parser.add_argument('--job-id', type=str, default=None, help='ID of the job to list') def list_jobs_arg_process(args): if args.job_id is not None: return {'id': args.job_id} return {'status': args.status} def list_jobs_rsp_parse(rsp): data = [] headers = ['identifier', 'project', 'spider', 'status', 'schedule', 'actor', 'timestamp', 'duration'] for job in rsp['jobs']: datum = [] for h in headers: datum.append(job[h]) data.append(datum) return {'headers': headers, 'data': data} list_jobs_cmd = Command( list_jobs_arg_setup, list_jobs_arg_process, url_append('/list-jobs.json'), list_jobs_rsp_parse, 'GET') #------------------------------------------------------------------------------- # Get log #------------------------------------------------------------------------------- def get_log_arg_setup(subparsers): parser = subparsers.add_parser('get-log', help='Get log') parser.set_defaults(command='get-log') parser.add_argument('--job-id', type=str, default=None, help='job ID') parser.add_argument('--log-type', type=str, default='err', choices=['out', 'err'], help='log type') def get_log_url_setup(args): if args.job_id is None: print('[!] You need to specify a job ID.') sys.exit(1) return '{}/get-log/data/{}.{}'.format(args.url, args.job_id, args.log_type) get_log_cmd = Command( get_log_arg_setup, lambda x: {}, get_log_url_setup, lambda x: x, 'GET') #------------------------------------------------------------------------------- # Push project #------------------------------------------------------------------------------- def push_project_arg_setup(subparsers): parser = subparsers.add_parser('push-project', help='Upload a project') parser.set_defaults(command='push-project') parser.add_argument('--project-path', type=str, default='.', help='project path') def push_project_arg_process(args): path = os.getcwd() if args.project_path.startswith('/'): path = args.project_path else: path = os.path.join(path, args.project_path) path = os.path.normpath(path) try: _, archive = build_project_archive(path) return {'archive': archive} except Exception as e: print('[!] Unable to create archive:', exc_repr(e)) sys.exit(1) def push_project_rsp_parse(rsp): data = [] for spider in rsp['spiders']: data.append([spider]) headers = [rsp['name']] return {'headers': headers, 'data': data} push_project_cmd = Command( push_project_arg_setup, push_project_arg_process, url_append('/push-project.json'), push_project_rsp_parse, 'POST') #------------------------------------------------------------------------------- # Schedule job #------------------------------------------------------------------------------- def schedule_job_arg_setup(subparsers): parser = subparsers.add_parser('schedule-job', help='Schedule a job') parser.set_defaults(command='schedule-job') parser.add_argument('--project', type=str, default=None, help='project name') parser.add_argument('--spider', type=str, default=None, help='spider name') parser.add_argument('--when', type=str, default='now', help='scheduling spec') parser.add_argument('--payload', type=str, default='{}', help='the args for spiders') def schedule_job_arg_process(args): if args.project is None: print('[!] You need to specify the project name.') sys.exit(1) if args.spider is None: print('[!] You need to specify the spider name.') sys.exit(1) return { 'project': args.project, 'spider': args.spider, 'when': args.when, 'payload': args.payload } def schedule_job_rsp_parse(rsp): data = [[rsp['identifier']]] headers = ['identifier'] return {'headers': headers, 'data': data} schedule_job_cmd = Command( schedule_job_arg_setup, schedule_job_arg_process, url_append('/schedule-job.json'), schedule_job_rsp_parse, 'POST') #------------------------------------------------------------------------------- # Cancel job #------------------------------------------------------------------------------- def cancel_job_arg_setup(subparsers): parser = subparsers.add_parser('cancel-job', help='Cancel a job') parser.set_defaults(command='cancel-job') parser.add_argument('--job-id', type=str, default=None, help='job ID') def cancel_job_arg_process(args): if args.job_id is None: print('[!] You need to specify the job ID.') sys.exit(1) return {'id': args.job_id} def cancel_job_rsp_parse(rsp): return 'Canceled.' cancel_job_cmd = Command( cancel_job_arg_setup, cancel_job_arg_process, url_append('/cancel-job.json'), cancel_job_rsp_parse, 'POST') #------------------------------------------------------------------------------- # Remove project #------------------------------------------------------------------------------- def remove_project_arg_setup(subparsers): parser = subparsers.add_parser('remove-project', help='Remove a project') parser.set_defaults(command='remove-project') parser.add_argument('--name', type=str, default=None, help='project name') def remove_project_arg_process(args): if args.name is None: print('[!] You need to specify the project name.') sys.exit(1) return {'name': args.name} def remove_project_rsp_parse(rsp): return 'Removed.' remove_project_cmd = Command( remove_project_arg_setup, remove_project_arg_process, url_append('/remove-project.json'), remove_project_rsp_parse, 'POST') #------------------------------------------------------------------------------- # List of commands #------------------------------------------------------------------------------- commands = { 'status': status_cmd, 'list-projects': list_projects_cmd, 'list-spiders': list_spiders_cmd, 'list-jobs': list_jobs_cmd, 'get-log': get_log_cmd, 'push-project': push_project_cmd, 'schedule-job': schedule_job_cmd, 'cancel-job': cancel_job_cmd, 'remove-project': remove_project_cmd }
package com.flockinger.poppynotes.notesService.model; import java.util.Date; import javax.validation.constraints.NotNull; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.index.CompoundIndex; import org.springframework.data.mongodb.core.index.CompoundIndexes; import org.springframework.data.mongodb.core.index.Indexed; import org.springframework.data.mongodb.core.mapping.Document; @Document(collection = "note") @CompoundIndexes( value = {@CompoundIndex(name = "lastedit_user_idx", def = "{'lastEdit': -1, 'userId' : 1}"), @CompoundIndex(name = "user_pinned_idx", def = "{'userId' : 1, 'pinned' : -1}"), @CompoundIndex(name = "lastedit_user_pin_idx", def = "{'lastEdit': -1, 'userId' : 1, 'pinned' : -1}")}) public class Note { @NotNull @Id private String id; @NotNull @Indexed private String userHash; @NotNull private Boolean pinned; @NotNull @Indexed private Date lastEdit; @NotNull private String title; private String initVector; private String content; public String getInitVector() { return initVector; } public void setInitVector(String initVector) { this.initVector = initVector; } public String getUserHash() { return userHash; } public void setUserHash(String userHash) { this.userHash = userHash; } public String getId() { return id; } public void setId(String id) { this.id = id; } public Boolean getPinned() { return pinned; } public void setPinned(Boolean pinned) { this.pinned = pinned; } public Date getLastEdit() { return lastEdit; } public void setLastEdit(Date lastEdit) { this.lastEdit = lastEdit; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
// Copyright (C) 2019. Huawei Technologies Co., Ltd. All rights reserved. // 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. #include "tensor_computing.h" #ifdef _USE_GPU #include "gpu/mali/tensor_computing_mali.h" #endif EE copy_infer_output_size(std::vector<Tensor *> inputTensor, ArchInfo_t archInfo) { auto arch = archInfo->arch; if (IS_GPU(arch)) { #ifdef _USE_GPU #endif } return SUCCESS; } EE copy(std::vector<Tensor> inputTensor, U32 srcOffset, U32 dstOffset, U32 srcStride, U32 dstStride, U32 length, ArchInfo_t archInfo) { auto arch = archInfo->arch; std::vector<TensorDesc> inputDesc = get_desc_from_tensors(inputTensor); std::vector<void *> input = get_data_from_tensors<void *>(inputTensor, arch); EE ret = NOT_SUPPORTED; if (IS_GPU(arch)) { #ifdef _USE_GPU ret = copy_mali(((MaliPara_t)(archInfo->archPara))->handle, inputDesc, input, srcOffset, dstOffset, srcStride, dstStride, length); #endif #ifdef _USE_CPU } else { U32 srcIndex = bytesOf(inputDesc[0].dt) * srcOffset; U32 dstIndex = bytesOf(inputDesc[1].dt) * dstOffset; U32 copyLength = length * bytesOf(inputDesc[0].dt); if (dstIndex + copyLength > inputTensor[1].bytes()) { UNI_ERROR_LOG("copy %u bytes to dst tensor(%u) beyond size(%u).\n", copyLength, dstIndex, inputTensor[1].bytes()); } if (srcIndex + copyLength > inputTensor[0].bytes()) { UNI_ERROR_LOG("copy %u bytes from src tensor(%u) beyond size(%u).\n", copyLength, srcIndex, inputTensor[0].bytes()); } memcpy((U8 *)input[1] + dstIndex, (U8 *)input[0] + srcIndex, copyLength); ret = SUCCESS; #endif } return ret; }
#!/bin/sh set -e set -u set -o pipefail function on_error { echo "$(realpath -mq "${0}"):$1: error: Unexpected failure" } trap 'on_error $LINENO' ERR if [ -z ${FRAMEWORKS_FOLDER_PATH+x} ]; then # If FRAMEWORKS_FOLDER_PATH is not set, then there's nowhere for us to copy # frameworks to, so exit 0 (signalling the script phase was successful). exit 0 fi echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" COCOAPODS_PARALLEL_CODE_SIGN="${COCOAPODS_PARALLEL_CODE_SIGN:-false}" SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" # Used as a return value for each invocation of `strip_invalid_archs` function. STRIP_BINARY_RETVAL=0 # This protects against multiple targets copying the same framework dependency at the same time. The solution # was originally proposed here: https://lists.samba.org/archive/rsync/2008-February/020158.html RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????") # Copies and strips a vendored framework install_framework() { if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then local source="${BUILT_PRODUCTS_DIR}/$1" elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" elif [ -r "$1" ]; then local source="$1" fi local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" if [ -L "${source}" ]; then echo "Symlinked..." source="$(readlink "${source}")" fi # Use filter instead of exclude so missing patterns don't throw errors. echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" local basename basename="$(basename -s .framework "$1")" binary="${destination}/${basename}.framework/${basename}" if ! [ -r "$binary" ]; then binary="${destination}/${basename}" elif [ -L "${binary}" ]; then echo "Destination binary is symlinked..." dirname="$(dirname "${binary}")" binary="${dirname}/$(readlink "${binary}")" fi # Strip invalid architectures so "fat" simulator / device frameworks work on device if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then strip_invalid_archs "$binary" fi # Resign the code if required by the build settings to avoid unstable apps code_sign_if_enabled "${destination}/$(basename "$1")" # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then local swift_runtime_libs swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u) for lib in $swift_runtime_libs; do echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" code_sign_if_enabled "${destination}/${lib}" done fi } # Copies and strips a vendored dSYM install_dsym() { local source="$1" warn_missing_arch=${2:-true} if [ -r "$source" ]; then # Copy the dSYM into the targets temp dir. echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DERIVED_FILES_DIR}\"" rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DERIVED_FILES_DIR}" local basename basename="$(basename -s .dSYM "$source")" binary_name="$(ls "$source/Contents/Resources/DWARF")" binary="${DERIVED_FILES_DIR}/${basename}.dSYM/Contents/Resources/DWARF/${binary_name}" # Strip invalid architectures so "fat" simulator / device frameworks work on device if [[ "$(file "$binary")" == *"Mach-O "*"dSYM companion"* ]]; then strip_invalid_archs "$binary" "$warn_missing_arch" fi if [[ $STRIP_BINARY_RETVAL == 1 ]]; then # Move the stripped file into its final destination. echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${DERIVED_FILES_DIR}/${basename}.framework.dSYM\" \"${DWARF_DSYM_FOLDER_PATH}\"" rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${DERIVED_FILES_DIR}/${basename}.dSYM" "${DWARF_DSYM_FOLDER_PATH}" else # The dSYM was not stripped at all, in this case touch a fake folder so the input/output paths from Xcode do not reexecute this script because the file is missing. touch "${DWARF_DSYM_FOLDER_PATH}/${basename}.dSYM" fi fi } # Copies the bcsymbolmap files of a vendored framework install_bcsymbolmap() { local bcsymbolmap_path="$1" local destination="${BUILT_PRODUCTS_DIR}" echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${bcsymbolmap_path}" "${destination}"" rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${bcsymbolmap_path}" "${destination}" } # Signs a framework with the provided identity code_sign_if_enabled() { if [ -n "${EXPANDED_CODE_SIGN_IDENTITY:-}" -a "${CODE_SIGNING_REQUIRED:-}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then # Use the current code_sign_identity echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" local code_sign_cmd="/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS:-} --preserve-metadata=identifier,entitlements '$1'" if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then code_sign_cmd="$code_sign_cmd &" fi echo "$code_sign_cmd" eval "$code_sign_cmd" fi } # Strip invalid architectures strip_invalid_archs() { binary="$1" warn_missing_arch=${2:-true} # Get architectures for current target binary binary_archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | awk '{$1=$1;print}' | rev)" # Intersect them with the architectures we are building for intersected_archs="$(echo ${ARCHS[@]} ${binary_archs[@]} | tr ' ' '\n' | sort | uniq -d)" # If there are no archs supported by this binary then warn the user if [[ -z "$intersected_archs" ]]; then if [[ "$warn_missing_arch" == "true" ]]; then echo "warning: [CP] Vendored binary '$binary' contains architectures ($binary_archs) none of which match the current build architectures ($ARCHS)." fi STRIP_BINARY_RETVAL=0 return fi stripped="" for arch in $binary_archs; do if ! [[ "${ARCHS}" == *"$arch"* ]]; then # Strip non-valid architectures in-place lipo -remove "$arch" -output "$binary" "$binary" stripped="$stripped $arch" fi done if [[ "$stripped" ]]; then echo "Stripped $binary of architectures:$stripped" fi STRIP_BINARY_RETVAL=1 } install_artifact() { artifact="$1" base="$(basename "$artifact")" case $base in *.framework) install_framework "$artifact" ;; *.dSYM) # Suppress arch warnings since XCFrameworks will include many dSYM files install_dsym "$artifact" "false" ;; *.bcsymbolmap) install_bcsymbolmap "$artifact" ;; *) echo "error: Unrecognized artifact "$artifact"" ;; esac } copy_artifacts() { file_list="$1" while read artifact; do install_artifact "$artifact" done <$file_list } ARTIFACT_LIST_FILE="${BUILT_PRODUCTS_DIR}/cocoapods-artifacts-${CONFIGURATION}.txt" if [ -r "${ARTIFACT_LIST_FILE}" ]; then copy_artifacts "${ARTIFACT_LIST_FILE}" fi if [[ "$CONFIGURATION" == "Debug" ]]; then install_framework "${BUILT_PRODUCTS_DIR}/AFNetworking/AFNetworking.framework" install_framework "${PODS_ROOT}/../../HeQiangFramework/DemoFramework.framework" install_framework "${BUILT_PRODUCTS_DIR}/HeQiangFramework/HeQiangFramework.framework" install_framework "${BUILT_PRODUCTS_DIR}/JSONModel/JSONModel.framework" fi if [[ "$CONFIGURATION" == "Release" ]]; then install_framework "${BUILT_PRODUCTS_DIR}/AFNetworking/AFNetworking.framework" install_framework "${PODS_ROOT}/../../HeQiangFramework/DemoFramework.framework" install_framework "${BUILT_PRODUCTS_DIR}/HeQiangFramework/HeQiangFramework.framework" install_framework "${BUILT_PRODUCTS_DIR}/JSONModel/JSONModel.framework" fi if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then wait fi
<reponame>nya-official/nya-server<gh_stars>0 /* * Description: A piece of text on a specific language * License: Apache-2.0 * Copyright: x-file.xyz */ package console; /** * Date: 2021-06-21 * Place: Zwingenberg, Germany * @author brito */ public class Lang { private String countryID, text; public String getCountryID() { return countryID; } public void setCountryID(String countryID) { this.countryID = countryID; } public String getText() { return text; } public void setText(String text) { this.text = text; } }
#!/bin/bash # PREREQUISITES # - g++ with c++11 support (gcc4.8.1+) and pthreads # - cmake # - JDK 8 (Scala requires JDK >=8 but DyNet at the moment has problem with JDK >=9) you MUST set JAVA_HOME variable # - git # - python3 and python3-dev with numpy # OPTIONAL # - Intel MKL -- speeds up computation on Intel CPU (you would need to modify relevant variables bellow) # - CUDA and cuDNN -- speeds up computation on NVidia GPU (you would need to modify relevant variables bellow) # - pip3 install 'scikit-learn==0.22.2' 'allennlp==0.4.2' 'thrift==0.11.0' -- if you want to use ELMo embeddings # - pip2 install jnius -- if you want to use supertagger from python2 START_DIR=$PWD SCALA_VER=2.12.6 CORES=4 # Modify this variable to speed up installation of dependencies on multi-core machine realpath() { [[ $1 = /* ]] && echo "$1" || echo "$PWD/${1#./}" } if [[ $(basename $(dirname $(realpath "$0"))) == "scripts" ]]; then PROJECT_DIR=$(dirname $(dirname $(realpath $0))) else PROJECT_DIR=$PWD fi echo PROJECT DIR IS ${PROJECT_DIR} DEPENDENCIES_DIR=${PROJECT_DIR}/dependencies DYNET_COMMIT=51b528c7013c3efa42c7a7bc04959995700e7a77 LIB_DIR=${PROJECT_DIR}/lib ########################## CUDA ######################### CUDA="-DBACKEND=eigen" # no CUDA # export CUDNN_ROOT="/opt/cuDNN-5.1_7.5" # this DyNet version can use only the older CUDNN # export CUDA_TOOLKIT_ROOT_DIR="/opt/cuda-8.0.44" # CUDA="-DBACKEND=cuda -DCUDA_TOOLKIT_ROOT_DIR=$CUDA_TOOLKIT_ROOT_DIR -DCUDNN_ROOT=$CUDNN_ROOT" # this is to use GPU ########################## Intel MKL ######################### # MKL_ROOT=`ls -1d $HOME/intel/compilers_and_libraries_20*.*/linux/mkl/ | head -1` # this is to use MKL # [ ! -z "$MKL_ROOT" ] || { echo 'finding Intel MKL failed' ; exit 1; } # echo FOUND MKL AT $MKL_ROOT # MKL="-DMKL=TRUE -DMKL_ROOT=$MKL_ROOT" # export MKL_NUM_THREADS=$CORES ######################## installation ######################## rm -rf ${DEPENDENCIES_DIR} ${LIB_DIR} ${PROJECT_DIR}/target mkdir -p ${DEPENDENCIES_DIR} cd ${DEPENDENCIES_DIR} ########################## installing sbt ######################### SBT_VERSION=1.1.6 SBT_DIR=${DEPENDENCIES_DIR}/sbt rm -rf ${SBT_DIR} wget --no-check-certificate https://github.com/sbt/sbt/releases/download/v${SBT_VERSION}/sbt-${SBT_VERSION}.tgz || { echo 'SBT download failed' ; exit 1; } tar xfvz sbt-${SBT_VERSION}.tgz rm sbt-${SBT_VERSION}.tgz mv sbt ${SBT_DIR} export PATH=${SBT_DIR}/bin:$PATH ########################## installing swig ######################### SWIG_DIR=${DEPENDENCIES_DIR}/swig # svn checkout https://svn.code.sf.net/p/swig/code/trunk swig-3.0.12 wget --no-check-certificate 'https://downloads.sourceforge.net/project/swig/swig/swig-3.0.12/swig-3.0.12.tar.gz?r=https%3A%2F%2Fsourceforge.net%2Fprojects%2Fswig%2Ffiles%2Flatest%2Fdownload&ts=1529975837' -O swig-3.0.12.tar.gz tar xfvz swig-3.0.12.tar.gz rm swig-3.0.12.tar.gz cd swig-3.0.12 ./configure --prefix=${SWIG_DIR} || { echo 'SWIG install failed' ; exit 1; } make -j ${CORES} || { echo 'SWIG install failed' ; exit 1; } make install || { echo 'SWIG install failed' ; exit 1; } cd .. rm -rf swig-3.0.12 export PATH=${SWIG_DIR}/bin:$PATH ########################## installing DyNet ######################### git clone https://github.com/clab/dynet.git || { echo 'DyNet install failed' ; exit 1; } # getting eigen mkdir eigen cd eigen wget https://github.com/clab/dynet/releases/download/2.1/eigen-b2e267dc99d4.zip || { echo 'Eigen download failed' ; exit 1; } unzip eigen-b2e267dc99d4.zip cd .. cd dynet git checkout ${DYNET_COMMIT} rm -rf contrib/swig/src/test mkdir -p build cd build cmake .. -DEIGEN3_INCLUDE_DIR=${DEPENDENCIES_DIR}/eigen -DENABLE_SWIG=ON -DSCALA_VERSION=${SCALA_VER} ${CUDA} ${MKL} || { echo 'DyNet install failed' ; exit 1; } make -j ${CORES} || { echo 'DyNet install failed' ; exit 1; } mkdir -p ${LIB_DIR} cd ${LIB_DIR} rm -f dynet*.jar # mv ${DEPENDENCIES_DIR}/dynet/build/contrib/swig/dynet_swigJNI.jar . # java lib mv ${DEPENDENCIES_DIR}/dynet/build/contrib/swig/dynet_swigJNI_dylib.jar . # native lib mv ${DEPENDENCIES_DIR}/dynet/build/contrib/swig/dynet_swigJNI_scala*.jar . # scala lib ######################################################################### rm -rf ${DEPENDENCIES_DIR}/swig rm -rf ${DEPENDENCIES_DIR}/eigen cd ${PROJECT_DIR} ${SBT_DIR}/bin/sbt assembly || { echo 'sbt assembly failed' ; exit 1; } cd ${START_DIR}
<filename>2018/H/2-mural/solution.build.js 'use strict'; function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } } function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } var parseCase = function parseCase(line, data) { var result = _objectSpread({}, data); if (!result.N) { result.N = parseInt(line); return result; } result.digits = line; result.isComplete = true; return result; }; var parseProblem = function parseProblem(line, problem) { if (!problem.T || problem.T === 0) { var _result = _objectSpread({}, problem, { T: parseInt(line) }); return _result; } var cases = _toConsumableArray(problem.cases); if (cases.length === 0 || cases[cases.length - 1].isComplete === true) { cases.push({ isComplete: false }); } var currentCase = cases[cases.length - 1]; cases[cases.length - 1] = parseCase(line, currentCase); var isComplete = cases.length === problem.T && cases[cases.length - 1].isComplete; var result = _objectSpread({}, problem, { cases, isComplete }); return result; }; var solve = function solve(data) { var digits = data.digits; var max = 0; var sums = []; var paintLength = Math.ceil(digits.length / 2); for (var i = 0; i < digits.length; i++) { var digit = parseInt(digits[i]); if (i === 0) { sums[i] = digit; } else { sums[i] = sums[i - 1] + digit; } if (i + 1 - paintLength < 0) { continue; } var sumsTail = i - paintLength < 0 ? 0 : sums[i - paintLength]; var paintScore = sums[i] - sumsTail; if (paintScore > max) { max = paintScore; } } return max; }; var solveCases = function solveCases(cases) { for (var index = 0; index < cases.length; index++) { var result = solve(cases[index]); console.log(`Case #${index + 1}: ${result}`); } }; var main = function main() { var readline = require('readline'); var problem = { T: 0, cases: [], isComplete: false }; var rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.on('line', function (line) { problem = parseProblem(line, problem); if (problem.isComplete) { rl.close(); } }).on('close', function () { solveCases(problem.cases); process.exit(0); }); }; if (!module.parent) { main(); }
<reponame>MOAMaster/AudioPlugSharp-SamplePlugins //----------------------------------------------------------------------------- // Project : SDK Core // Version : 1.0 // // Category : Common Base Classes // Filename : public.sdk/source/main/macmain.cpp // Created by : Steinberg, 01/2004 // Description : Mac OS X Bundle Entry // //----------------------------------------------------------------------------- // LICENSE // (c) 2020, Steinberg Media Technologies GmbH, All Rights Reserved //----------------------------------------------------------------------------- // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * 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. // * Neither the name of the Steinberg Media Technologies 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. //----------------------------------------------------------------------------- #include "pluginterfaces/base/fplatform.h" #ifndef __CF_USE_FRAMEWORK_INCLUDES__ #define __CF_USE_FRAMEWORK_INCLUDES__ 1 #endif #include <CoreFoundation/CoreFoundation.h> //------------------------------------------------------------------------ CFBundleRef ghInst = 0; int bundleRefCounter = 0; // counting for bundleEntry/bundleExit pairs void* moduleHandle = 0; #define VST_MAX_PATH 2048 char gPath[VST_MAX_PATH] = {0}; //------------------------------------------------------------------------ bool InitModule (); ///< must be provided by plug-in: called when the library is loaded bool DeinitModule (); ///< must be provided by plug-in: called when the library is unloaded //------------------------------------------------------------------------ extern "C" { SMTG_EXPORT_SYMBOL bool bundleEntry (CFBundleRef); SMTG_EXPORT_SYMBOL bool bundleExit (void); } #include <vector> std::vector<CFBundleRef> gBundleRefs; //------------------------------------------------------------------------ /** must be called from host right after loading bundle Note: this could be called more than one time! */ bool bundleEntry (CFBundleRef ref) { if (ref) { bundleRefCounter++; CFRetain (ref); // hold all bundle refs until plug-in is fully uninitialized gBundleRefs.push_back (ref); if (!moduleHandle) { ghInst = ref; moduleHandle = ref; // obtain the bundle path CFURLRef tempURL = CFBundleCopyBundleURL (ref); CFURLGetFileSystemRepresentation (tempURL, true, (UInt8*)gPath, VST_MAX_PATH); CFRelease (tempURL); } if (bundleRefCounter == 1) return InitModule (); } return true; } //------------------------------------------------------------------------ /** must be called from host right before unloading bundle Note: this could be called more than one time! */ bool bundleExit (void) { if (--bundleRefCounter == 0) { DeinitModule (); // release the CFBundleRef's once all bundleExit clients called in // there is no way to identify the proper CFBundleRef of the bundleExit call for (size_t i = 0; i < gBundleRefs.size (); i++) CFRelease (gBundleRefs[i]); gBundleRefs.clear (); } else if (bundleRefCounter < 0) return false; return true; }
<gh_stars>10-100 /* * Copyright 2009-2010 junithelper.org. * * 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.junithelper.core.generator; import org.junithelper.core.meta.ClassMeta; import org.junithelper.core.meta.ExceptionMeta; import org.junithelper.core.meta.MethodMeta; import org.junithelper.core.meta.TestMethodMeta; public interface TestMethodGenerator { void initialize(ClassMeta targetClassMeta); TestMethodMeta getTestMethodMeta(MethodMeta targetMethodMeta); TestMethodMeta getTestMethodMeta(MethodMeta targetMethodMeta, ExceptionMeta exception); String getTestMethodNamePrefix(TestMethodMeta testMethodMeta); String getTestMethodNamePrefix(TestMethodMeta testMethodMeta, ExceptionMeta exception); String getTestMethodSourceCode(TestMethodMeta testMethodMeta); }
#!/usr/bin/env bash # # Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. set -eu if [[ "${CHECK_STYLE}" != "yes" ]]; then echo "Skipping code style check as it is disabled for this build." exit 0 fi # This script assumes it is running the top-level google-cloud-cpp directory. readonly BINDIR="$(dirname "$0")" source "${BINDIR}/colors.sh" # This controls the output format from bash's `time` command, which we use # below to time blocks of the script. A newline is automatically included. readonly TIMEFORMAT="... %R seconds" problems="" printf "%-30s" "Running check-include-guards:" time { if ! find google/cloud -name '*.h' -print0 | xargs -0 awk -f "${BINDIR}/check-include-guards.gawk"; then problems="${problems} include-guards" fi } replace_original_if_changed() { if [[ $# != 2 ]]; then return 1 fi local original="$1" local reformatted="$2" if cmp -s "${original}" "${reformatted}"; then rm -f "${reformatted}" else chmod --reference="${original}" "${reformatted}" mv -f "${reformatted}" "${original}" fi } # Apply cmake_format to all the CMake list files. # https://github.com/cheshirekow/cmake_format printf "%-30s" "Running cmake-format:" time { git ls-files -z | grep -zE '((^|/)CMakeLists\.txt|\.cmake)$' | xargs -P "${NCPU}" -n 1 -0 cmake-format -i } # Apply clang-format(1) to fix whitespace and other formatting rules. # The version of clang-format is important, different versions have slightly # different formatting output (sigh). printf "%-30s" "Running clang-format:" time { git ls-files -z | grep -zE '\.(cc|h)$' | xargs -P "${NCPU}" -n 50 -0 clang-format -i } # Apply buildifier to fix the BUILD and .bzl formatting rules. # https://github.com/bazelbuild/buildtools/tree/master/buildifier printf "%-30s" "Running buildifier:" time { git ls-files -z | grep -zE '\.(BUILD|bzl)$' | xargs -0 buildifier -mode=fix git ls-files -z | grep -zE '(^|/)(BUILD|WORKSPACE)$' | xargs -0 buildifier -mode=fix } # Apply psf/black to format Python files. # https://pypi.org/project/black/ printf "%-30s" "Running black:" time { git ls-files -z | grep -z '\.py$' | xargs -0 python3 -m black --quiet } # Apply shfmt to format all shell scripts printf "%-30s" "Running shfmt:" time { git ls-files -z | grep -z '\.sh$' | xargs -0 shfmt -w -i 2 } # Apply shellcheck(1) to emit warnings for common scripting mistakes. printf "%-30s" "Running shellcheck:" time { if ! git ls-files -z | grep -z '\.sh$' | xargs -0 shellcheck \ --exclude=SC1090 \ --exclude=SC2034 \ --exclude=SC2153 \ --exclude=SC2181; then problems="${problems} shellcheck" fi } # Apply several transformations that cannot be enforced by clang-format: # - Replace any #include for grpc++/* with grpcpp/*. The paths with grpc++ # are obsoleted by the gRPC team, so we should not use them in our code. # - Replace grpc::<BLAH> with grpc::StatusCode::<BLAH>, the aliases in the # `grpc::` namespace do not exist inside google. printf "%-30s" "Running include fixes:" time { git ls-files -z | grep -zE '\.(cc|h)$' | while IFS= read -r -d $'\0' file; do # We used to run run `sed -i` to apply these changes, but that touches the # files even if there are no changes applied, forcing a rebuild each time. # So we first apply the change to a temporary file, and replace the original # only if something changed. sed -e 's/grpc::\([A-Z][A-Z_][A-Z_]*\)/grpc::StatusCode::\1/g' \ -e 's;#include <grpc\\+\\+/grpc\+\+.h>;#include <grpcpp/grpcpp.h>;' \ -e 's;#include <grpc\\+\\+/;#include <grpcpp/;' \ "${file}" >"${file}.tmp" replace_original_if_changed "${file}" "${file}.tmp" done } # Apply transformations to fix whitespace formatting in files not handled by # clang-format(1) above. For now we simply remove trailing blanks. Note that # we do not expand TABs (they currently only appear in Makefiles and Makefile # snippets). printf "%-30s" "Running whitespace fixes:" time { git ls-files -z | grep -zv '\.gz$' | while IFS= read -r -d $'\0' file; do sed -e 's/[[:blank:]][[:blank:]]*$//' \ "${file}" >"${file}.tmp" replace_original_if_changed "${file}" "${file}.tmp" done } # Report any differences created by running the formatting tools. if ! git diff --ignore-submodules=all --color --exit-code .; then problems="${problems} formatting" fi # Exit with an error IFF we are running as part of a CI build. Otherwise, a # human probably invoked this script in which case we'll just leave the # formatted files in their local git repo so they can diff them and commit the # correctly formatted files. if [[ -n "${problems}" ]]; then log_red "Detected style problems (${problems:1})" if [[ "${RUNNING_CI}" != "no" ]]; then exit 1 fi fi
<filename>decode.go package phpserialize import ( "bufio" "bytes" "errors" "fmt" "io" "math/bits" "reflect" "strconv" "strings" "time" ) type Decoder struct { s io.ByteScanner flags uint32 } const ( disallowUnknownFieldsFlag uint32 = 1 << iota ) const ( // bytesAllocLimit = 1e6 // 1mb // sliceAllocLimit = 1e4 maxMapSize = 1e6 ) var ( ErrUnsupported = errors.New(`unsupported target type`) ) type bufReader interface { // io.Reader io.ByteScanner } func Unmarshal(data []byte, v interface{}) error { d := NewDecoder(bytes.NewReader(data)) return d.Decode(v) } func UnmarshalString(data string, v interface{}) error { d := NewDecoder(strings.NewReader(data)) return d.Decode(v) } func NewDecoder(r io.Reader) *Decoder { d := new(Decoder) d.resetReader(r) return d } func (d *Decoder) resetReader(r io.Reader) { if br, ok := r.(bufReader); ok { //d.r = br d.s = br } else { br := bufio.NewReader(r) //d.r = br d.s = br } } //nolint:gocyclo func (d *Decoder) Decode(v interface{}) error { var err error switch v := v.(type) { case *string: if v != nil { *v, err = d.DecodeString() return err } case *[]byte: if v != nil { return ErrUnsupported // d.decodeBytesPtr(v) } case *int: if v != nil { *v, err = d.DecodeInt() return err } case *int8: if v != nil { *v, err = d.DecodeInt8() return err } case *int16: if v != nil { *v, err = d.DecodeInt16() return err } case *int32: if v != nil { *v, err = d.DecodeInt32() return err } case *int64: if v != nil { *v, err = d.DecodeInt64() return err } case *uint: return ErrUnsupported /*if v != nil { *v, err = d.DecodeUint() return err }*/ case *uint8: return ErrUnsupported /*if v != nil { *v, err = d.DecodeUint8() return err }*/ case *uint16: return ErrUnsupported /*if v != nil { *v, err = d.DecodeUint16() return err }*/ case *uint32: return ErrUnsupported /*if v != nil { *v, err = d.DecodeUint32() return err }*/ case *uint64: return ErrUnsupported /*if v != nil { *v, err = d.DecodeUint64() return err }*/ case *bool: if v != nil { *v, err = d.DecodeBool() return err } case *float32: if v != nil { *v, err = d.DecodeFloat32() return err } case *float64: if v != nil { *v, err = d.DecodeFloat64() return err } case *[]string: return d.decodeStringSlicePtr(v) case *map[string]string: return d.decodeMapStringStringPtr(v) case *map[string]interface{}: return ErrUnsupported // d.decodeMapStringInterfacePtr(v) case *time.Duration: if v != nil { vv, err := d.DecodeInt64() *v = time.Duration(vv) return err } case *time.Time: return ErrUnsupported /*if v != nil { *v, err = d.DecodeTime() return err }*/ } vv := reflect.ValueOf(v) if !vv.IsValid() { return errors.New("phpserialize: Decode(nil)") } if vv.Kind() != reflect.Ptr { return fmt.Errorf("phpserialize: Decode(non-pointer %T)", v) } if vv.IsNil() { return fmt.Errorf("phpserialize: Decode(non-settable %T)", v) } vv = vv.Elem() if vv.Kind() == reflect.Interface { if !vv.IsNil() { vv = vv.Elem() if vv.Kind() != reflect.Ptr { return fmt.Errorf("phpserialize: Decode(non-pointer %s)", vv.Type().String()) } } } return d.DecodeValue(vv) } func (d *Decoder) PeekCode() (byte, error) { c, err := d.s.ReadByte() if err != nil { return 0, err } return c, d.s.UnreadByte() } func (d *Decoder) hasNilCode() bool { code, err := d.PeekCode() return err == nil && code == 'N' } func (d *Decoder) DecodeNil() error { return d.skipExpected('N', ';') } func (d *Decoder) DecodeValue(v reflect.Value) error { decode := getDecoder(v.Type()) if decode == nil { return fmt.Errorf(`phpserialize: could not find decoder for: %s`, v.Type().String()) } return decode(d, v) } /** b:1; b:0; */ func (d *Decoder) DecodeBool() (bool, error) { if err := d.skipExpected('b', ':'); err != nil { return false, err } v, err := d.s.ReadByte() if err != nil { return false, err } if err := d.skipExpected(';'); err != nil { return false, err } switch v { case '1': return true, nil case '0': return false, nil default: return false, errors.New(`phpserialize: Decode(invalid boolean value)`) } } /** i:685230; i:-685230; */ func (d *Decoder) DecodeInt() (int, error) { v, err := d.DecodeSignedInt(bits.UintSize) if err != nil { return 0, err } return int(v), nil } func (d *Decoder) DecodeInt8() (int8, error) { v, err := d.DecodeSignedInt(8) if err != nil { return 0, err } return int8(v), nil } func (d *Decoder) DecodeInt16() (int16, error) { v, err := d.DecodeSignedInt(16) if err != nil { return 0, err } return int16(v), nil } func (d *Decoder) DecodeInt32() (int32, error) { v, err := d.DecodeSignedInt(32) if err != nil { return 0, err } return int32(v), nil } func (d *Decoder) DecodeInt64() (int64, error) { return d.DecodeSignedInt(64) } func (d *Decoder) DecodeSignedInt(bitSize int) (int64, error) { if err := d.skipExpected('i', ':'); err != nil { return 0, err } acc, err := d.readUntil(';') if err != nil { return 0, err } return strconv.ParseInt(string(acc), 10, bitSize) } func (d *Decoder) DecodeUnsignedInt(bitSize int) (uint64, error) { if err := d.skipExpected('i', ':'); err != nil { return 0, err } acc, err := d.readUntil(';') if err != nil { return 0, err } return strconv.ParseUint(string(acc), 10, bitSize) } /** d:685230.15; d:INF; d:-INF; d:NAN; */ func (d *Decoder) DecodeFloat64() (float64, error) { return d.DecodeFloat(64) } func (d *Decoder) DecodeFloat32() (float32, error) { v, err := d.DecodeFloat(32) if err != nil { return 0, err } return float32(v), nil } func (d *Decoder) DecodeFloat(bitSize int) (float64, error) { if err := d.skipExpected('d', ':'); err != nil { return 0, err } acc, err := d.readUntil(';') if err != nil { return 0, err } return strconv.ParseFloat(string(acc), bitSize) } func (d *Decoder) DecodeString() (string, error) { if err := d.skipExpected('s', ':'); err != nil { return ``, err } strLen, err := d.readUntilLen() if err != nil { return ``, err } if err := d.skipExpected('"'); err != nil { return ``, err } acc := make([]byte, strLen) for x := 0; x < strLen; x++ { b, err := d.s.ReadByte() if err != nil { return ``, err } acc[x] = b } if err := d.skipExpected('"', ';'); err != nil { return ``, err } return string(acc), nil } func (d *Decoder) readUntil(v byte) ([]byte, error) { var acc []byte for { b, err := d.s.ReadByte() if err != nil { return nil, err } if b == v { break } acc = append(acc, b) } return acc, nil } func (d *Decoder) readUntilLen() (int, error) { acc, err := d.readUntil(':') if err != nil { return 0, err } return strconv.Atoi(string(acc)) } func (d *Decoder) skipExpected(expected ...byte) error { for _, e := range expected { c, err := d.s.ReadByte() if err != nil { return err } if c != e { return fmt.Errorf(`phpserialize: Decode(expected byte '%c' found '%c')`, e, c) } } return nil } func (d *Decoder) decodeArrayLen() (int, error) { if err := d.skipExpected('a', ':'); err != nil { return 0, err } n, err := d.readUntilLen() if err != nil { return 0, err } if err := d.skipExpected('{'); err != nil { return 0, err } return n, nil } func min(a, b int) int { //nolint:unparam if a <= b { return a } return b }
<gh_stars>1-10 import React, { useRef, useState } from 'react'; import { PageHeaderWrapper } from '@ant-design/pro-layout'; import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table'; import { TableListItem, LoadingUnloadingRecordStatus, OperationStatus, dataRegux } from './data.d'; import { VehicleAccessRecord } from './service'; import { CarRecordPaginationConfig, onCarRecordTableLoad } from '../utils'; import styles from '../index.less'; import { Input } from 'antd'; import usePaginationBackButton from '@/hooks/usePaginationBackButton'; const TableList: React.FC<{}> = () => { const actionRef = useRef<ActionType>(); const inputRef = useRef<HTMLInputElement>(); // 获取分页返回按钮的函数 const getButton = usePaginationBackButton(actionRef); const [rowCarNo, setRowCarNo] = useState<string>(); const columns: ProColumns<TableListItem>[] = [ { title: '车牌识别码', dataIndex: 'carNo', // align: 'center', sorter: (a: any, b: any) => { return a.carNo.length - b.carNo.length; }, renderFormItem: () => { return ( <Input onChange={(e) => { e.persist(); setRowCarNo(e.target.value); }} ></Input> ); }, }, { title: '司机手机号', dataIndex: 'phone', valueType: 'option', align: 'center', }, { title: '车辆类型', dataIndex: 'type', align: 'center', valueType: 'option', }, { title: '车辆识别类型', dataIndex: 'carType', align: 'center', valueType: 'option', }, { title: '途径商户', dataIndex: 'merchant', align: 'center', valueType: 'option', }, { title: '操作人手机号', dataIndex: 'operatorPhone', align: 'center', valueType: 'option', }, { title: '操作人姓名', dataIndex: 'operator', align: 'center', valueType: 'option', }, { title: '当前操作', dataIndex: 'operation', align: 'center', valueType: 'option', valueEnum: { [LoadingUnloadingRecordStatus.LoadingStatus]: { text: LoadingUnloadingRecordStatus.LoadingStatus, status: 'Warning', }, [LoadingUnloadingRecordStatus.UnloadStatus]: { text: LoadingUnloadingRecordStatus.UnloadStatus, status: 'Success', }, }, filtered: false, filterDropdown: false, filterDropdownVisible: false, onHeaderCell: () => { return { className: 'close-sorter-icon' }; }, }, { title: '当前状态', dataIndex: 'status', valueType: 'option', align: 'center', valueEnum: { [OperationStatus.RuningStatus]: { text: OperationStatus.RuningStatus, status: 'Processing', }, [OperationStatus.ReleaseStatus]: { text: OperationStatus.ReleaseStatus, status: 'Default' }, }, filtered: false, filterDropdown: false, filterDropdownVisible: false, onHeaderCell: () => { return { className: 'close-sorter-icon' }; }, sorter: (a: any, b: any) => { return a.status.length - b.status.length; }, }, { title: '进场时间', dataIndex: 'createdAt', valueType: 'option', align: 'center', }, { title: '出场时间', dataIndex: 'outAt', valueType: 'option', align: 'center', sorter: (a: any, b: any) => { let checkA = dataRegux.test(a.outAt); let checkB = dataRegux.test(b.outAt); let obja = checkA ? new Date(a.outAt).getTime() : 0; let objb = checkB ? new Date(b.outAt).getTime() : 0; return obja - objb; }, }, { title: '操作时间', dataIndex: 'operationAt', valueType: 'option', align: 'center', }, ]; return ( <PageHeaderWrapper> <ProTable<TableListItem> headerTitle="车辆装卸货记录表格" actionRef={actionRef} rowKey="key" tableAlertRender={false} request={(params) => { let obj = { ...params, carNo: rowCarNo ? rowCarNo : undefined, }; return VehicleAccessRecord(obj); }} columns={columns} bordered pagination={CarRecordPaginationConfig} onLoad={onCarRecordTableLoad(inputRef, getButton)} className={styles.carRecordTable} options={{ reload: async () => { setRowCarNo(undefined); actionRef && actionRef.current && actionRef.current.reload(); }, fullScreen: true, setting: true, density: true, }} onRow={(record: any) => { return { onDoubleClick: () => { let obj: any = window.getSelection; let empt: any = document.getSelection(); obj ? obj().removeAllRanges() : empt.empty(); setRowCarNo(record.carNo); actionRef && actionRef.current && actionRef.current.reload(); }, }; }} onReset={() => { setRowCarNo(undefined); }} /> </PageHeaderWrapper> ); }; export default TableList;
<gh_stars>10-100 require 'spec_helper' describe 'Integration specs' do def test_app_location Pathname.new(File.dirname(__FILE__)).join('dummy_app') end let(:assets) {test_app_location.join('public', 'assets')} def run_in_test_app(command) Dir.chdir(test_app_location) do output = Kernel.send :`,command raise output unless $? == 0 end end before :all do FileUtils.rm_rf(test_app_location.join('public', 'assets')) run_in_test_app('rake assets:precompile 2>&1') end it 'should have symlinked application.js to the digested application.js' do expect(assets.join('application.js')).to be_a_symlink_to(find_asset_name('application-*.js')) expect(File.read(test_app_location.join('public','assets','application.js'))).to match(/alert\('application.js'\)/) end it 'should have symlinked 3rdpaty/all.js to the digested lib.js' do expect(assets.join('3rdparty/all.js')).to be_a_symlink_to(find_asset_name('3rdparty/lib-*.js')) expect(File.read(test_app_location.join('public','assets','3rdparty', 'all.js'))).to match(/alert\('3rd party js'\)/) end def find_asset_name(path) File.basename(Dir.chdir(assets) { Dir.glob(path).first }) end end
// sc: https://ru.hexlet.io/courses/js-arrays/lessons/strings/exercise_unit // strings.js // Реализуйте и экспортируйте по умолчанию функцию makeCensored, которая заменяет каждое // вхождение указанных слов в предложении на последовательность $#%! и возвращает полученную строку. // Аргументы: // Текст // Набор стоп-слов // Словом считается любая непрерывная последовательность символов, // включая любые спецсимволы(без пробелов). const makeCensored0 = (string, stopWords) => { const escapeRegExp = (str) => str.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&'); const stopStr = stopWords.map(escapeRegExp).join('|'); const stopWordsRegExp = new RegExp(`^${stopStr}$`, 'g'); return string .split(' ') .map((word) => word.replace(stopWordsRegExp, '$#%!')) .join(' '); }; const makeCensored = (string, stopWords) => string .split(' ') .map((word) => (stopWords.includes(word) ? '$#%!' : word)) .join(' ');
#!/usr/bin/env bash gradle appRun
<filename>src/bundle.js const fs = require('fs'); const path = require('path'); const resolve = require('resolve'); const srcURL = require('source-map-url'); const traverse = require('@babel/traverse').default; const { parse } = require('@babel/parser'); const { SourceListMap } = require('source-list-map'); const { transform } = require('sucrase'); const mfs = require('./memory-fs'); const prelude = require('./prelude'); const { isCSS, resolveApp } = require('./utils'); const { getConfigByKey } = require('./config'); const { CONFIG_EXTERNALS, CONFIG_GLOBALS, CONFIG_INPUT } = require('./constants'); function createAsset(absolutePath) { let compiledCode = {}; const relativePath = absolutePath.replace(resolveApp(), ''); const content = fs .readFileSync(resolveApp(absolutePath), 'utf-8') // TODO: Add in the option to define env variables .replace(/process\.env\.NODE_ENV/g, `'${process.env.NODE_ENV}'`); const hasSrcMapUrl = srcURL.existsIn(content); const dependencies = []; if (!hasSrcMapUrl) { const ast = parse(content, { allowImportExportEverywhere: true, sourceType: 'module', plugins: ['jsx', 'typescript'], }); // @see: https://github.com/egoist/konan traverse(ast, { enter(path) { if (path.node.type === 'CallExpression') { const callee = path.get('callee'); const isDynamicImport = callee.isImport(); if (callee.isIdentifier({ name: 'require' }) || isDynamicImport) { const arg = path.node.arguments[0]; dependencies.push(arg.value); } } else if ( path.node.type === 'ImportDeclaration' || path.node.type === 'ExportNamedDeclaration' || path.node.type === 'ExportAllDeclaration' ) { const { source } = path.node; if (source && source.value && !isCSS(source.value)) { dependencies.push(source.value); } } }, }); compiledCode = transform(content, { filePath: resolveApp(), transforms: ['imports', 'jsx', 'typescript'], }); } const map = hasSrcMapUrl && JSON.parse(fs.readFileSync(`${absolutePath}.map`, 'utf8')); const code = hasSrcMapUrl && srcURL.removeFrom(content); return { absolutePath, content: content, code: compiledCode.code || code, dependencies, hasSrcMapUrl, id: relativePath, map: compiledCode.map || map, }; } function createGraph(entry) { let queue; const mainAsset = createAsset(entry); queue = [mainAsset]; const regx = RegExp(`${getConfigByKey(CONFIG_EXTERNALS).replace(/,/g, '|')}`); for (let asset of queue) { const length = asset.dependencies.length; asset.mapping = {}; for (let i = 0; i < length; i++) { const dependency = asset.dependencies[i]; const res = resolve.sync(dependency, { basedir: path.dirname(asset.absolutePath), extensions: ['.js', '.ts', '.tsx'], preserveSymlinks: true, }); if (!/node_modules/g.test(res) || regx.test(res)) { const child = createAsset(res); asset.mapping[dependency] = child.id; queue.push(child); } } } return queue; } function createBundle(entry) { const bundle = 'bundle.js'; const bundleMap = `${bundle}.map`; const bundlePath = resolveApp(path.join('server', bundle)); const sourceListMap = new SourceListMap(); const modulesIds = []; const graph = createGraph(entry); const length = graph.length; const input = getConfigByKey(CONFIG_INPUT); // TODO: Add options to define env variables sourceListMap.add('var global = global || {};\n'); sourceListMap.add('var process = process || { env: {} };\n'); sourceListMap.add(`var configGlobals = ${JSON.stringify(getConfigByKey(CONFIG_GLOBALS))};\n`); sourceListMap.add(`var __DEV_PACK_ENTRY_POINT__ = "${graph[0].id}";\n`); sourceListMap.add('var __DEV_PACK_MODULES__ = {\n'); for (let i = 0; i < length; i++) { sourceListMapModule(graph, i, modulesIds, sourceListMap); } sourceListMap.add('};\n'); sourceListMap.add(prelude); const { map, source } = sourceListMap.toStringWithSourceMap({ file: bundlePath }); mfs.writeFileSync( resolveApp(path.join(input, bundle)), ` ${source} //# sourceMappingURL=${bundleMap} `, err => { if (err) throw err; } ); mfs.writeFileSync(resolveApp(path.join(input, bundleMap)), JSON.stringify(map), err => { if (err) throw err; }); } function createHotModuleUpdate(entry) { let hasSrcMapUrl; const entryBasename = path.basename(entry); const bundlePath = resolveApp(path.join(getConfigByKey(CONFIG_INPUT), entryBasename)); const sourceListMap = new SourceListMap(); const modulesIds = []; const graph = createGraph(entry); const length = graph.length; sourceListMap.add('hotUpdate({'); for (let i = 0; i < length; i++) { if (graph[i].id === entry) { hasSrcMapUrl = graph[i].hasSrcMapUrl; sourceListMapModule(graph, i, modulesIds, sourceListMap); break; } } sourceListMap.add('});'); const { map, source } = sourceListMap.toStringWithSourceMap({ file: bundlePath }); !hasSrcMapUrl && mfs.writeFileSync(`${bundlePath}.map`, JSON.stringify(map), err => { if (err) throw err; }); return !hasSrcMapUrl ? `${source}\n//# sourceMappingURL=${entryBasename}.map` : `hotUpdate({"${graph[0].id}": [function (require, module, exports) {\n${graph[0].code}\n},{},],\n});`; } function sourceListMapModule(graph, i, modulesIds, sourceListMap) { const mod = graph[i]; const id = mod.id; const hasId = modulesIds.indexOf(id) > -1; if (!hasId) { sourceListMap.add(`"${id}": [function (require, module, exports) {\n`); !mod.hasSrcMapUrl && sourceListMap.add(mod.code, mod.id, mod.content); mod.hasSrcMapUrl && sourceListMap.add(mod.code); sourceListMap.add(`\n},${JSON.stringify(mod.mapping)}],\n`); modulesIds.push(id); } } module.exports = { createBundle, createModule: createHotModuleUpdate, };
#!/bin/bash readonly ME=$(whoami) touch $HOME/.profile function set_env { export PATH="/usr/local/go/bin":$PATH export GOROOT="/usr/local/go" export APPDIR="/opt/gopath/src/github.com/alligrader/gradebook-api" export GOPATH="/opt/gopath" export GOBIN=$GOPATH/bin export PATH=$PATH:/usr/local/go/bin:$GOPATH/bin echo "export PATH=/usr/local/go/bin:\$PATH" echo "export GOROOT=/usr/local/go" echo "export GOPATH=/opt/gopath" >> $HOME/.profile echo "export GOBIN=\$GOPATH/bin" >> $HOME/.profile echo "export PATH=\$PATH:/usr/local/go/bin:$GOPATH/bin" >> $HOME/.profile echo "cd $APPDIR" >> $HOME/.bashrc source $HOME/.profile } function install_node_modules { cd $GOPATH/src/github.com/alligrader/gradebook npm install cd - } function install_godeps { sudo chown -R $ME:$ME /opt # Work around bug in Vagrant go get github.com/snikch/goodman go get bitbucket.org/liamstask/goose/cmd/goose go get github.com/Masterminds/glide go get -u github.com/goadesign/goa/... cd $APPDIR glide i cd - } function install_autoenv { echo '~~ installing autoenv ~~' git clone git://github.com/kennethreitz/autoenv.git $HOME/.autoenv echo '~~ cloning autoenv completed ~~' echo '~~ persisting autoenv to the .profile ~~' echo 'source ~/.autoenv/activate.sh' >> $HOME/.profile echo '~~ finshed installing autoenv ~~' } function install_spacecowboy { wget https://gist.githubusercontent.com/seanlinsley/3e49c09dcdfc37f05eb4/raw/2e61c48fef7adfdf7267199bc39d2ab5bf38e9b7/seeyouspacecowboy.rb mv seeyouspacecowboy.rb $HOME/.spacecowboy.rb echo 'ruby ~/.spacecowboy.rb' >> $HOME/.bash_logout } function make_storage { mkdir $HOME/storage } function configure_kubectl { echo "export KUBECONFIG=$APPDIR/.deploy/kubeconfig" >> $HOME/.profile echo "kubectl config use-context vagrant-single" >> $HOME/.profile } function main { set_env install_node_modules install_autoenv # This command breaks Docker. God love us. # install_spacecowboy install_godeps make_storage configure_kubectl } set -e set -x set -u main echo '~~ Provisioning User-Mode Complete ~~'
#pragma once #include <typed-geometry/detail/scalar_traits.hh> #include <typed-geometry/feature/assert.hh> #include <typed-geometry/functions/objects/normal.hh> #include <typed-geometry/functions/tests/vec_tests.hh> #include <typed-geometry/functions/vector/normalize.hh> #include <typed-geometry/types/angle.hh> #include <typed-geometry/types/objects/triangle.hh> #include <typed-geometry/types/vec.hh> namespace tg { // returns the (smaller) angle between two vectors, i.e. the result is in 0..pi (0°..180°) template <int D, class ScalarT> [[nodiscard]] constexpr angle_t<fractional_result<ScalarT>> angle_between(vec<D, ScalarT> const& a, vec<D, ScalarT> const& b) { constexpr auto lower = decltype(dot(normalize_safe(a), normalize_safe(b)))(-1); constexpr auto upper = decltype(dot(normalize_safe(a), normalize_safe(b)))(1); auto a_unit = normalize_safe(a); auto b_unit = normalize_safe(b); return acos(clamp(dot(a_unit, b_unit), lower, upper)); } // returns the (smaller) angle between two directions, i.e. the result is in 0..pi (0°..180°) template <int D, class ScalarT> [[nodiscard]] constexpr angle_t<fractional_result<ScalarT>> angle_between(dir<D, ScalarT> const& a, dir<D, ScalarT> const& b) { constexpr auto lower = decltype(dot(a, b))(-1); constexpr auto upper = decltype(dot(a, b))(1); return acos(clamp(dot(a, b), lower, upper)); } // returns the angle between any two objects with unambiguous normals. The result is in 0..pi (0°..180°) template <class A, class B> [[nodiscard]] constexpr auto angle_between(A const& a, B const& b) -> decltype(acos(dot(normal_of(a), normal_of(b)))) { // TODO(ks): call to angle_between(dir, dir)? constexpr auto lower = decltype(dot(normal_of(a), normal_of(b)))(-1); constexpr auto upper = decltype(dot(normal_of(a), normal_of(b)))(1); return acos(clamp(dot(normal_of(a), normal_of(b))), lower, upper); } // Returns the angle of a rotation of a towards b about the orthogonal_axis // The orthogonal axis is important to determine the direction of orientation (axb vs -axb) template <class ScalarT> [[nodiscard]] constexpr angle_t<fractional_result<ScalarT>> angle_towards(vec<3, ScalarT> const& a, vec<3, ScalarT> const& b, vec<3, ScalarT> const& orthogonal_axis) { TG_CONTRACT(are_orthogonal(a, orthogonal_axis)); TG_CONTRACT(are_orthogonal(b, orthogonal_axis)); auto a_unit = normalize_safe(a); auto b_unit = normalize_safe(b); auto axis_unit = normalize_safe(orthogonal_axis); auto angle = tg::atan2(dot(cross(a_unit, b_unit), axis_unit), dot(a_unit, b_unit)); return angle; } }
BS.SlackNotifierDialog = OO.extend(BS.AbstractModalDialog, { getContainer: function () { return $('slackNotifierDialog'); } }); jQuery(function ($) { loadBuildSettingsList(); $('.buildSettingsList').on('click', '.add-button', function (event) { event.preventDefault(); buildSettingEdit(); }).on('click', '.js-edit', function (event) { event.preventDefault(); buildSettingEdit($(this).closest('tr').data('id')); }).on('click', '.js-delete', function (event) { event.preventDefault(); buildSettingDelete($(this).closest('tr').data('id')); }).on('click', '.js-try', function (event) { event.preventDefault(); buildSettingTry($(this).closest('tr').data('id')); }); $('#mainContent').on('click', '.closeDialog', function (event) { event.preventDefault(); BS.SlackNotifierDialog.close(); }); BS.SlackNotifierDialog.saveBuildConfig = function () { var formData = $('#slackNotifier').serialize(); $.post(window.slackNotifier.buildSettingSaveUrl, formData, function (data) { if ('' === data) { loadBuildSettingsList(); BS.SlackNotifierDialog.close(); } else { $('#slackNotifier').find('.error').html(data).show(); } }); return false; }; function initCheckboxes() { function handleDependencies(element) { checkboxes.filter('[data-parent=' + element.attr('name') + ']').prop('disabled', !element.prop('checked')) } var checkboxes = $('.editPane .checkboxes-group input[type=checkbox]'); checkboxes.on('click', function () { handleDependencies($(this)) }); // disable all checkboxes which parent are unchecked checkboxes.filter('[data-parent]').each(function () { var element = $(this); if (undefined !== element.data('parent') && (!checkboxes.filter('[name=' + element.data('parent') + ']').prop('checked'))) { element.prop('disabled', true); } }) } function loadBuildSettingsList() { BS.ProgressPopup.showProgress("ajaxContainer", "Loading..."); BS.ajaxUpdater("ajaxContainer", window.slackNotifier.buildSettingListUrl, { onSuccess: function () { BS.ProgressPopup.hidePopup() } }); } function buildSettingEdit(id) { BS.ajaxRequest(window.slackNotifier.buildSettingEditUrl + (id ? '&id=' + id : ''), { onSuccess: function (response) { $('#slackNotifier').find('.modalDialogBody').html(response.responseText); BS.SlackNotifierDialog.showCentered(); initCheckboxes(); } }); } function buildSettingTry(id) { BS.DialogWithProgress.showProgress('Sending...'); BS.ajaxRequest(window.slackNotifier.buildSettingTryUrl + '?id=' + id, { onSuccess: function (response) { BS.DialogWithProgress.hideProgress(); BS.confirmDialog.show({ 'title': 'Message sent', 'text': response.responseText }); } }); } function buildSettingDelete(id) { BS.confirmDialog.show({ title: 'Delete notification settings', action: function () { BS.ajaxRequest(window.slackNotifier.buildSettingDeleteUrl + '?id=' + id, { onSuccess: function (response) { if ('' === response.responseText) { loadBuildSettingsList(); } else { BS.confirmDialog.show({ 'title': 'Delete failed', 'text': response.responseText }); } } }); } }); } });
#!/usr/bin/env bash MASON_NAME=v8 MASON_VERSION=5.1.281.47 MASON_LIB_FILE=lib/libv8_base.a . ${MASON_DIR}/mason.sh function mason_load_source { mason_download \ https://github.com/${MASON_NAME}/${MASON_NAME}/archive/${MASON_VERSION}.tar.gz \ 3304589e65c878dfe45898abb5e7c7f85a9c9ab6 mason_extract_tar_gz export MASON_BUILD_PATH=${MASON_ROOT}/.build/${MASON_NAME}-${MASON_VERSION} } function mason_prepare_compile { CCACHE_VERSION=3.3.1 ${MASON_DIR}/mason install ccache ${CCACHE_VERSION} MASON_CCACHE=$(${MASON_DIR}/mason prefix ccache ${CCACHE_VERSION}) # create a directory to cache v8 deps mkdir -p ../v8-deps cd ../v8-deps M_GYP_PATH=$(pwd)/build/gyp/ if [[ ! -d ${M_GYP_PATH} ]]; then git clone https://chromium.googlesource.com/external/gyp ${M_GYP_PATH} (cd ${M_GYP_PATH} && git checkout 4ec6c4e3a94bd04a6da2858163d40b2429b8aad1) fi M_ICU_PATH=$(pwd)/third_party/icu/ if [[ ! -d ${M_ICU_PATH} ]]; then git clone https://chromium.googlesource.com/chromium/deps/icu.git ${M_ICU_PATH} (cd ${M_ICU_PATH} && git checkout c291cde264469b20ca969ce8832088acb21e0c48) fi M_BUILDTOOLS_PATH=$(pwd)/buildtools/ if [[ ! -d ${M_BUILDTOOLS_PATH} ]]; then git clone https://chromium.googlesource.com/chromium/buildtools.git ${M_BUILDTOOLS_PATH} (cd ${M_BUILDTOOLS_PATH} && git checkout 80b5126f91be4eb359248d28696746ef09d5be67) fi M_CLANG_PATH=$(pwd)/tools/clang/ if [[ ! -d ${M_CLANG_PATH} ]]; then git clone https://chromium.googlesource.com/chromium/src/tools/clang.git ${M_CLANG_PATH} (cd ${M_CLANG_PATH} && git checkout faee82e064e04e5cbf60cc7327e7a81d2a4557ad) fi M_TRACE_PATH=$(pwd)/base/trace_event/common/ if [[ ! -d ${M_TRACE_PATH} ]]; then git clone https://chromium.googlesource.com/chromium/src/base/trace_event/common.git ${M_TRACE_PATH} (cd ${M_TRACE_PATH} && git checkout c8c8665c2deaf1cc749d9f8e153256d4f67bf1b8) fi M_GTEST_PATH=$(pwd)/testing/gtest/ if [[ ! -d ${M_GTEST_PATH} ]]; then git clone https://chromium.googlesource.com/external/github.com/google/googletest.git ${M_GTEST_PATH} (cd ${M_GTEST_PATH} && git checkout 6f8a66431cb592dad629028a50b3dd418a408c87) fi M_GMOCK_PATH=$(pwd)/testing/gmock/ if [[ ! -d ${M_GMOCK_PATH} ]]; then git clone https://chromium.googlesource.com/external/googlemock.git ${M_GMOCK_PATH} (cd ${M_GMOCK_PATH} && git checkout 0421b6f358139f02e102c9c332ce19a33faf75be) fi M_SWARMING_PATH=$(pwd)/tools/swarming_client/ if [[ ! -d ${M_SWARMING_PATH} ]]; then git clone https://chromium.googlesource.com/external/swarming.client.git ${M_SWARMING_PATH} (cd ${M_SWARMING_PATH} && git checkout df6e95e7669883c8fe9ef956c69a544154701a49) fi } function mason_compile { if [[ $(uname -s) == 'Darwin' ]]; then export LDFLAGS="${LDFLAGS:-} -stdlib=libc++" fi export CXX="${MASON_CCACHE}/bin/ccache ${CXX}" cp -r ${M_GYP_PATH} build/gyp cp -r ${M_ICU_PATH} third_party/icu cp -r ${M_BUILDTOOLS_PATH} buildtools cp -r ${M_CLANG_PATH} tools/clang mkdir -p base/trace_event cp -r ${M_TRACE_PATH} base/trace_event/common cp -r ${M_GTEST_PATH} testing/gtest cp -r ${M_GMOCK_PATH} testing/gmock cp -r ${M_SWARMING_PATH} tools/swarming_client # make gyp default to full archives for static libs rather than thin if [[ $(uname -s) == 'Linux' ]]; then perl -i -p -e "s/\'standalone_static_library\', 0\)/\'standalone_static_library\', 1\)/g;" build/gyp/pylib/gyp/generator/make.py fi #PYTHONPATH="$(pwd)/tools/generate_shim_headers:$(pwd)/build:$(pwd)/build/gyp/pylib:" \ #GYP_GENERATORS=make \ #build/gyp/gyp --generator-output="out" build/all.gyp \ # -Ibuild/standalone.gypi --depth=. \ # -Dv8_target_arch=x64 \ # -Dtarget_arch=x64 \ # -S.x64.release -Dv8_enable_backtrace=1 -Dwerror='' -Darm_fpu=default -Darm_float_abi=default \ # -Dv8_no_strict_aliasing=1 -Dv8_enable_i18n_support=0 GYPFLAGS=-Dmac_deployment_target=10.8 make x64.release library=static werror=no snapshot=on strictaliasing=off i18nsupport=off -j${MASON_CONCURRENCY} mkdir -p ${MASON_PREFIX}/include mkdir -p ${MASON_PREFIX}/lib cp -r include/* ${MASON_PREFIX}/include/ if [[ $(uname -s) == 'Darwin' ]]; then cp out/x64.release/*v8*.a ${MASON_PREFIX}/lib/ else cp out/x64.release/obj.target/tools/gyp/lib*.a ${MASON_PREFIX}/lib/ fi strip -S ${MASON_PREFIX}/lib/* } function mason_cflags { echo -I${MASON_PREFIX}/include } function mason_ldflags { : } function mason_static_libs { echo ${MASON_PREFIX}/lib/libv8_base.a ${MASON_PREFIX}/lib/libv8_libplatform.a ${MASON_PREFIX}/lib/libv8_external_snapshot.a ${MASON_PREFIX}/lib/libv8_libbase.a } function mason_clean { make clean } mason_run "$@"
/* * Description: Internal cookie * License: Apache-2.0 * Copyright: x-file.xyz */ package console; /** * Date: 2021-06-22 * Place: Zwingenberg, Germany * @author brito */ public class CookieInternal { private final String key, value; public CookieInternal(String key, String value) { this.key = key; this.value = value; } public String getKey() { return key; } public String getValue() { return value; } }
myList = [1,2,3,4,5] squaredList = [item * item for item in myList] print(squaredList)
<filename>editor/colorCharm.ts ///<reference path='refs.ts'/> module TDev { export class ColorCharm { // Preset color table private colorTable = { accent: "#3f3", /* subtle: "", */ chrome: "#222", /* foreground: "", */ /* background: "", */ black: "#000000", blue: "#0000FF", brown: "#A52A2A", cyan: "#00FFFF", "dark gray": "#A9A9A9", gray: "#808080", green: "#008000", "light gray": "#D3D3D3", magenta: "#FF00FF", orange: "#FFA500", purple: "#800080", red: "#FF0000", pink: "#FFCBDB", /* transparent: "#00FFFFFF", */ white: "#FFFFFF", yellow: "#FFFF00", sepia: "#704214" }; // HTML elements private palettes:any; private colorBox: HTMLElement; private inp = HTML.mkTextInput("text", lf("color")); private colorPreviewBox = div("colorPreviewBox"); private paletteSelector = div("paletteSelector"); private hsbCursor = div("hsbCursor cursor"); private hsbSquare = div("hsbSquare"); private hueCursor = div("hueCursor cursor"); private hueSlider = div("hueSlider"); // Status private selectedPalette: string; private initialColor: string = null; private initialTokens: AST.Token[] = null; private hsb = { hue: 0, saturation: 255, value: 255 }; private lastColor: string = null; private lastTokens: AST.Token[] = null; public getInitialTokens(): AST.Token[] { return this.initialTokens === null ? null : this.initialTokens.slice(0); } public getLastTokens(): AST.Token[] { return this.lastTokens === null ? null : this.lastTokens.slice(0); } // Metrics public getWidth(): number { return 314; } private getCursorWidth(): number { return SizeMgr.topFontSize * 1.5; } private cursorBorderWidth = 4; // Callbacks public onUpdate = null; public onEntered = null; public onCancelled = null; // Look for the current value public init(toks: AST.Token[]) { if (toks.length <= 0 || toks[0].nodeType() !== "propertyRef") return; var params = { toks: toks, index: 2, value: NaN }; var parseFloatTokens = (params:any) => { var s = ""; for (var i = params.index; i < params.toks.length; i++) { var ch = (<AST.Operator> params.toks[i]).data; if (ch === "," || ch === ")") { params.index = i; params.value = parseFloat(s); return; } s += ch; } params.value = NaN; }; var numTokens = 0; var propertyName = (<AST.PropertyRef> toks[0]).data; switch (propertyName) { case "is light theme": // Do nothing break; case "from rgb": parseFloatTokens(params); var r = params.value; params.index++; parseFloatTokens(params); var g = params.value; params.index++; parseFloatTokens(params); var b = params.value; this.initialColor = "#" + this.floatsToRgb(r, g, b); numTokens = params.index + 1; break; case "from argb": parseFloatTokens(params); var a = params.value; params.index++; parseFloatTokens(params); var r = params.value; params.index++; parseFloatTokens(params); var g = params.value; params.index++; parseFloatTokens(params); var b = params.value; this.initialColor = "#" + this.fillZero((a * 255).toString(16), 2) + this.floatsToRgb(r, g, b); numTokens = params.index + 1; break; case "from hsb": case "from ahsb": // not implemented yet. break; case "linear gradient": break; case "rand": case "random": numTokens = 1; this.initialColor = "random"; break; default: this.initialColor = propertyName; numTokens = 1; break; } if (numTokens === 0) { this.initialTokens = []; } else { this.initialTokens = toks.slice(0, numTokens); } } private initPresetPalette():HTMLElement { var tables:HTMLElement[] = []; for (var colorName in this.colorTable) { var presetColor = div("presetColor"); var htmlColor = this.colorIntToHtml(this.parseColorCode(colorName)); presetColor.style.color = htmlColor; presetColor.style.backgroundColor = htmlColor; presetColor.title = colorName; presetColor.withClick(e => { var colorName = (<MouseEvent> e).srcElement.getAttribute("title"); this.update(colorName); }); tables.push(presetColor); } return div("palette presetPalette", tables); } private initHsbPalette(): HTMLElement { var hsbBeforeDrag = { hue: 0, saturation: 255, value: 255 }; var hsbTimeoutHandler = null; var handler = (e:string, dx:number, dy:number) => { if (e === "drag") { var origPos = Util.offsetIn(this.hsbSquare, this.colorBox); var pos = Util.offsetIn(this.hsbCursor, this.colorBox); hsbBeforeDrag.saturation = pos.x - origPos.x + this.getCursorWidth()/2; hsbBeforeDrag.value = pos.y - origPos.y + this.getCursorWidth()/2; } else if (e === "move") { this.hsb.saturation = hsbBeforeDrag.saturation + dx; this.hsb.value = 255 - (hsbBeforeDrag.value + dy); hsbTimeoutHandler = () => { if (hsbTimeoutHandler === null) { return; } this.updateOnHsbInput(); Util.setTimeout(50, hsbTimeoutHandler); } Util.setTimeout(10, hsbTimeoutHandler); } else { hsbTimeoutHandler = null; } }; new DragHandler(this.hsbCursor, handler); var hueTimeoutHandler = null; var handler = (e:string, dx:number, dy:number) => { if (e === "drag") { var origPos = Util.offsetIn(this.hueSlider, this.colorBox); var pos = Util.offsetIn(this.hueCursor, this.colorBox); hsbBeforeDrag.hue = pos.y - origPos.y + this.getCursorWidth()/2; } else if (e === "move") { this.hsb.hue = hsbBeforeDrag.hue + dy; this.updateOnHsbInput(); hueTimeoutHandler = () => { if (hueTimeoutHandler === null) { return; } this.updateOnHsbInput(); Util.setTimeout(50, hueTimeoutHandler); } Util.setTimeout(10, hueTimeoutHandler); } else { hueTimeoutHandler = null; } } new DragHandler(this.hueCursor, handler); this.hsbCursor.style.pixelWidth = this.getCursorWidth(); this.hsbCursor.style.pixelHeight = this.getCursorWidth(); this.hueCursor.style.pixelHeight = this.getCursorWidth(); return div( "palette hsbPalette", [this.hsbCursor, this.hsbSquare, this.hueCursor, this.hueSlider]); } public show(x: number, y: number) { // Construct an input box var colorInputBox = div("colorInputBox", <any[]>[this.colorPreviewBox, this.inp]); var updateOnTextInput_ = () => this.updateOnTextInput(); this.inp.onkeyup = updateOnTextInput_; this.inp.onpaste = <any>updateOnTextInput_; Util.onInputChange(this.inp, updateOnTextInput_); // Construct palletes. this.palettes = { "Preset": this.initPresetPalette(), "HSB": this.initHsbPalette() } // Construct a palette selector for (var name in this.palettes) { var selector = span("paletteChoice", name); this.paletteSelector.appendChild(selector); selector.withClick(e => { var src = (<MouseEvent> e).srcElement; var name = src.childNodes[0].textContent; this.selectPalette(name); }); } // Construct the whole form this.colorBox = div( "colorBox charm", [colorInputBox, this.paletteSelector, this.palettes["Preset"], this.palettes["HSB"]]); this.colorBox.style.left = x + "px"; this.colorBox.style.top = y + "px"; var m = new ModalDialog(); m.opacity = 0; var cancelIt = false; m.onDismiss = () => { var a = TDev.TheEditor.currentAction(); if (!cancelIt && !!a) { if (this.onEntered !== null) this.onEntered(); } else { if (this.onCancelled !== null) this.onCancelled(); } }; m.showBare(this.colorBox); TheEditor.keyMgr.register("Esc", () => { cancelIt = true; m.dismiss(); return true }); TheEditor.keyMgr.register("Enter", () => { m.dismiss(); return true }); this.inp.value = this.initialColor; var isPreset: boolean = false; var c = this.parseColorCode(this.initialColor); if (c < 0) { isPreset = true; } else { for (var colorName in this.colorTable) if (colorName === this.initialColor) { isPreset = true; } this.colorPreviewBox.style.backgroundColor = this.colorIntToHtml(c); } this.selectPalette(isPreset ? "Preset" : "HSB"); Util.setKeyboardFocus(this.inp); } public selectPalette(paletteName: string) { for (var i = 0; i < this.paletteSelector.childNodes.length; i++) { var selector = <HTMLElement>this.paletteSelector.children[i]; if (selector.childNodes[0].textContent == paletteName) selector.classList.add("active"); else selector.classList.remove("active"); } for (var name in this.palettes) { var palette = this.palettes[name]; if (paletteName == name) palette.style.display = "block"; else palette.style.display = "none"; } this.selectedPalette = paletteName; this.updateOnTextInput(); } private updateOnTextInput() { if (this.selectedPalette === "HSB") { var c = this.parseColorCode(this.inp.value); if (c < 0) { return; } var newHsb = this.colorIntToHsb(c); if (!isNaN(newHsb.hue)) this.hsb.hue = newHsb.hue; this.hsb.saturation = newHsb.saturation; this.hsb.value = newHsb.value; this.updateOnHsbInput(); } else { this.update(this.inp.value); } } private updateOnHsbInput() { var inRange = (x: number, y: number, z: number): number => x < y ? y : (x > z ? z : x); this.hsb.hue = inRange(this.hsb.hue, 0, 255); this.hsb.saturation = inRange(this.hsb.saturation, 0, 255); this.hsb.value = inRange(this.hsb.value, 0, 255); var origPos:Position, pos:Position; // Set position of the cursor in the square origPos = Util.offsetIn(this.hsbSquare, this.colorBox); pos = Util.offsetIn(this.hsbCursor, this.colorBox); this.hsbCursor.style.left = (this.hsb.saturation + origPos.x - this.getCursorWidth()/2 - this.cursorBorderWidth) + "px"; this.hsbCursor.style.top = ((255 - this.hsb.value) + origPos.y - this.getCursorWidth()/2 - this.cursorBorderWidth) + "px"; // Set position of the cursor in the hue slider origPos = Util.offsetIn(this.hueSlider, this.colorBox); pos = Util.offsetIn(this.hueCursor, this.colorBox); this.hueCursor.style.left = origPos.x + "px"; this.hueCursor.style.top = (this.hsb.hue + origPos.y - this.getCursorWidth()/2 - this.cursorBorderWidth) + "px"; // Update background color of the square and the hue cursor var hueColor = "#" + this.hsbToRgb({ hue: this.hsb.hue, saturation: 255, value: 255 }); this.hsbSquare.style.backgroundColor = hueColor; this.hueCursor.style.backgroundColor = hueColor; // Update background color of the cursor and the preview box var color = "#" + this.hsbToRgb(this.hsb); this.hsbCursor.style.backgroundColor = color; this.update(color); } // Create new tokens to be inserted private update(color: string) { if (color === this.lastColor) return; this.inp.value = color; var c = this.parseColorCode(color); this.colorPreviewBox.style.backgroundColor = this.colorIntToHtml(c); var toks: AST.Token[] = null; if (this.inp.value == "random") { toks = [AST.mkPropRef("random")]; } else { for (var colorName in this.colorTable) { if (colorName === color) { toks = [AST.mkPropRef(colorName)]; break; } } } if (toks == null) { var r = ((c >> 16) & 0xff) / 0xff; var g = ((c >> 8) & 0xff) / 0xff; var b = (c & 0xff) / 0xff; var addOps = (x: number, toks: AST.Token[]) => { if (x === 0) { toks.push(AST.mkOp("0")); } else if (x === 1) { toks.push(AST.mkOp("1")); } else { var xInt = Math.round(x * 255); var sShortened = ""; var s = x.toString(); for (var i = 0; i < s.length; i++) { var ch = s[i]; toks.push(AST.mkOp(ch)); sShortened += ch; // Cut off nonsense string if (ch !== "." && xInt === Math.round(parseFloat(sShortened) * 255)) break; } } }; toks = [AST.mkPropRef("from rgb")]; toks.push(AST.mkOp("(")); addOps(r, toks); toks.push(AST.mkOp(",")); addOps(g, toks); toks.push(AST.mkOp(",")); addOps(b, toks); toks.push(AST.mkOp(")")); } if (this.onUpdate !== null) { this.onUpdate(toks); } this.lastTokens = toks; this.lastColor = color; } private fillZero(s: string, length: number): string { return s.length >= length ? s : new Array(length - s.length + 1).join('0') + s; } private parseColorCode(c: string): number { if (typeof c !== "string") return -1; // Preset colors for (var colorName in this.colorTable) if (colorName === c) { c = this.colorTable[c]; break; } // Remove '#' if (c[0] == "#") c = c.substr(1); // Test the format if (/^[0-9a-fA-F]+$/.test(c) === false) return -1; // #rgb if (c.length == 3) c = "f" + c; // #rrggbb else if (c.length == 6) c = "ff" + c; // #argb if (c.length == 4) { var coeff = parseInt(c[0], 16) / 15.0; var r = (parseInt(c[1], 16) * coeff) << 16; var g = (parseInt(c[2], 16) * coeff) << 8; var b = (parseInt(c[3], 16) * coeff); return r | g | b; } // #aarrggbb else if (c.length == 8) { var coeff = parseInt(c.substr(0, 2), 16) / 255; var r = (parseInt(c.substr(2, 2), 16) * coeff) << 16; var g = (parseInt(c.substr(4, 2), 16) * coeff) << 8; var b = (parseInt(c.substr(6, 2), 16) * coeff); return r | g | b; } return -1; } private colorIntToHtml(c: number): string { return "#" + this.fillZero(c.toString(16), 6); } private colorIntToHsb(c: number) { var r = (c >> 16) & 0xff; var g = (c >> 8) & 0xff; var b = c & 0xff; var max = r > g ? (r > b ? r : b) : (b > g ? b : g); var min = r > g ? (g > b ? b : g) : (r > b ? b : r); var d = max - min; var hsb = { hue: 0, saturation: 0, value: 0 }; hsb.value = max; if (max != 0) { hsb.saturation = d / max * 255; if (r == max) hsb.hue = (g - b) / d; else if (g == max) hsb.hue = 2 + (b - r) / d; else hsb.hue = 4 + (r - g) / d; if (hsb.hue < 0) hsb.hue += 6; else if (hsb.hue > 6) hsb.hue -= 6; hsb.hue = hsb.hue * 255 / 6; } return hsb; } private floatsToRgb(r: number, g: number, b: number): string { return this.fillZero(Math.round(r * 255).toString(16), 2) + this.fillZero(Math.round(g * 255).toString(16), 2) + this.fillZero(Math.round(b * 255).toString(16), 2); } private hsbToRgb(hsb:any): string { var hue = hsb.hue, saturation = hsb.saturation, value = hsb.value; // Get the color from hue value hue = hue * 360 / 255; while (hue >= 360 || hue < 0) hue += hue >= 360 ? -360 : 360; var region = Math.floor(hue / 60); var fraction = hue / 60 - region; var r:number, g:number, b:number; switch (region) { case 0: r = 1; g = fraction; b = 0; break; case 1: r = 1 - fraction; g = 1; b = 0; break; case 2: r = 0; g = 1; b = fraction; break; case 3: r = 0; g = 1 - fraction; b = 1; break; case 4: r = fraction; g = 0; b = 1; break; case 5: r = 1; g = 0; b = 1 - fraction; break; default: r = 0; g = 0; b = 0; break; } // Mix the color with white and black if (saturation < 0) saturation = 0; else if (saturation > 255) saturation = 255; if (value < 0) value = 0; else if (value > 255) value = 255; var f = (x: number, y: number, p: number) => x * p + y * (1 - p); r = f(r, 1, saturation / 255); r = f(r, 0, value / 255); g = f(g, 1, saturation / 255); g = f(g, 0, value / 255); b = f(b, 1, saturation / 255); b = f(b, 0, value / 255); return this.floatsToRgb(r, g, b); } } }
<gh_stars>0 package com.sphereon.factom.identity.did.entry; import com.sphereon.factom.identity.did.DIDVersion; import org.blockchain_innovation.factom.client.api.model.Entry; import org.factomprotocol.identity.did.model.BlockInfo; import org.factomprotocol.identity.did.model.IdentityEntry; import java.util.List; public class CreateIdentityContentEntry extends ResolvedFactomDIDEntry<IdentityEntry> { private int version; private List<String> keys; public CreateIdentityContentEntry(IdentityEntry content, String... tags) { super(DIDVersion.FACTOM_IDENTITY_CHAIN, content, null, tags); this.version = content.getVersion(); this.keys = content.getKeys(); initValidationRules(); } public CreateIdentityContentEntry(Entry entry, BlockInfo blockInfo) { super(entry, IdentityEntry.class, blockInfo); this.didVersion = DIDVersion.FACTOM_IDENTITY_CHAIN; this.version = getContent().getVersion(); this.keys = getContent().getKeys(); initValidationRules(); } public int getVersion() { return version; } public List<String> getKeys() { return keys; } }
#!/bin/sh gmsgenux.out /home/albarass/RedSeaInterpolation/ocean_interpolation/rs_example2/225d/grid198000006/gamscntr.dat CONOPT gmscr_ux.out /home/albarass/RedSeaInterpolation/ocean_interpolation/rs_example2/225d/grid198000006/gamscntr.dat echo OK > /home/albarass/RedSeaInterpolation/ocean_interpolation/rs_example2/225d/grid198000006/finished
<gh_stars>0 package com.thalesgroup.gemalto.idcloud.auth.sample; import android.app.Activity; import android.content.Context; import android.view.View; import android.widget.TextView; import androidx.appcompat.app.AlertDialog; import com.thales.dis.mobile.idcloud.auth.operation.IdCloudProgress; import java.util.concurrent.Semaphore; public class Progress { // get lock before accessing the SDK, to prevent concurrent access public final static Semaphore sdkLock = new Semaphore(1); private static AlertDialog alertDialog; public static void showProgress(Activity activity, IdCloudProgress progress) { activity.runOnUiThread(new Runnable() { @Override public void run() { String text = getStringForProgress(activity, progress); if (alertDialog != null) { ((TextView) alertDialog.findViewById(R.id.progress_text)).setText(text); } else { View view = activity.getLayoutInflater().inflate(R.layout.dialog_progress, null); ((TextView) view.findViewById(R.id.progress_text)).setText(text); alertDialog = new AlertDialog.Builder(activity) .setView(view) .create(); } alertDialog.show(); } }); } public static void hideProgress() { if (alertDialog != null) { alertDialog.dismiss(); alertDialog = null; } } private static String getStringForProgress(Context context, IdCloudProgress progressCode) { String progressStr; switch (progressCode) { case START: progressStr = context.getString(R.string.progress_start); break; case RETRIEVING_REQUEST: progressStr = context.getString(R.string.progress_retrieving_request); break; case PROCESSING_REQUEST: progressStr = context.getString(R.string.progress_processing_request); break; case VALIDATING_AUTHENTICATION: progressStr = context.getString(R.string.progress_validating_authentication); break; case END: progressStr = context.getString(R.string.progress_end); break; default: progressStr = "unsupported progress"; break; } return progressStr; } }
<reponame>jaysonmaldlonado1/bitpay-browser-extension import React from 'react'; import './tabs.scss'; import { NavLink, withRouter, RouteComponentProps } from 'react-router-dom'; const Tabs: React.FC<RouteComponentProps> = ({ location: { pathname } }) => { const routesVisible = ['/wallet', '/shop', '/settings']; const shouldShow = routesVisible.includes(pathname); return shouldShow ? ( <div className="tab-bar"> <NavLink to="/wallet" activeClassName="is-active"> <img className="inactive" alt="wallet" src="../assets/icons/wallet-icon.svg" /> <img className="active" alt="wallet" src="../assets/icons/wallet-icon--active.svg" /> </NavLink> <NavLink to="/shop" activeClassName="is-active"> <img className="inactive" alt="shop" src="../assets/icons/shop-icon.svg" /> <img className="active" alt="shop" src="../assets/icons/shop-icon--active.svg" /> </NavLink> <NavLink to="/settings" activeClassName="is-active"> <img className="inactive" alt="settings" src="../assets/icons/settings-icon.svg" /> <img className="active" alt="settings" src="../assets/icons/settings-icon--active.svg" /> </NavLink> </div> ) : null; }; export default withRouter(Tabs);
<reponame>chrishumboldt/rocket-utility /** * @author <NAME> */ export enum SizeType { NONE = 'none', SMALL = 'small', MEDIUM = 'medium', LARGE = 'large' }
import re def parse_twig_template(template_file): # Extracting template file name template_name = template_file.split('/')[-1] # Reading the content of the template file with open(template_file, 'r') as file: template_content = file.read() # Identifying and extracting all the Twig functions being called within the template twig_functions = re.findall(r'{{\s*([\w]+)\(', template_content) # Counting the occurrences of a specific Twig function within the template specific_function = 'url' specific_function_count = template_content.count('{{ ' + specific_function) return { 'template_name': template_name, 'twig_functions': twig_functions, 'specific_function_count': specific_function_count } # Example usage template_file = "/var/www/html/teste-october/themes/zwiebl-zwiebl_stellar/pages/404.htm" result = parse_twig_template(template_file) print(result)
public class BankAccount { private double balance; public BankAccount(double balance) { this.balance = balance; } public void deposit(double amount) { balance += amount; } public void withdraw(double amount) { balance -= amount; } public double getBalance() { return balance; } }
<filename>ods-main/src/main/java/cn/stylefeng/guns/onlineaccess/modular/service/ProjectUserService.java package cn.stylefeng.guns.onlineaccess.modular.service; import cn.stylefeng.guns.onlineaccess.modular.entity.ProjectUser; import cn.stylefeng.guns.onlineaccess.modular.result.ProjectUserResult; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.IService; import java.util.List; public interface ProjectUserService extends IService<ProjectUser> { List<ProjectUserResult> getDatanegotiatorByProjectIdResult(Long id, int type); }
#!/bin/sh export KONTROL_CERTS=$KITE_HOME/certs export KONTROL_PORT=6000 export KONTROL_USERNAME="openshift" export KONTROL_ENVIRONMENT="openshift" export KONTROL_STORAGE="etcd" export KONTROL_MACHINES="${ETCD_SERVICE_HOST}:4001" export KONTROL_URL="http://${KONTROL_SERVICE_HOST}:6000/kite" export KONTROL_PUBLICKEYFILE="$KONTROL_CERTS/key_pub.pem" export KONTROL_PRIVATEKEYFILE="$KONTROL_CERTS/key.pem" mkdir -p $KITE_HOME mkdir -p $KONTROL_CERTS [ -f $KONTROL_PRIVATEKEYFILE ] || openssl genrsa -out $KONTROL_PRIVATEKEYFILE 2048 [ -f $KONTROL_PUBLICKEYFILE ] || openssl rsa -in $KONTROL_PRIVATEKEYFILE -pubout > $KONTROL_PUBLICKEYFILE env /go/bin/kontrol -initial || exit 1 exec /go/bin/kontrol $@
def split_into_pairs(inputString): resultList = [] counter = 0 while counter < len(inputString): resultList.append(inputString[counter:counter + 2]) counter += 2 return resultList pairs = split_into_pairs("abcd") print(pairs)
from . import BasePage from .game_page import GamePage class ManualPhasePage(BasePage): """A game page.""" def render(self) -> None: """Render the game page.""" print( self.term.home + self.term.clear + self.term.move_y(self.term.height // 2) ) current_cash = self.state.getCash() if current_cash <= 1: if current_cash == 0: print( self.term.black_on_darkkhaki(self.term.center("There is no box D:")) ) else: print( self.term.black_on_darkkhaki( self.term.center(f"There is {current_cash} box") ) ) else: print( self.term.black_on_darkkhaki( self.term.center(f"There are {current_cash} boxes") ) ) print( self.term.move_y((self.term.height // 2) + 5) + self.term.center("Tap [Spacebar] to fold a box") ) def handle_input(self, key: str) -> None: """Handle input while in the game page.""" if key == " ": self.state.makeBox() if self.state.getCash() > 50: # Process to next phase. self.state.phase = "game" self.renderstate.set_prop(("current_phase", "game")) self.renderstate.set_prop(("current_page", GamePage)) elif key == "q": # Save the session. self.state.saveGame() self.renderstate.set_prop(("is_exiting", True)) # TODO: jumpyapple - set is_in_game to False
package fr.unice.polytech.si3.qgl.soyouz.classes.objectives.sailor.helper; import fr.unice.polytech.si3.qgl.soyouz.classes.marineland.entities.onboard.Gouvernail; /** * Class to determine the optimal Rudder configuration to be the closest possible to the objective. */ public class RudderConfigHelper { private final double neededRotation; /** * Constructor. * * @param neededRotation The angle between the boat and the checkpoint. */ public RudderConfigHelper(double neededRotation) { this.neededRotation = neededRotation; } /** * Determine if the rudder can fully complete the rotation. * * @return true if the angle is in range, false otherwise. */ private boolean rudderRotationIsInRange() { return Gouvernail.isValid(neededRotation); } /** * Determine the best rudder rotation possible to reduce the angle between the boat and the * checkpoint. * * @return the angle of rotation that the rudder will perform. */ public double findOptRudderRotation() { if (rudderRotationIsInRange()) { return neededRotation; } else { return Math.signum(neededRotation) * Gouvernail.ALLOWED_ROTATION; } } }
Document: mplayer-ru Title: MPlayer documentation (Russian) Author: The MPlayer team Abstract: This documentation describes the use of MPlayer. (Russian) MPlayer is a movie player for GNU/Linux that supports a wide range of audio and video formats, and output drivers. Section: Sound Format: HTML Index: /usr/share/doc/mplayer-doc/HTML/ru/index.html Files: /usr/share/doc/mplayer-doc/HTML/ru/*.html
#!/bin/bash # Take a screenshot of the emulator (for all platforms) function take_screenshot { pebble install --emulator $2 &> /dev/null pebble screenshot --emulator aplite screenshots/aplite/$1.png &> /dev/null } pebble kill (take_screenshot $1 "aplite") & (take_screenshot $1 "basalt") & (take_screenshot $1 "chalk") & # (pebble install --emulator "basalt" && pebble screenshot --emulator basalt screenshots/basalt/$1.png) & # (pebble install --emulator "chalk" && pebble screenshot --emulator chalk screenshots/chalk/$1.png) & wait echo "" > src/config.h
def find_min_max(list_of_nums): min_num = list_of_nums[0] max_num = list_of_nums[0] for num in list_of_nums: if num < min_num: min_num = num if num > max_num: max_num = num return (min_num, max_num) list_of_nums = [10, 24, 55, 16, 1, 9] (min_num, max_num) = find_min_max(list_of_nums) print("Min Num: {} Max Num: {}".format(min_num, max_num))
package webapp.dso; import org.noear.solon.core.handle.Context; import org.noear.solon.core.handle.Result; import org.noear.solon.validation.annotation.Whitelist; import org.noear.solon.validation.annotation.WhitelistValidator; public class WhitelistValidatorImpl extends WhitelistValidator { @Override public Result validateOfContext(Context ctx, Whitelist anno, String name, StringBuilder tmp) { System.out.println("成功定制..."); return Result.failure(); } }
# Etcher flash OS images to SD cards & USB drives, safely and easily - https://github.com/balena-io/etcher - util wget -O etcher.deb https://github.com/balena-io/etcher/releases/download/v1.5.5/balena-etcher-electron_1.5.5_amd64.deb sudo dpkg -i etcher.deb rm etcher.deb
#!/bin/sh set -e echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" install_framework() { if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then local source="${BUILT_PRODUCTS_DIR}/$1" elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" elif [ -r "$1" ]; then local source="$1" fi local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" if [ -L "${source}" ]; then echo "Symlinked..." source="$(readlink "${source}")" fi # use filter instead of exclude so missing patterns dont' throw errors echo "rsync -av --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" rsync -av --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" local basename basename="$(basename -s .framework "$1")" binary="${destination}/${basename}.framework/${basename}" if ! [ -r "$binary" ]; then binary="${destination}/${basename}" fi # Strip invalid architectures so "fat" simulator / device frameworks work on device if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then strip_invalid_archs "$binary" fi # Resign the code if required by the build settings to avoid unstable apps code_sign_if_enabled "${destination}/$(basename "$1")" # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then local swift_runtime_libs swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]}) for lib in $swift_runtime_libs; do echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" code_sign_if_enabled "${destination}/${lib}" done fi } # Signs a framework with the provided identity code_sign_if_enabled() { if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" -a "${CODE_SIGNING_REQUIRED}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then # Use the current code_sign_identitiy echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" echo "/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements \"$1\"" /usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements "$1" fi } # Strip invalid architectures strip_invalid_archs() { binary="$1" # Get architectures for current file archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | rev)" stripped="" for arch in $archs; do if ! [[ "${VALID_ARCHS}" == *"$arch"* ]]; then # Strip non-valid architectures in-place lipo -remove "$arch" -output "$binary" "$binary" || exit 1 stripped="$stripped $arch" fi done if [[ "$stripped" ]]; then echo "Stripped $binary of architectures:$stripped" fi } if [[ "$CONFIGURATION" == "Debug" ]]; then install_framework "$BUILT_PRODUCTS_DIR/GMAdditions/GMAdditions.framework" fi if [[ "$CONFIGURATION" == "Release" ]]; then install_framework "$BUILT_PRODUCTS_DIR/GMAdditions/GMAdditions.framework" fi
import { NestFactory } from '@nestjs/core'; import { AppModule } from 'src/app.module'; import { environment } from 'src/config/environments/environment'; import { SwaggerConfigService } from 'src/config/services/swagger-config.service'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.enableCors(); SwaggerConfigService.setup(app); await app.listen(environment.port, '0.0.0.0'); } bootstrap();
import Layout from "../components/Layout"; import '../main.css' const Disclaimer = (props)=>{ return( <Layout title="Disclaimer" {...props}> <section className="section legal"> <div className="container"> <h3 className="title">Legal</h3> <div className="tabs"> <ul> <li><a href="/terms-of-use">Terms of use</a></li> <li><a href="/privacy-policy">Privacy policy</a></li> <li><a>Referral terms</a></li> <li className="is-active"><a href="/disclaimer">Disclaimer</a></li> </ul> </div> <div className="tab-content content"> <h4>Disclaimer for The Academist</h4> <p>For more information or questions about our site’s disclaimer, please feel free to contact us by email at <EMAIL></p> <p>Disclaimers for theacademist.com</p> <p>All data on this website is published in good faith and for general information purpose only. theacademist.com and not warranty on the completeness, reliability, and accuracy of this information. Any action you take upon the information you find on this website (theacademist.com), is strictly at your risk. theacademist.com will not be liable for any losses and damages in connection with the use of our website.</p> <p>From The Academist, you can visit other websites through hyperlinks. While we do our best to provide only quality links to ethical websites that are relevant to your interests, we do not control their nature or content. The links are not an implication of our recommendation for their content which is privy to their terms. The links may connect to websites whose owners and content may change without notice without our opportunity to change their ‘bad’ links.</p> <p>You should also be aware that when leaving our website, other websites have different privacy policies and terms which are not in our control. Please beware of their Privacy Policies and their “Terms and Conditions” before engaging in any business or providing any data.</p> <p>Consent</p> <p>In using our website, you at this moment consent to our disclaimer terms and agree to them.</p> <p>Update</p> <p>If we make updates, amendments or changes to the disclaimer, those changes will be posted here promptly.</p> </div> </div> </section> </Layout> ); } export default Disclaimer;
<reponame>natla/javascript-ui-and-dom<filename>jQuery Plugins Homework/task-3-ListViews/lists.js $.fn.lists = function (lists) { var $container = this; var $listDiv = $('<div />').addClass('list-div'), $ul = $('<ul />'), $li = $('<li />').attr('draggable', true), $heading = $('<h3 />'), $link = $('<a />'), $button = $('<button />'), $input = $('<input />').attr('type', 'text'); for (var i = 0, len = lists.length; i < len; i += 1) { var list = lists[i], $currentListDiv = $listDiv.clone(true), $currentUl = $ul.clone(true), $currentHeading = $heading.clone(true).html(list[0]).appendTo($currentUl), $currentBtn = $button.clone(true).appendTo($currentUl), $currentInput = $input.clone(true).appendTo($currentUl); for (var j = 1, len2 = list.length; j < len2; j += 1) { var $currentLi = $li.clone(true), $currentLink = $link.clone(true).html(list[j]) .attr('href', 'https://www.google.bg/search?q=' + list[j]) .attr('target', '_blank') .appendTo($currentLi); $currentLi.appendTo($currentUl); } $currentUl.appendTo($currentListDiv); $currentListDiv.appendTo($container); } // drag and drop functionality: function makeDraggable(element){ element.draggable({ containment: $container, start: function () { $draggedLi = $(this); } }); return element; } makeDraggable($('li')); $('ul').droppable({ accept: 'li', drop: function () { $(this).append($draggedLi); $draggedLi.css('left', 0); $draggedLi.css('top', 0); } }); // clicking on the button displays the input: $container.on('click', 'button', function () { var $this = $(this); $this.next().show(); $this.hide(); }); // adding input value to the list of items: $container.on('change', 'input[type=text]', function () { var $this = $(this); var $text = $this.val(); var $newLi = ($('<li />')).appendTo($this.parent()); makeDraggable($newLi); $('<a />').html($text).attr('href', 'https://www.google.bg/search?q=' + $text) .attr('target', '_blank').appendTo($newLi); $this.prev().show(); $this.hide(); }); return $container; };
package io.smallrye.mutiny.converters; import io.smallrye.mutiny.Uni; public interface UniConverter<I, T> { /** * Convert from type to {@link Uni}. * * @param instance what is to be converted * @return {@link Uni} */ Uni<T> from(I instance); }
<reponame>pt-pintereach5/back-end<filename>api/articles/articles-router.js const express = require('express'); const router = express.Router(); const { restricted } = require('../auth/auth-middleware'); const Articles = require('../articles/articles-model'); const Categories = require('../categories/categories-model'); router.get('/api/articles', restricted, async (req, res) => { try { const articles = await Articles.find(); res.status(200).json(articles); } catch(err) { res.json(err.message) } }); router.get('/api/articles/:id', restricted, async (req, res) => { const {id} = req.params; try { const article = await Articles.findById(id); if (!article) { res.status(404).json({ message: 'the specified article does not exist' }); } else { res.status(200).json(article); } } catch(err) { res.json(err.message); } }); router.post('/api/articles', restricted, async (req, res) => { const article = req.body; try { if (!article.title || !article.source || !article.author || !article.contents) { res.status(400).json({ message: "please fill all required fields" }); } else { const newArticle = await Articles.create(article); res.status(201).json(newArticle); } } catch(err) { res.json(err.message); } }); router.put('/api/articles/:id', restricted, async (req, res) => { const {id} = req.params; const article = req.body; try { if (!article.title || !article.source || !article.author || !article.contents) { res.status(400).json({ message: "please fill all required fields" }); } else { const updArticle = await Articles.update(id, article); res.status(200).json(updArticle); } } catch(err) { res.status(500).json(err.message) } }); router.delete('/api/articles/:id', restricted, async (req, res) => { const {id} = req.params; try { const newArticlesList = await Articles.remove(id); res.status(200).json(newArticlesList); } catch(err) { res.status(500).json(err.message); } }); router.get('/api/articles/:id/categories', restricted, async (req, res) => { const {id} = req.params; try { const artCategories = await Articles.findArticleCategories(id); res.status(200).json(artCategories); } catch(err) { res.status(500).json(err.message); } }); router.post('/api/articles/:id', restricted, async (req, res) => { const {id} = req.params; const category = req.body; const categoryId = await Categories.findBy(category); try { const newAssign = await Articles.addArticleCategory({article_id: id, category_id: categoryId.category_id}); res.status(200).json(newAssign); } catch(err) { res.status(500).json(err.message); } }); module.exports = router;
#!/bin/bash # 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. workload_folder=`dirname "$0"` workload_folder=`cd "$workload_folder"; pwd` workload_root=${workload_folder}/../.. . "${workload_root}/../../bin/functions/load-bench-config.sh" SUBMARK=flink_scala enter_bench ScalaFlinkWordcount ${workload_root} ${workload_folder} show_bannar start rmr-hdfs $OUTPUT_HDFS || true SIZE=`dir_size $INPUT_HDFS` START_TIME=`timestamp` run-flink-job com.intel.flinkbench.ScalaWordCount $INPUT_HDFS $OUTPUT_HDFS END_TIME=`timestamp` OUTPUT_SIZE=`dir_size $OUTPUT_HDFS` gen_report ${START_TIME} ${END_TIME} dir_size=${SIZE} output_size=${OUTPUT_SIZE} show_bannar finish leave_bench